blob: 2012f61a15d10a45b741ea4969470bb3882c38a2 [file] [log] [blame]
The Android Open Source Project0c908882009-03-03 19:32:16 -08001/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.browser;
18
The Android Open Source Project0c908882009-03-03 19:32:16 -080019import android.app.Activity;
The Android Open Source Project0c908882009-03-03 19:32:16 -080020import android.app.AlertDialog;
21import android.app.ProgressDialog;
22import android.app.SearchManager;
23import android.content.ActivityNotFoundException;
24import android.content.BroadcastReceiver;
25import android.content.ComponentName;
Leon Scroggins58d56c62010-01-28 15:12:40 -050026import android.content.ContentProvider;
27import android.content.ContentProviderClient;
The Android Open Source Project0c908882009-03-03 19:32:16 -080028import android.content.ContentResolver;
Leon Scrogginsb6b7f9e2009-06-18 12:05:28 -040029import android.content.ContentUris;
The Android Open Source Project0c908882009-03-03 19:32:16 -080030import android.content.ContentValues;
31import android.content.Context;
32import android.content.DialogInterface;
33import android.content.Intent;
34import android.content.IntentFilter;
Grace Klobab4da0ad2009-05-14 14:45:40 -070035import android.content.pm.PackageInfo;
The Android Open Source Project0c908882009-03-03 19:32:16 -080036import android.content.pm.PackageManager;
37import android.content.pm.ResolveInfo;
The Android Open Source Project0c908882009-03-03 19:32:16 -080038import android.content.res.Configuration;
39import android.content.res.Resources;
40import android.database.Cursor;
Leon Scroggins96afcb12009-12-10 12:35:56 -050041import android.database.DatabaseUtils;
The Android Open Source Project0c908882009-03-03 19:32:16 -080042import android.graphics.Bitmap;
Andrei Popescu540035d2009-09-18 18:59:20 +010043import android.graphics.BitmapFactory;
The Android Open Source Project0c908882009-03-03 19:32:16 -080044import android.graphics.Canvas;
The Android Open Source Project0c908882009-03-03 19:32:16 -080045import android.graphics.Picture;
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -040046import android.graphics.PixelFormat;
47import android.graphics.Rect;
The Android Open Source Project0c908882009-03-03 19:32:16 -080048import android.graphics.drawable.Drawable;
The Android Open Source Project0c908882009-03-03 19:32:16 -080049import android.net.ConnectivityManager;
Andrei Popescu56199cc2010-01-12 22:39:16 +000050import android.net.NetworkInfo;
The Android Open Source Project0c908882009-03-03 19:32:16 -080051import android.net.Uri;
52import android.net.WebAddress;
The Android Open Source Project0c908882009-03-03 19:32:16 -080053import android.net.http.SslCertificate;
54import android.net.http.SslError;
55import android.os.AsyncTask;
56import android.os.Bundle;
57import android.os.Debug;
58import android.os.Environment;
59import android.os.Handler;
The Android Open Source Project0c908882009-03-03 19:32:16 -080060import android.os.Message;
61import android.os.PowerManager;
62import android.os.Process;
The Android Open Source Project0c908882009-03-03 19:32:16 -080063import android.os.ServiceManager;
64import android.os.SystemClock;
The Android Open Source Project0c908882009-03-03 19:32:16 -080065import android.provider.Browser;
Cary Clark5e335a32009-09-22 14:53:11 -040066import android.provider.ContactsContract;
67import android.provider.ContactsContract.Intents.Insert;
The Android Open Source Project0c908882009-03-03 19:32:16 -080068import android.provider.Downloads;
69import android.provider.MediaStore;
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -050070import android.speech.RecognizerResultsIntent;
The Android Open Source Project0c908882009-03-03 19:32:16 -080071import android.text.IClipboard;
72import android.text.TextUtils;
73import android.text.format.DateFormat;
Leon Scrogginsb94bf272009-09-25 15:22:08 -040074import android.util.AttributeSet;
The Android Open Source Project0c908882009-03-03 19:32:16 -080075import android.util.Log;
Dianne Hackborn385effd2010-02-24 20:03:04 -080076import android.util.Patterns;
The Android Open Source Project0c908882009-03-03 19:32:16 -080077import android.view.ContextMenu;
78import android.view.Gravity;
79import android.view.KeyEvent;
80import android.view.LayoutInflater;
81import android.view.Menu;
82import android.view.MenuInflater;
83import android.view.MenuItem;
84import android.view.View;
85import android.view.ViewGroup;
86import android.view.Window;
87import android.view.WindowManager;
88import android.view.ContextMenu.ContextMenuInfo;
89import android.view.MenuItem.OnMenuItemClickListener;
The Android Open Source Project0c908882009-03-03 19:32:16 -080090import android.webkit.CookieManager;
91import android.webkit.CookieSyncManager;
92import android.webkit.DownloadListener;
93import android.webkit.HttpAuthHandler;
Grace Klobab4da0ad2009-05-14 14:45:40 -070094import android.webkit.PluginManager;
The Android Open Source Project0c908882009-03-03 19:32:16 -080095import android.webkit.SslErrorHandler;
96import android.webkit.URLUtil;
Leon Clarkecb6cc862009-09-29 18:35:13 +010097import android.webkit.ValueCallback;
The Android Open Source Project0c908882009-03-03 19:32:16 -080098import android.webkit.WebChromeClient;
99import android.webkit.WebHistoryItem;
100import android.webkit.WebIconDatabase;
101import android.webkit.WebView;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800102import android.widget.EditText;
103import android.widget.FrameLayout;
104import android.widget.LinearLayout;
105import android.widget.TextView;
106import android.widget.Toast;
Fred Quintana752b6562009-12-18 10:18:26 -0800107import android.accounts.Account;
108import android.accounts.AccountManager;
109import android.accounts.AccountManagerFuture;
110import android.accounts.AuthenticatorException;
111import android.accounts.OperationCanceledException;
112import android.accounts.AccountManagerCallback;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800113
Bjorn Bringert10d1cca2010-02-10 14:22:12 +0000114import com.android.common.Search;
Leon Scroggins1fe13a52010-02-09 15:31:26 -0500115import com.android.common.speech.LoggingEvents;
Dan Egnor5ee906c2009-11-18 12:11:49 -0800116
Leon Scrogginsb6b7f9e2009-06-18 12:05:28 -0400117import java.io.ByteArrayOutputStream;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800118import java.io.File;
Ben Murdoch4f75ba22009-10-27 11:48:28 +0000119import java.io.IOException;
120import java.io.InputStream;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800121import java.net.MalformedURLException;
122import java.net.URI;
Dianne Hackborn99189432009-06-17 18:06:18 -0700123import java.net.URISyntaxException;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800124import java.net.URL;
125import java.net.URLEncoder;
126import java.text.ParseException;
127import java.util.Date;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800128import java.util.HashMap;
Andrei Popescu30995e72010-02-09 16:59:58 +0000129import java.util.HashSet;
Grace Kloba00f54c52010-01-27 14:53:51 -0800130import java.util.Iterator;
Andrei Popescu30995e72010-02-09 16:59:58 +0000131import java.util.List;
Grace Kloba068e48b2010-01-26 18:11:27 -0800132import java.util.Map;
Andrei Popescu30995e72010-02-09 16:59:58 +0000133import java.util.Set;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800134import java.util.regex.Matcher;
135import java.util.regex.Pattern;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800136
137public class BrowserActivity extends Activity
Shimeng (Simon) Wang98d5fce2010-03-16 13:23:39 -0700138 implements View.OnCreateContextMenuListener, DownloadListener {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800139
Dave Bort31a6d1c2009-04-13 15:56:49 -0700140 /* Define some aliases to make these debugging flags easier to refer to.
141 * This file imports android.provider.Browser, so we can't just refer to "Browser.DEBUG".
142 */
143 private final static boolean DEBUG = com.android.browser.Browser.DEBUG;
144 private final static boolean LOGV_ENABLED = com.android.browser.Browser.LOGV_ENABLED;
145 private final static boolean LOGD_ENABLED = com.android.browser.Browser.LOGD_ENABLED;
146
Satish Sampath565505b2009-05-29 15:37:27 +0100147 // These are single-character shortcuts for searching popular sources.
148 private static final int SHORTCUT_INVALID = 0;
149 private static final int SHORTCUT_GOOGLE_SEARCH = 1;
150 private static final int SHORTCUT_WIKIPEDIA_SEARCH = 2;
151 private static final int SHORTCUT_DICTIONARY_SEARCH = 3;
152 private static final int SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH = 4;
153
Cary Clarka9771242009-08-11 16:42:26 -0400154 private static class ClearThumbnails extends AsyncTask<File, Void, Void> {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800155 @Override
156 public Void doInBackground(File... files) {
157 if (files != null) {
158 for (File f : files) {
Cary Clarkd6be1752009-08-12 12:56:42 -0400159 if (!f.delete()) {
160 Log.e(LOGTAG, f.getPath() + " was not deleted");
161 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800162 }
163 }
164 return null;
165 }
166 }
167
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400168 /**
169 * This layout holds everything you see below the status bar, including the
170 * error console, the custom view container, and the webviews.
171 */
172 private FrameLayout mBrowserFrameLayout;
Leon Scroggins81db3662009-06-04 17:45:11 -0400173
Grace Kloba22ac16e2009-10-07 18:00:23 -0700174 @Override
175 public void onCreate(Bundle icicle) {
Dave Bort31a6d1c2009-04-13 15:56:49 -0700176 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800177 Log.v(LOGTAG, this + " onStart");
178 }
179 super.onCreate(icicle);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800180 // test the browser in OpenGL
181 // requestWindowFeature(Window.FEATURE_OPENGL);
182
Mike Reedd334bf52010-01-26 15:21:44 -0500183 // enable this to test the browser in 32bit
184 if (false) {
185 getWindow().setFormat(PixelFormat.RGBX_8888);
186 BitmapFactory.setDefaultConfig(Bitmap.Config.ARGB_8888);
187 }
188
The Android Open Source Project0c908882009-03-03 19:32:16 -0800189 setDefaultKeyMode(DEFAULT_KEYS_SEARCH_LOCAL);
190
191 mResolver = getContentResolver();
192
Grace Kloba0923d692009-09-23 21:37:25 -0700193 // If this was a web search request, pass it on to the default web
194 // search provider and finish this activity.
195 if (handleWebSearchIntent(getIntent())) {
196 finish();
197 return;
198 }
199
The Android Open Source Project0c908882009-03-03 19:32:16 -0800200 mSecLockIcon = Resources.getSystem().getDrawable(
201 android.R.drawable.ic_secure);
202 mMixLockIcon = Resources.getSystem().getDrawable(
203 android.R.drawable.ic_partial_secure);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800204
Leon Scroggins81db3662009-06-04 17:45:11 -0400205 FrameLayout frameLayout = (FrameLayout) getWindow().getDecorView()
206 .findViewById(com.android.internal.R.id.content);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400207 mBrowserFrameLayout = (FrameLayout) LayoutInflater.from(this)
208 .inflate(R.layout.custom_screen, null);
209 mContentView = (FrameLayout) mBrowserFrameLayout.findViewById(
210 R.id.main_content);
211 mErrorConsoleContainer = (LinearLayout) mBrowserFrameLayout
212 .findViewById(R.id.error_console);
213 mCustomViewContainer = (FrameLayout) mBrowserFrameLayout
214 .findViewById(R.id.fullscreen_custom_content);
215 frameLayout.addView(mBrowserFrameLayout, COVER_SCREEN_PARAMS);
Leon Scroggins68579392009-09-15 15:31:54 -0400216 mTitleBar = new TitleBar(this);
Grace Kloba1542f742010-03-17 21:11:15 -0700217 // mTitleBar will be always shown in the fully loaded mode
218 mTitleBar.setProgress(100);
Leon Scrogginsfe87bd32009-10-06 10:10:00 -0400219 mFakeTitleBar = new TitleBar(this);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800220
221 // Create the tab control and our initial tab
222 mTabControl = new TabControl(this);
223
224 // Open the icon database and retain all the bookmark urls for favicons
225 retainIconsOnStartup();
226
227 // Keep a settings instance handy.
228 mSettings = BrowserSettings.getInstance();
229 mSettings.setTabControl(mTabControl);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800230
231 PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
232 mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Browser");
233
Patrick Scott6adacc92010-03-05 08:24:51 -0500234 // Find out if the network is currently up.
235 ConnectivityManager cm = (ConnectivityManager) getSystemService(
236 Context.CONNECTIVITY_SERVICE);
237 NetworkInfo info = cm.getActiveNetworkInfo();
238 if (info != null) {
239 mIsNetworkUp = info.isAvailable();
240 }
241
Grace Klobaa34f6862009-07-31 16:28:17 -0700242 /* enables registration for changes in network status from
243 http stack */
244 mNetworkStateChangedFilter = new IntentFilter();
245 mNetworkStateChangedFilter.addAction(
246 ConnectivityManager.CONNECTIVITY_ACTION);
247 mNetworkStateIntentReceiver = new BroadcastReceiver() {
248 @Override
249 public void onReceive(Context context, Intent intent) {
250 if (intent.getAction().equals(
251 ConnectivityManager.CONNECTIVITY_ACTION)) {
Andrei Popescue4c98462010-02-19 15:44:13 +0000252
253 NetworkInfo info = intent.getParcelableExtra(
254 ConnectivityManager.EXTRA_NETWORK_INFO);
255 String typeName = info.getTypeName();
256 String subtypeName = info.getSubtypeName();
257 sendNetworkType(typeName.toLowerCase(),
258 (subtypeName != null ? subtypeName.toLowerCase() : ""));
259
260 onNetworkToggle(info.isAvailable());
Grace Klobaa34f6862009-07-31 16:28:17 -0700261 }
262 }
263 };
264
Grace Kloba615c6c92009-08-03 10:22:44 -0700265 IntentFilter filter = new IntentFilter(Intent.ACTION_PACKAGE_ADDED);
266 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
267 filter.addDataScheme("package");
268 mPackageInstallationReceiver = new BroadcastReceiver() {
269 @Override
270 public void onReceive(Context context, Intent intent) {
271 final String action = intent.getAction();
272 final String packageName = intent.getData()
273 .getSchemeSpecificPart();
274 final boolean replacing = intent.getBooleanExtra(
275 Intent.EXTRA_REPLACING, false);
276 if (Intent.ACTION_PACKAGE_REMOVED.equals(action) && replacing) {
277 // if it is replacing, refreshPlugins() when adding
278 return;
279 }
Andrei Popescu30995e72010-02-09 16:59:58 +0000280
281 if (sGoogleApps.contains(packageName)) {
282 BrowserActivity.this.packageChanged(packageName,
283 Intent.ACTION_PACKAGE_ADDED.equals(action));
284 }
285
Grace Kloba615c6c92009-08-03 10:22:44 -0700286 PackageManager pm = BrowserActivity.this.getPackageManager();
287 PackageInfo pkgInfo = null;
288 try {
289 pkgInfo = pm.getPackageInfo(packageName,
290 PackageManager.GET_PERMISSIONS);
291 } catch (PackageManager.NameNotFoundException e) {
292 return;
293 }
294 if (pkgInfo != null) {
295 String permissions[] = pkgInfo.requestedPermissions;
296 if (permissions == null) {
297 return;
298 }
299 boolean permissionOk = false;
300 for (String permit : permissions) {
301 if (PluginManager.PLUGIN_PERMISSION.equals(permit)) {
302 permissionOk = true;
303 break;
304 }
305 }
306 if (permissionOk) {
307 PluginManager.getInstance(BrowserActivity.this)
308 .refreshPlugins(
309 Intent.ACTION_PACKAGE_ADDED
310 .equals(action));
311 }
312 }
313 }
314 };
315 registerReceiver(mPackageInstallationReceiver, filter);
316
The Android Open Source Project0c908882009-03-03 19:32:16 -0800317 if (!mTabControl.restoreState(icicle)) {
318 // clear up the thumbnail directory if we can't restore the state as
319 // none of the files in the directory are referenced any more.
320 new ClearThumbnails().execute(
321 mTabControl.getThumbnailDir().listFiles());
Grace Klobaaab3f092009-07-30 12:29:51 -0700322 // there is no quit on Android. But if we can't restore the state,
323 // we can treat it as a new Browser, remove the old session cookies.
324 CookieManager.getInstance().removeSessionCookie();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800325 final Intent intent = getIntent();
326 final Bundle extra = intent.getExtras();
327 // Create an initial tab.
328 // If the intent is ACTION_VIEW and data is not null, the Browser is
329 // invoked to view the content by another application. In this case,
330 // the tab will be close when exit.
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700331 UrlData urlData = getUrlDataFromIntent(intent);
332
Leon Scroggins58d56c62010-01-28 15:12:40 -0500333 String action = intent.getAction();
Grace Kloba22ac16e2009-10-07 18:00:23 -0700334 final Tab t = mTabControl.createNewTab(
Leon Scroggins58d56c62010-01-28 15:12:40 -0500335 (Intent.ACTION_VIEW.equals(action) &&
336 intent.getData() != null)
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -0500337 || RecognizerResultsIntent.ACTION_VOICE_SEARCH_RESULTS
338 .equals(action),
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700339 intent.getStringExtra(Browser.EXTRA_APPLICATION_ID), urlData.mUrl);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800340 mTabControl.setCurrentTab(t);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800341 attachTabToContentView(t);
342 WebView webView = t.getWebView();
343 if (extra != null) {
344 int scale = extra.getInt(Browser.INITIAL_ZOOM_LEVEL, 0);
345 if (scale > 0 && scale <= 1000) {
346 webView.setInitialScale(scale);
347 }
348 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800349
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700350 if (urlData.isEmpty()) {
Shimeng (Simon) Wang98d5fce2010-03-16 13:23:39 -0700351 loadUrl(webView, mSettings.getHomePage());
The Android Open Source Project0c908882009-03-03 19:32:16 -0800352 } else {
Patrick Scott9d53da02010-02-19 10:19:01 -0500353 loadUrlDataIn(t, urlData);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800354 }
355 } else {
356 // TabControl.restoreState() will create a new tab even if
Leon Scroggins1f005d32009-08-10 17:36:42 -0400357 // restoring the state fails.
The Android Open Source Project0c908882009-03-03 19:32:16 -0800358 attachTabToContentView(mTabControl.getCurrentTab());
359 }
Grace Kloba615c6c92009-08-03 10:22:44 -0700360
Feng Qianb3c02da2009-06-29 15:58:08 -0700361 // Read JavaScript flags if it exists.
362 String jsFlags = mSettings.getJsFlags();
363 if (jsFlags.trim().length() != 0) {
364 mTabControl.getCurrentWebView().setJsFlags(jsFlags);
365 }
Andrei Popescu30995e72010-02-09 16:59:58 +0000366 // Work out which packages are installed on the system.
367 getInstalledPackages();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800368 }
369
Leon Scroggins58d56c62010-01-28 15:12:40 -0500370 /**
371 * Feed the previously stored results strings to the BrowserProvider so that
372 * the SearchDialog will show them instead of the standard searches.
373 * @param result String to show on the editable line of the SearchDialog.
374 */
375 /* package */ void showVoiceSearchResults(String result) {
376 ContentProviderClient client = mResolver.acquireContentProviderClient(
377 Browser.BOOKMARKS_URI);
378 ContentProvider prov = client.getLocalContentProvider();
379 BrowserProvider bp = (BrowserProvider) prov;
380 bp.setQueryResults(mTabControl.getCurrentTab().getVoiceSearchResults());
381 client.release();
382
Leon Scrogginsfbb3f152010-03-09 17:26:56 -0500383 Bundle bundle = createGoogleSearchSourceBundle(
384 GOOGLE_SEARCH_SOURCE_SEARCHKEY);
385 bundle.putBoolean(SearchManager.CONTEXT_IS_VOICE, true);
386 startSearch(result, false, bundle, false);
Leon Scroggins58d56c62010-01-28 15:12:40 -0500387 }
388
The Android Open Source Project0c908882009-03-03 19:32:16 -0800389 @Override
390 protected void onNewIntent(Intent intent) {
Grace Kloba22ac16e2009-10-07 18:00:23 -0700391 Tab current = mTabControl.getCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800392 // When a tab is closed on exit, the current tab index is set to -1.
393 // Reset before proceed as Browser requires the current tab to be set.
394 if (current == null) {
395 // Try to reset the tab in case the index was incorrect.
396 current = mTabControl.getTab(0);
397 if (current == null) {
398 // No tabs at all so just ignore this intent.
399 return;
400 }
401 mTabControl.setCurrentTab(current);
402 attachTabToContentView(current);
403 resetTitleAndIcon(current.getWebView());
404 }
405 final String action = intent.getAction();
406 final int flags = intent.getFlags();
407 if (Intent.ACTION_MAIN.equals(action) ||
408 (flags & Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY) != 0) {
409 // just resume the browser
410 return;
411 }
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -0500412 boolean activateVoiceSearch = RecognizerResultsIntent
413 .ACTION_VOICE_SEARCH_RESULTS.equals(action);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800414 if (Intent.ACTION_VIEW.equals(action)
415 || Intent.ACTION_SEARCH.equals(action)
416 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
Leon Scroggins58d56c62010-01-28 15:12:40 -0500417 || Intent.ACTION_WEB_SEARCH.equals(action)
418 || activateVoiceSearch) {
Leon Scroggins3b18ce32010-02-08 17:35:59 -0500419 if (current.isInVoiceSearchMode()) {
420 String title = current.getVoiceDisplayTitle();
421 if (title != null && title.equals(intent.getStringExtra(
422 SearchManager.QUERY))) {
423 // The user submitted the same search as the last voice
424 // search, so do nothing.
425 return;
426 }
Leon Scroggins1fe13a52010-02-09 15:31:26 -0500427 if (Intent.ACTION_SEARCH.equals(action)
428 && current.voiceSearchSourceIsGoogle()) {
429 Intent logIntent = new Intent(
430 LoggingEvents.ACTION_LOG_EVENT);
431 logIntent.putExtra(LoggingEvents.EXTRA_EVENT,
432 LoggingEvents.VoiceSearch.QUERY_UPDATED);
433 logIntent.putExtra(
434 LoggingEvents.VoiceSearch.EXTRA_QUERY_UPDATED_VALUE,
435 intent.getDataString());
436 sendBroadcast(logIntent);
437 // Note, onPageStarted will revert the voice title bar
438 // When http://b/issue?id=2379215 is fixed, we should update
439 // the title bar here.
440 }
Leon Scroggins3b18ce32010-02-08 17:35:59 -0500441 }
Satish Sampath565505b2009-05-29 15:37:27 +0100442 // If this was a search request (e.g. search query directly typed into the address bar),
443 // pass it on to the default web search provider.
444 if (handleWebSearchIntent(intent)) {
445 return;
446 }
447
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700448 UrlData urlData = getUrlDataFromIntent(intent);
449 if (urlData.isEmpty()) {
450 urlData = new UrlData(mSettings.getHomePage());
The Android Open Source Project0c908882009-03-03 19:32:16 -0800451 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700452
Grace Klobacc634032009-07-28 15:58:19 -0700453 final String appId = intent
454 .getStringExtra(Browser.EXTRA_APPLICATION_ID);
Leon Scroggins58d56c62010-01-28 15:12:40 -0500455 if ((Intent.ACTION_VIEW.equals(action) || activateVoiceSearch)
Grace Klobacc634032009-07-28 15:58:19 -0700456 && !getPackageName().equals(appId)
457 && (flags & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0) {
Grace Kloba22ac16e2009-10-07 18:00:23 -0700458 Tab appTab = mTabControl.getTabFromId(appId);
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700459 if (appTab != null) {
460 Log.i(LOGTAG, "Reusing tab for " + appId);
461 // Dismiss the subwindow if applicable.
462 dismissSubWindow(appTab);
463 // Since we might kill the WebView, remove it from the
464 // content view first.
465 removeTabFromContentView(appTab);
466 // Recreate the main WebView after destroying the old one.
467 // If the WebView has the same original url and is on that
468 // page, it can be reused.
469 boolean needsLoad =
Leon Scroggins6eac63e2010-03-15 18:19:14 -0400470 mTabControl.recreateWebView(appTab, urlData);
Ben Murdochbff2d602009-07-01 20:19:05 +0100471
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700472 if (current != appTab) {
Leon Scroggins1f005d32009-08-10 17:36:42 -0400473 switchToTab(mTabControl.getTabIndex(appTab));
474 if (needsLoad) {
Patrick Scott9d53da02010-02-19 10:19:01 -0500475 loadUrlDataIn(appTab, urlData);
Leon Scroggins1f005d32009-08-10 17:36:42 -0400476 }
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700477 } else {
Leon Scroggins1f005d32009-08-10 17:36:42 -0400478 // If the tab was the current tab, we have to attach
479 // it to the view system again.
480 attachTabToContentView(appTab);
481 if (needsLoad) {
Patrick Scott9d53da02010-02-19 10:19:01 -0500482 loadUrlDataIn(appTab, urlData);
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700483 }
484 }
485 return;
Patrick Scottcd115892009-07-16 09:42:58 -0400486 } else {
487 // No matching application tab, try to find a regular tab
488 // with a matching url.
489 appTab = mTabControl.findUnusedTabWithUrl(urlData.mUrl);
Leon Scroggins25515f82009-08-19 15:31:58 -0400490 if (appTab != null) {
491 if (current != appTab) {
492 switchToTab(mTabControl.getTabIndex(appTab));
493 }
494 // Otherwise, we are already viewing the correct tab.
Patrick Scottcd115892009-07-16 09:42:58 -0400495 } else {
496 // if FLAG_ACTIVITY_BROUGHT_TO_FRONT flag is on, the url
497 // will be opened in a new tab unless we have reached
498 // MAX_TABS. Then the url will be opened in the current
499 // tab. If a new tab is created, it will have "true" for
500 // exit on close.
Leon Scroggins1f005d32009-08-10 17:36:42 -0400501 openTabAndShow(urlData, true, appId);
Patrick Scottcd115892009-07-16 09:42:58 -0400502 }
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700503 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800504 } else {
Grace Kloba638d3f42009-11-23 10:35:04 -0800505 if (!urlData.isEmpty()
506 && urlData.mUrl.startsWith("about:debug")) {
507 if ("about:debug.dom".equals(urlData.mUrl)) {
508 current.getWebView().dumpDomTree(false);
509 } else if ("about:debug.dom.file".equals(urlData.mUrl)) {
510 current.getWebView().dumpDomTree(true);
511 } else if ("about:debug.render".equals(urlData.mUrl)) {
512 current.getWebView().dumpRenderTree(false);
513 } else if ("about:debug.render.file".equals(urlData.mUrl)) {
514 current.getWebView().dumpRenderTree(true);
515 } else if ("about:debug.display".equals(urlData.mUrl)) {
516 current.getWebView().dumpDisplayTree();
Mike Reed9b78e1d2010-01-13 14:40:52 -0800517 } else if (urlData.mUrl.startsWith("about:debug.drag")) {
518 int index = urlData.mUrl.codePointAt(16) - '0';
519 if (index <= 0 || index > 9) {
520 current.getWebView().setDragTracker(null);
521 } else {
522 current.getWebView().setDragTracker(new MeshTracker(index));
523 }
Grace Kloba638d3f42009-11-23 10:35:04 -0800524 } else {
525 mSettings.toggleDebugSettings();
526 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800527 return;
528 }
Leon Scroggins1f005d32009-08-10 17:36:42 -0400529 // Get rid of the subwindow if it exists
530 dismissSubWindow(current);
Patrick Scott9d53da02010-02-19 10:19:01 -0500531 loadUrlDataIn(current, urlData);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800532 }
533 }
534 }
535
Satish Sampath565505b2009-05-29 15:37:27 +0100536 private int parseUrlShortcut(String url) {
537 if (url == null) return SHORTCUT_INVALID;
538
539 // FIXME: quick search, need to be customized by setting
540 if (url.length() > 2 && url.charAt(1) == ' ') {
541 switch (url.charAt(0)) {
542 case 'g': return SHORTCUT_GOOGLE_SEARCH;
543 case 'w': return SHORTCUT_WIKIPEDIA_SEARCH;
544 case 'd': return SHORTCUT_DICTIONARY_SEARCH;
545 case 'l': return SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH;
546 }
547 }
548 return SHORTCUT_INVALID;
549 }
550
551 /**
552 * Launches the default web search activity with the query parameters if the given intent's data
553 * are identified as plain search terms and not URLs/shortcuts.
554 * @return true if the intent was handled and web search activity was launched, false if not.
555 */
556 private boolean handleWebSearchIntent(Intent intent) {
557 if (intent == null) return false;
558
559 String url = null;
560 final String action = intent.getAction();
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -0500561 if (RecognizerResultsIntent.ACTION_VOICE_SEARCH_RESULTS.equals(
562 action)) {
Leon Scroggins58d56c62010-01-28 15:12:40 -0500563 return false;
564 }
Satish Sampath565505b2009-05-29 15:37:27 +0100565 if (Intent.ACTION_VIEW.equals(action)) {
Grace Kloba1e705052009-09-29 13:13:36 -0700566 Uri data = intent.getData();
567 if (data != null) url = data.toString();
Satish Sampath565505b2009-05-29 15:37:27 +0100568 } else if (Intent.ACTION_SEARCH.equals(action)
569 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
570 || Intent.ACTION_WEB_SEARCH.equals(action)) {
571 url = intent.getStringExtra(SearchManager.QUERY);
572 }
Bjorn Bringert04851702009-09-22 10:36:01 +0100573 return handleWebSearchRequest(url, intent.getBundleExtra(SearchManager.APP_DATA),
574 intent.getStringExtra(SearchManager.EXTRA_DATA_KEY));
Satish Sampath565505b2009-05-29 15:37:27 +0100575 }
576
577 /**
578 * Launches the default web search activity with the query parameters if the given url string
579 * was identified as plain search terms and not URL/shortcut.
580 * @return true if the request was handled and web search activity was launched, false if not.
581 */
Bjorn Bringert04851702009-09-22 10:36:01 +0100582 private boolean handleWebSearchRequest(String inUrl, Bundle appData, String extraData) {
Satish Sampath565505b2009-05-29 15:37:27 +0100583 if (inUrl == null) return false;
584
585 // In general, we shouldn't modify URL from Intent.
586 // But currently, we get the user-typed URL from search box as well.
587 String url = fixUrl(inUrl).trim();
588
589 // URLs and site specific search shortcuts are handled by the regular flow of control, so
590 // return early.
Dan Egnor5ee906c2009-11-18 12:11:49 -0800591 if (Patterns.WEB_URL.matcher(url).matches()
Satish Sampathbc5b9f32009-06-04 18:21:40 +0100592 || ACCEPTED_URI_SCHEMA.matcher(url).matches()
Satish Sampath565505b2009-05-29 15:37:27 +0100593 || parseUrlShortcut(url) != SHORTCUT_INVALID) {
594 return false;
595 }
596
597 Browser.updateVisitedHistory(mResolver, url, false);
598 Browser.addSearchUrl(mResolver, url);
599
600 Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);
601 intent.addCategory(Intent.CATEGORY_DEFAULT);
602 intent.putExtra(SearchManager.QUERY, url);
Satish Sampath15e9f2d2009-06-23 22:29:49 +0100603 if (appData != null) {
604 intent.putExtra(SearchManager.APP_DATA, appData);
605 }
Bjorn Bringert04851702009-09-22 10:36:01 +0100606 if (extraData != null) {
607 intent.putExtra(SearchManager.EXTRA_DATA_KEY, extraData);
608 }
Grace Klobacc634032009-07-28 15:58:19 -0700609 intent.putExtra(Browser.EXTRA_APPLICATION_ID, getPackageName());
Satish Sampath565505b2009-05-29 15:37:27 +0100610 startActivity(intent);
611
612 return true;
613 }
614
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700615 private UrlData getUrlDataFromIntent(Intent intent) {
Leon Scroggins58d56c62010-01-28 15:12:40 -0500616 String url = "";
Grace Kloba068e48b2010-01-26 18:11:27 -0800617 Map<String, String> headers = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800618 if (intent != null) {
619 final String action = intent.getAction();
620 if (Intent.ACTION_VIEW.equals(action)) {
621 url = smartUrlFilter(intent.getData());
622 if (url != null && url.startsWith("content:")) {
623 /* Append mimetype so webview knows how to display */
624 String mimeType = intent.resolveType(getContentResolver());
625 if (mimeType != null) {
626 url += "?" + mimeType;
627 }
628 }
Grace Kloba068e48b2010-01-26 18:11:27 -0800629 if (url != null && url.startsWith("http")) {
Grace Kloba00f54c52010-01-27 14:53:51 -0800630 final Bundle pairs = intent
631 .getBundleExtra(Browser.EXTRA_HEADERS);
Grace Kloba2d508ed2010-01-28 11:39:15 -0800632 if (pairs != null && !pairs.isEmpty()) {
Grace Kloba00f54c52010-01-27 14:53:51 -0800633 Iterator<String> iter = pairs.keySet().iterator();
Grace Kloba068e48b2010-01-26 18:11:27 -0800634 headers = new HashMap<String, String>();
Grace Kloba00f54c52010-01-27 14:53:51 -0800635 while (iter.hasNext()) {
636 String key = iter.next();
637 headers.put(key, pairs.getString(key));
Grace Kloba068e48b2010-01-26 18:11:27 -0800638 }
639 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700640 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800641 } else if (Intent.ACTION_SEARCH.equals(action)
642 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
643 || Intent.ACTION_WEB_SEARCH.equals(action)) {
644 url = intent.getStringExtra(SearchManager.QUERY);
645 if (url != null) {
646 mLastEnteredUrl = url;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800647 // In general, we shouldn't modify URL from Intent.
648 // But currently, we get the user-typed URL from search box as well.
649 url = fixUrl(url);
650 url = smartUrlFilter(url);
Leon Scrogginsda3e0302010-03-02 16:01:49 -0500651 Browser.updateVisitedHistory(mResolver, url, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800652 String searchSource = "&source=android-" + GOOGLE_SEARCH_SOURCE_SUGGEST + "&";
653 if (url.contains(searchSource)) {
654 String source = null;
655 final Bundle appData = intent.getBundleExtra(SearchManager.APP_DATA);
656 if (appData != null) {
Bjorn Bringert10d1cca2010-02-10 14:22:12 +0000657 source = appData.getString(Search.SOURCE);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800658 }
659 if (TextUtils.isEmpty(source)) {
660 source = GOOGLE_SEARCH_SOURCE_UNKNOWN;
661 }
662 url = url.replace(searchSource, "&source=android-"+source+"&");
663 }
664 }
665 }
666 }
Leon Scroggins58d56c62010-01-28 15:12:40 -0500667 return new UrlData(url, headers, intent);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800668 }
Leon Scroggins58d56c62010-01-28 15:12:40 -0500669 /* package */ void showVoiceTitleBar(String title) {
670 mTitleBar.setInVoiceMode(true);
671 mFakeTitleBar.setInVoiceMode(true);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800672
Leon Scroggins58d56c62010-01-28 15:12:40 -0500673 mTitleBar.setDisplayTitle(title);
674 mFakeTitleBar.setDisplayTitle(title);
675 }
676 /* package */ void revertVoiceTitleBar() {
677 mTitleBar.setInVoiceMode(false);
678 mFakeTitleBar.setInVoiceMode(false);
679
Leon Scroggins003a5dd2010-03-10 12:13:14 -0500680 mTitleBar.setDisplayTitle(mUrl);
681 mFakeTitleBar.setDisplayTitle(mUrl);
Leon Scroggins58d56c62010-01-28 15:12:40 -0500682 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800683 /* package */ static String fixUrl(String inUrl) {
Cary Clark652ff872009-09-10 13:34:44 -0400684 // FIXME: Converting the url to lower case
685 // duplicates functionality in smartUrlFilter().
686 // However, changing all current callers of fixUrl to
687 // call smartUrlFilter in addition may have unwanted
688 // consequences, and is deferred for now.
689 int colon = inUrl.indexOf(':');
690 boolean allLower = true;
691 for (int index = 0; index < colon; index++) {
692 char ch = inUrl.charAt(index);
693 if (!Character.isLetter(ch)) {
694 break;
695 }
696 allLower &= Character.isLowerCase(ch);
697 if (index == colon - 1 && !allLower) {
698 inUrl = inUrl.substring(0, colon).toLowerCase()
699 + inUrl.substring(colon);
700 }
701 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800702 if (inUrl.startsWith("http://") || inUrl.startsWith("https://"))
703 return inUrl;
704 if (inUrl.startsWith("http:") ||
705 inUrl.startsWith("https:")) {
706 if (inUrl.startsWith("http:/") || inUrl.startsWith("https:/")) {
707 inUrl = inUrl.replaceFirst("/", "//");
708 } else inUrl = inUrl.replaceFirst(":", "://");
709 }
710 return inUrl;
711 }
712
Grace Kloba22ac16e2009-10-07 18:00:23 -0700713 @Override
714 protected void onResume() {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800715 super.onResume();
Dave Bort31a6d1c2009-04-13 15:56:49 -0700716 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800717 Log.v(LOGTAG, "BrowserActivity.onResume: this=" + this);
718 }
719
720 if (!mActivityInPause) {
721 Log.e(LOGTAG, "BrowserActivity is already resumed.");
722 return;
723 }
724
Mike Reed7bfa63b2009-05-28 11:08:32 -0400725 mTabControl.resumeCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800726 mActivityInPause = false;
Mike Reed7bfa63b2009-05-28 11:08:32 -0400727 resumeWebViewTimers();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800728
729 if (mWakeLock.isHeld()) {
730 mHandler.removeMessages(RELEASE_WAKELOCK);
731 mWakeLock.release();
732 }
733
The Android Open Source Project0c908882009-03-03 19:32:16 -0800734 registerReceiver(mNetworkStateIntentReceiver,
735 mNetworkStateChangedFilter);
736 WebView.enablePlatformNotifications();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800737 }
738
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400739 /**
740 * Since the actual title bar is embedded in the WebView, and removing it
Leon Scrogginsfe87bd32009-10-06 10:10:00 -0400741 * would change its appearance, use a different TitleBar to show overlayed
742 * at the top of the screen, when the menu is open or the page is loading.
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400743 */
744 private TitleBar mFakeTitleBar;
745
746 /**
Leon Scrogginsd8fd2fc2009-09-16 11:12:09 -0400747 * Holder for the fake title bar. It will have a foreground shadow, as well
748 * as a white background, so the fake title bar looks like the real one.
749 */
750 private ViewGroup mFakeTitleBarHolder;
751
752 /**
753 * Layout parameters for the fake title bar within mFakeTitleBarHolder
754 */
755 private FrameLayout.LayoutParams mFakeTitleBarParams
756 = new FrameLayout.LayoutParams(
Romain Guy15b8ec62010-01-08 15:06:43 -0800757 ViewGroup.LayoutParams.MATCH_PARENT,
Leon Scrogginsd8fd2fc2009-09-16 11:12:09 -0400758 ViewGroup.LayoutParams.WRAP_CONTENT);
759 /**
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400760 * Keeps track of whether the options menu is open. This is important in
761 * determining whether to show or hide the title bar overlay.
762 */
763 private boolean mOptionsMenuOpen;
764
765 /**
766 * Only meaningful when mOptionsMenuOpen is true. This variable keeps track
767 * of whether the configuration has changed. The first onMenuOpened call
768 * after a configuration change is simply a reopening of the same menu
769 * (i.e. mIconView did not change).
770 */
771 private boolean mConfigChanged;
772
773 /**
774 * Whether or not the options menu is in its smaller, icon menu form. When
775 * true, we want the title bar overlay to be up. When false, we do not.
776 * Only meaningful if mOptionsMenuOpen is true.
777 */
778 private boolean mIconView;
779
Leon Scrogginsa81a7642009-08-31 17:05:41 -0400780 @Override
781 public boolean onMenuOpened(int featureId, Menu menu) {
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400782 if (Window.FEATURE_OPTIONS_PANEL == featureId) {
783 if (mOptionsMenuOpen) {
784 if (mConfigChanged) {
785 // We do not need to make any changes to the state of the
786 // title bar, since the only thing that happened was a
787 // change in orientation
788 mConfigChanged = false;
789 } else {
790 if (mIconView) {
791 // Switching the menu to expanded view, so hide the
792 // title bar.
793 hideFakeTitleBar();
794 mIconView = false;
795 } else {
796 // Switching the menu back to icon view, so show the
797 // title bar once again.
798 showFakeTitleBar();
799 mIconView = true;
800 }
801 }
802 } else {
803 // The options menu is closed, so open it, and show the title
804 showFakeTitleBar();
805 mOptionsMenuOpen = true;
806 mConfigChanged = false;
807 mIconView = true;
808 }
809 }
Leon Scrogginsa81a7642009-08-31 17:05:41 -0400810 return true;
811 }
812
Leon Scrogginsb94bf272009-09-25 15:22:08 -0400813 /**
814 * Special class used exclusively for the shadow drawn underneath the fake
815 * title bar. The shadow does not need to be drawn if the WebView
816 * underneath is scrolled to the top, because it will draw directly on top
817 * of the embedded shadow.
818 */
819 private static class Shadow extends View {
820 private WebView mWebView;
821
822 public Shadow(Context context, AttributeSet attrs) {
823 super(context, attrs);
824 }
825
826 public void setWebView(WebView view) {
827 mWebView = view;
828 }
829
830 @Override
831 public void draw(Canvas canvas) {
832 // In general onDraw is the method to override, but we care about
833 // whether or not the background gets drawn, which happens in draw()
834 if (mWebView == null || mWebView.getScrollY() > getHeight()) {
835 super.draw(canvas);
836 }
Leon Scrogginsb94bf272009-09-25 15:22:08 -0400837 }
838 }
839
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400840 private void showFakeTitleBar() {
Patrick Scottf8de8ec2009-09-21 16:37:29 -0400841 final View decor = getWindow().peekDecorView();
Leon Scrogginsfe87bd32009-10-06 10:10:00 -0400842 if (mFakeTitleBar.getParent() == null && mActiveTabsPage == null
Patrick Scottf8de8ec2009-09-21 16:37:29 -0400843 && !mActivityInPause && decor != null
844 && decor.getWindowToken() != null) {
Cary Clarka0464552009-09-29 13:00:45 -0400845 Rect visRect = new Rect();
846 if (!mBrowserFrameLayout.getGlobalVisibleRect(visRect)) {
847 if (LOGD_ENABLED) {
848 Log.d(LOGTAG, "showFakeTitleBar visRect failed");
849 }
850 return;
851 }
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400852
853 WindowManager manager
854 = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
855
856 // Add the title bar to the window manager so it can receive touches
857 // while the menu is up
858 WindowManager.LayoutParams params
859 = new WindowManager.LayoutParams(
Romain Guy15b8ec62010-01-08 15:06:43 -0800860 ViewGroup.LayoutParams.MATCH_PARENT,
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400861 ViewGroup.LayoutParams.WRAP_CONTENT,
862 WindowManager.LayoutParams.TYPE_APPLICATION_SUB_PANEL,
863 WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
Leon Scroggins68549862009-09-21 16:02:01 -0400864 PixelFormat.TRANSLUCENT);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400865 params.gravity = Gravity.TOP;
Leon Scrogginsa27ff192009-09-14 12:58:04 -0400866 WebView mainView = mTabControl.getCurrentWebView();
Leon Scroggins68549862009-09-21 16:02:01 -0400867 boolean atTop = mainView != null && mainView.getScrollY() == 0;
Leon Scroggins83932c72009-09-30 11:55:54 -0400868 params.windowAnimations = atTop ? 0 : R.style.TitleBar;
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400869 // XXX : Without providing an offset, the fake title bar will be
870 // placed underneath the status bar. Use the global visible rect
871 // of mBrowserFrameLayout to determine the bottom of the status bar
Cary Clarka0464552009-09-29 13:00:45 -0400872 params.y = visRect.top;
Leon Scroggins68549862009-09-21 16:02:01 -0400873 // Add a holder for the title bar. It also holds a shadow to show
874 // below the title bar.
Leon Scrogginsd8fd2fc2009-09-16 11:12:09 -0400875 if (mFakeTitleBarHolder == null) {
876 mFakeTitleBarHolder = (ViewGroup) LayoutInflater.from(this)
877 .inflate(R.layout.title_bar_bg, null);
878 }
Leon Scrogginsb94bf272009-09-25 15:22:08 -0400879 Shadow shadow = (Shadow) mFakeTitleBarHolder.findViewById(
880 R.id.shadow);
881 shadow.setWebView(mainView);
Leon Scroggins68549862009-09-21 16:02:01 -0400882 mFakeTitleBarHolder.addView(mFakeTitleBar, 0, mFakeTitleBarParams);
Leon Scrogginsd8fd2fc2009-09-16 11:12:09 -0400883 manager.addView(mFakeTitleBarHolder, params);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400884 }
885 }
886
887 @Override
888 public void onOptionsMenuClosed(Menu menu) {
889 mOptionsMenuOpen = false;
Leon Scrogginsa27ff192009-09-14 12:58:04 -0400890 if (!mInLoad) {
891 hideFakeTitleBar();
892 } else if (!mIconView) {
893 // The page is currently loading, and we are in expanded mode, so
894 // we were not showing the menu. Show it once again. It will be
895 // removed when the page finishes.
896 showFakeTitleBar();
897 }
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400898 }
Grace Kloba22ac16e2009-10-07 18:00:23 -0700899
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400900 private void hideFakeTitleBar() {
Leon Scrogginsfe87bd32009-10-06 10:10:00 -0400901 if (mFakeTitleBar.getParent() == null) return;
Leon Scroggins20329572009-09-23 17:42:41 -0400902 WindowManager.LayoutParams params = (WindowManager.LayoutParams)
903 mFakeTitleBarHolder.getLayoutParams();
904 WebView mainView = mTabControl.getCurrentWebView();
905 // Although we decided whether or not to animate based on the current
906 // scroll position, the scroll position may have changed since the
907 // fake title bar was displayed. Make sure it has the appropriate
908 // animation/lack thereof before removing.
909 params.windowAnimations = mainView != null && mainView.getScrollY() == 0
Leon Scroggins83932c72009-09-30 11:55:54 -0400910 ? 0 : R.style.TitleBar;
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400911 WindowManager manager
912 = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
Leon Scroggins20329572009-09-23 17:42:41 -0400913 manager.updateViewLayout(mFakeTitleBarHolder, params);
Leon Scrogginsd8fd2fc2009-09-16 11:12:09 -0400914 mFakeTitleBarHolder.removeView(mFakeTitleBar);
915 manager.removeView(mFakeTitleBarHolder);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400916 }
917
The Android Open Source Project0c908882009-03-03 19:32:16 -0800918 /**
Leon Scrogginsc6fa1102009-09-21 10:40:01 -0400919 * Special method for the fake title bar to call when displaying its context
920 * menu, since it is in its own Window, and its parent does not show a
921 * context menu.
922 */
923 /* package */ void showTitleBarContextMenu() {
Cary Clark65f4a3c2009-09-28 17:05:06 -0400924 if (null == mTitleBar.getParent()) {
925 return;
926 }
Leon Scrogginsc6fa1102009-09-21 10:40:01 -0400927 openContextMenu(mTitleBar);
928 }
929
Leon Scrogginsb2b19f52009-10-09 16:10:00 -0400930 @Override
931 public void onContextMenuClosed(Menu menu) {
932 super.onContextMenuClosed(menu);
933 if (mInLoad) {
934 showFakeTitleBar();
935 }
936 }
937
Leon Scrogginsc6fa1102009-09-21 10:40:01 -0400938 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -0800939 * onSaveInstanceState(Bundle map)
940 * onSaveInstanceState is called right before onStop(). The map contains
941 * the saved state.
942 */
Grace Kloba22ac16e2009-10-07 18:00:23 -0700943 @Override
944 protected void onSaveInstanceState(Bundle outState) {
Dave Bort31a6d1c2009-04-13 15:56:49 -0700945 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800946 Log.v(LOGTAG, "BrowserActivity.onSaveInstanceState: this=" + this);
947 }
948 // the default implementation requires each view to have an id. As the
949 // browser handles the state itself and it doesn't use id for the views,
950 // don't call the default implementation. Otherwise it will trigger the
951 // warning like this, "couldn't save which view has focus because the
952 // focused view XXX has no id".
953
954 // Save all the tabs
955 mTabControl.saveState(outState);
956 }
957
Grace Kloba22ac16e2009-10-07 18:00:23 -0700958 @Override
959 protected void onPause() {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800960 super.onPause();
961
962 if (mActivityInPause) {
963 Log.e(LOGTAG, "BrowserActivity is already paused.");
964 return;
965 }
966
Mike Reed7bfa63b2009-05-28 11:08:32 -0400967 mTabControl.pauseCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800968 mActivityInPause = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -0400969 if (mTabControl.getCurrentIndex() >= 0 && !pauseWebViewTimers()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800970 mWakeLock.acquire();
971 mHandler.sendMessageDelayed(mHandler
972 .obtainMessage(RELEASE_WAKELOCK), WAKELOCK_TIMEOUT);
973 }
974
Leon Scrogginsa2ab6a72009-09-11 11:49:52 -0400975 // FIXME: This removes the active tabs page and resets the menu to
976 // MAIN_MENU. A better solution might be to do this work in onNewIntent
977 // but then we would need to save it in onSaveInstanceState and restore
978 // it in onCreate/onRestoreInstanceState
979 if (mActiveTabsPage != null) {
980 removeActiveTabPage(true);
981 }
982
The Android Open Source Project0c908882009-03-03 19:32:16 -0800983 cancelStopToast();
984
985 // unregister network state listener
986 unregisterReceiver(mNetworkStateIntentReceiver);
987 WebView.disablePlatformNotifications();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800988 }
989
Grace Kloba22ac16e2009-10-07 18:00:23 -0700990 @Override
991 protected void onDestroy() {
Dave Bort31a6d1c2009-04-13 15:56:49 -0700992 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800993 Log.v(LOGTAG, "BrowserActivity.onDestroy: this=" + this);
994 }
995 super.onDestroy();
Grace Kloba0923d692009-09-23 21:37:25 -0700996
Leon Scroggins8d5fa432009-10-02 15:55:59 -0400997 if (mUploadMessage != null) {
998 mUploadMessage.onReceiveValue(null);
999 mUploadMessage = null;
1000 }
1001
Grace Kloba0923d692009-09-23 21:37:25 -07001002 if (mTabControl == null) return;
1003
Grace Kloba1fc98a32009-10-21 13:23:08 -07001004 // Remove the fake title bar if it is there
1005 hideFakeTitleBar();
1006
The Android Open Source Project0c908882009-03-03 19:32:16 -08001007 // Remove the current tab and sub window
Grace Kloba22ac16e2009-10-07 18:00:23 -07001008 Tab t = mTabControl.getCurrentTab();
Patrick Scottfb5e77f2009-04-08 19:17:37 -07001009 if (t != null) {
1010 dismissSubWindow(t);
1011 removeTabFromContentView(t);
1012 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001013 // Destroy all the tabs
1014 mTabControl.destroy();
1015 WebIconDatabase.getInstance().close();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001016
Grace Klobab4da0ad2009-05-14 14:45:40 -07001017 unregisterReceiver(mPackageInstallationReceiver);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001018 }
1019
1020 @Override
1021 public void onConfigurationChanged(Configuration newConfig) {
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04001022 mConfigChanged = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001023 super.onConfigurationChanged(newConfig);
1024
1025 if (mPageInfoDialog != null) {
1026 mPageInfoDialog.dismiss();
1027 showPageInfo(
1028 mPageInfoView,
Leon Scrogginsc7b92f82010-01-11 18:17:31 -05001029 mPageInfoFromShowSSLCertificateOnError);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001030 }
1031 if (mSSLCertificateDialog != null) {
1032 mSSLCertificateDialog.dismiss();
1033 showSSLCertificate(
1034 mSSLCertificateView);
1035 }
1036 if (mSSLCertificateOnErrorDialog != null) {
1037 mSSLCertificateOnErrorDialog.dismiss();
1038 showSSLCertificateOnError(
1039 mSSLCertificateOnErrorView,
1040 mSSLCertificateOnErrorHandler,
1041 mSSLCertificateOnErrorError);
1042 }
1043 if (mHttpAuthenticationDialog != null) {
1044 String title = ((TextView) mHttpAuthenticationDialog
1045 .findViewById(com.android.internal.R.id.alertTitle)).getText()
1046 .toString();
1047 String name = ((TextView) mHttpAuthenticationDialog
1048 .findViewById(R.id.username_edit)).getText().toString();
1049 String password = ((TextView) mHttpAuthenticationDialog
1050 .findViewById(R.id.password_edit)).getText().toString();
1051 int focusId = mHttpAuthenticationDialog.getCurrentFocus()
1052 .getId();
1053 mHttpAuthenticationDialog.dismiss();
1054 showHttpAuthentication(mHttpAuthHandler, null, null, title,
1055 name, password, focusId);
1056 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001057 }
1058
Grace Kloba22ac16e2009-10-07 18:00:23 -07001059 @Override
1060 public void onLowMemory() {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001061 super.onLowMemory();
1062 mTabControl.freeMemory();
1063 }
1064
Mike Reed7bfa63b2009-05-28 11:08:32 -04001065 private boolean resumeWebViewTimers() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001066 Tab tab = mTabControl.getCurrentTab();
1067 boolean inLoad = tab.inLoad();
1068 if ((!mActivityInPause && !inLoad) || (mActivityInPause && inLoad)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001069 CookieSyncManager.getInstance().startSync();
Grace Kloba22ac16e2009-10-07 18:00:23 -07001070 WebView w = tab.getWebView();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001071 if (w != null) {
1072 w.resumeTimers();
1073 }
1074 return true;
1075 } else {
1076 return false;
1077 }
1078 }
1079
Mike Reed7bfa63b2009-05-28 11:08:32 -04001080 private boolean pauseWebViewTimers() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001081 Tab tab = mTabControl.getCurrentTab();
1082 boolean inLoad = tab.inLoad();
1083 if (mActivityInPause && !inLoad) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001084 CookieSyncManager.getInstance().stopSync();
1085 WebView w = mTabControl.getCurrentWebView();
1086 if (w != null) {
1087 w.pauseTimers();
1088 }
1089 return true;
1090 } else {
1091 return false;
1092 }
1093 }
1094
The Android Open Source Project0c908882009-03-03 19:32:16 -08001095 // Open the icon database and retain all the icons for visited sites.
1096 private void retainIconsOnStartup() {
1097 final WebIconDatabase db = WebIconDatabase.getInstance();
1098 db.open(getDir("icons", 0).getPath());
Leon Scroggins2c0f6112010-03-12 18:09:39 -05001099 Cursor c = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001100 try {
Leon Scroggins2c0f6112010-03-12 18:09:39 -05001101 c = Browser.getAllBookmarks(mResolver);
1102 if (c.moveToFirst()) {
1103 int urlIndex = c.getColumnIndex(Browser.BookmarkColumns.URL);
1104 do {
1105 String url = c.getString(urlIndex);
1106 db.retainIconForPageUrl(url);
1107 } while (c.moveToNext());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001108 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001109 } catch (IllegalStateException e) {
1110 Log.e(LOGTAG, "retainIconsOnStartup", e);
Leon Scroggins2c0f6112010-03-12 18:09:39 -05001111 } finally {
1112 if (c!= null) c.close();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001113 }
1114 }
1115
1116 // Helper method for getting the top window.
1117 WebView getTopWindow() {
1118 return mTabControl.getCurrentTopWebView();
1119 }
1120
Grace Kloba22ac16e2009-10-07 18:00:23 -07001121 TabControl getTabControl() {
1122 return mTabControl;
1123 }
1124
The Android Open Source Project0c908882009-03-03 19:32:16 -08001125 @Override
1126 public boolean onCreateOptionsMenu(Menu menu) {
1127 super.onCreateOptionsMenu(menu);
1128
1129 MenuInflater inflater = getMenuInflater();
1130 inflater.inflate(R.menu.browser, menu);
1131 mMenu = menu;
1132 updateInLoadMenuItems();
1133 return true;
1134 }
1135
1136 /**
1137 * As the menu can be open when loading state changes
1138 * we must manually update the state of the stop/reload menu
1139 * item
1140 */
1141 private void updateInLoadMenuItems() {
1142 if (mMenu == null) {
1143 return;
1144 }
1145 MenuItem src = mInLoad ?
1146 mMenu.findItem(R.id.stop_menu_id):
1147 mMenu.findItem(R.id.reload_menu_id);
1148 MenuItem dest = mMenu.findItem(R.id.stop_reload_menu_id);
1149 dest.setIcon(src.getIcon());
1150 dest.setTitle(src.getTitle());
1151 }
1152
1153 @Override
1154 public boolean onContextItemSelected(MenuItem item) {
1155 // chording is not an issue with context menus, but we use the same
1156 // options selector, so set mCanChord to true so we can access them.
1157 mCanChord = true;
1158 int id = item.getItemId();
Leon Scroggins96afcb12009-12-10 12:35:56 -05001159 boolean result = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001160 switch (id) {
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001161 // For the context menu from the title bar
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001162 case R.id.title_bar_copy_page_url:
Leon Scroggins96afcb12009-12-10 12:35:56 -05001163 Tab currentTab = mTabControl.getCurrentTab();
1164 if (null == currentTab) {
1165 result = false;
1166 break;
1167 }
1168 WebView mainView = currentTab.getWebView();
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001169 if (null == mainView) {
Leon Scroggins96afcb12009-12-10 12:35:56 -05001170 result = false;
1171 break;
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001172 }
Leon Scroggins96afcb12009-12-10 12:35:56 -05001173 copy(mainView.getUrl());
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001174 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001175 // -- Browser context menu
1176 case R.id.open_context_menu_id:
1177 case R.id.open_newtab_context_menu_id:
1178 case R.id.bookmark_context_menu_id:
1179 case R.id.save_link_context_menu_id:
1180 case R.id.share_link_context_menu_id:
1181 case R.id.copy_link_context_menu_id:
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001182 final WebView webView = getTopWindow();
1183 if (null == webView) {
Leon Scroggins96afcb12009-12-10 12:35:56 -05001184 result = false;
1185 break;
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001186 }
1187 final HashMap hrefMap = new HashMap();
1188 hrefMap.put("webview", webView);
1189 final Message msg = mHandler.obtainMessage(
1190 FOCUS_NODE_HREF, id, 0, hrefMap);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001191 webView.requestFocusNodeHref(msg);
1192 break;
1193
1194 default:
1195 // For other context menus
Leon Scroggins96afcb12009-12-10 12:35:56 -05001196 result = onOptionsItemSelected(item);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001197 }
1198 mCanChord = false;
Leon Scroggins96afcb12009-12-10 12:35:56 -05001199 return result;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001200 }
1201
1202 private Bundle createGoogleSearchSourceBundle(String source) {
1203 Bundle bundle = new Bundle();
Bjorn Bringert10d1cca2010-02-10 14:22:12 +00001204 bundle.putString(Search.SOURCE, source);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001205 return bundle;
1206 }
1207
Leon Scroggins8ad29922010-02-16 12:33:55 -05001208 /* package */ void editUrl() {
Leon Scroggins68579392009-09-15 15:31:54 -04001209 if (mOptionsMenuOpen) closeOptionsMenu();
Leon Scroggins5bbe9802009-07-31 13:10:55 -04001210 String url = (getTopWindow() == null) ? null : getTopWindow().getUrl();
Grace Kloba83f47342009-07-20 10:44:31 -07001211 startSearch(mSettings.getHomePage().equals(url) ? null : url, true,
Leon Scroggins8ad29922010-02-16 12:33:55 -05001212 null, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001213 }
1214
Leon Scroggins8ad29922010-02-16 12:33:55 -05001215 /**
1216 * Overriding this to insert a local information bundle
1217 */
The Android Open Source Project0c908882009-03-03 19:32:16 -08001218 @Override
1219 public void startSearch(String initialQuery, boolean selectInitialQuery,
1220 Bundle appSearchData, boolean globalSearch) {
1221 if (appSearchData == null) {
1222 appSearchData = createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_TYPE);
1223 }
1224 super.startSearch(initialQuery, selectInitialQuery, appSearchData, globalSearch);
1225 }
1226
Leon Scroggins1f005d32009-08-10 17:36:42 -04001227 /**
1228 * Switch tabs. Called by the TitleBarSet when sliding the title bar
1229 * results in changing tabs.
Leon Scroggins160a7e72009-08-14 18:28:01 -04001230 * @param index Index of the tab to change to, as defined by
1231 * mTabControl.getTabIndex(Tab t).
1232 * @return boolean True if we successfully switched to a different tab. If
1233 * the indexth tab is null, or if that tab is the same as
1234 * the current one, return false.
Leon Scroggins1f005d32009-08-10 17:36:42 -04001235 */
Leon Scroggins160a7e72009-08-14 18:28:01 -04001236 /* package */ boolean switchToTab(int index) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001237 Tab tab = mTabControl.getTab(index);
1238 Tab currentTab = mTabControl.getCurrentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04001239 if (tab == null || tab == currentTab) {
Leon Scroggins160a7e72009-08-14 18:28:01 -04001240 return false;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001241 }
1242 if (currentTab != null) {
1243 // currentTab may be null if it was just removed. In that case,
1244 // we do not need to remove it
1245 removeTabFromContentView(currentTab);
1246 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001247 mTabControl.setCurrentTab(tab);
1248 attachTabToContentView(tab);
Grace Klobaeb6eef42009-09-15 17:56:32 -07001249 resetTitleIconAndProgress();
1250 updateLockIconToLatest();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001251 return true;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001252 }
1253
Grace Kloba22ac16e2009-10-07 18:00:23 -07001254 /* package */ Tab openTabToHomePage() {
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001255 return openTabAndShow(mSettings.getHomePage(), false, null);
1256 }
1257
Leon Scroggins1f005d32009-08-10 17:36:42 -04001258 /* package */ void closeCurrentWindow() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001259 final Tab current = mTabControl.getCurrentTab();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001260 if (mTabControl.getTabCount() == 1) {
Leon Scroggins30444232009-09-04 18:36:20 -04001261 // This is the last tab. Open a new one, with the home
1262 // page and close the current one.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001263 openTabToHomePage();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001264 closeTab(current);
Leon Scroggins160a7e72009-08-14 18:28:01 -04001265 return;
1266 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07001267 final Tab parent = current.getParentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04001268 int indexToShow = -1;
1269 if (parent != null) {
1270 indexToShow = mTabControl.getTabIndex(parent);
1271 } else {
Leon Scroggins160a7e72009-08-14 18:28:01 -04001272 final int currentIndex = mTabControl.getCurrentIndex();
1273 // Try to move to the tab to the right
1274 indexToShow = currentIndex + 1;
1275 if (indexToShow > mTabControl.getTabCount() - 1) {
1276 // Try to move to the tab to the left
1277 indexToShow = currentIndex - 1;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001278 }
1279 }
Leon Scroggins160a7e72009-08-14 18:28:01 -04001280 if (switchToTab(indexToShow)) {
1281 // Close window
1282 closeTab(current);
1283 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001284 }
1285
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001286 private ActiveTabsPage mActiveTabsPage;
1287
1288 /**
1289 * Remove the active tabs page.
1290 * @param needToAttach If true, the active tabs page did not attach a tab
1291 * to the content view, so we need to do that here.
1292 */
1293 /* package */ void removeActiveTabPage(boolean needToAttach) {
1294 mContentView.removeView(mActiveTabsPage);
1295 mActiveTabsPage = null;
1296 mMenuState = R.id.MAIN_MENU;
1297 if (needToAttach) {
1298 attachTabToContentView(mTabControl.getCurrentTab());
1299 }
1300 getTopWindow().requestFocus();
1301 }
1302
The Android Open Source Project0c908882009-03-03 19:32:16 -08001303 @Override
1304 public boolean onOptionsItemSelected(MenuItem item) {
1305 if (!mCanChord) {
1306 // The user has already fired a shortcut with this hold down of the
1307 // menu key.
1308 return false;
1309 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001310 if (null == getTopWindow()) {
Leon Scroggins0d7ae0e2009-06-05 11:04:45 -04001311 return false;
1312 }
Grace Kloba6ee9c492009-07-13 10:04:34 -07001313 if (mMenuIsDown) {
1314 // The shortcut action consumes the MENU. Even if it is still down,
1315 // it won't trigger the next shortcut action. In the case of the
1316 // shortcut action triggering a new activity, like Bookmarks, we
1317 // won't get onKeyUp for MENU. So it is important to reset it here.
1318 mMenuIsDown = false;
1319 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001320 switch (item.getItemId()) {
1321 // -- Main menu
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001322 case R.id.new_tab_menu_id:
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001323 openTabToHomePage();
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001324 break;
1325
Leon Scroggins64b80f32009-08-07 12:03:34 -04001326 case R.id.goto_menu_id:
Leon Scroggins8ad29922010-02-16 12:33:55 -05001327 editUrl();
Leon Scrogginsb3a5bed2009-09-28 11:21:56 -04001328 break;
1329
1330 case R.id.bookmarks_menu_id:
Leon Scroggins30444232009-09-04 18:36:20 -04001331 bookmarksOrHistoryPicker(false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001332 break;
1333
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001334 case R.id.active_tabs_menu_id:
1335 mActiveTabsPage = new ActiveTabsPage(this, mTabControl);
1336 removeTabFromContentView(mTabControl.getCurrentTab());
Leon Scroggins43de6162009-09-14 19:59:58 -04001337 hideFakeTitleBar();
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001338 mContentView.addView(mActiveTabsPage, COVER_SCREEN_PARAMS);
1339 mActiveTabsPage.requestFocus();
1340 mMenuState = EMPTY_MENU;
1341 break;
1342
Leon Scroggins1f005d32009-08-10 17:36:42 -04001343 case R.id.add_bookmark_menu_id:
1344 Intent i = new Intent(BrowserActivity.this,
1345 AddBookmarkPage.class);
1346 WebView w = getTopWindow();
1347 i.putExtra("url", w.getUrl());
1348 i.putExtra("title", w.getTitle());
Grace Kloba83cdb2c2009-09-16 00:48:57 -07001349 i.putExtra("touch_icon_url", w.getTouchIconUrl());
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01001350 i.putExtra("thumbnail", createScreenshot(w));
Leon Scroggins1f005d32009-08-10 17:36:42 -04001351 startActivity(i);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001352 break;
1353
1354 case R.id.stop_reload_menu_id:
1355 if (mInLoad) {
1356 stopLoading();
1357 } else {
1358 getTopWindow().reload();
1359 }
1360 break;
1361
1362 case R.id.back_menu_id:
1363 getTopWindow().goBack();
1364 break;
1365
1366 case R.id.forward_menu_id:
1367 getTopWindow().goForward();
1368 break;
1369
1370 case R.id.close_menu_id:
1371 // Close the subwindow if it exists.
1372 if (mTabControl.getCurrentSubWindow() != null) {
1373 dismissSubWindow(mTabControl.getCurrentTab());
1374 break;
1375 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001376 closeCurrentWindow();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001377 break;
1378
1379 case R.id.homepage_menu_id:
Grace Kloba22ac16e2009-10-07 18:00:23 -07001380 Tab current = mTabControl.getCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001381 if (current != null) {
1382 dismissSubWindow(current);
Leon Scroggins92472e82010-02-17 16:32:28 -05001383 loadUrl(current.getWebView(), mSettings.getHomePage());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001384 }
1385 break;
1386
1387 case R.id.preferences_menu_id:
1388 Intent intent = new Intent(this,
1389 BrowserPreferencesPage.class);
Leon Scrogginsd5304942009-12-10 16:11:39 -05001390 intent.putExtra(BrowserPreferencesPage.CURRENT_PAGE,
1391 getTopWindow().getUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001392 startActivityForResult(intent, PREFERENCES_PAGE);
1393 break;
1394
1395 case R.id.find_menu_id:
1396 if (null == mFindDialog) {
1397 mFindDialog = new FindDialog(this);
1398 }
1399 mFindDialog.setWebView(getTopWindow());
1400 mFindDialog.show();
Cary Clark7d3ac792010-03-03 10:11:44 -05001401 getTopWindow().setFindIsUp(true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001402 mMenuState = EMPTY_MENU;
1403 break;
1404
1405 case R.id.select_text_id:
1406 getTopWindow().emulateShiftHeld();
1407 break;
1408 case R.id.page_info_menu_id:
1409 showPageInfo(mTabControl.getCurrentTab(), false);
1410 break;
1411
1412 case R.id.classic_history_menu_id:
Leon Scroggins30444232009-09-04 18:36:20 -04001413 bookmarksOrHistoryPicker(true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001414 break;
1415
Leon Scroggins96afcb12009-12-10 12:35:56 -05001416 case R.id.title_bar_share_page_url:
The Android Open Source Project0c908882009-03-03 19:32:16 -08001417 case R.id.share_page_menu_id:
Leon Scroggins96afcb12009-12-10 12:35:56 -05001418 Tab currentTab = mTabControl.getCurrentTab();
1419 if (null == currentTab) {
1420 mCanChord = false;
1421 return false;
1422 }
1423 currentTab.populatePickerData();
1424 sharePage(this, currentTab.getTitle(),
1425 currentTab.getUrl(), currentTab.getFavicon(),
1426 createScreenshot(currentTab.getWebView()));
The Android Open Source Project0c908882009-03-03 19:32:16 -08001427 break;
1428
1429 case R.id.dump_nav_menu_id:
1430 getTopWindow().debugDump();
1431 break;
1432
Andrei Popescu7a8b88b2010-02-02 00:30:38 +00001433 case R.id.dump_counters_menu_id:
1434 getTopWindow().dumpV8Counters();
1435 break;
1436
The Android Open Source Project0c908882009-03-03 19:32:16 -08001437 case R.id.zoom_in_menu_id:
1438 getTopWindow().zoomIn();
1439 break;
1440
1441 case R.id.zoom_out_menu_id:
1442 getTopWindow().zoomOut();
1443 break;
1444
1445 case R.id.view_downloads_menu_id:
1446 viewDownloads(null);
1447 break;
1448
The Android Open Source Project0c908882009-03-03 19:32:16 -08001449 case R.id.window_one_menu_id:
1450 case R.id.window_two_menu_id:
1451 case R.id.window_three_menu_id:
1452 case R.id.window_four_menu_id:
1453 case R.id.window_five_menu_id:
1454 case R.id.window_six_menu_id:
1455 case R.id.window_seven_menu_id:
1456 case R.id.window_eight_menu_id:
1457 {
1458 int menuid = item.getItemId();
1459 for (int id = 0; id < WINDOW_SHORTCUT_ID_ARRAY.length; id++) {
1460 if (WINDOW_SHORTCUT_ID_ARRAY[id] == menuid) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001461 Tab desiredTab = mTabControl.getTab(id);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001462 if (desiredTab != null &&
1463 desiredTab != mTabControl.getCurrentTab()) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001464 switchToTab(id);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001465 }
1466 break;
1467 }
1468 }
1469 }
1470 break;
1471
1472 default:
1473 if (!super.onOptionsItemSelected(item)) {
1474 return false;
1475 }
1476 // Otherwise fall through.
1477 }
1478 mCanChord = false;
1479 return true;
1480 }
1481
1482 public void closeFind() {
1483 mMenuState = R.id.MAIN_MENU;
1484 }
1485
Grace Kloba22ac16e2009-10-07 18:00:23 -07001486 @Override
1487 public boolean onPrepareOptionsMenu(Menu menu) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001488 // This happens when the user begins to hold down the menu key, so
1489 // allow them to chord to get a shortcut.
1490 mCanChord = true;
1491 // Note: setVisible will decide whether an item is visible; while
1492 // setEnabled() will decide whether an item is enabled, which also means
1493 // whether the matching shortcut key will function.
1494 super.onPrepareOptionsMenu(menu);
1495 switch (mMenuState) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001496 case EMPTY_MENU:
1497 if (mCurrentMenuState != mMenuState) {
1498 menu.setGroupVisible(R.id.MAIN_MENU, false);
1499 menu.setGroupEnabled(R.id.MAIN_MENU, false);
1500 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001501 }
1502 break;
1503 default:
1504 if (mCurrentMenuState != mMenuState) {
1505 menu.setGroupVisible(R.id.MAIN_MENU, true);
1506 menu.setGroupEnabled(R.id.MAIN_MENU, true);
1507 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001508 }
1509 final WebView w = getTopWindow();
1510 boolean canGoBack = false;
1511 boolean canGoForward = false;
1512 boolean isHome = false;
1513 if (w != null) {
1514 canGoBack = w.canGoBack();
1515 canGoForward = w.canGoForward();
1516 isHome = mSettings.getHomePage().equals(w.getUrl());
1517 }
1518 final MenuItem back = menu.findItem(R.id.back_menu_id);
1519 back.setEnabled(canGoBack);
1520
1521 final MenuItem home = menu.findItem(R.id.homepage_menu_id);
1522 home.setEnabled(!isHome);
1523
1524 menu.findItem(R.id.forward_menu_id)
1525 .setEnabled(canGoForward);
1526
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001527 menu.findItem(R.id.new_tab_menu_id).setEnabled(
Grace Kloba22ac16e2009-10-07 18:00:23 -07001528 mTabControl.canCreateNewTab());
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001529
The Android Open Source Project0c908882009-03-03 19:32:16 -08001530 // decide whether to show the share link option
1531 PackageManager pm = getPackageManager();
1532 Intent send = new Intent(Intent.ACTION_SEND);
1533 send.setType("text/plain");
1534 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1535 menu.findItem(R.id.share_page_menu_id).setVisible(ri != null);
1536
The Android Open Source Project0c908882009-03-03 19:32:16 -08001537 boolean isNavDump = mSettings.isNavDump();
1538 final MenuItem nav = menu.findItem(R.id.dump_nav_menu_id);
1539 nav.setVisible(isNavDump);
1540 nav.setEnabled(isNavDump);
Andrei Popescu7a8b88b2010-02-02 00:30:38 +00001541
1542 boolean showDebugSettings = mSettings.showDebugSettings();
1543 final MenuItem counter = menu.findItem(R.id.dump_counters_menu_id);
1544 counter.setVisible(showDebugSettings);
1545 counter.setEnabled(showDebugSettings);
1546
The Android Open Source Project0c908882009-03-03 19:32:16 -08001547 break;
1548 }
1549 mCurrentMenuState = mMenuState;
1550 return true;
1551 }
1552
1553 @Override
1554 public void onCreateContextMenu(ContextMenu menu, View v,
1555 ContextMenuInfo menuInfo) {
Leon Scroggins4e9f89b2010-02-22 16:54:14 -05001556 if (v instanceof TitleBar) {
1557 return;
1558 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001559 WebView webview = (WebView) v;
1560 WebView.HitTestResult result = webview.getHitTestResult();
1561 if (result == null) {
1562 return;
1563 }
1564
1565 int type = result.getType();
1566 if (type == WebView.HitTestResult.UNKNOWN_TYPE) {
1567 Log.w(LOGTAG,
1568 "We should not show context menu when nothing is touched");
1569 return;
1570 }
1571 if (type == WebView.HitTestResult.EDIT_TEXT_TYPE) {
1572 // let TextView handles context menu
1573 return;
1574 }
1575
1576 // Note, http://b/issue?id=1106666 is requesting that
1577 // an inflated menu can be used again. This is not available
1578 // yet, so inflate each time (yuk!)
1579 MenuInflater inflater = getMenuInflater();
1580 inflater.inflate(R.menu.browsercontext, menu);
1581
1582 // Show the correct menu group
1583 String extra = result.getExtra();
1584 menu.setGroupVisible(R.id.PHONE_MENU,
1585 type == WebView.HitTestResult.PHONE_TYPE);
1586 menu.setGroupVisible(R.id.EMAIL_MENU,
1587 type == WebView.HitTestResult.EMAIL_TYPE);
1588 menu.setGroupVisible(R.id.GEO_MENU,
1589 type == WebView.HitTestResult.GEO_TYPE);
1590 menu.setGroupVisible(R.id.IMAGE_MENU,
1591 type == WebView.HitTestResult.IMAGE_TYPE
1592 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1593 menu.setGroupVisible(R.id.ANCHOR_MENU,
1594 type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1595 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1596
1597 // Setup custom handling depending on the type
1598 switch (type) {
1599 case WebView.HitTestResult.PHONE_TYPE:
1600 menu.setHeaderTitle(Uri.decode(extra));
1601 menu.findItem(R.id.dial_context_menu_id).setIntent(
1602 new Intent(Intent.ACTION_VIEW, Uri
1603 .parse(WebView.SCHEME_TEL + extra)));
1604 Intent addIntent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
1605 addIntent.putExtra(Insert.PHONE, Uri.decode(extra));
Cary Clark5e335a32009-09-22 14:53:11 -04001606 addIntent.setType(ContactsContract.Contacts.CONTENT_ITEM_TYPE);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001607 menu.findItem(R.id.add_contact_context_menu_id).setIntent(
1608 addIntent);
1609 menu.findItem(R.id.copy_phone_context_menu_id).setOnMenuItemClickListener(
1610 new Copy(extra));
1611 break;
1612
1613 case WebView.HitTestResult.EMAIL_TYPE:
1614 menu.setHeaderTitle(extra);
1615 menu.findItem(R.id.email_context_menu_id).setIntent(
1616 new Intent(Intent.ACTION_VIEW, Uri
1617 .parse(WebView.SCHEME_MAILTO + extra)));
1618 menu.findItem(R.id.copy_mail_context_menu_id).setOnMenuItemClickListener(
1619 new Copy(extra));
1620 break;
1621
1622 case WebView.HitTestResult.GEO_TYPE:
1623 menu.setHeaderTitle(extra);
1624 menu.findItem(R.id.map_context_menu_id).setIntent(
1625 new Intent(Intent.ACTION_VIEW, Uri
1626 .parse(WebView.SCHEME_GEO
1627 + URLEncoder.encode(extra))));
1628 menu.findItem(R.id.copy_geo_context_menu_id).setOnMenuItemClickListener(
1629 new Copy(extra));
1630 break;
1631
1632 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1633 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
1634 TextView titleView = (TextView) LayoutInflater.from(this)
1635 .inflate(android.R.layout.browser_link_context_header,
1636 null);
1637 titleView.setText(extra);
1638 menu.setHeaderView(titleView);
1639 // decide whether to show the open link in new tab option
1640 menu.findItem(R.id.open_newtab_context_menu_id).setVisible(
Grace Kloba22ac16e2009-10-07 18:00:23 -07001641 mTabControl.canCreateNewTab());
Ben Murdochde353622009-10-12 10:29:00 +01001642 menu.findItem(R.id.bookmark_context_menu_id).setVisible(
1643 Bookmarks.urlHasAcceptableScheme(extra));
The Android Open Source Project0c908882009-03-03 19:32:16 -08001644 PackageManager pm = getPackageManager();
1645 Intent send = new Intent(Intent.ACTION_SEND);
1646 send.setType("text/plain");
1647 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1648 menu.findItem(R.id.share_link_context_menu_id).setVisible(ri != null);
1649 if (type == WebView.HitTestResult.SRC_ANCHOR_TYPE) {
1650 break;
1651 }
1652 // otherwise fall through to handle image part
1653 case WebView.HitTestResult.IMAGE_TYPE:
1654 if (type == WebView.HitTestResult.IMAGE_TYPE) {
1655 menu.setHeaderTitle(extra);
1656 }
1657 menu.findItem(R.id.view_image_context_menu_id).setIntent(
1658 new Intent(Intent.ACTION_VIEW, Uri.parse(extra)));
1659 menu.findItem(R.id.download_context_menu_id).
1660 setOnMenuItemClickListener(new Download(extra));
Ben Murdoch4f75ba22009-10-27 11:48:28 +00001661 menu.findItem(R.id.set_wallpaper_context_menu_id).
1662 setOnMenuItemClickListener(new SetAsWallpaper(extra));
The Android Open Source Project0c908882009-03-03 19:32:16 -08001663 break;
1664
1665 default:
1666 Log.w(LOGTAG, "We should not get here.");
1667 break;
1668 }
Leon Scrogginsb2b19f52009-10-09 16:10:00 -04001669 hideFakeTitleBar();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001670 }
1671
The Android Open Source Project0c908882009-03-03 19:32:16 -08001672 // Attach the given tab to the content view.
Grace Klobac928c302009-09-17 11:51:21 -07001673 // this should only be called for the current tab.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001674 private void attachTabToContentView(Tab t) {
Steve Block2bc69912009-07-30 14:45:13 +01001675 // Attach the container that contains the main WebView and any other UI
1676 // associated with the tab.
Patrick Scottd0119532009-09-17 08:00:31 -04001677 t.attachTabToContentView(mContentView);
Ben Murdochbff2d602009-07-01 20:19:05 +01001678
1679 if (mShouldShowErrorConsole) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001680 ErrorConsoleView errorConsole = t.getErrorConsole(true);
Ben Murdochbff2d602009-07-01 20:19:05 +01001681 if (errorConsole.numberOfErrors() == 0) {
1682 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
1683 } else {
1684 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
1685 }
1686
1687 mErrorConsoleContainer.addView(errorConsole,
Romain Guy15b8ec62010-01-08 15:06:43 -08001688 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
Ben Murdochbff2d602009-07-01 20:19:05 +01001689 ViewGroup.LayoutParams.WRAP_CONTENT));
1690 }
1691
Leon Scroggins39ab28e2009-09-02 21:20:30 -04001692 WebView view = t.getWebView();
Leon Scroggins55a5bc22009-09-04 17:00:08 -04001693 view.setEmbeddedTitleBar(mTitleBar);
Leon Scroggins58d56c62010-01-28 15:12:40 -05001694 if (t.isInVoiceSearchMode()) {
1695 showVoiceTitleBar(t.getVoiceDisplayTitle());
1696 } else {
1697 revertVoiceTitleBar();
1698 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001699 // Request focus on the top window.
1700 t.getTopWindow().requestFocus();
1701 }
1702
1703 // Attach a sub window to the main WebView of the given tab.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001704 void attachSubWindow(Tab t) {
Patrick Scottd0119532009-09-17 08:00:31 -04001705 t.attachSubWindow(mContentView);
1706 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001707 }
1708
1709 // Remove the given tab from the content view.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001710 private void removeTabFromContentView(Tab t) {
Steve Block2bc69912009-07-30 14:45:13 +01001711 // Remove the container that contains the main WebView.
Patrick Scottd0119532009-09-17 08:00:31 -04001712 t.removeTabFromContentView(mContentView);
Ben Murdochbff2d602009-07-01 20:19:05 +01001713
Grace Kloba22ac16e2009-10-07 18:00:23 -07001714 ErrorConsoleView errorConsole = t.getErrorConsole(false);
1715 if (errorConsole != null) {
1716 mErrorConsoleContainer.removeView(errorConsole);
Ben Murdochbff2d602009-07-01 20:19:05 +01001717 }
1718
Leon Scroggins39ab28e2009-09-02 21:20:30 -04001719 WebView view = t.getWebView();
Leon Scrogginsbb85b902009-09-14 19:27:20 -04001720 if (view != null) {
1721 view.setEmbeddedTitleBar(null);
1722 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001723 }
1724
1725 // Remove the sub window if it exists. Also called by TabControl when the
1726 // user clicks the 'X' to dismiss a sub window.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001727 /* package */ void dismissSubWindow(Tab t) {
Patrick Scottd0119532009-09-17 08:00:31 -04001728 t.removeSubWindow(mContentView);
Grace Kloba22ac16e2009-10-07 18:00:23 -07001729 // dismiss the subwindow. This will destroy the WebView.
1730 t.dismissSubWindow();
Patrick Scottd0119532009-09-17 08:00:31 -04001731 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001732 }
1733
Leon Scroggins1f005d32009-08-10 17:36:42 -04001734 // A wrapper function of {@link #openTabAndShow(UrlData, boolean, String)}
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07001735 // that accepts url as string.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001736 private Tab openTabAndShow(String url, boolean closeOnExit, String appId) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001737 return openTabAndShow(new UrlData(url), closeOnExit, appId);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001738 }
1739
1740 // This method does a ton of stuff. It will attempt to create a new tab
1741 // if we haven't reached MAX_TABS. Otherwise it uses the current tab. If
Leon Scroggins1f005d32009-08-10 17:36:42 -04001742 // url isn't null, it will load the given url.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001743 /* package */Tab openTabAndShow(UrlData urlData, boolean closeOnExit,
1744 String appId) {
1745 final Tab currentTab = mTabControl.getCurrentTab();
1746 if (mTabControl.canCreateNewTab()) {
1747 final Tab tab = mTabControl.createNewTab(closeOnExit, appId,
1748 urlData.mUrl);
Leon Scroggins1f005d32009-08-10 17:36:42 -04001749 WebView webview = tab.getWebView();
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001750 // If the last tab was removed from the active tabs page, currentTab
1751 // will be null.
1752 if (currentTab != null) {
1753 removeTabFromContentView(currentTab);
1754 }
Patrick Scott8bbd69f2009-08-14 13:35:53 -04001755 // We must set the new tab as the current tab to reflect the old
1756 // animation behavior.
1757 mTabControl.setCurrentTab(tab);
Grace Klobaeb6eef42009-09-15 17:56:32 -07001758 attachTabToContentView(tab);
Leon Scroggins160a7e72009-08-14 18:28:01 -04001759 if (!urlData.isEmpty()) {
Patrick Scott9d53da02010-02-19 10:19:01 -05001760 loadUrlDataIn(tab, urlData);
Leon Scroggins1f005d32009-08-10 17:36:42 -04001761 }
1762 return tab;
1763 } else {
1764 // Get rid of the subwindow if it exists
1765 dismissSubWindow(currentTab);
1766 if (!urlData.isEmpty()) {
1767 // Load the given url.
Patrick Scott9d53da02010-02-19 10:19:01 -05001768 loadUrlDataIn(currentTab, urlData);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001769 }
Leon Scroggins58d56c62010-01-28 15:12:40 -05001770 return currentTab;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001771 }
1772 }
1773
Grace Kloba22ac16e2009-10-07 18:00:23 -07001774 private Tab openTab(String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001775 if (mSettings.openInBackground()) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001776 Tab t = mTabControl.createNewTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001777 if (t != null) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001778 WebView view = t.getWebView();
Leon Scroggins92472e82010-02-17 16:32:28 -05001779 loadUrl(view, url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001780 }
Grace Klobac9181842009-04-14 08:53:22 -07001781 return t;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001782 } else {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001783 return openTabAndShow(url, false, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001784 }
1785 }
1786
1787 private class Copy implements OnMenuItemClickListener {
1788 private CharSequence mText;
1789
1790 public boolean onMenuItemClick(MenuItem item) {
1791 copy(mText);
1792 return true;
1793 }
1794
1795 public Copy(CharSequence toCopy) {
1796 mText = toCopy;
1797 }
1798 }
1799
1800 private class Download implements OnMenuItemClickListener {
1801 private String mText;
1802
1803 public boolean onMenuItemClick(MenuItem item) {
1804 onDownloadStartNoStream(mText, null, null, null, -1);
1805 return true;
1806 }
1807
1808 public Download(String toDownload) {
1809 mText = toDownload;
1810 }
1811 }
1812
Ben Murdoch4f75ba22009-10-27 11:48:28 +00001813 private class SetAsWallpaper extends Thread implements
1814 OnMenuItemClickListener, DialogInterface.OnCancelListener {
1815 private URL mUrl;
1816 private ProgressDialog mWallpaperProgress;
1817 private boolean mCanceled = false;
1818
1819 public SetAsWallpaper(String url) {
1820 try {
1821 mUrl = new URL(url);
1822 } catch (MalformedURLException e) {
1823 mUrl = null;
1824 }
1825 }
1826
1827 public void onCancel(DialogInterface dialog) {
1828 mCanceled = true;
1829 }
1830
1831 public boolean onMenuItemClick(MenuItem item) {
1832 if (mUrl != null) {
1833 // The user may have tried to set a image with a large file size as their
1834 // background so it may take a few moments to perform the operation. Display
1835 // a progress spinner while it is working.
1836 mWallpaperProgress = new ProgressDialog(BrowserActivity.this);
1837 mWallpaperProgress.setIndeterminate(true);
1838 mWallpaperProgress.setMessage(getText(R.string.progress_dialog_setting_wallpaper));
1839 mWallpaperProgress.setCancelable(true);
1840 mWallpaperProgress.setOnCancelListener(this);
1841 mWallpaperProgress.show();
1842 start();
1843 }
1844 return true;
1845 }
1846
1847 public void run() {
1848 Drawable oldWallpaper = BrowserActivity.this.getWallpaper();
1849 try {
1850 // TODO: This will cause the resource to be downloaded again, when we
1851 // should in most cases be able to grab it from the cache. To fix this
1852 // we should query WebCore to see if we can access a cached version and
1853 // instead open an input stream on that. This pattern could also be used
1854 // in the download manager where the same problem exists.
1855 InputStream inputstream = mUrl.openStream();
1856 if (inputstream != null) {
1857 setWallpaper(inputstream);
1858 }
1859 } catch (IOException e) {
1860 Log.e(LOGTAG, "Unable to set new wallpaper");
1861 // Act as though the user canceled the operation so we try to
1862 // restore the old wallpaper.
1863 mCanceled = true;
1864 }
1865
1866 if (mCanceled) {
1867 // Restore the old wallpaper if the user cancelled whilst we were setting
1868 // the new wallpaper.
1869 int width = oldWallpaper.getIntrinsicWidth();
1870 int height = oldWallpaper.getIntrinsicHeight();
1871 Bitmap bm = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
1872 Canvas canvas = new Canvas(bm);
1873 oldWallpaper.setBounds(0, 0, width, height);
1874 oldWallpaper.draw(canvas);
1875 try {
1876 setWallpaper(bm);
1877 } catch (IOException e) {
1878 Log.e(LOGTAG, "Unable to restore old wallpaper.");
1879 }
1880 mCanceled = false;
1881 }
1882
1883 if (mWallpaperProgress.isShowing()) {
1884 mWallpaperProgress.dismiss();
1885 }
1886 }
1887 }
1888
The Android Open Source Project0c908882009-03-03 19:32:16 -08001889 private void copy(CharSequence text) {
1890 try {
1891 IClipboard clip = IClipboard.Stub.asInterface(ServiceManager.getService("clipboard"));
1892 if (clip != null) {
1893 clip.setClipboardText(text);
1894 }
1895 } catch (android.os.RemoteException e) {
1896 Log.e(LOGTAG, "Copy failed", e);
1897 }
1898 }
1899
1900 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08001901 * Resets the browser title-view to whatever it must be
1902 * (for example, if we had a loading error)
1903 * When we have a new page, we call resetTitle, when we
1904 * have to reset the titlebar to whatever it used to be
1905 * (for example, if the user chose to stop loading), we
1906 * call resetTitleAndRevertLockIcon.
1907 */
1908 /* package */ void resetTitleAndRevertLockIcon() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001909 mTabControl.getCurrentTab().revertLockIcon();
1910 updateLockIconToLatest();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001911 resetTitleIconAndProgress();
1912 }
1913
1914 /**
1915 * Reset the title, favicon, and progress.
1916 */
1917 private void resetTitleIconAndProgress() {
1918 WebView current = mTabControl.getCurrentWebView();
1919 if (current == null) {
1920 return;
1921 }
1922 resetTitleAndIcon(current);
1923 int progress = current.getProgress();
Grace Kloba22ac16e2009-10-07 18:00:23 -07001924 current.getWebChromeClient().onProgressChanged(current, progress);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001925 }
1926
1927 // Reset the title and the icon based on the given item.
1928 private void resetTitleAndIcon(WebView view) {
1929 WebHistoryItem item = view.copyBackForwardList().getCurrentItem();
1930 if (item != null) {
Leon Scroggins68579392009-09-15 15:31:54 -04001931 setUrlTitle(item.getUrl(), item.getTitle());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001932 setFavicon(item.getFavicon());
1933 } else {
Leon Scroggins68579392009-09-15 15:31:54 -04001934 setUrlTitle(null, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001935 setFavicon(null);
1936 }
1937 }
1938
1939 /**
1940 * Sets a title composed of the URL and the title string.
1941 * @param url The URL of the site being loaded.
1942 * @param title The title of the site being loaded.
1943 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07001944 void setUrlTitle(String url, String title) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001945 mUrl = url;
1946 mTitle = title;
1947
Leon Scroggins58d56c62010-01-28 15:12:40 -05001948 // If we are in voice search mode, the title has already been set.
1949 if (mTabControl.getCurrentTab().isInVoiceSearchMode()) return;
1950 mTitleBar.setDisplayTitle(url);
1951 mFakeTitleBar.setDisplayTitle(url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001952 }
1953
1954 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08001955 * @param url The URL to build a title version of the URL from.
1956 * @return The title version of the URL or null if fails.
1957 * The title version of the URL can be either the URL hostname,
1958 * or the hostname with an "https://" prefix (for secure URLs),
1959 * or an empty string if, for example, the URL in question is a
1960 * file:// URL with no hostname.
1961 */
Leon Scroggins32e14a62009-06-11 10:26:34 -04001962 /* package */ static String buildTitleUrl(String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001963 String titleUrl = null;
1964
1965 if (url != null) {
1966 try {
1967 // parse the url string
1968 URL urlObj = new URL(url);
1969 if (urlObj != null) {
1970 titleUrl = "";
1971
1972 String protocol = urlObj.getProtocol();
1973 String host = urlObj.getHost();
1974
1975 if (host != null && 0 < host.length()) {
1976 titleUrl = host;
1977 if (protocol != null) {
1978 // if a secure site, add an "https://" prefix!
1979 if (protocol.equalsIgnoreCase("https")) {
1980 titleUrl = protocol + "://" + host;
1981 }
1982 }
1983 }
1984 }
1985 } catch (MalformedURLException e) {}
1986 }
1987
1988 return titleUrl;
1989 }
1990
1991 // Set the favicon in the title bar.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001992 void setFavicon(Bitmap icon) {
Leon Scroggins68579392009-09-15 15:31:54 -04001993 mTitleBar.setFavicon(icon);
Leon Scrogginsfe87bd32009-10-06 10:10:00 -04001994 mFakeTitleBar.setFavicon(icon);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001995 }
1996
1997 /**
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001998 * Close the tab, remove its associated title bar, and adjust mTabControl's
1999 * current tab to a valid value.
Leon Scroggins1f005d32009-08-10 17:36:42 -04002000 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07002001 /* package */ void closeTab(Tab t) {
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002002 int currentIndex = mTabControl.getCurrentIndex();
2003 int removeIndex = mTabControl.getTabIndex(t);
Leon Scroggins1f005d32009-08-10 17:36:42 -04002004 mTabControl.removeTab(t);
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002005 if (currentIndex >= removeIndex && currentIndex != 0) {
2006 currentIndex--;
2007 }
2008 mTabControl.setCurrentTab(mTabControl.getTab(currentIndex));
Andrei Popescua5bf1de2009-09-23 16:39:23 +01002009 resetTitleIconAndProgress();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002010 }
2011
Leon Scrogginsdcc5eeb2010-02-23 17:26:37 -05002012 /* package */ void goBackOnePageOrQuit() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002013 Tab current = mTabControl.getCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002014 if (current == null) {
2015 /*
2016 * Instead of finishing the activity, simply push this to the back
2017 * of the stack and let ActivityManager to choose the foreground
2018 * activity. As BrowserActivity is singleTask, it will be always the
2019 * root of the task. So we can use either true or false for
2020 * moveTaskToBack().
2021 */
2022 moveTaskToBack(true);
Grace Kloba00d85e72009-09-23 18:50:05 -07002023 return;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002024 }
2025 WebView w = current.getWebView();
2026 if (w.canGoBack()) {
2027 w.goBack();
2028 } else {
2029 // Check to see if we are closing a window that was created by
2030 // another window. If so, we switch back to that window.
Grace Kloba22ac16e2009-10-07 18:00:23 -07002031 Tab parent = current.getParentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002032 if (parent != null) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04002033 switchToTab(mTabControl.getTabIndex(parent));
2034 // Now we close the other tab
2035 closeTab(current);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002036 } else {
2037 if (current.closeOnExit()) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002038 // force the tab's inLoad() to be false as we are going to
2039 // either finish the activity or remove the tab. This will
2040 // ensure pauseWebViewTimers() taking action.
2041 mTabControl.getCurrentTab().clearInLoad();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002042 if (mTabControl.getTabCount() == 1) {
2043 finish();
2044 return;
2045 }
Mike Reed7bfa63b2009-05-28 11:08:32 -04002046 // call pauseWebViewTimers() now, we won't be able to call
2047 // it in onPause() as the WebView won't be valid.
Grace Klobaec1b5ad2009-08-18 08:42:32 -07002048 // Temporarily change mActivityInPause to be true as
2049 // pauseWebViewTimers() will do nothing if mActivityInPause
2050 // is false.
Grace Kloba918e1d72009-08-13 14:55:06 -07002051 boolean savedState = mActivityInPause;
2052 if (savedState) {
Grace Klobaec1b5ad2009-08-18 08:42:32 -07002053 Log.e(LOGTAG, "BrowserActivity is already paused "
2054 + "while handing goBackOnePageOrQuit.");
Grace Kloba918e1d72009-08-13 14:55:06 -07002055 }
2056 mActivityInPause = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -04002057 pauseWebViewTimers();
Grace Kloba918e1d72009-08-13 14:55:06 -07002058 mActivityInPause = savedState;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002059 removeTabFromContentView(current);
2060 mTabControl.removeTab(current);
2061 }
2062 /*
2063 * Instead of finishing the activity, simply push this to the back
2064 * of the stack and let ActivityManager to choose the foreground
2065 * activity. As BrowserActivity is singleTask, it will be always the
2066 * root of the task. So we can use either true or false for
2067 * moveTaskToBack().
2068 */
2069 moveTaskToBack(true);
2070 }
2071 }
2072 }
2073
Grace Kloba22ac16e2009-10-07 18:00:23 -07002074 boolean isMenuDown() {
2075 return mMenuIsDown;
2076 }
2077
Grace Kloba5942df02009-09-18 11:48:29 -07002078 @Override
2079 public boolean onKeyDown(int keyCode, KeyEvent event) {
Leon Scrogginsf65b50d2009-12-08 10:44:28 -05002080 // Even if MENU is already held down, we need to call to super to open
2081 // the IME on long press.
2082 if (KeyEvent.KEYCODE_MENU == keyCode) {
2083 mMenuIsDown = true;
2084 return super.onKeyDown(keyCode, event);
2085 }
Grace Kloba5942df02009-09-18 11:48:29 -07002086 // The default key mode is DEFAULT_KEYS_SEARCH_LOCAL. As the MENU is
2087 // still down, we don't want to trigger the search. Pretend to consume
2088 // the key and do nothing.
2089 if (mMenuIsDown) return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002090
Grace Kloba5942df02009-09-18 11:48:29 -07002091 switch(keyCode) {
Grace Kloba5942df02009-09-18 11:48:29 -07002092 case KeyEvent.KEYCODE_SPACE:
Grace Klobada0fe552009-09-22 18:17:24 -07002093 // WebView/WebTextView handle the keys in the KeyDown. As
2094 // the Activity's shortcut keys are only handled when WebView
2095 // doesn't, have to do it in onKeyDown instead of onKeyUp.
2096 if (event.isShiftPressed()) {
2097 getTopWindow().pageUp(false);
2098 } else {
2099 getTopWindow().pageDown(false);
2100 }
Grace Kloba5942df02009-09-18 11:48:29 -07002101 return true;
2102 case KeyEvent.KEYCODE_BACK:
2103 if (event.getRepeatCount() == 0) {
2104 event.startTracking();
2105 return true;
2106 } else if (mCustomView == null && mActiveTabsPage == null
2107 && event.isLongPress()) {
2108 bookmarksOrHistoryPicker(true);
2109 return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002110 }
Grace Kloba5942df02009-09-18 11:48:29 -07002111 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002112 }
Grace Kloba5942df02009-09-18 11:48:29 -07002113 return super.onKeyDown(keyCode, event);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002114 }
2115
Grace Kloba5942df02009-09-18 11:48:29 -07002116 @Override
2117 public boolean onKeyUp(int keyCode, KeyEvent event) {
2118 switch(keyCode) {
2119 case KeyEvent.KEYCODE_MENU:
2120 mMenuIsDown = false;
2121 break;
Grace Kloba5942df02009-09-18 11:48:29 -07002122 case KeyEvent.KEYCODE_BACK:
2123 if (event.isTracking() && !event.isCanceled()) {
2124 if (mCustomView != null) {
2125 // if a custom view is showing, hide it
Grace Kloba22ac16e2009-10-07 18:00:23 -07002126 mTabControl.getCurrentWebView().getWebChromeClient()
2127 .onHideCustomView();
Grace Kloba5942df02009-09-18 11:48:29 -07002128 } else if (mActiveTabsPage != null) {
2129 // if tab page is showing, hide it
2130 removeActiveTabPage(true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002131 } else {
Grace Kloba5942df02009-09-18 11:48:29 -07002132 WebView subwindow = mTabControl.getCurrentSubWindow();
2133 if (subwindow != null) {
2134 if (subwindow.canGoBack()) {
2135 subwindow.goBack();
2136 } else {
2137 dismissSubWindow(mTabControl.getCurrentTab());
2138 }
2139 } else {
2140 goBackOnePageOrQuit();
2141 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002142 }
Grace Kloba5942df02009-09-18 11:48:29 -07002143 return true;
2144 }
2145 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002146 }
Grace Kloba5942df02009-09-18 11:48:29 -07002147 return super.onKeyUp(keyCode, event);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002148 }
2149
Leon Scroggins68579392009-09-15 15:31:54 -04002150 /* package */ void stopLoading() {
Ben Murdochb7cc8b42009-09-28 10:59:09 +01002151 mDidStopLoad = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002152 resetTitleAndRevertLockIcon();
2153 WebView w = getTopWindow();
2154 w.stopLoading();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002155 // FIXME: before refactor, it is using mWebViewClient. So I keep the
2156 // same logic here. But for subwindow case, should we call into the main
2157 // WebView's onPageFinished as we never call its onPageStarted and if
2158 // the page finishes itself, we don't call onPageFinished.
2159 mTabControl.getCurrentWebView().getWebViewClient().onPageFinished(w,
2160 w.getUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08002161
2162 cancelStopToast();
2163 mStopToast = Toast
2164 .makeText(this, R.string.stopping, Toast.LENGTH_SHORT);
2165 mStopToast.show();
2166 }
2167
Grace Kloba22ac16e2009-10-07 18:00:23 -07002168 boolean didUserStopLoading() {
2169 return mDidStopLoad;
2170 }
2171
The Android Open Source Project0c908882009-03-03 19:32:16 -08002172 private void cancelStopToast() {
2173 if (mStopToast != null) {
2174 mStopToast.cancel();
2175 mStopToast = null;
2176 }
2177 }
2178
Grace Kloba22ac16e2009-10-07 18:00:23 -07002179 // called by a UI or non-UI thread to post the message
2180 public void postMessage(int what, int arg1, int arg2, Object obj,
2181 long delayMillis) {
2182 mHandler.sendMessageDelayed(mHandler.obtainMessage(what, arg1, arg2,
2183 obj), delayMillis);
2184 }
2185
2186 // called by a UI or non-UI thread to remove the message
2187 void removeMessages(int what, Object object) {
2188 mHandler.removeMessages(what, object);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002189 }
2190
2191 // public message ids
2192 public final static int LOAD_URL = 1001;
2193 public final static int STOP_LOAD = 1002;
2194
2195 // Message Ids
2196 private static final int FOCUS_NODE_HREF = 102;
Grace Kloba92c18a52009-07-31 23:48:32 -07002197 private static final int RELEASE_WAKELOCK = 107;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002198
Grace Kloba22ac16e2009-10-07 18:00:23 -07002199 static final int UPDATE_BOOKMARK_THUMBNAIL = 108;
Ben Murdoch2694e232009-09-29 09:41:11 +01002200
The Android Open Source Project0c908882009-03-03 19:32:16 -08002201 // Private handler for handling javascript and saving passwords
2202 private Handler mHandler = new Handler() {
2203
2204 public void handleMessage(Message msg) {
2205 switch (msg.what) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002206 case FOCUS_NODE_HREF:
Ben Murdoch2694e232009-09-29 09:41:11 +01002207 {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002208 String url = (String) msg.getData().get("url");
Ben Murdoch90d088c2009-11-17 18:14:04 +00002209 String title = (String) msg.getData().get("title");
The Android Open Source Project0c908882009-03-03 19:32:16 -08002210 if (url == null || url.length() == 0) {
2211 break;
2212 }
2213 HashMap focusNodeMap = (HashMap) msg.obj;
2214 WebView view = (WebView) focusNodeMap.get("webview");
2215 // Only apply the action if the top window did not change.
2216 if (getTopWindow() != view) {
2217 break;
2218 }
2219 switch (msg.arg1) {
2220 case R.id.open_context_menu_id:
2221 case R.id.view_image_context_menu_id:
Leon Scroggins92472e82010-02-17 16:32:28 -05002222 loadUrlFromContext(getTopWindow(), url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002223 break;
2224 case R.id.open_newtab_context_menu_id:
Grace Kloba22ac16e2009-10-07 18:00:23 -07002225 final Tab parent = mTabControl.getCurrentTab();
2226 final Tab newTab = openTab(url);
Grace Klobac9181842009-04-14 08:53:22 -07002227 if (newTab != parent) {
2228 parent.addChildTab(newTab);
2229 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002230 break;
2231 case R.id.bookmark_context_menu_id:
2232 Intent intent = new Intent(BrowserActivity.this,
2233 AddBookmarkPage.class);
2234 intent.putExtra("url", url);
Ben Murdoch90d088c2009-11-17 18:14:04 +00002235 intent.putExtra("title", title);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002236 startActivity(intent);
2237 break;
2238 case R.id.share_link_context_menu_id:
Leon Scroggins96afcb12009-12-10 12:35:56 -05002239 // See if this site has been visited before
2240 StringBuilder sb = new StringBuilder(
2241 Browser.BookmarkColumns.URL + " = ");
2242 DatabaseUtils.appendEscapedSQLString(sb, url);
2243 Cursor c = mResolver.query(Browser.BOOKMARKS_URI,
2244 Browser.HISTORY_PROJECTION,
2245 sb.toString(),
2246 null,
2247 null);
2248 if (c.moveToFirst()) {
2249 // The site has been visited before, so grab the
2250 // info from the database.
2251 Bitmap favicon = null;
2252 Bitmap thumbnail = null;
2253 String linkTitle = c.getString(Browser.
2254 HISTORY_PROJECTION_TITLE_INDEX);
2255 byte[] data = c.getBlob(Browser.
2256 HISTORY_PROJECTION_FAVICON_INDEX);
2257 if (data != null) {
2258 favicon = BitmapFactory.decodeByteArray(
2259 data, 0, data.length);
2260 }
2261 data = c.getBlob(Browser.
2262 HISTORY_PROJECTION_THUMBNAIL_INDEX);
2263 if (data != null) {
2264 thumbnail = BitmapFactory.decodeByteArray(
2265 data, 0, data.length);
2266 }
2267 sharePage(BrowserActivity.this,
2268 linkTitle, url, favicon, thumbnail);
2269 } else {
2270 Browser.sendString(BrowserActivity.this, url,
2271 getString(
2272 R.string.choosertitle_sharevia));
2273 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002274 break;
2275 case R.id.copy_link_context_menu_id:
2276 copy(url);
2277 break;
2278 case R.id.save_link_context_menu_id:
2279 case R.id.download_context_menu_id:
2280 onDownloadStartNoStream(url, null, null, null, -1);
2281 break;
2282 }
2283 break;
Ben Murdoch2694e232009-09-29 09:41:11 +01002284 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002285
2286 case LOAD_URL:
Leon Scroggins92472e82010-02-17 16:32:28 -05002287 loadUrlFromContext(getTopWindow(), (String) msg.obj);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002288 break;
2289
2290 case STOP_LOAD:
2291 stopLoading();
2292 break;
2293
The Android Open Source Project0c908882009-03-03 19:32:16 -08002294 case RELEASE_WAKELOCK:
2295 if (mWakeLock.isHeld()) {
2296 mWakeLock.release();
Grace Kloba5d0e02e2009-10-05 15:15:36 -07002297 // if we reach here, Browser should be still in the
2298 // background loading after WAKELOCK_TIMEOUT (5-min).
2299 // To avoid burning the battery, stop loading.
2300 mTabControl.stopAllLoading();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002301 }
2302 break;
Ben Murdoch2694e232009-09-29 09:41:11 +01002303
2304 case UPDATE_BOOKMARK_THUMBNAIL:
2305 WebView view = (WebView) msg.obj;
2306 if (view != null) {
2307 updateScreenshot(view);
2308 }
2309 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002310 }
2311 }
2312 };
2313
Leon Scroggins96afcb12009-12-10 12:35:56 -05002314 /**
2315 * Share a page, providing the title, url, favicon, and a screenshot. Uses
2316 * an {@link Intent} to launch the Activity chooser.
2317 * @param c Context used to launch a new Activity.
2318 * @param title Title of the page. Stored in the Intent with
Paul Westbrook03e6d392010-02-12 10:33:29 -08002319 * {@link Intent#EXTRA_SUBJECT}
Leon Scroggins96afcb12009-12-10 12:35:56 -05002320 * @param url URL of the page. Stored in the Intent with
2321 * {@link Intent#EXTRA_TEXT}
2322 * @param favicon Bitmap of the favicon for the page. Stored in the Intent
2323 * with {@link Browser#EXTRA_SHARE_FAVICON}
2324 * @param screenshot Bitmap of a screenshot of the page. Stored in the
2325 * Intent with {@link Browser#EXTRA_SHARE_SCREENSHOT}
2326 */
2327 public static final void sharePage(Context c, String title, String url,
2328 Bitmap favicon, Bitmap screenshot) {
2329 Intent send = new Intent(Intent.ACTION_SEND);
2330 send.setType("text/plain");
2331 send.putExtra(Intent.EXTRA_TEXT, url);
Paul Westbrook03e6d392010-02-12 10:33:29 -08002332 send.putExtra(Intent.EXTRA_SUBJECT, title);
Leon Scroggins96afcb12009-12-10 12:35:56 -05002333 send.putExtra(Browser.EXTRA_SHARE_FAVICON, favicon);
2334 send.putExtra(Browser.EXTRA_SHARE_SCREENSHOT, screenshot);
2335 try {
2336 c.startActivity(Intent.createChooser(send, c.getString(
2337 R.string.choosertitle_sharevia)));
2338 } catch(android.content.ActivityNotFoundException ex) {
2339 // if no app handles it, do nothing
2340 }
2341 }
2342
Leon Scroggins89c6d362009-07-15 16:54:37 -04002343 private void updateScreenshot(WebView view) {
2344 // If this is a bookmarked site, add a screenshot to the database.
2345 // FIXME: When should we update? Every time?
2346 // FIXME: Would like to make sure there is actually something to
2347 // draw, but the API for that (WebViewCore.pictureReady()) is not
2348 // currently accessible here.
Ben Murdochaac7aa62009-09-17 16:57:40 +01002349
Patrick Scott3918d442009-08-04 13:22:29 -04002350 ContentResolver cr = getContentResolver();
2351 final Cursor c = BrowserBookmarksAdapter.queryBookmarksForUrl(
Ben Murdochaac7aa62009-09-17 16:57:40 +01002352 cr, view.getOriginalUrl(), view.getUrl(), true);
Patrick Scott3918d442009-08-04 13:22:29 -04002353 if (c != null) {
Leon Scroggins89c6d362009-07-15 16:54:37 -04002354 boolean succeed = c.moveToFirst();
2355 ContentValues values = null;
2356 while (succeed) {
2357 if (values == null) {
2358 final ByteArrayOutputStream os
2359 = new ByteArrayOutputStream();
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002360 Bitmap bm = createScreenshot(view);
Leon Scroggins45800572009-09-29 16:38:47 -04002361 if (bm == null) {
2362 c.close();
2363 return;
2364 }
Leon Scroggins89c6d362009-07-15 16:54:37 -04002365 bm.compress(Bitmap.CompressFormat.PNG, 100, os);
2366 values = new ContentValues();
2367 values.put(Browser.BookmarkColumns.THUMBNAIL,
2368 os.toByteArray());
2369 }
2370 cr.update(ContentUris.withAppendedId(Browser.BOOKMARKS_URI,
2371 c.getInt(0)), values, null, null);
2372 succeed = c.moveToNext();
2373 }
2374 c.close();
2375 }
2376 }
2377
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002378 /**
Leon Scrogginsf8551612009-09-24 16:06:02 -04002379 * Values for the size of the thumbnail created when taking a screenshot.
2380 * Lazily initialized. Instead of using these directly, use
2381 * getDesiredThumbnailWidth() or getDesiredThumbnailHeight().
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002382 */
Leon Scrogginsf8551612009-09-24 16:06:02 -04002383 private static int THUMBNAIL_WIDTH = 0;
2384 private static int THUMBNAIL_HEIGHT = 0;
2385
2386 /**
2387 * Return the desired width for thumbnail screenshots, which are stored in
2388 * the database, and used on the bookmarks screen.
2389 * @param context Context for finding out the density of the screen.
2390 * @return int desired width for thumbnail screenshot.
2391 */
2392 /* package */ static int getDesiredThumbnailWidth(Context context) {
2393 if (THUMBNAIL_WIDTH == 0) {
2394 float density = context.getResources().getDisplayMetrics().density;
2395 THUMBNAIL_WIDTH = (int) (90 * density);
2396 THUMBNAIL_HEIGHT = (int) (80 * density);
2397 }
2398 return THUMBNAIL_WIDTH;
2399 }
2400
2401 /**
2402 * Return the desired height for thumbnail screenshots, which are stored in
2403 * the database, and used on the bookmarks screen.
2404 * @param context Context for finding out the density of the screen.
2405 * @return int desired height for thumbnail screenshot.
2406 */
2407 /* package */ static int getDesiredThumbnailHeight(Context context) {
2408 // To ensure that they are both initialized.
2409 getDesiredThumbnailWidth(context);
2410 return THUMBNAIL_HEIGHT;
2411 }
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002412
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002413 private Bitmap createScreenshot(WebView view) {
2414 Picture thumbnail = view.capturePicture();
Leon Scroggins45800572009-09-29 16:38:47 -04002415 if (thumbnail == null) {
2416 return null;
2417 }
Leon Scrogginsf8551612009-09-24 16:06:02 -04002418 Bitmap bm = Bitmap.createBitmap(getDesiredThumbnailWidth(this),
2419 getDesiredThumbnailHeight(this), Bitmap.Config.ARGB_4444);
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002420 Canvas canvas = new Canvas(bm);
2421 // May need to tweak these values to determine what is the
2422 // best scale factor
Ben Murdoch2694e232009-09-29 09:41:11 +01002423 int thumbnailWidth = thumbnail.getWidth();
Ben Murdochae59c3f2009-10-20 18:30:28 +01002424 int thumbnailHeight = thumbnail.getHeight();
2425 float scaleFactorX = 1.0f;
2426 float scaleFactorY = 1.0f;
Ben Murdoch2694e232009-09-29 09:41:11 +01002427 if (thumbnailWidth > 0) {
Ben Murdochae59c3f2009-10-20 18:30:28 +01002428 scaleFactorX = (float) getDesiredThumbnailWidth(this) /
Ben Murdoch2694e232009-09-29 09:41:11 +01002429 (float)thumbnailWidth;
Ben Murdochae59c3f2009-10-20 18:30:28 +01002430 } else {
2431 return null;
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002432 }
Ben Murdochae59c3f2009-10-20 18:30:28 +01002433
2434 if (view.getWidth() > view.getHeight() &&
2435 thumbnailHeight < view.getHeight() && thumbnailHeight > 0) {
2436 // If the device is in landscape and the page is shorter
2437 // than the height of the view, stretch the thumbnail to fill the
2438 // space.
2439 scaleFactorY = (float) getDesiredThumbnailHeight(this) /
2440 (float)thumbnailHeight;
2441 } else {
2442 // In the portrait case, this looks nice.
2443 scaleFactorY = scaleFactorX;
2444 }
2445
2446 canvas.scale(scaleFactorX, scaleFactorY);
2447
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002448 thumbnail.draw(canvas);
2449 return bm;
2450 }
2451
The Android Open Source Project0c908882009-03-03 19:32:16 -08002452 // -------------------------------------------------------------------------
Grace Kloba22ac16e2009-10-07 18:00:23 -07002453 // Helper function for WebViewClient.
The Android Open Source Project0c908882009-03-03 19:32:16 -08002454 //-------------------------------------------------------------------------
2455
2456 // Use in overrideUrlLoading
2457 /* package */ final static String SCHEME_WTAI = "wtai://wp/";
2458 /* package */ final static String SCHEME_WTAI_MC = "wtai://wp/mc;";
2459 /* package */ final static String SCHEME_WTAI_SD = "wtai://wp/sd;";
2460 /* package */ final static String SCHEME_WTAI_AP = "wtai://wp/ap;";
2461
Leon Scroggins92472e82010-02-17 16:32:28 -05002462 // Keep this initial progress in sync with initialProgressValue (* 100)
2463 // in ProgressTracker.cpp
2464 private final static int INITIAL_PROGRESS = 10;
2465
Grace Kloba22ac16e2009-10-07 18:00:23 -07002466 void onPageStarted(WebView view, String url, Bitmap favicon) {
2467 // when BrowserActivity just starts, onPageStarted may be called before
2468 // onResume as it is triggered from onCreate. Call resumeWebViewTimers
2469 // to start the timer. As we won't switch tabs while an activity is in
2470 // pause state, we can ensure calling resume and pause in pair.
2471 if (mActivityInPause) resumeWebViewTimers();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002472
Grace Kloba22ac16e2009-10-07 18:00:23 -07002473 resetLockIcon(url);
2474 setUrlTitle(url, null);
2475 setFavicon(favicon);
Leon Scroggins8cf8f682009-11-04 11:13:50 -08002476 // Show some progress so that the user knows the page is beginning to
2477 // load
Leon Scroggins92472e82010-02-17 16:32:28 -05002478 onProgressChanged(view, INITIAL_PROGRESS);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002479 mDidStopLoad = false;
Grace Kloba22ac16e2009-10-07 18:00:23 -07002480 if (!mIsNetworkUp) createAndShowNetworkDialog();
Patrick Scott15525d42009-09-21 13:39:37 -04002481
Grace Kloba22ac16e2009-10-07 18:00:23 -07002482 if (mSettings.isTracing()) {
2483 String host;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002484 try {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002485 WebAddress uri = new WebAddress(url);
2486 host = uri.mHost;
2487 } catch (android.net.ParseException ex) {
2488 host = "browser";
The Android Open Source Project0c908882009-03-03 19:32:16 -08002489 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002490 host = host.replace('.', '_');
2491 host += ".trace";
2492 mInTrace = true;
2493 Debug.startMethodTracing(host, 20 * 1024 * 1024);
2494 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002495
Grace Kloba22ac16e2009-10-07 18:00:23 -07002496 // Performance probe
2497 if (false) {
2498 mStart = SystemClock.uptimeMillis();
2499 mProcessStart = Process.getElapsedCpuTime();
2500 long[] sysCpu = new long[7];
2501 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2502 sysCpu, null)) {
2503 mUserStart = sysCpu[0] + sysCpu[1];
2504 mSystemStart = sysCpu[2];
2505 mIdleStart = sysCpu[3];
2506 mIrqStart = sysCpu[4] + sysCpu[5] + sysCpu[6];
2507 }
2508 mUiStart = SystemClock.currentThreadTimeMillis();
2509 }
2510 }
2511
2512 void onPageFinished(WebView view, String url) {
2513 // Reset the title and icon in case we stopped a provisional load.
2514 resetTitleAndIcon(view);
2515 // Update the lock icon image only once we are done loading
2516 updateLockIconToLatest();
2517 // pause the WebView timer and release the wake lock if it is finished
2518 // while BrowserActivity is in pause state.
2519 if (mActivityInPause && pauseWebViewTimers()) {
2520 if (mWakeLock.isHeld()) {
2521 mHandler.removeMessages(RELEASE_WAKELOCK);
2522 mWakeLock.release();
2523 }
2524 }
2525
2526 // Performance probe
2527 if (false) {
2528 long[] sysCpu = new long[7];
2529 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2530 sysCpu, null)) {
2531 String uiInfo = "UI thread used "
2532 + (SystemClock.currentThreadTimeMillis() - mUiStart)
2533 + " ms";
2534 if (LOGD_ENABLED) {
2535 Log.d(LOGTAG, uiInfo);
2536 }
2537 //The string that gets written to the log
2538 String performanceString = "It took total "
2539 + (SystemClock.uptimeMillis() - mStart)
2540 + " ms clock time to load the page."
2541 + "\nbrowser process used "
2542 + (Process.getElapsedCpuTime() - mProcessStart)
2543 + " ms, user processes used "
2544 + (sysCpu[0] + sysCpu[1] - mUserStart) * 10
2545 + " ms, kernel used "
2546 + (sysCpu[2] - mSystemStart) * 10
2547 + " ms, idle took " + (sysCpu[3] - mIdleStart) * 10
2548 + " ms and irq took "
2549 + (sysCpu[4] + sysCpu[5] + sysCpu[6] - mIrqStart)
2550 * 10 + " ms, " + uiInfo;
2551 if (LOGD_ENABLED) {
2552 Log.d(LOGTAG, performanceString + "\nWebpage: " + url);
2553 }
2554 if (url != null) {
2555 // strip the url to maintain consistency
2556 String newUrl = new String(url);
2557 if (newUrl.startsWith("http://www.")) {
2558 newUrl = newUrl.substring(11);
2559 } else if (newUrl.startsWith("http://")) {
2560 newUrl = newUrl.substring(7);
2561 } else if (newUrl.startsWith("https://www.")) {
2562 newUrl = newUrl.substring(12);
2563 } else if (newUrl.startsWith("https://")) {
2564 newUrl = newUrl.substring(8);
2565 }
2566 if (LOGD_ENABLED) {
2567 Log.d(LOGTAG, newUrl + " loaded");
2568 }
Grace Kloba5b078b52009-06-24 20:23:41 -07002569 }
2570 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002571 }
Grace Kloba5b078b52009-06-24 20:23:41 -07002572
Grace Kloba22ac16e2009-10-07 18:00:23 -07002573 if (mInTrace) {
2574 mInTrace = false;
2575 Debug.stopMethodTracing();
2576 }
2577 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002578
Grace Kloba22ac16e2009-10-07 18:00:23 -07002579 boolean shouldOverrideUrlLoading(WebView view, String url) {
2580 if (url.startsWith(SCHEME_WTAI)) {
2581 // wtai://wp/mc;number
2582 // number=string(phone-number)
2583 if (url.startsWith(SCHEME_WTAI_MC)) {
2584 Intent intent = new Intent(Intent.ACTION_VIEW,
2585 Uri.parse(WebView.SCHEME_TEL +
2586 url.substring(SCHEME_WTAI_MC.length())));
2587 startActivity(intent);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002588 return true;
2589 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002590 // wtai://wp/sd;dtmf
2591 // dtmf=string(dialstring)
2592 if (url.startsWith(SCHEME_WTAI_SD)) {
2593 // TODO: only send when there is active voice connection
2594 return false;
2595 }
2596 // wtai://wp/ap;number;name
2597 // number=string(phone-number)
2598 // name=string
2599 if (url.startsWith(SCHEME_WTAI_AP)) {
2600 // TODO
2601 return false;
2602 }
2603 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002604
Grace Kloba22ac16e2009-10-07 18:00:23 -07002605 // The "about:" schemes are internal to the browser; don't want these to
2606 // be dispatched to other apps.
2607 if (url.startsWith("about:")) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002608 return false;
2609 }
2610
Grace Kloba22ac16e2009-10-07 18:00:23 -07002611 Intent intent;
2612 // perform generic parsing of the URI to turn it into an Intent.
2613 try {
2614 intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME);
2615 } catch (URISyntaxException ex) {
2616 Log.w("Browser", "Bad URI " + url + ": " + ex.getMessage());
2617 return false;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002618 }
2619
Grace Kloba22ac16e2009-10-07 18:00:23 -07002620 // check whether the intent can be resolved. If not, we will see
2621 // whether we can download it from the Market.
2622 if (getPackageManager().resolveActivity(intent, 0) == null) {
2623 String packagename = intent.getPackage();
2624 if (packagename != null) {
2625 intent = new Intent(Intent.ACTION_VIEW, Uri
2626 .parse("market://search?q=pname:" + packagename));
2627 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2628 startActivity(intent);
2629 return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002630 } else {
2631 return false;
2632 }
2633 }
2634
Grace Kloba22ac16e2009-10-07 18:00:23 -07002635 // sanitize the Intent, ensuring web pages can not bypass browser
2636 // security (only access to BROWSABLE activities).
2637 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2638 intent.setComponent(null);
2639 try {
2640 if (startActivityIfNeeded(intent, -1)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002641 return true;
2642 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002643 } catch (ActivityNotFoundException ex) {
2644 // ignore the error. If no application can handle the URL,
2645 // eg about:blank, assume the browser can handle it.
2646 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002647
Grace Kloba22ac16e2009-10-07 18:00:23 -07002648 if (mMenuIsDown) {
2649 openTab(url);
2650 closeOptionsMenu();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002651 return true;
2652 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002653 return false;
2654 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002655
Grace Kloba22ac16e2009-10-07 18:00:23 -07002656 // -------------------------------------------------------------------------
2657 // Helper function for WebChromeClient
2658 // -------------------------------------------------------------------------
The Android Open Source Project0c908882009-03-03 19:32:16 -08002659
Grace Kloba22ac16e2009-10-07 18:00:23 -07002660 void onProgressChanged(WebView view, int newProgress) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002661 mFakeTitleBar.setProgress(newProgress);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002662
Grace Kloba22ac16e2009-10-07 18:00:23 -07002663 if (newProgress == 100) {
2664 // onProgressChanged() may continue to be called after the main
2665 // frame has finished loading, as any remaining sub frames continue
2666 // to load. We'll only get called once though with newProgress as
2667 // 100 when everything is loaded. (onPageFinished is called once
2668 // when the main frame completes loading regardless of the state of
2669 // any sub frames so calls to onProgressChanges may continue after
2670 // onPageFinished has executed)
2671 if (mInLoad) {
2672 mInLoad = false;
Leon Scrogginsa27ff192009-09-14 12:58:04 -04002673 updateInLoadMenuItems();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002674 // If the options menu is open, leave the title bar
2675 if (!mOptionsMenuOpen || !mIconView) {
2676 hideFakeTitleBar();
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07002677 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002678 }
Leon Scrogginsaa37e7f2010-03-05 11:51:20 -05002679 } else {
2680 if (!mInLoad) {
2681 // onPageFinished may have already been called but a subframe is
2682 // still loading and updating the progress. Reset mInLoad and
2683 // update the menu items.
2684 mInLoad = true;
2685 updateInLoadMenuItems();
2686 }
2687 // When the page first begins to load, the Activity may still be
2688 // paused, in which case showFakeTitleBar will do nothing. Call
2689 // again as the page continues to load so that it will be shown.
2690 // (Calling it will the fake title bar is already showing will also
2691 // do nothing.
Grace Kloba22ac16e2009-10-07 18:00:23 -07002692 if (!mOptionsMenuOpen || mIconView) {
2693 // This page has begun to load, so show the title bar
2694 showFakeTitleBar();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002695 }
2696 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002697 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002698
Grace Kloba22ac16e2009-10-07 18:00:23 -07002699 void onShowCustomView(View view, WebChromeClient.CustomViewCallback callback) {
Derek Sollenberger8ff57db2009-12-08 15:39:55 -05002700 // if a view already exists then immediately terminate the new one
2701 if (mCustomView != null) {
2702 callback.onCustomViewHidden();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002703 return;
Derek Sollenberger8ff57db2009-12-08 15:39:55 -05002704 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002705
2706 // Add the custom view to its container.
2707 mCustomViewContainer.addView(view, COVER_SCREEN_GRAVITY_CENTER);
2708 mCustomView = view;
2709 mCustomViewCallback = callback;
2710 // Save the menu state and set it to empty while the custom
2711 // view is showing.
2712 mOldMenuState = mMenuState;
2713 mMenuState = EMPTY_MENU;
2714 // Hide the content view.
2715 mContentView.setVisibility(View.GONE);
2716 // Finally show the custom view container.
Andrei Popescu163ab742009-10-20 17:58:23 +01002717 setStatusBarVisibility(false);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002718 mCustomViewContainer.setVisibility(View.VISIBLE);
2719 mCustomViewContainer.bringToFront();
2720 }
2721
2722 void onHideCustomView() {
2723 if (mCustomView == null)
2724 return;
2725
2726 // Hide the custom view.
2727 mCustomView.setVisibility(View.GONE);
2728 // Remove the custom view from its container.
2729 mCustomViewContainer.removeView(mCustomView);
2730 mCustomView = null;
2731 // Reset the old menu state.
2732 mMenuState = mOldMenuState;
2733 mOldMenuState = EMPTY_MENU;
2734 mCustomViewContainer.setVisibility(View.GONE);
2735 mCustomViewCallback.onCustomViewHidden();
2736 // Show the content view.
Andrei Popescu163ab742009-10-20 17:58:23 +01002737 setStatusBarVisibility(true);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002738 mContentView.setVisibility(View.VISIBLE);
2739 }
2740
2741 Bitmap getDefaultVideoPoster() {
2742 if (mDefaultVideoPoster == null) {
2743 mDefaultVideoPoster = BitmapFactory.decodeResource(
2744 getResources(), R.drawable.default_video_poster);
Patrick Scott3918d442009-08-04 13:22:29 -04002745 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002746 return mDefaultVideoPoster;
2747 }
Patrick Scott3918d442009-08-04 13:22:29 -04002748
Grace Kloba22ac16e2009-10-07 18:00:23 -07002749 View getVideoLoadingProgressView() {
2750 if (mVideoProgressView == null) {
2751 LayoutInflater inflater = LayoutInflater.from(BrowserActivity.this);
2752 mVideoProgressView = inflater.inflate(
2753 R.layout.video_loading_progress, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002754 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002755 return mVideoProgressView;
2756 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002757
Leon Scroggins8d5fa432009-10-02 15:55:59 -04002758 /*
2759 * The Object used to inform the WebView of the file to upload.
2760 */
2761 private ValueCallback<Uri> mUploadMessage;
2762
Grace Kloba22ac16e2009-10-07 18:00:23 -07002763 void openFileChooser(ValueCallback<Uri> uploadMsg) {
2764 if (mUploadMessage != null) return;
2765 mUploadMessage = uploadMsg;
2766 Intent i = new Intent(Intent.ACTION_GET_CONTENT);
2767 i.addCategory(Intent.CATEGORY_OPENABLE);
2768 i.setType("*/*");
2769 BrowserActivity.this.startActivityForResult(Intent.createChooser(i,
2770 getString(R.string.choose_upload)), FILE_SELECTED);
2771 }
2772
2773 // -------------------------------------------------------------------------
2774 // Implement functions for DownloadListener
2775 // -------------------------------------------------------------------------
2776
The Android Open Source Project0c908882009-03-03 19:32:16 -08002777 /**
2778 * Notify the host application a download should be done, or that
2779 * the data should be streamed if a streaming viewer is available.
2780 * @param url The full url to the content that should be downloaded
2781 * @param contentDisposition Content-disposition http header, if
2782 * present.
2783 * @param mimetype The mimetype of the content reported by the server
2784 * @param contentLength The file size reported by the server
2785 */
2786 public void onDownloadStart(String url, String userAgent,
2787 String contentDisposition, String mimetype, long contentLength) {
2788 // if we're dealing wih A/V content that's not explicitly marked
2789 // for download, check if it's streamable.
2790 if (contentDisposition == null
Patrick Scotte1fb9662009-08-31 14:31:52 -04002791 || !contentDisposition.regionMatches(
2792 true, 0, "attachment", 0, 10)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002793 // query the package manager to see if there's a registered handler
2794 // that matches.
2795 Intent intent = new Intent(Intent.ACTION_VIEW);
2796 intent.setDataAndType(Uri.parse(url), mimetype);
Patrick Scotte1fb9662009-08-31 14:31:52 -04002797 ResolveInfo info = getPackageManager().resolveActivity(intent,
2798 PackageManager.MATCH_DEFAULT_ONLY);
2799 if (info != null) {
2800 ComponentName myName = getComponentName();
2801 // If we resolved to ourselves, we don't want to attempt to
2802 // load the url only to try and download it again.
2803 if (!myName.getPackageName().equals(
2804 info.activityInfo.packageName)
2805 || !myName.getClassName().equals(
2806 info.activityInfo.name)) {
2807 // someone (other than us) knows how to handle this mime
2808 // type with this scheme, don't download.
2809 try {
2810 startActivity(intent);
2811 return;
2812 } catch (ActivityNotFoundException ex) {
2813 if (LOGD_ENABLED) {
2814 Log.d(LOGTAG, "activity not found for " + mimetype
2815 + " over " + Uri.parse(url).getScheme(),
2816 ex);
2817 }
2818 // Best behavior is to fall back to a download in this
2819 // case
The Android Open Source Project0c908882009-03-03 19:32:16 -08002820 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002821 }
2822 }
2823 }
2824 onDownloadStartNoStream(url, userAgent, contentDisposition, mimetype, contentLength);
2825 }
2826
2827 /**
2828 * Notify the host application a download should be done, even if there
2829 * is a streaming viewer available for thise type.
2830 * @param url The full url to the content that should be downloaded
2831 * @param contentDisposition Content-disposition http header, if
2832 * present.
2833 * @param mimetype The mimetype of the content reported by the server
2834 * @param contentLength The file size reported by the server
2835 */
2836 /*package */ void onDownloadStartNoStream(String url, String userAgent,
2837 String contentDisposition, String mimetype, long contentLength) {
2838
2839 String filename = URLUtil.guessFileName(url,
2840 contentDisposition, mimetype);
2841
2842 // Check to see if we have an SDCard
2843 String status = Environment.getExternalStorageState();
2844 if (!status.equals(Environment.MEDIA_MOUNTED)) {
2845 int title;
2846 String msg;
2847
2848 // Check to see if the SDCard is busy, same as the music app
2849 if (status.equals(Environment.MEDIA_SHARED)) {
2850 msg = getString(R.string.download_sdcard_busy_dlg_msg);
2851 title = R.string.download_sdcard_busy_dlg_title;
2852 } else {
2853 msg = getString(R.string.download_no_sdcard_dlg_msg, filename);
2854 title = R.string.download_no_sdcard_dlg_title;
2855 }
2856
2857 new AlertDialog.Builder(this)
2858 .setTitle(title)
2859 .setIcon(android.R.drawable.ic_dialog_alert)
2860 .setMessage(msg)
2861 .setPositiveButton(R.string.ok, null)
2862 .show();
2863 return;
2864 }
2865
2866 // java.net.URI is a lot stricter than KURL so we have to undo
2867 // KURL's percent-encoding and redo the encoding using java.net.URI.
2868 URI uri = null;
2869 try {
2870 // Undo the percent-encoding that KURL may have done.
2871 String newUrl = new String(URLUtil.decode(url.getBytes()));
2872 // Parse the url into pieces
2873 WebAddress w = new WebAddress(newUrl);
2874 String frag = null;
2875 String query = null;
2876 String path = w.mPath;
2877 // Break the path into path, query, and fragment
2878 if (path.length() > 0) {
2879 // Strip the fragment
2880 int idx = path.lastIndexOf('#');
2881 if (idx != -1) {
2882 frag = path.substring(idx + 1);
2883 path = path.substring(0, idx);
2884 }
2885 idx = path.lastIndexOf('?');
2886 if (idx != -1) {
2887 query = path.substring(idx + 1);
2888 path = path.substring(0, idx);
2889 }
2890 }
2891 uri = new URI(w.mScheme, w.mAuthInfo, w.mHost, w.mPort, path,
2892 query, frag);
2893 } catch (Exception e) {
2894 Log.e(LOGTAG, "Could not parse url for download: " + url, e);
2895 return;
2896 }
2897
2898 // XXX: Have to use the old url since the cookies were stored using the
2899 // old percent-encoded url.
2900 String cookies = CookieManager.getInstance().getCookie(url);
2901
2902 ContentValues values = new ContentValues();
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08002903 values.put(Downloads.Impl.COLUMN_URI, uri.toString());
2904 values.put(Downloads.Impl.COLUMN_COOKIE_DATA, cookies);
2905 values.put(Downloads.Impl.COLUMN_USER_AGENT, userAgent);
2906 values.put(Downloads.Impl.COLUMN_NOTIFICATION_PACKAGE,
The Android Open Source Project0c908882009-03-03 19:32:16 -08002907 getPackageName());
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08002908 values.put(Downloads.Impl.COLUMN_NOTIFICATION_CLASS,
The Android Open Source Project0c908882009-03-03 19:32:16 -08002909 BrowserDownloadPage.class.getCanonicalName());
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08002910 values.put(Downloads.Impl.COLUMN_VISIBILITY,
2911 Downloads.Impl.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
2912 values.put(Downloads.Impl.COLUMN_MIME_TYPE, mimetype);
2913 values.put(Downloads.Impl.COLUMN_FILE_NAME_HINT, filename);
2914 values.put(Downloads.Impl.COLUMN_DESCRIPTION, uri.getHost());
The Android Open Source Project0c908882009-03-03 19:32:16 -08002915 if (contentLength > 0) {
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08002916 values.put(Downloads.Impl.COLUMN_TOTAL_BYTES, contentLength);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002917 }
2918 if (mimetype == null) {
2919 // We must have long pressed on a link or image to download it. We
2920 // are not sure of the mimetype in this case, so do a head request
2921 new FetchUrlMimeType(this).execute(values);
2922 } else {
2923 final Uri contentUri =
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08002924 getContentResolver().insert(Downloads.Impl.CONTENT_URI, values);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002925 }
2926
2927 }
2928
Grace Kloba22ac16e2009-10-07 18:00:23 -07002929 // -------------------------------------------------------------------------
2930
The Android Open Source Project0c908882009-03-03 19:32:16 -08002931 /**
2932 * Resets the lock icon. This method is called when we start a new load and
2933 * know the url to be loaded.
2934 */
2935 private void resetLockIcon(String url) {
2936 // Save the lock-icon state (we revert to it if the load gets cancelled)
Grace Kloba22ac16e2009-10-07 18:00:23 -07002937 mTabControl.getCurrentTab().resetLockIcon(url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002938 updateLockIconImage(LOCK_ICON_UNSECURE);
2939 }
2940
The Android Open Source Project0c908882009-03-03 19:32:16 -08002941 /**
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04002942 * Update the lock icon to correspond to our latest state.
2943 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07002944 private void updateLockIconToLatest() {
2945 updateLockIconImage(mTabControl.getCurrentTab().getLockIconType());
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04002946 }
2947
2948 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08002949 * Updates the lock-icon image in the title-bar.
2950 */
2951 private void updateLockIconImage(int lockIconType) {
2952 Drawable d = null;
2953 if (lockIconType == LOCK_ICON_SECURE) {
2954 d = mSecLockIcon;
2955 } else if (lockIconType == LOCK_ICON_MIXED) {
2956 d = mMixLockIcon;
2957 }
Leon Scroggins68579392009-09-15 15:31:54 -04002958 mTitleBar.setLock(d);
Leon Scrogginsfe87bd32009-10-06 10:10:00 -04002959 mFakeTitleBar.setLock(d);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002960 }
2961
2962 /**
2963 * Displays a page-info dialog.
2964 * @param tab The tab to show info about
2965 * @param fromShowSSLCertificateOnError The flag that indicates whether
2966 * this dialog was opened from the SSL-certificate-on-error dialog or
2967 * not. This is important, since we need to know whether to return to
2968 * the parent dialog or simply dismiss.
2969 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07002970 private void showPageInfo(final Tab tab,
The Android Open Source Project0c908882009-03-03 19:32:16 -08002971 final boolean fromShowSSLCertificateOnError) {
2972 final LayoutInflater factory = LayoutInflater
2973 .from(this);
2974
2975 final View pageInfoView = factory.inflate(R.layout.page_info, null);
2976
2977 final WebView view = tab.getWebView();
2978
2979 String url = null;
2980 String title = null;
2981
2982 if (view == null) {
2983 url = tab.getUrl();
2984 title = tab.getTitle();
2985 } else if (view == mTabControl.getCurrentWebView()) {
2986 // Use the cached title and url if this is the current WebView
2987 url = mUrl;
2988 title = mTitle;
2989 } else {
2990 url = view.getUrl();
2991 title = view.getTitle();
2992 }
2993
2994 if (url == null) {
2995 url = "";
2996 }
2997 if (title == null) {
2998 title = "";
2999 }
3000
3001 ((TextView) pageInfoView.findViewById(R.id.address)).setText(url);
3002 ((TextView) pageInfoView.findViewById(R.id.title)).setText(title);
3003
3004 mPageInfoView = tab;
Leon Scrogginsc7b92f82010-01-11 18:17:31 -05003005 mPageInfoFromShowSSLCertificateOnError = fromShowSSLCertificateOnError;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003006
3007 AlertDialog.Builder alertDialogBuilder =
3008 new AlertDialog.Builder(this)
3009 .setTitle(R.string.page_info).setIcon(android.R.drawable.ic_dialog_info)
3010 .setView(pageInfoView)
3011 .setPositiveButton(
3012 R.string.ok,
3013 new DialogInterface.OnClickListener() {
3014 public void onClick(DialogInterface dialog,
3015 int whichButton) {
3016 mPageInfoDialog = null;
3017 mPageInfoView = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003018
3019 // if we came here from the SSL error dialog
3020 if (fromShowSSLCertificateOnError) {
3021 // go back to the SSL error dialog
3022 showSSLCertificateOnError(
3023 mSSLCertificateOnErrorView,
3024 mSSLCertificateOnErrorHandler,
3025 mSSLCertificateOnErrorError);
3026 }
3027 }
3028 })
3029 .setOnCancelListener(
3030 new DialogInterface.OnCancelListener() {
3031 public void onCancel(DialogInterface dialog) {
3032 mPageInfoDialog = null;
3033 mPageInfoView = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003034
3035 // if we came here from the SSL error dialog
3036 if (fromShowSSLCertificateOnError) {
3037 // go back to the SSL error dialog
3038 showSSLCertificateOnError(
3039 mSSLCertificateOnErrorView,
3040 mSSLCertificateOnErrorHandler,
3041 mSSLCertificateOnErrorError);
3042 }
3043 }
3044 });
3045
3046 // if we have a main top-level page SSL certificate set or a certificate
3047 // error
3048 if (fromShowSSLCertificateOnError ||
3049 (view != null && view.getCertificate() != null)) {
3050 // add a 'View Certificate' button
3051 alertDialogBuilder.setNeutralButton(
3052 R.string.view_certificate,
3053 new DialogInterface.OnClickListener() {
3054 public void onClick(DialogInterface dialog,
3055 int whichButton) {
3056 mPageInfoDialog = null;
3057 mPageInfoView = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003058
3059 // if we came here from the SSL error dialog
3060 if (fromShowSSLCertificateOnError) {
3061 // go back to the SSL error dialog
3062 showSSLCertificateOnError(
3063 mSSLCertificateOnErrorView,
3064 mSSLCertificateOnErrorHandler,
3065 mSSLCertificateOnErrorError);
3066 } else {
3067 // otherwise, display the top-most certificate from
3068 // the chain
3069 if (view.getCertificate() != null) {
3070 showSSLCertificate(tab);
3071 }
3072 }
3073 }
3074 });
3075 }
3076
3077 mPageInfoDialog = alertDialogBuilder.show();
3078 }
3079
3080 /**
3081 * Displays the main top-level page SSL certificate dialog
3082 * (accessible from the Page-Info dialog).
3083 * @param tab The tab to show certificate for.
3084 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003085 private void showSSLCertificate(final Tab tab) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003086 final View certificateView =
3087 inflateCertificateView(tab.getWebView().getCertificate());
3088 if (certificateView == null) {
3089 return;
3090 }
3091
3092 LayoutInflater factory = LayoutInflater.from(this);
3093
3094 final LinearLayout placeholder =
3095 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3096
3097 LinearLayout ll = (LinearLayout) factory.inflate(
3098 R.layout.ssl_success, placeholder);
3099 ((TextView)ll.findViewById(R.id.success))
3100 .setText(R.string.ssl_certificate_is_valid);
3101
3102 mSSLCertificateView = tab;
3103 mSSLCertificateDialog =
3104 new AlertDialog.Builder(this)
3105 .setTitle(R.string.ssl_certificate).setIcon(
3106 R.drawable.ic_dialog_browser_certificate_secure)
3107 .setView(certificateView)
3108 .setPositiveButton(R.string.ok,
3109 new DialogInterface.OnClickListener() {
3110 public void onClick(DialogInterface dialog,
3111 int whichButton) {
3112 mSSLCertificateDialog = null;
3113 mSSLCertificateView = null;
3114
3115 showPageInfo(tab, false);
3116 }
3117 })
3118 .setOnCancelListener(
3119 new DialogInterface.OnCancelListener() {
3120 public void onCancel(DialogInterface dialog) {
3121 mSSLCertificateDialog = null;
3122 mSSLCertificateView = null;
3123
3124 showPageInfo(tab, false);
3125 }
3126 })
3127 .show();
3128 }
3129
3130 /**
3131 * Displays the SSL error certificate dialog.
3132 * @param view The target web-view.
3133 * @param handler The SSL error handler responsible for cancelling the
3134 * connection that resulted in an SSL error or proceeding per user request.
3135 * @param error The SSL error object.
3136 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003137 void showSSLCertificateOnError(
The Android Open Source Project0c908882009-03-03 19:32:16 -08003138 final WebView view, final SslErrorHandler handler, final SslError error) {
3139
3140 final View certificateView =
3141 inflateCertificateView(error.getCertificate());
3142 if (certificateView == null) {
3143 return;
3144 }
3145
3146 LayoutInflater factory = LayoutInflater.from(this);
3147
3148 final LinearLayout placeholder =
3149 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3150
3151 if (error.hasError(SslError.SSL_UNTRUSTED)) {
3152 LinearLayout ll = (LinearLayout)factory
3153 .inflate(R.layout.ssl_warning, placeholder);
3154 ((TextView)ll.findViewById(R.id.warning))
3155 .setText(R.string.ssl_untrusted);
3156 }
3157
3158 if (error.hasError(SslError.SSL_IDMISMATCH)) {
3159 LinearLayout ll = (LinearLayout)factory
3160 .inflate(R.layout.ssl_warning, placeholder);
3161 ((TextView)ll.findViewById(R.id.warning))
3162 .setText(R.string.ssl_mismatch);
3163 }
3164
3165 if (error.hasError(SslError.SSL_EXPIRED)) {
3166 LinearLayout ll = (LinearLayout)factory
3167 .inflate(R.layout.ssl_warning, placeholder);
3168 ((TextView)ll.findViewById(R.id.warning))
3169 .setText(R.string.ssl_expired);
3170 }
3171
3172 if (error.hasError(SslError.SSL_NOTYETVALID)) {
3173 LinearLayout ll = (LinearLayout)factory
3174 .inflate(R.layout.ssl_warning, placeholder);
3175 ((TextView)ll.findViewById(R.id.warning))
3176 .setText(R.string.ssl_not_yet_valid);
3177 }
3178
3179 mSSLCertificateOnErrorHandler = handler;
3180 mSSLCertificateOnErrorView = view;
3181 mSSLCertificateOnErrorError = error;
3182 mSSLCertificateOnErrorDialog =
3183 new AlertDialog.Builder(this)
3184 .setTitle(R.string.ssl_certificate).setIcon(
3185 R.drawable.ic_dialog_browser_certificate_partially_secure)
3186 .setView(certificateView)
3187 .setPositiveButton(R.string.ok,
3188 new DialogInterface.OnClickListener() {
3189 public void onClick(DialogInterface dialog,
3190 int whichButton) {
3191 mSSLCertificateOnErrorDialog = null;
3192 mSSLCertificateOnErrorView = null;
3193 mSSLCertificateOnErrorHandler = null;
3194 mSSLCertificateOnErrorError = null;
3195
Grace Kloba22ac16e2009-10-07 18:00:23 -07003196 view.getWebViewClient().onReceivedSslError(
3197 view, handler, error);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003198 }
3199 })
3200 .setNeutralButton(R.string.page_info_view,
3201 new DialogInterface.OnClickListener() {
3202 public void onClick(DialogInterface dialog,
3203 int whichButton) {
3204 mSSLCertificateOnErrorDialog = null;
3205
3206 // do not clear the dialog state: we will
3207 // need to show the dialog again once the
3208 // user is done exploring the page-info details
3209
3210 showPageInfo(mTabControl.getTabFromView(view),
3211 true);
3212 }
3213 })
3214 .setOnCancelListener(
3215 new DialogInterface.OnCancelListener() {
3216 public void onCancel(DialogInterface dialog) {
3217 mSSLCertificateOnErrorDialog = null;
3218 mSSLCertificateOnErrorView = null;
3219 mSSLCertificateOnErrorHandler = null;
3220 mSSLCertificateOnErrorError = null;
3221
Grace Kloba22ac16e2009-10-07 18:00:23 -07003222 view.getWebViewClient().onReceivedSslError(
3223 view, handler, error);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003224 }
3225 })
3226 .show();
3227 }
3228
3229 /**
3230 * Inflates the SSL certificate view (helper method).
3231 * @param certificate The SSL certificate.
3232 * @return The resultant certificate view with issued-to, issued-by,
3233 * issued-on, expires-on, and possibly other fields set.
3234 * If the input certificate is null, returns null.
3235 */
3236 private View inflateCertificateView(SslCertificate certificate) {
3237 if (certificate == null) {
3238 return null;
3239 }
3240
3241 LayoutInflater factory = LayoutInflater.from(this);
3242
3243 View certificateView = factory.inflate(
3244 R.layout.ssl_certificate, null);
3245
3246 // issued to:
3247 SslCertificate.DName issuedTo = certificate.getIssuedTo();
3248 if (issuedTo != null) {
3249 ((TextView) certificateView.findViewById(R.id.to_common))
3250 .setText(issuedTo.getCName());
3251 ((TextView) certificateView.findViewById(R.id.to_org))
3252 .setText(issuedTo.getOName());
3253 ((TextView) certificateView.findViewById(R.id.to_org_unit))
3254 .setText(issuedTo.getUName());
3255 }
3256
3257 // issued by:
3258 SslCertificate.DName issuedBy = certificate.getIssuedBy();
3259 if (issuedBy != null) {
3260 ((TextView) certificateView.findViewById(R.id.by_common))
3261 .setText(issuedBy.getCName());
3262 ((TextView) certificateView.findViewById(R.id.by_org))
3263 .setText(issuedBy.getOName());
3264 ((TextView) certificateView.findViewById(R.id.by_org_unit))
3265 .setText(issuedBy.getUName());
3266 }
3267
3268 // issued on:
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003269 String issuedOn = formatCertificateDate(
3270 certificate.getValidNotBeforeDate());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003271 ((TextView) certificateView.findViewById(R.id.issued_on))
3272 .setText(issuedOn);
3273
3274 // expires on:
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003275 String expiresOn = formatCertificateDate(
3276 certificate.getValidNotAfterDate());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003277 ((TextView) certificateView.findViewById(R.id.expires_on))
3278 .setText(expiresOn);
3279
3280 return certificateView;
3281 }
3282
3283 /**
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003284 * Formats the certificate date to a properly localized date string.
The Android Open Source Project0c908882009-03-03 19:32:16 -08003285 * @return Properly localized version of the certificate date string and
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003286 * the "" if it fails to localize.
The Android Open Source Project0c908882009-03-03 19:32:16 -08003287 */
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003288 private String formatCertificateDate(Date certificateDate) {
3289 if (certificateDate == null) {
3290 return "";
The Android Open Source Project0c908882009-03-03 19:32:16 -08003291 }
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003292 String formattedDate = DateFormat.getDateFormat(this).format(certificateDate);
3293 if (formattedDate == null) {
3294 return "";
3295 }
3296 return formattedDate;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003297 }
3298
3299 /**
3300 * Displays an http-authentication dialog.
3301 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003302 void showHttpAuthentication(final HttpAuthHandler handler,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003303 final String host, final String realm, final String title,
3304 final String name, final String password, int focusId) {
3305 LayoutInflater factory = LayoutInflater.from(this);
3306 final View v = factory
3307 .inflate(R.layout.http_authentication, null);
3308 if (name != null) {
3309 ((EditText) v.findViewById(R.id.username_edit)).setText(name);
3310 }
3311 if (password != null) {
3312 ((EditText) v.findViewById(R.id.password_edit)).setText(password);
3313 }
3314
3315 String titleText = title;
3316 if (titleText == null) {
3317 titleText = getText(R.string.sign_in_to).toString().replace(
3318 "%s1", host).replace("%s2", realm);
3319 }
3320
3321 mHttpAuthHandler = handler;
3322 AlertDialog dialog = new AlertDialog.Builder(this)
3323 .setTitle(titleText)
3324 .setIcon(android.R.drawable.ic_dialog_alert)
3325 .setView(v)
3326 .setPositiveButton(R.string.action,
3327 new DialogInterface.OnClickListener() {
3328 public void onClick(DialogInterface dialog,
3329 int whichButton) {
3330 String nm = ((EditText) v
3331 .findViewById(R.id.username_edit))
3332 .getText().toString();
3333 String pw = ((EditText) v
3334 .findViewById(R.id.password_edit))
3335 .getText().toString();
3336 BrowserActivity.this.setHttpAuthUsernamePassword
3337 (host, realm, nm, pw);
3338 handler.proceed(nm, pw);
3339 mHttpAuthenticationDialog = null;
3340 mHttpAuthHandler = null;
3341 }})
3342 .setNegativeButton(R.string.cancel,
3343 new DialogInterface.OnClickListener() {
3344 public void onClick(DialogInterface dialog,
3345 int whichButton) {
3346 handler.cancel();
3347 BrowserActivity.this.resetTitleAndRevertLockIcon();
3348 mHttpAuthenticationDialog = null;
3349 mHttpAuthHandler = null;
3350 }})
3351 .setOnCancelListener(new DialogInterface.OnCancelListener() {
3352 public void onCancel(DialogInterface dialog) {
3353 handler.cancel();
3354 BrowserActivity.this.resetTitleAndRevertLockIcon();
3355 mHttpAuthenticationDialog = null;
3356 mHttpAuthHandler = null;
3357 }})
3358 .create();
3359 // Make the IME appear when the dialog is displayed if applicable.
3360 dialog.getWindow().setSoftInputMode(
3361 WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
3362 dialog.show();
3363 if (focusId != 0) {
3364 dialog.findViewById(focusId).requestFocus();
3365 } else {
3366 v.findViewById(R.id.username_edit).requestFocus();
3367 }
3368 mHttpAuthenticationDialog = dialog;
3369 }
3370
3371 public int getProgress() {
3372 WebView w = mTabControl.getCurrentWebView();
3373 if (w != null) {
3374 return w.getProgress();
3375 } else {
3376 return 100;
3377 }
3378 }
3379
3380 /**
3381 * Set HTTP authentication password.
3382 *
3383 * @param host The host for the password
3384 * @param realm The realm for the password
3385 * @param username The username for the password. If it is null, it means
3386 * password can't be saved.
3387 * @param password The password
3388 */
3389 public void setHttpAuthUsernamePassword(String host, String realm,
3390 String username,
3391 String password) {
3392 WebView w = mTabControl.getCurrentWebView();
3393 if (w != null) {
3394 w.setHttpAuthUsernamePassword(host, realm, username, password);
3395 }
3396 }
3397
3398 /**
3399 * connectivity manager says net has come or gone... inform the user
3400 * @param up true if net has come up, false if net has gone down
3401 */
3402 public void onNetworkToggle(boolean up) {
3403 if (up == mIsNetworkUp) {
3404 return;
3405 } else if (up) {
3406 mIsNetworkUp = true;
3407 if (mAlertDialog != null) {
3408 mAlertDialog.cancel();
3409 mAlertDialog = null;
3410 }
3411 } else {
3412 mIsNetworkUp = false;
Patrick Scotteb6ab2a2009-09-16 10:00:17 -04003413 if (mInLoad) {
3414 createAndShowNetworkDialog();
3415 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003416 }
3417 WebView w = mTabControl.getCurrentWebView();
3418 if (w != null) {
3419 w.setNetworkAvailable(up);
3420 }
3421 }
3422
Grace Kloba22ac16e2009-10-07 18:00:23 -07003423 boolean isNetworkUp() {
3424 return mIsNetworkUp;
3425 }
3426
Patrick Scotteb6ab2a2009-09-16 10:00:17 -04003427 // This method shows the network dialog alerting the user that the net is
3428 // down. It will only show the dialog if mAlertDialog is null.
3429 private void createAndShowNetworkDialog() {
3430 if (mAlertDialog == null) {
3431 mAlertDialog = new AlertDialog.Builder(this)
3432 .setTitle(R.string.loadSuspendedTitle)
3433 .setMessage(R.string.loadSuspended)
3434 .setPositiveButton(R.string.ok, null)
3435 .show();
3436 }
3437 }
3438
The Android Open Source Project0c908882009-03-03 19:32:16 -08003439 @Override
3440 protected void onActivityResult(int requestCode, int resultCode,
3441 Intent intent) {
Grace Klobabb394f32009-11-19 10:26:37 -08003442 if (getTopWindow() == null) return;
3443
The Android Open Source Project0c908882009-03-03 19:32:16 -08003444 switch (requestCode) {
3445 case COMBO_PAGE:
3446 if (resultCode == RESULT_OK && intent != null) {
3447 String data = intent.getAction();
3448 Bundle extras = intent.getExtras();
3449 if (extras != null && extras.getBoolean("new_window", false)) {
Leon Scroggins25d35472009-09-15 11:37:27 -04003450 openTab(data);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003451 } else {
Grace Kloba22ac16e2009-10-07 18:00:23 -07003452 final Tab currentTab =
The Android Open Source Project0c908882009-03-03 19:32:16 -08003453 mTabControl.getCurrentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04003454 dismissSubWindow(currentTab);
3455 if (data != null && data.length() != 0) {
Leon Scroggins92472e82010-02-17 16:32:28 -05003456 loadUrl(getTopWindow(), data);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003457 }
3458 }
3459 }
Leon Scrogginsfde97462010-01-11 13:06:21 -05003460 // Deliberately fall through to PREFERENCES_PAGE, since the
3461 // same extra may be attached to the COMBO_PAGE
3462 case PREFERENCES_PAGE:
3463 if (resultCode == RESULT_OK && intent != null) {
3464 String action = intent.getStringExtra(Intent.EXTRA_TEXT);
3465 if (BrowserSettings.PREF_CLEAR_HISTORY.equals(action)) {
3466 mTabControl.removeParentChildRelationShips();
3467 }
3468 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003469 break;
Leon Scroggins8d5fa432009-10-02 15:55:59 -04003470 // Choose a file from the file picker.
3471 case FILE_SELECTED:
3472 if (null == mUploadMessage) break;
3473 Uri result = intent == null || resultCode != RESULT_OK ? null
3474 : intent.getData();
3475 mUploadMessage.onReceiveValue(result);
3476 mUploadMessage = null;
3477 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003478 default:
3479 break;
3480 }
Leon Scroggins30444232009-09-04 18:36:20 -04003481 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003482 }
3483
3484 /*
3485 * This method is called as a result of the user selecting the options
Leon Scrogginsf08809b2010-01-21 09:27:46 -05003486 * menu to see the download window. It shows the download window on top of
3487 * the current window.
The Android Open Source Project0c908882009-03-03 19:32:16 -08003488 */
Leon Scrogginsf08809b2010-01-21 09:27:46 -05003489 private void viewDownloads(Uri downloadRecord) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003490 Intent intent = new Intent(this,
3491 BrowserDownloadPage.class);
3492 intent.setData(downloadRecord);
Grace Kloba22ac16e2009-10-07 18:00:23 -07003493 startActivityForResult(intent, BrowserActivity.DOWNLOAD_PAGE);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003494
3495 }
3496
Leon Scroggins160a7e72009-08-14 18:28:01 -04003497 /**
3498 * Open the Go page.
3499 * @param startWithHistory If true, open starting on the history tab.
3500 * Otherwise, start with the bookmarks tab.
Leon Scroggins160a7e72009-08-14 18:28:01 -04003501 */
Leon Scroggins30444232009-09-04 18:36:20 -04003502 /* package */ void bookmarksOrHistoryPicker(boolean startWithHistory) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003503 WebView current = mTabControl.getCurrentWebView();
3504 if (current == null) {
3505 return;
3506 }
3507 Intent intent = new Intent(this,
3508 CombinedBookmarkHistoryActivity.class);
3509 String title = current.getTitle();
3510 String url = current.getUrl();
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01003511 Bitmap thumbnail = createScreenshot(current);
3512
The Android Open Source Project0c908882009-03-03 19:32:16 -08003513 // Just in case the user opens bookmarks before a page finishes loading
3514 // so the current history item, and therefore the page, is null.
3515 if (null == url) {
3516 url = mLastEnteredUrl;
3517 // This can happen.
3518 if (null == url) {
3519 url = mSettings.getHomePage();
3520 }
3521 }
3522 // In case the web page has not yet received its associated title.
3523 if (title == null) {
3524 title = url;
3525 }
3526 intent.putExtra("title", title);
3527 intent.putExtra("url", url);
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01003528 intent.putExtra("thumbnail", thumbnail);
Leon Scroggins30444232009-09-04 18:36:20 -04003529 // Disable opening in a new window if we have maxed out the windows
Grace Kloba22ac16e2009-10-07 18:00:23 -07003530 intent.putExtra("disable_new_window", !mTabControl.canCreateNewTab());
Patrick Scott3918d442009-08-04 13:22:29 -04003531 intent.putExtra("touch_icon_url", current.getTouchIconUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003532 if (startWithHistory) {
3533 intent.putExtra(CombinedBookmarkHistoryActivity.STARTING_TAB,
3534 CombinedBookmarkHistoryActivity.HISTORY_TAB);
3535 }
3536 startActivityForResult(intent, COMBO_PAGE);
3537 }
3538
3539 // Called when loading from context menu or LOAD_URL message
Leon Scroggins92472e82010-02-17 16:32:28 -05003540 private void loadUrlFromContext(WebView view, String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003541 // In case the user enters nothing.
3542 if (url != null && url.length() != 0 && view != null) {
3543 url = smartUrlFilter(url);
Grace Kloba22ac16e2009-10-07 18:00:23 -07003544 if (!view.getWebViewClient().shouldOverrideUrlLoading(view, url)) {
Leon Scroggins92472e82010-02-17 16:32:28 -05003545 loadUrl(view, url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003546 }
3547 }
3548 }
3549
Leon Scroggins92472e82010-02-17 16:32:28 -05003550 /**
3551 * Load the URL into the given WebView and update the title bar
3552 * to reflect the new load. Call this instead of WebView.loadUrl
3553 * directly.
3554 * @param view The WebView used to load url.
3555 * @param url The URL to load.
3556 */
3557 private void loadUrl(WebView view, String url) {
3558 updateTitleBarForNewLoad(view, url);
3559 view.loadUrl(url);
3560 }
3561
3562 /**
3563 * Load UrlData into a Tab and update the title bar to reflect the new
3564 * load. Call this instead of UrlData.loadIn directly.
3565 * @param t The Tab used to load.
3566 * @param data The UrlData being loaded.
3567 */
3568 private void loadUrlDataIn(Tab t, UrlData data) {
3569 updateTitleBarForNewLoad(t.getWebView(), data.mUrl);
3570 data.loadIn(t);
3571 }
3572
3573 /**
3574 * If the WebView is the top window, update the title bar to reflect
3575 * loading the new URL. i.e. set its text, clear the favicon (which
3576 * will be set once the page begins loading), and set the progress to
3577 * INITIAL_PROGRESS to show that the page has begun to load. Called
3578 * by loadUrl and loadUrlDataIn.
3579 * @param view The WebView that is starting a load.
3580 * @param url The URL that is being loaded.
3581 */
3582 private void updateTitleBarForNewLoad(WebView view, String url) {
3583 if (view == getTopWindow()) {
3584 setUrlTitle(url, null);
3585 setFavicon(null);
3586 onProgressChanged(view, INITIAL_PROGRESS);
3587 }
3588 }
3589
The Android Open Source Project0c908882009-03-03 19:32:16 -08003590 private String smartUrlFilter(Uri inUri) {
3591 if (inUri != null) {
3592 return smartUrlFilter(inUri.toString());
3593 }
3594 return null;
3595 }
3596
Feng Qianb34f87a2009-03-24 21:27:26 -07003597 protected static final Pattern ACCEPTED_URI_SCHEMA = Pattern.compile(
The Android Open Source Project0c908882009-03-03 19:32:16 -08003598 "(?i)" + // switch on case insensitive matching
3599 "(" + // begin group for schema
3600 "(?:http|https|file):\\/\\/" +
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003601 "|(?:inline|data|about|content|javascript):" +
The Android Open Source Project0c908882009-03-03 19:32:16 -08003602 ")" +
3603 "(.*)" );
3604
3605 /**
3606 * Attempts to determine whether user input is a URL or search
3607 * terms. Anything with a space is passed to search.
3608 *
3609 * Converts to lowercase any mistakenly uppercased schema (i.e.,
3610 * "Http://" converts to "http://"
3611 *
3612 * @return Original or modified URL
3613 *
3614 */
3615 String smartUrlFilter(String url) {
3616
3617 String inUrl = url.trim();
3618 boolean hasSpace = inUrl.indexOf(' ') != -1;
3619
3620 Matcher matcher = ACCEPTED_URI_SCHEMA.matcher(inUrl);
3621 if (matcher.matches()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003622 // force scheme to lowercase
3623 String scheme = matcher.group(1);
3624 String lcScheme = scheme.toLowerCase();
3625 if (!lcScheme.equals(scheme)) {
Mitsuru Oshima123ecfb2009-05-18 19:11:14 -07003626 inUrl = lcScheme + matcher.group(2);
3627 }
3628 if (hasSpace) {
3629 inUrl = inUrl.replace(" ", "%20");
The Android Open Source Project0c908882009-03-03 19:32:16 -08003630 }
3631 return inUrl;
3632 }
3633 if (hasSpace) {
Satish Sampath565505b2009-05-29 15:37:27 +01003634 // FIXME: Is this the correct place to add to searches?
3635 // what if someone else calls this function?
3636 int shortcut = parseUrlShortcut(inUrl);
3637 if (shortcut != SHORTCUT_INVALID) {
3638 Browser.addSearchUrl(mResolver, inUrl);
3639 String query = inUrl.substring(2);
3640 switch (shortcut) {
3641 case SHORTCUT_GOOGLE_SEARCH:
Grace Kloba47fdfdb2009-06-30 11:15:34 -07003642 return URLUtil.composeSearchUrl(query, QuickSearch_G, QUERY_PLACE_HOLDER);
Satish Sampath565505b2009-05-29 15:37:27 +01003643 case SHORTCUT_WIKIPEDIA_SEARCH:
3644 return URLUtil.composeSearchUrl(query, QuickSearch_W, QUERY_PLACE_HOLDER);
3645 case SHORTCUT_DICTIONARY_SEARCH:
3646 return URLUtil.composeSearchUrl(query, QuickSearch_D, QUERY_PLACE_HOLDER);
3647 case SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH:
The Android Open Source Project0c908882009-03-03 19:32:16 -08003648 // FIXME: we need location in this case
Satish Sampath565505b2009-05-29 15:37:27 +01003649 return URLUtil.composeSearchUrl(query, QuickSearch_L, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003650 }
3651 }
3652 } else {
Dan Egnor5ee906c2009-11-18 12:11:49 -08003653 if (Patterns.WEB_URL.matcher(inUrl).matches()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003654 return URLUtil.guessUrl(inUrl);
3655 }
3656 }
3657
3658 Browser.addSearchUrl(mResolver, inUrl);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07003659 return URLUtil.composeSearchUrl(inUrl, QuickSearch_G, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003660 }
3661
Ben Murdochbff2d602009-07-01 20:19:05 +01003662 /* package */ void setShouldShowErrorConsole(boolean flag) {
3663 if (flag == mShouldShowErrorConsole) {
3664 // Nothing to do.
3665 return;
3666 }
3667
3668 mShouldShowErrorConsole = flag;
3669
Grace Kloba22ac16e2009-10-07 18:00:23 -07003670 ErrorConsoleView errorConsole = mTabControl.getCurrentTab()
3671 .getErrorConsole(true);
Ben Murdochbff2d602009-07-01 20:19:05 +01003672
3673 if (flag) {
3674 // Setting the show state of the console will cause it's the layout to be inflated.
3675 if (errorConsole.numberOfErrors() > 0) {
3676 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
3677 } else {
3678 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
3679 }
3680
3681 // Now we can add it to the main view.
3682 mErrorConsoleContainer.addView(errorConsole,
Romain Guy15b8ec62010-01-08 15:06:43 -08003683 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
Ben Murdochbff2d602009-07-01 20:19:05 +01003684 ViewGroup.LayoutParams.WRAP_CONTENT));
3685 } else {
3686 mErrorConsoleContainer.removeView(errorConsole);
3687 }
3688
3689 }
3690
Grace Kloba22ac16e2009-10-07 18:00:23 -07003691 boolean shouldShowErrorConsole() {
3692 return mShouldShowErrorConsole;
3693 }
3694
Andrei Popescu163ab742009-10-20 17:58:23 +01003695 private void setStatusBarVisibility(boolean visible) {
3696 int flag = visible ? 0 : WindowManager.LayoutParams.FLAG_FULLSCREEN;
3697 getWindow().setFlags(flag, WindowManager.LayoutParams.FLAG_FULLSCREEN);
3698 }
3699
Andrei Popescu56199cc2010-01-12 22:39:16 +00003700
3701 private void sendNetworkType(String type, String subtype) {
3702 WebView w = mTabControl.getCurrentWebView();
3703 if (w != null) {
3704 w.setNetworkType(type, subtype);
3705 }
3706 }
3707
Andrei Popescu30995e72010-02-09 16:59:58 +00003708 private void packageChanged(String packageName, boolean wasAdded) {
3709 WebView w = mTabControl.getCurrentWebView();
3710 if (w == null) {
3711 return;
3712 }
3713
3714 if (wasAdded) {
3715 w.addPackageName(packageName);
3716 } else {
3717 w.removePackageName(packageName);
3718 }
3719 }
3720
3721 private void addPackageNames(Set<String> packageNames) {
3722 WebView w = mTabControl.getCurrentWebView();
3723 if (w == null) {
3724 return;
3725 }
3726
3727 w.addPackageNames(packageNames);
3728 }
3729
3730 private void getInstalledPackages() {
3731 AsyncTask<Void, Void, Set<String> > task =
3732 new AsyncTask<Void, Void, Set<String> >() {
3733 protected Set<String> doInBackground(Void... unused) {
3734 Set<String> installedPackages = new HashSet<String>();
3735 PackageManager pm = BrowserActivity.this.getPackageManager();
3736 if (pm != null) {
3737 List<PackageInfo> packages = pm.getInstalledPackages(0);
3738 for (PackageInfo p : packages) {
3739 if (BrowserActivity.this.sGoogleApps.contains(p.packageName)) {
3740 installedPackages.add(p.packageName);
3741 }
3742 }
3743 }
3744
3745 return installedPackages;
3746 }
3747
3748 // Executes on the UI thread
3749 protected void onPostExecute(Set<String> installedPackages) {
3750 addPackageNames(installedPackages);
3751 }
3752 };
3753 task.execute();
3754 }
3755
Grace Klobaeb6eef42009-09-15 17:56:32 -07003756 final static int LOCK_ICON_UNSECURE = 0;
3757 final static int LOCK_ICON_SECURE = 1;
3758 final static int LOCK_ICON_MIXED = 2;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003759
The Android Open Source Project0c908882009-03-03 19:32:16 -08003760 private BrowserSettings mSettings;
3761 private TabControl mTabControl;
3762 private ContentResolver mResolver;
3763 private FrameLayout mContentView;
Andrei Popescuadc008d2009-06-26 14:11:30 +01003764 private View mCustomView;
3765 private FrameLayout mCustomViewContainer;
Andrei Popescuc9b55562009-07-07 10:51:15 +01003766 private WebChromeClient.CustomViewCallback mCustomViewCallback;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003767
3768 // FIXME, temp address onPrepareMenu performance problem. When we move everything out of
3769 // view, we should rewrite this.
3770 private int mCurrentMenuState = 0;
3771 private int mMenuState = R.id.MAIN_MENU;
Andrei Popescuadc008d2009-06-26 14:11:30 +01003772 private int mOldMenuState = EMPTY_MENU;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003773 private static final int EMPTY_MENU = -1;
3774 private Menu mMenu;
3775
3776 private FindDialog mFindDialog;
3777 // Used to prevent chording to result in firing two shortcuts immediately
3778 // one after another. Fixes bug 1211714.
3779 boolean mCanChord;
3780
3781 private boolean mInLoad;
3782 private boolean mIsNetworkUp;
Ben Murdochb7cc8b42009-09-28 10:59:09 +01003783 private boolean mDidStopLoad;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003784
The Android Open Source Project0c908882009-03-03 19:32:16 -08003785 private boolean mActivityInPause = true;
3786
3787 private boolean mMenuIsDown;
3788
The Android Open Source Project0c908882009-03-03 19:32:16 -08003789 private static boolean mInTrace;
3790
3791 // Performance probe
3792 private static final int[] SYSTEM_CPU_FORMAT = new int[] {
3793 Process.PROC_SPACE_TERM | Process.PROC_COMBINE,
3794 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 1: user time
3795 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 2: nice time
3796 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 3: sys time
3797 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 4: idle time
3798 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 5: iowait time
3799 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 6: irq time
3800 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG // 7: softirq time
3801 };
3802
3803 private long mStart;
3804 private long mProcessStart;
3805 private long mUserStart;
3806 private long mSystemStart;
3807 private long mIdleStart;
3808 private long mIrqStart;
3809
3810 private long mUiStart;
3811
3812 private Drawable mMixLockIcon;
3813 private Drawable mSecLockIcon;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003814
3815 /* hold a ref so we can auto-cancel if necessary */
3816 private AlertDialog mAlertDialog;
3817
The Android Open Source Project0c908882009-03-03 19:32:16 -08003818 // The up-to-date URL and title (these can be different from those stored
3819 // in WebView, since it takes some time for the information in WebView to
3820 // get updated)
3821 private String mUrl;
3822 private String mTitle;
3823
3824 // As PageInfo has different style for landscape / portrait, we have
3825 // to re-open it when configuration changed
3826 private AlertDialog mPageInfoDialog;
Grace Kloba22ac16e2009-10-07 18:00:23 -07003827 private Tab mPageInfoView;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003828 // If the Page-Info dialog is launched from the SSL-certificate-on-error
3829 // dialog, we should not just dismiss it, but should get back to the
3830 // SSL-certificate-on-error dialog. This flag is used to store this state
Leon Scrogginsc7b92f82010-01-11 18:17:31 -05003831 private boolean mPageInfoFromShowSSLCertificateOnError;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003832
3833 // as SSLCertificateOnError has different style for landscape / portrait,
3834 // we have to re-open it when configuration changed
3835 private AlertDialog mSSLCertificateOnErrorDialog;
3836 private WebView mSSLCertificateOnErrorView;
3837 private SslErrorHandler mSSLCertificateOnErrorHandler;
3838 private SslError mSSLCertificateOnErrorError;
3839
3840 // as SSLCertificate has different style for landscape / portrait, we
3841 // have to re-open it when configuration changed
3842 private AlertDialog mSSLCertificateDialog;
Grace Kloba22ac16e2009-10-07 18:00:23 -07003843 private Tab mSSLCertificateView;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003844
3845 // as HttpAuthentication has different style for landscape / portrait, we
3846 // have to re-open it when configuration changed
3847 private AlertDialog mHttpAuthenticationDialog;
3848 private HttpAuthHandler mHttpAuthHandler;
3849
3850 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_PARAMS =
3851 new FrameLayout.LayoutParams(
Romain Guy15b8ec62010-01-08 15:06:43 -08003852 ViewGroup.LayoutParams.MATCH_PARENT,
3853 ViewGroup.LayoutParams.MATCH_PARENT);
Andrei Popescuadc008d2009-06-26 14:11:30 +01003854 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_GRAVITY_CENTER =
3855 new FrameLayout.LayoutParams(
Romain Guy15b8ec62010-01-08 15:06:43 -08003856 ViewGroup.LayoutParams.MATCH_PARENT,
3857 ViewGroup.LayoutParams.MATCH_PARENT,
Andrei Popescuadc008d2009-06-26 14:11:30 +01003858 Gravity.CENTER);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07003859 // Google search
3860 final static String QuickSearch_G = "http://www.google.com/m?q=%s";
The Android Open Source Project0c908882009-03-03 19:32:16 -08003861 // Wikipedia search
3862 final static String QuickSearch_W = "http://en.wikipedia.org/w/index.php?search=%s&go=Go";
3863 // Dictionary search
3864 final static String QuickSearch_D = "http://dictionary.reference.com/search?q=%s";
3865 // Google Mobile Local search
3866 final static String QuickSearch_L = "http://www.google.com/m/search?site=local&q=%s&near=mountain+view";
3867
3868 final static String QUERY_PLACE_HOLDER = "%s";
3869
3870 // "source" parameter for Google search through search key
3871 final static String GOOGLE_SEARCH_SOURCE_SEARCHKEY = "browser-key";
3872 // "source" parameter for Google search through goto menu
3873 final static String GOOGLE_SEARCH_SOURCE_GOTO = "browser-goto";
3874 // "source" parameter for Google search through simplily type
3875 final static String GOOGLE_SEARCH_SOURCE_TYPE = "browser-type";
3876 // "source" parameter for Google search suggested by the browser
3877 final static String GOOGLE_SEARCH_SOURCE_SUGGEST = "browser-suggest";
3878 // "source" parameter for Google search from unknown source
3879 final static String GOOGLE_SEARCH_SOURCE_UNKNOWN = "unknown";
3880
3881 private final static String LOGTAG = "browser";
3882
The Android Open Source Project0c908882009-03-03 19:32:16 -08003883 private String mLastEnteredUrl;
3884
3885 private PowerManager.WakeLock mWakeLock;
3886 private final static int WAKELOCK_TIMEOUT = 5 * 60 * 1000; // 5 minutes
3887
3888 private Toast mStopToast;
3889
Leon Scroggins68579392009-09-15 15:31:54 -04003890 private TitleBar mTitleBar;
Leon Scroggins81db3662009-06-04 17:45:11 -04003891
Ben Murdochbff2d602009-07-01 20:19:05 +01003892 private LinearLayout mErrorConsoleContainer = null;
3893 private boolean mShouldShowErrorConsole = false;
3894
The Android Open Source Project0c908882009-03-03 19:32:16 -08003895 // As the ids are dynamically created, we can't guarantee that they will
3896 // be in sequence, so this static array maps ids to a window number.
3897 final static private int[] WINDOW_SHORTCUT_ID_ARRAY =
3898 { R.id.window_one_menu_id, R.id.window_two_menu_id, R.id.window_three_menu_id,
3899 R.id.window_four_menu_id, R.id.window_five_menu_id, R.id.window_six_menu_id,
3900 R.id.window_seven_menu_id, R.id.window_eight_menu_id };
3901
3902 // monitor platform changes
3903 private IntentFilter mNetworkStateChangedFilter;
3904 private BroadcastReceiver mNetworkStateIntentReceiver;
3905
Grace Klobab4da0ad2009-05-14 14:45:40 -07003906 private BroadcastReceiver mPackageInstallationReceiver;
3907
The Android Open Source Project0c908882009-03-03 19:32:16 -08003908 // activity requestCode
Nicolas Roard78a98e42009-05-11 13:34:17 +01003909 final static int COMBO_PAGE = 1;
3910 final static int DOWNLOAD_PAGE = 2;
3911 final static int PREFERENCES_PAGE = 3;
Leon Scroggins8d5fa432009-10-02 15:55:59 -04003912 final static int FILE_SELECTED = 4;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003913
Andrei Popescu540035d2009-09-18 18:59:20 +01003914 // the default <video> poster
3915 private Bitmap mDefaultVideoPoster;
3916 // the video progress view
3917 private View mVideoProgressView;
3918
Andrei Popescu30995e72010-02-09 16:59:58 +00003919 // The Google packages we monitor for the navigator.isApplicationInstalled()
3920 // API. Add as needed.
3921 private static Set<String> sGoogleApps;
3922 static {
3923 sGoogleApps = new HashSet<String>();
3924 sGoogleApps.add("com.google.android.youtube");
3925 }
3926
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003927 /**
3928 * A UrlData class to abstract how the content will be set to WebView.
3929 * This base class uses loadUrl to show the content.
3930 */
Leon Scroggins6eac63e2010-03-15 18:19:14 -04003931 /* package */ static class UrlData {
Grace Kloba068e48b2010-01-26 18:11:27 -08003932 final String mUrl;
3933 final Map<String, String> mHeaders;
Leon Scroggins58d56c62010-01-28 15:12:40 -05003934 final Intent mVoiceIntent;
Grace Kloba60e095c2009-06-16 11:50:55 -07003935
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003936 UrlData(String url) {
3937 this.mUrl = url;
Grace Kloba068e48b2010-01-26 18:11:27 -08003938 this.mHeaders = null;
Leon Scroggins58d56c62010-01-28 15:12:40 -05003939 this.mVoiceIntent = null;
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003940 }
Grace Kloba60e095c2009-06-16 11:50:55 -07003941
Leon Scroggins58d56c62010-01-28 15:12:40 -05003942 UrlData(String url, Map<String, String> headers, Intent intent) {
Grace Kloba068e48b2010-01-26 18:11:27 -08003943 this.mUrl = url;
3944 this.mHeaders = headers;
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -05003945 if (RecognizerResultsIntent.ACTION_VOICE_SEARCH_RESULTS
3946 .equals(intent.getAction())) {
Leon Scroggins58d56c62010-01-28 15:12:40 -05003947 this.mVoiceIntent = intent;
3948 } else {
3949 this.mVoiceIntent = null;
3950 }
Grace Kloba60e095c2009-06-16 11:50:55 -07003951 }
3952
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003953 boolean isEmpty() {
Leon Scroggins58d56c62010-01-28 15:12:40 -05003954 return mVoiceIntent == null && (mUrl == null || mUrl.length() == 0);
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003955 }
3956
Leon Scroggins92472e82010-02-17 16:32:28 -05003957 /**
3958 * Load this UrlData into the given Tab. Use loadUrlDataIn to update
3959 * the title bar as well.
3960 */
Leon Scroggins58d56c62010-01-28 15:12:40 -05003961 public void loadIn(Tab t) {
3962 if (mVoiceIntent != null) {
3963 t.activateVoiceSearchMode(mVoiceIntent);
3964 } else {
3965 t.getWebView().loadUrl(mUrl, mHeaders);
3966 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003967 }
3968 };
3969
Leon Scroggins1f005d32009-08-10 17:36:42 -04003970 /* package */ static final UrlData EMPTY_URL_DATA = new UrlData(null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003971}