blob: e6982c9329aba0031b5e87400f7e33173d88a169 [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
Leon Scrogginsd746a942010-05-19 13:21:44 -0400175 private boolean mXLargeScreenSize;
176
Grace Kloba22ac16e2009-10-07 18:00:23 -0700177 @Override
178 public void onCreate(Bundle icicle) {
Dave Bort31a6d1c2009-04-13 15:56:49 -0700179 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800180 Log.v(LOGTAG, this + " onStart");
181 }
182 super.onCreate(icicle);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800183 // test the browser in OpenGL
184 // requestWindowFeature(Window.FEATURE_OPENGL);
185
Mike Reedd334bf52010-01-26 15:21:44 -0500186 // enable this to test the browser in 32bit
187 if (false) {
188 getWindow().setFormat(PixelFormat.RGBX_8888);
189 BitmapFactory.setDefaultConfig(Bitmap.Config.ARGB_8888);
190 }
191
Svetoslav Ganov2b345992010-05-06 06:13:54 -0700192 if (AccessibilityManager.getInstance(this).isEnabled()) {
193 setDefaultKeyMode(DEFAULT_KEYS_DISABLE);
194 } else {
195 setDefaultKeyMode(DEFAULT_KEYS_SEARCH_LOCAL);
196 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800197
198 mResolver = getContentResolver();
199
Grace Kloba0923d692009-09-23 21:37:25 -0700200 // If this was a web search request, pass it on to the default web
201 // search provider and finish this activity.
202 if (handleWebSearchIntent(getIntent())) {
203 finish();
204 return;
205 }
206
The Android Open Source Project0c908882009-03-03 19:32:16 -0800207 mSecLockIcon = Resources.getSystem().getDrawable(
208 android.R.drawable.ic_secure);
209 mMixLockIcon = Resources.getSystem().getDrawable(
210 android.R.drawable.ic_partial_secure);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800211
Leon Scroggins81db3662009-06-04 17:45:11 -0400212 FrameLayout frameLayout = (FrameLayout) getWindow().getDecorView()
213 .findViewById(com.android.internal.R.id.content);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400214 mBrowserFrameLayout = (FrameLayout) LayoutInflater.from(this)
215 .inflate(R.layout.custom_screen, null);
216 mContentView = (FrameLayout) mBrowserFrameLayout.findViewById(
217 R.id.main_content);
218 mErrorConsoleContainer = (LinearLayout) mBrowserFrameLayout
219 .findViewById(R.id.error_console);
220 mCustomViewContainer = (FrameLayout) mBrowserFrameLayout
221 .findViewById(R.id.fullscreen_custom_content);
222 frameLayout.addView(mBrowserFrameLayout, COVER_SCREEN_PARAMS);
Leon Scrogginsd746a942010-05-19 13:21:44 -0400223 mXLargeScreenSize = (getResources().getConfiguration().screenLayout
224 & Configuration.SCREENLAYOUT_SIZE_MASK)
225 == Configuration.SCREENLAYOUT_SIZE_XLARGE;
226 if (mXLargeScreenSize) {
Leon Scroggins571b3762010-05-26 10:25:01 -0400227 mTitleBar = new TitleBarXLarge(this);
Leon Scrogginsd746a942010-05-19 13:21:44 -0400228 LinearLayout layout = (LinearLayout) mBrowserFrameLayout.
229 findViewById(R.id.vertical_layout);
230 layout.addView(mTitleBar, 0, new LinearLayout.LayoutParams(
231 ViewGroup.LayoutParams.MATCH_PARENT,
232 ViewGroup.LayoutParams.WRAP_CONTENT));
233 } else {
Leon Scroggins571b3762010-05-26 10:25:01 -0400234 mTitleBar = new TitleBar(this);
Leon Scrogginsd746a942010-05-19 13:21:44 -0400235 // mTitleBar will be always be shown in the fully loaded mode on
236 // phone
237 mTitleBar.setProgress(100);
238 // Fake title bar is not needed in xlarge layout
239 mFakeTitleBar = new TitleBar(this);
240 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800241
242 // Create the tab control and our initial tab
243 mTabControl = new TabControl(this);
244
245 // Open the icon database and retain all the bookmark urls for favicons
246 retainIconsOnStartup();
247
248 // Keep a settings instance handy.
249 mSettings = BrowserSettings.getInstance();
250 mSettings.setTabControl(mTabControl);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800251
252 PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
253 mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Browser");
254
Patrick Scott6adacc92010-03-05 08:24:51 -0500255 // Find out if the network is currently up.
256 ConnectivityManager cm = (ConnectivityManager) getSystemService(
257 Context.CONNECTIVITY_SERVICE);
258 NetworkInfo info = cm.getActiveNetworkInfo();
259 if (info != null) {
260 mIsNetworkUp = info.isAvailable();
261 }
262
Grace Klobaa34f6862009-07-31 16:28:17 -0700263 /* enables registration for changes in network status from
264 http stack */
265 mNetworkStateChangedFilter = new IntentFilter();
266 mNetworkStateChangedFilter.addAction(
267 ConnectivityManager.CONNECTIVITY_ACTION);
268 mNetworkStateIntentReceiver = new BroadcastReceiver() {
269 @Override
270 public void onReceive(Context context, Intent intent) {
271 if (intent.getAction().equals(
272 ConnectivityManager.CONNECTIVITY_ACTION)) {
Andrei Popescue4c98462010-02-19 15:44:13 +0000273
274 NetworkInfo info = intent.getParcelableExtra(
275 ConnectivityManager.EXTRA_NETWORK_INFO);
276 String typeName = info.getTypeName();
277 String subtypeName = info.getSubtypeName();
278 sendNetworkType(typeName.toLowerCase(),
279 (subtypeName != null ? subtypeName.toLowerCase() : ""));
280
281 onNetworkToggle(info.isAvailable());
Grace Klobaa34f6862009-07-31 16:28:17 -0700282 }
283 }
284 };
285
Grace Kloba615c6c92009-08-03 10:22:44 -0700286 IntentFilter filter = new IntentFilter(Intent.ACTION_PACKAGE_ADDED);
287 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
288 filter.addDataScheme("package");
289 mPackageInstallationReceiver = new BroadcastReceiver() {
290 @Override
291 public void onReceive(Context context, Intent intent) {
292 final String action = intent.getAction();
293 final String packageName = intent.getData()
294 .getSchemeSpecificPart();
295 final boolean replacing = intent.getBooleanExtra(
296 Intent.EXTRA_REPLACING, false);
297 if (Intent.ACTION_PACKAGE_REMOVED.equals(action) && replacing) {
298 // if it is replacing, refreshPlugins() when adding
299 return;
300 }
Andrei Popescu30995e72010-02-09 16:59:58 +0000301
302 if (sGoogleApps.contains(packageName)) {
303 BrowserActivity.this.packageChanged(packageName,
304 Intent.ACTION_PACKAGE_ADDED.equals(action));
305 }
306
Grace Kloba615c6c92009-08-03 10:22:44 -0700307 PackageManager pm = BrowserActivity.this.getPackageManager();
308 PackageInfo pkgInfo = null;
309 try {
310 pkgInfo = pm.getPackageInfo(packageName,
311 PackageManager.GET_PERMISSIONS);
312 } catch (PackageManager.NameNotFoundException e) {
313 return;
314 }
315 if (pkgInfo != null) {
316 String permissions[] = pkgInfo.requestedPermissions;
317 if (permissions == null) {
318 return;
319 }
320 boolean permissionOk = false;
321 for (String permit : permissions) {
322 if (PluginManager.PLUGIN_PERMISSION.equals(permit)) {
323 permissionOk = true;
324 break;
325 }
326 }
327 if (permissionOk) {
328 PluginManager.getInstance(BrowserActivity.this)
Grace Klobae56a0f22010-05-26 17:31:02 -0700329 .refreshPlugins(true);
Grace Kloba615c6c92009-08-03 10:22:44 -0700330 }
331 }
332 }
333 };
334 registerReceiver(mPackageInstallationReceiver, filter);
335
The Android Open Source Project0c908882009-03-03 19:32:16 -0800336 if (!mTabControl.restoreState(icicle)) {
337 // clear up the thumbnail directory if we can't restore the state as
338 // none of the files in the directory are referenced any more.
339 new ClearThumbnails().execute(
340 mTabControl.getThumbnailDir().listFiles());
Grace Klobaaab3f092009-07-30 12:29:51 -0700341 // there is no quit on Android. But if we can't restore the state,
342 // we can treat it as a new Browser, remove the old session cookies.
343 CookieManager.getInstance().removeSessionCookie();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800344 final Intent intent = getIntent();
345 final Bundle extra = intent.getExtras();
346 // Create an initial tab.
347 // If the intent is ACTION_VIEW and data is not null, the Browser is
348 // invoked to view the content by another application. In this case,
349 // the tab will be close when exit.
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700350 UrlData urlData = getUrlDataFromIntent(intent);
351
Leon Scroggins58d56c62010-01-28 15:12:40 -0500352 String action = intent.getAction();
Grace Kloba22ac16e2009-10-07 18:00:23 -0700353 final Tab t = mTabControl.createNewTab(
Leon Scroggins58d56c62010-01-28 15:12:40 -0500354 (Intent.ACTION_VIEW.equals(action) &&
355 intent.getData() != null)
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -0500356 || RecognizerResultsIntent.ACTION_VOICE_SEARCH_RESULTS
357 .equals(action),
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700358 intent.getStringExtra(Browser.EXTRA_APPLICATION_ID), urlData.mUrl);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800359 mTabControl.setCurrentTab(t);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800360 attachTabToContentView(t);
361 WebView webView = t.getWebView();
362 if (extra != null) {
363 int scale = extra.getInt(Browser.INITIAL_ZOOM_LEVEL, 0);
364 if (scale > 0 && scale <= 1000) {
365 webView.setInitialScale(scale);
366 }
367 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800368
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700369 if (urlData.isEmpty()) {
Shimeng (Simon) Wang98d5fce2010-03-16 13:23:39 -0700370 loadUrl(webView, mSettings.getHomePage());
The Android Open Source Project0c908882009-03-03 19:32:16 -0800371 } else {
Patrick Scott9d53da02010-02-19 10:19:01 -0500372 loadUrlDataIn(t, urlData);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800373 }
374 } else {
375 // TabControl.restoreState() will create a new tab even if
Leon Scroggins1f005d32009-08-10 17:36:42 -0400376 // restoring the state fails.
The Android Open Source Project0c908882009-03-03 19:32:16 -0800377 attachTabToContentView(mTabControl.getCurrentTab());
378 }
Grace Kloba615c6c92009-08-03 10:22:44 -0700379
Feng Qianb3c02da2009-06-29 15:58:08 -0700380 // Read JavaScript flags if it exists.
381 String jsFlags = mSettings.getJsFlags();
382 if (jsFlags.trim().length() != 0) {
383 mTabControl.getCurrentWebView().setJsFlags(jsFlags);
384 }
Andrei Popescu30995e72010-02-09 16:59:58 +0000385 // Work out which packages are installed on the system.
386 getInstalledPackages();
Bjorn Bringerta7611812010-03-24 11:12:02 +0000387
388 // Start watching the default geolocation permissions
389 mSystemAllowGeolocationOrigins
390 = new SystemAllowGeolocationOrigins(getApplicationContext());
391 mSystemAllowGeolocationOrigins.start();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800392 }
393
Leon Scroggins58d56c62010-01-28 15:12:40 -0500394 /**
395 * Feed the previously stored results strings to the BrowserProvider so that
396 * the SearchDialog will show them instead of the standard searches.
397 * @param result String to show on the editable line of the SearchDialog.
398 */
399 /* package */ void showVoiceSearchResults(String result) {
400 ContentProviderClient client = mResolver.acquireContentProviderClient(
401 Browser.BOOKMARKS_URI);
402 ContentProvider prov = client.getLocalContentProvider();
403 BrowserProvider bp = (BrowserProvider) prov;
404 bp.setQueryResults(mTabControl.getCurrentTab().getVoiceSearchResults());
405 client.release();
406
Leon Scrogginsfbb3f152010-03-09 17:26:56 -0500407 Bundle bundle = createGoogleSearchSourceBundle(
408 GOOGLE_SEARCH_SOURCE_SEARCHKEY);
409 bundle.putBoolean(SearchManager.CONTEXT_IS_VOICE, true);
410 startSearch(result, false, bundle, false);
Leon Scroggins58d56c62010-01-28 15:12:40 -0500411 }
412
The Android Open Source Project0c908882009-03-03 19:32:16 -0800413 @Override
414 protected void onNewIntent(Intent intent) {
Grace Kloba22ac16e2009-10-07 18:00:23 -0700415 Tab current = mTabControl.getCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800416 // When a tab is closed on exit, the current tab index is set to -1.
417 // Reset before proceed as Browser requires the current tab to be set.
418 if (current == null) {
419 // Try to reset the tab in case the index was incorrect.
420 current = mTabControl.getTab(0);
421 if (current == null) {
422 // No tabs at all so just ignore this intent.
423 return;
424 }
425 mTabControl.setCurrentTab(current);
426 attachTabToContentView(current);
427 resetTitleAndIcon(current.getWebView());
428 }
429 final String action = intent.getAction();
430 final int flags = intent.getFlags();
431 if (Intent.ACTION_MAIN.equals(action) ||
432 (flags & Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY) != 0) {
433 // just resume the browser
434 return;
435 }
Leon Scrogginsb8a844d2010-03-18 15:06:15 -0400436 // In case the SearchDialog is open.
437 ((SearchManager) getSystemService(Context.SEARCH_SERVICE))
438 .stopSearch();
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -0500439 boolean activateVoiceSearch = RecognizerResultsIntent
440 .ACTION_VOICE_SEARCH_RESULTS.equals(action);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800441 if (Intent.ACTION_VIEW.equals(action)
442 || Intent.ACTION_SEARCH.equals(action)
443 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
Leon Scroggins58d56c62010-01-28 15:12:40 -0500444 || Intent.ACTION_WEB_SEARCH.equals(action)
445 || activateVoiceSearch) {
Leon Scroggins3b18ce32010-02-08 17:35:59 -0500446 if (current.isInVoiceSearchMode()) {
447 String title = current.getVoiceDisplayTitle();
448 if (title != null && title.equals(intent.getStringExtra(
449 SearchManager.QUERY))) {
450 // The user submitted the same search as the last voice
451 // search, so do nothing.
452 return;
453 }
Leon Scroggins1fe13a52010-02-09 15:31:26 -0500454 if (Intent.ACTION_SEARCH.equals(action)
455 && current.voiceSearchSourceIsGoogle()) {
456 Intent logIntent = new Intent(
457 LoggingEvents.ACTION_LOG_EVENT);
458 logIntent.putExtra(LoggingEvents.EXTRA_EVENT,
459 LoggingEvents.VoiceSearch.QUERY_UPDATED);
460 logIntent.putExtra(
461 LoggingEvents.VoiceSearch.EXTRA_QUERY_UPDATED_VALUE,
462 intent.getDataString());
463 sendBroadcast(logIntent);
464 // Note, onPageStarted will revert the voice title bar
465 // When http://b/issue?id=2379215 is fixed, we should update
466 // the title bar here.
467 }
Leon Scroggins3b18ce32010-02-08 17:35:59 -0500468 }
Satish Sampath565505b2009-05-29 15:37:27 +0100469 // If this was a search request (e.g. search query directly typed into the address bar),
470 // pass it on to the default web search provider.
471 if (handleWebSearchIntent(intent)) {
472 return;
473 }
474
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700475 UrlData urlData = getUrlDataFromIntent(intent);
476 if (urlData.isEmpty()) {
477 urlData = new UrlData(mSettings.getHomePage());
The Android Open Source Project0c908882009-03-03 19:32:16 -0800478 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700479
Grace Klobacc634032009-07-28 15:58:19 -0700480 final String appId = intent
481 .getStringExtra(Browser.EXTRA_APPLICATION_ID);
Leon Scroggins47208682010-04-07 17:59:48 -0400482 if ((Intent.ACTION_VIEW.equals(action)
483 // If a voice search has no appId, it means that it came
484 // from the browser. In that case, reuse the current tab.
485 || (activateVoiceSearch && appId != null))
Grace Klobacc634032009-07-28 15:58:19 -0700486 && !getPackageName().equals(appId)
487 && (flags & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0) {
Grace Kloba22ac16e2009-10-07 18:00:23 -0700488 Tab appTab = mTabControl.getTabFromId(appId);
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700489 if (appTab != null) {
490 Log.i(LOGTAG, "Reusing tab for " + appId);
491 // Dismiss the subwindow if applicable.
492 dismissSubWindow(appTab);
493 // Since we might kill the WebView, remove it from the
494 // content view first.
495 removeTabFromContentView(appTab);
496 // Recreate the main WebView after destroying the old one.
497 // If the WebView has the same original url and is on that
498 // page, it can be reused.
499 boolean needsLoad =
Leon Scroggins6eac63e2010-03-15 18:19:14 -0400500 mTabControl.recreateWebView(appTab, urlData);
Ben Murdochbff2d602009-07-01 20:19:05 +0100501
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700502 if (current != appTab) {
Leon Scroggins1f005d32009-08-10 17:36:42 -0400503 switchToTab(mTabControl.getTabIndex(appTab));
504 if (needsLoad) {
Patrick Scott9d53da02010-02-19 10:19:01 -0500505 loadUrlDataIn(appTab, urlData);
Leon Scroggins1f005d32009-08-10 17:36:42 -0400506 }
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700507 } else {
Leon Scroggins1f005d32009-08-10 17:36:42 -0400508 // If the tab was the current tab, we have to attach
509 // it to the view system again.
510 attachTabToContentView(appTab);
511 if (needsLoad) {
Patrick Scott9d53da02010-02-19 10:19:01 -0500512 loadUrlDataIn(appTab, urlData);
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700513 }
514 }
515 return;
Patrick Scottcd115892009-07-16 09:42:58 -0400516 } else {
517 // No matching application tab, try to find a regular tab
518 // with a matching url.
519 appTab = mTabControl.findUnusedTabWithUrl(urlData.mUrl);
Leon Scroggins25515f82009-08-19 15:31:58 -0400520 if (appTab != null) {
521 if (current != appTab) {
522 switchToTab(mTabControl.getTabIndex(appTab));
523 }
524 // Otherwise, we are already viewing the correct tab.
Patrick Scottcd115892009-07-16 09:42:58 -0400525 } else {
526 // if FLAG_ACTIVITY_BROUGHT_TO_FRONT flag is on, the url
527 // will be opened in a new tab unless we have reached
528 // MAX_TABS. Then the url will be opened in the current
529 // tab. If a new tab is created, it will have "true" for
530 // exit on close.
Leon Scroggins1f005d32009-08-10 17:36:42 -0400531 openTabAndShow(urlData, true, appId);
Patrick Scottcd115892009-07-16 09:42:58 -0400532 }
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700533 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800534 } else {
Grace Kloba638d3f42009-11-23 10:35:04 -0800535 if (!urlData.isEmpty()
536 && urlData.mUrl.startsWith("about:debug")) {
537 if ("about:debug.dom".equals(urlData.mUrl)) {
538 current.getWebView().dumpDomTree(false);
539 } else if ("about:debug.dom.file".equals(urlData.mUrl)) {
540 current.getWebView().dumpDomTree(true);
541 } else if ("about:debug.render".equals(urlData.mUrl)) {
542 current.getWebView().dumpRenderTree(false);
543 } else if ("about:debug.render.file".equals(urlData.mUrl)) {
544 current.getWebView().dumpRenderTree(true);
545 } else if ("about:debug.display".equals(urlData.mUrl)) {
546 current.getWebView().dumpDisplayTree();
Mike Reed9b78e1d2010-01-13 14:40:52 -0800547 } else if (urlData.mUrl.startsWith("about:debug.drag")) {
548 int index = urlData.mUrl.codePointAt(16) - '0';
549 if (index <= 0 || index > 9) {
550 current.getWebView().setDragTracker(null);
551 } else {
552 current.getWebView().setDragTracker(new MeshTracker(index));
553 }
Grace Kloba638d3f42009-11-23 10:35:04 -0800554 } else {
555 mSettings.toggleDebugSettings();
556 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800557 return;
558 }
Leon Scroggins1f005d32009-08-10 17:36:42 -0400559 // Get rid of the subwindow if it exists
560 dismissSubWindow(current);
Leon Scroggins8588d152010-04-15 11:01:53 -0400561 // If the current Tab is being used as an application tab,
562 // remove the association, since the new Intent means that it is
563 // no longer associated with that application.
564 current.setAppId(null);
Patrick Scott9d53da02010-02-19 10:19:01 -0500565 loadUrlDataIn(current, urlData);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800566 }
567 }
568 }
569
Satish Sampath565505b2009-05-29 15:37:27 +0100570 private int parseUrlShortcut(String url) {
571 if (url == null) return SHORTCUT_INVALID;
572
573 // FIXME: quick search, need to be customized by setting
574 if (url.length() > 2 && url.charAt(1) == ' ') {
575 switch (url.charAt(0)) {
576 case 'g': return SHORTCUT_GOOGLE_SEARCH;
577 case 'w': return SHORTCUT_WIKIPEDIA_SEARCH;
578 case 'd': return SHORTCUT_DICTIONARY_SEARCH;
579 case 'l': return SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH;
580 }
581 }
582 return SHORTCUT_INVALID;
583 }
584
585 /**
586 * Launches the default web search activity with the query parameters if the given intent's data
587 * are identified as plain search terms and not URLs/shortcuts.
588 * @return true if the intent was handled and web search activity was launched, false if not.
589 */
590 private boolean handleWebSearchIntent(Intent intent) {
591 if (intent == null) return false;
592
593 String url = null;
594 final String action = intent.getAction();
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -0500595 if (RecognizerResultsIntent.ACTION_VOICE_SEARCH_RESULTS.equals(
596 action)) {
Leon Scroggins58d56c62010-01-28 15:12:40 -0500597 return false;
598 }
Satish Sampath565505b2009-05-29 15:37:27 +0100599 if (Intent.ACTION_VIEW.equals(action)) {
Grace Kloba1e705052009-09-29 13:13:36 -0700600 Uri data = intent.getData();
601 if (data != null) url = data.toString();
Satish Sampath565505b2009-05-29 15:37:27 +0100602 } else if (Intent.ACTION_SEARCH.equals(action)
603 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
604 || Intent.ACTION_WEB_SEARCH.equals(action)) {
605 url = intent.getStringExtra(SearchManager.QUERY);
606 }
Bjorn Bringert04851702009-09-22 10:36:01 +0100607 return handleWebSearchRequest(url, intent.getBundleExtra(SearchManager.APP_DATA),
608 intent.getStringExtra(SearchManager.EXTRA_DATA_KEY));
Satish Sampath565505b2009-05-29 15:37:27 +0100609 }
610
611 /**
612 * Launches the default web search activity with the query parameters if the given url string
613 * was identified as plain search terms and not URL/shortcut.
614 * @return true if the request was handled and web search activity was launched, false if not.
615 */
Bjorn Bringert04851702009-09-22 10:36:01 +0100616 private boolean handleWebSearchRequest(String inUrl, Bundle appData, String extraData) {
Satish Sampath565505b2009-05-29 15:37:27 +0100617 if (inUrl == null) return false;
618
619 // In general, we shouldn't modify URL from Intent.
620 // But currently, we get the user-typed URL from search box as well.
621 String url = fixUrl(inUrl).trim();
622
623 // URLs and site specific search shortcuts are handled by the regular flow of control, so
624 // return early.
Dan Egnor5ee906c2009-11-18 12:11:49 -0800625 if (Patterns.WEB_URL.matcher(url).matches()
Satish Sampathbc5b9f32009-06-04 18:21:40 +0100626 || ACCEPTED_URI_SCHEMA.matcher(url).matches()
Satish Sampath565505b2009-05-29 15:37:27 +0100627 || parseUrlShortcut(url) != SHORTCUT_INVALID) {
628 return false;
629 }
630
Leon Scroggins8d06e362010-03-24 14:45:57 -0400631 final ContentResolver cr = mResolver;
632 final String newUrl = url;
633 new AsyncTask<Void, Void, Void>() {
634 protected Void doInBackground(Void... unused) {
635 Browser.updateVisitedHistory(cr, newUrl, false);
636 Browser.addSearchUrl(cr, newUrl);
637 return null;
638 }
639 }.execute();
Satish Sampath565505b2009-05-29 15:37:27 +0100640
641 Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);
642 intent.addCategory(Intent.CATEGORY_DEFAULT);
643 intent.putExtra(SearchManager.QUERY, url);
Satish Sampath15e9f2d2009-06-23 22:29:49 +0100644 if (appData != null) {
645 intent.putExtra(SearchManager.APP_DATA, appData);
646 }
Bjorn Bringert04851702009-09-22 10:36:01 +0100647 if (extraData != null) {
648 intent.putExtra(SearchManager.EXTRA_DATA_KEY, extraData);
649 }
Grace Klobacc634032009-07-28 15:58:19 -0700650 intent.putExtra(Browser.EXTRA_APPLICATION_ID, getPackageName());
Satish Sampath565505b2009-05-29 15:37:27 +0100651 startActivity(intent);
652
653 return true;
654 }
655
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700656 private UrlData getUrlDataFromIntent(Intent intent) {
Leon Scroggins58d56c62010-01-28 15:12:40 -0500657 String url = "";
Grace Kloba068e48b2010-01-26 18:11:27 -0800658 Map<String, String> headers = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800659 if (intent != null) {
660 final String action = intent.getAction();
661 if (Intent.ACTION_VIEW.equals(action)) {
662 url = smartUrlFilter(intent.getData());
663 if (url != null && url.startsWith("content:")) {
664 /* Append mimetype so webview knows how to display */
665 String mimeType = intent.resolveType(getContentResolver());
666 if (mimeType != null) {
667 url += "?" + mimeType;
668 }
669 }
Grace Kloba068e48b2010-01-26 18:11:27 -0800670 if (url != null && url.startsWith("http")) {
Grace Kloba00f54c52010-01-27 14:53:51 -0800671 final Bundle pairs = intent
672 .getBundleExtra(Browser.EXTRA_HEADERS);
Grace Kloba2d508ed2010-01-28 11:39:15 -0800673 if (pairs != null && !pairs.isEmpty()) {
Grace Kloba00f54c52010-01-27 14:53:51 -0800674 Iterator<String> iter = pairs.keySet().iterator();
Grace Kloba068e48b2010-01-26 18:11:27 -0800675 headers = new HashMap<String, String>();
Grace Kloba00f54c52010-01-27 14:53:51 -0800676 while (iter.hasNext()) {
677 String key = iter.next();
678 headers.put(key, pairs.getString(key));
Grace Kloba068e48b2010-01-26 18:11:27 -0800679 }
680 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700681 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800682 } else if (Intent.ACTION_SEARCH.equals(action)
683 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
684 || Intent.ACTION_WEB_SEARCH.equals(action)) {
685 url = intent.getStringExtra(SearchManager.QUERY);
686 if (url != null) {
687 mLastEnteredUrl = url;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800688 // In general, we shouldn't modify URL from Intent.
689 // But currently, we get the user-typed URL from search box as well.
690 url = fixUrl(url);
691 url = smartUrlFilter(url);
Leon Scroggins8d06e362010-03-24 14:45:57 -0400692 final ContentResolver cr = mResolver;
693 final String newUrl = url;
694 new AsyncTask<Void, Void, Void>() {
695 protected Void doInBackground(Void... unused) {
696 Browser.updateVisitedHistory(cr, newUrl, false);
697 return null;
698 }
699 }.execute();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800700 String searchSource = "&source=android-" + GOOGLE_SEARCH_SOURCE_SUGGEST + "&";
701 if (url.contains(searchSource)) {
702 String source = null;
703 final Bundle appData = intent.getBundleExtra(SearchManager.APP_DATA);
704 if (appData != null) {
Bjorn Bringert10d1cca2010-02-10 14:22:12 +0000705 source = appData.getString(Search.SOURCE);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800706 }
707 if (TextUtils.isEmpty(source)) {
708 source = GOOGLE_SEARCH_SOURCE_UNKNOWN;
709 }
710 url = url.replace(searchSource, "&source=android-"+source+"&");
711 }
712 }
713 }
714 }
Leon Scroggins58d56c62010-01-28 15:12:40 -0500715 return new UrlData(url, headers, intent);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800716 }
Leon Scroggins58d56c62010-01-28 15:12:40 -0500717 /* package */ void showVoiceTitleBar(String title) {
718 mTitleBar.setInVoiceMode(true);
Leon Scroggins58d56c62010-01-28 15:12:40 -0500719 mTitleBar.setDisplayTitle(title);
Leon Scrogginsd746a942010-05-19 13:21:44 -0400720
721 if (!mXLargeScreenSize) {
722 mFakeTitleBar.setInVoiceMode(true);
723 mFakeTitleBar.setDisplayTitle(title);
724 }
Leon Scroggins58d56c62010-01-28 15:12:40 -0500725 }
726 /* package */ void revertVoiceTitleBar() {
727 mTitleBar.setInVoiceMode(false);
Leon Scroggins003a5dd2010-03-10 12:13:14 -0500728 mTitleBar.setDisplayTitle(mUrl);
Leon Scrogginsd746a942010-05-19 13:21:44 -0400729
730 if (!mXLargeScreenSize) {
731 mFakeTitleBar.setInVoiceMode(false);
732 mFakeTitleBar.setDisplayTitle(mUrl);
733 }
Leon Scroggins58d56c62010-01-28 15:12:40 -0500734 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800735 /* package */ static String fixUrl(String inUrl) {
Cary Clark652ff872009-09-10 13:34:44 -0400736 // FIXME: Converting the url to lower case
737 // duplicates functionality in smartUrlFilter().
738 // However, changing all current callers of fixUrl to
739 // call smartUrlFilter in addition may have unwanted
740 // consequences, and is deferred for now.
741 int colon = inUrl.indexOf(':');
742 boolean allLower = true;
743 for (int index = 0; index < colon; index++) {
744 char ch = inUrl.charAt(index);
745 if (!Character.isLetter(ch)) {
746 break;
747 }
748 allLower &= Character.isLowerCase(ch);
749 if (index == colon - 1 && !allLower) {
750 inUrl = inUrl.substring(0, colon).toLowerCase()
751 + inUrl.substring(colon);
752 }
753 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800754 if (inUrl.startsWith("http://") || inUrl.startsWith("https://"))
755 return inUrl;
756 if (inUrl.startsWith("http:") ||
757 inUrl.startsWith("https:")) {
758 if (inUrl.startsWith("http:/") || inUrl.startsWith("https:/")) {
759 inUrl = inUrl.replaceFirst("/", "//");
760 } else inUrl = inUrl.replaceFirst(":", "://");
761 }
762 return inUrl;
763 }
764
Grace Kloba22ac16e2009-10-07 18:00:23 -0700765 @Override
766 protected void onResume() {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800767 super.onResume();
Dave Bort31a6d1c2009-04-13 15:56:49 -0700768 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800769 Log.v(LOGTAG, "BrowserActivity.onResume: this=" + this);
770 }
771
772 if (!mActivityInPause) {
773 Log.e(LOGTAG, "BrowserActivity is already resumed.");
774 return;
775 }
776
Mike Reed7bfa63b2009-05-28 11:08:32 -0400777 mTabControl.resumeCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800778 mActivityInPause = false;
Mike Reed7bfa63b2009-05-28 11:08:32 -0400779 resumeWebViewTimers();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800780
781 if (mWakeLock.isHeld()) {
782 mHandler.removeMessages(RELEASE_WAKELOCK);
783 mWakeLock.release();
784 }
785
The Android Open Source Project0c908882009-03-03 19:32:16 -0800786 registerReceiver(mNetworkStateIntentReceiver,
787 mNetworkStateChangedFilter);
788 WebView.enablePlatformNotifications();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800789 }
790
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400791 /**
792 * Since the actual title bar is embedded in the WebView, and removing it
Leon Scrogginsfe87bd32009-10-06 10:10:00 -0400793 * would change its appearance, use a different TitleBar to show overlayed
794 * at the top of the screen, when the menu is open or the page is loading.
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400795 */
796 private TitleBar mFakeTitleBar;
797
798 /**
799 * Keeps track of whether the options menu is open. This is important in
800 * determining whether to show or hide the title bar overlay.
801 */
802 private boolean mOptionsMenuOpen;
803
804 /**
805 * Only meaningful when mOptionsMenuOpen is true. This variable keeps track
806 * of whether the configuration has changed. The first onMenuOpened call
807 * after a configuration change is simply a reopening of the same menu
808 * (i.e. mIconView did not change).
809 */
810 private boolean mConfigChanged;
811
812 /**
813 * Whether or not the options menu is in its smaller, icon menu form. When
814 * true, we want the title bar overlay to be up. When false, we do not.
815 * Only meaningful if mOptionsMenuOpen is true.
816 */
817 private boolean mIconView;
818
Leon Scrogginsa81a7642009-08-31 17:05:41 -0400819 @Override
820 public boolean onMenuOpened(int featureId, Menu menu) {
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400821 if (Window.FEATURE_OPTIONS_PANEL == featureId) {
822 if (mOptionsMenuOpen) {
823 if (mConfigChanged) {
824 // We do not need to make any changes to the state of the
825 // title bar, since the only thing that happened was a
826 // change in orientation
827 mConfigChanged = false;
828 } else {
829 if (mIconView) {
830 // Switching the menu to expanded view, so hide the
831 // title bar.
832 hideFakeTitleBar();
833 mIconView = false;
834 } else {
835 // Switching the menu back to icon view, so show the
836 // title bar once again.
837 showFakeTitleBar();
838 mIconView = true;
839 }
840 }
841 } else {
842 // The options menu is closed, so open it, and show the title
843 showFakeTitleBar();
844 mOptionsMenuOpen = true;
845 mConfigChanged = false;
846 mIconView = true;
847 }
848 }
Leon Scrogginsa81a7642009-08-31 17:05:41 -0400849 return true;
850 }
851
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400852 private void showFakeTitleBar() {
Leon Scrogginsd746a942010-05-19 13:21:44 -0400853 if (mXLargeScreenSize) return;
Leon Scrogginsfe87bd32009-10-06 10:10:00 -0400854 if (mFakeTitleBar.getParent() == null && mActiveTabsPage == null
Grace Kloba847c25b2010-03-30 16:00:26 -0700855 && !mActivityInPause) {
856 WebView mainView = mTabControl.getCurrentWebView();
857 // if there is no current WebView, don't show the faked title bar;
Grace Kloba65190702010-04-02 23:37:26 -0700858 if (mainView == null) {
Cary Clarka0464552009-09-29 13:00:45 -0400859 return;
860 }
Leon Scroggins79e36d92010-04-29 16:01:46 +0100861 // Do not need to check for null, since the current tab will have
862 // at least a main WebView, or we would have returned above.
863 if (getTopWindow().getFindIsUp()) {
864 // Do not show the fake title bar, which would cover up the
865 // FindDialog.
866 return;
867 }
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400868
869 WindowManager manager
870 = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
871
872 // Add the title bar to the window manager so it can receive touches
873 // while the menu is up
874 WindowManager.LayoutParams params
875 = new WindowManager.LayoutParams(
Romain Guy15b8ec62010-01-08 15:06:43 -0800876 ViewGroup.LayoutParams.MATCH_PARENT,
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400877 ViewGroup.LayoutParams.WRAP_CONTENT,
Grace Kloba847c25b2010-03-30 16:00:26 -0700878 WindowManager.LayoutParams.TYPE_APPLICATION,
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400879 WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
Leon Scroggins68549862009-09-21 16:02:01 -0400880 PixelFormat.TRANSLUCENT);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400881 params.gravity = Gravity.TOP;
Grace Kloba847c25b2010-03-30 16:00:26 -0700882 boolean atTop = mainView.getScrollY() == 0;
Leon Scroggins83932c72009-09-30 11:55:54 -0400883 params.windowAnimations = atTop ? 0 : R.style.TitleBar;
Grace Kloba13f9ace2010-03-18 21:44:14 -0700884 manager.addView(mFakeTitleBar, params);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400885 }
886 }
887
888 @Override
889 public void onOptionsMenuClosed(Menu menu) {
890 mOptionsMenuOpen = false;
Leon Scrogginsa27ff192009-09-14 12:58:04 -0400891 if (!mInLoad) {
892 hideFakeTitleBar();
893 } else if (!mIconView) {
894 // The page is currently loading, and we are in expanded mode, so
895 // we were not showing the menu. Show it once again. It will be
896 // removed when the page finishes.
897 showFakeTitleBar();
898 }
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400899 }
Grace Kloba22ac16e2009-10-07 18:00:23 -0700900
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400901 private void hideFakeTitleBar() {
Leon Scrogginsd746a942010-05-19 13:21:44 -0400902 if (mXLargeScreenSize || mFakeTitleBar.getParent() == null) return;
Leon Scroggins20329572009-09-23 17:42:41 -0400903 WindowManager.LayoutParams params = (WindowManager.LayoutParams)
Grace Kloba13f9ace2010-03-18 21:44:14 -0700904 mFakeTitleBar.getLayoutParams();
Leon Scroggins20329572009-09-23 17:42:41 -0400905 WebView mainView = mTabControl.getCurrentWebView();
906 // Although we decided whether or not to animate based on the current
907 // scroll position, the scroll position may have changed since the
908 // fake title bar was displayed. Make sure it has the appropriate
909 // animation/lack thereof before removing.
910 params.windowAnimations = mainView != null && mainView.getScrollY() == 0
Leon Scroggins83932c72009-09-30 11:55:54 -0400911 ? 0 : R.style.TitleBar;
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400912 WindowManager manager
913 = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
Grace Kloba13f9ace2010-03-18 21:44:14 -0700914 manager.updateViewLayout(mFakeTitleBar, params);
915 manager.removeView(mFakeTitleBar);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400916 }
917
The Android Open Source Project0c908882009-03-03 19:32:16 -0800918 /**
Leon Scrogginsc6fa1102009-09-21 10:40:01 -0400919 * Special method for the fake title bar to call when displaying its context
920 * menu, since it is in its own Window, and its parent does not show a
921 * context menu.
922 */
923 /* package */ void showTitleBarContextMenu() {
Cary Clark65f4a3c2009-09-28 17:05:06 -0400924 if (null == mTitleBar.getParent()) {
925 return;
926 }
Leon Scrogginsc6fa1102009-09-21 10:40:01 -0400927 openContextMenu(mTitleBar);
928 }
929
Leon Scrogginsb2b19f52009-10-09 16:10:00 -0400930 @Override
931 public void onContextMenuClosed(Menu menu) {
932 super.onContextMenuClosed(menu);
933 if (mInLoad) {
934 showFakeTitleBar();
935 }
936 }
937
Leon Scrogginsc6fa1102009-09-21 10:40:01 -0400938 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -0800939 * onSaveInstanceState(Bundle map)
940 * onSaveInstanceState is called right before onStop(). The map contains
941 * the saved state.
942 */
Grace Kloba22ac16e2009-10-07 18:00:23 -0700943 @Override
944 protected void onSaveInstanceState(Bundle outState) {
Dave Bort31a6d1c2009-04-13 15:56:49 -0700945 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800946 Log.v(LOGTAG, "BrowserActivity.onSaveInstanceState: this=" + this);
947 }
948 // the default implementation requires each view to have an id. As the
949 // browser handles the state itself and it doesn't use id for the views,
950 // don't call the default implementation. Otherwise it will trigger the
951 // warning like this, "couldn't save which view has focus because the
952 // focused view XXX has no id".
953
954 // Save all the tabs
955 mTabControl.saveState(outState);
956 }
957
Grace Kloba22ac16e2009-10-07 18:00:23 -0700958 @Override
959 protected void onPause() {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800960 super.onPause();
961
962 if (mActivityInPause) {
963 Log.e(LOGTAG, "BrowserActivity is already paused.");
964 return;
965 }
966
Mike Reed7bfa63b2009-05-28 11:08:32 -0400967 mTabControl.pauseCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800968 mActivityInPause = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -0400969 if (mTabControl.getCurrentIndex() >= 0 && !pauseWebViewTimers()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800970 mWakeLock.acquire();
971 mHandler.sendMessageDelayed(mHandler
972 .obtainMessage(RELEASE_WAKELOCK), WAKELOCK_TIMEOUT);
973 }
974
Leon Scrogginsa2ab6a72009-09-11 11:49:52 -0400975 // FIXME: This removes the active tabs page and resets the menu to
976 // MAIN_MENU. A better solution might be to do this work in onNewIntent
977 // but then we would need to save it in onSaveInstanceState and restore
978 // it in onCreate/onRestoreInstanceState
979 if (mActiveTabsPage != null) {
980 removeActiveTabPage(true);
981 }
982
The Android Open Source Project0c908882009-03-03 19:32:16 -0800983 cancelStopToast();
984
985 // unregister network state listener
986 unregisterReceiver(mNetworkStateIntentReceiver);
987 WebView.disablePlatformNotifications();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800988 }
989
Grace Kloba22ac16e2009-10-07 18:00:23 -0700990 @Override
991 protected void onDestroy() {
Dave Bort31a6d1c2009-04-13 15:56:49 -0700992 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800993 Log.v(LOGTAG, "BrowserActivity.onDestroy: this=" + this);
994 }
995 super.onDestroy();
Grace Kloba0923d692009-09-23 21:37:25 -0700996
Leon Scroggins8d5fa432009-10-02 15:55:59 -0400997 if (mUploadMessage != null) {
998 mUploadMessage.onReceiveValue(null);
999 mUploadMessage = null;
1000 }
1001
Grace Kloba0923d692009-09-23 21:37:25 -07001002 if (mTabControl == null) return;
1003
Grace Kloba1fc98a32009-10-21 13:23:08 -07001004 // Remove the fake title bar if it is there
1005 hideFakeTitleBar();
1006
The Android Open Source Project0c908882009-03-03 19:32:16 -08001007 // Remove the current tab and sub window
Grace Kloba22ac16e2009-10-07 18:00:23 -07001008 Tab t = mTabControl.getCurrentTab();
Patrick Scottfb5e77f2009-04-08 19:17:37 -07001009 if (t != null) {
1010 dismissSubWindow(t);
1011 removeTabFromContentView(t);
1012 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001013 // Destroy all the tabs
1014 mTabControl.destroy();
1015 WebIconDatabase.getInstance().close();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001016
Grace Klobab4da0ad2009-05-14 14:45:40 -07001017 unregisterReceiver(mPackageInstallationReceiver);
Bjorn Bringerta7611812010-03-24 11:12:02 +00001018
1019 // Stop watching the default geolocation permissions
1020 mSystemAllowGeolocationOrigins.stop();
1021 mSystemAllowGeolocationOrigins = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001022 }
1023
1024 @Override
1025 public void onConfigurationChanged(Configuration newConfig) {
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04001026 mConfigChanged = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001027 super.onConfigurationChanged(newConfig);
1028
1029 if (mPageInfoDialog != null) {
1030 mPageInfoDialog.dismiss();
1031 showPageInfo(
1032 mPageInfoView,
Leon Scrogginsc7b92f82010-01-11 18:17:31 -05001033 mPageInfoFromShowSSLCertificateOnError);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001034 }
1035 if (mSSLCertificateDialog != null) {
1036 mSSLCertificateDialog.dismiss();
1037 showSSLCertificate(
1038 mSSLCertificateView);
1039 }
1040 if (mSSLCertificateOnErrorDialog != null) {
1041 mSSLCertificateOnErrorDialog.dismiss();
1042 showSSLCertificateOnError(
1043 mSSLCertificateOnErrorView,
1044 mSSLCertificateOnErrorHandler,
1045 mSSLCertificateOnErrorError);
1046 }
1047 if (mHttpAuthenticationDialog != null) {
1048 String title = ((TextView) mHttpAuthenticationDialog
1049 .findViewById(com.android.internal.R.id.alertTitle)).getText()
1050 .toString();
1051 String name = ((TextView) mHttpAuthenticationDialog
1052 .findViewById(R.id.username_edit)).getText().toString();
1053 String password = ((TextView) mHttpAuthenticationDialog
1054 .findViewById(R.id.password_edit)).getText().toString();
1055 int focusId = mHttpAuthenticationDialog.getCurrentFocus()
1056 .getId();
1057 mHttpAuthenticationDialog.dismiss();
1058 showHttpAuthentication(mHttpAuthHandler, null, null, title,
1059 name, password, focusId);
1060 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001061 }
1062
Grace Kloba22ac16e2009-10-07 18:00:23 -07001063 @Override
1064 public void onLowMemory() {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001065 super.onLowMemory();
1066 mTabControl.freeMemory();
1067 }
1068
Cary Clarkff4d92c2010-03-25 11:17:03 -04001069 private void resumeWebViewTimers() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001070 Tab tab = mTabControl.getCurrentTab();
Cary Clarkff4d92c2010-03-25 11:17:03 -04001071 if (tab == null) return; // monkey can trigger this
Grace Kloba22ac16e2009-10-07 18:00:23 -07001072 boolean inLoad = tab.inLoad();
1073 if ((!mActivityInPause && !inLoad) || (mActivityInPause && inLoad)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001074 CookieSyncManager.getInstance().startSync();
Grace Kloba22ac16e2009-10-07 18:00:23 -07001075 WebView w = tab.getWebView();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001076 if (w != null) {
1077 w.resumeTimers();
1078 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001079 }
1080 }
1081
Mike Reed7bfa63b2009-05-28 11:08:32 -04001082 private boolean pauseWebViewTimers() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001083 Tab tab = mTabControl.getCurrentTab();
1084 boolean inLoad = tab.inLoad();
1085 if (mActivityInPause && !inLoad) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001086 CookieSyncManager.getInstance().stopSync();
1087 WebView w = mTabControl.getCurrentWebView();
1088 if (w != null) {
1089 w.pauseTimers();
1090 }
1091 return true;
1092 } else {
1093 return false;
1094 }
1095 }
1096
The Android Open Source Project0c908882009-03-03 19:32:16 -08001097 // Open the icon database and retain all the icons for visited sites.
1098 private void retainIconsOnStartup() {
1099 final WebIconDatabase db = WebIconDatabase.getInstance();
1100 db.open(getDir("icons", 0).getPath());
Leon Scroggins2c0f6112010-03-12 18:09:39 -05001101 Cursor c = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001102 try {
Leon Scroggins2c0f6112010-03-12 18:09:39 -05001103 c = Browser.getAllBookmarks(mResolver);
1104 if (c.moveToFirst()) {
1105 int urlIndex = c.getColumnIndex(Browser.BookmarkColumns.URL);
1106 do {
1107 String url = c.getString(urlIndex);
1108 db.retainIconForPageUrl(url);
1109 } while (c.moveToNext());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001110 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001111 } catch (IllegalStateException e) {
1112 Log.e(LOGTAG, "retainIconsOnStartup", e);
Leon Scroggins2c0f6112010-03-12 18:09:39 -05001113 } finally {
1114 if (c!= null) c.close();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001115 }
1116 }
1117
1118 // Helper method for getting the top window.
1119 WebView getTopWindow() {
1120 return mTabControl.getCurrentTopWebView();
1121 }
1122
Grace Kloba22ac16e2009-10-07 18:00:23 -07001123 TabControl getTabControl() {
1124 return mTabControl;
1125 }
1126
The Android Open Source Project0c908882009-03-03 19:32:16 -08001127 @Override
1128 public boolean onCreateOptionsMenu(Menu menu) {
1129 super.onCreateOptionsMenu(menu);
1130
1131 MenuInflater inflater = getMenuInflater();
1132 inflater.inflate(R.menu.browser, menu);
1133 mMenu = menu;
1134 updateInLoadMenuItems();
1135 return true;
1136 }
1137
1138 /**
1139 * As the menu can be open when loading state changes
1140 * we must manually update the state of the stop/reload menu
1141 * item
1142 */
1143 private void updateInLoadMenuItems() {
1144 if (mMenu == null) {
1145 return;
1146 }
1147 MenuItem src = mInLoad ?
1148 mMenu.findItem(R.id.stop_menu_id):
1149 mMenu.findItem(R.id.reload_menu_id);
1150 MenuItem dest = mMenu.findItem(R.id.stop_reload_menu_id);
1151 dest.setIcon(src.getIcon());
1152 dest.setTitle(src.getTitle());
1153 }
1154
1155 @Override
1156 public boolean onContextItemSelected(MenuItem item) {
1157 // chording is not an issue with context menus, but we use the same
1158 // options selector, so set mCanChord to true so we can access them.
1159 mCanChord = true;
1160 int id = item.getItemId();
Leon Scroggins96afcb12009-12-10 12:35:56 -05001161 boolean result = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001162 switch (id) {
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001163 // For the context menu from the title bar
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001164 case R.id.title_bar_copy_page_url:
Leon Scroggins96afcb12009-12-10 12:35:56 -05001165 Tab currentTab = mTabControl.getCurrentTab();
1166 if (null == currentTab) {
1167 result = false;
1168 break;
1169 }
1170 WebView mainView = currentTab.getWebView();
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001171 if (null == mainView) {
Leon Scroggins96afcb12009-12-10 12:35:56 -05001172 result = false;
1173 break;
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001174 }
Leon Scroggins96afcb12009-12-10 12:35:56 -05001175 copy(mainView.getUrl());
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001176 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001177 // -- Browser context menu
1178 case R.id.open_context_menu_id:
The Android Open Source Project0c908882009-03-03 19:32:16 -08001179 case R.id.bookmark_context_menu_id:
1180 case R.id.save_link_context_menu_id:
1181 case R.id.share_link_context_menu_id:
1182 case R.id.copy_link_context_menu_id:
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001183 final WebView webView = getTopWindow();
1184 if (null == webView) {
Leon Scroggins96afcb12009-12-10 12:35:56 -05001185 result = false;
1186 break;
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001187 }
1188 final HashMap hrefMap = new HashMap();
1189 hrefMap.put("webview", webView);
1190 final Message msg = mHandler.obtainMessage(
1191 FOCUS_NODE_HREF, id, 0, hrefMap);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001192 webView.requestFocusNodeHref(msg);
1193 break;
1194
1195 default:
1196 // For other context menus
Leon Scroggins96afcb12009-12-10 12:35:56 -05001197 result = onOptionsItemSelected(item);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001198 }
1199 mCanChord = false;
Leon Scroggins96afcb12009-12-10 12:35:56 -05001200 return result;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001201 }
1202
1203 private Bundle createGoogleSearchSourceBundle(String source) {
1204 Bundle bundle = new Bundle();
Bjorn Bringert10d1cca2010-02-10 14:22:12 +00001205 bundle.putString(Search.SOURCE, source);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001206 return bundle;
1207 }
1208
Leon Scroggins8ad29922010-02-16 12:33:55 -05001209 /* package */ void editUrl() {
Leon Scroggins68579392009-09-15 15:31:54 -04001210 if (mOptionsMenuOpen) closeOptionsMenu();
Leon Scroggins5bbe9802009-07-31 13:10:55 -04001211 String url = (getTopWindow() == null) ? null : getTopWindow().getUrl();
Grace Kloba83f47342009-07-20 10:44:31 -07001212 startSearch(mSettings.getHomePage().equals(url) ? null : url, true,
Leon Scroggins8ad29922010-02-16 12:33:55 -05001213 null, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001214 }
1215
Leon Scroggins8ad29922010-02-16 12:33:55 -05001216 /**
1217 * Overriding this to insert a local information bundle
1218 */
The Android Open Source Project0c908882009-03-03 19:32:16 -08001219 @Override
1220 public void startSearch(String initialQuery, boolean selectInitialQuery,
1221 Bundle appSearchData, boolean globalSearch) {
1222 if (appSearchData == null) {
1223 appSearchData = createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_TYPE);
1224 }
1225 super.startSearch(initialQuery, selectInitialQuery, appSearchData, globalSearch);
1226 }
1227
Leon Scroggins1f005d32009-08-10 17:36:42 -04001228 /**
1229 * Switch tabs. Called by the TitleBarSet when sliding the title bar
1230 * results in changing tabs.
Leon Scroggins160a7e72009-08-14 18:28:01 -04001231 * @param index Index of the tab to change to, as defined by
1232 * mTabControl.getTabIndex(Tab t).
1233 * @return boolean True if we successfully switched to a different tab. If
1234 * the indexth tab is null, or if that tab is the same as
1235 * the current one, return false.
Leon Scroggins1f005d32009-08-10 17:36:42 -04001236 */
Leon Scroggins160a7e72009-08-14 18:28:01 -04001237 /* package */ boolean switchToTab(int index) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001238 Tab tab = mTabControl.getTab(index);
1239 Tab currentTab = mTabControl.getCurrentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04001240 if (tab == null || tab == currentTab) {
Leon Scroggins160a7e72009-08-14 18:28:01 -04001241 return false;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001242 }
1243 if (currentTab != null) {
1244 // currentTab may be null if it was just removed. In that case,
1245 // we do not need to remove it
1246 removeTabFromContentView(currentTab);
1247 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001248 mTabControl.setCurrentTab(tab);
1249 attachTabToContentView(tab);
Grace Klobaeb6eef42009-09-15 17:56:32 -07001250 resetTitleIconAndProgress();
1251 updateLockIconToLatest();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001252 return true;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001253 }
1254
Grace Kloba22ac16e2009-10-07 18:00:23 -07001255 /* package */ Tab openTabToHomePage() {
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001256 return openTabAndShow(mSettings.getHomePage(), false, null);
1257 }
1258
Leon Scroggins1f005d32009-08-10 17:36:42 -04001259 /* package */ void closeCurrentWindow() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001260 final Tab current = mTabControl.getCurrentTab();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001261 if (mTabControl.getTabCount() == 1) {
Leon Scroggins30444232009-09-04 18:36:20 -04001262 // This is the last tab. Open a new one, with the home
1263 // page and close the current one.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001264 openTabToHomePage();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001265 closeTab(current);
Leon Scroggins160a7e72009-08-14 18:28:01 -04001266 return;
1267 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07001268 final Tab parent = current.getParentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04001269 int indexToShow = -1;
1270 if (parent != null) {
1271 indexToShow = mTabControl.getTabIndex(parent);
1272 } else {
Leon Scroggins160a7e72009-08-14 18:28:01 -04001273 final int currentIndex = mTabControl.getCurrentIndex();
1274 // Try to move to the tab to the right
1275 indexToShow = currentIndex + 1;
1276 if (indexToShow > mTabControl.getTabCount() - 1) {
1277 // Try to move to the tab to the left
1278 indexToShow = currentIndex - 1;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001279 }
1280 }
Leon Scroggins160a7e72009-08-14 18:28:01 -04001281 if (switchToTab(indexToShow)) {
1282 // Close window
1283 closeTab(current);
1284 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001285 }
1286
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001287 private ActiveTabsPage mActiveTabsPage;
1288
1289 /**
1290 * Remove the active tabs page.
1291 * @param needToAttach If true, the active tabs page did not attach a tab
1292 * to the content view, so we need to do that here.
1293 */
1294 /* package */ void removeActiveTabPage(boolean needToAttach) {
1295 mContentView.removeView(mActiveTabsPage);
Leon Scrogginsd746a942010-05-19 13:21:44 -04001296 mTitleBar.setVisibility(View.VISIBLE);
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001297 mActiveTabsPage = null;
1298 mMenuState = R.id.MAIN_MENU;
1299 if (needToAttach) {
1300 attachTabToContentView(mTabControl.getCurrentTab());
1301 }
1302 getTopWindow().requestFocus();
1303 }
1304
The Android Open Source Project0c908882009-03-03 19:32:16 -08001305 @Override
1306 public boolean onOptionsItemSelected(MenuItem item) {
1307 if (!mCanChord) {
1308 // The user has already fired a shortcut with this hold down of the
1309 // menu key.
1310 return false;
1311 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001312 if (null == getTopWindow()) {
Leon Scroggins0d7ae0e2009-06-05 11:04:45 -04001313 return false;
1314 }
Grace Kloba6ee9c492009-07-13 10:04:34 -07001315 if (mMenuIsDown) {
1316 // The shortcut action consumes the MENU. Even if it is still down,
1317 // it won't trigger the next shortcut action. In the case of the
1318 // shortcut action triggering a new activity, like Bookmarks, we
1319 // won't get onKeyUp for MENU. So it is important to reset it here.
1320 mMenuIsDown = false;
1321 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001322 switch (item.getItemId()) {
1323 // -- Main menu
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001324 case R.id.new_tab_menu_id:
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001325 openTabToHomePage();
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001326 break;
1327
Leon Scroggins64b80f32009-08-07 12:03:34 -04001328 case R.id.goto_menu_id:
Leon Scroggins8ad29922010-02-16 12:33:55 -05001329 editUrl();
Leon Scrogginsb3a5bed2009-09-28 11:21:56 -04001330 break;
1331
1332 case R.id.bookmarks_menu_id:
Leon Scroggins30444232009-09-04 18:36:20 -04001333 bookmarksOrHistoryPicker(false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001334 break;
1335
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001336 case R.id.active_tabs_menu_id:
1337 mActiveTabsPage = new ActiveTabsPage(this, mTabControl);
1338 removeTabFromContentView(mTabControl.getCurrentTab());
Leon Scrogginsd746a942010-05-19 13:21:44 -04001339 mTitleBar.setVisibility(View.GONE);
Leon Scroggins43de6162009-09-14 19:59:58 -04001340 hideFakeTitleBar();
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001341 mContentView.addView(mActiveTabsPage, COVER_SCREEN_PARAMS);
1342 mActiveTabsPage.requestFocus();
1343 mMenuState = EMPTY_MENU;
1344 break;
1345
Leon Scroggins1f005d32009-08-10 17:36:42 -04001346 case R.id.add_bookmark_menu_id:
Leon Scroggins571b3762010-05-26 10:25:01 -04001347 bookmarkCurrentPage();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001348 break;
1349
1350 case R.id.stop_reload_menu_id:
1351 if (mInLoad) {
1352 stopLoading();
1353 } else {
1354 getTopWindow().reload();
1355 }
1356 break;
1357
1358 case R.id.back_menu_id:
1359 getTopWindow().goBack();
1360 break;
1361
1362 case R.id.forward_menu_id:
1363 getTopWindow().goForward();
1364 break;
1365
1366 case R.id.close_menu_id:
1367 // Close the subwindow if it exists.
1368 if (mTabControl.getCurrentSubWindow() != null) {
1369 dismissSubWindow(mTabControl.getCurrentTab());
1370 break;
1371 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001372 closeCurrentWindow();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001373 break;
1374
1375 case R.id.homepage_menu_id:
Grace Kloba22ac16e2009-10-07 18:00:23 -07001376 Tab current = mTabControl.getCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001377 if (current != null) {
1378 dismissSubWindow(current);
Leon Scroggins92472e82010-02-17 16:32:28 -05001379 loadUrl(current.getWebView(), mSettings.getHomePage());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001380 }
1381 break;
1382
1383 case R.id.preferences_menu_id:
1384 Intent intent = new Intent(this,
1385 BrowserPreferencesPage.class);
Leon Scrogginsd5304942009-12-10 16:11:39 -05001386 intent.putExtra(BrowserPreferencesPage.CURRENT_PAGE,
1387 getTopWindow().getUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001388 startActivityForResult(intent, PREFERENCES_PAGE);
1389 break;
1390
1391 case R.id.find_menu_id:
1392 if (null == mFindDialog) {
1393 mFindDialog = new FindDialog(this);
1394 }
Leon Scroggins III211ba542010-04-19 13:21:13 -04001395 // Need to do something special for Tablet
Leon Scroggins79e36d92010-04-29 16:01:46 +01001396 Tab tab = mTabControl.getCurrentTab();
1397 if (tab.getSubWebView() == null) {
1398 // If the Find is being performed on the main webview,
1399 // remove the embedded title bar.
1400 WebView mainView = tab.getWebView();
1401 if (mainView != null) {
1402 mainView.setEmbeddedTitleBar(null);
1403 }
1404 }
1405 hideFakeTitleBar();
1406 tab.showFind(mFindDialog);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001407 mMenuState = EMPTY_MENU;
1408 break;
1409
1410 case R.id.select_text_id:
1411 getTopWindow().emulateShiftHeld();
1412 break;
1413 case R.id.page_info_menu_id:
1414 showPageInfo(mTabControl.getCurrentTab(), false);
1415 break;
1416
1417 case R.id.classic_history_menu_id:
Leon Scroggins30444232009-09-04 18:36:20 -04001418 bookmarksOrHistoryPicker(true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001419 break;
1420
Leon Scroggins96afcb12009-12-10 12:35:56 -05001421 case R.id.title_bar_share_page_url:
The Android Open Source Project0c908882009-03-03 19:32:16 -08001422 case R.id.share_page_menu_id:
Leon Scroggins96afcb12009-12-10 12:35:56 -05001423 Tab currentTab = mTabControl.getCurrentTab();
1424 if (null == currentTab) {
1425 mCanChord = false;
1426 return false;
1427 }
1428 currentTab.populatePickerData();
1429 sharePage(this, currentTab.getTitle(),
1430 currentTab.getUrl(), currentTab.getFavicon(),
1431 createScreenshot(currentTab.getWebView()));
The Android Open Source Project0c908882009-03-03 19:32:16 -08001432 break;
1433
1434 case R.id.dump_nav_menu_id:
1435 getTopWindow().debugDump();
1436 break;
1437
Andrei Popescu7a8b88b2010-02-02 00:30:38 +00001438 case R.id.dump_counters_menu_id:
1439 getTopWindow().dumpV8Counters();
1440 break;
1441
The Android Open Source Project0c908882009-03-03 19:32:16 -08001442 case R.id.zoom_in_menu_id:
1443 getTopWindow().zoomIn();
1444 break;
1445
1446 case R.id.zoom_out_menu_id:
1447 getTopWindow().zoomOut();
1448 break;
1449
1450 case R.id.view_downloads_menu_id:
1451 viewDownloads(null);
1452 break;
1453
The Android Open Source Project0c908882009-03-03 19:32:16 -08001454 case R.id.window_one_menu_id:
1455 case R.id.window_two_menu_id:
1456 case R.id.window_three_menu_id:
1457 case R.id.window_four_menu_id:
1458 case R.id.window_five_menu_id:
1459 case R.id.window_six_menu_id:
1460 case R.id.window_seven_menu_id:
1461 case R.id.window_eight_menu_id:
1462 {
1463 int menuid = item.getItemId();
1464 for (int id = 0; id < WINDOW_SHORTCUT_ID_ARRAY.length; id++) {
1465 if (WINDOW_SHORTCUT_ID_ARRAY[id] == menuid) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001466 Tab desiredTab = mTabControl.getTab(id);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001467 if (desiredTab != null &&
1468 desiredTab != mTabControl.getCurrentTab()) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001469 switchToTab(id);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001470 }
1471 break;
1472 }
1473 }
1474 }
1475 break;
1476
1477 default:
1478 if (!super.onOptionsItemSelected(item)) {
1479 return false;
1480 }
1481 // Otherwise fall through.
1482 }
1483 mCanChord = false;
1484 return true;
1485 }
1486
Leon Scroggins571b3762010-05-26 10:25:01 -04001487 /* package */ void bookmarkCurrentPage() {
1488 Intent i = new Intent(BrowserActivity.this,
1489 AddBookmarkPage.class);
1490 WebView w = getTopWindow();
1491 i.putExtra("url", w.getUrl());
1492 i.putExtra("title", w.getTitle());
1493 i.putExtra("touch_icon_url", w.getTouchIconUrl());
1494 i.putExtra("thumbnail", createScreenshot(w));
1495 startActivity(i);
1496 }
1497
Leon Scroggins III211ba542010-04-19 13:21:13 -04001498 /*
1499 * Remove the FindDialog.
1500 */
The Android Open Source Project0c908882009-03-03 19:32:16 -08001501 public void closeFind() {
Leon Scroggins79e36d92010-04-29 16:01:46 +01001502 Tab currentTab = mTabControl.getCurrentTab();
Leon Scroggins III211ba542010-04-19 13:21:13 -04001503 if (mFindDialog != null) {
Leon Scroggins79e36d92010-04-29 16:01:46 +01001504 currentTab.closeFind(mFindDialog);
Leon Scroggins III211ba542010-04-19 13:21:13 -04001505 mFindDialog.dismiss();
1506 }
Leon Scrogginsd746a942010-05-19 13:21:44 -04001507 if (!mXLargeScreenSize) {
1508 // If the Find was being performed in the main WebView, replace the
1509 // embedded title bar.
1510 if (currentTab.getSubWebView() == null) {
1511 WebView mainView = currentTab.getWebView();
1512 if (mainView != null) {
1513 mainView.setEmbeddedTitleBar(mTitleBar);
1514 }
Leon Scroggins79e36d92010-04-29 16:01:46 +01001515 }
1516 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001517 mMenuState = R.id.MAIN_MENU;
Leon Scroggins79e36d92010-04-29 16:01:46 +01001518 if (mInLoad) {
1519 // The title bar was hidden, because otherwise it would cover up the
1520 // find dialog. Now that the dialog has been removed, show the fake
1521 // title bar once again.
1522 showFakeTitleBar();
1523 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001524 }
1525
Grace Kloba22ac16e2009-10-07 18:00:23 -07001526 @Override
1527 public boolean onPrepareOptionsMenu(Menu menu) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001528 // This happens when the user begins to hold down the menu key, so
1529 // allow them to chord to get a shortcut.
1530 mCanChord = true;
1531 // Note: setVisible will decide whether an item is visible; while
1532 // setEnabled() will decide whether an item is enabled, which also means
1533 // whether the matching shortcut key will function.
1534 super.onPrepareOptionsMenu(menu);
1535 switch (mMenuState) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001536 case EMPTY_MENU:
1537 if (mCurrentMenuState != mMenuState) {
1538 menu.setGroupVisible(R.id.MAIN_MENU, false);
1539 menu.setGroupEnabled(R.id.MAIN_MENU, false);
1540 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001541 }
1542 break;
1543 default:
1544 if (mCurrentMenuState != mMenuState) {
1545 menu.setGroupVisible(R.id.MAIN_MENU, true);
1546 menu.setGroupEnabled(R.id.MAIN_MENU, true);
1547 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001548 }
1549 final WebView w = getTopWindow();
1550 boolean canGoBack = false;
1551 boolean canGoForward = false;
1552 boolean isHome = false;
1553 if (w != null) {
1554 canGoBack = w.canGoBack();
1555 canGoForward = w.canGoForward();
1556 isHome = mSettings.getHomePage().equals(w.getUrl());
1557 }
1558 final MenuItem back = menu.findItem(R.id.back_menu_id);
1559 back.setEnabled(canGoBack);
1560
1561 final MenuItem home = menu.findItem(R.id.homepage_menu_id);
1562 home.setEnabled(!isHome);
1563
1564 menu.findItem(R.id.forward_menu_id)
1565 .setEnabled(canGoForward);
1566
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001567 menu.findItem(R.id.new_tab_menu_id).setEnabled(
Grace Kloba22ac16e2009-10-07 18:00:23 -07001568 mTabControl.canCreateNewTab());
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001569
The Android Open Source Project0c908882009-03-03 19:32:16 -08001570 // decide whether to show the share link option
1571 PackageManager pm = getPackageManager();
1572 Intent send = new Intent(Intent.ACTION_SEND);
1573 send.setType("text/plain");
1574 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1575 menu.findItem(R.id.share_page_menu_id).setVisible(ri != null);
1576
The Android Open Source Project0c908882009-03-03 19:32:16 -08001577 boolean isNavDump = mSettings.isNavDump();
1578 final MenuItem nav = menu.findItem(R.id.dump_nav_menu_id);
1579 nav.setVisible(isNavDump);
1580 nav.setEnabled(isNavDump);
Andrei Popescu7a8b88b2010-02-02 00:30:38 +00001581
1582 boolean showDebugSettings = mSettings.showDebugSettings();
1583 final MenuItem counter = menu.findItem(R.id.dump_counters_menu_id);
1584 counter.setVisible(showDebugSettings);
1585 counter.setEnabled(showDebugSettings);
1586
The Android Open Source Project0c908882009-03-03 19:32:16 -08001587 break;
1588 }
1589 mCurrentMenuState = mMenuState;
1590 return true;
1591 }
1592
1593 @Override
1594 public void onCreateContextMenu(ContextMenu menu, View v,
1595 ContextMenuInfo menuInfo) {
Leon Scroggins571b3762010-05-26 10:25:01 -04001596 if (v instanceof TitleBarBase) {
Leon Scroggins4e9f89b2010-02-22 16:54:14 -05001597 return;
1598 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001599 WebView webview = (WebView) v;
1600 WebView.HitTestResult result = webview.getHitTestResult();
1601 if (result == null) {
1602 return;
1603 }
1604
1605 int type = result.getType();
1606 if (type == WebView.HitTestResult.UNKNOWN_TYPE) {
1607 Log.w(LOGTAG,
1608 "We should not show context menu when nothing is touched");
1609 return;
1610 }
1611 if (type == WebView.HitTestResult.EDIT_TEXT_TYPE) {
1612 // let TextView handles context menu
1613 return;
1614 }
1615
1616 // Note, http://b/issue?id=1106666 is requesting that
1617 // an inflated menu can be used again. This is not available
1618 // yet, so inflate each time (yuk!)
1619 MenuInflater inflater = getMenuInflater();
1620 inflater.inflate(R.menu.browsercontext, menu);
1621
1622 // Show the correct menu group
Leon Scroggins III9e997c72010-05-26 13:25:16 -04001623 final String extra = result.getExtra();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001624 menu.setGroupVisible(R.id.PHONE_MENU,
1625 type == WebView.HitTestResult.PHONE_TYPE);
1626 menu.setGroupVisible(R.id.EMAIL_MENU,
1627 type == WebView.HitTestResult.EMAIL_TYPE);
1628 menu.setGroupVisible(R.id.GEO_MENU,
1629 type == WebView.HitTestResult.GEO_TYPE);
1630 menu.setGroupVisible(R.id.IMAGE_MENU,
1631 type == WebView.HitTestResult.IMAGE_TYPE
1632 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1633 menu.setGroupVisible(R.id.ANCHOR_MENU,
1634 type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1635 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1636
1637 // Setup custom handling depending on the type
1638 switch (type) {
1639 case WebView.HitTestResult.PHONE_TYPE:
1640 menu.setHeaderTitle(Uri.decode(extra));
1641 menu.findItem(R.id.dial_context_menu_id).setIntent(
1642 new Intent(Intent.ACTION_VIEW, Uri
1643 .parse(WebView.SCHEME_TEL + extra)));
1644 Intent addIntent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
1645 addIntent.putExtra(Insert.PHONE, Uri.decode(extra));
Cary Clark5e335a32009-09-22 14:53:11 -04001646 addIntent.setType(ContactsContract.Contacts.CONTENT_ITEM_TYPE);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001647 menu.findItem(R.id.add_contact_context_menu_id).setIntent(
1648 addIntent);
1649 menu.findItem(R.id.copy_phone_context_menu_id).setOnMenuItemClickListener(
1650 new Copy(extra));
1651 break;
1652
1653 case WebView.HitTestResult.EMAIL_TYPE:
1654 menu.setHeaderTitle(extra);
1655 menu.findItem(R.id.email_context_menu_id).setIntent(
1656 new Intent(Intent.ACTION_VIEW, Uri
1657 .parse(WebView.SCHEME_MAILTO + extra)));
1658 menu.findItem(R.id.copy_mail_context_menu_id).setOnMenuItemClickListener(
1659 new Copy(extra));
1660 break;
1661
1662 case WebView.HitTestResult.GEO_TYPE:
1663 menu.setHeaderTitle(extra);
1664 menu.findItem(R.id.map_context_menu_id).setIntent(
1665 new Intent(Intent.ACTION_VIEW, Uri
1666 .parse(WebView.SCHEME_GEO
1667 + URLEncoder.encode(extra))));
1668 menu.findItem(R.id.copy_geo_context_menu_id).setOnMenuItemClickListener(
1669 new Copy(extra));
1670 break;
1671
1672 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1673 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
1674 TextView titleView = (TextView) LayoutInflater.from(this)
1675 .inflate(android.R.layout.browser_link_context_header,
1676 null);
1677 titleView.setText(extra);
1678 menu.setHeaderView(titleView);
1679 // decide whether to show the open link in new tab option
Leon Scroggins III9e997c72010-05-26 13:25:16 -04001680 boolean showNewTab = mTabControl.canCreateNewTab();
1681 MenuItem newTabItem
1682 = menu.findItem(R.id.open_newtab_context_menu_id);
1683 newTabItem.setVisible(showNewTab);
1684 if (showNewTab) {
1685 newTabItem.setOnMenuItemClickListener(
1686 new MenuItem.OnMenuItemClickListener() {
1687 public boolean onMenuItemClick(MenuItem item) {
1688 final Tab parent = mTabControl.getCurrentTab();
1689 final Tab newTab = openTab(extra);
1690 if (newTab != parent) {
1691 parent.addChildTab(newTab);
1692 }
1693 return true;
1694 }
1695 });
1696 }
Ben Murdochde353622009-10-12 10:29:00 +01001697 menu.findItem(R.id.bookmark_context_menu_id).setVisible(
1698 Bookmarks.urlHasAcceptableScheme(extra));
The Android Open Source Project0c908882009-03-03 19:32:16 -08001699 PackageManager pm = getPackageManager();
1700 Intent send = new Intent(Intent.ACTION_SEND);
1701 send.setType("text/plain");
1702 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1703 menu.findItem(R.id.share_link_context_menu_id).setVisible(ri != null);
1704 if (type == WebView.HitTestResult.SRC_ANCHOR_TYPE) {
1705 break;
1706 }
1707 // otherwise fall through to handle image part
1708 case WebView.HitTestResult.IMAGE_TYPE:
1709 if (type == WebView.HitTestResult.IMAGE_TYPE) {
1710 menu.setHeaderTitle(extra);
1711 }
1712 menu.findItem(R.id.view_image_context_menu_id).setIntent(
1713 new Intent(Intent.ACTION_VIEW, Uri.parse(extra)));
1714 menu.findItem(R.id.download_context_menu_id).
1715 setOnMenuItemClickListener(new Download(extra));
Ben Murdoch4f75ba22009-10-27 11:48:28 +00001716 menu.findItem(R.id.set_wallpaper_context_menu_id).
1717 setOnMenuItemClickListener(new SetAsWallpaper(extra));
The Android Open Source Project0c908882009-03-03 19:32:16 -08001718 break;
1719
1720 default:
1721 Log.w(LOGTAG, "We should not get here.");
1722 break;
1723 }
Leon Scrogginsb2b19f52009-10-09 16:10:00 -04001724 hideFakeTitleBar();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001725 }
1726
The Android Open Source Project0c908882009-03-03 19:32:16 -08001727 // Attach the given tab to the content view.
Grace Klobac928c302009-09-17 11:51:21 -07001728 // this should only be called for the current tab.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001729 private void attachTabToContentView(Tab t) {
Steve Block2bc69912009-07-30 14:45:13 +01001730 // Attach the container that contains the main WebView and any other UI
1731 // associated with the tab.
Patrick Scottd0119532009-09-17 08:00:31 -04001732 t.attachTabToContentView(mContentView);
Ben Murdochbff2d602009-07-01 20:19:05 +01001733
1734 if (mShouldShowErrorConsole) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001735 ErrorConsoleView errorConsole = t.getErrorConsole(true);
Ben Murdochbff2d602009-07-01 20:19:05 +01001736 if (errorConsole.numberOfErrors() == 0) {
1737 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
1738 } else {
1739 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
1740 }
1741
1742 mErrorConsoleContainer.addView(errorConsole,
Romain Guy15b8ec62010-01-08 15:06:43 -08001743 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
Ben Murdochbff2d602009-07-01 20:19:05 +01001744 ViewGroup.LayoutParams.WRAP_CONTENT));
1745 }
1746
Leon Scrogginsd746a942010-05-19 13:21:44 -04001747 if (!mXLargeScreenSize){
1748 WebView view = t.getWebView();
1749 view.setEmbeddedTitleBar(mTitleBar);
1750 }
Leon Scroggins58d56c62010-01-28 15:12:40 -05001751 if (t.isInVoiceSearchMode()) {
1752 showVoiceTitleBar(t.getVoiceDisplayTitle());
1753 } else {
1754 revertVoiceTitleBar();
1755 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001756 // Request focus on the top window.
1757 t.getTopWindow().requestFocus();
1758 }
1759
1760 // Attach a sub window to the main WebView of the given tab.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001761 void attachSubWindow(Tab t) {
Patrick Scottd0119532009-09-17 08:00:31 -04001762 t.attachSubWindow(mContentView);
1763 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001764 }
1765
1766 // Remove the given tab from the content view.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001767 private void removeTabFromContentView(Tab t) {
Steve Block2bc69912009-07-30 14:45:13 +01001768 // Remove the container that contains the main WebView.
Patrick Scottd0119532009-09-17 08:00:31 -04001769 t.removeTabFromContentView(mContentView);
Ben Murdochbff2d602009-07-01 20:19:05 +01001770
Grace Kloba22ac16e2009-10-07 18:00:23 -07001771 ErrorConsoleView errorConsole = t.getErrorConsole(false);
1772 if (errorConsole != null) {
1773 mErrorConsoleContainer.removeView(errorConsole);
Ben Murdochbff2d602009-07-01 20:19:05 +01001774 }
1775
Leon Scrogginsd746a942010-05-19 13:21:44 -04001776 if (!mXLargeScreenSize) {
1777 WebView view = t.getWebView();
1778 if (view != null) {
1779 view.setEmbeddedTitleBar(null);
1780 }
Leon Scrogginsbb85b902009-09-14 19:27:20 -04001781 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001782 }
1783
1784 // Remove the sub window if it exists. Also called by TabControl when the
1785 // user clicks the 'X' to dismiss a sub window.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001786 /* package */ void dismissSubWindow(Tab t) {
Patrick Scottd0119532009-09-17 08:00:31 -04001787 t.removeSubWindow(mContentView);
Grace Kloba22ac16e2009-10-07 18:00:23 -07001788 // dismiss the subwindow. This will destroy the WebView.
1789 t.dismissSubWindow();
Patrick Scottd0119532009-09-17 08:00:31 -04001790 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001791 }
1792
Leon Scroggins1f005d32009-08-10 17:36:42 -04001793 // A wrapper function of {@link #openTabAndShow(UrlData, boolean, String)}
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07001794 // that accepts url as string.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001795 private Tab openTabAndShow(String url, boolean closeOnExit, String appId) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001796 return openTabAndShow(new UrlData(url), closeOnExit, appId);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001797 }
1798
1799 // This method does a ton of stuff. It will attempt to create a new tab
1800 // if we haven't reached MAX_TABS. Otherwise it uses the current tab. If
Leon Scroggins1f005d32009-08-10 17:36:42 -04001801 // url isn't null, it will load the given url.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001802 /* package */Tab openTabAndShow(UrlData urlData, boolean closeOnExit,
1803 String appId) {
1804 final Tab currentTab = mTabControl.getCurrentTab();
1805 if (mTabControl.canCreateNewTab()) {
1806 final Tab tab = mTabControl.createNewTab(closeOnExit, appId,
1807 urlData.mUrl);
Leon Scroggins1f005d32009-08-10 17:36:42 -04001808 WebView webview = tab.getWebView();
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001809 // If the last tab was removed from the active tabs page, currentTab
1810 // will be null.
1811 if (currentTab != null) {
1812 removeTabFromContentView(currentTab);
1813 }
Patrick Scott8bbd69f2009-08-14 13:35:53 -04001814 // We must set the new tab as the current tab to reflect the old
1815 // animation behavior.
1816 mTabControl.setCurrentTab(tab);
Grace Klobaeb6eef42009-09-15 17:56:32 -07001817 attachTabToContentView(tab);
Leon Scroggins160a7e72009-08-14 18:28:01 -04001818 if (!urlData.isEmpty()) {
Patrick Scott9d53da02010-02-19 10:19:01 -05001819 loadUrlDataIn(tab, urlData);
Leon Scroggins1f005d32009-08-10 17:36:42 -04001820 }
1821 return tab;
1822 } else {
1823 // Get rid of the subwindow if it exists
1824 dismissSubWindow(currentTab);
1825 if (!urlData.isEmpty()) {
1826 // Load the given url.
Patrick Scott9d53da02010-02-19 10:19:01 -05001827 loadUrlDataIn(currentTab, urlData);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001828 }
Leon Scroggins58d56c62010-01-28 15:12:40 -05001829 return currentTab;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001830 }
1831 }
1832
Grace Kloba22ac16e2009-10-07 18:00:23 -07001833 private Tab openTab(String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001834 if (mSettings.openInBackground()) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001835 Tab t = mTabControl.createNewTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001836 if (t != null) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001837 WebView view = t.getWebView();
Leon Scroggins92472e82010-02-17 16:32:28 -05001838 loadUrl(view, url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001839 }
Grace Klobac9181842009-04-14 08:53:22 -07001840 return t;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001841 } else {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001842 return openTabAndShow(url, false, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001843 }
1844 }
1845
1846 private class Copy implements OnMenuItemClickListener {
1847 private CharSequence mText;
1848
1849 public boolean onMenuItemClick(MenuItem item) {
1850 copy(mText);
1851 return true;
1852 }
1853
1854 public Copy(CharSequence toCopy) {
1855 mText = toCopy;
1856 }
1857 }
1858
1859 private class Download implements OnMenuItemClickListener {
1860 private String mText;
1861
1862 public boolean onMenuItemClick(MenuItem item) {
1863 onDownloadStartNoStream(mText, null, null, null, -1);
1864 return true;
1865 }
1866
1867 public Download(String toDownload) {
1868 mText = toDownload;
1869 }
1870 }
1871
Ben Murdoch4f75ba22009-10-27 11:48:28 +00001872 private class SetAsWallpaper extends Thread implements
1873 OnMenuItemClickListener, DialogInterface.OnCancelListener {
1874 private URL mUrl;
1875 private ProgressDialog mWallpaperProgress;
1876 private boolean mCanceled = false;
1877
1878 public SetAsWallpaper(String url) {
1879 try {
1880 mUrl = new URL(url);
1881 } catch (MalformedURLException e) {
1882 mUrl = null;
1883 }
1884 }
1885
1886 public void onCancel(DialogInterface dialog) {
1887 mCanceled = true;
1888 }
1889
1890 public boolean onMenuItemClick(MenuItem item) {
1891 if (mUrl != null) {
1892 // The user may have tried to set a image with a large file size as their
1893 // background so it may take a few moments to perform the operation. Display
1894 // a progress spinner while it is working.
1895 mWallpaperProgress = new ProgressDialog(BrowserActivity.this);
1896 mWallpaperProgress.setIndeterminate(true);
1897 mWallpaperProgress.setMessage(getText(R.string.progress_dialog_setting_wallpaper));
1898 mWallpaperProgress.setCancelable(true);
1899 mWallpaperProgress.setOnCancelListener(this);
1900 mWallpaperProgress.show();
1901 start();
1902 }
1903 return true;
1904 }
1905
1906 public void run() {
1907 Drawable oldWallpaper = BrowserActivity.this.getWallpaper();
1908 try {
1909 // TODO: This will cause the resource to be downloaded again, when we
1910 // should in most cases be able to grab it from the cache. To fix this
1911 // we should query WebCore to see if we can access a cached version and
1912 // instead open an input stream on that. This pattern could also be used
1913 // in the download manager where the same problem exists.
1914 InputStream inputstream = mUrl.openStream();
1915 if (inputstream != null) {
1916 setWallpaper(inputstream);
1917 }
1918 } catch (IOException e) {
1919 Log.e(LOGTAG, "Unable to set new wallpaper");
1920 // Act as though the user canceled the operation so we try to
1921 // restore the old wallpaper.
1922 mCanceled = true;
1923 }
1924
1925 if (mCanceled) {
1926 // Restore the old wallpaper if the user cancelled whilst we were setting
1927 // the new wallpaper.
1928 int width = oldWallpaper.getIntrinsicWidth();
1929 int height = oldWallpaper.getIntrinsicHeight();
1930 Bitmap bm = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
1931 Canvas canvas = new Canvas(bm);
1932 oldWallpaper.setBounds(0, 0, width, height);
1933 oldWallpaper.draw(canvas);
1934 try {
1935 setWallpaper(bm);
1936 } catch (IOException e) {
1937 Log.e(LOGTAG, "Unable to restore old wallpaper.");
1938 }
1939 mCanceled = false;
1940 }
1941
1942 if (mWallpaperProgress.isShowing()) {
1943 mWallpaperProgress.dismiss();
1944 }
1945 }
1946 }
1947
The Android Open Source Project0c908882009-03-03 19:32:16 -08001948 private void copy(CharSequence text) {
1949 try {
1950 IClipboard clip = IClipboard.Stub.asInterface(ServiceManager.getService("clipboard"));
1951 if (clip != null) {
1952 clip.setClipboardText(text);
1953 }
1954 } catch (android.os.RemoteException e) {
1955 Log.e(LOGTAG, "Copy failed", e);
1956 }
1957 }
1958
1959 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08001960 * Resets the browser title-view to whatever it must be
1961 * (for example, if we had a loading error)
1962 * When we have a new page, we call resetTitle, when we
1963 * have to reset the titlebar to whatever it used to be
1964 * (for example, if the user chose to stop loading), we
1965 * call resetTitleAndRevertLockIcon.
1966 */
1967 /* package */ void resetTitleAndRevertLockIcon() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001968 mTabControl.getCurrentTab().revertLockIcon();
1969 updateLockIconToLatest();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001970 resetTitleIconAndProgress();
1971 }
1972
1973 /**
1974 * Reset the title, favicon, and progress.
1975 */
1976 private void resetTitleIconAndProgress() {
1977 WebView current = mTabControl.getCurrentWebView();
1978 if (current == null) {
1979 return;
1980 }
1981 resetTitleAndIcon(current);
1982 int progress = current.getProgress();
Grace Kloba22ac16e2009-10-07 18:00:23 -07001983 current.getWebChromeClient().onProgressChanged(current, progress);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001984 }
1985
1986 // Reset the title and the icon based on the given item.
1987 private void resetTitleAndIcon(WebView view) {
1988 WebHistoryItem item = view.copyBackForwardList().getCurrentItem();
1989 if (item != null) {
Leon Scroggins68579392009-09-15 15:31:54 -04001990 setUrlTitle(item.getUrl(), item.getTitle());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001991 setFavicon(item.getFavicon());
1992 } else {
Leon Scroggins68579392009-09-15 15:31:54 -04001993 setUrlTitle(null, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001994 setFavicon(null);
1995 }
1996 }
1997
1998 /**
1999 * Sets a title composed of the URL and the title string.
2000 * @param url The URL of the site being loaded.
2001 * @param title The title of the site being loaded.
2002 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07002003 void setUrlTitle(String url, String title) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002004 mUrl = url;
2005 mTitle = title;
2006
Leon Scroggins58d56c62010-01-28 15:12:40 -05002007 // If we are in voice search mode, the title has already been set.
2008 if (mTabControl.getCurrentTab().isInVoiceSearchMode()) return;
2009 mTitleBar.setDisplayTitle(url);
Leon Scrogginsd746a942010-05-19 13:21:44 -04002010 if (!mXLargeScreenSize) {
2011 mFakeTitleBar.setDisplayTitle(url);
2012 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002013 }
2014
2015 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08002016 * @param url The URL to build a title version of the URL from.
2017 * @return The title version of the URL or null if fails.
2018 * The title version of the URL can be either the URL hostname,
2019 * or the hostname with an "https://" prefix (for secure URLs),
2020 * or an empty string if, for example, the URL in question is a
2021 * file:// URL with no hostname.
2022 */
Leon Scroggins32e14a62009-06-11 10:26:34 -04002023 /* package */ static String buildTitleUrl(String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002024 String titleUrl = null;
2025
2026 if (url != null) {
2027 try {
2028 // parse the url string
2029 URL urlObj = new URL(url);
2030 if (urlObj != null) {
2031 titleUrl = "";
2032
2033 String protocol = urlObj.getProtocol();
2034 String host = urlObj.getHost();
2035
2036 if (host != null && 0 < host.length()) {
2037 titleUrl = host;
2038 if (protocol != null) {
2039 // if a secure site, add an "https://" prefix!
2040 if (protocol.equalsIgnoreCase("https")) {
2041 titleUrl = protocol + "://" + host;
2042 }
2043 }
2044 }
2045 }
2046 } catch (MalformedURLException e) {}
2047 }
2048
2049 return titleUrl;
2050 }
2051
2052 // Set the favicon in the title bar.
Grace Kloba22ac16e2009-10-07 18:00:23 -07002053 void setFavicon(Bitmap icon) {
Leon Scroggins68579392009-09-15 15:31:54 -04002054 mTitleBar.setFavicon(icon);
Leon Scrogginsd746a942010-05-19 13:21:44 -04002055 if (!mXLargeScreenSize) {
2056 mFakeTitleBar.setFavicon(icon);
2057 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002058 }
2059
2060 /**
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002061 * Close the tab, remove its associated title bar, and adjust mTabControl's
2062 * current tab to a valid value.
Leon Scroggins1f005d32009-08-10 17:36:42 -04002063 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07002064 /* package */ void closeTab(Tab t) {
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002065 int currentIndex = mTabControl.getCurrentIndex();
2066 int removeIndex = mTabControl.getTabIndex(t);
Leon Scroggins1f005d32009-08-10 17:36:42 -04002067 mTabControl.removeTab(t);
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002068 if (currentIndex >= removeIndex && currentIndex != 0) {
2069 currentIndex--;
2070 }
2071 mTabControl.setCurrentTab(mTabControl.getTab(currentIndex));
Andrei Popescua5bf1de2009-09-23 16:39:23 +01002072 resetTitleIconAndProgress();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002073 }
2074
Leon Scrogginsdcc5eeb2010-02-23 17:26:37 -05002075 /* package */ void goBackOnePageOrQuit() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002076 Tab current = mTabControl.getCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002077 if (current == null) {
2078 /*
2079 * Instead of finishing the activity, simply push this to the back
2080 * of the stack and let ActivityManager to choose the foreground
2081 * activity. As BrowserActivity is singleTask, it will be always the
2082 * root of the task. So we can use either true or false for
2083 * moveTaskToBack().
2084 */
2085 moveTaskToBack(true);
Grace Kloba00d85e72009-09-23 18:50:05 -07002086 return;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002087 }
2088 WebView w = current.getWebView();
2089 if (w.canGoBack()) {
2090 w.goBack();
2091 } else {
2092 // Check to see if we are closing a window that was created by
2093 // another window. If so, we switch back to that window.
Grace Kloba22ac16e2009-10-07 18:00:23 -07002094 Tab parent = current.getParentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002095 if (parent != null) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04002096 switchToTab(mTabControl.getTabIndex(parent));
2097 // Now we close the other tab
2098 closeTab(current);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002099 } else {
2100 if (current.closeOnExit()) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002101 // force the tab's inLoad() to be false as we are going to
2102 // either finish the activity or remove the tab. This will
2103 // ensure pauseWebViewTimers() taking action.
2104 mTabControl.getCurrentTab().clearInLoad();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002105 if (mTabControl.getTabCount() == 1) {
2106 finish();
2107 return;
2108 }
Mike Reed7bfa63b2009-05-28 11:08:32 -04002109 // call pauseWebViewTimers() now, we won't be able to call
2110 // it in onPause() as the WebView won't be valid.
Grace Klobaec1b5ad2009-08-18 08:42:32 -07002111 // Temporarily change mActivityInPause to be true as
2112 // pauseWebViewTimers() will do nothing if mActivityInPause
2113 // is false.
Grace Kloba918e1d72009-08-13 14:55:06 -07002114 boolean savedState = mActivityInPause;
2115 if (savedState) {
Grace Klobaec1b5ad2009-08-18 08:42:32 -07002116 Log.e(LOGTAG, "BrowserActivity is already paused "
2117 + "while handing goBackOnePageOrQuit.");
Grace Kloba918e1d72009-08-13 14:55:06 -07002118 }
2119 mActivityInPause = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -04002120 pauseWebViewTimers();
Grace Kloba918e1d72009-08-13 14:55:06 -07002121 mActivityInPause = savedState;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002122 removeTabFromContentView(current);
2123 mTabControl.removeTab(current);
2124 }
2125 /*
2126 * Instead of finishing the activity, simply push this to the back
2127 * of the stack and let ActivityManager to choose the foreground
2128 * activity. As BrowserActivity is singleTask, it will be always the
2129 * root of the task. So we can use either true or false for
2130 * moveTaskToBack().
2131 */
2132 moveTaskToBack(true);
2133 }
2134 }
2135 }
2136
Grace Kloba22ac16e2009-10-07 18:00:23 -07002137 boolean isMenuDown() {
2138 return mMenuIsDown;
2139 }
2140
Grace Kloba5942df02009-09-18 11:48:29 -07002141 @Override
2142 public boolean onKeyDown(int keyCode, KeyEvent event) {
Leon Scrogginsf65b50d2009-12-08 10:44:28 -05002143 // Even if MENU is already held down, we need to call to super to open
2144 // the IME on long press.
2145 if (KeyEvent.KEYCODE_MENU == keyCode) {
2146 mMenuIsDown = true;
2147 return super.onKeyDown(keyCode, event);
2148 }
Grace Kloba5942df02009-09-18 11:48:29 -07002149 // The default key mode is DEFAULT_KEYS_SEARCH_LOCAL. As the MENU is
2150 // still down, we don't want to trigger the search. Pretend to consume
2151 // the key and do nothing.
2152 if (mMenuIsDown) return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002153
Grace Kloba5942df02009-09-18 11:48:29 -07002154 switch(keyCode) {
Grace Kloba5942df02009-09-18 11:48:29 -07002155 case KeyEvent.KEYCODE_SPACE:
Grace Klobada0fe552009-09-22 18:17:24 -07002156 // WebView/WebTextView handle the keys in the KeyDown. As
2157 // the Activity's shortcut keys are only handled when WebView
2158 // doesn't, have to do it in onKeyDown instead of onKeyUp.
2159 if (event.isShiftPressed()) {
2160 getTopWindow().pageUp(false);
2161 } else {
2162 getTopWindow().pageDown(false);
2163 }
Grace Kloba5942df02009-09-18 11:48:29 -07002164 return true;
2165 case KeyEvent.KEYCODE_BACK:
2166 if (event.getRepeatCount() == 0) {
2167 event.startTracking();
2168 return true;
2169 } else if (mCustomView == null && mActiveTabsPage == null
2170 && event.isLongPress()) {
2171 bookmarksOrHistoryPicker(true);
2172 return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002173 }
Grace Kloba5942df02009-09-18 11:48:29 -07002174 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002175 }
Grace Kloba5942df02009-09-18 11:48:29 -07002176 return super.onKeyDown(keyCode, event);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002177 }
2178
Grace Kloba5942df02009-09-18 11:48:29 -07002179 @Override
2180 public boolean onKeyUp(int keyCode, KeyEvent event) {
2181 switch(keyCode) {
2182 case KeyEvent.KEYCODE_MENU:
2183 mMenuIsDown = false;
2184 break;
Grace Kloba5942df02009-09-18 11:48:29 -07002185 case KeyEvent.KEYCODE_BACK:
2186 if (event.isTracking() && !event.isCanceled()) {
2187 if (mCustomView != null) {
2188 // if a custom view is showing, hide it
Grace Kloba22ac16e2009-10-07 18:00:23 -07002189 mTabControl.getCurrentWebView().getWebChromeClient()
2190 .onHideCustomView();
Grace Kloba5942df02009-09-18 11:48:29 -07002191 } else if (mActiveTabsPage != null) {
2192 // if tab page is showing, hide it
2193 removeActiveTabPage(true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002194 } else {
Grace Kloba5942df02009-09-18 11:48:29 -07002195 WebView subwindow = mTabControl.getCurrentSubWindow();
2196 if (subwindow != null) {
2197 if (subwindow.canGoBack()) {
2198 subwindow.goBack();
2199 } else {
2200 dismissSubWindow(mTabControl.getCurrentTab());
2201 }
2202 } else {
2203 goBackOnePageOrQuit();
2204 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002205 }
Grace Kloba5942df02009-09-18 11:48:29 -07002206 return true;
2207 }
2208 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002209 }
Grace Kloba5942df02009-09-18 11:48:29 -07002210 return super.onKeyUp(keyCode, event);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002211 }
2212
Leon Scroggins68579392009-09-15 15:31:54 -04002213 /* package */ void stopLoading() {
Ben Murdochb7cc8b42009-09-28 10:59:09 +01002214 mDidStopLoad = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002215 resetTitleAndRevertLockIcon();
2216 WebView w = getTopWindow();
2217 w.stopLoading();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002218 // FIXME: before refactor, it is using mWebViewClient. So I keep the
2219 // same logic here. But for subwindow case, should we call into the main
2220 // WebView's onPageFinished as we never call its onPageStarted and if
2221 // the page finishes itself, we don't call onPageFinished.
2222 mTabControl.getCurrentWebView().getWebViewClient().onPageFinished(w,
2223 w.getUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08002224
2225 cancelStopToast();
2226 mStopToast = Toast
2227 .makeText(this, R.string.stopping, Toast.LENGTH_SHORT);
2228 mStopToast.show();
2229 }
2230
Grace Kloba22ac16e2009-10-07 18:00:23 -07002231 boolean didUserStopLoading() {
2232 return mDidStopLoad;
2233 }
2234
The Android Open Source Project0c908882009-03-03 19:32:16 -08002235 private void cancelStopToast() {
2236 if (mStopToast != null) {
2237 mStopToast.cancel();
2238 mStopToast = null;
2239 }
2240 }
2241
Grace Kloba22ac16e2009-10-07 18:00:23 -07002242 // called by a UI or non-UI thread to post the message
2243 public void postMessage(int what, int arg1, int arg2, Object obj,
2244 long delayMillis) {
2245 mHandler.sendMessageDelayed(mHandler.obtainMessage(what, arg1, arg2,
2246 obj), delayMillis);
2247 }
2248
2249 // called by a UI or non-UI thread to remove the message
2250 void removeMessages(int what, Object object) {
2251 mHandler.removeMessages(what, object);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002252 }
2253
2254 // public message ids
2255 public final static int LOAD_URL = 1001;
2256 public final static int STOP_LOAD = 1002;
2257
2258 // Message Ids
2259 private static final int FOCUS_NODE_HREF = 102;
Grace Kloba92c18a52009-07-31 23:48:32 -07002260 private static final int RELEASE_WAKELOCK = 107;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002261
Grace Kloba22ac16e2009-10-07 18:00:23 -07002262 static final int UPDATE_BOOKMARK_THUMBNAIL = 108;
Ben Murdoch2694e232009-09-29 09:41:11 +01002263
The Android Open Source Project0c908882009-03-03 19:32:16 -08002264 // Private handler for handling javascript and saving passwords
2265 private Handler mHandler = new Handler() {
2266
2267 public void handleMessage(Message msg) {
2268 switch (msg.what) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002269 case FOCUS_NODE_HREF:
Ben Murdoch2694e232009-09-29 09:41:11 +01002270 {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002271 String url = (String) msg.getData().get("url");
Ben Murdoch90d088c2009-11-17 18:14:04 +00002272 String title = (String) msg.getData().get("title");
The Android Open Source Project0c908882009-03-03 19:32:16 -08002273 if (url == null || url.length() == 0) {
2274 break;
2275 }
2276 HashMap focusNodeMap = (HashMap) msg.obj;
2277 WebView view = (WebView) focusNodeMap.get("webview");
2278 // Only apply the action if the top window did not change.
2279 if (getTopWindow() != view) {
2280 break;
2281 }
2282 switch (msg.arg1) {
2283 case R.id.open_context_menu_id:
2284 case R.id.view_image_context_menu_id:
Leon Scroggins92472e82010-02-17 16:32:28 -05002285 loadUrlFromContext(getTopWindow(), url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002286 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002287 case R.id.bookmark_context_menu_id:
2288 Intent intent = new Intent(BrowserActivity.this,
2289 AddBookmarkPage.class);
2290 intent.putExtra("url", url);
Ben Murdoch90d088c2009-11-17 18:14:04 +00002291 intent.putExtra("title", title);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002292 startActivity(intent);
2293 break;
2294 case R.id.share_link_context_menu_id:
Leon Scroggins3e204452010-05-10 11:06:03 -04002295 sharePage(BrowserActivity.this, title, url, null,
Leon Scroggins96afcb12009-12-10 12:35:56 -05002296 null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002297 break;
2298 case R.id.copy_link_context_menu_id:
2299 copy(url);
2300 break;
2301 case R.id.save_link_context_menu_id:
2302 case R.id.download_context_menu_id:
2303 onDownloadStartNoStream(url, null, null, null, -1);
2304 break;
2305 }
2306 break;
Ben Murdoch2694e232009-09-29 09:41:11 +01002307 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002308
2309 case LOAD_URL:
Leon Scroggins92472e82010-02-17 16:32:28 -05002310 loadUrlFromContext(getTopWindow(), (String) msg.obj);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002311 break;
2312
2313 case STOP_LOAD:
2314 stopLoading();
2315 break;
2316
The Android Open Source Project0c908882009-03-03 19:32:16 -08002317 case RELEASE_WAKELOCK:
2318 if (mWakeLock.isHeld()) {
2319 mWakeLock.release();
Grace Kloba5d0e02e2009-10-05 15:15:36 -07002320 // if we reach here, Browser should be still in the
2321 // background loading after WAKELOCK_TIMEOUT (5-min).
2322 // To avoid burning the battery, stop loading.
2323 mTabControl.stopAllLoading();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002324 }
2325 break;
Ben Murdoch2694e232009-09-29 09:41:11 +01002326
2327 case UPDATE_BOOKMARK_THUMBNAIL:
2328 WebView view = (WebView) msg.obj;
2329 if (view != null) {
2330 updateScreenshot(view);
2331 }
2332 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002333 }
2334 }
2335 };
2336
Leon Scroggins96afcb12009-12-10 12:35:56 -05002337 /**
2338 * Share a page, providing the title, url, favicon, and a screenshot. Uses
2339 * an {@link Intent} to launch the Activity chooser.
2340 * @param c Context used to launch a new Activity.
2341 * @param title Title of the page. Stored in the Intent with
Paul Westbrook03e6d392010-02-12 10:33:29 -08002342 * {@link Intent#EXTRA_SUBJECT}
Leon Scroggins96afcb12009-12-10 12:35:56 -05002343 * @param url URL of the page. Stored in the Intent with
2344 * {@link Intent#EXTRA_TEXT}
2345 * @param favicon Bitmap of the favicon for the page. Stored in the Intent
2346 * with {@link Browser#EXTRA_SHARE_FAVICON}
2347 * @param screenshot Bitmap of a screenshot of the page. Stored in the
2348 * Intent with {@link Browser#EXTRA_SHARE_SCREENSHOT}
2349 */
2350 public static final void sharePage(Context c, String title, String url,
2351 Bitmap favicon, Bitmap screenshot) {
2352 Intent send = new Intent(Intent.ACTION_SEND);
2353 send.setType("text/plain");
2354 send.putExtra(Intent.EXTRA_TEXT, url);
Paul Westbrook03e6d392010-02-12 10:33:29 -08002355 send.putExtra(Intent.EXTRA_SUBJECT, title);
Leon Scroggins96afcb12009-12-10 12:35:56 -05002356 send.putExtra(Browser.EXTRA_SHARE_FAVICON, favicon);
2357 send.putExtra(Browser.EXTRA_SHARE_SCREENSHOT, screenshot);
2358 try {
2359 c.startActivity(Intent.createChooser(send, c.getString(
2360 R.string.choosertitle_sharevia)));
2361 } catch(android.content.ActivityNotFoundException ex) {
2362 // if no app handles it, do nothing
2363 }
2364 }
2365
Leon Scroggins89c6d362009-07-15 16:54:37 -04002366 private void updateScreenshot(WebView view) {
2367 // If this is a bookmarked site, add a screenshot to the database.
2368 // FIXME: When should we update? Every time?
2369 // FIXME: Would like to make sure there is actually something to
2370 // draw, but the API for that (WebViewCore.pictureReady()) is not
2371 // currently accessible here.
Ben Murdochaac7aa62009-09-17 16:57:40 +01002372
Patrick Scottcb192b52010-04-14 14:38:55 -04002373 final Bitmap bm = createScreenshot(view);
2374 if (bm == null) {
2375 return;
Leon Scroggins89c6d362009-07-15 16:54:37 -04002376 }
Patrick Scottcb192b52010-04-14 14:38:55 -04002377
2378 final ContentResolver cr = getContentResolver();
2379 final String url = view.getUrl();
2380 final String originalUrl = view.getOriginalUrl();
2381
2382 new AsyncTask<Void, Void, Void>() {
2383 @Override
2384 protected Void doInBackground(Void... unused) {
2385 Cursor c = null;
2386 try {
2387 c = BrowserBookmarksAdapter.queryBookmarksForUrl(
2388 cr, originalUrl, url, true);
2389 if (c != null) {
2390 if (c.moveToFirst()) {
2391 ContentValues values = new ContentValues();
2392 final ByteArrayOutputStream os
2393 = new ByteArrayOutputStream();
2394 bm.compress(Bitmap.CompressFormat.PNG, 100, os);
2395 values.put(Browser.BookmarkColumns.THUMBNAIL,
2396 os.toByteArray());
2397 do {
2398 cr.update(ContentUris.withAppendedId(
2399 Browser.BOOKMARKS_URI, c.getInt(0)),
2400 values, null, null);
2401 } while (c.moveToNext());
2402 }
2403 }
2404 } catch (IllegalStateException e) {
2405 // Ignore
2406 } finally {
2407 if (c != null) c.close();
2408 }
2409 return null;
2410 }
2411 }.execute();
Leon Scroggins89c6d362009-07-15 16:54:37 -04002412 }
2413
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002414 /**
Leon Scrogginsf8551612009-09-24 16:06:02 -04002415 * Values for the size of the thumbnail created when taking a screenshot.
2416 * Lazily initialized. Instead of using these directly, use
2417 * getDesiredThumbnailWidth() or getDesiredThumbnailHeight().
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002418 */
Leon Scrogginsf8551612009-09-24 16:06:02 -04002419 private static int THUMBNAIL_WIDTH = 0;
2420 private static int THUMBNAIL_HEIGHT = 0;
2421
2422 /**
2423 * Return the desired width for thumbnail screenshots, which are stored in
2424 * the database, and used on the bookmarks screen.
2425 * @param context Context for finding out the density of the screen.
2426 * @return int desired width for thumbnail screenshot.
2427 */
2428 /* package */ static int getDesiredThumbnailWidth(Context context) {
2429 if (THUMBNAIL_WIDTH == 0) {
2430 float density = context.getResources().getDisplayMetrics().density;
2431 THUMBNAIL_WIDTH = (int) (90 * density);
2432 THUMBNAIL_HEIGHT = (int) (80 * density);
2433 }
2434 return THUMBNAIL_WIDTH;
2435 }
2436
2437 /**
2438 * Return the desired height for thumbnail screenshots, which are stored in
2439 * the database, and used on the bookmarks screen.
2440 * @param context Context for finding out the density of the screen.
2441 * @return int desired height for thumbnail screenshot.
2442 */
2443 /* package */ static int getDesiredThumbnailHeight(Context context) {
2444 // To ensure that they are both initialized.
2445 getDesiredThumbnailWidth(context);
2446 return THUMBNAIL_HEIGHT;
2447 }
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002448
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002449 private Bitmap createScreenshot(WebView view) {
2450 Picture thumbnail = view.capturePicture();
Leon Scroggins45800572009-09-29 16:38:47 -04002451 if (thumbnail == null) {
2452 return null;
2453 }
Leon Scrogginsf8551612009-09-24 16:06:02 -04002454 Bitmap bm = Bitmap.createBitmap(getDesiredThumbnailWidth(this),
Cary Clarkab168ba2010-04-08 09:11:28 -04002455 getDesiredThumbnailHeight(this), Bitmap.Config.RGB_565);
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002456 Canvas canvas = new Canvas(bm);
2457 // May need to tweak these values to determine what is the
2458 // best scale factor
Ben Murdoch2694e232009-09-29 09:41:11 +01002459 int thumbnailWidth = thumbnail.getWidth();
Ben Murdochae59c3f2009-10-20 18:30:28 +01002460 int thumbnailHeight = thumbnail.getHeight();
2461 float scaleFactorX = 1.0f;
2462 float scaleFactorY = 1.0f;
Ben Murdoch2694e232009-09-29 09:41:11 +01002463 if (thumbnailWidth > 0) {
Ben Murdochae59c3f2009-10-20 18:30:28 +01002464 scaleFactorX = (float) getDesiredThumbnailWidth(this) /
Ben Murdoch2694e232009-09-29 09:41:11 +01002465 (float)thumbnailWidth;
Ben Murdochae59c3f2009-10-20 18:30:28 +01002466 } else {
2467 return null;
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002468 }
Ben Murdochae59c3f2009-10-20 18:30:28 +01002469
2470 if (view.getWidth() > view.getHeight() &&
2471 thumbnailHeight < view.getHeight() && thumbnailHeight > 0) {
2472 // If the device is in landscape and the page is shorter
2473 // than the height of the view, stretch the thumbnail to fill the
2474 // space.
2475 scaleFactorY = (float) getDesiredThumbnailHeight(this) /
2476 (float)thumbnailHeight;
2477 } else {
2478 // In the portrait case, this looks nice.
2479 scaleFactorY = scaleFactorX;
2480 }
2481
2482 canvas.scale(scaleFactorX, scaleFactorY);
2483
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002484 thumbnail.draw(canvas);
2485 return bm;
2486 }
2487
The Android Open Source Project0c908882009-03-03 19:32:16 -08002488 // -------------------------------------------------------------------------
Grace Kloba22ac16e2009-10-07 18:00:23 -07002489 // Helper function for WebViewClient.
The Android Open Source Project0c908882009-03-03 19:32:16 -08002490 //-------------------------------------------------------------------------
2491
2492 // Use in overrideUrlLoading
2493 /* package */ final static String SCHEME_WTAI = "wtai://wp/";
2494 /* package */ final static String SCHEME_WTAI_MC = "wtai://wp/mc;";
2495 /* package */ final static String SCHEME_WTAI_SD = "wtai://wp/sd;";
2496 /* package */ final static String SCHEME_WTAI_AP = "wtai://wp/ap;";
2497
Leon Scroggins92472e82010-02-17 16:32:28 -05002498 // Keep this initial progress in sync with initialProgressValue (* 100)
2499 // in ProgressTracker.cpp
2500 private final static int INITIAL_PROGRESS = 10;
2501
Grace Kloba22ac16e2009-10-07 18:00:23 -07002502 void onPageStarted(WebView view, String url, Bitmap favicon) {
2503 // when BrowserActivity just starts, onPageStarted may be called before
2504 // onResume as it is triggered from onCreate. Call resumeWebViewTimers
2505 // to start the timer. As we won't switch tabs while an activity is in
2506 // pause state, we can ensure calling resume and pause in pair.
2507 if (mActivityInPause) resumeWebViewTimers();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002508
Grace Kloba22ac16e2009-10-07 18:00:23 -07002509 resetLockIcon(url);
2510 setUrlTitle(url, null);
2511 setFavicon(favicon);
Leon Scroggins8cf8f682009-11-04 11:13:50 -08002512 // Show some progress so that the user knows the page is beginning to
2513 // load
Leon Scroggins92472e82010-02-17 16:32:28 -05002514 onProgressChanged(view, INITIAL_PROGRESS);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002515 mDidStopLoad = false;
Grace Kloba22ac16e2009-10-07 18:00:23 -07002516 if (!mIsNetworkUp) createAndShowNetworkDialog();
Leon Scroggins III211ba542010-04-19 13:21:13 -04002517 if (view.getFindIsUp()) {
2518 closeFind();
2519 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002520 if (mSettings.isTracing()) {
2521 String host;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002522 try {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002523 WebAddress uri = new WebAddress(url);
2524 host = uri.mHost;
2525 } catch (android.net.ParseException ex) {
2526 host = "browser";
The Android Open Source Project0c908882009-03-03 19:32:16 -08002527 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002528 host = host.replace('.', '_');
2529 host += ".trace";
2530 mInTrace = true;
2531 Debug.startMethodTracing(host, 20 * 1024 * 1024);
2532 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002533
Grace Kloba22ac16e2009-10-07 18:00:23 -07002534 // Performance probe
2535 if (false) {
2536 mStart = SystemClock.uptimeMillis();
2537 mProcessStart = Process.getElapsedCpuTime();
2538 long[] sysCpu = new long[7];
2539 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2540 sysCpu, null)) {
2541 mUserStart = sysCpu[0] + sysCpu[1];
2542 mSystemStart = sysCpu[2];
2543 mIdleStart = sysCpu[3];
2544 mIrqStart = sysCpu[4] + sysCpu[5] + sysCpu[6];
2545 }
2546 mUiStart = SystemClock.currentThreadTimeMillis();
2547 }
2548 }
2549
2550 void onPageFinished(WebView view, String url) {
2551 // Reset the title and icon in case we stopped a provisional load.
2552 resetTitleAndIcon(view);
2553 // Update the lock icon image only once we are done loading
2554 updateLockIconToLatest();
2555 // pause the WebView timer and release the wake lock if it is finished
2556 // while BrowserActivity is in pause state.
2557 if (mActivityInPause && pauseWebViewTimers()) {
2558 if (mWakeLock.isHeld()) {
2559 mHandler.removeMessages(RELEASE_WAKELOCK);
2560 mWakeLock.release();
2561 }
2562 }
2563
2564 // Performance probe
2565 if (false) {
2566 long[] sysCpu = new long[7];
2567 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2568 sysCpu, null)) {
2569 String uiInfo = "UI thread used "
2570 + (SystemClock.currentThreadTimeMillis() - mUiStart)
2571 + " ms";
2572 if (LOGD_ENABLED) {
2573 Log.d(LOGTAG, uiInfo);
2574 }
2575 //The string that gets written to the log
2576 String performanceString = "It took total "
2577 + (SystemClock.uptimeMillis() - mStart)
2578 + " ms clock time to load the page."
2579 + "\nbrowser process used "
2580 + (Process.getElapsedCpuTime() - mProcessStart)
2581 + " ms, user processes used "
2582 + (sysCpu[0] + sysCpu[1] - mUserStart) * 10
2583 + " ms, kernel used "
2584 + (sysCpu[2] - mSystemStart) * 10
2585 + " ms, idle took " + (sysCpu[3] - mIdleStart) * 10
2586 + " ms and irq took "
2587 + (sysCpu[4] + sysCpu[5] + sysCpu[6] - mIrqStart)
2588 * 10 + " ms, " + uiInfo;
2589 if (LOGD_ENABLED) {
2590 Log.d(LOGTAG, performanceString + "\nWebpage: " + url);
2591 }
2592 if (url != null) {
2593 // strip the url to maintain consistency
2594 String newUrl = new String(url);
2595 if (newUrl.startsWith("http://www.")) {
2596 newUrl = newUrl.substring(11);
2597 } else if (newUrl.startsWith("http://")) {
2598 newUrl = newUrl.substring(7);
2599 } else if (newUrl.startsWith("https://www.")) {
2600 newUrl = newUrl.substring(12);
2601 } else if (newUrl.startsWith("https://")) {
2602 newUrl = newUrl.substring(8);
2603 }
2604 if (LOGD_ENABLED) {
2605 Log.d(LOGTAG, newUrl + " loaded");
2606 }
Grace Kloba5b078b52009-06-24 20:23:41 -07002607 }
2608 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002609 }
Grace Kloba5b078b52009-06-24 20:23:41 -07002610
Grace Kloba22ac16e2009-10-07 18:00:23 -07002611 if (mInTrace) {
2612 mInTrace = false;
2613 Debug.stopMethodTracing();
2614 }
2615 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002616
Grace Kloba22ac16e2009-10-07 18:00:23 -07002617 boolean shouldOverrideUrlLoading(WebView view, String url) {
2618 if (url.startsWith(SCHEME_WTAI)) {
2619 // wtai://wp/mc;number
2620 // number=string(phone-number)
2621 if (url.startsWith(SCHEME_WTAI_MC)) {
2622 Intent intent = new Intent(Intent.ACTION_VIEW,
2623 Uri.parse(WebView.SCHEME_TEL +
2624 url.substring(SCHEME_WTAI_MC.length())));
2625 startActivity(intent);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002626 return true;
2627 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002628 // wtai://wp/sd;dtmf
2629 // dtmf=string(dialstring)
2630 if (url.startsWith(SCHEME_WTAI_SD)) {
2631 // TODO: only send when there is active voice connection
2632 return false;
2633 }
2634 // wtai://wp/ap;number;name
2635 // number=string(phone-number)
2636 // name=string
2637 if (url.startsWith(SCHEME_WTAI_AP)) {
2638 // TODO
2639 return false;
2640 }
2641 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002642
Grace Kloba22ac16e2009-10-07 18:00:23 -07002643 // The "about:" schemes are internal to the browser; don't want these to
2644 // be dispatched to other apps.
2645 if (url.startsWith("about:")) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002646 return false;
2647 }
2648
Grace Kloba22ac16e2009-10-07 18:00:23 -07002649 Intent intent;
2650 // perform generic parsing of the URI to turn it into an Intent.
2651 try {
2652 intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME);
2653 } catch (URISyntaxException ex) {
2654 Log.w("Browser", "Bad URI " + url + ": " + ex.getMessage());
2655 return false;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002656 }
2657
Grace Kloba22ac16e2009-10-07 18:00:23 -07002658 // check whether the intent can be resolved. If not, we will see
2659 // whether we can download it from the Market.
2660 if (getPackageManager().resolveActivity(intent, 0) == null) {
2661 String packagename = intent.getPackage();
2662 if (packagename != null) {
2663 intent = new Intent(Intent.ACTION_VIEW, Uri
2664 .parse("market://search?q=pname:" + packagename));
2665 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2666 startActivity(intent);
2667 return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002668 } else {
2669 return false;
2670 }
2671 }
2672
Grace Kloba22ac16e2009-10-07 18:00:23 -07002673 // sanitize the Intent, ensuring web pages can not bypass browser
2674 // security (only access to BROWSABLE activities).
2675 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2676 intent.setComponent(null);
2677 try {
2678 if (startActivityIfNeeded(intent, -1)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002679 return true;
2680 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002681 } catch (ActivityNotFoundException ex) {
2682 // ignore the error. If no application can handle the URL,
2683 // eg about:blank, assume the browser can handle it.
2684 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002685
Grace Kloba22ac16e2009-10-07 18:00:23 -07002686 if (mMenuIsDown) {
2687 openTab(url);
2688 closeOptionsMenu();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002689 return true;
2690 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002691 return false;
2692 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002693
Grace Kloba22ac16e2009-10-07 18:00:23 -07002694 // -------------------------------------------------------------------------
2695 // Helper function for WebChromeClient
2696 // -------------------------------------------------------------------------
The Android Open Source Project0c908882009-03-03 19:32:16 -08002697
Grace Kloba22ac16e2009-10-07 18:00:23 -07002698 void onProgressChanged(WebView view, int newProgress) {
Leon Scrogginsd746a942010-05-19 13:21:44 -04002699 if (mXLargeScreenSize) {
2700 mTitleBar.setProgress(newProgress);
2701 } else {
2702 // On the phone, the fake title bar will always cover up the
2703 // regular title bar (or the regular one is offscreen), so only the
2704 // fake title bar needs to change its progress
2705 mFakeTitleBar.setProgress(newProgress);
2706 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002707
Grace Kloba22ac16e2009-10-07 18:00:23 -07002708 if (newProgress == 100) {
2709 // onProgressChanged() may continue to be called after the main
2710 // frame has finished loading, as any remaining sub frames continue
2711 // to load. We'll only get called once though with newProgress as
2712 // 100 when everything is loaded. (onPageFinished is called once
2713 // when the main frame completes loading regardless of the state of
2714 // any sub frames so calls to onProgressChanges may continue after
2715 // onPageFinished has executed)
2716 if (mInLoad) {
2717 mInLoad = false;
Leon Scrogginsa27ff192009-09-14 12:58:04 -04002718 updateInLoadMenuItems();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002719 // If the options menu is open, leave the title bar
2720 if (!mOptionsMenuOpen || !mIconView) {
2721 hideFakeTitleBar();
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07002722 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002723 }
Leon Scrogginsaa37e7f2010-03-05 11:51:20 -05002724 } else {
2725 if (!mInLoad) {
2726 // onPageFinished may have already been called but a subframe is
2727 // still loading and updating the progress. Reset mInLoad and
2728 // update the menu items.
2729 mInLoad = true;
2730 updateInLoadMenuItems();
2731 }
2732 // When the page first begins to load, the Activity may still be
2733 // paused, in which case showFakeTitleBar will do nothing. Call
2734 // again as the page continues to load so that it will be shown.
2735 // (Calling it will the fake title bar is already showing will also
2736 // do nothing.
Grace Kloba22ac16e2009-10-07 18:00:23 -07002737 if (!mOptionsMenuOpen || mIconView) {
2738 // This page has begun to load, so show the title bar
2739 showFakeTitleBar();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002740 }
2741 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002742 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002743
Grace Kloba22ac16e2009-10-07 18:00:23 -07002744 void onShowCustomView(View view, WebChromeClient.CustomViewCallback callback) {
Derek Sollenberger8ff57db2009-12-08 15:39:55 -05002745 // if a view already exists then immediately terminate the new one
2746 if (mCustomView != null) {
2747 callback.onCustomViewHidden();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002748 return;
Derek Sollenberger8ff57db2009-12-08 15:39:55 -05002749 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002750
2751 // Add the custom view to its container.
2752 mCustomViewContainer.addView(view, COVER_SCREEN_GRAVITY_CENTER);
2753 mCustomView = view;
2754 mCustomViewCallback = callback;
2755 // Save the menu state and set it to empty while the custom
2756 // view is showing.
2757 mOldMenuState = mMenuState;
2758 mMenuState = EMPTY_MENU;
2759 // Hide the content view.
2760 mContentView.setVisibility(View.GONE);
2761 // Finally show the custom view container.
Andrei Popescu163ab742009-10-20 17:58:23 +01002762 setStatusBarVisibility(false);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002763 mCustomViewContainer.setVisibility(View.VISIBLE);
2764 mCustomViewContainer.bringToFront();
2765 }
2766
2767 void onHideCustomView() {
2768 if (mCustomView == null)
2769 return;
2770
2771 // Hide the custom view.
2772 mCustomView.setVisibility(View.GONE);
2773 // Remove the custom view from its container.
2774 mCustomViewContainer.removeView(mCustomView);
2775 mCustomView = null;
2776 // Reset the old menu state.
2777 mMenuState = mOldMenuState;
2778 mOldMenuState = EMPTY_MENU;
2779 mCustomViewContainer.setVisibility(View.GONE);
2780 mCustomViewCallback.onCustomViewHidden();
2781 // Show the content view.
Andrei Popescu163ab742009-10-20 17:58:23 +01002782 setStatusBarVisibility(true);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002783 mContentView.setVisibility(View.VISIBLE);
2784 }
2785
2786 Bitmap getDefaultVideoPoster() {
2787 if (mDefaultVideoPoster == null) {
2788 mDefaultVideoPoster = BitmapFactory.decodeResource(
2789 getResources(), R.drawable.default_video_poster);
Patrick Scott3918d442009-08-04 13:22:29 -04002790 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002791 return mDefaultVideoPoster;
2792 }
Patrick Scott3918d442009-08-04 13:22:29 -04002793
Grace Kloba22ac16e2009-10-07 18:00:23 -07002794 View getVideoLoadingProgressView() {
2795 if (mVideoProgressView == null) {
2796 LayoutInflater inflater = LayoutInflater.from(BrowserActivity.this);
2797 mVideoProgressView = inflater.inflate(
2798 R.layout.video_loading_progress, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002799 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002800 return mVideoProgressView;
2801 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002802
Leon Scroggins8d5fa432009-10-02 15:55:59 -04002803 /*
2804 * The Object used to inform the WebView of the file to upload.
2805 */
2806 private ValueCallback<Uri> mUploadMessage;
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002807 private String mCameraFilePath;
Leon Scroggins8d5fa432009-10-02 15:55:59 -04002808
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002809 void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
2810
2811 final String imageMimeType = "image/*";
2812 final String imageSourceKey = "source";
2813 final String imageSourceValueCamera = "camera";
2814 final String imageSourceValueGallery = "gallery";
2815
2816 // image source can be 'gallery' or 'camera'.
2817 String imageSource = "";
2818
2819 // We add the camera intent if there was no accept type (or '*/*') or 'image/*'.
2820 boolean addCameraIntent = true;
2821
Grace Kloba22ac16e2009-10-07 18:00:23 -07002822 if (mUploadMessage != null) return;
2823 mUploadMessage = uploadMsg;
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002824
2825 // Parse the accept type.
2826 String params[] = acceptType.split(";");
2827 String mimeType = params[0];
2828
2829 for (String p : params) {
2830 String[] keyValue = p.split("=");
2831 if (keyValue.length == 2) {
2832 // Process key=value parameters.
2833 if (imageSourceKey.equals(keyValue[0])) {
2834 imageSource = keyValue[1];
2835 }
2836 }
2837 }
2838
2839 // This intent will display the standard OPENABLE file picker.
Grace Kloba22ac16e2009-10-07 18:00:23 -07002840 Intent i = new Intent(Intent.ACTION_GET_CONTENT);
2841 i.addCategory(Intent.CATEGORY_OPENABLE);
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002842
2843 // Create an intent to add to the standard file picker that will
2844 // capture an image from the camera. We'll combine this intent with
2845 // the standard OPENABLE picker unless the web developer specifically
2846 // requested the camera or gallery be opened by passing a parameter
2847 // in the accept type.
2848 Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
2849 File externalDataDir = Environment.getExternalStoragePublicDirectory(
2850 Environment.DIRECTORY_DCIM);
2851 File cameraDataDir = new File(externalDataDir.getAbsolutePath() +
2852 File.separator + "browser-photos");
2853 cameraDataDir.mkdirs();
2854 mCameraFilePath = cameraDataDir.getAbsolutePath() + File.separator +
2855 System.currentTimeMillis() + ".jpg";
2856 cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(mCameraFilePath)));
2857
2858 if (mimeType.equals(imageMimeType)) {
2859 i.setType(imageMimeType);
2860 if (imageSource.equals(imageSourceValueCamera)) {
2861 // Specified 'image/*' and requested the camera, so go ahead and launch the camera
2862 // directly.
2863 BrowserActivity.this.startActivityForResult(cameraIntent, FILE_SELECTED);
2864 return;
2865 } else if (imageSource.equals(imageSourceValueGallery)) {
2866 // Specified gallery as the source, so don't want to consider the camera.
2867 addCameraIntent = false;
2868 }
2869 } else {
2870 i.setType("*/*");
2871 }
2872
2873 // Combine the chooser and the extra choices (like camera)
2874 Intent chooser = new Intent(Intent.ACTION_CHOOSER);
2875 chooser.putExtra(Intent.EXTRA_INTENT, i);
2876
2877 if (addCameraIntent) {
2878 // Add the camera Intent
2879 Intent[] choices = new Intent[1];
2880 choices[0] = cameraIntent;
2881 chooser.putExtra(Intent.EXTRA_INITIAL_INTENTS, choices);
2882 }
2883
2884 chooser.putExtra(Intent.EXTRA_TITLE, getString(R.string.choose_upload));
2885 BrowserActivity.this.startActivityForResult(chooser, FILE_SELECTED);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002886 }
2887
2888 // -------------------------------------------------------------------------
2889 // Implement functions for DownloadListener
2890 // -------------------------------------------------------------------------
2891
The Android Open Source Project0c908882009-03-03 19:32:16 -08002892 /**
2893 * Notify the host application a download should be done, or that
2894 * the data should be streamed if a streaming viewer is available.
2895 * @param url The full url to the content that should be downloaded
2896 * @param contentDisposition Content-disposition http header, if
2897 * present.
2898 * @param mimetype The mimetype of the content reported by the server
2899 * @param contentLength The file size reported by the server
2900 */
2901 public void onDownloadStart(String url, String userAgent,
2902 String contentDisposition, String mimetype, long contentLength) {
2903 // if we're dealing wih A/V content that's not explicitly marked
2904 // for download, check if it's streamable.
2905 if (contentDisposition == null
Patrick Scotte1fb9662009-08-31 14:31:52 -04002906 || !contentDisposition.regionMatches(
2907 true, 0, "attachment", 0, 10)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002908 // query the package manager to see if there's a registered handler
2909 // that matches.
2910 Intent intent = new Intent(Intent.ACTION_VIEW);
2911 intent.setDataAndType(Uri.parse(url), mimetype);
Patrick Scotte1fb9662009-08-31 14:31:52 -04002912 ResolveInfo info = getPackageManager().resolveActivity(intent,
2913 PackageManager.MATCH_DEFAULT_ONLY);
2914 if (info != null) {
2915 ComponentName myName = getComponentName();
2916 // If we resolved to ourselves, we don't want to attempt to
2917 // load the url only to try and download it again.
2918 if (!myName.getPackageName().equals(
2919 info.activityInfo.packageName)
2920 || !myName.getClassName().equals(
2921 info.activityInfo.name)) {
2922 // someone (other than us) knows how to handle this mime
2923 // type with this scheme, don't download.
2924 try {
2925 startActivity(intent);
2926 return;
2927 } catch (ActivityNotFoundException ex) {
2928 if (LOGD_ENABLED) {
2929 Log.d(LOGTAG, "activity not found for " + mimetype
2930 + " over " + Uri.parse(url).getScheme(),
2931 ex);
2932 }
2933 // Best behavior is to fall back to a download in this
2934 // case
The Android Open Source Project0c908882009-03-03 19:32:16 -08002935 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002936 }
2937 }
2938 }
2939 onDownloadStartNoStream(url, userAgent, contentDisposition, mimetype, contentLength);
2940 }
2941
Kristian Monsenfa52d172010-03-25 18:29:21 +00002942 // This is to work around the fact that java.net.URI throws Exceptions
2943 // instead of just encoding URL's properly
2944 // Helper method for onDownloadStartNoStream
2945 private static String encodePath(String path) {
2946 char[] chars = path.toCharArray();
2947
2948 boolean needed = false;
2949 for (char c : chars) {
2950 if (c == '[' || c == ']') {
2951 needed = true;
2952 break;
2953 }
2954 }
2955 if (needed == false) {
2956 return path;
2957 }
2958
2959 StringBuilder sb = new StringBuilder("");
2960 for (char c : chars) {
2961 if (c == '[' || c == ']') {
2962 sb.append('%');
2963 sb.append(Integer.toHexString(c));
2964 } else {
2965 sb.append(c);
2966 }
2967 }
2968
2969 return sb.toString();
2970 }
2971
The Android Open Source Project0c908882009-03-03 19:32:16 -08002972 /**
2973 * Notify the host application a download should be done, even if there
2974 * is a streaming viewer available for thise type.
2975 * @param url The full url to the content that should be downloaded
2976 * @param contentDisposition Content-disposition http header, if
2977 * present.
2978 * @param mimetype The mimetype of the content reported by the server
2979 * @param contentLength The file size reported by the server
2980 */
2981 /*package */ void onDownloadStartNoStream(String url, String userAgent,
2982 String contentDisposition, String mimetype, long contentLength) {
2983
2984 String filename = URLUtil.guessFileName(url,
2985 contentDisposition, mimetype);
2986
2987 // Check to see if we have an SDCard
2988 String status = Environment.getExternalStorageState();
2989 if (!status.equals(Environment.MEDIA_MOUNTED)) {
2990 int title;
2991 String msg;
2992
2993 // Check to see if the SDCard is busy, same as the music app
2994 if (status.equals(Environment.MEDIA_SHARED)) {
2995 msg = getString(R.string.download_sdcard_busy_dlg_msg);
2996 title = R.string.download_sdcard_busy_dlg_title;
2997 } else {
2998 msg = getString(R.string.download_no_sdcard_dlg_msg, filename);
2999 title = R.string.download_no_sdcard_dlg_title;
3000 }
3001
3002 new AlertDialog.Builder(this)
3003 .setTitle(title)
3004 .setIcon(android.R.drawable.ic_dialog_alert)
3005 .setMessage(msg)
3006 .setPositiveButton(R.string.ok, null)
3007 .show();
3008 return;
3009 }
3010
Kristian Monsenfa52d172010-03-25 18:29:21 +00003011 // java.net.URI is a lot stricter than KURL so we have to encode some
3012 // extra characters. Fix for b 2538060 and b 1634719
3013 WebAddress webAddress;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003014 try {
Kristian Monsenfa52d172010-03-25 18:29:21 +00003015 webAddress = new WebAddress(url);
3016 webAddress.mPath = encodePath(webAddress.mPath);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003017 } catch (Exception e) {
Kristian Monsenfa52d172010-03-25 18:29:21 +00003018 // This only happens for very bad urls, we want to chatch the
3019 // exception here
3020 Log.e(LOGTAG, "Exception trying to parse url:" + url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003021 return;
3022 }
3023
3024 // XXX: Have to use the old url since the cookies were stored using the
3025 // old percent-encoded url.
3026 String cookies = CookieManager.getInstance().getCookie(url);
3027
3028 ContentValues values = new ContentValues();
Kristian Monsenfa52d172010-03-25 18:29:21 +00003029 values.put(Downloads.Impl.COLUMN_URI, webAddress.toString());
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08003030 values.put(Downloads.Impl.COLUMN_COOKIE_DATA, cookies);
3031 values.put(Downloads.Impl.COLUMN_USER_AGENT, userAgent);
3032 values.put(Downloads.Impl.COLUMN_NOTIFICATION_PACKAGE,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003033 getPackageName());
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08003034 values.put(Downloads.Impl.COLUMN_NOTIFICATION_CLASS,
Leon Scrogginsa563d092010-04-19 16:53:49 -04003035 OpenDownloadReceiver.class.getCanonicalName());
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08003036 values.put(Downloads.Impl.COLUMN_VISIBILITY,
3037 Downloads.Impl.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
3038 values.put(Downloads.Impl.COLUMN_MIME_TYPE, mimetype);
3039 values.put(Downloads.Impl.COLUMN_FILE_NAME_HINT, filename);
Kristian Monsenfa52d172010-03-25 18:29:21 +00003040 values.put(Downloads.Impl.COLUMN_DESCRIPTION, webAddress.mHost);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003041 if (contentLength > 0) {
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08003042 values.put(Downloads.Impl.COLUMN_TOTAL_BYTES, contentLength);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003043 }
3044 if (mimetype == null) {
3045 // We must have long pressed on a link or image to download it. We
3046 // are not sure of the mimetype in this case, so do a head request
3047 new FetchUrlMimeType(this).execute(values);
3048 } else {
3049 final Uri contentUri =
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08003050 getContentResolver().insert(Downloads.Impl.CONTENT_URI, values);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003051 }
Leon Scroggins9191a7f2010-03-18 14:44:44 -04003052 Toast.makeText(this, R.string.download_pending, Toast.LENGTH_SHORT)
3053 .show();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003054 }
3055
Grace Kloba22ac16e2009-10-07 18:00:23 -07003056 // -------------------------------------------------------------------------
3057
The Android Open Source Project0c908882009-03-03 19:32:16 -08003058 /**
3059 * Resets the lock icon. This method is called when we start a new load and
3060 * know the url to be loaded.
3061 */
3062 private void resetLockIcon(String url) {
3063 // Save the lock-icon state (we revert to it if the load gets cancelled)
Grace Kloba22ac16e2009-10-07 18:00:23 -07003064 mTabControl.getCurrentTab().resetLockIcon(url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003065 updateLockIconImage(LOCK_ICON_UNSECURE);
3066 }
3067
The Android Open Source Project0c908882009-03-03 19:32:16 -08003068 /**
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04003069 * Update the lock icon to correspond to our latest state.
3070 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003071 private void updateLockIconToLatest() {
3072 updateLockIconImage(mTabControl.getCurrentTab().getLockIconType());
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04003073 }
3074
3075 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08003076 * Updates the lock-icon image in the title-bar.
3077 */
3078 private void updateLockIconImage(int lockIconType) {
3079 Drawable d = null;
3080 if (lockIconType == LOCK_ICON_SECURE) {
3081 d = mSecLockIcon;
3082 } else if (lockIconType == LOCK_ICON_MIXED) {
3083 d = mMixLockIcon;
3084 }
Leon Scroggins68579392009-09-15 15:31:54 -04003085 mTitleBar.setLock(d);
Leon Scrogginsd746a942010-05-19 13:21:44 -04003086 if (!mXLargeScreenSize) {
3087 mFakeTitleBar.setLock(d);
3088 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003089 }
3090
3091 /**
3092 * Displays a page-info dialog.
3093 * @param tab The tab to show info about
3094 * @param fromShowSSLCertificateOnError The flag that indicates whether
3095 * this dialog was opened from the SSL-certificate-on-error dialog or
3096 * not. This is important, since we need to know whether to return to
3097 * the parent dialog or simply dismiss.
3098 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003099 private void showPageInfo(final Tab tab,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003100 final boolean fromShowSSLCertificateOnError) {
3101 final LayoutInflater factory = LayoutInflater
3102 .from(this);
3103
3104 final View pageInfoView = factory.inflate(R.layout.page_info, null);
3105
3106 final WebView view = tab.getWebView();
3107
3108 String url = null;
3109 String title = null;
3110
3111 if (view == null) {
3112 url = tab.getUrl();
3113 title = tab.getTitle();
3114 } else if (view == mTabControl.getCurrentWebView()) {
3115 // Use the cached title and url if this is the current WebView
3116 url = mUrl;
3117 title = mTitle;
3118 } else {
3119 url = view.getUrl();
3120 title = view.getTitle();
3121 }
3122
3123 if (url == null) {
3124 url = "";
3125 }
3126 if (title == null) {
3127 title = "";
3128 }
3129
3130 ((TextView) pageInfoView.findViewById(R.id.address)).setText(url);
3131 ((TextView) pageInfoView.findViewById(R.id.title)).setText(title);
3132
3133 mPageInfoView = tab;
Leon Scrogginsc7b92f82010-01-11 18:17:31 -05003134 mPageInfoFromShowSSLCertificateOnError = fromShowSSLCertificateOnError;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003135
3136 AlertDialog.Builder alertDialogBuilder =
3137 new AlertDialog.Builder(this)
3138 .setTitle(R.string.page_info).setIcon(android.R.drawable.ic_dialog_info)
3139 .setView(pageInfoView)
3140 .setPositiveButton(
3141 R.string.ok,
3142 new DialogInterface.OnClickListener() {
3143 public void onClick(DialogInterface dialog,
3144 int whichButton) {
3145 mPageInfoDialog = null;
3146 mPageInfoView = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003147
3148 // if we came here from the SSL error dialog
3149 if (fromShowSSLCertificateOnError) {
3150 // go back to the SSL error dialog
3151 showSSLCertificateOnError(
3152 mSSLCertificateOnErrorView,
3153 mSSLCertificateOnErrorHandler,
3154 mSSLCertificateOnErrorError);
3155 }
3156 }
3157 })
3158 .setOnCancelListener(
3159 new DialogInterface.OnCancelListener() {
3160 public void onCancel(DialogInterface dialog) {
3161 mPageInfoDialog = null;
3162 mPageInfoView = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003163
3164 // if we came here from the SSL error dialog
3165 if (fromShowSSLCertificateOnError) {
3166 // go back to the SSL error dialog
3167 showSSLCertificateOnError(
3168 mSSLCertificateOnErrorView,
3169 mSSLCertificateOnErrorHandler,
3170 mSSLCertificateOnErrorError);
3171 }
3172 }
3173 });
3174
3175 // if we have a main top-level page SSL certificate set or a certificate
3176 // error
3177 if (fromShowSSLCertificateOnError ||
3178 (view != null && view.getCertificate() != null)) {
3179 // add a 'View Certificate' button
3180 alertDialogBuilder.setNeutralButton(
3181 R.string.view_certificate,
3182 new DialogInterface.OnClickListener() {
3183 public void onClick(DialogInterface dialog,
3184 int whichButton) {
3185 mPageInfoDialog = null;
3186 mPageInfoView = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003187
3188 // if we came here from the SSL error dialog
3189 if (fromShowSSLCertificateOnError) {
3190 // go back to the SSL error dialog
3191 showSSLCertificateOnError(
3192 mSSLCertificateOnErrorView,
3193 mSSLCertificateOnErrorHandler,
3194 mSSLCertificateOnErrorError);
3195 } else {
3196 // otherwise, display the top-most certificate from
3197 // the chain
3198 if (view.getCertificate() != null) {
3199 showSSLCertificate(tab);
3200 }
3201 }
3202 }
3203 });
3204 }
3205
3206 mPageInfoDialog = alertDialogBuilder.show();
3207 }
3208
3209 /**
3210 * Displays the main top-level page SSL certificate dialog
3211 * (accessible from the Page-Info dialog).
3212 * @param tab The tab to show certificate for.
3213 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003214 private void showSSLCertificate(final Tab tab) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003215 final View certificateView =
3216 inflateCertificateView(tab.getWebView().getCertificate());
3217 if (certificateView == null) {
3218 return;
3219 }
3220
3221 LayoutInflater factory = LayoutInflater.from(this);
3222
3223 final LinearLayout placeholder =
3224 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3225
3226 LinearLayout ll = (LinearLayout) factory.inflate(
3227 R.layout.ssl_success, placeholder);
3228 ((TextView)ll.findViewById(R.id.success))
3229 .setText(R.string.ssl_certificate_is_valid);
3230
3231 mSSLCertificateView = tab;
3232 mSSLCertificateDialog =
3233 new AlertDialog.Builder(this)
3234 .setTitle(R.string.ssl_certificate).setIcon(
3235 R.drawable.ic_dialog_browser_certificate_secure)
3236 .setView(certificateView)
3237 .setPositiveButton(R.string.ok,
3238 new DialogInterface.OnClickListener() {
3239 public void onClick(DialogInterface dialog,
3240 int whichButton) {
3241 mSSLCertificateDialog = null;
3242 mSSLCertificateView = null;
3243
3244 showPageInfo(tab, false);
3245 }
3246 })
3247 .setOnCancelListener(
3248 new DialogInterface.OnCancelListener() {
3249 public void onCancel(DialogInterface dialog) {
3250 mSSLCertificateDialog = null;
3251 mSSLCertificateView = null;
3252
3253 showPageInfo(tab, false);
3254 }
3255 })
3256 .show();
3257 }
3258
3259 /**
3260 * Displays the SSL error certificate dialog.
3261 * @param view The target web-view.
3262 * @param handler The SSL error handler responsible for cancelling the
3263 * connection that resulted in an SSL error or proceeding per user request.
3264 * @param error The SSL error object.
3265 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003266 void showSSLCertificateOnError(
The Android Open Source Project0c908882009-03-03 19:32:16 -08003267 final WebView view, final SslErrorHandler handler, final SslError error) {
3268
3269 final View certificateView =
3270 inflateCertificateView(error.getCertificate());
3271 if (certificateView == null) {
3272 return;
3273 }
3274
3275 LayoutInflater factory = LayoutInflater.from(this);
3276
3277 final LinearLayout placeholder =
3278 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3279
3280 if (error.hasError(SslError.SSL_UNTRUSTED)) {
3281 LinearLayout ll = (LinearLayout)factory
3282 .inflate(R.layout.ssl_warning, placeholder);
3283 ((TextView)ll.findViewById(R.id.warning))
3284 .setText(R.string.ssl_untrusted);
3285 }
3286
3287 if (error.hasError(SslError.SSL_IDMISMATCH)) {
3288 LinearLayout ll = (LinearLayout)factory
3289 .inflate(R.layout.ssl_warning, placeholder);
3290 ((TextView)ll.findViewById(R.id.warning))
3291 .setText(R.string.ssl_mismatch);
3292 }
3293
3294 if (error.hasError(SslError.SSL_EXPIRED)) {
3295 LinearLayout ll = (LinearLayout)factory
3296 .inflate(R.layout.ssl_warning, placeholder);
3297 ((TextView)ll.findViewById(R.id.warning))
3298 .setText(R.string.ssl_expired);
3299 }
3300
3301 if (error.hasError(SslError.SSL_NOTYETVALID)) {
3302 LinearLayout ll = (LinearLayout)factory
3303 .inflate(R.layout.ssl_warning, placeholder);
3304 ((TextView)ll.findViewById(R.id.warning))
3305 .setText(R.string.ssl_not_yet_valid);
3306 }
3307
3308 mSSLCertificateOnErrorHandler = handler;
3309 mSSLCertificateOnErrorView = view;
3310 mSSLCertificateOnErrorError = error;
3311 mSSLCertificateOnErrorDialog =
3312 new AlertDialog.Builder(this)
3313 .setTitle(R.string.ssl_certificate).setIcon(
3314 R.drawable.ic_dialog_browser_certificate_partially_secure)
3315 .setView(certificateView)
3316 .setPositiveButton(R.string.ok,
3317 new DialogInterface.OnClickListener() {
3318 public void onClick(DialogInterface dialog,
3319 int whichButton) {
3320 mSSLCertificateOnErrorDialog = null;
3321 mSSLCertificateOnErrorView = null;
3322 mSSLCertificateOnErrorHandler = null;
3323 mSSLCertificateOnErrorError = null;
3324
Grace Kloba22ac16e2009-10-07 18:00:23 -07003325 view.getWebViewClient().onReceivedSslError(
3326 view, handler, error);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003327 }
3328 })
3329 .setNeutralButton(R.string.page_info_view,
3330 new DialogInterface.OnClickListener() {
3331 public void onClick(DialogInterface dialog,
3332 int whichButton) {
3333 mSSLCertificateOnErrorDialog = null;
3334
3335 // do not clear the dialog state: we will
3336 // need to show the dialog again once the
3337 // user is done exploring the page-info details
3338
3339 showPageInfo(mTabControl.getTabFromView(view),
3340 true);
3341 }
3342 })
3343 .setOnCancelListener(
3344 new DialogInterface.OnCancelListener() {
3345 public void onCancel(DialogInterface dialog) {
3346 mSSLCertificateOnErrorDialog = null;
3347 mSSLCertificateOnErrorView = null;
3348 mSSLCertificateOnErrorHandler = null;
3349 mSSLCertificateOnErrorError = null;
3350
Grace Kloba22ac16e2009-10-07 18:00:23 -07003351 view.getWebViewClient().onReceivedSslError(
3352 view, handler, error);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003353 }
3354 })
3355 .show();
3356 }
3357
3358 /**
3359 * Inflates the SSL certificate view (helper method).
3360 * @param certificate The SSL certificate.
3361 * @return The resultant certificate view with issued-to, issued-by,
3362 * issued-on, expires-on, and possibly other fields set.
3363 * If the input certificate is null, returns null.
3364 */
3365 private View inflateCertificateView(SslCertificate certificate) {
3366 if (certificate == null) {
3367 return null;
3368 }
3369
3370 LayoutInflater factory = LayoutInflater.from(this);
3371
3372 View certificateView = factory.inflate(
3373 R.layout.ssl_certificate, null);
3374
3375 // issued to:
3376 SslCertificate.DName issuedTo = certificate.getIssuedTo();
3377 if (issuedTo != null) {
3378 ((TextView) certificateView.findViewById(R.id.to_common))
3379 .setText(issuedTo.getCName());
3380 ((TextView) certificateView.findViewById(R.id.to_org))
3381 .setText(issuedTo.getOName());
3382 ((TextView) certificateView.findViewById(R.id.to_org_unit))
3383 .setText(issuedTo.getUName());
3384 }
3385
3386 // issued by:
3387 SslCertificate.DName issuedBy = certificate.getIssuedBy();
3388 if (issuedBy != null) {
3389 ((TextView) certificateView.findViewById(R.id.by_common))
3390 .setText(issuedBy.getCName());
3391 ((TextView) certificateView.findViewById(R.id.by_org))
3392 .setText(issuedBy.getOName());
3393 ((TextView) certificateView.findViewById(R.id.by_org_unit))
3394 .setText(issuedBy.getUName());
3395 }
3396
3397 // issued on:
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003398 String issuedOn = formatCertificateDate(
3399 certificate.getValidNotBeforeDate());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003400 ((TextView) certificateView.findViewById(R.id.issued_on))
3401 .setText(issuedOn);
3402
3403 // expires on:
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003404 String expiresOn = formatCertificateDate(
3405 certificate.getValidNotAfterDate());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003406 ((TextView) certificateView.findViewById(R.id.expires_on))
3407 .setText(expiresOn);
3408
3409 return certificateView;
3410 }
3411
3412 /**
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003413 * Formats the certificate date to a properly localized date string.
The Android Open Source Project0c908882009-03-03 19:32:16 -08003414 * @return Properly localized version of the certificate date string and
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003415 * the "" if it fails to localize.
The Android Open Source Project0c908882009-03-03 19:32:16 -08003416 */
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003417 private String formatCertificateDate(Date certificateDate) {
3418 if (certificateDate == null) {
3419 return "";
The Android Open Source Project0c908882009-03-03 19:32:16 -08003420 }
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003421 String formattedDate = DateFormat.getDateFormat(this).format(certificateDate);
3422 if (formattedDate == null) {
3423 return "";
3424 }
3425 return formattedDate;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003426 }
3427
3428 /**
3429 * Displays an http-authentication dialog.
3430 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003431 void showHttpAuthentication(final HttpAuthHandler handler,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003432 final String host, final String realm, final String title,
3433 final String name, final String password, int focusId) {
3434 LayoutInflater factory = LayoutInflater.from(this);
3435 final View v = factory
3436 .inflate(R.layout.http_authentication, null);
3437 if (name != null) {
3438 ((EditText) v.findViewById(R.id.username_edit)).setText(name);
3439 }
3440 if (password != null) {
3441 ((EditText) v.findViewById(R.id.password_edit)).setText(password);
3442 }
3443
3444 String titleText = title;
3445 if (titleText == null) {
3446 titleText = getText(R.string.sign_in_to).toString().replace(
3447 "%s1", host).replace("%s2", realm);
3448 }
3449
3450 mHttpAuthHandler = handler;
3451 AlertDialog dialog = new AlertDialog.Builder(this)
3452 .setTitle(titleText)
3453 .setIcon(android.R.drawable.ic_dialog_alert)
3454 .setView(v)
3455 .setPositiveButton(R.string.action,
3456 new DialogInterface.OnClickListener() {
3457 public void onClick(DialogInterface dialog,
3458 int whichButton) {
3459 String nm = ((EditText) v
3460 .findViewById(R.id.username_edit))
3461 .getText().toString();
3462 String pw = ((EditText) v
3463 .findViewById(R.id.password_edit))
3464 .getText().toString();
3465 BrowserActivity.this.setHttpAuthUsernamePassword
3466 (host, realm, nm, pw);
3467 handler.proceed(nm, pw);
3468 mHttpAuthenticationDialog = null;
3469 mHttpAuthHandler = null;
3470 }})
3471 .setNegativeButton(R.string.cancel,
3472 new DialogInterface.OnClickListener() {
3473 public void onClick(DialogInterface dialog,
3474 int whichButton) {
3475 handler.cancel();
3476 BrowserActivity.this.resetTitleAndRevertLockIcon();
3477 mHttpAuthenticationDialog = null;
3478 mHttpAuthHandler = null;
3479 }})
3480 .setOnCancelListener(new DialogInterface.OnCancelListener() {
3481 public void onCancel(DialogInterface dialog) {
3482 handler.cancel();
3483 BrowserActivity.this.resetTitleAndRevertLockIcon();
3484 mHttpAuthenticationDialog = null;
3485 mHttpAuthHandler = null;
3486 }})
3487 .create();
3488 // Make the IME appear when the dialog is displayed if applicable.
3489 dialog.getWindow().setSoftInputMode(
3490 WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
3491 dialog.show();
3492 if (focusId != 0) {
3493 dialog.findViewById(focusId).requestFocus();
3494 } else {
3495 v.findViewById(R.id.username_edit).requestFocus();
3496 }
3497 mHttpAuthenticationDialog = dialog;
3498 }
3499
3500 public int getProgress() {
3501 WebView w = mTabControl.getCurrentWebView();
3502 if (w != null) {
3503 return w.getProgress();
3504 } else {
3505 return 100;
3506 }
3507 }
3508
3509 /**
3510 * Set HTTP authentication password.
3511 *
3512 * @param host The host for the password
3513 * @param realm The realm for the password
3514 * @param username The username for the password. If it is null, it means
3515 * password can't be saved.
3516 * @param password The password
3517 */
3518 public void setHttpAuthUsernamePassword(String host, String realm,
3519 String username,
3520 String password) {
Steve Block95a53b22010-03-25 17:24:58 +00003521 WebView w = getTopWindow();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003522 if (w != null) {
3523 w.setHttpAuthUsernamePassword(host, realm, username, password);
3524 }
3525 }
3526
3527 /**
3528 * connectivity manager says net has come or gone... inform the user
3529 * @param up true if net has come up, false if net has gone down
3530 */
3531 public void onNetworkToggle(boolean up) {
3532 if (up == mIsNetworkUp) {
3533 return;
3534 } else if (up) {
3535 mIsNetworkUp = true;
3536 if (mAlertDialog != null) {
3537 mAlertDialog.cancel();
3538 mAlertDialog = null;
3539 }
3540 } else {
3541 mIsNetworkUp = false;
Patrick Scotteb6ab2a2009-09-16 10:00:17 -04003542 if (mInLoad) {
3543 createAndShowNetworkDialog();
3544 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003545 }
3546 WebView w = mTabControl.getCurrentWebView();
3547 if (w != null) {
3548 w.setNetworkAvailable(up);
3549 }
3550 }
3551
Grace Kloba22ac16e2009-10-07 18:00:23 -07003552 boolean isNetworkUp() {
3553 return mIsNetworkUp;
3554 }
3555
Patrick Scotteb6ab2a2009-09-16 10:00:17 -04003556 // This method shows the network dialog alerting the user that the net is
3557 // down. It will only show the dialog if mAlertDialog is null.
3558 private void createAndShowNetworkDialog() {
3559 if (mAlertDialog == null) {
3560 mAlertDialog = new AlertDialog.Builder(this)
3561 .setTitle(R.string.loadSuspendedTitle)
3562 .setMessage(R.string.loadSuspended)
3563 .setPositiveButton(R.string.ok, null)
3564 .show();
3565 }
3566 }
3567
The Android Open Source Project0c908882009-03-03 19:32:16 -08003568 @Override
3569 protected void onActivityResult(int requestCode, int resultCode,
3570 Intent intent) {
Grace Klobabb394f32009-11-19 10:26:37 -08003571 if (getTopWindow() == null) return;
3572
The Android Open Source Project0c908882009-03-03 19:32:16 -08003573 switch (requestCode) {
3574 case COMBO_PAGE:
3575 if (resultCode == RESULT_OK && intent != null) {
3576 String data = intent.getAction();
3577 Bundle extras = intent.getExtras();
3578 if (extras != null && extras.getBoolean("new_window", false)) {
Leon Scroggins25d35472009-09-15 11:37:27 -04003579 openTab(data);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003580 } else {
Grace Kloba22ac16e2009-10-07 18:00:23 -07003581 final Tab currentTab =
The Android Open Source Project0c908882009-03-03 19:32:16 -08003582 mTabControl.getCurrentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04003583 dismissSubWindow(currentTab);
3584 if (data != null && data.length() != 0) {
Leon Scroggins92472e82010-02-17 16:32:28 -05003585 loadUrl(getTopWindow(), data);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003586 }
3587 }
3588 }
Leon Scrogginsfde97462010-01-11 13:06:21 -05003589 // Deliberately fall through to PREFERENCES_PAGE, since the
3590 // same extra may be attached to the COMBO_PAGE
3591 case PREFERENCES_PAGE:
3592 if (resultCode == RESULT_OK && intent != null) {
3593 String action = intent.getStringExtra(Intent.EXTRA_TEXT);
3594 if (BrowserSettings.PREF_CLEAR_HISTORY.equals(action)) {
3595 mTabControl.removeParentChildRelationShips();
3596 }
3597 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003598 break;
Leon Scroggins8d5fa432009-10-02 15:55:59 -04003599 // Choose a file from the file picker.
3600 case FILE_SELECTED:
3601 if (null == mUploadMessage) break;
3602 Uri result = intent == null || resultCode != RESULT_OK ? null
3603 : intent.getData();
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003604
3605 // As we ask the camera to save the result of the user taking
3606 // a picture, the camera application does not return anything other
3607 // than RESULT_OK. So we need to check whether the file we expected
3608 // was written to disk in the in the case that we
3609 // did not get an intent returned but did get a RESULT_OK. If it was,
3610 // we assume that this result has came back from the camera.
3611 if (result == null && intent == null && resultCode == RESULT_OK) {
3612 File cameraFile = new File(mCameraFilePath);
3613 if (cameraFile.exists()) {
3614 result = Uri.fromFile(cameraFile);
Ben Murdoch07d34732010-05-27 18:34:46 +01003615 // Broadcast to the media scanner that we have a new photo
3616 // so it will be added into the gallery for the user.
3617 sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, result));
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003618 }
3619 }
3620
Leon Scroggins8d5fa432009-10-02 15:55:59 -04003621 mUploadMessage.onReceiveValue(result);
3622 mUploadMessage = null;
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003623 mCameraFilePath = null;
Leon Scroggins8d5fa432009-10-02 15:55:59 -04003624 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003625 default:
3626 break;
3627 }
Leon Scroggins30444232009-09-04 18:36:20 -04003628 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003629 }
3630
3631 /*
3632 * This method is called as a result of the user selecting the options
Leon Scrogginsf08809b2010-01-21 09:27:46 -05003633 * menu to see the download window. It shows the download window on top of
3634 * the current window.
The Android Open Source Project0c908882009-03-03 19:32:16 -08003635 */
Leon Scrogginsf08809b2010-01-21 09:27:46 -05003636 private void viewDownloads(Uri downloadRecord) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003637 Intent intent = new Intent(this,
3638 BrowserDownloadPage.class);
3639 intent.setData(downloadRecord);
Grace Kloba22ac16e2009-10-07 18:00:23 -07003640 startActivityForResult(intent, BrowserActivity.DOWNLOAD_PAGE);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003641
3642 }
3643
Leon Scroggins160a7e72009-08-14 18:28:01 -04003644 /**
3645 * Open the Go page.
3646 * @param startWithHistory If true, open starting on the history tab.
3647 * Otherwise, start with the bookmarks tab.
Leon Scroggins160a7e72009-08-14 18:28:01 -04003648 */
Leon Scroggins30444232009-09-04 18:36:20 -04003649 /* package */ void bookmarksOrHistoryPicker(boolean startWithHistory) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003650 WebView current = mTabControl.getCurrentWebView();
3651 if (current == null) {
3652 return;
3653 }
3654 Intent intent = new Intent(this,
3655 CombinedBookmarkHistoryActivity.class);
3656 String title = current.getTitle();
3657 String url = current.getUrl();
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01003658 Bitmap thumbnail = createScreenshot(current);
3659
The Android Open Source Project0c908882009-03-03 19:32:16 -08003660 // Just in case the user opens bookmarks before a page finishes loading
3661 // so the current history item, and therefore the page, is null.
3662 if (null == url) {
3663 url = mLastEnteredUrl;
3664 // This can happen.
3665 if (null == url) {
3666 url = mSettings.getHomePage();
3667 }
3668 }
3669 // In case the web page has not yet received its associated title.
3670 if (title == null) {
3671 title = url;
3672 }
3673 intent.putExtra("title", title);
3674 intent.putExtra("url", url);
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01003675 intent.putExtra("thumbnail", thumbnail);
Leon Scroggins30444232009-09-04 18:36:20 -04003676 // Disable opening in a new window if we have maxed out the windows
Grace Kloba22ac16e2009-10-07 18:00:23 -07003677 intent.putExtra("disable_new_window", !mTabControl.canCreateNewTab());
Patrick Scott3918d442009-08-04 13:22:29 -04003678 intent.putExtra("touch_icon_url", current.getTouchIconUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003679 if (startWithHistory) {
3680 intent.putExtra(CombinedBookmarkHistoryActivity.STARTING_TAB,
3681 CombinedBookmarkHistoryActivity.HISTORY_TAB);
3682 }
3683 startActivityForResult(intent, COMBO_PAGE);
3684 }
3685
3686 // Called when loading from context menu or LOAD_URL message
Leon Scroggins92472e82010-02-17 16:32:28 -05003687 private void loadUrlFromContext(WebView view, String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003688 // In case the user enters nothing.
3689 if (url != null && url.length() != 0 && view != null) {
3690 url = smartUrlFilter(url);
Grace Kloba22ac16e2009-10-07 18:00:23 -07003691 if (!view.getWebViewClient().shouldOverrideUrlLoading(view, url)) {
Leon Scroggins92472e82010-02-17 16:32:28 -05003692 loadUrl(view, url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003693 }
3694 }
3695 }
3696
Leon Scroggins92472e82010-02-17 16:32:28 -05003697 /**
3698 * Load the URL into the given WebView and update the title bar
3699 * to reflect the new load. Call this instead of WebView.loadUrl
3700 * directly.
3701 * @param view The WebView used to load url.
3702 * @param url The URL to load.
3703 */
3704 private void loadUrl(WebView view, String url) {
3705 updateTitleBarForNewLoad(view, url);
3706 view.loadUrl(url);
3707 }
3708
3709 /**
3710 * Load UrlData into a Tab and update the title bar to reflect the new
3711 * load. Call this instead of UrlData.loadIn directly.
3712 * @param t The Tab used to load.
3713 * @param data The UrlData being loaded.
3714 */
3715 private void loadUrlDataIn(Tab t, UrlData data) {
3716 updateTitleBarForNewLoad(t.getWebView(), data.mUrl);
3717 data.loadIn(t);
3718 }
3719
3720 /**
3721 * If the WebView is the top window, update the title bar to reflect
3722 * loading the new URL. i.e. set its text, clear the favicon (which
3723 * will be set once the page begins loading), and set the progress to
3724 * INITIAL_PROGRESS to show that the page has begun to load. Called
3725 * by loadUrl and loadUrlDataIn.
3726 * @param view The WebView that is starting a load.
3727 * @param url The URL that is being loaded.
3728 */
3729 private void updateTitleBarForNewLoad(WebView view, String url) {
3730 if (view == getTopWindow()) {
3731 setUrlTitle(url, null);
3732 setFavicon(null);
3733 onProgressChanged(view, INITIAL_PROGRESS);
3734 }
3735 }
3736
The Android Open Source Project0c908882009-03-03 19:32:16 -08003737 private String smartUrlFilter(Uri inUri) {
3738 if (inUri != null) {
3739 return smartUrlFilter(inUri.toString());
3740 }
3741 return null;
3742 }
3743
Feng Qianb34f87a2009-03-24 21:27:26 -07003744 protected static final Pattern ACCEPTED_URI_SCHEMA = Pattern.compile(
The Android Open Source Project0c908882009-03-03 19:32:16 -08003745 "(?i)" + // switch on case insensitive matching
3746 "(" + // begin group for schema
3747 "(?:http|https|file):\\/\\/" +
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003748 "|(?:inline|data|about|content|javascript):" +
The Android Open Source Project0c908882009-03-03 19:32:16 -08003749 ")" +
3750 "(.*)" );
3751
3752 /**
3753 * Attempts to determine whether user input is a URL or search
3754 * terms. Anything with a space is passed to search.
3755 *
3756 * Converts to lowercase any mistakenly uppercased schema (i.e.,
3757 * "Http://" converts to "http://"
3758 *
3759 * @return Original or modified URL
3760 *
3761 */
3762 String smartUrlFilter(String url) {
3763
3764 String inUrl = url.trim();
3765 boolean hasSpace = inUrl.indexOf(' ') != -1;
3766
3767 Matcher matcher = ACCEPTED_URI_SCHEMA.matcher(inUrl);
3768 if (matcher.matches()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003769 // force scheme to lowercase
3770 String scheme = matcher.group(1);
3771 String lcScheme = scheme.toLowerCase();
3772 if (!lcScheme.equals(scheme)) {
Mitsuru Oshima123ecfb2009-05-18 19:11:14 -07003773 inUrl = lcScheme + matcher.group(2);
3774 }
3775 if (hasSpace) {
3776 inUrl = inUrl.replace(" ", "%20");
The Android Open Source Project0c908882009-03-03 19:32:16 -08003777 }
3778 return inUrl;
3779 }
3780 if (hasSpace) {
Satish Sampath565505b2009-05-29 15:37:27 +01003781 // FIXME: Is this the correct place to add to searches?
3782 // what if someone else calls this function?
3783 int shortcut = parseUrlShortcut(inUrl);
3784 if (shortcut != SHORTCUT_INVALID) {
3785 Browser.addSearchUrl(mResolver, inUrl);
3786 String query = inUrl.substring(2);
3787 switch (shortcut) {
3788 case SHORTCUT_GOOGLE_SEARCH:
Grace Kloba47fdfdb2009-06-30 11:15:34 -07003789 return URLUtil.composeSearchUrl(query, QuickSearch_G, QUERY_PLACE_HOLDER);
Satish Sampath565505b2009-05-29 15:37:27 +01003790 case SHORTCUT_WIKIPEDIA_SEARCH:
3791 return URLUtil.composeSearchUrl(query, QuickSearch_W, QUERY_PLACE_HOLDER);
3792 case SHORTCUT_DICTIONARY_SEARCH:
3793 return URLUtil.composeSearchUrl(query, QuickSearch_D, QUERY_PLACE_HOLDER);
3794 case SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH:
The Android Open Source Project0c908882009-03-03 19:32:16 -08003795 // FIXME: we need location in this case
Satish Sampath565505b2009-05-29 15:37:27 +01003796 return URLUtil.composeSearchUrl(query, QuickSearch_L, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003797 }
3798 }
3799 } else {
Dan Egnor5ee906c2009-11-18 12:11:49 -08003800 if (Patterns.WEB_URL.matcher(inUrl).matches()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003801 return URLUtil.guessUrl(inUrl);
3802 }
3803 }
3804
3805 Browser.addSearchUrl(mResolver, inUrl);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07003806 return URLUtil.composeSearchUrl(inUrl, QuickSearch_G, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003807 }
3808
Ben Murdochbff2d602009-07-01 20:19:05 +01003809 /* package */ void setShouldShowErrorConsole(boolean flag) {
3810 if (flag == mShouldShowErrorConsole) {
3811 // Nothing to do.
3812 return;
3813 }
3814
3815 mShouldShowErrorConsole = flag;
3816
Grace Kloba22ac16e2009-10-07 18:00:23 -07003817 ErrorConsoleView errorConsole = mTabControl.getCurrentTab()
3818 .getErrorConsole(true);
Ben Murdochbff2d602009-07-01 20:19:05 +01003819
3820 if (flag) {
3821 // Setting the show state of the console will cause it's the layout to be inflated.
3822 if (errorConsole.numberOfErrors() > 0) {
3823 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
3824 } else {
3825 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
3826 }
3827
3828 // Now we can add it to the main view.
3829 mErrorConsoleContainer.addView(errorConsole,
Romain Guy15b8ec62010-01-08 15:06:43 -08003830 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
Ben Murdochbff2d602009-07-01 20:19:05 +01003831 ViewGroup.LayoutParams.WRAP_CONTENT));
3832 } else {
3833 mErrorConsoleContainer.removeView(errorConsole);
3834 }
3835
3836 }
3837
Grace Kloba22ac16e2009-10-07 18:00:23 -07003838 boolean shouldShowErrorConsole() {
3839 return mShouldShowErrorConsole;
3840 }
3841
Andrei Popescu163ab742009-10-20 17:58:23 +01003842 private void setStatusBarVisibility(boolean visible) {
3843 int flag = visible ? 0 : WindowManager.LayoutParams.FLAG_FULLSCREEN;
3844 getWindow().setFlags(flag, WindowManager.LayoutParams.FLAG_FULLSCREEN);
3845 }
3846
Andrei Popescu56199cc2010-01-12 22:39:16 +00003847
3848 private void sendNetworkType(String type, String subtype) {
3849 WebView w = mTabControl.getCurrentWebView();
3850 if (w != null) {
3851 w.setNetworkType(type, subtype);
3852 }
3853 }
3854
Andrei Popescu30995e72010-02-09 16:59:58 +00003855 private void packageChanged(String packageName, boolean wasAdded) {
3856 WebView w = mTabControl.getCurrentWebView();
3857 if (w == null) {
3858 return;
3859 }
3860
3861 if (wasAdded) {
3862 w.addPackageName(packageName);
3863 } else {
3864 w.removePackageName(packageName);
3865 }
3866 }
3867
3868 private void addPackageNames(Set<String> packageNames) {
3869 WebView w = mTabControl.getCurrentWebView();
3870 if (w == null) {
3871 return;
3872 }
3873
3874 w.addPackageNames(packageNames);
3875 }
3876
3877 private void getInstalledPackages() {
3878 AsyncTask<Void, Void, Set<String> > task =
3879 new AsyncTask<Void, Void, Set<String> >() {
3880 protected Set<String> doInBackground(Void... unused) {
3881 Set<String> installedPackages = new HashSet<String>();
3882 PackageManager pm = BrowserActivity.this.getPackageManager();
3883 if (pm != null) {
3884 List<PackageInfo> packages = pm.getInstalledPackages(0);
3885 for (PackageInfo p : packages) {
3886 if (BrowserActivity.this.sGoogleApps.contains(p.packageName)) {
3887 installedPackages.add(p.packageName);
3888 }
3889 }
3890 }
3891
3892 return installedPackages;
3893 }
3894
3895 // Executes on the UI thread
3896 protected void onPostExecute(Set<String> installedPackages) {
3897 addPackageNames(installedPackages);
3898 }
3899 };
3900 task.execute();
3901 }
3902
Grace Klobaeb6eef42009-09-15 17:56:32 -07003903 final static int LOCK_ICON_UNSECURE = 0;
3904 final static int LOCK_ICON_SECURE = 1;
3905 final static int LOCK_ICON_MIXED = 2;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003906
The Android Open Source Project0c908882009-03-03 19:32:16 -08003907 private BrowserSettings mSettings;
3908 private TabControl mTabControl;
3909 private ContentResolver mResolver;
3910 private FrameLayout mContentView;
Andrei Popescuadc008d2009-06-26 14:11:30 +01003911 private View mCustomView;
3912 private FrameLayout mCustomViewContainer;
Andrei Popescuc9b55562009-07-07 10:51:15 +01003913 private WebChromeClient.CustomViewCallback mCustomViewCallback;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003914
3915 // FIXME, temp address onPrepareMenu performance problem. When we move everything out of
3916 // view, we should rewrite this.
3917 private int mCurrentMenuState = 0;
3918 private int mMenuState = R.id.MAIN_MENU;
Andrei Popescuadc008d2009-06-26 14:11:30 +01003919 private int mOldMenuState = EMPTY_MENU;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003920 private static final int EMPTY_MENU = -1;
3921 private Menu mMenu;
3922
3923 private FindDialog mFindDialog;
3924 // Used to prevent chording to result in firing two shortcuts immediately
3925 // one after another. Fixes bug 1211714.
3926 boolean mCanChord;
3927
3928 private boolean mInLoad;
3929 private boolean mIsNetworkUp;
Ben Murdochb7cc8b42009-09-28 10:59:09 +01003930 private boolean mDidStopLoad;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003931
Cary Clark1f10cbf2010-03-22 11:45:23 -04003932 /* package */ boolean mActivityInPause = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003933
3934 private boolean mMenuIsDown;
3935
The Android Open Source Project0c908882009-03-03 19:32:16 -08003936 private static boolean mInTrace;
3937
3938 // Performance probe
3939 private static final int[] SYSTEM_CPU_FORMAT = new int[] {
3940 Process.PROC_SPACE_TERM | Process.PROC_COMBINE,
3941 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 1: user time
3942 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 2: nice time
3943 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 3: sys time
3944 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 4: idle time
3945 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 5: iowait time
3946 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 6: irq time
3947 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG // 7: softirq time
3948 };
3949
3950 private long mStart;
3951 private long mProcessStart;
3952 private long mUserStart;
3953 private long mSystemStart;
3954 private long mIdleStart;
3955 private long mIrqStart;
3956
3957 private long mUiStart;
3958
3959 private Drawable mMixLockIcon;
3960 private Drawable mSecLockIcon;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003961
3962 /* hold a ref so we can auto-cancel if necessary */
3963 private AlertDialog mAlertDialog;
3964
The Android Open Source Project0c908882009-03-03 19:32:16 -08003965 // The up-to-date URL and title (these can be different from those stored
3966 // in WebView, since it takes some time for the information in WebView to
3967 // get updated)
3968 private String mUrl;
3969 private String mTitle;
3970
3971 // As PageInfo has different style for landscape / portrait, we have
3972 // to re-open it when configuration changed
3973 private AlertDialog mPageInfoDialog;
Grace Kloba22ac16e2009-10-07 18:00:23 -07003974 private Tab mPageInfoView;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003975 // If the Page-Info dialog is launched from the SSL-certificate-on-error
3976 // dialog, we should not just dismiss it, but should get back to the
3977 // SSL-certificate-on-error dialog. This flag is used to store this state
Leon Scrogginsc7b92f82010-01-11 18:17:31 -05003978 private boolean mPageInfoFromShowSSLCertificateOnError;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003979
3980 // as SSLCertificateOnError has different style for landscape / portrait,
3981 // we have to re-open it when configuration changed
3982 private AlertDialog mSSLCertificateOnErrorDialog;
3983 private WebView mSSLCertificateOnErrorView;
3984 private SslErrorHandler mSSLCertificateOnErrorHandler;
3985 private SslError mSSLCertificateOnErrorError;
3986
3987 // as SSLCertificate has different style for landscape / portrait, we
3988 // have to re-open it when configuration changed
3989 private AlertDialog mSSLCertificateDialog;
Grace Kloba22ac16e2009-10-07 18:00:23 -07003990 private Tab mSSLCertificateView;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003991
3992 // as HttpAuthentication has different style for landscape / portrait, we
3993 // have to re-open it when configuration changed
3994 private AlertDialog mHttpAuthenticationDialog;
3995 private HttpAuthHandler mHttpAuthHandler;
3996
3997 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_PARAMS =
3998 new FrameLayout.LayoutParams(
Romain Guy15b8ec62010-01-08 15:06:43 -08003999 ViewGroup.LayoutParams.MATCH_PARENT,
4000 ViewGroup.LayoutParams.MATCH_PARENT);
Andrei Popescuadc008d2009-06-26 14:11:30 +01004001 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_GRAVITY_CENTER =
4002 new FrameLayout.LayoutParams(
Romain Guy15b8ec62010-01-08 15:06:43 -08004003 ViewGroup.LayoutParams.MATCH_PARENT,
4004 ViewGroup.LayoutParams.MATCH_PARENT,
Andrei Popescuadc008d2009-06-26 14:11:30 +01004005 Gravity.CENTER);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07004006 // Google search
4007 final static String QuickSearch_G = "http://www.google.com/m?q=%s";
The Android Open Source Project0c908882009-03-03 19:32:16 -08004008 // Wikipedia search
4009 final static String QuickSearch_W = "http://en.wikipedia.org/w/index.php?search=%s&go=Go";
4010 // Dictionary search
4011 final static String QuickSearch_D = "http://dictionary.reference.com/search?q=%s";
4012 // Google Mobile Local search
4013 final static String QuickSearch_L = "http://www.google.com/m/search?site=local&q=%s&near=mountain+view";
4014
4015 final static String QUERY_PLACE_HOLDER = "%s";
4016
4017 // "source" parameter for Google search through search key
4018 final static String GOOGLE_SEARCH_SOURCE_SEARCHKEY = "browser-key";
4019 // "source" parameter for Google search through goto menu
4020 final static String GOOGLE_SEARCH_SOURCE_GOTO = "browser-goto";
4021 // "source" parameter for Google search through simplily type
4022 final static String GOOGLE_SEARCH_SOURCE_TYPE = "browser-type";
4023 // "source" parameter for Google search suggested by the browser
4024 final static String GOOGLE_SEARCH_SOURCE_SUGGEST = "browser-suggest";
4025 // "source" parameter for Google search from unknown source
4026 final static String GOOGLE_SEARCH_SOURCE_UNKNOWN = "unknown";
4027
4028 private final static String LOGTAG = "browser";
4029
The Android Open Source Project0c908882009-03-03 19:32:16 -08004030 private String mLastEnteredUrl;
4031
4032 private PowerManager.WakeLock mWakeLock;
4033 private final static int WAKELOCK_TIMEOUT = 5 * 60 * 1000; // 5 minutes
4034
4035 private Toast mStopToast;
4036
Leon Scroggins571b3762010-05-26 10:25:01 -04004037 private TitleBarBase mTitleBar;
Leon Scroggins81db3662009-06-04 17:45:11 -04004038
Ben Murdochbff2d602009-07-01 20:19:05 +01004039 private LinearLayout mErrorConsoleContainer = null;
4040 private boolean mShouldShowErrorConsole = false;
4041
The Android Open Source Project0c908882009-03-03 19:32:16 -08004042 // As the ids are dynamically created, we can't guarantee that they will
4043 // be in sequence, so this static array maps ids to a window number.
4044 final static private int[] WINDOW_SHORTCUT_ID_ARRAY =
4045 { R.id.window_one_menu_id, R.id.window_two_menu_id, R.id.window_three_menu_id,
4046 R.id.window_four_menu_id, R.id.window_five_menu_id, R.id.window_six_menu_id,
4047 R.id.window_seven_menu_id, R.id.window_eight_menu_id };
4048
4049 // monitor platform changes
4050 private IntentFilter mNetworkStateChangedFilter;
4051 private BroadcastReceiver mNetworkStateIntentReceiver;
4052
Grace Klobab4da0ad2009-05-14 14:45:40 -07004053 private BroadcastReceiver mPackageInstallationReceiver;
4054
Bjorn Bringerta7611812010-03-24 11:12:02 +00004055 private SystemAllowGeolocationOrigins mSystemAllowGeolocationOrigins;
4056
The Android Open Source Project0c908882009-03-03 19:32:16 -08004057 // activity requestCode
Nicolas Roard78a98e42009-05-11 13:34:17 +01004058 final static int COMBO_PAGE = 1;
4059 final static int DOWNLOAD_PAGE = 2;
4060 final static int PREFERENCES_PAGE = 3;
Leon Scroggins8d5fa432009-10-02 15:55:59 -04004061 final static int FILE_SELECTED = 4;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004062
Andrei Popescu540035d2009-09-18 18:59:20 +01004063 // the default <video> poster
4064 private Bitmap mDefaultVideoPoster;
4065 // the video progress view
4066 private View mVideoProgressView;
4067
Andrei Popescu30995e72010-02-09 16:59:58 +00004068 // The Google packages we monitor for the navigator.isApplicationInstalled()
4069 // API. Add as needed.
4070 private static Set<String> sGoogleApps;
4071 static {
4072 sGoogleApps = new HashSet<String>();
4073 sGoogleApps.add("com.google.android.youtube");
4074 }
4075
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004076 /**
4077 * A UrlData class to abstract how the content will be set to WebView.
4078 * This base class uses loadUrl to show the content.
4079 */
Leon Scroggins6eac63e2010-03-15 18:19:14 -04004080 /* package */ static class UrlData {
Grace Kloba068e48b2010-01-26 18:11:27 -08004081 final String mUrl;
4082 final Map<String, String> mHeaders;
Leon Scroggins58d56c62010-01-28 15:12:40 -05004083 final Intent mVoiceIntent;
Grace Kloba60e095c2009-06-16 11:50:55 -07004084
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004085 UrlData(String url) {
4086 this.mUrl = url;
Grace Kloba068e48b2010-01-26 18:11:27 -08004087 this.mHeaders = null;
Leon Scroggins58d56c62010-01-28 15:12:40 -05004088 this.mVoiceIntent = null;
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004089 }
Grace Kloba60e095c2009-06-16 11:50:55 -07004090
Leon Scroggins58d56c62010-01-28 15:12:40 -05004091 UrlData(String url, Map<String, String> headers, Intent intent) {
Grace Kloba068e48b2010-01-26 18:11:27 -08004092 this.mUrl = url;
4093 this.mHeaders = headers;
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -05004094 if (RecognizerResultsIntent.ACTION_VOICE_SEARCH_RESULTS
4095 .equals(intent.getAction())) {
Leon Scroggins58d56c62010-01-28 15:12:40 -05004096 this.mVoiceIntent = intent;
4097 } else {
4098 this.mVoiceIntent = null;
4099 }
Grace Kloba60e095c2009-06-16 11:50:55 -07004100 }
4101
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004102 boolean isEmpty() {
Leon Scroggins58d56c62010-01-28 15:12:40 -05004103 return mVoiceIntent == null && (mUrl == null || mUrl.length() == 0);
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004104 }
4105
Leon Scroggins92472e82010-02-17 16:32:28 -05004106 /**
4107 * Load this UrlData into the given Tab. Use loadUrlDataIn to update
4108 * the title bar as well.
4109 */
Leon Scroggins58d56c62010-01-28 15:12:40 -05004110 public void loadIn(Tab t) {
4111 if (mVoiceIntent != null) {
4112 t.activateVoiceSearchMode(mVoiceIntent);
4113 } else {
4114 t.getWebView().loadUrl(mUrl, mHeaders);
4115 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004116 }
4117 };
4118
Leon Scroggins1f005d32009-08-10 17:36:42 -04004119 /* package */ static final UrlData EMPTY_URL_DATA = new UrlData(null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004120}