blob: 72ed2ecf76a97e3568a6d06e9e397b5598ad6690 [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
Leon Scroggins IIIcc14c8c2010-09-27 12:45:34 -0400194 // Keep a settings instance handy.
195 mSettings = BrowserSettings.getInstance();
196
Grace Kloba0923d692009-09-23 21:37:25 -0700197 // If this was a web search request, pass it on to the default web
198 // search provider and finish this activity.
199 if (handleWebSearchIntent(getIntent())) {
200 finish();
201 return;
202 }
203
The Android Open Source Project0c908882009-03-03 19:32:16 -0800204 mSecLockIcon = Resources.getSystem().getDrawable(
205 android.R.drawable.ic_secure);
206 mMixLockIcon = Resources.getSystem().getDrawable(
207 android.R.drawable.ic_partial_secure);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800208
Leon Scroggins81db3662009-06-04 17:45:11 -0400209 FrameLayout frameLayout = (FrameLayout) getWindow().getDecorView()
210 .findViewById(com.android.internal.R.id.content);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400211 mBrowserFrameLayout = (FrameLayout) LayoutInflater.from(this)
212 .inflate(R.layout.custom_screen, null);
213 mContentView = (FrameLayout) mBrowserFrameLayout.findViewById(
214 R.id.main_content);
215 mErrorConsoleContainer = (LinearLayout) mBrowserFrameLayout
216 .findViewById(R.id.error_console);
217 mCustomViewContainer = (FrameLayout) mBrowserFrameLayout
218 .findViewById(R.id.fullscreen_custom_content);
219 frameLayout.addView(mBrowserFrameLayout, COVER_SCREEN_PARAMS);
Leon Scroggins68579392009-09-15 15:31:54 -0400220 mTitleBar = new TitleBar(this);
Grace Kloba1542f742010-03-17 21:11:15 -0700221 // mTitleBar will be always shown in the fully loaded mode
222 mTitleBar.setProgress(100);
Leon Scrogginsfe87bd32009-10-06 10:10:00 -0400223 mFakeTitleBar = new TitleBar(this);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800224
225 // Create the tab control and our initial tab
226 mTabControl = new TabControl(this);
227
228 // Open the icon database and retain all the bookmark urls for favicons
229 retainIconsOnStartup();
230
The Android Open Source Project0c908882009-03-03 19:32:16 -0800231 mSettings.setTabControl(mTabControl);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800232
233 PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
234 mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Browser");
235
Patrick Scott6adacc92010-03-05 08:24:51 -0500236 // Find out if the network is currently up.
237 ConnectivityManager cm = (ConnectivityManager) getSystemService(
238 Context.CONNECTIVITY_SERVICE);
239 NetworkInfo info = cm.getActiveNetworkInfo();
240 if (info != null) {
241 mIsNetworkUp = info.isAvailable();
242 }
243
Grace Klobaa34f6862009-07-31 16:28:17 -0700244 /* enables registration for changes in network status from
245 http stack */
246 mNetworkStateChangedFilter = new IntentFilter();
247 mNetworkStateChangedFilter.addAction(
248 ConnectivityManager.CONNECTIVITY_ACTION);
249 mNetworkStateIntentReceiver = new BroadcastReceiver() {
250 @Override
251 public void onReceive(Context context, Intent intent) {
252 if (intent.getAction().equals(
253 ConnectivityManager.CONNECTIVITY_ACTION)) {
Andrei Popescue4c98462010-02-19 15:44:13 +0000254
255 NetworkInfo info = intent.getParcelableExtra(
256 ConnectivityManager.EXTRA_NETWORK_INFO);
257 String typeName = info.getTypeName();
258 String subtypeName = info.getSubtypeName();
259 sendNetworkType(typeName.toLowerCase(),
260 (subtypeName != null ? subtypeName.toLowerCase() : ""));
261
262 onNetworkToggle(info.isAvailable());
Grace Klobaa34f6862009-07-31 16:28:17 -0700263 }
264 }
265 };
266
Grace Kloba615c6c92009-08-03 10:22:44 -0700267 IntentFilter filter = new IntentFilter(Intent.ACTION_PACKAGE_ADDED);
268 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
269 filter.addDataScheme("package");
270 mPackageInstallationReceiver = new BroadcastReceiver() {
271 @Override
272 public void onReceive(Context context, Intent intent) {
273 final String action = intent.getAction();
274 final String packageName = intent.getData()
275 .getSchemeSpecificPart();
276 final boolean replacing = intent.getBooleanExtra(
277 Intent.EXTRA_REPLACING, false);
278 if (Intent.ACTION_PACKAGE_REMOVED.equals(action) && replacing) {
279 // if it is replacing, refreshPlugins() when adding
280 return;
281 }
Andrei Popescu30995e72010-02-09 16:59:58 +0000282
283 if (sGoogleApps.contains(packageName)) {
284 BrowserActivity.this.packageChanged(packageName,
285 Intent.ACTION_PACKAGE_ADDED.equals(action));
286 }
287
Grace Kloba615c6c92009-08-03 10:22:44 -0700288 PackageManager pm = BrowserActivity.this.getPackageManager();
289 PackageInfo pkgInfo = null;
290 try {
291 pkgInfo = pm.getPackageInfo(packageName,
292 PackageManager.GET_PERMISSIONS);
293 } catch (PackageManager.NameNotFoundException e) {
294 return;
295 }
296 if (pkgInfo != null) {
297 String permissions[] = pkgInfo.requestedPermissions;
298 if (permissions == null) {
299 return;
300 }
301 boolean permissionOk = false;
302 for (String permit : permissions) {
303 if (PluginManager.PLUGIN_PERMISSION.equals(permit)) {
304 permissionOk = true;
305 break;
306 }
307 }
308 if (permissionOk) {
309 PluginManager.getInstance(BrowserActivity.this)
310 .refreshPlugins(
311 Intent.ACTION_PACKAGE_ADDED
312 .equals(action));
313 }
314 }
315 }
316 };
317 registerReceiver(mPackageInstallationReceiver, filter);
318
The Android Open Source Project0c908882009-03-03 19:32:16 -0800319 if (!mTabControl.restoreState(icicle)) {
320 // clear up the thumbnail directory if we can't restore the state as
321 // none of the files in the directory are referenced any more.
322 new ClearThumbnails().execute(
323 mTabControl.getThumbnailDir().listFiles());
Grace Klobaaab3f092009-07-30 12:29:51 -0700324 // there is no quit on Android. But if we can't restore the state,
325 // we can treat it as a new Browser, remove the old session cookies.
326 CookieManager.getInstance().removeSessionCookie();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800327 final Intent intent = getIntent();
328 final Bundle extra = intent.getExtras();
329 // Create an initial tab.
330 // If the intent is ACTION_VIEW and data is not null, the Browser is
331 // invoked to view the content by another application. In this case,
332 // the tab will be close when exit.
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700333 UrlData urlData = getUrlDataFromIntent(intent);
334
Leon Scroggins58d56c62010-01-28 15:12:40 -0500335 String action = intent.getAction();
Grace Kloba22ac16e2009-10-07 18:00:23 -0700336 final Tab t = mTabControl.createNewTab(
Leon Scroggins58d56c62010-01-28 15:12:40 -0500337 (Intent.ACTION_VIEW.equals(action) &&
338 intent.getData() != null)
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -0500339 || RecognizerResultsIntent.ACTION_VOICE_SEARCH_RESULTS
340 .equals(action),
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700341 intent.getStringExtra(Browser.EXTRA_APPLICATION_ID), urlData.mUrl);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800342 mTabControl.setCurrentTab(t);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800343 attachTabToContentView(t);
344 WebView webView = t.getWebView();
345 if (extra != null) {
346 int scale = extra.getInt(Browser.INITIAL_ZOOM_LEVEL, 0);
347 if (scale > 0 && scale <= 1000) {
348 webView.setInitialScale(scale);
349 }
350 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800351
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700352 if (urlData.isEmpty()) {
Shimeng (Simon) Wang98d5fce2010-03-16 13:23:39 -0700353 loadUrl(webView, mSettings.getHomePage());
The Android Open Source Project0c908882009-03-03 19:32:16 -0800354 } else {
Patrick Scott9d53da02010-02-19 10:19:01 -0500355 loadUrlDataIn(t, urlData);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800356 }
357 } else {
358 // TabControl.restoreState() will create a new tab even if
Leon Scroggins1f005d32009-08-10 17:36:42 -0400359 // restoring the state fails.
The Android Open Source Project0c908882009-03-03 19:32:16 -0800360 attachTabToContentView(mTabControl.getCurrentTab());
361 }
Grace Kloba615c6c92009-08-03 10:22:44 -0700362
Cary Clark23cbeb72010-07-01 12:36:56 -0400363 // Delete old thumbnails to save space
364 File dir = mTabControl.getThumbnailDir();
365 if (dir.exists()) {
366 for (String child : dir.list()) {
367 File f = new File(dir, child);
368 f.delete();
369 }
370 }
371
Feng Qianb3c02da2009-06-29 15:58:08 -0700372 // Read JavaScript flags if it exists.
373 String jsFlags = mSettings.getJsFlags();
374 if (jsFlags.trim().length() != 0) {
375 mTabControl.getCurrentWebView().setJsFlags(jsFlags);
376 }
Andrei Popescu30995e72010-02-09 16:59:58 +0000377 // Work out which packages are installed on the system.
378 getInstalledPackages();
Bjorn Bringerta7611812010-03-24 11:12:02 +0000379
380 // Start watching the default geolocation permissions
381 mSystemAllowGeolocationOrigins
382 = new SystemAllowGeolocationOrigins(getApplicationContext());
383 mSystemAllowGeolocationOrigins.start();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800384 }
385
Leon Scroggins58d56c62010-01-28 15:12:40 -0500386 /**
387 * Feed the previously stored results strings to the BrowserProvider so that
388 * the SearchDialog will show them instead of the standard searches.
389 * @param result String to show on the editable line of the SearchDialog.
390 */
391 /* package */ void showVoiceSearchResults(String result) {
392 ContentProviderClient client = mResolver.acquireContentProviderClient(
393 Browser.BOOKMARKS_URI);
394 ContentProvider prov = client.getLocalContentProvider();
395 BrowserProvider bp = (BrowserProvider) prov;
396 bp.setQueryResults(mTabControl.getCurrentTab().getVoiceSearchResults());
397 client.release();
398
Leon Scrogginsfbb3f152010-03-09 17:26:56 -0500399 Bundle bundle = createGoogleSearchSourceBundle(
400 GOOGLE_SEARCH_SOURCE_SEARCHKEY);
401 bundle.putBoolean(SearchManager.CONTEXT_IS_VOICE, true);
402 startSearch(result, false, bundle, false);
Leon Scroggins58d56c62010-01-28 15:12:40 -0500403 }
404
The Android Open Source Project0c908882009-03-03 19:32:16 -0800405 @Override
406 protected void onNewIntent(Intent intent) {
Grace Kloba22ac16e2009-10-07 18:00:23 -0700407 Tab current = mTabControl.getCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800408 // When a tab is closed on exit, the current tab index is set to -1.
409 // Reset before proceed as Browser requires the current tab to be set.
410 if (current == null) {
411 // Try to reset the tab in case the index was incorrect.
412 current = mTabControl.getTab(0);
413 if (current == null) {
414 // No tabs at all so just ignore this intent.
415 return;
416 }
417 mTabControl.setCurrentTab(current);
418 attachTabToContentView(current);
419 resetTitleAndIcon(current.getWebView());
420 }
421 final String action = intent.getAction();
422 final int flags = intent.getFlags();
423 if (Intent.ACTION_MAIN.equals(action) ||
424 (flags & Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY) != 0) {
425 // just resume the browser
426 return;
427 }
Leon Scrogginsb8a844d2010-03-18 15:06:15 -0400428 // In case the SearchDialog is open.
429 ((SearchManager) getSystemService(Context.SEARCH_SERVICE))
430 .stopSearch();
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -0500431 boolean activateVoiceSearch = RecognizerResultsIntent
432 .ACTION_VOICE_SEARCH_RESULTS.equals(action);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800433 if (Intent.ACTION_VIEW.equals(action)
434 || Intent.ACTION_SEARCH.equals(action)
435 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
Leon Scroggins58d56c62010-01-28 15:12:40 -0500436 || Intent.ACTION_WEB_SEARCH.equals(action)
437 || activateVoiceSearch) {
Leon Scroggins3b18ce32010-02-08 17:35:59 -0500438 if (current.isInVoiceSearchMode()) {
439 String title = current.getVoiceDisplayTitle();
440 if (title != null && title.equals(intent.getStringExtra(
441 SearchManager.QUERY))) {
442 // The user submitted the same search as the last voice
443 // search, so do nothing.
444 return;
445 }
Leon Scroggins1fe13a52010-02-09 15:31:26 -0500446 if (Intent.ACTION_SEARCH.equals(action)
447 && current.voiceSearchSourceIsGoogle()) {
448 Intent logIntent = new Intent(
449 LoggingEvents.ACTION_LOG_EVENT);
450 logIntent.putExtra(LoggingEvents.EXTRA_EVENT,
451 LoggingEvents.VoiceSearch.QUERY_UPDATED);
452 logIntent.putExtra(
453 LoggingEvents.VoiceSearch.EXTRA_QUERY_UPDATED_VALUE,
454 intent.getDataString());
455 sendBroadcast(logIntent);
456 // Note, onPageStarted will revert the voice title bar
457 // When http://b/issue?id=2379215 is fixed, we should update
458 // the title bar here.
459 }
Leon Scroggins3b18ce32010-02-08 17:35:59 -0500460 }
Satish Sampath565505b2009-05-29 15:37:27 +0100461 // If this was a search request (e.g. search query directly typed into the address bar),
462 // pass it on to the default web search provider.
463 if (handleWebSearchIntent(intent)) {
464 return;
465 }
466
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700467 UrlData urlData = getUrlDataFromIntent(intent);
468 if (urlData.isEmpty()) {
469 urlData = new UrlData(mSettings.getHomePage());
The Android Open Source Project0c908882009-03-03 19:32:16 -0800470 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700471
Grace Klobacc634032009-07-28 15:58:19 -0700472 final String appId = intent
473 .getStringExtra(Browser.EXTRA_APPLICATION_ID);
Leon Scroggins47208682010-04-07 17:59:48 -0400474 if ((Intent.ACTION_VIEW.equals(action)
475 // If a voice search has no appId, it means that it came
476 // from the browser. In that case, reuse the current tab.
477 || (activateVoiceSearch && appId != null))
Grace Klobacc634032009-07-28 15:58:19 -0700478 && !getPackageName().equals(appId)
479 && (flags & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0) {
Grace Kloba22ac16e2009-10-07 18:00:23 -0700480 Tab appTab = mTabControl.getTabFromId(appId);
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700481 if (appTab != null) {
482 Log.i(LOGTAG, "Reusing tab for " + appId);
483 // Dismiss the subwindow if applicable.
484 dismissSubWindow(appTab);
485 // Since we might kill the WebView, remove it from the
486 // content view first.
487 removeTabFromContentView(appTab);
488 // Recreate the main WebView after destroying the old one.
489 // If the WebView has the same original url and is on that
490 // page, it can be reused.
491 boolean needsLoad =
Leon Scroggins6eac63e2010-03-15 18:19:14 -0400492 mTabControl.recreateWebView(appTab, urlData);
Ben Murdochbff2d602009-07-01 20:19:05 +0100493
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700494 if (current != appTab) {
Leon Scroggins1f005d32009-08-10 17:36:42 -0400495 switchToTab(mTabControl.getTabIndex(appTab));
496 if (needsLoad) {
Patrick Scott9d53da02010-02-19 10:19:01 -0500497 loadUrlDataIn(appTab, urlData);
Leon Scroggins1f005d32009-08-10 17:36:42 -0400498 }
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700499 } else {
Leon Scroggins1f005d32009-08-10 17:36:42 -0400500 // If the tab was the current tab, we have to attach
501 // it to the view system again.
502 attachTabToContentView(appTab);
503 if (needsLoad) {
Patrick Scott9d53da02010-02-19 10:19:01 -0500504 loadUrlDataIn(appTab, urlData);
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700505 }
506 }
507 return;
Patrick Scottcd115892009-07-16 09:42:58 -0400508 } else {
509 // No matching application tab, try to find a regular tab
510 // with a matching url.
511 appTab = mTabControl.findUnusedTabWithUrl(urlData.mUrl);
Leon Scroggins25515f82009-08-19 15:31:58 -0400512 if (appTab != null) {
513 if (current != appTab) {
514 switchToTab(mTabControl.getTabIndex(appTab));
515 }
516 // Otherwise, we are already viewing the correct tab.
Patrick Scottcd115892009-07-16 09:42:58 -0400517 } else {
518 // if FLAG_ACTIVITY_BROUGHT_TO_FRONT flag is on, the url
519 // will be opened in a new tab unless we have reached
520 // MAX_TABS. Then the url will be opened in the current
521 // tab. If a new tab is created, it will have "true" for
522 // exit on close.
Leon Scroggins1f005d32009-08-10 17:36:42 -0400523 openTabAndShow(urlData, true, appId);
Patrick Scottcd115892009-07-16 09:42:58 -0400524 }
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700525 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800526 } else {
Grace Kloba638d3f42009-11-23 10:35:04 -0800527 if (!urlData.isEmpty()
528 && urlData.mUrl.startsWith("about:debug")) {
529 if ("about:debug.dom".equals(urlData.mUrl)) {
530 current.getWebView().dumpDomTree(false);
531 } else if ("about:debug.dom.file".equals(urlData.mUrl)) {
532 current.getWebView().dumpDomTree(true);
533 } else if ("about:debug.render".equals(urlData.mUrl)) {
534 current.getWebView().dumpRenderTree(false);
535 } else if ("about:debug.render.file".equals(urlData.mUrl)) {
536 current.getWebView().dumpRenderTree(true);
537 } else if ("about:debug.display".equals(urlData.mUrl)) {
538 current.getWebView().dumpDisplayTree();
Mike Reed9b78e1d2010-01-13 14:40:52 -0800539 } else if (urlData.mUrl.startsWith("about:debug.drag")) {
540 int index = urlData.mUrl.codePointAt(16) - '0';
541 if (index <= 0 || index > 9) {
542 current.getWebView().setDragTracker(null);
543 } else {
544 current.getWebView().setDragTracker(new MeshTracker(index));
545 }
Grace Kloba638d3f42009-11-23 10:35:04 -0800546 } else {
547 mSettings.toggleDebugSettings();
548 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800549 return;
550 }
Leon Scroggins1f005d32009-08-10 17:36:42 -0400551 // Get rid of the subwindow if it exists
552 dismissSubWindow(current);
Leon Scroggins8588d152010-04-15 11:01:53 -0400553 // If the current Tab is being used as an application tab,
554 // remove the association, since the new Intent means that it is
555 // no longer associated with that application.
556 current.setAppId(null);
Patrick Scott9d53da02010-02-19 10:19:01 -0500557 loadUrlDataIn(current, urlData);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800558 }
559 }
560 }
561
Satish Sampath565505b2009-05-29 15:37:27 +0100562 private int parseUrlShortcut(String url) {
563 if (url == null) return SHORTCUT_INVALID;
564
565 // FIXME: quick search, need to be customized by setting
566 if (url.length() > 2 && url.charAt(1) == ' ') {
567 switch (url.charAt(0)) {
568 case 'g': return SHORTCUT_GOOGLE_SEARCH;
569 case 'w': return SHORTCUT_WIKIPEDIA_SEARCH;
570 case 'd': return SHORTCUT_DICTIONARY_SEARCH;
571 case 'l': return SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH;
572 }
573 }
574 return SHORTCUT_INVALID;
575 }
576
577 /**
578 * Launches the default web search activity with the query parameters if the given intent's data
579 * are identified as plain search terms and not URLs/shortcuts.
580 * @return true if the intent was handled and web search activity was launched, false if not.
581 */
582 private boolean handleWebSearchIntent(Intent intent) {
583 if (intent == null) return false;
584
585 String url = null;
586 final String action = intent.getAction();
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -0500587 if (RecognizerResultsIntent.ACTION_VOICE_SEARCH_RESULTS.equals(
588 action)) {
Leon Scroggins58d56c62010-01-28 15:12:40 -0500589 return false;
590 }
Satish Sampath565505b2009-05-29 15:37:27 +0100591 if (Intent.ACTION_VIEW.equals(action)) {
Grace Kloba1e705052009-09-29 13:13:36 -0700592 Uri data = intent.getData();
593 if (data != null) url = data.toString();
Satish Sampath565505b2009-05-29 15:37:27 +0100594 } else if (Intent.ACTION_SEARCH.equals(action)
595 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
596 || Intent.ACTION_WEB_SEARCH.equals(action)) {
597 url = intent.getStringExtra(SearchManager.QUERY);
598 }
Bjorn Bringert04851702009-09-22 10:36:01 +0100599 return handleWebSearchRequest(url, intent.getBundleExtra(SearchManager.APP_DATA),
600 intent.getStringExtra(SearchManager.EXTRA_DATA_KEY));
Satish Sampath565505b2009-05-29 15:37:27 +0100601 }
602
603 /**
604 * Launches the default web search activity with the query parameters if the given url string
605 * was identified as plain search terms and not URL/shortcut.
606 * @return true if the request was handled and web search activity was launched, false if not.
607 */
Bjorn Bringert04851702009-09-22 10:36:01 +0100608 private boolean handleWebSearchRequest(String inUrl, Bundle appData, String extraData) {
Satish Sampath565505b2009-05-29 15:37:27 +0100609 if (inUrl == null) return false;
610
611 // In general, we shouldn't modify URL from Intent.
612 // But currently, we get the user-typed URL from search box as well.
613 String url = fixUrl(inUrl).trim();
614
615 // URLs and site specific search shortcuts are handled by the regular flow of control, so
616 // return early.
Dan Egnor5ee906c2009-11-18 12:11:49 -0800617 if (Patterns.WEB_URL.matcher(url).matches()
Satish Sampathbc5b9f32009-06-04 18:21:40 +0100618 || ACCEPTED_URI_SCHEMA.matcher(url).matches()
Satish Sampath565505b2009-05-29 15:37:27 +0100619 || parseUrlShortcut(url) != SHORTCUT_INVALID) {
620 return false;
621 }
622
Leon Scroggins8d06e362010-03-24 14:45:57 -0400623 final ContentResolver cr = mResolver;
624 final String newUrl = url;
625 new AsyncTask<Void, Void, Void>() {
626 protected Void doInBackground(Void... unused) {
627 Browser.updateVisitedHistory(cr, newUrl, false);
628 Browser.addSearchUrl(cr, newUrl);
629 return null;
630 }
631 }.execute();
Satish Sampath565505b2009-05-29 15:37:27 +0100632
Bjorn Bringertd2670652010-09-13 14:06:41 +0100633 SearchEngine searchEngine = mSettings.getSearchEngine();
634 if (searchEngine == null) return false;
635 searchEngine.startSearch(this, url, appData, extraData);
Satish Sampath565505b2009-05-29 15:37:27 +0100636
637 return true;
638 }
639
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700640 private UrlData getUrlDataFromIntent(Intent intent) {
Leon Scroggins58d56c62010-01-28 15:12:40 -0500641 String url = "";
Grace Kloba068e48b2010-01-26 18:11:27 -0800642 Map<String, String> headers = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800643 if (intent != null) {
644 final String action = intent.getAction();
645 if (Intent.ACTION_VIEW.equals(action)) {
646 url = smartUrlFilter(intent.getData());
647 if (url != null && url.startsWith("content:")) {
648 /* Append mimetype so webview knows how to display */
649 String mimeType = intent.resolveType(getContentResolver());
650 if (mimeType != null) {
651 url += "?" + mimeType;
652 }
653 }
Grace Kloba068e48b2010-01-26 18:11:27 -0800654 if (url != null && url.startsWith("http")) {
Grace Kloba00f54c52010-01-27 14:53:51 -0800655 final Bundle pairs = intent
656 .getBundleExtra(Browser.EXTRA_HEADERS);
Grace Kloba2d508ed2010-01-28 11:39:15 -0800657 if (pairs != null && !pairs.isEmpty()) {
Grace Kloba00f54c52010-01-27 14:53:51 -0800658 Iterator<String> iter = pairs.keySet().iterator();
Grace Kloba068e48b2010-01-26 18:11:27 -0800659 headers = new HashMap<String, String>();
Grace Kloba00f54c52010-01-27 14:53:51 -0800660 while (iter.hasNext()) {
661 String key = iter.next();
662 headers.put(key, pairs.getString(key));
Grace Kloba068e48b2010-01-26 18:11:27 -0800663 }
664 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700665 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800666 } else if (Intent.ACTION_SEARCH.equals(action)
667 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
668 || Intent.ACTION_WEB_SEARCH.equals(action)) {
669 url = intent.getStringExtra(SearchManager.QUERY);
670 if (url != null) {
671 mLastEnteredUrl = url;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800672 // In general, we shouldn't modify URL from Intent.
673 // But currently, we get the user-typed URL from search box as well.
674 url = fixUrl(url);
675 url = smartUrlFilter(url);
Leon Scroggins8d06e362010-03-24 14:45:57 -0400676 final ContentResolver cr = mResolver;
677 final String newUrl = url;
678 new AsyncTask<Void, Void, Void>() {
679 protected Void doInBackground(Void... unused) {
680 Browser.updateVisitedHistory(cr, newUrl, false);
681 return null;
682 }
683 }.execute();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800684 String searchSource = "&source=android-" + GOOGLE_SEARCH_SOURCE_SUGGEST + "&";
685 if (url.contains(searchSource)) {
686 String source = null;
687 final Bundle appData = intent.getBundleExtra(SearchManager.APP_DATA);
688 if (appData != null) {
Bjorn Bringert10d1cca2010-02-10 14:22:12 +0000689 source = appData.getString(Search.SOURCE);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800690 }
691 if (TextUtils.isEmpty(source)) {
692 source = GOOGLE_SEARCH_SOURCE_UNKNOWN;
693 }
694 url = url.replace(searchSource, "&source=android-"+source+"&");
695 }
696 }
697 }
698 }
Leon Scroggins58d56c62010-01-28 15:12:40 -0500699 return new UrlData(url, headers, intent);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800700 }
Leon Scroggins58d56c62010-01-28 15:12:40 -0500701 /* package */ void showVoiceTitleBar(String title) {
702 mTitleBar.setInVoiceMode(true);
703 mFakeTitleBar.setInVoiceMode(true);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800704
Leon Scroggins58d56c62010-01-28 15:12:40 -0500705 mTitleBar.setDisplayTitle(title);
706 mFakeTitleBar.setDisplayTitle(title);
707 }
708 /* package */ void revertVoiceTitleBar() {
709 mTitleBar.setInVoiceMode(false);
710 mFakeTitleBar.setInVoiceMode(false);
711
Leon Scroggins003a5dd2010-03-10 12:13:14 -0500712 mTitleBar.setDisplayTitle(mUrl);
713 mFakeTitleBar.setDisplayTitle(mUrl);
Leon Scroggins58d56c62010-01-28 15:12:40 -0500714 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800715 /* package */ static String fixUrl(String inUrl) {
Cary Clark652ff872009-09-10 13:34:44 -0400716 // FIXME: Converting the url to lower case
717 // duplicates functionality in smartUrlFilter().
718 // However, changing all current callers of fixUrl to
719 // call smartUrlFilter in addition may have unwanted
720 // consequences, and is deferred for now.
721 int colon = inUrl.indexOf(':');
722 boolean allLower = true;
723 for (int index = 0; index < colon; index++) {
724 char ch = inUrl.charAt(index);
725 if (!Character.isLetter(ch)) {
726 break;
727 }
728 allLower &= Character.isLowerCase(ch);
729 if (index == colon - 1 && !allLower) {
730 inUrl = inUrl.substring(0, colon).toLowerCase()
731 + inUrl.substring(colon);
732 }
733 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800734 if (inUrl.startsWith("http://") || inUrl.startsWith("https://"))
735 return inUrl;
736 if (inUrl.startsWith("http:") ||
737 inUrl.startsWith("https:")) {
738 if (inUrl.startsWith("http:/") || inUrl.startsWith("https:/")) {
739 inUrl = inUrl.replaceFirst("/", "//");
740 } else inUrl = inUrl.replaceFirst(":", "://");
741 }
742 return inUrl;
743 }
744
Grace Kloba22ac16e2009-10-07 18:00:23 -0700745 @Override
746 protected void onResume() {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800747 super.onResume();
Dave Bort31a6d1c2009-04-13 15:56:49 -0700748 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800749 Log.v(LOGTAG, "BrowserActivity.onResume: this=" + this);
750 }
751
752 if (!mActivityInPause) {
753 Log.e(LOGTAG, "BrowserActivity is already resumed.");
754 return;
755 }
756
Mike Reed7bfa63b2009-05-28 11:08:32 -0400757 mTabControl.resumeCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800758 mActivityInPause = false;
Mike Reed7bfa63b2009-05-28 11:08:32 -0400759 resumeWebViewTimers();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800760
761 if (mWakeLock.isHeld()) {
762 mHandler.removeMessages(RELEASE_WAKELOCK);
763 mWakeLock.release();
764 }
765
The Android Open Source Project0c908882009-03-03 19:32:16 -0800766 registerReceiver(mNetworkStateIntentReceiver,
767 mNetworkStateChangedFilter);
768 WebView.enablePlatformNotifications();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800769 }
770
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400771 /**
772 * Since the actual title bar is embedded in the WebView, and removing it
Leon Scrogginsfe87bd32009-10-06 10:10:00 -0400773 * would change its appearance, use a different TitleBar to show overlayed
774 * at the top of the screen, when the menu is open or the page is loading.
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400775 */
776 private TitleBar mFakeTitleBar;
777
778 /**
779 * Keeps track of whether the options menu is open. This is important in
780 * determining whether to show or hide the title bar overlay.
781 */
782 private boolean mOptionsMenuOpen;
783
784 /**
785 * Only meaningful when mOptionsMenuOpen is true. This variable keeps track
786 * of whether the configuration has changed. The first onMenuOpened call
787 * after a configuration change is simply a reopening of the same menu
788 * (i.e. mIconView did not change).
789 */
790 private boolean mConfigChanged;
791
792 /**
793 * Whether or not the options menu is in its smaller, icon menu form. When
794 * true, we want the title bar overlay to be up. When false, we do not.
795 * Only meaningful if mOptionsMenuOpen is true.
796 */
797 private boolean mIconView;
798
Leon Scrogginsa81a7642009-08-31 17:05:41 -0400799 @Override
800 public boolean onMenuOpened(int featureId, Menu menu) {
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400801 if (Window.FEATURE_OPTIONS_PANEL == featureId) {
802 if (mOptionsMenuOpen) {
803 if (mConfigChanged) {
804 // We do not need to make any changes to the state of the
805 // title bar, since the only thing that happened was a
806 // change in orientation
807 mConfigChanged = false;
808 } else {
809 if (mIconView) {
810 // Switching the menu to expanded view, so hide the
811 // title bar.
812 hideFakeTitleBar();
813 mIconView = false;
814 } else {
815 // Switching the menu back to icon view, so show the
816 // title bar once again.
817 showFakeTitleBar();
818 mIconView = true;
819 }
820 }
821 } else {
822 // The options menu is closed, so open it, and show the title
823 showFakeTitleBar();
824 mOptionsMenuOpen = true;
825 mConfigChanged = false;
826 mIconView = true;
827 }
828 }
Leon Scrogginsa81a7642009-08-31 17:05:41 -0400829 return true;
830 }
831
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400832 private void showFakeTitleBar() {
Leon Scrogginsfe87bd32009-10-06 10:10:00 -0400833 if (mFakeTitleBar.getParent() == null && mActiveTabsPage == null
Grace Kloba847c25b2010-03-30 16:00:26 -0700834 && !mActivityInPause) {
835 WebView mainView = mTabControl.getCurrentWebView();
836 // if there is no current WebView, don't show the faked title bar;
Grace Kloba65190702010-04-02 23:37:26 -0700837 if (mainView == null) {
Cary Clarka0464552009-09-29 13:00:45 -0400838 return;
839 }
Cary Clark2c326e62010-08-19 18:40:57 -0400840 // Do not need to check for null, since the current tab will have
841 // at least a main WebView, or we would have returned above.
842 if (dialogIsUp()) {
843 // Do not show the fake title bar, which would cover up the
844 // find or select dialog.
845 return;
846 }
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400847
848 WindowManager manager
849 = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
850
851 // Add the title bar to the window manager so it can receive touches
852 // while the menu is up
853 WindowManager.LayoutParams params
854 = new WindowManager.LayoutParams(
Romain Guy15b8ec62010-01-08 15:06:43 -0800855 ViewGroup.LayoutParams.MATCH_PARENT,
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400856 ViewGroup.LayoutParams.WRAP_CONTENT,
Grace Kloba847c25b2010-03-30 16:00:26 -0700857 WindowManager.LayoutParams.TYPE_APPLICATION,
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400858 WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
Leon Scroggins68549862009-09-21 16:02:01 -0400859 PixelFormat.TRANSLUCENT);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400860 params.gravity = Gravity.TOP;
Grace Kloba847c25b2010-03-30 16:00:26 -0700861 boolean atTop = mainView.getScrollY() == 0;
Leon Scroggins83932c72009-09-30 11:55:54 -0400862 params.windowAnimations = atTop ? 0 : R.style.TitleBar;
Grace Kloba13f9ace2010-03-18 21:44:14 -0700863 manager.addView(mFakeTitleBar, params);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400864 }
865 }
866
867 @Override
868 public void onOptionsMenuClosed(Menu menu) {
869 mOptionsMenuOpen = false;
Leon Scrogginsa27ff192009-09-14 12:58:04 -0400870 if (!mInLoad) {
871 hideFakeTitleBar();
872 } else if (!mIconView) {
873 // The page is currently loading, and we are in expanded mode, so
874 // we were not showing the menu. Show it once again. It will be
875 // removed when the page finishes.
876 showFakeTitleBar();
877 }
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400878 }
Grace Kloba22ac16e2009-10-07 18:00:23 -0700879
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400880 private void hideFakeTitleBar() {
Leon Scrogginsfe87bd32009-10-06 10:10:00 -0400881 if (mFakeTitleBar.getParent() == null) return;
Leon Scroggins20329572009-09-23 17:42:41 -0400882 WindowManager.LayoutParams params = (WindowManager.LayoutParams)
Grace Kloba13f9ace2010-03-18 21:44:14 -0700883 mFakeTitleBar.getLayoutParams();
Leon Scroggins20329572009-09-23 17:42:41 -0400884 WebView mainView = mTabControl.getCurrentWebView();
885 // Although we decided whether or not to animate based on the current
886 // scroll position, the scroll position may have changed since the
887 // fake title bar was displayed. Make sure it has the appropriate
888 // animation/lack thereof before removing.
889 params.windowAnimations = mainView != null && mainView.getScrollY() == 0
Leon Scroggins83932c72009-09-30 11:55:54 -0400890 ? 0 : R.style.TitleBar;
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400891 WindowManager manager
892 = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
Grace Kloba13f9ace2010-03-18 21:44:14 -0700893 manager.updateViewLayout(mFakeTitleBar, params);
894 manager.removeView(mFakeTitleBar);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400895 }
896
The Android Open Source Project0c908882009-03-03 19:32:16 -0800897 /**
Leon Scrogginsc6fa1102009-09-21 10:40:01 -0400898 * Special method for the fake title bar to call when displaying its context
899 * menu, since it is in its own Window, and its parent does not show a
900 * context menu.
901 */
902 /* package */ void showTitleBarContextMenu() {
Cary Clark65f4a3c2009-09-28 17:05:06 -0400903 if (null == mTitleBar.getParent()) {
904 return;
905 }
Leon Scrogginsc6fa1102009-09-21 10:40:01 -0400906 openContextMenu(mTitleBar);
907 }
908
Leon Scrogginsb2b19f52009-10-09 16:10:00 -0400909 @Override
910 public void onContextMenuClosed(Menu menu) {
911 super.onContextMenuClosed(menu);
912 if (mInLoad) {
913 showFakeTitleBar();
914 }
915 }
916
Leon Scrogginsc6fa1102009-09-21 10:40:01 -0400917 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -0800918 * onSaveInstanceState(Bundle map)
919 * onSaveInstanceState is called right before onStop(). The map contains
920 * the saved state.
921 */
Grace Kloba22ac16e2009-10-07 18:00:23 -0700922 @Override
923 protected void onSaveInstanceState(Bundle outState) {
Dave Bort31a6d1c2009-04-13 15:56:49 -0700924 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800925 Log.v(LOGTAG, "BrowserActivity.onSaveInstanceState: this=" + this);
926 }
927 // the default implementation requires each view to have an id. As the
928 // browser handles the state itself and it doesn't use id for the views,
929 // don't call the default implementation. Otherwise it will trigger the
930 // warning like this, "couldn't save which view has focus because the
931 // focused view XXX has no id".
932
933 // Save all the tabs
934 mTabControl.saveState(outState);
935 }
936
Grace Kloba22ac16e2009-10-07 18:00:23 -0700937 @Override
938 protected void onPause() {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800939 super.onPause();
940
941 if (mActivityInPause) {
942 Log.e(LOGTAG, "BrowserActivity is already paused.");
943 return;
944 }
945
Mike Reed7bfa63b2009-05-28 11:08:32 -0400946 mTabControl.pauseCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800947 mActivityInPause = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -0400948 if (mTabControl.getCurrentIndex() >= 0 && !pauseWebViewTimers()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800949 mWakeLock.acquire();
950 mHandler.sendMessageDelayed(mHandler
951 .obtainMessage(RELEASE_WAKELOCK), WAKELOCK_TIMEOUT);
952 }
953
Leon Scrogginsa2ab6a72009-09-11 11:49:52 -0400954 // FIXME: This removes the active tabs page and resets the menu to
955 // MAIN_MENU. A better solution might be to do this work in onNewIntent
956 // but then we would need to save it in onSaveInstanceState and restore
957 // it in onCreate/onRestoreInstanceState
958 if (mActiveTabsPage != null) {
959 removeActiveTabPage(true);
960 }
961
The Android Open Source Project0c908882009-03-03 19:32:16 -0800962 cancelStopToast();
963
964 // unregister network state listener
965 unregisterReceiver(mNetworkStateIntentReceiver);
966 WebView.disablePlatformNotifications();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800967 }
968
Grace Kloba22ac16e2009-10-07 18:00:23 -0700969 @Override
970 protected void onDestroy() {
Dave Bort31a6d1c2009-04-13 15:56:49 -0700971 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800972 Log.v(LOGTAG, "BrowserActivity.onDestroy: this=" + this);
973 }
974 super.onDestroy();
Grace Kloba0923d692009-09-23 21:37:25 -0700975
Leon Scroggins8d5fa432009-10-02 15:55:59 -0400976 if (mUploadMessage != null) {
977 mUploadMessage.onReceiveValue(null);
978 mUploadMessage = null;
979 }
980
Grace Kloba0923d692009-09-23 21:37:25 -0700981 if (mTabControl == null) return;
982
Grace Kloba1fc98a32009-10-21 13:23:08 -0700983 // Remove the fake title bar if it is there
984 hideFakeTitleBar();
985
The Android Open Source Project0c908882009-03-03 19:32:16 -0800986 // Remove the current tab and sub window
Grace Kloba22ac16e2009-10-07 18:00:23 -0700987 Tab t = mTabControl.getCurrentTab();
Patrick Scottfb5e77f2009-04-08 19:17:37 -0700988 if (t != null) {
989 dismissSubWindow(t);
990 removeTabFromContentView(t);
991 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800992 // Destroy all the tabs
993 mTabControl.destroy();
994 WebIconDatabase.getInstance().close();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800995
Grace Klobab4da0ad2009-05-14 14:45:40 -0700996 unregisterReceiver(mPackageInstallationReceiver);
Bjorn Bringerta7611812010-03-24 11:12:02 +0000997
998 // Stop watching the default geolocation permissions
999 mSystemAllowGeolocationOrigins.stop();
1000 mSystemAllowGeolocationOrigins = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001001 }
1002
1003 @Override
1004 public void onConfigurationChanged(Configuration newConfig) {
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04001005 mConfigChanged = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001006 super.onConfigurationChanged(newConfig);
1007
1008 if (mPageInfoDialog != null) {
1009 mPageInfoDialog.dismiss();
1010 showPageInfo(
1011 mPageInfoView,
Leon Scrogginsc7b92f82010-01-11 18:17:31 -05001012 mPageInfoFromShowSSLCertificateOnError);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001013 }
1014 if (mSSLCertificateDialog != null) {
1015 mSSLCertificateDialog.dismiss();
1016 showSSLCertificate(
1017 mSSLCertificateView);
1018 }
1019 if (mSSLCertificateOnErrorDialog != null) {
1020 mSSLCertificateOnErrorDialog.dismiss();
1021 showSSLCertificateOnError(
1022 mSSLCertificateOnErrorView,
1023 mSSLCertificateOnErrorHandler,
1024 mSSLCertificateOnErrorError);
1025 }
1026 if (mHttpAuthenticationDialog != null) {
1027 String title = ((TextView) mHttpAuthenticationDialog
1028 .findViewById(com.android.internal.R.id.alertTitle)).getText()
1029 .toString();
1030 String name = ((TextView) mHttpAuthenticationDialog
1031 .findViewById(R.id.username_edit)).getText().toString();
1032 String password = ((TextView) mHttpAuthenticationDialog
1033 .findViewById(R.id.password_edit)).getText().toString();
1034 int focusId = mHttpAuthenticationDialog.getCurrentFocus()
1035 .getId();
1036 mHttpAuthenticationDialog.dismiss();
1037 showHttpAuthentication(mHttpAuthHandler, null, null, title,
1038 name, password, focusId);
1039 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001040 }
1041
Grace Kloba22ac16e2009-10-07 18:00:23 -07001042 @Override
1043 public void onLowMemory() {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001044 super.onLowMemory();
1045 mTabControl.freeMemory();
1046 }
1047
Cary Clarkff4d92c2010-03-25 11:17:03 -04001048 private void resumeWebViewTimers() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001049 Tab tab = mTabControl.getCurrentTab();
Cary Clarkff4d92c2010-03-25 11:17:03 -04001050 if (tab == null) return; // monkey can trigger this
Grace Kloba22ac16e2009-10-07 18:00:23 -07001051 boolean inLoad = tab.inLoad();
1052 if ((!mActivityInPause && !inLoad) || (mActivityInPause && inLoad)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001053 CookieSyncManager.getInstance().startSync();
Grace Kloba22ac16e2009-10-07 18:00:23 -07001054 WebView w = tab.getWebView();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001055 if (w != null) {
1056 w.resumeTimers();
1057 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001058 }
1059 }
1060
Mike Reed7bfa63b2009-05-28 11:08:32 -04001061 private boolean pauseWebViewTimers() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001062 Tab tab = mTabControl.getCurrentTab();
1063 boolean inLoad = tab.inLoad();
1064 if (mActivityInPause && !inLoad) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001065 CookieSyncManager.getInstance().stopSync();
1066 WebView w = mTabControl.getCurrentWebView();
1067 if (w != null) {
1068 w.pauseTimers();
1069 }
1070 return true;
1071 } else {
1072 return false;
1073 }
1074 }
1075
The Android Open Source Project0c908882009-03-03 19:32:16 -08001076 // Open the icon database and retain all the icons for visited sites.
1077 private void retainIconsOnStartup() {
1078 final WebIconDatabase db = WebIconDatabase.getInstance();
1079 db.open(getDir("icons", 0).getPath());
Leon Scroggins2c0f6112010-03-12 18:09:39 -05001080 Cursor c = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001081 try {
Leon Scroggins2c0f6112010-03-12 18:09:39 -05001082 c = Browser.getAllBookmarks(mResolver);
1083 if (c.moveToFirst()) {
1084 int urlIndex = c.getColumnIndex(Browser.BookmarkColumns.URL);
1085 do {
1086 String url = c.getString(urlIndex);
1087 db.retainIconForPageUrl(url);
1088 } while (c.moveToNext());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001089 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001090 } catch (IllegalStateException e) {
1091 Log.e(LOGTAG, "retainIconsOnStartup", e);
Leon Scroggins2c0f6112010-03-12 18:09:39 -05001092 } finally {
1093 if (c!= null) c.close();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001094 }
1095 }
1096
1097 // Helper method for getting the top window.
1098 WebView getTopWindow() {
1099 return mTabControl.getCurrentTopWebView();
1100 }
1101
Grace Kloba22ac16e2009-10-07 18:00:23 -07001102 TabControl getTabControl() {
1103 return mTabControl;
1104 }
1105
The Android Open Source Project0c908882009-03-03 19:32:16 -08001106 @Override
1107 public boolean onCreateOptionsMenu(Menu menu) {
1108 super.onCreateOptionsMenu(menu);
1109
1110 MenuInflater inflater = getMenuInflater();
1111 inflater.inflate(R.menu.browser, menu);
1112 mMenu = menu;
1113 updateInLoadMenuItems();
1114 return true;
1115 }
1116
1117 /**
1118 * As the menu can be open when loading state changes
1119 * we must manually update the state of the stop/reload menu
1120 * item
1121 */
1122 private void updateInLoadMenuItems() {
1123 if (mMenu == null) {
1124 return;
1125 }
1126 MenuItem src = mInLoad ?
1127 mMenu.findItem(R.id.stop_menu_id):
1128 mMenu.findItem(R.id.reload_menu_id);
1129 MenuItem dest = mMenu.findItem(R.id.stop_reload_menu_id);
1130 dest.setIcon(src.getIcon());
1131 dest.setTitle(src.getTitle());
1132 }
1133
1134 @Override
1135 public boolean onContextItemSelected(MenuItem item) {
1136 // chording is not an issue with context menus, but we use the same
1137 // options selector, so set mCanChord to true so we can access them.
1138 mCanChord = true;
1139 int id = item.getItemId();
Leon Scroggins96afcb12009-12-10 12:35:56 -05001140 boolean result = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001141 switch (id) {
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001142 // For the context menu from the title bar
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001143 case R.id.title_bar_copy_page_url:
Leon Scroggins96afcb12009-12-10 12:35:56 -05001144 Tab currentTab = mTabControl.getCurrentTab();
1145 if (null == currentTab) {
1146 result = false;
1147 break;
1148 }
1149 WebView mainView = currentTab.getWebView();
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001150 if (null == mainView) {
Leon Scroggins96afcb12009-12-10 12:35:56 -05001151 result = false;
1152 break;
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001153 }
Leon Scroggins96afcb12009-12-10 12:35:56 -05001154 copy(mainView.getUrl());
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001155 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001156 // -- Browser context menu
1157 case R.id.open_context_menu_id:
1158 case R.id.open_newtab_context_menu_id:
1159 case R.id.bookmark_context_menu_id:
1160 case R.id.save_link_context_menu_id:
1161 case R.id.share_link_context_menu_id:
1162 case R.id.copy_link_context_menu_id:
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001163 final WebView webView = getTopWindow();
1164 if (null == webView) {
Leon Scroggins96afcb12009-12-10 12:35:56 -05001165 result = false;
1166 break;
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001167 }
1168 final HashMap hrefMap = new HashMap();
1169 hrefMap.put("webview", webView);
1170 final Message msg = mHandler.obtainMessage(
1171 FOCUS_NODE_HREF, id, 0, hrefMap);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001172 webView.requestFocusNodeHref(msg);
1173 break;
1174
1175 default:
1176 // For other context menus
Leon Scroggins96afcb12009-12-10 12:35:56 -05001177 result = onOptionsItemSelected(item);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001178 }
1179 mCanChord = false;
Leon Scroggins96afcb12009-12-10 12:35:56 -05001180 return result;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001181 }
1182
1183 private Bundle createGoogleSearchSourceBundle(String source) {
1184 Bundle bundle = new Bundle();
Bjorn Bringert10d1cca2010-02-10 14:22:12 +00001185 bundle.putString(Search.SOURCE, source);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001186 return bundle;
1187 }
1188
Leon Scroggins8ad29922010-02-16 12:33:55 -05001189 /* package */ void editUrl() {
Leon Scroggins68579392009-09-15 15:31:54 -04001190 if (mOptionsMenuOpen) closeOptionsMenu();
Leon Scroggins5bbe9802009-07-31 13:10:55 -04001191 String url = (getTopWindow() == null) ? null : getTopWindow().getUrl();
Grace Kloba83f47342009-07-20 10:44:31 -07001192 startSearch(mSettings.getHomePage().equals(url) ? null : url, true,
Leon Scroggins8ad29922010-02-16 12:33:55 -05001193 null, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001194 }
1195
Leon Scroggins8ad29922010-02-16 12:33:55 -05001196 /**
1197 * Overriding this to insert a local information bundle
1198 */
The Android Open Source Project0c908882009-03-03 19:32:16 -08001199 @Override
1200 public void startSearch(String initialQuery, boolean selectInitialQuery,
1201 Bundle appSearchData, boolean globalSearch) {
1202 if (appSearchData == null) {
1203 appSearchData = createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_TYPE);
1204 }
Leon Scroggins III430057d2010-09-14 10:57:37 -04001205
1206 SearchEngine searchEngine = mSettings.getSearchEngine();
1207 if (searchEngine != null && !searchEngine.supportsVoiceSearch()) {
1208 appSearchData.putBoolean(SearchManager.DISABLE_VOICE_SEARCH, true);
1209 }
1210
The Android Open Source Project0c908882009-03-03 19:32:16 -08001211 super.startSearch(initialQuery, selectInitialQuery, appSearchData, globalSearch);
1212 }
1213
Leon Scroggins1f005d32009-08-10 17:36:42 -04001214 /**
1215 * Switch tabs. Called by the TitleBarSet when sliding the title bar
1216 * results in changing tabs.
Leon Scroggins160a7e72009-08-14 18:28:01 -04001217 * @param index Index of the tab to change to, as defined by
1218 * mTabControl.getTabIndex(Tab t).
1219 * @return boolean True if we successfully switched to a different tab. If
1220 * the indexth tab is null, or if that tab is the same as
1221 * the current one, return false.
Leon Scroggins1f005d32009-08-10 17:36:42 -04001222 */
Leon Scroggins160a7e72009-08-14 18:28:01 -04001223 /* package */ boolean switchToTab(int index) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001224 Tab tab = mTabControl.getTab(index);
1225 Tab currentTab = mTabControl.getCurrentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04001226 if (tab == null || tab == currentTab) {
Leon Scroggins160a7e72009-08-14 18:28:01 -04001227 return false;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001228 }
1229 if (currentTab != null) {
1230 // currentTab may be null if it was just removed. In that case,
1231 // we do not need to remove it
1232 removeTabFromContentView(currentTab);
1233 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001234 mTabControl.setCurrentTab(tab);
1235 attachTabToContentView(tab);
Grace Klobaeb6eef42009-09-15 17:56:32 -07001236 resetTitleIconAndProgress();
1237 updateLockIconToLatest();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001238 return true;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001239 }
1240
Grace Kloba22ac16e2009-10-07 18:00:23 -07001241 /* package */ Tab openTabToHomePage() {
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001242 return openTabAndShow(mSettings.getHomePage(), false, null);
1243 }
1244
Leon Scroggins1f005d32009-08-10 17:36:42 -04001245 /* package */ void closeCurrentWindow() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001246 final Tab current = mTabControl.getCurrentTab();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001247 if (mTabControl.getTabCount() == 1) {
Leon Scroggins30444232009-09-04 18:36:20 -04001248 // This is the last tab. Open a new one, with the home
1249 // page and close the current one.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001250 openTabToHomePage();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001251 closeTab(current);
Leon Scroggins160a7e72009-08-14 18:28:01 -04001252 return;
1253 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07001254 final Tab parent = current.getParentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04001255 int indexToShow = -1;
1256 if (parent != null) {
1257 indexToShow = mTabControl.getTabIndex(parent);
1258 } else {
Leon Scroggins160a7e72009-08-14 18:28:01 -04001259 final int currentIndex = mTabControl.getCurrentIndex();
1260 // Try to move to the tab to the right
1261 indexToShow = currentIndex + 1;
1262 if (indexToShow > mTabControl.getTabCount() - 1) {
1263 // Try to move to the tab to the left
1264 indexToShow = currentIndex - 1;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001265 }
1266 }
Leon Scroggins160a7e72009-08-14 18:28:01 -04001267 if (switchToTab(indexToShow)) {
1268 // Close window
1269 closeTab(current);
1270 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001271 }
1272
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001273 private ActiveTabsPage mActiveTabsPage;
1274
1275 /**
1276 * Remove the active tabs page.
1277 * @param needToAttach If true, the active tabs page did not attach a tab
1278 * to the content view, so we need to do that here.
1279 */
1280 /* package */ void removeActiveTabPage(boolean needToAttach) {
1281 mContentView.removeView(mActiveTabsPage);
1282 mActiveTabsPage = null;
1283 mMenuState = R.id.MAIN_MENU;
1284 if (needToAttach) {
1285 attachTabToContentView(mTabControl.getCurrentTab());
1286 }
1287 getTopWindow().requestFocus();
1288 }
1289
Cary Clark2c326e62010-08-19 18:40:57 -04001290 private WebView showDialog(WebDialog dialog) {
Cary Clark2c326e62010-08-19 18:40:57 -04001291 Tab tab = mTabControl.getCurrentTab();
1292 if (tab.getSubWebView() == null) {
1293 // If the find or select is being performed on the main webview,
1294 // remove the embedded title bar.
1295 WebView mainView = tab.getWebView();
1296 if (mainView != null) {
1297 mainView.setEmbeddedTitleBar(null);
1298 }
1299 }
1300 hideFakeTitleBar();
1301 mMenuState = EMPTY_MENU;
1302 return tab.showDialog(dialog);
1303 }
1304
The Android Open Source Project0c908882009-03-03 19:32:16 -08001305 @Override
1306 public boolean onOptionsItemSelected(MenuItem item) {
1307 if (!mCanChord) {
1308 // The user has already fired a shortcut with this hold down of the
1309 // menu key.
1310 return false;
1311 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001312 if (null == getTopWindow()) {
Leon Scroggins0d7ae0e2009-06-05 11:04:45 -04001313 return false;
1314 }
Grace Kloba6ee9c492009-07-13 10:04:34 -07001315 if (mMenuIsDown) {
1316 // The shortcut action consumes the MENU. Even if it is still down,
1317 // it won't trigger the next shortcut action. In the case of the
1318 // shortcut action triggering a new activity, like Bookmarks, we
1319 // won't get onKeyUp for MENU. So it is important to reset it here.
1320 mMenuIsDown = false;
1321 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001322 switch (item.getItemId()) {
1323 // -- Main menu
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001324 case R.id.new_tab_menu_id:
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001325 openTabToHomePage();
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001326 break;
1327
Leon Scroggins64b80f32009-08-07 12:03:34 -04001328 case R.id.goto_menu_id:
Leon Scroggins8ad29922010-02-16 12:33:55 -05001329 editUrl();
Leon Scrogginsb3a5bed2009-09-28 11:21:56 -04001330 break;
1331
1332 case R.id.bookmarks_menu_id:
Leon Scroggins30444232009-09-04 18:36:20 -04001333 bookmarksOrHistoryPicker(false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001334 break;
1335
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001336 case R.id.active_tabs_menu_id:
1337 mActiveTabsPage = new ActiveTabsPage(this, mTabControl);
1338 removeTabFromContentView(mTabControl.getCurrentTab());
Leon Scroggins43de6162009-09-14 19:59:58 -04001339 hideFakeTitleBar();
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001340 mContentView.addView(mActiveTabsPage, COVER_SCREEN_PARAMS);
1341 mActiveTabsPage.requestFocus();
1342 mMenuState = EMPTY_MENU;
1343 break;
1344
Leon Scroggins1f005d32009-08-10 17:36:42 -04001345 case R.id.add_bookmark_menu_id:
1346 Intent i = new Intent(BrowserActivity.this,
1347 AddBookmarkPage.class);
1348 WebView w = getTopWindow();
1349 i.putExtra("url", w.getUrl());
1350 i.putExtra("title", w.getTitle());
Grace Kloba83cdb2c2009-09-16 00:48:57 -07001351 i.putExtra("touch_icon_url", w.getTouchIconUrl());
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01001352 i.putExtra("thumbnail", createScreenshot(w));
Leon Scroggins1f005d32009-08-10 17:36:42 -04001353 startActivity(i);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001354 break;
1355
1356 case R.id.stop_reload_menu_id:
1357 if (mInLoad) {
1358 stopLoading();
1359 } else {
1360 getTopWindow().reload();
1361 }
1362 break;
1363
1364 case R.id.back_menu_id:
1365 getTopWindow().goBack();
1366 break;
1367
1368 case R.id.forward_menu_id:
1369 getTopWindow().goForward();
1370 break;
1371
1372 case R.id.close_menu_id:
1373 // Close the subwindow if it exists.
1374 if (mTabControl.getCurrentSubWindow() != null) {
1375 dismissSubWindow(mTabControl.getCurrentTab());
1376 break;
1377 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001378 closeCurrentWindow();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001379 break;
1380
1381 case R.id.homepage_menu_id:
Grace Kloba22ac16e2009-10-07 18:00:23 -07001382 Tab current = mTabControl.getCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001383 if (current != null) {
1384 dismissSubWindow(current);
Leon Scroggins92472e82010-02-17 16:32:28 -05001385 loadUrl(current.getWebView(), mSettings.getHomePage());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001386 }
1387 break;
1388
1389 case R.id.preferences_menu_id:
1390 Intent intent = new Intent(this,
1391 BrowserPreferencesPage.class);
Leon Scrogginsd5304942009-12-10 16:11:39 -05001392 intent.putExtra(BrowserPreferencesPage.CURRENT_PAGE,
1393 getTopWindow().getUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001394 startActivityForResult(intent, PREFERENCES_PAGE);
1395 break;
1396
1397 case R.id.find_menu_id:
Cary Clark2c326e62010-08-19 18:40:57 -04001398 showFindDialog();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001399 break;
1400
1401 case R.id.select_text_id:
Cary Clark5feb8ad2010-09-21 14:28:49 -04001402 if (true) {
1403 Tab currentTab = mTabControl.getCurrentTab();
1404 if (currentTab != null) {
1405 currentTab.getWebView().setUpSelect();
1406 }
1407 } else {
1408 showSelectDialog();
1409 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001410 break;
Cary Clark2c326e62010-08-19 18:40:57 -04001411
The Android Open Source Project0c908882009-03-03 19:32:16 -08001412 case R.id.page_info_menu_id:
1413 showPageInfo(mTabControl.getCurrentTab(), false);
1414 break;
1415
1416 case R.id.classic_history_menu_id:
Leon Scroggins30444232009-09-04 18:36:20 -04001417 bookmarksOrHistoryPicker(true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001418 break;
1419
Leon Scroggins96afcb12009-12-10 12:35:56 -05001420 case R.id.title_bar_share_page_url:
The Android Open Source Project0c908882009-03-03 19:32:16 -08001421 case R.id.share_page_menu_id:
Leon Scroggins96afcb12009-12-10 12:35:56 -05001422 Tab currentTab = mTabControl.getCurrentTab();
1423 if (null == currentTab) {
1424 mCanChord = false;
1425 return false;
1426 }
1427 currentTab.populatePickerData();
1428 sharePage(this, currentTab.getTitle(),
1429 currentTab.getUrl(), currentTab.getFavicon(),
1430 createScreenshot(currentTab.getWebView()));
The Android Open Source Project0c908882009-03-03 19:32:16 -08001431 break;
1432
1433 case R.id.dump_nav_menu_id:
1434 getTopWindow().debugDump();
1435 break;
1436
Andrei Popescu7a8b88b2010-02-02 00:30:38 +00001437 case R.id.dump_counters_menu_id:
1438 getTopWindow().dumpV8Counters();
1439 break;
1440
The Android Open Source Project0c908882009-03-03 19:32:16 -08001441 case R.id.zoom_in_menu_id:
1442 getTopWindow().zoomIn();
1443 break;
1444
1445 case R.id.zoom_out_menu_id:
1446 getTopWindow().zoomOut();
1447 break;
1448
1449 case R.id.view_downloads_menu_id:
1450 viewDownloads(null);
1451 break;
1452
The Android Open Source Project0c908882009-03-03 19:32:16 -08001453 case R.id.window_one_menu_id:
1454 case R.id.window_two_menu_id:
1455 case R.id.window_three_menu_id:
1456 case R.id.window_four_menu_id:
1457 case R.id.window_five_menu_id:
1458 case R.id.window_six_menu_id:
1459 case R.id.window_seven_menu_id:
1460 case R.id.window_eight_menu_id:
1461 {
1462 int menuid = item.getItemId();
1463 for (int id = 0; id < WINDOW_SHORTCUT_ID_ARRAY.length; id++) {
1464 if (WINDOW_SHORTCUT_ID_ARRAY[id] == menuid) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001465 Tab desiredTab = mTabControl.getTab(id);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001466 if (desiredTab != null &&
1467 desiredTab != mTabControl.getCurrentTab()) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001468 switchToTab(id);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001469 }
1470 break;
1471 }
1472 }
1473 }
1474 break;
1475
1476 default:
1477 if (!super.onOptionsItemSelected(item)) {
1478 return false;
1479 }
1480 // Otherwise fall through.
1481 }
1482 mCanChord = false;
1483 return true;
1484 }
1485
Cary Clark2c326e62010-08-19 18:40:57 -04001486 private boolean dialogIsUp() {
1487 return null != mFindDialog && mFindDialog.isVisible() ||
1488 null != mSelectDialog && mSelectDialog.isVisible();
1489 }
1490
1491 private boolean closeDialog(WebDialog dialog) {
1492 if (null == dialog || !dialog.isVisible()) return false;
1493 Tab currentTab = mTabControl.getCurrentTab();
1494 currentTab.closeDialog(dialog);
1495 dialog.dismiss();
1496 return true;
1497 }
1498
1499 /*
1500 * Remove the find dialog or select dialog.
1501 */
1502 public void closeDialogs() {
1503 if (!(closeDialog(mFindDialog) || closeDialog(mSelectDialog))) return;
1504 // If the Find was being performed in the main WebView, replace the
1505 // embedded title bar.
1506 Tab currentTab = mTabControl.getCurrentTab();
1507 if (currentTab.getSubWebView() == null) {
1508 WebView mainView = currentTab.getWebView();
1509 if (mainView != null) {
1510 mainView.setEmbeddedTitleBar(mTitleBar);
1511 }
1512 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001513 mMenuState = R.id.MAIN_MENU;
Cary Clark2c326e62010-08-19 18:40:57 -04001514 if (mInLoad) {
1515 // The title bar was hidden, because otherwise it would cover up the
1516 // find or select dialog. Now that the dialog has been removed,
1517 // show the fake title bar once again.
1518 showFakeTitleBar();
1519 }
1520 }
1521
1522 public void showFindDialog() {
1523 if (null == mFindDialog) {
1524 mFindDialog = new FindDialog(this);
1525 }
1526 showDialog(mFindDialog).setFindIsUp(true);
1527 }
1528
1529 public void setFindDialogText(String text) {
1530 mFindDialog.setText(text);
1531 }
1532
1533 public void showSelectDialog() {
1534 if (null == mSelectDialog) {
1535 mSelectDialog = new SelectDialog(this);
1536 }
1537 showDialog(mSelectDialog).setUpSelect();
1538 mSelectDialog.hideSoftInput();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001539 }
1540
Grace Kloba22ac16e2009-10-07 18:00:23 -07001541 @Override
1542 public boolean onPrepareOptionsMenu(Menu menu) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001543 // This happens when the user begins to hold down the menu key, so
1544 // allow them to chord to get a shortcut.
1545 mCanChord = true;
1546 // Note: setVisible will decide whether an item is visible; while
1547 // setEnabled() will decide whether an item is enabled, which also means
1548 // whether the matching shortcut key will function.
1549 super.onPrepareOptionsMenu(menu);
1550 switch (mMenuState) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001551 case EMPTY_MENU:
1552 if (mCurrentMenuState != mMenuState) {
1553 menu.setGroupVisible(R.id.MAIN_MENU, false);
1554 menu.setGroupEnabled(R.id.MAIN_MENU, false);
1555 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001556 }
1557 break;
1558 default:
1559 if (mCurrentMenuState != mMenuState) {
1560 menu.setGroupVisible(R.id.MAIN_MENU, true);
1561 menu.setGroupEnabled(R.id.MAIN_MENU, true);
1562 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001563 }
1564 final WebView w = getTopWindow();
1565 boolean canGoBack = false;
1566 boolean canGoForward = false;
1567 boolean isHome = false;
1568 if (w != null) {
1569 canGoBack = w.canGoBack();
1570 canGoForward = w.canGoForward();
1571 isHome = mSettings.getHomePage().equals(w.getUrl());
1572 }
1573 final MenuItem back = menu.findItem(R.id.back_menu_id);
1574 back.setEnabled(canGoBack);
1575
1576 final MenuItem home = menu.findItem(R.id.homepage_menu_id);
1577 home.setEnabled(!isHome);
1578
1579 menu.findItem(R.id.forward_menu_id)
1580 .setEnabled(canGoForward);
1581
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001582 menu.findItem(R.id.new_tab_menu_id).setEnabled(
Grace Kloba22ac16e2009-10-07 18:00:23 -07001583 mTabControl.canCreateNewTab());
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001584
The Android Open Source Project0c908882009-03-03 19:32:16 -08001585 // decide whether to show the share link option
1586 PackageManager pm = getPackageManager();
1587 Intent send = new Intent(Intent.ACTION_SEND);
1588 send.setType("text/plain");
1589 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1590 menu.findItem(R.id.share_page_menu_id).setVisible(ri != null);
1591
The Android Open Source Project0c908882009-03-03 19:32:16 -08001592 boolean isNavDump = mSettings.isNavDump();
1593 final MenuItem nav = menu.findItem(R.id.dump_nav_menu_id);
1594 nav.setVisible(isNavDump);
1595 nav.setEnabled(isNavDump);
Andrei Popescu7a8b88b2010-02-02 00:30:38 +00001596
1597 boolean showDebugSettings = mSettings.showDebugSettings();
1598 final MenuItem counter = menu.findItem(R.id.dump_counters_menu_id);
1599 counter.setVisible(showDebugSettings);
1600 counter.setEnabled(showDebugSettings);
1601
The Android Open Source Project0c908882009-03-03 19:32:16 -08001602 break;
1603 }
1604 mCurrentMenuState = mMenuState;
1605 return true;
1606 }
1607
1608 @Override
1609 public void onCreateContextMenu(ContextMenu menu, View v,
1610 ContextMenuInfo menuInfo) {
Leon Scroggins4e9f89b2010-02-22 16:54:14 -05001611 if (v instanceof TitleBar) {
1612 return;
1613 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001614 WebView webview = (WebView) v;
1615 WebView.HitTestResult result = webview.getHitTestResult();
1616 if (result == null) {
1617 return;
1618 }
1619
1620 int type = result.getType();
1621 if (type == WebView.HitTestResult.UNKNOWN_TYPE) {
1622 Log.w(LOGTAG,
1623 "We should not show context menu when nothing is touched");
1624 return;
1625 }
1626 if (type == WebView.HitTestResult.EDIT_TEXT_TYPE) {
1627 // let TextView handles context menu
1628 return;
1629 }
1630
1631 // Note, http://b/issue?id=1106666 is requesting that
1632 // an inflated menu can be used again. This is not available
1633 // yet, so inflate each time (yuk!)
1634 MenuInflater inflater = getMenuInflater();
1635 inflater.inflate(R.menu.browsercontext, menu);
1636
1637 // Show the correct menu group
1638 String extra = result.getExtra();
1639 menu.setGroupVisible(R.id.PHONE_MENU,
1640 type == WebView.HitTestResult.PHONE_TYPE);
1641 menu.setGroupVisible(R.id.EMAIL_MENU,
1642 type == WebView.HitTestResult.EMAIL_TYPE);
1643 menu.setGroupVisible(R.id.GEO_MENU,
1644 type == WebView.HitTestResult.GEO_TYPE);
1645 menu.setGroupVisible(R.id.IMAGE_MENU,
1646 type == WebView.HitTestResult.IMAGE_TYPE
1647 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1648 menu.setGroupVisible(R.id.ANCHOR_MENU,
1649 type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1650 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1651
1652 // Setup custom handling depending on the type
1653 switch (type) {
1654 case WebView.HitTestResult.PHONE_TYPE:
1655 menu.setHeaderTitle(Uri.decode(extra));
1656 menu.findItem(R.id.dial_context_menu_id).setIntent(
1657 new Intent(Intent.ACTION_VIEW, Uri
1658 .parse(WebView.SCHEME_TEL + extra)));
1659 Intent addIntent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
1660 addIntent.putExtra(Insert.PHONE, Uri.decode(extra));
Cary Clark5e335a32009-09-22 14:53:11 -04001661 addIntent.setType(ContactsContract.Contacts.CONTENT_ITEM_TYPE);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001662 menu.findItem(R.id.add_contact_context_menu_id).setIntent(
1663 addIntent);
1664 menu.findItem(R.id.copy_phone_context_menu_id).setOnMenuItemClickListener(
1665 new Copy(extra));
1666 break;
1667
1668 case WebView.HitTestResult.EMAIL_TYPE:
1669 menu.setHeaderTitle(extra);
1670 menu.findItem(R.id.email_context_menu_id).setIntent(
1671 new Intent(Intent.ACTION_VIEW, Uri
1672 .parse(WebView.SCHEME_MAILTO + extra)));
1673 menu.findItem(R.id.copy_mail_context_menu_id).setOnMenuItemClickListener(
1674 new Copy(extra));
1675 break;
1676
1677 case WebView.HitTestResult.GEO_TYPE:
1678 menu.setHeaderTitle(extra);
1679 menu.findItem(R.id.map_context_menu_id).setIntent(
1680 new Intent(Intent.ACTION_VIEW, Uri
1681 .parse(WebView.SCHEME_GEO
1682 + URLEncoder.encode(extra))));
1683 menu.findItem(R.id.copy_geo_context_menu_id).setOnMenuItemClickListener(
1684 new Copy(extra));
1685 break;
1686
1687 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1688 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
1689 TextView titleView = (TextView) LayoutInflater.from(this)
1690 .inflate(android.R.layout.browser_link_context_header,
1691 null);
1692 titleView.setText(extra);
1693 menu.setHeaderView(titleView);
1694 // decide whether to show the open link in new tab option
1695 menu.findItem(R.id.open_newtab_context_menu_id).setVisible(
Grace Kloba22ac16e2009-10-07 18:00:23 -07001696 mTabControl.canCreateNewTab());
Ben Murdochde353622009-10-12 10:29:00 +01001697 menu.findItem(R.id.bookmark_context_menu_id).setVisible(
1698 Bookmarks.urlHasAcceptableScheme(extra));
The Android Open Source Project0c908882009-03-03 19:32:16 -08001699 PackageManager pm = getPackageManager();
1700 Intent send = new Intent(Intent.ACTION_SEND);
1701 send.setType("text/plain");
1702 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1703 menu.findItem(R.id.share_link_context_menu_id).setVisible(ri != null);
1704 if (type == WebView.HitTestResult.SRC_ANCHOR_TYPE) {
1705 break;
1706 }
1707 // otherwise fall through to handle image part
1708 case WebView.HitTestResult.IMAGE_TYPE:
1709 if (type == WebView.HitTestResult.IMAGE_TYPE) {
1710 menu.setHeaderTitle(extra);
1711 }
1712 menu.findItem(R.id.view_image_context_menu_id).setIntent(
1713 new Intent(Intent.ACTION_VIEW, Uri.parse(extra)));
1714 menu.findItem(R.id.download_context_menu_id).
1715 setOnMenuItemClickListener(new Download(extra));
Ben Murdoch4f75ba22009-10-27 11:48:28 +00001716 menu.findItem(R.id.set_wallpaper_context_menu_id).
1717 setOnMenuItemClickListener(new SetAsWallpaper(extra));
The Android Open Source Project0c908882009-03-03 19:32:16 -08001718 break;
1719
1720 default:
1721 Log.w(LOGTAG, "We should not get here.");
1722 break;
1723 }
Leon Scrogginsb2b19f52009-10-09 16:10:00 -04001724 hideFakeTitleBar();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001725 }
1726
The Android Open Source Project0c908882009-03-03 19:32:16 -08001727 // Attach the given tab to the content view.
Grace Klobac928c302009-09-17 11:51:21 -07001728 // this should only be called for the current tab.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001729 private void attachTabToContentView(Tab t) {
Steve Block2bc69912009-07-30 14:45:13 +01001730 // Attach the container that contains the main WebView and any other UI
1731 // associated with the tab.
Patrick Scottd0119532009-09-17 08:00:31 -04001732 t.attachTabToContentView(mContentView);
Ben Murdochbff2d602009-07-01 20:19:05 +01001733
1734 if (mShouldShowErrorConsole) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001735 ErrorConsoleView errorConsole = t.getErrorConsole(true);
Ben Murdochbff2d602009-07-01 20:19:05 +01001736 if (errorConsole.numberOfErrors() == 0) {
1737 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
1738 } else {
1739 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
1740 }
1741
1742 mErrorConsoleContainer.addView(errorConsole,
Romain Guy15b8ec62010-01-08 15:06:43 -08001743 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
Ben Murdochbff2d602009-07-01 20:19:05 +01001744 ViewGroup.LayoutParams.WRAP_CONTENT));
1745 }
1746
Leon Scroggins39ab28e2009-09-02 21:20:30 -04001747 WebView view = t.getWebView();
Leon Scroggins55a5bc22009-09-04 17:00:08 -04001748 view.setEmbeddedTitleBar(mTitleBar);
Leon Scroggins58d56c62010-01-28 15:12:40 -05001749 if (t.isInVoiceSearchMode()) {
1750 showVoiceTitleBar(t.getVoiceDisplayTitle());
1751 } else {
1752 revertVoiceTitleBar();
1753 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001754 // Request focus on the top window.
1755 t.getTopWindow().requestFocus();
1756 }
1757
1758 // Attach a sub window to the main WebView of the given tab.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001759 void attachSubWindow(Tab t) {
Patrick Scottd0119532009-09-17 08:00:31 -04001760 t.attachSubWindow(mContentView);
1761 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001762 }
1763
1764 // Remove the given tab from the content view.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001765 private void removeTabFromContentView(Tab t) {
Steve Block2bc69912009-07-30 14:45:13 +01001766 // Remove the container that contains the main WebView.
Patrick Scottd0119532009-09-17 08:00:31 -04001767 t.removeTabFromContentView(mContentView);
Ben Murdochbff2d602009-07-01 20:19:05 +01001768
Grace Kloba22ac16e2009-10-07 18:00:23 -07001769 ErrorConsoleView errorConsole = t.getErrorConsole(false);
1770 if (errorConsole != null) {
1771 mErrorConsoleContainer.removeView(errorConsole);
Ben Murdochbff2d602009-07-01 20:19:05 +01001772 }
1773
Leon Scroggins39ab28e2009-09-02 21:20:30 -04001774 WebView view = t.getWebView();
Leon Scrogginsbb85b902009-09-14 19:27:20 -04001775 if (view != null) {
1776 view.setEmbeddedTitleBar(null);
1777 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001778 }
1779
1780 // Remove the sub window if it exists. Also called by TabControl when the
1781 // user clicks the 'X' to dismiss a sub window.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001782 /* package */ void dismissSubWindow(Tab t) {
Patrick Scottd0119532009-09-17 08:00:31 -04001783 t.removeSubWindow(mContentView);
Grace Kloba22ac16e2009-10-07 18:00:23 -07001784 // dismiss the subwindow. This will destroy the WebView.
1785 t.dismissSubWindow();
Patrick Scottd0119532009-09-17 08:00:31 -04001786 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001787 }
1788
Leon Scroggins1f005d32009-08-10 17:36:42 -04001789 // A wrapper function of {@link #openTabAndShow(UrlData, boolean, String)}
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07001790 // that accepts url as string.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001791 private Tab openTabAndShow(String url, boolean closeOnExit, String appId) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001792 return openTabAndShow(new UrlData(url), closeOnExit, appId);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001793 }
1794
1795 // This method does a ton of stuff. It will attempt to create a new tab
1796 // if we haven't reached MAX_TABS. Otherwise it uses the current tab. If
Leon Scroggins1f005d32009-08-10 17:36:42 -04001797 // url isn't null, it will load the given url.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001798 /* package */Tab openTabAndShow(UrlData urlData, boolean closeOnExit,
1799 String appId) {
1800 final Tab currentTab = mTabControl.getCurrentTab();
1801 if (mTabControl.canCreateNewTab()) {
1802 final Tab tab = mTabControl.createNewTab(closeOnExit, appId,
1803 urlData.mUrl);
Leon Scroggins1f005d32009-08-10 17:36:42 -04001804 WebView webview = tab.getWebView();
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001805 // If the last tab was removed from the active tabs page, currentTab
1806 // will be null.
1807 if (currentTab != null) {
1808 removeTabFromContentView(currentTab);
1809 }
Patrick Scott8bbd69f2009-08-14 13:35:53 -04001810 // We must set the new tab as the current tab to reflect the old
1811 // animation behavior.
1812 mTabControl.setCurrentTab(tab);
Grace Klobaeb6eef42009-09-15 17:56:32 -07001813 attachTabToContentView(tab);
Leon Scroggins160a7e72009-08-14 18:28:01 -04001814 if (!urlData.isEmpty()) {
Patrick Scott9d53da02010-02-19 10:19:01 -05001815 loadUrlDataIn(tab, urlData);
Leon Scroggins1f005d32009-08-10 17:36:42 -04001816 }
1817 return tab;
1818 } else {
1819 // Get rid of the subwindow if it exists
1820 dismissSubWindow(currentTab);
1821 if (!urlData.isEmpty()) {
1822 // Load the given url.
Patrick Scott9d53da02010-02-19 10:19:01 -05001823 loadUrlDataIn(currentTab, urlData);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001824 }
Leon Scroggins58d56c62010-01-28 15:12:40 -05001825 return currentTab;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001826 }
1827 }
1828
Grace Kloba22ac16e2009-10-07 18:00:23 -07001829 private Tab openTab(String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001830 if (mSettings.openInBackground()) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001831 Tab t = mTabControl.createNewTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001832 if (t != null) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001833 WebView view = t.getWebView();
Leon Scroggins92472e82010-02-17 16:32:28 -05001834 loadUrl(view, url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001835 }
Grace Klobac9181842009-04-14 08:53:22 -07001836 return t;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001837 } else {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001838 return openTabAndShow(url, false, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001839 }
1840 }
1841
1842 private class Copy implements OnMenuItemClickListener {
1843 private CharSequence mText;
1844
1845 public boolean onMenuItemClick(MenuItem item) {
1846 copy(mText);
1847 return true;
1848 }
1849
1850 public Copy(CharSequence toCopy) {
1851 mText = toCopy;
1852 }
1853 }
1854
1855 private class Download implements OnMenuItemClickListener {
1856 private String mText;
1857
1858 public boolean onMenuItemClick(MenuItem item) {
1859 onDownloadStartNoStream(mText, null, null, null, -1);
1860 return true;
1861 }
1862
1863 public Download(String toDownload) {
1864 mText = toDownload;
1865 }
1866 }
1867
Ben Murdoch4f75ba22009-10-27 11:48:28 +00001868 private class SetAsWallpaper extends Thread implements
1869 OnMenuItemClickListener, DialogInterface.OnCancelListener {
1870 private URL mUrl;
1871 private ProgressDialog mWallpaperProgress;
1872 private boolean mCanceled = false;
1873
1874 public SetAsWallpaper(String url) {
1875 try {
1876 mUrl = new URL(url);
1877 } catch (MalformedURLException e) {
1878 mUrl = null;
1879 }
1880 }
1881
1882 public void onCancel(DialogInterface dialog) {
1883 mCanceled = true;
1884 }
1885
1886 public boolean onMenuItemClick(MenuItem item) {
1887 if (mUrl != null) {
1888 // The user may have tried to set a image with a large file size as their
1889 // background so it may take a few moments to perform the operation. Display
1890 // a progress spinner while it is working.
1891 mWallpaperProgress = new ProgressDialog(BrowserActivity.this);
1892 mWallpaperProgress.setIndeterminate(true);
1893 mWallpaperProgress.setMessage(getText(R.string.progress_dialog_setting_wallpaper));
1894 mWallpaperProgress.setCancelable(true);
1895 mWallpaperProgress.setOnCancelListener(this);
1896 mWallpaperProgress.show();
1897 start();
1898 }
1899 return true;
1900 }
1901
1902 public void run() {
1903 Drawable oldWallpaper = BrowserActivity.this.getWallpaper();
1904 try {
1905 // TODO: This will cause the resource to be downloaded again, when we
1906 // should in most cases be able to grab it from the cache. To fix this
1907 // we should query WebCore to see if we can access a cached version and
1908 // instead open an input stream on that. This pattern could also be used
1909 // in the download manager where the same problem exists.
1910 InputStream inputstream = mUrl.openStream();
1911 if (inputstream != null) {
1912 setWallpaper(inputstream);
1913 }
1914 } catch (IOException e) {
1915 Log.e(LOGTAG, "Unable to set new wallpaper");
1916 // Act as though the user canceled the operation so we try to
1917 // restore the old wallpaper.
1918 mCanceled = true;
1919 }
1920
1921 if (mCanceled) {
1922 // Restore the old wallpaper if the user cancelled whilst we were setting
1923 // the new wallpaper.
1924 int width = oldWallpaper.getIntrinsicWidth();
1925 int height = oldWallpaper.getIntrinsicHeight();
1926 Bitmap bm = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
1927 Canvas canvas = new Canvas(bm);
1928 oldWallpaper.setBounds(0, 0, width, height);
1929 oldWallpaper.draw(canvas);
1930 try {
1931 setWallpaper(bm);
1932 } catch (IOException e) {
1933 Log.e(LOGTAG, "Unable to restore old wallpaper.");
1934 }
1935 mCanceled = false;
1936 }
1937
1938 if (mWallpaperProgress.isShowing()) {
1939 mWallpaperProgress.dismiss();
1940 }
1941 }
1942 }
1943
The Android Open Source Project0c908882009-03-03 19:32:16 -08001944 private void copy(CharSequence text) {
1945 try {
1946 IClipboard clip = IClipboard.Stub.asInterface(ServiceManager.getService("clipboard"));
1947 if (clip != null) {
1948 clip.setClipboardText(text);
1949 }
1950 } catch (android.os.RemoteException e) {
1951 Log.e(LOGTAG, "Copy failed", e);
1952 }
1953 }
1954
1955 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08001956 * Resets the browser title-view to whatever it must be
1957 * (for example, if we had a loading error)
1958 * When we have a new page, we call resetTitle, when we
1959 * have to reset the titlebar to whatever it used to be
1960 * (for example, if the user chose to stop loading), we
1961 * call resetTitleAndRevertLockIcon.
1962 */
1963 /* package */ void resetTitleAndRevertLockIcon() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001964 mTabControl.getCurrentTab().revertLockIcon();
1965 updateLockIconToLatest();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001966 resetTitleIconAndProgress();
1967 }
1968
1969 /**
1970 * Reset the title, favicon, and progress.
1971 */
1972 private void resetTitleIconAndProgress() {
1973 WebView current = mTabControl.getCurrentWebView();
1974 if (current == null) {
1975 return;
1976 }
1977 resetTitleAndIcon(current);
1978 int progress = current.getProgress();
Grace Kloba22ac16e2009-10-07 18:00:23 -07001979 current.getWebChromeClient().onProgressChanged(current, progress);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001980 }
1981
1982 // Reset the title and the icon based on the given item.
1983 private void resetTitleAndIcon(WebView view) {
1984 WebHistoryItem item = view.copyBackForwardList().getCurrentItem();
1985 if (item != null) {
Leon Scroggins68579392009-09-15 15:31:54 -04001986 setUrlTitle(item.getUrl(), item.getTitle());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001987 setFavicon(item.getFavicon());
1988 } else {
Leon Scroggins68579392009-09-15 15:31:54 -04001989 setUrlTitle(null, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001990 setFavicon(null);
1991 }
1992 }
1993
1994 /**
1995 * Sets a title composed of the URL and the title string.
1996 * @param url The URL of the site being loaded.
1997 * @param title The title of the site being loaded.
1998 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07001999 void setUrlTitle(String url, String title) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002000 mUrl = url;
2001 mTitle = title;
2002
Leon Scroggins58d56c62010-01-28 15:12:40 -05002003 // If we are in voice search mode, the title has already been set.
2004 if (mTabControl.getCurrentTab().isInVoiceSearchMode()) return;
2005 mTitleBar.setDisplayTitle(url);
2006 mFakeTitleBar.setDisplayTitle(url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002007 }
2008
2009 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08002010 * @param url The URL to build a title version of the URL from.
2011 * @return The title version of the URL or null if fails.
2012 * The title version of the URL can be either the URL hostname,
2013 * or the hostname with an "https://" prefix (for secure URLs),
2014 * or an empty string if, for example, the URL in question is a
2015 * file:// URL with no hostname.
2016 */
Leon Scroggins32e14a62009-06-11 10:26:34 -04002017 /* package */ static String buildTitleUrl(String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002018 String titleUrl = null;
2019
2020 if (url != null) {
2021 try {
2022 // parse the url string
2023 URL urlObj = new URL(url);
2024 if (urlObj != null) {
2025 titleUrl = "";
2026
2027 String protocol = urlObj.getProtocol();
2028 String host = urlObj.getHost();
2029
2030 if (host != null && 0 < host.length()) {
2031 titleUrl = host;
2032 if (protocol != null) {
2033 // if a secure site, add an "https://" prefix!
2034 if (protocol.equalsIgnoreCase("https")) {
2035 titleUrl = protocol + "://" + host;
2036 }
2037 }
2038 }
2039 }
2040 } catch (MalformedURLException e) {}
2041 }
2042
2043 return titleUrl;
2044 }
2045
2046 // Set the favicon in the title bar.
Grace Kloba22ac16e2009-10-07 18:00:23 -07002047 void setFavicon(Bitmap icon) {
Leon Scroggins68579392009-09-15 15:31:54 -04002048 mTitleBar.setFavicon(icon);
Leon Scrogginsfe87bd32009-10-06 10:10:00 -04002049 mFakeTitleBar.setFavicon(icon);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002050 }
2051
2052 /**
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002053 * Close the tab, remove its associated title bar, and adjust mTabControl's
2054 * current tab to a valid value.
Leon Scroggins1f005d32009-08-10 17:36:42 -04002055 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07002056 /* package */ void closeTab(Tab t) {
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002057 int currentIndex = mTabControl.getCurrentIndex();
2058 int removeIndex = mTabControl.getTabIndex(t);
Leon Scroggins1f005d32009-08-10 17:36:42 -04002059 mTabControl.removeTab(t);
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002060 if (currentIndex >= removeIndex && currentIndex != 0) {
2061 currentIndex--;
2062 }
2063 mTabControl.setCurrentTab(mTabControl.getTab(currentIndex));
Andrei Popescua5bf1de2009-09-23 16:39:23 +01002064 resetTitleIconAndProgress();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002065 }
2066
Leon Scrogginsdcc5eeb2010-02-23 17:26:37 -05002067 /* package */ void goBackOnePageOrQuit() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002068 Tab current = mTabControl.getCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002069 if (current == null) {
2070 /*
2071 * Instead of finishing the activity, simply push this to the back
2072 * of the stack and let ActivityManager to choose the foreground
2073 * activity. As BrowserActivity is singleTask, it will be always the
2074 * root of the task. So we can use either true or false for
2075 * moveTaskToBack().
2076 */
2077 moveTaskToBack(true);
Grace Kloba00d85e72009-09-23 18:50:05 -07002078 return;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002079 }
2080 WebView w = current.getWebView();
2081 if (w.canGoBack()) {
2082 w.goBack();
2083 } else {
2084 // Check to see if we are closing a window that was created by
2085 // another window. If so, we switch back to that window.
Grace Kloba22ac16e2009-10-07 18:00:23 -07002086 Tab parent = current.getParentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002087 if (parent != null) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04002088 switchToTab(mTabControl.getTabIndex(parent));
2089 // Now we close the other tab
2090 closeTab(current);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002091 } else {
2092 if (current.closeOnExit()) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002093 // force the tab's inLoad() to be false as we are going to
2094 // either finish the activity or remove the tab. This will
2095 // ensure pauseWebViewTimers() taking action.
2096 mTabControl.getCurrentTab().clearInLoad();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002097 if (mTabControl.getTabCount() == 1) {
2098 finish();
2099 return;
2100 }
Mike Reed7bfa63b2009-05-28 11:08:32 -04002101 // call pauseWebViewTimers() now, we won't be able to call
2102 // it in onPause() as the WebView won't be valid.
Grace Klobaec1b5ad2009-08-18 08:42:32 -07002103 // Temporarily change mActivityInPause to be true as
2104 // pauseWebViewTimers() will do nothing if mActivityInPause
2105 // is false.
Grace Kloba918e1d72009-08-13 14:55:06 -07002106 boolean savedState = mActivityInPause;
2107 if (savedState) {
Grace Klobaec1b5ad2009-08-18 08:42:32 -07002108 Log.e(LOGTAG, "BrowserActivity is already paused "
2109 + "while handing goBackOnePageOrQuit.");
Grace Kloba918e1d72009-08-13 14:55:06 -07002110 }
2111 mActivityInPause = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -04002112 pauseWebViewTimers();
Grace Kloba918e1d72009-08-13 14:55:06 -07002113 mActivityInPause = savedState;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002114 removeTabFromContentView(current);
2115 mTabControl.removeTab(current);
2116 }
2117 /*
2118 * Instead of finishing the activity, simply push this to the back
2119 * of the stack and let ActivityManager to choose the foreground
2120 * activity. As BrowserActivity is singleTask, it will be always the
2121 * root of the task. So we can use either true or false for
2122 * moveTaskToBack().
2123 */
2124 moveTaskToBack(true);
2125 }
2126 }
2127 }
2128
Grace Kloba22ac16e2009-10-07 18:00:23 -07002129 boolean isMenuDown() {
2130 return mMenuIsDown;
2131 }
2132
Grace Kloba5942df02009-09-18 11:48:29 -07002133 @Override
2134 public boolean onKeyDown(int keyCode, KeyEvent event) {
Leon Scrogginsf65b50d2009-12-08 10:44:28 -05002135 // Even if MENU is already held down, we need to call to super to open
2136 // the IME on long press.
2137 if (KeyEvent.KEYCODE_MENU == keyCode) {
2138 mMenuIsDown = true;
2139 return super.onKeyDown(keyCode, event);
2140 }
Grace Kloba5942df02009-09-18 11:48:29 -07002141 // The default key mode is DEFAULT_KEYS_SEARCH_LOCAL. As the MENU is
2142 // still down, we don't want to trigger the search. Pretend to consume
2143 // the key and do nothing.
2144 if (mMenuIsDown) return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002145
Grace Kloba5942df02009-09-18 11:48:29 -07002146 switch(keyCode) {
Grace Kloba5942df02009-09-18 11:48:29 -07002147 case KeyEvent.KEYCODE_SPACE:
Grace Klobada0fe552009-09-22 18:17:24 -07002148 // WebView/WebTextView handle the keys in the KeyDown. As
2149 // the Activity's shortcut keys are only handled when WebView
2150 // doesn't, have to do it in onKeyDown instead of onKeyUp.
2151 if (event.isShiftPressed()) {
2152 getTopWindow().pageUp(false);
2153 } else {
2154 getTopWindow().pageDown(false);
2155 }
Grace Kloba5942df02009-09-18 11:48:29 -07002156 return true;
2157 case KeyEvent.KEYCODE_BACK:
2158 if (event.getRepeatCount() == 0) {
2159 event.startTracking();
2160 return true;
2161 } else if (mCustomView == null && mActiveTabsPage == null
2162 && event.isLongPress()) {
2163 bookmarksOrHistoryPicker(true);
2164 return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002165 }
Grace Kloba5942df02009-09-18 11:48:29 -07002166 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002167 }
Grace Kloba5942df02009-09-18 11:48:29 -07002168 return super.onKeyDown(keyCode, event);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002169 }
2170
Grace Kloba5942df02009-09-18 11:48:29 -07002171 @Override
2172 public boolean onKeyUp(int keyCode, KeyEvent event) {
2173 switch(keyCode) {
2174 case KeyEvent.KEYCODE_MENU:
2175 mMenuIsDown = false;
2176 break;
Grace Kloba5942df02009-09-18 11:48:29 -07002177 case KeyEvent.KEYCODE_BACK:
2178 if (event.isTracking() && !event.isCanceled()) {
2179 if (mCustomView != null) {
2180 // if a custom view is showing, hide it
Grace Kloba22ac16e2009-10-07 18:00:23 -07002181 mTabControl.getCurrentWebView().getWebChromeClient()
2182 .onHideCustomView();
Grace Kloba5942df02009-09-18 11:48:29 -07002183 } else if (mActiveTabsPage != null) {
2184 // if tab page is showing, hide it
2185 removeActiveTabPage(true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002186 } else {
Grace Kloba5942df02009-09-18 11:48:29 -07002187 WebView subwindow = mTabControl.getCurrentSubWindow();
2188 if (subwindow != null) {
2189 if (subwindow.canGoBack()) {
2190 subwindow.goBack();
2191 } else {
2192 dismissSubWindow(mTabControl.getCurrentTab());
2193 }
2194 } else {
2195 goBackOnePageOrQuit();
2196 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002197 }
Grace Kloba5942df02009-09-18 11:48:29 -07002198 return true;
2199 }
2200 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002201 }
Grace Kloba5942df02009-09-18 11:48:29 -07002202 return super.onKeyUp(keyCode, event);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002203 }
2204
Leon Scroggins68579392009-09-15 15:31:54 -04002205 /* package */ void stopLoading() {
Ben Murdochb7cc8b42009-09-28 10:59:09 +01002206 mDidStopLoad = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002207 resetTitleAndRevertLockIcon();
2208 WebView w = getTopWindow();
2209 w.stopLoading();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002210 // FIXME: before refactor, it is using mWebViewClient. So I keep the
2211 // same logic here. But for subwindow case, should we call into the main
2212 // WebView's onPageFinished as we never call its onPageStarted and if
2213 // the page finishes itself, we don't call onPageFinished.
2214 mTabControl.getCurrentWebView().getWebViewClient().onPageFinished(w,
2215 w.getUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08002216
2217 cancelStopToast();
2218 mStopToast = Toast
2219 .makeText(this, R.string.stopping, Toast.LENGTH_SHORT);
2220 mStopToast.show();
2221 }
2222
Grace Kloba22ac16e2009-10-07 18:00:23 -07002223 boolean didUserStopLoading() {
2224 return mDidStopLoad;
2225 }
2226
The Android Open Source Project0c908882009-03-03 19:32:16 -08002227 private void cancelStopToast() {
2228 if (mStopToast != null) {
2229 mStopToast.cancel();
2230 mStopToast = null;
2231 }
2232 }
2233
Grace Kloba22ac16e2009-10-07 18:00:23 -07002234 // called by a UI or non-UI thread to post the message
2235 public void postMessage(int what, int arg1, int arg2, Object obj,
2236 long delayMillis) {
2237 mHandler.sendMessageDelayed(mHandler.obtainMessage(what, arg1, arg2,
2238 obj), delayMillis);
2239 }
2240
2241 // called by a UI or non-UI thread to remove the message
2242 void removeMessages(int what, Object object) {
2243 mHandler.removeMessages(what, object);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002244 }
2245
2246 // public message ids
2247 public final static int LOAD_URL = 1001;
2248 public final static int STOP_LOAD = 1002;
2249
2250 // Message Ids
2251 private static final int FOCUS_NODE_HREF = 102;
Grace Kloba92c18a52009-07-31 23:48:32 -07002252 private static final int RELEASE_WAKELOCK = 107;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002253
Grace Kloba22ac16e2009-10-07 18:00:23 -07002254 static final int UPDATE_BOOKMARK_THUMBNAIL = 108;
Ben Murdoch2694e232009-09-29 09:41:11 +01002255
The Android Open Source Project0c908882009-03-03 19:32:16 -08002256 // Private handler for handling javascript and saving passwords
2257 private Handler mHandler = new Handler() {
2258
2259 public void handleMessage(Message msg) {
2260 switch (msg.what) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002261 case FOCUS_NODE_HREF:
Ben Murdoch2694e232009-09-29 09:41:11 +01002262 {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002263 String url = (String) msg.getData().get("url");
Ben Murdoch90d088c2009-11-17 18:14:04 +00002264 String title = (String) msg.getData().get("title");
The Android Open Source Project0c908882009-03-03 19:32:16 -08002265 if (url == null || url.length() == 0) {
2266 break;
2267 }
2268 HashMap focusNodeMap = (HashMap) msg.obj;
2269 WebView view = (WebView) focusNodeMap.get("webview");
2270 // Only apply the action if the top window did not change.
2271 if (getTopWindow() != view) {
2272 break;
2273 }
2274 switch (msg.arg1) {
2275 case R.id.open_context_menu_id:
2276 case R.id.view_image_context_menu_id:
Leon Scroggins92472e82010-02-17 16:32:28 -05002277 loadUrlFromContext(getTopWindow(), url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002278 break;
2279 case R.id.open_newtab_context_menu_id:
Grace Kloba22ac16e2009-10-07 18:00:23 -07002280 final Tab parent = mTabControl.getCurrentTab();
2281 final Tab newTab = openTab(url);
Grace Klobac9181842009-04-14 08:53:22 -07002282 if (newTab != parent) {
2283 parent.addChildTab(newTab);
2284 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002285 break;
2286 case R.id.bookmark_context_menu_id:
2287 Intent intent = new Intent(BrowserActivity.this,
2288 AddBookmarkPage.class);
2289 intent.putExtra("url", url);
Ben Murdoch90d088c2009-11-17 18:14:04 +00002290 intent.putExtra("title", title);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002291 startActivity(intent);
2292 break;
2293 case R.id.share_link_context_menu_id:
Leon Scroggins96afcb12009-12-10 12:35:56 -05002294 // See if this site has been visited before
2295 StringBuilder sb = new StringBuilder(
2296 Browser.BookmarkColumns.URL + " = ");
2297 DatabaseUtils.appendEscapedSQLString(sb, url);
2298 Cursor c = mResolver.query(Browser.BOOKMARKS_URI,
2299 Browser.HISTORY_PROJECTION,
2300 sb.toString(),
2301 null,
2302 null);
2303 if (c.moveToFirst()) {
2304 // The site has been visited before, so grab the
2305 // info from the database.
2306 Bitmap favicon = null;
2307 Bitmap thumbnail = null;
2308 String linkTitle = c.getString(Browser.
2309 HISTORY_PROJECTION_TITLE_INDEX);
2310 byte[] data = c.getBlob(Browser.
2311 HISTORY_PROJECTION_FAVICON_INDEX);
2312 if (data != null) {
2313 favicon = BitmapFactory.decodeByteArray(
2314 data, 0, data.length);
2315 }
2316 data = c.getBlob(Browser.
2317 HISTORY_PROJECTION_THUMBNAIL_INDEX);
2318 if (data != null) {
2319 thumbnail = BitmapFactory.decodeByteArray(
2320 data, 0, data.length);
2321 }
2322 sharePage(BrowserActivity.this,
2323 linkTitle, url, favicon, thumbnail);
2324 } else {
2325 Browser.sendString(BrowserActivity.this, url,
2326 getString(
2327 R.string.choosertitle_sharevia));
2328 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002329 break;
2330 case R.id.copy_link_context_menu_id:
2331 copy(url);
2332 break;
2333 case R.id.save_link_context_menu_id:
2334 case R.id.download_context_menu_id:
2335 onDownloadStartNoStream(url, null, null, null, -1);
2336 break;
2337 }
2338 break;
Ben Murdoch2694e232009-09-29 09:41:11 +01002339 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002340
2341 case LOAD_URL:
Leon Scroggins92472e82010-02-17 16:32:28 -05002342 loadUrlFromContext(getTopWindow(), (String) msg.obj);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002343 break;
2344
2345 case STOP_LOAD:
2346 stopLoading();
2347 break;
2348
The Android Open Source Project0c908882009-03-03 19:32:16 -08002349 case RELEASE_WAKELOCK:
2350 if (mWakeLock.isHeld()) {
2351 mWakeLock.release();
Grace Kloba5d0e02e2009-10-05 15:15:36 -07002352 // if we reach here, Browser should be still in the
2353 // background loading after WAKELOCK_TIMEOUT (5-min).
2354 // To avoid burning the battery, stop loading.
2355 mTabControl.stopAllLoading();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002356 }
2357 break;
Ben Murdoch2694e232009-09-29 09:41:11 +01002358
2359 case UPDATE_BOOKMARK_THUMBNAIL:
2360 WebView view = (WebView) msg.obj;
2361 if (view != null) {
2362 updateScreenshot(view);
2363 }
2364 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002365 }
2366 }
2367 };
2368
Leon Scroggins96afcb12009-12-10 12:35:56 -05002369 /**
2370 * Share a page, providing the title, url, favicon, and a screenshot. Uses
2371 * an {@link Intent} to launch the Activity chooser.
2372 * @param c Context used to launch a new Activity.
2373 * @param title Title of the page. Stored in the Intent with
Paul Westbrook03e6d392010-02-12 10:33:29 -08002374 * {@link Intent#EXTRA_SUBJECT}
Leon Scroggins96afcb12009-12-10 12:35:56 -05002375 * @param url URL of the page. Stored in the Intent with
2376 * {@link Intent#EXTRA_TEXT}
2377 * @param favicon Bitmap of the favicon for the page. Stored in the Intent
2378 * with {@link Browser#EXTRA_SHARE_FAVICON}
2379 * @param screenshot Bitmap of a screenshot of the page. Stored in the
2380 * Intent with {@link Browser#EXTRA_SHARE_SCREENSHOT}
2381 */
2382 public static final void sharePage(Context c, String title, String url,
2383 Bitmap favicon, Bitmap screenshot) {
2384 Intent send = new Intent(Intent.ACTION_SEND);
2385 send.setType("text/plain");
2386 send.putExtra(Intent.EXTRA_TEXT, url);
Paul Westbrook03e6d392010-02-12 10:33:29 -08002387 send.putExtra(Intent.EXTRA_SUBJECT, title);
Leon Scroggins96afcb12009-12-10 12:35:56 -05002388 send.putExtra(Browser.EXTRA_SHARE_FAVICON, favicon);
2389 send.putExtra(Browser.EXTRA_SHARE_SCREENSHOT, screenshot);
2390 try {
2391 c.startActivity(Intent.createChooser(send, c.getString(
2392 R.string.choosertitle_sharevia)));
2393 } catch(android.content.ActivityNotFoundException ex) {
2394 // if no app handles it, do nothing
2395 }
2396 }
2397
Leon Scroggins89c6d362009-07-15 16:54:37 -04002398 private void updateScreenshot(WebView view) {
2399 // If this is a bookmarked site, add a screenshot to the database.
2400 // FIXME: When should we update? Every time?
2401 // FIXME: Would like to make sure there is actually something to
2402 // draw, but the API for that (WebViewCore.pictureReady()) is not
2403 // currently accessible here.
Ben Murdochaac7aa62009-09-17 16:57:40 +01002404
Patrick Scottcb192b52010-04-14 14:38:55 -04002405 final Bitmap bm = createScreenshot(view);
2406 if (bm == null) {
2407 return;
Leon Scroggins89c6d362009-07-15 16:54:37 -04002408 }
Patrick Scottcb192b52010-04-14 14:38:55 -04002409
2410 final ContentResolver cr = getContentResolver();
2411 final String url = view.getUrl();
2412 final String originalUrl = view.getOriginalUrl();
2413
2414 new AsyncTask<Void, Void, Void>() {
2415 @Override
2416 protected Void doInBackground(Void... unused) {
2417 Cursor c = null;
2418 try {
2419 c = BrowserBookmarksAdapter.queryBookmarksForUrl(
2420 cr, originalUrl, url, true);
2421 if (c != null) {
2422 if (c.moveToFirst()) {
2423 ContentValues values = new ContentValues();
2424 final ByteArrayOutputStream os
2425 = new ByteArrayOutputStream();
2426 bm.compress(Bitmap.CompressFormat.PNG, 100, os);
2427 values.put(Browser.BookmarkColumns.THUMBNAIL,
2428 os.toByteArray());
2429 do {
2430 cr.update(ContentUris.withAppendedId(
2431 Browser.BOOKMARKS_URI, c.getInt(0)),
2432 values, null, null);
2433 } while (c.moveToNext());
2434 }
2435 }
2436 } catch (IllegalStateException e) {
2437 // Ignore
2438 } finally {
2439 if (c != null) c.close();
2440 }
2441 return null;
2442 }
2443 }.execute();
Leon Scroggins89c6d362009-07-15 16:54:37 -04002444 }
2445
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002446 /**
Leon Scrogginsf8551612009-09-24 16:06:02 -04002447 * Values for the size of the thumbnail created when taking a screenshot.
2448 * Lazily initialized. Instead of using these directly, use
2449 * getDesiredThumbnailWidth() or getDesiredThumbnailHeight().
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002450 */
Leon Scrogginsf8551612009-09-24 16:06:02 -04002451 private static int THUMBNAIL_WIDTH = 0;
2452 private static int THUMBNAIL_HEIGHT = 0;
2453
2454 /**
2455 * Return the desired width for thumbnail screenshots, which are stored in
2456 * the database, and used on the bookmarks screen.
2457 * @param context Context for finding out the density of the screen.
2458 * @return int desired width for thumbnail screenshot.
2459 */
2460 /* package */ static int getDesiredThumbnailWidth(Context context) {
2461 if (THUMBNAIL_WIDTH == 0) {
2462 float density = context.getResources().getDisplayMetrics().density;
2463 THUMBNAIL_WIDTH = (int) (90 * density);
2464 THUMBNAIL_HEIGHT = (int) (80 * density);
2465 }
2466 return THUMBNAIL_WIDTH;
2467 }
2468
2469 /**
2470 * Return the desired height for thumbnail screenshots, which are stored in
2471 * the database, and used on the bookmarks screen.
2472 * @param context Context for finding out the density of the screen.
2473 * @return int desired height for thumbnail screenshot.
2474 */
2475 /* package */ static int getDesiredThumbnailHeight(Context context) {
2476 // To ensure that they are both initialized.
2477 getDesiredThumbnailWidth(context);
2478 return THUMBNAIL_HEIGHT;
2479 }
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002480
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002481 private Bitmap createScreenshot(WebView view) {
2482 Picture thumbnail = view.capturePicture();
Leon Scroggins45800572009-09-29 16:38:47 -04002483 if (thumbnail == null) {
2484 return null;
2485 }
Leon Scrogginsf8551612009-09-24 16:06:02 -04002486 Bitmap bm = Bitmap.createBitmap(getDesiredThumbnailWidth(this),
Cary Clarkab168ba2010-04-08 09:11:28 -04002487 getDesiredThumbnailHeight(this), Bitmap.Config.RGB_565);
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002488 Canvas canvas = new Canvas(bm);
2489 // May need to tweak these values to determine what is the
2490 // best scale factor
Ben Murdoch2694e232009-09-29 09:41:11 +01002491 int thumbnailWidth = thumbnail.getWidth();
Ben Murdochae59c3f2009-10-20 18:30:28 +01002492 int thumbnailHeight = thumbnail.getHeight();
2493 float scaleFactorX = 1.0f;
2494 float scaleFactorY = 1.0f;
Ben Murdoch2694e232009-09-29 09:41:11 +01002495 if (thumbnailWidth > 0) {
Ben Murdochae59c3f2009-10-20 18:30:28 +01002496 scaleFactorX = (float) getDesiredThumbnailWidth(this) /
Ben Murdoch2694e232009-09-29 09:41:11 +01002497 (float)thumbnailWidth;
Ben Murdochae59c3f2009-10-20 18:30:28 +01002498 } else {
2499 return null;
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002500 }
Ben Murdochae59c3f2009-10-20 18:30:28 +01002501
2502 if (view.getWidth() > view.getHeight() &&
2503 thumbnailHeight < view.getHeight() && thumbnailHeight > 0) {
2504 // If the device is in landscape and the page is shorter
2505 // than the height of the view, stretch the thumbnail to fill the
2506 // space.
2507 scaleFactorY = (float) getDesiredThumbnailHeight(this) /
2508 (float)thumbnailHeight;
2509 } else {
2510 // In the portrait case, this looks nice.
2511 scaleFactorY = scaleFactorX;
2512 }
2513
2514 canvas.scale(scaleFactorX, scaleFactorY);
2515
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002516 thumbnail.draw(canvas);
2517 return bm;
2518 }
2519
The Android Open Source Project0c908882009-03-03 19:32:16 -08002520 // -------------------------------------------------------------------------
Grace Kloba22ac16e2009-10-07 18:00:23 -07002521 // Helper function for WebViewClient.
The Android Open Source Project0c908882009-03-03 19:32:16 -08002522 //-------------------------------------------------------------------------
2523
2524 // Use in overrideUrlLoading
2525 /* package */ final static String SCHEME_WTAI = "wtai://wp/";
2526 /* package */ final static String SCHEME_WTAI_MC = "wtai://wp/mc;";
2527 /* package */ final static String SCHEME_WTAI_SD = "wtai://wp/sd;";
2528 /* package */ final static String SCHEME_WTAI_AP = "wtai://wp/ap;";
2529
Leon Scroggins92472e82010-02-17 16:32:28 -05002530 // Keep this initial progress in sync with initialProgressValue (* 100)
2531 // in ProgressTracker.cpp
2532 private final static int INITIAL_PROGRESS = 10;
2533
Grace Kloba22ac16e2009-10-07 18:00:23 -07002534 void onPageStarted(WebView view, String url, Bitmap favicon) {
2535 // when BrowserActivity just starts, onPageStarted may be called before
2536 // onResume as it is triggered from onCreate. Call resumeWebViewTimers
2537 // to start the timer. As we won't switch tabs while an activity is in
2538 // pause state, we can ensure calling resume and pause in pair.
2539 if (mActivityInPause) resumeWebViewTimers();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002540
Grace Kloba22ac16e2009-10-07 18:00:23 -07002541 resetLockIcon(url);
2542 setUrlTitle(url, null);
2543 setFavicon(favicon);
Leon Scroggins8cf8f682009-11-04 11:13:50 -08002544 // Show some progress so that the user knows the page is beginning to
2545 // load
Leon Scroggins92472e82010-02-17 16:32:28 -05002546 onProgressChanged(view, INITIAL_PROGRESS);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002547 mDidStopLoad = false;
Grace Kloba22ac16e2009-10-07 18:00:23 -07002548 if (!mIsNetworkUp) createAndShowNetworkDialog();
Cary Clark2c326e62010-08-19 18:40:57 -04002549 closeDialogs();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002550 if (mSettings.isTracing()) {
2551 String host;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002552 try {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002553 WebAddress uri = new WebAddress(url);
2554 host = uri.mHost;
2555 } catch (android.net.ParseException ex) {
2556 host = "browser";
The Android Open Source Project0c908882009-03-03 19:32:16 -08002557 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002558 host = host.replace('.', '_');
2559 host += ".trace";
2560 mInTrace = true;
2561 Debug.startMethodTracing(host, 20 * 1024 * 1024);
2562 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002563
Grace Kloba22ac16e2009-10-07 18:00:23 -07002564 // Performance probe
2565 if (false) {
2566 mStart = SystemClock.uptimeMillis();
2567 mProcessStart = Process.getElapsedCpuTime();
2568 long[] sysCpu = new long[7];
2569 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2570 sysCpu, null)) {
2571 mUserStart = sysCpu[0] + sysCpu[1];
2572 mSystemStart = sysCpu[2];
2573 mIdleStart = sysCpu[3];
2574 mIrqStart = sysCpu[4] + sysCpu[5] + sysCpu[6];
2575 }
2576 mUiStart = SystemClock.currentThreadTimeMillis();
2577 }
2578 }
2579
2580 void onPageFinished(WebView view, String url) {
2581 // Reset the title and icon in case we stopped a provisional load.
2582 resetTitleAndIcon(view);
2583 // Update the lock icon image only once we are done loading
2584 updateLockIconToLatest();
2585 // pause the WebView timer and release the wake lock if it is finished
2586 // while BrowserActivity is in pause state.
2587 if (mActivityInPause && pauseWebViewTimers()) {
2588 if (mWakeLock.isHeld()) {
2589 mHandler.removeMessages(RELEASE_WAKELOCK);
2590 mWakeLock.release();
2591 }
2592 }
2593
2594 // Performance probe
2595 if (false) {
2596 long[] sysCpu = new long[7];
2597 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2598 sysCpu, null)) {
2599 String uiInfo = "UI thread used "
2600 + (SystemClock.currentThreadTimeMillis() - mUiStart)
2601 + " ms";
2602 if (LOGD_ENABLED) {
2603 Log.d(LOGTAG, uiInfo);
2604 }
2605 //The string that gets written to the log
2606 String performanceString = "It took total "
2607 + (SystemClock.uptimeMillis() - mStart)
2608 + " ms clock time to load the page."
2609 + "\nbrowser process used "
2610 + (Process.getElapsedCpuTime() - mProcessStart)
2611 + " ms, user processes used "
2612 + (sysCpu[0] + sysCpu[1] - mUserStart) * 10
2613 + " ms, kernel used "
2614 + (sysCpu[2] - mSystemStart) * 10
2615 + " ms, idle took " + (sysCpu[3] - mIdleStart) * 10
2616 + " ms and irq took "
2617 + (sysCpu[4] + sysCpu[5] + sysCpu[6] - mIrqStart)
2618 * 10 + " ms, " + uiInfo;
2619 if (LOGD_ENABLED) {
2620 Log.d(LOGTAG, performanceString + "\nWebpage: " + url);
2621 }
2622 if (url != null) {
2623 // strip the url to maintain consistency
2624 String newUrl = new String(url);
2625 if (newUrl.startsWith("http://www.")) {
2626 newUrl = newUrl.substring(11);
2627 } else if (newUrl.startsWith("http://")) {
2628 newUrl = newUrl.substring(7);
2629 } else if (newUrl.startsWith("https://www.")) {
2630 newUrl = newUrl.substring(12);
2631 } else if (newUrl.startsWith("https://")) {
2632 newUrl = newUrl.substring(8);
2633 }
2634 if (LOGD_ENABLED) {
2635 Log.d(LOGTAG, newUrl + " loaded");
2636 }
Grace Kloba5b078b52009-06-24 20:23:41 -07002637 }
2638 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002639 }
Grace Kloba5b078b52009-06-24 20:23:41 -07002640
Grace Kloba22ac16e2009-10-07 18:00:23 -07002641 if (mInTrace) {
2642 mInTrace = false;
2643 Debug.stopMethodTracing();
2644 }
2645 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002646
Grace Kloba22ac16e2009-10-07 18:00:23 -07002647 boolean shouldOverrideUrlLoading(WebView view, String url) {
2648 if (url.startsWith(SCHEME_WTAI)) {
2649 // wtai://wp/mc;number
2650 // number=string(phone-number)
2651 if (url.startsWith(SCHEME_WTAI_MC)) {
2652 Intent intent = new Intent(Intent.ACTION_VIEW,
2653 Uri.parse(WebView.SCHEME_TEL +
2654 url.substring(SCHEME_WTAI_MC.length())));
2655 startActivity(intent);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002656 return true;
2657 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002658 // wtai://wp/sd;dtmf
2659 // dtmf=string(dialstring)
2660 if (url.startsWith(SCHEME_WTAI_SD)) {
2661 // TODO: only send when there is active voice connection
2662 return false;
2663 }
2664 // wtai://wp/ap;number;name
2665 // number=string(phone-number)
2666 // name=string
2667 if (url.startsWith(SCHEME_WTAI_AP)) {
2668 // TODO
2669 return false;
2670 }
2671 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002672
Grace Kloba22ac16e2009-10-07 18:00:23 -07002673 // The "about:" schemes are internal to the browser; don't want these to
2674 // be dispatched to other apps.
2675 if (url.startsWith("about:")) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002676 return false;
2677 }
2678
Grace Kloba22ac16e2009-10-07 18:00:23 -07002679 Intent intent;
2680 // perform generic parsing of the URI to turn it into an Intent.
2681 try {
2682 intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME);
2683 } catch (URISyntaxException ex) {
2684 Log.w("Browser", "Bad URI " + url + ": " + ex.getMessage());
2685 return false;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002686 }
2687
Grace Kloba22ac16e2009-10-07 18:00:23 -07002688 // check whether the intent can be resolved. If not, we will see
2689 // whether we can download it from the Market.
2690 if (getPackageManager().resolveActivity(intent, 0) == null) {
2691 String packagename = intent.getPackage();
2692 if (packagename != null) {
2693 intent = new Intent(Intent.ACTION_VIEW, Uri
2694 .parse("market://search?q=pname:" + packagename));
2695 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2696 startActivity(intent);
2697 return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002698 } else {
2699 return false;
2700 }
2701 }
2702
Grace Kloba22ac16e2009-10-07 18:00:23 -07002703 // sanitize the Intent, ensuring web pages can not bypass browser
2704 // security (only access to BROWSABLE activities).
2705 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2706 intent.setComponent(null);
2707 try {
2708 if (startActivityIfNeeded(intent, -1)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002709 return true;
2710 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002711 } catch (ActivityNotFoundException ex) {
2712 // ignore the error. If no application can handle the URL,
2713 // eg about:blank, assume the browser can handle it.
2714 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002715
Grace Kloba22ac16e2009-10-07 18:00:23 -07002716 if (mMenuIsDown) {
2717 openTab(url);
2718 closeOptionsMenu();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002719 return true;
2720 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002721 return false;
2722 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002723
Grace Kloba22ac16e2009-10-07 18:00:23 -07002724 // -------------------------------------------------------------------------
2725 // Helper function for WebChromeClient
2726 // -------------------------------------------------------------------------
The Android Open Source Project0c908882009-03-03 19:32:16 -08002727
Grace Kloba22ac16e2009-10-07 18:00:23 -07002728 void onProgressChanged(WebView view, int newProgress) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002729 mFakeTitleBar.setProgress(newProgress);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002730
Grace Kloba22ac16e2009-10-07 18:00:23 -07002731 if (newProgress == 100) {
2732 // onProgressChanged() may continue to be called after the main
2733 // frame has finished loading, as any remaining sub frames continue
2734 // to load. We'll only get called once though with newProgress as
2735 // 100 when everything is loaded. (onPageFinished is called once
2736 // when the main frame completes loading regardless of the state of
2737 // any sub frames so calls to onProgressChanges may continue after
2738 // onPageFinished has executed)
2739 if (mInLoad) {
2740 mInLoad = false;
Leon Scrogginsa27ff192009-09-14 12:58:04 -04002741 updateInLoadMenuItems();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002742 // If the options menu is open, leave the title bar
2743 if (!mOptionsMenuOpen || !mIconView) {
2744 hideFakeTitleBar();
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07002745 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002746 }
Leon Scrogginsaa37e7f2010-03-05 11:51:20 -05002747 } else {
2748 if (!mInLoad) {
2749 // onPageFinished may have already been called but a subframe is
2750 // still loading and updating the progress. Reset mInLoad and
2751 // update the menu items.
2752 mInLoad = true;
2753 updateInLoadMenuItems();
2754 }
2755 // When the page first begins to load, the Activity may still be
2756 // paused, in which case showFakeTitleBar will do nothing. Call
2757 // again as the page continues to load so that it will be shown.
2758 // (Calling it will the fake title bar is already showing will also
2759 // do nothing.
Grace Kloba22ac16e2009-10-07 18:00:23 -07002760 if (!mOptionsMenuOpen || mIconView) {
2761 // This page has begun to load, so show the title bar
2762 showFakeTitleBar();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002763 }
2764 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002765 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002766
Grace Kloba22ac16e2009-10-07 18:00:23 -07002767 void onShowCustomView(View view, WebChromeClient.CustomViewCallback callback) {
Derek Sollenberger8ff57db2009-12-08 15:39:55 -05002768 // if a view already exists then immediately terminate the new one
2769 if (mCustomView != null) {
2770 callback.onCustomViewHidden();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002771 return;
Derek Sollenberger8ff57db2009-12-08 15:39:55 -05002772 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002773
2774 // Add the custom view to its container.
2775 mCustomViewContainer.addView(view, COVER_SCREEN_GRAVITY_CENTER);
2776 mCustomView = view;
2777 mCustomViewCallback = callback;
2778 // Save the menu state and set it to empty while the custom
2779 // view is showing.
2780 mOldMenuState = mMenuState;
2781 mMenuState = EMPTY_MENU;
2782 // Hide the content view.
2783 mContentView.setVisibility(View.GONE);
2784 // Finally show the custom view container.
Andrei Popescu163ab742009-10-20 17:58:23 +01002785 setStatusBarVisibility(false);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002786 mCustomViewContainer.setVisibility(View.VISIBLE);
2787 mCustomViewContainer.bringToFront();
2788 }
2789
2790 void onHideCustomView() {
2791 if (mCustomView == null)
2792 return;
2793
2794 // Hide the custom view.
2795 mCustomView.setVisibility(View.GONE);
2796 // Remove the custom view from its container.
2797 mCustomViewContainer.removeView(mCustomView);
2798 mCustomView = null;
2799 // Reset the old menu state.
2800 mMenuState = mOldMenuState;
2801 mOldMenuState = EMPTY_MENU;
2802 mCustomViewContainer.setVisibility(View.GONE);
2803 mCustomViewCallback.onCustomViewHidden();
2804 // Show the content view.
Andrei Popescu163ab742009-10-20 17:58:23 +01002805 setStatusBarVisibility(true);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002806 mContentView.setVisibility(View.VISIBLE);
2807 }
2808
2809 Bitmap getDefaultVideoPoster() {
2810 if (mDefaultVideoPoster == null) {
2811 mDefaultVideoPoster = BitmapFactory.decodeResource(
2812 getResources(), R.drawable.default_video_poster);
Patrick Scott3918d442009-08-04 13:22:29 -04002813 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002814 return mDefaultVideoPoster;
2815 }
Patrick Scott3918d442009-08-04 13:22:29 -04002816
Grace Kloba22ac16e2009-10-07 18:00:23 -07002817 View getVideoLoadingProgressView() {
2818 if (mVideoProgressView == null) {
2819 LayoutInflater inflater = LayoutInflater.from(BrowserActivity.this);
2820 mVideoProgressView = inflater.inflate(
2821 R.layout.video_loading_progress, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002822 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002823 return mVideoProgressView;
2824 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002825
Leon Scroggins8d5fa432009-10-02 15:55:59 -04002826 /*
2827 * The Object used to inform the WebView of the file to upload.
2828 */
2829 private ValueCallback<Uri> mUploadMessage;
2830
Grace Kloba22ac16e2009-10-07 18:00:23 -07002831 void openFileChooser(ValueCallback<Uri> uploadMsg) {
2832 if (mUploadMessage != null) return;
2833 mUploadMessage = uploadMsg;
2834 Intent i = new Intent(Intent.ACTION_GET_CONTENT);
2835 i.addCategory(Intent.CATEGORY_OPENABLE);
2836 i.setType("*/*");
2837 BrowserActivity.this.startActivityForResult(Intent.createChooser(i,
2838 getString(R.string.choose_upload)), FILE_SELECTED);
2839 }
2840
2841 // -------------------------------------------------------------------------
2842 // Implement functions for DownloadListener
2843 // -------------------------------------------------------------------------
2844
The Android Open Source Project0c908882009-03-03 19:32:16 -08002845 /**
2846 * Notify the host application a download should be done, or that
2847 * the data should be streamed if a streaming viewer is available.
2848 * @param url The full url to the content that should be downloaded
2849 * @param contentDisposition Content-disposition http header, if
2850 * present.
2851 * @param mimetype The mimetype of the content reported by the server
2852 * @param contentLength The file size reported by the server
2853 */
2854 public void onDownloadStart(String url, String userAgent,
2855 String contentDisposition, String mimetype, long contentLength) {
2856 // if we're dealing wih A/V content that's not explicitly marked
2857 // for download, check if it's streamable.
2858 if (contentDisposition == null
Patrick Scotte1fb9662009-08-31 14:31:52 -04002859 || !contentDisposition.regionMatches(
2860 true, 0, "attachment", 0, 10)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002861 // query the package manager to see if there's a registered handler
2862 // that matches.
2863 Intent intent = new Intent(Intent.ACTION_VIEW);
2864 intent.setDataAndType(Uri.parse(url), mimetype);
Patrick Scotte1fb9662009-08-31 14:31:52 -04002865 ResolveInfo info = getPackageManager().resolveActivity(intent,
2866 PackageManager.MATCH_DEFAULT_ONLY);
2867 if (info != null) {
2868 ComponentName myName = getComponentName();
2869 // If we resolved to ourselves, we don't want to attempt to
2870 // load the url only to try and download it again.
2871 if (!myName.getPackageName().equals(
2872 info.activityInfo.packageName)
2873 || !myName.getClassName().equals(
2874 info.activityInfo.name)) {
2875 // someone (other than us) knows how to handle this mime
2876 // type with this scheme, don't download.
2877 try {
2878 startActivity(intent);
2879 return;
2880 } catch (ActivityNotFoundException ex) {
2881 if (LOGD_ENABLED) {
2882 Log.d(LOGTAG, "activity not found for " + mimetype
2883 + " over " + Uri.parse(url).getScheme(),
2884 ex);
2885 }
2886 // Best behavior is to fall back to a download in this
2887 // case
The Android Open Source Project0c908882009-03-03 19:32:16 -08002888 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002889 }
2890 }
2891 }
2892 onDownloadStartNoStream(url, userAgent, contentDisposition, mimetype, contentLength);
2893 }
2894
Kristian Monsenfa52d172010-03-25 18:29:21 +00002895 // This is to work around the fact that java.net.URI throws Exceptions
2896 // instead of just encoding URL's properly
2897 // Helper method for onDownloadStartNoStream
2898 private static String encodePath(String path) {
2899 char[] chars = path.toCharArray();
2900
2901 boolean needed = false;
2902 for (char c : chars) {
2903 if (c == '[' || c == ']') {
2904 needed = true;
2905 break;
2906 }
2907 }
2908 if (needed == false) {
2909 return path;
2910 }
2911
2912 StringBuilder sb = new StringBuilder("");
2913 for (char c : chars) {
2914 if (c == '[' || c == ']') {
2915 sb.append('%');
2916 sb.append(Integer.toHexString(c));
2917 } else {
2918 sb.append(c);
2919 }
2920 }
2921
2922 return sb.toString();
2923 }
2924
The Android Open Source Project0c908882009-03-03 19:32:16 -08002925 /**
2926 * Notify the host application a download should be done, even if there
2927 * is a streaming viewer available for thise type.
2928 * @param url The full url to the content that should be downloaded
2929 * @param contentDisposition Content-disposition http header, if
2930 * present.
2931 * @param mimetype The mimetype of the content reported by the server
2932 * @param contentLength The file size reported by the server
2933 */
2934 /*package */ void onDownloadStartNoStream(String url, String userAgent,
2935 String contentDisposition, String mimetype, long contentLength) {
2936
2937 String filename = URLUtil.guessFileName(url,
2938 contentDisposition, mimetype);
2939
2940 // Check to see if we have an SDCard
2941 String status = Environment.getExternalStorageState();
2942 if (!status.equals(Environment.MEDIA_MOUNTED)) {
2943 int title;
2944 String msg;
2945
2946 // Check to see if the SDCard is busy, same as the music app
2947 if (status.equals(Environment.MEDIA_SHARED)) {
2948 msg = getString(R.string.download_sdcard_busy_dlg_msg);
2949 title = R.string.download_sdcard_busy_dlg_title;
2950 } else {
2951 msg = getString(R.string.download_no_sdcard_dlg_msg, filename);
2952 title = R.string.download_no_sdcard_dlg_title;
2953 }
2954
2955 new AlertDialog.Builder(this)
2956 .setTitle(title)
2957 .setIcon(android.R.drawable.ic_dialog_alert)
2958 .setMessage(msg)
2959 .setPositiveButton(R.string.ok, null)
2960 .show();
2961 return;
2962 }
2963
Kristian Monsenfa52d172010-03-25 18:29:21 +00002964 // java.net.URI is a lot stricter than KURL so we have to encode some
2965 // extra characters. Fix for b 2538060 and b 1634719
2966 WebAddress webAddress;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002967 try {
Kristian Monsenfa52d172010-03-25 18:29:21 +00002968 webAddress = new WebAddress(url);
2969 webAddress.mPath = encodePath(webAddress.mPath);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002970 } catch (Exception e) {
Kristian Monsenfa52d172010-03-25 18:29:21 +00002971 // This only happens for very bad urls, we want to chatch the
2972 // exception here
2973 Log.e(LOGTAG, "Exception trying to parse url:" + url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002974 return;
2975 }
2976
2977 // XXX: Have to use the old url since the cookies were stored using the
2978 // old percent-encoded url.
2979 String cookies = CookieManager.getInstance().getCookie(url);
2980
2981 ContentValues values = new ContentValues();
Kristian Monsenfa52d172010-03-25 18:29:21 +00002982 values.put(Downloads.Impl.COLUMN_URI, webAddress.toString());
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08002983 values.put(Downloads.Impl.COLUMN_COOKIE_DATA, cookies);
2984 values.put(Downloads.Impl.COLUMN_USER_AGENT, userAgent);
2985 values.put(Downloads.Impl.COLUMN_NOTIFICATION_PACKAGE,
The Android Open Source Project0c908882009-03-03 19:32:16 -08002986 getPackageName());
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08002987 values.put(Downloads.Impl.COLUMN_NOTIFICATION_CLASS,
Leon Scrogginsa563d092010-04-19 16:53:49 -04002988 OpenDownloadReceiver.class.getCanonicalName());
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08002989 values.put(Downloads.Impl.COLUMN_VISIBILITY,
2990 Downloads.Impl.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
2991 values.put(Downloads.Impl.COLUMN_MIME_TYPE, mimetype);
2992 values.put(Downloads.Impl.COLUMN_FILE_NAME_HINT, filename);
Kristian Monsenfa52d172010-03-25 18:29:21 +00002993 values.put(Downloads.Impl.COLUMN_DESCRIPTION, webAddress.mHost);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002994 if (contentLength > 0) {
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08002995 values.put(Downloads.Impl.COLUMN_TOTAL_BYTES, contentLength);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002996 }
2997 if (mimetype == null) {
2998 // We must have long pressed on a link or image to download it. We
2999 // are not sure of the mimetype in this case, so do a head request
3000 new FetchUrlMimeType(this).execute(values);
3001 } else {
3002 final Uri contentUri =
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08003003 getContentResolver().insert(Downloads.Impl.CONTENT_URI, values);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003004 }
Leon Scroggins9191a7f2010-03-18 14:44:44 -04003005 Toast.makeText(this, R.string.download_pending, Toast.LENGTH_SHORT)
3006 .show();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003007 }
3008
Grace Kloba22ac16e2009-10-07 18:00:23 -07003009 // -------------------------------------------------------------------------
3010
The Android Open Source Project0c908882009-03-03 19:32:16 -08003011 /**
3012 * Resets the lock icon. This method is called when we start a new load and
3013 * know the url to be loaded.
3014 */
3015 private void resetLockIcon(String url) {
3016 // Save the lock-icon state (we revert to it if the load gets cancelled)
Grace Kloba22ac16e2009-10-07 18:00:23 -07003017 mTabControl.getCurrentTab().resetLockIcon(url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003018 updateLockIconImage(LOCK_ICON_UNSECURE);
3019 }
3020
The Android Open Source Project0c908882009-03-03 19:32:16 -08003021 /**
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04003022 * Update the lock icon to correspond to our latest state.
3023 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003024 private void updateLockIconToLatest() {
3025 updateLockIconImage(mTabControl.getCurrentTab().getLockIconType());
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04003026 }
3027
3028 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08003029 * Updates the lock-icon image in the title-bar.
3030 */
3031 private void updateLockIconImage(int lockIconType) {
3032 Drawable d = null;
3033 if (lockIconType == LOCK_ICON_SECURE) {
3034 d = mSecLockIcon;
3035 } else if (lockIconType == LOCK_ICON_MIXED) {
3036 d = mMixLockIcon;
3037 }
Leon Scroggins68579392009-09-15 15:31:54 -04003038 mTitleBar.setLock(d);
Leon Scrogginsfe87bd32009-10-06 10:10:00 -04003039 mFakeTitleBar.setLock(d);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003040 }
3041
3042 /**
3043 * Displays a page-info dialog.
3044 * @param tab The tab to show info about
3045 * @param fromShowSSLCertificateOnError The flag that indicates whether
3046 * this dialog was opened from the SSL-certificate-on-error dialog or
3047 * not. This is important, since we need to know whether to return to
3048 * the parent dialog or simply dismiss.
3049 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003050 private void showPageInfo(final Tab tab,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003051 final boolean fromShowSSLCertificateOnError) {
3052 final LayoutInflater factory = LayoutInflater
3053 .from(this);
3054
3055 final View pageInfoView = factory.inflate(R.layout.page_info, null);
3056
3057 final WebView view = tab.getWebView();
3058
3059 String url = null;
3060 String title = null;
3061
3062 if (view == null) {
3063 url = tab.getUrl();
3064 title = tab.getTitle();
3065 } else if (view == mTabControl.getCurrentWebView()) {
3066 // Use the cached title and url if this is the current WebView
3067 url = mUrl;
3068 title = mTitle;
3069 } else {
3070 url = view.getUrl();
3071 title = view.getTitle();
3072 }
3073
3074 if (url == null) {
3075 url = "";
3076 }
3077 if (title == null) {
3078 title = "";
3079 }
3080
3081 ((TextView) pageInfoView.findViewById(R.id.address)).setText(url);
3082 ((TextView) pageInfoView.findViewById(R.id.title)).setText(title);
3083
3084 mPageInfoView = tab;
Leon Scrogginsc7b92f82010-01-11 18:17:31 -05003085 mPageInfoFromShowSSLCertificateOnError = fromShowSSLCertificateOnError;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003086
3087 AlertDialog.Builder alertDialogBuilder =
3088 new AlertDialog.Builder(this)
3089 .setTitle(R.string.page_info).setIcon(android.R.drawable.ic_dialog_info)
3090 .setView(pageInfoView)
3091 .setPositiveButton(
3092 R.string.ok,
3093 new DialogInterface.OnClickListener() {
3094 public void onClick(DialogInterface dialog,
3095 int whichButton) {
3096 mPageInfoDialog = null;
3097 mPageInfoView = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003098
3099 // if we came here from the SSL error dialog
3100 if (fromShowSSLCertificateOnError) {
3101 // go back to the SSL error dialog
3102 showSSLCertificateOnError(
3103 mSSLCertificateOnErrorView,
3104 mSSLCertificateOnErrorHandler,
3105 mSSLCertificateOnErrorError);
3106 }
3107 }
3108 })
3109 .setOnCancelListener(
3110 new DialogInterface.OnCancelListener() {
3111 public void onCancel(DialogInterface dialog) {
3112 mPageInfoDialog = null;
3113 mPageInfoView = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003114
3115 // if we came here from the SSL error dialog
3116 if (fromShowSSLCertificateOnError) {
3117 // go back to the SSL error dialog
3118 showSSLCertificateOnError(
3119 mSSLCertificateOnErrorView,
3120 mSSLCertificateOnErrorHandler,
3121 mSSLCertificateOnErrorError);
3122 }
3123 }
3124 });
3125
3126 // if we have a main top-level page SSL certificate set or a certificate
3127 // error
3128 if (fromShowSSLCertificateOnError ||
3129 (view != null && view.getCertificate() != null)) {
3130 // add a 'View Certificate' button
3131 alertDialogBuilder.setNeutralButton(
3132 R.string.view_certificate,
3133 new DialogInterface.OnClickListener() {
3134 public void onClick(DialogInterface dialog,
3135 int whichButton) {
3136 mPageInfoDialog = null;
3137 mPageInfoView = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003138
3139 // if we came here from the SSL error dialog
3140 if (fromShowSSLCertificateOnError) {
3141 // go back to the SSL error dialog
3142 showSSLCertificateOnError(
3143 mSSLCertificateOnErrorView,
3144 mSSLCertificateOnErrorHandler,
3145 mSSLCertificateOnErrorError);
3146 } else {
3147 // otherwise, display the top-most certificate from
3148 // the chain
3149 if (view.getCertificate() != null) {
3150 showSSLCertificate(tab);
3151 }
3152 }
3153 }
3154 });
3155 }
3156
3157 mPageInfoDialog = alertDialogBuilder.show();
3158 }
3159
3160 /**
3161 * Displays the main top-level page SSL certificate dialog
3162 * (accessible from the Page-Info dialog).
3163 * @param tab The tab to show certificate for.
3164 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003165 private void showSSLCertificate(final Tab tab) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003166 final View certificateView =
3167 inflateCertificateView(tab.getWebView().getCertificate());
3168 if (certificateView == null) {
3169 return;
3170 }
3171
3172 LayoutInflater factory = LayoutInflater.from(this);
3173
3174 final LinearLayout placeholder =
3175 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3176
3177 LinearLayout ll = (LinearLayout) factory.inflate(
3178 R.layout.ssl_success, placeholder);
3179 ((TextView)ll.findViewById(R.id.success))
3180 .setText(R.string.ssl_certificate_is_valid);
3181
3182 mSSLCertificateView = tab;
3183 mSSLCertificateDialog =
3184 new AlertDialog.Builder(this)
3185 .setTitle(R.string.ssl_certificate).setIcon(
3186 R.drawable.ic_dialog_browser_certificate_secure)
3187 .setView(certificateView)
3188 .setPositiveButton(R.string.ok,
3189 new DialogInterface.OnClickListener() {
3190 public void onClick(DialogInterface dialog,
3191 int whichButton) {
3192 mSSLCertificateDialog = null;
3193 mSSLCertificateView = null;
3194
3195 showPageInfo(tab, false);
3196 }
3197 })
3198 .setOnCancelListener(
3199 new DialogInterface.OnCancelListener() {
3200 public void onCancel(DialogInterface dialog) {
3201 mSSLCertificateDialog = null;
3202 mSSLCertificateView = null;
3203
3204 showPageInfo(tab, false);
3205 }
3206 })
3207 .show();
3208 }
3209
3210 /**
3211 * Displays the SSL error certificate dialog.
3212 * @param view The target web-view.
3213 * @param handler The SSL error handler responsible for cancelling the
3214 * connection that resulted in an SSL error or proceeding per user request.
3215 * @param error The SSL error object.
3216 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003217 void showSSLCertificateOnError(
The Android Open Source Project0c908882009-03-03 19:32:16 -08003218 final WebView view, final SslErrorHandler handler, final SslError error) {
3219
3220 final View certificateView =
3221 inflateCertificateView(error.getCertificate());
3222 if (certificateView == null) {
3223 return;
3224 }
3225
3226 LayoutInflater factory = LayoutInflater.from(this);
3227
3228 final LinearLayout placeholder =
3229 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3230
3231 if (error.hasError(SslError.SSL_UNTRUSTED)) {
3232 LinearLayout ll = (LinearLayout)factory
3233 .inflate(R.layout.ssl_warning, placeholder);
3234 ((TextView)ll.findViewById(R.id.warning))
3235 .setText(R.string.ssl_untrusted);
3236 }
3237
3238 if (error.hasError(SslError.SSL_IDMISMATCH)) {
3239 LinearLayout ll = (LinearLayout)factory
3240 .inflate(R.layout.ssl_warning, placeholder);
3241 ((TextView)ll.findViewById(R.id.warning))
3242 .setText(R.string.ssl_mismatch);
3243 }
3244
3245 if (error.hasError(SslError.SSL_EXPIRED)) {
3246 LinearLayout ll = (LinearLayout)factory
3247 .inflate(R.layout.ssl_warning, placeholder);
3248 ((TextView)ll.findViewById(R.id.warning))
3249 .setText(R.string.ssl_expired);
3250 }
3251
3252 if (error.hasError(SslError.SSL_NOTYETVALID)) {
3253 LinearLayout ll = (LinearLayout)factory
3254 .inflate(R.layout.ssl_warning, placeholder);
3255 ((TextView)ll.findViewById(R.id.warning))
3256 .setText(R.string.ssl_not_yet_valid);
3257 }
3258
3259 mSSLCertificateOnErrorHandler = handler;
3260 mSSLCertificateOnErrorView = view;
3261 mSSLCertificateOnErrorError = error;
3262 mSSLCertificateOnErrorDialog =
3263 new AlertDialog.Builder(this)
3264 .setTitle(R.string.ssl_certificate).setIcon(
3265 R.drawable.ic_dialog_browser_certificate_partially_secure)
3266 .setView(certificateView)
3267 .setPositiveButton(R.string.ok,
3268 new DialogInterface.OnClickListener() {
3269 public void onClick(DialogInterface dialog,
3270 int whichButton) {
3271 mSSLCertificateOnErrorDialog = null;
3272 mSSLCertificateOnErrorView = null;
3273 mSSLCertificateOnErrorHandler = null;
3274 mSSLCertificateOnErrorError = null;
3275
Grace Kloba22ac16e2009-10-07 18:00:23 -07003276 view.getWebViewClient().onReceivedSslError(
3277 view, handler, error);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003278 }
3279 })
3280 .setNeutralButton(R.string.page_info_view,
3281 new DialogInterface.OnClickListener() {
3282 public void onClick(DialogInterface dialog,
3283 int whichButton) {
3284 mSSLCertificateOnErrorDialog = null;
3285
3286 // do not clear the dialog state: we will
3287 // need to show the dialog again once the
3288 // user is done exploring the page-info details
3289
3290 showPageInfo(mTabControl.getTabFromView(view),
3291 true);
3292 }
3293 })
3294 .setOnCancelListener(
3295 new DialogInterface.OnCancelListener() {
3296 public void onCancel(DialogInterface dialog) {
3297 mSSLCertificateOnErrorDialog = null;
3298 mSSLCertificateOnErrorView = null;
3299 mSSLCertificateOnErrorHandler = null;
3300 mSSLCertificateOnErrorError = null;
3301
Grace Kloba22ac16e2009-10-07 18:00:23 -07003302 view.getWebViewClient().onReceivedSslError(
3303 view, handler, error);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003304 }
3305 })
3306 .show();
3307 }
3308
3309 /**
3310 * Inflates the SSL certificate view (helper method).
3311 * @param certificate The SSL certificate.
3312 * @return The resultant certificate view with issued-to, issued-by,
3313 * issued-on, expires-on, and possibly other fields set.
3314 * If the input certificate is null, returns null.
3315 */
3316 private View inflateCertificateView(SslCertificate certificate) {
3317 if (certificate == null) {
3318 return null;
3319 }
3320
3321 LayoutInflater factory = LayoutInflater.from(this);
3322
3323 View certificateView = factory.inflate(
3324 R.layout.ssl_certificate, null);
3325
3326 // issued to:
3327 SslCertificate.DName issuedTo = certificate.getIssuedTo();
3328 if (issuedTo != null) {
3329 ((TextView) certificateView.findViewById(R.id.to_common))
3330 .setText(issuedTo.getCName());
3331 ((TextView) certificateView.findViewById(R.id.to_org))
3332 .setText(issuedTo.getOName());
3333 ((TextView) certificateView.findViewById(R.id.to_org_unit))
3334 .setText(issuedTo.getUName());
3335 }
3336
3337 // issued by:
3338 SslCertificate.DName issuedBy = certificate.getIssuedBy();
3339 if (issuedBy != null) {
3340 ((TextView) certificateView.findViewById(R.id.by_common))
3341 .setText(issuedBy.getCName());
3342 ((TextView) certificateView.findViewById(R.id.by_org))
3343 .setText(issuedBy.getOName());
3344 ((TextView) certificateView.findViewById(R.id.by_org_unit))
3345 .setText(issuedBy.getUName());
3346 }
3347
3348 // issued on:
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003349 String issuedOn = formatCertificateDate(
3350 certificate.getValidNotBeforeDate());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003351 ((TextView) certificateView.findViewById(R.id.issued_on))
3352 .setText(issuedOn);
3353
3354 // expires on:
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003355 String expiresOn = formatCertificateDate(
3356 certificate.getValidNotAfterDate());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003357 ((TextView) certificateView.findViewById(R.id.expires_on))
3358 .setText(expiresOn);
3359
3360 return certificateView;
3361 }
3362
3363 /**
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003364 * Formats the certificate date to a properly localized date string.
The Android Open Source Project0c908882009-03-03 19:32:16 -08003365 * @return Properly localized version of the certificate date string and
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003366 * the "" if it fails to localize.
The Android Open Source Project0c908882009-03-03 19:32:16 -08003367 */
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003368 private String formatCertificateDate(Date certificateDate) {
3369 if (certificateDate == null) {
3370 return "";
The Android Open Source Project0c908882009-03-03 19:32:16 -08003371 }
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003372 String formattedDate = DateFormat.getDateFormat(this).format(certificateDate);
3373 if (formattedDate == null) {
3374 return "";
3375 }
3376 return formattedDate;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003377 }
3378
3379 /**
3380 * Displays an http-authentication dialog.
3381 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003382 void showHttpAuthentication(final HttpAuthHandler handler,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003383 final String host, final String realm, final String title,
3384 final String name, final String password, int focusId) {
3385 LayoutInflater factory = LayoutInflater.from(this);
3386 final View v = factory
3387 .inflate(R.layout.http_authentication, null);
3388 if (name != null) {
3389 ((EditText) v.findViewById(R.id.username_edit)).setText(name);
3390 }
3391 if (password != null) {
3392 ((EditText) v.findViewById(R.id.password_edit)).setText(password);
3393 }
3394
3395 String titleText = title;
3396 if (titleText == null) {
3397 titleText = getText(R.string.sign_in_to).toString().replace(
3398 "%s1", host).replace("%s2", realm);
3399 }
3400
3401 mHttpAuthHandler = handler;
3402 AlertDialog dialog = new AlertDialog.Builder(this)
3403 .setTitle(titleText)
3404 .setIcon(android.R.drawable.ic_dialog_alert)
3405 .setView(v)
3406 .setPositiveButton(R.string.action,
3407 new DialogInterface.OnClickListener() {
3408 public void onClick(DialogInterface dialog,
3409 int whichButton) {
3410 String nm = ((EditText) v
3411 .findViewById(R.id.username_edit))
3412 .getText().toString();
3413 String pw = ((EditText) v
3414 .findViewById(R.id.password_edit))
3415 .getText().toString();
3416 BrowserActivity.this.setHttpAuthUsernamePassword
3417 (host, realm, nm, pw);
3418 handler.proceed(nm, pw);
3419 mHttpAuthenticationDialog = null;
3420 mHttpAuthHandler = null;
3421 }})
3422 .setNegativeButton(R.string.cancel,
3423 new DialogInterface.OnClickListener() {
3424 public void onClick(DialogInterface dialog,
3425 int whichButton) {
3426 handler.cancel();
3427 BrowserActivity.this.resetTitleAndRevertLockIcon();
3428 mHttpAuthenticationDialog = null;
3429 mHttpAuthHandler = null;
3430 }})
3431 .setOnCancelListener(new DialogInterface.OnCancelListener() {
3432 public void onCancel(DialogInterface dialog) {
3433 handler.cancel();
3434 BrowserActivity.this.resetTitleAndRevertLockIcon();
3435 mHttpAuthenticationDialog = null;
3436 mHttpAuthHandler = null;
3437 }})
3438 .create();
3439 // Make the IME appear when the dialog is displayed if applicable.
3440 dialog.getWindow().setSoftInputMode(
3441 WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
3442 dialog.show();
3443 if (focusId != 0) {
3444 dialog.findViewById(focusId).requestFocus();
3445 } else {
3446 v.findViewById(R.id.username_edit).requestFocus();
3447 }
3448 mHttpAuthenticationDialog = dialog;
3449 }
3450
3451 public int getProgress() {
3452 WebView w = mTabControl.getCurrentWebView();
3453 if (w != null) {
3454 return w.getProgress();
3455 } else {
3456 return 100;
3457 }
3458 }
3459
3460 /**
3461 * Set HTTP authentication password.
3462 *
3463 * @param host The host for the password
3464 * @param realm The realm for the password
3465 * @param username The username for the password. If it is null, it means
3466 * password can't be saved.
3467 * @param password The password
3468 */
3469 public void setHttpAuthUsernamePassword(String host, String realm,
3470 String username,
3471 String password) {
Steve Block95a53b22010-03-25 17:24:58 +00003472 WebView w = getTopWindow();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003473 if (w != null) {
3474 w.setHttpAuthUsernamePassword(host, realm, username, password);
3475 }
3476 }
3477
3478 /**
3479 * connectivity manager says net has come or gone... inform the user
3480 * @param up true if net has come up, false if net has gone down
3481 */
3482 public void onNetworkToggle(boolean up) {
3483 if (up == mIsNetworkUp) {
3484 return;
3485 } else if (up) {
3486 mIsNetworkUp = true;
3487 if (mAlertDialog != null) {
3488 mAlertDialog.cancel();
3489 mAlertDialog = null;
3490 }
3491 } else {
3492 mIsNetworkUp = false;
Patrick Scotteb6ab2a2009-09-16 10:00:17 -04003493 if (mInLoad) {
3494 createAndShowNetworkDialog();
3495 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003496 }
3497 WebView w = mTabControl.getCurrentWebView();
3498 if (w != null) {
3499 w.setNetworkAvailable(up);
3500 }
3501 }
3502
Grace Kloba22ac16e2009-10-07 18:00:23 -07003503 boolean isNetworkUp() {
3504 return mIsNetworkUp;
3505 }
3506
Patrick Scotteb6ab2a2009-09-16 10:00:17 -04003507 // This method shows the network dialog alerting the user that the net is
3508 // down. It will only show the dialog if mAlertDialog is null.
3509 private void createAndShowNetworkDialog() {
3510 if (mAlertDialog == null) {
3511 mAlertDialog = new AlertDialog.Builder(this)
3512 .setTitle(R.string.loadSuspendedTitle)
3513 .setMessage(R.string.loadSuspended)
3514 .setPositiveButton(R.string.ok, null)
3515 .show();
3516 }
3517 }
3518
The Android Open Source Project0c908882009-03-03 19:32:16 -08003519 @Override
3520 protected void onActivityResult(int requestCode, int resultCode,
3521 Intent intent) {
Grace Klobabb394f32009-11-19 10:26:37 -08003522 if (getTopWindow() == null) return;
3523
The Android Open Source Project0c908882009-03-03 19:32:16 -08003524 switch (requestCode) {
3525 case COMBO_PAGE:
3526 if (resultCode == RESULT_OK && intent != null) {
3527 String data = intent.getAction();
3528 Bundle extras = intent.getExtras();
3529 if (extras != null && extras.getBoolean("new_window", false)) {
Leon Scroggins25d35472009-09-15 11:37:27 -04003530 openTab(data);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003531 } else {
Grace Kloba22ac16e2009-10-07 18:00:23 -07003532 final Tab currentTab =
The Android Open Source Project0c908882009-03-03 19:32:16 -08003533 mTabControl.getCurrentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04003534 dismissSubWindow(currentTab);
3535 if (data != null && data.length() != 0) {
Leon Scroggins92472e82010-02-17 16:32:28 -05003536 loadUrl(getTopWindow(), data);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003537 }
3538 }
3539 }
Leon Scrogginsfde97462010-01-11 13:06:21 -05003540 // Deliberately fall through to PREFERENCES_PAGE, since the
3541 // same extra may be attached to the COMBO_PAGE
3542 case PREFERENCES_PAGE:
3543 if (resultCode == RESULT_OK && intent != null) {
3544 String action = intent.getStringExtra(Intent.EXTRA_TEXT);
3545 if (BrowserSettings.PREF_CLEAR_HISTORY.equals(action)) {
3546 mTabControl.removeParentChildRelationShips();
3547 }
3548 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003549 break;
Leon Scroggins8d5fa432009-10-02 15:55:59 -04003550 // Choose a file from the file picker.
3551 case FILE_SELECTED:
3552 if (null == mUploadMessage) break;
3553 Uri result = intent == null || resultCode != RESULT_OK ? null
3554 : intent.getData();
3555 mUploadMessage.onReceiveValue(result);
3556 mUploadMessage = null;
3557 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003558 default:
3559 break;
3560 }
Leon Scroggins30444232009-09-04 18:36:20 -04003561 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003562 }
3563
3564 /*
3565 * This method is called as a result of the user selecting the options
Leon Scrogginsf08809b2010-01-21 09:27:46 -05003566 * menu to see the download window. It shows the download window on top of
3567 * the current window.
The Android Open Source Project0c908882009-03-03 19:32:16 -08003568 */
Leon Scrogginsf08809b2010-01-21 09:27:46 -05003569 private void viewDownloads(Uri downloadRecord) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003570 Intent intent = new Intent(this,
3571 BrowserDownloadPage.class);
3572 intent.setData(downloadRecord);
Grace Kloba22ac16e2009-10-07 18:00:23 -07003573 startActivityForResult(intent, BrowserActivity.DOWNLOAD_PAGE);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003574
3575 }
3576
Leon Scroggins160a7e72009-08-14 18:28:01 -04003577 /**
3578 * Open the Go page.
3579 * @param startWithHistory If true, open starting on the history tab.
3580 * Otherwise, start with the bookmarks tab.
Leon Scroggins160a7e72009-08-14 18:28:01 -04003581 */
Leon Scroggins30444232009-09-04 18:36:20 -04003582 /* package */ void bookmarksOrHistoryPicker(boolean startWithHistory) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003583 WebView current = mTabControl.getCurrentWebView();
3584 if (current == null) {
3585 return;
3586 }
3587 Intent intent = new Intent(this,
3588 CombinedBookmarkHistoryActivity.class);
3589 String title = current.getTitle();
3590 String url = current.getUrl();
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01003591 Bitmap thumbnail = createScreenshot(current);
3592
The Android Open Source Project0c908882009-03-03 19:32:16 -08003593 // Just in case the user opens bookmarks before a page finishes loading
3594 // so the current history item, and therefore the page, is null.
3595 if (null == url) {
3596 url = mLastEnteredUrl;
3597 // This can happen.
3598 if (null == url) {
3599 url = mSettings.getHomePage();
3600 }
3601 }
3602 // In case the web page has not yet received its associated title.
3603 if (title == null) {
3604 title = url;
3605 }
3606 intent.putExtra("title", title);
3607 intent.putExtra("url", url);
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01003608 intent.putExtra("thumbnail", thumbnail);
Leon Scroggins30444232009-09-04 18:36:20 -04003609 // Disable opening in a new window if we have maxed out the windows
Grace Kloba22ac16e2009-10-07 18:00:23 -07003610 intent.putExtra("disable_new_window", !mTabControl.canCreateNewTab());
Patrick Scott3918d442009-08-04 13:22:29 -04003611 intent.putExtra("touch_icon_url", current.getTouchIconUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003612 if (startWithHistory) {
3613 intent.putExtra(CombinedBookmarkHistoryActivity.STARTING_TAB,
3614 CombinedBookmarkHistoryActivity.HISTORY_TAB);
3615 }
3616 startActivityForResult(intent, COMBO_PAGE);
3617 }
3618
3619 // Called when loading from context menu or LOAD_URL message
Leon Scroggins92472e82010-02-17 16:32:28 -05003620 private void loadUrlFromContext(WebView view, String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003621 // In case the user enters nothing.
3622 if (url != null && url.length() != 0 && view != null) {
3623 url = smartUrlFilter(url);
Grace Kloba22ac16e2009-10-07 18:00:23 -07003624 if (!view.getWebViewClient().shouldOverrideUrlLoading(view, url)) {
Leon Scroggins92472e82010-02-17 16:32:28 -05003625 loadUrl(view, url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003626 }
3627 }
3628 }
3629
Leon Scroggins92472e82010-02-17 16:32:28 -05003630 /**
3631 * Load the URL into the given WebView and update the title bar
3632 * to reflect the new load. Call this instead of WebView.loadUrl
3633 * directly.
3634 * @param view The WebView used to load url.
3635 * @param url The URL to load.
3636 */
3637 private void loadUrl(WebView view, String url) {
3638 updateTitleBarForNewLoad(view, url);
3639 view.loadUrl(url);
3640 }
3641
3642 /**
3643 * Load UrlData into a Tab and update the title bar to reflect the new
3644 * load. Call this instead of UrlData.loadIn directly.
3645 * @param t The Tab used to load.
3646 * @param data The UrlData being loaded.
3647 */
3648 private void loadUrlDataIn(Tab t, UrlData data) {
3649 updateTitleBarForNewLoad(t.getWebView(), data.mUrl);
3650 data.loadIn(t);
3651 }
3652
3653 /**
3654 * If the WebView is the top window, update the title bar to reflect
3655 * loading the new URL. i.e. set its text, clear the favicon (which
3656 * will be set once the page begins loading), and set the progress to
3657 * INITIAL_PROGRESS to show that the page has begun to load. Called
3658 * by loadUrl and loadUrlDataIn.
3659 * @param view The WebView that is starting a load.
3660 * @param url The URL that is being loaded.
3661 */
3662 private void updateTitleBarForNewLoad(WebView view, String url) {
3663 if (view == getTopWindow()) {
3664 setUrlTitle(url, null);
3665 setFavicon(null);
3666 onProgressChanged(view, INITIAL_PROGRESS);
3667 }
3668 }
3669
The Android Open Source Project0c908882009-03-03 19:32:16 -08003670 private String smartUrlFilter(Uri inUri) {
3671 if (inUri != null) {
3672 return smartUrlFilter(inUri.toString());
3673 }
3674 return null;
3675 }
3676
Feng Qianb34f87a2009-03-24 21:27:26 -07003677 protected static final Pattern ACCEPTED_URI_SCHEMA = Pattern.compile(
The Android Open Source Project0c908882009-03-03 19:32:16 -08003678 "(?i)" + // switch on case insensitive matching
3679 "(" + // begin group for schema
3680 "(?:http|https|file):\\/\\/" +
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003681 "|(?:inline|data|about|content|javascript):" +
The Android Open Source Project0c908882009-03-03 19:32:16 -08003682 ")" +
3683 "(.*)" );
3684
3685 /**
3686 * Attempts to determine whether user input is a URL or search
3687 * terms. Anything with a space is passed to search.
3688 *
3689 * Converts to lowercase any mistakenly uppercased schema (i.e.,
3690 * "Http://" converts to "http://"
3691 *
3692 * @return Original or modified URL
3693 *
3694 */
3695 String smartUrlFilter(String url) {
3696
3697 String inUrl = url.trim();
3698 boolean hasSpace = inUrl.indexOf(' ') != -1;
3699
3700 Matcher matcher = ACCEPTED_URI_SCHEMA.matcher(inUrl);
3701 if (matcher.matches()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003702 // force scheme to lowercase
3703 String scheme = matcher.group(1);
3704 String lcScheme = scheme.toLowerCase();
3705 if (!lcScheme.equals(scheme)) {
Mitsuru Oshima123ecfb2009-05-18 19:11:14 -07003706 inUrl = lcScheme + matcher.group(2);
3707 }
3708 if (hasSpace) {
3709 inUrl = inUrl.replace(" ", "%20");
The Android Open Source Project0c908882009-03-03 19:32:16 -08003710 }
3711 return inUrl;
3712 }
3713 if (hasSpace) {
Satish Sampath565505b2009-05-29 15:37:27 +01003714 // FIXME: Is this the correct place to add to searches?
3715 // what if someone else calls this function?
3716 int shortcut = parseUrlShortcut(inUrl);
3717 if (shortcut != SHORTCUT_INVALID) {
3718 Browser.addSearchUrl(mResolver, inUrl);
3719 String query = inUrl.substring(2);
3720 switch (shortcut) {
3721 case SHORTCUT_GOOGLE_SEARCH:
Grace Kloba47fdfdb2009-06-30 11:15:34 -07003722 return URLUtil.composeSearchUrl(query, QuickSearch_G, QUERY_PLACE_HOLDER);
Satish Sampath565505b2009-05-29 15:37:27 +01003723 case SHORTCUT_WIKIPEDIA_SEARCH:
3724 return URLUtil.composeSearchUrl(query, QuickSearch_W, QUERY_PLACE_HOLDER);
3725 case SHORTCUT_DICTIONARY_SEARCH:
3726 return URLUtil.composeSearchUrl(query, QuickSearch_D, QUERY_PLACE_HOLDER);
3727 case SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH:
The Android Open Source Project0c908882009-03-03 19:32:16 -08003728 // FIXME: we need location in this case
Satish Sampath565505b2009-05-29 15:37:27 +01003729 return URLUtil.composeSearchUrl(query, QuickSearch_L, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003730 }
3731 }
3732 } else {
Dan Egnor5ee906c2009-11-18 12:11:49 -08003733 if (Patterns.WEB_URL.matcher(inUrl).matches()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003734 return URLUtil.guessUrl(inUrl);
3735 }
3736 }
3737
3738 Browser.addSearchUrl(mResolver, inUrl);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07003739 return URLUtil.composeSearchUrl(inUrl, QuickSearch_G, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003740 }
3741
Ben Murdochbff2d602009-07-01 20:19:05 +01003742 /* package */ void setShouldShowErrorConsole(boolean flag) {
3743 if (flag == mShouldShowErrorConsole) {
3744 // Nothing to do.
3745 return;
3746 }
Leon Scroggins IIIa9e35b62010-09-16 15:30:15 -04003747 Tab t = mTabControl.getCurrentTab();
3748 if (t == null) {
3749 // There is no current tab so we cannot toggle the error console
3750 return;
3751 }
Ben Murdochbff2d602009-07-01 20:19:05 +01003752
3753 mShouldShowErrorConsole = flag;
3754
Leon Scroggins IIIa9e35b62010-09-16 15:30:15 -04003755 ErrorConsoleView errorConsole = t.getErrorConsole(true);
Ben Murdochbff2d602009-07-01 20:19:05 +01003756
3757 if (flag) {
3758 // Setting the show state of the console will cause it's the layout to be inflated.
3759 if (errorConsole.numberOfErrors() > 0) {
3760 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
3761 } else {
3762 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
3763 }
3764
3765 // Now we can add it to the main view.
3766 mErrorConsoleContainer.addView(errorConsole,
Romain Guy15b8ec62010-01-08 15:06:43 -08003767 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
Ben Murdochbff2d602009-07-01 20:19:05 +01003768 ViewGroup.LayoutParams.WRAP_CONTENT));
3769 } else {
3770 mErrorConsoleContainer.removeView(errorConsole);
3771 }
3772
3773 }
3774
Grace Kloba22ac16e2009-10-07 18:00:23 -07003775 boolean shouldShowErrorConsole() {
3776 return mShouldShowErrorConsole;
3777 }
3778
Andrei Popescu163ab742009-10-20 17:58:23 +01003779 private void setStatusBarVisibility(boolean visible) {
3780 int flag = visible ? 0 : WindowManager.LayoutParams.FLAG_FULLSCREEN;
3781 getWindow().setFlags(flag, WindowManager.LayoutParams.FLAG_FULLSCREEN);
3782 }
3783
Andrei Popescu56199cc2010-01-12 22:39:16 +00003784
3785 private void sendNetworkType(String type, String subtype) {
3786 WebView w = mTabControl.getCurrentWebView();
3787 if (w != null) {
3788 w.setNetworkType(type, subtype);
3789 }
3790 }
3791
Andrei Popescu30995e72010-02-09 16:59:58 +00003792 private void packageChanged(String packageName, boolean wasAdded) {
3793 WebView w = mTabControl.getCurrentWebView();
3794 if (w == null) {
3795 return;
3796 }
3797
3798 if (wasAdded) {
3799 w.addPackageName(packageName);
3800 } else {
3801 w.removePackageName(packageName);
3802 }
3803 }
3804
3805 private void addPackageNames(Set<String> packageNames) {
3806 WebView w = mTabControl.getCurrentWebView();
3807 if (w == null) {
3808 return;
3809 }
3810
3811 w.addPackageNames(packageNames);
3812 }
3813
3814 private void getInstalledPackages() {
3815 AsyncTask<Void, Void, Set<String> > task =
3816 new AsyncTask<Void, Void, Set<String> >() {
3817 protected Set<String> doInBackground(Void... unused) {
3818 Set<String> installedPackages = new HashSet<String>();
3819 PackageManager pm = BrowserActivity.this.getPackageManager();
3820 if (pm != null) {
3821 List<PackageInfo> packages = pm.getInstalledPackages(0);
3822 for (PackageInfo p : packages) {
3823 if (BrowserActivity.this.sGoogleApps.contains(p.packageName)) {
3824 installedPackages.add(p.packageName);
3825 }
3826 }
3827 }
3828
3829 return installedPackages;
3830 }
3831
3832 // Executes on the UI thread
3833 protected void onPostExecute(Set<String> installedPackages) {
3834 addPackageNames(installedPackages);
3835 }
3836 };
3837 task.execute();
3838 }
3839
Grace Klobaeb6eef42009-09-15 17:56:32 -07003840 final static int LOCK_ICON_UNSECURE = 0;
3841 final static int LOCK_ICON_SECURE = 1;
3842 final static int LOCK_ICON_MIXED = 2;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003843
The Android Open Source Project0c908882009-03-03 19:32:16 -08003844 private BrowserSettings mSettings;
3845 private TabControl mTabControl;
3846 private ContentResolver mResolver;
3847 private FrameLayout mContentView;
Andrei Popescuadc008d2009-06-26 14:11:30 +01003848 private View mCustomView;
3849 private FrameLayout mCustomViewContainer;
Andrei Popescuc9b55562009-07-07 10:51:15 +01003850 private WebChromeClient.CustomViewCallback mCustomViewCallback;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003851
3852 // FIXME, temp address onPrepareMenu performance problem. When we move everything out of
3853 // view, we should rewrite this.
3854 private int mCurrentMenuState = 0;
3855 private int mMenuState = R.id.MAIN_MENU;
Andrei Popescuadc008d2009-06-26 14:11:30 +01003856 private int mOldMenuState = EMPTY_MENU;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003857 private static final int EMPTY_MENU = -1;
3858 private Menu mMenu;
3859
3860 private FindDialog mFindDialog;
Cary Clark2c326e62010-08-19 18:40:57 -04003861 private SelectDialog mSelectDialog;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003862 // Used to prevent chording to result in firing two shortcuts immediately
3863 // one after another. Fixes bug 1211714.
3864 boolean mCanChord;
3865
3866 private boolean mInLoad;
3867 private boolean mIsNetworkUp;
Ben Murdochb7cc8b42009-09-28 10:59:09 +01003868 private boolean mDidStopLoad;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003869
Cary Clark1f10cbf2010-03-22 11:45:23 -04003870 /* package */ boolean mActivityInPause = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003871
3872 private boolean mMenuIsDown;
3873
The Android Open Source Project0c908882009-03-03 19:32:16 -08003874 private static boolean mInTrace;
3875
3876 // Performance probe
3877 private static final int[] SYSTEM_CPU_FORMAT = new int[] {
3878 Process.PROC_SPACE_TERM | Process.PROC_COMBINE,
3879 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 1: user time
3880 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 2: nice time
3881 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 3: sys time
3882 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 4: idle time
3883 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 5: iowait time
3884 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 6: irq time
3885 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG // 7: softirq time
3886 };
3887
3888 private long mStart;
3889 private long mProcessStart;
3890 private long mUserStart;
3891 private long mSystemStart;
3892 private long mIdleStart;
3893 private long mIrqStart;
3894
3895 private long mUiStart;
3896
3897 private Drawable mMixLockIcon;
3898 private Drawable mSecLockIcon;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003899
3900 /* hold a ref so we can auto-cancel if necessary */
3901 private AlertDialog mAlertDialog;
3902
The Android Open Source Project0c908882009-03-03 19:32:16 -08003903 // The up-to-date URL and title (these can be different from those stored
3904 // in WebView, since it takes some time for the information in WebView to
3905 // get updated)
3906 private String mUrl;
3907 private String mTitle;
3908
3909 // As PageInfo has different style for landscape / portrait, we have
3910 // to re-open it when configuration changed
3911 private AlertDialog mPageInfoDialog;
Grace Kloba22ac16e2009-10-07 18:00:23 -07003912 private Tab mPageInfoView;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003913 // If the Page-Info dialog is launched from the SSL-certificate-on-error
3914 // dialog, we should not just dismiss it, but should get back to the
3915 // SSL-certificate-on-error dialog. This flag is used to store this state
Leon Scrogginsc7b92f82010-01-11 18:17:31 -05003916 private boolean mPageInfoFromShowSSLCertificateOnError;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003917
3918 // as SSLCertificateOnError has different style for landscape / portrait,
3919 // we have to re-open it when configuration changed
3920 private AlertDialog mSSLCertificateOnErrorDialog;
3921 private WebView mSSLCertificateOnErrorView;
3922 private SslErrorHandler mSSLCertificateOnErrorHandler;
3923 private SslError mSSLCertificateOnErrorError;
3924
3925 // as SSLCertificate has different style for landscape / portrait, we
3926 // have to re-open it when configuration changed
3927 private AlertDialog mSSLCertificateDialog;
Grace Kloba22ac16e2009-10-07 18:00:23 -07003928 private Tab mSSLCertificateView;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003929
3930 // as HttpAuthentication has different style for landscape / portrait, we
3931 // have to re-open it when configuration changed
3932 private AlertDialog mHttpAuthenticationDialog;
3933 private HttpAuthHandler mHttpAuthHandler;
3934
3935 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_PARAMS =
3936 new FrameLayout.LayoutParams(
Romain Guy15b8ec62010-01-08 15:06:43 -08003937 ViewGroup.LayoutParams.MATCH_PARENT,
3938 ViewGroup.LayoutParams.MATCH_PARENT);
Andrei Popescuadc008d2009-06-26 14:11:30 +01003939 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_GRAVITY_CENTER =
3940 new FrameLayout.LayoutParams(
Romain Guy15b8ec62010-01-08 15:06:43 -08003941 ViewGroup.LayoutParams.MATCH_PARENT,
3942 ViewGroup.LayoutParams.MATCH_PARENT,
Andrei Popescuadc008d2009-06-26 14:11:30 +01003943 Gravity.CENTER);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07003944 // Google search
3945 final static String QuickSearch_G = "http://www.google.com/m?q=%s";
The Android Open Source Project0c908882009-03-03 19:32:16 -08003946 // Wikipedia search
3947 final static String QuickSearch_W = "http://en.wikipedia.org/w/index.php?search=%s&go=Go";
3948 // Dictionary search
3949 final static String QuickSearch_D = "http://dictionary.reference.com/search?q=%s";
3950 // Google Mobile Local search
3951 final static String QuickSearch_L = "http://www.google.com/m/search?site=local&q=%s&near=mountain+view";
3952
3953 final static String QUERY_PLACE_HOLDER = "%s";
3954
3955 // "source" parameter for Google search through search key
3956 final static String GOOGLE_SEARCH_SOURCE_SEARCHKEY = "browser-key";
3957 // "source" parameter for Google search through goto menu
3958 final static String GOOGLE_SEARCH_SOURCE_GOTO = "browser-goto";
3959 // "source" parameter for Google search through simplily type
3960 final static String GOOGLE_SEARCH_SOURCE_TYPE = "browser-type";
3961 // "source" parameter for Google search suggested by the browser
3962 final static String GOOGLE_SEARCH_SOURCE_SUGGEST = "browser-suggest";
3963 // "source" parameter for Google search from unknown source
3964 final static String GOOGLE_SEARCH_SOURCE_UNKNOWN = "unknown";
3965
3966 private final static String LOGTAG = "browser";
3967
The Android Open Source Project0c908882009-03-03 19:32:16 -08003968 private String mLastEnteredUrl;
3969
3970 private PowerManager.WakeLock mWakeLock;
3971 private final static int WAKELOCK_TIMEOUT = 5 * 60 * 1000; // 5 minutes
3972
3973 private Toast mStopToast;
3974
Leon Scroggins68579392009-09-15 15:31:54 -04003975 private TitleBar mTitleBar;
Leon Scroggins81db3662009-06-04 17:45:11 -04003976
Ben Murdochbff2d602009-07-01 20:19:05 +01003977 private LinearLayout mErrorConsoleContainer = null;
3978 private boolean mShouldShowErrorConsole = false;
3979
The Android Open Source Project0c908882009-03-03 19:32:16 -08003980 // As the ids are dynamically created, we can't guarantee that they will
3981 // be in sequence, so this static array maps ids to a window number.
3982 final static private int[] WINDOW_SHORTCUT_ID_ARRAY =
3983 { R.id.window_one_menu_id, R.id.window_two_menu_id, R.id.window_three_menu_id,
3984 R.id.window_four_menu_id, R.id.window_five_menu_id, R.id.window_six_menu_id,
3985 R.id.window_seven_menu_id, R.id.window_eight_menu_id };
3986
3987 // monitor platform changes
3988 private IntentFilter mNetworkStateChangedFilter;
3989 private BroadcastReceiver mNetworkStateIntentReceiver;
3990
Grace Klobab4da0ad2009-05-14 14:45:40 -07003991 private BroadcastReceiver mPackageInstallationReceiver;
3992
Bjorn Bringerta7611812010-03-24 11:12:02 +00003993 private SystemAllowGeolocationOrigins mSystemAllowGeolocationOrigins;
3994
The Android Open Source Project0c908882009-03-03 19:32:16 -08003995 // activity requestCode
Nicolas Roard78a98e42009-05-11 13:34:17 +01003996 final static int COMBO_PAGE = 1;
3997 final static int DOWNLOAD_PAGE = 2;
3998 final static int PREFERENCES_PAGE = 3;
Leon Scroggins8d5fa432009-10-02 15:55:59 -04003999 final static int FILE_SELECTED = 4;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004000
Andrei Popescu540035d2009-09-18 18:59:20 +01004001 // the default <video> poster
4002 private Bitmap mDefaultVideoPoster;
4003 // the video progress view
4004 private View mVideoProgressView;
4005
Andrei Popescu30995e72010-02-09 16:59:58 +00004006 // The Google packages we monitor for the navigator.isApplicationInstalled()
4007 // API. Add as needed.
4008 private static Set<String> sGoogleApps;
4009 static {
4010 sGoogleApps = new HashSet<String>();
4011 sGoogleApps.add("com.google.android.youtube");
4012 }
4013
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004014 /**
4015 * A UrlData class to abstract how the content will be set to WebView.
4016 * This base class uses loadUrl to show the content.
4017 */
Leon Scroggins6eac63e2010-03-15 18:19:14 -04004018 /* package */ static class UrlData {
Grace Kloba068e48b2010-01-26 18:11:27 -08004019 final String mUrl;
4020 final Map<String, String> mHeaders;
Leon Scroggins58d56c62010-01-28 15:12:40 -05004021 final Intent mVoiceIntent;
Grace Kloba60e095c2009-06-16 11:50:55 -07004022
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004023 UrlData(String url) {
4024 this.mUrl = url;
Grace Kloba068e48b2010-01-26 18:11:27 -08004025 this.mHeaders = null;
Leon Scroggins58d56c62010-01-28 15:12:40 -05004026 this.mVoiceIntent = null;
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004027 }
Grace Kloba60e095c2009-06-16 11:50:55 -07004028
Leon Scroggins58d56c62010-01-28 15:12:40 -05004029 UrlData(String url, Map<String, String> headers, Intent intent) {
Grace Kloba068e48b2010-01-26 18:11:27 -08004030 this.mUrl = url;
4031 this.mHeaders = headers;
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -05004032 if (RecognizerResultsIntent.ACTION_VOICE_SEARCH_RESULTS
4033 .equals(intent.getAction())) {
Leon Scroggins58d56c62010-01-28 15:12:40 -05004034 this.mVoiceIntent = intent;
4035 } else {
4036 this.mVoiceIntent = null;
4037 }
Grace Kloba60e095c2009-06-16 11:50:55 -07004038 }
4039
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004040 boolean isEmpty() {
Leon Scroggins58d56c62010-01-28 15:12:40 -05004041 return mVoiceIntent == null && (mUrl == null || mUrl.length() == 0);
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004042 }
4043
Leon Scroggins92472e82010-02-17 16:32:28 -05004044 /**
4045 * Load this UrlData into the given Tab. Use loadUrlDataIn to update
4046 * the title bar as well.
4047 */
Leon Scroggins58d56c62010-01-28 15:12:40 -05004048 public void loadIn(Tab t) {
4049 if (mVoiceIntent != null) {
4050 t.activateVoiceSearchMode(mVoiceIntent);
4051 } else {
4052 t.getWebView().loadUrl(mUrl, mHeaders);
4053 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004054 }
4055 };
4056
Leon Scroggins1f005d32009-08-10 17:36:42 -04004057 /* package */ static final UrlData EMPTY_URL_DATA = new UrlData(null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004058}