blob: b2d7d82c10c438c19b5d2d384b44e8f5845fe3bd [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 Scroggins68579392009-09-15 15:31:54 -0400223 mTitleBar = new TitleBar(this);
Leon Scrogginsd746a942010-05-19 13:21:44 -0400224 mXLargeScreenSize = (getResources().getConfiguration().screenLayout
225 & Configuration.SCREENLAYOUT_SIZE_MASK)
226 == Configuration.SCREENLAYOUT_SIZE_XLARGE;
227 if (mXLargeScreenSize) {
228 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 {
234 // mTitleBar will be always be shown in the fully loaded mode on
235 // phone
236 mTitleBar.setProgress(100);
237 // Fake title bar is not needed in xlarge layout
238 mFakeTitleBar = new TitleBar(this);
239 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800240
241 // Create the tab control and our initial tab
242 mTabControl = new TabControl(this);
243
244 // Open the icon database and retain all the bookmark urls for favicons
245 retainIconsOnStartup();
246
247 // Keep a settings instance handy.
248 mSettings = BrowserSettings.getInstance();
249 mSettings.setTabControl(mTabControl);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800250
251 PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
252 mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Browser");
253
Patrick Scott6adacc92010-03-05 08:24:51 -0500254 // Find out if the network is currently up.
255 ConnectivityManager cm = (ConnectivityManager) getSystemService(
256 Context.CONNECTIVITY_SERVICE);
257 NetworkInfo info = cm.getActiveNetworkInfo();
258 if (info != null) {
259 mIsNetworkUp = info.isAvailable();
260 }
261
Grace Klobaa34f6862009-07-31 16:28:17 -0700262 /* enables registration for changes in network status from
263 http stack */
264 mNetworkStateChangedFilter = new IntentFilter();
265 mNetworkStateChangedFilter.addAction(
266 ConnectivityManager.CONNECTIVITY_ACTION);
267 mNetworkStateIntentReceiver = new BroadcastReceiver() {
268 @Override
269 public void onReceive(Context context, Intent intent) {
270 if (intent.getAction().equals(
271 ConnectivityManager.CONNECTIVITY_ACTION)) {
Andrei Popescue4c98462010-02-19 15:44:13 +0000272
273 NetworkInfo info = intent.getParcelableExtra(
274 ConnectivityManager.EXTRA_NETWORK_INFO);
275 String typeName = info.getTypeName();
276 String subtypeName = info.getSubtypeName();
277 sendNetworkType(typeName.toLowerCase(),
278 (subtypeName != null ? subtypeName.toLowerCase() : ""));
279
280 onNetworkToggle(info.isAvailable());
Grace Klobaa34f6862009-07-31 16:28:17 -0700281 }
282 }
283 };
284
Grace Kloba615c6c92009-08-03 10:22:44 -0700285 IntentFilter filter = new IntentFilter(Intent.ACTION_PACKAGE_ADDED);
286 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
287 filter.addDataScheme("package");
288 mPackageInstallationReceiver = new BroadcastReceiver() {
289 @Override
290 public void onReceive(Context context, Intent intent) {
291 final String action = intent.getAction();
292 final String packageName = intent.getData()
293 .getSchemeSpecificPart();
294 final boolean replacing = intent.getBooleanExtra(
295 Intent.EXTRA_REPLACING, false);
296 if (Intent.ACTION_PACKAGE_REMOVED.equals(action) && replacing) {
297 // if it is replacing, refreshPlugins() when adding
298 return;
299 }
Andrei Popescu30995e72010-02-09 16:59:58 +0000300
301 if (sGoogleApps.contains(packageName)) {
302 BrowserActivity.this.packageChanged(packageName,
303 Intent.ACTION_PACKAGE_ADDED.equals(action));
304 }
305
Grace Kloba615c6c92009-08-03 10:22:44 -0700306 PackageManager pm = BrowserActivity.this.getPackageManager();
307 PackageInfo pkgInfo = null;
308 try {
309 pkgInfo = pm.getPackageInfo(packageName,
310 PackageManager.GET_PERMISSIONS);
311 } catch (PackageManager.NameNotFoundException e) {
312 return;
313 }
314 if (pkgInfo != null) {
315 String permissions[] = pkgInfo.requestedPermissions;
316 if (permissions == null) {
317 return;
318 }
319 boolean permissionOk = false;
320 for (String permit : permissions) {
321 if (PluginManager.PLUGIN_PERMISSION.equals(permit)) {
322 permissionOk = true;
323 break;
324 }
325 }
326 if (permissionOk) {
327 PluginManager.getInstance(BrowserActivity.this)
Grace Klobae56a0f22010-05-26 17:31:02 -0700328 .refreshPlugins(true);
Grace Kloba615c6c92009-08-03 10:22:44 -0700329 }
330 }
331 }
332 };
333 registerReceiver(mPackageInstallationReceiver, filter);
334
The Android Open Source Project0c908882009-03-03 19:32:16 -0800335 if (!mTabControl.restoreState(icicle)) {
336 // clear up the thumbnail directory if we can't restore the state as
337 // none of the files in the directory are referenced any more.
338 new ClearThumbnails().execute(
339 mTabControl.getThumbnailDir().listFiles());
Grace Klobaaab3f092009-07-30 12:29:51 -0700340 // there is no quit on Android. But if we can't restore the state,
341 // we can treat it as a new Browser, remove the old session cookies.
342 CookieManager.getInstance().removeSessionCookie();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800343 final Intent intent = getIntent();
344 final Bundle extra = intent.getExtras();
345 // Create an initial tab.
346 // If the intent is ACTION_VIEW and data is not null, the Browser is
347 // invoked to view the content by another application. In this case,
348 // the tab will be close when exit.
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700349 UrlData urlData = getUrlDataFromIntent(intent);
350
Leon Scroggins58d56c62010-01-28 15:12:40 -0500351 String action = intent.getAction();
Grace Kloba22ac16e2009-10-07 18:00:23 -0700352 final Tab t = mTabControl.createNewTab(
Leon Scroggins58d56c62010-01-28 15:12:40 -0500353 (Intent.ACTION_VIEW.equals(action) &&
354 intent.getData() != null)
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -0500355 || RecognizerResultsIntent.ACTION_VOICE_SEARCH_RESULTS
356 .equals(action),
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700357 intent.getStringExtra(Browser.EXTRA_APPLICATION_ID), urlData.mUrl);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800358 mTabControl.setCurrentTab(t);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800359 attachTabToContentView(t);
360 WebView webView = t.getWebView();
361 if (extra != null) {
362 int scale = extra.getInt(Browser.INITIAL_ZOOM_LEVEL, 0);
363 if (scale > 0 && scale <= 1000) {
364 webView.setInitialScale(scale);
365 }
366 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800367
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700368 if (urlData.isEmpty()) {
Shimeng (Simon) Wang98d5fce2010-03-16 13:23:39 -0700369 loadUrl(webView, mSettings.getHomePage());
The Android Open Source Project0c908882009-03-03 19:32:16 -0800370 } else {
Patrick Scott9d53da02010-02-19 10:19:01 -0500371 loadUrlDataIn(t, urlData);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800372 }
373 } else {
374 // TabControl.restoreState() will create a new tab even if
Leon Scroggins1f005d32009-08-10 17:36:42 -0400375 // restoring the state fails.
The Android Open Source Project0c908882009-03-03 19:32:16 -0800376 attachTabToContentView(mTabControl.getCurrentTab());
377 }
Grace Kloba615c6c92009-08-03 10:22:44 -0700378
Feng Qianb3c02da2009-06-29 15:58:08 -0700379 // Read JavaScript flags if it exists.
380 String jsFlags = mSettings.getJsFlags();
381 if (jsFlags.trim().length() != 0) {
382 mTabControl.getCurrentWebView().setJsFlags(jsFlags);
383 }
Andrei Popescu30995e72010-02-09 16:59:58 +0000384 // Work out which packages are installed on the system.
385 getInstalledPackages();
Bjorn Bringerta7611812010-03-24 11:12:02 +0000386
387 // Start watching the default geolocation permissions
388 mSystemAllowGeolocationOrigins
389 = new SystemAllowGeolocationOrigins(getApplicationContext());
390 mSystemAllowGeolocationOrigins.start();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800391 }
392
Leon Scroggins58d56c62010-01-28 15:12:40 -0500393 /**
394 * Feed the previously stored results strings to the BrowserProvider so that
395 * the SearchDialog will show them instead of the standard searches.
396 * @param result String to show on the editable line of the SearchDialog.
397 */
398 /* package */ void showVoiceSearchResults(String result) {
399 ContentProviderClient client = mResolver.acquireContentProviderClient(
400 Browser.BOOKMARKS_URI);
401 ContentProvider prov = client.getLocalContentProvider();
402 BrowserProvider bp = (BrowserProvider) prov;
403 bp.setQueryResults(mTabControl.getCurrentTab().getVoiceSearchResults());
404 client.release();
405
Leon Scrogginsfbb3f152010-03-09 17:26:56 -0500406 Bundle bundle = createGoogleSearchSourceBundle(
407 GOOGLE_SEARCH_SOURCE_SEARCHKEY);
408 bundle.putBoolean(SearchManager.CONTEXT_IS_VOICE, true);
409 startSearch(result, false, bundle, false);
Leon Scroggins58d56c62010-01-28 15:12:40 -0500410 }
411
The Android Open Source Project0c908882009-03-03 19:32:16 -0800412 @Override
413 protected void onNewIntent(Intent intent) {
Grace Kloba22ac16e2009-10-07 18:00:23 -0700414 Tab current = mTabControl.getCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800415 // When a tab is closed on exit, the current tab index is set to -1.
416 // Reset before proceed as Browser requires the current tab to be set.
417 if (current == null) {
418 // Try to reset the tab in case the index was incorrect.
419 current = mTabControl.getTab(0);
420 if (current == null) {
421 // No tabs at all so just ignore this intent.
422 return;
423 }
424 mTabControl.setCurrentTab(current);
425 attachTabToContentView(current);
426 resetTitleAndIcon(current.getWebView());
427 }
428 final String action = intent.getAction();
429 final int flags = intent.getFlags();
430 if (Intent.ACTION_MAIN.equals(action) ||
431 (flags & Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY) != 0) {
432 // just resume the browser
433 return;
434 }
Leon Scrogginsb8a844d2010-03-18 15:06:15 -0400435 // In case the SearchDialog is open.
436 ((SearchManager) getSystemService(Context.SEARCH_SERVICE))
437 .stopSearch();
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -0500438 boolean activateVoiceSearch = RecognizerResultsIntent
439 .ACTION_VOICE_SEARCH_RESULTS.equals(action);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800440 if (Intent.ACTION_VIEW.equals(action)
441 || Intent.ACTION_SEARCH.equals(action)
442 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
Leon Scroggins58d56c62010-01-28 15:12:40 -0500443 || Intent.ACTION_WEB_SEARCH.equals(action)
444 || activateVoiceSearch) {
Leon Scroggins3b18ce32010-02-08 17:35:59 -0500445 if (current.isInVoiceSearchMode()) {
446 String title = current.getVoiceDisplayTitle();
447 if (title != null && title.equals(intent.getStringExtra(
448 SearchManager.QUERY))) {
449 // The user submitted the same search as the last voice
450 // search, so do nothing.
451 return;
452 }
Leon Scroggins1fe13a52010-02-09 15:31:26 -0500453 if (Intent.ACTION_SEARCH.equals(action)
454 && current.voiceSearchSourceIsGoogle()) {
455 Intent logIntent = new Intent(
456 LoggingEvents.ACTION_LOG_EVENT);
457 logIntent.putExtra(LoggingEvents.EXTRA_EVENT,
458 LoggingEvents.VoiceSearch.QUERY_UPDATED);
459 logIntent.putExtra(
460 LoggingEvents.VoiceSearch.EXTRA_QUERY_UPDATED_VALUE,
461 intent.getDataString());
462 sendBroadcast(logIntent);
463 // Note, onPageStarted will revert the voice title bar
464 // When http://b/issue?id=2379215 is fixed, we should update
465 // the title bar here.
466 }
Leon Scroggins3b18ce32010-02-08 17:35:59 -0500467 }
Satish Sampath565505b2009-05-29 15:37:27 +0100468 // If this was a search request (e.g. search query directly typed into the address bar),
469 // pass it on to the default web search provider.
470 if (handleWebSearchIntent(intent)) {
471 return;
472 }
473
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700474 UrlData urlData = getUrlDataFromIntent(intent);
475 if (urlData.isEmpty()) {
476 urlData = new UrlData(mSettings.getHomePage());
The Android Open Source Project0c908882009-03-03 19:32:16 -0800477 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700478
Grace Klobacc634032009-07-28 15:58:19 -0700479 final String appId = intent
480 .getStringExtra(Browser.EXTRA_APPLICATION_ID);
Leon Scroggins47208682010-04-07 17:59:48 -0400481 if ((Intent.ACTION_VIEW.equals(action)
482 // If a voice search has no appId, it means that it came
483 // from the browser. In that case, reuse the current tab.
484 || (activateVoiceSearch && appId != null))
Grace Klobacc634032009-07-28 15:58:19 -0700485 && !getPackageName().equals(appId)
486 && (flags & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0) {
Grace Kloba22ac16e2009-10-07 18:00:23 -0700487 Tab appTab = mTabControl.getTabFromId(appId);
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700488 if (appTab != null) {
489 Log.i(LOGTAG, "Reusing tab for " + appId);
490 // Dismiss the subwindow if applicable.
491 dismissSubWindow(appTab);
492 // Since we might kill the WebView, remove it from the
493 // content view first.
494 removeTabFromContentView(appTab);
495 // Recreate the main WebView after destroying the old one.
496 // If the WebView has the same original url and is on that
497 // page, it can be reused.
498 boolean needsLoad =
Leon Scroggins6eac63e2010-03-15 18:19:14 -0400499 mTabControl.recreateWebView(appTab, urlData);
Ben Murdochbff2d602009-07-01 20:19:05 +0100500
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700501 if (current != appTab) {
Leon Scroggins1f005d32009-08-10 17:36:42 -0400502 switchToTab(mTabControl.getTabIndex(appTab));
503 if (needsLoad) {
Patrick Scott9d53da02010-02-19 10:19:01 -0500504 loadUrlDataIn(appTab, urlData);
Leon Scroggins1f005d32009-08-10 17:36:42 -0400505 }
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700506 } else {
Leon Scroggins1f005d32009-08-10 17:36:42 -0400507 // If the tab was the current tab, we have to attach
508 // it to the view system again.
509 attachTabToContentView(appTab);
510 if (needsLoad) {
Patrick Scott9d53da02010-02-19 10:19:01 -0500511 loadUrlDataIn(appTab, urlData);
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700512 }
513 }
514 return;
Patrick Scottcd115892009-07-16 09:42:58 -0400515 } else {
516 // No matching application tab, try to find a regular tab
517 // with a matching url.
518 appTab = mTabControl.findUnusedTabWithUrl(urlData.mUrl);
Leon Scroggins25515f82009-08-19 15:31:58 -0400519 if (appTab != null) {
520 if (current != appTab) {
521 switchToTab(mTabControl.getTabIndex(appTab));
522 }
523 // Otherwise, we are already viewing the correct tab.
Patrick Scottcd115892009-07-16 09:42:58 -0400524 } else {
525 // if FLAG_ACTIVITY_BROUGHT_TO_FRONT flag is on, the url
526 // will be opened in a new tab unless we have reached
527 // MAX_TABS. Then the url will be opened in the current
528 // tab. If a new tab is created, it will have "true" for
529 // exit on close.
Leon Scroggins1f005d32009-08-10 17:36:42 -0400530 openTabAndShow(urlData, true, appId);
Patrick Scottcd115892009-07-16 09:42:58 -0400531 }
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700532 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800533 } else {
Grace Kloba638d3f42009-11-23 10:35:04 -0800534 if (!urlData.isEmpty()
535 && urlData.mUrl.startsWith("about:debug")) {
536 if ("about:debug.dom".equals(urlData.mUrl)) {
537 current.getWebView().dumpDomTree(false);
538 } else if ("about:debug.dom.file".equals(urlData.mUrl)) {
539 current.getWebView().dumpDomTree(true);
540 } else if ("about:debug.render".equals(urlData.mUrl)) {
541 current.getWebView().dumpRenderTree(false);
542 } else if ("about:debug.render.file".equals(urlData.mUrl)) {
543 current.getWebView().dumpRenderTree(true);
544 } else if ("about:debug.display".equals(urlData.mUrl)) {
545 current.getWebView().dumpDisplayTree();
Mike Reed9b78e1d2010-01-13 14:40:52 -0800546 } else if (urlData.mUrl.startsWith("about:debug.drag")) {
547 int index = urlData.mUrl.codePointAt(16) - '0';
548 if (index <= 0 || index > 9) {
549 current.getWebView().setDragTracker(null);
550 } else {
551 current.getWebView().setDragTracker(new MeshTracker(index));
552 }
Grace Kloba638d3f42009-11-23 10:35:04 -0800553 } else {
554 mSettings.toggleDebugSettings();
555 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800556 return;
557 }
Leon Scroggins1f005d32009-08-10 17:36:42 -0400558 // Get rid of the subwindow if it exists
559 dismissSubWindow(current);
Leon Scroggins8588d152010-04-15 11:01:53 -0400560 // If the current Tab is being used as an application tab,
561 // remove the association, since the new Intent means that it is
562 // no longer associated with that application.
563 current.setAppId(null);
Patrick Scott9d53da02010-02-19 10:19:01 -0500564 loadUrlDataIn(current, urlData);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800565 }
566 }
567 }
568
Satish Sampath565505b2009-05-29 15:37:27 +0100569 private int parseUrlShortcut(String url) {
570 if (url == null) return SHORTCUT_INVALID;
571
572 // FIXME: quick search, need to be customized by setting
573 if (url.length() > 2 && url.charAt(1) == ' ') {
574 switch (url.charAt(0)) {
575 case 'g': return SHORTCUT_GOOGLE_SEARCH;
576 case 'w': return SHORTCUT_WIKIPEDIA_SEARCH;
577 case 'd': return SHORTCUT_DICTIONARY_SEARCH;
578 case 'l': return SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH;
579 }
580 }
581 return SHORTCUT_INVALID;
582 }
583
584 /**
585 * Launches the default web search activity with the query parameters if the given intent's data
586 * are identified as plain search terms and not URLs/shortcuts.
587 * @return true if the intent was handled and web search activity was launched, false if not.
588 */
589 private boolean handleWebSearchIntent(Intent intent) {
590 if (intent == null) return false;
591
592 String url = null;
593 final String action = intent.getAction();
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -0500594 if (RecognizerResultsIntent.ACTION_VOICE_SEARCH_RESULTS.equals(
595 action)) {
Leon Scroggins58d56c62010-01-28 15:12:40 -0500596 return false;
597 }
Satish Sampath565505b2009-05-29 15:37:27 +0100598 if (Intent.ACTION_VIEW.equals(action)) {
Grace Kloba1e705052009-09-29 13:13:36 -0700599 Uri data = intent.getData();
600 if (data != null) url = data.toString();
Satish Sampath565505b2009-05-29 15:37:27 +0100601 } else if (Intent.ACTION_SEARCH.equals(action)
602 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
603 || Intent.ACTION_WEB_SEARCH.equals(action)) {
604 url = intent.getStringExtra(SearchManager.QUERY);
605 }
Bjorn Bringert04851702009-09-22 10:36:01 +0100606 return handleWebSearchRequest(url, intent.getBundleExtra(SearchManager.APP_DATA),
607 intent.getStringExtra(SearchManager.EXTRA_DATA_KEY));
Satish Sampath565505b2009-05-29 15:37:27 +0100608 }
609
610 /**
611 * Launches the default web search activity with the query parameters if the given url string
612 * was identified as plain search terms and not URL/shortcut.
613 * @return true if the request was handled and web search activity was launched, false if not.
614 */
Bjorn Bringert04851702009-09-22 10:36:01 +0100615 private boolean handleWebSearchRequest(String inUrl, Bundle appData, String extraData) {
Satish Sampath565505b2009-05-29 15:37:27 +0100616 if (inUrl == null) return false;
617
618 // In general, we shouldn't modify URL from Intent.
619 // But currently, we get the user-typed URL from search box as well.
620 String url = fixUrl(inUrl).trim();
621
622 // URLs and site specific search shortcuts are handled by the regular flow of control, so
623 // return early.
Dan Egnor5ee906c2009-11-18 12:11:49 -0800624 if (Patterns.WEB_URL.matcher(url).matches()
Satish Sampathbc5b9f32009-06-04 18:21:40 +0100625 || ACCEPTED_URI_SCHEMA.matcher(url).matches()
Satish Sampath565505b2009-05-29 15:37:27 +0100626 || parseUrlShortcut(url) != SHORTCUT_INVALID) {
627 return false;
628 }
629
Leon Scroggins8d06e362010-03-24 14:45:57 -0400630 final ContentResolver cr = mResolver;
631 final String newUrl = url;
632 new AsyncTask<Void, Void, Void>() {
633 protected Void doInBackground(Void... unused) {
634 Browser.updateVisitedHistory(cr, newUrl, false);
635 Browser.addSearchUrl(cr, newUrl);
636 return null;
637 }
638 }.execute();
Satish Sampath565505b2009-05-29 15:37:27 +0100639
640 Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);
641 intent.addCategory(Intent.CATEGORY_DEFAULT);
642 intent.putExtra(SearchManager.QUERY, url);
Satish Sampath15e9f2d2009-06-23 22:29:49 +0100643 if (appData != null) {
644 intent.putExtra(SearchManager.APP_DATA, appData);
645 }
Bjorn Bringert04851702009-09-22 10:36:01 +0100646 if (extraData != null) {
647 intent.putExtra(SearchManager.EXTRA_DATA_KEY, extraData);
648 }
Grace Klobacc634032009-07-28 15:58:19 -0700649 intent.putExtra(Browser.EXTRA_APPLICATION_ID, getPackageName());
Satish Sampath565505b2009-05-29 15:37:27 +0100650 startActivity(intent);
651
652 return true;
653 }
654
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700655 private UrlData getUrlDataFromIntent(Intent intent) {
Leon Scroggins58d56c62010-01-28 15:12:40 -0500656 String url = "";
Grace Kloba068e48b2010-01-26 18:11:27 -0800657 Map<String, String> headers = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800658 if (intent != null) {
659 final String action = intent.getAction();
660 if (Intent.ACTION_VIEW.equals(action)) {
661 url = smartUrlFilter(intent.getData());
662 if (url != null && url.startsWith("content:")) {
663 /* Append mimetype so webview knows how to display */
664 String mimeType = intent.resolveType(getContentResolver());
665 if (mimeType != null) {
666 url += "?" + mimeType;
667 }
668 }
Grace Kloba068e48b2010-01-26 18:11:27 -0800669 if (url != null && url.startsWith("http")) {
Grace Kloba00f54c52010-01-27 14:53:51 -0800670 final Bundle pairs = intent
671 .getBundleExtra(Browser.EXTRA_HEADERS);
Grace Kloba2d508ed2010-01-28 11:39:15 -0800672 if (pairs != null && !pairs.isEmpty()) {
Grace Kloba00f54c52010-01-27 14:53:51 -0800673 Iterator<String> iter = pairs.keySet().iterator();
Grace Kloba068e48b2010-01-26 18:11:27 -0800674 headers = new HashMap<String, String>();
Grace Kloba00f54c52010-01-27 14:53:51 -0800675 while (iter.hasNext()) {
676 String key = iter.next();
677 headers.put(key, pairs.getString(key));
Grace Kloba068e48b2010-01-26 18:11:27 -0800678 }
679 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700680 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800681 } else if (Intent.ACTION_SEARCH.equals(action)
682 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
683 || Intent.ACTION_WEB_SEARCH.equals(action)) {
684 url = intent.getStringExtra(SearchManager.QUERY);
685 if (url != null) {
686 mLastEnteredUrl = url;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800687 // In general, we shouldn't modify URL from Intent.
688 // But currently, we get the user-typed URL from search box as well.
689 url = fixUrl(url);
690 url = smartUrlFilter(url);
Leon Scroggins8d06e362010-03-24 14:45:57 -0400691 final ContentResolver cr = mResolver;
692 final String newUrl = url;
693 new AsyncTask<Void, Void, Void>() {
694 protected Void doInBackground(Void... unused) {
695 Browser.updateVisitedHistory(cr, newUrl, false);
696 return null;
697 }
698 }.execute();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800699 String searchSource = "&source=android-" + GOOGLE_SEARCH_SOURCE_SUGGEST + "&";
700 if (url.contains(searchSource)) {
701 String source = null;
702 final Bundle appData = intent.getBundleExtra(SearchManager.APP_DATA);
703 if (appData != null) {
Bjorn Bringert10d1cca2010-02-10 14:22:12 +0000704 source = appData.getString(Search.SOURCE);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800705 }
706 if (TextUtils.isEmpty(source)) {
707 source = GOOGLE_SEARCH_SOURCE_UNKNOWN;
708 }
709 url = url.replace(searchSource, "&source=android-"+source+"&");
710 }
711 }
712 }
713 }
Leon Scroggins58d56c62010-01-28 15:12:40 -0500714 return new UrlData(url, headers, intent);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800715 }
Leon Scroggins58d56c62010-01-28 15:12:40 -0500716 /* package */ void showVoiceTitleBar(String title) {
717 mTitleBar.setInVoiceMode(true);
Leon Scroggins58d56c62010-01-28 15:12:40 -0500718 mTitleBar.setDisplayTitle(title);
Leon Scrogginsd746a942010-05-19 13:21:44 -0400719
720 if (!mXLargeScreenSize) {
721 mFakeTitleBar.setInVoiceMode(true);
722 mFakeTitleBar.setDisplayTitle(title);
723 }
Leon Scroggins58d56c62010-01-28 15:12:40 -0500724 }
725 /* package */ void revertVoiceTitleBar() {
726 mTitleBar.setInVoiceMode(false);
Leon Scroggins003a5dd2010-03-10 12:13:14 -0500727 mTitleBar.setDisplayTitle(mUrl);
Leon Scrogginsd746a942010-05-19 13:21:44 -0400728
729 if (!mXLargeScreenSize) {
730 mFakeTitleBar.setInVoiceMode(false);
731 mFakeTitleBar.setDisplayTitle(mUrl);
732 }
Leon Scroggins58d56c62010-01-28 15:12:40 -0500733 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800734 /* package */ static String fixUrl(String inUrl) {
Cary Clark652ff872009-09-10 13:34:44 -0400735 // FIXME: Converting the url to lower case
736 // duplicates functionality in smartUrlFilter().
737 // However, changing all current callers of fixUrl to
738 // call smartUrlFilter in addition may have unwanted
739 // consequences, and is deferred for now.
740 int colon = inUrl.indexOf(':');
741 boolean allLower = true;
742 for (int index = 0; index < colon; index++) {
743 char ch = inUrl.charAt(index);
744 if (!Character.isLetter(ch)) {
745 break;
746 }
747 allLower &= Character.isLowerCase(ch);
748 if (index == colon - 1 && !allLower) {
749 inUrl = inUrl.substring(0, colon).toLowerCase()
750 + inUrl.substring(colon);
751 }
752 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800753 if (inUrl.startsWith("http://") || inUrl.startsWith("https://"))
754 return inUrl;
755 if (inUrl.startsWith("http:") ||
756 inUrl.startsWith("https:")) {
757 if (inUrl.startsWith("http:/") || inUrl.startsWith("https:/")) {
758 inUrl = inUrl.replaceFirst("/", "//");
759 } else inUrl = inUrl.replaceFirst(":", "://");
760 }
761 return inUrl;
762 }
763
Grace Kloba22ac16e2009-10-07 18:00:23 -0700764 @Override
765 protected void onResume() {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800766 super.onResume();
Dave Bort31a6d1c2009-04-13 15:56:49 -0700767 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800768 Log.v(LOGTAG, "BrowserActivity.onResume: this=" + this);
769 }
770
771 if (!mActivityInPause) {
772 Log.e(LOGTAG, "BrowserActivity is already resumed.");
773 return;
774 }
775
Mike Reed7bfa63b2009-05-28 11:08:32 -0400776 mTabControl.resumeCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800777 mActivityInPause = false;
Mike Reed7bfa63b2009-05-28 11:08:32 -0400778 resumeWebViewTimers();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800779
780 if (mWakeLock.isHeld()) {
781 mHandler.removeMessages(RELEASE_WAKELOCK);
782 mWakeLock.release();
783 }
784
The Android Open Source Project0c908882009-03-03 19:32:16 -0800785 registerReceiver(mNetworkStateIntentReceiver,
786 mNetworkStateChangedFilter);
787 WebView.enablePlatformNotifications();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800788 }
789
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400790 /**
791 * Since the actual title bar is embedded in the WebView, and removing it
Leon Scrogginsfe87bd32009-10-06 10:10:00 -0400792 * would change its appearance, use a different TitleBar to show overlayed
793 * at the top of the screen, when the menu is open or the page is loading.
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400794 */
795 private TitleBar mFakeTitleBar;
796
797 /**
798 * Keeps track of whether the options menu is open. This is important in
799 * determining whether to show or hide the title bar overlay.
800 */
801 private boolean mOptionsMenuOpen;
802
803 /**
804 * Only meaningful when mOptionsMenuOpen is true. This variable keeps track
805 * of whether the configuration has changed. The first onMenuOpened call
806 * after a configuration change is simply a reopening of the same menu
807 * (i.e. mIconView did not change).
808 */
809 private boolean mConfigChanged;
810
811 /**
812 * Whether or not the options menu is in its smaller, icon menu form. When
813 * true, we want the title bar overlay to be up. When false, we do not.
814 * Only meaningful if mOptionsMenuOpen is true.
815 */
816 private boolean mIconView;
817
Leon Scrogginsa81a7642009-08-31 17:05:41 -0400818 @Override
819 public boolean onMenuOpened(int featureId, Menu menu) {
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400820 if (Window.FEATURE_OPTIONS_PANEL == featureId) {
821 if (mOptionsMenuOpen) {
822 if (mConfigChanged) {
823 // We do not need to make any changes to the state of the
824 // title bar, since the only thing that happened was a
825 // change in orientation
826 mConfigChanged = false;
827 } else {
828 if (mIconView) {
829 // Switching the menu to expanded view, so hide the
830 // title bar.
831 hideFakeTitleBar();
832 mIconView = false;
833 } else {
834 // Switching the menu back to icon view, so show the
835 // title bar once again.
836 showFakeTitleBar();
837 mIconView = true;
838 }
839 }
840 } else {
841 // The options menu is closed, so open it, and show the title
842 showFakeTitleBar();
843 mOptionsMenuOpen = true;
844 mConfigChanged = false;
845 mIconView = true;
846 }
847 }
Leon Scrogginsa81a7642009-08-31 17:05:41 -0400848 return true;
849 }
850
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400851 private void showFakeTitleBar() {
Leon Scrogginsd746a942010-05-19 13:21:44 -0400852 if (mXLargeScreenSize) return;
Leon Scrogginsfe87bd32009-10-06 10:10:00 -0400853 if (mFakeTitleBar.getParent() == null && mActiveTabsPage == null
Grace Kloba847c25b2010-03-30 16:00:26 -0700854 && !mActivityInPause) {
855 WebView mainView = mTabControl.getCurrentWebView();
856 // if there is no current WebView, don't show the faked title bar;
Grace Kloba65190702010-04-02 23:37:26 -0700857 if (mainView == null) {
Cary Clarka0464552009-09-29 13:00:45 -0400858 return;
859 }
Leon Scroggins79e36d92010-04-29 16:01:46 +0100860 // Do not need to check for null, since the current tab will have
861 // at least a main WebView, or we would have returned above.
862 if (getTopWindow().getFindIsUp()) {
863 // Do not show the fake title bar, which would cover up the
864 // FindDialog.
865 return;
866 }
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400867
868 WindowManager manager
869 = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
870
871 // Add the title bar to the window manager so it can receive touches
872 // while the menu is up
873 WindowManager.LayoutParams params
874 = new WindowManager.LayoutParams(
Romain Guy15b8ec62010-01-08 15:06:43 -0800875 ViewGroup.LayoutParams.MATCH_PARENT,
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400876 ViewGroup.LayoutParams.WRAP_CONTENT,
Grace Kloba847c25b2010-03-30 16:00:26 -0700877 WindowManager.LayoutParams.TYPE_APPLICATION,
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400878 WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
Leon Scroggins68549862009-09-21 16:02:01 -0400879 PixelFormat.TRANSLUCENT);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400880 params.gravity = Gravity.TOP;
Grace Kloba847c25b2010-03-30 16:00:26 -0700881 boolean atTop = mainView.getScrollY() == 0;
Leon Scroggins83932c72009-09-30 11:55:54 -0400882 params.windowAnimations = atTop ? 0 : R.style.TitleBar;
Grace Kloba13f9ace2010-03-18 21:44:14 -0700883 manager.addView(mFakeTitleBar, params);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400884 }
885 }
886
887 @Override
888 public void onOptionsMenuClosed(Menu menu) {
889 mOptionsMenuOpen = false;
Leon Scrogginsa27ff192009-09-14 12:58:04 -0400890 if (!mInLoad) {
891 hideFakeTitleBar();
892 } else if (!mIconView) {
893 // The page is currently loading, and we are in expanded mode, so
894 // we were not showing the menu. Show it once again. It will be
895 // removed when the page finishes.
896 showFakeTitleBar();
897 }
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400898 }
Grace Kloba22ac16e2009-10-07 18:00:23 -0700899
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400900 private void hideFakeTitleBar() {
Leon Scrogginsd746a942010-05-19 13:21:44 -0400901 if (mXLargeScreenSize || mFakeTitleBar.getParent() == null) return;
Leon Scroggins20329572009-09-23 17:42:41 -0400902 WindowManager.LayoutParams params = (WindowManager.LayoutParams)
Grace Kloba13f9ace2010-03-18 21:44:14 -0700903 mFakeTitleBar.getLayoutParams();
Leon Scroggins20329572009-09-23 17:42:41 -0400904 WebView mainView = mTabControl.getCurrentWebView();
905 // Although we decided whether or not to animate based on the current
906 // scroll position, the scroll position may have changed since the
907 // fake title bar was displayed. Make sure it has the appropriate
908 // animation/lack thereof before removing.
909 params.windowAnimations = mainView != null && mainView.getScrollY() == 0
Leon Scroggins83932c72009-09-30 11:55:54 -0400910 ? 0 : R.style.TitleBar;
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400911 WindowManager manager
912 = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
Grace Kloba13f9ace2010-03-18 21:44:14 -0700913 manager.updateViewLayout(mFakeTitleBar, params);
914 manager.removeView(mFakeTitleBar);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400915 }
916
The Android Open Source Project0c908882009-03-03 19:32:16 -0800917 /**
Leon Scrogginsc6fa1102009-09-21 10:40:01 -0400918 * Special method for the fake title bar to call when displaying its context
919 * menu, since it is in its own Window, and its parent does not show a
920 * context menu.
921 */
922 /* package */ void showTitleBarContextMenu() {
Cary Clark65f4a3c2009-09-28 17:05:06 -0400923 if (null == mTitleBar.getParent()) {
924 return;
925 }
Leon Scrogginsc6fa1102009-09-21 10:40:01 -0400926 openContextMenu(mTitleBar);
927 }
928
Leon Scrogginsb2b19f52009-10-09 16:10:00 -0400929 @Override
930 public void onContextMenuClosed(Menu menu) {
931 super.onContextMenuClosed(menu);
932 if (mInLoad) {
933 showFakeTitleBar();
934 }
935 }
936
Leon Scrogginsc6fa1102009-09-21 10:40:01 -0400937 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -0800938 * onSaveInstanceState(Bundle map)
939 * onSaveInstanceState is called right before onStop(). The map contains
940 * the saved state.
941 */
Grace Kloba22ac16e2009-10-07 18:00:23 -0700942 @Override
943 protected void onSaveInstanceState(Bundle outState) {
Dave Bort31a6d1c2009-04-13 15:56:49 -0700944 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800945 Log.v(LOGTAG, "BrowserActivity.onSaveInstanceState: this=" + this);
946 }
947 // the default implementation requires each view to have an id. As the
948 // browser handles the state itself and it doesn't use id for the views,
949 // don't call the default implementation. Otherwise it will trigger the
950 // warning like this, "couldn't save which view has focus because the
951 // focused view XXX has no id".
952
953 // Save all the tabs
954 mTabControl.saveState(outState);
955 }
956
Grace Kloba22ac16e2009-10-07 18:00:23 -0700957 @Override
958 protected void onPause() {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800959 super.onPause();
960
961 if (mActivityInPause) {
962 Log.e(LOGTAG, "BrowserActivity is already paused.");
963 return;
964 }
965
Mike Reed7bfa63b2009-05-28 11:08:32 -0400966 mTabControl.pauseCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800967 mActivityInPause = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -0400968 if (mTabControl.getCurrentIndex() >= 0 && !pauseWebViewTimers()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800969 mWakeLock.acquire();
970 mHandler.sendMessageDelayed(mHandler
971 .obtainMessage(RELEASE_WAKELOCK), WAKELOCK_TIMEOUT);
972 }
973
Leon Scrogginsa2ab6a72009-09-11 11:49:52 -0400974 // FIXME: This removes the active tabs page and resets the menu to
975 // MAIN_MENU. A better solution might be to do this work in onNewIntent
976 // but then we would need to save it in onSaveInstanceState and restore
977 // it in onCreate/onRestoreInstanceState
978 if (mActiveTabsPage != null) {
979 removeActiveTabPage(true);
980 }
981
The Android Open Source Project0c908882009-03-03 19:32:16 -0800982 cancelStopToast();
983
984 // unregister network state listener
985 unregisterReceiver(mNetworkStateIntentReceiver);
986 WebView.disablePlatformNotifications();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800987 }
988
Grace Kloba22ac16e2009-10-07 18:00:23 -0700989 @Override
990 protected void onDestroy() {
Dave Bort31a6d1c2009-04-13 15:56:49 -0700991 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800992 Log.v(LOGTAG, "BrowserActivity.onDestroy: this=" + this);
993 }
994 super.onDestroy();
Grace Kloba0923d692009-09-23 21:37:25 -0700995
Leon Scroggins8d5fa432009-10-02 15:55:59 -0400996 if (mUploadMessage != null) {
997 mUploadMessage.onReceiveValue(null);
998 mUploadMessage = null;
999 }
1000
Grace Kloba0923d692009-09-23 21:37:25 -07001001 if (mTabControl == null) return;
1002
Grace Kloba1fc98a32009-10-21 13:23:08 -07001003 // Remove the fake title bar if it is there
1004 hideFakeTitleBar();
1005
The Android Open Source Project0c908882009-03-03 19:32:16 -08001006 // Remove the current tab and sub window
Grace Kloba22ac16e2009-10-07 18:00:23 -07001007 Tab t = mTabControl.getCurrentTab();
Patrick Scottfb5e77f2009-04-08 19:17:37 -07001008 if (t != null) {
1009 dismissSubWindow(t);
1010 removeTabFromContentView(t);
1011 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001012 // Destroy all the tabs
1013 mTabControl.destroy();
1014 WebIconDatabase.getInstance().close();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001015
Grace Klobab4da0ad2009-05-14 14:45:40 -07001016 unregisterReceiver(mPackageInstallationReceiver);
Bjorn Bringerta7611812010-03-24 11:12:02 +00001017
1018 // Stop watching the default geolocation permissions
1019 mSystemAllowGeolocationOrigins.stop();
1020 mSystemAllowGeolocationOrigins = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001021 }
1022
1023 @Override
1024 public void onConfigurationChanged(Configuration newConfig) {
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04001025 mConfigChanged = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001026 super.onConfigurationChanged(newConfig);
1027
1028 if (mPageInfoDialog != null) {
1029 mPageInfoDialog.dismiss();
1030 showPageInfo(
1031 mPageInfoView,
Leon Scrogginsc7b92f82010-01-11 18:17:31 -05001032 mPageInfoFromShowSSLCertificateOnError);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001033 }
1034 if (mSSLCertificateDialog != null) {
1035 mSSLCertificateDialog.dismiss();
1036 showSSLCertificate(
1037 mSSLCertificateView);
1038 }
1039 if (mSSLCertificateOnErrorDialog != null) {
1040 mSSLCertificateOnErrorDialog.dismiss();
1041 showSSLCertificateOnError(
1042 mSSLCertificateOnErrorView,
1043 mSSLCertificateOnErrorHandler,
1044 mSSLCertificateOnErrorError);
1045 }
1046 if (mHttpAuthenticationDialog != null) {
1047 String title = ((TextView) mHttpAuthenticationDialog
1048 .findViewById(com.android.internal.R.id.alertTitle)).getText()
1049 .toString();
1050 String name = ((TextView) mHttpAuthenticationDialog
1051 .findViewById(R.id.username_edit)).getText().toString();
1052 String password = ((TextView) mHttpAuthenticationDialog
1053 .findViewById(R.id.password_edit)).getText().toString();
1054 int focusId = mHttpAuthenticationDialog.getCurrentFocus()
1055 .getId();
1056 mHttpAuthenticationDialog.dismiss();
1057 showHttpAuthentication(mHttpAuthHandler, null, null, title,
1058 name, password, focusId);
1059 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001060 }
1061
Grace Kloba22ac16e2009-10-07 18:00:23 -07001062 @Override
1063 public void onLowMemory() {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001064 super.onLowMemory();
1065 mTabControl.freeMemory();
1066 }
1067
Cary Clarkff4d92c2010-03-25 11:17:03 -04001068 private void resumeWebViewTimers() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001069 Tab tab = mTabControl.getCurrentTab();
Cary Clarkff4d92c2010-03-25 11:17:03 -04001070 if (tab == null) return; // monkey can trigger this
Grace Kloba22ac16e2009-10-07 18:00:23 -07001071 boolean inLoad = tab.inLoad();
1072 if ((!mActivityInPause && !inLoad) || (mActivityInPause && inLoad)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001073 CookieSyncManager.getInstance().startSync();
Grace Kloba22ac16e2009-10-07 18:00:23 -07001074 WebView w = tab.getWebView();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001075 if (w != null) {
1076 w.resumeTimers();
1077 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001078 }
1079 }
1080
Mike Reed7bfa63b2009-05-28 11:08:32 -04001081 private boolean pauseWebViewTimers() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001082 Tab tab = mTabControl.getCurrentTab();
1083 boolean inLoad = tab.inLoad();
1084 if (mActivityInPause && !inLoad) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001085 CookieSyncManager.getInstance().stopSync();
1086 WebView w = mTabControl.getCurrentWebView();
1087 if (w != null) {
1088 w.pauseTimers();
1089 }
1090 return true;
1091 } else {
1092 return false;
1093 }
1094 }
1095
The Android Open Source Project0c908882009-03-03 19:32:16 -08001096 // Open the icon database and retain all the icons for visited sites.
1097 private void retainIconsOnStartup() {
1098 final WebIconDatabase db = WebIconDatabase.getInstance();
1099 db.open(getDir("icons", 0).getPath());
Leon Scroggins2c0f6112010-03-12 18:09:39 -05001100 Cursor c = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001101 try {
Leon Scroggins2c0f6112010-03-12 18:09:39 -05001102 c = Browser.getAllBookmarks(mResolver);
1103 if (c.moveToFirst()) {
1104 int urlIndex = c.getColumnIndex(Browser.BookmarkColumns.URL);
1105 do {
1106 String url = c.getString(urlIndex);
1107 db.retainIconForPageUrl(url);
1108 } while (c.moveToNext());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001109 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001110 } catch (IllegalStateException e) {
1111 Log.e(LOGTAG, "retainIconsOnStartup", e);
Leon Scroggins2c0f6112010-03-12 18:09:39 -05001112 } finally {
1113 if (c!= null) c.close();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001114 }
1115 }
1116
1117 // Helper method for getting the top window.
1118 WebView getTopWindow() {
1119 return mTabControl.getCurrentTopWebView();
1120 }
1121
Grace Kloba22ac16e2009-10-07 18:00:23 -07001122 TabControl getTabControl() {
1123 return mTabControl;
1124 }
1125
The Android Open Source Project0c908882009-03-03 19:32:16 -08001126 @Override
1127 public boolean onCreateOptionsMenu(Menu menu) {
1128 super.onCreateOptionsMenu(menu);
1129
1130 MenuInflater inflater = getMenuInflater();
1131 inflater.inflate(R.menu.browser, menu);
1132 mMenu = menu;
1133 updateInLoadMenuItems();
1134 return true;
1135 }
1136
1137 /**
1138 * As the menu can be open when loading state changes
1139 * we must manually update the state of the stop/reload menu
1140 * item
1141 */
1142 private void updateInLoadMenuItems() {
1143 if (mMenu == null) {
1144 return;
1145 }
1146 MenuItem src = mInLoad ?
1147 mMenu.findItem(R.id.stop_menu_id):
1148 mMenu.findItem(R.id.reload_menu_id);
1149 MenuItem dest = mMenu.findItem(R.id.stop_reload_menu_id);
1150 dest.setIcon(src.getIcon());
1151 dest.setTitle(src.getTitle());
1152 }
1153
1154 @Override
1155 public boolean onContextItemSelected(MenuItem item) {
1156 // chording is not an issue with context menus, but we use the same
1157 // options selector, so set mCanChord to true so we can access them.
1158 mCanChord = true;
1159 int id = item.getItemId();
Leon Scroggins96afcb12009-12-10 12:35:56 -05001160 boolean result = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001161 switch (id) {
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001162 // For the context menu from the title bar
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001163 case R.id.title_bar_copy_page_url:
Leon Scroggins96afcb12009-12-10 12:35:56 -05001164 Tab currentTab = mTabControl.getCurrentTab();
1165 if (null == currentTab) {
1166 result = false;
1167 break;
1168 }
1169 WebView mainView = currentTab.getWebView();
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001170 if (null == mainView) {
Leon Scroggins96afcb12009-12-10 12:35:56 -05001171 result = false;
1172 break;
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001173 }
Leon Scroggins96afcb12009-12-10 12:35:56 -05001174 copy(mainView.getUrl());
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001175 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001176 // -- Browser context menu
1177 case R.id.open_context_menu_id:
The Android Open Source Project0c908882009-03-03 19:32:16 -08001178 case R.id.bookmark_context_menu_id:
1179 case R.id.save_link_context_menu_id:
1180 case R.id.share_link_context_menu_id:
1181 case R.id.copy_link_context_menu_id:
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001182 final WebView webView = getTopWindow();
1183 if (null == webView) {
Leon Scroggins96afcb12009-12-10 12:35:56 -05001184 result = false;
1185 break;
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001186 }
1187 final HashMap hrefMap = new HashMap();
1188 hrefMap.put("webview", webView);
1189 final Message msg = mHandler.obtainMessage(
1190 FOCUS_NODE_HREF, id, 0, hrefMap);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001191 webView.requestFocusNodeHref(msg);
1192 break;
1193
1194 default:
1195 // For other context menus
Leon Scroggins96afcb12009-12-10 12:35:56 -05001196 result = onOptionsItemSelected(item);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001197 }
1198 mCanChord = false;
Leon Scroggins96afcb12009-12-10 12:35:56 -05001199 return result;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001200 }
1201
1202 private Bundle createGoogleSearchSourceBundle(String source) {
1203 Bundle bundle = new Bundle();
Bjorn Bringert10d1cca2010-02-10 14:22:12 +00001204 bundle.putString(Search.SOURCE, source);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001205 return bundle;
1206 }
1207
Leon Scroggins8ad29922010-02-16 12:33:55 -05001208 /* package */ void editUrl() {
Leon Scroggins68579392009-09-15 15:31:54 -04001209 if (mOptionsMenuOpen) closeOptionsMenu();
Leon Scroggins5bbe9802009-07-31 13:10:55 -04001210 String url = (getTopWindow() == null) ? null : getTopWindow().getUrl();
Grace Kloba83f47342009-07-20 10:44:31 -07001211 startSearch(mSettings.getHomePage().equals(url) ? null : url, true,
Leon Scroggins8ad29922010-02-16 12:33:55 -05001212 null, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001213 }
1214
Leon Scroggins8ad29922010-02-16 12:33:55 -05001215 /**
1216 * Overriding this to insert a local information bundle
1217 */
The Android Open Source Project0c908882009-03-03 19:32:16 -08001218 @Override
1219 public void startSearch(String initialQuery, boolean selectInitialQuery,
1220 Bundle appSearchData, boolean globalSearch) {
1221 if (appSearchData == null) {
1222 appSearchData = createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_TYPE);
1223 }
1224 super.startSearch(initialQuery, selectInitialQuery, appSearchData, globalSearch);
1225 }
1226
Leon Scroggins1f005d32009-08-10 17:36:42 -04001227 /**
1228 * Switch tabs. Called by the TitleBarSet when sliding the title bar
1229 * results in changing tabs.
Leon Scroggins160a7e72009-08-14 18:28:01 -04001230 * @param index Index of the tab to change to, as defined by
1231 * mTabControl.getTabIndex(Tab t).
1232 * @return boolean True if we successfully switched to a different tab. If
1233 * the indexth tab is null, or if that tab is the same as
1234 * the current one, return false.
Leon Scroggins1f005d32009-08-10 17:36:42 -04001235 */
Leon Scroggins160a7e72009-08-14 18:28:01 -04001236 /* package */ boolean switchToTab(int index) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001237 Tab tab = mTabControl.getTab(index);
1238 Tab currentTab = mTabControl.getCurrentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04001239 if (tab == null || tab == currentTab) {
Leon Scroggins160a7e72009-08-14 18:28:01 -04001240 return false;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001241 }
1242 if (currentTab != null) {
1243 // currentTab may be null if it was just removed. In that case,
1244 // we do not need to remove it
1245 removeTabFromContentView(currentTab);
1246 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001247 mTabControl.setCurrentTab(tab);
1248 attachTabToContentView(tab);
Grace Klobaeb6eef42009-09-15 17:56:32 -07001249 resetTitleIconAndProgress();
1250 updateLockIconToLatest();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001251 return true;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001252 }
1253
Grace Kloba22ac16e2009-10-07 18:00:23 -07001254 /* package */ Tab openTabToHomePage() {
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001255 return openTabAndShow(mSettings.getHomePage(), false, null);
1256 }
1257
Leon Scroggins1f005d32009-08-10 17:36:42 -04001258 /* package */ void closeCurrentWindow() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001259 final Tab current = mTabControl.getCurrentTab();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001260 if (mTabControl.getTabCount() == 1) {
Leon Scroggins30444232009-09-04 18:36:20 -04001261 // This is the last tab. Open a new one, with the home
1262 // page and close the current one.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001263 openTabToHomePage();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001264 closeTab(current);
Leon Scroggins160a7e72009-08-14 18:28:01 -04001265 return;
1266 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07001267 final Tab parent = current.getParentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04001268 int indexToShow = -1;
1269 if (parent != null) {
1270 indexToShow = mTabControl.getTabIndex(parent);
1271 } else {
Leon Scroggins160a7e72009-08-14 18:28:01 -04001272 final int currentIndex = mTabControl.getCurrentIndex();
1273 // Try to move to the tab to the right
1274 indexToShow = currentIndex + 1;
1275 if (indexToShow > mTabControl.getTabCount() - 1) {
1276 // Try to move to the tab to the left
1277 indexToShow = currentIndex - 1;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001278 }
1279 }
Leon Scroggins160a7e72009-08-14 18:28:01 -04001280 if (switchToTab(indexToShow)) {
1281 // Close window
1282 closeTab(current);
1283 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001284 }
1285
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001286 private ActiveTabsPage mActiveTabsPage;
1287
1288 /**
1289 * Remove the active tabs page.
1290 * @param needToAttach If true, the active tabs page did not attach a tab
1291 * to the content view, so we need to do that here.
1292 */
1293 /* package */ void removeActiveTabPage(boolean needToAttach) {
1294 mContentView.removeView(mActiveTabsPage);
Leon Scrogginsd746a942010-05-19 13:21:44 -04001295 mTitleBar.setVisibility(View.VISIBLE);
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001296 mActiveTabsPage = null;
1297 mMenuState = R.id.MAIN_MENU;
1298 if (needToAttach) {
1299 attachTabToContentView(mTabControl.getCurrentTab());
1300 }
1301 getTopWindow().requestFocus();
1302 }
1303
The Android Open Source Project0c908882009-03-03 19:32:16 -08001304 @Override
1305 public boolean onOptionsItemSelected(MenuItem item) {
1306 if (!mCanChord) {
1307 // The user has already fired a shortcut with this hold down of the
1308 // menu key.
1309 return false;
1310 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001311 if (null == getTopWindow()) {
Leon Scroggins0d7ae0e2009-06-05 11:04:45 -04001312 return false;
1313 }
Grace Kloba6ee9c492009-07-13 10:04:34 -07001314 if (mMenuIsDown) {
1315 // The shortcut action consumes the MENU. Even if it is still down,
1316 // it won't trigger the next shortcut action. In the case of the
1317 // shortcut action triggering a new activity, like Bookmarks, we
1318 // won't get onKeyUp for MENU. So it is important to reset it here.
1319 mMenuIsDown = false;
1320 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001321 switch (item.getItemId()) {
1322 // -- Main menu
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001323 case R.id.new_tab_menu_id:
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001324 openTabToHomePage();
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001325 break;
1326
Leon Scroggins64b80f32009-08-07 12:03:34 -04001327 case R.id.goto_menu_id:
Leon Scroggins8ad29922010-02-16 12:33:55 -05001328 editUrl();
Leon Scrogginsb3a5bed2009-09-28 11:21:56 -04001329 break;
1330
1331 case R.id.bookmarks_menu_id:
Leon Scroggins30444232009-09-04 18:36:20 -04001332 bookmarksOrHistoryPicker(false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001333 break;
1334
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001335 case R.id.active_tabs_menu_id:
1336 mActiveTabsPage = new ActiveTabsPage(this, mTabControl);
1337 removeTabFromContentView(mTabControl.getCurrentTab());
Leon Scrogginsd746a942010-05-19 13:21:44 -04001338 mTitleBar.setVisibility(View.GONE);
Leon Scroggins43de6162009-09-14 19:59:58 -04001339 hideFakeTitleBar();
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001340 mContentView.addView(mActiveTabsPage, COVER_SCREEN_PARAMS);
1341 mActiveTabsPage.requestFocus();
1342 mMenuState = EMPTY_MENU;
1343 break;
1344
Leon Scroggins1f005d32009-08-10 17:36:42 -04001345 case R.id.add_bookmark_menu_id:
1346 Intent i = new Intent(BrowserActivity.this,
1347 AddBookmarkPage.class);
1348 WebView w = getTopWindow();
1349 i.putExtra("url", w.getUrl());
1350 i.putExtra("title", w.getTitle());
Grace Kloba83cdb2c2009-09-16 00:48:57 -07001351 i.putExtra("touch_icon_url", w.getTouchIconUrl());
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01001352 i.putExtra("thumbnail", createScreenshot(w));
Leon Scroggins1f005d32009-08-10 17:36:42 -04001353 startActivity(i);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001354 break;
1355
1356 case R.id.stop_reload_menu_id:
1357 if (mInLoad) {
1358 stopLoading();
1359 } else {
1360 getTopWindow().reload();
1361 }
1362 break;
1363
1364 case R.id.back_menu_id:
1365 getTopWindow().goBack();
1366 break;
1367
1368 case R.id.forward_menu_id:
1369 getTopWindow().goForward();
1370 break;
1371
1372 case R.id.close_menu_id:
1373 // Close the subwindow if it exists.
1374 if (mTabControl.getCurrentSubWindow() != null) {
1375 dismissSubWindow(mTabControl.getCurrentTab());
1376 break;
1377 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001378 closeCurrentWindow();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001379 break;
1380
1381 case R.id.homepage_menu_id:
Grace Kloba22ac16e2009-10-07 18:00:23 -07001382 Tab current = mTabControl.getCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001383 if (current != null) {
1384 dismissSubWindow(current);
Leon Scroggins92472e82010-02-17 16:32:28 -05001385 loadUrl(current.getWebView(), mSettings.getHomePage());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001386 }
1387 break;
1388
1389 case R.id.preferences_menu_id:
1390 Intent intent = new Intent(this,
1391 BrowserPreferencesPage.class);
Leon Scrogginsd5304942009-12-10 16:11:39 -05001392 intent.putExtra(BrowserPreferencesPage.CURRENT_PAGE,
1393 getTopWindow().getUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001394 startActivityForResult(intent, PREFERENCES_PAGE);
1395 break;
1396
1397 case R.id.find_menu_id:
1398 if (null == mFindDialog) {
1399 mFindDialog = new FindDialog(this);
1400 }
Leon Scroggins III211ba542010-04-19 13:21:13 -04001401 // Need to do something special for Tablet
Leon Scroggins79e36d92010-04-29 16:01:46 +01001402 Tab tab = mTabControl.getCurrentTab();
1403 if (tab.getSubWebView() == null) {
1404 // If the Find is being performed on the main webview,
1405 // remove the embedded title bar.
1406 WebView mainView = tab.getWebView();
1407 if (mainView != null) {
1408 mainView.setEmbeddedTitleBar(null);
1409 }
1410 }
1411 hideFakeTitleBar();
1412 tab.showFind(mFindDialog);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001413 mMenuState = EMPTY_MENU;
1414 break;
1415
1416 case R.id.select_text_id:
1417 getTopWindow().emulateShiftHeld();
1418 break;
1419 case R.id.page_info_menu_id:
1420 showPageInfo(mTabControl.getCurrentTab(), false);
1421 break;
1422
1423 case R.id.classic_history_menu_id:
Leon Scroggins30444232009-09-04 18:36:20 -04001424 bookmarksOrHistoryPicker(true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001425 break;
1426
Leon Scroggins96afcb12009-12-10 12:35:56 -05001427 case R.id.title_bar_share_page_url:
The Android Open Source Project0c908882009-03-03 19:32:16 -08001428 case R.id.share_page_menu_id:
Leon Scroggins96afcb12009-12-10 12:35:56 -05001429 Tab currentTab = mTabControl.getCurrentTab();
1430 if (null == currentTab) {
1431 mCanChord = false;
1432 return false;
1433 }
1434 currentTab.populatePickerData();
1435 sharePage(this, currentTab.getTitle(),
1436 currentTab.getUrl(), currentTab.getFavicon(),
1437 createScreenshot(currentTab.getWebView()));
The Android Open Source Project0c908882009-03-03 19:32:16 -08001438 break;
1439
1440 case R.id.dump_nav_menu_id:
1441 getTopWindow().debugDump();
1442 break;
1443
Andrei Popescu7a8b88b2010-02-02 00:30:38 +00001444 case R.id.dump_counters_menu_id:
1445 getTopWindow().dumpV8Counters();
1446 break;
1447
The Android Open Source Project0c908882009-03-03 19:32:16 -08001448 case R.id.zoom_in_menu_id:
1449 getTopWindow().zoomIn();
1450 break;
1451
1452 case R.id.zoom_out_menu_id:
1453 getTopWindow().zoomOut();
1454 break;
1455
1456 case R.id.view_downloads_menu_id:
1457 viewDownloads(null);
1458 break;
1459
The Android Open Source Project0c908882009-03-03 19:32:16 -08001460 case R.id.window_one_menu_id:
1461 case R.id.window_two_menu_id:
1462 case R.id.window_three_menu_id:
1463 case R.id.window_four_menu_id:
1464 case R.id.window_five_menu_id:
1465 case R.id.window_six_menu_id:
1466 case R.id.window_seven_menu_id:
1467 case R.id.window_eight_menu_id:
1468 {
1469 int menuid = item.getItemId();
1470 for (int id = 0; id < WINDOW_SHORTCUT_ID_ARRAY.length; id++) {
1471 if (WINDOW_SHORTCUT_ID_ARRAY[id] == menuid) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001472 Tab desiredTab = mTabControl.getTab(id);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001473 if (desiredTab != null &&
1474 desiredTab != mTabControl.getCurrentTab()) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001475 switchToTab(id);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001476 }
1477 break;
1478 }
1479 }
1480 }
1481 break;
1482
1483 default:
1484 if (!super.onOptionsItemSelected(item)) {
1485 return false;
1486 }
1487 // Otherwise fall through.
1488 }
1489 mCanChord = false;
1490 return true;
1491 }
1492
Leon Scroggins III211ba542010-04-19 13:21:13 -04001493 /*
1494 * Remove the FindDialog.
1495 */
The Android Open Source Project0c908882009-03-03 19:32:16 -08001496 public void closeFind() {
Leon Scroggins79e36d92010-04-29 16:01:46 +01001497 Tab currentTab = mTabControl.getCurrentTab();
Leon Scroggins III211ba542010-04-19 13:21:13 -04001498 if (mFindDialog != null) {
Leon Scroggins79e36d92010-04-29 16:01:46 +01001499 currentTab.closeFind(mFindDialog);
Leon Scroggins III211ba542010-04-19 13:21:13 -04001500 mFindDialog.dismiss();
1501 }
Leon Scrogginsd746a942010-05-19 13:21:44 -04001502 if (!mXLargeScreenSize) {
1503 // If the Find was being performed in the main WebView, replace the
1504 // embedded title bar.
1505 if (currentTab.getSubWebView() == null) {
1506 WebView mainView = currentTab.getWebView();
1507 if (mainView != null) {
1508 mainView.setEmbeddedTitleBar(mTitleBar);
1509 }
Leon Scroggins79e36d92010-04-29 16:01:46 +01001510 }
1511 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001512 mMenuState = R.id.MAIN_MENU;
Leon Scroggins79e36d92010-04-29 16:01:46 +01001513 if (mInLoad) {
1514 // The title bar was hidden, because otherwise it would cover up the
1515 // find dialog. Now that the dialog has been removed, show the fake
1516 // title bar once again.
1517 showFakeTitleBar();
1518 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001519 }
1520
Grace Kloba22ac16e2009-10-07 18:00:23 -07001521 @Override
1522 public boolean onPrepareOptionsMenu(Menu menu) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001523 // This happens when the user begins to hold down the menu key, so
1524 // allow them to chord to get a shortcut.
1525 mCanChord = true;
1526 // Note: setVisible will decide whether an item is visible; while
1527 // setEnabled() will decide whether an item is enabled, which also means
1528 // whether the matching shortcut key will function.
1529 super.onPrepareOptionsMenu(menu);
1530 switch (mMenuState) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001531 case EMPTY_MENU:
1532 if (mCurrentMenuState != mMenuState) {
1533 menu.setGroupVisible(R.id.MAIN_MENU, false);
1534 menu.setGroupEnabled(R.id.MAIN_MENU, false);
1535 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001536 }
1537 break;
1538 default:
1539 if (mCurrentMenuState != mMenuState) {
1540 menu.setGroupVisible(R.id.MAIN_MENU, true);
1541 menu.setGroupEnabled(R.id.MAIN_MENU, true);
1542 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001543 }
1544 final WebView w = getTopWindow();
1545 boolean canGoBack = false;
1546 boolean canGoForward = false;
1547 boolean isHome = false;
1548 if (w != null) {
1549 canGoBack = w.canGoBack();
1550 canGoForward = w.canGoForward();
1551 isHome = mSettings.getHomePage().equals(w.getUrl());
1552 }
1553 final MenuItem back = menu.findItem(R.id.back_menu_id);
1554 back.setEnabled(canGoBack);
1555
1556 final MenuItem home = menu.findItem(R.id.homepage_menu_id);
1557 home.setEnabled(!isHome);
1558
1559 menu.findItem(R.id.forward_menu_id)
1560 .setEnabled(canGoForward);
1561
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001562 menu.findItem(R.id.new_tab_menu_id).setEnabled(
Grace Kloba22ac16e2009-10-07 18:00:23 -07001563 mTabControl.canCreateNewTab());
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001564
The Android Open Source Project0c908882009-03-03 19:32:16 -08001565 // decide whether to show the share link option
1566 PackageManager pm = getPackageManager();
1567 Intent send = new Intent(Intent.ACTION_SEND);
1568 send.setType("text/plain");
1569 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1570 menu.findItem(R.id.share_page_menu_id).setVisible(ri != null);
1571
The Android Open Source Project0c908882009-03-03 19:32:16 -08001572 boolean isNavDump = mSettings.isNavDump();
1573 final MenuItem nav = menu.findItem(R.id.dump_nav_menu_id);
1574 nav.setVisible(isNavDump);
1575 nav.setEnabled(isNavDump);
Andrei Popescu7a8b88b2010-02-02 00:30:38 +00001576
1577 boolean showDebugSettings = mSettings.showDebugSettings();
1578 final MenuItem counter = menu.findItem(R.id.dump_counters_menu_id);
1579 counter.setVisible(showDebugSettings);
1580 counter.setEnabled(showDebugSettings);
1581
The Android Open Source Project0c908882009-03-03 19:32:16 -08001582 break;
1583 }
1584 mCurrentMenuState = mMenuState;
1585 return true;
1586 }
1587
1588 @Override
1589 public void onCreateContextMenu(ContextMenu menu, View v,
1590 ContextMenuInfo menuInfo) {
Leon Scroggins4e9f89b2010-02-22 16:54:14 -05001591 if (v instanceof TitleBar) {
1592 return;
1593 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001594 WebView webview = (WebView) v;
1595 WebView.HitTestResult result = webview.getHitTestResult();
1596 if (result == null) {
1597 return;
1598 }
1599
1600 int type = result.getType();
1601 if (type == WebView.HitTestResult.UNKNOWN_TYPE) {
1602 Log.w(LOGTAG,
1603 "We should not show context menu when nothing is touched");
1604 return;
1605 }
1606 if (type == WebView.HitTestResult.EDIT_TEXT_TYPE) {
1607 // let TextView handles context menu
1608 return;
1609 }
1610
1611 // Note, http://b/issue?id=1106666 is requesting that
1612 // an inflated menu can be used again. This is not available
1613 // yet, so inflate each time (yuk!)
1614 MenuInflater inflater = getMenuInflater();
1615 inflater.inflate(R.menu.browsercontext, menu);
1616
1617 // Show the correct menu group
Leon Scroggins III9e997c72010-05-26 13:25:16 -04001618 final String extra = result.getExtra();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001619 menu.setGroupVisible(R.id.PHONE_MENU,
1620 type == WebView.HitTestResult.PHONE_TYPE);
1621 menu.setGroupVisible(R.id.EMAIL_MENU,
1622 type == WebView.HitTestResult.EMAIL_TYPE);
1623 menu.setGroupVisible(R.id.GEO_MENU,
1624 type == WebView.HitTestResult.GEO_TYPE);
1625 menu.setGroupVisible(R.id.IMAGE_MENU,
1626 type == WebView.HitTestResult.IMAGE_TYPE
1627 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1628 menu.setGroupVisible(R.id.ANCHOR_MENU,
1629 type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1630 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1631
1632 // Setup custom handling depending on the type
1633 switch (type) {
1634 case WebView.HitTestResult.PHONE_TYPE:
1635 menu.setHeaderTitle(Uri.decode(extra));
1636 menu.findItem(R.id.dial_context_menu_id).setIntent(
1637 new Intent(Intent.ACTION_VIEW, Uri
1638 .parse(WebView.SCHEME_TEL + extra)));
1639 Intent addIntent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
1640 addIntent.putExtra(Insert.PHONE, Uri.decode(extra));
Cary Clark5e335a32009-09-22 14:53:11 -04001641 addIntent.setType(ContactsContract.Contacts.CONTENT_ITEM_TYPE);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001642 menu.findItem(R.id.add_contact_context_menu_id).setIntent(
1643 addIntent);
1644 menu.findItem(R.id.copy_phone_context_menu_id).setOnMenuItemClickListener(
1645 new Copy(extra));
1646 break;
1647
1648 case WebView.HitTestResult.EMAIL_TYPE:
1649 menu.setHeaderTitle(extra);
1650 menu.findItem(R.id.email_context_menu_id).setIntent(
1651 new Intent(Intent.ACTION_VIEW, Uri
1652 .parse(WebView.SCHEME_MAILTO + extra)));
1653 menu.findItem(R.id.copy_mail_context_menu_id).setOnMenuItemClickListener(
1654 new Copy(extra));
1655 break;
1656
1657 case WebView.HitTestResult.GEO_TYPE:
1658 menu.setHeaderTitle(extra);
1659 menu.findItem(R.id.map_context_menu_id).setIntent(
1660 new Intent(Intent.ACTION_VIEW, Uri
1661 .parse(WebView.SCHEME_GEO
1662 + URLEncoder.encode(extra))));
1663 menu.findItem(R.id.copy_geo_context_menu_id).setOnMenuItemClickListener(
1664 new Copy(extra));
1665 break;
1666
1667 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1668 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
1669 TextView titleView = (TextView) LayoutInflater.from(this)
1670 .inflate(android.R.layout.browser_link_context_header,
1671 null);
1672 titleView.setText(extra);
1673 menu.setHeaderView(titleView);
1674 // decide whether to show the open link in new tab option
Leon Scroggins III9e997c72010-05-26 13:25:16 -04001675 boolean showNewTab = mTabControl.canCreateNewTab();
1676 MenuItem newTabItem
1677 = menu.findItem(R.id.open_newtab_context_menu_id);
1678 newTabItem.setVisible(showNewTab);
1679 if (showNewTab) {
1680 newTabItem.setOnMenuItemClickListener(
1681 new MenuItem.OnMenuItemClickListener() {
1682 public boolean onMenuItemClick(MenuItem item) {
1683 final Tab parent = mTabControl.getCurrentTab();
1684 final Tab newTab = openTab(extra);
1685 if (newTab != parent) {
1686 parent.addChildTab(newTab);
1687 }
1688 return true;
1689 }
1690 });
1691 }
Ben Murdochde353622009-10-12 10:29:00 +01001692 menu.findItem(R.id.bookmark_context_menu_id).setVisible(
1693 Bookmarks.urlHasAcceptableScheme(extra));
The Android Open Source Project0c908882009-03-03 19:32:16 -08001694 PackageManager pm = getPackageManager();
1695 Intent send = new Intent(Intent.ACTION_SEND);
1696 send.setType("text/plain");
1697 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1698 menu.findItem(R.id.share_link_context_menu_id).setVisible(ri != null);
1699 if (type == WebView.HitTestResult.SRC_ANCHOR_TYPE) {
1700 break;
1701 }
1702 // otherwise fall through to handle image part
1703 case WebView.HitTestResult.IMAGE_TYPE:
1704 if (type == WebView.HitTestResult.IMAGE_TYPE) {
1705 menu.setHeaderTitle(extra);
1706 }
1707 menu.findItem(R.id.view_image_context_menu_id).setIntent(
1708 new Intent(Intent.ACTION_VIEW, Uri.parse(extra)));
1709 menu.findItem(R.id.download_context_menu_id).
1710 setOnMenuItemClickListener(new Download(extra));
Ben Murdoch4f75ba22009-10-27 11:48:28 +00001711 menu.findItem(R.id.set_wallpaper_context_menu_id).
1712 setOnMenuItemClickListener(new SetAsWallpaper(extra));
The Android Open Source Project0c908882009-03-03 19:32:16 -08001713 break;
1714
1715 default:
1716 Log.w(LOGTAG, "We should not get here.");
1717 break;
1718 }
Leon Scrogginsb2b19f52009-10-09 16:10:00 -04001719 hideFakeTitleBar();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001720 }
1721
The Android Open Source Project0c908882009-03-03 19:32:16 -08001722 // Attach the given tab to the content view.
Grace Klobac928c302009-09-17 11:51:21 -07001723 // this should only be called for the current tab.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001724 private void attachTabToContentView(Tab t) {
Steve Block2bc69912009-07-30 14:45:13 +01001725 // Attach the container that contains the main WebView and any other UI
1726 // associated with the tab.
Patrick Scottd0119532009-09-17 08:00:31 -04001727 t.attachTabToContentView(mContentView);
Ben Murdochbff2d602009-07-01 20:19:05 +01001728
1729 if (mShouldShowErrorConsole) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001730 ErrorConsoleView errorConsole = t.getErrorConsole(true);
Ben Murdochbff2d602009-07-01 20:19:05 +01001731 if (errorConsole.numberOfErrors() == 0) {
1732 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
1733 } else {
1734 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
1735 }
1736
1737 mErrorConsoleContainer.addView(errorConsole,
Romain Guy15b8ec62010-01-08 15:06:43 -08001738 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
Ben Murdochbff2d602009-07-01 20:19:05 +01001739 ViewGroup.LayoutParams.WRAP_CONTENT));
1740 }
1741
Leon Scrogginsd746a942010-05-19 13:21:44 -04001742 if (!mXLargeScreenSize){
1743 WebView view = t.getWebView();
1744 view.setEmbeddedTitleBar(mTitleBar);
1745 }
Leon Scroggins58d56c62010-01-28 15:12:40 -05001746 if (t.isInVoiceSearchMode()) {
1747 showVoiceTitleBar(t.getVoiceDisplayTitle());
1748 } else {
1749 revertVoiceTitleBar();
1750 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001751 // Request focus on the top window.
1752 t.getTopWindow().requestFocus();
1753 }
1754
1755 // Attach a sub window to the main WebView of the given tab.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001756 void attachSubWindow(Tab t) {
Patrick Scottd0119532009-09-17 08:00:31 -04001757 t.attachSubWindow(mContentView);
1758 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001759 }
1760
1761 // Remove the given tab from the content view.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001762 private void removeTabFromContentView(Tab t) {
Steve Block2bc69912009-07-30 14:45:13 +01001763 // Remove the container that contains the main WebView.
Patrick Scottd0119532009-09-17 08:00:31 -04001764 t.removeTabFromContentView(mContentView);
Ben Murdochbff2d602009-07-01 20:19:05 +01001765
Grace Kloba22ac16e2009-10-07 18:00:23 -07001766 ErrorConsoleView errorConsole = t.getErrorConsole(false);
1767 if (errorConsole != null) {
1768 mErrorConsoleContainer.removeView(errorConsole);
Ben Murdochbff2d602009-07-01 20:19:05 +01001769 }
1770
Leon Scrogginsd746a942010-05-19 13:21:44 -04001771 if (!mXLargeScreenSize) {
1772 WebView view = t.getWebView();
1773 if (view != null) {
1774 view.setEmbeddedTitleBar(null);
1775 }
Leon Scrogginsbb85b902009-09-14 19:27:20 -04001776 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001777 }
1778
1779 // Remove the sub window if it exists. Also called by TabControl when the
1780 // user clicks the 'X' to dismiss a sub window.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001781 /* package */ void dismissSubWindow(Tab t) {
Patrick Scottd0119532009-09-17 08:00:31 -04001782 t.removeSubWindow(mContentView);
Grace Kloba22ac16e2009-10-07 18:00:23 -07001783 // dismiss the subwindow. This will destroy the WebView.
1784 t.dismissSubWindow();
Patrick Scottd0119532009-09-17 08:00:31 -04001785 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001786 }
1787
Leon Scroggins1f005d32009-08-10 17:36:42 -04001788 // A wrapper function of {@link #openTabAndShow(UrlData, boolean, String)}
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07001789 // that accepts url as string.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001790 private Tab openTabAndShow(String url, boolean closeOnExit, String appId) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001791 return openTabAndShow(new UrlData(url), closeOnExit, appId);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001792 }
1793
1794 // This method does a ton of stuff. It will attempt to create a new tab
1795 // if we haven't reached MAX_TABS. Otherwise it uses the current tab. If
Leon Scroggins1f005d32009-08-10 17:36:42 -04001796 // url isn't null, it will load the given url.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001797 /* package */Tab openTabAndShow(UrlData urlData, boolean closeOnExit,
1798 String appId) {
1799 final Tab currentTab = mTabControl.getCurrentTab();
1800 if (mTabControl.canCreateNewTab()) {
1801 final Tab tab = mTabControl.createNewTab(closeOnExit, appId,
1802 urlData.mUrl);
Leon Scroggins1f005d32009-08-10 17:36:42 -04001803 WebView webview = tab.getWebView();
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001804 // If the last tab was removed from the active tabs page, currentTab
1805 // will be null.
1806 if (currentTab != null) {
1807 removeTabFromContentView(currentTab);
1808 }
Patrick Scott8bbd69f2009-08-14 13:35:53 -04001809 // We must set the new tab as the current tab to reflect the old
1810 // animation behavior.
1811 mTabControl.setCurrentTab(tab);
Grace Klobaeb6eef42009-09-15 17:56:32 -07001812 attachTabToContentView(tab);
Leon Scroggins160a7e72009-08-14 18:28:01 -04001813 if (!urlData.isEmpty()) {
Patrick Scott9d53da02010-02-19 10:19:01 -05001814 loadUrlDataIn(tab, urlData);
Leon Scroggins1f005d32009-08-10 17:36:42 -04001815 }
1816 return tab;
1817 } else {
1818 // Get rid of the subwindow if it exists
1819 dismissSubWindow(currentTab);
1820 if (!urlData.isEmpty()) {
1821 // Load the given url.
Patrick Scott9d53da02010-02-19 10:19:01 -05001822 loadUrlDataIn(currentTab, urlData);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001823 }
Leon Scroggins58d56c62010-01-28 15:12:40 -05001824 return currentTab;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001825 }
1826 }
1827
Grace Kloba22ac16e2009-10-07 18:00:23 -07001828 private Tab openTab(String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001829 if (mSettings.openInBackground()) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001830 Tab t = mTabControl.createNewTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001831 if (t != null) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001832 WebView view = t.getWebView();
Leon Scroggins92472e82010-02-17 16:32:28 -05001833 loadUrl(view, url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001834 }
Grace Klobac9181842009-04-14 08:53:22 -07001835 return t;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001836 } else {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001837 return openTabAndShow(url, false, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001838 }
1839 }
1840
1841 private class Copy implements OnMenuItemClickListener {
1842 private CharSequence mText;
1843
1844 public boolean onMenuItemClick(MenuItem item) {
1845 copy(mText);
1846 return true;
1847 }
1848
1849 public Copy(CharSequence toCopy) {
1850 mText = toCopy;
1851 }
1852 }
1853
1854 private class Download implements OnMenuItemClickListener {
1855 private String mText;
1856
1857 public boolean onMenuItemClick(MenuItem item) {
1858 onDownloadStartNoStream(mText, null, null, null, -1);
1859 return true;
1860 }
1861
1862 public Download(String toDownload) {
1863 mText = toDownload;
1864 }
1865 }
1866
Ben Murdoch4f75ba22009-10-27 11:48:28 +00001867 private class SetAsWallpaper extends Thread implements
1868 OnMenuItemClickListener, DialogInterface.OnCancelListener {
1869 private URL mUrl;
1870 private ProgressDialog mWallpaperProgress;
1871 private boolean mCanceled = false;
1872
1873 public SetAsWallpaper(String url) {
1874 try {
1875 mUrl = new URL(url);
1876 } catch (MalformedURLException e) {
1877 mUrl = null;
1878 }
1879 }
1880
1881 public void onCancel(DialogInterface dialog) {
1882 mCanceled = true;
1883 }
1884
1885 public boolean onMenuItemClick(MenuItem item) {
1886 if (mUrl != null) {
1887 // The user may have tried to set a image with a large file size as their
1888 // background so it may take a few moments to perform the operation. Display
1889 // a progress spinner while it is working.
1890 mWallpaperProgress = new ProgressDialog(BrowserActivity.this);
1891 mWallpaperProgress.setIndeterminate(true);
1892 mWallpaperProgress.setMessage(getText(R.string.progress_dialog_setting_wallpaper));
1893 mWallpaperProgress.setCancelable(true);
1894 mWallpaperProgress.setOnCancelListener(this);
1895 mWallpaperProgress.show();
1896 start();
1897 }
1898 return true;
1899 }
1900
1901 public void run() {
1902 Drawable oldWallpaper = BrowserActivity.this.getWallpaper();
1903 try {
1904 // TODO: This will cause the resource to be downloaded again, when we
1905 // should in most cases be able to grab it from the cache. To fix this
1906 // we should query WebCore to see if we can access a cached version and
1907 // instead open an input stream on that. This pattern could also be used
1908 // in the download manager where the same problem exists.
1909 InputStream inputstream = mUrl.openStream();
1910 if (inputstream != null) {
1911 setWallpaper(inputstream);
1912 }
1913 } catch (IOException e) {
1914 Log.e(LOGTAG, "Unable to set new wallpaper");
1915 // Act as though the user canceled the operation so we try to
1916 // restore the old wallpaper.
1917 mCanceled = true;
1918 }
1919
1920 if (mCanceled) {
1921 // Restore the old wallpaper if the user cancelled whilst we were setting
1922 // the new wallpaper.
1923 int width = oldWallpaper.getIntrinsicWidth();
1924 int height = oldWallpaper.getIntrinsicHeight();
1925 Bitmap bm = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
1926 Canvas canvas = new Canvas(bm);
1927 oldWallpaper.setBounds(0, 0, width, height);
1928 oldWallpaper.draw(canvas);
1929 try {
1930 setWallpaper(bm);
1931 } catch (IOException e) {
1932 Log.e(LOGTAG, "Unable to restore old wallpaper.");
1933 }
1934 mCanceled = false;
1935 }
1936
1937 if (mWallpaperProgress.isShowing()) {
1938 mWallpaperProgress.dismiss();
1939 }
1940 }
1941 }
1942
The Android Open Source Project0c908882009-03-03 19:32:16 -08001943 private void copy(CharSequence text) {
1944 try {
1945 IClipboard clip = IClipboard.Stub.asInterface(ServiceManager.getService("clipboard"));
1946 if (clip != null) {
1947 clip.setClipboardText(text);
1948 }
1949 } catch (android.os.RemoteException e) {
1950 Log.e(LOGTAG, "Copy failed", e);
1951 }
1952 }
1953
1954 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08001955 * Resets the browser title-view to whatever it must be
1956 * (for example, if we had a loading error)
1957 * When we have a new page, we call resetTitle, when we
1958 * have to reset the titlebar to whatever it used to be
1959 * (for example, if the user chose to stop loading), we
1960 * call resetTitleAndRevertLockIcon.
1961 */
1962 /* package */ void resetTitleAndRevertLockIcon() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001963 mTabControl.getCurrentTab().revertLockIcon();
1964 updateLockIconToLatest();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001965 resetTitleIconAndProgress();
1966 }
1967
1968 /**
1969 * Reset the title, favicon, and progress.
1970 */
1971 private void resetTitleIconAndProgress() {
1972 WebView current = mTabControl.getCurrentWebView();
1973 if (current == null) {
1974 return;
1975 }
1976 resetTitleAndIcon(current);
1977 int progress = current.getProgress();
Grace Kloba22ac16e2009-10-07 18:00:23 -07001978 current.getWebChromeClient().onProgressChanged(current, progress);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001979 }
1980
1981 // Reset the title and the icon based on the given item.
1982 private void resetTitleAndIcon(WebView view) {
1983 WebHistoryItem item = view.copyBackForwardList().getCurrentItem();
1984 if (item != null) {
Leon Scroggins68579392009-09-15 15:31:54 -04001985 setUrlTitle(item.getUrl(), item.getTitle());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001986 setFavicon(item.getFavicon());
1987 } else {
Leon Scroggins68579392009-09-15 15:31:54 -04001988 setUrlTitle(null, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001989 setFavicon(null);
1990 }
1991 }
1992
1993 /**
1994 * Sets a title composed of the URL and the title string.
1995 * @param url The URL of the site being loaded.
1996 * @param title The title of the site being loaded.
1997 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07001998 void setUrlTitle(String url, String title) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001999 mUrl = url;
2000 mTitle = title;
2001
Leon Scroggins58d56c62010-01-28 15:12:40 -05002002 // If we are in voice search mode, the title has already been set.
2003 if (mTabControl.getCurrentTab().isInVoiceSearchMode()) return;
2004 mTitleBar.setDisplayTitle(url);
Leon Scrogginsd746a942010-05-19 13:21:44 -04002005 if (!mXLargeScreenSize) {
2006 mFakeTitleBar.setDisplayTitle(url);
2007 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002008 }
2009
2010 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08002011 * @param url The URL to build a title version of the URL from.
2012 * @return The title version of the URL or null if fails.
2013 * The title version of the URL can be either the URL hostname,
2014 * or the hostname with an "https://" prefix (for secure URLs),
2015 * or an empty string if, for example, the URL in question is a
2016 * file:// URL with no hostname.
2017 */
Leon Scroggins32e14a62009-06-11 10:26:34 -04002018 /* package */ static String buildTitleUrl(String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002019 String titleUrl = null;
2020
2021 if (url != null) {
2022 try {
2023 // parse the url string
2024 URL urlObj = new URL(url);
2025 if (urlObj != null) {
2026 titleUrl = "";
2027
2028 String protocol = urlObj.getProtocol();
2029 String host = urlObj.getHost();
2030
2031 if (host != null && 0 < host.length()) {
2032 titleUrl = host;
2033 if (protocol != null) {
2034 // if a secure site, add an "https://" prefix!
2035 if (protocol.equalsIgnoreCase("https")) {
2036 titleUrl = protocol + "://" + host;
2037 }
2038 }
2039 }
2040 }
2041 } catch (MalformedURLException e) {}
2042 }
2043
2044 return titleUrl;
2045 }
2046
2047 // Set the favicon in the title bar.
Grace Kloba22ac16e2009-10-07 18:00:23 -07002048 void setFavicon(Bitmap icon) {
Leon Scroggins68579392009-09-15 15:31:54 -04002049 mTitleBar.setFavicon(icon);
Leon Scrogginsd746a942010-05-19 13:21:44 -04002050 if (!mXLargeScreenSize) {
2051 mFakeTitleBar.setFavicon(icon);
2052 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002053 }
2054
2055 /**
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002056 * Close the tab, remove its associated title bar, and adjust mTabControl's
2057 * current tab to a valid value.
Leon Scroggins1f005d32009-08-10 17:36:42 -04002058 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07002059 /* package */ void closeTab(Tab t) {
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002060 int currentIndex = mTabControl.getCurrentIndex();
2061 int removeIndex = mTabControl.getTabIndex(t);
Leon Scroggins1f005d32009-08-10 17:36:42 -04002062 mTabControl.removeTab(t);
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002063 if (currentIndex >= removeIndex && currentIndex != 0) {
2064 currentIndex--;
2065 }
2066 mTabControl.setCurrentTab(mTabControl.getTab(currentIndex));
Andrei Popescua5bf1de2009-09-23 16:39:23 +01002067 resetTitleIconAndProgress();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002068 }
2069
Leon Scrogginsdcc5eeb2010-02-23 17:26:37 -05002070 /* package */ void goBackOnePageOrQuit() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002071 Tab current = mTabControl.getCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002072 if (current == null) {
2073 /*
2074 * Instead of finishing the activity, simply push this to the back
2075 * of the stack and let ActivityManager to choose the foreground
2076 * activity. As BrowserActivity is singleTask, it will be always the
2077 * root of the task. So we can use either true or false for
2078 * moveTaskToBack().
2079 */
2080 moveTaskToBack(true);
Grace Kloba00d85e72009-09-23 18:50:05 -07002081 return;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002082 }
2083 WebView w = current.getWebView();
2084 if (w.canGoBack()) {
2085 w.goBack();
2086 } else {
2087 // Check to see if we are closing a window that was created by
2088 // another window. If so, we switch back to that window.
Grace Kloba22ac16e2009-10-07 18:00:23 -07002089 Tab parent = current.getParentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002090 if (parent != null) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04002091 switchToTab(mTabControl.getTabIndex(parent));
2092 // Now we close the other tab
2093 closeTab(current);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002094 } else {
2095 if (current.closeOnExit()) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002096 // force the tab's inLoad() to be false as we are going to
2097 // either finish the activity or remove the tab. This will
2098 // ensure pauseWebViewTimers() taking action.
2099 mTabControl.getCurrentTab().clearInLoad();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002100 if (mTabControl.getTabCount() == 1) {
2101 finish();
2102 return;
2103 }
Mike Reed7bfa63b2009-05-28 11:08:32 -04002104 // call pauseWebViewTimers() now, we won't be able to call
2105 // it in onPause() as the WebView won't be valid.
Grace Klobaec1b5ad2009-08-18 08:42:32 -07002106 // Temporarily change mActivityInPause to be true as
2107 // pauseWebViewTimers() will do nothing if mActivityInPause
2108 // is false.
Grace Kloba918e1d72009-08-13 14:55:06 -07002109 boolean savedState = mActivityInPause;
2110 if (savedState) {
Grace Klobaec1b5ad2009-08-18 08:42:32 -07002111 Log.e(LOGTAG, "BrowserActivity is already paused "
2112 + "while handing goBackOnePageOrQuit.");
Grace Kloba918e1d72009-08-13 14:55:06 -07002113 }
2114 mActivityInPause = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -04002115 pauseWebViewTimers();
Grace Kloba918e1d72009-08-13 14:55:06 -07002116 mActivityInPause = savedState;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002117 removeTabFromContentView(current);
2118 mTabControl.removeTab(current);
2119 }
2120 /*
2121 * Instead of finishing the activity, simply push this to the back
2122 * of the stack and let ActivityManager to choose the foreground
2123 * activity. As BrowserActivity is singleTask, it will be always the
2124 * root of the task. So we can use either true or false for
2125 * moveTaskToBack().
2126 */
2127 moveTaskToBack(true);
2128 }
2129 }
2130 }
2131
Grace Kloba22ac16e2009-10-07 18:00:23 -07002132 boolean isMenuDown() {
2133 return mMenuIsDown;
2134 }
2135
Grace Kloba5942df02009-09-18 11:48:29 -07002136 @Override
2137 public boolean onKeyDown(int keyCode, KeyEvent event) {
Leon Scrogginsf65b50d2009-12-08 10:44:28 -05002138 // Even if MENU is already held down, we need to call to super to open
2139 // the IME on long press.
2140 if (KeyEvent.KEYCODE_MENU == keyCode) {
2141 mMenuIsDown = true;
2142 return super.onKeyDown(keyCode, event);
2143 }
Grace Kloba5942df02009-09-18 11:48:29 -07002144 // The default key mode is DEFAULT_KEYS_SEARCH_LOCAL. As the MENU is
2145 // still down, we don't want to trigger the search. Pretend to consume
2146 // the key and do nothing.
2147 if (mMenuIsDown) return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002148
Grace Kloba5942df02009-09-18 11:48:29 -07002149 switch(keyCode) {
Grace Kloba5942df02009-09-18 11:48:29 -07002150 case KeyEvent.KEYCODE_SPACE:
Grace Klobada0fe552009-09-22 18:17:24 -07002151 // WebView/WebTextView handle the keys in the KeyDown. As
2152 // the Activity's shortcut keys are only handled when WebView
2153 // doesn't, have to do it in onKeyDown instead of onKeyUp.
2154 if (event.isShiftPressed()) {
2155 getTopWindow().pageUp(false);
2156 } else {
2157 getTopWindow().pageDown(false);
2158 }
Grace Kloba5942df02009-09-18 11:48:29 -07002159 return true;
2160 case KeyEvent.KEYCODE_BACK:
2161 if (event.getRepeatCount() == 0) {
2162 event.startTracking();
2163 return true;
2164 } else if (mCustomView == null && mActiveTabsPage == null
2165 && event.isLongPress()) {
2166 bookmarksOrHistoryPicker(true);
2167 return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002168 }
Grace Kloba5942df02009-09-18 11:48:29 -07002169 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002170 }
Grace Kloba5942df02009-09-18 11:48:29 -07002171 return super.onKeyDown(keyCode, event);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002172 }
2173
Grace Kloba5942df02009-09-18 11:48:29 -07002174 @Override
2175 public boolean onKeyUp(int keyCode, KeyEvent event) {
2176 switch(keyCode) {
2177 case KeyEvent.KEYCODE_MENU:
2178 mMenuIsDown = false;
2179 break;
Grace Kloba5942df02009-09-18 11:48:29 -07002180 case KeyEvent.KEYCODE_BACK:
2181 if (event.isTracking() && !event.isCanceled()) {
2182 if (mCustomView != null) {
2183 // if a custom view is showing, hide it
Grace Kloba22ac16e2009-10-07 18:00:23 -07002184 mTabControl.getCurrentWebView().getWebChromeClient()
2185 .onHideCustomView();
Grace Kloba5942df02009-09-18 11:48:29 -07002186 } else if (mActiveTabsPage != null) {
2187 // if tab page is showing, hide it
2188 removeActiveTabPage(true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002189 } else {
Grace Kloba5942df02009-09-18 11:48:29 -07002190 WebView subwindow = mTabControl.getCurrentSubWindow();
2191 if (subwindow != null) {
2192 if (subwindow.canGoBack()) {
2193 subwindow.goBack();
2194 } else {
2195 dismissSubWindow(mTabControl.getCurrentTab());
2196 }
2197 } else {
2198 goBackOnePageOrQuit();
2199 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002200 }
Grace Kloba5942df02009-09-18 11:48:29 -07002201 return true;
2202 }
2203 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002204 }
Grace Kloba5942df02009-09-18 11:48:29 -07002205 return super.onKeyUp(keyCode, event);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002206 }
2207
Leon Scroggins68579392009-09-15 15:31:54 -04002208 /* package */ void stopLoading() {
Ben Murdochb7cc8b42009-09-28 10:59:09 +01002209 mDidStopLoad = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002210 resetTitleAndRevertLockIcon();
2211 WebView w = getTopWindow();
2212 w.stopLoading();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002213 // FIXME: before refactor, it is using mWebViewClient. So I keep the
2214 // same logic here. But for subwindow case, should we call into the main
2215 // WebView's onPageFinished as we never call its onPageStarted and if
2216 // the page finishes itself, we don't call onPageFinished.
2217 mTabControl.getCurrentWebView().getWebViewClient().onPageFinished(w,
2218 w.getUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08002219
2220 cancelStopToast();
2221 mStopToast = Toast
2222 .makeText(this, R.string.stopping, Toast.LENGTH_SHORT);
2223 mStopToast.show();
2224 }
2225
Grace Kloba22ac16e2009-10-07 18:00:23 -07002226 boolean didUserStopLoading() {
2227 return mDidStopLoad;
2228 }
2229
The Android Open Source Project0c908882009-03-03 19:32:16 -08002230 private void cancelStopToast() {
2231 if (mStopToast != null) {
2232 mStopToast.cancel();
2233 mStopToast = null;
2234 }
2235 }
2236
Grace Kloba22ac16e2009-10-07 18:00:23 -07002237 // called by a UI or non-UI thread to post the message
2238 public void postMessage(int what, int arg1, int arg2, Object obj,
2239 long delayMillis) {
2240 mHandler.sendMessageDelayed(mHandler.obtainMessage(what, arg1, arg2,
2241 obj), delayMillis);
2242 }
2243
2244 // called by a UI or non-UI thread to remove the message
2245 void removeMessages(int what, Object object) {
2246 mHandler.removeMessages(what, object);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002247 }
2248
2249 // public message ids
2250 public final static int LOAD_URL = 1001;
2251 public final static int STOP_LOAD = 1002;
2252
2253 // Message Ids
2254 private static final int FOCUS_NODE_HREF = 102;
Grace Kloba92c18a52009-07-31 23:48:32 -07002255 private static final int RELEASE_WAKELOCK = 107;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002256
Grace Kloba22ac16e2009-10-07 18:00:23 -07002257 static final int UPDATE_BOOKMARK_THUMBNAIL = 108;
Ben Murdoch2694e232009-09-29 09:41:11 +01002258
The Android Open Source Project0c908882009-03-03 19:32:16 -08002259 // Private handler for handling javascript and saving passwords
2260 private Handler mHandler = new Handler() {
2261
2262 public void handleMessage(Message msg) {
2263 switch (msg.what) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002264 case FOCUS_NODE_HREF:
Ben Murdoch2694e232009-09-29 09:41:11 +01002265 {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002266 String url = (String) msg.getData().get("url");
Ben Murdoch90d088c2009-11-17 18:14:04 +00002267 String title = (String) msg.getData().get("title");
The Android Open Source Project0c908882009-03-03 19:32:16 -08002268 if (url == null || url.length() == 0) {
2269 break;
2270 }
2271 HashMap focusNodeMap = (HashMap) msg.obj;
2272 WebView view = (WebView) focusNodeMap.get("webview");
2273 // Only apply the action if the top window did not change.
2274 if (getTopWindow() != view) {
2275 break;
2276 }
2277 switch (msg.arg1) {
2278 case R.id.open_context_menu_id:
2279 case R.id.view_image_context_menu_id:
Leon Scroggins92472e82010-02-17 16:32:28 -05002280 loadUrlFromContext(getTopWindow(), url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002281 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002282 case R.id.bookmark_context_menu_id:
2283 Intent intent = new Intent(BrowserActivity.this,
2284 AddBookmarkPage.class);
2285 intent.putExtra("url", url);
Ben Murdoch90d088c2009-11-17 18:14:04 +00002286 intent.putExtra("title", title);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002287 startActivity(intent);
2288 break;
2289 case R.id.share_link_context_menu_id:
Leon Scroggins3e204452010-05-10 11:06:03 -04002290 sharePage(BrowserActivity.this, title, url, null,
Leon Scroggins96afcb12009-12-10 12:35:56 -05002291 null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002292 break;
2293 case R.id.copy_link_context_menu_id:
2294 copy(url);
2295 break;
2296 case R.id.save_link_context_menu_id:
2297 case R.id.download_context_menu_id:
2298 onDownloadStartNoStream(url, null, null, null, -1);
2299 break;
2300 }
2301 break;
Ben Murdoch2694e232009-09-29 09:41:11 +01002302 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002303
2304 case LOAD_URL:
Leon Scroggins92472e82010-02-17 16:32:28 -05002305 loadUrlFromContext(getTopWindow(), (String) msg.obj);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002306 break;
2307
2308 case STOP_LOAD:
2309 stopLoading();
2310 break;
2311
The Android Open Source Project0c908882009-03-03 19:32:16 -08002312 case RELEASE_WAKELOCK:
2313 if (mWakeLock.isHeld()) {
2314 mWakeLock.release();
Grace Kloba5d0e02e2009-10-05 15:15:36 -07002315 // if we reach here, Browser should be still in the
2316 // background loading after WAKELOCK_TIMEOUT (5-min).
2317 // To avoid burning the battery, stop loading.
2318 mTabControl.stopAllLoading();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002319 }
2320 break;
Ben Murdoch2694e232009-09-29 09:41:11 +01002321
2322 case UPDATE_BOOKMARK_THUMBNAIL:
2323 WebView view = (WebView) msg.obj;
2324 if (view != null) {
2325 updateScreenshot(view);
2326 }
2327 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002328 }
2329 }
2330 };
2331
Leon Scroggins96afcb12009-12-10 12:35:56 -05002332 /**
2333 * Share a page, providing the title, url, favicon, and a screenshot. Uses
2334 * an {@link Intent} to launch the Activity chooser.
2335 * @param c Context used to launch a new Activity.
2336 * @param title Title of the page. Stored in the Intent with
Paul Westbrook03e6d392010-02-12 10:33:29 -08002337 * {@link Intent#EXTRA_SUBJECT}
Leon Scroggins96afcb12009-12-10 12:35:56 -05002338 * @param url URL of the page. Stored in the Intent with
2339 * {@link Intent#EXTRA_TEXT}
2340 * @param favicon Bitmap of the favicon for the page. Stored in the Intent
2341 * with {@link Browser#EXTRA_SHARE_FAVICON}
2342 * @param screenshot Bitmap of a screenshot of the page. Stored in the
2343 * Intent with {@link Browser#EXTRA_SHARE_SCREENSHOT}
2344 */
2345 public static final void sharePage(Context c, String title, String url,
2346 Bitmap favicon, Bitmap screenshot) {
2347 Intent send = new Intent(Intent.ACTION_SEND);
2348 send.setType("text/plain");
2349 send.putExtra(Intent.EXTRA_TEXT, url);
Paul Westbrook03e6d392010-02-12 10:33:29 -08002350 send.putExtra(Intent.EXTRA_SUBJECT, title);
Leon Scroggins96afcb12009-12-10 12:35:56 -05002351 send.putExtra(Browser.EXTRA_SHARE_FAVICON, favicon);
2352 send.putExtra(Browser.EXTRA_SHARE_SCREENSHOT, screenshot);
2353 try {
2354 c.startActivity(Intent.createChooser(send, c.getString(
2355 R.string.choosertitle_sharevia)));
2356 } catch(android.content.ActivityNotFoundException ex) {
2357 // if no app handles it, do nothing
2358 }
2359 }
2360
Leon Scroggins89c6d362009-07-15 16:54:37 -04002361 private void updateScreenshot(WebView view) {
2362 // If this is a bookmarked site, add a screenshot to the database.
2363 // FIXME: When should we update? Every time?
2364 // FIXME: Would like to make sure there is actually something to
2365 // draw, but the API for that (WebViewCore.pictureReady()) is not
2366 // currently accessible here.
Ben Murdochaac7aa62009-09-17 16:57:40 +01002367
Patrick Scottcb192b52010-04-14 14:38:55 -04002368 final Bitmap bm = createScreenshot(view);
2369 if (bm == null) {
2370 return;
Leon Scroggins89c6d362009-07-15 16:54:37 -04002371 }
Patrick Scottcb192b52010-04-14 14:38:55 -04002372
2373 final ContentResolver cr = getContentResolver();
2374 final String url = view.getUrl();
2375 final String originalUrl = view.getOriginalUrl();
2376
2377 new AsyncTask<Void, Void, Void>() {
2378 @Override
2379 protected Void doInBackground(Void... unused) {
2380 Cursor c = null;
2381 try {
2382 c = BrowserBookmarksAdapter.queryBookmarksForUrl(
2383 cr, originalUrl, url, true);
2384 if (c != null) {
2385 if (c.moveToFirst()) {
2386 ContentValues values = new ContentValues();
2387 final ByteArrayOutputStream os
2388 = new ByteArrayOutputStream();
2389 bm.compress(Bitmap.CompressFormat.PNG, 100, os);
2390 values.put(Browser.BookmarkColumns.THUMBNAIL,
2391 os.toByteArray());
2392 do {
2393 cr.update(ContentUris.withAppendedId(
2394 Browser.BOOKMARKS_URI, c.getInt(0)),
2395 values, null, null);
2396 } while (c.moveToNext());
2397 }
2398 }
2399 } catch (IllegalStateException e) {
2400 // Ignore
2401 } finally {
2402 if (c != null) c.close();
2403 }
2404 return null;
2405 }
2406 }.execute();
Leon Scroggins89c6d362009-07-15 16:54:37 -04002407 }
2408
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002409 /**
Leon Scrogginsf8551612009-09-24 16:06:02 -04002410 * Values for the size of the thumbnail created when taking a screenshot.
2411 * Lazily initialized. Instead of using these directly, use
2412 * getDesiredThumbnailWidth() or getDesiredThumbnailHeight().
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002413 */
Leon Scrogginsf8551612009-09-24 16:06:02 -04002414 private static int THUMBNAIL_WIDTH = 0;
2415 private static int THUMBNAIL_HEIGHT = 0;
2416
2417 /**
2418 * Return the desired width for thumbnail screenshots, which are stored in
2419 * the database, and used on the bookmarks screen.
2420 * @param context Context for finding out the density of the screen.
2421 * @return int desired width for thumbnail screenshot.
2422 */
2423 /* package */ static int getDesiredThumbnailWidth(Context context) {
2424 if (THUMBNAIL_WIDTH == 0) {
2425 float density = context.getResources().getDisplayMetrics().density;
2426 THUMBNAIL_WIDTH = (int) (90 * density);
2427 THUMBNAIL_HEIGHT = (int) (80 * density);
2428 }
2429 return THUMBNAIL_WIDTH;
2430 }
2431
2432 /**
2433 * Return the desired height for thumbnail screenshots, which are stored in
2434 * the database, and used on the bookmarks screen.
2435 * @param context Context for finding out the density of the screen.
2436 * @return int desired height for thumbnail screenshot.
2437 */
2438 /* package */ static int getDesiredThumbnailHeight(Context context) {
2439 // To ensure that they are both initialized.
2440 getDesiredThumbnailWidth(context);
2441 return THUMBNAIL_HEIGHT;
2442 }
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002443
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002444 private Bitmap createScreenshot(WebView view) {
2445 Picture thumbnail = view.capturePicture();
Leon Scroggins45800572009-09-29 16:38:47 -04002446 if (thumbnail == null) {
2447 return null;
2448 }
Leon Scrogginsf8551612009-09-24 16:06:02 -04002449 Bitmap bm = Bitmap.createBitmap(getDesiredThumbnailWidth(this),
Cary Clarkab168ba2010-04-08 09:11:28 -04002450 getDesiredThumbnailHeight(this), Bitmap.Config.RGB_565);
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002451 Canvas canvas = new Canvas(bm);
2452 // May need to tweak these values to determine what is the
2453 // best scale factor
Ben Murdoch2694e232009-09-29 09:41:11 +01002454 int thumbnailWidth = thumbnail.getWidth();
Ben Murdochae59c3f2009-10-20 18:30:28 +01002455 int thumbnailHeight = thumbnail.getHeight();
2456 float scaleFactorX = 1.0f;
2457 float scaleFactorY = 1.0f;
Ben Murdoch2694e232009-09-29 09:41:11 +01002458 if (thumbnailWidth > 0) {
Ben Murdochae59c3f2009-10-20 18:30:28 +01002459 scaleFactorX = (float) getDesiredThumbnailWidth(this) /
Ben Murdoch2694e232009-09-29 09:41:11 +01002460 (float)thumbnailWidth;
Ben Murdochae59c3f2009-10-20 18:30:28 +01002461 } else {
2462 return null;
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002463 }
Ben Murdochae59c3f2009-10-20 18:30:28 +01002464
2465 if (view.getWidth() > view.getHeight() &&
2466 thumbnailHeight < view.getHeight() && thumbnailHeight > 0) {
2467 // If the device is in landscape and the page is shorter
2468 // than the height of the view, stretch the thumbnail to fill the
2469 // space.
2470 scaleFactorY = (float) getDesiredThumbnailHeight(this) /
2471 (float)thumbnailHeight;
2472 } else {
2473 // In the portrait case, this looks nice.
2474 scaleFactorY = scaleFactorX;
2475 }
2476
2477 canvas.scale(scaleFactorX, scaleFactorY);
2478
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002479 thumbnail.draw(canvas);
2480 return bm;
2481 }
2482
The Android Open Source Project0c908882009-03-03 19:32:16 -08002483 // -------------------------------------------------------------------------
Grace Kloba22ac16e2009-10-07 18:00:23 -07002484 // Helper function for WebViewClient.
The Android Open Source Project0c908882009-03-03 19:32:16 -08002485 //-------------------------------------------------------------------------
2486
2487 // Use in overrideUrlLoading
2488 /* package */ final static String SCHEME_WTAI = "wtai://wp/";
2489 /* package */ final static String SCHEME_WTAI_MC = "wtai://wp/mc;";
2490 /* package */ final static String SCHEME_WTAI_SD = "wtai://wp/sd;";
2491 /* package */ final static String SCHEME_WTAI_AP = "wtai://wp/ap;";
2492
Leon Scroggins92472e82010-02-17 16:32:28 -05002493 // Keep this initial progress in sync with initialProgressValue (* 100)
2494 // in ProgressTracker.cpp
2495 private final static int INITIAL_PROGRESS = 10;
2496
Grace Kloba22ac16e2009-10-07 18:00:23 -07002497 void onPageStarted(WebView view, String url, Bitmap favicon) {
2498 // when BrowserActivity just starts, onPageStarted may be called before
2499 // onResume as it is triggered from onCreate. Call resumeWebViewTimers
2500 // to start the timer. As we won't switch tabs while an activity is in
2501 // pause state, we can ensure calling resume and pause in pair.
2502 if (mActivityInPause) resumeWebViewTimers();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002503
Grace Kloba22ac16e2009-10-07 18:00:23 -07002504 resetLockIcon(url);
2505 setUrlTitle(url, null);
2506 setFavicon(favicon);
Leon Scroggins8cf8f682009-11-04 11:13:50 -08002507 // Show some progress so that the user knows the page is beginning to
2508 // load
Leon Scroggins92472e82010-02-17 16:32:28 -05002509 onProgressChanged(view, INITIAL_PROGRESS);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002510 mDidStopLoad = false;
Grace Kloba22ac16e2009-10-07 18:00:23 -07002511 if (!mIsNetworkUp) createAndShowNetworkDialog();
Leon Scroggins III211ba542010-04-19 13:21:13 -04002512 if (view.getFindIsUp()) {
2513 closeFind();
2514 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002515 if (mSettings.isTracing()) {
2516 String host;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002517 try {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002518 WebAddress uri = new WebAddress(url);
2519 host = uri.mHost;
2520 } catch (android.net.ParseException ex) {
2521 host = "browser";
The Android Open Source Project0c908882009-03-03 19:32:16 -08002522 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002523 host = host.replace('.', '_');
2524 host += ".trace";
2525 mInTrace = true;
2526 Debug.startMethodTracing(host, 20 * 1024 * 1024);
2527 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002528
Grace Kloba22ac16e2009-10-07 18:00:23 -07002529 // Performance probe
2530 if (false) {
2531 mStart = SystemClock.uptimeMillis();
2532 mProcessStart = Process.getElapsedCpuTime();
2533 long[] sysCpu = new long[7];
2534 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2535 sysCpu, null)) {
2536 mUserStart = sysCpu[0] + sysCpu[1];
2537 mSystemStart = sysCpu[2];
2538 mIdleStart = sysCpu[3];
2539 mIrqStart = sysCpu[4] + sysCpu[5] + sysCpu[6];
2540 }
2541 mUiStart = SystemClock.currentThreadTimeMillis();
2542 }
2543 }
2544
2545 void onPageFinished(WebView view, String url) {
2546 // Reset the title and icon in case we stopped a provisional load.
2547 resetTitleAndIcon(view);
2548 // Update the lock icon image only once we are done loading
2549 updateLockIconToLatest();
2550 // pause the WebView timer and release the wake lock if it is finished
2551 // while BrowserActivity is in pause state.
2552 if (mActivityInPause && pauseWebViewTimers()) {
2553 if (mWakeLock.isHeld()) {
2554 mHandler.removeMessages(RELEASE_WAKELOCK);
2555 mWakeLock.release();
2556 }
2557 }
2558
2559 // Performance probe
2560 if (false) {
2561 long[] sysCpu = new long[7];
2562 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2563 sysCpu, null)) {
2564 String uiInfo = "UI thread used "
2565 + (SystemClock.currentThreadTimeMillis() - mUiStart)
2566 + " ms";
2567 if (LOGD_ENABLED) {
2568 Log.d(LOGTAG, uiInfo);
2569 }
2570 //The string that gets written to the log
2571 String performanceString = "It took total "
2572 + (SystemClock.uptimeMillis() - mStart)
2573 + " ms clock time to load the page."
2574 + "\nbrowser process used "
2575 + (Process.getElapsedCpuTime() - mProcessStart)
2576 + " ms, user processes used "
2577 + (sysCpu[0] + sysCpu[1] - mUserStart) * 10
2578 + " ms, kernel used "
2579 + (sysCpu[2] - mSystemStart) * 10
2580 + " ms, idle took " + (sysCpu[3] - mIdleStart) * 10
2581 + " ms and irq took "
2582 + (sysCpu[4] + sysCpu[5] + sysCpu[6] - mIrqStart)
2583 * 10 + " ms, " + uiInfo;
2584 if (LOGD_ENABLED) {
2585 Log.d(LOGTAG, performanceString + "\nWebpage: " + url);
2586 }
2587 if (url != null) {
2588 // strip the url to maintain consistency
2589 String newUrl = new String(url);
2590 if (newUrl.startsWith("http://www.")) {
2591 newUrl = newUrl.substring(11);
2592 } else if (newUrl.startsWith("http://")) {
2593 newUrl = newUrl.substring(7);
2594 } else if (newUrl.startsWith("https://www.")) {
2595 newUrl = newUrl.substring(12);
2596 } else if (newUrl.startsWith("https://")) {
2597 newUrl = newUrl.substring(8);
2598 }
2599 if (LOGD_ENABLED) {
2600 Log.d(LOGTAG, newUrl + " loaded");
2601 }
Grace Kloba5b078b52009-06-24 20:23:41 -07002602 }
2603 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002604 }
Grace Kloba5b078b52009-06-24 20:23:41 -07002605
Grace Kloba22ac16e2009-10-07 18:00:23 -07002606 if (mInTrace) {
2607 mInTrace = false;
2608 Debug.stopMethodTracing();
2609 }
2610 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002611
Grace Kloba22ac16e2009-10-07 18:00:23 -07002612 boolean shouldOverrideUrlLoading(WebView view, String url) {
2613 if (url.startsWith(SCHEME_WTAI)) {
2614 // wtai://wp/mc;number
2615 // number=string(phone-number)
2616 if (url.startsWith(SCHEME_WTAI_MC)) {
2617 Intent intent = new Intent(Intent.ACTION_VIEW,
2618 Uri.parse(WebView.SCHEME_TEL +
2619 url.substring(SCHEME_WTAI_MC.length())));
2620 startActivity(intent);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002621 return true;
2622 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002623 // wtai://wp/sd;dtmf
2624 // dtmf=string(dialstring)
2625 if (url.startsWith(SCHEME_WTAI_SD)) {
2626 // TODO: only send when there is active voice connection
2627 return false;
2628 }
2629 // wtai://wp/ap;number;name
2630 // number=string(phone-number)
2631 // name=string
2632 if (url.startsWith(SCHEME_WTAI_AP)) {
2633 // TODO
2634 return false;
2635 }
2636 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002637
Grace Kloba22ac16e2009-10-07 18:00:23 -07002638 // The "about:" schemes are internal to the browser; don't want these to
2639 // be dispatched to other apps.
2640 if (url.startsWith("about:")) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002641 return false;
2642 }
2643
Grace Kloba22ac16e2009-10-07 18:00:23 -07002644 Intent intent;
2645 // perform generic parsing of the URI to turn it into an Intent.
2646 try {
2647 intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME);
2648 } catch (URISyntaxException ex) {
2649 Log.w("Browser", "Bad URI " + url + ": " + ex.getMessage());
2650 return false;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002651 }
2652
Grace Kloba22ac16e2009-10-07 18:00:23 -07002653 // check whether the intent can be resolved. If not, we will see
2654 // whether we can download it from the Market.
2655 if (getPackageManager().resolveActivity(intent, 0) == null) {
2656 String packagename = intent.getPackage();
2657 if (packagename != null) {
2658 intent = new Intent(Intent.ACTION_VIEW, Uri
2659 .parse("market://search?q=pname:" + packagename));
2660 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2661 startActivity(intent);
2662 return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002663 } else {
2664 return false;
2665 }
2666 }
2667
Grace Kloba22ac16e2009-10-07 18:00:23 -07002668 // sanitize the Intent, ensuring web pages can not bypass browser
2669 // security (only access to BROWSABLE activities).
2670 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2671 intent.setComponent(null);
2672 try {
2673 if (startActivityIfNeeded(intent, -1)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002674 return true;
2675 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002676 } catch (ActivityNotFoundException ex) {
2677 // ignore the error. If no application can handle the URL,
2678 // eg about:blank, assume the browser can handle it.
2679 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002680
Grace Kloba22ac16e2009-10-07 18:00:23 -07002681 if (mMenuIsDown) {
2682 openTab(url);
2683 closeOptionsMenu();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002684 return true;
2685 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002686 return false;
2687 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002688
Grace Kloba22ac16e2009-10-07 18:00:23 -07002689 // -------------------------------------------------------------------------
2690 // Helper function for WebChromeClient
2691 // -------------------------------------------------------------------------
The Android Open Source Project0c908882009-03-03 19:32:16 -08002692
Grace Kloba22ac16e2009-10-07 18:00:23 -07002693 void onProgressChanged(WebView view, int newProgress) {
Leon Scrogginsd746a942010-05-19 13:21:44 -04002694 if (mXLargeScreenSize) {
2695 mTitleBar.setProgress(newProgress);
2696 } else {
2697 // On the phone, the fake title bar will always cover up the
2698 // regular title bar (or the regular one is offscreen), so only the
2699 // fake title bar needs to change its progress
2700 mFakeTitleBar.setProgress(newProgress);
2701 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002702
Grace Kloba22ac16e2009-10-07 18:00:23 -07002703 if (newProgress == 100) {
2704 // onProgressChanged() may continue to be called after the main
2705 // frame has finished loading, as any remaining sub frames continue
2706 // to load. We'll only get called once though with newProgress as
2707 // 100 when everything is loaded. (onPageFinished is called once
2708 // when the main frame completes loading regardless of the state of
2709 // any sub frames so calls to onProgressChanges may continue after
2710 // onPageFinished has executed)
2711 if (mInLoad) {
2712 mInLoad = false;
Leon Scrogginsa27ff192009-09-14 12:58:04 -04002713 updateInLoadMenuItems();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002714 // If the options menu is open, leave the title bar
2715 if (!mOptionsMenuOpen || !mIconView) {
2716 hideFakeTitleBar();
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07002717 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002718 }
Leon Scrogginsaa37e7f2010-03-05 11:51:20 -05002719 } else {
2720 if (!mInLoad) {
2721 // onPageFinished may have already been called but a subframe is
2722 // still loading and updating the progress. Reset mInLoad and
2723 // update the menu items.
2724 mInLoad = true;
2725 updateInLoadMenuItems();
2726 }
2727 // When the page first begins to load, the Activity may still be
2728 // paused, in which case showFakeTitleBar will do nothing. Call
2729 // again as the page continues to load so that it will be shown.
2730 // (Calling it will the fake title bar is already showing will also
2731 // do nothing.
Grace Kloba22ac16e2009-10-07 18:00:23 -07002732 if (!mOptionsMenuOpen || mIconView) {
2733 // This page has begun to load, so show the title bar
2734 showFakeTitleBar();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002735 }
2736 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002737 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002738
Grace Kloba22ac16e2009-10-07 18:00:23 -07002739 void onShowCustomView(View view, WebChromeClient.CustomViewCallback callback) {
Derek Sollenberger8ff57db2009-12-08 15:39:55 -05002740 // if a view already exists then immediately terminate the new one
2741 if (mCustomView != null) {
2742 callback.onCustomViewHidden();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002743 return;
Derek Sollenberger8ff57db2009-12-08 15:39:55 -05002744 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002745
2746 // Add the custom view to its container.
2747 mCustomViewContainer.addView(view, COVER_SCREEN_GRAVITY_CENTER);
2748 mCustomView = view;
2749 mCustomViewCallback = callback;
2750 // Save the menu state and set it to empty while the custom
2751 // view is showing.
2752 mOldMenuState = mMenuState;
2753 mMenuState = EMPTY_MENU;
2754 // Hide the content view.
2755 mContentView.setVisibility(View.GONE);
2756 // Finally show the custom view container.
Andrei Popescu163ab742009-10-20 17:58:23 +01002757 setStatusBarVisibility(false);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002758 mCustomViewContainer.setVisibility(View.VISIBLE);
2759 mCustomViewContainer.bringToFront();
2760 }
2761
2762 void onHideCustomView() {
2763 if (mCustomView == null)
2764 return;
2765
2766 // Hide the custom view.
2767 mCustomView.setVisibility(View.GONE);
2768 // Remove the custom view from its container.
2769 mCustomViewContainer.removeView(mCustomView);
2770 mCustomView = null;
2771 // Reset the old menu state.
2772 mMenuState = mOldMenuState;
2773 mOldMenuState = EMPTY_MENU;
2774 mCustomViewContainer.setVisibility(View.GONE);
2775 mCustomViewCallback.onCustomViewHidden();
2776 // Show the content view.
Andrei Popescu163ab742009-10-20 17:58:23 +01002777 setStatusBarVisibility(true);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002778 mContentView.setVisibility(View.VISIBLE);
2779 }
2780
2781 Bitmap getDefaultVideoPoster() {
2782 if (mDefaultVideoPoster == null) {
2783 mDefaultVideoPoster = BitmapFactory.decodeResource(
2784 getResources(), R.drawable.default_video_poster);
Patrick Scott3918d442009-08-04 13:22:29 -04002785 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002786 return mDefaultVideoPoster;
2787 }
Patrick Scott3918d442009-08-04 13:22:29 -04002788
Grace Kloba22ac16e2009-10-07 18:00:23 -07002789 View getVideoLoadingProgressView() {
2790 if (mVideoProgressView == null) {
2791 LayoutInflater inflater = LayoutInflater.from(BrowserActivity.this);
2792 mVideoProgressView = inflater.inflate(
2793 R.layout.video_loading_progress, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002794 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002795 return mVideoProgressView;
2796 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002797
Leon Scroggins8d5fa432009-10-02 15:55:59 -04002798 /*
2799 * The Object used to inform the WebView of the file to upload.
2800 */
2801 private ValueCallback<Uri> mUploadMessage;
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002802 private String mCameraFilePath;
Leon Scroggins8d5fa432009-10-02 15:55:59 -04002803
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002804 void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
2805
2806 final String imageMimeType = "image/*";
2807 final String imageSourceKey = "source";
2808 final String imageSourceValueCamera = "camera";
2809 final String imageSourceValueGallery = "gallery";
2810
2811 // image source can be 'gallery' or 'camera'.
2812 String imageSource = "";
2813
2814 // We add the camera intent if there was no accept type (or '*/*') or 'image/*'.
2815 boolean addCameraIntent = true;
2816
Grace Kloba22ac16e2009-10-07 18:00:23 -07002817 if (mUploadMessage != null) return;
2818 mUploadMessage = uploadMsg;
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002819
2820 // Parse the accept type.
2821 String params[] = acceptType.split(";");
2822 String mimeType = params[0];
2823
2824 for (String p : params) {
2825 String[] keyValue = p.split("=");
2826 if (keyValue.length == 2) {
2827 // Process key=value parameters.
2828 if (imageSourceKey.equals(keyValue[0])) {
2829 imageSource = keyValue[1];
2830 }
2831 }
2832 }
2833
2834 // This intent will display the standard OPENABLE file picker.
Grace Kloba22ac16e2009-10-07 18:00:23 -07002835 Intent i = new Intent(Intent.ACTION_GET_CONTENT);
2836 i.addCategory(Intent.CATEGORY_OPENABLE);
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002837
2838 // Create an intent to add to the standard file picker that will
2839 // capture an image from the camera. We'll combine this intent with
2840 // the standard OPENABLE picker unless the web developer specifically
2841 // requested the camera or gallery be opened by passing a parameter
2842 // in the accept type.
2843 Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
2844 File externalDataDir = Environment.getExternalStoragePublicDirectory(
2845 Environment.DIRECTORY_DCIM);
2846 File cameraDataDir = new File(externalDataDir.getAbsolutePath() +
2847 File.separator + "browser-photos");
2848 cameraDataDir.mkdirs();
2849 mCameraFilePath = cameraDataDir.getAbsolutePath() + File.separator +
2850 System.currentTimeMillis() + ".jpg";
2851 cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(mCameraFilePath)));
2852
2853 if (mimeType.equals(imageMimeType)) {
2854 i.setType(imageMimeType);
2855 if (imageSource.equals(imageSourceValueCamera)) {
2856 // Specified 'image/*' and requested the camera, so go ahead and launch the camera
2857 // directly.
2858 BrowserActivity.this.startActivityForResult(cameraIntent, FILE_SELECTED);
2859 return;
2860 } else if (imageSource.equals(imageSourceValueGallery)) {
2861 // Specified gallery as the source, so don't want to consider the camera.
2862 addCameraIntent = false;
2863 }
2864 } else {
2865 i.setType("*/*");
2866 }
2867
2868 // Combine the chooser and the extra choices (like camera)
2869 Intent chooser = new Intent(Intent.ACTION_CHOOSER);
2870 chooser.putExtra(Intent.EXTRA_INTENT, i);
2871
2872 if (addCameraIntent) {
2873 // Add the camera Intent
2874 Intent[] choices = new Intent[1];
2875 choices[0] = cameraIntent;
2876 chooser.putExtra(Intent.EXTRA_INITIAL_INTENTS, choices);
2877 }
2878
2879 chooser.putExtra(Intent.EXTRA_TITLE, getString(R.string.choose_upload));
2880 BrowserActivity.this.startActivityForResult(chooser, FILE_SELECTED);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002881 }
2882
2883 // -------------------------------------------------------------------------
2884 // Implement functions for DownloadListener
2885 // -------------------------------------------------------------------------
2886
The Android Open Source Project0c908882009-03-03 19:32:16 -08002887 /**
2888 * Notify the host application a download should be done, or that
2889 * the data should be streamed if a streaming viewer is available.
2890 * @param url The full url to the content that should be downloaded
2891 * @param contentDisposition Content-disposition http header, if
2892 * present.
2893 * @param mimetype The mimetype of the content reported by the server
2894 * @param contentLength The file size reported by the server
2895 */
2896 public void onDownloadStart(String url, String userAgent,
2897 String contentDisposition, String mimetype, long contentLength) {
2898 // if we're dealing wih A/V content that's not explicitly marked
2899 // for download, check if it's streamable.
2900 if (contentDisposition == null
Patrick Scotte1fb9662009-08-31 14:31:52 -04002901 || !contentDisposition.regionMatches(
2902 true, 0, "attachment", 0, 10)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002903 // query the package manager to see if there's a registered handler
2904 // that matches.
2905 Intent intent = new Intent(Intent.ACTION_VIEW);
2906 intent.setDataAndType(Uri.parse(url), mimetype);
Patrick Scotte1fb9662009-08-31 14:31:52 -04002907 ResolveInfo info = getPackageManager().resolveActivity(intent,
2908 PackageManager.MATCH_DEFAULT_ONLY);
2909 if (info != null) {
2910 ComponentName myName = getComponentName();
2911 // If we resolved to ourselves, we don't want to attempt to
2912 // load the url only to try and download it again.
2913 if (!myName.getPackageName().equals(
2914 info.activityInfo.packageName)
2915 || !myName.getClassName().equals(
2916 info.activityInfo.name)) {
2917 // someone (other than us) knows how to handle this mime
2918 // type with this scheme, don't download.
2919 try {
2920 startActivity(intent);
2921 return;
2922 } catch (ActivityNotFoundException ex) {
2923 if (LOGD_ENABLED) {
2924 Log.d(LOGTAG, "activity not found for " + mimetype
2925 + " over " + Uri.parse(url).getScheme(),
2926 ex);
2927 }
2928 // Best behavior is to fall back to a download in this
2929 // case
The Android Open Source Project0c908882009-03-03 19:32:16 -08002930 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002931 }
2932 }
2933 }
2934 onDownloadStartNoStream(url, userAgent, contentDisposition, mimetype, contentLength);
2935 }
2936
Kristian Monsenfa52d172010-03-25 18:29:21 +00002937 // This is to work around the fact that java.net.URI throws Exceptions
2938 // instead of just encoding URL's properly
2939 // Helper method for onDownloadStartNoStream
2940 private static String encodePath(String path) {
2941 char[] chars = path.toCharArray();
2942
2943 boolean needed = false;
2944 for (char c : chars) {
2945 if (c == '[' || c == ']') {
2946 needed = true;
2947 break;
2948 }
2949 }
2950 if (needed == false) {
2951 return path;
2952 }
2953
2954 StringBuilder sb = new StringBuilder("");
2955 for (char c : chars) {
2956 if (c == '[' || c == ']') {
2957 sb.append('%');
2958 sb.append(Integer.toHexString(c));
2959 } else {
2960 sb.append(c);
2961 }
2962 }
2963
2964 return sb.toString();
2965 }
2966
The Android Open Source Project0c908882009-03-03 19:32:16 -08002967 /**
2968 * Notify the host application a download should be done, even if there
2969 * is a streaming viewer available for thise type.
2970 * @param url The full url to the content that should be downloaded
2971 * @param contentDisposition Content-disposition http header, if
2972 * present.
2973 * @param mimetype The mimetype of the content reported by the server
2974 * @param contentLength The file size reported by the server
2975 */
2976 /*package */ void onDownloadStartNoStream(String url, String userAgent,
2977 String contentDisposition, String mimetype, long contentLength) {
2978
2979 String filename = URLUtil.guessFileName(url,
2980 contentDisposition, mimetype);
2981
2982 // Check to see if we have an SDCard
2983 String status = Environment.getExternalStorageState();
2984 if (!status.equals(Environment.MEDIA_MOUNTED)) {
2985 int title;
2986 String msg;
2987
2988 // Check to see if the SDCard is busy, same as the music app
2989 if (status.equals(Environment.MEDIA_SHARED)) {
2990 msg = getString(R.string.download_sdcard_busy_dlg_msg);
2991 title = R.string.download_sdcard_busy_dlg_title;
2992 } else {
2993 msg = getString(R.string.download_no_sdcard_dlg_msg, filename);
2994 title = R.string.download_no_sdcard_dlg_title;
2995 }
2996
2997 new AlertDialog.Builder(this)
2998 .setTitle(title)
2999 .setIcon(android.R.drawable.ic_dialog_alert)
3000 .setMessage(msg)
3001 .setPositiveButton(R.string.ok, null)
3002 .show();
3003 return;
3004 }
3005
Kristian Monsenfa52d172010-03-25 18:29:21 +00003006 // java.net.URI is a lot stricter than KURL so we have to encode some
3007 // extra characters. Fix for b 2538060 and b 1634719
3008 WebAddress webAddress;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003009 try {
Kristian Monsenfa52d172010-03-25 18:29:21 +00003010 webAddress = new WebAddress(url);
3011 webAddress.mPath = encodePath(webAddress.mPath);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003012 } catch (Exception e) {
Kristian Monsenfa52d172010-03-25 18:29:21 +00003013 // This only happens for very bad urls, we want to chatch the
3014 // exception here
3015 Log.e(LOGTAG, "Exception trying to parse url:" + url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003016 return;
3017 }
3018
3019 // XXX: Have to use the old url since the cookies were stored using the
3020 // old percent-encoded url.
3021 String cookies = CookieManager.getInstance().getCookie(url);
3022
3023 ContentValues values = new ContentValues();
Kristian Monsenfa52d172010-03-25 18:29:21 +00003024 values.put(Downloads.Impl.COLUMN_URI, webAddress.toString());
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08003025 values.put(Downloads.Impl.COLUMN_COOKIE_DATA, cookies);
3026 values.put(Downloads.Impl.COLUMN_USER_AGENT, userAgent);
3027 values.put(Downloads.Impl.COLUMN_NOTIFICATION_PACKAGE,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003028 getPackageName());
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08003029 values.put(Downloads.Impl.COLUMN_NOTIFICATION_CLASS,
Leon Scrogginsa563d092010-04-19 16:53:49 -04003030 OpenDownloadReceiver.class.getCanonicalName());
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08003031 values.put(Downloads.Impl.COLUMN_VISIBILITY,
3032 Downloads.Impl.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
3033 values.put(Downloads.Impl.COLUMN_MIME_TYPE, mimetype);
3034 values.put(Downloads.Impl.COLUMN_FILE_NAME_HINT, filename);
Kristian Monsenfa52d172010-03-25 18:29:21 +00003035 values.put(Downloads.Impl.COLUMN_DESCRIPTION, webAddress.mHost);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003036 if (contentLength > 0) {
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08003037 values.put(Downloads.Impl.COLUMN_TOTAL_BYTES, contentLength);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003038 }
3039 if (mimetype == null) {
3040 // We must have long pressed on a link or image to download it. We
3041 // are not sure of the mimetype in this case, so do a head request
3042 new FetchUrlMimeType(this).execute(values);
3043 } else {
3044 final Uri contentUri =
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08003045 getContentResolver().insert(Downloads.Impl.CONTENT_URI, values);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003046 }
Leon Scroggins9191a7f2010-03-18 14:44:44 -04003047 Toast.makeText(this, R.string.download_pending, Toast.LENGTH_SHORT)
3048 .show();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003049 }
3050
Grace Kloba22ac16e2009-10-07 18:00:23 -07003051 // -------------------------------------------------------------------------
3052
The Android Open Source Project0c908882009-03-03 19:32:16 -08003053 /**
3054 * Resets the lock icon. This method is called when we start a new load and
3055 * know the url to be loaded.
3056 */
3057 private void resetLockIcon(String url) {
3058 // Save the lock-icon state (we revert to it if the load gets cancelled)
Grace Kloba22ac16e2009-10-07 18:00:23 -07003059 mTabControl.getCurrentTab().resetLockIcon(url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003060 updateLockIconImage(LOCK_ICON_UNSECURE);
3061 }
3062
The Android Open Source Project0c908882009-03-03 19:32:16 -08003063 /**
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04003064 * Update the lock icon to correspond to our latest state.
3065 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003066 private void updateLockIconToLatest() {
3067 updateLockIconImage(mTabControl.getCurrentTab().getLockIconType());
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04003068 }
3069
3070 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08003071 * Updates the lock-icon image in the title-bar.
3072 */
3073 private void updateLockIconImage(int lockIconType) {
3074 Drawable d = null;
3075 if (lockIconType == LOCK_ICON_SECURE) {
3076 d = mSecLockIcon;
3077 } else if (lockIconType == LOCK_ICON_MIXED) {
3078 d = mMixLockIcon;
3079 }
Leon Scroggins68579392009-09-15 15:31:54 -04003080 mTitleBar.setLock(d);
Leon Scrogginsd746a942010-05-19 13:21:44 -04003081 if (!mXLargeScreenSize) {
3082 mFakeTitleBar.setLock(d);
3083 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003084 }
3085
3086 /**
3087 * Displays a page-info dialog.
3088 * @param tab The tab to show info about
3089 * @param fromShowSSLCertificateOnError The flag that indicates whether
3090 * this dialog was opened from the SSL-certificate-on-error dialog or
3091 * not. This is important, since we need to know whether to return to
3092 * the parent dialog or simply dismiss.
3093 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003094 private void showPageInfo(final Tab tab,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003095 final boolean fromShowSSLCertificateOnError) {
3096 final LayoutInflater factory = LayoutInflater
3097 .from(this);
3098
3099 final View pageInfoView = factory.inflate(R.layout.page_info, null);
3100
3101 final WebView view = tab.getWebView();
3102
3103 String url = null;
3104 String title = null;
3105
3106 if (view == null) {
3107 url = tab.getUrl();
3108 title = tab.getTitle();
3109 } else if (view == mTabControl.getCurrentWebView()) {
3110 // Use the cached title and url if this is the current WebView
3111 url = mUrl;
3112 title = mTitle;
3113 } else {
3114 url = view.getUrl();
3115 title = view.getTitle();
3116 }
3117
3118 if (url == null) {
3119 url = "";
3120 }
3121 if (title == null) {
3122 title = "";
3123 }
3124
3125 ((TextView) pageInfoView.findViewById(R.id.address)).setText(url);
3126 ((TextView) pageInfoView.findViewById(R.id.title)).setText(title);
3127
3128 mPageInfoView = tab;
Leon Scrogginsc7b92f82010-01-11 18:17:31 -05003129 mPageInfoFromShowSSLCertificateOnError = fromShowSSLCertificateOnError;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003130
3131 AlertDialog.Builder alertDialogBuilder =
3132 new AlertDialog.Builder(this)
3133 .setTitle(R.string.page_info).setIcon(android.R.drawable.ic_dialog_info)
3134 .setView(pageInfoView)
3135 .setPositiveButton(
3136 R.string.ok,
3137 new DialogInterface.OnClickListener() {
3138 public void onClick(DialogInterface dialog,
3139 int whichButton) {
3140 mPageInfoDialog = null;
3141 mPageInfoView = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003142
3143 // if we came here from the SSL error dialog
3144 if (fromShowSSLCertificateOnError) {
3145 // go back to the SSL error dialog
3146 showSSLCertificateOnError(
3147 mSSLCertificateOnErrorView,
3148 mSSLCertificateOnErrorHandler,
3149 mSSLCertificateOnErrorError);
3150 }
3151 }
3152 })
3153 .setOnCancelListener(
3154 new DialogInterface.OnCancelListener() {
3155 public void onCancel(DialogInterface dialog) {
3156 mPageInfoDialog = null;
3157 mPageInfoView = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003158
3159 // if we came here from the SSL error dialog
3160 if (fromShowSSLCertificateOnError) {
3161 // go back to the SSL error dialog
3162 showSSLCertificateOnError(
3163 mSSLCertificateOnErrorView,
3164 mSSLCertificateOnErrorHandler,
3165 mSSLCertificateOnErrorError);
3166 }
3167 }
3168 });
3169
3170 // if we have a main top-level page SSL certificate set or a certificate
3171 // error
3172 if (fromShowSSLCertificateOnError ||
3173 (view != null && view.getCertificate() != null)) {
3174 // add a 'View Certificate' button
3175 alertDialogBuilder.setNeutralButton(
3176 R.string.view_certificate,
3177 new DialogInterface.OnClickListener() {
3178 public void onClick(DialogInterface dialog,
3179 int whichButton) {
3180 mPageInfoDialog = null;
3181 mPageInfoView = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003182
3183 // if we came here from the SSL error dialog
3184 if (fromShowSSLCertificateOnError) {
3185 // go back to the SSL error dialog
3186 showSSLCertificateOnError(
3187 mSSLCertificateOnErrorView,
3188 mSSLCertificateOnErrorHandler,
3189 mSSLCertificateOnErrorError);
3190 } else {
3191 // otherwise, display the top-most certificate from
3192 // the chain
3193 if (view.getCertificate() != null) {
3194 showSSLCertificate(tab);
3195 }
3196 }
3197 }
3198 });
3199 }
3200
3201 mPageInfoDialog = alertDialogBuilder.show();
3202 }
3203
3204 /**
3205 * Displays the main top-level page SSL certificate dialog
3206 * (accessible from the Page-Info dialog).
3207 * @param tab The tab to show certificate for.
3208 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003209 private void showSSLCertificate(final Tab tab) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003210 final View certificateView =
3211 inflateCertificateView(tab.getWebView().getCertificate());
3212 if (certificateView == null) {
3213 return;
3214 }
3215
3216 LayoutInflater factory = LayoutInflater.from(this);
3217
3218 final LinearLayout placeholder =
3219 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3220
3221 LinearLayout ll = (LinearLayout) factory.inflate(
3222 R.layout.ssl_success, placeholder);
3223 ((TextView)ll.findViewById(R.id.success))
3224 .setText(R.string.ssl_certificate_is_valid);
3225
3226 mSSLCertificateView = tab;
3227 mSSLCertificateDialog =
3228 new AlertDialog.Builder(this)
3229 .setTitle(R.string.ssl_certificate).setIcon(
3230 R.drawable.ic_dialog_browser_certificate_secure)
3231 .setView(certificateView)
3232 .setPositiveButton(R.string.ok,
3233 new DialogInterface.OnClickListener() {
3234 public void onClick(DialogInterface dialog,
3235 int whichButton) {
3236 mSSLCertificateDialog = null;
3237 mSSLCertificateView = null;
3238
3239 showPageInfo(tab, false);
3240 }
3241 })
3242 .setOnCancelListener(
3243 new DialogInterface.OnCancelListener() {
3244 public void onCancel(DialogInterface dialog) {
3245 mSSLCertificateDialog = null;
3246 mSSLCertificateView = null;
3247
3248 showPageInfo(tab, false);
3249 }
3250 })
3251 .show();
3252 }
3253
3254 /**
3255 * Displays the SSL error certificate dialog.
3256 * @param view The target web-view.
3257 * @param handler The SSL error handler responsible for cancelling the
3258 * connection that resulted in an SSL error or proceeding per user request.
3259 * @param error The SSL error object.
3260 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003261 void showSSLCertificateOnError(
The Android Open Source Project0c908882009-03-03 19:32:16 -08003262 final WebView view, final SslErrorHandler handler, final SslError error) {
3263
3264 final View certificateView =
3265 inflateCertificateView(error.getCertificate());
3266 if (certificateView == null) {
3267 return;
3268 }
3269
3270 LayoutInflater factory = LayoutInflater.from(this);
3271
3272 final LinearLayout placeholder =
3273 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3274
3275 if (error.hasError(SslError.SSL_UNTRUSTED)) {
3276 LinearLayout ll = (LinearLayout)factory
3277 .inflate(R.layout.ssl_warning, placeholder);
3278 ((TextView)ll.findViewById(R.id.warning))
3279 .setText(R.string.ssl_untrusted);
3280 }
3281
3282 if (error.hasError(SslError.SSL_IDMISMATCH)) {
3283 LinearLayout ll = (LinearLayout)factory
3284 .inflate(R.layout.ssl_warning, placeholder);
3285 ((TextView)ll.findViewById(R.id.warning))
3286 .setText(R.string.ssl_mismatch);
3287 }
3288
3289 if (error.hasError(SslError.SSL_EXPIRED)) {
3290 LinearLayout ll = (LinearLayout)factory
3291 .inflate(R.layout.ssl_warning, placeholder);
3292 ((TextView)ll.findViewById(R.id.warning))
3293 .setText(R.string.ssl_expired);
3294 }
3295
3296 if (error.hasError(SslError.SSL_NOTYETVALID)) {
3297 LinearLayout ll = (LinearLayout)factory
3298 .inflate(R.layout.ssl_warning, placeholder);
3299 ((TextView)ll.findViewById(R.id.warning))
3300 .setText(R.string.ssl_not_yet_valid);
3301 }
3302
3303 mSSLCertificateOnErrorHandler = handler;
3304 mSSLCertificateOnErrorView = view;
3305 mSSLCertificateOnErrorError = error;
3306 mSSLCertificateOnErrorDialog =
3307 new AlertDialog.Builder(this)
3308 .setTitle(R.string.ssl_certificate).setIcon(
3309 R.drawable.ic_dialog_browser_certificate_partially_secure)
3310 .setView(certificateView)
3311 .setPositiveButton(R.string.ok,
3312 new DialogInterface.OnClickListener() {
3313 public void onClick(DialogInterface dialog,
3314 int whichButton) {
3315 mSSLCertificateOnErrorDialog = null;
3316 mSSLCertificateOnErrorView = null;
3317 mSSLCertificateOnErrorHandler = null;
3318 mSSLCertificateOnErrorError = null;
3319
Grace Kloba22ac16e2009-10-07 18:00:23 -07003320 view.getWebViewClient().onReceivedSslError(
3321 view, handler, error);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003322 }
3323 })
3324 .setNeutralButton(R.string.page_info_view,
3325 new DialogInterface.OnClickListener() {
3326 public void onClick(DialogInterface dialog,
3327 int whichButton) {
3328 mSSLCertificateOnErrorDialog = null;
3329
3330 // do not clear the dialog state: we will
3331 // need to show the dialog again once the
3332 // user is done exploring the page-info details
3333
3334 showPageInfo(mTabControl.getTabFromView(view),
3335 true);
3336 }
3337 })
3338 .setOnCancelListener(
3339 new DialogInterface.OnCancelListener() {
3340 public void onCancel(DialogInterface dialog) {
3341 mSSLCertificateOnErrorDialog = null;
3342 mSSLCertificateOnErrorView = null;
3343 mSSLCertificateOnErrorHandler = null;
3344 mSSLCertificateOnErrorError = null;
3345
Grace Kloba22ac16e2009-10-07 18:00:23 -07003346 view.getWebViewClient().onReceivedSslError(
3347 view, handler, error);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003348 }
3349 })
3350 .show();
3351 }
3352
3353 /**
3354 * Inflates the SSL certificate view (helper method).
3355 * @param certificate The SSL certificate.
3356 * @return The resultant certificate view with issued-to, issued-by,
3357 * issued-on, expires-on, and possibly other fields set.
3358 * If the input certificate is null, returns null.
3359 */
3360 private View inflateCertificateView(SslCertificate certificate) {
3361 if (certificate == null) {
3362 return null;
3363 }
3364
3365 LayoutInflater factory = LayoutInflater.from(this);
3366
3367 View certificateView = factory.inflate(
3368 R.layout.ssl_certificate, null);
3369
3370 // issued to:
3371 SslCertificate.DName issuedTo = certificate.getIssuedTo();
3372 if (issuedTo != null) {
3373 ((TextView) certificateView.findViewById(R.id.to_common))
3374 .setText(issuedTo.getCName());
3375 ((TextView) certificateView.findViewById(R.id.to_org))
3376 .setText(issuedTo.getOName());
3377 ((TextView) certificateView.findViewById(R.id.to_org_unit))
3378 .setText(issuedTo.getUName());
3379 }
3380
3381 // issued by:
3382 SslCertificate.DName issuedBy = certificate.getIssuedBy();
3383 if (issuedBy != null) {
3384 ((TextView) certificateView.findViewById(R.id.by_common))
3385 .setText(issuedBy.getCName());
3386 ((TextView) certificateView.findViewById(R.id.by_org))
3387 .setText(issuedBy.getOName());
3388 ((TextView) certificateView.findViewById(R.id.by_org_unit))
3389 .setText(issuedBy.getUName());
3390 }
3391
3392 // issued on:
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003393 String issuedOn = formatCertificateDate(
3394 certificate.getValidNotBeforeDate());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003395 ((TextView) certificateView.findViewById(R.id.issued_on))
3396 .setText(issuedOn);
3397
3398 // expires on:
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003399 String expiresOn = formatCertificateDate(
3400 certificate.getValidNotAfterDate());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003401 ((TextView) certificateView.findViewById(R.id.expires_on))
3402 .setText(expiresOn);
3403
3404 return certificateView;
3405 }
3406
3407 /**
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003408 * Formats the certificate date to a properly localized date string.
The Android Open Source Project0c908882009-03-03 19:32:16 -08003409 * @return Properly localized version of the certificate date string and
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003410 * the "" if it fails to localize.
The Android Open Source Project0c908882009-03-03 19:32:16 -08003411 */
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003412 private String formatCertificateDate(Date certificateDate) {
3413 if (certificateDate == null) {
3414 return "";
The Android Open Source Project0c908882009-03-03 19:32:16 -08003415 }
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003416 String formattedDate = DateFormat.getDateFormat(this).format(certificateDate);
3417 if (formattedDate == null) {
3418 return "";
3419 }
3420 return formattedDate;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003421 }
3422
3423 /**
3424 * Displays an http-authentication dialog.
3425 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003426 void showHttpAuthentication(final HttpAuthHandler handler,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003427 final String host, final String realm, final String title,
3428 final String name, final String password, int focusId) {
3429 LayoutInflater factory = LayoutInflater.from(this);
3430 final View v = factory
3431 .inflate(R.layout.http_authentication, null);
3432 if (name != null) {
3433 ((EditText) v.findViewById(R.id.username_edit)).setText(name);
3434 }
3435 if (password != null) {
3436 ((EditText) v.findViewById(R.id.password_edit)).setText(password);
3437 }
3438
3439 String titleText = title;
3440 if (titleText == null) {
3441 titleText = getText(R.string.sign_in_to).toString().replace(
3442 "%s1", host).replace("%s2", realm);
3443 }
3444
3445 mHttpAuthHandler = handler;
3446 AlertDialog dialog = new AlertDialog.Builder(this)
3447 .setTitle(titleText)
3448 .setIcon(android.R.drawable.ic_dialog_alert)
3449 .setView(v)
3450 .setPositiveButton(R.string.action,
3451 new DialogInterface.OnClickListener() {
3452 public void onClick(DialogInterface dialog,
3453 int whichButton) {
3454 String nm = ((EditText) v
3455 .findViewById(R.id.username_edit))
3456 .getText().toString();
3457 String pw = ((EditText) v
3458 .findViewById(R.id.password_edit))
3459 .getText().toString();
3460 BrowserActivity.this.setHttpAuthUsernamePassword
3461 (host, realm, nm, pw);
3462 handler.proceed(nm, pw);
3463 mHttpAuthenticationDialog = null;
3464 mHttpAuthHandler = null;
3465 }})
3466 .setNegativeButton(R.string.cancel,
3467 new DialogInterface.OnClickListener() {
3468 public void onClick(DialogInterface dialog,
3469 int whichButton) {
3470 handler.cancel();
3471 BrowserActivity.this.resetTitleAndRevertLockIcon();
3472 mHttpAuthenticationDialog = null;
3473 mHttpAuthHandler = null;
3474 }})
3475 .setOnCancelListener(new DialogInterface.OnCancelListener() {
3476 public void onCancel(DialogInterface dialog) {
3477 handler.cancel();
3478 BrowserActivity.this.resetTitleAndRevertLockIcon();
3479 mHttpAuthenticationDialog = null;
3480 mHttpAuthHandler = null;
3481 }})
3482 .create();
3483 // Make the IME appear when the dialog is displayed if applicable.
3484 dialog.getWindow().setSoftInputMode(
3485 WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
3486 dialog.show();
3487 if (focusId != 0) {
3488 dialog.findViewById(focusId).requestFocus();
3489 } else {
3490 v.findViewById(R.id.username_edit).requestFocus();
3491 }
3492 mHttpAuthenticationDialog = dialog;
3493 }
3494
3495 public int getProgress() {
3496 WebView w = mTabControl.getCurrentWebView();
3497 if (w != null) {
3498 return w.getProgress();
3499 } else {
3500 return 100;
3501 }
3502 }
3503
3504 /**
3505 * Set HTTP authentication password.
3506 *
3507 * @param host The host for the password
3508 * @param realm The realm for the password
3509 * @param username The username for the password. If it is null, it means
3510 * password can't be saved.
3511 * @param password The password
3512 */
3513 public void setHttpAuthUsernamePassword(String host, String realm,
3514 String username,
3515 String password) {
Steve Block95a53b22010-03-25 17:24:58 +00003516 WebView w = getTopWindow();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003517 if (w != null) {
3518 w.setHttpAuthUsernamePassword(host, realm, username, password);
3519 }
3520 }
3521
3522 /**
3523 * connectivity manager says net has come or gone... inform the user
3524 * @param up true if net has come up, false if net has gone down
3525 */
3526 public void onNetworkToggle(boolean up) {
3527 if (up == mIsNetworkUp) {
3528 return;
3529 } else if (up) {
3530 mIsNetworkUp = true;
3531 if (mAlertDialog != null) {
3532 mAlertDialog.cancel();
3533 mAlertDialog = null;
3534 }
3535 } else {
3536 mIsNetworkUp = false;
Patrick Scotteb6ab2a2009-09-16 10:00:17 -04003537 if (mInLoad) {
3538 createAndShowNetworkDialog();
3539 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003540 }
3541 WebView w = mTabControl.getCurrentWebView();
3542 if (w != null) {
3543 w.setNetworkAvailable(up);
3544 }
3545 }
3546
Grace Kloba22ac16e2009-10-07 18:00:23 -07003547 boolean isNetworkUp() {
3548 return mIsNetworkUp;
3549 }
3550
Patrick Scotteb6ab2a2009-09-16 10:00:17 -04003551 // This method shows the network dialog alerting the user that the net is
3552 // down. It will only show the dialog if mAlertDialog is null.
3553 private void createAndShowNetworkDialog() {
3554 if (mAlertDialog == null) {
3555 mAlertDialog = new AlertDialog.Builder(this)
3556 .setTitle(R.string.loadSuspendedTitle)
3557 .setMessage(R.string.loadSuspended)
3558 .setPositiveButton(R.string.ok, null)
3559 .show();
3560 }
3561 }
3562
The Android Open Source Project0c908882009-03-03 19:32:16 -08003563 @Override
3564 protected void onActivityResult(int requestCode, int resultCode,
3565 Intent intent) {
Grace Klobabb394f32009-11-19 10:26:37 -08003566 if (getTopWindow() == null) return;
3567
The Android Open Source Project0c908882009-03-03 19:32:16 -08003568 switch (requestCode) {
3569 case COMBO_PAGE:
3570 if (resultCode == RESULT_OK && intent != null) {
3571 String data = intent.getAction();
3572 Bundle extras = intent.getExtras();
3573 if (extras != null && extras.getBoolean("new_window", false)) {
Leon Scroggins25d35472009-09-15 11:37:27 -04003574 openTab(data);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003575 } else {
Grace Kloba22ac16e2009-10-07 18:00:23 -07003576 final Tab currentTab =
The Android Open Source Project0c908882009-03-03 19:32:16 -08003577 mTabControl.getCurrentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04003578 dismissSubWindow(currentTab);
3579 if (data != null && data.length() != 0) {
Leon Scroggins92472e82010-02-17 16:32:28 -05003580 loadUrl(getTopWindow(), data);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003581 }
3582 }
3583 }
Leon Scrogginsfde97462010-01-11 13:06:21 -05003584 // Deliberately fall through to PREFERENCES_PAGE, since the
3585 // same extra may be attached to the COMBO_PAGE
3586 case PREFERENCES_PAGE:
3587 if (resultCode == RESULT_OK && intent != null) {
3588 String action = intent.getStringExtra(Intent.EXTRA_TEXT);
3589 if (BrowserSettings.PREF_CLEAR_HISTORY.equals(action)) {
3590 mTabControl.removeParentChildRelationShips();
3591 }
3592 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003593 break;
Leon Scroggins8d5fa432009-10-02 15:55:59 -04003594 // Choose a file from the file picker.
3595 case FILE_SELECTED:
3596 if (null == mUploadMessage) break;
3597 Uri result = intent == null || resultCode != RESULT_OK ? null
3598 : intent.getData();
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003599
3600 // As we ask the camera to save the result of the user taking
3601 // a picture, the camera application does not return anything other
3602 // than RESULT_OK. So we need to check whether the file we expected
3603 // was written to disk in the in the case that we
3604 // did not get an intent returned but did get a RESULT_OK. If it was,
3605 // we assume that this result has came back from the camera.
3606 if (result == null && intent == null && resultCode == RESULT_OK) {
3607 File cameraFile = new File(mCameraFilePath);
3608 if (cameraFile.exists()) {
3609 result = Uri.fromFile(cameraFile);
Ben Murdoch07d34732010-05-27 18:34:46 +01003610 // Broadcast to the media scanner that we have a new photo
3611 // so it will be added into the gallery for the user.
3612 sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, result));
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003613 }
3614 }
3615
Leon Scroggins8d5fa432009-10-02 15:55:59 -04003616 mUploadMessage.onReceiveValue(result);
3617 mUploadMessage = null;
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003618 mCameraFilePath = null;
Leon Scroggins8d5fa432009-10-02 15:55:59 -04003619 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003620 default:
3621 break;
3622 }
Leon Scroggins30444232009-09-04 18:36:20 -04003623 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003624 }
3625
3626 /*
3627 * This method is called as a result of the user selecting the options
Leon Scrogginsf08809b2010-01-21 09:27:46 -05003628 * menu to see the download window. It shows the download window on top of
3629 * the current window.
The Android Open Source Project0c908882009-03-03 19:32:16 -08003630 */
Leon Scrogginsf08809b2010-01-21 09:27:46 -05003631 private void viewDownloads(Uri downloadRecord) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003632 Intent intent = new Intent(this,
3633 BrowserDownloadPage.class);
3634 intent.setData(downloadRecord);
Grace Kloba22ac16e2009-10-07 18:00:23 -07003635 startActivityForResult(intent, BrowserActivity.DOWNLOAD_PAGE);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003636
3637 }
3638
Leon Scroggins160a7e72009-08-14 18:28:01 -04003639 /**
3640 * Open the Go page.
3641 * @param startWithHistory If true, open starting on the history tab.
3642 * Otherwise, start with the bookmarks tab.
Leon Scroggins160a7e72009-08-14 18:28:01 -04003643 */
Leon Scroggins30444232009-09-04 18:36:20 -04003644 /* package */ void bookmarksOrHistoryPicker(boolean startWithHistory) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003645 WebView current = mTabControl.getCurrentWebView();
3646 if (current == null) {
3647 return;
3648 }
3649 Intent intent = new Intent(this,
3650 CombinedBookmarkHistoryActivity.class);
3651 String title = current.getTitle();
3652 String url = current.getUrl();
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01003653 Bitmap thumbnail = createScreenshot(current);
3654
The Android Open Source Project0c908882009-03-03 19:32:16 -08003655 // Just in case the user opens bookmarks before a page finishes loading
3656 // so the current history item, and therefore the page, is null.
3657 if (null == url) {
3658 url = mLastEnteredUrl;
3659 // This can happen.
3660 if (null == url) {
3661 url = mSettings.getHomePage();
3662 }
3663 }
3664 // In case the web page has not yet received its associated title.
3665 if (title == null) {
3666 title = url;
3667 }
3668 intent.putExtra("title", title);
3669 intent.putExtra("url", url);
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01003670 intent.putExtra("thumbnail", thumbnail);
Leon Scroggins30444232009-09-04 18:36:20 -04003671 // Disable opening in a new window if we have maxed out the windows
Grace Kloba22ac16e2009-10-07 18:00:23 -07003672 intent.putExtra("disable_new_window", !mTabControl.canCreateNewTab());
Patrick Scott3918d442009-08-04 13:22:29 -04003673 intent.putExtra("touch_icon_url", current.getTouchIconUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003674 if (startWithHistory) {
3675 intent.putExtra(CombinedBookmarkHistoryActivity.STARTING_TAB,
3676 CombinedBookmarkHistoryActivity.HISTORY_TAB);
3677 }
3678 startActivityForResult(intent, COMBO_PAGE);
3679 }
3680
3681 // Called when loading from context menu or LOAD_URL message
Leon Scroggins92472e82010-02-17 16:32:28 -05003682 private void loadUrlFromContext(WebView view, String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003683 // In case the user enters nothing.
3684 if (url != null && url.length() != 0 && view != null) {
3685 url = smartUrlFilter(url);
Grace Kloba22ac16e2009-10-07 18:00:23 -07003686 if (!view.getWebViewClient().shouldOverrideUrlLoading(view, url)) {
Leon Scroggins92472e82010-02-17 16:32:28 -05003687 loadUrl(view, url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003688 }
3689 }
3690 }
3691
Leon Scroggins92472e82010-02-17 16:32:28 -05003692 /**
3693 * Load the URL into the given WebView and update the title bar
3694 * to reflect the new load. Call this instead of WebView.loadUrl
3695 * directly.
3696 * @param view The WebView used to load url.
3697 * @param url The URL to load.
3698 */
3699 private void loadUrl(WebView view, String url) {
3700 updateTitleBarForNewLoad(view, url);
3701 view.loadUrl(url);
3702 }
3703
3704 /**
3705 * Load UrlData into a Tab and update the title bar to reflect the new
3706 * load. Call this instead of UrlData.loadIn directly.
3707 * @param t The Tab used to load.
3708 * @param data The UrlData being loaded.
3709 */
3710 private void loadUrlDataIn(Tab t, UrlData data) {
3711 updateTitleBarForNewLoad(t.getWebView(), data.mUrl);
3712 data.loadIn(t);
3713 }
3714
3715 /**
3716 * If the WebView is the top window, update the title bar to reflect
3717 * loading the new URL. i.e. set its text, clear the favicon (which
3718 * will be set once the page begins loading), and set the progress to
3719 * INITIAL_PROGRESS to show that the page has begun to load. Called
3720 * by loadUrl and loadUrlDataIn.
3721 * @param view The WebView that is starting a load.
3722 * @param url The URL that is being loaded.
3723 */
3724 private void updateTitleBarForNewLoad(WebView view, String url) {
3725 if (view == getTopWindow()) {
3726 setUrlTitle(url, null);
3727 setFavicon(null);
3728 onProgressChanged(view, INITIAL_PROGRESS);
3729 }
3730 }
3731
The Android Open Source Project0c908882009-03-03 19:32:16 -08003732 private String smartUrlFilter(Uri inUri) {
3733 if (inUri != null) {
3734 return smartUrlFilter(inUri.toString());
3735 }
3736 return null;
3737 }
3738
Feng Qianb34f87a2009-03-24 21:27:26 -07003739 protected static final Pattern ACCEPTED_URI_SCHEMA = Pattern.compile(
The Android Open Source Project0c908882009-03-03 19:32:16 -08003740 "(?i)" + // switch on case insensitive matching
3741 "(" + // begin group for schema
3742 "(?:http|https|file):\\/\\/" +
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003743 "|(?:inline|data|about|content|javascript):" +
The Android Open Source Project0c908882009-03-03 19:32:16 -08003744 ")" +
3745 "(.*)" );
3746
3747 /**
3748 * Attempts to determine whether user input is a URL or search
3749 * terms. Anything with a space is passed to search.
3750 *
3751 * Converts to lowercase any mistakenly uppercased schema (i.e.,
3752 * "Http://" converts to "http://"
3753 *
3754 * @return Original or modified URL
3755 *
3756 */
3757 String smartUrlFilter(String url) {
3758
3759 String inUrl = url.trim();
3760 boolean hasSpace = inUrl.indexOf(' ') != -1;
3761
3762 Matcher matcher = ACCEPTED_URI_SCHEMA.matcher(inUrl);
3763 if (matcher.matches()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003764 // force scheme to lowercase
3765 String scheme = matcher.group(1);
3766 String lcScheme = scheme.toLowerCase();
3767 if (!lcScheme.equals(scheme)) {
Mitsuru Oshima123ecfb2009-05-18 19:11:14 -07003768 inUrl = lcScheme + matcher.group(2);
3769 }
3770 if (hasSpace) {
3771 inUrl = inUrl.replace(" ", "%20");
The Android Open Source Project0c908882009-03-03 19:32:16 -08003772 }
3773 return inUrl;
3774 }
3775 if (hasSpace) {
Satish Sampath565505b2009-05-29 15:37:27 +01003776 // FIXME: Is this the correct place to add to searches?
3777 // what if someone else calls this function?
3778 int shortcut = parseUrlShortcut(inUrl);
3779 if (shortcut != SHORTCUT_INVALID) {
3780 Browser.addSearchUrl(mResolver, inUrl);
3781 String query = inUrl.substring(2);
3782 switch (shortcut) {
3783 case SHORTCUT_GOOGLE_SEARCH:
Grace Kloba47fdfdb2009-06-30 11:15:34 -07003784 return URLUtil.composeSearchUrl(query, QuickSearch_G, QUERY_PLACE_HOLDER);
Satish Sampath565505b2009-05-29 15:37:27 +01003785 case SHORTCUT_WIKIPEDIA_SEARCH:
3786 return URLUtil.composeSearchUrl(query, QuickSearch_W, QUERY_PLACE_HOLDER);
3787 case SHORTCUT_DICTIONARY_SEARCH:
3788 return URLUtil.composeSearchUrl(query, QuickSearch_D, QUERY_PLACE_HOLDER);
3789 case SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH:
The Android Open Source Project0c908882009-03-03 19:32:16 -08003790 // FIXME: we need location in this case
Satish Sampath565505b2009-05-29 15:37:27 +01003791 return URLUtil.composeSearchUrl(query, QuickSearch_L, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003792 }
3793 }
3794 } else {
Dan Egnor5ee906c2009-11-18 12:11:49 -08003795 if (Patterns.WEB_URL.matcher(inUrl).matches()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003796 return URLUtil.guessUrl(inUrl);
3797 }
3798 }
3799
3800 Browser.addSearchUrl(mResolver, inUrl);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07003801 return URLUtil.composeSearchUrl(inUrl, QuickSearch_G, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003802 }
3803
Ben Murdochbff2d602009-07-01 20:19:05 +01003804 /* package */ void setShouldShowErrorConsole(boolean flag) {
3805 if (flag == mShouldShowErrorConsole) {
3806 // Nothing to do.
3807 return;
3808 }
3809
3810 mShouldShowErrorConsole = flag;
3811
Grace Kloba22ac16e2009-10-07 18:00:23 -07003812 ErrorConsoleView errorConsole = mTabControl.getCurrentTab()
3813 .getErrorConsole(true);
Ben Murdochbff2d602009-07-01 20:19:05 +01003814
3815 if (flag) {
3816 // Setting the show state of the console will cause it's the layout to be inflated.
3817 if (errorConsole.numberOfErrors() > 0) {
3818 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
3819 } else {
3820 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
3821 }
3822
3823 // Now we can add it to the main view.
3824 mErrorConsoleContainer.addView(errorConsole,
Romain Guy15b8ec62010-01-08 15:06:43 -08003825 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
Ben Murdochbff2d602009-07-01 20:19:05 +01003826 ViewGroup.LayoutParams.WRAP_CONTENT));
3827 } else {
3828 mErrorConsoleContainer.removeView(errorConsole);
3829 }
3830
3831 }
3832
Grace Kloba22ac16e2009-10-07 18:00:23 -07003833 boolean shouldShowErrorConsole() {
3834 return mShouldShowErrorConsole;
3835 }
3836
Andrei Popescu163ab742009-10-20 17:58:23 +01003837 private void setStatusBarVisibility(boolean visible) {
3838 int flag = visible ? 0 : WindowManager.LayoutParams.FLAG_FULLSCREEN;
3839 getWindow().setFlags(flag, WindowManager.LayoutParams.FLAG_FULLSCREEN);
3840 }
3841
Andrei Popescu56199cc2010-01-12 22:39:16 +00003842
3843 private void sendNetworkType(String type, String subtype) {
3844 WebView w = mTabControl.getCurrentWebView();
3845 if (w != null) {
3846 w.setNetworkType(type, subtype);
3847 }
3848 }
3849
Andrei Popescu30995e72010-02-09 16:59:58 +00003850 private void packageChanged(String packageName, boolean wasAdded) {
3851 WebView w = mTabControl.getCurrentWebView();
3852 if (w == null) {
3853 return;
3854 }
3855
3856 if (wasAdded) {
3857 w.addPackageName(packageName);
3858 } else {
3859 w.removePackageName(packageName);
3860 }
3861 }
3862
3863 private void addPackageNames(Set<String> packageNames) {
3864 WebView w = mTabControl.getCurrentWebView();
3865 if (w == null) {
3866 return;
3867 }
3868
3869 w.addPackageNames(packageNames);
3870 }
3871
3872 private void getInstalledPackages() {
3873 AsyncTask<Void, Void, Set<String> > task =
3874 new AsyncTask<Void, Void, Set<String> >() {
3875 protected Set<String> doInBackground(Void... unused) {
3876 Set<String> installedPackages = new HashSet<String>();
3877 PackageManager pm = BrowserActivity.this.getPackageManager();
3878 if (pm != null) {
3879 List<PackageInfo> packages = pm.getInstalledPackages(0);
3880 for (PackageInfo p : packages) {
3881 if (BrowserActivity.this.sGoogleApps.contains(p.packageName)) {
3882 installedPackages.add(p.packageName);
3883 }
3884 }
3885 }
3886
3887 return installedPackages;
3888 }
3889
3890 // Executes on the UI thread
3891 protected void onPostExecute(Set<String> installedPackages) {
3892 addPackageNames(installedPackages);
3893 }
3894 };
3895 task.execute();
3896 }
3897
Grace Klobaeb6eef42009-09-15 17:56:32 -07003898 final static int LOCK_ICON_UNSECURE = 0;
3899 final static int LOCK_ICON_SECURE = 1;
3900 final static int LOCK_ICON_MIXED = 2;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003901
The Android Open Source Project0c908882009-03-03 19:32:16 -08003902 private BrowserSettings mSettings;
3903 private TabControl mTabControl;
3904 private ContentResolver mResolver;
3905 private FrameLayout mContentView;
Andrei Popescuadc008d2009-06-26 14:11:30 +01003906 private View mCustomView;
3907 private FrameLayout mCustomViewContainer;
Andrei Popescuc9b55562009-07-07 10:51:15 +01003908 private WebChromeClient.CustomViewCallback mCustomViewCallback;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003909
3910 // FIXME, temp address onPrepareMenu performance problem. When we move everything out of
3911 // view, we should rewrite this.
3912 private int mCurrentMenuState = 0;
3913 private int mMenuState = R.id.MAIN_MENU;
Andrei Popescuadc008d2009-06-26 14:11:30 +01003914 private int mOldMenuState = EMPTY_MENU;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003915 private static final int EMPTY_MENU = -1;
3916 private Menu mMenu;
3917
3918 private FindDialog mFindDialog;
3919 // Used to prevent chording to result in firing two shortcuts immediately
3920 // one after another. Fixes bug 1211714.
3921 boolean mCanChord;
3922
3923 private boolean mInLoad;
3924 private boolean mIsNetworkUp;
Ben Murdochb7cc8b42009-09-28 10:59:09 +01003925 private boolean mDidStopLoad;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003926
Cary Clark1f10cbf2010-03-22 11:45:23 -04003927 /* package */ boolean mActivityInPause = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003928
3929 private boolean mMenuIsDown;
3930
The Android Open Source Project0c908882009-03-03 19:32:16 -08003931 private static boolean mInTrace;
3932
3933 // Performance probe
3934 private static final int[] SYSTEM_CPU_FORMAT = new int[] {
3935 Process.PROC_SPACE_TERM | Process.PROC_COMBINE,
3936 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 1: user time
3937 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 2: nice time
3938 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 3: sys time
3939 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 4: idle time
3940 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 5: iowait time
3941 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 6: irq time
3942 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG // 7: softirq time
3943 };
3944
3945 private long mStart;
3946 private long mProcessStart;
3947 private long mUserStart;
3948 private long mSystemStart;
3949 private long mIdleStart;
3950 private long mIrqStart;
3951
3952 private long mUiStart;
3953
3954 private Drawable mMixLockIcon;
3955 private Drawable mSecLockIcon;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003956
3957 /* hold a ref so we can auto-cancel if necessary */
3958 private AlertDialog mAlertDialog;
3959
The Android Open Source Project0c908882009-03-03 19:32:16 -08003960 // The up-to-date URL and title (these can be different from those stored
3961 // in WebView, since it takes some time for the information in WebView to
3962 // get updated)
3963 private String mUrl;
3964 private String mTitle;
3965
3966 // As PageInfo has different style for landscape / portrait, we have
3967 // to re-open it when configuration changed
3968 private AlertDialog mPageInfoDialog;
Grace Kloba22ac16e2009-10-07 18:00:23 -07003969 private Tab mPageInfoView;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003970 // If the Page-Info dialog is launched from the SSL-certificate-on-error
3971 // dialog, we should not just dismiss it, but should get back to the
3972 // SSL-certificate-on-error dialog. This flag is used to store this state
Leon Scrogginsc7b92f82010-01-11 18:17:31 -05003973 private boolean mPageInfoFromShowSSLCertificateOnError;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003974
3975 // as SSLCertificateOnError has different style for landscape / portrait,
3976 // we have to re-open it when configuration changed
3977 private AlertDialog mSSLCertificateOnErrorDialog;
3978 private WebView mSSLCertificateOnErrorView;
3979 private SslErrorHandler mSSLCertificateOnErrorHandler;
3980 private SslError mSSLCertificateOnErrorError;
3981
3982 // as SSLCertificate has different style for landscape / portrait, we
3983 // have to re-open it when configuration changed
3984 private AlertDialog mSSLCertificateDialog;
Grace Kloba22ac16e2009-10-07 18:00:23 -07003985 private Tab mSSLCertificateView;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003986
3987 // as HttpAuthentication has different style for landscape / portrait, we
3988 // have to re-open it when configuration changed
3989 private AlertDialog mHttpAuthenticationDialog;
3990 private HttpAuthHandler mHttpAuthHandler;
3991
3992 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_PARAMS =
3993 new FrameLayout.LayoutParams(
Romain Guy15b8ec62010-01-08 15:06:43 -08003994 ViewGroup.LayoutParams.MATCH_PARENT,
3995 ViewGroup.LayoutParams.MATCH_PARENT);
Andrei Popescuadc008d2009-06-26 14:11:30 +01003996 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_GRAVITY_CENTER =
3997 new FrameLayout.LayoutParams(
Romain Guy15b8ec62010-01-08 15:06:43 -08003998 ViewGroup.LayoutParams.MATCH_PARENT,
3999 ViewGroup.LayoutParams.MATCH_PARENT,
Andrei Popescuadc008d2009-06-26 14:11:30 +01004000 Gravity.CENTER);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07004001 // Google search
4002 final static String QuickSearch_G = "http://www.google.com/m?q=%s";
The Android Open Source Project0c908882009-03-03 19:32:16 -08004003 // Wikipedia search
4004 final static String QuickSearch_W = "http://en.wikipedia.org/w/index.php?search=%s&go=Go";
4005 // Dictionary search
4006 final static String QuickSearch_D = "http://dictionary.reference.com/search?q=%s";
4007 // Google Mobile Local search
4008 final static String QuickSearch_L = "http://www.google.com/m/search?site=local&q=%s&near=mountain+view";
4009
4010 final static String QUERY_PLACE_HOLDER = "%s";
4011
4012 // "source" parameter for Google search through search key
4013 final static String GOOGLE_SEARCH_SOURCE_SEARCHKEY = "browser-key";
4014 // "source" parameter for Google search through goto menu
4015 final static String GOOGLE_SEARCH_SOURCE_GOTO = "browser-goto";
4016 // "source" parameter for Google search through simplily type
4017 final static String GOOGLE_SEARCH_SOURCE_TYPE = "browser-type";
4018 // "source" parameter for Google search suggested by the browser
4019 final static String GOOGLE_SEARCH_SOURCE_SUGGEST = "browser-suggest";
4020 // "source" parameter for Google search from unknown source
4021 final static String GOOGLE_SEARCH_SOURCE_UNKNOWN = "unknown";
4022
4023 private final static String LOGTAG = "browser";
4024
The Android Open Source Project0c908882009-03-03 19:32:16 -08004025 private String mLastEnteredUrl;
4026
4027 private PowerManager.WakeLock mWakeLock;
4028 private final static int WAKELOCK_TIMEOUT = 5 * 60 * 1000; // 5 minutes
4029
4030 private Toast mStopToast;
4031
Leon Scroggins68579392009-09-15 15:31:54 -04004032 private TitleBar mTitleBar;
Leon Scroggins81db3662009-06-04 17:45:11 -04004033
Ben Murdochbff2d602009-07-01 20:19:05 +01004034 private LinearLayout mErrorConsoleContainer = null;
4035 private boolean mShouldShowErrorConsole = false;
4036
The Android Open Source Project0c908882009-03-03 19:32:16 -08004037 // As the ids are dynamically created, we can't guarantee that they will
4038 // be in sequence, so this static array maps ids to a window number.
4039 final static private int[] WINDOW_SHORTCUT_ID_ARRAY =
4040 { R.id.window_one_menu_id, R.id.window_two_menu_id, R.id.window_three_menu_id,
4041 R.id.window_four_menu_id, R.id.window_five_menu_id, R.id.window_six_menu_id,
4042 R.id.window_seven_menu_id, R.id.window_eight_menu_id };
4043
4044 // monitor platform changes
4045 private IntentFilter mNetworkStateChangedFilter;
4046 private BroadcastReceiver mNetworkStateIntentReceiver;
4047
Grace Klobab4da0ad2009-05-14 14:45:40 -07004048 private BroadcastReceiver mPackageInstallationReceiver;
4049
Bjorn Bringerta7611812010-03-24 11:12:02 +00004050 private SystemAllowGeolocationOrigins mSystemAllowGeolocationOrigins;
4051
The Android Open Source Project0c908882009-03-03 19:32:16 -08004052 // activity requestCode
Nicolas Roard78a98e42009-05-11 13:34:17 +01004053 final static int COMBO_PAGE = 1;
4054 final static int DOWNLOAD_PAGE = 2;
4055 final static int PREFERENCES_PAGE = 3;
Leon Scroggins8d5fa432009-10-02 15:55:59 -04004056 final static int FILE_SELECTED = 4;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004057
Andrei Popescu540035d2009-09-18 18:59:20 +01004058 // the default <video> poster
4059 private Bitmap mDefaultVideoPoster;
4060 // the video progress view
4061 private View mVideoProgressView;
4062
Andrei Popescu30995e72010-02-09 16:59:58 +00004063 // The Google packages we monitor for the navigator.isApplicationInstalled()
4064 // API. Add as needed.
4065 private static Set<String> sGoogleApps;
4066 static {
4067 sGoogleApps = new HashSet<String>();
4068 sGoogleApps.add("com.google.android.youtube");
4069 }
4070
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004071 /**
4072 * A UrlData class to abstract how the content will be set to WebView.
4073 * This base class uses loadUrl to show the content.
4074 */
Leon Scroggins6eac63e2010-03-15 18:19:14 -04004075 /* package */ static class UrlData {
Grace Kloba068e48b2010-01-26 18:11:27 -08004076 final String mUrl;
4077 final Map<String, String> mHeaders;
Leon Scroggins58d56c62010-01-28 15:12:40 -05004078 final Intent mVoiceIntent;
Grace Kloba60e095c2009-06-16 11:50:55 -07004079
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004080 UrlData(String url) {
4081 this.mUrl = url;
Grace Kloba068e48b2010-01-26 18:11:27 -08004082 this.mHeaders = null;
Leon Scroggins58d56c62010-01-28 15:12:40 -05004083 this.mVoiceIntent = null;
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004084 }
Grace Kloba60e095c2009-06-16 11:50:55 -07004085
Leon Scroggins58d56c62010-01-28 15:12:40 -05004086 UrlData(String url, Map<String, String> headers, Intent intent) {
Grace Kloba068e48b2010-01-26 18:11:27 -08004087 this.mUrl = url;
4088 this.mHeaders = headers;
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -05004089 if (RecognizerResultsIntent.ACTION_VOICE_SEARCH_RESULTS
4090 .equals(intent.getAction())) {
Leon Scroggins58d56c62010-01-28 15:12:40 -05004091 this.mVoiceIntent = intent;
4092 } else {
4093 this.mVoiceIntent = null;
4094 }
Grace Kloba60e095c2009-06-16 11:50:55 -07004095 }
4096
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004097 boolean isEmpty() {
Leon Scroggins58d56c62010-01-28 15:12:40 -05004098 return mVoiceIntent == null && (mUrl == null || mUrl.length() == 0);
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004099 }
4100
Leon Scroggins92472e82010-02-17 16:32:28 -05004101 /**
4102 * Load this UrlData into the given Tab. Use loadUrlDataIn to update
4103 * the title bar as well.
4104 */
Leon Scroggins58d56c62010-01-28 15:12:40 -05004105 public void loadIn(Tab t) {
4106 if (mVoiceIntent != null) {
4107 t.activateVoiceSearchMode(mVoiceIntent);
4108 } else {
4109 t.getWebView().loadUrl(mUrl, mHeaders);
4110 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004111 }
4112 };
4113
Leon Scroggins1f005d32009-08-10 17:36:42 -04004114 /* package */ static final UrlData EMPTY_URL_DATA = new UrlData(null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004115}