blob: 68ea2484cb14147b07724ecfc93cf1a8d4fbd745 [file] [log] [blame]
The Android Open Source Project0c908882009-03-03 19:32:16 -08001/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.browser;
18
The Android Open Source Project0c908882009-03-03 19:32:16 -080019import android.app.Activity;
The Android Open Source Project0c908882009-03-03 19:32:16 -080020import android.app.AlertDialog;
21import android.app.ProgressDialog;
22import android.app.SearchManager;
23import android.content.ActivityNotFoundException;
24import android.content.BroadcastReceiver;
25import android.content.ComponentName;
Leon Scroggins58d56c62010-01-28 15:12:40 -050026import android.content.ContentProvider;
27import android.content.ContentProviderClient;
The Android Open Source Project0c908882009-03-03 19:32:16 -080028import android.content.ContentResolver;
Leon Scrogginsb6b7f9e2009-06-18 12:05:28 -040029import android.content.ContentUris;
The Android Open Source Project0c908882009-03-03 19:32:16 -080030import android.content.ContentValues;
31import android.content.Context;
32import android.content.DialogInterface;
33import android.content.Intent;
34import android.content.IntentFilter;
Grace Klobab4da0ad2009-05-14 14:45:40 -070035import android.content.pm.PackageInfo;
The Android Open Source Project0c908882009-03-03 19:32:16 -080036import android.content.pm.PackageManager;
37import android.content.pm.ResolveInfo;
The Android Open Source Project0c908882009-03-03 19:32:16 -080038import android.content.res.Configuration;
39import android.content.res.Resources;
40import android.database.Cursor;
Leon Scroggins96afcb12009-12-10 12:35:56 -050041import android.database.DatabaseUtils;
The Android Open Source Project0c908882009-03-03 19:32:16 -080042import android.graphics.Bitmap;
Andrei Popescu540035d2009-09-18 18:59:20 +010043import android.graphics.BitmapFactory;
The Android Open Source Project0c908882009-03-03 19:32:16 -080044import android.graphics.Canvas;
The Android Open Source Project0c908882009-03-03 19:32:16 -080045import android.graphics.Picture;
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -040046import android.graphics.PixelFormat;
47import android.graphics.Rect;
The Android Open Source Project0c908882009-03-03 19:32:16 -080048import android.graphics.drawable.Drawable;
The Android Open Source Project0c908882009-03-03 19:32:16 -080049import android.net.ConnectivityManager;
Andrei Popescu56199cc2010-01-12 22:39:16 +000050import android.net.NetworkInfo;
The Android Open Source Project0c908882009-03-03 19:32:16 -080051import android.net.Uri;
52import android.net.WebAddress;
The Android Open Source Project0c908882009-03-03 19:32:16 -080053import android.net.http.SslCertificate;
54import android.net.http.SslError;
55import android.os.AsyncTask;
56import android.os.Bundle;
57import android.os.Debug;
58import android.os.Environment;
59import android.os.Handler;
The Android Open Source Project0c908882009-03-03 19:32:16 -080060import android.os.Message;
61import android.os.PowerManager;
62import android.os.Process;
The Android Open Source Project0c908882009-03-03 19:32:16 -080063import android.os.ServiceManager;
64import android.os.SystemClock;
The Android Open Source Project0c908882009-03-03 19:32:16 -080065import android.provider.Browser;
Cary Clark5e335a32009-09-22 14:53:11 -040066import android.provider.ContactsContract;
67import android.provider.ContactsContract.Intents.Insert;
The Android Open Source Project0c908882009-03-03 19:32:16 -080068import android.provider.Downloads;
69import android.provider.MediaStore;
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -050070import android.speech.RecognizerResultsIntent;
The Android Open Source Project0c908882009-03-03 19:32:16 -080071import android.text.IClipboard;
72import android.text.TextUtils;
73import android.text.format.DateFormat;
Leon Scrogginsb94bf272009-09-25 15:22:08 -040074import android.util.AttributeSet;
The Android Open Source Project0c908882009-03-03 19:32:16 -080075import android.util.Log;
Dianne Hackborn385effd2010-02-24 20:03:04 -080076import android.util.Patterns;
The Android Open Source Project0c908882009-03-03 19:32:16 -080077import android.view.ContextMenu;
78import android.view.Gravity;
79import android.view.KeyEvent;
80import android.view.LayoutInflater;
81import android.view.Menu;
82import android.view.MenuInflater;
83import android.view.MenuItem;
84import android.view.View;
85import android.view.ViewGroup;
86import android.view.Window;
87import android.view.WindowManager;
88import android.view.ContextMenu.ContextMenuInfo;
89import android.view.MenuItem.OnMenuItemClickListener;
Svetoslav Ganov2b345992010-05-06 06:13:54 -070090import android.view.accessibility.AccessibilityManager;
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 Bringert10d1cca2010-02-10 14:22:12 +0000115import com.android.common.Search;
Leon Scroggins1fe13a52010-02-09 15:31:26 -0500116import com.android.common.speech.LoggingEvents;
Dan Egnor5ee906c2009-11-18 12:11:49 -0800117
Leon Scrogginsb6b7f9e2009-06-18 12:05:28 -0400118import java.io.ByteArrayOutputStream;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800119import java.io.File;
Ben Murdoch4f75ba22009-10-27 11:48:28 +0000120import java.io.IOException;
121import java.io.InputStream;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800122import java.net.MalformedURLException;
123import java.net.URI;
Dianne Hackborn99189432009-06-17 18:06:18 -0700124import java.net.URISyntaxException;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800125import java.net.URL;
126import java.net.URLEncoder;
127import java.text.ParseException;
128import java.util.Date;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800129import java.util.HashMap;
Andrei Popescu30995e72010-02-09 16:59:58 +0000130import java.util.HashSet;
Grace Kloba00f54c52010-01-27 14:53:51 -0800131import java.util.Iterator;
Andrei Popescu30995e72010-02-09 16:59:58 +0000132import java.util.List;
Grace Kloba068e48b2010-01-26 18:11:27 -0800133import java.util.Map;
Andrei Popescu30995e72010-02-09 16:59:58 +0000134import java.util.Set;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800135import java.util.regex.Matcher;
136import java.util.regex.Pattern;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800137
138public class BrowserActivity extends Activity
Shimeng (Simon) Wang98d5fce2010-03-16 13:23:39 -0700139 implements View.OnCreateContextMenuListener, DownloadListener {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800140
Dave Bort31a6d1c2009-04-13 15:56:49 -0700141 /* Define some aliases to make these debugging flags easier to refer to.
142 * This file imports android.provider.Browser, so we can't just refer to "Browser.DEBUG".
143 */
144 private final static boolean DEBUG = com.android.browser.Browser.DEBUG;
145 private final static boolean LOGV_ENABLED = com.android.browser.Browser.LOGV_ENABLED;
146 private final static boolean LOGD_ENABLED = com.android.browser.Browser.LOGD_ENABLED;
147
Satish Sampath565505b2009-05-29 15:37:27 +0100148 // These are single-character shortcuts for searching popular sources.
149 private static final int SHORTCUT_INVALID = 0;
150 private static final int SHORTCUT_GOOGLE_SEARCH = 1;
151 private static final int SHORTCUT_WIKIPEDIA_SEARCH = 2;
152 private static final int SHORTCUT_DICTIONARY_SEARCH = 3;
153 private static final int SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH = 4;
154
Cary Clarka9771242009-08-11 16:42:26 -0400155 private static class ClearThumbnails extends AsyncTask<File, Void, Void> {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800156 @Override
157 public Void doInBackground(File... files) {
158 if (files != null) {
159 for (File f : files) {
Cary Clarkd6be1752009-08-12 12:56:42 -0400160 if (!f.delete()) {
161 Log.e(LOGTAG, f.getPath() + " was not deleted");
162 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800163 }
164 }
165 return null;
166 }
167 }
168
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400169 /**
170 * This layout holds everything you see below the status bar, including the
171 * error console, the custom view container, and the webviews.
172 */
173 private FrameLayout mBrowserFrameLayout;
Leon Scroggins81db3662009-06-04 17:45:11 -0400174
Grace Kloba22ac16e2009-10-07 18:00:23 -0700175 @Override
176 public void onCreate(Bundle icicle) {
Dave Bort31a6d1c2009-04-13 15:56:49 -0700177 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800178 Log.v(LOGTAG, this + " onStart");
179 }
180 super.onCreate(icicle);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800181 // test the browser in OpenGL
182 // requestWindowFeature(Window.FEATURE_OPENGL);
183
Mike Reedd334bf52010-01-26 15:21:44 -0500184 // enable this to test the browser in 32bit
185 if (false) {
186 getWindow().setFormat(PixelFormat.RGBX_8888);
187 BitmapFactory.setDefaultConfig(Bitmap.Config.ARGB_8888);
188 }
189
Svetoslav Ganov2b345992010-05-06 06:13:54 -0700190 if (AccessibilityManager.getInstance(this).isEnabled()) {
191 setDefaultKeyMode(DEFAULT_KEYS_DISABLE);
192 } else {
193 setDefaultKeyMode(DEFAULT_KEYS_SEARCH_LOCAL);
194 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800195
196 mResolver = getContentResolver();
197
Grace Kloba0923d692009-09-23 21:37:25 -0700198 // If this was a web search request, pass it on to the default web
199 // search provider and finish this activity.
200 if (handleWebSearchIntent(getIntent())) {
201 finish();
202 return;
203 }
204
The Android Open Source Project0c908882009-03-03 19:32:16 -0800205 mSecLockIcon = Resources.getSystem().getDrawable(
206 android.R.drawable.ic_secure);
207 mMixLockIcon = Resources.getSystem().getDrawable(
208 android.R.drawable.ic_partial_secure);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800209
Leon Scroggins81db3662009-06-04 17:45:11 -0400210 FrameLayout frameLayout = (FrameLayout) getWindow().getDecorView()
211 .findViewById(com.android.internal.R.id.content);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400212 mBrowserFrameLayout = (FrameLayout) LayoutInflater.from(this)
213 .inflate(R.layout.custom_screen, null);
214 mContentView = (FrameLayout) mBrowserFrameLayout.findViewById(
215 R.id.main_content);
216 mErrorConsoleContainer = (LinearLayout) mBrowserFrameLayout
217 .findViewById(R.id.error_console);
218 mCustomViewContainer = (FrameLayout) mBrowserFrameLayout
219 .findViewById(R.id.fullscreen_custom_content);
220 frameLayout.addView(mBrowserFrameLayout, COVER_SCREEN_PARAMS);
Leon Scroggins68579392009-09-15 15:31:54 -0400221 mTitleBar = new TitleBar(this);
Grace Kloba1542f742010-03-17 21:11:15 -0700222 // mTitleBar will be always shown in the fully loaded mode
223 mTitleBar.setProgress(100);
Leon Scrogginsfe87bd32009-10-06 10:10:00 -0400224 mFakeTitleBar = new TitleBar(this);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800225
226 // Create the tab control and our initial tab
227 mTabControl = new TabControl(this);
228
229 // Open the icon database and retain all the bookmark urls for favicons
230 retainIconsOnStartup();
231
232 // Keep a settings instance handy.
233 mSettings = BrowserSettings.getInstance();
234 mSettings.setTabControl(mTabControl);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800235
236 PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
237 mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Browser");
238
Patrick Scott6adacc92010-03-05 08:24:51 -0500239 // Find out if the network is currently up.
240 ConnectivityManager cm = (ConnectivityManager) getSystemService(
241 Context.CONNECTIVITY_SERVICE);
242 NetworkInfo info = cm.getActiveNetworkInfo();
243 if (info != null) {
244 mIsNetworkUp = info.isAvailable();
245 }
246
Grace Klobaa34f6862009-07-31 16:28:17 -0700247 /* enables registration for changes in network status from
248 http stack */
249 mNetworkStateChangedFilter = new IntentFilter();
250 mNetworkStateChangedFilter.addAction(
251 ConnectivityManager.CONNECTIVITY_ACTION);
252 mNetworkStateIntentReceiver = new BroadcastReceiver() {
253 @Override
254 public void onReceive(Context context, Intent intent) {
255 if (intent.getAction().equals(
256 ConnectivityManager.CONNECTIVITY_ACTION)) {
Andrei Popescue4c98462010-02-19 15:44:13 +0000257
258 NetworkInfo info = intent.getParcelableExtra(
259 ConnectivityManager.EXTRA_NETWORK_INFO);
260 String typeName = info.getTypeName();
261 String subtypeName = info.getSubtypeName();
262 sendNetworkType(typeName.toLowerCase(),
263 (subtypeName != null ? subtypeName.toLowerCase() : ""));
264
265 onNetworkToggle(info.isAvailable());
Grace Klobaa34f6862009-07-31 16:28:17 -0700266 }
267 }
268 };
269
Grace Kloba615c6c92009-08-03 10:22:44 -0700270 IntentFilter filter = new IntentFilter(Intent.ACTION_PACKAGE_ADDED);
271 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
272 filter.addDataScheme("package");
273 mPackageInstallationReceiver = new BroadcastReceiver() {
274 @Override
275 public void onReceive(Context context, Intent intent) {
276 final String action = intent.getAction();
277 final String packageName = intent.getData()
278 .getSchemeSpecificPart();
279 final boolean replacing = intent.getBooleanExtra(
280 Intent.EXTRA_REPLACING, false);
281 if (Intent.ACTION_PACKAGE_REMOVED.equals(action) && replacing) {
282 // if it is replacing, refreshPlugins() when adding
283 return;
284 }
Andrei Popescu30995e72010-02-09 16:59:58 +0000285
286 if (sGoogleApps.contains(packageName)) {
287 BrowserActivity.this.packageChanged(packageName,
288 Intent.ACTION_PACKAGE_ADDED.equals(action));
289 }
290
Grace Kloba615c6c92009-08-03 10:22:44 -0700291 PackageManager pm = BrowserActivity.this.getPackageManager();
292 PackageInfo pkgInfo = null;
293 try {
294 pkgInfo = pm.getPackageInfo(packageName,
295 PackageManager.GET_PERMISSIONS);
296 } catch (PackageManager.NameNotFoundException e) {
297 return;
298 }
299 if (pkgInfo != null) {
300 String permissions[] = pkgInfo.requestedPermissions;
301 if (permissions == null) {
302 return;
303 }
304 boolean permissionOk = false;
305 for (String permit : permissions) {
306 if (PluginManager.PLUGIN_PERMISSION.equals(permit)) {
307 permissionOk = true;
308 break;
309 }
310 }
311 if (permissionOk) {
312 PluginManager.getInstance(BrowserActivity.this)
313 .refreshPlugins(
314 Intent.ACTION_PACKAGE_ADDED
315 .equals(action));
316 }
317 }
318 }
319 };
320 registerReceiver(mPackageInstallationReceiver, filter);
321
The Android Open Source Project0c908882009-03-03 19:32:16 -0800322 if (!mTabControl.restoreState(icicle)) {
323 // clear up the thumbnail directory if we can't restore the state as
324 // none of the files in the directory are referenced any more.
325 new ClearThumbnails().execute(
326 mTabControl.getThumbnailDir().listFiles());
Grace Klobaaab3f092009-07-30 12:29:51 -0700327 // there is no quit on Android. But if we can't restore the state,
328 // we can treat it as a new Browser, remove the old session cookies.
329 CookieManager.getInstance().removeSessionCookie();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800330 final Intent intent = getIntent();
331 final Bundle extra = intent.getExtras();
332 // Create an initial tab.
333 // If the intent is ACTION_VIEW and data is not null, the Browser is
334 // invoked to view the content by another application. In this case,
335 // the tab will be close when exit.
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700336 UrlData urlData = getUrlDataFromIntent(intent);
337
Leon Scroggins58d56c62010-01-28 15:12:40 -0500338 String action = intent.getAction();
Grace Kloba22ac16e2009-10-07 18:00:23 -0700339 final Tab t = mTabControl.createNewTab(
Leon Scroggins58d56c62010-01-28 15:12:40 -0500340 (Intent.ACTION_VIEW.equals(action) &&
341 intent.getData() != null)
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -0500342 || RecognizerResultsIntent.ACTION_VOICE_SEARCH_RESULTS
343 .equals(action),
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700344 intent.getStringExtra(Browser.EXTRA_APPLICATION_ID), urlData.mUrl);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800345 mTabControl.setCurrentTab(t);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800346 attachTabToContentView(t);
347 WebView webView = t.getWebView();
348 if (extra != null) {
349 int scale = extra.getInt(Browser.INITIAL_ZOOM_LEVEL, 0);
350 if (scale > 0 && scale <= 1000) {
351 webView.setInitialScale(scale);
352 }
353 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800354
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700355 if (urlData.isEmpty()) {
Shimeng (Simon) Wang98d5fce2010-03-16 13:23:39 -0700356 loadUrl(webView, mSettings.getHomePage());
The Android Open Source Project0c908882009-03-03 19:32:16 -0800357 } else {
Patrick Scott9d53da02010-02-19 10:19:01 -0500358 loadUrlDataIn(t, urlData);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800359 }
360 } else {
361 // TabControl.restoreState() will create a new tab even if
Leon Scroggins1f005d32009-08-10 17:36:42 -0400362 // restoring the state fails.
The Android Open Source Project0c908882009-03-03 19:32:16 -0800363 attachTabToContentView(mTabControl.getCurrentTab());
364 }
Grace Kloba615c6c92009-08-03 10:22:44 -0700365
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 private int parseUrlShortcut(String url) {
557 if (url == null) return SHORTCUT_INVALID;
558
559 // FIXME: quick search, need to be customized by setting
560 if (url.length() > 2 && url.charAt(1) == ' ') {
561 switch (url.charAt(0)) {
562 case 'g': return SHORTCUT_GOOGLE_SEARCH;
563 case 'w': return SHORTCUT_WIKIPEDIA_SEARCH;
564 case 'd': return SHORTCUT_DICTIONARY_SEARCH;
565 case 'l': return SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH;
566 }
567 }
568 return SHORTCUT_INVALID;
569 }
570
571 /**
572 * Launches the default web search activity with the query parameters if the given intent's data
573 * are identified as plain search terms and not URLs/shortcuts.
574 * @return true if the intent was handled and web search activity was launched, false if not.
575 */
576 private boolean handleWebSearchIntent(Intent intent) {
577 if (intent == null) return false;
578
579 String url = null;
580 final String action = intent.getAction();
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -0500581 if (RecognizerResultsIntent.ACTION_VOICE_SEARCH_RESULTS.equals(
582 action)) {
Leon Scroggins58d56c62010-01-28 15:12:40 -0500583 return false;
584 }
Satish Sampath565505b2009-05-29 15:37:27 +0100585 if (Intent.ACTION_VIEW.equals(action)) {
Grace Kloba1e705052009-09-29 13:13:36 -0700586 Uri data = intent.getData();
587 if (data != null) url = data.toString();
Satish Sampath565505b2009-05-29 15:37:27 +0100588 } else if (Intent.ACTION_SEARCH.equals(action)
589 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
590 || Intent.ACTION_WEB_SEARCH.equals(action)) {
591 url = intent.getStringExtra(SearchManager.QUERY);
592 }
Bjorn Bringert04851702009-09-22 10:36:01 +0100593 return handleWebSearchRequest(url, intent.getBundleExtra(SearchManager.APP_DATA),
594 intent.getStringExtra(SearchManager.EXTRA_DATA_KEY));
Satish Sampath565505b2009-05-29 15:37:27 +0100595 }
596
597 /**
598 * Launches the default web search activity with the query parameters if the given url string
599 * was identified as plain search terms and not URL/shortcut.
600 * @return true if the request was handled and web search activity was launched, false if not.
601 */
Bjorn Bringert04851702009-09-22 10:36:01 +0100602 private boolean handleWebSearchRequest(String inUrl, Bundle appData, String extraData) {
Satish Sampath565505b2009-05-29 15:37:27 +0100603 if (inUrl == null) return false;
604
605 // In general, we shouldn't modify URL from Intent.
606 // But currently, we get the user-typed URL from search box as well.
607 String url = fixUrl(inUrl).trim();
608
609 // URLs and site specific search shortcuts are handled by the regular flow of control, so
610 // return early.
Dan Egnor5ee906c2009-11-18 12:11:49 -0800611 if (Patterns.WEB_URL.matcher(url).matches()
Satish Sampathbc5b9f32009-06-04 18:21:40 +0100612 || ACCEPTED_URI_SCHEMA.matcher(url).matches()
Satish Sampath565505b2009-05-29 15:37:27 +0100613 || parseUrlShortcut(url) != SHORTCUT_INVALID) {
614 return false;
615 }
616
Leon Scroggins8d06e362010-03-24 14:45:57 -0400617 final ContentResolver cr = mResolver;
618 final String newUrl = url;
619 new AsyncTask<Void, Void, Void>() {
620 protected Void doInBackground(Void... unused) {
621 Browser.updateVisitedHistory(cr, newUrl, false);
622 Browser.addSearchUrl(cr, newUrl);
623 return null;
624 }
625 }.execute();
Satish Sampath565505b2009-05-29 15:37:27 +0100626
627 Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);
628 intent.addCategory(Intent.CATEGORY_DEFAULT);
629 intent.putExtra(SearchManager.QUERY, url);
Satish Sampath15e9f2d2009-06-23 22:29:49 +0100630 if (appData != null) {
631 intent.putExtra(SearchManager.APP_DATA, appData);
632 }
Bjorn Bringert04851702009-09-22 10:36:01 +0100633 if (extraData != null) {
634 intent.putExtra(SearchManager.EXTRA_DATA_KEY, extraData);
635 }
Grace Klobacc634032009-07-28 15:58:19 -0700636 intent.putExtra(Browser.EXTRA_APPLICATION_ID, getPackageName());
Satish Sampath565505b2009-05-29 15:37:27 +0100637 startActivity(intent);
638
639 return true;
640 }
641
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700642 private UrlData getUrlDataFromIntent(Intent intent) {
Leon Scroggins58d56c62010-01-28 15:12:40 -0500643 String url = "";
Grace Kloba068e48b2010-01-26 18:11:27 -0800644 Map<String, String> headers = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800645 if (intent != null) {
646 final String action = intent.getAction();
647 if (Intent.ACTION_VIEW.equals(action)) {
648 url = smartUrlFilter(intent.getData());
649 if (url != null && url.startsWith("content:")) {
650 /* Append mimetype so webview knows how to display */
651 String mimeType = intent.resolveType(getContentResolver());
652 if (mimeType != null) {
653 url += "?" + mimeType;
654 }
655 }
Grace Kloba068e48b2010-01-26 18:11:27 -0800656 if (url != null && url.startsWith("http")) {
Grace Kloba00f54c52010-01-27 14:53:51 -0800657 final Bundle pairs = intent
658 .getBundleExtra(Browser.EXTRA_HEADERS);
Grace Kloba2d508ed2010-01-28 11:39:15 -0800659 if (pairs != null && !pairs.isEmpty()) {
Grace Kloba00f54c52010-01-27 14:53:51 -0800660 Iterator<String> iter = pairs.keySet().iterator();
Grace Kloba068e48b2010-01-26 18:11:27 -0800661 headers = new HashMap<String, String>();
Grace Kloba00f54c52010-01-27 14:53:51 -0800662 while (iter.hasNext()) {
663 String key = iter.next();
664 headers.put(key, pairs.getString(key));
Grace Kloba068e48b2010-01-26 18:11:27 -0800665 }
666 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700667 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800668 } else if (Intent.ACTION_SEARCH.equals(action)
669 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
670 || Intent.ACTION_WEB_SEARCH.equals(action)) {
671 url = intent.getStringExtra(SearchManager.QUERY);
672 if (url != null) {
673 mLastEnteredUrl = url;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800674 // In general, we shouldn't modify URL from Intent.
675 // But currently, we get the user-typed URL from search box as well.
676 url = fixUrl(url);
677 url = smartUrlFilter(url);
Leon Scroggins8d06e362010-03-24 14:45:57 -0400678 final ContentResolver cr = mResolver;
679 final String newUrl = url;
680 new AsyncTask<Void, Void, Void>() {
681 protected Void doInBackground(Void... unused) {
682 Browser.updateVisitedHistory(cr, newUrl, false);
683 return null;
684 }
685 }.execute();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800686 String searchSource = "&source=android-" + GOOGLE_SEARCH_SOURCE_SUGGEST + "&";
687 if (url.contains(searchSource)) {
688 String source = null;
689 final Bundle appData = intent.getBundleExtra(SearchManager.APP_DATA);
690 if (appData != null) {
Bjorn Bringert10d1cca2010-02-10 14:22:12 +0000691 source = appData.getString(Search.SOURCE);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800692 }
693 if (TextUtils.isEmpty(source)) {
694 source = GOOGLE_SEARCH_SOURCE_UNKNOWN;
695 }
696 url = url.replace(searchSource, "&source=android-"+source+"&");
697 }
698 }
699 }
700 }
Leon Scroggins58d56c62010-01-28 15:12:40 -0500701 return new UrlData(url, headers, intent);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800702 }
Leon Scroggins58d56c62010-01-28 15:12:40 -0500703 /* package */ void showVoiceTitleBar(String title) {
704 mTitleBar.setInVoiceMode(true);
705 mFakeTitleBar.setInVoiceMode(true);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800706
Leon Scroggins58d56c62010-01-28 15:12:40 -0500707 mTitleBar.setDisplayTitle(title);
708 mFakeTitleBar.setDisplayTitle(title);
709 }
710 /* package */ void revertVoiceTitleBar() {
711 mTitleBar.setInVoiceMode(false);
712 mFakeTitleBar.setInVoiceMode(false);
713
Leon Scroggins003a5dd2010-03-10 12:13:14 -0500714 mTitleBar.setDisplayTitle(mUrl);
715 mFakeTitleBar.setDisplayTitle(mUrl);
Leon Scroggins58d56c62010-01-28 15:12:40 -0500716 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800717 /* package */ static String fixUrl(String inUrl) {
Cary Clark652ff872009-09-10 13:34:44 -0400718 // FIXME: Converting the url to lower case
719 // duplicates functionality in smartUrlFilter().
720 // However, changing all current callers of fixUrl to
721 // call smartUrlFilter in addition may have unwanted
722 // consequences, and is deferred for now.
723 int colon = inUrl.indexOf(':');
724 boolean allLower = true;
725 for (int index = 0; index < colon; index++) {
726 char ch = inUrl.charAt(index);
727 if (!Character.isLetter(ch)) {
728 break;
729 }
730 allLower &= Character.isLowerCase(ch);
731 if (index == colon - 1 && !allLower) {
732 inUrl = inUrl.substring(0, colon).toLowerCase()
733 + inUrl.substring(colon);
734 }
735 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800736 if (inUrl.startsWith("http://") || inUrl.startsWith("https://"))
737 return inUrl;
738 if (inUrl.startsWith("http:") ||
739 inUrl.startsWith("https:")) {
740 if (inUrl.startsWith("http:/") || inUrl.startsWith("https:/")) {
741 inUrl = inUrl.replaceFirst("/", "//");
742 } else inUrl = inUrl.replaceFirst(":", "://");
743 }
744 return inUrl;
745 }
746
Grace Kloba22ac16e2009-10-07 18:00:23 -0700747 @Override
748 protected void onResume() {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800749 super.onResume();
Dave Bort31a6d1c2009-04-13 15:56:49 -0700750 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800751 Log.v(LOGTAG, "BrowserActivity.onResume: this=" + this);
752 }
753
754 if (!mActivityInPause) {
755 Log.e(LOGTAG, "BrowserActivity is already resumed.");
756 return;
757 }
758
Mike Reed7bfa63b2009-05-28 11:08:32 -0400759 mTabControl.resumeCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800760 mActivityInPause = false;
Mike Reed7bfa63b2009-05-28 11:08:32 -0400761 resumeWebViewTimers();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800762
763 if (mWakeLock.isHeld()) {
764 mHandler.removeMessages(RELEASE_WAKELOCK);
765 mWakeLock.release();
766 }
767
The Android Open Source Project0c908882009-03-03 19:32:16 -0800768 registerReceiver(mNetworkStateIntentReceiver,
769 mNetworkStateChangedFilter);
770 WebView.enablePlatformNotifications();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800771 }
772
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400773 /**
774 * Since the actual title bar is embedded in the WebView, and removing it
Leon Scrogginsfe87bd32009-10-06 10:10:00 -0400775 * would change its appearance, use a different TitleBar to show overlayed
776 * at the top of the screen, when the menu is open or the page is loading.
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400777 */
778 private TitleBar mFakeTitleBar;
779
780 /**
781 * Keeps track of whether the options menu is open. This is important in
782 * determining whether to show or hide the title bar overlay.
783 */
784 private boolean mOptionsMenuOpen;
785
786 /**
787 * Only meaningful when mOptionsMenuOpen is true. This variable keeps track
788 * of whether the configuration has changed. The first onMenuOpened call
789 * after a configuration change is simply a reopening of the same menu
790 * (i.e. mIconView did not change).
791 */
792 private boolean mConfigChanged;
793
794 /**
795 * Whether or not the options menu is in its smaller, icon menu form. When
796 * true, we want the title bar overlay to be up. When false, we do not.
797 * Only meaningful if mOptionsMenuOpen is true.
798 */
799 private boolean mIconView;
800
Leon Scrogginsa81a7642009-08-31 17:05:41 -0400801 @Override
802 public boolean onMenuOpened(int featureId, Menu menu) {
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400803 if (Window.FEATURE_OPTIONS_PANEL == featureId) {
804 if (mOptionsMenuOpen) {
805 if (mConfigChanged) {
806 // We do not need to make any changes to the state of the
807 // title bar, since the only thing that happened was a
808 // change in orientation
809 mConfigChanged = false;
810 } else {
811 if (mIconView) {
812 // Switching the menu to expanded view, so hide the
813 // title bar.
814 hideFakeTitleBar();
815 mIconView = false;
816 } else {
817 // Switching the menu back to icon view, so show the
818 // title bar once again.
819 showFakeTitleBar();
820 mIconView = true;
821 }
822 }
823 } else {
824 // The options menu is closed, so open it, and show the title
825 showFakeTitleBar();
826 mOptionsMenuOpen = true;
827 mConfigChanged = false;
828 mIconView = true;
829 }
830 }
Leon Scrogginsa81a7642009-08-31 17:05:41 -0400831 return true;
832 }
833
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400834 private void showFakeTitleBar() {
Leon Scrogginsfe87bd32009-10-06 10:10:00 -0400835 if (mFakeTitleBar.getParent() == null && mActiveTabsPage == null
Grace Kloba847c25b2010-03-30 16:00:26 -0700836 && !mActivityInPause) {
837 WebView mainView = mTabControl.getCurrentWebView();
838 // if there is no current WebView, don't show the faked title bar;
Grace Kloba65190702010-04-02 23:37:26 -0700839 if (mainView == null) {
Cary Clarka0464552009-09-29 13:00:45 -0400840 return;
841 }
Leon Scroggins79e36d92010-04-29 16:01:46 +0100842 // Do not need to check for null, since the current tab will have
843 // at least a main WebView, or we would have returned above.
844 if (getTopWindow().getFindIsUp()) {
845 // Do not show the fake title bar, which would cover up the
846 // FindDialog.
847 return;
848 }
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400849
850 WindowManager manager
851 = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
852
853 // Add the title bar to the window manager so it can receive touches
854 // while the menu is up
855 WindowManager.LayoutParams params
856 = new WindowManager.LayoutParams(
Romain Guy15b8ec62010-01-08 15:06:43 -0800857 ViewGroup.LayoutParams.MATCH_PARENT,
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400858 ViewGroup.LayoutParams.WRAP_CONTENT,
Grace Kloba847c25b2010-03-30 16:00:26 -0700859 WindowManager.LayoutParams.TYPE_APPLICATION,
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400860 WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
Leon Scroggins68549862009-09-21 16:02:01 -0400861 PixelFormat.TRANSLUCENT);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400862 params.gravity = Gravity.TOP;
Grace Kloba847c25b2010-03-30 16:00:26 -0700863 boolean atTop = mainView.getScrollY() == 0;
Leon Scroggins83932c72009-09-30 11:55:54 -0400864 params.windowAnimations = atTop ? 0 : R.style.TitleBar;
Grace Kloba13f9ace2010-03-18 21:44:14 -0700865 manager.addView(mFakeTitleBar, params);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400866 }
867 }
868
869 @Override
870 public void onOptionsMenuClosed(Menu menu) {
871 mOptionsMenuOpen = false;
Leon Scrogginsa27ff192009-09-14 12:58:04 -0400872 if (!mInLoad) {
873 hideFakeTitleBar();
874 } else if (!mIconView) {
875 // The page is currently loading, and we are in expanded mode, so
876 // we were not showing the menu. Show it once again. It will be
877 // removed when the page finishes.
878 showFakeTitleBar();
879 }
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400880 }
Grace Kloba22ac16e2009-10-07 18:00:23 -0700881
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400882 private void hideFakeTitleBar() {
Leon Scrogginsfe87bd32009-10-06 10:10:00 -0400883 if (mFakeTitleBar.getParent() == null) return;
Leon Scroggins20329572009-09-23 17:42:41 -0400884 WindowManager.LayoutParams params = (WindowManager.LayoutParams)
Grace Kloba13f9ace2010-03-18 21:44:14 -0700885 mFakeTitleBar.getLayoutParams();
Leon Scroggins20329572009-09-23 17:42:41 -0400886 WebView mainView = mTabControl.getCurrentWebView();
887 // Although we decided whether or not to animate based on the current
888 // scroll position, the scroll position may have changed since the
889 // fake title bar was displayed. Make sure it has the appropriate
890 // animation/lack thereof before removing.
891 params.windowAnimations = mainView != null && mainView.getScrollY() == 0
Leon Scroggins83932c72009-09-30 11:55:54 -0400892 ? 0 : R.style.TitleBar;
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400893 WindowManager manager
894 = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
Grace Kloba13f9ace2010-03-18 21:44:14 -0700895 manager.updateViewLayout(mFakeTitleBar, params);
896 manager.removeView(mFakeTitleBar);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400897 }
898
The Android Open Source Project0c908882009-03-03 19:32:16 -0800899 /**
Leon Scrogginsc6fa1102009-09-21 10:40:01 -0400900 * Special method for the fake title bar to call when displaying its context
901 * menu, since it is in its own Window, and its parent does not show a
902 * context menu.
903 */
904 /* package */ void showTitleBarContextMenu() {
Cary Clark65f4a3c2009-09-28 17:05:06 -0400905 if (null == mTitleBar.getParent()) {
906 return;
907 }
Leon Scrogginsc6fa1102009-09-21 10:40:01 -0400908 openContextMenu(mTitleBar);
909 }
910
Leon Scrogginsb2b19f52009-10-09 16:10:00 -0400911 @Override
912 public void onContextMenuClosed(Menu menu) {
913 super.onContextMenuClosed(menu);
914 if (mInLoad) {
915 showFakeTitleBar();
916 }
917 }
918
Leon Scrogginsc6fa1102009-09-21 10:40:01 -0400919 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -0800920 * onSaveInstanceState(Bundle map)
921 * onSaveInstanceState is called right before onStop(). The map contains
922 * the saved state.
923 */
Grace Kloba22ac16e2009-10-07 18:00:23 -0700924 @Override
925 protected void onSaveInstanceState(Bundle outState) {
Dave Bort31a6d1c2009-04-13 15:56:49 -0700926 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800927 Log.v(LOGTAG, "BrowserActivity.onSaveInstanceState: this=" + this);
928 }
929 // the default implementation requires each view to have an id. As the
930 // browser handles the state itself and it doesn't use id for the views,
931 // don't call the default implementation. Otherwise it will trigger the
932 // warning like this, "couldn't save which view has focus because the
933 // focused view XXX has no id".
934
935 // Save all the tabs
936 mTabControl.saveState(outState);
937 }
938
Grace Kloba22ac16e2009-10-07 18:00:23 -0700939 @Override
940 protected void onPause() {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800941 super.onPause();
942
943 if (mActivityInPause) {
944 Log.e(LOGTAG, "BrowserActivity is already paused.");
945 return;
946 }
947
Mike Reed7bfa63b2009-05-28 11:08:32 -0400948 mTabControl.pauseCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800949 mActivityInPause = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -0400950 if (mTabControl.getCurrentIndex() >= 0 && !pauseWebViewTimers()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800951 mWakeLock.acquire();
952 mHandler.sendMessageDelayed(mHandler
953 .obtainMessage(RELEASE_WAKELOCK), WAKELOCK_TIMEOUT);
954 }
955
Leon Scrogginsa2ab6a72009-09-11 11:49:52 -0400956 // FIXME: This removes the active tabs page and resets the menu to
957 // MAIN_MENU. A better solution might be to do this work in onNewIntent
958 // but then we would need to save it in onSaveInstanceState and restore
959 // it in onCreate/onRestoreInstanceState
960 if (mActiveTabsPage != null) {
961 removeActiveTabPage(true);
962 }
963
The Android Open Source Project0c908882009-03-03 19:32:16 -0800964 cancelStopToast();
965
966 // unregister network state listener
967 unregisterReceiver(mNetworkStateIntentReceiver);
968 WebView.disablePlatformNotifications();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800969 }
970
Grace Kloba22ac16e2009-10-07 18:00:23 -0700971 @Override
972 protected void onDestroy() {
Dave Bort31a6d1c2009-04-13 15:56:49 -0700973 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800974 Log.v(LOGTAG, "BrowserActivity.onDestroy: this=" + this);
975 }
976 super.onDestroy();
Grace Kloba0923d692009-09-23 21:37:25 -0700977
Leon Scroggins8d5fa432009-10-02 15:55:59 -0400978 if (mUploadMessage != null) {
979 mUploadMessage.onReceiveValue(null);
980 mUploadMessage = null;
981 }
982
Grace Kloba0923d692009-09-23 21:37:25 -0700983 if (mTabControl == null) return;
984
Grace Kloba1fc98a32009-10-21 13:23:08 -0700985 // Remove the fake title bar if it is there
986 hideFakeTitleBar();
987
The Android Open Source Project0c908882009-03-03 19:32:16 -0800988 // Remove the current tab and sub window
Grace Kloba22ac16e2009-10-07 18:00:23 -0700989 Tab t = mTabControl.getCurrentTab();
Patrick Scottfb5e77f2009-04-08 19:17:37 -0700990 if (t != null) {
991 dismissSubWindow(t);
992 removeTabFromContentView(t);
993 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800994 // Destroy all the tabs
995 mTabControl.destroy();
996 WebIconDatabase.getInstance().close();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800997
Grace Klobab4da0ad2009-05-14 14:45:40 -0700998 unregisterReceiver(mPackageInstallationReceiver);
Bjorn Bringerta7611812010-03-24 11:12:02 +0000999
1000 // Stop watching the default geolocation permissions
1001 mSystemAllowGeolocationOrigins.stop();
1002 mSystemAllowGeolocationOrigins = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001003 }
1004
1005 @Override
1006 public void onConfigurationChanged(Configuration newConfig) {
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04001007 mConfigChanged = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001008 super.onConfigurationChanged(newConfig);
1009
1010 if (mPageInfoDialog != null) {
1011 mPageInfoDialog.dismiss();
1012 showPageInfo(
1013 mPageInfoView,
Leon Scrogginsc7b92f82010-01-11 18:17:31 -05001014 mPageInfoFromShowSSLCertificateOnError);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001015 }
1016 if (mSSLCertificateDialog != null) {
1017 mSSLCertificateDialog.dismiss();
1018 showSSLCertificate(
1019 mSSLCertificateView);
1020 }
1021 if (mSSLCertificateOnErrorDialog != null) {
1022 mSSLCertificateOnErrorDialog.dismiss();
1023 showSSLCertificateOnError(
1024 mSSLCertificateOnErrorView,
1025 mSSLCertificateOnErrorHandler,
1026 mSSLCertificateOnErrorError);
1027 }
1028 if (mHttpAuthenticationDialog != null) {
1029 String title = ((TextView) mHttpAuthenticationDialog
1030 .findViewById(com.android.internal.R.id.alertTitle)).getText()
1031 .toString();
1032 String name = ((TextView) mHttpAuthenticationDialog
1033 .findViewById(R.id.username_edit)).getText().toString();
1034 String password = ((TextView) mHttpAuthenticationDialog
1035 .findViewById(R.id.password_edit)).getText().toString();
1036 int focusId = mHttpAuthenticationDialog.getCurrentFocus()
1037 .getId();
1038 mHttpAuthenticationDialog.dismiss();
1039 showHttpAuthentication(mHttpAuthHandler, null, null, title,
1040 name, password, focusId);
1041 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001042 }
1043
Grace Kloba22ac16e2009-10-07 18:00:23 -07001044 @Override
1045 public void onLowMemory() {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001046 super.onLowMemory();
1047 mTabControl.freeMemory();
1048 }
1049
Cary Clarkff4d92c2010-03-25 11:17:03 -04001050 private void resumeWebViewTimers() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001051 Tab tab = mTabControl.getCurrentTab();
Cary Clarkff4d92c2010-03-25 11:17:03 -04001052 if (tab == null) return; // monkey can trigger this
Grace Kloba22ac16e2009-10-07 18:00:23 -07001053 boolean inLoad = tab.inLoad();
1054 if ((!mActivityInPause && !inLoad) || (mActivityInPause && inLoad)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001055 CookieSyncManager.getInstance().startSync();
Grace Kloba22ac16e2009-10-07 18:00:23 -07001056 WebView w = tab.getWebView();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001057 if (w != null) {
1058 w.resumeTimers();
1059 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001060 }
1061 }
1062
Mike Reed7bfa63b2009-05-28 11:08:32 -04001063 private boolean pauseWebViewTimers() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001064 Tab tab = mTabControl.getCurrentTab();
1065 boolean inLoad = tab.inLoad();
1066 if (mActivityInPause && !inLoad) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001067 CookieSyncManager.getInstance().stopSync();
1068 WebView w = mTabControl.getCurrentWebView();
1069 if (w != null) {
1070 w.pauseTimers();
1071 }
1072 return true;
1073 } else {
1074 return false;
1075 }
1076 }
1077
The Android Open Source Project0c908882009-03-03 19:32:16 -08001078 // Open the icon database and retain all the icons for visited sites.
1079 private void retainIconsOnStartup() {
1080 final WebIconDatabase db = WebIconDatabase.getInstance();
1081 db.open(getDir("icons", 0).getPath());
Leon Scroggins2c0f6112010-03-12 18:09:39 -05001082 Cursor c = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001083 try {
Leon Scroggins2c0f6112010-03-12 18:09:39 -05001084 c = Browser.getAllBookmarks(mResolver);
1085 if (c.moveToFirst()) {
1086 int urlIndex = c.getColumnIndex(Browser.BookmarkColumns.URL);
1087 do {
1088 String url = c.getString(urlIndex);
1089 db.retainIconForPageUrl(url);
1090 } while (c.moveToNext());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001091 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001092 } catch (IllegalStateException e) {
1093 Log.e(LOGTAG, "retainIconsOnStartup", e);
Leon Scroggins2c0f6112010-03-12 18:09:39 -05001094 } finally {
1095 if (c!= null) c.close();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001096 }
1097 }
1098
1099 // Helper method for getting the top window.
1100 WebView getTopWindow() {
1101 return mTabControl.getCurrentTopWebView();
1102 }
1103
Grace Kloba22ac16e2009-10-07 18:00:23 -07001104 TabControl getTabControl() {
1105 return mTabControl;
1106 }
1107
The Android Open Source Project0c908882009-03-03 19:32:16 -08001108 @Override
1109 public boolean onCreateOptionsMenu(Menu menu) {
1110 super.onCreateOptionsMenu(menu);
1111
1112 MenuInflater inflater = getMenuInflater();
1113 inflater.inflate(R.menu.browser, menu);
1114 mMenu = menu;
1115 updateInLoadMenuItems();
1116 return true;
1117 }
1118
1119 /**
1120 * As the menu can be open when loading state changes
1121 * we must manually update the state of the stop/reload menu
1122 * item
1123 */
1124 private void updateInLoadMenuItems() {
1125 if (mMenu == null) {
1126 return;
1127 }
1128 MenuItem src = mInLoad ?
1129 mMenu.findItem(R.id.stop_menu_id):
1130 mMenu.findItem(R.id.reload_menu_id);
1131 MenuItem dest = mMenu.findItem(R.id.stop_reload_menu_id);
1132 dest.setIcon(src.getIcon());
1133 dest.setTitle(src.getTitle());
1134 }
1135
1136 @Override
1137 public boolean onContextItemSelected(MenuItem item) {
1138 // chording is not an issue with context menus, but we use the same
1139 // options selector, so set mCanChord to true so we can access them.
1140 mCanChord = true;
1141 int id = item.getItemId();
Leon Scroggins96afcb12009-12-10 12:35:56 -05001142 boolean result = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001143 switch (id) {
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001144 // For the context menu from the title bar
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001145 case R.id.title_bar_copy_page_url:
Leon Scroggins96afcb12009-12-10 12:35:56 -05001146 Tab currentTab = mTabControl.getCurrentTab();
1147 if (null == currentTab) {
1148 result = false;
1149 break;
1150 }
1151 WebView mainView = currentTab.getWebView();
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001152 if (null == mainView) {
Leon Scroggins96afcb12009-12-10 12:35:56 -05001153 result = false;
1154 break;
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001155 }
Leon Scroggins96afcb12009-12-10 12:35:56 -05001156 copy(mainView.getUrl());
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001157 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001158 // -- Browser context menu
1159 case R.id.open_context_menu_id:
1160 case R.id.open_newtab_context_menu_id:
1161 case R.id.bookmark_context_menu_id:
1162 case R.id.save_link_context_menu_id:
1163 case R.id.share_link_context_menu_id:
1164 case R.id.copy_link_context_menu_id:
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001165 final WebView webView = getTopWindow();
1166 if (null == webView) {
Leon Scroggins96afcb12009-12-10 12:35:56 -05001167 result = false;
1168 break;
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001169 }
1170 final HashMap hrefMap = new HashMap();
1171 hrefMap.put("webview", webView);
1172 final Message msg = mHandler.obtainMessage(
1173 FOCUS_NODE_HREF, id, 0, hrefMap);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001174 webView.requestFocusNodeHref(msg);
1175 break;
1176
1177 default:
1178 // For other context menus
Leon Scroggins96afcb12009-12-10 12:35:56 -05001179 result = onOptionsItemSelected(item);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001180 }
1181 mCanChord = false;
Leon Scroggins96afcb12009-12-10 12:35:56 -05001182 return result;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001183 }
1184
1185 private Bundle createGoogleSearchSourceBundle(String source) {
1186 Bundle bundle = new Bundle();
Bjorn Bringert10d1cca2010-02-10 14:22:12 +00001187 bundle.putString(Search.SOURCE, source);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001188 return bundle;
1189 }
1190
Leon Scroggins8ad29922010-02-16 12:33:55 -05001191 /* package */ void editUrl() {
Leon Scroggins68579392009-09-15 15:31:54 -04001192 if (mOptionsMenuOpen) closeOptionsMenu();
Leon Scroggins5bbe9802009-07-31 13:10:55 -04001193 String url = (getTopWindow() == null) ? null : getTopWindow().getUrl();
Grace Kloba83f47342009-07-20 10:44:31 -07001194 startSearch(mSettings.getHomePage().equals(url) ? null : url, true,
Leon Scroggins8ad29922010-02-16 12:33:55 -05001195 null, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001196 }
1197
Leon Scroggins8ad29922010-02-16 12:33:55 -05001198 /**
1199 * Overriding this to insert a local information bundle
1200 */
The Android Open Source Project0c908882009-03-03 19:32:16 -08001201 @Override
1202 public void startSearch(String initialQuery, boolean selectInitialQuery,
1203 Bundle appSearchData, boolean globalSearch) {
1204 if (appSearchData == null) {
1205 appSearchData = createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_TYPE);
1206 }
1207 super.startSearch(initialQuery, selectInitialQuery, appSearchData, globalSearch);
1208 }
1209
Leon Scroggins1f005d32009-08-10 17:36:42 -04001210 /**
1211 * Switch tabs. Called by the TitleBarSet when sliding the title bar
1212 * results in changing tabs.
Leon Scroggins160a7e72009-08-14 18:28:01 -04001213 * @param index Index of the tab to change to, as defined by
1214 * mTabControl.getTabIndex(Tab t).
1215 * @return boolean True if we successfully switched to a different tab. If
1216 * the indexth tab is null, or if that tab is the same as
1217 * the current one, return false.
Leon Scroggins1f005d32009-08-10 17:36:42 -04001218 */
Leon Scroggins160a7e72009-08-14 18:28:01 -04001219 /* package */ boolean switchToTab(int index) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001220 Tab tab = mTabControl.getTab(index);
1221 Tab currentTab = mTabControl.getCurrentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04001222 if (tab == null || tab == currentTab) {
Leon Scroggins160a7e72009-08-14 18:28:01 -04001223 return false;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001224 }
1225 if (currentTab != null) {
1226 // currentTab may be null if it was just removed. In that case,
1227 // we do not need to remove it
1228 removeTabFromContentView(currentTab);
1229 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001230 mTabControl.setCurrentTab(tab);
1231 attachTabToContentView(tab);
Grace Klobaeb6eef42009-09-15 17:56:32 -07001232 resetTitleIconAndProgress();
1233 updateLockIconToLatest();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001234 return true;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001235 }
1236
Grace Kloba22ac16e2009-10-07 18:00:23 -07001237 /* package */ Tab openTabToHomePage() {
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001238 return openTabAndShow(mSettings.getHomePage(), false, null);
1239 }
1240
Leon Scroggins1f005d32009-08-10 17:36:42 -04001241 /* package */ void closeCurrentWindow() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001242 final Tab current = mTabControl.getCurrentTab();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001243 if (mTabControl.getTabCount() == 1) {
Leon Scroggins30444232009-09-04 18:36:20 -04001244 // This is the last tab. Open a new one, with the home
1245 // page and close the current one.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001246 openTabToHomePage();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001247 closeTab(current);
Leon Scroggins160a7e72009-08-14 18:28:01 -04001248 return;
1249 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07001250 final Tab parent = current.getParentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04001251 int indexToShow = -1;
1252 if (parent != null) {
1253 indexToShow = mTabControl.getTabIndex(parent);
1254 } else {
Leon Scroggins160a7e72009-08-14 18:28:01 -04001255 final int currentIndex = mTabControl.getCurrentIndex();
1256 // Try to move to the tab to the right
1257 indexToShow = currentIndex + 1;
1258 if (indexToShow > mTabControl.getTabCount() - 1) {
1259 // Try to move to the tab to the left
1260 indexToShow = currentIndex - 1;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001261 }
1262 }
Leon Scroggins160a7e72009-08-14 18:28:01 -04001263 if (switchToTab(indexToShow)) {
1264 // Close window
1265 closeTab(current);
1266 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001267 }
1268
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001269 private ActiveTabsPage mActiveTabsPage;
1270
1271 /**
1272 * Remove the active tabs page.
1273 * @param needToAttach If true, the active tabs page did not attach a tab
1274 * to the content view, so we need to do that here.
1275 */
1276 /* package */ void removeActiveTabPage(boolean needToAttach) {
1277 mContentView.removeView(mActiveTabsPage);
1278 mActiveTabsPage = null;
1279 mMenuState = R.id.MAIN_MENU;
1280 if (needToAttach) {
1281 attachTabToContentView(mTabControl.getCurrentTab());
1282 }
1283 getTopWindow().requestFocus();
1284 }
1285
The Android Open Source Project0c908882009-03-03 19:32:16 -08001286 @Override
1287 public boolean onOptionsItemSelected(MenuItem item) {
1288 if (!mCanChord) {
1289 // The user has already fired a shortcut with this hold down of the
1290 // menu key.
1291 return false;
1292 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001293 if (null == getTopWindow()) {
Leon Scroggins0d7ae0e2009-06-05 11:04:45 -04001294 return false;
1295 }
Grace Kloba6ee9c492009-07-13 10:04:34 -07001296 if (mMenuIsDown) {
1297 // The shortcut action consumes the MENU. Even if it is still down,
1298 // it won't trigger the next shortcut action. In the case of the
1299 // shortcut action triggering a new activity, like Bookmarks, we
1300 // won't get onKeyUp for MENU. So it is important to reset it here.
1301 mMenuIsDown = false;
1302 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001303 switch (item.getItemId()) {
1304 // -- Main menu
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001305 case R.id.new_tab_menu_id:
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001306 openTabToHomePage();
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001307 break;
1308
Leon Scroggins64b80f32009-08-07 12:03:34 -04001309 case R.id.goto_menu_id:
Leon Scroggins8ad29922010-02-16 12:33:55 -05001310 editUrl();
Leon Scrogginsb3a5bed2009-09-28 11:21:56 -04001311 break;
1312
1313 case R.id.bookmarks_menu_id:
Leon Scroggins30444232009-09-04 18:36:20 -04001314 bookmarksOrHistoryPicker(false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001315 break;
1316
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001317 case R.id.active_tabs_menu_id:
1318 mActiveTabsPage = new ActiveTabsPage(this, mTabControl);
1319 removeTabFromContentView(mTabControl.getCurrentTab());
Leon Scroggins43de6162009-09-14 19:59:58 -04001320 hideFakeTitleBar();
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001321 mContentView.addView(mActiveTabsPage, COVER_SCREEN_PARAMS);
1322 mActiveTabsPage.requestFocus();
1323 mMenuState = EMPTY_MENU;
1324 break;
1325
Leon Scroggins1f005d32009-08-10 17:36:42 -04001326 case R.id.add_bookmark_menu_id:
1327 Intent i = new Intent(BrowserActivity.this,
1328 AddBookmarkPage.class);
1329 WebView w = getTopWindow();
1330 i.putExtra("url", w.getUrl());
1331 i.putExtra("title", w.getTitle());
Grace Kloba83cdb2c2009-09-16 00:48:57 -07001332 i.putExtra("touch_icon_url", w.getTouchIconUrl());
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01001333 i.putExtra("thumbnail", createScreenshot(w));
Leon Scroggins1f005d32009-08-10 17:36:42 -04001334 startActivity(i);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001335 break;
1336
1337 case R.id.stop_reload_menu_id:
1338 if (mInLoad) {
1339 stopLoading();
1340 } else {
1341 getTopWindow().reload();
1342 }
1343 break;
1344
1345 case R.id.back_menu_id:
1346 getTopWindow().goBack();
1347 break;
1348
1349 case R.id.forward_menu_id:
1350 getTopWindow().goForward();
1351 break;
1352
1353 case R.id.close_menu_id:
1354 // Close the subwindow if it exists.
1355 if (mTabControl.getCurrentSubWindow() != null) {
1356 dismissSubWindow(mTabControl.getCurrentTab());
1357 break;
1358 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001359 closeCurrentWindow();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001360 break;
1361
1362 case R.id.homepage_menu_id:
Grace Kloba22ac16e2009-10-07 18:00:23 -07001363 Tab current = mTabControl.getCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001364 if (current != null) {
1365 dismissSubWindow(current);
Leon Scroggins92472e82010-02-17 16:32:28 -05001366 loadUrl(current.getWebView(), mSettings.getHomePage());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001367 }
1368 break;
1369
1370 case R.id.preferences_menu_id:
1371 Intent intent = new Intent(this,
1372 BrowserPreferencesPage.class);
Leon Scrogginsd5304942009-12-10 16:11:39 -05001373 intent.putExtra(BrowserPreferencesPage.CURRENT_PAGE,
1374 getTopWindow().getUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001375 startActivityForResult(intent, PREFERENCES_PAGE);
1376 break;
1377
1378 case R.id.find_menu_id:
1379 if (null == mFindDialog) {
1380 mFindDialog = new FindDialog(this);
1381 }
Leon Scroggins III211ba542010-04-19 13:21:13 -04001382 // Need to do something special for Tablet
Leon Scroggins79e36d92010-04-29 16:01:46 +01001383 Tab tab = mTabControl.getCurrentTab();
1384 if (tab.getSubWebView() == null) {
1385 // If the Find is being performed on the main webview,
1386 // remove the embedded title bar.
1387 WebView mainView = tab.getWebView();
1388 if (mainView != null) {
1389 mainView.setEmbeddedTitleBar(null);
1390 }
1391 }
1392 hideFakeTitleBar();
1393 tab.showFind(mFindDialog);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001394 mMenuState = EMPTY_MENU;
1395 break;
1396
1397 case R.id.select_text_id:
1398 getTopWindow().emulateShiftHeld();
1399 break;
1400 case R.id.page_info_menu_id:
1401 showPageInfo(mTabControl.getCurrentTab(), false);
1402 break;
1403
1404 case R.id.classic_history_menu_id:
Leon Scroggins30444232009-09-04 18:36:20 -04001405 bookmarksOrHistoryPicker(true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001406 break;
1407
Leon Scroggins96afcb12009-12-10 12:35:56 -05001408 case R.id.title_bar_share_page_url:
The Android Open Source Project0c908882009-03-03 19:32:16 -08001409 case R.id.share_page_menu_id:
Leon Scroggins96afcb12009-12-10 12:35:56 -05001410 Tab currentTab = mTabControl.getCurrentTab();
1411 if (null == currentTab) {
1412 mCanChord = false;
1413 return false;
1414 }
1415 currentTab.populatePickerData();
1416 sharePage(this, currentTab.getTitle(),
1417 currentTab.getUrl(), currentTab.getFavicon(),
1418 createScreenshot(currentTab.getWebView()));
The Android Open Source Project0c908882009-03-03 19:32:16 -08001419 break;
1420
1421 case R.id.dump_nav_menu_id:
1422 getTopWindow().debugDump();
1423 break;
1424
Andrei Popescu7a8b88b2010-02-02 00:30:38 +00001425 case R.id.dump_counters_menu_id:
1426 getTopWindow().dumpV8Counters();
1427 break;
1428
The Android Open Source Project0c908882009-03-03 19:32:16 -08001429 case R.id.zoom_in_menu_id:
1430 getTopWindow().zoomIn();
1431 break;
1432
1433 case R.id.zoom_out_menu_id:
1434 getTopWindow().zoomOut();
1435 break;
1436
1437 case R.id.view_downloads_menu_id:
1438 viewDownloads(null);
1439 break;
1440
The Android Open Source Project0c908882009-03-03 19:32:16 -08001441 case R.id.window_one_menu_id:
1442 case R.id.window_two_menu_id:
1443 case R.id.window_three_menu_id:
1444 case R.id.window_four_menu_id:
1445 case R.id.window_five_menu_id:
1446 case R.id.window_six_menu_id:
1447 case R.id.window_seven_menu_id:
1448 case R.id.window_eight_menu_id:
1449 {
1450 int menuid = item.getItemId();
1451 for (int id = 0; id < WINDOW_SHORTCUT_ID_ARRAY.length; id++) {
1452 if (WINDOW_SHORTCUT_ID_ARRAY[id] == menuid) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001453 Tab desiredTab = mTabControl.getTab(id);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001454 if (desiredTab != null &&
1455 desiredTab != mTabControl.getCurrentTab()) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001456 switchToTab(id);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001457 }
1458 break;
1459 }
1460 }
1461 }
1462 break;
1463
1464 default:
1465 if (!super.onOptionsItemSelected(item)) {
1466 return false;
1467 }
1468 // Otherwise fall through.
1469 }
1470 mCanChord = false;
1471 return true;
1472 }
1473
Leon Scroggins III211ba542010-04-19 13:21:13 -04001474 /*
1475 * Remove the FindDialog.
1476 */
The Android Open Source Project0c908882009-03-03 19:32:16 -08001477 public void closeFind() {
Leon Scroggins79e36d92010-04-29 16:01:46 +01001478 Tab currentTab = mTabControl.getCurrentTab();
Leon Scroggins III211ba542010-04-19 13:21:13 -04001479 if (mFindDialog != null) {
Leon Scroggins79e36d92010-04-29 16:01:46 +01001480 currentTab.closeFind(mFindDialog);
Leon Scroggins III211ba542010-04-19 13:21:13 -04001481 mFindDialog.dismiss();
1482 }
Leon Scroggins79e36d92010-04-29 16:01:46 +01001483 // If the Find was being performed in the main WebView, replace the
1484 // embedded title bar.
1485 if (currentTab.getSubWebView() == null) {
1486 WebView mainView = currentTab.getWebView();
1487 if (mainView != null) {
1488 mainView.setEmbeddedTitleBar(mTitleBar);
1489 }
1490 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001491 mMenuState = R.id.MAIN_MENU;
Leon Scroggins79e36d92010-04-29 16:01:46 +01001492 if (mInLoad) {
1493 // The title bar was hidden, because otherwise it would cover up the
1494 // find dialog. Now that the dialog has been removed, show the fake
1495 // title bar once again.
1496 showFakeTitleBar();
1497 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001498 }
1499
Grace Kloba22ac16e2009-10-07 18:00:23 -07001500 @Override
1501 public boolean onPrepareOptionsMenu(Menu menu) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001502 // This happens when the user begins to hold down the menu key, so
1503 // allow them to chord to get a shortcut.
1504 mCanChord = true;
1505 // Note: setVisible will decide whether an item is visible; while
1506 // setEnabled() will decide whether an item is enabled, which also means
1507 // whether the matching shortcut key will function.
1508 super.onPrepareOptionsMenu(menu);
1509 switch (mMenuState) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001510 case EMPTY_MENU:
1511 if (mCurrentMenuState != mMenuState) {
1512 menu.setGroupVisible(R.id.MAIN_MENU, false);
1513 menu.setGroupEnabled(R.id.MAIN_MENU, false);
1514 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001515 }
1516 break;
1517 default:
1518 if (mCurrentMenuState != mMenuState) {
1519 menu.setGroupVisible(R.id.MAIN_MENU, true);
1520 menu.setGroupEnabled(R.id.MAIN_MENU, true);
1521 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001522 }
1523 final WebView w = getTopWindow();
1524 boolean canGoBack = false;
1525 boolean canGoForward = false;
1526 boolean isHome = false;
1527 if (w != null) {
1528 canGoBack = w.canGoBack();
1529 canGoForward = w.canGoForward();
1530 isHome = mSettings.getHomePage().equals(w.getUrl());
1531 }
1532 final MenuItem back = menu.findItem(R.id.back_menu_id);
1533 back.setEnabled(canGoBack);
1534
1535 final MenuItem home = menu.findItem(R.id.homepage_menu_id);
1536 home.setEnabled(!isHome);
1537
1538 menu.findItem(R.id.forward_menu_id)
1539 .setEnabled(canGoForward);
1540
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001541 menu.findItem(R.id.new_tab_menu_id).setEnabled(
Grace Kloba22ac16e2009-10-07 18:00:23 -07001542 mTabControl.canCreateNewTab());
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001543
The Android Open Source Project0c908882009-03-03 19:32:16 -08001544 // decide whether to show the share link option
1545 PackageManager pm = getPackageManager();
1546 Intent send = new Intent(Intent.ACTION_SEND);
1547 send.setType("text/plain");
1548 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1549 menu.findItem(R.id.share_page_menu_id).setVisible(ri != null);
1550
The Android Open Source Project0c908882009-03-03 19:32:16 -08001551 boolean isNavDump = mSettings.isNavDump();
1552 final MenuItem nav = menu.findItem(R.id.dump_nav_menu_id);
1553 nav.setVisible(isNavDump);
1554 nav.setEnabled(isNavDump);
Andrei Popescu7a8b88b2010-02-02 00:30:38 +00001555
1556 boolean showDebugSettings = mSettings.showDebugSettings();
1557 final MenuItem counter = menu.findItem(R.id.dump_counters_menu_id);
1558 counter.setVisible(showDebugSettings);
1559 counter.setEnabled(showDebugSettings);
1560
The Android Open Source Project0c908882009-03-03 19:32:16 -08001561 break;
1562 }
1563 mCurrentMenuState = mMenuState;
1564 return true;
1565 }
1566
1567 @Override
1568 public void onCreateContextMenu(ContextMenu menu, View v,
1569 ContextMenuInfo menuInfo) {
Leon Scroggins4e9f89b2010-02-22 16:54:14 -05001570 if (v instanceof TitleBar) {
1571 return;
1572 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001573 WebView webview = (WebView) v;
1574 WebView.HitTestResult result = webview.getHitTestResult();
1575 if (result == null) {
1576 return;
1577 }
1578
1579 int type = result.getType();
1580 if (type == WebView.HitTestResult.UNKNOWN_TYPE) {
1581 Log.w(LOGTAG,
1582 "We should not show context menu when nothing is touched");
1583 return;
1584 }
1585 if (type == WebView.HitTestResult.EDIT_TEXT_TYPE) {
1586 // let TextView handles context menu
1587 return;
1588 }
1589
1590 // Note, http://b/issue?id=1106666 is requesting that
1591 // an inflated menu can be used again. This is not available
1592 // yet, so inflate each time (yuk!)
1593 MenuInflater inflater = getMenuInflater();
1594 inflater.inflate(R.menu.browsercontext, menu);
1595
1596 // Show the correct menu group
1597 String extra = result.getExtra();
1598 menu.setGroupVisible(R.id.PHONE_MENU,
1599 type == WebView.HitTestResult.PHONE_TYPE);
1600 menu.setGroupVisible(R.id.EMAIL_MENU,
1601 type == WebView.HitTestResult.EMAIL_TYPE);
1602 menu.setGroupVisible(R.id.GEO_MENU,
1603 type == WebView.HitTestResult.GEO_TYPE);
1604 menu.setGroupVisible(R.id.IMAGE_MENU,
1605 type == WebView.HitTestResult.IMAGE_TYPE
1606 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1607 menu.setGroupVisible(R.id.ANCHOR_MENU,
1608 type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1609 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1610
1611 // Setup custom handling depending on the type
1612 switch (type) {
1613 case WebView.HitTestResult.PHONE_TYPE:
1614 menu.setHeaderTitle(Uri.decode(extra));
1615 menu.findItem(R.id.dial_context_menu_id).setIntent(
1616 new Intent(Intent.ACTION_VIEW, Uri
1617 .parse(WebView.SCHEME_TEL + extra)));
1618 Intent addIntent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
1619 addIntent.putExtra(Insert.PHONE, Uri.decode(extra));
Cary Clark5e335a32009-09-22 14:53:11 -04001620 addIntent.setType(ContactsContract.Contacts.CONTENT_ITEM_TYPE);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001621 menu.findItem(R.id.add_contact_context_menu_id).setIntent(
1622 addIntent);
1623 menu.findItem(R.id.copy_phone_context_menu_id).setOnMenuItemClickListener(
1624 new Copy(extra));
1625 break;
1626
1627 case WebView.HitTestResult.EMAIL_TYPE:
1628 menu.setHeaderTitle(extra);
1629 menu.findItem(R.id.email_context_menu_id).setIntent(
1630 new Intent(Intent.ACTION_VIEW, Uri
1631 .parse(WebView.SCHEME_MAILTO + extra)));
1632 menu.findItem(R.id.copy_mail_context_menu_id).setOnMenuItemClickListener(
1633 new Copy(extra));
1634 break;
1635
1636 case WebView.HitTestResult.GEO_TYPE:
1637 menu.setHeaderTitle(extra);
1638 menu.findItem(R.id.map_context_menu_id).setIntent(
1639 new Intent(Intent.ACTION_VIEW, Uri
1640 .parse(WebView.SCHEME_GEO
1641 + URLEncoder.encode(extra))));
1642 menu.findItem(R.id.copy_geo_context_menu_id).setOnMenuItemClickListener(
1643 new Copy(extra));
1644 break;
1645
1646 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1647 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
1648 TextView titleView = (TextView) LayoutInflater.from(this)
1649 .inflate(android.R.layout.browser_link_context_header,
1650 null);
1651 titleView.setText(extra);
1652 menu.setHeaderView(titleView);
1653 // decide whether to show the open link in new tab option
1654 menu.findItem(R.id.open_newtab_context_menu_id).setVisible(
Grace Kloba22ac16e2009-10-07 18:00:23 -07001655 mTabControl.canCreateNewTab());
Ben Murdochde353622009-10-12 10:29:00 +01001656 menu.findItem(R.id.bookmark_context_menu_id).setVisible(
1657 Bookmarks.urlHasAcceptableScheme(extra));
The Android Open Source Project0c908882009-03-03 19:32:16 -08001658 PackageManager pm = getPackageManager();
1659 Intent send = new Intent(Intent.ACTION_SEND);
1660 send.setType("text/plain");
1661 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1662 menu.findItem(R.id.share_link_context_menu_id).setVisible(ri != null);
1663 if (type == WebView.HitTestResult.SRC_ANCHOR_TYPE) {
1664 break;
1665 }
1666 // otherwise fall through to handle image part
1667 case WebView.HitTestResult.IMAGE_TYPE:
1668 if (type == WebView.HitTestResult.IMAGE_TYPE) {
1669 menu.setHeaderTitle(extra);
1670 }
1671 menu.findItem(R.id.view_image_context_menu_id).setIntent(
1672 new Intent(Intent.ACTION_VIEW, Uri.parse(extra)));
1673 menu.findItem(R.id.download_context_menu_id).
1674 setOnMenuItemClickListener(new Download(extra));
Ben Murdoch4f75ba22009-10-27 11:48:28 +00001675 menu.findItem(R.id.set_wallpaper_context_menu_id).
1676 setOnMenuItemClickListener(new SetAsWallpaper(extra));
The Android Open Source Project0c908882009-03-03 19:32:16 -08001677 break;
1678
1679 default:
1680 Log.w(LOGTAG, "We should not get here.");
1681 break;
1682 }
Leon Scrogginsb2b19f52009-10-09 16:10:00 -04001683 hideFakeTitleBar();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001684 }
1685
The Android Open Source Project0c908882009-03-03 19:32:16 -08001686 // Attach the given tab to the content view.
Grace Klobac928c302009-09-17 11:51:21 -07001687 // this should only be called for the current tab.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001688 private void attachTabToContentView(Tab t) {
Steve Block2bc69912009-07-30 14:45:13 +01001689 // Attach the container that contains the main WebView and any other UI
1690 // associated with the tab.
Patrick Scottd0119532009-09-17 08:00:31 -04001691 t.attachTabToContentView(mContentView);
Ben Murdochbff2d602009-07-01 20:19:05 +01001692
1693 if (mShouldShowErrorConsole) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001694 ErrorConsoleView errorConsole = t.getErrorConsole(true);
Ben Murdochbff2d602009-07-01 20:19:05 +01001695 if (errorConsole.numberOfErrors() == 0) {
1696 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
1697 } else {
1698 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
1699 }
1700
1701 mErrorConsoleContainer.addView(errorConsole,
Romain Guy15b8ec62010-01-08 15:06:43 -08001702 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
Ben Murdochbff2d602009-07-01 20:19:05 +01001703 ViewGroup.LayoutParams.WRAP_CONTENT));
1704 }
1705
Leon Scroggins39ab28e2009-09-02 21:20:30 -04001706 WebView view = t.getWebView();
Leon Scroggins55a5bc22009-09-04 17:00:08 -04001707 view.setEmbeddedTitleBar(mTitleBar);
Leon Scroggins58d56c62010-01-28 15:12:40 -05001708 if (t.isInVoiceSearchMode()) {
1709 showVoiceTitleBar(t.getVoiceDisplayTitle());
1710 } else {
1711 revertVoiceTitleBar();
1712 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001713 // Request focus on the top window.
1714 t.getTopWindow().requestFocus();
1715 }
1716
1717 // Attach a sub window to the main WebView of the given tab.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001718 void attachSubWindow(Tab t) {
Patrick Scottd0119532009-09-17 08:00:31 -04001719 t.attachSubWindow(mContentView);
1720 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001721 }
1722
1723 // Remove the given tab from the content view.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001724 private void removeTabFromContentView(Tab t) {
Steve Block2bc69912009-07-30 14:45:13 +01001725 // Remove the container that contains the main WebView.
Patrick Scottd0119532009-09-17 08:00:31 -04001726 t.removeTabFromContentView(mContentView);
Ben Murdochbff2d602009-07-01 20:19:05 +01001727
Grace Kloba22ac16e2009-10-07 18:00:23 -07001728 ErrorConsoleView errorConsole = t.getErrorConsole(false);
1729 if (errorConsole != null) {
1730 mErrorConsoleContainer.removeView(errorConsole);
Ben Murdochbff2d602009-07-01 20:19:05 +01001731 }
1732
Leon Scroggins39ab28e2009-09-02 21:20:30 -04001733 WebView view = t.getWebView();
Leon Scrogginsbb85b902009-09-14 19:27:20 -04001734 if (view != null) {
1735 view.setEmbeddedTitleBar(null);
1736 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001737 }
1738
1739 // Remove the sub window if it exists. Also called by TabControl when the
1740 // user clicks the 'X' to dismiss a sub window.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001741 /* package */ void dismissSubWindow(Tab t) {
Patrick Scottd0119532009-09-17 08:00:31 -04001742 t.removeSubWindow(mContentView);
Grace Kloba22ac16e2009-10-07 18:00:23 -07001743 // dismiss the subwindow. This will destroy the WebView.
1744 t.dismissSubWindow();
Patrick Scottd0119532009-09-17 08:00:31 -04001745 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001746 }
1747
Leon Scroggins1f005d32009-08-10 17:36:42 -04001748 // A wrapper function of {@link #openTabAndShow(UrlData, boolean, String)}
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07001749 // that accepts url as string.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001750 private Tab openTabAndShow(String url, boolean closeOnExit, String appId) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001751 return openTabAndShow(new UrlData(url), closeOnExit, appId);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001752 }
1753
1754 // This method does a ton of stuff. It will attempt to create a new tab
1755 // if we haven't reached MAX_TABS. Otherwise it uses the current tab. If
Leon Scroggins1f005d32009-08-10 17:36:42 -04001756 // url isn't null, it will load the given url.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001757 /* package */Tab openTabAndShow(UrlData urlData, boolean closeOnExit,
1758 String appId) {
1759 final Tab currentTab = mTabControl.getCurrentTab();
1760 if (mTabControl.canCreateNewTab()) {
1761 final Tab tab = mTabControl.createNewTab(closeOnExit, appId,
1762 urlData.mUrl);
Leon Scroggins1f005d32009-08-10 17:36:42 -04001763 WebView webview = tab.getWebView();
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001764 // If the last tab was removed from the active tabs page, currentTab
1765 // will be null.
1766 if (currentTab != null) {
1767 removeTabFromContentView(currentTab);
1768 }
Patrick Scott8bbd69f2009-08-14 13:35:53 -04001769 // We must set the new tab as the current tab to reflect the old
1770 // animation behavior.
1771 mTabControl.setCurrentTab(tab);
Grace Klobaeb6eef42009-09-15 17:56:32 -07001772 attachTabToContentView(tab);
Leon Scroggins160a7e72009-08-14 18:28:01 -04001773 if (!urlData.isEmpty()) {
Patrick Scott9d53da02010-02-19 10:19:01 -05001774 loadUrlDataIn(tab, urlData);
Leon Scroggins1f005d32009-08-10 17:36:42 -04001775 }
1776 return tab;
1777 } else {
1778 // Get rid of the subwindow if it exists
1779 dismissSubWindow(currentTab);
1780 if (!urlData.isEmpty()) {
1781 // Load the given url.
Patrick Scott9d53da02010-02-19 10:19:01 -05001782 loadUrlDataIn(currentTab, urlData);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001783 }
Leon Scroggins58d56c62010-01-28 15:12:40 -05001784 return currentTab;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001785 }
1786 }
1787
Grace Kloba22ac16e2009-10-07 18:00:23 -07001788 private Tab openTab(String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001789 if (mSettings.openInBackground()) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001790 Tab t = mTabControl.createNewTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001791 if (t != null) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001792 WebView view = t.getWebView();
Leon Scroggins92472e82010-02-17 16:32:28 -05001793 loadUrl(view, url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001794 }
Grace Klobac9181842009-04-14 08:53:22 -07001795 return t;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001796 } else {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001797 return openTabAndShow(url, false, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001798 }
1799 }
1800
1801 private class Copy implements OnMenuItemClickListener {
1802 private CharSequence mText;
1803
1804 public boolean onMenuItemClick(MenuItem item) {
1805 copy(mText);
1806 return true;
1807 }
1808
1809 public Copy(CharSequence toCopy) {
1810 mText = toCopy;
1811 }
1812 }
1813
1814 private class Download implements OnMenuItemClickListener {
1815 private String mText;
1816
1817 public boolean onMenuItemClick(MenuItem item) {
1818 onDownloadStartNoStream(mText, null, null, null, -1);
1819 return true;
1820 }
1821
1822 public Download(String toDownload) {
1823 mText = toDownload;
1824 }
1825 }
1826
Ben Murdoch4f75ba22009-10-27 11:48:28 +00001827 private class SetAsWallpaper extends Thread implements
1828 OnMenuItemClickListener, DialogInterface.OnCancelListener {
1829 private URL mUrl;
1830 private ProgressDialog mWallpaperProgress;
1831 private boolean mCanceled = false;
1832
1833 public SetAsWallpaper(String url) {
1834 try {
1835 mUrl = new URL(url);
1836 } catch (MalformedURLException e) {
1837 mUrl = null;
1838 }
1839 }
1840
1841 public void onCancel(DialogInterface dialog) {
1842 mCanceled = true;
1843 }
1844
1845 public boolean onMenuItemClick(MenuItem item) {
1846 if (mUrl != null) {
1847 // The user may have tried to set a image with a large file size as their
1848 // background so it may take a few moments to perform the operation. Display
1849 // a progress spinner while it is working.
1850 mWallpaperProgress = new ProgressDialog(BrowserActivity.this);
1851 mWallpaperProgress.setIndeterminate(true);
1852 mWallpaperProgress.setMessage(getText(R.string.progress_dialog_setting_wallpaper));
1853 mWallpaperProgress.setCancelable(true);
1854 mWallpaperProgress.setOnCancelListener(this);
1855 mWallpaperProgress.show();
1856 start();
1857 }
1858 return true;
1859 }
1860
1861 public void run() {
1862 Drawable oldWallpaper = BrowserActivity.this.getWallpaper();
1863 try {
1864 // TODO: This will cause the resource to be downloaded again, when we
1865 // should in most cases be able to grab it from the cache. To fix this
1866 // we should query WebCore to see if we can access a cached version and
1867 // instead open an input stream on that. This pattern could also be used
1868 // in the download manager where the same problem exists.
1869 InputStream inputstream = mUrl.openStream();
1870 if (inputstream != null) {
1871 setWallpaper(inputstream);
1872 }
1873 } catch (IOException e) {
1874 Log.e(LOGTAG, "Unable to set new wallpaper");
1875 // Act as though the user canceled the operation so we try to
1876 // restore the old wallpaper.
1877 mCanceled = true;
1878 }
1879
1880 if (mCanceled) {
1881 // Restore the old wallpaper if the user cancelled whilst we were setting
1882 // the new wallpaper.
1883 int width = oldWallpaper.getIntrinsicWidth();
1884 int height = oldWallpaper.getIntrinsicHeight();
1885 Bitmap bm = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
1886 Canvas canvas = new Canvas(bm);
1887 oldWallpaper.setBounds(0, 0, width, height);
1888 oldWallpaper.draw(canvas);
1889 try {
1890 setWallpaper(bm);
1891 } catch (IOException e) {
1892 Log.e(LOGTAG, "Unable to restore old wallpaper.");
1893 }
1894 mCanceled = false;
1895 }
1896
1897 if (mWallpaperProgress.isShowing()) {
1898 mWallpaperProgress.dismiss();
1899 }
1900 }
1901 }
1902
The Android Open Source Project0c908882009-03-03 19:32:16 -08001903 private void copy(CharSequence text) {
1904 try {
1905 IClipboard clip = IClipboard.Stub.asInterface(ServiceManager.getService("clipboard"));
1906 if (clip != null) {
1907 clip.setClipboardText(text);
1908 }
1909 } catch (android.os.RemoteException e) {
1910 Log.e(LOGTAG, "Copy failed", e);
1911 }
1912 }
1913
1914 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08001915 * Resets the browser title-view to whatever it must be
1916 * (for example, if we had a loading error)
1917 * When we have a new page, we call resetTitle, when we
1918 * have to reset the titlebar to whatever it used to be
1919 * (for example, if the user chose to stop loading), we
1920 * call resetTitleAndRevertLockIcon.
1921 */
1922 /* package */ void resetTitleAndRevertLockIcon() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001923 mTabControl.getCurrentTab().revertLockIcon();
1924 updateLockIconToLatest();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001925 resetTitleIconAndProgress();
1926 }
1927
1928 /**
1929 * Reset the title, favicon, and progress.
1930 */
1931 private void resetTitleIconAndProgress() {
1932 WebView current = mTabControl.getCurrentWebView();
1933 if (current == null) {
1934 return;
1935 }
1936 resetTitleAndIcon(current);
1937 int progress = current.getProgress();
Grace Kloba22ac16e2009-10-07 18:00:23 -07001938 current.getWebChromeClient().onProgressChanged(current, progress);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001939 }
1940
1941 // Reset the title and the icon based on the given item.
1942 private void resetTitleAndIcon(WebView view) {
1943 WebHistoryItem item = view.copyBackForwardList().getCurrentItem();
1944 if (item != null) {
Leon Scroggins68579392009-09-15 15:31:54 -04001945 setUrlTitle(item.getUrl(), item.getTitle());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001946 setFavicon(item.getFavicon());
1947 } else {
Leon Scroggins68579392009-09-15 15:31:54 -04001948 setUrlTitle(null, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001949 setFavicon(null);
1950 }
1951 }
1952
1953 /**
1954 * Sets a title composed of the URL and the title string.
1955 * @param url The URL of the site being loaded.
1956 * @param title The title of the site being loaded.
1957 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07001958 void setUrlTitle(String url, String title) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001959 mUrl = url;
1960 mTitle = title;
1961
Leon Scroggins58d56c62010-01-28 15:12:40 -05001962 // If we are in voice search mode, the title has already been set.
1963 if (mTabControl.getCurrentTab().isInVoiceSearchMode()) return;
1964 mTitleBar.setDisplayTitle(url);
1965 mFakeTitleBar.setDisplayTitle(url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001966 }
1967
1968 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08001969 * @param url The URL to build a title version of the URL from.
1970 * @return The title version of the URL or null if fails.
1971 * The title version of the URL can be either the URL hostname,
1972 * or the hostname with an "https://" prefix (for secure URLs),
1973 * or an empty string if, for example, the URL in question is a
1974 * file:// URL with no hostname.
1975 */
Leon Scroggins32e14a62009-06-11 10:26:34 -04001976 /* package */ static String buildTitleUrl(String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001977 String titleUrl = null;
1978
1979 if (url != null) {
1980 try {
1981 // parse the url string
1982 URL urlObj = new URL(url);
1983 if (urlObj != null) {
1984 titleUrl = "";
1985
1986 String protocol = urlObj.getProtocol();
1987 String host = urlObj.getHost();
1988
1989 if (host != null && 0 < host.length()) {
1990 titleUrl = host;
1991 if (protocol != null) {
1992 // if a secure site, add an "https://" prefix!
1993 if (protocol.equalsIgnoreCase("https")) {
1994 titleUrl = protocol + "://" + host;
1995 }
1996 }
1997 }
1998 }
1999 } catch (MalformedURLException e) {}
2000 }
2001
2002 return titleUrl;
2003 }
2004
2005 // Set the favicon in the title bar.
Grace Kloba22ac16e2009-10-07 18:00:23 -07002006 void setFavicon(Bitmap icon) {
Leon Scroggins68579392009-09-15 15:31:54 -04002007 mTitleBar.setFavicon(icon);
Leon Scrogginsfe87bd32009-10-06 10:10:00 -04002008 mFakeTitleBar.setFavicon(icon);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002009 }
2010
2011 /**
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002012 * Close the tab, remove its associated title bar, and adjust mTabControl's
2013 * current tab to a valid value.
Leon Scroggins1f005d32009-08-10 17:36:42 -04002014 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07002015 /* package */ void closeTab(Tab t) {
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002016 int currentIndex = mTabControl.getCurrentIndex();
2017 int removeIndex = mTabControl.getTabIndex(t);
Leon Scroggins1f005d32009-08-10 17:36:42 -04002018 mTabControl.removeTab(t);
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002019 if (currentIndex >= removeIndex && currentIndex != 0) {
2020 currentIndex--;
2021 }
2022 mTabControl.setCurrentTab(mTabControl.getTab(currentIndex));
Andrei Popescua5bf1de2009-09-23 16:39:23 +01002023 resetTitleIconAndProgress();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002024 }
2025
Leon Scrogginsdcc5eeb2010-02-23 17:26:37 -05002026 /* package */ void goBackOnePageOrQuit() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002027 Tab current = mTabControl.getCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002028 if (current == null) {
2029 /*
2030 * Instead of finishing the activity, simply push this to the back
2031 * of the stack and let ActivityManager to choose the foreground
2032 * activity. As BrowserActivity is singleTask, it will be always the
2033 * root of the task. So we can use either true or false for
2034 * moveTaskToBack().
2035 */
2036 moveTaskToBack(true);
Grace Kloba00d85e72009-09-23 18:50:05 -07002037 return;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002038 }
2039 WebView w = current.getWebView();
2040 if (w.canGoBack()) {
2041 w.goBack();
2042 } else {
2043 // Check to see if we are closing a window that was created by
2044 // another window. If so, we switch back to that window.
Grace Kloba22ac16e2009-10-07 18:00:23 -07002045 Tab parent = current.getParentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002046 if (parent != null) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04002047 switchToTab(mTabControl.getTabIndex(parent));
2048 // Now we close the other tab
2049 closeTab(current);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002050 } else {
2051 if (current.closeOnExit()) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002052 // force the tab's inLoad() to be false as we are going to
2053 // either finish the activity or remove the tab. This will
2054 // ensure pauseWebViewTimers() taking action.
2055 mTabControl.getCurrentTab().clearInLoad();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002056 if (mTabControl.getTabCount() == 1) {
2057 finish();
2058 return;
2059 }
Mike Reed7bfa63b2009-05-28 11:08:32 -04002060 // call pauseWebViewTimers() now, we won't be able to call
2061 // it in onPause() as the WebView won't be valid.
Grace Klobaec1b5ad2009-08-18 08:42:32 -07002062 // Temporarily change mActivityInPause to be true as
2063 // pauseWebViewTimers() will do nothing if mActivityInPause
2064 // is false.
Grace Kloba918e1d72009-08-13 14:55:06 -07002065 boolean savedState = mActivityInPause;
2066 if (savedState) {
Grace Klobaec1b5ad2009-08-18 08:42:32 -07002067 Log.e(LOGTAG, "BrowserActivity is already paused "
2068 + "while handing goBackOnePageOrQuit.");
Grace Kloba918e1d72009-08-13 14:55:06 -07002069 }
2070 mActivityInPause = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -04002071 pauseWebViewTimers();
Grace Kloba918e1d72009-08-13 14:55:06 -07002072 mActivityInPause = savedState;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002073 removeTabFromContentView(current);
2074 mTabControl.removeTab(current);
2075 }
2076 /*
2077 * Instead of finishing the activity, simply push this to the back
2078 * of the stack and let ActivityManager to choose the foreground
2079 * activity. As BrowserActivity is singleTask, it will be always the
2080 * root of the task. So we can use either true or false for
2081 * moveTaskToBack().
2082 */
2083 moveTaskToBack(true);
2084 }
2085 }
2086 }
2087
Grace Kloba22ac16e2009-10-07 18:00:23 -07002088 boolean isMenuDown() {
2089 return mMenuIsDown;
2090 }
2091
Grace Kloba5942df02009-09-18 11:48:29 -07002092 @Override
2093 public boolean onKeyDown(int keyCode, KeyEvent event) {
Leon Scrogginsf65b50d2009-12-08 10:44:28 -05002094 // Even if MENU is already held down, we need to call to super to open
2095 // the IME on long press.
2096 if (KeyEvent.KEYCODE_MENU == keyCode) {
2097 mMenuIsDown = true;
2098 return super.onKeyDown(keyCode, event);
2099 }
Grace Kloba5942df02009-09-18 11:48:29 -07002100 // The default key mode is DEFAULT_KEYS_SEARCH_LOCAL. As the MENU is
2101 // still down, we don't want to trigger the search. Pretend to consume
2102 // the key and do nothing.
2103 if (mMenuIsDown) return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002104
Grace Kloba5942df02009-09-18 11:48:29 -07002105 switch(keyCode) {
Grace Kloba5942df02009-09-18 11:48:29 -07002106 case KeyEvent.KEYCODE_SPACE:
Grace Klobada0fe552009-09-22 18:17:24 -07002107 // WebView/WebTextView handle the keys in the KeyDown. As
2108 // the Activity's shortcut keys are only handled when WebView
2109 // doesn't, have to do it in onKeyDown instead of onKeyUp.
2110 if (event.isShiftPressed()) {
2111 getTopWindow().pageUp(false);
2112 } else {
2113 getTopWindow().pageDown(false);
2114 }
Grace Kloba5942df02009-09-18 11:48:29 -07002115 return true;
2116 case KeyEvent.KEYCODE_BACK:
2117 if (event.getRepeatCount() == 0) {
2118 event.startTracking();
2119 return true;
2120 } else if (mCustomView == null && mActiveTabsPage == null
2121 && event.isLongPress()) {
2122 bookmarksOrHistoryPicker(true);
2123 return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002124 }
Grace Kloba5942df02009-09-18 11:48:29 -07002125 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002126 }
Grace Kloba5942df02009-09-18 11:48:29 -07002127 return super.onKeyDown(keyCode, event);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002128 }
2129
Grace Kloba5942df02009-09-18 11:48:29 -07002130 @Override
2131 public boolean onKeyUp(int keyCode, KeyEvent event) {
2132 switch(keyCode) {
2133 case KeyEvent.KEYCODE_MENU:
2134 mMenuIsDown = false;
2135 break;
Grace Kloba5942df02009-09-18 11:48:29 -07002136 case KeyEvent.KEYCODE_BACK:
2137 if (event.isTracking() && !event.isCanceled()) {
2138 if (mCustomView != null) {
2139 // if a custom view is showing, hide it
Grace Kloba22ac16e2009-10-07 18:00:23 -07002140 mTabControl.getCurrentWebView().getWebChromeClient()
2141 .onHideCustomView();
Grace Kloba5942df02009-09-18 11:48:29 -07002142 } else if (mActiveTabsPage != null) {
2143 // if tab page is showing, hide it
2144 removeActiveTabPage(true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002145 } else {
Grace Kloba5942df02009-09-18 11:48:29 -07002146 WebView subwindow = mTabControl.getCurrentSubWindow();
2147 if (subwindow != null) {
2148 if (subwindow.canGoBack()) {
2149 subwindow.goBack();
2150 } else {
2151 dismissSubWindow(mTabControl.getCurrentTab());
2152 }
2153 } else {
2154 goBackOnePageOrQuit();
2155 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002156 }
Grace Kloba5942df02009-09-18 11:48:29 -07002157 return true;
2158 }
2159 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002160 }
Grace Kloba5942df02009-09-18 11:48:29 -07002161 return super.onKeyUp(keyCode, event);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002162 }
2163
Leon Scroggins68579392009-09-15 15:31:54 -04002164 /* package */ void stopLoading() {
Ben Murdochb7cc8b42009-09-28 10:59:09 +01002165 mDidStopLoad = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002166 resetTitleAndRevertLockIcon();
2167 WebView w = getTopWindow();
2168 w.stopLoading();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002169 // FIXME: before refactor, it is using mWebViewClient. So I keep the
2170 // same logic here. But for subwindow case, should we call into the main
2171 // WebView's onPageFinished as we never call its onPageStarted and if
2172 // the page finishes itself, we don't call onPageFinished.
2173 mTabControl.getCurrentWebView().getWebViewClient().onPageFinished(w,
2174 w.getUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08002175
2176 cancelStopToast();
2177 mStopToast = Toast
2178 .makeText(this, R.string.stopping, Toast.LENGTH_SHORT);
2179 mStopToast.show();
2180 }
2181
Grace Kloba22ac16e2009-10-07 18:00:23 -07002182 boolean didUserStopLoading() {
2183 return mDidStopLoad;
2184 }
2185
The Android Open Source Project0c908882009-03-03 19:32:16 -08002186 private void cancelStopToast() {
2187 if (mStopToast != null) {
2188 mStopToast.cancel();
2189 mStopToast = null;
2190 }
2191 }
2192
Grace Kloba22ac16e2009-10-07 18:00:23 -07002193 // called by a UI or non-UI thread to post the message
2194 public void postMessage(int what, int arg1, int arg2, Object obj,
2195 long delayMillis) {
2196 mHandler.sendMessageDelayed(mHandler.obtainMessage(what, arg1, arg2,
2197 obj), delayMillis);
2198 }
2199
2200 // called by a UI or non-UI thread to remove the message
2201 void removeMessages(int what, Object object) {
2202 mHandler.removeMessages(what, object);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002203 }
2204
2205 // public message ids
2206 public final static int LOAD_URL = 1001;
2207 public final static int STOP_LOAD = 1002;
2208
2209 // Message Ids
2210 private static final int FOCUS_NODE_HREF = 102;
Grace Kloba92c18a52009-07-31 23:48:32 -07002211 private static final int RELEASE_WAKELOCK = 107;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002212
Grace Kloba22ac16e2009-10-07 18:00:23 -07002213 static final int UPDATE_BOOKMARK_THUMBNAIL = 108;
Ben Murdoch2694e232009-09-29 09:41:11 +01002214
The Android Open Source Project0c908882009-03-03 19:32:16 -08002215 // Private handler for handling javascript and saving passwords
2216 private Handler mHandler = new Handler() {
2217
2218 public void handleMessage(Message msg) {
2219 switch (msg.what) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002220 case FOCUS_NODE_HREF:
Ben Murdoch2694e232009-09-29 09:41:11 +01002221 {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002222 String url = (String) msg.getData().get("url");
Ben Murdoch90d088c2009-11-17 18:14:04 +00002223 String title = (String) msg.getData().get("title");
The Android Open Source Project0c908882009-03-03 19:32:16 -08002224 if (url == null || url.length() == 0) {
2225 break;
2226 }
2227 HashMap focusNodeMap = (HashMap) msg.obj;
2228 WebView view = (WebView) focusNodeMap.get("webview");
2229 // Only apply the action if the top window did not change.
2230 if (getTopWindow() != view) {
2231 break;
2232 }
2233 switch (msg.arg1) {
2234 case R.id.open_context_menu_id:
2235 case R.id.view_image_context_menu_id:
Leon Scroggins92472e82010-02-17 16:32:28 -05002236 loadUrlFromContext(getTopWindow(), url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002237 break;
2238 case R.id.open_newtab_context_menu_id:
Grace Kloba22ac16e2009-10-07 18:00:23 -07002239 final Tab parent = mTabControl.getCurrentTab();
2240 final Tab newTab = openTab(url);
Grace Klobac9181842009-04-14 08:53:22 -07002241 if (newTab != parent) {
2242 parent.addChildTab(newTab);
2243 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002244 break;
2245 case R.id.bookmark_context_menu_id:
2246 Intent intent = new Intent(BrowserActivity.this,
2247 AddBookmarkPage.class);
2248 intent.putExtra("url", url);
Ben Murdoch90d088c2009-11-17 18:14:04 +00002249 intent.putExtra("title", title);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002250 startActivity(intent);
2251 break;
2252 case R.id.share_link_context_menu_id:
Leon Scroggins3e204452010-05-10 11:06:03 -04002253 sharePage(BrowserActivity.this, title, url, null,
Leon Scroggins96afcb12009-12-10 12:35:56 -05002254 null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002255 break;
2256 case R.id.copy_link_context_menu_id:
2257 copy(url);
2258 break;
2259 case R.id.save_link_context_menu_id:
2260 case R.id.download_context_menu_id:
2261 onDownloadStartNoStream(url, null, null, null, -1);
2262 break;
2263 }
2264 break;
Ben Murdoch2694e232009-09-29 09:41:11 +01002265 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002266
2267 case LOAD_URL:
Leon Scroggins92472e82010-02-17 16:32:28 -05002268 loadUrlFromContext(getTopWindow(), (String) msg.obj);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002269 break;
2270
2271 case STOP_LOAD:
2272 stopLoading();
2273 break;
2274
The Android Open Source Project0c908882009-03-03 19:32:16 -08002275 case RELEASE_WAKELOCK:
2276 if (mWakeLock.isHeld()) {
2277 mWakeLock.release();
Grace Kloba5d0e02e2009-10-05 15:15:36 -07002278 // if we reach here, Browser should be still in the
2279 // background loading after WAKELOCK_TIMEOUT (5-min).
2280 // To avoid burning the battery, stop loading.
2281 mTabControl.stopAllLoading();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002282 }
2283 break;
Ben Murdoch2694e232009-09-29 09:41:11 +01002284
2285 case UPDATE_BOOKMARK_THUMBNAIL:
2286 WebView view = (WebView) msg.obj;
2287 if (view != null) {
2288 updateScreenshot(view);
2289 }
2290 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002291 }
2292 }
2293 };
2294
Leon Scroggins96afcb12009-12-10 12:35:56 -05002295 /**
2296 * Share a page, providing the title, url, favicon, and a screenshot. Uses
2297 * an {@link Intent} to launch the Activity chooser.
2298 * @param c Context used to launch a new Activity.
2299 * @param title Title of the page. Stored in the Intent with
Paul Westbrook03e6d392010-02-12 10:33:29 -08002300 * {@link Intent#EXTRA_SUBJECT}
Leon Scroggins96afcb12009-12-10 12:35:56 -05002301 * @param url URL of the page. Stored in the Intent with
2302 * {@link Intent#EXTRA_TEXT}
2303 * @param favicon Bitmap of the favicon for the page. Stored in the Intent
2304 * with {@link Browser#EXTRA_SHARE_FAVICON}
2305 * @param screenshot Bitmap of a screenshot of the page. Stored in the
2306 * Intent with {@link Browser#EXTRA_SHARE_SCREENSHOT}
2307 */
2308 public static final void sharePage(Context c, String title, String url,
2309 Bitmap favicon, Bitmap screenshot) {
2310 Intent send = new Intent(Intent.ACTION_SEND);
2311 send.setType("text/plain");
2312 send.putExtra(Intent.EXTRA_TEXT, url);
Paul Westbrook03e6d392010-02-12 10:33:29 -08002313 send.putExtra(Intent.EXTRA_SUBJECT, title);
Leon Scroggins96afcb12009-12-10 12:35:56 -05002314 send.putExtra(Browser.EXTRA_SHARE_FAVICON, favicon);
2315 send.putExtra(Browser.EXTRA_SHARE_SCREENSHOT, screenshot);
2316 try {
2317 c.startActivity(Intent.createChooser(send, c.getString(
2318 R.string.choosertitle_sharevia)));
2319 } catch(android.content.ActivityNotFoundException ex) {
2320 // if no app handles it, do nothing
2321 }
2322 }
2323
Leon Scroggins89c6d362009-07-15 16:54:37 -04002324 private void updateScreenshot(WebView view) {
2325 // If this is a bookmarked site, add a screenshot to the database.
2326 // FIXME: When should we update? Every time?
2327 // FIXME: Would like to make sure there is actually something to
2328 // draw, but the API for that (WebViewCore.pictureReady()) is not
2329 // currently accessible here.
Ben Murdochaac7aa62009-09-17 16:57:40 +01002330
Patrick Scottcb192b52010-04-14 14:38:55 -04002331 final Bitmap bm = createScreenshot(view);
2332 if (bm == null) {
2333 return;
Leon Scroggins89c6d362009-07-15 16:54:37 -04002334 }
Patrick Scottcb192b52010-04-14 14:38:55 -04002335
2336 final ContentResolver cr = getContentResolver();
2337 final String url = view.getUrl();
2338 final String originalUrl = view.getOriginalUrl();
2339
2340 new AsyncTask<Void, Void, Void>() {
2341 @Override
2342 protected Void doInBackground(Void... unused) {
2343 Cursor c = null;
2344 try {
2345 c = BrowserBookmarksAdapter.queryBookmarksForUrl(
2346 cr, originalUrl, url, true);
2347 if (c != null) {
2348 if (c.moveToFirst()) {
2349 ContentValues values = new ContentValues();
2350 final ByteArrayOutputStream os
2351 = new ByteArrayOutputStream();
2352 bm.compress(Bitmap.CompressFormat.PNG, 100, os);
2353 values.put(Browser.BookmarkColumns.THUMBNAIL,
2354 os.toByteArray());
2355 do {
2356 cr.update(ContentUris.withAppendedId(
2357 Browser.BOOKMARKS_URI, c.getInt(0)),
2358 values, null, null);
2359 } while (c.moveToNext());
2360 }
2361 }
2362 } catch (IllegalStateException e) {
2363 // Ignore
2364 } finally {
2365 if (c != null) c.close();
2366 }
2367 return null;
2368 }
2369 }.execute();
Leon Scroggins89c6d362009-07-15 16:54:37 -04002370 }
2371
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002372 /**
Leon Scrogginsf8551612009-09-24 16:06:02 -04002373 * Values for the size of the thumbnail created when taking a screenshot.
2374 * Lazily initialized. Instead of using these directly, use
2375 * getDesiredThumbnailWidth() or getDesiredThumbnailHeight().
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002376 */
Leon Scrogginsf8551612009-09-24 16:06:02 -04002377 private static int THUMBNAIL_WIDTH = 0;
2378 private static int THUMBNAIL_HEIGHT = 0;
2379
2380 /**
2381 * Return the desired width for thumbnail screenshots, which are stored in
2382 * the database, and used on the bookmarks screen.
2383 * @param context Context for finding out the density of the screen.
2384 * @return int desired width for thumbnail screenshot.
2385 */
2386 /* package */ static int getDesiredThumbnailWidth(Context context) {
2387 if (THUMBNAIL_WIDTH == 0) {
2388 float density = context.getResources().getDisplayMetrics().density;
2389 THUMBNAIL_WIDTH = (int) (90 * density);
2390 THUMBNAIL_HEIGHT = (int) (80 * density);
2391 }
2392 return THUMBNAIL_WIDTH;
2393 }
2394
2395 /**
2396 * Return the desired height for thumbnail screenshots, which are stored in
2397 * the database, and used on the bookmarks screen.
2398 * @param context Context for finding out the density of the screen.
2399 * @return int desired height for thumbnail screenshot.
2400 */
2401 /* package */ static int getDesiredThumbnailHeight(Context context) {
2402 // To ensure that they are both initialized.
2403 getDesiredThumbnailWidth(context);
2404 return THUMBNAIL_HEIGHT;
2405 }
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002406
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002407 private Bitmap createScreenshot(WebView view) {
2408 Picture thumbnail = view.capturePicture();
Leon Scroggins45800572009-09-29 16:38:47 -04002409 if (thumbnail == null) {
2410 return null;
2411 }
Leon Scrogginsf8551612009-09-24 16:06:02 -04002412 Bitmap bm = Bitmap.createBitmap(getDesiredThumbnailWidth(this),
Cary Clarkab168ba2010-04-08 09:11:28 -04002413 getDesiredThumbnailHeight(this), Bitmap.Config.RGB_565);
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002414 Canvas canvas = new Canvas(bm);
2415 // May need to tweak these values to determine what is the
2416 // best scale factor
Ben Murdoch2694e232009-09-29 09:41:11 +01002417 int thumbnailWidth = thumbnail.getWidth();
Ben Murdochae59c3f2009-10-20 18:30:28 +01002418 int thumbnailHeight = thumbnail.getHeight();
2419 float scaleFactorX = 1.0f;
2420 float scaleFactorY = 1.0f;
Ben Murdoch2694e232009-09-29 09:41:11 +01002421 if (thumbnailWidth > 0) {
Ben Murdochae59c3f2009-10-20 18:30:28 +01002422 scaleFactorX = (float) getDesiredThumbnailWidth(this) /
Ben Murdoch2694e232009-09-29 09:41:11 +01002423 (float)thumbnailWidth;
Ben Murdochae59c3f2009-10-20 18:30:28 +01002424 } else {
2425 return null;
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002426 }
Ben Murdochae59c3f2009-10-20 18:30:28 +01002427
2428 if (view.getWidth() > view.getHeight() &&
2429 thumbnailHeight < view.getHeight() && thumbnailHeight > 0) {
2430 // If the device is in landscape and the page is shorter
2431 // than the height of the view, stretch the thumbnail to fill the
2432 // space.
2433 scaleFactorY = (float) getDesiredThumbnailHeight(this) /
2434 (float)thumbnailHeight;
2435 } else {
2436 // In the portrait case, this looks nice.
2437 scaleFactorY = scaleFactorX;
2438 }
2439
2440 canvas.scale(scaleFactorX, scaleFactorY);
2441
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002442 thumbnail.draw(canvas);
2443 return bm;
2444 }
2445
The Android Open Source Project0c908882009-03-03 19:32:16 -08002446 // -------------------------------------------------------------------------
Grace Kloba22ac16e2009-10-07 18:00:23 -07002447 // Helper function for WebViewClient.
The Android Open Source Project0c908882009-03-03 19:32:16 -08002448 //-------------------------------------------------------------------------
2449
2450 // Use in overrideUrlLoading
2451 /* package */ final static String SCHEME_WTAI = "wtai://wp/";
2452 /* package */ final static String SCHEME_WTAI_MC = "wtai://wp/mc;";
2453 /* package */ final static String SCHEME_WTAI_SD = "wtai://wp/sd;";
2454 /* package */ final static String SCHEME_WTAI_AP = "wtai://wp/ap;";
2455
Leon Scroggins92472e82010-02-17 16:32:28 -05002456 // Keep this initial progress in sync with initialProgressValue (* 100)
2457 // in ProgressTracker.cpp
2458 private final static int INITIAL_PROGRESS = 10;
2459
Grace Kloba22ac16e2009-10-07 18:00:23 -07002460 void onPageStarted(WebView view, String url, Bitmap favicon) {
2461 // when BrowserActivity just starts, onPageStarted may be called before
2462 // onResume as it is triggered from onCreate. Call resumeWebViewTimers
2463 // to start the timer. As we won't switch tabs while an activity is in
2464 // pause state, we can ensure calling resume and pause in pair.
2465 if (mActivityInPause) resumeWebViewTimers();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002466
Grace Kloba22ac16e2009-10-07 18:00:23 -07002467 resetLockIcon(url);
2468 setUrlTitle(url, null);
2469 setFavicon(favicon);
Leon Scroggins8cf8f682009-11-04 11:13:50 -08002470 // Show some progress so that the user knows the page is beginning to
2471 // load
Leon Scroggins92472e82010-02-17 16:32:28 -05002472 onProgressChanged(view, INITIAL_PROGRESS);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002473 mDidStopLoad = false;
Grace Kloba22ac16e2009-10-07 18:00:23 -07002474 if (!mIsNetworkUp) createAndShowNetworkDialog();
Leon Scroggins III211ba542010-04-19 13:21:13 -04002475 if (view.getFindIsUp()) {
2476 closeFind();
2477 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002478 if (mSettings.isTracing()) {
2479 String host;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002480 try {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002481 WebAddress uri = new WebAddress(url);
2482 host = uri.mHost;
2483 } catch (android.net.ParseException ex) {
2484 host = "browser";
The Android Open Source Project0c908882009-03-03 19:32:16 -08002485 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002486 host = host.replace('.', '_');
2487 host += ".trace";
2488 mInTrace = true;
2489 Debug.startMethodTracing(host, 20 * 1024 * 1024);
2490 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002491
Grace Kloba22ac16e2009-10-07 18:00:23 -07002492 // Performance probe
2493 if (false) {
2494 mStart = SystemClock.uptimeMillis();
2495 mProcessStart = Process.getElapsedCpuTime();
2496 long[] sysCpu = new long[7];
2497 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2498 sysCpu, null)) {
2499 mUserStart = sysCpu[0] + sysCpu[1];
2500 mSystemStart = sysCpu[2];
2501 mIdleStart = sysCpu[3];
2502 mIrqStart = sysCpu[4] + sysCpu[5] + sysCpu[6];
2503 }
2504 mUiStart = SystemClock.currentThreadTimeMillis();
2505 }
2506 }
2507
2508 void onPageFinished(WebView view, String url) {
2509 // Reset the title and icon in case we stopped a provisional load.
2510 resetTitleAndIcon(view);
2511 // Update the lock icon image only once we are done loading
2512 updateLockIconToLatest();
2513 // pause the WebView timer and release the wake lock if it is finished
2514 // while BrowserActivity is in pause state.
2515 if (mActivityInPause && pauseWebViewTimers()) {
2516 if (mWakeLock.isHeld()) {
2517 mHandler.removeMessages(RELEASE_WAKELOCK);
2518 mWakeLock.release();
2519 }
2520 }
2521
2522 // Performance probe
2523 if (false) {
2524 long[] sysCpu = new long[7];
2525 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2526 sysCpu, null)) {
2527 String uiInfo = "UI thread used "
2528 + (SystemClock.currentThreadTimeMillis() - mUiStart)
2529 + " ms";
2530 if (LOGD_ENABLED) {
2531 Log.d(LOGTAG, uiInfo);
2532 }
2533 //The string that gets written to the log
2534 String performanceString = "It took total "
2535 + (SystemClock.uptimeMillis() - mStart)
2536 + " ms clock time to load the page."
2537 + "\nbrowser process used "
2538 + (Process.getElapsedCpuTime() - mProcessStart)
2539 + " ms, user processes used "
2540 + (sysCpu[0] + sysCpu[1] - mUserStart) * 10
2541 + " ms, kernel used "
2542 + (sysCpu[2] - mSystemStart) * 10
2543 + " ms, idle took " + (sysCpu[3] - mIdleStart) * 10
2544 + " ms and irq took "
2545 + (sysCpu[4] + sysCpu[5] + sysCpu[6] - mIrqStart)
2546 * 10 + " ms, " + uiInfo;
2547 if (LOGD_ENABLED) {
2548 Log.d(LOGTAG, performanceString + "\nWebpage: " + url);
2549 }
2550 if (url != null) {
2551 // strip the url to maintain consistency
2552 String newUrl = new String(url);
2553 if (newUrl.startsWith("http://www.")) {
2554 newUrl = newUrl.substring(11);
2555 } else if (newUrl.startsWith("http://")) {
2556 newUrl = newUrl.substring(7);
2557 } else if (newUrl.startsWith("https://www.")) {
2558 newUrl = newUrl.substring(12);
2559 } else if (newUrl.startsWith("https://")) {
2560 newUrl = newUrl.substring(8);
2561 }
2562 if (LOGD_ENABLED) {
2563 Log.d(LOGTAG, newUrl + " loaded");
2564 }
Grace Kloba5b078b52009-06-24 20:23:41 -07002565 }
2566 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002567 }
Grace Kloba5b078b52009-06-24 20:23:41 -07002568
Grace Kloba22ac16e2009-10-07 18:00:23 -07002569 if (mInTrace) {
2570 mInTrace = false;
2571 Debug.stopMethodTracing();
2572 }
2573 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002574
Grace Kloba22ac16e2009-10-07 18:00:23 -07002575 boolean shouldOverrideUrlLoading(WebView view, String url) {
2576 if (url.startsWith(SCHEME_WTAI)) {
2577 // wtai://wp/mc;number
2578 // number=string(phone-number)
2579 if (url.startsWith(SCHEME_WTAI_MC)) {
2580 Intent intent = new Intent(Intent.ACTION_VIEW,
2581 Uri.parse(WebView.SCHEME_TEL +
2582 url.substring(SCHEME_WTAI_MC.length())));
2583 startActivity(intent);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002584 return true;
2585 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002586 // wtai://wp/sd;dtmf
2587 // dtmf=string(dialstring)
2588 if (url.startsWith(SCHEME_WTAI_SD)) {
2589 // TODO: only send when there is active voice connection
2590 return false;
2591 }
2592 // wtai://wp/ap;number;name
2593 // number=string(phone-number)
2594 // name=string
2595 if (url.startsWith(SCHEME_WTAI_AP)) {
2596 // TODO
2597 return false;
2598 }
2599 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002600
Grace Kloba22ac16e2009-10-07 18:00:23 -07002601 // The "about:" schemes are internal to the browser; don't want these to
2602 // be dispatched to other apps.
2603 if (url.startsWith("about:")) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002604 return false;
2605 }
2606
Grace Kloba22ac16e2009-10-07 18:00:23 -07002607 Intent intent;
2608 // perform generic parsing of the URI to turn it into an Intent.
2609 try {
2610 intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME);
2611 } catch (URISyntaxException ex) {
2612 Log.w("Browser", "Bad URI " + url + ": " + ex.getMessage());
2613 return false;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002614 }
2615
Grace Kloba22ac16e2009-10-07 18:00:23 -07002616 // check whether the intent can be resolved. If not, we will see
2617 // whether we can download it from the Market.
2618 if (getPackageManager().resolveActivity(intent, 0) == null) {
2619 String packagename = intent.getPackage();
2620 if (packagename != null) {
2621 intent = new Intent(Intent.ACTION_VIEW, Uri
2622 .parse("market://search?q=pname:" + packagename));
2623 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2624 startActivity(intent);
2625 return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002626 } else {
2627 return false;
2628 }
2629 }
2630
Grace Kloba22ac16e2009-10-07 18:00:23 -07002631 // sanitize the Intent, ensuring web pages can not bypass browser
2632 // security (only access to BROWSABLE activities).
2633 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2634 intent.setComponent(null);
2635 try {
2636 if (startActivityIfNeeded(intent, -1)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002637 return true;
2638 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002639 } catch (ActivityNotFoundException ex) {
2640 // ignore the error. If no application can handle the URL,
2641 // eg about:blank, assume the browser can handle it.
2642 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002643
Grace Kloba22ac16e2009-10-07 18:00:23 -07002644 if (mMenuIsDown) {
2645 openTab(url);
2646 closeOptionsMenu();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002647 return true;
2648 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002649 return false;
2650 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002651
Grace Kloba22ac16e2009-10-07 18:00:23 -07002652 // -------------------------------------------------------------------------
2653 // Helper function for WebChromeClient
2654 // -------------------------------------------------------------------------
The Android Open Source Project0c908882009-03-03 19:32:16 -08002655
Grace Kloba22ac16e2009-10-07 18:00:23 -07002656 void onProgressChanged(WebView view, int newProgress) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002657 mFakeTitleBar.setProgress(newProgress);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002658
Grace Kloba22ac16e2009-10-07 18:00:23 -07002659 if (newProgress == 100) {
2660 // onProgressChanged() may continue to be called after the main
2661 // frame has finished loading, as any remaining sub frames continue
2662 // to load. We'll only get called once though with newProgress as
2663 // 100 when everything is loaded. (onPageFinished is called once
2664 // when the main frame completes loading regardless of the state of
2665 // any sub frames so calls to onProgressChanges may continue after
2666 // onPageFinished has executed)
2667 if (mInLoad) {
2668 mInLoad = false;
Leon Scrogginsa27ff192009-09-14 12:58:04 -04002669 updateInLoadMenuItems();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002670 // If the options menu is open, leave the title bar
2671 if (!mOptionsMenuOpen || !mIconView) {
2672 hideFakeTitleBar();
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07002673 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002674 }
Leon Scrogginsaa37e7f2010-03-05 11:51:20 -05002675 } else {
2676 if (!mInLoad) {
2677 // onPageFinished may have already been called but a subframe is
2678 // still loading and updating the progress. Reset mInLoad and
2679 // update the menu items.
2680 mInLoad = true;
2681 updateInLoadMenuItems();
2682 }
2683 // When the page first begins to load, the Activity may still be
2684 // paused, in which case showFakeTitleBar will do nothing. Call
2685 // again as the page continues to load so that it will be shown.
2686 // (Calling it will the fake title bar is already showing will also
2687 // do nothing.
Grace Kloba22ac16e2009-10-07 18:00:23 -07002688 if (!mOptionsMenuOpen || mIconView) {
2689 // This page has begun to load, so show the title bar
2690 showFakeTitleBar();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002691 }
2692 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002693 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002694
Grace Kloba22ac16e2009-10-07 18:00:23 -07002695 void onShowCustomView(View view, WebChromeClient.CustomViewCallback callback) {
Derek Sollenberger8ff57db2009-12-08 15:39:55 -05002696 // if a view already exists then immediately terminate the new one
2697 if (mCustomView != null) {
2698 callback.onCustomViewHidden();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002699 return;
Derek Sollenberger8ff57db2009-12-08 15:39:55 -05002700 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002701
2702 // Add the custom view to its container.
2703 mCustomViewContainer.addView(view, COVER_SCREEN_GRAVITY_CENTER);
2704 mCustomView = view;
2705 mCustomViewCallback = callback;
2706 // Save the menu state and set it to empty while the custom
2707 // view is showing.
2708 mOldMenuState = mMenuState;
2709 mMenuState = EMPTY_MENU;
2710 // Hide the content view.
2711 mContentView.setVisibility(View.GONE);
2712 // Finally show the custom view container.
Andrei Popescu163ab742009-10-20 17:58:23 +01002713 setStatusBarVisibility(false);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002714 mCustomViewContainer.setVisibility(View.VISIBLE);
2715 mCustomViewContainer.bringToFront();
2716 }
2717
2718 void onHideCustomView() {
2719 if (mCustomView == null)
2720 return;
2721
2722 // Hide the custom view.
2723 mCustomView.setVisibility(View.GONE);
2724 // Remove the custom view from its container.
2725 mCustomViewContainer.removeView(mCustomView);
2726 mCustomView = null;
2727 // Reset the old menu state.
2728 mMenuState = mOldMenuState;
2729 mOldMenuState = EMPTY_MENU;
2730 mCustomViewContainer.setVisibility(View.GONE);
2731 mCustomViewCallback.onCustomViewHidden();
2732 // Show the content view.
Andrei Popescu163ab742009-10-20 17:58:23 +01002733 setStatusBarVisibility(true);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002734 mContentView.setVisibility(View.VISIBLE);
2735 }
2736
2737 Bitmap getDefaultVideoPoster() {
2738 if (mDefaultVideoPoster == null) {
2739 mDefaultVideoPoster = BitmapFactory.decodeResource(
2740 getResources(), R.drawable.default_video_poster);
Patrick Scott3918d442009-08-04 13:22:29 -04002741 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002742 return mDefaultVideoPoster;
2743 }
Patrick Scott3918d442009-08-04 13:22:29 -04002744
Grace Kloba22ac16e2009-10-07 18:00:23 -07002745 View getVideoLoadingProgressView() {
2746 if (mVideoProgressView == null) {
2747 LayoutInflater inflater = LayoutInflater.from(BrowserActivity.this);
2748 mVideoProgressView = inflater.inflate(
2749 R.layout.video_loading_progress, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002750 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002751 return mVideoProgressView;
2752 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002753
Leon Scroggins8d5fa432009-10-02 15:55:59 -04002754 /*
2755 * The Object used to inform the WebView of the file to upload.
2756 */
2757 private ValueCallback<Uri> mUploadMessage;
2758
Grace Kloba22ac16e2009-10-07 18:00:23 -07002759 void openFileChooser(ValueCallback<Uri> uploadMsg) {
2760 if (mUploadMessage != null) return;
2761 mUploadMessage = uploadMsg;
2762 Intent i = new Intent(Intent.ACTION_GET_CONTENT);
2763 i.addCategory(Intent.CATEGORY_OPENABLE);
2764 i.setType("*/*");
2765 BrowserActivity.this.startActivityForResult(Intent.createChooser(i,
2766 getString(R.string.choose_upload)), FILE_SELECTED);
2767 }
2768
2769 // -------------------------------------------------------------------------
2770 // Implement functions for DownloadListener
2771 // -------------------------------------------------------------------------
2772
The Android Open Source Project0c908882009-03-03 19:32:16 -08002773 /**
2774 * Notify the host application a download should be done, or that
2775 * the data should be streamed if a streaming viewer is available.
2776 * @param url The full url to the content that should be downloaded
2777 * @param contentDisposition Content-disposition http header, if
2778 * present.
2779 * @param mimetype The mimetype of the content reported by the server
2780 * @param contentLength The file size reported by the server
2781 */
2782 public void onDownloadStart(String url, String userAgent,
2783 String contentDisposition, String mimetype, long contentLength) {
2784 // if we're dealing wih A/V content that's not explicitly marked
2785 // for download, check if it's streamable.
2786 if (contentDisposition == null
Patrick Scotte1fb9662009-08-31 14:31:52 -04002787 || !contentDisposition.regionMatches(
2788 true, 0, "attachment", 0, 10)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002789 // query the package manager to see if there's a registered handler
2790 // that matches.
2791 Intent intent = new Intent(Intent.ACTION_VIEW);
2792 intent.setDataAndType(Uri.parse(url), mimetype);
Patrick Scotte1fb9662009-08-31 14:31:52 -04002793 ResolveInfo info = getPackageManager().resolveActivity(intent,
2794 PackageManager.MATCH_DEFAULT_ONLY);
2795 if (info != null) {
2796 ComponentName myName = getComponentName();
2797 // If we resolved to ourselves, we don't want to attempt to
2798 // load the url only to try and download it again.
2799 if (!myName.getPackageName().equals(
2800 info.activityInfo.packageName)
2801 || !myName.getClassName().equals(
2802 info.activityInfo.name)) {
2803 // someone (other than us) knows how to handle this mime
2804 // type with this scheme, don't download.
2805 try {
2806 startActivity(intent);
2807 return;
2808 } catch (ActivityNotFoundException ex) {
2809 if (LOGD_ENABLED) {
2810 Log.d(LOGTAG, "activity not found for " + mimetype
2811 + " over " + Uri.parse(url).getScheme(),
2812 ex);
2813 }
2814 // Best behavior is to fall back to a download in this
2815 // case
The Android Open Source Project0c908882009-03-03 19:32:16 -08002816 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002817 }
2818 }
2819 }
2820 onDownloadStartNoStream(url, userAgent, contentDisposition, mimetype, contentLength);
2821 }
2822
Kristian Monsenfa52d172010-03-25 18:29:21 +00002823 // This is to work around the fact that java.net.URI throws Exceptions
2824 // instead of just encoding URL's properly
2825 // Helper method for onDownloadStartNoStream
2826 private static String encodePath(String path) {
2827 char[] chars = path.toCharArray();
2828
2829 boolean needed = false;
2830 for (char c : chars) {
2831 if (c == '[' || c == ']') {
2832 needed = true;
2833 break;
2834 }
2835 }
2836 if (needed == false) {
2837 return path;
2838 }
2839
2840 StringBuilder sb = new StringBuilder("");
2841 for (char c : chars) {
2842 if (c == '[' || c == ']') {
2843 sb.append('%');
2844 sb.append(Integer.toHexString(c));
2845 } else {
2846 sb.append(c);
2847 }
2848 }
2849
2850 return sb.toString();
2851 }
2852
The Android Open Source Project0c908882009-03-03 19:32:16 -08002853 /**
2854 * Notify the host application a download should be done, even if there
2855 * is a streaming viewer available for thise type.
2856 * @param url The full url to the content that should be downloaded
2857 * @param contentDisposition Content-disposition http header, if
2858 * present.
2859 * @param mimetype The mimetype of the content reported by the server
2860 * @param contentLength The file size reported by the server
2861 */
2862 /*package */ void onDownloadStartNoStream(String url, String userAgent,
2863 String contentDisposition, String mimetype, long contentLength) {
2864
2865 String filename = URLUtil.guessFileName(url,
2866 contentDisposition, mimetype);
2867
2868 // Check to see if we have an SDCard
2869 String status = Environment.getExternalStorageState();
2870 if (!status.equals(Environment.MEDIA_MOUNTED)) {
2871 int title;
2872 String msg;
2873
2874 // Check to see if the SDCard is busy, same as the music app
2875 if (status.equals(Environment.MEDIA_SHARED)) {
2876 msg = getString(R.string.download_sdcard_busy_dlg_msg);
2877 title = R.string.download_sdcard_busy_dlg_title;
2878 } else {
2879 msg = getString(R.string.download_no_sdcard_dlg_msg, filename);
2880 title = R.string.download_no_sdcard_dlg_title;
2881 }
2882
2883 new AlertDialog.Builder(this)
2884 .setTitle(title)
2885 .setIcon(android.R.drawable.ic_dialog_alert)
2886 .setMessage(msg)
2887 .setPositiveButton(R.string.ok, null)
2888 .show();
2889 return;
2890 }
2891
Kristian Monsenfa52d172010-03-25 18:29:21 +00002892 // java.net.URI is a lot stricter than KURL so we have to encode some
2893 // extra characters. Fix for b 2538060 and b 1634719
2894 WebAddress webAddress;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002895 try {
Kristian Monsenfa52d172010-03-25 18:29:21 +00002896 webAddress = new WebAddress(url);
2897 webAddress.mPath = encodePath(webAddress.mPath);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002898 } catch (Exception e) {
Kristian Monsenfa52d172010-03-25 18:29:21 +00002899 // This only happens for very bad urls, we want to chatch the
2900 // exception here
2901 Log.e(LOGTAG, "Exception trying to parse url:" + url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002902 return;
2903 }
2904
2905 // XXX: Have to use the old url since the cookies were stored using the
2906 // old percent-encoded url.
2907 String cookies = CookieManager.getInstance().getCookie(url);
2908
2909 ContentValues values = new ContentValues();
Kristian Monsenfa52d172010-03-25 18:29:21 +00002910 values.put(Downloads.Impl.COLUMN_URI, webAddress.toString());
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08002911 values.put(Downloads.Impl.COLUMN_COOKIE_DATA, cookies);
2912 values.put(Downloads.Impl.COLUMN_USER_AGENT, userAgent);
2913 values.put(Downloads.Impl.COLUMN_NOTIFICATION_PACKAGE,
The Android Open Source Project0c908882009-03-03 19:32:16 -08002914 getPackageName());
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08002915 values.put(Downloads.Impl.COLUMN_NOTIFICATION_CLASS,
Leon Scrogginsa563d092010-04-19 16:53:49 -04002916 OpenDownloadReceiver.class.getCanonicalName());
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08002917 values.put(Downloads.Impl.COLUMN_VISIBILITY,
2918 Downloads.Impl.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
2919 values.put(Downloads.Impl.COLUMN_MIME_TYPE, mimetype);
2920 values.put(Downloads.Impl.COLUMN_FILE_NAME_HINT, filename);
Kristian Monsenfa52d172010-03-25 18:29:21 +00002921 values.put(Downloads.Impl.COLUMN_DESCRIPTION, webAddress.mHost);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002922 if (contentLength > 0) {
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08002923 values.put(Downloads.Impl.COLUMN_TOTAL_BYTES, contentLength);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002924 }
2925 if (mimetype == null) {
2926 // We must have long pressed on a link or image to download it. We
2927 // are not sure of the mimetype in this case, so do a head request
2928 new FetchUrlMimeType(this).execute(values);
2929 } else {
2930 final Uri contentUri =
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08002931 getContentResolver().insert(Downloads.Impl.CONTENT_URI, values);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002932 }
Leon Scroggins9191a7f2010-03-18 14:44:44 -04002933 Toast.makeText(this, R.string.download_pending, Toast.LENGTH_SHORT)
2934 .show();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002935 }
2936
Grace Kloba22ac16e2009-10-07 18:00:23 -07002937 // -------------------------------------------------------------------------
2938
The Android Open Source Project0c908882009-03-03 19:32:16 -08002939 /**
2940 * Resets the lock icon. This method is called when we start a new load and
2941 * know the url to be loaded.
2942 */
2943 private void resetLockIcon(String url) {
2944 // Save the lock-icon state (we revert to it if the load gets cancelled)
Grace Kloba22ac16e2009-10-07 18:00:23 -07002945 mTabControl.getCurrentTab().resetLockIcon(url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002946 updateLockIconImage(LOCK_ICON_UNSECURE);
2947 }
2948
The Android Open Source Project0c908882009-03-03 19:32:16 -08002949 /**
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04002950 * Update the lock icon to correspond to our latest state.
2951 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07002952 private void updateLockIconToLatest() {
2953 updateLockIconImage(mTabControl.getCurrentTab().getLockIconType());
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04002954 }
2955
2956 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08002957 * Updates the lock-icon image in the title-bar.
2958 */
2959 private void updateLockIconImage(int lockIconType) {
2960 Drawable d = null;
2961 if (lockIconType == LOCK_ICON_SECURE) {
2962 d = mSecLockIcon;
2963 } else if (lockIconType == LOCK_ICON_MIXED) {
2964 d = mMixLockIcon;
2965 }
Leon Scroggins68579392009-09-15 15:31:54 -04002966 mTitleBar.setLock(d);
Leon Scrogginsfe87bd32009-10-06 10:10:00 -04002967 mFakeTitleBar.setLock(d);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002968 }
2969
2970 /**
2971 * Displays a page-info dialog.
2972 * @param tab The tab to show info about
2973 * @param fromShowSSLCertificateOnError The flag that indicates whether
2974 * this dialog was opened from the SSL-certificate-on-error dialog or
2975 * not. This is important, since we need to know whether to return to
2976 * the parent dialog or simply dismiss.
2977 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07002978 private void showPageInfo(final Tab tab,
The Android Open Source Project0c908882009-03-03 19:32:16 -08002979 final boolean fromShowSSLCertificateOnError) {
2980 final LayoutInflater factory = LayoutInflater
2981 .from(this);
2982
2983 final View pageInfoView = factory.inflate(R.layout.page_info, null);
2984
2985 final WebView view = tab.getWebView();
2986
2987 String url = null;
2988 String title = null;
2989
2990 if (view == null) {
2991 url = tab.getUrl();
2992 title = tab.getTitle();
2993 } else if (view == mTabControl.getCurrentWebView()) {
2994 // Use the cached title and url if this is the current WebView
2995 url = mUrl;
2996 title = mTitle;
2997 } else {
2998 url = view.getUrl();
2999 title = view.getTitle();
3000 }
3001
3002 if (url == null) {
3003 url = "";
3004 }
3005 if (title == null) {
3006 title = "";
3007 }
3008
3009 ((TextView) pageInfoView.findViewById(R.id.address)).setText(url);
3010 ((TextView) pageInfoView.findViewById(R.id.title)).setText(title);
3011
3012 mPageInfoView = tab;
Leon Scrogginsc7b92f82010-01-11 18:17:31 -05003013 mPageInfoFromShowSSLCertificateOnError = fromShowSSLCertificateOnError;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003014
3015 AlertDialog.Builder alertDialogBuilder =
3016 new AlertDialog.Builder(this)
3017 .setTitle(R.string.page_info).setIcon(android.R.drawable.ic_dialog_info)
3018 .setView(pageInfoView)
3019 .setPositiveButton(
3020 R.string.ok,
3021 new DialogInterface.OnClickListener() {
3022 public void onClick(DialogInterface dialog,
3023 int whichButton) {
3024 mPageInfoDialog = null;
3025 mPageInfoView = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003026
3027 // if we came here from the SSL error dialog
3028 if (fromShowSSLCertificateOnError) {
3029 // go back to the SSL error dialog
3030 showSSLCertificateOnError(
3031 mSSLCertificateOnErrorView,
3032 mSSLCertificateOnErrorHandler,
3033 mSSLCertificateOnErrorError);
3034 }
3035 }
3036 })
3037 .setOnCancelListener(
3038 new DialogInterface.OnCancelListener() {
3039 public void onCancel(DialogInterface dialog) {
3040 mPageInfoDialog = null;
3041 mPageInfoView = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003042
3043 // if we came here from the SSL error dialog
3044 if (fromShowSSLCertificateOnError) {
3045 // go back to the SSL error dialog
3046 showSSLCertificateOnError(
3047 mSSLCertificateOnErrorView,
3048 mSSLCertificateOnErrorHandler,
3049 mSSLCertificateOnErrorError);
3050 }
3051 }
3052 });
3053
3054 // if we have a main top-level page SSL certificate set or a certificate
3055 // error
3056 if (fromShowSSLCertificateOnError ||
3057 (view != null && view.getCertificate() != null)) {
3058 // add a 'View Certificate' button
3059 alertDialogBuilder.setNeutralButton(
3060 R.string.view_certificate,
3061 new DialogInterface.OnClickListener() {
3062 public void onClick(DialogInterface dialog,
3063 int whichButton) {
3064 mPageInfoDialog = null;
3065 mPageInfoView = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003066
3067 // if we came here from the SSL error dialog
3068 if (fromShowSSLCertificateOnError) {
3069 // go back to the SSL error dialog
3070 showSSLCertificateOnError(
3071 mSSLCertificateOnErrorView,
3072 mSSLCertificateOnErrorHandler,
3073 mSSLCertificateOnErrorError);
3074 } else {
3075 // otherwise, display the top-most certificate from
3076 // the chain
3077 if (view.getCertificate() != null) {
3078 showSSLCertificate(tab);
3079 }
3080 }
3081 }
3082 });
3083 }
3084
3085 mPageInfoDialog = alertDialogBuilder.show();
3086 }
3087
3088 /**
3089 * Displays the main top-level page SSL certificate dialog
3090 * (accessible from the Page-Info dialog).
3091 * @param tab The tab to show certificate for.
3092 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003093 private void showSSLCertificate(final Tab tab) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003094 final View certificateView =
3095 inflateCertificateView(tab.getWebView().getCertificate());
3096 if (certificateView == null) {
3097 return;
3098 }
3099
3100 LayoutInflater factory = LayoutInflater.from(this);
3101
3102 final LinearLayout placeholder =
3103 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3104
3105 LinearLayout ll = (LinearLayout) factory.inflate(
3106 R.layout.ssl_success, placeholder);
3107 ((TextView)ll.findViewById(R.id.success))
3108 .setText(R.string.ssl_certificate_is_valid);
3109
3110 mSSLCertificateView = tab;
3111 mSSLCertificateDialog =
3112 new AlertDialog.Builder(this)
3113 .setTitle(R.string.ssl_certificate).setIcon(
3114 R.drawable.ic_dialog_browser_certificate_secure)
3115 .setView(certificateView)
3116 .setPositiveButton(R.string.ok,
3117 new DialogInterface.OnClickListener() {
3118 public void onClick(DialogInterface dialog,
3119 int whichButton) {
3120 mSSLCertificateDialog = null;
3121 mSSLCertificateView = null;
3122
3123 showPageInfo(tab, false);
3124 }
3125 })
3126 .setOnCancelListener(
3127 new DialogInterface.OnCancelListener() {
3128 public void onCancel(DialogInterface dialog) {
3129 mSSLCertificateDialog = null;
3130 mSSLCertificateView = null;
3131
3132 showPageInfo(tab, false);
3133 }
3134 })
3135 .show();
3136 }
3137
3138 /**
3139 * Displays the SSL error certificate dialog.
3140 * @param view The target web-view.
3141 * @param handler The SSL error handler responsible for cancelling the
3142 * connection that resulted in an SSL error or proceeding per user request.
3143 * @param error The SSL error object.
3144 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003145 void showSSLCertificateOnError(
The Android Open Source Project0c908882009-03-03 19:32:16 -08003146 final WebView view, final SslErrorHandler handler, final SslError error) {
3147
3148 final View certificateView =
3149 inflateCertificateView(error.getCertificate());
3150 if (certificateView == null) {
3151 return;
3152 }
3153
3154 LayoutInflater factory = LayoutInflater.from(this);
3155
3156 final LinearLayout placeholder =
3157 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3158
3159 if (error.hasError(SslError.SSL_UNTRUSTED)) {
3160 LinearLayout ll = (LinearLayout)factory
3161 .inflate(R.layout.ssl_warning, placeholder);
3162 ((TextView)ll.findViewById(R.id.warning))
3163 .setText(R.string.ssl_untrusted);
3164 }
3165
3166 if (error.hasError(SslError.SSL_IDMISMATCH)) {
3167 LinearLayout ll = (LinearLayout)factory
3168 .inflate(R.layout.ssl_warning, placeholder);
3169 ((TextView)ll.findViewById(R.id.warning))
3170 .setText(R.string.ssl_mismatch);
3171 }
3172
3173 if (error.hasError(SslError.SSL_EXPIRED)) {
3174 LinearLayout ll = (LinearLayout)factory
3175 .inflate(R.layout.ssl_warning, placeholder);
3176 ((TextView)ll.findViewById(R.id.warning))
3177 .setText(R.string.ssl_expired);
3178 }
3179
3180 if (error.hasError(SslError.SSL_NOTYETVALID)) {
3181 LinearLayout ll = (LinearLayout)factory
3182 .inflate(R.layout.ssl_warning, placeholder);
3183 ((TextView)ll.findViewById(R.id.warning))
3184 .setText(R.string.ssl_not_yet_valid);
3185 }
3186
3187 mSSLCertificateOnErrorHandler = handler;
3188 mSSLCertificateOnErrorView = view;
3189 mSSLCertificateOnErrorError = error;
3190 mSSLCertificateOnErrorDialog =
3191 new AlertDialog.Builder(this)
3192 .setTitle(R.string.ssl_certificate).setIcon(
3193 R.drawable.ic_dialog_browser_certificate_partially_secure)
3194 .setView(certificateView)
3195 .setPositiveButton(R.string.ok,
3196 new DialogInterface.OnClickListener() {
3197 public void onClick(DialogInterface dialog,
3198 int whichButton) {
3199 mSSLCertificateOnErrorDialog = null;
3200 mSSLCertificateOnErrorView = null;
3201 mSSLCertificateOnErrorHandler = null;
3202 mSSLCertificateOnErrorError = null;
3203
Grace Kloba22ac16e2009-10-07 18:00:23 -07003204 view.getWebViewClient().onReceivedSslError(
3205 view, handler, error);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003206 }
3207 })
3208 .setNeutralButton(R.string.page_info_view,
3209 new DialogInterface.OnClickListener() {
3210 public void onClick(DialogInterface dialog,
3211 int whichButton) {
3212 mSSLCertificateOnErrorDialog = null;
3213
3214 // do not clear the dialog state: we will
3215 // need to show the dialog again once the
3216 // user is done exploring the page-info details
3217
3218 showPageInfo(mTabControl.getTabFromView(view),
3219 true);
3220 }
3221 })
3222 .setOnCancelListener(
3223 new DialogInterface.OnCancelListener() {
3224 public void onCancel(DialogInterface dialog) {
3225 mSSLCertificateOnErrorDialog = null;
3226 mSSLCertificateOnErrorView = null;
3227 mSSLCertificateOnErrorHandler = null;
3228 mSSLCertificateOnErrorError = null;
3229
Grace Kloba22ac16e2009-10-07 18:00:23 -07003230 view.getWebViewClient().onReceivedSslError(
3231 view, handler, error);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003232 }
3233 })
3234 .show();
3235 }
3236
3237 /**
3238 * Inflates the SSL certificate view (helper method).
3239 * @param certificate The SSL certificate.
3240 * @return The resultant certificate view with issued-to, issued-by,
3241 * issued-on, expires-on, and possibly other fields set.
3242 * If the input certificate is null, returns null.
3243 */
3244 private View inflateCertificateView(SslCertificate certificate) {
3245 if (certificate == null) {
3246 return null;
3247 }
3248
3249 LayoutInflater factory = LayoutInflater.from(this);
3250
3251 View certificateView = factory.inflate(
3252 R.layout.ssl_certificate, null);
3253
3254 // issued to:
3255 SslCertificate.DName issuedTo = certificate.getIssuedTo();
3256 if (issuedTo != null) {
3257 ((TextView) certificateView.findViewById(R.id.to_common))
3258 .setText(issuedTo.getCName());
3259 ((TextView) certificateView.findViewById(R.id.to_org))
3260 .setText(issuedTo.getOName());
3261 ((TextView) certificateView.findViewById(R.id.to_org_unit))
3262 .setText(issuedTo.getUName());
3263 }
3264
3265 // issued by:
3266 SslCertificate.DName issuedBy = certificate.getIssuedBy();
3267 if (issuedBy != null) {
3268 ((TextView) certificateView.findViewById(R.id.by_common))
3269 .setText(issuedBy.getCName());
3270 ((TextView) certificateView.findViewById(R.id.by_org))
3271 .setText(issuedBy.getOName());
3272 ((TextView) certificateView.findViewById(R.id.by_org_unit))
3273 .setText(issuedBy.getUName());
3274 }
3275
3276 // issued on:
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003277 String issuedOn = formatCertificateDate(
3278 certificate.getValidNotBeforeDate());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003279 ((TextView) certificateView.findViewById(R.id.issued_on))
3280 .setText(issuedOn);
3281
3282 // expires on:
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003283 String expiresOn = formatCertificateDate(
3284 certificate.getValidNotAfterDate());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003285 ((TextView) certificateView.findViewById(R.id.expires_on))
3286 .setText(expiresOn);
3287
3288 return certificateView;
3289 }
3290
3291 /**
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003292 * Formats the certificate date to a properly localized date string.
The Android Open Source Project0c908882009-03-03 19:32:16 -08003293 * @return Properly localized version of the certificate date string and
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003294 * the "" if it fails to localize.
The Android Open Source Project0c908882009-03-03 19:32:16 -08003295 */
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003296 private String formatCertificateDate(Date certificateDate) {
3297 if (certificateDate == null) {
3298 return "";
The Android Open Source Project0c908882009-03-03 19:32:16 -08003299 }
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003300 String formattedDate = DateFormat.getDateFormat(this).format(certificateDate);
3301 if (formattedDate == null) {
3302 return "";
3303 }
3304 return formattedDate;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003305 }
3306
3307 /**
3308 * Displays an http-authentication dialog.
3309 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003310 void showHttpAuthentication(final HttpAuthHandler handler,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003311 final String host, final String realm, final String title,
3312 final String name, final String password, int focusId) {
3313 LayoutInflater factory = LayoutInflater.from(this);
3314 final View v = factory
3315 .inflate(R.layout.http_authentication, null);
3316 if (name != null) {
3317 ((EditText) v.findViewById(R.id.username_edit)).setText(name);
3318 }
3319 if (password != null) {
3320 ((EditText) v.findViewById(R.id.password_edit)).setText(password);
3321 }
3322
3323 String titleText = title;
3324 if (titleText == null) {
3325 titleText = getText(R.string.sign_in_to).toString().replace(
3326 "%s1", host).replace("%s2", realm);
3327 }
3328
3329 mHttpAuthHandler = handler;
3330 AlertDialog dialog = new AlertDialog.Builder(this)
3331 .setTitle(titleText)
3332 .setIcon(android.R.drawable.ic_dialog_alert)
3333 .setView(v)
3334 .setPositiveButton(R.string.action,
3335 new DialogInterface.OnClickListener() {
3336 public void onClick(DialogInterface dialog,
3337 int whichButton) {
3338 String nm = ((EditText) v
3339 .findViewById(R.id.username_edit))
3340 .getText().toString();
3341 String pw = ((EditText) v
3342 .findViewById(R.id.password_edit))
3343 .getText().toString();
3344 BrowserActivity.this.setHttpAuthUsernamePassword
3345 (host, realm, nm, pw);
3346 handler.proceed(nm, pw);
3347 mHttpAuthenticationDialog = null;
3348 mHttpAuthHandler = null;
3349 }})
3350 .setNegativeButton(R.string.cancel,
3351 new DialogInterface.OnClickListener() {
3352 public void onClick(DialogInterface dialog,
3353 int whichButton) {
3354 handler.cancel();
3355 BrowserActivity.this.resetTitleAndRevertLockIcon();
3356 mHttpAuthenticationDialog = null;
3357 mHttpAuthHandler = null;
3358 }})
3359 .setOnCancelListener(new DialogInterface.OnCancelListener() {
3360 public void onCancel(DialogInterface dialog) {
3361 handler.cancel();
3362 BrowserActivity.this.resetTitleAndRevertLockIcon();
3363 mHttpAuthenticationDialog = null;
3364 mHttpAuthHandler = null;
3365 }})
3366 .create();
3367 // Make the IME appear when the dialog is displayed if applicable.
3368 dialog.getWindow().setSoftInputMode(
3369 WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
3370 dialog.show();
3371 if (focusId != 0) {
3372 dialog.findViewById(focusId).requestFocus();
3373 } else {
3374 v.findViewById(R.id.username_edit).requestFocus();
3375 }
3376 mHttpAuthenticationDialog = dialog;
3377 }
3378
3379 public int getProgress() {
3380 WebView w = mTabControl.getCurrentWebView();
3381 if (w != null) {
3382 return w.getProgress();
3383 } else {
3384 return 100;
3385 }
3386 }
3387
3388 /**
3389 * Set HTTP authentication password.
3390 *
3391 * @param host The host for the password
3392 * @param realm The realm for the password
3393 * @param username The username for the password. If it is null, it means
3394 * password can't be saved.
3395 * @param password The password
3396 */
3397 public void setHttpAuthUsernamePassword(String host, String realm,
3398 String username,
3399 String password) {
Steve Block95a53b22010-03-25 17:24:58 +00003400 WebView w = getTopWindow();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003401 if (w != null) {
3402 w.setHttpAuthUsernamePassword(host, realm, username, password);
3403 }
3404 }
3405
3406 /**
3407 * connectivity manager says net has come or gone... inform the user
3408 * @param up true if net has come up, false if net has gone down
3409 */
3410 public void onNetworkToggle(boolean up) {
3411 if (up == mIsNetworkUp) {
3412 return;
3413 } else if (up) {
3414 mIsNetworkUp = true;
3415 if (mAlertDialog != null) {
3416 mAlertDialog.cancel();
3417 mAlertDialog = null;
3418 }
3419 } else {
3420 mIsNetworkUp = false;
Patrick Scotteb6ab2a2009-09-16 10:00:17 -04003421 if (mInLoad) {
3422 createAndShowNetworkDialog();
3423 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003424 }
3425 WebView w = mTabControl.getCurrentWebView();
3426 if (w != null) {
3427 w.setNetworkAvailable(up);
3428 }
3429 }
3430
Grace Kloba22ac16e2009-10-07 18:00:23 -07003431 boolean isNetworkUp() {
3432 return mIsNetworkUp;
3433 }
3434
Patrick Scotteb6ab2a2009-09-16 10:00:17 -04003435 // This method shows the network dialog alerting the user that the net is
3436 // down. It will only show the dialog if mAlertDialog is null.
3437 private void createAndShowNetworkDialog() {
3438 if (mAlertDialog == null) {
3439 mAlertDialog = new AlertDialog.Builder(this)
3440 .setTitle(R.string.loadSuspendedTitle)
3441 .setMessage(R.string.loadSuspended)
3442 .setPositiveButton(R.string.ok, null)
3443 .show();
3444 }
3445 }
3446
The Android Open Source Project0c908882009-03-03 19:32:16 -08003447 @Override
3448 protected void onActivityResult(int requestCode, int resultCode,
3449 Intent intent) {
Grace Klobabb394f32009-11-19 10:26:37 -08003450 if (getTopWindow() == null) return;
3451
The Android Open Source Project0c908882009-03-03 19:32:16 -08003452 switch (requestCode) {
3453 case COMBO_PAGE:
3454 if (resultCode == RESULT_OK && intent != null) {
3455 String data = intent.getAction();
3456 Bundle extras = intent.getExtras();
3457 if (extras != null && extras.getBoolean("new_window", false)) {
Leon Scroggins25d35472009-09-15 11:37:27 -04003458 openTab(data);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003459 } else {
Grace Kloba22ac16e2009-10-07 18:00:23 -07003460 final Tab currentTab =
The Android Open Source Project0c908882009-03-03 19:32:16 -08003461 mTabControl.getCurrentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04003462 dismissSubWindow(currentTab);
3463 if (data != null && data.length() != 0) {
Leon Scroggins92472e82010-02-17 16:32:28 -05003464 loadUrl(getTopWindow(), data);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003465 }
3466 }
3467 }
Leon Scrogginsfde97462010-01-11 13:06:21 -05003468 // Deliberately fall through to PREFERENCES_PAGE, since the
3469 // same extra may be attached to the COMBO_PAGE
3470 case PREFERENCES_PAGE:
3471 if (resultCode == RESULT_OK && intent != null) {
3472 String action = intent.getStringExtra(Intent.EXTRA_TEXT);
3473 if (BrowserSettings.PREF_CLEAR_HISTORY.equals(action)) {
3474 mTabControl.removeParentChildRelationShips();
3475 }
3476 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003477 break;
Leon Scroggins8d5fa432009-10-02 15:55:59 -04003478 // Choose a file from the file picker.
3479 case FILE_SELECTED:
3480 if (null == mUploadMessage) break;
3481 Uri result = intent == null || resultCode != RESULT_OK ? null
3482 : intent.getData();
3483 mUploadMessage.onReceiveValue(result);
3484 mUploadMessage = null;
3485 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003486 default:
3487 break;
3488 }
Leon Scroggins30444232009-09-04 18:36:20 -04003489 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003490 }
3491
3492 /*
3493 * This method is called as a result of the user selecting the options
Leon Scrogginsf08809b2010-01-21 09:27:46 -05003494 * menu to see the download window. It shows the download window on top of
3495 * the current window.
The Android Open Source Project0c908882009-03-03 19:32:16 -08003496 */
Leon Scrogginsf08809b2010-01-21 09:27:46 -05003497 private void viewDownloads(Uri downloadRecord) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003498 Intent intent = new Intent(this,
3499 BrowserDownloadPage.class);
3500 intent.setData(downloadRecord);
Grace Kloba22ac16e2009-10-07 18:00:23 -07003501 startActivityForResult(intent, BrowserActivity.DOWNLOAD_PAGE);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003502
3503 }
3504
Leon Scroggins160a7e72009-08-14 18:28:01 -04003505 /**
3506 * Open the Go page.
3507 * @param startWithHistory If true, open starting on the history tab.
3508 * Otherwise, start with the bookmarks tab.
Leon Scroggins160a7e72009-08-14 18:28:01 -04003509 */
Leon Scroggins30444232009-09-04 18:36:20 -04003510 /* package */ void bookmarksOrHistoryPicker(boolean startWithHistory) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003511 WebView current = mTabControl.getCurrentWebView();
3512 if (current == null) {
3513 return;
3514 }
3515 Intent intent = new Intent(this,
3516 CombinedBookmarkHistoryActivity.class);
3517 String title = current.getTitle();
3518 String url = current.getUrl();
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01003519 Bitmap thumbnail = createScreenshot(current);
3520
The Android Open Source Project0c908882009-03-03 19:32:16 -08003521 // Just in case the user opens bookmarks before a page finishes loading
3522 // so the current history item, and therefore the page, is null.
3523 if (null == url) {
3524 url = mLastEnteredUrl;
3525 // This can happen.
3526 if (null == url) {
3527 url = mSettings.getHomePage();
3528 }
3529 }
3530 // In case the web page has not yet received its associated title.
3531 if (title == null) {
3532 title = url;
3533 }
3534 intent.putExtra("title", title);
3535 intent.putExtra("url", url);
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01003536 intent.putExtra("thumbnail", thumbnail);
Leon Scroggins30444232009-09-04 18:36:20 -04003537 // Disable opening in a new window if we have maxed out the windows
Grace Kloba22ac16e2009-10-07 18:00:23 -07003538 intent.putExtra("disable_new_window", !mTabControl.canCreateNewTab());
Patrick Scott3918d442009-08-04 13:22:29 -04003539 intent.putExtra("touch_icon_url", current.getTouchIconUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003540 if (startWithHistory) {
3541 intent.putExtra(CombinedBookmarkHistoryActivity.STARTING_TAB,
3542 CombinedBookmarkHistoryActivity.HISTORY_TAB);
3543 }
3544 startActivityForResult(intent, COMBO_PAGE);
3545 }
3546
3547 // Called when loading from context menu or LOAD_URL message
Leon Scroggins92472e82010-02-17 16:32:28 -05003548 private void loadUrlFromContext(WebView view, String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003549 // In case the user enters nothing.
3550 if (url != null && url.length() != 0 && view != null) {
3551 url = smartUrlFilter(url);
Grace Kloba22ac16e2009-10-07 18:00:23 -07003552 if (!view.getWebViewClient().shouldOverrideUrlLoading(view, url)) {
Leon Scroggins92472e82010-02-17 16:32:28 -05003553 loadUrl(view, url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003554 }
3555 }
3556 }
3557
Leon Scroggins92472e82010-02-17 16:32:28 -05003558 /**
3559 * Load the URL into the given WebView and update the title bar
3560 * to reflect the new load. Call this instead of WebView.loadUrl
3561 * directly.
3562 * @param view The WebView used to load url.
3563 * @param url The URL to load.
3564 */
3565 private void loadUrl(WebView view, String url) {
3566 updateTitleBarForNewLoad(view, url);
3567 view.loadUrl(url);
3568 }
3569
3570 /**
3571 * Load UrlData into a Tab and update the title bar to reflect the new
3572 * load. Call this instead of UrlData.loadIn directly.
3573 * @param t The Tab used to load.
3574 * @param data The UrlData being loaded.
3575 */
3576 private void loadUrlDataIn(Tab t, UrlData data) {
3577 updateTitleBarForNewLoad(t.getWebView(), data.mUrl);
3578 data.loadIn(t);
3579 }
3580
3581 /**
3582 * If the WebView is the top window, update the title bar to reflect
3583 * loading the new URL. i.e. set its text, clear the favicon (which
3584 * will be set once the page begins loading), and set the progress to
3585 * INITIAL_PROGRESS to show that the page has begun to load. Called
3586 * by loadUrl and loadUrlDataIn.
3587 * @param view The WebView that is starting a load.
3588 * @param url The URL that is being loaded.
3589 */
3590 private void updateTitleBarForNewLoad(WebView view, String url) {
3591 if (view == getTopWindow()) {
3592 setUrlTitle(url, null);
3593 setFavicon(null);
3594 onProgressChanged(view, INITIAL_PROGRESS);
3595 }
3596 }
3597
The Android Open Source Project0c908882009-03-03 19:32:16 -08003598 private String smartUrlFilter(Uri inUri) {
3599 if (inUri != null) {
3600 return smartUrlFilter(inUri.toString());
3601 }
3602 return null;
3603 }
3604
Feng Qianb34f87a2009-03-24 21:27:26 -07003605 protected static final Pattern ACCEPTED_URI_SCHEMA = Pattern.compile(
The Android Open Source Project0c908882009-03-03 19:32:16 -08003606 "(?i)" + // switch on case insensitive matching
3607 "(" + // begin group for schema
3608 "(?:http|https|file):\\/\\/" +
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003609 "|(?:inline|data|about|content|javascript):" +
The Android Open Source Project0c908882009-03-03 19:32:16 -08003610 ")" +
3611 "(.*)" );
3612
3613 /**
3614 * Attempts to determine whether user input is a URL or search
3615 * terms. Anything with a space is passed to search.
3616 *
3617 * Converts to lowercase any mistakenly uppercased schema (i.e.,
3618 * "Http://" converts to "http://"
3619 *
3620 * @return Original or modified URL
3621 *
3622 */
3623 String smartUrlFilter(String url) {
3624
3625 String inUrl = url.trim();
3626 boolean hasSpace = inUrl.indexOf(' ') != -1;
3627
3628 Matcher matcher = ACCEPTED_URI_SCHEMA.matcher(inUrl);
3629 if (matcher.matches()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003630 // force scheme to lowercase
3631 String scheme = matcher.group(1);
3632 String lcScheme = scheme.toLowerCase();
3633 if (!lcScheme.equals(scheme)) {
Mitsuru Oshima123ecfb2009-05-18 19:11:14 -07003634 inUrl = lcScheme + matcher.group(2);
3635 }
3636 if (hasSpace) {
3637 inUrl = inUrl.replace(" ", "%20");
The Android Open Source Project0c908882009-03-03 19:32:16 -08003638 }
3639 return inUrl;
3640 }
3641 if (hasSpace) {
Satish Sampath565505b2009-05-29 15:37:27 +01003642 // FIXME: Is this the correct place to add to searches?
3643 // what if someone else calls this function?
3644 int shortcut = parseUrlShortcut(inUrl);
3645 if (shortcut != SHORTCUT_INVALID) {
3646 Browser.addSearchUrl(mResolver, inUrl);
3647 String query = inUrl.substring(2);
3648 switch (shortcut) {
3649 case SHORTCUT_GOOGLE_SEARCH:
Grace Kloba47fdfdb2009-06-30 11:15:34 -07003650 return URLUtil.composeSearchUrl(query, QuickSearch_G, QUERY_PLACE_HOLDER);
Satish Sampath565505b2009-05-29 15:37:27 +01003651 case SHORTCUT_WIKIPEDIA_SEARCH:
3652 return URLUtil.composeSearchUrl(query, QuickSearch_W, QUERY_PLACE_HOLDER);
3653 case SHORTCUT_DICTIONARY_SEARCH:
3654 return URLUtil.composeSearchUrl(query, QuickSearch_D, QUERY_PLACE_HOLDER);
3655 case SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH:
The Android Open Source Project0c908882009-03-03 19:32:16 -08003656 // FIXME: we need location in this case
Satish Sampath565505b2009-05-29 15:37:27 +01003657 return URLUtil.composeSearchUrl(query, QuickSearch_L, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003658 }
3659 }
3660 } else {
Dan Egnor5ee906c2009-11-18 12:11:49 -08003661 if (Patterns.WEB_URL.matcher(inUrl).matches()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003662 return URLUtil.guessUrl(inUrl);
3663 }
3664 }
3665
3666 Browser.addSearchUrl(mResolver, inUrl);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07003667 return URLUtil.composeSearchUrl(inUrl, QuickSearch_G, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003668 }
3669
Ben Murdochbff2d602009-07-01 20:19:05 +01003670 /* package */ void setShouldShowErrorConsole(boolean flag) {
3671 if (flag == mShouldShowErrorConsole) {
3672 // Nothing to do.
3673 return;
3674 }
3675
3676 mShouldShowErrorConsole = flag;
3677
Grace Kloba22ac16e2009-10-07 18:00:23 -07003678 ErrorConsoleView errorConsole = mTabControl.getCurrentTab()
3679 .getErrorConsole(true);
Ben Murdochbff2d602009-07-01 20:19:05 +01003680
3681 if (flag) {
3682 // Setting the show state of the console will cause it's the layout to be inflated.
3683 if (errorConsole.numberOfErrors() > 0) {
3684 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
3685 } else {
3686 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
3687 }
3688
3689 // Now we can add it to the main view.
3690 mErrorConsoleContainer.addView(errorConsole,
Romain Guy15b8ec62010-01-08 15:06:43 -08003691 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
Ben Murdochbff2d602009-07-01 20:19:05 +01003692 ViewGroup.LayoutParams.WRAP_CONTENT));
3693 } else {
3694 mErrorConsoleContainer.removeView(errorConsole);
3695 }
3696
3697 }
3698
Grace Kloba22ac16e2009-10-07 18:00:23 -07003699 boolean shouldShowErrorConsole() {
3700 return mShouldShowErrorConsole;
3701 }
3702
Andrei Popescu163ab742009-10-20 17:58:23 +01003703 private void setStatusBarVisibility(boolean visible) {
3704 int flag = visible ? 0 : WindowManager.LayoutParams.FLAG_FULLSCREEN;
3705 getWindow().setFlags(flag, WindowManager.LayoutParams.FLAG_FULLSCREEN);
3706 }
3707
Andrei Popescu56199cc2010-01-12 22:39:16 +00003708
3709 private void sendNetworkType(String type, String subtype) {
3710 WebView w = mTabControl.getCurrentWebView();
3711 if (w != null) {
3712 w.setNetworkType(type, subtype);
3713 }
3714 }
3715
Andrei Popescu30995e72010-02-09 16:59:58 +00003716 private void packageChanged(String packageName, boolean wasAdded) {
3717 WebView w = mTabControl.getCurrentWebView();
3718 if (w == null) {
3719 return;
3720 }
3721
3722 if (wasAdded) {
3723 w.addPackageName(packageName);
3724 } else {
3725 w.removePackageName(packageName);
3726 }
3727 }
3728
3729 private void addPackageNames(Set<String> packageNames) {
3730 WebView w = mTabControl.getCurrentWebView();
3731 if (w == null) {
3732 return;
3733 }
3734
3735 w.addPackageNames(packageNames);
3736 }
3737
3738 private void getInstalledPackages() {
3739 AsyncTask<Void, Void, Set<String> > task =
3740 new AsyncTask<Void, Void, Set<String> >() {
3741 protected Set<String> doInBackground(Void... unused) {
3742 Set<String> installedPackages = new HashSet<String>();
3743 PackageManager pm = BrowserActivity.this.getPackageManager();
3744 if (pm != null) {
3745 List<PackageInfo> packages = pm.getInstalledPackages(0);
3746 for (PackageInfo p : packages) {
3747 if (BrowserActivity.this.sGoogleApps.contains(p.packageName)) {
3748 installedPackages.add(p.packageName);
3749 }
3750 }
3751 }
3752
3753 return installedPackages;
3754 }
3755
3756 // Executes on the UI thread
3757 protected void onPostExecute(Set<String> installedPackages) {
3758 addPackageNames(installedPackages);
3759 }
3760 };
3761 task.execute();
3762 }
3763
Grace Klobaeb6eef42009-09-15 17:56:32 -07003764 final static int LOCK_ICON_UNSECURE = 0;
3765 final static int LOCK_ICON_SECURE = 1;
3766 final static int LOCK_ICON_MIXED = 2;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003767
The Android Open Source Project0c908882009-03-03 19:32:16 -08003768 private BrowserSettings mSettings;
3769 private TabControl mTabControl;
3770 private ContentResolver mResolver;
3771 private FrameLayout mContentView;
Andrei Popescuadc008d2009-06-26 14:11:30 +01003772 private View mCustomView;
3773 private FrameLayout mCustomViewContainer;
Andrei Popescuc9b55562009-07-07 10:51:15 +01003774 private WebChromeClient.CustomViewCallback mCustomViewCallback;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003775
3776 // FIXME, temp address onPrepareMenu performance problem. When we move everything out of
3777 // view, we should rewrite this.
3778 private int mCurrentMenuState = 0;
3779 private int mMenuState = R.id.MAIN_MENU;
Andrei Popescuadc008d2009-06-26 14:11:30 +01003780 private int mOldMenuState = EMPTY_MENU;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003781 private static final int EMPTY_MENU = -1;
3782 private Menu mMenu;
3783
3784 private FindDialog mFindDialog;
3785 // Used to prevent chording to result in firing two shortcuts immediately
3786 // one after another. Fixes bug 1211714.
3787 boolean mCanChord;
3788
3789 private boolean mInLoad;
3790 private boolean mIsNetworkUp;
Ben Murdochb7cc8b42009-09-28 10:59:09 +01003791 private boolean mDidStopLoad;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003792
Cary Clark1f10cbf2010-03-22 11:45:23 -04003793 /* package */ boolean mActivityInPause = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003794
3795 private boolean mMenuIsDown;
3796
The Android Open Source Project0c908882009-03-03 19:32:16 -08003797 private static boolean mInTrace;
3798
3799 // Performance probe
3800 private static final int[] SYSTEM_CPU_FORMAT = new int[] {
3801 Process.PROC_SPACE_TERM | Process.PROC_COMBINE,
3802 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 1: user time
3803 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 2: nice time
3804 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 3: sys time
3805 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 4: idle time
3806 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 5: iowait time
3807 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 6: irq time
3808 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG // 7: softirq time
3809 };
3810
3811 private long mStart;
3812 private long mProcessStart;
3813 private long mUserStart;
3814 private long mSystemStart;
3815 private long mIdleStart;
3816 private long mIrqStart;
3817
3818 private long mUiStart;
3819
3820 private Drawable mMixLockIcon;
3821 private Drawable mSecLockIcon;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003822
3823 /* hold a ref so we can auto-cancel if necessary */
3824 private AlertDialog mAlertDialog;
3825
The Android Open Source Project0c908882009-03-03 19:32:16 -08003826 // The up-to-date URL and title (these can be different from those stored
3827 // in WebView, since it takes some time for the information in WebView to
3828 // get updated)
3829 private String mUrl;
3830 private String mTitle;
3831
3832 // As PageInfo has different style for landscape / portrait, we have
3833 // to re-open it when configuration changed
3834 private AlertDialog mPageInfoDialog;
Grace Kloba22ac16e2009-10-07 18:00:23 -07003835 private Tab mPageInfoView;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003836 // If the Page-Info dialog is launched from the SSL-certificate-on-error
3837 // dialog, we should not just dismiss it, but should get back to the
3838 // SSL-certificate-on-error dialog. This flag is used to store this state
Leon Scrogginsc7b92f82010-01-11 18:17:31 -05003839 private boolean mPageInfoFromShowSSLCertificateOnError;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003840
3841 // as SSLCertificateOnError has different style for landscape / portrait,
3842 // we have to re-open it when configuration changed
3843 private AlertDialog mSSLCertificateOnErrorDialog;
3844 private WebView mSSLCertificateOnErrorView;
3845 private SslErrorHandler mSSLCertificateOnErrorHandler;
3846 private SslError mSSLCertificateOnErrorError;
3847
3848 // as SSLCertificate has different style for landscape / portrait, we
3849 // have to re-open it when configuration changed
3850 private AlertDialog mSSLCertificateDialog;
Grace Kloba22ac16e2009-10-07 18:00:23 -07003851 private Tab mSSLCertificateView;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003852
3853 // as HttpAuthentication has different style for landscape / portrait, we
3854 // have to re-open it when configuration changed
3855 private AlertDialog mHttpAuthenticationDialog;
3856 private HttpAuthHandler mHttpAuthHandler;
3857
3858 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_PARAMS =
3859 new FrameLayout.LayoutParams(
Romain Guy15b8ec62010-01-08 15:06:43 -08003860 ViewGroup.LayoutParams.MATCH_PARENT,
3861 ViewGroup.LayoutParams.MATCH_PARENT);
Andrei Popescuadc008d2009-06-26 14:11:30 +01003862 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_GRAVITY_CENTER =
3863 new FrameLayout.LayoutParams(
Romain Guy15b8ec62010-01-08 15:06:43 -08003864 ViewGroup.LayoutParams.MATCH_PARENT,
3865 ViewGroup.LayoutParams.MATCH_PARENT,
Andrei Popescuadc008d2009-06-26 14:11:30 +01003866 Gravity.CENTER);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07003867 // Google search
3868 final static String QuickSearch_G = "http://www.google.com/m?q=%s";
The Android Open Source Project0c908882009-03-03 19:32:16 -08003869 // Wikipedia search
3870 final static String QuickSearch_W = "http://en.wikipedia.org/w/index.php?search=%s&go=Go";
3871 // Dictionary search
3872 final static String QuickSearch_D = "http://dictionary.reference.com/search?q=%s";
3873 // Google Mobile Local search
3874 final static String QuickSearch_L = "http://www.google.com/m/search?site=local&q=%s&near=mountain+view";
3875
3876 final static String QUERY_PLACE_HOLDER = "%s";
3877
3878 // "source" parameter for Google search through search key
3879 final static String GOOGLE_SEARCH_SOURCE_SEARCHKEY = "browser-key";
3880 // "source" parameter for Google search through goto menu
3881 final static String GOOGLE_SEARCH_SOURCE_GOTO = "browser-goto";
3882 // "source" parameter for Google search through simplily type
3883 final static String GOOGLE_SEARCH_SOURCE_TYPE = "browser-type";
3884 // "source" parameter for Google search suggested by the browser
3885 final static String GOOGLE_SEARCH_SOURCE_SUGGEST = "browser-suggest";
3886 // "source" parameter for Google search from unknown source
3887 final static String GOOGLE_SEARCH_SOURCE_UNKNOWN = "unknown";
3888
3889 private final static String LOGTAG = "browser";
3890
The Android Open Source Project0c908882009-03-03 19:32:16 -08003891 private String mLastEnteredUrl;
3892
3893 private PowerManager.WakeLock mWakeLock;
3894 private final static int WAKELOCK_TIMEOUT = 5 * 60 * 1000; // 5 minutes
3895
3896 private Toast mStopToast;
3897
Leon Scroggins68579392009-09-15 15:31:54 -04003898 private TitleBar mTitleBar;
Leon Scroggins81db3662009-06-04 17:45:11 -04003899
Ben Murdochbff2d602009-07-01 20:19:05 +01003900 private LinearLayout mErrorConsoleContainer = null;
3901 private boolean mShouldShowErrorConsole = false;
3902
The Android Open Source Project0c908882009-03-03 19:32:16 -08003903 // As the ids are dynamically created, we can't guarantee that they will
3904 // be in sequence, so this static array maps ids to a window number.
3905 final static private int[] WINDOW_SHORTCUT_ID_ARRAY =
3906 { R.id.window_one_menu_id, R.id.window_two_menu_id, R.id.window_three_menu_id,
3907 R.id.window_four_menu_id, R.id.window_five_menu_id, R.id.window_six_menu_id,
3908 R.id.window_seven_menu_id, R.id.window_eight_menu_id };
3909
3910 // monitor platform changes
3911 private IntentFilter mNetworkStateChangedFilter;
3912 private BroadcastReceiver mNetworkStateIntentReceiver;
3913
Grace Klobab4da0ad2009-05-14 14:45:40 -07003914 private BroadcastReceiver mPackageInstallationReceiver;
3915
Bjorn Bringerta7611812010-03-24 11:12:02 +00003916 private SystemAllowGeolocationOrigins mSystemAllowGeolocationOrigins;
3917
The Android Open Source Project0c908882009-03-03 19:32:16 -08003918 // activity requestCode
Nicolas Roard78a98e42009-05-11 13:34:17 +01003919 final static int COMBO_PAGE = 1;
3920 final static int DOWNLOAD_PAGE = 2;
3921 final static int PREFERENCES_PAGE = 3;
Leon Scroggins8d5fa432009-10-02 15:55:59 -04003922 final static int FILE_SELECTED = 4;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003923
Andrei Popescu540035d2009-09-18 18:59:20 +01003924 // the default <video> poster
3925 private Bitmap mDefaultVideoPoster;
3926 // the video progress view
3927 private View mVideoProgressView;
3928
Andrei Popescu30995e72010-02-09 16:59:58 +00003929 // The Google packages we monitor for the navigator.isApplicationInstalled()
3930 // API. Add as needed.
3931 private static Set<String> sGoogleApps;
3932 static {
3933 sGoogleApps = new HashSet<String>();
3934 sGoogleApps.add("com.google.android.youtube");
3935 }
3936
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003937 /**
3938 * A UrlData class to abstract how the content will be set to WebView.
3939 * This base class uses loadUrl to show the content.
3940 */
Leon Scroggins6eac63e2010-03-15 18:19:14 -04003941 /* package */ static class UrlData {
Grace Kloba068e48b2010-01-26 18:11:27 -08003942 final String mUrl;
3943 final Map<String, String> mHeaders;
Leon Scroggins58d56c62010-01-28 15:12:40 -05003944 final Intent mVoiceIntent;
Grace Kloba60e095c2009-06-16 11:50:55 -07003945
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003946 UrlData(String url) {
3947 this.mUrl = url;
Grace Kloba068e48b2010-01-26 18:11:27 -08003948 this.mHeaders = null;
Leon Scroggins58d56c62010-01-28 15:12:40 -05003949 this.mVoiceIntent = null;
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003950 }
Grace Kloba60e095c2009-06-16 11:50:55 -07003951
Leon Scroggins58d56c62010-01-28 15:12:40 -05003952 UrlData(String url, Map<String, String> headers, Intent intent) {
Grace Kloba068e48b2010-01-26 18:11:27 -08003953 this.mUrl = url;
3954 this.mHeaders = headers;
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -05003955 if (RecognizerResultsIntent.ACTION_VOICE_SEARCH_RESULTS
3956 .equals(intent.getAction())) {
Leon Scroggins58d56c62010-01-28 15:12:40 -05003957 this.mVoiceIntent = intent;
3958 } else {
3959 this.mVoiceIntent = null;
3960 }
Grace Kloba60e095c2009-06-16 11:50:55 -07003961 }
3962
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003963 boolean isEmpty() {
Leon Scroggins58d56c62010-01-28 15:12:40 -05003964 return mVoiceIntent == null && (mUrl == null || mUrl.length() == 0);
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003965 }
3966
Leon Scroggins92472e82010-02-17 16:32:28 -05003967 /**
3968 * Load this UrlData into the given Tab. Use loadUrlDataIn to update
3969 * the title bar as well.
3970 */
Leon Scroggins58d56c62010-01-28 15:12:40 -05003971 public void loadIn(Tab t) {
3972 if (mVoiceIntent != null) {
3973 t.activateVoiceSearchMode(mVoiceIntent);
3974 } else {
3975 t.getWebView().loadUrl(mUrl, mHeaders);
3976 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003977 }
3978 };
3979
Leon Scroggins1f005d32009-08-10 17:36:42 -04003980 /* package */ static final UrlData EMPTY_URL_DATA = new UrlData(null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003981}