blob: deb57f3096d20c73f9d6d0f17908c2a7041cddd7 [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
Satish Sampath565505b2009-05-29 15:37:27 +0100149 // These are single-character shortcuts for searching popular sources.
150 private static final int SHORTCUT_INVALID = 0;
151 private static final int SHORTCUT_GOOGLE_SEARCH = 1;
152 private static final int SHORTCUT_WIKIPEDIA_SEARCH = 2;
153 private static final int SHORTCUT_DICTIONARY_SEARCH = 3;
154 private static final int SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH = 4;
155
Cary Clarka9771242009-08-11 16:42:26 -0400156 private static class ClearThumbnails extends AsyncTask<File, Void, Void> {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800157 @Override
158 public Void doInBackground(File... files) {
159 if (files != null) {
160 for (File f : files) {
Cary Clarkd6be1752009-08-12 12:56:42 -0400161 if (!f.delete()) {
162 Log.e(LOGTAG, f.getPath() + " was not deleted");
163 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800164 }
165 }
166 return null;
167 }
168 }
169
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400170 /**
171 * This layout holds everything you see below the status bar, including the
172 * error console, the custom view container, and the webviews.
173 */
174 private FrameLayout mBrowserFrameLayout;
Leon Scroggins81db3662009-06-04 17:45:11 -0400175
Grace Kloba22ac16e2009-10-07 18:00:23 -0700176 @Override
177 public void onCreate(Bundle icicle) {
Dave Bort31a6d1c2009-04-13 15:56:49 -0700178 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800179 Log.v(LOGTAG, this + " onStart");
180 }
181 super.onCreate(icicle);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800182 // test the browser in OpenGL
183 // requestWindowFeature(Window.FEATURE_OPENGL);
184
Mike Reedd334bf52010-01-26 15:21:44 -0500185 // enable this to test the browser in 32bit
186 if (false) {
187 getWindow().setFormat(PixelFormat.RGBX_8888);
188 BitmapFactory.setDefaultConfig(Bitmap.Config.ARGB_8888);
189 }
190
The Android Open Source Project0c908882009-03-03 19:32:16 -0800191 setDefaultKeyMode(DEFAULT_KEYS_SEARCH_LOCAL);
192
193 mResolver = getContentResolver();
194
Leon Scroggins IIIcc14c8c2010-09-27 12:45:34 -0400195 // Keep a settings instance handy.
196 mSettings = BrowserSettings.getInstance();
197
Grace Kloba0923d692009-09-23 21:37:25 -0700198 // If this was a web search request, pass it on to the default web
199 // search provider and finish this activity.
200 if (handleWebSearchIntent(getIntent())) {
201 finish();
202 return;
203 }
204
The Android Open Source Project0c908882009-03-03 19:32:16 -0800205 mSecLockIcon = Resources.getSystem().getDrawable(
206 android.R.drawable.ic_secure);
207 mMixLockIcon = Resources.getSystem().getDrawable(
208 android.R.drawable.ic_partial_secure);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800209
Leon Scroggins81db3662009-06-04 17:45:11 -0400210 FrameLayout frameLayout = (FrameLayout) getWindow().getDecorView()
211 .findViewById(com.android.internal.R.id.content);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400212 mBrowserFrameLayout = (FrameLayout) LayoutInflater.from(this)
213 .inflate(R.layout.custom_screen, null);
214 mContentView = (FrameLayout) mBrowserFrameLayout.findViewById(
215 R.id.main_content);
216 mErrorConsoleContainer = (LinearLayout) mBrowserFrameLayout
217 .findViewById(R.id.error_console);
218 mCustomViewContainer = (FrameLayout) mBrowserFrameLayout
219 .findViewById(R.id.fullscreen_custom_content);
220 frameLayout.addView(mBrowserFrameLayout, COVER_SCREEN_PARAMS);
Leon Scroggins68579392009-09-15 15:31:54 -0400221 mTitleBar = new TitleBar(this);
Grace Kloba1542f742010-03-17 21:11:15 -0700222 // mTitleBar will be always shown in the fully loaded mode
223 mTitleBar.setProgress(100);
Leon Scrogginsfe87bd32009-10-06 10:10:00 -0400224 mFakeTitleBar = new TitleBar(this);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800225
226 // Create the tab control and our initial tab
227 mTabControl = new TabControl(this);
228
229 // Open the icon database and retain all the bookmark urls for favicons
230 retainIconsOnStartup();
231
The Android Open Source Project0c908882009-03-03 19:32:16 -0800232 mSettings.setTabControl(mTabControl);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800233
234 PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
235 mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Browser");
236
Patrick Scott6adacc92010-03-05 08:24:51 -0500237 // Find out if the network is currently up.
238 ConnectivityManager cm = (ConnectivityManager) getSystemService(
239 Context.CONNECTIVITY_SERVICE);
240 NetworkInfo info = cm.getActiveNetworkInfo();
241 if (info != null) {
242 mIsNetworkUp = info.isAvailable();
243 }
244
Grace Klobaa34f6862009-07-31 16:28:17 -0700245 /* enables registration for changes in network status from
246 http stack */
247 mNetworkStateChangedFilter = new IntentFilter();
248 mNetworkStateChangedFilter.addAction(
249 ConnectivityManager.CONNECTIVITY_ACTION);
250 mNetworkStateIntentReceiver = new BroadcastReceiver() {
251 @Override
252 public void onReceive(Context context, Intent intent) {
253 if (intent.getAction().equals(
254 ConnectivityManager.CONNECTIVITY_ACTION)) {
Andrei Popescue4c98462010-02-19 15:44:13 +0000255
256 NetworkInfo info = intent.getParcelableExtra(
257 ConnectivityManager.EXTRA_NETWORK_INFO);
258 String typeName = info.getTypeName();
259 String subtypeName = info.getSubtypeName();
260 sendNetworkType(typeName.toLowerCase(),
261 (subtypeName != null ? subtypeName.toLowerCase() : ""));
262
263 onNetworkToggle(info.isAvailable());
Grace Klobaa34f6862009-07-31 16:28:17 -0700264 }
265 }
266 };
267
Grace Kloba615c6c92009-08-03 10:22:44 -0700268 IntentFilter filter = new IntentFilter(Intent.ACTION_PACKAGE_ADDED);
269 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
270 filter.addDataScheme("package");
271 mPackageInstallationReceiver = new BroadcastReceiver() {
272 @Override
273 public void onReceive(Context context, Intent intent) {
274 final String action = intent.getAction();
275 final String packageName = intent.getData()
276 .getSchemeSpecificPart();
277 final boolean replacing = intent.getBooleanExtra(
278 Intent.EXTRA_REPLACING, false);
279 if (Intent.ACTION_PACKAGE_REMOVED.equals(action) && replacing) {
280 // if it is replacing, refreshPlugins() when adding
281 return;
282 }
Andrei Popescu30995e72010-02-09 16:59:58 +0000283
284 if (sGoogleApps.contains(packageName)) {
285 BrowserActivity.this.packageChanged(packageName,
286 Intent.ACTION_PACKAGE_ADDED.equals(action));
287 }
288
Grace Kloba615c6c92009-08-03 10:22:44 -0700289 PackageManager pm = BrowserActivity.this.getPackageManager();
290 PackageInfo pkgInfo = null;
291 try {
292 pkgInfo = pm.getPackageInfo(packageName,
293 PackageManager.GET_PERMISSIONS);
294 } catch (PackageManager.NameNotFoundException e) {
295 return;
296 }
297 if (pkgInfo != null) {
298 String permissions[] = pkgInfo.requestedPermissions;
299 if (permissions == null) {
300 return;
301 }
302 boolean permissionOk = false;
303 for (String permit : permissions) {
304 if (PluginManager.PLUGIN_PERMISSION.equals(permit)) {
305 permissionOk = true;
306 break;
307 }
308 }
309 if (permissionOk) {
310 PluginManager.getInstance(BrowserActivity.this)
311 .refreshPlugins(
312 Intent.ACTION_PACKAGE_ADDED
313 .equals(action));
314 }
315 }
316 }
317 };
318 registerReceiver(mPackageInstallationReceiver, filter);
319
The Android Open Source Project0c908882009-03-03 19:32:16 -0800320 if (!mTabControl.restoreState(icicle)) {
321 // clear up the thumbnail directory if we can't restore the state as
322 // none of the files in the directory are referenced any more.
323 new ClearThumbnails().execute(
324 mTabControl.getThumbnailDir().listFiles());
Grace Klobaaab3f092009-07-30 12:29:51 -0700325 // there is no quit on Android. But if we can't restore the state,
326 // we can treat it as a new Browser, remove the old session cookies.
327 CookieManager.getInstance().removeSessionCookie();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800328 final Intent intent = getIntent();
329 final Bundle extra = intent.getExtras();
330 // Create an initial tab.
331 // If the intent is ACTION_VIEW and data is not null, the Browser is
332 // invoked to view the content by another application. In this case,
333 // the tab will be close when exit.
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700334 UrlData urlData = getUrlDataFromIntent(intent);
335
Leon Scroggins58d56c62010-01-28 15:12:40 -0500336 String action = intent.getAction();
Grace Kloba22ac16e2009-10-07 18:00:23 -0700337 final Tab t = mTabControl.createNewTab(
Leon Scroggins58d56c62010-01-28 15:12:40 -0500338 (Intent.ACTION_VIEW.equals(action) &&
339 intent.getData() != null)
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -0500340 || RecognizerResultsIntent.ACTION_VOICE_SEARCH_RESULTS
341 .equals(action),
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700342 intent.getStringExtra(Browser.EXTRA_APPLICATION_ID), urlData.mUrl);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800343 mTabControl.setCurrentTab(t);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800344 attachTabToContentView(t);
345 WebView webView = t.getWebView();
346 if (extra != null) {
347 int scale = extra.getInt(Browser.INITIAL_ZOOM_LEVEL, 0);
348 if (scale > 0 && scale <= 1000) {
349 webView.setInitialScale(scale);
350 }
351 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800352
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700353 if (urlData.isEmpty()) {
Shimeng (Simon) Wang98d5fce2010-03-16 13:23:39 -0700354 loadUrl(webView, mSettings.getHomePage());
The Android Open Source Project0c908882009-03-03 19:32:16 -0800355 } else {
Patrick Scott9d53da02010-02-19 10:19:01 -0500356 loadUrlDataIn(t, urlData);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800357 }
358 } else {
359 // TabControl.restoreState() will create a new tab even if
Leon Scroggins1f005d32009-08-10 17:36:42 -0400360 // restoring the state fails.
The Android Open Source Project0c908882009-03-03 19:32:16 -0800361 attachTabToContentView(mTabControl.getCurrentTab());
362 }
Grace Kloba615c6c92009-08-03 10:22:44 -0700363
Cary Clark23cbeb72010-07-01 12:36:56 -0400364 // Delete old thumbnails to save space
365 File dir = mTabControl.getThumbnailDir();
366 if (dir.exists()) {
367 for (String child : dir.list()) {
368 File f = new File(dir, child);
369 f.delete();
370 }
371 }
372
Feng Qianb3c02da2009-06-29 15:58:08 -0700373 // Read JavaScript flags if it exists.
374 String jsFlags = mSettings.getJsFlags();
375 if (jsFlags.trim().length() != 0) {
376 mTabControl.getCurrentWebView().setJsFlags(jsFlags);
377 }
Andrei Popescu30995e72010-02-09 16:59:58 +0000378 // Work out which packages are installed on the system.
379 getInstalledPackages();
Bjorn Bringerta7611812010-03-24 11:12:02 +0000380
381 // Start watching the default geolocation permissions
382 mSystemAllowGeolocationOrigins
383 = new SystemAllowGeolocationOrigins(getApplicationContext());
384 mSystemAllowGeolocationOrigins.start();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800385 }
386
Leon Scroggins58d56c62010-01-28 15:12:40 -0500387 /**
388 * Feed the previously stored results strings to the BrowserProvider so that
389 * the SearchDialog will show them instead of the standard searches.
390 * @param result String to show on the editable line of the SearchDialog.
391 */
392 /* package */ void showVoiceSearchResults(String result) {
393 ContentProviderClient client = mResolver.acquireContentProviderClient(
394 Browser.BOOKMARKS_URI);
395 ContentProvider prov = client.getLocalContentProvider();
396 BrowserProvider bp = (BrowserProvider) prov;
397 bp.setQueryResults(mTabControl.getCurrentTab().getVoiceSearchResults());
398 client.release();
399
Leon Scrogginsfbb3f152010-03-09 17:26:56 -0500400 Bundle bundle = createGoogleSearchSourceBundle(
401 GOOGLE_SEARCH_SOURCE_SEARCHKEY);
402 bundle.putBoolean(SearchManager.CONTEXT_IS_VOICE, true);
403 startSearch(result, false, bundle, false);
Leon Scroggins58d56c62010-01-28 15:12:40 -0500404 }
405
The Android Open Source Project0c908882009-03-03 19:32:16 -0800406 @Override
407 protected void onNewIntent(Intent intent) {
Grace Kloba22ac16e2009-10-07 18:00:23 -0700408 Tab current = mTabControl.getCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800409 // When a tab is closed on exit, the current tab index is set to -1.
410 // Reset before proceed as Browser requires the current tab to be set.
411 if (current == null) {
412 // Try to reset the tab in case the index was incorrect.
413 current = mTabControl.getTab(0);
414 if (current == null) {
415 // No tabs at all so just ignore this intent.
416 return;
417 }
418 mTabControl.setCurrentTab(current);
419 attachTabToContentView(current);
420 resetTitleAndIcon(current.getWebView());
421 }
422 final String action = intent.getAction();
423 final int flags = intent.getFlags();
424 if (Intent.ACTION_MAIN.equals(action) ||
425 (flags & Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY) != 0) {
426 // just resume the browser
427 return;
428 }
Leon Scrogginsb8a844d2010-03-18 15:06:15 -0400429 // In case the SearchDialog is open.
430 ((SearchManager) getSystemService(Context.SEARCH_SERVICE))
431 .stopSearch();
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -0500432 boolean activateVoiceSearch = RecognizerResultsIntent
433 .ACTION_VOICE_SEARCH_RESULTS.equals(action);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800434 if (Intent.ACTION_VIEW.equals(action)
435 || Intent.ACTION_SEARCH.equals(action)
436 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
Leon Scroggins58d56c62010-01-28 15:12:40 -0500437 || Intent.ACTION_WEB_SEARCH.equals(action)
438 || activateVoiceSearch) {
Leon Scroggins3b18ce32010-02-08 17:35:59 -0500439 if (current.isInVoiceSearchMode()) {
440 String title = current.getVoiceDisplayTitle();
441 if (title != null && title.equals(intent.getStringExtra(
442 SearchManager.QUERY))) {
443 // The user submitted the same search as the last voice
444 // search, so do nothing.
445 return;
446 }
Leon Scroggins1fe13a52010-02-09 15:31:26 -0500447 if (Intent.ACTION_SEARCH.equals(action)
448 && current.voiceSearchSourceIsGoogle()) {
449 Intent logIntent = new Intent(
450 LoggingEvents.ACTION_LOG_EVENT);
451 logIntent.putExtra(LoggingEvents.EXTRA_EVENT,
452 LoggingEvents.VoiceSearch.QUERY_UPDATED);
453 logIntent.putExtra(
454 LoggingEvents.VoiceSearch.EXTRA_QUERY_UPDATED_VALUE,
455 intent.getDataString());
456 sendBroadcast(logIntent);
457 // Note, onPageStarted will revert the voice title bar
458 // When http://b/issue?id=2379215 is fixed, we should update
459 // the title bar here.
460 }
Leon Scroggins3b18ce32010-02-08 17:35:59 -0500461 }
Satish Sampath565505b2009-05-29 15:37:27 +0100462 // If this was a search request (e.g. search query directly typed into the address bar),
463 // pass it on to the default web search provider.
464 if (handleWebSearchIntent(intent)) {
465 return;
466 }
467
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700468 UrlData urlData = getUrlDataFromIntent(intent);
469 if (urlData.isEmpty()) {
470 urlData = new UrlData(mSettings.getHomePage());
The Android Open Source Project0c908882009-03-03 19:32:16 -0800471 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700472
Grace Klobacc634032009-07-28 15:58:19 -0700473 final String appId = intent
474 .getStringExtra(Browser.EXTRA_APPLICATION_ID);
Leon Scroggins47208682010-04-07 17:59:48 -0400475 if ((Intent.ACTION_VIEW.equals(action)
476 // If a voice search has no appId, it means that it came
477 // from the browser. In that case, reuse the current tab.
478 || (activateVoiceSearch && appId != null))
Grace Klobacc634032009-07-28 15:58:19 -0700479 && !getPackageName().equals(appId)
480 && (flags & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0) {
Grace Kloba22ac16e2009-10-07 18:00:23 -0700481 Tab appTab = mTabControl.getTabFromId(appId);
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700482 if (appTab != null) {
483 Log.i(LOGTAG, "Reusing tab for " + appId);
484 // Dismiss the subwindow if applicable.
485 dismissSubWindow(appTab);
486 // Since we might kill the WebView, remove it from the
487 // content view first.
488 removeTabFromContentView(appTab);
489 // Recreate the main WebView after destroying the old one.
490 // If the WebView has the same original url and is on that
491 // page, it can be reused.
492 boolean needsLoad =
Leon Scroggins6eac63e2010-03-15 18:19:14 -0400493 mTabControl.recreateWebView(appTab, urlData);
Ben Murdochbff2d602009-07-01 20:19:05 +0100494
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700495 if (current != appTab) {
Leon Scroggins1f005d32009-08-10 17:36:42 -0400496 switchToTab(mTabControl.getTabIndex(appTab));
497 if (needsLoad) {
Patrick Scott9d53da02010-02-19 10:19:01 -0500498 loadUrlDataIn(appTab, urlData);
Leon Scroggins1f005d32009-08-10 17:36:42 -0400499 }
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700500 } else {
Leon Scroggins1f005d32009-08-10 17:36:42 -0400501 // If the tab was the current tab, we have to attach
502 // it to the view system again.
503 attachTabToContentView(appTab);
504 if (needsLoad) {
Patrick Scott9d53da02010-02-19 10:19:01 -0500505 loadUrlDataIn(appTab, urlData);
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700506 }
507 }
508 return;
Patrick Scottcd115892009-07-16 09:42:58 -0400509 } else {
510 // No matching application tab, try to find a regular tab
511 // with a matching url.
512 appTab = mTabControl.findUnusedTabWithUrl(urlData.mUrl);
Leon Scroggins25515f82009-08-19 15:31:58 -0400513 if (appTab != null) {
514 if (current != appTab) {
515 switchToTab(mTabControl.getTabIndex(appTab));
516 }
517 // Otherwise, we are already viewing the correct tab.
Patrick Scottcd115892009-07-16 09:42:58 -0400518 } else {
519 // if FLAG_ACTIVITY_BROUGHT_TO_FRONT flag is on, the url
520 // will be opened in a new tab unless we have reached
521 // MAX_TABS. Then the url will be opened in the current
522 // tab. If a new tab is created, it will have "true" for
523 // exit on close.
Leon Scroggins1f005d32009-08-10 17:36:42 -0400524 openTabAndShow(urlData, true, appId);
Patrick Scottcd115892009-07-16 09:42:58 -0400525 }
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700526 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800527 } else {
Grace Kloba638d3f42009-11-23 10:35:04 -0800528 if (!urlData.isEmpty()
529 && urlData.mUrl.startsWith("about:debug")) {
530 if ("about:debug.dom".equals(urlData.mUrl)) {
531 current.getWebView().dumpDomTree(false);
532 } else if ("about:debug.dom.file".equals(urlData.mUrl)) {
533 current.getWebView().dumpDomTree(true);
534 } else if ("about:debug.render".equals(urlData.mUrl)) {
535 current.getWebView().dumpRenderTree(false);
536 } else if ("about:debug.render.file".equals(urlData.mUrl)) {
537 current.getWebView().dumpRenderTree(true);
538 } else if ("about:debug.display".equals(urlData.mUrl)) {
539 current.getWebView().dumpDisplayTree();
Mike Reed9b78e1d2010-01-13 14:40:52 -0800540 } else if (urlData.mUrl.startsWith("about:debug.drag")) {
541 int index = urlData.mUrl.codePointAt(16) - '0';
542 if (index <= 0 || index > 9) {
543 current.getWebView().setDragTracker(null);
544 } else {
545 current.getWebView().setDragTracker(new MeshTracker(index));
546 }
Grace Kloba638d3f42009-11-23 10:35:04 -0800547 } else {
548 mSettings.toggleDebugSettings();
549 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800550 return;
551 }
Leon Scroggins1f005d32009-08-10 17:36:42 -0400552 // Get rid of the subwindow if it exists
553 dismissSubWindow(current);
Leon Scroggins8588d152010-04-15 11:01:53 -0400554 // If the current Tab is being used as an application tab,
555 // remove the association, since the new Intent means that it is
556 // no longer associated with that application.
557 current.setAppId(null);
Patrick Scott9d53da02010-02-19 10:19:01 -0500558 loadUrlDataIn(current, urlData);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800559 }
560 }
561 }
562
Satish Sampath565505b2009-05-29 15:37:27 +0100563 private int parseUrlShortcut(String url) {
564 if (url == null) return SHORTCUT_INVALID;
565
566 // FIXME: quick search, need to be customized by setting
567 if (url.length() > 2 && url.charAt(1) == ' ') {
568 switch (url.charAt(0)) {
569 case 'g': return SHORTCUT_GOOGLE_SEARCH;
570 case 'w': return SHORTCUT_WIKIPEDIA_SEARCH;
571 case 'd': return SHORTCUT_DICTIONARY_SEARCH;
572 case 'l': return SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH;
573 }
574 }
575 return SHORTCUT_INVALID;
576 }
577
578 /**
579 * Launches the default web search activity with the query parameters if the given intent's data
580 * are identified as plain search terms and not URLs/shortcuts.
581 * @return true if the intent was handled and web search activity was launched, false if not.
582 */
583 private boolean handleWebSearchIntent(Intent intent) {
584 if (intent == null) return false;
585
586 String url = null;
587 final String action = intent.getAction();
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -0500588 if (RecognizerResultsIntent.ACTION_VOICE_SEARCH_RESULTS.equals(
589 action)) {
Leon Scroggins58d56c62010-01-28 15:12:40 -0500590 return false;
591 }
Satish Sampath565505b2009-05-29 15:37:27 +0100592 if (Intent.ACTION_VIEW.equals(action)) {
Grace Kloba1e705052009-09-29 13:13:36 -0700593 Uri data = intent.getData();
594 if (data != null) url = data.toString();
Satish Sampath565505b2009-05-29 15:37:27 +0100595 } else if (Intent.ACTION_SEARCH.equals(action)
596 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
597 || Intent.ACTION_WEB_SEARCH.equals(action)) {
598 url = intent.getStringExtra(SearchManager.QUERY);
599 }
Bjorn Bringert04851702009-09-22 10:36:01 +0100600 return handleWebSearchRequest(url, intent.getBundleExtra(SearchManager.APP_DATA),
601 intent.getStringExtra(SearchManager.EXTRA_DATA_KEY));
Satish Sampath565505b2009-05-29 15:37:27 +0100602 }
603
604 /**
605 * Launches the default web search activity with the query parameters if the given url string
606 * was identified as plain search terms and not URL/shortcut.
607 * @return true if the request was handled and web search activity was launched, false if not.
608 */
Bjorn Bringert04851702009-09-22 10:36:01 +0100609 private boolean handleWebSearchRequest(String inUrl, Bundle appData, String extraData) {
Satish Sampath565505b2009-05-29 15:37:27 +0100610 if (inUrl == null) return false;
611
612 // In general, we shouldn't modify URL from Intent.
613 // But currently, we get the user-typed URL from search box as well.
614 String url = fixUrl(inUrl).trim();
615
616 // URLs and site specific search shortcuts are handled by the regular flow of control, so
617 // return early.
Dan Egnor5ee906c2009-11-18 12:11:49 -0800618 if (Patterns.WEB_URL.matcher(url).matches()
Satish Sampathbc5b9f32009-06-04 18:21:40 +0100619 || ACCEPTED_URI_SCHEMA.matcher(url).matches()
Satish Sampath565505b2009-05-29 15:37:27 +0100620 || parseUrlShortcut(url) != SHORTCUT_INVALID) {
621 return false;
622 }
623
Leon Scroggins8d06e362010-03-24 14:45:57 -0400624 final ContentResolver cr = mResolver;
625 final String newUrl = url;
626 new AsyncTask<Void, Void, Void>() {
627 protected Void doInBackground(Void... unused) {
628 Browser.updateVisitedHistory(cr, newUrl, false);
629 Browser.addSearchUrl(cr, newUrl);
630 return null;
631 }
632 }.execute();
Satish Sampath565505b2009-05-29 15:37:27 +0100633
Bjorn Bringertd2670652010-09-13 14:06:41 +0100634 SearchEngine searchEngine = mSettings.getSearchEngine();
635 if (searchEngine == null) return false;
636 searchEngine.startSearch(this, url, appData, extraData);
Satish Sampath565505b2009-05-29 15:37:27 +0100637
638 return true;
639 }
640
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700641 private UrlData getUrlDataFromIntent(Intent intent) {
Leon Scroggins58d56c62010-01-28 15:12:40 -0500642 String url = "";
Grace Kloba068e48b2010-01-26 18:11:27 -0800643 Map<String, String> headers = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800644 if (intent != null) {
645 final String action = intent.getAction();
646 if (Intent.ACTION_VIEW.equals(action)) {
647 url = smartUrlFilter(intent.getData());
648 if (url != null && url.startsWith("content:")) {
649 /* Append mimetype so webview knows how to display */
650 String mimeType = intent.resolveType(getContentResolver());
651 if (mimeType != null) {
652 url += "?" + mimeType;
653 }
654 }
Grace Kloba068e48b2010-01-26 18:11:27 -0800655 if (url != null && url.startsWith("http")) {
Grace Kloba00f54c52010-01-27 14:53:51 -0800656 final Bundle pairs = intent
657 .getBundleExtra(Browser.EXTRA_HEADERS);
Grace Kloba2d508ed2010-01-28 11:39:15 -0800658 if (pairs != null && !pairs.isEmpty()) {
Grace Kloba00f54c52010-01-27 14:53:51 -0800659 Iterator<String> iter = pairs.keySet().iterator();
Grace Kloba068e48b2010-01-26 18:11:27 -0800660 headers = new HashMap<String, String>();
Grace Kloba00f54c52010-01-27 14:53:51 -0800661 while (iter.hasNext()) {
662 String key = iter.next();
663 headers.put(key, pairs.getString(key));
Grace Kloba068e48b2010-01-26 18:11:27 -0800664 }
665 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700666 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800667 } else if (Intent.ACTION_SEARCH.equals(action)
668 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
669 || Intent.ACTION_WEB_SEARCH.equals(action)) {
670 url = intent.getStringExtra(SearchManager.QUERY);
671 if (url != null) {
672 mLastEnteredUrl = url;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800673 // In general, we shouldn't modify URL from Intent.
674 // But currently, we get the user-typed URL from search box as well.
675 url = fixUrl(url);
676 url = smartUrlFilter(url);
Leon Scroggins8d06e362010-03-24 14:45:57 -0400677 final ContentResolver cr = mResolver;
678 final String newUrl = url;
679 new AsyncTask<Void, Void, Void>() {
680 protected Void doInBackground(Void... unused) {
681 Browser.updateVisitedHistory(cr, newUrl, false);
682 return null;
683 }
684 }.execute();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800685 String searchSource = "&source=android-" + GOOGLE_SEARCH_SOURCE_SUGGEST + "&";
686 if (url.contains(searchSource)) {
687 String source = null;
688 final Bundle appData = intent.getBundleExtra(SearchManager.APP_DATA);
689 if (appData != null) {
Bjorn Bringert10d1cca2010-02-10 14:22:12 +0000690 source = appData.getString(Search.SOURCE);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800691 }
692 if (TextUtils.isEmpty(source)) {
693 source = GOOGLE_SEARCH_SOURCE_UNKNOWN;
694 }
695 url = url.replace(searchSource, "&source=android-"+source+"&");
696 }
697 }
698 }
699 }
Leon Scroggins58d56c62010-01-28 15:12:40 -0500700 return new UrlData(url, headers, intent);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800701 }
Leon Scroggins58d56c62010-01-28 15:12:40 -0500702 /* package */ void showVoiceTitleBar(String title) {
703 mTitleBar.setInVoiceMode(true);
704 mFakeTitleBar.setInVoiceMode(true);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800705
Leon Scroggins58d56c62010-01-28 15:12:40 -0500706 mTitleBar.setDisplayTitle(title);
707 mFakeTitleBar.setDisplayTitle(title);
708 }
709 /* package */ void revertVoiceTitleBar() {
710 mTitleBar.setInVoiceMode(false);
711 mFakeTitleBar.setInVoiceMode(false);
712
Leon Scroggins003a5dd2010-03-10 12:13:14 -0500713 mTitleBar.setDisplayTitle(mUrl);
714 mFakeTitleBar.setDisplayTitle(mUrl);
Leon Scroggins58d56c62010-01-28 15:12:40 -0500715 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800716 /* package */ static String fixUrl(String inUrl) {
Cary Clark652ff872009-09-10 13:34:44 -0400717 // FIXME: Converting the url to lower case
718 // duplicates functionality in smartUrlFilter().
719 // However, changing all current callers of fixUrl to
720 // call smartUrlFilter in addition may have unwanted
721 // consequences, and is deferred for now.
722 int colon = inUrl.indexOf(':');
723 boolean allLower = true;
724 for (int index = 0; index < colon; index++) {
725 char ch = inUrl.charAt(index);
726 if (!Character.isLetter(ch)) {
727 break;
728 }
729 allLower &= Character.isLowerCase(ch);
730 if (index == colon - 1 && !allLower) {
731 inUrl = inUrl.substring(0, colon).toLowerCase()
732 + inUrl.substring(colon);
733 }
734 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800735 if (inUrl.startsWith("http://") || inUrl.startsWith("https://"))
736 return inUrl;
737 if (inUrl.startsWith("http:") ||
738 inUrl.startsWith("https:")) {
739 if (inUrl.startsWith("http:/") || inUrl.startsWith("https:/")) {
740 inUrl = inUrl.replaceFirst("/", "//");
741 } else inUrl = inUrl.replaceFirst(":", "://");
742 }
743 return inUrl;
744 }
745
Grace Kloba22ac16e2009-10-07 18:00:23 -0700746 @Override
747 protected void onResume() {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800748 super.onResume();
Dave Bort31a6d1c2009-04-13 15:56:49 -0700749 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800750 Log.v(LOGTAG, "BrowserActivity.onResume: this=" + this);
751 }
752
753 if (!mActivityInPause) {
754 Log.e(LOGTAG, "BrowserActivity is already resumed.");
755 return;
756 }
757
Mike Reed7bfa63b2009-05-28 11:08:32 -0400758 mTabControl.resumeCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800759 mActivityInPause = false;
Mike Reed7bfa63b2009-05-28 11:08:32 -0400760 resumeWebViewTimers();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800761
762 if (mWakeLock.isHeld()) {
763 mHandler.removeMessages(RELEASE_WAKELOCK);
764 mWakeLock.release();
765 }
766
The Android Open Source Project0c908882009-03-03 19:32:16 -0800767 registerReceiver(mNetworkStateIntentReceiver,
768 mNetworkStateChangedFilter);
769 WebView.enablePlatformNotifications();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800770 }
771
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400772 /**
773 * Since the actual title bar is embedded in the WebView, and removing it
Leon Scrogginsfe87bd32009-10-06 10:10:00 -0400774 * would change its appearance, use a different TitleBar to show overlayed
775 * at the top of the screen, when the menu is open or the page is loading.
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400776 */
777 private TitleBar mFakeTitleBar;
778
779 /**
780 * Keeps track of whether the options menu is open. This is important in
781 * determining whether to show or hide the title bar overlay.
782 */
783 private boolean mOptionsMenuOpen;
784
785 /**
786 * Only meaningful when mOptionsMenuOpen is true. This variable keeps track
787 * of whether the configuration has changed. The first onMenuOpened call
788 * after a configuration change is simply a reopening of the same menu
789 * (i.e. mIconView did not change).
790 */
791 private boolean mConfigChanged;
792
793 /**
794 * Whether or not the options menu is in its smaller, icon menu form. When
795 * true, we want the title bar overlay to be up. When false, we do not.
796 * Only meaningful if mOptionsMenuOpen is true.
797 */
798 private boolean mIconView;
799
Leon Scrogginsa81a7642009-08-31 17:05:41 -0400800 @Override
801 public boolean onMenuOpened(int featureId, Menu menu) {
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400802 if (Window.FEATURE_OPTIONS_PANEL == featureId) {
803 if (mOptionsMenuOpen) {
804 if (mConfigChanged) {
805 // We do not need to make any changes to the state of the
806 // title bar, since the only thing that happened was a
807 // change in orientation
808 mConfigChanged = false;
809 } else {
810 if (mIconView) {
811 // Switching the menu to expanded view, so hide the
812 // title bar.
813 hideFakeTitleBar();
814 mIconView = false;
815 } else {
816 // Switching the menu back to icon view, so show the
817 // title bar once again.
818 showFakeTitleBar();
819 mIconView = true;
820 }
821 }
822 } else {
823 // The options menu is closed, so open it, and show the title
824 showFakeTitleBar();
825 mOptionsMenuOpen = true;
826 mConfigChanged = false;
827 mIconView = true;
828 }
829 }
Leon Scrogginsa81a7642009-08-31 17:05:41 -0400830 return true;
831 }
832
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400833 private void showFakeTitleBar() {
Leon Scrogginsfe87bd32009-10-06 10:10:00 -0400834 if (mFakeTitleBar.getParent() == null && mActiveTabsPage == null
Grace Kloba847c25b2010-03-30 16:00:26 -0700835 && !mActivityInPause) {
836 WebView mainView = mTabControl.getCurrentWebView();
837 // if there is no current WebView, don't show the faked title bar;
Grace Kloba65190702010-04-02 23:37:26 -0700838 if (mainView == null) {
Cary Clarka0464552009-09-29 13:00:45 -0400839 return;
840 }
Cary Clark2c326e62010-08-19 18:40:57 -0400841 // Do not need to check for null, since the current tab will have
842 // at least a main WebView, or we would have returned above.
843 if (dialogIsUp()) {
844 // Do not show the fake title bar, which would cover up the
845 // find or select dialog.
846 return;
847 }
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400848
849 WindowManager manager
850 = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
851
852 // Add the title bar to the window manager so it can receive touches
853 // while the menu is up
854 WindowManager.LayoutParams params
855 = new WindowManager.LayoutParams(
Romain Guy15b8ec62010-01-08 15:06:43 -0800856 ViewGroup.LayoutParams.MATCH_PARENT,
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400857 ViewGroup.LayoutParams.WRAP_CONTENT,
Grace Kloba847c25b2010-03-30 16:00:26 -0700858 WindowManager.LayoutParams.TYPE_APPLICATION,
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400859 WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
Leon Scroggins68549862009-09-21 16:02:01 -0400860 PixelFormat.TRANSLUCENT);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400861 params.gravity = Gravity.TOP;
Grace Kloba847c25b2010-03-30 16:00:26 -0700862 boolean atTop = mainView.getScrollY() == 0;
Leon Scroggins83932c72009-09-30 11:55:54 -0400863 params.windowAnimations = atTop ? 0 : R.style.TitleBar;
Grace Kloba13f9ace2010-03-18 21:44:14 -0700864 manager.addView(mFakeTitleBar, params);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400865 }
866 }
867
868 @Override
869 public void onOptionsMenuClosed(Menu menu) {
870 mOptionsMenuOpen = false;
Leon Scrogginsa27ff192009-09-14 12:58:04 -0400871 if (!mInLoad) {
872 hideFakeTitleBar();
873 } else if (!mIconView) {
874 // The page is currently loading, and we are in expanded mode, so
875 // we were not showing the menu. Show it once again. It will be
876 // removed when the page finishes.
877 showFakeTitleBar();
878 }
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400879 }
Grace Kloba22ac16e2009-10-07 18:00:23 -0700880
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400881 private void hideFakeTitleBar() {
Leon Scrogginsfe87bd32009-10-06 10:10:00 -0400882 if (mFakeTitleBar.getParent() == null) return;
Leon Scroggins20329572009-09-23 17:42:41 -0400883 WindowManager.LayoutParams params = (WindowManager.LayoutParams)
Grace Kloba13f9ace2010-03-18 21:44:14 -0700884 mFakeTitleBar.getLayoutParams();
Leon Scroggins20329572009-09-23 17:42:41 -0400885 WebView mainView = mTabControl.getCurrentWebView();
886 // Although we decided whether or not to animate based on the current
887 // scroll position, the scroll position may have changed since the
888 // fake title bar was displayed. Make sure it has the appropriate
889 // animation/lack thereof before removing.
890 params.windowAnimations = mainView != null && mainView.getScrollY() == 0
Leon Scroggins83932c72009-09-30 11:55:54 -0400891 ? 0 : R.style.TitleBar;
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400892 WindowManager manager
893 = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
Grace Kloba13f9ace2010-03-18 21:44:14 -0700894 manager.updateViewLayout(mFakeTitleBar, params);
895 manager.removeView(mFakeTitleBar);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400896 }
897
The Android Open Source Project0c908882009-03-03 19:32:16 -0800898 /**
Leon Scrogginsc6fa1102009-09-21 10:40:01 -0400899 * Special method for the fake title bar to call when displaying its context
900 * menu, since it is in its own Window, and its parent does not show a
901 * context menu.
902 */
903 /* package */ void showTitleBarContextMenu() {
Cary Clark65f4a3c2009-09-28 17:05:06 -0400904 if (null == mTitleBar.getParent()) {
905 return;
906 }
Leon Scrogginsc6fa1102009-09-21 10:40:01 -0400907 openContextMenu(mTitleBar);
908 }
909
Leon Scrogginsb2b19f52009-10-09 16:10:00 -0400910 @Override
911 public void onContextMenuClosed(Menu menu) {
912 super.onContextMenuClosed(menu);
913 if (mInLoad) {
914 showFakeTitleBar();
915 }
916 }
917
Leon Scrogginsc6fa1102009-09-21 10:40:01 -0400918 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -0800919 * onSaveInstanceState(Bundle map)
920 * onSaveInstanceState is called right before onStop(). The map contains
921 * the saved state.
922 */
Grace Kloba22ac16e2009-10-07 18:00:23 -0700923 @Override
924 protected void onSaveInstanceState(Bundle outState) {
Dave Bort31a6d1c2009-04-13 15:56:49 -0700925 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800926 Log.v(LOGTAG, "BrowserActivity.onSaveInstanceState: this=" + this);
927 }
928 // the default implementation requires each view to have an id. As the
929 // browser handles the state itself and it doesn't use id for the views,
930 // don't call the default implementation. Otherwise it will trigger the
931 // warning like this, "couldn't save which view has focus because the
932 // focused view XXX has no id".
933
934 // Save all the tabs
935 mTabControl.saveState(outState);
936 }
937
Grace Kloba22ac16e2009-10-07 18:00:23 -0700938 @Override
939 protected void onPause() {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800940 super.onPause();
941
942 if (mActivityInPause) {
943 Log.e(LOGTAG, "BrowserActivity is already paused.");
944 return;
945 }
946
Mike Reed7bfa63b2009-05-28 11:08:32 -0400947 mTabControl.pauseCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800948 mActivityInPause = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -0400949 if (mTabControl.getCurrentIndex() >= 0 && !pauseWebViewTimers()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800950 mWakeLock.acquire();
951 mHandler.sendMessageDelayed(mHandler
952 .obtainMessage(RELEASE_WAKELOCK), WAKELOCK_TIMEOUT);
953 }
954
Leon Scrogginsa2ab6a72009-09-11 11:49:52 -0400955 // FIXME: This removes the active tabs page and resets the menu to
956 // MAIN_MENU. A better solution might be to do this work in onNewIntent
957 // but then we would need to save it in onSaveInstanceState and restore
958 // it in onCreate/onRestoreInstanceState
959 if (mActiveTabsPage != null) {
960 removeActiveTabPage(true);
961 }
962
The Android Open Source Project0c908882009-03-03 19:32:16 -0800963 cancelStopToast();
964
965 // unregister network state listener
966 unregisterReceiver(mNetworkStateIntentReceiver);
967 WebView.disablePlatformNotifications();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800968 }
969
Grace Kloba22ac16e2009-10-07 18:00:23 -0700970 @Override
971 protected void onDestroy() {
Dave Bort31a6d1c2009-04-13 15:56:49 -0700972 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800973 Log.v(LOGTAG, "BrowserActivity.onDestroy: this=" + this);
974 }
975 super.onDestroy();
Grace Kloba0923d692009-09-23 21:37:25 -0700976
Leon Scroggins8d5fa432009-10-02 15:55:59 -0400977 if (mUploadMessage != null) {
978 mUploadMessage.onReceiveValue(null);
979 mUploadMessage = null;
980 }
981
Grace Kloba0923d692009-09-23 21:37:25 -0700982 if (mTabControl == null) return;
983
Grace Kloba1fc98a32009-10-21 13:23:08 -0700984 // Remove the fake title bar if it is there
985 hideFakeTitleBar();
986
The Android Open Source Project0c908882009-03-03 19:32:16 -0800987 // Remove the current tab and sub window
Grace Kloba22ac16e2009-10-07 18:00:23 -0700988 Tab t = mTabControl.getCurrentTab();
Patrick Scottfb5e77f2009-04-08 19:17:37 -0700989 if (t != null) {
990 dismissSubWindow(t);
991 removeTabFromContentView(t);
992 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800993 // Destroy all the tabs
994 mTabControl.destroy();
995 WebIconDatabase.getInstance().close();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800996
Grace Klobab4da0ad2009-05-14 14:45:40 -0700997 unregisterReceiver(mPackageInstallationReceiver);
Bjorn Bringerta7611812010-03-24 11:12:02 +0000998
999 // Stop watching the default geolocation permissions
1000 mSystemAllowGeolocationOrigins.stop();
1001 mSystemAllowGeolocationOrigins = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001002 }
1003
1004 @Override
1005 public void onConfigurationChanged(Configuration newConfig) {
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04001006 mConfigChanged = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001007 super.onConfigurationChanged(newConfig);
1008
1009 if (mPageInfoDialog != null) {
1010 mPageInfoDialog.dismiss();
1011 showPageInfo(
1012 mPageInfoView,
Leon Scrogginsc7b92f82010-01-11 18:17:31 -05001013 mPageInfoFromShowSSLCertificateOnError);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001014 }
1015 if (mSSLCertificateDialog != null) {
1016 mSSLCertificateDialog.dismiss();
1017 showSSLCertificate(
1018 mSSLCertificateView);
1019 }
1020 if (mSSLCertificateOnErrorDialog != null) {
1021 mSSLCertificateOnErrorDialog.dismiss();
1022 showSSLCertificateOnError(
1023 mSSLCertificateOnErrorView,
1024 mSSLCertificateOnErrorHandler,
1025 mSSLCertificateOnErrorError);
1026 }
1027 if (mHttpAuthenticationDialog != null) {
1028 String title = ((TextView) mHttpAuthenticationDialog
1029 .findViewById(com.android.internal.R.id.alertTitle)).getText()
1030 .toString();
1031 String name = ((TextView) mHttpAuthenticationDialog
1032 .findViewById(R.id.username_edit)).getText().toString();
1033 String password = ((TextView) mHttpAuthenticationDialog
1034 .findViewById(R.id.password_edit)).getText().toString();
1035 int focusId = mHttpAuthenticationDialog.getCurrentFocus()
1036 .getId();
1037 mHttpAuthenticationDialog.dismiss();
1038 showHttpAuthentication(mHttpAuthHandler, null, null, title,
1039 name, password, focusId);
1040 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001041 }
1042
Grace Kloba22ac16e2009-10-07 18:00:23 -07001043 @Override
1044 public void onLowMemory() {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001045 super.onLowMemory();
1046 mTabControl.freeMemory();
1047 }
1048
Cary Clarkff4d92c2010-03-25 11:17:03 -04001049 private void resumeWebViewTimers() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001050 Tab tab = mTabControl.getCurrentTab();
Cary Clarkff4d92c2010-03-25 11:17:03 -04001051 if (tab == null) return; // monkey can trigger this
Grace Kloba22ac16e2009-10-07 18:00:23 -07001052 boolean inLoad = tab.inLoad();
1053 if ((!mActivityInPause && !inLoad) || (mActivityInPause && inLoad)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001054 CookieSyncManager.getInstance().startSync();
Grace Kloba22ac16e2009-10-07 18:00:23 -07001055 WebView w = tab.getWebView();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001056 if (w != null) {
1057 w.resumeTimers();
1058 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001059 }
1060 }
1061
Mike Reed7bfa63b2009-05-28 11:08:32 -04001062 private boolean pauseWebViewTimers() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001063 Tab tab = mTabControl.getCurrentTab();
1064 boolean inLoad = tab.inLoad();
1065 if (mActivityInPause && !inLoad) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001066 CookieSyncManager.getInstance().stopSync();
1067 WebView w = mTabControl.getCurrentWebView();
1068 if (w != null) {
1069 w.pauseTimers();
1070 }
1071 return true;
1072 } else {
1073 return false;
1074 }
1075 }
1076
The Android Open Source Project0c908882009-03-03 19:32:16 -08001077 // Open the icon database and retain all the icons for visited sites.
1078 private void retainIconsOnStartup() {
1079 final WebIconDatabase db = WebIconDatabase.getInstance();
1080 db.open(getDir("icons", 0).getPath());
Leon Scroggins2c0f6112010-03-12 18:09:39 -05001081 Cursor c = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001082 try {
Leon Scroggins2c0f6112010-03-12 18:09:39 -05001083 c = Browser.getAllBookmarks(mResolver);
1084 if (c.moveToFirst()) {
1085 int urlIndex = c.getColumnIndex(Browser.BookmarkColumns.URL);
1086 do {
1087 String url = c.getString(urlIndex);
1088 db.retainIconForPageUrl(url);
1089 } while (c.moveToNext());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001090 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001091 } catch (IllegalStateException e) {
1092 Log.e(LOGTAG, "retainIconsOnStartup", e);
Leon Scroggins2c0f6112010-03-12 18:09:39 -05001093 } finally {
1094 if (c!= null) c.close();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001095 }
1096 }
1097
1098 // Helper method for getting the top window.
1099 WebView getTopWindow() {
1100 return mTabControl.getCurrentTopWebView();
1101 }
1102
Grace Kloba22ac16e2009-10-07 18:00:23 -07001103 TabControl getTabControl() {
1104 return mTabControl;
1105 }
1106
The Android Open Source Project0c908882009-03-03 19:32:16 -08001107 @Override
1108 public boolean onCreateOptionsMenu(Menu menu) {
1109 super.onCreateOptionsMenu(menu);
1110
1111 MenuInflater inflater = getMenuInflater();
1112 inflater.inflate(R.menu.browser, menu);
1113 mMenu = menu;
1114 updateInLoadMenuItems();
1115 return true;
1116 }
1117
1118 /**
1119 * As the menu can be open when loading state changes
1120 * we must manually update the state of the stop/reload menu
1121 * item
1122 */
1123 private void updateInLoadMenuItems() {
1124 if (mMenu == null) {
1125 return;
1126 }
1127 MenuItem src = mInLoad ?
1128 mMenu.findItem(R.id.stop_menu_id):
1129 mMenu.findItem(R.id.reload_menu_id);
1130 MenuItem dest = mMenu.findItem(R.id.stop_reload_menu_id);
1131 dest.setIcon(src.getIcon());
1132 dest.setTitle(src.getTitle());
1133 }
1134
1135 @Override
1136 public boolean onContextItemSelected(MenuItem item) {
1137 // chording is not an issue with context menus, but we use the same
1138 // options selector, so set mCanChord to true so we can access them.
1139 mCanChord = true;
1140 int id = item.getItemId();
Leon Scroggins96afcb12009-12-10 12:35:56 -05001141 boolean result = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001142 switch (id) {
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001143 // For the context menu from the title bar
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001144 case R.id.title_bar_copy_page_url:
Leon Scroggins96afcb12009-12-10 12:35:56 -05001145 Tab currentTab = mTabControl.getCurrentTab();
1146 if (null == currentTab) {
1147 result = false;
1148 break;
1149 }
1150 WebView mainView = currentTab.getWebView();
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001151 if (null == mainView) {
Leon Scroggins96afcb12009-12-10 12:35:56 -05001152 result = false;
1153 break;
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001154 }
Leon Scroggins96afcb12009-12-10 12:35:56 -05001155 copy(mainView.getUrl());
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001156 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001157 // -- Browser context menu
1158 case R.id.open_context_menu_id:
1159 case R.id.open_newtab_context_menu_id:
1160 case R.id.bookmark_context_menu_id:
1161 case R.id.save_link_context_menu_id:
1162 case R.id.share_link_context_menu_id:
1163 case R.id.copy_link_context_menu_id:
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001164 final WebView webView = getTopWindow();
1165 if (null == webView) {
Leon Scroggins96afcb12009-12-10 12:35:56 -05001166 result = false;
1167 break;
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001168 }
1169 final HashMap hrefMap = new HashMap();
1170 hrefMap.put("webview", webView);
1171 final Message msg = mHandler.obtainMessage(
1172 FOCUS_NODE_HREF, id, 0, hrefMap);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001173 webView.requestFocusNodeHref(msg);
1174 break;
1175
1176 default:
1177 // For other context menus
Leon Scroggins96afcb12009-12-10 12:35:56 -05001178 result = onOptionsItemSelected(item);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001179 }
1180 mCanChord = false;
Leon Scroggins96afcb12009-12-10 12:35:56 -05001181 return result;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001182 }
1183
1184 private Bundle createGoogleSearchSourceBundle(String source) {
1185 Bundle bundle = new Bundle();
Bjorn Bringert10d1cca2010-02-10 14:22:12 +00001186 bundle.putString(Search.SOURCE, source);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001187 return bundle;
1188 }
1189
Leon Scroggins8ad29922010-02-16 12:33:55 -05001190 /* package */ void editUrl() {
Leon Scroggins68579392009-09-15 15:31:54 -04001191 if (mOptionsMenuOpen) closeOptionsMenu();
Leon Scroggins5bbe9802009-07-31 13:10:55 -04001192 String url = (getTopWindow() == null) ? null : getTopWindow().getUrl();
Grace Kloba83f47342009-07-20 10:44:31 -07001193 startSearch(mSettings.getHomePage().equals(url) ? null : url, true,
Leon Scroggins8ad29922010-02-16 12:33:55 -05001194 null, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001195 }
1196
Leon Scroggins8ad29922010-02-16 12:33:55 -05001197 /**
1198 * Overriding this to insert a local information bundle
1199 */
The Android Open Source Project0c908882009-03-03 19:32:16 -08001200 @Override
1201 public void startSearch(String initialQuery, boolean selectInitialQuery,
1202 Bundle appSearchData, boolean globalSearch) {
1203 if (appSearchData == null) {
1204 appSearchData = createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_TYPE);
1205 }
Leon Scroggins III430057d2010-09-14 10:57:37 -04001206
1207 SearchEngine searchEngine = mSettings.getSearchEngine();
1208 if (searchEngine != null && !searchEngine.supportsVoiceSearch()) {
1209 appSearchData.putBoolean(SearchManager.DISABLE_VOICE_SEARCH, true);
1210 }
1211
The Android Open Source Project0c908882009-03-03 19:32:16 -08001212 super.startSearch(initialQuery, selectInitialQuery, appSearchData, globalSearch);
1213 }
1214
Leon Scroggins1f005d32009-08-10 17:36:42 -04001215 /**
1216 * Switch tabs. Called by the TitleBarSet when sliding the title bar
1217 * results in changing tabs.
Leon Scroggins160a7e72009-08-14 18:28:01 -04001218 * @param index Index of the tab to change to, as defined by
1219 * mTabControl.getTabIndex(Tab t).
1220 * @return boolean True if we successfully switched to a different tab. If
1221 * the indexth tab is null, or if that tab is the same as
1222 * the current one, return false.
Leon Scroggins1f005d32009-08-10 17:36:42 -04001223 */
Leon Scroggins160a7e72009-08-14 18:28:01 -04001224 /* package */ boolean switchToTab(int index) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001225 Tab tab = mTabControl.getTab(index);
1226 Tab currentTab = mTabControl.getCurrentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04001227 if (tab == null || tab == currentTab) {
Leon Scroggins160a7e72009-08-14 18:28:01 -04001228 return false;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001229 }
1230 if (currentTab != null) {
1231 // currentTab may be null if it was just removed. In that case,
1232 // we do not need to remove it
1233 removeTabFromContentView(currentTab);
1234 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001235 mTabControl.setCurrentTab(tab);
1236 attachTabToContentView(tab);
Grace Klobaeb6eef42009-09-15 17:56:32 -07001237 resetTitleIconAndProgress();
1238 updateLockIconToLatest();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001239 return true;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001240 }
1241
Grace Kloba22ac16e2009-10-07 18:00:23 -07001242 /* package */ Tab openTabToHomePage() {
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001243 return openTabAndShow(mSettings.getHomePage(), false, null);
1244 }
1245
Leon Scroggins1f005d32009-08-10 17:36:42 -04001246 /* package */ void closeCurrentWindow() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001247 final Tab current = mTabControl.getCurrentTab();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001248 if (mTabControl.getTabCount() == 1) {
Leon Scroggins30444232009-09-04 18:36:20 -04001249 // This is the last tab. Open a new one, with the home
1250 // page and close the current one.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001251 openTabToHomePage();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001252 closeTab(current);
Leon Scroggins160a7e72009-08-14 18:28:01 -04001253 return;
1254 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07001255 final Tab parent = current.getParentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04001256 int indexToShow = -1;
1257 if (parent != null) {
1258 indexToShow = mTabControl.getTabIndex(parent);
1259 } else {
Leon Scroggins160a7e72009-08-14 18:28:01 -04001260 final int currentIndex = mTabControl.getCurrentIndex();
1261 // Try to move to the tab to the right
1262 indexToShow = currentIndex + 1;
1263 if (indexToShow > mTabControl.getTabCount() - 1) {
1264 // Try to move to the tab to the left
1265 indexToShow = currentIndex - 1;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001266 }
1267 }
Leon Scroggins160a7e72009-08-14 18:28:01 -04001268 if (switchToTab(indexToShow)) {
1269 // Close window
1270 closeTab(current);
1271 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001272 }
1273
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001274 private ActiveTabsPage mActiveTabsPage;
1275
1276 /**
1277 * Remove the active tabs page.
1278 * @param needToAttach If true, the active tabs page did not attach a tab
1279 * to the content view, so we need to do that here.
1280 */
1281 /* package */ void removeActiveTabPage(boolean needToAttach) {
1282 mContentView.removeView(mActiveTabsPage);
1283 mActiveTabsPage = null;
1284 mMenuState = R.id.MAIN_MENU;
1285 if (needToAttach) {
1286 attachTabToContentView(mTabControl.getCurrentTab());
1287 }
1288 getTopWindow().requestFocus();
1289 }
1290
Cary Clark2c326e62010-08-19 18:40:57 -04001291 private WebView showDialog(WebDialog dialog) {
Cary Clark2c326e62010-08-19 18:40:57 -04001292 Tab tab = mTabControl.getCurrentTab();
1293 if (tab.getSubWebView() == null) {
1294 // If the find or select is being performed on the main webview,
1295 // remove the embedded title bar.
1296 WebView mainView = tab.getWebView();
1297 if (mainView != null) {
1298 mainView.setEmbeddedTitleBar(null);
1299 }
1300 }
1301 hideFakeTitleBar();
1302 mMenuState = EMPTY_MENU;
1303 return tab.showDialog(dialog);
1304 }
1305
The Android Open Source Project0c908882009-03-03 19:32:16 -08001306 @Override
1307 public boolean onOptionsItemSelected(MenuItem item) {
1308 if (!mCanChord) {
1309 // The user has already fired a shortcut with this hold down of the
1310 // menu key.
1311 return false;
1312 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001313 if (null == getTopWindow()) {
Leon Scroggins0d7ae0e2009-06-05 11:04:45 -04001314 return false;
1315 }
Grace Kloba6ee9c492009-07-13 10:04:34 -07001316 if (mMenuIsDown) {
1317 // The shortcut action consumes the MENU. Even if it is still down,
1318 // it won't trigger the next shortcut action. In the case of the
1319 // shortcut action triggering a new activity, like Bookmarks, we
1320 // won't get onKeyUp for MENU. So it is important to reset it here.
1321 mMenuIsDown = false;
1322 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001323 switch (item.getItemId()) {
1324 // -- Main menu
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001325 case R.id.new_tab_menu_id:
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001326 openTabToHomePage();
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001327 break;
1328
Leon Scroggins64b80f32009-08-07 12:03:34 -04001329 case R.id.goto_menu_id:
Leon Scroggins8ad29922010-02-16 12:33:55 -05001330 editUrl();
Leon Scrogginsb3a5bed2009-09-28 11:21:56 -04001331 break;
1332
1333 case R.id.bookmarks_menu_id:
Leon Scroggins30444232009-09-04 18:36:20 -04001334 bookmarksOrHistoryPicker(false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001335 break;
1336
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001337 case R.id.active_tabs_menu_id:
1338 mActiveTabsPage = new ActiveTabsPage(this, mTabControl);
1339 removeTabFromContentView(mTabControl.getCurrentTab());
Leon Scroggins43de6162009-09-14 19:59:58 -04001340 hideFakeTitleBar();
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001341 mContentView.addView(mActiveTabsPage, COVER_SCREEN_PARAMS);
1342 mActiveTabsPage.requestFocus();
1343 mMenuState = EMPTY_MENU;
1344 break;
1345
Leon Scroggins1f005d32009-08-10 17:36:42 -04001346 case R.id.add_bookmark_menu_id:
1347 Intent i = new Intent(BrowserActivity.this,
1348 AddBookmarkPage.class);
1349 WebView w = getTopWindow();
1350 i.putExtra("url", w.getUrl());
1351 i.putExtra("title", w.getTitle());
Grace Kloba83cdb2c2009-09-16 00:48:57 -07001352 i.putExtra("touch_icon_url", w.getTouchIconUrl());
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01001353 i.putExtra("thumbnail", createScreenshot(w));
Leon Scroggins1f005d32009-08-10 17:36:42 -04001354 startActivity(i);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001355 break;
1356
1357 case R.id.stop_reload_menu_id:
1358 if (mInLoad) {
1359 stopLoading();
1360 } else {
1361 getTopWindow().reload();
1362 }
1363 break;
1364
1365 case R.id.back_menu_id:
1366 getTopWindow().goBack();
1367 break;
1368
1369 case R.id.forward_menu_id:
1370 getTopWindow().goForward();
1371 break;
1372
1373 case R.id.close_menu_id:
1374 // Close the subwindow if it exists.
1375 if (mTabControl.getCurrentSubWindow() != null) {
1376 dismissSubWindow(mTabControl.getCurrentTab());
1377 break;
1378 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001379 closeCurrentWindow();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001380 break;
1381
1382 case R.id.homepage_menu_id:
Grace Kloba22ac16e2009-10-07 18:00:23 -07001383 Tab current = mTabControl.getCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001384 if (current != null) {
1385 dismissSubWindow(current);
Leon Scroggins92472e82010-02-17 16:32:28 -05001386 loadUrl(current.getWebView(), mSettings.getHomePage());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001387 }
1388 break;
1389
1390 case R.id.preferences_menu_id:
1391 Intent intent = new Intent(this,
1392 BrowserPreferencesPage.class);
Leon Scrogginsd5304942009-12-10 16:11:39 -05001393 intent.putExtra(BrowserPreferencesPage.CURRENT_PAGE,
1394 getTopWindow().getUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001395 startActivityForResult(intent, PREFERENCES_PAGE);
1396 break;
1397
1398 case R.id.find_menu_id:
Cary Clark2c326e62010-08-19 18:40:57 -04001399 showFindDialog();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001400 break;
1401
1402 case R.id.select_text_id:
Cary Clark5feb8ad2010-09-21 14:28:49 -04001403 if (true) {
1404 Tab currentTab = mTabControl.getCurrentTab();
1405 if (currentTab != null) {
1406 currentTab.getWebView().setUpSelect();
1407 }
1408 } else {
1409 showSelectDialog();
1410 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001411 break;
Cary Clark2c326e62010-08-19 18:40:57 -04001412
The Android Open Source Project0c908882009-03-03 19:32:16 -08001413 case R.id.page_info_menu_id:
1414 showPageInfo(mTabControl.getCurrentTab(), false);
1415 break;
1416
1417 case R.id.classic_history_menu_id:
Leon Scroggins30444232009-09-04 18:36:20 -04001418 bookmarksOrHistoryPicker(true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001419 break;
1420
Leon Scroggins96afcb12009-12-10 12:35:56 -05001421 case R.id.title_bar_share_page_url:
The Android Open Source Project0c908882009-03-03 19:32:16 -08001422 case R.id.share_page_menu_id:
Leon Scroggins96afcb12009-12-10 12:35:56 -05001423 Tab currentTab = mTabControl.getCurrentTab();
1424 if (null == currentTab) {
1425 mCanChord = false;
1426 return false;
1427 }
1428 currentTab.populatePickerData();
1429 sharePage(this, currentTab.getTitle(),
1430 currentTab.getUrl(), currentTab.getFavicon(),
1431 createScreenshot(currentTab.getWebView()));
The Android Open Source Project0c908882009-03-03 19:32:16 -08001432 break;
1433
1434 case R.id.dump_nav_menu_id:
1435 getTopWindow().debugDump();
1436 break;
1437
Andrei Popescu7a8b88b2010-02-02 00:30:38 +00001438 case R.id.dump_counters_menu_id:
1439 getTopWindow().dumpV8Counters();
1440 break;
1441
The Android Open Source Project0c908882009-03-03 19:32:16 -08001442 case R.id.zoom_in_menu_id:
1443 getTopWindow().zoomIn();
1444 break;
1445
1446 case R.id.zoom_out_menu_id:
1447 getTopWindow().zoomOut();
1448 break;
1449
1450 case R.id.view_downloads_menu_id:
Leon Scroggins IIIa682a3c2010-09-27 12:32:40 -04001451 viewDownloads();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001452 break;
1453
The Android Open Source Project0c908882009-03-03 19:32:16 -08001454 case R.id.window_one_menu_id:
1455 case R.id.window_two_menu_id:
1456 case R.id.window_three_menu_id:
1457 case R.id.window_four_menu_id:
1458 case R.id.window_five_menu_id:
1459 case R.id.window_six_menu_id:
1460 case R.id.window_seven_menu_id:
1461 case R.id.window_eight_menu_id:
1462 {
1463 int menuid = item.getItemId();
1464 for (int id = 0; id < WINDOW_SHORTCUT_ID_ARRAY.length; id++) {
1465 if (WINDOW_SHORTCUT_ID_ARRAY[id] == menuid) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001466 Tab desiredTab = mTabControl.getTab(id);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001467 if (desiredTab != null &&
1468 desiredTab != mTabControl.getCurrentTab()) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001469 switchToTab(id);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001470 }
1471 break;
1472 }
1473 }
1474 }
1475 break;
1476
1477 default:
1478 if (!super.onOptionsItemSelected(item)) {
1479 return false;
1480 }
1481 // Otherwise fall through.
1482 }
1483 mCanChord = false;
1484 return true;
1485 }
1486
Cary Clark2c326e62010-08-19 18:40:57 -04001487 private boolean dialogIsUp() {
1488 return null != mFindDialog && mFindDialog.isVisible() ||
1489 null != mSelectDialog && mSelectDialog.isVisible();
1490 }
1491
1492 private boolean closeDialog(WebDialog dialog) {
1493 if (null == dialog || !dialog.isVisible()) return false;
1494 Tab currentTab = mTabControl.getCurrentTab();
1495 currentTab.closeDialog(dialog);
1496 dialog.dismiss();
1497 return true;
1498 }
1499
1500 /*
1501 * Remove the find dialog or select dialog.
1502 */
1503 public void closeDialogs() {
1504 if (!(closeDialog(mFindDialog) || closeDialog(mSelectDialog))) return;
1505 // If the Find was being performed in the main WebView, replace the
1506 // embedded title bar.
1507 Tab currentTab = mTabControl.getCurrentTab();
1508 if (currentTab.getSubWebView() == null) {
1509 WebView mainView = currentTab.getWebView();
1510 if (mainView != null) {
1511 mainView.setEmbeddedTitleBar(mTitleBar);
1512 }
1513 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001514 mMenuState = R.id.MAIN_MENU;
Cary Clark2c326e62010-08-19 18:40:57 -04001515 if (mInLoad) {
1516 // The title bar was hidden, because otherwise it would cover up the
1517 // find or select dialog. Now that the dialog has been removed,
1518 // show the fake title bar once again.
1519 showFakeTitleBar();
1520 }
1521 }
1522
1523 public void showFindDialog() {
1524 if (null == mFindDialog) {
1525 mFindDialog = new FindDialog(this);
1526 }
1527 showDialog(mFindDialog).setFindIsUp(true);
1528 }
1529
1530 public void setFindDialogText(String text) {
1531 mFindDialog.setText(text);
1532 }
1533
1534 public void showSelectDialog() {
1535 if (null == mSelectDialog) {
1536 mSelectDialog = new SelectDialog(this);
1537 }
1538 showDialog(mSelectDialog).setUpSelect();
1539 mSelectDialog.hideSoftInput();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001540 }
1541
Grace Kloba22ac16e2009-10-07 18:00:23 -07001542 @Override
1543 public boolean onPrepareOptionsMenu(Menu menu) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001544 // This happens when the user begins to hold down the menu key, so
1545 // allow them to chord to get a shortcut.
1546 mCanChord = true;
1547 // Note: setVisible will decide whether an item is visible; while
1548 // setEnabled() will decide whether an item is enabled, which also means
1549 // whether the matching shortcut key will function.
1550 super.onPrepareOptionsMenu(menu);
1551 switch (mMenuState) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001552 case EMPTY_MENU:
1553 if (mCurrentMenuState != mMenuState) {
1554 menu.setGroupVisible(R.id.MAIN_MENU, false);
1555 menu.setGroupEnabled(R.id.MAIN_MENU, false);
1556 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001557 }
1558 break;
1559 default:
1560 if (mCurrentMenuState != mMenuState) {
1561 menu.setGroupVisible(R.id.MAIN_MENU, true);
1562 menu.setGroupEnabled(R.id.MAIN_MENU, true);
1563 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001564 }
1565 final WebView w = getTopWindow();
1566 boolean canGoBack = false;
1567 boolean canGoForward = false;
1568 boolean isHome = false;
1569 if (w != null) {
1570 canGoBack = w.canGoBack();
1571 canGoForward = w.canGoForward();
1572 isHome = mSettings.getHomePage().equals(w.getUrl());
1573 }
1574 final MenuItem back = menu.findItem(R.id.back_menu_id);
1575 back.setEnabled(canGoBack);
1576
1577 final MenuItem home = menu.findItem(R.id.homepage_menu_id);
1578 home.setEnabled(!isHome);
1579
1580 menu.findItem(R.id.forward_menu_id)
1581 .setEnabled(canGoForward);
1582
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001583 menu.findItem(R.id.new_tab_menu_id).setEnabled(
Grace Kloba22ac16e2009-10-07 18:00:23 -07001584 mTabControl.canCreateNewTab());
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001585
The Android Open Source Project0c908882009-03-03 19:32:16 -08001586 // decide whether to show the share link option
1587 PackageManager pm = getPackageManager();
1588 Intent send = new Intent(Intent.ACTION_SEND);
1589 send.setType("text/plain");
1590 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1591 menu.findItem(R.id.share_page_menu_id).setVisible(ri != null);
1592
The Android Open Source Project0c908882009-03-03 19:32:16 -08001593 boolean isNavDump = mSettings.isNavDump();
1594 final MenuItem nav = menu.findItem(R.id.dump_nav_menu_id);
1595 nav.setVisible(isNavDump);
1596 nav.setEnabled(isNavDump);
Andrei Popescu7a8b88b2010-02-02 00:30:38 +00001597
1598 boolean showDebugSettings = mSettings.showDebugSettings();
1599 final MenuItem counter = menu.findItem(R.id.dump_counters_menu_id);
1600 counter.setVisible(showDebugSettings);
1601 counter.setEnabled(showDebugSettings);
1602
The Android Open Source Project0c908882009-03-03 19:32:16 -08001603 break;
1604 }
1605 mCurrentMenuState = mMenuState;
1606 return true;
1607 }
1608
1609 @Override
1610 public void onCreateContextMenu(ContextMenu menu, View v,
1611 ContextMenuInfo menuInfo) {
Leon Scroggins4e9f89b2010-02-22 16:54:14 -05001612 if (v instanceof TitleBar) {
1613 return;
1614 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001615 WebView webview = (WebView) v;
1616 WebView.HitTestResult result = webview.getHitTestResult();
1617 if (result == null) {
1618 return;
1619 }
1620
1621 int type = result.getType();
1622 if (type == WebView.HitTestResult.UNKNOWN_TYPE) {
1623 Log.w(LOGTAG,
1624 "We should not show context menu when nothing is touched");
1625 return;
1626 }
1627 if (type == WebView.HitTestResult.EDIT_TEXT_TYPE) {
1628 // let TextView handles context menu
1629 return;
1630 }
1631
1632 // Note, http://b/issue?id=1106666 is requesting that
1633 // an inflated menu can be used again. This is not available
1634 // yet, so inflate each time (yuk!)
1635 MenuInflater inflater = getMenuInflater();
1636 inflater.inflate(R.menu.browsercontext, menu);
1637
1638 // Show the correct menu group
1639 String extra = result.getExtra();
1640 menu.setGroupVisible(R.id.PHONE_MENU,
1641 type == WebView.HitTestResult.PHONE_TYPE);
1642 menu.setGroupVisible(R.id.EMAIL_MENU,
1643 type == WebView.HitTestResult.EMAIL_TYPE);
1644 menu.setGroupVisible(R.id.GEO_MENU,
1645 type == WebView.HitTestResult.GEO_TYPE);
1646 menu.setGroupVisible(R.id.IMAGE_MENU,
1647 type == WebView.HitTestResult.IMAGE_TYPE
1648 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1649 menu.setGroupVisible(R.id.ANCHOR_MENU,
1650 type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1651 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1652
1653 // Setup custom handling depending on the type
1654 switch (type) {
1655 case WebView.HitTestResult.PHONE_TYPE:
1656 menu.setHeaderTitle(Uri.decode(extra));
1657 menu.findItem(R.id.dial_context_menu_id).setIntent(
1658 new Intent(Intent.ACTION_VIEW, Uri
1659 .parse(WebView.SCHEME_TEL + extra)));
1660 Intent addIntent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
1661 addIntent.putExtra(Insert.PHONE, Uri.decode(extra));
Cary Clark5e335a32009-09-22 14:53:11 -04001662 addIntent.setType(ContactsContract.Contacts.CONTENT_ITEM_TYPE);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001663 menu.findItem(R.id.add_contact_context_menu_id).setIntent(
1664 addIntent);
1665 menu.findItem(R.id.copy_phone_context_menu_id).setOnMenuItemClickListener(
1666 new Copy(extra));
1667 break;
1668
1669 case WebView.HitTestResult.EMAIL_TYPE:
1670 menu.setHeaderTitle(extra);
1671 menu.findItem(R.id.email_context_menu_id).setIntent(
1672 new Intent(Intent.ACTION_VIEW, Uri
1673 .parse(WebView.SCHEME_MAILTO + extra)));
1674 menu.findItem(R.id.copy_mail_context_menu_id).setOnMenuItemClickListener(
1675 new Copy(extra));
1676 break;
1677
1678 case WebView.HitTestResult.GEO_TYPE:
1679 menu.setHeaderTitle(extra);
1680 menu.findItem(R.id.map_context_menu_id).setIntent(
1681 new Intent(Intent.ACTION_VIEW, Uri
1682 .parse(WebView.SCHEME_GEO
1683 + URLEncoder.encode(extra))));
1684 menu.findItem(R.id.copy_geo_context_menu_id).setOnMenuItemClickListener(
1685 new Copy(extra));
1686 break;
1687
1688 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1689 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
1690 TextView titleView = (TextView) LayoutInflater.from(this)
1691 .inflate(android.R.layout.browser_link_context_header,
1692 null);
1693 titleView.setText(extra);
1694 menu.setHeaderView(titleView);
1695 // decide whether to show the open link in new tab option
1696 menu.findItem(R.id.open_newtab_context_menu_id).setVisible(
Grace Kloba22ac16e2009-10-07 18:00:23 -07001697 mTabControl.canCreateNewTab());
Ben Murdochde353622009-10-12 10:29:00 +01001698 menu.findItem(R.id.bookmark_context_menu_id).setVisible(
1699 Bookmarks.urlHasAcceptableScheme(extra));
The Android Open Source Project0c908882009-03-03 19:32:16 -08001700 PackageManager pm = getPackageManager();
1701 Intent send = new Intent(Intent.ACTION_SEND);
1702 send.setType("text/plain");
1703 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1704 menu.findItem(R.id.share_link_context_menu_id).setVisible(ri != null);
1705 if (type == WebView.HitTestResult.SRC_ANCHOR_TYPE) {
1706 break;
1707 }
1708 // otherwise fall through to handle image part
1709 case WebView.HitTestResult.IMAGE_TYPE:
1710 if (type == WebView.HitTestResult.IMAGE_TYPE) {
1711 menu.setHeaderTitle(extra);
1712 }
1713 menu.findItem(R.id.view_image_context_menu_id).setIntent(
1714 new Intent(Intent.ACTION_VIEW, Uri.parse(extra)));
1715 menu.findItem(R.id.download_context_menu_id).
1716 setOnMenuItemClickListener(new Download(extra));
Ben Murdoch4f75ba22009-10-27 11:48:28 +00001717 menu.findItem(R.id.set_wallpaper_context_menu_id).
1718 setOnMenuItemClickListener(new SetAsWallpaper(extra));
The Android Open Source Project0c908882009-03-03 19:32:16 -08001719 break;
1720
1721 default:
1722 Log.w(LOGTAG, "We should not get here.");
1723 break;
1724 }
Leon Scrogginsb2b19f52009-10-09 16:10:00 -04001725 hideFakeTitleBar();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001726 }
1727
The Android Open Source Project0c908882009-03-03 19:32:16 -08001728 // Attach the given tab to the content view.
Grace Klobac928c302009-09-17 11:51:21 -07001729 // this should only be called for the current tab.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001730 private void attachTabToContentView(Tab t) {
Steve Block2bc69912009-07-30 14:45:13 +01001731 // Attach the container that contains the main WebView and any other UI
1732 // associated with the tab.
Patrick Scottd0119532009-09-17 08:00:31 -04001733 t.attachTabToContentView(mContentView);
Ben Murdochbff2d602009-07-01 20:19:05 +01001734
1735 if (mShouldShowErrorConsole) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001736 ErrorConsoleView errorConsole = t.getErrorConsole(true);
Ben Murdochbff2d602009-07-01 20:19:05 +01001737 if (errorConsole.numberOfErrors() == 0) {
1738 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
1739 } else {
1740 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
1741 }
1742
1743 mErrorConsoleContainer.addView(errorConsole,
Romain Guy15b8ec62010-01-08 15:06:43 -08001744 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
Ben Murdochbff2d602009-07-01 20:19:05 +01001745 ViewGroup.LayoutParams.WRAP_CONTENT));
1746 }
1747
Leon Scroggins39ab28e2009-09-02 21:20:30 -04001748 WebView view = t.getWebView();
Leon Scroggins55a5bc22009-09-04 17:00:08 -04001749 view.setEmbeddedTitleBar(mTitleBar);
Leon Scroggins58d56c62010-01-28 15:12:40 -05001750 if (t.isInVoiceSearchMode()) {
1751 showVoiceTitleBar(t.getVoiceDisplayTitle());
1752 } else {
1753 revertVoiceTitleBar();
1754 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001755 // Request focus on the top window.
1756 t.getTopWindow().requestFocus();
1757 }
1758
1759 // Attach a sub window to the main WebView of the given tab.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001760 void attachSubWindow(Tab t) {
Patrick Scottd0119532009-09-17 08:00:31 -04001761 t.attachSubWindow(mContentView);
1762 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001763 }
1764
1765 // Remove the given tab from the content view.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001766 private void removeTabFromContentView(Tab t) {
Steve Block2bc69912009-07-30 14:45:13 +01001767 // Remove the container that contains the main WebView.
Patrick Scottd0119532009-09-17 08:00:31 -04001768 t.removeTabFromContentView(mContentView);
Ben Murdochbff2d602009-07-01 20:19:05 +01001769
Grace Kloba22ac16e2009-10-07 18:00:23 -07001770 ErrorConsoleView errorConsole = t.getErrorConsole(false);
1771 if (errorConsole != null) {
1772 mErrorConsoleContainer.removeView(errorConsole);
Ben Murdochbff2d602009-07-01 20:19:05 +01001773 }
1774
Leon Scroggins39ab28e2009-09-02 21:20:30 -04001775 WebView view = t.getWebView();
Leon Scrogginsbb85b902009-09-14 19:27:20 -04001776 if (view != null) {
1777 view.setEmbeddedTitleBar(null);
1778 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001779 }
1780
1781 // Remove the sub window if it exists. Also called by TabControl when the
1782 // user clicks the 'X' to dismiss a sub window.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001783 /* package */ void dismissSubWindow(Tab t) {
Patrick Scottd0119532009-09-17 08:00:31 -04001784 t.removeSubWindow(mContentView);
Grace Kloba22ac16e2009-10-07 18:00:23 -07001785 // dismiss the subwindow. This will destroy the WebView.
1786 t.dismissSubWindow();
Patrick Scottd0119532009-09-17 08:00:31 -04001787 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001788 }
1789
Leon Scroggins1f005d32009-08-10 17:36:42 -04001790 // A wrapper function of {@link #openTabAndShow(UrlData, boolean, String)}
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07001791 // that accepts url as string.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001792 private Tab openTabAndShow(String url, boolean closeOnExit, String appId) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001793 return openTabAndShow(new UrlData(url), closeOnExit, appId);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001794 }
1795
1796 // This method does a ton of stuff. It will attempt to create a new tab
1797 // if we haven't reached MAX_TABS. Otherwise it uses the current tab. If
Leon Scroggins1f005d32009-08-10 17:36:42 -04001798 // url isn't null, it will load the given url.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001799 /* package */Tab openTabAndShow(UrlData urlData, boolean closeOnExit,
1800 String appId) {
1801 final Tab currentTab = mTabControl.getCurrentTab();
1802 if (mTabControl.canCreateNewTab()) {
1803 final Tab tab = mTabControl.createNewTab(closeOnExit, appId,
1804 urlData.mUrl);
Leon Scroggins1f005d32009-08-10 17:36:42 -04001805 WebView webview = tab.getWebView();
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001806 // If the last tab was removed from the active tabs page, currentTab
1807 // will be null.
1808 if (currentTab != null) {
1809 removeTabFromContentView(currentTab);
1810 }
Patrick Scott8bbd69f2009-08-14 13:35:53 -04001811 // We must set the new tab as the current tab to reflect the old
1812 // animation behavior.
1813 mTabControl.setCurrentTab(tab);
Grace Klobaeb6eef42009-09-15 17:56:32 -07001814 attachTabToContentView(tab);
Leon Scroggins160a7e72009-08-14 18:28:01 -04001815 if (!urlData.isEmpty()) {
Patrick Scott9d53da02010-02-19 10:19:01 -05001816 loadUrlDataIn(tab, urlData);
Leon Scroggins1f005d32009-08-10 17:36:42 -04001817 }
1818 return tab;
1819 } else {
1820 // Get rid of the subwindow if it exists
1821 dismissSubWindow(currentTab);
1822 if (!urlData.isEmpty()) {
1823 // Load the given url.
Patrick Scott9d53da02010-02-19 10:19:01 -05001824 loadUrlDataIn(currentTab, urlData);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001825 }
Leon Scroggins58d56c62010-01-28 15:12:40 -05001826 return currentTab;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001827 }
1828 }
1829
Grace Kloba22ac16e2009-10-07 18:00:23 -07001830 private Tab openTab(String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001831 if (mSettings.openInBackground()) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001832 Tab t = mTabControl.createNewTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001833 if (t != null) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001834 WebView view = t.getWebView();
Leon Scroggins92472e82010-02-17 16:32:28 -05001835 loadUrl(view, url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001836 }
Grace Klobac9181842009-04-14 08:53:22 -07001837 return t;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001838 } else {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001839 return openTabAndShow(url, false, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001840 }
1841 }
1842
1843 private class Copy implements OnMenuItemClickListener {
1844 private CharSequence mText;
1845
1846 public boolean onMenuItemClick(MenuItem item) {
1847 copy(mText);
1848 return true;
1849 }
1850
1851 public Copy(CharSequence toCopy) {
1852 mText = toCopy;
1853 }
1854 }
1855
1856 private class Download implements OnMenuItemClickListener {
1857 private String mText;
1858
1859 public boolean onMenuItemClick(MenuItem item) {
1860 onDownloadStartNoStream(mText, null, null, null, -1);
1861 return true;
1862 }
1863
1864 public Download(String toDownload) {
1865 mText = toDownload;
1866 }
1867 }
1868
Ben Murdoch4f75ba22009-10-27 11:48:28 +00001869 private class SetAsWallpaper extends Thread implements
1870 OnMenuItemClickListener, DialogInterface.OnCancelListener {
1871 private URL mUrl;
1872 private ProgressDialog mWallpaperProgress;
1873 private boolean mCanceled = false;
1874
1875 public SetAsWallpaper(String url) {
1876 try {
1877 mUrl = new URL(url);
1878 } catch (MalformedURLException e) {
1879 mUrl = null;
1880 }
1881 }
1882
1883 public void onCancel(DialogInterface dialog) {
1884 mCanceled = true;
1885 }
1886
1887 public boolean onMenuItemClick(MenuItem item) {
1888 if (mUrl != null) {
1889 // The user may have tried to set a image with a large file size as their
1890 // background so it may take a few moments to perform the operation. Display
1891 // a progress spinner while it is working.
1892 mWallpaperProgress = new ProgressDialog(BrowserActivity.this);
1893 mWallpaperProgress.setIndeterminate(true);
1894 mWallpaperProgress.setMessage(getText(R.string.progress_dialog_setting_wallpaper));
1895 mWallpaperProgress.setCancelable(true);
1896 mWallpaperProgress.setOnCancelListener(this);
1897 mWallpaperProgress.show();
1898 start();
1899 }
1900 return true;
1901 }
1902
1903 public void run() {
1904 Drawable oldWallpaper = BrowserActivity.this.getWallpaper();
1905 try {
1906 // TODO: This will cause the resource to be downloaded again, when we
1907 // should in most cases be able to grab it from the cache. To fix this
1908 // we should query WebCore to see if we can access a cached version and
1909 // instead open an input stream on that. This pattern could also be used
1910 // in the download manager where the same problem exists.
1911 InputStream inputstream = mUrl.openStream();
1912 if (inputstream != null) {
1913 setWallpaper(inputstream);
1914 }
1915 } catch (IOException e) {
1916 Log.e(LOGTAG, "Unable to set new wallpaper");
1917 // Act as though the user canceled the operation so we try to
1918 // restore the old wallpaper.
1919 mCanceled = true;
1920 }
1921
1922 if (mCanceled) {
1923 // Restore the old wallpaper if the user cancelled whilst we were setting
1924 // the new wallpaper.
1925 int width = oldWallpaper.getIntrinsicWidth();
1926 int height = oldWallpaper.getIntrinsicHeight();
1927 Bitmap bm = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
1928 Canvas canvas = new Canvas(bm);
1929 oldWallpaper.setBounds(0, 0, width, height);
1930 oldWallpaper.draw(canvas);
1931 try {
1932 setWallpaper(bm);
1933 } catch (IOException e) {
1934 Log.e(LOGTAG, "Unable to restore old wallpaper.");
1935 }
1936 mCanceled = false;
1937 }
1938
1939 if (mWallpaperProgress.isShowing()) {
1940 mWallpaperProgress.dismiss();
1941 }
1942 }
1943 }
1944
The Android Open Source Project0c908882009-03-03 19:32:16 -08001945 private void copy(CharSequence text) {
1946 try {
1947 IClipboard clip = IClipboard.Stub.asInterface(ServiceManager.getService("clipboard"));
1948 if (clip != null) {
1949 clip.setClipboardText(text);
1950 }
1951 } catch (android.os.RemoteException e) {
1952 Log.e(LOGTAG, "Copy failed", e);
1953 }
1954 }
1955
1956 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08001957 * Resets the browser title-view to whatever it must be
1958 * (for example, if we had a loading error)
1959 * When we have a new page, we call resetTitle, when we
1960 * have to reset the titlebar to whatever it used to be
1961 * (for example, if the user chose to stop loading), we
1962 * call resetTitleAndRevertLockIcon.
1963 */
1964 /* package */ void resetTitleAndRevertLockIcon() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001965 mTabControl.getCurrentTab().revertLockIcon();
1966 updateLockIconToLatest();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001967 resetTitleIconAndProgress();
1968 }
1969
1970 /**
1971 * Reset the title, favicon, and progress.
1972 */
1973 private void resetTitleIconAndProgress() {
1974 WebView current = mTabControl.getCurrentWebView();
1975 if (current == null) {
1976 return;
1977 }
1978 resetTitleAndIcon(current);
1979 int progress = current.getProgress();
Grace Kloba22ac16e2009-10-07 18:00:23 -07001980 current.getWebChromeClient().onProgressChanged(current, progress);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001981 }
1982
1983 // Reset the title and the icon based on the given item.
1984 private void resetTitleAndIcon(WebView view) {
1985 WebHistoryItem item = view.copyBackForwardList().getCurrentItem();
1986 if (item != null) {
Leon Scroggins68579392009-09-15 15:31:54 -04001987 setUrlTitle(item.getUrl(), item.getTitle());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001988 setFavicon(item.getFavicon());
1989 } else {
Leon Scroggins68579392009-09-15 15:31:54 -04001990 setUrlTitle(null, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001991 setFavicon(null);
1992 }
1993 }
1994
1995 /**
1996 * Sets a title composed of the URL and the title string.
1997 * @param url The URL of the site being loaded.
1998 * @param title The title of the site being loaded.
1999 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07002000 void setUrlTitle(String url, String title) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002001 mUrl = url;
2002 mTitle = title;
2003
Leon Scroggins58d56c62010-01-28 15:12:40 -05002004 // If we are in voice search mode, the title has already been set.
2005 if (mTabControl.getCurrentTab().isInVoiceSearchMode()) return;
2006 mTitleBar.setDisplayTitle(url);
2007 mFakeTitleBar.setDisplayTitle(url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002008 }
2009
2010 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08002011 * @param url The URL to build a title version of the URL from.
2012 * @return The title version of the URL or null if fails.
2013 * The title version of the URL can be either the URL hostname,
2014 * or the hostname with an "https://" prefix (for secure URLs),
2015 * or an empty string if, for example, the URL in question is a
2016 * file:// URL with no hostname.
2017 */
Leon Scroggins32e14a62009-06-11 10:26:34 -04002018 /* package */ static String buildTitleUrl(String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002019 String titleUrl = null;
2020
2021 if (url != null) {
2022 try {
2023 // parse the url string
2024 URL urlObj = new URL(url);
2025 if (urlObj != null) {
2026 titleUrl = "";
2027
2028 String protocol = urlObj.getProtocol();
2029 String host = urlObj.getHost();
2030
2031 if (host != null && 0 < host.length()) {
2032 titleUrl = host;
2033 if (protocol != null) {
2034 // if a secure site, add an "https://" prefix!
2035 if (protocol.equalsIgnoreCase("https")) {
2036 titleUrl = protocol + "://" + host;
2037 }
2038 }
2039 }
2040 }
2041 } catch (MalformedURLException e) {}
2042 }
2043
2044 return titleUrl;
2045 }
2046
2047 // Set the favicon in the title bar.
Grace Kloba22ac16e2009-10-07 18:00:23 -07002048 void setFavicon(Bitmap icon) {
Leon Scroggins68579392009-09-15 15:31:54 -04002049 mTitleBar.setFavicon(icon);
Leon Scrogginsfe87bd32009-10-06 10:10:00 -04002050 mFakeTitleBar.setFavicon(icon);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002051 }
2052
2053 /**
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002054 * Close the tab, remove its associated title bar, and adjust mTabControl's
2055 * current tab to a valid value.
Leon Scroggins1f005d32009-08-10 17:36:42 -04002056 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07002057 /* package */ void closeTab(Tab t) {
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002058 int currentIndex = mTabControl.getCurrentIndex();
2059 int removeIndex = mTabControl.getTabIndex(t);
Leon Scroggins1f005d32009-08-10 17:36:42 -04002060 mTabControl.removeTab(t);
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002061 if (currentIndex >= removeIndex && currentIndex != 0) {
2062 currentIndex--;
2063 }
2064 mTabControl.setCurrentTab(mTabControl.getTab(currentIndex));
Andrei Popescua5bf1de2009-09-23 16:39:23 +01002065 resetTitleIconAndProgress();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002066 }
2067
Leon Scrogginsdcc5eeb2010-02-23 17:26:37 -05002068 /* package */ void goBackOnePageOrQuit() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002069 Tab current = mTabControl.getCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002070 if (current == null) {
2071 /*
2072 * Instead of finishing the activity, simply push this to the back
2073 * of the stack and let ActivityManager to choose the foreground
2074 * activity. As BrowserActivity is singleTask, it will be always the
2075 * root of the task. So we can use either true or false for
2076 * moveTaskToBack().
2077 */
2078 moveTaskToBack(true);
Grace Kloba00d85e72009-09-23 18:50:05 -07002079 return;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002080 }
2081 WebView w = current.getWebView();
2082 if (w.canGoBack()) {
2083 w.goBack();
2084 } else {
2085 // Check to see if we are closing a window that was created by
2086 // another window. If so, we switch back to that window.
Grace Kloba22ac16e2009-10-07 18:00:23 -07002087 Tab parent = current.getParentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002088 if (parent != null) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04002089 switchToTab(mTabControl.getTabIndex(parent));
2090 // Now we close the other tab
2091 closeTab(current);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002092 } else {
2093 if (current.closeOnExit()) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002094 // force the tab's inLoad() to be false as we are going to
2095 // either finish the activity or remove the tab. This will
2096 // ensure pauseWebViewTimers() taking action.
2097 mTabControl.getCurrentTab().clearInLoad();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002098 if (mTabControl.getTabCount() == 1) {
2099 finish();
2100 return;
2101 }
Mike Reed7bfa63b2009-05-28 11:08:32 -04002102 // call pauseWebViewTimers() now, we won't be able to call
2103 // it in onPause() as the WebView won't be valid.
Grace Klobaec1b5ad2009-08-18 08:42:32 -07002104 // Temporarily change mActivityInPause to be true as
2105 // pauseWebViewTimers() will do nothing if mActivityInPause
2106 // is false.
Grace Kloba918e1d72009-08-13 14:55:06 -07002107 boolean savedState = mActivityInPause;
2108 if (savedState) {
Grace Klobaec1b5ad2009-08-18 08:42:32 -07002109 Log.e(LOGTAG, "BrowserActivity is already paused "
2110 + "while handing goBackOnePageOrQuit.");
Grace Kloba918e1d72009-08-13 14:55:06 -07002111 }
2112 mActivityInPause = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -04002113 pauseWebViewTimers();
Grace Kloba918e1d72009-08-13 14:55:06 -07002114 mActivityInPause = savedState;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002115 removeTabFromContentView(current);
2116 mTabControl.removeTab(current);
2117 }
2118 /*
2119 * Instead of finishing the activity, simply push this to the back
2120 * of the stack and let ActivityManager to choose the foreground
2121 * activity. As BrowserActivity is singleTask, it will be always the
2122 * root of the task. So we can use either true or false for
2123 * moveTaskToBack().
2124 */
2125 moveTaskToBack(true);
2126 }
2127 }
2128 }
2129
Grace Kloba22ac16e2009-10-07 18:00:23 -07002130 boolean isMenuDown() {
2131 return mMenuIsDown;
2132 }
2133
Grace Kloba5942df02009-09-18 11:48:29 -07002134 @Override
2135 public boolean onKeyDown(int keyCode, KeyEvent event) {
Leon Scrogginsf65b50d2009-12-08 10:44:28 -05002136 // Even if MENU is already held down, we need to call to super to open
2137 // the IME on long press.
2138 if (KeyEvent.KEYCODE_MENU == keyCode) {
2139 mMenuIsDown = true;
2140 return super.onKeyDown(keyCode, event);
2141 }
Grace Kloba5942df02009-09-18 11:48:29 -07002142 // The default key mode is DEFAULT_KEYS_SEARCH_LOCAL. As the MENU is
2143 // still down, we don't want to trigger the search. Pretend to consume
2144 // the key and do nothing.
2145 if (mMenuIsDown) return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002146
Grace Kloba5942df02009-09-18 11:48:29 -07002147 switch(keyCode) {
Grace Kloba5942df02009-09-18 11:48:29 -07002148 case KeyEvent.KEYCODE_SPACE:
Grace Klobada0fe552009-09-22 18:17:24 -07002149 // WebView/WebTextView handle the keys in the KeyDown. As
2150 // the Activity's shortcut keys are only handled when WebView
2151 // doesn't, have to do it in onKeyDown instead of onKeyUp.
2152 if (event.isShiftPressed()) {
2153 getTopWindow().pageUp(false);
2154 } else {
2155 getTopWindow().pageDown(false);
2156 }
Grace Kloba5942df02009-09-18 11:48:29 -07002157 return true;
2158 case KeyEvent.KEYCODE_BACK:
2159 if (event.getRepeatCount() == 0) {
2160 event.startTracking();
2161 return true;
2162 } else if (mCustomView == null && mActiveTabsPage == null
2163 && event.isLongPress()) {
2164 bookmarksOrHistoryPicker(true);
2165 return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002166 }
Grace Kloba5942df02009-09-18 11:48:29 -07002167 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002168 }
Grace Kloba5942df02009-09-18 11:48:29 -07002169 return super.onKeyDown(keyCode, event);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002170 }
2171
Grace Kloba5942df02009-09-18 11:48:29 -07002172 @Override
2173 public boolean onKeyUp(int keyCode, KeyEvent event) {
2174 switch(keyCode) {
2175 case KeyEvent.KEYCODE_MENU:
2176 mMenuIsDown = false;
2177 break;
Grace Kloba5942df02009-09-18 11:48:29 -07002178 case KeyEvent.KEYCODE_BACK:
2179 if (event.isTracking() && !event.isCanceled()) {
2180 if (mCustomView != null) {
2181 // if a custom view is showing, hide it
Grace Kloba22ac16e2009-10-07 18:00:23 -07002182 mTabControl.getCurrentWebView().getWebChromeClient()
2183 .onHideCustomView();
Grace Kloba5942df02009-09-18 11:48:29 -07002184 } else if (mActiveTabsPage != null) {
2185 // if tab page is showing, hide it
2186 removeActiveTabPage(true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002187 } else {
Grace Kloba5942df02009-09-18 11:48:29 -07002188 WebView subwindow = mTabControl.getCurrentSubWindow();
2189 if (subwindow != null) {
2190 if (subwindow.canGoBack()) {
2191 subwindow.goBack();
2192 } else {
2193 dismissSubWindow(mTabControl.getCurrentTab());
2194 }
2195 } else {
2196 goBackOnePageOrQuit();
2197 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002198 }
Grace Kloba5942df02009-09-18 11:48:29 -07002199 return true;
2200 }
2201 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002202 }
Grace Kloba5942df02009-09-18 11:48:29 -07002203 return super.onKeyUp(keyCode, event);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002204 }
2205
Leon Scroggins68579392009-09-15 15:31:54 -04002206 /* package */ void stopLoading() {
Ben Murdochb7cc8b42009-09-28 10:59:09 +01002207 mDidStopLoad = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002208 resetTitleAndRevertLockIcon();
2209 WebView w = getTopWindow();
2210 w.stopLoading();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002211 // FIXME: before refactor, it is using mWebViewClient. So I keep the
2212 // same logic here. But for subwindow case, should we call into the main
2213 // WebView's onPageFinished as we never call its onPageStarted and if
2214 // the page finishes itself, we don't call onPageFinished.
2215 mTabControl.getCurrentWebView().getWebViewClient().onPageFinished(w,
2216 w.getUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08002217
2218 cancelStopToast();
2219 mStopToast = Toast
2220 .makeText(this, R.string.stopping, Toast.LENGTH_SHORT);
2221 mStopToast.show();
2222 }
2223
Grace Kloba22ac16e2009-10-07 18:00:23 -07002224 boolean didUserStopLoading() {
2225 return mDidStopLoad;
2226 }
2227
The Android Open Source Project0c908882009-03-03 19:32:16 -08002228 private void cancelStopToast() {
2229 if (mStopToast != null) {
2230 mStopToast.cancel();
2231 mStopToast = null;
2232 }
2233 }
2234
Grace Kloba22ac16e2009-10-07 18:00:23 -07002235 // called by a UI or non-UI thread to post the message
2236 public void postMessage(int what, int arg1, int arg2, Object obj,
2237 long delayMillis) {
2238 mHandler.sendMessageDelayed(mHandler.obtainMessage(what, arg1, arg2,
2239 obj), delayMillis);
2240 }
2241
2242 // called by a UI or non-UI thread to remove the message
2243 void removeMessages(int what, Object object) {
2244 mHandler.removeMessages(what, object);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002245 }
2246
2247 // public message ids
2248 public final static int LOAD_URL = 1001;
2249 public final static int STOP_LOAD = 1002;
2250
2251 // Message Ids
2252 private static final int FOCUS_NODE_HREF = 102;
Grace Kloba92c18a52009-07-31 23:48:32 -07002253 private static final int RELEASE_WAKELOCK = 107;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002254
Grace Kloba22ac16e2009-10-07 18:00:23 -07002255 static final int UPDATE_BOOKMARK_THUMBNAIL = 108;
Ben Murdoch2694e232009-09-29 09:41:11 +01002256
The Android Open Source Project0c908882009-03-03 19:32:16 -08002257 // Private handler for handling javascript and saving passwords
2258 private Handler mHandler = new Handler() {
2259
2260 public void handleMessage(Message msg) {
2261 switch (msg.what) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002262 case FOCUS_NODE_HREF:
Ben Murdoch2694e232009-09-29 09:41:11 +01002263 {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002264 String url = (String) msg.getData().get("url");
Ben Murdoch90d088c2009-11-17 18:14:04 +00002265 String title = (String) msg.getData().get("title");
The Android Open Source Project0c908882009-03-03 19:32:16 -08002266 if (url == null || url.length() == 0) {
2267 break;
2268 }
2269 HashMap focusNodeMap = (HashMap) msg.obj;
2270 WebView view = (WebView) focusNodeMap.get("webview");
2271 // Only apply the action if the top window did not change.
2272 if (getTopWindow() != view) {
2273 break;
2274 }
2275 switch (msg.arg1) {
2276 case R.id.open_context_menu_id:
2277 case R.id.view_image_context_menu_id:
Leon Scroggins92472e82010-02-17 16:32:28 -05002278 loadUrlFromContext(getTopWindow(), url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002279 break;
2280 case R.id.open_newtab_context_menu_id:
Grace Kloba22ac16e2009-10-07 18:00:23 -07002281 final Tab parent = mTabControl.getCurrentTab();
2282 final Tab newTab = openTab(url);
Grace Klobac9181842009-04-14 08:53:22 -07002283 if (newTab != parent) {
2284 parent.addChildTab(newTab);
2285 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002286 break;
2287 case R.id.bookmark_context_menu_id:
2288 Intent intent = new Intent(BrowserActivity.this,
2289 AddBookmarkPage.class);
2290 intent.putExtra("url", url);
Ben Murdoch90d088c2009-11-17 18:14:04 +00002291 intent.putExtra("title", title);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002292 startActivity(intent);
2293 break;
2294 case R.id.share_link_context_menu_id:
Leon Scroggins96afcb12009-12-10 12:35:56 -05002295 // See if this site has been visited before
2296 StringBuilder sb = new StringBuilder(
2297 Browser.BookmarkColumns.URL + " = ");
2298 DatabaseUtils.appendEscapedSQLString(sb, url);
2299 Cursor c = mResolver.query(Browser.BOOKMARKS_URI,
2300 Browser.HISTORY_PROJECTION,
2301 sb.toString(),
2302 null,
2303 null);
2304 if (c.moveToFirst()) {
2305 // The site has been visited before, so grab the
2306 // info from the database.
2307 Bitmap favicon = null;
2308 Bitmap thumbnail = null;
2309 String linkTitle = c.getString(Browser.
2310 HISTORY_PROJECTION_TITLE_INDEX);
2311 byte[] data = c.getBlob(Browser.
2312 HISTORY_PROJECTION_FAVICON_INDEX);
2313 if (data != null) {
2314 favicon = BitmapFactory.decodeByteArray(
2315 data, 0, data.length);
2316 }
2317 data = c.getBlob(Browser.
2318 HISTORY_PROJECTION_THUMBNAIL_INDEX);
2319 if (data != null) {
2320 thumbnail = BitmapFactory.decodeByteArray(
2321 data, 0, data.length);
2322 }
2323 sharePage(BrowserActivity.this,
2324 linkTitle, url, favicon, thumbnail);
2325 } else {
2326 Browser.sendString(BrowserActivity.this, url,
2327 getString(
2328 R.string.choosertitle_sharevia));
2329 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002330 break;
2331 case R.id.copy_link_context_menu_id:
2332 copy(url);
2333 break;
2334 case R.id.save_link_context_menu_id:
2335 case R.id.download_context_menu_id:
2336 onDownloadStartNoStream(url, null, null, null, -1);
2337 break;
2338 }
2339 break;
Ben Murdoch2694e232009-09-29 09:41:11 +01002340 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002341
2342 case LOAD_URL:
Leon Scroggins92472e82010-02-17 16:32:28 -05002343 loadUrlFromContext(getTopWindow(), (String) msg.obj);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002344 break;
2345
2346 case STOP_LOAD:
2347 stopLoading();
2348 break;
2349
The Android Open Source Project0c908882009-03-03 19:32:16 -08002350 case RELEASE_WAKELOCK:
2351 if (mWakeLock.isHeld()) {
2352 mWakeLock.release();
Grace Kloba5d0e02e2009-10-05 15:15:36 -07002353 // if we reach here, Browser should be still in the
2354 // background loading after WAKELOCK_TIMEOUT (5-min).
2355 // To avoid burning the battery, stop loading.
2356 mTabControl.stopAllLoading();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002357 }
2358 break;
Ben Murdoch2694e232009-09-29 09:41:11 +01002359
2360 case UPDATE_BOOKMARK_THUMBNAIL:
2361 WebView view = (WebView) msg.obj;
2362 if (view != null) {
2363 updateScreenshot(view);
2364 }
2365 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002366 }
2367 }
2368 };
2369
Leon Scroggins96afcb12009-12-10 12:35:56 -05002370 /**
2371 * Share a page, providing the title, url, favicon, and a screenshot. Uses
2372 * an {@link Intent} to launch the Activity chooser.
2373 * @param c Context used to launch a new Activity.
2374 * @param title Title of the page. Stored in the Intent with
Paul Westbrook03e6d392010-02-12 10:33:29 -08002375 * {@link Intent#EXTRA_SUBJECT}
Leon Scroggins96afcb12009-12-10 12:35:56 -05002376 * @param url URL of the page. Stored in the Intent with
2377 * {@link Intent#EXTRA_TEXT}
2378 * @param favicon Bitmap of the favicon for the page. Stored in the Intent
2379 * with {@link Browser#EXTRA_SHARE_FAVICON}
2380 * @param screenshot Bitmap of a screenshot of the page. Stored in the
2381 * Intent with {@link Browser#EXTRA_SHARE_SCREENSHOT}
2382 */
2383 public static final void sharePage(Context c, String title, String url,
2384 Bitmap favicon, Bitmap screenshot) {
2385 Intent send = new Intent(Intent.ACTION_SEND);
2386 send.setType("text/plain");
2387 send.putExtra(Intent.EXTRA_TEXT, url);
Paul Westbrook03e6d392010-02-12 10:33:29 -08002388 send.putExtra(Intent.EXTRA_SUBJECT, title);
Leon Scroggins96afcb12009-12-10 12:35:56 -05002389 send.putExtra(Browser.EXTRA_SHARE_FAVICON, favicon);
2390 send.putExtra(Browser.EXTRA_SHARE_SCREENSHOT, screenshot);
2391 try {
2392 c.startActivity(Intent.createChooser(send, c.getString(
2393 R.string.choosertitle_sharevia)));
2394 } catch(android.content.ActivityNotFoundException ex) {
2395 // if no app handles it, do nothing
2396 }
2397 }
2398
Leon Scroggins89c6d362009-07-15 16:54:37 -04002399 private void updateScreenshot(WebView view) {
2400 // If this is a bookmarked site, add a screenshot to the database.
2401 // FIXME: When should we update? Every time?
2402 // FIXME: Would like to make sure there is actually something to
2403 // draw, but the API for that (WebViewCore.pictureReady()) is not
2404 // currently accessible here.
Ben Murdochaac7aa62009-09-17 16:57:40 +01002405
Patrick Scottcb192b52010-04-14 14:38:55 -04002406 final Bitmap bm = createScreenshot(view);
2407 if (bm == null) {
2408 return;
Leon Scroggins89c6d362009-07-15 16:54:37 -04002409 }
Patrick Scottcb192b52010-04-14 14:38:55 -04002410
2411 final ContentResolver cr = getContentResolver();
2412 final String url = view.getUrl();
2413 final String originalUrl = view.getOriginalUrl();
2414
2415 new AsyncTask<Void, Void, Void>() {
2416 @Override
2417 protected Void doInBackground(Void... unused) {
2418 Cursor c = null;
2419 try {
2420 c = BrowserBookmarksAdapter.queryBookmarksForUrl(
2421 cr, originalUrl, url, true);
2422 if (c != null) {
2423 if (c.moveToFirst()) {
2424 ContentValues values = new ContentValues();
2425 final ByteArrayOutputStream os
2426 = new ByteArrayOutputStream();
2427 bm.compress(Bitmap.CompressFormat.PNG, 100, os);
2428 values.put(Browser.BookmarkColumns.THUMBNAIL,
2429 os.toByteArray());
2430 do {
2431 cr.update(ContentUris.withAppendedId(
2432 Browser.BOOKMARKS_URI, c.getInt(0)),
2433 values, null, null);
2434 } while (c.moveToNext());
2435 }
2436 }
2437 } catch (IllegalStateException e) {
2438 // Ignore
2439 } finally {
2440 if (c != null) c.close();
2441 }
2442 return null;
2443 }
2444 }.execute();
Leon Scroggins89c6d362009-07-15 16:54:37 -04002445 }
2446
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002447 /**
Leon Scrogginsf8551612009-09-24 16:06:02 -04002448 * Values for the size of the thumbnail created when taking a screenshot.
2449 * Lazily initialized. Instead of using these directly, use
2450 * getDesiredThumbnailWidth() or getDesiredThumbnailHeight().
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002451 */
Leon Scrogginsf8551612009-09-24 16:06:02 -04002452 private static int THUMBNAIL_WIDTH = 0;
2453 private static int THUMBNAIL_HEIGHT = 0;
2454
2455 /**
2456 * Return the desired width for thumbnail screenshots, which are stored in
2457 * the database, and used on the bookmarks screen.
2458 * @param context Context for finding out the density of the screen.
2459 * @return int desired width for thumbnail screenshot.
2460 */
2461 /* package */ static int getDesiredThumbnailWidth(Context context) {
2462 if (THUMBNAIL_WIDTH == 0) {
2463 float density = context.getResources().getDisplayMetrics().density;
2464 THUMBNAIL_WIDTH = (int) (90 * density);
2465 THUMBNAIL_HEIGHT = (int) (80 * density);
2466 }
2467 return THUMBNAIL_WIDTH;
2468 }
2469
2470 /**
2471 * Return the desired height for thumbnail screenshots, which are stored in
2472 * the database, and used on the bookmarks screen.
2473 * @param context Context for finding out the density of the screen.
2474 * @return int desired height for thumbnail screenshot.
2475 */
2476 /* package */ static int getDesiredThumbnailHeight(Context context) {
2477 // To ensure that they are both initialized.
2478 getDesiredThumbnailWidth(context);
2479 return THUMBNAIL_HEIGHT;
2480 }
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002481
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002482 private Bitmap createScreenshot(WebView view) {
2483 Picture thumbnail = view.capturePicture();
Leon Scroggins45800572009-09-29 16:38:47 -04002484 if (thumbnail == null) {
2485 return null;
2486 }
Leon Scrogginsf8551612009-09-24 16:06:02 -04002487 Bitmap bm = Bitmap.createBitmap(getDesiredThumbnailWidth(this),
Cary Clarkab168ba2010-04-08 09:11:28 -04002488 getDesiredThumbnailHeight(this), Bitmap.Config.RGB_565);
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002489 Canvas canvas = new Canvas(bm);
2490 // May need to tweak these values to determine what is the
2491 // best scale factor
Ben Murdoch2694e232009-09-29 09:41:11 +01002492 int thumbnailWidth = thumbnail.getWidth();
Ben Murdochae59c3f2009-10-20 18:30:28 +01002493 int thumbnailHeight = thumbnail.getHeight();
2494 float scaleFactorX = 1.0f;
2495 float scaleFactorY = 1.0f;
Ben Murdoch2694e232009-09-29 09:41:11 +01002496 if (thumbnailWidth > 0) {
Ben Murdochae59c3f2009-10-20 18:30:28 +01002497 scaleFactorX = (float) getDesiredThumbnailWidth(this) /
Ben Murdoch2694e232009-09-29 09:41:11 +01002498 (float)thumbnailWidth;
Ben Murdochae59c3f2009-10-20 18:30:28 +01002499 } else {
2500 return null;
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002501 }
Ben Murdochae59c3f2009-10-20 18:30:28 +01002502
2503 if (view.getWidth() > view.getHeight() &&
2504 thumbnailHeight < view.getHeight() && thumbnailHeight > 0) {
2505 // If the device is in landscape and the page is shorter
2506 // than the height of the view, stretch the thumbnail to fill the
2507 // space.
2508 scaleFactorY = (float) getDesiredThumbnailHeight(this) /
2509 (float)thumbnailHeight;
2510 } else {
2511 // In the portrait case, this looks nice.
2512 scaleFactorY = scaleFactorX;
2513 }
2514
2515 canvas.scale(scaleFactorX, scaleFactorY);
2516
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002517 thumbnail.draw(canvas);
2518 return bm;
2519 }
2520
The Android Open Source Project0c908882009-03-03 19:32:16 -08002521 // -------------------------------------------------------------------------
Grace Kloba22ac16e2009-10-07 18:00:23 -07002522 // Helper function for WebViewClient.
The Android Open Source Project0c908882009-03-03 19:32:16 -08002523 //-------------------------------------------------------------------------
2524
2525 // Use in overrideUrlLoading
2526 /* package */ final static String SCHEME_WTAI = "wtai://wp/";
2527 /* package */ final static String SCHEME_WTAI_MC = "wtai://wp/mc;";
2528 /* package */ final static String SCHEME_WTAI_SD = "wtai://wp/sd;";
2529 /* package */ final static String SCHEME_WTAI_AP = "wtai://wp/ap;";
2530
Leon Scroggins92472e82010-02-17 16:32:28 -05002531 // Keep this initial progress in sync with initialProgressValue (* 100)
2532 // in ProgressTracker.cpp
2533 private final static int INITIAL_PROGRESS = 10;
2534
Grace Kloba22ac16e2009-10-07 18:00:23 -07002535 void onPageStarted(WebView view, String url, Bitmap favicon) {
2536 // when BrowserActivity just starts, onPageStarted may be called before
2537 // onResume as it is triggered from onCreate. Call resumeWebViewTimers
2538 // to start the timer. As we won't switch tabs while an activity is in
2539 // pause state, we can ensure calling resume and pause in pair.
2540 if (mActivityInPause) resumeWebViewTimers();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002541
Grace Kloba22ac16e2009-10-07 18:00:23 -07002542 resetLockIcon(url);
2543 setUrlTitle(url, null);
2544 setFavicon(favicon);
Leon Scroggins8cf8f682009-11-04 11:13:50 -08002545 // Show some progress so that the user knows the page is beginning to
2546 // load
Leon Scroggins92472e82010-02-17 16:32:28 -05002547 onProgressChanged(view, INITIAL_PROGRESS);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002548 mDidStopLoad = false;
Grace Kloba22ac16e2009-10-07 18:00:23 -07002549 if (!mIsNetworkUp) createAndShowNetworkDialog();
Cary Clark2c326e62010-08-19 18:40:57 -04002550 closeDialogs();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002551 if (mSettings.isTracing()) {
2552 String host;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002553 try {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002554 WebAddress uri = new WebAddress(url);
2555 host = uri.mHost;
2556 } catch (android.net.ParseException ex) {
2557 host = "browser";
The Android Open Source Project0c908882009-03-03 19:32:16 -08002558 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002559 host = host.replace('.', '_');
2560 host += ".trace";
2561 mInTrace = true;
2562 Debug.startMethodTracing(host, 20 * 1024 * 1024);
2563 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002564
Grace Kloba22ac16e2009-10-07 18:00:23 -07002565 // Performance probe
2566 if (false) {
2567 mStart = SystemClock.uptimeMillis();
2568 mProcessStart = Process.getElapsedCpuTime();
2569 long[] sysCpu = new long[7];
2570 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2571 sysCpu, null)) {
2572 mUserStart = sysCpu[0] + sysCpu[1];
2573 mSystemStart = sysCpu[2];
2574 mIdleStart = sysCpu[3];
2575 mIrqStart = sysCpu[4] + sysCpu[5] + sysCpu[6];
2576 }
2577 mUiStart = SystemClock.currentThreadTimeMillis();
2578 }
2579 }
2580
2581 void onPageFinished(WebView view, String url) {
2582 // Reset the title and icon in case we stopped a provisional load.
2583 resetTitleAndIcon(view);
2584 // Update the lock icon image only once we are done loading
2585 updateLockIconToLatest();
2586 // pause the WebView timer and release the wake lock if it is finished
2587 // while BrowserActivity is in pause state.
2588 if (mActivityInPause && pauseWebViewTimers()) {
2589 if (mWakeLock.isHeld()) {
2590 mHandler.removeMessages(RELEASE_WAKELOCK);
2591 mWakeLock.release();
2592 }
2593 }
2594
2595 // Performance probe
2596 if (false) {
2597 long[] sysCpu = new long[7];
2598 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2599 sysCpu, null)) {
2600 String uiInfo = "UI thread used "
2601 + (SystemClock.currentThreadTimeMillis() - mUiStart)
2602 + " ms";
2603 if (LOGD_ENABLED) {
2604 Log.d(LOGTAG, uiInfo);
2605 }
2606 //The string that gets written to the log
2607 String performanceString = "It took total "
2608 + (SystemClock.uptimeMillis() - mStart)
2609 + " ms clock time to load the page."
2610 + "\nbrowser process used "
2611 + (Process.getElapsedCpuTime() - mProcessStart)
2612 + " ms, user processes used "
2613 + (sysCpu[0] + sysCpu[1] - mUserStart) * 10
2614 + " ms, kernel used "
2615 + (sysCpu[2] - mSystemStart) * 10
2616 + " ms, idle took " + (sysCpu[3] - mIdleStart) * 10
2617 + " ms and irq took "
2618 + (sysCpu[4] + sysCpu[5] + sysCpu[6] - mIrqStart)
2619 * 10 + " ms, " + uiInfo;
2620 if (LOGD_ENABLED) {
2621 Log.d(LOGTAG, performanceString + "\nWebpage: " + url);
2622 }
2623 if (url != null) {
2624 // strip the url to maintain consistency
2625 String newUrl = new String(url);
2626 if (newUrl.startsWith("http://www.")) {
2627 newUrl = newUrl.substring(11);
2628 } else if (newUrl.startsWith("http://")) {
2629 newUrl = newUrl.substring(7);
2630 } else if (newUrl.startsWith("https://www.")) {
2631 newUrl = newUrl.substring(12);
2632 } else if (newUrl.startsWith("https://")) {
2633 newUrl = newUrl.substring(8);
2634 }
2635 if (LOGD_ENABLED) {
2636 Log.d(LOGTAG, newUrl + " loaded");
2637 }
Grace Kloba5b078b52009-06-24 20:23:41 -07002638 }
2639 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002640 }
Grace Kloba5b078b52009-06-24 20:23:41 -07002641
Grace Kloba22ac16e2009-10-07 18:00:23 -07002642 if (mInTrace) {
2643 mInTrace = false;
2644 Debug.stopMethodTracing();
2645 }
2646 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002647
Grace Kloba22ac16e2009-10-07 18:00:23 -07002648 boolean shouldOverrideUrlLoading(WebView view, String url) {
2649 if (url.startsWith(SCHEME_WTAI)) {
2650 // wtai://wp/mc;number
2651 // number=string(phone-number)
2652 if (url.startsWith(SCHEME_WTAI_MC)) {
2653 Intent intent = new Intent(Intent.ACTION_VIEW,
2654 Uri.parse(WebView.SCHEME_TEL +
2655 url.substring(SCHEME_WTAI_MC.length())));
2656 startActivity(intent);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002657 return true;
2658 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002659 // wtai://wp/sd;dtmf
2660 // dtmf=string(dialstring)
2661 if (url.startsWith(SCHEME_WTAI_SD)) {
2662 // TODO: only send when there is active voice connection
2663 return false;
2664 }
2665 // wtai://wp/ap;number;name
2666 // number=string(phone-number)
2667 // name=string
2668 if (url.startsWith(SCHEME_WTAI_AP)) {
2669 // TODO
2670 return false;
2671 }
2672 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002673
Grace Kloba22ac16e2009-10-07 18:00:23 -07002674 // The "about:" schemes are internal to the browser; don't want these to
2675 // be dispatched to other apps.
2676 if (url.startsWith("about:")) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002677 return false;
2678 }
2679
Grace Kloba22ac16e2009-10-07 18:00:23 -07002680 Intent intent;
2681 // perform generic parsing of the URI to turn it into an Intent.
2682 try {
2683 intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME);
2684 } catch (URISyntaxException ex) {
2685 Log.w("Browser", "Bad URI " + url + ": " + ex.getMessage());
2686 return false;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002687 }
2688
Grace Kloba22ac16e2009-10-07 18:00:23 -07002689 // check whether the intent can be resolved. If not, we will see
2690 // whether we can download it from the Market.
2691 if (getPackageManager().resolveActivity(intent, 0) == null) {
2692 String packagename = intent.getPackage();
2693 if (packagename != null) {
2694 intent = new Intent(Intent.ACTION_VIEW, Uri
2695 .parse("market://search?q=pname:" + packagename));
2696 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2697 startActivity(intent);
2698 return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002699 } else {
2700 return false;
2701 }
2702 }
2703
Grace Kloba22ac16e2009-10-07 18:00:23 -07002704 // sanitize the Intent, ensuring web pages can not bypass browser
2705 // security (only access to BROWSABLE activities).
2706 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2707 intent.setComponent(null);
2708 try {
2709 if (startActivityIfNeeded(intent, -1)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002710 return true;
2711 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002712 } catch (ActivityNotFoundException ex) {
2713 // ignore the error. If no application can handle the URL,
2714 // eg about:blank, assume the browser can handle it.
2715 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002716
Grace Kloba22ac16e2009-10-07 18:00:23 -07002717 if (mMenuIsDown) {
2718 openTab(url);
2719 closeOptionsMenu();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002720 return true;
2721 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002722 return false;
2723 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002724
Grace Kloba22ac16e2009-10-07 18:00:23 -07002725 // -------------------------------------------------------------------------
2726 // Helper function for WebChromeClient
2727 // -------------------------------------------------------------------------
The Android Open Source Project0c908882009-03-03 19:32:16 -08002728
Grace Kloba22ac16e2009-10-07 18:00:23 -07002729 void onProgressChanged(WebView view, int newProgress) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002730 mFakeTitleBar.setProgress(newProgress);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002731
Grace Kloba22ac16e2009-10-07 18:00:23 -07002732 if (newProgress == 100) {
2733 // onProgressChanged() may continue to be called after the main
2734 // frame has finished loading, as any remaining sub frames continue
2735 // to load. We'll only get called once though with newProgress as
2736 // 100 when everything is loaded. (onPageFinished is called once
2737 // when the main frame completes loading regardless of the state of
2738 // any sub frames so calls to onProgressChanges may continue after
2739 // onPageFinished has executed)
2740 if (mInLoad) {
2741 mInLoad = false;
Leon Scrogginsa27ff192009-09-14 12:58:04 -04002742 updateInLoadMenuItems();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002743 // If the options menu is open, leave the title bar
2744 if (!mOptionsMenuOpen || !mIconView) {
2745 hideFakeTitleBar();
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07002746 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002747 }
Leon Scrogginsaa37e7f2010-03-05 11:51:20 -05002748 } else {
2749 if (!mInLoad) {
2750 // onPageFinished may have already been called but a subframe is
2751 // still loading and updating the progress. Reset mInLoad and
2752 // update the menu items.
2753 mInLoad = true;
2754 updateInLoadMenuItems();
2755 }
2756 // When the page first begins to load, the Activity may still be
2757 // paused, in which case showFakeTitleBar will do nothing. Call
2758 // again as the page continues to load so that it will be shown.
2759 // (Calling it will the fake title bar is already showing will also
2760 // do nothing.
Grace Kloba22ac16e2009-10-07 18:00:23 -07002761 if (!mOptionsMenuOpen || mIconView) {
2762 // This page has begun to load, so show the title bar
2763 showFakeTitleBar();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002764 }
2765 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002766 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002767
Grace Kloba22ac16e2009-10-07 18:00:23 -07002768 void onShowCustomView(View view, WebChromeClient.CustomViewCallback callback) {
Derek Sollenberger8ff57db2009-12-08 15:39:55 -05002769 // if a view already exists then immediately terminate the new one
2770 if (mCustomView != null) {
2771 callback.onCustomViewHidden();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002772 return;
Derek Sollenberger8ff57db2009-12-08 15:39:55 -05002773 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002774
2775 // Add the custom view to its container.
2776 mCustomViewContainer.addView(view, COVER_SCREEN_GRAVITY_CENTER);
2777 mCustomView = view;
2778 mCustomViewCallback = callback;
2779 // Save the menu state and set it to empty while the custom
2780 // view is showing.
2781 mOldMenuState = mMenuState;
2782 mMenuState = EMPTY_MENU;
2783 // Hide the content view.
2784 mContentView.setVisibility(View.GONE);
2785 // Finally show the custom view container.
Andrei Popescu163ab742009-10-20 17:58:23 +01002786 setStatusBarVisibility(false);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002787 mCustomViewContainer.setVisibility(View.VISIBLE);
2788 mCustomViewContainer.bringToFront();
2789 }
2790
2791 void onHideCustomView() {
2792 if (mCustomView == null)
2793 return;
2794
2795 // Hide the custom view.
2796 mCustomView.setVisibility(View.GONE);
2797 // Remove the custom view from its container.
2798 mCustomViewContainer.removeView(mCustomView);
2799 mCustomView = null;
2800 // Reset the old menu state.
2801 mMenuState = mOldMenuState;
2802 mOldMenuState = EMPTY_MENU;
2803 mCustomViewContainer.setVisibility(View.GONE);
2804 mCustomViewCallback.onCustomViewHidden();
2805 // Show the content view.
Andrei Popescu163ab742009-10-20 17:58:23 +01002806 setStatusBarVisibility(true);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002807 mContentView.setVisibility(View.VISIBLE);
2808 }
2809
2810 Bitmap getDefaultVideoPoster() {
2811 if (mDefaultVideoPoster == null) {
2812 mDefaultVideoPoster = BitmapFactory.decodeResource(
2813 getResources(), R.drawable.default_video_poster);
Patrick Scott3918d442009-08-04 13:22:29 -04002814 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002815 return mDefaultVideoPoster;
2816 }
Patrick Scott3918d442009-08-04 13:22:29 -04002817
Grace Kloba22ac16e2009-10-07 18:00:23 -07002818 View getVideoLoadingProgressView() {
2819 if (mVideoProgressView == null) {
2820 LayoutInflater inflater = LayoutInflater.from(BrowserActivity.this);
2821 mVideoProgressView = inflater.inflate(
2822 R.layout.video_loading_progress, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002823 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002824 return mVideoProgressView;
2825 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002826
Leon Scroggins8d5fa432009-10-02 15:55:59 -04002827 /*
2828 * The Object used to inform the WebView of the file to upload.
2829 */
2830 private ValueCallback<Uri> mUploadMessage;
2831
Grace Kloba22ac16e2009-10-07 18:00:23 -07002832 void openFileChooser(ValueCallback<Uri> uploadMsg) {
2833 if (mUploadMessage != null) return;
2834 mUploadMessage = uploadMsg;
2835 Intent i = new Intent(Intent.ACTION_GET_CONTENT);
2836 i.addCategory(Intent.CATEGORY_OPENABLE);
2837 i.setType("*/*");
2838 BrowserActivity.this.startActivityForResult(Intent.createChooser(i,
2839 getString(R.string.choose_upload)), FILE_SELECTED);
2840 }
2841
2842 // -------------------------------------------------------------------------
2843 // Implement functions for DownloadListener
2844 // -------------------------------------------------------------------------
2845
The Android Open Source Project0c908882009-03-03 19:32:16 -08002846 /**
2847 * Notify the host application a download should be done, or that
2848 * the data should be streamed if a streaming viewer is available.
2849 * @param url The full url to the content that should be downloaded
2850 * @param contentDisposition Content-disposition http header, if
2851 * present.
2852 * @param mimetype The mimetype of the content reported by the server
2853 * @param contentLength The file size reported by the server
2854 */
2855 public void onDownloadStart(String url, String userAgent,
2856 String contentDisposition, String mimetype, long contentLength) {
2857 // if we're dealing wih A/V content that's not explicitly marked
2858 // for download, check if it's streamable.
2859 if (contentDisposition == null
Patrick Scotte1fb9662009-08-31 14:31:52 -04002860 || !contentDisposition.regionMatches(
2861 true, 0, "attachment", 0, 10)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002862 // query the package manager to see if there's a registered handler
2863 // that matches.
2864 Intent intent = new Intent(Intent.ACTION_VIEW);
2865 intent.setDataAndType(Uri.parse(url), mimetype);
Patrick Scotte1fb9662009-08-31 14:31:52 -04002866 ResolveInfo info = getPackageManager().resolveActivity(intent,
2867 PackageManager.MATCH_DEFAULT_ONLY);
2868 if (info != null) {
2869 ComponentName myName = getComponentName();
2870 // If we resolved to ourselves, we don't want to attempt to
2871 // load the url only to try and download it again.
2872 if (!myName.getPackageName().equals(
2873 info.activityInfo.packageName)
2874 || !myName.getClassName().equals(
2875 info.activityInfo.name)) {
2876 // someone (other than us) knows how to handle this mime
2877 // type with this scheme, don't download.
2878 try {
2879 startActivity(intent);
2880 return;
2881 } catch (ActivityNotFoundException ex) {
2882 if (LOGD_ENABLED) {
2883 Log.d(LOGTAG, "activity not found for " + mimetype
2884 + " over " + Uri.parse(url).getScheme(),
2885 ex);
2886 }
2887 // Best behavior is to fall back to a download in this
2888 // case
The Android Open Source Project0c908882009-03-03 19:32:16 -08002889 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002890 }
2891 }
2892 }
2893 onDownloadStartNoStream(url, userAgent, contentDisposition, mimetype, contentLength);
2894 }
2895
Kristian Monsenfa52d172010-03-25 18:29:21 +00002896 // This is to work around the fact that java.net.URI throws Exceptions
2897 // instead of just encoding URL's properly
2898 // Helper method for onDownloadStartNoStream
2899 private static String encodePath(String path) {
2900 char[] chars = path.toCharArray();
2901
2902 boolean needed = false;
2903 for (char c : chars) {
2904 if (c == '[' || c == ']') {
2905 needed = true;
2906 break;
2907 }
2908 }
2909 if (needed == false) {
2910 return path;
2911 }
2912
2913 StringBuilder sb = new StringBuilder("");
2914 for (char c : chars) {
2915 if (c == '[' || c == ']') {
2916 sb.append('%');
2917 sb.append(Integer.toHexString(c));
2918 } else {
2919 sb.append(c);
2920 }
2921 }
2922
2923 return sb.toString();
2924 }
2925
The Android Open Source Project0c908882009-03-03 19:32:16 -08002926 /**
2927 * Notify the host application a download should be done, even if there
2928 * is a streaming viewer available for thise type.
2929 * @param url The full url to the content that should be downloaded
2930 * @param contentDisposition Content-disposition http header, if
2931 * present.
2932 * @param mimetype The mimetype of the content reported by the server
2933 * @param contentLength The file size reported by the server
2934 */
2935 /*package */ void onDownloadStartNoStream(String url, String userAgent,
2936 String contentDisposition, String mimetype, long contentLength) {
2937
2938 String filename = URLUtil.guessFileName(url,
2939 contentDisposition, mimetype);
2940
2941 // Check to see if we have an SDCard
2942 String status = Environment.getExternalStorageState();
2943 if (!status.equals(Environment.MEDIA_MOUNTED)) {
2944 int title;
2945 String msg;
2946
2947 // Check to see if the SDCard is busy, same as the music app
2948 if (status.equals(Environment.MEDIA_SHARED)) {
2949 msg = getString(R.string.download_sdcard_busy_dlg_msg);
2950 title = R.string.download_sdcard_busy_dlg_title;
2951 } else {
2952 msg = getString(R.string.download_no_sdcard_dlg_msg, filename);
2953 title = R.string.download_no_sdcard_dlg_title;
2954 }
2955
2956 new AlertDialog.Builder(this)
2957 .setTitle(title)
2958 .setIcon(android.R.drawable.ic_dialog_alert)
2959 .setMessage(msg)
2960 .setPositiveButton(R.string.ok, null)
2961 .show();
2962 return;
2963 }
2964
Kristian Monsenfa52d172010-03-25 18:29:21 +00002965 // java.net.URI is a lot stricter than KURL so we have to encode some
2966 // extra characters. Fix for b 2538060 and b 1634719
2967 WebAddress webAddress;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002968 try {
Kristian Monsenfa52d172010-03-25 18:29:21 +00002969 webAddress = new WebAddress(url);
2970 webAddress.mPath = encodePath(webAddress.mPath);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002971 } catch (Exception e) {
Kristian Monsenfa52d172010-03-25 18:29:21 +00002972 // This only happens for very bad urls, we want to chatch the
2973 // exception here
2974 Log.e(LOGTAG, "Exception trying to parse url:" + url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002975 return;
2976 }
2977
2978 // XXX: Have to use the old url since the cookies were stored using the
2979 // old percent-encoded url.
2980 String cookies = CookieManager.getInstance().getCookie(url);
2981
2982 ContentValues values = new ContentValues();
Kristian Monsenfa52d172010-03-25 18:29:21 +00002983 values.put(Downloads.Impl.COLUMN_URI, webAddress.toString());
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08002984 values.put(Downloads.Impl.COLUMN_COOKIE_DATA, cookies);
2985 values.put(Downloads.Impl.COLUMN_USER_AGENT, userAgent);
2986 values.put(Downloads.Impl.COLUMN_NOTIFICATION_PACKAGE,
The Android Open Source Project0c908882009-03-03 19:32:16 -08002987 getPackageName());
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08002988 values.put(Downloads.Impl.COLUMN_NOTIFICATION_CLASS,
Leon Scrogginsa563d092010-04-19 16:53:49 -04002989 OpenDownloadReceiver.class.getCanonicalName());
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08002990 values.put(Downloads.Impl.COLUMN_VISIBILITY,
2991 Downloads.Impl.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
2992 values.put(Downloads.Impl.COLUMN_MIME_TYPE, mimetype);
2993 values.put(Downloads.Impl.COLUMN_FILE_NAME_HINT, filename);
Kristian Monsenfa52d172010-03-25 18:29:21 +00002994 values.put(Downloads.Impl.COLUMN_DESCRIPTION, webAddress.mHost);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002995 if (contentLength > 0) {
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08002996 values.put(Downloads.Impl.COLUMN_TOTAL_BYTES, contentLength);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002997 }
2998 if (mimetype == null) {
2999 // We must have long pressed on a link or image to download it. We
3000 // are not sure of the mimetype in this case, so do a head request
3001 new FetchUrlMimeType(this).execute(values);
3002 } else {
3003 final Uri contentUri =
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08003004 getContentResolver().insert(Downloads.Impl.CONTENT_URI, values);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003005 }
Leon Scroggins9191a7f2010-03-18 14:44:44 -04003006 Toast.makeText(this, R.string.download_pending, Toast.LENGTH_SHORT)
3007 .show();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003008 }
3009
Grace Kloba22ac16e2009-10-07 18:00:23 -07003010 // -------------------------------------------------------------------------
3011
The Android Open Source Project0c908882009-03-03 19:32:16 -08003012 /**
3013 * Resets the lock icon. This method is called when we start a new load and
3014 * know the url to be loaded.
3015 */
3016 private void resetLockIcon(String url) {
3017 // Save the lock-icon state (we revert to it if the load gets cancelled)
Grace Kloba22ac16e2009-10-07 18:00:23 -07003018 mTabControl.getCurrentTab().resetLockIcon(url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003019 updateLockIconImage(LOCK_ICON_UNSECURE);
3020 }
3021
The Android Open Source Project0c908882009-03-03 19:32:16 -08003022 /**
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04003023 * Update the lock icon to correspond to our latest state.
3024 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003025 private void updateLockIconToLatest() {
3026 updateLockIconImage(mTabControl.getCurrentTab().getLockIconType());
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04003027 }
3028
3029 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08003030 * Updates the lock-icon image in the title-bar.
3031 */
3032 private void updateLockIconImage(int lockIconType) {
3033 Drawable d = null;
3034 if (lockIconType == LOCK_ICON_SECURE) {
3035 d = mSecLockIcon;
3036 } else if (lockIconType == LOCK_ICON_MIXED) {
3037 d = mMixLockIcon;
3038 }
Leon Scroggins68579392009-09-15 15:31:54 -04003039 mTitleBar.setLock(d);
Leon Scrogginsfe87bd32009-10-06 10:10:00 -04003040 mFakeTitleBar.setLock(d);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003041 }
3042
3043 /**
3044 * Displays a page-info dialog.
3045 * @param tab The tab to show info about
3046 * @param fromShowSSLCertificateOnError The flag that indicates whether
3047 * this dialog was opened from the SSL-certificate-on-error dialog or
3048 * not. This is important, since we need to know whether to return to
3049 * the parent dialog or simply dismiss.
3050 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003051 private void showPageInfo(final Tab tab,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003052 final boolean fromShowSSLCertificateOnError) {
3053 final LayoutInflater factory = LayoutInflater
3054 .from(this);
3055
3056 final View pageInfoView = factory.inflate(R.layout.page_info, null);
3057
3058 final WebView view = tab.getWebView();
3059
3060 String url = null;
3061 String title = null;
3062
3063 if (view == null) {
3064 url = tab.getUrl();
3065 title = tab.getTitle();
3066 } else if (view == mTabControl.getCurrentWebView()) {
3067 // Use the cached title and url if this is the current WebView
3068 url = mUrl;
3069 title = mTitle;
3070 } else {
3071 url = view.getUrl();
3072 title = view.getTitle();
3073 }
3074
3075 if (url == null) {
3076 url = "";
3077 }
3078 if (title == null) {
3079 title = "";
3080 }
3081
3082 ((TextView) pageInfoView.findViewById(R.id.address)).setText(url);
3083 ((TextView) pageInfoView.findViewById(R.id.title)).setText(title);
3084
3085 mPageInfoView = tab;
Leon Scrogginsc7b92f82010-01-11 18:17:31 -05003086 mPageInfoFromShowSSLCertificateOnError = fromShowSSLCertificateOnError;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003087
3088 AlertDialog.Builder alertDialogBuilder =
3089 new AlertDialog.Builder(this)
3090 .setTitle(R.string.page_info).setIcon(android.R.drawable.ic_dialog_info)
3091 .setView(pageInfoView)
3092 .setPositiveButton(
3093 R.string.ok,
3094 new DialogInterface.OnClickListener() {
3095 public void onClick(DialogInterface dialog,
3096 int whichButton) {
3097 mPageInfoDialog = null;
3098 mPageInfoView = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003099
3100 // if we came here from the SSL error dialog
3101 if (fromShowSSLCertificateOnError) {
3102 // go back to the SSL error dialog
3103 showSSLCertificateOnError(
3104 mSSLCertificateOnErrorView,
3105 mSSLCertificateOnErrorHandler,
3106 mSSLCertificateOnErrorError);
3107 }
3108 }
3109 })
3110 .setOnCancelListener(
3111 new DialogInterface.OnCancelListener() {
3112 public void onCancel(DialogInterface dialog) {
3113 mPageInfoDialog = null;
3114 mPageInfoView = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003115
3116 // if we came here from the SSL error dialog
3117 if (fromShowSSLCertificateOnError) {
3118 // go back to the SSL error dialog
3119 showSSLCertificateOnError(
3120 mSSLCertificateOnErrorView,
3121 mSSLCertificateOnErrorHandler,
3122 mSSLCertificateOnErrorError);
3123 }
3124 }
3125 });
3126
3127 // if we have a main top-level page SSL certificate set or a certificate
3128 // error
3129 if (fromShowSSLCertificateOnError ||
3130 (view != null && view.getCertificate() != null)) {
3131 // add a 'View Certificate' button
3132 alertDialogBuilder.setNeutralButton(
3133 R.string.view_certificate,
3134 new DialogInterface.OnClickListener() {
3135 public void onClick(DialogInterface dialog,
3136 int whichButton) {
3137 mPageInfoDialog = null;
3138 mPageInfoView = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003139
3140 // if we came here from the SSL error dialog
3141 if (fromShowSSLCertificateOnError) {
3142 // go back to the SSL error dialog
3143 showSSLCertificateOnError(
3144 mSSLCertificateOnErrorView,
3145 mSSLCertificateOnErrorHandler,
3146 mSSLCertificateOnErrorError);
3147 } else {
3148 // otherwise, display the top-most certificate from
3149 // the chain
3150 if (view.getCertificate() != null) {
3151 showSSLCertificate(tab);
3152 }
3153 }
3154 }
3155 });
3156 }
3157
3158 mPageInfoDialog = alertDialogBuilder.show();
3159 }
3160
3161 /**
3162 * Displays the main top-level page SSL certificate dialog
3163 * (accessible from the Page-Info dialog).
3164 * @param tab The tab to show certificate for.
3165 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003166 private void showSSLCertificate(final Tab tab) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003167 final View certificateView =
3168 inflateCertificateView(tab.getWebView().getCertificate());
3169 if (certificateView == null) {
3170 return;
3171 }
3172
3173 LayoutInflater factory = LayoutInflater.from(this);
3174
3175 final LinearLayout placeholder =
3176 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3177
3178 LinearLayout ll = (LinearLayout) factory.inflate(
3179 R.layout.ssl_success, placeholder);
3180 ((TextView)ll.findViewById(R.id.success))
3181 .setText(R.string.ssl_certificate_is_valid);
3182
3183 mSSLCertificateView = tab;
3184 mSSLCertificateDialog =
3185 new AlertDialog.Builder(this)
3186 .setTitle(R.string.ssl_certificate).setIcon(
3187 R.drawable.ic_dialog_browser_certificate_secure)
3188 .setView(certificateView)
3189 .setPositiveButton(R.string.ok,
3190 new DialogInterface.OnClickListener() {
3191 public void onClick(DialogInterface dialog,
3192 int whichButton) {
3193 mSSLCertificateDialog = null;
3194 mSSLCertificateView = null;
3195
3196 showPageInfo(tab, false);
3197 }
3198 })
3199 .setOnCancelListener(
3200 new DialogInterface.OnCancelListener() {
3201 public void onCancel(DialogInterface dialog) {
3202 mSSLCertificateDialog = null;
3203 mSSLCertificateView = null;
3204
3205 showPageInfo(tab, false);
3206 }
3207 })
3208 .show();
3209 }
3210
3211 /**
3212 * Displays the SSL error certificate dialog.
3213 * @param view The target web-view.
3214 * @param handler The SSL error handler responsible for cancelling the
3215 * connection that resulted in an SSL error or proceeding per user request.
3216 * @param error The SSL error object.
3217 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003218 void showSSLCertificateOnError(
The Android Open Source Project0c908882009-03-03 19:32:16 -08003219 final WebView view, final SslErrorHandler handler, final SslError error) {
3220
3221 final View certificateView =
3222 inflateCertificateView(error.getCertificate());
3223 if (certificateView == null) {
3224 return;
3225 }
3226
3227 LayoutInflater factory = LayoutInflater.from(this);
3228
3229 final LinearLayout placeholder =
3230 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3231
3232 if (error.hasError(SslError.SSL_UNTRUSTED)) {
3233 LinearLayout ll = (LinearLayout)factory
3234 .inflate(R.layout.ssl_warning, placeholder);
3235 ((TextView)ll.findViewById(R.id.warning))
3236 .setText(R.string.ssl_untrusted);
3237 }
3238
3239 if (error.hasError(SslError.SSL_IDMISMATCH)) {
3240 LinearLayout ll = (LinearLayout)factory
3241 .inflate(R.layout.ssl_warning, placeholder);
3242 ((TextView)ll.findViewById(R.id.warning))
3243 .setText(R.string.ssl_mismatch);
3244 }
3245
3246 if (error.hasError(SslError.SSL_EXPIRED)) {
3247 LinearLayout ll = (LinearLayout)factory
3248 .inflate(R.layout.ssl_warning, placeholder);
3249 ((TextView)ll.findViewById(R.id.warning))
3250 .setText(R.string.ssl_expired);
3251 }
3252
3253 if (error.hasError(SslError.SSL_NOTYETVALID)) {
3254 LinearLayout ll = (LinearLayout)factory
3255 .inflate(R.layout.ssl_warning, placeholder);
3256 ((TextView)ll.findViewById(R.id.warning))
3257 .setText(R.string.ssl_not_yet_valid);
3258 }
3259
3260 mSSLCertificateOnErrorHandler = handler;
3261 mSSLCertificateOnErrorView = view;
3262 mSSLCertificateOnErrorError = error;
3263 mSSLCertificateOnErrorDialog =
3264 new AlertDialog.Builder(this)
3265 .setTitle(R.string.ssl_certificate).setIcon(
3266 R.drawable.ic_dialog_browser_certificate_partially_secure)
3267 .setView(certificateView)
3268 .setPositiveButton(R.string.ok,
3269 new DialogInterface.OnClickListener() {
3270 public void onClick(DialogInterface dialog,
3271 int whichButton) {
3272 mSSLCertificateOnErrorDialog = null;
3273 mSSLCertificateOnErrorView = null;
3274 mSSLCertificateOnErrorHandler = null;
3275 mSSLCertificateOnErrorError = null;
3276
Grace Kloba22ac16e2009-10-07 18:00:23 -07003277 view.getWebViewClient().onReceivedSslError(
3278 view, handler, error);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003279 }
3280 })
3281 .setNeutralButton(R.string.page_info_view,
3282 new DialogInterface.OnClickListener() {
3283 public void onClick(DialogInterface dialog,
3284 int whichButton) {
3285 mSSLCertificateOnErrorDialog = null;
3286
3287 // do not clear the dialog state: we will
3288 // need to show the dialog again once the
3289 // user is done exploring the page-info details
3290
3291 showPageInfo(mTabControl.getTabFromView(view),
3292 true);
3293 }
3294 })
3295 .setOnCancelListener(
3296 new DialogInterface.OnCancelListener() {
3297 public void onCancel(DialogInterface dialog) {
3298 mSSLCertificateOnErrorDialog = null;
3299 mSSLCertificateOnErrorView = null;
3300 mSSLCertificateOnErrorHandler = null;
3301 mSSLCertificateOnErrorError = null;
3302
Grace Kloba22ac16e2009-10-07 18:00:23 -07003303 view.getWebViewClient().onReceivedSslError(
3304 view, handler, error);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003305 }
3306 })
3307 .show();
3308 }
3309
3310 /**
3311 * Inflates the SSL certificate view (helper method).
3312 * @param certificate The SSL certificate.
3313 * @return The resultant certificate view with issued-to, issued-by,
3314 * issued-on, expires-on, and possibly other fields set.
3315 * If the input certificate is null, returns null.
3316 */
3317 private View inflateCertificateView(SslCertificate certificate) {
3318 if (certificate == null) {
3319 return null;
3320 }
3321
3322 LayoutInflater factory = LayoutInflater.from(this);
3323
3324 View certificateView = factory.inflate(
3325 R.layout.ssl_certificate, null);
3326
3327 // issued to:
3328 SslCertificate.DName issuedTo = certificate.getIssuedTo();
3329 if (issuedTo != null) {
3330 ((TextView) certificateView.findViewById(R.id.to_common))
3331 .setText(issuedTo.getCName());
3332 ((TextView) certificateView.findViewById(R.id.to_org))
3333 .setText(issuedTo.getOName());
3334 ((TextView) certificateView.findViewById(R.id.to_org_unit))
3335 .setText(issuedTo.getUName());
3336 }
3337
3338 // issued by:
3339 SslCertificate.DName issuedBy = certificate.getIssuedBy();
3340 if (issuedBy != null) {
3341 ((TextView) certificateView.findViewById(R.id.by_common))
3342 .setText(issuedBy.getCName());
3343 ((TextView) certificateView.findViewById(R.id.by_org))
3344 .setText(issuedBy.getOName());
3345 ((TextView) certificateView.findViewById(R.id.by_org_unit))
3346 .setText(issuedBy.getUName());
3347 }
3348
3349 // issued on:
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003350 String issuedOn = formatCertificateDate(
3351 certificate.getValidNotBeforeDate());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003352 ((TextView) certificateView.findViewById(R.id.issued_on))
3353 .setText(issuedOn);
3354
3355 // expires on:
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003356 String expiresOn = formatCertificateDate(
3357 certificate.getValidNotAfterDate());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003358 ((TextView) certificateView.findViewById(R.id.expires_on))
3359 .setText(expiresOn);
3360
3361 return certificateView;
3362 }
3363
3364 /**
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003365 * Formats the certificate date to a properly localized date string.
The Android Open Source Project0c908882009-03-03 19:32:16 -08003366 * @return Properly localized version of the certificate date string and
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003367 * the "" if it fails to localize.
The Android Open Source Project0c908882009-03-03 19:32:16 -08003368 */
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003369 private String formatCertificateDate(Date certificateDate) {
3370 if (certificateDate == null) {
3371 return "";
The Android Open Source Project0c908882009-03-03 19:32:16 -08003372 }
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003373 String formattedDate = DateFormat.getDateFormat(this).format(certificateDate);
3374 if (formattedDate == null) {
3375 return "";
3376 }
3377 return formattedDate;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003378 }
3379
3380 /**
3381 * Displays an http-authentication dialog.
3382 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003383 void showHttpAuthentication(final HttpAuthHandler handler,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003384 final String host, final String realm, final String title,
3385 final String name, final String password, int focusId) {
3386 LayoutInflater factory = LayoutInflater.from(this);
3387 final View v = factory
3388 .inflate(R.layout.http_authentication, null);
3389 if (name != null) {
3390 ((EditText) v.findViewById(R.id.username_edit)).setText(name);
3391 }
3392 if (password != null) {
3393 ((EditText) v.findViewById(R.id.password_edit)).setText(password);
3394 }
3395
3396 String titleText = title;
3397 if (titleText == null) {
3398 titleText = getText(R.string.sign_in_to).toString().replace(
3399 "%s1", host).replace("%s2", realm);
3400 }
3401
3402 mHttpAuthHandler = handler;
3403 AlertDialog dialog = new AlertDialog.Builder(this)
3404 .setTitle(titleText)
3405 .setIcon(android.R.drawable.ic_dialog_alert)
3406 .setView(v)
3407 .setPositiveButton(R.string.action,
3408 new DialogInterface.OnClickListener() {
3409 public void onClick(DialogInterface dialog,
3410 int whichButton) {
3411 String nm = ((EditText) v
3412 .findViewById(R.id.username_edit))
3413 .getText().toString();
3414 String pw = ((EditText) v
3415 .findViewById(R.id.password_edit))
3416 .getText().toString();
3417 BrowserActivity.this.setHttpAuthUsernamePassword
3418 (host, realm, nm, pw);
3419 handler.proceed(nm, pw);
3420 mHttpAuthenticationDialog = null;
3421 mHttpAuthHandler = null;
3422 }})
3423 .setNegativeButton(R.string.cancel,
3424 new DialogInterface.OnClickListener() {
3425 public void onClick(DialogInterface dialog,
3426 int whichButton) {
3427 handler.cancel();
3428 BrowserActivity.this.resetTitleAndRevertLockIcon();
3429 mHttpAuthenticationDialog = null;
3430 mHttpAuthHandler = null;
3431 }})
3432 .setOnCancelListener(new DialogInterface.OnCancelListener() {
3433 public void onCancel(DialogInterface dialog) {
3434 handler.cancel();
3435 BrowserActivity.this.resetTitleAndRevertLockIcon();
3436 mHttpAuthenticationDialog = null;
3437 mHttpAuthHandler = null;
3438 }})
3439 .create();
3440 // Make the IME appear when the dialog is displayed if applicable.
3441 dialog.getWindow().setSoftInputMode(
3442 WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
3443 dialog.show();
3444 if (focusId != 0) {
3445 dialog.findViewById(focusId).requestFocus();
3446 } else {
3447 v.findViewById(R.id.username_edit).requestFocus();
3448 }
3449 mHttpAuthenticationDialog = dialog;
3450 }
3451
3452 public int getProgress() {
3453 WebView w = mTabControl.getCurrentWebView();
3454 if (w != null) {
3455 return w.getProgress();
3456 } else {
3457 return 100;
3458 }
3459 }
3460
3461 /**
3462 * Set HTTP authentication password.
3463 *
3464 * @param host The host for the password
3465 * @param realm The realm for the password
3466 * @param username The username for the password. If it is null, it means
3467 * password can't be saved.
3468 * @param password The password
3469 */
3470 public void setHttpAuthUsernamePassword(String host, String realm,
3471 String username,
3472 String password) {
Steve Block95a53b22010-03-25 17:24:58 +00003473 WebView w = getTopWindow();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003474 if (w != null) {
3475 w.setHttpAuthUsernamePassword(host, realm, username, password);
3476 }
3477 }
3478
3479 /**
3480 * connectivity manager says net has come or gone... inform the user
3481 * @param up true if net has come up, false if net has gone down
3482 */
3483 public void onNetworkToggle(boolean up) {
3484 if (up == mIsNetworkUp) {
3485 return;
3486 } else if (up) {
3487 mIsNetworkUp = true;
3488 if (mAlertDialog != null) {
3489 mAlertDialog.cancel();
3490 mAlertDialog = null;
3491 }
3492 } else {
3493 mIsNetworkUp = false;
Patrick Scotteb6ab2a2009-09-16 10:00:17 -04003494 if (mInLoad) {
3495 createAndShowNetworkDialog();
3496 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003497 }
3498 WebView w = mTabControl.getCurrentWebView();
3499 if (w != null) {
3500 w.setNetworkAvailable(up);
3501 }
3502 }
3503
Grace Kloba22ac16e2009-10-07 18:00:23 -07003504 boolean isNetworkUp() {
3505 return mIsNetworkUp;
3506 }
3507
Patrick Scotteb6ab2a2009-09-16 10:00:17 -04003508 // This method shows the network dialog alerting the user that the net is
3509 // down. It will only show the dialog if mAlertDialog is null.
3510 private void createAndShowNetworkDialog() {
3511 if (mAlertDialog == null) {
3512 mAlertDialog = new AlertDialog.Builder(this)
3513 .setTitle(R.string.loadSuspendedTitle)
3514 .setMessage(R.string.loadSuspended)
3515 .setPositiveButton(R.string.ok, null)
3516 .show();
3517 }
3518 }
3519
The Android Open Source Project0c908882009-03-03 19:32:16 -08003520 @Override
3521 protected void onActivityResult(int requestCode, int resultCode,
3522 Intent intent) {
Grace Klobabb394f32009-11-19 10:26:37 -08003523 if (getTopWindow() == null) return;
3524
The Android Open Source Project0c908882009-03-03 19:32:16 -08003525 switch (requestCode) {
3526 case COMBO_PAGE:
3527 if (resultCode == RESULT_OK && intent != null) {
3528 String data = intent.getAction();
3529 Bundle extras = intent.getExtras();
3530 if (extras != null && extras.getBoolean("new_window", false)) {
Leon Scroggins25d35472009-09-15 11:37:27 -04003531 openTab(data);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003532 } else {
Grace Kloba22ac16e2009-10-07 18:00:23 -07003533 final Tab currentTab =
The Android Open Source Project0c908882009-03-03 19:32:16 -08003534 mTabControl.getCurrentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04003535 dismissSubWindow(currentTab);
3536 if (data != null && data.length() != 0) {
Leon Scroggins92472e82010-02-17 16:32:28 -05003537 loadUrl(getTopWindow(), data);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003538 }
3539 }
3540 }
Leon Scrogginsfde97462010-01-11 13:06:21 -05003541 // Deliberately fall through to PREFERENCES_PAGE, since the
3542 // same extra may be attached to the COMBO_PAGE
3543 case PREFERENCES_PAGE:
3544 if (resultCode == RESULT_OK && intent != null) {
3545 String action = intent.getStringExtra(Intent.EXTRA_TEXT);
3546 if (BrowserSettings.PREF_CLEAR_HISTORY.equals(action)) {
3547 mTabControl.removeParentChildRelationShips();
3548 }
3549 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003550 break;
Leon Scroggins8d5fa432009-10-02 15:55:59 -04003551 // Choose a file from the file picker.
3552 case FILE_SELECTED:
3553 if (null == mUploadMessage) break;
3554 Uri result = intent == null || resultCode != RESULT_OK ? null
3555 : intent.getData();
3556 mUploadMessage.onReceiveValue(result);
3557 mUploadMessage = null;
3558 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003559 default:
3560 break;
3561 }
Leon Scroggins30444232009-09-04 18:36:20 -04003562 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003563 }
3564
3565 /*
3566 * This method is called as a result of the user selecting the options
Leon Scrogginsf08809b2010-01-21 09:27:46 -05003567 * menu to see the download window. It shows the download window on top of
3568 * the current window.
The Android Open Source Project0c908882009-03-03 19:32:16 -08003569 */
Leon Scroggins IIIa682a3c2010-09-27 12:32:40 -04003570 private void viewDownloads() {
3571 Intent intent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
3572 startActivity(intent);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003573 }
3574
Leon Scroggins160a7e72009-08-14 18:28:01 -04003575 /**
3576 * Open the Go page.
3577 * @param startWithHistory If true, open starting on the history tab.
3578 * Otherwise, start with the bookmarks tab.
Leon Scroggins160a7e72009-08-14 18:28:01 -04003579 */
Leon Scroggins30444232009-09-04 18:36:20 -04003580 /* package */ void bookmarksOrHistoryPicker(boolean startWithHistory) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003581 WebView current = mTabControl.getCurrentWebView();
3582 if (current == null) {
3583 return;
3584 }
3585 Intent intent = new Intent(this,
3586 CombinedBookmarkHistoryActivity.class);
3587 String title = current.getTitle();
3588 String url = current.getUrl();
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01003589 Bitmap thumbnail = createScreenshot(current);
3590
The Android Open Source Project0c908882009-03-03 19:32:16 -08003591 // Just in case the user opens bookmarks before a page finishes loading
3592 // so the current history item, and therefore the page, is null.
3593 if (null == url) {
3594 url = mLastEnteredUrl;
3595 // This can happen.
3596 if (null == url) {
3597 url = mSettings.getHomePage();
3598 }
3599 }
3600 // In case the web page has not yet received its associated title.
3601 if (title == null) {
3602 title = url;
3603 }
3604 intent.putExtra("title", title);
3605 intent.putExtra("url", url);
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01003606 intent.putExtra("thumbnail", thumbnail);
Leon Scroggins30444232009-09-04 18:36:20 -04003607 // Disable opening in a new window if we have maxed out the windows
Grace Kloba22ac16e2009-10-07 18:00:23 -07003608 intent.putExtra("disable_new_window", !mTabControl.canCreateNewTab());
Patrick Scott3918d442009-08-04 13:22:29 -04003609 intent.putExtra("touch_icon_url", current.getTouchIconUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003610 if (startWithHistory) {
3611 intent.putExtra(CombinedBookmarkHistoryActivity.STARTING_TAB,
3612 CombinedBookmarkHistoryActivity.HISTORY_TAB);
3613 }
3614 startActivityForResult(intent, COMBO_PAGE);
3615 }
3616
3617 // Called when loading from context menu or LOAD_URL message
Leon Scroggins92472e82010-02-17 16:32:28 -05003618 private void loadUrlFromContext(WebView view, String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003619 // In case the user enters nothing.
3620 if (url != null && url.length() != 0 && view != null) {
3621 url = smartUrlFilter(url);
Grace Kloba22ac16e2009-10-07 18:00:23 -07003622 if (!view.getWebViewClient().shouldOverrideUrlLoading(view, url)) {
Leon Scroggins92472e82010-02-17 16:32:28 -05003623 loadUrl(view, url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003624 }
3625 }
3626 }
3627
Leon Scroggins92472e82010-02-17 16:32:28 -05003628 /**
3629 * Load the URL into the given WebView and update the title bar
3630 * to reflect the new load. Call this instead of WebView.loadUrl
3631 * directly.
3632 * @param view The WebView used to load url.
3633 * @param url The URL to load.
3634 */
3635 private void loadUrl(WebView view, String url) {
3636 updateTitleBarForNewLoad(view, url);
3637 view.loadUrl(url);
3638 }
3639
3640 /**
3641 * Load UrlData into a Tab and update the title bar to reflect the new
3642 * load. Call this instead of UrlData.loadIn directly.
3643 * @param t The Tab used to load.
3644 * @param data The UrlData being loaded.
3645 */
3646 private void loadUrlDataIn(Tab t, UrlData data) {
3647 updateTitleBarForNewLoad(t.getWebView(), data.mUrl);
3648 data.loadIn(t);
3649 }
3650
3651 /**
3652 * If the WebView is the top window, update the title bar to reflect
3653 * loading the new URL. i.e. set its text, clear the favicon (which
3654 * will be set once the page begins loading), and set the progress to
3655 * INITIAL_PROGRESS to show that the page has begun to load. Called
3656 * by loadUrl and loadUrlDataIn.
3657 * @param view The WebView that is starting a load.
3658 * @param url The URL that is being loaded.
3659 */
3660 private void updateTitleBarForNewLoad(WebView view, String url) {
3661 if (view == getTopWindow()) {
3662 setUrlTitle(url, null);
3663 setFavicon(null);
3664 onProgressChanged(view, INITIAL_PROGRESS);
3665 }
3666 }
3667
The Android Open Source Project0c908882009-03-03 19:32:16 -08003668 private String smartUrlFilter(Uri inUri) {
3669 if (inUri != null) {
3670 return smartUrlFilter(inUri.toString());
3671 }
3672 return null;
3673 }
3674
Feng Qianb34f87a2009-03-24 21:27:26 -07003675 protected static final Pattern ACCEPTED_URI_SCHEMA = Pattern.compile(
The Android Open Source Project0c908882009-03-03 19:32:16 -08003676 "(?i)" + // switch on case insensitive matching
3677 "(" + // begin group for schema
3678 "(?:http|https|file):\\/\\/" +
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003679 "|(?:inline|data|about|content|javascript):" +
The Android Open Source Project0c908882009-03-03 19:32:16 -08003680 ")" +
3681 "(.*)" );
3682
3683 /**
3684 * Attempts to determine whether user input is a URL or search
3685 * terms. Anything with a space is passed to search.
3686 *
3687 * Converts to lowercase any mistakenly uppercased schema (i.e.,
3688 * "Http://" converts to "http://"
3689 *
3690 * @return Original or modified URL
3691 *
3692 */
3693 String smartUrlFilter(String url) {
3694
3695 String inUrl = url.trim();
3696 boolean hasSpace = inUrl.indexOf(' ') != -1;
3697
3698 Matcher matcher = ACCEPTED_URI_SCHEMA.matcher(inUrl);
3699 if (matcher.matches()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003700 // force scheme to lowercase
3701 String scheme = matcher.group(1);
3702 String lcScheme = scheme.toLowerCase();
3703 if (!lcScheme.equals(scheme)) {
Mitsuru Oshima123ecfb2009-05-18 19:11:14 -07003704 inUrl = lcScheme + matcher.group(2);
3705 }
3706 if (hasSpace) {
3707 inUrl = inUrl.replace(" ", "%20");
The Android Open Source Project0c908882009-03-03 19:32:16 -08003708 }
3709 return inUrl;
3710 }
3711 if (hasSpace) {
Satish Sampath565505b2009-05-29 15:37:27 +01003712 // FIXME: Is this the correct place to add to searches?
3713 // what if someone else calls this function?
3714 int shortcut = parseUrlShortcut(inUrl);
3715 if (shortcut != SHORTCUT_INVALID) {
3716 Browser.addSearchUrl(mResolver, inUrl);
3717 String query = inUrl.substring(2);
3718 switch (shortcut) {
3719 case SHORTCUT_GOOGLE_SEARCH:
Grace Kloba47fdfdb2009-06-30 11:15:34 -07003720 return URLUtil.composeSearchUrl(query, QuickSearch_G, QUERY_PLACE_HOLDER);
Satish Sampath565505b2009-05-29 15:37:27 +01003721 case SHORTCUT_WIKIPEDIA_SEARCH:
3722 return URLUtil.composeSearchUrl(query, QuickSearch_W, QUERY_PLACE_HOLDER);
3723 case SHORTCUT_DICTIONARY_SEARCH:
3724 return URLUtil.composeSearchUrl(query, QuickSearch_D, QUERY_PLACE_HOLDER);
3725 case SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH:
The Android Open Source Project0c908882009-03-03 19:32:16 -08003726 // FIXME: we need location in this case
Satish Sampath565505b2009-05-29 15:37:27 +01003727 return URLUtil.composeSearchUrl(query, QuickSearch_L, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003728 }
3729 }
3730 } else {
Dan Egnor5ee906c2009-11-18 12:11:49 -08003731 if (Patterns.WEB_URL.matcher(inUrl).matches()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003732 return URLUtil.guessUrl(inUrl);
3733 }
3734 }
3735
3736 Browser.addSearchUrl(mResolver, inUrl);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07003737 return URLUtil.composeSearchUrl(inUrl, QuickSearch_G, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003738 }
3739
Ben Murdochbff2d602009-07-01 20:19:05 +01003740 /* package */ void setShouldShowErrorConsole(boolean flag) {
3741 if (flag == mShouldShowErrorConsole) {
3742 // Nothing to do.
3743 return;
3744 }
Leon Scroggins IIIa9e35b62010-09-16 15:30:15 -04003745 Tab t = mTabControl.getCurrentTab();
3746 if (t == null) {
3747 // There is no current tab so we cannot toggle the error console
3748 return;
3749 }
Ben Murdochbff2d602009-07-01 20:19:05 +01003750
3751 mShouldShowErrorConsole = flag;
3752
Leon Scroggins IIIa9e35b62010-09-16 15:30:15 -04003753 ErrorConsoleView errorConsole = t.getErrorConsole(true);
Ben Murdochbff2d602009-07-01 20:19:05 +01003754
3755 if (flag) {
3756 // Setting the show state of the console will cause it's the layout to be inflated.
3757 if (errorConsole.numberOfErrors() > 0) {
3758 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
3759 } else {
3760 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
3761 }
3762
3763 // Now we can add it to the main view.
3764 mErrorConsoleContainer.addView(errorConsole,
Romain Guy15b8ec62010-01-08 15:06:43 -08003765 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
Ben Murdochbff2d602009-07-01 20:19:05 +01003766 ViewGroup.LayoutParams.WRAP_CONTENT));
3767 } else {
3768 mErrorConsoleContainer.removeView(errorConsole);
3769 }
3770
3771 }
3772
Grace Kloba22ac16e2009-10-07 18:00:23 -07003773 boolean shouldShowErrorConsole() {
3774 return mShouldShowErrorConsole;
3775 }
3776
Andrei Popescu163ab742009-10-20 17:58:23 +01003777 private void setStatusBarVisibility(boolean visible) {
3778 int flag = visible ? 0 : WindowManager.LayoutParams.FLAG_FULLSCREEN;
3779 getWindow().setFlags(flag, WindowManager.LayoutParams.FLAG_FULLSCREEN);
3780 }
3781
Andrei Popescu56199cc2010-01-12 22:39:16 +00003782
3783 private void sendNetworkType(String type, String subtype) {
3784 WebView w = mTabControl.getCurrentWebView();
3785 if (w != null) {
3786 w.setNetworkType(type, subtype);
3787 }
3788 }
3789
Andrei Popescu30995e72010-02-09 16:59:58 +00003790 private void packageChanged(String packageName, boolean wasAdded) {
3791 WebView w = mTabControl.getCurrentWebView();
3792 if (w == null) {
3793 return;
3794 }
3795
3796 if (wasAdded) {
3797 w.addPackageName(packageName);
3798 } else {
3799 w.removePackageName(packageName);
3800 }
3801 }
3802
3803 private void addPackageNames(Set<String> packageNames) {
3804 WebView w = mTabControl.getCurrentWebView();
3805 if (w == null) {
3806 return;
3807 }
3808
3809 w.addPackageNames(packageNames);
3810 }
3811
3812 private void getInstalledPackages() {
3813 AsyncTask<Void, Void, Set<String> > task =
3814 new AsyncTask<Void, Void, Set<String> >() {
3815 protected Set<String> doInBackground(Void... unused) {
3816 Set<String> installedPackages = new HashSet<String>();
3817 PackageManager pm = BrowserActivity.this.getPackageManager();
3818 if (pm != null) {
3819 List<PackageInfo> packages = pm.getInstalledPackages(0);
3820 for (PackageInfo p : packages) {
3821 if (BrowserActivity.this.sGoogleApps.contains(p.packageName)) {
3822 installedPackages.add(p.packageName);
3823 }
3824 }
3825 }
3826
3827 return installedPackages;
3828 }
3829
3830 // Executes on the UI thread
3831 protected void onPostExecute(Set<String> installedPackages) {
3832 addPackageNames(installedPackages);
3833 }
3834 };
3835 task.execute();
3836 }
3837
Grace Klobaeb6eef42009-09-15 17:56:32 -07003838 final static int LOCK_ICON_UNSECURE = 0;
3839 final static int LOCK_ICON_SECURE = 1;
3840 final static int LOCK_ICON_MIXED = 2;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003841
The Android Open Source Project0c908882009-03-03 19:32:16 -08003842 private BrowserSettings mSettings;
3843 private TabControl mTabControl;
3844 private ContentResolver mResolver;
3845 private FrameLayout mContentView;
Andrei Popescuadc008d2009-06-26 14:11:30 +01003846 private View mCustomView;
3847 private FrameLayout mCustomViewContainer;
Andrei Popescuc9b55562009-07-07 10:51:15 +01003848 private WebChromeClient.CustomViewCallback mCustomViewCallback;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003849
3850 // FIXME, temp address onPrepareMenu performance problem. When we move everything out of
3851 // view, we should rewrite this.
3852 private int mCurrentMenuState = 0;
3853 private int mMenuState = R.id.MAIN_MENU;
Andrei Popescuadc008d2009-06-26 14:11:30 +01003854 private int mOldMenuState = EMPTY_MENU;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003855 private static final int EMPTY_MENU = -1;
3856 private Menu mMenu;
3857
3858 private FindDialog mFindDialog;
Cary Clark2c326e62010-08-19 18:40:57 -04003859 private SelectDialog mSelectDialog;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003860 // Used to prevent chording to result in firing two shortcuts immediately
3861 // one after another. Fixes bug 1211714.
3862 boolean mCanChord;
3863
3864 private boolean mInLoad;
3865 private boolean mIsNetworkUp;
Ben Murdochb7cc8b42009-09-28 10:59:09 +01003866 private boolean mDidStopLoad;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003867
Cary Clark1f10cbf2010-03-22 11:45:23 -04003868 /* package */ boolean mActivityInPause = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003869
3870 private boolean mMenuIsDown;
3871
The Android Open Source Project0c908882009-03-03 19:32:16 -08003872 private static boolean mInTrace;
3873
3874 // Performance probe
3875 private static final int[] SYSTEM_CPU_FORMAT = new int[] {
3876 Process.PROC_SPACE_TERM | Process.PROC_COMBINE,
3877 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 1: user time
3878 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 2: nice time
3879 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 3: sys time
3880 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 4: idle time
3881 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 5: iowait time
3882 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 6: irq time
3883 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG // 7: softirq time
3884 };
3885
3886 private long mStart;
3887 private long mProcessStart;
3888 private long mUserStart;
3889 private long mSystemStart;
3890 private long mIdleStart;
3891 private long mIrqStart;
3892
3893 private long mUiStart;
3894
3895 private Drawable mMixLockIcon;
3896 private Drawable mSecLockIcon;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003897
3898 /* hold a ref so we can auto-cancel if necessary */
3899 private AlertDialog mAlertDialog;
3900
The Android Open Source Project0c908882009-03-03 19:32:16 -08003901 // The up-to-date URL and title (these can be different from those stored
3902 // in WebView, since it takes some time for the information in WebView to
3903 // get updated)
3904 private String mUrl;
3905 private String mTitle;
3906
3907 // As PageInfo has different style for landscape / portrait, we have
3908 // to re-open it when configuration changed
3909 private AlertDialog mPageInfoDialog;
Grace Kloba22ac16e2009-10-07 18:00:23 -07003910 private Tab mPageInfoView;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003911 // If the Page-Info dialog is launched from the SSL-certificate-on-error
3912 // dialog, we should not just dismiss it, but should get back to the
3913 // SSL-certificate-on-error dialog. This flag is used to store this state
Leon Scrogginsc7b92f82010-01-11 18:17:31 -05003914 private boolean mPageInfoFromShowSSLCertificateOnError;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003915
3916 // as SSLCertificateOnError has different style for landscape / portrait,
3917 // we have to re-open it when configuration changed
3918 private AlertDialog mSSLCertificateOnErrorDialog;
3919 private WebView mSSLCertificateOnErrorView;
3920 private SslErrorHandler mSSLCertificateOnErrorHandler;
3921 private SslError mSSLCertificateOnErrorError;
3922
3923 // as SSLCertificate has different style for landscape / portrait, we
3924 // have to re-open it when configuration changed
3925 private AlertDialog mSSLCertificateDialog;
Grace Kloba22ac16e2009-10-07 18:00:23 -07003926 private Tab mSSLCertificateView;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003927
3928 // as HttpAuthentication has different style for landscape / portrait, we
3929 // have to re-open it when configuration changed
3930 private AlertDialog mHttpAuthenticationDialog;
3931 private HttpAuthHandler mHttpAuthHandler;
3932
3933 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_PARAMS =
3934 new FrameLayout.LayoutParams(
Romain Guy15b8ec62010-01-08 15:06:43 -08003935 ViewGroup.LayoutParams.MATCH_PARENT,
3936 ViewGroup.LayoutParams.MATCH_PARENT);
Andrei Popescuadc008d2009-06-26 14:11:30 +01003937 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_GRAVITY_CENTER =
3938 new FrameLayout.LayoutParams(
Romain Guy15b8ec62010-01-08 15:06:43 -08003939 ViewGroup.LayoutParams.MATCH_PARENT,
3940 ViewGroup.LayoutParams.MATCH_PARENT,
Andrei Popescuadc008d2009-06-26 14:11:30 +01003941 Gravity.CENTER);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07003942 // Google search
3943 final static String QuickSearch_G = "http://www.google.com/m?q=%s";
The Android Open Source Project0c908882009-03-03 19:32:16 -08003944 // Wikipedia search
3945 final static String QuickSearch_W = "http://en.wikipedia.org/w/index.php?search=%s&go=Go";
3946 // Dictionary search
3947 final static String QuickSearch_D = "http://dictionary.reference.com/search?q=%s";
3948 // Google Mobile Local search
3949 final static String QuickSearch_L = "http://www.google.com/m/search?site=local&q=%s&near=mountain+view";
3950
3951 final static String QUERY_PLACE_HOLDER = "%s";
3952
3953 // "source" parameter for Google search through search key
3954 final static String GOOGLE_SEARCH_SOURCE_SEARCHKEY = "browser-key";
3955 // "source" parameter for Google search through goto menu
3956 final static String GOOGLE_SEARCH_SOURCE_GOTO = "browser-goto";
3957 // "source" parameter for Google search through simplily type
3958 final static String GOOGLE_SEARCH_SOURCE_TYPE = "browser-type";
3959 // "source" parameter for Google search suggested by the browser
3960 final static String GOOGLE_SEARCH_SOURCE_SUGGEST = "browser-suggest";
3961 // "source" parameter for Google search from unknown source
3962 final static String GOOGLE_SEARCH_SOURCE_UNKNOWN = "unknown";
3963
3964 private final static String LOGTAG = "browser";
3965
The Android Open Source Project0c908882009-03-03 19:32:16 -08003966 private String mLastEnteredUrl;
3967
3968 private PowerManager.WakeLock mWakeLock;
3969 private final static int WAKELOCK_TIMEOUT = 5 * 60 * 1000; // 5 minutes
3970
3971 private Toast mStopToast;
3972
Leon Scroggins68579392009-09-15 15:31:54 -04003973 private TitleBar mTitleBar;
Leon Scroggins81db3662009-06-04 17:45:11 -04003974
Ben Murdochbff2d602009-07-01 20:19:05 +01003975 private LinearLayout mErrorConsoleContainer = null;
3976 private boolean mShouldShowErrorConsole = false;
3977
The Android Open Source Project0c908882009-03-03 19:32:16 -08003978 // As the ids are dynamically created, we can't guarantee that they will
3979 // be in sequence, so this static array maps ids to a window number.
3980 final static private int[] WINDOW_SHORTCUT_ID_ARRAY =
3981 { R.id.window_one_menu_id, R.id.window_two_menu_id, R.id.window_three_menu_id,
3982 R.id.window_four_menu_id, R.id.window_five_menu_id, R.id.window_six_menu_id,
3983 R.id.window_seven_menu_id, R.id.window_eight_menu_id };
3984
3985 // monitor platform changes
3986 private IntentFilter mNetworkStateChangedFilter;
3987 private BroadcastReceiver mNetworkStateIntentReceiver;
3988
Grace Klobab4da0ad2009-05-14 14:45:40 -07003989 private BroadcastReceiver mPackageInstallationReceiver;
3990
Bjorn Bringerta7611812010-03-24 11:12:02 +00003991 private SystemAllowGeolocationOrigins mSystemAllowGeolocationOrigins;
3992
The Android Open Source Project0c908882009-03-03 19:32:16 -08003993 // activity requestCode
Nicolas Roard78a98e42009-05-11 13:34:17 +01003994 final static int COMBO_PAGE = 1;
Nicolas Roard78a98e42009-05-11 13:34:17 +01003995 final static int PREFERENCES_PAGE = 3;
Leon Scroggins8d5fa432009-10-02 15:55:59 -04003996 final static int FILE_SELECTED = 4;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003997
Andrei Popescu540035d2009-09-18 18:59:20 +01003998 // the default <video> poster
3999 private Bitmap mDefaultVideoPoster;
4000 // the video progress view
4001 private View mVideoProgressView;
4002
Andrei Popescu30995e72010-02-09 16:59:58 +00004003 // The Google packages we monitor for the navigator.isApplicationInstalled()
4004 // API. Add as needed.
4005 private static Set<String> sGoogleApps;
4006 static {
4007 sGoogleApps = new HashSet<String>();
4008 sGoogleApps.add("com.google.android.youtube");
4009 }
4010
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004011 /**
4012 * A UrlData class to abstract how the content will be set to WebView.
4013 * This base class uses loadUrl to show the content.
4014 */
Leon Scroggins6eac63e2010-03-15 18:19:14 -04004015 /* package */ static class UrlData {
Grace Kloba068e48b2010-01-26 18:11:27 -08004016 final String mUrl;
4017 final Map<String, String> mHeaders;
Leon Scroggins58d56c62010-01-28 15:12:40 -05004018 final Intent mVoiceIntent;
Grace Kloba60e095c2009-06-16 11:50:55 -07004019
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004020 UrlData(String url) {
4021 this.mUrl = url;
Grace Kloba068e48b2010-01-26 18:11:27 -08004022 this.mHeaders = null;
Leon Scroggins58d56c62010-01-28 15:12:40 -05004023 this.mVoiceIntent = null;
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004024 }
Grace Kloba60e095c2009-06-16 11:50:55 -07004025
Leon Scroggins58d56c62010-01-28 15:12:40 -05004026 UrlData(String url, Map<String, String> headers, Intent intent) {
Grace Kloba068e48b2010-01-26 18:11:27 -08004027 this.mUrl = url;
4028 this.mHeaders = headers;
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -05004029 if (RecognizerResultsIntent.ACTION_VOICE_SEARCH_RESULTS
4030 .equals(intent.getAction())) {
Leon Scroggins58d56c62010-01-28 15:12:40 -05004031 this.mVoiceIntent = intent;
4032 } else {
4033 this.mVoiceIntent = null;
4034 }
Grace Kloba60e095c2009-06-16 11:50:55 -07004035 }
4036
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004037 boolean isEmpty() {
Leon Scroggins58d56c62010-01-28 15:12:40 -05004038 return mVoiceIntent == null && (mUrl == null || mUrl.length() == 0);
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004039 }
4040
Leon Scroggins92472e82010-02-17 16:32:28 -05004041 /**
4042 * Load this UrlData into the given Tab. Use loadUrlDataIn to update
4043 * the title bar as well.
4044 */
Leon Scroggins58d56c62010-01-28 15:12:40 -05004045 public void loadIn(Tab t) {
4046 if (mVoiceIntent != null) {
4047 t.activateVoiceSearchMode(mVoiceIntent);
4048 } else {
4049 t.getWebView().loadUrl(mUrl, mHeaders);
4050 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004051 }
4052 };
4053
Leon Scroggins1f005d32009-08-10 17:36:42 -04004054 /* package */ static final UrlData EMPTY_URL_DATA = new UrlData(null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004055}