blob: cae3324c5130137ad013304813f30132d3b911f7 [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;
Steve Howard5a862fc2010-09-28 12:52:06 -070021import android.app.DownloadManager;
The Android Open Source Project0c908882009-03-03 19:32:16 -080022import android.app.ProgressDialog;
23import android.app.SearchManager;
24import android.content.ActivityNotFoundException;
25import android.content.BroadcastReceiver;
26import android.content.ComponentName;
Leon Scroggins58d56c62010-01-28 15:12:40 -050027import android.content.ContentProvider;
28import android.content.ContentProviderClient;
The Android Open Source Project0c908882009-03-03 19:32:16 -080029import android.content.ContentResolver;
Leon Scrogginsb6b7f9e2009-06-18 12:05:28 -040030import android.content.ContentUris;
The Android Open Source Project0c908882009-03-03 19:32:16 -080031import android.content.ContentValues;
32import android.content.Context;
33import android.content.DialogInterface;
34import android.content.Intent;
35import android.content.IntentFilter;
Grace Klobab4da0ad2009-05-14 14:45:40 -070036import android.content.pm.PackageInfo;
The Android Open Source Project0c908882009-03-03 19:32:16 -080037import android.content.pm.PackageManager;
38import android.content.pm.ResolveInfo;
The Android Open Source Project0c908882009-03-03 19:32:16 -080039import android.content.res.Configuration;
40import android.content.res.Resources;
41import android.database.Cursor;
Leon Scroggins96afcb12009-12-10 12:35:56 -050042import android.database.DatabaseUtils;
The Android Open Source Project0c908882009-03-03 19:32:16 -080043import android.graphics.Bitmap;
Andrei Popescu540035d2009-09-18 18:59:20 +010044import android.graphics.BitmapFactory;
The Android Open Source Project0c908882009-03-03 19:32:16 -080045import android.graphics.Canvas;
The Android Open Source Project0c908882009-03-03 19:32:16 -080046import android.graphics.Picture;
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -040047import android.graphics.PixelFormat;
48import android.graphics.Rect;
The Android Open Source Project0c908882009-03-03 19:32:16 -080049import android.graphics.drawable.Drawable;
The Android Open Source Project0c908882009-03-03 19:32:16 -080050import android.net.ConnectivityManager;
Andrei Popescu56199cc2010-01-12 22:39:16 +000051import android.net.NetworkInfo;
The Android Open Source Project0c908882009-03-03 19:32:16 -080052import android.net.Uri;
53import android.net.WebAddress;
The Android Open Source Project0c908882009-03-03 19:32:16 -080054import android.net.http.SslCertificate;
55import android.net.http.SslError;
56import android.os.AsyncTask;
57import android.os.Bundle;
58import android.os.Debug;
59import android.os.Environment;
60import android.os.Handler;
The Android Open Source Project0c908882009-03-03 19:32:16 -080061import android.os.Message;
62import android.os.PowerManager;
63import android.os.Process;
The Android Open Source Project0c908882009-03-03 19:32:16 -080064import android.os.ServiceManager;
65import android.os.SystemClock;
The Android Open Source Project0c908882009-03-03 19:32:16 -080066import android.provider.Browser;
Cary Clark5e335a32009-09-22 14:53:11 -040067import android.provider.ContactsContract;
68import android.provider.ContactsContract.Intents.Insert;
The Android Open Source Project0c908882009-03-03 19:32:16 -080069import android.provider.Downloads;
70import android.provider.MediaStore;
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -050071import android.speech.RecognizerResultsIntent;
The Android Open Source Project0c908882009-03-03 19:32:16 -080072import android.text.IClipboard;
73import android.text.TextUtils;
74import android.text.format.DateFormat;
Leon Scrogginsb94bf272009-09-25 15:22:08 -040075import android.util.AttributeSet;
The Android Open Source Project0c908882009-03-03 19:32:16 -080076import android.util.Log;
Dianne Hackborn385effd2010-02-24 20:03:04 -080077import android.util.Patterns;
The Android Open Source Project0c908882009-03-03 19:32:16 -080078import android.view.ContextMenu;
79import android.view.Gravity;
80import android.view.KeyEvent;
81import android.view.LayoutInflater;
82import android.view.Menu;
83import android.view.MenuInflater;
84import android.view.MenuItem;
85import android.view.View;
86import android.view.ViewGroup;
87import android.view.Window;
88import android.view.WindowManager;
89import android.view.ContextMenu.ContextMenuInfo;
90import android.view.MenuItem.OnMenuItemClickListener;
The Android Open Source Project0c908882009-03-03 19:32:16 -080091import android.webkit.CookieManager;
92import android.webkit.CookieSyncManager;
93import android.webkit.DownloadListener;
94import android.webkit.HttpAuthHandler;
Grace Klobab4da0ad2009-05-14 14:45:40 -070095import android.webkit.PluginManager;
The Android Open Source Project0c908882009-03-03 19:32:16 -080096import android.webkit.SslErrorHandler;
97import android.webkit.URLUtil;
Leon Clarkecb6cc862009-09-29 18:35:13 +010098import android.webkit.ValueCallback;
The Android Open Source Project0c908882009-03-03 19:32:16 -080099import android.webkit.WebChromeClient;
100import android.webkit.WebHistoryItem;
101import android.webkit.WebIconDatabase;
102import android.webkit.WebView;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800103import android.widget.EditText;
104import android.widget.FrameLayout;
105import android.widget.LinearLayout;
106import android.widget.TextView;
107import android.widget.Toast;
Fred Quintana752b6562009-12-18 10:18:26 -0800108import android.accounts.Account;
109import android.accounts.AccountManager;
110import android.accounts.AccountManagerFuture;
111import android.accounts.AuthenticatorException;
112import android.accounts.OperationCanceledException;
113import android.accounts.AccountManagerCallback;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800114
Bjorn Bringertd2670652010-09-13 14:06:41 +0100115import com.android.browser.search.SearchEngine;
Bjorn Bringert10d1cca2010-02-10 14:22:12 +0000116import com.android.common.Search;
Leon Scroggins1fe13a52010-02-09 15:31:26 -0500117import com.android.common.speech.LoggingEvents;
Dan Egnor5ee906c2009-11-18 12:11:49 -0800118
Leon Scrogginsb6b7f9e2009-06-18 12:05:28 -0400119import java.io.ByteArrayOutputStream;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800120import java.io.File;
Ben Murdoch4f75ba22009-10-27 11:48:28 +0000121import java.io.IOException;
122import java.io.InputStream;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800123import java.net.MalformedURLException;
124import java.net.URI;
Dianne Hackborn99189432009-06-17 18:06:18 -0700125import java.net.URISyntaxException;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800126import java.net.URL;
127import java.net.URLEncoder;
128import java.text.ParseException;
129import java.util.Date;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800130import java.util.HashMap;
Andrei Popescu30995e72010-02-09 16:59:58 +0000131import java.util.HashSet;
Grace Kloba00f54c52010-01-27 14:53:51 -0800132import java.util.Iterator;
Andrei Popescu30995e72010-02-09 16:59:58 +0000133import java.util.List;
Grace Kloba068e48b2010-01-26 18:11:27 -0800134import java.util.Map;
Andrei Popescu30995e72010-02-09 16:59:58 +0000135import java.util.Set;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800136import java.util.regex.Matcher;
137import java.util.regex.Pattern;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800138
139public class BrowserActivity extends Activity
Shimeng (Simon) Wang98d5fce2010-03-16 13:23:39 -0700140 implements View.OnCreateContextMenuListener, DownloadListener {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800141
Dave Bort31a6d1c2009-04-13 15:56:49 -0700142 /* Define some aliases to make these debugging flags easier to refer to.
143 * This file imports android.provider.Browser, so we can't just refer to "Browser.DEBUG".
144 */
145 private final static boolean DEBUG = com.android.browser.Browser.DEBUG;
146 private final static boolean LOGV_ENABLED = com.android.browser.Browser.LOGV_ENABLED;
147 private final static boolean LOGD_ENABLED = com.android.browser.Browser.LOGD_ENABLED;
148
Cary Clarka9771242009-08-11 16:42:26 -0400149 private static class ClearThumbnails extends AsyncTask<File, Void, Void> {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800150 @Override
151 public Void doInBackground(File... files) {
152 if (files != null) {
153 for (File f : files) {
Cary Clarkd6be1752009-08-12 12:56:42 -0400154 if (!f.delete()) {
155 Log.e(LOGTAG, f.getPath() + " was not deleted");
156 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800157 }
158 }
159 return null;
160 }
161 }
162
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400163 /**
164 * This layout holds everything you see below the status bar, including the
165 * error console, the custom view container, and the webviews.
166 */
167 private FrameLayout mBrowserFrameLayout;
Leon Scroggins81db3662009-06-04 17:45:11 -0400168
Grace Kloba22ac16e2009-10-07 18:00:23 -0700169 @Override
170 public void onCreate(Bundle icicle) {
Dave Bort31a6d1c2009-04-13 15:56:49 -0700171 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800172 Log.v(LOGTAG, this + " onStart");
173 }
174 super.onCreate(icicle);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800175 // test the browser in OpenGL
176 // requestWindowFeature(Window.FEATURE_OPENGL);
177
Mike Reedd334bf52010-01-26 15:21:44 -0500178 // enable this to test the browser in 32bit
179 if (false) {
180 getWindow().setFormat(PixelFormat.RGBX_8888);
181 BitmapFactory.setDefaultConfig(Bitmap.Config.ARGB_8888);
182 }
183
The Android Open Source Project0c908882009-03-03 19:32:16 -0800184 setDefaultKeyMode(DEFAULT_KEYS_SEARCH_LOCAL);
185
186 mResolver = getContentResolver();
187
Leon Scroggins IIIcc14c8c2010-09-27 12:45:34 -0400188 // Keep a settings instance handy.
189 mSettings = BrowserSettings.getInstance();
190
Ed Tam8ba13bc2011-05-05 16:19:48 -0700191 mSettings.updateRlzValues(this);
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
The Android Open Source Project0c908882009-03-03 19:32:16 -0800227 mSettings.setTabControl(mTabControl);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800228
229 PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
230 mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Browser");
231
Patrick Scott6adacc92010-03-05 08:24:51 -0500232 // Find out if the network is currently up.
233 ConnectivityManager cm = (ConnectivityManager) getSystemService(
234 Context.CONNECTIVITY_SERVICE);
235 NetworkInfo info = cm.getActiveNetworkInfo();
236 if (info != null) {
237 mIsNetworkUp = info.isAvailable();
238 }
239
Grace Klobaa34f6862009-07-31 16:28:17 -0700240 /* enables registration for changes in network status from
241 http stack */
242 mNetworkStateChangedFilter = new IntentFilter();
243 mNetworkStateChangedFilter.addAction(
244 ConnectivityManager.CONNECTIVITY_ACTION);
245 mNetworkStateIntentReceiver = new BroadcastReceiver() {
246 @Override
247 public void onReceive(Context context, Intent intent) {
248 if (intent.getAction().equals(
249 ConnectivityManager.CONNECTIVITY_ACTION)) {
Andrei Popescue4c98462010-02-19 15:44:13 +0000250
251 NetworkInfo info = intent.getParcelableExtra(
252 ConnectivityManager.EXTRA_NETWORK_INFO);
253 String typeName = info.getTypeName();
254 String subtypeName = info.getSubtypeName();
255 sendNetworkType(typeName.toLowerCase(),
256 (subtypeName != null ? subtypeName.toLowerCase() : ""));
257
258 onNetworkToggle(info.isAvailable());
Grace Klobaa34f6862009-07-31 16:28:17 -0700259 }
260 }
261 };
262
Grace Kloba615c6c92009-08-03 10:22:44 -0700263 IntentFilter filter = new IntentFilter(Intent.ACTION_PACKAGE_ADDED);
264 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
265 filter.addDataScheme("package");
266 mPackageInstallationReceiver = new BroadcastReceiver() {
267 @Override
268 public void onReceive(Context context, Intent intent) {
269 final String action = intent.getAction();
270 final String packageName = intent.getData()
271 .getSchemeSpecificPart();
272 final boolean replacing = intent.getBooleanExtra(
273 Intent.EXTRA_REPLACING, false);
274 if (Intent.ACTION_PACKAGE_REMOVED.equals(action) && replacing) {
275 // if it is replacing, refreshPlugins() when adding
276 return;
277 }
Andrei Popescu30995e72010-02-09 16:59:58 +0000278
279 if (sGoogleApps.contains(packageName)) {
280 BrowserActivity.this.packageChanged(packageName,
281 Intent.ACTION_PACKAGE_ADDED.equals(action));
282 }
283
Grace Kloba615c6c92009-08-03 10:22:44 -0700284 PackageManager pm = BrowserActivity.this.getPackageManager();
285 PackageInfo pkgInfo = null;
286 try {
287 pkgInfo = pm.getPackageInfo(packageName,
288 PackageManager.GET_PERMISSIONS);
289 } catch (PackageManager.NameNotFoundException e) {
290 return;
291 }
292 if (pkgInfo != null) {
293 String permissions[] = pkgInfo.requestedPermissions;
294 if (permissions == null) {
295 return;
296 }
297 boolean permissionOk = false;
298 for (String permit : permissions) {
299 if (PluginManager.PLUGIN_PERMISSION.equals(permit)) {
300 permissionOk = true;
301 break;
302 }
303 }
304 if (permissionOk) {
305 PluginManager.getInstance(BrowserActivity.this)
306 .refreshPlugins(
307 Intent.ACTION_PACKAGE_ADDED
308 .equals(action));
309 }
310 }
311 }
312 };
313 registerReceiver(mPackageInstallationReceiver, filter);
314
The Android Open Source Project0c908882009-03-03 19:32:16 -0800315 if (!mTabControl.restoreState(icicle)) {
316 // clear up the thumbnail directory if we can't restore the state as
317 // none of the files in the directory are referenced any more.
318 new ClearThumbnails().execute(
319 mTabControl.getThumbnailDir().listFiles());
Grace Klobaaab3f092009-07-30 12:29:51 -0700320 // there is no quit on Android. But if we can't restore the state,
321 // we can treat it as a new Browser, remove the old session cookies.
322 CookieManager.getInstance().removeSessionCookie();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800323 final Intent intent = getIntent();
324 final Bundle extra = intent.getExtras();
325 // Create an initial tab.
326 // If the intent is ACTION_VIEW and data is not null, the Browser is
327 // invoked to view the content by another application. In this case,
328 // the tab will be close when exit.
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700329 UrlData urlData = getUrlDataFromIntent(intent);
330
Leon Scroggins58d56c62010-01-28 15:12:40 -0500331 String action = intent.getAction();
Grace Kloba22ac16e2009-10-07 18:00:23 -0700332 final Tab t = mTabControl.createNewTab(
Leon Scroggins58d56c62010-01-28 15:12:40 -0500333 (Intent.ACTION_VIEW.equals(action) &&
334 intent.getData() != null)
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -0500335 || RecognizerResultsIntent.ACTION_VOICE_SEARCH_RESULTS
336 .equals(action),
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700337 intent.getStringExtra(Browser.EXTRA_APPLICATION_ID), urlData.mUrl);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800338 mTabControl.setCurrentTab(t);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800339 attachTabToContentView(t);
340 WebView webView = t.getWebView();
341 if (extra != null) {
342 int scale = extra.getInt(Browser.INITIAL_ZOOM_LEVEL, 0);
343 if (scale > 0 && scale <= 1000) {
344 webView.setInitialScale(scale);
345 }
346 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800347
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700348 if (urlData.isEmpty()) {
Shimeng (Simon) Wang98d5fce2010-03-16 13:23:39 -0700349 loadUrl(webView, mSettings.getHomePage());
The Android Open Source Project0c908882009-03-03 19:32:16 -0800350 } else {
Patrick Scott9d53da02010-02-19 10:19:01 -0500351 loadUrlDataIn(t, urlData);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800352 }
353 } else {
354 // TabControl.restoreState() will create a new tab even if
Leon Scroggins1f005d32009-08-10 17:36:42 -0400355 // restoring the state fails.
The Android Open Source Project0c908882009-03-03 19:32:16 -0800356 attachTabToContentView(mTabControl.getCurrentTab());
357 }
Grace Kloba615c6c92009-08-03 10:22:44 -0700358
Cary Clark23cbeb72010-07-01 12:36:56 -0400359 // Delete old thumbnails to save space
360 File dir = mTabControl.getThumbnailDir();
361 if (dir.exists()) {
362 for (String child : dir.list()) {
363 File f = new File(dir, child);
364 f.delete();
365 }
366 }
367
Feng Qianb3c02da2009-06-29 15:58:08 -0700368 // Read JavaScript flags if it exists.
369 String jsFlags = mSettings.getJsFlags();
370 if (jsFlags.trim().length() != 0) {
371 mTabControl.getCurrentWebView().setJsFlags(jsFlags);
372 }
Andrei Popescu30995e72010-02-09 16:59:58 +0000373 // Work out which packages are installed on the system.
374 getInstalledPackages();
Bjorn Bringerta7611812010-03-24 11:12:02 +0000375
376 // Start watching the default geolocation permissions
377 mSystemAllowGeolocationOrigins
378 = new SystemAllowGeolocationOrigins(getApplicationContext());
379 mSystemAllowGeolocationOrigins.start();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800380 }
381
Leon Scroggins58d56c62010-01-28 15:12:40 -0500382 /**
383 * Feed the previously stored results strings to the BrowserProvider so that
384 * the SearchDialog will show them instead of the standard searches.
385 * @param result String to show on the editable line of the SearchDialog.
386 */
387 /* package */ void showVoiceSearchResults(String result) {
388 ContentProviderClient client = mResolver.acquireContentProviderClient(
389 Browser.BOOKMARKS_URI);
390 ContentProvider prov = client.getLocalContentProvider();
391 BrowserProvider bp = (BrowserProvider) prov;
392 bp.setQueryResults(mTabControl.getCurrentTab().getVoiceSearchResults());
393 client.release();
394
Leon Scrogginsfbb3f152010-03-09 17:26:56 -0500395 Bundle bundle = createGoogleSearchSourceBundle(
396 GOOGLE_SEARCH_SOURCE_SEARCHKEY);
397 bundle.putBoolean(SearchManager.CONTEXT_IS_VOICE, true);
398 startSearch(result, false, bundle, false);
Leon Scroggins58d56c62010-01-28 15:12:40 -0500399 }
400
The Android Open Source Project0c908882009-03-03 19:32:16 -0800401 @Override
402 protected void onNewIntent(Intent intent) {
Grace Kloba22ac16e2009-10-07 18:00:23 -0700403 Tab current = mTabControl.getCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800404 // When a tab is closed on exit, the current tab index is set to -1.
405 // Reset before proceed as Browser requires the current tab to be set.
406 if (current == null) {
407 // Try to reset the tab in case the index was incorrect.
408 current = mTabControl.getTab(0);
409 if (current == null) {
410 // No tabs at all so just ignore this intent.
411 return;
412 }
413 mTabControl.setCurrentTab(current);
414 attachTabToContentView(current);
415 resetTitleAndIcon(current.getWebView());
416 }
417 final String action = intent.getAction();
418 final int flags = intent.getFlags();
419 if (Intent.ACTION_MAIN.equals(action) ||
420 (flags & Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY) != 0) {
421 // just resume the browser
422 return;
423 }
Leon Scrogginsb8a844d2010-03-18 15:06:15 -0400424 // In case the SearchDialog is open.
425 ((SearchManager) getSystemService(Context.SEARCH_SERVICE))
426 .stopSearch();
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -0500427 boolean activateVoiceSearch = RecognizerResultsIntent
428 .ACTION_VOICE_SEARCH_RESULTS.equals(action);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800429 if (Intent.ACTION_VIEW.equals(action)
430 || Intent.ACTION_SEARCH.equals(action)
431 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
Leon Scroggins58d56c62010-01-28 15:12:40 -0500432 || Intent.ACTION_WEB_SEARCH.equals(action)
433 || activateVoiceSearch) {
Leon Scroggins3b18ce32010-02-08 17:35:59 -0500434 if (current.isInVoiceSearchMode()) {
435 String title = current.getVoiceDisplayTitle();
436 if (title != null && title.equals(intent.getStringExtra(
437 SearchManager.QUERY))) {
438 // The user submitted the same search as the last voice
439 // search, so do nothing.
440 return;
441 }
Leon Scroggins1fe13a52010-02-09 15:31:26 -0500442 if (Intent.ACTION_SEARCH.equals(action)
443 && current.voiceSearchSourceIsGoogle()) {
444 Intent logIntent = new Intent(
445 LoggingEvents.ACTION_LOG_EVENT);
446 logIntent.putExtra(LoggingEvents.EXTRA_EVENT,
447 LoggingEvents.VoiceSearch.QUERY_UPDATED);
448 logIntent.putExtra(
449 LoggingEvents.VoiceSearch.EXTRA_QUERY_UPDATED_VALUE,
450 intent.getDataString());
451 sendBroadcast(logIntent);
452 // Note, onPageStarted will revert the voice title bar
453 // When http://b/issue?id=2379215 is fixed, we should update
454 // the title bar here.
455 }
Leon Scroggins3b18ce32010-02-08 17:35:59 -0500456 }
Satish Sampath565505b2009-05-29 15:37:27 +0100457 // If this was a search request (e.g. search query directly typed into the address bar),
458 // pass it on to the default web search provider.
459 if (handleWebSearchIntent(intent)) {
460 return;
461 }
462
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700463 UrlData urlData = getUrlDataFromIntent(intent);
464 if (urlData.isEmpty()) {
465 urlData = new UrlData(mSettings.getHomePage());
The Android Open Source Project0c908882009-03-03 19:32:16 -0800466 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700467
Grace Klobacc634032009-07-28 15:58:19 -0700468 final String appId = intent
469 .getStringExtra(Browser.EXTRA_APPLICATION_ID);
Leon Scroggins47208682010-04-07 17:59:48 -0400470 if ((Intent.ACTION_VIEW.equals(action)
471 // If a voice search has no appId, it means that it came
472 // from the browser. In that case, reuse the current tab.
473 || (activateVoiceSearch && appId != null))
Grace Klobacc634032009-07-28 15:58:19 -0700474 && !getPackageName().equals(appId)
475 && (flags & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0) {
Grace Kloba22ac16e2009-10-07 18:00:23 -0700476 Tab appTab = mTabControl.getTabFromId(appId);
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700477 if (appTab != null) {
478 Log.i(LOGTAG, "Reusing tab for " + appId);
479 // Dismiss the subwindow if applicable.
480 dismissSubWindow(appTab);
481 // Since we might kill the WebView, remove it from the
482 // content view first.
483 removeTabFromContentView(appTab);
484 // Recreate the main WebView after destroying the old one.
485 // If the WebView has the same original url and is on that
486 // page, it can be reused.
487 boolean needsLoad =
Leon Scroggins6eac63e2010-03-15 18:19:14 -0400488 mTabControl.recreateWebView(appTab, urlData);
Ben Murdochbff2d602009-07-01 20:19:05 +0100489
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700490 if (current != appTab) {
Leon Scroggins1f005d32009-08-10 17:36:42 -0400491 switchToTab(mTabControl.getTabIndex(appTab));
492 if (needsLoad) {
Patrick Scott9d53da02010-02-19 10:19:01 -0500493 loadUrlDataIn(appTab, urlData);
Leon Scroggins1f005d32009-08-10 17:36:42 -0400494 }
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700495 } else {
Leon Scroggins1f005d32009-08-10 17:36:42 -0400496 // If the tab was the current tab, we have to attach
497 // it to the view system again.
498 attachTabToContentView(appTab);
499 if (needsLoad) {
Patrick Scott9d53da02010-02-19 10:19:01 -0500500 loadUrlDataIn(appTab, urlData);
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700501 }
502 }
503 return;
Patrick Scottcd115892009-07-16 09:42:58 -0400504 } else {
505 // No matching application tab, try to find a regular tab
506 // with a matching url.
507 appTab = mTabControl.findUnusedTabWithUrl(urlData.mUrl);
Leon Scroggins25515f82009-08-19 15:31:58 -0400508 if (appTab != null) {
509 if (current != appTab) {
510 switchToTab(mTabControl.getTabIndex(appTab));
511 }
512 // Otherwise, we are already viewing the correct tab.
Patrick Scottcd115892009-07-16 09:42:58 -0400513 } else {
514 // if FLAG_ACTIVITY_BROUGHT_TO_FRONT flag is on, the url
515 // will be opened in a new tab unless we have reached
516 // MAX_TABS. Then the url will be opened in the current
517 // tab. If a new tab is created, it will have "true" for
518 // exit on close.
Leon Scroggins1f005d32009-08-10 17:36:42 -0400519 openTabAndShow(urlData, true, appId);
Patrick Scottcd115892009-07-16 09:42:58 -0400520 }
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700521 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800522 } else {
Grace Kloba638d3f42009-11-23 10:35:04 -0800523 if (!urlData.isEmpty()
524 && urlData.mUrl.startsWith("about:debug")) {
525 if ("about:debug.dom".equals(urlData.mUrl)) {
526 current.getWebView().dumpDomTree(false);
527 } else if ("about:debug.dom.file".equals(urlData.mUrl)) {
528 current.getWebView().dumpDomTree(true);
529 } else if ("about:debug.render".equals(urlData.mUrl)) {
530 current.getWebView().dumpRenderTree(false);
531 } else if ("about:debug.render.file".equals(urlData.mUrl)) {
532 current.getWebView().dumpRenderTree(true);
533 } else if ("about:debug.display".equals(urlData.mUrl)) {
534 current.getWebView().dumpDisplayTree();
Mike Reed9b78e1d2010-01-13 14:40:52 -0800535 } else if (urlData.mUrl.startsWith("about:debug.drag")) {
536 int index = urlData.mUrl.codePointAt(16) - '0';
537 if (index <= 0 || index > 9) {
538 current.getWebView().setDragTracker(null);
539 } else {
540 current.getWebView().setDragTracker(new MeshTracker(index));
541 }
Grace Kloba638d3f42009-11-23 10:35:04 -0800542 } else {
543 mSettings.toggleDebugSettings();
544 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800545 return;
546 }
Leon Scroggins1f005d32009-08-10 17:36:42 -0400547 // Get rid of the subwindow if it exists
548 dismissSubWindow(current);
Leon Scroggins8588d152010-04-15 11:01:53 -0400549 // If the current Tab is being used as an application tab,
550 // remove the association, since the new Intent means that it is
551 // no longer associated with that application.
552 current.setAppId(null);
Patrick Scott9d53da02010-02-19 10:19:01 -0500553 loadUrlDataIn(current, urlData);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800554 }
555 }
556 }
557
Satish Sampath565505b2009-05-29 15:37:27 +0100558 /**
559 * Launches the default web search activity with the query parameters if the given intent's data
560 * are identified as plain search terms and not URLs/shortcuts.
561 * @return true if the intent was handled and web search activity was launched, false if not.
562 */
563 private boolean handleWebSearchIntent(Intent intent) {
564 if (intent == null) return false;
565
566 String url = null;
567 final String action = intent.getAction();
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -0500568 if (RecognizerResultsIntent.ACTION_VOICE_SEARCH_RESULTS.equals(
569 action)) {
Leon Scroggins58d56c62010-01-28 15:12:40 -0500570 return false;
571 }
Satish Sampath565505b2009-05-29 15:37:27 +0100572 if (Intent.ACTION_VIEW.equals(action)) {
Grace Kloba1e705052009-09-29 13:13:36 -0700573 Uri data = intent.getData();
574 if (data != null) url = data.toString();
Satish Sampath565505b2009-05-29 15:37:27 +0100575 } else if (Intent.ACTION_SEARCH.equals(action)
576 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
577 || Intent.ACTION_WEB_SEARCH.equals(action)) {
578 url = intent.getStringExtra(SearchManager.QUERY);
579 }
Bjorn Bringert04851702009-09-22 10:36:01 +0100580 return handleWebSearchRequest(url, intent.getBundleExtra(SearchManager.APP_DATA),
581 intent.getStringExtra(SearchManager.EXTRA_DATA_KEY));
Satish Sampath565505b2009-05-29 15:37:27 +0100582 }
583
584 /**
585 * Launches the default web search activity with the query parameters if the given url string
586 * was identified as plain search terms and not URL/shortcut.
587 * @return true if the request was handled and web search activity was launched, false if not.
588 */
Bjorn Bringert04851702009-09-22 10:36:01 +0100589 private boolean handleWebSearchRequest(String inUrl, Bundle appData, String extraData) {
Satish Sampath565505b2009-05-29 15:37:27 +0100590 if (inUrl == null) return false;
591
592 // In general, we shouldn't modify URL from Intent.
593 // But currently, we get the user-typed URL from search box as well.
594 String url = fixUrl(inUrl).trim();
595
Leon Scroggins956cf012010-10-07 13:51:57 -0400596 // URLs are handled by the regular flow of control, so
Satish Sampath565505b2009-05-29 15:37:27 +0100597 // return early.
Dan Egnor5ee906c2009-11-18 12:11:49 -0800598 if (Patterns.WEB_URL.matcher(url).matches()
Leon Scroggins956cf012010-10-07 13:51:57 -0400599 || ACCEPTED_URI_SCHEMA.matcher(url).matches()) {
Satish Sampath565505b2009-05-29 15:37:27 +0100600 return false;
601 }
602
Leon Scroggins8d06e362010-03-24 14:45:57 -0400603 final ContentResolver cr = mResolver;
604 final String newUrl = url;
605 new AsyncTask<Void, Void, Void>() {
606 protected Void doInBackground(Void... unused) {
607 Browser.updateVisitedHistory(cr, newUrl, false);
608 Browser.addSearchUrl(cr, newUrl);
609 return null;
610 }
611 }.execute();
Satish Sampath565505b2009-05-29 15:37:27 +0100612
Bjorn Bringertd2670652010-09-13 14:06:41 +0100613 SearchEngine searchEngine = mSettings.getSearchEngine();
614 if (searchEngine == null) return false;
615 searchEngine.startSearch(this, url, appData, extraData);
Satish Sampath565505b2009-05-29 15:37:27 +0100616
617 return true;
618 }
619
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700620 private UrlData getUrlDataFromIntent(Intent intent) {
Leon Scroggins58d56c62010-01-28 15:12:40 -0500621 String url = "";
Grace Kloba068e48b2010-01-26 18:11:27 -0800622 Map<String, String> headers = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800623 if (intent != null) {
624 final String action = intent.getAction();
625 if (Intent.ACTION_VIEW.equals(action)) {
626 url = smartUrlFilter(intent.getData());
Grace Kloba068e48b2010-01-26 18:11:27 -0800627 if (url != null && url.startsWith("http")) {
Grace Kloba00f54c52010-01-27 14:53:51 -0800628 final Bundle pairs = intent
629 .getBundleExtra(Browser.EXTRA_HEADERS);
Grace Kloba2d508ed2010-01-28 11:39:15 -0800630 if (pairs != null && !pairs.isEmpty()) {
Grace Kloba00f54c52010-01-27 14:53:51 -0800631 Iterator<String> iter = pairs.keySet().iterator();
Grace Kloba068e48b2010-01-26 18:11:27 -0800632 headers = new HashMap<String, String>();
Grace Kloba00f54c52010-01-27 14:53:51 -0800633 while (iter.hasNext()) {
634 String key = iter.next();
635 headers.put(key, pairs.getString(key));
Grace Kloba068e48b2010-01-26 18:11:27 -0800636 }
637 }
Ed Tam8ba13bc2011-05-05 16:19:48 -0700638
639 // AppId will be set to the Browser for Search Bar initiated searches
640 final String appId = intent.getStringExtra(Browser.EXTRA_APPLICATION_ID);
641 if (getPackageName().equals(appId)) {
642 String rlz = mSettings.getRlzValue();
643 Uri uri = Uri.parse(url);
644 if (!rlz.isEmpty() && needsRlz(uri)) {
645 Uri rlzUri = addRlzParameter(uri, rlz);
646 url = rlzUri.toString();
647 }
648 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700649 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800650 } else if (Intent.ACTION_SEARCH.equals(action)
651 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
652 || Intent.ACTION_WEB_SEARCH.equals(action)) {
653 url = intent.getStringExtra(SearchManager.QUERY);
654 if (url != null) {
655 mLastEnteredUrl = url;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800656 // In general, we shouldn't modify URL from Intent.
657 // But currently, we get the user-typed URL from search box as well.
658 url = fixUrl(url);
659 url = smartUrlFilter(url);
Leon Scroggins8d06e362010-03-24 14:45:57 -0400660 final ContentResolver cr = mResolver;
661 final String newUrl = url;
662 new AsyncTask<Void, Void, Void>() {
663 protected Void doInBackground(Void... unused) {
664 Browser.updateVisitedHistory(cr, newUrl, false);
665 return null;
666 }
667 }.execute();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800668 String searchSource = "&source=android-" + GOOGLE_SEARCH_SOURCE_SUGGEST + "&";
669 if (url.contains(searchSource)) {
670 String source = null;
671 final Bundle appData = intent.getBundleExtra(SearchManager.APP_DATA);
672 if (appData != null) {
Bjorn Bringert10d1cca2010-02-10 14:22:12 +0000673 source = appData.getString(Search.SOURCE);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800674 }
675 if (TextUtils.isEmpty(source)) {
676 source = GOOGLE_SEARCH_SOURCE_UNKNOWN;
677 }
678 url = url.replace(searchSource, "&source=android-"+source+"&");
679 }
680 }
681 }
682 }
Leon Scroggins58d56c62010-01-28 15:12:40 -0500683 return new UrlData(url, headers, intent);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800684 }
Leon Scroggins58d56c62010-01-28 15:12:40 -0500685 /* package */ void showVoiceTitleBar(String title) {
686 mTitleBar.setInVoiceMode(true);
687 mFakeTitleBar.setInVoiceMode(true);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800688
Leon Scroggins58d56c62010-01-28 15:12:40 -0500689 mTitleBar.setDisplayTitle(title);
690 mFakeTitleBar.setDisplayTitle(title);
691 }
692 /* package */ void revertVoiceTitleBar() {
693 mTitleBar.setInVoiceMode(false);
694 mFakeTitleBar.setInVoiceMode(false);
695
Leon Scroggins003a5dd2010-03-10 12:13:14 -0500696 mTitleBar.setDisplayTitle(mUrl);
697 mFakeTitleBar.setDisplayTitle(mUrl);
Leon Scroggins58d56c62010-01-28 15:12:40 -0500698 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800699 /* package */ static String fixUrl(String inUrl) {
Cary Clark652ff872009-09-10 13:34:44 -0400700 // FIXME: Converting the url to lower case
701 // duplicates functionality in smartUrlFilter().
702 // However, changing all current callers of fixUrl to
703 // call smartUrlFilter in addition may have unwanted
704 // consequences, and is deferred for now.
705 int colon = inUrl.indexOf(':');
706 boolean allLower = true;
707 for (int index = 0; index < colon; index++) {
708 char ch = inUrl.charAt(index);
709 if (!Character.isLetter(ch)) {
710 break;
711 }
712 allLower &= Character.isLowerCase(ch);
713 if (index == colon - 1 && !allLower) {
714 inUrl = inUrl.substring(0, colon).toLowerCase()
715 + inUrl.substring(colon);
716 }
717 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800718 if (inUrl.startsWith("http://") || inUrl.startsWith("https://"))
719 return inUrl;
720 if (inUrl.startsWith("http:") ||
721 inUrl.startsWith("https:")) {
722 if (inUrl.startsWith("http:/") || inUrl.startsWith("https:/")) {
723 inUrl = inUrl.replaceFirst("/", "//");
724 } else inUrl = inUrl.replaceFirst(":", "://");
725 }
726 return inUrl;
727 }
728
Grace Kloba22ac16e2009-10-07 18:00:23 -0700729 @Override
730 protected void onResume() {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800731 super.onResume();
Dave Bort31a6d1c2009-04-13 15:56:49 -0700732 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800733 Log.v(LOGTAG, "BrowserActivity.onResume: this=" + this);
734 }
735
736 if (!mActivityInPause) {
737 Log.e(LOGTAG, "BrowserActivity is already resumed.");
738 return;
739 }
740
Mike Reed7bfa63b2009-05-28 11:08:32 -0400741 mTabControl.resumeCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800742 mActivityInPause = false;
Mike Reed7bfa63b2009-05-28 11:08:32 -0400743 resumeWebViewTimers();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800744
745 if (mWakeLock.isHeld()) {
746 mHandler.removeMessages(RELEASE_WAKELOCK);
747 mWakeLock.release();
748 }
749
The Android Open Source Project0c908882009-03-03 19:32:16 -0800750 registerReceiver(mNetworkStateIntentReceiver,
751 mNetworkStateChangedFilter);
752 WebView.enablePlatformNotifications();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800753 }
754
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400755 /**
756 * Since the actual title bar is embedded in the WebView, and removing it
Leon Scrogginsfe87bd32009-10-06 10:10:00 -0400757 * would change its appearance, use a different TitleBar to show overlayed
758 * at the top of the screen, when the menu is open or the page is loading.
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400759 */
760 private TitleBar mFakeTitleBar;
761
762 /**
763 * Keeps track of whether the options menu is open. This is important in
764 * determining whether to show or hide the title bar overlay.
765 */
766 private boolean mOptionsMenuOpen;
767
768 /**
769 * Only meaningful when mOptionsMenuOpen is true. This variable keeps track
770 * of whether the configuration has changed. The first onMenuOpened call
771 * after a configuration change is simply a reopening of the same menu
772 * (i.e. mIconView did not change).
773 */
774 private boolean mConfigChanged;
775
776 /**
777 * Whether or not the options menu is in its smaller, icon menu form. When
778 * true, we want the title bar overlay to be up. When false, we do not.
779 * Only meaningful if mOptionsMenuOpen is true.
780 */
781 private boolean mIconView;
782
Leon Scrogginsa81a7642009-08-31 17:05:41 -0400783 @Override
784 public boolean onMenuOpened(int featureId, Menu menu) {
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400785 if (Window.FEATURE_OPTIONS_PANEL == featureId) {
786 if (mOptionsMenuOpen) {
787 if (mConfigChanged) {
788 // We do not need to make any changes to the state of the
789 // title bar, since the only thing that happened was a
790 // change in orientation
791 mConfigChanged = false;
792 } else {
793 if (mIconView) {
794 // Switching the menu to expanded view, so hide the
795 // title bar.
796 hideFakeTitleBar();
797 mIconView = false;
798 } else {
799 // Switching the menu back to icon view, so show the
800 // title bar once again.
801 showFakeTitleBar();
802 mIconView = true;
803 }
804 }
805 } else {
806 // The options menu is closed, so open it, and show the title
807 showFakeTitleBar();
808 mOptionsMenuOpen = true;
809 mConfigChanged = false;
810 mIconView = true;
811 }
812 }
Leon Scrogginsa81a7642009-08-31 17:05:41 -0400813 return true;
814 }
815
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400816 private void showFakeTitleBar() {
Leon Scrogginsfe87bd32009-10-06 10:10:00 -0400817 if (mFakeTitleBar.getParent() == null && mActiveTabsPage == null
Grace Kloba847c25b2010-03-30 16:00:26 -0700818 && !mActivityInPause) {
819 WebView mainView = mTabControl.getCurrentWebView();
820 // if there is no current WebView, don't show the faked title bar;
Grace Kloba65190702010-04-02 23:37:26 -0700821 if (mainView == null) {
Cary Clarka0464552009-09-29 13:00:45 -0400822 return;
823 }
Cary Clark2c326e62010-08-19 18:40:57 -0400824 // Do not need to check for null, since the current tab will have
825 // at least a main WebView, or we would have returned above.
826 if (dialogIsUp()) {
827 // Do not show the fake title bar, which would cover up the
828 // find or select dialog.
829 return;
830 }
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400831
832 WindowManager manager
833 = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
834
835 // Add the title bar to the window manager so it can receive touches
836 // while the menu is up
837 WindowManager.LayoutParams params
838 = new WindowManager.LayoutParams(
Romain Guy15b8ec62010-01-08 15:06:43 -0800839 ViewGroup.LayoutParams.MATCH_PARENT,
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400840 ViewGroup.LayoutParams.WRAP_CONTENT,
Grace Kloba847c25b2010-03-30 16:00:26 -0700841 WindowManager.LayoutParams.TYPE_APPLICATION,
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400842 WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
Leon Scroggins68549862009-09-21 16:02:01 -0400843 PixelFormat.TRANSLUCENT);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400844 params.gravity = Gravity.TOP;
Grace Kloba847c25b2010-03-30 16:00:26 -0700845 boolean atTop = mainView.getScrollY() == 0;
Leon Scroggins83932c72009-09-30 11:55:54 -0400846 params.windowAnimations = atTop ? 0 : R.style.TitleBar;
Grace Kloba13f9ace2010-03-18 21:44:14 -0700847 manager.addView(mFakeTitleBar, params);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400848 }
849 }
850
851 @Override
852 public void onOptionsMenuClosed(Menu menu) {
853 mOptionsMenuOpen = false;
Leon Scrogginsa27ff192009-09-14 12:58:04 -0400854 if (!mInLoad) {
855 hideFakeTitleBar();
856 } else if (!mIconView) {
857 // The page is currently loading, and we are in expanded mode, so
858 // we were not showing the menu. Show it once again. It will be
859 // removed when the page finishes.
860 showFakeTitleBar();
861 }
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400862 }
Grace Kloba22ac16e2009-10-07 18:00:23 -0700863
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400864 private void hideFakeTitleBar() {
Leon Scrogginsfe87bd32009-10-06 10:10:00 -0400865 if (mFakeTitleBar.getParent() == null) return;
Leon Scroggins20329572009-09-23 17:42:41 -0400866 WindowManager.LayoutParams params = (WindowManager.LayoutParams)
Grace Kloba13f9ace2010-03-18 21:44:14 -0700867 mFakeTitleBar.getLayoutParams();
Leon Scroggins20329572009-09-23 17:42:41 -0400868 WebView mainView = mTabControl.getCurrentWebView();
869 // Although we decided whether or not to animate based on the current
870 // scroll position, the scroll position may have changed since the
871 // fake title bar was displayed. Make sure it has the appropriate
872 // animation/lack thereof before removing.
873 params.windowAnimations = mainView != null && mainView.getScrollY() == 0
Leon Scroggins83932c72009-09-30 11:55:54 -0400874 ? 0 : R.style.TitleBar;
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400875 WindowManager manager
876 = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
Grace Kloba13f9ace2010-03-18 21:44:14 -0700877 manager.updateViewLayout(mFakeTitleBar, params);
878 manager.removeView(mFakeTitleBar);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400879 }
880
The Android Open Source Project0c908882009-03-03 19:32:16 -0800881 /**
Leon Scrogginsc6fa1102009-09-21 10:40:01 -0400882 * Special method for the fake title bar to call when displaying its context
883 * menu, since it is in its own Window, and its parent does not show a
884 * context menu.
885 */
886 /* package */ void showTitleBarContextMenu() {
Cary Clark65f4a3c2009-09-28 17:05:06 -0400887 if (null == mTitleBar.getParent()) {
888 return;
889 }
Leon Scrogginsc6fa1102009-09-21 10:40:01 -0400890 openContextMenu(mTitleBar);
891 }
892
Leon Scrogginsb2b19f52009-10-09 16:10:00 -0400893 @Override
894 public void onContextMenuClosed(Menu menu) {
895 super.onContextMenuClosed(menu);
896 if (mInLoad) {
897 showFakeTitleBar();
898 }
899 }
900
Leon Scrogginsc6fa1102009-09-21 10:40:01 -0400901 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -0800902 * onSaveInstanceState(Bundle map)
903 * onSaveInstanceState is called right before onStop(). The map contains
904 * the saved state.
905 */
Grace Kloba22ac16e2009-10-07 18:00:23 -0700906 @Override
907 protected void onSaveInstanceState(Bundle outState) {
Dave Bort31a6d1c2009-04-13 15:56:49 -0700908 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800909 Log.v(LOGTAG, "BrowserActivity.onSaveInstanceState: this=" + this);
910 }
911 // the default implementation requires each view to have an id. As the
912 // browser handles the state itself and it doesn't use id for the views,
913 // don't call the default implementation. Otherwise it will trigger the
914 // warning like this, "couldn't save which view has focus because the
915 // focused view XXX has no id".
916
917 // Save all the tabs
918 mTabControl.saveState(outState);
919 }
920
Grace Kloba22ac16e2009-10-07 18:00:23 -0700921 @Override
922 protected void onPause() {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800923 super.onPause();
924
925 if (mActivityInPause) {
926 Log.e(LOGTAG, "BrowserActivity is already paused.");
927 return;
928 }
929
Mike Reed7bfa63b2009-05-28 11:08:32 -0400930 mTabControl.pauseCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800931 mActivityInPause = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -0400932 if (mTabControl.getCurrentIndex() >= 0 && !pauseWebViewTimers()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800933 mWakeLock.acquire();
934 mHandler.sendMessageDelayed(mHandler
935 .obtainMessage(RELEASE_WAKELOCK), WAKELOCK_TIMEOUT);
936 }
937
Leon Scrogginsa2ab6a72009-09-11 11:49:52 -0400938 // FIXME: This removes the active tabs page and resets the menu to
939 // MAIN_MENU. A better solution might be to do this work in onNewIntent
940 // but then we would need to save it in onSaveInstanceState and restore
941 // it in onCreate/onRestoreInstanceState
942 if (mActiveTabsPage != null) {
943 removeActiveTabPage(true);
944 }
945
The Android Open Source Project0c908882009-03-03 19:32:16 -0800946 cancelStopToast();
947
948 // unregister network state listener
949 unregisterReceiver(mNetworkStateIntentReceiver);
950 WebView.disablePlatformNotifications();
Ben Murdocha4909cb2010-11-30 20:48:15 +0000951
952 if (mCustomView != null) {
953 mTabControl.getCurrentWebView().getWebChromeClient().onHideCustomView();
954 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800955 }
956
Grace Kloba22ac16e2009-10-07 18:00:23 -0700957 @Override
958 protected void onDestroy() {
Dave Bort31a6d1c2009-04-13 15:56:49 -0700959 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800960 Log.v(LOGTAG, "BrowserActivity.onDestroy: this=" + this);
961 }
962 super.onDestroy();
Grace Kloba0923d692009-09-23 21:37:25 -0700963
Leon Scroggins8d5fa432009-10-02 15:55:59 -0400964 if (mUploadMessage != null) {
965 mUploadMessage.onReceiveValue(null);
966 mUploadMessage = null;
967 }
968
Grace Kloba0923d692009-09-23 21:37:25 -0700969 if (mTabControl == null) return;
970
Grace Kloba1fc98a32009-10-21 13:23:08 -0700971 // Remove the fake title bar if it is there
972 hideFakeTitleBar();
973
The Android Open Source Project0c908882009-03-03 19:32:16 -0800974 // Remove the current tab and sub window
Grace Kloba22ac16e2009-10-07 18:00:23 -0700975 Tab t = mTabControl.getCurrentTab();
Patrick Scottfb5e77f2009-04-08 19:17:37 -0700976 if (t != null) {
977 dismissSubWindow(t);
978 removeTabFromContentView(t);
979 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800980 // Destroy all the tabs
981 mTabControl.destroy();
982 WebIconDatabase.getInstance().close();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800983
Grace Klobab4da0ad2009-05-14 14:45:40 -0700984 unregisterReceiver(mPackageInstallationReceiver);
Bjorn Bringerta7611812010-03-24 11:12:02 +0000985
986 // Stop watching the default geolocation permissions
987 mSystemAllowGeolocationOrigins.stop();
988 mSystemAllowGeolocationOrigins = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800989 }
990
991 @Override
992 public void onConfigurationChanged(Configuration newConfig) {
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400993 mConfigChanged = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800994 super.onConfigurationChanged(newConfig);
995
996 if (mPageInfoDialog != null) {
997 mPageInfoDialog.dismiss();
998 showPageInfo(
999 mPageInfoView,
Leon Scrogginsc7b92f82010-01-11 18:17:31 -05001000 mPageInfoFromShowSSLCertificateOnError);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001001 }
1002 if (mSSLCertificateDialog != null) {
1003 mSSLCertificateDialog.dismiss();
1004 showSSLCertificate(
1005 mSSLCertificateView);
1006 }
1007 if (mSSLCertificateOnErrorDialog != null) {
1008 mSSLCertificateOnErrorDialog.dismiss();
1009 showSSLCertificateOnError(
1010 mSSLCertificateOnErrorView,
1011 mSSLCertificateOnErrorHandler,
1012 mSSLCertificateOnErrorError);
1013 }
1014 if (mHttpAuthenticationDialog != null) {
1015 String title = ((TextView) mHttpAuthenticationDialog
1016 .findViewById(com.android.internal.R.id.alertTitle)).getText()
1017 .toString();
1018 String name = ((TextView) mHttpAuthenticationDialog
1019 .findViewById(R.id.username_edit)).getText().toString();
1020 String password = ((TextView) mHttpAuthenticationDialog
1021 .findViewById(R.id.password_edit)).getText().toString();
1022 int focusId = mHttpAuthenticationDialog.getCurrentFocus()
1023 .getId();
1024 mHttpAuthenticationDialog.dismiss();
1025 showHttpAuthentication(mHttpAuthHandler, null, null, title,
1026 name, password, focusId);
1027 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001028 }
1029
Grace Kloba22ac16e2009-10-07 18:00:23 -07001030 @Override
1031 public void onLowMemory() {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001032 super.onLowMemory();
1033 mTabControl.freeMemory();
1034 }
1035
Cary Clarkff4d92c2010-03-25 11:17:03 -04001036 private void resumeWebViewTimers() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001037 Tab tab = mTabControl.getCurrentTab();
Cary Clarkff4d92c2010-03-25 11:17:03 -04001038 if (tab == null) return; // monkey can trigger this
Grace Kloba22ac16e2009-10-07 18:00:23 -07001039 boolean inLoad = tab.inLoad();
1040 if ((!mActivityInPause && !inLoad) || (mActivityInPause && inLoad)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001041 CookieSyncManager.getInstance().startSync();
Grace Kloba22ac16e2009-10-07 18:00:23 -07001042 WebView w = tab.getWebView();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001043 if (w != null) {
1044 w.resumeTimers();
1045 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001046 }
1047 }
1048
Mike Reed7bfa63b2009-05-28 11:08:32 -04001049 private boolean pauseWebViewTimers() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001050 Tab tab = mTabControl.getCurrentTab();
1051 boolean inLoad = tab.inLoad();
1052 if (mActivityInPause && !inLoad) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001053 CookieSyncManager.getInstance().stopSync();
1054 WebView w = mTabControl.getCurrentWebView();
1055 if (w != null) {
1056 w.pauseTimers();
1057 }
1058 return true;
1059 } else {
1060 return false;
1061 }
1062 }
1063
The Android Open Source Project0c908882009-03-03 19:32:16 -08001064 // Open the icon database and retain all the icons for visited sites.
1065 private void retainIconsOnStartup() {
1066 final WebIconDatabase db = WebIconDatabase.getInstance();
1067 db.open(getDir("icons", 0).getPath());
Leon Scroggins2c0f6112010-03-12 18:09:39 -05001068 Cursor c = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001069 try {
Leon Scroggins2c0f6112010-03-12 18:09:39 -05001070 c = Browser.getAllBookmarks(mResolver);
1071 if (c.moveToFirst()) {
1072 int urlIndex = c.getColumnIndex(Browser.BookmarkColumns.URL);
1073 do {
1074 String url = c.getString(urlIndex);
1075 db.retainIconForPageUrl(url);
1076 } while (c.moveToNext());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001077 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001078 } catch (IllegalStateException e) {
1079 Log.e(LOGTAG, "retainIconsOnStartup", e);
Leon Scroggins2c0f6112010-03-12 18:09:39 -05001080 } finally {
1081 if (c!= null) c.close();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001082 }
1083 }
1084
1085 // Helper method for getting the top window.
1086 WebView getTopWindow() {
1087 return mTabControl.getCurrentTopWebView();
1088 }
1089
Grace Kloba22ac16e2009-10-07 18:00:23 -07001090 TabControl getTabControl() {
1091 return mTabControl;
1092 }
1093
The Android Open Source Project0c908882009-03-03 19:32:16 -08001094 @Override
1095 public boolean onCreateOptionsMenu(Menu menu) {
1096 super.onCreateOptionsMenu(menu);
1097
1098 MenuInflater inflater = getMenuInflater();
1099 inflater.inflate(R.menu.browser, menu);
1100 mMenu = menu;
1101 updateInLoadMenuItems();
1102 return true;
1103 }
1104
1105 /**
1106 * As the menu can be open when loading state changes
1107 * we must manually update the state of the stop/reload menu
1108 * item
1109 */
1110 private void updateInLoadMenuItems() {
1111 if (mMenu == null) {
1112 return;
1113 }
1114 MenuItem src = mInLoad ?
1115 mMenu.findItem(R.id.stop_menu_id):
1116 mMenu.findItem(R.id.reload_menu_id);
1117 MenuItem dest = mMenu.findItem(R.id.stop_reload_menu_id);
1118 dest.setIcon(src.getIcon());
1119 dest.setTitle(src.getTitle());
1120 }
1121
1122 @Override
1123 public boolean onContextItemSelected(MenuItem item) {
1124 // chording is not an issue with context menus, but we use the same
1125 // options selector, so set mCanChord to true so we can access them.
1126 mCanChord = true;
1127 int id = item.getItemId();
Leon Scroggins96afcb12009-12-10 12:35:56 -05001128 boolean result = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001129 switch (id) {
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001130 // For the context menu from the title bar
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001131 case R.id.title_bar_copy_page_url:
Leon Scroggins96afcb12009-12-10 12:35:56 -05001132 Tab currentTab = mTabControl.getCurrentTab();
1133 if (null == currentTab) {
1134 result = false;
1135 break;
1136 }
1137 WebView mainView = currentTab.getWebView();
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001138 if (null == mainView) {
Leon Scroggins96afcb12009-12-10 12:35:56 -05001139 result = false;
1140 break;
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001141 }
Leon Scroggins96afcb12009-12-10 12:35:56 -05001142 copy(mainView.getUrl());
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001143 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001144 // -- Browser context menu
1145 case R.id.open_context_menu_id:
1146 case R.id.open_newtab_context_menu_id:
1147 case R.id.bookmark_context_menu_id:
1148 case R.id.save_link_context_menu_id:
1149 case R.id.share_link_context_menu_id:
1150 case R.id.copy_link_context_menu_id:
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001151 final WebView webView = getTopWindow();
1152 if (null == webView) {
Leon Scroggins96afcb12009-12-10 12:35:56 -05001153 result = false;
1154 break;
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001155 }
1156 final HashMap hrefMap = new HashMap();
1157 hrefMap.put("webview", webView);
1158 final Message msg = mHandler.obtainMessage(
1159 FOCUS_NODE_HREF, id, 0, hrefMap);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001160 webView.requestFocusNodeHref(msg);
1161 break;
1162
1163 default:
1164 // For other context menus
Leon Scroggins96afcb12009-12-10 12:35:56 -05001165 result = onOptionsItemSelected(item);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001166 }
1167 mCanChord = false;
Leon Scroggins96afcb12009-12-10 12:35:56 -05001168 return result;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001169 }
1170
1171 private Bundle createGoogleSearchSourceBundle(String source) {
1172 Bundle bundle = new Bundle();
Bjorn Bringert10d1cca2010-02-10 14:22:12 +00001173 bundle.putString(Search.SOURCE, source);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001174 return bundle;
1175 }
1176
Leon Scroggins8ad29922010-02-16 12:33:55 -05001177 /* package */ void editUrl() {
Leon Scroggins68579392009-09-15 15:31:54 -04001178 if (mOptionsMenuOpen) closeOptionsMenu();
Leon Scroggins5bbe9802009-07-31 13:10:55 -04001179 String url = (getTopWindow() == null) ? null : getTopWindow().getUrl();
Grace Kloba83f47342009-07-20 10:44:31 -07001180 startSearch(mSettings.getHomePage().equals(url) ? null : url, true,
Leon Scroggins8ad29922010-02-16 12:33:55 -05001181 null, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001182 }
1183
Leon Scroggins8ad29922010-02-16 12:33:55 -05001184 /**
1185 * Overriding this to insert a local information bundle
1186 */
The Android Open Source Project0c908882009-03-03 19:32:16 -08001187 @Override
1188 public void startSearch(String initialQuery, boolean selectInitialQuery,
1189 Bundle appSearchData, boolean globalSearch) {
1190 if (appSearchData == null) {
1191 appSearchData = createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_TYPE);
1192 }
Leon Scroggins III430057d2010-09-14 10:57:37 -04001193
1194 SearchEngine searchEngine = mSettings.getSearchEngine();
1195 if (searchEngine != null && !searchEngine.supportsVoiceSearch()) {
1196 appSearchData.putBoolean(SearchManager.DISABLE_VOICE_SEARCH, true);
1197 }
1198
The Android Open Source Project0c908882009-03-03 19:32:16 -08001199 super.startSearch(initialQuery, selectInitialQuery, appSearchData, globalSearch);
1200 }
1201
Leon Scroggins1f005d32009-08-10 17:36:42 -04001202 /**
1203 * Switch tabs. Called by the TitleBarSet when sliding the title bar
1204 * results in changing tabs.
Leon Scroggins160a7e72009-08-14 18:28:01 -04001205 * @param index Index of the tab to change to, as defined by
1206 * mTabControl.getTabIndex(Tab t).
1207 * @return boolean True if we successfully switched to a different tab. If
1208 * the indexth tab is null, or if that tab is the same as
1209 * the current one, return false.
Leon Scroggins1f005d32009-08-10 17:36:42 -04001210 */
Leon Scroggins160a7e72009-08-14 18:28:01 -04001211 /* package */ boolean switchToTab(int index) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001212 Tab tab = mTabControl.getTab(index);
1213 Tab currentTab = mTabControl.getCurrentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04001214 if (tab == null || tab == currentTab) {
Leon Scroggins160a7e72009-08-14 18:28:01 -04001215 return false;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001216 }
1217 if (currentTab != null) {
1218 // currentTab may be null if it was just removed. In that case,
1219 // we do not need to remove it
1220 removeTabFromContentView(currentTab);
1221 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001222 mTabControl.setCurrentTab(tab);
1223 attachTabToContentView(tab);
Grace Klobaeb6eef42009-09-15 17:56:32 -07001224 resetTitleIconAndProgress();
1225 updateLockIconToLatest();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001226 return true;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001227 }
1228
Grace Kloba22ac16e2009-10-07 18:00:23 -07001229 /* package */ Tab openTabToHomePage() {
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001230 return openTabAndShow(mSettings.getHomePage(), false, null);
1231 }
1232
Leon Scroggins1f005d32009-08-10 17:36:42 -04001233 /* package */ void closeCurrentWindow() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001234 final Tab current = mTabControl.getCurrentTab();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001235 if (mTabControl.getTabCount() == 1) {
Leon Scroggins30444232009-09-04 18:36:20 -04001236 // This is the last tab. Open a new one, with the home
1237 // page and close the current one.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001238 openTabToHomePage();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001239 closeTab(current);
Leon Scroggins160a7e72009-08-14 18:28:01 -04001240 return;
1241 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07001242 final Tab parent = current.getParentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04001243 int indexToShow = -1;
1244 if (parent != null) {
1245 indexToShow = mTabControl.getTabIndex(parent);
1246 } else {
Leon Scroggins160a7e72009-08-14 18:28:01 -04001247 final int currentIndex = mTabControl.getCurrentIndex();
1248 // Try to move to the tab to the right
1249 indexToShow = currentIndex + 1;
1250 if (indexToShow > mTabControl.getTabCount() - 1) {
1251 // Try to move to the tab to the left
1252 indexToShow = currentIndex - 1;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001253 }
1254 }
Leon Scroggins160a7e72009-08-14 18:28:01 -04001255 if (switchToTab(indexToShow)) {
1256 // Close window
1257 closeTab(current);
1258 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001259 }
1260
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001261 private ActiveTabsPage mActiveTabsPage;
1262
1263 /**
1264 * Remove the active tabs page.
1265 * @param needToAttach If true, the active tabs page did not attach a tab
1266 * to the content view, so we need to do that here.
1267 */
1268 /* package */ void removeActiveTabPage(boolean needToAttach) {
1269 mContentView.removeView(mActiveTabsPage);
1270 mActiveTabsPage = null;
1271 mMenuState = R.id.MAIN_MENU;
1272 if (needToAttach) {
1273 attachTabToContentView(mTabControl.getCurrentTab());
1274 }
1275 getTopWindow().requestFocus();
1276 }
1277
Cary Clark2c326e62010-08-19 18:40:57 -04001278 private WebView showDialog(WebDialog dialog) {
Cary Clark2c326e62010-08-19 18:40:57 -04001279 Tab tab = mTabControl.getCurrentTab();
1280 if (tab.getSubWebView() == null) {
1281 // If the find or select is being performed on the main webview,
1282 // remove the embedded title bar.
1283 WebView mainView = tab.getWebView();
1284 if (mainView != null) {
1285 mainView.setEmbeddedTitleBar(null);
1286 }
1287 }
1288 hideFakeTitleBar();
1289 mMenuState = EMPTY_MENU;
1290 return tab.showDialog(dialog);
1291 }
1292
The Android Open Source Project0c908882009-03-03 19:32:16 -08001293 @Override
1294 public boolean onOptionsItemSelected(MenuItem item) {
1295 if (!mCanChord) {
1296 // The user has already fired a shortcut with this hold down of the
1297 // menu key.
1298 return false;
1299 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001300 if (null == getTopWindow()) {
Leon Scroggins0d7ae0e2009-06-05 11:04:45 -04001301 return false;
1302 }
Grace Kloba6ee9c492009-07-13 10:04:34 -07001303 if (mMenuIsDown) {
1304 // The shortcut action consumes the MENU. Even if it is still down,
1305 // it won't trigger the next shortcut action. In the case of the
1306 // shortcut action triggering a new activity, like Bookmarks, we
1307 // won't get onKeyUp for MENU. So it is important to reset it here.
1308 mMenuIsDown = false;
1309 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001310 switch (item.getItemId()) {
1311 // -- Main menu
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001312 case R.id.new_tab_menu_id:
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001313 openTabToHomePage();
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001314 break;
1315
Leon Scroggins64b80f32009-08-07 12:03:34 -04001316 case R.id.goto_menu_id:
Leon Scroggins8ad29922010-02-16 12:33:55 -05001317 editUrl();
Leon Scrogginsb3a5bed2009-09-28 11:21:56 -04001318 break;
1319
1320 case R.id.bookmarks_menu_id:
Leon Scroggins30444232009-09-04 18:36:20 -04001321 bookmarksOrHistoryPicker(false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001322 break;
1323
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001324 case R.id.active_tabs_menu_id:
1325 mActiveTabsPage = new ActiveTabsPage(this, mTabControl);
1326 removeTabFromContentView(mTabControl.getCurrentTab());
Leon Scroggins43de6162009-09-14 19:59:58 -04001327 hideFakeTitleBar();
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001328 mContentView.addView(mActiveTabsPage, COVER_SCREEN_PARAMS);
1329 mActiveTabsPage.requestFocus();
1330 mMenuState = EMPTY_MENU;
1331 break;
1332
Leon Scroggins1f005d32009-08-10 17:36:42 -04001333 case R.id.add_bookmark_menu_id:
1334 Intent i = new Intent(BrowserActivity.this,
1335 AddBookmarkPage.class);
1336 WebView w = getTopWindow();
1337 i.putExtra("url", w.getUrl());
1338 i.putExtra("title", w.getTitle());
Grace Kloba83cdb2c2009-09-16 00:48:57 -07001339 i.putExtra("touch_icon_url", w.getTouchIconUrl());
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01001340 i.putExtra("thumbnail", createScreenshot(w));
Leon Scroggins1f005d32009-08-10 17:36:42 -04001341 startActivity(i);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001342 break;
1343
1344 case R.id.stop_reload_menu_id:
1345 if (mInLoad) {
1346 stopLoading();
1347 } else {
1348 getTopWindow().reload();
1349 }
1350 break;
1351
1352 case R.id.back_menu_id:
1353 getTopWindow().goBack();
1354 break;
1355
1356 case R.id.forward_menu_id:
1357 getTopWindow().goForward();
1358 break;
1359
1360 case R.id.close_menu_id:
1361 // Close the subwindow if it exists.
1362 if (mTabControl.getCurrentSubWindow() != null) {
1363 dismissSubWindow(mTabControl.getCurrentTab());
1364 break;
1365 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001366 closeCurrentWindow();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001367 break;
1368
1369 case R.id.homepage_menu_id:
Grace Kloba22ac16e2009-10-07 18:00:23 -07001370 Tab current = mTabControl.getCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001371 if (current != null) {
1372 dismissSubWindow(current);
Leon Scroggins92472e82010-02-17 16:32:28 -05001373 loadUrl(current.getWebView(), mSettings.getHomePage());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001374 }
1375 break;
1376
1377 case R.id.preferences_menu_id:
1378 Intent intent = new Intent(this,
1379 BrowserPreferencesPage.class);
Leon Scrogginsd5304942009-12-10 16:11:39 -05001380 intent.putExtra(BrowserPreferencesPage.CURRENT_PAGE,
1381 getTopWindow().getUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001382 startActivityForResult(intent, PREFERENCES_PAGE);
1383 break;
1384
1385 case R.id.find_menu_id:
Cary Clark2c326e62010-08-19 18:40:57 -04001386 showFindDialog();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001387 break;
1388
1389 case R.id.select_text_id:
Cary Clark5feb8ad2010-09-21 14:28:49 -04001390 if (true) {
1391 Tab currentTab = mTabControl.getCurrentTab();
1392 if (currentTab != null) {
1393 currentTab.getWebView().setUpSelect();
1394 }
1395 } else {
1396 showSelectDialog();
1397 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001398 break;
Cary Clark2c326e62010-08-19 18:40:57 -04001399
The Android Open Source Project0c908882009-03-03 19:32:16 -08001400 case R.id.page_info_menu_id:
1401 showPageInfo(mTabControl.getCurrentTab(), false);
1402 break;
1403
1404 case R.id.classic_history_menu_id:
Leon Scroggins30444232009-09-04 18:36:20 -04001405 bookmarksOrHistoryPicker(true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001406 break;
1407
Leon Scroggins96afcb12009-12-10 12:35:56 -05001408 case R.id.title_bar_share_page_url:
The Android Open Source Project0c908882009-03-03 19:32:16 -08001409 case R.id.share_page_menu_id:
Leon Scroggins96afcb12009-12-10 12:35:56 -05001410 Tab currentTab = mTabControl.getCurrentTab();
1411 if (null == currentTab) {
1412 mCanChord = false;
1413 return false;
1414 }
1415 currentTab.populatePickerData();
1416 sharePage(this, currentTab.getTitle(),
1417 currentTab.getUrl(), currentTab.getFavicon(),
1418 createScreenshot(currentTab.getWebView()));
The Android Open Source Project0c908882009-03-03 19:32:16 -08001419 break;
1420
1421 case R.id.dump_nav_menu_id:
1422 getTopWindow().debugDump();
1423 break;
1424
Andrei Popescu7a8b88b2010-02-02 00:30:38 +00001425 case R.id.dump_counters_menu_id:
1426 getTopWindow().dumpV8Counters();
1427 break;
1428
The Android Open Source Project0c908882009-03-03 19:32:16 -08001429 case R.id.zoom_in_menu_id:
1430 getTopWindow().zoomIn();
1431 break;
1432
1433 case R.id.zoom_out_menu_id:
1434 getTopWindow().zoomOut();
1435 break;
1436
1437 case R.id.view_downloads_menu_id:
Leon Scroggins IIIa682a3c2010-09-27 12:32:40 -04001438 viewDownloads();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001439 break;
1440
The Android Open Source Project0c908882009-03-03 19:32:16 -08001441 case R.id.window_one_menu_id:
1442 case R.id.window_two_menu_id:
1443 case R.id.window_three_menu_id:
1444 case R.id.window_four_menu_id:
1445 case R.id.window_five_menu_id:
1446 case R.id.window_six_menu_id:
1447 case R.id.window_seven_menu_id:
1448 case R.id.window_eight_menu_id:
1449 {
1450 int menuid = item.getItemId();
1451 for (int id = 0; id < WINDOW_SHORTCUT_ID_ARRAY.length; id++) {
1452 if (WINDOW_SHORTCUT_ID_ARRAY[id] == menuid) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001453 Tab desiredTab = mTabControl.getTab(id);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001454 if (desiredTab != null &&
1455 desiredTab != mTabControl.getCurrentTab()) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001456 switchToTab(id);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001457 }
1458 break;
1459 }
1460 }
1461 }
1462 break;
1463
1464 default:
1465 if (!super.onOptionsItemSelected(item)) {
1466 return false;
1467 }
1468 // Otherwise fall through.
1469 }
1470 mCanChord = false;
1471 return true;
1472 }
1473
Cary Clark2c326e62010-08-19 18:40:57 -04001474 private boolean dialogIsUp() {
1475 return null != mFindDialog && mFindDialog.isVisible() ||
1476 null != mSelectDialog && mSelectDialog.isVisible();
1477 }
1478
1479 private boolean closeDialog(WebDialog dialog) {
1480 if (null == dialog || !dialog.isVisible()) return false;
1481 Tab currentTab = mTabControl.getCurrentTab();
1482 currentTab.closeDialog(dialog);
1483 dialog.dismiss();
1484 return true;
1485 }
1486
1487 /*
1488 * Remove the find dialog or select dialog.
1489 */
1490 public void closeDialogs() {
1491 if (!(closeDialog(mFindDialog) || closeDialog(mSelectDialog))) return;
1492 // If the Find was being performed in the main WebView, replace the
1493 // embedded title bar.
1494 Tab currentTab = mTabControl.getCurrentTab();
1495 if (currentTab.getSubWebView() == null) {
1496 WebView mainView = currentTab.getWebView();
1497 if (mainView != null) {
1498 mainView.setEmbeddedTitleBar(mTitleBar);
1499 }
1500 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001501 mMenuState = R.id.MAIN_MENU;
Cary Clark2c326e62010-08-19 18:40:57 -04001502 if (mInLoad) {
1503 // The title bar was hidden, because otherwise it would cover up the
1504 // find or select dialog. Now that the dialog has been removed,
1505 // show the fake title bar once again.
1506 showFakeTitleBar();
1507 }
1508 }
1509
1510 public void showFindDialog() {
1511 if (null == mFindDialog) {
1512 mFindDialog = new FindDialog(this);
1513 }
1514 showDialog(mFindDialog).setFindIsUp(true);
1515 }
1516
1517 public void setFindDialogText(String text) {
1518 mFindDialog.setText(text);
1519 }
1520
1521 public void showSelectDialog() {
1522 if (null == mSelectDialog) {
1523 mSelectDialog = new SelectDialog(this);
1524 }
1525 showDialog(mSelectDialog).setUpSelect();
1526 mSelectDialog.hideSoftInput();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001527 }
1528
Grace Kloba22ac16e2009-10-07 18:00:23 -07001529 @Override
1530 public boolean onPrepareOptionsMenu(Menu menu) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001531 // This happens when the user begins to hold down the menu key, so
1532 // allow them to chord to get a shortcut.
1533 mCanChord = true;
1534 // Note: setVisible will decide whether an item is visible; while
1535 // setEnabled() will decide whether an item is enabled, which also means
1536 // whether the matching shortcut key will function.
1537 super.onPrepareOptionsMenu(menu);
1538 switch (mMenuState) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001539 case EMPTY_MENU:
1540 if (mCurrentMenuState != mMenuState) {
1541 menu.setGroupVisible(R.id.MAIN_MENU, false);
1542 menu.setGroupEnabled(R.id.MAIN_MENU, false);
1543 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001544 }
1545 break;
1546 default:
1547 if (mCurrentMenuState != mMenuState) {
1548 menu.setGroupVisible(R.id.MAIN_MENU, true);
1549 menu.setGroupEnabled(R.id.MAIN_MENU, true);
1550 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001551 }
1552 final WebView w = getTopWindow();
1553 boolean canGoBack = false;
1554 boolean canGoForward = false;
1555 boolean isHome = false;
1556 if (w != null) {
1557 canGoBack = w.canGoBack();
1558 canGoForward = w.canGoForward();
1559 isHome = mSettings.getHomePage().equals(w.getUrl());
1560 }
1561 final MenuItem back = menu.findItem(R.id.back_menu_id);
1562 back.setEnabled(canGoBack);
1563
1564 final MenuItem home = menu.findItem(R.id.homepage_menu_id);
1565 home.setEnabled(!isHome);
1566
1567 menu.findItem(R.id.forward_menu_id)
1568 .setEnabled(canGoForward);
1569
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001570 menu.findItem(R.id.new_tab_menu_id).setEnabled(
Grace Kloba22ac16e2009-10-07 18:00:23 -07001571 mTabControl.canCreateNewTab());
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001572
The Android Open Source Project0c908882009-03-03 19:32:16 -08001573 // decide whether to show the share link option
1574 PackageManager pm = getPackageManager();
1575 Intent send = new Intent(Intent.ACTION_SEND);
1576 send.setType("text/plain");
1577 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1578 menu.findItem(R.id.share_page_menu_id).setVisible(ri != null);
1579
The Android Open Source Project0c908882009-03-03 19:32:16 -08001580 boolean isNavDump = mSettings.isNavDump();
1581 final MenuItem nav = menu.findItem(R.id.dump_nav_menu_id);
1582 nav.setVisible(isNavDump);
1583 nav.setEnabled(isNavDump);
Andrei Popescu7a8b88b2010-02-02 00:30:38 +00001584
1585 boolean showDebugSettings = mSettings.showDebugSettings();
1586 final MenuItem counter = menu.findItem(R.id.dump_counters_menu_id);
1587 counter.setVisible(showDebugSettings);
1588 counter.setEnabled(showDebugSettings);
1589
The Android Open Source Project0c908882009-03-03 19:32:16 -08001590 break;
1591 }
1592 mCurrentMenuState = mMenuState;
1593 return true;
1594 }
1595
1596 @Override
1597 public void onCreateContextMenu(ContextMenu menu, View v,
1598 ContextMenuInfo menuInfo) {
Leon Scroggins4e9f89b2010-02-22 16:54:14 -05001599 if (v instanceof TitleBar) {
1600 return;
1601 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001602 WebView webview = (WebView) v;
1603 WebView.HitTestResult result = webview.getHitTestResult();
1604 if (result == null) {
1605 return;
1606 }
1607
1608 int type = result.getType();
1609 if (type == WebView.HitTestResult.UNKNOWN_TYPE) {
1610 Log.w(LOGTAG,
1611 "We should not show context menu when nothing is touched");
1612 return;
1613 }
1614 if (type == WebView.HitTestResult.EDIT_TEXT_TYPE) {
1615 // let TextView handles context menu
1616 return;
1617 }
1618
1619 // Note, http://b/issue?id=1106666 is requesting that
1620 // an inflated menu can be used again. This is not available
1621 // yet, so inflate each time (yuk!)
1622 MenuInflater inflater = getMenuInflater();
1623 inflater.inflate(R.menu.browsercontext, menu);
1624
1625 // Show the correct menu group
1626 String extra = result.getExtra();
1627 menu.setGroupVisible(R.id.PHONE_MENU,
1628 type == WebView.HitTestResult.PHONE_TYPE);
1629 menu.setGroupVisible(R.id.EMAIL_MENU,
1630 type == WebView.HitTestResult.EMAIL_TYPE);
1631 menu.setGroupVisible(R.id.GEO_MENU,
1632 type == WebView.HitTestResult.GEO_TYPE);
1633 menu.setGroupVisible(R.id.IMAGE_MENU,
1634 type == WebView.HitTestResult.IMAGE_TYPE
1635 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1636 menu.setGroupVisible(R.id.ANCHOR_MENU,
1637 type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1638 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1639
1640 // Setup custom handling depending on the type
1641 switch (type) {
1642 case WebView.HitTestResult.PHONE_TYPE:
1643 menu.setHeaderTitle(Uri.decode(extra));
1644 menu.findItem(R.id.dial_context_menu_id).setIntent(
1645 new Intent(Intent.ACTION_VIEW, Uri
1646 .parse(WebView.SCHEME_TEL + extra)));
1647 Intent addIntent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
1648 addIntent.putExtra(Insert.PHONE, Uri.decode(extra));
Cary Clark5e335a32009-09-22 14:53:11 -04001649 addIntent.setType(ContactsContract.Contacts.CONTENT_ITEM_TYPE);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001650 menu.findItem(R.id.add_contact_context_menu_id).setIntent(
1651 addIntent);
1652 menu.findItem(R.id.copy_phone_context_menu_id).setOnMenuItemClickListener(
1653 new Copy(extra));
1654 break;
1655
1656 case WebView.HitTestResult.EMAIL_TYPE:
1657 menu.setHeaderTitle(extra);
1658 menu.findItem(R.id.email_context_menu_id).setIntent(
1659 new Intent(Intent.ACTION_VIEW, Uri
1660 .parse(WebView.SCHEME_MAILTO + extra)));
1661 menu.findItem(R.id.copy_mail_context_menu_id).setOnMenuItemClickListener(
1662 new Copy(extra));
1663 break;
1664
1665 case WebView.HitTestResult.GEO_TYPE:
1666 menu.setHeaderTitle(extra);
1667 menu.findItem(R.id.map_context_menu_id).setIntent(
1668 new Intent(Intent.ACTION_VIEW, Uri
1669 .parse(WebView.SCHEME_GEO
1670 + URLEncoder.encode(extra))));
1671 menu.findItem(R.id.copy_geo_context_menu_id).setOnMenuItemClickListener(
1672 new Copy(extra));
1673 break;
1674
1675 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1676 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
1677 TextView titleView = (TextView) LayoutInflater.from(this)
1678 .inflate(android.R.layout.browser_link_context_header,
1679 null);
1680 titleView.setText(extra);
1681 menu.setHeaderView(titleView);
1682 // decide whether to show the open link in new tab option
1683 menu.findItem(R.id.open_newtab_context_menu_id).setVisible(
Grace Kloba22ac16e2009-10-07 18:00:23 -07001684 mTabControl.canCreateNewTab());
Ben Murdochde353622009-10-12 10:29:00 +01001685 menu.findItem(R.id.bookmark_context_menu_id).setVisible(
1686 Bookmarks.urlHasAcceptableScheme(extra));
The Android Open Source Project0c908882009-03-03 19:32:16 -08001687 PackageManager pm = getPackageManager();
1688 Intent send = new Intent(Intent.ACTION_SEND);
1689 send.setType("text/plain");
1690 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1691 menu.findItem(R.id.share_link_context_menu_id).setVisible(ri != null);
1692 if (type == WebView.HitTestResult.SRC_ANCHOR_TYPE) {
1693 break;
1694 }
1695 // otherwise fall through to handle image part
1696 case WebView.HitTestResult.IMAGE_TYPE:
1697 if (type == WebView.HitTestResult.IMAGE_TYPE) {
1698 menu.setHeaderTitle(extra);
1699 }
1700 menu.findItem(R.id.view_image_context_menu_id).setIntent(
1701 new Intent(Intent.ACTION_VIEW, Uri.parse(extra)));
1702 menu.findItem(R.id.download_context_menu_id).
1703 setOnMenuItemClickListener(new Download(extra));
Ben Murdoch4f75ba22009-10-27 11:48:28 +00001704 menu.findItem(R.id.set_wallpaper_context_menu_id).
1705 setOnMenuItemClickListener(new SetAsWallpaper(extra));
The Android Open Source Project0c908882009-03-03 19:32:16 -08001706 break;
1707
1708 default:
1709 Log.w(LOGTAG, "We should not get here.");
1710 break;
1711 }
Leon Scrogginsb2b19f52009-10-09 16:10:00 -04001712 hideFakeTitleBar();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001713 }
1714
The Android Open Source Project0c908882009-03-03 19:32:16 -08001715 // Attach the given tab to the content view.
Grace Klobac928c302009-09-17 11:51:21 -07001716 // this should only be called for the current tab.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001717 private void attachTabToContentView(Tab t) {
Steve Block2bc69912009-07-30 14:45:13 +01001718 // Attach the container that contains the main WebView and any other UI
1719 // associated with the tab.
Patrick Scottd0119532009-09-17 08:00:31 -04001720 t.attachTabToContentView(mContentView);
Ben Murdochbff2d602009-07-01 20:19:05 +01001721
1722 if (mShouldShowErrorConsole) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001723 ErrorConsoleView errorConsole = t.getErrorConsole(true);
Ben Murdochbff2d602009-07-01 20:19:05 +01001724 if (errorConsole.numberOfErrors() == 0) {
1725 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
1726 } else {
1727 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
1728 }
1729
1730 mErrorConsoleContainer.addView(errorConsole,
Romain Guy15b8ec62010-01-08 15:06:43 -08001731 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
Ben Murdochbff2d602009-07-01 20:19:05 +01001732 ViewGroup.LayoutParams.WRAP_CONTENT));
1733 }
1734
Leon Scroggins39ab28e2009-09-02 21:20:30 -04001735 WebView view = t.getWebView();
Leon Scroggins55a5bc22009-09-04 17:00:08 -04001736 view.setEmbeddedTitleBar(mTitleBar);
Leon Scroggins58d56c62010-01-28 15:12:40 -05001737 if (t.isInVoiceSearchMode()) {
1738 showVoiceTitleBar(t.getVoiceDisplayTitle());
1739 } else {
1740 revertVoiceTitleBar();
1741 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001742 // Request focus on the top window.
1743 t.getTopWindow().requestFocus();
1744 }
1745
1746 // Attach a sub window to the main WebView of the given tab.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001747 void attachSubWindow(Tab t) {
Patrick Scottd0119532009-09-17 08:00:31 -04001748 t.attachSubWindow(mContentView);
1749 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001750 }
1751
1752 // Remove the given tab from the content view.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001753 private void removeTabFromContentView(Tab t) {
Steve Block2bc69912009-07-30 14:45:13 +01001754 // Remove the container that contains the main WebView.
Patrick Scottd0119532009-09-17 08:00:31 -04001755 t.removeTabFromContentView(mContentView);
Ben Murdochbff2d602009-07-01 20:19:05 +01001756
Grace Kloba22ac16e2009-10-07 18:00:23 -07001757 ErrorConsoleView errorConsole = t.getErrorConsole(false);
1758 if (errorConsole != null) {
1759 mErrorConsoleContainer.removeView(errorConsole);
Ben Murdochbff2d602009-07-01 20:19:05 +01001760 }
1761
Leon Scroggins39ab28e2009-09-02 21:20:30 -04001762 WebView view = t.getWebView();
Leon Scrogginsbb85b902009-09-14 19:27:20 -04001763 if (view != null) {
1764 view.setEmbeddedTitleBar(null);
1765 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001766 }
1767
1768 // Remove the sub window if it exists. Also called by TabControl when the
1769 // user clicks the 'X' to dismiss a sub window.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001770 /* package */ void dismissSubWindow(Tab t) {
Patrick Scottd0119532009-09-17 08:00:31 -04001771 t.removeSubWindow(mContentView);
Grace Kloba22ac16e2009-10-07 18:00:23 -07001772 // dismiss the subwindow. This will destroy the WebView.
1773 t.dismissSubWindow();
Patrick Scottd0119532009-09-17 08:00:31 -04001774 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001775 }
1776
Leon Scroggins1f005d32009-08-10 17:36:42 -04001777 // A wrapper function of {@link #openTabAndShow(UrlData, boolean, String)}
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07001778 // that accepts url as string.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001779 private Tab openTabAndShow(String url, boolean closeOnExit, String appId) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001780 return openTabAndShow(new UrlData(url), closeOnExit, appId);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001781 }
1782
1783 // This method does a ton of stuff. It will attempt to create a new tab
1784 // if we haven't reached MAX_TABS. Otherwise it uses the current tab. If
Leon Scroggins1f005d32009-08-10 17:36:42 -04001785 // url isn't null, it will load the given url.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001786 /* package */Tab openTabAndShow(UrlData urlData, boolean closeOnExit,
1787 String appId) {
John Reckafa4ab12011-06-20 18:30:26 -07001788 Tab currentTab = mTabControl.getCurrentTab();
1789 if (!mTabControl.canCreateNewTab()) {
1790 Tab closeTab = mTabControl.getTab(0);
1791 closeTab(closeTab);
1792 if (closeTab == currentTab) {
1793 currentTab = null;
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001794 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001795 }
John Reckafa4ab12011-06-20 18:30:26 -07001796 final Tab tab = mTabControl.createNewTab(closeOnExit, appId,
1797 urlData.mUrl);
1798 WebView webview = tab.getWebView();
1799 // If the last tab was removed from the active tabs page, currentTab
1800 // will be null.
1801 if (currentTab != null) {
1802 removeTabFromContentView(currentTab);
1803 }
1804 // We must set the new tab as the current tab to reflect the old
1805 // animation behavior.
1806 mTabControl.setCurrentTab(tab);
1807 attachTabToContentView(tab);
1808 if (!urlData.isEmpty()) {
1809 loadUrlDataIn(tab, urlData);
1810 }
1811 return tab;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001812 }
1813
Grace Kloba22ac16e2009-10-07 18:00:23 -07001814 private Tab openTab(String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001815 if (mSettings.openInBackground()) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001816 Tab t = mTabControl.createNewTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001817 if (t != null) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001818 WebView view = t.getWebView();
Leon Scroggins92472e82010-02-17 16:32:28 -05001819 loadUrl(view, url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001820 }
Grace Klobac9181842009-04-14 08:53:22 -07001821 return t;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001822 } else {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001823 return openTabAndShow(url, false, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001824 }
1825 }
1826
1827 private class Copy implements OnMenuItemClickListener {
1828 private CharSequence mText;
1829
1830 public boolean onMenuItemClick(MenuItem item) {
1831 copy(mText);
1832 return true;
1833 }
1834
1835 public Copy(CharSequence toCopy) {
1836 mText = toCopy;
1837 }
1838 }
1839
1840 private class Download implements OnMenuItemClickListener {
1841 private String mText;
1842
1843 public boolean onMenuItemClick(MenuItem item) {
1844 onDownloadStartNoStream(mText, null, null, null, -1);
1845 return true;
1846 }
1847
1848 public Download(String toDownload) {
1849 mText = toDownload;
1850 }
1851 }
1852
Ben Murdoch4f75ba22009-10-27 11:48:28 +00001853 private class SetAsWallpaper extends Thread implements
1854 OnMenuItemClickListener, DialogInterface.OnCancelListener {
1855 private URL mUrl;
1856 private ProgressDialog mWallpaperProgress;
1857 private boolean mCanceled = false;
1858
1859 public SetAsWallpaper(String url) {
1860 try {
1861 mUrl = new URL(url);
1862 } catch (MalformedURLException e) {
1863 mUrl = null;
1864 }
1865 }
1866
1867 public void onCancel(DialogInterface dialog) {
1868 mCanceled = true;
1869 }
1870
1871 public boolean onMenuItemClick(MenuItem item) {
1872 if (mUrl != null) {
1873 // The user may have tried to set a image with a large file size as their
1874 // background so it may take a few moments to perform the operation. Display
1875 // a progress spinner while it is working.
1876 mWallpaperProgress = new ProgressDialog(BrowserActivity.this);
1877 mWallpaperProgress.setIndeterminate(true);
1878 mWallpaperProgress.setMessage(getText(R.string.progress_dialog_setting_wallpaper));
1879 mWallpaperProgress.setCancelable(true);
1880 mWallpaperProgress.setOnCancelListener(this);
1881 mWallpaperProgress.show();
1882 start();
1883 }
1884 return true;
1885 }
1886
1887 public void run() {
1888 Drawable oldWallpaper = BrowserActivity.this.getWallpaper();
1889 try {
1890 // TODO: This will cause the resource to be downloaded again, when we
1891 // should in most cases be able to grab it from the cache. To fix this
1892 // we should query WebCore to see if we can access a cached version and
1893 // instead open an input stream on that. This pattern could also be used
1894 // in the download manager where the same problem exists.
1895 InputStream inputstream = mUrl.openStream();
1896 if (inputstream != null) {
1897 setWallpaper(inputstream);
1898 }
1899 } catch (IOException e) {
1900 Log.e(LOGTAG, "Unable to set new wallpaper");
1901 // Act as though the user canceled the operation so we try to
1902 // restore the old wallpaper.
1903 mCanceled = true;
1904 }
1905
1906 if (mCanceled) {
1907 // Restore the old wallpaper if the user cancelled whilst we were setting
1908 // the new wallpaper.
1909 int width = oldWallpaper.getIntrinsicWidth();
1910 int height = oldWallpaper.getIntrinsicHeight();
1911 Bitmap bm = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
1912 Canvas canvas = new Canvas(bm);
1913 oldWallpaper.setBounds(0, 0, width, height);
1914 oldWallpaper.draw(canvas);
1915 try {
1916 setWallpaper(bm);
1917 } catch (IOException e) {
1918 Log.e(LOGTAG, "Unable to restore old wallpaper.");
1919 }
1920 mCanceled = false;
1921 }
1922
1923 if (mWallpaperProgress.isShowing()) {
1924 mWallpaperProgress.dismiss();
1925 }
1926 }
1927 }
1928
The Android Open Source Project0c908882009-03-03 19:32:16 -08001929 private void copy(CharSequence text) {
1930 try {
1931 IClipboard clip = IClipboard.Stub.asInterface(ServiceManager.getService("clipboard"));
1932 if (clip != null) {
1933 clip.setClipboardText(text);
1934 }
1935 } catch (android.os.RemoteException e) {
1936 Log.e(LOGTAG, "Copy failed", e);
1937 }
1938 }
1939
1940 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08001941 * Resets the browser title-view to whatever it must be
1942 * (for example, if we had a loading error)
1943 * When we have a new page, we call resetTitle, when we
1944 * have to reset the titlebar to whatever it used to be
1945 * (for example, if the user chose to stop loading), we
1946 * call resetTitleAndRevertLockIcon.
1947 */
1948 /* package */ void resetTitleAndRevertLockIcon() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001949 mTabControl.getCurrentTab().revertLockIcon();
1950 updateLockIconToLatest();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001951 resetTitleIconAndProgress();
1952 }
1953
1954 /**
1955 * Reset the title, favicon, and progress.
1956 */
1957 private void resetTitleIconAndProgress() {
1958 WebView current = mTabControl.getCurrentWebView();
1959 if (current == null) {
1960 return;
1961 }
1962 resetTitleAndIcon(current);
1963 int progress = current.getProgress();
Grace Kloba22ac16e2009-10-07 18:00:23 -07001964 current.getWebChromeClient().onProgressChanged(current, progress);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001965 }
1966
1967 // Reset the title and the icon based on the given item.
1968 private void resetTitleAndIcon(WebView view) {
1969 WebHistoryItem item = view.copyBackForwardList().getCurrentItem();
1970 if (item != null) {
Leon Scroggins68579392009-09-15 15:31:54 -04001971 setUrlTitle(item.getUrl(), item.getTitle());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001972 setFavicon(item.getFavicon());
1973 } else {
Leon Scroggins68579392009-09-15 15:31:54 -04001974 setUrlTitle(null, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001975 setFavicon(null);
1976 }
1977 }
1978
1979 /**
1980 * Sets a title composed of the URL and the title string.
1981 * @param url The URL of the site being loaded.
1982 * @param title The title of the site being loaded.
1983 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07001984 void setUrlTitle(String url, String title) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001985 mUrl = url;
1986 mTitle = title;
1987
Leon Scroggins58d56c62010-01-28 15:12:40 -05001988 // If we are in voice search mode, the title has already been set.
1989 if (mTabControl.getCurrentTab().isInVoiceSearchMode()) return;
1990 mTitleBar.setDisplayTitle(url);
1991 mFakeTitleBar.setDisplayTitle(url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001992 }
1993
1994 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08001995 * @param url The URL to build a title version of the URL from.
1996 * @return The title version of the URL or null if fails.
1997 * The title version of the URL can be either the URL hostname,
1998 * or the hostname with an "https://" prefix (for secure URLs),
1999 * or an empty string if, for example, the URL in question is a
2000 * file:// URL with no hostname.
2001 */
Leon Scroggins32e14a62009-06-11 10:26:34 -04002002 /* package */ static String buildTitleUrl(String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002003 String titleUrl = null;
2004
2005 if (url != null) {
2006 try {
2007 // parse the url string
2008 URL urlObj = new URL(url);
2009 if (urlObj != null) {
2010 titleUrl = "";
2011
2012 String protocol = urlObj.getProtocol();
2013 String host = urlObj.getHost();
2014
2015 if (host != null && 0 < host.length()) {
2016 titleUrl = host;
2017 if (protocol != null) {
2018 // if a secure site, add an "https://" prefix!
2019 if (protocol.equalsIgnoreCase("https")) {
2020 titleUrl = protocol + "://" + host;
2021 }
2022 }
2023 }
2024 }
2025 } catch (MalformedURLException e) {}
2026 }
2027
2028 return titleUrl;
2029 }
2030
2031 // Set the favicon in the title bar.
Grace Kloba22ac16e2009-10-07 18:00:23 -07002032 void setFavicon(Bitmap icon) {
Leon Scroggins68579392009-09-15 15:31:54 -04002033 mTitleBar.setFavicon(icon);
Leon Scrogginsfe87bd32009-10-06 10:10:00 -04002034 mFakeTitleBar.setFavicon(icon);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002035 }
2036
2037 /**
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002038 * Close the tab, remove its associated title bar, and adjust mTabControl's
2039 * current tab to a valid value.
Leon Scroggins1f005d32009-08-10 17:36:42 -04002040 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07002041 /* package */ void closeTab(Tab t) {
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002042 int currentIndex = mTabControl.getCurrentIndex();
2043 int removeIndex = mTabControl.getTabIndex(t);
Leon Scroggins1f005d32009-08-10 17:36:42 -04002044 mTabControl.removeTab(t);
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002045 if (currentIndex >= removeIndex && currentIndex != 0) {
2046 currentIndex--;
2047 }
2048 mTabControl.setCurrentTab(mTabControl.getTab(currentIndex));
Andrei Popescua5bf1de2009-09-23 16:39:23 +01002049 resetTitleIconAndProgress();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002050 }
2051
Leon Scrogginsdcc5eeb2010-02-23 17:26:37 -05002052 /* package */ void goBackOnePageOrQuit() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002053 Tab current = mTabControl.getCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002054 if (current == null) {
2055 /*
2056 * Instead of finishing the activity, simply push this to the back
2057 * of the stack and let ActivityManager to choose the foreground
2058 * activity. As BrowserActivity is singleTask, it will be always the
2059 * root of the task. So we can use either true or false for
2060 * moveTaskToBack().
2061 */
2062 moveTaskToBack(true);
Grace Kloba00d85e72009-09-23 18:50:05 -07002063 return;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002064 }
2065 WebView w = current.getWebView();
2066 if (w.canGoBack()) {
2067 w.goBack();
2068 } else {
2069 // Check to see if we are closing a window that was created by
2070 // another window. If so, we switch back to that window.
Grace Kloba22ac16e2009-10-07 18:00:23 -07002071 Tab parent = current.getParentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002072 if (parent != null) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04002073 switchToTab(mTabControl.getTabIndex(parent));
2074 // Now we close the other tab
2075 closeTab(current);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002076 } else {
2077 if (current.closeOnExit()) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002078 // force the tab's inLoad() to be false as we are going to
2079 // either finish the activity or remove the tab. This will
2080 // ensure pauseWebViewTimers() taking action.
2081 mTabControl.getCurrentTab().clearInLoad();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002082 if (mTabControl.getTabCount() == 1) {
2083 finish();
2084 return;
2085 }
Mike Reed7bfa63b2009-05-28 11:08:32 -04002086 // call pauseWebViewTimers() now, we won't be able to call
2087 // it in onPause() as the WebView won't be valid.
Grace Klobaec1b5ad2009-08-18 08:42:32 -07002088 // Temporarily change mActivityInPause to be true as
2089 // pauseWebViewTimers() will do nothing if mActivityInPause
2090 // is false.
Grace Kloba918e1d72009-08-13 14:55:06 -07002091 boolean savedState = mActivityInPause;
2092 if (savedState) {
Grace Klobaec1b5ad2009-08-18 08:42:32 -07002093 Log.e(LOGTAG, "BrowserActivity is already paused "
2094 + "while handing goBackOnePageOrQuit.");
Grace Kloba918e1d72009-08-13 14:55:06 -07002095 }
2096 mActivityInPause = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -04002097 pauseWebViewTimers();
Grace Kloba918e1d72009-08-13 14:55:06 -07002098 mActivityInPause = savedState;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002099 removeTabFromContentView(current);
2100 mTabControl.removeTab(current);
2101 }
2102 /*
2103 * Instead of finishing the activity, simply push this to the back
2104 * of the stack and let ActivityManager to choose the foreground
2105 * activity. As BrowserActivity is singleTask, it will be always the
2106 * root of the task. So we can use either true or false for
2107 * moveTaskToBack().
2108 */
2109 moveTaskToBack(true);
2110 }
2111 }
2112 }
2113
Grace Kloba22ac16e2009-10-07 18:00:23 -07002114 boolean isMenuDown() {
2115 return mMenuIsDown;
2116 }
2117
Grace Kloba5942df02009-09-18 11:48:29 -07002118 @Override
2119 public boolean onKeyDown(int keyCode, KeyEvent event) {
Leon Scrogginsf65b50d2009-12-08 10:44:28 -05002120 // Even if MENU is already held down, we need to call to super to open
2121 // the IME on long press.
2122 if (KeyEvent.KEYCODE_MENU == keyCode) {
2123 mMenuIsDown = true;
2124 return super.onKeyDown(keyCode, event);
2125 }
Grace Kloba5942df02009-09-18 11:48:29 -07002126 // The default key mode is DEFAULT_KEYS_SEARCH_LOCAL. As the MENU is
2127 // still down, we don't want to trigger the search. Pretend to consume
2128 // the key and do nothing.
2129 if (mMenuIsDown) return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002130
Grace Kloba5942df02009-09-18 11:48:29 -07002131 switch(keyCode) {
Grace Kloba5942df02009-09-18 11:48:29 -07002132 case KeyEvent.KEYCODE_SPACE:
Grace Klobada0fe552009-09-22 18:17:24 -07002133 // WebView/WebTextView handle the keys in the KeyDown. As
2134 // the Activity's shortcut keys are only handled when WebView
2135 // doesn't, have to do it in onKeyDown instead of onKeyUp.
2136 if (event.isShiftPressed()) {
2137 getTopWindow().pageUp(false);
2138 } else {
2139 getTopWindow().pageDown(false);
2140 }
Grace Kloba5942df02009-09-18 11:48:29 -07002141 return true;
2142 case KeyEvent.KEYCODE_BACK:
2143 if (event.getRepeatCount() == 0) {
2144 event.startTracking();
2145 return true;
2146 } else if (mCustomView == null && mActiveTabsPage == null
2147 && event.isLongPress()) {
2148 bookmarksOrHistoryPicker(true);
2149 return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002150 }
Grace Kloba5942df02009-09-18 11:48:29 -07002151 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002152 }
Grace Kloba5942df02009-09-18 11:48:29 -07002153 return super.onKeyDown(keyCode, event);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002154 }
2155
Grace Kloba5942df02009-09-18 11:48:29 -07002156 @Override
2157 public boolean onKeyUp(int keyCode, KeyEvent event) {
2158 switch(keyCode) {
2159 case KeyEvent.KEYCODE_MENU:
2160 mMenuIsDown = false;
2161 break;
Grace Kloba5942df02009-09-18 11:48:29 -07002162 case KeyEvent.KEYCODE_BACK:
2163 if (event.isTracking() && !event.isCanceled()) {
2164 if (mCustomView != null) {
2165 // if a custom view is showing, hide it
Grace Kloba22ac16e2009-10-07 18:00:23 -07002166 mTabControl.getCurrentWebView().getWebChromeClient()
2167 .onHideCustomView();
Grace Kloba5942df02009-09-18 11:48:29 -07002168 } else if (mActiveTabsPage != null) {
2169 // if tab page is showing, hide it
2170 removeActiveTabPage(true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002171 } else {
Grace Kloba5942df02009-09-18 11:48:29 -07002172 WebView subwindow = mTabControl.getCurrentSubWindow();
2173 if (subwindow != null) {
2174 if (subwindow.canGoBack()) {
2175 subwindow.goBack();
2176 } else {
2177 dismissSubWindow(mTabControl.getCurrentTab());
2178 }
2179 } else {
2180 goBackOnePageOrQuit();
2181 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002182 }
Grace Kloba5942df02009-09-18 11:48:29 -07002183 return true;
2184 }
2185 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002186 }
Grace Kloba5942df02009-09-18 11:48:29 -07002187 return super.onKeyUp(keyCode, event);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002188 }
2189
Leon Scroggins68579392009-09-15 15:31:54 -04002190 /* package */ void stopLoading() {
Ben Murdochb7cc8b42009-09-28 10:59:09 +01002191 mDidStopLoad = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002192 resetTitleAndRevertLockIcon();
2193 WebView w = getTopWindow();
2194 w.stopLoading();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002195 // FIXME: before refactor, it is using mWebViewClient. So I keep the
2196 // same logic here. But for subwindow case, should we call into the main
2197 // WebView's onPageFinished as we never call its onPageStarted and if
2198 // the page finishes itself, we don't call onPageFinished.
2199 mTabControl.getCurrentWebView().getWebViewClient().onPageFinished(w,
2200 w.getUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08002201
2202 cancelStopToast();
2203 mStopToast = Toast
2204 .makeText(this, R.string.stopping, Toast.LENGTH_SHORT);
2205 mStopToast.show();
2206 }
2207
Grace Kloba22ac16e2009-10-07 18:00:23 -07002208 boolean didUserStopLoading() {
2209 return mDidStopLoad;
2210 }
2211
The Android Open Source Project0c908882009-03-03 19:32:16 -08002212 private void cancelStopToast() {
2213 if (mStopToast != null) {
2214 mStopToast.cancel();
2215 mStopToast = null;
2216 }
2217 }
2218
Grace Kloba22ac16e2009-10-07 18:00:23 -07002219 // called by a UI or non-UI thread to post the message
2220 public void postMessage(int what, int arg1, int arg2, Object obj,
2221 long delayMillis) {
2222 mHandler.sendMessageDelayed(mHandler.obtainMessage(what, arg1, arg2,
2223 obj), delayMillis);
2224 }
2225
2226 // called by a UI or non-UI thread to remove the message
2227 void removeMessages(int what, Object object) {
2228 mHandler.removeMessages(what, object);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002229 }
2230
2231 // public message ids
2232 public final static int LOAD_URL = 1001;
2233 public final static int STOP_LOAD = 1002;
2234
2235 // Message Ids
2236 private static final int FOCUS_NODE_HREF = 102;
Grace Kloba92c18a52009-07-31 23:48:32 -07002237 private static final int RELEASE_WAKELOCK = 107;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002238
Grace Kloba22ac16e2009-10-07 18:00:23 -07002239 static final int UPDATE_BOOKMARK_THUMBNAIL = 108;
Ben Murdoch2694e232009-09-29 09:41:11 +01002240
The Android Open Source Project0c908882009-03-03 19:32:16 -08002241 // Private handler for handling javascript and saving passwords
2242 private Handler mHandler = new Handler() {
2243
2244 public void handleMessage(Message msg) {
2245 switch (msg.what) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002246 case FOCUS_NODE_HREF:
Ben Murdoch2694e232009-09-29 09:41:11 +01002247 {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002248 String url = (String) msg.getData().get("url");
Ben Murdoch90d088c2009-11-17 18:14:04 +00002249 String title = (String) msg.getData().get("title");
The Android Open Source Project0c908882009-03-03 19:32:16 -08002250 if (url == null || url.length() == 0) {
2251 break;
2252 }
2253 HashMap focusNodeMap = (HashMap) msg.obj;
2254 WebView view = (WebView) focusNodeMap.get("webview");
2255 // Only apply the action if the top window did not change.
2256 if (getTopWindow() != view) {
2257 break;
2258 }
2259 switch (msg.arg1) {
2260 case R.id.open_context_menu_id:
2261 case R.id.view_image_context_menu_id:
Leon Scroggins92472e82010-02-17 16:32:28 -05002262 loadUrlFromContext(getTopWindow(), url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002263 break;
2264 case R.id.open_newtab_context_menu_id:
Grace Kloba22ac16e2009-10-07 18:00:23 -07002265 final Tab parent = mTabControl.getCurrentTab();
2266 final Tab newTab = openTab(url);
Grace Klobac9181842009-04-14 08:53:22 -07002267 if (newTab != parent) {
2268 parent.addChildTab(newTab);
2269 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002270 break;
2271 case R.id.bookmark_context_menu_id:
2272 Intent intent = new Intent(BrowserActivity.this,
2273 AddBookmarkPage.class);
2274 intent.putExtra("url", url);
Ben Murdoch90d088c2009-11-17 18:14:04 +00002275 intent.putExtra("title", title);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002276 startActivity(intent);
2277 break;
2278 case R.id.share_link_context_menu_id:
Leon Scroggins96afcb12009-12-10 12:35:56 -05002279 // See if this site has been visited before
2280 StringBuilder sb = new StringBuilder(
2281 Browser.BookmarkColumns.URL + " = ");
2282 DatabaseUtils.appendEscapedSQLString(sb, url);
Henrik Baarde2629032010-10-04 12:18:43 +02002283 Cursor c = null;
2284 try {
2285 c = mResolver.query(Browser.BOOKMARKS_URI,
2286 Browser.HISTORY_PROJECTION,
2287 sb.toString(),
2288 null,
2289 null);
2290 if (c.moveToFirst()) {
2291 // The site has been visited before, so grab the
2292 // info from the database.
2293 Bitmap favicon = null;
2294 Bitmap thumbnail = null;
2295 String linkTitle = c.getString(Browser.
2296 HISTORY_PROJECTION_TITLE_INDEX);
2297 byte[] data = c.getBlob(Browser.
2298 HISTORY_PROJECTION_FAVICON_INDEX);
2299 if (data != null) {
2300 favicon = BitmapFactory.decodeByteArray(
2301 data, 0, data.length);
2302 }
2303 data = c.getBlob(Browser.
2304 HISTORY_PROJECTION_THUMBNAIL_INDEX);
2305 if (data != null) {
2306 thumbnail = BitmapFactory.decodeByteArray(
2307 data, 0, data.length);
2308 }
2309 sharePage(BrowserActivity.this,
2310 linkTitle, url, favicon, thumbnail);
2311 } else {
2312 Browser.sendString(BrowserActivity.this, url,
2313 getString(
2314 R.string.choosertitle_sharevia));
Leon Scroggins96afcb12009-12-10 12:35:56 -05002315 }
Henrik Baarde2629032010-10-04 12:18:43 +02002316 } finally {
2317 if (c != null) c.close();
Leon Scroggins96afcb12009-12-10 12:35:56 -05002318 }
Channagoud Kadabi37182262010-09-15 23:48:29 -07002319 // close the cursor after its used
2320 if (c != null) {
2321 c.close();
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;
Grace Kloba22ac16e2009-10-07 18:00:23 -07002787 // Hide the custom view.
2788 mCustomView.setVisibility(View.GONE);
2789 // Remove the custom view from its container.
2790 mCustomViewContainer.removeView(mCustomView);
2791 mCustomView = null;
2792 // Reset the old menu state.
2793 mMenuState = mOldMenuState;
2794 mOldMenuState = EMPTY_MENU;
2795 mCustomViewContainer.setVisibility(View.GONE);
2796 mCustomViewCallback.onCustomViewHidden();
2797 // Show the content view.
Andrei Popescu163ab742009-10-20 17:58:23 +01002798 setStatusBarVisibility(true);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002799 mContentView.setVisibility(View.VISIBLE);
2800 }
2801
2802 Bitmap getDefaultVideoPoster() {
2803 if (mDefaultVideoPoster == null) {
2804 mDefaultVideoPoster = BitmapFactory.decodeResource(
2805 getResources(), R.drawable.default_video_poster);
Patrick Scott3918d442009-08-04 13:22:29 -04002806 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002807 return mDefaultVideoPoster;
2808 }
Patrick Scott3918d442009-08-04 13:22:29 -04002809
Grace Kloba22ac16e2009-10-07 18:00:23 -07002810 View getVideoLoadingProgressView() {
2811 if (mVideoProgressView == null) {
2812 LayoutInflater inflater = LayoutInflater.from(BrowserActivity.this);
2813 mVideoProgressView = inflater.inflate(
2814 R.layout.video_loading_progress, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002815 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002816 return mVideoProgressView;
2817 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002818
Leon Scroggins8d5fa432009-10-02 15:55:59 -04002819 /*
2820 * The Object used to inform the WebView of the file to upload.
2821 */
2822 private ValueCallback<Uri> mUploadMessage;
2823
Grace Kloba22ac16e2009-10-07 18:00:23 -07002824 void openFileChooser(ValueCallback<Uri> uploadMsg) {
2825 if (mUploadMessage != null) return;
2826 mUploadMessage = uploadMsg;
2827 Intent i = new Intent(Intent.ACTION_GET_CONTENT);
2828 i.addCategory(Intent.CATEGORY_OPENABLE);
2829 i.setType("*/*");
2830 BrowserActivity.this.startActivityForResult(Intent.createChooser(i,
2831 getString(R.string.choose_upload)), FILE_SELECTED);
2832 }
2833
2834 // -------------------------------------------------------------------------
2835 // Implement functions for DownloadListener
2836 // -------------------------------------------------------------------------
2837
The Android Open Source Project0c908882009-03-03 19:32:16 -08002838 /**
2839 * Notify the host application a download should be done, or that
2840 * the data should be streamed if a streaming viewer is available.
2841 * @param url The full url to the content that should be downloaded
2842 * @param contentDisposition Content-disposition http header, if
2843 * present.
2844 * @param mimetype The mimetype of the content reported by the server
2845 * @param contentLength The file size reported by the server
2846 */
2847 public void onDownloadStart(String url, String userAgent,
2848 String contentDisposition, String mimetype, long contentLength) {
2849 // if we're dealing wih A/V content that's not explicitly marked
2850 // for download, check if it's streamable.
2851 if (contentDisposition == null
Patrick Scotte1fb9662009-08-31 14:31:52 -04002852 || !contentDisposition.regionMatches(
2853 true, 0, "attachment", 0, 10)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002854 // query the package manager to see if there's a registered handler
2855 // that matches.
2856 Intent intent = new Intent(Intent.ACTION_VIEW);
2857 intent.setDataAndType(Uri.parse(url), mimetype);
Patrick Scotte1fb9662009-08-31 14:31:52 -04002858 ResolveInfo info = getPackageManager().resolveActivity(intent,
2859 PackageManager.MATCH_DEFAULT_ONLY);
2860 if (info != null) {
2861 ComponentName myName = getComponentName();
2862 // If we resolved to ourselves, we don't want to attempt to
2863 // load the url only to try and download it again.
2864 if (!myName.getPackageName().equals(
2865 info.activityInfo.packageName)
2866 || !myName.getClassName().equals(
2867 info.activityInfo.name)) {
2868 // someone (other than us) knows how to handle this mime
2869 // type with this scheme, don't download.
2870 try {
2871 startActivity(intent);
2872 return;
2873 } catch (ActivityNotFoundException ex) {
2874 if (LOGD_ENABLED) {
2875 Log.d(LOGTAG, "activity not found for " + mimetype
2876 + " over " + Uri.parse(url).getScheme(),
2877 ex);
2878 }
2879 // Best behavior is to fall back to a download in this
2880 // case
The Android Open Source Project0c908882009-03-03 19:32:16 -08002881 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002882 }
2883 }
2884 }
2885 onDownloadStartNoStream(url, userAgent, contentDisposition, mimetype, contentLength);
2886 }
2887
Kristian Monsenfa52d172010-03-25 18:29:21 +00002888 // This is to work around the fact that java.net.URI throws Exceptions
2889 // instead of just encoding URL's properly
2890 // Helper method for onDownloadStartNoStream
2891 private static String encodePath(String path) {
2892 char[] chars = path.toCharArray();
2893
2894 boolean needed = false;
2895 for (char c : chars) {
2896 if (c == '[' || c == ']') {
2897 needed = true;
2898 break;
2899 }
2900 }
2901 if (needed == false) {
2902 return path;
2903 }
2904
2905 StringBuilder sb = new StringBuilder("");
2906 for (char c : chars) {
2907 if (c == '[' || c == ']') {
2908 sb.append('%');
2909 sb.append(Integer.toHexString(c));
2910 } else {
2911 sb.append(c);
2912 }
2913 }
2914
2915 return sb.toString();
2916 }
2917
The Android Open Source Project0c908882009-03-03 19:32:16 -08002918 /**
2919 * Notify the host application a download should be done, even if there
2920 * is a streaming viewer available for thise type.
2921 * @param url The full url to the content that should be downloaded
2922 * @param contentDisposition Content-disposition http header, if
2923 * present.
2924 * @param mimetype The mimetype of the content reported by the server
2925 * @param contentLength The file size reported by the server
2926 */
2927 /*package */ void onDownloadStartNoStream(String url, String userAgent,
2928 String contentDisposition, String mimetype, long contentLength) {
2929
2930 String filename = URLUtil.guessFileName(url,
2931 contentDisposition, mimetype);
2932
2933 // Check to see if we have an SDCard
2934 String status = Environment.getExternalStorageState();
2935 if (!status.equals(Environment.MEDIA_MOUNTED)) {
2936 int title;
2937 String msg;
2938
2939 // Check to see if the SDCard is busy, same as the music app
2940 if (status.equals(Environment.MEDIA_SHARED)) {
2941 msg = getString(R.string.download_sdcard_busy_dlg_msg);
2942 title = R.string.download_sdcard_busy_dlg_title;
2943 } else {
2944 msg = getString(R.string.download_no_sdcard_dlg_msg, filename);
2945 title = R.string.download_no_sdcard_dlg_title;
2946 }
2947
2948 new AlertDialog.Builder(this)
2949 .setTitle(title)
2950 .setIcon(android.R.drawable.ic_dialog_alert)
2951 .setMessage(msg)
2952 .setPositiveButton(R.string.ok, null)
2953 .show();
2954 return;
2955 }
2956
Kristian Monsenfa52d172010-03-25 18:29:21 +00002957 // java.net.URI is a lot stricter than KURL so we have to encode some
2958 // extra characters. Fix for b 2538060 and b 1634719
2959 WebAddress webAddress;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002960 try {
Kristian Monsenfa52d172010-03-25 18:29:21 +00002961 webAddress = new WebAddress(url);
2962 webAddress.mPath = encodePath(webAddress.mPath);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002963 } catch (Exception e) {
Kristian Monsenfa52d172010-03-25 18:29:21 +00002964 // This only happens for very bad urls, we want to chatch the
2965 // exception here
2966 Log.e(LOGTAG, "Exception trying to parse url:" + url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002967 return;
2968 }
2969
2970 // XXX: Have to use the old url since the cookies were stored using the
2971 // old percent-encoded url.
2972 String cookies = CookieManager.getInstance().getCookie(url);
2973
2974 ContentValues values = new ContentValues();
Kristian Monsenfa52d172010-03-25 18:29:21 +00002975 values.put(Downloads.Impl.COLUMN_URI, webAddress.toString());
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08002976 values.put(Downloads.Impl.COLUMN_COOKIE_DATA, cookies);
2977 values.put(Downloads.Impl.COLUMN_USER_AGENT, userAgent);
2978 values.put(Downloads.Impl.COLUMN_NOTIFICATION_PACKAGE,
The Android Open Source Project0c908882009-03-03 19:32:16 -08002979 getPackageName());
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08002980 values.put(Downloads.Impl.COLUMN_NOTIFICATION_CLASS,
Leon Scrogginsa563d092010-04-19 16:53:49 -04002981 OpenDownloadReceiver.class.getCanonicalName());
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08002982 values.put(Downloads.Impl.COLUMN_VISIBILITY,
2983 Downloads.Impl.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
2984 values.put(Downloads.Impl.COLUMN_MIME_TYPE, mimetype);
2985 values.put(Downloads.Impl.COLUMN_FILE_NAME_HINT, filename);
Kristian Monsenfa52d172010-03-25 18:29:21 +00002986 values.put(Downloads.Impl.COLUMN_DESCRIPTION, webAddress.mHost);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002987 if (contentLength > 0) {
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08002988 values.put(Downloads.Impl.COLUMN_TOTAL_BYTES, contentLength);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002989 }
2990 if (mimetype == null) {
2991 // We must have long pressed on a link or image to download it. We
2992 // are not sure of the mimetype in this case, so do a head request
2993 new FetchUrlMimeType(this).execute(values);
2994 } else {
2995 final Uri contentUri =
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08002996 getContentResolver().insert(Downloads.Impl.CONTENT_URI, values);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002997 }
Leon Scroggins9191a7f2010-03-18 14:44:44 -04002998 Toast.makeText(this, R.string.download_pending, Toast.LENGTH_SHORT)
2999 .show();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003000 }
3001
Grace Kloba22ac16e2009-10-07 18:00:23 -07003002 // -------------------------------------------------------------------------
3003
The Android Open Source Project0c908882009-03-03 19:32:16 -08003004 /**
3005 * Resets the lock icon. This method is called when we start a new load and
3006 * know the url to be loaded.
3007 */
3008 private void resetLockIcon(String url) {
3009 // Save the lock-icon state (we revert to it if the load gets cancelled)
Grace Kloba22ac16e2009-10-07 18:00:23 -07003010 mTabControl.getCurrentTab().resetLockIcon(url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003011 updateLockIconImage(LOCK_ICON_UNSECURE);
3012 }
3013
The Android Open Source Project0c908882009-03-03 19:32:16 -08003014 /**
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04003015 * Update the lock icon to correspond to our latest state.
3016 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003017 private void updateLockIconToLatest() {
3018 updateLockIconImage(mTabControl.getCurrentTab().getLockIconType());
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04003019 }
3020
3021 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08003022 * Updates the lock-icon image in the title-bar.
3023 */
3024 private void updateLockIconImage(int lockIconType) {
3025 Drawable d = null;
3026 if (lockIconType == LOCK_ICON_SECURE) {
3027 d = mSecLockIcon;
3028 } else if (lockIconType == LOCK_ICON_MIXED) {
3029 d = mMixLockIcon;
3030 }
Leon Scroggins68579392009-09-15 15:31:54 -04003031 mTitleBar.setLock(d);
Leon Scrogginsfe87bd32009-10-06 10:10:00 -04003032 mFakeTitleBar.setLock(d);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003033 }
3034
3035 /**
3036 * Displays a page-info dialog.
3037 * @param tab The tab to show info about
3038 * @param fromShowSSLCertificateOnError The flag that indicates whether
3039 * this dialog was opened from the SSL-certificate-on-error dialog or
3040 * not. This is important, since we need to know whether to return to
3041 * the parent dialog or simply dismiss.
3042 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003043 private void showPageInfo(final Tab tab,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003044 final boolean fromShowSSLCertificateOnError) {
3045 final LayoutInflater factory = LayoutInflater
3046 .from(this);
3047
3048 final View pageInfoView = factory.inflate(R.layout.page_info, null);
3049
3050 final WebView view = tab.getWebView();
3051
3052 String url = null;
3053 String title = null;
3054
3055 if (view == null) {
3056 url = tab.getUrl();
3057 title = tab.getTitle();
3058 } else if (view == mTabControl.getCurrentWebView()) {
3059 // Use the cached title and url if this is the current WebView
3060 url = mUrl;
3061 title = mTitle;
3062 } else {
3063 url = view.getUrl();
3064 title = view.getTitle();
3065 }
3066
3067 if (url == null) {
3068 url = "";
3069 }
3070 if (title == null) {
3071 title = "";
3072 }
3073
3074 ((TextView) pageInfoView.findViewById(R.id.address)).setText(url);
3075 ((TextView) pageInfoView.findViewById(R.id.title)).setText(title);
3076
3077 mPageInfoView = tab;
Leon Scrogginsc7b92f82010-01-11 18:17:31 -05003078 mPageInfoFromShowSSLCertificateOnError = fromShowSSLCertificateOnError;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003079
3080 AlertDialog.Builder alertDialogBuilder =
3081 new AlertDialog.Builder(this)
3082 .setTitle(R.string.page_info).setIcon(android.R.drawable.ic_dialog_info)
3083 .setView(pageInfoView)
3084 .setPositiveButton(
3085 R.string.ok,
3086 new DialogInterface.OnClickListener() {
3087 public void onClick(DialogInterface dialog,
3088 int whichButton) {
3089 mPageInfoDialog = null;
3090 mPageInfoView = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003091
3092 // if we came here from the SSL error dialog
3093 if (fromShowSSLCertificateOnError) {
3094 // go back to the SSL error dialog
3095 showSSLCertificateOnError(
3096 mSSLCertificateOnErrorView,
3097 mSSLCertificateOnErrorHandler,
3098 mSSLCertificateOnErrorError);
3099 }
3100 }
3101 })
3102 .setOnCancelListener(
3103 new DialogInterface.OnCancelListener() {
3104 public void onCancel(DialogInterface dialog) {
3105 mPageInfoDialog = null;
3106 mPageInfoView = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003107
3108 // if we came here from the SSL error dialog
3109 if (fromShowSSLCertificateOnError) {
3110 // go back to the SSL error dialog
3111 showSSLCertificateOnError(
3112 mSSLCertificateOnErrorView,
3113 mSSLCertificateOnErrorHandler,
3114 mSSLCertificateOnErrorError);
3115 }
3116 }
3117 });
3118
3119 // if we have a main top-level page SSL certificate set or a certificate
3120 // error
3121 if (fromShowSSLCertificateOnError ||
3122 (view != null && view.getCertificate() != null)) {
3123 // add a 'View Certificate' button
3124 alertDialogBuilder.setNeutralButton(
3125 R.string.view_certificate,
3126 new DialogInterface.OnClickListener() {
3127 public void onClick(DialogInterface dialog,
3128 int whichButton) {
3129 mPageInfoDialog = null;
3130 mPageInfoView = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003131
3132 // if we came here from the SSL error dialog
3133 if (fromShowSSLCertificateOnError) {
3134 // go back to the SSL error dialog
3135 showSSLCertificateOnError(
3136 mSSLCertificateOnErrorView,
3137 mSSLCertificateOnErrorHandler,
3138 mSSLCertificateOnErrorError);
3139 } else {
3140 // otherwise, display the top-most certificate from
3141 // the chain
3142 if (view.getCertificate() != null) {
3143 showSSLCertificate(tab);
3144 }
3145 }
3146 }
3147 });
3148 }
3149
3150 mPageInfoDialog = alertDialogBuilder.show();
3151 }
3152
3153 /**
3154 * Displays the main top-level page SSL certificate dialog
3155 * (accessible from the Page-Info dialog).
3156 * @param tab The tab to show certificate for.
3157 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003158 private void showSSLCertificate(final Tab tab) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003159 final View certificateView =
3160 inflateCertificateView(tab.getWebView().getCertificate());
3161 if (certificateView == null) {
3162 return;
3163 }
3164
3165 LayoutInflater factory = LayoutInflater.from(this);
3166
3167 final LinearLayout placeholder =
3168 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3169
3170 LinearLayout ll = (LinearLayout) factory.inflate(
3171 R.layout.ssl_success, placeholder);
3172 ((TextView)ll.findViewById(R.id.success))
3173 .setText(R.string.ssl_certificate_is_valid);
3174
3175 mSSLCertificateView = tab;
3176 mSSLCertificateDialog =
3177 new AlertDialog.Builder(this)
3178 .setTitle(R.string.ssl_certificate).setIcon(
3179 R.drawable.ic_dialog_browser_certificate_secure)
3180 .setView(certificateView)
3181 .setPositiveButton(R.string.ok,
3182 new DialogInterface.OnClickListener() {
3183 public void onClick(DialogInterface dialog,
3184 int whichButton) {
3185 mSSLCertificateDialog = null;
3186 mSSLCertificateView = null;
3187
3188 showPageInfo(tab, false);
3189 }
3190 })
3191 .setOnCancelListener(
3192 new DialogInterface.OnCancelListener() {
3193 public void onCancel(DialogInterface dialog) {
3194 mSSLCertificateDialog = null;
3195 mSSLCertificateView = null;
3196
3197 showPageInfo(tab, false);
3198 }
3199 })
3200 .show();
3201 }
3202
3203 /**
3204 * Displays the SSL error certificate dialog.
3205 * @param view The target web-view.
3206 * @param handler The SSL error handler responsible for cancelling the
3207 * connection that resulted in an SSL error or proceeding per user request.
3208 * @param error The SSL error object.
3209 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003210 void showSSLCertificateOnError(
The Android Open Source Project0c908882009-03-03 19:32:16 -08003211 final WebView view, final SslErrorHandler handler, final SslError error) {
3212
3213 final View certificateView =
3214 inflateCertificateView(error.getCertificate());
3215 if (certificateView == null) {
3216 return;
3217 }
3218
3219 LayoutInflater factory = LayoutInflater.from(this);
3220
3221 final LinearLayout placeholder =
3222 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3223
3224 if (error.hasError(SslError.SSL_UNTRUSTED)) {
3225 LinearLayout ll = (LinearLayout)factory
3226 .inflate(R.layout.ssl_warning, placeholder);
3227 ((TextView)ll.findViewById(R.id.warning))
3228 .setText(R.string.ssl_untrusted);
3229 }
3230
3231 if (error.hasError(SslError.SSL_IDMISMATCH)) {
3232 LinearLayout ll = (LinearLayout)factory
3233 .inflate(R.layout.ssl_warning, placeholder);
3234 ((TextView)ll.findViewById(R.id.warning))
3235 .setText(R.string.ssl_mismatch);
3236 }
3237
3238 if (error.hasError(SslError.SSL_EXPIRED)) {
3239 LinearLayout ll = (LinearLayout)factory
3240 .inflate(R.layout.ssl_warning, placeholder);
3241 ((TextView)ll.findViewById(R.id.warning))
3242 .setText(R.string.ssl_expired);
3243 }
3244
3245 if (error.hasError(SslError.SSL_NOTYETVALID)) {
3246 LinearLayout ll = (LinearLayout)factory
3247 .inflate(R.layout.ssl_warning, placeholder);
3248 ((TextView)ll.findViewById(R.id.warning))
3249 .setText(R.string.ssl_not_yet_valid);
3250 }
3251
3252 mSSLCertificateOnErrorHandler = handler;
3253 mSSLCertificateOnErrorView = view;
3254 mSSLCertificateOnErrorError = error;
3255 mSSLCertificateOnErrorDialog =
3256 new AlertDialog.Builder(this)
3257 .setTitle(R.string.ssl_certificate).setIcon(
3258 R.drawable.ic_dialog_browser_certificate_partially_secure)
3259 .setView(certificateView)
3260 .setPositiveButton(R.string.ok,
3261 new DialogInterface.OnClickListener() {
3262 public void onClick(DialogInterface dialog,
3263 int whichButton) {
3264 mSSLCertificateOnErrorDialog = null;
3265 mSSLCertificateOnErrorView = null;
3266 mSSLCertificateOnErrorHandler = null;
3267 mSSLCertificateOnErrorError = null;
3268
Grace Kloba22ac16e2009-10-07 18:00:23 -07003269 view.getWebViewClient().onReceivedSslError(
3270 view, handler, error);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003271 }
3272 })
3273 .setNeutralButton(R.string.page_info_view,
3274 new DialogInterface.OnClickListener() {
3275 public void onClick(DialogInterface dialog,
3276 int whichButton) {
3277 mSSLCertificateOnErrorDialog = null;
3278
3279 // do not clear the dialog state: we will
3280 // need to show the dialog again once the
3281 // user is done exploring the page-info details
3282
3283 showPageInfo(mTabControl.getTabFromView(view),
3284 true);
3285 }
3286 })
3287 .setOnCancelListener(
3288 new DialogInterface.OnCancelListener() {
3289 public void onCancel(DialogInterface dialog) {
3290 mSSLCertificateOnErrorDialog = null;
3291 mSSLCertificateOnErrorView = null;
3292 mSSLCertificateOnErrorHandler = null;
3293 mSSLCertificateOnErrorError = null;
3294
Grace Kloba22ac16e2009-10-07 18:00:23 -07003295 view.getWebViewClient().onReceivedSslError(
3296 view, handler, error);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003297 }
3298 })
3299 .show();
3300 }
3301
3302 /**
3303 * Inflates the SSL certificate view (helper method).
3304 * @param certificate The SSL certificate.
3305 * @return The resultant certificate view with issued-to, issued-by,
3306 * issued-on, expires-on, and possibly other fields set.
3307 * If the input certificate is null, returns null.
3308 */
3309 private View inflateCertificateView(SslCertificate certificate) {
3310 if (certificate == null) {
3311 return null;
3312 }
3313
3314 LayoutInflater factory = LayoutInflater.from(this);
3315
3316 View certificateView = factory.inflate(
3317 R.layout.ssl_certificate, null);
3318
3319 // issued to:
3320 SslCertificate.DName issuedTo = certificate.getIssuedTo();
3321 if (issuedTo != null) {
3322 ((TextView) certificateView.findViewById(R.id.to_common))
3323 .setText(issuedTo.getCName());
3324 ((TextView) certificateView.findViewById(R.id.to_org))
3325 .setText(issuedTo.getOName());
3326 ((TextView) certificateView.findViewById(R.id.to_org_unit))
3327 .setText(issuedTo.getUName());
3328 }
3329
3330 // issued by:
3331 SslCertificate.DName issuedBy = certificate.getIssuedBy();
3332 if (issuedBy != null) {
3333 ((TextView) certificateView.findViewById(R.id.by_common))
3334 .setText(issuedBy.getCName());
3335 ((TextView) certificateView.findViewById(R.id.by_org))
3336 .setText(issuedBy.getOName());
3337 ((TextView) certificateView.findViewById(R.id.by_org_unit))
3338 .setText(issuedBy.getUName());
3339 }
3340
3341 // issued on:
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003342 String issuedOn = formatCertificateDate(
3343 certificate.getValidNotBeforeDate());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003344 ((TextView) certificateView.findViewById(R.id.issued_on))
3345 .setText(issuedOn);
3346
3347 // expires on:
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003348 String expiresOn = formatCertificateDate(
3349 certificate.getValidNotAfterDate());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003350 ((TextView) certificateView.findViewById(R.id.expires_on))
3351 .setText(expiresOn);
3352
3353 return certificateView;
3354 }
3355
3356 /**
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003357 * Formats the certificate date to a properly localized date string.
The Android Open Source Project0c908882009-03-03 19:32:16 -08003358 * @return Properly localized version of the certificate date string and
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003359 * the "" if it fails to localize.
The Android Open Source Project0c908882009-03-03 19:32:16 -08003360 */
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003361 private String formatCertificateDate(Date certificateDate) {
3362 if (certificateDate == null) {
3363 return "";
The Android Open Source Project0c908882009-03-03 19:32:16 -08003364 }
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003365 String formattedDate = DateFormat.getDateFormat(this).format(certificateDate);
3366 if (formattedDate == null) {
3367 return "";
3368 }
3369 return formattedDate;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003370 }
3371
3372 /**
3373 * Displays an http-authentication dialog.
3374 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003375 void showHttpAuthentication(final HttpAuthHandler handler,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003376 final String host, final String realm, final String title,
3377 final String name, final String password, int focusId) {
3378 LayoutInflater factory = LayoutInflater.from(this);
3379 final View v = factory
3380 .inflate(R.layout.http_authentication, null);
3381 if (name != null) {
3382 ((EditText) v.findViewById(R.id.username_edit)).setText(name);
3383 }
3384 if (password != null) {
3385 ((EditText) v.findViewById(R.id.password_edit)).setText(password);
3386 }
3387
3388 String titleText = title;
3389 if (titleText == null) {
3390 titleText = getText(R.string.sign_in_to).toString().replace(
3391 "%s1", host).replace("%s2", realm);
3392 }
3393
3394 mHttpAuthHandler = handler;
3395 AlertDialog dialog = new AlertDialog.Builder(this)
3396 .setTitle(titleText)
3397 .setIcon(android.R.drawable.ic_dialog_alert)
3398 .setView(v)
3399 .setPositiveButton(R.string.action,
3400 new DialogInterface.OnClickListener() {
3401 public void onClick(DialogInterface dialog,
3402 int whichButton) {
3403 String nm = ((EditText) v
3404 .findViewById(R.id.username_edit))
3405 .getText().toString();
3406 String pw = ((EditText) v
3407 .findViewById(R.id.password_edit))
3408 .getText().toString();
3409 BrowserActivity.this.setHttpAuthUsernamePassword
3410 (host, realm, nm, pw);
3411 handler.proceed(nm, pw);
3412 mHttpAuthenticationDialog = null;
3413 mHttpAuthHandler = null;
3414 }})
3415 .setNegativeButton(R.string.cancel,
3416 new DialogInterface.OnClickListener() {
3417 public void onClick(DialogInterface dialog,
3418 int whichButton) {
3419 handler.cancel();
3420 BrowserActivity.this.resetTitleAndRevertLockIcon();
3421 mHttpAuthenticationDialog = null;
3422 mHttpAuthHandler = null;
3423 }})
3424 .setOnCancelListener(new DialogInterface.OnCancelListener() {
3425 public void onCancel(DialogInterface dialog) {
3426 handler.cancel();
3427 BrowserActivity.this.resetTitleAndRevertLockIcon();
3428 mHttpAuthenticationDialog = null;
3429 mHttpAuthHandler = null;
3430 }})
3431 .create();
3432 // Make the IME appear when the dialog is displayed if applicable.
3433 dialog.getWindow().setSoftInputMode(
3434 WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
3435 dialog.show();
3436 if (focusId != 0) {
3437 dialog.findViewById(focusId).requestFocus();
3438 } else {
3439 v.findViewById(R.id.username_edit).requestFocus();
3440 }
3441 mHttpAuthenticationDialog = dialog;
3442 }
3443
3444 public int getProgress() {
3445 WebView w = mTabControl.getCurrentWebView();
3446 if (w != null) {
3447 return w.getProgress();
3448 } else {
3449 return 100;
3450 }
3451 }
3452
3453 /**
3454 * Set HTTP authentication password.
3455 *
3456 * @param host The host for the password
3457 * @param realm The realm for the password
3458 * @param username The username for the password. If it is null, it means
3459 * password can't be saved.
3460 * @param password The password
3461 */
3462 public void setHttpAuthUsernamePassword(String host, String realm,
3463 String username,
3464 String password) {
Steve Block95a53b22010-03-25 17:24:58 +00003465 WebView w = getTopWindow();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003466 if (w != null) {
3467 w.setHttpAuthUsernamePassword(host, realm, username, password);
3468 }
3469 }
3470
3471 /**
3472 * connectivity manager says net has come or gone... inform the user
3473 * @param up true if net has come up, false if net has gone down
3474 */
3475 public void onNetworkToggle(boolean up) {
3476 if (up == mIsNetworkUp) {
3477 return;
3478 } else if (up) {
3479 mIsNetworkUp = true;
3480 if (mAlertDialog != null) {
3481 mAlertDialog.cancel();
3482 mAlertDialog = null;
3483 }
3484 } else {
3485 mIsNetworkUp = false;
Patrick Scotteb6ab2a2009-09-16 10:00:17 -04003486 if (mInLoad) {
3487 createAndShowNetworkDialog();
3488 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003489 }
3490 WebView w = mTabControl.getCurrentWebView();
3491 if (w != null) {
3492 w.setNetworkAvailable(up);
3493 }
3494 }
3495
Grace Kloba22ac16e2009-10-07 18:00:23 -07003496 boolean isNetworkUp() {
3497 return mIsNetworkUp;
3498 }
3499
Patrick Scotteb6ab2a2009-09-16 10:00:17 -04003500 // This method shows the network dialog alerting the user that the net is
3501 // down. It will only show the dialog if mAlertDialog is null.
3502 private void createAndShowNetworkDialog() {
3503 if (mAlertDialog == null) {
3504 mAlertDialog = new AlertDialog.Builder(this)
3505 .setTitle(R.string.loadSuspendedTitle)
3506 .setMessage(R.string.loadSuspended)
3507 .setPositiveButton(R.string.ok, null)
3508 .show();
3509 }
3510 }
3511
The Android Open Source Project0c908882009-03-03 19:32:16 -08003512 @Override
3513 protected void onActivityResult(int requestCode, int resultCode,
3514 Intent intent) {
Grace Klobabb394f32009-11-19 10:26:37 -08003515 if (getTopWindow() == null) return;
3516
The Android Open Source Project0c908882009-03-03 19:32:16 -08003517 switch (requestCode) {
3518 case COMBO_PAGE:
3519 if (resultCode == RESULT_OK && intent != null) {
3520 String data = intent.getAction();
3521 Bundle extras = intent.getExtras();
3522 if (extras != null && extras.getBoolean("new_window", false)) {
Leon Scroggins25d35472009-09-15 11:37:27 -04003523 openTab(data);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003524 } else {
Grace Kloba22ac16e2009-10-07 18:00:23 -07003525 final Tab currentTab =
The Android Open Source Project0c908882009-03-03 19:32:16 -08003526 mTabControl.getCurrentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04003527 dismissSubWindow(currentTab);
3528 if (data != null && data.length() != 0) {
Leon Scroggins92472e82010-02-17 16:32:28 -05003529 loadUrl(getTopWindow(), data);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003530 }
3531 }
3532 }
Leon Scrogginsfde97462010-01-11 13:06:21 -05003533 // Deliberately fall through to PREFERENCES_PAGE, since the
3534 // same extra may be attached to the COMBO_PAGE
3535 case PREFERENCES_PAGE:
3536 if (resultCode == RESULT_OK && intent != null) {
3537 String action = intent.getStringExtra(Intent.EXTRA_TEXT);
3538 if (BrowserSettings.PREF_CLEAR_HISTORY.equals(action)) {
3539 mTabControl.removeParentChildRelationShips();
3540 }
3541 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003542 break;
Leon Scroggins8d5fa432009-10-02 15:55:59 -04003543 // Choose a file from the file picker.
3544 case FILE_SELECTED:
3545 if (null == mUploadMessage) break;
3546 Uri result = intent == null || resultCode != RESULT_OK ? null
3547 : intent.getData();
3548 mUploadMessage.onReceiveValue(result);
3549 mUploadMessage = null;
3550 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003551 default:
3552 break;
3553 }
Leon Scroggins30444232009-09-04 18:36:20 -04003554 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003555 }
3556
3557 /*
3558 * This method is called as a result of the user selecting the options
Leon Scrogginsf08809b2010-01-21 09:27:46 -05003559 * menu to see the download window. It shows the download window on top of
3560 * the current window.
The Android Open Source Project0c908882009-03-03 19:32:16 -08003561 */
Leon Scroggins IIIa682a3c2010-09-27 12:32:40 -04003562 private void viewDownloads() {
3563 Intent intent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
3564 startActivity(intent);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003565 }
3566
Leon Scroggins160a7e72009-08-14 18:28:01 -04003567 /**
3568 * Open the Go page.
3569 * @param startWithHistory If true, open starting on the history tab.
3570 * Otherwise, start with the bookmarks tab.
Leon Scroggins160a7e72009-08-14 18:28:01 -04003571 */
Leon Scroggins30444232009-09-04 18:36:20 -04003572 /* package */ void bookmarksOrHistoryPicker(boolean startWithHistory) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003573 WebView current = mTabControl.getCurrentWebView();
3574 if (current == null) {
3575 return;
3576 }
3577 Intent intent = new Intent(this,
3578 CombinedBookmarkHistoryActivity.class);
3579 String title = current.getTitle();
3580 String url = current.getUrl();
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01003581 Bitmap thumbnail = createScreenshot(current);
3582
The Android Open Source Project0c908882009-03-03 19:32:16 -08003583 // Just in case the user opens bookmarks before a page finishes loading
3584 // so the current history item, and therefore the page, is null.
3585 if (null == url) {
3586 url = mLastEnteredUrl;
3587 // This can happen.
3588 if (null == url) {
3589 url = mSettings.getHomePage();
3590 }
3591 }
3592 // In case the web page has not yet received its associated title.
3593 if (title == null) {
3594 title = url;
3595 }
3596 intent.putExtra("title", title);
3597 intent.putExtra("url", url);
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01003598 intent.putExtra("thumbnail", thumbnail);
Leon Scroggins30444232009-09-04 18:36:20 -04003599 // Disable opening in a new window if we have maxed out the windows
Grace Kloba22ac16e2009-10-07 18:00:23 -07003600 intent.putExtra("disable_new_window", !mTabControl.canCreateNewTab());
Patrick Scott3918d442009-08-04 13:22:29 -04003601 intent.putExtra("touch_icon_url", current.getTouchIconUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003602 if (startWithHistory) {
3603 intent.putExtra(CombinedBookmarkHistoryActivity.STARTING_TAB,
3604 CombinedBookmarkHistoryActivity.HISTORY_TAB);
3605 }
3606 startActivityForResult(intent, COMBO_PAGE);
3607 }
3608
3609 // Called when loading from context menu or LOAD_URL message
Leon Scroggins92472e82010-02-17 16:32:28 -05003610 private void loadUrlFromContext(WebView view, String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003611 // In case the user enters nothing.
3612 if (url != null && url.length() != 0 && view != null) {
3613 url = smartUrlFilter(url);
Grace Kloba22ac16e2009-10-07 18:00:23 -07003614 if (!view.getWebViewClient().shouldOverrideUrlLoading(view, url)) {
Leon Scroggins92472e82010-02-17 16:32:28 -05003615 loadUrl(view, url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003616 }
3617 }
3618 }
3619
Leon Scroggins92472e82010-02-17 16:32:28 -05003620 /**
3621 * Load the URL into the given WebView and update the title bar
3622 * to reflect the new load. Call this instead of WebView.loadUrl
3623 * directly.
3624 * @param view The WebView used to load url.
3625 * @param url The URL to load.
3626 */
3627 private void loadUrl(WebView view, String url) {
3628 updateTitleBarForNewLoad(view, url);
3629 view.loadUrl(url);
3630 }
3631
3632 /**
3633 * Load UrlData into a Tab and update the title bar to reflect the new
3634 * load. Call this instead of UrlData.loadIn directly.
3635 * @param t The Tab used to load.
3636 * @param data The UrlData being loaded.
3637 */
3638 private void loadUrlDataIn(Tab t, UrlData data) {
3639 updateTitleBarForNewLoad(t.getWebView(), data.mUrl);
3640 data.loadIn(t);
3641 }
3642
3643 /**
3644 * If the WebView is the top window, update the title bar to reflect
3645 * loading the new URL. i.e. set its text, clear the favicon (which
3646 * will be set once the page begins loading), and set the progress to
3647 * INITIAL_PROGRESS to show that the page has begun to load. Called
3648 * by loadUrl and loadUrlDataIn.
3649 * @param view The WebView that is starting a load.
3650 * @param url The URL that is being loaded.
3651 */
3652 private void updateTitleBarForNewLoad(WebView view, String url) {
3653 if (view == getTopWindow()) {
3654 setUrlTitle(url, null);
3655 setFavicon(null);
3656 onProgressChanged(view, INITIAL_PROGRESS);
3657 }
3658 }
3659
The Android Open Source Project0c908882009-03-03 19:32:16 -08003660 private String smartUrlFilter(Uri inUri) {
3661 if (inUri != null) {
3662 return smartUrlFilter(inUri.toString());
3663 }
3664 return null;
3665 }
3666
Feng Qianb34f87a2009-03-24 21:27:26 -07003667 protected static final Pattern ACCEPTED_URI_SCHEMA = Pattern.compile(
The Android Open Source Project0c908882009-03-03 19:32:16 -08003668 "(?i)" + // switch on case insensitive matching
3669 "(" + // begin group for schema
3670 "(?:http|https|file):\\/\\/" +
Huahui Wu604a5982011-03-22 15:00:11 -07003671 "|(?:inline|data|about|javascript):" +
The Android Open Source Project0c908882009-03-03 19:32:16 -08003672 ")" +
3673 "(.*)" );
3674
3675 /**
3676 * Attempts to determine whether user input is a URL or search
3677 * terms. Anything with a space is passed to search.
3678 *
3679 * Converts to lowercase any mistakenly uppercased schema (i.e.,
3680 * "Http://" converts to "http://"
3681 *
3682 * @return Original or modified URL
3683 *
3684 */
3685 String smartUrlFilter(String url) {
3686
3687 String inUrl = url.trim();
3688 boolean hasSpace = inUrl.indexOf(' ') != -1;
3689
3690 Matcher matcher = ACCEPTED_URI_SCHEMA.matcher(inUrl);
3691 if (matcher.matches()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003692 // force scheme to lowercase
3693 String scheme = matcher.group(1);
3694 String lcScheme = scheme.toLowerCase();
3695 if (!lcScheme.equals(scheme)) {
Mitsuru Oshima123ecfb2009-05-18 19:11:14 -07003696 inUrl = lcScheme + matcher.group(2);
3697 }
3698 if (hasSpace) {
3699 inUrl = inUrl.replace(" ", "%20");
The Android Open Source Project0c908882009-03-03 19:32:16 -08003700 }
3701 return inUrl;
3702 }
Leon Scroggins956cf012010-10-07 13:51:57 -04003703 if (!hasSpace) {
Dan Egnor5ee906c2009-11-18 12:11:49 -08003704 if (Patterns.WEB_URL.matcher(inUrl).matches()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003705 return URLUtil.guessUrl(inUrl);
3706 }
3707 }
3708
Leon Scroggins956cf012010-10-07 13:51:57 -04003709 // FIXME: Is this the correct place to add to searches?
3710 // what if someone else calls this function?
3711
The Android Open Source Project0c908882009-03-03 19:32:16 -08003712 Browser.addSearchUrl(mResolver, inUrl);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07003713 return URLUtil.composeSearchUrl(inUrl, QuickSearch_G, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003714 }
3715
Ben Murdochbff2d602009-07-01 20:19:05 +01003716 /* package */ void setShouldShowErrorConsole(boolean flag) {
3717 if (flag == mShouldShowErrorConsole) {
3718 // Nothing to do.
3719 return;
3720 }
Leon Scroggins IIIa9e35b62010-09-16 15:30:15 -04003721 Tab t = mTabControl.getCurrentTab();
3722 if (t == null) {
3723 // There is no current tab so we cannot toggle the error console
3724 return;
3725 }
Ben Murdochbff2d602009-07-01 20:19:05 +01003726
3727 mShouldShowErrorConsole = flag;
3728
Leon Scroggins IIIa9e35b62010-09-16 15:30:15 -04003729 ErrorConsoleView errorConsole = t.getErrorConsole(true);
Ben Murdochbff2d602009-07-01 20:19:05 +01003730
3731 if (flag) {
3732 // Setting the show state of the console will cause it's the layout to be inflated.
3733 if (errorConsole.numberOfErrors() > 0) {
3734 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
3735 } else {
3736 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
3737 }
3738
3739 // Now we can add it to the main view.
3740 mErrorConsoleContainer.addView(errorConsole,
Romain Guy15b8ec62010-01-08 15:06:43 -08003741 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
Ben Murdochbff2d602009-07-01 20:19:05 +01003742 ViewGroup.LayoutParams.WRAP_CONTENT));
3743 } else {
3744 mErrorConsoleContainer.removeView(errorConsole);
3745 }
3746
3747 }
3748
Grace Kloba22ac16e2009-10-07 18:00:23 -07003749 boolean shouldShowErrorConsole() {
3750 return mShouldShowErrorConsole;
3751 }
3752
Andrei Popescu163ab742009-10-20 17:58:23 +01003753 private void setStatusBarVisibility(boolean visible) {
3754 int flag = visible ? 0 : WindowManager.LayoutParams.FLAG_FULLSCREEN;
3755 getWindow().setFlags(flag, WindowManager.LayoutParams.FLAG_FULLSCREEN);
3756 }
3757
Andrei Popescu56199cc2010-01-12 22:39:16 +00003758
3759 private void sendNetworkType(String type, String subtype) {
3760 WebView w = mTabControl.getCurrentWebView();
3761 if (w != null) {
3762 w.setNetworkType(type, subtype);
3763 }
3764 }
3765
Andrei Popescu30995e72010-02-09 16:59:58 +00003766 private void packageChanged(String packageName, boolean wasAdded) {
3767 WebView w = mTabControl.getCurrentWebView();
3768 if (w == null) {
3769 return;
3770 }
3771
3772 if (wasAdded) {
3773 w.addPackageName(packageName);
3774 } else {
3775 w.removePackageName(packageName);
3776 }
3777 }
3778
3779 private void addPackageNames(Set<String> packageNames) {
3780 WebView w = mTabControl.getCurrentWebView();
3781 if (w == null) {
3782 return;
3783 }
3784
3785 w.addPackageNames(packageNames);
3786 }
3787
3788 private void getInstalledPackages() {
3789 AsyncTask<Void, Void, Set<String> > task =
3790 new AsyncTask<Void, Void, Set<String> >() {
3791 protected Set<String> doInBackground(Void... unused) {
3792 Set<String> installedPackages = new HashSet<String>();
3793 PackageManager pm = BrowserActivity.this.getPackageManager();
3794 if (pm != null) {
3795 List<PackageInfo> packages = pm.getInstalledPackages(0);
3796 for (PackageInfo p : packages) {
3797 if (BrowserActivity.this.sGoogleApps.contains(p.packageName)) {
3798 installedPackages.add(p.packageName);
3799 }
3800 }
3801 }
3802
3803 return installedPackages;
3804 }
3805
3806 // Executes on the UI thread
3807 protected void onPostExecute(Set<String> installedPackages) {
3808 addPackageNames(installedPackages);
3809 }
3810 };
3811 task.execute();
3812 }
3813
Grace Klobaeb6eef42009-09-15 17:56:32 -07003814 final static int LOCK_ICON_UNSECURE = 0;
3815 final static int LOCK_ICON_SECURE = 1;
3816 final static int LOCK_ICON_MIXED = 2;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003817
The Android Open Source Project0c908882009-03-03 19:32:16 -08003818 private BrowserSettings mSettings;
3819 private TabControl mTabControl;
3820 private ContentResolver mResolver;
3821 private FrameLayout mContentView;
Andrei Popescuadc008d2009-06-26 14:11:30 +01003822 private View mCustomView;
3823 private FrameLayout mCustomViewContainer;
Andrei Popescuc9b55562009-07-07 10:51:15 +01003824 private WebChromeClient.CustomViewCallback mCustomViewCallback;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003825
3826 // FIXME, temp address onPrepareMenu performance problem. When we move everything out of
3827 // view, we should rewrite this.
3828 private int mCurrentMenuState = 0;
3829 private int mMenuState = R.id.MAIN_MENU;
Andrei Popescuadc008d2009-06-26 14:11:30 +01003830 private int mOldMenuState = EMPTY_MENU;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003831 private static final int EMPTY_MENU = -1;
3832 private Menu mMenu;
3833
3834 private FindDialog mFindDialog;
Cary Clark2c326e62010-08-19 18:40:57 -04003835 private SelectDialog mSelectDialog;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003836 // Used to prevent chording to result in firing two shortcuts immediately
3837 // one after another. Fixes bug 1211714.
3838 boolean mCanChord;
3839
3840 private boolean mInLoad;
3841 private boolean mIsNetworkUp;
Ben Murdochb7cc8b42009-09-28 10:59:09 +01003842 private boolean mDidStopLoad;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003843
Cary Clark1f10cbf2010-03-22 11:45:23 -04003844 /* package */ boolean mActivityInPause = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003845
3846 private boolean mMenuIsDown;
3847
The Android Open Source Project0c908882009-03-03 19:32:16 -08003848 private static boolean mInTrace;
3849
3850 // Performance probe
3851 private static final int[] SYSTEM_CPU_FORMAT = new int[] {
3852 Process.PROC_SPACE_TERM | Process.PROC_COMBINE,
3853 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 1: user time
3854 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 2: nice time
3855 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 3: sys time
3856 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 4: idle time
3857 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 5: iowait time
3858 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 6: irq time
3859 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG // 7: softirq time
3860 };
3861
3862 private long mStart;
3863 private long mProcessStart;
3864 private long mUserStart;
3865 private long mSystemStart;
3866 private long mIdleStart;
3867 private long mIrqStart;
3868
3869 private long mUiStart;
3870
3871 private Drawable mMixLockIcon;
3872 private Drawable mSecLockIcon;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003873
3874 /* hold a ref so we can auto-cancel if necessary */
3875 private AlertDialog mAlertDialog;
3876
The Android Open Source Project0c908882009-03-03 19:32:16 -08003877 // The up-to-date URL and title (these can be different from those stored
3878 // in WebView, since it takes some time for the information in WebView to
3879 // get updated)
3880 private String mUrl;
3881 private String mTitle;
3882
3883 // As PageInfo has different style for landscape / portrait, we have
3884 // to re-open it when configuration changed
3885 private AlertDialog mPageInfoDialog;
Grace Kloba22ac16e2009-10-07 18:00:23 -07003886 private Tab mPageInfoView;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003887 // If the Page-Info dialog is launched from the SSL-certificate-on-error
3888 // dialog, we should not just dismiss it, but should get back to the
3889 // SSL-certificate-on-error dialog. This flag is used to store this state
Leon Scrogginsc7b92f82010-01-11 18:17:31 -05003890 private boolean mPageInfoFromShowSSLCertificateOnError;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003891
3892 // as SSLCertificateOnError has different style for landscape / portrait,
3893 // we have to re-open it when configuration changed
3894 private AlertDialog mSSLCertificateOnErrorDialog;
3895 private WebView mSSLCertificateOnErrorView;
3896 private SslErrorHandler mSSLCertificateOnErrorHandler;
3897 private SslError mSSLCertificateOnErrorError;
3898
3899 // as SSLCertificate has different style for landscape / portrait, we
3900 // have to re-open it when configuration changed
3901 private AlertDialog mSSLCertificateDialog;
Grace Kloba22ac16e2009-10-07 18:00:23 -07003902 private Tab mSSLCertificateView;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003903
3904 // as HttpAuthentication has different style for landscape / portrait, we
3905 // have to re-open it when configuration changed
3906 private AlertDialog mHttpAuthenticationDialog;
3907 private HttpAuthHandler mHttpAuthHandler;
3908
3909 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_PARAMS =
3910 new FrameLayout.LayoutParams(
Romain Guy15b8ec62010-01-08 15:06:43 -08003911 ViewGroup.LayoutParams.MATCH_PARENT,
3912 ViewGroup.LayoutParams.MATCH_PARENT);
Andrei Popescuadc008d2009-06-26 14:11:30 +01003913 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_GRAVITY_CENTER =
3914 new FrameLayout.LayoutParams(
Romain Guy15b8ec62010-01-08 15:06:43 -08003915 ViewGroup.LayoutParams.MATCH_PARENT,
3916 ViewGroup.LayoutParams.MATCH_PARENT,
Andrei Popescuadc008d2009-06-26 14:11:30 +01003917 Gravity.CENTER);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07003918 // Google search
3919 final static String QuickSearch_G = "http://www.google.com/m?q=%s";
The Android Open Source Project0c908882009-03-03 19:32:16 -08003920
3921 final static String QUERY_PLACE_HOLDER = "%s";
3922
3923 // "source" parameter for Google search through search key
3924 final static String GOOGLE_SEARCH_SOURCE_SEARCHKEY = "browser-key";
3925 // "source" parameter for Google search through goto menu
3926 final static String GOOGLE_SEARCH_SOURCE_GOTO = "browser-goto";
3927 // "source" parameter for Google search through simplily type
3928 final static String GOOGLE_SEARCH_SOURCE_TYPE = "browser-type";
3929 // "source" parameter for Google search suggested by the browser
3930 final static String GOOGLE_SEARCH_SOURCE_SUGGEST = "browser-suggest";
3931 // "source" parameter for Google search from unknown source
3932 final static String GOOGLE_SEARCH_SOURCE_UNKNOWN = "unknown";
3933
3934 private final static String LOGTAG = "browser";
3935
The Android Open Source Project0c908882009-03-03 19:32:16 -08003936 private String mLastEnteredUrl;
3937
3938 private PowerManager.WakeLock mWakeLock;
3939 private final static int WAKELOCK_TIMEOUT = 5 * 60 * 1000; // 5 minutes
3940
3941 private Toast mStopToast;
3942
Leon Scroggins68579392009-09-15 15:31:54 -04003943 private TitleBar mTitleBar;
Leon Scroggins81db3662009-06-04 17:45:11 -04003944
Ben Murdochbff2d602009-07-01 20:19:05 +01003945 private LinearLayout mErrorConsoleContainer = null;
3946 private boolean mShouldShowErrorConsole = false;
3947
The Android Open Source Project0c908882009-03-03 19:32:16 -08003948 // As the ids are dynamically created, we can't guarantee that they will
3949 // be in sequence, so this static array maps ids to a window number.
3950 final static private int[] WINDOW_SHORTCUT_ID_ARRAY =
3951 { R.id.window_one_menu_id, R.id.window_two_menu_id, R.id.window_three_menu_id,
3952 R.id.window_four_menu_id, R.id.window_five_menu_id, R.id.window_six_menu_id,
3953 R.id.window_seven_menu_id, R.id.window_eight_menu_id };
3954
3955 // monitor platform changes
3956 private IntentFilter mNetworkStateChangedFilter;
3957 private BroadcastReceiver mNetworkStateIntentReceiver;
3958
Grace Klobab4da0ad2009-05-14 14:45:40 -07003959 private BroadcastReceiver mPackageInstallationReceiver;
3960
Bjorn Bringerta7611812010-03-24 11:12:02 +00003961 private SystemAllowGeolocationOrigins mSystemAllowGeolocationOrigins;
3962
The Android Open Source Project0c908882009-03-03 19:32:16 -08003963 // activity requestCode
Nicolas Roard78a98e42009-05-11 13:34:17 +01003964 final static int COMBO_PAGE = 1;
Nicolas Roard78a98e42009-05-11 13:34:17 +01003965 final static int PREFERENCES_PAGE = 3;
Leon Scroggins8d5fa432009-10-02 15:55:59 -04003966 final static int FILE_SELECTED = 4;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003967
Andrei Popescu540035d2009-09-18 18:59:20 +01003968 // the default <video> poster
3969 private Bitmap mDefaultVideoPoster;
3970 // the video progress view
3971 private View mVideoProgressView;
3972
Andrei Popescu30995e72010-02-09 16:59:58 +00003973 // The Google packages we monitor for the navigator.isApplicationInstalled()
3974 // API. Add as needed.
3975 private static Set<String> sGoogleApps;
3976 static {
3977 sGoogleApps = new HashSet<String>();
3978 sGoogleApps.add("com.google.android.youtube");
3979 }
3980
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003981 /**
3982 * A UrlData class to abstract how the content will be set to WebView.
3983 * This base class uses loadUrl to show the content.
3984 */
Leon Scroggins6eac63e2010-03-15 18:19:14 -04003985 /* package */ static class UrlData {
Grace Kloba068e48b2010-01-26 18:11:27 -08003986 final String mUrl;
3987 final Map<String, String> mHeaders;
Leon Scroggins58d56c62010-01-28 15:12:40 -05003988 final Intent mVoiceIntent;
Grace Kloba60e095c2009-06-16 11:50:55 -07003989
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003990 UrlData(String url) {
3991 this.mUrl = url;
Grace Kloba068e48b2010-01-26 18:11:27 -08003992 this.mHeaders = null;
Leon Scroggins58d56c62010-01-28 15:12:40 -05003993 this.mVoiceIntent = null;
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003994 }
Grace Kloba60e095c2009-06-16 11:50:55 -07003995
Leon Scroggins58d56c62010-01-28 15:12:40 -05003996 UrlData(String url, Map<String, String> headers, Intent intent) {
Grace Kloba068e48b2010-01-26 18:11:27 -08003997 this.mUrl = url;
3998 this.mHeaders = headers;
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -05003999 if (RecognizerResultsIntent.ACTION_VOICE_SEARCH_RESULTS
4000 .equals(intent.getAction())) {
Leon Scroggins58d56c62010-01-28 15:12:40 -05004001 this.mVoiceIntent = intent;
4002 } else {
4003 this.mVoiceIntent = null;
4004 }
Grace Kloba60e095c2009-06-16 11:50:55 -07004005 }
4006
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004007 boolean isEmpty() {
Leon Scroggins58d56c62010-01-28 15:12:40 -05004008 return mVoiceIntent == null && (mUrl == null || mUrl.length() == 0);
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004009 }
4010
Leon Scroggins92472e82010-02-17 16:32:28 -05004011 /**
4012 * Load this UrlData into the given Tab. Use loadUrlDataIn to update
4013 * the title bar as well.
4014 */
Leon Scroggins58d56c62010-01-28 15:12:40 -05004015 public void loadIn(Tab t) {
4016 if (mVoiceIntent != null) {
4017 t.activateVoiceSearchMode(mVoiceIntent);
4018 } else {
4019 t.getWebView().loadUrl(mUrl, mHeaders);
4020 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004021 }
4022 };
4023
Leon Scroggins1f005d32009-08-10 17:36:42 -04004024 /* package */ static final UrlData EMPTY_URL_DATA = new UrlData(null);
Ed Tam8ba13bc2011-05-05 16:19:48 -07004025
4026 private static boolean needsRlz(Uri uri) {
4027 if ((uri.getQueryParameter("rlz") == null) &&
4028 (uri.getQueryParameter("q") != null) &&
4029 UrlUtils.isGoogleUri(uri)) {
4030 return true;
4031 }
4032 return false;
4033 }
4034
4035 private static Uri addRlzParameter(Uri uri, String rlz) {
4036 if (rlz.isEmpty()) {
4037 return uri;
4038 }
4039 return uri.buildUpon().appendQueryParameter("rlz", rlz).build();
4040 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08004041}