blob: 5c71bf518e9601f4fcceda803affb0c526f46757 [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;
The Android Open Source Project0c908882009-03-03 19:32:16 -080090import android.webkit.CookieManager;
91import android.webkit.CookieSyncManager;
92import android.webkit.DownloadListener;
93import android.webkit.HttpAuthHandler;
Grace Klobab4da0ad2009-05-14 14:45:40 -070094import android.webkit.PluginManager;
The Android Open Source Project0c908882009-03-03 19:32:16 -080095import android.webkit.SslErrorHandler;
96import android.webkit.URLUtil;
Leon Clarkecb6cc862009-09-29 18:35:13 +010097import android.webkit.ValueCallback;
The Android Open Source Project0c908882009-03-03 19:32:16 -080098import android.webkit.WebChromeClient;
99import android.webkit.WebHistoryItem;
100import android.webkit.WebIconDatabase;
101import android.webkit.WebView;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800102import android.widget.EditText;
103import android.widget.FrameLayout;
104import android.widget.LinearLayout;
105import android.widget.TextView;
106import android.widget.Toast;
Fred Quintana752b6562009-12-18 10:18:26 -0800107import android.accounts.Account;
108import android.accounts.AccountManager;
109import android.accounts.AccountManagerFuture;
110import android.accounts.AuthenticatorException;
111import android.accounts.OperationCanceledException;
112import android.accounts.AccountManagerCallback;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800113
Bjorn Bringert10d1cca2010-02-10 14:22:12 +0000114import com.android.common.Search;
Leon Scroggins1fe13a52010-02-09 15:31:26 -0500115import com.android.common.speech.LoggingEvents;
Dan Egnor5ee906c2009-11-18 12:11:49 -0800116
Leon Scrogginsb6b7f9e2009-06-18 12:05:28 -0400117import java.io.ByteArrayOutputStream;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800118import java.io.File;
Ben Murdoch4f75ba22009-10-27 11:48:28 +0000119import java.io.IOException;
120import java.io.InputStream;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800121import java.net.MalformedURLException;
122import java.net.URI;
Dianne Hackborn99189432009-06-17 18:06:18 -0700123import java.net.URISyntaxException;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800124import java.net.URL;
125import java.net.URLEncoder;
126import java.text.ParseException;
127import java.util.Date;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800128import java.util.HashMap;
Andrei Popescu30995e72010-02-09 16:59:58 +0000129import java.util.HashSet;
Grace Kloba00f54c52010-01-27 14:53:51 -0800130import java.util.Iterator;
Andrei Popescu30995e72010-02-09 16:59:58 +0000131import java.util.List;
Grace Kloba068e48b2010-01-26 18:11:27 -0800132import java.util.Map;
Andrei Popescu30995e72010-02-09 16:59:58 +0000133import java.util.Set;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800134import java.util.regex.Matcher;
135import java.util.regex.Pattern;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800136
137public class BrowserActivity extends Activity
Shimeng (Simon) Wang98d5fce2010-03-16 13:23:39 -0700138 implements View.OnCreateContextMenuListener, DownloadListener {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800139
Dave Bort31a6d1c2009-04-13 15:56:49 -0700140 /* Define some aliases to make these debugging flags easier to refer to.
141 * This file imports android.provider.Browser, so we can't just refer to "Browser.DEBUG".
142 */
143 private final static boolean DEBUG = com.android.browser.Browser.DEBUG;
144 private final static boolean LOGV_ENABLED = com.android.browser.Browser.LOGV_ENABLED;
145 private final static boolean LOGD_ENABLED = com.android.browser.Browser.LOGD_ENABLED;
146
Satish Sampath565505b2009-05-29 15:37:27 +0100147 // These are single-character shortcuts for searching popular sources.
148 private static final int SHORTCUT_INVALID = 0;
149 private static final int SHORTCUT_GOOGLE_SEARCH = 1;
150 private static final int SHORTCUT_WIKIPEDIA_SEARCH = 2;
151 private static final int SHORTCUT_DICTIONARY_SEARCH = 3;
152 private static final int SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH = 4;
153
Cary Clarka9771242009-08-11 16:42:26 -0400154 private static class ClearThumbnails extends AsyncTask<File, Void, Void> {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800155 @Override
156 public Void doInBackground(File... files) {
157 if (files != null) {
158 for (File f : files) {
Cary Clarkd6be1752009-08-12 12:56:42 -0400159 if (!f.delete()) {
160 Log.e(LOGTAG, f.getPath() + " was not deleted");
161 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800162 }
163 }
164 return null;
165 }
166 }
167
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400168 /**
169 * This layout holds everything you see below the status bar, including the
170 * error console, the custom view container, and the webviews.
171 */
172 private FrameLayout mBrowserFrameLayout;
Leon Scroggins81db3662009-06-04 17:45:11 -0400173
Grace Kloba22ac16e2009-10-07 18:00:23 -0700174 @Override
175 public void onCreate(Bundle icicle) {
Dave Bort31a6d1c2009-04-13 15:56:49 -0700176 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800177 Log.v(LOGTAG, this + " onStart");
178 }
179 super.onCreate(icicle);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800180 // test the browser in OpenGL
181 // requestWindowFeature(Window.FEATURE_OPENGL);
182
Mike Reedd334bf52010-01-26 15:21:44 -0500183 // enable this to test the browser in 32bit
184 if (false) {
185 getWindow().setFormat(PixelFormat.RGBX_8888);
186 BitmapFactory.setDefaultConfig(Bitmap.Config.ARGB_8888);
187 }
188
The Android Open Source Project0c908882009-03-03 19:32:16 -0800189 setDefaultKeyMode(DEFAULT_KEYS_SEARCH_LOCAL);
190
191 mResolver = getContentResolver();
192
Grace Kloba0923d692009-09-23 21:37:25 -0700193 // If this was a web search request, pass it on to the default web
194 // search provider and finish this activity.
195 if (handleWebSearchIntent(getIntent())) {
196 finish();
197 return;
198 }
199
The Android Open Source Project0c908882009-03-03 19:32:16 -0800200 mSecLockIcon = Resources.getSystem().getDrawable(
201 android.R.drawable.ic_secure);
202 mMixLockIcon = Resources.getSystem().getDrawable(
203 android.R.drawable.ic_partial_secure);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800204
Leon Scroggins81db3662009-06-04 17:45:11 -0400205 FrameLayout frameLayout = (FrameLayout) getWindow().getDecorView()
206 .findViewById(com.android.internal.R.id.content);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400207 mBrowserFrameLayout = (FrameLayout) LayoutInflater.from(this)
208 .inflate(R.layout.custom_screen, null);
209 mContentView = (FrameLayout) mBrowserFrameLayout.findViewById(
210 R.id.main_content);
211 mErrorConsoleContainer = (LinearLayout) mBrowserFrameLayout
212 .findViewById(R.id.error_console);
213 mCustomViewContainer = (FrameLayout) mBrowserFrameLayout
214 .findViewById(R.id.fullscreen_custom_content);
215 frameLayout.addView(mBrowserFrameLayout, COVER_SCREEN_PARAMS);
Leon Scroggins68579392009-09-15 15:31:54 -0400216 mTitleBar = new TitleBar(this);
Grace Kloba1542f742010-03-17 21:11:15 -0700217 // mTitleBar will be always shown in the fully loaded mode
218 mTitleBar.setProgress(100);
Leon Scrogginsfe87bd32009-10-06 10:10:00 -0400219 mFakeTitleBar = new TitleBar(this);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800220
221 // Create the tab control and our initial tab
222 mTabControl = new TabControl(this);
223
224 // Open the icon database and retain all the bookmark urls for favicons
225 retainIconsOnStartup();
226
227 // Keep a settings instance handy.
228 mSettings = BrowserSettings.getInstance();
229 mSettings.setTabControl(mTabControl);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800230
231 PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
232 mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Browser");
233
Patrick Scott6adacc92010-03-05 08:24:51 -0500234 // Find out if the network is currently up.
235 ConnectivityManager cm = (ConnectivityManager) getSystemService(
236 Context.CONNECTIVITY_SERVICE);
237 NetworkInfo info = cm.getActiveNetworkInfo();
238 if (info != null) {
239 mIsNetworkUp = info.isAvailable();
240 }
241
Grace Klobaa34f6862009-07-31 16:28:17 -0700242 /* enables registration for changes in network status from
243 http stack */
244 mNetworkStateChangedFilter = new IntentFilter();
245 mNetworkStateChangedFilter.addAction(
246 ConnectivityManager.CONNECTIVITY_ACTION);
247 mNetworkStateIntentReceiver = new BroadcastReceiver() {
248 @Override
249 public void onReceive(Context context, Intent intent) {
250 if (intent.getAction().equals(
251 ConnectivityManager.CONNECTIVITY_ACTION)) {
Andrei Popescue4c98462010-02-19 15:44:13 +0000252
253 NetworkInfo info = intent.getParcelableExtra(
254 ConnectivityManager.EXTRA_NETWORK_INFO);
255 String typeName = info.getTypeName();
256 String subtypeName = info.getSubtypeName();
257 sendNetworkType(typeName.toLowerCase(),
258 (subtypeName != null ? subtypeName.toLowerCase() : ""));
259
260 onNetworkToggle(info.isAvailable());
Grace Klobaa34f6862009-07-31 16:28:17 -0700261 }
262 }
263 };
264
Grace Kloba615c6c92009-08-03 10:22:44 -0700265 IntentFilter filter = new IntentFilter(Intent.ACTION_PACKAGE_ADDED);
266 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
267 filter.addDataScheme("package");
268 mPackageInstallationReceiver = new BroadcastReceiver() {
269 @Override
270 public void onReceive(Context context, Intent intent) {
271 final String action = intent.getAction();
272 final String packageName = intent.getData()
273 .getSchemeSpecificPart();
274 final boolean replacing = intent.getBooleanExtra(
275 Intent.EXTRA_REPLACING, false);
276 if (Intent.ACTION_PACKAGE_REMOVED.equals(action) && replacing) {
277 // if it is replacing, refreshPlugins() when adding
278 return;
279 }
Andrei Popescu30995e72010-02-09 16:59:58 +0000280
281 if (sGoogleApps.contains(packageName)) {
282 BrowserActivity.this.packageChanged(packageName,
283 Intent.ACTION_PACKAGE_ADDED.equals(action));
284 }
285
Grace Kloba615c6c92009-08-03 10:22:44 -0700286 PackageManager pm = BrowserActivity.this.getPackageManager();
287 PackageInfo pkgInfo = null;
288 try {
289 pkgInfo = pm.getPackageInfo(packageName,
290 PackageManager.GET_PERMISSIONS);
291 } catch (PackageManager.NameNotFoundException e) {
292 return;
293 }
294 if (pkgInfo != null) {
295 String permissions[] = pkgInfo.requestedPermissions;
296 if (permissions == null) {
297 return;
298 }
299 boolean permissionOk = false;
300 for (String permit : permissions) {
301 if (PluginManager.PLUGIN_PERMISSION.equals(permit)) {
302 permissionOk = true;
303 break;
304 }
305 }
306 if (permissionOk) {
307 PluginManager.getInstance(BrowserActivity.this)
308 .refreshPlugins(
309 Intent.ACTION_PACKAGE_ADDED
310 .equals(action));
311 }
312 }
313 }
314 };
315 registerReceiver(mPackageInstallationReceiver, filter);
316
The Android Open Source Project0c908882009-03-03 19:32:16 -0800317 if (!mTabControl.restoreState(icicle)) {
318 // clear up the thumbnail directory if we can't restore the state as
319 // none of the files in the directory are referenced any more.
320 new ClearThumbnails().execute(
321 mTabControl.getThumbnailDir().listFiles());
Grace Klobaaab3f092009-07-30 12:29:51 -0700322 // there is no quit on Android. But if we can't restore the state,
323 // we can treat it as a new Browser, remove the old session cookies.
324 CookieManager.getInstance().removeSessionCookie();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800325 final Intent intent = getIntent();
326 final Bundle extra = intent.getExtras();
327 // Create an initial tab.
328 // If the intent is ACTION_VIEW and data is not null, the Browser is
329 // invoked to view the content by another application. In this case,
330 // the tab will be close when exit.
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700331 UrlData urlData = getUrlDataFromIntent(intent);
332
Leon Scroggins58d56c62010-01-28 15:12:40 -0500333 String action = intent.getAction();
Grace Kloba22ac16e2009-10-07 18:00:23 -0700334 final Tab t = mTabControl.createNewTab(
Leon Scroggins58d56c62010-01-28 15:12:40 -0500335 (Intent.ACTION_VIEW.equals(action) &&
336 intent.getData() != null)
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -0500337 || RecognizerResultsIntent.ACTION_VOICE_SEARCH_RESULTS
338 .equals(action),
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700339 intent.getStringExtra(Browser.EXTRA_APPLICATION_ID), urlData.mUrl);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800340 mTabControl.setCurrentTab(t);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800341 attachTabToContentView(t);
342 WebView webView = t.getWebView();
343 if (extra != null) {
344 int scale = extra.getInt(Browser.INITIAL_ZOOM_LEVEL, 0);
345 if (scale > 0 && scale <= 1000) {
346 webView.setInitialScale(scale);
347 }
348 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800349
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700350 if (urlData.isEmpty()) {
Shimeng (Simon) Wang98d5fce2010-03-16 13:23:39 -0700351 loadUrl(webView, mSettings.getHomePage());
The Android Open Source Project0c908882009-03-03 19:32:16 -0800352 } else {
Patrick Scott9d53da02010-02-19 10:19:01 -0500353 loadUrlDataIn(t, urlData);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800354 }
355 } else {
356 // TabControl.restoreState() will create a new tab even if
Leon Scroggins1f005d32009-08-10 17:36:42 -0400357 // restoring the state fails.
The Android Open Source Project0c908882009-03-03 19:32:16 -0800358 attachTabToContentView(mTabControl.getCurrentTab());
359 }
Grace Kloba615c6c92009-08-03 10:22:44 -0700360
Feng Qianb3c02da2009-06-29 15:58:08 -0700361 // Read JavaScript flags if it exists.
362 String jsFlags = mSettings.getJsFlags();
363 if (jsFlags.trim().length() != 0) {
364 mTabControl.getCurrentWebView().setJsFlags(jsFlags);
365 }
Andrei Popescu30995e72010-02-09 16:59:58 +0000366 // Work out which packages are installed on the system.
367 getInstalledPackages();
Bjorn Bringerta7611812010-03-24 11:12:02 +0000368
369 // Start watching the default geolocation permissions
370 mSystemAllowGeolocationOrigins
371 = new SystemAllowGeolocationOrigins(getApplicationContext());
372 mSystemAllowGeolocationOrigins.start();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800373 }
374
Leon Scroggins58d56c62010-01-28 15:12:40 -0500375 /**
376 * Feed the previously stored results strings to the BrowserProvider so that
377 * the SearchDialog will show them instead of the standard searches.
378 * @param result String to show on the editable line of the SearchDialog.
379 */
380 /* package */ void showVoiceSearchResults(String result) {
381 ContentProviderClient client = mResolver.acquireContentProviderClient(
382 Browser.BOOKMARKS_URI);
383 ContentProvider prov = client.getLocalContentProvider();
384 BrowserProvider bp = (BrowserProvider) prov;
385 bp.setQueryResults(mTabControl.getCurrentTab().getVoiceSearchResults());
386 client.release();
387
Leon Scrogginsfbb3f152010-03-09 17:26:56 -0500388 Bundle bundle = createGoogleSearchSourceBundle(
389 GOOGLE_SEARCH_SOURCE_SEARCHKEY);
390 bundle.putBoolean(SearchManager.CONTEXT_IS_VOICE, true);
391 startSearch(result, false, bundle, false);
Leon Scroggins58d56c62010-01-28 15:12:40 -0500392 }
393
The Android Open Source Project0c908882009-03-03 19:32:16 -0800394 @Override
395 protected void onNewIntent(Intent intent) {
Grace Kloba22ac16e2009-10-07 18:00:23 -0700396 Tab current = mTabControl.getCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800397 // When a tab is closed on exit, the current tab index is set to -1.
398 // Reset before proceed as Browser requires the current tab to be set.
399 if (current == null) {
400 // Try to reset the tab in case the index was incorrect.
401 current = mTabControl.getTab(0);
402 if (current == null) {
403 // No tabs at all so just ignore this intent.
404 return;
405 }
406 mTabControl.setCurrentTab(current);
407 attachTabToContentView(current);
408 resetTitleAndIcon(current.getWebView());
409 }
410 final String action = intent.getAction();
411 final int flags = intent.getFlags();
412 if (Intent.ACTION_MAIN.equals(action) ||
413 (flags & Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY) != 0) {
414 // just resume the browser
415 return;
416 }
Leon Scrogginsb8a844d2010-03-18 15:06:15 -0400417 // In case the SearchDialog is open.
418 ((SearchManager) getSystemService(Context.SEARCH_SERVICE))
419 .stopSearch();
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -0500420 boolean activateVoiceSearch = RecognizerResultsIntent
421 .ACTION_VOICE_SEARCH_RESULTS.equals(action);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800422 if (Intent.ACTION_VIEW.equals(action)
423 || Intent.ACTION_SEARCH.equals(action)
424 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
Leon Scroggins58d56c62010-01-28 15:12:40 -0500425 || Intent.ACTION_WEB_SEARCH.equals(action)
426 || activateVoiceSearch) {
Leon Scroggins3b18ce32010-02-08 17:35:59 -0500427 if (current.isInVoiceSearchMode()) {
428 String title = current.getVoiceDisplayTitle();
429 if (title != null && title.equals(intent.getStringExtra(
430 SearchManager.QUERY))) {
431 // The user submitted the same search as the last voice
432 // search, so do nothing.
433 return;
434 }
Leon Scroggins1fe13a52010-02-09 15:31:26 -0500435 if (Intent.ACTION_SEARCH.equals(action)
436 && current.voiceSearchSourceIsGoogle()) {
437 Intent logIntent = new Intent(
438 LoggingEvents.ACTION_LOG_EVENT);
439 logIntent.putExtra(LoggingEvents.EXTRA_EVENT,
440 LoggingEvents.VoiceSearch.QUERY_UPDATED);
441 logIntent.putExtra(
442 LoggingEvents.VoiceSearch.EXTRA_QUERY_UPDATED_VALUE,
443 intent.getDataString());
444 sendBroadcast(logIntent);
445 // Note, onPageStarted will revert the voice title bar
446 // When http://b/issue?id=2379215 is fixed, we should update
447 // the title bar here.
448 }
Leon Scroggins3b18ce32010-02-08 17:35:59 -0500449 }
Satish Sampath565505b2009-05-29 15:37:27 +0100450 // If this was a search request (e.g. search query directly typed into the address bar),
451 // pass it on to the default web search provider.
452 if (handleWebSearchIntent(intent)) {
453 return;
454 }
455
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700456 UrlData urlData = getUrlDataFromIntent(intent);
457 if (urlData.isEmpty()) {
458 urlData = new UrlData(mSettings.getHomePage());
The Android Open Source Project0c908882009-03-03 19:32:16 -0800459 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700460
Grace Klobacc634032009-07-28 15:58:19 -0700461 final String appId = intent
462 .getStringExtra(Browser.EXTRA_APPLICATION_ID);
Leon Scroggins47208682010-04-07 17:59:48 -0400463 if ((Intent.ACTION_VIEW.equals(action)
464 // If a voice search has no appId, it means that it came
465 // from the browser. In that case, reuse the current tab.
466 || (activateVoiceSearch && appId != null))
Grace Klobacc634032009-07-28 15:58:19 -0700467 && !getPackageName().equals(appId)
468 && (flags & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0) {
Grace Kloba22ac16e2009-10-07 18:00:23 -0700469 Tab appTab = mTabControl.getTabFromId(appId);
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700470 if (appTab != null) {
471 Log.i(LOGTAG, "Reusing tab for " + appId);
472 // Dismiss the subwindow if applicable.
473 dismissSubWindow(appTab);
474 // Since we might kill the WebView, remove it from the
475 // content view first.
476 removeTabFromContentView(appTab);
477 // Recreate the main WebView after destroying the old one.
478 // If the WebView has the same original url and is on that
479 // page, it can be reused.
480 boolean needsLoad =
Leon Scroggins6eac63e2010-03-15 18:19:14 -0400481 mTabControl.recreateWebView(appTab, urlData);
Ben Murdochbff2d602009-07-01 20:19:05 +0100482
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700483 if (current != appTab) {
Leon Scroggins1f005d32009-08-10 17:36:42 -0400484 switchToTab(mTabControl.getTabIndex(appTab));
485 if (needsLoad) {
Patrick Scott9d53da02010-02-19 10:19:01 -0500486 loadUrlDataIn(appTab, urlData);
Leon Scroggins1f005d32009-08-10 17:36:42 -0400487 }
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700488 } else {
Leon Scroggins1f005d32009-08-10 17:36:42 -0400489 // If the tab was the current tab, we have to attach
490 // it to the view system again.
491 attachTabToContentView(appTab);
492 if (needsLoad) {
Patrick Scott9d53da02010-02-19 10:19:01 -0500493 loadUrlDataIn(appTab, urlData);
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700494 }
495 }
496 return;
Patrick Scottcd115892009-07-16 09:42:58 -0400497 } else {
498 // No matching application tab, try to find a regular tab
499 // with a matching url.
500 appTab = mTabControl.findUnusedTabWithUrl(urlData.mUrl);
Leon Scroggins25515f82009-08-19 15:31:58 -0400501 if (appTab != null) {
502 if (current != appTab) {
503 switchToTab(mTabControl.getTabIndex(appTab));
504 }
505 // Otherwise, we are already viewing the correct tab.
Patrick Scottcd115892009-07-16 09:42:58 -0400506 } else {
507 // if FLAG_ACTIVITY_BROUGHT_TO_FRONT flag is on, the url
508 // will be opened in a new tab unless we have reached
509 // MAX_TABS. Then the url will be opened in the current
510 // tab. If a new tab is created, it will have "true" for
511 // exit on close.
Leon Scroggins1f005d32009-08-10 17:36:42 -0400512 openTabAndShow(urlData, true, appId);
Patrick Scottcd115892009-07-16 09:42:58 -0400513 }
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700514 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800515 } else {
Grace Kloba638d3f42009-11-23 10:35:04 -0800516 if (!urlData.isEmpty()
517 && urlData.mUrl.startsWith("about:debug")) {
518 if ("about:debug.dom".equals(urlData.mUrl)) {
519 current.getWebView().dumpDomTree(false);
520 } else if ("about:debug.dom.file".equals(urlData.mUrl)) {
521 current.getWebView().dumpDomTree(true);
522 } else if ("about:debug.render".equals(urlData.mUrl)) {
523 current.getWebView().dumpRenderTree(false);
524 } else if ("about:debug.render.file".equals(urlData.mUrl)) {
525 current.getWebView().dumpRenderTree(true);
526 } else if ("about:debug.display".equals(urlData.mUrl)) {
527 current.getWebView().dumpDisplayTree();
Mike Reed9b78e1d2010-01-13 14:40:52 -0800528 } else if (urlData.mUrl.startsWith("about:debug.drag")) {
529 int index = urlData.mUrl.codePointAt(16) - '0';
530 if (index <= 0 || index > 9) {
531 current.getWebView().setDragTracker(null);
532 } else {
533 current.getWebView().setDragTracker(new MeshTracker(index));
534 }
Grace Kloba638d3f42009-11-23 10:35:04 -0800535 } else {
536 mSettings.toggleDebugSettings();
537 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800538 return;
539 }
Leon Scroggins1f005d32009-08-10 17:36:42 -0400540 // Get rid of the subwindow if it exists
541 dismissSubWindow(current);
Leon Scroggins8588d152010-04-15 11:01:53 -0400542 // If the current Tab is being used as an application tab,
543 // remove the association, since the new Intent means that it is
544 // no longer associated with that application.
545 current.setAppId(null);
Patrick Scott9d53da02010-02-19 10:19:01 -0500546 loadUrlDataIn(current, urlData);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800547 }
548 }
549 }
550
Satish Sampath565505b2009-05-29 15:37:27 +0100551 private int parseUrlShortcut(String url) {
552 if (url == null) return SHORTCUT_INVALID;
553
554 // FIXME: quick search, need to be customized by setting
555 if (url.length() > 2 && url.charAt(1) == ' ') {
556 switch (url.charAt(0)) {
557 case 'g': return SHORTCUT_GOOGLE_SEARCH;
558 case 'w': return SHORTCUT_WIKIPEDIA_SEARCH;
559 case 'd': return SHORTCUT_DICTIONARY_SEARCH;
560 case 'l': return SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH;
561 }
562 }
563 return SHORTCUT_INVALID;
564 }
565
566 /**
567 * Launches the default web search activity with the query parameters if the given intent's data
568 * are identified as plain search terms and not URLs/shortcuts.
569 * @return true if the intent was handled and web search activity was launched, false if not.
570 */
571 private boolean handleWebSearchIntent(Intent intent) {
572 if (intent == null) return false;
573
574 String url = null;
575 final String action = intent.getAction();
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -0500576 if (RecognizerResultsIntent.ACTION_VOICE_SEARCH_RESULTS.equals(
577 action)) {
Leon Scroggins58d56c62010-01-28 15:12:40 -0500578 return false;
579 }
Satish Sampath565505b2009-05-29 15:37:27 +0100580 if (Intent.ACTION_VIEW.equals(action)) {
Grace Kloba1e705052009-09-29 13:13:36 -0700581 Uri data = intent.getData();
582 if (data != null) url = data.toString();
Satish Sampath565505b2009-05-29 15:37:27 +0100583 } else if (Intent.ACTION_SEARCH.equals(action)
584 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
585 || Intent.ACTION_WEB_SEARCH.equals(action)) {
586 url = intent.getStringExtra(SearchManager.QUERY);
587 }
Bjorn Bringert04851702009-09-22 10:36:01 +0100588 return handleWebSearchRequest(url, intent.getBundleExtra(SearchManager.APP_DATA),
589 intent.getStringExtra(SearchManager.EXTRA_DATA_KEY));
Satish Sampath565505b2009-05-29 15:37:27 +0100590 }
591
592 /**
593 * Launches the default web search activity with the query parameters if the given url string
594 * was identified as plain search terms and not URL/shortcut.
595 * @return true if the request was handled and web search activity was launched, false if not.
596 */
Bjorn Bringert04851702009-09-22 10:36:01 +0100597 private boolean handleWebSearchRequest(String inUrl, Bundle appData, String extraData) {
Satish Sampath565505b2009-05-29 15:37:27 +0100598 if (inUrl == null) return false;
599
600 // In general, we shouldn't modify URL from Intent.
601 // But currently, we get the user-typed URL from search box as well.
602 String url = fixUrl(inUrl).trim();
603
604 // URLs and site specific search shortcuts are handled by the regular flow of control, so
605 // return early.
Dan Egnor5ee906c2009-11-18 12:11:49 -0800606 if (Patterns.WEB_URL.matcher(url).matches()
Satish Sampathbc5b9f32009-06-04 18:21:40 +0100607 || ACCEPTED_URI_SCHEMA.matcher(url).matches()
Satish Sampath565505b2009-05-29 15:37:27 +0100608 || parseUrlShortcut(url) != SHORTCUT_INVALID) {
609 return false;
610 }
611
Leon Scroggins8d06e362010-03-24 14:45:57 -0400612 final ContentResolver cr = mResolver;
613 final String newUrl = url;
614 new AsyncTask<Void, Void, Void>() {
615 protected Void doInBackground(Void... unused) {
616 Browser.updateVisitedHistory(cr, newUrl, false);
617 Browser.addSearchUrl(cr, newUrl);
618 return null;
619 }
620 }.execute();
Satish Sampath565505b2009-05-29 15:37:27 +0100621
622 Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);
623 intent.addCategory(Intent.CATEGORY_DEFAULT);
624 intent.putExtra(SearchManager.QUERY, url);
Satish Sampath15e9f2d2009-06-23 22:29:49 +0100625 if (appData != null) {
626 intent.putExtra(SearchManager.APP_DATA, appData);
627 }
Bjorn Bringert04851702009-09-22 10:36:01 +0100628 if (extraData != null) {
629 intent.putExtra(SearchManager.EXTRA_DATA_KEY, extraData);
630 }
Grace Klobacc634032009-07-28 15:58:19 -0700631 intent.putExtra(Browser.EXTRA_APPLICATION_ID, getPackageName());
Mattias Falk552751e2010-08-23 12:03:57 +0200632
633 // can't be sure there is an activity for the Intent
634 try {
635 startActivity(intent);
636 } catch (ActivityNotFoundException ex) {
637 return false;
638 }
Satish Sampath565505b2009-05-29 15:37:27 +0100639
640 return true;
641 }
642
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700643 private UrlData getUrlDataFromIntent(Intent intent) {
Leon Scroggins58d56c62010-01-28 15:12:40 -0500644 String url = "";
Grace Kloba068e48b2010-01-26 18:11:27 -0800645 Map<String, String> headers = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800646 if (intent != null) {
647 final String action = intent.getAction();
648 if (Intent.ACTION_VIEW.equals(action)) {
649 url = smartUrlFilter(intent.getData());
650 if (url != null && url.startsWith("content:")) {
651 /* Append mimetype so webview knows how to display */
652 String mimeType = intent.resolveType(getContentResolver());
653 if (mimeType != null) {
654 url += "?" + mimeType;
655 }
656 }
Grace Kloba068e48b2010-01-26 18:11:27 -0800657 if (url != null && url.startsWith("http")) {
Grace Kloba00f54c52010-01-27 14:53:51 -0800658 final Bundle pairs = intent
659 .getBundleExtra(Browser.EXTRA_HEADERS);
Grace Kloba2d508ed2010-01-28 11:39:15 -0800660 if (pairs != null && !pairs.isEmpty()) {
Grace Kloba00f54c52010-01-27 14:53:51 -0800661 Iterator<String> iter = pairs.keySet().iterator();
Grace Kloba068e48b2010-01-26 18:11:27 -0800662 headers = new HashMap<String, String>();
Grace Kloba00f54c52010-01-27 14:53:51 -0800663 while (iter.hasNext()) {
664 String key = iter.next();
665 headers.put(key, pairs.getString(key));
Grace Kloba068e48b2010-01-26 18:11:27 -0800666 }
667 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700668 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800669 } else if (Intent.ACTION_SEARCH.equals(action)
670 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
671 || Intent.ACTION_WEB_SEARCH.equals(action)) {
672 url = intent.getStringExtra(SearchManager.QUERY);
673 if (url != null) {
674 mLastEnteredUrl = url;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800675 // In general, we shouldn't modify URL from Intent.
676 // But currently, we get the user-typed URL from search box as well.
677 url = fixUrl(url);
678 url = smartUrlFilter(url);
Leon Scroggins8d06e362010-03-24 14:45:57 -0400679 final ContentResolver cr = mResolver;
680 final String newUrl = url;
681 new AsyncTask<Void, Void, Void>() {
682 protected Void doInBackground(Void... unused) {
683 Browser.updateVisitedHistory(cr, newUrl, false);
684 return null;
685 }
686 }.execute();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800687 String searchSource = "&source=android-" + GOOGLE_SEARCH_SOURCE_SUGGEST + "&";
688 if (url.contains(searchSource)) {
689 String source = null;
690 final Bundle appData = intent.getBundleExtra(SearchManager.APP_DATA);
691 if (appData != null) {
Bjorn Bringert10d1cca2010-02-10 14:22:12 +0000692 source = appData.getString(Search.SOURCE);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800693 }
694 if (TextUtils.isEmpty(source)) {
695 source = GOOGLE_SEARCH_SOURCE_UNKNOWN;
696 }
697 url = url.replace(searchSource, "&source=android-"+source+"&");
698 }
699 }
700 }
701 }
Leon Scroggins58d56c62010-01-28 15:12:40 -0500702 return new UrlData(url, headers, intent);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800703 }
Leon Scroggins58d56c62010-01-28 15:12:40 -0500704 /* package */ void showVoiceTitleBar(String title) {
705 mTitleBar.setInVoiceMode(true);
706 mFakeTitleBar.setInVoiceMode(true);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800707
Leon Scroggins58d56c62010-01-28 15:12:40 -0500708 mTitleBar.setDisplayTitle(title);
709 mFakeTitleBar.setDisplayTitle(title);
710 }
711 /* package */ void revertVoiceTitleBar() {
712 mTitleBar.setInVoiceMode(false);
713 mFakeTitleBar.setInVoiceMode(false);
714
Leon Scroggins003a5dd2010-03-10 12:13:14 -0500715 mTitleBar.setDisplayTitle(mUrl);
716 mFakeTitleBar.setDisplayTitle(mUrl);
Leon Scroggins58d56c62010-01-28 15:12:40 -0500717 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800718 /* package */ static String fixUrl(String inUrl) {
Cary Clark652ff872009-09-10 13:34:44 -0400719 // FIXME: Converting the url to lower case
720 // duplicates functionality in smartUrlFilter().
721 // However, changing all current callers of fixUrl to
722 // call smartUrlFilter in addition may have unwanted
723 // consequences, and is deferred for now.
724 int colon = inUrl.indexOf(':');
725 boolean allLower = true;
726 for (int index = 0; index < colon; index++) {
727 char ch = inUrl.charAt(index);
728 if (!Character.isLetter(ch)) {
729 break;
730 }
731 allLower &= Character.isLowerCase(ch);
732 if (index == colon - 1 && !allLower) {
733 inUrl = inUrl.substring(0, colon).toLowerCase()
734 + inUrl.substring(colon);
735 }
736 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800737 if (inUrl.startsWith("http://") || inUrl.startsWith("https://"))
738 return inUrl;
739 if (inUrl.startsWith("http:") ||
740 inUrl.startsWith("https:")) {
741 if (inUrl.startsWith("http:/") || inUrl.startsWith("https:/")) {
742 inUrl = inUrl.replaceFirst("/", "//");
743 } else inUrl = inUrl.replaceFirst(":", "://");
744 }
745 return inUrl;
746 }
747
Grace Kloba22ac16e2009-10-07 18:00:23 -0700748 @Override
749 protected void onResume() {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800750 super.onResume();
Dave Bort31a6d1c2009-04-13 15:56:49 -0700751 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800752 Log.v(LOGTAG, "BrowserActivity.onResume: this=" + this);
753 }
754
755 if (!mActivityInPause) {
756 Log.e(LOGTAG, "BrowserActivity is already resumed.");
757 return;
758 }
759
Mike Reed7bfa63b2009-05-28 11:08:32 -0400760 mTabControl.resumeCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800761 mActivityInPause = false;
Mike Reed7bfa63b2009-05-28 11:08:32 -0400762 resumeWebViewTimers();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800763
764 if (mWakeLock.isHeld()) {
765 mHandler.removeMessages(RELEASE_WAKELOCK);
766 mWakeLock.release();
767 }
768
The Android Open Source Project0c908882009-03-03 19:32:16 -0800769 registerReceiver(mNetworkStateIntentReceiver,
770 mNetworkStateChangedFilter);
771 WebView.enablePlatformNotifications();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800772 }
773
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400774 /**
775 * Since the actual title bar is embedded in the WebView, and removing it
Leon Scrogginsfe87bd32009-10-06 10:10:00 -0400776 * would change its appearance, use a different TitleBar to show overlayed
777 * at the top of the screen, when the menu is open or the page is loading.
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400778 */
779 private TitleBar mFakeTitleBar;
780
781 /**
782 * Keeps track of whether the options menu is open. This is important in
783 * determining whether to show or hide the title bar overlay.
784 */
785 private boolean mOptionsMenuOpen;
786
787 /**
788 * Only meaningful when mOptionsMenuOpen is true. This variable keeps track
789 * of whether the configuration has changed. The first onMenuOpened call
790 * after a configuration change is simply a reopening of the same menu
791 * (i.e. mIconView did not change).
792 */
793 private boolean mConfigChanged;
794
795 /**
796 * Whether or not the options menu is in its smaller, icon menu form. When
797 * true, we want the title bar overlay to be up. When false, we do not.
798 * Only meaningful if mOptionsMenuOpen is true.
799 */
800 private boolean mIconView;
801
Leon Scrogginsa81a7642009-08-31 17:05:41 -0400802 @Override
803 public boolean onMenuOpened(int featureId, Menu menu) {
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400804 if (Window.FEATURE_OPTIONS_PANEL == featureId) {
805 if (mOptionsMenuOpen) {
806 if (mConfigChanged) {
807 // We do not need to make any changes to the state of the
808 // title bar, since the only thing that happened was a
809 // change in orientation
810 mConfigChanged = false;
811 } else {
812 if (mIconView) {
813 // Switching the menu to expanded view, so hide the
814 // title bar.
815 hideFakeTitleBar();
816 mIconView = false;
817 } else {
818 // Switching the menu back to icon view, so show the
819 // title bar once again.
820 showFakeTitleBar();
821 mIconView = true;
822 }
823 }
824 } else {
825 // The options menu is closed, so open it, and show the title
826 showFakeTitleBar();
827 mOptionsMenuOpen = true;
828 mConfigChanged = false;
829 mIconView = true;
830 }
831 }
Leon Scrogginsa81a7642009-08-31 17:05:41 -0400832 return true;
833 }
834
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400835 private void showFakeTitleBar() {
Leon Scrogginsfe87bd32009-10-06 10:10:00 -0400836 if (mFakeTitleBar.getParent() == null && mActiveTabsPage == null
Grace Kloba847c25b2010-03-30 16:00:26 -0700837 && !mActivityInPause) {
838 WebView mainView = mTabControl.getCurrentWebView();
839 // if there is no current WebView, don't show the faked title bar;
Grace Kloba65190702010-04-02 23:37:26 -0700840 if (mainView == null) {
Cary Clarka0464552009-09-29 13:00:45 -0400841 return;
842 }
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400843
844 WindowManager manager
845 = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
846
847 // Add the title bar to the window manager so it can receive touches
848 // while the menu is up
849 WindowManager.LayoutParams params
850 = new WindowManager.LayoutParams(
Romain Guy15b8ec62010-01-08 15:06:43 -0800851 ViewGroup.LayoutParams.MATCH_PARENT,
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400852 ViewGroup.LayoutParams.WRAP_CONTENT,
Grace Kloba847c25b2010-03-30 16:00:26 -0700853 WindowManager.LayoutParams.TYPE_APPLICATION,
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400854 WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
Leon Scroggins68549862009-09-21 16:02:01 -0400855 PixelFormat.TRANSLUCENT);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400856 params.gravity = Gravity.TOP;
Grace Kloba847c25b2010-03-30 16:00:26 -0700857 boolean atTop = mainView.getScrollY() == 0;
Leon Scroggins83932c72009-09-30 11:55:54 -0400858 params.windowAnimations = atTop ? 0 : R.style.TitleBar;
Grace Kloba13f9ace2010-03-18 21:44:14 -0700859 manager.addView(mFakeTitleBar, params);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400860 }
861 }
862
863 @Override
864 public void onOptionsMenuClosed(Menu menu) {
865 mOptionsMenuOpen = false;
Leon Scrogginsa27ff192009-09-14 12:58:04 -0400866 if (!mInLoad) {
867 hideFakeTitleBar();
868 } else if (!mIconView) {
869 // The page is currently loading, and we are in expanded mode, so
870 // we were not showing the menu. Show it once again. It will be
871 // removed when the page finishes.
872 showFakeTitleBar();
873 }
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400874 }
Grace Kloba22ac16e2009-10-07 18:00:23 -0700875
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400876 private void hideFakeTitleBar() {
Leon Scrogginsfe87bd32009-10-06 10:10:00 -0400877 if (mFakeTitleBar.getParent() == null) return;
Leon Scroggins20329572009-09-23 17:42:41 -0400878 WindowManager.LayoutParams params = (WindowManager.LayoutParams)
Grace Kloba13f9ace2010-03-18 21:44:14 -0700879 mFakeTitleBar.getLayoutParams();
Leon Scroggins20329572009-09-23 17:42:41 -0400880 WebView mainView = mTabControl.getCurrentWebView();
881 // Although we decided whether or not to animate based on the current
882 // scroll position, the scroll position may have changed since the
883 // fake title bar was displayed. Make sure it has the appropriate
884 // animation/lack thereof before removing.
885 params.windowAnimations = mainView != null && mainView.getScrollY() == 0
Leon Scroggins83932c72009-09-30 11:55:54 -0400886 ? 0 : R.style.TitleBar;
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400887 WindowManager manager
888 = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
Grace Kloba13f9ace2010-03-18 21:44:14 -0700889 manager.updateViewLayout(mFakeTitleBar, params);
890 manager.removeView(mFakeTitleBar);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400891 }
892
The Android Open Source Project0c908882009-03-03 19:32:16 -0800893 /**
Leon Scrogginsc6fa1102009-09-21 10:40:01 -0400894 * Special method for the fake title bar to call when displaying its context
895 * menu, since it is in its own Window, and its parent does not show a
896 * context menu.
897 */
898 /* package */ void showTitleBarContextMenu() {
Cary Clark65f4a3c2009-09-28 17:05:06 -0400899 if (null == mTitleBar.getParent()) {
900 return;
901 }
Leon Scrogginsc6fa1102009-09-21 10:40:01 -0400902 openContextMenu(mTitleBar);
903 }
904
Leon Scrogginsb2b19f52009-10-09 16:10:00 -0400905 @Override
906 public void onContextMenuClosed(Menu menu) {
907 super.onContextMenuClosed(menu);
908 if (mInLoad) {
909 showFakeTitleBar();
910 }
911 }
912
Leon Scrogginsc6fa1102009-09-21 10:40:01 -0400913 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -0800914 * onSaveInstanceState(Bundle map)
915 * onSaveInstanceState is called right before onStop(). The map contains
916 * the saved state.
917 */
Grace Kloba22ac16e2009-10-07 18:00:23 -0700918 @Override
919 protected void onSaveInstanceState(Bundle outState) {
Dave Bort31a6d1c2009-04-13 15:56:49 -0700920 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800921 Log.v(LOGTAG, "BrowserActivity.onSaveInstanceState: this=" + this);
922 }
923 // the default implementation requires each view to have an id. As the
924 // browser handles the state itself and it doesn't use id for the views,
925 // don't call the default implementation. Otherwise it will trigger the
926 // warning like this, "couldn't save which view has focus because the
927 // focused view XXX has no id".
928
929 // Save all the tabs
930 mTabControl.saveState(outState);
931 }
932
Grace Kloba22ac16e2009-10-07 18:00:23 -0700933 @Override
934 protected void onPause() {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800935 super.onPause();
936
937 if (mActivityInPause) {
938 Log.e(LOGTAG, "BrowserActivity is already paused.");
939 return;
940 }
941
Mike Reed7bfa63b2009-05-28 11:08:32 -0400942 mTabControl.pauseCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800943 mActivityInPause = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -0400944 if (mTabControl.getCurrentIndex() >= 0 && !pauseWebViewTimers()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800945 mWakeLock.acquire();
946 mHandler.sendMessageDelayed(mHandler
947 .obtainMessage(RELEASE_WAKELOCK), WAKELOCK_TIMEOUT);
948 }
949
Leon Scrogginsa2ab6a72009-09-11 11:49:52 -0400950 // FIXME: This removes the active tabs page and resets the menu to
951 // MAIN_MENU. A better solution might be to do this work in onNewIntent
952 // but then we would need to save it in onSaveInstanceState and restore
953 // it in onCreate/onRestoreInstanceState
954 if (mActiveTabsPage != null) {
955 removeActiveTabPage(true);
956 }
957
The Android Open Source Project0c908882009-03-03 19:32:16 -0800958 cancelStopToast();
959
960 // unregister network state listener
961 unregisterReceiver(mNetworkStateIntentReceiver);
962 WebView.disablePlatformNotifications();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800963 }
964
Grace Kloba22ac16e2009-10-07 18:00:23 -0700965 @Override
966 protected void onDestroy() {
Dave Bort31a6d1c2009-04-13 15:56:49 -0700967 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800968 Log.v(LOGTAG, "BrowserActivity.onDestroy: this=" + this);
969 }
970 super.onDestroy();
Grace Kloba0923d692009-09-23 21:37:25 -0700971
Leon Scroggins8d5fa432009-10-02 15:55:59 -0400972 if (mUploadMessage != null) {
973 mUploadMessage.onReceiveValue(null);
974 mUploadMessage = null;
975 }
976
Grace Kloba0923d692009-09-23 21:37:25 -0700977 if (mTabControl == null) return;
978
Grace Kloba1fc98a32009-10-21 13:23:08 -0700979 // Remove the fake title bar if it is there
980 hideFakeTitleBar();
981
The Android Open Source Project0c908882009-03-03 19:32:16 -0800982 // Remove the current tab and sub window
Grace Kloba22ac16e2009-10-07 18:00:23 -0700983 Tab t = mTabControl.getCurrentTab();
Patrick Scottfb5e77f2009-04-08 19:17:37 -0700984 if (t != null) {
985 dismissSubWindow(t);
986 removeTabFromContentView(t);
987 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800988 // Destroy all the tabs
989 mTabControl.destroy();
990 WebIconDatabase.getInstance().close();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800991
Grace Klobab4da0ad2009-05-14 14:45:40 -0700992 unregisterReceiver(mPackageInstallationReceiver);
Bjorn Bringerta7611812010-03-24 11:12:02 +0000993
994 // Stop watching the default geolocation permissions
995 mSystemAllowGeolocationOrigins.stop();
996 mSystemAllowGeolocationOrigins = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800997 }
998
999 @Override
1000 public void onConfigurationChanged(Configuration newConfig) {
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04001001 mConfigChanged = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001002 super.onConfigurationChanged(newConfig);
1003
1004 if (mPageInfoDialog != null) {
1005 mPageInfoDialog.dismiss();
1006 showPageInfo(
1007 mPageInfoView,
Leon Scrogginsc7b92f82010-01-11 18:17:31 -05001008 mPageInfoFromShowSSLCertificateOnError);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001009 }
1010 if (mSSLCertificateDialog != null) {
1011 mSSLCertificateDialog.dismiss();
1012 showSSLCertificate(
1013 mSSLCertificateView);
1014 }
1015 if (mSSLCertificateOnErrorDialog != null) {
1016 mSSLCertificateOnErrorDialog.dismiss();
1017 showSSLCertificateOnError(
1018 mSSLCertificateOnErrorView,
1019 mSSLCertificateOnErrorHandler,
1020 mSSLCertificateOnErrorError);
1021 }
1022 if (mHttpAuthenticationDialog != null) {
1023 String title = ((TextView) mHttpAuthenticationDialog
1024 .findViewById(com.android.internal.R.id.alertTitle)).getText()
1025 .toString();
1026 String name = ((TextView) mHttpAuthenticationDialog
1027 .findViewById(R.id.username_edit)).getText().toString();
1028 String password = ((TextView) mHttpAuthenticationDialog
1029 .findViewById(R.id.password_edit)).getText().toString();
1030 int focusId = mHttpAuthenticationDialog.getCurrentFocus()
1031 .getId();
1032 mHttpAuthenticationDialog.dismiss();
1033 showHttpAuthentication(mHttpAuthHandler, null, null, title,
1034 name, password, focusId);
1035 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001036 }
1037
Grace Kloba22ac16e2009-10-07 18:00:23 -07001038 @Override
1039 public void onLowMemory() {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001040 super.onLowMemory();
1041 mTabControl.freeMemory();
1042 }
1043
Cary Clarkff4d92c2010-03-25 11:17:03 -04001044 private void resumeWebViewTimers() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001045 Tab tab = mTabControl.getCurrentTab();
Cary Clarkff4d92c2010-03-25 11:17:03 -04001046 if (tab == null) return; // monkey can trigger this
Grace Kloba22ac16e2009-10-07 18:00:23 -07001047 boolean inLoad = tab.inLoad();
1048 if ((!mActivityInPause && !inLoad) || (mActivityInPause && inLoad)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001049 CookieSyncManager.getInstance().startSync();
Grace Kloba22ac16e2009-10-07 18:00:23 -07001050 WebView w = tab.getWebView();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001051 if (w != null) {
1052 w.resumeTimers();
1053 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001054 }
1055 }
1056
Mike Reed7bfa63b2009-05-28 11:08:32 -04001057 private boolean pauseWebViewTimers() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001058 Tab tab = mTabControl.getCurrentTab();
1059 boolean inLoad = tab.inLoad();
1060 if (mActivityInPause && !inLoad) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001061 CookieSyncManager.getInstance().stopSync();
1062 WebView w = mTabControl.getCurrentWebView();
1063 if (w != null) {
1064 w.pauseTimers();
1065 }
1066 return true;
1067 } else {
1068 return false;
1069 }
1070 }
1071
The Android Open Source Project0c908882009-03-03 19:32:16 -08001072 // Open the icon database and retain all the icons for visited sites.
1073 private void retainIconsOnStartup() {
1074 final WebIconDatabase db = WebIconDatabase.getInstance();
1075 db.open(getDir("icons", 0).getPath());
Leon Scroggins2c0f6112010-03-12 18:09:39 -05001076 Cursor c = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001077 try {
Leon Scroggins2c0f6112010-03-12 18:09:39 -05001078 c = Browser.getAllBookmarks(mResolver);
1079 if (c.moveToFirst()) {
1080 int urlIndex = c.getColumnIndex(Browser.BookmarkColumns.URL);
1081 do {
1082 String url = c.getString(urlIndex);
1083 db.retainIconForPageUrl(url);
1084 } while (c.moveToNext());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001085 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001086 } catch (IllegalStateException e) {
1087 Log.e(LOGTAG, "retainIconsOnStartup", e);
Leon Scroggins2c0f6112010-03-12 18:09:39 -05001088 } finally {
1089 if (c!= null) c.close();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001090 }
1091 }
1092
1093 // Helper method for getting the top window.
1094 WebView getTopWindow() {
1095 return mTabControl.getCurrentTopWebView();
1096 }
1097
Grace Kloba22ac16e2009-10-07 18:00:23 -07001098 TabControl getTabControl() {
1099 return mTabControl;
1100 }
1101
The Android Open Source Project0c908882009-03-03 19:32:16 -08001102 @Override
1103 public boolean onCreateOptionsMenu(Menu menu) {
1104 super.onCreateOptionsMenu(menu);
1105
1106 MenuInflater inflater = getMenuInflater();
1107 inflater.inflate(R.menu.browser, menu);
1108 mMenu = menu;
1109 updateInLoadMenuItems();
1110 return true;
1111 }
1112
1113 /**
1114 * As the menu can be open when loading state changes
1115 * we must manually update the state of the stop/reload menu
1116 * item
1117 */
1118 private void updateInLoadMenuItems() {
1119 if (mMenu == null) {
1120 return;
1121 }
1122 MenuItem src = mInLoad ?
1123 mMenu.findItem(R.id.stop_menu_id):
1124 mMenu.findItem(R.id.reload_menu_id);
1125 MenuItem dest = mMenu.findItem(R.id.stop_reload_menu_id);
1126 dest.setIcon(src.getIcon());
1127 dest.setTitle(src.getTitle());
1128 }
1129
1130 @Override
1131 public boolean onContextItemSelected(MenuItem item) {
1132 // chording is not an issue with context menus, but we use the same
1133 // options selector, so set mCanChord to true so we can access them.
1134 mCanChord = true;
1135 int id = item.getItemId();
Leon Scroggins96afcb12009-12-10 12:35:56 -05001136 boolean result = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001137 switch (id) {
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001138 // For the context menu from the title bar
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001139 case R.id.title_bar_copy_page_url:
Leon Scroggins96afcb12009-12-10 12:35:56 -05001140 Tab currentTab = mTabControl.getCurrentTab();
1141 if (null == currentTab) {
1142 result = false;
1143 break;
1144 }
1145 WebView mainView = currentTab.getWebView();
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001146 if (null == mainView) {
Leon Scroggins96afcb12009-12-10 12:35:56 -05001147 result = false;
1148 break;
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001149 }
Leon Scroggins96afcb12009-12-10 12:35:56 -05001150 copy(mainView.getUrl());
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001151 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001152 // -- Browser context menu
1153 case R.id.open_context_menu_id:
1154 case R.id.open_newtab_context_menu_id:
1155 case R.id.bookmark_context_menu_id:
1156 case R.id.save_link_context_menu_id:
1157 case R.id.share_link_context_menu_id:
1158 case R.id.copy_link_context_menu_id:
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001159 final WebView webView = getTopWindow();
1160 if (null == webView) {
Leon Scroggins96afcb12009-12-10 12:35:56 -05001161 result = false;
1162 break;
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001163 }
1164 final HashMap hrefMap = new HashMap();
1165 hrefMap.put("webview", webView);
1166 final Message msg = mHandler.obtainMessage(
1167 FOCUS_NODE_HREF, id, 0, hrefMap);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001168 webView.requestFocusNodeHref(msg);
1169 break;
1170
1171 default:
1172 // For other context menus
Leon Scroggins96afcb12009-12-10 12:35:56 -05001173 result = onOptionsItemSelected(item);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001174 }
1175 mCanChord = false;
Leon Scroggins96afcb12009-12-10 12:35:56 -05001176 return result;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001177 }
1178
1179 private Bundle createGoogleSearchSourceBundle(String source) {
1180 Bundle bundle = new Bundle();
Bjorn Bringert10d1cca2010-02-10 14:22:12 +00001181 bundle.putString(Search.SOURCE, source);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001182 return bundle;
1183 }
1184
Leon Scroggins8ad29922010-02-16 12:33:55 -05001185 /* package */ void editUrl() {
Leon Scroggins68579392009-09-15 15:31:54 -04001186 if (mOptionsMenuOpen) closeOptionsMenu();
Leon Scroggins5bbe9802009-07-31 13:10:55 -04001187 String url = (getTopWindow() == null) ? null : getTopWindow().getUrl();
Grace Kloba83f47342009-07-20 10:44:31 -07001188 startSearch(mSettings.getHomePage().equals(url) ? null : url, true,
Leon Scroggins8ad29922010-02-16 12:33:55 -05001189 null, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001190 }
1191
Leon Scroggins8ad29922010-02-16 12:33:55 -05001192 /**
1193 * Overriding this to insert a local information bundle
1194 */
The Android Open Source Project0c908882009-03-03 19:32:16 -08001195 @Override
1196 public void startSearch(String initialQuery, boolean selectInitialQuery,
1197 Bundle appSearchData, boolean globalSearch) {
1198 if (appSearchData == null) {
1199 appSearchData = createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_TYPE);
1200 }
1201 super.startSearch(initialQuery, selectInitialQuery, appSearchData, globalSearch);
1202 }
1203
Leon Scroggins1f005d32009-08-10 17:36:42 -04001204 /**
1205 * Switch tabs. Called by the TitleBarSet when sliding the title bar
1206 * results in changing tabs.
Leon Scroggins160a7e72009-08-14 18:28:01 -04001207 * @param index Index of the tab to change to, as defined by
1208 * mTabControl.getTabIndex(Tab t).
1209 * @return boolean True if we successfully switched to a different tab. If
1210 * the indexth tab is null, or if that tab is the same as
1211 * the current one, return false.
Leon Scroggins1f005d32009-08-10 17:36:42 -04001212 */
Leon Scroggins160a7e72009-08-14 18:28:01 -04001213 /* package */ boolean switchToTab(int index) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001214 Tab tab = mTabControl.getTab(index);
1215 Tab currentTab = mTabControl.getCurrentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04001216 if (tab == null || tab == currentTab) {
Leon Scroggins160a7e72009-08-14 18:28:01 -04001217 return false;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001218 }
1219 if (currentTab != null) {
1220 // currentTab may be null if it was just removed. In that case,
1221 // we do not need to remove it
1222 removeTabFromContentView(currentTab);
1223 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001224 mTabControl.setCurrentTab(tab);
1225 attachTabToContentView(tab);
Grace Klobaeb6eef42009-09-15 17:56:32 -07001226 resetTitleIconAndProgress();
1227 updateLockIconToLatest();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001228 return true;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001229 }
1230
Grace Kloba22ac16e2009-10-07 18:00:23 -07001231 /* package */ Tab openTabToHomePage() {
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001232 return openTabAndShow(mSettings.getHomePage(), false, null);
1233 }
1234
Leon Scroggins1f005d32009-08-10 17:36:42 -04001235 /* package */ void closeCurrentWindow() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001236 final Tab current = mTabControl.getCurrentTab();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001237 if (mTabControl.getTabCount() == 1) {
Leon Scroggins30444232009-09-04 18:36:20 -04001238 // This is the last tab. Open a new one, with the home
1239 // page and close the current one.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001240 openTabToHomePage();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001241 closeTab(current);
Leon Scroggins160a7e72009-08-14 18:28:01 -04001242 return;
1243 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07001244 final Tab parent = current.getParentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04001245 int indexToShow = -1;
1246 if (parent != null) {
1247 indexToShow = mTabControl.getTabIndex(parent);
1248 } else {
Leon Scroggins160a7e72009-08-14 18:28:01 -04001249 final int currentIndex = mTabControl.getCurrentIndex();
1250 // Try to move to the tab to the right
1251 indexToShow = currentIndex + 1;
1252 if (indexToShow > mTabControl.getTabCount() - 1) {
1253 // Try to move to the tab to the left
1254 indexToShow = currentIndex - 1;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001255 }
1256 }
Leon Scroggins160a7e72009-08-14 18:28:01 -04001257 if (switchToTab(indexToShow)) {
1258 // Close window
1259 closeTab(current);
1260 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001261 }
1262
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001263 private ActiveTabsPage mActiveTabsPage;
1264
1265 /**
1266 * Remove the active tabs page.
1267 * @param needToAttach If true, the active tabs page did not attach a tab
1268 * to the content view, so we need to do that here.
1269 */
1270 /* package */ void removeActiveTabPage(boolean needToAttach) {
1271 mContentView.removeView(mActiveTabsPage);
1272 mActiveTabsPage = null;
1273 mMenuState = R.id.MAIN_MENU;
1274 if (needToAttach) {
1275 attachTabToContentView(mTabControl.getCurrentTab());
1276 }
1277 getTopWindow().requestFocus();
1278 }
1279
The Android Open Source Project0c908882009-03-03 19:32:16 -08001280 @Override
1281 public boolean onOptionsItemSelected(MenuItem item) {
1282 if (!mCanChord) {
1283 // The user has already fired a shortcut with this hold down of the
1284 // menu key.
1285 return false;
1286 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001287 if (null == getTopWindow()) {
Leon Scroggins0d7ae0e2009-06-05 11:04:45 -04001288 return false;
1289 }
Grace Kloba6ee9c492009-07-13 10:04:34 -07001290 if (mMenuIsDown) {
1291 // The shortcut action consumes the MENU. Even if it is still down,
1292 // it won't trigger the next shortcut action. In the case of the
1293 // shortcut action triggering a new activity, like Bookmarks, we
1294 // won't get onKeyUp for MENU. So it is important to reset it here.
1295 mMenuIsDown = false;
1296 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001297 switch (item.getItemId()) {
1298 // -- Main menu
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001299 case R.id.new_tab_menu_id:
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001300 openTabToHomePage();
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001301 break;
1302
Leon Scroggins64b80f32009-08-07 12:03:34 -04001303 case R.id.goto_menu_id:
Leon Scroggins8ad29922010-02-16 12:33:55 -05001304 editUrl();
Leon Scrogginsb3a5bed2009-09-28 11:21:56 -04001305 break;
1306
1307 case R.id.bookmarks_menu_id:
Leon Scroggins30444232009-09-04 18:36:20 -04001308 bookmarksOrHistoryPicker(false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001309 break;
1310
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001311 case R.id.active_tabs_menu_id:
1312 mActiveTabsPage = new ActiveTabsPage(this, mTabControl);
1313 removeTabFromContentView(mTabControl.getCurrentTab());
Leon Scroggins43de6162009-09-14 19:59:58 -04001314 hideFakeTitleBar();
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001315 mContentView.addView(mActiveTabsPage, COVER_SCREEN_PARAMS);
1316 mActiveTabsPage.requestFocus();
1317 mMenuState = EMPTY_MENU;
1318 break;
1319
Leon Scroggins1f005d32009-08-10 17:36:42 -04001320 case R.id.add_bookmark_menu_id:
1321 Intent i = new Intent(BrowserActivity.this,
1322 AddBookmarkPage.class);
1323 WebView w = getTopWindow();
1324 i.putExtra("url", w.getUrl());
1325 i.putExtra("title", w.getTitle());
Grace Kloba83cdb2c2009-09-16 00:48:57 -07001326 i.putExtra("touch_icon_url", w.getTouchIconUrl());
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01001327 i.putExtra("thumbnail", createScreenshot(w));
Leon Scroggins1f005d32009-08-10 17:36:42 -04001328 startActivity(i);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001329 break;
1330
1331 case R.id.stop_reload_menu_id:
1332 if (mInLoad) {
1333 stopLoading();
1334 } else {
1335 getTopWindow().reload();
1336 }
1337 break;
1338
1339 case R.id.back_menu_id:
1340 getTopWindow().goBack();
1341 break;
1342
1343 case R.id.forward_menu_id:
1344 getTopWindow().goForward();
1345 break;
1346
1347 case R.id.close_menu_id:
1348 // Close the subwindow if it exists.
1349 if (mTabControl.getCurrentSubWindow() != null) {
1350 dismissSubWindow(mTabControl.getCurrentTab());
1351 break;
1352 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001353 closeCurrentWindow();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001354 break;
1355
1356 case R.id.homepage_menu_id:
Grace Kloba22ac16e2009-10-07 18:00:23 -07001357 Tab current = mTabControl.getCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001358 if (current != null) {
1359 dismissSubWindow(current);
Leon Scroggins92472e82010-02-17 16:32:28 -05001360 loadUrl(current.getWebView(), mSettings.getHomePage());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001361 }
1362 break;
1363
1364 case R.id.preferences_menu_id:
1365 Intent intent = new Intent(this,
1366 BrowserPreferencesPage.class);
Leon Scrogginsd5304942009-12-10 16:11:39 -05001367 intent.putExtra(BrowserPreferencesPage.CURRENT_PAGE,
1368 getTopWindow().getUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001369 startActivityForResult(intent, PREFERENCES_PAGE);
1370 break;
1371
1372 case R.id.find_menu_id:
1373 if (null == mFindDialog) {
1374 mFindDialog = new FindDialog(this);
1375 }
1376 mFindDialog.setWebView(getTopWindow());
1377 mFindDialog.show();
Cary Clark7d3ac792010-03-03 10:11:44 -05001378 getTopWindow().setFindIsUp(true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001379 mMenuState = EMPTY_MENU;
1380 break;
1381
1382 case R.id.select_text_id:
1383 getTopWindow().emulateShiftHeld();
1384 break;
1385 case R.id.page_info_menu_id:
1386 showPageInfo(mTabControl.getCurrentTab(), false);
1387 break;
1388
1389 case R.id.classic_history_menu_id:
Leon Scroggins30444232009-09-04 18:36:20 -04001390 bookmarksOrHistoryPicker(true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001391 break;
1392
Leon Scroggins96afcb12009-12-10 12:35:56 -05001393 case R.id.title_bar_share_page_url:
The Android Open Source Project0c908882009-03-03 19:32:16 -08001394 case R.id.share_page_menu_id:
Leon Scroggins96afcb12009-12-10 12:35:56 -05001395 Tab currentTab = mTabControl.getCurrentTab();
1396 if (null == currentTab) {
1397 mCanChord = false;
1398 return false;
1399 }
1400 currentTab.populatePickerData();
1401 sharePage(this, currentTab.getTitle(),
1402 currentTab.getUrl(), currentTab.getFavicon(),
1403 createScreenshot(currentTab.getWebView()));
The Android Open Source Project0c908882009-03-03 19:32:16 -08001404 break;
1405
1406 case R.id.dump_nav_menu_id:
1407 getTopWindow().debugDump();
1408 break;
1409
Andrei Popescu7a8b88b2010-02-02 00:30:38 +00001410 case R.id.dump_counters_menu_id:
1411 getTopWindow().dumpV8Counters();
1412 break;
1413
The Android Open Source Project0c908882009-03-03 19:32:16 -08001414 case R.id.zoom_in_menu_id:
1415 getTopWindow().zoomIn();
1416 break;
1417
1418 case R.id.zoom_out_menu_id:
1419 getTopWindow().zoomOut();
1420 break;
1421
1422 case R.id.view_downloads_menu_id:
1423 viewDownloads(null);
1424 break;
1425
The Android Open Source Project0c908882009-03-03 19:32:16 -08001426 case R.id.window_one_menu_id:
1427 case R.id.window_two_menu_id:
1428 case R.id.window_three_menu_id:
1429 case R.id.window_four_menu_id:
1430 case R.id.window_five_menu_id:
1431 case R.id.window_six_menu_id:
1432 case R.id.window_seven_menu_id:
1433 case R.id.window_eight_menu_id:
1434 {
1435 int menuid = item.getItemId();
1436 for (int id = 0; id < WINDOW_SHORTCUT_ID_ARRAY.length; id++) {
1437 if (WINDOW_SHORTCUT_ID_ARRAY[id] == menuid) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001438 Tab desiredTab = mTabControl.getTab(id);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001439 if (desiredTab != null &&
1440 desiredTab != mTabControl.getCurrentTab()) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001441 switchToTab(id);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001442 }
1443 break;
1444 }
1445 }
1446 }
1447 break;
1448
1449 default:
1450 if (!super.onOptionsItemSelected(item)) {
1451 return false;
1452 }
1453 // Otherwise fall through.
1454 }
1455 mCanChord = false;
1456 return true;
1457 }
1458
1459 public void closeFind() {
1460 mMenuState = R.id.MAIN_MENU;
1461 }
1462
Grace Kloba22ac16e2009-10-07 18:00:23 -07001463 @Override
1464 public boolean onPrepareOptionsMenu(Menu menu) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001465 // This happens when the user begins to hold down the menu key, so
1466 // allow them to chord to get a shortcut.
1467 mCanChord = true;
1468 // Note: setVisible will decide whether an item is visible; while
1469 // setEnabled() will decide whether an item is enabled, which also means
1470 // whether the matching shortcut key will function.
1471 super.onPrepareOptionsMenu(menu);
1472 switch (mMenuState) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001473 case EMPTY_MENU:
1474 if (mCurrentMenuState != mMenuState) {
1475 menu.setGroupVisible(R.id.MAIN_MENU, false);
1476 menu.setGroupEnabled(R.id.MAIN_MENU, false);
1477 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001478 }
1479 break;
1480 default:
1481 if (mCurrentMenuState != mMenuState) {
1482 menu.setGroupVisible(R.id.MAIN_MENU, true);
1483 menu.setGroupEnabled(R.id.MAIN_MENU, true);
1484 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001485 }
1486 final WebView w = getTopWindow();
1487 boolean canGoBack = false;
1488 boolean canGoForward = false;
1489 boolean isHome = false;
1490 if (w != null) {
1491 canGoBack = w.canGoBack();
1492 canGoForward = w.canGoForward();
1493 isHome = mSettings.getHomePage().equals(w.getUrl());
1494 }
1495 final MenuItem back = menu.findItem(R.id.back_menu_id);
1496 back.setEnabled(canGoBack);
1497
1498 final MenuItem home = menu.findItem(R.id.homepage_menu_id);
1499 home.setEnabled(!isHome);
1500
1501 menu.findItem(R.id.forward_menu_id)
1502 .setEnabled(canGoForward);
1503
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001504 menu.findItem(R.id.new_tab_menu_id).setEnabled(
Grace Kloba22ac16e2009-10-07 18:00:23 -07001505 mTabControl.canCreateNewTab());
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001506
The Android Open Source Project0c908882009-03-03 19:32:16 -08001507 // decide whether to show the share link option
1508 PackageManager pm = getPackageManager();
1509 Intent send = new Intent(Intent.ACTION_SEND);
1510 send.setType("text/plain");
1511 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1512 menu.findItem(R.id.share_page_menu_id).setVisible(ri != null);
1513
The Android Open Source Project0c908882009-03-03 19:32:16 -08001514 boolean isNavDump = mSettings.isNavDump();
1515 final MenuItem nav = menu.findItem(R.id.dump_nav_menu_id);
1516 nav.setVisible(isNavDump);
1517 nav.setEnabled(isNavDump);
Andrei Popescu7a8b88b2010-02-02 00:30:38 +00001518
1519 boolean showDebugSettings = mSettings.showDebugSettings();
1520 final MenuItem counter = menu.findItem(R.id.dump_counters_menu_id);
1521 counter.setVisible(showDebugSettings);
1522 counter.setEnabled(showDebugSettings);
1523
The Android Open Source Project0c908882009-03-03 19:32:16 -08001524 break;
1525 }
1526 mCurrentMenuState = mMenuState;
1527 return true;
1528 }
1529
1530 @Override
1531 public void onCreateContextMenu(ContextMenu menu, View v,
1532 ContextMenuInfo menuInfo) {
Leon Scroggins4e9f89b2010-02-22 16:54:14 -05001533 if (v instanceof TitleBar) {
1534 return;
1535 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001536 WebView webview = (WebView) v;
1537 WebView.HitTestResult result = webview.getHitTestResult();
1538 if (result == null) {
1539 return;
1540 }
1541
1542 int type = result.getType();
1543 if (type == WebView.HitTestResult.UNKNOWN_TYPE) {
1544 Log.w(LOGTAG,
1545 "We should not show context menu when nothing is touched");
1546 return;
1547 }
1548 if (type == WebView.HitTestResult.EDIT_TEXT_TYPE) {
1549 // let TextView handles context menu
1550 return;
1551 }
1552
1553 // Note, http://b/issue?id=1106666 is requesting that
1554 // an inflated menu can be used again. This is not available
1555 // yet, so inflate each time (yuk!)
1556 MenuInflater inflater = getMenuInflater();
1557 inflater.inflate(R.menu.browsercontext, menu);
1558
1559 // Show the correct menu group
1560 String extra = result.getExtra();
1561 menu.setGroupVisible(R.id.PHONE_MENU,
1562 type == WebView.HitTestResult.PHONE_TYPE);
1563 menu.setGroupVisible(R.id.EMAIL_MENU,
1564 type == WebView.HitTestResult.EMAIL_TYPE);
1565 menu.setGroupVisible(R.id.GEO_MENU,
1566 type == WebView.HitTestResult.GEO_TYPE);
1567 menu.setGroupVisible(R.id.IMAGE_MENU,
1568 type == WebView.HitTestResult.IMAGE_TYPE
1569 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1570 menu.setGroupVisible(R.id.ANCHOR_MENU,
1571 type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1572 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1573
1574 // Setup custom handling depending on the type
1575 switch (type) {
1576 case WebView.HitTestResult.PHONE_TYPE:
1577 menu.setHeaderTitle(Uri.decode(extra));
1578 menu.findItem(R.id.dial_context_menu_id).setIntent(
1579 new Intent(Intent.ACTION_VIEW, Uri
1580 .parse(WebView.SCHEME_TEL + extra)));
1581 Intent addIntent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
1582 addIntent.putExtra(Insert.PHONE, Uri.decode(extra));
Cary Clark5e335a32009-09-22 14:53:11 -04001583 addIntent.setType(ContactsContract.Contacts.CONTENT_ITEM_TYPE);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001584 menu.findItem(R.id.add_contact_context_menu_id).setIntent(
1585 addIntent);
1586 menu.findItem(R.id.copy_phone_context_menu_id).setOnMenuItemClickListener(
1587 new Copy(extra));
1588 break;
1589
1590 case WebView.HitTestResult.EMAIL_TYPE:
1591 menu.setHeaderTitle(extra);
1592 menu.findItem(R.id.email_context_menu_id).setIntent(
1593 new Intent(Intent.ACTION_VIEW, Uri
1594 .parse(WebView.SCHEME_MAILTO + extra)));
1595 menu.findItem(R.id.copy_mail_context_menu_id).setOnMenuItemClickListener(
1596 new Copy(extra));
1597 break;
1598
1599 case WebView.HitTestResult.GEO_TYPE:
1600 menu.setHeaderTitle(extra);
1601 menu.findItem(R.id.map_context_menu_id).setIntent(
1602 new Intent(Intent.ACTION_VIEW, Uri
1603 .parse(WebView.SCHEME_GEO
1604 + URLEncoder.encode(extra))));
1605 menu.findItem(R.id.copy_geo_context_menu_id).setOnMenuItemClickListener(
1606 new Copy(extra));
1607 break;
1608
1609 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1610 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
1611 TextView titleView = (TextView) LayoutInflater.from(this)
1612 .inflate(android.R.layout.browser_link_context_header,
1613 null);
1614 titleView.setText(extra);
1615 menu.setHeaderView(titleView);
1616 // decide whether to show the open link in new tab option
1617 menu.findItem(R.id.open_newtab_context_menu_id).setVisible(
Grace Kloba22ac16e2009-10-07 18:00:23 -07001618 mTabControl.canCreateNewTab());
Ben Murdochde353622009-10-12 10:29:00 +01001619 menu.findItem(R.id.bookmark_context_menu_id).setVisible(
1620 Bookmarks.urlHasAcceptableScheme(extra));
The Android Open Source Project0c908882009-03-03 19:32:16 -08001621 PackageManager pm = getPackageManager();
1622 Intent send = new Intent(Intent.ACTION_SEND);
1623 send.setType("text/plain");
1624 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1625 menu.findItem(R.id.share_link_context_menu_id).setVisible(ri != null);
1626 if (type == WebView.HitTestResult.SRC_ANCHOR_TYPE) {
1627 break;
1628 }
1629 // otherwise fall through to handle image part
1630 case WebView.HitTestResult.IMAGE_TYPE:
1631 if (type == WebView.HitTestResult.IMAGE_TYPE) {
1632 menu.setHeaderTitle(extra);
1633 }
1634 menu.findItem(R.id.view_image_context_menu_id).setIntent(
1635 new Intent(Intent.ACTION_VIEW, Uri.parse(extra)));
1636 menu.findItem(R.id.download_context_menu_id).
1637 setOnMenuItemClickListener(new Download(extra));
Ben Murdoch4f75ba22009-10-27 11:48:28 +00001638 menu.findItem(R.id.set_wallpaper_context_menu_id).
1639 setOnMenuItemClickListener(new SetAsWallpaper(extra));
The Android Open Source Project0c908882009-03-03 19:32:16 -08001640 break;
1641
1642 default:
1643 Log.w(LOGTAG, "We should not get here.");
1644 break;
1645 }
Leon Scrogginsb2b19f52009-10-09 16:10:00 -04001646 hideFakeTitleBar();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001647 }
1648
The Android Open Source Project0c908882009-03-03 19:32:16 -08001649 // Attach the given tab to the content view.
Grace Klobac928c302009-09-17 11:51:21 -07001650 // this should only be called for the current tab.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001651 private void attachTabToContentView(Tab t) {
Steve Block2bc69912009-07-30 14:45:13 +01001652 // Attach the container that contains the main WebView and any other UI
1653 // associated with the tab.
Patrick Scottd0119532009-09-17 08:00:31 -04001654 t.attachTabToContentView(mContentView);
Ben Murdochbff2d602009-07-01 20:19:05 +01001655
1656 if (mShouldShowErrorConsole) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001657 ErrorConsoleView errorConsole = t.getErrorConsole(true);
Ben Murdochbff2d602009-07-01 20:19:05 +01001658 if (errorConsole.numberOfErrors() == 0) {
1659 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
1660 } else {
1661 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
1662 }
1663
1664 mErrorConsoleContainer.addView(errorConsole,
Romain Guy15b8ec62010-01-08 15:06:43 -08001665 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
Ben Murdochbff2d602009-07-01 20:19:05 +01001666 ViewGroup.LayoutParams.WRAP_CONTENT));
1667 }
1668
Leon Scroggins39ab28e2009-09-02 21:20:30 -04001669 WebView view = t.getWebView();
Leon Scroggins55a5bc22009-09-04 17:00:08 -04001670 view.setEmbeddedTitleBar(mTitleBar);
Leon Scroggins58d56c62010-01-28 15:12:40 -05001671 if (t.isInVoiceSearchMode()) {
1672 showVoiceTitleBar(t.getVoiceDisplayTitle());
1673 } else {
1674 revertVoiceTitleBar();
1675 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001676 // Request focus on the top window.
1677 t.getTopWindow().requestFocus();
1678 }
1679
1680 // Attach a sub window to the main WebView of the given tab.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001681 void attachSubWindow(Tab t) {
Patrick Scottd0119532009-09-17 08:00:31 -04001682 t.attachSubWindow(mContentView);
1683 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001684 }
1685
1686 // Remove the given tab from the content view.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001687 private void removeTabFromContentView(Tab t) {
Steve Block2bc69912009-07-30 14:45:13 +01001688 // Remove the container that contains the main WebView.
Patrick Scottd0119532009-09-17 08:00:31 -04001689 t.removeTabFromContentView(mContentView);
Ben Murdochbff2d602009-07-01 20:19:05 +01001690
Grace Kloba22ac16e2009-10-07 18:00:23 -07001691 ErrorConsoleView errorConsole = t.getErrorConsole(false);
1692 if (errorConsole != null) {
1693 mErrorConsoleContainer.removeView(errorConsole);
Ben Murdochbff2d602009-07-01 20:19:05 +01001694 }
1695
Leon Scroggins39ab28e2009-09-02 21:20:30 -04001696 WebView view = t.getWebView();
Leon Scrogginsbb85b902009-09-14 19:27:20 -04001697 if (view != null) {
1698 view.setEmbeddedTitleBar(null);
1699 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001700 }
1701
1702 // Remove the sub window if it exists. Also called by TabControl when the
1703 // user clicks the 'X' to dismiss a sub window.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001704 /* package */ void dismissSubWindow(Tab t) {
Patrick Scottd0119532009-09-17 08:00:31 -04001705 t.removeSubWindow(mContentView);
Grace Kloba22ac16e2009-10-07 18:00:23 -07001706 // dismiss the subwindow. This will destroy the WebView.
1707 t.dismissSubWindow();
Patrick Scottd0119532009-09-17 08:00:31 -04001708 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001709 }
1710
Leon Scroggins1f005d32009-08-10 17:36:42 -04001711 // A wrapper function of {@link #openTabAndShow(UrlData, boolean, String)}
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07001712 // that accepts url as string.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001713 private Tab openTabAndShow(String url, boolean closeOnExit, String appId) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001714 return openTabAndShow(new UrlData(url), closeOnExit, appId);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001715 }
1716
1717 // This method does a ton of stuff. It will attempt to create a new tab
1718 // if we haven't reached MAX_TABS. Otherwise it uses the current tab. If
Leon Scroggins1f005d32009-08-10 17:36:42 -04001719 // url isn't null, it will load the given url.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001720 /* package */Tab openTabAndShow(UrlData urlData, boolean closeOnExit,
1721 String appId) {
1722 final Tab currentTab = mTabControl.getCurrentTab();
1723 if (mTabControl.canCreateNewTab()) {
1724 final Tab tab = mTabControl.createNewTab(closeOnExit, appId,
1725 urlData.mUrl);
Leon Scroggins1f005d32009-08-10 17:36:42 -04001726 WebView webview = tab.getWebView();
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001727 // If the last tab was removed from the active tabs page, currentTab
1728 // will be null.
1729 if (currentTab != null) {
1730 removeTabFromContentView(currentTab);
1731 }
Patrick Scott8bbd69f2009-08-14 13:35:53 -04001732 // We must set the new tab as the current tab to reflect the old
1733 // animation behavior.
1734 mTabControl.setCurrentTab(tab);
Grace Klobaeb6eef42009-09-15 17:56:32 -07001735 attachTabToContentView(tab);
Leon Scroggins160a7e72009-08-14 18:28:01 -04001736 if (!urlData.isEmpty()) {
Patrick Scott9d53da02010-02-19 10:19:01 -05001737 loadUrlDataIn(tab, urlData);
Leon Scroggins1f005d32009-08-10 17:36:42 -04001738 }
1739 return tab;
1740 } else {
1741 // Get rid of the subwindow if it exists
1742 dismissSubWindow(currentTab);
1743 if (!urlData.isEmpty()) {
1744 // Load the given url.
Patrick Scott9d53da02010-02-19 10:19:01 -05001745 loadUrlDataIn(currentTab, urlData);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001746 }
Leon Scroggins58d56c62010-01-28 15:12:40 -05001747 return currentTab;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001748 }
1749 }
1750
Grace Kloba22ac16e2009-10-07 18:00:23 -07001751 private Tab openTab(String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001752 if (mSettings.openInBackground()) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001753 Tab t = mTabControl.createNewTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001754 if (t != null) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001755 WebView view = t.getWebView();
Leon Scroggins92472e82010-02-17 16:32:28 -05001756 loadUrl(view, url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001757 }
Grace Klobac9181842009-04-14 08:53:22 -07001758 return t;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001759 } else {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001760 return openTabAndShow(url, false, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001761 }
1762 }
1763
1764 private class Copy implements OnMenuItemClickListener {
1765 private CharSequence mText;
1766
1767 public boolean onMenuItemClick(MenuItem item) {
1768 copy(mText);
1769 return true;
1770 }
1771
1772 public Copy(CharSequence toCopy) {
1773 mText = toCopy;
1774 }
1775 }
1776
1777 private class Download implements OnMenuItemClickListener {
1778 private String mText;
1779
1780 public boolean onMenuItemClick(MenuItem item) {
1781 onDownloadStartNoStream(mText, null, null, null, -1);
1782 return true;
1783 }
1784
1785 public Download(String toDownload) {
1786 mText = toDownload;
1787 }
1788 }
1789
Ben Murdoch4f75ba22009-10-27 11:48:28 +00001790 private class SetAsWallpaper extends Thread implements
1791 OnMenuItemClickListener, DialogInterface.OnCancelListener {
1792 private URL mUrl;
1793 private ProgressDialog mWallpaperProgress;
1794 private boolean mCanceled = false;
1795
1796 public SetAsWallpaper(String url) {
1797 try {
1798 mUrl = new URL(url);
1799 } catch (MalformedURLException e) {
1800 mUrl = null;
1801 }
1802 }
1803
1804 public void onCancel(DialogInterface dialog) {
1805 mCanceled = true;
1806 }
1807
1808 public boolean onMenuItemClick(MenuItem item) {
1809 if (mUrl != null) {
1810 // The user may have tried to set a image with a large file size as their
1811 // background so it may take a few moments to perform the operation. Display
1812 // a progress spinner while it is working.
1813 mWallpaperProgress = new ProgressDialog(BrowserActivity.this);
1814 mWallpaperProgress.setIndeterminate(true);
1815 mWallpaperProgress.setMessage(getText(R.string.progress_dialog_setting_wallpaper));
1816 mWallpaperProgress.setCancelable(true);
1817 mWallpaperProgress.setOnCancelListener(this);
1818 mWallpaperProgress.show();
1819 start();
1820 }
1821 return true;
1822 }
1823
1824 public void run() {
1825 Drawable oldWallpaper = BrowserActivity.this.getWallpaper();
1826 try {
1827 // TODO: This will cause the resource to be downloaded again, when we
1828 // should in most cases be able to grab it from the cache. To fix this
1829 // we should query WebCore to see if we can access a cached version and
1830 // instead open an input stream on that. This pattern could also be used
1831 // in the download manager where the same problem exists.
1832 InputStream inputstream = mUrl.openStream();
1833 if (inputstream != null) {
1834 setWallpaper(inputstream);
1835 }
1836 } catch (IOException e) {
1837 Log.e(LOGTAG, "Unable to set new wallpaper");
1838 // Act as though the user canceled the operation so we try to
1839 // restore the old wallpaper.
1840 mCanceled = true;
1841 }
1842
1843 if (mCanceled) {
1844 // Restore the old wallpaper if the user cancelled whilst we were setting
1845 // the new wallpaper.
1846 int width = oldWallpaper.getIntrinsicWidth();
1847 int height = oldWallpaper.getIntrinsicHeight();
1848 Bitmap bm = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
1849 Canvas canvas = new Canvas(bm);
1850 oldWallpaper.setBounds(0, 0, width, height);
1851 oldWallpaper.draw(canvas);
1852 try {
1853 setWallpaper(bm);
1854 } catch (IOException e) {
1855 Log.e(LOGTAG, "Unable to restore old wallpaper.");
1856 }
1857 mCanceled = false;
1858 }
1859
1860 if (mWallpaperProgress.isShowing()) {
1861 mWallpaperProgress.dismiss();
1862 }
1863 }
1864 }
1865
The Android Open Source Project0c908882009-03-03 19:32:16 -08001866 private void copy(CharSequence text) {
1867 try {
1868 IClipboard clip = IClipboard.Stub.asInterface(ServiceManager.getService("clipboard"));
1869 if (clip != null) {
1870 clip.setClipboardText(text);
1871 }
1872 } catch (android.os.RemoteException e) {
1873 Log.e(LOGTAG, "Copy failed", e);
1874 }
1875 }
1876
1877 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08001878 * Resets the browser title-view to whatever it must be
1879 * (for example, if we had a loading error)
1880 * When we have a new page, we call resetTitle, when we
1881 * have to reset the titlebar to whatever it used to be
1882 * (for example, if the user chose to stop loading), we
1883 * call resetTitleAndRevertLockIcon.
1884 */
1885 /* package */ void resetTitleAndRevertLockIcon() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001886 mTabControl.getCurrentTab().revertLockIcon();
1887 updateLockIconToLatest();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001888 resetTitleIconAndProgress();
1889 }
1890
1891 /**
1892 * Reset the title, favicon, and progress.
1893 */
1894 private void resetTitleIconAndProgress() {
1895 WebView current = mTabControl.getCurrentWebView();
1896 if (current == null) {
1897 return;
1898 }
1899 resetTitleAndIcon(current);
1900 int progress = current.getProgress();
Grace Kloba22ac16e2009-10-07 18:00:23 -07001901 current.getWebChromeClient().onProgressChanged(current, progress);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001902 }
1903
1904 // Reset the title and the icon based on the given item.
1905 private void resetTitleAndIcon(WebView view) {
1906 WebHistoryItem item = view.copyBackForwardList().getCurrentItem();
1907 if (item != null) {
Leon Scroggins68579392009-09-15 15:31:54 -04001908 setUrlTitle(item.getUrl(), item.getTitle());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001909 setFavicon(item.getFavicon());
1910 } else {
Leon Scroggins68579392009-09-15 15:31:54 -04001911 setUrlTitle(null, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001912 setFavicon(null);
1913 }
1914 }
1915
1916 /**
1917 * Sets a title composed of the URL and the title string.
1918 * @param url The URL of the site being loaded.
1919 * @param title The title of the site being loaded.
1920 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07001921 void setUrlTitle(String url, String title) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001922 mUrl = url;
1923 mTitle = title;
1924
Leon Scroggins58d56c62010-01-28 15:12:40 -05001925 // If we are in voice search mode, the title has already been set.
1926 if (mTabControl.getCurrentTab().isInVoiceSearchMode()) return;
1927 mTitleBar.setDisplayTitle(url);
1928 mFakeTitleBar.setDisplayTitle(url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001929 }
1930
1931 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08001932 * @param url The URL to build a title version of the URL from.
1933 * @return The title version of the URL or null if fails.
1934 * The title version of the URL can be either the URL hostname,
1935 * or the hostname with an "https://" prefix (for secure URLs),
1936 * or an empty string if, for example, the URL in question is a
1937 * file:// URL with no hostname.
1938 */
Leon Scroggins32e14a62009-06-11 10:26:34 -04001939 /* package */ static String buildTitleUrl(String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001940 String titleUrl = null;
1941
1942 if (url != null) {
1943 try {
1944 // parse the url string
1945 URL urlObj = new URL(url);
1946 if (urlObj != null) {
1947 titleUrl = "";
1948
1949 String protocol = urlObj.getProtocol();
1950 String host = urlObj.getHost();
1951
1952 if (host != null && 0 < host.length()) {
1953 titleUrl = host;
1954 if (protocol != null) {
1955 // if a secure site, add an "https://" prefix!
1956 if (protocol.equalsIgnoreCase("https")) {
1957 titleUrl = protocol + "://" + host;
1958 }
1959 }
1960 }
1961 }
1962 } catch (MalformedURLException e) {}
1963 }
1964
1965 return titleUrl;
1966 }
1967
1968 // Set the favicon in the title bar.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001969 void setFavicon(Bitmap icon) {
Leon Scroggins68579392009-09-15 15:31:54 -04001970 mTitleBar.setFavicon(icon);
Leon Scrogginsfe87bd32009-10-06 10:10:00 -04001971 mFakeTitleBar.setFavicon(icon);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001972 }
1973
1974 /**
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001975 * Close the tab, remove its associated title bar, and adjust mTabControl's
1976 * current tab to a valid value.
Leon Scroggins1f005d32009-08-10 17:36:42 -04001977 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07001978 /* package */ void closeTab(Tab t) {
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001979 int currentIndex = mTabControl.getCurrentIndex();
1980 int removeIndex = mTabControl.getTabIndex(t);
Leon Scroggins1f005d32009-08-10 17:36:42 -04001981 mTabControl.removeTab(t);
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001982 if (currentIndex >= removeIndex && currentIndex != 0) {
1983 currentIndex--;
1984 }
1985 mTabControl.setCurrentTab(mTabControl.getTab(currentIndex));
Andrei Popescua5bf1de2009-09-23 16:39:23 +01001986 resetTitleIconAndProgress();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001987 }
1988
Leon Scrogginsdcc5eeb2010-02-23 17:26:37 -05001989 /* package */ void goBackOnePageOrQuit() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001990 Tab current = mTabControl.getCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001991 if (current == null) {
1992 /*
1993 * Instead of finishing the activity, simply push this to the back
1994 * of the stack and let ActivityManager to choose the foreground
1995 * activity. As BrowserActivity is singleTask, it will be always the
1996 * root of the task. So we can use either true or false for
1997 * moveTaskToBack().
1998 */
1999 moveTaskToBack(true);
Grace Kloba00d85e72009-09-23 18:50:05 -07002000 return;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002001 }
2002 WebView w = current.getWebView();
2003 if (w.canGoBack()) {
2004 w.goBack();
2005 } else {
2006 // Check to see if we are closing a window that was created by
2007 // another window. If so, we switch back to that window.
Grace Kloba22ac16e2009-10-07 18:00:23 -07002008 Tab parent = current.getParentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002009 if (parent != null) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04002010 switchToTab(mTabControl.getTabIndex(parent));
2011 // Now we close the other tab
2012 closeTab(current);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002013 } else {
2014 if (current.closeOnExit()) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002015 // force the tab's inLoad() to be false as we are going to
2016 // either finish the activity or remove the tab. This will
2017 // ensure pauseWebViewTimers() taking action.
2018 mTabControl.getCurrentTab().clearInLoad();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002019 if (mTabControl.getTabCount() == 1) {
2020 finish();
2021 return;
2022 }
Mike Reed7bfa63b2009-05-28 11:08:32 -04002023 // call pauseWebViewTimers() now, we won't be able to call
2024 // it in onPause() as the WebView won't be valid.
Grace Klobaec1b5ad2009-08-18 08:42:32 -07002025 // Temporarily change mActivityInPause to be true as
2026 // pauseWebViewTimers() will do nothing if mActivityInPause
2027 // is false.
Grace Kloba918e1d72009-08-13 14:55:06 -07002028 boolean savedState = mActivityInPause;
2029 if (savedState) {
Grace Klobaec1b5ad2009-08-18 08:42:32 -07002030 Log.e(LOGTAG, "BrowserActivity is already paused "
2031 + "while handing goBackOnePageOrQuit.");
Grace Kloba918e1d72009-08-13 14:55:06 -07002032 }
2033 mActivityInPause = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -04002034 pauseWebViewTimers();
Grace Kloba918e1d72009-08-13 14:55:06 -07002035 mActivityInPause = savedState;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002036 removeTabFromContentView(current);
2037 mTabControl.removeTab(current);
2038 }
2039 /*
2040 * Instead of finishing the activity, simply push this to the back
2041 * of the stack and let ActivityManager to choose the foreground
2042 * activity. As BrowserActivity is singleTask, it will be always the
2043 * root of the task. So we can use either true or false for
2044 * moveTaskToBack().
2045 */
2046 moveTaskToBack(true);
2047 }
2048 }
2049 }
2050
Grace Kloba22ac16e2009-10-07 18:00:23 -07002051 boolean isMenuDown() {
2052 return mMenuIsDown;
2053 }
2054
Grace Kloba5942df02009-09-18 11:48:29 -07002055 @Override
2056 public boolean onKeyDown(int keyCode, KeyEvent event) {
Leon Scrogginsf65b50d2009-12-08 10:44:28 -05002057 // Even if MENU is already held down, we need to call to super to open
2058 // the IME on long press.
2059 if (KeyEvent.KEYCODE_MENU == keyCode) {
2060 mMenuIsDown = true;
2061 return super.onKeyDown(keyCode, event);
2062 }
Grace Kloba5942df02009-09-18 11:48:29 -07002063 // The default key mode is DEFAULT_KEYS_SEARCH_LOCAL. As the MENU is
2064 // still down, we don't want to trigger the search. Pretend to consume
2065 // the key and do nothing.
2066 if (mMenuIsDown) return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002067
Grace Kloba5942df02009-09-18 11:48:29 -07002068 switch(keyCode) {
Grace Kloba5942df02009-09-18 11:48:29 -07002069 case KeyEvent.KEYCODE_SPACE:
Grace Klobada0fe552009-09-22 18:17:24 -07002070 // WebView/WebTextView handle the keys in the KeyDown. As
2071 // the Activity's shortcut keys are only handled when WebView
2072 // doesn't, have to do it in onKeyDown instead of onKeyUp.
2073 if (event.isShiftPressed()) {
2074 getTopWindow().pageUp(false);
2075 } else {
2076 getTopWindow().pageDown(false);
2077 }
Grace Kloba5942df02009-09-18 11:48:29 -07002078 return true;
2079 case KeyEvent.KEYCODE_BACK:
2080 if (event.getRepeatCount() == 0) {
2081 event.startTracking();
2082 return true;
2083 } else if (mCustomView == null && mActiveTabsPage == null
2084 && event.isLongPress()) {
2085 bookmarksOrHistoryPicker(true);
2086 return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002087 }
Grace Kloba5942df02009-09-18 11:48:29 -07002088 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002089 }
Grace Kloba5942df02009-09-18 11:48:29 -07002090 return super.onKeyDown(keyCode, event);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002091 }
2092
Grace Kloba5942df02009-09-18 11:48:29 -07002093 @Override
2094 public boolean onKeyUp(int keyCode, KeyEvent event) {
2095 switch(keyCode) {
2096 case KeyEvent.KEYCODE_MENU:
2097 mMenuIsDown = false;
2098 break;
Grace Kloba5942df02009-09-18 11:48:29 -07002099 case KeyEvent.KEYCODE_BACK:
2100 if (event.isTracking() && !event.isCanceled()) {
2101 if (mCustomView != null) {
2102 // if a custom view is showing, hide it
Grace Kloba22ac16e2009-10-07 18:00:23 -07002103 mTabControl.getCurrentWebView().getWebChromeClient()
2104 .onHideCustomView();
Grace Kloba5942df02009-09-18 11:48:29 -07002105 } else if (mActiveTabsPage != null) {
2106 // if tab page is showing, hide it
2107 removeActiveTabPage(true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002108 } else {
Grace Kloba5942df02009-09-18 11:48:29 -07002109 WebView subwindow = mTabControl.getCurrentSubWindow();
2110 if (subwindow != null) {
2111 if (subwindow.canGoBack()) {
2112 subwindow.goBack();
2113 } else {
2114 dismissSubWindow(mTabControl.getCurrentTab());
2115 }
2116 } else {
2117 goBackOnePageOrQuit();
2118 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002119 }
Grace Kloba5942df02009-09-18 11:48:29 -07002120 return true;
2121 }
2122 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002123 }
Grace Kloba5942df02009-09-18 11:48:29 -07002124 return super.onKeyUp(keyCode, event);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002125 }
2126
Leon Scroggins68579392009-09-15 15:31:54 -04002127 /* package */ void stopLoading() {
Ben Murdochb7cc8b42009-09-28 10:59:09 +01002128 mDidStopLoad = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002129 resetTitleAndRevertLockIcon();
2130 WebView w = getTopWindow();
2131 w.stopLoading();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002132 // FIXME: before refactor, it is using mWebViewClient. So I keep the
2133 // same logic here. But for subwindow case, should we call into the main
2134 // WebView's onPageFinished as we never call its onPageStarted and if
2135 // the page finishes itself, we don't call onPageFinished.
2136 mTabControl.getCurrentWebView().getWebViewClient().onPageFinished(w,
2137 w.getUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08002138
2139 cancelStopToast();
2140 mStopToast = Toast
2141 .makeText(this, R.string.stopping, Toast.LENGTH_SHORT);
2142 mStopToast.show();
2143 }
2144
Grace Kloba22ac16e2009-10-07 18:00:23 -07002145 boolean didUserStopLoading() {
2146 return mDidStopLoad;
2147 }
2148
The Android Open Source Project0c908882009-03-03 19:32:16 -08002149 private void cancelStopToast() {
2150 if (mStopToast != null) {
2151 mStopToast.cancel();
2152 mStopToast = null;
2153 }
2154 }
2155
Grace Kloba22ac16e2009-10-07 18:00:23 -07002156 // called by a UI or non-UI thread to post the message
2157 public void postMessage(int what, int arg1, int arg2, Object obj,
2158 long delayMillis) {
2159 mHandler.sendMessageDelayed(mHandler.obtainMessage(what, arg1, arg2,
2160 obj), delayMillis);
2161 }
2162
2163 // called by a UI or non-UI thread to remove the message
2164 void removeMessages(int what, Object object) {
2165 mHandler.removeMessages(what, object);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002166 }
2167
2168 // public message ids
2169 public final static int LOAD_URL = 1001;
2170 public final static int STOP_LOAD = 1002;
2171
2172 // Message Ids
2173 private static final int FOCUS_NODE_HREF = 102;
Grace Kloba92c18a52009-07-31 23:48:32 -07002174 private static final int RELEASE_WAKELOCK = 107;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002175
Grace Kloba22ac16e2009-10-07 18:00:23 -07002176 static final int UPDATE_BOOKMARK_THUMBNAIL = 108;
Ben Murdoch2694e232009-09-29 09:41:11 +01002177
The Android Open Source Project0c908882009-03-03 19:32:16 -08002178 // Private handler for handling javascript and saving passwords
2179 private Handler mHandler = new Handler() {
2180
2181 public void handleMessage(Message msg) {
2182 switch (msg.what) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002183 case FOCUS_NODE_HREF:
Ben Murdoch2694e232009-09-29 09:41:11 +01002184 {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002185 String url = (String) msg.getData().get("url");
Ben Murdoch90d088c2009-11-17 18:14:04 +00002186 String title = (String) msg.getData().get("title");
The Android Open Source Project0c908882009-03-03 19:32:16 -08002187 if (url == null || url.length() == 0) {
2188 break;
2189 }
2190 HashMap focusNodeMap = (HashMap) msg.obj;
2191 WebView view = (WebView) focusNodeMap.get("webview");
2192 // Only apply the action if the top window did not change.
2193 if (getTopWindow() != view) {
2194 break;
2195 }
2196 switch (msg.arg1) {
2197 case R.id.open_context_menu_id:
2198 case R.id.view_image_context_menu_id:
Leon Scroggins92472e82010-02-17 16:32:28 -05002199 loadUrlFromContext(getTopWindow(), url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002200 break;
2201 case R.id.open_newtab_context_menu_id:
Grace Kloba22ac16e2009-10-07 18:00:23 -07002202 final Tab parent = mTabControl.getCurrentTab();
2203 final Tab newTab = openTab(url);
Grace Klobac9181842009-04-14 08:53:22 -07002204 if (newTab != parent) {
2205 parent.addChildTab(newTab);
2206 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002207 break;
2208 case R.id.bookmark_context_menu_id:
2209 Intent intent = new Intent(BrowserActivity.this,
2210 AddBookmarkPage.class);
2211 intent.putExtra("url", url);
Ben Murdoch90d088c2009-11-17 18:14:04 +00002212 intent.putExtra("title", title);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002213 startActivity(intent);
2214 break;
2215 case R.id.share_link_context_menu_id:
Leon Scroggins96afcb12009-12-10 12:35:56 -05002216 // See if this site has been visited before
2217 StringBuilder sb = new StringBuilder(
2218 Browser.BookmarkColumns.URL + " = ");
2219 DatabaseUtils.appendEscapedSQLString(sb, url);
Henrik Baarde2629032010-10-04 12:18:43 +02002220 Cursor c = null;
2221 try {
2222 c = mResolver.query(Browser.BOOKMARKS_URI,
2223 Browser.HISTORY_PROJECTION,
2224 sb.toString(),
2225 null,
2226 null);
2227 if (c.moveToFirst()) {
2228 // The site has been visited before, so grab the
2229 // info from the database.
2230 Bitmap favicon = null;
2231 Bitmap thumbnail = null;
2232 String linkTitle = c.getString(Browser.
2233 HISTORY_PROJECTION_TITLE_INDEX);
2234 byte[] data = c.getBlob(Browser.
2235 HISTORY_PROJECTION_FAVICON_INDEX);
2236 if (data != null) {
2237 favicon = BitmapFactory.decodeByteArray(
2238 data, 0, data.length);
2239 }
2240 data = c.getBlob(Browser.
2241 HISTORY_PROJECTION_THUMBNAIL_INDEX);
2242 if (data != null) {
2243 thumbnail = BitmapFactory.decodeByteArray(
2244 data, 0, data.length);
2245 }
2246 sharePage(BrowserActivity.this,
2247 linkTitle, url, favicon, thumbnail);
2248 } else {
2249 Browser.sendString(BrowserActivity.this, url,
2250 getString(
2251 R.string.choosertitle_sharevia));
Leon Scroggins96afcb12009-12-10 12:35:56 -05002252 }
Henrik Baarde2629032010-10-04 12:18:43 +02002253 } finally {
2254 if (c != null) c.close();
Leon Scroggins96afcb12009-12-10 12:35:56 -05002255 }
Channagoud Kadabi37182262010-09-15 23:48:29 -07002256 // close the cursor after its used
2257 if (c != null) {
2258 c.close();
2259 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002260 break;
2261 case R.id.copy_link_context_menu_id:
2262 copy(url);
2263 break;
2264 case R.id.save_link_context_menu_id:
2265 case R.id.download_context_menu_id:
2266 onDownloadStartNoStream(url, null, null, null, -1);
2267 break;
2268 }
2269 break;
Ben Murdoch2694e232009-09-29 09:41:11 +01002270 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002271
2272 case LOAD_URL:
Leon Scroggins92472e82010-02-17 16:32:28 -05002273 loadUrlFromContext(getTopWindow(), (String) msg.obj);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002274 break;
2275
2276 case STOP_LOAD:
2277 stopLoading();
2278 break;
2279
The Android Open Source Project0c908882009-03-03 19:32:16 -08002280 case RELEASE_WAKELOCK:
2281 if (mWakeLock.isHeld()) {
2282 mWakeLock.release();
Grace Kloba5d0e02e2009-10-05 15:15:36 -07002283 // if we reach here, Browser should be still in the
2284 // background loading after WAKELOCK_TIMEOUT (5-min).
2285 // To avoid burning the battery, stop loading.
2286 mTabControl.stopAllLoading();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002287 }
2288 break;
Ben Murdoch2694e232009-09-29 09:41:11 +01002289
2290 case UPDATE_BOOKMARK_THUMBNAIL:
2291 WebView view = (WebView) msg.obj;
2292 if (view != null) {
2293 updateScreenshot(view);
2294 }
2295 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002296 }
2297 }
2298 };
2299
Leon Scroggins96afcb12009-12-10 12:35:56 -05002300 /**
2301 * Share a page, providing the title, url, favicon, and a screenshot. Uses
2302 * an {@link Intent} to launch the Activity chooser.
2303 * @param c Context used to launch a new Activity.
2304 * @param title Title of the page. Stored in the Intent with
Paul Westbrook03e6d392010-02-12 10:33:29 -08002305 * {@link Intent#EXTRA_SUBJECT}
Leon Scroggins96afcb12009-12-10 12:35:56 -05002306 * @param url URL of the page. Stored in the Intent with
2307 * {@link Intent#EXTRA_TEXT}
2308 * @param favicon Bitmap of the favicon for the page. Stored in the Intent
2309 * with {@link Browser#EXTRA_SHARE_FAVICON}
2310 * @param screenshot Bitmap of a screenshot of the page. Stored in the
2311 * Intent with {@link Browser#EXTRA_SHARE_SCREENSHOT}
2312 */
2313 public static final void sharePage(Context c, String title, String url,
2314 Bitmap favicon, Bitmap screenshot) {
2315 Intent send = new Intent(Intent.ACTION_SEND);
2316 send.setType("text/plain");
2317 send.putExtra(Intent.EXTRA_TEXT, url);
Paul Westbrook03e6d392010-02-12 10:33:29 -08002318 send.putExtra(Intent.EXTRA_SUBJECT, title);
Leon Scroggins96afcb12009-12-10 12:35:56 -05002319 send.putExtra(Browser.EXTRA_SHARE_FAVICON, favicon);
2320 send.putExtra(Browser.EXTRA_SHARE_SCREENSHOT, screenshot);
2321 try {
2322 c.startActivity(Intent.createChooser(send, c.getString(
2323 R.string.choosertitle_sharevia)));
2324 } catch(android.content.ActivityNotFoundException ex) {
2325 // if no app handles it, do nothing
2326 }
2327 }
2328
Leon Scroggins89c6d362009-07-15 16:54:37 -04002329 private void updateScreenshot(WebView view) {
2330 // If this is a bookmarked site, add a screenshot to the database.
2331 // FIXME: When should we update? Every time?
2332 // FIXME: Would like to make sure there is actually something to
2333 // draw, but the API for that (WebViewCore.pictureReady()) is not
2334 // currently accessible here.
Ben Murdochaac7aa62009-09-17 16:57:40 +01002335
Patrick Scottcb192b52010-04-14 14:38:55 -04002336 final Bitmap bm = createScreenshot(view);
2337 if (bm == null) {
2338 return;
Leon Scroggins89c6d362009-07-15 16:54:37 -04002339 }
Patrick Scottcb192b52010-04-14 14:38:55 -04002340
2341 final ContentResolver cr = getContentResolver();
2342 final String url = view.getUrl();
2343 final String originalUrl = view.getOriginalUrl();
2344
2345 new AsyncTask<Void, Void, Void>() {
2346 @Override
2347 protected Void doInBackground(Void... unused) {
2348 Cursor c = null;
2349 try {
2350 c = BrowserBookmarksAdapter.queryBookmarksForUrl(
2351 cr, originalUrl, url, true);
2352 if (c != null) {
2353 if (c.moveToFirst()) {
2354 ContentValues values = new ContentValues();
2355 final ByteArrayOutputStream os
2356 = new ByteArrayOutputStream();
2357 bm.compress(Bitmap.CompressFormat.PNG, 100, os);
2358 values.put(Browser.BookmarkColumns.THUMBNAIL,
2359 os.toByteArray());
2360 do {
2361 cr.update(ContentUris.withAppendedId(
2362 Browser.BOOKMARKS_URI, c.getInt(0)),
2363 values, null, null);
2364 } while (c.moveToNext());
2365 }
2366 }
2367 } catch (IllegalStateException e) {
2368 // Ignore
2369 } finally {
2370 if (c != null) c.close();
2371 }
2372 return null;
2373 }
2374 }.execute();
Leon Scroggins89c6d362009-07-15 16:54:37 -04002375 }
2376
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002377 /**
Leon Scrogginsf8551612009-09-24 16:06:02 -04002378 * Values for the size of the thumbnail created when taking a screenshot.
2379 * Lazily initialized. Instead of using these directly, use
2380 * getDesiredThumbnailWidth() or getDesiredThumbnailHeight().
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002381 */
Leon Scrogginsf8551612009-09-24 16:06:02 -04002382 private static int THUMBNAIL_WIDTH = 0;
2383 private static int THUMBNAIL_HEIGHT = 0;
2384
2385 /**
2386 * Return the desired width for thumbnail screenshots, which are stored in
2387 * the database, and used on the bookmarks screen.
2388 * @param context Context for finding out the density of the screen.
2389 * @return int desired width for thumbnail screenshot.
2390 */
2391 /* package */ static int getDesiredThumbnailWidth(Context context) {
2392 if (THUMBNAIL_WIDTH == 0) {
2393 float density = context.getResources().getDisplayMetrics().density;
2394 THUMBNAIL_WIDTH = (int) (90 * density);
2395 THUMBNAIL_HEIGHT = (int) (80 * density);
2396 }
2397 return THUMBNAIL_WIDTH;
2398 }
2399
2400 /**
2401 * Return the desired height for thumbnail screenshots, which are stored in
2402 * the database, and used on the bookmarks screen.
2403 * @param context Context for finding out the density of the screen.
2404 * @return int desired height for thumbnail screenshot.
2405 */
2406 /* package */ static int getDesiredThumbnailHeight(Context context) {
2407 // To ensure that they are both initialized.
2408 getDesiredThumbnailWidth(context);
2409 return THUMBNAIL_HEIGHT;
2410 }
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002411
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002412 private Bitmap createScreenshot(WebView view) {
2413 Picture thumbnail = view.capturePicture();
Leon Scroggins45800572009-09-29 16:38:47 -04002414 if (thumbnail == null) {
2415 return null;
2416 }
Leon Scrogginsf8551612009-09-24 16:06:02 -04002417 Bitmap bm = Bitmap.createBitmap(getDesiredThumbnailWidth(this),
Cary Clarkab168ba2010-04-08 09:11:28 -04002418 getDesiredThumbnailHeight(this), Bitmap.Config.RGB_565);
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002419 Canvas canvas = new Canvas(bm);
2420 // May need to tweak these values to determine what is the
2421 // best scale factor
Ben Murdoch2694e232009-09-29 09:41:11 +01002422 int thumbnailWidth = thumbnail.getWidth();
Ben Murdochae59c3f2009-10-20 18:30:28 +01002423 int thumbnailHeight = thumbnail.getHeight();
2424 float scaleFactorX = 1.0f;
2425 float scaleFactorY = 1.0f;
Ben Murdoch2694e232009-09-29 09:41:11 +01002426 if (thumbnailWidth > 0) {
Ben Murdochae59c3f2009-10-20 18:30:28 +01002427 scaleFactorX = (float) getDesiredThumbnailWidth(this) /
Ben Murdoch2694e232009-09-29 09:41:11 +01002428 (float)thumbnailWidth;
Ben Murdochae59c3f2009-10-20 18:30:28 +01002429 } else {
2430 return null;
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002431 }
Ben Murdochae59c3f2009-10-20 18:30:28 +01002432
2433 if (view.getWidth() > view.getHeight() &&
2434 thumbnailHeight < view.getHeight() && thumbnailHeight > 0) {
2435 // If the device is in landscape and the page is shorter
2436 // than the height of the view, stretch the thumbnail to fill the
2437 // space.
2438 scaleFactorY = (float) getDesiredThumbnailHeight(this) /
2439 (float)thumbnailHeight;
2440 } else {
2441 // In the portrait case, this looks nice.
2442 scaleFactorY = scaleFactorX;
2443 }
2444
2445 canvas.scale(scaleFactorX, scaleFactorY);
2446
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002447 thumbnail.draw(canvas);
2448 return bm;
2449 }
2450
The Android Open Source Project0c908882009-03-03 19:32:16 -08002451 // -------------------------------------------------------------------------
Grace Kloba22ac16e2009-10-07 18:00:23 -07002452 // Helper function for WebViewClient.
The Android Open Source Project0c908882009-03-03 19:32:16 -08002453 //-------------------------------------------------------------------------
2454
2455 // Use in overrideUrlLoading
2456 /* package */ final static String SCHEME_WTAI = "wtai://wp/";
2457 /* package */ final static String SCHEME_WTAI_MC = "wtai://wp/mc;";
2458 /* package */ final static String SCHEME_WTAI_SD = "wtai://wp/sd;";
2459 /* package */ final static String SCHEME_WTAI_AP = "wtai://wp/ap;";
2460
Leon Scroggins92472e82010-02-17 16:32:28 -05002461 // Keep this initial progress in sync with initialProgressValue (* 100)
2462 // in ProgressTracker.cpp
2463 private final static int INITIAL_PROGRESS = 10;
2464
Grace Kloba22ac16e2009-10-07 18:00:23 -07002465 void onPageStarted(WebView view, String url, Bitmap favicon) {
2466 // when BrowserActivity just starts, onPageStarted may be called before
2467 // onResume as it is triggered from onCreate. Call resumeWebViewTimers
2468 // to start the timer. As we won't switch tabs while an activity is in
2469 // pause state, we can ensure calling resume and pause in pair.
2470 if (mActivityInPause) resumeWebViewTimers();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002471
Grace Kloba22ac16e2009-10-07 18:00:23 -07002472 resetLockIcon(url);
2473 setUrlTitle(url, null);
2474 setFavicon(favicon);
Leon Scroggins8cf8f682009-11-04 11:13:50 -08002475 // Show some progress so that the user knows the page is beginning to
2476 // load
Leon Scroggins92472e82010-02-17 16:32:28 -05002477 onProgressChanged(view, INITIAL_PROGRESS);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002478 mDidStopLoad = false;
Grace Kloba22ac16e2009-10-07 18:00:23 -07002479 if (!mIsNetworkUp) createAndShowNetworkDialog();
Patrick Scott15525d42009-09-21 13:39:37 -04002480
Grace Kloba22ac16e2009-10-07 18:00:23 -07002481 if (mSettings.isTracing()) {
2482 String host;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002483 try {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002484 WebAddress uri = new WebAddress(url);
2485 host = uri.mHost;
2486 } catch (android.net.ParseException ex) {
2487 host = "browser";
The Android Open Source Project0c908882009-03-03 19:32:16 -08002488 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002489 host = host.replace('.', '_');
2490 host += ".trace";
2491 mInTrace = true;
2492 Debug.startMethodTracing(host, 20 * 1024 * 1024);
2493 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002494
Grace Kloba22ac16e2009-10-07 18:00:23 -07002495 // Performance probe
2496 if (false) {
2497 mStart = SystemClock.uptimeMillis();
2498 mProcessStart = Process.getElapsedCpuTime();
2499 long[] sysCpu = new long[7];
2500 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2501 sysCpu, null)) {
2502 mUserStart = sysCpu[0] + sysCpu[1];
2503 mSystemStart = sysCpu[2];
2504 mIdleStart = sysCpu[3];
2505 mIrqStart = sysCpu[4] + sysCpu[5] + sysCpu[6];
2506 }
2507 mUiStart = SystemClock.currentThreadTimeMillis();
2508 }
2509 }
2510
2511 void onPageFinished(WebView view, String url) {
2512 // Reset the title and icon in case we stopped a provisional load.
2513 resetTitleAndIcon(view);
2514 // Update the lock icon image only once we are done loading
2515 updateLockIconToLatest();
2516 // pause the WebView timer and release the wake lock if it is finished
2517 // while BrowserActivity is in pause state.
2518 if (mActivityInPause && pauseWebViewTimers()) {
2519 if (mWakeLock.isHeld()) {
2520 mHandler.removeMessages(RELEASE_WAKELOCK);
2521 mWakeLock.release();
2522 }
2523 }
2524
2525 // Performance probe
2526 if (false) {
2527 long[] sysCpu = new long[7];
2528 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2529 sysCpu, null)) {
2530 String uiInfo = "UI thread used "
2531 + (SystemClock.currentThreadTimeMillis() - mUiStart)
2532 + " ms";
2533 if (LOGD_ENABLED) {
2534 Log.d(LOGTAG, uiInfo);
2535 }
2536 //The string that gets written to the log
2537 String performanceString = "It took total "
2538 + (SystemClock.uptimeMillis() - mStart)
2539 + " ms clock time to load the page."
2540 + "\nbrowser process used "
2541 + (Process.getElapsedCpuTime() - mProcessStart)
2542 + " ms, user processes used "
2543 + (sysCpu[0] + sysCpu[1] - mUserStart) * 10
2544 + " ms, kernel used "
2545 + (sysCpu[2] - mSystemStart) * 10
2546 + " ms, idle took " + (sysCpu[3] - mIdleStart) * 10
2547 + " ms and irq took "
2548 + (sysCpu[4] + sysCpu[5] + sysCpu[6] - mIrqStart)
2549 * 10 + " ms, " + uiInfo;
2550 if (LOGD_ENABLED) {
2551 Log.d(LOGTAG, performanceString + "\nWebpage: " + url);
2552 }
2553 if (url != null) {
2554 // strip the url to maintain consistency
2555 String newUrl = new String(url);
2556 if (newUrl.startsWith("http://www.")) {
2557 newUrl = newUrl.substring(11);
2558 } else if (newUrl.startsWith("http://")) {
2559 newUrl = newUrl.substring(7);
2560 } else if (newUrl.startsWith("https://www.")) {
2561 newUrl = newUrl.substring(12);
2562 } else if (newUrl.startsWith("https://")) {
2563 newUrl = newUrl.substring(8);
2564 }
2565 if (LOGD_ENABLED) {
2566 Log.d(LOGTAG, newUrl + " loaded");
2567 }
Grace Kloba5b078b52009-06-24 20:23:41 -07002568 }
2569 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002570 }
Grace Kloba5b078b52009-06-24 20:23:41 -07002571
Grace Kloba22ac16e2009-10-07 18:00:23 -07002572 if (mInTrace) {
2573 mInTrace = false;
2574 Debug.stopMethodTracing();
2575 }
2576 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002577
Grace Kloba22ac16e2009-10-07 18:00:23 -07002578 boolean shouldOverrideUrlLoading(WebView view, String url) {
2579 if (url.startsWith(SCHEME_WTAI)) {
2580 // wtai://wp/mc;number
2581 // number=string(phone-number)
2582 if (url.startsWith(SCHEME_WTAI_MC)) {
2583 Intent intent = new Intent(Intent.ACTION_VIEW,
2584 Uri.parse(WebView.SCHEME_TEL +
2585 url.substring(SCHEME_WTAI_MC.length())));
2586 startActivity(intent);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002587 return true;
2588 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002589 // wtai://wp/sd;dtmf
2590 // dtmf=string(dialstring)
2591 if (url.startsWith(SCHEME_WTAI_SD)) {
2592 // TODO: only send when there is active voice connection
2593 return false;
2594 }
2595 // wtai://wp/ap;number;name
2596 // number=string(phone-number)
2597 // name=string
2598 if (url.startsWith(SCHEME_WTAI_AP)) {
2599 // TODO
2600 return false;
2601 }
2602 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002603
Grace Kloba22ac16e2009-10-07 18:00:23 -07002604 // The "about:" schemes are internal to the browser; don't want these to
2605 // be dispatched to other apps.
2606 if (url.startsWith("about:")) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002607 return false;
2608 }
2609
Grace Kloba22ac16e2009-10-07 18:00:23 -07002610 Intent intent;
2611 // perform generic parsing of the URI to turn it into an Intent.
2612 try {
2613 intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME);
2614 } catch (URISyntaxException ex) {
2615 Log.w("Browser", "Bad URI " + url + ": " + ex.getMessage());
2616 return false;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002617 }
2618
Grace Kloba22ac16e2009-10-07 18:00:23 -07002619 // check whether the intent can be resolved. If not, we will see
2620 // whether we can download it from the Market.
2621 if (getPackageManager().resolveActivity(intent, 0) == null) {
2622 String packagename = intent.getPackage();
2623 if (packagename != null) {
2624 intent = new Intent(Intent.ACTION_VIEW, Uri
2625 .parse("market://search?q=pname:" + packagename));
2626 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2627 startActivity(intent);
2628 return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002629 } else {
2630 return false;
2631 }
2632 }
2633
Grace Kloba22ac16e2009-10-07 18:00:23 -07002634 // sanitize the Intent, ensuring web pages can not bypass browser
2635 // security (only access to BROWSABLE activities).
2636 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2637 intent.setComponent(null);
2638 try {
2639 if (startActivityIfNeeded(intent, -1)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002640 return true;
2641 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002642 } catch (ActivityNotFoundException ex) {
2643 // ignore the error. If no application can handle the URL,
2644 // eg about:blank, assume the browser can handle it.
2645 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002646
Grace Kloba22ac16e2009-10-07 18:00:23 -07002647 if (mMenuIsDown) {
2648 openTab(url);
2649 closeOptionsMenu();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002650 return true;
2651 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002652 return false;
2653 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002654
Grace Kloba22ac16e2009-10-07 18:00:23 -07002655 // -------------------------------------------------------------------------
2656 // Helper function for WebChromeClient
2657 // -------------------------------------------------------------------------
The Android Open Source Project0c908882009-03-03 19:32:16 -08002658
Grace Kloba22ac16e2009-10-07 18:00:23 -07002659 void onProgressChanged(WebView view, int newProgress) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002660 mFakeTitleBar.setProgress(newProgress);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002661
Grace Kloba22ac16e2009-10-07 18:00:23 -07002662 if (newProgress == 100) {
2663 // onProgressChanged() may continue to be called after the main
2664 // frame has finished loading, as any remaining sub frames continue
2665 // to load. We'll only get called once though with newProgress as
2666 // 100 when everything is loaded. (onPageFinished is called once
2667 // when the main frame completes loading regardless of the state of
2668 // any sub frames so calls to onProgressChanges may continue after
2669 // onPageFinished has executed)
2670 if (mInLoad) {
2671 mInLoad = false;
Leon Scrogginsa27ff192009-09-14 12:58:04 -04002672 updateInLoadMenuItems();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002673 // If the options menu is open, leave the title bar
2674 if (!mOptionsMenuOpen || !mIconView) {
2675 hideFakeTitleBar();
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07002676 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002677 }
Leon Scrogginsaa37e7f2010-03-05 11:51:20 -05002678 } else {
2679 if (!mInLoad) {
2680 // onPageFinished may have already been called but a subframe is
2681 // still loading and updating the progress. Reset mInLoad and
2682 // update the menu items.
2683 mInLoad = true;
2684 updateInLoadMenuItems();
2685 }
2686 // When the page first begins to load, the Activity may still be
2687 // paused, in which case showFakeTitleBar will do nothing. Call
2688 // again as the page continues to load so that it will be shown.
2689 // (Calling it will the fake title bar is already showing will also
2690 // do nothing.
Grace Kloba22ac16e2009-10-07 18:00:23 -07002691 if (!mOptionsMenuOpen || mIconView) {
2692 // This page has begun to load, so show the title bar
2693 showFakeTitleBar();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002694 }
2695 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002696 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002697
Grace Kloba22ac16e2009-10-07 18:00:23 -07002698 void onShowCustomView(View view, WebChromeClient.CustomViewCallback callback) {
Derek Sollenberger8ff57db2009-12-08 15:39:55 -05002699 // if a view already exists then immediately terminate the new one
2700 if (mCustomView != null) {
2701 callback.onCustomViewHidden();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002702 return;
Derek Sollenberger8ff57db2009-12-08 15:39:55 -05002703 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002704
2705 // Add the custom view to its container.
2706 mCustomViewContainer.addView(view, COVER_SCREEN_GRAVITY_CENTER);
2707 mCustomView = view;
2708 mCustomViewCallback = callback;
2709 // Save the menu state and set it to empty while the custom
2710 // view is showing.
2711 mOldMenuState = mMenuState;
2712 mMenuState = EMPTY_MENU;
2713 // Hide the content view.
2714 mContentView.setVisibility(View.GONE);
2715 // Finally show the custom view container.
Andrei Popescu163ab742009-10-20 17:58:23 +01002716 setStatusBarVisibility(false);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002717 mCustomViewContainer.setVisibility(View.VISIBLE);
2718 mCustomViewContainer.bringToFront();
2719 }
2720
2721 void onHideCustomView() {
2722 if (mCustomView == null)
2723 return;
2724
2725 // Hide the custom view.
2726 mCustomView.setVisibility(View.GONE);
2727 // Remove the custom view from its container.
2728 mCustomViewContainer.removeView(mCustomView);
2729 mCustomView = null;
2730 // Reset the old menu state.
2731 mMenuState = mOldMenuState;
2732 mOldMenuState = EMPTY_MENU;
2733 mCustomViewContainer.setVisibility(View.GONE);
2734 mCustomViewCallback.onCustomViewHidden();
2735 // Show the content view.
Andrei Popescu163ab742009-10-20 17:58:23 +01002736 setStatusBarVisibility(true);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002737 mContentView.setVisibility(View.VISIBLE);
2738 }
2739
2740 Bitmap getDefaultVideoPoster() {
2741 if (mDefaultVideoPoster == null) {
2742 mDefaultVideoPoster = BitmapFactory.decodeResource(
2743 getResources(), R.drawable.default_video_poster);
Patrick Scott3918d442009-08-04 13:22:29 -04002744 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002745 return mDefaultVideoPoster;
2746 }
Patrick Scott3918d442009-08-04 13:22:29 -04002747
Grace Kloba22ac16e2009-10-07 18:00:23 -07002748 View getVideoLoadingProgressView() {
2749 if (mVideoProgressView == null) {
2750 LayoutInflater inflater = LayoutInflater.from(BrowserActivity.this);
2751 mVideoProgressView = inflater.inflate(
2752 R.layout.video_loading_progress, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002753 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002754 return mVideoProgressView;
2755 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002756
Leon Scroggins8d5fa432009-10-02 15:55:59 -04002757 /*
2758 * The Object used to inform the WebView of the file to upload.
2759 */
2760 private ValueCallback<Uri> mUploadMessage;
2761
Grace Kloba22ac16e2009-10-07 18:00:23 -07002762 void openFileChooser(ValueCallback<Uri> uploadMsg) {
2763 if (mUploadMessage != null) return;
2764 mUploadMessage = uploadMsg;
2765 Intent i = new Intent(Intent.ACTION_GET_CONTENT);
2766 i.addCategory(Intent.CATEGORY_OPENABLE);
2767 i.setType("*/*");
2768 BrowserActivity.this.startActivityForResult(Intent.createChooser(i,
2769 getString(R.string.choose_upload)), FILE_SELECTED);
2770 }
2771
2772 // -------------------------------------------------------------------------
2773 // Implement functions for DownloadListener
2774 // -------------------------------------------------------------------------
2775
The Android Open Source Project0c908882009-03-03 19:32:16 -08002776 /**
2777 * Notify the host application a download should be done, or that
2778 * the data should be streamed if a streaming viewer is available.
2779 * @param url The full url to the content that should be downloaded
2780 * @param contentDisposition Content-disposition http header, if
2781 * present.
2782 * @param mimetype The mimetype of the content reported by the server
2783 * @param contentLength The file size reported by the server
2784 */
2785 public void onDownloadStart(String url, String userAgent,
2786 String contentDisposition, String mimetype, long contentLength) {
2787 // if we're dealing wih A/V content that's not explicitly marked
2788 // for download, check if it's streamable.
2789 if (contentDisposition == null
Patrick Scotte1fb9662009-08-31 14:31:52 -04002790 || !contentDisposition.regionMatches(
2791 true, 0, "attachment", 0, 10)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002792 // query the package manager to see if there's a registered handler
2793 // that matches.
2794 Intent intent = new Intent(Intent.ACTION_VIEW);
2795 intent.setDataAndType(Uri.parse(url), mimetype);
Patrick Scotte1fb9662009-08-31 14:31:52 -04002796 ResolveInfo info = getPackageManager().resolveActivity(intent,
2797 PackageManager.MATCH_DEFAULT_ONLY);
2798 if (info != null) {
2799 ComponentName myName = getComponentName();
2800 // If we resolved to ourselves, we don't want to attempt to
2801 // load the url only to try and download it again.
2802 if (!myName.getPackageName().equals(
2803 info.activityInfo.packageName)
2804 || !myName.getClassName().equals(
2805 info.activityInfo.name)) {
2806 // someone (other than us) knows how to handle this mime
2807 // type with this scheme, don't download.
2808 try {
2809 startActivity(intent);
2810 return;
2811 } catch (ActivityNotFoundException ex) {
2812 if (LOGD_ENABLED) {
2813 Log.d(LOGTAG, "activity not found for " + mimetype
2814 + " over " + Uri.parse(url).getScheme(),
2815 ex);
2816 }
2817 // Best behavior is to fall back to a download in this
2818 // case
The Android Open Source Project0c908882009-03-03 19:32:16 -08002819 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002820 }
2821 }
2822 }
2823 onDownloadStartNoStream(url, userAgent, contentDisposition, mimetype, contentLength);
2824 }
2825
Kristian Monsenfa52d172010-03-25 18:29:21 +00002826 // This is to work around the fact that java.net.URI throws Exceptions
2827 // instead of just encoding URL's properly
2828 // Helper method for onDownloadStartNoStream
2829 private static String encodePath(String path) {
2830 char[] chars = path.toCharArray();
2831
2832 boolean needed = false;
2833 for (char c : chars) {
2834 if (c == '[' || c == ']') {
2835 needed = true;
2836 break;
2837 }
2838 }
2839 if (needed == false) {
2840 return path;
2841 }
2842
2843 StringBuilder sb = new StringBuilder("");
2844 for (char c : chars) {
2845 if (c == '[' || c == ']') {
2846 sb.append('%');
2847 sb.append(Integer.toHexString(c));
2848 } else {
2849 sb.append(c);
2850 }
2851 }
2852
2853 return sb.toString();
2854 }
2855
The Android Open Source Project0c908882009-03-03 19:32:16 -08002856 /**
2857 * Notify the host application a download should be done, even if there
2858 * is a streaming viewer available for thise type.
2859 * @param url The full url to the content that should be downloaded
2860 * @param contentDisposition Content-disposition http header, if
2861 * present.
2862 * @param mimetype The mimetype of the content reported by the server
2863 * @param contentLength The file size reported by the server
2864 */
2865 /*package */ void onDownloadStartNoStream(String url, String userAgent,
2866 String contentDisposition, String mimetype, long contentLength) {
2867
2868 String filename = URLUtil.guessFileName(url,
2869 contentDisposition, mimetype);
2870
2871 // Check to see if we have an SDCard
2872 String status = Environment.getExternalStorageState();
2873 if (!status.equals(Environment.MEDIA_MOUNTED)) {
2874 int title;
2875 String msg;
2876
2877 // Check to see if the SDCard is busy, same as the music app
2878 if (status.equals(Environment.MEDIA_SHARED)) {
2879 msg = getString(R.string.download_sdcard_busy_dlg_msg);
2880 title = R.string.download_sdcard_busy_dlg_title;
2881 } else {
2882 msg = getString(R.string.download_no_sdcard_dlg_msg, filename);
2883 title = R.string.download_no_sdcard_dlg_title;
2884 }
2885
2886 new AlertDialog.Builder(this)
2887 .setTitle(title)
2888 .setIcon(android.R.drawable.ic_dialog_alert)
2889 .setMessage(msg)
2890 .setPositiveButton(R.string.ok, null)
2891 .show();
2892 return;
2893 }
2894
Kristian Monsenfa52d172010-03-25 18:29:21 +00002895 // java.net.URI is a lot stricter than KURL so we have to encode some
2896 // extra characters. Fix for b 2538060 and b 1634719
2897 WebAddress webAddress;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002898 try {
Kristian Monsenfa52d172010-03-25 18:29:21 +00002899 webAddress = new WebAddress(url);
2900 webAddress.mPath = encodePath(webAddress.mPath);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002901 } catch (Exception e) {
Kristian Monsenfa52d172010-03-25 18:29:21 +00002902 // This only happens for very bad urls, we want to chatch the
2903 // exception here
2904 Log.e(LOGTAG, "Exception trying to parse url:" + url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002905 return;
2906 }
2907
2908 // XXX: Have to use the old url since the cookies were stored using the
2909 // old percent-encoded url.
2910 String cookies = CookieManager.getInstance().getCookie(url);
2911
2912 ContentValues values = new ContentValues();
Kristian Monsenfa52d172010-03-25 18:29:21 +00002913 values.put(Downloads.Impl.COLUMN_URI, webAddress.toString());
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08002914 values.put(Downloads.Impl.COLUMN_COOKIE_DATA, cookies);
2915 values.put(Downloads.Impl.COLUMN_USER_AGENT, userAgent);
2916 values.put(Downloads.Impl.COLUMN_NOTIFICATION_PACKAGE,
The Android Open Source Project0c908882009-03-03 19:32:16 -08002917 getPackageName());
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08002918 values.put(Downloads.Impl.COLUMN_NOTIFICATION_CLASS,
Leon Scrogginsa563d092010-04-19 16:53:49 -04002919 OpenDownloadReceiver.class.getCanonicalName());
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08002920 values.put(Downloads.Impl.COLUMN_VISIBILITY,
2921 Downloads.Impl.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
2922 values.put(Downloads.Impl.COLUMN_MIME_TYPE, mimetype);
2923 values.put(Downloads.Impl.COLUMN_FILE_NAME_HINT, filename);
Kristian Monsenfa52d172010-03-25 18:29:21 +00002924 values.put(Downloads.Impl.COLUMN_DESCRIPTION, webAddress.mHost);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002925 if (contentLength > 0) {
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08002926 values.put(Downloads.Impl.COLUMN_TOTAL_BYTES, contentLength);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002927 }
2928 if (mimetype == null) {
2929 // We must have long pressed on a link or image to download it. We
2930 // are not sure of the mimetype in this case, so do a head request
2931 new FetchUrlMimeType(this).execute(values);
2932 } else {
2933 final Uri contentUri =
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08002934 getContentResolver().insert(Downloads.Impl.CONTENT_URI, values);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002935 }
Leon Scroggins9191a7f2010-03-18 14:44:44 -04002936 Toast.makeText(this, R.string.download_pending, Toast.LENGTH_SHORT)
2937 .show();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002938 }
2939
Grace Kloba22ac16e2009-10-07 18:00:23 -07002940 // -------------------------------------------------------------------------
2941
The Android Open Source Project0c908882009-03-03 19:32:16 -08002942 /**
2943 * Resets the lock icon. This method is called when we start a new load and
2944 * know the url to be loaded.
2945 */
2946 private void resetLockIcon(String url) {
2947 // Save the lock-icon state (we revert to it if the load gets cancelled)
Grace Kloba22ac16e2009-10-07 18:00:23 -07002948 mTabControl.getCurrentTab().resetLockIcon(url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002949 updateLockIconImage(LOCK_ICON_UNSECURE);
2950 }
2951
The Android Open Source Project0c908882009-03-03 19:32:16 -08002952 /**
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04002953 * Update the lock icon to correspond to our latest state.
2954 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07002955 private void updateLockIconToLatest() {
2956 updateLockIconImage(mTabControl.getCurrentTab().getLockIconType());
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04002957 }
2958
2959 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08002960 * Updates the lock-icon image in the title-bar.
2961 */
2962 private void updateLockIconImage(int lockIconType) {
2963 Drawable d = null;
2964 if (lockIconType == LOCK_ICON_SECURE) {
2965 d = mSecLockIcon;
2966 } else if (lockIconType == LOCK_ICON_MIXED) {
2967 d = mMixLockIcon;
2968 }
Leon Scroggins68579392009-09-15 15:31:54 -04002969 mTitleBar.setLock(d);
Leon Scrogginsfe87bd32009-10-06 10:10:00 -04002970 mFakeTitleBar.setLock(d);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002971 }
2972
2973 /**
2974 * Displays a page-info dialog.
2975 * @param tab The tab to show info about
2976 * @param fromShowSSLCertificateOnError The flag that indicates whether
2977 * this dialog was opened from the SSL-certificate-on-error dialog or
2978 * not. This is important, since we need to know whether to return to
2979 * the parent dialog or simply dismiss.
2980 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07002981 private void showPageInfo(final Tab tab,
The Android Open Source Project0c908882009-03-03 19:32:16 -08002982 final boolean fromShowSSLCertificateOnError) {
2983 final LayoutInflater factory = LayoutInflater
2984 .from(this);
2985
2986 final View pageInfoView = factory.inflate(R.layout.page_info, null);
2987
2988 final WebView view = tab.getWebView();
2989
2990 String url = null;
2991 String title = null;
2992
2993 if (view == null) {
2994 url = tab.getUrl();
2995 title = tab.getTitle();
2996 } else if (view == mTabControl.getCurrentWebView()) {
2997 // Use the cached title and url if this is the current WebView
2998 url = mUrl;
2999 title = mTitle;
3000 } else {
3001 url = view.getUrl();
3002 title = view.getTitle();
3003 }
3004
3005 if (url == null) {
3006 url = "";
3007 }
3008 if (title == null) {
3009 title = "";
3010 }
3011
3012 ((TextView) pageInfoView.findViewById(R.id.address)).setText(url);
3013 ((TextView) pageInfoView.findViewById(R.id.title)).setText(title);
3014
3015 mPageInfoView = tab;
Leon Scrogginsc7b92f82010-01-11 18:17:31 -05003016 mPageInfoFromShowSSLCertificateOnError = fromShowSSLCertificateOnError;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003017
3018 AlertDialog.Builder alertDialogBuilder =
3019 new AlertDialog.Builder(this)
3020 .setTitle(R.string.page_info).setIcon(android.R.drawable.ic_dialog_info)
3021 .setView(pageInfoView)
3022 .setPositiveButton(
3023 R.string.ok,
3024 new DialogInterface.OnClickListener() {
3025 public void onClick(DialogInterface dialog,
3026 int whichButton) {
3027 mPageInfoDialog = null;
3028 mPageInfoView = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003029
3030 // if we came here from the SSL error dialog
3031 if (fromShowSSLCertificateOnError) {
3032 // go back to the SSL error dialog
3033 showSSLCertificateOnError(
3034 mSSLCertificateOnErrorView,
3035 mSSLCertificateOnErrorHandler,
3036 mSSLCertificateOnErrorError);
3037 }
3038 }
3039 })
3040 .setOnCancelListener(
3041 new DialogInterface.OnCancelListener() {
3042 public void onCancel(DialogInterface dialog) {
3043 mPageInfoDialog = null;
3044 mPageInfoView = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003045
3046 // if we came here from the SSL error dialog
3047 if (fromShowSSLCertificateOnError) {
3048 // go back to the SSL error dialog
3049 showSSLCertificateOnError(
3050 mSSLCertificateOnErrorView,
3051 mSSLCertificateOnErrorHandler,
3052 mSSLCertificateOnErrorError);
3053 }
3054 }
3055 });
3056
3057 // if we have a main top-level page SSL certificate set or a certificate
3058 // error
3059 if (fromShowSSLCertificateOnError ||
3060 (view != null && view.getCertificate() != null)) {
3061 // add a 'View Certificate' button
3062 alertDialogBuilder.setNeutralButton(
3063 R.string.view_certificate,
3064 new DialogInterface.OnClickListener() {
3065 public void onClick(DialogInterface dialog,
3066 int whichButton) {
3067 mPageInfoDialog = null;
3068 mPageInfoView = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003069
3070 // if we came here from the SSL error dialog
3071 if (fromShowSSLCertificateOnError) {
3072 // go back to the SSL error dialog
3073 showSSLCertificateOnError(
3074 mSSLCertificateOnErrorView,
3075 mSSLCertificateOnErrorHandler,
3076 mSSLCertificateOnErrorError);
3077 } else {
3078 // otherwise, display the top-most certificate from
3079 // the chain
3080 if (view.getCertificate() != null) {
3081 showSSLCertificate(tab);
3082 }
3083 }
3084 }
3085 });
3086 }
3087
3088 mPageInfoDialog = alertDialogBuilder.show();
3089 }
3090
3091 /**
3092 * Displays the main top-level page SSL certificate dialog
3093 * (accessible from the Page-Info dialog).
3094 * @param tab The tab to show certificate for.
3095 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003096 private void showSSLCertificate(final Tab tab) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003097 final View certificateView =
3098 inflateCertificateView(tab.getWebView().getCertificate());
3099 if (certificateView == null) {
3100 return;
3101 }
3102
3103 LayoutInflater factory = LayoutInflater.from(this);
3104
3105 final LinearLayout placeholder =
3106 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3107
3108 LinearLayout ll = (LinearLayout) factory.inflate(
3109 R.layout.ssl_success, placeholder);
3110 ((TextView)ll.findViewById(R.id.success))
3111 .setText(R.string.ssl_certificate_is_valid);
3112
3113 mSSLCertificateView = tab;
3114 mSSLCertificateDialog =
3115 new AlertDialog.Builder(this)
3116 .setTitle(R.string.ssl_certificate).setIcon(
3117 R.drawable.ic_dialog_browser_certificate_secure)
3118 .setView(certificateView)
3119 .setPositiveButton(R.string.ok,
3120 new DialogInterface.OnClickListener() {
3121 public void onClick(DialogInterface dialog,
3122 int whichButton) {
3123 mSSLCertificateDialog = null;
3124 mSSLCertificateView = null;
3125
3126 showPageInfo(tab, false);
3127 }
3128 })
3129 .setOnCancelListener(
3130 new DialogInterface.OnCancelListener() {
3131 public void onCancel(DialogInterface dialog) {
3132 mSSLCertificateDialog = null;
3133 mSSLCertificateView = null;
3134
3135 showPageInfo(tab, false);
3136 }
3137 })
3138 .show();
3139 }
3140
3141 /**
3142 * Displays the SSL error certificate dialog.
3143 * @param view The target web-view.
3144 * @param handler The SSL error handler responsible for cancelling the
3145 * connection that resulted in an SSL error or proceeding per user request.
3146 * @param error The SSL error object.
3147 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003148 void showSSLCertificateOnError(
The Android Open Source Project0c908882009-03-03 19:32:16 -08003149 final WebView view, final SslErrorHandler handler, final SslError error) {
3150
3151 final View certificateView =
3152 inflateCertificateView(error.getCertificate());
3153 if (certificateView == null) {
3154 return;
3155 }
3156
3157 LayoutInflater factory = LayoutInflater.from(this);
3158
3159 final LinearLayout placeholder =
3160 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3161
3162 if (error.hasError(SslError.SSL_UNTRUSTED)) {
3163 LinearLayout ll = (LinearLayout)factory
3164 .inflate(R.layout.ssl_warning, placeholder);
3165 ((TextView)ll.findViewById(R.id.warning))
3166 .setText(R.string.ssl_untrusted);
3167 }
3168
3169 if (error.hasError(SslError.SSL_IDMISMATCH)) {
3170 LinearLayout ll = (LinearLayout)factory
3171 .inflate(R.layout.ssl_warning, placeholder);
3172 ((TextView)ll.findViewById(R.id.warning))
3173 .setText(R.string.ssl_mismatch);
3174 }
3175
3176 if (error.hasError(SslError.SSL_EXPIRED)) {
3177 LinearLayout ll = (LinearLayout)factory
3178 .inflate(R.layout.ssl_warning, placeholder);
3179 ((TextView)ll.findViewById(R.id.warning))
3180 .setText(R.string.ssl_expired);
3181 }
3182
3183 if (error.hasError(SslError.SSL_NOTYETVALID)) {
3184 LinearLayout ll = (LinearLayout)factory
3185 .inflate(R.layout.ssl_warning, placeholder);
3186 ((TextView)ll.findViewById(R.id.warning))
3187 .setText(R.string.ssl_not_yet_valid);
3188 }
3189
3190 mSSLCertificateOnErrorHandler = handler;
3191 mSSLCertificateOnErrorView = view;
3192 mSSLCertificateOnErrorError = error;
3193 mSSLCertificateOnErrorDialog =
3194 new AlertDialog.Builder(this)
3195 .setTitle(R.string.ssl_certificate).setIcon(
3196 R.drawable.ic_dialog_browser_certificate_partially_secure)
3197 .setView(certificateView)
3198 .setPositiveButton(R.string.ok,
3199 new DialogInterface.OnClickListener() {
3200 public void onClick(DialogInterface dialog,
3201 int whichButton) {
3202 mSSLCertificateOnErrorDialog = null;
3203 mSSLCertificateOnErrorView = null;
3204 mSSLCertificateOnErrorHandler = null;
3205 mSSLCertificateOnErrorError = null;
3206
Grace Kloba22ac16e2009-10-07 18:00:23 -07003207 view.getWebViewClient().onReceivedSslError(
3208 view, handler, error);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003209 }
3210 })
3211 .setNeutralButton(R.string.page_info_view,
3212 new DialogInterface.OnClickListener() {
3213 public void onClick(DialogInterface dialog,
3214 int whichButton) {
3215 mSSLCertificateOnErrorDialog = null;
3216
3217 // do not clear the dialog state: we will
3218 // need to show the dialog again once the
3219 // user is done exploring the page-info details
3220
3221 showPageInfo(mTabControl.getTabFromView(view),
3222 true);
3223 }
3224 })
3225 .setOnCancelListener(
3226 new DialogInterface.OnCancelListener() {
3227 public void onCancel(DialogInterface dialog) {
3228 mSSLCertificateOnErrorDialog = null;
3229 mSSLCertificateOnErrorView = null;
3230 mSSLCertificateOnErrorHandler = null;
3231 mSSLCertificateOnErrorError = null;
3232
Grace Kloba22ac16e2009-10-07 18:00:23 -07003233 view.getWebViewClient().onReceivedSslError(
3234 view, handler, error);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003235 }
3236 })
3237 .show();
3238 }
3239
3240 /**
3241 * Inflates the SSL certificate view (helper method).
3242 * @param certificate The SSL certificate.
3243 * @return The resultant certificate view with issued-to, issued-by,
3244 * issued-on, expires-on, and possibly other fields set.
3245 * If the input certificate is null, returns null.
3246 */
3247 private View inflateCertificateView(SslCertificate certificate) {
3248 if (certificate == null) {
3249 return null;
3250 }
3251
3252 LayoutInflater factory = LayoutInflater.from(this);
3253
3254 View certificateView = factory.inflate(
3255 R.layout.ssl_certificate, null);
3256
3257 // issued to:
3258 SslCertificate.DName issuedTo = certificate.getIssuedTo();
3259 if (issuedTo != null) {
3260 ((TextView) certificateView.findViewById(R.id.to_common))
3261 .setText(issuedTo.getCName());
3262 ((TextView) certificateView.findViewById(R.id.to_org))
3263 .setText(issuedTo.getOName());
3264 ((TextView) certificateView.findViewById(R.id.to_org_unit))
3265 .setText(issuedTo.getUName());
3266 }
3267
3268 // issued by:
3269 SslCertificate.DName issuedBy = certificate.getIssuedBy();
3270 if (issuedBy != null) {
3271 ((TextView) certificateView.findViewById(R.id.by_common))
3272 .setText(issuedBy.getCName());
3273 ((TextView) certificateView.findViewById(R.id.by_org))
3274 .setText(issuedBy.getOName());
3275 ((TextView) certificateView.findViewById(R.id.by_org_unit))
3276 .setText(issuedBy.getUName());
3277 }
3278
3279 // issued on:
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003280 String issuedOn = formatCertificateDate(
3281 certificate.getValidNotBeforeDate());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003282 ((TextView) certificateView.findViewById(R.id.issued_on))
3283 .setText(issuedOn);
3284
3285 // expires on:
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003286 String expiresOn = formatCertificateDate(
3287 certificate.getValidNotAfterDate());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003288 ((TextView) certificateView.findViewById(R.id.expires_on))
3289 .setText(expiresOn);
3290
3291 return certificateView;
3292 }
3293
3294 /**
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003295 * Formats the certificate date to a properly localized date string.
The Android Open Source Project0c908882009-03-03 19:32:16 -08003296 * @return Properly localized version of the certificate date string and
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003297 * the "" if it fails to localize.
The Android Open Source Project0c908882009-03-03 19:32:16 -08003298 */
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003299 private String formatCertificateDate(Date certificateDate) {
3300 if (certificateDate == null) {
3301 return "";
The Android Open Source Project0c908882009-03-03 19:32:16 -08003302 }
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003303 String formattedDate = DateFormat.getDateFormat(this).format(certificateDate);
3304 if (formattedDate == null) {
3305 return "";
3306 }
3307 return formattedDate;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003308 }
3309
3310 /**
3311 * Displays an http-authentication dialog.
3312 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003313 void showHttpAuthentication(final HttpAuthHandler handler,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003314 final String host, final String realm, final String title,
3315 final String name, final String password, int focusId) {
3316 LayoutInflater factory = LayoutInflater.from(this);
3317 final View v = factory
3318 .inflate(R.layout.http_authentication, null);
3319 if (name != null) {
3320 ((EditText) v.findViewById(R.id.username_edit)).setText(name);
3321 }
3322 if (password != null) {
3323 ((EditText) v.findViewById(R.id.password_edit)).setText(password);
3324 }
3325
3326 String titleText = title;
3327 if (titleText == null) {
3328 titleText = getText(R.string.sign_in_to).toString().replace(
3329 "%s1", host).replace("%s2", realm);
3330 }
3331
3332 mHttpAuthHandler = handler;
3333 AlertDialog dialog = new AlertDialog.Builder(this)
3334 .setTitle(titleText)
3335 .setIcon(android.R.drawable.ic_dialog_alert)
3336 .setView(v)
3337 .setPositiveButton(R.string.action,
3338 new DialogInterface.OnClickListener() {
3339 public void onClick(DialogInterface dialog,
3340 int whichButton) {
3341 String nm = ((EditText) v
3342 .findViewById(R.id.username_edit))
3343 .getText().toString();
3344 String pw = ((EditText) v
3345 .findViewById(R.id.password_edit))
3346 .getText().toString();
3347 BrowserActivity.this.setHttpAuthUsernamePassword
3348 (host, realm, nm, pw);
3349 handler.proceed(nm, pw);
3350 mHttpAuthenticationDialog = null;
3351 mHttpAuthHandler = null;
3352 }})
3353 .setNegativeButton(R.string.cancel,
3354 new DialogInterface.OnClickListener() {
3355 public void onClick(DialogInterface dialog,
3356 int whichButton) {
3357 handler.cancel();
3358 BrowserActivity.this.resetTitleAndRevertLockIcon();
3359 mHttpAuthenticationDialog = null;
3360 mHttpAuthHandler = null;
3361 }})
3362 .setOnCancelListener(new DialogInterface.OnCancelListener() {
3363 public void onCancel(DialogInterface dialog) {
3364 handler.cancel();
3365 BrowserActivity.this.resetTitleAndRevertLockIcon();
3366 mHttpAuthenticationDialog = null;
3367 mHttpAuthHandler = null;
3368 }})
3369 .create();
3370 // Make the IME appear when the dialog is displayed if applicable.
3371 dialog.getWindow().setSoftInputMode(
3372 WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
3373 dialog.show();
3374 if (focusId != 0) {
3375 dialog.findViewById(focusId).requestFocus();
3376 } else {
3377 v.findViewById(R.id.username_edit).requestFocus();
3378 }
3379 mHttpAuthenticationDialog = dialog;
3380 }
3381
3382 public int getProgress() {
3383 WebView w = mTabControl.getCurrentWebView();
3384 if (w != null) {
3385 return w.getProgress();
3386 } else {
3387 return 100;
3388 }
3389 }
3390
3391 /**
3392 * Set HTTP authentication password.
3393 *
3394 * @param host The host for the password
3395 * @param realm The realm for the password
3396 * @param username The username for the password. If it is null, it means
3397 * password can't be saved.
3398 * @param password The password
3399 */
3400 public void setHttpAuthUsernamePassword(String host, String realm,
3401 String username,
3402 String password) {
Steve Block95a53b22010-03-25 17:24:58 +00003403 WebView w = getTopWindow();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003404 if (w != null) {
3405 w.setHttpAuthUsernamePassword(host, realm, username, password);
3406 }
3407 }
3408
3409 /**
3410 * connectivity manager says net has come or gone... inform the user
3411 * @param up true if net has come up, false if net has gone down
3412 */
3413 public void onNetworkToggle(boolean up) {
3414 if (up == mIsNetworkUp) {
3415 return;
3416 } else if (up) {
3417 mIsNetworkUp = true;
3418 if (mAlertDialog != null) {
3419 mAlertDialog.cancel();
3420 mAlertDialog = null;
3421 }
3422 } else {
3423 mIsNetworkUp = false;
Patrick Scotteb6ab2a2009-09-16 10:00:17 -04003424 if (mInLoad) {
3425 createAndShowNetworkDialog();
3426 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003427 }
3428 WebView w = mTabControl.getCurrentWebView();
3429 if (w != null) {
3430 w.setNetworkAvailable(up);
3431 }
3432 }
3433
Grace Kloba22ac16e2009-10-07 18:00:23 -07003434 boolean isNetworkUp() {
3435 return mIsNetworkUp;
3436 }
3437
Patrick Scotteb6ab2a2009-09-16 10:00:17 -04003438 // This method shows the network dialog alerting the user that the net is
3439 // down. It will only show the dialog if mAlertDialog is null.
3440 private void createAndShowNetworkDialog() {
3441 if (mAlertDialog == null) {
3442 mAlertDialog = new AlertDialog.Builder(this)
3443 .setTitle(R.string.loadSuspendedTitle)
3444 .setMessage(R.string.loadSuspended)
3445 .setPositiveButton(R.string.ok, null)
3446 .show();
3447 }
3448 }
3449
The Android Open Source Project0c908882009-03-03 19:32:16 -08003450 @Override
3451 protected void onActivityResult(int requestCode, int resultCode,
3452 Intent intent) {
Grace Klobabb394f32009-11-19 10:26:37 -08003453 if (getTopWindow() == null) return;
3454
The Android Open Source Project0c908882009-03-03 19:32:16 -08003455 switch (requestCode) {
3456 case COMBO_PAGE:
3457 if (resultCode == RESULT_OK && intent != null) {
3458 String data = intent.getAction();
3459 Bundle extras = intent.getExtras();
3460 if (extras != null && extras.getBoolean("new_window", false)) {
Leon Scroggins25d35472009-09-15 11:37:27 -04003461 openTab(data);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003462 } else {
Grace Kloba22ac16e2009-10-07 18:00:23 -07003463 final Tab currentTab =
The Android Open Source Project0c908882009-03-03 19:32:16 -08003464 mTabControl.getCurrentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04003465 dismissSubWindow(currentTab);
3466 if (data != null && data.length() != 0) {
Leon Scroggins92472e82010-02-17 16:32:28 -05003467 loadUrl(getTopWindow(), data);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003468 }
3469 }
3470 }
Leon Scrogginsfde97462010-01-11 13:06:21 -05003471 // Deliberately fall through to PREFERENCES_PAGE, since the
3472 // same extra may be attached to the COMBO_PAGE
3473 case PREFERENCES_PAGE:
3474 if (resultCode == RESULT_OK && intent != null) {
3475 String action = intent.getStringExtra(Intent.EXTRA_TEXT);
3476 if (BrowserSettings.PREF_CLEAR_HISTORY.equals(action)) {
3477 mTabControl.removeParentChildRelationShips();
3478 }
3479 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003480 break;
Leon Scroggins8d5fa432009-10-02 15:55:59 -04003481 // Choose a file from the file picker.
3482 case FILE_SELECTED:
3483 if (null == mUploadMessage) break;
3484 Uri result = intent == null || resultCode != RESULT_OK ? null
3485 : intent.getData();
3486 mUploadMessage.onReceiveValue(result);
3487 mUploadMessage = null;
3488 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003489 default:
3490 break;
3491 }
Leon Scroggins30444232009-09-04 18:36:20 -04003492 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003493 }
3494
3495 /*
3496 * This method is called as a result of the user selecting the options
Leon Scrogginsf08809b2010-01-21 09:27:46 -05003497 * menu to see the download window. It shows the download window on top of
3498 * the current window.
The Android Open Source Project0c908882009-03-03 19:32:16 -08003499 */
Leon Scrogginsf08809b2010-01-21 09:27:46 -05003500 private void viewDownloads(Uri downloadRecord) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003501 Intent intent = new Intent(this,
3502 BrowserDownloadPage.class);
3503 intent.setData(downloadRecord);
Grace Kloba22ac16e2009-10-07 18:00:23 -07003504 startActivityForResult(intent, BrowserActivity.DOWNLOAD_PAGE);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003505
3506 }
3507
Leon Scroggins160a7e72009-08-14 18:28:01 -04003508 /**
3509 * Open the Go page.
3510 * @param startWithHistory If true, open starting on the history tab.
3511 * Otherwise, start with the bookmarks tab.
Leon Scroggins160a7e72009-08-14 18:28:01 -04003512 */
Leon Scroggins30444232009-09-04 18:36:20 -04003513 /* package */ void bookmarksOrHistoryPicker(boolean startWithHistory) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003514 WebView current = mTabControl.getCurrentWebView();
3515 if (current == null) {
3516 return;
3517 }
3518 Intent intent = new Intent(this,
3519 CombinedBookmarkHistoryActivity.class);
3520 String title = current.getTitle();
3521 String url = current.getUrl();
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01003522 Bitmap thumbnail = createScreenshot(current);
3523
The Android Open Source Project0c908882009-03-03 19:32:16 -08003524 // Just in case the user opens bookmarks before a page finishes loading
3525 // so the current history item, and therefore the page, is null.
3526 if (null == url) {
3527 url = mLastEnteredUrl;
3528 // This can happen.
3529 if (null == url) {
3530 url = mSettings.getHomePage();
3531 }
3532 }
3533 // In case the web page has not yet received its associated title.
3534 if (title == null) {
3535 title = url;
3536 }
3537 intent.putExtra("title", title);
3538 intent.putExtra("url", url);
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01003539 intent.putExtra("thumbnail", thumbnail);
Leon Scroggins30444232009-09-04 18:36:20 -04003540 // Disable opening in a new window if we have maxed out the windows
Grace Kloba22ac16e2009-10-07 18:00:23 -07003541 intent.putExtra("disable_new_window", !mTabControl.canCreateNewTab());
Patrick Scott3918d442009-08-04 13:22:29 -04003542 intent.putExtra("touch_icon_url", current.getTouchIconUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003543 if (startWithHistory) {
3544 intent.putExtra(CombinedBookmarkHistoryActivity.STARTING_TAB,
3545 CombinedBookmarkHistoryActivity.HISTORY_TAB);
3546 }
3547 startActivityForResult(intent, COMBO_PAGE);
3548 }
3549
3550 // Called when loading from context menu or LOAD_URL message
Leon Scroggins92472e82010-02-17 16:32:28 -05003551 private void loadUrlFromContext(WebView view, String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003552 // In case the user enters nothing.
3553 if (url != null && url.length() != 0 && view != null) {
3554 url = smartUrlFilter(url);
Grace Kloba22ac16e2009-10-07 18:00:23 -07003555 if (!view.getWebViewClient().shouldOverrideUrlLoading(view, url)) {
Leon Scroggins92472e82010-02-17 16:32:28 -05003556 loadUrl(view, url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003557 }
3558 }
3559 }
3560
Leon Scroggins92472e82010-02-17 16:32:28 -05003561 /**
3562 * Load the URL into the given WebView and update the title bar
3563 * to reflect the new load. Call this instead of WebView.loadUrl
3564 * directly.
3565 * @param view The WebView used to load url.
3566 * @param url The URL to load.
3567 */
3568 private void loadUrl(WebView view, String url) {
3569 updateTitleBarForNewLoad(view, url);
3570 view.loadUrl(url);
3571 }
3572
3573 /**
3574 * Load UrlData into a Tab and update the title bar to reflect the new
3575 * load. Call this instead of UrlData.loadIn directly.
3576 * @param t The Tab used to load.
3577 * @param data The UrlData being loaded.
3578 */
3579 private void loadUrlDataIn(Tab t, UrlData data) {
3580 updateTitleBarForNewLoad(t.getWebView(), data.mUrl);
3581 data.loadIn(t);
3582 }
3583
3584 /**
3585 * If the WebView is the top window, update the title bar to reflect
3586 * loading the new URL. i.e. set its text, clear the favicon (which
3587 * will be set once the page begins loading), and set the progress to
3588 * INITIAL_PROGRESS to show that the page has begun to load. Called
3589 * by loadUrl and loadUrlDataIn.
3590 * @param view The WebView that is starting a load.
3591 * @param url The URL that is being loaded.
3592 */
3593 private void updateTitleBarForNewLoad(WebView view, String url) {
3594 if (view == getTopWindow()) {
3595 setUrlTitle(url, null);
3596 setFavicon(null);
3597 onProgressChanged(view, INITIAL_PROGRESS);
3598 }
3599 }
3600
The Android Open Source Project0c908882009-03-03 19:32:16 -08003601 private String smartUrlFilter(Uri inUri) {
3602 if (inUri != null) {
3603 return smartUrlFilter(inUri.toString());
3604 }
3605 return null;
3606 }
3607
Feng Qianb34f87a2009-03-24 21:27:26 -07003608 protected static final Pattern ACCEPTED_URI_SCHEMA = Pattern.compile(
The Android Open Source Project0c908882009-03-03 19:32:16 -08003609 "(?i)" + // switch on case insensitive matching
3610 "(" + // begin group for schema
3611 "(?:http|https|file):\\/\\/" +
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003612 "|(?:inline|data|about|content|javascript):" +
The Android Open Source Project0c908882009-03-03 19:32:16 -08003613 ")" +
3614 "(.*)" );
3615
3616 /**
3617 * Attempts to determine whether user input is a URL or search
3618 * terms. Anything with a space is passed to search.
3619 *
3620 * Converts to lowercase any mistakenly uppercased schema (i.e.,
3621 * "Http://" converts to "http://"
3622 *
3623 * @return Original or modified URL
3624 *
3625 */
3626 String smartUrlFilter(String url) {
3627
3628 String inUrl = url.trim();
3629 boolean hasSpace = inUrl.indexOf(' ') != -1;
3630
3631 Matcher matcher = ACCEPTED_URI_SCHEMA.matcher(inUrl);
3632 if (matcher.matches()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003633 // force scheme to lowercase
3634 String scheme = matcher.group(1);
3635 String lcScheme = scheme.toLowerCase();
3636 if (!lcScheme.equals(scheme)) {
Mitsuru Oshima123ecfb2009-05-18 19:11:14 -07003637 inUrl = lcScheme + matcher.group(2);
3638 }
3639 if (hasSpace) {
3640 inUrl = inUrl.replace(" ", "%20");
The Android Open Source Project0c908882009-03-03 19:32:16 -08003641 }
3642 return inUrl;
3643 }
3644 if (hasSpace) {
Satish Sampath565505b2009-05-29 15:37:27 +01003645 // FIXME: Is this the correct place to add to searches?
3646 // what if someone else calls this function?
3647 int shortcut = parseUrlShortcut(inUrl);
3648 if (shortcut != SHORTCUT_INVALID) {
3649 Browser.addSearchUrl(mResolver, inUrl);
3650 String query = inUrl.substring(2);
3651 switch (shortcut) {
3652 case SHORTCUT_GOOGLE_SEARCH:
Grace Kloba47fdfdb2009-06-30 11:15:34 -07003653 return URLUtil.composeSearchUrl(query, QuickSearch_G, QUERY_PLACE_HOLDER);
Satish Sampath565505b2009-05-29 15:37:27 +01003654 case SHORTCUT_WIKIPEDIA_SEARCH:
3655 return URLUtil.composeSearchUrl(query, QuickSearch_W, QUERY_PLACE_HOLDER);
3656 case SHORTCUT_DICTIONARY_SEARCH:
3657 return URLUtil.composeSearchUrl(query, QuickSearch_D, QUERY_PLACE_HOLDER);
3658 case SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH:
The Android Open Source Project0c908882009-03-03 19:32:16 -08003659 // FIXME: we need location in this case
Satish Sampath565505b2009-05-29 15:37:27 +01003660 return URLUtil.composeSearchUrl(query, QuickSearch_L, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003661 }
3662 }
3663 } else {
Dan Egnor5ee906c2009-11-18 12:11:49 -08003664 if (Patterns.WEB_URL.matcher(inUrl).matches()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003665 return URLUtil.guessUrl(inUrl);
3666 }
3667 }
3668
3669 Browser.addSearchUrl(mResolver, inUrl);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07003670 return URLUtil.composeSearchUrl(inUrl, QuickSearch_G, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003671 }
3672
Ben Murdochbff2d602009-07-01 20:19:05 +01003673 /* package */ void setShouldShowErrorConsole(boolean flag) {
3674 if (flag == mShouldShowErrorConsole) {
3675 // Nothing to do.
3676 return;
3677 }
3678
3679 mShouldShowErrorConsole = flag;
3680
Grace Kloba22ac16e2009-10-07 18:00:23 -07003681 ErrorConsoleView errorConsole = mTabControl.getCurrentTab()
3682 .getErrorConsole(true);
Ben Murdochbff2d602009-07-01 20:19:05 +01003683
3684 if (flag) {
3685 // Setting the show state of the console will cause it's the layout to be inflated.
3686 if (errorConsole.numberOfErrors() > 0) {
3687 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
3688 } else {
3689 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
3690 }
3691
3692 // Now we can add it to the main view.
3693 mErrorConsoleContainer.addView(errorConsole,
Romain Guy15b8ec62010-01-08 15:06:43 -08003694 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
Ben Murdochbff2d602009-07-01 20:19:05 +01003695 ViewGroup.LayoutParams.WRAP_CONTENT));
3696 } else {
3697 mErrorConsoleContainer.removeView(errorConsole);
3698 }
3699
3700 }
3701
Grace Kloba22ac16e2009-10-07 18:00:23 -07003702 boolean shouldShowErrorConsole() {
3703 return mShouldShowErrorConsole;
3704 }
3705
Andrei Popescu163ab742009-10-20 17:58:23 +01003706 private void setStatusBarVisibility(boolean visible) {
3707 int flag = visible ? 0 : WindowManager.LayoutParams.FLAG_FULLSCREEN;
3708 getWindow().setFlags(flag, WindowManager.LayoutParams.FLAG_FULLSCREEN);
3709 }
3710
Andrei Popescu56199cc2010-01-12 22:39:16 +00003711
3712 private void sendNetworkType(String type, String subtype) {
3713 WebView w = mTabControl.getCurrentWebView();
3714 if (w != null) {
3715 w.setNetworkType(type, subtype);
3716 }
3717 }
3718
Andrei Popescu30995e72010-02-09 16:59:58 +00003719 private void packageChanged(String packageName, boolean wasAdded) {
3720 WebView w = mTabControl.getCurrentWebView();
3721 if (w == null) {
3722 return;
3723 }
3724
3725 if (wasAdded) {
3726 w.addPackageName(packageName);
3727 } else {
3728 w.removePackageName(packageName);
3729 }
3730 }
3731
3732 private void addPackageNames(Set<String> packageNames) {
3733 WebView w = mTabControl.getCurrentWebView();
3734 if (w == null) {
3735 return;
3736 }
3737
3738 w.addPackageNames(packageNames);
3739 }
3740
3741 private void getInstalledPackages() {
3742 AsyncTask<Void, Void, Set<String> > task =
3743 new AsyncTask<Void, Void, Set<String> >() {
3744 protected Set<String> doInBackground(Void... unused) {
3745 Set<String> installedPackages = new HashSet<String>();
3746 PackageManager pm = BrowserActivity.this.getPackageManager();
3747 if (pm != null) {
3748 List<PackageInfo> packages = pm.getInstalledPackages(0);
3749 for (PackageInfo p : packages) {
3750 if (BrowserActivity.this.sGoogleApps.contains(p.packageName)) {
3751 installedPackages.add(p.packageName);
3752 }
3753 }
3754 }
3755
3756 return installedPackages;
3757 }
3758
3759 // Executes on the UI thread
3760 protected void onPostExecute(Set<String> installedPackages) {
3761 addPackageNames(installedPackages);
3762 }
3763 };
3764 task.execute();
3765 }
3766
Grace Klobaeb6eef42009-09-15 17:56:32 -07003767 final static int LOCK_ICON_UNSECURE = 0;
3768 final static int LOCK_ICON_SECURE = 1;
3769 final static int LOCK_ICON_MIXED = 2;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003770
The Android Open Source Project0c908882009-03-03 19:32:16 -08003771 private BrowserSettings mSettings;
3772 private TabControl mTabControl;
3773 private ContentResolver mResolver;
3774 private FrameLayout mContentView;
Andrei Popescuadc008d2009-06-26 14:11:30 +01003775 private View mCustomView;
3776 private FrameLayout mCustomViewContainer;
Andrei Popescuc9b55562009-07-07 10:51:15 +01003777 private WebChromeClient.CustomViewCallback mCustomViewCallback;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003778
3779 // FIXME, temp address onPrepareMenu performance problem. When we move everything out of
3780 // view, we should rewrite this.
3781 private int mCurrentMenuState = 0;
3782 private int mMenuState = R.id.MAIN_MENU;
Andrei Popescuadc008d2009-06-26 14:11:30 +01003783 private int mOldMenuState = EMPTY_MENU;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003784 private static final int EMPTY_MENU = -1;
3785 private Menu mMenu;
3786
3787 private FindDialog mFindDialog;
3788 // Used to prevent chording to result in firing two shortcuts immediately
3789 // one after another. Fixes bug 1211714.
3790 boolean mCanChord;
3791
3792 private boolean mInLoad;
3793 private boolean mIsNetworkUp;
Ben Murdochb7cc8b42009-09-28 10:59:09 +01003794 private boolean mDidStopLoad;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003795
Cary Clark1f10cbf2010-03-22 11:45:23 -04003796 /* package */ boolean mActivityInPause = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003797
3798 private boolean mMenuIsDown;
3799
The Android Open Source Project0c908882009-03-03 19:32:16 -08003800 private static boolean mInTrace;
3801
3802 // Performance probe
3803 private static final int[] SYSTEM_CPU_FORMAT = new int[] {
3804 Process.PROC_SPACE_TERM | Process.PROC_COMBINE,
3805 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 1: user time
3806 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 2: nice time
3807 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 3: sys time
3808 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 4: idle time
3809 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 5: iowait time
3810 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 6: irq time
3811 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG // 7: softirq time
3812 };
3813
3814 private long mStart;
3815 private long mProcessStart;
3816 private long mUserStart;
3817 private long mSystemStart;
3818 private long mIdleStart;
3819 private long mIrqStart;
3820
3821 private long mUiStart;
3822
3823 private Drawable mMixLockIcon;
3824 private Drawable mSecLockIcon;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003825
3826 /* hold a ref so we can auto-cancel if necessary */
3827 private AlertDialog mAlertDialog;
3828
The Android Open Source Project0c908882009-03-03 19:32:16 -08003829 // The up-to-date URL and title (these can be different from those stored
3830 // in WebView, since it takes some time for the information in WebView to
3831 // get updated)
3832 private String mUrl;
3833 private String mTitle;
3834
3835 // As PageInfo has different style for landscape / portrait, we have
3836 // to re-open it when configuration changed
3837 private AlertDialog mPageInfoDialog;
Grace Kloba22ac16e2009-10-07 18:00:23 -07003838 private Tab mPageInfoView;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003839 // If the Page-Info dialog is launched from the SSL-certificate-on-error
3840 // dialog, we should not just dismiss it, but should get back to the
3841 // SSL-certificate-on-error dialog. This flag is used to store this state
Leon Scrogginsc7b92f82010-01-11 18:17:31 -05003842 private boolean mPageInfoFromShowSSLCertificateOnError;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003843
3844 // as SSLCertificateOnError has different style for landscape / portrait,
3845 // we have to re-open it when configuration changed
3846 private AlertDialog mSSLCertificateOnErrorDialog;
3847 private WebView mSSLCertificateOnErrorView;
3848 private SslErrorHandler mSSLCertificateOnErrorHandler;
3849 private SslError mSSLCertificateOnErrorError;
3850
3851 // as SSLCertificate has different style for landscape / portrait, we
3852 // have to re-open it when configuration changed
3853 private AlertDialog mSSLCertificateDialog;
Grace Kloba22ac16e2009-10-07 18:00:23 -07003854 private Tab mSSLCertificateView;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003855
3856 // as HttpAuthentication has different style for landscape / portrait, we
3857 // have to re-open it when configuration changed
3858 private AlertDialog mHttpAuthenticationDialog;
3859 private HttpAuthHandler mHttpAuthHandler;
3860
3861 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_PARAMS =
3862 new FrameLayout.LayoutParams(
Romain Guy15b8ec62010-01-08 15:06:43 -08003863 ViewGroup.LayoutParams.MATCH_PARENT,
3864 ViewGroup.LayoutParams.MATCH_PARENT);
Andrei Popescuadc008d2009-06-26 14:11:30 +01003865 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_GRAVITY_CENTER =
3866 new FrameLayout.LayoutParams(
Romain Guy15b8ec62010-01-08 15:06:43 -08003867 ViewGroup.LayoutParams.MATCH_PARENT,
3868 ViewGroup.LayoutParams.MATCH_PARENT,
Andrei Popescuadc008d2009-06-26 14:11:30 +01003869 Gravity.CENTER);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07003870 // Google search
3871 final static String QuickSearch_G = "http://www.google.com/m?q=%s";
The Android Open Source Project0c908882009-03-03 19:32:16 -08003872 // Wikipedia search
3873 final static String QuickSearch_W = "http://en.wikipedia.org/w/index.php?search=%s&go=Go";
3874 // Dictionary search
3875 final static String QuickSearch_D = "http://dictionary.reference.com/search?q=%s";
3876 // Google Mobile Local search
3877 final static String QuickSearch_L = "http://www.google.com/m/search?site=local&q=%s&near=mountain+view";
3878
3879 final static String QUERY_PLACE_HOLDER = "%s";
3880
3881 // "source" parameter for Google search through search key
3882 final static String GOOGLE_SEARCH_SOURCE_SEARCHKEY = "browser-key";
3883 // "source" parameter for Google search through goto menu
3884 final static String GOOGLE_SEARCH_SOURCE_GOTO = "browser-goto";
3885 // "source" parameter for Google search through simplily type
3886 final static String GOOGLE_SEARCH_SOURCE_TYPE = "browser-type";
3887 // "source" parameter for Google search suggested by the browser
3888 final static String GOOGLE_SEARCH_SOURCE_SUGGEST = "browser-suggest";
3889 // "source" parameter for Google search from unknown source
3890 final static String GOOGLE_SEARCH_SOURCE_UNKNOWN = "unknown";
3891
3892 private final static String LOGTAG = "browser";
3893
The Android Open Source Project0c908882009-03-03 19:32:16 -08003894 private String mLastEnteredUrl;
3895
3896 private PowerManager.WakeLock mWakeLock;
3897 private final static int WAKELOCK_TIMEOUT = 5 * 60 * 1000; // 5 minutes
3898
3899 private Toast mStopToast;
3900
Leon Scroggins68579392009-09-15 15:31:54 -04003901 private TitleBar mTitleBar;
Leon Scroggins81db3662009-06-04 17:45:11 -04003902
Ben Murdochbff2d602009-07-01 20:19:05 +01003903 private LinearLayout mErrorConsoleContainer = null;
3904 private boolean mShouldShowErrorConsole = false;
3905
The Android Open Source Project0c908882009-03-03 19:32:16 -08003906 // As the ids are dynamically created, we can't guarantee that they will
3907 // be in sequence, so this static array maps ids to a window number.
3908 final static private int[] WINDOW_SHORTCUT_ID_ARRAY =
3909 { R.id.window_one_menu_id, R.id.window_two_menu_id, R.id.window_three_menu_id,
3910 R.id.window_four_menu_id, R.id.window_five_menu_id, R.id.window_six_menu_id,
3911 R.id.window_seven_menu_id, R.id.window_eight_menu_id };
3912
3913 // monitor platform changes
3914 private IntentFilter mNetworkStateChangedFilter;
3915 private BroadcastReceiver mNetworkStateIntentReceiver;
3916
Grace Klobab4da0ad2009-05-14 14:45:40 -07003917 private BroadcastReceiver mPackageInstallationReceiver;
3918
Bjorn Bringerta7611812010-03-24 11:12:02 +00003919 private SystemAllowGeolocationOrigins mSystemAllowGeolocationOrigins;
3920
The Android Open Source Project0c908882009-03-03 19:32:16 -08003921 // activity requestCode
Nicolas Roard78a98e42009-05-11 13:34:17 +01003922 final static int COMBO_PAGE = 1;
3923 final static int DOWNLOAD_PAGE = 2;
3924 final static int PREFERENCES_PAGE = 3;
Leon Scroggins8d5fa432009-10-02 15:55:59 -04003925 final static int FILE_SELECTED = 4;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003926
Andrei Popescu540035d2009-09-18 18:59:20 +01003927 // the default <video> poster
3928 private Bitmap mDefaultVideoPoster;
3929 // the video progress view
3930 private View mVideoProgressView;
3931
Andrei Popescu30995e72010-02-09 16:59:58 +00003932 // The Google packages we monitor for the navigator.isApplicationInstalled()
3933 // API. Add as needed.
3934 private static Set<String> sGoogleApps;
3935 static {
3936 sGoogleApps = new HashSet<String>();
3937 sGoogleApps.add("com.google.android.youtube");
3938 }
3939
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003940 /**
3941 * A UrlData class to abstract how the content will be set to WebView.
3942 * This base class uses loadUrl to show the content.
3943 */
Leon Scroggins6eac63e2010-03-15 18:19:14 -04003944 /* package */ static class UrlData {
Grace Kloba068e48b2010-01-26 18:11:27 -08003945 final String mUrl;
3946 final Map<String, String> mHeaders;
Leon Scroggins58d56c62010-01-28 15:12:40 -05003947 final Intent mVoiceIntent;
Grace Kloba60e095c2009-06-16 11:50:55 -07003948
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003949 UrlData(String url) {
3950 this.mUrl = url;
Grace Kloba068e48b2010-01-26 18:11:27 -08003951 this.mHeaders = null;
Leon Scroggins58d56c62010-01-28 15:12:40 -05003952 this.mVoiceIntent = null;
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003953 }
Grace Kloba60e095c2009-06-16 11:50:55 -07003954
Leon Scroggins58d56c62010-01-28 15:12:40 -05003955 UrlData(String url, Map<String, String> headers, Intent intent) {
Grace Kloba068e48b2010-01-26 18:11:27 -08003956 this.mUrl = url;
3957 this.mHeaders = headers;
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -05003958 if (RecognizerResultsIntent.ACTION_VOICE_SEARCH_RESULTS
3959 .equals(intent.getAction())) {
Leon Scroggins58d56c62010-01-28 15:12:40 -05003960 this.mVoiceIntent = intent;
3961 } else {
3962 this.mVoiceIntent = null;
3963 }
Grace Kloba60e095c2009-06-16 11:50:55 -07003964 }
3965
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003966 boolean isEmpty() {
Leon Scroggins58d56c62010-01-28 15:12:40 -05003967 return mVoiceIntent == null && (mUrl == null || mUrl.length() == 0);
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003968 }
3969
Leon Scroggins92472e82010-02-17 16:32:28 -05003970 /**
3971 * Load this UrlData into the given Tab. Use loadUrlDataIn to update
3972 * the title bar as well.
3973 */
Leon Scroggins58d56c62010-01-28 15:12:40 -05003974 public void loadIn(Tab t) {
3975 if (mVoiceIntent != null) {
3976 t.activateVoiceSearchMode(mVoiceIntent);
3977 } else {
3978 t.getWebView().loadUrl(mUrl, mHeaders);
3979 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003980 }
3981 };
3982
Leon Scroggins1f005d32009-08-10 17:36:42 -04003983 /* package */ static final UrlData EMPTY_URL_DATA = new UrlData(null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003984}