blob: a2c2f32c2348773ca25ab8aa8438abb144cbbbd2 [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
Michael Kolbed217742010-08-10 17:52:34 -070019import android.app.ActionBar;
The Android Open Source Project0c908882009-03-03 19:32:16 -080020import android.app.Activity;
The Android Open Source Project0c908882009-03-03 19:32:16 -080021import android.app.AlertDialog;
22import android.app.ProgressDialog;
23import android.app.SearchManager;
24import android.content.ActivityNotFoundException;
25import android.content.BroadcastReceiver;
Dianne Hackborn80f32622010-08-05 14:17:53 -070026import android.content.ClipboardManager;
The Android Open Source Project0c908882009-03-03 19:32:16 -080027import android.content.ComponentName;
Leon Scroggins58d56c62010-01-28 15:12:40 -050028import android.content.ContentProvider;
29import android.content.ContentProviderClient;
The Android Open Source Project0c908882009-03-03 19:32:16 -080030import android.content.ContentResolver;
Leon Scrogginsb6b7f9e2009-06-18 12:05:28 -040031import android.content.ContentUris;
The Android Open Source Project0c908882009-03-03 19:32:16 -080032import android.content.ContentValues;
33import android.content.Context;
34import android.content.DialogInterface;
35import android.content.Intent;
36import android.content.IntentFilter;
Grace Klobab4da0ad2009-05-14 14:45:40 -070037import android.content.pm.PackageInfo;
The Android Open Source Project0c908882009-03-03 19:32:16 -080038import android.content.pm.PackageManager;
39import android.content.pm.ResolveInfo;
The Android Open Source Project0c908882009-03-03 19:32:16 -080040import android.content.res.Configuration;
41import android.content.res.Resources;
42import android.database.Cursor;
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;
The Android Open Source Project0c908882009-03-03 19:32:16 -080048import android.graphics.drawable.Drawable;
The Android Open Source Project0c908882009-03-03 19:32:16 -080049import android.net.ConnectivityManager;
Andrei Popescu56199cc2010-01-12 22:39:16 +000050import android.net.NetworkInfo;
The Android Open Source Project0c908882009-03-03 19:32:16 -080051import android.net.Uri;
52import android.net.WebAddress;
The Android Open Source Project0c908882009-03-03 19:32:16 -080053import android.net.http.SslCertificate;
54import android.net.http.SslError;
55import android.os.AsyncTask;
56import android.os.Bundle;
57import android.os.Debug;
58import android.os.Environment;
59import android.os.Handler;
The Android Open Source Project0c908882009-03-03 19:32:16 -080060import android.os.Message;
61import android.os.PowerManager;
62import android.os.Process;
The Android Open Source Project0c908882009-03-03 19:32:16 -080063import android.os.SystemClock;
The Android Open Source Project0c908882009-03-03 19:32:16 -080064import android.provider.Browser;
Cary Clark5e335a32009-09-22 14:53:11 -040065import android.provider.ContactsContract;
Michael Kolba2b2ba82010-08-04 17:54:03 -070066import android.provider.ContactsContract.Intents.Insert;
The Android Open Source Project0c908882009-03-03 19:32:16 -080067import android.provider.Downloads;
68import android.provider.MediaStore;
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -050069import android.speech.RecognizerResultsIntent;
The Android Open Source Project0c908882009-03-03 19:32:16 -080070import android.text.TextUtils;
71import android.text.format.DateFormat;
The Android Open Source Project0c908882009-03-03 19:32:16 -080072import android.util.Log;
Dianne Hackborn385effd2010-02-24 20:03:04 -080073import android.util.Patterns;
The Android Open Source Project0c908882009-03-03 19:32:16 -080074import android.view.ContextMenu;
Michael Kolba2b2ba82010-08-04 17:54:03 -070075import android.view.ContextMenu.ContextMenuInfo;
The Android Open Source Project0c908882009-03-03 19:32:16 -080076import android.view.Gravity;
77import android.view.KeyEvent;
78import android.view.LayoutInflater;
79import android.view.Menu;
80import android.view.MenuInflater;
81import android.view.MenuItem;
Michael Kolba2b2ba82010-08-04 17:54:03 -070082import android.view.MenuItem.OnMenuItemClickListener;
The Android Open Source Project0c908882009-03-03 19:32:16 -080083import android.view.View;
84import android.view.ViewGroup;
85import android.view.Window;
86import android.view.WindowManager;
Svetoslav Ganov2b345992010-05-06 06:13:54 -070087import android.view.accessibility.AccessibilityManager;
The Android Open Source Project0c908882009-03-03 19:32:16 -080088import android.webkit.CookieManager;
89import android.webkit.CookieSyncManager;
90import android.webkit.DownloadListener;
91import android.webkit.HttpAuthHandler;
Grace Klobab4da0ad2009-05-14 14:45:40 -070092import android.webkit.PluginManager;
The Android Open Source Project0c908882009-03-03 19:32:16 -080093import android.webkit.SslErrorHandler;
94import android.webkit.URLUtil;
Leon Clarkecb6cc862009-09-29 18:35:13 +010095import android.webkit.ValueCallback;
The Android Open Source Project0c908882009-03-03 19:32:16 -080096import android.webkit.WebChromeClient;
97import android.webkit.WebHistoryItem;
98import android.webkit.WebIconDatabase;
99import android.webkit.WebView;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800100import android.widget.EditText;
101import android.widget.FrameLayout;
102import android.widget.LinearLayout;
103import android.widget.TextView;
104import android.widget.Toast;
105
Michael Kolba2b2ba82010-08-04 17:54:03 -0700106import com.android.browser.ScrollWebView.ScrollListener;
Bjorn Bringert10d1cca2010-02-10 14:22:12 +0000107import com.android.common.Search;
Leon Scroggins1fe13a52010-02-09 15:31:26 -0500108import com.android.common.speech.LoggingEvents;
Dan Egnor5ee906c2009-11-18 12:11:49 -0800109
Leon Scrogginsb6b7f9e2009-06-18 12:05:28 -0400110import java.io.ByteArrayOutputStream;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800111import java.io.File;
Ben Murdoch4f75ba22009-10-27 11:48:28 +0000112import java.io.IOException;
113import java.io.InputStream;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800114import java.net.MalformedURLException;
Dianne Hackborn99189432009-06-17 18:06:18 -0700115import java.net.URISyntaxException;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800116import java.net.URL;
117import java.net.URLEncoder;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800118import java.util.Date;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800119import java.util.HashMap;
Andrei Popescu30995e72010-02-09 16:59:58 +0000120import java.util.HashSet;
Grace Kloba00f54c52010-01-27 14:53:51 -0800121import java.util.Iterator;
Andrei Popescu30995e72010-02-09 16:59:58 +0000122import java.util.List;
Grace Kloba068e48b2010-01-26 18:11:27 -0800123import java.util.Map;
Andrei Popescu30995e72010-02-09 16:59:58 +0000124import java.util.Set;
Michael Kolbfe251992010-07-08 15:41:55 -0700125import java.util.Vector;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800126import java.util.regex.Matcher;
127import java.util.regex.Pattern;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800128
129public class BrowserActivity extends Activity
Shimeng (Simon) Wang98d5fce2010-03-16 13:23:39 -0700130 implements View.OnCreateContextMenuListener, DownloadListener {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800131
Dave Bort31a6d1c2009-04-13 15:56:49 -0700132 /* Define some aliases to make these debugging flags easier to refer to.
133 * This file imports android.provider.Browser, so we can't just refer to "Browser.DEBUG".
134 */
135 private final static boolean DEBUG = com.android.browser.Browser.DEBUG;
136 private final static boolean LOGV_ENABLED = com.android.browser.Browser.LOGV_ENABLED;
137 private final static boolean LOGD_ENABLED = com.android.browser.Browser.LOGD_ENABLED;
138
Satish Sampath565505b2009-05-29 15:37:27 +0100139 // These are single-character shortcuts for searching popular sources.
140 private static final int SHORTCUT_INVALID = 0;
141 private static final int SHORTCUT_GOOGLE_SEARCH = 1;
142 private static final int SHORTCUT_WIKIPEDIA_SEARCH = 2;
143 private static final int SHORTCUT_DICTIONARY_SEARCH = 3;
144 private static final int SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH = 4;
145
Cary Clarka9771242009-08-11 16:42:26 -0400146 private static class ClearThumbnails extends AsyncTask<File, Void, Void> {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800147 @Override
148 public Void doInBackground(File... files) {
149 if (files != null) {
150 for (File f : files) {
Cary Clarkd6be1752009-08-12 12:56:42 -0400151 if (!f.delete()) {
152 Log.e(LOGTAG, f.getPath() + " was not deleted");
153 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800154 }
155 }
156 return null;
157 }
158 }
159
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400160 /**
161 * This layout holds everything you see below the status bar, including the
162 * error console, the custom view container, and the webviews.
163 */
164 private FrameLayout mBrowserFrameLayout;
Leon Scroggins81db3662009-06-04 17:45:11 -0400165
Leon Scrogginsd746a942010-05-19 13:21:44 -0400166 private boolean mXLargeScreenSize;
167
Grace Kloba22ac16e2009-10-07 18:00:23 -0700168 @Override
169 public void onCreate(Bundle icicle) {
Dave Bort31a6d1c2009-04-13 15:56:49 -0700170 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800171 Log.v(LOGTAG, this + " onStart");
172 }
173 super.onCreate(icicle);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800174 // test the browser in OpenGL
175 // requestWindowFeature(Window.FEATURE_OPENGL);
176
Mike Reedd334bf52010-01-26 15:21:44 -0500177 // enable this to test the browser in 32bit
178 if (false) {
179 getWindow().setFormat(PixelFormat.RGBX_8888);
180 BitmapFactory.setDefaultConfig(Bitmap.Config.ARGB_8888);
181 }
182
Svetoslav Ganov2b345992010-05-06 06:13:54 -0700183 if (AccessibilityManager.getInstance(this).isEnabled()) {
184 setDefaultKeyMode(DEFAULT_KEYS_DISABLE);
185 } else {
186 setDefaultKeyMode(DEFAULT_KEYS_SEARCH_LOCAL);
187 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800188
189 mResolver = getContentResolver();
190
Grace Kloba0923d692009-09-23 21:37:25 -0700191 // If this was a web search request, pass it on to the default web
192 // search provider and finish this activity.
193 if (handleWebSearchIntent(getIntent())) {
194 finish();
195 return;
196 }
197
The Android Open Source Project0c908882009-03-03 19:32:16 -0800198 mSecLockIcon = Resources.getSystem().getDrawable(
199 android.R.drawable.ic_secure);
200 mMixLockIcon = Resources.getSystem().getDrawable(
201 android.R.drawable.ic_partial_secure);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800202
Michael Kolbed217742010-08-10 17:52:34 -0700203 // Create the tab control and our initial tab
204 mTabControl = new TabControl(this);
205
206 mXLargeScreenSize = (getResources().getConfiguration().screenLayout
207 & Configuration.SCREENLAYOUT_SIZE_MASK)
208 == Configuration.SCREENLAYOUT_SIZE_XLARGE;
209
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);
Michael Kolbe0a36662010-06-29 10:37:12 -0700221
Leon Scrogginsd746a942010-05-19 13:21:44 -0400222 if (mXLargeScreenSize) {
Michael Kolba2b2ba82010-08-04 17:54:03 -0700223 mTitleBar = new TitleBarXLarge(this);
224 mTitleBar.setProgress(100);
225 mFakeTitleBar = new TitleBarXLarge(this);
Michael Kolbed217742010-08-10 17:52:34 -0700226 ActionBar actionBar = getActionBar();
Michael Kolba2b2ba82010-08-04 17:54:03 -0700227 mTabBar = new TabBar(this, mTabControl, (TitleBarXLarge) mFakeTitleBar);
Michael Kolbed217742010-08-10 17:52:34 -0700228 actionBar.setCustomNavigationMode(mTabBar);
Leon Scrogginsd746a942010-05-19 13:21:44 -0400229 } else {
Leon Scroggins571b3762010-05-26 10:25:01 -0400230 mTitleBar = new TitleBar(this);
Leon Scrogginsd746a942010-05-19 13:21:44 -0400231 // mTitleBar will be always be shown in the fully loaded mode on
232 // phone
233 mTitleBar.setProgress(100);
Leon Scrogginsd746a942010-05-19 13:21:44 -0400234 mFakeTitleBar = new TitleBar(this);
235 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800236
The Android Open Source Project0c908882009-03-03 19:32:16 -0800237 // Open the icon database and retain all the bookmark urls for favicons
238 retainIconsOnStartup();
239
240 // Keep a settings instance handy.
241 mSettings = BrowserSettings.getInstance();
242 mSettings.setTabControl(mTabControl);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800243
244 PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
245 mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Browser");
246
Patrick Scott6adacc92010-03-05 08:24:51 -0500247 // Find out if the network is currently up.
248 ConnectivityManager cm = (ConnectivityManager) getSystemService(
249 Context.CONNECTIVITY_SERVICE);
250 NetworkInfo info = cm.getActiveNetworkInfo();
251 if (info != null) {
252 mIsNetworkUp = info.isAvailable();
253 }
254
Grace Klobaa34f6862009-07-31 16:28:17 -0700255 /* enables registration for changes in network status from
256 http stack */
257 mNetworkStateChangedFilter = new IntentFilter();
258 mNetworkStateChangedFilter.addAction(
259 ConnectivityManager.CONNECTIVITY_ACTION);
260 mNetworkStateIntentReceiver = new BroadcastReceiver() {
261 @Override
262 public void onReceive(Context context, Intent intent) {
263 if (intent.getAction().equals(
264 ConnectivityManager.CONNECTIVITY_ACTION)) {
Andrei Popescue4c98462010-02-19 15:44:13 +0000265
266 NetworkInfo info = intent.getParcelableExtra(
267 ConnectivityManager.EXTRA_NETWORK_INFO);
268 String typeName = info.getTypeName();
269 String subtypeName = info.getSubtypeName();
270 sendNetworkType(typeName.toLowerCase(),
271 (subtypeName != null ? subtypeName.toLowerCase() : ""));
272
273 onNetworkToggle(info.isAvailable());
Grace Klobaa34f6862009-07-31 16:28:17 -0700274 }
275 }
276 };
277
Grace Kloba615c6c92009-08-03 10:22:44 -0700278 IntentFilter filter = new IntentFilter(Intent.ACTION_PACKAGE_ADDED);
279 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
280 filter.addDataScheme("package");
281 mPackageInstallationReceiver = new BroadcastReceiver() {
282 @Override
283 public void onReceive(Context context, Intent intent) {
284 final String action = intent.getAction();
285 final String packageName = intent.getData()
286 .getSchemeSpecificPart();
287 final boolean replacing = intent.getBooleanExtra(
288 Intent.EXTRA_REPLACING, false);
289 if (Intent.ACTION_PACKAGE_REMOVED.equals(action) && replacing) {
290 // if it is replacing, refreshPlugins() when adding
291 return;
292 }
Andrei Popescu30995e72010-02-09 16:59:58 +0000293
294 if (sGoogleApps.contains(packageName)) {
295 BrowserActivity.this.packageChanged(packageName,
296 Intent.ACTION_PACKAGE_ADDED.equals(action));
297 }
298
Grace Kloba615c6c92009-08-03 10:22:44 -0700299 PackageManager pm = BrowserActivity.this.getPackageManager();
300 PackageInfo pkgInfo = null;
301 try {
302 pkgInfo = pm.getPackageInfo(packageName,
303 PackageManager.GET_PERMISSIONS);
304 } catch (PackageManager.NameNotFoundException e) {
305 return;
306 }
307 if (pkgInfo != null) {
308 String permissions[] = pkgInfo.requestedPermissions;
309 if (permissions == null) {
310 return;
311 }
312 boolean permissionOk = false;
313 for (String permit : permissions) {
314 if (PluginManager.PLUGIN_PERMISSION.equals(permit)) {
315 permissionOk = true;
316 break;
317 }
318 }
319 if (permissionOk) {
320 PluginManager.getInstance(BrowserActivity.this)
Grace Klobae56a0f22010-05-26 17:31:02 -0700321 .refreshPlugins(true);
Grace Kloba615c6c92009-08-03 10:22:44 -0700322 }
323 }
324 }
325 };
326 registerReceiver(mPackageInstallationReceiver, filter);
327
The Android Open Source Project0c908882009-03-03 19:32:16 -0800328 if (!mTabControl.restoreState(icicle)) {
329 // clear up the thumbnail directory if we can't restore the state as
330 // none of the files in the directory are referenced any more.
331 new ClearThumbnails().execute(
332 mTabControl.getThumbnailDir().listFiles());
Grace Klobaaab3f092009-07-30 12:29:51 -0700333 // there is no quit on Android. But if we can't restore the state,
334 // we can treat it as a new Browser, remove the old session cookies.
335 CookieManager.getInstance().removeSessionCookie();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800336 final Intent intent = getIntent();
337 final Bundle extra = intent.getExtras();
338 // Create an initial tab.
339 // If the intent is ACTION_VIEW and data is not null, the Browser is
340 // invoked to view the content by another application. In this case,
341 // the tab will be close when exit.
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700342 UrlData urlData = getUrlDataFromIntent(intent);
343
Leon Scroggins58d56c62010-01-28 15:12:40 -0500344 String action = intent.getAction();
Grace Kloba22ac16e2009-10-07 18:00:23 -0700345 final Tab t = mTabControl.createNewTab(
Leon Scroggins58d56c62010-01-28 15:12:40 -0500346 (Intent.ACTION_VIEW.equals(action) &&
347 intent.getData() != null)
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -0500348 || RecognizerResultsIntent.ACTION_VOICE_SEARCH_RESULTS
349 .equals(action),
Elliott Slaughterf0f03952010-07-14 18:10:36 -0700350 intent.getStringExtra(Browser.EXTRA_APPLICATION_ID),
351 urlData.mUrl, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800352 mTabControl.setCurrentTab(t);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800353 attachTabToContentView(t);
354 WebView webView = t.getWebView();
355 if (extra != null) {
356 int scale = extra.getInt(Browser.INITIAL_ZOOM_LEVEL, 0);
357 if (scale > 0 && scale <= 1000) {
358 webView.setInitialScale(scale);
359 }
360 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800361
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700362 if (urlData.isEmpty()) {
Shimeng (Simon) Wang98d5fce2010-03-16 13:23:39 -0700363 loadUrl(webView, mSettings.getHomePage());
The Android Open Source Project0c908882009-03-03 19:32:16 -0800364 } else {
Patrick Scott9d53da02010-02-19 10:19:01 -0500365 loadUrlDataIn(t, urlData);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800366 }
367 } else {
368 // TabControl.restoreState() will create a new tab even if
Leon Scroggins1f005d32009-08-10 17:36:42 -0400369 // restoring the state fails.
The Android Open Source Project0c908882009-03-03 19:32:16 -0800370 attachTabToContentView(mTabControl.getCurrentTab());
371 }
Grace Kloba615c6c92009-08-03 10:22:44 -0700372
Cary Clarkb4b83182010-07-01 12:36:56 -0400373 // Delete old thumbnails to save space
374 File dir = mTabControl.getThumbnailDir();
375 if (dir.exists()) {
376 for (String child : dir.list()) {
377 File f = new File(dir, child);
378 f.delete();
379 }
380 }
381
Feng Qianb3c02da2009-06-29 15:58:08 -0700382 // Read JavaScript flags if it exists.
383 String jsFlags = mSettings.getJsFlags();
384 if (jsFlags.trim().length() != 0) {
385 mTabControl.getCurrentWebView().setJsFlags(jsFlags);
386 }
Andrei Popescu30995e72010-02-09 16:59:58 +0000387 // Work out which packages are installed on the system.
388 getInstalledPackages();
Bjorn Bringerta7611812010-03-24 11:12:02 +0000389
390 // Start watching the default geolocation permissions
391 mSystemAllowGeolocationOrigins
392 = new SystemAllowGeolocationOrigins(getApplicationContext());
393 mSystemAllowGeolocationOrigins.start();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800394 }
395
Michael Kolba2b2ba82010-08-04 17:54:03 -0700396 ScrollListener getScrollListener() {
397 return mTabBar;
398 }
399
Leon Scroggins58d56c62010-01-28 15:12:40 -0500400 /**
401 * Feed the previously stored results strings to the BrowserProvider so that
402 * the SearchDialog will show them instead of the standard searches.
403 * @param result String to show on the editable line of the SearchDialog.
404 */
405 /* package */ void showVoiceSearchResults(String result) {
406 ContentProviderClient client = mResolver.acquireContentProviderClient(
407 Browser.BOOKMARKS_URI);
408 ContentProvider prov = client.getLocalContentProvider();
409 BrowserProvider bp = (BrowserProvider) prov;
410 bp.setQueryResults(mTabControl.getCurrentTab().getVoiceSearchResults());
411 client.release();
412
Leon Scrogginsfbb3f152010-03-09 17:26:56 -0500413 Bundle bundle = createGoogleSearchSourceBundle(
414 GOOGLE_SEARCH_SOURCE_SEARCHKEY);
415 bundle.putBoolean(SearchManager.CONTEXT_IS_VOICE, true);
416 startSearch(result, false, bundle, false);
Leon Scroggins58d56c62010-01-28 15:12:40 -0500417 }
418
The Android Open Source Project0c908882009-03-03 19:32:16 -0800419 @Override
420 protected void onNewIntent(Intent intent) {
Grace Kloba22ac16e2009-10-07 18:00:23 -0700421 Tab current = mTabControl.getCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800422 // When a tab is closed on exit, the current tab index is set to -1.
423 // Reset before proceed as Browser requires the current tab to be set.
424 if (current == null) {
425 // Try to reset the tab in case the index was incorrect.
426 current = mTabControl.getTab(0);
427 if (current == null) {
428 // No tabs at all so just ignore this intent.
429 return;
430 }
431 mTabControl.setCurrentTab(current);
432 attachTabToContentView(current);
433 resetTitleAndIcon(current.getWebView());
434 }
435 final String action = intent.getAction();
436 final int flags = intent.getFlags();
437 if (Intent.ACTION_MAIN.equals(action) ||
438 (flags & Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY) != 0) {
439 // just resume the browser
440 return;
441 }
Leon Scrogginsb8a844d2010-03-18 15:06:15 -0400442 // In case the SearchDialog is open.
443 ((SearchManager) getSystemService(Context.SEARCH_SERVICE))
444 .stopSearch();
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -0500445 boolean activateVoiceSearch = RecognizerResultsIntent
446 .ACTION_VOICE_SEARCH_RESULTS.equals(action);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800447 if (Intent.ACTION_VIEW.equals(action)
448 || Intent.ACTION_SEARCH.equals(action)
449 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
Leon Scroggins58d56c62010-01-28 15:12:40 -0500450 || Intent.ACTION_WEB_SEARCH.equals(action)
451 || activateVoiceSearch) {
Leon Scroggins3b18ce32010-02-08 17:35:59 -0500452 if (current.isInVoiceSearchMode()) {
453 String title = current.getVoiceDisplayTitle();
454 if (title != null && title.equals(intent.getStringExtra(
455 SearchManager.QUERY))) {
456 // The user submitted the same search as the last voice
457 // search, so do nothing.
458 return;
459 }
Leon Scroggins1fe13a52010-02-09 15:31:26 -0500460 if (Intent.ACTION_SEARCH.equals(action)
461 && current.voiceSearchSourceIsGoogle()) {
462 Intent logIntent = new Intent(
463 LoggingEvents.ACTION_LOG_EVENT);
464 logIntent.putExtra(LoggingEvents.EXTRA_EVENT,
465 LoggingEvents.VoiceSearch.QUERY_UPDATED);
466 logIntent.putExtra(
467 LoggingEvents.VoiceSearch.EXTRA_QUERY_UPDATED_VALUE,
468 intent.getDataString());
469 sendBroadcast(logIntent);
470 // Note, onPageStarted will revert the voice title bar
471 // When http://b/issue?id=2379215 is fixed, we should update
472 // the title bar here.
473 }
Leon Scroggins3b18ce32010-02-08 17:35:59 -0500474 }
Satish Sampath565505b2009-05-29 15:37:27 +0100475 // If this was a search request (e.g. search query directly typed into the address bar),
476 // pass it on to the default web search provider.
477 if (handleWebSearchIntent(intent)) {
478 return;
479 }
480
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700481 UrlData urlData = getUrlDataFromIntent(intent);
482 if (urlData.isEmpty()) {
483 urlData = new UrlData(mSettings.getHomePage());
The Android Open Source Project0c908882009-03-03 19:32:16 -0800484 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700485
Grace Klobacc634032009-07-28 15:58:19 -0700486 final String appId = intent
487 .getStringExtra(Browser.EXTRA_APPLICATION_ID);
Leon Scroggins47208682010-04-07 17:59:48 -0400488 if ((Intent.ACTION_VIEW.equals(action)
489 // If a voice search has no appId, it means that it came
490 // from the browser. In that case, reuse the current tab.
491 || (activateVoiceSearch && appId != null))
Grace Klobacc634032009-07-28 15:58:19 -0700492 && !getPackageName().equals(appId)
493 && (flags & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0) {
Grace Kloba22ac16e2009-10-07 18:00:23 -0700494 Tab appTab = mTabControl.getTabFromId(appId);
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700495 if (appTab != null) {
496 Log.i(LOGTAG, "Reusing tab for " + appId);
497 // Dismiss the subwindow if applicable.
498 dismissSubWindow(appTab);
499 // Since we might kill the WebView, remove it from the
500 // content view first.
501 removeTabFromContentView(appTab);
502 // Recreate the main WebView after destroying the old one.
503 // If the WebView has the same original url and is on that
504 // page, it can be reused.
505 boolean needsLoad =
Leon Scroggins6eac63e2010-03-15 18:19:14 -0400506 mTabControl.recreateWebView(appTab, urlData);
Ben Murdochbff2d602009-07-01 20:19:05 +0100507
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700508 if (current != appTab) {
Leon Scroggins1f005d32009-08-10 17:36:42 -0400509 switchToTab(mTabControl.getTabIndex(appTab));
510 if (needsLoad) {
Patrick Scott9d53da02010-02-19 10:19:01 -0500511 loadUrlDataIn(appTab, urlData);
Leon Scroggins1f005d32009-08-10 17:36:42 -0400512 }
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700513 } else {
Leon Scroggins1f005d32009-08-10 17:36:42 -0400514 // If the tab was the current tab, we have to attach
515 // it to the view system again.
516 attachTabToContentView(appTab);
517 if (needsLoad) {
Patrick Scott9d53da02010-02-19 10:19:01 -0500518 loadUrlDataIn(appTab, urlData);
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700519 }
520 }
521 return;
Patrick Scottcd115892009-07-16 09:42:58 -0400522 } else {
523 // No matching application tab, try to find a regular tab
524 // with a matching url.
525 appTab = mTabControl.findUnusedTabWithUrl(urlData.mUrl);
Leon Scroggins25515f82009-08-19 15:31:58 -0400526 if (appTab != null) {
527 if (current != appTab) {
528 switchToTab(mTabControl.getTabIndex(appTab));
529 }
530 // Otherwise, we are already viewing the correct tab.
Patrick Scottcd115892009-07-16 09:42:58 -0400531 } else {
532 // if FLAG_ACTIVITY_BROUGHT_TO_FRONT flag is on, the url
533 // will be opened in a new tab unless we have reached
534 // MAX_TABS. Then the url will be opened in the current
535 // tab. If a new tab is created, it will have "true" for
536 // exit on close.
Leon Scroggins1f005d32009-08-10 17:36:42 -0400537 openTabAndShow(urlData, true, appId);
Patrick Scottcd115892009-07-16 09:42:58 -0400538 }
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700539 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800540 } else {
Grace Kloba638d3f42009-11-23 10:35:04 -0800541 if (!urlData.isEmpty()
542 && urlData.mUrl.startsWith("about:debug")) {
543 if ("about:debug.dom".equals(urlData.mUrl)) {
544 current.getWebView().dumpDomTree(false);
545 } else if ("about:debug.dom.file".equals(urlData.mUrl)) {
546 current.getWebView().dumpDomTree(true);
547 } else if ("about:debug.render".equals(urlData.mUrl)) {
548 current.getWebView().dumpRenderTree(false);
549 } else if ("about:debug.render.file".equals(urlData.mUrl)) {
550 current.getWebView().dumpRenderTree(true);
551 } else if ("about:debug.display".equals(urlData.mUrl)) {
552 current.getWebView().dumpDisplayTree();
Mike Reed9b78e1d2010-01-13 14:40:52 -0800553 } else if (urlData.mUrl.startsWith("about:debug.drag")) {
554 int index = urlData.mUrl.codePointAt(16) - '0';
555 if (index <= 0 || index > 9) {
556 current.getWebView().setDragTracker(null);
557 } else {
558 current.getWebView().setDragTracker(new MeshTracker(index));
559 }
Grace Kloba638d3f42009-11-23 10:35:04 -0800560 } else {
561 mSettings.toggleDebugSettings();
562 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800563 return;
564 }
Leon Scroggins1f005d32009-08-10 17:36:42 -0400565 // Get rid of the subwindow if it exists
566 dismissSubWindow(current);
Leon Scroggins8588d152010-04-15 11:01:53 -0400567 // If the current Tab is being used as an application tab,
568 // remove the association, since the new Intent means that it is
569 // no longer associated with that application.
570 current.setAppId(null);
Patrick Scott9d53da02010-02-19 10:19:01 -0500571 loadUrlDataIn(current, urlData);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800572 }
573 }
574 }
575
Satish Sampath565505b2009-05-29 15:37:27 +0100576 private int parseUrlShortcut(String url) {
577 if (url == null) return SHORTCUT_INVALID;
578
579 // FIXME: quick search, need to be customized by setting
580 if (url.length() > 2 && url.charAt(1) == ' ') {
581 switch (url.charAt(0)) {
582 case 'g': return SHORTCUT_GOOGLE_SEARCH;
583 case 'w': return SHORTCUT_WIKIPEDIA_SEARCH;
584 case 'd': return SHORTCUT_DICTIONARY_SEARCH;
585 case 'l': return SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH;
586 }
587 }
588 return SHORTCUT_INVALID;
589 }
590
591 /**
592 * Launches the default web search activity with the query parameters if the given intent's data
593 * are identified as plain search terms and not URLs/shortcuts.
594 * @return true if the intent was handled and web search activity was launched, false if not.
595 */
596 private boolean handleWebSearchIntent(Intent intent) {
597 if (intent == null) return false;
598
599 String url = null;
600 final String action = intent.getAction();
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -0500601 if (RecognizerResultsIntent.ACTION_VOICE_SEARCH_RESULTS.equals(
602 action)) {
Leon Scroggins58d56c62010-01-28 15:12:40 -0500603 return false;
604 }
Satish Sampath565505b2009-05-29 15:37:27 +0100605 if (Intent.ACTION_VIEW.equals(action)) {
Grace Kloba1e705052009-09-29 13:13:36 -0700606 Uri data = intent.getData();
607 if (data != null) url = data.toString();
Satish Sampath565505b2009-05-29 15:37:27 +0100608 } else if (Intent.ACTION_SEARCH.equals(action)
609 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
610 || Intent.ACTION_WEB_SEARCH.equals(action)) {
611 url = intent.getStringExtra(SearchManager.QUERY);
612 }
Bjorn Bringert04851702009-09-22 10:36:01 +0100613 return handleWebSearchRequest(url, intent.getBundleExtra(SearchManager.APP_DATA),
614 intent.getStringExtra(SearchManager.EXTRA_DATA_KEY));
Satish Sampath565505b2009-05-29 15:37:27 +0100615 }
616
617 /**
618 * Launches the default web search activity with the query parameters if the given url string
619 * was identified as plain search terms and not URL/shortcut.
620 * @return true if the request was handled and web search activity was launched, false if not.
621 */
Bjorn Bringert04851702009-09-22 10:36:01 +0100622 private boolean handleWebSearchRequest(String inUrl, Bundle appData, String extraData) {
Satish Sampath565505b2009-05-29 15:37:27 +0100623 if (inUrl == null) return false;
624
625 // In general, we shouldn't modify URL from Intent.
626 // But currently, we get the user-typed URL from search box as well.
627 String url = fixUrl(inUrl).trim();
628
629 // URLs and site specific search shortcuts are handled by the regular flow of control, so
630 // return early.
Dan Egnor5ee906c2009-11-18 12:11:49 -0800631 if (Patterns.WEB_URL.matcher(url).matches()
Satish Sampathbc5b9f32009-06-04 18:21:40 +0100632 || ACCEPTED_URI_SCHEMA.matcher(url).matches()
Satish Sampath565505b2009-05-29 15:37:27 +0100633 || parseUrlShortcut(url) != SHORTCUT_INVALID) {
634 return false;
635 }
636
Leon Scroggins8d06e362010-03-24 14:45:57 -0400637 final ContentResolver cr = mResolver;
638 final String newUrl = url;
Elliott Slaughterf0f03952010-07-14 18:10:36 -0700639 if (!mTabControl.getCurrentWebView().isPrivateBrowsingEnabled()) {
640 new AsyncTask<Void, Void, Void>() {
641 @Override
642 protected Void doInBackground(Void... unused) {
643 Browser.updateVisitedHistory(cr, newUrl, false);
644 Browser.addSearchUrl(cr, newUrl);
645 return null;
646 }
647 }.execute();
648 }
Satish Sampath565505b2009-05-29 15:37:27 +0100649
650 Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);
651 intent.addCategory(Intent.CATEGORY_DEFAULT);
652 intent.putExtra(SearchManager.QUERY, url);
Satish Sampath15e9f2d2009-06-23 22:29:49 +0100653 if (appData != null) {
654 intent.putExtra(SearchManager.APP_DATA, appData);
655 }
Bjorn Bringert04851702009-09-22 10:36:01 +0100656 if (extraData != null) {
657 intent.putExtra(SearchManager.EXTRA_DATA_KEY, extraData);
658 }
Grace Klobacc634032009-07-28 15:58:19 -0700659 intent.putExtra(Browser.EXTRA_APPLICATION_ID, getPackageName());
Satish Sampath565505b2009-05-29 15:37:27 +0100660 startActivity(intent);
661
662 return true;
663 }
664
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700665 private UrlData getUrlDataFromIntent(Intent intent) {
Leon Scroggins58d56c62010-01-28 15:12:40 -0500666 String url = "";
Grace Kloba068e48b2010-01-26 18:11:27 -0800667 Map<String, String> headers = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800668 if (intent != null) {
669 final String action = intent.getAction();
670 if (Intent.ACTION_VIEW.equals(action)) {
671 url = smartUrlFilter(intent.getData());
672 if (url != null && url.startsWith("content:")) {
673 /* Append mimetype so webview knows how to display */
674 String mimeType = intent.resolveType(getContentResolver());
675 if (mimeType != null) {
676 url += "?" + mimeType;
677 }
678 }
Grace Kloba068e48b2010-01-26 18:11:27 -0800679 if (url != null && url.startsWith("http")) {
Grace Kloba00f54c52010-01-27 14:53:51 -0800680 final Bundle pairs = intent
681 .getBundleExtra(Browser.EXTRA_HEADERS);
Grace Kloba2d508ed2010-01-28 11:39:15 -0800682 if (pairs != null && !pairs.isEmpty()) {
Grace Kloba00f54c52010-01-27 14:53:51 -0800683 Iterator<String> iter = pairs.keySet().iterator();
Grace Kloba068e48b2010-01-26 18:11:27 -0800684 headers = new HashMap<String, String>();
Grace Kloba00f54c52010-01-27 14:53:51 -0800685 while (iter.hasNext()) {
686 String key = iter.next();
687 headers.put(key, pairs.getString(key));
Grace Kloba068e48b2010-01-26 18:11:27 -0800688 }
689 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700690 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800691 } else if (Intent.ACTION_SEARCH.equals(action)
692 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
693 || Intent.ACTION_WEB_SEARCH.equals(action)) {
694 url = intent.getStringExtra(SearchManager.QUERY);
695 if (url != null) {
696 mLastEnteredUrl = url;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800697 // In general, we shouldn't modify URL from Intent.
698 // But currently, we get the user-typed URL from search box as well.
699 url = fixUrl(url);
700 url = smartUrlFilter(url);
Leon Scroggins8d06e362010-03-24 14:45:57 -0400701 final ContentResolver cr = mResolver;
702 final String newUrl = url;
703 new AsyncTask<Void, Void, Void>() {
Michael Kolbe0a36662010-06-29 10:37:12 -0700704 @Override
Leon Scroggins8d06e362010-03-24 14:45:57 -0400705 protected Void doInBackground(Void... unused) {
706 Browser.updateVisitedHistory(cr, newUrl, false);
707 return null;
708 }
709 }.execute();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800710 String searchSource = "&source=android-" + GOOGLE_SEARCH_SOURCE_SUGGEST + "&";
711 if (url.contains(searchSource)) {
712 String source = null;
713 final Bundle appData = intent.getBundleExtra(SearchManager.APP_DATA);
714 if (appData != null) {
Bjorn Bringert10d1cca2010-02-10 14:22:12 +0000715 source = appData.getString(Search.SOURCE);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800716 }
717 if (TextUtils.isEmpty(source)) {
718 source = GOOGLE_SEARCH_SOURCE_UNKNOWN;
719 }
720 url = url.replace(searchSource, "&source=android-"+source+"&");
721 }
722 }
723 }
724 }
Leon Scroggins58d56c62010-01-28 15:12:40 -0500725 return new UrlData(url, headers, intent);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800726 }
Leon Scroggins58d56c62010-01-28 15:12:40 -0500727 /* package */ void showVoiceTitleBar(String title) {
728 mTitleBar.setInVoiceMode(true);
Leon Scroggins58d56c62010-01-28 15:12:40 -0500729 mTitleBar.setDisplayTitle(title);
Michael Kolba2b2ba82010-08-04 17:54:03 -0700730 mFakeTitleBar.setInVoiceMode(true);
731 mFakeTitleBar.setDisplayTitle(title);
Leon Scroggins58d56c62010-01-28 15:12:40 -0500732 }
733 /* package */ void revertVoiceTitleBar() {
734 mTitleBar.setInVoiceMode(false);
Leon Scroggins003a5dd2010-03-10 12:13:14 -0500735 mTitleBar.setDisplayTitle(mUrl);
Michael Kolba2b2ba82010-08-04 17:54:03 -0700736 mFakeTitleBar.setInVoiceMode(false);
737 mFakeTitleBar.setDisplayTitle(mUrl);
Leon Scroggins58d56c62010-01-28 15:12:40 -0500738 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800739 /* package */ static String fixUrl(String inUrl) {
Cary Clark652ff872009-09-10 13:34:44 -0400740 // FIXME: Converting the url to lower case
741 // duplicates functionality in smartUrlFilter().
742 // However, changing all current callers of fixUrl to
743 // call smartUrlFilter in addition may have unwanted
744 // consequences, and is deferred for now.
745 int colon = inUrl.indexOf(':');
746 boolean allLower = true;
747 for (int index = 0; index < colon; index++) {
748 char ch = inUrl.charAt(index);
749 if (!Character.isLetter(ch)) {
750 break;
751 }
752 allLower &= Character.isLowerCase(ch);
753 if (index == colon - 1 && !allLower) {
754 inUrl = inUrl.substring(0, colon).toLowerCase()
755 + inUrl.substring(colon);
756 }
757 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800758 if (inUrl.startsWith("http://") || inUrl.startsWith("https://"))
759 return inUrl;
760 if (inUrl.startsWith("http:") ||
761 inUrl.startsWith("https:")) {
762 if (inUrl.startsWith("http:/") || inUrl.startsWith("https:/")) {
763 inUrl = inUrl.replaceFirst("/", "//");
764 } else inUrl = inUrl.replaceFirst(":", "://");
765 }
766 return inUrl;
767 }
768
Grace Kloba22ac16e2009-10-07 18:00:23 -0700769 @Override
770 protected void onResume() {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800771 super.onResume();
Dave Bort31a6d1c2009-04-13 15:56:49 -0700772 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800773 Log.v(LOGTAG, "BrowserActivity.onResume: this=" + this);
774 }
775
776 if (!mActivityInPause) {
777 Log.e(LOGTAG, "BrowserActivity is already resumed.");
778 return;
779 }
780
Mike Reed7bfa63b2009-05-28 11:08:32 -0400781 mTabControl.resumeCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800782 mActivityInPause = false;
Mike Reed7bfa63b2009-05-28 11:08:32 -0400783 resumeWebViewTimers();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800784
785 if (mWakeLock.isHeld()) {
786 mHandler.removeMessages(RELEASE_WAKELOCK);
787 mWakeLock.release();
788 }
789
The Android Open Source Project0c908882009-03-03 19:32:16 -0800790 registerReceiver(mNetworkStateIntentReceiver,
791 mNetworkStateChangedFilter);
792 WebView.enablePlatformNotifications();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800793 }
794
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400795 /**
796 * Since the actual title bar is embedded in the WebView, and removing it
Leon Scrogginsfe87bd32009-10-06 10:10:00 -0400797 * would change its appearance, use a different TitleBar to show overlayed
798 * at the top of the screen, when the menu is open or the page is loading.
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400799 */
Michael Kolba2b2ba82010-08-04 17:54:03 -0700800 private TitleBarBase mFakeTitleBar;
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400801
802 /**
803 * Keeps track of whether the options menu is open. This is important in
804 * determining whether to show or hide the title bar overlay.
805 */
806 private boolean mOptionsMenuOpen;
807
808 /**
809 * Only meaningful when mOptionsMenuOpen is true. This variable keeps track
810 * of whether the configuration has changed. The first onMenuOpened call
811 * after a configuration change is simply a reopening of the same menu
812 * (i.e. mIconView did not change).
813 */
814 private boolean mConfigChanged;
815
816 /**
817 * Whether or not the options menu is in its smaller, icon menu form. When
818 * true, we want the title bar overlay to be up. When false, we do not.
819 * Only meaningful if mOptionsMenuOpen is true.
820 */
821 private boolean mIconView;
822
Leon Scrogginsa81a7642009-08-31 17:05:41 -0400823 @Override
824 public boolean onMenuOpened(int featureId, Menu menu) {
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400825 if (Window.FEATURE_OPTIONS_PANEL == featureId) {
826 if (mOptionsMenuOpen) {
827 if (mConfigChanged) {
828 // We do not need to make any changes to the state of the
829 // title bar, since the only thing that happened was a
830 // change in orientation
831 mConfigChanged = false;
832 } else {
833 if (mIconView) {
834 // Switching the menu to expanded view, so hide the
835 // title bar.
836 hideFakeTitleBar();
837 mIconView = false;
838 } else {
839 // Switching the menu back to icon view, so show the
840 // title bar once again.
841 showFakeTitleBar();
842 mIconView = true;
843 }
844 }
845 } else {
846 // The options menu is closed, so open it, and show the title
847 showFakeTitleBar();
848 mOptionsMenuOpen = true;
849 mConfigChanged = false;
850 mIconView = true;
851 }
852 }
Leon Scrogginsa81a7642009-08-31 17:05:41 -0400853 return true;
854 }
855
Michael Kolba2b2ba82010-08-04 17:54:03 -0700856 void showFakeTitleBar() {
857 if (!isFakeTitleBarShowing() && mActiveTabsPage == null && !mActivityInPause) {
Grace Kloba847c25b2010-03-30 16:00:26 -0700858 WebView mainView = mTabControl.getCurrentWebView();
859 // if there is no current WebView, don't show the faked title bar;
Grace Kloba65190702010-04-02 23:37:26 -0700860 if (mainView == null) {
Cary Clarka0464552009-09-29 13:00:45 -0400861 return;
862 }
Leon Scroggins79e36d92010-04-29 16:01:46 +0100863 // Do not need to check for null, since the current tab will have
864 // at least a main WebView, or we would have returned above.
Cary Clark01cfcdd2010-06-04 16:36:45 -0400865 if (dialogIsUp()) {
Leon Scroggins79e36d92010-04-29 16:01:46 +0100866 // Do not show the fake title bar, which would cover up the
Cary Clark01cfcdd2010-06-04 16:36:45 -0400867 // find or select dialog.
Leon Scroggins79e36d92010-04-29 16:01:46 +0100868 return;
869 }
Michael Kolba2b2ba82010-08-04 17:54:03 -0700870 if (mXLargeScreenSize) {
871 mContentView.addView(mFakeTitleBar);
872 mTabBar.onShowTitleBar();
873 } else {
874 WindowManager manager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400875
Michael Kolba2b2ba82010-08-04 17:54:03 -0700876 // Add the title bar to the window manager so it can receive
877 // touches
878 // while the menu is up
879 WindowManager.LayoutParams params =
880 new WindowManager.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
881 ViewGroup.LayoutParams.WRAP_CONTENT,
882 WindowManager.LayoutParams.TYPE_APPLICATION,
883 WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
884 PixelFormat.TRANSLUCENT);
885 params.gravity = Gravity.TOP;
886 boolean atTop = mainView.getScrollY() == 0;
887 params.windowAnimations = atTop ? 0 : R.style.TitleBar;
888 manager.addView(mFakeTitleBar, params);
889 }
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400890 }
891 }
892
893 @Override
894 public void onOptionsMenuClosed(Menu menu) {
895 mOptionsMenuOpen = false;
Leon Scrogginsa27ff192009-09-14 12:58:04 -0400896 if (!mInLoad) {
897 hideFakeTitleBar();
898 } else if (!mIconView) {
899 // The page is currently loading, and we are in expanded mode, so
900 // we were not showing the menu. Show it once again. It will be
901 // removed when the page finishes.
902 showFakeTitleBar();
903 }
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400904 }
Grace Kloba22ac16e2009-10-07 18:00:23 -0700905
Michael Kolba2b2ba82010-08-04 17:54:03 -0700906 void stopScrolling() {
907 ((ScrollWebView) mTabControl.getCurrentWebView()).stopScroll();
908 }
909
910 void hideFakeTitleBar() {
911 if (!isFakeTitleBarShowing()) return;
912 if (mXLargeScreenSize) {
913 mContentView.removeView(mFakeTitleBar);
914 mTabBar.onHideTitleBar();
915 } else {
916 WindowManager.LayoutParams params =
917 (WindowManager.LayoutParams) mFakeTitleBar.getLayoutParams();
918 WebView mainView = mTabControl.getCurrentWebView();
919 // Although we decided whether or not to animate based on the
920 // current
921 // scroll position, the scroll position may have changed since the
922 // fake title bar was displayed. Make sure it has the appropriate
923 // animation/lack thereof before removing.
924 params.windowAnimations =
925 mainView != null && mainView.getScrollY() == 0 ? 0 : R.style.TitleBar;
926 WindowManager manager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
927 manager.updateViewLayout(mFakeTitleBar, params);
928 manager.removeView(mFakeTitleBar);
929 }
930 }
931
932 boolean isFakeTitleBarShowing() {
933 return (mFakeTitleBar.getParent() != null);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400934 }
935
The Android Open Source Project0c908882009-03-03 19:32:16 -0800936 /**
Leon Scrogginsc6fa1102009-09-21 10:40:01 -0400937 * Special method for the fake title bar to call when displaying its context
938 * menu, since it is in its own Window, and its parent does not show a
939 * context menu.
940 */
941 /* package */ void showTitleBarContextMenu() {
Cary Clark65f4a3c2009-09-28 17:05:06 -0400942 if (null == mTitleBar.getParent()) {
943 return;
944 }
Leon Scrogginsc6fa1102009-09-21 10:40:01 -0400945 openContextMenu(mTitleBar);
946 }
947
Leon Scrogginsb2b19f52009-10-09 16:10:00 -0400948 @Override
949 public void onContextMenuClosed(Menu menu) {
950 super.onContextMenuClosed(menu);
951 if (mInLoad) {
952 showFakeTitleBar();
953 }
954 }
955
Leon Scrogginsc6fa1102009-09-21 10:40:01 -0400956 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -0800957 * onSaveInstanceState(Bundle map)
958 * onSaveInstanceState is called right before onStop(). The map contains
959 * the saved state.
960 */
Grace Kloba22ac16e2009-10-07 18:00:23 -0700961 @Override
962 protected void onSaveInstanceState(Bundle outState) {
Dave Bort31a6d1c2009-04-13 15:56:49 -0700963 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800964 Log.v(LOGTAG, "BrowserActivity.onSaveInstanceState: this=" + this);
965 }
966 // the default implementation requires each view to have an id. As the
967 // browser handles the state itself and it doesn't use id for the views,
968 // don't call the default implementation. Otherwise it will trigger the
969 // warning like this, "couldn't save which view has focus because the
970 // focused view XXX has no id".
971
972 // Save all the tabs
973 mTabControl.saveState(outState);
974 }
975
Grace Kloba22ac16e2009-10-07 18:00:23 -0700976 @Override
977 protected void onPause() {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800978 super.onPause();
979
980 if (mActivityInPause) {
981 Log.e(LOGTAG, "BrowserActivity is already paused.");
982 return;
983 }
984
Mike Reed7bfa63b2009-05-28 11:08:32 -0400985 mTabControl.pauseCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800986 mActivityInPause = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -0400987 if (mTabControl.getCurrentIndex() >= 0 && !pauseWebViewTimers()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800988 mWakeLock.acquire();
989 mHandler.sendMessageDelayed(mHandler
990 .obtainMessage(RELEASE_WAKELOCK), WAKELOCK_TIMEOUT);
991 }
992
Leon Scrogginsa2ab6a72009-09-11 11:49:52 -0400993 // FIXME: This removes the active tabs page and resets the menu to
994 // MAIN_MENU. A better solution might be to do this work in onNewIntent
995 // but then we would need to save it in onSaveInstanceState and restore
996 // it in onCreate/onRestoreInstanceState
997 if (mActiveTabsPage != null) {
998 removeActiveTabPage(true);
999 }
1000
The Android Open Source Project0c908882009-03-03 19:32:16 -08001001 cancelStopToast();
1002
1003 // unregister network state listener
1004 unregisterReceiver(mNetworkStateIntentReceiver);
1005 WebView.disablePlatformNotifications();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001006 }
1007
Grace Kloba22ac16e2009-10-07 18:00:23 -07001008 @Override
1009 protected void onDestroy() {
Dave Bort31a6d1c2009-04-13 15:56:49 -07001010 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001011 Log.v(LOGTAG, "BrowserActivity.onDestroy: this=" + this);
1012 }
1013 super.onDestroy();
Grace Kloba0923d692009-09-23 21:37:25 -07001014
Leon Scroggins8d5fa432009-10-02 15:55:59 -04001015 if (mUploadMessage != null) {
1016 mUploadMessage.onReceiveValue(null);
1017 mUploadMessage = null;
1018 }
1019
Grace Kloba0923d692009-09-23 21:37:25 -07001020 if (mTabControl == null) return;
1021
Grace Kloba1fc98a32009-10-21 13:23:08 -07001022 // Remove the fake title bar if it is there
1023 hideFakeTitleBar();
1024
The Android Open Source Project0c908882009-03-03 19:32:16 -08001025 // Remove the current tab and sub window
Grace Kloba22ac16e2009-10-07 18:00:23 -07001026 Tab t = mTabControl.getCurrentTab();
Patrick Scottfb5e77f2009-04-08 19:17:37 -07001027 if (t != null) {
1028 dismissSubWindow(t);
1029 removeTabFromContentView(t);
1030 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001031 // Destroy all the tabs
1032 mTabControl.destroy();
1033 WebIconDatabase.getInstance().close();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001034
Grace Klobab4da0ad2009-05-14 14:45:40 -07001035 unregisterReceiver(mPackageInstallationReceiver);
Bjorn Bringerta7611812010-03-24 11:12:02 +00001036
1037 // Stop watching the default geolocation permissions
1038 mSystemAllowGeolocationOrigins.stop();
1039 mSystemAllowGeolocationOrigins = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001040 }
1041
1042 @Override
1043 public void onConfigurationChanged(Configuration newConfig) {
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04001044 mConfigChanged = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001045 super.onConfigurationChanged(newConfig);
1046
1047 if (mPageInfoDialog != null) {
1048 mPageInfoDialog.dismiss();
1049 showPageInfo(
1050 mPageInfoView,
Leon Scrogginsc7b92f82010-01-11 18:17:31 -05001051 mPageInfoFromShowSSLCertificateOnError);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001052 }
1053 if (mSSLCertificateDialog != null) {
1054 mSSLCertificateDialog.dismiss();
1055 showSSLCertificate(
1056 mSSLCertificateView);
1057 }
1058 if (mSSLCertificateOnErrorDialog != null) {
1059 mSSLCertificateOnErrorDialog.dismiss();
1060 showSSLCertificateOnError(
1061 mSSLCertificateOnErrorView,
1062 mSSLCertificateOnErrorHandler,
1063 mSSLCertificateOnErrorError);
1064 }
1065 if (mHttpAuthenticationDialog != null) {
1066 String title = ((TextView) mHttpAuthenticationDialog
1067 .findViewById(com.android.internal.R.id.alertTitle)).getText()
1068 .toString();
1069 String name = ((TextView) mHttpAuthenticationDialog
1070 .findViewById(R.id.username_edit)).getText().toString();
1071 String password = ((TextView) mHttpAuthenticationDialog
1072 .findViewById(R.id.password_edit)).getText().toString();
1073 int focusId = mHttpAuthenticationDialog.getCurrentFocus()
1074 .getId();
1075 mHttpAuthenticationDialog.dismiss();
1076 showHttpAuthentication(mHttpAuthHandler, null, null, title,
1077 name, password, focusId);
1078 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001079 }
1080
Grace Kloba22ac16e2009-10-07 18:00:23 -07001081 @Override
1082 public void onLowMemory() {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001083 super.onLowMemory();
1084 mTabControl.freeMemory();
1085 }
1086
Cary Clarkff4d92c2010-03-25 11:17:03 -04001087 private void resumeWebViewTimers() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001088 Tab tab = mTabControl.getCurrentTab();
Cary Clarkff4d92c2010-03-25 11:17:03 -04001089 if (tab == null) return; // monkey can trigger this
Grace Kloba22ac16e2009-10-07 18:00:23 -07001090 boolean inLoad = tab.inLoad();
1091 if ((!mActivityInPause && !inLoad) || (mActivityInPause && inLoad)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001092 CookieSyncManager.getInstance().startSync();
Grace Kloba22ac16e2009-10-07 18:00:23 -07001093 WebView w = tab.getWebView();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001094 if (w != null) {
1095 w.resumeTimers();
1096 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001097 }
1098 }
1099
Mike Reed7bfa63b2009-05-28 11:08:32 -04001100 private boolean pauseWebViewTimers() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001101 Tab tab = mTabControl.getCurrentTab();
1102 boolean inLoad = tab.inLoad();
1103 if (mActivityInPause && !inLoad) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001104 CookieSyncManager.getInstance().stopSync();
1105 WebView w = mTabControl.getCurrentWebView();
1106 if (w != null) {
1107 w.pauseTimers();
1108 }
1109 return true;
1110 } else {
1111 return false;
1112 }
1113 }
1114
The Android Open Source Project0c908882009-03-03 19:32:16 -08001115 // Open the icon database and retain all the icons for visited sites.
1116 private void retainIconsOnStartup() {
1117 final WebIconDatabase db = WebIconDatabase.getInstance();
1118 db.open(getDir("icons", 0).getPath());
Leon Scroggins2c0f6112010-03-12 18:09:39 -05001119 Cursor c = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001120 try {
Leon Scroggins2c0f6112010-03-12 18:09:39 -05001121 c = Browser.getAllBookmarks(mResolver);
1122 if (c.moveToFirst()) {
1123 int urlIndex = c.getColumnIndex(Browser.BookmarkColumns.URL);
1124 do {
1125 String url = c.getString(urlIndex);
1126 db.retainIconForPageUrl(url);
1127 } while (c.moveToNext());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001128 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001129 } catch (IllegalStateException e) {
1130 Log.e(LOGTAG, "retainIconsOnStartup", e);
Leon Scroggins2c0f6112010-03-12 18:09:39 -05001131 } finally {
1132 if (c!= null) c.close();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001133 }
1134 }
1135
1136 // Helper method for getting the top window.
1137 WebView getTopWindow() {
1138 return mTabControl.getCurrentTopWebView();
1139 }
1140
Grace Kloba22ac16e2009-10-07 18:00:23 -07001141 TabControl getTabControl() {
1142 return mTabControl;
1143 }
1144
The Android Open Source Project0c908882009-03-03 19:32:16 -08001145 @Override
1146 public boolean onCreateOptionsMenu(Menu menu) {
1147 super.onCreateOptionsMenu(menu);
1148
1149 MenuInflater inflater = getMenuInflater();
1150 inflater.inflate(R.menu.browser, menu);
1151 mMenu = menu;
1152 updateInLoadMenuItems();
1153 return true;
1154 }
1155
1156 /**
1157 * As the menu can be open when loading state changes
1158 * we must manually update the state of the stop/reload menu
1159 * item
1160 */
1161 private void updateInLoadMenuItems() {
1162 if (mMenu == null) {
1163 return;
1164 }
Michael Kolbe0a36662010-06-29 10:37:12 -07001165 MenuItem dest = mMenu.findItem(R.id.stop_reload_menu_id);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001166 MenuItem src = mInLoad ?
1167 mMenu.findItem(R.id.stop_menu_id):
Michael Kolbe0a36662010-06-29 10:37:12 -07001168 mMenu.findItem(R.id.reload_menu_id);
1169 if (src != null) {
1170 dest.setIcon(src.getIcon());
1171 dest.setTitle(src.getTitle());
1172 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001173 }
1174
1175 @Override
1176 public boolean onContextItemSelected(MenuItem item) {
1177 // chording is not an issue with context menus, but we use the same
1178 // options selector, so set mCanChord to true so we can access them.
1179 mCanChord = true;
1180 int id = item.getItemId();
Leon Scroggins96afcb12009-12-10 12:35:56 -05001181 boolean result = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001182 switch (id) {
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001183 // For the context menu from the title bar
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001184 case R.id.title_bar_copy_page_url:
Leon Scroggins96afcb12009-12-10 12:35:56 -05001185 Tab currentTab = mTabControl.getCurrentTab();
1186 if (null == currentTab) {
1187 result = false;
1188 break;
1189 }
1190 WebView mainView = currentTab.getWebView();
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001191 if (null == mainView) {
Leon Scroggins96afcb12009-12-10 12:35:56 -05001192 result = false;
1193 break;
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001194 }
Leon Scroggins96afcb12009-12-10 12:35:56 -05001195 copy(mainView.getUrl());
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001196 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001197 // -- Browser context menu
1198 case R.id.open_context_menu_id:
The Android Open Source Project0c908882009-03-03 19:32:16 -08001199 case R.id.bookmark_context_menu_id:
1200 case R.id.save_link_context_menu_id:
1201 case R.id.share_link_context_menu_id:
1202 case R.id.copy_link_context_menu_id:
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001203 final WebView webView = getTopWindow();
1204 if (null == webView) {
Leon Scroggins96afcb12009-12-10 12:35:56 -05001205 result = false;
1206 break;
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001207 }
1208 final HashMap hrefMap = new HashMap();
1209 hrefMap.put("webview", webView);
1210 final Message msg = mHandler.obtainMessage(
1211 FOCUS_NODE_HREF, id, 0, hrefMap);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001212 webView.requestFocusNodeHref(msg);
1213 break;
1214
1215 default:
1216 // For other context menus
Leon Scroggins96afcb12009-12-10 12:35:56 -05001217 result = onOptionsItemSelected(item);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001218 }
1219 mCanChord = false;
Leon Scroggins96afcb12009-12-10 12:35:56 -05001220 return result;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001221 }
1222
1223 private Bundle createGoogleSearchSourceBundle(String source) {
1224 Bundle bundle = new Bundle();
Bjorn Bringert10d1cca2010-02-10 14:22:12 +00001225 bundle.putString(Search.SOURCE, source);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001226 return bundle;
1227 }
1228
Leon Scroggins8ad29922010-02-16 12:33:55 -05001229 /* package */ void editUrl() {
Leon Scroggins68579392009-09-15 15:31:54 -04001230 if (mOptionsMenuOpen) closeOptionsMenu();
Leon Scroggins5bbe9802009-07-31 13:10:55 -04001231 String url = (getTopWindow() == null) ? null : getTopWindow().getUrl();
Grace Kloba83f47342009-07-20 10:44:31 -07001232 startSearch(mSettings.getHomePage().equals(url) ? null : url, true,
Leon Scroggins8ad29922010-02-16 12:33:55 -05001233 null, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001234 }
1235
Leon Scroggins8ad29922010-02-16 12:33:55 -05001236 /**
1237 * Overriding this to insert a local information bundle
1238 */
The Android Open Source Project0c908882009-03-03 19:32:16 -08001239 @Override
1240 public void startSearch(String initialQuery, boolean selectInitialQuery,
1241 Bundle appSearchData, boolean globalSearch) {
1242 if (appSearchData == null) {
1243 appSearchData = createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_TYPE);
1244 }
1245 super.startSearch(initialQuery, selectInitialQuery, appSearchData, globalSearch);
1246 }
1247
Leon Scroggins1f005d32009-08-10 17:36:42 -04001248 /**
1249 * Switch tabs. Called by the TitleBarSet when sliding the title bar
1250 * results in changing tabs.
Leon Scroggins160a7e72009-08-14 18:28:01 -04001251 * @param index Index of the tab to change to, as defined by
1252 * mTabControl.getTabIndex(Tab t).
1253 * @return boolean True if we successfully switched to a different tab. If
1254 * the indexth tab is null, or if that tab is the same as
1255 * the current one, return false.
Leon Scroggins1f005d32009-08-10 17:36:42 -04001256 */
Leon Scroggins160a7e72009-08-14 18:28:01 -04001257 /* package */ boolean switchToTab(int index) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001258 Tab tab = mTabControl.getTab(index);
1259 Tab currentTab = mTabControl.getCurrentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04001260 if (tab == null || tab == currentTab) {
Leon Scroggins160a7e72009-08-14 18:28:01 -04001261 return false;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001262 }
1263 if (currentTab != null) {
1264 // currentTab may be null if it was just removed. In that case,
1265 // we do not need to remove it
1266 removeTabFromContentView(currentTab);
1267 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001268 mTabControl.setCurrentTab(tab);
1269 attachTabToContentView(tab);
Grace Klobaeb6eef42009-09-15 17:56:32 -07001270 resetTitleIconAndProgress();
1271 updateLockIconToLatest();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001272 return true;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001273 }
1274
Grace Kloba22ac16e2009-10-07 18:00:23 -07001275 /* package */ Tab openTabToHomePage() {
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001276 return openTabAndShow(mSettings.getHomePage(), false, null);
1277 }
1278
Leon Scroggins1f005d32009-08-10 17:36:42 -04001279 /* package */ void closeCurrentWindow() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001280 final Tab current = mTabControl.getCurrentTab();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001281 if (mTabControl.getTabCount() == 1) {
Leon Scroggins30444232009-09-04 18:36:20 -04001282 // This is the last tab. Open a new one, with the home
1283 // page and close the current one.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001284 openTabToHomePage();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001285 closeTab(current);
Leon Scroggins160a7e72009-08-14 18:28:01 -04001286 return;
1287 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07001288 final Tab parent = current.getParentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04001289 int indexToShow = -1;
1290 if (parent != null) {
1291 indexToShow = mTabControl.getTabIndex(parent);
1292 } else {
Leon Scroggins160a7e72009-08-14 18:28:01 -04001293 final int currentIndex = mTabControl.getCurrentIndex();
1294 // Try to move to the tab to the right
1295 indexToShow = currentIndex + 1;
1296 if (indexToShow > mTabControl.getTabCount() - 1) {
1297 // Try to move to the tab to the left
1298 indexToShow = currentIndex - 1;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001299 }
1300 }
Leon Scroggins160a7e72009-08-14 18:28:01 -04001301 if (switchToTab(indexToShow)) {
1302 // Close window
1303 closeTab(current);
1304 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001305 }
1306
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001307 private ActiveTabsPage mActiveTabsPage;
1308
1309 /**
1310 * Remove the active tabs page.
1311 * @param needToAttach If true, the active tabs page did not attach a tab
1312 * to the content view, so we need to do that here.
1313 */
1314 /* package */ void removeActiveTabPage(boolean needToAttach) {
1315 mContentView.removeView(mActiveTabsPage);
Leon Scrogginsd746a942010-05-19 13:21:44 -04001316 mTitleBar.setVisibility(View.VISIBLE);
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001317 mActiveTabsPage = null;
1318 mMenuState = R.id.MAIN_MENU;
1319 if (needToAttach) {
1320 attachTabToContentView(mTabControl.getCurrentTab());
1321 }
1322 getTopWindow().requestFocus();
1323 }
1324
Cary Clark01cfcdd2010-06-04 16:36:45 -04001325 private WebView showDialog(WebDialog dialog) {
1326 // Need to do something special for Tablet
1327 Tab tab = mTabControl.getCurrentTab();
1328 if (tab.getSubWebView() == null) {
1329 // If the find or select is being performed on the main webview,
1330 // remove the embedded title bar.
1331 WebView mainView = tab.getWebView();
1332 if (mainView != null) {
1333 mainView.setEmbeddedTitleBar(null);
1334 }
1335 }
1336 hideFakeTitleBar();
1337 mMenuState = EMPTY_MENU;
1338 return tab.showDialog(dialog);
1339 }
1340
The Android Open Source Project0c908882009-03-03 19:32:16 -08001341 @Override
1342 public boolean onOptionsItemSelected(MenuItem item) {
Michael Kolbed217742010-08-10 17:52:34 -07001343 // check the action bar button before mCanChord check, as the prepare call
1344 // doesn't come for action bar buttons
1345 if (item.getItemId() == R.id.newtab) {
1346 bookmarksOrHistoryPicker(false, true);
1347 return true;
1348 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001349 if (!mCanChord) {
1350 // The user has already fired a shortcut with this hold down of the
1351 // menu key.
1352 return false;
1353 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001354 if (null == getTopWindow()) {
Leon Scroggins0d7ae0e2009-06-05 11:04:45 -04001355 return false;
1356 }
Grace Kloba6ee9c492009-07-13 10:04:34 -07001357 if (mMenuIsDown) {
1358 // The shortcut action consumes the MENU. Even if it is still down,
1359 // it won't trigger the next shortcut action. In the case of the
1360 // shortcut action triggering a new activity, like Bookmarks, we
1361 // won't get onKeyUp for MENU. So it is important to reset it here.
1362 mMenuIsDown = false;
1363 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001364 switch (item.getItemId()) {
1365 // -- Main menu
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001366 case R.id.new_tab_menu_id:
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001367 openTabToHomePage();
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001368 break;
1369
Leon Scroggins64b80f32009-08-07 12:03:34 -04001370 case R.id.goto_menu_id:
Leon Scroggins8ad29922010-02-16 12:33:55 -05001371 editUrl();
Leon Scrogginsb3a5bed2009-09-28 11:21:56 -04001372 break;
1373
1374 case R.id.bookmarks_menu_id:
Michael Kolb68792c82010-08-09 16:39:18 -07001375 bookmarksOrHistoryPicker(false, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001376 break;
1377
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001378 case R.id.active_tabs_menu_id:
1379 mActiveTabsPage = new ActiveTabsPage(this, mTabControl);
1380 removeTabFromContentView(mTabControl.getCurrentTab());
Leon Scrogginsd746a942010-05-19 13:21:44 -04001381 mTitleBar.setVisibility(View.GONE);
Leon Scroggins43de6162009-09-14 19:59:58 -04001382 hideFakeTitleBar();
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001383 mContentView.addView(mActiveTabsPage, COVER_SCREEN_PARAMS);
1384 mActiveTabsPage.requestFocus();
1385 mMenuState = EMPTY_MENU;
1386 break;
1387
Leon Scroggins1f005d32009-08-10 17:36:42 -04001388 case R.id.add_bookmark_menu_id:
Leon Scroggins571b3762010-05-26 10:25:01 -04001389 bookmarkCurrentPage();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001390 break;
1391
1392 case R.id.stop_reload_menu_id:
1393 if (mInLoad) {
1394 stopLoading();
1395 } else {
1396 getTopWindow().reload();
1397 }
1398 break;
1399
1400 case R.id.back_menu_id:
1401 getTopWindow().goBack();
1402 break;
1403
1404 case R.id.forward_menu_id:
1405 getTopWindow().goForward();
1406 break;
1407
1408 case R.id.close_menu_id:
1409 // Close the subwindow if it exists.
1410 if (mTabControl.getCurrentSubWindow() != null) {
1411 dismissSubWindow(mTabControl.getCurrentTab());
1412 break;
1413 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001414 closeCurrentWindow();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001415 break;
1416
1417 case R.id.homepage_menu_id:
Grace Kloba22ac16e2009-10-07 18:00:23 -07001418 Tab current = mTabControl.getCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001419 if (current != null) {
1420 dismissSubWindow(current);
Leon Scroggins92472e82010-02-17 16:32:28 -05001421 loadUrl(current.getWebView(), mSettings.getHomePage());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001422 }
1423 break;
1424
1425 case R.id.preferences_menu_id:
1426 Intent intent = new Intent(this,
1427 BrowserPreferencesPage.class);
Leon Scrogginsd5304942009-12-10 16:11:39 -05001428 intent.putExtra(BrowserPreferencesPage.CURRENT_PAGE,
1429 getTopWindow().getUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001430 startActivityForResult(intent, PREFERENCES_PAGE);
1431 break;
1432
1433 case R.id.find_menu_id:
Cary Clark01cfcdd2010-06-04 16:36:45 -04001434 showFindDialog();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001435 break;
1436
Elliott Slaughter0ced08c2010-06-30 11:40:42 -07001437 case R.id.save_webarchive_menu_id:
1438 if (LOGD_ENABLED) {
1439 Log.d(LOGTAG, "Save as Web Archive");
1440 }
1441 String directory = getExternalFilesDir(null).getAbsolutePath() + File.separator;
1442 getTopWindow().saveWebArchive(directory, true, new ValueCallback<String>() {
1443 @Override
1444 public void onReceiveValue(String value) {
1445 if (value != null) {
1446 Toast.makeText(BrowserActivity.this, R.string.webarchive_saved, Toast.LENGTH_SHORT).show();
1447 } else {
1448 Toast.makeText(BrowserActivity.this, R.string.webarchive_failed, Toast.LENGTH_SHORT).show();
1449 }
1450 }
1451 });
1452 break;
1453
The Android Open Source Project0c908882009-03-03 19:32:16 -08001454 case R.id.page_info_menu_id:
1455 showPageInfo(mTabControl.getCurrentTab(), false);
1456 break;
1457
1458 case R.id.classic_history_menu_id:
Michael Kolb68792c82010-08-09 16:39:18 -07001459 bookmarksOrHistoryPicker(true, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001460 break;
1461
Leon Scroggins96afcb12009-12-10 12:35:56 -05001462 case R.id.title_bar_share_page_url:
The Android Open Source Project0c908882009-03-03 19:32:16 -08001463 case R.id.share_page_menu_id:
Leon Scroggins96afcb12009-12-10 12:35:56 -05001464 Tab currentTab = mTabControl.getCurrentTab();
1465 if (null == currentTab) {
1466 mCanChord = false;
1467 return false;
1468 }
1469 currentTab.populatePickerData();
1470 sharePage(this, currentTab.getTitle(),
1471 currentTab.getUrl(), currentTab.getFavicon(),
Ben Murdoch87cc65d2010-06-29 20:34:10 +01001472 createScreenshot(currentTab.getWebView(), getDesiredThumbnailWidth(this),
1473 getDesiredThumbnailHeight(this)));
The Android Open Source Project0c908882009-03-03 19:32:16 -08001474 break;
1475
1476 case R.id.dump_nav_menu_id:
1477 getTopWindow().debugDump();
1478 break;
1479
Andrei Popescu7a8b88b2010-02-02 00:30:38 +00001480 case R.id.dump_counters_menu_id:
1481 getTopWindow().dumpV8Counters();
1482 break;
1483
The Android Open Source Project0c908882009-03-03 19:32:16 -08001484 case R.id.zoom_in_menu_id:
1485 getTopWindow().zoomIn();
1486 break;
1487
1488 case R.id.zoom_out_menu_id:
1489 getTopWindow().zoomOut();
1490 break;
1491
1492 case R.id.view_downloads_menu_id:
1493 viewDownloads(null);
1494 break;
1495
The Android Open Source Project0c908882009-03-03 19:32:16 -08001496 case R.id.window_one_menu_id:
1497 case R.id.window_two_menu_id:
1498 case R.id.window_three_menu_id:
1499 case R.id.window_four_menu_id:
1500 case R.id.window_five_menu_id:
1501 case R.id.window_six_menu_id:
1502 case R.id.window_seven_menu_id:
1503 case R.id.window_eight_menu_id:
1504 {
1505 int menuid = item.getItemId();
1506 for (int id = 0; id < WINDOW_SHORTCUT_ID_ARRAY.length; id++) {
1507 if (WINDOW_SHORTCUT_ID_ARRAY[id] == menuid) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001508 Tab desiredTab = mTabControl.getTab(id);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001509 if (desiredTab != null &&
1510 desiredTab != mTabControl.getCurrentTab()) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001511 switchToTab(id);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001512 }
1513 break;
1514 }
1515 }
1516 }
1517 break;
1518
1519 default:
1520 if (!super.onOptionsItemSelected(item)) {
1521 return false;
1522 }
1523 // Otherwise fall through.
1524 }
1525 mCanChord = false;
1526 return true;
1527 }
1528
Leon Scroggins571b3762010-05-26 10:25:01 -04001529 /* package */ void bookmarkCurrentPage() {
1530 Intent i = new Intent(BrowserActivity.this,
1531 AddBookmarkPage.class);
1532 WebView w = getTopWindow();
1533 i.putExtra("url", w.getUrl());
1534 i.putExtra("title", w.getTitle());
1535 i.putExtra("touch_icon_url", w.getTouchIconUrl());
Ben Murdoch87cc65d2010-06-29 20:34:10 +01001536 i.putExtra("thumbnail", createScreenshot(w, getDesiredThumbnailWidth(this),
1537 getDesiredThumbnailHeight(this)));
Ben Murdocheecb4e62010-07-06 16:30:38 +01001538 i.putExtra("url_editable", false);
Leon Scroggins571b3762010-05-26 10:25:01 -04001539 startActivity(i);
1540 }
1541
Cary Clark01cfcdd2010-06-04 16:36:45 -04001542 private boolean dialogIsUp() {
1543 return null != mFindDialog && mFindDialog.isVisible() ||
1544 null != mSelectDialog && mSelectDialog.isVisible();
1545 }
1546
1547 private boolean closeDialog(WebDialog dialog) {
1548 if (null == dialog || !dialog.isVisible()) return false;
Leon Scroggins79e36d92010-04-29 16:01:46 +01001549 Tab currentTab = mTabControl.getCurrentTab();
Cary Clark01cfcdd2010-06-04 16:36:45 -04001550 currentTab.closeDialog(dialog);
1551 dialog.dismiss();
1552 return true;
1553 }
1554
1555 /*
1556 * Remove the find dialog or select dialog.
1557 */
1558 public void closeDialogs() {
1559 if (!(closeDialog(mFindDialog) || closeDialog(mSelectDialog))) return;
Michael Kolba2b2ba82010-08-04 17:54:03 -07001560 // If the Find was being performed in the main WebView, replace the
1561 // embedded title bar.
1562 Tab currentTab = mTabControl.getCurrentTab();
1563 if (currentTab.getSubWebView() == null) {
1564 WebView mainView = currentTab.getWebView();
1565 if (mainView != null) {
1566 mainView.setEmbeddedTitleBar(mTitleBar);
Leon Scroggins79e36d92010-04-29 16:01:46 +01001567 }
1568 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001569 mMenuState = R.id.MAIN_MENU;
Leon Scroggins79e36d92010-04-29 16:01:46 +01001570 if (mInLoad) {
1571 // The title bar was hidden, because otherwise it would cover up the
Michael Kolba2b2ba82010-08-04 17:54:03 -07001572 // find or select dialog. Now that the dialog has been removed,
Cary Clark01cfcdd2010-06-04 16:36:45 -04001573 // show the fake title bar once again.
Leon Scroggins79e36d92010-04-29 16:01:46 +01001574 showFakeTitleBar();
1575 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001576 }
1577
Cary Clark01cfcdd2010-06-04 16:36:45 -04001578 public void showFindDialog() {
1579 if (null == mFindDialog) {
1580 mFindDialog = new FindDialog(this);
1581 }
1582 showDialog(mFindDialog).setFindIsUp(true);
1583 }
1584
1585 public void setFindDialogText(String text) {
1586 mFindDialog.setText(text);
1587 }
1588
1589 public void showSelectDialog() {
1590 if (null == mSelectDialog) {
1591 mSelectDialog = new SelectDialog(this);
1592 }
1593 showDialog(mSelectDialog).setUpSelect();
1594 mSelectDialog.hideSoftInput();
1595 }
1596
Grace Kloba22ac16e2009-10-07 18:00:23 -07001597 @Override
1598 public boolean onPrepareOptionsMenu(Menu menu) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001599 // This happens when the user begins to hold down the menu key, so
1600 // allow them to chord to get a shortcut.
1601 mCanChord = true;
1602 // Note: setVisible will decide whether an item is visible; while
1603 // setEnabled() will decide whether an item is enabled, which also means
1604 // whether the matching shortcut key will function.
1605 super.onPrepareOptionsMenu(menu);
1606 switch (mMenuState) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001607 case EMPTY_MENU:
1608 if (mCurrentMenuState != mMenuState) {
1609 menu.setGroupVisible(R.id.MAIN_MENU, false);
1610 menu.setGroupEnabled(R.id.MAIN_MENU, false);
1611 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001612 }
1613 break;
1614 default:
1615 if (mCurrentMenuState != mMenuState) {
1616 menu.setGroupVisible(R.id.MAIN_MENU, true);
1617 menu.setGroupEnabled(R.id.MAIN_MENU, true);
1618 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001619 }
1620 final WebView w = getTopWindow();
1621 boolean canGoBack = false;
1622 boolean canGoForward = false;
1623 boolean isHome = false;
1624 if (w != null) {
1625 canGoBack = w.canGoBack();
1626 canGoForward = w.canGoForward();
1627 isHome = mSettings.getHomePage().equals(w.getUrl());
1628 }
1629 final MenuItem back = menu.findItem(R.id.back_menu_id);
1630 back.setEnabled(canGoBack);
1631
1632 final MenuItem home = menu.findItem(R.id.homepage_menu_id);
1633 home.setEnabled(!isHome);
1634
Michael Kolbe0a36662010-06-29 10:37:12 -07001635 final MenuItem forward = menu.findItem(R.id.forward_menu_id);
1636 forward.setEnabled(canGoForward);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001637
Michael Kolbed217742010-08-10 17:52:34 -07001638 if (!mXLargeScreenSize) {
1639 final MenuItem newtab = menu.findItem(R.id.new_tab_menu_id);
1640 newtab.setEnabled(mTabControl.canCreateNewTab());
1641 }
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001642
The Android Open Source Project0c908882009-03-03 19:32:16 -08001643 // decide whether to show the share link option
1644 PackageManager pm = getPackageManager();
1645 Intent send = new Intent(Intent.ACTION_SEND);
1646 send.setType("text/plain");
1647 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1648 menu.findItem(R.id.share_page_menu_id).setVisible(ri != null);
1649
The Android Open Source Project0c908882009-03-03 19:32:16 -08001650 boolean isNavDump = mSettings.isNavDump();
1651 final MenuItem nav = menu.findItem(R.id.dump_nav_menu_id);
1652 nav.setVisible(isNavDump);
1653 nav.setEnabled(isNavDump);
Andrei Popescu7a8b88b2010-02-02 00:30:38 +00001654
1655 boolean showDebugSettings = mSettings.showDebugSettings();
1656 final MenuItem counter = menu.findItem(R.id.dump_counters_menu_id);
1657 counter.setVisible(showDebugSettings);
1658 counter.setEnabled(showDebugSettings);
1659
The Android Open Source Project0c908882009-03-03 19:32:16 -08001660 break;
1661 }
1662 mCurrentMenuState = mMenuState;
1663 return true;
1664 }
1665
1666 @Override
1667 public void onCreateContextMenu(ContextMenu menu, View v,
1668 ContextMenuInfo menuInfo) {
Leon Scroggins571b3762010-05-26 10:25:01 -04001669 if (v instanceof TitleBarBase) {
Leon Scroggins4e9f89b2010-02-22 16:54:14 -05001670 return;
1671 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001672 WebView webview = (WebView) v;
1673 WebView.HitTestResult result = webview.getHitTestResult();
1674 if (result == null) {
1675 return;
1676 }
1677
1678 int type = result.getType();
1679 if (type == WebView.HitTestResult.UNKNOWN_TYPE) {
1680 Log.w(LOGTAG,
1681 "We should not show context menu when nothing is touched");
1682 return;
1683 }
1684 if (type == WebView.HitTestResult.EDIT_TEXT_TYPE) {
1685 // let TextView handles context menu
1686 return;
1687 }
1688
1689 // Note, http://b/issue?id=1106666 is requesting that
1690 // an inflated menu can be used again. This is not available
1691 // yet, so inflate each time (yuk!)
1692 MenuInflater inflater = getMenuInflater();
1693 inflater.inflate(R.menu.browsercontext, menu);
1694
1695 // Show the correct menu group
Leon Scroggins III9e997c72010-05-26 13:25:16 -04001696 final String extra = result.getExtra();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001697 menu.setGroupVisible(R.id.PHONE_MENU,
1698 type == WebView.HitTestResult.PHONE_TYPE);
1699 menu.setGroupVisible(R.id.EMAIL_MENU,
1700 type == WebView.HitTestResult.EMAIL_TYPE);
1701 menu.setGroupVisible(R.id.GEO_MENU,
1702 type == WebView.HitTestResult.GEO_TYPE);
1703 menu.setGroupVisible(R.id.IMAGE_MENU,
1704 type == WebView.HitTestResult.IMAGE_TYPE
1705 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1706 menu.setGroupVisible(R.id.ANCHOR_MENU,
1707 type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1708 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1709
1710 // Setup custom handling depending on the type
1711 switch (type) {
1712 case WebView.HitTestResult.PHONE_TYPE:
1713 menu.setHeaderTitle(Uri.decode(extra));
1714 menu.findItem(R.id.dial_context_menu_id).setIntent(
1715 new Intent(Intent.ACTION_VIEW, Uri
1716 .parse(WebView.SCHEME_TEL + extra)));
1717 Intent addIntent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
1718 addIntent.putExtra(Insert.PHONE, Uri.decode(extra));
Cary Clark5e335a32009-09-22 14:53:11 -04001719 addIntent.setType(ContactsContract.Contacts.CONTENT_ITEM_TYPE);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001720 menu.findItem(R.id.add_contact_context_menu_id).setIntent(
1721 addIntent);
1722 menu.findItem(R.id.copy_phone_context_menu_id).setOnMenuItemClickListener(
1723 new Copy(extra));
1724 break;
1725
1726 case WebView.HitTestResult.EMAIL_TYPE:
1727 menu.setHeaderTitle(extra);
1728 menu.findItem(R.id.email_context_menu_id).setIntent(
1729 new Intent(Intent.ACTION_VIEW, Uri
1730 .parse(WebView.SCHEME_MAILTO + extra)));
1731 menu.findItem(R.id.copy_mail_context_menu_id).setOnMenuItemClickListener(
1732 new Copy(extra));
1733 break;
1734
1735 case WebView.HitTestResult.GEO_TYPE:
1736 menu.setHeaderTitle(extra);
1737 menu.findItem(R.id.map_context_menu_id).setIntent(
1738 new Intent(Intent.ACTION_VIEW, Uri
1739 .parse(WebView.SCHEME_GEO
1740 + URLEncoder.encode(extra))));
1741 menu.findItem(R.id.copy_geo_context_menu_id).setOnMenuItemClickListener(
1742 new Copy(extra));
1743 break;
1744
1745 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1746 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
1747 TextView titleView = (TextView) LayoutInflater.from(this)
1748 .inflate(android.R.layout.browser_link_context_header,
1749 null);
1750 titleView.setText(extra);
1751 menu.setHeaderView(titleView);
1752 // decide whether to show the open link in new tab option
Leon Scroggins III9e997c72010-05-26 13:25:16 -04001753 boolean showNewTab = mTabControl.canCreateNewTab();
1754 MenuItem newTabItem
1755 = menu.findItem(R.id.open_newtab_context_menu_id);
1756 newTabItem.setVisible(showNewTab);
1757 if (showNewTab) {
1758 newTabItem.setOnMenuItemClickListener(
1759 new MenuItem.OnMenuItemClickListener() {
1760 public boolean onMenuItemClick(MenuItem item) {
1761 final Tab parent = mTabControl.getCurrentTab();
Michael Kolb68792c82010-08-09 16:39:18 -07001762 final Tab newTab = openTab(extra, false);
Leon Scroggins III9e997c72010-05-26 13:25:16 -04001763 if (newTab != parent) {
1764 parent.addChildTab(newTab);
1765 }
1766 return true;
1767 }
1768 });
1769 }
Ben Murdochde353622009-10-12 10:29:00 +01001770 menu.findItem(R.id.bookmark_context_menu_id).setVisible(
1771 Bookmarks.urlHasAcceptableScheme(extra));
The Android Open Source Project0c908882009-03-03 19:32:16 -08001772 PackageManager pm = getPackageManager();
1773 Intent send = new Intent(Intent.ACTION_SEND);
1774 send.setType("text/plain");
1775 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1776 menu.findItem(R.id.share_link_context_menu_id).setVisible(ri != null);
1777 if (type == WebView.HitTestResult.SRC_ANCHOR_TYPE) {
1778 break;
1779 }
1780 // otherwise fall through to handle image part
1781 case WebView.HitTestResult.IMAGE_TYPE:
1782 if (type == WebView.HitTestResult.IMAGE_TYPE) {
1783 menu.setHeaderTitle(extra);
1784 }
1785 menu.findItem(R.id.view_image_context_menu_id).setIntent(
1786 new Intent(Intent.ACTION_VIEW, Uri.parse(extra)));
1787 menu.findItem(R.id.download_context_menu_id).
1788 setOnMenuItemClickListener(new Download(extra));
Ben Murdoch4f75ba22009-10-27 11:48:28 +00001789 menu.findItem(R.id.set_wallpaper_context_menu_id).
1790 setOnMenuItemClickListener(new SetAsWallpaper(extra));
The Android Open Source Project0c908882009-03-03 19:32:16 -08001791 break;
1792
1793 default:
1794 Log.w(LOGTAG, "We should not get here.");
1795 break;
1796 }
Leon Scrogginsb2b19f52009-10-09 16:10:00 -04001797 hideFakeTitleBar();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001798 }
1799
The Android Open Source Project0c908882009-03-03 19:32:16 -08001800 // Attach the given tab to the content view.
Grace Klobac928c302009-09-17 11:51:21 -07001801 // this should only be called for the current tab.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001802 private void attachTabToContentView(Tab t) {
Steve Block2bc69912009-07-30 14:45:13 +01001803 // Attach the container that contains the main WebView and any other UI
1804 // associated with the tab.
Patrick Scottd0119532009-09-17 08:00:31 -04001805 t.attachTabToContentView(mContentView);
Ben Murdochbff2d602009-07-01 20:19:05 +01001806
1807 if (mShouldShowErrorConsole) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001808 ErrorConsoleView errorConsole = t.getErrorConsole(true);
Ben Murdochbff2d602009-07-01 20:19:05 +01001809 if (errorConsole.numberOfErrors() == 0) {
1810 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
1811 } else {
1812 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
1813 }
1814
1815 mErrorConsoleContainer.addView(errorConsole,
Romain Guy15b8ec62010-01-08 15:06:43 -08001816 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
Ben Murdochbff2d602009-07-01 20:19:05 +01001817 ViewGroup.LayoutParams.WRAP_CONTENT));
1818 }
1819
Michael Kolba2b2ba82010-08-04 17:54:03 -07001820 WebView view = t.getWebView();
1821 view.setEmbeddedTitleBar(mTitleBar);
Leon Scroggins58d56c62010-01-28 15:12:40 -05001822 if (t.isInVoiceSearchMode()) {
1823 showVoiceTitleBar(t.getVoiceDisplayTitle());
1824 } else {
1825 revertVoiceTitleBar();
1826 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001827 // Request focus on the top window.
1828 t.getTopWindow().requestFocus();
Michael Kolba2b2ba82010-08-04 17:54:03 -07001829 if (mTabControl.getTabChangeListener() != null) {
1830 mTabControl.getTabChangeListener().onCurrentTab(t);
1831 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001832 }
1833
1834 // Attach a sub window to the main WebView of the given tab.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001835 void attachSubWindow(Tab t) {
Patrick Scottd0119532009-09-17 08:00:31 -04001836 t.attachSubWindow(mContentView);
1837 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001838 }
1839
1840 // Remove the given tab from the content view.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001841 private void removeTabFromContentView(Tab t) {
Steve Block2bc69912009-07-30 14:45:13 +01001842 // Remove the container that contains the main WebView.
Patrick Scottd0119532009-09-17 08:00:31 -04001843 t.removeTabFromContentView(mContentView);
Ben Murdochbff2d602009-07-01 20:19:05 +01001844
Grace Kloba22ac16e2009-10-07 18:00:23 -07001845 ErrorConsoleView errorConsole = t.getErrorConsole(false);
1846 if (errorConsole != null) {
1847 mErrorConsoleContainer.removeView(errorConsole);
Ben Murdochbff2d602009-07-01 20:19:05 +01001848 }
1849
Michael Kolba2b2ba82010-08-04 17:54:03 -07001850 WebView view = t.getWebView();
1851 if (view != null) {
1852 view.setEmbeddedTitleBar(null);
Leon Scrogginsbb85b902009-09-14 19:27:20 -04001853 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001854 }
1855
1856 // Remove the sub window if it exists. Also called by TabControl when the
1857 // user clicks the 'X' to dismiss a sub window.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001858 /* package */ void dismissSubWindow(Tab t) {
Patrick Scottd0119532009-09-17 08:00:31 -04001859 t.removeSubWindow(mContentView);
Grace Kloba22ac16e2009-10-07 18:00:23 -07001860 // dismiss the subwindow. This will destroy the WebView.
1861 t.dismissSubWindow();
Patrick Scottd0119532009-09-17 08:00:31 -04001862 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001863 }
1864
Leon Scroggins1f005d32009-08-10 17:36:42 -04001865 // A wrapper function of {@link #openTabAndShow(UrlData, boolean, String)}
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07001866 // that accepts url as string.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001867 private Tab openTabAndShow(String url, boolean closeOnExit, String appId) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001868 return openTabAndShow(new UrlData(url), closeOnExit, appId);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001869 }
1870
1871 // This method does a ton of stuff. It will attempt to create a new tab
1872 // if we haven't reached MAX_TABS. Otherwise it uses the current tab. If
Leon Scroggins1f005d32009-08-10 17:36:42 -04001873 // url isn't null, it will load the given url.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001874 /* package */Tab openTabAndShow(UrlData urlData, boolean closeOnExit,
1875 String appId) {
1876 final Tab currentTab = mTabControl.getCurrentTab();
1877 if (mTabControl.canCreateNewTab()) {
1878 final Tab tab = mTabControl.createNewTab(closeOnExit, appId,
Elliott Slaughterf0f03952010-07-14 18:10:36 -07001879 urlData.mUrl, false);
Leon Scroggins1f005d32009-08-10 17:36:42 -04001880 WebView webview = tab.getWebView();
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001881 // If the last tab was removed from the active tabs page, currentTab
1882 // will be null.
1883 if (currentTab != null) {
1884 removeTabFromContentView(currentTab);
1885 }
Patrick Scott8bbd69f2009-08-14 13:35:53 -04001886 // We must set the new tab as the current tab to reflect the old
1887 // animation behavior.
1888 mTabControl.setCurrentTab(tab);
Grace Klobaeb6eef42009-09-15 17:56:32 -07001889 attachTabToContentView(tab);
Leon Scroggins160a7e72009-08-14 18:28:01 -04001890 if (!urlData.isEmpty()) {
Patrick Scott9d53da02010-02-19 10:19:01 -05001891 loadUrlDataIn(tab, urlData);
Leon Scroggins1f005d32009-08-10 17:36:42 -04001892 }
1893 return tab;
1894 } else {
1895 // Get rid of the subwindow if it exists
1896 dismissSubWindow(currentTab);
1897 if (!urlData.isEmpty()) {
1898 // Load the given url.
Patrick Scott9d53da02010-02-19 10:19:01 -05001899 loadUrlDataIn(currentTab, urlData);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001900 }
Leon Scroggins58d56c62010-01-28 15:12:40 -05001901 return currentTab;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001902 }
1903 }
1904
Michael Kolb68792c82010-08-09 16:39:18 -07001905 private Tab openTab(String url, boolean forceForeground) {
1906 if (mSettings.openInBackground() && !forceForeground) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001907 Tab t = mTabControl.createNewTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001908 if (t != null) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001909 WebView view = t.getWebView();
Leon Scroggins92472e82010-02-17 16:32:28 -05001910 loadUrl(view, url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001911 }
Grace Klobac9181842009-04-14 08:53:22 -07001912 return t;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001913 } else {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001914 return openTabAndShow(url, false, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001915 }
1916 }
1917
Elliott Slaughterf0f03952010-07-14 18:10:36 -07001918 /* package */ Tab openIncognitoTab() {
1919 if (mTabControl.canCreateNewTab()) {
1920 Tab currentTab = mTabControl.getCurrentTab();
1921 Tab tab = mTabControl.createNewTab(false, null, null, true);
1922 if (currentTab != null) {
1923 removeTabFromContentView(currentTab);
1924 }
1925 mTabControl.setCurrentTab(tab);
1926 attachTabToContentView(tab);
1927 return tab;
1928 }
1929 return null;
1930 }
1931
The Android Open Source Project0c908882009-03-03 19:32:16 -08001932 private class Copy implements OnMenuItemClickListener {
1933 private CharSequence mText;
1934
1935 public boolean onMenuItemClick(MenuItem item) {
1936 copy(mText);
1937 return true;
1938 }
1939
1940 public Copy(CharSequence toCopy) {
1941 mText = toCopy;
1942 }
1943 }
1944
1945 private class Download implements OnMenuItemClickListener {
1946 private String mText;
1947
1948 public boolean onMenuItemClick(MenuItem item) {
1949 onDownloadStartNoStream(mText, null, null, null, -1);
1950 return true;
1951 }
1952
1953 public Download(String toDownload) {
1954 mText = toDownload;
1955 }
1956 }
1957
Ben Murdoch4f75ba22009-10-27 11:48:28 +00001958 private class SetAsWallpaper extends Thread implements
1959 OnMenuItemClickListener, DialogInterface.OnCancelListener {
1960 private URL mUrl;
1961 private ProgressDialog mWallpaperProgress;
1962 private boolean mCanceled = false;
1963
1964 public SetAsWallpaper(String url) {
1965 try {
1966 mUrl = new URL(url);
1967 } catch (MalformedURLException e) {
1968 mUrl = null;
1969 }
1970 }
1971
1972 public void onCancel(DialogInterface dialog) {
1973 mCanceled = true;
1974 }
1975
1976 public boolean onMenuItemClick(MenuItem item) {
1977 if (mUrl != null) {
1978 // The user may have tried to set a image with a large file size as their
1979 // background so it may take a few moments to perform the operation. Display
1980 // a progress spinner while it is working.
1981 mWallpaperProgress = new ProgressDialog(BrowserActivity.this);
1982 mWallpaperProgress.setIndeterminate(true);
1983 mWallpaperProgress.setMessage(getText(R.string.progress_dialog_setting_wallpaper));
1984 mWallpaperProgress.setCancelable(true);
1985 mWallpaperProgress.setOnCancelListener(this);
1986 mWallpaperProgress.show();
1987 start();
1988 }
1989 return true;
1990 }
1991
Michael Kolbe0a36662010-06-29 10:37:12 -07001992 @Override
Ben Murdoch4f75ba22009-10-27 11:48:28 +00001993 public void run() {
1994 Drawable oldWallpaper = BrowserActivity.this.getWallpaper();
1995 try {
1996 // TODO: This will cause the resource to be downloaded again, when we
1997 // should in most cases be able to grab it from the cache. To fix this
1998 // we should query WebCore to see if we can access a cached version and
1999 // instead open an input stream on that. This pattern could also be used
2000 // in the download manager where the same problem exists.
2001 InputStream inputstream = mUrl.openStream();
2002 if (inputstream != null) {
2003 setWallpaper(inputstream);
2004 }
2005 } catch (IOException e) {
2006 Log.e(LOGTAG, "Unable to set new wallpaper");
2007 // Act as though the user canceled the operation so we try to
2008 // restore the old wallpaper.
2009 mCanceled = true;
2010 }
2011
2012 if (mCanceled) {
2013 // Restore the old wallpaper if the user cancelled whilst we were setting
2014 // the new wallpaper.
2015 int width = oldWallpaper.getIntrinsicWidth();
2016 int height = oldWallpaper.getIntrinsicHeight();
2017 Bitmap bm = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
2018 Canvas canvas = new Canvas(bm);
2019 oldWallpaper.setBounds(0, 0, width, height);
2020 oldWallpaper.draw(canvas);
2021 try {
2022 setWallpaper(bm);
2023 } catch (IOException e) {
2024 Log.e(LOGTAG, "Unable to restore old wallpaper.");
2025 }
2026 mCanceled = false;
2027 }
2028
2029 if (mWallpaperProgress.isShowing()) {
2030 mWallpaperProgress.dismiss();
2031 }
2032 }
2033 }
2034
The Android Open Source Project0c908882009-03-03 19:32:16 -08002035 private void copy(CharSequence text) {
Dianne Hackborn80f32622010-08-05 14:17:53 -07002036 ClipboardManager cm = (ClipboardManager)getSystemService(Context.CLIPBOARD_SERVICE);
2037 cm.setText(text);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002038 }
2039
2040 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08002041 * Resets the browser title-view to whatever it must be
2042 * (for example, if we had a loading error)
2043 * When we have a new page, we call resetTitle, when we
2044 * have to reset the titlebar to whatever it used to be
2045 * (for example, if the user chose to stop loading), we
2046 * call resetTitleAndRevertLockIcon.
2047 */
2048 /* package */ void resetTitleAndRevertLockIcon() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002049 mTabControl.getCurrentTab().revertLockIcon();
2050 updateLockIconToLatest();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002051 resetTitleIconAndProgress();
2052 }
2053
2054 /**
2055 * Reset the title, favicon, and progress.
2056 */
2057 private void resetTitleIconAndProgress() {
2058 WebView current = mTabControl.getCurrentWebView();
2059 if (current == null) {
2060 return;
2061 }
2062 resetTitleAndIcon(current);
2063 int progress = current.getProgress();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002064 current.getWebChromeClient().onProgressChanged(current, progress);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002065 }
2066
2067 // Reset the title and the icon based on the given item.
2068 private void resetTitleAndIcon(WebView view) {
2069 WebHistoryItem item = view.copyBackForwardList().getCurrentItem();
2070 if (item != null) {
Leon Scroggins68579392009-09-15 15:31:54 -04002071 setUrlTitle(item.getUrl(), item.getTitle());
The Android Open Source Project0c908882009-03-03 19:32:16 -08002072 setFavicon(item.getFavicon());
2073 } else {
Leon Scroggins68579392009-09-15 15:31:54 -04002074 setUrlTitle(null, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002075 setFavicon(null);
2076 }
2077 }
2078
2079 /**
2080 * Sets a title composed of the URL and the title string.
2081 * @param url The URL of the site being loaded.
2082 * @param title The title of the site being loaded.
2083 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07002084 void setUrlTitle(String url, String title) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002085 mUrl = url;
2086 mTitle = title;
2087
Leon Scroggins58d56c62010-01-28 15:12:40 -05002088 // If we are in voice search mode, the title has already been set.
2089 if (mTabControl.getCurrentTab().isInVoiceSearchMode()) return;
2090 mTitleBar.setDisplayTitle(url);
Michael Kolba2b2ba82010-08-04 17:54:03 -07002091 mFakeTitleBar.setDisplayTitle(url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002092 }
2093
2094 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08002095 * @param url The URL to build a title version of the URL from.
2096 * @return The title version of the URL or null if fails.
2097 * The title version of the URL can be either the URL hostname,
2098 * or the hostname with an "https://" prefix (for secure URLs),
2099 * or an empty string if, for example, the URL in question is a
2100 * file:// URL with no hostname.
2101 */
Leon Scroggins32e14a62009-06-11 10:26:34 -04002102 /* package */ static String buildTitleUrl(String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002103 String titleUrl = null;
2104
2105 if (url != null) {
2106 try {
2107 // parse the url string
2108 URL urlObj = new URL(url);
2109 if (urlObj != null) {
2110 titleUrl = "";
2111
2112 String protocol = urlObj.getProtocol();
2113 String host = urlObj.getHost();
2114
2115 if (host != null && 0 < host.length()) {
2116 titleUrl = host;
2117 if (protocol != null) {
2118 // if a secure site, add an "https://" prefix!
2119 if (protocol.equalsIgnoreCase("https")) {
2120 titleUrl = protocol + "://" + host;
2121 }
2122 }
2123 }
2124 }
2125 } catch (MalformedURLException e) {}
2126 }
2127
2128 return titleUrl;
2129 }
2130
2131 // Set the favicon in the title bar.
Grace Kloba22ac16e2009-10-07 18:00:23 -07002132 void setFavicon(Bitmap icon) {
Leon Scroggins68579392009-09-15 15:31:54 -04002133 mTitleBar.setFavicon(icon);
Michael Kolba2b2ba82010-08-04 17:54:03 -07002134 mFakeTitleBar.setFavicon(icon);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002135 }
2136
2137 /**
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002138 * Close the tab, remove its associated title bar, and adjust mTabControl's
2139 * current tab to a valid value.
Leon Scroggins1f005d32009-08-10 17:36:42 -04002140 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07002141 /* package */ void closeTab(Tab t) {
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002142 int currentIndex = mTabControl.getCurrentIndex();
2143 int removeIndex = mTabControl.getTabIndex(t);
Leon Scroggins1f005d32009-08-10 17:36:42 -04002144 mTabControl.removeTab(t);
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002145 if (currentIndex >= removeIndex && currentIndex != 0) {
2146 currentIndex--;
2147 }
2148 mTabControl.setCurrentTab(mTabControl.getTab(currentIndex));
Andrei Popescua5bf1de2009-09-23 16:39:23 +01002149 resetTitleIconAndProgress();
Leon Scroggins654899b2010-06-25 16:25:23 -04002150 updateLockIconToLatest();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002151 }
2152
Leon Scrogginsdcc5eeb2010-02-23 17:26:37 -05002153 /* package */ void goBackOnePageOrQuit() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002154 Tab current = mTabControl.getCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002155 if (current == null) {
2156 /*
2157 * Instead of finishing the activity, simply push this to the back
2158 * of the stack and let ActivityManager to choose the foreground
2159 * activity. As BrowserActivity is singleTask, it will be always the
2160 * root of the task. So we can use either true or false for
2161 * moveTaskToBack().
2162 */
2163 moveTaskToBack(true);
Grace Kloba00d85e72009-09-23 18:50:05 -07002164 return;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002165 }
2166 WebView w = current.getWebView();
2167 if (w.canGoBack()) {
2168 w.goBack();
2169 } else {
2170 // Check to see if we are closing a window that was created by
2171 // another window. If so, we switch back to that window.
Grace Kloba22ac16e2009-10-07 18:00:23 -07002172 Tab parent = current.getParentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002173 if (parent != null) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04002174 switchToTab(mTabControl.getTabIndex(parent));
2175 // Now we close the other tab
2176 closeTab(current);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002177 } else {
2178 if (current.closeOnExit()) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002179 // force the tab's inLoad() to be false as we are going to
2180 // either finish the activity or remove the tab. This will
2181 // ensure pauseWebViewTimers() taking action.
2182 mTabControl.getCurrentTab().clearInLoad();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002183 if (mTabControl.getTabCount() == 1) {
2184 finish();
2185 return;
2186 }
Mike Reed7bfa63b2009-05-28 11:08:32 -04002187 // call pauseWebViewTimers() now, we won't be able to call
2188 // it in onPause() as the WebView won't be valid.
Grace Klobaec1b5ad2009-08-18 08:42:32 -07002189 // Temporarily change mActivityInPause to be true as
2190 // pauseWebViewTimers() will do nothing if mActivityInPause
2191 // is false.
Grace Kloba918e1d72009-08-13 14:55:06 -07002192 boolean savedState = mActivityInPause;
2193 if (savedState) {
Grace Klobaec1b5ad2009-08-18 08:42:32 -07002194 Log.e(LOGTAG, "BrowserActivity is already paused "
2195 + "while handing goBackOnePageOrQuit.");
Grace Kloba918e1d72009-08-13 14:55:06 -07002196 }
2197 mActivityInPause = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -04002198 pauseWebViewTimers();
Grace Kloba918e1d72009-08-13 14:55:06 -07002199 mActivityInPause = savedState;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002200 removeTabFromContentView(current);
2201 mTabControl.removeTab(current);
2202 }
2203 /*
2204 * Instead of finishing the activity, simply push this to the back
2205 * of the stack and let ActivityManager to choose the foreground
2206 * activity. As BrowserActivity is singleTask, it will be always the
2207 * root of the task. So we can use either true or false for
2208 * moveTaskToBack().
2209 */
2210 moveTaskToBack(true);
2211 }
2212 }
2213 }
2214
Grace Kloba22ac16e2009-10-07 18:00:23 -07002215 boolean isMenuDown() {
2216 return mMenuIsDown;
2217 }
2218
Grace Kloba5942df02009-09-18 11:48:29 -07002219 @Override
2220 public boolean onKeyDown(int keyCode, KeyEvent event) {
Leon Scrogginsf65b50d2009-12-08 10:44:28 -05002221 // Even if MENU is already held down, we need to call to super to open
2222 // the IME on long press.
2223 if (KeyEvent.KEYCODE_MENU == keyCode) {
2224 mMenuIsDown = true;
2225 return super.onKeyDown(keyCode, event);
2226 }
Grace Kloba5942df02009-09-18 11:48:29 -07002227 // The default key mode is DEFAULT_KEYS_SEARCH_LOCAL. As the MENU is
2228 // still down, we don't want to trigger the search. Pretend to consume
2229 // the key and do nothing.
2230 if (mMenuIsDown) return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002231
Grace Kloba5942df02009-09-18 11:48:29 -07002232 switch(keyCode) {
Grace Kloba5942df02009-09-18 11:48:29 -07002233 case KeyEvent.KEYCODE_SPACE:
Grace Klobada0fe552009-09-22 18:17:24 -07002234 // WebView/WebTextView handle the keys in the KeyDown. As
2235 // the Activity's shortcut keys are only handled when WebView
2236 // doesn't, have to do it in onKeyDown instead of onKeyUp.
2237 if (event.isShiftPressed()) {
2238 getTopWindow().pageUp(false);
2239 } else {
2240 getTopWindow().pageDown(false);
2241 }
Grace Kloba5942df02009-09-18 11:48:29 -07002242 return true;
2243 case KeyEvent.KEYCODE_BACK:
2244 if (event.getRepeatCount() == 0) {
2245 event.startTracking();
2246 return true;
2247 } else if (mCustomView == null && mActiveTabsPage == null
2248 && event.isLongPress()) {
Michael Kolb68792c82010-08-09 16:39:18 -07002249 bookmarksOrHistoryPicker(true, false);
Grace Kloba5942df02009-09-18 11:48:29 -07002250 return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002251 }
Grace Kloba5942df02009-09-18 11:48:29 -07002252 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002253 }
Grace Kloba5942df02009-09-18 11:48:29 -07002254 return super.onKeyDown(keyCode, event);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002255 }
2256
Grace Kloba5942df02009-09-18 11:48:29 -07002257 @Override
2258 public boolean onKeyUp(int keyCode, KeyEvent event) {
2259 switch(keyCode) {
2260 case KeyEvent.KEYCODE_MENU:
2261 mMenuIsDown = false;
2262 break;
Grace Kloba5942df02009-09-18 11:48:29 -07002263 case KeyEvent.KEYCODE_BACK:
2264 if (event.isTracking() && !event.isCanceled()) {
2265 if (mCustomView != null) {
2266 // if a custom view is showing, hide it
Grace Kloba22ac16e2009-10-07 18:00:23 -07002267 mTabControl.getCurrentWebView().getWebChromeClient()
2268 .onHideCustomView();
Grace Kloba5942df02009-09-18 11:48:29 -07002269 } else if (mActiveTabsPage != null) {
2270 // if tab page is showing, hide it
2271 removeActiveTabPage(true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002272 } else {
Grace Kloba5942df02009-09-18 11:48:29 -07002273 WebView subwindow = mTabControl.getCurrentSubWindow();
2274 if (subwindow != null) {
2275 if (subwindow.canGoBack()) {
2276 subwindow.goBack();
2277 } else {
2278 dismissSubWindow(mTabControl.getCurrentTab());
2279 }
2280 } else {
2281 goBackOnePageOrQuit();
2282 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002283 }
Grace Kloba5942df02009-09-18 11:48:29 -07002284 return true;
2285 }
2286 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002287 }
Grace Kloba5942df02009-09-18 11:48:29 -07002288 return super.onKeyUp(keyCode, event);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002289 }
2290
Leon Scroggins68579392009-09-15 15:31:54 -04002291 /* package */ void stopLoading() {
Ben Murdochb7cc8b42009-09-28 10:59:09 +01002292 mDidStopLoad = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002293 resetTitleAndRevertLockIcon();
2294 WebView w = getTopWindow();
2295 w.stopLoading();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002296 // FIXME: before refactor, it is using mWebViewClient. So I keep the
2297 // same logic here. But for subwindow case, should we call into the main
2298 // WebView's onPageFinished as we never call its onPageStarted and if
2299 // the page finishes itself, we don't call onPageFinished.
2300 mTabControl.getCurrentWebView().getWebViewClient().onPageFinished(w,
2301 w.getUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08002302
2303 cancelStopToast();
2304 mStopToast = Toast
2305 .makeText(this, R.string.stopping, Toast.LENGTH_SHORT);
2306 mStopToast.show();
2307 }
2308
Grace Kloba22ac16e2009-10-07 18:00:23 -07002309 boolean didUserStopLoading() {
2310 return mDidStopLoad;
2311 }
2312
The Android Open Source Project0c908882009-03-03 19:32:16 -08002313 private void cancelStopToast() {
2314 if (mStopToast != null) {
2315 mStopToast.cancel();
2316 mStopToast = null;
2317 }
2318 }
2319
Grace Kloba22ac16e2009-10-07 18:00:23 -07002320 // called by a UI or non-UI thread to post the message
2321 public void postMessage(int what, int arg1, int arg2, Object obj,
2322 long delayMillis) {
2323 mHandler.sendMessageDelayed(mHandler.obtainMessage(what, arg1, arg2,
2324 obj), delayMillis);
2325 }
2326
2327 // called by a UI or non-UI thread to remove the message
2328 void removeMessages(int what, Object object) {
2329 mHandler.removeMessages(what, object);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002330 }
2331
2332 // public message ids
2333 public final static int LOAD_URL = 1001;
2334 public final static int STOP_LOAD = 1002;
2335
2336 // Message Ids
2337 private static final int FOCUS_NODE_HREF = 102;
Grace Kloba92c18a52009-07-31 23:48:32 -07002338 private static final int RELEASE_WAKELOCK = 107;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002339
Grace Kloba22ac16e2009-10-07 18:00:23 -07002340 static final int UPDATE_BOOKMARK_THUMBNAIL = 108;
Ben Murdoch2694e232009-09-29 09:41:11 +01002341
Ben Murdocheecb4e62010-07-06 16:30:38 +01002342 private static final int TOUCH_ICON_DOWNLOADED = 109;
2343
The Android Open Source Project0c908882009-03-03 19:32:16 -08002344 // Private handler for handling javascript and saving passwords
2345 private Handler mHandler = new Handler() {
2346
Michael Kolbe0a36662010-06-29 10:37:12 -07002347 @Override
The Android Open Source Project0c908882009-03-03 19:32:16 -08002348 public void handleMessage(Message msg) {
2349 switch (msg.what) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002350 case FOCUS_NODE_HREF:
Ben Murdoch2694e232009-09-29 09:41:11 +01002351 {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002352 String url = (String) msg.getData().get("url");
Ben Murdoch90d088c2009-11-17 18:14:04 +00002353 String title = (String) msg.getData().get("title");
The Android Open Source Project0c908882009-03-03 19:32:16 -08002354 if (url == null || url.length() == 0) {
2355 break;
2356 }
2357 HashMap focusNodeMap = (HashMap) msg.obj;
2358 WebView view = (WebView) focusNodeMap.get("webview");
2359 // Only apply the action if the top window did not change.
2360 if (getTopWindow() != view) {
2361 break;
2362 }
2363 switch (msg.arg1) {
2364 case R.id.open_context_menu_id:
2365 case R.id.view_image_context_menu_id:
Leon Scroggins92472e82010-02-17 16:32:28 -05002366 loadUrlFromContext(getTopWindow(), url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002367 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002368 case R.id.bookmark_context_menu_id:
2369 Intent intent = new Intent(BrowserActivity.this,
2370 AddBookmarkPage.class);
2371 intent.putExtra("url", url);
Ben Murdoch90d088c2009-11-17 18:14:04 +00002372 intent.putExtra("title", title);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002373 startActivity(intent);
2374 break;
2375 case R.id.share_link_context_menu_id:
Leon Scroggins3e204452010-05-10 11:06:03 -04002376 sharePage(BrowserActivity.this, title, url, null,
Leon Scroggins96afcb12009-12-10 12:35:56 -05002377 null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002378 break;
2379 case R.id.copy_link_context_menu_id:
2380 copy(url);
2381 break;
2382 case R.id.save_link_context_menu_id:
2383 case R.id.download_context_menu_id:
2384 onDownloadStartNoStream(url, null, null, null, -1);
2385 break;
2386 }
2387 break;
Ben Murdoch2694e232009-09-29 09:41:11 +01002388 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002389
2390 case LOAD_URL:
Leon Scroggins92472e82010-02-17 16:32:28 -05002391 loadUrlFromContext(getTopWindow(), (String) msg.obj);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002392 break;
2393
2394 case STOP_LOAD:
2395 stopLoading();
2396 break;
2397
The Android Open Source Project0c908882009-03-03 19:32:16 -08002398 case RELEASE_WAKELOCK:
2399 if (mWakeLock.isHeld()) {
2400 mWakeLock.release();
Grace Kloba5d0e02e2009-10-05 15:15:36 -07002401 // if we reach here, Browser should be still in the
2402 // background loading after WAKELOCK_TIMEOUT (5-min).
2403 // To avoid burning the battery, stop loading.
2404 mTabControl.stopAllLoading();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002405 }
2406 break;
Ben Murdoch2694e232009-09-29 09:41:11 +01002407
2408 case UPDATE_BOOKMARK_THUMBNAIL:
2409 WebView view = (WebView) msg.obj;
2410 if (view != null) {
2411 updateScreenshot(view);
2412 }
2413 break;
Ben Murdocheecb4e62010-07-06 16:30:38 +01002414
2415 case TOUCH_ICON_DOWNLOADED:
2416 Bundle b = msg.getData();
2417 showSaveToHomescreenDialog(b.getString("url"),
2418 b.getString("title"),
2419 (Bitmap) b.getParcelable("touchIcon"),
2420 (Bitmap) b.getParcelable("favicon"));
2421 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002422 }
2423 }
2424 };
2425
Leon Scroggins96afcb12009-12-10 12:35:56 -05002426 /**
2427 * Share a page, providing the title, url, favicon, and a screenshot. Uses
2428 * an {@link Intent} to launch the Activity chooser.
2429 * @param c Context used to launch a new Activity.
2430 * @param title Title of the page. Stored in the Intent with
Paul Westbrook03e6d392010-02-12 10:33:29 -08002431 * {@link Intent#EXTRA_SUBJECT}
Leon Scroggins96afcb12009-12-10 12:35:56 -05002432 * @param url URL of the page. Stored in the Intent with
2433 * {@link Intent#EXTRA_TEXT}
2434 * @param favicon Bitmap of the favicon for the page. Stored in the Intent
2435 * with {@link Browser#EXTRA_SHARE_FAVICON}
2436 * @param screenshot Bitmap of a screenshot of the page. Stored in the
2437 * Intent with {@link Browser#EXTRA_SHARE_SCREENSHOT}
2438 */
2439 public static final void sharePage(Context c, String title, String url,
2440 Bitmap favicon, Bitmap screenshot) {
2441 Intent send = new Intent(Intent.ACTION_SEND);
2442 send.setType("text/plain");
2443 send.putExtra(Intent.EXTRA_TEXT, url);
Paul Westbrook03e6d392010-02-12 10:33:29 -08002444 send.putExtra(Intent.EXTRA_SUBJECT, title);
Leon Scroggins96afcb12009-12-10 12:35:56 -05002445 send.putExtra(Browser.EXTRA_SHARE_FAVICON, favicon);
2446 send.putExtra(Browser.EXTRA_SHARE_SCREENSHOT, screenshot);
2447 try {
2448 c.startActivity(Intent.createChooser(send, c.getString(
2449 R.string.choosertitle_sharevia)));
2450 } catch(android.content.ActivityNotFoundException ex) {
2451 // if no app handles it, do nothing
2452 }
2453 }
2454
Leon Scroggins89c6d362009-07-15 16:54:37 -04002455 private void updateScreenshot(WebView view) {
2456 // If this is a bookmarked site, add a screenshot to the database.
2457 // FIXME: When should we update? Every time?
2458 // FIXME: Would like to make sure there is actually something to
2459 // draw, but the API for that (WebViewCore.pictureReady()) is not
2460 // currently accessible here.
Ben Murdochaac7aa62009-09-17 16:57:40 +01002461
Ben Murdoch87cc65d2010-06-29 20:34:10 +01002462 final Bitmap bm = createScreenshot(view, getDesiredThumbnailWidth(this),
2463 getDesiredThumbnailHeight(this));
Patrick Scottcb192b52010-04-14 14:38:55 -04002464 if (bm == null) {
2465 return;
Leon Scroggins89c6d362009-07-15 16:54:37 -04002466 }
Patrick Scottcb192b52010-04-14 14:38:55 -04002467
2468 final ContentResolver cr = getContentResolver();
2469 final String url = view.getUrl();
2470 final String originalUrl = view.getOriginalUrl();
2471
2472 new AsyncTask<Void, Void, Void>() {
2473 @Override
2474 protected Void doInBackground(Void... unused) {
2475 Cursor c = null;
2476 try {
Jeff Hamilton84029622010-08-05 14:29:28 -05002477 c = Bookmarks.queryBookmarksForUrl(
Patrick Scottcb192b52010-04-14 14:38:55 -04002478 cr, originalUrl, url, true);
2479 if (c != null) {
2480 if (c.moveToFirst()) {
2481 ContentValues values = new ContentValues();
2482 final ByteArrayOutputStream os
2483 = new ByteArrayOutputStream();
2484 bm.compress(Bitmap.CompressFormat.PNG, 100, os);
2485 values.put(Browser.BookmarkColumns.THUMBNAIL,
2486 os.toByteArray());
2487 do {
2488 cr.update(ContentUris.withAppendedId(
2489 Browser.BOOKMARKS_URI, c.getInt(0)),
2490 values, null, null);
2491 } while (c.moveToNext());
2492 }
2493 }
2494 } catch (IllegalStateException e) {
2495 // Ignore
2496 } finally {
2497 if (c != null) c.close();
2498 }
2499 return null;
2500 }
2501 }.execute();
Leon Scroggins89c6d362009-07-15 16:54:37 -04002502 }
2503
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002504 /**
Leon Scrogginsf8551612009-09-24 16:06:02 -04002505 * Values for the size of the thumbnail created when taking a screenshot.
2506 * Lazily initialized. Instead of using these directly, use
2507 * getDesiredThumbnailWidth() or getDesiredThumbnailHeight().
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002508 */
Leon Scrogginsf8551612009-09-24 16:06:02 -04002509 private static int THUMBNAIL_WIDTH = 0;
2510 private static int THUMBNAIL_HEIGHT = 0;
2511
2512 /**
2513 * Return the desired width for thumbnail screenshots, which are stored in
2514 * the database, and used on the bookmarks screen.
2515 * @param context Context for finding out the density of the screen.
2516 * @return int desired width for thumbnail screenshot.
2517 */
2518 /* package */ static int getDesiredThumbnailWidth(Context context) {
2519 if (THUMBNAIL_WIDTH == 0) {
2520 float density = context.getResources().getDisplayMetrics().density;
2521 THUMBNAIL_WIDTH = (int) (90 * density);
2522 THUMBNAIL_HEIGHT = (int) (80 * density);
2523 }
2524 return THUMBNAIL_WIDTH;
2525 }
2526
2527 /**
2528 * Return the desired height for thumbnail screenshots, which are stored in
2529 * the database, and used on the bookmarks screen.
2530 * @param context Context for finding out the density of the screen.
2531 * @return int desired height for thumbnail screenshot.
2532 */
2533 /* package */ static int getDesiredThumbnailHeight(Context context) {
2534 // To ensure that they are both initialized.
2535 getDesiredThumbnailWidth(context);
2536 return THUMBNAIL_HEIGHT;
2537 }
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002538
Ben Murdoch87cc65d2010-06-29 20:34:10 +01002539 private Bitmap createScreenshot(WebView view, int width, int height) {
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002540 Picture thumbnail = view.capturePicture();
Leon Scroggins45800572009-09-29 16:38:47 -04002541 if (thumbnail == null) {
2542 return null;
2543 }
Ben Murdoch87cc65d2010-06-29 20:34:10 +01002544 Bitmap bm = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002545 Canvas canvas = new Canvas(bm);
2546 // May need to tweak these values to determine what is the
2547 // best scale factor
Ben Murdoch2694e232009-09-29 09:41:11 +01002548 int thumbnailWidth = thumbnail.getWidth();
Ben Murdochae59c3f2009-10-20 18:30:28 +01002549 int thumbnailHeight = thumbnail.getHeight();
2550 float scaleFactorX = 1.0f;
2551 float scaleFactorY = 1.0f;
Ben Murdoch2694e232009-09-29 09:41:11 +01002552 if (thumbnailWidth > 0) {
Ben Murdoch87cc65d2010-06-29 20:34:10 +01002553 scaleFactorX = (float) width / (float)thumbnailWidth;
Ben Murdochae59c3f2009-10-20 18:30:28 +01002554 } else {
2555 return null;
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002556 }
Ben Murdochae59c3f2009-10-20 18:30:28 +01002557
2558 if (view.getWidth() > view.getHeight() &&
2559 thumbnailHeight < view.getHeight() && thumbnailHeight > 0) {
2560 // If the device is in landscape and the page is shorter
2561 // than the height of the view, stretch the thumbnail to fill the
2562 // space.
Ben Murdoch87cc65d2010-06-29 20:34:10 +01002563 scaleFactorY = (float) height / (float)thumbnailHeight;
Ben Murdochae59c3f2009-10-20 18:30:28 +01002564 } else {
2565 // In the portrait case, this looks nice.
2566 scaleFactorY = scaleFactorX;
2567 }
2568
2569 canvas.scale(scaleFactorX, scaleFactorY);
2570
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002571 thumbnail.draw(canvas);
2572 return bm;
2573 }
2574
The Android Open Source Project0c908882009-03-03 19:32:16 -08002575 // -------------------------------------------------------------------------
Grace Kloba22ac16e2009-10-07 18:00:23 -07002576 // Helper function for WebViewClient.
The Android Open Source Project0c908882009-03-03 19:32:16 -08002577 //-------------------------------------------------------------------------
2578
2579 // Use in overrideUrlLoading
2580 /* package */ final static String SCHEME_WTAI = "wtai://wp/";
2581 /* package */ final static String SCHEME_WTAI_MC = "wtai://wp/mc;";
2582 /* package */ final static String SCHEME_WTAI_SD = "wtai://wp/sd;";
2583 /* package */ final static String SCHEME_WTAI_AP = "wtai://wp/ap;";
2584
Leon Scroggins92472e82010-02-17 16:32:28 -05002585 // Keep this initial progress in sync with initialProgressValue (* 100)
2586 // in ProgressTracker.cpp
2587 private final static int INITIAL_PROGRESS = 10;
2588
Grace Kloba22ac16e2009-10-07 18:00:23 -07002589 void onPageStarted(WebView view, String url, Bitmap favicon) {
2590 // when BrowserActivity just starts, onPageStarted may be called before
2591 // onResume as it is triggered from onCreate. Call resumeWebViewTimers
2592 // to start the timer. As we won't switch tabs while an activity is in
2593 // pause state, we can ensure calling resume and pause in pair.
2594 if (mActivityInPause) resumeWebViewTimers();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002595
Grace Kloba22ac16e2009-10-07 18:00:23 -07002596 resetLockIcon(url);
2597 setUrlTitle(url, null);
2598 setFavicon(favicon);
Leon Scroggins8cf8f682009-11-04 11:13:50 -08002599 // Show some progress so that the user knows the page is beginning to
2600 // load
Leon Scroggins92472e82010-02-17 16:32:28 -05002601 onProgressChanged(view, INITIAL_PROGRESS);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002602 mDidStopLoad = false;
Grace Kloba22ac16e2009-10-07 18:00:23 -07002603 if (!mIsNetworkUp) createAndShowNetworkDialog();
Cary Clark01cfcdd2010-06-04 16:36:45 -04002604 closeDialogs();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002605 if (mSettings.isTracing()) {
2606 String host;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002607 try {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002608 WebAddress uri = new WebAddress(url);
2609 host = uri.mHost;
2610 } catch (android.net.ParseException ex) {
2611 host = "browser";
The Android Open Source Project0c908882009-03-03 19:32:16 -08002612 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002613 host = host.replace('.', '_');
2614 host += ".trace";
2615 mInTrace = true;
2616 Debug.startMethodTracing(host, 20 * 1024 * 1024);
2617 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002618
Grace Kloba22ac16e2009-10-07 18:00:23 -07002619 // Performance probe
2620 if (false) {
2621 mStart = SystemClock.uptimeMillis();
2622 mProcessStart = Process.getElapsedCpuTime();
2623 long[] sysCpu = new long[7];
2624 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2625 sysCpu, null)) {
2626 mUserStart = sysCpu[0] + sysCpu[1];
2627 mSystemStart = sysCpu[2];
2628 mIdleStart = sysCpu[3];
2629 mIrqStart = sysCpu[4] + sysCpu[5] + sysCpu[6];
2630 }
2631 mUiStart = SystemClock.currentThreadTimeMillis();
2632 }
2633 }
2634
2635 void onPageFinished(WebView view, String url) {
2636 // Reset the title and icon in case we stopped a provisional load.
2637 resetTitleAndIcon(view);
2638 // Update the lock icon image only once we are done loading
2639 updateLockIconToLatest();
2640 // pause the WebView timer and release the wake lock if it is finished
2641 // while BrowserActivity is in pause state.
2642 if (mActivityInPause && pauseWebViewTimers()) {
2643 if (mWakeLock.isHeld()) {
2644 mHandler.removeMessages(RELEASE_WAKELOCK);
2645 mWakeLock.release();
2646 }
2647 }
2648
2649 // Performance probe
2650 if (false) {
2651 long[] sysCpu = new long[7];
2652 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2653 sysCpu, null)) {
2654 String uiInfo = "UI thread used "
2655 + (SystemClock.currentThreadTimeMillis() - mUiStart)
2656 + " ms";
2657 if (LOGD_ENABLED) {
2658 Log.d(LOGTAG, uiInfo);
2659 }
2660 //The string that gets written to the log
2661 String performanceString = "It took total "
2662 + (SystemClock.uptimeMillis() - mStart)
2663 + " ms clock time to load the page."
2664 + "\nbrowser process used "
2665 + (Process.getElapsedCpuTime() - mProcessStart)
2666 + " ms, user processes used "
2667 + (sysCpu[0] + sysCpu[1] - mUserStart) * 10
2668 + " ms, kernel used "
2669 + (sysCpu[2] - mSystemStart) * 10
2670 + " ms, idle took " + (sysCpu[3] - mIdleStart) * 10
2671 + " ms and irq took "
2672 + (sysCpu[4] + sysCpu[5] + sysCpu[6] - mIrqStart)
2673 * 10 + " ms, " + uiInfo;
2674 if (LOGD_ENABLED) {
2675 Log.d(LOGTAG, performanceString + "\nWebpage: " + url);
2676 }
2677 if (url != null) {
2678 // strip the url to maintain consistency
2679 String newUrl = new String(url);
2680 if (newUrl.startsWith("http://www.")) {
2681 newUrl = newUrl.substring(11);
2682 } else if (newUrl.startsWith("http://")) {
2683 newUrl = newUrl.substring(7);
2684 } else if (newUrl.startsWith("https://www.")) {
2685 newUrl = newUrl.substring(12);
2686 } else if (newUrl.startsWith("https://")) {
2687 newUrl = newUrl.substring(8);
2688 }
2689 if (LOGD_ENABLED) {
2690 Log.d(LOGTAG, newUrl + " loaded");
2691 }
Grace Kloba5b078b52009-06-24 20:23:41 -07002692 }
2693 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002694 }
Grace Kloba5b078b52009-06-24 20:23:41 -07002695
Grace Kloba22ac16e2009-10-07 18:00:23 -07002696 if (mInTrace) {
2697 mInTrace = false;
2698 Debug.stopMethodTracing();
2699 }
2700 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002701
Grace Klobae7fe26b2010-06-28 16:23:33 -07002702 private void closeEmptyChildTab() {
2703 Tab current = mTabControl.getCurrentTab();
2704 if (current != null
2705 && current.getWebView().copyBackForwardList().getSize() == 0) {
2706 Tab parent = current.getParentTab();
2707 if (parent != null) {
2708 switchToTab(mTabControl.getTabIndex(parent));
2709 closeTab(current);
2710 }
2711 }
2712 }
2713
Grace Kloba22ac16e2009-10-07 18:00:23 -07002714 boolean shouldOverrideUrlLoading(WebView view, String url) {
2715 if (url.startsWith(SCHEME_WTAI)) {
2716 // wtai://wp/mc;number
2717 // number=string(phone-number)
2718 if (url.startsWith(SCHEME_WTAI_MC)) {
2719 Intent intent = new Intent(Intent.ACTION_VIEW,
2720 Uri.parse(WebView.SCHEME_TEL +
2721 url.substring(SCHEME_WTAI_MC.length())));
2722 startActivity(intent);
Grace Klobae7fe26b2010-06-28 16:23:33 -07002723 // before leaving BrowserActivity, close the empty child tab.
2724 // If a new tab is created through JavaScript open to load this
2725 // url, we would like to close it as we will load this url in a
2726 // different Activity.
2727 closeEmptyChildTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002728 return true;
2729 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002730 // wtai://wp/sd;dtmf
2731 // dtmf=string(dialstring)
2732 if (url.startsWith(SCHEME_WTAI_SD)) {
2733 // TODO: only send when there is active voice connection
2734 return false;
2735 }
2736 // wtai://wp/ap;number;name
2737 // number=string(phone-number)
2738 // name=string
2739 if (url.startsWith(SCHEME_WTAI_AP)) {
2740 // TODO
2741 return false;
2742 }
2743 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002744
Grace Kloba22ac16e2009-10-07 18:00:23 -07002745 // The "about:" schemes are internal to the browser; don't want these to
2746 // be dispatched to other apps.
2747 if (url.startsWith("about:")) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002748 return false;
2749 }
2750
Grace Kloba22ac16e2009-10-07 18:00:23 -07002751 Intent intent;
2752 // perform generic parsing of the URI to turn it into an Intent.
2753 try {
2754 intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME);
2755 } catch (URISyntaxException ex) {
2756 Log.w("Browser", "Bad URI " + url + ": " + ex.getMessage());
2757 return false;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002758 }
2759
Grace Kloba22ac16e2009-10-07 18:00:23 -07002760 // check whether the intent can be resolved. If not, we will see
2761 // whether we can download it from the Market.
2762 if (getPackageManager().resolveActivity(intent, 0) == null) {
2763 String packagename = intent.getPackage();
2764 if (packagename != null) {
2765 intent = new Intent(Intent.ACTION_VIEW, Uri
2766 .parse("market://search?q=pname:" + packagename));
2767 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2768 startActivity(intent);
Grace Klobae7fe26b2010-06-28 16:23:33 -07002769 // before leaving BrowserActivity, close the empty child tab.
2770 // If a new tab is created through JavaScript open to load this
2771 // url, we would like to close it as we will load this url in a
2772 // different Activity.
2773 closeEmptyChildTab();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002774 return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002775 } else {
2776 return false;
2777 }
2778 }
2779
Grace Kloba22ac16e2009-10-07 18:00:23 -07002780 // sanitize the Intent, ensuring web pages can not bypass browser
2781 // security (only access to BROWSABLE activities).
2782 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2783 intent.setComponent(null);
2784 try {
2785 if (startActivityIfNeeded(intent, -1)) {
Grace Klobae7fe26b2010-06-28 16:23:33 -07002786 // before leaving BrowserActivity, close the empty child tab.
2787 // If a new tab is created through JavaScript open to load this
2788 // url, we would like to close it as we will load this url in a
2789 // different Activity.
2790 closeEmptyChildTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002791 return true;
2792 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002793 } catch (ActivityNotFoundException ex) {
2794 // ignore the error. If no application can handle the URL,
2795 // eg about:blank, assume the browser can handle it.
2796 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002797
Grace Kloba22ac16e2009-10-07 18:00:23 -07002798 if (mMenuIsDown) {
Michael Kolb68792c82010-08-09 16:39:18 -07002799 openTab(url, false);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002800 closeOptionsMenu();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002801 return true;
2802 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002803 return false;
2804 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002805
Grace Kloba22ac16e2009-10-07 18:00:23 -07002806 // -------------------------------------------------------------------------
2807 // Helper function for WebChromeClient
2808 // -------------------------------------------------------------------------
The Android Open Source Project0c908882009-03-03 19:32:16 -08002809
Grace Kloba22ac16e2009-10-07 18:00:23 -07002810 void onProgressChanged(WebView view, int newProgress) {
Michael Kolba2b2ba82010-08-04 17:54:03 -07002811
2812 // On the phone, the fake title bar will always cover up the
2813 // regular title bar (or the regular one is offscreen), so only the
2814 // fake title bar needs to change its progress
2815 mFakeTitleBar.setProgress(newProgress);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002816
Grace Kloba22ac16e2009-10-07 18:00:23 -07002817 if (newProgress == 100) {
2818 // onProgressChanged() may continue to be called after the main
2819 // frame has finished loading, as any remaining sub frames continue
2820 // to load. We'll only get called once though with newProgress as
2821 // 100 when everything is loaded. (onPageFinished is called once
2822 // when the main frame completes loading regardless of the state of
2823 // any sub frames so calls to onProgressChanges may continue after
2824 // onPageFinished has executed)
2825 if (mInLoad) {
2826 mInLoad = false;
Leon Scrogginsa27ff192009-09-14 12:58:04 -04002827 updateInLoadMenuItems();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002828 // If the options menu is open, leave the title bar
2829 if (!mOptionsMenuOpen || !mIconView) {
2830 hideFakeTitleBar();
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07002831 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002832 }
Leon Scrogginsaa37e7f2010-03-05 11:51:20 -05002833 } else {
2834 if (!mInLoad) {
2835 // onPageFinished may have already been called but a subframe is
2836 // still loading and updating the progress. Reset mInLoad and
2837 // update the menu items.
2838 mInLoad = true;
2839 updateInLoadMenuItems();
2840 }
2841 // When the page first begins to load, the Activity may still be
2842 // paused, in which case showFakeTitleBar will do nothing. Call
2843 // again as the page continues to load so that it will be shown.
2844 // (Calling it will the fake title bar is already showing will also
2845 // do nothing.
Grace Kloba22ac16e2009-10-07 18:00:23 -07002846 if (!mOptionsMenuOpen || mIconView) {
2847 // This page has begun to load, so show the title bar
2848 showFakeTitleBar();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002849 }
2850 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002851 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002852
Grace Kloba22ac16e2009-10-07 18:00:23 -07002853 void onShowCustomView(View view, WebChromeClient.CustomViewCallback callback) {
Derek Sollenberger8ff57db2009-12-08 15:39:55 -05002854 // if a view already exists then immediately terminate the new one
2855 if (mCustomView != null) {
2856 callback.onCustomViewHidden();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002857 return;
Derek Sollenberger8ff57db2009-12-08 15:39:55 -05002858 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002859
2860 // Add the custom view to its container.
2861 mCustomViewContainer.addView(view, COVER_SCREEN_GRAVITY_CENTER);
2862 mCustomView = view;
2863 mCustomViewCallback = callback;
2864 // Save the menu state and set it to empty while the custom
2865 // view is showing.
2866 mOldMenuState = mMenuState;
2867 mMenuState = EMPTY_MENU;
2868 // Hide the content view.
2869 mContentView.setVisibility(View.GONE);
2870 // Finally show the custom view container.
Andrei Popescu163ab742009-10-20 17:58:23 +01002871 setStatusBarVisibility(false);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002872 mCustomViewContainer.setVisibility(View.VISIBLE);
2873 mCustomViewContainer.bringToFront();
2874 }
2875
2876 void onHideCustomView() {
2877 if (mCustomView == null)
2878 return;
2879
2880 // Hide the custom view.
2881 mCustomView.setVisibility(View.GONE);
2882 // Remove the custom view from its container.
2883 mCustomViewContainer.removeView(mCustomView);
2884 mCustomView = null;
2885 // Reset the old menu state.
2886 mMenuState = mOldMenuState;
2887 mOldMenuState = EMPTY_MENU;
2888 mCustomViewContainer.setVisibility(View.GONE);
2889 mCustomViewCallback.onCustomViewHidden();
2890 // Show the content view.
Andrei Popescu163ab742009-10-20 17:58:23 +01002891 setStatusBarVisibility(true);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002892 mContentView.setVisibility(View.VISIBLE);
2893 }
2894
2895 Bitmap getDefaultVideoPoster() {
2896 if (mDefaultVideoPoster == null) {
2897 mDefaultVideoPoster = BitmapFactory.decodeResource(
2898 getResources(), R.drawable.default_video_poster);
Patrick Scott3918d442009-08-04 13:22:29 -04002899 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002900 return mDefaultVideoPoster;
2901 }
Patrick Scott3918d442009-08-04 13:22:29 -04002902
Grace Kloba22ac16e2009-10-07 18:00:23 -07002903 View getVideoLoadingProgressView() {
2904 if (mVideoProgressView == null) {
2905 LayoutInflater inflater = LayoutInflater.from(BrowserActivity.this);
2906 mVideoProgressView = inflater.inflate(
2907 R.layout.video_loading_progress, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002908 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002909 return mVideoProgressView;
2910 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002911
Leon Scroggins8d5fa432009-10-02 15:55:59 -04002912 /*
2913 * The Object used to inform the WebView of the file to upload.
2914 */
2915 private ValueCallback<Uri> mUploadMessage;
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002916 private String mCameraFilePath;
Leon Scroggins8d5fa432009-10-02 15:55:59 -04002917
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002918 void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
2919
2920 final String imageMimeType = "image/*";
Ben Murdoch6af492a2010-06-15 12:38:17 +01002921 final String videoMimeType = "video/*";
Ben Murdoch039bd472010-07-21 21:26:57 +01002922 final String audioMimeType = "audio/*";
Ben Murdochb50d7402010-07-16 12:42:22 +01002923 final String mediaSourceKey = "capture";
Ben Murdoch6af492a2010-06-15 12:38:17 +01002924 final String mediaSourceValueCamera = "camera";
Ben Murdochb50d7402010-07-16 12:42:22 +01002925 final String mediaSourceValueFileSystem = "filesystem";
Ben Murdoch6af492a2010-06-15 12:38:17 +01002926 final String mediaSourceValueCamcorder = "camcorder";
Ben Murdoch039bd472010-07-21 21:26:57 +01002927 final String mediaSourceValueMicrophone = "microphone";
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002928
Ben Murdoch039bd472010-07-21 21:26:57 +01002929 // media source can be 'filesystem' or 'camera' or 'camcorder' or 'microphone'.
Ben Murdoch6af492a2010-06-15 12:38:17 +01002930 String mediaSource = "";
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002931
Ben Murdoch6af492a2010-06-15 12:38:17 +01002932 // We add the camera intent if there was no accept type (or '*/*' or 'image/*').
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002933 boolean addCameraIntent = true;
Ben Murdoch6af492a2010-06-15 12:38:17 +01002934 // We add the camcorder intent if there was no accept type (or '*/*' or 'video/*').
2935 boolean addCamcorderIntent = true;
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002936
Ben Murdoch6af492a2010-06-15 12:38:17 +01002937 if (mUploadMessage != null) {
2938 // Already a file picker operation in progress.
2939 return;
2940 }
2941
Grace Kloba22ac16e2009-10-07 18:00:23 -07002942 mUploadMessage = uploadMsg;
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002943
2944 // Parse the accept type.
2945 String params[] = acceptType.split(";");
2946 String mimeType = params[0];
2947
2948 for (String p : params) {
2949 String[] keyValue = p.split("=");
2950 if (keyValue.length == 2) {
2951 // Process key=value parameters.
Ben Murdoch6af492a2010-06-15 12:38:17 +01002952 if (mediaSourceKey.equals(keyValue[0])) {
2953 mediaSource = keyValue[1];
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002954 }
2955 }
2956 }
2957
2958 // This intent will display the standard OPENABLE file picker.
Grace Kloba22ac16e2009-10-07 18:00:23 -07002959 Intent i = new Intent(Intent.ACTION_GET_CONTENT);
2960 i.addCategory(Intent.CATEGORY_OPENABLE);
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002961
2962 // Create an intent to add to the standard file picker that will
2963 // capture an image from the camera. We'll combine this intent with
2964 // the standard OPENABLE picker unless the web developer specifically
2965 // requested the camera or gallery be opened by passing a parameter
2966 // in the accept type.
2967 Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
2968 File externalDataDir = Environment.getExternalStoragePublicDirectory(
2969 Environment.DIRECTORY_DCIM);
2970 File cameraDataDir = new File(externalDataDir.getAbsolutePath() +
2971 File.separator + "browser-photos");
2972 cameraDataDir.mkdirs();
2973 mCameraFilePath = cameraDataDir.getAbsolutePath() + File.separator +
2974 System.currentTimeMillis() + ".jpg";
2975 cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(mCameraFilePath)));
2976
Ben Murdoch6af492a2010-06-15 12:38:17 +01002977 Intent camcorderIntent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
2978
Ben Murdoch039bd472010-07-21 21:26:57 +01002979 Intent soundRecIntent = new Intent(MediaStore.Audio.Media.RECORD_SOUND_ACTION);
2980
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002981 if (mimeType.equals(imageMimeType)) {
2982 i.setType(imageMimeType);
Ben Murdoch6af492a2010-06-15 12:38:17 +01002983 addCamcorderIntent = false;
2984 if (mediaSource.equals(mediaSourceValueCamera)) {
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002985 // Specified 'image/*' and requested the camera, so go ahead and launch the camera
2986 // directly.
2987 BrowserActivity.this.startActivityForResult(cameraIntent, FILE_SELECTED);
2988 return;
Ben Murdochb50d7402010-07-16 12:42:22 +01002989 } else if (mediaSource.equals(mediaSourceValueFileSystem)) {
2990 // Specified filesytem as the source, so don't want to consider the camera.
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002991 addCameraIntent = false;
2992 }
Ben Murdoch6af492a2010-06-15 12:38:17 +01002993 } else if (mimeType.equals(videoMimeType)) {
2994 i.setType(videoMimeType);
2995 addCameraIntent = false;
2996 // The camcorder saves it's own file and returns it to us in the intent, so
2997 // we don't need to generate one here.
2998 mCameraFilePath = null;
2999
3000 if (mediaSource.equals(mediaSourceValueCamcorder)) {
Ben Murdoch039bd472010-07-21 21:26:57 +01003001 // Specified 'video/*' and requested the camcorder, so go ahead and launch the
3002 // camcorder directly.
Ben Murdoch6af492a2010-06-15 12:38:17 +01003003 BrowserActivity.this.startActivityForResult(camcorderIntent, FILE_SELECTED);
3004 return;
Ben Murdochb50d7402010-07-16 12:42:22 +01003005 } else if (mediaSource.equals(mediaSourceValueFileSystem)) {
3006 // Specified filesystem as the source, so don't want to consider the camcorder.
Ben Murdoch6af492a2010-06-15 12:38:17 +01003007 addCamcorderIntent = false;
3008 }
Ben Murdoch039bd472010-07-21 21:26:57 +01003009 } else if (mimeType.equals(audioMimeType)) {
3010 i.setType(audioMimeType);
3011 addCameraIntent = false;
3012 addCamcorderIntent = false;
3013 if (mediaSource.equals(mediaSourceValueMicrophone)) {
3014 // Specified 'audio/*' and requested microphone, so go ahead and launch the sound
3015 // recorder.
3016 BrowserActivity.this.startActivityForResult(soundRecIntent, FILE_SELECTED);
3017 return;
3018 }
3019 // On a default system, there is no single option to open an audio "gallery". Both the
3020 // sound recorder and music browser respond to the OPENABLE/audio/* intent unlike the
3021 // image/* and video/* OPENABLE intents where the image / video gallery are the only
3022 // respondants (and so the user is not prompted by default).
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003023 } else {
3024 i.setType("*/*");
3025 }
3026
Ben Murdoch6af492a2010-06-15 12:38:17 +01003027 // Combine the chooser and the extra choices (like camera or camcorder)
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003028 Intent chooser = new Intent(Intent.ACTION_CHOOSER);
3029 chooser.putExtra(Intent.EXTRA_INTENT, i);
3030
Ben Murdoch6af492a2010-06-15 12:38:17 +01003031 Vector<Intent> extraInitialIntents = new Vector<Intent>(0);
3032
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003033 if (addCameraIntent) {
Ben Murdoch6af492a2010-06-15 12:38:17 +01003034 extraInitialIntents.add(cameraIntent);
3035 }
3036
3037 if (addCamcorderIntent) {
3038 extraInitialIntents.add(camcorderIntent);
3039 }
3040
3041 if (extraInitialIntents.size() > 0) {
3042 Intent[] extraIntents = new Intent[extraInitialIntents.size()];
3043 chooser.putExtra(Intent.EXTRA_INITIAL_INTENTS, extraInitialIntents.toArray(extraIntents));
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003044 }
3045
3046 chooser.putExtra(Intent.EXTRA_TITLE, getString(R.string.choose_upload));
3047 BrowserActivity.this.startActivityForResult(chooser, FILE_SELECTED);
Grace Kloba22ac16e2009-10-07 18:00:23 -07003048 }
3049
3050 // -------------------------------------------------------------------------
3051 // Implement functions for DownloadListener
3052 // -------------------------------------------------------------------------
3053
The Android Open Source Project0c908882009-03-03 19:32:16 -08003054 /**
3055 * Notify the host application a download should be done, or that
3056 * the data should be streamed if a streaming viewer is available.
3057 * @param url The full url to the content that should be downloaded
3058 * @param contentDisposition Content-disposition http header, if
3059 * present.
3060 * @param mimetype The mimetype of the content reported by the server
3061 * @param contentLength The file size reported by the server
3062 */
3063 public void onDownloadStart(String url, String userAgent,
3064 String contentDisposition, String mimetype, long contentLength) {
3065 // if we're dealing wih A/V content that's not explicitly marked
3066 // for download, check if it's streamable.
3067 if (contentDisposition == null
Patrick Scotte1fb9662009-08-31 14:31:52 -04003068 || !contentDisposition.regionMatches(
3069 true, 0, "attachment", 0, 10)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003070 // query the package manager to see if there's a registered handler
3071 // that matches.
3072 Intent intent = new Intent(Intent.ACTION_VIEW);
3073 intent.setDataAndType(Uri.parse(url), mimetype);
Patrick Scotte1fb9662009-08-31 14:31:52 -04003074 ResolveInfo info = getPackageManager().resolveActivity(intent,
3075 PackageManager.MATCH_DEFAULT_ONLY);
3076 if (info != null) {
3077 ComponentName myName = getComponentName();
3078 // If we resolved to ourselves, we don't want to attempt to
3079 // load the url only to try and download it again.
3080 if (!myName.getPackageName().equals(
3081 info.activityInfo.packageName)
3082 || !myName.getClassName().equals(
3083 info.activityInfo.name)) {
3084 // someone (other than us) knows how to handle this mime
3085 // type with this scheme, don't download.
3086 try {
3087 startActivity(intent);
3088 return;
3089 } catch (ActivityNotFoundException ex) {
3090 if (LOGD_ENABLED) {
3091 Log.d(LOGTAG, "activity not found for " + mimetype
3092 + " over " + Uri.parse(url).getScheme(),
3093 ex);
3094 }
3095 // Best behavior is to fall back to a download in this
3096 // case
The Android Open Source Project0c908882009-03-03 19:32:16 -08003097 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003098 }
3099 }
3100 }
3101 onDownloadStartNoStream(url, userAgent, contentDisposition, mimetype, contentLength);
3102 }
3103
Kristian Monsenfa52d172010-03-25 18:29:21 +00003104 // This is to work around the fact that java.net.URI throws Exceptions
3105 // instead of just encoding URL's properly
3106 // Helper method for onDownloadStartNoStream
3107 private static String encodePath(String path) {
3108 char[] chars = path.toCharArray();
3109
3110 boolean needed = false;
3111 for (char c : chars) {
3112 if (c == '[' || c == ']') {
3113 needed = true;
3114 break;
3115 }
3116 }
3117 if (needed == false) {
3118 return path;
3119 }
3120
3121 StringBuilder sb = new StringBuilder("");
3122 for (char c : chars) {
3123 if (c == '[' || c == ']') {
3124 sb.append('%');
3125 sb.append(Integer.toHexString(c));
3126 } else {
3127 sb.append(c);
3128 }
3129 }
3130
3131 return sb.toString();
3132 }
3133
The Android Open Source Project0c908882009-03-03 19:32:16 -08003134 /**
3135 * Notify the host application a download should be done, even if there
3136 * is a streaming viewer available for thise type.
3137 * @param url The full url to the content that should be downloaded
3138 * @param contentDisposition Content-disposition http header, if
3139 * present.
3140 * @param mimetype The mimetype of the content reported by the server
3141 * @param contentLength The file size reported by the server
3142 */
3143 /*package */ void onDownloadStartNoStream(String url, String userAgent,
3144 String contentDisposition, String mimetype, long contentLength) {
3145
3146 String filename = URLUtil.guessFileName(url,
3147 contentDisposition, mimetype);
3148
3149 // Check to see if we have an SDCard
3150 String status = Environment.getExternalStorageState();
3151 if (!status.equals(Environment.MEDIA_MOUNTED)) {
3152 int title;
3153 String msg;
3154
3155 // Check to see if the SDCard is busy, same as the music app
3156 if (status.equals(Environment.MEDIA_SHARED)) {
3157 msg = getString(R.string.download_sdcard_busy_dlg_msg);
3158 title = R.string.download_sdcard_busy_dlg_title;
3159 } else {
3160 msg = getString(R.string.download_no_sdcard_dlg_msg, filename);
3161 title = R.string.download_no_sdcard_dlg_title;
3162 }
3163
3164 new AlertDialog.Builder(this)
3165 .setTitle(title)
3166 .setIcon(android.R.drawable.ic_dialog_alert)
3167 .setMessage(msg)
3168 .setPositiveButton(R.string.ok, null)
3169 .show();
3170 return;
3171 }
3172
Kristian Monsenfa52d172010-03-25 18:29:21 +00003173 // java.net.URI is a lot stricter than KURL so we have to encode some
3174 // extra characters. Fix for b 2538060 and b 1634719
3175 WebAddress webAddress;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003176 try {
Kristian Monsenfa52d172010-03-25 18:29:21 +00003177 webAddress = new WebAddress(url);
3178 webAddress.mPath = encodePath(webAddress.mPath);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003179 } catch (Exception e) {
Kristian Monsenfa52d172010-03-25 18:29:21 +00003180 // This only happens for very bad urls, we want to chatch the
3181 // exception here
3182 Log.e(LOGTAG, "Exception trying to parse url:" + url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003183 return;
3184 }
3185
3186 // XXX: Have to use the old url since the cookies were stored using the
3187 // old percent-encoded url.
3188 String cookies = CookieManager.getInstance().getCookie(url);
3189
3190 ContentValues values = new ContentValues();
Kristian Monsenfa52d172010-03-25 18:29:21 +00003191 values.put(Downloads.Impl.COLUMN_URI, webAddress.toString());
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08003192 values.put(Downloads.Impl.COLUMN_COOKIE_DATA, cookies);
3193 values.put(Downloads.Impl.COLUMN_USER_AGENT, userAgent);
3194 values.put(Downloads.Impl.COLUMN_NOTIFICATION_PACKAGE,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003195 getPackageName());
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08003196 values.put(Downloads.Impl.COLUMN_NOTIFICATION_CLASS,
Leon Scrogginsa563d092010-04-19 16:53:49 -04003197 OpenDownloadReceiver.class.getCanonicalName());
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08003198 values.put(Downloads.Impl.COLUMN_VISIBILITY,
3199 Downloads.Impl.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
3200 values.put(Downloads.Impl.COLUMN_MIME_TYPE, mimetype);
3201 values.put(Downloads.Impl.COLUMN_FILE_NAME_HINT, filename);
Kristian Monsenfa52d172010-03-25 18:29:21 +00003202 values.put(Downloads.Impl.COLUMN_DESCRIPTION, webAddress.mHost);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003203 if (contentLength > 0) {
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08003204 values.put(Downloads.Impl.COLUMN_TOTAL_BYTES, contentLength);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003205 }
3206 if (mimetype == null) {
3207 // We must have long pressed on a link or image to download it. We
3208 // are not sure of the mimetype in this case, so do a head request
3209 new FetchUrlMimeType(this).execute(values);
3210 } else {
3211 final Uri contentUri =
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08003212 getContentResolver().insert(Downloads.Impl.CONTENT_URI, values);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003213 }
Leon Scroggins9191a7f2010-03-18 14:44:44 -04003214 Toast.makeText(this, R.string.download_pending, Toast.LENGTH_SHORT)
3215 .show();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003216 }
3217
Grace Kloba22ac16e2009-10-07 18:00:23 -07003218 // -------------------------------------------------------------------------
3219
The Android Open Source Project0c908882009-03-03 19:32:16 -08003220 /**
3221 * Resets the lock icon. This method is called when we start a new load and
3222 * know the url to be loaded.
3223 */
3224 private void resetLockIcon(String url) {
3225 // Save the lock-icon state (we revert to it if the load gets cancelled)
Grace Kloba22ac16e2009-10-07 18:00:23 -07003226 mTabControl.getCurrentTab().resetLockIcon(url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003227 updateLockIconImage(LOCK_ICON_UNSECURE);
3228 }
3229
The Android Open Source Project0c908882009-03-03 19:32:16 -08003230 /**
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04003231 * Update the lock icon to correspond to our latest state.
3232 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003233 private void updateLockIconToLatest() {
Leon Scroggins91f65fc2010-06-29 13:52:39 -04003234 Tab t = mTabControl.getCurrentTab();
3235 if (t != null) {
3236 updateLockIconImage(t.getLockIconType());
3237 }
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04003238 }
3239
3240 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08003241 * Updates the lock-icon image in the title-bar.
3242 */
3243 private void updateLockIconImage(int lockIconType) {
3244 Drawable d = null;
3245 if (lockIconType == LOCK_ICON_SECURE) {
3246 d = mSecLockIcon;
3247 } else if (lockIconType == LOCK_ICON_MIXED) {
3248 d = mMixLockIcon;
3249 }
Leon Scroggins68579392009-09-15 15:31:54 -04003250 mTitleBar.setLock(d);
Michael Kolba2b2ba82010-08-04 17:54:03 -07003251 mFakeTitleBar.setLock(d);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003252 }
3253
3254 /**
3255 * Displays a page-info dialog.
3256 * @param tab The tab to show info about
3257 * @param fromShowSSLCertificateOnError The flag that indicates whether
3258 * this dialog was opened from the SSL-certificate-on-error dialog or
3259 * not. This is important, since we need to know whether to return to
3260 * the parent dialog or simply dismiss.
3261 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003262 private void showPageInfo(final Tab tab,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003263 final boolean fromShowSSLCertificateOnError) {
3264 final LayoutInflater factory = LayoutInflater
3265 .from(this);
3266
3267 final View pageInfoView = factory.inflate(R.layout.page_info, null);
3268
3269 final WebView view = tab.getWebView();
3270
3271 String url = null;
3272 String title = null;
3273
3274 if (view == null) {
3275 url = tab.getUrl();
3276 title = tab.getTitle();
3277 } else if (view == mTabControl.getCurrentWebView()) {
3278 // Use the cached title and url if this is the current WebView
3279 url = mUrl;
3280 title = mTitle;
3281 } else {
3282 url = view.getUrl();
3283 title = view.getTitle();
3284 }
3285
3286 if (url == null) {
3287 url = "";
3288 }
3289 if (title == null) {
3290 title = "";
3291 }
3292
3293 ((TextView) pageInfoView.findViewById(R.id.address)).setText(url);
3294 ((TextView) pageInfoView.findViewById(R.id.title)).setText(title);
3295
3296 mPageInfoView = tab;
Leon Scrogginsc7b92f82010-01-11 18:17:31 -05003297 mPageInfoFromShowSSLCertificateOnError = fromShowSSLCertificateOnError;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003298
3299 AlertDialog.Builder alertDialogBuilder =
3300 new AlertDialog.Builder(this)
3301 .setTitle(R.string.page_info).setIcon(android.R.drawable.ic_dialog_info)
3302 .setView(pageInfoView)
3303 .setPositiveButton(
3304 R.string.ok,
3305 new DialogInterface.OnClickListener() {
3306 public void onClick(DialogInterface dialog,
3307 int whichButton) {
3308 mPageInfoDialog = null;
3309 mPageInfoView = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003310
3311 // if we came here from the SSL error dialog
3312 if (fromShowSSLCertificateOnError) {
3313 // go back to the SSL error dialog
3314 showSSLCertificateOnError(
3315 mSSLCertificateOnErrorView,
3316 mSSLCertificateOnErrorHandler,
3317 mSSLCertificateOnErrorError);
3318 }
3319 }
3320 })
3321 .setOnCancelListener(
3322 new DialogInterface.OnCancelListener() {
3323 public void onCancel(DialogInterface dialog) {
3324 mPageInfoDialog = null;
3325 mPageInfoView = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003326
3327 // if we came here from the SSL error dialog
3328 if (fromShowSSLCertificateOnError) {
3329 // go back to the SSL error dialog
3330 showSSLCertificateOnError(
3331 mSSLCertificateOnErrorView,
3332 mSSLCertificateOnErrorHandler,
3333 mSSLCertificateOnErrorError);
3334 }
3335 }
3336 });
3337
3338 // if we have a main top-level page SSL certificate set or a certificate
3339 // error
3340 if (fromShowSSLCertificateOnError ||
3341 (view != null && view.getCertificate() != null)) {
3342 // add a 'View Certificate' button
3343 alertDialogBuilder.setNeutralButton(
3344 R.string.view_certificate,
3345 new DialogInterface.OnClickListener() {
3346 public void onClick(DialogInterface dialog,
3347 int whichButton) {
3348 mPageInfoDialog = null;
3349 mPageInfoView = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003350
3351 // if we came here from the SSL error dialog
3352 if (fromShowSSLCertificateOnError) {
3353 // go back to the SSL error dialog
3354 showSSLCertificateOnError(
3355 mSSLCertificateOnErrorView,
3356 mSSLCertificateOnErrorHandler,
3357 mSSLCertificateOnErrorError);
3358 } else {
3359 // otherwise, display the top-most certificate from
3360 // the chain
3361 if (view.getCertificate() != null) {
3362 showSSLCertificate(tab);
3363 }
3364 }
3365 }
3366 });
3367 }
3368
3369 mPageInfoDialog = alertDialogBuilder.show();
3370 }
3371
3372 /**
3373 * Displays the main top-level page SSL certificate dialog
3374 * (accessible from the Page-Info dialog).
3375 * @param tab The tab to show certificate for.
3376 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003377 private void showSSLCertificate(final Tab tab) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003378 final View certificateView =
3379 inflateCertificateView(tab.getWebView().getCertificate());
3380 if (certificateView == null) {
3381 return;
3382 }
3383
3384 LayoutInflater factory = LayoutInflater.from(this);
3385
3386 final LinearLayout placeholder =
3387 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3388
3389 LinearLayout ll = (LinearLayout) factory.inflate(
3390 R.layout.ssl_success, placeholder);
3391 ((TextView)ll.findViewById(R.id.success))
3392 .setText(R.string.ssl_certificate_is_valid);
3393
3394 mSSLCertificateView = tab;
3395 mSSLCertificateDialog =
3396 new AlertDialog.Builder(this)
3397 .setTitle(R.string.ssl_certificate).setIcon(
3398 R.drawable.ic_dialog_browser_certificate_secure)
3399 .setView(certificateView)
3400 .setPositiveButton(R.string.ok,
3401 new DialogInterface.OnClickListener() {
3402 public void onClick(DialogInterface dialog,
3403 int whichButton) {
3404 mSSLCertificateDialog = null;
3405 mSSLCertificateView = null;
3406
3407 showPageInfo(tab, false);
3408 }
3409 })
3410 .setOnCancelListener(
3411 new DialogInterface.OnCancelListener() {
3412 public void onCancel(DialogInterface dialog) {
3413 mSSLCertificateDialog = null;
3414 mSSLCertificateView = null;
3415
3416 showPageInfo(tab, false);
3417 }
3418 })
3419 .show();
3420 }
3421
3422 /**
3423 * Displays the SSL error certificate dialog.
3424 * @param view The target web-view.
3425 * @param handler The SSL error handler responsible for cancelling the
3426 * connection that resulted in an SSL error or proceeding per user request.
3427 * @param error The SSL error object.
3428 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003429 void showSSLCertificateOnError(
The Android Open Source Project0c908882009-03-03 19:32:16 -08003430 final WebView view, final SslErrorHandler handler, final SslError error) {
3431
3432 final View certificateView =
3433 inflateCertificateView(error.getCertificate());
3434 if (certificateView == null) {
3435 return;
3436 }
3437
3438 LayoutInflater factory = LayoutInflater.from(this);
3439
3440 final LinearLayout placeholder =
3441 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3442
3443 if (error.hasError(SslError.SSL_UNTRUSTED)) {
3444 LinearLayout ll = (LinearLayout)factory
3445 .inflate(R.layout.ssl_warning, placeholder);
3446 ((TextView)ll.findViewById(R.id.warning))
3447 .setText(R.string.ssl_untrusted);
3448 }
3449
3450 if (error.hasError(SslError.SSL_IDMISMATCH)) {
3451 LinearLayout ll = (LinearLayout)factory
3452 .inflate(R.layout.ssl_warning, placeholder);
3453 ((TextView)ll.findViewById(R.id.warning))
3454 .setText(R.string.ssl_mismatch);
3455 }
3456
3457 if (error.hasError(SslError.SSL_EXPIRED)) {
3458 LinearLayout ll = (LinearLayout)factory
3459 .inflate(R.layout.ssl_warning, placeholder);
3460 ((TextView)ll.findViewById(R.id.warning))
3461 .setText(R.string.ssl_expired);
3462 }
3463
3464 if (error.hasError(SslError.SSL_NOTYETVALID)) {
3465 LinearLayout ll = (LinearLayout)factory
3466 .inflate(R.layout.ssl_warning, placeholder);
3467 ((TextView)ll.findViewById(R.id.warning))
3468 .setText(R.string.ssl_not_yet_valid);
3469 }
3470
3471 mSSLCertificateOnErrorHandler = handler;
3472 mSSLCertificateOnErrorView = view;
3473 mSSLCertificateOnErrorError = error;
3474 mSSLCertificateOnErrorDialog =
3475 new AlertDialog.Builder(this)
3476 .setTitle(R.string.ssl_certificate).setIcon(
3477 R.drawable.ic_dialog_browser_certificate_partially_secure)
3478 .setView(certificateView)
3479 .setPositiveButton(R.string.ok,
3480 new DialogInterface.OnClickListener() {
3481 public void onClick(DialogInterface dialog,
3482 int whichButton) {
3483 mSSLCertificateOnErrorDialog = null;
3484 mSSLCertificateOnErrorView = null;
3485 mSSLCertificateOnErrorHandler = null;
3486 mSSLCertificateOnErrorError = null;
3487
Grace Kloba22ac16e2009-10-07 18:00:23 -07003488 view.getWebViewClient().onReceivedSslError(
3489 view, handler, error);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003490 }
3491 })
3492 .setNeutralButton(R.string.page_info_view,
3493 new DialogInterface.OnClickListener() {
3494 public void onClick(DialogInterface dialog,
3495 int whichButton) {
3496 mSSLCertificateOnErrorDialog = null;
3497
3498 // do not clear the dialog state: we will
3499 // need to show the dialog again once the
3500 // user is done exploring the page-info details
3501
3502 showPageInfo(mTabControl.getTabFromView(view),
3503 true);
3504 }
3505 })
3506 .setOnCancelListener(
3507 new DialogInterface.OnCancelListener() {
3508 public void onCancel(DialogInterface dialog) {
3509 mSSLCertificateOnErrorDialog = null;
3510 mSSLCertificateOnErrorView = null;
3511 mSSLCertificateOnErrorHandler = null;
3512 mSSLCertificateOnErrorError = null;
3513
Grace Kloba22ac16e2009-10-07 18:00:23 -07003514 view.getWebViewClient().onReceivedSslError(
3515 view, handler, error);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003516 }
3517 })
3518 .show();
3519 }
3520
3521 /**
3522 * Inflates the SSL certificate view (helper method).
3523 * @param certificate The SSL certificate.
3524 * @return The resultant certificate view with issued-to, issued-by,
3525 * issued-on, expires-on, and possibly other fields set.
3526 * If the input certificate is null, returns null.
3527 */
3528 private View inflateCertificateView(SslCertificate certificate) {
3529 if (certificate == null) {
3530 return null;
3531 }
3532
3533 LayoutInflater factory = LayoutInflater.from(this);
3534
3535 View certificateView = factory.inflate(
3536 R.layout.ssl_certificate, null);
3537
3538 // issued to:
3539 SslCertificate.DName issuedTo = certificate.getIssuedTo();
3540 if (issuedTo != null) {
3541 ((TextView) certificateView.findViewById(R.id.to_common))
3542 .setText(issuedTo.getCName());
3543 ((TextView) certificateView.findViewById(R.id.to_org))
3544 .setText(issuedTo.getOName());
3545 ((TextView) certificateView.findViewById(R.id.to_org_unit))
3546 .setText(issuedTo.getUName());
3547 }
3548
3549 // issued by:
3550 SslCertificate.DName issuedBy = certificate.getIssuedBy();
3551 if (issuedBy != null) {
3552 ((TextView) certificateView.findViewById(R.id.by_common))
3553 .setText(issuedBy.getCName());
3554 ((TextView) certificateView.findViewById(R.id.by_org))
3555 .setText(issuedBy.getOName());
3556 ((TextView) certificateView.findViewById(R.id.by_org_unit))
3557 .setText(issuedBy.getUName());
3558 }
3559
3560 // issued on:
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003561 String issuedOn = formatCertificateDate(
3562 certificate.getValidNotBeforeDate());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003563 ((TextView) certificateView.findViewById(R.id.issued_on))
3564 .setText(issuedOn);
3565
3566 // expires on:
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003567 String expiresOn = formatCertificateDate(
3568 certificate.getValidNotAfterDate());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003569 ((TextView) certificateView.findViewById(R.id.expires_on))
3570 .setText(expiresOn);
3571
3572 return certificateView;
3573 }
3574
3575 /**
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003576 * Formats the certificate date to a properly localized date string.
The Android Open Source Project0c908882009-03-03 19:32:16 -08003577 * @return Properly localized version of the certificate date string and
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003578 * the "" if it fails to localize.
The Android Open Source Project0c908882009-03-03 19:32:16 -08003579 */
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003580 private String formatCertificateDate(Date certificateDate) {
3581 if (certificateDate == null) {
3582 return "";
The Android Open Source Project0c908882009-03-03 19:32:16 -08003583 }
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003584 String formattedDate = DateFormat.getDateFormat(this).format(certificateDate);
3585 if (formattedDate == null) {
3586 return "";
3587 }
3588 return formattedDate;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003589 }
3590
3591 /**
3592 * Displays an http-authentication dialog.
3593 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003594 void showHttpAuthentication(final HttpAuthHandler handler,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003595 final String host, final String realm, final String title,
3596 final String name, final String password, int focusId) {
3597 LayoutInflater factory = LayoutInflater.from(this);
3598 final View v = factory
3599 .inflate(R.layout.http_authentication, null);
3600 if (name != null) {
3601 ((EditText) v.findViewById(R.id.username_edit)).setText(name);
3602 }
3603 if (password != null) {
3604 ((EditText) v.findViewById(R.id.password_edit)).setText(password);
3605 }
3606
3607 String titleText = title;
3608 if (titleText == null) {
3609 titleText = getText(R.string.sign_in_to).toString().replace(
3610 "%s1", host).replace("%s2", realm);
3611 }
3612
3613 mHttpAuthHandler = handler;
3614 AlertDialog dialog = new AlertDialog.Builder(this)
3615 .setTitle(titleText)
3616 .setIcon(android.R.drawable.ic_dialog_alert)
3617 .setView(v)
3618 .setPositiveButton(R.string.action,
3619 new DialogInterface.OnClickListener() {
3620 public void onClick(DialogInterface dialog,
3621 int whichButton) {
3622 String nm = ((EditText) v
3623 .findViewById(R.id.username_edit))
3624 .getText().toString();
3625 String pw = ((EditText) v
3626 .findViewById(R.id.password_edit))
3627 .getText().toString();
3628 BrowserActivity.this.setHttpAuthUsernamePassword
3629 (host, realm, nm, pw);
3630 handler.proceed(nm, pw);
3631 mHttpAuthenticationDialog = null;
3632 mHttpAuthHandler = null;
3633 }})
3634 .setNegativeButton(R.string.cancel,
3635 new DialogInterface.OnClickListener() {
3636 public void onClick(DialogInterface dialog,
3637 int whichButton) {
3638 handler.cancel();
3639 BrowserActivity.this.resetTitleAndRevertLockIcon();
3640 mHttpAuthenticationDialog = null;
3641 mHttpAuthHandler = null;
3642 }})
3643 .setOnCancelListener(new DialogInterface.OnCancelListener() {
3644 public void onCancel(DialogInterface dialog) {
3645 handler.cancel();
3646 BrowserActivity.this.resetTitleAndRevertLockIcon();
3647 mHttpAuthenticationDialog = null;
3648 mHttpAuthHandler = null;
3649 }})
3650 .create();
3651 // Make the IME appear when the dialog is displayed if applicable.
3652 dialog.getWindow().setSoftInputMode(
3653 WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
3654 dialog.show();
3655 if (focusId != 0) {
3656 dialog.findViewById(focusId).requestFocus();
3657 } else {
3658 v.findViewById(R.id.username_edit).requestFocus();
3659 }
3660 mHttpAuthenticationDialog = dialog;
3661 }
3662
3663 public int getProgress() {
3664 WebView w = mTabControl.getCurrentWebView();
3665 if (w != null) {
3666 return w.getProgress();
3667 } else {
3668 return 100;
3669 }
3670 }
3671
3672 /**
3673 * Set HTTP authentication password.
3674 *
3675 * @param host The host for the password
3676 * @param realm The realm for the password
3677 * @param username The username for the password. If it is null, it means
3678 * password can't be saved.
3679 * @param password The password
3680 */
3681 public void setHttpAuthUsernamePassword(String host, String realm,
3682 String username,
3683 String password) {
Steve Block95a53b22010-03-25 17:24:58 +00003684 WebView w = getTopWindow();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003685 if (w != null) {
3686 w.setHttpAuthUsernamePassword(host, realm, username, password);
3687 }
3688 }
3689
3690 /**
3691 * connectivity manager says net has come or gone... inform the user
3692 * @param up true if net has come up, false if net has gone down
3693 */
3694 public void onNetworkToggle(boolean up) {
3695 if (up == mIsNetworkUp) {
3696 return;
3697 } else if (up) {
3698 mIsNetworkUp = true;
3699 if (mAlertDialog != null) {
3700 mAlertDialog.cancel();
3701 mAlertDialog = null;
3702 }
3703 } else {
3704 mIsNetworkUp = false;
Patrick Scotteb6ab2a2009-09-16 10:00:17 -04003705 if (mInLoad) {
3706 createAndShowNetworkDialog();
3707 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003708 }
3709 WebView w = mTabControl.getCurrentWebView();
3710 if (w != null) {
3711 w.setNetworkAvailable(up);
3712 }
3713 }
3714
Grace Kloba22ac16e2009-10-07 18:00:23 -07003715 boolean isNetworkUp() {
3716 return mIsNetworkUp;
3717 }
3718
Patrick Scotteb6ab2a2009-09-16 10:00:17 -04003719 // This method shows the network dialog alerting the user that the net is
3720 // down. It will only show the dialog if mAlertDialog is null.
3721 private void createAndShowNetworkDialog() {
3722 if (mAlertDialog == null) {
3723 mAlertDialog = new AlertDialog.Builder(this)
3724 .setTitle(R.string.loadSuspendedTitle)
3725 .setMessage(R.string.loadSuspended)
3726 .setPositiveButton(R.string.ok, null)
3727 .show();
3728 }
3729 }
3730
The Android Open Source Project0c908882009-03-03 19:32:16 -08003731 @Override
3732 protected void onActivityResult(int requestCode, int resultCode,
3733 Intent intent) {
Grace Klobabb394f32009-11-19 10:26:37 -08003734 if (getTopWindow() == null) return;
3735
The Android Open Source Project0c908882009-03-03 19:32:16 -08003736 switch (requestCode) {
3737 case COMBO_PAGE:
3738 if (resultCode == RESULT_OK && intent != null) {
3739 String data = intent.getAction();
3740 Bundle extras = intent.getExtras();
3741 if (extras != null && extras.getBoolean("new_window", false)) {
Michael Kolb68792c82010-08-09 16:39:18 -07003742 openTab(data, false);
3743 } else if ((extras != null) &&
3744 extras.getBoolean(CombinedBookmarkHistoryActivity.NEWTAB_MODE)) {
3745 openTab(data, true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003746 } else {
Michael Kolb68792c82010-08-09 16:39:18 -07003747 final Tab currentTab = mTabControl.getCurrentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04003748 dismissSubWindow(currentTab);
3749 if (data != null && data.length() != 0) {
Leon Scroggins92472e82010-02-17 16:32:28 -05003750 loadUrl(getTopWindow(), data);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003751 }
3752 }
3753 }
Leon Scrogginsfde97462010-01-11 13:06:21 -05003754 // Deliberately fall through to PREFERENCES_PAGE, since the
3755 // same extra may be attached to the COMBO_PAGE
3756 case PREFERENCES_PAGE:
3757 if (resultCode == RESULT_OK && intent != null) {
3758 String action = intent.getStringExtra(Intent.EXTRA_TEXT);
3759 if (BrowserSettings.PREF_CLEAR_HISTORY.equals(action)) {
3760 mTabControl.removeParentChildRelationShips();
3761 }
3762 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003763 break;
Leon Scroggins8d5fa432009-10-02 15:55:59 -04003764 // Choose a file from the file picker.
3765 case FILE_SELECTED:
3766 if (null == mUploadMessage) break;
3767 Uri result = intent == null || resultCode != RESULT_OK ? null
3768 : intent.getData();
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003769
3770 // As we ask the camera to save the result of the user taking
3771 // a picture, the camera application does not return anything other
3772 // than RESULT_OK. So we need to check whether the file we expected
3773 // was written to disk in the in the case that we
3774 // did not get an intent returned but did get a RESULT_OK. If it was,
3775 // we assume that this result has came back from the camera.
3776 if (result == null && intent == null && resultCode == RESULT_OK) {
3777 File cameraFile = new File(mCameraFilePath);
3778 if (cameraFile.exists()) {
3779 result = Uri.fromFile(cameraFile);
Ben Murdoch07d34732010-05-27 18:34:46 +01003780 // Broadcast to the media scanner that we have a new photo
3781 // so it will be added into the gallery for the user.
3782 sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, result));
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003783 }
3784 }
Leon Scroggins8d5fa432009-10-02 15:55:59 -04003785 mUploadMessage.onReceiveValue(result);
3786 mUploadMessage = null;
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003787 mCameraFilePath = null;
Leon Scroggins8d5fa432009-10-02 15:55:59 -04003788 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003789 default:
3790 break;
3791 }
Leon Scroggins30444232009-09-04 18:36:20 -04003792 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003793 }
3794
3795 /*
3796 * This method is called as a result of the user selecting the options
Leon Scrogginsf08809b2010-01-21 09:27:46 -05003797 * menu to see the download window. It shows the download window on top of
3798 * the current window.
The Android Open Source Project0c908882009-03-03 19:32:16 -08003799 */
Leon Scrogginsf08809b2010-01-21 09:27:46 -05003800 private void viewDownloads(Uri downloadRecord) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003801 Intent intent = new Intent(this,
3802 BrowserDownloadPage.class);
3803 intent.setData(downloadRecord);
Grace Kloba22ac16e2009-10-07 18:00:23 -07003804 startActivityForResult(intent, BrowserActivity.DOWNLOAD_PAGE);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003805
3806 }
3807
Ben Murdocheecb4e62010-07-06 16:30:38 +01003808 /* package*/ void promptAddOrInstallBookmark() {
3809 final Tab current = mTabControl.getCurrentTab();
3810 Resources resources = getResources();
3811 CharSequence[] choices = {
3812 resources.getString(R.string.save_to_bookmarks),
3813 resources.getString(R.string.create_shortcut_bookmark)
3814 };
3815
3816 AlertDialog.Builder builder = new AlertDialog.Builder(this);
3817 builder.setTitle(R.string.add_new_bookmark);
3818 builder.setItems(choices, new DialogInterface.OnClickListener() {
3819 public void onClick(DialogInterface dialog, int item) {
3820 if (item == 0) {
3821 bookmarkCurrentPage();
3822 } else if (item == 1) {
3823 current.populatePickerData();
3824 String touchIconUrl = mTabControl.getCurrentWebView().getTouchIconUrl();
3825 if (touchIconUrl != null) {
3826 // Download the touch icon for this site then save it to the
3827 // homescreen.
3828 Bundle b = new Bundle();
3829 b.putString("url", current.getUrl());
3830 b.putString("title", current.getTitle());
3831 b.putParcelable("favicon", current.getFavicon());
3832 Message msg = mHandler.obtainMessage(TOUCH_ICON_DOWNLOADED);
3833 msg.setData(b);
Ben Murdochccb5de02010-07-19 18:38:17 +01003834 new DownloadTouchIcon(BrowserActivity.this, msg,
Ben Murdocheecb4e62010-07-06 16:30:38 +01003835 mTabControl.getCurrentWebView().getSettings()
3836 .getUserAgentString()).execute(touchIconUrl);
3837 } else {
3838 // add to homescreen, can do it immediately as there is no touch
3839 // icon.
3840 showSaveToHomescreenDialog(current.getUrl(), current.getTitle(),
3841 null, current.getFavicon());
3842 }
3843 }
3844 }
3845 });
3846 builder.create().show();
3847 }
3848
Leon Scroggins160a7e72009-08-14 18:28:01 -04003849 /**
3850 * Open the Go page.
3851 * @param startWithHistory If true, open starting on the history tab.
3852 * Otherwise, start with the bookmarks tab.
Leon Scroggins160a7e72009-08-14 18:28:01 -04003853 */
Michael Kolb68792c82010-08-09 16:39:18 -07003854 /* package */ void bookmarksOrHistoryPicker(boolean startWithHistory, boolean newTabMode) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003855 WebView current = mTabControl.getCurrentWebView();
3856 if (current == null) {
3857 return;
3858 }
3859 Intent intent = new Intent(this,
3860 CombinedBookmarkHistoryActivity.class);
3861 String title = current.getTitle();
3862 String url = current.getUrl();
Ben Murdoch87cc65d2010-06-29 20:34:10 +01003863 Bitmap thumbnail = createScreenshot(current, getDesiredThumbnailWidth(this),
3864 getDesiredThumbnailHeight(this));
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01003865
The Android Open Source Project0c908882009-03-03 19:32:16 -08003866 // Just in case the user opens bookmarks before a page finishes loading
3867 // so the current history item, and therefore the page, is null.
3868 if (null == url) {
3869 url = mLastEnteredUrl;
3870 // This can happen.
3871 if (null == url) {
3872 url = mSettings.getHomePage();
3873 }
3874 }
3875 // In case the web page has not yet received its associated title.
3876 if (title == null) {
3877 title = url;
3878 }
3879 intent.putExtra("title", title);
3880 intent.putExtra("url", url);
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01003881 intent.putExtra("thumbnail", thumbnail);
Leon Scroggins30444232009-09-04 18:36:20 -04003882 // Disable opening in a new window if we have maxed out the windows
Grace Kloba22ac16e2009-10-07 18:00:23 -07003883 intent.putExtra("disable_new_window", !mTabControl.canCreateNewTab());
Patrick Scott3918d442009-08-04 13:22:29 -04003884 intent.putExtra("touch_icon_url", current.getTouchIconUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003885 if (startWithHistory) {
3886 intent.putExtra(CombinedBookmarkHistoryActivity.STARTING_TAB,
3887 CombinedBookmarkHistoryActivity.HISTORY_TAB);
3888 }
Michael Kolb68792c82010-08-09 16:39:18 -07003889 if (newTabMode) {
3890 intent.putExtra(CombinedBookmarkHistoryActivity.NEWTAB_MODE, true);
3891 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003892 startActivityForResult(intent, COMBO_PAGE);
3893 }
3894
Ben Murdocheecb4e62010-07-06 16:30:38 +01003895 private void showSaveToHomescreenDialog(String url, String title, Bitmap touchIcon,
3896 Bitmap favicon) {
3897 Intent intent = new Intent(this, SaveToHomescreenDialog.class);
3898
3899 // Just in case the user tries to save before a page finishes loading
3900 // so the current history item, and therefore the page, is null.
3901 if (null == url) {
3902 url = mLastEnteredUrl;
3903 // This can happen.
3904 if (null == url) {
3905 url = mSettings.getHomePage();
3906 }
3907 }
3908
3909 // In case the web page has not yet received its associated title.
3910 if (title == null) {
3911 title = url;
3912 }
3913
3914 intent.putExtra("title", title);
3915 intent.putExtra("url", url);
3916 intent.putExtra("favicon", favicon);
3917 intent.putExtra("touchIcon", touchIcon);
3918 startActivity(intent);
3919 }
3920
3921
The Android Open Source Project0c908882009-03-03 19:32:16 -08003922 // Called when loading from context menu or LOAD_URL message
Leon Scroggins92472e82010-02-17 16:32:28 -05003923 private void loadUrlFromContext(WebView view, String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003924 // In case the user enters nothing.
3925 if (url != null && url.length() != 0 && view != null) {
3926 url = smartUrlFilter(url);
Grace Kloba22ac16e2009-10-07 18:00:23 -07003927 if (!view.getWebViewClient().shouldOverrideUrlLoading(view, url)) {
Leon Scroggins92472e82010-02-17 16:32:28 -05003928 loadUrl(view, url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003929 }
3930 }
3931 }
3932
Leon Scroggins92472e82010-02-17 16:32:28 -05003933 /**
3934 * Load the URL into the given WebView and update the title bar
3935 * to reflect the new load. Call this instead of WebView.loadUrl
3936 * directly.
3937 * @param view The WebView used to load url.
3938 * @param url The URL to load.
3939 */
3940 private void loadUrl(WebView view, String url) {
3941 updateTitleBarForNewLoad(view, url);
3942 view.loadUrl(url);
3943 }
3944
3945 /**
3946 * Load UrlData into a Tab and update the title bar to reflect the new
3947 * load. Call this instead of UrlData.loadIn directly.
3948 * @param t The Tab used to load.
3949 * @param data The UrlData being loaded.
3950 */
3951 private void loadUrlDataIn(Tab t, UrlData data) {
3952 updateTitleBarForNewLoad(t.getWebView(), data.mUrl);
3953 data.loadIn(t);
3954 }
3955
3956 /**
3957 * If the WebView is the top window, update the title bar to reflect
3958 * loading the new URL. i.e. set its text, clear the favicon (which
3959 * will be set once the page begins loading), and set the progress to
3960 * INITIAL_PROGRESS to show that the page has begun to load. Called
3961 * by loadUrl and loadUrlDataIn.
3962 * @param view The WebView that is starting a load.
3963 * @param url The URL that is being loaded.
3964 */
3965 private void updateTitleBarForNewLoad(WebView view, String url) {
3966 if (view == getTopWindow()) {
3967 setUrlTitle(url, null);
3968 setFavicon(null);
3969 onProgressChanged(view, INITIAL_PROGRESS);
3970 }
3971 }
3972
The Android Open Source Project0c908882009-03-03 19:32:16 -08003973 private String smartUrlFilter(Uri inUri) {
3974 if (inUri != null) {
3975 return smartUrlFilter(inUri.toString());
3976 }
3977 return null;
3978 }
3979
Feng Qianb34f87a2009-03-24 21:27:26 -07003980 protected static final Pattern ACCEPTED_URI_SCHEMA = Pattern.compile(
The Android Open Source Project0c908882009-03-03 19:32:16 -08003981 "(?i)" + // switch on case insensitive matching
3982 "(" + // begin group for schema
3983 "(?:http|https|file):\\/\\/" +
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003984 "|(?:inline|data|about|content|javascript):" +
The Android Open Source Project0c908882009-03-03 19:32:16 -08003985 ")" +
3986 "(.*)" );
3987
3988 /**
3989 * Attempts to determine whether user input is a URL or search
3990 * terms. Anything with a space is passed to search.
3991 *
3992 * Converts to lowercase any mistakenly uppercased schema (i.e.,
3993 * "Http://" converts to "http://"
3994 *
3995 * @return Original or modified URL
3996 *
3997 */
3998 String smartUrlFilter(String url) {
3999
4000 String inUrl = url.trim();
4001 boolean hasSpace = inUrl.indexOf(' ') != -1;
4002
4003 Matcher matcher = ACCEPTED_URI_SCHEMA.matcher(inUrl);
4004 if (matcher.matches()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08004005 // force scheme to lowercase
4006 String scheme = matcher.group(1);
4007 String lcScheme = scheme.toLowerCase();
4008 if (!lcScheme.equals(scheme)) {
Mitsuru Oshima123ecfb2009-05-18 19:11:14 -07004009 inUrl = lcScheme + matcher.group(2);
4010 }
4011 if (hasSpace) {
4012 inUrl = inUrl.replace(" ", "%20");
The Android Open Source Project0c908882009-03-03 19:32:16 -08004013 }
4014 return inUrl;
4015 }
4016 if (hasSpace) {
Satish Sampath565505b2009-05-29 15:37:27 +01004017 // FIXME: Is this the correct place to add to searches?
4018 // what if someone else calls this function?
4019 int shortcut = parseUrlShortcut(inUrl);
4020 if (shortcut != SHORTCUT_INVALID) {
4021 Browser.addSearchUrl(mResolver, inUrl);
4022 String query = inUrl.substring(2);
4023 switch (shortcut) {
4024 case SHORTCUT_GOOGLE_SEARCH:
Grace Kloba47fdfdb2009-06-30 11:15:34 -07004025 return URLUtil.composeSearchUrl(query, QuickSearch_G, QUERY_PLACE_HOLDER);
Satish Sampath565505b2009-05-29 15:37:27 +01004026 case SHORTCUT_WIKIPEDIA_SEARCH:
4027 return URLUtil.composeSearchUrl(query, QuickSearch_W, QUERY_PLACE_HOLDER);
4028 case SHORTCUT_DICTIONARY_SEARCH:
4029 return URLUtil.composeSearchUrl(query, QuickSearch_D, QUERY_PLACE_HOLDER);
4030 case SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH:
The Android Open Source Project0c908882009-03-03 19:32:16 -08004031 // FIXME: we need location in this case
Satish Sampath565505b2009-05-29 15:37:27 +01004032 return URLUtil.composeSearchUrl(query, QuickSearch_L, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004033 }
4034 }
4035 } else {
Dan Egnor5ee906c2009-11-18 12:11:49 -08004036 if (Patterns.WEB_URL.matcher(inUrl).matches()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08004037 return URLUtil.guessUrl(inUrl);
4038 }
4039 }
4040
4041 Browser.addSearchUrl(mResolver, inUrl);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07004042 return URLUtil.composeSearchUrl(inUrl, QuickSearch_G, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004043 }
4044
Ben Murdochbff2d602009-07-01 20:19:05 +01004045 /* package */ void setShouldShowErrorConsole(boolean flag) {
4046 if (flag == mShouldShowErrorConsole) {
4047 // Nothing to do.
4048 return;
4049 }
4050
4051 mShouldShowErrorConsole = flag;
4052
Grace Kloba22ac16e2009-10-07 18:00:23 -07004053 ErrorConsoleView errorConsole = mTabControl.getCurrentTab()
4054 .getErrorConsole(true);
Ben Murdochbff2d602009-07-01 20:19:05 +01004055
4056 if (flag) {
4057 // Setting the show state of the console will cause it's the layout to be inflated.
4058 if (errorConsole.numberOfErrors() > 0) {
4059 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
4060 } else {
4061 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
4062 }
4063
4064 // Now we can add it to the main view.
4065 mErrorConsoleContainer.addView(errorConsole,
Romain Guy15b8ec62010-01-08 15:06:43 -08004066 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
Ben Murdochbff2d602009-07-01 20:19:05 +01004067 ViewGroup.LayoutParams.WRAP_CONTENT));
4068 } else {
4069 mErrorConsoleContainer.removeView(errorConsole);
4070 }
4071
4072 }
4073
Grace Kloba22ac16e2009-10-07 18:00:23 -07004074 boolean shouldShowErrorConsole() {
4075 return mShouldShowErrorConsole;
4076 }
4077
Andrei Popescu163ab742009-10-20 17:58:23 +01004078 private void setStatusBarVisibility(boolean visible) {
4079 int flag = visible ? 0 : WindowManager.LayoutParams.FLAG_FULLSCREEN;
4080 getWindow().setFlags(flag, WindowManager.LayoutParams.FLAG_FULLSCREEN);
4081 }
4082
Andrei Popescu56199cc2010-01-12 22:39:16 +00004083
4084 private void sendNetworkType(String type, String subtype) {
4085 WebView w = mTabControl.getCurrentWebView();
4086 if (w != null) {
4087 w.setNetworkType(type, subtype);
4088 }
4089 }
4090
Andrei Popescu30995e72010-02-09 16:59:58 +00004091 private void packageChanged(String packageName, boolean wasAdded) {
4092 WebView w = mTabControl.getCurrentWebView();
4093 if (w == null) {
4094 return;
4095 }
4096
4097 if (wasAdded) {
4098 w.addPackageName(packageName);
4099 } else {
4100 w.removePackageName(packageName);
4101 }
4102 }
4103
4104 private void addPackageNames(Set<String> packageNames) {
4105 WebView w = mTabControl.getCurrentWebView();
4106 if (w == null) {
4107 return;
4108 }
4109
4110 w.addPackageNames(packageNames);
4111 }
4112
4113 private void getInstalledPackages() {
4114 AsyncTask<Void, Void, Set<String> > task =
4115 new AsyncTask<Void, Void, Set<String> >() {
Michael Kolbe0a36662010-06-29 10:37:12 -07004116 @Override
Andrei Popescu30995e72010-02-09 16:59:58 +00004117 protected Set<String> doInBackground(Void... unused) {
4118 Set<String> installedPackages = new HashSet<String>();
4119 PackageManager pm = BrowserActivity.this.getPackageManager();
4120 if (pm != null) {
4121 List<PackageInfo> packages = pm.getInstalledPackages(0);
4122 for (PackageInfo p : packages) {
4123 if (BrowserActivity.this.sGoogleApps.contains(p.packageName)) {
4124 installedPackages.add(p.packageName);
4125 }
4126 }
4127 }
4128
4129 return installedPackages;
4130 }
4131
4132 // Executes on the UI thread
Michael Kolbe0a36662010-06-29 10:37:12 -07004133 @Override
Andrei Popescu30995e72010-02-09 16:59:58 +00004134 protected void onPostExecute(Set<String> installedPackages) {
4135 addPackageNames(installedPackages);
4136 }
4137 };
4138 task.execute();
4139 }
4140
Grace Klobaeb6eef42009-09-15 17:56:32 -07004141 final static int LOCK_ICON_UNSECURE = 0;
4142 final static int LOCK_ICON_SECURE = 1;
4143 final static int LOCK_ICON_MIXED = 2;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004144
The Android Open Source Project0c908882009-03-03 19:32:16 -08004145 private BrowserSettings mSettings;
4146 private TabControl mTabControl;
4147 private ContentResolver mResolver;
4148 private FrameLayout mContentView;
Andrei Popescuadc008d2009-06-26 14:11:30 +01004149 private View mCustomView;
4150 private FrameLayout mCustomViewContainer;
Andrei Popescuc9b55562009-07-07 10:51:15 +01004151 private WebChromeClient.CustomViewCallback mCustomViewCallback;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004152
4153 // FIXME, temp address onPrepareMenu performance problem. When we move everything out of
4154 // view, we should rewrite this.
4155 private int mCurrentMenuState = 0;
4156 private int mMenuState = R.id.MAIN_MENU;
Andrei Popescuadc008d2009-06-26 14:11:30 +01004157 private int mOldMenuState = EMPTY_MENU;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004158 private static final int EMPTY_MENU = -1;
4159 private Menu mMenu;
4160
4161 private FindDialog mFindDialog;
Cary Clark01cfcdd2010-06-04 16:36:45 -04004162 private SelectDialog mSelectDialog;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004163 // Used to prevent chording to result in firing two shortcuts immediately
4164 // one after another. Fixes bug 1211714.
4165 boolean mCanChord;
4166
4167 private boolean mInLoad;
4168 private boolean mIsNetworkUp;
Ben Murdochb7cc8b42009-09-28 10:59:09 +01004169 private boolean mDidStopLoad;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004170
Cary Clark1f10cbf2010-03-22 11:45:23 -04004171 /* package */ boolean mActivityInPause = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004172
4173 private boolean mMenuIsDown;
4174
The Android Open Source Project0c908882009-03-03 19:32:16 -08004175 private static boolean mInTrace;
4176
4177 // Performance probe
4178 private static final int[] SYSTEM_CPU_FORMAT = new int[] {
4179 Process.PROC_SPACE_TERM | Process.PROC_COMBINE,
4180 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 1: user time
4181 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 2: nice time
4182 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 3: sys time
4183 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 4: idle time
4184 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 5: iowait time
4185 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 6: irq time
4186 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG // 7: softirq time
4187 };
4188
4189 private long mStart;
4190 private long mProcessStart;
4191 private long mUserStart;
4192 private long mSystemStart;
4193 private long mIdleStart;
4194 private long mIrqStart;
4195
4196 private long mUiStart;
4197
4198 private Drawable mMixLockIcon;
4199 private Drawable mSecLockIcon;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004200
4201 /* hold a ref so we can auto-cancel if necessary */
4202 private AlertDialog mAlertDialog;
4203
The Android Open Source Project0c908882009-03-03 19:32:16 -08004204 // The up-to-date URL and title (these can be different from those stored
4205 // in WebView, since it takes some time for the information in WebView to
4206 // get updated)
4207 private String mUrl;
4208 private String mTitle;
4209
4210 // As PageInfo has different style for landscape / portrait, we have
4211 // to re-open it when configuration changed
4212 private AlertDialog mPageInfoDialog;
Grace Kloba22ac16e2009-10-07 18:00:23 -07004213 private Tab mPageInfoView;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004214 // If the Page-Info dialog is launched from the SSL-certificate-on-error
4215 // dialog, we should not just dismiss it, but should get back to the
4216 // SSL-certificate-on-error dialog. This flag is used to store this state
Leon Scrogginsc7b92f82010-01-11 18:17:31 -05004217 private boolean mPageInfoFromShowSSLCertificateOnError;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004218
4219 // as SSLCertificateOnError has different style for landscape / portrait,
4220 // we have to re-open it when configuration changed
4221 private AlertDialog mSSLCertificateOnErrorDialog;
4222 private WebView mSSLCertificateOnErrorView;
4223 private SslErrorHandler mSSLCertificateOnErrorHandler;
4224 private SslError mSSLCertificateOnErrorError;
4225
4226 // as SSLCertificate has different style for landscape / portrait, we
4227 // have to re-open it when configuration changed
4228 private AlertDialog mSSLCertificateDialog;
Grace Kloba22ac16e2009-10-07 18:00:23 -07004229 private Tab mSSLCertificateView;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004230
4231 // as HttpAuthentication has different style for landscape / portrait, we
4232 // have to re-open it when configuration changed
4233 private AlertDialog mHttpAuthenticationDialog;
4234 private HttpAuthHandler mHttpAuthHandler;
4235
4236 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_PARAMS =
4237 new FrameLayout.LayoutParams(
Romain Guy15b8ec62010-01-08 15:06:43 -08004238 ViewGroup.LayoutParams.MATCH_PARENT,
4239 ViewGroup.LayoutParams.MATCH_PARENT);
Andrei Popescuadc008d2009-06-26 14:11:30 +01004240 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_GRAVITY_CENTER =
4241 new FrameLayout.LayoutParams(
Romain Guy15b8ec62010-01-08 15:06:43 -08004242 ViewGroup.LayoutParams.MATCH_PARENT,
4243 ViewGroup.LayoutParams.MATCH_PARENT,
Andrei Popescuadc008d2009-06-26 14:11:30 +01004244 Gravity.CENTER);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07004245 // Google search
4246 final static String QuickSearch_G = "http://www.google.com/m?q=%s";
The Android Open Source Project0c908882009-03-03 19:32:16 -08004247 // Wikipedia search
4248 final static String QuickSearch_W = "http://en.wikipedia.org/w/index.php?search=%s&go=Go";
4249 // Dictionary search
4250 final static String QuickSearch_D = "http://dictionary.reference.com/search?q=%s";
4251 // Google Mobile Local search
4252 final static String QuickSearch_L = "http://www.google.com/m/search?site=local&q=%s&near=mountain+view";
4253
4254 final static String QUERY_PLACE_HOLDER = "%s";
4255
4256 // "source" parameter for Google search through search key
4257 final static String GOOGLE_SEARCH_SOURCE_SEARCHKEY = "browser-key";
4258 // "source" parameter for Google search through goto menu
4259 final static String GOOGLE_SEARCH_SOURCE_GOTO = "browser-goto";
4260 // "source" parameter for Google search through simplily type
4261 final static String GOOGLE_SEARCH_SOURCE_TYPE = "browser-type";
4262 // "source" parameter for Google search suggested by the browser
4263 final static String GOOGLE_SEARCH_SOURCE_SUGGEST = "browser-suggest";
4264 // "source" parameter for Google search from unknown source
4265 final static String GOOGLE_SEARCH_SOURCE_UNKNOWN = "unknown";
4266
4267 private final static String LOGTAG = "browser";
4268
The Android Open Source Project0c908882009-03-03 19:32:16 -08004269 private String mLastEnteredUrl;
4270
4271 private PowerManager.WakeLock mWakeLock;
4272 private final static int WAKELOCK_TIMEOUT = 5 * 60 * 1000; // 5 minutes
4273
4274 private Toast mStopToast;
4275
Leon Scroggins571b3762010-05-26 10:25:01 -04004276 private TitleBarBase mTitleBar;
Michael Kolba2b2ba82010-08-04 17:54:03 -07004277 private TabBar mTabBar;
Leon Scroggins81db3662009-06-04 17:45:11 -04004278
Ben Murdochbff2d602009-07-01 20:19:05 +01004279 private LinearLayout mErrorConsoleContainer = null;
4280 private boolean mShouldShowErrorConsole = false;
4281
The Android Open Source Project0c908882009-03-03 19:32:16 -08004282 // As the ids are dynamically created, we can't guarantee that they will
4283 // be in sequence, so this static array maps ids to a window number.
4284 final static private int[] WINDOW_SHORTCUT_ID_ARRAY =
4285 { R.id.window_one_menu_id, R.id.window_two_menu_id, R.id.window_three_menu_id,
4286 R.id.window_four_menu_id, R.id.window_five_menu_id, R.id.window_six_menu_id,
4287 R.id.window_seven_menu_id, R.id.window_eight_menu_id };
4288
4289 // monitor platform changes
4290 private IntentFilter mNetworkStateChangedFilter;
4291 private BroadcastReceiver mNetworkStateIntentReceiver;
4292
Grace Klobab4da0ad2009-05-14 14:45:40 -07004293 private BroadcastReceiver mPackageInstallationReceiver;
4294
Bjorn Bringerta7611812010-03-24 11:12:02 +00004295 private SystemAllowGeolocationOrigins mSystemAllowGeolocationOrigins;
4296
The Android Open Source Project0c908882009-03-03 19:32:16 -08004297 // activity requestCode
Nicolas Roard78a98e42009-05-11 13:34:17 +01004298 final static int COMBO_PAGE = 1;
4299 final static int DOWNLOAD_PAGE = 2;
4300 final static int PREFERENCES_PAGE = 3;
Leon Scroggins8d5fa432009-10-02 15:55:59 -04004301 final static int FILE_SELECTED = 4;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004302
Andrei Popescu540035d2009-09-18 18:59:20 +01004303 // the default <video> poster
4304 private Bitmap mDefaultVideoPoster;
4305 // the video progress view
4306 private View mVideoProgressView;
4307
Andrei Popescu30995e72010-02-09 16:59:58 +00004308 // The Google packages we monitor for the navigator.isApplicationInstalled()
4309 // API. Add as needed.
4310 private static Set<String> sGoogleApps;
4311 static {
4312 sGoogleApps = new HashSet<String>();
4313 sGoogleApps.add("com.google.android.youtube");
4314 }
4315
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004316 /**
4317 * A UrlData class to abstract how the content will be set to WebView.
4318 * This base class uses loadUrl to show the content.
4319 */
Leon Scroggins6eac63e2010-03-15 18:19:14 -04004320 /* package */ static class UrlData {
Grace Kloba068e48b2010-01-26 18:11:27 -08004321 final String mUrl;
4322 final Map<String, String> mHeaders;
Leon Scroggins58d56c62010-01-28 15:12:40 -05004323 final Intent mVoiceIntent;
Grace Kloba60e095c2009-06-16 11:50:55 -07004324
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004325 UrlData(String url) {
4326 this.mUrl = url;
Grace Kloba068e48b2010-01-26 18:11:27 -08004327 this.mHeaders = null;
Leon Scroggins58d56c62010-01-28 15:12:40 -05004328 this.mVoiceIntent = null;
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004329 }
Grace Kloba60e095c2009-06-16 11:50:55 -07004330
Leon Scroggins58d56c62010-01-28 15:12:40 -05004331 UrlData(String url, Map<String, String> headers, Intent intent) {
Grace Kloba068e48b2010-01-26 18:11:27 -08004332 this.mUrl = url;
4333 this.mHeaders = headers;
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -05004334 if (RecognizerResultsIntent.ACTION_VOICE_SEARCH_RESULTS
4335 .equals(intent.getAction())) {
Leon Scroggins58d56c62010-01-28 15:12:40 -05004336 this.mVoiceIntent = intent;
4337 } else {
4338 this.mVoiceIntent = null;
4339 }
Grace Kloba60e095c2009-06-16 11:50:55 -07004340 }
4341
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004342 boolean isEmpty() {
Leon Scroggins58d56c62010-01-28 15:12:40 -05004343 return mVoiceIntent == null && (mUrl == null || mUrl.length() == 0);
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004344 }
4345
Leon Scroggins92472e82010-02-17 16:32:28 -05004346 /**
4347 * Load this UrlData into the given Tab. Use loadUrlDataIn to update
4348 * the title bar as well.
4349 */
Leon Scroggins58d56c62010-01-28 15:12:40 -05004350 public void loadIn(Tab t) {
4351 if (mVoiceIntent != null) {
4352 t.activateVoiceSearchMode(mVoiceIntent);
4353 } else {
4354 t.getWebView().loadUrl(mUrl, mHeaders);
4355 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004356 }
4357 };
4358
Leon Scroggins1f005d32009-08-10 17:36:42 -04004359 /* package */ static final UrlData EMPTY_URL_DATA = new UrlData(null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004360}