blob: 4c8fc5cc3061be743cfccb9061c70156a2c31212 [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);
Leon Scrogginsfe87bd32009-10-06 10:10:00 -0400217 mFakeTitleBar = new TitleBar(this);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800218
219 // Create the tab control and our initial tab
220 mTabControl = new TabControl(this);
221
222 // Open the icon database and retain all the bookmark urls for favicons
223 retainIconsOnStartup();
224
225 // Keep a settings instance handy.
226 mSettings = BrowserSettings.getInstance();
227 mSettings.setTabControl(mTabControl);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800228
229 PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
230 mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Browser");
231
Patrick Scott6adacc92010-03-05 08:24:51 -0500232 // Find out if the network is currently up.
233 ConnectivityManager cm = (ConnectivityManager) getSystemService(
234 Context.CONNECTIVITY_SERVICE);
235 NetworkInfo info = cm.getActiveNetworkInfo();
236 if (info != null) {
237 mIsNetworkUp = info.isAvailable();
238 }
239
Grace Klobaa34f6862009-07-31 16:28:17 -0700240 /* enables registration for changes in network status from
241 http stack */
242 mNetworkStateChangedFilter = new IntentFilter();
243 mNetworkStateChangedFilter.addAction(
244 ConnectivityManager.CONNECTIVITY_ACTION);
245 mNetworkStateIntentReceiver = new BroadcastReceiver() {
246 @Override
247 public void onReceive(Context context, Intent intent) {
248 if (intent.getAction().equals(
249 ConnectivityManager.CONNECTIVITY_ACTION)) {
Andrei Popescue4c98462010-02-19 15:44:13 +0000250
251 NetworkInfo info = intent.getParcelableExtra(
252 ConnectivityManager.EXTRA_NETWORK_INFO);
253 String typeName = info.getTypeName();
254 String subtypeName = info.getSubtypeName();
255 sendNetworkType(typeName.toLowerCase(),
256 (subtypeName != null ? subtypeName.toLowerCase() : ""));
257
258 onNetworkToggle(info.isAvailable());
Grace Klobaa34f6862009-07-31 16:28:17 -0700259 }
260 }
261 };
262
Grace Kloba615c6c92009-08-03 10:22:44 -0700263 IntentFilter filter = new IntentFilter(Intent.ACTION_PACKAGE_ADDED);
264 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
265 filter.addDataScheme("package");
266 mPackageInstallationReceiver = new BroadcastReceiver() {
267 @Override
268 public void onReceive(Context context, Intent intent) {
269 final String action = intent.getAction();
270 final String packageName = intent.getData()
271 .getSchemeSpecificPart();
272 final boolean replacing = intent.getBooleanExtra(
273 Intent.EXTRA_REPLACING, false);
274 if (Intent.ACTION_PACKAGE_REMOVED.equals(action) && replacing) {
275 // if it is replacing, refreshPlugins() when adding
276 return;
277 }
Andrei Popescu30995e72010-02-09 16:59:58 +0000278
279 if (sGoogleApps.contains(packageName)) {
280 BrowserActivity.this.packageChanged(packageName,
281 Intent.ACTION_PACKAGE_ADDED.equals(action));
282 }
283
Grace Kloba615c6c92009-08-03 10:22:44 -0700284 PackageManager pm = BrowserActivity.this.getPackageManager();
285 PackageInfo pkgInfo = null;
286 try {
287 pkgInfo = pm.getPackageInfo(packageName,
288 PackageManager.GET_PERMISSIONS);
289 } catch (PackageManager.NameNotFoundException e) {
290 return;
291 }
292 if (pkgInfo != null) {
293 String permissions[] = pkgInfo.requestedPermissions;
294 if (permissions == null) {
295 return;
296 }
297 boolean permissionOk = false;
298 for (String permit : permissions) {
299 if (PluginManager.PLUGIN_PERMISSION.equals(permit)) {
300 permissionOk = true;
301 break;
302 }
303 }
304 if (permissionOk) {
305 PluginManager.getInstance(BrowserActivity.this)
306 .refreshPlugins(
307 Intent.ACTION_PACKAGE_ADDED
308 .equals(action));
309 }
310 }
311 }
312 };
313 registerReceiver(mPackageInstallationReceiver, filter);
314
The Android Open Source Project0c908882009-03-03 19:32:16 -0800315 if (!mTabControl.restoreState(icicle)) {
316 // clear up the thumbnail directory if we can't restore the state as
317 // none of the files in the directory are referenced any more.
318 new ClearThumbnails().execute(
319 mTabControl.getThumbnailDir().listFiles());
Grace Klobaaab3f092009-07-30 12:29:51 -0700320 // there is no quit on Android. But if we can't restore the state,
321 // we can treat it as a new Browser, remove the old session cookies.
322 CookieManager.getInstance().removeSessionCookie();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800323 final Intent intent = getIntent();
324 final Bundle extra = intent.getExtras();
325 // Create an initial tab.
326 // If the intent is ACTION_VIEW and data is not null, the Browser is
327 // invoked to view the content by another application. In this case,
328 // the tab will be close when exit.
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700329 UrlData urlData = getUrlDataFromIntent(intent);
330
Leon Scroggins58d56c62010-01-28 15:12:40 -0500331 String action = intent.getAction();
Grace Kloba22ac16e2009-10-07 18:00:23 -0700332 final Tab t = mTabControl.createNewTab(
Leon Scroggins58d56c62010-01-28 15:12:40 -0500333 (Intent.ACTION_VIEW.equals(action) &&
334 intent.getData() != null)
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -0500335 || RecognizerResultsIntent.ACTION_VOICE_SEARCH_RESULTS
336 .equals(action),
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700337 intent.getStringExtra(Browser.EXTRA_APPLICATION_ID), urlData.mUrl);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800338 mTabControl.setCurrentTab(t);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800339 attachTabToContentView(t);
340 WebView webView = t.getWebView();
341 if (extra != null) {
342 int scale = extra.getInt(Browser.INITIAL_ZOOM_LEVEL, 0);
343 if (scale > 0 && scale <= 1000) {
344 webView.setInitialScale(scale);
345 }
346 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800347
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700348 if (urlData.isEmpty()) {
Shimeng (Simon) Wang98d5fce2010-03-16 13:23:39 -0700349 loadUrl(webView, mSettings.getHomePage());
The Android Open Source Project0c908882009-03-03 19:32:16 -0800350 } else {
Patrick Scott9d53da02010-02-19 10:19:01 -0500351 loadUrlDataIn(t, urlData);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800352 }
353 } else {
354 // TabControl.restoreState() will create a new tab even if
Leon Scroggins1f005d32009-08-10 17:36:42 -0400355 // restoring the state fails.
The Android Open Source Project0c908882009-03-03 19:32:16 -0800356 attachTabToContentView(mTabControl.getCurrentTab());
357 }
Grace Kloba615c6c92009-08-03 10:22:44 -0700358
Feng Qianb3c02da2009-06-29 15:58:08 -0700359 // Read JavaScript flags if it exists.
360 String jsFlags = mSettings.getJsFlags();
361 if (jsFlags.trim().length() != 0) {
362 mTabControl.getCurrentWebView().setJsFlags(jsFlags);
363 }
Andrei Popescu30995e72010-02-09 16:59:58 +0000364 // Work out which packages are installed on the system.
365 getInstalledPackages();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800366 }
367
Leon Scroggins58d56c62010-01-28 15:12:40 -0500368 /**
369 * Feed the previously stored results strings to the BrowserProvider so that
370 * the SearchDialog will show them instead of the standard searches.
371 * @param result String to show on the editable line of the SearchDialog.
372 */
373 /* package */ void showVoiceSearchResults(String result) {
374 ContentProviderClient client = mResolver.acquireContentProviderClient(
375 Browser.BOOKMARKS_URI);
376 ContentProvider prov = client.getLocalContentProvider();
377 BrowserProvider bp = (BrowserProvider) prov;
378 bp.setQueryResults(mTabControl.getCurrentTab().getVoiceSearchResults());
379 client.release();
380
Leon Scrogginsfbb3f152010-03-09 17:26:56 -0500381 Bundle bundle = createGoogleSearchSourceBundle(
382 GOOGLE_SEARCH_SOURCE_SEARCHKEY);
383 bundle.putBoolean(SearchManager.CONTEXT_IS_VOICE, true);
384 startSearch(result, false, bundle, false);
Leon Scroggins58d56c62010-01-28 15:12:40 -0500385 }
386
The Android Open Source Project0c908882009-03-03 19:32:16 -0800387 @Override
388 protected void onNewIntent(Intent intent) {
Grace Kloba22ac16e2009-10-07 18:00:23 -0700389 Tab current = mTabControl.getCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800390 // When a tab is closed on exit, the current tab index is set to -1.
391 // Reset before proceed as Browser requires the current tab to be set.
392 if (current == null) {
393 // Try to reset the tab in case the index was incorrect.
394 current = mTabControl.getTab(0);
395 if (current == null) {
396 // No tabs at all so just ignore this intent.
397 return;
398 }
399 mTabControl.setCurrentTab(current);
400 attachTabToContentView(current);
401 resetTitleAndIcon(current.getWebView());
402 }
403 final String action = intent.getAction();
404 final int flags = intent.getFlags();
405 if (Intent.ACTION_MAIN.equals(action) ||
406 (flags & Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY) != 0) {
407 // just resume the browser
408 return;
409 }
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -0500410 boolean activateVoiceSearch = RecognizerResultsIntent
411 .ACTION_VOICE_SEARCH_RESULTS.equals(action);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800412 if (Intent.ACTION_VIEW.equals(action)
413 || Intent.ACTION_SEARCH.equals(action)
414 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
Leon Scroggins58d56c62010-01-28 15:12:40 -0500415 || Intent.ACTION_WEB_SEARCH.equals(action)
416 || activateVoiceSearch) {
Leon Scroggins3b18ce32010-02-08 17:35:59 -0500417 if (current.isInVoiceSearchMode()) {
418 String title = current.getVoiceDisplayTitle();
419 if (title != null && title.equals(intent.getStringExtra(
420 SearchManager.QUERY))) {
421 // The user submitted the same search as the last voice
422 // search, so do nothing.
423 return;
424 }
Leon Scroggins1fe13a52010-02-09 15:31:26 -0500425 if (Intent.ACTION_SEARCH.equals(action)
426 && current.voiceSearchSourceIsGoogle()) {
427 Intent logIntent = new Intent(
428 LoggingEvents.ACTION_LOG_EVENT);
429 logIntent.putExtra(LoggingEvents.EXTRA_EVENT,
430 LoggingEvents.VoiceSearch.QUERY_UPDATED);
431 logIntent.putExtra(
432 LoggingEvents.VoiceSearch.EXTRA_QUERY_UPDATED_VALUE,
433 intent.getDataString());
434 sendBroadcast(logIntent);
435 // Note, onPageStarted will revert the voice title bar
436 // When http://b/issue?id=2379215 is fixed, we should update
437 // the title bar here.
438 }
Leon Scroggins3b18ce32010-02-08 17:35:59 -0500439 }
Satish Sampath565505b2009-05-29 15:37:27 +0100440 // If this was a search request (e.g. search query directly typed into the address bar),
441 // pass it on to the default web search provider.
442 if (handleWebSearchIntent(intent)) {
443 return;
444 }
445
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700446 UrlData urlData = getUrlDataFromIntent(intent);
447 if (urlData.isEmpty()) {
448 urlData = new UrlData(mSettings.getHomePage());
The Android Open Source Project0c908882009-03-03 19:32:16 -0800449 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700450
Grace Klobacc634032009-07-28 15:58:19 -0700451 final String appId = intent
452 .getStringExtra(Browser.EXTRA_APPLICATION_ID);
Leon Scroggins58d56c62010-01-28 15:12:40 -0500453 if ((Intent.ACTION_VIEW.equals(action) || activateVoiceSearch)
Grace Klobacc634032009-07-28 15:58:19 -0700454 && !getPackageName().equals(appId)
455 && (flags & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0) {
Grace Kloba22ac16e2009-10-07 18:00:23 -0700456 Tab appTab = mTabControl.getTabFromId(appId);
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700457 if (appTab != null) {
458 Log.i(LOGTAG, "Reusing tab for " + appId);
459 // Dismiss the subwindow if applicable.
460 dismissSubWindow(appTab);
461 // Since we might kill the WebView, remove it from the
462 // content view first.
463 removeTabFromContentView(appTab);
464 // Recreate the main WebView after destroying the old one.
465 // If the WebView has the same original url and is on that
466 // page, it can be reused.
467 boolean needsLoad =
Leon Scroggins6eac63e2010-03-15 18:19:14 -0400468 mTabControl.recreateWebView(appTab, urlData);
Ben Murdochbff2d602009-07-01 20:19:05 +0100469
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700470 if (current != appTab) {
Leon Scroggins1f005d32009-08-10 17:36:42 -0400471 switchToTab(mTabControl.getTabIndex(appTab));
472 if (needsLoad) {
Patrick Scott9d53da02010-02-19 10:19:01 -0500473 loadUrlDataIn(appTab, urlData);
Leon Scroggins1f005d32009-08-10 17:36:42 -0400474 }
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700475 } else {
Leon Scroggins1f005d32009-08-10 17:36:42 -0400476 // If the tab was the current tab, we have to attach
477 // it to the view system again.
478 attachTabToContentView(appTab);
479 if (needsLoad) {
Patrick Scott9d53da02010-02-19 10:19:01 -0500480 loadUrlDataIn(appTab, urlData);
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700481 }
482 }
483 return;
Patrick Scottcd115892009-07-16 09:42:58 -0400484 } else {
485 // No matching application tab, try to find a regular tab
486 // with a matching url.
487 appTab = mTabControl.findUnusedTabWithUrl(urlData.mUrl);
Leon Scroggins25515f82009-08-19 15:31:58 -0400488 if (appTab != null) {
489 if (current != appTab) {
490 switchToTab(mTabControl.getTabIndex(appTab));
491 }
492 // Otherwise, we are already viewing the correct tab.
Patrick Scottcd115892009-07-16 09:42:58 -0400493 } else {
494 // if FLAG_ACTIVITY_BROUGHT_TO_FRONT flag is on, the url
495 // will be opened in a new tab unless we have reached
496 // MAX_TABS. Then the url will be opened in the current
497 // tab. If a new tab is created, it will have "true" for
498 // exit on close.
Leon Scroggins1f005d32009-08-10 17:36:42 -0400499 openTabAndShow(urlData, true, appId);
Patrick Scottcd115892009-07-16 09:42:58 -0400500 }
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700501 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800502 } else {
Grace Kloba638d3f42009-11-23 10:35:04 -0800503 if (!urlData.isEmpty()
504 && urlData.mUrl.startsWith("about:debug")) {
505 if ("about:debug.dom".equals(urlData.mUrl)) {
506 current.getWebView().dumpDomTree(false);
507 } else if ("about:debug.dom.file".equals(urlData.mUrl)) {
508 current.getWebView().dumpDomTree(true);
509 } else if ("about:debug.render".equals(urlData.mUrl)) {
510 current.getWebView().dumpRenderTree(false);
511 } else if ("about:debug.render.file".equals(urlData.mUrl)) {
512 current.getWebView().dumpRenderTree(true);
513 } else if ("about:debug.display".equals(urlData.mUrl)) {
514 current.getWebView().dumpDisplayTree();
Mike Reed9b78e1d2010-01-13 14:40:52 -0800515 } else if (urlData.mUrl.startsWith("about:debug.drag")) {
516 int index = urlData.mUrl.codePointAt(16) - '0';
517 if (index <= 0 || index > 9) {
518 current.getWebView().setDragTracker(null);
519 } else {
520 current.getWebView().setDragTracker(new MeshTracker(index));
521 }
Grace Kloba638d3f42009-11-23 10:35:04 -0800522 } else {
523 mSettings.toggleDebugSettings();
524 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800525 return;
526 }
Leon Scroggins1f005d32009-08-10 17:36:42 -0400527 // Get rid of the subwindow if it exists
528 dismissSubWindow(current);
Patrick Scott9d53da02010-02-19 10:19:01 -0500529 loadUrlDataIn(current, urlData);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800530 }
531 }
532 }
533
Satish Sampath565505b2009-05-29 15:37:27 +0100534 private int parseUrlShortcut(String url) {
535 if (url == null) return SHORTCUT_INVALID;
536
537 // FIXME: quick search, need to be customized by setting
538 if (url.length() > 2 && url.charAt(1) == ' ') {
539 switch (url.charAt(0)) {
540 case 'g': return SHORTCUT_GOOGLE_SEARCH;
541 case 'w': return SHORTCUT_WIKIPEDIA_SEARCH;
542 case 'd': return SHORTCUT_DICTIONARY_SEARCH;
543 case 'l': return SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH;
544 }
545 }
546 return SHORTCUT_INVALID;
547 }
548
549 /**
550 * Launches the default web search activity with the query parameters if the given intent's data
551 * are identified as plain search terms and not URLs/shortcuts.
552 * @return true if the intent was handled and web search activity was launched, false if not.
553 */
554 private boolean handleWebSearchIntent(Intent intent) {
555 if (intent == null) return false;
556
557 String url = null;
558 final String action = intent.getAction();
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -0500559 if (RecognizerResultsIntent.ACTION_VOICE_SEARCH_RESULTS.equals(
560 action)) {
Leon Scroggins58d56c62010-01-28 15:12:40 -0500561 return false;
562 }
Satish Sampath565505b2009-05-29 15:37:27 +0100563 if (Intent.ACTION_VIEW.equals(action)) {
Grace Kloba1e705052009-09-29 13:13:36 -0700564 Uri data = intent.getData();
565 if (data != null) url = data.toString();
Satish Sampath565505b2009-05-29 15:37:27 +0100566 } else if (Intent.ACTION_SEARCH.equals(action)
567 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
568 || Intent.ACTION_WEB_SEARCH.equals(action)) {
569 url = intent.getStringExtra(SearchManager.QUERY);
570 }
Bjorn Bringert04851702009-09-22 10:36:01 +0100571 return handleWebSearchRequest(url, intent.getBundleExtra(SearchManager.APP_DATA),
572 intent.getStringExtra(SearchManager.EXTRA_DATA_KEY));
Satish Sampath565505b2009-05-29 15:37:27 +0100573 }
574
575 /**
576 * Launches the default web search activity with the query parameters if the given url string
577 * was identified as plain search terms and not URL/shortcut.
578 * @return true if the request was handled and web search activity was launched, false if not.
579 */
Bjorn Bringert04851702009-09-22 10:36:01 +0100580 private boolean handleWebSearchRequest(String inUrl, Bundle appData, String extraData) {
Satish Sampath565505b2009-05-29 15:37:27 +0100581 if (inUrl == null) return false;
582
583 // In general, we shouldn't modify URL from Intent.
584 // But currently, we get the user-typed URL from search box as well.
585 String url = fixUrl(inUrl).trim();
586
587 // URLs and site specific search shortcuts are handled by the regular flow of control, so
588 // return early.
Dan Egnor5ee906c2009-11-18 12:11:49 -0800589 if (Patterns.WEB_URL.matcher(url).matches()
Satish Sampathbc5b9f32009-06-04 18:21:40 +0100590 || ACCEPTED_URI_SCHEMA.matcher(url).matches()
Satish Sampath565505b2009-05-29 15:37:27 +0100591 || parseUrlShortcut(url) != SHORTCUT_INVALID) {
592 return false;
593 }
594
595 Browser.updateVisitedHistory(mResolver, url, false);
596 Browser.addSearchUrl(mResolver, url);
597
598 Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);
599 intent.addCategory(Intent.CATEGORY_DEFAULT);
600 intent.putExtra(SearchManager.QUERY, url);
Satish Sampath15e9f2d2009-06-23 22:29:49 +0100601 if (appData != null) {
602 intent.putExtra(SearchManager.APP_DATA, appData);
603 }
Bjorn Bringert04851702009-09-22 10:36:01 +0100604 if (extraData != null) {
605 intent.putExtra(SearchManager.EXTRA_DATA_KEY, extraData);
606 }
Grace Klobacc634032009-07-28 15:58:19 -0700607 intent.putExtra(Browser.EXTRA_APPLICATION_ID, getPackageName());
Satish Sampath565505b2009-05-29 15:37:27 +0100608 startActivity(intent);
609
610 return true;
611 }
612
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700613 private UrlData getUrlDataFromIntent(Intent intent) {
Leon Scroggins58d56c62010-01-28 15:12:40 -0500614 String url = "";
Grace Kloba068e48b2010-01-26 18:11:27 -0800615 Map<String, String> headers = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800616 if (intent != null) {
617 final String action = intent.getAction();
618 if (Intent.ACTION_VIEW.equals(action)) {
619 url = smartUrlFilter(intent.getData());
620 if (url != null && url.startsWith("content:")) {
621 /* Append mimetype so webview knows how to display */
622 String mimeType = intent.resolveType(getContentResolver());
623 if (mimeType != null) {
624 url += "?" + mimeType;
625 }
626 }
Grace Kloba068e48b2010-01-26 18:11:27 -0800627 if (url != null && url.startsWith("http")) {
Grace Kloba00f54c52010-01-27 14:53:51 -0800628 final Bundle pairs = intent
629 .getBundleExtra(Browser.EXTRA_HEADERS);
Grace Kloba2d508ed2010-01-28 11:39:15 -0800630 if (pairs != null && !pairs.isEmpty()) {
Grace Kloba00f54c52010-01-27 14:53:51 -0800631 Iterator<String> iter = pairs.keySet().iterator();
Grace Kloba068e48b2010-01-26 18:11:27 -0800632 headers = new HashMap<String, String>();
Grace Kloba00f54c52010-01-27 14:53:51 -0800633 while (iter.hasNext()) {
634 String key = iter.next();
635 headers.put(key, pairs.getString(key));
Grace Kloba068e48b2010-01-26 18:11:27 -0800636 }
637 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700638 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800639 } else if (Intent.ACTION_SEARCH.equals(action)
640 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
641 || Intent.ACTION_WEB_SEARCH.equals(action)) {
642 url = intent.getStringExtra(SearchManager.QUERY);
643 if (url != null) {
644 mLastEnteredUrl = url;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800645 // In general, we shouldn't modify URL from Intent.
646 // But currently, we get the user-typed URL from search box as well.
647 url = fixUrl(url);
648 url = smartUrlFilter(url);
Leon Scrogginsda3e0302010-03-02 16:01:49 -0500649 Browser.updateVisitedHistory(mResolver, url, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800650 String searchSource = "&source=android-" + GOOGLE_SEARCH_SOURCE_SUGGEST + "&";
651 if (url.contains(searchSource)) {
652 String source = null;
653 final Bundle appData = intent.getBundleExtra(SearchManager.APP_DATA);
654 if (appData != null) {
Bjorn Bringert10d1cca2010-02-10 14:22:12 +0000655 source = appData.getString(Search.SOURCE);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800656 }
657 if (TextUtils.isEmpty(source)) {
658 source = GOOGLE_SEARCH_SOURCE_UNKNOWN;
659 }
660 url = url.replace(searchSource, "&source=android-"+source+"&");
661 }
662 }
663 }
664 }
Leon Scroggins58d56c62010-01-28 15:12:40 -0500665 return new UrlData(url, headers, intent);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800666 }
Leon Scroggins58d56c62010-01-28 15:12:40 -0500667 /* package */ void showVoiceTitleBar(String title) {
668 mTitleBar.setInVoiceMode(true);
669 mFakeTitleBar.setInVoiceMode(true);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800670
Leon Scroggins58d56c62010-01-28 15:12:40 -0500671 mTitleBar.setDisplayTitle(title);
672 mFakeTitleBar.setDisplayTitle(title);
673 }
674 /* package */ void revertVoiceTitleBar() {
675 mTitleBar.setInVoiceMode(false);
676 mFakeTitleBar.setInVoiceMode(false);
677
Leon Scroggins003a5dd2010-03-10 12:13:14 -0500678 mTitleBar.setDisplayTitle(mUrl);
679 mFakeTitleBar.setDisplayTitle(mUrl);
Leon Scroggins58d56c62010-01-28 15:12:40 -0500680 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800681 /* package */ static String fixUrl(String inUrl) {
Cary Clark652ff872009-09-10 13:34:44 -0400682 // FIXME: Converting the url to lower case
683 // duplicates functionality in smartUrlFilter().
684 // However, changing all current callers of fixUrl to
685 // call smartUrlFilter in addition may have unwanted
686 // consequences, and is deferred for now.
687 int colon = inUrl.indexOf(':');
688 boolean allLower = true;
689 for (int index = 0; index < colon; index++) {
690 char ch = inUrl.charAt(index);
691 if (!Character.isLetter(ch)) {
692 break;
693 }
694 allLower &= Character.isLowerCase(ch);
695 if (index == colon - 1 && !allLower) {
696 inUrl = inUrl.substring(0, colon).toLowerCase()
697 + inUrl.substring(colon);
698 }
699 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800700 if (inUrl.startsWith("http://") || inUrl.startsWith("https://"))
701 return inUrl;
702 if (inUrl.startsWith("http:") ||
703 inUrl.startsWith("https:")) {
704 if (inUrl.startsWith("http:/") || inUrl.startsWith("https:/")) {
705 inUrl = inUrl.replaceFirst("/", "//");
706 } else inUrl = inUrl.replaceFirst(":", "://");
707 }
708 return inUrl;
709 }
710
Grace Kloba22ac16e2009-10-07 18:00:23 -0700711 @Override
712 protected void onResume() {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800713 super.onResume();
Dave Bort31a6d1c2009-04-13 15:56:49 -0700714 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800715 Log.v(LOGTAG, "BrowserActivity.onResume: this=" + this);
716 }
717
718 if (!mActivityInPause) {
719 Log.e(LOGTAG, "BrowserActivity is already resumed.");
720 return;
721 }
722
Mike Reed7bfa63b2009-05-28 11:08:32 -0400723 mTabControl.resumeCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800724 mActivityInPause = false;
Mike Reed7bfa63b2009-05-28 11:08:32 -0400725 resumeWebViewTimers();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800726
727 if (mWakeLock.isHeld()) {
728 mHandler.removeMessages(RELEASE_WAKELOCK);
729 mWakeLock.release();
730 }
731
The Android Open Source Project0c908882009-03-03 19:32:16 -0800732 registerReceiver(mNetworkStateIntentReceiver,
733 mNetworkStateChangedFilter);
734 WebView.enablePlatformNotifications();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800735 }
736
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400737 /**
738 * Since the actual title bar is embedded in the WebView, and removing it
Leon Scrogginsfe87bd32009-10-06 10:10:00 -0400739 * would change its appearance, use a different TitleBar to show overlayed
740 * at the top of the screen, when the menu is open or the page is loading.
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400741 */
742 private TitleBar mFakeTitleBar;
743
744 /**
Leon Scrogginsd8fd2fc2009-09-16 11:12:09 -0400745 * Holder for the fake title bar. It will have a foreground shadow, as well
746 * as a white background, so the fake title bar looks like the real one.
747 */
748 private ViewGroup mFakeTitleBarHolder;
749
750 /**
751 * Layout parameters for the fake title bar within mFakeTitleBarHolder
752 */
753 private FrameLayout.LayoutParams mFakeTitleBarParams
754 = new FrameLayout.LayoutParams(
Romain Guy15b8ec62010-01-08 15:06:43 -0800755 ViewGroup.LayoutParams.MATCH_PARENT,
Leon Scrogginsd8fd2fc2009-09-16 11:12:09 -0400756 ViewGroup.LayoutParams.WRAP_CONTENT);
757 /**
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400758 * Keeps track of whether the options menu is open. This is important in
759 * determining whether to show or hide the title bar overlay.
760 */
761 private boolean mOptionsMenuOpen;
762
763 /**
764 * Only meaningful when mOptionsMenuOpen is true. This variable keeps track
765 * of whether the configuration has changed. The first onMenuOpened call
766 * after a configuration change is simply a reopening of the same menu
767 * (i.e. mIconView did not change).
768 */
769 private boolean mConfigChanged;
770
771 /**
772 * Whether or not the options menu is in its smaller, icon menu form. When
773 * true, we want the title bar overlay to be up. When false, we do not.
774 * Only meaningful if mOptionsMenuOpen is true.
775 */
776 private boolean mIconView;
777
Leon Scrogginsa81a7642009-08-31 17:05:41 -0400778 @Override
779 public boolean onMenuOpened(int featureId, Menu menu) {
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400780 if (Window.FEATURE_OPTIONS_PANEL == featureId) {
781 if (mOptionsMenuOpen) {
782 if (mConfigChanged) {
783 // We do not need to make any changes to the state of the
784 // title bar, since the only thing that happened was a
785 // change in orientation
786 mConfigChanged = false;
787 } else {
788 if (mIconView) {
789 // Switching the menu to expanded view, so hide the
790 // title bar.
791 hideFakeTitleBar();
792 mIconView = false;
793 } else {
794 // Switching the menu back to icon view, so show the
795 // title bar once again.
796 showFakeTitleBar();
797 mIconView = true;
798 }
799 }
800 } else {
801 // The options menu is closed, so open it, and show the title
802 showFakeTitleBar();
803 mOptionsMenuOpen = true;
804 mConfigChanged = false;
805 mIconView = true;
806 }
807 }
Leon Scrogginsa81a7642009-08-31 17:05:41 -0400808 return true;
809 }
810
Leon Scrogginsb94bf272009-09-25 15:22:08 -0400811 /**
812 * Special class used exclusively for the shadow drawn underneath the fake
813 * title bar. The shadow does not need to be drawn if the WebView
814 * underneath is scrolled to the top, because it will draw directly on top
815 * of the embedded shadow.
816 */
817 private static class Shadow extends View {
818 private WebView mWebView;
819
820 public Shadow(Context context, AttributeSet attrs) {
821 super(context, attrs);
822 }
823
824 public void setWebView(WebView view) {
825 mWebView = view;
826 }
827
828 @Override
829 public void draw(Canvas canvas) {
830 // In general onDraw is the method to override, but we care about
831 // whether or not the background gets drawn, which happens in draw()
832 if (mWebView == null || mWebView.getScrollY() > getHeight()) {
833 super.draw(canvas);
834 }
835 // Need to invalidate so that if the scroll position changes, we
836 // still draw as appropriate.
837 invalidate();
838 }
839 }
840
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400841 private void showFakeTitleBar() {
Patrick Scottf8de8ec2009-09-21 16:37:29 -0400842 final View decor = getWindow().peekDecorView();
Leon Scrogginsfe87bd32009-10-06 10:10:00 -0400843 if (mFakeTitleBar.getParent() == null && mActiveTabsPage == null
Patrick Scottf8de8ec2009-09-21 16:37:29 -0400844 && !mActivityInPause && decor != null
845 && decor.getWindowToken() != null) {
Cary Clarka0464552009-09-29 13:00:45 -0400846 Rect visRect = new Rect();
847 if (!mBrowserFrameLayout.getGlobalVisibleRect(visRect)) {
848 if (LOGD_ENABLED) {
849 Log.d(LOGTAG, "showFakeTitleBar visRect failed");
850 }
851 return;
852 }
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400853
854 WindowManager manager
855 = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
856
857 // Add the title bar to the window manager so it can receive touches
858 // while the menu is up
859 WindowManager.LayoutParams params
860 = new WindowManager.LayoutParams(
Romain Guy15b8ec62010-01-08 15:06:43 -0800861 ViewGroup.LayoutParams.MATCH_PARENT,
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400862 ViewGroup.LayoutParams.WRAP_CONTENT,
863 WindowManager.LayoutParams.TYPE_APPLICATION_SUB_PANEL,
864 WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
Leon Scroggins68549862009-09-21 16:02:01 -0400865 PixelFormat.TRANSLUCENT);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400866 params.gravity = Gravity.TOP;
Leon Scrogginsa27ff192009-09-14 12:58:04 -0400867 WebView mainView = mTabControl.getCurrentWebView();
Leon Scroggins68549862009-09-21 16:02:01 -0400868 boolean atTop = mainView != null && mainView.getScrollY() == 0;
Leon Scroggins83932c72009-09-30 11:55:54 -0400869 params.windowAnimations = atTop ? 0 : R.style.TitleBar;
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400870 // XXX : Without providing an offset, the fake title bar will be
871 // placed underneath the status bar. Use the global visible rect
872 // of mBrowserFrameLayout to determine the bottom of the status bar
Cary Clarka0464552009-09-29 13:00:45 -0400873 params.y = visRect.top;
Leon Scroggins68549862009-09-21 16:02:01 -0400874 // Add a holder for the title bar. It also holds a shadow to show
875 // below the title bar.
Leon Scrogginsd8fd2fc2009-09-16 11:12:09 -0400876 if (mFakeTitleBarHolder == null) {
877 mFakeTitleBarHolder = (ViewGroup) LayoutInflater.from(this)
878 .inflate(R.layout.title_bar_bg, null);
879 }
Leon Scrogginsb94bf272009-09-25 15:22:08 -0400880 Shadow shadow = (Shadow) mFakeTitleBarHolder.findViewById(
881 R.id.shadow);
882 shadow.setWebView(mainView);
Leon Scroggins68549862009-09-21 16:02:01 -0400883 mFakeTitleBarHolder.addView(mFakeTitleBar, 0, mFakeTitleBarParams);
Leon Scrogginsd8fd2fc2009-09-16 11:12:09 -0400884 manager.addView(mFakeTitleBarHolder, params);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400885 }
886 }
887
888 @Override
889 public void onOptionsMenuClosed(Menu menu) {
890 mOptionsMenuOpen = false;
Leon Scrogginsa27ff192009-09-14 12:58:04 -0400891 if (!mInLoad) {
892 hideFakeTitleBar();
893 } else if (!mIconView) {
894 // The page is currently loading, and we are in expanded mode, so
895 // we were not showing the menu. Show it once again. It will be
896 // removed when the page finishes.
897 showFakeTitleBar();
898 }
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400899 }
Grace Kloba22ac16e2009-10-07 18:00:23 -0700900
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400901 private void hideFakeTitleBar() {
Leon Scrogginsfe87bd32009-10-06 10:10:00 -0400902 if (mFakeTitleBar.getParent() == null) return;
Leon Scroggins20329572009-09-23 17:42:41 -0400903 WindowManager.LayoutParams params = (WindowManager.LayoutParams)
904 mFakeTitleBarHolder.getLayoutParams();
905 WebView mainView = mTabControl.getCurrentWebView();
906 // Although we decided whether or not to animate based on the current
907 // scroll position, the scroll position may have changed since the
908 // fake title bar was displayed. Make sure it has the appropriate
909 // animation/lack thereof before removing.
910 params.windowAnimations = mainView != null && mainView.getScrollY() == 0
Leon Scroggins83932c72009-09-30 11:55:54 -0400911 ? 0 : R.style.TitleBar;
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400912 WindowManager manager
913 = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
Leon Scroggins20329572009-09-23 17:42:41 -0400914 manager.updateViewLayout(mFakeTitleBarHolder, params);
Leon Scrogginsd8fd2fc2009-09-16 11:12:09 -0400915 mFakeTitleBarHolder.removeView(mFakeTitleBar);
916 manager.removeView(mFakeTitleBarHolder);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400917 }
918
The Android Open Source Project0c908882009-03-03 19:32:16 -0800919 /**
Leon Scrogginsc6fa1102009-09-21 10:40:01 -0400920 * Special method for the fake title bar to call when displaying its context
921 * menu, since it is in its own Window, and its parent does not show a
922 * context menu.
923 */
924 /* package */ void showTitleBarContextMenu() {
Cary Clark65f4a3c2009-09-28 17:05:06 -0400925 if (null == mTitleBar.getParent()) {
926 return;
927 }
Leon Scrogginsc6fa1102009-09-21 10:40:01 -0400928 openContextMenu(mTitleBar);
929 }
930
Leon Scrogginsb2b19f52009-10-09 16:10:00 -0400931 @Override
932 public void onContextMenuClosed(Menu menu) {
933 super.onContextMenuClosed(menu);
934 if (mInLoad) {
935 showFakeTitleBar();
936 }
937 }
938
Leon Scrogginsc6fa1102009-09-21 10:40:01 -0400939 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -0800940 * onSaveInstanceState(Bundle map)
941 * onSaveInstanceState is called right before onStop(). The map contains
942 * the saved state.
943 */
Grace Kloba22ac16e2009-10-07 18:00:23 -0700944 @Override
945 protected void onSaveInstanceState(Bundle outState) {
Dave Bort31a6d1c2009-04-13 15:56:49 -0700946 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800947 Log.v(LOGTAG, "BrowserActivity.onSaveInstanceState: this=" + this);
948 }
949 // the default implementation requires each view to have an id. As the
950 // browser handles the state itself and it doesn't use id for the views,
951 // don't call the default implementation. Otherwise it will trigger the
952 // warning like this, "couldn't save which view has focus because the
953 // focused view XXX has no id".
954
955 // Save all the tabs
956 mTabControl.saveState(outState);
957 }
958
Grace Kloba22ac16e2009-10-07 18:00:23 -0700959 @Override
960 protected void onPause() {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800961 super.onPause();
962
963 if (mActivityInPause) {
964 Log.e(LOGTAG, "BrowserActivity is already paused.");
965 return;
966 }
967
Mike Reed7bfa63b2009-05-28 11:08:32 -0400968 mTabControl.pauseCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800969 mActivityInPause = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -0400970 if (mTabControl.getCurrentIndex() >= 0 && !pauseWebViewTimers()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800971 mWakeLock.acquire();
972 mHandler.sendMessageDelayed(mHandler
973 .obtainMessage(RELEASE_WAKELOCK), WAKELOCK_TIMEOUT);
974 }
975
Leon Scrogginsa2ab6a72009-09-11 11:49:52 -0400976 // FIXME: This removes the active tabs page and resets the menu to
977 // MAIN_MENU. A better solution might be to do this work in onNewIntent
978 // but then we would need to save it in onSaveInstanceState and restore
979 // it in onCreate/onRestoreInstanceState
980 if (mActiveTabsPage != null) {
981 removeActiveTabPage(true);
982 }
983
The Android Open Source Project0c908882009-03-03 19:32:16 -0800984 cancelStopToast();
985
986 // unregister network state listener
987 unregisterReceiver(mNetworkStateIntentReceiver);
988 WebView.disablePlatformNotifications();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800989 }
990
Grace Kloba22ac16e2009-10-07 18:00:23 -0700991 @Override
992 protected void onDestroy() {
Dave Bort31a6d1c2009-04-13 15:56:49 -0700993 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800994 Log.v(LOGTAG, "BrowserActivity.onDestroy: this=" + this);
995 }
996 super.onDestroy();
Grace Kloba0923d692009-09-23 21:37:25 -0700997
Leon Scroggins8d5fa432009-10-02 15:55:59 -0400998 if (mUploadMessage != null) {
999 mUploadMessage.onReceiveValue(null);
1000 mUploadMessage = null;
1001 }
1002
Grace Kloba0923d692009-09-23 21:37:25 -07001003 if (mTabControl == null) return;
1004
Grace Kloba1fc98a32009-10-21 13:23:08 -07001005 // Remove the fake title bar if it is there
1006 hideFakeTitleBar();
1007
The Android Open Source Project0c908882009-03-03 19:32:16 -08001008 // Remove the current tab and sub window
Grace Kloba22ac16e2009-10-07 18:00:23 -07001009 Tab t = mTabControl.getCurrentTab();
Patrick Scottfb5e77f2009-04-08 19:17:37 -07001010 if (t != null) {
1011 dismissSubWindow(t);
1012 removeTabFromContentView(t);
1013 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001014 // Destroy all the tabs
1015 mTabControl.destroy();
1016 WebIconDatabase.getInstance().close();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001017
Grace Klobab4da0ad2009-05-14 14:45:40 -07001018 unregisterReceiver(mPackageInstallationReceiver);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001019 }
1020
1021 @Override
1022 public void onConfigurationChanged(Configuration newConfig) {
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04001023 mConfigChanged = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001024 super.onConfigurationChanged(newConfig);
1025
1026 if (mPageInfoDialog != null) {
1027 mPageInfoDialog.dismiss();
1028 showPageInfo(
1029 mPageInfoView,
Leon Scrogginsc7b92f82010-01-11 18:17:31 -05001030 mPageInfoFromShowSSLCertificateOnError);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001031 }
1032 if (mSSLCertificateDialog != null) {
1033 mSSLCertificateDialog.dismiss();
1034 showSSLCertificate(
1035 mSSLCertificateView);
1036 }
1037 if (mSSLCertificateOnErrorDialog != null) {
1038 mSSLCertificateOnErrorDialog.dismiss();
1039 showSSLCertificateOnError(
1040 mSSLCertificateOnErrorView,
1041 mSSLCertificateOnErrorHandler,
1042 mSSLCertificateOnErrorError);
1043 }
1044 if (mHttpAuthenticationDialog != null) {
1045 String title = ((TextView) mHttpAuthenticationDialog
1046 .findViewById(com.android.internal.R.id.alertTitle)).getText()
1047 .toString();
1048 String name = ((TextView) mHttpAuthenticationDialog
1049 .findViewById(R.id.username_edit)).getText().toString();
1050 String password = ((TextView) mHttpAuthenticationDialog
1051 .findViewById(R.id.password_edit)).getText().toString();
1052 int focusId = mHttpAuthenticationDialog.getCurrentFocus()
1053 .getId();
1054 mHttpAuthenticationDialog.dismiss();
1055 showHttpAuthentication(mHttpAuthHandler, null, null, title,
1056 name, password, focusId);
1057 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001058 }
1059
Grace Kloba22ac16e2009-10-07 18:00:23 -07001060 @Override
1061 public void onLowMemory() {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001062 super.onLowMemory();
1063 mTabControl.freeMemory();
1064 }
1065
Mike Reed7bfa63b2009-05-28 11:08:32 -04001066 private boolean resumeWebViewTimers() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001067 Tab tab = mTabControl.getCurrentTab();
1068 boolean inLoad = tab.inLoad();
1069 if ((!mActivityInPause && !inLoad) || (mActivityInPause && inLoad)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001070 CookieSyncManager.getInstance().startSync();
Grace Kloba22ac16e2009-10-07 18:00:23 -07001071 WebView w = tab.getWebView();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001072 if (w != null) {
1073 w.resumeTimers();
1074 }
1075 return true;
1076 } else {
1077 return false;
1078 }
1079 }
1080
Mike Reed7bfa63b2009-05-28 11:08:32 -04001081 private boolean pauseWebViewTimers() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001082 Tab tab = mTabControl.getCurrentTab();
1083 boolean inLoad = tab.inLoad();
1084 if (mActivityInPause && !inLoad) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001085 CookieSyncManager.getInstance().stopSync();
1086 WebView w = mTabControl.getCurrentWebView();
1087 if (w != null) {
1088 w.pauseTimers();
1089 }
1090 return true;
1091 } else {
1092 return false;
1093 }
1094 }
1095
The Android Open Source Project0c908882009-03-03 19:32:16 -08001096 // Open the icon database and retain all the icons for visited sites.
1097 private void retainIconsOnStartup() {
1098 final WebIconDatabase db = WebIconDatabase.getInstance();
1099 db.open(getDir("icons", 0).getPath());
Leon Scroggins2c0f6112010-03-12 18:09:39 -05001100 Cursor c = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001101 try {
Leon Scroggins2c0f6112010-03-12 18:09:39 -05001102 c = Browser.getAllBookmarks(mResolver);
1103 if (c.moveToFirst()) {
1104 int urlIndex = c.getColumnIndex(Browser.BookmarkColumns.URL);
1105 do {
1106 String url = c.getString(urlIndex);
1107 db.retainIconForPageUrl(url);
1108 } while (c.moveToNext());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001109 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001110 } catch (IllegalStateException e) {
1111 Log.e(LOGTAG, "retainIconsOnStartup", e);
Leon Scroggins2c0f6112010-03-12 18:09:39 -05001112 } finally {
1113 if (c!= null) c.close();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001114 }
1115 }
1116
1117 // Helper method for getting the top window.
1118 WebView getTopWindow() {
1119 return mTabControl.getCurrentTopWebView();
1120 }
1121
Grace Kloba22ac16e2009-10-07 18:00:23 -07001122 TabControl getTabControl() {
1123 return mTabControl;
1124 }
1125
The Android Open Source Project0c908882009-03-03 19:32:16 -08001126 @Override
1127 public boolean onCreateOptionsMenu(Menu menu) {
1128 super.onCreateOptionsMenu(menu);
1129
1130 MenuInflater inflater = getMenuInflater();
1131 inflater.inflate(R.menu.browser, menu);
1132 mMenu = menu;
1133 updateInLoadMenuItems();
1134 return true;
1135 }
1136
1137 /**
1138 * As the menu can be open when loading state changes
1139 * we must manually update the state of the stop/reload menu
1140 * item
1141 */
1142 private void updateInLoadMenuItems() {
1143 if (mMenu == null) {
1144 return;
1145 }
1146 MenuItem src = mInLoad ?
1147 mMenu.findItem(R.id.stop_menu_id):
1148 mMenu.findItem(R.id.reload_menu_id);
1149 MenuItem dest = mMenu.findItem(R.id.stop_reload_menu_id);
1150 dest.setIcon(src.getIcon());
1151 dest.setTitle(src.getTitle());
1152 }
1153
1154 @Override
1155 public boolean onContextItemSelected(MenuItem item) {
1156 // chording is not an issue with context menus, but we use the same
1157 // options selector, so set mCanChord to true so we can access them.
1158 mCanChord = true;
1159 int id = item.getItemId();
Leon Scroggins96afcb12009-12-10 12:35:56 -05001160 boolean result = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001161 switch (id) {
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001162 // For the context menu from the title bar
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001163 case R.id.title_bar_copy_page_url:
Leon Scroggins96afcb12009-12-10 12:35:56 -05001164 Tab currentTab = mTabControl.getCurrentTab();
1165 if (null == currentTab) {
1166 result = false;
1167 break;
1168 }
1169 WebView mainView = currentTab.getWebView();
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001170 if (null == mainView) {
Leon Scroggins96afcb12009-12-10 12:35:56 -05001171 result = false;
1172 break;
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001173 }
Leon Scroggins96afcb12009-12-10 12:35:56 -05001174 copy(mainView.getUrl());
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001175 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001176 // -- Browser context menu
1177 case R.id.open_context_menu_id:
1178 case R.id.open_newtab_context_menu_id:
1179 case R.id.bookmark_context_menu_id:
1180 case R.id.save_link_context_menu_id:
1181 case R.id.share_link_context_menu_id:
1182 case R.id.copy_link_context_menu_id:
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001183 final WebView webView = getTopWindow();
1184 if (null == webView) {
Leon Scroggins96afcb12009-12-10 12:35:56 -05001185 result = false;
1186 break;
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001187 }
1188 final HashMap hrefMap = new HashMap();
1189 hrefMap.put("webview", webView);
1190 final Message msg = mHandler.obtainMessage(
1191 FOCUS_NODE_HREF, id, 0, hrefMap);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001192 webView.requestFocusNodeHref(msg);
1193 break;
1194
1195 default:
1196 // For other context menus
Leon Scroggins96afcb12009-12-10 12:35:56 -05001197 result = onOptionsItemSelected(item);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001198 }
1199 mCanChord = false;
Leon Scroggins96afcb12009-12-10 12:35:56 -05001200 return result;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001201 }
1202
1203 private Bundle createGoogleSearchSourceBundle(String source) {
1204 Bundle bundle = new Bundle();
Bjorn Bringert10d1cca2010-02-10 14:22:12 +00001205 bundle.putString(Search.SOURCE, source);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001206 return bundle;
1207 }
1208
Leon Scroggins8ad29922010-02-16 12:33:55 -05001209 /* package */ void editUrl() {
Leon Scroggins68579392009-09-15 15:31:54 -04001210 if (mOptionsMenuOpen) closeOptionsMenu();
Leon Scroggins5bbe9802009-07-31 13:10:55 -04001211 String url = (getTopWindow() == null) ? null : getTopWindow().getUrl();
Grace Kloba83f47342009-07-20 10:44:31 -07001212 startSearch(mSettings.getHomePage().equals(url) ? null : url, true,
Leon Scroggins8ad29922010-02-16 12:33:55 -05001213 null, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001214 }
1215
Leon Scroggins8ad29922010-02-16 12:33:55 -05001216 /**
1217 * Overriding this to insert a local information bundle
1218 */
The Android Open Source Project0c908882009-03-03 19:32:16 -08001219 @Override
1220 public void startSearch(String initialQuery, boolean selectInitialQuery,
1221 Bundle appSearchData, boolean globalSearch) {
1222 if (appSearchData == null) {
1223 appSearchData = createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_TYPE);
1224 }
1225 super.startSearch(initialQuery, selectInitialQuery, appSearchData, globalSearch);
1226 }
1227
Leon Scroggins1f005d32009-08-10 17:36:42 -04001228 /**
1229 * Switch tabs. Called by the TitleBarSet when sliding the title bar
1230 * results in changing tabs.
Leon Scroggins160a7e72009-08-14 18:28:01 -04001231 * @param index Index of the tab to change to, as defined by
1232 * mTabControl.getTabIndex(Tab t).
1233 * @return boolean True if we successfully switched to a different tab. If
1234 * the indexth tab is null, or if that tab is the same as
1235 * the current one, return false.
Leon Scroggins1f005d32009-08-10 17:36:42 -04001236 */
Leon Scroggins160a7e72009-08-14 18:28:01 -04001237 /* package */ boolean switchToTab(int index) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001238 Tab tab = mTabControl.getTab(index);
1239 Tab currentTab = mTabControl.getCurrentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04001240 if (tab == null || tab == currentTab) {
Leon Scroggins160a7e72009-08-14 18:28:01 -04001241 return false;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001242 }
1243 if (currentTab != null) {
1244 // currentTab may be null if it was just removed. In that case,
1245 // we do not need to remove it
1246 removeTabFromContentView(currentTab);
1247 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001248 mTabControl.setCurrentTab(tab);
1249 attachTabToContentView(tab);
Grace Klobaeb6eef42009-09-15 17:56:32 -07001250 resetTitleIconAndProgress();
1251 updateLockIconToLatest();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001252 return true;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001253 }
1254
Grace Kloba22ac16e2009-10-07 18:00:23 -07001255 /* package */ Tab openTabToHomePage() {
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001256 return openTabAndShow(mSettings.getHomePage(), false, null);
1257 }
1258
Leon Scroggins1f005d32009-08-10 17:36:42 -04001259 /* package */ void closeCurrentWindow() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001260 final Tab current = mTabControl.getCurrentTab();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001261 if (mTabControl.getTabCount() == 1) {
Leon Scroggins30444232009-09-04 18:36:20 -04001262 // This is the last tab. Open a new one, with the home
1263 // page and close the current one.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001264 openTabToHomePage();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001265 closeTab(current);
Leon Scroggins160a7e72009-08-14 18:28:01 -04001266 return;
1267 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07001268 final Tab parent = current.getParentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04001269 int indexToShow = -1;
1270 if (parent != null) {
1271 indexToShow = mTabControl.getTabIndex(parent);
1272 } else {
Leon Scroggins160a7e72009-08-14 18:28:01 -04001273 final int currentIndex = mTabControl.getCurrentIndex();
1274 // Try to move to the tab to the right
1275 indexToShow = currentIndex + 1;
1276 if (indexToShow > mTabControl.getTabCount() - 1) {
1277 // Try to move to the tab to the left
1278 indexToShow = currentIndex - 1;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001279 }
1280 }
Leon Scroggins160a7e72009-08-14 18:28:01 -04001281 if (switchToTab(indexToShow)) {
1282 // Close window
1283 closeTab(current);
1284 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001285 }
1286
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001287 private ActiveTabsPage mActiveTabsPage;
1288
1289 /**
1290 * Remove the active tabs page.
1291 * @param needToAttach If true, the active tabs page did not attach a tab
1292 * to the content view, so we need to do that here.
1293 */
1294 /* package */ void removeActiveTabPage(boolean needToAttach) {
1295 mContentView.removeView(mActiveTabsPage);
1296 mActiveTabsPage = null;
1297 mMenuState = R.id.MAIN_MENU;
1298 if (needToAttach) {
1299 attachTabToContentView(mTabControl.getCurrentTab());
1300 }
1301 getTopWindow().requestFocus();
1302 }
1303
The Android Open Source Project0c908882009-03-03 19:32:16 -08001304 @Override
1305 public boolean onOptionsItemSelected(MenuItem item) {
1306 if (!mCanChord) {
1307 // The user has already fired a shortcut with this hold down of the
1308 // menu key.
1309 return false;
1310 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001311 if (null == getTopWindow()) {
Leon Scroggins0d7ae0e2009-06-05 11:04:45 -04001312 return false;
1313 }
Grace Kloba6ee9c492009-07-13 10:04:34 -07001314 if (mMenuIsDown) {
1315 // The shortcut action consumes the MENU. Even if it is still down,
1316 // it won't trigger the next shortcut action. In the case of the
1317 // shortcut action triggering a new activity, like Bookmarks, we
1318 // won't get onKeyUp for MENU. So it is important to reset it here.
1319 mMenuIsDown = false;
1320 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001321 switch (item.getItemId()) {
1322 // -- Main menu
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001323 case R.id.new_tab_menu_id:
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001324 openTabToHomePage();
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001325 break;
1326
Leon Scroggins64b80f32009-08-07 12:03:34 -04001327 case R.id.goto_menu_id:
Leon Scroggins8ad29922010-02-16 12:33:55 -05001328 editUrl();
Leon Scrogginsb3a5bed2009-09-28 11:21:56 -04001329 break;
1330
1331 case R.id.bookmarks_menu_id:
Leon Scroggins30444232009-09-04 18:36:20 -04001332 bookmarksOrHistoryPicker(false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001333 break;
1334
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001335 case R.id.active_tabs_menu_id:
1336 mActiveTabsPage = new ActiveTabsPage(this, mTabControl);
1337 removeTabFromContentView(mTabControl.getCurrentTab());
Leon Scroggins43de6162009-09-14 19:59:58 -04001338 hideFakeTitleBar();
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001339 mContentView.addView(mActiveTabsPage, COVER_SCREEN_PARAMS);
1340 mActiveTabsPage.requestFocus();
1341 mMenuState = EMPTY_MENU;
1342 break;
1343
Leon Scroggins1f005d32009-08-10 17:36:42 -04001344 case R.id.add_bookmark_menu_id:
1345 Intent i = new Intent(BrowserActivity.this,
1346 AddBookmarkPage.class);
1347 WebView w = getTopWindow();
1348 i.putExtra("url", w.getUrl());
1349 i.putExtra("title", w.getTitle());
Grace Kloba83cdb2c2009-09-16 00:48:57 -07001350 i.putExtra("touch_icon_url", w.getTouchIconUrl());
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01001351 i.putExtra("thumbnail", createScreenshot(w));
Leon Scroggins1f005d32009-08-10 17:36:42 -04001352 startActivity(i);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001353 break;
1354
1355 case R.id.stop_reload_menu_id:
1356 if (mInLoad) {
1357 stopLoading();
1358 } else {
1359 getTopWindow().reload();
1360 }
1361 break;
1362
1363 case R.id.back_menu_id:
1364 getTopWindow().goBack();
1365 break;
1366
1367 case R.id.forward_menu_id:
1368 getTopWindow().goForward();
1369 break;
1370
1371 case R.id.close_menu_id:
1372 // Close the subwindow if it exists.
1373 if (mTabControl.getCurrentSubWindow() != null) {
1374 dismissSubWindow(mTabControl.getCurrentTab());
1375 break;
1376 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001377 closeCurrentWindow();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001378 break;
1379
1380 case R.id.homepage_menu_id:
Grace Kloba22ac16e2009-10-07 18:00:23 -07001381 Tab current = mTabControl.getCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001382 if (current != null) {
1383 dismissSubWindow(current);
Leon Scroggins92472e82010-02-17 16:32:28 -05001384 loadUrl(current.getWebView(), mSettings.getHomePage());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001385 }
1386 break;
1387
1388 case R.id.preferences_menu_id:
1389 Intent intent = new Intent(this,
1390 BrowserPreferencesPage.class);
Leon Scrogginsd5304942009-12-10 16:11:39 -05001391 intent.putExtra(BrowserPreferencesPage.CURRENT_PAGE,
1392 getTopWindow().getUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001393 startActivityForResult(intent, PREFERENCES_PAGE);
1394 break;
1395
1396 case R.id.find_menu_id:
1397 if (null == mFindDialog) {
1398 mFindDialog = new FindDialog(this);
1399 }
1400 mFindDialog.setWebView(getTopWindow());
1401 mFindDialog.show();
Cary Clark7d3ac792010-03-03 10:11:44 -05001402 getTopWindow().setFindIsUp(true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001403 mMenuState = EMPTY_MENU;
1404 break;
1405
1406 case R.id.select_text_id:
1407 getTopWindow().emulateShiftHeld();
1408 break;
1409 case R.id.page_info_menu_id:
1410 showPageInfo(mTabControl.getCurrentTab(), false);
1411 break;
1412
1413 case R.id.classic_history_menu_id:
Leon Scroggins30444232009-09-04 18:36:20 -04001414 bookmarksOrHistoryPicker(true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001415 break;
1416
Leon Scroggins96afcb12009-12-10 12:35:56 -05001417 case R.id.title_bar_share_page_url:
The Android Open Source Project0c908882009-03-03 19:32:16 -08001418 case R.id.share_page_menu_id:
Leon Scroggins96afcb12009-12-10 12:35:56 -05001419 Tab currentTab = mTabControl.getCurrentTab();
1420 if (null == currentTab) {
1421 mCanChord = false;
1422 return false;
1423 }
1424 currentTab.populatePickerData();
1425 sharePage(this, currentTab.getTitle(),
1426 currentTab.getUrl(), currentTab.getFavicon(),
1427 createScreenshot(currentTab.getWebView()));
The Android Open Source Project0c908882009-03-03 19:32:16 -08001428 break;
1429
1430 case R.id.dump_nav_menu_id:
1431 getTopWindow().debugDump();
1432 break;
1433
Andrei Popescu7a8b88b2010-02-02 00:30:38 +00001434 case R.id.dump_counters_menu_id:
1435 getTopWindow().dumpV8Counters();
1436 break;
1437
The Android Open Source Project0c908882009-03-03 19:32:16 -08001438 case R.id.zoom_in_menu_id:
1439 getTopWindow().zoomIn();
1440 break;
1441
1442 case R.id.zoom_out_menu_id:
1443 getTopWindow().zoomOut();
1444 break;
1445
1446 case R.id.view_downloads_menu_id:
1447 viewDownloads(null);
1448 break;
1449
The Android Open Source Project0c908882009-03-03 19:32:16 -08001450 case R.id.window_one_menu_id:
1451 case R.id.window_two_menu_id:
1452 case R.id.window_three_menu_id:
1453 case R.id.window_four_menu_id:
1454 case R.id.window_five_menu_id:
1455 case R.id.window_six_menu_id:
1456 case R.id.window_seven_menu_id:
1457 case R.id.window_eight_menu_id:
1458 {
1459 int menuid = item.getItemId();
1460 for (int id = 0; id < WINDOW_SHORTCUT_ID_ARRAY.length; id++) {
1461 if (WINDOW_SHORTCUT_ID_ARRAY[id] == menuid) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001462 Tab desiredTab = mTabControl.getTab(id);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001463 if (desiredTab != null &&
1464 desiredTab != mTabControl.getCurrentTab()) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001465 switchToTab(id);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001466 }
1467 break;
1468 }
1469 }
1470 }
1471 break;
1472
1473 default:
1474 if (!super.onOptionsItemSelected(item)) {
1475 return false;
1476 }
1477 // Otherwise fall through.
1478 }
1479 mCanChord = false;
1480 return true;
1481 }
1482
1483 public void closeFind() {
1484 mMenuState = R.id.MAIN_MENU;
1485 }
1486
Grace Kloba22ac16e2009-10-07 18:00:23 -07001487 @Override
1488 public boolean onPrepareOptionsMenu(Menu menu) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001489 // This happens when the user begins to hold down the menu key, so
1490 // allow them to chord to get a shortcut.
1491 mCanChord = true;
1492 // Note: setVisible will decide whether an item is visible; while
1493 // setEnabled() will decide whether an item is enabled, which also means
1494 // whether the matching shortcut key will function.
1495 super.onPrepareOptionsMenu(menu);
1496 switch (mMenuState) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001497 case EMPTY_MENU:
1498 if (mCurrentMenuState != mMenuState) {
1499 menu.setGroupVisible(R.id.MAIN_MENU, false);
1500 menu.setGroupEnabled(R.id.MAIN_MENU, false);
1501 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001502 }
1503 break;
1504 default:
1505 if (mCurrentMenuState != mMenuState) {
1506 menu.setGroupVisible(R.id.MAIN_MENU, true);
1507 menu.setGroupEnabled(R.id.MAIN_MENU, true);
1508 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001509 }
1510 final WebView w = getTopWindow();
1511 boolean canGoBack = false;
1512 boolean canGoForward = false;
1513 boolean isHome = false;
1514 if (w != null) {
1515 canGoBack = w.canGoBack();
1516 canGoForward = w.canGoForward();
1517 isHome = mSettings.getHomePage().equals(w.getUrl());
1518 }
1519 final MenuItem back = menu.findItem(R.id.back_menu_id);
1520 back.setEnabled(canGoBack);
1521
1522 final MenuItem home = menu.findItem(R.id.homepage_menu_id);
1523 home.setEnabled(!isHome);
1524
1525 menu.findItem(R.id.forward_menu_id)
1526 .setEnabled(canGoForward);
1527
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001528 menu.findItem(R.id.new_tab_menu_id).setEnabled(
Grace Kloba22ac16e2009-10-07 18:00:23 -07001529 mTabControl.canCreateNewTab());
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001530
The Android Open Source Project0c908882009-03-03 19:32:16 -08001531 // decide whether to show the share link option
1532 PackageManager pm = getPackageManager();
1533 Intent send = new Intent(Intent.ACTION_SEND);
1534 send.setType("text/plain");
1535 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1536 menu.findItem(R.id.share_page_menu_id).setVisible(ri != null);
1537
The Android Open Source Project0c908882009-03-03 19:32:16 -08001538 boolean isNavDump = mSettings.isNavDump();
1539 final MenuItem nav = menu.findItem(R.id.dump_nav_menu_id);
1540 nav.setVisible(isNavDump);
1541 nav.setEnabled(isNavDump);
Andrei Popescu7a8b88b2010-02-02 00:30:38 +00001542
1543 boolean showDebugSettings = mSettings.showDebugSettings();
1544 final MenuItem counter = menu.findItem(R.id.dump_counters_menu_id);
1545 counter.setVisible(showDebugSettings);
1546 counter.setEnabled(showDebugSettings);
1547
The Android Open Source Project0c908882009-03-03 19:32:16 -08001548 break;
1549 }
1550 mCurrentMenuState = mMenuState;
1551 return true;
1552 }
1553
1554 @Override
1555 public void onCreateContextMenu(ContextMenu menu, View v,
1556 ContextMenuInfo menuInfo) {
Leon Scroggins4e9f89b2010-02-22 16:54:14 -05001557 if (v instanceof TitleBar) {
1558 return;
1559 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001560 WebView webview = (WebView) v;
1561 WebView.HitTestResult result = webview.getHitTestResult();
1562 if (result == null) {
1563 return;
1564 }
1565
1566 int type = result.getType();
1567 if (type == WebView.HitTestResult.UNKNOWN_TYPE) {
1568 Log.w(LOGTAG,
1569 "We should not show context menu when nothing is touched");
1570 return;
1571 }
1572 if (type == WebView.HitTestResult.EDIT_TEXT_TYPE) {
1573 // let TextView handles context menu
1574 return;
1575 }
1576
1577 // Note, http://b/issue?id=1106666 is requesting that
1578 // an inflated menu can be used again. This is not available
1579 // yet, so inflate each time (yuk!)
1580 MenuInflater inflater = getMenuInflater();
1581 inflater.inflate(R.menu.browsercontext, menu);
1582
1583 // Show the correct menu group
1584 String extra = result.getExtra();
1585 menu.setGroupVisible(R.id.PHONE_MENU,
1586 type == WebView.HitTestResult.PHONE_TYPE);
1587 menu.setGroupVisible(R.id.EMAIL_MENU,
1588 type == WebView.HitTestResult.EMAIL_TYPE);
1589 menu.setGroupVisible(R.id.GEO_MENU,
1590 type == WebView.HitTestResult.GEO_TYPE);
1591 menu.setGroupVisible(R.id.IMAGE_MENU,
1592 type == WebView.HitTestResult.IMAGE_TYPE
1593 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1594 menu.setGroupVisible(R.id.ANCHOR_MENU,
1595 type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1596 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1597
1598 // Setup custom handling depending on the type
1599 switch (type) {
1600 case WebView.HitTestResult.PHONE_TYPE:
1601 menu.setHeaderTitle(Uri.decode(extra));
1602 menu.findItem(R.id.dial_context_menu_id).setIntent(
1603 new Intent(Intent.ACTION_VIEW, Uri
1604 .parse(WebView.SCHEME_TEL + extra)));
1605 Intent addIntent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
1606 addIntent.putExtra(Insert.PHONE, Uri.decode(extra));
Cary Clark5e335a32009-09-22 14:53:11 -04001607 addIntent.setType(ContactsContract.Contacts.CONTENT_ITEM_TYPE);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001608 menu.findItem(R.id.add_contact_context_menu_id).setIntent(
1609 addIntent);
1610 menu.findItem(R.id.copy_phone_context_menu_id).setOnMenuItemClickListener(
1611 new Copy(extra));
1612 break;
1613
1614 case WebView.HitTestResult.EMAIL_TYPE:
1615 menu.setHeaderTitle(extra);
1616 menu.findItem(R.id.email_context_menu_id).setIntent(
1617 new Intent(Intent.ACTION_VIEW, Uri
1618 .parse(WebView.SCHEME_MAILTO + extra)));
1619 menu.findItem(R.id.copy_mail_context_menu_id).setOnMenuItemClickListener(
1620 new Copy(extra));
1621 break;
1622
1623 case WebView.HitTestResult.GEO_TYPE:
1624 menu.setHeaderTitle(extra);
1625 menu.findItem(R.id.map_context_menu_id).setIntent(
1626 new Intent(Intent.ACTION_VIEW, Uri
1627 .parse(WebView.SCHEME_GEO
1628 + URLEncoder.encode(extra))));
1629 menu.findItem(R.id.copy_geo_context_menu_id).setOnMenuItemClickListener(
1630 new Copy(extra));
1631 break;
1632
1633 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1634 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
1635 TextView titleView = (TextView) LayoutInflater.from(this)
1636 .inflate(android.R.layout.browser_link_context_header,
1637 null);
1638 titleView.setText(extra);
1639 menu.setHeaderView(titleView);
1640 // decide whether to show the open link in new tab option
1641 menu.findItem(R.id.open_newtab_context_menu_id).setVisible(
Grace Kloba22ac16e2009-10-07 18:00:23 -07001642 mTabControl.canCreateNewTab());
Ben Murdochde353622009-10-12 10:29:00 +01001643 menu.findItem(R.id.bookmark_context_menu_id).setVisible(
1644 Bookmarks.urlHasAcceptableScheme(extra));
The Android Open Source Project0c908882009-03-03 19:32:16 -08001645 PackageManager pm = getPackageManager();
1646 Intent send = new Intent(Intent.ACTION_SEND);
1647 send.setType("text/plain");
1648 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1649 menu.findItem(R.id.share_link_context_menu_id).setVisible(ri != null);
1650 if (type == WebView.HitTestResult.SRC_ANCHOR_TYPE) {
1651 break;
1652 }
1653 // otherwise fall through to handle image part
1654 case WebView.HitTestResult.IMAGE_TYPE:
1655 if (type == WebView.HitTestResult.IMAGE_TYPE) {
1656 menu.setHeaderTitle(extra);
1657 }
1658 menu.findItem(R.id.view_image_context_menu_id).setIntent(
1659 new Intent(Intent.ACTION_VIEW, Uri.parse(extra)));
1660 menu.findItem(R.id.download_context_menu_id).
1661 setOnMenuItemClickListener(new Download(extra));
Ben Murdoch4f75ba22009-10-27 11:48:28 +00001662 menu.findItem(R.id.set_wallpaper_context_menu_id).
1663 setOnMenuItemClickListener(new SetAsWallpaper(extra));
The Android Open Source Project0c908882009-03-03 19:32:16 -08001664 break;
1665
1666 default:
1667 Log.w(LOGTAG, "We should not get here.");
1668 break;
1669 }
Leon Scrogginsb2b19f52009-10-09 16:10:00 -04001670 hideFakeTitleBar();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001671 }
1672
The Android Open Source Project0c908882009-03-03 19:32:16 -08001673 // Attach the given tab to the content view.
Grace Klobac928c302009-09-17 11:51:21 -07001674 // this should only be called for the current tab.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001675 private void attachTabToContentView(Tab t) {
Steve Block2bc69912009-07-30 14:45:13 +01001676 // Attach the container that contains the main WebView and any other UI
1677 // associated with the tab.
Patrick Scottd0119532009-09-17 08:00:31 -04001678 t.attachTabToContentView(mContentView);
Ben Murdochbff2d602009-07-01 20:19:05 +01001679
1680 if (mShouldShowErrorConsole) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001681 ErrorConsoleView errorConsole = t.getErrorConsole(true);
Ben Murdochbff2d602009-07-01 20:19:05 +01001682 if (errorConsole.numberOfErrors() == 0) {
1683 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
1684 } else {
1685 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
1686 }
1687
1688 mErrorConsoleContainer.addView(errorConsole,
Romain Guy15b8ec62010-01-08 15:06:43 -08001689 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
Ben Murdochbff2d602009-07-01 20:19:05 +01001690 ViewGroup.LayoutParams.WRAP_CONTENT));
1691 }
1692
Leon Scroggins39ab28e2009-09-02 21:20:30 -04001693 WebView view = t.getWebView();
Leon Scroggins55a5bc22009-09-04 17:00:08 -04001694 view.setEmbeddedTitleBar(mTitleBar);
Leon Scroggins58d56c62010-01-28 15:12:40 -05001695 if (t.isInVoiceSearchMode()) {
1696 showVoiceTitleBar(t.getVoiceDisplayTitle());
1697 } else {
1698 revertVoiceTitleBar();
1699 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001700 // Request focus on the top window.
1701 t.getTopWindow().requestFocus();
1702 }
1703
1704 // Attach a sub window to the main WebView of the given tab.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001705 void attachSubWindow(Tab t) {
Patrick Scottd0119532009-09-17 08:00:31 -04001706 t.attachSubWindow(mContentView);
1707 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001708 }
1709
1710 // Remove the given tab from the content view.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001711 private void removeTabFromContentView(Tab t) {
Steve Block2bc69912009-07-30 14:45:13 +01001712 // Remove the container that contains the main WebView.
Patrick Scottd0119532009-09-17 08:00:31 -04001713 t.removeTabFromContentView(mContentView);
Ben Murdochbff2d602009-07-01 20:19:05 +01001714
Grace Kloba22ac16e2009-10-07 18:00:23 -07001715 ErrorConsoleView errorConsole = t.getErrorConsole(false);
1716 if (errorConsole != null) {
1717 mErrorConsoleContainer.removeView(errorConsole);
Ben Murdochbff2d602009-07-01 20:19:05 +01001718 }
1719
Leon Scroggins39ab28e2009-09-02 21:20:30 -04001720 WebView view = t.getWebView();
Leon Scrogginsbb85b902009-09-14 19:27:20 -04001721 if (view != null) {
1722 view.setEmbeddedTitleBar(null);
1723 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001724 }
1725
1726 // Remove the sub window if it exists. Also called by TabControl when the
1727 // user clicks the 'X' to dismiss a sub window.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001728 /* package */ void dismissSubWindow(Tab t) {
Patrick Scottd0119532009-09-17 08:00:31 -04001729 t.removeSubWindow(mContentView);
Grace Kloba22ac16e2009-10-07 18:00:23 -07001730 // dismiss the subwindow. This will destroy the WebView.
1731 t.dismissSubWindow();
Patrick Scottd0119532009-09-17 08:00:31 -04001732 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001733 }
1734
Leon Scroggins1f005d32009-08-10 17:36:42 -04001735 // A wrapper function of {@link #openTabAndShow(UrlData, boolean, String)}
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07001736 // that accepts url as string.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001737 private Tab openTabAndShow(String url, boolean closeOnExit, String appId) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001738 return openTabAndShow(new UrlData(url), closeOnExit, appId);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001739 }
1740
1741 // This method does a ton of stuff. It will attempt to create a new tab
1742 // if we haven't reached MAX_TABS. Otherwise it uses the current tab. If
Leon Scroggins1f005d32009-08-10 17:36:42 -04001743 // url isn't null, it will load the given url.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001744 /* package */Tab openTabAndShow(UrlData urlData, boolean closeOnExit,
1745 String appId) {
1746 final Tab currentTab = mTabControl.getCurrentTab();
1747 if (mTabControl.canCreateNewTab()) {
1748 final Tab tab = mTabControl.createNewTab(closeOnExit, appId,
1749 urlData.mUrl);
Leon Scroggins1f005d32009-08-10 17:36:42 -04001750 WebView webview = tab.getWebView();
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001751 // If the last tab was removed from the active tabs page, currentTab
1752 // will be null.
1753 if (currentTab != null) {
1754 removeTabFromContentView(currentTab);
1755 }
Patrick Scott8bbd69f2009-08-14 13:35:53 -04001756 // We must set the new tab as the current tab to reflect the old
1757 // animation behavior.
1758 mTabControl.setCurrentTab(tab);
Grace Klobaeb6eef42009-09-15 17:56:32 -07001759 attachTabToContentView(tab);
Leon Scroggins160a7e72009-08-14 18:28:01 -04001760 if (!urlData.isEmpty()) {
Patrick Scott9d53da02010-02-19 10:19:01 -05001761 loadUrlDataIn(tab, urlData);
Leon Scroggins1f005d32009-08-10 17:36:42 -04001762 }
1763 return tab;
1764 } else {
1765 // Get rid of the subwindow if it exists
1766 dismissSubWindow(currentTab);
1767 if (!urlData.isEmpty()) {
1768 // Load the given url.
Patrick Scott9d53da02010-02-19 10:19:01 -05001769 loadUrlDataIn(currentTab, urlData);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001770 }
Leon Scroggins58d56c62010-01-28 15:12:40 -05001771 return currentTab;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001772 }
1773 }
1774
Grace Kloba22ac16e2009-10-07 18:00:23 -07001775 private Tab openTab(String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001776 if (mSettings.openInBackground()) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001777 Tab t = mTabControl.createNewTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001778 if (t != null) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001779 WebView view = t.getWebView();
Leon Scroggins92472e82010-02-17 16:32:28 -05001780 loadUrl(view, url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001781 }
Grace Klobac9181842009-04-14 08:53:22 -07001782 return t;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001783 } else {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001784 return openTabAndShow(url, false, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001785 }
1786 }
1787
1788 private class Copy implements OnMenuItemClickListener {
1789 private CharSequence mText;
1790
1791 public boolean onMenuItemClick(MenuItem item) {
1792 copy(mText);
1793 return true;
1794 }
1795
1796 public Copy(CharSequence toCopy) {
1797 mText = toCopy;
1798 }
1799 }
1800
1801 private class Download implements OnMenuItemClickListener {
1802 private String mText;
1803
1804 public boolean onMenuItemClick(MenuItem item) {
1805 onDownloadStartNoStream(mText, null, null, null, -1);
1806 return true;
1807 }
1808
1809 public Download(String toDownload) {
1810 mText = toDownload;
1811 }
1812 }
1813
Ben Murdoch4f75ba22009-10-27 11:48:28 +00001814 private class SetAsWallpaper extends Thread implements
1815 OnMenuItemClickListener, DialogInterface.OnCancelListener {
1816 private URL mUrl;
1817 private ProgressDialog mWallpaperProgress;
1818 private boolean mCanceled = false;
1819
1820 public SetAsWallpaper(String url) {
1821 try {
1822 mUrl = new URL(url);
1823 } catch (MalformedURLException e) {
1824 mUrl = null;
1825 }
1826 }
1827
1828 public void onCancel(DialogInterface dialog) {
1829 mCanceled = true;
1830 }
1831
1832 public boolean onMenuItemClick(MenuItem item) {
1833 if (mUrl != null) {
1834 // The user may have tried to set a image with a large file size as their
1835 // background so it may take a few moments to perform the operation. Display
1836 // a progress spinner while it is working.
1837 mWallpaperProgress = new ProgressDialog(BrowserActivity.this);
1838 mWallpaperProgress.setIndeterminate(true);
1839 mWallpaperProgress.setMessage(getText(R.string.progress_dialog_setting_wallpaper));
1840 mWallpaperProgress.setCancelable(true);
1841 mWallpaperProgress.setOnCancelListener(this);
1842 mWallpaperProgress.show();
1843 start();
1844 }
1845 return true;
1846 }
1847
1848 public void run() {
1849 Drawable oldWallpaper = BrowserActivity.this.getWallpaper();
1850 try {
1851 // TODO: This will cause the resource to be downloaded again, when we
1852 // should in most cases be able to grab it from the cache. To fix this
1853 // we should query WebCore to see if we can access a cached version and
1854 // instead open an input stream on that. This pattern could also be used
1855 // in the download manager where the same problem exists.
1856 InputStream inputstream = mUrl.openStream();
1857 if (inputstream != null) {
1858 setWallpaper(inputstream);
1859 }
1860 } catch (IOException e) {
1861 Log.e(LOGTAG, "Unable to set new wallpaper");
1862 // Act as though the user canceled the operation so we try to
1863 // restore the old wallpaper.
1864 mCanceled = true;
1865 }
1866
1867 if (mCanceled) {
1868 // Restore the old wallpaper if the user cancelled whilst we were setting
1869 // the new wallpaper.
1870 int width = oldWallpaper.getIntrinsicWidth();
1871 int height = oldWallpaper.getIntrinsicHeight();
1872 Bitmap bm = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
1873 Canvas canvas = new Canvas(bm);
1874 oldWallpaper.setBounds(0, 0, width, height);
1875 oldWallpaper.draw(canvas);
1876 try {
1877 setWallpaper(bm);
1878 } catch (IOException e) {
1879 Log.e(LOGTAG, "Unable to restore old wallpaper.");
1880 }
1881 mCanceled = false;
1882 }
1883
1884 if (mWallpaperProgress.isShowing()) {
1885 mWallpaperProgress.dismiss();
1886 }
1887 }
1888 }
1889
The Android Open Source Project0c908882009-03-03 19:32:16 -08001890 private void copy(CharSequence text) {
1891 try {
1892 IClipboard clip = IClipboard.Stub.asInterface(ServiceManager.getService("clipboard"));
1893 if (clip != null) {
1894 clip.setClipboardText(text);
1895 }
1896 } catch (android.os.RemoteException e) {
1897 Log.e(LOGTAG, "Copy failed", e);
1898 }
1899 }
1900
1901 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08001902 * Resets the browser title-view to whatever it must be
1903 * (for example, if we had a loading error)
1904 * When we have a new page, we call resetTitle, when we
1905 * have to reset the titlebar to whatever it used to be
1906 * (for example, if the user chose to stop loading), we
1907 * call resetTitleAndRevertLockIcon.
1908 */
1909 /* package */ void resetTitleAndRevertLockIcon() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001910 mTabControl.getCurrentTab().revertLockIcon();
1911 updateLockIconToLatest();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001912 resetTitleIconAndProgress();
1913 }
1914
1915 /**
1916 * Reset the title, favicon, and progress.
1917 */
1918 private void resetTitleIconAndProgress() {
1919 WebView current = mTabControl.getCurrentWebView();
1920 if (current == null) {
1921 return;
1922 }
1923 resetTitleAndIcon(current);
1924 int progress = current.getProgress();
Grace Kloba22ac16e2009-10-07 18:00:23 -07001925 current.getWebChromeClient().onProgressChanged(current, progress);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001926 }
1927
1928 // Reset the title and the icon based on the given item.
1929 private void resetTitleAndIcon(WebView view) {
1930 WebHistoryItem item = view.copyBackForwardList().getCurrentItem();
1931 if (item != null) {
Leon Scroggins68579392009-09-15 15:31:54 -04001932 setUrlTitle(item.getUrl(), item.getTitle());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001933 setFavicon(item.getFavicon());
1934 } else {
Leon Scroggins68579392009-09-15 15:31:54 -04001935 setUrlTitle(null, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001936 setFavicon(null);
1937 }
1938 }
1939
1940 /**
1941 * Sets a title composed of the URL and the title string.
1942 * @param url The URL of the site being loaded.
1943 * @param title The title of the site being loaded.
1944 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07001945 void setUrlTitle(String url, String title) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001946 mUrl = url;
1947 mTitle = title;
1948
Leon Scroggins58d56c62010-01-28 15:12:40 -05001949 // If we are in voice search mode, the title has already been set.
1950 if (mTabControl.getCurrentTab().isInVoiceSearchMode()) return;
1951 mTitleBar.setDisplayTitle(url);
1952 mFakeTitleBar.setDisplayTitle(url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001953 }
1954
1955 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08001956 * @param url The URL to build a title version of the URL from.
1957 * @return The title version of the URL or null if fails.
1958 * The title version of the URL can be either the URL hostname,
1959 * or the hostname with an "https://" prefix (for secure URLs),
1960 * or an empty string if, for example, the URL in question is a
1961 * file:// URL with no hostname.
1962 */
Leon Scroggins32e14a62009-06-11 10:26:34 -04001963 /* package */ static String buildTitleUrl(String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001964 String titleUrl = null;
1965
1966 if (url != null) {
1967 try {
1968 // parse the url string
1969 URL urlObj = new URL(url);
1970 if (urlObj != null) {
1971 titleUrl = "";
1972
1973 String protocol = urlObj.getProtocol();
1974 String host = urlObj.getHost();
1975
1976 if (host != null && 0 < host.length()) {
1977 titleUrl = host;
1978 if (protocol != null) {
1979 // if a secure site, add an "https://" prefix!
1980 if (protocol.equalsIgnoreCase("https")) {
1981 titleUrl = protocol + "://" + host;
1982 }
1983 }
1984 }
1985 }
1986 } catch (MalformedURLException e) {}
1987 }
1988
1989 return titleUrl;
1990 }
1991
1992 // Set the favicon in the title bar.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001993 void setFavicon(Bitmap icon) {
Leon Scroggins68579392009-09-15 15:31:54 -04001994 mTitleBar.setFavicon(icon);
Leon Scrogginsfe87bd32009-10-06 10:10:00 -04001995 mFakeTitleBar.setFavicon(icon);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001996 }
1997
1998 /**
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001999 * Close the tab, remove its associated title bar, and adjust mTabControl's
2000 * current tab to a valid value.
Leon Scroggins1f005d32009-08-10 17:36:42 -04002001 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07002002 /* package */ void closeTab(Tab t) {
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002003 int currentIndex = mTabControl.getCurrentIndex();
2004 int removeIndex = mTabControl.getTabIndex(t);
Leon Scroggins1f005d32009-08-10 17:36:42 -04002005 mTabControl.removeTab(t);
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002006 if (currentIndex >= removeIndex && currentIndex != 0) {
2007 currentIndex--;
2008 }
2009 mTabControl.setCurrentTab(mTabControl.getTab(currentIndex));
Andrei Popescua5bf1de2009-09-23 16:39:23 +01002010 resetTitleIconAndProgress();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002011 }
2012
Leon Scrogginsdcc5eeb2010-02-23 17:26:37 -05002013 /* package */ void goBackOnePageOrQuit() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002014 Tab current = mTabControl.getCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002015 if (current == null) {
2016 /*
2017 * Instead of finishing the activity, simply push this to the back
2018 * of the stack and let ActivityManager to choose the foreground
2019 * activity. As BrowserActivity is singleTask, it will be always the
2020 * root of the task. So we can use either true or false for
2021 * moveTaskToBack().
2022 */
2023 moveTaskToBack(true);
Grace Kloba00d85e72009-09-23 18:50:05 -07002024 return;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002025 }
2026 WebView w = current.getWebView();
2027 if (w.canGoBack()) {
2028 w.goBack();
2029 } else {
2030 // Check to see if we are closing a window that was created by
2031 // another window. If so, we switch back to that window.
Grace Kloba22ac16e2009-10-07 18:00:23 -07002032 Tab parent = current.getParentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002033 if (parent != null) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04002034 switchToTab(mTabControl.getTabIndex(parent));
2035 // Now we close the other tab
2036 closeTab(current);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002037 } else {
2038 if (current.closeOnExit()) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002039 // force the tab's inLoad() to be false as we are going to
2040 // either finish the activity or remove the tab. This will
2041 // ensure pauseWebViewTimers() taking action.
2042 mTabControl.getCurrentTab().clearInLoad();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002043 if (mTabControl.getTabCount() == 1) {
2044 finish();
2045 return;
2046 }
Mike Reed7bfa63b2009-05-28 11:08:32 -04002047 // call pauseWebViewTimers() now, we won't be able to call
2048 // it in onPause() as the WebView won't be valid.
Grace Klobaec1b5ad2009-08-18 08:42:32 -07002049 // Temporarily change mActivityInPause to be true as
2050 // pauseWebViewTimers() will do nothing if mActivityInPause
2051 // is false.
Grace Kloba918e1d72009-08-13 14:55:06 -07002052 boolean savedState = mActivityInPause;
2053 if (savedState) {
Grace Klobaec1b5ad2009-08-18 08:42:32 -07002054 Log.e(LOGTAG, "BrowserActivity is already paused "
2055 + "while handing goBackOnePageOrQuit.");
Grace Kloba918e1d72009-08-13 14:55:06 -07002056 }
2057 mActivityInPause = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -04002058 pauseWebViewTimers();
Grace Kloba918e1d72009-08-13 14:55:06 -07002059 mActivityInPause = savedState;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002060 removeTabFromContentView(current);
2061 mTabControl.removeTab(current);
2062 }
2063 /*
2064 * Instead of finishing the activity, simply push this to the back
2065 * of the stack and let ActivityManager to choose the foreground
2066 * activity. As BrowserActivity is singleTask, it will be always the
2067 * root of the task. So we can use either true or false for
2068 * moveTaskToBack().
2069 */
2070 moveTaskToBack(true);
2071 }
2072 }
2073 }
2074
Grace Kloba22ac16e2009-10-07 18:00:23 -07002075 boolean isMenuDown() {
2076 return mMenuIsDown;
2077 }
2078
Grace Kloba5942df02009-09-18 11:48:29 -07002079 @Override
2080 public boolean onKeyDown(int keyCode, KeyEvent event) {
Leon Scrogginsf65b50d2009-12-08 10:44:28 -05002081 // Even if MENU is already held down, we need to call to super to open
2082 // the IME on long press.
2083 if (KeyEvent.KEYCODE_MENU == keyCode) {
2084 mMenuIsDown = true;
2085 return super.onKeyDown(keyCode, event);
2086 }
Grace Kloba5942df02009-09-18 11:48:29 -07002087 // The default key mode is DEFAULT_KEYS_SEARCH_LOCAL. As the MENU is
2088 // still down, we don't want to trigger the search. Pretend to consume
2089 // the key and do nothing.
2090 if (mMenuIsDown) return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002091
Grace Kloba5942df02009-09-18 11:48:29 -07002092 switch(keyCode) {
Grace Kloba5942df02009-09-18 11:48:29 -07002093 case KeyEvent.KEYCODE_SPACE:
Grace Klobada0fe552009-09-22 18:17:24 -07002094 // WebView/WebTextView handle the keys in the KeyDown. As
2095 // the Activity's shortcut keys are only handled when WebView
2096 // doesn't, have to do it in onKeyDown instead of onKeyUp.
2097 if (event.isShiftPressed()) {
2098 getTopWindow().pageUp(false);
2099 } else {
2100 getTopWindow().pageDown(false);
2101 }
Grace Kloba5942df02009-09-18 11:48:29 -07002102 return true;
2103 case KeyEvent.KEYCODE_BACK:
2104 if (event.getRepeatCount() == 0) {
2105 event.startTracking();
2106 return true;
2107 } else if (mCustomView == null && mActiveTabsPage == null
2108 && event.isLongPress()) {
2109 bookmarksOrHistoryPicker(true);
2110 return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002111 }
Grace Kloba5942df02009-09-18 11:48:29 -07002112 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002113 }
Grace Kloba5942df02009-09-18 11:48:29 -07002114 return super.onKeyDown(keyCode, event);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002115 }
2116
Grace Kloba5942df02009-09-18 11:48:29 -07002117 @Override
2118 public boolean onKeyUp(int keyCode, KeyEvent event) {
2119 switch(keyCode) {
2120 case KeyEvent.KEYCODE_MENU:
2121 mMenuIsDown = false;
2122 break;
Grace Kloba5942df02009-09-18 11:48:29 -07002123 case KeyEvent.KEYCODE_BACK:
2124 if (event.isTracking() && !event.isCanceled()) {
2125 if (mCustomView != null) {
2126 // if a custom view is showing, hide it
Grace Kloba22ac16e2009-10-07 18:00:23 -07002127 mTabControl.getCurrentWebView().getWebChromeClient()
2128 .onHideCustomView();
Grace Kloba5942df02009-09-18 11:48:29 -07002129 } else if (mActiveTabsPage != null) {
2130 // if tab page is showing, hide it
2131 removeActiveTabPage(true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002132 } else {
Grace Kloba5942df02009-09-18 11:48:29 -07002133 WebView subwindow = mTabControl.getCurrentSubWindow();
2134 if (subwindow != null) {
2135 if (subwindow.canGoBack()) {
2136 subwindow.goBack();
2137 } else {
2138 dismissSubWindow(mTabControl.getCurrentTab());
2139 }
2140 } else {
2141 goBackOnePageOrQuit();
2142 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002143 }
Grace Kloba5942df02009-09-18 11:48:29 -07002144 return true;
2145 }
2146 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002147 }
Grace Kloba5942df02009-09-18 11:48:29 -07002148 return super.onKeyUp(keyCode, event);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002149 }
2150
Leon Scroggins68579392009-09-15 15:31:54 -04002151 /* package */ void stopLoading() {
Ben Murdochb7cc8b42009-09-28 10:59:09 +01002152 mDidStopLoad = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002153 resetTitleAndRevertLockIcon();
2154 WebView w = getTopWindow();
2155 w.stopLoading();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002156 // FIXME: before refactor, it is using mWebViewClient. So I keep the
2157 // same logic here. But for subwindow case, should we call into the main
2158 // WebView's onPageFinished as we never call its onPageStarted and if
2159 // the page finishes itself, we don't call onPageFinished.
2160 mTabControl.getCurrentWebView().getWebViewClient().onPageFinished(w,
2161 w.getUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08002162
2163 cancelStopToast();
2164 mStopToast = Toast
2165 .makeText(this, R.string.stopping, Toast.LENGTH_SHORT);
2166 mStopToast.show();
2167 }
2168
Grace Kloba22ac16e2009-10-07 18:00:23 -07002169 boolean didUserStopLoading() {
2170 return mDidStopLoad;
2171 }
2172
The Android Open Source Project0c908882009-03-03 19:32:16 -08002173 private void cancelStopToast() {
2174 if (mStopToast != null) {
2175 mStopToast.cancel();
2176 mStopToast = null;
2177 }
2178 }
2179
Grace Kloba22ac16e2009-10-07 18:00:23 -07002180 // called by a UI or non-UI thread to post the message
2181 public void postMessage(int what, int arg1, int arg2, Object obj,
2182 long delayMillis) {
2183 mHandler.sendMessageDelayed(mHandler.obtainMessage(what, arg1, arg2,
2184 obj), delayMillis);
2185 }
2186
2187 // called by a UI or non-UI thread to remove the message
2188 void removeMessages(int what, Object object) {
2189 mHandler.removeMessages(what, object);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002190 }
2191
2192 // public message ids
2193 public final static int LOAD_URL = 1001;
2194 public final static int STOP_LOAD = 1002;
2195
2196 // Message Ids
2197 private static final int FOCUS_NODE_HREF = 102;
Grace Kloba92c18a52009-07-31 23:48:32 -07002198 private static final int RELEASE_WAKELOCK = 107;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002199
Grace Kloba22ac16e2009-10-07 18:00:23 -07002200 static final int UPDATE_BOOKMARK_THUMBNAIL = 108;
Ben Murdoch2694e232009-09-29 09:41:11 +01002201
The Android Open Source Project0c908882009-03-03 19:32:16 -08002202 // Private handler for handling javascript and saving passwords
2203 private Handler mHandler = new Handler() {
2204
2205 public void handleMessage(Message msg) {
2206 switch (msg.what) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002207 case FOCUS_NODE_HREF:
Ben Murdoch2694e232009-09-29 09:41:11 +01002208 {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002209 String url = (String) msg.getData().get("url");
Ben Murdoch90d088c2009-11-17 18:14:04 +00002210 String title = (String) msg.getData().get("title");
The Android Open Source Project0c908882009-03-03 19:32:16 -08002211 if (url == null || url.length() == 0) {
2212 break;
2213 }
2214 HashMap focusNodeMap = (HashMap) msg.obj;
2215 WebView view = (WebView) focusNodeMap.get("webview");
2216 // Only apply the action if the top window did not change.
2217 if (getTopWindow() != view) {
2218 break;
2219 }
2220 switch (msg.arg1) {
2221 case R.id.open_context_menu_id:
2222 case R.id.view_image_context_menu_id:
Leon Scroggins92472e82010-02-17 16:32:28 -05002223 loadUrlFromContext(getTopWindow(), url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002224 break;
2225 case R.id.open_newtab_context_menu_id:
Grace Kloba22ac16e2009-10-07 18:00:23 -07002226 final Tab parent = mTabControl.getCurrentTab();
2227 final Tab newTab = openTab(url);
Grace Klobac9181842009-04-14 08:53:22 -07002228 if (newTab != parent) {
2229 parent.addChildTab(newTab);
2230 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002231 break;
2232 case R.id.bookmark_context_menu_id:
2233 Intent intent = new Intent(BrowserActivity.this,
2234 AddBookmarkPage.class);
2235 intent.putExtra("url", url);
Ben Murdoch90d088c2009-11-17 18:14:04 +00002236 intent.putExtra("title", title);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002237 startActivity(intent);
2238 break;
2239 case R.id.share_link_context_menu_id:
Leon Scroggins96afcb12009-12-10 12:35:56 -05002240 // See if this site has been visited before
2241 StringBuilder sb = new StringBuilder(
2242 Browser.BookmarkColumns.URL + " = ");
2243 DatabaseUtils.appendEscapedSQLString(sb, url);
2244 Cursor c = mResolver.query(Browser.BOOKMARKS_URI,
2245 Browser.HISTORY_PROJECTION,
2246 sb.toString(),
2247 null,
2248 null);
2249 if (c.moveToFirst()) {
2250 // The site has been visited before, so grab the
2251 // info from the database.
2252 Bitmap favicon = null;
2253 Bitmap thumbnail = null;
2254 String linkTitle = c.getString(Browser.
2255 HISTORY_PROJECTION_TITLE_INDEX);
2256 byte[] data = c.getBlob(Browser.
2257 HISTORY_PROJECTION_FAVICON_INDEX);
2258 if (data != null) {
2259 favicon = BitmapFactory.decodeByteArray(
2260 data, 0, data.length);
2261 }
2262 data = c.getBlob(Browser.
2263 HISTORY_PROJECTION_THUMBNAIL_INDEX);
2264 if (data != null) {
2265 thumbnail = BitmapFactory.decodeByteArray(
2266 data, 0, data.length);
2267 }
2268 sharePage(BrowserActivity.this,
2269 linkTitle, url, favicon, thumbnail);
2270 } else {
2271 Browser.sendString(BrowserActivity.this, url,
2272 getString(
2273 R.string.choosertitle_sharevia));
2274 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002275 break;
2276 case R.id.copy_link_context_menu_id:
2277 copy(url);
2278 break;
2279 case R.id.save_link_context_menu_id:
2280 case R.id.download_context_menu_id:
2281 onDownloadStartNoStream(url, null, null, null, -1);
2282 break;
2283 }
2284 break;
Ben Murdoch2694e232009-09-29 09:41:11 +01002285 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002286
2287 case LOAD_URL:
Leon Scroggins92472e82010-02-17 16:32:28 -05002288 loadUrlFromContext(getTopWindow(), (String) msg.obj);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002289 break;
2290
2291 case STOP_LOAD:
2292 stopLoading();
2293 break;
2294
The Android Open Source Project0c908882009-03-03 19:32:16 -08002295 case RELEASE_WAKELOCK:
2296 if (mWakeLock.isHeld()) {
2297 mWakeLock.release();
Grace Kloba5d0e02e2009-10-05 15:15:36 -07002298 // if we reach here, Browser should be still in the
2299 // background loading after WAKELOCK_TIMEOUT (5-min).
2300 // To avoid burning the battery, stop loading.
2301 mTabControl.stopAllLoading();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002302 }
2303 break;
Ben Murdoch2694e232009-09-29 09:41:11 +01002304
2305 case UPDATE_BOOKMARK_THUMBNAIL:
2306 WebView view = (WebView) msg.obj;
2307 if (view != null) {
2308 updateScreenshot(view);
2309 }
2310 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002311 }
2312 }
2313 };
2314
Leon Scroggins96afcb12009-12-10 12:35:56 -05002315 /**
2316 * Share a page, providing the title, url, favicon, and a screenshot. Uses
2317 * an {@link Intent} to launch the Activity chooser.
2318 * @param c Context used to launch a new Activity.
2319 * @param title Title of the page. Stored in the Intent with
Paul Westbrook03e6d392010-02-12 10:33:29 -08002320 * {@link Intent#EXTRA_SUBJECT}
Leon Scroggins96afcb12009-12-10 12:35:56 -05002321 * @param url URL of the page. Stored in the Intent with
2322 * {@link Intent#EXTRA_TEXT}
2323 * @param favicon Bitmap of the favicon for the page. Stored in the Intent
2324 * with {@link Browser#EXTRA_SHARE_FAVICON}
2325 * @param screenshot Bitmap of a screenshot of the page. Stored in the
2326 * Intent with {@link Browser#EXTRA_SHARE_SCREENSHOT}
2327 */
2328 public static final void sharePage(Context c, String title, String url,
2329 Bitmap favicon, Bitmap screenshot) {
2330 Intent send = new Intent(Intent.ACTION_SEND);
2331 send.setType("text/plain");
2332 send.putExtra(Intent.EXTRA_TEXT, url);
Paul Westbrook03e6d392010-02-12 10:33:29 -08002333 send.putExtra(Intent.EXTRA_SUBJECT, title);
Leon Scroggins96afcb12009-12-10 12:35:56 -05002334 send.putExtra(Browser.EXTRA_SHARE_FAVICON, favicon);
2335 send.putExtra(Browser.EXTRA_SHARE_SCREENSHOT, screenshot);
2336 try {
2337 c.startActivity(Intent.createChooser(send, c.getString(
2338 R.string.choosertitle_sharevia)));
2339 } catch(android.content.ActivityNotFoundException ex) {
2340 // if no app handles it, do nothing
2341 }
2342 }
2343
Leon Scroggins89c6d362009-07-15 16:54:37 -04002344 private void updateScreenshot(WebView view) {
2345 // If this is a bookmarked site, add a screenshot to the database.
2346 // FIXME: When should we update? Every time?
2347 // FIXME: Would like to make sure there is actually something to
2348 // draw, but the API for that (WebViewCore.pictureReady()) is not
2349 // currently accessible here.
Ben Murdochaac7aa62009-09-17 16:57:40 +01002350
Patrick Scott3918d442009-08-04 13:22:29 -04002351 ContentResolver cr = getContentResolver();
2352 final Cursor c = BrowserBookmarksAdapter.queryBookmarksForUrl(
Ben Murdochaac7aa62009-09-17 16:57:40 +01002353 cr, view.getOriginalUrl(), view.getUrl(), true);
Patrick Scott3918d442009-08-04 13:22:29 -04002354 if (c != null) {
Leon Scroggins89c6d362009-07-15 16:54:37 -04002355 boolean succeed = c.moveToFirst();
2356 ContentValues values = null;
2357 while (succeed) {
2358 if (values == null) {
2359 final ByteArrayOutputStream os
2360 = new ByteArrayOutputStream();
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002361 Bitmap bm = createScreenshot(view);
Leon Scroggins45800572009-09-29 16:38:47 -04002362 if (bm == null) {
2363 c.close();
2364 return;
2365 }
Leon Scroggins89c6d362009-07-15 16:54:37 -04002366 bm.compress(Bitmap.CompressFormat.PNG, 100, os);
2367 values = new ContentValues();
2368 values.put(Browser.BookmarkColumns.THUMBNAIL,
2369 os.toByteArray());
2370 }
2371 cr.update(ContentUris.withAppendedId(Browser.BOOKMARKS_URI,
2372 c.getInt(0)), values, null, null);
2373 succeed = c.moveToNext();
2374 }
2375 c.close();
2376 }
2377 }
2378
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002379 /**
Leon Scrogginsf8551612009-09-24 16:06:02 -04002380 * Values for the size of the thumbnail created when taking a screenshot.
2381 * Lazily initialized. Instead of using these directly, use
2382 * getDesiredThumbnailWidth() or getDesiredThumbnailHeight().
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002383 */
Leon Scrogginsf8551612009-09-24 16:06:02 -04002384 private static int THUMBNAIL_WIDTH = 0;
2385 private static int THUMBNAIL_HEIGHT = 0;
2386
2387 /**
2388 * Return the desired width for thumbnail screenshots, which are stored in
2389 * the database, and used on the bookmarks screen.
2390 * @param context Context for finding out the density of the screen.
2391 * @return int desired width for thumbnail screenshot.
2392 */
2393 /* package */ static int getDesiredThumbnailWidth(Context context) {
2394 if (THUMBNAIL_WIDTH == 0) {
2395 float density = context.getResources().getDisplayMetrics().density;
2396 THUMBNAIL_WIDTH = (int) (90 * density);
2397 THUMBNAIL_HEIGHT = (int) (80 * density);
2398 }
2399 return THUMBNAIL_WIDTH;
2400 }
2401
2402 /**
2403 * Return the desired height for thumbnail screenshots, which are stored in
2404 * the database, and used on the bookmarks screen.
2405 * @param context Context for finding out the density of the screen.
2406 * @return int desired height for thumbnail screenshot.
2407 */
2408 /* package */ static int getDesiredThumbnailHeight(Context context) {
2409 // To ensure that they are both initialized.
2410 getDesiredThumbnailWidth(context);
2411 return THUMBNAIL_HEIGHT;
2412 }
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002413
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002414 private Bitmap createScreenshot(WebView view) {
2415 Picture thumbnail = view.capturePicture();
Leon Scroggins45800572009-09-29 16:38:47 -04002416 if (thumbnail == null) {
2417 return null;
2418 }
Leon Scrogginsf8551612009-09-24 16:06:02 -04002419 Bitmap bm = Bitmap.createBitmap(getDesiredThumbnailWidth(this),
2420 getDesiredThumbnailHeight(this), Bitmap.Config.ARGB_4444);
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002421 Canvas canvas = new Canvas(bm);
2422 // May need to tweak these values to determine what is the
2423 // best scale factor
Ben Murdoch2694e232009-09-29 09:41:11 +01002424 int thumbnailWidth = thumbnail.getWidth();
Ben Murdochae59c3f2009-10-20 18:30:28 +01002425 int thumbnailHeight = thumbnail.getHeight();
2426 float scaleFactorX = 1.0f;
2427 float scaleFactorY = 1.0f;
Ben Murdoch2694e232009-09-29 09:41:11 +01002428 if (thumbnailWidth > 0) {
Ben Murdochae59c3f2009-10-20 18:30:28 +01002429 scaleFactorX = (float) getDesiredThumbnailWidth(this) /
Ben Murdoch2694e232009-09-29 09:41:11 +01002430 (float)thumbnailWidth;
Ben Murdochae59c3f2009-10-20 18:30:28 +01002431 } else {
2432 return null;
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002433 }
Ben Murdochae59c3f2009-10-20 18:30:28 +01002434
2435 if (view.getWidth() > view.getHeight() &&
2436 thumbnailHeight < view.getHeight() && thumbnailHeight > 0) {
2437 // If the device is in landscape and the page is shorter
2438 // than the height of the view, stretch the thumbnail to fill the
2439 // space.
2440 scaleFactorY = (float) getDesiredThumbnailHeight(this) /
2441 (float)thumbnailHeight;
2442 } else {
2443 // In the portrait case, this looks nice.
2444 scaleFactorY = scaleFactorX;
2445 }
2446
2447 canvas.scale(scaleFactorX, scaleFactorY);
2448
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002449 thumbnail.draw(canvas);
2450 return bm;
2451 }
2452
The Android Open Source Project0c908882009-03-03 19:32:16 -08002453 // -------------------------------------------------------------------------
Grace Kloba22ac16e2009-10-07 18:00:23 -07002454 // Helper function for WebViewClient.
The Android Open Source Project0c908882009-03-03 19:32:16 -08002455 //-------------------------------------------------------------------------
2456
2457 // Use in overrideUrlLoading
2458 /* package */ final static String SCHEME_WTAI = "wtai://wp/";
2459 /* package */ final static String SCHEME_WTAI_MC = "wtai://wp/mc;";
2460 /* package */ final static String SCHEME_WTAI_SD = "wtai://wp/sd;";
2461 /* package */ final static String SCHEME_WTAI_AP = "wtai://wp/ap;";
2462
Leon Scroggins92472e82010-02-17 16:32:28 -05002463 // Keep this initial progress in sync with initialProgressValue (* 100)
2464 // in ProgressTracker.cpp
2465 private final static int INITIAL_PROGRESS = 10;
2466
Grace Kloba22ac16e2009-10-07 18:00:23 -07002467 void onPageStarted(WebView view, String url, Bitmap favicon) {
2468 // when BrowserActivity just starts, onPageStarted may be called before
2469 // onResume as it is triggered from onCreate. Call resumeWebViewTimers
2470 // to start the timer. As we won't switch tabs while an activity is in
2471 // pause state, we can ensure calling resume and pause in pair.
2472 if (mActivityInPause) resumeWebViewTimers();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002473
Grace Kloba22ac16e2009-10-07 18:00:23 -07002474 resetLockIcon(url);
2475 setUrlTitle(url, null);
2476 setFavicon(favicon);
Leon Scroggins8cf8f682009-11-04 11:13:50 -08002477 // Show some progress so that the user knows the page is beginning to
2478 // load
Leon Scroggins92472e82010-02-17 16:32:28 -05002479 onProgressChanged(view, INITIAL_PROGRESS);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002480 mDidStopLoad = false;
Grace Kloba22ac16e2009-10-07 18:00:23 -07002481 if (!mIsNetworkUp) createAndShowNetworkDialog();
Patrick Scott15525d42009-09-21 13:39:37 -04002482
Grace Kloba22ac16e2009-10-07 18:00:23 -07002483 if (mSettings.isTracing()) {
2484 String host;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002485 try {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002486 WebAddress uri = new WebAddress(url);
2487 host = uri.mHost;
2488 } catch (android.net.ParseException ex) {
2489 host = "browser";
The Android Open Source Project0c908882009-03-03 19:32:16 -08002490 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002491 host = host.replace('.', '_');
2492 host += ".trace";
2493 mInTrace = true;
2494 Debug.startMethodTracing(host, 20 * 1024 * 1024);
2495 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002496
Grace Kloba22ac16e2009-10-07 18:00:23 -07002497 // Performance probe
2498 if (false) {
2499 mStart = SystemClock.uptimeMillis();
2500 mProcessStart = Process.getElapsedCpuTime();
2501 long[] sysCpu = new long[7];
2502 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2503 sysCpu, null)) {
2504 mUserStart = sysCpu[0] + sysCpu[1];
2505 mSystemStart = sysCpu[2];
2506 mIdleStart = sysCpu[3];
2507 mIrqStart = sysCpu[4] + sysCpu[5] + sysCpu[6];
2508 }
2509 mUiStart = SystemClock.currentThreadTimeMillis();
2510 }
2511 }
2512
2513 void onPageFinished(WebView view, String url) {
2514 // Reset the title and icon in case we stopped a provisional load.
2515 resetTitleAndIcon(view);
2516 // Update the lock icon image only once we are done loading
2517 updateLockIconToLatest();
2518 // pause the WebView timer and release the wake lock if it is finished
2519 // while BrowserActivity is in pause state.
2520 if (mActivityInPause && pauseWebViewTimers()) {
2521 if (mWakeLock.isHeld()) {
2522 mHandler.removeMessages(RELEASE_WAKELOCK);
2523 mWakeLock.release();
2524 }
2525 }
2526
2527 // Performance probe
2528 if (false) {
2529 long[] sysCpu = new long[7];
2530 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2531 sysCpu, null)) {
2532 String uiInfo = "UI thread used "
2533 + (SystemClock.currentThreadTimeMillis() - mUiStart)
2534 + " ms";
2535 if (LOGD_ENABLED) {
2536 Log.d(LOGTAG, uiInfo);
2537 }
2538 //The string that gets written to the log
2539 String performanceString = "It took total "
2540 + (SystemClock.uptimeMillis() - mStart)
2541 + " ms clock time to load the page."
2542 + "\nbrowser process used "
2543 + (Process.getElapsedCpuTime() - mProcessStart)
2544 + " ms, user processes used "
2545 + (sysCpu[0] + sysCpu[1] - mUserStart) * 10
2546 + " ms, kernel used "
2547 + (sysCpu[2] - mSystemStart) * 10
2548 + " ms, idle took " + (sysCpu[3] - mIdleStart) * 10
2549 + " ms and irq took "
2550 + (sysCpu[4] + sysCpu[5] + sysCpu[6] - mIrqStart)
2551 * 10 + " ms, " + uiInfo;
2552 if (LOGD_ENABLED) {
2553 Log.d(LOGTAG, performanceString + "\nWebpage: " + url);
2554 }
2555 if (url != null) {
2556 // strip the url to maintain consistency
2557 String newUrl = new String(url);
2558 if (newUrl.startsWith("http://www.")) {
2559 newUrl = newUrl.substring(11);
2560 } else if (newUrl.startsWith("http://")) {
2561 newUrl = newUrl.substring(7);
2562 } else if (newUrl.startsWith("https://www.")) {
2563 newUrl = newUrl.substring(12);
2564 } else if (newUrl.startsWith("https://")) {
2565 newUrl = newUrl.substring(8);
2566 }
2567 if (LOGD_ENABLED) {
2568 Log.d(LOGTAG, newUrl + " loaded");
2569 }
Grace Kloba5b078b52009-06-24 20:23:41 -07002570 }
2571 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002572 }
Grace Kloba5b078b52009-06-24 20:23:41 -07002573
Grace Kloba22ac16e2009-10-07 18:00:23 -07002574 if (mInTrace) {
2575 mInTrace = false;
2576 Debug.stopMethodTracing();
2577 }
2578 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002579
Grace Kloba22ac16e2009-10-07 18:00:23 -07002580 boolean shouldOverrideUrlLoading(WebView view, String url) {
2581 if (url.startsWith(SCHEME_WTAI)) {
2582 // wtai://wp/mc;number
2583 // number=string(phone-number)
2584 if (url.startsWith(SCHEME_WTAI_MC)) {
2585 Intent intent = new Intent(Intent.ACTION_VIEW,
2586 Uri.parse(WebView.SCHEME_TEL +
2587 url.substring(SCHEME_WTAI_MC.length())));
2588 startActivity(intent);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002589 return true;
2590 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002591 // wtai://wp/sd;dtmf
2592 // dtmf=string(dialstring)
2593 if (url.startsWith(SCHEME_WTAI_SD)) {
2594 // TODO: only send when there is active voice connection
2595 return false;
2596 }
2597 // wtai://wp/ap;number;name
2598 // number=string(phone-number)
2599 // name=string
2600 if (url.startsWith(SCHEME_WTAI_AP)) {
2601 // TODO
2602 return false;
2603 }
2604 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002605
Grace Kloba22ac16e2009-10-07 18:00:23 -07002606 // The "about:" schemes are internal to the browser; don't want these to
2607 // be dispatched to other apps.
2608 if (url.startsWith("about:")) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002609 return false;
2610 }
2611
Grace Kloba22ac16e2009-10-07 18:00:23 -07002612 Intent intent;
2613 // perform generic parsing of the URI to turn it into an Intent.
2614 try {
2615 intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME);
2616 } catch (URISyntaxException ex) {
2617 Log.w("Browser", "Bad URI " + url + ": " + ex.getMessage());
2618 return false;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002619 }
2620
Grace Kloba22ac16e2009-10-07 18:00:23 -07002621 // check whether the intent can be resolved. If not, we will see
2622 // whether we can download it from the Market.
2623 if (getPackageManager().resolveActivity(intent, 0) == null) {
2624 String packagename = intent.getPackage();
2625 if (packagename != null) {
2626 intent = new Intent(Intent.ACTION_VIEW, Uri
2627 .parse("market://search?q=pname:" + packagename));
2628 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2629 startActivity(intent);
2630 return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002631 } else {
2632 return false;
2633 }
2634 }
2635
Grace Kloba22ac16e2009-10-07 18:00:23 -07002636 // sanitize the Intent, ensuring web pages can not bypass browser
2637 // security (only access to BROWSABLE activities).
2638 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2639 intent.setComponent(null);
2640 try {
2641 if (startActivityIfNeeded(intent, -1)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002642 return true;
2643 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002644 } catch (ActivityNotFoundException ex) {
2645 // ignore the error. If no application can handle the URL,
2646 // eg about:blank, assume the browser can handle it.
2647 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002648
Grace Kloba22ac16e2009-10-07 18:00:23 -07002649 if (mMenuIsDown) {
2650 openTab(url);
2651 closeOptionsMenu();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002652 return true;
2653 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002654 return false;
2655 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002656
Grace Kloba22ac16e2009-10-07 18:00:23 -07002657 // -------------------------------------------------------------------------
2658 // Helper function for WebChromeClient
2659 // -------------------------------------------------------------------------
The Android Open Source Project0c908882009-03-03 19:32:16 -08002660
Grace Kloba22ac16e2009-10-07 18:00:23 -07002661 void onProgressChanged(WebView view, int newProgress) {
2662 mTitleBar.setProgress(newProgress);
2663 mFakeTitleBar.setProgress(newProgress);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002664
Grace Kloba22ac16e2009-10-07 18:00:23 -07002665 if (newProgress == 100) {
2666 // onProgressChanged() may continue to be called after the main
2667 // frame has finished loading, as any remaining sub frames continue
2668 // to load. We'll only get called once though with newProgress as
2669 // 100 when everything is loaded. (onPageFinished is called once
2670 // when the main frame completes loading regardless of the state of
2671 // any sub frames so calls to onProgressChanges may continue after
2672 // onPageFinished has executed)
2673 if (mInLoad) {
2674 mInLoad = false;
Leon Scrogginsa27ff192009-09-14 12:58:04 -04002675 updateInLoadMenuItems();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002676 // If the options menu is open, leave the title bar
2677 if (!mOptionsMenuOpen || !mIconView) {
2678 hideFakeTitleBar();
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07002679 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002680 }
Leon Scrogginsaa37e7f2010-03-05 11:51:20 -05002681 } else {
2682 if (!mInLoad) {
2683 // onPageFinished may have already been called but a subframe is
2684 // still loading and updating the progress. Reset mInLoad and
2685 // update the menu items.
2686 mInLoad = true;
2687 updateInLoadMenuItems();
2688 }
2689 // When the page first begins to load, the Activity may still be
2690 // paused, in which case showFakeTitleBar will do nothing. Call
2691 // again as the page continues to load so that it will be shown.
2692 // (Calling it will the fake title bar is already showing will also
2693 // do nothing.
Grace Kloba22ac16e2009-10-07 18:00:23 -07002694 if (!mOptionsMenuOpen || mIconView) {
2695 // This page has begun to load, so show the title bar
2696 showFakeTitleBar();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002697 }
2698 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002699 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002700
Grace Kloba22ac16e2009-10-07 18:00:23 -07002701 void onShowCustomView(View view, WebChromeClient.CustomViewCallback callback) {
Derek Sollenberger8ff57db2009-12-08 15:39:55 -05002702 // if a view already exists then immediately terminate the new one
2703 if (mCustomView != null) {
2704 callback.onCustomViewHidden();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002705 return;
Derek Sollenberger8ff57db2009-12-08 15:39:55 -05002706 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002707
2708 // Add the custom view to its container.
2709 mCustomViewContainer.addView(view, COVER_SCREEN_GRAVITY_CENTER);
2710 mCustomView = view;
2711 mCustomViewCallback = callback;
2712 // Save the menu state and set it to empty while the custom
2713 // view is showing.
2714 mOldMenuState = mMenuState;
2715 mMenuState = EMPTY_MENU;
2716 // Hide the content view.
2717 mContentView.setVisibility(View.GONE);
2718 // Finally show the custom view container.
Andrei Popescu163ab742009-10-20 17:58:23 +01002719 setStatusBarVisibility(false);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002720 mCustomViewContainer.setVisibility(View.VISIBLE);
2721 mCustomViewContainer.bringToFront();
2722 }
2723
2724 void onHideCustomView() {
2725 if (mCustomView == null)
2726 return;
2727
2728 // Hide the custom view.
2729 mCustomView.setVisibility(View.GONE);
2730 // Remove the custom view from its container.
2731 mCustomViewContainer.removeView(mCustomView);
2732 mCustomView = null;
2733 // Reset the old menu state.
2734 mMenuState = mOldMenuState;
2735 mOldMenuState = EMPTY_MENU;
2736 mCustomViewContainer.setVisibility(View.GONE);
2737 mCustomViewCallback.onCustomViewHidden();
2738 // Show the content view.
Andrei Popescu163ab742009-10-20 17:58:23 +01002739 setStatusBarVisibility(true);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002740 mContentView.setVisibility(View.VISIBLE);
2741 }
2742
2743 Bitmap getDefaultVideoPoster() {
2744 if (mDefaultVideoPoster == null) {
2745 mDefaultVideoPoster = BitmapFactory.decodeResource(
2746 getResources(), R.drawable.default_video_poster);
Patrick Scott3918d442009-08-04 13:22:29 -04002747 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002748 return mDefaultVideoPoster;
2749 }
Patrick Scott3918d442009-08-04 13:22:29 -04002750
Grace Kloba22ac16e2009-10-07 18:00:23 -07002751 View getVideoLoadingProgressView() {
2752 if (mVideoProgressView == null) {
2753 LayoutInflater inflater = LayoutInflater.from(BrowserActivity.this);
2754 mVideoProgressView = inflater.inflate(
2755 R.layout.video_loading_progress, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002756 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002757 return mVideoProgressView;
2758 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002759
Leon Scroggins8d5fa432009-10-02 15:55:59 -04002760 /*
2761 * The Object used to inform the WebView of the file to upload.
2762 */
2763 private ValueCallback<Uri> mUploadMessage;
2764
Grace Kloba22ac16e2009-10-07 18:00:23 -07002765 void openFileChooser(ValueCallback<Uri> uploadMsg) {
2766 if (mUploadMessage != null) return;
2767 mUploadMessage = uploadMsg;
2768 Intent i = new Intent(Intent.ACTION_GET_CONTENT);
2769 i.addCategory(Intent.CATEGORY_OPENABLE);
2770 i.setType("*/*");
2771 BrowserActivity.this.startActivityForResult(Intent.createChooser(i,
2772 getString(R.string.choose_upload)), FILE_SELECTED);
2773 }
2774
2775 // -------------------------------------------------------------------------
2776 // Implement functions for DownloadListener
2777 // -------------------------------------------------------------------------
2778
The Android Open Source Project0c908882009-03-03 19:32:16 -08002779 /**
2780 * Notify the host application a download should be done, or that
2781 * the data should be streamed if a streaming viewer is available.
2782 * @param url The full url to the content that should be downloaded
2783 * @param contentDisposition Content-disposition http header, if
2784 * present.
2785 * @param mimetype The mimetype of the content reported by the server
2786 * @param contentLength The file size reported by the server
2787 */
2788 public void onDownloadStart(String url, String userAgent,
2789 String contentDisposition, String mimetype, long contentLength) {
2790 // if we're dealing wih A/V content that's not explicitly marked
2791 // for download, check if it's streamable.
2792 if (contentDisposition == null
Patrick Scotte1fb9662009-08-31 14:31:52 -04002793 || !contentDisposition.regionMatches(
2794 true, 0, "attachment", 0, 10)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002795 // query the package manager to see if there's a registered handler
2796 // that matches.
2797 Intent intent = new Intent(Intent.ACTION_VIEW);
2798 intent.setDataAndType(Uri.parse(url), mimetype);
Patrick Scotte1fb9662009-08-31 14:31:52 -04002799 ResolveInfo info = getPackageManager().resolveActivity(intent,
2800 PackageManager.MATCH_DEFAULT_ONLY);
2801 if (info != null) {
2802 ComponentName myName = getComponentName();
2803 // If we resolved to ourselves, we don't want to attempt to
2804 // load the url only to try and download it again.
2805 if (!myName.getPackageName().equals(
2806 info.activityInfo.packageName)
2807 || !myName.getClassName().equals(
2808 info.activityInfo.name)) {
2809 // someone (other than us) knows how to handle this mime
2810 // type with this scheme, don't download.
2811 try {
2812 startActivity(intent);
2813 return;
2814 } catch (ActivityNotFoundException ex) {
2815 if (LOGD_ENABLED) {
2816 Log.d(LOGTAG, "activity not found for " + mimetype
2817 + " over " + Uri.parse(url).getScheme(),
2818 ex);
2819 }
2820 // Best behavior is to fall back to a download in this
2821 // case
The Android Open Source Project0c908882009-03-03 19:32:16 -08002822 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002823 }
2824 }
2825 }
2826 onDownloadStartNoStream(url, userAgent, contentDisposition, mimetype, contentLength);
2827 }
2828
2829 /**
2830 * Notify the host application a download should be done, even if there
2831 * is a streaming viewer available for thise type.
2832 * @param url The full url to the content that should be downloaded
2833 * @param contentDisposition Content-disposition http header, if
2834 * present.
2835 * @param mimetype The mimetype of the content reported by the server
2836 * @param contentLength The file size reported by the server
2837 */
2838 /*package */ void onDownloadStartNoStream(String url, String userAgent,
2839 String contentDisposition, String mimetype, long contentLength) {
2840
2841 String filename = URLUtil.guessFileName(url,
2842 contentDisposition, mimetype);
2843
2844 // Check to see if we have an SDCard
2845 String status = Environment.getExternalStorageState();
2846 if (!status.equals(Environment.MEDIA_MOUNTED)) {
2847 int title;
2848 String msg;
2849
2850 // Check to see if the SDCard is busy, same as the music app
2851 if (status.equals(Environment.MEDIA_SHARED)) {
2852 msg = getString(R.string.download_sdcard_busy_dlg_msg);
2853 title = R.string.download_sdcard_busy_dlg_title;
2854 } else {
2855 msg = getString(R.string.download_no_sdcard_dlg_msg, filename);
2856 title = R.string.download_no_sdcard_dlg_title;
2857 }
2858
2859 new AlertDialog.Builder(this)
2860 .setTitle(title)
2861 .setIcon(android.R.drawable.ic_dialog_alert)
2862 .setMessage(msg)
2863 .setPositiveButton(R.string.ok, null)
2864 .show();
2865 return;
2866 }
2867
2868 // java.net.URI is a lot stricter than KURL so we have to undo
2869 // KURL's percent-encoding and redo the encoding using java.net.URI.
2870 URI uri = null;
2871 try {
2872 // Undo the percent-encoding that KURL may have done.
2873 String newUrl = new String(URLUtil.decode(url.getBytes()));
2874 // Parse the url into pieces
2875 WebAddress w = new WebAddress(newUrl);
2876 String frag = null;
2877 String query = null;
2878 String path = w.mPath;
2879 // Break the path into path, query, and fragment
2880 if (path.length() > 0) {
2881 // Strip the fragment
2882 int idx = path.lastIndexOf('#');
2883 if (idx != -1) {
2884 frag = path.substring(idx + 1);
2885 path = path.substring(0, idx);
2886 }
2887 idx = path.lastIndexOf('?');
2888 if (idx != -1) {
2889 query = path.substring(idx + 1);
2890 path = path.substring(0, idx);
2891 }
2892 }
2893 uri = new URI(w.mScheme, w.mAuthInfo, w.mHost, w.mPort, path,
2894 query, frag);
2895 } catch (Exception e) {
2896 Log.e(LOGTAG, "Could not parse url for download: " + url, e);
2897 return;
2898 }
2899
2900 // XXX: Have to use the old url since the cookies were stored using the
2901 // old percent-encoded url.
2902 String cookies = CookieManager.getInstance().getCookie(url);
2903
2904 ContentValues values = new ContentValues();
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08002905 values.put(Downloads.Impl.COLUMN_URI, uri.toString());
2906 values.put(Downloads.Impl.COLUMN_COOKIE_DATA, cookies);
2907 values.put(Downloads.Impl.COLUMN_USER_AGENT, userAgent);
2908 values.put(Downloads.Impl.COLUMN_NOTIFICATION_PACKAGE,
The Android Open Source Project0c908882009-03-03 19:32:16 -08002909 getPackageName());
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08002910 values.put(Downloads.Impl.COLUMN_NOTIFICATION_CLASS,
The Android Open Source Project0c908882009-03-03 19:32:16 -08002911 BrowserDownloadPage.class.getCanonicalName());
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08002912 values.put(Downloads.Impl.COLUMN_VISIBILITY,
2913 Downloads.Impl.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
2914 values.put(Downloads.Impl.COLUMN_MIME_TYPE, mimetype);
2915 values.put(Downloads.Impl.COLUMN_FILE_NAME_HINT, filename);
2916 values.put(Downloads.Impl.COLUMN_DESCRIPTION, uri.getHost());
The Android Open Source Project0c908882009-03-03 19:32:16 -08002917 if (contentLength > 0) {
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08002918 values.put(Downloads.Impl.COLUMN_TOTAL_BYTES, contentLength);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002919 }
2920 if (mimetype == null) {
2921 // We must have long pressed on a link or image to download it. We
2922 // are not sure of the mimetype in this case, so do a head request
2923 new FetchUrlMimeType(this).execute(values);
2924 } else {
2925 final Uri contentUri =
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08002926 getContentResolver().insert(Downloads.Impl.CONTENT_URI, values);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002927 }
2928
2929 }
2930
Grace Kloba22ac16e2009-10-07 18:00:23 -07002931 // -------------------------------------------------------------------------
2932
The Android Open Source Project0c908882009-03-03 19:32:16 -08002933 /**
2934 * Resets the lock icon. This method is called when we start a new load and
2935 * know the url to be loaded.
2936 */
2937 private void resetLockIcon(String url) {
2938 // Save the lock-icon state (we revert to it if the load gets cancelled)
Grace Kloba22ac16e2009-10-07 18:00:23 -07002939 mTabControl.getCurrentTab().resetLockIcon(url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002940 updateLockIconImage(LOCK_ICON_UNSECURE);
2941 }
2942
The Android Open Source Project0c908882009-03-03 19:32:16 -08002943 /**
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04002944 * Update the lock icon to correspond to our latest state.
2945 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07002946 private void updateLockIconToLatest() {
2947 updateLockIconImage(mTabControl.getCurrentTab().getLockIconType());
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04002948 }
2949
2950 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08002951 * Updates the lock-icon image in the title-bar.
2952 */
2953 private void updateLockIconImage(int lockIconType) {
2954 Drawable d = null;
2955 if (lockIconType == LOCK_ICON_SECURE) {
2956 d = mSecLockIcon;
2957 } else if (lockIconType == LOCK_ICON_MIXED) {
2958 d = mMixLockIcon;
2959 }
Leon Scroggins68579392009-09-15 15:31:54 -04002960 mTitleBar.setLock(d);
Leon Scrogginsfe87bd32009-10-06 10:10:00 -04002961 mFakeTitleBar.setLock(d);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002962 }
2963
2964 /**
2965 * Displays a page-info dialog.
2966 * @param tab The tab to show info about
2967 * @param fromShowSSLCertificateOnError The flag that indicates whether
2968 * this dialog was opened from the SSL-certificate-on-error dialog or
2969 * not. This is important, since we need to know whether to return to
2970 * the parent dialog or simply dismiss.
2971 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07002972 private void showPageInfo(final Tab tab,
The Android Open Source Project0c908882009-03-03 19:32:16 -08002973 final boolean fromShowSSLCertificateOnError) {
2974 final LayoutInflater factory = LayoutInflater
2975 .from(this);
2976
2977 final View pageInfoView = factory.inflate(R.layout.page_info, null);
2978
2979 final WebView view = tab.getWebView();
2980
2981 String url = null;
2982 String title = null;
2983
2984 if (view == null) {
2985 url = tab.getUrl();
2986 title = tab.getTitle();
2987 } else if (view == mTabControl.getCurrentWebView()) {
2988 // Use the cached title and url if this is the current WebView
2989 url = mUrl;
2990 title = mTitle;
2991 } else {
2992 url = view.getUrl();
2993 title = view.getTitle();
2994 }
2995
2996 if (url == null) {
2997 url = "";
2998 }
2999 if (title == null) {
3000 title = "";
3001 }
3002
3003 ((TextView) pageInfoView.findViewById(R.id.address)).setText(url);
3004 ((TextView) pageInfoView.findViewById(R.id.title)).setText(title);
3005
3006 mPageInfoView = tab;
Leon Scrogginsc7b92f82010-01-11 18:17:31 -05003007 mPageInfoFromShowSSLCertificateOnError = fromShowSSLCertificateOnError;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003008
3009 AlertDialog.Builder alertDialogBuilder =
3010 new AlertDialog.Builder(this)
3011 .setTitle(R.string.page_info).setIcon(android.R.drawable.ic_dialog_info)
3012 .setView(pageInfoView)
3013 .setPositiveButton(
3014 R.string.ok,
3015 new DialogInterface.OnClickListener() {
3016 public void onClick(DialogInterface dialog,
3017 int whichButton) {
3018 mPageInfoDialog = null;
3019 mPageInfoView = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003020
3021 // if we came here from the SSL error dialog
3022 if (fromShowSSLCertificateOnError) {
3023 // go back to the SSL error dialog
3024 showSSLCertificateOnError(
3025 mSSLCertificateOnErrorView,
3026 mSSLCertificateOnErrorHandler,
3027 mSSLCertificateOnErrorError);
3028 }
3029 }
3030 })
3031 .setOnCancelListener(
3032 new DialogInterface.OnCancelListener() {
3033 public void onCancel(DialogInterface dialog) {
3034 mPageInfoDialog = null;
3035 mPageInfoView = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003036
3037 // if we came here from the SSL error dialog
3038 if (fromShowSSLCertificateOnError) {
3039 // go back to the SSL error dialog
3040 showSSLCertificateOnError(
3041 mSSLCertificateOnErrorView,
3042 mSSLCertificateOnErrorHandler,
3043 mSSLCertificateOnErrorError);
3044 }
3045 }
3046 });
3047
3048 // if we have a main top-level page SSL certificate set or a certificate
3049 // error
3050 if (fromShowSSLCertificateOnError ||
3051 (view != null && view.getCertificate() != null)) {
3052 // add a 'View Certificate' button
3053 alertDialogBuilder.setNeutralButton(
3054 R.string.view_certificate,
3055 new DialogInterface.OnClickListener() {
3056 public void onClick(DialogInterface dialog,
3057 int whichButton) {
3058 mPageInfoDialog = null;
3059 mPageInfoView = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003060
3061 // if we came here from the SSL error dialog
3062 if (fromShowSSLCertificateOnError) {
3063 // go back to the SSL error dialog
3064 showSSLCertificateOnError(
3065 mSSLCertificateOnErrorView,
3066 mSSLCertificateOnErrorHandler,
3067 mSSLCertificateOnErrorError);
3068 } else {
3069 // otherwise, display the top-most certificate from
3070 // the chain
3071 if (view.getCertificate() != null) {
3072 showSSLCertificate(tab);
3073 }
3074 }
3075 }
3076 });
3077 }
3078
3079 mPageInfoDialog = alertDialogBuilder.show();
3080 }
3081
3082 /**
3083 * Displays the main top-level page SSL certificate dialog
3084 * (accessible from the Page-Info dialog).
3085 * @param tab The tab to show certificate for.
3086 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003087 private void showSSLCertificate(final Tab tab) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003088 final View certificateView =
3089 inflateCertificateView(tab.getWebView().getCertificate());
3090 if (certificateView == null) {
3091 return;
3092 }
3093
3094 LayoutInflater factory = LayoutInflater.from(this);
3095
3096 final LinearLayout placeholder =
3097 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3098
3099 LinearLayout ll = (LinearLayout) factory.inflate(
3100 R.layout.ssl_success, placeholder);
3101 ((TextView)ll.findViewById(R.id.success))
3102 .setText(R.string.ssl_certificate_is_valid);
3103
3104 mSSLCertificateView = tab;
3105 mSSLCertificateDialog =
3106 new AlertDialog.Builder(this)
3107 .setTitle(R.string.ssl_certificate).setIcon(
3108 R.drawable.ic_dialog_browser_certificate_secure)
3109 .setView(certificateView)
3110 .setPositiveButton(R.string.ok,
3111 new DialogInterface.OnClickListener() {
3112 public void onClick(DialogInterface dialog,
3113 int whichButton) {
3114 mSSLCertificateDialog = null;
3115 mSSLCertificateView = null;
3116
3117 showPageInfo(tab, false);
3118 }
3119 })
3120 .setOnCancelListener(
3121 new DialogInterface.OnCancelListener() {
3122 public void onCancel(DialogInterface dialog) {
3123 mSSLCertificateDialog = null;
3124 mSSLCertificateView = null;
3125
3126 showPageInfo(tab, false);
3127 }
3128 })
3129 .show();
3130 }
3131
3132 /**
3133 * Displays the SSL error certificate dialog.
3134 * @param view The target web-view.
3135 * @param handler The SSL error handler responsible for cancelling the
3136 * connection that resulted in an SSL error or proceeding per user request.
3137 * @param error The SSL error object.
3138 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003139 void showSSLCertificateOnError(
The Android Open Source Project0c908882009-03-03 19:32:16 -08003140 final WebView view, final SslErrorHandler handler, final SslError error) {
3141
3142 final View certificateView =
3143 inflateCertificateView(error.getCertificate());
3144 if (certificateView == null) {
3145 return;
3146 }
3147
3148 LayoutInflater factory = LayoutInflater.from(this);
3149
3150 final LinearLayout placeholder =
3151 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3152
3153 if (error.hasError(SslError.SSL_UNTRUSTED)) {
3154 LinearLayout ll = (LinearLayout)factory
3155 .inflate(R.layout.ssl_warning, placeholder);
3156 ((TextView)ll.findViewById(R.id.warning))
3157 .setText(R.string.ssl_untrusted);
3158 }
3159
3160 if (error.hasError(SslError.SSL_IDMISMATCH)) {
3161 LinearLayout ll = (LinearLayout)factory
3162 .inflate(R.layout.ssl_warning, placeholder);
3163 ((TextView)ll.findViewById(R.id.warning))
3164 .setText(R.string.ssl_mismatch);
3165 }
3166
3167 if (error.hasError(SslError.SSL_EXPIRED)) {
3168 LinearLayout ll = (LinearLayout)factory
3169 .inflate(R.layout.ssl_warning, placeholder);
3170 ((TextView)ll.findViewById(R.id.warning))
3171 .setText(R.string.ssl_expired);
3172 }
3173
3174 if (error.hasError(SslError.SSL_NOTYETVALID)) {
3175 LinearLayout ll = (LinearLayout)factory
3176 .inflate(R.layout.ssl_warning, placeholder);
3177 ((TextView)ll.findViewById(R.id.warning))
3178 .setText(R.string.ssl_not_yet_valid);
3179 }
3180
3181 mSSLCertificateOnErrorHandler = handler;
3182 mSSLCertificateOnErrorView = view;
3183 mSSLCertificateOnErrorError = error;
3184 mSSLCertificateOnErrorDialog =
3185 new AlertDialog.Builder(this)
3186 .setTitle(R.string.ssl_certificate).setIcon(
3187 R.drawable.ic_dialog_browser_certificate_partially_secure)
3188 .setView(certificateView)
3189 .setPositiveButton(R.string.ok,
3190 new DialogInterface.OnClickListener() {
3191 public void onClick(DialogInterface dialog,
3192 int whichButton) {
3193 mSSLCertificateOnErrorDialog = null;
3194 mSSLCertificateOnErrorView = null;
3195 mSSLCertificateOnErrorHandler = null;
3196 mSSLCertificateOnErrorError = null;
3197
Grace Kloba22ac16e2009-10-07 18:00:23 -07003198 view.getWebViewClient().onReceivedSslError(
3199 view, handler, error);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003200 }
3201 })
3202 .setNeutralButton(R.string.page_info_view,
3203 new DialogInterface.OnClickListener() {
3204 public void onClick(DialogInterface dialog,
3205 int whichButton) {
3206 mSSLCertificateOnErrorDialog = null;
3207
3208 // do not clear the dialog state: we will
3209 // need to show the dialog again once the
3210 // user is done exploring the page-info details
3211
3212 showPageInfo(mTabControl.getTabFromView(view),
3213 true);
3214 }
3215 })
3216 .setOnCancelListener(
3217 new DialogInterface.OnCancelListener() {
3218 public void onCancel(DialogInterface dialog) {
3219 mSSLCertificateOnErrorDialog = null;
3220 mSSLCertificateOnErrorView = null;
3221 mSSLCertificateOnErrorHandler = null;
3222 mSSLCertificateOnErrorError = null;
3223
Grace Kloba22ac16e2009-10-07 18:00:23 -07003224 view.getWebViewClient().onReceivedSslError(
3225 view, handler, error);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003226 }
3227 })
3228 .show();
3229 }
3230
3231 /**
3232 * Inflates the SSL certificate view (helper method).
3233 * @param certificate The SSL certificate.
3234 * @return The resultant certificate view with issued-to, issued-by,
3235 * issued-on, expires-on, and possibly other fields set.
3236 * If the input certificate is null, returns null.
3237 */
3238 private View inflateCertificateView(SslCertificate certificate) {
3239 if (certificate == null) {
3240 return null;
3241 }
3242
3243 LayoutInflater factory = LayoutInflater.from(this);
3244
3245 View certificateView = factory.inflate(
3246 R.layout.ssl_certificate, null);
3247
3248 // issued to:
3249 SslCertificate.DName issuedTo = certificate.getIssuedTo();
3250 if (issuedTo != null) {
3251 ((TextView) certificateView.findViewById(R.id.to_common))
3252 .setText(issuedTo.getCName());
3253 ((TextView) certificateView.findViewById(R.id.to_org))
3254 .setText(issuedTo.getOName());
3255 ((TextView) certificateView.findViewById(R.id.to_org_unit))
3256 .setText(issuedTo.getUName());
3257 }
3258
3259 // issued by:
3260 SslCertificate.DName issuedBy = certificate.getIssuedBy();
3261 if (issuedBy != null) {
3262 ((TextView) certificateView.findViewById(R.id.by_common))
3263 .setText(issuedBy.getCName());
3264 ((TextView) certificateView.findViewById(R.id.by_org))
3265 .setText(issuedBy.getOName());
3266 ((TextView) certificateView.findViewById(R.id.by_org_unit))
3267 .setText(issuedBy.getUName());
3268 }
3269
3270 // issued on:
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003271 String issuedOn = formatCertificateDate(
3272 certificate.getValidNotBeforeDate());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003273 ((TextView) certificateView.findViewById(R.id.issued_on))
3274 .setText(issuedOn);
3275
3276 // expires on:
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003277 String expiresOn = formatCertificateDate(
3278 certificate.getValidNotAfterDate());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003279 ((TextView) certificateView.findViewById(R.id.expires_on))
3280 .setText(expiresOn);
3281
3282 return certificateView;
3283 }
3284
3285 /**
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003286 * Formats the certificate date to a properly localized date string.
The Android Open Source Project0c908882009-03-03 19:32:16 -08003287 * @return Properly localized version of the certificate date string and
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003288 * the "" if it fails to localize.
The Android Open Source Project0c908882009-03-03 19:32:16 -08003289 */
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003290 private String formatCertificateDate(Date certificateDate) {
3291 if (certificateDate == null) {
3292 return "";
The Android Open Source Project0c908882009-03-03 19:32:16 -08003293 }
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003294 String formattedDate = DateFormat.getDateFormat(this).format(certificateDate);
3295 if (formattedDate == null) {
3296 return "";
3297 }
3298 return formattedDate;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003299 }
3300
3301 /**
3302 * Displays an http-authentication dialog.
3303 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003304 void showHttpAuthentication(final HttpAuthHandler handler,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003305 final String host, final String realm, final String title,
3306 final String name, final String password, int focusId) {
3307 LayoutInflater factory = LayoutInflater.from(this);
3308 final View v = factory
3309 .inflate(R.layout.http_authentication, null);
3310 if (name != null) {
3311 ((EditText) v.findViewById(R.id.username_edit)).setText(name);
3312 }
3313 if (password != null) {
3314 ((EditText) v.findViewById(R.id.password_edit)).setText(password);
3315 }
3316
3317 String titleText = title;
3318 if (titleText == null) {
3319 titleText = getText(R.string.sign_in_to).toString().replace(
3320 "%s1", host).replace("%s2", realm);
3321 }
3322
3323 mHttpAuthHandler = handler;
3324 AlertDialog dialog = new AlertDialog.Builder(this)
3325 .setTitle(titleText)
3326 .setIcon(android.R.drawable.ic_dialog_alert)
3327 .setView(v)
3328 .setPositiveButton(R.string.action,
3329 new DialogInterface.OnClickListener() {
3330 public void onClick(DialogInterface dialog,
3331 int whichButton) {
3332 String nm = ((EditText) v
3333 .findViewById(R.id.username_edit))
3334 .getText().toString();
3335 String pw = ((EditText) v
3336 .findViewById(R.id.password_edit))
3337 .getText().toString();
3338 BrowserActivity.this.setHttpAuthUsernamePassword
3339 (host, realm, nm, pw);
3340 handler.proceed(nm, pw);
3341 mHttpAuthenticationDialog = null;
3342 mHttpAuthHandler = null;
3343 }})
3344 .setNegativeButton(R.string.cancel,
3345 new DialogInterface.OnClickListener() {
3346 public void onClick(DialogInterface dialog,
3347 int whichButton) {
3348 handler.cancel();
3349 BrowserActivity.this.resetTitleAndRevertLockIcon();
3350 mHttpAuthenticationDialog = null;
3351 mHttpAuthHandler = null;
3352 }})
3353 .setOnCancelListener(new DialogInterface.OnCancelListener() {
3354 public void onCancel(DialogInterface dialog) {
3355 handler.cancel();
3356 BrowserActivity.this.resetTitleAndRevertLockIcon();
3357 mHttpAuthenticationDialog = null;
3358 mHttpAuthHandler = null;
3359 }})
3360 .create();
3361 // Make the IME appear when the dialog is displayed if applicable.
3362 dialog.getWindow().setSoftInputMode(
3363 WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
3364 dialog.show();
3365 if (focusId != 0) {
3366 dialog.findViewById(focusId).requestFocus();
3367 } else {
3368 v.findViewById(R.id.username_edit).requestFocus();
3369 }
3370 mHttpAuthenticationDialog = dialog;
3371 }
3372
3373 public int getProgress() {
3374 WebView w = mTabControl.getCurrentWebView();
3375 if (w != null) {
3376 return w.getProgress();
3377 } else {
3378 return 100;
3379 }
3380 }
3381
3382 /**
3383 * Set HTTP authentication password.
3384 *
3385 * @param host The host for the password
3386 * @param realm The realm for the password
3387 * @param username The username for the password. If it is null, it means
3388 * password can't be saved.
3389 * @param password The password
3390 */
3391 public void setHttpAuthUsernamePassword(String host, String realm,
3392 String username,
3393 String password) {
3394 WebView w = mTabControl.getCurrentWebView();
3395 if (w != null) {
3396 w.setHttpAuthUsernamePassword(host, realm, username, password);
3397 }
3398 }
3399
3400 /**
3401 * connectivity manager says net has come or gone... inform the user
3402 * @param up true if net has come up, false if net has gone down
3403 */
3404 public void onNetworkToggle(boolean up) {
3405 if (up == mIsNetworkUp) {
3406 return;
3407 } else if (up) {
3408 mIsNetworkUp = true;
3409 if (mAlertDialog != null) {
3410 mAlertDialog.cancel();
3411 mAlertDialog = null;
3412 }
3413 } else {
3414 mIsNetworkUp = false;
Patrick Scotteb6ab2a2009-09-16 10:00:17 -04003415 if (mInLoad) {
3416 createAndShowNetworkDialog();
3417 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003418 }
3419 WebView w = mTabControl.getCurrentWebView();
3420 if (w != null) {
3421 w.setNetworkAvailable(up);
3422 }
3423 }
3424
Grace Kloba22ac16e2009-10-07 18:00:23 -07003425 boolean isNetworkUp() {
3426 return mIsNetworkUp;
3427 }
3428
Patrick Scotteb6ab2a2009-09-16 10:00:17 -04003429 // This method shows the network dialog alerting the user that the net is
3430 // down. It will only show the dialog if mAlertDialog is null.
3431 private void createAndShowNetworkDialog() {
3432 if (mAlertDialog == null) {
3433 mAlertDialog = new AlertDialog.Builder(this)
3434 .setTitle(R.string.loadSuspendedTitle)
3435 .setMessage(R.string.loadSuspended)
3436 .setPositiveButton(R.string.ok, null)
3437 .show();
3438 }
3439 }
3440
The Android Open Source Project0c908882009-03-03 19:32:16 -08003441 @Override
3442 protected void onActivityResult(int requestCode, int resultCode,
3443 Intent intent) {
Grace Klobabb394f32009-11-19 10:26:37 -08003444 if (getTopWindow() == null) return;
3445
The Android Open Source Project0c908882009-03-03 19:32:16 -08003446 switch (requestCode) {
3447 case COMBO_PAGE:
3448 if (resultCode == RESULT_OK && intent != null) {
3449 String data = intent.getAction();
3450 Bundle extras = intent.getExtras();
3451 if (extras != null && extras.getBoolean("new_window", false)) {
Leon Scroggins25d35472009-09-15 11:37:27 -04003452 openTab(data);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003453 } else {
Grace Kloba22ac16e2009-10-07 18:00:23 -07003454 final Tab currentTab =
The Android Open Source Project0c908882009-03-03 19:32:16 -08003455 mTabControl.getCurrentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04003456 dismissSubWindow(currentTab);
3457 if (data != null && data.length() != 0) {
Leon Scroggins92472e82010-02-17 16:32:28 -05003458 loadUrl(getTopWindow(), data);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003459 }
3460 }
3461 }
Leon Scrogginsfde97462010-01-11 13:06:21 -05003462 // Deliberately fall through to PREFERENCES_PAGE, since the
3463 // same extra may be attached to the COMBO_PAGE
3464 case PREFERENCES_PAGE:
3465 if (resultCode == RESULT_OK && intent != null) {
3466 String action = intent.getStringExtra(Intent.EXTRA_TEXT);
3467 if (BrowserSettings.PREF_CLEAR_HISTORY.equals(action)) {
3468 mTabControl.removeParentChildRelationShips();
3469 }
3470 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003471 break;
Leon Scroggins8d5fa432009-10-02 15:55:59 -04003472 // Choose a file from the file picker.
3473 case FILE_SELECTED:
3474 if (null == mUploadMessage) break;
3475 Uri result = intent == null || resultCode != RESULT_OK ? null
3476 : intent.getData();
3477 mUploadMessage.onReceiveValue(result);
3478 mUploadMessage = null;
3479 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003480 default:
3481 break;
3482 }
Leon Scroggins30444232009-09-04 18:36:20 -04003483 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003484 }
3485
3486 /*
3487 * This method is called as a result of the user selecting the options
Leon Scrogginsf08809b2010-01-21 09:27:46 -05003488 * menu to see the download window. It shows the download window on top of
3489 * the current window.
The Android Open Source Project0c908882009-03-03 19:32:16 -08003490 */
Leon Scrogginsf08809b2010-01-21 09:27:46 -05003491 private void viewDownloads(Uri downloadRecord) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003492 Intent intent = new Intent(this,
3493 BrowserDownloadPage.class);
3494 intent.setData(downloadRecord);
Grace Kloba22ac16e2009-10-07 18:00:23 -07003495 startActivityForResult(intent, BrowserActivity.DOWNLOAD_PAGE);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003496
3497 }
3498
Leon Scroggins160a7e72009-08-14 18:28:01 -04003499 /**
3500 * Open the Go page.
3501 * @param startWithHistory If true, open starting on the history tab.
3502 * Otherwise, start with the bookmarks tab.
Leon Scroggins160a7e72009-08-14 18:28:01 -04003503 */
Leon Scroggins30444232009-09-04 18:36:20 -04003504 /* package */ void bookmarksOrHistoryPicker(boolean startWithHistory) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003505 WebView current = mTabControl.getCurrentWebView();
3506 if (current == null) {
3507 return;
3508 }
3509 Intent intent = new Intent(this,
3510 CombinedBookmarkHistoryActivity.class);
3511 String title = current.getTitle();
3512 String url = current.getUrl();
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01003513 Bitmap thumbnail = createScreenshot(current);
3514
The Android Open Source Project0c908882009-03-03 19:32:16 -08003515 // Just in case the user opens bookmarks before a page finishes loading
3516 // so the current history item, and therefore the page, is null.
3517 if (null == url) {
3518 url = mLastEnteredUrl;
3519 // This can happen.
3520 if (null == url) {
3521 url = mSettings.getHomePage();
3522 }
3523 }
3524 // In case the web page has not yet received its associated title.
3525 if (title == null) {
3526 title = url;
3527 }
3528 intent.putExtra("title", title);
3529 intent.putExtra("url", url);
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01003530 intent.putExtra("thumbnail", thumbnail);
Leon Scroggins30444232009-09-04 18:36:20 -04003531 // Disable opening in a new window if we have maxed out the windows
Grace Kloba22ac16e2009-10-07 18:00:23 -07003532 intent.putExtra("disable_new_window", !mTabControl.canCreateNewTab());
Patrick Scott3918d442009-08-04 13:22:29 -04003533 intent.putExtra("touch_icon_url", current.getTouchIconUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003534 if (startWithHistory) {
3535 intent.putExtra(CombinedBookmarkHistoryActivity.STARTING_TAB,
3536 CombinedBookmarkHistoryActivity.HISTORY_TAB);
3537 }
3538 startActivityForResult(intent, COMBO_PAGE);
3539 }
3540
3541 // Called when loading from context menu or LOAD_URL message
Leon Scroggins92472e82010-02-17 16:32:28 -05003542 private void loadUrlFromContext(WebView view, String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003543 // In case the user enters nothing.
3544 if (url != null && url.length() != 0 && view != null) {
3545 url = smartUrlFilter(url);
Grace Kloba22ac16e2009-10-07 18:00:23 -07003546 if (!view.getWebViewClient().shouldOverrideUrlLoading(view, url)) {
Leon Scroggins92472e82010-02-17 16:32:28 -05003547 loadUrl(view, url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003548 }
3549 }
3550 }
3551
Leon Scroggins92472e82010-02-17 16:32:28 -05003552 /**
3553 * Load the URL into the given WebView and update the title bar
3554 * to reflect the new load. Call this instead of WebView.loadUrl
3555 * directly.
3556 * @param view The WebView used to load url.
3557 * @param url The URL to load.
3558 */
3559 private void loadUrl(WebView view, String url) {
3560 updateTitleBarForNewLoad(view, url);
3561 view.loadUrl(url);
3562 }
3563
3564 /**
3565 * Load UrlData into a Tab and update the title bar to reflect the new
3566 * load. Call this instead of UrlData.loadIn directly.
3567 * @param t The Tab used to load.
3568 * @param data The UrlData being loaded.
3569 */
3570 private void loadUrlDataIn(Tab t, UrlData data) {
3571 updateTitleBarForNewLoad(t.getWebView(), data.mUrl);
3572 data.loadIn(t);
3573 }
3574
3575 /**
3576 * If the WebView is the top window, update the title bar to reflect
3577 * loading the new URL. i.e. set its text, clear the favicon (which
3578 * will be set once the page begins loading), and set the progress to
3579 * INITIAL_PROGRESS to show that the page has begun to load. Called
3580 * by loadUrl and loadUrlDataIn.
3581 * @param view The WebView that is starting a load.
3582 * @param url The URL that is being loaded.
3583 */
3584 private void updateTitleBarForNewLoad(WebView view, String url) {
3585 if (view == getTopWindow()) {
3586 setUrlTitle(url, null);
3587 setFavicon(null);
3588 onProgressChanged(view, INITIAL_PROGRESS);
3589 }
3590 }
3591
The Android Open Source Project0c908882009-03-03 19:32:16 -08003592 private String smartUrlFilter(Uri inUri) {
3593 if (inUri != null) {
3594 return smartUrlFilter(inUri.toString());
3595 }
3596 return null;
3597 }
3598
Feng Qianb34f87a2009-03-24 21:27:26 -07003599 protected static final Pattern ACCEPTED_URI_SCHEMA = Pattern.compile(
The Android Open Source Project0c908882009-03-03 19:32:16 -08003600 "(?i)" + // switch on case insensitive matching
3601 "(" + // begin group for schema
3602 "(?:http|https|file):\\/\\/" +
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003603 "|(?:inline|data|about|content|javascript):" +
The Android Open Source Project0c908882009-03-03 19:32:16 -08003604 ")" +
3605 "(.*)" );
3606
3607 /**
3608 * Attempts to determine whether user input is a URL or search
3609 * terms. Anything with a space is passed to search.
3610 *
3611 * Converts to lowercase any mistakenly uppercased schema (i.e.,
3612 * "Http://" converts to "http://"
3613 *
3614 * @return Original or modified URL
3615 *
3616 */
3617 String smartUrlFilter(String url) {
3618
3619 String inUrl = url.trim();
3620 boolean hasSpace = inUrl.indexOf(' ') != -1;
3621
3622 Matcher matcher = ACCEPTED_URI_SCHEMA.matcher(inUrl);
3623 if (matcher.matches()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003624 // force scheme to lowercase
3625 String scheme = matcher.group(1);
3626 String lcScheme = scheme.toLowerCase();
3627 if (!lcScheme.equals(scheme)) {
Mitsuru Oshima123ecfb2009-05-18 19:11:14 -07003628 inUrl = lcScheme + matcher.group(2);
3629 }
3630 if (hasSpace) {
3631 inUrl = inUrl.replace(" ", "%20");
The Android Open Source Project0c908882009-03-03 19:32:16 -08003632 }
3633 return inUrl;
3634 }
3635 if (hasSpace) {
Satish Sampath565505b2009-05-29 15:37:27 +01003636 // FIXME: Is this the correct place to add to searches?
3637 // what if someone else calls this function?
3638 int shortcut = parseUrlShortcut(inUrl);
3639 if (shortcut != SHORTCUT_INVALID) {
3640 Browser.addSearchUrl(mResolver, inUrl);
3641 String query = inUrl.substring(2);
3642 switch (shortcut) {
3643 case SHORTCUT_GOOGLE_SEARCH:
Grace Kloba47fdfdb2009-06-30 11:15:34 -07003644 return URLUtil.composeSearchUrl(query, QuickSearch_G, QUERY_PLACE_HOLDER);
Satish Sampath565505b2009-05-29 15:37:27 +01003645 case SHORTCUT_WIKIPEDIA_SEARCH:
3646 return URLUtil.composeSearchUrl(query, QuickSearch_W, QUERY_PLACE_HOLDER);
3647 case SHORTCUT_DICTIONARY_SEARCH:
3648 return URLUtil.composeSearchUrl(query, QuickSearch_D, QUERY_PLACE_HOLDER);
3649 case SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH:
The Android Open Source Project0c908882009-03-03 19:32:16 -08003650 // FIXME: we need location in this case
Satish Sampath565505b2009-05-29 15:37:27 +01003651 return URLUtil.composeSearchUrl(query, QuickSearch_L, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003652 }
3653 }
3654 } else {
Dan Egnor5ee906c2009-11-18 12:11:49 -08003655 if (Patterns.WEB_URL.matcher(inUrl).matches()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003656 return URLUtil.guessUrl(inUrl);
3657 }
3658 }
3659
3660 Browser.addSearchUrl(mResolver, inUrl);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07003661 return URLUtil.composeSearchUrl(inUrl, QuickSearch_G, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003662 }
3663
Ben Murdochbff2d602009-07-01 20:19:05 +01003664 /* package */ void setShouldShowErrorConsole(boolean flag) {
3665 if (flag == mShouldShowErrorConsole) {
3666 // Nothing to do.
3667 return;
3668 }
3669
3670 mShouldShowErrorConsole = flag;
3671
Grace Kloba22ac16e2009-10-07 18:00:23 -07003672 ErrorConsoleView errorConsole = mTabControl.getCurrentTab()
3673 .getErrorConsole(true);
Ben Murdochbff2d602009-07-01 20:19:05 +01003674
3675 if (flag) {
3676 // Setting the show state of the console will cause it's the layout to be inflated.
3677 if (errorConsole.numberOfErrors() > 0) {
3678 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
3679 } else {
3680 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
3681 }
3682
3683 // Now we can add it to the main view.
3684 mErrorConsoleContainer.addView(errorConsole,
Romain Guy15b8ec62010-01-08 15:06:43 -08003685 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
Ben Murdochbff2d602009-07-01 20:19:05 +01003686 ViewGroup.LayoutParams.WRAP_CONTENT));
3687 } else {
3688 mErrorConsoleContainer.removeView(errorConsole);
3689 }
3690
3691 }
3692
Grace Kloba22ac16e2009-10-07 18:00:23 -07003693 boolean shouldShowErrorConsole() {
3694 return mShouldShowErrorConsole;
3695 }
3696
Andrei Popescu163ab742009-10-20 17:58:23 +01003697 private void setStatusBarVisibility(boolean visible) {
3698 int flag = visible ? 0 : WindowManager.LayoutParams.FLAG_FULLSCREEN;
3699 getWindow().setFlags(flag, WindowManager.LayoutParams.FLAG_FULLSCREEN);
3700 }
3701
Andrei Popescu56199cc2010-01-12 22:39:16 +00003702
3703 private void sendNetworkType(String type, String subtype) {
3704 WebView w = mTabControl.getCurrentWebView();
3705 if (w != null) {
3706 w.setNetworkType(type, subtype);
3707 }
3708 }
3709
Andrei Popescu30995e72010-02-09 16:59:58 +00003710 private void packageChanged(String packageName, boolean wasAdded) {
3711 WebView w = mTabControl.getCurrentWebView();
3712 if (w == null) {
3713 return;
3714 }
3715
3716 if (wasAdded) {
3717 w.addPackageName(packageName);
3718 } else {
3719 w.removePackageName(packageName);
3720 }
3721 }
3722
3723 private void addPackageNames(Set<String> packageNames) {
3724 WebView w = mTabControl.getCurrentWebView();
3725 if (w == null) {
3726 return;
3727 }
3728
3729 w.addPackageNames(packageNames);
3730 }
3731
3732 private void getInstalledPackages() {
3733 AsyncTask<Void, Void, Set<String> > task =
3734 new AsyncTask<Void, Void, Set<String> >() {
3735 protected Set<String> doInBackground(Void... unused) {
3736 Set<String> installedPackages = new HashSet<String>();
3737 PackageManager pm = BrowserActivity.this.getPackageManager();
3738 if (pm != null) {
3739 List<PackageInfo> packages = pm.getInstalledPackages(0);
3740 for (PackageInfo p : packages) {
3741 if (BrowserActivity.this.sGoogleApps.contains(p.packageName)) {
3742 installedPackages.add(p.packageName);
3743 }
3744 }
3745 }
3746
3747 return installedPackages;
3748 }
3749
3750 // Executes on the UI thread
3751 protected void onPostExecute(Set<String> installedPackages) {
3752 addPackageNames(installedPackages);
3753 }
3754 };
3755 task.execute();
3756 }
3757
Grace Klobaeb6eef42009-09-15 17:56:32 -07003758 final static int LOCK_ICON_UNSECURE = 0;
3759 final static int LOCK_ICON_SECURE = 1;
3760 final static int LOCK_ICON_MIXED = 2;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003761
The Android Open Source Project0c908882009-03-03 19:32:16 -08003762 private BrowserSettings mSettings;
3763 private TabControl mTabControl;
3764 private ContentResolver mResolver;
3765 private FrameLayout mContentView;
Andrei Popescuadc008d2009-06-26 14:11:30 +01003766 private View mCustomView;
3767 private FrameLayout mCustomViewContainer;
Andrei Popescuc9b55562009-07-07 10:51:15 +01003768 private WebChromeClient.CustomViewCallback mCustomViewCallback;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003769
3770 // FIXME, temp address onPrepareMenu performance problem. When we move everything out of
3771 // view, we should rewrite this.
3772 private int mCurrentMenuState = 0;
3773 private int mMenuState = R.id.MAIN_MENU;
Andrei Popescuadc008d2009-06-26 14:11:30 +01003774 private int mOldMenuState = EMPTY_MENU;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003775 private static final int EMPTY_MENU = -1;
3776 private Menu mMenu;
3777
3778 private FindDialog mFindDialog;
3779 // Used to prevent chording to result in firing two shortcuts immediately
3780 // one after another. Fixes bug 1211714.
3781 boolean mCanChord;
3782
3783 private boolean mInLoad;
3784 private boolean mIsNetworkUp;
Ben Murdochb7cc8b42009-09-28 10:59:09 +01003785 private boolean mDidStopLoad;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003786
The Android Open Source Project0c908882009-03-03 19:32:16 -08003787 private boolean mActivityInPause = true;
3788
3789 private boolean mMenuIsDown;
3790
The Android Open Source Project0c908882009-03-03 19:32:16 -08003791 private static boolean mInTrace;
3792
3793 // Performance probe
3794 private static final int[] SYSTEM_CPU_FORMAT = new int[] {
3795 Process.PROC_SPACE_TERM | Process.PROC_COMBINE,
3796 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 1: user time
3797 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 2: nice time
3798 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 3: sys time
3799 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 4: idle time
3800 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 5: iowait time
3801 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 6: irq time
3802 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG // 7: softirq time
3803 };
3804
3805 private long mStart;
3806 private long mProcessStart;
3807 private long mUserStart;
3808 private long mSystemStart;
3809 private long mIdleStart;
3810 private long mIrqStart;
3811
3812 private long mUiStart;
3813
3814 private Drawable mMixLockIcon;
3815 private Drawable mSecLockIcon;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003816
3817 /* hold a ref so we can auto-cancel if necessary */
3818 private AlertDialog mAlertDialog;
3819
The Android Open Source Project0c908882009-03-03 19:32:16 -08003820 // The up-to-date URL and title (these can be different from those stored
3821 // in WebView, since it takes some time for the information in WebView to
3822 // get updated)
3823 private String mUrl;
3824 private String mTitle;
3825
3826 // As PageInfo has different style for landscape / portrait, we have
3827 // to re-open it when configuration changed
3828 private AlertDialog mPageInfoDialog;
Grace Kloba22ac16e2009-10-07 18:00:23 -07003829 private Tab mPageInfoView;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003830 // If the Page-Info dialog is launched from the SSL-certificate-on-error
3831 // dialog, we should not just dismiss it, but should get back to the
3832 // SSL-certificate-on-error dialog. This flag is used to store this state
Leon Scrogginsc7b92f82010-01-11 18:17:31 -05003833 private boolean mPageInfoFromShowSSLCertificateOnError;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003834
3835 // as SSLCertificateOnError has different style for landscape / portrait,
3836 // we have to re-open it when configuration changed
3837 private AlertDialog mSSLCertificateOnErrorDialog;
3838 private WebView mSSLCertificateOnErrorView;
3839 private SslErrorHandler mSSLCertificateOnErrorHandler;
3840 private SslError mSSLCertificateOnErrorError;
3841
3842 // as SSLCertificate has different style for landscape / portrait, we
3843 // have to re-open it when configuration changed
3844 private AlertDialog mSSLCertificateDialog;
Grace Kloba22ac16e2009-10-07 18:00:23 -07003845 private Tab mSSLCertificateView;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003846
3847 // as HttpAuthentication has different style for landscape / portrait, we
3848 // have to re-open it when configuration changed
3849 private AlertDialog mHttpAuthenticationDialog;
3850 private HttpAuthHandler mHttpAuthHandler;
3851
3852 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_PARAMS =
3853 new FrameLayout.LayoutParams(
Romain Guy15b8ec62010-01-08 15:06:43 -08003854 ViewGroup.LayoutParams.MATCH_PARENT,
3855 ViewGroup.LayoutParams.MATCH_PARENT);
Andrei Popescuadc008d2009-06-26 14:11:30 +01003856 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_GRAVITY_CENTER =
3857 new FrameLayout.LayoutParams(
Romain Guy15b8ec62010-01-08 15:06:43 -08003858 ViewGroup.LayoutParams.MATCH_PARENT,
3859 ViewGroup.LayoutParams.MATCH_PARENT,
Andrei Popescuadc008d2009-06-26 14:11:30 +01003860 Gravity.CENTER);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07003861 // Google search
3862 final static String QuickSearch_G = "http://www.google.com/m?q=%s";
The Android Open Source Project0c908882009-03-03 19:32:16 -08003863 // Wikipedia search
3864 final static String QuickSearch_W = "http://en.wikipedia.org/w/index.php?search=%s&go=Go";
3865 // Dictionary search
3866 final static String QuickSearch_D = "http://dictionary.reference.com/search?q=%s";
3867 // Google Mobile Local search
3868 final static String QuickSearch_L = "http://www.google.com/m/search?site=local&q=%s&near=mountain+view";
3869
3870 final static String QUERY_PLACE_HOLDER = "%s";
3871
3872 // "source" parameter for Google search through search key
3873 final static String GOOGLE_SEARCH_SOURCE_SEARCHKEY = "browser-key";
3874 // "source" parameter for Google search through goto menu
3875 final static String GOOGLE_SEARCH_SOURCE_GOTO = "browser-goto";
3876 // "source" parameter for Google search through simplily type
3877 final static String GOOGLE_SEARCH_SOURCE_TYPE = "browser-type";
3878 // "source" parameter for Google search suggested by the browser
3879 final static String GOOGLE_SEARCH_SOURCE_SUGGEST = "browser-suggest";
3880 // "source" parameter for Google search from unknown source
3881 final static String GOOGLE_SEARCH_SOURCE_UNKNOWN = "unknown";
3882
3883 private final static String LOGTAG = "browser";
3884
The Android Open Source Project0c908882009-03-03 19:32:16 -08003885 private String mLastEnteredUrl;
3886
3887 private PowerManager.WakeLock mWakeLock;
3888 private final static int WAKELOCK_TIMEOUT = 5 * 60 * 1000; // 5 minutes
3889
3890 private Toast mStopToast;
3891
Leon Scroggins68579392009-09-15 15:31:54 -04003892 private TitleBar mTitleBar;
Leon Scroggins81db3662009-06-04 17:45:11 -04003893
Ben Murdochbff2d602009-07-01 20:19:05 +01003894 private LinearLayout mErrorConsoleContainer = null;
3895 private boolean mShouldShowErrorConsole = false;
3896
The Android Open Source Project0c908882009-03-03 19:32:16 -08003897 // As the ids are dynamically created, we can't guarantee that they will
3898 // be in sequence, so this static array maps ids to a window number.
3899 final static private int[] WINDOW_SHORTCUT_ID_ARRAY =
3900 { R.id.window_one_menu_id, R.id.window_two_menu_id, R.id.window_three_menu_id,
3901 R.id.window_four_menu_id, R.id.window_five_menu_id, R.id.window_six_menu_id,
3902 R.id.window_seven_menu_id, R.id.window_eight_menu_id };
3903
3904 // monitor platform changes
3905 private IntentFilter mNetworkStateChangedFilter;
3906 private BroadcastReceiver mNetworkStateIntentReceiver;
3907
Grace Klobab4da0ad2009-05-14 14:45:40 -07003908 private BroadcastReceiver mPackageInstallationReceiver;
3909
The Android Open Source Project0c908882009-03-03 19:32:16 -08003910 // activity requestCode
Nicolas Roard78a98e42009-05-11 13:34:17 +01003911 final static int COMBO_PAGE = 1;
3912 final static int DOWNLOAD_PAGE = 2;
3913 final static int PREFERENCES_PAGE = 3;
Leon Scroggins8d5fa432009-10-02 15:55:59 -04003914 final static int FILE_SELECTED = 4;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003915
Andrei Popescu540035d2009-09-18 18:59:20 +01003916 // the default <video> poster
3917 private Bitmap mDefaultVideoPoster;
3918 // the video progress view
3919 private View mVideoProgressView;
3920
Andrei Popescu30995e72010-02-09 16:59:58 +00003921 // The Google packages we monitor for the navigator.isApplicationInstalled()
3922 // API. Add as needed.
3923 private static Set<String> sGoogleApps;
3924 static {
3925 sGoogleApps = new HashSet<String>();
3926 sGoogleApps.add("com.google.android.youtube");
3927 }
3928
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003929 /**
3930 * A UrlData class to abstract how the content will be set to WebView.
3931 * This base class uses loadUrl to show the content.
3932 */
Leon Scroggins6eac63e2010-03-15 18:19:14 -04003933 /* package */ static class UrlData {
Grace Kloba068e48b2010-01-26 18:11:27 -08003934 final String mUrl;
3935 final Map<String, String> mHeaders;
Leon Scroggins58d56c62010-01-28 15:12:40 -05003936 final Intent mVoiceIntent;
Grace Kloba60e095c2009-06-16 11:50:55 -07003937
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003938 UrlData(String url) {
3939 this.mUrl = url;
Grace Kloba068e48b2010-01-26 18:11:27 -08003940 this.mHeaders = null;
Leon Scroggins58d56c62010-01-28 15:12:40 -05003941 this.mVoiceIntent = null;
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003942 }
Grace Kloba60e095c2009-06-16 11:50:55 -07003943
Leon Scroggins58d56c62010-01-28 15:12:40 -05003944 UrlData(String url, Map<String, String> headers, Intent intent) {
Grace Kloba068e48b2010-01-26 18:11:27 -08003945 this.mUrl = url;
3946 this.mHeaders = headers;
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -05003947 if (RecognizerResultsIntent.ACTION_VOICE_SEARCH_RESULTS
3948 .equals(intent.getAction())) {
Leon Scroggins58d56c62010-01-28 15:12:40 -05003949 this.mVoiceIntent = intent;
3950 } else {
3951 this.mVoiceIntent = null;
3952 }
Grace Kloba60e095c2009-06-16 11:50:55 -07003953 }
3954
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003955 boolean isEmpty() {
Leon Scroggins58d56c62010-01-28 15:12:40 -05003956 return mVoiceIntent == null && (mUrl == null || mUrl.length() == 0);
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003957 }
3958
Leon Scroggins92472e82010-02-17 16:32:28 -05003959 /**
3960 * Load this UrlData into the given Tab. Use loadUrlDataIn to update
3961 * the title bar as well.
3962 */
Leon Scroggins58d56c62010-01-28 15:12:40 -05003963 public void loadIn(Tab t) {
3964 if (mVoiceIntent != null) {
3965 t.activateVoiceSearchMode(mVoiceIntent);
3966 } else {
3967 t.getWebView().loadUrl(mUrl, mHeaders);
3968 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003969 }
3970 };
3971
Leon Scroggins1f005d32009-08-10 17:36:42 -04003972 /* package */ static final UrlData EMPTY_URL_DATA = new UrlData(null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003973}