blob: 793f68952c8236f0bd2351b6487e62cf8ec4000a [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());
625 if (url != null && url.startsWith("content:")) {
626 /* Append mimetype so webview knows how to display */
627 String mimeType = intent.resolveType(getContentResolver());
628 if (mimeType != null) {
629 url += "?" + mimeType;
630 }
631 }
Grace Kloba068e48b2010-01-26 18:11:27 -0800632 if (url != null && url.startsWith("http")) {
Grace Kloba00f54c52010-01-27 14:53:51 -0800633 final Bundle pairs = intent
634 .getBundleExtra(Browser.EXTRA_HEADERS);
Grace Kloba2d508ed2010-01-28 11:39:15 -0800635 if (pairs != null && !pairs.isEmpty()) {
Grace Kloba00f54c52010-01-27 14:53:51 -0800636 Iterator<String> iter = pairs.keySet().iterator();
Grace Kloba068e48b2010-01-26 18:11:27 -0800637 headers = new HashMap<String, String>();
Grace Kloba00f54c52010-01-27 14:53:51 -0800638 while (iter.hasNext()) {
639 String key = iter.next();
640 headers.put(key, pairs.getString(key));
Grace Kloba068e48b2010-01-26 18:11:27 -0800641 }
642 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700643 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800644 } else if (Intent.ACTION_SEARCH.equals(action)
645 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
646 || Intent.ACTION_WEB_SEARCH.equals(action)) {
647 url = intent.getStringExtra(SearchManager.QUERY);
648 if (url != null) {
649 mLastEnteredUrl = url;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800650 // In general, we shouldn't modify URL from Intent.
651 // But currently, we get the user-typed URL from search box as well.
652 url = fixUrl(url);
653 url = smartUrlFilter(url);
Leon Scroggins8d06e362010-03-24 14:45:57 -0400654 final ContentResolver cr = mResolver;
655 final String newUrl = url;
656 new AsyncTask<Void, Void, Void>() {
657 protected Void doInBackground(Void... unused) {
658 Browser.updateVisitedHistory(cr, newUrl, false);
659 return null;
660 }
661 }.execute();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800662 String searchSource = "&source=android-" + GOOGLE_SEARCH_SOURCE_SUGGEST + "&";
663 if (url.contains(searchSource)) {
664 String source = null;
665 final Bundle appData = intent.getBundleExtra(SearchManager.APP_DATA);
666 if (appData != null) {
Bjorn Bringert10d1cca2010-02-10 14:22:12 +0000667 source = appData.getString(Search.SOURCE);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800668 }
669 if (TextUtils.isEmpty(source)) {
670 source = GOOGLE_SEARCH_SOURCE_UNKNOWN;
671 }
672 url = url.replace(searchSource, "&source=android-"+source+"&");
673 }
674 }
675 }
676 }
Leon Scroggins58d56c62010-01-28 15:12:40 -0500677 return new UrlData(url, headers, intent);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800678 }
Leon Scroggins58d56c62010-01-28 15:12:40 -0500679 /* package */ void showVoiceTitleBar(String title) {
680 mTitleBar.setInVoiceMode(true);
681 mFakeTitleBar.setInVoiceMode(true);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800682
Leon Scroggins58d56c62010-01-28 15:12:40 -0500683 mTitleBar.setDisplayTitle(title);
684 mFakeTitleBar.setDisplayTitle(title);
685 }
686 /* package */ void revertVoiceTitleBar() {
687 mTitleBar.setInVoiceMode(false);
688 mFakeTitleBar.setInVoiceMode(false);
689
Leon Scroggins003a5dd2010-03-10 12:13:14 -0500690 mTitleBar.setDisplayTitle(mUrl);
691 mFakeTitleBar.setDisplayTitle(mUrl);
Leon Scroggins58d56c62010-01-28 15:12:40 -0500692 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800693 /* package */ static String fixUrl(String inUrl) {
Cary Clark652ff872009-09-10 13:34:44 -0400694 // FIXME: Converting the url to lower case
695 // duplicates functionality in smartUrlFilter().
696 // However, changing all current callers of fixUrl to
697 // call smartUrlFilter in addition may have unwanted
698 // consequences, and is deferred for now.
699 int colon = inUrl.indexOf(':');
700 boolean allLower = true;
701 for (int index = 0; index < colon; index++) {
702 char ch = inUrl.charAt(index);
703 if (!Character.isLetter(ch)) {
704 break;
705 }
706 allLower &= Character.isLowerCase(ch);
707 if (index == colon - 1 && !allLower) {
708 inUrl = inUrl.substring(0, colon).toLowerCase()
709 + inUrl.substring(colon);
710 }
711 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800712 if (inUrl.startsWith("http://") || inUrl.startsWith("https://"))
713 return inUrl;
714 if (inUrl.startsWith("http:") ||
715 inUrl.startsWith("https:")) {
716 if (inUrl.startsWith("http:/") || inUrl.startsWith("https:/")) {
717 inUrl = inUrl.replaceFirst("/", "//");
718 } else inUrl = inUrl.replaceFirst(":", "://");
719 }
720 return inUrl;
721 }
722
Grace Kloba22ac16e2009-10-07 18:00:23 -0700723 @Override
724 protected void onResume() {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800725 super.onResume();
Dave Bort31a6d1c2009-04-13 15:56:49 -0700726 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800727 Log.v(LOGTAG, "BrowserActivity.onResume: this=" + this);
728 }
729
730 if (!mActivityInPause) {
731 Log.e(LOGTAG, "BrowserActivity is already resumed.");
732 return;
733 }
734
Mike Reed7bfa63b2009-05-28 11:08:32 -0400735 mTabControl.resumeCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800736 mActivityInPause = false;
Mike Reed7bfa63b2009-05-28 11:08:32 -0400737 resumeWebViewTimers();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800738
739 if (mWakeLock.isHeld()) {
740 mHandler.removeMessages(RELEASE_WAKELOCK);
741 mWakeLock.release();
742 }
743
The Android Open Source Project0c908882009-03-03 19:32:16 -0800744 registerReceiver(mNetworkStateIntentReceiver,
745 mNetworkStateChangedFilter);
746 WebView.enablePlatformNotifications();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800747 }
748
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400749 /**
750 * Since the actual title bar is embedded in the WebView, and removing it
Leon Scrogginsfe87bd32009-10-06 10:10:00 -0400751 * would change its appearance, use a different TitleBar to show overlayed
752 * at the top of the screen, when the menu is open or the page is loading.
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400753 */
754 private TitleBar mFakeTitleBar;
755
756 /**
757 * Keeps track of whether the options menu is open. This is important in
758 * determining whether to show or hide the title bar overlay.
759 */
760 private boolean mOptionsMenuOpen;
761
762 /**
763 * Only meaningful when mOptionsMenuOpen is true. This variable keeps track
764 * of whether the configuration has changed. The first onMenuOpened call
765 * after a configuration change is simply a reopening of the same menu
766 * (i.e. mIconView did not change).
767 */
768 private boolean mConfigChanged;
769
770 /**
771 * Whether or not the options menu is in its smaller, icon menu form. When
772 * true, we want the title bar overlay to be up. When false, we do not.
773 * Only meaningful if mOptionsMenuOpen is true.
774 */
775 private boolean mIconView;
776
Leon Scrogginsa81a7642009-08-31 17:05:41 -0400777 @Override
778 public boolean onMenuOpened(int featureId, Menu menu) {
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400779 if (Window.FEATURE_OPTIONS_PANEL == featureId) {
780 if (mOptionsMenuOpen) {
781 if (mConfigChanged) {
782 // We do not need to make any changes to the state of the
783 // title bar, since the only thing that happened was a
784 // change in orientation
785 mConfigChanged = false;
786 } else {
787 if (mIconView) {
788 // Switching the menu to expanded view, so hide the
789 // title bar.
790 hideFakeTitleBar();
791 mIconView = false;
792 } else {
793 // Switching the menu back to icon view, so show the
794 // title bar once again.
795 showFakeTitleBar();
796 mIconView = true;
797 }
798 }
799 } else {
800 // The options menu is closed, so open it, and show the title
801 showFakeTitleBar();
802 mOptionsMenuOpen = true;
803 mConfigChanged = false;
804 mIconView = true;
805 }
806 }
Leon Scrogginsa81a7642009-08-31 17:05:41 -0400807 return true;
808 }
809
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400810 private void showFakeTitleBar() {
Leon Scrogginsfe87bd32009-10-06 10:10:00 -0400811 if (mFakeTitleBar.getParent() == null && mActiveTabsPage == null
Grace Kloba847c25b2010-03-30 16:00:26 -0700812 && !mActivityInPause) {
813 WebView mainView = mTabControl.getCurrentWebView();
814 // if there is no current WebView, don't show the faked title bar;
Grace Kloba65190702010-04-02 23:37:26 -0700815 if (mainView == null) {
Cary Clarka0464552009-09-29 13:00:45 -0400816 return;
817 }
Cary Clark2c326e62010-08-19 18:40:57 -0400818 // Do not need to check for null, since the current tab will have
819 // at least a main WebView, or we would have returned above.
820 if (dialogIsUp()) {
821 // Do not show the fake title bar, which would cover up the
822 // find or select dialog.
823 return;
824 }
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400825
826 WindowManager manager
827 = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
828
829 // Add the title bar to the window manager so it can receive touches
830 // while the menu is up
831 WindowManager.LayoutParams params
832 = new WindowManager.LayoutParams(
Romain Guy15b8ec62010-01-08 15:06:43 -0800833 ViewGroup.LayoutParams.MATCH_PARENT,
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400834 ViewGroup.LayoutParams.WRAP_CONTENT,
Grace Kloba847c25b2010-03-30 16:00:26 -0700835 WindowManager.LayoutParams.TYPE_APPLICATION,
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400836 WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
Leon Scroggins68549862009-09-21 16:02:01 -0400837 PixelFormat.TRANSLUCENT);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400838 params.gravity = Gravity.TOP;
Grace Kloba847c25b2010-03-30 16:00:26 -0700839 boolean atTop = mainView.getScrollY() == 0;
Leon Scroggins83932c72009-09-30 11:55:54 -0400840 params.windowAnimations = atTop ? 0 : R.style.TitleBar;
Grace Kloba13f9ace2010-03-18 21:44:14 -0700841 manager.addView(mFakeTitleBar, params);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400842 }
843 }
844
845 @Override
846 public void onOptionsMenuClosed(Menu menu) {
847 mOptionsMenuOpen = false;
Leon Scrogginsa27ff192009-09-14 12:58:04 -0400848 if (!mInLoad) {
849 hideFakeTitleBar();
850 } else if (!mIconView) {
851 // The page is currently loading, and we are in expanded mode, so
852 // we were not showing the menu. Show it once again. It will be
853 // removed when the page finishes.
854 showFakeTitleBar();
855 }
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400856 }
Grace Kloba22ac16e2009-10-07 18:00:23 -0700857
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400858 private void hideFakeTitleBar() {
Leon Scrogginsfe87bd32009-10-06 10:10:00 -0400859 if (mFakeTitleBar.getParent() == null) return;
Leon Scroggins20329572009-09-23 17:42:41 -0400860 WindowManager.LayoutParams params = (WindowManager.LayoutParams)
Grace Kloba13f9ace2010-03-18 21:44:14 -0700861 mFakeTitleBar.getLayoutParams();
Leon Scroggins20329572009-09-23 17:42:41 -0400862 WebView mainView = mTabControl.getCurrentWebView();
863 // Although we decided whether or not to animate based on the current
864 // scroll position, the scroll position may have changed since the
865 // fake title bar was displayed. Make sure it has the appropriate
866 // animation/lack thereof before removing.
867 params.windowAnimations = mainView != null && mainView.getScrollY() == 0
Leon Scroggins83932c72009-09-30 11:55:54 -0400868 ? 0 : R.style.TitleBar;
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400869 WindowManager manager
870 = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
Grace Kloba13f9ace2010-03-18 21:44:14 -0700871 manager.updateViewLayout(mFakeTitleBar, params);
872 manager.removeView(mFakeTitleBar);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400873 }
874
The Android Open Source Project0c908882009-03-03 19:32:16 -0800875 /**
Leon Scrogginsc6fa1102009-09-21 10:40:01 -0400876 * Special method for the fake title bar to call when displaying its context
877 * menu, since it is in its own Window, and its parent does not show a
878 * context menu.
879 */
880 /* package */ void showTitleBarContextMenu() {
Cary Clark65f4a3c2009-09-28 17:05:06 -0400881 if (null == mTitleBar.getParent()) {
882 return;
883 }
Leon Scrogginsc6fa1102009-09-21 10:40:01 -0400884 openContextMenu(mTitleBar);
885 }
886
Leon Scrogginsb2b19f52009-10-09 16:10:00 -0400887 @Override
888 public void onContextMenuClosed(Menu menu) {
889 super.onContextMenuClosed(menu);
890 if (mInLoad) {
891 showFakeTitleBar();
892 }
893 }
894
Leon Scrogginsc6fa1102009-09-21 10:40:01 -0400895 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -0800896 * onSaveInstanceState(Bundle map)
897 * onSaveInstanceState is called right before onStop(). The map contains
898 * the saved state.
899 */
Grace Kloba22ac16e2009-10-07 18:00:23 -0700900 @Override
901 protected void onSaveInstanceState(Bundle outState) {
Dave Bort31a6d1c2009-04-13 15:56:49 -0700902 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800903 Log.v(LOGTAG, "BrowserActivity.onSaveInstanceState: this=" + this);
904 }
905 // the default implementation requires each view to have an id. As the
906 // browser handles the state itself and it doesn't use id for the views,
907 // don't call the default implementation. Otherwise it will trigger the
908 // warning like this, "couldn't save which view has focus because the
909 // focused view XXX has no id".
910
911 // Save all the tabs
912 mTabControl.saveState(outState);
913 }
914
Grace Kloba22ac16e2009-10-07 18:00:23 -0700915 @Override
916 protected void onPause() {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800917 super.onPause();
918
919 if (mActivityInPause) {
920 Log.e(LOGTAG, "BrowserActivity is already paused.");
921 return;
922 }
923
Mike Reed7bfa63b2009-05-28 11:08:32 -0400924 mTabControl.pauseCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800925 mActivityInPause = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -0400926 if (mTabControl.getCurrentIndex() >= 0 && !pauseWebViewTimers()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800927 mWakeLock.acquire();
928 mHandler.sendMessageDelayed(mHandler
929 .obtainMessage(RELEASE_WAKELOCK), WAKELOCK_TIMEOUT);
930 }
931
Leon Scrogginsa2ab6a72009-09-11 11:49:52 -0400932 // FIXME: This removes the active tabs page and resets the menu to
933 // MAIN_MENU. A better solution might be to do this work in onNewIntent
934 // but then we would need to save it in onSaveInstanceState and restore
935 // it in onCreate/onRestoreInstanceState
936 if (mActiveTabsPage != null) {
937 removeActiveTabPage(true);
938 }
939
The Android Open Source Project0c908882009-03-03 19:32:16 -0800940 cancelStopToast();
941
942 // unregister network state listener
943 unregisterReceiver(mNetworkStateIntentReceiver);
944 WebView.disablePlatformNotifications();
Ben Murdocha4909cb2010-11-30 20:48:15 +0000945
946 if (mCustomView != null) {
947 mTabControl.getCurrentWebView().getWebChromeClient().onHideCustomView();
948 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800949 }
950
Grace Kloba22ac16e2009-10-07 18:00:23 -0700951 @Override
952 protected void onDestroy() {
Dave Bort31a6d1c2009-04-13 15:56:49 -0700953 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800954 Log.v(LOGTAG, "BrowserActivity.onDestroy: this=" + this);
955 }
956 super.onDestroy();
Grace Kloba0923d692009-09-23 21:37:25 -0700957
Leon Scroggins8d5fa432009-10-02 15:55:59 -0400958 if (mUploadMessage != null) {
959 mUploadMessage.onReceiveValue(null);
960 mUploadMessage = null;
961 }
962
Grace Kloba0923d692009-09-23 21:37:25 -0700963 if (mTabControl == null) return;
964
Grace Kloba1fc98a32009-10-21 13:23:08 -0700965 // Remove the fake title bar if it is there
966 hideFakeTitleBar();
967
The Android Open Source Project0c908882009-03-03 19:32:16 -0800968 // Remove the current tab and sub window
Grace Kloba22ac16e2009-10-07 18:00:23 -0700969 Tab t = mTabControl.getCurrentTab();
Patrick Scottfb5e77f2009-04-08 19:17:37 -0700970 if (t != null) {
971 dismissSubWindow(t);
972 removeTabFromContentView(t);
973 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800974 // Destroy all the tabs
975 mTabControl.destroy();
976 WebIconDatabase.getInstance().close();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800977
Grace Klobab4da0ad2009-05-14 14:45:40 -0700978 unregisterReceiver(mPackageInstallationReceiver);
Bjorn Bringerta7611812010-03-24 11:12:02 +0000979
980 // Stop watching the default geolocation permissions
981 mSystemAllowGeolocationOrigins.stop();
982 mSystemAllowGeolocationOrigins = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800983 }
984
985 @Override
986 public void onConfigurationChanged(Configuration newConfig) {
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400987 mConfigChanged = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800988 super.onConfigurationChanged(newConfig);
989
990 if (mPageInfoDialog != null) {
991 mPageInfoDialog.dismiss();
992 showPageInfo(
993 mPageInfoView,
Leon Scrogginsc7b92f82010-01-11 18:17:31 -0500994 mPageInfoFromShowSSLCertificateOnError);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800995 }
996 if (mSSLCertificateDialog != null) {
997 mSSLCertificateDialog.dismiss();
998 showSSLCertificate(
999 mSSLCertificateView);
1000 }
1001 if (mSSLCertificateOnErrorDialog != null) {
1002 mSSLCertificateOnErrorDialog.dismiss();
1003 showSSLCertificateOnError(
1004 mSSLCertificateOnErrorView,
1005 mSSLCertificateOnErrorHandler,
1006 mSSLCertificateOnErrorError);
1007 }
1008 if (mHttpAuthenticationDialog != null) {
1009 String title = ((TextView) mHttpAuthenticationDialog
1010 .findViewById(com.android.internal.R.id.alertTitle)).getText()
1011 .toString();
1012 String name = ((TextView) mHttpAuthenticationDialog
1013 .findViewById(R.id.username_edit)).getText().toString();
1014 String password = ((TextView) mHttpAuthenticationDialog
1015 .findViewById(R.id.password_edit)).getText().toString();
1016 int focusId = mHttpAuthenticationDialog.getCurrentFocus()
1017 .getId();
1018 mHttpAuthenticationDialog.dismiss();
1019 showHttpAuthentication(mHttpAuthHandler, null, null, title,
1020 name, password, focusId);
1021 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001022 }
1023
Grace Kloba22ac16e2009-10-07 18:00:23 -07001024 @Override
1025 public void onLowMemory() {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001026 super.onLowMemory();
1027 mTabControl.freeMemory();
1028 }
1029
Cary Clarkff4d92c2010-03-25 11:17:03 -04001030 private void resumeWebViewTimers() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001031 Tab tab = mTabControl.getCurrentTab();
Cary Clarkff4d92c2010-03-25 11:17:03 -04001032 if (tab == null) return; // monkey can trigger this
Grace Kloba22ac16e2009-10-07 18:00:23 -07001033 boolean inLoad = tab.inLoad();
1034 if ((!mActivityInPause && !inLoad) || (mActivityInPause && inLoad)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001035 CookieSyncManager.getInstance().startSync();
Grace Kloba22ac16e2009-10-07 18:00:23 -07001036 WebView w = tab.getWebView();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001037 if (w != null) {
1038 w.resumeTimers();
1039 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001040 }
1041 }
1042
Mike Reed7bfa63b2009-05-28 11:08:32 -04001043 private boolean pauseWebViewTimers() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001044 Tab tab = mTabControl.getCurrentTab();
1045 boolean inLoad = tab.inLoad();
1046 if (mActivityInPause && !inLoad) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001047 CookieSyncManager.getInstance().stopSync();
1048 WebView w = mTabControl.getCurrentWebView();
1049 if (w != null) {
1050 w.pauseTimers();
1051 }
1052 return true;
1053 } else {
1054 return false;
1055 }
1056 }
1057
The Android Open Source Project0c908882009-03-03 19:32:16 -08001058 // Open the icon database and retain all the icons for visited sites.
1059 private void retainIconsOnStartup() {
1060 final WebIconDatabase db = WebIconDatabase.getInstance();
1061 db.open(getDir("icons", 0).getPath());
Leon Scroggins2c0f6112010-03-12 18:09:39 -05001062 Cursor c = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001063 try {
Leon Scroggins2c0f6112010-03-12 18:09:39 -05001064 c = Browser.getAllBookmarks(mResolver);
1065 if (c.moveToFirst()) {
1066 int urlIndex = c.getColumnIndex(Browser.BookmarkColumns.URL);
1067 do {
1068 String url = c.getString(urlIndex);
1069 db.retainIconForPageUrl(url);
1070 } while (c.moveToNext());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001071 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001072 } catch (IllegalStateException e) {
1073 Log.e(LOGTAG, "retainIconsOnStartup", e);
Leon Scroggins2c0f6112010-03-12 18:09:39 -05001074 } finally {
1075 if (c!= null) c.close();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001076 }
1077 }
1078
1079 // Helper method for getting the top window.
1080 WebView getTopWindow() {
1081 return mTabControl.getCurrentTopWebView();
1082 }
1083
Grace Kloba22ac16e2009-10-07 18:00:23 -07001084 TabControl getTabControl() {
1085 return mTabControl;
1086 }
1087
The Android Open Source Project0c908882009-03-03 19:32:16 -08001088 @Override
1089 public boolean onCreateOptionsMenu(Menu menu) {
1090 super.onCreateOptionsMenu(menu);
1091
1092 MenuInflater inflater = getMenuInflater();
1093 inflater.inflate(R.menu.browser, menu);
1094 mMenu = menu;
1095 updateInLoadMenuItems();
1096 return true;
1097 }
1098
1099 /**
1100 * As the menu can be open when loading state changes
1101 * we must manually update the state of the stop/reload menu
1102 * item
1103 */
1104 private void updateInLoadMenuItems() {
1105 if (mMenu == null) {
1106 return;
1107 }
1108 MenuItem src = mInLoad ?
1109 mMenu.findItem(R.id.stop_menu_id):
1110 mMenu.findItem(R.id.reload_menu_id);
1111 MenuItem dest = mMenu.findItem(R.id.stop_reload_menu_id);
1112 dest.setIcon(src.getIcon());
1113 dest.setTitle(src.getTitle());
1114 }
1115
1116 @Override
1117 public boolean onContextItemSelected(MenuItem item) {
1118 // chording is not an issue with context menus, but we use the same
1119 // options selector, so set mCanChord to true so we can access them.
1120 mCanChord = true;
1121 int id = item.getItemId();
Leon Scroggins96afcb12009-12-10 12:35:56 -05001122 boolean result = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001123 switch (id) {
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001124 // For the context menu from the title bar
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001125 case R.id.title_bar_copy_page_url:
Leon Scroggins96afcb12009-12-10 12:35:56 -05001126 Tab currentTab = mTabControl.getCurrentTab();
1127 if (null == currentTab) {
1128 result = false;
1129 break;
1130 }
1131 WebView mainView = currentTab.getWebView();
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001132 if (null == mainView) {
Leon Scroggins96afcb12009-12-10 12:35:56 -05001133 result = false;
1134 break;
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001135 }
Leon Scroggins96afcb12009-12-10 12:35:56 -05001136 copy(mainView.getUrl());
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001137 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001138 // -- Browser context menu
1139 case R.id.open_context_menu_id:
1140 case R.id.open_newtab_context_menu_id:
1141 case R.id.bookmark_context_menu_id:
1142 case R.id.save_link_context_menu_id:
1143 case R.id.share_link_context_menu_id:
1144 case R.id.copy_link_context_menu_id:
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001145 final WebView webView = getTopWindow();
1146 if (null == webView) {
Leon Scroggins96afcb12009-12-10 12:35:56 -05001147 result = false;
1148 break;
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001149 }
1150 final HashMap hrefMap = new HashMap();
1151 hrefMap.put("webview", webView);
1152 final Message msg = mHandler.obtainMessage(
1153 FOCUS_NODE_HREF, id, 0, hrefMap);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001154 webView.requestFocusNodeHref(msg);
1155 break;
1156
1157 default:
1158 // For other context menus
Leon Scroggins96afcb12009-12-10 12:35:56 -05001159 result = onOptionsItemSelected(item);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001160 }
1161 mCanChord = false;
Leon Scroggins96afcb12009-12-10 12:35:56 -05001162 return result;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001163 }
1164
1165 private Bundle createGoogleSearchSourceBundle(String source) {
1166 Bundle bundle = new Bundle();
Bjorn Bringert10d1cca2010-02-10 14:22:12 +00001167 bundle.putString(Search.SOURCE, source);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001168 return bundle;
1169 }
1170
Leon Scroggins8ad29922010-02-16 12:33:55 -05001171 /* package */ void editUrl() {
Leon Scroggins68579392009-09-15 15:31:54 -04001172 if (mOptionsMenuOpen) closeOptionsMenu();
Leon Scroggins5bbe9802009-07-31 13:10:55 -04001173 String url = (getTopWindow() == null) ? null : getTopWindow().getUrl();
Grace Kloba83f47342009-07-20 10:44:31 -07001174 startSearch(mSettings.getHomePage().equals(url) ? null : url, true,
Leon Scroggins8ad29922010-02-16 12:33:55 -05001175 null, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001176 }
1177
Leon Scroggins8ad29922010-02-16 12:33:55 -05001178 /**
1179 * Overriding this to insert a local information bundle
1180 */
The Android Open Source Project0c908882009-03-03 19:32:16 -08001181 @Override
1182 public void startSearch(String initialQuery, boolean selectInitialQuery,
1183 Bundle appSearchData, boolean globalSearch) {
1184 if (appSearchData == null) {
1185 appSearchData = createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_TYPE);
1186 }
Leon Scroggins III430057d2010-09-14 10:57:37 -04001187
1188 SearchEngine searchEngine = mSettings.getSearchEngine();
1189 if (searchEngine != null && !searchEngine.supportsVoiceSearch()) {
1190 appSearchData.putBoolean(SearchManager.DISABLE_VOICE_SEARCH, true);
1191 }
1192
The Android Open Source Project0c908882009-03-03 19:32:16 -08001193 super.startSearch(initialQuery, selectInitialQuery, appSearchData, globalSearch);
1194 }
1195
Leon Scroggins1f005d32009-08-10 17:36:42 -04001196 /**
1197 * Switch tabs. Called by the TitleBarSet when sliding the title bar
1198 * results in changing tabs.
Leon Scroggins160a7e72009-08-14 18:28:01 -04001199 * @param index Index of the tab to change to, as defined by
1200 * mTabControl.getTabIndex(Tab t).
1201 * @return boolean True if we successfully switched to a different tab. If
1202 * the indexth tab is null, or if that tab is the same as
1203 * the current one, return false.
Leon Scroggins1f005d32009-08-10 17:36:42 -04001204 */
Leon Scroggins160a7e72009-08-14 18:28:01 -04001205 /* package */ boolean switchToTab(int index) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001206 Tab tab = mTabControl.getTab(index);
1207 Tab currentTab = mTabControl.getCurrentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04001208 if (tab == null || tab == currentTab) {
Leon Scroggins160a7e72009-08-14 18:28:01 -04001209 return false;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001210 }
1211 if (currentTab != null) {
1212 // currentTab may be null if it was just removed. In that case,
1213 // we do not need to remove it
1214 removeTabFromContentView(currentTab);
1215 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001216 mTabControl.setCurrentTab(tab);
1217 attachTabToContentView(tab);
Grace Klobaeb6eef42009-09-15 17:56:32 -07001218 resetTitleIconAndProgress();
1219 updateLockIconToLatest();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001220 return true;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001221 }
1222
Grace Kloba22ac16e2009-10-07 18:00:23 -07001223 /* package */ Tab openTabToHomePage() {
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001224 return openTabAndShow(mSettings.getHomePage(), false, null);
1225 }
1226
Leon Scroggins1f005d32009-08-10 17:36:42 -04001227 /* package */ void closeCurrentWindow() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001228 final Tab current = mTabControl.getCurrentTab();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001229 if (mTabControl.getTabCount() == 1) {
Leon Scroggins30444232009-09-04 18:36:20 -04001230 // This is the last tab. Open a new one, with the home
1231 // page and close the current one.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001232 openTabToHomePage();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001233 closeTab(current);
Leon Scroggins160a7e72009-08-14 18:28:01 -04001234 return;
1235 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07001236 final Tab parent = current.getParentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04001237 int indexToShow = -1;
1238 if (parent != null) {
1239 indexToShow = mTabControl.getTabIndex(parent);
1240 } else {
Leon Scroggins160a7e72009-08-14 18:28:01 -04001241 final int currentIndex = mTabControl.getCurrentIndex();
1242 // Try to move to the tab to the right
1243 indexToShow = currentIndex + 1;
1244 if (indexToShow > mTabControl.getTabCount() - 1) {
1245 // Try to move to the tab to the left
1246 indexToShow = currentIndex - 1;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001247 }
1248 }
Leon Scroggins160a7e72009-08-14 18:28:01 -04001249 if (switchToTab(indexToShow)) {
1250 // Close window
1251 closeTab(current);
1252 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001253 }
1254
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001255 private ActiveTabsPage mActiveTabsPage;
1256
1257 /**
1258 * Remove the active tabs page.
1259 * @param needToAttach If true, the active tabs page did not attach a tab
1260 * to the content view, so we need to do that here.
1261 */
1262 /* package */ void removeActiveTabPage(boolean needToAttach) {
1263 mContentView.removeView(mActiveTabsPage);
1264 mActiveTabsPage = null;
1265 mMenuState = R.id.MAIN_MENU;
1266 if (needToAttach) {
1267 attachTabToContentView(mTabControl.getCurrentTab());
1268 }
1269 getTopWindow().requestFocus();
1270 }
1271
Cary Clark2c326e62010-08-19 18:40:57 -04001272 private WebView showDialog(WebDialog dialog) {
Cary Clark2c326e62010-08-19 18:40:57 -04001273 Tab tab = mTabControl.getCurrentTab();
1274 if (tab.getSubWebView() == null) {
1275 // If the find or select is being performed on the main webview,
1276 // remove the embedded title bar.
1277 WebView mainView = tab.getWebView();
1278 if (mainView != null) {
1279 mainView.setEmbeddedTitleBar(null);
1280 }
1281 }
1282 hideFakeTitleBar();
1283 mMenuState = EMPTY_MENU;
1284 return tab.showDialog(dialog);
1285 }
1286
The Android Open Source Project0c908882009-03-03 19:32:16 -08001287 @Override
1288 public boolean onOptionsItemSelected(MenuItem item) {
1289 if (!mCanChord) {
1290 // The user has already fired a shortcut with this hold down of the
1291 // menu key.
1292 return false;
1293 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001294 if (null == getTopWindow()) {
Leon Scroggins0d7ae0e2009-06-05 11:04:45 -04001295 return false;
1296 }
Grace Kloba6ee9c492009-07-13 10:04:34 -07001297 if (mMenuIsDown) {
1298 // The shortcut action consumes the MENU. Even if it is still down,
1299 // it won't trigger the next shortcut action. In the case of the
1300 // shortcut action triggering a new activity, like Bookmarks, we
1301 // won't get onKeyUp for MENU. So it is important to reset it here.
1302 mMenuIsDown = false;
1303 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001304 switch (item.getItemId()) {
1305 // -- Main menu
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001306 case R.id.new_tab_menu_id:
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001307 openTabToHomePage();
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001308 break;
1309
Leon Scroggins64b80f32009-08-07 12:03:34 -04001310 case R.id.goto_menu_id:
Leon Scroggins8ad29922010-02-16 12:33:55 -05001311 editUrl();
Leon Scrogginsb3a5bed2009-09-28 11:21:56 -04001312 break;
1313
1314 case R.id.bookmarks_menu_id:
Leon Scroggins30444232009-09-04 18:36:20 -04001315 bookmarksOrHistoryPicker(false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001316 break;
1317
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001318 case R.id.active_tabs_menu_id:
1319 mActiveTabsPage = new ActiveTabsPage(this, mTabControl);
1320 removeTabFromContentView(mTabControl.getCurrentTab());
Leon Scroggins43de6162009-09-14 19:59:58 -04001321 hideFakeTitleBar();
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001322 mContentView.addView(mActiveTabsPage, COVER_SCREEN_PARAMS);
1323 mActiveTabsPage.requestFocus();
1324 mMenuState = EMPTY_MENU;
1325 break;
1326
Leon Scroggins1f005d32009-08-10 17:36:42 -04001327 case R.id.add_bookmark_menu_id:
1328 Intent i = new Intent(BrowserActivity.this,
1329 AddBookmarkPage.class);
1330 WebView w = getTopWindow();
1331 i.putExtra("url", w.getUrl());
1332 i.putExtra("title", w.getTitle());
Grace Kloba83cdb2c2009-09-16 00:48:57 -07001333 i.putExtra("touch_icon_url", w.getTouchIconUrl());
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01001334 i.putExtra("thumbnail", createScreenshot(w));
Leon Scroggins1f005d32009-08-10 17:36:42 -04001335 startActivity(i);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001336 break;
1337
1338 case R.id.stop_reload_menu_id:
1339 if (mInLoad) {
1340 stopLoading();
1341 } else {
1342 getTopWindow().reload();
1343 }
1344 break;
1345
1346 case R.id.back_menu_id:
1347 getTopWindow().goBack();
1348 break;
1349
1350 case R.id.forward_menu_id:
1351 getTopWindow().goForward();
1352 break;
1353
1354 case R.id.close_menu_id:
1355 // Close the subwindow if it exists.
1356 if (mTabControl.getCurrentSubWindow() != null) {
1357 dismissSubWindow(mTabControl.getCurrentTab());
1358 break;
1359 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001360 closeCurrentWindow();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001361 break;
1362
1363 case R.id.homepage_menu_id:
Grace Kloba22ac16e2009-10-07 18:00:23 -07001364 Tab current = mTabControl.getCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001365 if (current != null) {
1366 dismissSubWindow(current);
Leon Scroggins92472e82010-02-17 16:32:28 -05001367 loadUrl(current.getWebView(), mSettings.getHomePage());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001368 }
1369 break;
1370
1371 case R.id.preferences_menu_id:
1372 Intent intent = new Intent(this,
1373 BrowserPreferencesPage.class);
Leon Scrogginsd5304942009-12-10 16:11:39 -05001374 intent.putExtra(BrowserPreferencesPage.CURRENT_PAGE,
1375 getTopWindow().getUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001376 startActivityForResult(intent, PREFERENCES_PAGE);
1377 break;
1378
1379 case R.id.find_menu_id:
Cary Clark2c326e62010-08-19 18:40:57 -04001380 showFindDialog();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001381 break;
1382
1383 case R.id.select_text_id:
Cary Clark5feb8ad2010-09-21 14:28:49 -04001384 if (true) {
1385 Tab currentTab = mTabControl.getCurrentTab();
1386 if (currentTab != null) {
1387 currentTab.getWebView().setUpSelect();
1388 }
1389 } else {
1390 showSelectDialog();
1391 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001392 break;
Cary Clark2c326e62010-08-19 18:40:57 -04001393
The Android Open Source Project0c908882009-03-03 19:32:16 -08001394 case R.id.page_info_menu_id:
1395 showPageInfo(mTabControl.getCurrentTab(), false);
1396 break;
1397
1398 case R.id.classic_history_menu_id:
Leon Scroggins30444232009-09-04 18:36:20 -04001399 bookmarksOrHistoryPicker(true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001400 break;
1401
Leon Scroggins96afcb12009-12-10 12:35:56 -05001402 case R.id.title_bar_share_page_url:
The Android Open Source Project0c908882009-03-03 19:32:16 -08001403 case R.id.share_page_menu_id:
Leon Scroggins96afcb12009-12-10 12:35:56 -05001404 Tab currentTab = mTabControl.getCurrentTab();
1405 if (null == currentTab) {
1406 mCanChord = false;
1407 return false;
1408 }
1409 currentTab.populatePickerData();
1410 sharePage(this, currentTab.getTitle(),
1411 currentTab.getUrl(), currentTab.getFavicon(),
1412 createScreenshot(currentTab.getWebView()));
The Android Open Source Project0c908882009-03-03 19:32:16 -08001413 break;
1414
1415 case R.id.dump_nav_menu_id:
1416 getTopWindow().debugDump();
1417 break;
1418
Andrei Popescu7a8b88b2010-02-02 00:30:38 +00001419 case R.id.dump_counters_menu_id:
1420 getTopWindow().dumpV8Counters();
1421 break;
1422
The Android Open Source Project0c908882009-03-03 19:32:16 -08001423 case R.id.zoom_in_menu_id:
1424 getTopWindow().zoomIn();
1425 break;
1426
1427 case R.id.zoom_out_menu_id:
1428 getTopWindow().zoomOut();
1429 break;
1430
1431 case R.id.view_downloads_menu_id:
Leon Scroggins IIIa682a3c2010-09-27 12:32:40 -04001432 viewDownloads();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001433 break;
1434
The Android Open Source Project0c908882009-03-03 19:32:16 -08001435 case R.id.window_one_menu_id:
1436 case R.id.window_two_menu_id:
1437 case R.id.window_three_menu_id:
1438 case R.id.window_four_menu_id:
1439 case R.id.window_five_menu_id:
1440 case R.id.window_six_menu_id:
1441 case R.id.window_seven_menu_id:
1442 case R.id.window_eight_menu_id:
1443 {
1444 int menuid = item.getItemId();
1445 for (int id = 0; id < WINDOW_SHORTCUT_ID_ARRAY.length; id++) {
1446 if (WINDOW_SHORTCUT_ID_ARRAY[id] == menuid) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001447 Tab desiredTab = mTabControl.getTab(id);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001448 if (desiredTab != null &&
1449 desiredTab != mTabControl.getCurrentTab()) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001450 switchToTab(id);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001451 }
1452 break;
1453 }
1454 }
1455 }
1456 break;
1457
1458 default:
1459 if (!super.onOptionsItemSelected(item)) {
1460 return false;
1461 }
1462 // Otherwise fall through.
1463 }
1464 mCanChord = false;
1465 return true;
1466 }
1467
Cary Clark2c326e62010-08-19 18:40:57 -04001468 private boolean dialogIsUp() {
1469 return null != mFindDialog && mFindDialog.isVisible() ||
1470 null != mSelectDialog && mSelectDialog.isVisible();
1471 }
1472
1473 private boolean closeDialog(WebDialog dialog) {
1474 if (null == dialog || !dialog.isVisible()) return false;
1475 Tab currentTab = mTabControl.getCurrentTab();
1476 currentTab.closeDialog(dialog);
1477 dialog.dismiss();
1478 return true;
1479 }
1480
1481 /*
1482 * Remove the find dialog or select dialog.
1483 */
1484 public void closeDialogs() {
1485 if (!(closeDialog(mFindDialog) || closeDialog(mSelectDialog))) return;
1486 // If the Find was being performed in the main WebView, replace the
1487 // embedded title bar.
1488 Tab currentTab = mTabControl.getCurrentTab();
1489 if (currentTab.getSubWebView() == null) {
1490 WebView mainView = currentTab.getWebView();
1491 if (mainView != null) {
1492 mainView.setEmbeddedTitleBar(mTitleBar);
1493 }
1494 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001495 mMenuState = R.id.MAIN_MENU;
Cary Clark2c326e62010-08-19 18:40:57 -04001496 if (mInLoad) {
1497 // The title bar was hidden, because otherwise it would cover up the
1498 // find or select dialog. Now that the dialog has been removed,
1499 // show the fake title bar once again.
1500 showFakeTitleBar();
1501 }
1502 }
1503
1504 public void showFindDialog() {
1505 if (null == mFindDialog) {
1506 mFindDialog = new FindDialog(this);
1507 }
1508 showDialog(mFindDialog).setFindIsUp(true);
1509 }
1510
1511 public void setFindDialogText(String text) {
1512 mFindDialog.setText(text);
1513 }
1514
1515 public void showSelectDialog() {
1516 if (null == mSelectDialog) {
1517 mSelectDialog = new SelectDialog(this);
1518 }
1519 showDialog(mSelectDialog).setUpSelect();
1520 mSelectDialog.hideSoftInput();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001521 }
1522
Grace Kloba22ac16e2009-10-07 18:00:23 -07001523 @Override
1524 public boolean onPrepareOptionsMenu(Menu menu) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001525 // This happens when the user begins to hold down the menu key, so
1526 // allow them to chord to get a shortcut.
1527 mCanChord = true;
1528 // Note: setVisible will decide whether an item is visible; while
1529 // setEnabled() will decide whether an item is enabled, which also means
1530 // whether the matching shortcut key will function.
1531 super.onPrepareOptionsMenu(menu);
1532 switch (mMenuState) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001533 case EMPTY_MENU:
1534 if (mCurrentMenuState != mMenuState) {
1535 menu.setGroupVisible(R.id.MAIN_MENU, false);
1536 menu.setGroupEnabled(R.id.MAIN_MENU, false);
1537 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001538 }
1539 break;
1540 default:
1541 if (mCurrentMenuState != mMenuState) {
1542 menu.setGroupVisible(R.id.MAIN_MENU, true);
1543 menu.setGroupEnabled(R.id.MAIN_MENU, true);
1544 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001545 }
1546 final WebView w = getTopWindow();
1547 boolean canGoBack = false;
1548 boolean canGoForward = false;
1549 boolean isHome = false;
1550 if (w != null) {
1551 canGoBack = w.canGoBack();
1552 canGoForward = w.canGoForward();
1553 isHome = mSettings.getHomePage().equals(w.getUrl());
1554 }
1555 final MenuItem back = menu.findItem(R.id.back_menu_id);
1556 back.setEnabled(canGoBack);
1557
1558 final MenuItem home = menu.findItem(R.id.homepage_menu_id);
1559 home.setEnabled(!isHome);
1560
1561 menu.findItem(R.id.forward_menu_id)
1562 .setEnabled(canGoForward);
1563
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001564 menu.findItem(R.id.new_tab_menu_id).setEnabled(
Grace Kloba22ac16e2009-10-07 18:00:23 -07001565 mTabControl.canCreateNewTab());
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001566
The Android Open Source Project0c908882009-03-03 19:32:16 -08001567 // decide whether to show the share link option
1568 PackageManager pm = getPackageManager();
1569 Intent send = new Intent(Intent.ACTION_SEND);
1570 send.setType("text/plain");
1571 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1572 menu.findItem(R.id.share_page_menu_id).setVisible(ri != null);
1573
The Android Open Source Project0c908882009-03-03 19:32:16 -08001574 boolean isNavDump = mSettings.isNavDump();
1575 final MenuItem nav = menu.findItem(R.id.dump_nav_menu_id);
1576 nav.setVisible(isNavDump);
1577 nav.setEnabled(isNavDump);
Andrei Popescu7a8b88b2010-02-02 00:30:38 +00001578
1579 boolean showDebugSettings = mSettings.showDebugSettings();
1580 final MenuItem counter = menu.findItem(R.id.dump_counters_menu_id);
1581 counter.setVisible(showDebugSettings);
1582 counter.setEnabled(showDebugSettings);
1583
The Android Open Source Project0c908882009-03-03 19:32:16 -08001584 break;
1585 }
1586 mCurrentMenuState = mMenuState;
1587 return true;
1588 }
1589
1590 @Override
1591 public void onCreateContextMenu(ContextMenu menu, View v,
1592 ContextMenuInfo menuInfo) {
Leon Scroggins4e9f89b2010-02-22 16:54:14 -05001593 if (v instanceof TitleBar) {
1594 return;
1595 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001596 WebView webview = (WebView) v;
1597 WebView.HitTestResult result = webview.getHitTestResult();
1598 if (result == null) {
1599 return;
1600 }
1601
1602 int type = result.getType();
1603 if (type == WebView.HitTestResult.UNKNOWN_TYPE) {
1604 Log.w(LOGTAG,
1605 "We should not show context menu when nothing is touched");
1606 return;
1607 }
1608 if (type == WebView.HitTestResult.EDIT_TEXT_TYPE) {
1609 // let TextView handles context menu
1610 return;
1611 }
1612
1613 // Note, http://b/issue?id=1106666 is requesting that
1614 // an inflated menu can be used again. This is not available
1615 // yet, so inflate each time (yuk!)
1616 MenuInflater inflater = getMenuInflater();
1617 inflater.inflate(R.menu.browsercontext, menu);
1618
1619 // Show the correct menu group
1620 String extra = result.getExtra();
1621 menu.setGroupVisible(R.id.PHONE_MENU,
1622 type == WebView.HitTestResult.PHONE_TYPE);
1623 menu.setGroupVisible(R.id.EMAIL_MENU,
1624 type == WebView.HitTestResult.EMAIL_TYPE);
1625 menu.setGroupVisible(R.id.GEO_MENU,
1626 type == WebView.HitTestResult.GEO_TYPE);
1627 menu.setGroupVisible(R.id.IMAGE_MENU,
1628 type == WebView.HitTestResult.IMAGE_TYPE
1629 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1630 menu.setGroupVisible(R.id.ANCHOR_MENU,
1631 type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1632 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1633
1634 // Setup custom handling depending on the type
1635 switch (type) {
1636 case WebView.HitTestResult.PHONE_TYPE:
1637 menu.setHeaderTitle(Uri.decode(extra));
1638 menu.findItem(R.id.dial_context_menu_id).setIntent(
1639 new Intent(Intent.ACTION_VIEW, Uri
1640 .parse(WebView.SCHEME_TEL + extra)));
1641 Intent addIntent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
1642 addIntent.putExtra(Insert.PHONE, Uri.decode(extra));
Cary Clark5e335a32009-09-22 14:53:11 -04001643 addIntent.setType(ContactsContract.Contacts.CONTENT_ITEM_TYPE);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001644 menu.findItem(R.id.add_contact_context_menu_id).setIntent(
1645 addIntent);
1646 menu.findItem(R.id.copy_phone_context_menu_id).setOnMenuItemClickListener(
1647 new Copy(extra));
1648 break;
1649
1650 case WebView.HitTestResult.EMAIL_TYPE:
1651 menu.setHeaderTitle(extra);
1652 menu.findItem(R.id.email_context_menu_id).setIntent(
1653 new Intent(Intent.ACTION_VIEW, Uri
1654 .parse(WebView.SCHEME_MAILTO + extra)));
1655 menu.findItem(R.id.copy_mail_context_menu_id).setOnMenuItemClickListener(
1656 new Copy(extra));
1657 break;
1658
1659 case WebView.HitTestResult.GEO_TYPE:
1660 menu.setHeaderTitle(extra);
1661 menu.findItem(R.id.map_context_menu_id).setIntent(
1662 new Intent(Intent.ACTION_VIEW, Uri
1663 .parse(WebView.SCHEME_GEO
1664 + URLEncoder.encode(extra))));
1665 menu.findItem(R.id.copy_geo_context_menu_id).setOnMenuItemClickListener(
1666 new Copy(extra));
1667 break;
1668
1669 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1670 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
1671 TextView titleView = (TextView) LayoutInflater.from(this)
1672 .inflate(android.R.layout.browser_link_context_header,
1673 null);
1674 titleView.setText(extra);
1675 menu.setHeaderView(titleView);
1676 // decide whether to show the open link in new tab option
1677 menu.findItem(R.id.open_newtab_context_menu_id).setVisible(
Grace Kloba22ac16e2009-10-07 18:00:23 -07001678 mTabControl.canCreateNewTab());
Ben Murdochde353622009-10-12 10:29:00 +01001679 menu.findItem(R.id.bookmark_context_menu_id).setVisible(
1680 Bookmarks.urlHasAcceptableScheme(extra));
The Android Open Source Project0c908882009-03-03 19:32:16 -08001681 PackageManager pm = getPackageManager();
1682 Intent send = new Intent(Intent.ACTION_SEND);
1683 send.setType("text/plain");
1684 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1685 menu.findItem(R.id.share_link_context_menu_id).setVisible(ri != null);
1686 if (type == WebView.HitTestResult.SRC_ANCHOR_TYPE) {
1687 break;
1688 }
1689 // otherwise fall through to handle image part
1690 case WebView.HitTestResult.IMAGE_TYPE:
1691 if (type == WebView.HitTestResult.IMAGE_TYPE) {
1692 menu.setHeaderTitle(extra);
1693 }
1694 menu.findItem(R.id.view_image_context_menu_id).setIntent(
1695 new Intent(Intent.ACTION_VIEW, Uri.parse(extra)));
1696 menu.findItem(R.id.download_context_menu_id).
1697 setOnMenuItemClickListener(new Download(extra));
Ben Murdoch4f75ba22009-10-27 11:48:28 +00001698 menu.findItem(R.id.set_wallpaper_context_menu_id).
1699 setOnMenuItemClickListener(new SetAsWallpaper(extra));
The Android Open Source Project0c908882009-03-03 19:32:16 -08001700 break;
1701
1702 default:
1703 Log.w(LOGTAG, "We should not get here.");
1704 break;
1705 }
Leon Scrogginsb2b19f52009-10-09 16:10:00 -04001706 hideFakeTitleBar();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001707 }
1708
The Android Open Source Project0c908882009-03-03 19:32:16 -08001709 // Attach the given tab to the content view.
Grace Klobac928c302009-09-17 11:51:21 -07001710 // this should only be called for the current tab.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001711 private void attachTabToContentView(Tab t) {
Steve Block2bc69912009-07-30 14:45:13 +01001712 // Attach the container that contains the main WebView and any other UI
1713 // associated with the tab.
Patrick Scottd0119532009-09-17 08:00:31 -04001714 t.attachTabToContentView(mContentView);
Ben Murdochbff2d602009-07-01 20:19:05 +01001715
1716 if (mShouldShowErrorConsole) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001717 ErrorConsoleView errorConsole = t.getErrorConsole(true);
Ben Murdochbff2d602009-07-01 20:19:05 +01001718 if (errorConsole.numberOfErrors() == 0) {
1719 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
1720 } else {
1721 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
1722 }
1723
1724 mErrorConsoleContainer.addView(errorConsole,
Romain Guy15b8ec62010-01-08 15:06:43 -08001725 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
Ben Murdochbff2d602009-07-01 20:19:05 +01001726 ViewGroup.LayoutParams.WRAP_CONTENT));
1727 }
1728
Leon Scroggins39ab28e2009-09-02 21:20:30 -04001729 WebView view = t.getWebView();
Leon Scroggins55a5bc22009-09-04 17:00:08 -04001730 view.setEmbeddedTitleBar(mTitleBar);
Leon Scroggins58d56c62010-01-28 15:12:40 -05001731 if (t.isInVoiceSearchMode()) {
1732 showVoiceTitleBar(t.getVoiceDisplayTitle());
1733 } else {
1734 revertVoiceTitleBar();
1735 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001736 // Request focus on the top window.
1737 t.getTopWindow().requestFocus();
1738 }
1739
1740 // Attach a sub window to the main WebView of the given tab.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001741 void attachSubWindow(Tab t) {
Patrick Scottd0119532009-09-17 08:00:31 -04001742 t.attachSubWindow(mContentView);
1743 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001744 }
1745
1746 // Remove the given tab from the content view.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001747 private void removeTabFromContentView(Tab t) {
Steve Block2bc69912009-07-30 14:45:13 +01001748 // Remove the container that contains the main WebView.
Patrick Scottd0119532009-09-17 08:00:31 -04001749 t.removeTabFromContentView(mContentView);
Ben Murdochbff2d602009-07-01 20:19:05 +01001750
Grace Kloba22ac16e2009-10-07 18:00:23 -07001751 ErrorConsoleView errorConsole = t.getErrorConsole(false);
1752 if (errorConsole != null) {
1753 mErrorConsoleContainer.removeView(errorConsole);
Ben Murdochbff2d602009-07-01 20:19:05 +01001754 }
1755
Leon Scroggins39ab28e2009-09-02 21:20:30 -04001756 WebView view = t.getWebView();
Leon Scrogginsbb85b902009-09-14 19:27:20 -04001757 if (view != null) {
1758 view.setEmbeddedTitleBar(null);
1759 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001760 }
1761
1762 // Remove the sub window if it exists. Also called by TabControl when the
1763 // user clicks the 'X' to dismiss a sub window.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001764 /* package */ void dismissSubWindow(Tab t) {
Patrick Scottd0119532009-09-17 08:00:31 -04001765 t.removeSubWindow(mContentView);
Grace Kloba22ac16e2009-10-07 18:00:23 -07001766 // dismiss the subwindow. This will destroy the WebView.
1767 t.dismissSubWindow();
Patrick Scottd0119532009-09-17 08:00:31 -04001768 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001769 }
1770
Leon Scroggins1f005d32009-08-10 17:36:42 -04001771 // A wrapper function of {@link #openTabAndShow(UrlData, boolean, String)}
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07001772 // that accepts url as string.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001773 private Tab openTabAndShow(String url, boolean closeOnExit, String appId) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001774 return openTabAndShow(new UrlData(url), closeOnExit, appId);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001775 }
1776
1777 // This method does a ton of stuff. It will attempt to create a new tab
1778 // if we haven't reached MAX_TABS. Otherwise it uses the current tab. If
Leon Scroggins1f005d32009-08-10 17:36:42 -04001779 // url isn't null, it will load the given url.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001780 /* package */Tab openTabAndShow(UrlData urlData, boolean closeOnExit,
1781 String appId) {
1782 final Tab currentTab = mTabControl.getCurrentTab();
1783 if (mTabControl.canCreateNewTab()) {
1784 final Tab tab = mTabControl.createNewTab(closeOnExit, appId,
1785 urlData.mUrl);
Leon Scroggins1f005d32009-08-10 17:36:42 -04001786 WebView webview = tab.getWebView();
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001787 // If the last tab was removed from the active tabs page, currentTab
1788 // will be null.
1789 if (currentTab != null) {
1790 removeTabFromContentView(currentTab);
1791 }
Patrick Scott8bbd69f2009-08-14 13:35:53 -04001792 // We must set the new tab as the current tab to reflect the old
1793 // animation behavior.
1794 mTabControl.setCurrentTab(tab);
Grace Klobaeb6eef42009-09-15 17:56:32 -07001795 attachTabToContentView(tab);
Leon Scroggins160a7e72009-08-14 18:28:01 -04001796 if (!urlData.isEmpty()) {
Patrick Scott9d53da02010-02-19 10:19:01 -05001797 loadUrlDataIn(tab, urlData);
Leon Scroggins1f005d32009-08-10 17:36:42 -04001798 }
1799 return tab;
1800 } else {
1801 // Get rid of the subwindow if it exists
1802 dismissSubWindow(currentTab);
1803 if (!urlData.isEmpty()) {
1804 // Load the given url.
Patrick Scott9d53da02010-02-19 10:19:01 -05001805 loadUrlDataIn(currentTab, urlData);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001806 }
Leon Scroggins58d56c62010-01-28 15:12:40 -05001807 return currentTab;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001808 }
1809 }
1810
Grace Kloba22ac16e2009-10-07 18:00:23 -07001811 private Tab openTab(String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001812 if (mSettings.openInBackground()) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001813 Tab t = mTabControl.createNewTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001814 if (t != null) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001815 WebView view = t.getWebView();
Leon Scroggins92472e82010-02-17 16:32:28 -05001816 loadUrl(view, url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001817 }
Grace Klobac9181842009-04-14 08:53:22 -07001818 return t;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001819 } else {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001820 return openTabAndShow(url, false, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001821 }
1822 }
1823
1824 private class Copy implements OnMenuItemClickListener {
1825 private CharSequence mText;
1826
1827 public boolean onMenuItemClick(MenuItem item) {
1828 copy(mText);
1829 return true;
1830 }
1831
1832 public Copy(CharSequence toCopy) {
1833 mText = toCopy;
1834 }
1835 }
1836
1837 private class Download implements OnMenuItemClickListener {
1838 private String mText;
1839
1840 public boolean onMenuItemClick(MenuItem item) {
1841 onDownloadStartNoStream(mText, null, null, null, -1);
1842 return true;
1843 }
1844
1845 public Download(String toDownload) {
1846 mText = toDownload;
1847 }
1848 }
1849
Ben Murdoch4f75ba22009-10-27 11:48:28 +00001850 private class SetAsWallpaper extends Thread implements
1851 OnMenuItemClickListener, DialogInterface.OnCancelListener {
1852 private URL mUrl;
1853 private ProgressDialog mWallpaperProgress;
1854 private boolean mCanceled = false;
1855
1856 public SetAsWallpaper(String url) {
1857 try {
1858 mUrl = new URL(url);
1859 } catch (MalformedURLException e) {
1860 mUrl = null;
1861 }
1862 }
1863
1864 public void onCancel(DialogInterface dialog) {
1865 mCanceled = true;
1866 }
1867
1868 public boolean onMenuItemClick(MenuItem item) {
1869 if (mUrl != null) {
1870 // The user may have tried to set a image with a large file size as their
1871 // background so it may take a few moments to perform the operation. Display
1872 // a progress spinner while it is working.
1873 mWallpaperProgress = new ProgressDialog(BrowserActivity.this);
1874 mWallpaperProgress.setIndeterminate(true);
1875 mWallpaperProgress.setMessage(getText(R.string.progress_dialog_setting_wallpaper));
1876 mWallpaperProgress.setCancelable(true);
1877 mWallpaperProgress.setOnCancelListener(this);
1878 mWallpaperProgress.show();
1879 start();
1880 }
1881 return true;
1882 }
1883
1884 public void run() {
1885 Drawable oldWallpaper = BrowserActivity.this.getWallpaper();
1886 try {
1887 // TODO: This will cause the resource to be downloaded again, when we
1888 // should in most cases be able to grab it from the cache. To fix this
1889 // we should query WebCore to see if we can access a cached version and
1890 // instead open an input stream on that. This pattern could also be used
1891 // in the download manager where the same problem exists.
1892 InputStream inputstream = mUrl.openStream();
1893 if (inputstream != null) {
1894 setWallpaper(inputstream);
1895 }
1896 } catch (IOException e) {
1897 Log.e(LOGTAG, "Unable to set new wallpaper");
1898 // Act as though the user canceled the operation so we try to
1899 // restore the old wallpaper.
1900 mCanceled = true;
1901 }
1902
1903 if (mCanceled) {
1904 // Restore the old wallpaper if the user cancelled whilst we were setting
1905 // the new wallpaper.
1906 int width = oldWallpaper.getIntrinsicWidth();
1907 int height = oldWallpaper.getIntrinsicHeight();
1908 Bitmap bm = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
1909 Canvas canvas = new Canvas(bm);
1910 oldWallpaper.setBounds(0, 0, width, height);
1911 oldWallpaper.draw(canvas);
1912 try {
1913 setWallpaper(bm);
1914 } catch (IOException e) {
1915 Log.e(LOGTAG, "Unable to restore old wallpaper.");
1916 }
1917 mCanceled = false;
1918 }
1919
1920 if (mWallpaperProgress.isShowing()) {
1921 mWallpaperProgress.dismiss();
1922 }
1923 }
1924 }
1925
The Android Open Source Project0c908882009-03-03 19:32:16 -08001926 private void copy(CharSequence text) {
1927 try {
1928 IClipboard clip = IClipboard.Stub.asInterface(ServiceManager.getService("clipboard"));
1929 if (clip != null) {
1930 clip.setClipboardText(text);
1931 }
1932 } catch (android.os.RemoteException e) {
1933 Log.e(LOGTAG, "Copy failed", e);
1934 }
1935 }
1936
1937 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08001938 * Resets the browser title-view to whatever it must be
1939 * (for example, if we had a loading error)
1940 * When we have a new page, we call resetTitle, when we
1941 * have to reset the titlebar to whatever it used to be
1942 * (for example, if the user chose to stop loading), we
1943 * call resetTitleAndRevertLockIcon.
1944 */
1945 /* package */ void resetTitleAndRevertLockIcon() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001946 mTabControl.getCurrentTab().revertLockIcon();
1947 updateLockIconToLatest();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001948 resetTitleIconAndProgress();
1949 }
1950
1951 /**
1952 * Reset the title, favicon, and progress.
1953 */
1954 private void resetTitleIconAndProgress() {
1955 WebView current = mTabControl.getCurrentWebView();
1956 if (current == null) {
1957 return;
1958 }
1959 resetTitleAndIcon(current);
1960 int progress = current.getProgress();
Grace Kloba22ac16e2009-10-07 18:00:23 -07001961 current.getWebChromeClient().onProgressChanged(current, progress);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001962 }
1963
1964 // Reset the title and the icon based on the given item.
1965 private void resetTitleAndIcon(WebView view) {
1966 WebHistoryItem item = view.copyBackForwardList().getCurrentItem();
1967 if (item != null) {
Leon Scroggins68579392009-09-15 15:31:54 -04001968 setUrlTitle(item.getUrl(), item.getTitle());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001969 setFavicon(item.getFavicon());
1970 } else {
Leon Scroggins68579392009-09-15 15:31:54 -04001971 setUrlTitle(null, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001972 setFavicon(null);
1973 }
1974 }
1975
1976 /**
1977 * Sets a title composed of the URL and the title string.
1978 * @param url The URL of the site being loaded.
1979 * @param title The title of the site being loaded.
1980 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07001981 void setUrlTitle(String url, String title) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001982 mUrl = url;
1983 mTitle = title;
1984
Leon Scroggins58d56c62010-01-28 15:12:40 -05001985 // If we are in voice search mode, the title has already been set.
1986 if (mTabControl.getCurrentTab().isInVoiceSearchMode()) return;
1987 mTitleBar.setDisplayTitle(url);
1988 mFakeTitleBar.setDisplayTitle(url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001989 }
1990
1991 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08001992 * @param url The URL to build a title version of the URL from.
1993 * @return The title version of the URL or null if fails.
1994 * The title version of the URL can be either the URL hostname,
1995 * or the hostname with an "https://" prefix (for secure URLs),
1996 * or an empty string if, for example, the URL in question is a
1997 * file:// URL with no hostname.
1998 */
Leon Scroggins32e14a62009-06-11 10:26:34 -04001999 /* package */ static String buildTitleUrl(String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002000 String titleUrl = null;
2001
2002 if (url != null) {
2003 try {
2004 // parse the url string
2005 URL urlObj = new URL(url);
2006 if (urlObj != null) {
2007 titleUrl = "";
2008
2009 String protocol = urlObj.getProtocol();
2010 String host = urlObj.getHost();
2011
2012 if (host != null && 0 < host.length()) {
2013 titleUrl = host;
2014 if (protocol != null) {
2015 // if a secure site, add an "https://" prefix!
2016 if (protocol.equalsIgnoreCase("https")) {
2017 titleUrl = protocol + "://" + host;
2018 }
2019 }
2020 }
2021 }
2022 } catch (MalformedURLException e) {}
2023 }
2024
2025 return titleUrl;
2026 }
2027
2028 // Set the favicon in the title bar.
Grace Kloba22ac16e2009-10-07 18:00:23 -07002029 void setFavicon(Bitmap icon) {
Leon Scroggins68579392009-09-15 15:31:54 -04002030 mTitleBar.setFavicon(icon);
Leon Scrogginsfe87bd32009-10-06 10:10:00 -04002031 mFakeTitleBar.setFavicon(icon);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002032 }
2033
2034 /**
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002035 * Close the tab, remove its associated title bar, and adjust mTabControl's
2036 * current tab to a valid value.
Leon Scroggins1f005d32009-08-10 17:36:42 -04002037 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07002038 /* package */ void closeTab(Tab t) {
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002039 int currentIndex = mTabControl.getCurrentIndex();
2040 int removeIndex = mTabControl.getTabIndex(t);
Leon Scroggins1f005d32009-08-10 17:36:42 -04002041 mTabControl.removeTab(t);
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002042 if (currentIndex >= removeIndex && currentIndex != 0) {
2043 currentIndex--;
2044 }
2045 mTabControl.setCurrentTab(mTabControl.getTab(currentIndex));
Andrei Popescua5bf1de2009-09-23 16:39:23 +01002046 resetTitleIconAndProgress();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002047 }
2048
Leon Scrogginsdcc5eeb2010-02-23 17:26:37 -05002049 /* package */ void goBackOnePageOrQuit() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002050 Tab current = mTabControl.getCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002051 if (current == null) {
2052 /*
2053 * Instead of finishing the activity, simply push this to the back
2054 * of the stack and let ActivityManager to choose the foreground
2055 * activity. As BrowserActivity is singleTask, it will be always the
2056 * root of the task. So we can use either true or false for
2057 * moveTaskToBack().
2058 */
2059 moveTaskToBack(true);
Grace Kloba00d85e72009-09-23 18:50:05 -07002060 return;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002061 }
2062 WebView w = current.getWebView();
2063 if (w.canGoBack()) {
2064 w.goBack();
2065 } else {
2066 // Check to see if we are closing a window that was created by
2067 // another window. If so, we switch back to that window.
Grace Kloba22ac16e2009-10-07 18:00:23 -07002068 Tab parent = current.getParentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002069 if (parent != null) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04002070 switchToTab(mTabControl.getTabIndex(parent));
2071 // Now we close the other tab
2072 closeTab(current);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002073 } else {
2074 if (current.closeOnExit()) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002075 // force the tab's inLoad() to be false as we are going to
2076 // either finish the activity or remove the tab. This will
2077 // ensure pauseWebViewTimers() taking action.
2078 mTabControl.getCurrentTab().clearInLoad();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002079 if (mTabControl.getTabCount() == 1) {
2080 finish();
2081 return;
2082 }
Mike Reed7bfa63b2009-05-28 11:08:32 -04002083 // call pauseWebViewTimers() now, we won't be able to call
2084 // it in onPause() as the WebView won't be valid.
Grace Klobaec1b5ad2009-08-18 08:42:32 -07002085 // Temporarily change mActivityInPause to be true as
2086 // pauseWebViewTimers() will do nothing if mActivityInPause
2087 // is false.
Grace Kloba918e1d72009-08-13 14:55:06 -07002088 boolean savedState = mActivityInPause;
2089 if (savedState) {
Grace Klobaec1b5ad2009-08-18 08:42:32 -07002090 Log.e(LOGTAG, "BrowserActivity is already paused "
2091 + "while handing goBackOnePageOrQuit.");
Grace Kloba918e1d72009-08-13 14:55:06 -07002092 }
2093 mActivityInPause = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -04002094 pauseWebViewTimers();
Grace Kloba918e1d72009-08-13 14:55:06 -07002095 mActivityInPause = savedState;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002096 removeTabFromContentView(current);
2097 mTabControl.removeTab(current);
2098 }
2099 /*
2100 * Instead of finishing the activity, simply push this to the back
2101 * of the stack and let ActivityManager to choose the foreground
2102 * activity. As BrowserActivity is singleTask, it will be always the
2103 * root of the task. So we can use either true or false for
2104 * moveTaskToBack().
2105 */
2106 moveTaskToBack(true);
2107 }
2108 }
2109 }
2110
Grace Kloba22ac16e2009-10-07 18:00:23 -07002111 boolean isMenuDown() {
2112 return mMenuIsDown;
2113 }
2114
Grace Kloba5942df02009-09-18 11:48:29 -07002115 @Override
2116 public boolean onKeyDown(int keyCode, KeyEvent event) {
Leon Scrogginsf65b50d2009-12-08 10:44:28 -05002117 // Even if MENU is already held down, we need to call to super to open
2118 // the IME on long press.
2119 if (KeyEvent.KEYCODE_MENU == keyCode) {
2120 mMenuIsDown = true;
2121 return super.onKeyDown(keyCode, event);
2122 }
Grace Kloba5942df02009-09-18 11:48:29 -07002123 // The default key mode is DEFAULT_KEYS_SEARCH_LOCAL. As the MENU is
2124 // still down, we don't want to trigger the search. Pretend to consume
2125 // the key and do nothing.
2126 if (mMenuIsDown) return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002127
Grace Kloba5942df02009-09-18 11:48:29 -07002128 switch(keyCode) {
Grace Kloba5942df02009-09-18 11:48:29 -07002129 case KeyEvent.KEYCODE_SPACE:
Grace Klobada0fe552009-09-22 18:17:24 -07002130 // WebView/WebTextView handle the keys in the KeyDown. As
2131 // the Activity's shortcut keys are only handled when WebView
2132 // doesn't, have to do it in onKeyDown instead of onKeyUp.
2133 if (event.isShiftPressed()) {
2134 getTopWindow().pageUp(false);
2135 } else {
2136 getTopWindow().pageDown(false);
2137 }
Grace Kloba5942df02009-09-18 11:48:29 -07002138 return true;
2139 case KeyEvent.KEYCODE_BACK:
2140 if (event.getRepeatCount() == 0) {
2141 event.startTracking();
2142 return true;
2143 } else if (mCustomView == null && mActiveTabsPage == null
2144 && event.isLongPress()) {
2145 bookmarksOrHistoryPicker(true);
2146 return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002147 }
Grace Kloba5942df02009-09-18 11:48:29 -07002148 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002149 }
Grace Kloba5942df02009-09-18 11:48:29 -07002150 return super.onKeyDown(keyCode, event);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002151 }
2152
Grace Kloba5942df02009-09-18 11:48:29 -07002153 @Override
2154 public boolean onKeyUp(int keyCode, KeyEvent event) {
2155 switch(keyCode) {
2156 case KeyEvent.KEYCODE_MENU:
2157 mMenuIsDown = false;
2158 break;
Grace Kloba5942df02009-09-18 11:48:29 -07002159 case KeyEvent.KEYCODE_BACK:
2160 if (event.isTracking() && !event.isCanceled()) {
2161 if (mCustomView != null) {
2162 // if a custom view is showing, hide it
Grace Kloba22ac16e2009-10-07 18:00:23 -07002163 mTabControl.getCurrentWebView().getWebChromeClient()
2164 .onHideCustomView();
Grace Kloba5942df02009-09-18 11:48:29 -07002165 } else if (mActiveTabsPage != null) {
2166 // if tab page is showing, hide it
2167 removeActiveTabPage(true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002168 } else {
Grace Kloba5942df02009-09-18 11:48:29 -07002169 WebView subwindow = mTabControl.getCurrentSubWindow();
2170 if (subwindow != null) {
2171 if (subwindow.canGoBack()) {
2172 subwindow.goBack();
2173 } else {
2174 dismissSubWindow(mTabControl.getCurrentTab());
2175 }
2176 } else {
2177 goBackOnePageOrQuit();
2178 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002179 }
Grace Kloba5942df02009-09-18 11:48:29 -07002180 return true;
2181 }
2182 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002183 }
Grace Kloba5942df02009-09-18 11:48:29 -07002184 return super.onKeyUp(keyCode, event);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002185 }
2186
Leon Scroggins68579392009-09-15 15:31:54 -04002187 /* package */ void stopLoading() {
Ben Murdochb7cc8b42009-09-28 10:59:09 +01002188 mDidStopLoad = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002189 resetTitleAndRevertLockIcon();
2190 WebView w = getTopWindow();
2191 w.stopLoading();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002192 // FIXME: before refactor, it is using mWebViewClient. So I keep the
2193 // same logic here. But for subwindow case, should we call into the main
2194 // WebView's onPageFinished as we never call its onPageStarted and if
2195 // the page finishes itself, we don't call onPageFinished.
2196 mTabControl.getCurrentWebView().getWebViewClient().onPageFinished(w,
2197 w.getUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08002198
2199 cancelStopToast();
2200 mStopToast = Toast
2201 .makeText(this, R.string.stopping, Toast.LENGTH_SHORT);
2202 mStopToast.show();
2203 }
2204
Grace Kloba22ac16e2009-10-07 18:00:23 -07002205 boolean didUserStopLoading() {
2206 return mDidStopLoad;
2207 }
2208
The Android Open Source Project0c908882009-03-03 19:32:16 -08002209 private void cancelStopToast() {
2210 if (mStopToast != null) {
2211 mStopToast.cancel();
2212 mStopToast = null;
2213 }
2214 }
2215
Grace Kloba22ac16e2009-10-07 18:00:23 -07002216 // called by a UI or non-UI thread to post the message
2217 public void postMessage(int what, int arg1, int arg2, Object obj,
2218 long delayMillis) {
2219 mHandler.sendMessageDelayed(mHandler.obtainMessage(what, arg1, arg2,
2220 obj), delayMillis);
2221 }
2222
2223 // called by a UI or non-UI thread to remove the message
2224 void removeMessages(int what, Object object) {
2225 mHandler.removeMessages(what, object);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002226 }
2227
2228 // public message ids
2229 public final static int LOAD_URL = 1001;
2230 public final static int STOP_LOAD = 1002;
2231
2232 // Message Ids
2233 private static final int FOCUS_NODE_HREF = 102;
Grace Kloba92c18a52009-07-31 23:48:32 -07002234 private static final int RELEASE_WAKELOCK = 107;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002235
Grace Kloba22ac16e2009-10-07 18:00:23 -07002236 static final int UPDATE_BOOKMARK_THUMBNAIL = 108;
Ben Murdoch2694e232009-09-29 09:41:11 +01002237
The Android Open Source Project0c908882009-03-03 19:32:16 -08002238 // Private handler for handling javascript and saving passwords
2239 private Handler mHandler = new Handler() {
2240
2241 public void handleMessage(Message msg) {
2242 switch (msg.what) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002243 case FOCUS_NODE_HREF:
Ben Murdoch2694e232009-09-29 09:41:11 +01002244 {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002245 String url = (String) msg.getData().get("url");
Ben Murdoch90d088c2009-11-17 18:14:04 +00002246 String title = (String) msg.getData().get("title");
The Android Open Source Project0c908882009-03-03 19:32:16 -08002247 if (url == null || url.length() == 0) {
2248 break;
2249 }
2250 HashMap focusNodeMap = (HashMap) msg.obj;
2251 WebView view = (WebView) focusNodeMap.get("webview");
2252 // Only apply the action if the top window did not change.
2253 if (getTopWindow() != view) {
2254 break;
2255 }
2256 switch (msg.arg1) {
2257 case R.id.open_context_menu_id:
2258 case R.id.view_image_context_menu_id:
Leon Scroggins92472e82010-02-17 16:32:28 -05002259 loadUrlFromContext(getTopWindow(), url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002260 break;
2261 case R.id.open_newtab_context_menu_id:
Grace Kloba22ac16e2009-10-07 18:00:23 -07002262 final Tab parent = mTabControl.getCurrentTab();
2263 final Tab newTab = openTab(url);
Grace Klobac9181842009-04-14 08:53:22 -07002264 if (newTab != parent) {
2265 parent.addChildTab(newTab);
2266 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002267 break;
2268 case R.id.bookmark_context_menu_id:
2269 Intent intent = new Intent(BrowserActivity.this,
2270 AddBookmarkPage.class);
2271 intent.putExtra("url", url);
Ben Murdoch90d088c2009-11-17 18:14:04 +00002272 intent.putExtra("title", title);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002273 startActivity(intent);
2274 break;
2275 case R.id.share_link_context_menu_id:
Leon Scroggins96afcb12009-12-10 12:35:56 -05002276 // See if this site has been visited before
2277 StringBuilder sb = new StringBuilder(
2278 Browser.BookmarkColumns.URL + " = ");
2279 DatabaseUtils.appendEscapedSQLString(sb, url);
2280 Cursor c = mResolver.query(Browser.BOOKMARKS_URI,
2281 Browser.HISTORY_PROJECTION,
2282 sb.toString(),
2283 null,
2284 null);
2285 if (c.moveToFirst()) {
2286 // The site has been visited before, so grab the
2287 // info from the database.
2288 Bitmap favicon = null;
2289 Bitmap thumbnail = null;
2290 String linkTitle = c.getString(Browser.
2291 HISTORY_PROJECTION_TITLE_INDEX);
2292 byte[] data = c.getBlob(Browser.
2293 HISTORY_PROJECTION_FAVICON_INDEX);
2294 if (data != null) {
2295 favicon = BitmapFactory.decodeByteArray(
2296 data, 0, data.length);
2297 }
2298 data = c.getBlob(Browser.
2299 HISTORY_PROJECTION_THUMBNAIL_INDEX);
2300 if (data != null) {
2301 thumbnail = BitmapFactory.decodeByteArray(
2302 data, 0, data.length);
2303 }
2304 sharePage(BrowserActivity.this,
2305 linkTitle, url, favicon, thumbnail);
2306 } else {
2307 Browser.sendString(BrowserActivity.this, url,
2308 getString(
2309 R.string.choosertitle_sharevia));
2310 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002311 break;
2312 case R.id.copy_link_context_menu_id:
2313 copy(url);
2314 break;
2315 case R.id.save_link_context_menu_id:
2316 case R.id.download_context_menu_id:
2317 onDownloadStartNoStream(url, null, null, null, -1);
2318 break;
2319 }
2320 break;
Ben Murdoch2694e232009-09-29 09:41:11 +01002321 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002322
2323 case LOAD_URL:
Leon Scroggins92472e82010-02-17 16:32:28 -05002324 loadUrlFromContext(getTopWindow(), (String) msg.obj);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002325 break;
2326
2327 case STOP_LOAD:
2328 stopLoading();
2329 break;
2330
The Android Open Source Project0c908882009-03-03 19:32:16 -08002331 case RELEASE_WAKELOCK:
2332 if (mWakeLock.isHeld()) {
2333 mWakeLock.release();
Grace Kloba5d0e02e2009-10-05 15:15:36 -07002334 // if we reach here, Browser should be still in the
2335 // background loading after WAKELOCK_TIMEOUT (5-min).
2336 // To avoid burning the battery, stop loading.
2337 mTabControl.stopAllLoading();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002338 }
2339 break;
Ben Murdoch2694e232009-09-29 09:41:11 +01002340
2341 case UPDATE_BOOKMARK_THUMBNAIL:
2342 WebView view = (WebView) msg.obj;
2343 if (view != null) {
2344 updateScreenshot(view);
2345 }
2346 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002347 }
2348 }
2349 };
2350
Leon Scroggins96afcb12009-12-10 12:35:56 -05002351 /**
2352 * Share a page, providing the title, url, favicon, and a screenshot. Uses
2353 * an {@link Intent} to launch the Activity chooser.
2354 * @param c Context used to launch a new Activity.
2355 * @param title Title of the page. Stored in the Intent with
Paul Westbrook03e6d392010-02-12 10:33:29 -08002356 * {@link Intent#EXTRA_SUBJECT}
Leon Scroggins96afcb12009-12-10 12:35:56 -05002357 * @param url URL of the page. Stored in the Intent with
2358 * {@link Intent#EXTRA_TEXT}
2359 * @param favicon Bitmap of the favicon for the page. Stored in the Intent
2360 * with {@link Browser#EXTRA_SHARE_FAVICON}
2361 * @param screenshot Bitmap of a screenshot of the page. Stored in the
2362 * Intent with {@link Browser#EXTRA_SHARE_SCREENSHOT}
2363 */
2364 public static final void sharePage(Context c, String title, String url,
2365 Bitmap favicon, Bitmap screenshot) {
2366 Intent send = new Intent(Intent.ACTION_SEND);
2367 send.setType("text/plain");
2368 send.putExtra(Intent.EXTRA_TEXT, url);
Paul Westbrook03e6d392010-02-12 10:33:29 -08002369 send.putExtra(Intent.EXTRA_SUBJECT, title);
Leon Scroggins96afcb12009-12-10 12:35:56 -05002370 send.putExtra(Browser.EXTRA_SHARE_FAVICON, favicon);
2371 send.putExtra(Browser.EXTRA_SHARE_SCREENSHOT, screenshot);
2372 try {
2373 c.startActivity(Intent.createChooser(send, c.getString(
2374 R.string.choosertitle_sharevia)));
2375 } catch(android.content.ActivityNotFoundException ex) {
2376 // if no app handles it, do nothing
2377 }
2378 }
2379
Leon Scroggins89c6d362009-07-15 16:54:37 -04002380 private void updateScreenshot(WebView view) {
2381 // If this is a bookmarked site, add a screenshot to the database.
2382 // FIXME: When should we update? Every time?
2383 // FIXME: Would like to make sure there is actually something to
2384 // draw, but the API for that (WebViewCore.pictureReady()) is not
2385 // currently accessible here.
Ben Murdochaac7aa62009-09-17 16:57:40 +01002386
Patrick Scottcb192b52010-04-14 14:38:55 -04002387 final Bitmap bm = createScreenshot(view);
2388 if (bm == null) {
2389 return;
Leon Scroggins89c6d362009-07-15 16:54:37 -04002390 }
Patrick Scottcb192b52010-04-14 14:38:55 -04002391
2392 final ContentResolver cr = getContentResolver();
2393 final String url = view.getUrl();
2394 final String originalUrl = view.getOriginalUrl();
2395
2396 new AsyncTask<Void, Void, Void>() {
2397 @Override
2398 protected Void doInBackground(Void... unused) {
2399 Cursor c = null;
2400 try {
2401 c = BrowserBookmarksAdapter.queryBookmarksForUrl(
2402 cr, originalUrl, url, true);
2403 if (c != null) {
2404 if (c.moveToFirst()) {
2405 ContentValues values = new ContentValues();
2406 final ByteArrayOutputStream os
2407 = new ByteArrayOutputStream();
2408 bm.compress(Bitmap.CompressFormat.PNG, 100, os);
2409 values.put(Browser.BookmarkColumns.THUMBNAIL,
2410 os.toByteArray());
2411 do {
2412 cr.update(ContentUris.withAppendedId(
2413 Browser.BOOKMARKS_URI, c.getInt(0)),
2414 values, null, null);
2415 } while (c.moveToNext());
2416 }
2417 }
2418 } catch (IllegalStateException e) {
2419 // Ignore
2420 } finally {
2421 if (c != null) c.close();
2422 }
2423 return null;
2424 }
2425 }.execute();
Leon Scroggins89c6d362009-07-15 16:54:37 -04002426 }
2427
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002428 /**
Leon Scrogginsf8551612009-09-24 16:06:02 -04002429 * Values for the size of the thumbnail created when taking a screenshot.
2430 * Lazily initialized. Instead of using these directly, use
2431 * getDesiredThumbnailWidth() or getDesiredThumbnailHeight().
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002432 */
Leon Scrogginsf8551612009-09-24 16:06:02 -04002433 private static int THUMBNAIL_WIDTH = 0;
2434 private static int THUMBNAIL_HEIGHT = 0;
2435
2436 /**
2437 * Return the desired width for thumbnail screenshots, which are stored in
2438 * the database, and used on the bookmarks screen.
2439 * @param context Context for finding out the density of the screen.
2440 * @return int desired width for thumbnail screenshot.
2441 */
2442 /* package */ static int getDesiredThumbnailWidth(Context context) {
2443 if (THUMBNAIL_WIDTH == 0) {
2444 float density = context.getResources().getDisplayMetrics().density;
2445 THUMBNAIL_WIDTH = (int) (90 * density);
2446 THUMBNAIL_HEIGHT = (int) (80 * density);
2447 }
2448 return THUMBNAIL_WIDTH;
2449 }
2450
2451 /**
2452 * Return the desired height for thumbnail screenshots, which are stored in
2453 * the database, and used on the bookmarks screen.
2454 * @param context Context for finding out the density of the screen.
2455 * @return int desired height for thumbnail screenshot.
2456 */
2457 /* package */ static int getDesiredThumbnailHeight(Context context) {
2458 // To ensure that they are both initialized.
2459 getDesiredThumbnailWidth(context);
2460 return THUMBNAIL_HEIGHT;
2461 }
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002462
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002463 private Bitmap createScreenshot(WebView view) {
2464 Picture thumbnail = view.capturePicture();
Leon Scroggins45800572009-09-29 16:38:47 -04002465 if (thumbnail == null) {
2466 return null;
2467 }
Leon Scrogginsf8551612009-09-24 16:06:02 -04002468 Bitmap bm = Bitmap.createBitmap(getDesiredThumbnailWidth(this),
Cary Clarkab168ba2010-04-08 09:11:28 -04002469 getDesiredThumbnailHeight(this), Bitmap.Config.RGB_565);
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002470 Canvas canvas = new Canvas(bm);
2471 // May need to tweak these values to determine what is the
2472 // best scale factor
Ben Murdoch2694e232009-09-29 09:41:11 +01002473 int thumbnailWidth = thumbnail.getWidth();
Ben Murdochae59c3f2009-10-20 18:30:28 +01002474 int thumbnailHeight = thumbnail.getHeight();
2475 float scaleFactorX = 1.0f;
2476 float scaleFactorY = 1.0f;
Ben Murdoch2694e232009-09-29 09:41:11 +01002477 if (thumbnailWidth > 0) {
Ben Murdochae59c3f2009-10-20 18:30:28 +01002478 scaleFactorX = (float) getDesiredThumbnailWidth(this) /
Ben Murdoch2694e232009-09-29 09:41:11 +01002479 (float)thumbnailWidth;
Ben Murdochae59c3f2009-10-20 18:30:28 +01002480 } else {
2481 return null;
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002482 }
Ben Murdochae59c3f2009-10-20 18:30:28 +01002483
2484 if (view.getWidth() > view.getHeight() &&
2485 thumbnailHeight < view.getHeight() && thumbnailHeight > 0) {
2486 // If the device is in landscape and the page is shorter
2487 // than the height of the view, stretch the thumbnail to fill the
2488 // space.
2489 scaleFactorY = (float) getDesiredThumbnailHeight(this) /
2490 (float)thumbnailHeight;
2491 } else {
2492 // In the portrait case, this looks nice.
2493 scaleFactorY = scaleFactorX;
2494 }
2495
2496 canvas.scale(scaleFactorX, scaleFactorY);
2497
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002498 thumbnail.draw(canvas);
2499 return bm;
2500 }
2501
The Android Open Source Project0c908882009-03-03 19:32:16 -08002502 // -------------------------------------------------------------------------
Grace Kloba22ac16e2009-10-07 18:00:23 -07002503 // Helper function for WebViewClient.
The Android Open Source Project0c908882009-03-03 19:32:16 -08002504 //-------------------------------------------------------------------------
2505
2506 // Use in overrideUrlLoading
2507 /* package */ final static String SCHEME_WTAI = "wtai://wp/";
2508 /* package */ final static String SCHEME_WTAI_MC = "wtai://wp/mc;";
2509 /* package */ final static String SCHEME_WTAI_SD = "wtai://wp/sd;";
2510 /* package */ final static String SCHEME_WTAI_AP = "wtai://wp/ap;";
2511
Leon Scroggins92472e82010-02-17 16:32:28 -05002512 // Keep this initial progress in sync with initialProgressValue (* 100)
2513 // in ProgressTracker.cpp
2514 private final static int INITIAL_PROGRESS = 10;
2515
Grace Kloba22ac16e2009-10-07 18:00:23 -07002516 void onPageStarted(WebView view, String url, Bitmap favicon) {
2517 // when BrowserActivity just starts, onPageStarted may be called before
2518 // onResume as it is triggered from onCreate. Call resumeWebViewTimers
2519 // to start the timer. As we won't switch tabs while an activity is in
2520 // pause state, we can ensure calling resume and pause in pair.
2521 if (mActivityInPause) resumeWebViewTimers();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002522
Grace Kloba22ac16e2009-10-07 18:00:23 -07002523 resetLockIcon(url);
2524 setUrlTitle(url, null);
2525 setFavicon(favicon);
Leon Scroggins8cf8f682009-11-04 11:13:50 -08002526 // Show some progress so that the user knows the page is beginning to
2527 // load
Leon Scroggins92472e82010-02-17 16:32:28 -05002528 onProgressChanged(view, INITIAL_PROGRESS);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002529 mDidStopLoad = false;
Grace Kloba22ac16e2009-10-07 18:00:23 -07002530 if (!mIsNetworkUp) createAndShowNetworkDialog();
Cary Clark2c326e62010-08-19 18:40:57 -04002531 closeDialogs();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002532 if (mSettings.isTracing()) {
2533 String host;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002534 try {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002535 WebAddress uri = new WebAddress(url);
2536 host = uri.mHost;
2537 } catch (android.net.ParseException ex) {
2538 host = "browser";
The Android Open Source Project0c908882009-03-03 19:32:16 -08002539 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002540 host = host.replace('.', '_');
2541 host += ".trace";
2542 mInTrace = true;
2543 Debug.startMethodTracing(host, 20 * 1024 * 1024);
2544 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002545
Grace Kloba22ac16e2009-10-07 18:00:23 -07002546 // Performance probe
2547 if (false) {
2548 mStart = SystemClock.uptimeMillis();
2549 mProcessStart = Process.getElapsedCpuTime();
2550 long[] sysCpu = new long[7];
2551 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2552 sysCpu, null)) {
2553 mUserStart = sysCpu[0] + sysCpu[1];
2554 mSystemStart = sysCpu[2];
2555 mIdleStart = sysCpu[3];
2556 mIrqStart = sysCpu[4] + sysCpu[5] + sysCpu[6];
2557 }
2558 mUiStart = SystemClock.currentThreadTimeMillis();
2559 }
2560 }
2561
2562 void onPageFinished(WebView view, String url) {
2563 // Reset the title and icon in case we stopped a provisional load.
2564 resetTitleAndIcon(view);
2565 // Update the lock icon image only once we are done loading
2566 updateLockIconToLatest();
2567 // pause the WebView timer and release the wake lock if it is finished
2568 // while BrowserActivity is in pause state.
2569 if (mActivityInPause && pauseWebViewTimers()) {
2570 if (mWakeLock.isHeld()) {
2571 mHandler.removeMessages(RELEASE_WAKELOCK);
2572 mWakeLock.release();
2573 }
2574 }
2575
2576 // Performance probe
2577 if (false) {
2578 long[] sysCpu = new long[7];
2579 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2580 sysCpu, null)) {
2581 String uiInfo = "UI thread used "
2582 + (SystemClock.currentThreadTimeMillis() - mUiStart)
2583 + " ms";
2584 if (LOGD_ENABLED) {
2585 Log.d(LOGTAG, uiInfo);
2586 }
2587 //The string that gets written to the log
2588 String performanceString = "It took total "
2589 + (SystemClock.uptimeMillis() - mStart)
2590 + " ms clock time to load the page."
2591 + "\nbrowser process used "
2592 + (Process.getElapsedCpuTime() - mProcessStart)
2593 + " ms, user processes used "
2594 + (sysCpu[0] + sysCpu[1] - mUserStart) * 10
2595 + " ms, kernel used "
2596 + (sysCpu[2] - mSystemStart) * 10
2597 + " ms, idle took " + (sysCpu[3] - mIdleStart) * 10
2598 + " ms and irq took "
2599 + (sysCpu[4] + sysCpu[5] + sysCpu[6] - mIrqStart)
2600 * 10 + " ms, " + uiInfo;
2601 if (LOGD_ENABLED) {
2602 Log.d(LOGTAG, performanceString + "\nWebpage: " + url);
2603 }
2604 if (url != null) {
2605 // strip the url to maintain consistency
2606 String newUrl = new String(url);
2607 if (newUrl.startsWith("http://www.")) {
2608 newUrl = newUrl.substring(11);
2609 } else if (newUrl.startsWith("http://")) {
2610 newUrl = newUrl.substring(7);
2611 } else if (newUrl.startsWith("https://www.")) {
2612 newUrl = newUrl.substring(12);
2613 } else if (newUrl.startsWith("https://")) {
2614 newUrl = newUrl.substring(8);
2615 }
2616 if (LOGD_ENABLED) {
2617 Log.d(LOGTAG, newUrl + " loaded");
2618 }
Grace Kloba5b078b52009-06-24 20:23:41 -07002619 }
2620 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002621 }
Grace Kloba5b078b52009-06-24 20:23:41 -07002622
Grace Kloba22ac16e2009-10-07 18:00:23 -07002623 if (mInTrace) {
2624 mInTrace = false;
2625 Debug.stopMethodTracing();
2626 }
2627 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002628
Grace Kloba22ac16e2009-10-07 18:00:23 -07002629 boolean shouldOverrideUrlLoading(WebView view, String url) {
2630 if (url.startsWith(SCHEME_WTAI)) {
2631 // wtai://wp/mc;number
2632 // number=string(phone-number)
2633 if (url.startsWith(SCHEME_WTAI_MC)) {
2634 Intent intent = new Intent(Intent.ACTION_VIEW,
2635 Uri.parse(WebView.SCHEME_TEL +
2636 url.substring(SCHEME_WTAI_MC.length())));
2637 startActivity(intent);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002638 return true;
2639 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002640 // wtai://wp/sd;dtmf
2641 // dtmf=string(dialstring)
2642 if (url.startsWith(SCHEME_WTAI_SD)) {
2643 // TODO: only send when there is active voice connection
2644 return false;
2645 }
2646 // wtai://wp/ap;number;name
2647 // number=string(phone-number)
2648 // name=string
2649 if (url.startsWith(SCHEME_WTAI_AP)) {
2650 // TODO
2651 return false;
2652 }
2653 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002654
Grace Kloba22ac16e2009-10-07 18:00:23 -07002655 // The "about:" schemes are internal to the browser; don't want these to
2656 // be dispatched to other apps.
2657 if (url.startsWith("about:")) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002658 return false;
2659 }
2660
Grace Kloba22ac16e2009-10-07 18:00:23 -07002661 Intent intent;
2662 // perform generic parsing of the URI to turn it into an Intent.
2663 try {
2664 intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME);
2665 } catch (URISyntaxException ex) {
2666 Log.w("Browser", "Bad URI " + url + ": " + ex.getMessage());
2667 return false;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002668 }
2669
Grace Kloba22ac16e2009-10-07 18:00:23 -07002670 // check whether the intent can be resolved. If not, we will see
2671 // whether we can download it from the Market.
2672 if (getPackageManager().resolveActivity(intent, 0) == null) {
2673 String packagename = intent.getPackage();
2674 if (packagename != null) {
2675 intent = new Intent(Intent.ACTION_VIEW, Uri
2676 .parse("market://search?q=pname:" + packagename));
2677 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2678 startActivity(intent);
2679 return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002680 } else {
2681 return false;
2682 }
2683 }
2684
Grace Kloba22ac16e2009-10-07 18:00:23 -07002685 // sanitize the Intent, ensuring web pages can not bypass browser
2686 // security (only access to BROWSABLE activities).
2687 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2688 intent.setComponent(null);
2689 try {
2690 if (startActivityIfNeeded(intent, -1)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002691 return true;
2692 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002693 } catch (ActivityNotFoundException ex) {
2694 // ignore the error. If no application can handle the URL,
2695 // eg about:blank, assume the browser can handle it.
2696 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002697
Grace Kloba22ac16e2009-10-07 18:00:23 -07002698 if (mMenuIsDown) {
2699 openTab(url);
2700 closeOptionsMenu();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002701 return true;
2702 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002703 return false;
2704 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002705
Grace Kloba22ac16e2009-10-07 18:00:23 -07002706 // -------------------------------------------------------------------------
2707 // Helper function for WebChromeClient
2708 // -------------------------------------------------------------------------
The Android Open Source Project0c908882009-03-03 19:32:16 -08002709
Grace Kloba22ac16e2009-10-07 18:00:23 -07002710 void onProgressChanged(WebView view, int newProgress) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002711 mFakeTitleBar.setProgress(newProgress);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002712
Grace Kloba22ac16e2009-10-07 18:00:23 -07002713 if (newProgress == 100) {
2714 // onProgressChanged() may continue to be called after the main
2715 // frame has finished loading, as any remaining sub frames continue
2716 // to load. We'll only get called once though with newProgress as
2717 // 100 when everything is loaded. (onPageFinished is called once
2718 // when the main frame completes loading regardless of the state of
2719 // any sub frames so calls to onProgressChanges may continue after
2720 // onPageFinished has executed)
2721 if (mInLoad) {
2722 mInLoad = false;
Leon Scrogginsa27ff192009-09-14 12:58:04 -04002723 updateInLoadMenuItems();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002724 // If the options menu is open, leave the title bar
2725 if (!mOptionsMenuOpen || !mIconView) {
2726 hideFakeTitleBar();
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07002727 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002728 }
Leon Scrogginsaa37e7f2010-03-05 11:51:20 -05002729 } else {
2730 if (!mInLoad) {
2731 // onPageFinished may have already been called but a subframe is
2732 // still loading and updating the progress. Reset mInLoad and
2733 // update the menu items.
2734 mInLoad = true;
2735 updateInLoadMenuItems();
2736 }
2737 // When the page first begins to load, the Activity may still be
2738 // paused, in which case showFakeTitleBar will do nothing. Call
2739 // again as the page continues to load so that it will be shown.
2740 // (Calling it will the fake title bar is already showing will also
2741 // do nothing.
Grace Kloba22ac16e2009-10-07 18:00:23 -07002742 if (!mOptionsMenuOpen || mIconView) {
2743 // This page has begun to load, so show the title bar
2744 showFakeTitleBar();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002745 }
2746 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002747 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002748
Grace Kloba22ac16e2009-10-07 18:00:23 -07002749 void onShowCustomView(View view, WebChromeClient.CustomViewCallback callback) {
Derek Sollenberger8ff57db2009-12-08 15:39:55 -05002750 // if a view already exists then immediately terminate the new one
2751 if (mCustomView != null) {
2752 callback.onCustomViewHidden();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002753 return;
Derek Sollenberger8ff57db2009-12-08 15:39:55 -05002754 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002755
2756 // Add the custom view to its container.
2757 mCustomViewContainer.addView(view, COVER_SCREEN_GRAVITY_CENTER);
2758 mCustomView = view;
2759 mCustomViewCallback = callback;
2760 // Save the menu state and set it to empty while the custom
2761 // view is showing.
2762 mOldMenuState = mMenuState;
2763 mMenuState = EMPTY_MENU;
2764 // Hide the content view.
2765 mContentView.setVisibility(View.GONE);
2766 // Finally show the custom view container.
Andrei Popescu163ab742009-10-20 17:58:23 +01002767 setStatusBarVisibility(false);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002768 mCustomViewContainer.setVisibility(View.VISIBLE);
2769 mCustomViewContainer.bringToFront();
2770 }
2771
2772 void onHideCustomView() {
2773 if (mCustomView == null)
2774 return;
Grace Kloba22ac16e2009-10-07 18:00:23 -07002775 // Hide the custom view.
2776 mCustomView.setVisibility(View.GONE);
2777 // Remove the custom view from its container.
2778 mCustomViewContainer.removeView(mCustomView);
2779 mCustomView = null;
2780 // Reset the old menu state.
2781 mMenuState = mOldMenuState;
2782 mOldMenuState = EMPTY_MENU;
2783 mCustomViewContainer.setVisibility(View.GONE);
2784 mCustomViewCallback.onCustomViewHidden();
2785 // Show the content view.
Andrei Popescu163ab742009-10-20 17:58:23 +01002786 setStatusBarVisibility(true);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002787 mContentView.setVisibility(View.VISIBLE);
2788 }
2789
2790 Bitmap getDefaultVideoPoster() {
2791 if (mDefaultVideoPoster == null) {
2792 mDefaultVideoPoster = BitmapFactory.decodeResource(
2793 getResources(), R.drawable.default_video_poster);
Patrick Scott3918d442009-08-04 13:22:29 -04002794 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002795 return mDefaultVideoPoster;
2796 }
Patrick Scott3918d442009-08-04 13:22:29 -04002797
Grace Kloba22ac16e2009-10-07 18:00:23 -07002798 View getVideoLoadingProgressView() {
2799 if (mVideoProgressView == null) {
2800 LayoutInflater inflater = LayoutInflater.from(BrowserActivity.this);
2801 mVideoProgressView = inflater.inflate(
2802 R.layout.video_loading_progress, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002803 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002804 return mVideoProgressView;
2805 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002806
Leon Scroggins8d5fa432009-10-02 15:55:59 -04002807 /*
2808 * The Object used to inform the WebView of the file to upload.
2809 */
2810 private ValueCallback<Uri> mUploadMessage;
2811
Grace Kloba22ac16e2009-10-07 18:00:23 -07002812 void openFileChooser(ValueCallback<Uri> uploadMsg) {
2813 if (mUploadMessage != null) return;
2814 mUploadMessage = uploadMsg;
2815 Intent i = new Intent(Intent.ACTION_GET_CONTENT);
2816 i.addCategory(Intent.CATEGORY_OPENABLE);
2817 i.setType("*/*");
2818 BrowserActivity.this.startActivityForResult(Intent.createChooser(i,
2819 getString(R.string.choose_upload)), FILE_SELECTED);
2820 }
2821
2822 // -------------------------------------------------------------------------
2823 // Implement functions for DownloadListener
2824 // -------------------------------------------------------------------------
2825
The Android Open Source Project0c908882009-03-03 19:32:16 -08002826 /**
2827 * Notify the host application a download should be done, or that
2828 * the data should be streamed if a streaming viewer is available.
2829 * @param url The full url to the content that should be downloaded
2830 * @param contentDisposition Content-disposition http header, if
2831 * present.
2832 * @param mimetype The mimetype of the content reported by the server
2833 * @param contentLength The file size reported by the server
2834 */
2835 public void onDownloadStart(String url, String userAgent,
2836 String contentDisposition, String mimetype, long contentLength) {
2837 // if we're dealing wih A/V content that's not explicitly marked
2838 // for download, check if it's streamable.
2839 if (contentDisposition == null
Patrick Scotte1fb9662009-08-31 14:31:52 -04002840 || !contentDisposition.regionMatches(
2841 true, 0, "attachment", 0, 10)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002842 // query the package manager to see if there's a registered handler
2843 // that matches.
2844 Intent intent = new Intent(Intent.ACTION_VIEW);
2845 intent.setDataAndType(Uri.parse(url), mimetype);
Patrick Scotte1fb9662009-08-31 14:31:52 -04002846 ResolveInfo info = getPackageManager().resolveActivity(intent,
2847 PackageManager.MATCH_DEFAULT_ONLY);
2848 if (info != null) {
2849 ComponentName myName = getComponentName();
2850 // If we resolved to ourselves, we don't want to attempt to
2851 // load the url only to try and download it again.
2852 if (!myName.getPackageName().equals(
2853 info.activityInfo.packageName)
2854 || !myName.getClassName().equals(
2855 info.activityInfo.name)) {
2856 // someone (other than us) knows how to handle this mime
2857 // type with this scheme, don't download.
2858 try {
2859 startActivity(intent);
2860 return;
2861 } catch (ActivityNotFoundException ex) {
2862 if (LOGD_ENABLED) {
2863 Log.d(LOGTAG, "activity not found for " + mimetype
2864 + " over " + Uri.parse(url).getScheme(),
2865 ex);
2866 }
2867 // Best behavior is to fall back to a download in this
2868 // case
The Android Open Source Project0c908882009-03-03 19:32:16 -08002869 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002870 }
2871 }
2872 }
2873 onDownloadStartNoStream(url, userAgent, contentDisposition, mimetype, contentLength);
2874 }
2875
Kristian Monsenfa52d172010-03-25 18:29:21 +00002876 // This is to work around the fact that java.net.URI throws Exceptions
2877 // instead of just encoding URL's properly
2878 // Helper method for onDownloadStartNoStream
2879 private static String encodePath(String path) {
2880 char[] chars = path.toCharArray();
2881
2882 boolean needed = false;
2883 for (char c : chars) {
2884 if (c == '[' || c == ']') {
2885 needed = true;
2886 break;
2887 }
2888 }
2889 if (needed == false) {
2890 return path;
2891 }
2892
2893 StringBuilder sb = new StringBuilder("");
2894 for (char c : chars) {
2895 if (c == '[' || c == ']') {
2896 sb.append('%');
2897 sb.append(Integer.toHexString(c));
2898 } else {
2899 sb.append(c);
2900 }
2901 }
2902
2903 return sb.toString();
2904 }
2905
The Android Open Source Project0c908882009-03-03 19:32:16 -08002906 /**
2907 * Notify the host application a download should be done, even if there
2908 * is a streaming viewer available for thise type.
2909 * @param url The full url to the content that should be downloaded
2910 * @param contentDisposition Content-disposition http header, if
2911 * present.
2912 * @param mimetype The mimetype of the content reported by the server
2913 * @param contentLength The file size reported by the server
2914 */
2915 /*package */ void onDownloadStartNoStream(String url, String userAgent,
2916 String contentDisposition, String mimetype, long contentLength) {
2917
2918 String filename = URLUtil.guessFileName(url,
2919 contentDisposition, mimetype);
2920
2921 // Check to see if we have an SDCard
2922 String status = Environment.getExternalStorageState();
2923 if (!status.equals(Environment.MEDIA_MOUNTED)) {
2924 int title;
2925 String msg;
2926
2927 // Check to see if the SDCard is busy, same as the music app
2928 if (status.equals(Environment.MEDIA_SHARED)) {
2929 msg = getString(R.string.download_sdcard_busy_dlg_msg);
2930 title = R.string.download_sdcard_busy_dlg_title;
2931 } else {
2932 msg = getString(R.string.download_no_sdcard_dlg_msg, filename);
2933 title = R.string.download_no_sdcard_dlg_title;
2934 }
2935
2936 new AlertDialog.Builder(this)
2937 .setTitle(title)
2938 .setIcon(android.R.drawable.ic_dialog_alert)
2939 .setMessage(msg)
2940 .setPositiveButton(R.string.ok, null)
2941 .show();
2942 return;
2943 }
2944
Kristian Monsenfa52d172010-03-25 18:29:21 +00002945 // java.net.URI is a lot stricter than KURL so we have to encode some
2946 // extra characters. Fix for b 2538060 and b 1634719
2947 WebAddress webAddress;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002948 try {
Kristian Monsenfa52d172010-03-25 18:29:21 +00002949 webAddress = new WebAddress(url);
2950 webAddress.mPath = encodePath(webAddress.mPath);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002951 } catch (Exception e) {
Kristian Monsenfa52d172010-03-25 18:29:21 +00002952 // This only happens for very bad urls, we want to chatch the
2953 // exception here
2954 Log.e(LOGTAG, "Exception trying to parse url:" + url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002955 return;
2956 }
2957
2958 // XXX: Have to use the old url since the cookies were stored using the
2959 // old percent-encoded url.
2960 String cookies = CookieManager.getInstance().getCookie(url);
2961
2962 ContentValues values = new ContentValues();
Kristian Monsenfa52d172010-03-25 18:29:21 +00002963 values.put(Downloads.Impl.COLUMN_URI, webAddress.toString());
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08002964 values.put(Downloads.Impl.COLUMN_COOKIE_DATA, cookies);
2965 values.put(Downloads.Impl.COLUMN_USER_AGENT, userAgent);
2966 values.put(Downloads.Impl.COLUMN_NOTIFICATION_PACKAGE,
The Android Open Source Project0c908882009-03-03 19:32:16 -08002967 getPackageName());
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08002968 values.put(Downloads.Impl.COLUMN_NOTIFICATION_CLASS,
Leon Scrogginsa563d092010-04-19 16:53:49 -04002969 OpenDownloadReceiver.class.getCanonicalName());
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08002970 values.put(Downloads.Impl.COLUMN_VISIBILITY,
2971 Downloads.Impl.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
2972 values.put(Downloads.Impl.COLUMN_MIME_TYPE, mimetype);
2973 values.put(Downloads.Impl.COLUMN_FILE_NAME_HINT, filename);
Kristian Monsenfa52d172010-03-25 18:29:21 +00002974 values.put(Downloads.Impl.COLUMN_DESCRIPTION, webAddress.mHost);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002975 if (contentLength > 0) {
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08002976 values.put(Downloads.Impl.COLUMN_TOTAL_BYTES, contentLength);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002977 }
2978 if (mimetype == null) {
2979 // We must have long pressed on a link or image to download it. We
2980 // are not sure of the mimetype in this case, so do a head request
2981 new FetchUrlMimeType(this).execute(values);
2982 } else {
2983 final Uri contentUri =
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08002984 getContentResolver().insert(Downloads.Impl.CONTENT_URI, values);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002985 }
Leon Scroggins9191a7f2010-03-18 14:44:44 -04002986 Toast.makeText(this, R.string.download_pending, Toast.LENGTH_SHORT)
2987 .show();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002988 }
2989
Grace Kloba22ac16e2009-10-07 18:00:23 -07002990 // -------------------------------------------------------------------------
2991
The Android Open Source Project0c908882009-03-03 19:32:16 -08002992 /**
2993 * Resets the lock icon. This method is called when we start a new load and
2994 * know the url to be loaded.
2995 */
2996 private void resetLockIcon(String url) {
2997 // Save the lock-icon state (we revert to it if the load gets cancelled)
Grace Kloba22ac16e2009-10-07 18:00:23 -07002998 mTabControl.getCurrentTab().resetLockIcon(url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002999 updateLockIconImage(LOCK_ICON_UNSECURE);
3000 }
3001
The Android Open Source Project0c908882009-03-03 19:32:16 -08003002 /**
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04003003 * Update the lock icon to correspond to our latest state.
3004 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003005 private void updateLockIconToLatest() {
3006 updateLockIconImage(mTabControl.getCurrentTab().getLockIconType());
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04003007 }
3008
3009 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08003010 * Updates the lock-icon image in the title-bar.
3011 */
3012 private void updateLockIconImage(int lockIconType) {
3013 Drawable d = null;
3014 if (lockIconType == LOCK_ICON_SECURE) {
3015 d = mSecLockIcon;
3016 } else if (lockIconType == LOCK_ICON_MIXED) {
3017 d = mMixLockIcon;
3018 }
Leon Scroggins68579392009-09-15 15:31:54 -04003019 mTitleBar.setLock(d);
Leon Scrogginsfe87bd32009-10-06 10:10:00 -04003020 mFakeTitleBar.setLock(d);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003021 }
3022
3023 /**
3024 * Displays a page-info dialog.
3025 * @param tab The tab to show info about
3026 * @param fromShowSSLCertificateOnError The flag that indicates whether
3027 * this dialog was opened from the SSL-certificate-on-error dialog or
3028 * not. This is important, since we need to know whether to return to
3029 * the parent dialog or simply dismiss.
3030 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003031 private void showPageInfo(final Tab tab,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003032 final boolean fromShowSSLCertificateOnError) {
3033 final LayoutInflater factory = LayoutInflater
3034 .from(this);
3035
3036 final View pageInfoView = factory.inflate(R.layout.page_info, null);
3037
3038 final WebView view = tab.getWebView();
3039
3040 String url = null;
3041 String title = null;
3042
3043 if (view == null) {
3044 url = tab.getUrl();
3045 title = tab.getTitle();
3046 } else if (view == mTabControl.getCurrentWebView()) {
3047 // Use the cached title and url if this is the current WebView
3048 url = mUrl;
3049 title = mTitle;
3050 } else {
3051 url = view.getUrl();
3052 title = view.getTitle();
3053 }
3054
3055 if (url == null) {
3056 url = "";
3057 }
3058 if (title == null) {
3059 title = "";
3060 }
3061
3062 ((TextView) pageInfoView.findViewById(R.id.address)).setText(url);
3063 ((TextView) pageInfoView.findViewById(R.id.title)).setText(title);
3064
3065 mPageInfoView = tab;
Leon Scrogginsc7b92f82010-01-11 18:17:31 -05003066 mPageInfoFromShowSSLCertificateOnError = fromShowSSLCertificateOnError;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003067
3068 AlertDialog.Builder alertDialogBuilder =
3069 new AlertDialog.Builder(this)
3070 .setTitle(R.string.page_info).setIcon(android.R.drawable.ic_dialog_info)
3071 .setView(pageInfoView)
3072 .setPositiveButton(
3073 R.string.ok,
3074 new DialogInterface.OnClickListener() {
3075 public void onClick(DialogInterface dialog,
3076 int whichButton) {
3077 mPageInfoDialog = null;
3078 mPageInfoView = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003079
3080 // if we came here from the SSL error dialog
3081 if (fromShowSSLCertificateOnError) {
3082 // go back to the SSL error dialog
3083 showSSLCertificateOnError(
3084 mSSLCertificateOnErrorView,
3085 mSSLCertificateOnErrorHandler,
3086 mSSLCertificateOnErrorError);
3087 }
3088 }
3089 })
3090 .setOnCancelListener(
3091 new DialogInterface.OnCancelListener() {
3092 public void onCancel(DialogInterface dialog) {
3093 mPageInfoDialog = null;
3094 mPageInfoView = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003095
3096 // if we came here from the SSL error dialog
3097 if (fromShowSSLCertificateOnError) {
3098 // go back to the SSL error dialog
3099 showSSLCertificateOnError(
3100 mSSLCertificateOnErrorView,
3101 mSSLCertificateOnErrorHandler,
3102 mSSLCertificateOnErrorError);
3103 }
3104 }
3105 });
3106
3107 // if we have a main top-level page SSL certificate set or a certificate
3108 // error
3109 if (fromShowSSLCertificateOnError ||
3110 (view != null && view.getCertificate() != null)) {
3111 // add a 'View Certificate' button
3112 alertDialogBuilder.setNeutralButton(
3113 R.string.view_certificate,
3114 new DialogInterface.OnClickListener() {
3115 public void onClick(DialogInterface dialog,
3116 int whichButton) {
3117 mPageInfoDialog = null;
3118 mPageInfoView = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003119
3120 // if we came here from the SSL error dialog
3121 if (fromShowSSLCertificateOnError) {
3122 // go back to the SSL error dialog
3123 showSSLCertificateOnError(
3124 mSSLCertificateOnErrorView,
3125 mSSLCertificateOnErrorHandler,
3126 mSSLCertificateOnErrorError);
3127 } else {
3128 // otherwise, display the top-most certificate from
3129 // the chain
3130 if (view.getCertificate() != null) {
3131 showSSLCertificate(tab);
3132 }
3133 }
3134 }
3135 });
3136 }
3137
3138 mPageInfoDialog = alertDialogBuilder.show();
3139 }
3140
3141 /**
3142 * Displays the main top-level page SSL certificate dialog
3143 * (accessible from the Page-Info dialog).
3144 * @param tab The tab to show certificate for.
3145 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003146 private void showSSLCertificate(final Tab tab) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003147 final View certificateView =
3148 inflateCertificateView(tab.getWebView().getCertificate());
3149 if (certificateView == null) {
3150 return;
3151 }
3152
3153 LayoutInflater factory = LayoutInflater.from(this);
3154
3155 final LinearLayout placeholder =
3156 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3157
3158 LinearLayout ll = (LinearLayout) factory.inflate(
3159 R.layout.ssl_success, placeholder);
3160 ((TextView)ll.findViewById(R.id.success))
3161 .setText(R.string.ssl_certificate_is_valid);
3162
3163 mSSLCertificateView = tab;
3164 mSSLCertificateDialog =
3165 new AlertDialog.Builder(this)
3166 .setTitle(R.string.ssl_certificate).setIcon(
3167 R.drawable.ic_dialog_browser_certificate_secure)
3168 .setView(certificateView)
3169 .setPositiveButton(R.string.ok,
3170 new DialogInterface.OnClickListener() {
3171 public void onClick(DialogInterface dialog,
3172 int whichButton) {
3173 mSSLCertificateDialog = null;
3174 mSSLCertificateView = null;
3175
3176 showPageInfo(tab, false);
3177 }
3178 })
3179 .setOnCancelListener(
3180 new DialogInterface.OnCancelListener() {
3181 public void onCancel(DialogInterface dialog) {
3182 mSSLCertificateDialog = null;
3183 mSSLCertificateView = null;
3184
3185 showPageInfo(tab, false);
3186 }
3187 })
3188 .show();
3189 }
3190
3191 /**
3192 * Displays the SSL error certificate dialog.
3193 * @param view The target web-view.
3194 * @param handler The SSL error handler responsible for cancelling the
3195 * connection that resulted in an SSL error or proceeding per user request.
3196 * @param error The SSL error object.
3197 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003198 void showSSLCertificateOnError(
The Android Open Source Project0c908882009-03-03 19:32:16 -08003199 final WebView view, final SslErrorHandler handler, final SslError error) {
3200
3201 final View certificateView =
3202 inflateCertificateView(error.getCertificate());
3203 if (certificateView == null) {
3204 return;
3205 }
3206
3207 LayoutInflater factory = LayoutInflater.from(this);
3208
3209 final LinearLayout placeholder =
3210 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3211
3212 if (error.hasError(SslError.SSL_UNTRUSTED)) {
3213 LinearLayout ll = (LinearLayout)factory
3214 .inflate(R.layout.ssl_warning, placeholder);
3215 ((TextView)ll.findViewById(R.id.warning))
3216 .setText(R.string.ssl_untrusted);
3217 }
3218
3219 if (error.hasError(SslError.SSL_IDMISMATCH)) {
3220 LinearLayout ll = (LinearLayout)factory
3221 .inflate(R.layout.ssl_warning, placeholder);
3222 ((TextView)ll.findViewById(R.id.warning))
3223 .setText(R.string.ssl_mismatch);
3224 }
3225
3226 if (error.hasError(SslError.SSL_EXPIRED)) {
3227 LinearLayout ll = (LinearLayout)factory
3228 .inflate(R.layout.ssl_warning, placeholder);
3229 ((TextView)ll.findViewById(R.id.warning))
3230 .setText(R.string.ssl_expired);
3231 }
3232
3233 if (error.hasError(SslError.SSL_NOTYETVALID)) {
3234 LinearLayout ll = (LinearLayout)factory
3235 .inflate(R.layout.ssl_warning, placeholder);
3236 ((TextView)ll.findViewById(R.id.warning))
3237 .setText(R.string.ssl_not_yet_valid);
3238 }
3239
3240 mSSLCertificateOnErrorHandler = handler;
3241 mSSLCertificateOnErrorView = view;
3242 mSSLCertificateOnErrorError = error;
3243 mSSLCertificateOnErrorDialog =
3244 new AlertDialog.Builder(this)
3245 .setTitle(R.string.ssl_certificate).setIcon(
3246 R.drawable.ic_dialog_browser_certificate_partially_secure)
3247 .setView(certificateView)
3248 .setPositiveButton(R.string.ok,
3249 new DialogInterface.OnClickListener() {
3250 public void onClick(DialogInterface dialog,
3251 int whichButton) {
3252 mSSLCertificateOnErrorDialog = null;
3253 mSSLCertificateOnErrorView = null;
3254 mSSLCertificateOnErrorHandler = null;
3255 mSSLCertificateOnErrorError = null;
3256
Grace Kloba22ac16e2009-10-07 18:00:23 -07003257 view.getWebViewClient().onReceivedSslError(
3258 view, handler, error);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003259 }
3260 })
3261 .setNeutralButton(R.string.page_info_view,
3262 new DialogInterface.OnClickListener() {
3263 public void onClick(DialogInterface dialog,
3264 int whichButton) {
3265 mSSLCertificateOnErrorDialog = null;
3266
3267 // do not clear the dialog state: we will
3268 // need to show the dialog again once the
3269 // user is done exploring the page-info details
3270
3271 showPageInfo(mTabControl.getTabFromView(view),
3272 true);
3273 }
3274 })
3275 .setOnCancelListener(
3276 new DialogInterface.OnCancelListener() {
3277 public void onCancel(DialogInterface dialog) {
3278 mSSLCertificateOnErrorDialog = null;
3279 mSSLCertificateOnErrorView = null;
3280 mSSLCertificateOnErrorHandler = null;
3281 mSSLCertificateOnErrorError = null;
3282
Grace Kloba22ac16e2009-10-07 18:00:23 -07003283 view.getWebViewClient().onReceivedSslError(
3284 view, handler, error);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003285 }
3286 })
3287 .show();
3288 }
3289
3290 /**
3291 * Inflates the SSL certificate view (helper method).
3292 * @param certificate The SSL certificate.
3293 * @return The resultant certificate view with issued-to, issued-by,
3294 * issued-on, expires-on, and possibly other fields set.
3295 * If the input certificate is null, returns null.
3296 */
3297 private View inflateCertificateView(SslCertificate certificate) {
3298 if (certificate == null) {
3299 return null;
3300 }
3301
3302 LayoutInflater factory = LayoutInflater.from(this);
3303
3304 View certificateView = factory.inflate(
3305 R.layout.ssl_certificate, null);
3306
3307 // issued to:
3308 SslCertificate.DName issuedTo = certificate.getIssuedTo();
3309 if (issuedTo != null) {
3310 ((TextView) certificateView.findViewById(R.id.to_common))
3311 .setText(issuedTo.getCName());
3312 ((TextView) certificateView.findViewById(R.id.to_org))
3313 .setText(issuedTo.getOName());
3314 ((TextView) certificateView.findViewById(R.id.to_org_unit))
3315 .setText(issuedTo.getUName());
3316 }
3317
3318 // issued by:
3319 SslCertificate.DName issuedBy = certificate.getIssuedBy();
3320 if (issuedBy != null) {
3321 ((TextView) certificateView.findViewById(R.id.by_common))
3322 .setText(issuedBy.getCName());
3323 ((TextView) certificateView.findViewById(R.id.by_org))
3324 .setText(issuedBy.getOName());
3325 ((TextView) certificateView.findViewById(R.id.by_org_unit))
3326 .setText(issuedBy.getUName());
3327 }
3328
3329 // issued on:
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003330 String issuedOn = formatCertificateDate(
3331 certificate.getValidNotBeforeDate());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003332 ((TextView) certificateView.findViewById(R.id.issued_on))
3333 .setText(issuedOn);
3334
3335 // expires on:
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003336 String expiresOn = formatCertificateDate(
3337 certificate.getValidNotAfterDate());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003338 ((TextView) certificateView.findViewById(R.id.expires_on))
3339 .setText(expiresOn);
3340
3341 return certificateView;
3342 }
3343
3344 /**
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003345 * Formats the certificate date to a properly localized date string.
The Android Open Source Project0c908882009-03-03 19:32:16 -08003346 * @return Properly localized version of the certificate date string and
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003347 * the "" if it fails to localize.
The Android Open Source Project0c908882009-03-03 19:32:16 -08003348 */
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003349 private String formatCertificateDate(Date certificateDate) {
3350 if (certificateDate == null) {
3351 return "";
The Android Open Source Project0c908882009-03-03 19:32:16 -08003352 }
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003353 String formattedDate = DateFormat.getDateFormat(this).format(certificateDate);
3354 if (formattedDate == null) {
3355 return "";
3356 }
3357 return formattedDate;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003358 }
3359
3360 /**
3361 * Displays an http-authentication dialog.
3362 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003363 void showHttpAuthentication(final HttpAuthHandler handler,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003364 final String host, final String realm, final String title,
3365 final String name, final String password, int focusId) {
3366 LayoutInflater factory = LayoutInflater.from(this);
3367 final View v = factory
3368 .inflate(R.layout.http_authentication, null);
3369 if (name != null) {
3370 ((EditText) v.findViewById(R.id.username_edit)).setText(name);
3371 }
3372 if (password != null) {
3373 ((EditText) v.findViewById(R.id.password_edit)).setText(password);
3374 }
3375
3376 String titleText = title;
3377 if (titleText == null) {
3378 titleText = getText(R.string.sign_in_to).toString().replace(
3379 "%s1", host).replace("%s2", realm);
3380 }
3381
3382 mHttpAuthHandler = handler;
3383 AlertDialog dialog = new AlertDialog.Builder(this)
3384 .setTitle(titleText)
3385 .setIcon(android.R.drawable.ic_dialog_alert)
3386 .setView(v)
3387 .setPositiveButton(R.string.action,
3388 new DialogInterface.OnClickListener() {
3389 public void onClick(DialogInterface dialog,
3390 int whichButton) {
3391 String nm = ((EditText) v
3392 .findViewById(R.id.username_edit))
3393 .getText().toString();
3394 String pw = ((EditText) v
3395 .findViewById(R.id.password_edit))
3396 .getText().toString();
3397 BrowserActivity.this.setHttpAuthUsernamePassword
3398 (host, realm, nm, pw);
3399 handler.proceed(nm, pw);
3400 mHttpAuthenticationDialog = null;
3401 mHttpAuthHandler = null;
3402 }})
3403 .setNegativeButton(R.string.cancel,
3404 new DialogInterface.OnClickListener() {
3405 public void onClick(DialogInterface dialog,
3406 int whichButton) {
3407 handler.cancel();
3408 BrowserActivity.this.resetTitleAndRevertLockIcon();
3409 mHttpAuthenticationDialog = null;
3410 mHttpAuthHandler = null;
3411 }})
3412 .setOnCancelListener(new DialogInterface.OnCancelListener() {
3413 public void onCancel(DialogInterface dialog) {
3414 handler.cancel();
3415 BrowserActivity.this.resetTitleAndRevertLockIcon();
3416 mHttpAuthenticationDialog = null;
3417 mHttpAuthHandler = null;
3418 }})
3419 .create();
3420 // Make the IME appear when the dialog is displayed if applicable.
3421 dialog.getWindow().setSoftInputMode(
3422 WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
3423 dialog.show();
3424 if (focusId != 0) {
3425 dialog.findViewById(focusId).requestFocus();
3426 } else {
3427 v.findViewById(R.id.username_edit).requestFocus();
3428 }
3429 mHttpAuthenticationDialog = dialog;
3430 }
3431
3432 public int getProgress() {
3433 WebView w = mTabControl.getCurrentWebView();
3434 if (w != null) {
3435 return w.getProgress();
3436 } else {
3437 return 100;
3438 }
3439 }
3440
3441 /**
3442 * Set HTTP authentication password.
3443 *
3444 * @param host The host for the password
3445 * @param realm The realm for the password
3446 * @param username The username for the password. If it is null, it means
3447 * password can't be saved.
3448 * @param password The password
3449 */
3450 public void setHttpAuthUsernamePassword(String host, String realm,
3451 String username,
3452 String password) {
Steve Block95a53b22010-03-25 17:24:58 +00003453 WebView w = getTopWindow();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003454 if (w != null) {
3455 w.setHttpAuthUsernamePassword(host, realm, username, password);
3456 }
3457 }
3458
3459 /**
3460 * connectivity manager says net has come or gone... inform the user
3461 * @param up true if net has come up, false if net has gone down
3462 */
3463 public void onNetworkToggle(boolean up) {
3464 if (up == mIsNetworkUp) {
3465 return;
3466 } else if (up) {
3467 mIsNetworkUp = true;
3468 if (mAlertDialog != null) {
3469 mAlertDialog.cancel();
3470 mAlertDialog = null;
3471 }
3472 } else {
3473 mIsNetworkUp = false;
Patrick Scotteb6ab2a2009-09-16 10:00:17 -04003474 if (mInLoad) {
3475 createAndShowNetworkDialog();
3476 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003477 }
3478 WebView w = mTabControl.getCurrentWebView();
3479 if (w != null) {
3480 w.setNetworkAvailable(up);
3481 }
3482 }
3483
Grace Kloba22ac16e2009-10-07 18:00:23 -07003484 boolean isNetworkUp() {
3485 return mIsNetworkUp;
3486 }
3487
Patrick Scotteb6ab2a2009-09-16 10:00:17 -04003488 // This method shows the network dialog alerting the user that the net is
3489 // down. It will only show the dialog if mAlertDialog is null.
3490 private void createAndShowNetworkDialog() {
3491 if (mAlertDialog == null) {
3492 mAlertDialog = new AlertDialog.Builder(this)
3493 .setTitle(R.string.loadSuspendedTitle)
3494 .setMessage(R.string.loadSuspended)
3495 .setPositiveButton(R.string.ok, null)
3496 .show();
3497 }
3498 }
3499
The Android Open Source Project0c908882009-03-03 19:32:16 -08003500 @Override
3501 protected void onActivityResult(int requestCode, int resultCode,
3502 Intent intent) {
Grace Klobabb394f32009-11-19 10:26:37 -08003503 if (getTopWindow() == null) return;
3504
The Android Open Source Project0c908882009-03-03 19:32:16 -08003505 switch (requestCode) {
3506 case COMBO_PAGE:
3507 if (resultCode == RESULT_OK && intent != null) {
3508 String data = intent.getAction();
3509 Bundle extras = intent.getExtras();
3510 if (extras != null && extras.getBoolean("new_window", false)) {
Leon Scroggins25d35472009-09-15 11:37:27 -04003511 openTab(data);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003512 } else {
Grace Kloba22ac16e2009-10-07 18:00:23 -07003513 final Tab currentTab =
The Android Open Source Project0c908882009-03-03 19:32:16 -08003514 mTabControl.getCurrentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04003515 dismissSubWindow(currentTab);
3516 if (data != null && data.length() != 0) {
Leon Scroggins92472e82010-02-17 16:32:28 -05003517 loadUrl(getTopWindow(), data);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003518 }
3519 }
3520 }
Leon Scrogginsfde97462010-01-11 13:06:21 -05003521 // Deliberately fall through to PREFERENCES_PAGE, since the
3522 // same extra may be attached to the COMBO_PAGE
3523 case PREFERENCES_PAGE:
3524 if (resultCode == RESULT_OK && intent != null) {
3525 String action = intent.getStringExtra(Intent.EXTRA_TEXT);
3526 if (BrowserSettings.PREF_CLEAR_HISTORY.equals(action)) {
3527 mTabControl.removeParentChildRelationShips();
3528 }
3529 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003530 break;
Leon Scroggins8d5fa432009-10-02 15:55:59 -04003531 // Choose a file from the file picker.
3532 case FILE_SELECTED:
3533 if (null == mUploadMessage) break;
3534 Uri result = intent == null || resultCode != RESULT_OK ? null
3535 : intent.getData();
3536 mUploadMessage.onReceiveValue(result);
3537 mUploadMessage = null;
3538 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003539 default:
3540 break;
3541 }
Leon Scroggins30444232009-09-04 18:36:20 -04003542 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003543 }
3544
3545 /*
3546 * This method is called as a result of the user selecting the options
Leon Scrogginsf08809b2010-01-21 09:27:46 -05003547 * menu to see the download window. It shows the download window on top of
3548 * the current window.
The Android Open Source Project0c908882009-03-03 19:32:16 -08003549 */
Leon Scroggins IIIa682a3c2010-09-27 12:32:40 -04003550 private void viewDownloads() {
3551 Intent intent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
3552 startActivity(intent);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003553 }
3554
Leon Scroggins160a7e72009-08-14 18:28:01 -04003555 /**
3556 * Open the Go page.
3557 * @param startWithHistory If true, open starting on the history tab.
3558 * Otherwise, start with the bookmarks tab.
Leon Scroggins160a7e72009-08-14 18:28:01 -04003559 */
Leon Scroggins30444232009-09-04 18:36:20 -04003560 /* package */ void bookmarksOrHistoryPicker(boolean startWithHistory) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003561 WebView current = mTabControl.getCurrentWebView();
3562 if (current == null) {
3563 return;
3564 }
3565 Intent intent = new Intent(this,
3566 CombinedBookmarkHistoryActivity.class);
3567 String title = current.getTitle();
3568 String url = current.getUrl();
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01003569 Bitmap thumbnail = createScreenshot(current);
3570
The Android Open Source Project0c908882009-03-03 19:32:16 -08003571 // Just in case the user opens bookmarks before a page finishes loading
3572 // so the current history item, and therefore the page, is null.
3573 if (null == url) {
3574 url = mLastEnteredUrl;
3575 // This can happen.
3576 if (null == url) {
3577 url = mSettings.getHomePage();
3578 }
3579 }
3580 // In case the web page has not yet received its associated title.
3581 if (title == null) {
3582 title = url;
3583 }
3584 intent.putExtra("title", title);
3585 intent.putExtra("url", url);
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01003586 intent.putExtra("thumbnail", thumbnail);
Leon Scroggins30444232009-09-04 18:36:20 -04003587 // Disable opening in a new window if we have maxed out the windows
Grace Kloba22ac16e2009-10-07 18:00:23 -07003588 intent.putExtra("disable_new_window", !mTabControl.canCreateNewTab());
Patrick Scott3918d442009-08-04 13:22:29 -04003589 intent.putExtra("touch_icon_url", current.getTouchIconUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003590 if (startWithHistory) {
3591 intent.putExtra(CombinedBookmarkHistoryActivity.STARTING_TAB,
3592 CombinedBookmarkHistoryActivity.HISTORY_TAB);
3593 }
3594 startActivityForResult(intent, COMBO_PAGE);
3595 }
3596
3597 // Called when loading from context menu or LOAD_URL message
Leon Scroggins92472e82010-02-17 16:32:28 -05003598 private void loadUrlFromContext(WebView view, String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003599 // In case the user enters nothing.
3600 if (url != null && url.length() != 0 && view != null) {
3601 url = smartUrlFilter(url);
Grace Kloba22ac16e2009-10-07 18:00:23 -07003602 if (!view.getWebViewClient().shouldOverrideUrlLoading(view, url)) {
Leon Scroggins92472e82010-02-17 16:32:28 -05003603 loadUrl(view, url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003604 }
3605 }
3606 }
3607
Leon Scroggins92472e82010-02-17 16:32:28 -05003608 /**
3609 * Load the URL into the given WebView and update the title bar
3610 * to reflect the new load. Call this instead of WebView.loadUrl
3611 * directly.
3612 * @param view The WebView used to load url.
3613 * @param url The URL to load.
3614 */
3615 private void loadUrl(WebView view, String url) {
3616 updateTitleBarForNewLoad(view, url);
3617 view.loadUrl(url);
3618 }
3619
3620 /**
3621 * Load UrlData into a Tab and update the title bar to reflect the new
3622 * load. Call this instead of UrlData.loadIn directly.
3623 * @param t The Tab used to load.
3624 * @param data The UrlData being loaded.
3625 */
3626 private void loadUrlDataIn(Tab t, UrlData data) {
3627 updateTitleBarForNewLoad(t.getWebView(), data.mUrl);
3628 data.loadIn(t);
3629 }
3630
3631 /**
3632 * If the WebView is the top window, update the title bar to reflect
3633 * loading the new URL. i.e. set its text, clear the favicon (which
3634 * will be set once the page begins loading), and set the progress to
3635 * INITIAL_PROGRESS to show that the page has begun to load. Called
3636 * by loadUrl and loadUrlDataIn.
3637 * @param view The WebView that is starting a load.
3638 * @param url The URL that is being loaded.
3639 */
3640 private void updateTitleBarForNewLoad(WebView view, String url) {
3641 if (view == getTopWindow()) {
3642 setUrlTitle(url, null);
3643 setFavicon(null);
3644 onProgressChanged(view, INITIAL_PROGRESS);
3645 }
3646 }
3647
The Android Open Source Project0c908882009-03-03 19:32:16 -08003648 private String smartUrlFilter(Uri inUri) {
3649 if (inUri != null) {
3650 return smartUrlFilter(inUri.toString());
3651 }
3652 return null;
3653 }
3654
Feng Qianb34f87a2009-03-24 21:27:26 -07003655 protected static final Pattern ACCEPTED_URI_SCHEMA = Pattern.compile(
The Android Open Source Project0c908882009-03-03 19:32:16 -08003656 "(?i)" + // switch on case insensitive matching
3657 "(" + // begin group for schema
3658 "(?:http|https|file):\\/\\/" +
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003659 "|(?:inline|data|about|content|javascript):" +
The Android Open Source Project0c908882009-03-03 19:32:16 -08003660 ")" +
3661 "(.*)" );
3662
3663 /**
3664 * Attempts to determine whether user input is a URL or search
3665 * terms. Anything with a space is passed to search.
3666 *
3667 * Converts to lowercase any mistakenly uppercased schema (i.e.,
3668 * "Http://" converts to "http://"
3669 *
3670 * @return Original or modified URL
3671 *
3672 */
3673 String smartUrlFilter(String url) {
3674
3675 String inUrl = url.trim();
3676 boolean hasSpace = inUrl.indexOf(' ') != -1;
3677
3678 Matcher matcher = ACCEPTED_URI_SCHEMA.matcher(inUrl);
3679 if (matcher.matches()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003680 // force scheme to lowercase
3681 String scheme = matcher.group(1);
3682 String lcScheme = scheme.toLowerCase();
3683 if (!lcScheme.equals(scheme)) {
Mitsuru Oshima123ecfb2009-05-18 19:11:14 -07003684 inUrl = lcScheme + matcher.group(2);
3685 }
3686 if (hasSpace) {
3687 inUrl = inUrl.replace(" ", "%20");
The Android Open Source Project0c908882009-03-03 19:32:16 -08003688 }
3689 return inUrl;
3690 }
Leon Scroggins956cf012010-10-07 13:51:57 -04003691 if (!hasSpace) {
Dan Egnor5ee906c2009-11-18 12:11:49 -08003692 if (Patterns.WEB_URL.matcher(inUrl).matches()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003693 return URLUtil.guessUrl(inUrl);
3694 }
3695 }
3696
Leon Scroggins956cf012010-10-07 13:51:57 -04003697 // FIXME: Is this the correct place to add to searches?
3698 // what if someone else calls this function?
3699
The Android Open Source Project0c908882009-03-03 19:32:16 -08003700 Browser.addSearchUrl(mResolver, inUrl);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07003701 return URLUtil.composeSearchUrl(inUrl, QuickSearch_G, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003702 }
3703
Ben Murdochbff2d602009-07-01 20:19:05 +01003704 /* package */ void setShouldShowErrorConsole(boolean flag) {
3705 if (flag == mShouldShowErrorConsole) {
3706 // Nothing to do.
3707 return;
3708 }
Leon Scroggins IIIa9e35b62010-09-16 15:30:15 -04003709 Tab t = mTabControl.getCurrentTab();
3710 if (t == null) {
3711 // There is no current tab so we cannot toggle the error console
3712 return;
3713 }
Ben Murdochbff2d602009-07-01 20:19:05 +01003714
3715 mShouldShowErrorConsole = flag;
3716
Leon Scroggins IIIa9e35b62010-09-16 15:30:15 -04003717 ErrorConsoleView errorConsole = t.getErrorConsole(true);
Ben Murdochbff2d602009-07-01 20:19:05 +01003718
3719 if (flag) {
3720 // Setting the show state of the console will cause it's the layout to be inflated.
3721 if (errorConsole.numberOfErrors() > 0) {
3722 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
3723 } else {
3724 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
3725 }
3726
3727 // Now we can add it to the main view.
3728 mErrorConsoleContainer.addView(errorConsole,
Romain Guy15b8ec62010-01-08 15:06:43 -08003729 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
Ben Murdochbff2d602009-07-01 20:19:05 +01003730 ViewGroup.LayoutParams.WRAP_CONTENT));
3731 } else {
3732 mErrorConsoleContainer.removeView(errorConsole);
3733 }
3734
3735 }
3736
Grace Kloba22ac16e2009-10-07 18:00:23 -07003737 boolean shouldShowErrorConsole() {
3738 return mShouldShowErrorConsole;
3739 }
3740
Andrei Popescu163ab742009-10-20 17:58:23 +01003741 private void setStatusBarVisibility(boolean visible) {
3742 int flag = visible ? 0 : WindowManager.LayoutParams.FLAG_FULLSCREEN;
3743 getWindow().setFlags(flag, WindowManager.LayoutParams.FLAG_FULLSCREEN);
3744 }
3745
Andrei Popescu56199cc2010-01-12 22:39:16 +00003746
3747 private void sendNetworkType(String type, String subtype) {
3748 WebView w = mTabControl.getCurrentWebView();
3749 if (w != null) {
3750 w.setNetworkType(type, subtype);
3751 }
3752 }
3753
Andrei Popescu30995e72010-02-09 16:59:58 +00003754 private void packageChanged(String packageName, boolean wasAdded) {
3755 WebView w = mTabControl.getCurrentWebView();
3756 if (w == null) {
3757 return;
3758 }
3759
3760 if (wasAdded) {
3761 w.addPackageName(packageName);
3762 } else {
3763 w.removePackageName(packageName);
3764 }
3765 }
3766
3767 private void addPackageNames(Set<String> packageNames) {
3768 WebView w = mTabControl.getCurrentWebView();
3769 if (w == null) {
3770 return;
3771 }
3772
3773 w.addPackageNames(packageNames);
3774 }
3775
3776 private void getInstalledPackages() {
3777 AsyncTask<Void, Void, Set<String> > task =
3778 new AsyncTask<Void, Void, Set<String> >() {
3779 protected Set<String> doInBackground(Void... unused) {
3780 Set<String> installedPackages = new HashSet<String>();
3781 PackageManager pm = BrowserActivity.this.getPackageManager();
3782 if (pm != null) {
3783 List<PackageInfo> packages = pm.getInstalledPackages(0);
3784 for (PackageInfo p : packages) {
3785 if (BrowserActivity.this.sGoogleApps.contains(p.packageName)) {
3786 installedPackages.add(p.packageName);
3787 }
3788 }
3789 }
3790
3791 return installedPackages;
3792 }
3793
3794 // Executes on the UI thread
3795 protected void onPostExecute(Set<String> installedPackages) {
3796 addPackageNames(installedPackages);
3797 }
3798 };
3799 task.execute();
3800 }
3801
Grace Klobaeb6eef42009-09-15 17:56:32 -07003802 final static int LOCK_ICON_UNSECURE = 0;
3803 final static int LOCK_ICON_SECURE = 1;
3804 final static int LOCK_ICON_MIXED = 2;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003805
The Android Open Source Project0c908882009-03-03 19:32:16 -08003806 private BrowserSettings mSettings;
3807 private TabControl mTabControl;
3808 private ContentResolver mResolver;
3809 private FrameLayout mContentView;
Andrei Popescuadc008d2009-06-26 14:11:30 +01003810 private View mCustomView;
3811 private FrameLayout mCustomViewContainer;
Andrei Popescuc9b55562009-07-07 10:51:15 +01003812 private WebChromeClient.CustomViewCallback mCustomViewCallback;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003813
3814 // FIXME, temp address onPrepareMenu performance problem. When we move everything out of
3815 // view, we should rewrite this.
3816 private int mCurrentMenuState = 0;
3817 private int mMenuState = R.id.MAIN_MENU;
Andrei Popescuadc008d2009-06-26 14:11:30 +01003818 private int mOldMenuState = EMPTY_MENU;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003819 private static final int EMPTY_MENU = -1;
3820 private Menu mMenu;
3821
3822 private FindDialog mFindDialog;
Cary Clark2c326e62010-08-19 18:40:57 -04003823 private SelectDialog mSelectDialog;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003824 // Used to prevent chording to result in firing two shortcuts immediately
3825 // one after another. Fixes bug 1211714.
3826 boolean mCanChord;
3827
3828 private boolean mInLoad;
3829 private boolean mIsNetworkUp;
Ben Murdochb7cc8b42009-09-28 10:59:09 +01003830 private boolean mDidStopLoad;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003831
Cary Clark1f10cbf2010-03-22 11:45:23 -04003832 /* package */ boolean mActivityInPause = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003833
3834 private boolean mMenuIsDown;
3835
The Android Open Source Project0c908882009-03-03 19:32:16 -08003836 private static boolean mInTrace;
3837
3838 // Performance probe
3839 private static final int[] SYSTEM_CPU_FORMAT = new int[] {
3840 Process.PROC_SPACE_TERM | Process.PROC_COMBINE,
3841 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 1: user time
3842 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 2: nice time
3843 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 3: sys time
3844 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 4: idle time
3845 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 5: iowait time
3846 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 6: irq time
3847 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG // 7: softirq time
3848 };
3849
3850 private long mStart;
3851 private long mProcessStart;
3852 private long mUserStart;
3853 private long mSystemStart;
3854 private long mIdleStart;
3855 private long mIrqStart;
3856
3857 private long mUiStart;
3858
3859 private Drawable mMixLockIcon;
3860 private Drawable mSecLockIcon;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003861
3862 /* hold a ref so we can auto-cancel if necessary */
3863 private AlertDialog mAlertDialog;
3864
The Android Open Source Project0c908882009-03-03 19:32:16 -08003865 // The up-to-date URL and title (these can be different from those stored
3866 // in WebView, since it takes some time for the information in WebView to
3867 // get updated)
3868 private String mUrl;
3869 private String mTitle;
3870
3871 // As PageInfo has different style for landscape / portrait, we have
3872 // to re-open it when configuration changed
3873 private AlertDialog mPageInfoDialog;
Grace Kloba22ac16e2009-10-07 18:00:23 -07003874 private Tab mPageInfoView;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003875 // If the Page-Info dialog is launched from the SSL-certificate-on-error
3876 // dialog, we should not just dismiss it, but should get back to the
3877 // SSL-certificate-on-error dialog. This flag is used to store this state
Leon Scrogginsc7b92f82010-01-11 18:17:31 -05003878 private boolean mPageInfoFromShowSSLCertificateOnError;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003879
3880 // as SSLCertificateOnError has different style for landscape / portrait,
3881 // we have to re-open it when configuration changed
3882 private AlertDialog mSSLCertificateOnErrorDialog;
3883 private WebView mSSLCertificateOnErrorView;
3884 private SslErrorHandler mSSLCertificateOnErrorHandler;
3885 private SslError mSSLCertificateOnErrorError;
3886
3887 // as SSLCertificate has different style for landscape / portrait, we
3888 // have to re-open it when configuration changed
3889 private AlertDialog mSSLCertificateDialog;
Grace Kloba22ac16e2009-10-07 18:00:23 -07003890 private Tab mSSLCertificateView;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003891
3892 // as HttpAuthentication has different style for landscape / portrait, we
3893 // have to re-open it when configuration changed
3894 private AlertDialog mHttpAuthenticationDialog;
3895 private HttpAuthHandler mHttpAuthHandler;
3896
3897 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_PARAMS =
3898 new FrameLayout.LayoutParams(
Romain Guy15b8ec62010-01-08 15:06:43 -08003899 ViewGroup.LayoutParams.MATCH_PARENT,
3900 ViewGroup.LayoutParams.MATCH_PARENT);
Andrei Popescuadc008d2009-06-26 14:11:30 +01003901 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_GRAVITY_CENTER =
3902 new FrameLayout.LayoutParams(
Romain Guy15b8ec62010-01-08 15:06:43 -08003903 ViewGroup.LayoutParams.MATCH_PARENT,
3904 ViewGroup.LayoutParams.MATCH_PARENT,
Andrei Popescuadc008d2009-06-26 14:11:30 +01003905 Gravity.CENTER);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07003906 // Google search
3907 final static String QuickSearch_G = "http://www.google.com/m?q=%s";
The Android Open Source Project0c908882009-03-03 19:32:16 -08003908
3909 final static String QUERY_PLACE_HOLDER = "%s";
3910
3911 // "source" parameter for Google search through search key
3912 final static String GOOGLE_SEARCH_SOURCE_SEARCHKEY = "browser-key";
3913 // "source" parameter for Google search through goto menu
3914 final static String GOOGLE_SEARCH_SOURCE_GOTO = "browser-goto";
3915 // "source" parameter for Google search through simplily type
3916 final static String GOOGLE_SEARCH_SOURCE_TYPE = "browser-type";
3917 // "source" parameter for Google search suggested by the browser
3918 final static String GOOGLE_SEARCH_SOURCE_SUGGEST = "browser-suggest";
3919 // "source" parameter for Google search from unknown source
3920 final static String GOOGLE_SEARCH_SOURCE_UNKNOWN = "unknown";
3921
3922 private final static String LOGTAG = "browser";
3923
The Android Open Source Project0c908882009-03-03 19:32:16 -08003924 private String mLastEnteredUrl;
3925
3926 private PowerManager.WakeLock mWakeLock;
3927 private final static int WAKELOCK_TIMEOUT = 5 * 60 * 1000; // 5 minutes
3928
3929 private Toast mStopToast;
3930
Leon Scroggins68579392009-09-15 15:31:54 -04003931 private TitleBar mTitleBar;
Leon Scroggins81db3662009-06-04 17:45:11 -04003932
Ben Murdochbff2d602009-07-01 20:19:05 +01003933 private LinearLayout mErrorConsoleContainer = null;
3934 private boolean mShouldShowErrorConsole = false;
3935
The Android Open Source Project0c908882009-03-03 19:32:16 -08003936 // As the ids are dynamically created, we can't guarantee that they will
3937 // be in sequence, so this static array maps ids to a window number.
3938 final static private int[] WINDOW_SHORTCUT_ID_ARRAY =
3939 { R.id.window_one_menu_id, R.id.window_two_menu_id, R.id.window_three_menu_id,
3940 R.id.window_four_menu_id, R.id.window_five_menu_id, R.id.window_six_menu_id,
3941 R.id.window_seven_menu_id, R.id.window_eight_menu_id };
3942
3943 // monitor platform changes
3944 private IntentFilter mNetworkStateChangedFilter;
3945 private BroadcastReceiver mNetworkStateIntentReceiver;
3946
Grace Klobab4da0ad2009-05-14 14:45:40 -07003947 private BroadcastReceiver mPackageInstallationReceiver;
3948
Bjorn Bringerta7611812010-03-24 11:12:02 +00003949 private SystemAllowGeolocationOrigins mSystemAllowGeolocationOrigins;
3950
The Android Open Source Project0c908882009-03-03 19:32:16 -08003951 // activity requestCode
Nicolas Roard78a98e42009-05-11 13:34:17 +01003952 final static int COMBO_PAGE = 1;
Nicolas Roard78a98e42009-05-11 13:34:17 +01003953 final static int PREFERENCES_PAGE = 3;
Leon Scroggins8d5fa432009-10-02 15:55:59 -04003954 final static int FILE_SELECTED = 4;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003955
Andrei Popescu540035d2009-09-18 18:59:20 +01003956 // the default <video> poster
3957 private Bitmap mDefaultVideoPoster;
3958 // the video progress view
3959 private View mVideoProgressView;
3960
Andrei Popescu30995e72010-02-09 16:59:58 +00003961 // The Google packages we monitor for the navigator.isApplicationInstalled()
3962 // API. Add as needed.
3963 private static Set<String> sGoogleApps;
3964 static {
3965 sGoogleApps = new HashSet<String>();
3966 sGoogleApps.add("com.google.android.youtube");
3967 }
3968
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003969 /**
3970 * A UrlData class to abstract how the content will be set to WebView.
3971 * This base class uses loadUrl to show the content.
3972 */
Leon Scroggins6eac63e2010-03-15 18:19:14 -04003973 /* package */ static class UrlData {
Grace Kloba068e48b2010-01-26 18:11:27 -08003974 final String mUrl;
3975 final Map<String, String> mHeaders;
Leon Scroggins58d56c62010-01-28 15:12:40 -05003976 final Intent mVoiceIntent;
Grace Kloba60e095c2009-06-16 11:50:55 -07003977
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003978 UrlData(String url) {
3979 this.mUrl = url;
Grace Kloba068e48b2010-01-26 18:11:27 -08003980 this.mHeaders = null;
Leon Scroggins58d56c62010-01-28 15:12:40 -05003981 this.mVoiceIntent = null;
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003982 }
Grace Kloba60e095c2009-06-16 11:50:55 -07003983
Leon Scroggins58d56c62010-01-28 15:12:40 -05003984 UrlData(String url, Map<String, String> headers, Intent intent) {
Grace Kloba068e48b2010-01-26 18:11:27 -08003985 this.mUrl = url;
3986 this.mHeaders = headers;
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -05003987 if (RecognizerResultsIntent.ACTION_VOICE_SEARCH_RESULTS
3988 .equals(intent.getAction())) {
Leon Scroggins58d56c62010-01-28 15:12:40 -05003989 this.mVoiceIntent = intent;
3990 } else {
3991 this.mVoiceIntent = null;
3992 }
Grace Kloba60e095c2009-06-16 11:50:55 -07003993 }
3994
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003995 boolean isEmpty() {
Leon Scroggins58d56c62010-01-28 15:12:40 -05003996 return mVoiceIntent == null && (mUrl == null || mUrl.length() == 0);
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003997 }
3998
Leon Scroggins92472e82010-02-17 16:32:28 -05003999 /**
4000 * Load this UrlData into the given Tab. Use loadUrlDataIn to update
4001 * the title bar as well.
4002 */
Leon Scroggins58d56c62010-01-28 15:12:40 -05004003 public void loadIn(Tab t) {
4004 if (mVoiceIntent != null) {
4005 t.activateVoiceSearchMode(mVoiceIntent);
4006 } else {
4007 t.getWebView().loadUrl(mUrl, mHeaders);
4008 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004009 }
4010 };
4011
Leon Scroggins1f005d32009-08-10 17:36:42 -04004012 /* package */ static final UrlData EMPTY_URL_DATA = new UrlData(null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004013}