blob: 548eba6c750cd27d268e7ef40a60dca2aebc1618 [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;
Jeff Hamilton8ce956c2010-08-17 11:13:53 -050065import android.provider.BrowserContract;
Cary Clark5e335a32009-09-22 14:53:11 -040066import android.provider.ContactsContract;
Michael Kolba2b2ba82010-08-04 17:54:03 -070067import android.provider.ContactsContract.Intents.Insert;
The Android Open Source Project0c908882009-03-03 19:32:16 -080068import android.provider.Downloads;
69import android.provider.MediaStore;
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -050070import android.speech.RecognizerResultsIntent;
The Android Open Source Project0c908882009-03-03 19:32:16 -080071import android.text.TextUtils;
72import android.text.format.DateFormat;
The Android Open Source Project0c908882009-03-03 19:32:16 -080073import android.util.Log;
Dianne Hackborn385effd2010-02-24 20:03:04 -080074import android.util.Patterns;
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -040075import android.view.ActionMode;
The Android Open Source Project0c908882009-03-03 19:32:16 -080076import android.view.ContextMenu;
Michael Kolba2b2ba82010-08-04 17:54:03 -070077import android.view.ContextMenu.ContextMenuInfo;
The Android Open Source Project0c908882009-03-03 19:32:16 -080078import android.view.Gravity;
79import android.view.KeyEvent;
80import android.view.LayoutInflater;
81import android.view.Menu;
82import android.view.MenuInflater;
83import android.view.MenuItem;
Michael Kolba2b2ba82010-08-04 17:54:03 -070084import android.view.MenuItem.OnMenuItemClickListener;
The Android Open Source Project0c908882009-03-03 19:32:16 -080085import android.view.View;
86import android.view.ViewGroup;
87import android.view.Window;
88import android.view.WindowManager;
Svetoslav Ganov2b345992010-05-06 06:13:54 -070089import android.view.accessibility.AccessibilityManager;
The Android Open Source Project0c908882009-03-03 19:32:16 -080090import android.webkit.CookieManager;
91import android.webkit.CookieSyncManager;
92import android.webkit.DownloadListener;
93import android.webkit.HttpAuthHandler;
Grace Klobab4da0ad2009-05-14 14:45:40 -070094import android.webkit.PluginManager;
The Android Open Source Project0c908882009-03-03 19:32:16 -080095import android.webkit.SslErrorHandler;
96import android.webkit.URLUtil;
Leon Clarkecb6cc862009-09-29 18:35:13 +010097import android.webkit.ValueCallback;
The Android Open Source Project0c908882009-03-03 19:32:16 -080098import android.webkit.WebChromeClient;
99import android.webkit.WebHistoryItem;
100import android.webkit.WebIconDatabase;
101import android.webkit.WebView;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800102import android.widget.EditText;
103import android.widget.FrameLayout;
104import android.widget.LinearLayout;
105import android.widget.TextView;
106import android.widget.Toast;
107
Michael Kolba2b2ba82010-08-04 17:54:03 -0700108import com.android.browser.ScrollWebView.ScrollListener;
Bjorn Bringert10d1cca2010-02-10 14:22:12 +0000109import com.android.common.Search;
Leon Scroggins1fe13a52010-02-09 15:31:26 -0500110import com.android.common.speech.LoggingEvents;
Dan Egnor5ee906c2009-11-18 12:11:49 -0800111
Leon Scrogginsb6b7f9e2009-06-18 12:05:28 -0400112import java.io.ByteArrayOutputStream;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800113import java.io.File;
Ben Murdoch4f75ba22009-10-27 11:48:28 +0000114import java.io.IOException;
115import java.io.InputStream;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800116import java.net.MalformedURLException;
Dianne Hackborn99189432009-06-17 18:06:18 -0700117import java.net.URISyntaxException;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800118import java.net.URL;
119import java.net.URLEncoder;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800120import java.util.Date;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800121import java.util.HashMap;
Andrei Popescu30995e72010-02-09 16:59:58 +0000122import java.util.HashSet;
Grace Kloba00f54c52010-01-27 14:53:51 -0800123import java.util.Iterator;
Andrei Popescu30995e72010-02-09 16:59:58 +0000124import java.util.List;
Grace Kloba068e48b2010-01-26 18:11:27 -0800125import java.util.Map;
Andrei Popescu30995e72010-02-09 16:59:58 +0000126import java.util.Set;
Michael Kolbfe251992010-07-08 15:41:55 -0700127import java.util.Vector;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800128import java.util.regex.Matcher;
129import java.util.regex.Pattern;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800130
131public class BrowserActivity extends Activity
Shimeng (Simon) Wang98d5fce2010-03-16 13:23:39 -0700132 implements View.OnCreateContextMenuListener, DownloadListener {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800133
Dave Bort31a6d1c2009-04-13 15:56:49 -0700134 /* Define some aliases to make these debugging flags easier to refer to.
135 * This file imports android.provider.Browser, so we can't just refer to "Browser.DEBUG".
136 */
137 private final static boolean DEBUG = com.android.browser.Browser.DEBUG;
138 private final static boolean LOGV_ENABLED = com.android.browser.Browser.LOGV_ENABLED;
139 private final static boolean LOGD_ENABLED = com.android.browser.Browser.LOGD_ENABLED;
140
Satish Sampath565505b2009-05-29 15:37:27 +0100141 // These are single-character shortcuts for searching popular sources.
142 private static final int SHORTCUT_INVALID = 0;
143 private static final int SHORTCUT_GOOGLE_SEARCH = 1;
144 private static final int SHORTCUT_WIKIPEDIA_SEARCH = 2;
145 private static final int SHORTCUT_DICTIONARY_SEARCH = 3;
146 private static final int SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH = 4;
147
Cary Clarka9771242009-08-11 16:42:26 -0400148 private static class ClearThumbnails extends AsyncTask<File, Void, Void> {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800149 @Override
150 public Void doInBackground(File... files) {
151 if (files != null) {
152 for (File f : files) {
Cary Clarkd6be1752009-08-12 12:56:42 -0400153 if (!f.delete()) {
154 Log.e(LOGTAG, f.getPath() + " was not deleted");
155 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800156 }
157 }
158 return null;
159 }
160 }
161
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400162 /**
163 * This layout holds everything you see below the status bar, including the
164 * error console, the custom view container, and the webviews.
165 */
166 private FrameLayout mBrowserFrameLayout;
Leon Scroggins81db3662009-06-04 17:45:11 -0400167
Leon Scrogginsd746a942010-05-19 13:21:44 -0400168 private boolean mXLargeScreenSize;
169
Jeff Davidson43610292010-07-16 16:03:58 -0700170 private Boolean mIsProviderPresent = null;
171 private Uri mRlzUri = null;
172
Grace Kloba22ac16e2009-10-07 18:00:23 -0700173 @Override
174 public void onCreate(Bundle icicle) {
Dave Bort31a6d1c2009-04-13 15:56:49 -0700175 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800176 Log.v(LOGTAG, this + " onStart");
177 }
178 super.onCreate(icicle);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800179 // test the browser in OpenGL
180 // requestWindowFeature(Window.FEATURE_OPENGL);
181
Mike Reedd334bf52010-01-26 15:21:44 -0500182 // enable this to test the browser in 32bit
183 if (false) {
184 getWindow().setFormat(PixelFormat.RGBX_8888);
185 BitmapFactory.setDefaultConfig(Bitmap.Config.ARGB_8888);
186 }
187
Svetoslav Ganov2b345992010-05-06 06:13:54 -0700188 if (AccessibilityManager.getInstance(this).isEnabled()) {
189 setDefaultKeyMode(DEFAULT_KEYS_DISABLE);
190 } else {
191 setDefaultKeyMode(DEFAULT_KEYS_SEARCH_LOCAL);
192 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800193
194 mResolver = getContentResolver();
195
Grace Kloba0923d692009-09-23 21:37:25 -0700196 // If this was a web search request, pass it on to the default web
197 // search provider and finish this activity.
198 if (handleWebSearchIntent(getIntent())) {
199 finish();
200 return;
201 }
202
The Android Open Source Project0c908882009-03-03 19:32:16 -0800203 mSecLockIcon = Resources.getSystem().getDrawable(
204 android.R.drawable.ic_secure);
205 mMixLockIcon = Resources.getSystem().getDrawable(
206 android.R.drawable.ic_partial_secure);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800207
Michael Kolbed217742010-08-10 17:52:34 -0700208 // Create the tab control and our initial tab
209 mTabControl = new TabControl(this);
210
211 mXLargeScreenSize = (getResources().getConfiguration().screenLayout
212 & Configuration.SCREENLAYOUT_SIZE_MASK)
213 == Configuration.SCREENLAYOUT_SIZE_XLARGE;
214
Leon Scroggins81db3662009-06-04 17:45:11 -0400215 FrameLayout frameLayout = (FrameLayout) getWindow().getDecorView()
216 .findViewById(com.android.internal.R.id.content);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400217 mBrowserFrameLayout = (FrameLayout) LayoutInflater.from(this)
218 .inflate(R.layout.custom_screen, null);
219 mContentView = (FrameLayout) mBrowserFrameLayout.findViewById(
220 R.id.main_content);
221 mErrorConsoleContainer = (LinearLayout) mBrowserFrameLayout
222 .findViewById(R.id.error_console);
223 mCustomViewContainer = (FrameLayout) mBrowserFrameLayout
224 .findViewById(R.id.fullscreen_custom_content);
225 frameLayout.addView(mBrowserFrameLayout, COVER_SCREEN_PARAMS);
Michael Kolbe0a36662010-06-29 10:37:12 -0700226
Leon Scrogginsd746a942010-05-19 13:21:44 -0400227 if (mXLargeScreenSize) {
Michael Kolba2b2ba82010-08-04 17:54:03 -0700228 mTitleBar = new TitleBarXLarge(this);
229 mTitleBar.setProgress(100);
230 mFakeTitleBar = new TitleBarXLarge(this);
Michael Kolbed217742010-08-10 17:52:34 -0700231 ActionBar actionBar = getActionBar();
Michael Kolba2b2ba82010-08-04 17:54:03 -0700232 mTabBar = new TabBar(this, mTabControl, (TitleBarXLarge) mFakeTitleBar);
Michael Kolbed217742010-08-10 17:52:34 -0700233 actionBar.setCustomNavigationMode(mTabBar);
Leon Scrogginsd746a942010-05-19 13:21:44 -0400234 } else {
Leon Scroggins571b3762010-05-26 10:25:01 -0400235 mTitleBar = new TitleBar(this);
Leon Scrogginsd746a942010-05-19 13:21:44 -0400236 // mTitleBar will be always be shown in the fully loaded mode on
237 // phone
238 mTitleBar.setProgress(100);
Leon Scrogginsd746a942010-05-19 13:21:44 -0400239 mFakeTitleBar = new TitleBar(this);
240 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800241
The Android Open Source Project0c908882009-03-03 19:32:16 -0800242 // Open the icon database and retain all the bookmark urls for favicons
243 retainIconsOnStartup();
244
245 // Keep a settings instance handy.
246 mSettings = BrowserSettings.getInstance();
247 mSettings.setTabControl(mTabControl);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800248
249 PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
250 mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Browser");
251
Patrick Scott6adacc92010-03-05 08:24:51 -0500252 // Find out if the network is currently up.
253 ConnectivityManager cm = (ConnectivityManager) getSystemService(
254 Context.CONNECTIVITY_SERVICE);
255 NetworkInfo info = cm.getActiveNetworkInfo();
256 if (info != null) {
257 mIsNetworkUp = info.isAvailable();
258 }
259
Grace Klobaa34f6862009-07-31 16:28:17 -0700260 /* enables registration for changes in network status from
261 http stack */
262 mNetworkStateChangedFilter = new IntentFilter();
263 mNetworkStateChangedFilter.addAction(
264 ConnectivityManager.CONNECTIVITY_ACTION);
265 mNetworkStateIntentReceiver = new BroadcastReceiver() {
266 @Override
267 public void onReceive(Context context, Intent intent) {
268 if (intent.getAction().equals(
269 ConnectivityManager.CONNECTIVITY_ACTION)) {
Andrei Popescue4c98462010-02-19 15:44:13 +0000270
271 NetworkInfo info = intent.getParcelableExtra(
272 ConnectivityManager.EXTRA_NETWORK_INFO);
273 String typeName = info.getTypeName();
274 String subtypeName = info.getSubtypeName();
275 sendNetworkType(typeName.toLowerCase(),
276 (subtypeName != null ? subtypeName.toLowerCase() : ""));
277
278 onNetworkToggle(info.isAvailable());
Grace Klobaa34f6862009-07-31 16:28:17 -0700279 }
280 }
281 };
282
Grace Kloba615c6c92009-08-03 10:22:44 -0700283 IntentFilter filter = new IntentFilter(Intent.ACTION_PACKAGE_ADDED);
284 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
285 filter.addDataScheme("package");
286 mPackageInstallationReceiver = new BroadcastReceiver() {
287 @Override
288 public void onReceive(Context context, Intent intent) {
289 final String action = intent.getAction();
290 final String packageName = intent.getData()
291 .getSchemeSpecificPart();
292 final boolean replacing = intent.getBooleanExtra(
293 Intent.EXTRA_REPLACING, false);
294 if (Intent.ACTION_PACKAGE_REMOVED.equals(action) && replacing) {
295 // if it is replacing, refreshPlugins() when adding
296 return;
297 }
Andrei Popescu30995e72010-02-09 16:59:58 +0000298
299 if (sGoogleApps.contains(packageName)) {
300 BrowserActivity.this.packageChanged(packageName,
301 Intent.ACTION_PACKAGE_ADDED.equals(action));
302 }
303
Grace Kloba615c6c92009-08-03 10:22:44 -0700304 PackageManager pm = BrowserActivity.this.getPackageManager();
305 PackageInfo pkgInfo = null;
306 try {
307 pkgInfo = pm.getPackageInfo(packageName,
308 PackageManager.GET_PERMISSIONS);
309 } catch (PackageManager.NameNotFoundException e) {
310 return;
311 }
312 if (pkgInfo != null) {
313 String permissions[] = pkgInfo.requestedPermissions;
314 if (permissions == null) {
315 return;
316 }
317 boolean permissionOk = false;
318 for (String permit : permissions) {
319 if (PluginManager.PLUGIN_PERMISSION.equals(permit)) {
320 permissionOk = true;
321 break;
322 }
323 }
324 if (permissionOk) {
325 PluginManager.getInstance(BrowserActivity.this)
Grace Klobae56a0f22010-05-26 17:31:02 -0700326 .refreshPlugins(true);
Grace Kloba615c6c92009-08-03 10:22:44 -0700327 }
328 }
329 }
330 };
331 registerReceiver(mPackageInstallationReceiver, filter);
332
The Android Open Source Project0c908882009-03-03 19:32:16 -0800333 if (!mTabControl.restoreState(icicle)) {
334 // clear up the thumbnail directory if we can't restore the state as
335 // none of the files in the directory are referenced any more.
336 new ClearThumbnails().execute(
337 mTabControl.getThumbnailDir().listFiles());
Grace Klobaaab3f092009-07-30 12:29:51 -0700338 // there is no quit on Android. But if we can't restore the state,
339 // we can treat it as a new Browser, remove the old session cookies.
340 CookieManager.getInstance().removeSessionCookie();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800341 final Intent intent = getIntent();
342 final Bundle extra = intent.getExtras();
343 // Create an initial tab.
344 // If the intent is ACTION_VIEW and data is not null, the Browser is
345 // invoked to view the content by another application. In this case,
346 // the tab will be close when exit.
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700347 UrlData urlData = getUrlDataFromIntent(intent);
348
Leon Scroggins58d56c62010-01-28 15:12:40 -0500349 String action = intent.getAction();
Grace Kloba22ac16e2009-10-07 18:00:23 -0700350 final Tab t = mTabControl.createNewTab(
Leon Scroggins58d56c62010-01-28 15:12:40 -0500351 (Intent.ACTION_VIEW.equals(action) &&
352 intent.getData() != null)
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -0500353 || RecognizerResultsIntent.ACTION_VOICE_SEARCH_RESULTS
354 .equals(action),
Elliott Slaughterf0f03952010-07-14 18:10:36 -0700355 intent.getStringExtra(Browser.EXTRA_APPLICATION_ID),
356 urlData.mUrl, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800357 mTabControl.setCurrentTab(t);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800358 attachTabToContentView(t);
359 WebView webView = t.getWebView();
360 if (extra != null) {
361 int scale = extra.getInt(Browser.INITIAL_ZOOM_LEVEL, 0);
362 if (scale > 0 && scale <= 1000) {
363 webView.setInitialScale(scale);
364 }
365 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800366
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700367 if (urlData.isEmpty()) {
Shimeng (Simon) Wang98d5fce2010-03-16 13:23:39 -0700368 loadUrl(webView, mSettings.getHomePage());
The Android Open Source Project0c908882009-03-03 19:32:16 -0800369 } else {
Patrick Scott9d53da02010-02-19 10:19:01 -0500370 loadUrlDataIn(t, urlData);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800371 }
372 } else {
373 // TabControl.restoreState() will create a new tab even if
Leon Scroggins1f005d32009-08-10 17:36:42 -0400374 // restoring the state fails.
The Android Open Source Project0c908882009-03-03 19:32:16 -0800375 attachTabToContentView(mTabControl.getCurrentTab());
376 }
Grace Kloba615c6c92009-08-03 10:22:44 -0700377
Cary Clarkb4b83182010-07-01 12:36:56 -0400378 // Delete old thumbnails to save space
379 File dir = mTabControl.getThumbnailDir();
380 if (dir.exists()) {
381 for (String child : dir.list()) {
382 File f = new File(dir, child);
383 f.delete();
384 }
385 }
386
Feng Qianb3c02da2009-06-29 15:58:08 -0700387 // Read JavaScript flags if it exists.
388 String jsFlags = mSettings.getJsFlags();
389 if (jsFlags.trim().length() != 0) {
390 mTabControl.getCurrentWebView().setJsFlags(jsFlags);
391 }
Andrei Popescu30995e72010-02-09 16:59:58 +0000392 // Work out which packages are installed on the system.
393 getInstalledPackages();
Bjorn Bringerta7611812010-03-24 11:12:02 +0000394
395 // Start watching the default geolocation permissions
396 mSystemAllowGeolocationOrigins
397 = new SystemAllowGeolocationOrigins(getApplicationContext());
398 mSystemAllowGeolocationOrigins.start();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800399 }
400
Michael Kolba2b2ba82010-08-04 17:54:03 -0700401 ScrollListener getScrollListener() {
402 return mTabBar;
403 }
404
Leon Scroggins58d56c62010-01-28 15:12:40 -0500405 /**
406 * Feed the previously stored results strings to the BrowserProvider so that
407 * the SearchDialog will show them instead of the standard searches.
408 * @param result String to show on the editable line of the SearchDialog.
409 */
410 /* package */ void showVoiceSearchResults(String result) {
411 ContentProviderClient client = mResolver.acquireContentProviderClient(
412 Browser.BOOKMARKS_URI);
413 ContentProvider prov = client.getLocalContentProvider();
414 BrowserProvider bp = (BrowserProvider) prov;
415 bp.setQueryResults(mTabControl.getCurrentTab().getVoiceSearchResults());
416 client.release();
417
Leon Scrogginsfbb3f152010-03-09 17:26:56 -0500418 Bundle bundle = createGoogleSearchSourceBundle(
419 GOOGLE_SEARCH_SOURCE_SEARCHKEY);
420 bundle.putBoolean(SearchManager.CONTEXT_IS_VOICE, true);
421 startSearch(result, false, bundle, false);
Leon Scroggins58d56c62010-01-28 15:12:40 -0500422 }
423
The Android Open Source Project0c908882009-03-03 19:32:16 -0800424 @Override
425 protected void onNewIntent(Intent intent) {
Grace Kloba22ac16e2009-10-07 18:00:23 -0700426 Tab current = mTabControl.getCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800427 // When a tab is closed on exit, the current tab index is set to -1.
428 // Reset before proceed as Browser requires the current tab to be set.
429 if (current == null) {
430 // Try to reset the tab in case the index was incorrect.
431 current = mTabControl.getTab(0);
432 if (current == null) {
433 // No tabs at all so just ignore this intent.
434 return;
435 }
436 mTabControl.setCurrentTab(current);
437 attachTabToContentView(current);
438 resetTitleAndIcon(current.getWebView());
439 }
440 final String action = intent.getAction();
441 final int flags = intent.getFlags();
442 if (Intent.ACTION_MAIN.equals(action) ||
443 (flags & Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY) != 0) {
444 // just resume the browser
445 return;
446 }
Leon Scrogginsb8a844d2010-03-18 15:06:15 -0400447 // In case the SearchDialog is open.
448 ((SearchManager) getSystemService(Context.SEARCH_SERVICE))
449 .stopSearch();
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -0500450 boolean activateVoiceSearch = RecognizerResultsIntent
451 .ACTION_VOICE_SEARCH_RESULTS.equals(action);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800452 if (Intent.ACTION_VIEW.equals(action)
453 || Intent.ACTION_SEARCH.equals(action)
454 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
Leon Scroggins58d56c62010-01-28 15:12:40 -0500455 || Intent.ACTION_WEB_SEARCH.equals(action)
456 || activateVoiceSearch) {
Leon Scroggins3b18ce32010-02-08 17:35:59 -0500457 if (current.isInVoiceSearchMode()) {
458 String title = current.getVoiceDisplayTitle();
459 if (title != null && title.equals(intent.getStringExtra(
460 SearchManager.QUERY))) {
461 // The user submitted the same search as the last voice
462 // search, so do nothing.
463 return;
464 }
Leon Scroggins1fe13a52010-02-09 15:31:26 -0500465 if (Intent.ACTION_SEARCH.equals(action)
466 && current.voiceSearchSourceIsGoogle()) {
467 Intent logIntent = new Intent(
468 LoggingEvents.ACTION_LOG_EVENT);
469 logIntent.putExtra(LoggingEvents.EXTRA_EVENT,
470 LoggingEvents.VoiceSearch.QUERY_UPDATED);
471 logIntent.putExtra(
472 LoggingEvents.VoiceSearch.EXTRA_QUERY_UPDATED_VALUE,
473 intent.getDataString());
474 sendBroadcast(logIntent);
475 // Note, onPageStarted will revert the voice title bar
476 // When http://b/issue?id=2379215 is fixed, we should update
477 // the title bar here.
478 }
Leon Scroggins3b18ce32010-02-08 17:35:59 -0500479 }
Satish Sampath565505b2009-05-29 15:37:27 +0100480 // If this was a search request (e.g. search query directly typed into the address bar),
481 // pass it on to the default web search provider.
482 if (handleWebSearchIntent(intent)) {
483 return;
484 }
485
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700486 UrlData urlData = getUrlDataFromIntent(intent);
487 if (urlData.isEmpty()) {
488 urlData = new UrlData(mSettings.getHomePage());
The Android Open Source Project0c908882009-03-03 19:32:16 -0800489 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700490
Grace Klobacc634032009-07-28 15:58:19 -0700491 final String appId = intent
492 .getStringExtra(Browser.EXTRA_APPLICATION_ID);
Leon Scroggins47208682010-04-07 17:59:48 -0400493 if ((Intent.ACTION_VIEW.equals(action)
494 // If a voice search has no appId, it means that it came
495 // from the browser. In that case, reuse the current tab.
496 || (activateVoiceSearch && appId != null))
Grace Klobacc634032009-07-28 15:58:19 -0700497 && !getPackageName().equals(appId)
498 && (flags & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0) {
Grace Kloba22ac16e2009-10-07 18:00:23 -0700499 Tab appTab = mTabControl.getTabFromId(appId);
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700500 if (appTab != null) {
501 Log.i(LOGTAG, "Reusing tab for " + appId);
502 // Dismiss the subwindow if applicable.
503 dismissSubWindow(appTab);
504 // Since we might kill the WebView, remove it from the
505 // content view first.
506 removeTabFromContentView(appTab);
507 // Recreate the main WebView after destroying the old one.
508 // If the WebView has the same original url and is on that
509 // page, it can be reused.
510 boolean needsLoad =
Leon Scroggins6eac63e2010-03-15 18:19:14 -0400511 mTabControl.recreateWebView(appTab, urlData);
Ben Murdochbff2d602009-07-01 20:19:05 +0100512
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700513 if (current != appTab) {
Leon Scroggins1f005d32009-08-10 17:36:42 -0400514 switchToTab(mTabControl.getTabIndex(appTab));
515 if (needsLoad) {
Patrick Scott9d53da02010-02-19 10:19:01 -0500516 loadUrlDataIn(appTab, urlData);
Leon Scroggins1f005d32009-08-10 17:36:42 -0400517 }
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700518 } else {
Leon Scroggins1f005d32009-08-10 17:36:42 -0400519 // If the tab was the current tab, we have to attach
520 // it to the view system again.
521 attachTabToContentView(appTab);
522 if (needsLoad) {
Patrick Scott9d53da02010-02-19 10:19:01 -0500523 loadUrlDataIn(appTab, urlData);
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700524 }
525 }
526 return;
Patrick Scottcd115892009-07-16 09:42:58 -0400527 } else {
528 // No matching application tab, try to find a regular tab
529 // with a matching url.
530 appTab = mTabControl.findUnusedTabWithUrl(urlData.mUrl);
Leon Scroggins25515f82009-08-19 15:31:58 -0400531 if (appTab != null) {
532 if (current != appTab) {
533 switchToTab(mTabControl.getTabIndex(appTab));
534 }
535 // Otherwise, we are already viewing the correct tab.
Patrick Scottcd115892009-07-16 09:42:58 -0400536 } else {
537 // if FLAG_ACTIVITY_BROUGHT_TO_FRONT flag is on, the url
538 // will be opened in a new tab unless we have reached
539 // MAX_TABS. Then the url will be opened in the current
540 // tab. If a new tab is created, it will have "true" for
541 // exit on close.
Leon Scroggins1f005d32009-08-10 17:36:42 -0400542 openTabAndShow(urlData, true, appId);
Patrick Scottcd115892009-07-16 09:42:58 -0400543 }
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700544 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800545 } else {
Grace Kloba638d3f42009-11-23 10:35:04 -0800546 if (!urlData.isEmpty()
547 && urlData.mUrl.startsWith("about:debug")) {
548 if ("about:debug.dom".equals(urlData.mUrl)) {
549 current.getWebView().dumpDomTree(false);
550 } else if ("about:debug.dom.file".equals(urlData.mUrl)) {
551 current.getWebView().dumpDomTree(true);
552 } else if ("about:debug.render".equals(urlData.mUrl)) {
553 current.getWebView().dumpRenderTree(false);
554 } else if ("about:debug.render.file".equals(urlData.mUrl)) {
555 current.getWebView().dumpRenderTree(true);
556 } else if ("about:debug.display".equals(urlData.mUrl)) {
557 current.getWebView().dumpDisplayTree();
Mike Reed9b78e1d2010-01-13 14:40:52 -0800558 } else if (urlData.mUrl.startsWith("about:debug.drag")) {
559 int index = urlData.mUrl.codePointAt(16) - '0';
560 if (index <= 0 || index > 9) {
561 current.getWebView().setDragTracker(null);
562 } else {
563 current.getWebView().setDragTracker(new MeshTracker(index));
564 }
Grace Kloba638d3f42009-11-23 10:35:04 -0800565 } else {
566 mSettings.toggleDebugSettings();
567 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800568 return;
569 }
Leon Scroggins1f005d32009-08-10 17:36:42 -0400570 // Get rid of the subwindow if it exists
571 dismissSubWindow(current);
Leon Scroggins8588d152010-04-15 11:01:53 -0400572 // If the current Tab is being used as an application tab,
573 // remove the association, since the new Intent means that it is
574 // no longer associated with that application.
575 current.setAppId(null);
Patrick Scott9d53da02010-02-19 10:19:01 -0500576 loadUrlDataIn(current, urlData);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800577 }
578 }
579 }
580
Satish Sampath565505b2009-05-29 15:37:27 +0100581 private int parseUrlShortcut(String url) {
582 if (url == null) return SHORTCUT_INVALID;
583
584 // FIXME: quick search, need to be customized by setting
585 if (url.length() > 2 && url.charAt(1) == ' ') {
586 switch (url.charAt(0)) {
587 case 'g': return SHORTCUT_GOOGLE_SEARCH;
588 case 'w': return SHORTCUT_WIKIPEDIA_SEARCH;
589 case 'd': return SHORTCUT_DICTIONARY_SEARCH;
590 case 'l': return SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH;
591 }
592 }
593 return SHORTCUT_INVALID;
594 }
595
596 /**
597 * Launches the default web search activity with the query parameters if the given intent's data
598 * are identified as plain search terms and not URLs/shortcuts.
599 * @return true if the intent was handled and web search activity was launched, false if not.
600 */
601 private boolean handleWebSearchIntent(Intent intent) {
602 if (intent == null) return false;
603
604 String url = null;
605 final String action = intent.getAction();
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -0500606 if (RecognizerResultsIntent.ACTION_VOICE_SEARCH_RESULTS.equals(
607 action)) {
Leon Scroggins58d56c62010-01-28 15:12:40 -0500608 return false;
609 }
Satish Sampath565505b2009-05-29 15:37:27 +0100610 if (Intent.ACTION_VIEW.equals(action)) {
Grace Kloba1e705052009-09-29 13:13:36 -0700611 Uri data = intent.getData();
612 if (data != null) url = data.toString();
Satish Sampath565505b2009-05-29 15:37:27 +0100613 } else if (Intent.ACTION_SEARCH.equals(action)
614 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
615 || Intent.ACTION_WEB_SEARCH.equals(action)) {
616 url = intent.getStringExtra(SearchManager.QUERY);
617 }
Bjorn Bringert04851702009-09-22 10:36:01 +0100618 return handleWebSearchRequest(url, intent.getBundleExtra(SearchManager.APP_DATA),
619 intent.getStringExtra(SearchManager.EXTRA_DATA_KEY));
Satish Sampath565505b2009-05-29 15:37:27 +0100620 }
621
622 /**
623 * Launches the default web search activity with the query parameters if the given url string
624 * was identified as plain search terms and not URL/shortcut.
625 * @return true if the request was handled and web search activity was launched, false if not.
626 */
Bjorn Bringert04851702009-09-22 10:36:01 +0100627 private boolean handleWebSearchRequest(String inUrl, Bundle appData, String extraData) {
Satish Sampath565505b2009-05-29 15:37:27 +0100628 if (inUrl == null) return false;
629
630 // In general, we shouldn't modify URL from Intent.
631 // But currently, we get the user-typed URL from search box as well.
632 String url = fixUrl(inUrl).trim();
633
634 // URLs and site specific search shortcuts are handled by the regular flow of control, so
635 // return early.
Dan Egnor5ee906c2009-11-18 12:11:49 -0800636 if (Patterns.WEB_URL.matcher(url).matches()
Satish Sampathbc5b9f32009-06-04 18:21:40 +0100637 || ACCEPTED_URI_SCHEMA.matcher(url).matches()
Satish Sampath565505b2009-05-29 15:37:27 +0100638 || parseUrlShortcut(url) != SHORTCUT_INVALID) {
639 return false;
640 }
641
Leon Scroggins8d06e362010-03-24 14:45:57 -0400642 final ContentResolver cr = mResolver;
643 final String newUrl = url;
Elliott Slaughter627d96f2010-08-18 16:35:30 -0700644 if (mTabControl == null || !mTabControl.getCurrentWebView().isPrivateBrowsingEnabled()) {
Elliott Slaughterf0f03952010-07-14 18:10:36 -0700645 new AsyncTask<Void, Void, Void>() {
646 @Override
647 protected Void doInBackground(Void... unused) {
648 Browser.updateVisitedHistory(cr, newUrl, false);
649 Browser.addSearchUrl(cr, newUrl);
650 return null;
651 }
652 }.execute();
653 }
Satish Sampath565505b2009-05-29 15:37:27 +0100654
655 Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);
656 intent.addCategory(Intent.CATEGORY_DEFAULT);
657 intent.putExtra(SearchManager.QUERY, url);
Satish Sampath15e9f2d2009-06-23 22:29:49 +0100658 if (appData != null) {
659 intent.putExtra(SearchManager.APP_DATA, appData);
660 }
Bjorn Bringert04851702009-09-22 10:36:01 +0100661 if (extraData != null) {
662 intent.putExtra(SearchManager.EXTRA_DATA_KEY, extraData);
663 }
Grace Klobacc634032009-07-28 15:58:19 -0700664 intent.putExtra(Browser.EXTRA_APPLICATION_ID, getPackageName());
Satish Sampath565505b2009-05-29 15:37:27 +0100665 startActivity(intent);
666
667 return true;
668 }
669
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700670 private UrlData getUrlDataFromIntent(Intent intent) {
Leon Scroggins58d56c62010-01-28 15:12:40 -0500671 String url = "";
Grace Kloba068e48b2010-01-26 18:11:27 -0800672 Map<String, String> headers = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800673 if (intent != null) {
674 final String action = intent.getAction();
675 if (Intent.ACTION_VIEW.equals(action)) {
676 url = smartUrlFilter(intent.getData());
677 if (url != null && url.startsWith("content:")) {
678 /* Append mimetype so webview knows how to display */
679 String mimeType = intent.resolveType(getContentResolver());
680 if (mimeType != null) {
681 url += "?" + mimeType;
682 }
683 }
Grace Kloba068e48b2010-01-26 18:11:27 -0800684 if (url != null && url.startsWith("http")) {
Grace Kloba00f54c52010-01-27 14:53:51 -0800685 final Bundle pairs = intent
686 .getBundleExtra(Browser.EXTRA_HEADERS);
Grace Kloba2d508ed2010-01-28 11:39:15 -0800687 if (pairs != null && !pairs.isEmpty()) {
Grace Kloba00f54c52010-01-27 14:53:51 -0800688 Iterator<String> iter = pairs.keySet().iterator();
Grace Kloba068e48b2010-01-26 18:11:27 -0800689 headers = new HashMap<String, String>();
Grace Kloba00f54c52010-01-27 14:53:51 -0800690 while (iter.hasNext()) {
691 String key = iter.next();
692 headers.put(key, pairs.getString(key));
Grace Kloba068e48b2010-01-26 18:11:27 -0800693 }
694 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700695 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800696 } else if (Intent.ACTION_SEARCH.equals(action)
697 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
698 || Intent.ACTION_WEB_SEARCH.equals(action)) {
699 url = intent.getStringExtra(SearchManager.QUERY);
700 if (url != null) {
701 mLastEnteredUrl = url;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800702 // In general, we shouldn't modify URL from Intent.
703 // But currently, we get the user-typed URL from search box as well.
704 url = fixUrl(url);
705 url = smartUrlFilter(url);
Leon Scroggins8d06e362010-03-24 14:45:57 -0400706 final ContentResolver cr = mResolver;
707 final String newUrl = url;
708 new AsyncTask<Void, Void, Void>() {
Michael Kolbe0a36662010-06-29 10:37:12 -0700709 @Override
Leon Scroggins8d06e362010-03-24 14:45:57 -0400710 protected Void doInBackground(Void... unused) {
711 Browser.updateVisitedHistory(cr, newUrl, false);
712 return null;
713 }
714 }.execute();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800715 String searchSource = "&source=android-" + GOOGLE_SEARCH_SOURCE_SUGGEST + "&";
716 if (url.contains(searchSource)) {
717 String source = null;
718 final Bundle appData = intent.getBundleExtra(SearchManager.APP_DATA);
719 if (appData != null) {
Bjorn Bringert10d1cca2010-02-10 14:22:12 +0000720 source = appData.getString(Search.SOURCE);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800721 }
722 if (TextUtils.isEmpty(source)) {
723 source = GOOGLE_SEARCH_SOURCE_UNKNOWN;
724 }
725 url = url.replace(searchSource, "&source=android-"+source+"&");
726 }
727 }
728 }
729 }
Leon Scroggins58d56c62010-01-28 15:12:40 -0500730 return new UrlData(url, headers, intent);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800731 }
Leon Scroggins58d56c62010-01-28 15:12:40 -0500732 /* package */ void showVoiceTitleBar(String title) {
733 mTitleBar.setInVoiceMode(true);
Leon Scroggins58d56c62010-01-28 15:12:40 -0500734 mTitleBar.setDisplayTitle(title);
Michael Kolba2b2ba82010-08-04 17:54:03 -0700735 mFakeTitleBar.setInVoiceMode(true);
736 mFakeTitleBar.setDisplayTitle(title);
Leon Scroggins58d56c62010-01-28 15:12:40 -0500737 }
738 /* package */ void revertVoiceTitleBar() {
739 mTitleBar.setInVoiceMode(false);
Leon Scroggins003a5dd2010-03-10 12:13:14 -0500740 mTitleBar.setDisplayTitle(mUrl);
Michael Kolba2b2ba82010-08-04 17:54:03 -0700741 mFakeTitleBar.setInVoiceMode(false);
742 mFakeTitleBar.setDisplayTitle(mUrl);
Leon Scroggins58d56c62010-01-28 15:12:40 -0500743 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800744 /* package */ static String fixUrl(String inUrl) {
Cary Clark652ff872009-09-10 13:34:44 -0400745 // FIXME: Converting the url to lower case
746 // duplicates functionality in smartUrlFilter().
747 // However, changing all current callers of fixUrl to
748 // call smartUrlFilter in addition may have unwanted
749 // consequences, and is deferred for now.
750 int colon = inUrl.indexOf(':');
751 boolean allLower = true;
752 for (int index = 0; index < colon; index++) {
753 char ch = inUrl.charAt(index);
754 if (!Character.isLetter(ch)) {
755 break;
756 }
757 allLower &= Character.isLowerCase(ch);
758 if (index == colon - 1 && !allLower) {
759 inUrl = inUrl.substring(0, colon).toLowerCase()
760 + inUrl.substring(colon);
761 }
762 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800763 if (inUrl.startsWith("http://") || inUrl.startsWith("https://"))
764 return inUrl;
765 if (inUrl.startsWith("http:") ||
766 inUrl.startsWith("https:")) {
767 if (inUrl.startsWith("http:/") || inUrl.startsWith("https:/")) {
768 inUrl = inUrl.replaceFirst("/", "//");
769 } else inUrl = inUrl.replaceFirst(":", "://");
770 }
771 return inUrl;
772 }
773
Grace Kloba22ac16e2009-10-07 18:00:23 -0700774 @Override
775 protected void onResume() {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800776 super.onResume();
Dave Bort31a6d1c2009-04-13 15:56:49 -0700777 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800778 Log.v(LOGTAG, "BrowserActivity.onResume: this=" + this);
779 }
780
781 if (!mActivityInPause) {
782 Log.e(LOGTAG, "BrowserActivity is already resumed.");
783 return;
784 }
785
Mike Reed7bfa63b2009-05-28 11:08:32 -0400786 mTabControl.resumeCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800787 mActivityInPause = false;
Mike Reed7bfa63b2009-05-28 11:08:32 -0400788 resumeWebViewTimers();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800789
790 if (mWakeLock.isHeld()) {
791 mHandler.removeMessages(RELEASE_WAKELOCK);
792 mWakeLock.release();
793 }
794
The Android Open Source Project0c908882009-03-03 19:32:16 -0800795 registerReceiver(mNetworkStateIntentReceiver,
796 mNetworkStateChangedFilter);
797 WebView.enablePlatformNotifications();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800798 }
799
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400800 /**
801 * Since the actual title bar is embedded in the WebView, and removing it
Leon Scrogginsfe87bd32009-10-06 10:10:00 -0400802 * would change its appearance, use a different TitleBar to show overlayed
803 * at the top of the screen, when the menu is open or the page is loading.
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400804 */
Michael Kolba2b2ba82010-08-04 17:54:03 -0700805 private TitleBarBase mFakeTitleBar;
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400806
807 /**
808 * Keeps track of whether the options menu is open. This is important in
809 * determining whether to show or hide the title bar overlay.
810 */
811 private boolean mOptionsMenuOpen;
812
813 /**
814 * Only meaningful when mOptionsMenuOpen is true. This variable keeps track
815 * of whether the configuration has changed. The first onMenuOpened call
816 * after a configuration change is simply a reopening of the same menu
817 * (i.e. mIconView did not change).
818 */
819 private boolean mConfigChanged;
820
821 /**
822 * Whether or not the options menu is in its smaller, icon menu form. When
823 * true, we want the title bar overlay to be up. When false, we do not.
824 * Only meaningful if mOptionsMenuOpen is true.
825 */
826 private boolean mIconView;
827
Leon Scrogginsa81a7642009-08-31 17:05:41 -0400828 @Override
829 public boolean onMenuOpened(int featureId, Menu menu) {
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400830 if (Window.FEATURE_OPTIONS_PANEL == featureId) {
831 if (mOptionsMenuOpen) {
832 if (mConfigChanged) {
833 // We do not need to make any changes to the state of the
834 // title bar, since the only thing that happened was a
835 // change in orientation
836 mConfigChanged = false;
837 } else {
838 if (mIconView) {
839 // Switching the menu to expanded view, so hide the
840 // title bar.
841 hideFakeTitleBar();
842 mIconView = false;
843 } else {
844 // Switching the menu back to icon view, so show the
845 // title bar once again.
846 showFakeTitleBar();
847 mIconView = true;
848 }
849 }
850 } else {
851 // The options menu is closed, so open it, and show the title
852 showFakeTitleBar();
853 mOptionsMenuOpen = true;
854 mConfigChanged = false;
855 mIconView = true;
856 }
857 }
Leon Scrogginsa81a7642009-08-31 17:05:41 -0400858 return true;
859 }
860
Michael Kolba2b2ba82010-08-04 17:54:03 -0700861 void showFakeTitleBar() {
862 if (!isFakeTitleBarShowing() && mActiveTabsPage == null && !mActivityInPause) {
Grace Kloba847c25b2010-03-30 16:00:26 -0700863 WebView mainView = mTabControl.getCurrentWebView();
864 // if there is no current WebView, don't show the faked title bar;
Grace Kloba65190702010-04-02 23:37:26 -0700865 if (mainView == null) {
Cary Clarka0464552009-09-29 13:00:45 -0400866 return;
867 }
Leon Scroggins79e36d92010-04-29 16:01:46 +0100868 // Do not need to check for null, since the current tab will have
869 // at least a main WebView, or we would have returned above.
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -0400870 if (isInCustomActionMode()) {
871 // Do not show the fake title bar, while a custom ActionMode
872 // (i.e. find or select) is showing.
Leon Scroggins79e36d92010-04-29 16:01:46 +0100873 return;
874 }
Michael Kolba2b2ba82010-08-04 17:54:03 -0700875 if (mXLargeScreenSize) {
876 mContentView.addView(mFakeTitleBar);
877 mTabBar.onShowTitleBar();
878 } else {
879 WindowManager manager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400880
Michael Kolba2b2ba82010-08-04 17:54:03 -0700881 // Add the title bar to the window manager so it can receive
882 // touches
883 // while the menu is up
884 WindowManager.LayoutParams params =
885 new WindowManager.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
886 ViewGroup.LayoutParams.WRAP_CONTENT,
887 WindowManager.LayoutParams.TYPE_APPLICATION,
888 WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
889 PixelFormat.TRANSLUCENT);
890 params.gravity = Gravity.TOP;
891 boolean atTop = mainView.getScrollY() == 0;
892 params.windowAnimations = atTop ? 0 : R.style.TitleBar;
893 manager.addView(mFakeTitleBar, params);
894 }
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400895 }
896 }
897
898 @Override
899 public void onOptionsMenuClosed(Menu menu) {
900 mOptionsMenuOpen = false;
Leon Scrogginsa27ff192009-09-14 12:58:04 -0400901 if (!mInLoad) {
902 hideFakeTitleBar();
903 } else if (!mIconView) {
904 // The page is currently loading, and we are in expanded mode, so
905 // we were not showing the menu. Show it once again. It will be
906 // removed when the page finishes.
907 showFakeTitleBar();
908 }
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400909 }
Grace Kloba22ac16e2009-10-07 18:00:23 -0700910
Michael Kolba2b2ba82010-08-04 17:54:03 -0700911 void stopScrolling() {
912 ((ScrollWebView) mTabControl.getCurrentWebView()).stopScroll();
913 }
914
915 void hideFakeTitleBar() {
916 if (!isFakeTitleBarShowing()) return;
917 if (mXLargeScreenSize) {
918 mContentView.removeView(mFakeTitleBar);
919 mTabBar.onHideTitleBar();
920 } else {
921 WindowManager.LayoutParams params =
922 (WindowManager.LayoutParams) mFakeTitleBar.getLayoutParams();
923 WebView mainView = mTabControl.getCurrentWebView();
924 // Although we decided whether or not to animate based on the
925 // current
926 // scroll position, the scroll position may have changed since the
927 // fake title bar was displayed. Make sure it has the appropriate
928 // animation/lack thereof before removing.
929 params.windowAnimations =
930 mainView != null && mainView.getScrollY() == 0 ? 0 : R.style.TitleBar;
931 WindowManager manager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
932 manager.updateViewLayout(mFakeTitleBar, params);
933 manager.removeView(mFakeTitleBar);
934 }
935 }
936
937 boolean isFakeTitleBarShowing() {
938 return (mFakeTitleBar.getParent() != null);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400939 }
940
The Android Open Source Project0c908882009-03-03 19:32:16 -0800941 /**
Leon Scrogginsc6fa1102009-09-21 10:40:01 -0400942 * Special method for the fake title bar to call when displaying its context
943 * menu, since it is in its own Window, and its parent does not show a
944 * context menu.
945 */
946 /* package */ void showTitleBarContextMenu() {
Cary Clark65f4a3c2009-09-28 17:05:06 -0400947 if (null == mTitleBar.getParent()) {
948 return;
949 }
Leon Scrogginsc6fa1102009-09-21 10:40:01 -0400950 openContextMenu(mTitleBar);
951 }
952
Leon Scrogginsb2b19f52009-10-09 16:10:00 -0400953 @Override
954 public void onContextMenuClosed(Menu menu) {
955 super.onContextMenuClosed(menu);
956 if (mInLoad) {
957 showFakeTitleBar();
958 }
959 }
960
Leon Scrogginsc6fa1102009-09-21 10:40:01 -0400961 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -0800962 * onSaveInstanceState(Bundle map)
963 * onSaveInstanceState is called right before onStop(). The map contains
964 * the saved state.
965 */
Grace Kloba22ac16e2009-10-07 18:00:23 -0700966 @Override
967 protected void onSaveInstanceState(Bundle outState) {
Dave Bort31a6d1c2009-04-13 15:56:49 -0700968 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800969 Log.v(LOGTAG, "BrowserActivity.onSaveInstanceState: this=" + this);
970 }
971 // the default implementation requires each view to have an id. As the
972 // browser handles the state itself and it doesn't use id for the views,
973 // don't call the default implementation. Otherwise it will trigger the
974 // warning like this, "couldn't save which view has focus because the
975 // focused view XXX has no id".
976
977 // Save all the tabs
978 mTabControl.saveState(outState);
979 }
980
Grace Kloba22ac16e2009-10-07 18:00:23 -0700981 @Override
982 protected void onPause() {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800983 super.onPause();
984
985 if (mActivityInPause) {
986 Log.e(LOGTAG, "BrowserActivity is already paused.");
987 return;
988 }
989
Mike Reed7bfa63b2009-05-28 11:08:32 -0400990 mTabControl.pauseCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800991 mActivityInPause = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -0400992 if (mTabControl.getCurrentIndex() >= 0 && !pauseWebViewTimers()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800993 mWakeLock.acquire();
994 mHandler.sendMessageDelayed(mHandler
995 .obtainMessage(RELEASE_WAKELOCK), WAKELOCK_TIMEOUT);
996 }
997
Leon Scrogginsa2ab6a72009-09-11 11:49:52 -0400998 // FIXME: This removes the active tabs page and resets the menu to
999 // MAIN_MENU. A better solution might be to do this work in onNewIntent
1000 // but then we would need to save it in onSaveInstanceState and restore
1001 // it in onCreate/onRestoreInstanceState
1002 if (mActiveTabsPage != null) {
1003 removeActiveTabPage(true);
1004 }
1005
The Android Open Source Project0c908882009-03-03 19:32:16 -08001006 cancelStopToast();
1007
1008 // unregister network state listener
1009 unregisterReceiver(mNetworkStateIntentReceiver);
1010 WebView.disablePlatformNotifications();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001011 }
1012
Grace Kloba22ac16e2009-10-07 18:00:23 -07001013 @Override
1014 protected void onDestroy() {
Dave Bort31a6d1c2009-04-13 15:56:49 -07001015 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001016 Log.v(LOGTAG, "BrowserActivity.onDestroy: this=" + this);
1017 }
1018 super.onDestroy();
Grace Kloba0923d692009-09-23 21:37:25 -07001019
Leon Scroggins8d5fa432009-10-02 15:55:59 -04001020 if (mUploadMessage != null) {
1021 mUploadMessage.onReceiveValue(null);
1022 mUploadMessage = null;
1023 }
1024
Grace Kloba0923d692009-09-23 21:37:25 -07001025 if (mTabControl == null) return;
1026
Grace Kloba1fc98a32009-10-21 13:23:08 -07001027 // Remove the fake title bar if it is there
1028 hideFakeTitleBar();
1029
The Android Open Source Project0c908882009-03-03 19:32:16 -08001030 // Remove the current tab and sub window
Grace Kloba22ac16e2009-10-07 18:00:23 -07001031 Tab t = mTabControl.getCurrentTab();
Patrick Scottfb5e77f2009-04-08 19:17:37 -07001032 if (t != null) {
1033 dismissSubWindow(t);
1034 removeTabFromContentView(t);
1035 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001036 // Destroy all the tabs
1037 mTabControl.destroy();
1038 WebIconDatabase.getInstance().close();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001039
Grace Klobab4da0ad2009-05-14 14:45:40 -07001040 unregisterReceiver(mPackageInstallationReceiver);
Bjorn Bringerta7611812010-03-24 11:12:02 +00001041
1042 // Stop watching the default geolocation permissions
1043 mSystemAllowGeolocationOrigins.stop();
1044 mSystemAllowGeolocationOrigins = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001045 }
1046
1047 @Override
1048 public void onConfigurationChanged(Configuration newConfig) {
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04001049 mConfigChanged = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001050 super.onConfigurationChanged(newConfig);
1051
1052 if (mPageInfoDialog != null) {
1053 mPageInfoDialog.dismiss();
1054 showPageInfo(
1055 mPageInfoView,
Leon Scrogginsc7b92f82010-01-11 18:17:31 -05001056 mPageInfoFromShowSSLCertificateOnError);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001057 }
1058 if (mSSLCertificateDialog != null) {
1059 mSSLCertificateDialog.dismiss();
1060 showSSLCertificate(
1061 mSSLCertificateView);
1062 }
1063 if (mSSLCertificateOnErrorDialog != null) {
1064 mSSLCertificateOnErrorDialog.dismiss();
1065 showSSLCertificateOnError(
1066 mSSLCertificateOnErrorView,
1067 mSSLCertificateOnErrorHandler,
1068 mSSLCertificateOnErrorError);
1069 }
1070 if (mHttpAuthenticationDialog != null) {
1071 String title = ((TextView) mHttpAuthenticationDialog
1072 .findViewById(com.android.internal.R.id.alertTitle)).getText()
1073 .toString();
1074 String name = ((TextView) mHttpAuthenticationDialog
1075 .findViewById(R.id.username_edit)).getText().toString();
1076 String password = ((TextView) mHttpAuthenticationDialog
1077 .findViewById(R.id.password_edit)).getText().toString();
1078 int focusId = mHttpAuthenticationDialog.getCurrentFocus()
1079 .getId();
1080 mHttpAuthenticationDialog.dismiss();
1081 showHttpAuthentication(mHttpAuthHandler, null, null, title,
1082 name, password, focusId);
1083 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001084 }
1085
Grace Kloba22ac16e2009-10-07 18:00:23 -07001086 @Override
1087 public void onLowMemory() {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001088 super.onLowMemory();
1089 mTabControl.freeMemory();
1090 }
1091
Cary Clarkff4d92c2010-03-25 11:17:03 -04001092 private void resumeWebViewTimers() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001093 Tab tab = mTabControl.getCurrentTab();
Cary Clarkff4d92c2010-03-25 11:17:03 -04001094 if (tab == null) return; // monkey can trigger this
Grace Kloba22ac16e2009-10-07 18:00:23 -07001095 boolean inLoad = tab.inLoad();
1096 if ((!mActivityInPause && !inLoad) || (mActivityInPause && inLoad)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001097 CookieSyncManager.getInstance().startSync();
Grace Kloba22ac16e2009-10-07 18:00:23 -07001098 WebView w = tab.getWebView();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001099 if (w != null) {
1100 w.resumeTimers();
1101 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001102 }
1103 }
1104
Mike Reed7bfa63b2009-05-28 11:08:32 -04001105 private boolean pauseWebViewTimers() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001106 Tab tab = mTabControl.getCurrentTab();
1107 boolean inLoad = tab.inLoad();
1108 if (mActivityInPause && !inLoad) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001109 CookieSyncManager.getInstance().stopSync();
1110 WebView w = mTabControl.getCurrentWebView();
1111 if (w != null) {
1112 w.pauseTimers();
1113 }
1114 return true;
1115 } else {
1116 return false;
1117 }
1118 }
1119
The Android Open Source Project0c908882009-03-03 19:32:16 -08001120 // Open the icon database and retain all the icons for visited sites.
1121 private void retainIconsOnStartup() {
1122 final WebIconDatabase db = WebIconDatabase.getInstance();
1123 db.open(getDir("icons", 0).getPath());
Leon Scroggins2c0f6112010-03-12 18:09:39 -05001124 Cursor c = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001125 try {
Leon Scroggins2c0f6112010-03-12 18:09:39 -05001126 c = Browser.getAllBookmarks(mResolver);
1127 if (c.moveToFirst()) {
1128 int urlIndex = c.getColumnIndex(Browser.BookmarkColumns.URL);
1129 do {
1130 String url = c.getString(urlIndex);
1131 db.retainIconForPageUrl(url);
1132 } while (c.moveToNext());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001133 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001134 } catch (IllegalStateException e) {
1135 Log.e(LOGTAG, "retainIconsOnStartup", e);
Leon Scroggins2c0f6112010-03-12 18:09:39 -05001136 } finally {
1137 if (c!= null) c.close();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001138 }
1139 }
1140
1141 // Helper method for getting the top window.
1142 WebView getTopWindow() {
1143 return mTabControl.getCurrentTopWebView();
1144 }
1145
Grace Kloba22ac16e2009-10-07 18:00:23 -07001146 TabControl getTabControl() {
1147 return mTabControl;
1148 }
1149
The Android Open Source Project0c908882009-03-03 19:32:16 -08001150 @Override
1151 public boolean onCreateOptionsMenu(Menu menu) {
1152 super.onCreateOptionsMenu(menu);
1153
1154 MenuInflater inflater = getMenuInflater();
1155 inflater.inflate(R.menu.browser, menu);
1156 mMenu = menu;
1157 updateInLoadMenuItems();
1158 return true;
1159 }
1160
1161 /**
1162 * As the menu can be open when loading state changes
1163 * we must manually update the state of the stop/reload menu
1164 * item
1165 */
1166 private void updateInLoadMenuItems() {
1167 if (mMenu == null) {
1168 return;
1169 }
Michael Kolbe0a36662010-06-29 10:37:12 -07001170 MenuItem dest = mMenu.findItem(R.id.stop_reload_menu_id);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001171 MenuItem src = mInLoad ?
1172 mMenu.findItem(R.id.stop_menu_id):
Michael Kolbe0a36662010-06-29 10:37:12 -07001173 mMenu.findItem(R.id.reload_menu_id);
1174 if (src != null) {
1175 dest.setIcon(src.getIcon());
1176 dest.setTitle(src.getTitle());
1177 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001178 }
1179
1180 @Override
1181 public boolean onContextItemSelected(MenuItem item) {
1182 // chording is not an issue with context menus, but we use the same
1183 // options selector, so set mCanChord to true so we can access them.
1184 mCanChord = true;
1185 int id = item.getItemId();
Leon Scroggins96afcb12009-12-10 12:35:56 -05001186 boolean result = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001187 switch (id) {
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001188 // For the context menu from the title bar
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001189 case R.id.title_bar_copy_page_url:
Leon Scroggins96afcb12009-12-10 12:35:56 -05001190 Tab currentTab = mTabControl.getCurrentTab();
1191 if (null == currentTab) {
1192 result = false;
1193 break;
1194 }
1195 WebView mainView = currentTab.getWebView();
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001196 if (null == mainView) {
Leon Scroggins96afcb12009-12-10 12:35:56 -05001197 result = false;
1198 break;
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001199 }
Leon Scroggins96afcb12009-12-10 12:35:56 -05001200 copy(mainView.getUrl());
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001201 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001202 // -- Browser context menu
1203 case R.id.open_context_menu_id:
The Android Open Source Project0c908882009-03-03 19:32:16 -08001204 case R.id.bookmark_context_menu_id:
1205 case R.id.save_link_context_menu_id:
1206 case R.id.share_link_context_menu_id:
1207 case R.id.copy_link_context_menu_id:
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001208 final WebView webView = getTopWindow();
1209 if (null == webView) {
Leon Scroggins96afcb12009-12-10 12:35:56 -05001210 result = false;
1211 break;
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001212 }
1213 final HashMap hrefMap = new HashMap();
1214 hrefMap.put("webview", webView);
1215 final Message msg = mHandler.obtainMessage(
1216 FOCUS_NODE_HREF, id, 0, hrefMap);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001217 webView.requestFocusNodeHref(msg);
1218 break;
1219
1220 default:
1221 // For other context menus
Leon Scroggins96afcb12009-12-10 12:35:56 -05001222 result = onOptionsItemSelected(item);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001223 }
1224 mCanChord = false;
Leon Scroggins96afcb12009-12-10 12:35:56 -05001225 return result;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001226 }
1227
1228 private Bundle createGoogleSearchSourceBundle(String source) {
1229 Bundle bundle = new Bundle();
Bjorn Bringert10d1cca2010-02-10 14:22:12 +00001230 bundle.putString(Search.SOURCE, source);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001231 return bundle;
1232 }
1233
Leon Scroggins8ad29922010-02-16 12:33:55 -05001234 /* package */ void editUrl() {
Leon Scroggins68579392009-09-15 15:31:54 -04001235 if (mOptionsMenuOpen) closeOptionsMenu();
Leon Scroggins5bbe9802009-07-31 13:10:55 -04001236 String url = (getTopWindow() == null) ? null : getTopWindow().getUrl();
Grace Kloba83f47342009-07-20 10:44:31 -07001237 startSearch(mSettings.getHomePage().equals(url) ? null : url, true,
Leon Scroggins8ad29922010-02-16 12:33:55 -05001238 null, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001239 }
1240
Leon Scroggins8ad29922010-02-16 12:33:55 -05001241 /**
1242 * Overriding this to insert a local information bundle
1243 */
The Android Open Source Project0c908882009-03-03 19:32:16 -08001244 @Override
1245 public void startSearch(String initialQuery, boolean selectInitialQuery,
1246 Bundle appSearchData, boolean globalSearch) {
1247 if (appSearchData == null) {
1248 appSearchData = createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_TYPE);
1249 }
1250 super.startSearch(initialQuery, selectInitialQuery, appSearchData, globalSearch);
1251 }
1252
Leon Scroggins1f005d32009-08-10 17:36:42 -04001253 /**
1254 * Switch tabs. Called by the TitleBarSet when sliding the title bar
1255 * results in changing tabs.
Leon Scroggins160a7e72009-08-14 18:28:01 -04001256 * @param index Index of the tab to change to, as defined by
1257 * mTabControl.getTabIndex(Tab t).
1258 * @return boolean True if we successfully switched to a different tab. If
1259 * the indexth tab is null, or if that tab is the same as
1260 * the current one, return false.
Leon Scroggins1f005d32009-08-10 17:36:42 -04001261 */
Leon Scroggins160a7e72009-08-14 18:28:01 -04001262 /* package */ boolean switchToTab(int index) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001263 Tab tab = mTabControl.getTab(index);
1264 Tab currentTab = mTabControl.getCurrentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04001265 if (tab == null || tab == currentTab) {
Leon Scroggins160a7e72009-08-14 18:28:01 -04001266 return false;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001267 }
1268 if (currentTab != null) {
1269 // currentTab may be null if it was just removed. In that case,
1270 // we do not need to remove it
1271 removeTabFromContentView(currentTab);
1272 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001273 mTabControl.setCurrentTab(tab);
1274 attachTabToContentView(tab);
Grace Klobaeb6eef42009-09-15 17:56:32 -07001275 resetTitleIconAndProgress();
1276 updateLockIconToLatest();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001277 return true;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001278 }
1279
Grace Kloba22ac16e2009-10-07 18:00:23 -07001280 /* package */ Tab openTabToHomePage() {
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001281 return openTabAndShow(mSettings.getHomePage(), false, null);
1282 }
1283
Leon Scroggins1f005d32009-08-10 17:36:42 -04001284 /* package */ void closeCurrentWindow() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001285 final Tab current = mTabControl.getCurrentTab();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001286 if (mTabControl.getTabCount() == 1) {
Leon Scroggins30444232009-09-04 18:36:20 -04001287 // This is the last tab. Open a new one, with the home
1288 // page and close the current one.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001289 openTabToHomePage();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001290 closeTab(current);
Leon Scroggins160a7e72009-08-14 18:28:01 -04001291 return;
1292 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07001293 final Tab parent = current.getParentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04001294 int indexToShow = -1;
1295 if (parent != null) {
1296 indexToShow = mTabControl.getTabIndex(parent);
1297 } else {
Leon Scroggins160a7e72009-08-14 18:28:01 -04001298 final int currentIndex = mTabControl.getCurrentIndex();
1299 // Try to move to the tab to the right
1300 indexToShow = currentIndex + 1;
1301 if (indexToShow > mTabControl.getTabCount() - 1) {
1302 // Try to move to the tab to the left
1303 indexToShow = currentIndex - 1;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001304 }
1305 }
Leon Scroggins160a7e72009-08-14 18:28:01 -04001306 if (switchToTab(indexToShow)) {
1307 // Close window
1308 closeTab(current);
1309 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001310 }
1311
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001312 private ActiveTabsPage mActiveTabsPage;
1313
1314 /**
1315 * Remove the active tabs page.
1316 * @param needToAttach If true, the active tabs page did not attach a tab
1317 * to the content view, so we need to do that here.
1318 */
1319 /* package */ void removeActiveTabPage(boolean needToAttach) {
1320 mContentView.removeView(mActiveTabsPage);
Leon Scrogginsd746a942010-05-19 13:21:44 -04001321 mTitleBar.setVisibility(View.VISIBLE);
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001322 mActiveTabsPage = null;
1323 mMenuState = R.id.MAIN_MENU;
1324 if (needToAttach) {
1325 attachTabToContentView(mTabControl.getCurrentTab());
1326 }
1327 getTopWindow().requestFocus();
1328 }
1329
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04001330 @Override
1331 public ActionMode onStartActionMode(ActionMode.Callback callback) {
1332 ActionMode mode = super.onStartActionMode(callback);
1333 if (callback instanceof FindActionModeCallback
1334 || callback instanceof SelectActionModeCallback) {
1335 // For find and select, hide extra title bars. They will
1336 // be replaced in onEndActionMode.
1337 Tab tab = mTabControl.getCurrentTab();
1338 if (tab.getSubWebView() == null) {
1339 // If the find or select is being performed on the main webview,
1340 // remove the embedded title bar.
1341 WebView mainView = tab.getWebView();
1342 if (mainView != null) {
1343 mainView.setEmbeddedTitleBar(null);
1344 }
Cary Clark01cfcdd2010-06-04 16:36:45 -04001345 }
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04001346 hideFakeTitleBar();
1347 mActionMode = mode;
1348 } else {
1349 // Do not store other ActionModes, since we are unable to determine
1350 // when they finish.
1351 mActionMode = null;
Cary Clark01cfcdd2010-06-04 16:36:45 -04001352 }
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04001353 return mode;
Cary Clark01cfcdd2010-06-04 16:36:45 -04001354 }
1355
The Android Open Source Project0c908882009-03-03 19:32:16 -08001356 @Override
1357 public boolean onOptionsItemSelected(MenuItem item) {
Michael Kolbed217742010-08-10 17:52:34 -07001358 // check the action bar button before mCanChord check, as the prepare call
1359 // doesn't come for action bar buttons
1360 if (item.getItemId() == R.id.newtab) {
1361 bookmarksOrHistoryPicker(false, true);
1362 return true;
1363 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001364 if (!mCanChord) {
1365 // The user has already fired a shortcut with this hold down of the
1366 // menu key.
1367 return false;
1368 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001369 if (null == getTopWindow()) {
Leon Scroggins0d7ae0e2009-06-05 11:04:45 -04001370 return false;
1371 }
Grace Kloba6ee9c492009-07-13 10:04:34 -07001372 if (mMenuIsDown) {
1373 // The shortcut action consumes the MENU. Even if it is still down,
1374 // it won't trigger the next shortcut action. In the case of the
1375 // shortcut action triggering a new activity, like Bookmarks, we
1376 // won't get onKeyUp for MENU. So it is important to reset it here.
1377 mMenuIsDown = false;
1378 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001379 switch (item.getItemId()) {
1380 // -- Main menu
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001381 case R.id.new_tab_menu_id:
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001382 openTabToHomePage();
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001383 break;
1384
Michael Kolbae62fd42010-08-18 16:33:28 -07001385 case R.id.incognito_menu_id:
1386 openIncognitoTab();
1387 break;
1388
Leon Scroggins64b80f32009-08-07 12:03:34 -04001389 case R.id.goto_menu_id:
Leon Scroggins8ad29922010-02-16 12:33:55 -05001390 editUrl();
Leon Scrogginsb3a5bed2009-09-28 11:21:56 -04001391 break;
1392
1393 case R.id.bookmarks_menu_id:
Michael Kolb68792c82010-08-09 16:39:18 -07001394 bookmarksOrHistoryPicker(false, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001395 break;
1396
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001397 case R.id.active_tabs_menu_id:
1398 mActiveTabsPage = new ActiveTabsPage(this, mTabControl);
1399 removeTabFromContentView(mTabControl.getCurrentTab());
Leon Scrogginsd746a942010-05-19 13:21:44 -04001400 mTitleBar.setVisibility(View.GONE);
Leon Scroggins43de6162009-09-14 19:59:58 -04001401 hideFakeTitleBar();
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001402 mContentView.addView(mActiveTabsPage, COVER_SCREEN_PARAMS);
1403 mActiveTabsPage.requestFocus();
1404 mMenuState = EMPTY_MENU;
1405 break;
1406
Leon Scroggins1f005d32009-08-10 17:36:42 -04001407 case R.id.add_bookmark_menu_id:
Leon Scroggins571b3762010-05-26 10:25:01 -04001408 bookmarkCurrentPage();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001409 break;
1410
1411 case R.id.stop_reload_menu_id:
1412 if (mInLoad) {
1413 stopLoading();
1414 } else {
1415 getTopWindow().reload();
1416 }
1417 break;
1418
1419 case R.id.back_menu_id:
1420 getTopWindow().goBack();
1421 break;
1422
1423 case R.id.forward_menu_id:
1424 getTopWindow().goForward();
1425 break;
1426
1427 case R.id.close_menu_id:
1428 // Close the subwindow if it exists.
1429 if (mTabControl.getCurrentSubWindow() != null) {
1430 dismissSubWindow(mTabControl.getCurrentTab());
1431 break;
1432 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001433 closeCurrentWindow();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001434 break;
1435
1436 case R.id.homepage_menu_id:
Grace Kloba22ac16e2009-10-07 18:00:23 -07001437 Tab current = mTabControl.getCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001438 if (current != null) {
1439 dismissSubWindow(current);
Leon Scroggins92472e82010-02-17 16:32:28 -05001440 loadUrl(current.getWebView(), mSettings.getHomePage());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001441 }
1442 break;
1443
1444 case R.id.preferences_menu_id:
1445 Intent intent = new Intent(this,
1446 BrowserPreferencesPage.class);
Leon Scrogginsd5304942009-12-10 16:11:39 -05001447 intent.putExtra(BrowserPreferencesPage.CURRENT_PAGE,
1448 getTopWindow().getUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001449 startActivityForResult(intent, PREFERENCES_PAGE);
1450 break;
1451
1452 case R.id.find_menu_id:
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04001453 showFindDialog(null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001454 break;
1455
Elliott Slaughter0ced08c2010-06-30 11:40:42 -07001456 case R.id.save_webarchive_menu_id:
1457 if (LOGD_ENABLED) {
1458 Log.d(LOGTAG, "Save as Web Archive");
1459 }
1460 String directory = getExternalFilesDir(null).getAbsolutePath() + File.separator;
1461 getTopWindow().saveWebArchive(directory, true, new ValueCallback<String>() {
1462 @Override
1463 public void onReceiveValue(String value) {
1464 if (value != null) {
1465 Toast.makeText(BrowserActivity.this, R.string.webarchive_saved, Toast.LENGTH_SHORT).show();
1466 } else {
1467 Toast.makeText(BrowserActivity.this, R.string.webarchive_failed, Toast.LENGTH_SHORT).show();
1468 }
1469 }
1470 });
1471 break;
1472
The Android Open Source Project0c908882009-03-03 19:32:16 -08001473 case R.id.page_info_menu_id:
1474 showPageInfo(mTabControl.getCurrentTab(), false);
1475 break;
1476
1477 case R.id.classic_history_menu_id:
Michael Kolb68792c82010-08-09 16:39:18 -07001478 bookmarksOrHistoryPicker(true, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001479 break;
1480
Leon Scroggins96afcb12009-12-10 12:35:56 -05001481 case R.id.title_bar_share_page_url:
The Android Open Source Project0c908882009-03-03 19:32:16 -08001482 case R.id.share_page_menu_id:
Leon Scroggins96afcb12009-12-10 12:35:56 -05001483 Tab currentTab = mTabControl.getCurrentTab();
1484 if (null == currentTab) {
1485 mCanChord = false;
1486 return false;
1487 }
1488 currentTab.populatePickerData();
1489 sharePage(this, currentTab.getTitle(),
1490 currentTab.getUrl(), currentTab.getFavicon(),
Ben Murdoch87cc65d2010-06-29 20:34:10 +01001491 createScreenshot(currentTab.getWebView(), getDesiredThumbnailWidth(this),
1492 getDesiredThumbnailHeight(this)));
The Android Open Source Project0c908882009-03-03 19:32:16 -08001493 break;
1494
1495 case R.id.dump_nav_menu_id:
1496 getTopWindow().debugDump();
1497 break;
1498
Andrei Popescu7a8b88b2010-02-02 00:30:38 +00001499 case R.id.dump_counters_menu_id:
1500 getTopWindow().dumpV8Counters();
1501 break;
1502
The Android Open Source Project0c908882009-03-03 19:32:16 -08001503 case R.id.zoom_in_menu_id:
1504 getTopWindow().zoomIn();
1505 break;
1506
1507 case R.id.zoom_out_menu_id:
1508 getTopWindow().zoomOut();
1509 break;
1510
1511 case R.id.view_downloads_menu_id:
1512 viewDownloads(null);
1513 break;
1514
The Android Open Source Project0c908882009-03-03 19:32:16 -08001515 case R.id.window_one_menu_id:
1516 case R.id.window_two_menu_id:
1517 case R.id.window_three_menu_id:
1518 case R.id.window_four_menu_id:
1519 case R.id.window_five_menu_id:
1520 case R.id.window_six_menu_id:
1521 case R.id.window_seven_menu_id:
1522 case R.id.window_eight_menu_id:
1523 {
1524 int menuid = item.getItemId();
1525 for (int id = 0; id < WINDOW_SHORTCUT_ID_ARRAY.length; id++) {
1526 if (WINDOW_SHORTCUT_ID_ARRAY[id] == menuid) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001527 Tab desiredTab = mTabControl.getTab(id);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001528 if (desiredTab != null &&
1529 desiredTab != mTabControl.getCurrentTab()) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001530 switchToTab(id);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001531 }
1532 break;
1533 }
1534 }
1535 }
1536 break;
1537
1538 default:
1539 if (!super.onOptionsItemSelected(item)) {
1540 return false;
1541 }
1542 // Otherwise fall through.
1543 }
1544 mCanChord = false;
1545 return true;
1546 }
1547
Leon Scroggins571b3762010-05-26 10:25:01 -04001548 /* package */ void bookmarkCurrentPage() {
1549 Intent i = new Intent(BrowserActivity.this,
1550 AddBookmarkPage.class);
1551 WebView w = getTopWindow();
1552 i.putExtra("url", w.getUrl());
1553 i.putExtra("title", w.getTitle());
1554 i.putExtra("touch_icon_url", w.getTouchIconUrl());
Ben Murdoch87cc65d2010-06-29 20:34:10 +01001555 i.putExtra("thumbnail", createScreenshot(w, getDesiredThumbnailWidth(this),
1556 getDesiredThumbnailHeight(this)));
Ben Murdocheecb4e62010-07-06 16:30:38 +01001557 i.putExtra("url_editable", false);
Leon Scroggins571b3762010-05-26 10:25:01 -04001558 startActivity(i);
1559 }
1560
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04001561 /*
1562 * True if a custom ActionMode (i.e. find or select) is in use.
1563 */
1564 private boolean isInCustomActionMode() {
1565 return mActionMode != null;
Cary Clark01cfcdd2010-06-04 16:36:45 -04001566 }
1567
1568 /*
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04001569 * End the current ActionMode. Only works for find and select.
Cary Clark01cfcdd2010-06-04 16:36:45 -04001570 */
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04001571 void endActionMode() {
1572 if (mActionMode != null) {
1573 mActionMode.finish();
1574 }
1575 }
1576
1577 /*
1578 * Called by find and select when they are finished. Replace title bars
1579 * as necessary.
1580 */
1581 public void onEndActionMode() {
1582 if (!isInCustomActionMode()) return;
Michael Kolba2b2ba82010-08-04 17:54:03 -07001583 // If the Find was being performed in the main WebView, replace the
1584 // embedded title bar.
1585 Tab currentTab = mTabControl.getCurrentTab();
1586 if (currentTab.getSubWebView() == null) {
1587 WebView mainView = currentTab.getWebView();
1588 if (mainView != null) {
1589 mainView.setEmbeddedTitleBar(mTitleBar);
Leon Scroggins79e36d92010-04-29 16:01:46 +01001590 }
1591 }
Leon Scroggins79e36d92010-04-29 16:01:46 +01001592 if (mInLoad) {
1593 // The title bar was hidden, because otherwise it would cover up the
Michael Kolba2b2ba82010-08-04 17:54:03 -07001594 // find or select dialog. Now that the dialog has been removed,
Cary Clark01cfcdd2010-06-04 16:36:45 -04001595 // show the fake title bar once again.
Leon Scroggins79e36d92010-04-29 16:01:46 +01001596 showFakeTitleBar();
1597 }
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04001598 mActionMode = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001599 }
1600
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04001601 private FindActionModeCallback mFindCallback;
1602 private SelectActionModeCallback mSelectCallback;
1603
1604 // For select and find, we keep track of the ActionMode so that
1605 // finish() can be called as desired.
1606 private ActionMode mActionMode;
1607
1608 /*
1609 * Open the find ActionMode.
1610 * @param text If non null, will be placed in find to be searched for.
1611 */
1612 public void showFindDialog(String text) {
1613 if (null == mFindCallback) {
1614 mFindCallback = new FindActionModeCallback(this);
Cary Clark01cfcdd2010-06-04 16:36:45 -04001615 }
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04001616 WebView webView = getTopWindow();
1617 webView.setFindIsUp(true);
1618 mFindCallback.setWebView(webView);
1619 startActionMode(mFindCallback);
1620 if (text != null) mFindCallback.setText(text);
Cary Clark01cfcdd2010-06-04 16:36:45 -04001621 }
1622
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04001623 /*
1624 * Show the select ActionMode.
1625 */
Cary Clark01cfcdd2010-06-04 16:36:45 -04001626 public void showSelectDialog() {
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04001627 if (null == mSelectCallback) {
1628 mSelectCallback = new SelectActionModeCallback(this);
Cary Clark01cfcdd2010-06-04 16:36:45 -04001629 }
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04001630 WebView webView = getTopWindow();
1631 webView.setUpSelect();
1632 mSelectCallback.setWebView(webView);
1633 startActionMode(mSelectCallback);
Cary Clark01cfcdd2010-06-04 16:36:45 -04001634 }
1635
Grace Kloba22ac16e2009-10-07 18:00:23 -07001636 @Override
1637 public boolean onPrepareOptionsMenu(Menu menu) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001638 // This happens when the user begins to hold down the menu key, so
1639 // allow them to chord to get a shortcut.
1640 mCanChord = true;
1641 // Note: setVisible will decide whether an item is visible; while
1642 // setEnabled() will decide whether an item is enabled, which also means
1643 // whether the matching shortcut key will function.
1644 super.onPrepareOptionsMenu(menu);
1645 switch (mMenuState) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001646 case EMPTY_MENU:
1647 if (mCurrentMenuState != mMenuState) {
1648 menu.setGroupVisible(R.id.MAIN_MENU, false);
1649 menu.setGroupEnabled(R.id.MAIN_MENU, false);
1650 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001651 }
1652 break;
1653 default:
1654 if (mCurrentMenuState != mMenuState) {
1655 menu.setGroupVisible(R.id.MAIN_MENU, true);
1656 menu.setGroupEnabled(R.id.MAIN_MENU, true);
1657 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001658 }
1659 final WebView w = getTopWindow();
1660 boolean canGoBack = false;
1661 boolean canGoForward = false;
1662 boolean isHome = false;
1663 if (w != null) {
1664 canGoBack = w.canGoBack();
1665 canGoForward = w.canGoForward();
1666 isHome = mSettings.getHomePage().equals(w.getUrl());
1667 }
1668 final MenuItem back = menu.findItem(R.id.back_menu_id);
1669 back.setEnabled(canGoBack);
1670
1671 final MenuItem home = menu.findItem(R.id.homepage_menu_id);
1672 home.setEnabled(!isHome);
1673
Michael Kolbe0a36662010-06-29 10:37:12 -07001674 final MenuItem forward = menu.findItem(R.id.forward_menu_id);
1675 forward.setEnabled(canGoForward);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001676
Michael Kolbed217742010-08-10 17:52:34 -07001677 if (!mXLargeScreenSize) {
1678 final MenuItem newtab = menu.findItem(R.id.new_tab_menu_id);
1679 newtab.setEnabled(mTabControl.canCreateNewTab());
1680 }
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001681
The Android Open Source Project0c908882009-03-03 19:32:16 -08001682 // decide whether to show the share link option
1683 PackageManager pm = getPackageManager();
1684 Intent send = new Intent(Intent.ACTION_SEND);
1685 send.setType("text/plain");
1686 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1687 menu.findItem(R.id.share_page_menu_id).setVisible(ri != null);
1688
The Android Open Source Project0c908882009-03-03 19:32:16 -08001689 boolean isNavDump = mSettings.isNavDump();
1690 final MenuItem nav = menu.findItem(R.id.dump_nav_menu_id);
1691 nav.setVisible(isNavDump);
1692 nav.setEnabled(isNavDump);
Andrei Popescu7a8b88b2010-02-02 00:30:38 +00001693
1694 boolean showDebugSettings = mSettings.showDebugSettings();
1695 final MenuItem counter = menu.findItem(R.id.dump_counters_menu_id);
1696 counter.setVisible(showDebugSettings);
1697 counter.setEnabled(showDebugSettings);
1698
The Android Open Source Project0c908882009-03-03 19:32:16 -08001699 break;
1700 }
1701 mCurrentMenuState = mMenuState;
1702 return true;
1703 }
1704
1705 @Override
1706 public void onCreateContextMenu(ContextMenu menu, View v,
1707 ContextMenuInfo menuInfo) {
Leon Scroggins571b3762010-05-26 10:25:01 -04001708 if (v instanceof TitleBarBase) {
Leon Scroggins4e9f89b2010-02-22 16:54:14 -05001709 return;
1710 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001711 WebView webview = (WebView) v;
1712 WebView.HitTestResult result = webview.getHitTestResult();
1713 if (result == null) {
1714 return;
1715 }
1716
1717 int type = result.getType();
1718 if (type == WebView.HitTestResult.UNKNOWN_TYPE) {
1719 Log.w(LOGTAG,
1720 "We should not show context menu when nothing is touched");
1721 return;
1722 }
1723 if (type == WebView.HitTestResult.EDIT_TEXT_TYPE) {
1724 // let TextView handles context menu
1725 return;
1726 }
1727
1728 // Note, http://b/issue?id=1106666 is requesting that
1729 // an inflated menu can be used again. This is not available
1730 // yet, so inflate each time (yuk!)
1731 MenuInflater inflater = getMenuInflater();
1732 inflater.inflate(R.menu.browsercontext, menu);
1733
1734 // Show the correct menu group
Leon Scroggins III9e997c72010-05-26 13:25:16 -04001735 final String extra = result.getExtra();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001736 menu.setGroupVisible(R.id.PHONE_MENU,
1737 type == WebView.HitTestResult.PHONE_TYPE);
1738 menu.setGroupVisible(R.id.EMAIL_MENU,
1739 type == WebView.HitTestResult.EMAIL_TYPE);
1740 menu.setGroupVisible(R.id.GEO_MENU,
1741 type == WebView.HitTestResult.GEO_TYPE);
1742 menu.setGroupVisible(R.id.IMAGE_MENU,
1743 type == WebView.HitTestResult.IMAGE_TYPE
1744 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1745 menu.setGroupVisible(R.id.ANCHOR_MENU,
1746 type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1747 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1748
1749 // Setup custom handling depending on the type
1750 switch (type) {
1751 case WebView.HitTestResult.PHONE_TYPE:
1752 menu.setHeaderTitle(Uri.decode(extra));
1753 menu.findItem(R.id.dial_context_menu_id).setIntent(
1754 new Intent(Intent.ACTION_VIEW, Uri
1755 .parse(WebView.SCHEME_TEL + extra)));
1756 Intent addIntent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
1757 addIntent.putExtra(Insert.PHONE, Uri.decode(extra));
Cary Clark5e335a32009-09-22 14:53:11 -04001758 addIntent.setType(ContactsContract.Contacts.CONTENT_ITEM_TYPE);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001759 menu.findItem(R.id.add_contact_context_menu_id).setIntent(
1760 addIntent);
1761 menu.findItem(R.id.copy_phone_context_menu_id).setOnMenuItemClickListener(
1762 new Copy(extra));
1763 break;
1764
1765 case WebView.HitTestResult.EMAIL_TYPE:
1766 menu.setHeaderTitle(extra);
1767 menu.findItem(R.id.email_context_menu_id).setIntent(
1768 new Intent(Intent.ACTION_VIEW, Uri
1769 .parse(WebView.SCHEME_MAILTO + extra)));
1770 menu.findItem(R.id.copy_mail_context_menu_id).setOnMenuItemClickListener(
1771 new Copy(extra));
1772 break;
1773
1774 case WebView.HitTestResult.GEO_TYPE:
1775 menu.setHeaderTitle(extra);
1776 menu.findItem(R.id.map_context_menu_id).setIntent(
1777 new Intent(Intent.ACTION_VIEW, Uri
1778 .parse(WebView.SCHEME_GEO
1779 + URLEncoder.encode(extra))));
1780 menu.findItem(R.id.copy_geo_context_menu_id).setOnMenuItemClickListener(
1781 new Copy(extra));
1782 break;
1783
1784 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1785 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
1786 TextView titleView = (TextView) LayoutInflater.from(this)
1787 .inflate(android.R.layout.browser_link_context_header,
1788 null);
1789 titleView.setText(extra);
1790 menu.setHeaderView(titleView);
1791 // decide whether to show the open link in new tab option
Leon Scroggins III9e997c72010-05-26 13:25:16 -04001792 boolean showNewTab = mTabControl.canCreateNewTab();
1793 MenuItem newTabItem
1794 = menu.findItem(R.id.open_newtab_context_menu_id);
1795 newTabItem.setVisible(showNewTab);
1796 if (showNewTab) {
1797 newTabItem.setOnMenuItemClickListener(
1798 new MenuItem.OnMenuItemClickListener() {
1799 public boolean onMenuItemClick(MenuItem item) {
1800 final Tab parent = mTabControl.getCurrentTab();
Michael Kolb68792c82010-08-09 16:39:18 -07001801 final Tab newTab = openTab(extra, false);
Leon Scroggins III9e997c72010-05-26 13:25:16 -04001802 if (newTab != parent) {
1803 parent.addChildTab(newTab);
1804 }
1805 return true;
1806 }
1807 });
1808 }
Ben Murdochde353622009-10-12 10:29:00 +01001809 menu.findItem(R.id.bookmark_context_menu_id).setVisible(
1810 Bookmarks.urlHasAcceptableScheme(extra));
The Android Open Source Project0c908882009-03-03 19:32:16 -08001811 PackageManager pm = getPackageManager();
1812 Intent send = new Intent(Intent.ACTION_SEND);
1813 send.setType("text/plain");
1814 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1815 menu.findItem(R.id.share_link_context_menu_id).setVisible(ri != null);
1816 if (type == WebView.HitTestResult.SRC_ANCHOR_TYPE) {
1817 break;
1818 }
1819 // otherwise fall through to handle image part
1820 case WebView.HitTestResult.IMAGE_TYPE:
1821 if (type == WebView.HitTestResult.IMAGE_TYPE) {
1822 menu.setHeaderTitle(extra);
1823 }
1824 menu.findItem(R.id.view_image_context_menu_id).setIntent(
1825 new Intent(Intent.ACTION_VIEW, Uri.parse(extra)));
1826 menu.findItem(R.id.download_context_menu_id).
1827 setOnMenuItemClickListener(new Download(extra));
Ben Murdoch4f75ba22009-10-27 11:48:28 +00001828 menu.findItem(R.id.set_wallpaper_context_menu_id).
1829 setOnMenuItemClickListener(new SetAsWallpaper(extra));
The Android Open Source Project0c908882009-03-03 19:32:16 -08001830 break;
1831
1832 default:
1833 Log.w(LOGTAG, "We should not get here.");
1834 break;
1835 }
Leon Scrogginsb2b19f52009-10-09 16:10:00 -04001836 hideFakeTitleBar();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001837 }
1838
The Android Open Source Project0c908882009-03-03 19:32:16 -08001839 // Attach the given tab to the content view.
Grace Klobac928c302009-09-17 11:51:21 -07001840 // this should only be called for the current tab.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001841 private void attachTabToContentView(Tab t) {
Steve Block2bc69912009-07-30 14:45:13 +01001842 // Attach the container that contains the main WebView and any other UI
1843 // associated with the tab.
Patrick Scottd0119532009-09-17 08:00:31 -04001844 t.attachTabToContentView(mContentView);
Ben Murdochbff2d602009-07-01 20:19:05 +01001845
1846 if (mShouldShowErrorConsole) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001847 ErrorConsoleView errorConsole = t.getErrorConsole(true);
Ben Murdochbff2d602009-07-01 20:19:05 +01001848 if (errorConsole.numberOfErrors() == 0) {
1849 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
1850 } else {
1851 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
1852 }
1853
1854 mErrorConsoleContainer.addView(errorConsole,
Romain Guy15b8ec62010-01-08 15:06:43 -08001855 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
Ben Murdochbff2d602009-07-01 20:19:05 +01001856 ViewGroup.LayoutParams.WRAP_CONTENT));
1857 }
1858
Michael Kolba2b2ba82010-08-04 17:54:03 -07001859 WebView view = t.getWebView();
1860 view.setEmbeddedTitleBar(mTitleBar);
Leon Scroggins58d56c62010-01-28 15:12:40 -05001861 if (t.isInVoiceSearchMode()) {
1862 showVoiceTitleBar(t.getVoiceDisplayTitle());
1863 } else {
1864 revertVoiceTitleBar();
1865 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001866 // Request focus on the top window.
1867 t.getTopWindow().requestFocus();
Michael Kolba2b2ba82010-08-04 17:54:03 -07001868 if (mTabControl.getTabChangeListener() != null) {
1869 mTabControl.getTabChangeListener().onCurrentTab(t);
1870 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001871 }
1872
1873 // Attach a sub window to the main WebView of the given tab.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001874 void attachSubWindow(Tab t) {
Patrick Scottd0119532009-09-17 08:00:31 -04001875 t.attachSubWindow(mContentView);
1876 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001877 }
1878
1879 // Remove the given tab from the content view.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001880 private void removeTabFromContentView(Tab t) {
Steve Block2bc69912009-07-30 14:45:13 +01001881 // Remove the container that contains the main WebView.
Patrick Scottd0119532009-09-17 08:00:31 -04001882 t.removeTabFromContentView(mContentView);
Ben Murdochbff2d602009-07-01 20:19:05 +01001883
Grace Kloba22ac16e2009-10-07 18:00:23 -07001884 ErrorConsoleView errorConsole = t.getErrorConsole(false);
1885 if (errorConsole != null) {
1886 mErrorConsoleContainer.removeView(errorConsole);
Ben Murdochbff2d602009-07-01 20:19:05 +01001887 }
1888
Michael Kolba2b2ba82010-08-04 17:54:03 -07001889 WebView view = t.getWebView();
1890 if (view != null) {
1891 view.setEmbeddedTitleBar(null);
Leon Scrogginsbb85b902009-09-14 19:27:20 -04001892 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001893 }
1894
1895 // Remove the sub window if it exists. Also called by TabControl when the
1896 // user clicks the 'X' to dismiss a sub window.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001897 /* package */ void dismissSubWindow(Tab t) {
Patrick Scottd0119532009-09-17 08:00:31 -04001898 t.removeSubWindow(mContentView);
Grace Kloba22ac16e2009-10-07 18:00:23 -07001899 // dismiss the subwindow. This will destroy the WebView.
1900 t.dismissSubWindow();
Patrick Scottd0119532009-09-17 08:00:31 -04001901 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001902 }
1903
Leon Scroggins1f005d32009-08-10 17:36:42 -04001904 // A wrapper function of {@link #openTabAndShow(UrlData, boolean, String)}
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07001905 // that accepts url as string.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001906 private Tab openTabAndShow(String url, boolean closeOnExit, String appId) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001907 return openTabAndShow(new UrlData(url), closeOnExit, appId);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001908 }
1909
1910 // This method does a ton of stuff. It will attempt to create a new tab
1911 // if we haven't reached MAX_TABS. Otherwise it uses the current tab. If
Leon Scroggins1f005d32009-08-10 17:36:42 -04001912 // url isn't null, it will load the given url.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001913 /* package */Tab openTabAndShow(UrlData urlData, boolean closeOnExit,
1914 String appId) {
1915 final Tab currentTab = mTabControl.getCurrentTab();
1916 if (mTabControl.canCreateNewTab()) {
1917 final Tab tab = mTabControl.createNewTab(closeOnExit, appId,
Elliott Slaughterf0f03952010-07-14 18:10:36 -07001918 urlData.mUrl, false);
Leon Scroggins1f005d32009-08-10 17:36:42 -04001919 WebView webview = tab.getWebView();
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001920 // If the last tab was removed from the active tabs page, currentTab
1921 // will be null.
1922 if (currentTab != null) {
1923 removeTabFromContentView(currentTab);
1924 }
Patrick Scott8bbd69f2009-08-14 13:35:53 -04001925 // We must set the new tab as the current tab to reflect the old
1926 // animation behavior.
1927 mTabControl.setCurrentTab(tab);
Grace Klobaeb6eef42009-09-15 17:56:32 -07001928 attachTabToContentView(tab);
Leon Scroggins160a7e72009-08-14 18:28:01 -04001929 if (!urlData.isEmpty()) {
Patrick Scott9d53da02010-02-19 10:19:01 -05001930 loadUrlDataIn(tab, urlData);
Leon Scroggins1f005d32009-08-10 17:36:42 -04001931 }
1932 return tab;
1933 } else {
1934 // Get rid of the subwindow if it exists
1935 dismissSubWindow(currentTab);
1936 if (!urlData.isEmpty()) {
1937 // Load the given url.
Patrick Scott9d53da02010-02-19 10:19:01 -05001938 loadUrlDataIn(currentTab, urlData);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001939 }
Leon Scroggins58d56c62010-01-28 15:12:40 -05001940 return currentTab;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001941 }
1942 }
1943
Michael Kolb68792c82010-08-09 16:39:18 -07001944 private Tab openTab(String url, boolean forceForeground) {
1945 if (mSettings.openInBackground() && !forceForeground) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001946 Tab t = mTabControl.createNewTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001947 if (t != null) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001948 WebView view = t.getWebView();
Leon Scroggins92472e82010-02-17 16:32:28 -05001949 loadUrl(view, url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001950 }
Grace Klobac9181842009-04-14 08:53:22 -07001951 return t;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001952 } else {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001953 return openTabAndShow(url, false, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001954 }
1955 }
1956
Elliott Slaughterf0f03952010-07-14 18:10:36 -07001957 /* package */ Tab openIncognitoTab() {
1958 if (mTabControl.canCreateNewTab()) {
1959 Tab currentTab = mTabControl.getCurrentTab();
1960 Tab tab = mTabControl.createNewTab(false, null, null, true);
1961 if (currentTab != null) {
1962 removeTabFromContentView(currentTab);
1963 }
1964 mTabControl.setCurrentTab(tab);
1965 attachTabToContentView(tab);
1966 return tab;
1967 }
1968 return null;
1969 }
1970
The Android Open Source Project0c908882009-03-03 19:32:16 -08001971 private class Copy implements OnMenuItemClickListener {
1972 private CharSequence mText;
1973
1974 public boolean onMenuItemClick(MenuItem item) {
1975 copy(mText);
1976 return true;
1977 }
1978
1979 public Copy(CharSequence toCopy) {
1980 mText = toCopy;
1981 }
1982 }
1983
1984 private class Download implements OnMenuItemClickListener {
1985 private String mText;
1986
1987 public boolean onMenuItemClick(MenuItem item) {
1988 onDownloadStartNoStream(mText, null, null, null, -1);
1989 return true;
1990 }
1991
1992 public Download(String toDownload) {
1993 mText = toDownload;
1994 }
1995 }
1996
Ben Murdoch4f75ba22009-10-27 11:48:28 +00001997 private class SetAsWallpaper extends Thread implements
1998 OnMenuItemClickListener, DialogInterface.OnCancelListener {
1999 private URL mUrl;
2000 private ProgressDialog mWallpaperProgress;
2001 private boolean mCanceled = false;
2002
2003 public SetAsWallpaper(String url) {
2004 try {
2005 mUrl = new URL(url);
2006 } catch (MalformedURLException e) {
2007 mUrl = null;
2008 }
2009 }
2010
2011 public void onCancel(DialogInterface dialog) {
2012 mCanceled = true;
2013 }
2014
2015 public boolean onMenuItemClick(MenuItem item) {
2016 if (mUrl != null) {
2017 // The user may have tried to set a image with a large file size as their
2018 // background so it may take a few moments to perform the operation. Display
2019 // a progress spinner while it is working.
2020 mWallpaperProgress = new ProgressDialog(BrowserActivity.this);
2021 mWallpaperProgress.setIndeterminate(true);
2022 mWallpaperProgress.setMessage(getText(R.string.progress_dialog_setting_wallpaper));
2023 mWallpaperProgress.setCancelable(true);
2024 mWallpaperProgress.setOnCancelListener(this);
2025 mWallpaperProgress.show();
2026 start();
2027 }
2028 return true;
2029 }
2030
Michael Kolbe0a36662010-06-29 10:37:12 -07002031 @Override
Ben Murdoch4f75ba22009-10-27 11:48:28 +00002032 public void run() {
2033 Drawable oldWallpaper = BrowserActivity.this.getWallpaper();
2034 try {
2035 // TODO: This will cause the resource to be downloaded again, when we
2036 // should in most cases be able to grab it from the cache. To fix this
2037 // we should query WebCore to see if we can access a cached version and
2038 // instead open an input stream on that. This pattern could also be used
2039 // in the download manager where the same problem exists.
2040 InputStream inputstream = mUrl.openStream();
2041 if (inputstream != null) {
2042 setWallpaper(inputstream);
2043 }
2044 } catch (IOException e) {
2045 Log.e(LOGTAG, "Unable to set new wallpaper");
2046 // Act as though the user canceled the operation so we try to
2047 // restore the old wallpaper.
2048 mCanceled = true;
2049 }
2050
2051 if (mCanceled) {
2052 // Restore the old wallpaper if the user cancelled whilst we were setting
2053 // the new wallpaper.
2054 int width = oldWallpaper.getIntrinsicWidth();
2055 int height = oldWallpaper.getIntrinsicHeight();
2056 Bitmap bm = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
2057 Canvas canvas = new Canvas(bm);
2058 oldWallpaper.setBounds(0, 0, width, height);
2059 oldWallpaper.draw(canvas);
2060 try {
2061 setWallpaper(bm);
2062 } catch (IOException e) {
2063 Log.e(LOGTAG, "Unable to restore old wallpaper.");
2064 }
2065 mCanceled = false;
2066 }
2067
2068 if (mWallpaperProgress.isShowing()) {
2069 mWallpaperProgress.dismiss();
2070 }
2071 }
2072 }
2073
The Android Open Source Project0c908882009-03-03 19:32:16 -08002074 private void copy(CharSequence text) {
Dianne Hackborn80f32622010-08-05 14:17:53 -07002075 ClipboardManager cm = (ClipboardManager)getSystemService(Context.CLIPBOARD_SERVICE);
2076 cm.setText(text);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002077 }
2078
2079 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08002080 * Resets the browser title-view to whatever it must be
2081 * (for example, if we had a loading error)
2082 * When we have a new page, we call resetTitle, when we
2083 * have to reset the titlebar to whatever it used to be
2084 * (for example, if the user chose to stop loading), we
2085 * call resetTitleAndRevertLockIcon.
2086 */
2087 /* package */ void resetTitleAndRevertLockIcon() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002088 mTabControl.getCurrentTab().revertLockIcon();
2089 updateLockIconToLatest();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002090 resetTitleIconAndProgress();
2091 }
2092
2093 /**
2094 * Reset the title, favicon, and progress.
2095 */
2096 private void resetTitleIconAndProgress() {
2097 WebView current = mTabControl.getCurrentWebView();
2098 if (current == null) {
2099 return;
2100 }
2101 resetTitleAndIcon(current);
2102 int progress = current.getProgress();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002103 current.getWebChromeClient().onProgressChanged(current, progress);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002104 }
2105
2106 // Reset the title and the icon based on the given item.
2107 private void resetTitleAndIcon(WebView view) {
2108 WebHistoryItem item = view.copyBackForwardList().getCurrentItem();
2109 if (item != null) {
Leon Scroggins68579392009-09-15 15:31:54 -04002110 setUrlTitle(item.getUrl(), item.getTitle());
The Android Open Source Project0c908882009-03-03 19:32:16 -08002111 setFavicon(item.getFavicon());
2112 } else {
Leon Scroggins68579392009-09-15 15:31:54 -04002113 setUrlTitle(null, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002114 setFavicon(null);
2115 }
2116 }
2117
2118 /**
2119 * Sets a title composed of the URL and the title string.
2120 * @param url The URL of the site being loaded.
2121 * @param title The title of the site being loaded.
2122 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07002123 void setUrlTitle(String url, String title) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002124 mUrl = url;
2125 mTitle = title;
2126
Leon Scroggins58d56c62010-01-28 15:12:40 -05002127 // If we are in voice search mode, the title has already been set.
2128 if (mTabControl.getCurrentTab().isInVoiceSearchMode()) return;
2129 mTitleBar.setDisplayTitle(url);
Michael Kolba2b2ba82010-08-04 17:54:03 -07002130 mFakeTitleBar.setDisplayTitle(url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002131 }
2132
2133 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08002134 * @param url The URL to build a title version of the URL from.
2135 * @return The title version of the URL or null if fails.
2136 * The title version of the URL can be either the URL hostname,
2137 * or the hostname with an "https://" prefix (for secure URLs),
2138 * or an empty string if, for example, the URL in question is a
2139 * file:// URL with no hostname.
2140 */
Leon Scroggins32e14a62009-06-11 10:26:34 -04002141 /* package */ static String buildTitleUrl(String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002142 String titleUrl = null;
2143
2144 if (url != null) {
2145 try {
2146 // parse the url string
2147 URL urlObj = new URL(url);
2148 if (urlObj != null) {
2149 titleUrl = "";
2150
2151 String protocol = urlObj.getProtocol();
2152 String host = urlObj.getHost();
2153
2154 if (host != null && 0 < host.length()) {
2155 titleUrl = host;
2156 if (protocol != null) {
2157 // if a secure site, add an "https://" prefix!
2158 if (protocol.equalsIgnoreCase("https")) {
2159 titleUrl = protocol + "://" + host;
2160 }
2161 }
2162 }
2163 }
2164 } catch (MalformedURLException e) {}
2165 }
2166
2167 return titleUrl;
2168 }
2169
2170 // Set the favicon in the title bar.
Grace Kloba22ac16e2009-10-07 18:00:23 -07002171 void setFavicon(Bitmap icon) {
Leon Scroggins68579392009-09-15 15:31:54 -04002172 mTitleBar.setFavicon(icon);
Michael Kolba2b2ba82010-08-04 17:54:03 -07002173 mFakeTitleBar.setFavicon(icon);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002174 }
2175
2176 /**
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002177 * Close the tab, remove its associated title bar, and adjust mTabControl's
2178 * current tab to a valid value.
Leon Scroggins1f005d32009-08-10 17:36:42 -04002179 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07002180 /* package */ void closeTab(Tab t) {
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002181 int currentIndex = mTabControl.getCurrentIndex();
2182 int removeIndex = mTabControl.getTabIndex(t);
Leon Scroggins1f005d32009-08-10 17:36:42 -04002183 mTabControl.removeTab(t);
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002184 if (currentIndex >= removeIndex && currentIndex != 0) {
2185 currentIndex--;
2186 }
2187 mTabControl.setCurrentTab(mTabControl.getTab(currentIndex));
Andrei Popescua5bf1de2009-09-23 16:39:23 +01002188 resetTitleIconAndProgress();
Leon Scroggins654899b2010-06-25 16:25:23 -04002189 updateLockIconToLatest();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002190 }
2191
Leon Scrogginsdcc5eeb2010-02-23 17:26:37 -05002192 /* package */ void goBackOnePageOrQuit() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002193 Tab current = mTabControl.getCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002194 if (current == null) {
2195 /*
2196 * Instead of finishing the activity, simply push this to the back
2197 * of the stack and let ActivityManager to choose the foreground
2198 * activity. As BrowserActivity is singleTask, it will be always the
2199 * root of the task. So we can use either true or false for
2200 * moveTaskToBack().
2201 */
2202 moveTaskToBack(true);
Grace Kloba00d85e72009-09-23 18:50:05 -07002203 return;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002204 }
2205 WebView w = current.getWebView();
2206 if (w.canGoBack()) {
2207 w.goBack();
2208 } else {
2209 // Check to see if we are closing a window that was created by
2210 // another window. If so, we switch back to that window.
Grace Kloba22ac16e2009-10-07 18:00:23 -07002211 Tab parent = current.getParentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002212 if (parent != null) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04002213 switchToTab(mTabControl.getTabIndex(parent));
2214 // Now we close the other tab
2215 closeTab(current);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002216 } else {
2217 if (current.closeOnExit()) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002218 // force the tab's inLoad() to be false as we are going to
2219 // either finish the activity or remove the tab. This will
2220 // ensure pauseWebViewTimers() taking action.
2221 mTabControl.getCurrentTab().clearInLoad();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002222 if (mTabControl.getTabCount() == 1) {
2223 finish();
2224 return;
2225 }
Mike Reed7bfa63b2009-05-28 11:08:32 -04002226 // call pauseWebViewTimers() now, we won't be able to call
2227 // it in onPause() as the WebView won't be valid.
Grace Klobaec1b5ad2009-08-18 08:42:32 -07002228 // Temporarily change mActivityInPause to be true as
2229 // pauseWebViewTimers() will do nothing if mActivityInPause
2230 // is false.
Grace Kloba918e1d72009-08-13 14:55:06 -07002231 boolean savedState = mActivityInPause;
2232 if (savedState) {
Grace Klobaec1b5ad2009-08-18 08:42:32 -07002233 Log.e(LOGTAG, "BrowserActivity is already paused "
2234 + "while handing goBackOnePageOrQuit.");
Grace Kloba918e1d72009-08-13 14:55:06 -07002235 }
2236 mActivityInPause = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -04002237 pauseWebViewTimers();
Grace Kloba918e1d72009-08-13 14:55:06 -07002238 mActivityInPause = savedState;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002239 removeTabFromContentView(current);
2240 mTabControl.removeTab(current);
2241 }
2242 /*
2243 * Instead of finishing the activity, simply push this to the back
2244 * of the stack and let ActivityManager to choose the foreground
2245 * activity. As BrowserActivity is singleTask, it will be always the
2246 * root of the task. So we can use either true or false for
2247 * moveTaskToBack().
2248 */
2249 moveTaskToBack(true);
2250 }
2251 }
2252 }
2253
Grace Kloba22ac16e2009-10-07 18:00:23 -07002254 boolean isMenuDown() {
2255 return mMenuIsDown;
2256 }
2257
Grace Kloba5942df02009-09-18 11:48:29 -07002258 @Override
2259 public boolean onKeyDown(int keyCode, KeyEvent event) {
Leon Scrogginsf65b50d2009-12-08 10:44:28 -05002260 // Even if MENU is already held down, we need to call to super to open
2261 // the IME on long press.
2262 if (KeyEvent.KEYCODE_MENU == keyCode) {
2263 mMenuIsDown = true;
2264 return super.onKeyDown(keyCode, event);
2265 }
Grace Kloba5942df02009-09-18 11:48:29 -07002266 // The default key mode is DEFAULT_KEYS_SEARCH_LOCAL. As the MENU is
2267 // still down, we don't want to trigger the search. Pretend to consume
2268 // the key and do nothing.
2269 if (mMenuIsDown) return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002270
Grace Kloba5942df02009-09-18 11:48:29 -07002271 switch(keyCode) {
Grace Kloba5942df02009-09-18 11:48:29 -07002272 case KeyEvent.KEYCODE_SPACE:
Grace Klobada0fe552009-09-22 18:17:24 -07002273 // WebView/WebTextView handle the keys in the KeyDown. As
2274 // the Activity's shortcut keys are only handled when WebView
2275 // doesn't, have to do it in onKeyDown instead of onKeyUp.
2276 if (event.isShiftPressed()) {
2277 getTopWindow().pageUp(false);
2278 } else {
2279 getTopWindow().pageDown(false);
2280 }
Grace Kloba5942df02009-09-18 11:48:29 -07002281 return true;
2282 case KeyEvent.KEYCODE_BACK:
2283 if (event.getRepeatCount() == 0) {
2284 event.startTracking();
2285 return true;
2286 } else if (mCustomView == null && mActiveTabsPage == null
2287 && event.isLongPress()) {
Michael Kolb68792c82010-08-09 16:39:18 -07002288 bookmarksOrHistoryPicker(true, false);
Grace Kloba5942df02009-09-18 11:48:29 -07002289 return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002290 }
Grace Kloba5942df02009-09-18 11:48:29 -07002291 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002292 }
Grace Kloba5942df02009-09-18 11:48:29 -07002293 return super.onKeyDown(keyCode, event);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002294 }
2295
Grace Kloba5942df02009-09-18 11:48:29 -07002296 @Override
2297 public boolean onKeyUp(int keyCode, KeyEvent event) {
2298 switch(keyCode) {
2299 case KeyEvent.KEYCODE_MENU:
2300 mMenuIsDown = false;
2301 break;
Grace Kloba5942df02009-09-18 11:48:29 -07002302 case KeyEvent.KEYCODE_BACK:
2303 if (event.isTracking() && !event.isCanceled()) {
2304 if (mCustomView != null) {
2305 // if a custom view is showing, hide it
Grace Kloba22ac16e2009-10-07 18:00:23 -07002306 mTabControl.getCurrentWebView().getWebChromeClient()
2307 .onHideCustomView();
Grace Kloba5942df02009-09-18 11:48:29 -07002308 } else if (mActiveTabsPage != null) {
2309 // if tab page is showing, hide it
2310 removeActiveTabPage(true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002311 } else {
Grace Kloba5942df02009-09-18 11:48:29 -07002312 WebView subwindow = mTabControl.getCurrentSubWindow();
2313 if (subwindow != null) {
2314 if (subwindow.canGoBack()) {
2315 subwindow.goBack();
2316 } else {
2317 dismissSubWindow(mTabControl.getCurrentTab());
2318 }
2319 } else {
2320 goBackOnePageOrQuit();
2321 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002322 }
Grace Kloba5942df02009-09-18 11:48:29 -07002323 return true;
2324 }
2325 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002326 }
Grace Kloba5942df02009-09-18 11:48:29 -07002327 return super.onKeyUp(keyCode, event);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002328 }
2329
Leon Scroggins68579392009-09-15 15:31:54 -04002330 /* package */ void stopLoading() {
Ben Murdochb7cc8b42009-09-28 10:59:09 +01002331 mDidStopLoad = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002332 resetTitleAndRevertLockIcon();
2333 WebView w = getTopWindow();
2334 w.stopLoading();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002335 // FIXME: before refactor, it is using mWebViewClient. So I keep the
2336 // same logic here. But for subwindow case, should we call into the main
2337 // WebView's onPageFinished as we never call its onPageStarted and if
2338 // the page finishes itself, we don't call onPageFinished.
2339 mTabControl.getCurrentWebView().getWebViewClient().onPageFinished(w,
2340 w.getUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08002341
2342 cancelStopToast();
2343 mStopToast = Toast
2344 .makeText(this, R.string.stopping, Toast.LENGTH_SHORT);
2345 mStopToast.show();
2346 }
2347
Grace Kloba22ac16e2009-10-07 18:00:23 -07002348 boolean didUserStopLoading() {
2349 return mDidStopLoad;
2350 }
2351
The Android Open Source Project0c908882009-03-03 19:32:16 -08002352 private void cancelStopToast() {
2353 if (mStopToast != null) {
2354 mStopToast.cancel();
2355 mStopToast = null;
2356 }
2357 }
2358
Grace Kloba22ac16e2009-10-07 18:00:23 -07002359 // called by a UI or non-UI thread to post the message
2360 public void postMessage(int what, int arg1, int arg2, Object obj,
2361 long delayMillis) {
2362 mHandler.sendMessageDelayed(mHandler.obtainMessage(what, arg1, arg2,
2363 obj), delayMillis);
2364 }
2365
2366 // called by a UI or non-UI thread to remove the message
2367 void removeMessages(int what, Object object) {
2368 mHandler.removeMessages(what, object);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002369 }
2370
2371 // public message ids
2372 public final static int LOAD_URL = 1001;
2373 public final static int STOP_LOAD = 1002;
2374
2375 // Message Ids
2376 private static final int FOCUS_NODE_HREF = 102;
Grace Kloba92c18a52009-07-31 23:48:32 -07002377 private static final int RELEASE_WAKELOCK = 107;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002378
Grace Kloba22ac16e2009-10-07 18:00:23 -07002379 static final int UPDATE_BOOKMARK_THUMBNAIL = 108;
Ben Murdoch2694e232009-09-29 09:41:11 +01002380
Ben Murdocheecb4e62010-07-06 16:30:38 +01002381 private static final int TOUCH_ICON_DOWNLOADED = 109;
2382
The Android Open Source Project0c908882009-03-03 19:32:16 -08002383 // Private handler for handling javascript and saving passwords
2384 private Handler mHandler = new Handler() {
2385
Michael Kolbe0a36662010-06-29 10:37:12 -07002386 @Override
The Android Open Source Project0c908882009-03-03 19:32:16 -08002387 public void handleMessage(Message msg) {
2388 switch (msg.what) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002389 case FOCUS_NODE_HREF:
Ben Murdoch2694e232009-09-29 09:41:11 +01002390 {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002391 String url = (String) msg.getData().get("url");
Ben Murdoch90d088c2009-11-17 18:14:04 +00002392 String title = (String) msg.getData().get("title");
The Android Open Source Project0c908882009-03-03 19:32:16 -08002393 if (url == null || url.length() == 0) {
2394 break;
2395 }
2396 HashMap focusNodeMap = (HashMap) msg.obj;
2397 WebView view = (WebView) focusNodeMap.get("webview");
2398 // Only apply the action if the top window did not change.
2399 if (getTopWindow() != view) {
2400 break;
2401 }
2402 switch (msg.arg1) {
2403 case R.id.open_context_menu_id:
2404 case R.id.view_image_context_menu_id:
Leon Scroggins92472e82010-02-17 16:32:28 -05002405 loadUrlFromContext(getTopWindow(), url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002406 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002407 case R.id.bookmark_context_menu_id:
2408 Intent intent = new Intent(BrowserActivity.this,
2409 AddBookmarkPage.class);
2410 intent.putExtra("url", url);
Ben Murdoch90d088c2009-11-17 18:14:04 +00002411 intent.putExtra("title", title);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002412 startActivity(intent);
2413 break;
2414 case R.id.share_link_context_menu_id:
Leon Scroggins3e204452010-05-10 11:06:03 -04002415 sharePage(BrowserActivity.this, title, url, null,
Leon Scroggins96afcb12009-12-10 12:35:56 -05002416 null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002417 break;
2418 case R.id.copy_link_context_menu_id:
2419 copy(url);
2420 break;
2421 case R.id.save_link_context_menu_id:
2422 case R.id.download_context_menu_id:
2423 onDownloadStartNoStream(url, null, null, null, -1);
2424 break;
2425 }
2426 break;
Ben Murdoch2694e232009-09-29 09:41:11 +01002427 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002428
2429 case LOAD_URL:
Leon Scroggins92472e82010-02-17 16:32:28 -05002430 loadUrlFromContext(getTopWindow(), (String) msg.obj);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002431 break;
2432
2433 case STOP_LOAD:
2434 stopLoading();
2435 break;
2436
The Android Open Source Project0c908882009-03-03 19:32:16 -08002437 case RELEASE_WAKELOCK:
2438 if (mWakeLock.isHeld()) {
2439 mWakeLock.release();
Grace Kloba5d0e02e2009-10-05 15:15:36 -07002440 // if we reach here, Browser should be still in the
2441 // background loading after WAKELOCK_TIMEOUT (5-min).
2442 // To avoid burning the battery, stop loading.
2443 mTabControl.stopAllLoading();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002444 }
2445 break;
Ben Murdoch2694e232009-09-29 09:41:11 +01002446
2447 case UPDATE_BOOKMARK_THUMBNAIL:
2448 WebView view = (WebView) msg.obj;
2449 if (view != null) {
2450 updateScreenshot(view);
2451 }
2452 break;
Ben Murdocheecb4e62010-07-06 16:30:38 +01002453
2454 case TOUCH_ICON_DOWNLOADED:
2455 Bundle b = msg.getData();
2456 showSaveToHomescreenDialog(b.getString("url"),
2457 b.getString("title"),
2458 (Bitmap) b.getParcelable("touchIcon"),
2459 (Bitmap) b.getParcelable("favicon"));
2460 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002461 }
2462 }
2463 };
2464
Leon Scroggins96afcb12009-12-10 12:35:56 -05002465 /**
2466 * Share a page, providing the title, url, favicon, and a screenshot. Uses
2467 * an {@link Intent} to launch the Activity chooser.
2468 * @param c Context used to launch a new Activity.
2469 * @param title Title of the page. Stored in the Intent with
Paul Westbrook03e6d392010-02-12 10:33:29 -08002470 * {@link Intent#EXTRA_SUBJECT}
Leon Scroggins96afcb12009-12-10 12:35:56 -05002471 * @param url URL of the page. Stored in the Intent with
2472 * {@link Intent#EXTRA_TEXT}
2473 * @param favicon Bitmap of the favicon for the page. Stored in the Intent
2474 * with {@link Browser#EXTRA_SHARE_FAVICON}
2475 * @param screenshot Bitmap of a screenshot of the page. Stored in the
2476 * Intent with {@link Browser#EXTRA_SHARE_SCREENSHOT}
2477 */
2478 public static final void sharePage(Context c, String title, String url,
2479 Bitmap favicon, Bitmap screenshot) {
2480 Intent send = new Intent(Intent.ACTION_SEND);
2481 send.setType("text/plain");
2482 send.putExtra(Intent.EXTRA_TEXT, url);
Paul Westbrook03e6d392010-02-12 10:33:29 -08002483 send.putExtra(Intent.EXTRA_SUBJECT, title);
Leon Scroggins96afcb12009-12-10 12:35:56 -05002484 send.putExtra(Browser.EXTRA_SHARE_FAVICON, favicon);
2485 send.putExtra(Browser.EXTRA_SHARE_SCREENSHOT, screenshot);
2486 try {
2487 c.startActivity(Intent.createChooser(send, c.getString(
2488 R.string.choosertitle_sharevia)));
2489 } catch(android.content.ActivityNotFoundException ex) {
2490 // if no app handles it, do nothing
2491 }
2492 }
2493
Leon Scroggins89c6d362009-07-15 16:54:37 -04002494 private void updateScreenshot(WebView view) {
2495 // If this is a bookmarked site, add a screenshot to the database.
2496 // FIXME: When should we update? Every time?
2497 // FIXME: Would like to make sure there is actually something to
2498 // draw, but the API for that (WebViewCore.pictureReady()) is not
2499 // currently accessible here.
Ben Murdochaac7aa62009-09-17 16:57:40 +01002500
Ben Murdoch87cc65d2010-06-29 20:34:10 +01002501 final Bitmap bm = createScreenshot(view, getDesiredThumbnailWidth(this),
2502 getDesiredThumbnailHeight(this));
Patrick Scottcb192b52010-04-14 14:38:55 -04002503 if (bm == null) {
2504 return;
Leon Scroggins89c6d362009-07-15 16:54:37 -04002505 }
Patrick Scottcb192b52010-04-14 14:38:55 -04002506
2507 final ContentResolver cr = getContentResolver();
2508 final String url = view.getUrl();
2509 final String originalUrl = view.getOriginalUrl();
2510
2511 new AsyncTask<Void, Void, Void>() {
2512 @Override
2513 protected Void doInBackground(Void... unused) {
2514 Cursor c = null;
2515 try {
Jeff Hamilton84029622010-08-05 14:29:28 -05002516 c = Bookmarks.queryBookmarksForUrl(
Jeff Hamilton8ce956c2010-08-17 11:13:53 -05002517 cr, originalUrl, url);
Patrick Scottcb192b52010-04-14 14:38:55 -04002518 if (c != null) {
2519 if (c.moveToFirst()) {
2520 ContentValues values = new ContentValues();
2521 final ByteArrayOutputStream os
2522 = new ByteArrayOutputStream();
2523 bm.compress(Bitmap.CompressFormat.PNG, 100, os);
Jeff Hamilton8ce956c2010-08-17 11:13:53 -05002524 values.put(BrowserContract.Bookmarks.THUMBNAIL,
Patrick Scottcb192b52010-04-14 14:38:55 -04002525 os.toByteArray());
2526 do {
2527 cr.update(ContentUris.withAppendedId(
Jeff Hamilton8ce956c2010-08-17 11:13:53 -05002528 BrowserContract.Bookmarks.CONTENT_URI, c.getLong(0)),
Patrick Scottcb192b52010-04-14 14:38:55 -04002529 values, null, null);
2530 } while (c.moveToNext());
2531 }
2532 }
2533 } catch (IllegalStateException e) {
2534 // Ignore
2535 } finally {
2536 if (c != null) c.close();
2537 }
2538 return null;
2539 }
2540 }.execute();
Leon Scroggins89c6d362009-07-15 16:54:37 -04002541 }
2542
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002543 /**
Leon Scrogginsf8551612009-09-24 16:06:02 -04002544 * Values for the size of the thumbnail created when taking a screenshot.
2545 * Lazily initialized. Instead of using these directly, use
2546 * getDesiredThumbnailWidth() or getDesiredThumbnailHeight().
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002547 */
Leon Scrogginsf8551612009-09-24 16:06:02 -04002548 private static int THUMBNAIL_WIDTH = 0;
2549 private static int THUMBNAIL_HEIGHT = 0;
2550
2551 /**
2552 * Return the desired width for thumbnail screenshots, which are stored in
2553 * the database, and used on the bookmarks screen.
2554 * @param context Context for finding out the density of the screen.
2555 * @return int desired width for thumbnail screenshot.
2556 */
2557 /* package */ static int getDesiredThumbnailWidth(Context context) {
2558 if (THUMBNAIL_WIDTH == 0) {
2559 float density = context.getResources().getDisplayMetrics().density;
2560 THUMBNAIL_WIDTH = (int) (90 * density);
2561 THUMBNAIL_HEIGHT = (int) (80 * density);
2562 }
2563 return THUMBNAIL_WIDTH;
2564 }
2565
2566 /**
2567 * Return the desired height for thumbnail screenshots, which are stored in
2568 * the database, and used on the bookmarks screen.
2569 * @param context Context for finding out the density of the screen.
2570 * @return int desired height for thumbnail screenshot.
2571 */
2572 /* package */ static int getDesiredThumbnailHeight(Context context) {
2573 // To ensure that they are both initialized.
2574 getDesiredThumbnailWidth(context);
2575 return THUMBNAIL_HEIGHT;
2576 }
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002577
Ben Murdoch87cc65d2010-06-29 20:34:10 +01002578 private Bitmap createScreenshot(WebView view, int width, int height) {
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002579 Picture thumbnail = view.capturePicture();
Leon Scroggins45800572009-09-29 16:38:47 -04002580 if (thumbnail == null) {
2581 return null;
2582 }
Ben Murdoch87cc65d2010-06-29 20:34:10 +01002583 Bitmap bm = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002584 Canvas canvas = new Canvas(bm);
2585 // May need to tweak these values to determine what is the
2586 // best scale factor
Ben Murdoch2694e232009-09-29 09:41:11 +01002587 int thumbnailWidth = thumbnail.getWidth();
Ben Murdochae59c3f2009-10-20 18:30:28 +01002588 int thumbnailHeight = thumbnail.getHeight();
2589 float scaleFactorX = 1.0f;
2590 float scaleFactorY = 1.0f;
Ben Murdoch2694e232009-09-29 09:41:11 +01002591 if (thumbnailWidth > 0) {
Ben Murdoch87cc65d2010-06-29 20:34:10 +01002592 scaleFactorX = (float) width / (float)thumbnailWidth;
Ben Murdochae59c3f2009-10-20 18:30:28 +01002593 } else {
2594 return null;
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002595 }
Ben Murdochae59c3f2009-10-20 18:30:28 +01002596
2597 if (view.getWidth() > view.getHeight() &&
2598 thumbnailHeight < view.getHeight() && thumbnailHeight > 0) {
2599 // If the device is in landscape and the page is shorter
2600 // than the height of the view, stretch the thumbnail to fill the
2601 // space.
Ben Murdoch87cc65d2010-06-29 20:34:10 +01002602 scaleFactorY = (float) height / (float)thumbnailHeight;
Ben Murdochae59c3f2009-10-20 18:30:28 +01002603 } else {
2604 // In the portrait case, this looks nice.
2605 scaleFactorY = scaleFactorX;
2606 }
2607
2608 canvas.scale(scaleFactorX, scaleFactorY);
2609
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002610 thumbnail.draw(canvas);
2611 return bm;
2612 }
2613
The Android Open Source Project0c908882009-03-03 19:32:16 -08002614 // -------------------------------------------------------------------------
Grace Kloba22ac16e2009-10-07 18:00:23 -07002615 // Helper function for WebViewClient.
The Android Open Source Project0c908882009-03-03 19:32:16 -08002616 //-------------------------------------------------------------------------
2617
2618 // Use in overrideUrlLoading
2619 /* package */ final static String SCHEME_WTAI = "wtai://wp/";
2620 /* package */ final static String SCHEME_WTAI_MC = "wtai://wp/mc;";
2621 /* package */ final static String SCHEME_WTAI_SD = "wtai://wp/sd;";
2622 /* package */ final static String SCHEME_WTAI_AP = "wtai://wp/ap;";
2623
Leon Scroggins92472e82010-02-17 16:32:28 -05002624 // Keep this initial progress in sync with initialProgressValue (* 100)
2625 // in ProgressTracker.cpp
2626 private final static int INITIAL_PROGRESS = 10;
2627
Grace Kloba22ac16e2009-10-07 18:00:23 -07002628 void onPageStarted(WebView view, String url, Bitmap favicon) {
2629 // when BrowserActivity just starts, onPageStarted may be called before
2630 // onResume as it is triggered from onCreate. Call resumeWebViewTimers
2631 // to start the timer. As we won't switch tabs while an activity is in
2632 // pause state, we can ensure calling resume and pause in pair.
2633 if (mActivityInPause) resumeWebViewTimers();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002634
Grace Kloba22ac16e2009-10-07 18:00:23 -07002635 resetLockIcon(url);
2636 setUrlTitle(url, null);
2637 setFavicon(favicon);
Leon Scroggins8cf8f682009-11-04 11:13:50 -08002638 // Show some progress so that the user knows the page is beginning to
2639 // load
Leon Scroggins92472e82010-02-17 16:32:28 -05002640 onProgressChanged(view, INITIAL_PROGRESS);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002641 mDidStopLoad = false;
Grace Kloba22ac16e2009-10-07 18:00:23 -07002642 if (!mIsNetworkUp) createAndShowNetworkDialog();
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04002643 endActionMode();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002644 if (mSettings.isTracing()) {
2645 String host;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002646 try {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002647 WebAddress uri = new WebAddress(url);
2648 host = uri.mHost;
2649 } catch (android.net.ParseException ex) {
2650 host = "browser";
The Android Open Source Project0c908882009-03-03 19:32:16 -08002651 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002652 host = host.replace('.', '_');
2653 host += ".trace";
2654 mInTrace = true;
2655 Debug.startMethodTracing(host, 20 * 1024 * 1024);
2656 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002657
Grace Kloba22ac16e2009-10-07 18:00:23 -07002658 // Performance probe
2659 if (false) {
2660 mStart = SystemClock.uptimeMillis();
2661 mProcessStart = Process.getElapsedCpuTime();
2662 long[] sysCpu = new long[7];
2663 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2664 sysCpu, null)) {
2665 mUserStart = sysCpu[0] + sysCpu[1];
2666 mSystemStart = sysCpu[2];
2667 mIdleStart = sysCpu[3];
2668 mIrqStart = sysCpu[4] + sysCpu[5] + sysCpu[6];
2669 }
2670 mUiStart = SystemClock.currentThreadTimeMillis();
2671 }
2672 }
2673
2674 void onPageFinished(WebView view, String url) {
2675 // Reset the title and icon in case we stopped a provisional load.
2676 resetTitleAndIcon(view);
2677 // Update the lock icon image only once we are done loading
2678 updateLockIconToLatest();
2679 // pause the WebView timer and release the wake lock if it is finished
2680 // while BrowserActivity is in pause state.
2681 if (mActivityInPause && pauseWebViewTimers()) {
2682 if (mWakeLock.isHeld()) {
2683 mHandler.removeMessages(RELEASE_WAKELOCK);
2684 mWakeLock.release();
2685 }
2686 }
2687
2688 // Performance probe
2689 if (false) {
2690 long[] sysCpu = new long[7];
2691 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2692 sysCpu, null)) {
2693 String uiInfo = "UI thread used "
2694 + (SystemClock.currentThreadTimeMillis() - mUiStart)
2695 + " ms";
2696 if (LOGD_ENABLED) {
2697 Log.d(LOGTAG, uiInfo);
2698 }
2699 //The string that gets written to the log
2700 String performanceString = "It took total "
2701 + (SystemClock.uptimeMillis() - mStart)
2702 + " ms clock time to load the page."
2703 + "\nbrowser process used "
2704 + (Process.getElapsedCpuTime() - mProcessStart)
2705 + " ms, user processes used "
2706 + (sysCpu[0] + sysCpu[1] - mUserStart) * 10
2707 + " ms, kernel used "
2708 + (sysCpu[2] - mSystemStart) * 10
2709 + " ms, idle took " + (sysCpu[3] - mIdleStart) * 10
2710 + " ms and irq took "
2711 + (sysCpu[4] + sysCpu[5] + sysCpu[6] - mIrqStart)
2712 * 10 + " ms, " + uiInfo;
2713 if (LOGD_ENABLED) {
2714 Log.d(LOGTAG, performanceString + "\nWebpage: " + url);
2715 }
2716 if (url != null) {
2717 // strip the url to maintain consistency
2718 String newUrl = new String(url);
2719 if (newUrl.startsWith("http://www.")) {
2720 newUrl = newUrl.substring(11);
2721 } else if (newUrl.startsWith("http://")) {
2722 newUrl = newUrl.substring(7);
2723 } else if (newUrl.startsWith("https://www.")) {
2724 newUrl = newUrl.substring(12);
2725 } else if (newUrl.startsWith("https://")) {
2726 newUrl = newUrl.substring(8);
2727 }
2728 if (LOGD_ENABLED) {
2729 Log.d(LOGTAG, newUrl + " loaded");
2730 }
Grace Kloba5b078b52009-06-24 20:23:41 -07002731 }
2732 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002733 }
Grace Kloba5b078b52009-06-24 20:23:41 -07002734
Grace Kloba22ac16e2009-10-07 18:00:23 -07002735 if (mInTrace) {
2736 mInTrace = false;
2737 Debug.stopMethodTracing();
2738 }
2739 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002740
Grace Klobae7fe26b2010-06-28 16:23:33 -07002741 private void closeEmptyChildTab() {
2742 Tab current = mTabControl.getCurrentTab();
2743 if (current != null
2744 && current.getWebView().copyBackForwardList().getSize() == 0) {
2745 Tab parent = current.getParentTab();
2746 if (parent != null) {
2747 switchToTab(mTabControl.getTabIndex(parent));
2748 closeTab(current);
2749 }
2750 }
2751 }
2752
Grace Kloba22ac16e2009-10-07 18:00:23 -07002753 boolean shouldOverrideUrlLoading(WebView view, String url) {
2754 if (url.startsWith(SCHEME_WTAI)) {
2755 // wtai://wp/mc;number
2756 // number=string(phone-number)
2757 if (url.startsWith(SCHEME_WTAI_MC)) {
2758 Intent intent = new Intent(Intent.ACTION_VIEW,
2759 Uri.parse(WebView.SCHEME_TEL +
2760 url.substring(SCHEME_WTAI_MC.length())));
2761 startActivity(intent);
Grace Klobae7fe26b2010-06-28 16:23:33 -07002762 // before leaving BrowserActivity, close the empty child tab.
2763 // If a new tab is created through JavaScript open to load this
2764 // url, we would like to close it as we will load this url in a
2765 // different Activity.
2766 closeEmptyChildTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002767 return true;
2768 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002769 // wtai://wp/sd;dtmf
2770 // dtmf=string(dialstring)
2771 if (url.startsWith(SCHEME_WTAI_SD)) {
2772 // TODO: only send when there is active voice connection
2773 return false;
2774 }
2775 // wtai://wp/ap;number;name
2776 // number=string(phone-number)
2777 // name=string
2778 if (url.startsWith(SCHEME_WTAI_AP)) {
2779 // TODO
2780 return false;
2781 }
2782 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002783
Grace Kloba22ac16e2009-10-07 18:00:23 -07002784 // The "about:" schemes are internal to the browser; don't want these to
2785 // be dispatched to other apps.
2786 if (url.startsWith("about:")) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002787 return false;
2788 }
2789
Jeff Davidson43610292010-07-16 16:03:58 -07002790 // If this is a Google search, attempt to add an RLZ string (if one isn't already present).
2791 if (rlzProviderPresent()) {
2792 Uri siteUri = Uri.parse(url);
2793 if (needsRlzString(siteUri)) {
2794 String rlz = null;
2795 Cursor cur = null;
2796 try {
2797 cur = getContentResolver().query(getRlzUri(), null, null, null, null);
2798 if (cur != null && cur.moveToFirst() && !cur.isNull(0)) {
2799 url = siteUri.buildUpon()
2800 .appendQueryParameter("rlz", cur.getString(0))
2801 .build().toString();
2802 }
2803 } finally {
2804 if (cur != null) {
2805 cur.close();
2806 }
2807 }
2808 loadUrl(view, url);
2809 return true;
2810 }
2811 }
2812
Grace Kloba22ac16e2009-10-07 18:00:23 -07002813 Intent intent;
2814 // perform generic parsing of the URI to turn it into an Intent.
2815 try {
2816 intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME);
2817 } catch (URISyntaxException ex) {
2818 Log.w("Browser", "Bad URI " + url + ": " + ex.getMessage());
2819 return false;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002820 }
2821
Grace Kloba22ac16e2009-10-07 18:00:23 -07002822 // check whether the intent can be resolved. If not, we will see
2823 // whether we can download it from the Market.
2824 if (getPackageManager().resolveActivity(intent, 0) == null) {
2825 String packagename = intent.getPackage();
2826 if (packagename != null) {
2827 intent = new Intent(Intent.ACTION_VIEW, Uri
2828 .parse("market://search?q=pname:" + packagename));
2829 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2830 startActivity(intent);
Grace Klobae7fe26b2010-06-28 16:23:33 -07002831 // before leaving BrowserActivity, close the empty child tab.
2832 // If a new tab is created through JavaScript open to load this
2833 // url, we would like to close it as we will load this url in a
2834 // different Activity.
2835 closeEmptyChildTab();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002836 return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002837 } else {
2838 return false;
2839 }
2840 }
2841
Grace Kloba22ac16e2009-10-07 18:00:23 -07002842 // sanitize the Intent, ensuring web pages can not bypass browser
2843 // security (only access to BROWSABLE activities).
2844 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2845 intent.setComponent(null);
2846 try {
2847 if (startActivityIfNeeded(intent, -1)) {
Grace Klobae7fe26b2010-06-28 16:23:33 -07002848 // before leaving BrowserActivity, close the empty child tab.
2849 // If a new tab is created through JavaScript open to load this
2850 // url, we would like to close it as we will load this url in a
2851 // different Activity.
2852 closeEmptyChildTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002853 return true;
2854 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002855 } catch (ActivityNotFoundException ex) {
2856 // ignore the error. If no application can handle the URL,
2857 // eg about:blank, assume the browser can handle it.
2858 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002859
Grace Kloba22ac16e2009-10-07 18:00:23 -07002860 if (mMenuIsDown) {
Michael Kolb68792c82010-08-09 16:39:18 -07002861 openTab(url, false);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002862 closeOptionsMenu();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002863 return true;
2864 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002865 return false;
2866 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002867
Jeff Davidson43610292010-07-16 16:03:58 -07002868 // Determine whether the RLZ provider is present on the system.
2869 private boolean rlzProviderPresent() {
2870 if (mIsProviderPresent == null) {
2871 PackageManager pm = getPackageManager();
2872 mIsProviderPresent = pm.resolveContentProvider(BrowserSettings.RLZ_PROVIDER, 0) != null;
2873 }
2874 return mIsProviderPresent;
2875 }
2876
2877 // Retrieve the RLZ access point string and cache the URI used to retrieve RLZ values.
2878 private Uri getRlzUri() {
2879 if (mRlzUri == null) {
2880 String ap = getResources().getString(R.string.rlz_access_point);
2881 mRlzUri = Uri.withAppendedPath(BrowserSettings.RLZ_PROVIDER_URI, ap);
2882 }
2883 return mRlzUri;
2884 }
2885
2886 // Determine if this URI appears to be for a Google search and does not have an RLZ parameter.
2887 // Taken largely from Chrome source, src/chrome/browser/google_url_tracker.cc
2888 private static boolean needsRlzString(Uri uri) {
2889 if ((uri.getQueryParameter("q") != null) && (uri.getQueryParameter("rlz") == null)) {
2890 String host = uri.getHost();
2891 if (host == null) {
2892 return false;
2893 }
2894 String[] hostComponents = host.split("\\.");
2895
2896 if (hostComponents.length < 2) {
2897 return false;
2898 }
2899 int googleComponent = hostComponents.length - 2;
2900 String component = hostComponents[googleComponent];
2901 if (!"google".equals(component)) {
2902 if (hostComponents.length < 3 ||
2903 (!"co".equals(component) && !"com".equals(component))) {
2904 return false;
2905 }
2906 googleComponent = hostComponents.length - 3;
2907 if (!"google".equals(hostComponents[googleComponent])) {
2908 return false;
2909 }
2910 }
2911
2912 // Google corp network handling.
2913 if (googleComponent > 0 && "corp".equals(hostComponents[googleComponent - 1])) {
2914 return false;
2915 }
2916
2917 return true;
2918 }
2919 return false;
2920 }
2921
Grace Kloba22ac16e2009-10-07 18:00:23 -07002922 // -------------------------------------------------------------------------
2923 // Helper function for WebChromeClient
2924 // -------------------------------------------------------------------------
The Android Open Source Project0c908882009-03-03 19:32:16 -08002925
Grace Kloba22ac16e2009-10-07 18:00:23 -07002926 void onProgressChanged(WebView view, int newProgress) {
Michael Kolba2b2ba82010-08-04 17:54:03 -07002927
2928 // On the phone, the fake title bar will always cover up the
2929 // regular title bar (or the regular one is offscreen), so only the
2930 // fake title bar needs to change its progress
2931 mFakeTitleBar.setProgress(newProgress);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002932
Grace Kloba22ac16e2009-10-07 18:00:23 -07002933 if (newProgress == 100) {
2934 // onProgressChanged() may continue to be called after the main
2935 // frame has finished loading, as any remaining sub frames continue
2936 // to load. We'll only get called once though with newProgress as
2937 // 100 when everything is loaded. (onPageFinished is called once
2938 // when the main frame completes loading regardless of the state of
2939 // any sub frames so calls to onProgressChanges may continue after
2940 // onPageFinished has executed)
2941 if (mInLoad) {
2942 mInLoad = false;
Leon Scrogginsa27ff192009-09-14 12:58:04 -04002943 updateInLoadMenuItems();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002944 // If the options menu is open, leave the title bar
2945 if (!mOptionsMenuOpen || !mIconView) {
2946 hideFakeTitleBar();
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07002947 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002948 }
Leon Scrogginsaa37e7f2010-03-05 11:51:20 -05002949 } else {
2950 if (!mInLoad) {
2951 // onPageFinished may have already been called but a subframe is
2952 // still loading and updating the progress. Reset mInLoad and
2953 // update the menu items.
2954 mInLoad = true;
2955 updateInLoadMenuItems();
2956 }
2957 // When the page first begins to load, the Activity may still be
2958 // paused, in which case showFakeTitleBar will do nothing. Call
2959 // again as the page continues to load so that it will be shown.
2960 // (Calling it will the fake title bar is already showing will also
2961 // do nothing.
Grace Kloba22ac16e2009-10-07 18:00:23 -07002962 if (!mOptionsMenuOpen || mIconView) {
2963 // This page has begun to load, so show the title bar
2964 showFakeTitleBar();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002965 }
2966 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002967 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002968
Grace Kloba22ac16e2009-10-07 18:00:23 -07002969 void onShowCustomView(View view, WebChromeClient.CustomViewCallback callback) {
Derek Sollenberger8ff57db2009-12-08 15:39:55 -05002970 // if a view already exists then immediately terminate the new one
2971 if (mCustomView != null) {
2972 callback.onCustomViewHidden();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002973 return;
Derek Sollenberger8ff57db2009-12-08 15:39:55 -05002974 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002975
2976 // Add the custom view to its container.
2977 mCustomViewContainer.addView(view, COVER_SCREEN_GRAVITY_CENTER);
2978 mCustomView = view;
2979 mCustomViewCallback = callback;
2980 // Save the menu state and set it to empty while the custom
2981 // view is showing.
2982 mOldMenuState = mMenuState;
2983 mMenuState = EMPTY_MENU;
2984 // Hide the content view.
2985 mContentView.setVisibility(View.GONE);
2986 // Finally show the custom view container.
Andrei Popescu163ab742009-10-20 17:58:23 +01002987 setStatusBarVisibility(false);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002988 mCustomViewContainer.setVisibility(View.VISIBLE);
2989 mCustomViewContainer.bringToFront();
2990 }
2991
2992 void onHideCustomView() {
2993 if (mCustomView == null)
2994 return;
2995
2996 // Hide the custom view.
2997 mCustomView.setVisibility(View.GONE);
2998 // Remove the custom view from its container.
2999 mCustomViewContainer.removeView(mCustomView);
3000 mCustomView = null;
3001 // Reset the old menu state.
3002 mMenuState = mOldMenuState;
3003 mOldMenuState = EMPTY_MENU;
3004 mCustomViewContainer.setVisibility(View.GONE);
3005 mCustomViewCallback.onCustomViewHidden();
3006 // Show the content view.
Andrei Popescu163ab742009-10-20 17:58:23 +01003007 setStatusBarVisibility(true);
Grace Kloba22ac16e2009-10-07 18:00:23 -07003008 mContentView.setVisibility(View.VISIBLE);
3009 }
3010
3011 Bitmap getDefaultVideoPoster() {
3012 if (mDefaultVideoPoster == null) {
3013 mDefaultVideoPoster = BitmapFactory.decodeResource(
3014 getResources(), R.drawable.default_video_poster);
Patrick Scott3918d442009-08-04 13:22:29 -04003015 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07003016 return mDefaultVideoPoster;
3017 }
Patrick Scott3918d442009-08-04 13:22:29 -04003018
Grace Kloba22ac16e2009-10-07 18:00:23 -07003019 View getVideoLoadingProgressView() {
3020 if (mVideoProgressView == null) {
3021 LayoutInflater inflater = LayoutInflater.from(BrowserActivity.this);
3022 mVideoProgressView = inflater.inflate(
3023 R.layout.video_loading_progress, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003024 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07003025 return mVideoProgressView;
3026 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003027
Leon Scroggins8d5fa432009-10-02 15:55:59 -04003028 /*
3029 * The Object used to inform the WebView of the file to upload.
3030 */
3031 private ValueCallback<Uri> mUploadMessage;
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003032 private String mCameraFilePath;
Leon Scroggins8d5fa432009-10-02 15:55:59 -04003033
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003034 void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
3035
3036 final String imageMimeType = "image/*";
Ben Murdoch6af492a2010-06-15 12:38:17 +01003037 final String videoMimeType = "video/*";
Ben Murdoch039bd472010-07-21 21:26:57 +01003038 final String audioMimeType = "audio/*";
Ben Murdochb50d7402010-07-16 12:42:22 +01003039 final String mediaSourceKey = "capture";
Ben Murdoch6af492a2010-06-15 12:38:17 +01003040 final String mediaSourceValueCamera = "camera";
Ben Murdochb50d7402010-07-16 12:42:22 +01003041 final String mediaSourceValueFileSystem = "filesystem";
Ben Murdoch6af492a2010-06-15 12:38:17 +01003042 final String mediaSourceValueCamcorder = "camcorder";
Ben Murdoch039bd472010-07-21 21:26:57 +01003043 final String mediaSourceValueMicrophone = "microphone";
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003044
Ben Murdoch039bd472010-07-21 21:26:57 +01003045 // media source can be 'filesystem' or 'camera' or 'camcorder' or 'microphone'.
Ben Murdoch6af492a2010-06-15 12:38:17 +01003046 String mediaSource = "";
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003047
Ben Murdoch6af492a2010-06-15 12:38:17 +01003048 // We add the camera intent if there was no accept type (or '*/*' or 'image/*').
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003049 boolean addCameraIntent = true;
Ben Murdoch6af492a2010-06-15 12:38:17 +01003050 // We add the camcorder intent if there was no accept type (or '*/*' or 'video/*').
3051 boolean addCamcorderIntent = true;
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003052
Ben Murdoch6af492a2010-06-15 12:38:17 +01003053 if (mUploadMessage != null) {
3054 // Already a file picker operation in progress.
3055 return;
3056 }
3057
Grace Kloba22ac16e2009-10-07 18:00:23 -07003058 mUploadMessage = uploadMsg;
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003059
3060 // Parse the accept type.
3061 String params[] = acceptType.split(";");
3062 String mimeType = params[0];
3063
3064 for (String p : params) {
3065 String[] keyValue = p.split("=");
3066 if (keyValue.length == 2) {
3067 // Process key=value parameters.
Ben Murdoch6af492a2010-06-15 12:38:17 +01003068 if (mediaSourceKey.equals(keyValue[0])) {
3069 mediaSource = keyValue[1];
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003070 }
3071 }
3072 }
3073
3074 // This intent will display the standard OPENABLE file picker.
Grace Kloba22ac16e2009-10-07 18:00:23 -07003075 Intent i = new Intent(Intent.ACTION_GET_CONTENT);
3076 i.addCategory(Intent.CATEGORY_OPENABLE);
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003077
3078 // Create an intent to add to the standard file picker that will
3079 // capture an image from the camera. We'll combine this intent with
3080 // the standard OPENABLE picker unless the web developer specifically
3081 // requested the camera or gallery be opened by passing a parameter
3082 // in the accept type.
3083 Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
3084 File externalDataDir = Environment.getExternalStoragePublicDirectory(
3085 Environment.DIRECTORY_DCIM);
3086 File cameraDataDir = new File(externalDataDir.getAbsolutePath() +
3087 File.separator + "browser-photos");
3088 cameraDataDir.mkdirs();
3089 mCameraFilePath = cameraDataDir.getAbsolutePath() + File.separator +
3090 System.currentTimeMillis() + ".jpg";
3091 cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(mCameraFilePath)));
3092
Ben Murdoch6af492a2010-06-15 12:38:17 +01003093 Intent camcorderIntent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
3094
Ben Murdoch039bd472010-07-21 21:26:57 +01003095 Intent soundRecIntent = new Intent(MediaStore.Audio.Media.RECORD_SOUND_ACTION);
3096
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003097 if (mimeType.equals(imageMimeType)) {
3098 i.setType(imageMimeType);
Ben Murdoch6af492a2010-06-15 12:38:17 +01003099 addCamcorderIntent = false;
3100 if (mediaSource.equals(mediaSourceValueCamera)) {
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003101 // Specified 'image/*' and requested the camera, so go ahead and launch the camera
3102 // directly.
3103 BrowserActivity.this.startActivityForResult(cameraIntent, FILE_SELECTED);
3104 return;
Ben Murdochb50d7402010-07-16 12:42:22 +01003105 } else if (mediaSource.equals(mediaSourceValueFileSystem)) {
3106 // Specified filesytem as the source, so don't want to consider the camera.
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003107 addCameraIntent = false;
3108 }
Ben Murdoch6af492a2010-06-15 12:38:17 +01003109 } else if (mimeType.equals(videoMimeType)) {
3110 i.setType(videoMimeType);
3111 addCameraIntent = false;
3112 // The camcorder saves it's own file and returns it to us in the intent, so
3113 // we don't need to generate one here.
3114 mCameraFilePath = null;
3115
3116 if (mediaSource.equals(mediaSourceValueCamcorder)) {
Ben Murdoch039bd472010-07-21 21:26:57 +01003117 // Specified 'video/*' and requested the camcorder, so go ahead and launch the
3118 // camcorder directly.
Ben Murdoch6af492a2010-06-15 12:38:17 +01003119 BrowserActivity.this.startActivityForResult(camcorderIntent, FILE_SELECTED);
3120 return;
Ben Murdochb50d7402010-07-16 12:42:22 +01003121 } else if (mediaSource.equals(mediaSourceValueFileSystem)) {
3122 // Specified filesystem as the source, so don't want to consider the camcorder.
Ben Murdoch6af492a2010-06-15 12:38:17 +01003123 addCamcorderIntent = false;
3124 }
Ben Murdoch039bd472010-07-21 21:26:57 +01003125 } else if (mimeType.equals(audioMimeType)) {
3126 i.setType(audioMimeType);
3127 addCameraIntent = false;
3128 addCamcorderIntent = false;
3129 if (mediaSource.equals(mediaSourceValueMicrophone)) {
3130 // Specified 'audio/*' and requested microphone, so go ahead and launch the sound
3131 // recorder.
3132 BrowserActivity.this.startActivityForResult(soundRecIntent, FILE_SELECTED);
3133 return;
3134 }
3135 // On a default system, there is no single option to open an audio "gallery". Both the
3136 // sound recorder and music browser respond to the OPENABLE/audio/* intent unlike the
3137 // image/* and video/* OPENABLE intents where the image / video gallery are the only
3138 // respondants (and so the user is not prompted by default).
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003139 } else {
3140 i.setType("*/*");
3141 }
3142
Ben Murdoch6af492a2010-06-15 12:38:17 +01003143 // Combine the chooser and the extra choices (like camera or camcorder)
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003144 Intent chooser = new Intent(Intent.ACTION_CHOOSER);
3145 chooser.putExtra(Intent.EXTRA_INTENT, i);
3146
Ben Murdoch6af492a2010-06-15 12:38:17 +01003147 Vector<Intent> extraInitialIntents = new Vector<Intent>(0);
3148
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003149 if (addCameraIntent) {
Ben Murdoch6af492a2010-06-15 12:38:17 +01003150 extraInitialIntents.add(cameraIntent);
3151 }
3152
3153 if (addCamcorderIntent) {
3154 extraInitialIntents.add(camcorderIntent);
3155 }
3156
3157 if (extraInitialIntents.size() > 0) {
3158 Intent[] extraIntents = new Intent[extraInitialIntents.size()];
3159 chooser.putExtra(Intent.EXTRA_INITIAL_INTENTS, extraInitialIntents.toArray(extraIntents));
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003160 }
3161
3162 chooser.putExtra(Intent.EXTRA_TITLE, getString(R.string.choose_upload));
3163 BrowserActivity.this.startActivityForResult(chooser, FILE_SELECTED);
Grace Kloba22ac16e2009-10-07 18:00:23 -07003164 }
3165
3166 // -------------------------------------------------------------------------
3167 // Implement functions for DownloadListener
3168 // -------------------------------------------------------------------------
3169
The Android Open Source Project0c908882009-03-03 19:32:16 -08003170 /**
3171 * Notify the host application a download should be done, or that
3172 * the data should be streamed if a streaming viewer is available.
3173 * @param url The full url to the content that should be downloaded
3174 * @param contentDisposition Content-disposition http header, if
3175 * present.
3176 * @param mimetype The mimetype of the content reported by the server
3177 * @param contentLength The file size reported by the server
3178 */
3179 public void onDownloadStart(String url, String userAgent,
3180 String contentDisposition, String mimetype, long contentLength) {
3181 // if we're dealing wih A/V content that's not explicitly marked
3182 // for download, check if it's streamable.
3183 if (contentDisposition == null
Patrick Scotte1fb9662009-08-31 14:31:52 -04003184 || !contentDisposition.regionMatches(
3185 true, 0, "attachment", 0, 10)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003186 // query the package manager to see if there's a registered handler
3187 // that matches.
3188 Intent intent = new Intent(Intent.ACTION_VIEW);
3189 intent.setDataAndType(Uri.parse(url), mimetype);
Patrick Scotte1fb9662009-08-31 14:31:52 -04003190 ResolveInfo info = getPackageManager().resolveActivity(intent,
3191 PackageManager.MATCH_DEFAULT_ONLY);
3192 if (info != null) {
3193 ComponentName myName = getComponentName();
3194 // If we resolved to ourselves, we don't want to attempt to
3195 // load the url only to try and download it again.
3196 if (!myName.getPackageName().equals(
3197 info.activityInfo.packageName)
3198 || !myName.getClassName().equals(
3199 info.activityInfo.name)) {
3200 // someone (other than us) knows how to handle this mime
3201 // type with this scheme, don't download.
3202 try {
3203 startActivity(intent);
3204 return;
3205 } catch (ActivityNotFoundException ex) {
3206 if (LOGD_ENABLED) {
3207 Log.d(LOGTAG, "activity not found for " + mimetype
3208 + " over " + Uri.parse(url).getScheme(),
3209 ex);
3210 }
3211 // Best behavior is to fall back to a download in this
3212 // case
The Android Open Source Project0c908882009-03-03 19:32:16 -08003213 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003214 }
3215 }
3216 }
3217 onDownloadStartNoStream(url, userAgent, contentDisposition, mimetype, contentLength);
3218 }
3219
Kristian Monsenfa52d172010-03-25 18:29:21 +00003220 // This is to work around the fact that java.net.URI throws Exceptions
3221 // instead of just encoding URL's properly
3222 // Helper method for onDownloadStartNoStream
3223 private static String encodePath(String path) {
3224 char[] chars = path.toCharArray();
3225
3226 boolean needed = false;
3227 for (char c : chars) {
3228 if (c == '[' || c == ']') {
3229 needed = true;
3230 break;
3231 }
3232 }
3233 if (needed == false) {
3234 return path;
3235 }
3236
3237 StringBuilder sb = new StringBuilder("");
3238 for (char c : chars) {
3239 if (c == '[' || c == ']') {
3240 sb.append('%');
3241 sb.append(Integer.toHexString(c));
3242 } else {
3243 sb.append(c);
3244 }
3245 }
3246
3247 return sb.toString();
3248 }
3249
The Android Open Source Project0c908882009-03-03 19:32:16 -08003250 /**
3251 * Notify the host application a download should be done, even if there
3252 * is a streaming viewer available for thise type.
3253 * @param url The full url to the content that should be downloaded
3254 * @param contentDisposition Content-disposition http header, if
3255 * present.
3256 * @param mimetype The mimetype of the content reported by the server
3257 * @param contentLength The file size reported by the server
3258 */
3259 /*package */ void onDownloadStartNoStream(String url, String userAgent,
3260 String contentDisposition, String mimetype, long contentLength) {
3261
3262 String filename = URLUtil.guessFileName(url,
3263 contentDisposition, mimetype);
3264
3265 // Check to see if we have an SDCard
3266 String status = Environment.getExternalStorageState();
3267 if (!status.equals(Environment.MEDIA_MOUNTED)) {
3268 int title;
3269 String msg;
3270
3271 // Check to see if the SDCard is busy, same as the music app
3272 if (status.equals(Environment.MEDIA_SHARED)) {
3273 msg = getString(R.string.download_sdcard_busy_dlg_msg);
3274 title = R.string.download_sdcard_busy_dlg_title;
3275 } else {
3276 msg = getString(R.string.download_no_sdcard_dlg_msg, filename);
3277 title = R.string.download_no_sdcard_dlg_title;
3278 }
3279
3280 new AlertDialog.Builder(this)
3281 .setTitle(title)
3282 .setIcon(android.R.drawable.ic_dialog_alert)
3283 .setMessage(msg)
3284 .setPositiveButton(R.string.ok, null)
3285 .show();
3286 return;
3287 }
3288
Kristian Monsenfa52d172010-03-25 18:29:21 +00003289 // java.net.URI is a lot stricter than KURL so we have to encode some
3290 // extra characters. Fix for b 2538060 and b 1634719
3291 WebAddress webAddress;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003292 try {
Kristian Monsenfa52d172010-03-25 18:29:21 +00003293 webAddress = new WebAddress(url);
3294 webAddress.mPath = encodePath(webAddress.mPath);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003295 } catch (Exception e) {
Kristian Monsenfa52d172010-03-25 18:29:21 +00003296 // This only happens for very bad urls, we want to chatch the
3297 // exception here
3298 Log.e(LOGTAG, "Exception trying to parse url:" + url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003299 return;
3300 }
3301
3302 // XXX: Have to use the old url since the cookies were stored using the
3303 // old percent-encoded url.
3304 String cookies = CookieManager.getInstance().getCookie(url);
3305
3306 ContentValues values = new ContentValues();
Kristian Monsenfa52d172010-03-25 18:29:21 +00003307 values.put(Downloads.Impl.COLUMN_URI, webAddress.toString());
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08003308 values.put(Downloads.Impl.COLUMN_COOKIE_DATA, cookies);
3309 values.put(Downloads.Impl.COLUMN_USER_AGENT, userAgent);
3310 values.put(Downloads.Impl.COLUMN_NOTIFICATION_PACKAGE,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003311 getPackageName());
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08003312 values.put(Downloads.Impl.COLUMN_NOTIFICATION_CLASS,
Leon Scrogginsa563d092010-04-19 16:53:49 -04003313 OpenDownloadReceiver.class.getCanonicalName());
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08003314 values.put(Downloads.Impl.COLUMN_VISIBILITY,
3315 Downloads.Impl.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
3316 values.put(Downloads.Impl.COLUMN_MIME_TYPE, mimetype);
3317 values.put(Downloads.Impl.COLUMN_FILE_NAME_HINT, filename);
Kristian Monsenfa52d172010-03-25 18:29:21 +00003318 values.put(Downloads.Impl.COLUMN_DESCRIPTION, webAddress.mHost);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003319 if (contentLength > 0) {
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08003320 values.put(Downloads.Impl.COLUMN_TOTAL_BYTES, contentLength);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003321 }
3322 if (mimetype == null) {
3323 // We must have long pressed on a link or image to download it. We
3324 // are not sure of the mimetype in this case, so do a head request
3325 new FetchUrlMimeType(this).execute(values);
3326 } else {
3327 final Uri contentUri =
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08003328 getContentResolver().insert(Downloads.Impl.CONTENT_URI, values);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003329 }
Leon Scroggins9191a7f2010-03-18 14:44:44 -04003330 Toast.makeText(this, R.string.download_pending, Toast.LENGTH_SHORT)
3331 .show();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003332 }
3333
Grace Kloba22ac16e2009-10-07 18:00:23 -07003334 // -------------------------------------------------------------------------
3335
The Android Open Source Project0c908882009-03-03 19:32:16 -08003336 /**
3337 * Resets the lock icon. This method is called when we start a new load and
3338 * know the url to be loaded.
3339 */
3340 private void resetLockIcon(String url) {
3341 // Save the lock-icon state (we revert to it if the load gets cancelled)
Grace Kloba22ac16e2009-10-07 18:00:23 -07003342 mTabControl.getCurrentTab().resetLockIcon(url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003343 updateLockIconImage(LOCK_ICON_UNSECURE);
3344 }
3345
The Android Open Source Project0c908882009-03-03 19:32:16 -08003346 /**
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04003347 * Update the lock icon to correspond to our latest state.
3348 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003349 private void updateLockIconToLatest() {
Leon Scroggins91f65fc2010-06-29 13:52:39 -04003350 Tab t = mTabControl.getCurrentTab();
3351 if (t != null) {
3352 updateLockIconImage(t.getLockIconType());
3353 }
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04003354 }
3355
3356 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08003357 * Updates the lock-icon image in the title-bar.
3358 */
3359 private void updateLockIconImage(int lockIconType) {
3360 Drawable d = null;
3361 if (lockIconType == LOCK_ICON_SECURE) {
3362 d = mSecLockIcon;
3363 } else if (lockIconType == LOCK_ICON_MIXED) {
3364 d = mMixLockIcon;
3365 }
Leon Scroggins68579392009-09-15 15:31:54 -04003366 mTitleBar.setLock(d);
Michael Kolba2b2ba82010-08-04 17:54:03 -07003367 mFakeTitleBar.setLock(d);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003368 }
3369
3370 /**
3371 * Displays a page-info dialog.
3372 * @param tab The tab to show info about
3373 * @param fromShowSSLCertificateOnError The flag that indicates whether
3374 * this dialog was opened from the SSL-certificate-on-error dialog or
3375 * not. This is important, since we need to know whether to return to
3376 * the parent dialog or simply dismiss.
3377 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003378 private void showPageInfo(final Tab tab,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003379 final boolean fromShowSSLCertificateOnError) {
3380 final LayoutInflater factory = LayoutInflater
3381 .from(this);
3382
3383 final View pageInfoView = factory.inflate(R.layout.page_info, null);
3384
3385 final WebView view = tab.getWebView();
3386
3387 String url = null;
3388 String title = null;
3389
3390 if (view == null) {
3391 url = tab.getUrl();
3392 title = tab.getTitle();
3393 } else if (view == mTabControl.getCurrentWebView()) {
3394 // Use the cached title and url if this is the current WebView
3395 url = mUrl;
3396 title = mTitle;
3397 } else {
3398 url = view.getUrl();
3399 title = view.getTitle();
3400 }
3401
3402 if (url == null) {
3403 url = "";
3404 }
3405 if (title == null) {
3406 title = "";
3407 }
3408
3409 ((TextView) pageInfoView.findViewById(R.id.address)).setText(url);
3410 ((TextView) pageInfoView.findViewById(R.id.title)).setText(title);
3411
3412 mPageInfoView = tab;
Leon Scrogginsc7b92f82010-01-11 18:17:31 -05003413 mPageInfoFromShowSSLCertificateOnError = fromShowSSLCertificateOnError;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003414
3415 AlertDialog.Builder alertDialogBuilder =
3416 new AlertDialog.Builder(this)
3417 .setTitle(R.string.page_info).setIcon(android.R.drawable.ic_dialog_info)
3418 .setView(pageInfoView)
3419 .setPositiveButton(
3420 R.string.ok,
3421 new DialogInterface.OnClickListener() {
3422 public void onClick(DialogInterface dialog,
3423 int whichButton) {
3424 mPageInfoDialog = null;
3425 mPageInfoView = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003426
3427 // if we came here from the SSL error dialog
3428 if (fromShowSSLCertificateOnError) {
3429 // go back to the SSL error dialog
3430 showSSLCertificateOnError(
3431 mSSLCertificateOnErrorView,
3432 mSSLCertificateOnErrorHandler,
3433 mSSLCertificateOnErrorError);
3434 }
3435 }
3436 })
3437 .setOnCancelListener(
3438 new DialogInterface.OnCancelListener() {
3439 public void onCancel(DialogInterface dialog) {
3440 mPageInfoDialog = null;
3441 mPageInfoView = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003442
3443 // if we came here from the SSL error dialog
3444 if (fromShowSSLCertificateOnError) {
3445 // go back to the SSL error dialog
3446 showSSLCertificateOnError(
3447 mSSLCertificateOnErrorView,
3448 mSSLCertificateOnErrorHandler,
3449 mSSLCertificateOnErrorError);
3450 }
3451 }
3452 });
3453
3454 // if we have a main top-level page SSL certificate set or a certificate
3455 // error
3456 if (fromShowSSLCertificateOnError ||
3457 (view != null && view.getCertificate() != null)) {
3458 // add a 'View Certificate' button
3459 alertDialogBuilder.setNeutralButton(
3460 R.string.view_certificate,
3461 new DialogInterface.OnClickListener() {
3462 public void onClick(DialogInterface dialog,
3463 int whichButton) {
3464 mPageInfoDialog = null;
3465 mPageInfoView = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003466
3467 // if we came here from the SSL error dialog
3468 if (fromShowSSLCertificateOnError) {
3469 // go back to the SSL error dialog
3470 showSSLCertificateOnError(
3471 mSSLCertificateOnErrorView,
3472 mSSLCertificateOnErrorHandler,
3473 mSSLCertificateOnErrorError);
3474 } else {
3475 // otherwise, display the top-most certificate from
3476 // the chain
3477 if (view.getCertificate() != null) {
3478 showSSLCertificate(tab);
3479 }
3480 }
3481 }
3482 });
3483 }
3484
3485 mPageInfoDialog = alertDialogBuilder.show();
3486 }
3487
3488 /**
3489 * Displays the main top-level page SSL certificate dialog
3490 * (accessible from the Page-Info dialog).
3491 * @param tab The tab to show certificate for.
3492 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003493 private void showSSLCertificate(final Tab tab) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003494 final View certificateView =
3495 inflateCertificateView(tab.getWebView().getCertificate());
3496 if (certificateView == null) {
3497 return;
3498 }
3499
3500 LayoutInflater factory = LayoutInflater.from(this);
3501
3502 final LinearLayout placeholder =
3503 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3504
3505 LinearLayout ll = (LinearLayout) factory.inflate(
3506 R.layout.ssl_success, placeholder);
3507 ((TextView)ll.findViewById(R.id.success))
3508 .setText(R.string.ssl_certificate_is_valid);
3509
3510 mSSLCertificateView = tab;
3511 mSSLCertificateDialog =
3512 new AlertDialog.Builder(this)
3513 .setTitle(R.string.ssl_certificate).setIcon(
3514 R.drawable.ic_dialog_browser_certificate_secure)
3515 .setView(certificateView)
3516 .setPositiveButton(R.string.ok,
3517 new DialogInterface.OnClickListener() {
3518 public void onClick(DialogInterface dialog,
3519 int whichButton) {
3520 mSSLCertificateDialog = null;
3521 mSSLCertificateView = null;
3522
3523 showPageInfo(tab, false);
3524 }
3525 })
3526 .setOnCancelListener(
3527 new DialogInterface.OnCancelListener() {
3528 public void onCancel(DialogInterface dialog) {
3529 mSSLCertificateDialog = null;
3530 mSSLCertificateView = null;
3531
3532 showPageInfo(tab, false);
3533 }
3534 })
3535 .show();
3536 }
3537
3538 /**
3539 * Displays the SSL error certificate dialog.
3540 * @param view The target web-view.
3541 * @param handler The SSL error handler responsible for cancelling the
3542 * connection that resulted in an SSL error or proceeding per user request.
3543 * @param error The SSL error object.
3544 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003545 void showSSLCertificateOnError(
The Android Open Source Project0c908882009-03-03 19:32:16 -08003546 final WebView view, final SslErrorHandler handler, final SslError error) {
3547
3548 final View certificateView =
3549 inflateCertificateView(error.getCertificate());
3550 if (certificateView == null) {
3551 return;
3552 }
3553
3554 LayoutInflater factory = LayoutInflater.from(this);
3555
3556 final LinearLayout placeholder =
3557 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3558
3559 if (error.hasError(SslError.SSL_UNTRUSTED)) {
3560 LinearLayout ll = (LinearLayout)factory
3561 .inflate(R.layout.ssl_warning, placeholder);
3562 ((TextView)ll.findViewById(R.id.warning))
3563 .setText(R.string.ssl_untrusted);
3564 }
3565
3566 if (error.hasError(SslError.SSL_IDMISMATCH)) {
3567 LinearLayout ll = (LinearLayout)factory
3568 .inflate(R.layout.ssl_warning, placeholder);
3569 ((TextView)ll.findViewById(R.id.warning))
3570 .setText(R.string.ssl_mismatch);
3571 }
3572
3573 if (error.hasError(SslError.SSL_EXPIRED)) {
3574 LinearLayout ll = (LinearLayout)factory
3575 .inflate(R.layout.ssl_warning, placeholder);
3576 ((TextView)ll.findViewById(R.id.warning))
3577 .setText(R.string.ssl_expired);
3578 }
3579
3580 if (error.hasError(SslError.SSL_NOTYETVALID)) {
3581 LinearLayout ll = (LinearLayout)factory
3582 .inflate(R.layout.ssl_warning, placeholder);
3583 ((TextView)ll.findViewById(R.id.warning))
3584 .setText(R.string.ssl_not_yet_valid);
3585 }
3586
3587 mSSLCertificateOnErrorHandler = handler;
3588 mSSLCertificateOnErrorView = view;
3589 mSSLCertificateOnErrorError = error;
3590 mSSLCertificateOnErrorDialog =
3591 new AlertDialog.Builder(this)
3592 .setTitle(R.string.ssl_certificate).setIcon(
3593 R.drawable.ic_dialog_browser_certificate_partially_secure)
3594 .setView(certificateView)
3595 .setPositiveButton(R.string.ok,
3596 new DialogInterface.OnClickListener() {
3597 public void onClick(DialogInterface dialog,
3598 int whichButton) {
3599 mSSLCertificateOnErrorDialog = null;
3600 mSSLCertificateOnErrorView = null;
3601 mSSLCertificateOnErrorHandler = null;
3602 mSSLCertificateOnErrorError = null;
3603
Grace Kloba22ac16e2009-10-07 18:00:23 -07003604 view.getWebViewClient().onReceivedSslError(
3605 view, handler, error);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003606 }
3607 })
3608 .setNeutralButton(R.string.page_info_view,
3609 new DialogInterface.OnClickListener() {
3610 public void onClick(DialogInterface dialog,
3611 int whichButton) {
3612 mSSLCertificateOnErrorDialog = null;
3613
3614 // do not clear the dialog state: we will
3615 // need to show the dialog again once the
3616 // user is done exploring the page-info details
3617
3618 showPageInfo(mTabControl.getTabFromView(view),
3619 true);
3620 }
3621 })
3622 .setOnCancelListener(
3623 new DialogInterface.OnCancelListener() {
3624 public void onCancel(DialogInterface dialog) {
3625 mSSLCertificateOnErrorDialog = null;
3626 mSSLCertificateOnErrorView = null;
3627 mSSLCertificateOnErrorHandler = null;
3628 mSSLCertificateOnErrorError = null;
3629
Grace Kloba22ac16e2009-10-07 18:00:23 -07003630 view.getWebViewClient().onReceivedSslError(
3631 view, handler, error);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003632 }
3633 })
3634 .show();
3635 }
3636
3637 /**
3638 * Inflates the SSL certificate view (helper method).
3639 * @param certificate The SSL certificate.
3640 * @return The resultant certificate view with issued-to, issued-by,
3641 * issued-on, expires-on, and possibly other fields set.
3642 * If the input certificate is null, returns null.
3643 */
3644 private View inflateCertificateView(SslCertificate certificate) {
3645 if (certificate == null) {
3646 return null;
3647 }
3648
3649 LayoutInflater factory = LayoutInflater.from(this);
3650
3651 View certificateView = factory.inflate(
3652 R.layout.ssl_certificate, null);
3653
3654 // issued to:
3655 SslCertificate.DName issuedTo = certificate.getIssuedTo();
3656 if (issuedTo != null) {
3657 ((TextView) certificateView.findViewById(R.id.to_common))
3658 .setText(issuedTo.getCName());
3659 ((TextView) certificateView.findViewById(R.id.to_org))
3660 .setText(issuedTo.getOName());
3661 ((TextView) certificateView.findViewById(R.id.to_org_unit))
3662 .setText(issuedTo.getUName());
3663 }
3664
3665 // issued by:
3666 SslCertificate.DName issuedBy = certificate.getIssuedBy();
3667 if (issuedBy != null) {
3668 ((TextView) certificateView.findViewById(R.id.by_common))
3669 .setText(issuedBy.getCName());
3670 ((TextView) certificateView.findViewById(R.id.by_org))
3671 .setText(issuedBy.getOName());
3672 ((TextView) certificateView.findViewById(R.id.by_org_unit))
3673 .setText(issuedBy.getUName());
3674 }
3675
3676 // issued on:
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003677 String issuedOn = formatCertificateDate(
3678 certificate.getValidNotBeforeDate());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003679 ((TextView) certificateView.findViewById(R.id.issued_on))
3680 .setText(issuedOn);
3681
3682 // expires on:
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003683 String expiresOn = formatCertificateDate(
3684 certificate.getValidNotAfterDate());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003685 ((TextView) certificateView.findViewById(R.id.expires_on))
3686 .setText(expiresOn);
3687
3688 return certificateView;
3689 }
3690
3691 /**
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003692 * Formats the certificate date to a properly localized date string.
The Android Open Source Project0c908882009-03-03 19:32:16 -08003693 * @return Properly localized version of the certificate date string and
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003694 * the "" if it fails to localize.
The Android Open Source Project0c908882009-03-03 19:32:16 -08003695 */
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003696 private String formatCertificateDate(Date certificateDate) {
3697 if (certificateDate == null) {
3698 return "";
The Android Open Source Project0c908882009-03-03 19:32:16 -08003699 }
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003700 String formattedDate = DateFormat.getDateFormat(this).format(certificateDate);
3701 if (formattedDate == null) {
3702 return "";
3703 }
3704 return formattedDate;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003705 }
3706
3707 /**
3708 * Displays an http-authentication dialog.
3709 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003710 void showHttpAuthentication(final HttpAuthHandler handler,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003711 final String host, final String realm, final String title,
3712 final String name, final String password, int focusId) {
3713 LayoutInflater factory = LayoutInflater.from(this);
3714 final View v = factory
3715 .inflate(R.layout.http_authentication, null);
3716 if (name != null) {
3717 ((EditText) v.findViewById(R.id.username_edit)).setText(name);
3718 }
3719 if (password != null) {
3720 ((EditText) v.findViewById(R.id.password_edit)).setText(password);
3721 }
3722
3723 String titleText = title;
3724 if (titleText == null) {
3725 titleText = getText(R.string.sign_in_to).toString().replace(
3726 "%s1", host).replace("%s2", realm);
3727 }
3728
3729 mHttpAuthHandler = handler;
3730 AlertDialog dialog = new AlertDialog.Builder(this)
3731 .setTitle(titleText)
3732 .setIcon(android.R.drawable.ic_dialog_alert)
3733 .setView(v)
3734 .setPositiveButton(R.string.action,
3735 new DialogInterface.OnClickListener() {
3736 public void onClick(DialogInterface dialog,
3737 int whichButton) {
3738 String nm = ((EditText) v
3739 .findViewById(R.id.username_edit))
3740 .getText().toString();
3741 String pw = ((EditText) v
3742 .findViewById(R.id.password_edit))
3743 .getText().toString();
3744 BrowserActivity.this.setHttpAuthUsernamePassword
3745 (host, realm, nm, pw);
3746 handler.proceed(nm, pw);
3747 mHttpAuthenticationDialog = null;
3748 mHttpAuthHandler = null;
3749 }})
3750 .setNegativeButton(R.string.cancel,
3751 new DialogInterface.OnClickListener() {
3752 public void onClick(DialogInterface dialog,
3753 int whichButton) {
3754 handler.cancel();
3755 BrowserActivity.this.resetTitleAndRevertLockIcon();
3756 mHttpAuthenticationDialog = null;
3757 mHttpAuthHandler = null;
3758 }})
3759 .setOnCancelListener(new DialogInterface.OnCancelListener() {
3760 public void onCancel(DialogInterface dialog) {
3761 handler.cancel();
3762 BrowserActivity.this.resetTitleAndRevertLockIcon();
3763 mHttpAuthenticationDialog = null;
3764 mHttpAuthHandler = null;
3765 }})
3766 .create();
3767 // Make the IME appear when the dialog is displayed if applicable.
3768 dialog.getWindow().setSoftInputMode(
3769 WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
3770 dialog.show();
3771 if (focusId != 0) {
3772 dialog.findViewById(focusId).requestFocus();
3773 } else {
3774 v.findViewById(R.id.username_edit).requestFocus();
3775 }
3776 mHttpAuthenticationDialog = dialog;
3777 }
3778
3779 public int getProgress() {
3780 WebView w = mTabControl.getCurrentWebView();
3781 if (w != null) {
3782 return w.getProgress();
3783 } else {
3784 return 100;
3785 }
3786 }
3787
3788 /**
3789 * Set HTTP authentication password.
3790 *
3791 * @param host The host for the password
3792 * @param realm The realm for the password
3793 * @param username The username for the password. If it is null, it means
3794 * password can't be saved.
3795 * @param password The password
3796 */
3797 public void setHttpAuthUsernamePassword(String host, String realm,
3798 String username,
3799 String password) {
Steve Block95a53b22010-03-25 17:24:58 +00003800 WebView w = getTopWindow();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003801 if (w != null) {
3802 w.setHttpAuthUsernamePassword(host, realm, username, password);
3803 }
3804 }
3805
3806 /**
3807 * connectivity manager says net has come or gone... inform the user
3808 * @param up true if net has come up, false if net has gone down
3809 */
3810 public void onNetworkToggle(boolean up) {
3811 if (up == mIsNetworkUp) {
3812 return;
3813 } else if (up) {
3814 mIsNetworkUp = true;
3815 if (mAlertDialog != null) {
3816 mAlertDialog.cancel();
3817 mAlertDialog = null;
3818 }
3819 } else {
3820 mIsNetworkUp = false;
Patrick Scotteb6ab2a2009-09-16 10:00:17 -04003821 if (mInLoad) {
3822 createAndShowNetworkDialog();
3823 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003824 }
3825 WebView w = mTabControl.getCurrentWebView();
3826 if (w != null) {
3827 w.setNetworkAvailable(up);
3828 }
3829 }
3830
Grace Kloba22ac16e2009-10-07 18:00:23 -07003831 boolean isNetworkUp() {
3832 return mIsNetworkUp;
3833 }
3834
Patrick Scotteb6ab2a2009-09-16 10:00:17 -04003835 // This method shows the network dialog alerting the user that the net is
3836 // down. It will only show the dialog if mAlertDialog is null.
3837 private void createAndShowNetworkDialog() {
3838 if (mAlertDialog == null) {
3839 mAlertDialog = new AlertDialog.Builder(this)
3840 .setTitle(R.string.loadSuspendedTitle)
3841 .setMessage(R.string.loadSuspended)
3842 .setPositiveButton(R.string.ok, null)
3843 .show();
3844 }
3845 }
3846
The Android Open Source Project0c908882009-03-03 19:32:16 -08003847 @Override
3848 protected void onActivityResult(int requestCode, int resultCode,
3849 Intent intent) {
Grace Klobabb394f32009-11-19 10:26:37 -08003850 if (getTopWindow() == null) return;
3851
The Android Open Source Project0c908882009-03-03 19:32:16 -08003852 switch (requestCode) {
3853 case COMBO_PAGE:
3854 if (resultCode == RESULT_OK && intent != null) {
3855 String data = intent.getAction();
3856 Bundle extras = intent.getExtras();
3857 if (extras != null && extras.getBoolean("new_window", false)) {
Michael Kolb68792c82010-08-09 16:39:18 -07003858 openTab(data, false);
3859 } else if ((extras != null) &&
3860 extras.getBoolean(CombinedBookmarkHistoryActivity.NEWTAB_MODE)) {
3861 openTab(data, true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003862 } else {
Michael Kolb68792c82010-08-09 16:39:18 -07003863 final Tab currentTab = mTabControl.getCurrentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04003864 dismissSubWindow(currentTab);
3865 if (data != null && data.length() != 0) {
Leon Scroggins92472e82010-02-17 16:32:28 -05003866 loadUrl(getTopWindow(), data);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003867 }
3868 }
3869 }
Leon Scrogginsfde97462010-01-11 13:06:21 -05003870 // Deliberately fall through to PREFERENCES_PAGE, since the
3871 // same extra may be attached to the COMBO_PAGE
3872 case PREFERENCES_PAGE:
3873 if (resultCode == RESULT_OK && intent != null) {
3874 String action = intent.getStringExtra(Intent.EXTRA_TEXT);
3875 if (BrowserSettings.PREF_CLEAR_HISTORY.equals(action)) {
3876 mTabControl.removeParentChildRelationShips();
3877 }
3878 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003879 break;
Leon Scroggins8d5fa432009-10-02 15:55:59 -04003880 // Choose a file from the file picker.
3881 case FILE_SELECTED:
3882 if (null == mUploadMessage) break;
3883 Uri result = intent == null || resultCode != RESULT_OK ? null
3884 : intent.getData();
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003885
3886 // As we ask the camera to save the result of the user taking
3887 // a picture, the camera application does not return anything other
3888 // than RESULT_OK. So we need to check whether the file we expected
3889 // was written to disk in the in the case that we
3890 // did not get an intent returned but did get a RESULT_OK. If it was,
3891 // we assume that this result has came back from the camera.
3892 if (result == null && intent == null && resultCode == RESULT_OK) {
3893 File cameraFile = new File(mCameraFilePath);
3894 if (cameraFile.exists()) {
3895 result = Uri.fromFile(cameraFile);
Ben Murdoch07d34732010-05-27 18:34:46 +01003896 // Broadcast to the media scanner that we have a new photo
3897 // so it will be added into the gallery for the user.
3898 sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, result));
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003899 }
3900 }
Leon Scroggins8d5fa432009-10-02 15:55:59 -04003901 mUploadMessage.onReceiveValue(result);
3902 mUploadMessage = null;
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003903 mCameraFilePath = null;
Leon Scroggins8d5fa432009-10-02 15:55:59 -04003904 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003905 default:
3906 break;
3907 }
Leon Scroggins30444232009-09-04 18:36:20 -04003908 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003909 }
3910
3911 /*
3912 * This method is called as a result of the user selecting the options
Leon Scrogginsf08809b2010-01-21 09:27:46 -05003913 * menu to see the download window. It shows the download window on top of
3914 * the current window.
The Android Open Source Project0c908882009-03-03 19:32:16 -08003915 */
Leon Scrogginsf08809b2010-01-21 09:27:46 -05003916 private void viewDownloads(Uri downloadRecord) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003917 Intent intent = new Intent(this,
3918 BrowserDownloadPage.class);
3919 intent.setData(downloadRecord);
Grace Kloba22ac16e2009-10-07 18:00:23 -07003920 startActivityForResult(intent, BrowserActivity.DOWNLOAD_PAGE);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003921
3922 }
3923
Ben Murdocheecb4e62010-07-06 16:30:38 +01003924 /* package*/ void promptAddOrInstallBookmark() {
3925 final Tab current = mTabControl.getCurrentTab();
3926 Resources resources = getResources();
3927 CharSequence[] choices = {
3928 resources.getString(R.string.save_to_bookmarks),
3929 resources.getString(R.string.create_shortcut_bookmark)
3930 };
3931
3932 AlertDialog.Builder builder = new AlertDialog.Builder(this);
3933 builder.setTitle(R.string.add_new_bookmark);
3934 builder.setItems(choices, new DialogInterface.OnClickListener() {
3935 public void onClick(DialogInterface dialog, int item) {
3936 if (item == 0) {
3937 bookmarkCurrentPage();
3938 } else if (item == 1) {
3939 current.populatePickerData();
3940 String touchIconUrl = mTabControl.getCurrentWebView().getTouchIconUrl();
3941 if (touchIconUrl != null) {
3942 // Download the touch icon for this site then save it to the
3943 // homescreen.
3944 Bundle b = new Bundle();
3945 b.putString("url", current.getUrl());
3946 b.putString("title", current.getTitle());
3947 b.putParcelable("favicon", current.getFavicon());
3948 Message msg = mHandler.obtainMessage(TOUCH_ICON_DOWNLOADED);
3949 msg.setData(b);
Ben Murdochccb5de02010-07-19 18:38:17 +01003950 new DownloadTouchIcon(BrowserActivity.this, msg,
Ben Murdocheecb4e62010-07-06 16:30:38 +01003951 mTabControl.getCurrentWebView().getSettings()
3952 .getUserAgentString()).execute(touchIconUrl);
3953 } else {
3954 // add to homescreen, can do it immediately as there is no touch
3955 // icon.
3956 showSaveToHomescreenDialog(current.getUrl(), current.getTitle(),
3957 null, current.getFavicon());
3958 }
3959 }
3960 }
3961 });
3962 builder.create().show();
3963 }
3964
Leon Scroggins160a7e72009-08-14 18:28:01 -04003965 /**
3966 * Open the Go page.
3967 * @param startWithHistory If true, open starting on the history tab.
3968 * Otherwise, start with the bookmarks tab.
Leon Scroggins160a7e72009-08-14 18:28:01 -04003969 */
Michael Kolb68792c82010-08-09 16:39:18 -07003970 /* package */ void bookmarksOrHistoryPicker(boolean startWithHistory, boolean newTabMode) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003971 WebView current = mTabControl.getCurrentWebView();
3972 if (current == null) {
3973 return;
3974 }
3975 Intent intent = new Intent(this,
3976 CombinedBookmarkHistoryActivity.class);
3977 String title = current.getTitle();
3978 String url = current.getUrl();
Ben Murdoch87cc65d2010-06-29 20:34:10 +01003979 Bitmap thumbnail = createScreenshot(current, getDesiredThumbnailWidth(this),
3980 getDesiredThumbnailHeight(this));
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01003981
The Android Open Source Project0c908882009-03-03 19:32:16 -08003982 // Just in case the user opens bookmarks before a page finishes loading
3983 // so the current history item, and therefore the page, is null.
3984 if (null == url) {
3985 url = mLastEnteredUrl;
3986 // This can happen.
3987 if (null == url) {
3988 url = mSettings.getHomePage();
3989 }
3990 }
3991 // In case the web page has not yet received its associated title.
3992 if (title == null) {
3993 title = url;
3994 }
3995 intent.putExtra("title", title);
3996 intent.putExtra("url", url);
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01003997 intent.putExtra("thumbnail", thumbnail);
Leon Scroggins30444232009-09-04 18:36:20 -04003998 // Disable opening in a new window if we have maxed out the windows
Grace Kloba22ac16e2009-10-07 18:00:23 -07003999 intent.putExtra("disable_new_window", !mTabControl.canCreateNewTab());
Patrick Scott3918d442009-08-04 13:22:29 -04004000 intent.putExtra("touch_icon_url", current.getTouchIconUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08004001 if (startWithHistory) {
Jeff Hamilton64144e42010-08-18 16:31:59 -05004002 intent.putExtra(CombinedBookmarkHistoryActivity.STARTING_FRAGMENT,
4003 CombinedBookmarkHistoryActivity.FRAGMENT_ID_HISTORY);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004004 }
Michael Kolb68792c82010-08-09 16:39:18 -07004005 if (newTabMode) {
4006 intent.putExtra(CombinedBookmarkHistoryActivity.NEWTAB_MODE, true);
4007 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08004008 startActivityForResult(intent, COMBO_PAGE);
4009 }
4010
Ben Murdocheecb4e62010-07-06 16:30:38 +01004011 private void showSaveToHomescreenDialog(String url, String title, Bitmap touchIcon,
4012 Bitmap favicon) {
4013 Intent intent = new Intent(this, SaveToHomescreenDialog.class);
4014
4015 // Just in case the user tries to save before a page finishes loading
4016 // so the current history item, and therefore the page, is null.
4017 if (null == url) {
4018 url = mLastEnteredUrl;
4019 // This can happen.
4020 if (null == url) {
4021 url = mSettings.getHomePage();
4022 }
4023 }
4024
4025 // In case the web page has not yet received its associated title.
4026 if (title == null) {
4027 title = url;
4028 }
4029
4030 intent.putExtra("title", title);
4031 intent.putExtra("url", url);
4032 intent.putExtra("favicon", favicon);
4033 intent.putExtra("touchIcon", touchIcon);
4034 startActivity(intent);
4035 }
4036
4037
The Android Open Source Project0c908882009-03-03 19:32:16 -08004038 // Called when loading from context menu or LOAD_URL message
Leon Scroggins92472e82010-02-17 16:32:28 -05004039 private void loadUrlFromContext(WebView view, String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08004040 // In case the user enters nothing.
4041 if (url != null && url.length() != 0 && view != null) {
4042 url = smartUrlFilter(url);
Grace Kloba22ac16e2009-10-07 18:00:23 -07004043 if (!view.getWebViewClient().shouldOverrideUrlLoading(view, url)) {
Leon Scroggins92472e82010-02-17 16:32:28 -05004044 loadUrl(view, url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004045 }
4046 }
4047 }
4048
Leon Scroggins92472e82010-02-17 16:32:28 -05004049 /**
4050 * Load the URL into the given WebView and update the title bar
4051 * to reflect the new load. Call this instead of WebView.loadUrl
4052 * directly.
4053 * @param view The WebView used to load url.
4054 * @param url The URL to load.
4055 */
4056 private void loadUrl(WebView view, String url) {
4057 updateTitleBarForNewLoad(view, url);
4058 view.loadUrl(url);
4059 }
4060
4061 /**
4062 * Load UrlData into a Tab and update the title bar to reflect the new
4063 * load. Call this instead of UrlData.loadIn directly.
4064 * @param t The Tab used to load.
4065 * @param data The UrlData being loaded.
4066 */
4067 private void loadUrlDataIn(Tab t, UrlData data) {
4068 updateTitleBarForNewLoad(t.getWebView(), data.mUrl);
4069 data.loadIn(t);
4070 }
4071
4072 /**
4073 * If the WebView is the top window, update the title bar to reflect
4074 * loading the new URL. i.e. set its text, clear the favicon (which
4075 * will be set once the page begins loading), and set the progress to
4076 * INITIAL_PROGRESS to show that the page has begun to load. Called
4077 * by loadUrl and loadUrlDataIn.
4078 * @param view The WebView that is starting a load.
4079 * @param url The URL that is being loaded.
4080 */
4081 private void updateTitleBarForNewLoad(WebView view, String url) {
4082 if (view == getTopWindow()) {
4083 setUrlTitle(url, null);
4084 setFavicon(null);
4085 onProgressChanged(view, INITIAL_PROGRESS);
4086 }
4087 }
4088
The Android Open Source Project0c908882009-03-03 19:32:16 -08004089 private String smartUrlFilter(Uri inUri) {
4090 if (inUri != null) {
4091 return smartUrlFilter(inUri.toString());
4092 }
4093 return null;
4094 }
4095
Feng Qianb34f87a2009-03-24 21:27:26 -07004096 protected static final Pattern ACCEPTED_URI_SCHEMA = Pattern.compile(
The Android Open Source Project0c908882009-03-03 19:32:16 -08004097 "(?i)" + // switch on case insensitive matching
4098 "(" + // begin group for schema
4099 "(?:http|https|file):\\/\\/" +
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004100 "|(?:inline|data|about|content|javascript):" +
The Android Open Source Project0c908882009-03-03 19:32:16 -08004101 ")" +
4102 "(.*)" );
4103
4104 /**
4105 * Attempts to determine whether user input is a URL or search
4106 * terms. Anything with a space is passed to search.
4107 *
4108 * Converts to lowercase any mistakenly uppercased schema (i.e.,
4109 * "Http://" converts to "http://"
4110 *
4111 * @return Original or modified URL
4112 *
4113 */
4114 String smartUrlFilter(String url) {
4115
4116 String inUrl = url.trim();
4117 boolean hasSpace = inUrl.indexOf(' ') != -1;
4118
4119 Matcher matcher = ACCEPTED_URI_SCHEMA.matcher(inUrl);
4120 if (matcher.matches()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08004121 // force scheme to lowercase
4122 String scheme = matcher.group(1);
4123 String lcScheme = scheme.toLowerCase();
4124 if (!lcScheme.equals(scheme)) {
Mitsuru Oshima123ecfb2009-05-18 19:11:14 -07004125 inUrl = lcScheme + matcher.group(2);
4126 }
4127 if (hasSpace) {
4128 inUrl = inUrl.replace(" ", "%20");
The Android Open Source Project0c908882009-03-03 19:32:16 -08004129 }
4130 return inUrl;
4131 }
4132 if (hasSpace) {
Satish Sampath565505b2009-05-29 15:37:27 +01004133 // FIXME: Is this the correct place to add to searches?
4134 // what if someone else calls this function?
4135 int shortcut = parseUrlShortcut(inUrl);
4136 if (shortcut != SHORTCUT_INVALID) {
4137 Browser.addSearchUrl(mResolver, inUrl);
4138 String query = inUrl.substring(2);
4139 switch (shortcut) {
4140 case SHORTCUT_GOOGLE_SEARCH:
Grace Kloba47fdfdb2009-06-30 11:15:34 -07004141 return URLUtil.composeSearchUrl(query, QuickSearch_G, QUERY_PLACE_HOLDER);
Satish Sampath565505b2009-05-29 15:37:27 +01004142 case SHORTCUT_WIKIPEDIA_SEARCH:
4143 return URLUtil.composeSearchUrl(query, QuickSearch_W, QUERY_PLACE_HOLDER);
4144 case SHORTCUT_DICTIONARY_SEARCH:
4145 return URLUtil.composeSearchUrl(query, QuickSearch_D, QUERY_PLACE_HOLDER);
4146 case SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH:
The Android Open Source Project0c908882009-03-03 19:32:16 -08004147 // FIXME: we need location in this case
Satish Sampath565505b2009-05-29 15:37:27 +01004148 return URLUtil.composeSearchUrl(query, QuickSearch_L, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004149 }
4150 }
4151 } else {
Dan Egnor5ee906c2009-11-18 12:11:49 -08004152 if (Patterns.WEB_URL.matcher(inUrl).matches()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08004153 return URLUtil.guessUrl(inUrl);
4154 }
4155 }
4156
4157 Browser.addSearchUrl(mResolver, inUrl);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07004158 return URLUtil.composeSearchUrl(inUrl, QuickSearch_G, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004159 }
4160
Ben Murdochbff2d602009-07-01 20:19:05 +01004161 /* package */ void setShouldShowErrorConsole(boolean flag) {
4162 if (flag == mShouldShowErrorConsole) {
4163 // Nothing to do.
4164 return;
4165 }
4166
4167 mShouldShowErrorConsole = flag;
4168
Grace Kloba22ac16e2009-10-07 18:00:23 -07004169 ErrorConsoleView errorConsole = mTabControl.getCurrentTab()
4170 .getErrorConsole(true);
Ben Murdochbff2d602009-07-01 20:19:05 +01004171
4172 if (flag) {
4173 // Setting the show state of the console will cause it's the layout to be inflated.
4174 if (errorConsole.numberOfErrors() > 0) {
4175 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
4176 } else {
4177 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
4178 }
4179
4180 // Now we can add it to the main view.
4181 mErrorConsoleContainer.addView(errorConsole,
Romain Guy15b8ec62010-01-08 15:06:43 -08004182 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
Ben Murdochbff2d602009-07-01 20:19:05 +01004183 ViewGroup.LayoutParams.WRAP_CONTENT));
4184 } else {
4185 mErrorConsoleContainer.removeView(errorConsole);
4186 }
4187
4188 }
4189
Grace Kloba22ac16e2009-10-07 18:00:23 -07004190 boolean shouldShowErrorConsole() {
4191 return mShouldShowErrorConsole;
4192 }
4193
Andrei Popescu163ab742009-10-20 17:58:23 +01004194 private void setStatusBarVisibility(boolean visible) {
4195 int flag = visible ? 0 : WindowManager.LayoutParams.FLAG_FULLSCREEN;
4196 getWindow().setFlags(flag, WindowManager.LayoutParams.FLAG_FULLSCREEN);
4197 }
4198
Andrei Popescu56199cc2010-01-12 22:39:16 +00004199
4200 private void sendNetworkType(String type, String subtype) {
4201 WebView w = mTabControl.getCurrentWebView();
4202 if (w != null) {
4203 w.setNetworkType(type, subtype);
4204 }
4205 }
4206
Andrei Popescu30995e72010-02-09 16:59:58 +00004207 private void packageChanged(String packageName, boolean wasAdded) {
4208 WebView w = mTabControl.getCurrentWebView();
4209 if (w == null) {
4210 return;
4211 }
4212
4213 if (wasAdded) {
4214 w.addPackageName(packageName);
4215 } else {
4216 w.removePackageName(packageName);
4217 }
4218 }
4219
4220 private void addPackageNames(Set<String> packageNames) {
4221 WebView w = mTabControl.getCurrentWebView();
4222 if (w == null) {
4223 return;
4224 }
4225
4226 w.addPackageNames(packageNames);
4227 }
4228
4229 private void getInstalledPackages() {
4230 AsyncTask<Void, Void, Set<String> > task =
4231 new AsyncTask<Void, Void, Set<String> >() {
Michael Kolbe0a36662010-06-29 10:37:12 -07004232 @Override
Andrei Popescu30995e72010-02-09 16:59:58 +00004233 protected Set<String> doInBackground(Void... unused) {
4234 Set<String> installedPackages = new HashSet<String>();
4235 PackageManager pm = BrowserActivity.this.getPackageManager();
4236 if (pm != null) {
4237 List<PackageInfo> packages = pm.getInstalledPackages(0);
4238 for (PackageInfo p : packages) {
4239 if (BrowserActivity.this.sGoogleApps.contains(p.packageName)) {
4240 installedPackages.add(p.packageName);
4241 }
4242 }
4243 }
4244
4245 return installedPackages;
4246 }
4247
4248 // Executes on the UI thread
Michael Kolbe0a36662010-06-29 10:37:12 -07004249 @Override
Andrei Popescu30995e72010-02-09 16:59:58 +00004250 protected void onPostExecute(Set<String> installedPackages) {
4251 addPackageNames(installedPackages);
4252 }
4253 };
4254 task.execute();
4255 }
4256
Grace Klobaeb6eef42009-09-15 17:56:32 -07004257 final static int LOCK_ICON_UNSECURE = 0;
4258 final static int LOCK_ICON_SECURE = 1;
4259 final static int LOCK_ICON_MIXED = 2;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004260
The Android Open Source Project0c908882009-03-03 19:32:16 -08004261 private BrowserSettings mSettings;
4262 private TabControl mTabControl;
4263 private ContentResolver mResolver;
4264 private FrameLayout mContentView;
Andrei Popescuadc008d2009-06-26 14:11:30 +01004265 private View mCustomView;
4266 private FrameLayout mCustomViewContainer;
Andrei Popescuc9b55562009-07-07 10:51:15 +01004267 private WebChromeClient.CustomViewCallback mCustomViewCallback;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004268
4269 // FIXME, temp address onPrepareMenu performance problem. When we move everything out of
4270 // view, we should rewrite this.
4271 private int mCurrentMenuState = 0;
4272 private int mMenuState = R.id.MAIN_MENU;
Andrei Popescuadc008d2009-06-26 14:11:30 +01004273 private int mOldMenuState = EMPTY_MENU;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004274 private static final int EMPTY_MENU = -1;
4275 private Menu mMenu;
4276
The Android Open Source Project0c908882009-03-03 19:32:16 -08004277 // Used to prevent chording to result in firing two shortcuts immediately
4278 // one after another. Fixes bug 1211714.
4279 boolean mCanChord;
4280
4281 private boolean mInLoad;
4282 private boolean mIsNetworkUp;
Ben Murdochb7cc8b42009-09-28 10:59:09 +01004283 private boolean mDidStopLoad;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004284
Cary Clark1f10cbf2010-03-22 11:45:23 -04004285 /* package */ boolean mActivityInPause = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004286
4287 private boolean mMenuIsDown;
4288
The Android Open Source Project0c908882009-03-03 19:32:16 -08004289 private static boolean mInTrace;
4290
4291 // Performance probe
4292 private static final int[] SYSTEM_CPU_FORMAT = new int[] {
4293 Process.PROC_SPACE_TERM | Process.PROC_COMBINE,
4294 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 1: user time
4295 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 2: nice time
4296 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 3: sys time
4297 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 4: idle time
4298 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 5: iowait time
4299 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 6: irq time
4300 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG // 7: softirq time
4301 };
4302
4303 private long mStart;
4304 private long mProcessStart;
4305 private long mUserStart;
4306 private long mSystemStart;
4307 private long mIdleStart;
4308 private long mIrqStart;
4309
4310 private long mUiStart;
4311
4312 private Drawable mMixLockIcon;
4313 private Drawable mSecLockIcon;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004314
4315 /* hold a ref so we can auto-cancel if necessary */
4316 private AlertDialog mAlertDialog;
4317
The Android Open Source Project0c908882009-03-03 19:32:16 -08004318 // The up-to-date URL and title (these can be different from those stored
4319 // in WebView, since it takes some time for the information in WebView to
4320 // get updated)
4321 private String mUrl;
4322 private String mTitle;
4323
4324 // As PageInfo has different style for landscape / portrait, we have
4325 // to re-open it when configuration changed
4326 private AlertDialog mPageInfoDialog;
Grace Kloba22ac16e2009-10-07 18:00:23 -07004327 private Tab mPageInfoView;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004328 // If the Page-Info dialog is launched from the SSL-certificate-on-error
4329 // dialog, we should not just dismiss it, but should get back to the
4330 // SSL-certificate-on-error dialog. This flag is used to store this state
Leon Scrogginsc7b92f82010-01-11 18:17:31 -05004331 private boolean mPageInfoFromShowSSLCertificateOnError;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004332
4333 // as SSLCertificateOnError has different style for landscape / portrait,
4334 // we have to re-open it when configuration changed
4335 private AlertDialog mSSLCertificateOnErrorDialog;
4336 private WebView mSSLCertificateOnErrorView;
4337 private SslErrorHandler mSSLCertificateOnErrorHandler;
4338 private SslError mSSLCertificateOnErrorError;
4339
4340 // as SSLCertificate has different style for landscape / portrait, we
4341 // have to re-open it when configuration changed
4342 private AlertDialog mSSLCertificateDialog;
Grace Kloba22ac16e2009-10-07 18:00:23 -07004343 private Tab mSSLCertificateView;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004344
4345 // as HttpAuthentication has different style for landscape / portrait, we
4346 // have to re-open it when configuration changed
4347 private AlertDialog mHttpAuthenticationDialog;
4348 private HttpAuthHandler mHttpAuthHandler;
4349
4350 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_PARAMS =
4351 new FrameLayout.LayoutParams(
Romain Guy15b8ec62010-01-08 15:06:43 -08004352 ViewGroup.LayoutParams.MATCH_PARENT,
4353 ViewGroup.LayoutParams.MATCH_PARENT);
Andrei Popescuadc008d2009-06-26 14:11:30 +01004354 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_GRAVITY_CENTER =
4355 new FrameLayout.LayoutParams(
Romain Guy15b8ec62010-01-08 15:06:43 -08004356 ViewGroup.LayoutParams.MATCH_PARENT,
4357 ViewGroup.LayoutParams.MATCH_PARENT,
Andrei Popescuadc008d2009-06-26 14:11:30 +01004358 Gravity.CENTER);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07004359 // Google search
4360 final static String QuickSearch_G = "http://www.google.com/m?q=%s";
The Android Open Source Project0c908882009-03-03 19:32:16 -08004361 // Wikipedia search
4362 final static String QuickSearch_W = "http://en.wikipedia.org/w/index.php?search=%s&go=Go";
4363 // Dictionary search
4364 final static String QuickSearch_D = "http://dictionary.reference.com/search?q=%s";
4365 // Google Mobile Local search
4366 final static String QuickSearch_L = "http://www.google.com/m/search?site=local&q=%s&near=mountain+view";
4367
4368 final static String QUERY_PLACE_HOLDER = "%s";
4369
4370 // "source" parameter for Google search through search key
4371 final static String GOOGLE_SEARCH_SOURCE_SEARCHKEY = "browser-key";
4372 // "source" parameter for Google search through goto menu
4373 final static String GOOGLE_SEARCH_SOURCE_GOTO = "browser-goto";
4374 // "source" parameter for Google search through simplily type
4375 final static String GOOGLE_SEARCH_SOURCE_TYPE = "browser-type";
4376 // "source" parameter for Google search suggested by the browser
4377 final static String GOOGLE_SEARCH_SOURCE_SUGGEST = "browser-suggest";
4378 // "source" parameter for Google search from unknown source
4379 final static String GOOGLE_SEARCH_SOURCE_UNKNOWN = "unknown";
4380
4381 private final static String LOGTAG = "browser";
4382
The Android Open Source Project0c908882009-03-03 19:32:16 -08004383 private String mLastEnteredUrl;
4384
4385 private PowerManager.WakeLock mWakeLock;
4386 private final static int WAKELOCK_TIMEOUT = 5 * 60 * 1000; // 5 minutes
4387
4388 private Toast mStopToast;
4389
Leon Scroggins571b3762010-05-26 10:25:01 -04004390 private TitleBarBase mTitleBar;
Michael Kolba2b2ba82010-08-04 17:54:03 -07004391 private TabBar mTabBar;
Leon Scroggins81db3662009-06-04 17:45:11 -04004392
Ben Murdochbff2d602009-07-01 20:19:05 +01004393 private LinearLayout mErrorConsoleContainer = null;
4394 private boolean mShouldShowErrorConsole = false;
4395
The Android Open Source Project0c908882009-03-03 19:32:16 -08004396 // As the ids are dynamically created, we can't guarantee that they will
4397 // be in sequence, so this static array maps ids to a window number.
4398 final static private int[] WINDOW_SHORTCUT_ID_ARRAY =
4399 { R.id.window_one_menu_id, R.id.window_two_menu_id, R.id.window_three_menu_id,
4400 R.id.window_four_menu_id, R.id.window_five_menu_id, R.id.window_six_menu_id,
4401 R.id.window_seven_menu_id, R.id.window_eight_menu_id };
4402
4403 // monitor platform changes
4404 private IntentFilter mNetworkStateChangedFilter;
4405 private BroadcastReceiver mNetworkStateIntentReceiver;
4406
Grace Klobab4da0ad2009-05-14 14:45:40 -07004407 private BroadcastReceiver mPackageInstallationReceiver;
4408
Bjorn Bringerta7611812010-03-24 11:12:02 +00004409 private SystemAllowGeolocationOrigins mSystemAllowGeolocationOrigins;
4410
The Android Open Source Project0c908882009-03-03 19:32:16 -08004411 // activity requestCode
Nicolas Roard78a98e42009-05-11 13:34:17 +01004412 final static int COMBO_PAGE = 1;
4413 final static int DOWNLOAD_PAGE = 2;
4414 final static int PREFERENCES_PAGE = 3;
Leon Scroggins8d5fa432009-10-02 15:55:59 -04004415 final static int FILE_SELECTED = 4;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004416
Andrei Popescu540035d2009-09-18 18:59:20 +01004417 // the default <video> poster
4418 private Bitmap mDefaultVideoPoster;
4419 // the video progress view
4420 private View mVideoProgressView;
4421
Andrei Popescu30995e72010-02-09 16:59:58 +00004422 // The Google packages we monitor for the navigator.isApplicationInstalled()
4423 // API. Add as needed.
4424 private static Set<String> sGoogleApps;
4425 static {
4426 sGoogleApps = new HashSet<String>();
4427 sGoogleApps.add("com.google.android.youtube");
4428 }
4429
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004430 /**
4431 * A UrlData class to abstract how the content will be set to WebView.
4432 * This base class uses loadUrl to show the content.
4433 */
Leon Scroggins6eac63e2010-03-15 18:19:14 -04004434 /* package */ static class UrlData {
Grace Kloba068e48b2010-01-26 18:11:27 -08004435 final String mUrl;
4436 final Map<String, String> mHeaders;
Leon Scroggins58d56c62010-01-28 15:12:40 -05004437 final Intent mVoiceIntent;
Grace Kloba60e095c2009-06-16 11:50:55 -07004438
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004439 UrlData(String url) {
4440 this.mUrl = url;
Grace Kloba068e48b2010-01-26 18:11:27 -08004441 this.mHeaders = null;
Leon Scroggins58d56c62010-01-28 15:12:40 -05004442 this.mVoiceIntent = null;
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004443 }
Grace Kloba60e095c2009-06-16 11:50:55 -07004444
Leon Scroggins58d56c62010-01-28 15:12:40 -05004445 UrlData(String url, Map<String, String> headers, Intent intent) {
Grace Kloba068e48b2010-01-26 18:11:27 -08004446 this.mUrl = url;
4447 this.mHeaders = headers;
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -05004448 if (RecognizerResultsIntent.ACTION_VOICE_SEARCH_RESULTS
4449 .equals(intent.getAction())) {
Leon Scroggins58d56c62010-01-28 15:12:40 -05004450 this.mVoiceIntent = intent;
4451 } else {
4452 this.mVoiceIntent = null;
4453 }
Grace Kloba60e095c2009-06-16 11:50:55 -07004454 }
4455
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004456 boolean isEmpty() {
Leon Scroggins58d56c62010-01-28 15:12:40 -05004457 return mVoiceIntent == null && (mUrl == null || mUrl.length() == 0);
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004458 }
4459
Leon Scroggins92472e82010-02-17 16:32:28 -05004460 /**
4461 * Load this UrlData into the given Tab. Use loadUrlDataIn to update
4462 * the title bar as well.
4463 */
Leon Scroggins58d56c62010-01-28 15:12:40 -05004464 public void loadIn(Tab t) {
4465 if (mVoiceIntent != null) {
4466 t.activateVoiceSearchMode(mVoiceIntent);
4467 } else {
4468 t.getWebView().loadUrl(mUrl, mHeaders);
4469 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004470 }
4471 };
4472
Leon Scroggins1f005d32009-08-10 17:36:42 -04004473 /* package */ static final UrlData EMPTY_URL_DATA = new UrlData(null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004474}