blob: 55e5177734b5109bcf99ad9937564517fd480fb3 [file] [log] [blame]
The Android Open Source Project0c908882009-03-03 19:32:16 -08001/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.browser;
18
The Android Open Source Project0c908882009-03-03 19:32:16 -080019import android.app.Activity;
The Android Open Source Project0c908882009-03-03 19:32:16 -080020import android.app.AlertDialog;
21import android.app.ProgressDialog;
22import android.app.SearchManager;
23import android.content.ActivityNotFoundException;
24import android.content.BroadcastReceiver;
25import android.content.ComponentName;
Leon Scroggins58d56c62010-01-28 15:12:40 -050026import android.content.ContentProvider;
27import android.content.ContentProviderClient;
The Android Open Source Project0c908882009-03-03 19:32:16 -080028import android.content.ContentResolver;
Leon Scrogginsb6b7f9e2009-06-18 12:05:28 -040029import android.content.ContentUris;
The Android Open Source Project0c908882009-03-03 19:32:16 -080030import android.content.ContentValues;
31import android.content.Context;
32import android.content.DialogInterface;
33import android.content.Intent;
34import android.content.IntentFilter;
Grace Klobab4da0ad2009-05-14 14:45:40 -070035import android.content.pm.PackageInfo;
The Android Open Source Project0c908882009-03-03 19:32:16 -080036import android.content.pm.PackageManager;
37import android.content.pm.ResolveInfo;
The Android Open Source Project0c908882009-03-03 19:32:16 -080038import android.content.res.Configuration;
39import android.content.res.Resources;
40import android.database.Cursor;
Leon Scroggins96afcb12009-12-10 12:35:56 -050041import android.database.DatabaseUtils;
The Android Open Source Project0c908882009-03-03 19:32:16 -080042import android.graphics.Bitmap;
Andrei Popescu540035d2009-09-18 18:59:20 +010043import android.graphics.BitmapFactory;
The Android Open Source Project0c908882009-03-03 19:32:16 -080044import android.graphics.Canvas;
The Android Open Source Project0c908882009-03-03 19:32:16 -080045import android.graphics.Picture;
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -040046import android.graphics.PixelFormat;
47import android.graphics.Rect;
The Android Open Source Project0c908882009-03-03 19:32:16 -080048import android.graphics.drawable.Drawable;
The Android Open Source Project0c908882009-03-03 19:32:16 -080049import android.net.ConnectivityManager;
Andrei Popescu56199cc2010-01-12 22:39:16 +000050import android.net.NetworkInfo;
The Android Open Source Project0c908882009-03-03 19:32:16 -080051import android.net.Uri;
52import android.net.WebAddress;
The Android Open Source Project0c908882009-03-03 19:32:16 -080053import android.net.http.SslCertificate;
54import android.net.http.SslError;
55import android.os.AsyncTask;
56import android.os.Bundle;
57import android.os.Debug;
58import android.os.Environment;
59import android.os.Handler;
The Android Open Source Project0c908882009-03-03 19:32:16 -080060import android.os.Message;
61import android.os.PowerManager;
62import android.os.Process;
The Android Open Source Project0c908882009-03-03 19:32:16 -080063import android.os.ServiceManager;
64import android.os.SystemClock;
The Android Open Source Project0c908882009-03-03 19:32:16 -080065import android.provider.Browser;
Cary Clark5e335a32009-09-22 14:53:11 -040066import android.provider.ContactsContract;
67import android.provider.ContactsContract.Intents.Insert;
The Android Open Source Project0c908882009-03-03 19:32:16 -080068import android.provider.Downloads;
69import android.provider.MediaStore;
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -050070import android.speech.RecognizerResultsIntent;
The Android Open Source Project0c908882009-03-03 19:32:16 -080071import android.text.IClipboard;
72import android.text.TextUtils;
73import android.text.format.DateFormat;
Leon Scrogginsb94bf272009-09-25 15:22:08 -040074import android.util.AttributeSet;
The Android Open Source Project0c908882009-03-03 19:32:16 -080075import android.util.Log;
Dianne Hackborn385effd2010-02-24 20:03:04 -080076import android.util.Patterns;
The Android Open Source Project0c908882009-03-03 19:32:16 -080077import android.view.ContextMenu;
78import android.view.Gravity;
79import android.view.KeyEvent;
80import android.view.LayoutInflater;
81import android.view.Menu;
82import android.view.MenuInflater;
83import android.view.MenuItem;
84import android.view.View;
85import android.view.ViewGroup;
86import android.view.Window;
87import android.view.WindowManager;
88import android.view.ContextMenu.ContextMenuInfo;
89import android.view.MenuItem.OnMenuItemClickListener;
The Android Open Source Project0c908882009-03-03 19:32:16 -080090import android.webkit.CookieManager;
91import android.webkit.CookieSyncManager;
92import android.webkit.DownloadListener;
93import android.webkit.HttpAuthHandler;
Grace Klobab4da0ad2009-05-14 14:45:40 -070094import android.webkit.PluginManager;
The Android Open Source Project0c908882009-03-03 19:32:16 -080095import android.webkit.SslErrorHandler;
96import android.webkit.URLUtil;
Leon Clarkecb6cc862009-09-29 18:35:13 +010097import android.webkit.ValueCallback;
The Android Open Source Project0c908882009-03-03 19:32:16 -080098import android.webkit.WebChromeClient;
99import android.webkit.WebHistoryItem;
100import android.webkit.WebIconDatabase;
101import android.webkit.WebView;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800102import android.widget.EditText;
103import android.widget.FrameLayout;
104import android.widget.LinearLayout;
105import android.widget.TextView;
106import android.widget.Toast;
Fred Quintana752b6562009-12-18 10:18:26 -0800107import android.accounts.Account;
108import android.accounts.AccountManager;
109import android.accounts.AccountManagerFuture;
110import android.accounts.AuthenticatorException;
111import android.accounts.OperationCanceledException;
112import android.accounts.AccountManagerCallback;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800113
Bjorn Bringert10d1cca2010-02-10 14:22:12 +0000114import com.android.common.Search;
Leon Scroggins1fe13a52010-02-09 15:31:26 -0500115import com.android.common.speech.LoggingEvents;
Dan Egnor5ee906c2009-11-18 12:11:49 -0800116
Leon Scrogginsb6b7f9e2009-06-18 12:05:28 -0400117import java.io.ByteArrayOutputStream;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800118import java.io.File;
Ben Murdoch4f75ba22009-10-27 11:48:28 +0000119import java.io.IOException;
120import java.io.InputStream;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800121import java.net.MalformedURLException;
122import java.net.URI;
Dianne Hackborn99189432009-06-17 18:06:18 -0700123import java.net.URISyntaxException;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800124import java.net.URL;
125import java.net.URLEncoder;
126import java.text.ParseException;
127import java.util.Date;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800128import java.util.HashMap;
Andrei Popescu30995e72010-02-09 16:59:58 +0000129import java.util.HashSet;
Grace Kloba00f54c52010-01-27 14:53:51 -0800130import java.util.Iterator;
Andrei Popescu30995e72010-02-09 16:59:58 +0000131import java.util.List;
Grace Kloba068e48b2010-01-26 18:11:27 -0800132import java.util.Map;
Andrei Popescu30995e72010-02-09 16:59:58 +0000133import java.util.Set;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800134import java.util.regex.Matcher;
135import java.util.regex.Pattern;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800136
137public class BrowserActivity extends Activity
Shimeng (Simon) Wang98d5fce2010-03-16 13:23:39 -0700138 implements View.OnCreateContextMenuListener, DownloadListener {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800139
Dave Bort31a6d1c2009-04-13 15:56:49 -0700140 /* Define some aliases to make these debugging flags easier to refer to.
141 * This file imports android.provider.Browser, so we can't just refer to "Browser.DEBUG".
142 */
143 private final static boolean DEBUG = com.android.browser.Browser.DEBUG;
144 private final static boolean LOGV_ENABLED = com.android.browser.Browser.LOGV_ENABLED;
145 private final static boolean LOGD_ENABLED = com.android.browser.Browser.LOGD_ENABLED;
146
Satish Sampath565505b2009-05-29 15:37:27 +0100147 // These are single-character shortcuts for searching popular sources.
148 private static final int SHORTCUT_INVALID = 0;
149 private static final int SHORTCUT_GOOGLE_SEARCH = 1;
150 private static final int SHORTCUT_WIKIPEDIA_SEARCH = 2;
151 private static final int SHORTCUT_DICTIONARY_SEARCH = 3;
152 private static final int SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH = 4;
153
Cary Clarka9771242009-08-11 16:42:26 -0400154 private static class ClearThumbnails extends AsyncTask<File, Void, Void> {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800155 @Override
156 public Void doInBackground(File... files) {
157 if (files != null) {
158 for (File f : files) {
Cary Clarkd6be1752009-08-12 12:56:42 -0400159 if (!f.delete()) {
160 Log.e(LOGTAG, f.getPath() + " was not deleted");
161 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800162 }
163 }
164 return null;
165 }
166 }
167
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400168 /**
169 * This layout holds everything you see below the status bar, including the
170 * error console, the custom view container, and the webviews.
171 */
172 private FrameLayout mBrowserFrameLayout;
Leon Scroggins81db3662009-06-04 17:45:11 -0400173
Grace Kloba22ac16e2009-10-07 18:00:23 -0700174 @Override
175 public void onCreate(Bundle icicle) {
Dave Bort31a6d1c2009-04-13 15:56:49 -0700176 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800177 Log.v(LOGTAG, this + " onStart");
178 }
179 super.onCreate(icicle);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800180 // test the browser in OpenGL
181 // requestWindowFeature(Window.FEATURE_OPENGL);
182
Mike Reedd334bf52010-01-26 15:21:44 -0500183 // enable this to test the browser in 32bit
184 if (false) {
185 getWindow().setFormat(PixelFormat.RGBX_8888);
186 BitmapFactory.setDefaultConfig(Bitmap.Config.ARGB_8888);
187 }
188
The Android Open Source Project0c908882009-03-03 19:32:16 -0800189 setDefaultKeyMode(DEFAULT_KEYS_SEARCH_LOCAL);
190
191 mResolver = getContentResolver();
192
Grace Kloba0923d692009-09-23 21:37:25 -0700193 // If this was a web search request, pass it on to the default web
194 // search provider and finish this activity.
195 if (handleWebSearchIntent(getIntent())) {
196 finish();
197 return;
198 }
199
The Android Open Source Project0c908882009-03-03 19:32:16 -0800200 mSecLockIcon = Resources.getSystem().getDrawable(
201 android.R.drawable.ic_secure);
202 mMixLockIcon = Resources.getSystem().getDrawable(
203 android.R.drawable.ic_partial_secure);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800204
Leon Scroggins81db3662009-06-04 17:45:11 -0400205 FrameLayout frameLayout = (FrameLayout) getWindow().getDecorView()
206 .findViewById(com.android.internal.R.id.content);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400207 mBrowserFrameLayout = (FrameLayout) LayoutInflater.from(this)
208 .inflate(R.layout.custom_screen, null);
209 mContentView = (FrameLayout) mBrowserFrameLayout.findViewById(
210 R.id.main_content);
211 mErrorConsoleContainer = (LinearLayout) mBrowserFrameLayout
212 .findViewById(R.id.error_console);
213 mCustomViewContainer = (FrameLayout) mBrowserFrameLayout
214 .findViewById(R.id.fullscreen_custom_content);
215 frameLayout.addView(mBrowserFrameLayout, COVER_SCREEN_PARAMS);
Leon Scroggins68579392009-09-15 15:31:54 -0400216 mTitleBar = new TitleBar(this);
Leon Scrogginsfe87bd32009-10-06 10:10:00 -0400217 mFakeTitleBar = new TitleBar(this);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800218
219 // Create the tab control and our initial tab
220 mTabControl = new TabControl(this);
221
222 // Open the icon database and retain all the bookmark urls for favicons
223 retainIconsOnStartup();
224
225 // Keep a settings instance handy.
226 mSettings = BrowserSettings.getInstance();
227 mSettings.setTabControl(mTabControl);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800228
229 PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
230 mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Browser");
231
Patrick Scott6adacc92010-03-05 08:24:51 -0500232 // Find out if the network is currently up.
233 ConnectivityManager cm = (ConnectivityManager) getSystemService(
234 Context.CONNECTIVITY_SERVICE);
235 NetworkInfo info = cm.getActiveNetworkInfo();
236 if (info != null) {
237 mIsNetworkUp = info.isAvailable();
238 }
239
Grace Klobaa34f6862009-07-31 16:28:17 -0700240 /* enables registration for changes in network status from
241 http stack */
242 mNetworkStateChangedFilter = new IntentFilter();
243 mNetworkStateChangedFilter.addAction(
244 ConnectivityManager.CONNECTIVITY_ACTION);
245 mNetworkStateIntentReceiver = new BroadcastReceiver() {
246 @Override
247 public void onReceive(Context context, Intent intent) {
248 if (intent.getAction().equals(
249 ConnectivityManager.CONNECTIVITY_ACTION)) {
Andrei Popescue4c98462010-02-19 15:44:13 +0000250
251 NetworkInfo info = intent.getParcelableExtra(
252 ConnectivityManager.EXTRA_NETWORK_INFO);
253 String typeName = info.getTypeName();
254 String subtypeName = info.getSubtypeName();
255 sendNetworkType(typeName.toLowerCase(),
256 (subtypeName != null ? subtypeName.toLowerCase() : ""));
257
258 onNetworkToggle(info.isAvailable());
Grace Klobaa34f6862009-07-31 16:28:17 -0700259 }
260 }
261 };
262
Grace Kloba615c6c92009-08-03 10:22:44 -0700263 IntentFilter filter = new IntentFilter(Intent.ACTION_PACKAGE_ADDED);
264 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
265 filter.addDataScheme("package");
266 mPackageInstallationReceiver = new BroadcastReceiver() {
267 @Override
268 public void onReceive(Context context, Intent intent) {
269 final String action = intent.getAction();
270 final String packageName = intent.getData()
271 .getSchemeSpecificPart();
272 final boolean replacing = intent.getBooleanExtra(
273 Intent.EXTRA_REPLACING, false);
274 if (Intent.ACTION_PACKAGE_REMOVED.equals(action) && replacing) {
275 // if it is replacing, refreshPlugins() when adding
276 return;
277 }
Andrei Popescu30995e72010-02-09 16:59:58 +0000278
279 if (sGoogleApps.contains(packageName)) {
280 BrowserActivity.this.packageChanged(packageName,
281 Intent.ACTION_PACKAGE_ADDED.equals(action));
282 }
283
Grace Kloba615c6c92009-08-03 10:22:44 -0700284 PackageManager pm = BrowserActivity.this.getPackageManager();
285 PackageInfo pkgInfo = null;
286 try {
287 pkgInfo = pm.getPackageInfo(packageName,
288 PackageManager.GET_PERMISSIONS);
289 } catch (PackageManager.NameNotFoundException e) {
290 return;
291 }
292 if (pkgInfo != null) {
293 String permissions[] = pkgInfo.requestedPermissions;
294 if (permissions == null) {
295 return;
296 }
297 boolean permissionOk = false;
298 for (String permit : permissions) {
299 if (PluginManager.PLUGIN_PERMISSION.equals(permit)) {
300 permissionOk = true;
301 break;
302 }
303 }
304 if (permissionOk) {
305 PluginManager.getInstance(BrowserActivity.this)
306 .refreshPlugins(
307 Intent.ACTION_PACKAGE_ADDED
308 .equals(action));
309 }
310 }
311 }
312 };
313 registerReceiver(mPackageInstallationReceiver, filter);
314
The Android Open Source Project0c908882009-03-03 19:32:16 -0800315 if (!mTabControl.restoreState(icicle)) {
316 // clear up the thumbnail directory if we can't restore the state as
317 // none of the files in the directory are referenced any more.
318 new ClearThumbnails().execute(
319 mTabControl.getThumbnailDir().listFiles());
Grace Klobaaab3f092009-07-30 12:29:51 -0700320 // there is no quit on Android. But if we can't restore the state,
321 // we can treat it as a new Browser, remove the old session cookies.
322 CookieManager.getInstance().removeSessionCookie();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800323 final Intent intent = getIntent();
324 final Bundle extra = intent.getExtras();
325 // Create an initial tab.
326 // If the intent is ACTION_VIEW and data is not null, the Browser is
327 // invoked to view the content by another application. In this case,
328 // the tab will be close when exit.
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700329 UrlData urlData = getUrlDataFromIntent(intent);
330
Leon Scroggins58d56c62010-01-28 15:12:40 -0500331 String action = intent.getAction();
Grace Kloba22ac16e2009-10-07 18:00:23 -0700332 final Tab t = mTabControl.createNewTab(
Leon Scroggins58d56c62010-01-28 15:12:40 -0500333 (Intent.ACTION_VIEW.equals(action) &&
334 intent.getData() != null)
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -0500335 || RecognizerResultsIntent.ACTION_VOICE_SEARCH_RESULTS
336 .equals(action),
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700337 intent.getStringExtra(Browser.EXTRA_APPLICATION_ID), urlData.mUrl);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800338 mTabControl.setCurrentTab(t);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800339 attachTabToContentView(t);
340 WebView webView = t.getWebView();
341 if (extra != null) {
342 int scale = extra.getInt(Browser.INITIAL_ZOOM_LEVEL, 0);
343 if (scale > 0 && scale <= 1000) {
344 webView.setInitialScale(scale);
345 }
346 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800347
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700348 if (urlData.isEmpty()) {
Shimeng (Simon) Wang98d5fce2010-03-16 13:23:39 -0700349 loadUrl(webView, mSettings.getHomePage());
The Android Open Source Project0c908882009-03-03 19:32:16 -0800350 } else {
Patrick Scott9d53da02010-02-19 10:19:01 -0500351 loadUrlDataIn(t, urlData);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800352 }
353 } else {
354 // TabControl.restoreState() will create a new tab even if
Leon Scroggins1f005d32009-08-10 17:36:42 -0400355 // restoring the state fails.
The Android Open Source Project0c908882009-03-03 19:32:16 -0800356 attachTabToContentView(mTabControl.getCurrentTab());
357 }
Grace Kloba615c6c92009-08-03 10:22:44 -0700358
Feng Qianb3c02da2009-06-29 15:58:08 -0700359 // Read JavaScript flags if it exists.
360 String jsFlags = mSettings.getJsFlags();
361 if (jsFlags.trim().length() != 0) {
362 mTabControl.getCurrentWebView().setJsFlags(jsFlags);
363 }
Andrei Popescu30995e72010-02-09 16:59:58 +0000364 // Work out which packages are installed on the system.
365 getInstalledPackages();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800366 }
367
Leon Scroggins58d56c62010-01-28 15:12:40 -0500368 /**
369 * Feed the previously stored results strings to the BrowserProvider so that
370 * the SearchDialog will show them instead of the standard searches.
371 * @param result String to show on the editable line of the SearchDialog.
372 */
373 /* package */ void showVoiceSearchResults(String result) {
374 ContentProviderClient client = mResolver.acquireContentProviderClient(
375 Browser.BOOKMARKS_URI);
376 ContentProvider prov = client.getLocalContentProvider();
377 BrowserProvider bp = (BrowserProvider) prov;
378 bp.setQueryResults(mTabControl.getCurrentTab().getVoiceSearchResults());
379 client.release();
380
Leon Scrogginsfbb3f152010-03-09 17:26:56 -0500381 Bundle bundle = createGoogleSearchSourceBundle(
382 GOOGLE_SEARCH_SOURCE_SEARCHKEY);
383 bundle.putBoolean(SearchManager.CONTEXT_IS_VOICE, true);
384 startSearch(result, false, bundle, false);
Leon Scroggins58d56c62010-01-28 15:12:40 -0500385 }
386
The Android Open Source Project0c908882009-03-03 19:32:16 -0800387 @Override
388 protected void onNewIntent(Intent intent) {
Grace Kloba22ac16e2009-10-07 18:00:23 -0700389 Tab current = mTabControl.getCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800390 // When a tab is closed on exit, the current tab index is set to -1.
391 // Reset before proceed as Browser requires the current tab to be set.
392 if (current == null) {
393 // Try to reset the tab in case the index was incorrect.
394 current = mTabControl.getTab(0);
395 if (current == null) {
396 // No tabs at all so just ignore this intent.
397 return;
398 }
399 mTabControl.setCurrentTab(current);
400 attachTabToContentView(current);
401 resetTitleAndIcon(current.getWebView());
402 }
403 final String action = intent.getAction();
404 final int flags = intent.getFlags();
405 if (Intent.ACTION_MAIN.equals(action) ||
406 (flags & Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY) != 0) {
407 // just resume the browser
408 return;
409 }
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -0500410 boolean activateVoiceSearch = RecognizerResultsIntent
411 .ACTION_VOICE_SEARCH_RESULTS.equals(action);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800412 if (Intent.ACTION_VIEW.equals(action)
413 || Intent.ACTION_SEARCH.equals(action)
414 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
Leon Scroggins58d56c62010-01-28 15:12:40 -0500415 || Intent.ACTION_WEB_SEARCH.equals(action)
416 || activateVoiceSearch) {
Leon Scroggins3b18ce32010-02-08 17:35:59 -0500417 if (current.isInVoiceSearchMode()) {
418 String title = current.getVoiceDisplayTitle();
419 if (title != null && title.equals(intent.getStringExtra(
420 SearchManager.QUERY))) {
421 // The user submitted the same search as the last voice
422 // search, so do nothing.
423 return;
424 }
Leon Scroggins1fe13a52010-02-09 15:31:26 -0500425 if (Intent.ACTION_SEARCH.equals(action)
426 && current.voiceSearchSourceIsGoogle()) {
427 Intent logIntent = new Intent(
428 LoggingEvents.ACTION_LOG_EVENT);
429 logIntent.putExtra(LoggingEvents.EXTRA_EVENT,
430 LoggingEvents.VoiceSearch.QUERY_UPDATED);
431 logIntent.putExtra(
432 LoggingEvents.VoiceSearch.EXTRA_QUERY_UPDATED_VALUE,
433 intent.getDataString());
434 sendBroadcast(logIntent);
435 // Note, onPageStarted will revert the voice title bar
436 // When http://b/issue?id=2379215 is fixed, we should update
437 // the title bar here.
438 }
Leon Scroggins3b18ce32010-02-08 17:35:59 -0500439 }
Satish Sampath565505b2009-05-29 15:37:27 +0100440 // If this was a search request (e.g. search query directly typed into the address bar),
441 // pass it on to the default web search provider.
442 if (handleWebSearchIntent(intent)) {
443 return;
444 }
445
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700446 UrlData urlData = getUrlDataFromIntent(intent);
447 if (urlData.isEmpty()) {
448 urlData = new UrlData(mSettings.getHomePage());
The Android Open Source Project0c908882009-03-03 19:32:16 -0800449 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700450
Grace Klobacc634032009-07-28 15:58:19 -0700451 final String appId = intent
452 .getStringExtra(Browser.EXTRA_APPLICATION_ID);
Leon Scroggins58d56c62010-01-28 15:12:40 -0500453 if ((Intent.ACTION_VIEW.equals(action) || activateVoiceSearch)
Grace Klobacc634032009-07-28 15:58:19 -0700454 && !getPackageName().equals(appId)
455 && (flags & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0) {
Grace Kloba22ac16e2009-10-07 18:00:23 -0700456 Tab appTab = mTabControl.getTabFromId(appId);
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700457 if (appTab != null) {
458 Log.i(LOGTAG, "Reusing tab for " + appId);
459 // Dismiss the subwindow if applicable.
460 dismissSubWindow(appTab);
461 // Since we might kill the WebView, remove it from the
462 // content view first.
463 removeTabFromContentView(appTab);
464 // Recreate the main WebView after destroying the old one.
465 // If the WebView has the same original url and is on that
466 // page, it can be reused.
467 boolean needsLoad =
Leon Scroggins945f1002010-03-15 13:10:45 -0400468 mTabControl.recreateWebView(appTab, urlData.mUrl)
469 // If there is a voice intent in the UrlData, then
470 // recreateWebView may return false, but we still
471 // need to force a load.
472 || urlData.mVoiceIntent != null;
Ben Murdochbff2d602009-07-01 20:19:05 +0100473
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700474 if (current != appTab) {
Leon Scroggins1f005d32009-08-10 17:36:42 -0400475 switchToTab(mTabControl.getTabIndex(appTab));
476 if (needsLoad) {
Patrick Scott9d53da02010-02-19 10:19:01 -0500477 loadUrlDataIn(appTab, urlData);
Leon Scroggins1f005d32009-08-10 17:36:42 -0400478 }
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700479 } else {
Leon Scroggins1f005d32009-08-10 17:36:42 -0400480 // If the tab was the current tab, we have to attach
481 // it to the view system again.
482 attachTabToContentView(appTab);
483 if (needsLoad) {
Patrick Scott9d53da02010-02-19 10:19:01 -0500484 loadUrlDataIn(appTab, urlData);
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700485 }
486 }
487 return;
Patrick Scottcd115892009-07-16 09:42:58 -0400488 } else {
489 // No matching application tab, try to find a regular tab
490 // with a matching url.
491 appTab = mTabControl.findUnusedTabWithUrl(urlData.mUrl);
Leon Scroggins25515f82009-08-19 15:31:58 -0400492 if (appTab != null) {
493 if (current != appTab) {
494 switchToTab(mTabControl.getTabIndex(appTab));
495 }
496 // Otherwise, we are already viewing the correct tab.
Patrick Scottcd115892009-07-16 09:42:58 -0400497 } else {
498 // if FLAG_ACTIVITY_BROUGHT_TO_FRONT flag is on, the url
499 // will be opened in a new tab unless we have reached
500 // MAX_TABS. Then the url will be opened in the current
501 // tab. If a new tab is created, it will have "true" for
502 // exit on close.
Leon Scroggins1f005d32009-08-10 17:36:42 -0400503 openTabAndShow(urlData, true, appId);
Patrick Scottcd115892009-07-16 09:42:58 -0400504 }
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700505 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800506 } else {
Grace Kloba638d3f42009-11-23 10:35:04 -0800507 if (!urlData.isEmpty()
508 && urlData.mUrl.startsWith("about:debug")) {
509 if ("about:debug.dom".equals(urlData.mUrl)) {
510 current.getWebView().dumpDomTree(false);
511 } else if ("about:debug.dom.file".equals(urlData.mUrl)) {
512 current.getWebView().dumpDomTree(true);
513 } else if ("about:debug.render".equals(urlData.mUrl)) {
514 current.getWebView().dumpRenderTree(false);
515 } else if ("about:debug.render.file".equals(urlData.mUrl)) {
516 current.getWebView().dumpRenderTree(true);
517 } else if ("about:debug.display".equals(urlData.mUrl)) {
518 current.getWebView().dumpDisplayTree();
Mike Reed9b78e1d2010-01-13 14:40:52 -0800519 } else if (urlData.mUrl.startsWith("about:debug.drag")) {
520 int index = urlData.mUrl.codePointAt(16) - '0';
521 if (index <= 0 || index > 9) {
522 current.getWebView().setDragTracker(null);
523 } else {
524 current.getWebView().setDragTracker(new MeshTracker(index));
525 }
Grace Kloba638d3f42009-11-23 10:35:04 -0800526 } else {
527 mSettings.toggleDebugSettings();
528 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800529 return;
530 }
Leon Scroggins1f005d32009-08-10 17:36:42 -0400531 // Get rid of the subwindow if it exists
532 dismissSubWindow(current);
Patrick Scott9d53da02010-02-19 10:19:01 -0500533 loadUrlDataIn(current, urlData);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800534 }
535 }
536 }
537
Satish Sampath565505b2009-05-29 15:37:27 +0100538 private int parseUrlShortcut(String url) {
539 if (url == null) return SHORTCUT_INVALID;
540
541 // FIXME: quick search, need to be customized by setting
542 if (url.length() > 2 && url.charAt(1) == ' ') {
543 switch (url.charAt(0)) {
544 case 'g': return SHORTCUT_GOOGLE_SEARCH;
545 case 'w': return SHORTCUT_WIKIPEDIA_SEARCH;
546 case 'd': return SHORTCUT_DICTIONARY_SEARCH;
547 case 'l': return SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH;
548 }
549 }
550 return SHORTCUT_INVALID;
551 }
552
553 /**
554 * Launches the default web search activity with the query parameters if the given intent's data
555 * are identified as plain search terms and not URLs/shortcuts.
556 * @return true if the intent was handled and web search activity was launched, false if not.
557 */
558 private boolean handleWebSearchIntent(Intent intent) {
559 if (intent == null) return false;
560
561 String url = null;
562 final String action = intent.getAction();
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -0500563 if (RecognizerResultsIntent.ACTION_VOICE_SEARCH_RESULTS.equals(
564 action)) {
Leon Scroggins58d56c62010-01-28 15:12:40 -0500565 return false;
566 }
Satish Sampath565505b2009-05-29 15:37:27 +0100567 if (Intent.ACTION_VIEW.equals(action)) {
Grace Kloba1e705052009-09-29 13:13:36 -0700568 Uri data = intent.getData();
569 if (data != null) url = data.toString();
Satish Sampath565505b2009-05-29 15:37:27 +0100570 } else if (Intent.ACTION_SEARCH.equals(action)
571 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
572 || Intent.ACTION_WEB_SEARCH.equals(action)) {
573 url = intent.getStringExtra(SearchManager.QUERY);
574 }
Bjorn Bringert04851702009-09-22 10:36:01 +0100575 return handleWebSearchRequest(url, intent.getBundleExtra(SearchManager.APP_DATA),
576 intent.getStringExtra(SearchManager.EXTRA_DATA_KEY));
Satish Sampath565505b2009-05-29 15:37:27 +0100577 }
578
579 /**
580 * Launches the default web search activity with the query parameters if the given url string
581 * was identified as plain search terms and not URL/shortcut.
582 * @return true if the request was handled and web search activity was launched, false if not.
583 */
Bjorn Bringert04851702009-09-22 10:36:01 +0100584 private boolean handleWebSearchRequest(String inUrl, Bundle appData, String extraData) {
Satish Sampath565505b2009-05-29 15:37:27 +0100585 if (inUrl == null) return false;
586
587 // In general, we shouldn't modify URL from Intent.
588 // But currently, we get the user-typed URL from search box as well.
589 String url = fixUrl(inUrl).trim();
590
591 // URLs and site specific search shortcuts are handled by the regular flow of control, so
592 // return early.
Dan Egnor5ee906c2009-11-18 12:11:49 -0800593 if (Patterns.WEB_URL.matcher(url).matches()
Satish Sampathbc5b9f32009-06-04 18:21:40 +0100594 || ACCEPTED_URI_SCHEMA.matcher(url).matches()
Satish Sampath565505b2009-05-29 15:37:27 +0100595 || parseUrlShortcut(url) != SHORTCUT_INVALID) {
596 return false;
597 }
598
599 Browser.updateVisitedHistory(mResolver, url, false);
600 Browser.addSearchUrl(mResolver, url);
601
602 Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);
603 intent.addCategory(Intent.CATEGORY_DEFAULT);
604 intent.putExtra(SearchManager.QUERY, url);
Satish Sampath15e9f2d2009-06-23 22:29:49 +0100605 if (appData != null) {
606 intent.putExtra(SearchManager.APP_DATA, appData);
607 }
Bjorn Bringert04851702009-09-22 10:36:01 +0100608 if (extraData != null) {
609 intent.putExtra(SearchManager.EXTRA_DATA_KEY, extraData);
610 }
Grace Klobacc634032009-07-28 15:58:19 -0700611 intent.putExtra(Browser.EXTRA_APPLICATION_ID, getPackageName());
Satish Sampath565505b2009-05-29 15:37:27 +0100612 startActivity(intent);
613
614 return true;
615 }
616
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700617 private UrlData getUrlDataFromIntent(Intent intent) {
Leon Scroggins58d56c62010-01-28 15:12:40 -0500618 String url = "";
Grace Kloba068e48b2010-01-26 18:11:27 -0800619 Map<String, String> headers = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800620 if (intent != null) {
621 final String action = intent.getAction();
622 if (Intent.ACTION_VIEW.equals(action)) {
623 url = smartUrlFilter(intent.getData());
624 if (url != null && url.startsWith("content:")) {
625 /* Append mimetype so webview knows how to display */
626 String mimeType = intent.resolveType(getContentResolver());
627 if (mimeType != null) {
628 url += "?" + mimeType;
629 }
630 }
Grace Kloba068e48b2010-01-26 18:11:27 -0800631 if (url != null && url.startsWith("http")) {
Grace Kloba00f54c52010-01-27 14:53:51 -0800632 final Bundle pairs = intent
633 .getBundleExtra(Browser.EXTRA_HEADERS);
Grace Kloba2d508ed2010-01-28 11:39:15 -0800634 if (pairs != null && !pairs.isEmpty()) {
Grace Kloba00f54c52010-01-27 14:53:51 -0800635 Iterator<String> iter = pairs.keySet().iterator();
Grace Kloba068e48b2010-01-26 18:11:27 -0800636 headers = new HashMap<String, String>();
Grace Kloba00f54c52010-01-27 14:53:51 -0800637 while (iter.hasNext()) {
638 String key = iter.next();
639 headers.put(key, pairs.getString(key));
Grace Kloba068e48b2010-01-26 18:11:27 -0800640 }
641 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700642 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800643 } else if (Intent.ACTION_SEARCH.equals(action)
644 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
645 || Intent.ACTION_WEB_SEARCH.equals(action)) {
646 url = intent.getStringExtra(SearchManager.QUERY);
647 if (url != null) {
648 mLastEnteredUrl = url;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800649 // In general, we shouldn't modify URL from Intent.
650 // But currently, we get the user-typed URL from search box as well.
651 url = fixUrl(url);
652 url = smartUrlFilter(url);
Leon Scrogginsda3e0302010-03-02 16:01:49 -0500653 Browser.updateVisitedHistory(mResolver, url, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800654 String searchSource = "&source=android-" + GOOGLE_SEARCH_SOURCE_SUGGEST + "&";
655 if (url.contains(searchSource)) {
656 String source = null;
657 final Bundle appData = intent.getBundleExtra(SearchManager.APP_DATA);
658 if (appData != null) {
Bjorn Bringert10d1cca2010-02-10 14:22:12 +0000659 source = appData.getString(Search.SOURCE);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800660 }
661 if (TextUtils.isEmpty(source)) {
662 source = GOOGLE_SEARCH_SOURCE_UNKNOWN;
663 }
664 url = url.replace(searchSource, "&source=android-"+source+"&");
665 }
666 }
667 }
668 }
Leon Scroggins58d56c62010-01-28 15:12:40 -0500669 return new UrlData(url, headers, intent);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800670 }
Leon Scroggins58d56c62010-01-28 15:12:40 -0500671 /* package */ void showVoiceTitleBar(String title) {
672 mTitleBar.setInVoiceMode(true);
673 mFakeTitleBar.setInVoiceMode(true);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800674
Leon Scroggins58d56c62010-01-28 15:12:40 -0500675 mTitleBar.setDisplayTitle(title);
676 mFakeTitleBar.setDisplayTitle(title);
677 }
678 /* package */ void revertVoiceTitleBar() {
679 mTitleBar.setInVoiceMode(false);
680 mFakeTitleBar.setInVoiceMode(false);
681
Leon Scroggins003a5dd2010-03-10 12:13:14 -0500682 mTitleBar.setDisplayTitle(mUrl);
683 mFakeTitleBar.setDisplayTitle(mUrl);
Leon Scroggins58d56c62010-01-28 15:12:40 -0500684 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800685 /* package */ static String fixUrl(String inUrl) {
Cary Clark652ff872009-09-10 13:34:44 -0400686 // FIXME: Converting the url to lower case
687 // duplicates functionality in smartUrlFilter().
688 // However, changing all current callers of fixUrl to
689 // call smartUrlFilter in addition may have unwanted
690 // consequences, and is deferred for now.
691 int colon = inUrl.indexOf(':');
692 boolean allLower = true;
693 for (int index = 0; index < colon; index++) {
694 char ch = inUrl.charAt(index);
695 if (!Character.isLetter(ch)) {
696 break;
697 }
698 allLower &= Character.isLowerCase(ch);
699 if (index == colon - 1 && !allLower) {
700 inUrl = inUrl.substring(0, colon).toLowerCase()
701 + inUrl.substring(colon);
702 }
703 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800704 if (inUrl.startsWith("http://") || inUrl.startsWith("https://"))
705 return inUrl;
706 if (inUrl.startsWith("http:") ||
707 inUrl.startsWith("https:")) {
708 if (inUrl.startsWith("http:/") || inUrl.startsWith("https:/")) {
709 inUrl = inUrl.replaceFirst("/", "//");
710 } else inUrl = inUrl.replaceFirst(":", "://");
711 }
712 return inUrl;
713 }
714
Grace Kloba22ac16e2009-10-07 18:00:23 -0700715 @Override
716 protected void onResume() {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800717 super.onResume();
Dave Bort31a6d1c2009-04-13 15:56:49 -0700718 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800719 Log.v(LOGTAG, "BrowserActivity.onResume: this=" + this);
720 }
721
722 if (!mActivityInPause) {
723 Log.e(LOGTAG, "BrowserActivity is already resumed.");
724 return;
725 }
726
Mike Reed7bfa63b2009-05-28 11:08:32 -0400727 mTabControl.resumeCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800728 mActivityInPause = false;
Mike Reed7bfa63b2009-05-28 11:08:32 -0400729 resumeWebViewTimers();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800730
731 if (mWakeLock.isHeld()) {
732 mHandler.removeMessages(RELEASE_WAKELOCK);
733 mWakeLock.release();
734 }
735
The Android Open Source Project0c908882009-03-03 19:32:16 -0800736 registerReceiver(mNetworkStateIntentReceiver,
737 mNetworkStateChangedFilter);
738 WebView.enablePlatformNotifications();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800739 }
740
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400741 /**
742 * Since the actual title bar is embedded in the WebView, and removing it
Leon Scrogginsfe87bd32009-10-06 10:10:00 -0400743 * would change its appearance, use a different TitleBar to show overlayed
744 * at the top of the screen, when the menu is open or the page is loading.
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400745 */
746 private TitleBar mFakeTitleBar;
747
748 /**
Leon Scrogginsd8fd2fc2009-09-16 11:12:09 -0400749 * Holder for the fake title bar. It will have a foreground shadow, as well
750 * as a white background, so the fake title bar looks like the real one.
751 */
752 private ViewGroup mFakeTitleBarHolder;
753
754 /**
755 * Layout parameters for the fake title bar within mFakeTitleBarHolder
756 */
757 private FrameLayout.LayoutParams mFakeTitleBarParams
758 = new FrameLayout.LayoutParams(
Romain Guy15b8ec62010-01-08 15:06:43 -0800759 ViewGroup.LayoutParams.MATCH_PARENT,
Leon Scrogginsd8fd2fc2009-09-16 11:12:09 -0400760 ViewGroup.LayoutParams.WRAP_CONTENT);
761 /**
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400762 * Keeps track of whether the options menu is open. This is important in
763 * determining whether to show or hide the title bar overlay.
764 */
765 private boolean mOptionsMenuOpen;
766
767 /**
768 * Only meaningful when mOptionsMenuOpen is true. This variable keeps track
769 * of whether the configuration has changed. The first onMenuOpened call
770 * after a configuration change is simply a reopening of the same menu
771 * (i.e. mIconView did not change).
772 */
773 private boolean mConfigChanged;
774
775 /**
776 * Whether or not the options menu is in its smaller, icon menu form. When
777 * true, we want the title bar overlay to be up. When false, we do not.
778 * Only meaningful if mOptionsMenuOpen is true.
779 */
780 private boolean mIconView;
781
Leon Scrogginsa81a7642009-08-31 17:05:41 -0400782 @Override
783 public boolean onMenuOpened(int featureId, Menu menu) {
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400784 if (Window.FEATURE_OPTIONS_PANEL == featureId) {
785 if (mOptionsMenuOpen) {
786 if (mConfigChanged) {
787 // We do not need to make any changes to the state of the
788 // title bar, since the only thing that happened was a
789 // change in orientation
790 mConfigChanged = false;
791 } else {
792 if (mIconView) {
793 // Switching the menu to expanded view, so hide the
794 // title bar.
795 hideFakeTitleBar();
796 mIconView = false;
797 } else {
798 // Switching the menu back to icon view, so show the
799 // title bar once again.
800 showFakeTitleBar();
801 mIconView = true;
802 }
803 }
804 } else {
805 // The options menu is closed, so open it, and show the title
806 showFakeTitleBar();
807 mOptionsMenuOpen = true;
808 mConfigChanged = false;
809 mIconView = true;
810 }
811 }
Leon Scrogginsa81a7642009-08-31 17:05:41 -0400812 return true;
813 }
814
Leon Scrogginsb94bf272009-09-25 15:22:08 -0400815 /**
816 * Special class used exclusively for the shadow drawn underneath the fake
817 * title bar. The shadow does not need to be drawn if the WebView
818 * underneath is scrolled to the top, because it will draw directly on top
819 * of the embedded shadow.
820 */
821 private static class Shadow extends View {
822 private WebView mWebView;
823
824 public Shadow(Context context, AttributeSet attrs) {
825 super(context, attrs);
826 }
827
828 public void setWebView(WebView view) {
829 mWebView = view;
830 }
831
832 @Override
833 public void draw(Canvas canvas) {
834 // In general onDraw is the method to override, but we care about
835 // whether or not the background gets drawn, which happens in draw()
836 if (mWebView == null || mWebView.getScrollY() > getHeight()) {
837 super.draw(canvas);
838 }
839 // Need to invalidate so that if the scroll position changes, we
840 // still draw as appropriate.
841 invalidate();
842 }
843 }
844
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400845 private void showFakeTitleBar() {
Patrick Scottf8de8ec2009-09-21 16:37:29 -0400846 final View decor = getWindow().peekDecorView();
Leon Scrogginsfe87bd32009-10-06 10:10:00 -0400847 if (mFakeTitleBar.getParent() == null && mActiveTabsPage == null
Patrick Scottf8de8ec2009-09-21 16:37:29 -0400848 && !mActivityInPause && decor != null
849 && decor.getWindowToken() != null) {
Cary Clarka0464552009-09-29 13:00:45 -0400850 Rect visRect = new Rect();
851 if (!mBrowserFrameLayout.getGlobalVisibleRect(visRect)) {
852 if (LOGD_ENABLED) {
853 Log.d(LOGTAG, "showFakeTitleBar visRect failed");
854 }
855 return;
856 }
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400857
858 WindowManager manager
859 = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
860
861 // Add the title bar to the window manager so it can receive touches
862 // while the menu is up
863 WindowManager.LayoutParams params
864 = new WindowManager.LayoutParams(
Romain Guy15b8ec62010-01-08 15:06:43 -0800865 ViewGroup.LayoutParams.MATCH_PARENT,
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400866 ViewGroup.LayoutParams.WRAP_CONTENT,
867 WindowManager.LayoutParams.TYPE_APPLICATION_SUB_PANEL,
868 WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
Leon Scroggins68549862009-09-21 16:02:01 -0400869 PixelFormat.TRANSLUCENT);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400870 params.gravity = Gravity.TOP;
Leon Scrogginsa27ff192009-09-14 12:58:04 -0400871 WebView mainView = mTabControl.getCurrentWebView();
Leon Scroggins68549862009-09-21 16:02:01 -0400872 boolean atTop = mainView != null && mainView.getScrollY() == 0;
Leon Scroggins83932c72009-09-30 11:55:54 -0400873 params.windowAnimations = atTop ? 0 : R.style.TitleBar;
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400874 // XXX : Without providing an offset, the fake title bar will be
875 // placed underneath the status bar. Use the global visible rect
876 // of mBrowserFrameLayout to determine the bottom of the status bar
Cary Clarka0464552009-09-29 13:00:45 -0400877 params.y = visRect.top;
Leon Scroggins68549862009-09-21 16:02:01 -0400878 // Add a holder for the title bar. It also holds a shadow to show
879 // below the title bar.
Leon Scrogginsd8fd2fc2009-09-16 11:12:09 -0400880 if (mFakeTitleBarHolder == null) {
881 mFakeTitleBarHolder = (ViewGroup) LayoutInflater.from(this)
882 .inflate(R.layout.title_bar_bg, null);
883 }
Leon Scrogginsb94bf272009-09-25 15:22:08 -0400884 Shadow shadow = (Shadow) mFakeTitleBarHolder.findViewById(
885 R.id.shadow);
886 shadow.setWebView(mainView);
Leon Scroggins68549862009-09-21 16:02:01 -0400887 mFakeTitleBarHolder.addView(mFakeTitleBar, 0, mFakeTitleBarParams);
Leon Scrogginsd8fd2fc2009-09-16 11:12:09 -0400888 manager.addView(mFakeTitleBarHolder, params);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400889 }
890 }
891
892 @Override
893 public void onOptionsMenuClosed(Menu menu) {
894 mOptionsMenuOpen = false;
Leon Scrogginsa27ff192009-09-14 12:58:04 -0400895 if (!mInLoad) {
896 hideFakeTitleBar();
897 } else if (!mIconView) {
898 // The page is currently loading, and we are in expanded mode, so
899 // we were not showing the menu. Show it once again. It will be
900 // removed when the page finishes.
901 showFakeTitleBar();
902 }
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400903 }
Grace Kloba22ac16e2009-10-07 18:00:23 -0700904
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400905 private void hideFakeTitleBar() {
Leon Scrogginsfe87bd32009-10-06 10:10:00 -0400906 if (mFakeTitleBar.getParent() == null) return;
Leon Scroggins20329572009-09-23 17:42:41 -0400907 WindowManager.LayoutParams params = (WindowManager.LayoutParams)
908 mFakeTitleBarHolder.getLayoutParams();
909 WebView mainView = mTabControl.getCurrentWebView();
910 // Although we decided whether or not to animate based on the current
911 // scroll position, the scroll position may have changed since the
912 // fake title bar was displayed. Make sure it has the appropriate
913 // animation/lack thereof before removing.
914 params.windowAnimations = mainView != null && mainView.getScrollY() == 0
Leon Scroggins83932c72009-09-30 11:55:54 -0400915 ? 0 : R.style.TitleBar;
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400916 WindowManager manager
917 = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
Leon Scroggins20329572009-09-23 17:42:41 -0400918 manager.updateViewLayout(mFakeTitleBarHolder, params);
Leon Scrogginsd8fd2fc2009-09-16 11:12:09 -0400919 mFakeTitleBarHolder.removeView(mFakeTitleBar);
920 manager.removeView(mFakeTitleBarHolder);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400921 }
922
The Android Open Source Project0c908882009-03-03 19:32:16 -0800923 /**
Leon Scrogginsc6fa1102009-09-21 10:40:01 -0400924 * Special method for the fake title bar to call when displaying its context
925 * menu, since it is in its own Window, and its parent does not show a
926 * context menu.
927 */
928 /* package */ void showTitleBarContextMenu() {
Cary Clark65f4a3c2009-09-28 17:05:06 -0400929 if (null == mTitleBar.getParent()) {
930 return;
931 }
Leon Scrogginsc6fa1102009-09-21 10:40:01 -0400932 openContextMenu(mTitleBar);
933 }
934
Leon Scrogginsb2b19f52009-10-09 16:10:00 -0400935 @Override
936 public void onContextMenuClosed(Menu menu) {
937 super.onContextMenuClosed(menu);
938 if (mInLoad) {
939 showFakeTitleBar();
940 }
941 }
942
Leon Scrogginsc6fa1102009-09-21 10:40:01 -0400943 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -0800944 * onSaveInstanceState(Bundle map)
945 * onSaveInstanceState is called right before onStop(). The map contains
946 * the saved state.
947 */
Grace Kloba22ac16e2009-10-07 18:00:23 -0700948 @Override
949 protected void onSaveInstanceState(Bundle outState) {
Dave Bort31a6d1c2009-04-13 15:56:49 -0700950 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800951 Log.v(LOGTAG, "BrowserActivity.onSaveInstanceState: this=" + this);
952 }
953 // the default implementation requires each view to have an id. As the
954 // browser handles the state itself and it doesn't use id for the views,
955 // don't call the default implementation. Otherwise it will trigger the
956 // warning like this, "couldn't save which view has focus because the
957 // focused view XXX has no id".
958
959 // Save all the tabs
960 mTabControl.saveState(outState);
961 }
962
Grace Kloba22ac16e2009-10-07 18:00:23 -0700963 @Override
964 protected void onPause() {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800965 super.onPause();
966
967 if (mActivityInPause) {
968 Log.e(LOGTAG, "BrowserActivity is already paused.");
969 return;
970 }
971
Mike Reed7bfa63b2009-05-28 11:08:32 -0400972 mTabControl.pauseCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800973 mActivityInPause = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -0400974 if (mTabControl.getCurrentIndex() >= 0 && !pauseWebViewTimers()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800975 mWakeLock.acquire();
976 mHandler.sendMessageDelayed(mHandler
977 .obtainMessage(RELEASE_WAKELOCK), WAKELOCK_TIMEOUT);
978 }
979
Leon Scrogginsa2ab6a72009-09-11 11:49:52 -0400980 // FIXME: This removes the active tabs page and resets the menu to
981 // MAIN_MENU. A better solution might be to do this work in onNewIntent
982 // but then we would need to save it in onSaveInstanceState and restore
983 // it in onCreate/onRestoreInstanceState
984 if (mActiveTabsPage != null) {
985 removeActiveTabPage(true);
986 }
987
The Android Open Source Project0c908882009-03-03 19:32:16 -0800988 cancelStopToast();
989
990 // unregister network state listener
991 unregisterReceiver(mNetworkStateIntentReceiver);
992 WebView.disablePlatformNotifications();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800993 }
994
Grace Kloba22ac16e2009-10-07 18:00:23 -0700995 @Override
996 protected void onDestroy() {
Dave Bort31a6d1c2009-04-13 15:56:49 -0700997 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800998 Log.v(LOGTAG, "BrowserActivity.onDestroy: this=" + this);
999 }
1000 super.onDestroy();
Grace Kloba0923d692009-09-23 21:37:25 -07001001
Leon Scroggins8d5fa432009-10-02 15:55:59 -04001002 if (mUploadMessage != null) {
1003 mUploadMessage.onReceiveValue(null);
1004 mUploadMessage = null;
1005 }
1006
Grace Kloba0923d692009-09-23 21:37:25 -07001007 if (mTabControl == null) return;
1008
Grace Kloba1fc98a32009-10-21 13:23:08 -07001009 // Remove the fake title bar if it is there
1010 hideFakeTitleBar();
1011
The Android Open Source Project0c908882009-03-03 19:32:16 -08001012 // Remove the current tab and sub window
Grace Kloba22ac16e2009-10-07 18:00:23 -07001013 Tab t = mTabControl.getCurrentTab();
Patrick Scottfb5e77f2009-04-08 19:17:37 -07001014 if (t != null) {
1015 dismissSubWindow(t);
1016 removeTabFromContentView(t);
1017 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001018 // Destroy all the tabs
1019 mTabControl.destroy();
1020 WebIconDatabase.getInstance().close();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001021
Grace Klobab4da0ad2009-05-14 14:45:40 -07001022 unregisterReceiver(mPackageInstallationReceiver);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001023 }
1024
1025 @Override
1026 public void onConfigurationChanged(Configuration newConfig) {
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04001027 mConfigChanged = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001028 super.onConfigurationChanged(newConfig);
1029
1030 if (mPageInfoDialog != null) {
1031 mPageInfoDialog.dismiss();
1032 showPageInfo(
1033 mPageInfoView,
Leon Scrogginsc7b92f82010-01-11 18:17:31 -05001034 mPageInfoFromShowSSLCertificateOnError);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001035 }
1036 if (mSSLCertificateDialog != null) {
1037 mSSLCertificateDialog.dismiss();
1038 showSSLCertificate(
1039 mSSLCertificateView);
1040 }
1041 if (mSSLCertificateOnErrorDialog != null) {
1042 mSSLCertificateOnErrorDialog.dismiss();
1043 showSSLCertificateOnError(
1044 mSSLCertificateOnErrorView,
1045 mSSLCertificateOnErrorHandler,
1046 mSSLCertificateOnErrorError);
1047 }
1048 if (mHttpAuthenticationDialog != null) {
1049 String title = ((TextView) mHttpAuthenticationDialog
1050 .findViewById(com.android.internal.R.id.alertTitle)).getText()
1051 .toString();
1052 String name = ((TextView) mHttpAuthenticationDialog
1053 .findViewById(R.id.username_edit)).getText().toString();
1054 String password = ((TextView) mHttpAuthenticationDialog
1055 .findViewById(R.id.password_edit)).getText().toString();
1056 int focusId = mHttpAuthenticationDialog.getCurrentFocus()
1057 .getId();
1058 mHttpAuthenticationDialog.dismiss();
1059 showHttpAuthentication(mHttpAuthHandler, null, null, title,
1060 name, password, focusId);
1061 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001062 }
1063
Grace Kloba22ac16e2009-10-07 18:00:23 -07001064 @Override
1065 public void onLowMemory() {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001066 super.onLowMemory();
1067 mTabControl.freeMemory();
1068 }
1069
Mike Reed7bfa63b2009-05-28 11:08:32 -04001070 private boolean resumeWebViewTimers() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001071 Tab tab = mTabControl.getCurrentTab();
1072 boolean inLoad = tab.inLoad();
1073 if ((!mActivityInPause && !inLoad) || (mActivityInPause && inLoad)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001074 CookieSyncManager.getInstance().startSync();
Grace Kloba22ac16e2009-10-07 18:00:23 -07001075 WebView w = tab.getWebView();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001076 if (w != null) {
1077 w.resumeTimers();
1078 }
1079 return true;
1080 } else {
1081 return false;
1082 }
1083 }
1084
Mike Reed7bfa63b2009-05-28 11:08:32 -04001085 private boolean pauseWebViewTimers() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001086 Tab tab = mTabControl.getCurrentTab();
1087 boolean inLoad = tab.inLoad();
1088 if (mActivityInPause && !inLoad) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001089 CookieSyncManager.getInstance().stopSync();
1090 WebView w = mTabControl.getCurrentWebView();
1091 if (w != null) {
1092 w.pauseTimers();
1093 }
1094 return true;
1095 } else {
1096 return false;
1097 }
1098 }
1099
The Android Open Source Project0c908882009-03-03 19:32:16 -08001100 // Open the icon database and retain all the icons for visited sites.
1101 private void retainIconsOnStartup() {
1102 final WebIconDatabase db = WebIconDatabase.getInstance();
1103 db.open(getDir("icons", 0).getPath());
Leon Scroggins2c0f6112010-03-12 18:09:39 -05001104 Cursor c = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001105 try {
Leon Scroggins2c0f6112010-03-12 18:09:39 -05001106 c = Browser.getAllBookmarks(mResolver);
1107 if (c.moveToFirst()) {
1108 int urlIndex = c.getColumnIndex(Browser.BookmarkColumns.URL);
1109 do {
1110 String url = c.getString(urlIndex);
1111 db.retainIconForPageUrl(url);
1112 } while (c.moveToNext());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001113 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001114 } catch (IllegalStateException e) {
1115 Log.e(LOGTAG, "retainIconsOnStartup", e);
Leon Scroggins2c0f6112010-03-12 18:09:39 -05001116 } finally {
1117 if (c!= null) c.close();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001118 }
1119 }
1120
1121 // Helper method for getting the top window.
1122 WebView getTopWindow() {
1123 return mTabControl.getCurrentTopWebView();
1124 }
1125
Grace Kloba22ac16e2009-10-07 18:00:23 -07001126 TabControl getTabControl() {
1127 return mTabControl;
1128 }
1129
The Android Open Source Project0c908882009-03-03 19:32:16 -08001130 @Override
1131 public boolean onCreateOptionsMenu(Menu menu) {
1132 super.onCreateOptionsMenu(menu);
1133
1134 MenuInflater inflater = getMenuInflater();
1135 inflater.inflate(R.menu.browser, menu);
1136 mMenu = menu;
1137 updateInLoadMenuItems();
1138 return true;
1139 }
1140
1141 /**
1142 * As the menu can be open when loading state changes
1143 * we must manually update the state of the stop/reload menu
1144 * item
1145 */
1146 private void updateInLoadMenuItems() {
1147 if (mMenu == null) {
1148 return;
1149 }
1150 MenuItem src = mInLoad ?
1151 mMenu.findItem(R.id.stop_menu_id):
1152 mMenu.findItem(R.id.reload_menu_id);
1153 MenuItem dest = mMenu.findItem(R.id.stop_reload_menu_id);
1154 dest.setIcon(src.getIcon());
1155 dest.setTitle(src.getTitle());
1156 }
1157
1158 @Override
1159 public boolean onContextItemSelected(MenuItem item) {
1160 // chording is not an issue with context menus, but we use the same
1161 // options selector, so set mCanChord to true so we can access them.
1162 mCanChord = true;
1163 int id = item.getItemId();
Leon Scroggins96afcb12009-12-10 12:35:56 -05001164 boolean result = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001165 switch (id) {
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001166 // For the context menu from the title bar
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001167 case R.id.title_bar_copy_page_url:
Leon Scroggins96afcb12009-12-10 12:35:56 -05001168 Tab currentTab = mTabControl.getCurrentTab();
1169 if (null == currentTab) {
1170 result = false;
1171 break;
1172 }
1173 WebView mainView = currentTab.getWebView();
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001174 if (null == mainView) {
Leon Scroggins96afcb12009-12-10 12:35:56 -05001175 result = false;
1176 break;
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001177 }
Leon Scroggins96afcb12009-12-10 12:35:56 -05001178 copy(mainView.getUrl());
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001179 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001180 // -- Browser context menu
1181 case R.id.open_context_menu_id:
1182 case R.id.open_newtab_context_menu_id:
1183 case R.id.bookmark_context_menu_id:
1184 case R.id.save_link_context_menu_id:
1185 case R.id.share_link_context_menu_id:
1186 case R.id.copy_link_context_menu_id:
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001187 final WebView webView = getTopWindow();
1188 if (null == webView) {
Leon Scroggins96afcb12009-12-10 12:35:56 -05001189 result = false;
1190 break;
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001191 }
1192 final HashMap hrefMap = new HashMap();
1193 hrefMap.put("webview", webView);
1194 final Message msg = mHandler.obtainMessage(
1195 FOCUS_NODE_HREF, id, 0, hrefMap);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001196 webView.requestFocusNodeHref(msg);
1197 break;
1198
1199 default:
1200 // For other context menus
Leon Scroggins96afcb12009-12-10 12:35:56 -05001201 result = onOptionsItemSelected(item);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001202 }
1203 mCanChord = false;
Leon Scroggins96afcb12009-12-10 12:35:56 -05001204 return result;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001205 }
1206
1207 private Bundle createGoogleSearchSourceBundle(String source) {
1208 Bundle bundle = new Bundle();
Bjorn Bringert10d1cca2010-02-10 14:22:12 +00001209 bundle.putString(Search.SOURCE, source);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001210 return bundle;
1211 }
1212
Leon Scroggins8ad29922010-02-16 12:33:55 -05001213 /* package */ void editUrl() {
Leon Scroggins68579392009-09-15 15:31:54 -04001214 if (mOptionsMenuOpen) closeOptionsMenu();
Leon Scroggins5bbe9802009-07-31 13:10:55 -04001215 String url = (getTopWindow() == null) ? null : getTopWindow().getUrl();
Grace Kloba83f47342009-07-20 10:44:31 -07001216 startSearch(mSettings.getHomePage().equals(url) ? null : url, true,
Leon Scroggins8ad29922010-02-16 12:33:55 -05001217 null, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001218 }
1219
Leon Scroggins8ad29922010-02-16 12:33:55 -05001220 /**
1221 * Overriding this to insert a local information bundle
1222 */
The Android Open Source Project0c908882009-03-03 19:32:16 -08001223 @Override
1224 public void startSearch(String initialQuery, boolean selectInitialQuery,
1225 Bundle appSearchData, boolean globalSearch) {
1226 if (appSearchData == null) {
1227 appSearchData = createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_TYPE);
1228 }
1229 super.startSearch(initialQuery, selectInitialQuery, appSearchData, globalSearch);
1230 }
1231
Leon Scroggins1f005d32009-08-10 17:36:42 -04001232 /**
1233 * Switch tabs. Called by the TitleBarSet when sliding the title bar
1234 * results in changing tabs.
Leon Scroggins160a7e72009-08-14 18:28:01 -04001235 * @param index Index of the tab to change to, as defined by
1236 * mTabControl.getTabIndex(Tab t).
1237 * @return boolean True if we successfully switched to a different tab. If
1238 * the indexth tab is null, or if that tab is the same as
1239 * the current one, return false.
Leon Scroggins1f005d32009-08-10 17:36:42 -04001240 */
Leon Scroggins160a7e72009-08-14 18:28:01 -04001241 /* package */ boolean switchToTab(int index) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001242 Tab tab = mTabControl.getTab(index);
1243 Tab currentTab = mTabControl.getCurrentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04001244 if (tab == null || tab == currentTab) {
Leon Scroggins160a7e72009-08-14 18:28:01 -04001245 return false;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001246 }
1247 if (currentTab != null) {
1248 // currentTab may be null if it was just removed. In that case,
1249 // we do not need to remove it
1250 removeTabFromContentView(currentTab);
1251 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001252 mTabControl.setCurrentTab(tab);
1253 attachTabToContentView(tab);
Grace Klobaeb6eef42009-09-15 17:56:32 -07001254 resetTitleIconAndProgress();
1255 updateLockIconToLatest();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001256 return true;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001257 }
1258
Grace Kloba22ac16e2009-10-07 18:00:23 -07001259 /* package */ Tab openTabToHomePage() {
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001260 return openTabAndShow(mSettings.getHomePage(), false, null);
1261 }
1262
Leon Scroggins1f005d32009-08-10 17:36:42 -04001263 /* package */ void closeCurrentWindow() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001264 final Tab current = mTabControl.getCurrentTab();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001265 if (mTabControl.getTabCount() == 1) {
Leon Scroggins30444232009-09-04 18:36:20 -04001266 // This is the last tab. Open a new one, with the home
1267 // page and close the current one.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001268 openTabToHomePage();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001269 closeTab(current);
Leon Scroggins160a7e72009-08-14 18:28:01 -04001270 return;
1271 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07001272 final Tab parent = current.getParentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04001273 int indexToShow = -1;
1274 if (parent != null) {
1275 indexToShow = mTabControl.getTabIndex(parent);
1276 } else {
Leon Scroggins160a7e72009-08-14 18:28:01 -04001277 final int currentIndex = mTabControl.getCurrentIndex();
1278 // Try to move to the tab to the right
1279 indexToShow = currentIndex + 1;
1280 if (indexToShow > mTabControl.getTabCount() - 1) {
1281 // Try to move to the tab to the left
1282 indexToShow = currentIndex - 1;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001283 }
1284 }
Leon Scroggins160a7e72009-08-14 18:28:01 -04001285 if (switchToTab(indexToShow)) {
1286 // Close window
1287 closeTab(current);
1288 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001289 }
1290
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001291 private ActiveTabsPage mActiveTabsPage;
1292
1293 /**
1294 * Remove the active tabs page.
1295 * @param needToAttach If true, the active tabs page did not attach a tab
1296 * to the content view, so we need to do that here.
1297 */
1298 /* package */ void removeActiveTabPage(boolean needToAttach) {
1299 mContentView.removeView(mActiveTabsPage);
1300 mActiveTabsPage = null;
1301 mMenuState = R.id.MAIN_MENU;
1302 if (needToAttach) {
1303 attachTabToContentView(mTabControl.getCurrentTab());
1304 }
1305 getTopWindow().requestFocus();
1306 }
1307
The Android Open Source Project0c908882009-03-03 19:32:16 -08001308 @Override
1309 public boolean onOptionsItemSelected(MenuItem item) {
1310 if (!mCanChord) {
1311 // The user has already fired a shortcut with this hold down of the
1312 // menu key.
1313 return false;
1314 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001315 if (null == getTopWindow()) {
Leon Scroggins0d7ae0e2009-06-05 11:04:45 -04001316 return false;
1317 }
Grace Kloba6ee9c492009-07-13 10:04:34 -07001318 if (mMenuIsDown) {
1319 // The shortcut action consumes the MENU. Even if it is still down,
1320 // it won't trigger the next shortcut action. In the case of the
1321 // shortcut action triggering a new activity, like Bookmarks, we
1322 // won't get onKeyUp for MENU. So it is important to reset it here.
1323 mMenuIsDown = false;
1324 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001325 switch (item.getItemId()) {
1326 // -- Main menu
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001327 case R.id.new_tab_menu_id:
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001328 openTabToHomePage();
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001329 break;
1330
Leon Scroggins64b80f32009-08-07 12:03:34 -04001331 case R.id.goto_menu_id:
Leon Scroggins8ad29922010-02-16 12:33:55 -05001332 editUrl();
Leon Scrogginsb3a5bed2009-09-28 11:21:56 -04001333 break;
1334
1335 case R.id.bookmarks_menu_id:
Leon Scroggins30444232009-09-04 18:36:20 -04001336 bookmarksOrHistoryPicker(false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001337 break;
1338
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001339 case R.id.active_tabs_menu_id:
1340 mActiveTabsPage = new ActiveTabsPage(this, mTabControl);
1341 removeTabFromContentView(mTabControl.getCurrentTab());
Leon Scroggins43de6162009-09-14 19:59:58 -04001342 hideFakeTitleBar();
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001343 mContentView.addView(mActiveTabsPage, COVER_SCREEN_PARAMS);
1344 mActiveTabsPage.requestFocus();
1345 mMenuState = EMPTY_MENU;
1346 break;
1347
Leon Scroggins1f005d32009-08-10 17:36:42 -04001348 case R.id.add_bookmark_menu_id:
1349 Intent i = new Intent(BrowserActivity.this,
1350 AddBookmarkPage.class);
1351 WebView w = getTopWindow();
1352 i.putExtra("url", w.getUrl());
1353 i.putExtra("title", w.getTitle());
Grace Kloba83cdb2c2009-09-16 00:48:57 -07001354 i.putExtra("touch_icon_url", w.getTouchIconUrl());
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01001355 i.putExtra("thumbnail", createScreenshot(w));
Leon Scroggins1f005d32009-08-10 17:36:42 -04001356 startActivity(i);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001357 break;
1358
1359 case R.id.stop_reload_menu_id:
1360 if (mInLoad) {
1361 stopLoading();
1362 } else {
1363 getTopWindow().reload();
1364 }
1365 break;
1366
1367 case R.id.back_menu_id:
1368 getTopWindow().goBack();
1369 break;
1370
1371 case R.id.forward_menu_id:
1372 getTopWindow().goForward();
1373 break;
1374
1375 case R.id.close_menu_id:
1376 // Close the subwindow if it exists.
1377 if (mTabControl.getCurrentSubWindow() != null) {
1378 dismissSubWindow(mTabControl.getCurrentTab());
1379 break;
1380 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001381 closeCurrentWindow();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001382 break;
1383
1384 case R.id.homepage_menu_id:
Grace Kloba22ac16e2009-10-07 18:00:23 -07001385 Tab current = mTabControl.getCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001386 if (current != null) {
1387 dismissSubWindow(current);
Leon Scroggins92472e82010-02-17 16:32:28 -05001388 loadUrl(current.getWebView(), mSettings.getHomePage());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001389 }
1390 break;
1391
1392 case R.id.preferences_menu_id:
1393 Intent intent = new Intent(this,
1394 BrowserPreferencesPage.class);
Leon Scrogginsd5304942009-12-10 16:11:39 -05001395 intent.putExtra(BrowserPreferencesPage.CURRENT_PAGE,
1396 getTopWindow().getUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001397 startActivityForResult(intent, PREFERENCES_PAGE);
1398 break;
1399
1400 case R.id.find_menu_id:
1401 if (null == mFindDialog) {
1402 mFindDialog = new FindDialog(this);
1403 }
1404 mFindDialog.setWebView(getTopWindow());
1405 mFindDialog.show();
Cary Clark7d3ac792010-03-03 10:11:44 -05001406 getTopWindow().setFindIsUp(true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001407 mMenuState = EMPTY_MENU;
1408 break;
1409
1410 case R.id.select_text_id:
1411 getTopWindow().emulateShiftHeld();
1412 break;
1413 case R.id.page_info_menu_id:
1414 showPageInfo(mTabControl.getCurrentTab(), false);
1415 break;
1416
1417 case R.id.classic_history_menu_id:
Leon Scroggins30444232009-09-04 18:36:20 -04001418 bookmarksOrHistoryPicker(true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001419 break;
1420
Leon Scroggins96afcb12009-12-10 12:35:56 -05001421 case R.id.title_bar_share_page_url:
The Android Open Source Project0c908882009-03-03 19:32:16 -08001422 case R.id.share_page_menu_id:
Leon Scroggins96afcb12009-12-10 12:35:56 -05001423 Tab currentTab = mTabControl.getCurrentTab();
1424 if (null == currentTab) {
1425 mCanChord = false;
1426 return false;
1427 }
1428 currentTab.populatePickerData();
1429 sharePage(this, currentTab.getTitle(),
1430 currentTab.getUrl(), currentTab.getFavicon(),
1431 createScreenshot(currentTab.getWebView()));
The Android Open Source Project0c908882009-03-03 19:32:16 -08001432 break;
1433
1434 case R.id.dump_nav_menu_id:
1435 getTopWindow().debugDump();
1436 break;
1437
Andrei Popescu7a8b88b2010-02-02 00:30:38 +00001438 case R.id.dump_counters_menu_id:
1439 getTopWindow().dumpV8Counters();
1440 break;
1441
The Android Open Source Project0c908882009-03-03 19:32:16 -08001442 case R.id.zoom_in_menu_id:
1443 getTopWindow().zoomIn();
1444 break;
1445
1446 case R.id.zoom_out_menu_id:
1447 getTopWindow().zoomOut();
1448 break;
1449
1450 case R.id.view_downloads_menu_id:
1451 viewDownloads(null);
1452 break;
1453
The Android Open Source Project0c908882009-03-03 19:32:16 -08001454 case R.id.window_one_menu_id:
1455 case R.id.window_two_menu_id:
1456 case R.id.window_three_menu_id:
1457 case R.id.window_four_menu_id:
1458 case R.id.window_five_menu_id:
1459 case R.id.window_six_menu_id:
1460 case R.id.window_seven_menu_id:
1461 case R.id.window_eight_menu_id:
1462 {
1463 int menuid = item.getItemId();
1464 for (int id = 0; id < WINDOW_SHORTCUT_ID_ARRAY.length; id++) {
1465 if (WINDOW_SHORTCUT_ID_ARRAY[id] == menuid) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001466 Tab desiredTab = mTabControl.getTab(id);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001467 if (desiredTab != null &&
1468 desiredTab != mTabControl.getCurrentTab()) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001469 switchToTab(id);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001470 }
1471 break;
1472 }
1473 }
1474 }
1475 break;
1476
1477 default:
1478 if (!super.onOptionsItemSelected(item)) {
1479 return false;
1480 }
1481 // Otherwise fall through.
1482 }
1483 mCanChord = false;
1484 return true;
1485 }
1486
1487 public void closeFind() {
1488 mMenuState = R.id.MAIN_MENU;
1489 }
1490
Grace Kloba22ac16e2009-10-07 18:00:23 -07001491 @Override
1492 public boolean onPrepareOptionsMenu(Menu menu) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001493 // This happens when the user begins to hold down the menu key, so
1494 // allow them to chord to get a shortcut.
1495 mCanChord = true;
1496 // Note: setVisible will decide whether an item is visible; while
1497 // setEnabled() will decide whether an item is enabled, which also means
1498 // whether the matching shortcut key will function.
1499 super.onPrepareOptionsMenu(menu);
1500 switch (mMenuState) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001501 case EMPTY_MENU:
1502 if (mCurrentMenuState != mMenuState) {
1503 menu.setGroupVisible(R.id.MAIN_MENU, false);
1504 menu.setGroupEnabled(R.id.MAIN_MENU, false);
1505 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001506 }
1507 break;
1508 default:
1509 if (mCurrentMenuState != mMenuState) {
1510 menu.setGroupVisible(R.id.MAIN_MENU, true);
1511 menu.setGroupEnabled(R.id.MAIN_MENU, true);
1512 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001513 }
1514 final WebView w = getTopWindow();
1515 boolean canGoBack = false;
1516 boolean canGoForward = false;
1517 boolean isHome = false;
1518 if (w != null) {
1519 canGoBack = w.canGoBack();
1520 canGoForward = w.canGoForward();
1521 isHome = mSettings.getHomePage().equals(w.getUrl());
1522 }
1523 final MenuItem back = menu.findItem(R.id.back_menu_id);
1524 back.setEnabled(canGoBack);
1525
1526 final MenuItem home = menu.findItem(R.id.homepage_menu_id);
1527 home.setEnabled(!isHome);
1528
1529 menu.findItem(R.id.forward_menu_id)
1530 .setEnabled(canGoForward);
1531
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001532 menu.findItem(R.id.new_tab_menu_id).setEnabled(
Grace Kloba22ac16e2009-10-07 18:00:23 -07001533 mTabControl.canCreateNewTab());
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001534
The Android Open Source Project0c908882009-03-03 19:32:16 -08001535 // decide whether to show the share link option
1536 PackageManager pm = getPackageManager();
1537 Intent send = new Intent(Intent.ACTION_SEND);
1538 send.setType("text/plain");
1539 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1540 menu.findItem(R.id.share_page_menu_id).setVisible(ri != null);
1541
The Android Open Source Project0c908882009-03-03 19:32:16 -08001542 boolean isNavDump = mSettings.isNavDump();
1543 final MenuItem nav = menu.findItem(R.id.dump_nav_menu_id);
1544 nav.setVisible(isNavDump);
1545 nav.setEnabled(isNavDump);
Andrei Popescu7a8b88b2010-02-02 00:30:38 +00001546
1547 boolean showDebugSettings = mSettings.showDebugSettings();
1548 final MenuItem counter = menu.findItem(R.id.dump_counters_menu_id);
1549 counter.setVisible(showDebugSettings);
1550 counter.setEnabled(showDebugSettings);
1551
The Android Open Source Project0c908882009-03-03 19:32:16 -08001552 break;
1553 }
1554 mCurrentMenuState = mMenuState;
1555 return true;
1556 }
1557
1558 @Override
1559 public void onCreateContextMenu(ContextMenu menu, View v,
1560 ContextMenuInfo menuInfo) {
Leon Scroggins4e9f89b2010-02-22 16:54:14 -05001561 if (v instanceof TitleBar) {
1562 return;
1563 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001564 WebView webview = (WebView) v;
1565 WebView.HitTestResult result = webview.getHitTestResult();
1566 if (result == null) {
1567 return;
1568 }
1569
1570 int type = result.getType();
1571 if (type == WebView.HitTestResult.UNKNOWN_TYPE) {
1572 Log.w(LOGTAG,
1573 "We should not show context menu when nothing is touched");
1574 return;
1575 }
1576 if (type == WebView.HitTestResult.EDIT_TEXT_TYPE) {
1577 // let TextView handles context menu
1578 return;
1579 }
1580
1581 // Note, http://b/issue?id=1106666 is requesting that
1582 // an inflated menu can be used again. This is not available
1583 // yet, so inflate each time (yuk!)
1584 MenuInflater inflater = getMenuInflater();
1585 inflater.inflate(R.menu.browsercontext, menu);
1586
1587 // Show the correct menu group
1588 String extra = result.getExtra();
1589 menu.setGroupVisible(R.id.PHONE_MENU,
1590 type == WebView.HitTestResult.PHONE_TYPE);
1591 menu.setGroupVisible(R.id.EMAIL_MENU,
1592 type == WebView.HitTestResult.EMAIL_TYPE);
1593 menu.setGroupVisible(R.id.GEO_MENU,
1594 type == WebView.HitTestResult.GEO_TYPE);
1595 menu.setGroupVisible(R.id.IMAGE_MENU,
1596 type == WebView.HitTestResult.IMAGE_TYPE
1597 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1598 menu.setGroupVisible(R.id.ANCHOR_MENU,
1599 type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1600 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1601
1602 // Setup custom handling depending on the type
1603 switch (type) {
1604 case WebView.HitTestResult.PHONE_TYPE:
1605 menu.setHeaderTitle(Uri.decode(extra));
1606 menu.findItem(R.id.dial_context_menu_id).setIntent(
1607 new Intent(Intent.ACTION_VIEW, Uri
1608 .parse(WebView.SCHEME_TEL + extra)));
1609 Intent addIntent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
1610 addIntent.putExtra(Insert.PHONE, Uri.decode(extra));
Cary Clark5e335a32009-09-22 14:53:11 -04001611 addIntent.setType(ContactsContract.Contacts.CONTENT_ITEM_TYPE);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001612 menu.findItem(R.id.add_contact_context_menu_id).setIntent(
1613 addIntent);
1614 menu.findItem(R.id.copy_phone_context_menu_id).setOnMenuItemClickListener(
1615 new Copy(extra));
1616 break;
1617
1618 case WebView.HitTestResult.EMAIL_TYPE:
1619 menu.setHeaderTitle(extra);
1620 menu.findItem(R.id.email_context_menu_id).setIntent(
1621 new Intent(Intent.ACTION_VIEW, Uri
1622 .parse(WebView.SCHEME_MAILTO + extra)));
1623 menu.findItem(R.id.copy_mail_context_menu_id).setOnMenuItemClickListener(
1624 new Copy(extra));
1625 break;
1626
1627 case WebView.HitTestResult.GEO_TYPE:
1628 menu.setHeaderTitle(extra);
1629 menu.findItem(R.id.map_context_menu_id).setIntent(
1630 new Intent(Intent.ACTION_VIEW, Uri
1631 .parse(WebView.SCHEME_GEO
1632 + URLEncoder.encode(extra))));
1633 menu.findItem(R.id.copy_geo_context_menu_id).setOnMenuItemClickListener(
1634 new Copy(extra));
1635 break;
1636
1637 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1638 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
1639 TextView titleView = (TextView) LayoutInflater.from(this)
1640 .inflate(android.R.layout.browser_link_context_header,
1641 null);
1642 titleView.setText(extra);
1643 menu.setHeaderView(titleView);
1644 // decide whether to show the open link in new tab option
1645 menu.findItem(R.id.open_newtab_context_menu_id).setVisible(
Grace Kloba22ac16e2009-10-07 18:00:23 -07001646 mTabControl.canCreateNewTab());
Ben Murdochde353622009-10-12 10:29:00 +01001647 menu.findItem(R.id.bookmark_context_menu_id).setVisible(
1648 Bookmarks.urlHasAcceptableScheme(extra));
The Android Open Source Project0c908882009-03-03 19:32:16 -08001649 PackageManager pm = getPackageManager();
1650 Intent send = new Intent(Intent.ACTION_SEND);
1651 send.setType("text/plain");
1652 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1653 menu.findItem(R.id.share_link_context_menu_id).setVisible(ri != null);
1654 if (type == WebView.HitTestResult.SRC_ANCHOR_TYPE) {
1655 break;
1656 }
1657 // otherwise fall through to handle image part
1658 case WebView.HitTestResult.IMAGE_TYPE:
1659 if (type == WebView.HitTestResult.IMAGE_TYPE) {
1660 menu.setHeaderTitle(extra);
1661 }
1662 menu.findItem(R.id.view_image_context_menu_id).setIntent(
1663 new Intent(Intent.ACTION_VIEW, Uri.parse(extra)));
1664 menu.findItem(R.id.download_context_menu_id).
1665 setOnMenuItemClickListener(new Download(extra));
Ben Murdoch4f75ba22009-10-27 11:48:28 +00001666 menu.findItem(R.id.set_wallpaper_context_menu_id).
1667 setOnMenuItemClickListener(new SetAsWallpaper(extra));
The Android Open Source Project0c908882009-03-03 19:32:16 -08001668 break;
1669
1670 default:
1671 Log.w(LOGTAG, "We should not get here.");
1672 break;
1673 }
Leon Scrogginsb2b19f52009-10-09 16:10:00 -04001674 hideFakeTitleBar();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001675 }
1676
The Android Open Source Project0c908882009-03-03 19:32:16 -08001677 // Attach the given tab to the content view.
Grace Klobac928c302009-09-17 11:51:21 -07001678 // this should only be called for the current tab.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001679 private void attachTabToContentView(Tab t) {
Steve Block2bc69912009-07-30 14:45:13 +01001680 // Attach the container that contains the main WebView and any other UI
1681 // associated with the tab.
Patrick Scottd0119532009-09-17 08:00:31 -04001682 t.attachTabToContentView(mContentView);
Ben Murdochbff2d602009-07-01 20:19:05 +01001683
1684 if (mShouldShowErrorConsole) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001685 ErrorConsoleView errorConsole = t.getErrorConsole(true);
Ben Murdochbff2d602009-07-01 20:19:05 +01001686 if (errorConsole.numberOfErrors() == 0) {
1687 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
1688 } else {
1689 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
1690 }
1691
1692 mErrorConsoleContainer.addView(errorConsole,
Romain Guy15b8ec62010-01-08 15:06:43 -08001693 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
Ben Murdochbff2d602009-07-01 20:19:05 +01001694 ViewGroup.LayoutParams.WRAP_CONTENT));
1695 }
1696
Leon Scroggins39ab28e2009-09-02 21:20:30 -04001697 WebView view = t.getWebView();
Leon Scroggins55a5bc22009-09-04 17:00:08 -04001698 view.setEmbeddedTitleBar(mTitleBar);
Leon Scroggins58d56c62010-01-28 15:12:40 -05001699 if (t.isInVoiceSearchMode()) {
1700 showVoiceTitleBar(t.getVoiceDisplayTitle());
1701 } else {
1702 revertVoiceTitleBar();
1703 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001704 // Request focus on the top window.
1705 t.getTopWindow().requestFocus();
1706 }
1707
1708 // Attach a sub window to the main WebView of the given tab.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001709 void attachSubWindow(Tab t) {
Patrick Scottd0119532009-09-17 08:00:31 -04001710 t.attachSubWindow(mContentView);
1711 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001712 }
1713
1714 // Remove the given tab from the content view.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001715 private void removeTabFromContentView(Tab t) {
Steve Block2bc69912009-07-30 14:45:13 +01001716 // Remove the container that contains the main WebView.
Patrick Scottd0119532009-09-17 08:00:31 -04001717 t.removeTabFromContentView(mContentView);
Ben Murdochbff2d602009-07-01 20:19:05 +01001718
Grace Kloba22ac16e2009-10-07 18:00:23 -07001719 ErrorConsoleView errorConsole = t.getErrorConsole(false);
1720 if (errorConsole != null) {
1721 mErrorConsoleContainer.removeView(errorConsole);
Ben Murdochbff2d602009-07-01 20:19:05 +01001722 }
1723
Leon Scroggins39ab28e2009-09-02 21:20:30 -04001724 WebView view = t.getWebView();
Leon Scrogginsbb85b902009-09-14 19:27:20 -04001725 if (view != null) {
1726 view.setEmbeddedTitleBar(null);
1727 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001728 }
1729
1730 // Remove the sub window if it exists. Also called by TabControl when the
1731 // user clicks the 'X' to dismiss a sub window.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001732 /* package */ void dismissSubWindow(Tab t) {
Patrick Scottd0119532009-09-17 08:00:31 -04001733 t.removeSubWindow(mContentView);
Grace Kloba22ac16e2009-10-07 18:00:23 -07001734 // dismiss the subwindow. This will destroy the WebView.
1735 t.dismissSubWindow();
Patrick Scottd0119532009-09-17 08:00:31 -04001736 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001737 }
1738
Leon Scroggins1f005d32009-08-10 17:36:42 -04001739 // A wrapper function of {@link #openTabAndShow(UrlData, boolean, String)}
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07001740 // that accepts url as string.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001741 private Tab openTabAndShow(String url, boolean closeOnExit, String appId) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001742 return openTabAndShow(new UrlData(url), closeOnExit, appId);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001743 }
1744
1745 // This method does a ton of stuff. It will attempt to create a new tab
1746 // if we haven't reached MAX_TABS. Otherwise it uses the current tab. If
Leon Scroggins1f005d32009-08-10 17:36:42 -04001747 // url isn't null, it will load the given url.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001748 /* package */Tab openTabAndShow(UrlData urlData, boolean closeOnExit,
1749 String appId) {
1750 final Tab currentTab = mTabControl.getCurrentTab();
1751 if (mTabControl.canCreateNewTab()) {
1752 final Tab tab = mTabControl.createNewTab(closeOnExit, appId,
1753 urlData.mUrl);
Leon Scroggins1f005d32009-08-10 17:36:42 -04001754 WebView webview = tab.getWebView();
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001755 // If the last tab was removed from the active tabs page, currentTab
1756 // will be null.
1757 if (currentTab != null) {
1758 removeTabFromContentView(currentTab);
1759 }
Patrick Scott8bbd69f2009-08-14 13:35:53 -04001760 // We must set the new tab as the current tab to reflect the old
1761 // animation behavior.
1762 mTabControl.setCurrentTab(tab);
Grace Klobaeb6eef42009-09-15 17:56:32 -07001763 attachTabToContentView(tab);
Leon Scroggins160a7e72009-08-14 18:28:01 -04001764 if (!urlData.isEmpty()) {
Patrick Scott9d53da02010-02-19 10:19:01 -05001765 loadUrlDataIn(tab, urlData);
Leon Scroggins1f005d32009-08-10 17:36:42 -04001766 }
1767 return tab;
1768 } else {
1769 // Get rid of the subwindow if it exists
1770 dismissSubWindow(currentTab);
1771 if (!urlData.isEmpty()) {
1772 // Load the given url.
Patrick Scott9d53da02010-02-19 10:19:01 -05001773 loadUrlDataIn(currentTab, urlData);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001774 }
Leon Scroggins58d56c62010-01-28 15:12:40 -05001775 return currentTab;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001776 }
1777 }
1778
Grace Kloba22ac16e2009-10-07 18:00:23 -07001779 private Tab openTab(String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001780 if (mSettings.openInBackground()) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001781 Tab t = mTabControl.createNewTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001782 if (t != null) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001783 WebView view = t.getWebView();
Leon Scroggins92472e82010-02-17 16:32:28 -05001784 loadUrl(view, url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001785 }
Grace Klobac9181842009-04-14 08:53:22 -07001786 return t;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001787 } else {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001788 return openTabAndShow(url, false, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001789 }
1790 }
1791
1792 private class Copy implements OnMenuItemClickListener {
1793 private CharSequence mText;
1794
1795 public boolean onMenuItemClick(MenuItem item) {
1796 copy(mText);
1797 return true;
1798 }
1799
1800 public Copy(CharSequence toCopy) {
1801 mText = toCopy;
1802 }
1803 }
1804
1805 private class Download implements OnMenuItemClickListener {
1806 private String mText;
1807
1808 public boolean onMenuItemClick(MenuItem item) {
1809 onDownloadStartNoStream(mText, null, null, null, -1);
1810 return true;
1811 }
1812
1813 public Download(String toDownload) {
1814 mText = toDownload;
1815 }
1816 }
1817
Ben Murdoch4f75ba22009-10-27 11:48:28 +00001818 private class SetAsWallpaper extends Thread implements
1819 OnMenuItemClickListener, DialogInterface.OnCancelListener {
1820 private URL mUrl;
1821 private ProgressDialog mWallpaperProgress;
1822 private boolean mCanceled = false;
1823
1824 public SetAsWallpaper(String url) {
1825 try {
1826 mUrl = new URL(url);
1827 } catch (MalformedURLException e) {
1828 mUrl = null;
1829 }
1830 }
1831
1832 public void onCancel(DialogInterface dialog) {
1833 mCanceled = true;
1834 }
1835
1836 public boolean onMenuItemClick(MenuItem item) {
1837 if (mUrl != null) {
1838 // The user may have tried to set a image with a large file size as their
1839 // background so it may take a few moments to perform the operation. Display
1840 // a progress spinner while it is working.
1841 mWallpaperProgress = new ProgressDialog(BrowserActivity.this);
1842 mWallpaperProgress.setIndeterminate(true);
1843 mWallpaperProgress.setMessage(getText(R.string.progress_dialog_setting_wallpaper));
1844 mWallpaperProgress.setCancelable(true);
1845 mWallpaperProgress.setOnCancelListener(this);
1846 mWallpaperProgress.show();
1847 start();
1848 }
1849 return true;
1850 }
1851
1852 public void run() {
1853 Drawable oldWallpaper = BrowserActivity.this.getWallpaper();
1854 try {
1855 // TODO: This will cause the resource to be downloaded again, when we
1856 // should in most cases be able to grab it from the cache. To fix this
1857 // we should query WebCore to see if we can access a cached version and
1858 // instead open an input stream on that. This pattern could also be used
1859 // in the download manager where the same problem exists.
1860 InputStream inputstream = mUrl.openStream();
1861 if (inputstream != null) {
1862 setWallpaper(inputstream);
1863 }
1864 } catch (IOException e) {
1865 Log.e(LOGTAG, "Unable to set new wallpaper");
1866 // Act as though the user canceled the operation so we try to
1867 // restore the old wallpaper.
1868 mCanceled = true;
1869 }
1870
1871 if (mCanceled) {
1872 // Restore the old wallpaper if the user cancelled whilst we were setting
1873 // the new wallpaper.
1874 int width = oldWallpaper.getIntrinsicWidth();
1875 int height = oldWallpaper.getIntrinsicHeight();
1876 Bitmap bm = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
1877 Canvas canvas = new Canvas(bm);
1878 oldWallpaper.setBounds(0, 0, width, height);
1879 oldWallpaper.draw(canvas);
1880 try {
1881 setWallpaper(bm);
1882 } catch (IOException e) {
1883 Log.e(LOGTAG, "Unable to restore old wallpaper.");
1884 }
1885 mCanceled = false;
1886 }
1887
1888 if (mWallpaperProgress.isShowing()) {
1889 mWallpaperProgress.dismiss();
1890 }
1891 }
1892 }
1893
The Android Open Source Project0c908882009-03-03 19:32:16 -08001894 private void copy(CharSequence text) {
1895 try {
1896 IClipboard clip = IClipboard.Stub.asInterface(ServiceManager.getService("clipboard"));
1897 if (clip != null) {
1898 clip.setClipboardText(text);
1899 }
1900 } catch (android.os.RemoteException e) {
1901 Log.e(LOGTAG, "Copy failed", e);
1902 }
1903 }
1904
1905 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08001906 * Resets the browser title-view to whatever it must be
1907 * (for example, if we had a loading error)
1908 * When we have a new page, we call resetTitle, when we
1909 * have to reset the titlebar to whatever it used to be
1910 * (for example, if the user chose to stop loading), we
1911 * call resetTitleAndRevertLockIcon.
1912 */
1913 /* package */ void resetTitleAndRevertLockIcon() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001914 mTabControl.getCurrentTab().revertLockIcon();
1915 updateLockIconToLatest();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001916 resetTitleIconAndProgress();
1917 }
1918
1919 /**
1920 * Reset the title, favicon, and progress.
1921 */
1922 private void resetTitleIconAndProgress() {
1923 WebView current = mTabControl.getCurrentWebView();
1924 if (current == null) {
1925 return;
1926 }
1927 resetTitleAndIcon(current);
1928 int progress = current.getProgress();
Grace Kloba22ac16e2009-10-07 18:00:23 -07001929 current.getWebChromeClient().onProgressChanged(current, progress);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001930 }
1931
1932 // Reset the title and the icon based on the given item.
1933 private void resetTitleAndIcon(WebView view) {
1934 WebHistoryItem item = view.copyBackForwardList().getCurrentItem();
1935 if (item != null) {
Leon Scroggins68579392009-09-15 15:31:54 -04001936 setUrlTitle(item.getUrl(), item.getTitle());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001937 setFavicon(item.getFavicon());
1938 } else {
Leon Scroggins68579392009-09-15 15:31:54 -04001939 setUrlTitle(null, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001940 setFavicon(null);
1941 }
1942 }
1943
1944 /**
1945 * Sets a title composed of the URL and the title string.
1946 * @param url The URL of the site being loaded.
1947 * @param title The title of the site being loaded.
1948 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07001949 void setUrlTitle(String url, String title) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001950 mUrl = url;
1951 mTitle = title;
1952
Leon Scroggins58d56c62010-01-28 15:12:40 -05001953 // If we are in voice search mode, the title has already been set.
1954 if (mTabControl.getCurrentTab().isInVoiceSearchMode()) return;
1955 mTitleBar.setDisplayTitle(url);
1956 mFakeTitleBar.setDisplayTitle(url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001957 }
1958
1959 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08001960 * @param url The URL to build a title version of the URL from.
1961 * @return The title version of the URL or null if fails.
1962 * The title version of the URL can be either the URL hostname,
1963 * or the hostname with an "https://" prefix (for secure URLs),
1964 * or an empty string if, for example, the URL in question is a
1965 * file:// URL with no hostname.
1966 */
Leon Scroggins32e14a62009-06-11 10:26:34 -04001967 /* package */ static String buildTitleUrl(String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001968 String titleUrl = null;
1969
1970 if (url != null) {
1971 try {
1972 // parse the url string
1973 URL urlObj = new URL(url);
1974 if (urlObj != null) {
1975 titleUrl = "";
1976
1977 String protocol = urlObj.getProtocol();
1978 String host = urlObj.getHost();
1979
1980 if (host != null && 0 < host.length()) {
1981 titleUrl = host;
1982 if (protocol != null) {
1983 // if a secure site, add an "https://" prefix!
1984 if (protocol.equalsIgnoreCase("https")) {
1985 titleUrl = protocol + "://" + host;
1986 }
1987 }
1988 }
1989 }
1990 } catch (MalformedURLException e) {}
1991 }
1992
1993 return titleUrl;
1994 }
1995
1996 // Set the favicon in the title bar.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001997 void setFavicon(Bitmap icon) {
Leon Scroggins68579392009-09-15 15:31:54 -04001998 mTitleBar.setFavicon(icon);
Leon Scrogginsfe87bd32009-10-06 10:10:00 -04001999 mFakeTitleBar.setFavicon(icon);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002000 }
2001
2002 /**
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002003 * Close the tab, remove its associated title bar, and adjust mTabControl's
2004 * current tab to a valid value.
Leon Scroggins1f005d32009-08-10 17:36:42 -04002005 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07002006 /* package */ void closeTab(Tab t) {
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002007 int currentIndex = mTabControl.getCurrentIndex();
2008 int removeIndex = mTabControl.getTabIndex(t);
Leon Scroggins1f005d32009-08-10 17:36:42 -04002009 mTabControl.removeTab(t);
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002010 if (currentIndex >= removeIndex && currentIndex != 0) {
2011 currentIndex--;
2012 }
2013 mTabControl.setCurrentTab(mTabControl.getTab(currentIndex));
Andrei Popescua5bf1de2009-09-23 16:39:23 +01002014 resetTitleIconAndProgress();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002015 }
2016
Leon Scrogginsdcc5eeb2010-02-23 17:26:37 -05002017 /* package */ void goBackOnePageOrQuit() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002018 Tab current = mTabControl.getCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002019 if (current == null) {
2020 /*
2021 * Instead of finishing the activity, simply push this to the back
2022 * of the stack and let ActivityManager to choose the foreground
2023 * activity. As BrowserActivity is singleTask, it will be always the
2024 * root of the task. So we can use either true or false for
2025 * moveTaskToBack().
2026 */
2027 moveTaskToBack(true);
Grace Kloba00d85e72009-09-23 18:50:05 -07002028 return;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002029 }
2030 WebView w = current.getWebView();
2031 if (w.canGoBack()) {
2032 w.goBack();
2033 } else {
2034 // Check to see if we are closing a window that was created by
2035 // another window. If so, we switch back to that window.
Grace Kloba22ac16e2009-10-07 18:00:23 -07002036 Tab parent = current.getParentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002037 if (parent != null) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04002038 switchToTab(mTabControl.getTabIndex(parent));
2039 // Now we close the other tab
2040 closeTab(current);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002041 } else {
2042 if (current.closeOnExit()) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002043 // force the tab's inLoad() to be false as we are going to
2044 // either finish the activity or remove the tab. This will
2045 // ensure pauseWebViewTimers() taking action.
2046 mTabControl.getCurrentTab().clearInLoad();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002047 if (mTabControl.getTabCount() == 1) {
2048 finish();
2049 return;
2050 }
Mike Reed7bfa63b2009-05-28 11:08:32 -04002051 // call pauseWebViewTimers() now, we won't be able to call
2052 // it in onPause() as the WebView won't be valid.
Grace Klobaec1b5ad2009-08-18 08:42:32 -07002053 // Temporarily change mActivityInPause to be true as
2054 // pauseWebViewTimers() will do nothing if mActivityInPause
2055 // is false.
Grace Kloba918e1d72009-08-13 14:55:06 -07002056 boolean savedState = mActivityInPause;
2057 if (savedState) {
Grace Klobaec1b5ad2009-08-18 08:42:32 -07002058 Log.e(LOGTAG, "BrowserActivity is already paused "
2059 + "while handing goBackOnePageOrQuit.");
Grace Kloba918e1d72009-08-13 14:55:06 -07002060 }
2061 mActivityInPause = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -04002062 pauseWebViewTimers();
Grace Kloba918e1d72009-08-13 14:55:06 -07002063 mActivityInPause = savedState;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002064 removeTabFromContentView(current);
2065 mTabControl.removeTab(current);
2066 }
2067 /*
2068 * Instead of finishing the activity, simply push this to the back
2069 * of the stack and let ActivityManager to choose the foreground
2070 * activity. As BrowserActivity is singleTask, it will be always the
2071 * root of the task. So we can use either true or false for
2072 * moveTaskToBack().
2073 */
2074 moveTaskToBack(true);
2075 }
2076 }
2077 }
2078
Grace Kloba22ac16e2009-10-07 18:00:23 -07002079 boolean isMenuDown() {
2080 return mMenuIsDown;
2081 }
2082
Grace Kloba5942df02009-09-18 11:48:29 -07002083 @Override
2084 public boolean onKeyDown(int keyCode, KeyEvent event) {
Leon Scrogginsf65b50d2009-12-08 10:44:28 -05002085 // Even if MENU is already held down, we need to call to super to open
2086 // the IME on long press.
2087 if (KeyEvent.KEYCODE_MENU == keyCode) {
2088 mMenuIsDown = true;
2089 return super.onKeyDown(keyCode, event);
2090 }
Grace Kloba5942df02009-09-18 11:48:29 -07002091 // The default key mode is DEFAULT_KEYS_SEARCH_LOCAL. As the MENU is
2092 // still down, we don't want to trigger the search. Pretend to consume
2093 // the key and do nothing.
2094 if (mMenuIsDown) return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002095
Grace Kloba5942df02009-09-18 11:48:29 -07002096 switch(keyCode) {
Grace Kloba5942df02009-09-18 11:48:29 -07002097 case KeyEvent.KEYCODE_SPACE:
Grace Klobada0fe552009-09-22 18:17:24 -07002098 // WebView/WebTextView handle the keys in the KeyDown. As
2099 // the Activity's shortcut keys are only handled when WebView
2100 // doesn't, have to do it in onKeyDown instead of onKeyUp.
2101 if (event.isShiftPressed()) {
2102 getTopWindow().pageUp(false);
2103 } else {
2104 getTopWindow().pageDown(false);
2105 }
Grace Kloba5942df02009-09-18 11:48:29 -07002106 return true;
2107 case KeyEvent.KEYCODE_BACK:
2108 if (event.getRepeatCount() == 0) {
2109 event.startTracking();
2110 return true;
2111 } else if (mCustomView == null && mActiveTabsPage == null
2112 && event.isLongPress()) {
2113 bookmarksOrHistoryPicker(true);
2114 return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002115 }
Grace Kloba5942df02009-09-18 11:48:29 -07002116 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002117 }
Grace Kloba5942df02009-09-18 11:48:29 -07002118 return super.onKeyDown(keyCode, event);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002119 }
2120
Grace Kloba5942df02009-09-18 11:48:29 -07002121 @Override
2122 public boolean onKeyUp(int keyCode, KeyEvent event) {
2123 switch(keyCode) {
2124 case KeyEvent.KEYCODE_MENU:
2125 mMenuIsDown = false;
2126 break;
Grace Kloba5942df02009-09-18 11:48:29 -07002127 case KeyEvent.KEYCODE_BACK:
2128 if (event.isTracking() && !event.isCanceled()) {
2129 if (mCustomView != null) {
2130 // if a custom view is showing, hide it
Grace Kloba22ac16e2009-10-07 18:00:23 -07002131 mTabControl.getCurrentWebView().getWebChromeClient()
2132 .onHideCustomView();
Grace Kloba5942df02009-09-18 11:48:29 -07002133 } else if (mActiveTabsPage != null) {
2134 // if tab page is showing, hide it
2135 removeActiveTabPage(true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002136 } else {
Grace Kloba5942df02009-09-18 11:48:29 -07002137 WebView subwindow = mTabControl.getCurrentSubWindow();
2138 if (subwindow != null) {
2139 if (subwindow.canGoBack()) {
2140 subwindow.goBack();
2141 } else {
2142 dismissSubWindow(mTabControl.getCurrentTab());
2143 }
2144 } else {
2145 goBackOnePageOrQuit();
2146 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002147 }
Grace Kloba5942df02009-09-18 11:48:29 -07002148 return true;
2149 }
2150 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002151 }
Grace Kloba5942df02009-09-18 11:48:29 -07002152 return super.onKeyUp(keyCode, event);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002153 }
2154
Leon Scroggins68579392009-09-15 15:31:54 -04002155 /* package */ void stopLoading() {
Ben Murdochb7cc8b42009-09-28 10:59:09 +01002156 mDidStopLoad = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002157 resetTitleAndRevertLockIcon();
2158 WebView w = getTopWindow();
2159 w.stopLoading();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002160 // FIXME: before refactor, it is using mWebViewClient. So I keep the
2161 // same logic here. But for subwindow case, should we call into the main
2162 // WebView's onPageFinished as we never call its onPageStarted and if
2163 // the page finishes itself, we don't call onPageFinished.
2164 mTabControl.getCurrentWebView().getWebViewClient().onPageFinished(w,
2165 w.getUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08002166
2167 cancelStopToast();
2168 mStopToast = Toast
2169 .makeText(this, R.string.stopping, Toast.LENGTH_SHORT);
2170 mStopToast.show();
2171 }
2172
Grace Kloba22ac16e2009-10-07 18:00:23 -07002173 boolean didUserStopLoading() {
2174 return mDidStopLoad;
2175 }
2176
The Android Open Source Project0c908882009-03-03 19:32:16 -08002177 private void cancelStopToast() {
2178 if (mStopToast != null) {
2179 mStopToast.cancel();
2180 mStopToast = null;
2181 }
2182 }
2183
Grace Kloba22ac16e2009-10-07 18:00:23 -07002184 // called by a UI or non-UI thread to post the message
2185 public void postMessage(int what, int arg1, int arg2, Object obj,
2186 long delayMillis) {
2187 mHandler.sendMessageDelayed(mHandler.obtainMessage(what, arg1, arg2,
2188 obj), delayMillis);
2189 }
2190
2191 // called by a UI or non-UI thread to remove the message
2192 void removeMessages(int what, Object object) {
2193 mHandler.removeMessages(what, object);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002194 }
2195
2196 // public message ids
2197 public final static int LOAD_URL = 1001;
2198 public final static int STOP_LOAD = 1002;
2199
2200 // Message Ids
2201 private static final int FOCUS_NODE_HREF = 102;
Grace Kloba92c18a52009-07-31 23:48:32 -07002202 private static final int RELEASE_WAKELOCK = 107;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002203
Grace Kloba22ac16e2009-10-07 18:00:23 -07002204 static final int UPDATE_BOOKMARK_THUMBNAIL = 108;
Ben Murdoch2694e232009-09-29 09:41:11 +01002205
The Android Open Source Project0c908882009-03-03 19:32:16 -08002206 // Private handler for handling javascript and saving passwords
2207 private Handler mHandler = new Handler() {
2208
2209 public void handleMessage(Message msg) {
2210 switch (msg.what) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002211 case FOCUS_NODE_HREF:
Ben Murdoch2694e232009-09-29 09:41:11 +01002212 {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002213 String url = (String) msg.getData().get("url");
Ben Murdoch90d088c2009-11-17 18:14:04 +00002214 String title = (String) msg.getData().get("title");
The Android Open Source Project0c908882009-03-03 19:32:16 -08002215 if (url == null || url.length() == 0) {
2216 break;
2217 }
2218 HashMap focusNodeMap = (HashMap) msg.obj;
2219 WebView view = (WebView) focusNodeMap.get("webview");
2220 // Only apply the action if the top window did not change.
2221 if (getTopWindow() != view) {
2222 break;
2223 }
2224 switch (msg.arg1) {
2225 case R.id.open_context_menu_id:
2226 case R.id.view_image_context_menu_id:
Leon Scroggins92472e82010-02-17 16:32:28 -05002227 loadUrlFromContext(getTopWindow(), url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002228 break;
2229 case R.id.open_newtab_context_menu_id:
Grace Kloba22ac16e2009-10-07 18:00:23 -07002230 final Tab parent = mTabControl.getCurrentTab();
2231 final Tab newTab = openTab(url);
Grace Klobac9181842009-04-14 08:53:22 -07002232 if (newTab != parent) {
2233 parent.addChildTab(newTab);
2234 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002235 break;
2236 case R.id.bookmark_context_menu_id:
2237 Intent intent = new Intent(BrowserActivity.this,
2238 AddBookmarkPage.class);
2239 intent.putExtra("url", url);
Ben Murdoch90d088c2009-11-17 18:14:04 +00002240 intent.putExtra("title", title);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002241 startActivity(intent);
2242 break;
2243 case R.id.share_link_context_menu_id:
Leon Scroggins96afcb12009-12-10 12:35:56 -05002244 // See if this site has been visited before
2245 StringBuilder sb = new StringBuilder(
2246 Browser.BookmarkColumns.URL + " = ");
2247 DatabaseUtils.appendEscapedSQLString(sb, url);
2248 Cursor c = mResolver.query(Browser.BOOKMARKS_URI,
2249 Browser.HISTORY_PROJECTION,
2250 sb.toString(),
2251 null,
2252 null);
2253 if (c.moveToFirst()) {
2254 // The site has been visited before, so grab the
2255 // info from the database.
2256 Bitmap favicon = null;
2257 Bitmap thumbnail = null;
2258 String linkTitle = c.getString(Browser.
2259 HISTORY_PROJECTION_TITLE_INDEX);
2260 byte[] data = c.getBlob(Browser.
2261 HISTORY_PROJECTION_FAVICON_INDEX);
2262 if (data != null) {
2263 favicon = BitmapFactory.decodeByteArray(
2264 data, 0, data.length);
2265 }
2266 data = c.getBlob(Browser.
2267 HISTORY_PROJECTION_THUMBNAIL_INDEX);
2268 if (data != null) {
2269 thumbnail = BitmapFactory.decodeByteArray(
2270 data, 0, data.length);
2271 }
2272 sharePage(BrowserActivity.this,
2273 linkTitle, url, favicon, thumbnail);
2274 } else {
2275 Browser.sendString(BrowserActivity.this, url,
2276 getString(
2277 R.string.choosertitle_sharevia));
2278 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002279 break;
2280 case R.id.copy_link_context_menu_id:
2281 copy(url);
2282 break;
2283 case R.id.save_link_context_menu_id:
2284 case R.id.download_context_menu_id:
2285 onDownloadStartNoStream(url, null, null, null, -1);
2286 break;
2287 }
2288 break;
Ben Murdoch2694e232009-09-29 09:41:11 +01002289 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002290
2291 case LOAD_URL:
Leon Scroggins92472e82010-02-17 16:32:28 -05002292 loadUrlFromContext(getTopWindow(), (String) msg.obj);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002293 break;
2294
2295 case STOP_LOAD:
2296 stopLoading();
2297 break;
2298
The Android Open Source Project0c908882009-03-03 19:32:16 -08002299 case RELEASE_WAKELOCK:
2300 if (mWakeLock.isHeld()) {
2301 mWakeLock.release();
Grace Kloba5d0e02e2009-10-05 15:15:36 -07002302 // if we reach here, Browser should be still in the
2303 // background loading after WAKELOCK_TIMEOUT (5-min).
2304 // To avoid burning the battery, stop loading.
2305 mTabControl.stopAllLoading();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002306 }
2307 break;
Ben Murdoch2694e232009-09-29 09:41:11 +01002308
2309 case UPDATE_BOOKMARK_THUMBNAIL:
2310 WebView view = (WebView) msg.obj;
2311 if (view != null) {
2312 updateScreenshot(view);
2313 }
2314 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002315 }
2316 }
2317 };
2318
Leon Scroggins96afcb12009-12-10 12:35:56 -05002319 /**
2320 * Share a page, providing the title, url, favicon, and a screenshot. Uses
2321 * an {@link Intent} to launch the Activity chooser.
2322 * @param c Context used to launch a new Activity.
2323 * @param title Title of the page. Stored in the Intent with
Paul Westbrook03e6d392010-02-12 10:33:29 -08002324 * {@link Intent#EXTRA_SUBJECT}
Leon Scroggins96afcb12009-12-10 12:35:56 -05002325 * @param url URL of the page. Stored in the Intent with
2326 * {@link Intent#EXTRA_TEXT}
2327 * @param favicon Bitmap of the favicon for the page. Stored in the Intent
2328 * with {@link Browser#EXTRA_SHARE_FAVICON}
2329 * @param screenshot Bitmap of a screenshot of the page. Stored in the
2330 * Intent with {@link Browser#EXTRA_SHARE_SCREENSHOT}
2331 */
2332 public static final void sharePage(Context c, String title, String url,
2333 Bitmap favicon, Bitmap screenshot) {
2334 Intent send = new Intent(Intent.ACTION_SEND);
2335 send.setType("text/plain");
2336 send.putExtra(Intent.EXTRA_TEXT, url);
Paul Westbrook03e6d392010-02-12 10:33:29 -08002337 send.putExtra(Intent.EXTRA_SUBJECT, title);
Leon Scroggins96afcb12009-12-10 12:35:56 -05002338 send.putExtra(Browser.EXTRA_SHARE_FAVICON, favicon);
2339 send.putExtra(Browser.EXTRA_SHARE_SCREENSHOT, screenshot);
2340 try {
2341 c.startActivity(Intent.createChooser(send, c.getString(
2342 R.string.choosertitle_sharevia)));
2343 } catch(android.content.ActivityNotFoundException ex) {
2344 // if no app handles it, do nothing
2345 }
2346 }
2347
Leon Scroggins89c6d362009-07-15 16:54:37 -04002348 private void updateScreenshot(WebView view) {
2349 // If this is a bookmarked site, add a screenshot to the database.
2350 // FIXME: When should we update? Every time?
2351 // FIXME: Would like to make sure there is actually something to
2352 // draw, but the API for that (WebViewCore.pictureReady()) is not
2353 // currently accessible here.
Ben Murdochaac7aa62009-09-17 16:57:40 +01002354
Patrick Scott3918d442009-08-04 13:22:29 -04002355 ContentResolver cr = getContentResolver();
2356 final Cursor c = BrowserBookmarksAdapter.queryBookmarksForUrl(
Ben Murdochaac7aa62009-09-17 16:57:40 +01002357 cr, view.getOriginalUrl(), view.getUrl(), true);
Patrick Scott3918d442009-08-04 13:22:29 -04002358 if (c != null) {
Leon Scroggins89c6d362009-07-15 16:54:37 -04002359 boolean succeed = c.moveToFirst();
2360 ContentValues values = null;
2361 while (succeed) {
2362 if (values == null) {
2363 final ByteArrayOutputStream os
2364 = new ByteArrayOutputStream();
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002365 Bitmap bm = createScreenshot(view);
Leon Scroggins45800572009-09-29 16:38:47 -04002366 if (bm == null) {
2367 c.close();
2368 return;
2369 }
Leon Scroggins89c6d362009-07-15 16:54:37 -04002370 bm.compress(Bitmap.CompressFormat.PNG, 100, os);
2371 values = new ContentValues();
2372 values.put(Browser.BookmarkColumns.THUMBNAIL,
2373 os.toByteArray());
2374 }
2375 cr.update(ContentUris.withAppendedId(Browser.BOOKMARKS_URI,
2376 c.getInt(0)), values, null, null);
2377 succeed = c.moveToNext();
2378 }
2379 c.close();
2380 }
2381 }
2382
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002383 /**
Leon Scrogginsf8551612009-09-24 16:06:02 -04002384 * Values for the size of the thumbnail created when taking a screenshot.
2385 * Lazily initialized. Instead of using these directly, use
2386 * getDesiredThumbnailWidth() or getDesiredThumbnailHeight().
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002387 */
Leon Scrogginsf8551612009-09-24 16:06:02 -04002388 private static int THUMBNAIL_WIDTH = 0;
2389 private static int THUMBNAIL_HEIGHT = 0;
2390
2391 /**
2392 * Return the desired width for thumbnail screenshots, which are stored in
2393 * the database, and used on the bookmarks screen.
2394 * @param context Context for finding out the density of the screen.
2395 * @return int desired width for thumbnail screenshot.
2396 */
2397 /* package */ static int getDesiredThumbnailWidth(Context context) {
2398 if (THUMBNAIL_WIDTH == 0) {
2399 float density = context.getResources().getDisplayMetrics().density;
2400 THUMBNAIL_WIDTH = (int) (90 * density);
2401 THUMBNAIL_HEIGHT = (int) (80 * density);
2402 }
2403 return THUMBNAIL_WIDTH;
2404 }
2405
2406 /**
2407 * Return the desired height for thumbnail screenshots, which are stored in
2408 * the database, and used on the bookmarks screen.
2409 * @param context Context for finding out the density of the screen.
2410 * @return int desired height for thumbnail screenshot.
2411 */
2412 /* package */ static int getDesiredThumbnailHeight(Context context) {
2413 // To ensure that they are both initialized.
2414 getDesiredThumbnailWidth(context);
2415 return THUMBNAIL_HEIGHT;
2416 }
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002417
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002418 private Bitmap createScreenshot(WebView view) {
2419 Picture thumbnail = view.capturePicture();
Leon Scroggins45800572009-09-29 16:38:47 -04002420 if (thumbnail == null) {
2421 return null;
2422 }
Leon Scrogginsf8551612009-09-24 16:06:02 -04002423 Bitmap bm = Bitmap.createBitmap(getDesiredThumbnailWidth(this),
2424 getDesiredThumbnailHeight(this), Bitmap.Config.ARGB_4444);
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002425 Canvas canvas = new Canvas(bm);
2426 // May need to tweak these values to determine what is the
2427 // best scale factor
Ben Murdoch2694e232009-09-29 09:41:11 +01002428 int thumbnailWidth = thumbnail.getWidth();
Ben Murdochae59c3f2009-10-20 18:30:28 +01002429 int thumbnailHeight = thumbnail.getHeight();
2430 float scaleFactorX = 1.0f;
2431 float scaleFactorY = 1.0f;
Ben Murdoch2694e232009-09-29 09:41:11 +01002432 if (thumbnailWidth > 0) {
Ben Murdochae59c3f2009-10-20 18:30:28 +01002433 scaleFactorX = (float) getDesiredThumbnailWidth(this) /
Ben Murdoch2694e232009-09-29 09:41:11 +01002434 (float)thumbnailWidth;
Ben Murdochae59c3f2009-10-20 18:30:28 +01002435 } else {
2436 return null;
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002437 }
Ben Murdochae59c3f2009-10-20 18:30:28 +01002438
2439 if (view.getWidth() > view.getHeight() &&
2440 thumbnailHeight < view.getHeight() && thumbnailHeight > 0) {
2441 // If the device is in landscape and the page is shorter
2442 // than the height of the view, stretch the thumbnail to fill the
2443 // space.
2444 scaleFactorY = (float) getDesiredThumbnailHeight(this) /
2445 (float)thumbnailHeight;
2446 } else {
2447 // In the portrait case, this looks nice.
2448 scaleFactorY = scaleFactorX;
2449 }
2450
2451 canvas.scale(scaleFactorX, scaleFactorY);
2452
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002453 thumbnail.draw(canvas);
2454 return bm;
2455 }
2456
The Android Open Source Project0c908882009-03-03 19:32:16 -08002457 // -------------------------------------------------------------------------
Grace Kloba22ac16e2009-10-07 18:00:23 -07002458 // Helper function for WebViewClient.
The Android Open Source Project0c908882009-03-03 19:32:16 -08002459 //-------------------------------------------------------------------------
2460
2461 // Use in overrideUrlLoading
2462 /* package */ final static String SCHEME_WTAI = "wtai://wp/";
2463 /* package */ final static String SCHEME_WTAI_MC = "wtai://wp/mc;";
2464 /* package */ final static String SCHEME_WTAI_SD = "wtai://wp/sd;";
2465 /* package */ final static String SCHEME_WTAI_AP = "wtai://wp/ap;";
2466
Leon Scroggins92472e82010-02-17 16:32:28 -05002467 // Keep this initial progress in sync with initialProgressValue (* 100)
2468 // in ProgressTracker.cpp
2469 private final static int INITIAL_PROGRESS = 10;
2470
Grace Kloba22ac16e2009-10-07 18:00:23 -07002471 void onPageStarted(WebView view, String url, Bitmap favicon) {
2472 // when BrowserActivity just starts, onPageStarted may be called before
2473 // onResume as it is triggered from onCreate. Call resumeWebViewTimers
2474 // to start the timer. As we won't switch tabs while an activity is in
2475 // pause state, we can ensure calling resume and pause in pair.
2476 if (mActivityInPause) resumeWebViewTimers();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002477
Grace Kloba22ac16e2009-10-07 18:00:23 -07002478 resetLockIcon(url);
2479 setUrlTitle(url, null);
2480 setFavicon(favicon);
Leon Scroggins8cf8f682009-11-04 11:13:50 -08002481 // Show some progress so that the user knows the page is beginning to
2482 // load
Leon Scroggins92472e82010-02-17 16:32:28 -05002483 onProgressChanged(view, INITIAL_PROGRESS);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002484 mDidStopLoad = false;
Grace Kloba22ac16e2009-10-07 18:00:23 -07002485 if (!mIsNetworkUp) createAndShowNetworkDialog();
Patrick Scott15525d42009-09-21 13:39:37 -04002486
Grace Kloba22ac16e2009-10-07 18:00:23 -07002487 if (mSettings.isTracing()) {
2488 String host;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002489 try {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002490 WebAddress uri = new WebAddress(url);
2491 host = uri.mHost;
2492 } catch (android.net.ParseException ex) {
2493 host = "browser";
The Android Open Source Project0c908882009-03-03 19:32:16 -08002494 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002495 host = host.replace('.', '_');
2496 host += ".trace";
2497 mInTrace = true;
2498 Debug.startMethodTracing(host, 20 * 1024 * 1024);
2499 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002500
Grace Kloba22ac16e2009-10-07 18:00:23 -07002501 // Performance probe
2502 if (false) {
2503 mStart = SystemClock.uptimeMillis();
2504 mProcessStart = Process.getElapsedCpuTime();
2505 long[] sysCpu = new long[7];
2506 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2507 sysCpu, null)) {
2508 mUserStart = sysCpu[0] + sysCpu[1];
2509 mSystemStart = sysCpu[2];
2510 mIdleStart = sysCpu[3];
2511 mIrqStart = sysCpu[4] + sysCpu[5] + sysCpu[6];
2512 }
2513 mUiStart = SystemClock.currentThreadTimeMillis();
2514 }
2515 }
2516
2517 void onPageFinished(WebView view, String url) {
2518 // Reset the title and icon in case we stopped a provisional load.
2519 resetTitleAndIcon(view);
2520 // Update the lock icon image only once we are done loading
2521 updateLockIconToLatest();
2522 // pause the WebView timer and release the wake lock if it is finished
2523 // while BrowserActivity is in pause state.
2524 if (mActivityInPause && pauseWebViewTimers()) {
2525 if (mWakeLock.isHeld()) {
2526 mHandler.removeMessages(RELEASE_WAKELOCK);
2527 mWakeLock.release();
2528 }
2529 }
2530
2531 // Performance probe
2532 if (false) {
2533 long[] sysCpu = new long[7];
2534 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2535 sysCpu, null)) {
2536 String uiInfo = "UI thread used "
2537 + (SystemClock.currentThreadTimeMillis() - mUiStart)
2538 + " ms";
2539 if (LOGD_ENABLED) {
2540 Log.d(LOGTAG, uiInfo);
2541 }
2542 //The string that gets written to the log
2543 String performanceString = "It took total "
2544 + (SystemClock.uptimeMillis() - mStart)
2545 + " ms clock time to load the page."
2546 + "\nbrowser process used "
2547 + (Process.getElapsedCpuTime() - mProcessStart)
2548 + " ms, user processes used "
2549 + (sysCpu[0] + sysCpu[1] - mUserStart) * 10
2550 + " ms, kernel used "
2551 + (sysCpu[2] - mSystemStart) * 10
2552 + " ms, idle took " + (sysCpu[3] - mIdleStart) * 10
2553 + " ms and irq took "
2554 + (sysCpu[4] + sysCpu[5] + sysCpu[6] - mIrqStart)
2555 * 10 + " ms, " + uiInfo;
2556 if (LOGD_ENABLED) {
2557 Log.d(LOGTAG, performanceString + "\nWebpage: " + url);
2558 }
2559 if (url != null) {
2560 // strip the url to maintain consistency
2561 String newUrl = new String(url);
2562 if (newUrl.startsWith("http://www.")) {
2563 newUrl = newUrl.substring(11);
2564 } else if (newUrl.startsWith("http://")) {
2565 newUrl = newUrl.substring(7);
2566 } else if (newUrl.startsWith("https://www.")) {
2567 newUrl = newUrl.substring(12);
2568 } else if (newUrl.startsWith("https://")) {
2569 newUrl = newUrl.substring(8);
2570 }
2571 if (LOGD_ENABLED) {
2572 Log.d(LOGTAG, newUrl + " loaded");
2573 }
Grace Kloba5b078b52009-06-24 20:23:41 -07002574 }
2575 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002576 }
Grace Kloba5b078b52009-06-24 20:23:41 -07002577
Grace Kloba22ac16e2009-10-07 18:00:23 -07002578 if (mInTrace) {
2579 mInTrace = false;
2580 Debug.stopMethodTracing();
2581 }
2582 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002583
Grace Kloba22ac16e2009-10-07 18:00:23 -07002584 boolean shouldOverrideUrlLoading(WebView view, String url) {
2585 if (url.startsWith(SCHEME_WTAI)) {
2586 // wtai://wp/mc;number
2587 // number=string(phone-number)
2588 if (url.startsWith(SCHEME_WTAI_MC)) {
2589 Intent intent = new Intent(Intent.ACTION_VIEW,
2590 Uri.parse(WebView.SCHEME_TEL +
2591 url.substring(SCHEME_WTAI_MC.length())));
2592 startActivity(intent);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002593 return true;
2594 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002595 // wtai://wp/sd;dtmf
2596 // dtmf=string(dialstring)
2597 if (url.startsWith(SCHEME_WTAI_SD)) {
2598 // TODO: only send when there is active voice connection
2599 return false;
2600 }
2601 // wtai://wp/ap;number;name
2602 // number=string(phone-number)
2603 // name=string
2604 if (url.startsWith(SCHEME_WTAI_AP)) {
2605 // TODO
2606 return false;
2607 }
2608 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002609
Grace Kloba22ac16e2009-10-07 18:00:23 -07002610 // The "about:" schemes are internal to the browser; don't want these to
2611 // be dispatched to other apps.
2612 if (url.startsWith("about:")) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002613 return false;
2614 }
2615
Grace Kloba22ac16e2009-10-07 18:00:23 -07002616 Intent intent;
2617 // perform generic parsing of the URI to turn it into an Intent.
2618 try {
2619 intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME);
2620 } catch (URISyntaxException ex) {
2621 Log.w("Browser", "Bad URI " + url + ": " + ex.getMessage());
2622 return false;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002623 }
2624
Grace Kloba22ac16e2009-10-07 18:00:23 -07002625 // check whether the intent can be resolved. If not, we will see
2626 // whether we can download it from the Market.
2627 if (getPackageManager().resolveActivity(intent, 0) == null) {
2628 String packagename = intent.getPackage();
2629 if (packagename != null) {
2630 intent = new Intent(Intent.ACTION_VIEW, Uri
2631 .parse("market://search?q=pname:" + packagename));
2632 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2633 startActivity(intent);
2634 return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002635 } else {
2636 return false;
2637 }
2638 }
2639
Grace Kloba22ac16e2009-10-07 18:00:23 -07002640 // sanitize the Intent, ensuring web pages can not bypass browser
2641 // security (only access to BROWSABLE activities).
2642 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2643 intent.setComponent(null);
2644 try {
2645 if (startActivityIfNeeded(intent, -1)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002646 return true;
2647 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002648 } catch (ActivityNotFoundException ex) {
2649 // ignore the error. If no application can handle the URL,
2650 // eg about:blank, assume the browser can handle it.
2651 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002652
Grace Kloba22ac16e2009-10-07 18:00:23 -07002653 if (mMenuIsDown) {
2654 openTab(url);
2655 closeOptionsMenu();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002656 return true;
2657 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002658 return false;
2659 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002660
Grace Kloba22ac16e2009-10-07 18:00:23 -07002661 // -------------------------------------------------------------------------
2662 // Helper function for WebChromeClient
2663 // -------------------------------------------------------------------------
The Android Open Source Project0c908882009-03-03 19:32:16 -08002664
Grace Kloba22ac16e2009-10-07 18:00:23 -07002665 void onProgressChanged(WebView view, int newProgress) {
2666 mTitleBar.setProgress(newProgress);
2667 mFakeTitleBar.setProgress(newProgress);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002668
Grace Kloba22ac16e2009-10-07 18:00:23 -07002669 if (newProgress == 100) {
2670 // onProgressChanged() may continue to be called after the main
2671 // frame has finished loading, as any remaining sub frames continue
2672 // to load. We'll only get called once though with newProgress as
2673 // 100 when everything is loaded. (onPageFinished is called once
2674 // when the main frame completes loading regardless of the state of
2675 // any sub frames so calls to onProgressChanges may continue after
2676 // onPageFinished has executed)
2677 if (mInLoad) {
2678 mInLoad = false;
Leon Scrogginsa27ff192009-09-14 12:58:04 -04002679 updateInLoadMenuItems();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002680 // If the options menu is open, leave the title bar
2681 if (!mOptionsMenuOpen || !mIconView) {
2682 hideFakeTitleBar();
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07002683 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002684 }
Leon Scrogginsaa37e7f2010-03-05 11:51:20 -05002685 } else {
2686 if (!mInLoad) {
2687 // onPageFinished may have already been called but a subframe is
2688 // still loading and updating the progress. Reset mInLoad and
2689 // update the menu items.
2690 mInLoad = true;
2691 updateInLoadMenuItems();
2692 }
2693 // When the page first begins to load, the Activity may still be
2694 // paused, in which case showFakeTitleBar will do nothing. Call
2695 // again as the page continues to load so that it will be shown.
2696 // (Calling it will the fake title bar is already showing will also
2697 // do nothing.
Grace Kloba22ac16e2009-10-07 18:00:23 -07002698 if (!mOptionsMenuOpen || mIconView) {
2699 // This page has begun to load, so show the title bar
2700 showFakeTitleBar();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002701 }
2702 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002703 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002704
Grace Kloba22ac16e2009-10-07 18:00:23 -07002705 void onShowCustomView(View view, WebChromeClient.CustomViewCallback callback) {
Derek Sollenberger8ff57db2009-12-08 15:39:55 -05002706 // if a view already exists then immediately terminate the new one
2707 if (mCustomView != null) {
2708 callback.onCustomViewHidden();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002709 return;
Derek Sollenberger8ff57db2009-12-08 15:39:55 -05002710 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002711
2712 // Add the custom view to its container.
2713 mCustomViewContainer.addView(view, COVER_SCREEN_GRAVITY_CENTER);
2714 mCustomView = view;
2715 mCustomViewCallback = callback;
2716 // Save the menu state and set it to empty while the custom
2717 // view is showing.
2718 mOldMenuState = mMenuState;
2719 mMenuState = EMPTY_MENU;
2720 // Hide the content view.
2721 mContentView.setVisibility(View.GONE);
2722 // Finally show the custom view container.
Andrei Popescu163ab742009-10-20 17:58:23 +01002723 setStatusBarVisibility(false);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002724 mCustomViewContainer.setVisibility(View.VISIBLE);
2725 mCustomViewContainer.bringToFront();
2726 }
2727
2728 void onHideCustomView() {
2729 if (mCustomView == null)
2730 return;
2731
2732 // Hide the custom view.
2733 mCustomView.setVisibility(View.GONE);
2734 // Remove the custom view from its container.
2735 mCustomViewContainer.removeView(mCustomView);
2736 mCustomView = null;
2737 // Reset the old menu state.
2738 mMenuState = mOldMenuState;
2739 mOldMenuState = EMPTY_MENU;
2740 mCustomViewContainer.setVisibility(View.GONE);
2741 mCustomViewCallback.onCustomViewHidden();
2742 // Show the content view.
Andrei Popescu163ab742009-10-20 17:58:23 +01002743 setStatusBarVisibility(true);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002744 mContentView.setVisibility(View.VISIBLE);
2745 }
2746
2747 Bitmap getDefaultVideoPoster() {
2748 if (mDefaultVideoPoster == null) {
2749 mDefaultVideoPoster = BitmapFactory.decodeResource(
2750 getResources(), R.drawable.default_video_poster);
Patrick Scott3918d442009-08-04 13:22:29 -04002751 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002752 return mDefaultVideoPoster;
2753 }
Patrick Scott3918d442009-08-04 13:22:29 -04002754
Grace Kloba22ac16e2009-10-07 18:00:23 -07002755 View getVideoLoadingProgressView() {
2756 if (mVideoProgressView == null) {
2757 LayoutInflater inflater = LayoutInflater.from(BrowserActivity.this);
2758 mVideoProgressView = inflater.inflate(
2759 R.layout.video_loading_progress, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002760 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002761 return mVideoProgressView;
2762 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002763
Leon Scroggins8d5fa432009-10-02 15:55:59 -04002764 /*
2765 * The Object used to inform the WebView of the file to upload.
2766 */
2767 private ValueCallback<Uri> mUploadMessage;
2768
Grace Kloba22ac16e2009-10-07 18:00:23 -07002769 void openFileChooser(ValueCallback<Uri> uploadMsg) {
2770 if (mUploadMessage != null) return;
2771 mUploadMessage = uploadMsg;
2772 Intent i = new Intent(Intent.ACTION_GET_CONTENT);
2773 i.addCategory(Intent.CATEGORY_OPENABLE);
2774 i.setType("*/*");
2775 BrowserActivity.this.startActivityForResult(Intent.createChooser(i,
2776 getString(R.string.choose_upload)), FILE_SELECTED);
2777 }
2778
2779 // -------------------------------------------------------------------------
2780 // Implement functions for DownloadListener
2781 // -------------------------------------------------------------------------
2782
The Android Open Source Project0c908882009-03-03 19:32:16 -08002783 /**
2784 * Notify the host application a download should be done, or that
2785 * the data should be streamed if a streaming viewer is available.
2786 * @param url The full url to the content that should be downloaded
2787 * @param contentDisposition Content-disposition http header, if
2788 * present.
2789 * @param mimetype The mimetype of the content reported by the server
2790 * @param contentLength The file size reported by the server
2791 */
2792 public void onDownloadStart(String url, String userAgent,
2793 String contentDisposition, String mimetype, long contentLength) {
2794 // if we're dealing wih A/V content that's not explicitly marked
2795 // for download, check if it's streamable.
2796 if (contentDisposition == null
Patrick Scotte1fb9662009-08-31 14:31:52 -04002797 || !contentDisposition.regionMatches(
2798 true, 0, "attachment", 0, 10)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002799 // query the package manager to see if there's a registered handler
2800 // that matches.
2801 Intent intent = new Intent(Intent.ACTION_VIEW);
2802 intent.setDataAndType(Uri.parse(url), mimetype);
Patrick Scotte1fb9662009-08-31 14:31:52 -04002803 ResolveInfo info = getPackageManager().resolveActivity(intent,
2804 PackageManager.MATCH_DEFAULT_ONLY);
2805 if (info != null) {
2806 ComponentName myName = getComponentName();
2807 // If we resolved to ourselves, we don't want to attempt to
2808 // load the url only to try and download it again.
2809 if (!myName.getPackageName().equals(
2810 info.activityInfo.packageName)
2811 || !myName.getClassName().equals(
2812 info.activityInfo.name)) {
2813 // someone (other than us) knows how to handle this mime
2814 // type with this scheme, don't download.
2815 try {
2816 startActivity(intent);
2817 return;
2818 } catch (ActivityNotFoundException ex) {
2819 if (LOGD_ENABLED) {
2820 Log.d(LOGTAG, "activity not found for " + mimetype
2821 + " over " + Uri.parse(url).getScheme(),
2822 ex);
2823 }
2824 // Best behavior is to fall back to a download in this
2825 // case
The Android Open Source Project0c908882009-03-03 19:32:16 -08002826 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002827 }
2828 }
2829 }
2830 onDownloadStartNoStream(url, userAgent, contentDisposition, mimetype, contentLength);
2831 }
2832
2833 /**
2834 * Notify the host application a download should be done, even if there
2835 * is a streaming viewer available for thise type.
2836 * @param url The full url to the content that should be downloaded
2837 * @param contentDisposition Content-disposition http header, if
2838 * present.
2839 * @param mimetype The mimetype of the content reported by the server
2840 * @param contentLength The file size reported by the server
2841 */
2842 /*package */ void onDownloadStartNoStream(String url, String userAgent,
2843 String contentDisposition, String mimetype, long contentLength) {
2844
2845 String filename = URLUtil.guessFileName(url,
2846 contentDisposition, mimetype);
2847
2848 // Check to see if we have an SDCard
2849 String status = Environment.getExternalStorageState();
2850 if (!status.equals(Environment.MEDIA_MOUNTED)) {
2851 int title;
2852 String msg;
2853
2854 // Check to see if the SDCard is busy, same as the music app
2855 if (status.equals(Environment.MEDIA_SHARED)) {
2856 msg = getString(R.string.download_sdcard_busy_dlg_msg);
2857 title = R.string.download_sdcard_busy_dlg_title;
2858 } else {
2859 msg = getString(R.string.download_no_sdcard_dlg_msg, filename);
2860 title = R.string.download_no_sdcard_dlg_title;
2861 }
2862
2863 new AlertDialog.Builder(this)
2864 .setTitle(title)
2865 .setIcon(android.R.drawable.ic_dialog_alert)
2866 .setMessage(msg)
2867 .setPositiveButton(R.string.ok, null)
2868 .show();
2869 return;
2870 }
2871
2872 // java.net.URI is a lot stricter than KURL so we have to undo
2873 // KURL's percent-encoding and redo the encoding using java.net.URI.
2874 URI uri = null;
2875 try {
2876 // Undo the percent-encoding that KURL may have done.
2877 String newUrl = new String(URLUtil.decode(url.getBytes()));
2878 // Parse the url into pieces
2879 WebAddress w = new WebAddress(newUrl);
2880 String frag = null;
2881 String query = null;
2882 String path = w.mPath;
2883 // Break the path into path, query, and fragment
2884 if (path.length() > 0) {
2885 // Strip the fragment
2886 int idx = path.lastIndexOf('#');
2887 if (idx != -1) {
2888 frag = path.substring(idx + 1);
2889 path = path.substring(0, idx);
2890 }
2891 idx = path.lastIndexOf('?');
2892 if (idx != -1) {
2893 query = path.substring(idx + 1);
2894 path = path.substring(0, idx);
2895 }
2896 }
2897 uri = new URI(w.mScheme, w.mAuthInfo, w.mHost, w.mPort, path,
2898 query, frag);
2899 } catch (Exception e) {
2900 Log.e(LOGTAG, "Could not parse url for download: " + url, e);
2901 return;
2902 }
2903
2904 // XXX: Have to use the old url since the cookies were stored using the
2905 // old percent-encoded url.
2906 String cookies = CookieManager.getInstance().getCookie(url);
2907
2908 ContentValues values = new ContentValues();
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08002909 values.put(Downloads.Impl.COLUMN_URI, uri.toString());
2910 values.put(Downloads.Impl.COLUMN_COOKIE_DATA, cookies);
2911 values.put(Downloads.Impl.COLUMN_USER_AGENT, userAgent);
2912 values.put(Downloads.Impl.COLUMN_NOTIFICATION_PACKAGE,
The Android Open Source Project0c908882009-03-03 19:32:16 -08002913 getPackageName());
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08002914 values.put(Downloads.Impl.COLUMN_NOTIFICATION_CLASS,
The Android Open Source Project0c908882009-03-03 19:32:16 -08002915 BrowserDownloadPage.class.getCanonicalName());
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08002916 values.put(Downloads.Impl.COLUMN_VISIBILITY,
2917 Downloads.Impl.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
2918 values.put(Downloads.Impl.COLUMN_MIME_TYPE, mimetype);
2919 values.put(Downloads.Impl.COLUMN_FILE_NAME_HINT, filename);
2920 values.put(Downloads.Impl.COLUMN_DESCRIPTION, uri.getHost());
The Android Open Source Project0c908882009-03-03 19:32:16 -08002921 if (contentLength > 0) {
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08002922 values.put(Downloads.Impl.COLUMN_TOTAL_BYTES, contentLength);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002923 }
2924 if (mimetype == null) {
2925 // We must have long pressed on a link or image to download it. We
2926 // are not sure of the mimetype in this case, so do a head request
2927 new FetchUrlMimeType(this).execute(values);
2928 } else {
2929 final Uri contentUri =
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08002930 getContentResolver().insert(Downloads.Impl.CONTENT_URI, values);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002931 }
2932
2933 }
2934
Grace Kloba22ac16e2009-10-07 18:00:23 -07002935 // -------------------------------------------------------------------------
2936
The Android Open Source Project0c908882009-03-03 19:32:16 -08002937 /**
2938 * Resets the lock icon. This method is called when we start a new load and
2939 * know the url to be loaded.
2940 */
2941 private void resetLockIcon(String url) {
2942 // Save the lock-icon state (we revert to it if the load gets cancelled)
Grace Kloba22ac16e2009-10-07 18:00:23 -07002943 mTabControl.getCurrentTab().resetLockIcon(url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002944 updateLockIconImage(LOCK_ICON_UNSECURE);
2945 }
2946
The Android Open Source Project0c908882009-03-03 19:32:16 -08002947 /**
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04002948 * Update the lock icon to correspond to our latest state.
2949 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07002950 private void updateLockIconToLatest() {
2951 updateLockIconImage(mTabControl.getCurrentTab().getLockIconType());
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04002952 }
2953
2954 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08002955 * Updates the lock-icon image in the title-bar.
2956 */
2957 private void updateLockIconImage(int lockIconType) {
2958 Drawable d = null;
2959 if (lockIconType == LOCK_ICON_SECURE) {
2960 d = mSecLockIcon;
2961 } else if (lockIconType == LOCK_ICON_MIXED) {
2962 d = mMixLockIcon;
2963 }
Leon Scroggins68579392009-09-15 15:31:54 -04002964 mTitleBar.setLock(d);
Leon Scrogginsfe87bd32009-10-06 10:10:00 -04002965 mFakeTitleBar.setLock(d);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002966 }
2967
2968 /**
2969 * Displays a page-info dialog.
2970 * @param tab The tab to show info about
2971 * @param fromShowSSLCertificateOnError The flag that indicates whether
2972 * this dialog was opened from the SSL-certificate-on-error dialog or
2973 * not. This is important, since we need to know whether to return to
2974 * the parent dialog or simply dismiss.
2975 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07002976 private void showPageInfo(final Tab tab,
The Android Open Source Project0c908882009-03-03 19:32:16 -08002977 final boolean fromShowSSLCertificateOnError) {
2978 final LayoutInflater factory = LayoutInflater
2979 .from(this);
2980
2981 final View pageInfoView = factory.inflate(R.layout.page_info, null);
2982
2983 final WebView view = tab.getWebView();
2984
2985 String url = null;
2986 String title = null;
2987
2988 if (view == null) {
2989 url = tab.getUrl();
2990 title = tab.getTitle();
2991 } else if (view == mTabControl.getCurrentWebView()) {
2992 // Use the cached title and url if this is the current WebView
2993 url = mUrl;
2994 title = mTitle;
2995 } else {
2996 url = view.getUrl();
2997 title = view.getTitle();
2998 }
2999
3000 if (url == null) {
3001 url = "";
3002 }
3003 if (title == null) {
3004 title = "";
3005 }
3006
3007 ((TextView) pageInfoView.findViewById(R.id.address)).setText(url);
3008 ((TextView) pageInfoView.findViewById(R.id.title)).setText(title);
3009
3010 mPageInfoView = tab;
Leon Scrogginsc7b92f82010-01-11 18:17:31 -05003011 mPageInfoFromShowSSLCertificateOnError = fromShowSSLCertificateOnError;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003012
3013 AlertDialog.Builder alertDialogBuilder =
3014 new AlertDialog.Builder(this)
3015 .setTitle(R.string.page_info).setIcon(android.R.drawable.ic_dialog_info)
3016 .setView(pageInfoView)
3017 .setPositiveButton(
3018 R.string.ok,
3019 new DialogInterface.OnClickListener() {
3020 public void onClick(DialogInterface dialog,
3021 int whichButton) {
3022 mPageInfoDialog = null;
3023 mPageInfoView = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003024
3025 // if we came here from the SSL error dialog
3026 if (fromShowSSLCertificateOnError) {
3027 // go back to the SSL error dialog
3028 showSSLCertificateOnError(
3029 mSSLCertificateOnErrorView,
3030 mSSLCertificateOnErrorHandler,
3031 mSSLCertificateOnErrorError);
3032 }
3033 }
3034 })
3035 .setOnCancelListener(
3036 new DialogInterface.OnCancelListener() {
3037 public void onCancel(DialogInterface dialog) {
3038 mPageInfoDialog = null;
3039 mPageInfoView = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003040
3041 // if we came here from the SSL error dialog
3042 if (fromShowSSLCertificateOnError) {
3043 // go back to the SSL error dialog
3044 showSSLCertificateOnError(
3045 mSSLCertificateOnErrorView,
3046 mSSLCertificateOnErrorHandler,
3047 mSSLCertificateOnErrorError);
3048 }
3049 }
3050 });
3051
3052 // if we have a main top-level page SSL certificate set or a certificate
3053 // error
3054 if (fromShowSSLCertificateOnError ||
3055 (view != null && view.getCertificate() != null)) {
3056 // add a 'View Certificate' button
3057 alertDialogBuilder.setNeutralButton(
3058 R.string.view_certificate,
3059 new DialogInterface.OnClickListener() {
3060 public void onClick(DialogInterface dialog,
3061 int whichButton) {
3062 mPageInfoDialog = null;
3063 mPageInfoView = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003064
3065 // if we came here from the SSL error dialog
3066 if (fromShowSSLCertificateOnError) {
3067 // go back to the SSL error dialog
3068 showSSLCertificateOnError(
3069 mSSLCertificateOnErrorView,
3070 mSSLCertificateOnErrorHandler,
3071 mSSLCertificateOnErrorError);
3072 } else {
3073 // otherwise, display the top-most certificate from
3074 // the chain
3075 if (view.getCertificate() != null) {
3076 showSSLCertificate(tab);
3077 }
3078 }
3079 }
3080 });
3081 }
3082
3083 mPageInfoDialog = alertDialogBuilder.show();
3084 }
3085
3086 /**
3087 * Displays the main top-level page SSL certificate dialog
3088 * (accessible from the Page-Info dialog).
3089 * @param tab The tab to show certificate for.
3090 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003091 private void showSSLCertificate(final Tab tab) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003092 final View certificateView =
3093 inflateCertificateView(tab.getWebView().getCertificate());
3094 if (certificateView == null) {
3095 return;
3096 }
3097
3098 LayoutInflater factory = LayoutInflater.from(this);
3099
3100 final LinearLayout placeholder =
3101 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3102
3103 LinearLayout ll = (LinearLayout) factory.inflate(
3104 R.layout.ssl_success, placeholder);
3105 ((TextView)ll.findViewById(R.id.success))
3106 .setText(R.string.ssl_certificate_is_valid);
3107
3108 mSSLCertificateView = tab;
3109 mSSLCertificateDialog =
3110 new AlertDialog.Builder(this)
3111 .setTitle(R.string.ssl_certificate).setIcon(
3112 R.drawable.ic_dialog_browser_certificate_secure)
3113 .setView(certificateView)
3114 .setPositiveButton(R.string.ok,
3115 new DialogInterface.OnClickListener() {
3116 public void onClick(DialogInterface dialog,
3117 int whichButton) {
3118 mSSLCertificateDialog = null;
3119 mSSLCertificateView = null;
3120
3121 showPageInfo(tab, false);
3122 }
3123 })
3124 .setOnCancelListener(
3125 new DialogInterface.OnCancelListener() {
3126 public void onCancel(DialogInterface dialog) {
3127 mSSLCertificateDialog = null;
3128 mSSLCertificateView = null;
3129
3130 showPageInfo(tab, false);
3131 }
3132 })
3133 .show();
3134 }
3135
3136 /**
3137 * Displays the SSL error certificate dialog.
3138 * @param view The target web-view.
3139 * @param handler The SSL error handler responsible for cancelling the
3140 * connection that resulted in an SSL error or proceeding per user request.
3141 * @param error The SSL error object.
3142 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003143 void showSSLCertificateOnError(
The Android Open Source Project0c908882009-03-03 19:32:16 -08003144 final WebView view, final SslErrorHandler handler, final SslError error) {
3145
3146 final View certificateView =
3147 inflateCertificateView(error.getCertificate());
3148 if (certificateView == null) {
3149 return;
3150 }
3151
3152 LayoutInflater factory = LayoutInflater.from(this);
3153
3154 final LinearLayout placeholder =
3155 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3156
3157 if (error.hasError(SslError.SSL_UNTRUSTED)) {
3158 LinearLayout ll = (LinearLayout)factory
3159 .inflate(R.layout.ssl_warning, placeholder);
3160 ((TextView)ll.findViewById(R.id.warning))
3161 .setText(R.string.ssl_untrusted);
3162 }
3163
3164 if (error.hasError(SslError.SSL_IDMISMATCH)) {
3165 LinearLayout ll = (LinearLayout)factory
3166 .inflate(R.layout.ssl_warning, placeholder);
3167 ((TextView)ll.findViewById(R.id.warning))
3168 .setText(R.string.ssl_mismatch);
3169 }
3170
3171 if (error.hasError(SslError.SSL_EXPIRED)) {
3172 LinearLayout ll = (LinearLayout)factory
3173 .inflate(R.layout.ssl_warning, placeholder);
3174 ((TextView)ll.findViewById(R.id.warning))
3175 .setText(R.string.ssl_expired);
3176 }
3177
3178 if (error.hasError(SslError.SSL_NOTYETVALID)) {
3179 LinearLayout ll = (LinearLayout)factory
3180 .inflate(R.layout.ssl_warning, placeholder);
3181 ((TextView)ll.findViewById(R.id.warning))
3182 .setText(R.string.ssl_not_yet_valid);
3183 }
3184
3185 mSSLCertificateOnErrorHandler = handler;
3186 mSSLCertificateOnErrorView = view;
3187 mSSLCertificateOnErrorError = error;
3188 mSSLCertificateOnErrorDialog =
3189 new AlertDialog.Builder(this)
3190 .setTitle(R.string.ssl_certificate).setIcon(
3191 R.drawable.ic_dialog_browser_certificate_partially_secure)
3192 .setView(certificateView)
3193 .setPositiveButton(R.string.ok,
3194 new DialogInterface.OnClickListener() {
3195 public void onClick(DialogInterface dialog,
3196 int whichButton) {
3197 mSSLCertificateOnErrorDialog = null;
3198 mSSLCertificateOnErrorView = null;
3199 mSSLCertificateOnErrorHandler = null;
3200 mSSLCertificateOnErrorError = null;
3201
Grace Kloba22ac16e2009-10-07 18:00:23 -07003202 view.getWebViewClient().onReceivedSslError(
3203 view, handler, error);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003204 }
3205 })
3206 .setNeutralButton(R.string.page_info_view,
3207 new DialogInterface.OnClickListener() {
3208 public void onClick(DialogInterface dialog,
3209 int whichButton) {
3210 mSSLCertificateOnErrorDialog = null;
3211
3212 // do not clear the dialog state: we will
3213 // need to show the dialog again once the
3214 // user is done exploring the page-info details
3215
3216 showPageInfo(mTabControl.getTabFromView(view),
3217 true);
3218 }
3219 })
3220 .setOnCancelListener(
3221 new DialogInterface.OnCancelListener() {
3222 public void onCancel(DialogInterface dialog) {
3223 mSSLCertificateOnErrorDialog = null;
3224 mSSLCertificateOnErrorView = null;
3225 mSSLCertificateOnErrorHandler = null;
3226 mSSLCertificateOnErrorError = null;
3227
Grace Kloba22ac16e2009-10-07 18:00:23 -07003228 view.getWebViewClient().onReceivedSslError(
3229 view, handler, error);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003230 }
3231 })
3232 .show();
3233 }
3234
3235 /**
3236 * Inflates the SSL certificate view (helper method).
3237 * @param certificate The SSL certificate.
3238 * @return The resultant certificate view with issued-to, issued-by,
3239 * issued-on, expires-on, and possibly other fields set.
3240 * If the input certificate is null, returns null.
3241 */
3242 private View inflateCertificateView(SslCertificate certificate) {
3243 if (certificate == null) {
3244 return null;
3245 }
3246
3247 LayoutInflater factory = LayoutInflater.from(this);
3248
3249 View certificateView = factory.inflate(
3250 R.layout.ssl_certificate, null);
3251
3252 // issued to:
3253 SslCertificate.DName issuedTo = certificate.getIssuedTo();
3254 if (issuedTo != null) {
3255 ((TextView) certificateView.findViewById(R.id.to_common))
3256 .setText(issuedTo.getCName());
3257 ((TextView) certificateView.findViewById(R.id.to_org))
3258 .setText(issuedTo.getOName());
3259 ((TextView) certificateView.findViewById(R.id.to_org_unit))
3260 .setText(issuedTo.getUName());
3261 }
3262
3263 // issued by:
3264 SslCertificate.DName issuedBy = certificate.getIssuedBy();
3265 if (issuedBy != null) {
3266 ((TextView) certificateView.findViewById(R.id.by_common))
3267 .setText(issuedBy.getCName());
3268 ((TextView) certificateView.findViewById(R.id.by_org))
3269 .setText(issuedBy.getOName());
3270 ((TextView) certificateView.findViewById(R.id.by_org_unit))
3271 .setText(issuedBy.getUName());
3272 }
3273
3274 // issued on:
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003275 String issuedOn = formatCertificateDate(
3276 certificate.getValidNotBeforeDate());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003277 ((TextView) certificateView.findViewById(R.id.issued_on))
3278 .setText(issuedOn);
3279
3280 // expires on:
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003281 String expiresOn = formatCertificateDate(
3282 certificate.getValidNotAfterDate());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003283 ((TextView) certificateView.findViewById(R.id.expires_on))
3284 .setText(expiresOn);
3285
3286 return certificateView;
3287 }
3288
3289 /**
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003290 * Formats the certificate date to a properly localized date string.
The Android Open Source Project0c908882009-03-03 19:32:16 -08003291 * @return Properly localized version of the certificate date string and
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003292 * the "" if it fails to localize.
The Android Open Source Project0c908882009-03-03 19:32:16 -08003293 */
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003294 private String formatCertificateDate(Date certificateDate) {
3295 if (certificateDate == null) {
3296 return "";
The Android Open Source Project0c908882009-03-03 19:32:16 -08003297 }
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003298 String formattedDate = DateFormat.getDateFormat(this).format(certificateDate);
3299 if (formattedDate == null) {
3300 return "";
3301 }
3302 return formattedDate;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003303 }
3304
3305 /**
3306 * Displays an http-authentication dialog.
3307 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003308 void showHttpAuthentication(final HttpAuthHandler handler,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003309 final String host, final String realm, final String title,
3310 final String name, final String password, int focusId) {
3311 LayoutInflater factory = LayoutInflater.from(this);
3312 final View v = factory
3313 .inflate(R.layout.http_authentication, null);
3314 if (name != null) {
3315 ((EditText) v.findViewById(R.id.username_edit)).setText(name);
3316 }
3317 if (password != null) {
3318 ((EditText) v.findViewById(R.id.password_edit)).setText(password);
3319 }
3320
3321 String titleText = title;
3322 if (titleText == null) {
3323 titleText = getText(R.string.sign_in_to).toString().replace(
3324 "%s1", host).replace("%s2", realm);
3325 }
3326
3327 mHttpAuthHandler = handler;
3328 AlertDialog dialog = new AlertDialog.Builder(this)
3329 .setTitle(titleText)
3330 .setIcon(android.R.drawable.ic_dialog_alert)
3331 .setView(v)
3332 .setPositiveButton(R.string.action,
3333 new DialogInterface.OnClickListener() {
3334 public void onClick(DialogInterface dialog,
3335 int whichButton) {
3336 String nm = ((EditText) v
3337 .findViewById(R.id.username_edit))
3338 .getText().toString();
3339 String pw = ((EditText) v
3340 .findViewById(R.id.password_edit))
3341 .getText().toString();
3342 BrowserActivity.this.setHttpAuthUsernamePassword
3343 (host, realm, nm, pw);
3344 handler.proceed(nm, pw);
3345 mHttpAuthenticationDialog = null;
3346 mHttpAuthHandler = null;
3347 }})
3348 .setNegativeButton(R.string.cancel,
3349 new DialogInterface.OnClickListener() {
3350 public void onClick(DialogInterface dialog,
3351 int whichButton) {
3352 handler.cancel();
3353 BrowserActivity.this.resetTitleAndRevertLockIcon();
3354 mHttpAuthenticationDialog = null;
3355 mHttpAuthHandler = null;
3356 }})
3357 .setOnCancelListener(new DialogInterface.OnCancelListener() {
3358 public void onCancel(DialogInterface dialog) {
3359 handler.cancel();
3360 BrowserActivity.this.resetTitleAndRevertLockIcon();
3361 mHttpAuthenticationDialog = null;
3362 mHttpAuthHandler = null;
3363 }})
3364 .create();
3365 // Make the IME appear when the dialog is displayed if applicable.
3366 dialog.getWindow().setSoftInputMode(
3367 WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
3368 dialog.show();
3369 if (focusId != 0) {
3370 dialog.findViewById(focusId).requestFocus();
3371 } else {
3372 v.findViewById(R.id.username_edit).requestFocus();
3373 }
3374 mHttpAuthenticationDialog = dialog;
3375 }
3376
3377 public int getProgress() {
3378 WebView w = mTabControl.getCurrentWebView();
3379 if (w != null) {
3380 return w.getProgress();
3381 } else {
3382 return 100;
3383 }
3384 }
3385
3386 /**
3387 * Set HTTP authentication password.
3388 *
3389 * @param host The host for the password
3390 * @param realm The realm for the password
3391 * @param username The username for the password. If it is null, it means
3392 * password can't be saved.
3393 * @param password The password
3394 */
3395 public void setHttpAuthUsernamePassword(String host, String realm,
3396 String username,
3397 String password) {
3398 WebView w = mTabControl.getCurrentWebView();
3399 if (w != null) {
3400 w.setHttpAuthUsernamePassword(host, realm, username, password);
3401 }
3402 }
3403
3404 /**
3405 * connectivity manager says net has come or gone... inform the user
3406 * @param up true if net has come up, false if net has gone down
3407 */
3408 public void onNetworkToggle(boolean up) {
3409 if (up == mIsNetworkUp) {
3410 return;
3411 } else if (up) {
3412 mIsNetworkUp = true;
3413 if (mAlertDialog != null) {
3414 mAlertDialog.cancel();
3415 mAlertDialog = null;
3416 }
3417 } else {
3418 mIsNetworkUp = false;
Patrick Scotteb6ab2a2009-09-16 10:00:17 -04003419 if (mInLoad) {
3420 createAndShowNetworkDialog();
3421 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003422 }
3423 WebView w = mTabControl.getCurrentWebView();
3424 if (w != null) {
3425 w.setNetworkAvailable(up);
3426 }
3427 }
3428
Grace Kloba22ac16e2009-10-07 18:00:23 -07003429 boolean isNetworkUp() {
3430 return mIsNetworkUp;
3431 }
3432
Patrick Scotteb6ab2a2009-09-16 10:00:17 -04003433 // This method shows the network dialog alerting the user that the net is
3434 // down. It will only show the dialog if mAlertDialog is null.
3435 private void createAndShowNetworkDialog() {
3436 if (mAlertDialog == null) {
3437 mAlertDialog = new AlertDialog.Builder(this)
3438 .setTitle(R.string.loadSuspendedTitle)
3439 .setMessage(R.string.loadSuspended)
3440 .setPositiveButton(R.string.ok, null)
3441 .show();
3442 }
3443 }
3444
The Android Open Source Project0c908882009-03-03 19:32:16 -08003445 @Override
3446 protected void onActivityResult(int requestCode, int resultCode,
3447 Intent intent) {
Grace Klobabb394f32009-11-19 10:26:37 -08003448 if (getTopWindow() == null) return;
3449
The Android Open Source Project0c908882009-03-03 19:32:16 -08003450 switch (requestCode) {
3451 case COMBO_PAGE:
3452 if (resultCode == RESULT_OK && intent != null) {
3453 String data = intent.getAction();
3454 Bundle extras = intent.getExtras();
3455 if (extras != null && extras.getBoolean("new_window", false)) {
Leon Scroggins25d35472009-09-15 11:37:27 -04003456 openTab(data);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003457 } else {
Grace Kloba22ac16e2009-10-07 18:00:23 -07003458 final Tab currentTab =
The Android Open Source Project0c908882009-03-03 19:32:16 -08003459 mTabControl.getCurrentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04003460 dismissSubWindow(currentTab);
3461 if (data != null && data.length() != 0) {
Leon Scroggins92472e82010-02-17 16:32:28 -05003462 loadUrl(getTopWindow(), data);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003463 }
3464 }
3465 }
Leon Scrogginsfde97462010-01-11 13:06:21 -05003466 // Deliberately fall through to PREFERENCES_PAGE, since the
3467 // same extra may be attached to the COMBO_PAGE
3468 case PREFERENCES_PAGE:
3469 if (resultCode == RESULT_OK && intent != null) {
3470 String action = intent.getStringExtra(Intent.EXTRA_TEXT);
3471 if (BrowserSettings.PREF_CLEAR_HISTORY.equals(action)) {
3472 mTabControl.removeParentChildRelationShips();
3473 }
3474 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003475 break;
Leon Scroggins8d5fa432009-10-02 15:55:59 -04003476 // Choose a file from the file picker.
3477 case FILE_SELECTED:
3478 if (null == mUploadMessage) break;
3479 Uri result = intent == null || resultCode != RESULT_OK ? null
3480 : intent.getData();
3481 mUploadMessage.onReceiveValue(result);
3482 mUploadMessage = null;
3483 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003484 default:
3485 break;
3486 }
Leon Scroggins30444232009-09-04 18:36:20 -04003487 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003488 }
3489
3490 /*
3491 * This method is called as a result of the user selecting the options
Leon Scrogginsf08809b2010-01-21 09:27:46 -05003492 * menu to see the download window. It shows the download window on top of
3493 * the current window.
The Android Open Source Project0c908882009-03-03 19:32:16 -08003494 */
Leon Scrogginsf08809b2010-01-21 09:27:46 -05003495 private void viewDownloads(Uri downloadRecord) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003496 Intent intent = new Intent(this,
3497 BrowserDownloadPage.class);
3498 intent.setData(downloadRecord);
Grace Kloba22ac16e2009-10-07 18:00:23 -07003499 startActivityForResult(intent, BrowserActivity.DOWNLOAD_PAGE);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003500
3501 }
3502
Leon Scroggins160a7e72009-08-14 18:28:01 -04003503 /**
3504 * Open the Go page.
3505 * @param startWithHistory If true, open starting on the history tab.
3506 * Otherwise, start with the bookmarks tab.
Leon Scroggins160a7e72009-08-14 18:28:01 -04003507 */
Leon Scroggins30444232009-09-04 18:36:20 -04003508 /* package */ void bookmarksOrHistoryPicker(boolean startWithHistory) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003509 WebView current = mTabControl.getCurrentWebView();
3510 if (current == null) {
3511 return;
3512 }
3513 Intent intent = new Intent(this,
3514 CombinedBookmarkHistoryActivity.class);
3515 String title = current.getTitle();
3516 String url = current.getUrl();
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01003517 Bitmap thumbnail = createScreenshot(current);
3518
The Android Open Source Project0c908882009-03-03 19:32:16 -08003519 // Just in case the user opens bookmarks before a page finishes loading
3520 // so the current history item, and therefore the page, is null.
3521 if (null == url) {
3522 url = mLastEnteredUrl;
3523 // This can happen.
3524 if (null == url) {
3525 url = mSettings.getHomePage();
3526 }
3527 }
3528 // In case the web page has not yet received its associated title.
3529 if (title == null) {
3530 title = url;
3531 }
3532 intent.putExtra("title", title);
3533 intent.putExtra("url", url);
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01003534 intent.putExtra("thumbnail", thumbnail);
Leon Scroggins30444232009-09-04 18:36:20 -04003535 // Disable opening in a new window if we have maxed out the windows
Grace Kloba22ac16e2009-10-07 18:00:23 -07003536 intent.putExtra("disable_new_window", !mTabControl.canCreateNewTab());
Patrick Scott3918d442009-08-04 13:22:29 -04003537 intent.putExtra("touch_icon_url", current.getTouchIconUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003538 if (startWithHistory) {
3539 intent.putExtra(CombinedBookmarkHistoryActivity.STARTING_TAB,
3540 CombinedBookmarkHistoryActivity.HISTORY_TAB);
3541 }
3542 startActivityForResult(intent, COMBO_PAGE);
3543 }
3544
3545 // Called when loading from context menu or LOAD_URL message
Leon Scroggins92472e82010-02-17 16:32:28 -05003546 private void loadUrlFromContext(WebView view, String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003547 // In case the user enters nothing.
3548 if (url != null && url.length() != 0 && view != null) {
3549 url = smartUrlFilter(url);
Grace Kloba22ac16e2009-10-07 18:00:23 -07003550 if (!view.getWebViewClient().shouldOverrideUrlLoading(view, url)) {
Leon Scroggins92472e82010-02-17 16:32:28 -05003551 loadUrl(view, url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003552 }
3553 }
3554 }
3555
Leon Scroggins92472e82010-02-17 16:32:28 -05003556 /**
3557 * Load the URL into the given WebView and update the title bar
3558 * to reflect the new load. Call this instead of WebView.loadUrl
3559 * directly.
3560 * @param view The WebView used to load url.
3561 * @param url The URL to load.
3562 */
3563 private void loadUrl(WebView view, String url) {
3564 updateTitleBarForNewLoad(view, url);
3565 view.loadUrl(url);
3566 }
3567
3568 /**
3569 * Load UrlData into a Tab and update the title bar to reflect the new
3570 * load. Call this instead of UrlData.loadIn directly.
3571 * @param t The Tab used to load.
3572 * @param data The UrlData being loaded.
3573 */
3574 private void loadUrlDataIn(Tab t, UrlData data) {
3575 updateTitleBarForNewLoad(t.getWebView(), data.mUrl);
3576 data.loadIn(t);
3577 }
3578
3579 /**
3580 * If the WebView is the top window, update the title bar to reflect
3581 * loading the new URL. i.e. set its text, clear the favicon (which
3582 * will be set once the page begins loading), and set the progress to
3583 * INITIAL_PROGRESS to show that the page has begun to load. Called
3584 * by loadUrl and loadUrlDataIn.
3585 * @param view The WebView that is starting a load.
3586 * @param url The URL that is being loaded.
3587 */
3588 private void updateTitleBarForNewLoad(WebView view, String url) {
3589 if (view == getTopWindow()) {
3590 setUrlTitle(url, null);
3591 setFavicon(null);
3592 onProgressChanged(view, INITIAL_PROGRESS);
3593 }
3594 }
3595
The Android Open Source Project0c908882009-03-03 19:32:16 -08003596 private String smartUrlFilter(Uri inUri) {
3597 if (inUri != null) {
3598 return smartUrlFilter(inUri.toString());
3599 }
3600 return null;
3601 }
3602
Feng Qianb34f87a2009-03-24 21:27:26 -07003603 protected static final Pattern ACCEPTED_URI_SCHEMA = Pattern.compile(
The Android Open Source Project0c908882009-03-03 19:32:16 -08003604 "(?i)" + // switch on case insensitive matching
3605 "(" + // begin group for schema
3606 "(?:http|https|file):\\/\\/" +
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003607 "|(?:inline|data|about|content|javascript):" +
The Android Open Source Project0c908882009-03-03 19:32:16 -08003608 ")" +
3609 "(.*)" );
3610
3611 /**
3612 * Attempts to determine whether user input is a URL or search
3613 * terms. Anything with a space is passed to search.
3614 *
3615 * Converts to lowercase any mistakenly uppercased schema (i.e.,
3616 * "Http://" converts to "http://"
3617 *
3618 * @return Original or modified URL
3619 *
3620 */
3621 String smartUrlFilter(String url) {
3622
3623 String inUrl = url.trim();
3624 boolean hasSpace = inUrl.indexOf(' ') != -1;
3625
3626 Matcher matcher = ACCEPTED_URI_SCHEMA.matcher(inUrl);
3627 if (matcher.matches()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003628 // force scheme to lowercase
3629 String scheme = matcher.group(1);
3630 String lcScheme = scheme.toLowerCase();
3631 if (!lcScheme.equals(scheme)) {
Mitsuru Oshima123ecfb2009-05-18 19:11:14 -07003632 inUrl = lcScheme + matcher.group(2);
3633 }
3634 if (hasSpace) {
3635 inUrl = inUrl.replace(" ", "%20");
The Android Open Source Project0c908882009-03-03 19:32:16 -08003636 }
3637 return inUrl;
3638 }
3639 if (hasSpace) {
Satish Sampath565505b2009-05-29 15:37:27 +01003640 // FIXME: Is this the correct place to add to searches?
3641 // what if someone else calls this function?
3642 int shortcut = parseUrlShortcut(inUrl);
3643 if (shortcut != SHORTCUT_INVALID) {
3644 Browser.addSearchUrl(mResolver, inUrl);
3645 String query = inUrl.substring(2);
3646 switch (shortcut) {
3647 case SHORTCUT_GOOGLE_SEARCH:
Grace Kloba47fdfdb2009-06-30 11:15:34 -07003648 return URLUtil.composeSearchUrl(query, QuickSearch_G, QUERY_PLACE_HOLDER);
Satish Sampath565505b2009-05-29 15:37:27 +01003649 case SHORTCUT_WIKIPEDIA_SEARCH:
3650 return URLUtil.composeSearchUrl(query, QuickSearch_W, QUERY_PLACE_HOLDER);
3651 case SHORTCUT_DICTIONARY_SEARCH:
3652 return URLUtil.composeSearchUrl(query, QuickSearch_D, QUERY_PLACE_HOLDER);
3653 case SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH:
The Android Open Source Project0c908882009-03-03 19:32:16 -08003654 // FIXME: we need location in this case
Satish Sampath565505b2009-05-29 15:37:27 +01003655 return URLUtil.composeSearchUrl(query, QuickSearch_L, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003656 }
3657 }
3658 } else {
Dan Egnor5ee906c2009-11-18 12:11:49 -08003659 if (Patterns.WEB_URL.matcher(inUrl).matches()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003660 return URLUtil.guessUrl(inUrl);
3661 }
3662 }
3663
3664 Browser.addSearchUrl(mResolver, inUrl);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07003665 return URLUtil.composeSearchUrl(inUrl, QuickSearch_G, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003666 }
3667
Ben Murdochbff2d602009-07-01 20:19:05 +01003668 /* package */ void setShouldShowErrorConsole(boolean flag) {
3669 if (flag == mShouldShowErrorConsole) {
3670 // Nothing to do.
3671 return;
3672 }
3673
3674 mShouldShowErrorConsole = flag;
3675
Grace Kloba22ac16e2009-10-07 18:00:23 -07003676 ErrorConsoleView errorConsole = mTabControl.getCurrentTab()
3677 .getErrorConsole(true);
Ben Murdochbff2d602009-07-01 20:19:05 +01003678
3679 if (flag) {
3680 // Setting the show state of the console will cause it's the layout to be inflated.
3681 if (errorConsole.numberOfErrors() > 0) {
3682 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
3683 } else {
3684 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
3685 }
3686
3687 // Now we can add it to the main view.
3688 mErrorConsoleContainer.addView(errorConsole,
Romain Guy15b8ec62010-01-08 15:06:43 -08003689 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
Ben Murdochbff2d602009-07-01 20:19:05 +01003690 ViewGroup.LayoutParams.WRAP_CONTENT));
3691 } else {
3692 mErrorConsoleContainer.removeView(errorConsole);
3693 }
3694
3695 }
3696
Grace Kloba22ac16e2009-10-07 18:00:23 -07003697 boolean shouldShowErrorConsole() {
3698 return mShouldShowErrorConsole;
3699 }
3700
Andrei Popescu163ab742009-10-20 17:58:23 +01003701 private void setStatusBarVisibility(boolean visible) {
3702 int flag = visible ? 0 : WindowManager.LayoutParams.FLAG_FULLSCREEN;
3703 getWindow().setFlags(flag, WindowManager.LayoutParams.FLAG_FULLSCREEN);
3704 }
3705
Andrei Popescu56199cc2010-01-12 22:39:16 +00003706
3707 private void sendNetworkType(String type, String subtype) {
3708 WebView w = mTabControl.getCurrentWebView();
3709 if (w != null) {
3710 w.setNetworkType(type, subtype);
3711 }
3712 }
3713
Andrei Popescu30995e72010-02-09 16:59:58 +00003714 private void packageChanged(String packageName, boolean wasAdded) {
3715 WebView w = mTabControl.getCurrentWebView();
3716 if (w == null) {
3717 return;
3718 }
3719
3720 if (wasAdded) {
3721 w.addPackageName(packageName);
3722 } else {
3723 w.removePackageName(packageName);
3724 }
3725 }
3726
3727 private void addPackageNames(Set<String> packageNames) {
3728 WebView w = mTabControl.getCurrentWebView();
3729 if (w == null) {
3730 return;
3731 }
3732
3733 w.addPackageNames(packageNames);
3734 }
3735
3736 private void getInstalledPackages() {
3737 AsyncTask<Void, Void, Set<String> > task =
3738 new AsyncTask<Void, Void, Set<String> >() {
3739 protected Set<String> doInBackground(Void... unused) {
3740 Set<String> installedPackages = new HashSet<String>();
3741 PackageManager pm = BrowserActivity.this.getPackageManager();
3742 if (pm != null) {
3743 List<PackageInfo> packages = pm.getInstalledPackages(0);
3744 for (PackageInfo p : packages) {
3745 if (BrowserActivity.this.sGoogleApps.contains(p.packageName)) {
3746 installedPackages.add(p.packageName);
3747 }
3748 }
3749 }
3750
3751 return installedPackages;
3752 }
3753
3754 // Executes on the UI thread
3755 protected void onPostExecute(Set<String> installedPackages) {
3756 addPackageNames(installedPackages);
3757 }
3758 };
3759 task.execute();
3760 }
3761
Grace Klobaeb6eef42009-09-15 17:56:32 -07003762 final static int LOCK_ICON_UNSECURE = 0;
3763 final static int LOCK_ICON_SECURE = 1;
3764 final static int LOCK_ICON_MIXED = 2;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003765
The Android Open Source Project0c908882009-03-03 19:32:16 -08003766 private BrowserSettings mSettings;
3767 private TabControl mTabControl;
3768 private ContentResolver mResolver;
3769 private FrameLayout mContentView;
Andrei Popescuadc008d2009-06-26 14:11:30 +01003770 private View mCustomView;
3771 private FrameLayout mCustomViewContainer;
Andrei Popescuc9b55562009-07-07 10:51:15 +01003772 private WebChromeClient.CustomViewCallback mCustomViewCallback;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003773
3774 // FIXME, temp address onPrepareMenu performance problem. When we move everything out of
3775 // view, we should rewrite this.
3776 private int mCurrentMenuState = 0;
3777 private int mMenuState = R.id.MAIN_MENU;
Andrei Popescuadc008d2009-06-26 14:11:30 +01003778 private int mOldMenuState = EMPTY_MENU;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003779 private static final int EMPTY_MENU = -1;
3780 private Menu mMenu;
3781
3782 private FindDialog mFindDialog;
3783 // Used to prevent chording to result in firing two shortcuts immediately
3784 // one after another. Fixes bug 1211714.
3785 boolean mCanChord;
3786
3787 private boolean mInLoad;
3788 private boolean mIsNetworkUp;
Ben Murdochb7cc8b42009-09-28 10:59:09 +01003789 private boolean mDidStopLoad;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003790
The Android Open Source Project0c908882009-03-03 19:32:16 -08003791 private boolean mActivityInPause = true;
3792
3793 private boolean mMenuIsDown;
3794
The Android Open Source Project0c908882009-03-03 19:32:16 -08003795 private static boolean mInTrace;
3796
3797 // Performance probe
3798 private static final int[] SYSTEM_CPU_FORMAT = new int[] {
3799 Process.PROC_SPACE_TERM | Process.PROC_COMBINE,
3800 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 1: user time
3801 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 2: nice time
3802 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 3: sys time
3803 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 4: idle time
3804 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 5: iowait time
3805 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 6: irq time
3806 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG // 7: softirq time
3807 };
3808
3809 private long mStart;
3810 private long mProcessStart;
3811 private long mUserStart;
3812 private long mSystemStart;
3813 private long mIdleStart;
3814 private long mIrqStart;
3815
3816 private long mUiStart;
3817
3818 private Drawable mMixLockIcon;
3819 private Drawable mSecLockIcon;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003820
3821 /* hold a ref so we can auto-cancel if necessary */
3822 private AlertDialog mAlertDialog;
3823
The Android Open Source Project0c908882009-03-03 19:32:16 -08003824 // The up-to-date URL and title (these can be different from those stored
3825 // in WebView, since it takes some time for the information in WebView to
3826 // get updated)
3827 private String mUrl;
3828 private String mTitle;
3829
3830 // As PageInfo has different style for landscape / portrait, we have
3831 // to re-open it when configuration changed
3832 private AlertDialog mPageInfoDialog;
Grace Kloba22ac16e2009-10-07 18:00:23 -07003833 private Tab mPageInfoView;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003834 // If the Page-Info dialog is launched from the SSL-certificate-on-error
3835 // dialog, we should not just dismiss it, but should get back to the
3836 // SSL-certificate-on-error dialog. This flag is used to store this state
Leon Scrogginsc7b92f82010-01-11 18:17:31 -05003837 private boolean mPageInfoFromShowSSLCertificateOnError;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003838
3839 // as SSLCertificateOnError has different style for landscape / portrait,
3840 // we have to re-open it when configuration changed
3841 private AlertDialog mSSLCertificateOnErrorDialog;
3842 private WebView mSSLCertificateOnErrorView;
3843 private SslErrorHandler mSSLCertificateOnErrorHandler;
3844 private SslError mSSLCertificateOnErrorError;
3845
3846 // as SSLCertificate has different style for landscape / portrait, we
3847 // have to re-open it when configuration changed
3848 private AlertDialog mSSLCertificateDialog;
Grace Kloba22ac16e2009-10-07 18:00:23 -07003849 private Tab mSSLCertificateView;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003850
3851 // as HttpAuthentication has different style for landscape / portrait, we
3852 // have to re-open it when configuration changed
3853 private AlertDialog mHttpAuthenticationDialog;
3854 private HttpAuthHandler mHttpAuthHandler;
3855
3856 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_PARAMS =
3857 new FrameLayout.LayoutParams(
Romain Guy15b8ec62010-01-08 15:06:43 -08003858 ViewGroup.LayoutParams.MATCH_PARENT,
3859 ViewGroup.LayoutParams.MATCH_PARENT);
Andrei Popescuadc008d2009-06-26 14:11:30 +01003860 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_GRAVITY_CENTER =
3861 new FrameLayout.LayoutParams(
Romain Guy15b8ec62010-01-08 15:06:43 -08003862 ViewGroup.LayoutParams.MATCH_PARENT,
3863 ViewGroup.LayoutParams.MATCH_PARENT,
Andrei Popescuadc008d2009-06-26 14:11:30 +01003864 Gravity.CENTER);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07003865 // Google search
3866 final static String QuickSearch_G = "http://www.google.com/m?q=%s";
The Android Open Source Project0c908882009-03-03 19:32:16 -08003867 // Wikipedia search
3868 final static String QuickSearch_W = "http://en.wikipedia.org/w/index.php?search=%s&go=Go";
3869 // Dictionary search
3870 final static String QuickSearch_D = "http://dictionary.reference.com/search?q=%s";
3871 // Google Mobile Local search
3872 final static String QuickSearch_L = "http://www.google.com/m/search?site=local&q=%s&near=mountain+view";
3873
3874 final static String QUERY_PLACE_HOLDER = "%s";
3875
3876 // "source" parameter for Google search through search key
3877 final static String GOOGLE_SEARCH_SOURCE_SEARCHKEY = "browser-key";
3878 // "source" parameter for Google search through goto menu
3879 final static String GOOGLE_SEARCH_SOURCE_GOTO = "browser-goto";
3880 // "source" parameter for Google search through simplily type
3881 final static String GOOGLE_SEARCH_SOURCE_TYPE = "browser-type";
3882 // "source" parameter for Google search suggested by the browser
3883 final static String GOOGLE_SEARCH_SOURCE_SUGGEST = "browser-suggest";
3884 // "source" parameter for Google search from unknown source
3885 final static String GOOGLE_SEARCH_SOURCE_UNKNOWN = "unknown";
3886
3887 private final static String LOGTAG = "browser";
3888
The Android Open Source Project0c908882009-03-03 19:32:16 -08003889 private String mLastEnteredUrl;
3890
3891 private PowerManager.WakeLock mWakeLock;
3892 private final static int WAKELOCK_TIMEOUT = 5 * 60 * 1000; // 5 minutes
3893
3894 private Toast mStopToast;
3895
Leon Scroggins68579392009-09-15 15:31:54 -04003896 private TitleBar mTitleBar;
Leon Scroggins81db3662009-06-04 17:45:11 -04003897
Ben Murdochbff2d602009-07-01 20:19:05 +01003898 private LinearLayout mErrorConsoleContainer = null;
3899 private boolean mShouldShowErrorConsole = false;
3900
The Android Open Source Project0c908882009-03-03 19:32:16 -08003901 // As the ids are dynamically created, we can't guarantee that they will
3902 // be in sequence, so this static array maps ids to a window number.
3903 final static private int[] WINDOW_SHORTCUT_ID_ARRAY =
3904 { R.id.window_one_menu_id, R.id.window_two_menu_id, R.id.window_three_menu_id,
3905 R.id.window_four_menu_id, R.id.window_five_menu_id, R.id.window_six_menu_id,
3906 R.id.window_seven_menu_id, R.id.window_eight_menu_id };
3907
3908 // monitor platform changes
3909 private IntentFilter mNetworkStateChangedFilter;
3910 private BroadcastReceiver mNetworkStateIntentReceiver;
3911
Grace Klobab4da0ad2009-05-14 14:45:40 -07003912 private BroadcastReceiver mPackageInstallationReceiver;
3913
The Android Open Source Project0c908882009-03-03 19:32:16 -08003914 // activity requestCode
Nicolas Roard78a98e42009-05-11 13:34:17 +01003915 final static int COMBO_PAGE = 1;
3916 final static int DOWNLOAD_PAGE = 2;
3917 final static int PREFERENCES_PAGE = 3;
Leon Scroggins8d5fa432009-10-02 15:55:59 -04003918 final static int FILE_SELECTED = 4;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003919
Andrei Popescu540035d2009-09-18 18:59:20 +01003920 // the default <video> poster
3921 private Bitmap mDefaultVideoPoster;
3922 // the video progress view
3923 private View mVideoProgressView;
3924
Andrei Popescu30995e72010-02-09 16:59:58 +00003925 // The Google packages we monitor for the navigator.isApplicationInstalled()
3926 // API. Add as needed.
3927 private static Set<String> sGoogleApps;
3928 static {
3929 sGoogleApps = new HashSet<String>();
3930 sGoogleApps.add("com.google.android.youtube");
3931 }
3932
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003933 /**
3934 * A UrlData class to abstract how the content will be set to WebView.
3935 * This base class uses loadUrl to show the content.
3936 */
3937 private static class UrlData {
Grace Kloba068e48b2010-01-26 18:11:27 -08003938 final String mUrl;
3939 final Map<String, String> mHeaders;
Leon Scroggins58d56c62010-01-28 15:12:40 -05003940 final Intent mVoiceIntent;
Grace Kloba60e095c2009-06-16 11:50:55 -07003941
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003942 UrlData(String url) {
3943 this.mUrl = url;
Grace Kloba068e48b2010-01-26 18:11:27 -08003944 this.mHeaders = null;
Leon Scroggins58d56c62010-01-28 15:12:40 -05003945 this.mVoiceIntent = null;
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003946 }
Grace Kloba60e095c2009-06-16 11:50:55 -07003947
Leon Scroggins58d56c62010-01-28 15:12:40 -05003948 UrlData(String url, Map<String, String> headers, Intent intent) {
Grace Kloba068e48b2010-01-26 18:11:27 -08003949 this.mUrl = url;
3950 this.mHeaders = headers;
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -05003951 if (RecognizerResultsIntent.ACTION_VOICE_SEARCH_RESULTS
3952 .equals(intent.getAction())) {
Leon Scroggins58d56c62010-01-28 15:12:40 -05003953 this.mVoiceIntent = intent;
3954 } else {
3955 this.mVoiceIntent = null;
3956 }
Grace Kloba60e095c2009-06-16 11:50:55 -07003957 }
3958
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003959 boolean isEmpty() {
Leon Scroggins58d56c62010-01-28 15:12:40 -05003960 return mVoiceIntent == null && (mUrl == null || mUrl.length() == 0);
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003961 }
3962
Leon Scroggins92472e82010-02-17 16:32:28 -05003963 /**
3964 * Load this UrlData into the given Tab. Use loadUrlDataIn to update
3965 * the title bar as well.
3966 */
Leon Scroggins58d56c62010-01-28 15:12:40 -05003967 public void loadIn(Tab t) {
3968 if (mVoiceIntent != null) {
3969 t.activateVoiceSearchMode(mVoiceIntent);
3970 } else {
3971 t.getWebView().loadUrl(mUrl, mHeaders);
3972 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003973 }
3974 };
3975
Leon Scroggins1f005d32009-08-10 17:36:42 -04003976 /* package */ static final UrlData EMPTY_URL_DATA = new UrlData(null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003977}