blob: 22a0b1fc90526a3a7209ccb1144cb368b2cb27f1 [file] [log] [blame]
The Android Open Source Project0c908882009-03-03 19:32:16 -08001/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.browser;
18
The Android Open Source Project0c908882009-03-03 19:32:16 -080019import android.app.Activity;
The Android Open Source Project0c908882009-03-03 19:32:16 -080020import android.app.AlertDialog;
21import android.app.ProgressDialog;
22import android.app.SearchManager;
23import android.content.ActivityNotFoundException;
24import android.content.BroadcastReceiver;
25import android.content.ComponentName;
Leon Scroggins58d56c62010-01-28 15:12:40 -050026import android.content.ContentProvider;
27import android.content.ContentProviderClient;
The Android Open Source Project0c908882009-03-03 19:32:16 -080028import android.content.ContentResolver;
Leon Scrogginsb6b7f9e2009-06-18 12:05:28 -040029import android.content.ContentUris;
The Android Open Source Project0c908882009-03-03 19:32:16 -080030import android.content.ContentValues;
31import android.content.Context;
32import android.content.DialogInterface;
33import android.content.Intent;
34import android.content.IntentFilter;
Grace Klobab4da0ad2009-05-14 14:45:40 -070035import android.content.pm.PackageInfo;
The Android Open Source Project0c908882009-03-03 19:32:16 -080036import android.content.pm.PackageManager;
37import android.content.pm.ResolveInfo;
The Android Open Source Project0c908882009-03-03 19:32:16 -080038import android.content.res.Configuration;
39import android.content.res.Resources;
40import android.database.Cursor;
Leon Scroggins96afcb12009-12-10 12:35:56 -050041import android.database.DatabaseUtils;
The Android Open Source Project0c908882009-03-03 19:32:16 -080042import android.graphics.Bitmap;
Andrei Popescu540035d2009-09-18 18:59:20 +010043import android.graphics.BitmapFactory;
The Android Open Source Project0c908882009-03-03 19:32:16 -080044import android.graphics.Canvas;
The Android Open Source Project0c908882009-03-03 19:32:16 -080045import android.graphics.Picture;
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -040046import android.graphics.PixelFormat;
47import android.graphics.Rect;
The Android Open Source Project0c908882009-03-03 19:32:16 -080048import android.graphics.drawable.Drawable;
The Android Open Source Project0c908882009-03-03 19:32:16 -080049import android.net.ConnectivityManager;
Andrei Popescu56199cc2010-01-12 22:39:16 +000050import android.net.NetworkInfo;
The Android Open Source Project0c908882009-03-03 19:32:16 -080051import android.net.Uri;
52import android.net.WebAddress;
The Android Open Source Project0c908882009-03-03 19:32:16 -080053import android.net.http.SslCertificate;
54import android.net.http.SslError;
55import android.os.AsyncTask;
56import android.os.Bundle;
57import android.os.Debug;
58import android.os.Environment;
59import android.os.Handler;
The Android Open Source Project0c908882009-03-03 19:32:16 -080060import android.os.Message;
61import android.os.PowerManager;
62import android.os.Process;
The Android Open Source Project0c908882009-03-03 19:32:16 -080063import android.os.ServiceManager;
64import android.os.SystemClock;
The Android Open Source Project0c908882009-03-03 19:32:16 -080065import android.provider.Browser;
Cary Clark5e335a32009-09-22 14:53:11 -040066import android.provider.ContactsContract;
67import android.provider.ContactsContract.Intents.Insert;
The Android Open Source Project0c908882009-03-03 19:32:16 -080068import android.provider.Downloads;
69import android.provider.MediaStore;
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -050070import android.speech.RecognizerResultsIntent;
The Android Open Source Project0c908882009-03-03 19:32:16 -080071import android.text.IClipboard;
72import android.text.TextUtils;
73import android.text.format.DateFormat;
Leon Scrogginsb94bf272009-09-25 15:22:08 -040074import android.util.AttributeSet;
The Android Open Source Project0c908882009-03-03 19:32:16 -080075import android.util.Log;
Dianne Hackborn385effd2010-02-24 20:03:04 -080076import android.util.Patterns;
The Android Open Source Project0c908882009-03-03 19:32:16 -080077import android.view.ContextMenu;
78import android.view.Gravity;
79import android.view.KeyEvent;
80import android.view.LayoutInflater;
81import android.view.Menu;
82import android.view.MenuInflater;
83import android.view.MenuItem;
84import android.view.View;
85import android.view.ViewGroup;
86import android.view.Window;
87import android.view.WindowManager;
88import android.view.ContextMenu.ContextMenuInfo;
89import android.view.MenuItem.OnMenuItemClickListener;
The Android Open Source Project0c908882009-03-03 19:32:16 -080090import android.webkit.CookieManager;
91import android.webkit.CookieSyncManager;
92import android.webkit.DownloadListener;
93import android.webkit.HttpAuthHandler;
Grace Klobab4da0ad2009-05-14 14:45:40 -070094import android.webkit.PluginManager;
The Android Open Source Project0c908882009-03-03 19:32:16 -080095import android.webkit.SslErrorHandler;
96import android.webkit.URLUtil;
Leon Clarkecb6cc862009-09-29 18:35:13 +010097import android.webkit.ValueCallback;
The Android Open Source Project0c908882009-03-03 19:32:16 -080098import android.webkit.WebChromeClient;
99import android.webkit.WebHistoryItem;
100import android.webkit.WebIconDatabase;
101import android.webkit.WebView;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800102import android.widget.EditText;
103import android.widget.FrameLayout;
104import android.widget.LinearLayout;
105import android.widget.TextView;
106import android.widget.Toast;
Fred Quintana752b6562009-12-18 10:18:26 -0800107import android.accounts.Account;
108import android.accounts.AccountManager;
109import android.accounts.AccountManagerFuture;
110import android.accounts.AuthenticatorException;
111import android.accounts.OperationCanceledException;
112import android.accounts.AccountManagerCallback;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800113
Bjorn Bringert10d1cca2010-02-10 14:22:12 +0000114import com.android.common.Search;
Leon Scroggins1fe13a52010-02-09 15:31:26 -0500115import com.android.common.speech.LoggingEvents;
Dan Egnor5ee906c2009-11-18 12:11:49 -0800116
Leon Scrogginsb6b7f9e2009-06-18 12:05:28 -0400117import java.io.ByteArrayOutputStream;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800118import java.io.File;
Ben Murdoch4f75ba22009-10-27 11:48:28 +0000119import java.io.IOException;
120import java.io.InputStream;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800121import java.net.MalformedURLException;
122import java.net.URI;
Dianne Hackborn99189432009-06-17 18:06:18 -0700123import java.net.URISyntaxException;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800124import java.net.URL;
125import java.net.URLEncoder;
126import java.text.ParseException;
127import java.util.Date;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800128import java.util.HashMap;
Andrei Popescu30995e72010-02-09 16:59:58 +0000129import java.util.HashSet;
Grace Kloba00f54c52010-01-27 14:53:51 -0800130import java.util.Iterator;
Andrei Popescu30995e72010-02-09 16:59:58 +0000131import java.util.List;
Grace Kloba068e48b2010-01-26 18:11:27 -0800132import java.util.Map;
Andrei Popescu30995e72010-02-09 16:59:58 +0000133import java.util.Set;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800134import java.util.regex.Matcher;
135import java.util.regex.Pattern;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800136
137public class BrowserActivity extends Activity
Shimeng (Simon) Wang98d5fce2010-03-16 13:23:39 -0700138 implements View.OnCreateContextMenuListener, DownloadListener {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800139
Dave Bort31a6d1c2009-04-13 15:56:49 -0700140 /* Define some aliases to make these debugging flags easier to refer to.
141 * This file imports android.provider.Browser, so we can't just refer to "Browser.DEBUG".
142 */
143 private final static boolean DEBUG = com.android.browser.Browser.DEBUG;
144 private final static boolean LOGV_ENABLED = com.android.browser.Browser.LOGV_ENABLED;
145 private final static boolean LOGD_ENABLED = com.android.browser.Browser.LOGD_ENABLED;
146
Satish Sampath565505b2009-05-29 15:37:27 +0100147 // These are single-character shortcuts for searching popular sources.
148 private static final int SHORTCUT_INVALID = 0;
149 private static final int SHORTCUT_GOOGLE_SEARCH = 1;
150 private static final int SHORTCUT_WIKIPEDIA_SEARCH = 2;
151 private static final int SHORTCUT_DICTIONARY_SEARCH = 3;
152 private static final int SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH = 4;
153
Cary Clarka9771242009-08-11 16:42:26 -0400154 private static class ClearThumbnails extends AsyncTask<File, Void, Void> {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800155 @Override
156 public Void doInBackground(File... files) {
157 if (files != null) {
158 for (File f : files) {
Cary Clarkd6be1752009-08-12 12:56:42 -0400159 if (!f.delete()) {
160 Log.e(LOGTAG, f.getPath() + " was not deleted");
161 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800162 }
163 }
164 return null;
165 }
166 }
167
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400168 /**
169 * This layout holds everything you see below the status bar, including the
170 * error console, the custom view container, and the webviews.
171 */
172 private FrameLayout mBrowserFrameLayout;
Leon Scroggins81db3662009-06-04 17:45:11 -0400173
Grace Kloba22ac16e2009-10-07 18:00:23 -0700174 @Override
175 public void onCreate(Bundle icicle) {
Dave Bort31a6d1c2009-04-13 15:56:49 -0700176 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800177 Log.v(LOGTAG, this + " onStart");
178 }
179 super.onCreate(icicle);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800180 // test the browser in OpenGL
181 // requestWindowFeature(Window.FEATURE_OPENGL);
182
Mike Reedd334bf52010-01-26 15:21:44 -0500183 // enable this to test the browser in 32bit
184 if (false) {
185 getWindow().setFormat(PixelFormat.RGBX_8888);
186 BitmapFactory.setDefaultConfig(Bitmap.Config.ARGB_8888);
187 }
188
The Android Open Source Project0c908882009-03-03 19:32:16 -0800189 setDefaultKeyMode(DEFAULT_KEYS_SEARCH_LOCAL);
190
191 mResolver = getContentResolver();
192
Grace Kloba0923d692009-09-23 21:37:25 -0700193 // If this was a web search request, pass it on to the default web
194 // search provider and finish this activity.
195 if (handleWebSearchIntent(getIntent())) {
196 finish();
197 return;
198 }
199
The Android Open Source Project0c908882009-03-03 19:32:16 -0800200 mSecLockIcon = Resources.getSystem().getDrawable(
201 android.R.drawable.ic_secure);
202 mMixLockIcon = Resources.getSystem().getDrawable(
203 android.R.drawable.ic_partial_secure);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800204
Leon Scroggins81db3662009-06-04 17:45:11 -0400205 FrameLayout frameLayout = (FrameLayout) getWindow().getDecorView()
206 .findViewById(com.android.internal.R.id.content);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400207 mBrowserFrameLayout = (FrameLayout) LayoutInflater.from(this)
208 .inflate(R.layout.custom_screen, null);
209 mContentView = (FrameLayout) mBrowserFrameLayout.findViewById(
210 R.id.main_content);
211 mErrorConsoleContainer = (LinearLayout) mBrowserFrameLayout
212 .findViewById(R.id.error_console);
213 mCustomViewContainer = (FrameLayout) mBrowserFrameLayout
214 .findViewById(R.id.fullscreen_custom_content);
215 frameLayout.addView(mBrowserFrameLayout, COVER_SCREEN_PARAMS);
Leon Scroggins68579392009-09-15 15:31:54 -0400216 mTitleBar = new TitleBar(this);
Grace Kloba1542f742010-03-17 21:11:15 -0700217 // mTitleBar will be always shown in the fully loaded mode
218 mTitleBar.setProgress(100);
Leon Scrogginsfe87bd32009-10-06 10:10:00 -0400219 mFakeTitleBar = new TitleBar(this);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800220
221 // Create the tab control and our initial tab
222 mTabControl = new TabControl(this);
223
224 // Open the icon database and retain all the bookmark urls for favicons
225 retainIconsOnStartup();
226
227 // Keep a settings instance handy.
228 mSettings = BrowserSettings.getInstance();
229 mSettings.setTabControl(mTabControl);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800230
231 PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
232 mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Browser");
233
Patrick Scott6adacc92010-03-05 08:24:51 -0500234 // Find out if the network is currently up.
235 ConnectivityManager cm = (ConnectivityManager) getSystemService(
236 Context.CONNECTIVITY_SERVICE);
237 NetworkInfo info = cm.getActiveNetworkInfo();
238 if (info != null) {
239 mIsNetworkUp = info.isAvailable();
240 }
241
Grace Klobaa34f6862009-07-31 16:28:17 -0700242 /* enables registration for changes in network status from
243 http stack */
244 mNetworkStateChangedFilter = new IntentFilter();
245 mNetworkStateChangedFilter.addAction(
246 ConnectivityManager.CONNECTIVITY_ACTION);
247 mNetworkStateIntentReceiver = new BroadcastReceiver() {
248 @Override
249 public void onReceive(Context context, Intent intent) {
250 if (intent.getAction().equals(
251 ConnectivityManager.CONNECTIVITY_ACTION)) {
Andrei Popescue4c98462010-02-19 15:44:13 +0000252
253 NetworkInfo info = intent.getParcelableExtra(
254 ConnectivityManager.EXTRA_NETWORK_INFO);
255 String typeName = info.getTypeName();
256 String subtypeName = info.getSubtypeName();
257 sendNetworkType(typeName.toLowerCase(),
258 (subtypeName != null ? subtypeName.toLowerCase() : ""));
259
260 onNetworkToggle(info.isAvailable());
Grace Klobaa34f6862009-07-31 16:28:17 -0700261 }
262 }
263 };
264
Grace Kloba615c6c92009-08-03 10:22:44 -0700265 IntentFilter filter = new IntentFilter(Intent.ACTION_PACKAGE_ADDED);
266 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
267 filter.addDataScheme("package");
268 mPackageInstallationReceiver = new BroadcastReceiver() {
269 @Override
270 public void onReceive(Context context, Intent intent) {
271 final String action = intent.getAction();
272 final String packageName = intent.getData()
273 .getSchemeSpecificPart();
274 final boolean replacing = intent.getBooleanExtra(
275 Intent.EXTRA_REPLACING, false);
276 if (Intent.ACTION_PACKAGE_REMOVED.equals(action) && replacing) {
277 // if it is replacing, refreshPlugins() when adding
278 return;
279 }
Andrei Popescu30995e72010-02-09 16:59:58 +0000280
281 if (sGoogleApps.contains(packageName)) {
282 BrowserActivity.this.packageChanged(packageName,
283 Intent.ACTION_PACKAGE_ADDED.equals(action));
284 }
285
Grace Kloba615c6c92009-08-03 10:22:44 -0700286 PackageManager pm = BrowserActivity.this.getPackageManager();
287 PackageInfo pkgInfo = null;
288 try {
289 pkgInfo = pm.getPackageInfo(packageName,
290 PackageManager.GET_PERMISSIONS);
291 } catch (PackageManager.NameNotFoundException e) {
292 return;
293 }
294 if (pkgInfo != null) {
295 String permissions[] = pkgInfo.requestedPermissions;
296 if (permissions == null) {
297 return;
298 }
299 boolean permissionOk = false;
300 for (String permit : permissions) {
301 if (PluginManager.PLUGIN_PERMISSION.equals(permit)) {
302 permissionOk = true;
303 break;
304 }
305 }
306 if (permissionOk) {
307 PluginManager.getInstance(BrowserActivity.this)
308 .refreshPlugins(
309 Intent.ACTION_PACKAGE_ADDED
310 .equals(action));
311 }
312 }
313 }
314 };
315 registerReceiver(mPackageInstallationReceiver, filter);
316
The Android Open Source Project0c908882009-03-03 19:32:16 -0800317 if (!mTabControl.restoreState(icicle)) {
318 // clear up the thumbnail directory if we can't restore the state as
319 // none of the files in the directory are referenced any more.
320 new ClearThumbnails().execute(
321 mTabControl.getThumbnailDir().listFiles());
Grace Klobaaab3f092009-07-30 12:29:51 -0700322 // there is no quit on Android. But if we can't restore the state,
323 // we can treat it as a new Browser, remove the old session cookies.
324 CookieManager.getInstance().removeSessionCookie();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800325 final Intent intent = getIntent();
326 final Bundle extra = intent.getExtras();
327 // Create an initial tab.
328 // If the intent is ACTION_VIEW and data is not null, the Browser is
329 // invoked to view the content by another application. In this case,
330 // the tab will be close when exit.
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700331 UrlData urlData = getUrlDataFromIntent(intent);
332
Leon Scroggins58d56c62010-01-28 15:12:40 -0500333 String action = intent.getAction();
Grace Kloba22ac16e2009-10-07 18:00:23 -0700334 final Tab t = mTabControl.createNewTab(
Leon Scroggins58d56c62010-01-28 15:12:40 -0500335 (Intent.ACTION_VIEW.equals(action) &&
336 intent.getData() != null)
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -0500337 || RecognizerResultsIntent.ACTION_VOICE_SEARCH_RESULTS
338 .equals(action),
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700339 intent.getStringExtra(Browser.EXTRA_APPLICATION_ID), urlData.mUrl);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800340 mTabControl.setCurrentTab(t);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800341 attachTabToContentView(t);
342 WebView webView = t.getWebView();
343 if (extra != null) {
344 int scale = extra.getInt(Browser.INITIAL_ZOOM_LEVEL, 0);
345 if (scale > 0 && scale <= 1000) {
346 webView.setInitialScale(scale);
347 }
348 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800349
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700350 if (urlData.isEmpty()) {
Shimeng (Simon) Wang98d5fce2010-03-16 13:23:39 -0700351 loadUrl(webView, mSettings.getHomePage());
The Android Open Source Project0c908882009-03-03 19:32:16 -0800352 } else {
Patrick Scott9d53da02010-02-19 10:19:01 -0500353 loadUrlDataIn(t, urlData);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800354 }
355 } else {
356 // TabControl.restoreState() will create a new tab even if
Leon Scroggins1f005d32009-08-10 17:36:42 -0400357 // restoring the state fails.
The Android Open Source Project0c908882009-03-03 19:32:16 -0800358 attachTabToContentView(mTabControl.getCurrentTab());
359 }
Grace Kloba615c6c92009-08-03 10:22:44 -0700360
Cary Clark23cbeb72010-07-01 12:36:56 -0400361 // Delete old thumbnails to save space
362 File dir = mTabControl.getThumbnailDir();
363 if (dir.exists()) {
364 for (String child : dir.list()) {
365 File f = new File(dir, child);
366 f.delete();
367 }
368 }
369
Feng Qianb3c02da2009-06-29 15:58:08 -0700370 // Read JavaScript flags if it exists.
371 String jsFlags = mSettings.getJsFlags();
372 if (jsFlags.trim().length() != 0) {
373 mTabControl.getCurrentWebView().setJsFlags(jsFlags);
374 }
Andrei Popescu30995e72010-02-09 16:59:58 +0000375 // Work out which packages are installed on the system.
376 getInstalledPackages();
Bjorn Bringerta7611812010-03-24 11:12:02 +0000377
378 // Start watching the default geolocation permissions
379 mSystemAllowGeolocationOrigins
380 = new SystemAllowGeolocationOrigins(getApplicationContext());
381 mSystemAllowGeolocationOrigins.start();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800382 }
383
Leon Scroggins58d56c62010-01-28 15:12:40 -0500384 /**
385 * Feed the previously stored results strings to the BrowserProvider so that
386 * the SearchDialog will show them instead of the standard searches.
387 * @param result String to show on the editable line of the SearchDialog.
388 */
389 /* package */ void showVoiceSearchResults(String result) {
390 ContentProviderClient client = mResolver.acquireContentProviderClient(
391 Browser.BOOKMARKS_URI);
392 ContentProvider prov = client.getLocalContentProvider();
393 BrowserProvider bp = (BrowserProvider) prov;
394 bp.setQueryResults(mTabControl.getCurrentTab().getVoiceSearchResults());
395 client.release();
396
Leon Scrogginsfbb3f152010-03-09 17:26:56 -0500397 Bundle bundle = createGoogleSearchSourceBundle(
398 GOOGLE_SEARCH_SOURCE_SEARCHKEY);
399 bundle.putBoolean(SearchManager.CONTEXT_IS_VOICE, true);
400 startSearch(result, false, bundle, false);
Leon Scroggins58d56c62010-01-28 15:12:40 -0500401 }
402
The Android Open Source Project0c908882009-03-03 19:32:16 -0800403 @Override
404 protected void onNewIntent(Intent intent) {
Grace Kloba22ac16e2009-10-07 18:00:23 -0700405 Tab current = mTabControl.getCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800406 // When a tab is closed on exit, the current tab index is set to -1.
407 // Reset before proceed as Browser requires the current tab to be set.
408 if (current == null) {
409 // Try to reset the tab in case the index was incorrect.
410 current = mTabControl.getTab(0);
411 if (current == null) {
412 // No tabs at all so just ignore this intent.
413 return;
414 }
415 mTabControl.setCurrentTab(current);
416 attachTabToContentView(current);
417 resetTitleAndIcon(current.getWebView());
418 }
419 final String action = intent.getAction();
420 final int flags = intent.getFlags();
421 if (Intent.ACTION_MAIN.equals(action) ||
422 (flags & Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY) != 0) {
423 // just resume the browser
424 return;
425 }
Leon Scrogginsb8a844d2010-03-18 15:06:15 -0400426 // In case the SearchDialog is open.
427 ((SearchManager) getSystemService(Context.SEARCH_SERVICE))
428 .stopSearch();
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -0500429 boolean activateVoiceSearch = RecognizerResultsIntent
430 .ACTION_VOICE_SEARCH_RESULTS.equals(action);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800431 if (Intent.ACTION_VIEW.equals(action)
432 || Intent.ACTION_SEARCH.equals(action)
433 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
Leon Scroggins58d56c62010-01-28 15:12:40 -0500434 || Intent.ACTION_WEB_SEARCH.equals(action)
435 || activateVoiceSearch) {
Leon Scroggins3b18ce32010-02-08 17:35:59 -0500436 if (current.isInVoiceSearchMode()) {
437 String title = current.getVoiceDisplayTitle();
438 if (title != null && title.equals(intent.getStringExtra(
439 SearchManager.QUERY))) {
440 // The user submitted the same search as the last voice
441 // search, so do nothing.
442 return;
443 }
Leon Scroggins1fe13a52010-02-09 15:31:26 -0500444 if (Intent.ACTION_SEARCH.equals(action)
445 && current.voiceSearchSourceIsGoogle()) {
446 Intent logIntent = new Intent(
447 LoggingEvents.ACTION_LOG_EVENT);
448 logIntent.putExtra(LoggingEvents.EXTRA_EVENT,
449 LoggingEvents.VoiceSearch.QUERY_UPDATED);
450 logIntent.putExtra(
451 LoggingEvents.VoiceSearch.EXTRA_QUERY_UPDATED_VALUE,
452 intent.getDataString());
453 sendBroadcast(logIntent);
454 // Note, onPageStarted will revert the voice title bar
455 // When http://b/issue?id=2379215 is fixed, we should update
456 // the title bar here.
457 }
Leon Scroggins3b18ce32010-02-08 17:35:59 -0500458 }
Satish Sampath565505b2009-05-29 15:37:27 +0100459 // If this was a search request (e.g. search query directly typed into the address bar),
460 // pass it on to the default web search provider.
461 if (handleWebSearchIntent(intent)) {
462 return;
463 }
464
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700465 UrlData urlData = getUrlDataFromIntent(intent);
466 if (urlData.isEmpty()) {
467 urlData = new UrlData(mSettings.getHomePage());
The Android Open Source Project0c908882009-03-03 19:32:16 -0800468 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700469
Grace Klobacc634032009-07-28 15:58:19 -0700470 final String appId = intent
471 .getStringExtra(Browser.EXTRA_APPLICATION_ID);
Leon Scroggins47208682010-04-07 17:59:48 -0400472 if ((Intent.ACTION_VIEW.equals(action)
473 // If a voice search has no appId, it means that it came
474 // from the browser. In that case, reuse the current tab.
475 || (activateVoiceSearch && appId != null))
Grace Klobacc634032009-07-28 15:58:19 -0700476 && !getPackageName().equals(appId)
477 && (flags & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0) {
Grace Kloba22ac16e2009-10-07 18:00:23 -0700478 Tab appTab = mTabControl.getTabFromId(appId);
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700479 if (appTab != null) {
480 Log.i(LOGTAG, "Reusing tab for " + appId);
481 // Dismiss the subwindow if applicable.
482 dismissSubWindow(appTab);
483 // Since we might kill the WebView, remove it from the
484 // content view first.
485 removeTabFromContentView(appTab);
486 // Recreate the main WebView after destroying the old one.
487 // If the WebView has the same original url and is on that
488 // page, it can be reused.
489 boolean needsLoad =
Leon Scroggins6eac63e2010-03-15 18:19:14 -0400490 mTabControl.recreateWebView(appTab, urlData);
Ben Murdochbff2d602009-07-01 20:19:05 +0100491
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700492 if (current != appTab) {
Leon Scroggins1f005d32009-08-10 17:36:42 -0400493 switchToTab(mTabControl.getTabIndex(appTab));
494 if (needsLoad) {
Patrick Scott9d53da02010-02-19 10:19:01 -0500495 loadUrlDataIn(appTab, urlData);
Leon Scroggins1f005d32009-08-10 17:36:42 -0400496 }
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700497 } else {
Leon Scroggins1f005d32009-08-10 17:36:42 -0400498 // If the tab was the current tab, we have to attach
499 // it to the view system again.
500 attachTabToContentView(appTab);
501 if (needsLoad) {
Patrick Scott9d53da02010-02-19 10:19:01 -0500502 loadUrlDataIn(appTab, urlData);
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700503 }
504 }
505 return;
Patrick Scottcd115892009-07-16 09:42:58 -0400506 } else {
507 // No matching application tab, try to find a regular tab
508 // with a matching url.
509 appTab = mTabControl.findUnusedTabWithUrl(urlData.mUrl);
Leon Scroggins25515f82009-08-19 15:31:58 -0400510 if (appTab != null) {
511 if (current != appTab) {
512 switchToTab(mTabControl.getTabIndex(appTab));
513 }
514 // Otherwise, we are already viewing the correct tab.
Patrick Scottcd115892009-07-16 09:42:58 -0400515 } else {
516 // if FLAG_ACTIVITY_BROUGHT_TO_FRONT flag is on, the url
517 // will be opened in a new tab unless we have reached
518 // MAX_TABS. Then the url will be opened in the current
519 // tab. If a new tab is created, it will have "true" for
520 // exit on close.
Leon Scroggins1f005d32009-08-10 17:36:42 -0400521 openTabAndShow(urlData, true, appId);
Patrick Scottcd115892009-07-16 09:42:58 -0400522 }
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700523 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800524 } else {
Grace Kloba638d3f42009-11-23 10:35:04 -0800525 if (!urlData.isEmpty()
526 && urlData.mUrl.startsWith("about:debug")) {
527 if ("about:debug.dom".equals(urlData.mUrl)) {
528 current.getWebView().dumpDomTree(false);
529 } else if ("about:debug.dom.file".equals(urlData.mUrl)) {
530 current.getWebView().dumpDomTree(true);
531 } else if ("about:debug.render".equals(urlData.mUrl)) {
532 current.getWebView().dumpRenderTree(false);
533 } else if ("about:debug.render.file".equals(urlData.mUrl)) {
534 current.getWebView().dumpRenderTree(true);
535 } else if ("about:debug.display".equals(urlData.mUrl)) {
536 current.getWebView().dumpDisplayTree();
Mike Reed9b78e1d2010-01-13 14:40:52 -0800537 } else if (urlData.mUrl.startsWith("about:debug.drag")) {
538 int index = urlData.mUrl.codePointAt(16) - '0';
539 if (index <= 0 || index > 9) {
540 current.getWebView().setDragTracker(null);
541 } else {
542 current.getWebView().setDragTracker(new MeshTracker(index));
543 }
Grace Kloba638d3f42009-11-23 10:35:04 -0800544 } else {
545 mSettings.toggleDebugSettings();
546 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800547 return;
548 }
Leon Scroggins1f005d32009-08-10 17:36:42 -0400549 // Get rid of the subwindow if it exists
550 dismissSubWindow(current);
Leon Scroggins8588d152010-04-15 11:01:53 -0400551 // If the current Tab is being used as an application tab,
552 // remove the association, since the new Intent means that it is
553 // no longer associated with that application.
554 current.setAppId(null);
Patrick Scott9d53da02010-02-19 10:19:01 -0500555 loadUrlDataIn(current, urlData);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800556 }
557 }
558 }
559
Satish Sampath565505b2009-05-29 15:37:27 +0100560 private int parseUrlShortcut(String url) {
561 if (url == null) return SHORTCUT_INVALID;
562
563 // FIXME: quick search, need to be customized by setting
564 if (url.length() > 2 && url.charAt(1) == ' ') {
565 switch (url.charAt(0)) {
566 case 'g': return SHORTCUT_GOOGLE_SEARCH;
567 case 'w': return SHORTCUT_WIKIPEDIA_SEARCH;
568 case 'd': return SHORTCUT_DICTIONARY_SEARCH;
569 case 'l': return SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH;
570 }
571 }
572 return SHORTCUT_INVALID;
573 }
574
575 /**
576 * Launches the default web search activity with the query parameters if the given intent's data
577 * are identified as plain search terms and not URLs/shortcuts.
578 * @return true if the intent was handled and web search activity was launched, false if not.
579 */
580 private boolean handleWebSearchIntent(Intent intent) {
581 if (intent == null) return false;
582
583 String url = null;
584 final String action = intent.getAction();
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -0500585 if (RecognizerResultsIntent.ACTION_VOICE_SEARCH_RESULTS.equals(
586 action)) {
Leon Scroggins58d56c62010-01-28 15:12:40 -0500587 return false;
588 }
Satish Sampath565505b2009-05-29 15:37:27 +0100589 if (Intent.ACTION_VIEW.equals(action)) {
Grace Kloba1e705052009-09-29 13:13:36 -0700590 Uri data = intent.getData();
591 if (data != null) url = data.toString();
Satish Sampath565505b2009-05-29 15:37:27 +0100592 } else if (Intent.ACTION_SEARCH.equals(action)
593 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
594 || Intent.ACTION_WEB_SEARCH.equals(action)) {
595 url = intent.getStringExtra(SearchManager.QUERY);
596 }
Bjorn Bringert04851702009-09-22 10:36:01 +0100597 return handleWebSearchRequest(url, intent.getBundleExtra(SearchManager.APP_DATA),
598 intent.getStringExtra(SearchManager.EXTRA_DATA_KEY));
Satish Sampath565505b2009-05-29 15:37:27 +0100599 }
600
601 /**
602 * Launches the default web search activity with the query parameters if the given url string
603 * was identified as plain search terms and not URL/shortcut.
604 * @return true if the request was handled and web search activity was launched, false if not.
605 */
Bjorn Bringert04851702009-09-22 10:36:01 +0100606 private boolean handleWebSearchRequest(String inUrl, Bundle appData, String extraData) {
Satish Sampath565505b2009-05-29 15:37:27 +0100607 if (inUrl == null) return false;
608
609 // In general, we shouldn't modify URL from Intent.
610 // But currently, we get the user-typed URL from search box as well.
611 String url = fixUrl(inUrl).trim();
612
613 // URLs and site specific search shortcuts are handled by the regular flow of control, so
614 // return early.
Dan Egnor5ee906c2009-11-18 12:11:49 -0800615 if (Patterns.WEB_URL.matcher(url).matches()
Satish Sampathbc5b9f32009-06-04 18:21:40 +0100616 || ACCEPTED_URI_SCHEMA.matcher(url).matches()
Satish Sampath565505b2009-05-29 15:37:27 +0100617 || parseUrlShortcut(url) != SHORTCUT_INVALID) {
618 return false;
619 }
620
Leon Scroggins8d06e362010-03-24 14:45:57 -0400621 final ContentResolver cr = mResolver;
622 final String newUrl = url;
623 new AsyncTask<Void, Void, Void>() {
624 protected Void doInBackground(Void... unused) {
625 Browser.updateVisitedHistory(cr, newUrl, false);
626 Browser.addSearchUrl(cr, newUrl);
627 return null;
628 }
629 }.execute();
Satish Sampath565505b2009-05-29 15:37:27 +0100630
631 Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);
632 intent.addCategory(Intent.CATEGORY_DEFAULT);
633 intent.putExtra(SearchManager.QUERY, url);
Satish Sampath15e9f2d2009-06-23 22:29:49 +0100634 if (appData != null) {
635 intent.putExtra(SearchManager.APP_DATA, appData);
636 }
Bjorn Bringert04851702009-09-22 10:36:01 +0100637 if (extraData != null) {
638 intent.putExtra(SearchManager.EXTRA_DATA_KEY, extraData);
639 }
Grace Klobacc634032009-07-28 15:58:19 -0700640 intent.putExtra(Browser.EXTRA_APPLICATION_ID, getPackageName());
Satish Sampath565505b2009-05-29 15:37:27 +0100641 startActivity(intent);
642
643 return true;
644 }
645
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700646 private UrlData getUrlDataFromIntent(Intent intent) {
Leon Scroggins58d56c62010-01-28 15:12:40 -0500647 String url = "";
Grace Kloba068e48b2010-01-26 18:11:27 -0800648 Map<String, String> headers = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800649 if (intent != null) {
650 final String action = intent.getAction();
651 if (Intent.ACTION_VIEW.equals(action)) {
652 url = smartUrlFilter(intent.getData());
653 if (url != null && url.startsWith("content:")) {
654 /* Append mimetype so webview knows how to display */
655 String mimeType = intent.resolveType(getContentResolver());
656 if (mimeType != null) {
657 url += "?" + mimeType;
658 }
659 }
Grace Kloba068e48b2010-01-26 18:11:27 -0800660 if (url != null && url.startsWith("http")) {
Grace Kloba00f54c52010-01-27 14:53:51 -0800661 final Bundle pairs = intent
662 .getBundleExtra(Browser.EXTRA_HEADERS);
Grace Kloba2d508ed2010-01-28 11:39:15 -0800663 if (pairs != null && !pairs.isEmpty()) {
Grace Kloba00f54c52010-01-27 14:53:51 -0800664 Iterator<String> iter = pairs.keySet().iterator();
Grace Kloba068e48b2010-01-26 18:11:27 -0800665 headers = new HashMap<String, String>();
Grace Kloba00f54c52010-01-27 14:53:51 -0800666 while (iter.hasNext()) {
667 String key = iter.next();
668 headers.put(key, pairs.getString(key));
Grace Kloba068e48b2010-01-26 18:11:27 -0800669 }
670 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700671 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800672 } else if (Intent.ACTION_SEARCH.equals(action)
673 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
674 || Intent.ACTION_WEB_SEARCH.equals(action)) {
675 url = intent.getStringExtra(SearchManager.QUERY);
676 if (url != null) {
677 mLastEnteredUrl = url;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800678 // In general, we shouldn't modify URL from Intent.
679 // But currently, we get the user-typed URL from search box as well.
680 url = fixUrl(url);
681 url = smartUrlFilter(url);
Leon Scroggins8d06e362010-03-24 14:45:57 -0400682 final ContentResolver cr = mResolver;
683 final String newUrl = url;
684 new AsyncTask<Void, Void, Void>() {
685 protected Void doInBackground(Void... unused) {
686 Browser.updateVisitedHistory(cr, newUrl, false);
687 return null;
688 }
689 }.execute();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800690 String searchSource = "&source=android-" + GOOGLE_SEARCH_SOURCE_SUGGEST + "&";
691 if (url.contains(searchSource)) {
692 String source = null;
693 final Bundle appData = intent.getBundleExtra(SearchManager.APP_DATA);
694 if (appData != null) {
Bjorn Bringert10d1cca2010-02-10 14:22:12 +0000695 source = appData.getString(Search.SOURCE);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800696 }
697 if (TextUtils.isEmpty(source)) {
698 source = GOOGLE_SEARCH_SOURCE_UNKNOWN;
699 }
700 url = url.replace(searchSource, "&source=android-"+source+"&");
701 }
702 }
703 }
704 }
Leon Scroggins58d56c62010-01-28 15:12:40 -0500705 return new UrlData(url, headers, intent);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800706 }
Leon Scroggins58d56c62010-01-28 15:12:40 -0500707 /* package */ void showVoiceTitleBar(String title) {
708 mTitleBar.setInVoiceMode(true);
709 mFakeTitleBar.setInVoiceMode(true);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800710
Leon Scroggins58d56c62010-01-28 15:12:40 -0500711 mTitleBar.setDisplayTitle(title);
712 mFakeTitleBar.setDisplayTitle(title);
713 }
714 /* package */ void revertVoiceTitleBar() {
715 mTitleBar.setInVoiceMode(false);
716 mFakeTitleBar.setInVoiceMode(false);
717
Leon Scroggins003a5dd2010-03-10 12:13:14 -0500718 mTitleBar.setDisplayTitle(mUrl);
719 mFakeTitleBar.setDisplayTitle(mUrl);
Leon Scroggins58d56c62010-01-28 15:12:40 -0500720 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800721 /* package */ static String fixUrl(String inUrl) {
Cary Clark652ff872009-09-10 13:34:44 -0400722 // FIXME: Converting the url to lower case
723 // duplicates functionality in smartUrlFilter().
724 // However, changing all current callers of fixUrl to
725 // call smartUrlFilter in addition may have unwanted
726 // consequences, and is deferred for now.
727 int colon = inUrl.indexOf(':');
728 boolean allLower = true;
729 for (int index = 0; index < colon; index++) {
730 char ch = inUrl.charAt(index);
731 if (!Character.isLetter(ch)) {
732 break;
733 }
734 allLower &= Character.isLowerCase(ch);
735 if (index == colon - 1 && !allLower) {
736 inUrl = inUrl.substring(0, colon).toLowerCase()
737 + inUrl.substring(colon);
738 }
739 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800740 if (inUrl.startsWith("http://") || inUrl.startsWith("https://"))
741 return inUrl;
742 if (inUrl.startsWith("http:") ||
743 inUrl.startsWith("https:")) {
744 if (inUrl.startsWith("http:/") || inUrl.startsWith("https:/")) {
745 inUrl = inUrl.replaceFirst("/", "//");
746 } else inUrl = inUrl.replaceFirst(":", "://");
747 }
748 return inUrl;
749 }
750
Grace Kloba22ac16e2009-10-07 18:00:23 -0700751 @Override
752 protected void onResume() {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800753 super.onResume();
Dave Bort31a6d1c2009-04-13 15:56:49 -0700754 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800755 Log.v(LOGTAG, "BrowserActivity.onResume: this=" + this);
756 }
757
758 if (!mActivityInPause) {
759 Log.e(LOGTAG, "BrowserActivity is already resumed.");
760 return;
761 }
762
Mike Reed7bfa63b2009-05-28 11:08:32 -0400763 mTabControl.resumeCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800764 mActivityInPause = false;
Mike Reed7bfa63b2009-05-28 11:08:32 -0400765 resumeWebViewTimers();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800766
767 if (mWakeLock.isHeld()) {
768 mHandler.removeMessages(RELEASE_WAKELOCK);
769 mWakeLock.release();
770 }
771
The Android Open Source Project0c908882009-03-03 19:32:16 -0800772 registerReceiver(mNetworkStateIntentReceiver,
773 mNetworkStateChangedFilter);
774 WebView.enablePlatformNotifications();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800775 }
776
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400777 /**
778 * Since the actual title bar is embedded in the WebView, and removing it
Leon Scrogginsfe87bd32009-10-06 10:10:00 -0400779 * would change its appearance, use a different TitleBar to show overlayed
780 * at the top of the screen, when the menu is open or the page is loading.
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400781 */
782 private TitleBar mFakeTitleBar;
783
784 /**
785 * Keeps track of whether the options menu is open. This is important in
786 * determining whether to show or hide the title bar overlay.
787 */
788 private boolean mOptionsMenuOpen;
789
790 /**
791 * Only meaningful when mOptionsMenuOpen is true. This variable keeps track
792 * of whether the configuration has changed. The first onMenuOpened call
793 * after a configuration change is simply a reopening of the same menu
794 * (i.e. mIconView did not change).
795 */
796 private boolean mConfigChanged;
797
798 /**
799 * Whether or not the options menu is in its smaller, icon menu form. When
800 * true, we want the title bar overlay to be up. When false, we do not.
801 * Only meaningful if mOptionsMenuOpen is true.
802 */
803 private boolean mIconView;
804
Leon Scrogginsa81a7642009-08-31 17:05:41 -0400805 @Override
806 public boolean onMenuOpened(int featureId, Menu menu) {
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400807 if (Window.FEATURE_OPTIONS_PANEL == featureId) {
808 if (mOptionsMenuOpen) {
809 if (mConfigChanged) {
810 // We do not need to make any changes to the state of the
811 // title bar, since the only thing that happened was a
812 // change in orientation
813 mConfigChanged = false;
814 } else {
815 if (mIconView) {
816 // Switching the menu to expanded view, so hide the
817 // title bar.
818 hideFakeTitleBar();
819 mIconView = false;
820 } else {
821 // Switching the menu back to icon view, so show the
822 // title bar once again.
823 showFakeTitleBar();
824 mIconView = true;
825 }
826 }
827 } else {
828 // The options menu is closed, so open it, and show the title
829 showFakeTitleBar();
830 mOptionsMenuOpen = true;
831 mConfigChanged = false;
832 mIconView = true;
833 }
834 }
Leon Scrogginsa81a7642009-08-31 17:05:41 -0400835 return true;
836 }
837
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400838 private void showFakeTitleBar() {
Leon Scrogginsfe87bd32009-10-06 10:10:00 -0400839 if (mFakeTitleBar.getParent() == null && mActiveTabsPage == null
Grace Kloba847c25b2010-03-30 16:00:26 -0700840 && !mActivityInPause) {
841 WebView mainView = mTabControl.getCurrentWebView();
842 // if there is no current WebView, don't show the faked title bar;
Grace Kloba65190702010-04-02 23:37:26 -0700843 if (mainView == null) {
Cary Clarka0464552009-09-29 13:00:45 -0400844 return;
845 }
Cary Clark2c326e62010-08-19 18:40:57 -0400846 // Do not need to check for null, since the current tab will have
847 // at least a main WebView, or we would have returned above.
848 if (dialogIsUp()) {
849 // Do not show the fake title bar, which would cover up the
850 // find or select dialog.
851 return;
852 }
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400853
854 WindowManager manager
855 = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
856
857 // Add the title bar to the window manager so it can receive touches
858 // while the menu is up
859 WindowManager.LayoutParams params
860 = new WindowManager.LayoutParams(
Romain Guy15b8ec62010-01-08 15:06:43 -0800861 ViewGroup.LayoutParams.MATCH_PARENT,
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400862 ViewGroup.LayoutParams.WRAP_CONTENT,
Grace Kloba847c25b2010-03-30 16:00:26 -0700863 WindowManager.LayoutParams.TYPE_APPLICATION,
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400864 WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
Leon Scroggins68549862009-09-21 16:02:01 -0400865 PixelFormat.TRANSLUCENT);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400866 params.gravity = Gravity.TOP;
Grace Kloba847c25b2010-03-30 16:00:26 -0700867 boolean atTop = mainView.getScrollY() == 0;
Leon Scroggins83932c72009-09-30 11:55:54 -0400868 params.windowAnimations = atTop ? 0 : R.style.TitleBar;
Grace Kloba13f9ace2010-03-18 21:44:14 -0700869 manager.addView(mFakeTitleBar, params);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400870 }
871 }
872
873 @Override
874 public void onOptionsMenuClosed(Menu menu) {
875 mOptionsMenuOpen = false;
Leon Scrogginsa27ff192009-09-14 12:58:04 -0400876 if (!mInLoad) {
877 hideFakeTitleBar();
878 } else if (!mIconView) {
879 // The page is currently loading, and we are in expanded mode, so
880 // we were not showing the menu. Show it once again. It will be
881 // removed when the page finishes.
882 showFakeTitleBar();
883 }
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400884 }
Grace Kloba22ac16e2009-10-07 18:00:23 -0700885
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400886 private void hideFakeTitleBar() {
Leon Scrogginsfe87bd32009-10-06 10:10:00 -0400887 if (mFakeTitleBar.getParent() == null) return;
Leon Scroggins20329572009-09-23 17:42:41 -0400888 WindowManager.LayoutParams params = (WindowManager.LayoutParams)
Grace Kloba13f9ace2010-03-18 21:44:14 -0700889 mFakeTitleBar.getLayoutParams();
Leon Scroggins20329572009-09-23 17:42:41 -0400890 WebView mainView = mTabControl.getCurrentWebView();
891 // Although we decided whether or not to animate based on the current
892 // scroll position, the scroll position may have changed since the
893 // fake title bar was displayed. Make sure it has the appropriate
894 // animation/lack thereof before removing.
895 params.windowAnimations = mainView != null && mainView.getScrollY() == 0
Leon Scroggins83932c72009-09-30 11:55:54 -0400896 ? 0 : R.style.TitleBar;
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400897 WindowManager manager
898 = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
Grace Kloba13f9ace2010-03-18 21:44:14 -0700899 manager.updateViewLayout(mFakeTitleBar, params);
900 manager.removeView(mFakeTitleBar);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400901 }
902
The Android Open Source Project0c908882009-03-03 19:32:16 -0800903 /**
Leon Scrogginsc6fa1102009-09-21 10:40:01 -0400904 * Special method for the fake title bar to call when displaying its context
905 * menu, since it is in its own Window, and its parent does not show a
906 * context menu.
907 */
908 /* package */ void showTitleBarContextMenu() {
Cary Clark65f4a3c2009-09-28 17:05:06 -0400909 if (null == mTitleBar.getParent()) {
910 return;
911 }
Leon Scrogginsc6fa1102009-09-21 10:40:01 -0400912 openContextMenu(mTitleBar);
913 }
914
Leon Scrogginsb2b19f52009-10-09 16:10:00 -0400915 @Override
916 public void onContextMenuClosed(Menu menu) {
917 super.onContextMenuClosed(menu);
918 if (mInLoad) {
919 showFakeTitleBar();
920 }
921 }
922
Leon Scrogginsc6fa1102009-09-21 10:40:01 -0400923 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -0800924 * onSaveInstanceState(Bundle map)
925 * onSaveInstanceState is called right before onStop(). The map contains
926 * the saved state.
927 */
Grace Kloba22ac16e2009-10-07 18:00:23 -0700928 @Override
929 protected void onSaveInstanceState(Bundle outState) {
Dave Bort31a6d1c2009-04-13 15:56:49 -0700930 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800931 Log.v(LOGTAG, "BrowserActivity.onSaveInstanceState: this=" + this);
932 }
933 // the default implementation requires each view to have an id. As the
934 // browser handles the state itself and it doesn't use id for the views,
935 // don't call the default implementation. Otherwise it will trigger the
936 // warning like this, "couldn't save which view has focus because the
937 // focused view XXX has no id".
938
939 // Save all the tabs
940 mTabControl.saveState(outState);
941 }
942
Grace Kloba22ac16e2009-10-07 18:00:23 -0700943 @Override
944 protected void onPause() {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800945 super.onPause();
946
947 if (mActivityInPause) {
948 Log.e(LOGTAG, "BrowserActivity is already paused.");
949 return;
950 }
951
Mike Reed7bfa63b2009-05-28 11:08:32 -0400952 mTabControl.pauseCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800953 mActivityInPause = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -0400954 if (mTabControl.getCurrentIndex() >= 0 && !pauseWebViewTimers()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800955 mWakeLock.acquire();
956 mHandler.sendMessageDelayed(mHandler
957 .obtainMessage(RELEASE_WAKELOCK), WAKELOCK_TIMEOUT);
958 }
959
Leon Scrogginsa2ab6a72009-09-11 11:49:52 -0400960 // FIXME: This removes the active tabs page and resets the menu to
961 // MAIN_MENU. A better solution might be to do this work in onNewIntent
962 // but then we would need to save it in onSaveInstanceState and restore
963 // it in onCreate/onRestoreInstanceState
964 if (mActiveTabsPage != null) {
965 removeActiveTabPage(true);
966 }
967
The Android Open Source Project0c908882009-03-03 19:32:16 -0800968 cancelStopToast();
969
970 // unregister network state listener
971 unregisterReceiver(mNetworkStateIntentReceiver);
972 WebView.disablePlatformNotifications();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800973 }
974
Grace Kloba22ac16e2009-10-07 18:00:23 -0700975 @Override
976 protected void onDestroy() {
Dave Bort31a6d1c2009-04-13 15:56:49 -0700977 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800978 Log.v(LOGTAG, "BrowserActivity.onDestroy: this=" + this);
979 }
980 super.onDestroy();
Grace Kloba0923d692009-09-23 21:37:25 -0700981
Leon Scroggins8d5fa432009-10-02 15:55:59 -0400982 if (mUploadMessage != null) {
983 mUploadMessage.onReceiveValue(null);
984 mUploadMessage = null;
985 }
986
Grace Kloba0923d692009-09-23 21:37:25 -0700987 if (mTabControl == null) return;
988
Grace Kloba1fc98a32009-10-21 13:23:08 -0700989 // Remove the fake title bar if it is there
990 hideFakeTitleBar();
991
The Android Open Source Project0c908882009-03-03 19:32:16 -0800992 // Remove the current tab and sub window
Grace Kloba22ac16e2009-10-07 18:00:23 -0700993 Tab t = mTabControl.getCurrentTab();
Patrick Scottfb5e77f2009-04-08 19:17:37 -0700994 if (t != null) {
995 dismissSubWindow(t);
996 removeTabFromContentView(t);
997 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800998 // Destroy all the tabs
999 mTabControl.destroy();
1000 WebIconDatabase.getInstance().close();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001001
Grace Klobab4da0ad2009-05-14 14:45:40 -07001002 unregisterReceiver(mPackageInstallationReceiver);
Bjorn Bringerta7611812010-03-24 11:12:02 +00001003
1004 // Stop watching the default geolocation permissions
1005 mSystemAllowGeolocationOrigins.stop();
1006 mSystemAllowGeolocationOrigins = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001007 }
1008
1009 @Override
1010 public void onConfigurationChanged(Configuration newConfig) {
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04001011 mConfigChanged = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001012 super.onConfigurationChanged(newConfig);
1013
1014 if (mPageInfoDialog != null) {
1015 mPageInfoDialog.dismiss();
1016 showPageInfo(
1017 mPageInfoView,
Leon Scrogginsc7b92f82010-01-11 18:17:31 -05001018 mPageInfoFromShowSSLCertificateOnError);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001019 }
1020 if (mSSLCertificateDialog != null) {
1021 mSSLCertificateDialog.dismiss();
1022 showSSLCertificate(
1023 mSSLCertificateView);
1024 }
1025 if (mSSLCertificateOnErrorDialog != null) {
1026 mSSLCertificateOnErrorDialog.dismiss();
1027 showSSLCertificateOnError(
1028 mSSLCertificateOnErrorView,
1029 mSSLCertificateOnErrorHandler,
1030 mSSLCertificateOnErrorError);
1031 }
1032 if (mHttpAuthenticationDialog != null) {
1033 String title = ((TextView) mHttpAuthenticationDialog
1034 .findViewById(com.android.internal.R.id.alertTitle)).getText()
1035 .toString();
1036 String name = ((TextView) mHttpAuthenticationDialog
1037 .findViewById(R.id.username_edit)).getText().toString();
1038 String password = ((TextView) mHttpAuthenticationDialog
1039 .findViewById(R.id.password_edit)).getText().toString();
1040 int focusId = mHttpAuthenticationDialog.getCurrentFocus()
1041 .getId();
1042 mHttpAuthenticationDialog.dismiss();
1043 showHttpAuthentication(mHttpAuthHandler, null, null, title,
1044 name, password, focusId);
1045 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001046 }
1047
Grace Kloba22ac16e2009-10-07 18:00:23 -07001048 @Override
1049 public void onLowMemory() {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001050 super.onLowMemory();
1051 mTabControl.freeMemory();
1052 }
1053
Cary Clarkff4d92c2010-03-25 11:17:03 -04001054 private void resumeWebViewTimers() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001055 Tab tab = mTabControl.getCurrentTab();
Cary Clarkff4d92c2010-03-25 11:17:03 -04001056 if (tab == null) return; // monkey can trigger this
Grace Kloba22ac16e2009-10-07 18:00:23 -07001057 boolean inLoad = tab.inLoad();
1058 if ((!mActivityInPause && !inLoad) || (mActivityInPause && inLoad)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001059 CookieSyncManager.getInstance().startSync();
Grace Kloba22ac16e2009-10-07 18:00:23 -07001060 WebView w = tab.getWebView();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001061 if (w != null) {
1062 w.resumeTimers();
1063 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001064 }
1065 }
1066
Mike Reed7bfa63b2009-05-28 11:08:32 -04001067 private boolean pauseWebViewTimers() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001068 Tab tab = mTabControl.getCurrentTab();
1069 boolean inLoad = tab.inLoad();
1070 if (mActivityInPause && !inLoad) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001071 CookieSyncManager.getInstance().stopSync();
1072 WebView w = mTabControl.getCurrentWebView();
1073 if (w != null) {
1074 w.pauseTimers();
1075 }
1076 return true;
1077 } else {
1078 return false;
1079 }
1080 }
1081
The Android Open Source Project0c908882009-03-03 19:32:16 -08001082 // Open the icon database and retain all the icons for visited sites.
1083 private void retainIconsOnStartup() {
1084 final WebIconDatabase db = WebIconDatabase.getInstance();
1085 db.open(getDir("icons", 0).getPath());
Leon Scroggins2c0f6112010-03-12 18:09:39 -05001086 Cursor c = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001087 try {
Leon Scroggins2c0f6112010-03-12 18:09:39 -05001088 c = Browser.getAllBookmarks(mResolver);
1089 if (c.moveToFirst()) {
1090 int urlIndex = c.getColumnIndex(Browser.BookmarkColumns.URL);
1091 do {
1092 String url = c.getString(urlIndex);
1093 db.retainIconForPageUrl(url);
1094 } while (c.moveToNext());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001095 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001096 } catch (IllegalStateException e) {
1097 Log.e(LOGTAG, "retainIconsOnStartup", e);
Leon Scroggins2c0f6112010-03-12 18:09:39 -05001098 } finally {
1099 if (c!= null) c.close();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001100 }
1101 }
1102
1103 // Helper method for getting the top window.
1104 WebView getTopWindow() {
1105 return mTabControl.getCurrentTopWebView();
1106 }
1107
Grace Kloba22ac16e2009-10-07 18:00:23 -07001108 TabControl getTabControl() {
1109 return mTabControl;
1110 }
1111
The Android Open Source Project0c908882009-03-03 19:32:16 -08001112 @Override
1113 public boolean onCreateOptionsMenu(Menu menu) {
1114 super.onCreateOptionsMenu(menu);
1115
1116 MenuInflater inflater = getMenuInflater();
1117 inflater.inflate(R.menu.browser, menu);
1118 mMenu = menu;
1119 updateInLoadMenuItems();
1120 return true;
1121 }
1122
1123 /**
1124 * As the menu can be open when loading state changes
1125 * we must manually update the state of the stop/reload menu
1126 * item
1127 */
1128 private void updateInLoadMenuItems() {
1129 if (mMenu == null) {
1130 return;
1131 }
1132 MenuItem src = mInLoad ?
1133 mMenu.findItem(R.id.stop_menu_id):
1134 mMenu.findItem(R.id.reload_menu_id);
1135 MenuItem dest = mMenu.findItem(R.id.stop_reload_menu_id);
1136 dest.setIcon(src.getIcon());
1137 dest.setTitle(src.getTitle());
1138 }
1139
1140 @Override
1141 public boolean onContextItemSelected(MenuItem item) {
1142 // chording is not an issue with context menus, but we use the same
1143 // options selector, so set mCanChord to true so we can access them.
1144 mCanChord = true;
1145 int id = item.getItemId();
Leon Scroggins96afcb12009-12-10 12:35:56 -05001146 boolean result = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001147 switch (id) {
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001148 // For the context menu from the title bar
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001149 case R.id.title_bar_copy_page_url:
Leon Scroggins96afcb12009-12-10 12:35:56 -05001150 Tab currentTab = mTabControl.getCurrentTab();
1151 if (null == currentTab) {
1152 result = false;
1153 break;
1154 }
1155 WebView mainView = currentTab.getWebView();
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001156 if (null == mainView) {
Leon Scroggins96afcb12009-12-10 12:35:56 -05001157 result = false;
1158 break;
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001159 }
Leon Scroggins96afcb12009-12-10 12:35:56 -05001160 copy(mainView.getUrl());
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001161 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001162 // -- Browser context menu
1163 case R.id.open_context_menu_id:
1164 case R.id.open_newtab_context_menu_id:
1165 case R.id.bookmark_context_menu_id:
1166 case R.id.save_link_context_menu_id:
1167 case R.id.share_link_context_menu_id:
1168 case R.id.copy_link_context_menu_id:
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001169 final WebView webView = getTopWindow();
1170 if (null == webView) {
Leon Scroggins96afcb12009-12-10 12:35:56 -05001171 result = false;
1172 break;
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001173 }
1174 final HashMap hrefMap = new HashMap();
1175 hrefMap.put("webview", webView);
1176 final Message msg = mHandler.obtainMessage(
1177 FOCUS_NODE_HREF, id, 0, hrefMap);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001178 webView.requestFocusNodeHref(msg);
1179 break;
1180
1181 default:
1182 // For other context menus
Leon Scroggins96afcb12009-12-10 12:35:56 -05001183 result = onOptionsItemSelected(item);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001184 }
1185 mCanChord = false;
Leon Scroggins96afcb12009-12-10 12:35:56 -05001186 return result;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001187 }
1188
1189 private Bundle createGoogleSearchSourceBundle(String source) {
1190 Bundle bundle = new Bundle();
Bjorn Bringert10d1cca2010-02-10 14:22:12 +00001191 bundle.putString(Search.SOURCE, source);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001192 return bundle;
1193 }
1194
Leon Scroggins8ad29922010-02-16 12:33:55 -05001195 /* package */ void editUrl() {
Leon Scroggins68579392009-09-15 15:31:54 -04001196 if (mOptionsMenuOpen) closeOptionsMenu();
Leon Scroggins5bbe9802009-07-31 13:10:55 -04001197 String url = (getTopWindow() == null) ? null : getTopWindow().getUrl();
Grace Kloba83f47342009-07-20 10:44:31 -07001198 startSearch(mSettings.getHomePage().equals(url) ? null : url, true,
Leon Scroggins8ad29922010-02-16 12:33:55 -05001199 null, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001200 }
1201
Leon Scroggins8ad29922010-02-16 12:33:55 -05001202 /**
1203 * Overriding this to insert a local information bundle
1204 */
The Android Open Source Project0c908882009-03-03 19:32:16 -08001205 @Override
1206 public void startSearch(String initialQuery, boolean selectInitialQuery,
1207 Bundle appSearchData, boolean globalSearch) {
1208 if (appSearchData == null) {
1209 appSearchData = createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_TYPE);
1210 }
1211 super.startSearch(initialQuery, selectInitialQuery, appSearchData, globalSearch);
1212 }
1213
Leon Scroggins1f005d32009-08-10 17:36:42 -04001214 /**
1215 * Switch tabs. Called by the TitleBarSet when sliding the title bar
1216 * results in changing tabs.
Leon Scroggins160a7e72009-08-14 18:28:01 -04001217 * @param index Index of the tab to change to, as defined by
1218 * mTabControl.getTabIndex(Tab t).
1219 * @return boolean True if we successfully switched to a different tab. If
1220 * the indexth tab is null, or if that tab is the same as
1221 * the current one, return false.
Leon Scroggins1f005d32009-08-10 17:36:42 -04001222 */
Leon Scroggins160a7e72009-08-14 18:28:01 -04001223 /* package */ boolean switchToTab(int index) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001224 Tab tab = mTabControl.getTab(index);
1225 Tab currentTab = mTabControl.getCurrentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04001226 if (tab == null || tab == currentTab) {
Leon Scroggins160a7e72009-08-14 18:28:01 -04001227 return false;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001228 }
1229 if (currentTab != null) {
1230 // currentTab may be null if it was just removed. In that case,
1231 // we do not need to remove it
1232 removeTabFromContentView(currentTab);
1233 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001234 mTabControl.setCurrentTab(tab);
1235 attachTabToContentView(tab);
Grace Klobaeb6eef42009-09-15 17:56:32 -07001236 resetTitleIconAndProgress();
1237 updateLockIconToLatest();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001238 return true;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001239 }
1240
Grace Kloba22ac16e2009-10-07 18:00:23 -07001241 /* package */ Tab openTabToHomePage() {
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001242 return openTabAndShow(mSettings.getHomePage(), false, null);
1243 }
1244
Leon Scroggins1f005d32009-08-10 17:36:42 -04001245 /* package */ void closeCurrentWindow() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001246 final Tab current = mTabControl.getCurrentTab();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001247 if (mTabControl.getTabCount() == 1) {
Leon Scroggins30444232009-09-04 18:36:20 -04001248 // This is the last tab. Open a new one, with the home
1249 // page and close the current one.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001250 openTabToHomePage();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001251 closeTab(current);
Leon Scroggins160a7e72009-08-14 18:28:01 -04001252 return;
1253 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07001254 final Tab parent = current.getParentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04001255 int indexToShow = -1;
1256 if (parent != null) {
1257 indexToShow = mTabControl.getTabIndex(parent);
1258 } else {
Leon Scroggins160a7e72009-08-14 18:28:01 -04001259 final int currentIndex = mTabControl.getCurrentIndex();
1260 // Try to move to the tab to the right
1261 indexToShow = currentIndex + 1;
1262 if (indexToShow > mTabControl.getTabCount() - 1) {
1263 // Try to move to the tab to the left
1264 indexToShow = currentIndex - 1;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001265 }
1266 }
Leon Scroggins160a7e72009-08-14 18:28:01 -04001267 if (switchToTab(indexToShow)) {
1268 // Close window
1269 closeTab(current);
1270 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001271 }
1272
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001273 private ActiveTabsPage mActiveTabsPage;
1274
1275 /**
1276 * Remove the active tabs page.
1277 * @param needToAttach If true, the active tabs page did not attach a tab
1278 * to the content view, so we need to do that here.
1279 */
1280 /* package */ void removeActiveTabPage(boolean needToAttach) {
1281 mContentView.removeView(mActiveTabsPage);
1282 mActiveTabsPage = null;
1283 mMenuState = R.id.MAIN_MENU;
1284 if (needToAttach) {
1285 attachTabToContentView(mTabControl.getCurrentTab());
1286 }
1287 getTopWindow().requestFocus();
1288 }
1289
Cary Clark2c326e62010-08-19 18:40:57 -04001290 private WebView showDialog(WebDialog dialog) {
1291 // Need to do something special for Tablet
1292 Tab tab = mTabControl.getCurrentTab();
1293 if (tab.getSubWebView() == null) {
1294 // If the find or select is being performed on the main webview,
1295 // remove the embedded title bar.
1296 WebView mainView = tab.getWebView();
1297 if (mainView != null) {
1298 mainView.setEmbeddedTitleBar(null);
1299 }
1300 }
1301 hideFakeTitleBar();
1302 mMenuState = EMPTY_MENU;
1303 return tab.showDialog(dialog);
1304 }
1305
The Android Open Source Project0c908882009-03-03 19:32:16 -08001306 @Override
1307 public boolean onOptionsItemSelected(MenuItem item) {
1308 if (!mCanChord) {
1309 // The user has already fired a shortcut with this hold down of the
1310 // menu key.
1311 return false;
1312 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001313 if (null == getTopWindow()) {
Leon Scroggins0d7ae0e2009-06-05 11:04:45 -04001314 return false;
1315 }
Grace Kloba6ee9c492009-07-13 10:04:34 -07001316 if (mMenuIsDown) {
1317 // The shortcut action consumes the MENU. Even if it is still down,
1318 // it won't trigger the next shortcut action. In the case of the
1319 // shortcut action triggering a new activity, like Bookmarks, we
1320 // won't get onKeyUp for MENU. So it is important to reset it here.
1321 mMenuIsDown = false;
1322 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001323 switch (item.getItemId()) {
1324 // -- Main menu
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001325 case R.id.new_tab_menu_id:
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001326 openTabToHomePage();
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001327 break;
1328
Leon Scroggins64b80f32009-08-07 12:03:34 -04001329 case R.id.goto_menu_id:
Leon Scroggins8ad29922010-02-16 12:33:55 -05001330 editUrl();
Leon Scrogginsb3a5bed2009-09-28 11:21:56 -04001331 break;
1332
1333 case R.id.bookmarks_menu_id:
Leon Scroggins30444232009-09-04 18:36:20 -04001334 bookmarksOrHistoryPicker(false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001335 break;
1336
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001337 case R.id.active_tabs_menu_id:
1338 mActiveTabsPage = new ActiveTabsPage(this, mTabControl);
1339 removeTabFromContentView(mTabControl.getCurrentTab());
Leon Scroggins43de6162009-09-14 19:59:58 -04001340 hideFakeTitleBar();
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001341 mContentView.addView(mActiveTabsPage, COVER_SCREEN_PARAMS);
1342 mActiveTabsPage.requestFocus();
1343 mMenuState = EMPTY_MENU;
1344 break;
1345
Leon Scroggins1f005d32009-08-10 17:36:42 -04001346 case R.id.add_bookmark_menu_id:
1347 Intent i = new Intent(BrowserActivity.this,
1348 AddBookmarkPage.class);
1349 WebView w = getTopWindow();
1350 i.putExtra("url", w.getUrl());
1351 i.putExtra("title", w.getTitle());
Grace Kloba83cdb2c2009-09-16 00:48:57 -07001352 i.putExtra("touch_icon_url", w.getTouchIconUrl());
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01001353 i.putExtra("thumbnail", createScreenshot(w));
Leon Scroggins1f005d32009-08-10 17:36:42 -04001354 startActivity(i);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001355 break;
1356
1357 case R.id.stop_reload_menu_id:
1358 if (mInLoad) {
1359 stopLoading();
1360 } else {
1361 getTopWindow().reload();
1362 }
1363 break;
1364
1365 case R.id.back_menu_id:
1366 getTopWindow().goBack();
1367 break;
1368
1369 case R.id.forward_menu_id:
1370 getTopWindow().goForward();
1371 break;
1372
1373 case R.id.close_menu_id:
1374 // Close the subwindow if it exists.
1375 if (mTabControl.getCurrentSubWindow() != null) {
1376 dismissSubWindow(mTabControl.getCurrentTab());
1377 break;
1378 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001379 closeCurrentWindow();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001380 break;
1381
1382 case R.id.homepage_menu_id:
Grace Kloba22ac16e2009-10-07 18:00:23 -07001383 Tab current = mTabControl.getCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001384 if (current != null) {
1385 dismissSubWindow(current);
Leon Scroggins92472e82010-02-17 16:32:28 -05001386 loadUrl(current.getWebView(), mSettings.getHomePage());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001387 }
1388 break;
1389
1390 case R.id.preferences_menu_id:
1391 Intent intent = new Intent(this,
1392 BrowserPreferencesPage.class);
Leon Scrogginsd5304942009-12-10 16:11:39 -05001393 intent.putExtra(BrowserPreferencesPage.CURRENT_PAGE,
1394 getTopWindow().getUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001395 startActivityForResult(intent, PREFERENCES_PAGE);
1396 break;
1397
1398 case R.id.find_menu_id:
Cary Clark2c326e62010-08-19 18:40:57 -04001399 showFindDialog();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001400 break;
1401
1402 case R.id.select_text_id:
Cary Clark2c326e62010-08-19 18:40:57 -04001403 showSelectDialog();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001404 break;
Cary Clark2c326e62010-08-19 18:40:57 -04001405
The Android Open Source Project0c908882009-03-03 19:32:16 -08001406 case R.id.page_info_menu_id:
1407 showPageInfo(mTabControl.getCurrentTab(), false);
1408 break;
1409
1410 case R.id.classic_history_menu_id:
Leon Scroggins30444232009-09-04 18:36:20 -04001411 bookmarksOrHistoryPicker(true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001412 break;
1413
Leon Scroggins96afcb12009-12-10 12:35:56 -05001414 case R.id.title_bar_share_page_url:
The Android Open Source Project0c908882009-03-03 19:32:16 -08001415 case R.id.share_page_menu_id:
Leon Scroggins96afcb12009-12-10 12:35:56 -05001416 Tab currentTab = mTabControl.getCurrentTab();
1417 if (null == currentTab) {
1418 mCanChord = false;
1419 return false;
1420 }
1421 currentTab.populatePickerData();
1422 sharePage(this, currentTab.getTitle(),
1423 currentTab.getUrl(), currentTab.getFavicon(),
1424 createScreenshot(currentTab.getWebView()));
The Android Open Source Project0c908882009-03-03 19:32:16 -08001425 break;
1426
1427 case R.id.dump_nav_menu_id:
1428 getTopWindow().debugDump();
1429 break;
1430
Andrei Popescu7a8b88b2010-02-02 00:30:38 +00001431 case R.id.dump_counters_menu_id:
1432 getTopWindow().dumpV8Counters();
1433 break;
1434
The Android Open Source Project0c908882009-03-03 19:32:16 -08001435 case R.id.zoom_in_menu_id:
1436 getTopWindow().zoomIn();
1437 break;
1438
1439 case R.id.zoom_out_menu_id:
1440 getTopWindow().zoomOut();
1441 break;
1442
1443 case R.id.view_downloads_menu_id:
1444 viewDownloads(null);
1445 break;
1446
The Android Open Source Project0c908882009-03-03 19:32:16 -08001447 case R.id.window_one_menu_id:
1448 case R.id.window_two_menu_id:
1449 case R.id.window_three_menu_id:
1450 case R.id.window_four_menu_id:
1451 case R.id.window_five_menu_id:
1452 case R.id.window_six_menu_id:
1453 case R.id.window_seven_menu_id:
1454 case R.id.window_eight_menu_id:
1455 {
1456 int menuid = item.getItemId();
1457 for (int id = 0; id < WINDOW_SHORTCUT_ID_ARRAY.length; id++) {
1458 if (WINDOW_SHORTCUT_ID_ARRAY[id] == menuid) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001459 Tab desiredTab = mTabControl.getTab(id);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001460 if (desiredTab != null &&
1461 desiredTab != mTabControl.getCurrentTab()) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001462 switchToTab(id);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001463 }
1464 break;
1465 }
1466 }
1467 }
1468 break;
1469
1470 default:
1471 if (!super.onOptionsItemSelected(item)) {
1472 return false;
1473 }
1474 // Otherwise fall through.
1475 }
1476 mCanChord = false;
1477 return true;
1478 }
1479
Cary Clark2c326e62010-08-19 18:40:57 -04001480 private boolean dialogIsUp() {
1481 return null != mFindDialog && mFindDialog.isVisible() ||
1482 null != mSelectDialog && mSelectDialog.isVisible();
1483 }
1484
1485 private boolean closeDialog(WebDialog dialog) {
1486 if (null == dialog || !dialog.isVisible()) return false;
1487 Tab currentTab = mTabControl.getCurrentTab();
1488 currentTab.closeDialog(dialog);
1489 dialog.dismiss();
1490 return true;
1491 }
1492
1493 /*
1494 * Remove the find dialog or select dialog.
1495 */
1496 public void closeDialogs() {
1497 if (!(closeDialog(mFindDialog) || closeDialog(mSelectDialog))) return;
1498 // If the Find was being performed in the main WebView, replace the
1499 // embedded title bar.
1500 Tab currentTab = mTabControl.getCurrentTab();
1501 if (currentTab.getSubWebView() == null) {
1502 WebView mainView = currentTab.getWebView();
1503 if (mainView != null) {
1504 mainView.setEmbeddedTitleBar(mTitleBar);
1505 }
1506 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001507 mMenuState = R.id.MAIN_MENU;
Cary Clark2c326e62010-08-19 18:40:57 -04001508 if (mInLoad) {
1509 // The title bar was hidden, because otherwise it would cover up the
1510 // find or select dialog. Now that the dialog has been removed,
1511 // show the fake title bar once again.
1512 showFakeTitleBar();
1513 }
1514 }
1515
1516 public void showFindDialog() {
1517 if (null == mFindDialog) {
1518 mFindDialog = new FindDialog(this);
1519 }
1520 showDialog(mFindDialog).setFindIsUp(true);
1521 }
1522
1523 public void setFindDialogText(String text) {
1524 mFindDialog.setText(text);
1525 }
1526
1527 public void showSelectDialog() {
1528 if (null == mSelectDialog) {
1529 mSelectDialog = new SelectDialog(this);
1530 }
1531 showDialog(mSelectDialog).setUpSelect();
1532 mSelectDialog.hideSoftInput();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001533 }
1534
Grace Kloba22ac16e2009-10-07 18:00:23 -07001535 @Override
1536 public boolean onPrepareOptionsMenu(Menu menu) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001537 // This happens when the user begins to hold down the menu key, so
1538 // allow them to chord to get a shortcut.
1539 mCanChord = true;
1540 // Note: setVisible will decide whether an item is visible; while
1541 // setEnabled() will decide whether an item is enabled, which also means
1542 // whether the matching shortcut key will function.
1543 super.onPrepareOptionsMenu(menu);
1544 switch (mMenuState) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001545 case EMPTY_MENU:
1546 if (mCurrentMenuState != mMenuState) {
1547 menu.setGroupVisible(R.id.MAIN_MENU, false);
1548 menu.setGroupEnabled(R.id.MAIN_MENU, false);
1549 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001550 }
1551 break;
1552 default:
1553 if (mCurrentMenuState != mMenuState) {
1554 menu.setGroupVisible(R.id.MAIN_MENU, true);
1555 menu.setGroupEnabled(R.id.MAIN_MENU, true);
1556 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001557 }
1558 final WebView w = getTopWindow();
1559 boolean canGoBack = false;
1560 boolean canGoForward = false;
1561 boolean isHome = false;
1562 if (w != null) {
1563 canGoBack = w.canGoBack();
1564 canGoForward = w.canGoForward();
1565 isHome = mSettings.getHomePage().equals(w.getUrl());
1566 }
1567 final MenuItem back = menu.findItem(R.id.back_menu_id);
1568 back.setEnabled(canGoBack);
1569
1570 final MenuItem home = menu.findItem(R.id.homepage_menu_id);
1571 home.setEnabled(!isHome);
1572
1573 menu.findItem(R.id.forward_menu_id)
1574 .setEnabled(canGoForward);
1575
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001576 menu.findItem(R.id.new_tab_menu_id).setEnabled(
Grace Kloba22ac16e2009-10-07 18:00:23 -07001577 mTabControl.canCreateNewTab());
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001578
The Android Open Source Project0c908882009-03-03 19:32:16 -08001579 // decide whether to show the share link option
1580 PackageManager pm = getPackageManager();
1581 Intent send = new Intent(Intent.ACTION_SEND);
1582 send.setType("text/plain");
1583 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1584 menu.findItem(R.id.share_page_menu_id).setVisible(ri != null);
1585
The Android Open Source Project0c908882009-03-03 19:32:16 -08001586 boolean isNavDump = mSettings.isNavDump();
1587 final MenuItem nav = menu.findItem(R.id.dump_nav_menu_id);
1588 nav.setVisible(isNavDump);
1589 nav.setEnabled(isNavDump);
Andrei Popescu7a8b88b2010-02-02 00:30:38 +00001590
1591 boolean showDebugSettings = mSettings.showDebugSettings();
1592 final MenuItem counter = menu.findItem(R.id.dump_counters_menu_id);
1593 counter.setVisible(showDebugSettings);
1594 counter.setEnabled(showDebugSettings);
1595
The Android Open Source Project0c908882009-03-03 19:32:16 -08001596 break;
1597 }
1598 mCurrentMenuState = mMenuState;
1599 return true;
1600 }
1601
1602 @Override
1603 public void onCreateContextMenu(ContextMenu menu, View v,
1604 ContextMenuInfo menuInfo) {
Leon Scroggins4e9f89b2010-02-22 16:54:14 -05001605 if (v instanceof TitleBar) {
1606 return;
1607 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001608 WebView webview = (WebView) v;
1609 WebView.HitTestResult result = webview.getHitTestResult();
1610 if (result == null) {
1611 return;
1612 }
1613
1614 int type = result.getType();
1615 if (type == WebView.HitTestResult.UNKNOWN_TYPE) {
1616 Log.w(LOGTAG,
1617 "We should not show context menu when nothing is touched");
1618 return;
1619 }
1620 if (type == WebView.HitTestResult.EDIT_TEXT_TYPE) {
1621 // let TextView handles context menu
1622 return;
1623 }
1624
1625 // Note, http://b/issue?id=1106666 is requesting that
1626 // an inflated menu can be used again. This is not available
1627 // yet, so inflate each time (yuk!)
1628 MenuInflater inflater = getMenuInflater();
1629 inflater.inflate(R.menu.browsercontext, menu);
1630
1631 // Show the correct menu group
1632 String extra = result.getExtra();
1633 menu.setGroupVisible(R.id.PHONE_MENU,
1634 type == WebView.HitTestResult.PHONE_TYPE);
1635 menu.setGroupVisible(R.id.EMAIL_MENU,
1636 type == WebView.HitTestResult.EMAIL_TYPE);
1637 menu.setGroupVisible(R.id.GEO_MENU,
1638 type == WebView.HitTestResult.GEO_TYPE);
1639 menu.setGroupVisible(R.id.IMAGE_MENU,
1640 type == WebView.HitTestResult.IMAGE_TYPE
1641 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1642 menu.setGroupVisible(R.id.ANCHOR_MENU,
1643 type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1644 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1645
1646 // Setup custom handling depending on the type
1647 switch (type) {
1648 case WebView.HitTestResult.PHONE_TYPE:
1649 menu.setHeaderTitle(Uri.decode(extra));
1650 menu.findItem(R.id.dial_context_menu_id).setIntent(
1651 new Intent(Intent.ACTION_VIEW, Uri
1652 .parse(WebView.SCHEME_TEL + extra)));
1653 Intent addIntent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
1654 addIntent.putExtra(Insert.PHONE, Uri.decode(extra));
Cary Clark5e335a32009-09-22 14:53:11 -04001655 addIntent.setType(ContactsContract.Contacts.CONTENT_ITEM_TYPE);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001656 menu.findItem(R.id.add_contact_context_menu_id).setIntent(
1657 addIntent);
1658 menu.findItem(R.id.copy_phone_context_menu_id).setOnMenuItemClickListener(
1659 new Copy(extra));
1660 break;
1661
1662 case WebView.HitTestResult.EMAIL_TYPE:
1663 menu.setHeaderTitle(extra);
1664 menu.findItem(R.id.email_context_menu_id).setIntent(
1665 new Intent(Intent.ACTION_VIEW, Uri
1666 .parse(WebView.SCHEME_MAILTO + extra)));
1667 menu.findItem(R.id.copy_mail_context_menu_id).setOnMenuItemClickListener(
1668 new Copy(extra));
1669 break;
1670
1671 case WebView.HitTestResult.GEO_TYPE:
1672 menu.setHeaderTitle(extra);
1673 menu.findItem(R.id.map_context_menu_id).setIntent(
1674 new Intent(Intent.ACTION_VIEW, Uri
1675 .parse(WebView.SCHEME_GEO
1676 + URLEncoder.encode(extra))));
1677 menu.findItem(R.id.copy_geo_context_menu_id).setOnMenuItemClickListener(
1678 new Copy(extra));
1679 break;
1680
1681 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1682 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
1683 TextView titleView = (TextView) LayoutInflater.from(this)
1684 .inflate(android.R.layout.browser_link_context_header,
1685 null);
1686 titleView.setText(extra);
1687 menu.setHeaderView(titleView);
1688 // decide whether to show the open link in new tab option
1689 menu.findItem(R.id.open_newtab_context_menu_id).setVisible(
Grace Kloba22ac16e2009-10-07 18:00:23 -07001690 mTabControl.canCreateNewTab());
Ben Murdochde353622009-10-12 10:29:00 +01001691 menu.findItem(R.id.bookmark_context_menu_id).setVisible(
1692 Bookmarks.urlHasAcceptableScheme(extra));
The Android Open Source Project0c908882009-03-03 19:32:16 -08001693 PackageManager pm = getPackageManager();
1694 Intent send = new Intent(Intent.ACTION_SEND);
1695 send.setType("text/plain");
1696 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1697 menu.findItem(R.id.share_link_context_menu_id).setVisible(ri != null);
1698 if (type == WebView.HitTestResult.SRC_ANCHOR_TYPE) {
1699 break;
1700 }
1701 // otherwise fall through to handle image part
1702 case WebView.HitTestResult.IMAGE_TYPE:
1703 if (type == WebView.HitTestResult.IMAGE_TYPE) {
1704 menu.setHeaderTitle(extra);
1705 }
1706 menu.findItem(R.id.view_image_context_menu_id).setIntent(
1707 new Intent(Intent.ACTION_VIEW, Uri.parse(extra)));
1708 menu.findItem(R.id.download_context_menu_id).
1709 setOnMenuItemClickListener(new Download(extra));
Ben Murdoch4f75ba22009-10-27 11:48:28 +00001710 menu.findItem(R.id.set_wallpaper_context_menu_id).
1711 setOnMenuItemClickListener(new SetAsWallpaper(extra));
The Android Open Source Project0c908882009-03-03 19:32:16 -08001712 break;
1713
1714 default:
1715 Log.w(LOGTAG, "We should not get here.");
1716 break;
1717 }
Leon Scrogginsb2b19f52009-10-09 16:10:00 -04001718 hideFakeTitleBar();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001719 }
1720
The Android Open Source Project0c908882009-03-03 19:32:16 -08001721 // Attach the given tab to the content view.
Grace Klobac928c302009-09-17 11:51:21 -07001722 // this should only be called for the current tab.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001723 private void attachTabToContentView(Tab t) {
Steve Block2bc69912009-07-30 14:45:13 +01001724 // Attach the container that contains the main WebView and any other UI
1725 // associated with the tab.
Patrick Scottd0119532009-09-17 08:00:31 -04001726 t.attachTabToContentView(mContentView);
Ben Murdochbff2d602009-07-01 20:19:05 +01001727
1728 if (mShouldShowErrorConsole) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001729 ErrorConsoleView errorConsole = t.getErrorConsole(true);
Ben Murdochbff2d602009-07-01 20:19:05 +01001730 if (errorConsole.numberOfErrors() == 0) {
1731 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
1732 } else {
1733 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
1734 }
1735
1736 mErrorConsoleContainer.addView(errorConsole,
Romain Guy15b8ec62010-01-08 15:06:43 -08001737 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
Ben Murdochbff2d602009-07-01 20:19:05 +01001738 ViewGroup.LayoutParams.WRAP_CONTENT));
1739 }
1740
Leon Scroggins39ab28e2009-09-02 21:20:30 -04001741 WebView view = t.getWebView();
Leon Scroggins55a5bc22009-09-04 17:00:08 -04001742 view.setEmbeddedTitleBar(mTitleBar);
Leon Scroggins58d56c62010-01-28 15:12:40 -05001743 if (t.isInVoiceSearchMode()) {
1744 showVoiceTitleBar(t.getVoiceDisplayTitle());
1745 } else {
1746 revertVoiceTitleBar();
1747 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001748 // Request focus on the top window.
1749 t.getTopWindow().requestFocus();
1750 }
1751
1752 // Attach a sub window to the main WebView of the given tab.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001753 void attachSubWindow(Tab t) {
Patrick Scottd0119532009-09-17 08:00:31 -04001754 t.attachSubWindow(mContentView);
1755 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001756 }
1757
1758 // Remove the given tab from the content view.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001759 private void removeTabFromContentView(Tab t) {
Steve Block2bc69912009-07-30 14:45:13 +01001760 // Remove the container that contains the main WebView.
Patrick Scottd0119532009-09-17 08:00:31 -04001761 t.removeTabFromContentView(mContentView);
Ben Murdochbff2d602009-07-01 20:19:05 +01001762
Grace Kloba22ac16e2009-10-07 18:00:23 -07001763 ErrorConsoleView errorConsole = t.getErrorConsole(false);
1764 if (errorConsole != null) {
1765 mErrorConsoleContainer.removeView(errorConsole);
Ben Murdochbff2d602009-07-01 20:19:05 +01001766 }
1767
Leon Scroggins39ab28e2009-09-02 21:20:30 -04001768 WebView view = t.getWebView();
Leon Scrogginsbb85b902009-09-14 19:27:20 -04001769 if (view != null) {
1770 view.setEmbeddedTitleBar(null);
1771 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001772 }
1773
1774 // Remove the sub window if it exists. Also called by TabControl when the
1775 // user clicks the 'X' to dismiss a sub window.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001776 /* package */ void dismissSubWindow(Tab t) {
Patrick Scottd0119532009-09-17 08:00:31 -04001777 t.removeSubWindow(mContentView);
Grace Kloba22ac16e2009-10-07 18:00:23 -07001778 // dismiss the subwindow. This will destroy the WebView.
1779 t.dismissSubWindow();
Patrick Scottd0119532009-09-17 08:00:31 -04001780 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001781 }
1782
Leon Scroggins1f005d32009-08-10 17:36:42 -04001783 // A wrapper function of {@link #openTabAndShow(UrlData, boolean, String)}
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07001784 // that accepts url as string.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001785 private Tab openTabAndShow(String url, boolean closeOnExit, String appId) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001786 return openTabAndShow(new UrlData(url), closeOnExit, appId);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001787 }
1788
1789 // This method does a ton of stuff. It will attempt to create a new tab
1790 // if we haven't reached MAX_TABS. Otherwise it uses the current tab. If
Leon Scroggins1f005d32009-08-10 17:36:42 -04001791 // url isn't null, it will load the given url.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001792 /* package */Tab openTabAndShow(UrlData urlData, boolean closeOnExit,
1793 String appId) {
1794 final Tab currentTab = mTabControl.getCurrentTab();
1795 if (mTabControl.canCreateNewTab()) {
1796 final Tab tab = mTabControl.createNewTab(closeOnExit, appId,
1797 urlData.mUrl);
Leon Scroggins1f005d32009-08-10 17:36:42 -04001798 WebView webview = tab.getWebView();
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001799 // If the last tab was removed from the active tabs page, currentTab
1800 // will be null.
1801 if (currentTab != null) {
1802 removeTabFromContentView(currentTab);
1803 }
Patrick Scott8bbd69f2009-08-14 13:35:53 -04001804 // We must set the new tab as the current tab to reflect the old
1805 // animation behavior.
1806 mTabControl.setCurrentTab(tab);
Grace Klobaeb6eef42009-09-15 17:56:32 -07001807 attachTabToContentView(tab);
Leon Scroggins160a7e72009-08-14 18:28:01 -04001808 if (!urlData.isEmpty()) {
Patrick Scott9d53da02010-02-19 10:19:01 -05001809 loadUrlDataIn(tab, urlData);
Leon Scroggins1f005d32009-08-10 17:36:42 -04001810 }
1811 return tab;
1812 } else {
1813 // Get rid of the subwindow if it exists
1814 dismissSubWindow(currentTab);
1815 if (!urlData.isEmpty()) {
1816 // Load the given url.
Patrick Scott9d53da02010-02-19 10:19:01 -05001817 loadUrlDataIn(currentTab, urlData);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001818 }
Leon Scroggins58d56c62010-01-28 15:12:40 -05001819 return currentTab;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001820 }
1821 }
1822
Grace Kloba22ac16e2009-10-07 18:00:23 -07001823 private Tab openTab(String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001824 if (mSettings.openInBackground()) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001825 Tab t = mTabControl.createNewTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001826 if (t != null) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001827 WebView view = t.getWebView();
Leon Scroggins92472e82010-02-17 16:32:28 -05001828 loadUrl(view, url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001829 }
Grace Klobac9181842009-04-14 08:53:22 -07001830 return t;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001831 } else {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001832 return openTabAndShow(url, false, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001833 }
1834 }
1835
1836 private class Copy implements OnMenuItemClickListener {
1837 private CharSequence mText;
1838
1839 public boolean onMenuItemClick(MenuItem item) {
1840 copy(mText);
1841 return true;
1842 }
1843
1844 public Copy(CharSequence toCopy) {
1845 mText = toCopy;
1846 }
1847 }
1848
1849 private class Download implements OnMenuItemClickListener {
1850 private String mText;
1851
1852 public boolean onMenuItemClick(MenuItem item) {
1853 onDownloadStartNoStream(mText, null, null, null, -1);
1854 return true;
1855 }
1856
1857 public Download(String toDownload) {
1858 mText = toDownload;
1859 }
1860 }
1861
Ben Murdoch4f75ba22009-10-27 11:48:28 +00001862 private class SetAsWallpaper extends Thread implements
1863 OnMenuItemClickListener, DialogInterface.OnCancelListener {
1864 private URL mUrl;
1865 private ProgressDialog mWallpaperProgress;
1866 private boolean mCanceled = false;
1867
1868 public SetAsWallpaper(String url) {
1869 try {
1870 mUrl = new URL(url);
1871 } catch (MalformedURLException e) {
1872 mUrl = null;
1873 }
1874 }
1875
1876 public void onCancel(DialogInterface dialog) {
1877 mCanceled = true;
1878 }
1879
1880 public boolean onMenuItemClick(MenuItem item) {
1881 if (mUrl != null) {
1882 // The user may have tried to set a image with a large file size as their
1883 // background so it may take a few moments to perform the operation. Display
1884 // a progress spinner while it is working.
1885 mWallpaperProgress = new ProgressDialog(BrowserActivity.this);
1886 mWallpaperProgress.setIndeterminate(true);
1887 mWallpaperProgress.setMessage(getText(R.string.progress_dialog_setting_wallpaper));
1888 mWallpaperProgress.setCancelable(true);
1889 mWallpaperProgress.setOnCancelListener(this);
1890 mWallpaperProgress.show();
1891 start();
1892 }
1893 return true;
1894 }
1895
1896 public void run() {
1897 Drawable oldWallpaper = BrowserActivity.this.getWallpaper();
1898 try {
1899 // TODO: This will cause the resource to be downloaded again, when we
1900 // should in most cases be able to grab it from the cache. To fix this
1901 // we should query WebCore to see if we can access a cached version and
1902 // instead open an input stream on that. This pattern could also be used
1903 // in the download manager where the same problem exists.
1904 InputStream inputstream = mUrl.openStream();
1905 if (inputstream != null) {
1906 setWallpaper(inputstream);
1907 }
1908 } catch (IOException e) {
1909 Log.e(LOGTAG, "Unable to set new wallpaper");
1910 // Act as though the user canceled the operation so we try to
1911 // restore the old wallpaper.
1912 mCanceled = true;
1913 }
1914
1915 if (mCanceled) {
1916 // Restore the old wallpaper if the user cancelled whilst we were setting
1917 // the new wallpaper.
1918 int width = oldWallpaper.getIntrinsicWidth();
1919 int height = oldWallpaper.getIntrinsicHeight();
1920 Bitmap bm = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
1921 Canvas canvas = new Canvas(bm);
1922 oldWallpaper.setBounds(0, 0, width, height);
1923 oldWallpaper.draw(canvas);
1924 try {
1925 setWallpaper(bm);
1926 } catch (IOException e) {
1927 Log.e(LOGTAG, "Unable to restore old wallpaper.");
1928 }
1929 mCanceled = false;
1930 }
1931
1932 if (mWallpaperProgress.isShowing()) {
1933 mWallpaperProgress.dismiss();
1934 }
1935 }
1936 }
1937
The Android Open Source Project0c908882009-03-03 19:32:16 -08001938 private void copy(CharSequence text) {
1939 try {
1940 IClipboard clip = IClipboard.Stub.asInterface(ServiceManager.getService("clipboard"));
1941 if (clip != null) {
1942 clip.setClipboardText(text);
1943 }
1944 } catch (android.os.RemoteException e) {
1945 Log.e(LOGTAG, "Copy failed", e);
1946 }
1947 }
1948
1949 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08001950 * Resets the browser title-view to whatever it must be
1951 * (for example, if we had a loading error)
1952 * When we have a new page, we call resetTitle, when we
1953 * have to reset the titlebar to whatever it used to be
1954 * (for example, if the user chose to stop loading), we
1955 * call resetTitleAndRevertLockIcon.
1956 */
1957 /* package */ void resetTitleAndRevertLockIcon() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001958 mTabControl.getCurrentTab().revertLockIcon();
1959 updateLockIconToLatest();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001960 resetTitleIconAndProgress();
1961 }
1962
1963 /**
1964 * Reset the title, favicon, and progress.
1965 */
1966 private void resetTitleIconAndProgress() {
1967 WebView current = mTabControl.getCurrentWebView();
1968 if (current == null) {
1969 return;
1970 }
1971 resetTitleAndIcon(current);
1972 int progress = current.getProgress();
Grace Kloba22ac16e2009-10-07 18:00:23 -07001973 current.getWebChromeClient().onProgressChanged(current, progress);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001974 }
1975
1976 // Reset the title and the icon based on the given item.
1977 private void resetTitleAndIcon(WebView view) {
1978 WebHistoryItem item = view.copyBackForwardList().getCurrentItem();
1979 if (item != null) {
Leon Scroggins68579392009-09-15 15:31:54 -04001980 setUrlTitle(item.getUrl(), item.getTitle());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001981 setFavicon(item.getFavicon());
1982 } else {
Leon Scroggins68579392009-09-15 15:31:54 -04001983 setUrlTitle(null, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001984 setFavicon(null);
1985 }
1986 }
1987
1988 /**
1989 * Sets a title composed of the URL and the title string.
1990 * @param url The URL of the site being loaded.
1991 * @param title The title of the site being loaded.
1992 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07001993 void setUrlTitle(String url, String title) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001994 mUrl = url;
1995 mTitle = title;
1996
Leon Scroggins58d56c62010-01-28 15:12:40 -05001997 // If we are in voice search mode, the title has already been set.
1998 if (mTabControl.getCurrentTab().isInVoiceSearchMode()) return;
1999 mTitleBar.setDisplayTitle(url);
2000 mFakeTitleBar.setDisplayTitle(url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002001 }
2002
2003 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08002004 * @param url The URL to build a title version of the URL from.
2005 * @return The title version of the URL or null if fails.
2006 * The title version of the URL can be either the URL hostname,
2007 * or the hostname with an "https://" prefix (for secure URLs),
2008 * or an empty string if, for example, the URL in question is a
2009 * file:// URL with no hostname.
2010 */
Leon Scroggins32e14a62009-06-11 10:26:34 -04002011 /* package */ static String buildTitleUrl(String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002012 String titleUrl = null;
2013
2014 if (url != null) {
2015 try {
2016 // parse the url string
2017 URL urlObj = new URL(url);
2018 if (urlObj != null) {
2019 titleUrl = "";
2020
2021 String protocol = urlObj.getProtocol();
2022 String host = urlObj.getHost();
2023
2024 if (host != null && 0 < host.length()) {
2025 titleUrl = host;
2026 if (protocol != null) {
2027 // if a secure site, add an "https://" prefix!
2028 if (protocol.equalsIgnoreCase("https")) {
2029 titleUrl = protocol + "://" + host;
2030 }
2031 }
2032 }
2033 }
2034 } catch (MalformedURLException e) {}
2035 }
2036
2037 return titleUrl;
2038 }
2039
2040 // Set the favicon in the title bar.
Grace Kloba22ac16e2009-10-07 18:00:23 -07002041 void setFavicon(Bitmap icon) {
Leon Scroggins68579392009-09-15 15:31:54 -04002042 mTitleBar.setFavicon(icon);
Leon Scrogginsfe87bd32009-10-06 10:10:00 -04002043 mFakeTitleBar.setFavicon(icon);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002044 }
2045
2046 /**
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002047 * Close the tab, remove its associated title bar, and adjust mTabControl's
2048 * current tab to a valid value.
Leon Scroggins1f005d32009-08-10 17:36:42 -04002049 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07002050 /* package */ void closeTab(Tab t) {
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002051 int currentIndex = mTabControl.getCurrentIndex();
2052 int removeIndex = mTabControl.getTabIndex(t);
Leon Scroggins1f005d32009-08-10 17:36:42 -04002053 mTabControl.removeTab(t);
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002054 if (currentIndex >= removeIndex && currentIndex != 0) {
2055 currentIndex--;
2056 }
2057 mTabControl.setCurrentTab(mTabControl.getTab(currentIndex));
Andrei Popescua5bf1de2009-09-23 16:39:23 +01002058 resetTitleIconAndProgress();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002059 }
2060
Leon Scrogginsdcc5eeb2010-02-23 17:26:37 -05002061 /* package */ void goBackOnePageOrQuit() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002062 Tab current = mTabControl.getCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002063 if (current == null) {
2064 /*
2065 * Instead of finishing the activity, simply push this to the back
2066 * of the stack and let ActivityManager to choose the foreground
2067 * activity. As BrowserActivity is singleTask, it will be always the
2068 * root of the task. So we can use either true or false for
2069 * moveTaskToBack().
2070 */
2071 moveTaskToBack(true);
Grace Kloba00d85e72009-09-23 18:50:05 -07002072 return;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002073 }
2074 WebView w = current.getWebView();
2075 if (w.canGoBack()) {
2076 w.goBack();
2077 } else {
2078 // Check to see if we are closing a window that was created by
2079 // another window. If so, we switch back to that window.
Grace Kloba22ac16e2009-10-07 18:00:23 -07002080 Tab parent = current.getParentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002081 if (parent != null) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04002082 switchToTab(mTabControl.getTabIndex(parent));
2083 // Now we close the other tab
2084 closeTab(current);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002085 } else {
2086 if (current.closeOnExit()) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002087 // force the tab's inLoad() to be false as we are going to
2088 // either finish the activity or remove the tab. This will
2089 // ensure pauseWebViewTimers() taking action.
2090 mTabControl.getCurrentTab().clearInLoad();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002091 if (mTabControl.getTabCount() == 1) {
2092 finish();
2093 return;
2094 }
Mike Reed7bfa63b2009-05-28 11:08:32 -04002095 // call pauseWebViewTimers() now, we won't be able to call
2096 // it in onPause() as the WebView won't be valid.
Grace Klobaec1b5ad2009-08-18 08:42:32 -07002097 // Temporarily change mActivityInPause to be true as
2098 // pauseWebViewTimers() will do nothing if mActivityInPause
2099 // is false.
Grace Kloba918e1d72009-08-13 14:55:06 -07002100 boolean savedState = mActivityInPause;
2101 if (savedState) {
Grace Klobaec1b5ad2009-08-18 08:42:32 -07002102 Log.e(LOGTAG, "BrowserActivity is already paused "
2103 + "while handing goBackOnePageOrQuit.");
Grace Kloba918e1d72009-08-13 14:55:06 -07002104 }
2105 mActivityInPause = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -04002106 pauseWebViewTimers();
Grace Kloba918e1d72009-08-13 14:55:06 -07002107 mActivityInPause = savedState;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002108 removeTabFromContentView(current);
2109 mTabControl.removeTab(current);
2110 }
2111 /*
2112 * Instead of finishing the activity, simply push this to the back
2113 * of the stack and let ActivityManager to choose the foreground
2114 * activity. As BrowserActivity is singleTask, it will be always the
2115 * root of the task. So we can use either true or false for
2116 * moveTaskToBack().
2117 */
2118 moveTaskToBack(true);
2119 }
2120 }
2121 }
2122
Grace Kloba22ac16e2009-10-07 18:00:23 -07002123 boolean isMenuDown() {
2124 return mMenuIsDown;
2125 }
2126
Grace Kloba5942df02009-09-18 11:48:29 -07002127 @Override
2128 public boolean onKeyDown(int keyCode, KeyEvent event) {
Leon Scrogginsf65b50d2009-12-08 10:44:28 -05002129 // Even if MENU is already held down, we need to call to super to open
2130 // the IME on long press.
2131 if (KeyEvent.KEYCODE_MENU == keyCode) {
2132 mMenuIsDown = true;
2133 return super.onKeyDown(keyCode, event);
2134 }
Grace Kloba5942df02009-09-18 11:48:29 -07002135 // The default key mode is DEFAULT_KEYS_SEARCH_LOCAL. As the MENU is
2136 // still down, we don't want to trigger the search. Pretend to consume
2137 // the key and do nothing.
2138 if (mMenuIsDown) return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002139
Grace Kloba5942df02009-09-18 11:48:29 -07002140 switch(keyCode) {
Grace Kloba5942df02009-09-18 11:48:29 -07002141 case KeyEvent.KEYCODE_SPACE:
Grace Klobada0fe552009-09-22 18:17:24 -07002142 // WebView/WebTextView handle the keys in the KeyDown. As
2143 // the Activity's shortcut keys are only handled when WebView
2144 // doesn't, have to do it in onKeyDown instead of onKeyUp.
2145 if (event.isShiftPressed()) {
2146 getTopWindow().pageUp(false);
2147 } else {
2148 getTopWindow().pageDown(false);
2149 }
Grace Kloba5942df02009-09-18 11:48:29 -07002150 return true;
2151 case KeyEvent.KEYCODE_BACK:
2152 if (event.getRepeatCount() == 0) {
2153 event.startTracking();
2154 return true;
2155 } else if (mCustomView == null && mActiveTabsPage == null
2156 && event.isLongPress()) {
2157 bookmarksOrHistoryPicker(true);
2158 return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002159 }
Grace Kloba5942df02009-09-18 11:48:29 -07002160 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002161 }
Grace Kloba5942df02009-09-18 11:48:29 -07002162 return super.onKeyDown(keyCode, event);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002163 }
2164
Grace Kloba5942df02009-09-18 11:48:29 -07002165 @Override
2166 public boolean onKeyUp(int keyCode, KeyEvent event) {
2167 switch(keyCode) {
2168 case KeyEvent.KEYCODE_MENU:
2169 mMenuIsDown = false;
2170 break;
Grace Kloba5942df02009-09-18 11:48:29 -07002171 case KeyEvent.KEYCODE_BACK:
2172 if (event.isTracking() && !event.isCanceled()) {
2173 if (mCustomView != null) {
2174 // if a custom view is showing, hide it
Grace Kloba22ac16e2009-10-07 18:00:23 -07002175 mTabControl.getCurrentWebView().getWebChromeClient()
2176 .onHideCustomView();
Grace Kloba5942df02009-09-18 11:48:29 -07002177 } else if (mActiveTabsPage != null) {
2178 // if tab page is showing, hide it
2179 removeActiveTabPage(true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002180 } else {
Grace Kloba5942df02009-09-18 11:48:29 -07002181 WebView subwindow = mTabControl.getCurrentSubWindow();
2182 if (subwindow != null) {
2183 if (subwindow.canGoBack()) {
2184 subwindow.goBack();
2185 } else {
2186 dismissSubWindow(mTabControl.getCurrentTab());
2187 }
2188 } else {
2189 goBackOnePageOrQuit();
2190 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002191 }
Grace Kloba5942df02009-09-18 11:48:29 -07002192 return true;
2193 }
2194 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002195 }
Grace Kloba5942df02009-09-18 11:48:29 -07002196 return super.onKeyUp(keyCode, event);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002197 }
2198
Leon Scroggins68579392009-09-15 15:31:54 -04002199 /* package */ void stopLoading() {
Ben Murdochb7cc8b42009-09-28 10:59:09 +01002200 mDidStopLoad = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002201 resetTitleAndRevertLockIcon();
2202 WebView w = getTopWindow();
2203 w.stopLoading();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002204 // FIXME: before refactor, it is using mWebViewClient. So I keep the
2205 // same logic here. But for subwindow case, should we call into the main
2206 // WebView's onPageFinished as we never call its onPageStarted and if
2207 // the page finishes itself, we don't call onPageFinished.
2208 mTabControl.getCurrentWebView().getWebViewClient().onPageFinished(w,
2209 w.getUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08002210
2211 cancelStopToast();
2212 mStopToast = Toast
2213 .makeText(this, R.string.stopping, Toast.LENGTH_SHORT);
2214 mStopToast.show();
2215 }
2216
Grace Kloba22ac16e2009-10-07 18:00:23 -07002217 boolean didUserStopLoading() {
2218 return mDidStopLoad;
2219 }
2220
The Android Open Source Project0c908882009-03-03 19:32:16 -08002221 private void cancelStopToast() {
2222 if (mStopToast != null) {
2223 mStopToast.cancel();
2224 mStopToast = null;
2225 }
2226 }
2227
Grace Kloba22ac16e2009-10-07 18:00:23 -07002228 // called by a UI or non-UI thread to post the message
2229 public void postMessage(int what, int arg1, int arg2, Object obj,
2230 long delayMillis) {
2231 mHandler.sendMessageDelayed(mHandler.obtainMessage(what, arg1, arg2,
2232 obj), delayMillis);
2233 }
2234
2235 // called by a UI or non-UI thread to remove the message
2236 void removeMessages(int what, Object object) {
2237 mHandler.removeMessages(what, object);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002238 }
2239
2240 // public message ids
2241 public final static int LOAD_URL = 1001;
2242 public final static int STOP_LOAD = 1002;
2243
2244 // Message Ids
2245 private static final int FOCUS_NODE_HREF = 102;
Grace Kloba92c18a52009-07-31 23:48:32 -07002246 private static final int RELEASE_WAKELOCK = 107;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002247
Grace Kloba22ac16e2009-10-07 18:00:23 -07002248 static final int UPDATE_BOOKMARK_THUMBNAIL = 108;
Ben Murdoch2694e232009-09-29 09:41:11 +01002249
The Android Open Source Project0c908882009-03-03 19:32:16 -08002250 // Private handler for handling javascript and saving passwords
2251 private Handler mHandler = new Handler() {
2252
2253 public void handleMessage(Message msg) {
2254 switch (msg.what) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002255 case FOCUS_NODE_HREF:
Ben Murdoch2694e232009-09-29 09:41:11 +01002256 {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002257 String url = (String) msg.getData().get("url");
Ben Murdoch90d088c2009-11-17 18:14:04 +00002258 String title = (String) msg.getData().get("title");
The Android Open Source Project0c908882009-03-03 19:32:16 -08002259 if (url == null || url.length() == 0) {
2260 break;
2261 }
2262 HashMap focusNodeMap = (HashMap) msg.obj;
2263 WebView view = (WebView) focusNodeMap.get("webview");
2264 // Only apply the action if the top window did not change.
2265 if (getTopWindow() != view) {
2266 break;
2267 }
2268 switch (msg.arg1) {
2269 case R.id.open_context_menu_id:
2270 case R.id.view_image_context_menu_id:
Leon Scroggins92472e82010-02-17 16:32:28 -05002271 loadUrlFromContext(getTopWindow(), url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002272 break;
2273 case R.id.open_newtab_context_menu_id:
Grace Kloba22ac16e2009-10-07 18:00:23 -07002274 final Tab parent = mTabControl.getCurrentTab();
2275 final Tab newTab = openTab(url);
Grace Klobac9181842009-04-14 08:53:22 -07002276 if (newTab != parent) {
2277 parent.addChildTab(newTab);
2278 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002279 break;
2280 case R.id.bookmark_context_menu_id:
2281 Intent intent = new Intent(BrowserActivity.this,
2282 AddBookmarkPage.class);
2283 intent.putExtra("url", url);
Ben Murdoch90d088c2009-11-17 18:14:04 +00002284 intent.putExtra("title", title);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002285 startActivity(intent);
2286 break;
2287 case R.id.share_link_context_menu_id:
Leon Scroggins96afcb12009-12-10 12:35:56 -05002288 // See if this site has been visited before
2289 StringBuilder sb = new StringBuilder(
2290 Browser.BookmarkColumns.URL + " = ");
2291 DatabaseUtils.appendEscapedSQLString(sb, url);
2292 Cursor c = mResolver.query(Browser.BOOKMARKS_URI,
2293 Browser.HISTORY_PROJECTION,
2294 sb.toString(),
2295 null,
2296 null);
2297 if (c.moveToFirst()) {
2298 // The site has been visited before, so grab the
2299 // info from the database.
2300 Bitmap favicon = null;
2301 Bitmap thumbnail = null;
2302 String linkTitle = c.getString(Browser.
2303 HISTORY_PROJECTION_TITLE_INDEX);
2304 byte[] data = c.getBlob(Browser.
2305 HISTORY_PROJECTION_FAVICON_INDEX);
2306 if (data != null) {
2307 favicon = BitmapFactory.decodeByteArray(
2308 data, 0, data.length);
2309 }
2310 data = c.getBlob(Browser.
2311 HISTORY_PROJECTION_THUMBNAIL_INDEX);
2312 if (data != null) {
2313 thumbnail = BitmapFactory.decodeByteArray(
2314 data, 0, data.length);
2315 }
2316 sharePage(BrowserActivity.this,
2317 linkTitle, url, favicon, thumbnail);
2318 } else {
2319 Browser.sendString(BrowserActivity.this, url,
2320 getString(
2321 R.string.choosertitle_sharevia));
2322 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002323 break;
2324 case R.id.copy_link_context_menu_id:
2325 copy(url);
2326 break;
2327 case R.id.save_link_context_menu_id:
2328 case R.id.download_context_menu_id:
2329 onDownloadStartNoStream(url, null, null, null, -1);
2330 break;
2331 }
2332 break;
Ben Murdoch2694e232009-09-29 09:41:11 +01002333 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002334
2335 case LOAD_URL:
Leon Scroggins92472e82010-02-17 16:32:28 -05002336 loadUrlFromContext(getTopWindow(), (String) msg.obj);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002337 break;
2338
2339 case STOP_LOAD:
2340 stopLoading();
2341 break;
2342
The Android Open Source Project0c908882009-03-03 19:32:16 -08002343 case RELEASE_WAKELOCK:
2344 if (mWakeLock.isHeld()) {
2345 mWakeLock.release();
Grace Kloba5d0e02e2009-10-05 15:15:36 -07002346 // if we reach here, Browser should be still in the
2347 // background loading after WAKELOCK_TIMEOUT (5-min).
2348 // To avoid burning the battery, stop loading.
2349 mTabControl.stopAllLoading();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002350 }
2351 break;
Ben Murdoch2694e232009-09-29 09:41:11 +01002352
2353 case UPDATE_BOOKMARK_THUMBNAIL:
2354 WebView view = (WebView) msg.obj;
2355 if (view != null) {
2356 updateScreenshot(view);
2357 }
2358 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002359 }
2360 }
2361 };
2362
Leon Scroggins96afcb12009-12-10 12:35:56 -05002363 /**
2364 * Share a page, providing the title, url, favicon, and a screenshot. Uses
2365 * an {@link Intent} to launch the Activity chooser.
2366 * @param c Context used to launch a new Activity.
2367 * @param title Title of the page. Stored in the Intent with
Paul Westbrook03e6d392010-02-12 10:33:29 -08002368 * {@link Intent#EXTRA_SUBJECT}
Leon Scroggins96afcb12009-12-10 12:35:56 -05002369 * @param url URL of the page. Stored in the Intent with
2370 * {@link Intent#EXTRA_TEXT}
2371 * @param favicon Bitmap of the favicon for the page. Stored in the Intent
2372 * with {@link Browser#EXTRA_SHARE_FAVICON}
2373 * @param screenshot Bitmap of a screenshot of the page. Stored in the
2374 * Intent with {@link Browser#EXTRA_SHARE_SCREENSHOT}
2375 */
2376 public static final void sharePage(Context c, String title, String url,
2377 Bitmap favicon, Bitmap screenshot) {
2378 Intent send = new Intent(Intent.ACTION_SEND);
2379 send.setType("text/plain");
2380 send.putExtra(Intent.EXTRA_TEXT, url);
Paul Westbrook03e6d392010-02-12 10:33:29 -08002381 send.putExtra(Intent.EXTRA_SUBJECT, title);
Leon Scroggins96afcb12009-12-10 12:35:56 -05002382 send.putExtra(Browser.EXTRA_SHARE_FAVICON, favicon);
2383 send.putExtra(Browser.EXTRA_SHARE_SCREENSHOT, screenshot);
2384 try {
2385 c.startActivity(Intent.createChooser(send, c.getString(
2386 R.string.choosertitle_sharevia)));
2387 } catch(android.content.ActivityNotFoundException ex) {
2388 // if no app handles it, do nothing
2389 }
2390 }
2391
Leon Scroggins89c6d362009-07-15 16:54:37 -04002392 private void updateScreenshot(WebView view) {
2393 // If this is a bookmarked site, add a screenshot to the database.
2394 // FIXME: When should we update? Every time?
2395 // FIXME: Would like to make sure there is actually something to
2396 // draw, but the API for that (WebViewCore.pictureReady()) is not
2397 // currently accessible here.
Ben Murdochaac7aa62009-09-17 16:57:40 +01002398
Patrick Scottcb192b52010-04-14 14:38:55 -04002399 final Bitmap bm = createScreenshot(view);
2400 if (bm == null) {
2401 return;
Leon Scroggins89c6d362009-07-15 16:54:37 -04002402 }
Patrick Scottcb192b52010-04-14 14:38:55 -04002403
2404 final ContentResolver cr = getContentResolver();
2405 final String url = view.getUrl();
2406 final String originalUrl = view.getOriginalUrl();
2407
2408 new AsyncTask<Void, Void, Void>() {
2409 @Override
2410 protected Void doInBackground(Void... unused) {
2411 Cursor c = null;
2412 try {
2413 c = BrowserBookmarksAdapter.queryBookmarksForUrl(
2414 cr, originalUrl, url, true);
2415 if (c != null) {
2416 if (c.moveToFirst()) {
2417 ContentValues values = new ContentValues();
2418 final ByteArrayOutputStream os
2419 = new ByteArrayOutputStream();
2420 bm.compress(Bitmap.CompressFormat.PNG, 100, os);
2421 values.put(Browser.BookmarkColumns.THUMBNAIL,
2422 os.toByteArray());
2423 do {
2424 cr.update(ContentUris.withAppendedId(
2425 Browser.BOOKMARKS_URI, c.getInt(0)),
2426 values, null, null);
2427 } while (c.moveToNext());
2428 }
2429 }
2430 } catch (IllegalStateException e) {
2431 // Ignore
2432 } finally {
2433 if (c != null) c.close();
2434 }
2435 return null;
2436 }
2437 }.execute();
Leon Scroggins89c6d362009-07-15 16:54:37 -04002438 }
2439
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002440 /**
Leon Scrogginsf8551612009-09-24 16:06:02 -04002441 * Values for the size of the thumbnail created when taking a screenshot.
2442 * Lazily initialized. Instead of using these directly, use
2443 * getDesiredThumbnailWidth() or getDesiredThumbnailHeight().
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002444 */
Leon Scrogginsf8551612009-09-24 16:06:02 -04002445 private static int THUMBNAIL_WIDTH = 0;
2446 private static int THUMBNAIL_HEIGHT = 0;
2447
2448 /**
2449 * Return the desired width for thumbnail screenshots, which are stored in
2450 * the database, and used on the bookmarks screen.
2451 * @param context Context for finding out the density of the screen.
2452 * @return int desired width for thumbnail screenshot.
2453 */
2454 /* package */ static int getDesiredThumbnailWidth(Context context) {
2455 if (THUMBNAIL_WIDTH == 0) {
2456 float density = context.getResources().getDisplayMetrics().density;
2457 THUMBNAIL_WIDTH = (int) (90 * density);
2458 THUMBNAIL_HEIGHT = (int) (80 * density);
2459 }
2460 return THUMBNAIL_WIDTH;
2461 }
2462
2463 /**
2464 * Return the desired height for thumbnail screenshots, which are stored in
2465 * the database, and used on the bookmarks screen.
2466 * @param context Context for finding out the density of the screen.
2467 * @return int desired height for thumbnail screenshot.
2468 */
2469 /* package */ static int getDesiredThumbnailHeight(Context context) {
2470 // To ensure that they are both initialized.
2471 getDesiredThumbnailWidth(context);
2472 return THUMBNAIL_HEIGHT;
2473 }
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002474
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002475 private Bitmap createScreenshot(WebView view) {
2476 Picture thumbnail = view.capturePicture();
Leon Scroggins45800572009-09-29 16:38:47 -04002477 if (thumbnail == null) {
2478 return null;
2479 }
Leon Scrogginsf8551612009-09-24 16:06:02 -04002480 Bitmap bm = Bitmap.createBitmap(getDesiredThumbnailWidth(this),
Cary Clarkab168ba2010-04-08 09:11:28 -04002481 getDesiredThumbnailHeight(this), Bitmap.Config.RGB_565);
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002482 Canvas canvas = new Canvas(bm);
2483 // May need to tweak these values to determine what is the
2484 // best scale factor
Ben Murdoch2694e232009-09-29 09:41:11 +01002485 int thumbnailWidth = thumbnail.getWidth();
Ben Murdochae59c3f2009-10-20 18:30:28 +01002486 int thumbnailHeight = thumbnail.getHeight();
2487 float scaleFactorX = 1.0f;
2488 float scaleFactorY = 1.0f;
Ben Murdoch2694e232009-09-29 09:41:11 +01002489 if (thumbnailWidth > 0) {
Ben Murdochae59c3f2009-10-20 18:30:28 +01002490 scaleFactorX = (float) getDesiredThumbnailWidth(this) /
Ben Murdoch2694e232009-09-29 09:41:11 +01002491 (float)thumbnailWidth;
Ben Murdochae59c3f2009-10-20 18:30:28 +01002492 } else {
2493 return null;
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002494 }
Ben Murdochae59c3f2009-10-20 18:30:28 +01002495
2496 if (view.getWidth() > view.getHeight() &&
2497 thumbnailHeight < view.getHeight() && thumbnailHeight > 0) {
2498 // If the device is in landscape and the page is shorter
2499 // than the height of the view, stretch the thumbnail to fill the
2500 // space.
2501 scaleFactorY = (float) getDesiredThumbnailHeight(this) /
2502 (float)thumbnailHeight;
2503 } else {
2504 // In the portrait case, this looks nice.
2505 scaleFactorY = scaleFactorX;
2506 }
2507
2508 canvas.scale(scaleFactorX, scaleFactorY);
2509
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002510 thumbnail.draw(canvas);
2511 return bm;
2512 }
2513
The Android Open Source Project0c908882009-03-03 19:32:16 -08002514 // -------------------------------------------------------------------------
Grace Kloba22ac16e2009-10-07 18:00:23 -07002515 // Helper function for WebViewClient.
The Android Open Source Project0c908882009-03-03 19:32:16 -08002516 //-------------------------------------------------------------------------
2517
2518 // Use in overrideUrlLoading
2519 /* package */ final static String SCHEME_WTAI = "wtai://wp/";
2520 /* package */ final static String SCHEME_WTAI_MC = "wtai://wp/mc;";
2521 /* package */ final static String SCHEME_WTAI_SD = "wtai://wp/sd;";
2522 /* package */ final static String SCHEME_WTAI_AP = "wtai://wp/ap;";
2523
Leon Scroggins92472e82010-02-17 16:32:28 -05002524 // Keep this initial progress in sync with initialProgressValue (* 100)
2525 // in ProgressTracker.cpp
2526 private final static int INITIAL_PROGRESS = 10;
2527
Grace Kloba22ac16e2009-10-07 18:00:23 -07002528 void onPageStarted(WebView view, String url, Bitmap favicon) {
2529 // when BrowserActivity just starts, onPageStarted may be called before
2530 // onResume as it is triggered from onCreate. Call resumeWebViewTimers
2531 // to start the timer. As we won't switch tabs while an activity is in
2532 // pause state, we can ensure calling resume and pause in pair.
2533 if (mActivityInPause) resumeWebViewTimers();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002534
Grace Kloba22ac16e2009-10-07 18:00:23 -07002535 resetLockIcon(url);
2536 setUrlTitle(url, null);
2537 setFavicon(favicon);
Leon Scroggins8cf8f682009-11-04 11:13:50 -08002538 // Show some progress so that the user knows the page is beginning to
2539 // load
Leon Scroggins92472e82010-02-17 16:32:28 -05002540 onProgressChanged(view, INITIAL_PROGRESS);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002541 mDidStopLoad = false;
Grace Kloba22ac16e2009-10-07 18:00:23 -07002542 if (!mIsNetworkUp) createAndShowNetworkDialog();
Cary Clark2c326e62010-08-19 18:40:57 -04002543 closeDialogs();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002544 if (mSettings.isTracing()) {
2545 String host;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002546 try {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002547 WebAddress uri = new WebAddress(url);
2548 host = uri.mHost;
2549 } catch (android.net.ParseException ex) {
2550 host = "browser";
The Android Open Source Project0c908882009-03-03 19:32:16 -08002551 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002552 host = host.replace('.', '_');
2553 host += ".trace";
2554 mInTrace = true;
2555 Debug.startMethodTracing(host, 20 * 1024 * 1024);
2556 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002557
Grace Kloba22ac16e2009-10-07 18:00:23 -07002558 // Performance probe
2559 if (false) {
2560 mStart = SystemClock.uptimeMillis();
2561 mProcessStart = Process.getElapsedCpuTime();
2562 long[] sysCpu = new long[7];
2563 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2564 sysCpu, null)) {
2565 mUserStart = sysCpu[0] + sysCpu[1];
2566 mSystemStart = sysCpu[2];
2567 mIdleStart = sysCpu[3];
2568 mIrqStart = sysCpu[4] + sysCpu[5] + sysCpu[6];
2569 }
2570 mUiStart = SystemClock.currentThreadTimeMillis();
2571 }
2572 }
2573
2574 void onPageFinished(WebView view, String url) {
2575 // Reset the title and icon in case we stopped a provisional load.
2576 resetTitleAndIcon(view);
2577 // Update the lock icon image only once we are done loading
2578 updateLockIconToLatest();
2579 // pause the WebView timer and release the wake lock if it is finished
2580 // while BrowserActivity is in pause state.
2581 if (mActivityInPause && pauseWebViewTimers()) {
2582 if (mWakeLock.isHeld()) {
2583 mHandler.removeMessages(RELEASE_WAKELOCK);
2584 mWakeLock.release();
2585 }
2586 }
2587
2588 // Performance probe
2589 if (false) {
2590 long[] sysCpu = new long[7];
2591 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2592 sysCpu, null)) {
2593 String uiInfo = "UI thread used "
2594 + (SystemClock.currentThreadTimeMillis() - mUiStart)
2595 + " ms";
2596 if (LOGD_ENABLED) {
2597 Log.d(LOGTAG, uiInfo);
2598 }
2599 //The string that gets written to the log
2600 String performanceString = "It took total "
2601 + (SystemClock.uptimeMillis() - mStart)
2602 + " ms clock time to load the page."
2603 + "\nbrowser process used "
2604 + (Process.getElapsedCpuTime() - mProcessStart)
2605 + " ms, user processes used "
2606 + (sysCpu[0] + sysCpu[1] - mUserStart) * 10
2607 + " ms, kernel used "
2608 + (sysCpu[2] - mSystemStart) * 10
2609 + " ms, idle took " + (sysCpu[3] - mIdleStart) * 10
2610 + " ms and irq took "
2611 + (sysCpu[4] + sysCpu[5] + sysCpu[6] - mIrqStart)
2612 * 10 + " ms, " + uiInfo;
2613 if (LOGD_ENABLED) {
2614 Log.d(LOGTAG, performanceString + "\nWebpage: " + url);
2615 }
2616 if (url != null) {
2617 // strip the url to maintain consistency
2618 String newUrl = new String(url);
2619 if (newUrl.startsWith("http://www.")) {
2620 newUrl = newUrl.substring(11);
2621 } else if (newUrl.startsWith("http://")) {
2622 newUrl = newUrl.substring(7);
2623 } else if (newUrl.startsWith("https://www.")) {
2624 newUrl = newUrl.substring(12);
2625 } else if (newUrl.startsWith("https://")) {
2626 newUrl = newUrl.substring(8);
2627 }
2628 if (LOGD_ENABLED) {
2629 Log.d(LOGTAG, newUrl + " loaded");
2630 }
Grace Kloba5b078b52009-06-24 20:23:41 -07002631 }
2632 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002633 }
Grace Kloba5b078b52009-06-24 20:23:41 -07002634
Grace Kloba22ac16e2009-10-07 18:00:23 -07002635 if (mInTrace) {
2636 mInTrace = false;
2637 Debug.stopMethodTracing();
2638 }
2639 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002640
Grace Kloba22ac16e2009-10-07 18:00:23 -07002641 boolean shouldOverrideUrlLoading(WebView view, String url) {
2642 if (url.startsWith(SCHEME_WTAI)) {
2643 // wtai://wp/mc;number
2644 // number=string(phone-number)
2645 if (url.startsWith(SCHEME_WTAI_MC)) {
2646 Intent intent = new Intent(Intent.ACTION_VIEW,
2647 Uri.parse(WebView.SCHEME_TEL +
2648 url.substring(SCHEME_WTAI_MC.length())));
2649 startActivity(intent);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002650 return true;
2651 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002652 // wtai://wp/sd;dtmf
2653 // dtmf=string(dialstring)
2654 if (url.startsWith(SCHEME_WTAI_SD)) {
2655 // TODO: only send when there is active voice connection
2656 return false;
2657 }
2658 // wtai://wp/ap;number;name
2659 // number=string(phone-number)
2660 // name=string
2661 if (url.startsWith(SCHEME_WTAI_AP)) {
2662 // TODO
2663 return false;
2664 }
2665 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002666
Grace Kloba22ac16e2009-10-07 18:00:23 -07002667 // The "about:" schemes are internal to the browser; don't want these to
2668 // be dispatched to other apps.
2669 if (url.startsWith("about:")) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002670 return false;
2671 }
2672
Grace Kloba22ac16e2009-10-07 18:00:23 -07002673 Intent intent;
2674 // perform generic parsing of the URI to turn it into an Intent.
2675 try {
2676 intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME);
2677 } catch (URISyntaxException ex) {
2678 Log.w("Browser", "Bad URI " + url + ": " + ex.getMessage());
2679 return false;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002680 }
2681
Grace Kloba22ac16e2009-10-07 18:00:23 -07002682 // check whether the intent can be resolved. If not, we will see
2683 // whether we can download it from the Market.
2684 if (getPackageManager().resolveActivity(intent, 0) == null) {
2685 String packagename = intent.getPackage();
2686 if (packagename != null) {
2687 intent = new Intent(Intent.ACTION_VIEW, Uri
2688 .parse("market://search?q=pname:" + packagename));
2689 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2690 startActivity(intent);
2691 return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002692 } else {
2693 return false;
2694 }
2695 }
2696
Grace Kloba22ac16e2009-10-07 18:00:23 -07002697 // sanitize the Intent, ensuring web pages can not bypass browser
2698 // security (only access to BROWSABLE activities).
2699 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2700 intent.setComponent(null);
2701 try {
2702 if (startActivityIfNeeded(intent, -1)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002703 return true;
2704 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002705 } catch (ActivityNotFoundException ex) {
2706 // ignore the error. If no application can handle the URL,
2707 // eg about:blank, assume the browser can handle it.
2708 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002709
Grace Kloba22ac16e2009-10-07 18:00:23 -07002710 if (mMenuIsDown) {
2711 openTab(url);
2712 closeOptionsMenu();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002713 return true;
2714 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002715 return false;
2716 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002717
Grace Kloba22ac16e2009-10-07 18:00:23 -07002718 // -------------------------------------------------------------------------
2719 // Helper function for WebChromeClient
2720 // -------------------------------------------------------------------------
The Android Open Source Project0c908882009-03-03 19:32:16 -08002721
Grace Kloba22ac16e2009-10-07 18:00:23 -07002722 void onProgressChanged(WebView view, int newProgress) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002723 mFakeTitleBar.setProgress(newProgress);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002724
Grace Kloba22ac16e2009-10-07 18:00:23 -07002725 if (newProgress == 100) {
2726 // onProgressChanged() may continue to be called after the main
2727 // frame has finished loading, as any remaining sub frames continue
2728 // to load. We'll only get called once though with newProgress as
2729 // 100 when everything is loaded. (onPageFinished is called once
2730 // when the main frame completes loading regardless of the state of
2731 // any sub frames so calls to onProgressChanges may continue after
2732 // onPageFinished has executed)
2733 if (mInLoad) {
2734 mInLoad = false;
Leon Scrogginsa27ff192009-09-14 12:58:04 -04002735 updateInLoadMenuItems();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002736 // If the options menu is open, leave the title bar
2737 if (!mOptionsMenuOpen || !mIconView) {
2738 hideFakeTitleBar();
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07002739 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002740 }
Leon Scrogginsaa37e7f2010-03-05 11:51:20 -05002741 } else {
2742 if (!mInLoad) {
2743 // onPageFinished may have already been called but a subframe is
2744 // still loading and updating the progress. Reset mInLoad and
2745 // update the menu items.
2746 mInLoad = true;
2747 updateInLoadMenuItems();
2748 }
2749 // When the page first begins to load, the Activity may still be
2750 // paused, in which case showFakeTitleBar will do nothing. Call
2751 // again as the page continues to load so that it will be shown.
2752 // (Calling it will the fake title bar is already showing will also
2753 // do nothing.
Grace Kloba22ac16e2009-10-07 18:00:23 -07002754 if (!mOptionsMenuOpen || mIconView) {
2755 // This page has begun to load, so show the title bar
2756 showFakeTitleBar();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002757 }
2758 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002759 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002760
Grace Kloba22ac16e2009-10-07 18:00:23 -07002761 void onShowCustomView(View view, WebChromeClient.CustomViewCallback callback) {
Derek Sollenberger8ff57db2009-12-08 15:39:55 -05002762 // if a view already exists then immediately terminate the new one
2763 if (mCustomView != null) {
2764 callback.onCustomViewHidden();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002765 return;
Derek Sollenberger8ff57db2009-12-08 15:39:55 -05002766 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002767
2768 // Add the custom view to its container.
2769 mCustomViewContainer.addView(view, COVER_SCREEN_GRAVITY_CENTER);
2770 mCustomView = view;
2771 mCustomViewCallback = callback;
2772 // Save the menu state and set it to empty while the custom
2773 // view is showing.
2774 mOldMenuState = mMenuState;
2775 mMenuState = EMPTY_MENU;
2776 // Hide the content view.
2777 mContentView.setVisibility(View.GONE);
2778 // Finally show the custom view container.
Andrei Popescu163ab742009-10-20 17:58:23 +01002779 setStatusBarVisibility(false);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002780 mCustomViewContainer.setVisibility(View.VISIBLE);
2781 mCustomViewContainer.bringToFront();
2782 }
2783
2784 void onHideCustomView() {
2785 if (mCustomView == null)
2786 return;
2787
2788 // Hide the custom view.
2789 mCustomView.setVisibility(View.GONE);
2790 // Remove the custom view from its container.
2791 mCustomViewContainer.removeView(mCustomView);
2792 mCustomView = null;
2793 // Reset the old menu state.
2794 mMenuState = mOldMenuState;
2795 mOldMenuState = EMPTY_MENU;
2796 mCustomViewContainer.setVisibility(View.GONE);
2797 mCustomViewCallback.onCustomViewHidden();
2798 // Show the content view.
Andrei Popescu163ab742009-10-20 17:58:23 +01002799 setStatusBarVisibility(true);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002800 mContentView.setVisibility(View.VISIBLE);
2801 }
2802
2803 Bitmap getDefaultVideoPoster() {
2804 if (mDefaultVideoPoster == null) {
2805 mDefaultVideoPoster = BitmapFactory.decodeResource(
2806 getResources(), R.drawable.default_video_poster);
Patrick Scott3918d442009-08-04 13:22:29 -04002807 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002808 return mDefaultVideoPoster;
2809 }
Patrick Scott3918d442009-08-04 13:22:29 -04002810
Grace Kloba22ac16e2009-10-07 18:00:23 -07002811 View getVideoLoadingProgressView() {
2812 if (mVideoProgressView == null) {
2813 LayoutInflater inflater = LayoutInflater.from(BrowserActivity.this);
2814 mVideoProgressView = inflater.inflate(
2815 R.layout.video_loading_progress, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002816 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002817 return mVideoProgressView;
2818 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002819
Leon Scroggins8d5fa432009-10-02 15:55:59 -04002820 /*
2821 * The Object used to inform the WebView of the file to upload.
2822 */
2823 private ValueCallback<Uri> mUploadMessage;
2824
Grace Kloba22ac16e2009-10-07 18:00:23 -07002825 void openFileChooser(ValueCallback<Uri> uploadMsg) {
2826 if (mUploadMessage != null) return;
2827 mUploadMessage = uploadMsg;
2828 Intent i = new Intent(Intent.ACTION_GET_CONTENT);
2829 i.addCategory(Intent.CATEGORY_OPENABLE);
2830 i.setType("*/*");
2831 BrowserActivity.this.startActivityForResult(Intent.createChooser(i,
2832 getString(R.string.choose_upload)), FILE_SELECTED);
2833 }
2834
2835 // -------------------------------------------------------------------------
2836 // Implement functions for DownloadListener
2837 // -------------------------------------------------------------------------
2838
The Android Open Source Project0c908882009-03-03 19:32:16 -08002839 /**
2840 * Notify the host application a download should be done, or that
2841 * the data should be streamed if a streaming viewer is available.
2842 * @param url The full url to the content that should be downloaded
2843 * @param contentDisposition Content-disposition http header, if
2844 * present.
2845 * @param mimetype The mimetype of the content reported by the server
2846 * @param contentLength The file size reported by the server
2847 */
2848 public void onDownloadStart(String url, String userAgent,
2849 String contentDisposition, String mimetype, long contentLength) {
2850 // if we're dealing wih A/V content that's not explicitly marked
2851 // for download, check if it's streamable.
2852 if (contentDisposition == null
Patrick Scotte1fb9662009-08-31 14:31:52 -04002853 || !contentDisposition.regionMatches(
2854 true, 0, "attachment", 0, 10)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002855 // query the package manager to see if there's a registered handler
2856 // that matches.
2857 Intent intent = new Intent(Intent.ACTION_VIEW);
2858 intent.setDataAndType(Uri.parse(url), mimetype);
Patrick Scotte1fb9662009-08-31 14:31:52 -04002859 ResolveInfo info = getPackageManager().resolveActivity(intent,
2860 PackageManager.MATCH_DEFAULT_ONLY);
2861 if (info != null) {
2862 ComponentName myName = getComponentName();
2863 // If we resolved to ourselves, we don't want to attempt to
2864 // load the url only to try and download it again.
2865 if (!myName.getPackageName().equals(
2866 info.activityInfo.packageName)
2867 || !myName.getClassName().equals(
2868 info.activityInfo.name)) {
2869 // someone (other than us) knows how to handle this mime
2870 // type with this scheme, don't download.
2871 try {
2872 startActivity(intent);
2873 return;
2874 } catch (ActivityNotFoundException ex) {
2875 if (LOGD_ENABLED) {
2876 Log.d(LOGTAG, "activity not found for " + mimetype
2877 + " over " + Uri.parse(url).getScheme(),
2878 ex);
2879 }
2880 // Best behavior is to fall back to a download in this
2881 // case
The Android Open Source Project0c908882009-03-03 19:32:16 -08002882 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002883 }
2884 }
2885 }
2886 onDownloadStartNoStream(url, userAgent, contentDisposition, mimetype, contentLength);
2887 }
2888
Kristian Monsenfa52d172010-03-25 18:29:21 +00002889 // This is to work around the fact that java.net.URI throws Exceptions
2890 // instead of just encoding URL's properly
2891 // Helper method for onDownloadStartNoStream
2892 private static String encodePath(String path) {
2893 char[] chars = path.toCharArray();
2894
2895 boolean needed = false;
2896 for (char c : chars) {
2897 if (c == '[' || c == ']') {
2898 needed = true;
2899 break;
2900 }
2901 }
2902 if (needed == false) {
2903 return path;
2904 }
2905
2906 StringBuilder sb = new StringBuilder("");
2907 for (char c : chars) {
2908 if (c == '[' || c == ']') {
2909 sb.append('%');
2910 sb.append(Integer.toHexString(c));
2911 } else {
2912 sb.append(c);
2913 }
2914 }
2915
2916 return sb.toString();
2917 }
2918
The Android Open Source Project0c908882009-03-03 19:32:16 -08002919 /**
2920 * Notify the host application a download should be done, even if there
2921 * is a streaming viewer available for thise type.
2922 * @param url The full url to the content that should be downloaded
2923 * @param contentDisposition Content-disposition http header, if
2924 * present.
2925 * @param mimetype The mimetype of the content reported by the server
2926 * @param contentLength The file size reported by the server
2927 */
2928 /*package */ void onDownloadStartNoStream(String url, String userAgent,
2929 String contentDisposition, String mimetype, long contentLength) {
2930
2931 String filename = URLUtil.guessFileName(url,
2932 contentDisposition, mimetype);
2933
2934 // Check to see if we have an SDCard
2935 String status = Environment.getExternalStorageState();
2936 if (!status.equals(Environment.MEDIA_MOUNTED)) {
2937 int title;
2938 String msg;
2939
2940 // Check to see if the SDCard is busy, same as the music app
2941 if (status.equals(Environment.MEDIA_SHARED)) {
2942 msg = getString(R.string.download_sdcard_busy_dlg_msg);
2943 title = R.string.download_sdcard_busy_dlg_title;
2944 } else {
2945 msg = getString(R.string.download_no_sdcard_dlg_msg, filename);
2946 title = R.string.download_no_sdcard_dlg_title;
2947 }
2948
2949 new AlertDialog.Builder(this)
2950 .setTitle(title)
2951 .setIcon(android.R.drawable.ic_dialog_alert)
2952 .setMessage(msg)
2953 .setPositiveButton(R.string.ok, null)
2954 .show();
2955 return;
2956 }
2957
Kristian Monsenfa52d172010-03-25 18:29:21 +00002958 // java.net.URI is a lot stricter than KURL so we have to encode some
2959 // extra characters. Fix for b 2538060 and b 1634719
2960 WebAddress webAddress;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002961 try {
Kristian Monsenfa52d172010-03-25 18:29:21 +00002962 webAddress = new WebAddress(url);
2963 webAddress.mPath = encodePath(webAddress.mPath);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002964 } catch (Exception e) {
Kristian Monsenfa52d172010-03-25 18:29:21 +00002965 // This only happens for very bad urls, we want to chatch the
2966 // exception here
2967 Log.e(LOGTAG, "Exception trying to parse url:" + url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002968 return;
2969 }
2970
2971 // XXX: Have to use the old url since the cookies were stored using the
2972 // old percent-encoded url.
2973 String cookies = CookieManager.getInstance().getCookie(url);
2974
2975 ContentValues values = new ContentValues();
Kristian Monsenfa52d172010-03-25 18:29:21 +00002976 values.put(Downloads.Impl.COLUMN_URI, webAddress.toString());
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08002977 values.put(Downloads.Impl.COLUMN_COOKIE_DATA, cookies);
2978 values.put(Downloads.Impl.COLUMN_USER_AGENT, userAgent);
2979 values.put(Downloads.Impl.COLUMN_NOTIFICATION_PACKAGE,
The Android Open Source Project0c908882009-03-03 19:32:16 -08002980 getPackageName());
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08002981 values.put(Downloads.Impl.COLUMN_NOTIFICATION_CLASS,
Leon Scrogginsa563d092010-04-19 16:53:49 -04002982 OpenDownloadReceiver.class.getCanonicalName());
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08002983 values.put(Downloads.Impl.COLUMN_VISIBILITY,
2984 Downloads.Impl.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
2985 values.put(Downloads.Impl.COLUMN_MIME_TYPE, mimetype);
2986 values.put(Downloads.Impl.COLUMN_FILE_NAME_HINT, filename);
Kristian Monsenfa52d172010-03-25 18:29:21 +00002987 values.put(Downloads.Impl.COLUMN_DESCRIPTION, webAddress.mHost);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002988 if (contentLength > 0) {
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08002989 values.put(Downloads.Impl.COLUMN_TOTAL_BYTES, contentLength);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002990 }
2991 if (mimetype == null) {
2992 // We must have long pressed on a link or image to download it. We
2993 // are not sure of the mimetype in this case, so do a head request
2994 new FetchUrlMimeType(this).execute(values);
2995 } else {
2996 final Uri contentUri =
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08002997 getContentResolver().insert(Downloads.Impl.CONTENT_URI, values);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002998 }
Leon Scroggins9191a7f2010-03-18 14:44:44 -04002999 Toast.makeText(this, R.string.download_pending, Toast.LENGTH_SHORT)
3000 .show();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003001 }
3002
Grace Kloba22ac16e2009-10-07 18:00:23 -07003003 // -------------------------------------------------------------------------
3004
The Android Open Source Project0c908882009-03-03 19:32:16 -08003005 /**
3006 * Resets the lock icon. This method is called when we start a new load and
3007 * know the url to be loaded.
3008 */
3009 private void resetLockIcon(String url) {
3010 // Save the lock-icon state (we revert to it if the load gets cancelled)
Grace Kloba22ac16e2009-10-07 18:00:23 -07003011 mTabControl.getCurrentTab().resetLockIcon(url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003012 updateLockIconImage(LOCK_ICON_UNSECURE);
3013 }
3014
The Android Open Source Project0c908882009-03-03 19:32:16 -08003015 /**
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04003016 * Update the lock icon to correspond to our latest state.
3017 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003018 private void updateLockIconToLatest() {
3019 updateLockIconImage(mTabControl.getCurrentTab().getLockIconType());
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04003020 }
3021
3022 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08003023 * Updates the lock-icon image in the title-bar.
3024 */
3025 private void updateLockIconImage(int lockIconType) {
3026 Drawable d = null;
3027 if (lockIconType == LOCK_ICON_SECURE) {
3028 d = mSecLockIcon;
3029 } else if (lockIconType == LOCK_ICON_MIXED) {
3030 d = mMixLockIcon;
3031 }
Leon Scroggins68579392009-09-15 15:31:54 -04003032 mTitleBar.setLock(d);
Leon Scrogginsfe87bd32009-10-06 10:10:00 -04003033 mFakeTitleBar.setLock(d);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003034 }
3035
3036 /**
3037 * Displays a page-info dialog.
3038 * @param tab The tab to show info about
3039 * @param fromShowSSLCertificateOnError The flag that indicates whether
3040 * this dialog was opened from the SSL-certificate-on-error dialog or
3041 * not. This is important, since we need to know whether to return to
3042 * the parent dialog or simply dismiss.
3043 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003044 private void showPageInfo(final Tab tab,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003045 final boolean fromShowSSLCertificateOnError) {
3046 final LayoutInflater factory = LayoutInflater
3047 .from(this);
3048
3049 final View pageInfoView = factory.inflate(R.layout.page_info, null);
3050
3051 final WebView view = tab.getWebView();
3052
3053 String url = null;
3054 String title = null;
3055
3056 if (view == null) {
3057 url = tab.getUrl();
3058 title = tab.getTitle();
3059 } else if (view == mTabControl.getCurrentWebView()) {
3060 // Use the cached title and url if this is the current WebView
3061 url = mUrl;
3062 title = mTitle;
3063 } else {
3064 url = view.getUrl();
3065 title = view.getTitle();
3066 }
3067
3068 if (url == null) {
3069 url = "";
3070 }
3071 if (title == null) {
3072 title = "";
3073 }
3074
3075 ((TextView) pageInfoView.findViewById(R.id.address)).setText(url);
3076 ((TextView) pageInfoView.findViewById(R.id.title)).setText(title);
3077
3078 mPageInfoView = tab;
Leon Scrogginsc7b92f82010-01-11 18:17:31 -05003079 mPageInfoFromShowSSLCertificateOnError = fromShowSSLCertificateOnError;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003080
3081 AlertDialog.Builder alertDialogBuilder =
3082 new AlertDialog.Builder(this)
3083 .setTitle(R.string.page_info).setIcon(android.R.drawable.ic_dialog_info)
3084 .setView(pageInfoView)
3085 .setPositiveButton(
3086 R.string.ok,
3087 new DialogInterface.OnClickListener() {
3088 public void onClick(DialogInterface dialog,
3089 int whichButton) {
3090 mPageInfoDialog = null;
3091 mPageInfoView = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003092
3093 // if we came here from the SSL error dialog
3094 if (fromShowSSLCertificateOnError) {
3095 // go back to the SSL error dialog
3096 showSSLCertificateOnError(
3097 mSSLCertificateOnErrorView,
3098 mSSLCertificateOnErrorHandler,
3099 mSSLCertificateOnErrorError);
3100 }
3101 }
3102 })
3103 .setOnCancelListener(
3104 new DialogInterface.OnCancelListener() {
3105 public void onCancel(DialogInterface dialog) {
3106 mPageInfoDialog = null;
3107 mPageInfoView = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003108
3109 // if we came here from the SSL error dialog
3110 if (fromShowSSLCertificateOnError) {
3111 // go back to the SSL error dialog
3112 showSSLCertificateOnError(
3113 mSSLCertificateOnErrorView,
3114 mSSLCertificateOnErrorHandler,
3115 mSSLCertificateOnErrorError);
3116 }
3117 }
3118 });
3119
3120 // if we have a main top-level page SSL certificate set or a certificate
3121 // error
3122 if (fromShowSSLCertificateOnError ||
3123 (view != null && view.getCertificate() != null)) {
3124 // add a 'View Certificate' button
3125 alertDialogBuilder.setNeutralButton(
3126 R.string.view_certificate,
3127 new DialogInterface.OnClickListener() {
3128 public void onClick(DialogInterface dialog,
3129 int whichButton) {
3130 mPageInfoDialog = null;
3131 mPageInfoView = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003132
3133 // if we came here from the SSL error dialog
3134 if (fromShowSSLCertificateOnError) {
3135 // go back to the SSL error dialog
3136 showSSLCertificateOnError(
3137 mSSLCertificateOnErrorView,
3138 mSSLCertificateOnErrorHandler,
3139 mSSLCertificateOnErrorError);
3140 } else {
3141 // otherwise, display the top-most certificate from
3142 // the chain
3143 if (view.getCertificate() != null) {
3144 showSSLCertificate(tab);
3145 }
3146 }
3147 }
3148 });
3149 }
3150
3151 mPageInfoDialog = alertDialogBuilder.show();
3152 }
3153
3154 /**
3155 * Displays the main top-level page SSL certificate dialog
3156 * (accessible from the Page-Info dialog).
3157 * @param tab The tab to show certificate for.
3158 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003159 private void showSSLCertificate(final Tab tab) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003160 final View certificateView =
3161 inflateCertificateView(tab.getWebView().getCertificate());
3162 if (certificateView == null) {
3163 return;
3164 }
3165
3166 LayoutInflater factory = LayoutInflater.from(this);
3167
3168 final LinearLayout placeholder =
3169 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3170
3171 LinearLayout ll = (LinearLayout) factory.inflate(
3172 R.layout.ssl_success, placeholder);
3173 ((TextView)ll.findViewById(R.id.success))
3174 .setText(R.string.ssl_certificate_is_valid);
3175
3176 mSSLCertificateView = tab;
3177 mSSLCertificateDialog =
3178 new AlertDialog.Builder(this)
3179 .setTitle(R.string.ssl_certificate).setIcon(
3180 R.drawable.ic_dialog_browser_certificate_secure)
3181 .setView(certificateView)
3182 .setPositiveButton(R.string.ok,
3183 new DialogInterface.OnClickListener() {
3184 public void onClick(DialogInterface dialog,
3185 int whichButton) {
3186 mSSLCertificateDialog = null;
3187 mSSLCertificateView = null;
3188
3189 showPageInfo(tab, false);
3190 }
3191 })
3192 .setOnCancelListener(
3193 new DialogInterface.OnCancelListener() {
3194 public void onCancel(DialogInterface dialog) {
3195 mSSLCertificateDialog = null;
3196 mSSLCertificateView = null;
3197
3198 showPageInfo(tab, false);
3199 }
3200 })
3201 .show();
3202 }
3203
3204 /**
3205 * Displays the SSL error certificate dialog.
3206 * @param view The target web-view.
3207 * @param handler The SSL error handler responsible for cancelling the
3208 * connection that resulted in an SSL error or proceeding per user request.
3209 * @param error The SSL error object.
3210 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003211 void showSSLCertificateOnError(
The Android Open Source Project0c908882009-03-03 19:32:16 -08003212 final WebView view, final SslErrorHandler handler, final SslError error) {
3213
3214 final View certificateView =
3215 inflateCertificateView(error.getCertificate());
3216 if (certificateView == null) {
3217 return;
3218 }
3219
3220 LayoutInflater factory = LayoutInflater.from(this);
3221
3222 final LinearLayout placeholder =
3223 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3224
3225 if (error.hasError(SslError.SSL_UNTRUSTED)) {
3226 LinearLayout ll = (LinearLayout)factory
3227 .inflate(R.layout.ssl_warning, placeholder);
3228 ((TextView)ll.findViewById(R.id.warning))
3229 .setText(R.string.ssl_untrusted);
3230 }
3231
3232 if (error.hasError(SslError.SSL_IDMISMATCH)) {
3233 LinearLayout ll = (LinearLayout)factory
3234 .inflate(R.layout.ssl_warning, placeholder);
3235 ((TextView)ll.findViewById(R.id.warning))
3236 .setText(R.string.ssl_mismatch);
3237 }
3238
3239 if (error.hasError(SslError.SSL_EXPIRED)) {
3240 LinearLayout ll = (LinearLayout)factory
3241 .inflate(R.layout.ssl_warning, placeholder);
3242 ((TextView)ll.findViewById(R.id.warning))
3243 .setText(R.string.ssl_expired);
3244 }
3245
3246 if (error.hasError(SslError.SSL_NOTYETVALID)) {
3247 LinearLayout ll = (LinearLayout)factory
3248 .inflate(R.layout.ssl_warning, placeholder);
3249 ((TextView)ll.findViewById(R.id.warning))
3250 .setText(R.string.ssl_not_yet_valid);
3251 }
3252
3253 mSSLCertificateOnErrorHandler = handler;
3254 mSSLCertificateOnErrorView = view;
3255 mSSLCertificateOnErrorError = error;
3256 mSSLCertificateOnErrorDialog =
3257 new AlertDialog.Builder(this)
3258 .setTitle(R.string.ssl_certificate).setIcon(
3259 R.drawable.ic_dialog_browser_certificate_partially_secure)
3260 .setView(certificateView)
3261 .setPositiveButton(R.string.ok,
3262 new DialogInterface.OnClickListener() {
3263 public void onClick(DialogInterface dialog,
3264 int whichButton) {
3265 mSSLCertificateOnErrorDialog = null;
3266 mSSLCertificateOnErrorView = null;
3267 mSSLCertificateOnErrorHandler = null;
3268 mSSLCertificateOnErrorError = null;
3269
Grace Kloba22ac16e2009-10-07 18:00:23 -07003270 view.getWebViewClient().onReceivedSslError(
3271 view, handler, error);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003272 }
3273 })
3274 .setNeutralButton(R.string.page_info_view,
3275 new DialogInterface.OnClickListener() {
3276 public void onClick(DialogInterface dialog,
3277 int whichButton) {
3278 mSSLCertificateOnErrorDialog = null;
3279
3280 // do not clear the dialog state: we will
3281 // need to show the dialog again once the
3282 // user is done exploring the page-info details
3283
3284 showPageInfo(mTabControl.getTabFromView(view),
3285 true);
3286 }
3287 })
3288 .setOnCancelListener(
3289 new DialogInterface.OnCancelListener() {
3290 public void onCancel(DialogInterface dialog) {
3291 mSSLCertificateOnErrorDialog = null;
3292 mSSLCertificateOnErrorView = null;
3293 mSSLCertificateOnErrorHandler = null;
3294 mSSLCertificateOnErrorError = null;
3295
Grace Kloba22ac16e2009-10-07 18:00:23 -07003296 view.getWebViewClient().onReceivedSslError(
3297 view, handler, error);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003298 }
3299 })
3300 .show();
3301 }
3302
3303 /**
3304 * Inflates the SSL certificate view (helper method).
3305 * @param certificate The SSL certificate.
3306 * @return The resultant certificate view with issued-to, issued-by,
3307 * issued-on, expires-on, and possibly other fields set.
3308 * If the input certificate is null, returns null.
3309 */
3310 private View inflateCertificateView(SslCertificate certificate) {
3311 if (certificate == null) {
3312 return null;
3313 }
3314
3315 LayoutInflater factory = LayoutInflater.from(this);
3316
3317 View certificateView = factory.inflate(
3318 R.layout.ssl_certificate, null);
3319
3320 // issued to:
3321 SslCertificate.DName issuedTo = certificate.getIssuedTo();
3322 if (issuedTo != null) {
3323 ((TextView) certificateView.findViewById(R.id.to_common))
3324 .setText(issuedTo.getCName());
3325 ((TextView) certificateView.findViewById(R.id.to_org))
3326 .setText(issuedTo.getOName());
3327 ((TextView) certificateView.findViewById(R.id.to_org_unit))
3328 .setText(issuedTo.getUName());
3329 }
3330
3331 // issued by:
3332 SslCertificate.DName issuedBy = certificate.getIssuedBy();
3333 if (issuedBy != null) {
3334 ((TextView) certificateView.findViewById(R.id.by_common))
3335 .setText(issuedBy.getCName());
3336 ((TextView) certificateView.findViewById(R.id.by_org))
3337 .setText(issuedBy.getOName());
3338 ((TextView) certificateView.findViewById(R.id.by_org_unit))
3339 .setText(issuedBy.getUName());
3340 }
3341
3342 // issued on:
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003343 String issuedOn = formatCertificateDate(
3344 certificate.getValidNotBeforeDate());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003345 ((TextView) certificateView.findViewById(R.id.issued_on))
3346 .setText(issuedOn);
3347
3348 // expires on:
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003349 String expiresOn = formatCertificateDate(
3350 certificate.getValidNotAfterDate());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003351 ((TextView) certificateView.findViewById(R.id.expires_on))
3352 .setText(expiresOn);
3353
3354 return certificateView;
3355 }
3356
3357 /**
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003358 * Formats the certificate date to a properly localized date string.
The Android Open Source Project0c908882009-03-03 19:32:16 -08003359 * @return Properly localized version of the certificate date string and
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003360 * the "" if it fails to localize.
The Android Open Source Project0c908882009-03-03 19:32:16 -08003361 */
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003362 private String formatCertificateDate(Date certificateDate) {
3363 if (certificateDate == null) {
3364 return "";
The Android Open Source Project0c908882009-03-03 19:32:16 -08003365 }
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003366 String formattedDate = DateFormat.getDateFormat(this).format(certificateDate);
3367 if (formattedDate == null) {
3368 return "";
3369 }
3370 return formattedDate;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003371 }
3372
3373 /**
3374 * Displays an http-authentication dialog.
3375 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003376 void showHttpAuthentication(final HttpAuthHandler handler,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003377 final String host, final String realm, final String title,
3378 final String name, final String password, int focusId) {
3379 LayoutInflater factory = LayoutInflater.from(this);
3380 final View v = factory
3381 .inflate(R.layout.http_authentication, null);
3382 if (name != null) {
3383 ((EditText) v.findViewById(R.id.username_edit)).setText(name);
3384 }
3385 if (password != null) {
3386 ((EditText) v.findViewById(R.id.password_edit)).setText(password);
3387 }
3388
3389 String titleText = title;
3390 if (titleText == null) {
3391 titleText = getText(R.string.sign_in_to).toString().replace(
3392 "%s1", host).replace("%s2", realm);
3393 }
3394
3395 mHttpAuthHandler = handler;
3396 AlertDialog dialog = new AlertDialog.Builder(this)
3397 .setTitle(titleText)
3398 .setIcon(android.R.drawable.ic_dialog_alert)
3399 .setView(v)
3400 .setPositiveButton(R.string.action,
3401 new DialogInterface.OnClickListener() {
3402 public void onClick(DialogInterface dialog,
3403 int whichButton) {
3404 String nm = ((EditText) v
3405 .findViewById(R.id.username_edit))
3406 .getText().toString();
3407 String pw = ((EditText) v
3408 .findViewById(R.id.password_edit))
3409 .getText().toString();
3410 BrowserActivity.this.setHttpAuthUsernamePassword
3411 (host, realm, nm, pw);
3412 handler.proceed(nm, pw);
3413 mHttpAuthenticationDialog = null;
3414 mHttpAuthHandler = null;
3415 }})
3416 .setNegativeButton(R.string.cancel,
3417 new DialogInterface.OnClickListener() {
3418 public void onClick(DialogInterface dialog,
3419 int whichButton) {
3420 handler.cancel();
3421 BrowserActivity.this.resetTitleAndRevertLockIcon();
3422 mHttpAuthenticationDialog = null;
3423 mHttpAuthHandler = null;
3424 }})
3425 .setOnCancelListener(new DialogInterface.OnCancelListener() {
3426 public void onCancel(DialogInterface dialog) {
3427 handler.cancel();
3428 BrowserActivity.this.resetTitleAndRevertLockIcon();
3429 mHttpAuthenticationDialog = null;
3430 mHttpAuthHandler = null;
3431 }})
3432 .create();
3433 // Make the IME appear when the dialog is displayed if applicable.
3434 dialog.getWindow().setSoftInputMode(
3435 WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
3436 dialog.show();
3437 if (focusId != 0) {
3438 dialog.findViewById(focusId).requestFocus();
3439 } else {
3440 v.findViewById(R.id.username_edit).requestFocus();
3441 }
3442 mHttpAuthenticationDialog = dialog;
3443 }
3444
3445 public int getProgress() {
3446 WebView w = mTabControl.getCurrentWebView();
3447 if (w != null) {
3448 return w.getProgress();
3449 } else {
3450 return 100;
3451 }
3452 }
3453
3454 /**
3455 * Set HTTP authentication password.
3456 *
3457 * @param host The host for the password
3458 * @param realm The realm for the password
3459 * @param username The username for the password. If it is null, it means
3460 * password can't be saved.
3461 * @param password The password
3462 */
3463 public void setHttpAuthUsernamePassword(String host, String realm,
3464 String username,
3465 String password) {
Steve Block95a53b22010-03-25 17:24:58 +00003466 WebView w = getTopWindow();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003467 if (w != null) {
3468 w.setHttpAuthUsernamePassword(host, realm, username, password);
3469 }
3470 }
3471
3472 /**
3473 * connectivity manager says net has come or gone... inform the user
3474 * @param up true if net has come up, false if net has gone down
3475 */
3476 public void onNetworkToggle(boolean up) {
3477 if (up == mIsNetworkUp) {
3478 return;
3479 } else if (up) {
3480 mIsNetworkUp = true;
3481 if (mAlertDialog != null) {
3482 mAlertDialog.cancel();
3483 mAlertDialog = null;
3484 }
3485 } else {
3486 mIsNetworkUp = false;
Patrick Scotteb6ab2a2009-09-16 10:00:17 -04003487 if (mInLoad) {
3488 createAndShowNetworkDialog();
3489 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003490 }
3491 WebView w = mTabControl.getCurrentWebView();
3492 if (w != null) {
3493 w.setNetworkAvailable(up);
3494 }
3495 }
3496
Grace Kloba22ac16e2009-10-07 18:00:23 -07003497 boolean isNetworkUp() {
3498 return mIsNetworkUp;
3499 }
3500
Patrick Scotteb6ab2a2009-09-16 10:00:17 -04003501 // This method shows the network dialog alerting the user that the net is
3502 // down. It will only show the dialog if mAlertDialog is null.
3503 private void createAndShowNetworkDialog() {
3504 if (mAlertDialog == null) {
3505 mAlertDialog = new AlertDialog.Builder(this)
3506 .setTitle(R.string.loadSuspendedTitle)
3507 .setMessage(R.string.loadSuspended)
3508 .setPositiveButton(R.string.ok, null)
3509 .show();
3510 }
3511 }
3512
The Android Open Source Project0c908882009-03-03 19:32:16 -08003513 @Override
3514 protected void onActivityResult(int requestCode, int resultCode,
3515 Intent intent) {
Grace Klobabb394f32009-11-19 10:26:37 -08003516 if (getTopWindow() == null) return;
3517
The Android Open Source Project0c908882009-03-03 19:32:16 -08003518 switch (requestCode) {
3519 case COMBO_PAGE:
3520 if (resultCode == RESULT_OK && intent != null) {
3521 String data = intent.getAction();
3522 Bundle extras = intent.getExtras();
3523 if (extras != null && extras.getBoolean("new_window", false)) {
Leon Scroggins25d35472009-09-15 11:37:27 -04003524 openTab(data);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003525 } else {
Grace Kloba22ac16e2009-10-07 18:00:23 -07003526 final Tab currentTab =
The Android Open Source Project0c908882009-03-03 19:32:16 -08003527 mTabControl.getCurrentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04003528 dismissSubWindow(currentTab);
3529 if (data != null && data.length() != 0) {
Leon Scroggins92472e82010-02-17 16:32:28 -05003530 loadUrl(getTopWindow(), data);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003531 }
3532 }
3533 }
Leon Scrogginsfde97462010-01-11 13:06:21 -05003534 // Deliberately fall through to PREFERENCES_PAGE, since the
3535 // same extra may be attached to the COMBO_PAGE
3536 case PREFERENCES_PAGE:
3537 if (resultCode == RESULT_OK && intent != null) {
3538 String action = intent.getStringExtra(Intent.EXTRA_TEXT);
3539 if (BrowserSettings.PREF_CLEAR_HISTORY.equals(action)) {
3540 mTabControl.removeParentChildRelationShips();
3541 }
3542 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003543 break;
Leon Scroggins8d5fa432009-10-02 15:55:59 -04003544 // Choose a file from the file picker.
3545 case FILE_SELECTED:
3546 if (null == mUploadMessage) break;
3547 Uri result = intent == null || resultCode != RESULT_OK ? null
3548 : intent.getData();
3549 mUploadMessage.onReceiveValue(result);
3550 mUploadMessage = null;
3551 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003552 default:
3553 break;
3554 }
Leon Scroggins30444232009-09-04 18:36:20 -04003555 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003556 }
3557
3558 /*
3559 * This method is called as a result of the user selecting the options
Leon Scrogginsf08809b2010-01-21 09:27:46 -05003560 * menu to see the download window. It shows the download window on top of
3561 * the current window.
The Android Open Source Project0c908882009-03-03 19:32:16 -08003562 */
Leon Scrogginsf08809b2010-01-21 09:27:46 -05003563 private void viewDownloads(Uri downloadRecord) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003564 Intent intent = new Intent(this,
3565 BrowserDownloadPage.class);
3566 intent.setData(downloadRecord);
Grace Kloba22ac16e2009-10-07 18:00:23 -07003567 startActivityForResult(intent, BrowserActivity.DOWNLOAD_PAGE);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003568
3569 }
3570
Leon Scroggins160a7e72009-08-14 18:28:01 -04003571 /**
3572 * Open the Go page.
3573 * @param startWithHistory If true, open starting on the history tab.
3574 * Otherwise, start with the bookmarks tab.
Leon Scroggins160a7e72009-08-14 18:28:01 -04003575 */
Leon Scroggins30444232009-09-04 18:36:20 -04003576 /* package */ void bookmarksOrHistoryPicker(boolean startWithHistory) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003577 WebView current = mTabControl.getCurrentWebView();
3578 if (current == null) {
3579 return;
3580 }
3581 Intent intent = new Intent(this,
3582 CombinedBookmarkHistoryActivity.class);
3583 String title = current.getTitle();
3584 String url = current.getUrl();
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01003585 Bitmap thumbnail = createScreenshot(current);
3586
The Android Open Source Project0c908882009-03-03 19:32:16 -08003587 // Just in case the user opens bookmarks before a page finishes loading
3588 // so the current history item, and therefore the page, is null.
3589 if (null == url) {
3590 url = mLastEnteredUrl;
3591 // This can happen.
3592 if (null == url) {
3593 url = mSettings.getHomePage();
3594 }
3595 }
3596 // In case the web page has not yet received its associated title.
3597 if (title == null) {
3598 title = url;
3599 }
3600 intent.putExtra("title", title);
3601 intent.putExtra("url", url);
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01003602 intent.putExtra("thumbnail", thumbnail);
Leon Scroggins30444232009-09-04 18:36:20 -04003603 // Disable opening in a new window if we have maxed out the windows
Grace Kloba22ac16e2009-10-07 18:00:23 -07003604 intent.putExtra("disable_new_window", !mTabControl.canCreateNewTab());
Patrick Scott3918d442009-08-04 13:22:29 -04003605 intent.putExtra("touch_icon_url", current.getTouchIconUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003606 if (startWithHistory) {
3607 intent.putExtra(CombinedBookmarkHistoryActivity.STARTING_TAB,
3608 CombinedBookmarkHistoryActivity.HISTORY_TAB);
3609 }
3610 startActivityForResult(intent, COMBO_PAGE);
3611 }
3612
3613 // Called when loading from context menu or LOAD_URL message
Leon Scroggins92472e82010-02-17 16:32:28 -05003614 private void loadUrlFromContext(WebView view, String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003615 // In case the user enters nothing.
3616 if (url != null && url.length() != 0 && view != null) {
3617 url = smartUrlFilter(url);
Grace Kloba22ac16e2009-10-07 18:00:23 -07003618 if (!view.getWebViewClient().shouldOverrideUrlLoading(view, url)) {
Leon Scroggins92472e82010-02-17 16:32:28 -05003619 loadUrl(view, url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003620 }
3621 }
3622 }
3623
Leon Scroggins92472e82010-02-17 16:32:28 -05003624 /**
3625 * Load the URL into the given WebView and update the title bar
3626 * to reflect the new load. Call this instead of WebView.loadUrl
3627 * directly.
3628 * @param view The WebView used to load url.
3629 * @param url The URL to load.
3630 */
3631 private void loadUrl(WebView view, String url) {
3632 updateTitleBarForNewLoad(view, url);
3633 view.loadUrl(url);
3634 }
3635
3636 /**
3637 * Load UrlData into a Tab and update the title bar to reflect the new
3638 * load. Call this instead of UrlData.loadIn directly.
3639 * @param t The Tab used to load.
3640 * @param data The UrlData being loaded.
3641 */
3642 private void loadUrlDataIn(Tab t, UrlData data) {
3643 updateTitleBarForNewLoad(t.getWebView(), data.mUrl);
3644 data.loadIn(t);
3645 }
3646
3647 /**
3648 * If the WebView is the top window, update the title bar to reflect
3649 * loading the new URL. i.e. set its text, clear the favicon (which
3650 * will be set once the page begins loading), and set the progress to
3651 * INITIAL_PROGRESS to show that the page has begun to load. Called
3652 * by loadUrl and loadUrlDataIn.
3653 * @param view The WebView that is starting a load.
3654 * @param url The URL that is being loaded.
3655 */
3656 private void updateTitleBarForNewLoad(WebView view, String url) {
3657 if (view == getTopWindow()) {
3658 setUrlTitle(url, null);
3659 setFavicon(null);
3660 onProgressChanged(view, INITIAL_PROGRESS);
3661 }
3662 }
3663
The Android Open Source Project0c908882009-03-03 19:32:16 -08003664 private String smartUrlFilter(Uri inUri) {
3665 if (inUri != null) {
3666 return smartUrlFilter(inUri.toString());
3667 }
3668 return null;
3669 }
3670
Feng Qianb34f87a2009-03-24 21:27:26 -07003671 protected static final Pattern ACCEPTED_URI_SCHEMA = Pattern.compile(
The Android Open Source Project0c908882009-03-03 19:32:16 -08003672 "(?i)" + // switch on case insensitive matching
3673 "(" + // begin group for schema
3674 "(?:http|https|file):\\/\\/" +
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003675 "|(?:inline|data|about|content|javascript):" +
The Android Open Source Project0c908882009-03-03 19:32:16 -08003676 ")" +
3677 "(.*)" );
3678
3679 /**
3680 * Attempts to determine whether user input is a URL or search
3681 * terms. Anything with a space is passed to search.
3682 *
3683 * Converts to lowercase any mistakenly uppercased schema (i.e.,
3684 * "Http://" converts to "http://"
3685 *
3686 * @return Original or modified URL
3687 *
3688 */
3689 String smartUrlFilter(String url) {
3690
3691 String inUrl = url.trim();
3692 boolean hasSpace = inUrl.indexOf(' ') != -1;
3693
3694 Matcher matcher = ACCEPTED_URI_SCHEMA.matcher(inUrl);
3695 if (matcher.matches()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003696 // force scheme to lowercase
3697 String scheme = matcher.group(1);
3698 String lcScheme = scheme.toLowerCase();
3699 if (!lcScheme.equals(scheme)) {
Mitsuru Oshima123ecfb2009-05-18 19:11:14 -07003700 inUrl = lcScheme + matcher.group(2);
3701 }
3702 if (hasSpace) {
3703 inUrl = inUrl.replace(" ", "%20");
The Android Open Source Project0c908882009-03-03 19:32:16 -08003704 }
3705 return inUrl;
3706 }
3707 if (hasSpace) {
Satish Sampath565505b2009-05-29 15:37:27 +01003708 // FIXME: Is this the correct place to add to searches?
3709 // what if someone else calls this function?
3710 int shortcut = parseUrlShortcut(inUrl);
3711 if (shortcut != SHORTCUT_INVALID) {
3712 Browser.addSearchUrl(mResolver, inUrl);
3713 String query = inUrl.substring(2);
3714 switch (shortcut) {
3715 case SHORTCUT_GOOGLE_SEARCH:
Grace Kloba47fdfdb2009-06-30 11:15:34 -07003716 return URLUtil.composeSearchUrl(query, QuickSearch_G, QUERY_PLACE_HOLDER);
Satish Sampath565505b2009-05-29 15:37:27 +01003717 case SHORTCUT_WIKIPEDIA_SEARCH:
3718 return URLUtil.composeSearchUrl(query, QuickSearch_W, QUERY_PLACE_HOLDER);
3719 case SHORTCUT_DICTIONARY_SEARCH:
3720 return URLUtil.composeSearchUrl(query, QuickSearch_D, QUERY_PLACE_HOLDER);
3721 case SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH:
The Android Open Source Project0c908882009-03-03 19:32:16 -08003722 // FIXME: we need location in this case
Satish Sampath565505b2009-05-29 15:37:27 +01003723 return URLUtil.composeSearchUrl(query, QuickSearch_L, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003724 }
3725 }
3726 } else {
Dan Egnor5ee906c2009-11-18 12:11:49 -08003727 if (Patterns.WEB_URL.matcher(inUrl).matches()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003728 return URLUtil.guessUrl(inUrl);
3729 }
3730 }
3731
3732 Browser.addSearchUrl(mResolver, inUrl);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07003733 return URLUtil.composeSearchUrl(inUrl, QuickSearch_G, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003734 }
3735
Ben Murdochbff2d602009-07-01 20:19:05 +01003736 /* package */ void setShouldShowErrorConsole(boolean flag) {
3737 if (flag == mShouldShowErrorConsole) {
3738 // Nothing to do.
3739 return;
3740 }
3741
3742 mShouldShowErrorConsole = flag;
3743
Grace Kloba22ac16e2009-10-07 18:00:23 -07003744 ErrorConsoleView errorConsole = mTabControl.getCurrentTab()
3745 .getErrorConsole(true);
Ben Murdochbff2d602009-07-01 20:19:05 +01003746
3747 if (flag) {
3748 // Setting the show state of the console will cause it's the layout to be inflated.
3749 if (errorConsole.numberOfErrors() > 0) {
3750 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
3751 } else {
3752 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
3753 }
3754
3755 // Now we can add it to the main view.
3756 mErrorConsoleContainer.addView(errorConsole,
Romain Guy15b8ec62010-01-08 15:06:43 -08003757 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
Ben Murdochbff2d602009-07-01 20:19:05 +01003758 ViewGroup.LayoutParams.WRAP_CONTENT));
3759 } else {
3760 mErrorConsoleContainer.removeView(errorConsole);
3761 }
3762
3763 }
3764
Grace Kloba22ac16e2009-10-07 18:00:23 -07003765 boolean shouldShowErrorConsole() {
3766 return mShouldShowErrorConsole;
3767 }
3768
Andrei Popescu163ab742009-10-20 17:58:23 +01003769 private void setStatusBarVisibility(boolean visible) {
3770 int flag = visible ? 0 : WindowManager.LayoutParams.FLAG_FULLSCREEN;
3771 getWindow().setFlags(flag, WindowManager.LayoutParams.FLAG_FULLSCREEN);
3772 }
3773
Andrei Popescu56199cc2010-01-12 22:39:16 +00003774
3775 private void sendNetworkType(String type, String subtype) {
3776 WebView w = mTabControl.getCurrentWebView();
3777 if (w != null) {
3778 w.setNetworkType(type, subtype);
3779 }
3780 }
3781
Andrei Popescu30995e72010-02-09 16:59:58 +00003782 private void packageChanged(String packageName, boolean wasAdded) {
3783 WebView w = mTabControl.getCurrentWebView();
3784 if (w == null) {
3785 return;
3786 }
3787
3788 if (wasAdded) {
3789 w.addPackageName(packageName);
3790 } else {
3791 w.removePackageName(packageName);
3792 }
3793 }
3794
3795 private void addPackageNames(Set<String> packageNames) {
3796 WebView w = mTabControl.getCurrentWebView();
3797 if (w == null) {
3798 return;
3799 }
3800
3801 w.addPackageNames(packageNames);
3802 }
3803
3804 private void getInstalledPackages() {
3805 AsyncTask<Void, Void, Set<String> > task =
3806 new AsyncTask<Void, Void, Set<String> >() {
3807 protected Set<String> doInBackground(Void... unused) {
3808 Set<String> installedPackages = new HashSet<String>();
3809 PackageManager pm = BrowserActivity.this.getPackageManager();
3810 if (pm != null) {
3811 List<PackageInfo> packages = pm.getInstalledPackages(0);
3812 for (PackageInfo p : packages) {
3813 if (BrowserActivity.this.sGoogleApps.contains(p.packageName)) {
3814 installedPackages.add(p.packageName);
3815 }
3816 }
3817 }
3818
3819 return installedPackages;
3820 }
3821
3822 // Executes on the UI thread
3823 protected void onPostExecute(Set<String> installedPackages) {
3824 addPackageNames(installedPackages);
3825 }
3826 };
3827 task.execute();
3828 }
3829
Grace Klobaeb6eef42009-09-15 17:56:32 -07003830 final static int LOCK_ICON_UNSECURE = 0;
3831 final static int LOCK_ICON_SECURE = 1;
3832 final static int LOCK_ICON_MIXED = 2;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003833
The Android Open Source Project0c908882009-03-03 19:32:16 -08003834 private BrowserSettings mSettings;
3835 private TabControl mTabControl;
3836 private ContentResolver mResolver;
3837 private FrameLayout mContentView;
Andrei Popescuadc008d2009-06-26 14:11:30 +01003838 private View mCustomView;
3839 private FrameLayout mCustomViewContainer;
Andrei Popescuc9b55562009-07-07 10:51:15 +01003840 private WebChromeClient.CustomViewCallback mCustomViewCallback;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003841
3842 // FIXME, temp address onPrepareMenu performance problem. When we move everything out of
3843 // view, we should rewrite this.
3844 private int mCurrentMenuState = 0;
3845 private int mMenuState = R.id.MAIN_MENU;
Andrei Popescuadc008d2009-06-26 14:11:30 +01003846 private int mOldMenuState = EMPTY_MENU;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003847 private static final int EMPTY_MENU = -1;
3848 private Menu mMenu;
3849
3850 private FindDialog mFindDialog;
Cary Clark2c326e62010-08-19 18:40:57 -04003851 private SelectDialog mSelectDialog;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003852 // Used to prevent chording to result in firing two shortcuts immediately
3853 // one after another. Fixes bug 1211714.
3854 boolean mCanChord;
3855
3856 private boolean mInLoad;
3857 private boolean mIsNetworkUp;
Ben Murdochb7cc8b42009-09-28 10:59:09 +01003858 private boolean mDidStopLoad;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003859
Cary Clark1f10cbf2010-03-22 11:45:23 -04003860 /* package */ boolean mActivityInPause = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003861
3862 private boolean mMenuIsDown;
3863
The Android Open Source Project0c908882009-03-03 19:32:16 -08003864 private static boolean mInTrace;
3865
3866 // Performance probe
3867 private static final int[] SYSTEM_CPU_FORMAT = new int[] {
3868 Process.PROC_SPACE_TERM | Process.PROC_COMBINE,
3869 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 1: user time
3870 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 2: nice time
3871 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 3: sys time
3872 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 4: idle time
3873 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 5: iowait time
3874 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 6: irq time
3875 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG // 7: softirq time
3876 };
3877
3878 private long mStart;
3879 private long mProcessStart;
3880 private long mUserStart;
3881 private long mSystemStart;
3882 private long mIdleStart;
3883 private long mIrqStart;
3884
3885 private long mUiStart;
3886
3887 private Drawable mMixLockIcon;
3888 private Drawable mSecLockIcon;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003889
3890 /* hold a ref so we can auto-cancel if necessary */
3891 private AlertDialog mAlertDialog;
3892
The Android Open Source Project0c908882009-03-03 19:32:16 -08003893 // The up-to-date URL and title (these can be different from those stored
3894 // in WebView, since it takes some time for the information in WebView to
3895 // get updated)
3896 private String mUrl;
3897 private String mTitle;
3898
3899 // As PageInfo has different style for landscape / portrait, we have
3900 // to re-open it when configuration changed
3901 private AlertDialog mPageInfoDialog;
Grace Kloba22ac16e2009-10-07 18:00:23 -07003902 private Tab mPageInfoView;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003903 // If the Page-Info dialog is launched from the SSL-certificate-on-error
3904 // dialog, we should not just dismiss it, but should get back to the
3905 // SSL-certificate-on-error dialog. This flag is used to store this state
Leon Scrogginsc7b92f82010-01-11 18:17:31 -05003906 private boolean mPageInfoFromShowSSLCertificateOnError;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003907
3908 // as SSLCertificateOnError has different style for landscape / portrait,
3909 // we have to re-open it when configuration changed
3910 private AlertDialog mSSLCertificateOnErrorDialog;
3911 private WebView mSSLCertificateOnErrorView;
3912 private SslErrorHandler mSSLCertificateOnErrorHandler;
3913 private SslError mSSLCertificateOnErrorError;
3914
3915 // as SSLCertificate has different style for landscape / portrait, we
3916 // have to re-open it when configuration changed
3917 private AlertDialog mSSLCertificateDialog;
Grace Kloba22ac16e2009-10-07 18:00:23 -07003918 private Tab mSSLCertificateView;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003919
3920 // as HttpAuthentication has different style for landscape / portrait, we
3921 // have to re-open it when configuration changed
3922 private AlertDialog mHttpAuthenticationDialog;
3923 private HttpAuthHandler mHttpAuthHandler;
3924
3925 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_PARAMS =
3926 new FrameLayout.LayoutParams(
Romain Guy15b8ec62010-01-08 15:06:43 -08003927 ViewGroup.LayoutParams.MATCH_PARENT,
3928 ViewGroup.LayoutParams.MATCH_PARENT);
Andrei Popescuadc008d2009-06-26 14:11:30 +01003929 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_GRAVITY_CENTER =
3930 new FrameLayout.LayoutParams(
Romain Guy15b8ec62010-01-08 15:06:43 -08003931 ViewGroup.LayoutParams.MATCH_PARENT,
3932 ViewGroup.LayoutParams.MATCH_PARENT,
Andrei Popescuadc008d2009-06-26 14:11:30 +01003933 Gravity.CENTER);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07003934 // Google search
3935 final static String QuickSearch_G = "http://www.google.com/m?q=%s";
The Android Open Source Project0c908882009-03-03 19:32:16 -08003936 // Wikipedia search
3937 final static String QuickSearch_W = "http://en.wikipedia.org/w/index.php?search=%s&go=Go";
3938 // Dictionary search
3939 final static String QuickSearch_D = "http://dictionary.reference.com/search?q=%s";
3940 // Google Mobile Local search
3941 final static String QuickSearch_L = "http://www.google.com/m/search?site=local&q=%s&near=mountain+view";
3942
3943 final static String QUERY_PLACE_HOLDER = "%s";
3944
3945 // "source" parameter for Google search through search key
3946 final static String GOOGLE_SEARCH_SOURCE_SEARCHKEY = "browser-key";
3947 // "source" parameter for Google search through goto menu
3948 final static String GOOGLE_SEARCH_SOURCE_GOTO = "browser-goto";
3949 // "source" parameter for Google search through simplily type
3950 final static String GOOGLE_SEARCH_SOURCE_TYPE = "browser-type";
3951 // "source" parameter for Google search suggested by the browser
3952 final static String GOOGLE_SEARCH_SOURCE_SUGGEST = "browser-suggest";
3953 // "source" parameter for Google search from unknown source
3954 final static String GOOGLE_SEARCH_SOURCE_UNKNOWN = "unknown";
3955
3956 private final static String LOGTAG = "browser";
3957
The Android Open Source Project0c908882009-03-03 19:32:16 -08003958 private String mLastEnteredUrl;
3959
3960 private PowerManager.WakeLock mWakeLock;
3961 private final static int WAKELOCK_TIMEOUT = 5 * 60 * 1000; // 5 minutes
3962
3963 private Toast mStopToast;
3964
Leon Scroggins68579392009-09-15 15:31:54 -04003965 private TitleBar mTitleBar;
Leon Scroggins81db3662009-06-04 17:45:11 -04003966
Ben Murdochbff2d602009-07-01 20:19:05 +01003967 private LinearLayout mErrorConsoleContainer = null;
3968 private boolean mShouldShowErrorConsole = false;
3969
The Android Open Source Project0c908882009-03-03 19:32:16 -08003970 // As the ids are dynamically created, we can't guarantee that they will
3971 // be in sequence, so this static array maps ids to a window number.
3972 final static private int[] WINDOW_SHORTCUT_ID_ARRAY =
3973 { R.id.window_one_menu_id, R.id.window_two_menu_id, R.id.window_three_menu_id,
3974 R.id.window_four_menu_id, R.id.window_five_menu_id, R.id.window_six_menu_id,
3975 R.id.window_seven_menu_id, R.id.window_eight_menu_id };
3976
3977 // monitor platform changes
3978 private IntentFilter mNetworkStateChangedFilter;
3979 private BroadcastReceiver mNetworkStateIntentReceiver;
3980
Grace Klobab4da0ad2009-05-14 14:45:40 -07003981 private BroadcastReceiver mPackageInstallationReceiver;
3982
Bjorn Bringerta7611812010-03-24 11:12:02 +00003983 private SystemAllowGeolocationOrigins mSystemAllowGeolocationOrigins;
3984
The Android Open Source Project0c908882009-03-03 19:32:16 -08003985 // activity requestCode
Nicolas Roard78a98e42009-05-11 13:34:17 +01003986 final static int COMBO_PAGE = 1;
3987 final static int DOWNLOAD_PAGE = 2;
3988 final static int PREFERENCES_PAGE = 3;
Leon Scroggins8d5fa432009-10-02 15:55:59 -04003989 final static int FILE_SELECTED = 4;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003990
Andrei Popescu540035d2009-09-18 18:59:20 +01003991 // the default <video> poster
3992 private Bitmap mDefaultVideoPoster;
3993 // the video progress view
3994 private View mVideoProgressView;
3995
Andrei Popescu30995e72010-02-09 16:59:58 +00003996 // The Google packages we monitor for the navigator.isApplicationInstalled()
3997 // API. Add as needed.
3998 private static Set<String> sGoogleApps;
3999 static {
4000 sGoogleApps = new HashSet<String>();
4001 sGoogleApps.add("com.google.android.youtube");
4002 }
4003
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004004 /**
4005 * A UrlData class to abstract how the content will be set to WebView.
4006 * This base class uses loadUrl to show the content.
4007 */
Leon Scroggins6eac63e2010-03-15 18:19:14 -04004008 /* package */ static class UrlData {
Grace Kloba068e48b2010-01-26 18:11:27 -08004009 final String mUrl;
4010 final Map<String, String> mHeaders;
Leon Scroggins58d56c62010-01-28 15:12:40 -05004011 final Intent mVoiceIntent;
Grace Kloba60e095c2009-06-16 11:50:55 -07004012
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004013 UrlData(String url) {
4014 this.mUrl = url;
Grace Kloba068e48b2010-01-26 18:11:27 -08004015 this.mHeaders = null;
Leon Scroggins58d56c62010-01-28 15:12:40 -05004016 this.mVoiceIntent = null;
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004017 }
Grace Kloba60e095c2009-06-16 11:50:55 -07004018
Leon Scroggins58d56c62010-01-28 15:12:40 -05004019 UrlData(String url, Map<String, String> headers, Intent intent) {
Grace Kloba068e48b2010-01-26 18:11:27 -08004020 this.mUrl = url;
4021 this.mHeaders = headers;
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -05004022 if (RecognizerResultsIntent.ACTION_VOICE_SEARCH_RESULTS
4023 .equals(intent.getAction())) {
Leon Scroggins58d56c62010-01-28 15:12:40 -05004024 this.mVoiceIntent = intent;
4025 } else {
4026 this.mVoiceIntent = null;
4027 }
Grace Kloba60e095c2009-06-16 11:50:55 -07004028 }
4029
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004030 boolean isEmpty() {
Leon Scroggins58d56c62010-01-28 15:12:40 -05004031 return mVoiceIntent == null && (mUrl == null || mUrl.length() == 0);
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004032 }
4033
Leon Scroggins92472e82010-02-17 16:32:28 -05004034 /**
4035 * Load this UrlData into the given Tab. Use loadUrlDataIn to update
4036 * the title bar as well.
4037 */
Leon Scroggins58d56c62010-01-28 15:12:40 -05004038 public void loadIn(Tab t) {
4039 if (mVoiceIntent != null) {
4040 t.activateVoiceSearchMode(mVoiceIntent);
4041 } else {
4042 t.getWebView().loadUrl(mUrl, mHeaders);
4043 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004044 }
4045 };
4046
Leon Scroggins1f005d32009-08-10 17:36:42 -04004047 /* package */ static final UrlData EMPTY_URL_DATA = new UrlData(null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004048}