blob: 6f477882a77ab24f2e07ac0df10c3b1170d0b23a [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 }
1188 super.startSearch(initialQuery, selectInitialQuery, appSearchData, globalSearch);
1189 }
1190
Leon Scroggins1f005d32009-08-10 17:36:42 -04001191 /**
1192 * Switch tabs. Called by the TitleBarSet when sliding the title bar
1193 * results in changing tabs.
Leon Scroggins160a7e72009-08-14 18:28:01 -04001194 * @param index Index of the tab to change to, as defined by
1195 * mTabControl.getTabIndex(Tab t).
1196 * @return boolean True if we successfully switched to a different tab. If
1197 * the indexth tab is null, or if that tab is the same as
1198 * the current one, return false.
Leon Scroggins1f005d32009-08-10 17:36:42 -04001199 */
Leon Scroggins160a7e72009-08-14 18:28:01 -04001200 /* package */ boolean switchToTab(int index) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001201 Tab tab = mTabControl.getTab(index);
1202 Tab currentTab = mTabControl.getCurrentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04001203 if (tab == null || tab == currentTab) {
Leon Scroggins160a7e72009-08-14 18:28:01 -04001204 return false;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001205 }
1206 if (currentTab != null) {
1207 // currentTab may be null if it was just removed. In that case,
1208 // we do not need to remove it
1209 removeTabFromContentView(currentTab);
1210 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001211 mTabControl.setCurrentTab(tab);
1212 attachTabToContentView(tab);
Grace Klobaeb6eef42009-09-15 17:56:32 -07001213 resetTitleIconAndProgress();
1214 updateLockIconToLatest();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001215 return true;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001216 }
1217
Grace Kloba22ac16e2009-10-07 18:00:23 -07001218 /* package */ Tab openTabToHomePage() {
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001219 return openTabAndShow(mSettings.getHomePage(), false, null);
1220 }
1221
Leon Scroggins1f005d32009-08-10 17:36:42 -04001222 /* package */ void closeCurrentWindow() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001223 final Tab current = mTabControl.getCurrentTab();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001224 if (mTabControl.getTabCount() == 1) {
Leon Scroggins30444232009-09-04 18:36:20 -04001225 // This is the last tab. Open a new one, with the home
1226 // page and close the current one.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001227 openTabToHomePage();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001228 closeTab(current);
Leon Scroggins160a7e72009-08-14 18:28:01 -04001229 return;
1230 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07001231 final Tab parent = current.getParentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04001232 int indexToShow = -1;
1233 if (parent != null) {
1234 indexToShow = mTabControl.getTabIndex(parent);
1235 } else {
Leon Scroggins160a7e72009-08-14 18:28:01 -04001236 final int currentIndex = mTabControl.getCurrentIndex();
1237 // Try to move to the tab to the right
1238 indexToShow = currentIndex + 1;
1239 if (indexToShow > mTabControl.getTabCount() - 1) {
1240 // Try to move to the tab to the left
1241 indexToShow = currentIndex - 1;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001242 }
1243 }
Leon Scroggins160a7e72009-08-14 18:28:01 -04001244 if (switchToTab(indexToShow)) {
1245 // Close window
1246 closeTab(current);
1247 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001248 }
1249
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001250 private ActiveTabsPage mActiveTabsPage;
1251
1252 /**
1253 * Remove the active tabs page.
1254 * @param needToAttach If true, the active tabs page did not attach a tab
1255 * to the content view, so we need to do that here.
1256 */
1257 /* package */ void removeActiveTabPage(boolean needToAttach) {
1258 mContentView.removeView(mActiveTabsPage);
1259 mActiveTabsPage = null;
1260 mMenuState = R.id.MAIN_MENU;
1261 if (needToAttach) {
1262 attachTabToContentView(mTabControl.getCurrentTab());
1263 }
1264 getTopWindow().requestFocus();
1265 }
1266
The Android Open Source Project0c908882009-03-03 19:32:16 -08001267 @Override
1268 public boolean onOptionsItemSelected(MenuItem item) {
1269 if (!mCanChord) {
1270 // The user has already fired a shortcut with this hold down of the
1271 // menu key.
1272 return false;
1273 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001274 if (null == getTopWindow()) {
Leon Scroggins0d7ae0e2009-06-05 11:04:45 -04001275 return false;
1276 }
Grace Kloba6ee9c492009-07-13 10:04:34 -07001277 if (mMenuIsDown) {
1278 // The shortcut action consumes the MENU. Even if it is still down,
1279 // it won't trigger the next shortcut action. In the case of the
1280 // shortcut action triggering a new activity, like Bookmarks, we
1281 // won't get onKeyUp for MENU. So it is important to reset it here.
1282 mMenuIsDown = false;
1283 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001284 switch (item.getItemId()) {
1285 // -- Main menu
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001286 case R.id.new_tab_menu_id:
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001287 openTabToHomePage();
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001288 break;
1289
Leon Scroggins64b80f32009-08-07 12:03:34 -04001290 case R.id.goto_menu_id:
Leon Scroggins8ad29922010-02-16 12:33:55 -05001291 editUrl();
Leon Scrogginsb3a5bed2009-09-28 11:21:56 -04001292 break;
1293
1294 case R.id.bookmarks_menu_id:
Leon Scroggins30444232009-09-04 18:36:20 -04001295 bookmarksOrHistoryPicker(false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001296 break;
1297
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001298 case R.id.active_tabs_menu_id:
1299 mActiveTabsPage = new ActiveTabsPage(this, mTabControl);
1300 removeTabFromContentView(mTabControl.getCurrentTab());
Leon Scroggins43de6162009-09-14 19:59:58 -04001301 hideFakeTitleBar();
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001302 mContentView.addView(mActiveTabsPage, COVER_SCREEN_PARAMS);
1303 mActiveTabsPage.requestFocus();
1304 mMenuState = EMPTY_MENU;
1305 break;
1306
Leon Scroggins1f005d32009-08-10 17:36:42 -04001307 case R.id.add_bookmark_menu_id:
1308 Intent i = new Intent(BrowserActivity.this,
1309 AddBookmarkPage.class);
1310 WebView w = getTopWindow();
1311 i.putExtra("url", w.getUrl());
1312 i.putExtra("title", w.getTitle());
Grace Kloba83cdb2c2009-09-16 00:48:57 -07001313 i.putExtra("touch_icon_url", w.getTouchIconUrl());
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01001314 i.putExtra("thumbnail", createScreenshot(w));
Leon Scroggins1f005d32009-08-10 17:36:42 -04001315 startActivity(i);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001316 break;
1317
1318 case R.id.stop_reload_menu_id:
1319 if (mInLoad) {
1320 stopLoading();
1321 } else {
1322 getTopWindow().reload();
1323 }
1324 break;
1325
1326 case R.id.back_menu_id:
1327 getTopWindow().goBack();
1328 break;
1329
1330 case R.id.forward_menu_id:
1331 getTopWindow().goForward();
1332 break;
1333
1334 case R.id.close_menu_id:
1335 // Close the subwindow if it exists.
1336 if (mTabControl.getCurrentSubWindow() != null) {
1337 dismissSubWindow(mTabControl.getCurrentTab());
1338 break;
1339 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001340 closeCurrentWindow();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001341 break;
1342
1343 case R.id.homepage_menu_id:
Grace Kloba22ac16e2009-10-07 18:00:23 -07001344 Tab current = mTabControl.getCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001345 if (current != null) {
1346 dismissSubWindow(current);
Leon Scroggins92472e82010-02-17 16:32:28 -05001347 loadUrl(current.getWebView(), mSettings.getHomePage());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001348 }
1349 break;
1350
1351 case R.id.preferences_menu_id:
1352 Intent intent = new Intent(this,
1353 BrowserPreferencesPage.class);
Leon Scrogginsd5304942009-12-10 16:11:39 -05001354 intent.putExtra(BrowserPreferencesPage.CURRENT_PAGE,
1355 getTopWindow().getUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001356 startActivityForResult(intent, PREFERENCES_PAGE);
1357 break;
1358
1359 case R.id.find_menu_id:
1360 if (null == mFindDialog) {
1361 mFindDialog = new FindDialog(this);
1362 }
1363 mFindDialog.setWebView(getTopWindow());
1364 mFindDialog.show();
Cary Clark7d3ac792010-03-03 10:11:44 -05001365 getTopWindow().setFindIsUp(true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001366 mMenuState = EMPTY_MENU;
1367 break;
1368
1369 case R.id.select_text_id:
1370 getTopWindow().emulateShiftHeld();
1371 break;
1372 case R.id.page_info_menu_id:
1373 showPageInfo(mTabControl.getCurrentTab(), false);
1374 break;
1375
1376 case R.id.classic_history_menu_id:
Leon Scroggins30444232009-09-04 18:36:20 -04001377 bookmarksOrHistoryPicker(true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001378 break;
1379
Leon Scroggins96afcb12009-12-10 12:35:56 -05001380 case R.id.title_bar_share_page_url:
The Android Open Source Project0c908882009-03-03 19:32:16 -08001381 case R.id.share_page_menu_id:
Leon Scroggins96afcb12009-12-10 12:35:56 -05001382 Tab currentTab = mTabControl.getCurrentTab();
1383 if (null == currentTab) {
1384 mCanChord = false;
1385 return false;
1386 }
1387 currentTab.populatePickerData();
1388 sharePage(this, currentTab.getTitle(),
1389 currentTab.getUrl(), currentTab.getFavicon(),
1390 createScreenshot(currentTab.getWebView()));
The Android Open Source Project0c908882009-03-03 19:32:16 -08001391 break;
1392
1393 case R.id.dump_nav_menu_id:
1394 getTopWindow().debugDump();
1395 break;
1396
Andrei Popescu7a8b88b2010-02-02 00:30:38 +00001397 case R.id.dump_counters_menu_id:
1398 getTopWindow().dumpV8Counters();
1399 break;
1400
The Android Open Source Project0c908882009-03-03 19:32:16 -08001401 case R.id.zoom_in_menu_id:
1402 getTopWindow().zoomIn();
1403 break;
1404
1405 case R.id.zoom_out_menu_id:
1406 getTopWindow().zoomOut();
1407 break;
1408
1409 case R.id.view_downloads_menu_id:
1410 viewDownloads(null);
1411 break;
1412
The Android Open Source Project0c908882009-03-03 19:32:16 -08001413 case R.id.window_one_menu_id:
1414 case R.id.window_two_menu_id:
1415 case R.id.window_three_menu_id:
1416 case R.id.window_four_menu_id:
1417 case R.id.window_five_menu_id:
1418 case R.id.window_six_menu_id:
1419 case R.id.window_seven_menu_id:
1420 case R.id.window_eight_menu_id:
1421 {
1422 int menuid = item.getItemId();
1423 for (int id = 0; id < WINDOW_SHORTCUT_ID_ARRAY.length; id++) {
1424 if (WINDOW_SHORTCUT_ID_ARRAY[id] == menuid) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001425 Tab desiredTab = mTabControl.getTab(id);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001426 if (desiredTab != null &&
1427 desiredTab != mTabControl.getCurrentTab()) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001428 switchToTab(id);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001429 }
1430 break;
1431 }
1432 }
1433 }
1434 break;
1435
1436 default:
1437 if (!super.onOptionsItemSelected(item)) {
1438 return false;
1439 }
1440 // Otherwise fall through.
1441 }
1442 mCanChord = false;
1443 return true;
1444 }
1445
1446 public void closeFind() {
1447 mMenuState = R.id.MAIN_MENU;
1448 }
1449
Grace Kloba22ac16e2009-10-07 18:00:23 -07001450 @Override
1451 public boolean onPrepareOptionsMenu(Menu menu) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001452 // This happens when the user begins to hold down the menu key, so
1453 // allow them to chord to get a shortcut.
1454 mCanChord = true;
1455 // Note: setVisible will decide whether an item is visible; while
1456 // setEnabled() will decide whether an item is enabled, which also means
1457 // whether the matching shortcut key will function.
1458 super.onPrepareOptionsMenu(menu);
1459 switch (mMenuState) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001460 case EMPTY_MENU:
1461 if (mCurrentMenuState != mMenuState) {
1462 menu.setGroupVisible(R.id.MAIN_MENU, false);
1463 menu.setGroupEnabled(R.id.MAIN_MENU, false);
1464 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001465 }
1466 break;
1467 default:
1468 if (mCurrentMenuState != mMenuState) {
1469 menu.setGroupVisible(R.id.MAIN_MENU, true);
1470 menu.setGroupEnabled(R.id.MAIN_MENU, true);
1471 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001472 }
1473 final WebView w = getTopWindow();
1474 boolean canGoBack = false;
1475 boolean canGoForward = false;
1476 boolean isHome = false;
1477 if (w != null) {
1478 canGoBack = w.canGoBack();
1479 canGoForward = w.canGoForward();
1480 isHome = mSettings.getHomePage().equals(w.getUrl());
1481 }
1482 final MenuItem back = menu.findItem(R.id.back_menu_id);
1483 back.setEnabled(canGoBack);
1484
1485 final MenuItem home = menu.findItem(R.id.homepage_menu_id);
1486 home.setEnabled(!isHome);
1487
1488 menu.findItem(R.id.forward_menu_id)
1489 .setEnabled(canGoForward);
1490
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001491 menu.findItem(R.id.new_tab_menu_id).setEnabled(
Grace Kloba22ac16e2009-10-07 18:00:23 -07001492 mTabControl.canCreateNewTab());
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001493
The Android Open Source Project0c908882009-03-03 19:32:16 -08001494 // decide whether to show the share link option
1495 PackageManager pm = getPackageManager();
1496 Intent send = new Intent(Intent.ACTION_SEND);
1497 send.setType("text/plain");
1498 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1499 menu.findItem(R.id.share_page_menu_id).setVisible(ri != null);
1500
The Android Open Source Project0c908882009-03-03 19:32:16 -08001501 boolean isNavDump = mSettings.isNavDump();
1502 final MenuItem nav = menu.findItem(R.id.dump_nav_menu_id);
1503 nav.setVisible(isNavDump);
1504 nav.setEnabled(isNavDump);
Andrei Popescu7a8b88b2010-02-02 00:30:38 +00001505
1506 boolean showDebugSettings = mSettings.showDebugSettings();
1507 final MenuItem counter = menu.findItem(R.id.dump_counters_menu_id);
1508 counter.setVisible(showDebugSettings);
1509 counter.setEnabled(showDebugSettings);
1510
The Android Open Source Project0c908882009-03-03 19:32:16 -08001511 break;
1512 }
1513 mCurrentMenuState = mMenuState;
1514 return true;
1515 }
1516
1517 @Override
1518 public void onCreateContextMenu(ContextMenu menu, View v,
1519 ContextMenuInfo menuInfo) {
Leon Scroggins4e9f89b2010-02-22 16:54:14 -05001520 if (v instanceof TitleBar) {
1521 return;
1522 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001523 WebView webview = (WebView) v;
1524 WebView.HitTestResult result = webview.getHitTestResult();
1525 if (result == null) {
1526 return;
1527 }
1528
1529 int type = result.getType();
1530 if (type == WebView.HitTestResult.UNKNOWN_TYPE) {
1531 Log.w(LOGTAG,
1532 "We should not show context menu when nothing is touched");
1533 return;
1534 }
1535 if (type == WebView.HitTestResult.EDIT_TEXT_TYPE) {
1536 // let TextView handles context menu
1537 return;
1538 }
1539
1540 // Note, http://b/issue?id=1106666 is requesting that
1541 // an inflated menu can be used again. This is not available
1542 // yet, so inflate each time (yuk!)
1543 MenuInflater inflater = getMenuInflater();
1544 inflater.inflate(R.menu.browsercontext, menu);
1545
1546 // Show the correct menu group
1547 String extra = result.getExtra();
1548 menu.setGroupVisible(R.id.PHONE_MENU,
1549 type == WebView.HitTestResult.PHONE_TYPE);
1550 menu.setGroupVisible(R.id.EMAIL_MENU,
1551 type == WebView.HitTestResult.EMAIL_TYPE);
1552 menu.setGroupVisible(R.id.GEO_MENU,
1553 type == WebView.HitTestResult.GEO_TYPE);
1554 menu.setGroupVisible(R.id.IMAGE_MENU,
1555 type == WebView.HitTestResult.IMAGE_TYPE
1556 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1557 menu.setGroupVisible(R.id.ANCHOR_MENU,
1558 type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1559 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1560
1561 // Setup custom handling depending on the type
1562 switch (type) {
1563 case WebView.HitTestResult.PHONE_TYPE:
1564 menu.setHeaderTitle(Uri.decode(extra));
1565 menu.findItem(R.id.dial_context_menu_id).setIntent(
1566 new Intent(Intent.ACTION_VIEW, Uri
1567 .parse(WebView.SCHEME_TEL + extra)));
1568 Intent addIntent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
1569 addIntent.putExtra(Insert.PHONE, Uri.decode(extra));
Cary Clark5e335a32009-09-22 14:53:11 -04001570 addIntent.setType(ContactsContract.Contacts.CONTENT_ITEM_TYPE);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001571 menu.findItem(R.id.add_contact_context_menu_id).setIntent(
1572 addIntent);
1573 menu.findItem(R.id.copy_phone_context_menu_id).setOnMenuItemClickListener(
1574 new Copy(extra));
1575 break;
1576
1577 case WebView.HitTestResult.EMAIL_TYPE:
1578 menu.setHeaderTitle(extra);
1579 menu.findItem(R.id.email_context_menu_id).setIntent(
1580 new Intent(Intent.ACTION_VIEW, Uri
1581 .parse(WebView.SCHEME_MAILTO + extra)));
1582 menu.findItem(R.id.copy_mail_context_menu_id).setOnMenuItemClickListener(
1583 new Copy(extra));
1584 break;
1585
1586 case WebView.HitTestResult.GEO_TYPE:
1587 menu.setHeaderTitle(extra);
1588 menu.findItem(R.id.map_context_menu_id).setIntent(
1589 new Intent(Intent.ACTION_VIEW, Uri
1590 .parse(WebView.SCHEME_GEO
1591 + URLEncoder.encode(extra))));
1592 menu.findItem(R.id.copy_geo_context_menu_id).setOnMenuItemClickListener(
1593 new Copy(extra));
1594 break;
1595
1596 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1597 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
1598 TextView titleView = (TextView) LayoutInflater.from(this)
1599 .inflate(android.R.layout.browser_link_context_header,
1600 null);
1601 titleView.setText(extra);
1602 menu.setHeaderView(titleView);
1603 // decide whether to show the open link in new tab option
1604 menu.findItem(R.id.open_newtab_context_menu_id).setVisible(
Grace Kloba22ac16e2009-10-07 18:00:23 -07001605 mTabControl.canCreateNewTab());
Ben Murdochde353622009-10-12 10:29:00 +01001606 menu.findItem(R.id.bookmark_context_menu_id).setVisible(
1607 Bookmarks.urlHasAcceptableScheme(extra));
The Android Open Source Project0c908882009-03-03 19:32:16 -08001608 PackageManager pm = getPackageManager();
1609 Intent send = new Intent(Intent.ACTION_SEND);
1610 send.setType("text/plain");
1611 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1612 menu.findItem(R.id.share_link_context_menu_id).setVisible(ri != null);
1613 if (type == WebView.HitTestResult.SRC_ANCHOR_TYPE) {
1614 break;
1615 }
1616 // otherwise fall through to handle image part
1617 case WebView.HitTestResult.IMAGE_TYPE:
1618 if (type == WebView.HitTestResult.IMAGE_TYPE) {
1619 menu.setHeaderTitle(extra);
1620 }
1621 menu.findItem(R.id.view_image_context_menu_id).setIntent(
1622 new Intent(Intent.ACTION_VIEW, Uri.parse(extra)));
1623 menu.findItem(R.id.download_context_menu_id).
1624 setOnMenuItemClickListener(new Download(extra));
Ben Murdoch4f75ba22009-10-27 11:48:28 +00001625 menu.findItem(R.id.set_wallpaper_context_menu_id).
1626 setOnMenuItemClickListener(new SetAsWallpaper(extra));
The Android Open Source Project0c908882009-03-03 19:32:16 -08001627 break;
1628
1629 default:
1630 Log.w(LOGTAG, "We should not get here.");
1631 break;
1632 }
Leon Scrogginsb2b19f52009-10-09 16:10:00 -04001633 hideFakeTitleBar();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001634 }
1635
The Android Open Source Project0c908882009-03-03 19:32:16 -08001636 // Attach the given tab to the content view.
Grace Klobac928c302009-09-17 11:51:21 -07001637 // this should only be called for the current tab.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001638 private void attachTabToContentView(Tab t) {
Steve Block2bc69912009-07-30 14:45:13 +01001639 // Attach the container that contains the main WebView and any other UI
1640 // associated with the tab.
Patrick Scottd0119532009-09-17 08:00:31 -04001641 t.attachTabToContentView(mContentView);
Ben Murdochbff2d602009-07-01 20:19:05 +01001642
1643 if (mShouldShowErrorConsole) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001644 ErrorConsoleView errorConsole = t.getErrorConsole(true);
Ben Murdochbff2d602009-07-01 20:19:05 +01001645 if (errorConsole.numberOfErrors() == 0) {
1646 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
1647 } else {
1648 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
1649 }
1650
1651 mErrorConsoleContainer.addView(errorConsole,
Romain Guy15b8ec62010-01-08 15:06:43 -08001652 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
Ben Murdochbff2d602009-07-01 20:19:05 +01001653 ViewGroup.LayoutParams.WRAP_CONTENT));
1654 }
1655
Leon Scroggins39ab28e2009-09-02 21:20:30 -04001656 WebView view = t.getWebView();
Leon Scroggins55a5bc22009-09-04 17:00:08 -04001657 view.setEmbeddedTitleBar(mTitleBar);
Leon Scroggins58d56c62010-01-28 15:12:40 -05001658 if (t.isInVoiceSearchMode()) {
1659 showVoiceTitleBar(t.getVoiceDisplayTitle());
1660 } else {
1661 revertVoiceTitleBar();
1662 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001663 // Request focus on the top window.
1664 t.getTopWindow().requestFocus();
1665 }
1666
1667 // Attach a sub window to the main WebView of the given tab.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001668 void attachSubWindow(Tab t) {
Patrick Scottd0119532009-09-17 08:00:31 -04001669 t.attachSubWindow(mContentView);
1670 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001671 }
1672
1673 // Remove the given tab from the content view.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001674 private void removeTabFromContentView(Tab t) {
Steve Block2bc69912009-07-30 14:45:13 +01001675 // Remove the container that contains the main WebView.
Patrick Scottd0119532009-09-17 08:00:31 -04001676 t.removeTabFromContentView(mContentView);
Ben Murdochbff2d602009-07-01 20:19:05 +01001677
Grace Kloba22ac16e2009-10-07 18:00:23 -07001678 ErrorConsoleView errorConsole = t.getErrorConsole(false);
1679 if (errorConsole != null) {
1680 mErrorConsoleContainer.removeView(errorConsole);
Ben Murdochbff2d602009-07-01 20:19:05 +01001681 }
1682
Leon Scroggins39ab28e2009-09-02 21:20:30 -04001683 WebView view = t.getWebView();
Leon Scrogginsbb85b902009-09-14 19:27:20 -04001684 if (view != null) {
1685 view.setEmbeddedTitleBar(null);
1686 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001687 }
1688
1689 // Remove the sub window if it exists. Also called by TabControl when the
1690 // user clicks the 'X' to dismiss a sub window.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001691 /* package */ void dismissSubWindow(Tab t) {
Patrick Scottd0119532009-09-17 08:00:31 -04001692 t.removeSubWindow(mContentView);
Grace Kloba22ac16e2009-10-07 18:00:23 -07001693 // dismiss the subwindow. This will destroy the WebView.
1694 t.dismissSubWindow();
Patrick Scottd0119532009-09-17 08:00:31 -04001695 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001696 }
1697
Leon Scroggins1f005d32009-08-10 17:36:42 -04001698 // A wrapper function of {@link #openTabAndShow(UrlData, boolean, String)}
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07001699 // that accepts url as string.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001700 private Tab openTabAndShow(String url, boolean closeOnExit, String appId) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001701 return openTabAndShow(new UrlData(url), closeOnExit, appId);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001702 }
1703
1704 // This method does a ton of stuff. It will attempt to create a new tab
1705 // if we haven't reached MAX_TABS. Otherwise it uses the current tab. If
Leon Scroggins1f005d32009-08-10 17:36:42 -04001706 // url isn't null, it will load the given url.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001707 /* package */Tab openTabAndShow(UrlData urlData, boolean closeOnExit,
1708 String appId) {
1709 final Tab currentTab = mTabControl.getCurrentTab();
1710 if (mTabControl.canCreateNewTab()) {
1711 final Tab tab = mTabControl.createNewTab(closeOnExit, appId,
1712 urlData.mUrl);
Leon Scroggins1f005d32009-08-10 17:36:42 -04001713 WebView webview = tab.getWebView();
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001714 // If the last tab was removed from the active tabs page, currentTab
1715 // will be null.
1716 if (currentTab != null) {
1717 removeTabFromContentView(currentTab);
1718 }
Patrick Scott8bbd69f2009-08-14 13:35:53 -04001719 // We must set the new tab as the current tab to reflect the old
1720 // animation behavior.
1721 mTabControl.setCurrentTab(tab);
Grace Klobaeb6eef42009-09-15 17:56:32 -07001722 attachTabToContentView(tab);
Leon Scroggins160a7e72009-08-14 18:28:01 -04001723 if (!urlData.isEmpty()) {
Patrick Scott9d53da02010-02-19 10:19:01 -05001724 loadUrlDataIn(tab, urlData);
Leon Scroggins1f005d32009-08-10 17:36:42 -04001725 }
1726 return tab;
1727 } else {
1728 // Get rid of the subwindow if it exists
1729 dismissSubWindow(currentTab);
1730 if (!urlData.isEmpty()) {
1731 // Load the given url.
Patrick Scott9d53da02010-02-19 10:19:01 -05001732 loadUrlDataIn(currentTab, urlData);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001733 }
Leon Scroggins58d56c62010-01-28 15:12:40 -05001734 return currentTab;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001735 }
1736 }
1737
Grace Kloba22ac16e2009-10-07 18:00:23 -07001738 private Tab openTab(String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001739 if (mSettings.openInBackground()) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001740 Tab t = mTabControl.createNewTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001741 if (t != null) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001742 WebView view = t.getWebView();
Leon Scroggins92472e82010-02-17 16:32:28 -05001743 loadUrl(view, url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001744 }
Grace Klobac9181842009-04-14 08:53:22 -07001745 return t;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001746 } else {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001747 return openTabAndShow(url, false, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001748 }
1749 }
1750
1751 private class Copy implements OnMenuItemClickListener {
1752 private CharSequence mText;
1753
1754 public boolean onMenuItemClick(MenuItem item) {
1755 copy(mText);
1756 return true;
1757 }
1758
1759 public Copy(CharSequence toCopy) {
1760 mText = toCopy;
1761 }
1762 }
1763
1764 private class Download implements OnMenuItemClickListener {
1765 private String mText;
1766
1767 public boolean onMenuItemClick(MenuItem item) {
1768 onDownloadStartNoStream(mText, null, null, null, -1);
1769 return true;
1770 }
1771
1772 public Download(String toDownload) {
1773 mText = toDownload;
1774 }
1775 }
1776
Ben Murdoch4f75ba22009-10-27 11:48:28 +00001777 private class SetAsWallpaper extends Thread implements
1778 OnMenuItemClickListener, DialogInterface.OnCancelListener {
1779 private URL mUrl;
1780 private ProgressDialog mWallpaperProgress;
1781 private boolean mCanceled = false;
1782
1783 public SetAsWallpaper(String url) {
1784 try {
1785 mUrl = new URL(url);
1786 } catch (MalformedURLException e) {
1787 mUrl = null;
1788 }
1789 }
1790
1791 public void onCancel(DialogInterface dialog) {
1792 mCanceled = true;
1793 }
1794
1795 public boolean onMenuItemClick(MenuItem item) {
1796 if (mUrl != null) {
1797 // The user may have tried to set a image with a large file size as their
1798 // background so it may take a few moments to perform the operation. Display
1799 // a progress spinner while it is working.
1800 mWallpaperProgress = new ProgressDialog(BrowserActivity.this);
1801 mWallpaperProgress.setIndeterminate(true);
1802 mWallpaperProgress.setMessage(getText(R.string.progress_dialog_setting_wallpaper));
1803 mWallpaperProgress.setCancelable(true);
1804 mWallpaperProgress.setOnCancelListener(this);
1805 mWallpaperProgress.show();
1806 start();
1807 }
1808 return true;
1809 }
1810
1811 public void run() {
1812 Drawable oldWallpaper = BrowserActivity.this.getWallpaper();
1813 try {
1814 // TODO: This will cause the resource to be downloaded again, when we
1815 // should in most cases be able to grab it from the cache. To fix this
1816 // we should query WebCore to see if we can access a cached version and
1817 // instead open an input stream on that. This pattern could also be used
1818 // in the download manager where the same problem exists.
1819 InputStream inputstream = mUrl.openStream();
1820 if (inputstream != null) {
1821 setWallpaper(inputstream);
1822 }
1823 } catch (IOException e) {
1824 Log.e(LOGTAG, "Unable to set new wallpaper");
1825 // Act as though the user canceled the operation so we try to
1826 // restore the old wallpaper.
1827 mCanceled = true;
1828 }
1829
1830 if (mCanceled) {
1831 // Restore the old wallpaper if the user cancelled whilst we were setting
1832 // the new wallpaper.
1833 int width = oldWallpaper.getIntrinsicWidth();
1834 int height = oldWallpaper.getIntrinsicHeight();
1835 Bitmap bm = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
1836 Canvas canvas = new Canvas(bm);
1837 oldWallpaper.setBounds(0, 0, width, height);
1838 oldWallpaper.draw(canvas);
1839 try {
1840 setWallpaper(bm);
1841 } catch (IOException e) {
1842 Log.e(LOGTAG, "Unable to restore old wallpaper.");
1843 }
1844 mCanceled = false;
1845 }
1846
1847 if (mWallpaperProgress.isShowing()) {
1848 mWallpaperProgress.dismiss();
1849 }
1850 }
1851 }
1852
The Android Open Source Project0c908882009-03-03 19:32:16 -08001853 private void copy(CharSequence text) {
1854 try {
1855 IClipboard clip = IClipboard.Stub.asInterface(ServiceManager.getService("clipboard"));
1856 if (clip != null) {
1857 clip.setClipboardText(text);
1858 }
1859 } catch (android.os.RemoteException e) {
1860 Log.e(LOGTAG, "Copy failed", e);
1861 }
1862 }
1863
1864 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08001865 * Resets the browser title-view to whatever it must be
1866 * (for example, if we had a loading error)
1867 * When we have a new page, we call resetTitle, when we
1868 * have to reset the titlebar to whatever it used to be
1869 * (for example, if the user chose to stop loading), we
1870 * call resetTitleAndRevertLockIcon.
1871 */
1872 /* package */ void resetTitleAndRevertLockIcon() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001873 mTabControl.getCurrentTab().revertLockIcon();
1874 updateLockIconToLatest();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001875 resetTitleIconAndProgress();
1876 }
1877
1878 /**
1879 * Reset the title, favicon, and progress.
1880 */
1881 private void resetTitleIconAndProgress() {
1882 WebView current = mTabControl.getCurrentWebView();
1883 if (current == null) {
1884 return;
1885 }
1886 resetTitleAndIcon(current);
1887 int progress = current.getProgress();
Grace Kloba22ac16e2009-10-07 18:00:23 -07001888 current.getWebChromeClient().onProgressChanged(current, progress);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001889 }
1890
1891 // Reset the title and the icon based on the given item.
1892 private void resetTitleAndIcon(WebView view) {
1893 WebHistoryItem item = view.copyBackForwardList().getCurrentItem();
1894 if (item != null) {
Leon Scroggins68579392009-09-15 15:31:54 -04001895 setUrlTitle(item.getUrl(), item.getTitle());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001896 setFavicon(item.getFavicon());
1897 } else {
Leon Scroggins68579392009-09-15 15:31:54 -04001898 setUrlTitle(null, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001899 setFavicon(null);
1900 }
1901 }
1902
1903 /**
1904 * Sets a title composed of the URL and the title string.
1905 * @param url The URL of the site being loaded.
1906 * @param title The title of the site being loaded.
1907 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07001908 void setUrlTitle(String url, String title) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001909 mUrl = url;
1910 mTitle = title;
1911
Leon Scroggins58d56c62010-01-28 15:12:40 -05001912 // If we are in voice search mode, the title has already been set.
1913 if (mTabControl.getCurrentTab().isInVoiceSearchMode()) return;
1914 mTitleBar.setDisplayTitle(url);
1915 mFakeTitleBar.setDisplayTitle(url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001916 }
1917
1918 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08001919 * @param url The URL to build a title version of the URL from.
1920 * @return The title version of the URL or null if fails.
1921 * The title version of the URL can be either the URL hostname,
1922 * or the hostname with an "https://" prefix (for secure URLs),
1923 * or an empty string if, for example, the URL in question is a
1924 * file:// URL with no hostname.
1925 */
Leon Scroggins32e14a62009-06-11 10:26:34 -04001926 /* package */ static String buildTitleUrl(String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001927 String titleUrl = null;
1928
1929 if (url != null) {
1930 try {
1931 // parse the url string
1932 URL urlObj = new URL(url);
1933 if (urlObj != null) {
1934 titleUrl = "";
1935
1936 String protocol = urlObj.getProtocol();
1937 String host = urlObj.getHost();
1938
1939 if (host != null && 0 < host.length()) {
1940 titleUrl = host;
1941 if (protocol != null) {
1942 // if a secure site, add an "https://" prefix!
1943 if (protocol.equalsIgnoreCase("https")) {
1944 titleUrl = protocol + "://" + host;
1945 }
1946 }
1947 }
1948 }
1949 } catch (MalformedURLException e) {}
1950 }
1951
1952 return titleUrl;
1953 }
1954
1955 // Set the favicon in the title bar.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001956 void setFavicon(Bitmap icon) {
Leon Scroggins68579392009-09-15 15:31:54 -04001957 mTitleBar.setFavicon(icon);
Leon Scrogginsfe87bd32009-10-06 10:10:00 -04001958 mFakeTitleBar.setFavicon(icon);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001959 }
1960
1961 /**
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001962 * Close the tab, remove its associated title bar, and adjust mTabControl's
1963 * current tab to a valid value.
Leon Scroggins1f005d32009-08-10 17:36:42 -04001964 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07001965 /* package */ void closeTab(Tab t) {
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001966 int currentIndex = mTabControl.getCurrentIndex();
1967 int removeIndex = mTabControl.getTabIndex(t);
Leon Scroggins1f005d32009-08-10 17:36:42 -04001968 mTabControl.removeTab(t);
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001969 if (currentIndex >= removeIndex && currentIndex != 0) {
1970 currentIndex--;
1971 }
1972 mTabControl.setCurrentTab(mTabControl.getTab(currentIndex));
Andrei Popescua5bf1de2009-09-23 16:39:23 +01001973 resetTitleIconAndProgress();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001974 }
1975
Leon Scrogginsdcc5eeb2010-02-23 17:26:37 -05001976 /* package */ void goBackOnePageOrQuit() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001977 Tab current = mTabControl.getCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001978 if (current == null) {
1979 /*
1980 * Instead of finishing the activity, simply push this to the back
1981 * of the stack and let ActivityManager to choose the foreground
1982 * activity. As BrowserActivity is singleTask, it will be always the
1983 * root of the task. So we can use either true or false for
1984 * moveTaskToBack().
1985 */
1986 moveTaskToBack(true);
Grace Kloba00d85e72009-09-23 18:50:05 -07001987 return;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001988 }
1989 WebView w = current.getWebView();
1990 if (w.canGoBack()) {
1991 w.goBack();
1992 } else {
1993 // Check to see if we are closing a window that was created by
1994 // another window. If so, we switch back to that window.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001995 Tab parent = current.getParentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001996 if (parent != null) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001997 switchToTab(mTabControl.getTabIndex(parent));
1998 // Now we close the other tab
1999 closeTab(current);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002000 } else {
2001 if (current.closeOnExit()) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002002 // force the tab's inLoad() to be false as we are going to
2003 // either finish the activity or remove the tab. This will
2004 // ensure pauseWebViewTimers() taking action.
2005 mTabControl.getCurrentTab().clearInLoad();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002006 if (mTabControl.getTabCount() == 1) {
2007 finish();
2008 return;
2009 }
Mike Reed7bfa63b2009-05-28 11:08:32 -04002010 // call pauseWebViewTimers() now, we won't be able to call
2011 // it in onPause() as the WebView won't be valid.
Grace Klobaec1b5ad2009-08-18 08:42:32 -07002012 // Temporarily change mActivityInPause to be true as
2013 // pauseWebViewTimers() will do nothing if mActivityInPause
2014 // is false.
Grace Kloba918e1d72009-08-13 14:55:06 -07002015 boolean savedState = mActivityInPause;
2016 if (savedState) {
Grace Klobaec1b5ad2009-08-18 08:42:32 -07002017 Log.e(LOGTAG, "BrowserActivity is already paused "
2018 + "while handing goBackOnePageOrQuit.");
Grace Kloba918e1d72009-08-13 14:55:06 -07002019 }
2020 mActivityInPause = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -04002021 pauseWebViewTimers();
Grace Kloba918e1d72009-08-13 14:55:06 -07002022 mActivityInPause = savedState;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002023 removeTabFromContentView(current);
2024 mTabControl.removeTab(current);
2025 }
2026 /*
2027 * Instead of finishing the activity, simply push this to the back
2028 * of the stack and let ActivityManager to choose the foreground
2029 * activity. As BrowserActivity is singleTask, it will be always the
2030 * root of the task. So we can use either true or false for
2031 * moveTaskToBack().
2032 */
2033 moveTaskToBack(true);
2034 }
2035 }
2036 }
2037
Grace Kloba22ac16e2009-10-07 18:00:23 -07002038 boolean isMenuDown() {
2039 return mMenuIsDown;
2040 }
2041
Grace Kloba5942df02009-09-18 11:48:29 -07002042 @Override
2043 public boolean onKeyDown(int keyCode, KeyEvent event) {
Leon Scrogginsf65b50d2009-12-08 10:44:28 -05002044 // Even if MENU is already held down, we need to call to super to open
2045 // the IME on long press.
2046 if (KeyEvent.KEYCODE_MENU == keyCode) {
2047 mMenuIsDown = true;
2048 return super.onKeyDown(keyCode, event);
2049 }
Grace Kloba5942df02009-09-18 11:48:29 -07002050 // The default key mode is DEFAULT_KEYS_SEARCH_LOCAL. As the MENU is
2051 // still down, we don't want to trigger the search. Pretend to consume
2052 // the key and do nothing.
2053 if (mMenuIsDown) return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002054
Grace Kloba5942df02009-09-18 11:48:29 -07002055 switch(keyCode) {
Grace Kloba5942df02009-09-18 11:48:29 -07002056 case KeyEvent.KEYCODE_SPACE:
Grace Klobada0fe552009-09-22 18:17:24 -07002057 // WebView/WebTextView handle the keys in the KeyDown. As
2058 // the Activity's shortcut keys are only handled when WebView
2059 // doesn't, have to do it in onKeyDown instead of onKeyUp.
2060 if (event.isShiftPressed()) {
2061 getTopWindow().pageUp(false);
2062 } else {
2063 getTopWindow().pageDown(false);
2064 }
Grace Kloba5942df02009-09-18 11:48:29 -07002065 return true;
2066 case KeyEvent.KEYCODE_BACK:
2067 if (event.getRepeatCount() == 0) {
2068 event.startTracking();
2069 return true;
2070 } else if (mCustomView == null && mActiveTabsPage == null
2071 && event.isLongPress()) {
2072 bookmarksOrHistoryPicker(true);
2073 return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002074 }
Grace Kloba5942df02009-09-18 11:48:29 -07002075 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002076 }
Grace Kloba5942df02009-09-18 11:48:29 -07002077 return super.onKeyDown(keyCode, event);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002078 }
2079
Grace Kloba5942df02009-09-18 11:48:29 -07002080 @Override
2081 public boolean onKeyUp(int keyCode, KeyEvent event) {
2082 switch(keyCode) {
2083 case KeyEvent.KEYCODE_MENU:
2084 mMenuIsDown = false;
2085 break;
Grace Kloba5942df02009-09-18 11:48:29 -07002086 case KeyEvent.KEYCODE_BACK:
2087 if (event.isTracking() && !event.isCanceled()) {
2088 if (mCustomView != null) {
2089 // if a custom view is showing, hide it
Grace Kloba22ac16e2009-10-07 18:00:23 -07002090 mTabControl.getCurrentWebView().getWebChromeClient()
2091 .onHideCustomView();
Grace Kloba5942df02009-09-18 11:48:29 -07002092 } else if (mActiveTabsPage != null) {
2093 // if tab page is showing, hide it
2094 removeActiveTabPage(true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002095 } else {
Grace Kloba5942df02009-09-18 11:48:29 -07002096 WebView subwindow = mTabControl.getCurrentSubWindow();
2097 if (subwindow != null) {
2098 if (subwindow.canGoBack()) {
2099 subwindow.goBack();
2100 } else {
2101 dismissSubWindow(mTabControl.getCurrentTab());
2102 }
2103 } else {
2104 goBackOnePageOrQuit();
2105 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002106 }
Grace Kloba5942df02009-09-18 11:48:29 -07002107 return true;
2108 }
2109 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002110 }
Grace Kloba5942df02009-09-18 11:48:29 -07002111 return super.onKeyUp(keyCode, event);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002112 }
2113
Leon Scroggins68579392009-09-15 15:31:54 -04002114 /* package */ void stopLoading() {
Ben Murdochb7cc8b42009-09-28 10:59:09 +01002115 mDidStopLoad = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002116 resetTitleAndRevertLockIcon();
2117 WebView w = getTopWindow();
2118 w.stopLoading();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002119 // FIXME: before refactor, it is using mWebViewClient. So I keep the
2120 // same logic here. But for subwindow case, should we call into the main
2121 // WebView's onPageFinished as we never call its onPageStarted and if
2122 // the page finishes itself, we don't call onPageFinished.
2123 mTabControl.getCurrentWebView().getWebViewClient().onPageFinished(w,
2124 w.getUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08002125
2126 cancelStopToast();
2127 mStopToast = Toast
2128 .makeText(this, R.string.stopping, Toast.LENGTH_SHORT);
2129 mStopToast.show();
2130 }
2131
Grace Kloba22ac16e2009-10-07 18:00:23 -07002132 boolean didUserStopLoading() {
2133 return mDidStopLoad;
2134 }
2135
The Android Open Source Project0c908882009-03-03 19:32:16 -08002136 private void cancelStopToast() {
2137 if (mStopToast != null) {
2138 mStopToast.cancel();
2139 mStopToast = null;
2140 }
2141 }
2142
Grace Kloba22ac16e2009-10-07 18:00:23 -07002143 // called by a UI or non-UI thread to post the message
2144 public void postMessage(int what, int arg1, int arg2, Object obj,
2145 long delayMillis) {
2146 mHandler.sendMessageDelayed(mHandler.obtainMessage(what, arg1, arg2,
2147 obj), delayMillis);
2148 }
2149
2150 // called by a UI or non-UI thread to remove the message
2151 void removeMessages(int what, Object object) {
2152 mHandler.removeMessages(what, object);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002153 }
2154
2155 // public message ids
2156 public final static int LOAD_URL = 1001;
2157 public final static int STOP_LOAD = 1002;
2158
2159 // Message Ids
2160 private static final int FOCUS_NODE_HREF = 102;
Grace Kloba92c18a52009-07-31 23:48:32 -07002161 private static final int RELEASE_WAKELOCK = 107;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002162
Grace Kloba22ac16e2009-10-07 18:00:23 -07002163 static final int UPDATE_BOOKMARK_THUMBNAIL = 108;
Ben Murdoch2694e232009-09-29 09:41:11 +01002164
The Android Open Source Project0c908882009-03-03 19:32:16 -08002165 // Private handler for handling javascript and saving passwords
2166 private Handler mHandler = new Handler() {
2167
2168 public void handleMessage(Message msg) {
2169 switch (msg.what) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002170 case FOCUS_NODE_HREF:
Ben Murdoch2694e232009-09-29 09:41:11 +01002171 {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002172 String url = (String) msg.getData().get("url");
Ben Murdoch90d088c2009-11-17 18:14:04 +00002173 String title = (String) msg.getData().get("title");
The Android Open Source Project0c908882009-03-03 19:32:16 -08002174 if (url == null || url.length() == 0) {
2175 break;
2176 }
2177 HashMap focusNodeMap = (HashMap) msg.obj;
2178 WebView view = (WebView) focusNodeMap.get("webview");
2179 // Only apply the action if the top window did not change.
2180 if (getTopWindow() != view) {
2181 break;
2182 }
2183 switch (msg.arg1) {
2184 case R.id.open_context_menu_id:
2185 case R.id.view_image_context_menu_id:
Leon Scroggins92472e82010-02-17 16:32:28 -05002186 loadUrlFromContext(getTopWindow(), url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002187 break;
2188 case R.id.open_newtab_context_menu_id:
Grace Kloba22ac16e2009-10-07 18:00:23 -07002189 final Tab parent = mTabControl.getCurrentTab();
2190 final Tab newTab = openTab(url);
Grace Klobac9181842009-04-14 08:53:22 -07002191 if (newTab != parent) {
2192 parent.addChildTab(newTab);
2193 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002194 break;
2195 case R.id.bookmark_context_menu_id:
2196 Intent intent = new Intent(BrowserActivity.this,
2197 AddBookmarkPage.class);
2198 intent.putExtra("url", url);
Ben Murdoch90d088c2009-11-17 18:14:04 +00002199 intent.putExtra("title", title);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002200 startActivity(intent);
2201 break;
2202 case R.id.share_link_context_menu_id:
Leon Scroggins96afcb12009-12-10 12:35:56 -05002203 // See if this site has been visited before
2204 StringBuilder sb = new StringBuilder(
2205 Browser.BookmarkColumns.URL + " = ");
2206 DatabaseUtils.appendEscapedSQLString(sb, url);
2207 Cursor c = mResolver.query(Browser.BOOKMARKS_URI,
2208 Browser.HISTORY_PROJECTION,
2209 sb.toString(),
2210 null,
2211 null);
2212 if (c.moveToFirst()) {
2213 // The site has been visited before, so grab the
2214 // info from the database.
2215 Bitmap favicon = null;
2216 Bitmap thumbnail = null;
2217 String linkTitle = c.getString(Browser.
2218 HISTORY_PROJECTION_TITLE_INDEX);
2219 byte[] data = c.getBlob(Browser.
2220 HISTORY_PROJECTION_FAVICON_INDEX);
2221 if (data != null) {
2222 favicon = BitmapFactory.decodeByteArray(
2223 data, 0, data.length);
2224 }
2225 data = c.getBlob(Browser.
2226 HISTORY_PROJECTION_THUMBNAIL_INDEX);
2227 if (data != null) {
2228 thumbnail = BitmapFactory.decodeByteArray(
2229 data, 0, data.length);
2230 }
2231 sharePage(BrowserActivity.this,
2232 linkTitle, url, favicon, thumbnail);
2233 } else {
2234 Browser.sendString(BrowserActivity.this, url,
2235 getString(
2236 R.string.choosertitle_sharevia));
2237 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002238 break;
2239 case R.id.copy_link_context_menu_id:
2240 copy(url);
2241 break;
2242 case R.id.save_link_context_menu_id:
2243 case R.id.download_context_menu_id:
2244 onDownloadStartNoStream(url, null, null, null, -1);
2245 break;
2246 }
2247 break;
Ben Murdoch2694e232009-09-29 09:41:11 +01002248 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002249
2250 case LOAD_URL:
Leon Scroggins92472e82010-02-17 16:32:28 -05002251 loadUrlFromContext(getTopWindow(), (String) msg.obj);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002252 break;
2253
2254 case STOP_LOAD:
2255 stopLoading();
2256 break;
2257
The Android Open Source Project0c908882009-03-03 19:32:16 -08002258 case RELEASE_WAKELOCK:
2259 if (mWakeLock.isHeld()) {
2260 mWakeLock.release();
Grace Kloba5d0e02e2009-10-05 15:15:36 -07002261 // if we reach here, Browser should be still in the
2262 // background loading after WAKELOCK_TIMEOUT (5-min).
2263 // To avoid burning the battery, stop loading.
2264 mTabControl.stopAllLoading();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002265 }
2266 break;
Ben Murdoch2694e232009-09-29 09:41:11 +01002267
2268 case UPDATE_BOOKMARK_THUMBNAIL:
2269 WebView view = (WebView) msg.obj;
2270 if (view != null) {
2271 updateScreenshot(view);
2272 }
2273 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002274 }
2275 }
2276 };
2277
Leon Scroggins96afcb12009-12-10 12:35:56 -05002278 /**
2279 * Share a page, providing the title, url, favicon, and a screenshot. Uses
2280 * an {@link Intent} to launch the Activity chooser.
2281 * @param c Context used to launch a new Activity.
2282 * @param title Title of the page. Stored in the Intent with
Paul Westbrook03e6d392010-02-12 10:33:29 -08002283 * {@link Intent#EXTRA_SUBJECT}
Leon Scroggins96afcb12009-12-10 12:35:56 -05002284 * @param url URL of the page. Stored in the Intent with
2285 * {@link Intent#EXTRA_TEXT}
2286 * @param favicon Bitmap of the favicon for the page. Stored in the Intent
2287 * with {@link Browser#EXTRA_SHARE_FAVICON}
2288 * @param screenshot Bitmap of a screenshot of the page. Stored in the
2289 * Intent with {@link Browser#EXTRA_SHARE_SCREENSHOT}
2290 */
2291 public static final void sharePage(Context c, String title, String url,
2292 Bitmap favicon, Bitmap screenshot) {
2293 Intent send = new Intent(Intent.ACTION_SEND);
2294 send.setType("text/plain");
2295 send.putExtra(Intent.EXTRA_TEXT, url);
Paul Westbrook03e6d392010-02-12 10:33:29 -08002296 send.putExtra(Intent.EXTRA_SUBJECT, title);
Leon Scroggins96afcb12009-12-10 12:35:56 -05002297 send.putExtra(Browser.EXTRA_SHARE_FAVICON, favicon);
2298 send.putExtra(Browser.EXTRA_SHARE_SCREENSHOT, screenshot);
2299 try {
2300 c.startActivity(Intent.createChooser(send, c.getString(
2301 R.string.choosertitle_sharevia)));
2302 } catch(android.content.ActivityNotFoundException ex) {
2303 // if no app handles it, do nothing
2304 }
2305 }
2306
Leon Scroggins89c6d362009-07-15 16:54:37 -04002307 private void updateScreenshot(WebView view) {
2308 // If this is a bookmarked site, add a screenshot to the database.
2309 // FIXME: When should we update? Every time?
2310 // FIXME: Would like to make sure there is actually something to
2311 // draw, but the API for that (WebViewCore.pictureReady()) is not
2312 // currently accessible here.
Ben Murdochaac7aa62009-09-17 16:57:40 +01002313
Patrick Scottcb192b52010-04-14 14:38:55 -04002314 final Bitmap bm = createScreenshot(view);
2315 if (bm == null) {
2316 return;
Leon Scroggins89c6d362009-07-15 16:54:37 -04002317 }
Patrick Scottcb192b52010-04-14 14:38:55 -04002318
2319 final ContentResolver cr = getContentResolver();
2320 final String url = view.getUrl();
2321 final String originalUrl = view.getOriginalUrl();
2322
2323 new AsyncTask<Void, Void, Void>() {
2324 @Override
2325 protected Void doInBackground(Void... unused) {
2326 Cursor c = null;
2327 try {
2328 c = BrowserBookmarksAdapter.queryBookmarksForUrl(
2329 cr, originalUrl, url, true);
2330 if (c != null) {
2331 if (c.moveToFirst()) {
2332 ContentValues values = new ContentValues();
2333 final ByteArrayOutputStream os
2334 = new ByteArrayOutputStream();
2335 bm.compress(Bitmap.CompressFormat.PNG, 100, os);
2336 values.put(Browser.BookmarkColumns.THUMBNAIL,
2337 os.toByteArray());
2338 do {
2339 cr.update(ContentUris.withAppendedId(
2340 Browser.BOOKMARKS_URI, c.getInt(0)),
2341 values, null, null);
2342 } while (c.moveToNext());
2343 }
2344 }
2345 } catch (IllegalStateException e) {
2346 // Ignore
2347 } finally {
2348 if (c != null) c.close();
2349 }
2350 return null;
2351 }
2352 }.execute();
Leon Scroggins89c6d362009-07-15 16:54:37 -04002353 }
2354
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002355 /**
Leon Scrogginsf8551612009-09-24 16:06:02 -04002356 * Values for the size of the thumbnail created when taking a screenshot.
2357 * Lazily initialized. Instead of using these directly, use
2358 * getDesiredThumbnailWidth() or getDesiredThumbnailHeight().
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002359 */
Leon Scrogginsf8551612009-09-24 16:06:02 -04002360 private static int THUMBNAIL_WIDTH = 0;
2361 private static int THUMBNAIL_HEIGHT = 0;
2362
2363 /**
2364 * Return the desired width for thumbnail screenshots, which are stored in
2365 * the database, and used on the bookmarks screen.
2366 * @param context Context for finding out the density of the screen.
2367 * @return int desired width for thumbnail screenshot.
2368 */
2369 /* package */ static int getDesiredThumbnailWidth(Context context) {
2370 if (THUMBNAIL_WIDTH == 0) {
2371 float density = context.getResources().getDisplayMetrics().density;
2372 THUMBNAIL_WIDTH = (int) (90 * density);
2373 THUMBNAIL_HEIGHT = (int) (80 * density);
2374 }
2375 return THUMBNAIL_WIDTH;
2376 }
2377
2378 /**
2379 * Return the desired height for thumbnail screenshots, which are stored in
2380 * the database, and used on the bookmarks screen.
2381 * @param context Context for finding out the density of the screen.
2382 * @return int desired height for thumbnail screenshot.
2383 */
2384 /* package */ static int getDesiredThumbnailHeight(Context context) {
2385 // To ensure that they are both initialized.
2386 getDesiredThumbnailWidth(context);
2387 return THUMBNAIL_HEIGHT;
2388 }
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002389
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002390 private Bitmap createScreenshot(WebView view) {
2391 Picture thumbnail = view.capturePicture();
Leon Scroggins45800572009-09-29 16:38:47 -04002392 if (thumbnail == null) {
2393 return null;
2394 }
Leon Scrogginsf8551612009-09-24 16:06:02 -04002395 Bitmap bm = Bitmap.createBitmap(getDesiredThumbnailWidth(this),
Cary Clarkab168ba2010-04-08 09:11:28 -04002396 getDesiredThumbnailHeight(this), Bitmap.Config.RGB_565);
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002397 Canvas canvas = new Canvas(bm);
2398 // May need to tweak these values to determine what is the
2399 // best scale factor
Ben Murdoch2694e232009-09-29 09:41:11 +01002400 int thumbnailWidth = thumbnail.getWidth();
Ben Murdochae59c3f2009-10-20 18:30:28 +01002401 int thumbnailHeight = thumbnail.getHeight();
2402 float scaleFactorX = 1.0f;
2403 float scaleFactorY = 1.0f;
Ben Murdoch2694e232009-09-29 09:41:11 +01002404 if (thumbnailWidth > 0) {
Ben Murdochae59c3f2009-10-20 18:30:28 +01002405 scaleFactorX = (float) getDesiredThumbnailWidth(this) /
Ben Murdoch2694e232009-09-29 09:41:11 +01002406 (float)thumbnailWidth;
Ben Murdochae59c3f2009-10-20 18:30:28 +01002407 } else {
2408 return null;
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002409 }
Ben Murdochae59c3f2009-10-20 18:30:28 +01002410
2411 if (view.getWidth() > view.getHeight() &&
2412 thumbnailHeight < view.getHeight() && thumbnailHeight > 0) {
2413 // If the device is in landscape and the page is shorter
2414 // than the height of the view, stretch the thumbnail to fill the
2415 // space.
2416 scaleFactorY = (float) getDesiredThumbnailHeight(this) /
2417 (float)thumbnailHeight;
2418 } else {
2419 // In the portrait case, this looks nice.
2420 scaleFactorY = scaleFactorX;
2421 }
2422
2423 canvas.scale(scaleFactorX, scaleFactorY);
2424
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002425 thumbnail.draw(canvas);
2426 return bm;
2427 }
2428
The Android Open Source Project0c908882009-03-03 19:32:16 -08002429 // -------------------------------------------------------------------------
Grace Kloba22ac16e2009-10-07 18:00:23 -07002430 // Helper function for WebViewClient.
The Android Open Source Project0c908882009-03-03 19:32:16 -08002431 //-------------------------------------------------------------------------
2432
2433 // Use in overrideUrlLoading
2434 /* package */ final static String SCHEME_WTAI = "wtai://wp/";
2435 /* package */ final static String SCHEME_WTAI_MC = "wtai://wp/mc;";
2436 /* package */ final static String SCHEME_WTAI_SD = "wtai://wp/sd;";
2437 /* package */ final static String SCHEME_WTAI_AP = "wtai://wp/ap;";
2438
Leon Scroggins92472e82010-02-17 16:32:28 -05002439 // Keep this initial progress in sync with initialProgressValue (* 100)
2440 // in ProgressTracker.cpp
2441 private final static int INITIAL_PROGRESS = 10;
2442
Grace Kloba22ac16e2009-10-07 18:00:23 -07002443 void onPageStarted(WebView view, String url, Bitmap favicon) {
2444 // when BrowserActivity just starts, onPageStarted may be called before
2445 // onResume as it is triggered from onCreate. Call resumeWebViewTimers
2446 // to start the timer. As we won't switch tabs while an activity is in
2447 // pause state, we can ensure calling resume and pause in pair.
2448 if (mActivityInPause) resumeWebViewTimers();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002449
Grace Kloba22ac16e2009-10-07 18:00:23 -07002450 resetLockIcon(url);
2451 setUrlTitle(url, null);
2452 setFavicon(favicon);
Leon Scroggins8cf8f682009-11-04 11:13:50 -08002453 // Show some progress so that the user knows the page is beginning to
2454 // load
Leon Scroggins92472e82010-02-17 16:32:28 -05002455 onProgressChanged(view, INITIAL_PROGRESS);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002456 mDidStopLoad = false;
Grace Kloba22ac16e2009-10-07 18:00:23 -07002457 if (!mIsNetworkUp) createAndShowNetworkDialog();
Patrick Scott15525d42009-09-21 13:39:37 -04002458
Grace Kloba22ac16e2009-10-07 18:00:23 -07002459 if (mSettings.isTracing()) {
2460 String host;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002461 try {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002462 WebAddress uri = new WebAddress(url);
2463 host = uri.mHost;
2464 } catch (android.net.ParseException ex) {
2465 host = "browser";
The Android Open Source Project0c908882009-03-03 19:32:16 -08002466 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002467 host = host.replace('.', '_');
2468 host += ".trace";
2469 mInTrace = true;
2470 Debug.startMethodTracing(host, 20 * 1024 * 1024);
2471 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002472
Grace Kloba22ac16e2009-10-07 18:00:23 -07002473 // Performance probe
2474 if (false) {
2475 mStart = SystemClock.uptimeMillis();
2476 mProcessStart = Process.getElapsedCpuTime();
2477 long[] sysCpu = new long[7];
2478 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2479 sysCpu, null)) {
2480 mUserStart = sysCpu[0] + sysCpu[1];
2481 mSystemStart = sysCpu[2];
2482 mIdleStart = sysCpu[3];
2483 mIrqStart = sysCpu[4] + sysCpu[5] + sysCpu[6];
2484 }
2485 mUiStart = SystemClock.currentThreadTimeMillis();
2486 }
2487 }
2488
2489 void onPageFinished(WebView view, String url) {
2490 // Reset the title and icon in case we stopped a provisional load.
2491 resetTitleAndIcon(view);
2492 // Update the lock icon image only once we are done loading
2493 updateLockIconToLatest();
2494 // pause the WebView timer and release the wake lock if it is finished
2495 // while BrowserActivity is in pause state.
2496 if (mActivityInPause && pauseWebViewTimers()) {
2497 if (mWakeLock.isHeld()) {
2498 mHandler.removeMessages(RELEASE_WAKELOCK);
2499 mWakeLock.release();
2500 }
2501 }
2502
2503 // Performance probe
2504 if (false) {
2505 long[] sysCpu = new long[7];
2506 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2507 sysCpu, null)) {
2508 String uiInfo = "UI thread used "
2509 + (SystemClock.currentThreadTimeMillis() - mUiStart)
2510 + " ms";
2511 if (LOGD_ENABLED) {
2512 Log.d(LOGTAG, uiInfo);
2513 }
2514 //The string that gets written to the log
2515 String performanceString = "It took total "
2516 + (SystemClock.uptimeMillis() - mStart)
2517 + " ms clock time to load the page."
2518 + "\nbrowser process used "
2519 + (Process.getElapsedCpuTime() - mProcessStart)
2520 + " ms, user processes used "
2521 + (sysCpu[0] + sysCpu[1] - mUserStart) * 10
2522 + " ms, kernel used "
2523 + (sysCpu[2] - mSystemStart) * 10
2524 + " ms, idle took " + (sysCpu[3] - mIdleStart) * 10
2525 + " ms and irq took "
2526 + (sysCpu[4] + sysCpu[5] + sysCpu[6] - mIrqStart)
2527 * 10 + " ms, " + uiInfo;
2528 if (LOGD_ENABLED) {
2529 Log.d(LOGTAG, performanceString + "\nWebpage: " + url);
2530 }
2531 if (url != null) {
2532 // strip the url to maintain consistency
2533 String newUrl = new String(url);
2534 if (newUrl.startsWith("http://www.")) {
2535 newUrl = newUrl.substring(11);
2536 } else if (newUrl.startsWith("http://")) {
2537 newUrl = newUrl.substring(7);
2538 } else if (newUrl.startsWith("https://www.")) {
2539 newUrl = newUrl.substring(12);
2540 } else if (newUrl.startsWith("https://")) {
2541 newUrl = newUrl.substring(8);
2542 }
2543 if (LOGD_ENABLED) {
2544 Log.d(LOGTAG, newUrl + " loaded");
2545 }
Grace Kloba5b078b52009-06-24 20:23:41 -07002546 }
2547 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002548 }
Grace Kloba5b078b52009-06-24 20:23:41 -07002549
Grace Kloba22ac16e2009-10-07 18:00:23 -07002550 if (mInTrace) {
2551 mInTrace = false;
2552 Debug.stopMethodTracing();
2553 }
2554 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002555
Grace Kloba22ac16e2009-10-07 18:00:23 -07002556 boolean shouldOverrideUrlLoading(WebView view, String url) {
2557 if (url.startsWith(SCHEME_WTAI)) {
2558 // wtai://wp/mc;number
2559 // number=string(phone-number)
2560 if (url.startsWith(SCHEME_WTAI_MC)) {
2561 Intent intent = new Intent(Intent.ACTION_VIEW,
2562 Uri.parse(WebView.SCHEME_TEL +
2563 url.substring(SCHEME_WTAI_MC.length())));
2564 startActivity(intent);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002565 return true;
2566 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002567 // wtai://wp/sd;dtmf
2568 // dtmf=string(dialstring)
2569 if (url.startsWith(SCHEME_WTAI_SD)) {
2570 // TODO: only send when there is active voice connection
2571 return false;
2572 }
2573 // wtai://wp/ap;number;name
2574 // number=string(phone-number)
2575 // name=string
2576 if (url.startsWith(SCHEME_WTAI_AP)) {
2577 // TODO
2578 return false;
2579 }
2580 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002581
Grace Kloba22ac16e2009-10-07 18:00:23 -07002582 // The "about:" schemes are internal to the browser; don't want these to
2583 // be dispatched to other apps.
2584 if (url.startsWith("about:")) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002585 return false;
2586 }
2587
Grace Kloba22ac16e2009-10-07 18:00:23 -07002588 Intent intent;
2589 // perform generic parsing of the URI to turn it into an Intent.
2590 try {
2591 intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME);
2592 } catch (URISyntaxException ex) {
2593 Log.w("Browser", "Bad URI " + url + ": " + ex.getMessage());
2594 return false;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002595 }
2596
Grace Kloba22ac16e2009-10-07 18:00:23 -07002597 // check whether the intent can be resolved. If not, we will see
2598 // whether we can download it from the Market.
2599 if (getPackageManager().resolveActivity(intent, 0) == null) {
2600 String packagename = intent.getPackage();
2601 if (packagename != null) {
2602 intent = new Intent(Intent.ACTION_VIEW, Uri
2603 .parse("market://search?q=pname:" + packagename));
2604 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2605 startActivity(intent);
2606 return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002607 } else {
2608 return false;
2609 }
2610 }
2611
Grace Kloba22ac16e2009-10-07 18:00:23 -07002612 // sanitize the Intent, ensuring web pages can not bypass browser
2613 // security (only access to BROWSABLE activities).
2614 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2615 intent.setComponent(null);
2616 try {
2617 if (startActivityIfNeeded(intent, -1)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002618 return true;
2619 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002620 } catch (ActivityNotFoundException ex) {
2621 // ignore the error. If no application can handle the URL,
2622 // eg about:blank, assume the browser can handle it.
2623 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002624
Grace Kloba22ac16e2009-10-07 18:00:23 -07002625 if (mMenuIsDown) {
2626 openTab(url);
2627 closeOptionsMenu();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002628 return true;
2629 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002630 return false;
2631 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002632
Grace Kloba22ac16e2009-10-07 18:00:23 -07002633 // -------------------------------------------------------------------------
2634 // Helper function for WebChromeClient
2635 // -------------------------------------------------------------------------
The Android Open Source Project0c908882009-03-03 19:32:16 -08002636
Grace Kloba22ac16e2009-10-07 18:00:23 -07002637 void onProgressChanged(WebView view, int newProgress) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002638 mFakeTitleBar.setProgress(newProgress);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002639
Grace Kloba22ac16e2009-10-07 18:00:23 -07002640 if (newProgress == 100) {
2641 // onProgressChanged() may continue to be called after the main
2642 // frame has finished loading, as any remaining sub frames continue
2643 // to load. We'll only get called once though with newProgress as
2644 // 100 when everything is loaded. (onPageFinished is called once
2645 // when the main frame completes loading regardless of the state of
2646 // any sub frames so calls to onProgressChanges may continue after
2647 // onPageFinished has executed)
2648 if (mInLoad) {
2649 mInLoad = false;
Leon Scrogginsa27ff192009-09-14 12:58:04 -04002650 updateInLoadMenuItems();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002651 // If the options menu is open, leave the title bar
2652 if (!mOptionsMenuOpen || !mIconView) {
2653 hideFakeTitleBar();
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07002654 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002655 }
Leon Scrogginsaa37e7f2010-03-05 11:51:20 -05002656 } else {
2657 if (!mInLoad) {
2658 // onPageFinished may have already been called but a subframe is
2659 // still loading and updating the progress. Reset mInLoad and
2660 // update the menu items.
2661 mInLoad = true;
2662 updateInLoadMenuItems();
2663 }
2664 // When the page first begins to load, the Activity may still be
2665 // paused, in which case showFakeTitleBar will do nothing. Call
2666 // again as the page continues to load so that it will be shown.
2667 // (Calling it will the fake title bar is already showing will also
2668 // do nothing.
Grace Kloba22ac16e2009-10-07 18:00:23 -07002669 if (!mOptionsMenuOpen || mIconView) {
2670 // This page has begun to load, so show the title bar
2671 showFakeTitleBar();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002672 }
2673 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002674 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002675
Grace Kloba22ac16e2009-10-07 18:00:23 -07002676 void onShowCustomView(View view, WebChromeClient.CustomViewCallback callback) {
Derek Sollenberger8ff57db2009-12-08 15:39:55 -05002677 // if a view already exists then immediately terminate the new one
2678 if (mCustomView != null) {
2679 callback.onCustomViewHidden();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002680 return;
Derek Sollenberger8ff57db2009-12-08 15:39:55 -05002681 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002682
2683 // Add the custom view to its container.
2684 mCustomViewContainer.addView(view, COVER_SCREEN_GRAVITY_CENTER);
2685 mCustomView = view;
2686 mCustomViewCallback = callback;
2687 // Save the menu state and set it to empty while the custom
2688 // view is showing.
2689 mOldMenuState = mMenuState;
2690 mMenuState = EMPTY_MENU;
2691 // Hide the content view.
2692 mContentView.setVisibility(View.GONE);
2693 // Finally show the custom view container.
Andrei Popescu163ab742009-10-20 17:58:23 +01002694 setStatusBarVisibility(false);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002695 mCustomViewContainer.setVisibility(View.VISIBLE);
2696 mCustomViewContainer.bringToFront();
2697 }
2698
2699 void onHideCustomView() {
2700 if (mCustomView == null)
2701 return;
2702
2703 // Hide the custom view.
2704 mCustomView.setVisibility(View.GONE);
2705 // Remove the custom view from its container.
2706 mCustomViewContainer.removeView(mCustomView);
2707 mCustomView = null;
2708 // Reset the old menu state.
2709 mMenuState = mOldMenuState;
2710 mOldMenuState = EMPTY_MENU;
2711 mCustomViewContainer.setVisibility(View.GONE);
2712 mCustomViewCallback.onCustomViewHidden();
2713 // Show the content view.
Andrei Popescu163ab742009-10-20 17:58:23 +01002714 setStatusBarVisibility(true);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002715 mContentView.setVisibility(View.VISIBLE);
2716 }
2717
2718 Bitmap getDefaultVideoPoster() {
2719 if (mDefaultVideoPoster == null) {
2720 mDefaultVideoPoster = BitmapFactory.decodeResource(
2721 getResources(), R.drawable.default_video_poster);
Patrick Scott3918d442009-08-04 13:22:29 -04002722 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002723 return mDefaultVideoPoster;
2724 }
Patrick Scott3918d442009-08-04 13:22:29 -04002725
Grace Kloba22ac16e2009-10-07 18:00:23 -07002726 View getVideoLoadingProgressView() {
2727 if (mVideoProgressView == null) {
2728 LayoutInflater inflater = LayoutInflater.from(BrowserActivity.this);
2729 mVideoProgressView = inflater.inflate(
2730 R.layout.video_loading_progress, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002731 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002732 return mVideoProgressView;
2733 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002734
Leon Scroggins8d5fa432009-10-02 15:55:59 -04002735 /*
2736 * The Object used to inform the WebView of the file to upload.
2737 */
2738 private ValueCallback<Uri> mUploadMessage;
2739
Grace Kloba22ac16e2009-10-07 18:00:23 -07002740 void openFileChooser(ValueCallback<Uri> uploadMsg) {
2741 if (mUploadMessage != null) return;
2742 mUploadMessage = uploadMsg;
2743 Intent i = new Intent(Intent.ACTION_GET_CONTENT);
2744 i.addCategory(Intent.CATEGORY_OPENABLE);
2745 i.setType("*/*");
2746 BrowserActivity.this.startActivityForResult(Intent.createChooser(i,
2747 getString(R.string.choose_upload)), FILE_SELECTED);
2748 }
2749
2750 // -------------------------------------------------------------------------
2751 // Implement functions for DownloadListener
2752 // -------------------------------------------------------------------------
2753
The Android Open Source Project0c908882009-03-03 19:32:16 -08002754 /**
2755 * Notify the host application a download should be done, or that
2756 * the data should be streamed if a streaming viewer is available.
2757 * @param url The full url to the content that should be downloaded
2758 * @param contentDisposition Content-disposition http header, if
2759 * present.
2760 * @param mimetype The mimetype of the content reported by the server
2761 * @param contentLength The file size reported by the server
2762 */
2763 public void onDownloadStart(String url, String userAgent,
2764 String contentDisposition, String mimetype, long contentLength) {
2765 // if we're dealing wih A/V content that's not explicitly marked
2766 // for download, check if it's streamable.
2767 if (contentDisposition == null
Patrick Scotte1fb9662009-08-31 14:31:52 -04002768 || !contentDisposition.regionMatches(
2769 true, 0, "attachment", 0, 10)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002770 // query the package manager to see if there's a registered handler
2771 // that matches.
2772 Intent intent = new Intent(Intent.ACTION_VIEW);
2773 intent.setDataAndType(Uri.parse(url), mimetype);
Patrick Scotte1fb9662009-08-31 14:31:52 -04002774 ResolveInfo info = getPackageManager().resolveActivity(intent,
2775 PackageManager.MATCH_DEFAULT_ONLY);
2776 if (info != null) {
2777 ComponentName myName = getComponentName();
2778 // If we resolved to ourselves, we don't want to attempt to
2779 // load the url only to try and download it again.
2780 if (!myName.getPackageName().equals(
2781 info.activityInfo.packageName)
2782 || !myName.getClassName().equals(
2783 info.activityInfo.name)) {
2784 // someone (other than us) knows how to handle this mime
2785 // type with this scheme, don't download.
2786 try {
2787 startActivity(intent);
2788 return;
2789 } catch (ActivityNotFoundException ex) {
2790 if (LOGD_ENABLED) {
2791 Log.d(LOGTAG, "activity not found for " + mimetype
2792 + " over " + Uri.parse(url).getScheme(),
2793 ex);
2794 }
2795 // Best behavior is to fall back to a download in this
2796 // case
The Android Open Source Project0c908882009-03-03 19:32:16 -08002797 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002798 }
2799 }
2800 }
2801 onDownloadStartNoStream(url, userAgent, contentDisposition, mimetype, contentLength);
2802 }
2803
Kristian Monsenfa52d172010-03-25 18:29:21 +00002804 // This is to work around the fact that java.net.URI throws Exceptions
2805 // instead of just encoding URL's properly
2806 // Helper method for onDownloadStartNoStream
2807 private static String encodePath(String path) {
2808 char[] chars = path.toCharArray();
2809
2810 boolean needed = false;
2811 for (char c : chars) {
2812 if (c == '[' || c == ']') {
2813 needed = true;
2814 break;
2815 }
2816 }
2817 if (needed == false) {
2818 return path;
2819 }
2820
2821 StringBuilder sb = new StringBuilder("");
2822 for (char c : chars) {
2823 if (c == '[' || c == ']') {
2824 sb.append('%');
2825 sb.append(Integer.toHexString(c));
2826 } else {
2827 sb.append(c);
2828 }
2829 }
2830
2831 return sb.toString();
2832 }
2833
The Android Open Source Project0c908882009-03-03 19:32:16 -08002834 /**
2835 * Notify the host application a download should be done, even if there
2836 * is a streaming viewer available for thise type.
2837 * @param url The full url to the content that should be downloaded
2838 * @param contentDisposition Content-disposition http header, if
2839 * present.
2840 * @param mimetype The mimetype of the content reported by the server
2841 * @param contentLength The file size reported by the server
2842 */
2843 /*package */ void onDownloadStartNoStream(String url, String userAgent,
2844 String contentDisposition, String mimetype, long contentLength) {
2845
2846 String filename = URLUtil.guessFileName(url,
2847 contentDisposition, mimetype);
2848
2849 // Check to see if we have an SDCard
2850 String status = Environment.getExternalStorageState();
2851 if (!status.equals(Environment.MEDIA_MOUNTED)) {
2852 int title;
2853 String msg;
2854
2855 // Check to see if the SDCard is busy, same as the music app
2856 if (status.equals(Environment.MEDIA_SHARED)) {
2857 msg = getString(R.string.download_sdcard_busy_dlg_msg);
2858 title = R.string.download_sdcard_busy_dlg_title;
2859 } else {
2860 msg = getString(R.string.download_no_sdcard_dlg_msg, filename);
2861 title = R.string.download_no_sdcard_dlg_title;
2862 }
2863
2864 new AlertDialog.Builder(this)
2865 .setTitle(title)
2866 .setIcon(android.R.drawable.ic_dialog_alert)
2867 .setMessage(msg)
2868 .setPositiveButton(R.string.ok, null)
2869 .show();
2870 return;
2871 }
2872
Kristian Monsenfa52d172010-03-25 18:29:21 +00002873 // java.net.URI is a lot stricter than KURL so we have to encode some
2874 // extra characters. Fix for b 2538060 and b 1634719
2875 WebAddress webAddress;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002876 try {
Kristian Monsenfa52d172010-03-25 18:29:21 +00002877 webAddress = new WebAddress(url);
2878 webAddress.mPath = encodePath(webAddress.mPath);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002879 } catch (Exception e) {
Kristian Monsenfa52d172010-03-25 18:29:21 +00002880 // This only happens for very bad urls, we want to chatch the
2881 // exception here
2882 Log.e(LOGTAG, "Exception trying to parse url:" + url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002883 return;
2884 }
2885
2886 // XXX: Have to use the old url since the cookies were stored using the
2887 // old percent-encoded url.
2888 String cookies = CookieManager.getInstance().getCookie(url);
2889
2890 ContentValues values = new ContentValues();
Kristian Monsenfa52d172010-03-25 18:29:21 +00002891 values.put(Downloads.Impl.COLUMN_URI, webAddress.toString());
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08002892 values.put(Downloads.Impl.COLUMN_COOKIE_DATA, cookies);
2893 values.put(Downloads.Impl.COLUMN_USER_AGENT, userAgent);
2894 values.put(Downloads.Impl.COLUMN_NOTIFICATION_PACKAGE,
The Android Open Source Project0c908882009-03-03 19:32:16 -08002895 getPackageName());
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08002896 values.put(Downloads.Impl.COLUMN_NOTIFICATION_CLASS,
Leon Scrogginsa563d092010-04-19 16:53:49 -04002897 OpenDownloadReceiver.class.getCanonicalName());
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08002898 values.put(Downloads.Impl.COLUMN_VISIBILITY,
2899 Downloads.Impl.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
2900 values.put(Downloads.Impl.COLUMN_MIME_TYPE, mimetype);
2901 values.put(Downloads.Impl.COLUMN_FILE_NAME_HINT, filename);
Kristian Monsenfa52d172010-03-25 18:29:21 +00002902 values.put(Downloads.Impl.COLUMN_DESCRIPTION, webAddress.mHost);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002903 if (contentLength > 0) {
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08002904 values.put(Downloads.Impl.COLUMN_TOTAL_BYTES, contentLength);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002905 }
2906 if (mimetype == null) {
2907 // We must have long pressed on a link or image to download it. We
2908 // are not sure of the mimetype in this case, so do a head request
2909 new FetchUrlMimeType(this).execute(values);
2910 } else {
2911 final Uri contentUri =
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08002912 getContentResolver().insert(Downloads.Impl.CONTENT_URI, values);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002913 }
Leon Scroggins9191a7f2010-03-18 14:44:44 -04002914 Toast.makeText(this, R.string.download_pending, Toast.LENGTH_SHORT)
2915 .show();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002916 }
2917
Grace Kloba22ac16e2009-10-07 18:00:23 -07002918 // -------------------------------------------------------------------------
2919
The Android Open Source Project0c908882009-03-03 19:32:16 -08002920 /**
2921 * Resets the lock icon. This method is called when we start a new load and
2922 * know the url to be loaded.
2923 */
2924 private void resetLockIcon(String url) {
2925 // Save the lock-icon state (we revert to it if the load gets cancelled)
Grace Kloba22ac16e2009-10-07 18:00:23 -07002926 mTabControl.getCurrentTab().resetLockIcon(url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002927 updateLockIconImage(LOCK_ICON_UNSECURE);
2928 }
2929
The Android Open Source Project0c908882009-03-03 19:32:16 -08002930 /**
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04002931 * Update the lock icon to correspond to our latest state.
2932 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07002933 private void updateLockIconToLatest() {
2934 updateLockIconImage(mTabControl.getCurrentTab().getLockIconType());
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04002935 }
2936
2937 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08002938 * Updates the lock-icon image in the title-bar.
2939 */
2940 private void updateLockIconImage(int lockIconType) {
2941 Drawable d = null;
2942 if (lockIconType == LOCK_ICON_SECURE) {
2943 d = mSecLockIcon;
2944 } else if (lockIconType == LOCK_ICON_MIXED) {
2945 d = mMixLockIcon;
2946 }
Leon Scroggins68579392009-09-15 15:31:54 -04002947 mTitleBar.setLock(d);
Leon Scrogginsfe87bd32009-10-06 10:10:00 -04002948 mFakeTitleBar.setLock(d);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002949 }
2950
2951 /**
2952 * Displays a page-info dialog.
2953 * @param tab The tab to show info about
2954 * @param fromShowSSLCertificateOnError The flag that indicates whether
2955 * this dialog was opened from the SSL-certificate-on-error dialog or
2956 * not. This is important, since we need to know whether to return to
2957 * the parent dialog or simply dismiss.
2958 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07002959 private void showPageInfo(final Tab tab,
The Android Open Source Project0c908882009-03-03 19:32:16 -08002960 final boolean fromShowSSLCertificateOnError) {
2961 final LayoutInflater factory = LayoutInflater
2962 .from(this);
2963
2964 final View pageInfoView = factory.inflate(R.layout.page_info, null);
2965
2966 final WebView view = tab.getWebView();
2967
2968 String url = null;
2969 String title = null;
2970
2971 if (view == null) {
2972 url = tab.getUrl();
2973 title = tab.getTitle();
2974 } else if (view == mTabControl.getCurrentWebView()) {
2975 // Use the cached title and url if this is the current WebView
2976 url = mUrl;
2977 title = mTitle;
2978 } else {
2979 url = view.getUrl();
2980 title = view.getTitle();
2981 }
2982
2983 if (url == null) {
2984 url = "";
2985 }
2986 if (title == null) {
2987 title = "";
2988 }
2989
2990 ((TextView) pageInfoView.findViewById(R.id.address)).setText(url);
2991 ((TextView) pageInfoView.findViewById(R.id.title)).setText(title);
2992
2993 mPageInfoView = tab;
Leon Scrogginsc7b92f82010-01-11 18:17:31 -05002994 mPageInfoFromShowSSLCertificateOnError = fromShowSSLCertificateOnError;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002995
2996 AlertDialog.Builder alertDialogBuilder =
2997 new AlertDialog.Builder(this)
2998 .setTitle(R.string.page_info).setIcon(android.R.drawable.ic_dialog_info)
2999 .setView(pageInfoView)
3000 .setPositiveButton(
3001 R.string.ok,
3002 new DialogInterface.OnClickListener() {
3003 public void onClick(DialogInterface dialog,
3004 int whichButton) {
3005 mPageInfoDialog = null;
3006 mPageInfoView = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003007
3008 // if we came here from the SSL error dialog
3009 if (fromShowSSLCertificateOnError) {
3010 // go back to the SSL error dialog
3011 showSSLCertificateOnError(
3012 mSSLCertificateOnErrorView,
3013 mSSLCertificateOnErrorHandler,
3014 mSSLCertificateOnErrorError);
3015 }
3016 }
3017 })
3018 .setOnCancelListener(
3019 new DialogInterface.OnCancelListener() {
3020 public void onCancel(DialogInterface dialog) {
3021 mPageInfoDialog = null;
3022 mPageInfoView = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003023
3024 // if we came here from the SSL error dialog
3025 if (fromShowSSLCertificateOnError) {
3026 // go back to the SSL error dialog
3027 showSSLCertificateOnError(
3028 mSSLCertificateOnErrorView,
3029 mSSLCertificateOnErrorHandler,
3030 mSSLCertificateOnErrorError);
3031 }
3032 }
3033 });
3034
3035 // if we have a main top-level page SSL certificate set or a certificate
3036 // error
3037 if (fromShowSSLCertificateOnError ||
3038 (view != null && view.getCertificate() != null)) {
3039 // add a 'View Certificate' button
3040 alertDialogBuilder.setNeutralButton(
3041 R.string.view_certificate,
3042 new DialogInterface.OnClickListener() {
3043 public void onClick(DialogInterface dialog,
3044 int whichButton) {
3045 mPageInfoDialog = null;
3046 mPageInfoView = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003047
3048 // if we came here from the SSL error dialog
3049 if (fromShowSSLCertificateOnError) {
3050 // go back to the SSL error dialog
3051 showSSLCertificateOnError(
3052 mSSLCertificateOnErrorView,
3053 mSSLCertificateOnErrorHandler,
3054 mSSLCertificateOnErrorError);
3055 } else {
3056 // otherwise, display the top-most certificate from
3057 // the chain
3058 if (view.getCertificate() != null) {
3059 showSSLCertificate(tab);
3060 }
3061 }
3062 }
3063 });
3064 }
3065
3066 mPageInfoDialog = alertDialogBuilder.show();
3067 }
3068
3069 /**
3070 * Displays the main top-level page SSL certificate dialog
3071 * (accessible from the Page-Info dialog).
3072 * @param tab The tab to show certificate for.
3073 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003074 private void showSSLCertificate(final Tab tab) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003075 final View certificateView =
3076 inflateCertificateView(tab.getWebView().getCertificate());
3077 if (certificateView == null) {
3078 return;
3079 }
3080
3081 LayoutInflater factory = LayoutInflater.from(this);
3082
3083 final LinearLayout placeholder =
3084 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3085
3086 LinearLayout ll = (LinearLayout) factory.inflate(
3087 R.layout.ssl_success, placeholder);
3088 ((TextView)ll.findViewById(R.id.success))
3089 .setText(R.string.ssl_certificate_is_valid);
3090
3091 mSSLCertificateView = tab;
3092 mSSLCertificateDialog =
3093 new AlertDialog.Builder(this)
3094 .setTitle(R.string.ssl_certificate).setIcon(
3095 R.drawable.ic_dialog_browser_certificate_secure)
3096 .setView(certificateView)
3097 .setPositiveButton(R.string.ok,
3098 new DialogInterface.OnClickListener() {
3099 public void onClick(DialogInterface dialog,
3100 int whichButton) {
3101 mSSLCertificateDialog = null;
3102 mSSLCertificateView = null;
3103
3104 showPageInfo(tab, false);
3105 }
3106 })
3107 .setOnCancelListener(
3108 new DialogInterface.OnCancelListener() {
3109 public void onCancel(DialogInterface dialog) {
3110 mSSLCertificateDialog = null;
3111 mSSLCertificateView = null;
3112
3113 showPageInfo(tab, false);
3114 }
3115 })
3116 .show();
3117 }
3118
3119 /**
3120 * Displays the SSL error certificate dialog.
3121 * @param view The target web-view.
3122 * @param handler The SSL error handler responsible for cancelling the
3123 * connection that resulted in an SSL error or proceeding per user request.
3124 * @param error The SSL error object.
3125 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003126 void showSSLCertificateOnError(
The Android Open Source Project0c908882009-03-03 19:32:16 -08003127 final WebView view, final SslErrorHandler handler, final SslError error) {
3128
3129 final View certificateView =
3130 inflateCertificateView(error.getCertificate());
3131 if (certificateView == null) {
3132 return;
3133 }
3134
3135 LayoutInflater factory = LayoutInflater.from(this);
3136
3137 final LinearLayout placeholder =
3138 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3139
3140 if (error.hasError(SslError.SSL_UNTRUSTED)) {
3141 LinearLayout ll = (LinearLayout)factory
3142 .inflate(R.layout.ssl_warning, placeholder);
3143 ((TextView)ll.findViewById(R.id.warning))
3144 .setText(R.string.ssl_untrusted);
3145 }
3146
3147 if (error.hasError(SslError.SSL_IDMISMATCH)) {
3148 LinearLayout ll = (LinearLayout)factory
3149 .inflate(R.layout.ssl_warning, placeholder);
3150 ((TextView)ll.findViewById(R.id.warning))
3151 .setText(R.string.ssl_mismatch);
3152 }
3153
3154 if (error.hasError(SslError.SSL_EXPIRED)) {
3155 LinearLayout ll = (LinearLayout)factory
3156 .inflate(R.layout.ssl_warning, placeholder);
3157 ((TextView)ll.findViewById(R.id.warning))
3158 .setText(R.string.ssl_expired);
3159 }
3160
3161 if (error.hasError(SslError.SSL_NOTYETVALID)) {
3162 LinearLayout ll = (LinearLayout)factory
3163 .inflate(R.layout.ssl_warning, placeholder);
3164 ((TextView)ll.findViewById(R.id.warning))
3165 .setText(R.string.ssl_not_yet_valid);
3166 }
3167
3168 mSSLCertificateOnErrorHandler = handler;
3169 mSSLCertificateOnErrorView = view;
3170 mSSLCertificateOnErrorError = error;
3171 mSSLCertificateOnErrorDialog =
3172 new AlertDialog.Builder(this)
3173 .setTitle(R.string.ssl_certificate).setIcon(
3174 R.drawable.ic_dialog_browser_certificate_partially_secure)
3175 .setView(certificateView)
3176 .setPositiveButton(R.string.ok,
3177 new DialogInterface.OnClickListener() {
3178 public void onClick(DialogInterface dialog,
3179 int whichButton) {
3180 mSSLCertificateOnErrorDialog = null;
3181 mSSLCertificateOnErrorView = null;
3182 mSSLCertificateOnErrorHandler = null;
3183 mSSLCertificateOnErrorError = null;
3184
Grace Kloba22ac16e2009-10-07 18:00:23 -07003185 view.getWebViewClient().onReceivedSslError(
3186 view, handler, error);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003187 }
3188 })
3189 .setNeutralButton(R.string.page_info_view,
3190 new DialogInterface.OnClickListener() {
3191 public void onClick(DialogInterface dialog,
3192 int whichButton) {
3193 mSSLCertificateOnErrorDialog = null;
3194
3195 // do not clear the dialog state: we will
3196 // need to show the dialog again once the
3197 // user is done exploring the page-info details
3198
3199 showPageInfo(mTabControl.getTabFromView(view),
3200 true);
3201 }
3202 })
3203 .setOnCancelListener(
3204 new DialogInterface.OnCancelListener() {
3205 public void onCancel(DialogInterface dialog) {
3206 mSSLCertificateOnErrorDialog = null;
3207 mSSLCertificateOnErrorView = null;
3208 mSSLCertificateOnErrorHandler = null;
3209 mSSLCertificateOnErrorError = null;
3210
Grace Kloba22ac16e2009-10-07 18:00:23 -07003211 view.getWebViewClient().onReceivedSslError(
3212 view, handler, error);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003213 }
3214 })
3215 .show();
3216 }
3217
3218 /**
3219 * Inflates the SSL certificate view (helper method).
3220 * @param certificate The SSL certificate.
3221 * @return The resultant certificate view with issued-to, issued-by,
3222 * issued-on, expires-on, and possibly other fields set.
3223 * If the input certificate is null, returns null.
3224 */
3225 private View inflateCertificateView(SslCertificate certificate) {
3226 if (certificate == null) {
3227 return null;
3228 }
3229
3230 LayoutInflater factory = LayoutInflater.from(this);
3231
3232 View certificateView = factory.inflate(
3233 R.layout.ssl_certificate, null);
3234
3235 // issued to:
3236 SslCertificate.DName issuedTo = certificate.getIssuedTo();
3237 if (issuedTo != null) {
3238 ((TextView) certificateView.findViewById(R.id.to_common))
3239 .setText(issuedTo.getCName());
3240 ((TextView) certificateView.findViewById(R.id.to_org))
3241 .setText(issuedTo.getOName());
3242 ((TextView) certificateView.findViewById(R.id.to_org_unit))
3243 .setText(issuedTo.getUName());
3244 }
3245
3246 // issued by:
3247 SslCertificate.DName issuedBy = certificate.getIssuedBy();
3248 if (issuedBy != null) {
3249 ((TextView) certificateView.findViewById(R.id.by_common))
3250 .setText(issuedBy.getCName());
3251 ((TextView) certificateView.findViewById(R.id.by_org))
3252 .setText(issuedBy.getOName());
3253 ((TextView) certificateView.findViewById(R.id.by_org_unit))
3254 .setText(issuedBy.getUName());
3255 }
3256
3257 // issued on:
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003258 String issuedOn = formatCertificateDate(
3259 certificate.getValidNotBeforeDate());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003260 ((TextView) certificateView.findViewById(R.id.issued_on))
3261 .setText(issuedOn);
3262
3263 // expires on:
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003264 String expiresOn = formatCertificateDate(
3265 certificate.getValidNotAfterDate());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003266 ((TextView) certificateView.findViewById(R.id.expires_on))
3267 .setText(expiresOn);
3268
3269 return certificateView;
3270 }
3271
3272 /**
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003273 * Formats the certificate date to a properly localized date string.
The Android Open Source Project0c908882009-03-03 19:32:16 -08003274 * @return Properly localized version of the certificate date string and
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003275 * the "" if it fails to localize.
The Android Open Source Project0c908882009-03-03 19:32:16 -08003276 */
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003277 private String formatCertificateDate(Date certificateDate) {
3278 if (certificateDate == null) {
3279 return "";
The Android Open Source Project0c908882009-03-03 19:32:16 -08003280 }
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003281 String formattedDate = DateFormat.getDateFormat(this).format(certificateDate);
3282 if (formattedDate == null) {
3283 return "";
3284 }
3285 return formattedDate;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003286 }
3287
3288 /**
3289 * Displays an http-authentication dialog.
3290 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003291 void showHttpAuthentication(final HttpAuthHandler handler,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003292 final String host, final String realm, final String title,
3293 final String name, final String password, int focusId) {
3294 LayoutInflater factory = LayoutInflater.from(this);
3295 final View v = factory
3296 .inflate(R.layout.http_authentication, null);
3297 if (name != null) {
3298 ((EditText) v.findViewById(R.id.username_edit)).setText(name);
3299 }
3300 if (password != null) {
3301 ((EditText) v.findViewById(R.id.password_edit)).setText(password);
3302 }
3303
3304 String titleText = title;
3305 if (titleText == null) {
3306 titleText = getText(R.string.sign_in_to).toString().replace(
3307 "%s1", host).replace("%s2", realm);
3308 }
3309
3310 mHttpAuthHandler = handler;
3311 AlertDialog dialog = new AlertDialog.Builder(this)
3312 .setTitle(titleText)
3313 .setIcon(android.R.drawable.ic_dialog_alert)
3314 .setView(v)
3315 .setPositiveButton(R.string.action,
3316 new DialogInterface.OnClickListener() {
3317 public void onClick(DialogInterface dialog,
3318 int whichButton) {
3319 String nm = ((EditText) v
3320 .findViewById(R.id.username_edit))
3321 .getText().toString();
3322 String pw = ((EditText) v
3323 .findViewById(R.id.password_edit))
3324 .getText().toString();
3325 BrowserActivity.this.setHttpAuthUsernamePassword
3326 (host, realm, nm, pw);
3327 handler.proceed(nm, pw);
3328 mHttpAuthenticationDialog = null;
3329 mHttpAuthHandler = null;
3330 }})
3331 .setNegativeButton(R.string.cancel,
3332 new DialogInterface.OnClickListener() {
3333 public void onClick(DialogInterface dialog,
3334 int whichButton) {
3335 handler.cancel();
3336 BrowserActivity.this.resetTitleAndRevertLockIcon();
3337 mHttpAuthenticationDialog = null;
3338 mHttpAuthHandler = null;
3339 }})
3340 .setOnCancelListener(new DialogInterface.OnCancelListener() {
3341 public void onCancel(DialogInterface dialog) {
3342 handler.cancel();
3343 BrowserActivity.this.resetTitleAndRevertLockIcon();
3344 mHttpAuthenticationDialog = null;
3345 mHttpAuthHandler = null;
3346 }})
3347 .create();
3348 // Make the IME appear when the dialog is displayed if applicable.
3349 dialog.getWindow().setSoftInputMode(
3350 WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
3351 dialog.show();
3352 if (focusId != 0) {
3353 dialog.findViewById(focusId).requestFocus();
3354 } else {
3355 v.findViewById(R.id.username_edit).requestFocus();
3356 }
3357 mHttpAuthenticationDialog = dialog;
3358 }
3359
3360 public int getProgress() {
3361 WebView w = mTabControl.getCurrentWebView();
3362 if (w != null) {
3363 return w.getProgress();
3364 } else {
3365 return 100;
3366 }
3367 }
3368
3369 /**
3370 * Set HTTP authentication password.
3371 *
3372 * @param host The host for the password
3373 * @param realm The realm for the password
3374 * @param username The username for the password. If it is null, it means
3375 * password can't be saved.
3376 * @param password The password
3377 */
3378 public void setHttpAuthUsernamePassword(String host, String realm,
3379 String username,
3380 String password) {
Steve Block95a53b22010-03-25 17:24:58 +00003381 WebView w = getTopWindow();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003382 if (w != null) {
3383 w.setHttpAuthUsernamePassword(host, realm, username, password);
3384 }
3385 }
3386
3387 /**
3388 * connectivity manager says net has come or gone... inform the user
3389 * @param up true if net has come up, false if net has gone down
3390 */
3391 public void onNetworkToggle(boolean up) {
3392 if (up == mIsNetworkUp) {
3393 return;
3394 } else if (up) {
3395 mIsNetworkUp = true;
3396 if (mAlertDialog != null) {
3397 mAlertDialog.cancel();
3398 mAlertDialog = null;
3399 }
3400 } else {
3401 mIsNetworkUp = false;
Patrick Scotteb6ab2a2009-09-16 10:00:17 -04003402 if (mInLoad) {
3403 createAndShowNetworkDialog();
3404 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003405 }
3406 WebView w = mTabControl.getCurrentWebView();
3407 if (w != null) {
3408 w.setNetworkAvailable(up);
3409 }
3410 }
3411
Grace Kloba22ac16e2009-10-07 18:00:23 -07003412 boolean isNetworkUp() {
3413 return mIsNetworkUp;
3414 }
3415
Patrick Scotteb6ab2a2009-09-16 10:00:17 -04003416 // This method shows the network dialog alerting the user that the net is
3417 // down. It will only show the dialog if mAlertDialog is null.
3418 private void createAndShowNetworkDialog() {
3419 if (mAlertDialog == null) {
3420 mAlertDialog = new AlertDialog.Builder(this)
3421 .setTitle(R.string.loadSuspendedTitle)
3422 .setMessage(R.string.loadSuspended)
3423 .setPositiveButton(R.string.ok, null)
3424 .show();
3425 }
3426 }
3427
The Android Open Source Project0c908882009-03-03 19:32:16 -08003428 @Override
3429 protected void onActivityResult(int requestCode, int resultCode,
3430 Intent intent) {
Grace Klobabb394f32009-11-19 10:26:37 -08003431 if (getTopWindow() == null) return;
3432
The Android Open Source Project0c908882009-03-03 19:32:16 -08003433 switch (requestCode) {
3434 case COMBO_PAGE:
3435 if (resultCode == RESULT_OK && intent != null) {
3436 String data = intent.getAction();
3437 Bundle extras = intent.getExtras();
3438 if (extras != null && extras.getBoolean("new_window", false)) {
Leon Scroggins25d35472009-09-15 11:37:27 -04003439 openTab(data);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003440 } else {
Grace Kloba22ac16e2009-10-07 18:00:23 -07003441 final Tab currentTab =
The Android Open Source Project0c908882009-03-03 19:32:16 -08003442 mTabControl.getCurrentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04003443 dismissSubWindow(currentTab);
3444 if (data != null && data.length() != 0) {
Leon Scroggins92472e82010-02-17 16:32:28 -05003445 loadUrl(getTopWindow(), data);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003446 }
3447 }
3448 }
Leon Scrogginsfde97462010-01-11 13:06:21 -05003449 // Deliberately fall through to PREFERENCES_PAGE, since the
3450 // same extra may be attached to the COMBO_PAGE
3451 case PREFERENCES_PAGE:
3452 if (resultCode == RESULT_OK && intent != null) {
3453 String action = intent.getStringExtra(Intent.EXTRA_TEXT);
3454 if (BrowserSettings.PREF_CLEAR_HISTORY.equals(action)) {
3455 mTabControl.removeParentChildRelationShips();
3456 }
3457 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003458 break;
Leon Scroggins8d5fa432009-10-02 15:55:59 -04003459 // Choose a file from the file picker.
3460 case FILE_SELECTED:
3461 if (null == mUploadMessage) break;
3462 Uri result = intent == null || resultCode != RESULT_OK ? null
3463 : intent.getData();
3464 mUploadMessage.onReceiveValue(result);
3465 mUploadMessage = null;
3466 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003467 default:
3468 break;
3469 }
Leon Scroggins30444232009-09-04 18:36:20 -04003470 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003471 }
3472
3473 /*
3474 * This method is called as a result of the user selecting the options
Leon Scrogginsf08809b2010-01-21 09:27:46 -05003475 * menu to see the download window. It shows the download window on top of
3476 * the current window.
The Android Open Source Project0c908882009-03-03 19:32:16 -08003477 */
Leon Scrogginsf08809b2010-01-21 09:27:46 -05003478 private void viewDownloads(Uri downloadRecord) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003479 Intent intent = new Intent(this,
3480 BrowserDownloadPage.class);
3481 intent.setData(downloadRecord);
Grace Kloba22ac16e2009-10-07 18:00:23 -07003482 startActivityForResult(intent, BrowserActivity.DOWNLOAD_PAGE);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003483
3484 }
3485
Leon Scroggins160a7e72009-08-14 18:28:01 -04003486 /**
3487 * Open the Go page.
3488 * @param startWithHistory If true, open starting on the history tab.
3489 * Otherwise, start with the bookmarks tab.
Leon Scroggins160a7e72009-08-14 18:28:01 -04003490 */
Leon Scroggins30444232009-09-04 18:36:20 -04003491 /* package */ void bookmarksOrHistoryPicker(boolean startWithHistory) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003492 WebView current = mTabControl.getCurrentWebView();
3493 if (current == null) {
3494 return;
3495 }
3496 Intent intent = new Intent(this,
3497 CombinedBookmarkHistoryActivity.class);
3498 String title = current.getTitle();
3499 String url = current.getUrl();
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01003500 Bitmap thumbnail = createScreenshot(current);
3501
The Android Open Source Project0c908882009-03-03 19:32:16 -08003502 // Just in case the user opens bookmarks before a page finishes loading
3503 // so the current history item, and therefore the page, is null.
3504 if (null == url) {
3505 url = mLastEnteredUrl;
3506 // This can happen.
3507 if (null == url) {
3508 url = mSettings.getHomePage();
3509 }
3510 }
3511 // In case the web page has not yet received its associated title.
3512 if (title == null) {
3513 title = url;
3514 }
3515 intent.putExtra("title", title);
3516 intent.putExtra("url", url);
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01003517 intent.putExtra("thumbnail", thumbnail);
Leon Scroggins30444232009-09-04 18:36:20 -04003518 // Disable opening in a new window if we have maxed out the windows
Grace Kloba22ac16e2009-10-07 18:00:23 -07003519 intent.putExtra("disable_new_window", !mTabControl.canCreateNewTab());
Patrick Scott3918d442009-08-04 13:22:29 -04003520 intent.putExtra("touch_icon_url", current.getTouchIconUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003521 if (startWithHistory) {
3522 intent.putExtra(CombinedBookmarkHistoryActivity.STARTING_TAB,
3523 CombinedBookmarkHistoryActivity.HISTORY_TAB);
3524 }
3525 startActivityForResult(intent, COMBO_PAGE);
3526 }
3527
3528 // Called when loading from context menu or LOAD_URL message
Leon Scroggins92472e82010-02-17 16:32:28 -05003529 private void loadUrlFromContext(WebView view, String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003530 // In case the user enters nothing.
3531 if (url != null && url.length() != 0 && view != null) {
3532 url = smartUrlFilter(url);
Grace Kloba22ac16e2009-10-07 18:00:23 -07003533 if (!view.getWebViewClient().shouldOverrideUrlLoading(view, url)) {
Leon Scroggins92472e82010-02-17 16:32:28 -05003534 loadUrl(view, url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003535 }
3536 }
3537 }
3538
Leon Scroggins92472e82010-02-17 16:32:28 -05003539 /**
3540 * Load the URL into the given WebView and update the title bar
3541 * to reflect the new load. Call this instead of WebView.loadUrl
3542 * directly.
3543 * @param view The WebView used to load url.
3544 * @param url The URL to load.
3545 */
3546 private void loadUrl(WebView view, String url) {
3547 updateTitleBarForNewLoad(view, url);
3548 view.loadUrl(url);
3549 }
3550
3551 /**
3552 * Load UrlData into a Tab and update the title bar to reflect the new
3553 * load. Call this instead of UrlData.loadIn directly.
3554 * @param t The Tab used to load.
3555 * @param data The UrlData being loaded.
3556 */
3557 private void loadUrlDataIn(Tab t, UrlData data) {
3558 updateTitleBarForNewLoad(t.getWebView(), data.mUrl);
3559 data.loadIn(t);
3560 }
3561
3562 /**
3563 * If the WebView is the top window, update the title bar to reflect
3564 * loading the new URL. i.e. set its text, clear the favicon (which
3565 * will be set once the page begins loading), and set the progress to
3566 * INITIAL_PROGRESS to show that the page has begun to load. Called
3567 * by loadUrl and loadUrlDataIn.
3568 * @param view The WebView that is starting a load.
3569 * @param url The URL that is being loaded.
3570 */
3571 private void updateTitleBarForNewLoad(WebView view, String url) {
3572 if (view == getTopWindow()) {
3573 setUrlTitle(url, null);
3574 setFavicon(null);
3575 onProgressChanged(view, INITIAL_PROGRESS);
3576 }
3577 }
3578
The Android Open Source Project0c908882009-03-03 19:32:16 -08003579 private String smartUrlFilter(Uri inUri) {
3580 if (inUri != null) {
3581 return smartUrlFilter(inUri.toString());
3582 }
3583 return null;
3584 }
3585
Feng Qianb34f87a2009-03-24 21:27:26 -07003586 protected static final Pattern ACCEPTED_URI_SCHEMA = Pattern.compile(
The Android Open Source Project0c908882009-03-03 19:32:16 -08003587 "(?i)" + // switch on case insensitive matching
3588 "(" + // begin group for schema
3589 "(?:http|https|file):\\/\\/" +
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003590 "|(?:inline|data|about|content|javascript):" +
The Android Open Source Project0c908882009-03-03 19:32:16 -08003591 ")" +
3592 "(.*)" );
3593
3594 /**
3595 * Attempts to determine whether user input is a URL or search
3596 * terms. Anything with a space is passed to search.
3597 *
3598 * Converts to lowercase any mistakenly uppercased schema (i.e.,
3599 * "Http://" converts to "http://"
3600 *
3601 * @return Original or modified URL
3602 *
3603 */
3604 String smartUrlFilter(String url) {
3605
3606 String inUrl = url.trim();
3607 boolean hasSpace = inUrl.indexOf(' ') != -1;
3608
3609 Matcher matcher = ACCEPTED_URI_SCHEMA.matcher(inUrl);
3610 if (matcher.matches()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003611 // force scheme to lowercase
3612 String scheme = matcher.group(1);
3613 String lcScheme = scheme.toLowerCase();
3614 if (!lcScheme.equals(scheme)) {
Mitsuru Oshima123ecfb2009-05-18 19:11:14 -07003615 inUrl = lcScheme + matcher.group(2);
3616 }
3617 if (hasSpace) {
3618 inUrl = inUrl.replace(" ", "%20");
The Android Open Source Project0c908882009-03-03 19:32:16 -08003619 }
3620 return inUrl;
3621 }
3622 if (hasSpace) {
Satish Sampath565505b2009-05-29 15:37:27 +01003623 // FIXME: Is this the correct place to add to searches?
3624 // what if someone else calls this function?
3625 int shortcut = parseUrlShortcut(inUrl);
3626 if (shortcut != SHORTCUT_INVALID) {
3627 Browser.addSearchUrl(mResolver, inUrl);
3628 String query = inUrl.substring(2);
3629 switch (shortcut) {
3630 case SHORTCUT_GOOGLE_SEARCH:
Grace Kloba47fdfdb2009-06-30 11:15:34 -07003631 return URLUtil.composeSearchUrl(query, QuickSearch_G, QUERY_PLACE_HOLDER);
Satish Sampath565505b2009-05-29 15:37:27 +01003632 case SHORTCUT_WIKIPEDIA_SEARCH:
3633 return URLUtil.composeSearchUrl(query, QuickSearch_W, QUERY_PLACE_HOLDER);
3634 case SHORTCUT_DICTIONARY_SEARCH:
3635 return URLUtil.composeSearchUrl(query, QuickSearch_D, QUERY_PLACE_HOLDER);
3636 case SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH:
The Android Open Source Project0c908882009-03-03 19:32:16 -08003637 // FIXME: we need location in this case
Satish Sampath565505b2009-05-29 15:37:27 +01003638 return URLUtil.composeSearchUrl(query, QuickSearch_L, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003639 }
3640 }
3641 } else {
Dan Egnor5ee906c2009-11-18 12:11:49 -08003642 if (Patterns.WEB_URL.matcher(inUrl).matches()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003643 return URLUtil.guessUrl(inUrl);
3644 }
3645 }
3646
3647 Browser.addSearchUrl(mResolver, inUrl);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07003648 return URLUtil.composeSearchUrl(inUrl, QuickSearch_G, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003649 }
3650
Ben Murdochbff2d602009-07-01 20:19:05 +01003651 /* package */ void setShouldShowErrorConsole(boolean flag) {
3652 if (flag == mShouldShowErrorConsole) {
3653 // Nothing to do.
3654 return;
3655 }
3656
3657 mShouldShowErrorConsole = flag;
3658
Grace Kloba22ac16e2009-10-07 18:00:23 -07003659 ErrorConsoleView errorConsole = mTabControl.getCurrentTab()
3660 .getErrorConsole(true);
Ben Murdochbff2d602009-07-01 20:19:05 +01003661
3662 if (flag) {
3663 // Setting the show state of the console will cause it's the layout to be inflated.
3664 if (errorConsole.numberOfErrors() > 0) {
3665 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
3666 } else {
3667 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
3668 }
3669
3670 // Now we can add it to the main view.
3671 mErrorConsoleContainer.addView(errorConsole,
Romain Guy15b8ec62010-01-08 15:06:43 -08003672 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
Ben Murdochbff2d602009-07-01 20:19:05 +01003673 ViewGroup.LayoutParams.WRAP_CONTENT));
3674 } else {
3675 mErrorConsoleContainer.removeView(errorConsole);
3676 }
3677
3678 }
3679
Grace Kloba22ac16e2009-10-07 18:00:23 -07003680 boolean shouldShowErrorConsole() {
3681 return mShouldShowErrorConsole;
3682 }
3683
Andrei Popescu163ab742009-10-20 17:58:23 +01003684 private void setStatusBarVisibility(boolean visible) {
3685 int flag = visible ? 0 : WindowManager.LayoutParams.FLAG_FULLSCREEN;
3686 getWindow().setFlags(flag, WindowManager.LayoutParams.FLAG_FULLSCREEN);
3687 }
3688
Andrei Popescu56199cc2010-01-12 22:39:16 +00003689
3690 private void sendNetworkType(String type, String subtype) {
3691 WebView w = mTabControl.getCurrentWebView();
3692 if (w != null) {
3693 w.setNetworkType(type, subtype);
3694 }
3695 }
3696
Andrei Popescu30995e72010-02-09 16:59:58 +00003697 private void packageChanged(String packageName, boolean wasAdded) {
3698 WebView w = mTabControl.getCurrentWebView();
3699 if (w == null) {
3700 return;
3701 }
3702
3703 if (wasAdded) {
3704 w.addPackageName(packageName);
3705 } else {
3706 w.removePackageName(packageName);
3707 }
3708 }
3709
3710 private void addPackageNames(Set<String> packageNames) {
3711 WebView w = mTabControl.getCurrentWebView();
3712 if (w == null) {
3713 return;
3714 }
3715
3716 w.addPackageNames(packageNames);
3717 }
3718
3719 private void getInstalledPackages() {
3720 AsyncTask<Void, Void, Set<String> > task =
3721 new AsyncTask<Void, Void, Set<String> >() {
3722 protected Set<String> doInBackground(Void... unused) {
3723 Set<String> installedPackages = new HashSet<String>();
3724 PackageManager pm = BrowserActivity.this.getPackageManager();
3725 if (pm != null) {
3726 List<PackageInfo> packages = pm.getInstalledPackages(0);
3727 for (PackageInfo p : packages) {
3728 if (BrowserActivity.this.sGoogleApps.contains(p.packageName)) {
3729 installedPackages.add(p.packageName);
3730 }
3731 }
3732 }
3733
3734 return installedPackages;
3735 }
3736
3737 // Executes on the UI thread
3738 protected void onPostExecute(Set<String> installedPackages) {
3739 addPackageNames(installedPackages);
3740 }
3741 };
3742 task.execute();
3743 }
3744
Grace Klobaeb6eef42009-09-15 17:56:32 -07003745 final static int LOCK_ICON_UNSECURE = 0;
3746 final static int LOCK_ICON_SECURE = 1;
3747 final static int LOCK_ICON_MIXED = 2;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003748
The Android Open Source Project0c908882009-03-03 19:32:16 -08003749 private BrowserSettings mSettings;
3750 private TabControl mTabControl;
3751 private ContentResolver mResolver;
3752 private FrameLayout mContentView;
Andrei Popescuadc008d2009-06-26 14:11:30 +01003753 private View mCustomView;
3754 private FrameLayout mCustomViewContainer;
Andrei Popescuc9b55562009-07-07 10:51:15 +01003755 private WebChromeClient.CustomViewCallback mCustomViewCallback;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003756
3757 // FIXME, temp address onPrepareMenu performance problem. When we move everything out of
3758 // view, we should rewrite this.
3759 private int mCurrentMenuState = 0;
3760 private int mMenuState = R.id.MAIN_MENU;
Andrei Popescuadc008d2009-06-26 14:11:30 +01003761 private int mOldMenuState = EMPTY_MENU;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003762 private static final int EMPTY_MENU = -1;
3763 private Menu mMenu;
3764
3765 private FindDialog mFindDialog;
3766 // Used to prevent chording to result in firing two shortcuts immediately
3767 // one after another. Fixes bug 1211714.
3768 boolean mCanChord;
3769
3770 private boolean mInLoad;
3771 private boolean mIsNetworkUp;
Ben Murdochb7cc8b42009-09-28 10:59:09 +01003772 private boolean mDidStopLoad;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003773
Cary Clark1f10cbf2010-03-22 11:45:23 -04003774 /* package */ boolean mActivityInPause = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003775
3776 private boolean mMenuIsDown;
3777
The Android Open Source Project0c908882009-03-03 19:32:16 -08003778 private static boolean mInTrace;
3779
3780 // Performance probe
3781 private static final int[] SYSTEM_CPU_FORMAT = new int[] {
3782 Process.PROC_SPACE_TERM | Process.PROC_COMBINE,
3783 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 1: user time
3784 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 2: nice time
3785 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 3: sys time
3786 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 4: idle time
3787 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 5: iowait time
3788 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 6: irq time
3789 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG // 7: softirq time
3790 };
3791
3792 private long mStart;
3793 private long mProcessStart;
3794 private long mUserStart;
3795 private long mSystemStart;
3796 private long mIdleStart;
3797 private long mIrqStart;
3798
3799 private long mUiStart;
3800
3801 private Drawable mMixLockIcon;
3802 private Drawable mSecLockIcon;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003803
3804 /* hold a ref so we can auto-cancel if necessary */
3805 private AlertDialog mAlertDialog;
3806
The Android Open Source Project0c908882009-03-03 19:32:16 -08003807 // The up-to-date URL and title (these can be different from those stored
3808 // in WebView, since it takes some time for the information in WebView to
3809 // get updated)
3810 private String mUrl;
3811 private String mTitle;
3812
3813 // As PageInfo has different style for landscape / portrait, we have
3814 // to re-open it when configuration changed
3815 private AlertDialog mPageInfoDialog;
Grace Kloba22ac16e2009-10-07 18:00:23 -07003816 private Tab mPageInfoView;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003817 // If the Page-Info dialog is launched from the SSL-certificate-on-error
3818 // dialog, we should not just dismiss it, but should get back to the
3819 // SSL-certificate-on-error dialog. This flag is used to store this state
Leon Scrogginsc7b92f82010-01-11 18:17:31 -05003820 private boolean mPageInfoFromShowSSLCertificateOnError;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003821
3822 // as SSLCertificateOnError has different style for landscape / portrait,
3823 // we have to re-open it when configuration changed
3824 private AlertDialog mSSLCertificateOnErrorDialog;
3825 private WebView mSSLCertificateOnErrorView;
3826 private SslErrorHandler mSSLCertificateOnErrorHandler;
3827 private SslError mSSLCertificateOnErrorError;
3828
3829 // as SSLCertificate has different style for landscape / portrait, we
3830 // have to re-open it when configuration changed
3831 private AlertDialog mSSLCertificateDialog;
Grace Kloba22ac16e2009-10-07 18:00:23 -07003832 private Tab mSSLCertificateView;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003833
3834 // as HttpAuthentication has different style for landscape / portrait, we
3835 // have to re-open it when configuration changed
3836 private AlertDialog mHttpAuthenticationDialog;
3837 private HttpAuthHandler mHttpAuthHandler;
3838
3839 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_PARAMS =
3840 new FrameLayout.LayoutParams(
Romain Guy15b8ec62010-01-08 15:06:43 -08003841 ViewGroup.LayoutParams.MATCH_PARENT,
3842 ViewGroup.LayoutParams.MATCH_PARENT);
Andrei Popescuadc008d2009-06-26 14:11:30 +01003843 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_GRAVITY_CENTER =
3844 new FrameLayout.LayoutParams(
Romain Guy15b8ec62010-01-08 15:06:43 -08003845 ViewGroup.LayoutParams.MATCH_PARENT,
3846 ViewGroup.LayoutParams.MATCH_PARENT,
Andrei Popescuadc008d2009-06-26 14:11:30 +01003847 Gravity.CENTER);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07003848 // Google search
3849 final static String QuickSearch_G = "http://www.google.com/m?q=%s";
The Android Open Source Project0c908882009-03-03 19:32:16 -08003850 // Wikipedia search
3851 final static String QuickSearch_W = "http://en.wikipedia.org/w/index.php?search=%s&go=Go";
3852 // Dictionary search
3853 final static String QuickSearch_D = "http://dictionary.reference.com/search?q=%s";
3854 // Google Mobile Local search
3855 final static String QuickSearch_L = "http://www.google.com/m/search?site=local&q=%s&near=mountain+view";
3856
3857 final static String QUERY_PLACE_HOLDER = "%s";
3858
3859 // "source" parameter for Google search through search key
3860 final static String GOOGLE_SEARCH_SOURCE_SEARCHKEY = "browser-key";
3861 // "source" parameter for Google search through goto menu
3862 final static String GOOGLE_SEARCH_SOURCE_GOTO = "browser-goto";
3863 // "source" parameter for Google search through simplily type
3864 final static String GOOGLE_SEARCH_SOURCE_TYPE = "browser-type";
3865 // "source" parameter for Google search suggested by the browser
3866 final static String GOOGLE_SEARCH_SOURCE_SUGGEST = "browser-suggest";
3867 // "source" parameter for Google search from unknown source
3868 final static String GOOGLE_SEARCH_SOURCE_UNKNOWN = "unknown";
3869
3870 private final static String LOGTAG = "browser";
3871
The Android Open Source Project0c908882009-03-03 19:32:16 -08003872 private String mLastEnteredUrl;
3873
3874 private PowerManager.WakeLock mWakeLock;
3875 private final static int WAKELOCK_TIMEOUT = 5 * 60 * 1000; // 5 minutes
3876
3877 private Toast mStopToast;
3878
Leon Scroggins68579392009-09-15 15:31:54 -04003879 private TitleBar mTitleBar;
Leon Scroggins81db3662009-06-04 17:45:11 -04003880
Ben Murdochbff2d602009-07-01 20:19:05 +01003881 private LinearLayout mErrorConsoleContainer = null;
3882 private boolean mShouldShowErrorConsole = false;
3883
The Android Open Source Project0c908882009-03-03 19:32:16 -08003884 // As the ids are dynamically created, we can't guarantee that they will
3885 // be in sequence, so this static array maps ids to a window number.
3886 final static private int[] WINDOW_SHORTCUT_ID_ARRAY =
3887 { R.id.window_one_menu_id, R.id.window_two_menu_id, R.id.window_three_menu_id,
3888 R.id.window_four_menu_id, R.id.window_five_menu_id, R.id.window_six_menu_id,
3889 R.id.window_seven_menu_id, R.id.window_eight_menu_id };
3890
3891 // monitor platform changes
3892 private IntentFilter mNetworkStateChangedFilter;
3893 private BroadcastReceiver mNetworkStateIntentReceiver;
3894
Grace Klobab4da0ad2009-05-14 14:45:40 -07003895 private BroadcastReceiver mPackageInstallationReceiver;
3896
Bjorn Bringerta7611812010-03-24 11:12:02 +00003897 private SystemAllowGeolocationOrigins mSystemAllowGeolocationOrigins;
3898
The Android Open Source Project0c908882009-03-03 19:32:16 -08003899 // activity requestCode
Nicolas Roard78a98e42009-05-11 13:34:17 +01003900 final static int COMBO_PAGE = 1;
3901 final static int DOWNLOAD_PAGE = 2;
3902 final static int PREFERENCES_PAGE = 3;
Leon Scroggins8d5fa432009-10-02 15:55:59 -04003903 final static int FILE_SELECTED = 4;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003904
Andrei Popescu540035d2009-09-18 18:59:20 +01003905 // the default <video> poster
3906 private Bitmap mDefaultVideoPoster;
3907 // the video progress view
3908 private View mVideoProgressView;
3909
Andrei Popescu30995e72010-02-09 16:59:58 +00003910 // The Google packages we monitor for the navigator.isApplicationInstalled()
3911 // API. Add as needed.
3912 private static Set<String> sGoogleApps;
3913 static {
3914 sGoogleApps = new HashSet<String>();
3915 sGoogleApps.add("com.google.android.youtube");
3916 }
3917
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003918 /**
3919 * A UrlData class to abstract how the content will be set to WebView.
3920 * This base class uses loadUrl to show the content.
3921 */
Leon Scroggins6eac63e2010-03-15 18:19:14 -04003922 /* package */ static class UrlData {
Grace Kloba068e48b2010-01-26 18:11:27 -08003923 final String mUrl;
3924 final Map<String, String> mHeaders;
Leon Scroggins58d56c62010-01-28 15:12:40 -05003925 final Intent mVoiceIntent;
Grace Kloba60e095c2009-06-16 11:50:55 -07003926
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003927 UrlData(String url) {
3928 this.mUrl = url;
Grace Kloba068e48b2010-01-26 18:11:27 -08003929 this.mHeaders = null;
Leon Scroggins58d56c62010-01-28 15:12:40 -05003930 this.mVoiceIntent = null;
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003931 }
Grace Kloba60e095c2009-06-16 11:50:55 -07003932
Leon Scroggins58d56c62010-01-28 15:12:40 -05003933 UrlData(String url, Map<String, String> headers, Intent intent) {
Grace Kloba068e48b2010-01-26 18:11:27 -08003934 this.mUrl = url;
3935 this.mHeaders = headers;
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -05003936 if (RecognizerResultsIntent.ACTION_VOICE_SEARCH_RESULTS
3937 .equals(intent.getAction())) {
Leon Scroggins58d56c62010-01-28 15:12:40 -05003938 this.mVoiceIntent = intent;
3939 } else {
3940 this.mVoiceIntent = null;
3941 }
Grace Kloba60e095c2009-06-16 11:50:55 -07003942 }
3943
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003944 boolean isEmpty() {
Leon Scroggins58d56c62010-01-28 15:12:40 -05003945 return mVoiceIntent == null && (mUrl == null || mUrl.length() == 0);
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003946 }
3947
Leon Scroggins92472e82010-02-17 16:32:28 -05003948 /**
3949 * Load this UrlData into the given Tab. Use loadUrlDataIn to update
3950 * the title bar as well.
3951 */
Leon Scroggins58d56c62010-01-28 15:12:40 -05003952 public void loadIn(Tab t) {
3953 if (mVoiceIntent != null) {
3954 t.activateVoiceSearchMode(mVoiceIntent);
3955 } else {
3956 t.getWebView().loadUrl(mUrl, mHeaders);
3957 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003958 }
3959 };
3960
Leon Scroggins1f005d32009-08-10 17:36:42 -04003961 /* package */ static final UrlData EMPTY_URL_DATA = new UrlData(null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003962}