blob: 435560b5eee0aebe840a3b5ed8ff9694eac9a755 [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;
Steve Howard5a862fc2010-09-28 12:52:06 -070021import android.app.DownloadManager;
The Android Open Source Project0c908882009-03-03 19:32:16 -080022import android.app.ProgressDialog;
23import android.app.SearchManager;
24import android.content.ActivityNotFoundException;
25import android.content.BroadcastReceiver;
26import android.content.ComponentName;
Leon Scroggins58d56c62010-01-28 15:12:40 -050027import android.content.ContentProvider;
28import android.content.ContentProviderClient;
The Android Open Source Project0c908882009-03-03 19:32:16 -080029import android.content.ContentResolver;
Leon Scrogginsb6b7f9e2009-06-18 12:05:28 -040030import android.content.ContentUris;
The Android Open Source Project0c908882009-03-03 19:32:16 -080031import android.content.ContentValues;
32import android.content.Context;
33import android.content.DialogInterface;
34import android.content.Intent;
35import android.content.IntentFilter;
Grace Klobab4da0ad2009-05-14 14:45:40 -070036import android.content.pm.PackageInfo;
The Android Open Source Project0c908882009-03-03 19:32:16 -080037import android.content.pm.PackageManager;
38import android.content.pm.ResolveInfo;
The Android Open Source Project0c908882009-03-03 19:32:16 -080039import android.content.res.Configuration;
40import android.content.res.Resources;
41import android.database.Cursor;
Leon Scroggins96afcb12009-12-10 12:35:56 -050042import android.database.DatabaseUtils;
The Android Open Source Project0c908882009-03-03 19:32:16 -080043import android.graphics.Bitmap;
Andrei Popescu540035d2009-09-18 18:59:20 +010044import android.graphics.BitmapFactory;
The Android Open Source Project0c908882009-03-03 19:32:16 -080045import android.graphics.Canvas;
The Android Open Source Project0c908882009-03-03 19:32:16 -080046import android.graphics.Picture;
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -040047import android.graphics.PixelFormat;
48import android.graphics.Rect;
The Android Open Source Project0c908882009-03-03 19:32:16 -080049import android.graphics.drawable.Drawable;
The Android Open Source Project0c908882009-03-03 19:32:16 -080050import android.net.ConnectivityManager;
Andrei Popescu56199cc2010-01-12 22:39:16 +000051import android.net.NetworkInfo;
The Android Open Source Project0c908882009-03-03 19:32:16 -080052import android.net.Uri;
53import android.net.WebAddress;
The Android Open Source Project0c908882009-03-03 19:32:16 -080054import android.net.http.SslCertificate;
55import android.net.http.SslError;
56import android.os.AsyncTask;
57import android.os.Bundle;
58import android.os.Debug;
59import android.os.Environment;
60import android.os.Handler;
The Android Open Source Project0c908882009-03-03 19:32:16 -080061import android.os.Message;
62import android.os.PowerManager;
63import android.os.Process;
The Android Open Source Project0c908882009-03-03 19:32:16 -080064import android.os.ServiceManager;
65import android.os.SystemClock;
The Android Open Source Project0c908882009-03-03 19:32:16 -080066import android.provider.Browser;
Cary Clark5e335a32009-09-22 14:53:11 -040067import android.provider.ContactsContract;
68import android.provider.ContactsContract.Intents.Insert;
The Android Open Source Project0c908882009-03-03 19:32:16 -080069import android.provider.Downloads;
70import android.provider.MediaStore;
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -050071import android.speech.RecognizerResultsIntent;
The Android Open Source Project0c908882009-03-03 19:32:16 -080072import android.text.IClipboard;
73import android.text.TextUtils;
74import android.text.format.DateFormat;
Leon Scrogginsb94bf272009-09-25 15:22:08 -040075import android.util.AttributeSet;
The Android Open Source Project0c908882009-03-03 19:32:16 -080076import android.util.Log;
Dianne Hackborn385effd2010-02-24 20:03:04 -080077import android.util.Patterns;
The Android Open Source Project0c908882009-03-03 19:32:16 -080078import android.view.ContextMenu;
79import android.view.Gravity;
80import android.view.KeyEvent;
81import android.view.LayoutInflater;
82import android.view.Menu;
83import android.view.MenuInflater;
84import android.view.MenuItem;
85import android.view.View;
86import android.view.ViewGroup;
87import android.view.Window;
88import android.view.WindowManager;
89import android.view.ContextMenu.ContextMenuInfo;
90import android.view.MenuItem.OnMenuItemClickListener;
The Android Open Source Project0c908882009-03-03 19:32:16 -080091import android.webkit.CookieManager;
92import android.webkit.CookieSyncManager;
93import android.webkit.DownloadListener;
94import android.webkit.HttpAuthHandler;
Grace Klobab4da0ad2009-05-14 14:45:40 -070095import android.webkit.PluginManager;
The Android Open Source Project0c908882009-03-03 19:32:16 -080096import android.webkit.SslErrorHandler;
97import android.webkit.URLUtil;
Leon Clarkecb6cc862009-09-29 18:35:13 +010098import android.webkit.ValueCallback;
The Android Open Source Project0c908882009-03-03 19:32:16 -080099import android.webkit.WebChromeClient;
100import android.webkit.WebHistoryItem;
101import android.webkit.WebIconDatabase;
102import android.webkit.WebView;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800103import android.widget.EditText;
104import android.widget.FrameLayout;
105import android.widget.LinearLayout;
106import android.widget.TextView;
107import android.widget.Toast;
Fred Quintana752b6562009-12-18 10:18:26 -0800108import android.accounts.Account;
109import android.accounts.AccountManager;
110import android.accounts.AccountManagerFuture;
111import android.accounts.AuthenticatorException;
112import android.accounts.OperationCanceledException;
113import android.accounts.AccountManagerCallback;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800114
Bjorn Bringertd2670652010-09-13 14:06:41 +0100115import com.android.browser.search.SearchEngine;
Bjorn Bringert10d1cca2010-02-10 14:22:12 +0000116import com.android.common.Search;
Leon Scroggins1fe13a52010-02-09 15:31:26 -0500117import com.android.common.speech.LoggingEvents;
Dan Egnor5ee906c2009-11-18 12:11:49 -0800118
Leon Scrogginsb6b7f9e2009-06-18 12:05:28 -0400119import java.io.ByteArrayOutputStream;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800120import java.io.File;
Ben Murdoch4f75ba22009-10-27 11:48:28 +0000121import java.io.IOException;
122import java.io.InputStream;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800123import java.net.MalformedURLException;
124import java.net.URI;
Dianne Hackborn99189432009-06-17 18:06:18 -0700125import java.net.URISyntaxException;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800126import java.net.URL;
127import java.net.URLEncoder;
128import java.text.ParseException;
129import java.util.Date;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800130import java.util.HashMap;
Andrei Popescu30995e72010-02-09 16:59:58 +0000131import java.util.HashSet;
Grace Kloba00f54c52010-01-27 14:53:51 -0800132import java.util.Iterator;
Andrei Popescu30995e72010-02-09 16:59:58 +0000133import java.util.List;
Grace Kloba068e48b2010-01-26 18:11:27 -0800134import java.util.Map;
Andrei Popescu30995e72010-02-09 16:59:58 +0000135import java.util.Set;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800136import java.util.regex.Matcher;
137import java.util.regex.Pattern;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800138
139public class BrowserActivity extends Activity
Shimeng (Simon) Wang98d5fce2010-03-16 13:23:39 -0700140 implements View.OnCreateContextMenuListener, DownloadListener {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800141
Dave Bort31a6d1c2009-04-13 15:56:49 -0700142 /* Define some aliases to make these debugging flags easier to refer to.
143 * This file imports android.provider.Browser, so we can't just refer to "Browser.DEBUG".
144 */
145 private final static boolean DEBUG = com.android.browser.Browser.DEBUG;
146 private final static boolean LOGV_ENABLED = com.android.browser.Browser.LOGV_ENABLED;
147 private final static boolean LOGD_ENABLED = com.android.browser.Browser.LOGD_ENABLED;
148
Cary Clarka9771242009-08-11 16:42:26 -0400149 private static class ClearThumbnails extends AsyncTask<File, Void, Void> {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800150 @Override
151 public Void doInBackground(File... files) {
152 if (files != null) {
153 for (File f : files) {
Cary Clarkd6be1752009-08-12 12:56:42 -0400154 if (!f.delete()) {
155 Log.e(LOGTAG, f.getPath() + " was not deleted");
156 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800157 }
158 }
159 return null;
160 }
161 }
162
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400163 /**
164 * This layout holds everything you see below the status bar, including the
165 * error console, the custom view container, and the webviews.
166 */
167 private FrameLayout mBrowserFrameLayout;
Leon Scroggins81db3662009-06-04 17:45:11 -0400168
Grace Kloba22ac16e2009-10-07 18:00:23 -0700169 @Override
170 public void onCreate(Bundle icicle) {
Dave Bort31a6d1c2009-04-13 15:56:49 -0700171 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800172 Log.v(LOGTAG, this + " onStart");
173 }
174 super.onCreate(icicle);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800175 // test the browser in OpenGL
176 // requestWindowFeature(Window.FEATURE_OPENGL);
177
Mike Reedd334bf52010-01-26 15:21:44 -0500178 // enable this to test the browser in 32bit
179 if (false) {
180 getWindow().setFormat(PixelFormat.RGBX_8888);
181 BitmapFactory.setDefaultConfig(Bitmap.Config.ARGB_8888);
182 }
183
The Android Open Source Project0c908882009-03-03 19:32:16 -0800184 setDefaultKeyMode(DEFAULT_KEYS_SEARCH_LOCAL);
185
186 mResolver = getContentResolver();
187
Leon Scroggins IIIcc14c8c2010-09-27 12:45:34 -0400188 // Keep a settings instance handy.
189 mSettings = BrowserSettings.getInstance();
190
Grace Kloba0923d692009-09-23 21:37:25 -0700191 // If this was a web search request, pass it on to the default web
192 // search provider and finish this activity.
193 if (handleWebSearchIntent(getIntent())) {
194 finish();
195 return;
196 }
197
The Android Open Source Project0c908882009-03-03 19:32:16 -0800198 mSecLockIcon = Resources.getSystem().getDrawable(
199 android.R.drawable.ic_secure);
200 mMixLockIcon = Resources.getSystem().getDrawable(
201 android.R.drawable.ic_partial_secure);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800202
Leon Scroggins81db3662009-06-04 17:45:11 -0400203 FrameLayout frameLayout = (FrameLayout) getWindow().getDecorView()
204 .findViewById(com.android.internal.R.id.content);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400205 mBrowserFrameLayout = (FrameLayout) LayoutInflater.from(this)
206 .inflate(R.layout.custom_screen, null);
207 mContentView = (FrameLayout) mBrowserFrameLayout.findViewById(
208 R.id.main_content);
209 mErrorConsoleContainer = (LinearLayout) mBrowserFrameLayout
210 .findViewById(R.id.error_console);
211 mCustomViewContainer = (FrameLayout) mBrowserFrameLayout
212 .findViewById(R.id.fullscreen_custom_content);
213 frameLayout.addView(mBrowserFrameLayout, COVER_SCREEN_PARAMS);
Leon Scroggins68579392009-09-15 15:31:54 -0400214 mTitleBar = new TitleBar(this);
Grace Kloba1542f742010-03-17 21:11:15 -0700215 // mTitleBar will be always shown in the fully loaded mode
216 mTitleBar.setProgress(100);
Leon Scrogginsfe87bd32009-10-06 10:10:00 -0400217 mFakeTitleBar = new TitleBar(this);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800218
219 // Create the tab control and our initial tab
220 mTabControl = new TabControl(this);
221
222 // Open the icon database and retain all the bookmark urls for favicons
223 retainIconsOnStartup();
224
The Android Open Source Project0c908882009-03-03 19:32:16 -0800225 mSettings.setTabControl(mTabControl);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800226
227 PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
228 mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Browser");
229
Patrick Scott6adacc92010-03-05 08:24:51 -0500230 // Find out if the network is currently up.
231 ConnectivityManager cm = (ConnectivityManager) getSystemService(
232 Context.CONNECTIVITY_SERVICE);
233 NetworkInfo info = cm.getActiveNetworkInfo();
234 if (info != null) {
235 mIsNetworkUp = info.isAvailable();
236 }
237
Grace Klobaa34f6862009-07-31 16:28:17 -0700238 /* enables registration for changes in network status from
239 http stack */
240 mNetworkStateChangedFilter = new IntentFilter();
241 mNetworkStateChangedFilter.addAction(
242 ConnectivityManager.CONNECTIVITY_ACTION);
243 mNetworkStateIntentReceiver = new BroadcastReceiver() {
244 @Override
245 public void onReceive(Context context, Intent intent) {
246 if (intent.getAction().equals(
247 ConnectivityManager.CONNECTIVITY_ACTION)) {
Andrei Popescue4c98462010-02-19 15:44:13 +0000248
249 NetworkInfo info = intent.getParcelableExtra(
250 ConnectivityManager.EXTRA_NETWORK_INFO);
251 String typeName = info.getTypeName();
252 String subtypeName = info.getSubtypeName();
253 sendNetworkType(typeName.toLowerCase(),
254 (subtypeName != null ? subtypeName.toLowerCase() : ""));
255
256 onNetworkToggle(info.isAvailable());
Grace Klobaa34f6862009-07-31 16:28:17 -0700257 }
258 }
259 };
260
Grace Kloba615c6c92009-08-03 10:22:44 -0700261 IntentFilter filter = new IntentFilter(Intent.ACTION_PACKAGE_ADDED);
262 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
263 filter.addDataScheme("package");
264 mPackageInstallationReceiver = new BroadcastReceiver() {
265 @Override
266 public void onReceive(Context context, Intent intent) {
267 final String action = intent.getAction();
268 final String packageName = intent.getData()
269 .getSchemeSpecificPart();
270 final boolean replacing = intent.getBooleanExtra(
271 Intent.EXTRA_REPLACING, false);
272 if (Intent.ACTION_PACKAGE_REMOVED.equals(action) && replacing) {
273 // if it is replacing, refreshPlugins() when adding
274 return;
275 }
Andrei Popescu30995e72010-02-09 16:59:58 +0000276
277 if (sGoogleApps.contains(packageName)) {
278 BrowserActivity.this.packageChanged(packageName,
279 Intent.ACTION_PACKAGE_ADDED.equals(action));
280 }
281
Grace Kloba615c6c92009-08-03 10:22:44 -0700282 PackageManager pm = BrowserActivity.this.getPackageManager();
283 PackageInfo pkgInfo = null;
284 try {
285 pkgInfo = pm.getPackageInfo(packageName,
286 PackageManager.GET_PERMISSIONS);
287 } catch (PackageManager.NameNotFoundException e) {
288 return;
289 }
290 if (pkgInfo != null) {
291 String permissions[] = pkgInfo.requestedPermissions;
292 if (permissions == null) {
293 return;
294 }
295 boolean permissionOk = false;
296 for (String permit : permissions) {
297 if (PluginManager.PLUGIN_PERMISSION.equals(permit)) {
298 permissionOk = true;
299 break;
300 }
301 }
302 if (permissionOk) {
303 PluginManager.getInstance(BrowserActivity.this)
304 .refreshPlugins(
305 Intent.ACTION_PACKAGE_ADDED
306 .equals(action));
307 }
308 }
309 }
310 };
311 registerReceiver(mPackageInstallationReceiver, filter);
312
The Android Open Source Project0c908882009-03-03 19:32:16 -0800313 if (!mTabControl.restoreState(icicle)) {
314 // clear up the thumbnail directory if we can't restore the state as
315 // none of the files in the directory are referenced any more.
316 new ClearThumbnails().execute(
317 mTabControl.getThumbnailDir().listFiles());
Grace Klobaaab3f092009-07-30 12:29:51 -0700318 // there is no quit on Android. But if we can't restore the state,
319 // we can treat it as a new Browser, remove the old session cookies.
320 CookieManager.getInstance().removeSessionCookie();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800321 final Intent intent = getIntent();
322 final Bundle extra = intent.getExtras();
323 // Create an initial tab.
324 // If the intent is ACTION_VIEW and data is not null, the Browser is
325 // invoked to view the content by another application. In this case,
326 // the tab will be close when exit.
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700327 UrlData urlData = getUrlDataFromIntent(intent);
328
Leon Scroggins58d56c62010-01-28 15:12:40 -0500329 String action = intent.getAction();
Grace Kloba22ac16e2009-10-07 18:00:23 -0700330 final Tab t = mTabControl.createNewTab(
Leon Scroggins58d56c62010-01-28 15:12:40 -0500331 (Intent.ACTION_VIEW.equals(action) &&
332 intent.getData() != null)
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -0500333 || RecognizerResultsIntent.ACTION_VOICE_SEARCH_RESULTS
334 .equals(action),
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700335 intent.getStringExtra(Browser.EXTRA_APPLICATION_ID), urlData.mUrl);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800336 mTabControl.setCurrentTab(t);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800337 attachTabToContentView(t);
338 WebView webView = t.getWebView();
339 if (extra != null) {
340 int scale = extra.getInt(Browser.INITIAL_ZOOM_LEVEL, 0);
341 if (scale > 0 && scale <= 1000) {
342 webView.setInitialScale(scale);
343 }
344 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800345
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700346 if (urlData.isEmpty()) {
Shimeng (Simon) Wang98d5fce2010-03-16 13:23:39 -0700347 loadUrl(webView, mSettings.getHomePage());
The Android Open Source Project0c908882009-03-03 19:32:16 -0800348 } else {
Patrick Scott9d53da02010-02-19 10:19:01 -0500349 loadUrlDataIn(t, urlData);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800350 }
351 } else {
352 // TabControl.restoreState() will create a new tab even if
Leon Scroggins1f005d32009-08-10 17:36:42 -0400353 // restoring the state fails.
The Android Open Source Project0c908882009-03-03 19:32:16 -0800354 attachTabToContentView(mTabControl.getCurrentTab());
355 }
Grace Kloba615c6c92009-08-03 10:22:44 -0700356
Cary Clark23cbeb72010-07-01 12:36:56 -0400357 // Delete old thumbnails to save space
358 File dir = mTabControl.getThumbnailDir();
359 if (dir.exists()) {
360 for (String child : dir.list()) {
361 File f = new File(dir, child);
362 f.delete();
363 }
364 }
365
Feng Qianb3c02da2009-06-29 15:58:08 -0700366 // Read JavaScript flags if it exists.
367 String jsFlags = mSettings.getJsFlags();
368 if (jsFlags.trim().length() != 0) {
369 mTabControl.getCurrentWebView().setJsFlags(jsFlags);
370 }
Andrei Popescu30995e72010-02-09 16:59:58 +0000371 // Work out which packages are installed on the system.
372 getInstalledPackages();
Bjorn Bringerta7611812010-03-24 11:12:02 +0000373
374 // Start watching the default geolocation permissions
375 mSystemAllowGeolocationOrigins
376 = new SystemAllowGeolocationOrigins(getApplicationContext());
377 mSystemAllowGeolocationOrigins.start();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800378 }
379
Leon Scroggins58d56c62010-01-28 15:12:40 -0500380 /**
381 * Feed the previously stored results strings to the BrowserProvider so that
382 * the SearchDialog will show them instead of the standard searches.
383 * @param result String to show on the editable line of the SearchDialog.
384 */
385 /* package */ void showVoiceSearchResults(String result) {
386 ContentProviderClient client = mResolver.acquireContentProviderClient(
387 Browser.BOOKMARKS_URI);
388 ContentProvider prov = client.getLocalContentProvider();
389 BrowserProvider bp = (BrowserProvider) prov;
390 bp.setQueryResults(mTabControl.getCurrentTab().getVoiceSearchResults());
391 client.release();
392
Leon Scrogginsfbb3f152010-03-09 17:26:56 -0500393 Bundle bundle = createGoogleSearchSourceBundle(
394 GOOGLE_SEARCH_SOURCE_SEARCHKEY);
395 bundle.putBoolean(SearchManager.CONTEXT_IS_VOICE, true);
396 startSearch(result, false, bundle, false);
Leon Scroggins58d56c62010-01-28 15:12:40 -0500397 }
398
The Android Open Source Project0c908882009-03-03 19:32:16 -0800399 @Override
400 protected void onNewIntent(Intent intent) {
Grace Kloba22ac16e2009-10-07 18:00:23 -0700401 Tab current = mTabControl.getCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800402 // When a tab is closed on exit, the current tab index is set to -1.
403 // Reset before proceed as Browser requires the current tab to be set.
404 if (current == null) {
405 // Try to reset the tab in case the index was incorrect.
406 current = mTabControl.getTab(0);
407 if (current == null) {
408 // No tabs at all so just ignore this intent.
409 return;
410 }
411 mTabControl.setCurrentTab(current);
412 attachTabToContentView(current);
413 resetTitleAndIcon(current.getWebView());
414 }
415 final String action = intent.getAction();
416 final int flags = intent.getFlags();
417 if (Intent.ACTION_MAIN.equals(action) ||
418 (flags & Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY) != 0) {
419 // just resume the browser
420 return;
421 }
Leon Scrogginsb8a844d2010-03-18 15:06:15 -0400422 // In case the SearchDialog is open.
423 ((SearchManager) getSystemService(Context.SEARCH_SERVICE))
424 .stopSearch();
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -0500425 boolean activateVoiceSearch = RecognizerResultsIntent
426 .ACTION_VOICE_SEARCH_RESULTS.equals(action);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800427 if (Intent.ACTION_VIEW.equals(action)
428 || Intent.ACTION_SEARCH.equals(action)
429 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
Leon Scroggins58d56c62010-01-28 15:12:40 -0500430 || Intent.ACTION_WEB_SEARCH.equals(action)
431 || activateVoiceSearch) {
Leon Scroggins3b18ce32010-02-08 17:35:59 -0500432 if (current.isInVoiceSearchMode()) {
433 String title = current.getVoiceDisplayTitle();
434 if (title != null && title.equals(intent.getStringExtra(
435 SearchManager.QUERY))) {
436 // The user submitted the same search as the last voice
437 // search, so do nothing.
438 return;
439 }
Leon Scroggins1fe13a52010-02-09 15:31:26 -0500440 if (Intent.ACTION_SEARCH.equals(action)
441 && current.voiceSearchSourceIsGoogle()) {
442 Intent logIntent = new Intent(
443 LoggingEvents.ACTION_LOG_EVENT);
444 logIntent.putExtra(LoggingEvents.EXTRA_EVENT,
445 LoggingEvents.VoiceSearch.QUERY_UPDATED);
446 logIntent.putExtra(
447 LoggingEvents.VoiceSearch.EXTRA_QUERY_UPDATED_VALUE,
448 intent.getDataString());
449 sendBroadcast(logIntent);
450 // Note, onPageStarted will revert the voice title bar
451 // When http://b/issue?id=2379215 is fixed, we should update
452 // the title bar here.
453 }
Leon Scroggins3b18ce32010-02-08 17:35:59 -0500454 }
Satish Sampath565505b2009-05-29 15:37:27 +0100455 // If this was a search request (e.g. search query directly typed into the address bar),
456 // pass it on to the default web search provider.
457 if (handleWebSearchIntent(intent)) {
458 return;
459 }
460
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700461 UrlData urlData = getUrlDataFromIntent(intent);
462 if (urlData.isEmpty()) {
463 urlData = new UrlData(mSettings.getHomePage());
The Android Open Source Project0c908882009-03-03 19:32:16 -0800464 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700465
Grace Klobacc634032009-07-28 15:58:19 -0700466 final String appId = intent
467 .getStringExtra(Browser.EXTRA_APPLICATION_ID);
Leon Scroggins47208682010-04-07 17:59:48 -0400468 if ((Intent.ACTION_VIEW.equals(action)
469 // If a voice search has no appId, it means that it came
470 // from the browser. In that case, reuse the current tab.
471 || (activateVoiceSearch && appId != null))
Grace Klobacc634032009-07-28 15:58:19 -0700472 && !getPackageName().equals(appId)
473 && (flags & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0) {
Grace Kloba22ac16e2009-10-07 18:00:23 -0700474 Tab appTab = mTabControl.getTabFromId(appId);
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700475 if (appTab != null) {
476 Log.i(LOGTAG, "Reusing tab for " + appId);
477 // Dismiss the subwindow if applicable.
478 dismissSubWindow(appTab);
479 // Since we might kill the WebView, remove it from the
480 // content view first.
481 removeTabFromContentView(appTab);
482 // Recreate the main WebView after destroying the old one.
483 // If the WebView has the same original url and is on that
484 // page, it can be reused.
485 boolean needsLoad =
Leon Scroggins6eac63e2010-03-15 18:19:14 -0400486 mTabControl.recreateWebView(appTab, urlData);
Ben Murdochbff2d602009-07-01 20:19:05 +0100487
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700488 if (current != appTab) {
Leon Scroggins1f005d32009-08-10 17:36:42 -0400489 switchToTab(mTabControl.getTabIndex(appTab));
490 if (needsLoad) {
Patrick Scott9d53da02010-02-19 10:19:01 -0500491 loadUrlDataIn(appTab, urlData);
Leon Scroggins1f005d32009-08-10 17:36:42 -0400492 }
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700493 } else {
Leon Scroggins1f005d32009-08-10 17:36:42 -0400494 // If the tab was the current tab, we have to attach
495 // it to the view system again.
496 attachTabToContentView(appTab);
497 if (needsLoad) {
Patrick Scott9d53da02010-02-19 10:19:01 -0500498 loadUrlDataIn(appTab, urlData);
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700499 }
500 }
501 return;
Patrick Scottcd115892009-07-16 09:42:58 -0400502 } else {
503 // No matching application tab, try to find a regular tab
504 // with a matching url.
505 appTab = mTabControl.findUnusedTabWithUrl(urlData.mUrl);
Leon Scroggins25515f82009-08-19 15:31:58 -0400506 if (appTab != null) {
507 if (current != appTab) {
508 switchToTab(mTabControl.getTabIndex(appTab));
509 }
510 // Otherwise, we are already viewing the correct tab.
Patrick Scottcd115892009-07-16 09:42:58 -0400511 } else {
512 // if FLAG_ACTIVITY_BROUGHT_TO_FRONT flag is on, the url
513 // will be opened in a new tab unless we have reached
514 // MAX_TABS. Then the url will be opened in the current
515 // tab. If a new tab is created, it will have "true" for
516 // exit on close.
Leon Scroggins1f005d32009-08-10 17:36:42 -0400517 openTabAndShow(urlData, true, appId);
Patrick Scottcd115892009-07-16 09:42:58 -0400518 }
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700519 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800520 } else {
Grace Kloba638d3f42009-11-23 10:35:04 -0800521 if (!urlData.isEmpty()
522 && urlData.mUrl.startsWith("about:debug")) {
523 if ("about:debug.dom".equals(urlData.mUrl)) {
524 current.getWebView().dumpDomTree(false);
525 } else if ("about:debug.dom.file".equals(urlData.mUrl)) {
526 current.getWebView().dumpDomTree(true);
527 } else if ("about:debug.render".equals(urlData.mUrl)) {
528 current.getWebView().dumpRenderTree(false);
529 } else if ("about:debug.render.file".equals(urlData.mUrl)) {
530 current.getWebView().dumpRenderTree(true);
531 } else if ("about:debug.display".equals(urlData.mUrl)) {
532 current.getWebView().dumpDisplayTree();
Mike Reed9b78e1d2010-01-13 14:40:52 -0800533 } else if (urlData.mUrl.startsWith("about:debug.drag")) {
534 int index = urlData.mUrl.codePointAt(16) - '0';
535 if (index <= 0 || index > 9) {
536 current.getWebView().setDragTracker(null);
537 } else {
538 current.getWebView().setDragTracker(new MeshTracker(index));
539 }
Grace Kloba638d3f42009-11-23 10:35:04 -0800540 } else {
541 mSettings.toggleDebugSettings();
542 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800543 return;
544 }
Leon Scroggins1f005d32009-08-10 17:36:42 -0400545 // Get rid of the subwindow if it exists
546 dismissSubWindow(current);
Leon Scroggins8588d152010-04-15 11:01:53 -0400547 // If the current Tab is being used as an application tab,
548 // remove the association, since the new Intent means that it is
549 // no longer associated with that application.
550 current.setAppId(null);
Patrick Scott9d53da02010-02-19 10:19:01 -0500551 loadUrlDataIn(current, urlData);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800552 }
553 }
554 }
555
Satish Sampath565505b2009-05-29 15:37:27 +0100556 /**
557 * Launches the default web search activity with the query parameters if the given intent's data
558 * are identified as plain search terms and not URLs/shortcuts.
559 * @return true if the intent was handled and web search activity was launched, false if not.
560 */
561 private boolean handleWebSearchIntent(Intent intent) {
562 if (intent == null) return false;
563
564 String url = null;
565 final String action = intent.getAction();
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -0500566 if (RecognizerResultsIntent.ACTION_VOICE_SEARCH_RESULTS.equals(
567 action)) {
Leon Scroggins58d56c62010-01-28 15:12:40 -0500568 return false;
569 }
Satish Sampath565505b2009-05-29 15:37:27 +0100570 if (Intent.ACTION_VIEW.equals(action)) {
Grace Kloba1e705052009-09-29 13:13:36 -0700571 Uri data = intent.getData();
572 if (data != null) url = data.toString();
Satish Sampath565505b2009-05-29 15:37:27 +0100573 } else if (Intent.ACTION_SEARCH.equals(action)
574 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
575 || Intent.ACTION_WEB_SEARCH.equals(action)) {
576 url = intent.getStringExtra(SearchManager.QUERY);
577 }
Bjorn Bringert04851702009-09-22 10:36:01 +0100578 return handleWebSearchRequest(url, intent.getBundleExtra(SearchManager.APP_DATA),
579 intent.getStringExtra(SearchManager.EXTRA_DATA_KEY));
Satish Sampath565505b2009-05-29 15:37:27 +0100580 }
581
582 /**
583 * Launches the default web search activity with the query parameters if the given url string
584 * was identified as plain search terms and not URL/shortcut.
585 * @return true if the request was handled and web search activity was launched, false if not.
586 */
Bjorn Bringert04851702009-09-22 10:36:01 +0100587 private boolean handleWebSearchRequest(String inUrl, Bundle appData, String extraData) {
Satish Sampath565505b2009-05-29 15:37:27 +0100588 if (inUrl == null) return false;
589
590 // In general, we shouldn't modify URL from Intent.
591 // But currently, we get the user-typed URL from search box as well.
592 String url = fixUrl(inUrl).trim();
593
Leon Scroggins956cf012010-10-07 13:51:57 -0400594 // URLs are handled by the regular flow of control, so
Satish Sampath565505b2009-05-29 15:37:27 +0100595 // return early.
Dan Egnor5ee906c2009-11-18 12:11:49 -0800596 if (Patterns.WEB_URL.matcher(url).matches()
Leon Scroggins956cf012010-10-07 13:51:57 -0400597 || ACCEPTED_URI_SCHEMA.matcher(url).matches()) {
Satish Sampath565505b2009-05-29 15:37:27 +0100598 return false;
599 }
600
Leon Scroggins8d06e362010-03-24 14:45:57 -0400601 final ContentResolver cr = mResolver;
602 final String newUrl = url;
603 new AsyncTask<Void, Void, Void>() {
604 protected Void doInBackground(Void... unused) {
605 Browser.updateVisitedHistory(cr, newUrl, false);
606 Browser.addSearchUrl(cr, newUrl);
607 return null;
608 }
609 }.execute();
Satish Sampath565505b2009-05-29 15:37:27 +0100610
Bjorn Bringertd2670652010-09-13 14:06:41 +0100611 SearchEngine searchEngine = mSettings.getSearchEngine();
612 if (searchEngine == null) return false;
613 searchEngine.startSearch(this, url, appData, extraData);
Satish Sampath565505b2009-05-29 15:37:27 +0100614
615 return true;
616 }
617
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700618 private UrlData getUrlDataFromIntent(Intent intent) {
Leon Scroggins58d56c62010-01-28 15:12:40 -0500619 String url = "";
Grace Kloba068e48b2010-01-26 18:11:27 -0800620 Map<String, String> headers = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800621 if (intent != null) {
622 final String action = intent.getAction();
623 if (Intent.ACTION_VIEW.equals(action)) {
624 url = smartUrlFilter(intent.getData());
Grace Kloba068e48b2010-01-26 18:11:27 -0800625 if (url != null && url.startsWith("http")) {
Grace Kloba00f54c52010-01-27 14:53:51 -0800626 final Bundle pairs = intent
627 .getBundleExtra(Browser.EXTRA_HEADERS);
Grace Kloba2d508ed2010-01-28 11:39:15 -0800628 if (pairs != null && !pairs.isEmpty()) {
Grace Kloba00f54c52010-01-27 14:53:51 -0800629 Iterator<String> iter = pairs.keySet().iterator();
Grace Kloba068e48b2010-01-26 18:11:27 -0800630 headers = new HashMap<String, String>();
Grace Kloba00f54c52010-01-27 14:53:51 -0800631 while (iter.hasNext()) {
632 String key = iter.next();
633 headers.put(key, pairs.getString(key));
Grace Kloba068e48b2010-01-26 18:11:27 -0800634 }
635 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700636 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800637 } else if (Intent.ACTION_SEARCH.equals(action)
638 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
639 || Intent.ACTION_WEB_SEARCH.equals(action)) {
640 url = intent.getStringExtra(SearchManager.QUERY);
641 if (url != null) {
642 mLastEnteredUrl = url;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800643 // In general, we shouldn't modify URL from Intent.
644 // But currently, we get the user-typed URL from search box as well.
645 url = fixUrl(url);
646 url = smartUrlFilter(url);
Leon Scroggins8d06e362010-03-24 14:45:57 -0400647 final ContentResolver cr = mResolver;
648 final String newUrl = url;
649 new AsyncTask<Void, Void, Void>() {
650 protected Void doInBackground(Void... unused) {
651 Browser.updateVisitedHistory(cr, newUrl, false);
652 return null;
653 }
654 }.execute();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800655 String searchSource = "&source=android-" + GOOGLE_SEARCH_SOURCE_SUGGEST + "&";
656 if (url.contains(searchSource)) {
657 String source = null;
658 final Bundle appData = intent.getBundleExtra(SearchManager.APP_DATA);
659 if (appData != null) {
Bjorn Bringert10d1cca2010-02-10 14:22:12 +0000660 source = appData.getString(Search.SOURCE);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800661 }
662 if (TextUtils.isEmpty(source)) {
663 source = GOOGLE_SEARCH_SOURCE_UNKNOWN;
664 }
665 url = url.replace(searchSource, "&source=android-"+source+"&");
666 }
667 }
668 }
669 }
Leon Scroggins58d56c62010-01-28 15:12:40 -0500670 return new UrlData(url, headers, intent);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800671 }
Leon Scroggins58d56c62010-01-28 15:12:40 -0500672 /* package */ void showVoiceTitleBar(String title) {
673 mTitleBar.setInVoiceMode(true);
674 mFakeTitleBar.setInVoiceMode(true);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800675
Leon Scroggins58d56c62010-01-28 15:12:40 -0500676 mTitleBar.setDisplayTitle(title);
677 mFakeTitleBar.setDisplayTitle(title);
678 }
679 /* package */ void revertVoiceTitleBar() {
680 mTitleBar.setInVoiceMode(false);
681 mFakeTitleBar.setInVoiceMode(false);
682
Leon Scroggins003a5dd2010-03-10 12:13:14 -0500683 mTitleBar.setDisplayTitle(mUrl);
684 mFakeTitleBar.setDisplayTitle(mUrl);
Leon Scroggins58d56c62010-01-28 15:12:40 -0500685 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800686 /* package */ static String fixUrl(String inUrl) {
Cary Clark652ff872009-09-10 13:34:44 -0400687 // FIXME: Converting the url to lower case
688 // duplicates functionality in smartUrlFilter().
689 // However, changing all current callers of fixUrl to
690 // call smartUrlFilter in addition may have unwanted
691 // consequences, and is deferred for now.
692 int colon = inUrl.indexOf(':');
693 boolean allLower = true;
694 for (int index = 0; index < colon; index++) {
695 char ch = inUrl.charAt(index);
696 if (!Character.isLetter(ch)) {
697 break;
698 }
699 allLower &= Character.isLowerCase(ch);
700 if (index == colon - 1 && !allLower) {
701 inUrl = inUrl.substring(0, colon).toLowerCase()
702 + inUrl.substring(colon);
703 }
704 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800705 if (inUrl.startsWith("http://") || inUrl.startsWith("https://"))
706 return inUrl;
707 if (inUrl.startsWith("http:") ||
708 inUrl.startsWith("https:")) {
709 if (inUrl.startsWith("http:/") || inUrl.startsWith("https:/")) {
710 inUrl = inUrl.replaceFirst("/", "//");
711 } else inUrl = inUrl.replaceFirst(":", "://");
712 }
713 return inUrl;
714 }
715
Grace Kloba22ac16e2009-10-07 18:00:23 -0700716 @Override
717 protected void onResume() {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800718 super.onResume();
Dave Bort31a6d1c2009-04-13 15:56:49 -0700719 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800720 Log.v(LOGTAG, "BrowserActivity.onResume: this=" + this);
721 }
722
723 if (!mActivityInPause) {
724 Log.e(LOGTAG, "BrowserActivity is already resumed.");
725 return;
726 }
727
Mike Reed7bfa63b2009-05-28 11:08:32 -0400728 mTabControl.resumeCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800729 mActivityInPause = false;
Mike Reed7bfa63b2009-05-28 11:08:32 -0400730 resumeWebViewTimers();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800731
732 if (mWakeLock.isHeld()) {
733 mHandler.removeMessages(RELEASE_WAKELOCK);
734 mWakeLock.release();
735 }
736
The Android Open Source Project0c908882009-03-03 19:32:16 -0800737 registerReceiver(mNetworkStateIntentReceiver,
738 mNetworkStateChangedFilter);
739 WebView.enablePlatformNotifications();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800740 }
741
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400742 /**
743 * Since the actual title bar is embedded in the WebView, and removing it
Leon Scrogginsfe87bd32009-10-06 10:10:00 -0400744 * would change its appearance, use a different TitleBar to show overlayed
745 * at the top of the screen, when the menu is open or the page is loading.
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400746 */
747 private TitleBar mFakeTitleBar;
748
749 /**
750 * Keeps track of whether the options menu is open. This is important in
751 * determining whether to show or hide the title bar overlay.
752 */
753 private boolean mOptionsMenuOpen;
754
755 /**
756 * Only meaningful when mOptionsMenuOpen is true. This variable keeps track
757 * of whether the configuration has changed. The first onMenuOpened call
758 * after a configuration change is simply a reopening of the same menu
759 * (i.e. mIconView did not change).
760 */
761 private boolean mConfigChanged;
762
763 /**
764 * Whether or not the options menu is in its smaller, icon menu form. When
765 * true, we want the title bar overlay to be up. When false, we do not.
766 * Only meaningful if mOptionsMenuOpen is true.
767 */
768 private boolean mIconView;
769
Leon Scrogginsa81a7642009-08-31 17:05:41 -0400770 @Override
771 public boolean onMenuOpened(int featureId, Menu menu) {
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400772 if (Window.FEATURE_OPTIONS_PANEL == featureId) {
773 if (mOptionsMenuOpen) {
774 if (mConfigChanged) {
775 // We do not need to make any changes to the state of the
776 // title bar, since the only thing that happened was a
777 // change in orientation
778 mConfigChanged = false;
779 } else {
780 if (mIconView) {
781 // Switching the menu to expanded view, so hide the
782 // title bar.
783 hideFakeTitleBar();
784 mIconView = false;
785 } else {
786 // Switching the menu back to icon view, so show the
787 // title bar once again.
788 showFakeTitleBar();
789 mIconView = true;
790 }
791 }
792 } else {
793 // The options menu is closed, so open it, and show the title
794 showFakeTitleBar();
795 mOptionsMenuOpen = true;
796 mConfigChanged = false;
797 mIconView = true;
798 }
799 }
Leon Scrogginsa81a7642009-08-31 17:05:41 -0400800 return true;
801 }
802
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400803 private void showFakeTitleBar() {
Leon Scrogginsfe87bd32009-10-06 10:10:00 -0400804 if (mFakeTitleBar.getParent() == null && mActiveTabsPage == null
Grace Kloba847c25b2010-03-30 16:00:26 -0700805 && !mActivityInPause) {
806 WebView mainView = mTabControl.getCurrentWebView();
807 // if there is no current WebView, don't show the faked title bar;
Grace Kloba65190702010-04-02 23:37:26 -0700808 if (mainView == null) {
Cary Clarka0464552009-09-29 13:00:45 -0400809 return;
810 }
Cary Clark2c326e62010-08-19 18:40:57 -0400811 // Do not need to check for null, since the current tab will have
812 // at least a main WebView, or we would have returned above.
813 if (dialogIsUp()) {
814 // Do not show the fake title bar, which would cover up the
815 // find or select dialog.
816 return;
817 }
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400818
819 WindowManager manager
820 = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
821
822 // Add the title bar to the window manager so it can receive touches
823 // while the menu is up
824 WindowManager.LayoutParams params
825 = new WindowManager.LayoutParams(
Romain Guy15b8ec62010-01-08 15:06:43 -0800826 ViewGroup.LayoutParams.MATCH_PARENT,
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400827 ViewGroup.LayoutParams.WRAP_CONTENT,
Grace Kloba847c25b2010-03-30 16:00:26 -0700828 WindowManager.LayoutParams.TYPE_APPLICATION,
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400829 WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
Leon Scroggins68549862009-09-21 16:02:01 -0400830 PixelFormat.TRANSLUCENT);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400831 params.gravity = Gravity.TOP;
Grace Kloba847c25b2010-03-30 16:00:26 -0700832 boolean atTop = mainView.getScrollY() == 0;
Leon Scroggins83932c72009-09-30 11:55:54 -0400833 params.windowAnimations = atTop ? 0 : R.style.TitleBar;
Grace Kloba13f9ace2010-03-18 21:44:14 -0700834 manager.addView(mFakeTitleBar, params);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400835 }
836 }
837
838 @Override
839 public void onOptionsMenuClosed(Menu menu) {
840 mOptionsMenuOpen = false;
Leon Scrogginsa27ff192009-09-14 12:58:04 -0400841 if (!mInLoad) {
842 hideFakeTitleBar();
843 } else if (!mIconView) {
844 // The page is currently loading, and we are in expanded mode, so
845 // we were not showing the menu. Show it once again. It will be
846 // removed when the page finishes.
847 showFakeTitleBar();
848 }
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400849 }
Grace Kloba22ac16e2009-10-07 18:00:23 -0700850
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400851 private void hideFakeTitleBar() {
Leon Scrogginsfe87bd32009-10-06 10:10:00 -0400852 if (mFakeTitleBar.getParent() == null) return;
Leon Scroggins20329572009-09-23 17:42:41 -0400853 WindowManager.LayoutParams params = (WindowManager.LayoutParams)
Grace Kloba13f9ace2010-03-18 21:44:14 -0700854 mFakeTitleBar.getLayoutParams();
Leon Scroggins20329572009-09-23 17:42:41 -0400855 WebView mainView = mTabControl.getCurrentWebView();
856 // Although we decided whether or not to animate based on the current
857 // scroll position, the scroll position may have changed since the
858 // fake title bar was displayed. Make sure it has the appropriate
859 // animation/lack thereof before removing.
860 params.windowAnimations = mainView != null && mainView.getScrollY() == 0
Leon Scroggins83932c72009-09-30 11:55:54 -0400861 ? 0 : R.style.TitleBar;
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400862 WindowManager manager
863 = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
Grace Kloba13f9ace2010-03-18 21:44:14 -0700864 manager.updateViewLayout(mFakeTitleBar, params);
865 manager.removeView(mFakeTitleBar);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400866 }
867
The Android Open Source Project0c908882009-03-03 19:32:16 -0800868 /**
Leon Scrogginsc6fa1102009-09-21 10:40:01 -0400869 * Special method for the fake title bar to call when displaying its context
870 * menu, since it is in its own Window, and its parent does not show a
871 * context menu.
872 */
873 /* package */ void showTitleBarContextMenu() {
Cary Clark65f4a3c2009-09-28 17:05:06 -0400874 if (null == mTitleBar.getParent()) {
875 return;
876 }
Leon Scrogginsc6fa1102009-09-21 10:40:01 -0400877 openContextMenu(mTitleBar);
878 }
879
Leon Scrogginsb2b19f52009-10-09 16:10:00 -0400880 @Override
881 public void onContextMenuClosed(Menu menu) {
882 super.onContextMenuClosed(menu);
883 if (mInLoad) {
884 showFakeTitleBar();
885 }
886 }
887
Leon Scrogginsc6fa1102009-09-21 10:40:01 -0400888 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -0800889 * onSaveInstanceState(Bundle map)
890 * onSaveInstanceState is called right before onStop(). The map contains
891 * the saved state.
892 */
Grace Kloba22ac16e2009-10-07 18:00:23 -0700893 @Override
894 protected void onSaveInstanceState(Bundle outState) {
Dave Bort31a6d1c2009-04-13 15:56:49 -0700895 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800896 Log.v(LOGTAG, "BrowserActivity.onSaveInstanceState: this=" + this);
897 }
898 // the default implementation requires each view to have an id. As the
899 // browser handles the state itself and it doesn't use id for the views,
900 // don't call the default implementation. Otherwise it will trigger the
901 // warning like this, "couldn't save which view has focus because the
902 // focused view XXX has no id".
903
904 // Save all the tabs
905 mTabControl.saveState(outState);
906 }
907
Grace Kloba22ac16e2009-10-07 18:00:23 -0700908 @Override
909 protected void onPause() {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800910 super.onPause();
911
912 if (mActivityInPause) {
913 Log.e(LOGTAG, "BrowserActivity is already paused.");
914 return;
915 }
916
Mike Reed7bfa63b2009-05-28 11:08:32 -0400917 mTabControl.pauseCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800918 mActivityInPause = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -0400919 if (mTabControl.getCurrentIndex() >= 0 && !pauseWebViewTimers()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800920 mWakeLock.acquire();
921 mHandler.sendMessageDelayed(mHandler
922 .obtainMessage(RELEASE_WAKELOCK), WAKELOCK_TIMEOUT);
923 }
924
Leon Scrogginsa2ab6a72009-09-11 11:49:52 -0400925 // FIXME: This removes the active tabs page and resets the menu to
926 // MAIN_MENU. A better solution might be to do this work in onNewIntent
927 // but then we would need to save it in onSaveInstanceState and restore
928 // it in onCreate/onRestoreInstanceState
929 if (mActiveTabsPage != null) {
930 removeActiveTabPage(true);
931 }
932
The Android Open Source Project0c908882009-03-03 19:32:16 -0800933 cancelStopToast();
934
935 // unregister network state listener
936 unregisterReceiver(mNetworkStateIntentReceiver);
937 WebView.disablePlatformNotifications();
Ben Murdocha4909cb2010-11-30 20:48:15 +0000938
939 if (mCustomView != null) {
940 mTabControl.getCurrentWebView().getWebChromeClient().onHideCustomView();
941 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800942 }
943
Grace Kloba22ac16e2009-10-07 18:00:23 -0700944 @Override
945 protected void onDestroy() {
Dave Bort31a6d1c2009-04-13 15:56:49 -0700946 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800947 Log.v(LOGTAG, "BrowserActivity.onDestroy: this=" + this);
948 }
949 super.onDestroy();
Grace Kloba0923d692009-09-23 21:37:25 -0700950
Leon Scroggins8d5fa432009-10-02 15:55:59 -0400951 if (mUploadMessage != null) {
952 mUploadMessage.onReceiveValue(null);
953 mUploadMessage = null;
954 }
955
Grace Kloba0923d692009-09-23 21:37:25 -0700956 if (mTabControl == null) return;
957
Grace Kloba1fc98a32009-10-21 13:23:08 -0700958 // Remove the fake title bar if it is there
959 hideFakeTitleBar();
960
The Android Open Source Project0c908882009-03-03 19:32:16 -0800961 // Remove the current tab and sub window
Grace Kloba22ac16e2009-10-07 18:00:23 -0700962 Tab t = mTabControl.getCurrentTab();
Patrick Scottfb5e77f2009-04-08 19:17:37 -0700963 if (t != null) {
964 dismissSubWindow(t);
965 removeTabFromContentView(t);
966 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800967 // Destroy all the tabs
968 mTabControl.destroy();
969 WebIconDatabase.getInstance().close();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800970
Grace Klobab4da0ad2009-05-14 14:45:40 -0700971 unregisterReceiver(mPackageInstallationReceiver);
Bjorn Bringerta7611812010-03-24 11:12:02 +0000972
973 // Stop watching the default geolocation permissions
974 mSystemAllowGeolocationOrigins.stop();
975 mSystemAllowGeolocationOrigins = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800976 }
977
978 @Override
979 public void onConfigurationChanged(Configuration newConfig) {
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400980 mConfigChanged = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800981 super.onConfigurationChanged(newConfig);
982
983 if (mPageInfoDialog != null) {
984 mPageInfoDialog.dismiss();
985 showPageInfo(
986 mPageInfoView,
Leon Scrogginsc7b92f82010-01-11 18:17:31 -0500987 mPageInfoFromShowSSLCertificateOnError);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800988 }
989 if (mSSLCertificateDialog != null) {
990 mSSLCertificateDialog.dismiss();
991 showSSLCertificate(
992 mSSLCertificateView);
993 }
994 if (mSSLCertificateOnErrorDialog != null) {
995 mSSLCertificateOnErrorDialog.dismiss();
996 showSSLCertificateOnError(
997 mSSLCertificateOnErrorView,
998 mSSLCertificateOnErrorHandler,
999 mSSLCertificateOnErrorError);
1000 }
1001 if (mHttpAuthenticationDialog != null) {
1002 String title = ((TextView) mHttpAuthenticationDialog
1003 .findViewById(com.android.internal.R.id.alertTitle)).getText()
1004 .toString();
1005 String name = ((TextView) mHttpAuthenticationDialog
1006 .findViewById(R.id.username_edit)).getText().toString();
1007 String password = ((TextView) mHttpAuthenticationDialog
1008 .findViewById(R.id.password_edit)).getText().toString();
1009 int focusId = mHttpAuthenticationDialog.getCurrentFocus()
1010 .getId();
1011 mHttpAuthenticationDialog.dismiss();
1012 showHttpAuthentication(mHttpAuthHandler, null, null, title,
1013 name, password, focusId);
1014 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001015 }
1016
Grace Kloba22ac16e2009-10-07 18:00:23 -07001017 @Override
1018 public void onLowMemory() {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001019 super.onLowMemory();
1020 mTabControl.freeMemory();
1021 }
1022
Cary Clarkff4d92c2010-03-25 11:17:03 -04001023 private void resumeWebViewTimers() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001024 Tab tab = mTabControl.getCurrentTab();
Cary Clarkff4d92c2010-03-25 11:17:03 -04001025 if (tab == null) return; // monkey can trigger this
Grace Kloba22ac16e2009-10-07 18:00:23 -07001026 boolean inLoad = tab.inLoad();
1027 if ((!mActivityInPause && !inLoad) || (mActivityInPause && inLoad)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001028 CookieSyncManager.getInstance().startSync();
Grace Kloba22ac16e2009-10-07 18:00:23 -07001029 WebView w = tab.getWebView();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001030 if (w != null) {
1031 w.resumeTimers();
1032 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001033 }
1034 }
1035
Mike Reed7bfa63b2009-05-28 11:08:32 -04001036 private boolean pauseWebViewTimers() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001037 Tab tab = mTabControl.getCurrentTab();
1038 boolean inLoad = tab.inLoad();
1039 if (mActivityInPause && !inLoad) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001040 CookieSyncManager.getInstance().stopSync();
1041 WebView w = mTabControl.getCurrentWebView();
1042 if (w != null) {
1043 w.pauseTimers();
1044 }
1045 return true;
1046 } else {
1047 return false;
1048 }
1049 }
1050
The Android Open Source Project0c908882009-03-03 19:32:16 -08001051 // Open the icon database and retain all the icons for visited sites.
1052 private void retainIconsOnStartup() {
1053 final WebIconDatabase db = WebIconDatabase.getInstance();
1054 db.open(getDir("icons", 0).getPath());
Leon Scroggins2c0f6112010-03-12 18:09:39 -05001055 Cursor c = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001056 try {
Leon Scroggins2c0f6112010-03-12 18:09:39 -05001057 c = Browser.getAllBookmarks(mResolver);
1058 if (c.moveToFirst()) {
1059 int urlIndex = c.getColumnIndex(Browser.BookmarkColumns.URL);
1060 do {
1061 String url = c.getString(urlIndex);
1062 db.retainIconForPageUrl(url);
1063 } while (c.moveToNext());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001064 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001065 } catch (IllegalStateException e) {
1066 Log.e(LOGTAG, "retainIconsOnStartup", e);
Leon Scroggins2c0f6112010-03-12 18:09:39 -05001067 } finally {
1068 if (c!= null) c.close();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001069 }
1070 }
1071
1072 // Helper method for getting the top window.
1073 WebView getTopWindow() {
1074 return mTabControl.getCurrentTopWebView();
1075 }
1076
Grace Kloba22ac16e2009-10-07 18:00:23 -07001077 TabControl getTabControl() {
1078 return mTabControl;
1079 }
1080
The Android Open Source Project0c908882009-03-03 19:32:16 -08001081 @Override
1082 public boolean onCreateOptionsMenu(Menu menu) {
1083 super.onCreateOptionsMenu(menu);
1084
1085 MenuInflater inflater = getMenuInflater();
1086 inflater.inflate(R.menu.browser, menu);
1087 mMenu = menu;
1088 updateInLoadMenuItems();
1089 return true;
1090 }
1091
1092 /**
1093 * As the menu can be open when loading state changes
1094 * we must manually update the state of the stop/reload menu
1095 * item
1096 */
1097 private void updateInLoadMenuItems() {
1098 if (mMenu == null) {
1099 return;
1100 }
1101 MenuItem src = mInLoad ?
1102 mMenu.findItem(R.id.stop_menu_id):
1103 mMenu.findItem(R.id.reload_menu_id);
1104 MenuItem dest = mMenu.findItem(R.id.stop_reload_menu_id);
1105 dest.setIcon(src.getIcon());
1106 dest.setTitle(src.getTitle());
1107 }
1108
1109 @Override
1110 public boolean onContextItemSelected(MenuItem item) {
1111 // chording is not an issue with context menus, but we use the same
1112 // options selector, so set mCanChord to true so we can access them.
1113 mCanChord = true;
1114 int id = item.getItemId();
Leon Scroggins96afcb12009-12-10 12:35:56 -05001115 boolean result = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001116 switch (id) {
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001117 // For the context menu from the title bar
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001118 case R.id.title_bar_copy_page_url:
Leon Scroggins96afcb12009-12-10 12:35:56 -05001119 Tab currentTab = mTabControl.getCurrentTab();
1120 if (null == currentTab) {
1121 result = false;
1122 break;
1123 }
1124 WebView mainView = currentTab.getWebView();
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001125 if (null == mainView) {
Leon Scroggins96afcb12009-12-10 12:35:56 -05001126 result = false;
1127 break;
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001128 }
Leon Scroggins96afcb12009-12-10 12:35:56 -05001129 copy(mainView.getUrl());
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001130 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001131 // -- Browser context menu
1132 case R.id.open_context_menu_id:
1133 case R.id.open_newtab_context_menu_id:
1134 case R.id.bookmark_context_menu_id:
1135 case R.id.save_link_context_menu_id:
1136 case R.id.share_link_context_menu_id:
1137 case R.id.copy_link_context_menu_id:
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001138 final WebView webView = getTopWindow();
1139 if (null == webView) {
Leon Scroggins96afcb12009-12-10 12:35:56 -05001140 result = false;
1141 break;
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001142 }
1143 final HashMap hrefMap = new HashMap();
1144 hrefMap.put("webview", webView);
1145 final Message msg = mHandler.obtainMessage(
1146 FOCUS_NODE_HREF, id, 0, hrefMap);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001147 webView.requestFocusNodeHref(msg);
1148 break;
1149
1150 default:
1151 // For other context menus
Leon Scroggins96afcb12009-12-10 12:35:56 -05001152 result = onOptionsItemSelected(item);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001153 }
1154 mCanChord = false;
Leon Scroggins96afcb12009-12-10 12:35:56 -05001155 return result;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001156 }
1157
1158 private Bundle createGoogleSearchSourceBundle(String source) {
1159 Bundle bundle = new Bundle();
Bjorn Bringert10d1cca2010-02-10 14:22:12 +00001160 bundle.putString(Search.SOURCE, source);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001161 return bundle;
1162 }
1163
Leon Scroggins8ad29922010-02-16 12:33:55 -05001164 /* package */ void editUrl() {
Leon Scroggins68579392009-09-15 15:31:54 -04001165 if (mOptionsMenuOpen) closeOptionsMenu();
Leon Scroggins5bbe9802009-07-31 13:10:55 -04001166 String url = (getTopWindow() == null) ? null : getTopWindow().getUrl();
Grace Kloba83f47342009-07-20 10:44:31 -07001167 startSearch(mSettings.getHomePage().equals(url) ? null : url, true,
Leon Scroggins8ad29922010-02-16 12:33:55 -05001168 null, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001169 }
1170
Leon Scroggins8ad29922010-02-16 12:33:55 -05001171 /**
1172 * Overriding this to insert a local information bundle
1173 */
The Android Open Source Project0c908882009-03-03 19:32:16 -08001174 @Override
1175 public void startSearch(String initialQuery, boolean selectInitialQuery,
1176 Bundle appSearchData, boolean globalSearch) {
1177 if (appSearchData == null) {
1178 appSearchData = createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_TYPE);
1179 }
Leon Scroggins III430057d2010-09-14 10:57:37 -04001180
1181 SearchEngine searchEngine = mSettings.getSearchEngine();
1182 if (searchEngine != null && !searchEngine.supportsVoiceSearch()) {
1183 appSearchData.putBoolean(SearchManager.DISABLE_VOICE_SEARCH, true);
1184 }
1185
The Android Open Source Project0c908882009-03-03 19:32:16 -08001186 super.startSearch(initialQuery, selectInitialQuery, appSearchData, globalSearch);
1187 }
1188
Leon Scroggins1f005d32009-08-10 17:36:42 -04001189 /**
1190 * Switch tabs. Called by the TitleBarSet when sliding the title bar
1191 * results in changing tabs.
Leon Scroggins160a7e72009-08-14 18:28:01 -04001192 * @param index Index of the tab to change to, as defined by
1193 * mTabControl.getTabIndex(Tab t).
1194 * @return boolean True if we successfully switched to a different tab. If
1195 * the indexth tab is null, or if that tab is the same as
1196 * the current one, return false.
Leon Scroggins1f005d32009-08-10 17:36:42 -04001197 */
Leon Scroggins160a7e72009-08-14 18:28:01 -04001198 /* package */ boolean switchToTab(int index) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001199 Tab tab = mTabControl.getTab(index);
1200 Tab currentTab = mTabControl.getCurrentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04001201 if (tab == null || tab == currentTab) {
Leon Scroggins160a7e72009-08-14 18:28:01 -04001202 return false;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001203 }
1204 if (currentTab != null) {
1205 // currentTab may be null if it was just removed. In that case,
1206 // we do not need to remove it
1207 removeTabFromContentView(currentTab);
1208 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001209 mTabControl.setCurrentTab(tab);
1210 attachTabToContentView(tab);
Grace Klobaeb6eef42009-09-15 17:56:32 -07001211 resetTitleIconAndProgress();
1212 updateLockIconToLatest();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001213 return true;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001214 }
1215
Grace Kloba22ac16e2009-10-07 18:00:23 -07001216 /* package */ Tab openTabToHomePage() {
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001217 return openTabAndShow(mSettings.getHomePage(), false, null);
1218 }
1219
Leon Scroggins1f005d32009-08-10 17:36:42 -04001220 /* package */ void closeCurrentWindow() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001221 final Tab current = mTabControl.getCurrentTab();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001222 if (mTabControl.getTabCount() == 1) {
Leon Scroggins30444232009-09-04 18:36:20 -04001223 // This is the last tab. Open a new one, with the home
1224 // page and close the current one.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001225 openTabToHomePage();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001226 closeTab(current);
Leon Scroggins160a7e72009-08-14 18:28:01 -04001227 return;
1228 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07001229 final Tab parent = current.getParentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04001230 int indexToShow = -1;
1231 if (parent != null) {
1232 indexToShow = mTabControl.getTabIndex(parent);
1233 } else {
Leon Scroggins160a7e72009-08-14 18:28:01 -04001234 final int currentIndex = mTabControl.getCurrentIndex();
1235 // Try to move to the tab to the right
1236 indexToShow = currentIndex + 1;
1237 if (indexToShow > mTabControl.getTabCount() - 1) {
1238 // Try to move to the tab to the left
1239 indexToShow = currentIndex - 1;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001240 }
1241 }
Leon Scroggins160a7e72009-08-14 18:28:01 -04001242 if (switchToTab(indexToShow)) {
1243 // Close window
1244 closeTab(current);
1245 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001246 }
1247
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001248 private ActiveTabsPage mActiveTabsPage;
1249
1250 /**
1251 * Remove the active tabs page.
1252 * @param needToAttach If true, the active tabs page did not attach a tab
1253 * to the content view, so we need to do that here.
1254 */
1255 /* package */ void removeActiveTabPage(boolean needToAttach) {
1256 mContentView.removeView(mActiveTabsPage);
1257 mActiveTabsPage = null;
1258 mMenuState = R.id.MAIN_MENU;
1259 if (needToAttach) {
1260 attachTabToContentView(mTabControl.getCurrentTab());
1261 }
1262 getTopWindow().requestFocus();
1263 }
1264
Cary Clark2c326e62010-08-19 18:40:57 -04001265 private WebView showDialog(WebDialog dialog) {
Cary Clark2c326e62010-08-19 18:40:57 -04001266 Tab tab = mTabControl.getCurrentTab();
1267 if (tab.getSubWebView() == null) {
1268 // If the find or select is being performed on the main webview,
1269 // remove the embedded title bar.
1270 WebView mainView = tab.getWebView();
1271 if (mainView != null) {
1272 mainView.setEmbeddedTitleBar(null);
1273 }
1274 }
1275 hideFakeTitleBar();
1276 mMenuState = EMPTY_MENU;
1277 return tab.showDialog(dialog);
1278 }
1279
The Android Open Source Project0c908882009-03-03 19:32:16 -08001280 @Override
1281 public boolean onOptionsItemSelected(MenuItem item) {
1282 if (!mCanChord) {
1283 // The user has already fired a shortcut with this hold down of the
1284 // menu key.
1285 return false;
1286 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001287 if (null == getTopWindow()) {
Leon Scroggins0d7ae0e2009-06-05 11:04:45 -04001288 return false;
1289 }
Grace Kloba6ee9c492009-07-13 10:04:34 -07001290 if (mMenuIsDown) {
1291 // The shortcut action consumes the MENU. Even if it is still down,
1292 // it won't trigger the next shortcut action. In the case of the
1293 // shortcut action triggering a new activity, like Bookmarks, we
1294 // won't get onKeyUp for MENU. So it is important to reset it here.
1295 mMenuIsDown = false;
1296 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001297 switch (item.getItemId()) {
1298 // -- Main menu
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001299 case R.id.new_tab_menu_id:
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001300 openTabToHomePage();
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001301 break;
1302
Leon Scroggins64b80f32009-08-07 12:03:34 -04001303 case R.id.goto_menu_id:
Leon Scroggins8ad29922010-02-16 12:33:55 -05001304 editUrl();
Leon Scrogginsb3a5bed2009-09-28 11:21:56 -04001305 break;
1306
1307 case R.id.bookmarks_menu_id:
Leon Scroggins30444232009-09-04 18:36:20 -04001308 bookmarksOrHistoryPicker(false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001309 break;
1310
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001311 case R.id.active_tabs_menu_id:
1312 mActiveTabsPage = new ActiveTabsPage(this, mTabControl);
1313 removeTabFromContentView(mTabControl.getCurrentTab());
Leon Scroggins43de6162009-09-14 19:59:58 -04001314 hideFakeTitleBar();
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001315 mContentView.addView(mActiveTabsPage, COVER_SCREEN_PARAMS);
1316 mActiveTabsPage.requestFocus();
1317 mMenuState = EMPTY_MENU;
1318 break;
1319
Leon Scroggins1f005d32009-08-10 17:36:42 -04001320 case R.id.add_bookmark_menu_id:
1321 Intent i = new Intent(BrowserActivity.this,
1322 AddBookmarkPage.class);
1323 WebView w = getTopWindow();
1324 i.putExtra("url", w.getUrl());
1325 i.putExtra("title", w.getTitle());
Grace Kloba83cdb2c2009-09-16 00:48:57 -07001326 i.putExtra("touch_icon_url", w.getTouchIconUrl());
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01001327 i.putExtra("thumbnail", createScreenshot(w));
Leon Scroggins1f005d32009-08-10 17:36:42 -04001328 startActivity(i);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001329 break;
1330
1331 case R.id.stop_reload_menu_id:
1332 if (mInLoad) {
1333 stopLoading();
1334 } else {
1335 getTopWindow().reload();
1336 }
1337 break;
1338
1339 case R.id.back_menu_id:
1340 getTopWindow().goBack();
1341 break;
1342
1343 case R.id.forward_menu_id:
1344 getTopWindow().goForward();
1345 break;
1346
1347 case R.id.close_menu_id:
1348 // Close the subwindow if it exists.
1349 if (mTabControl.getCurrentSubWindow() != null) {
1350 dismissSubWindow(mTabControl.getCurrentTab());
1351 break;
1352 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001353 closeCurrentWindow();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001354 break;
1355
1356 case R.id.homepage_menu_id:
Grace Kloba22ac16e2009-10-07 18:00:23 -07001357 Tab current = mTabControl.getCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001358 if (current != null) {
1359 dismissSubWindow(current);
Leon Scroggins92472e82010-02-17 16:32:28 -05001360 loadUrl(current.getWebView(), mSettings.getHomePage());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001361 }
1362 break;
1363
1364 case R.id.preferences_menu_id:
1365 Intent intent = new Intent(this,
1366 BrowserPreferencesPage.class);
Leon Scrogginsd5304942009-12-10 16:11:39 -05001367 intent.putExtra(BrowserPreferencesPage.CURRENT_PAGE,
1368 getTopWindow().getUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001369 startActivityForResult(intent, PREFERENCES_PAGE);
1370 break;
1371
1372 case R.id.find_menu_id:
Cary Clark2c326e62010-08-19 18:40:57 -04001373 showFindDialog();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001374 break;
1375
1376 case R.id.select_text_id:
Cary Clark5feb8ad2010-09-21 14:28:49 -04001377 if (true) {
1378 Tab currentTab = mTabControl.getCurrentTab();
1379 if (currentTab != null) {
1380 currentTab.getWebView().setUpSelect();
1381 }
1382 } else {
1383 showSelectDialog();
1384 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001385 break;
Cary Clark2c326e62010-08-19 18:40:57 -04001386
The Android Open Source Project0c908882009-03-03 19:32:16 -08001387 case R.id.page_info_menu_id:
1388 showPageInfo(mTabControl.getCurrentTab(), false);
1389 break;
1390
1391 case R.id.classic_history_menu_id:
Leon Scroggins30444232009-09-04 18:36:20 -04001392 bookmarksOrHistoryPicker(true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001393 break;
1394
Leon Scroggins96afcb12009-12-10 12:35:56 -05001395 case R.id.title_bar_share_page_url:
The Android Open Source Project0c908882009-03-03 19:32:16 -08001396 case R.id.share_page_menu_id:
Leon Scroggins96afcb12009-12-10 12:35:56 -05001397 Tab currentTab = mTabControl.getCurrentTab();
1398 if (null == currentTab) {
1399 mCanChord = false;
1400 return false;
1401 }
1402 currentTab.populatePickerData();
1403 sharePage(this, currentTab.getTitle(),
1404 currentTab.getUrl(), currentTab.getFavicon(),
1405 createScreenshot(currentTab.getWebView()));
The Android Open Source Project0c908882009-03-03 19:32:16 -08001406 break;
1407
1408 case R.id.dump_nav_menu_id:
1409 getTopWindow().debugDump();
1410 break;
1411
Andrei Popescu7a8b88b2010-02-02 00:30:38 +00001412 case R.id.dump_counters_menu_id:
1413 getTopWindow().dumpV8Counters();
1414 break;
1415
The Android Open Source Project0c908882009-03-03 19:32:16 -08001416 case R.id.zoom_in_menu_id:
1417 getTopWindow().zoomIn();
1418 break;
1419
1420 case R.id.zoom_out_menu_id:
1421 getTopWindow().zoomOut();
1422 break;
1423
1424 case R.id.view_downloads_menu_id:
Leon Scroggins IIIa682a3c2010-09-27 12:32:40 -04001425 viewDownloads();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001426 break;
1427
The Android Open Source Project0c908882009-03-03 19:32:16 -08001428 case R.id.window_one_menu_id:
1429 case R.id.window_two_menu_id:
1430 case R.id.window_three_menu_id:
1431 case R.id.window_four_menu_id:
1432 case R.id.window_five_menu_id:
1433 case R.id.window_six_menu_id:
1434 case R.id.window_seven_menu_id:
1435 case R.id.window_eight_menu_id:
1436 {
1437 int menuid = item.getItemId();
1438 for (int id = 0; id < WINDOW_SHORTCUT_ID_ARRAY.length; id++) {
1439 if (WINDOW_SHORTCUT_ID_ARRAY[id] == menuid) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001440 Tab desiredTab = mTabControl.getTab(id);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001441 if (desiredTab != null &&
1442 desiredTab != mTabControl.getCurrentTab()) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001443 switchToTab(id);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001444 }
1445 break;
1446 }
1447 }
1448 }
1449 break;
1450
1451 default:
1452 if (!super.onOptionsItemSelected(item)) {
1453 return false;
1454 }
1455 // Otherwise fall through.
1456 }
1457 mCanChord = false;
1458 return true;
1459 }
1460
Cary Clark2c326e62010-08-19 18:40:57 -04001461 private boolean dialogIsUp() {
1462 return null != mFindDialog && mFindDialog.isVisible() ||
1463 null != mSelectDialog && mSelectDialog.isVisible();
1464 }
1465
1466 private boolean closeDialog(WebDialog dialog) {
1467 if (null == dialog || !dialog.isVisible()) return false;
1468 Tab currentTab = mTabControl.getCurrentTab();
1469 currentTab.closeDialog(dialog);
1470 dialog.dismiss();
1471 return true;
1472 }
1473
1474 /*
1475 * Remove the find dialog or select dialog.
1476 */
1477 public void closeDialogs() {
1478 if (!(closeDialog(mFindDialog) || closeDialog(mSelectDialog))) return;
1479 // If the Find was being performed in the main WebView, replace the
1480 // embedded title bar.
1481 Tab currentTab = mTabControl.getCurrentTab();
1482 if (currentTab.getSubWebView() == null) {
1483 WebView mainView = currentTab.getWebView();
1484 if (mainView != null) {
1485 mainView.setEmbeddedTitleBar(mTitleBar);
1486 }
1487 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001488 mMenuState = R.id.MAIN_MENU;
Cary Clark2c326e62010-08-19 18:40:57 -04001489 if (mInLoad) {
1490 // The title bar was hidden, because otherwise it would cover up the
1491 // find or select dialog. Now that the dialog has been removed,
1492 // show the fake title bar once again.
1493 showFakeTitleBar();
1494 }
1495 }
1496
1497 public void showFindDialog() {
1498 if (null == mFindDialog) {
1499 mFindDialog = new FindDialog(this);
1500 }
1501 showDialog(mFindDialog).setFindIsUp(true);
1502 }
1503
1504 public void setFindDialogText(String text) {
1505 mFindDialog.setText(text);
1506 }
1507
1508 public void showSelectDialog() {
1509 if (null == mSelectDialog) {
1510 mSelectDialog = new SelectDialog(this);
1511 }
1512 showDialog(mSelectDialog).setUpSelect();
1513 mSelectDialog.hideSoftInput();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001514 }
1515
Grace Kloba22ac16e2009-10-07 18:00:23 -07001516 @Override
1517 public boolean onPrepareOptionsMenu(Menu menu) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001518 // This happens when the user begins to hold down the menu key, so
1519 // allow them to chord to get a shortcut.
1520 mCanChord = true;
1521 // Note: setVisible will decide whether an item is visible; while
1522 // setEnabled() will decide whether an item is enabled, which also means
1523 // whether the matching shortcut key will function.
1524 super.onPrepareOptionsMenu(menu);
1525 switch (mMenuState) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001526 case EMPTY_MENU:
1527 if (mCurrentMenuState != mMenuState) {
1528 menu.setGroupVisible(R.id.MAIN_MENU, false);
1529 menu.setGroupEnabled(R.id.MAIN_MENU, false);
1530 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001531 }
1532 break;
1533 default:
1534 if (mCurrentMenuState != mMenuState) {
1535 menu.setGroupVisible(R.id.MAIN_MENU, true);
1536 menu.setGroupEnabled(R.id.MAIN_MENU, true);
1537 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001538 }
1539 final WebView w = getTopWindow();
1540 boolean canGoBack = false;
1541 boolean canGoForward = false;
1542 boolean isHome = false;
1543 if (w != null) {
1544 canGoBack = w.canGoBack();
1545 canGoForward = w.canGoForward();
1546 isHome = mSettings.getHomePage().equals(w.getUrl());
1547 }
1548 final MenuItem back = menu.findItem(R.id.back_menu_id);
1549 back.setEnabled(canGoBack);
1550
1551 final MenuItem home = menu.findItem(R.id.homepage_menu_id);
1552 home.setEnabled(!isHome);
1553
1554 menu.findItem(R.id.forward_menu_id)
1555 .setEnabled(canGoForward);
1556
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001557 menu.findItem(R.id.new_tab_menu_id).setEnabled(
Grace Kloba22ac16e2009-10-07 18:00:23 -07001558 mTabControl.canCreateNewTab());
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001559
The Android Open Source Project0c908882009-03-03 19:32:16 -08001560 // decide whether to show the share link option
1561 PackageManager pm = getPackageManager();
1562 Intent send = new Intent(Intent.ACTION_SEND);
1563 send.setType("text/plain");
1564 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1565 menu.findItem(R.id.share_page_menu_id).setVisible(ri != null);
1566
The Android Open Source Project0c908882009-03-03 19:32:16 -08001567 boolean isNavDump = mSettings.isNavDump();
1568 final MenuItem nav = menu.findItem(R.id.dump_nav_menu_id);
1569 nav.setVisible(isNavDump);
1570 nav.setEnabled(isNavDump);
Andrei Popescu7a8b88b2010-02-02 00:30:38 +00001571
1572 boolean showDebugSettings = mSettings.showDebugSettings();
1573 final MenuItem counter = menu.findItem(R.id.dump_counters_menu_id);
1574 counter.setVisible(showDebugSettings);
1575 counter.setEnabled(showDebugSettings);
1576
The Android Open Source Project0c908882009-03-03 19:32:16 -08001577 break;
1578 }
1579 mCurrentMenuState = mMenuState;
1580 return true;
1581 }
1582
1583 @Override
1584 public void onCreateContextMenu(ContextMenu menu, View v,
1585 ContextMenuInfo menuInfo) {
Leon Scroggins4e9f89b2010-02-22 16:54:14 -05001586 if (v instanceof TitleBar) {
1587 return;
1588 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001589 WebView webview = (WebView) v;
1590 WebView.HitTestResult result = webview.getHitTestResult();
1591 if (result == null) {
1592 return;
1593 }
1594
1595 int type = result.getType();
1596 if (type == WebView.HitTestResult.UNKNOWN_TYPE) {
1597 Log.w(LOGTAG,
1598 "We should not show context menu when nothing is touched");
1599 return;
1600 }
1601 if (type == WebView.HitTestResult.EDIT_TEXT_TYPE) {
1602 // let TextView handles context menu
1603 return;
1604 }
1605
1606 // Note, http://b/issue?id=1106666 is requesting that
1607 // an inflated menu can be used again. This is not available
1608 // yet, so inflate each time (yuk!)
1609 MenuInflater inflater = getMenuInflater();
1610 inflater.inflate(R.menu.browsercontext, menu);
1611
1612 // Show the correct menu group
1613 String extra = result.getExtra();
1614 menu.setGroupVisible(R.id.PHONE_MENU,
1615 type == WebView.HitTestResult.PHONE_TYPE);
1616 menu.setGroupVisible(R.id.EMAIL_MENU,
1617 type == WebView.HitTestResult.EMAIL_TYPE);
1618 menu.setGroupVisible(R.id.GEO_MENU,
1619 type == WebView.HitTestResult.GEO_TYPE);
1620 menu.setGroupVisible(R.id.IMAGE_MENU,
1621 type == WebView.HitTestResult.IMAGE_TYPE
1622 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1623 menu.setGroupVisible(R.id.ANCHOR_MENU,
1624 type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1625 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1626
1627 // Setup custom handling depending on the type
1628 switch (type) {
1629 case WebView.HitTestResult.PHONE_TYPE:
1630 menu.setHeaderTitle(Uri.decode(extra));
1631 menu.findItem(R.id.dial_context_menu_id).setIntent(
1632 new Intent(Intent.ACTION_VIEW, Uri
1633 .parse(WebView.SCHEME_TEL + extra)));
1634 Intent addIntent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
1635 addIntent.putExtra(Insert.PHONE, Uri.decode(extra));
Cary Clark5e335a32009-09-22 14:53:11 -04001636 addIntent.setType(ContactsContract.Contacts.CONTENT_ITEM_TYPE);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001637 menu.findItem(R.id.add_contact_context_menu_id).setIntent(
1638 addIntent);
1639 menu.findItem(R.id.copy_phone_context_menu_id).setOnMenuItemClickListener(
1640 new Copy(extra));
1641 break;
1642
1643 case WebView.HitTestResult.EMAIL_TYPE:
1644 menu.setHeaderTitle(extra);
1645 menu.findItem(R.id.email_context_menu_id).setIntent(
1646 new Intent(Intent.ACTION_VIEW, Uri
1647 .parse(WebView.SCHEME_MAILTO + extra)));
1648 menu.findItem(R.id.copy_mail_context_menu_id).setOnMenuItemClickListener(
1649 new Copy(extra));
1650 break;
1651
1652 case WebView.HitTestResult.GEO_TYPE:
1653 menu.setHeaderTitle(extra);
1654 menu.findItem(R.id.map_context_menu_id).setIntent(
1655 new Intent(Intent.ACTION_VIEW, Uri
1656 .parse(WebView.SCHEME_GEO
1657 + URLEncoder.encode(extra))));
1658 menu.findItem(R.id.copy_geo_context_menu_id).setOnMenuItemClickListener(
1659 new Copy(extra));
1660 break;
1661
1662 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1663 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
1664 TextView titleView = (TextView) LayoutInflater.from(this)
1665 .inflate(android.R.layout.browser_link_context_header,
1666 null);
1667 titleView.setText(extra);
1668 menu.setHeaderView(titleView);
1669 // decide whether to show the open link in new tab option
1670 menu.findItem(R.id.open_newtab_context_menu_id).setVisible(
Grace Kloba22ac16e2009-10-07 18:00:23 -07001671 mTabControl.canCreateNewTab());
Ben Murdochde353622009-10-12 10:29:00 +01001672 menu.findItem(R.id.bookmark_context_menu_id).setVisible(
1673 Bookmarks.urlHasAcceptableScheme(extra));
The Android Open Source Project0c908882009-03-03 19:32:16 -08001674 PackageManager pm = getPackageManager();
1675 Intent send = new Intent(Intent.ACTION_SEND);
1676 send.setType("text/plain");
1677 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1678 menu.findItem(R.id.share_link_context_menu_id).setVisible(ri != null);
1679 if (type == WebView.HitTestResult.SRC_ANCHOR_TYPE) {
1680 break;
1681 }
1682 // otherwise fall through to handle image part
1683 case WebView.HitTestResult.IMAGE_TYPE:
1684 if (type == WebView.HitTestResult.IMAGE_TYPE) {
1685 menu.setHeaderTitle(extra);
1686 }
1687 menu.findItem(R.id.view_image_context_menu_id).setIntent(
1688 new Intent(Intent.ACTION_VIEW, Uri.parse(extra)));
1689 menu.findItem(R.id.download_context_menu_id).
1690 setOnMenuItemClickListener(new Download(extra));
Ben Murdoch4f75ba22009-10-27 11:48:28 +00001691 menu.findItem(R.id.set_wallpaper_context_menu_id).
1692 setOnMenuItemClickListener(new SetAsWallpaper(extra));
The Android Open Source Project0c908882009-03-03 19:32:16 -08001693 break;
1694
1695 default:
1696 Log.w(LOGTAG, "We should not get here.");
1697 break;
1698 }
Leon Scrogginsb2b19f52009-10-09 16:10:00 -04001699 hideFakeTitleBar();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001700 }
1701
The Android Open Source Project0c908882009-03-03 19:32:16 -08001702 // Attach the given tab to the content view.
Grace Klobac928c302009-09-17 11:51:21 -07001703 // this should only be called for the current tab.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001704 private void attachTabToContentView(Tab t) {
Steve Block2bc69912009-07-30 14:45:13 +01001705 // Attach the container that contains the main WebView and any other UI
1706 // associated with the tab.
Patrick Scottd0119532009-09-17 08:00:31 -04001707 t.attachTabToContentView(mContentView);
Ben Murdochbff2d602009-07-01 20:19:05 +01001708
1709 if (mShouldShowErrorConsole) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001710 ErrorConsoleView errorConsole = t.getErrorConsole(true);
Ben Murdochbff2d602009-07-01 20:19:05 +01001711 if (errorConsole.numberOfErrors() == 0) {
1712 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
1713 } else {
1714 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
1715 }
1716
1717 mErrorConsoleContainer.addView(errorConsole,
Romain Guy15b8ec62010-01-08 15:06:43 -08001718 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
Ben Murdochbff2d602009-07-01 20:19:05 +01001719 ViewGroup.LayoutParams.WRAP_CONTENT));
1720 }
1721
Leon Scroggins39ab28e2009-09-02 21:20:30 -04001722 WebView view = t.getWebView();
Leon Scroggins55a5bc22009-09-04 17:00:08 -04001723 view.setEmbeddedTitleBar(mTitleBar);
Leon Scroggins58d56c62010-01-28 15:12:40 -05001724 if (t.isInVoiceSearchMode()) {
1725 showVoiceTitleBar(t.getVoiceDisplayTitle());
1726 } else {
1727 revertVoiceTitleBar();
1728 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001729 // Request focus on the top window.
1730 t.getTopWindow().requestFocus();
1731 }
1732
1733 // Attach a sub window to the main WebView of the given tab.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001734 void attachSubWindow(Tab t) {
Patrick Scottd0119532009-09-17 08:00:31 -04001735 t.attachSubWindow(mContentView);
1736 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001737 }
1738
1739 // Remove the given tab from the content view.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001740 private void removeTabFromContentView(Tab t) {
Steve Block2bc69912009-07-30 14:45:13 +01001741 // Remove the container that contains the main WebView.
Patrick Scottd0119532009-09-17 08:00:31 -04001742 t.removeTabFromContentView(mContentView);
Ben Murdochbff2d602009-07-01 20:19:05 +01001743
Grace Kloba22ac16e2009-10-07 18:00:23 -07001744 ErrorConsoleView errorConsole = t.getErrorConsole(false);
1745 if (errorConsole != null) {
1746 mErrorConsoleContainer.removeView(errorConsole);
Ben Murdochbff2d602009-07-01 20:19:05 +01001747 }
1748
Leon Scroggins39ab28e2009-09-02 21:20:30 -04001749 WebView view = t.getWebView();
Leon Scrogginsbb85b902009-09-14 19:27:20 -04001750 if (view != null) {
1751 view.setEmbeddedTitleBar(null);
1752 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001753 }
1754
1755 // Remove the sub window if it exists. Also called by TabControl when the
1756 // user clicks the 'X' to dismiss a sub window.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001757 /* package */ void dismissSubWindow(Tab t) {
Patrick Scottd0119532009-09-17 08:00:31 -04001758 t.removeSubWindow(mContentView);
Grace Kloba22ac16e2009-10-07 18:00:23 -07001759 // dismiss the subwindow. This will destroy the WebView.
1760 t.dismissSubWindow();
Patrick Scottd0119532009-09-17 08:00:31 -04001761 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001762 }
1763
Leon Scroggins1f005d32009-08-10 17:36:42 -04001764 // A wrapper function of {@link #openTabAndShow(UrlData, boolean, String)}
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07001765 // that accepts url as string.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001766 private Tab openTabAndShow(String url, boolean closeOnExit, String appId) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001767 return openTabAndShow(new UrlData(url), closeOnExit, appId);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001768 }
1769
1770 // This method does a ton of stuff. It will attempt to create a new tab
1771 // if we haven't reached MAX_TABS. Otherwise it uses the current tab. If
Leon Scroggins1f005d32009-08-10 17:36:42 -04001772 // url isn't null, it will load the given url.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001773 /* package */Tab openTabAndShow(UrlData urlData, boolean closeOnExit,
1774 String appId) {
1775 final Tab currentTab = mTabControl.getCurrentTab();
1776 if (mTabControl.canCreateNewTab()) {
1777 final Tab tab = mTabControl.createNewTab(closeOnExit, appId,
1778 urlData.mUrl);
Leon Scroggins1f005d32009-08-10 17:36:42 -04001779 WebView webview = tab.getWebView();
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001780 // If the last tab was removed from the active tabs page, currentTab
1781 // will be null.
1782 if (currentTab != null) {
1783 removeTabFromContentView(currentTab);
1784 }
Patrick Scott8bbd69f2009-08-14 13:35:53 -04001785 // We must set the new tab as the current tab to reflect the old
1786 // animation behavior.
1787 mTabControl.setCurrentTab(tab);
Grace Klobaeb6eef42009-09-15 17:56:32 -07001788 attachTabToContentView(tab);
Leon Scroggins160a7e72009-08-14 18:28:01 -04001789 if (!urlData.isEmpty()) {
Patrick Scott9d53da02010-02-19 10:19:01 -05001790 loadUrlDataIn(tab, urlData);
Leon Scroggins1f005d32009-08-10 17:36:42 -04001791 }
1792 return tab;
1793 } else {
1794 // Get rid of the subwindow if it exists
1795 dismissSubWindow(currentTab);
1796 if (!urlData.isEmpty()) {
1797 // Load the given url.
Patrick Scott9d53da02010-02-19 10:19:01 -05001798 loadUrlDataIn(currentTab, urlData);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001799 }
Leon Scroggins58d56c62010-01-28 15:12:40 -05001800 return currentTab;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001801 }
1802 }
1803
Grace Kloba22ac16e2009-10-07 18:00:23 -07001804 private Tab openTab(String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001805 if (mSettings.openInBackground()) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001806 Tab t = mTabControl.createNewTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001807 if (t != null) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001808 WebView view = t.getWebView();
Leon Scroggins92472e82010-02-17 16:32:28 -05001809 loadUrl(view, url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001810 }
Grace Klobac9181842009-04-14 08:53:22 -07001811 return t;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001812 } else {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001813 return openTabAndShow(url, false, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001814 }
1815 }
1816
1817 private class Copy implements OnMenuItemClickListener {
1818 private CharSequence mText;
1819
1820 public boolean onMenuItemClick(MenuItem item) {
1821 copy(mText);
1822 return true;
1823 }
1824
1825 public Copy(CharSequence toCopy) {
1826 mText = toCopy;
1827 }
1828 }
1829
1830 private class Download implements OnMenuItemClickListener {
1831 private String mText;
1832
1833 public boolean onMenuItemClick(MenuItem item) {
1834 onDownloadStartNoStream(mText, null, null, null, -1);
1835 return true;
1836 }
1837
1838 public Download(String toDownload) {
1839 mText = toDownload;
1840 }
1841 }
1842
Ben Murdoch4f75ba22009-10-27 11:48:28 +00001843 private class SetAsWallpaper extends Thread implements
1844 OnMenuItemClickListener, DialogInterface.OnCancelListener {
1845 private URL mUrl;
1846 private ProgressDialog mWallpaperProgress;
1847 private boolean mCanceled = false;
1848
1849 public SetAsWallpaper(String url) {
1850 try {
1851 mUrl = new URL(url);
1852 } catch (MalformedURLException e) {
1853 mUrl = null;
1854 }
1855 }
1856
1857 public void onCancel(DialogInterface dialog) {
1858 mCanceled = true;
1859 }
1860
1861 public boolean onMenuItemClick(MenuItem item) {
1862 if (mUrl != null) {
1863 // The user may have tried to set a image with a large file size as their
1864 // background so it may take a few moments to perform the operation. Display
1865 // a progress spinner while it is working.
1866 mWallpaperProgress = new ProgressDialog(BrowserActivity.this);
1867 mWallpaperProgress.setIndeterminate(true);
1868 mWallpaperProgress.setMessage(getText(R.string.progress_dialog_setting_wallpaper));
1869 mWallpaperProgress.setCancelable(true);
1870 mWallpaperProgress.setOnCancelListener(this);
1871 mWallpaperProgress.show();
1872 start();
1873 }
1874 return true;
1875 }
1876
1877 public void run() {
1878 Drawable oldWallpaper = BrowserActivity.this.getWallpaper();
1879 try {
1880 // TODO: This will cause the resource to be downloaded again, when we
1881 // should in most cases be able to grab it from the cache. To fix this
1882 // we should query WebCore to see if we can access a cached version and
1883 // instead open an input stream on that. This pattern could also be used
1884 // in the download manager where the same problem exists.
1885 InputStream inputstream = mUrl.openStream();
1886 if (inputstream != null) {
1887 setWallpaper(inputstream);
1888 }
1889 } catch (IOException e) {
1890 Log.e(LOGTAG, "Unable to set new wallpaper");
1891 // Act as though the user canceled the operation so we try to
1892 // restore the old wallpaper.
1893 mCanceled = true;
1894 }
1895
1896 if (mCanceled) {
1897 // Restore the old wallpaper if the user cancelled whilst we were setting
1898 // the new wallpaper.
1899 int width = oldWallpaper.getIntrinsicWidth();
1900 int height = oldWallpaper.getIntrinsicHeight();
1901 Bitmap bm = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
1902 Canvas canvas = new Canvas(bm);
1903 oldWallpaper.setBounds(0, 0, width, height);
1904 oldWallpaper.draw(canvas);
1905 try {
1906 setWallpaper(bm);
1907 } catch (IOException e) {
1908 Log.e(LOGTAG, "Unable to restore old wallpaper.");
1909 }
1910 mCanceled = false;
1911 }
1912
1913 if (mWallpaperProgress.isShowing()) {
1914 mWallpaperProgress.dismiss();
1915 }
1916 }
1917 }
1918
The Android Open Source Project0c908882009-03-03 19:32:16 -08001919 private void copy(CharSequence text) {
1920 try {
1921 IClipboard clip = IClipboard.Stub.asInterface(ServiceManager.getService("clipboard"));
1922 if (clip != null) {
1923 clip.setClipboardText(text);
1924 }
1925 } catch (android.os.RemoteException e) {
1926 Log.e(LOGTAG, "Copy failed", e);
1927 }
1928 }
1929
1930 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08001931 * Resets the browser title-view to whatever it must be
1932 * (for example, if we had a loading error)
1933 * When we have a new page, we call resetTitle, when we
1934 * have to reset the titlebar to whatever it used to be
1935 * (for example, if the user chose to stop loading), we
1936 * call resetTitleAndRevertLockIcon.
1937 */
1938 /* package */ void resetTitleAndRevertLockIcon() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001939 mTabControl.getCurrentTab().revertLockIcon();
1940 updateLockIconToLatest();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001941 resetTitleIconAndProgress();
1942 }
1943
1944 /**
1945 * Reset the title, favicon, and progress.
1946 */
1947 private void resetTitleIconAndProgress() {
1948 WebView current = mTabControl.getCurrentWebView();
1949 if (current == null) {
1950 return;
1951 }
1952 resetTitleAndIcon(current);
1953 int progress = current.getProgress();
Grace Kloba22ac16e2009-10-07 18:00:23 -07001954 current.getWebChromeClient().onProgressChanged(current, progress);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001955 }
1956
1957 // Reset the title and the icon based on the given item.
1958 private void resetTitleAndIcon(WebView view) {
1959 WebHistoryItem item = view.copyBackForwardList().getCurrentItem();
1960 if (item != null) {
Leon Scroggins68579392009-09-15 15:31:54 -04001961 setUrlTitle(item.getUrl(), item.getTitle());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001962 setFavicon(item.getFavicon());
1963 } else {
Leon Scroggins68579392009-09-15 15:31:54 -04001964 setUrlTitle(null, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001965 setFavicon(null);
1966 }
1967 }
1968
1969 /**
1970 * Sets a title composed of the URL and the title string.
1971 * @param url The URL of the site being loaded.
1972 * @param title The title of the site being loaded.
1973 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07001974 void setUrlTitle(String url, String title) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001975 mUrl = url;
1976 mTitle = title;
1977
Leon Scroggins58d56c62010-01-28 15:12:40 -05001978 // If we are in voice search mode, the title has already been set.
1979 if (mTabControl.getCurrentTab().isInVoiceSearchMode()) return;
1980 mTitleBar.setDisplayTitle(url);
1981 mFakeTitleBar.setDisplayTitle(url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001982 }
1983
1984 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08001985 * @param url The URL to build a title version of the URL from.
1986 * @return The title version of the URL or null if fails.
1987 * The title version of the URL can be either the URL hostname,
1988 * or the hostname with an "https://" prefix (for secure URLs),
1989 * or an empty string if, for example, the URL in question is a
1990 * file:// URL with no hostname.
1991 */
Leon Scroggins32e14a62009-06-11 10:26:34 -04001992 /* package */ static String buildTitleUrl(String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001993 String titleUrl = null;
1994
1995 if (url != null) {
1996 try {
1997 // parse the url string
1998 URL urlObj = new URL(url);
1999 if (urlObj != null) {
2000 titleUrl = "";
2001
2002 String protocol = urlObj.getProtocol();
2003 String host = urlObj.getHost();
2004
2005 if (host != null && 0 < host.length()) {
2006 titleUrl = host;
2007 if (protocol != null) {
2008 // if a secure site, add an "https://" prefix!
2009 if (protocol.equalsIgnoreCase("https")) {
2010 titleUrl = protocol + "://" + host;
2011 }
2012 }
2013 }
2014 }
2015 } catch (MalformedURLException e) {}
2016 }
2017
2018 return titleUrl;
2019 }
2020
2021 // Set the favicon in the title bar.
Grace Kloba22ac16e2009-10-07 18:00:23 -07002022 void setFavicon(Bitmap icon) {
Leon Scroggins68579392009-09-15 15:31:54 -04002023 mTitleBar.setFavicon(icon);
Leon Scrogginsfe87bd32009-10-06 10:10:00 -04002024 mFakeTitleBar.setFavicon(icon);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002025 }
2026
2027 /**
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002028 * Close the tab, remove its associated title bar, and adjust mTabControl's
2029 * current tab to a valid value.
Leon Scroggins1f005d32009-08-10 17:36:42 -04002030 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07002031 /* package */ void closeTab(Tab t) {
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002032 int currentIndex = mTabControl.getCurrentIndex();
2033 int removeIndex = mTabControl.getTabIndex(t);
Leon Scroggins1f005d32009-08-10 17:36:42 -04002034 mTabControl.removeTab(t);
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002035 if (currentIndex >= removeIndex && currentIndex != 0) {
2036 currentIndex--;
2037 }
2038 mTabControl.setCurrentTab(mTabControl.getTab(currentIndex));
Andrei Popescua5bf1de2009-09-23 16:39:23 +01002039 resetTitleIconAndProgress();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002040 }
2041
Leon Scrogginsdcc5eeb2010-02-23 17:26:37 -05002042 /* package */ void goBackOnePageOrQuit() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002043 Tab current = mTabControl.getCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002044 if (current == null) {
2045 /*
2046 * Instead of finishing the activity, simply push this to the back
2047 * of the stack and let ActivityManager to choose the foreground
2048 * activity. As BrowserActivity is singleTask, it will be always the
2049 * root of the task. So we can use either true or false for
2050 * moveTaskToBack().
2051 */
2052 moveTaskToBack(true);
Grace Kloba00d85e72009-09-23 18:50:05 -07002053 return;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002054 }
2055 WebView w = current.getWebView();
2056 if (w.canGoBack()) {
2057 w.goBack();
2058 } else {
2059 // Check to see if we are closing a window that was created by
2060 // another window. If so, we switch back to that window.
Grace Kloba22ac16e2009-10-07 18:00:23 -07002061 Tab parent = current.getParentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002062 if (parent != null) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04002063 switchToTab(mTabControl.getTabIndex(parent));
2064 // Now we close the other tab
2065 closeTab(current);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002066 } else {
2067 if (current.closeOnExit()) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002068 // force the tab's inLoad() to be false as we are going to
2069 // either finish the activity or remove the tab. This will
2070 // ensure pauseWebViewTimers() taking action.
2071 mTabControl.getCurrentTab().clearInLoad();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002072 if (mTabControl.getTabCount() == 1) {
2073 finish();
2074 return;
2075 }
Mike Reed7bfa63b2009-05-28 11:08:32 -04002076 // call pauseWebViewTimers() now, we won't be able to call
2077 // it in onPause() as the WebView won't be valid.
Grace Klobaec1b5ad2009-08-18 08:42:32 -07002078 // Temporarily change mActivityInPause to be true as
2079 // pauseWebViewTimers() will do nothing if mActivityInPause
2080 // is false.
Grace Kloba918e1d72009-08-13 14:55:06 -07002081 boolean savedState = mActivityInPause;
2082 if (savedState) {
Grace Klobaec1b5ad2009-08-18 08:42:32 -07002083 Log.e(LOGTAG, "BrowserActivity is already paused "
2084 + "while handing goBackOnePageOrQuit.");
Grace Kloba918e1d72009-08-13 14:55:06 -07002085 }
2086 mActivityInPause = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -04002087 pauseWebViewTimers();
Grace Kloba918e1d72009-08-13 14:55:06 -07002088 mActivityInPause = savedState;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002089 removeTabFromContentView(current);
2090 mTabControl.removeTab(current);
2091 }
2092 /*
2093 * Instead of finishing the activity, simply push this to the back
2094 * of the stack and let ActivityManager to choose the foreground
2095 * activity. As BrowserActivity is singleTask, it will be always the
2096 * root of the task. So we can use either true or false for
2097 * moveTaskToBack().
2098 */
2099 moveTaskToBack(true);
2100 }
2101 }
2102 }
2103
Grace Kloba22ac16e2009-10-07 18:00:23 -07002104 boolean isMenuDown() {
2105 return mMenuIsDown;
2106 }
2107
Grace Kloba5942df02009-09-18 11:48:29 -07002108 @Override
2109 public boolean onKeyDown(int keyCode, KeyEvent event) {
Leon Scrogginsf65b50d2009-12-08 10:44:28 -05002110 // Even if MENU is already held down, we need to call to super to open
2111 // the IME on long press.
2112 if (KeyEvent.KEYCODE_MENU == keyCode) {
2113 mMenuIsDown = true;
2114 return super.onKeyDown(keyCode, event);
2115 }
Grace Kloba5942df02009-09-18 11:48:29 -07002116 // The default key mode is DEFAULT_KEYS_SEARCH_LOCAL. As the MENU is
2117 // still down, we don't want to trigger the search. Pretend to consume
2118 // the key and do nothing.
2119 if (mMenuIsDown) return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002120
Grace Kloba5942df02009-09-18 11:48:29 -07002121 switch(keyCode) {
Grace Kloba5942df02009-09-18 11:48:29 -07002122 case KeyEvent.KEYCODE_SPACE:
Grace Klobada0fe552009-09-22 18:17:24 -07002123 // WebView/WebTextView handle the keys in the KeyDown. As
2124 // the Activity's shortcut keys are only handled when WebView
2125 // doesn't, have to do it in onKeyDown instead of onKeyUp.
2126 if (event.isShiftPressed()) {
2127 getTopWindow().pageUp(false);
2128 } else {
2129 getTopWindow().pageDown(false);
2130 }
Grace Kloba5942df02009-09-18 11:48:29 -07002131 return true;
2132 case KeyEvent.KEYCODE_BACK:
2133 if (event.getRepeatCount() == 0) {
2134 event.startTracking();
2135 return true;
2136 } else if (mCustomView == null && mActiveTabsPage == null
2137 && event.isLongPress()) {
2138 bookmarksOrHistoryPicker(true);
2139 return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002140 }
Grace Kloba5942df02009-09-18 11:48:29 -07002141 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002142 }
Grace Kloba5942df02009-09-18 11:48:29 -07002143 return super.onKeyDown(keyCode, event);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002144 }
2145
Grace Kloba5942df02009-09-18 11:48:29 -07002146 @Override
2147 public boolean onKeyUp(int keyCode, KeyEvent event) {
2148 switch(keyCode) {
2149 case KeyEvent.KEYCODE_MENU:
2150 mMenuIsDown = false;
2151 break;
Grace Kloba5942df02009-09-18 11:48:29 -07002152 case KeyEvent.KEYCODE_BACK:
2153 if (event.isTracking() && !event.isCanceled()) {
2154 if (mCustomView != null) {
2155 // if a custom view is showing, hide it
Grace Kloba22ac16e2009-10-07 18:00:23 -07002156 mTabControl.getCurrentWebView().getWebChromeClient()
2157 .onHideCustomView();
Grace Kloba5942df02009-09-18 11:48:29 -07002158 } else if (mActiveTabsPage != null) {
2159 // if tab page is showing, hide it
2160 removeActiveTabPage(true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002161 } else {
Grace Kloba5942df02009-09-18 11:48:29 -07002162 WebView subwindow = mTabControl.getCurrentSubWindow();
2163 if (subwindow != null) {
2164 if (subwindow.canGoBack()) {
2165 subwindow.goBack();
2166 } else {
2167 dismissSubWindow(mTabControl.getCurrentTab());
2168 }
2169 } else {
2170 goBackOnePageOrQuit();
2171 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002172 }
Grace Kloba5942df02009-09-18 11:48:29 -07002173 return true;
2174 }
2175 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002176 }
Grace Kloba5942df02009-09-18 11:48:29 -07002177 return super.onKeyUp(keyCode, event);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002178 }
2179
Leon Scroggins68579392009-09-15 15:31:54 -04002180 /* package */ void stopLoading() {
Ben Murdochb7cc8b42009-09-28 10:59:09 +01002181 mDidStopLoad = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002182 resetTitleAndRevertLockIcon();
2183 WebView w = getTopWindow();
2184 w.stopLoading();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002185 // FIXME: before refactor, it is using mWebViewClient. So I keep the
2186 // same logic here. But for subwindow case, should we call into the main
2187 // WebView's onPageFinished as we never call its onPageStarted and if
2188 // the page finishes itself, we don't call onPageFinished.
2189 mTabControl.getCurrentWebView().getWebViewClient().onPageFinished(w,
2190 w.getUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08002191
2192 cancelStopToast();
2193 mStopToast = Toast
2194 .makeText(this, R.string.stopping, Toast.LENGTH_SHORT);
2195 mStopToast.show();
2196 }
2197
Grace Kloba22ac16e2009-10-07 18:00:23 -07002198 boolean didUserStopLoading() {
2199 return mDidStopLoad;
2200 }
2201
The Android Open Source Project0c908882009-03-03 19:32:16 -08002202 private void cancelStopToast() {
2203 if (mStopToast != null) {
2204 mStopToast.cancel();
2205 mStopToast = null;
2206 }
2207 }
2208
Grace Kloba22ac16e2009-10-07 18:00:23 -07002209 // called by a UI or non-UI thread to post the message
2210 public void postMessage(int what, int arg1, int arg2, Object obj,
2211 long delayMillis) {
2212 mHandler.sendMessageDelayed(mHandler.obtainMessage(what, arg1, arg2,
2213 obj), delayMillis);
2214 }
2215
2216 // called by a UI or non-UI thread to remove the message
2217 void removeMessages(int what, Object object) {
2218 mHandler.removeMessages(what, object);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002219 }
2220
2221 // public message ids
2222 public final static int LOAD_URL = 1001;
2223 public final static int STOP_LOAD = 1002;
2224
2225 // Message Ids
2226 private static final int FOCUS_NODE_HREF = 102;
Grace Kloba92c18a52009-07-31 23:48:32 -07002227 private static final int RELEASE_WAKELOCK = 107;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002228
Grace Kloba22ac16e2009-10-07 18:00:23 -07002229 static final int UPDATE_BOOKMARK_THUMBNAIL = 108;
Ben Murdoch2694e232009-09-29 09:41:11 +01002230
The Android Open Source Project0c908882009-03-03 19:32:16 -08002231 // Private handler for handling javascript and saving passwords
2232 private Handler mHandler = new Handler() {
2233
2234 public void handleMessage(Message msg) {
2235 switch (msg.what) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002236 case FOCUS_NODE_HREF:
Ben Murdoch2694e232009-09-29 09:41:11 +01002237 {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002238 String url = (String) msg.getData().get("url");
Ben Murdoch90d088c2009-11-17 18:14:04 +00002239 String title = (String) msg.getData().get("title");
The Android Open Source Project0c908882009-03-03 19:32:16 -08002240 if (url == null || url.length() == 0) {
2241 break;
2242 }
2243 HashMap focusNodeMap = (HashMap) msg.obj;
2244 WebView view = (WebView) focusNodeMap.get("webview");
2245 // Only apply the action if the top window did not change.
2246 if (getTopWindow() != view) {
2247 break;
2248 }
2249 switch (msg.arg1) {
2250 case R.id.open_context_menu_id:
2251 case R.id.view_image_context_menu_id:
Leon Scroggins92472e82010-02-17 16:32:28 -05002252 loadUrlFromContext(getTopWindow(), url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002253 break;
2254 case R.id.open_newtab_context_menu_id:
Grace Kloba22ac16e2009-10-07 18:00:23 -07002255 final Tab parent = mTabControl.getCurrentTab();
2256 final Tab newTab = openTab(url);
Grace Klobac9181842009-04-14 08:53:22 -07002257 if (newTab != parent) {
2258 parent.addChildTab(newTab);
2259 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002260 break;
2261 case R.id.bookmark_context_menu_id:
2262 Intent intent = new Intent(BrowserActivity.this,
2263 AddBookmarkPage.class);
2264 intent.putExtra("url", url);
Ben Murdoch90d088c2009-11-17 18:14:04 +00002265 intent.putExtra("title", title);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002266 startActivity(intent);
2267 break;
2268 case R.id.share_link_context_menu_id:
Leon Scroggins96afcb12009-12-10 12:35:56 -05002269 // See if this site has been visited before
2270 StringBuilder sb = new StringBuilder(
2271 Browser.BookmarkColumns.URL + " = ");
2272 DatabaseUtils.appendEscapedSQLString(sb, url);
2273 Cursor c = mResolver.query(Browser.BOOKMARKS_URI,
2274 Browser.HISTORY_PROJECTION,
2275 sb.toString(),
2276 null,
2277 null);
2278 if (c.moveToFirst()) {
2279 // The site has been visited before, so grab the
2280 // info from the database.
2281 Bitmap favicon = null;
2282 Bitmap thumbnail = null;
2283 String linkTitle = c.getString(Browser.
2284 HISTORY_PROJECTION_TITLE_INDEX);
2285 byte[] data = c.getBlob(Browser.
2286 HISTORY_PROJECTION_FAVICON_INDEX);
2287 if (data != null) {
2288 favicon = BitmapFactory.decodeByteArray(
2289 data, 0, data.length);
2290 }
2291 data = c.getBlob(Browser.
2292 HISTORY_PROJECTION_THUMBNAIL_INDEX);
2293 if (data != null) {
2294 thumbnail = BitmapFactory.decodeByteArray(
2295 data, 0, data.length);
2296 }
2297 sharePage(BrowserActivity.this,
2298 linkTitle, url, favicon, thumbnail);
2299 } else {
2300 Browser.sendString(BrowserActivity.this, url,
2301 getString(
2302 R.string.choosertitle_sharevia));
2303 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002304 break;
2305 case R.id.copy_link_context_menu_id:
2306 copy(url);
2307 break;
2308 case R.id.save_link_context_menu_id:
2309 case R.id.download_context_menu_id:
2310 onDownloadStartNoStream(url, null, null, null, -1);
2311 break;
2312 }
2313 break;
Ben Murdoch2694e232009-09-29 09:41:11 +01002314 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002315
2316 case LOAD_URL:
Leon Scroggins92472e82010-02-17 16:32:28 -05002317 loadUrlFromContext(getTopWindow(), (String) msg.obj);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002318 break;
2319
2320 case STOP_LOAD:
2321 stopLoading();
2322 break;
2323
The Android Open Source Project0c908882009-03-03 19:32:16 -08002324 case RELEASE_WAKELOCK:
2325 if (mWakeLock.isHeld()) {
2326 mWakeLock.release();
Grace Kloba5d0e02e2009-10-05 15:15:36 -07002327 // if we reach here, Browser should be still in the
2328 // background loading after WAKELOCK_TIMEOUT (5-min).
2329 // To avoid burning the battery, stop loading.
2330 mTabControl.stopAllLoading();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002331 }
2332 break;
Ben Murdoch2694e232009-09-29 09:41:11 +01002333
2334 case UPDATE_BOOKMARK_THUMBNAIL:
2335 WebView view = (WebView) msg.obj;
2336 if (view != null) {
2337 updateScreenshot(view);
2338 }
2339 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002340 }
2341 }
2342 };
2343
Leon Scroggins96afcb12009-12-10 12:35:56 -05002344 /**
2345 * Share a page, providing the title, url, favicon, and a screenshot. Uses
2346 * an {@link Intent} to launch the Activity chooser.
2347 * @param c Context used to launch a new Activity.
2348 * @param title Title of the page. Stored in the Intent with
Paul Westbrook03e6d392010-02-12 10:33:29 -08002349 * {@link Intent#EXTRA_SUBJECT}
Leon Scroggins96afcb12009-12-10 12:35:56 -05002350 * @param url URL of the page. Stored in the Intent with
2351 * {@link Intent#EXTRA_TEXT}
2352 * @param favicon Bitmap of the favicon for the page. Stored in the Intent
2353 * with {@link Browser#EXTRA_SHARE_FAVICON}
2354 * @param screenshot Bitmap of a screenshot of the page. Stored in the
2355 * Intent with {@link Browser#EXTRA_SHARE_SCREENSHOT}
2356 */
2357 public static final void sharePage(Context c, String title, String url,
2358 Bitmap favicon, Bitmap screenshot) {
2359 Intent send = new Intent(Intent.ACTION_SEND);
2360 send.setType("text/plain");
2361 send.putExtra(Intent.EXTRA_TEXT, url);
Paul Westbrook03e6d392010-02-12 10:33:29 -08002362 send.putExtra(Intent.EXTRA_SUBJECT, title);
Leon Scroggins96afcb12009-12-10 12:35:56 -05002363 send.putExtra(Browser.EXTRA_SHARE_FAVICON, favicon);
2364 send.putExtra(Browser.EXTRA_SHARE_SCREENSHOT, screenshot);
2365 try {
2366 c.startActivity(Intent.createChooser(send, c.getString(
2367 R.string.choosertitle_sharevia)));
2368 } catch(android.content.ActivityNotFoundException ex) {
2369 // if no app handles it, do nothing
2370 }
2371 }
2372
Leon Scroggins89c6d362009-07-15 16:54:37 -04002373 private void updateScreenshot(WebView view) {
2374 // If this is a bookmarked site, add a screenshot to the database.
2375 // FIXME: When should we update? Every time?
2376 // FIXME: Would like to make sure there is actually something to
2377 // draw, but the API for that (WebViewCore.pictureReady()) is not
2378 // currently accessible here.
Ben Murdochaac7aa62009-09-17 16:57:40 +01002379
Patrick Scottcb192b52010-04-14 14:38:55 -04002380 final Bitmap bm = createScreenshot(view);
2381 if (bm == null) {
2382 return;
Leon Scroggins89c6d362009-07-15 16:54:37 -04002383 }
Patrick Scottcb192b52010-04-14 14:38:55 -04002384
2385 final ContentResolver cr = getContentResolver();
2386 final String url = view.getUrl();
2387 final String originalUrl = view.getOriginalUrl();
2388
2389 new AsyncTask<Void, Void, Void>() {
2390 @Override
2391 protected Void doInBackground(Void... unused) {
2392 Cursor c = null;
2393 try {
2394 c = BrowserBookmarksAdapter.queryBookmarksForUrl(
2395 cr, originalUrl, url, true);
2396 if (c != null) {
2397 if (c.moveToFirst()) {
2398 ContentValues values = new ContentValues();
2399 final ByteArrayOutputStream os
2400 = new ByteArrayOutputStream();
2401 bm.compress(Bitmap.CompressFormat.PNG, 100, os);
2402 values.put(Browser.BookmarkColumns.THUMBNAIL,
2403 os.toByteArray());
2404 do {
2405 cr.update(ContentUris.withAppendedId(
2406 Browser.BOOKMARKS_URI, c.getInt(0)),
2407 values, null, null);
2408 } while (c.moveToNext());
2409 }
2410 }
2411 } catch (IllegalStateException e) {
2412 // Ignore
2413 } finally {
2414 if (c != null) c.close();
2415 }
2416 return null;
2417 }
2418 }.execute();
Leon Scroggins89c6d362009-07-15 16:54:37 -04002419 }
2420
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002421 /**
Leon Scrogginsf8551612009-09-24 16:06:02 -04002422 * Values for the size of the thumbnail created when taking a screenshot.
2423 * Lazily initialized. Instead of using these directly, use
2424 * getDesiredThumbnailWidth() or getDesiredThumbnailHeight().
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002425 */
Leon Scrogginsf8551612009-09-24 16:06:02 -04002426 private static int THUMBNAIL_WIDTH = 0;
2427 private static int THUMBNAIL_HEIGHT = 0;
2428
2429 /**
2430 * Return the desired width for thumbnail screenshots, which are stored in
2431 * the database, and used on the bookmarks screen.
2432 * @param context Context for finding out the density of the screen.
2433 * @return int desired width for thumbnail screenshot.
2434 */
2435 /* package */ static int getDesiredThumbnailWidth(Context context) {
2436 if (THUMBNAIL_WIDTH == 0) {
2437 float density = context.getResources().getDisplayMetrics().density;
2438 THUMBNAIL_WIDTH = (int) (90 * density);
2439 THUMBNAIL_HEIGHT = (int) (80 * density);
2440 }
2441 return THUMBNAIL_WIDTH;
2442 }
2443
2444 /**
2445 * Return the desired height for thumbnail screenshots, which are stored in
2446 * the database, and used on the bookmarks screen.
2447 * @param context Context for finding out the density of the screen.
2448 * @return int desired height for thumbnail screenshot.
2449 */
2450 /* package */ static int getDesiredThumbnailHeight(Context context) {
2451 // To ensure that they are both initialized.
2452 getDesiredThumbnailWidth(context);
2453 return THUMBNAIL_HEIGHT;
2454 }
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002455
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002456 private Bitmap createScreenshot(WebView view) {
2457 Picture thumbnail = view.capturePicture();
Leon Scroggins45800572009-09-29 16:38:47 -04002458 if (thumbnail == null) {
2459 return null;
2460 }
Leon Scrogginsf8551612009-09-24 16:06:02 -04002461 Bitmap bm = Bitmap.createBitmap(getDesiredThumbnailWidth(this),
Cary Clarkab168ba2010-04-08 09:11:28 -04002462 getDesiredThumbnailHeight(this), Bitmap.Config.RGB_565);
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002463 Canvas canvas = new Canvas(bm);
2464 // May need to tweak these values to determine what is the
2465 // best scale factor
Ben Murdoch2694e232009-09-29 09:41:11 +01002466 int thumbnailWidth = thumbnail.getWidth();
Ben Murdochae59c3f2009-10-20 18:30:28 +01002467 int thumbnailHeight = thumbnail.getHeight();
2468 float scaleFactorX = 1.0f;
2469 float scaleFactorY = 1.0f;
Ben Murdoch2694e232009-09-29 09:41:11 +01002470 if (thumbnailWidth > 0) {
Ben Murdochae59c3f2009-10-20 18:30:28 +01002471 scaleFactorX = (float) getDesiredThumbnailWidth(this) /
Ben Murdoch2694e232009-09-29 09:41:11 +01002472 (float)thumbnailWidth;
Ben Murdochae59c3f2009-10-20 18:30:28 +01002473 } else {
2474 return null;
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002475 }
Ben Murdochae59c3f2009-10-20 18:30:28 +01002476
2477 if (view.getWidth() > view.getHeight() &&
2478 thumbnailHeight < view.getHeight() && thumbnailHeight > 0) {
2479 // If the device is in landscape and the page is shorter
2480 // than the height of the view, stretch the thumbnail to fill the
2481 // space.
2482 scaleFactorY = (float) getDesiredThumbnailHeight(this) /
2483 (float)thumbnailHeight;
2484 } else {
2485 // In the portrait case, this looks nice.
2486 scaleFactorY = scaleFactorX;
2487 }
2488
2489 canvas.scale(scaleFactorX, scaleFactorY);
2490
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002491 thumbnail.draw(canvas);
2492 return bm;
2493 }
2494
The Android Open Source Project0c908882009-03-03 19:32:16 -08002495 // -------------------------------------------------------------------------
Grace Kloba22ac16e2009-10-07 18:00:23 -07002496 // Helper function for WebViewClient.
The Android Open Source Project0c908882009-03-03 19:32:16 -08002497 //-------------------------------------------------------------------------
2498
2499 // Use in overrideUrlLoading
2500 /* package */ final static String SCHEME_WTAI = "wtai://wp/";
2501 /* package */ final static String SCHEME_WTAI_MC = "wtai://wp/mc;";
2502 /* package */ final static String SCHEME_WTAI_SD = "wtai://wp/sd;";
2503 /* package */ final static String SCHEME_WTAI_AP = "wtai://wp/ap;";
2504
Leon Scroggins92472e82010-02-17 16:32:28 -05002505 // Keep this initial progress in sync with initialProgressValue (* 100)
2506 // in ProgressTracker.cpp
2507 private final static int INITIAL_PROGRESS = 10;
2508
Grace Kloba22ac16e2009-10-07 18:00:23 -07002509 void onPageStarted(WebView view, String url, Bitmap favicon) {
2510 // when BrowserActivity just starts, onPageStarted may be called before
2511 // onResume as it is triggered from onCreate. Call resumeWebViewTimers
2512 // to start the timer. As we won't switch tabs while an activity is in
2513 // pause state, we can ensure calling resume and pause in pair.
2514 if (mActivityInPause) resumeWebViewTimers();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002515
Grace Kloba22ac16e2009-10-07 18:00:23 -07002516 resetLockIcon(url);
2517 setUrlTitle(url, null);
2518 setFavicon(favicon);
Leon Scroggins8cf8f682009-11-04 11:13:50 -08002519 // Show some progress so that the user knows the page is beginning to
2520 // load
Leon Scroggins92472e82010-02-17 16:32:28 -05002521 onProgressChanged(view, INITIAL_PROGRESS);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002522 mDidStopLoad = false;
Grace Kloba22ac16e2009-10-07 18:00:23 -07002523 if (!mIsNetworkUp) createAndShowNetworkDialog();
Cary Clark2c326e62010-08-19 18:40:57 -04002524 closeDialogs();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002525 if (mSettings.isTracing()) {
2526 String host;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002527 try {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002528 WebAddress uri = new WebAddress(url);
2529 host = uri.mHost;
2530 } catch (android.net.ParseException ex) {
2531 host = "browser";
The Android Open Source Project0c908882009-03-03 19:32:16 -08002532 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002533 host = host.replace('.', '_');
2534 host += ".trace";
2535 mInTrace = true;
2536 Debug.startMethodTracing(host, 20 * 1024 * 1024);
2537 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002538
Grace Kloba22ac16e2009-10-07 18:00:23 -07002539 // Performance probe
2540 if (false) {
2541 mStart = SystemClock.uptimeMillis();
2542 mProcessStart = Process.getElapsedCpuTime();
2543 long[] sysCpu = new long[7];
2544 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2545 sysCpu, null)) {
2546 mUserStart = sysCpu[0] + sysCpu[1];
2547 mSystemStart = sysCpu[2];
2548 mIdleStart = sysCpu[3];
2549 mIrqStart = sysCpu[4] + sysCpu[5] + sysCpu[6];
2550 }
2551 mUiStart = SystemClock.currentThreadTimeMillis();
2552 }
2553 }
2554
2555 void onPageFinished(WebView view, String url) {
2556 // Reset the title and icon in case we stopped a provisional load.
2557 resetTitleAndIcon(view);
2558 // Update the lock icon image only once we are done loading
2559 updateLockIconToLatest();
2560 // pause the WebView timer and release the wake lock if it is finished
2561 // while BrowserActivity is in pause state.
2562 if (mActivityInPause && pauseWebViewTimers()) {
2563 if (mWakeLock.isHeld()) {
2564 mHandler.removeMessages(RELEASE_WAKELOCK);
2565 mWakeLock.release();
2566 }
2567 }
2568
2569 // Performance probe
2570 if (false) {
2571 long[] sysCpu = new long[7];
2572 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2573 sysCpu, null)) {
2574 String uiInfo = "UI thread used "
2575 + (SystemClock.currentThreadTimeMillis() - mUiStart)
2576 + " ms";
2577 if (LOGD_ENABLED) {
2578 Log.d(LOGTAG, uiInfo);
2579 }
2580 //The string that gets written to the log
2581 String performanceString = "It took total "
2582 + (SystemClock.uptimeMillis() - mStart)
2583 + " ms clock time to load the page."
2584 + "\nbrowser process used "
2585 + (Process.getElapsedCpuTime() - mProcessStart)
2586 + " ms, user processes used "
2587 + (sysCpu[0] + sysCpu[1] - mUserStart) * 10
2588 + " ms, kernel used "
2589 + (sysCpu[2] - mSystemStart) * 10
2590 + " ms, idle took " + (sysCpu[3] - mIdleStart) * 10
2591 + " ms and irq took "
2592 + (sysCpu[4] + sysCpu[5] + sysCpu[6] - mIrqStart)
2593 * 10 + " ms, " + uiInfo;
2594 if (LOGD_ENABLED) {
2595 Log.d(LOGTAG, performanceString + "\nWebpage: " + url);
2596 }
2597 if (url != null) {
2598 // strip the url to maintain consistency
2599 String newUrl = new String(url);
2600 if (newUrl.startsWith("http://www.")) {
2601 newUrl = newUrl.substring(11);
2602 } else if (newUrl.startsWith("http://")) {
2603 newUrl = newUrl.substring(7);
2604 } else if (newUrl.startsWith("https://www.")) {
2605 newUrl = newUrl.substring(12);
2606 } else if (newUrl.startsWith("https://")) {
2607 newUrl = newUrl.substring(8);
2608 }
2609 if (LOGD_ENABLED) {
2610 Log.d(LOGTAG, newUrl + " loaded");
2611 }
Grace Kloba5b078b52009-06-24 20:23:41 -07002612 }
2613 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002614 }
Grace Kloba5b078b52009-06-24 20:23:41 -07002615
Grace Kloba22ac16e2009-10-07 18:00:23 -07002616 if (mInTrace) {
2617 mInTrace = false;
2618 Debug.stopMethodTracing();
2619 }
2620 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002621
Grace Kloba22ac16e2009-10-07 18:00:23 -07002622 boolean shouldOverrideUrlLoading(WebView view, String url) {
2623 if (url.startsWith(SCHEME_WTAI)) {
2624 // wtai://wp/mc;number
2625 // number=string(phone-number)
2626 if (url.startsWith(SCHEME_WTAI_MC)) {
2627 Intent intent = new Intent(Intent.ACTION_VIEW,
2628 Uri.parse(WebView.SCHEME_TEL +
2629 url.substring(SCHEME_WTAI_MC.length())));
2630 startActivity(intent);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002631 return true;
2632 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002633 // wtai://wp/sd;dtmf
2634 // dtmf=string(dialstring)
2635 if (url.startsWith(SCHEME_WTAI_SD)) {
2636 // TODO: only send when there is active voice connection
2637 return false;
2638 }
2639 // wtai://wp/ap;number;name
2640 // number=string(phone-number)
2641 // name=string
2642 if (url.startsWith(SCHEME_WTAI_AP)) {
2643 // TODO
2644 return false;
2645 }
2646 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002647
Grace Kloba22ac16e2009-10-07 18:00:23 -07002648 // The "about:" schemes are internal to the browser; don't want these to
2649 // be dispatched to other apps.
2650 if (url.startsWith("about:")) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002651 return false;
2652 }
2653
Grace Kloba22ac16e2009-10-07 18:00:23 -07002654 Intent intent;
2655 // perform generic parsing of the URI to turn it into an Intent.
2656 try {
2657 intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME);
2658 } catch (URISyntaxException ex) {
2659 Log.w("Browser", "Bad URI " + url + ": " + ex.getMessage());
2660 return false;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002661 }
2662
Grace Kloba22ac16e2009-10-07 18:00:23 -07002663 // check whether the intent can be resolved. If not, we will see
2664 // whether we can download it from the Market.
2665 if (getPackageManager().resolveActivity(intent, 0) == null) {
2666 String packagename = intent.getPackage();
2667 if (packagename != null) {
2668 intent = new Intent(Intent.ACTION_VIEW, Uri
2669 .parse("market://search?q=pname:" + packagename));
2670 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2671 startActivity(intent);
2672 return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002673 } else {
2674 return false;
2675 }
2676 }
2677
Grace Kloba22ac16e2009-10-07 18:00:23 -07002678 // sanitize the Intent, ensuring web pages can not bypass browser
2679 // security (only access to BROWSABLE activities).
2680 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2681 intent.setComponent(null);
2682 try {
2683 if (startActivityIfNeeded(intent, -1)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002684 return true;
2685 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002686 } catch (ActivityNotFoundException ex) {
2687 // ignore the error. If no application can handle the URL,
2688 // eg about:blank, assume the browser can handle it.
2689 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002690
Grace Kloba22ac16e2009-10-07 18:00:23 -07002691 if (mMenuIsDown) {
2692 openTab(url);
2693 closeOptionsMenu();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002694 return true;
2695 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002696 return false;
2697 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002698
Grace Kloba22ac16e2009-10-07 18:00:23 -07002699 // -------------------------------------------------------------------------
2700 // Helper function for WebChromeClient
2701 // -------------------------------------------------------------------------
The Android Open Source Project0c908882009-03-03 19:32:16 -08002702
Grace Kloba22ac16e2009-10-07 18:00:23 -07002703 void onProgressChanged(WebView view, int newProgress) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002704 mFakeTitleBar.setProgress(newProgress);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002705
Grace Kloba22ac16e2009-10-07 18:00:23 -07002706 if (newProgress == 100) {
2707 // onProgressChanged() may continue to be called after the main
2708 // frame has finished loading, as any remaining sub frames continue
2709 // to load. We'll only get called once though with newProgress as
2710 // 100 when everything is loaded. (onPageFinished is called once
2711 // when the main frame completes loading regardless of the state of
2712 // any sub frames so calls to onProgressChanges may continue after
2713 // onPageFinished has executed)
2714 if (mInLoad) {
2715 mInLoad = false;
Leon Scrogginsa27ff192009-09-14 12:58:04 -04002716 updateInLoadMenuItems();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002717 // If the options menu is open, leave the title bar
2718 if (!mOptionsMenuOpen || !mIconView) {
2719 hideFakeTitleBar();
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07002720 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002721 }
Leon Scrogginsaa37e7f2010-03-05 11:51:20 -05002722 } else {
2723 if (!mInLoad) {
2724 // onPageFinished may have already been called but a subframe is
2725 // still loading and updating the progress. Reset mInLoad and
2726 // update the menu items.
2727 mInLoad = true;
2728 updateInLoadMenuItems();
2729 }
2730 // When the page first begins to load, the Activity may still be
2731 // paused, in which case showFakeTitleBar will do nothing. Call
2732 // again as the page continues to load so that it will be shown.
2733 // (Calling it will the fake title bar is already showing will also
2734 // do nothing.
Grace Kloba22ac16e2009-10-07 18:00:23 -07002735 if (!mOptionsMenuOpen || mIconView) {
2736 // This page has begun to load, so show the title bar
2737 showFakeTitleBar();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002738 }
2739 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002740 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002741
Grace Kloba22ac16e2009-10-07 18:00:23 -07002742 void onShowCustomView(View view, WebChromeClient.CustomViewCallback callback) {
Derek Sollenberger8ff57db2009-12-08 15:39:55 -05002743 // if a view already exists then immediately terminate the new one
2744 if (mCustomView != null) {
2745 callback.onCustomViewHidden();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002746 return;
Derek Sollenberger8ff57db2009-12-08 15:39:55 -05002747 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002748
2749 // Add the custom view to its container.
2750 mCustomViewContainer.addView(view, COVER_SCREEN_GRAVITY_CENTER);
2751 mCustomView = view;
2752 mCustomViewCallback = callback;
2753 // Save the menu state and set it to empty while the custom
2754 // view is showing.
2755 mOldMenuState = mMenuState;
2756 mMenuState = EMPTY_MENU;
2757 // Hide the content view.
2758 mContentView.setVisibility(View.GONE);
2759 // Finally show the custom view container.
Andrei Popescu163ab742009-10-20 17:58:23 +01002760 setStatusBarVisibility(false);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002761 mCustomViewContainer.setVisibility(View.VISIBLE);
2762 mCustomViewContainer.bringToFront();
2763 }
2764
2765 void onHideCustomView() {
2766 if (mCustomView == null)
2767 return;
Grace Kloba22ac16e2009-10-07 18:00:23 -07002768 // Hide the custom view.
2769 mCustomView.setVisibility(View.GONE);
2770 // Remove the custom view from its container.
2771 mCustomViewContainer.removeView(mCustomView);
2772 mCustomView = null;
2773 // Reset the old menu state.
2774 mMenuState = mOldMenuState;
2775 mOldMenuState = EMPTY_MENU;
2776 mCustomViewContainer.setVisibility(View.GONE);
2777 mCustomViewCallback.onCustomViewHidden();
2778 // Show the content view.
Andrei Popescu163ab742009-10-20 17:58:23 +01002779 setStatusBarVisibility(true);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002780 mContentView.setVisibility(View.VISIBLE);
2781 }
2782
2783 Bitmap getDefaultVideoPoster() {
2784 if (mDefaultVideoPoster == null) {
2785 mDefaultVideoPoster = BitmapFactory.decodeResource(
2786 getResources(), R.drawable.default_video_poster);
Patrick Scott3918d442009-08-04 13:22:29 -04002787 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002788 return mDefaultVideoPoster;
2789 }
Patrick Scott3918d442009-08-04 13:22:29 -04002790
Grace Kloba22ac16e2009-10-07 18:00:23 -07002791 View getVideoLoadingProgressView() {
2792 if (mVideoProgressView == null) {
2793 LayoutInflater inflater = LayoutInflater.from(BrowserActivity.this);
2794 mVideoProgressView = inflater.inflate(
2795 R.layout.video_loading_progress, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002796 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002797 return mVideoProgressView;
2798 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002799
Leon Scroggins8d5fa432009-10-02 15:55:59 -04002800 /*
2801 * The Object used to inform the WebView of the file to upload.
2802 */
2803 private ValueCallback<Uri> mUploadMessage;
2804
Grace Kloba22ac16e2009-10-07 18:00:23 -07002805 void openFileChooser(ValueCallback<Uri> uploadMsg) {
2806 if (mUploadMessage != null) return;
2807 mUploadMessage = uploadMsg;
2808 Intent i = new Intent(Intent.ACTION_GET_CONTENT);
2809 i.addCategory(Intent.CATEGORY_OPENABLE);
2810 i.setType("*/*");
2811 BrowserActivity.this.startActivityForResult(Intent.createChooser(i,
2812 getString(R.string.choose_upload)), FILE_SELECTED);
2813 }
2814
2815 // -------------------------------------------------------------------------
2816 // Implement functions for DownloadListener
2817 // -------------------------------------------------------------------------
2818
The Android Open Source Project0c908882009-03-03 19:32:16 -08002819 /**
2820 * Notify the host application a download should be done, or that
2821 * the data should be streamed if a streaming viewer is available.
2822 * @param url The full url to the content that should be downloaded
2823 * @param contentDisposition Content-disposition http header, if
2824 * present.
2825 * @param mimetype The mimetype of the content reported by the server
2826 * @param contentLength The file size reported by the server
2827 */
2828 public void onDownloadStart(String url, String userAgent,
2829 String contentDisposition, String mimetype, long contentLength) {
2830 // if we're dealing wih A/V content that's not explicitly marked
2831 // for download, check if it's streamable.
2832 if (contentDisposition == null
Patrick Scotte1fb9662009-08-31 14:31:52 -04002833 || !contentDisposition.regionMatches(
2834 true, 0, "attachment", 0, 10)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002835 // query the package manager to see if there's a registered handler
2836 // that matches.
2837 Intent intent = new Intent(Intent.ACTION_VIEW);
2838 intent.setDataAndType(Uri.parse(url), mimetype);
Patrick Scotte1fb9662009-08-31 14:31:52 -04002839 ResolveInfo info = getPackageManager().resolveActivity(intent,
2840 PackageManager.MATCH_DEFAULT_ONLY);
2841 if (info != null) {
2842 ComponentName myName = getComponentName();
2843 // If we resolved to ourselves, we don't want to attempt to
2844 // load the url only to try and download it again.
2845 if (!myName.getPackageName().equals(
2846 info.activityInfo.packageName)
2847 || !myName.getClassName().equals(
2848 info.activityInfo.name)) {
2849 // someone (other than us) knows how to handle this mime
2850 // type with this scheme, don't download.
2851 try {
2852 startActivity(intent);
2853 return;
2854 } catch (ActivityNotFoundException ex) {
2855 if (LOGD_ENABLED) {
2856 Log.d(LOGTAG, "activity not found for " + mimetype
2857 + " over " + Uri.parse(url).getScheme(),
2858 ex);
2859 }
2860 // Best behavior is to fall back to a download in this
2861 // case
The Android Open Source Project0c908882009-03-03 19:32:16 -08002862 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002863 }
2864 }
2865 }
2866 onDownloadStartNoStream(url, userAgent, contentDisposition, mimetype, contentLength);
2867 }
2868
Kristian Monsenfa52d172010-03-25 18:29:21 +00002869 // This is to work around the fact that java.net.URI throws Exceptions
2870 // instead of just encoding URL's properly
2871 // Helper method for onDownloadStartNoStream
2872 private static String encodePath(String path) {
2873 char[] chars = path.toCharArray();
2874
2875 boolean needed = false;
2876 for (char c : chars) {
2877 if (c == '[' || c == ']') {
2878 needed = true;
2879 break;
2880 }
2881 }
2882 if (needed == false) {
2883 return path;
2884 }
2885
2886 StringBuilder sb = new StringBuilder("");
2887 for (char c : chars) {
2888 if (c == '[' || c == ']') {
2889 sb.append('%');
2890 sb.append(Integer.toHexString(c));
2891 } else {
2892 sb.append(c);
2893 }
2894 }
2895
2896 return sb.toString();
2897 }
2898
The Android Open Source Project0c908882009-03-03 19:32:16 -08002899 /**
2900 * Notify the host application a download should be done, even if there
2901 * is a streaming viewer available for thise type.
2902 * @param url The full url to the content that should be downloaded
2903 * @param contentDisposition Content-disposition http header, if
2904 * present.
2905 * @param mimetype The mimetype of the content reported by the server
2906 * @param contentLength The file size reported by the server
2907 */
2908 /*package */ void onDownloadStartNoStream(String url, String userAgent,
2909 String contentDisposition, String mimetype, long contentLength) {
2910
2911 String filename = URLUtil.guessFileName(url,
2912 contentDisposition, mimetype);
2913
2914 // Check to see if we have an SDCard
2915 String status = Environment.getExternalStorageState();
2916 if (!status.equals(Environment.MEDIA_MOUNTED)) {
2917 int title;
2918 String msg;
2919
2920 // Check to see if the SDCard is busy, same as the music app
2921 if (status.equals(Environment.MEDIA_SHARED)) {
2922 msg = getString(R.string.download_sdcard_busy_dlg_msg);
2923 title = R.string.download_sdcard_busy_dlg_title;
2924 } else {
2925 msg = getString(R.string.download_no_sdcard_dlg_msg, filename);
2926 title = R.string.download_no_sdcard_dlg_title;
2927 }
2928
2929 new AlertDialog.Builder(this)
2930 .setTitle(title)
2931 .setIcon(android.R.drawable.ic_dialog_alert)
2932 .setMessage(msg)
2933 .setPositiveButton(R.string.ok, null)
2934 .show();
2935 return;
2936 }
2937
Kristian Monsenfa52d172010-03-25 18:29:21 +00002938 // java.net.URI is a lot stricter than KURL so we have to encode some
2939 // extra characters. Fix for b 2538060 and b 1634719
2940 WebAddress webAddress;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002941 try {
Kristian Monsenfa52d172010-03-25 18:29:21 +00002942 webAddress = new WebAddress(url);
2943 webAddress.mPath = encodePath(webAddress.mPath);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002944 } catch (Exception e) {
Kristian Monsenfa52d172010-03-25 18:29:21 +00002945 // This only happens for very bad urls, we want to chatch the
2946 // exception here
2947 Log.e(LOGTAG, "Exception trying to parse url:" + url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002948 return;
2949 }
2950
2951 // XXX: Have to use the old url since the cookies were stored using the
2952 // old percent-encoded url.
2953 String cookies = CookieManager.getInstance().getCookie(url);
2954
2955 ContentValues values = new ContentValues();
Kristian Monsenfa52d172010-03-25 18:29:21 +00002956 values.put(Downloads.Impl.COLUMN_URI, webAddress.toString());
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08002957 values.put(Downloads.Impl.COLUMN_COOKIE_DATA, cookies);
2958 values.put(Downloads.Impl.COLUMN_USER_AGENT, userAgent);
2959 values.put(Downloads.Impl.COLUMN_NOTIFICATION_PACKAGE,
The Android Open Source Project0c908882009-03-03 19:32:16 -08002960 getPackageName());
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08002961 values.put(Downloads.Impl.COLUMN_NOTIFICATION_CLASS,
Leon Scrogginsa563d092010-04-19 16:53:49 -04002962 OpenDownloadReceiver.class.getCanonicalName());
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08002963 values.put(Downloads.Impl.COLUMN_VISIBILITY,
2964 Downloads.Impl.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
2965 values.put(Downloads.Impl.COLUMN_MIME_TYPE, mimetype);
2966 values.put(Downloads.Impl.COLUMN_FILE_NAME_HINT, filename);
Kristian Monsenfa52d172010-03-25 18:29:21 +00002967 values.put(Downloads.Impl.COLUMN_DESCRIPTION, webAddress.mHost);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002968 if (contentLength > 0) {
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08002969 values.put(Downloads.Impl.COLUMN_TOTAL_BYTES, contentLength);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002970 }
2971 if (mimetype == null) {
2972 // We must have long pressed on a link or image to download it. We
2973 // are not sure of the mimetype in this case, so do a head request
2974 new FetchUrlMimeType(this).execute(values);
2975 } else {
2976 final Uri contentUri =
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08002977 getContentResolver().insert(Downloads.Impl.CONTENT_URI, values);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002978 }
Leon Scroggins9191a7f2010-03-18 14:44:44 -04002979 Toast.makeText(this, R.string.download_pending, Toast.LENGTH_SHORT)
2980 .show();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002981 }
2982
Grace Kloba22ac16e2009-10-07 18:00:23 -07002983 // -------------------------------------------------------------------------
2984
The Android Open Source Project0c908882009-03-03 19:32:16 -08002985 /**
2986 * Resets the lock icon. This method is called when we start a new load and
2987 * know the url to be loaded.
2988 */
2989 private void resetLockIcon(String url) {
2990 // Save the lock-icon state (we revert to it if the load gets cancelled)
Grace Kloba22ac16e2009-10-07 18:00:23 -07002991 mTabControl.getCurrentTab().resetLockIcon(url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002992 updateLockIconImage(LOCK_ICON_UNSECURE);
2993 }
2994
The Android Open Source Project0c908882009-03-03 19:32:16 -08002995 /**
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04002996 * Update the lock icon to correspond to our latest state.
2997 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07002998 private void updateLockIconToLatest() {
2999 updateLockIconImage(mTabControl.getCurrentTab().getLockIconType());
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04003000 }
3001
3002 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08003003 * Updates the lock-icon image in the title-bar.
3004 */
3005 private void updateLockIconImage(int lockIconType) {
3006 Drawable d = null;
3007 if (lockIconType == LOCK_ICON_SECURE) {
3008 d = mSecLockIcon;
3009 } else if (lockIconType == LOCK_ICON_MIXED) {
3010 d = mMixLockIcon;
3011 }
Leon Scroggins68579392009-09-15 15:31:54 -04003012 mTitleBar.setLock(d);
Leon Scrogginsfe87bd32009-10-06 10:10:00 -04003013 mFakeTitleBar.setLock(d);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003014 }
3015
3016 /**
3017 * Displays a page-info dialog.
3018 * @param tab The tab to show info about
3019 * @param fromShowSSLCertificateOnError The flag that indicates whether
3020 * this dialog was opened from the SSL-certificate-on-error dialog or
3021 * not. This is important, since we need to know whether to return to
3022 * the parent dialog or simply dismiss.
3023 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003024 private void showPageInfo(final Tab tab,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003025 final boolean fromShowSSLCertificateOnError) {
3026 final LayoutInflater factory = LayoutInflater
3027 .from(this);
3028
3029 final View pageInfoView = factory.inflate(R.layout.page_info, null);
3030
3031 final WebView view = tab.getWebView();
3032
3033 String url = null;
3034 String title = null;
3035
3036 if (view == null) {
3037 url = tab.getUrl();
3038 title = tab.getTitle();
3039 } else if (view == mTabControl.getCurrentWebView()) {
3040 // Use the cached title and url if this is the current WebView
3041 url = mUrl;
3042 title = mTitle;
3043 } else {
3044 url = view.getUrl();
3045 title = view.getTitle();
3046 }
3047
3048 if (url == null) {
3049 url = "";
3050 }
3051 if (title == null) {
3052 title = "";
3053 }
3054
3055 ((TextView) pageInfoView.findViewById(R.id.address)).setText(url);
3056 ((TextView) pageInfoView.findViewById(R.id.title)).setText(title);
3057
3058 mPageInfoView = tab;
Leon Scrogginsc7b92f82010-01-11 18:17:31 -05003059 mPageInfoFromShowSSLCertificateOnError = fromShowSSLCertificateOnError;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003060
3061 AlertDialog.Builder alertDialogBuilder =
3062 new AlertDialog.Builder(this)
3063 .setTitle(R.string.page_info).setIcon(android.R.drawable.ic_dialog_info)
3064 .setView(pageInfoView)
3065 .setPositiveButton(
3066 R.string.ok,
3067 new DialogInterface.OnClickListener() {
3068 public void onClick(DialogInterface dialog,
3069 int whichButton) {
3070 mPageInfoDialog = null;
3071 mPageInfoView = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003072
3073 // if we came here from the SSL error dialog
3074 if (fromShowSSLCertificateOnError) {
3075 // go back to the SSL error dialog
3076 showSSLCertificateOnError(
3077 mSSLCertificateOnErrorView,
3078 mSSLCertificateOnErrorHandler,
3079 mSSLCertificateOnErrorError);
3080 }
3081 }
3082 })
3083 .setOnCancelListener(
3084 new DialogInterface.OnCancelListener() {
3085 public void onCancel(DialogInterface dialog) {
3086 mPageInfoDialog = null;
3087 mPageInfoView = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003088
3089 // if we came here from the SSL error dialog
3090 if (fromShowSSLCertificateOnError) {
3091 // go back to the SSL error dialog
3092 showSSLCertificateOnError(
3093 mSSLCertificateOnErrorView,
3094 mSSLCertificateOnErrorHandler,
3095 mSSLCertificateOnErrorError);
3096 }
3097 }
3098 });
3099
3100 // if we have a main top-level page SSL certificate set or a certificate
3101 // error
3102 if (fromShowSSLCertificateOnError ||
3103 (view != null && view.getCertificate() != null)) {
3104 // add a 'View Certificate' button
3105 alertDialogBuilder.setNeutralButton(
3106 R.string.view_certificate,
3107 new DialogInterface.OnClickListener() {
3108 public void onClick(DialogInterface dialog,
3109 int whichButton) {
3110 mPageInfoDialog = null;
3111 mPageInfoView = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003112
3113 // if we came here from the SSL error dialog
3114 if (fromShowSSLCertificateOnError) {
3115 // go back to the SSL error dialog
3116 showSSLCertificateOnError(
3117 mSSLCertificateOnErrorView,
3118 mSSLCertificateOnErrorHandler,
3119 mSSLCertificateOnErrorError);
3120 } else {
3121 // otherwise, display the top-most certificate from
3122 // the chain
3123 if (view.getCertificate() != null) {
3124 showSSLCertificate(tab);
3125 }
3126 }
3127 }
3128 });
3129 }
3130
3131 mPageInfoDialog = alertDialogBuilder.show();
3132 }
3133
3134 /**
3135 * Displays the main top-level page SSL certificate dialog
3136 * (accessible from the Page-Info dialog).
3137 * @param tab The tab to show certificate for.
3138 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003139 private void showSSLCertificate(final Tab tab) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003140 final View certificateView =
3141 inflateCertificateView(tab.getWebView().getCertificate());
3142 if (certificateView == null) {
3143 return;
3144 }
3145
3146 LayoutInflater factory = LayoutInflater.from(this);
3147
3148 final LinearLayout placeholder =
3149 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3150
3151 LinearLayout ll = (LinearLayout) factory.inflate(
3152 R.layout.ssl_success, placeholder);
3153 ((TextView)ll.findViewById(R.id.success))
3154 .setText(R.string.ssl_certificate_is_valid);
3155
3156 mSSLCertificateView = tab;
3157 mSSLCertificateDialog =
3158 new AlertDialog.Builder(this)
3159 .setTitle(R.string.ssl_certificate).setIcon(
3160 R.drawable.ic_dialog_browser_certificate_secure)
3161 .setView(certificateView)
3162 .setPositiveButton(R.string.ok,
3163 new DialogInterface.OnClickListener() {
3164 public void onClick(DialogInterface dialog,
3165 int whichButton) {
3166 mSSLCertificateDialog = null;
3167 mSSLCertificateView = null;
3168
3169 showPageInfo(tab, false);
3170 }
3171 })
3172 .setOnCancelListener(
3173 new DialogInterface.OnCancelListener() {
3174 public void onCancel(DialogInterface dialog) {
3175 mSSLCertificateDialog = null;
3176 mSSLCertificateView = null;
3177
3178 showPageInfo(tab, false);
3179 }
3180 })
3181 .show();
3182 }
3183
3184 /**
3185 * Displays the SSL error certificate dialog.
3186 * @param view The target web-view.
3187 * @param handler The SSL error handler responsible for cancelling the
3188 * connection that resulted in an SSL error or proceeding per user request.
3189 * @param error The SSL error object.
3190 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003191 void showSSLCertificateOnError(
The Android Open Source Project0c908882009-03-03 19:32:16 -08003192 final WebView view, final SslErrorHandler handler, final SslError error) {
3193
3194 final View certificateView =
3195 inflateCertificateView(error.getCertificate());
3196 if (certificateView == null) {
3197 return;
3198 }
3199
3200 LayoutInflater factory = LayoutInflater.from(this);
3201
3202 final LinearLayout placeholder =
3203 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3204
3205 if (error.hasError(SslError.SSL_UNTRUSTED)) {
3206 LinearLayout ll = (LinearLayout)factory
3207 .inflate(R.layout.ssl_warning, placeholder);
3208 ((TextView)ll.findViewById(R.id.warning))
3209 .setText(R.string.ssl_untrusted);
3210 }
3211
3212 if (error.hasError(SslError.SSL_IDMISMATCH)) {
3213 LinearLayout ll = (LinearLayout)factory
3214 .inflate(R.layout.ssl_warning, placeholder);
3215 ((TextView)ll.findViewById(R.id.warning))
3216 .setText(R.string.ssl_mismatch);
3217 }
3218
3219 if (error.hasError(SslError.SSL_EXPIRED)) {
3220 LinearLayout ll = (LinearLayout)factory
3221 .inflate(R.layout.ssl_warning, placeholder);
3222 ((TextView)ll.findViewById(R.id.warning))
3223 .setText(R.string.ssl_expired);
3224 }
3225
3226 if (error.hasError(SslError.SSL_NOTYETVALID)) {
3227 LinearLayout ll = (LinearLayout)factory
3228 .inflate(R.layout.ssl_warning, placeholder);
3229 ((TextView)ll.findViewById(R.id.warning))
3230 .setText(R.string.ssl_not_yet_valid);
3231 }
3232
3233 mSSLCertificateOnErrorHandler = handler;
3234 mSSLCertificateOnErrorView = view;
3235 mSSLCertificateOnErrorError = error;
3236 mSSLCertificateOnErrorDialog =
3237 new AlertDialog.Builder(this)
3238 .setTitle(R.string.ssl_certificate).setIcon(
3239 R.drawable.ic_dialog_browser_certificate_partially_secure)
3240 .setView(certificateView)
3241 .setPositiveButton(R.string.ok,
3242 new DialogInterface.OnClickListener() {
3243 public void onClick(DialogInterface dialog,
3244 int whichButton) {
3245 mSSLCertificateOnErrorDialog = null;
3246 mSSLCertificateOnErrorView = null;
3247 mSSLCertificateOnErrorHandler = null;
3248 mSSLCertificateOnErrorError = null;
3249
Grace Kloba22ac16e2009-10-07 18:00:23 -07003250 view.getWebViewClient().onReceivedSslError(
3251 view, handler, error);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003252 }
3253 })
3254 .setNeutralButton(R.string.page_info_view,
3255 new DialogInterface.OnClickListener() {
3256 public void onClick(DialogInterface dialog,
3257 int whichButton) {
3258 mSSLCertificateOnErrorDialog = null;
3259
3260 // do not clear the dialog state: we will
3261 // need to show the dialog again once the
3262 // user is done exploring the page-info details
3263
3264 showPageInfo(mTabControl.getTabFromView(view),
3265 true);
3266 }
3267 })
3268 .setOnCancelListener(
3269 new DialogInterface.OnCancelListener() {
3270 public void onCancel(DialogInterface dialog) {
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 .show();
3281 }
3282
3283 /**
3284 * Inflates the SSL certificate view (helper method).
3285 * @param certificate The SSL certificate.
3286 * @return The resultant certificate view with issued-to, issued-by,
3287 * issued-on, expires-on, and possibly other fields set.
3288 * If the input certificate is null, returns null.
3289 */
3290 private View inflateCertificateView(SslCertificate certificate) {
3291 if (certificate == null) {
3292 return null;
3293 }
3294
3295 LayoutInflater factory = LayoutInflater.from(this);
3296
3297 View certificateView = factory.inflate(
3298 R.layout.ssl_certificate, null);
3299
3300 // issued to:
3301 SslCertificate.DName issuedTo = certificate.getIssuedTo();
3302 if (issuedTo != null) {
3303 ((TextView) certificateView.findViewById(R.id.to_common))
3304 .setText(issuedTo.getCName());
3305 ((TextView) certificateView.findViewById(R.id.to_org))
3306 .setText(issuedTo.getOName());
3307 ((TextView) certificateView.findViewById(R.id.to_org_unit))
3308 .setText(issuedTo.getUName());
3309 }
3310
3311 // issued by:
3312 SslCertificate.DName issuedBy = certificate.getIssuedBy();
3313 if (issuedBy != null) {
3314 ((TextView) certificateView.findViewById(R.id.by_common))
3315 .setText(issuedBy.getCName());
3316 ((TextView) certificateView.findViewById(R.id.by_org))
3317 .setText(issuedBy.getOName());
3318 ((TextView) certificateView.findViewById(R.id.by_org_unit))
3319 .setText(issuedBy.getUName());
3320 }
3321
3322 // issued on:
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003323 String issuedOn = formatCertificateDate(
3324 certificate.getValidNotBeforeDate());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003325 ((TextView) certificateView.findViewById(R.id.issued_on))
3326 .setText(issuedOn);
3327
3328 // expires on:
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003329 String expiresOn = formatCertificateDate(
3330 certificate.getValidNotAfterDate());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003331 ((TextView) certificateView.findViewById(R.id.expires_on))
3332 .setText(expiresOn);
3333
3334 return certificateView;
3335 }
3336
3337 /**
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003338 * Formats the certificate date to a properly localized date string.
The Android Open Source Project0c908882009-03-03 19:32:16 -08003339 * @return Properly localized version of the certificate date string and
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003340 * the "" if it fails to localize.
The Android Open Source Project0c908882009-03-03 19:32:16 -08003341 */
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003342 private String formatCertificateDate(Date certificateDate) {
3343 if (certificateDate == null) {
3344 return "";
The Android Open Source Project0c908882009-03-03 19:32:16 -08003345 }
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003346 String formattedDate = DateFormat.getDateFormat(this).format(certificateDate);
3347 if (formattedDate == null) {
3348 return "";
3349 }
3350 return formattedDate;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003351 }
3352
3353 /**
3354 * Displays an http-authentication dialog.
3355 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003356 void showHttpAuthentication(final HttpAuthHandler handler,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003357 final String host, final String realm, final String title,
3358 final String name, final String password, int focusId) {
3359 LayoutInflater factory = LayoutInflater.from(this);
3360 final View v = factory
3361 .inflate(R.layout.http_authentication, null);
3362 if (name != null) {
3363 ((EditText) v.findViewById(R.id.username_edit)).setText(name);
3364 }
3365 if (password != null) {
3366 ((EditText) v.findViewById(R.id.password_edit)).setText(password);
3367 }
3368
3369 String titleText = title;
3370 if (titleText == null) {
3371 titleText = getText(R.string.sign_in_to).toString().replace(
3372 "%s1", host).replace("%s2", realm);
3373 }
3374
3375 mHttpAuthHandler = handler;
3376 AlertDialog dialog = new AlertDialog.Builder(this)
3377 .setTitle(titleText)
3378 .setIcon(android.R.drawable.ic_dialog_alert)
3379 .setView(v)
3380 .setPositiveButton(R.string.action,
3381 new DialogInterface.OnClickListener() {
3382 public void onClick(DialogInterface dialog,
3383 int whichButton) {
3384 String nm = ((EditText) v
3385 .findViewById(R.id.username_edit))
3386 .getText().toString();
3387 String pw = ((EditText) v
3388 .findViewById(R.id.password_edit))
3389 .getText().toString();
3390 BrowserActivity.this.setHttpAuthUsernamePassword
3391 (host, realm, nm, pw);
3392 handler.proceed(nm, pw);
3393 mHttpAuthenticationDialog = null;
3394 mHttpAuthHandler = null;
3395 }})
3396 .setNegativeButton(R.string.cancel,
3397 new DialogInterface.OnClickListener() {
3398 public void onClick(DialogInterface dialog,
3399 int whichButton) {
3400 handler.cancel();
3401 BrowserActivity.this.resetTitleAndRevertLockIcon();
3402 mHttpAuthenticationDialog = null;
3403 mHttpAuthHandler = null;
3404 }})
3405 .setOnCancelListener(new DialogInterface.OnCancelListener() {
3406 public void onCancel(DialogInterface dialog) {
3407 handler.cancel();
3408 BrowserActivity.this.resetTitleAndRevertLockIcon();
3409 mHttpAuthenticationDialog = null;
3410 mHttpAuthHandler = null;
3411 }})
3412 .create();
3413 // Make the IME appear when the dialog is displayed if applicable.
3414 dialog.getWindow().setSoftInputMode(
3415 WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
3416 dialog.show();
3417 if (focusId != 0) {
3418 dialog.findViewById(focusId).requestFocus();
3419 } else {
3420 v.findViewById(R.id.username_edit).requestFocus();
3421 }
3422 mHttpAuthenticationDialog = dialog;
3423 }
3424
3425 public int getProgress() {
3426 WebView w = mTabControl.getCurrentWebView();
3427 if (w != null) {
3428 return w.getProgress();
3429 } else {
3430 return 100;
3431 }
3432 }
3433
3434 /**
3435 * Set HTTP authentication password.
3436 *
3437 * @param host The host for the password
3438 * @param realm The realm for the password
3439 * @param username The username for the password. If it is null, it means
3440 * password can't be saved.
3441 * @param password The password
3442 */
3443 public void setHttpAuthUsernamePassword(String host, String realm,
3444 String username,
3445 String password) {
Steve Block95a53b22010-03-25 17:24:58 +00003446 WebView w = getTopWindow();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003447 if (w != null) {
3448 w.setHttpAuthUsernamePassword(host, realm, username, password);
3449 }
3450 }
3451
3452 /**
3453 * connectivity manager says net has come or gone... inform the user
3454 * @param up true if net has come up, false if net has gone down
3455 */
3456 public void onNetworkToggle(boolean up) {
3457 if (up == mIsNetworkUp) {
3458 return;
3459 } else if (up) {
3460 mIsNetworkUp = true;
3461 if (mAlertDialog != null) {
3462 mAlertDialog.cancel();
3463 mAlertDialog = null;
3464 }
3465 } else {
3466 mIsNetworkUp = false;
Patrick Scotteb6ab2a2009-09-16 10:00:17 -04003467 if (mInLoad) {
3468 createAndShowNetworkDialog();
3469 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003470 }
3471 WebView w = mTabControl.getCurrentWebView();
3472 if (w != null) {
3473 w.setNetworkAvailable(up);
3474 }
3475 }
3476
Grace Kloba22ac16e2009-10-07 18:00:23 -07003477 boolean isNetworkUp() {
3478 return mIsNetworkUp;
3479 }
3480
Patrick Scotteb6ab2a2009-09-16 10:00:17 -04003481 // This method shows the network dialog alerting the user that the net is
3482 // down. It will only show the dialog if mAlertDialog is null.
3483 private void createAndShowNetworkDialog() {
3484 if (mAlertDialog == null) {
3485 mAlertDialog = new AlertDialog.Builder(this)
3486 .setTitle(R.string.loadSuspendedTitle)
3487 .setMessage(R.string.loadSuspended)
3488 .setPositiveButton(R.string.ok, null)
3489 .show();
3490 }
3491 }
3492
The Android Open Source Project0c908882009-03-03 19:32:16 -08003493 @Override
3494 protected void onActivityResult(int requestCode, int resultCode,
3495 Intent intent) {
Grace Klobabb394f32009-11-19 10:26:37 -08003496 if (getTopWindow() == null) return;
3497
The Android Open Source Project0c908882009-03-03 19:32:16 -08003498 switch (requestCode) {
3499 case COMBO_PAGE:
3500 if (resultCode == RESULT_OK && intent != null) {
3501 String data = intent.getAction();
3502 Bundle extras = intent.getExtras();
3503 if (extras != null && extras.getBoolean("new_window", false)) {
Leon Scroggins25d35472009-09-15 11:37:27 -04003504 openTab(data);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003505 } else {
Grace Kloba22ac16e2009-10-07 18:00:23 -07003506 final Tab currentTab =
The Android Open Source Project0c908882009-03-03 19:32:16 -08003507 mTabControl.getCurrentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04003508 dismissSubWindow(currentTab);
3509 if (data != null && data.length() != 0) {
Leon Scroggins92472e82010-02-17 16:32:28 -05003510 loadUrl(getTopWindow(), data);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003511 }
3512 }
3513 }
Leon Scrogginsfde97462010-01-11 13:06:21 -05003514 // Deliberately fall through to PREFERENCES_PAGE, since the
3515 // same extra may be attached to the COMBO_PAGE
3516 case PREFERENCES_PAGE:
3517 if (resultCode == RESULT_OK && intent != null) {
3518 String action = intent.getStringExtra(Intent.EXTRA_TEXT);
3519 if (BrowserSettings.PREF_CLEAR_HISTORY.equals(action)) {
3520 mTabControl.removeParentChildRelationShips();
3521 }
3522 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003523 break;
Leon Scroggins8d5fa432009-10-02 15:55:59 -04003524 // Choose a file from the file picker.
3525 case FILE_SELECTED:
3526 if (null == mUploadMessage) break;
3527 Uri result = intent == null || resultCode != RESULT_OK ? null
3528 : intent.getData();
3529 mUploadMessage.onReceiveValue(result);
3530 mUploadMessage = null;
3531 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003532 default:
3533 break;
3534 }
Leon Scroggins30444232009-09-04 18:36:20 -04003535 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003536 }
3537
3538 /*
3539 * This method is called as a result of the user selecting the options
Leon Scrogginsf08809b2010-01-21 09:27:46 -05003540 * menu to see the download window. It shows the download window on top of
3541 * the current window.
The Android Open Source Project0c908882009-03-03 19:32:16 -08003542 */
Leon Scroggins IIIa682a3c2010-09-27 12:32:40 -04003543 private void viewDownloads() {
3544 Intent intent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
3545 startActivity(intent);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003546 }
3547
Leon Scroggins160a7e72009-08-14 18:28:01 -04003548 /**
3549 * Open the Go page.
3550 * @param startWithHistory If true, open starting on the history tab.
3551 * Otherwise, start with the bookmarks tab.
Leon Scroggins160a7e72009-08-14 18:28:01 -04003552 */
Leon Scroggins30444232009-09-04 18:36:20 -04003553 /* package */ void bookmarksOrHistoryPicker(boolean startWithHistory) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003554 WebView current = mTabControl.getCurrentWebView();
3555 if (current == null) {
3556 return;
3557 }
3558 Intent intent = new Intent(this,
3559 CombinedBookmarkHistoryActivity.class);
3560 String title = current.getTitle();
3561 String url = current.getUrl();
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01003562 Bitmap thumbnail = createScreenshot(current);
3563
The Android Open Source Project0c908882009-03-03 19:32:16 -08003564 // Just in case the user opens bookmarks before a page finishes loading
3565 // so the current history item, and therefore the page, is null.
3566 if (null == url) {
3567 url = mLastEnteredUrl;
3568 // This can happen.
3569 if (null == url) {
3570 url = mSettings.getHomePage();
3571 }
3572 }
3573 // In case the web page has not yet received its associated title.
3574 if (title == null) {
3575 title = url;
3576 }
3577 intent.putExtra("title", title);
3578 intent.putExtra("url", url);
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01003579 intent.putExtra("thumbnail", thumbnail);
Leon Scroggins30444232009-09-04 18:36:20 -04003580 // Disable opening in a new window if we have maxed out the windows
Grace Kloba22ac16e2009-10-07 18:00:23 -07003581 intent.putExtra("disable_new_window", !mTabControl.canCreateNewTab());
Patrick Scott3918d442009-08-04 13:22:29 -04003582 intent.putExtra("touch_icon_url", current.getTouchIconUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003583 if (startWithHistory) {
3584 intent.putExtra(CombinedBookmarkHistoryActivity.STARTING_TAB,
3585 CombinedBookmarkHistoryActivity.HISTORY_TAB);
3586 }
3587 startActivityForResult(intent, COMBO_PAGE);
3588 }
3589
3590 // Called when loading from context menu or LOAD_URL message
Leon Scroggins92472e82010-02-17 16:32:28 -05003591 private void loadUrlFromContext(WebView view, String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003592 // In case the user enters nothing.
3593 if (url != null && url.length() != 0 && view != null) {
3594 url = smartUrlFilter(url);
Grace Kloba22ac16e2009-10-07 18:00:23 -07003595 if (!view.getWebViewClient().shouldOverrideUrlLoading(view, url)) {
Leon Scroggins92472e82010-02-17 16:32:28 -05003596 loadUrl(view, url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003597 }
3598 }
3599 }
3600
Leon Scroggins92472e82010-02-17 16:32:28 -05003601 /**
3602 * Load the URL into the given WebView and update the title bar
3603 * to reflect the new load. Call this instead of WebView.loadUrl
3604 * directly.
3605 * @param view The WebView used to load url.
3606 * @param url The URL to load.
3607 */
3608 private void loadUrl(WebView view, String url) {
3609 updateTitleBarForNewLoad(view, url);
3610 view.loadUrl(url);
3611 }
3612
3613 /**
3614 * Load UrlData into a Tab and update the title bar to reflect the new
3615 * load. Call this instead of UrlData.loadIn directly.
3616 * @param t The Tab used to load.
3617 * @param data The UrlData being loaded.
3618 */
3619 private void loadUrlDataIn(Tab t, UrlData data) {
3620 updateTitleBarForNewLoad(t.getWebView(), data.mUrl);
3621 data.loadIn(t);
3622 }
3623
3624 /**
3625 * If the WebView is the top window, update the title bar to reflect
3626 * loading the new URL. i.e. set its text, clear the favicon (which
3627 * will be set once the page begins loading), and set the progress to
3628 * INITIAL_PROGRESS to show that the page has begun to load. Called
3629 * by loadUrl and loadUrlDataIn.
3630 * @param view The WebView that is starting a load.
3631 * @param url The URL that is being loaded.
3632 */
3633 private void updateTitleBarForNewLoad(WebView view, String url) {
3634 if (view == getTopWindow()) {
3635 setUrlTitle(url, null);
3636 setFavicon(null);
3637 onProgressChanged(view, INITIAL_PROGRESS);
3638 }
3639 }
3640
The Android Open Source Project0c908882009-03-03 19:32:16 -08003641 private String smartUrlFilter(Uri inUri) {
3642 if (inUri != null) {
3643 return smartUrlFilter(inUri.toString());
3644 }
3645 return null;
3646 }
3647
Feng Qianb34f87a2009-03-24 21:27:26 -07003648 protected static final Pattern ACCEPTED_URI_SCHEMA = Pattern.compile(
The Android Open Source Project0c908882009-03-03 19:32:16 -08003649 "(?i)" + // switch on case insensitive matching
3650 "(" + // begin group for schema
3651 "(?:http|https|file):\\/\\/" +
Huahui Wu604a5982011-03-22 15:00:11 -07003652 "|(?:inline|data|about|javascript):" +
The Android Open Source Project0c908882009-03-03 19:32:16 -08003653 ")" +
3654 "(.*)" );
3655
3656 /**
3657 * Attempts to determine whether user input is a URL or search
3658 * terms. Anything with a space is passed to search.
3659 *
3660 * Converts to lowercase any mistakenly uppercased schema (i.e.,
3661 * "Http://" converts to "http://"
3662 *
3663 * @return Original or modified URL
3664 *
3665 */
3666 String smartUrlFilter(String url) {
3667
3668 String inUrl = url.trim();
3669 boolean hasSpace = inUrl.indexOf(' ') != -1;
3670
3671 Matcher matcher = ACCEPTED_URI_SCHEMA.matcher(inUrl);
3672 if (matcher.matches()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003673 // force scheme to lowercase
3674 String scheme = matcher.group(1);
3675 String lcScheme = scheme.toLowerCase();
3676 if (!lcScheme.equals(scheme)) {
Mitsuru Oshima123ecfb2009-05-18 19:11:14 -07003677 inUrl = lcScheme + matcher.group(2);
3678 }
3679 if (hasSpace) {
3680 inUrl = inUrl.replace(" ", "%20");
The Android Open Source Project0c908882009-03-03 19:32:16 -08003681 }
3682 return inUrl;
3683 }
Leon Scroggins956cf012010-10-07 13:51:57 -04003684 if (!hasSpace) {
Dan Egnor5ee906c2009-11-18 12:11:49 -08003685 if (Patterns.WEB_URL.matcher(inUrl).matches()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003686 return URLUtil.guessUrl(inUrl);
3687 }
3688 }
3689
Leon Scroggins956cf012010-10-07 13:51:57 -04003690 // FIXME: Is this the correct place to add to searches?
3691 // what if someone else calls this function?
3692
The Android Open Source Project0c908882009-03-03 19:32:16 -08003693 Browser.addSearchUrl(mResolver, inUrl);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07003694 return URLUtil.composeSearchUrl(inUrl, QuickSearch_G, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003695 }
3696
Ben Murdochbff2d602009-07-01 20:19:05 +01003697 /* package */ void setShouldShowErrorConsole(boolean flag) {
3698 if (flag == mShouldShowErrorConsole) {
3699 // Nothing to do.
3700 return;
3701 }
Leon Scroggins IIIa9e35b62010-09-16 15:30:15 -04003702 Tab t = mTabControl.getCurrentTab();
3703 if (t == null) {
3704 // There is no current tab so we cannot toggle the error console
3705 return;
3706 }
Ben Murdochbff2d602009-07-01 20:19:05 +01003707
3708 mShouldShowErrorConsole = flag;
3709
Leon Scroggins IIIa9e35b62010-09-16 15:30:15 -04003710 ErrorConsoleView errorConsole = t.getErrorConsole(true);
Ben Murdochbff2d602009-07-01 20:19:05 +01003711
3712 if (flag) {
3713 // Setting the show state of the console will cause it's the layout to be inflated.
3714 if (errorConsole.numberOfErrors() > 0) {
3715 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
3716 } else {
3717 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
3718 }
3719
3720 // Now we can add it to the main view.
3721 mErrorConsoleContainer.addView(errorConsole,
Romain Guy15b8ec62010-01-08 15:06:43 -08003722 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
Ben Murdochbff2d602009-07-01 20:19:05 +01003723 ViewGroup.LayoutParams.WRAP_CONTENT));
3724 } else {
3725 mErrorConsoleContainer.removeView(errorConsole);
3726 }
3727
3728 }
3729
Grace Kloba22ac16e2009-10-07 18:00:23 -07003730 boolean shouldShowErrorConsole() {
3731 return mShouldShowErrorConsole;
3732 }
3733
Andrei Popescu163ab742009-10-20 17:58:23 +01003734 private void setStatusBarVisibility(boolean visible) {
3735 int flag = visible ? 0 : WindowManager.LayoutParams.FLAG_FULLSCREEN;
3736 getWindow().setFlags(flag, WindowManager.LayoutParams.FLAG_FULLSCREEN);
3737 }
3738
Andrei Popescu56199cc2010-01-12 22:39:16 +00003739
3740 private void sendNetworkType(String type, String subtype) {
3741 WebView w = mTabControl.getCurrentWebView();
3742 if (w != null) {
3743 w.setNetworkType(type, subtype);
3744 }
3745 }
3746
Andrei Popescu30995e72010-02-09 16:59:58 +00003747 private void packageChanged(String packageName, boolean wasAdded) {
3748 WebView w = mTabControl.getCurrentWebView();
3749 if (w == null) {
3750 return;
3751 }
3752
3753 if (wasAdded) {
3754 w.addPackageName(packageName);
3755 } else {
3756 w.removePackageName(packageName);
3757 }
3758 }
3759
3760 private void addPackageNames(Set<String> packageNames) {
3761 WebView w = mTabControl.getCurrentWebView();
3762 if (w == null) {
3763 return;
3764 }
3765
3766 w.addPackageNames(packageNames);
3767 }
3768
3769 private void getInstalledPackages() {
3770 AsyncTask<Void, Void, Set<String> > task =
3771 new AsyncTask<Void, Void, Set<String> >() {
3772 protected Set<String> doInBackground(Void... unused) {
3773 Set<String> installedPackages = new HashSet<String>();
3774 PackageManager pm = BrowserActivity.this.getPackageManager();
3775 if (pm != null) {
3776 List<PackageInfo> packages = pm.getInstalledPackages(0);
3777 for (PackageInfo p : packages) {
3778 if (BrowserActivity.this.sGoogleApps.contains(p.packageName)) {
3779 installedPackages.add(p.packageName);
3780 }
3781 }
3782 }
3783
3784 return installedPackages;
3785 }
3786
3787 // Executes on the UI thread
3788 protected void onPostExecute(Set<String> installedPackages) {
3789 addPackageNames(installedPackages);
3790 }
3791 };
3792 task.execute();
3793 }
3794
Grace Klobaeb6eef42009-09-15 17:56:32 -07003795 final static int LOCK_ICON_UNSECURE = 0;
3796 final static int LOCK_ICON_SECURE = 1;
3797 final static int LOCK_ICON_MIXED = 2;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003798
The Android Open Source Project0c908882009-03-03 19:32:16 -08003799 private BrowserSettings mSettings;
3800 private TabControl mTabControl;
3801 private ContentResolver mResolver;
3802 private FrameLayout mContentView;
Andrei Popescuadc008d2009-06-26 14:11:30 +01003803 private View mCustomView;
3804 private FrameLayout mCustomViewContainer;
Andrei Popescuc9b55562009-07-07 10:51:15 +01003805 private WebChromeClient.CustomViewCallback mCustomViewCallback;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003806
3807 // FIXME, temp address onPrepareMenu performance problem. When we move everything out of
3808 // view, we should rewrite this.
3809 private int mCurrentMenuState = 0;
3810 private int mMenuState = R.id.MAIN_MENU;
Andrei Popescuadc008d2009-06-26 14:11:30 +01003811 private int mOldMenuState = EMPTY_MENU;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003812 private static final int EMPTY_MENU = -1;
3813 private Menu mMenu;
3814
3815 private FindDialog mFindDialog;
Cary Clark2c326e62010-08-19 18:40:57 -04003816 private SelectDialog mSelectDialog;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003817 // Used to prevent chording to result in firing two shortcuts immediately
3818 // one after another. Fixes bug 1211714.
3819 boolean mCanChord;
3820
3821 private boolean mInLoad;
3822 private boolean mIsNetworkUp;
Ben Murdochb7cc8b42009-09-28 10:59:09 +01003823 private boolean mDidStopLoad;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003824
Cary Clark1f10cbf2010-03-22 11:45:23 -04003825 /* package */ boolean mActivityInPause = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003826
3827 private boolean mMenuIsDown;
3828
The Android Open Source Project0c908882009-03-03 19:32:16 -08003829 private static boolean mInTrace;
3830
3831 // Performance probe
3832 private static final int[] SYSTEM_CPU_FORMAT = new int[] {
3833 Process.PROC_SPACE_TERM | Process.PROC_COMBINE,
3834 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 1: user time
3835 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 2: nice time
3836 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 3: sys time
3837 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 4: idle time
3838 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 5: iowait time
3839 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 6: irq time
3840 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG // 7: softirq time
3841 };
3842
3843 private long mStart;
3844 private long mProcessStart;
3845 private long mUserStart;
3846 private long mSystemStart;
3847 private long mIdleStart;
3848 private long mIrqStart;
3849
3850 private long mUiStart;
3851
3852 private Drawable mMixLockIcon;
3853 private Drawable mSecLockIcon;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003854
3855 /* hold a ref so we can auto-cancel if necessary */
3856 private AlertDialog mAlertDialog;
3857
The Android Open Source Project0c908882009-03-03 19:32:16 -08003858 // The up-to-date URL and title (these can be different from those stored
3859 // in WebView, since it takes some time for the information in WebView to
3860 // get updated)
3861 private String mUrl;
3862 private String mTitle;
3863
3864 // As PageInfo has different style for landscape / portrait, we have
3865 // to re-open it when configuration changed
3866 private AlertDialog mPageInfoDialog;
Grace Kloba22ac16e2009-10-07 18:00:23 -07003867 private Tab mPageInfoView;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003868 // If the Page-Info dialog is launched from the SSL-certificate-on-error
3869 // dialog, we should not just dismiss it, but should get back to the
3870 // SSL-certificate-on-error dialog. This flag is used to store this state
Leon Scrogginsc7b92f82010-01-11 18:17:31 -05003871 private boolean mPageInfoFromShowSSLCertificateOnError;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003872
3873 // as SSLCertificateOnError has different style for landscape / portrait,
3874 // we have to re-open it when configuration changed
3875 private AlertDialog mSSLCertificateOnErrorDialog;
3876 private WebView mSSLCertificateOnErrorView;
3877 private SslErrorHandler mSSLCertificateOnErrorHandler;
3878 private SslError mSSLCertificateOnErrorError;
3879
3880 // as SSLCertificate has different style for landscape / portrait, we
3881 // have to re-open it when configuration changed
3882 private AlertDialog mSSLCertificateDialog;
Grace Kloba22ac16e2009-10-07 18:00:23 -07003883 private Tab mSSLCertificateView;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003884
3885 // as HttpAuthentication has different style for landscape / portrait, we
3886 // have to re-open it when configuration changed
3887 private AlertDialog mHttpAuthenticationDialog;
3888 private HttpAuthHandler mHttpAuthHandler;
3889
3890 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_PARAMS =
3891 new FrameLayout.LayoutParams(
Romain Guy15b8ec62010-01-08 15:06:43 -08003892 ViewGroup.LayoutParams.MATCH_PARENT,
3893 ViewGroup.LayoutParams.MATCH_PARENT);
Andrei Popescuadc008d2009-06-26 14:11:30 +01003894 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_GRAVITY_CENTER =
3895 new FrameLayout.LayoutParams(
Romain Guy15b8ec62010-01-08 15:06:43 -08003896 ViewGroup.LayoutParams.MATCH_PARENT,
3897 ViewGroup.LayoutParams.MATCH_PARENT,
Andrei Popescuadc008d2009-06-26 14:11:30 +01003898 Gravity.CENTER);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07003899 // Google search
3900 final static String QuickSearch_G = "http://www.google.com/m?q=%s";
The Android Open Source Project0c908882009-03-03 19:32:16 -08003901
3902 final static String QUERY_PLACE_HOLDER = "%s";
3903
3904 // "source" parameter for Google search through search key
3905 final static String GOOGLE_SEARCH_SOURCE_SEARCHKEY = "browser-key";
3906 // "source" parameter for Google search through goto menu
3907 final static String GOOGLE_SEARCH_SOURCE_GOTO = "browser-goto";
3908 // "source" parameter for Google search through simplily type
3909 final static String GOOGLE_SEARCH_SOURCE_TYPE = "browser-type";
3910 // "source" parameter for Google search suggested by the browser
3911 final static String GOOGLE_SEARCH_SOURCE_SUGGEST = "browser-suggest";
3912 // "source" parameter for Google search from unknown source
3913 final static String GOOGLE_SEARCH_SOURCE_UNKNOWN = "unknown";
3914
3915 private final static String LOGTAG = "browser";
3916
The Android Open Source Project0c908882009-03-03 19:32:16 -08003917 private String mLastEnteredUrl;
3918
3919 private PowerManager.WakeLock mWakeLock;
3920 private final static int WAKELOCK_TIMEOUT = 5 * 60 * 1000; // 5 minutes
3921
3922 private Toast mStopToast;
3923
Leon Scroggins68579392009-09-15 15:31:54 -04003924 private TitleBar mTitleBar;
Leon Scroggins81db3662009-06-04 17:45:11 -04003925
Ben Murdochbff2d602009-07-01 20:19:05 +01003926 private LinearLayout mErrorConsoleContainer = null;
3927 private boolean mShouldShowErrorConsole = false;
3928
The Android Open Source Project0c908882009-03-03 19:32:16 -08003929 // As the ids are dynamically created, we can't guarantee that they will
3930 // be in sequence, so this static array maps ids to a window number.
3931 final static private int[] WINDOW_SHORTCUT_ID_ARRAY =
3932 { R.id.window_one_menu_id, R.id.window_two_menu_id, R.id.window_three_menu_id,
3933 R.id.window_four_menu_id, R.id.window_five_menu_id, R.id.window_six_menu_id,
3934 R.id.window_seven_menu_id, R.id.window_eight_menu_id };
3935
3936 // monitor platform changes
3937 private IntentFilter mNetworkStateChangedFilter;
3938 private BroadcastReceiver mNetworkStateIntentReceiver;
3939
Grace Klobab4da0ad2009-05-14 14:45:40 -07003940 private BroadcastReceiver mPackageInstallationReceiver;
3941
Bjorn Bringerta7611812010-03-24 11:12:02 +00003942 private SystemAllowGeolocationOrigins mSystemAllowGeolocationOrigins;
3943
The Android Open Source Project0c908882009-03-03 19:32:16 -08003944 // activity requestCode
Nicolas Roard78a98e42009-05-11 13:34:17 +01003945 final static int COMBO_PAGE = 1;
Nicolas Roard78a98e42009-05-11 13:34:17 +01003946 final static int PREFERENCES_PAGE = 3;
Leon Scroggins8d5fa432009-10-02 15:55:59 -04003947 final static int FILE_SELECTED = 4;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003948
Andrei Popescu540035d2009-09-18 18:59:20 +01003949 // the default <video> poster
3950 private Bitmap mDefaultVideoPoster;
3951 // the video progress view
3952 private View mVideoProgressView;
3953
Andrei Popescu30995e72010-02-09 16:59:58 +00003954 // The Google packages we monitor for the navigator.isApplicationInstalled()
3955 // API. Add as needed.
3956 private static Set<String> sGoogleApps;
3957 static {
3958 sGoogleApps = new HashSet<String>();
3959 sGoogleApps.add("com.google.android.youtube");
3960 }
3961
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003962 /**
3963 * A UrlData class to abstract how the content will be set to WebView.
3964 * This base class uses loadUrl to show the content.
3965 */
Leon Scroggins6eac63e2010-03-15 18:19:14 -04003966 /* package */ static class UrlData {
Grace Kloba068e48b2010-01-26 18:11:27 -08003967 final String mUrl;
3968 final Map<String, String> mHeaders;
Leon Scroggins58d56c62010-01-28 15:12:40 -05003969 final Intent mVoiceIntent;
Grace Kloba60e095c2009-06-16 11:50:55 -07003970
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003971 UrlData(String url) {
3972 this.mUrl = url;
Grace Kloba068e48b2010-01-26 18:11:27 -08003973 this.mHeaders = null;
Leon Scroggins58d56c62010-01-28 15:12:40 -05003974 this.mVoiceIntent = null;
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003975 }
Grace Kloba60e095c2009-06-16 11:50:55 -07003976
Leon Scroggins58d56c62010-01-28 15:12:40 -05003977 UrlData(String url, Map<String, String> headers, Intent intent) {
Grace Kloba068e48b2010-01-26 18:11:27 -08003978 this.mUrl = url;
3979 this.mHeaders = headers;
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -05003980 if (RecognizerResultsIntent.ACTION_VOICE_SEARCH_RESULTS
3981 .equals(intent.getAction())) {
Leon Scroggins58d56c62010-01-28 15:12:40 -05003982 this.mVoiceIntent = intent;
3983 } else {
3984 this.mVoiceIntent = null;
3985 }
Grace Kloba60e095c2009-06-16 11:50:55 -07003986 }
3987
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003988 boolean isEmpty() {
Leon Scroggins58d56c62010-01-28 15:12:40 -05003989 return mVoiceIntent == null && (mUrl == null || mUrl.length() == 0);
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003990 }
3991
Leon Scroggins92472e82010-02-17 16:32:28 -05003992 /**
3993 * Load this UrlData into the given Tab. Use loadUrlDataIn to update
3994 * the title bar as well.
3995 */
Leon Scroggins58d56c62010-01-28 15:12:40 -05003996 public void loadIn(Tab t) {
3997 if (mVoiceIntent != null) {
3998 t.activateVoiceSearchMode(mVoiceIntent);
3999 } else {
4000 t.getWebView().loadUrl(mUrl, mHeaders);
4001 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004002 }
4003 };
4004
Leon Scroggins1f005d32009-08-10 17:36:42 -04004005 /* package */ static final UrlData EMPTY_URL_DATA = new UrlData(null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004006}