blob: 99bf0174cd073c424ac50cc89d08e89c57249a0f [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
Grace Kloba22ac16e2009-10-07 18:00:23 -0700170 @Override
171 public void onCreate(Bundle icicle) {
Dave Bort31a6d1c2009-04-13 15:56:49 -0700172 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800173 Log.v(LOGTAG, this + " onStart");
174 }
175 super.onCreate(icicle);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800176 // test the browser in OpenGL
177 // requestWindowFeature(Window.FEATURE_OPENGL);
178
Mike Reedd334bf52010-01-26 15:21:44 -0500179 // enable this to test the browser in 32bit
180 if (false) {
181 getWindow().setFormat(PixelFormat.RGBX_8888);
182 BitmapFactory.setDefaultConfig(Bitmap.Config.ARGB_8888);
183 }
184
Svetoslav Ganov2b345992010-05-06 06:13:54 -0700185 if (AccessibilityManager.getInstance(this).isEnabled()) {
186 setDefaultKeyMode(DEFAULT_KEYS_DISABLE);
187 } else {
188 setDefaultKeyMode(DEFAULT_KEYS_SEARCH_LOCAL);
189 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800190
191 mResolver = getContentResolver();
192
Grace Kloba0923d692009-09-23 21:37:25 -0700193 // If this was a web search request, pass it on to the default web
194 // search provider and finish this activity.
195 if (handleWebSearchIntent(getIntent())) {
196 finish();
197 return;
198 }
199
The Android Open Source Project0c908882009-03-03 19:32:16 -0800200 mSecLockIcon = Resources.getSystem().getDrawable(
201 android.R.drawable.ic_secure);
202 mMixLockIcon = Resources.getSystem().getDrawable(
203 android.R.drawable.ic_partial_secure);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800204
Michael Kolbed217742010-08-10 17:52:34 -0700205 // Create the tab control and our initial tab
206 mTabControl = new TabControl(this);
207
208 mXLargeScreenSize = (getResources().getConfiguration().screenLayout
209 & Configuration.SCREENLAYOUT_SIZE_MASK)
210 == Configuration.SCREENLAYOUT_SIZE_XLARGE;
211
Leon Scroggins81db3662009-06-04 17:45:11 -0400212 FrameLayout frameLayout = (FrameLayout) getWindow().getDecorView()
213 .findViewById(com.android.internal.R.id.content);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400214 mBrowserFrameLayout = (FrameLayout) LayoutInflater.from(this)
215 .inflate(R.layout.custom_screen, null);
216 mContentView = (FrameLayout) mBrowserFrameLayout.findViewById(
217 R.id.main_content);
218 mErrorConsoleContainer = (LinearLayout) mBrowserFrameLayout
219 .findViewById(R.id.error_console);
220 mCustomViewContainer = (FrameLayout) mBrowserFrameLayout
221 .findViewById(R.id.fullscreen_custom_content);
222 frameLayout.addView(mBrowserFrameLayout, COVER_SCREEN_PARAMS);
Michael Kolbe0a36662010-06-29 10:37:12 -0700223
Leon Scrogginsd746a942010-05-19 13:21:44 -0400224 if (mXLargeScreenSize) {
Michael Kolba2b2ba82010-08-04 17:54:03 -0700225 mTitleBar = new TitleBarXLarge(this);
226 mTitleBar.setProgress(100);
227 mFakeTitleBar = new TitleBarXLarge(this);
Michael Kolbed217742010-08-10 17:52:34 -0700228 ActionBar actionBar = getActionBar();
Michael Kolba2b2ba82010-08-04 17:54:03 -0700229 mTabBar = new TabBar(this, mTabControl, (TitleBarXLarge) mFakeTitleBar);
Michael Kolbed217742010-08-10 17:52:34 -0700230 actionBar.setCustomNavigationMode(mTabBar);
Leon Scrogginsd746a942010-05-19 13:21:44 -0400231 } else {
Leon Scroggins571b3762010-05-26 10:25:01 -0400232 mTitleBar = new TitleBar(this);
Leon Scrogginsd746a942010-05-19 13:21:44 -0400233 // mTitleBar will be always be shown in the fully loaded mode on
234 // phone
235 mTitleBar.setProgress(100);
Leon Scrogginsd746a942010-05-19 13:21:44 -0400236 mFakeTitleBar = new TitleBar(this);
237 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800238
The Android Open Source Project0c908882009-03-03 19:32:16 -0800239 // Open the icon database and retain all the bookmark urls for favicons
240 retainIconsOnStartup();
241
242 // Keep a settings instance handy.
243 mSettings = BrowserSettings.getInstance();
244 mSettings.setTabControl(mTabControl);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800245
246 PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
247 mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Browser");
248
Patrick Scott6adacc92010-03-05 08:24:51 -0500249 // Find out if the network is currently up.
250 ConnectivityManager cm = (ConnectivityManager) getSystemService(
251 Context.CONNECTIVITY_SERVICE);
252 NetworkInfo info = cm.getActiveNetworkInfo();
253 if (info != null) {
254 mIsNetworkUp = info.isAvailable();
255 }
256
Grace Klobaa34f6862009-07-31 16:28:17 -0700257 /* enables registration for changes in network status from
258 http stack */
259 mNetworkStateChangedFilter = new IntentFilter();
260 mNetworkStateChangedFilter.addAction(
261 ConnectivityManager.CONNECTIVITY_ACTION);
262 mNetworkStateIntentReceiver = new BroadcastReceiver() {
263 @Override
264 public void onReceive(Context context, Intent intent) {
265 if (intent.getAction().equals(
266 ConnectivityManager.CONNECTIVITY_ACTION)) {
Andrei Popescue4c98462010-02-19 15:44:13 +0000267
268 NetworkInfo info = intent.getParcelableExtra(
269 ConnectivityManager.EXTRA_NETWORK_INFO);
270 String typeName = info.getTypeName();
271 String subtypeName = info.getSubtypeName();
272 sendNetworkType(typeName.toLowerCase(),
273 (subtypeName != null ? subtypeName.toLowerCase() : ""));
274
275 onNetworkToggle(info.isAvailable());
Grace Klobaa34f6862009-07-31 16:28:17 -0700276 }
277 }
278 };
279
Grace Kloba615c6c92009-08-03 10:22:44 -0700280 IntentFilter filter = new IntentFilter(Intent.ACTION_PACKAGE_ADDED);
281 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
282 filter.addDataScheme("package");
283 mPackageInstallationReceiver = new BroadcastReceiver() {
284 @Override
285 public void onReceive(Context context, Intent intent) {
286 final String action = intent.getAction();
287 final String packageName = intent.getData()
288 .getSchemeSpecificPart();
289 final boolean replacing = intent.getBooleanExtra(
290 Intent.EXTRA_REPLACING, false);
291 if (Intent.ACTION_PACKAGE_REMOVED.equals(action) && replacing) {
292 // if it is replacing, refreshPlugins() when adding
293 return;
294 }
Andrei Popescu30995e72010-02-09 16:59:58 +0000295
296 if (sGoogleApps.contains(packageName)) {
297 BrowserActivity.this.packageChanged(packageName,
298 Intent.ACTION_PACKAGE_ADDED.equals(action));
299 }
300
Grace Kloba615c6c92009-08-03 10:22:44 -0700301 PackageManager pm = BrowserActivity.this.getPackageManager();
302 PackageInfo pkgInfo = null;
303 try {
304 pkgInfo = pm.getPackageInfo(packageName,
305 PackageManager.GET_PERMISSIONS);
306 } catch (PackageManager.NameNotFoundException e) {
307 return;
308 }
309 if (pkgInfo != null) {
310 String permissions[] = pkgInfo.requestedPermissions;
311 if (permissions == null) {
312 return;
313 }
314 boolean permissionOk = false;
315 for (String permit : permissions) {
316 if (PluginManager.PLUGIN_PERMISSION.equals(permit)) {
317 permissionOk = true;
318 break;
319 }
320 }
321 if (permissionOk) {
322 PluginManager.getInstance(BrowserActivity.this)
Grace Klobae56a0f22010-05-26 17:31:02 -0700323 .refreshPlugins(true);
Grace Kloba615c6c92009-08-03 10:22:44 -0700324 }
325 }
326 }
327 };
328 registerReceiver(mPackageInstallationReceiver, filter);
329
The Android Open Source Project0c908882009-03-03 19:32:16 -0800330 if (!mTabControl.restoreState(icicle)) {
331 // clear up the thumbnail directory if we can't restore the state as
332 // none of the files in the directory are referenced any more.
333 new ClearThumbnails().execute(
334 mTabControl.getThumbnailDir().listFiles());
Grace Klobaaab3f092009-07-30 12:29:51 -0700335 // there is no quit on Android. But if we can't restore the state,
336 // we can treat it as a new Browser, remove the old session cookies.
337 CookieManager.getInstance().removeSessionCookie();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800338 final Intent intent = getIntent();
339 final Bundle extra = intent.getExtras();
340 // Create an initial tab.
341 // If the intent is ACTION_VIEW and data is not null, the Browser is
342 // invoked to view the content by another application. In this case,
343 // the tab will be close when exit.
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700344 UrlData urlData = getUrlDataFromIntent(intent);
345
Leon Scroggins58d56c62010-01-28 15:12:40 -0500346 String action = intent.getAction();
Grace Kloba22ac16e2009-10-07 18:00:23 -0700347 final Tab t = mTabControl.createNewTab(
Leon Scroggins58d56c62010-01-28 15:12:40 -0500348 (Intent.ACTION_VIEW.equals(action) &&
349 intent.getData() != null)
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -0500350 || RecognizerResultsIntent.ACTION_VOICE_SEARCH_RESULTS
351 .equals(action),
Elliott Slaughterf0f03952010-07-14 18:10:36 -0700352 intent.getStringExtra(Browser.EXTRA_APPLICATION_ID),
353 urlData.mUrl, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800354 mTabControl.setCurrentTab(t);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800355 attachTabToContentView(t);
356 WebView webView = t.getWebView();
357 if (extra != null) {
358 int scale = extra.getInt(Browser.INITIAL_ZOOM_LEVEL, 0);
359 if (scale > 0 && scale <= 1000) {
360 webView.setInitialScale(scale);
361 }
362 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800363
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700364 if (urlData.isEmpty()) {
Shimeng (Simon) Wang98d5fce2010-03-16 13:23:39 -0700365 loadUrl(webView, mSettings.getHomePage());
The Android Open Source Project0c908882009-03-03 19:32:16 -0800366 } else {
Patrick Scott9d53da02010-02-19 10:19:01 -0500367 loadUrlDataIn(t, urlData);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800368 }
369 } else {
370 // TabControl.restoreState() will create a new tab even if
Leon Scroggins1f005d32009-08-10 17:36:42 -0400371 // restoring the state fails.
The Android Open Source Project0c908882009-03-03 19:32:16 -0800372 attachTabToContentView(mTabControl.getCurrentTab());
373 }
Grace Kloba615c6c92009-08-03 10:22:44 -0700374
Cary Clarkb4b83182010-07-01 12:36:56 -0400375 // Delete old thumbnails to save space
376 File dir = mTabControl.getThumbnailDir();
377 if (dir.exists()) {
378 for (String child : dir.list()) {
379 File f = new File(dir, child);
380 f.delete();
381 }
382 }
383
Feng Qianb3c02da2009-06-29 15:58:08 -0700384 // Read JavaScript flags if it exists.
385 String jsFlags = mSettings.getJsFlags();
386 if (jsFlags.trim().length() != 0) {
387 mTabControl.getCurrentWebView().setJsFlags(jsFlags);
388 }
Andrei Popescu30995e72010-02-09 16:59:58 +0000389 // Work out which packages are installed on the system.
390 getInstalledPackages();
Bjorn Bringerta7611812010-03-24 11:12:02 +0000391
392 // Start watching the default geolocation permissions
393 mSystemAllowGeolocationOrigins
394 = new SystemAllowGeolocationOrigins(getApplicationContext());
395 mSystemAllowGeolocationOrigins.start();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800396 }
397
Michael Kolba2b2ba82010-08-04 17:54:03 -0700398 ScrollListener getScrollListener() {
399 return mTabBar;
400 }
401
Leon Scroggins58d56c62010-01-28 15:12:40 -0500402 /**
403 * Feed the previously stored results strings to the BrowserProvider so that
404 * the SearchDialog will show them instead of the standard searches.
405 * @param result String to show on the editable line of the SearchDialog.
406 */
407 /* package */ void showVoiceSearchResults(String result) {
408 ContentProviderClient client = mResolver.acquireContentProviderClient(
409 Browser.BOOKMARKS_URI);
410 ContentProvider prov = client.getLocalContentProvider();
411 BrowserProvider bp = (BrowserProvider) prov;
412 bp.setQueryResults(mTabControl.getCurrentTab().getVoiceSearchResults());
413 client.release();
414
Leon Scrogginsfbb3f152010-03-09 17:26:56 -0500415 Bundle bundle = createGoogleSearchSourceBundle(
416 GOOGLE_SEARCH_SOURCE_SEARCHKEY);
417 bundle.putBoolean(SearchManager.CONTEXT_IS_VOICE, true);
418 startSearch(result, false, bundle, false);
Leon Scroggins58d56c62010-01-28 15:12:40 -0500419 }
420
The Android Open Source Project0c908882009-03-03 19:32:16 -0800421 @Override
422 protected void onNewIntent(Intent intent) {
Grace Kloba22ac16e2009-10-07 18:00:23 -0700423 Tab current = mTabControl.getCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800424 // When a tab is closed on exit, the current tab index is set to -1.
425 // Reset before proceed as Browser requires the current tab to be set.
426 if (current == null) {
427 // Try to reset the tab in case the index was incorrect.
428 current = mTabControl.getTab(0);
429 if (current == null) {
430 // No tabs at all so just ignore this intent.
431 return;
432 }
433 mTabControl.setCurrentTab(current);
434 attachTabToContentView(current);
435 resetTitleAndIcon(current.getWebView());
436 }
437 final String action = intent.getAction();
438 final int flags = intent.getFlags();
439 if (Intent.ACTION_MAIN.equals(action) ||
440 (flags & Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY) != 0) {
441 // just resume the browser
442 return;
443 }
Leon Scrogginsb8a844d2010-03-18 15:06:15 -0400444 // In case the SearchDialog is open.
445 ((SearchManager) getSystemService(Context.SEARCH_SERVICE))
446 .stopSearch();
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -0500447 boolean activateVoiceSearch = RecognizerResultsIntent
448 .ACTION_VOICE_SEARCH_RESULTS.equals(action);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800449 if (Intent.ACTION_VIEW.equals(action)
450 || Intent.ACTION_SEARCH.equals(action)
451 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
Leon Scroggins58d56c62010-01-28 15:12:40 -0500452 || Intent.ACTION_WEB_SEARCH.equals(action)
453 || activateVoiceSearch) {
Leon Scroggins3b18ce32010-02-08 17:35:59 -0500454 if (current.isInVoiceSearchMode()) {
455 String title = current.getVoiceDisplayTitle();
456 if (title != null && title.equals(intent.getStringExtra(
457 SearchManager.QUERY))) {
458 // The user submitted the same search as the last voice
459 // search, so do nothing.
460 return;
461 }
Leon Scroggins1fe13a52010-02-09 15:31:26 -0500462 if (Intent.ACTION_SEARCH.equals(action)
463 && current.voiceSearchSourceIsGoogle()) {
464 Intent logIntent = new Intent(
465 LoggingEvents.ACTION_LOG_EVENT);
466 logIntent.putExtra(LoggingEvents.EXTRA_EVENT,
467 LoggingEvents.VoiceSearch.QUERY_UPDATED);
468 logIntent.putExtra(
469 LoggingEvents.VoiceSearch.EXTRA_QUERY_UPDATED_VALUE,
470 intent.getDataString());
471 sendBroadcast(logIntent);
472 // Note, onPageStarted will revert the voice title bar
473 // When http://b/issue?id=2379215 is fixed, we should update
474 // the title bar here.
475 }
Leon Scroggins3b18ce32010-02-08 17:35:59 -0500476 }
Satish Sampath565505b2009-05-29 15:37:27 +0100477 // If this was a search request (e.g. search query directly typed into the address bar),
478 // pass it on to the default web search provider.
479 if (handleWebSearchIntent(intent)) {
480 return;
481 }
482
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700483 UrlData urlData = getUrlDataFromIntent(intent);
484 if (urlData.isEmpty()) {
485 urlData = new UrlData(mSettings.getHomePage());
The Android Open Source Project0c908882009-03-03 19:32:16 -0800486 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700487
Grace Klobacc634032009-07-28 15:58:19 -0700488 final String appId = intent
489 .getStringExtra(Browser.EXTRA_APPLICATION_ID);
Leon Scroggins47208682010-04-07 17:59:48 -0400490 if ((Intent.ACTION_VIEW.equals(action)
491 // If a voice search has no appId, it means that it came
492 // from the browser. In that case, reuse the current tab.
493 || (activateVoiceSearch && appId != null))
Grace Klobacc634032009-07-28 15:58:19 -0700494 && !getPackageName().equals(appId)
495 && (flags & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0) {
Grace Kloba22ac16e2009-10-07 18:00:23 -0700496 Tab appTab = mTabControl.getTabFromId(appId);
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700497 if (appTab != null) {
498 Log.i(LOGTAG, "Reusing tab for " + appId);
499 // Dismiss the subwindow if applicable.
500 dismissSubWindow(appTab);
501 // Since we might kill the WebView, remove it from the
502 // content view first.
503 removeTabFromContentView(appTab);
504 // Recreate the main WebView after destroying the old one.
505 // If the WebView has the same original url and is on that
506 // page, it can be reused.
507 boolean needsLoad =
Leon Scroggins6eac63e2010-03-15 18:19:14 -0400508 mTabControl.recreateWebView(appTab, urlData);
Ben Murdochbff2d602009-07-01 20:19:05 +0100509
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700510 if (current != appTab) {
Leon Scroggins1f005d32009-08-10 17:36:42 -0400511 switchToTab(mTabControl.getTabIndex(appTab));
512 if (needsLoad) {
Patrick Scott9d53da02010-02-19 10:19:01 -0500513 loadUrlDataIn(appTab, urlData);
Leon Scroggins1f005d32009-08-10 17:36:42 -0400514 }
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700515 } else {
Leon Scroggins1f005d32009-08-10 17:36:42 -0400516 // If the tab was the current tab, we have to attach
517 // it to the view system again.
518 attachTabToContentView(appTab);
519 if (needsLoad) {
Patrick Scott9d53da02010-02-19 10:19:01 -0500520 loadUrlDataIn(appTab, urlData);
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700521 }
522 }
523 return;
Patrick Scottcd115892009-07-16 09:42:58 -0400524 } else {
525 // No matching application tab, try to find a regular tab
526 // with a matching url.
527 appTab = mTabControl.findUnusedTabWithUrl(urlData.mUrl);
Leon Scroggins25515f82009-08-19 15:31:58 -0400528 if (appTab != null) {
529 if (current != appTab) {
530 switchToTab(mTabControl.getTabIndex(appTab));
531 }
532 // Otherwise, we are already viewing the correct tab.
Patrick Scottcd115892009-07-16 09:42:58 -0400533 } else {
534 // if FLAG_ACTIVITY_BROUGHT_TO_FRONT flag is on, the url
535 // will be opened in a new tab unless we have reached
536 // MAX_TABS. Then the url will be opened in the current
537 // tab. If a new tab is created, it will have "true" for
538 // exit on close.
Leon Scroggins1f005d32009-08-10 17:36:42 -0400539 openTabAndShow(urlData, true, appId);
Patrick Scottcd115892009-07-16 09:42:58 -0400540 }
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700541 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800542 } else {
Grace Kloba638d3f42009-11-23 10:35:04 -0800543 if (!urlData.isEmpty()
544 && urlData.mUrl.startsWith("about:debug")) {
545 if ("about:debug.dom".equals(urlData.mUrl)) {
546 current.getWebView().dumpDomTree(false);
547 } else if ("about:debug.dom.file".equals(urlData.mUrl)) {
548 current.getWebView().dumpDomTree(true);
549 } else if ("about:debug.render".equals(urlData.mUrl)) {
550 current.getWebView().dumpRenderTree(false);
551 } else if ("about:debug.render.file".equals(urlData.mUrl)) {
552 current.getWebView().dumpRenderTree(true);
553 } else if ("about:debug.display".equals(urlData.mUrl)) {
554 current.getWebView().dumpDisplayTree();
Mike Reed9b78e1d2010-01-13 14:40:52 -0800555 } else if (urlData.mUrl.startsWith("about:debug.drag")) {
556 int index = urlData.mUrl.codePointAt(16) - '0';
557 if (index <= 0 || index > 9) {
558 current.getWebView().setDragTracker(null);
559 } else {
560 current.getWebView().setDragTracker(new MeshTracker(index));
561 }
Grace Kloba638d3f42009-11-23 10:35:04 -0800562 } else {
563 mSettings.toggleDebugSettings();
564 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800565 return;
566 }
Leon Scroggins1f005d32009-08-10 17:36:42 -0400567 // Get rid of the subwindow if it exists
568 dismissSubWindow(current);
Leon Scroggins8588d152010-04-15 11:01:53 -0400569 // If the current Tab is being used as an application tab,
570 // remove the association, since the new Intent means that it is
571 // no longer associated with that application.
572 current.setAppId(null);
Patrick Scott9d53da02010-02-19 10:19:01 -0500573 loadUrlDataIn(current, urlData);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800574 }
575 }
576 }
577
Satish Sampath565505b2009-05-29 15:37:27 +0100578 private int parseUrlShortcut(String url) {
579 if (url == null) return SHORTCUT_INVALID;
580
581 // FIXME: quick search, need to be customized by setting
582 if (url.length() > 2 && url.charAt(1) == ' ') {
583 switch (url.charAt(0)) {
584 case 'g': return SHORTCUT_GOOGLE_SEARCH;
585 case 'w': return SHORTCUT_WIKIPEDIA_SEARCH;
586 case 'd': return SHORTCUT_DICTIONARY_SEARCH;
587 case 'l': return SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH;
588 }
589 }
590 return SHORTCUT_INVALID;
591 }
592
593 /**
594 * Launches the default web search activity with the query parameters if the given intent's data
595 * are identified as plain search terms and not URLs/shortcuts.
596 * @return true if the intent was handled and web search activity was launched, false if not.
597 */
598 private boolean handleWebSearchIntent(Intent intent) {
599 if (intent == null) return false;
600
601 String url = null;
602 final String action = intent.getAction();
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -0500603 if (RecognizerResultsIntent.ACTION_VOICE_SEARCH_RESULTS.equals(
604 action)) {
Leon Scroggins58d56c62010-01-28 15:12:40 -0500605 return false;
606 }
Satish Sampath565505b2009-05-29 15:37:27 +0100607 if (Intent.ACTION_VIEW.equals(action)) {
Grace Kloba1e705052009-09-29 13:13:36 -0700608 Uri data = intent.getData();
609 if (data != null) url = data.toString();
Satish Sampath565505b2009-05-29 15:37:27 +0100610 } else if (Intent.ACTION_SEARCH.equals(action)
611 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
612 || Intent.ACTION_WEB_SEARCH.equals(action)) {
613 url = intent.getStringExtra(SearchManager.QUERY);
614 }
Bjorn Bringert04851702009-09-22 10:36:01 +0100615 return handleWebSearchRequest(url, intent.getBundleExtra(SearchManager.APP_DATA),
616 intent.getStringExtra(SearchManager.EXTRA_DATA_KEY));
Satish Sampath565505b2009-05-29 15:37:27 +0100617 }
618
619 /**
620 * Launches the default web search activity with the query parameters if the given url string
621 * was identified as plain search terms and not URL/shortcut.
622 * @return true if the request was handled and web search activity was launched, false if not.
623 */
Bjorn Bringert04851702009-09-22 10:36:01 +0100624 private boolean handleWebSearchRequest(String inUrl, Bundle appData, String extraData) {
Satish Sampath565505b2009-05-29 15:37:27 +0100625 if (inUrl == null) return false;
626
627 // In general, we shouldn't modify URL from Intent.
628 // But currently, we get the user-typed URL from search box as well.
629 String url = fixUrl(inUrl).trim();
630
631 // URLs and site specific search shortcuts are handled by the regular flow of control, so
632 // return early.
Dan Egnor5ee906c2009-11-18 12:11:49 -0800633 if (Patterns.WEB_URL.matcher(url).matches()
Satish Sampathbc5b9f32009-06-04 18:21:40 +0100634 || ACCEPTED_URI_SCHEMA.matcher(url).matches()
Satish Sampath565505b2009-05-29 15:37:27 +0100635 || parseUrlShortcut(url) != SHORTCUT_INVALID) {
636 return false;
637 }
638
Leon Scroggins8d06e362010-03-24 14:45:57 -0400639 final ContentResolver cr = mResolver;
640 final String newUrl = url;
Elliott Slaughterf0f03952010-07-14 18:10:36 -0700641 if (!mTabControl.getCurrentWebView().isPrivateBrowsingEnabled()) {
642 new AsyncTask<Void, Void, Void>() {
643 @Override
644 protected Void doInBackground(Void... unused) {
645 Browser.updateVisitedHistory(cr, newUrl, false);
646 Browser.addSearchUrl(cr, newUrl);
647 return null;
648 }
649 }.execute();
650 }
Satish Sampath565505b2009-05-29 15:37:27 +0100651
652 Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);
653 intent.addCategory(Intent.CATEGORY_DEFAULT);
654 intent.putExtra(SearchManager.QUERY, url);
Satish Sampath15e9f2d2009-06-23 22:29:49 +0100655 if (appData != null) {
656 intent.putExtra(SearchManager.APP_DATA, appData);
657 }
Bjorn Bringert04851702009-09-22 10:36:01 +0100658 if (extraData != null) {
659 intent.putExtra(SearchManager.EXTRA_DATA_KEY, extraData);
660 }
Grace Klobacc634032009-07-28 15:58:19 -0700661 intent.putExtra(Browser.EXTRA_APPLICATION_ID, getPackageName());
Satish Sampath565505b2009-05-29 15:37:27 +0100662 startActivity(intent);
663
664 return true;
665 }
666
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700667 private UrlData getUrlDataFromIntent(Intent intent) {
Leon Scroggins58d56c62010-01-28 15:12:40 -0500668 String url = "";
Grace Kloba068e48b2010-01-26 18:11:27 -0800669 Map<String, String> headers = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800670 if (intent != null) {
671 final String action = intent.getAction();
672 if (Intent.ACTION_VIEW.equals(action)) {
673 url = smartUrlFilter(intent.getData());
674 if (url != null && url.startsWith("content:")) {
675 /* Append mimetype so webview knows how to display */
676 String mimeType = intent.resolveType(getContentResolver());
677 if (mimeType != null) {
678 url += "?" + mimeType;
679 }
680 }
Grace Kloba068e48b2010-01-26 18:11:27 -0800681 if (url != null && url.startsWith("http")) {
Grace Kloba00f54c52010-01-27 14:53:51 -0800682 final Bundle pairs = intent
683 .getBundleExtra(Browser.EXTRA_HEADERS);
Grace Kloba2d508ed2010-01-28 11:39:15 -0800684 if (pairs != null && !pairs.isEmpty()) {
Grace Kloba00f54c52010-01-27 14:53:51 -0800685 Iterator<String> iter = pairs.keySet().iterator();
Grace Kloba068e48b2010-01-26 18:11:27 -0800686 headers = new HashMap<String, String>();
Grace Kloba00f54c52010-01-27 14:53:51 -0800687 while (iter.hasNext()) {
688 String key = iter.next();
689 headers.put(key, pairs.getString(key));
Grace Kloba068e48b2010-01-26 18:11:27 -0800690 }
691 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700692 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800693 } else if (Intent.ACTION_SEARCH.equals(action)
694 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
695 || Intent.ACTION_WEB_SEARCH.equals(action)) {
696 url = intent.getStringExtra(SearchManager.QUERY);
697 if (url != null) {
698 mLastEnteredUrl = url;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800699 // In general, we shouldn't modify URL from Intent.
700 // But currently, we get the user-typed URL from search box as well.
701 url = fixUrl(url);
702 url = smartUrlFilter(url);
Leon Scroggins8d06e362010-03-24 14:45:57 -0400703 final ContentResolver cr = mResolver;
704 final String newUrl = url;
705 new AsyncTask<Void, Void, Void>() {
Michael Kolbe0a36662010-06-29 10:37:12 -0700706 @Override
Leon Scroggins8d06e362010-03-24 14:45:57 -0400707 protected Void doInBackground(Void... unused) {
708 Browser.updateVisitedHistory(cr, newUrl, false);
709 return null;
710 }
711 }.execute();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800712 String searchSource = "&source=android-" + GOOGLE_SEARCH_SOURCE_SUGGEST + "&";
713 if (url.contains(searchSource)) {
714 String source = null;
715 final Bundle appData = intent.getBundleExtra(SearchManager.APP_DATA);
716 if (appData != null) {
Bjorn Bringert10d1cca2010-02-10 14:22:12 +0000717 source = appData.getString(Search.SOURCE);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800718 }
719 if (TextUtils.isEmpty(source)) {
720 source = GOOGLE_SEARCH_SOURCE_UNKNOWN;
721 }
722 url = url.replace(searchSource, "&source=android-"+source+"&");
723 }
724 }
725 }
726 }
Leon Scroggins58d56c62010-01-28 15:12:40 -0500727 return new UrlData(url, headers, intent);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800728 }
Leon Scroggins58d56c62010-01-28 15:12:40 -0500729 /* package */ void showVoiceTitleBar(String title) {
730 mTitleBar.setInVoiceMode(true);
Leon Scroggins58d56c62010-01-28 15:12:40 -0500731 mTitleBar.setDisplayTitle(title);
Michael Kolba2b2ba82010-08-04 17:54:03 -0700732 mFakeTitleBar.setInVoiceMode(true);
733 mFakeTitleBar.setDisplayTitle(title);
Leon Scroggins58d56c62010-01-28 15:12:40 -0500734 }
735 /* package */ void revertVoiceTitleBar() {
736 mTitleBar.setInVoiceMode(false);
Leon Scroggins003a5dd2010-03-10 12:13:14 -0500737 mTitleBar.setDisplayTitle(mUrl);
Michael Kolba2b2ba82010-08-04 17:54:03 -0700738 mFakeTitleBar.setInVoiceMode(false);
739 mFakeTitleBar.setDisplayTitle(mUrl);
Leon Scroggins58d56c62010-01-28 15:12:40 -0500740 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800741 /* package */ static String fixUrl(String inUrl) {
Cary Clark652ff872009-09-10 13:34:44 -0400742 // FIXME: Converting the url to lower case
743 // duplicates functionality in smartUrlFilter().
744 // However, changing all current callers of fixUrl to
745 // call smartUrlFilter in addition may have unwanted
746 // consequences, and is deferred for now.
747 int colon = inUrl.indexOf(':');
748 boolean allLower = true;
749 for (int index = 0; index < colon; index++) {
750 char ch = inUrl.charAt(index);
751 if (!Character.isLetter(ch)) {
752 break;
753 }
754 allLower &= Character.isLowerCase(ch);
755 if (index == colon - 1 && !allLower) {
756 inUrl = inUrl.substring(0, colon).toLowerCase()
757 + inUrl.substring(colon);
758 }
759 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800760 if (inUrl.startsWith("http://") || inUrl.startsWith("https://"))
761 return inUrl;
762 if (inUrl.startsWith("http:") ||
763 inUrl.startsWith("https:")) {
764 if (inUrl.startsWith("http:/") || inUrl.startsWith("https:/")) {
765 inUrl = inUrl.replaceFirst("/", "//");
766 } else inUrl = inUrl.replaceFirst(":", "://");
767 }
768 return inUrl;
769 }
770
Grace Kloba22ac16e2009-10-07 18:00:23 -0700771 @Override
772 protected void onResume() {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800773 super.onResume();
Dave Bort31a6d1c2009-04-13 15:56:49 -0700774 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800775 Log.v(LOGTAG, "BrowserActivity.onResume: this=" + this);
776 }
777
778 if (!mActivityInPause) {
779 Log.e(LOGTAG, "BrowserActivity is already resumed.");
780 return;
781 }
782
Mike Reed7bfa63b2009-05-28 11:08:32 -0400783 mTabControl.resumeCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800784 mActivityInPause = false;
Mike Reed7bfa63b2009-05-28 11:08:32 -0400785 resumeWebViewTimers();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800786
787 if (mWakeLock.isHeld()) {
788 mHandler.removeMessages(RELEASE_WAKELOCK);
789 mWakeLock.release();
790 }
791
The Android Open Source Project0c908882009-03-03 19:32:16 -0800792 registerReceiver(mNetworkStateIntentReceiver,
793 mNetworkStateChangedFilter);
794 WebView.enablePlatformNotifications();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800795 }
796
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400797 /**
798 * Since the actual title bar is embedded in the WebView, and removing it
Leon Scrogginsfe87bd32009-10-06 10:10:00 -0400799 * would change its appearance, use a different TitleBar to show overlayed
800 * at the top of the screen, when the menu is open or the page is loading.
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400801 */
Michael Kolba2b2ba82010-08-04 17:54:03 -0700802 private TitleBarBase mFakeTitleBar;
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400803
804 /**
805 * Keeps track of whether the options menu is open. This is important in
806 * determining whether to show or hide the title bar overlay.
807 */
808 private boolean mOptionsMenuOpen;
809
810 /**
811 * Only meaningful when mOptionsMenuOpen is true. This variable keeps track
812 * of whether the configuration has changed. The first onMenuOpened call
813 * after a configuration change is simply a reopening of the same menu
814 * (i.e. mIconView did not change).
815 */
816 private boolean mConfigChanged;
817
818 /**
819 * Whether or not the options menu is in its smaller, icon menu form. When
820 * true, we want the title bar overlay to be up. When false, we do not.
821 * Only meaningful if mOptionsMenuOpen is true.
822 */
823 private boolean mIconView;
824
Leon Scrogginsa81a7642009-08-31 17:05:41 -0400825 @Override
826 public boolean onMenuOpened(int featureId, Menu menu) {
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400827 if (Window.FEATURE_OPTIONS_PANEL == featureId) {
828 if (mOptionsMenuOpen) {
829 if (mConfigChanged) {
830 // We do not need to make any changes to the state of the
831 // title bar, since the only thing that happened was a
832 // change in orientation
833 mConfigChanged = false;
834 } else {
835 if (mIconView) {
836 // Switching the menu to expanded view, so hide the
837 // title bar.
838 hideFakeTitleBar();
839 mIconView = false;
840 } else {
841 // Switching the menu back to icon view, so show the
842 // title bar once again.
843 showFakeTitleBar();
844 mIconView = true;
845 }
846 }
847 } else {
848 // The options menu is closed, so open it, and show the title
849 showFakeTitleBar();
850 mOptionsMenuOpen = true;
851 mConfigChanged = false;
852 mIconView = true;
853 }
854 }
Leon Scrogginsa81a7642009-08-31 17:05:41 -0400855 return true;
856 }
857
Michael Kolba2b2ba82010-08-04 17:54:03 -0700858 void showFakeTitleBar() {
859 if (!isFakeTitleBarShowing() && mActiveTabsPage == null && !mActivityInPause) {
Grace Kloba847c25b2010-03-30 16:00:26 -0700860 WebView mainView = mTabControl.getCurrentWebView();
861 // if there is no current WebView, don't show the faked title bar;
Grace Kloba65190702010-04-02 23:37:26 -0700862 if (mainView == null) {
Cary Clarka0464552009-09-29 13:00:45 -0400863 return;
864 }
Leon Scroggins79e36d92010-04-29 16:01:46 +0100865 // Do not need to check for null, since the current tab will have
866 // at least a main WebView, or we would have returned above.
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -0400867 if (isInCustomActionMode()) {
868 // Do not show the fake title bar, while a custom ActionMode
869 // (i.e. find or select) is showing.
Leon Scroggins79e36d92010-04-29 16:01:46 +0100870 return;
871 }
Michael Kolba2b2ba82010-08-04 17:54:03 -0700872 if (mXLargeScreenSize) {
873 mContentView.addView(mFakeTitleBar);
874 mTabBar.onShowTitleBar();
875 } else {
876 WindowManager manager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400877
Michael Kolba2b2ba82010-08-04 17:54:03 -0700878 // Add the title bar to the window manager so it can receive
879 // touches
880 // while the menu is up
881 WindowManager.LayoutParams params =
882 new WindowManager.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
883 ViewGroup.LayoutParams.WRAP_CONTENT,
884 WindowManager.LayoutParams.TYPE_APPLICATION,
885 WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
886 PixelFormat.TRANSLUCENT);
887 params.gravity = Gravity.TOP;
888 boolean atTop = mainView.getScrollY() == 0;
889 params.windowAnimations = atTop ? 0 : R.style.TitleBar;
890 manager.addView(mFakeTitleBar, params);
891 }
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400892 }
893 }
894
895 @Override
896 public void onOptionsMenuClosed(Menu menu) {
897 mOptionsMenuOpen = false;
Leon Scrogginsa27ff192009-09-14 12:58:04 -0400898 if (!mInLoad) {
899 hideFakeTitleBar();
900 } else if (!mIconView) {
901 // The page is currently loading, and we are in expanded mode, so
902 // we were not showing the menu. Show it once again. It will be
903 // removed when the page finishes.
904 showFakeTitleBar();
905 }
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400906 }
Grace Kloba22ac16e2009-10-07 18:00:23 -0700907
Michael Kolba2b2ba82010-08-04 17:54:03 -0700908 void stopScrolling() {
909 ((ScrollWebView) mTabControl.getCurrentWebView()).stopScroll();
910 }
911
912 void hideFakeTitleBar() {
913 if (!isFakeTitleBarShowing()) return;
914 if (mXLargeScreenSize) {
915 mContentView.removeView(mFakeTitleBar);
916 mTabBar.onHideTitleBar();
917 } else {
918 WindowManager.LayoutParams params =
919 (WindowManager.LayoutParams) mFakeTitleBar.getLayoutParams();
920 WebView mainView = mTabControl.getCurrentWebView();
921 // Although we decided whether or not to animate based on the
922 // current
923 // scroll position, the scroll position may have changed since the
924 // fake title bar was displayed. Make sure it has the appropriate
925 // animation/lack thereof before removing.
926 params.windowAnimations =
927 mainView != null && mainView.getScrollY() == 0 ? 0 : R.style.TitleBar;
928 WindowManager manager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
929 manager.updateViewLayout(mFakeTitleBar, params);
930 manager.removeView(mFakeTitleBar);
931 }
932 }
933
934 boolean isFakeTitleBarShowing() {
935 return (mFakeTitleBar.getParent() != null);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400936 }
937
The Android Open Source Project0c908882009-03-03 19:32:16 -0800938 /**
Leon Scrogginsc6fa1102009-09-21 10:40:01 -0400939 * Special method for the fake title bar to call when displaying its context
940 * menu, since it is in its own Window, and its parent does not show a
941 * context menu.
942 */
943 /* package */ void showTitleBarContextMenu() {
Cary Clark65f4a3c2009-09-28 17:05:06 -0400944 if (null == mTitleBar.getParent()) {
945 return;
946 }
Leon Scrogginsc6fa1102009-09-21 10:40:01 -0400947 openContextMenu(mTitleBar);
948 }
949
Leon Scrogginsb2b19f52009-10-09 16:10:00 -0400950 @Override
951 public void onContextMenuClosed(Menu menu) {
952 super.onContextMenuClosed(menu);
953 if (mInLoad) {
954 showFakeTitleBar();
955 }
956 }
957
Leon Scrogginsc6fa1102009-09-21 10:40:01 -0400958 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -0800959 * onSaveInstanceState(Bundle map)
960 * onSaveInstanceState is called right before onStop(). The map contains
961 * the saved state.
962 */
Grace Kloba22ac16e2009-10-07 18:00:23 -0700963 @Override
964 protected void onSaveInstanceState(Bundle outState) {
Dave Bort31a6d1c2009-04-13 15:56:49 -0700965 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800966 Log.v(LOGTAG, "BrowserActivity.onSaveInstanceState: this=" + this);
967 }
968 // the default implementation requires each view to have an id. As the
969 // browser handles the state itself and it doesn't use id for the views,
970 // don't call the default implementation. Otherwise it will trigger the
971 // warning like this, "couldn't save which view has focus because the
972 // focused view XXX has no id".
973
974 // Save all the tabs
975 mTabControl.saveState(outState);
976 }
977
Grace Kloba22ac16e2009-10-07 18:00:23 -0700978 @Override
979 protected void onPause() {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800980 super.onPause();
981
982 if (mActivityInPause) {
983 Log.e(LOGTAG, "BrowserActivity is already paused.");
984 return;
985 }
986
Mike Reed7bfa63b2009-05-28 11:08:32 -0400987 mTabControl.pauseCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800988 mActivityInPause = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -0400989 if (mTabControl.getCurrentIndex() >= 0 && !pauseWebViewTimers()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800990 mWakeLock.acquire();
991 mHandler.sendMessageDelayed(mHandler
992 .obtainMessage(RELEASE_WAKELOCK), WAKELOCK_TIMEOUT);
993 }
994
Leon Scrogginsa2ab6a72009-09-11 11:49:52 -0400995 // FIXME: This removes the active tabs page and resets the menu to
996 // MAIN_MENU. A better solution might be to do this work in onNewIntent
997 // but then we would need to save it in onSaveInstanceState and restore
998 // it in onCreate/onRestoreInstanceState
999 if (mActiveTabsPage != null) {
1000 removeActiveTabPage(true);
1001 }
1002
The Android Open Source Project0c908882009-03-03 19:32:16 -08001003 cancelStopToast();
1004
1005 // unregister network state listener
1006 unregisterReceiver(mNetworkStateIntentReceiver);
1007 WebView.disablePlatformNotifications();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001008 }
1009
Grace Kloba22ac16e2009-10-07 18:00:23 -07001010 @Override
1011 protected void onDestroy() {
Dave Bort31a6d1c2009-04-13 15:56:49 -07001012 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001013 Log.v(LOGTAG, "BrowserActivity.onDestroy: this=" + this);
1014 }
1015 super.onDestroy();
Grace Kloba0923d692009-09-23 21:37:25 -07001016
Leon Scroggins8d5fa432009-10-02 15:55:59 -04001017 if (mUploadMessage != null) {
1018 mUploadMessage.onReceiveValue(null);
1019 mUploadMessage = null;
1020 }
1021
Grace Kloba0923d692009-09-23 21:37:25 -07001022 if (mTabControl == null) return;
1023
Grace Kloba1fc98a32009-10-21 13:23:08 -07001024 // Remove the fake title bar if it is there
1025 hideFakeTitleBar();
1026
The Android Open Source Project0c908882009-03-03 19:32:16 -08001027 // Remove the current tab and sub window
Grace Kloba22ac16e2009-10-07 18:00:23 -07001028 Tab t = mTabControl.getCurrentTab();
Patrick Scottfb5e77f2009-04-08 19:17:37 -07001029 if (t != null) {
1030 dismissSubWindow(t);
1031 removeTabFromContentView(t);
1032 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001033 // Destroy all the tabs
1034 mTabControl.destroy();
1035 WebIconDatabase.getInstance().close();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001036
Grace Klobab4da0ad2009-05-14 14:45:40 -07001037 unregisterReceiver(mPackageInstallationReceiver);
Bjorn Bringerta7611812010-03-24 11:12:02 +00001038
1039 // Stop watching the default geolocation permissions
1040 mSystemAllowGeolocationOrigins.stop();
1041 mSystemAllowGeolocationOrigins = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001042 }
1043
1044 @Override
1045 public void onConfigurationChanged(Configuration newConfig) {
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04001046 mConfigChanged = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001047 super.onConfigurationChanged(newConfig);
1048
1049 if (mPageInfoDialog != null) {
1050 mPageInfoDialog.dismiss();
1051 showPageInfo(
1052 mPageInfoView,
Leon Scrogginsc7b92f82010-01-11 18:17:31 -05001053 mPageInfoFromShowSSLCertificateOnError);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001054 }
1055 if (mSSLCertificateDialog != null) {
1056 mSSLCertificateDialog.dismiss();
1057 showSSLCertificate(
1058 mSSLCertificateView);
1059 }
1060 if (mSSLCertificateOnErrorDialog != null) {
1061 mSSLCertificateOnErrorDialog.dismiss();
1062 showSSLCertificateOnError(
1063 mSSLCertificateOnErrorView,
1064 mSSLCertificateOnErrorHandler,
1065 mSSLCertificateOnErrorError);
1066 }
1067 if (mHttpAuthenticationDialog != null) {
1068 String title = ((TextView) mHttpAuthenticationDialog
1069 .findViewById(com.android.internal.R.id.alertTitle)).getText()
1070 .toString();
1071 String name = ((TextView) mHttpAuthenticationDialog
1072 .findViewById(R.id.username_edit)).getText().toString();
1073 String password = ((TextView) mHttpAuthenticationDialog
1074 .findViewById(R.id.password_edit)).getText().toString();
1075 int focusId = mHttpAuthenticationDialog.getCurrentFocus()
1076 .getId();
1077 mHttpAuthenticationDialog.dismiss();
1078 showHttpAuthentication(mHttpAuthHandler, null, null, title,
1079 name, password, focusId);
1080 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001081 }
1082
Grace Kloba22ac16e2009-10-07 18:00:23 -07001083 @Override
1084 public void onLowMemory() {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001085 super.onLowMemory();
1086 mTabControl.freeMemory();
1087 }
1088
Cary Clarkff4d92c2010-03-25 11:17:03 -04001089 private void resumeWebViewTimers() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001090 Tab tab = mTabControl.getCurrentTab();
Cary Clarkff4d92c2010-03-25 11:17:03 -04001091 if (tab == null) return; // monkey can trigger this
Grace Kloba22ac16e2009-10-07 18:00:23 -07001092 boolean inLoad = tab.inLoad();
1093 if ((!mActivityInPause && !inLoad) || (mActivityInPause && inLoad)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001094 CookieSyncManager.getInstance().startSync();
Grace Kloba22ac16e2009-10-07 18:00:23 -07001095 WebView w = tab.getWebView();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001096 if (w != null) {
1097 w.resumeTimers();
1098 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001099 }
1100 }
1101
Mike Reed7bfa63b2009-05-28 11:08:32 -04001102 private boolean pauseWebViewTimers() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001103 Tab tab = mTabControl.getCurrentTab();
1104 boolean inLoad = tab.inLoad();
1105 if (mActivityInPause && !inLoad) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001106 CookieSyncManager.getInstance().stopSync();
1107 WebView w = mTabControl.getCurrentWebView();
1108 if (w != null) {
1109 w.pauseTimers();
1110 }
1111 return true;
1112 } else {
1113 return false;
1114 }
1115 }
1116
The Android Open Source Project0c908882009-03-03 19:32:16 -08001117 // Open the icon database and retain all the icons for visited sites.
1118 private void retainIconsOnStartup() {
1119 final WebIconDatabase db = WebIconDatabase.getInstance();
1120 db.open(getDir("icons", 0).getPath());
Leon Scroggins2c0f6112010-03-12 18:09:39 -05001121 Cursor c = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001122 try {
Leon Scroggins2c0f6112010-03-12 18:09:39 -05001123 c = Browser.getAllBookmarks(mResolver);
1124 if (c.moveToFirst()) {
1125 int urlIndex = c.getColumnIndex(Browser.BookmarkColumns.URL);
1126 do {
1127 String url = c.getString(urlIndex);
1128 db.retainIconForPageUrl(url);
1129 } while (c.moveToNext());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001130 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001131 } catch (IllegalStateException e) {
1132 Log.e(LOGTAG, "retainIconsOnStartup", e);
Leon Scroggins2c0f6112010-03-12 18:09:39 -05001133 } finally {
1134 if (c!= null) c.close();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001135 }
1136 }
1137
1138 // Helper method for getting the top window.
1139 WebView getTopWindow() {
1140 return mTabControl.getCurrentTopWebView();
1141 }
1142
Grace Kloba22ac16e2009-10-07 18:00:23 -07001143 TabControl getTabControl() {
1144 return mTabControl;
1145 }
1146
The Android Open Source Project0c908882009-03-03 19:32:16 -08001147 @Override
1148 public boolean onCreateOptionsMenu(Menu menu) {
1149 super.onCreateOptionsMenu(menu);
1150
1151 MenuInflater inflater = getMenuInflater();
1152 inflater.inflate(R.menu.browser, menu);
1153 mMenu = menu;
1154 updateInLoadMenuItems();
1155 return true;
1156 }
1157
1158 /**
1159 * As the menu can be open when loading state changes
1160 * we must manually update the state of the stop/reload menu
1161 * item
1162 */
1163 private void updateInLoadMenuItems() {
1164 if (mMenu == null) {
1165 return;
1166 }
Michael Kolbe0a36662010-06-29 10:37:12 -07001167 MenuItem dest = mMenu.findItem(R.id.stop_reload_menu_id);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001168 MenuItem src = mInLoad ?
1169 mMenu.findItem(R.id.stop_menu_id):
Michael Kolbe0a36662010-06-29 10:37:12 -07001170 mMenu.findItem(R.id.reload_menu_id);
1171 if (src != null) {
1172 dest.setIcon(src.getIcon());
1173 dest.setTitle(src.getTitle());
1174 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001175 }
1176
1177 @Override
1178 public boolean onContextItemSelected(MenuItem item) {
1179 // chording is not an issue with context menus, but we use the same
1180 // options selector, so set mCanChord to true so we can access them.
1181 mCanChord = true;
1182 int id = item.getItemId();
Leon Scroggins96afcb12009-12-10 12:35:56 -05001183 boolean result = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001184 switch (id) {
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001185 // For the context menu from the title bar
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001186 case R.id.title_bar_copy_page_url:
Leon Scroggins96afcb12009-12-10 12:35:56 -05001187 Tab currentTab = mTabControl.getCurrentTab();
1188 if (null == currentTab) {
1189 result = false;
1190 break;
1191 }
1192 WebView mainView = currentTab.getWebView();
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001193 if (null == mainView) {
Leon Scroggins96afcb12009-12-10 12:35:56 -05001194 result = false;
1195 break;
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001196 }
Leon Scroggins96afcb12009-12-10 12:35:56 -05001197 copy(mainView.getUrl());
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001198 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001199 // -- Browser context menu
1200 case R.id.open_context_menu_id:
The Android Open Source Project0c908882009-03-03 19:32:16 -08001201 case R.id.bookmark_context_menu_id:
1202 case R.id.save_link_context_menu_id:
1203 case R.id.share_link_context_menu_id:
1204 case R.id.copy_link_context_menu_id:
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001205 final WebView webView = getTopWindow();
1206 if (null == webView) {
Leon Scroggins96afcb12009-12-10 12:35:56 -05001207 result = false;
1208 break;
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001209 }
1210 final HashMap hrefMap = new HashMap();
1211 hrefMap.put("webview", webView);
1212 final Message msg = mHandler.obtainMessage(
1213 FOCUS_NODE_HREF, id, 0, hrefMap);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001214 webView.requestFocusNodeHref(msg);
1215 break;
1216
1217 default:
1218 // For other context menus
Leon Scroggins96afcb12009-12-10 12:35:56 -05001219 result = onOptionsItemSelected(item);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001220 }
1221 mCanChord = false;
Leon Scroggins96afcb12009-12-10 12:35:56 -05001222 return result;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001223 }
1224
1225 private Bundle createGoogleSearchSourceBundle(String source) {
1226 Bundle bundle = new Bundle();
Bjorn Bringert10d1cca2010-02-10 14:22:12 +00001227 bundle.putString(Search.SOURCE, source);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001228 return bundle;
1229 }
1230
Leon Scroggins8ad29922010-02-16 12:33:55 -05001231 /* package */ void editUrl() {
Leon Scroggins68579392009-09-15 15:31:54 -04001232 if (mOptionsMenuOpen) closeOptionsMenu();
Leon Scroggins5bbe9802009-07-31 13:10:55 -04001233 String url = (getTopWindow() == null) ? null : getTopWindow().getUrl();
Grace Kloba83f47342009-07-20 10:44:31 -07001234 startSearch(mSettings.getHomePage().equals(url) ? null : url, true,
Leon Scroggins8ad29922010-02-16 12:33:55 -05001235 null, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001236 }
1237
Leon Scroggins8ad29922010-02-16 12:33:55 -05001238 /**
1239 * Overriding this to insert a local information bundle
1240 */
The Android Open Source Project0c908882009-03-03 19:32:16 -08001241 @Override
1242 public void startSearch(String initialQuery, boolean selectInitialQuery,
1243 Bundle appSearchData, boolean globalSearch) {
1244 if (appSearchData == null) {
1245 appSearchData = createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_TYPE);
1246 }
1247 super.startSearch(initialQuery, selectInitialQuery, appSearchData, globalSearch);
1248 }
1249
Leon Scroggins1f005d32009-08-10 17:36:42 -04001250 /**
1251 * Switch tabs. Called by the TitleBarSet when sliding the title bar
1252 * results in changing tabs.
Leon Scroggins160a7e72009-08-14 18:28:01 -04001253 * @param index Index of the tab to change to, as defined by
1254 * mTabControl.getTabIndex(Tab t).
1255 * @return boolean True if we successfully switched to a different tab. If
1256 * the indexth tab is null, or if that tab is the same as
1257 * the current one, return false.
Leon Scroggins1f005d32009-08-10 17:36:42 -04001258 */
Leon Scroggins160a7e72009-08-14 18:28:01 -04001259 /* package */ boolean switchToTab(int index) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001260 Tab tab = mTabControl.getTab(index);
1261 Tab currentTab = mTabControl.getCurrentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04001262 if (tab == null || tab == currentTab) {
Leon Scroggins160a7e72009-08-14 18:28:01 -04001263 return false;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001264 }
1265 if (currentTab != null) {
1266 // currentTab may be null if it was just removed. In that case,
1267 // we do not need to remove it
1268 removeTabFromContentView(currentTab);
1269 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001270 mTabControl.setCurrentTab(tab);
1271 attachTabToContentView(tab);
Grace Klobaeb6eef42009-09-15 17:56:32 -07001272 resetTitleIconAndProgress();
1273 updateLockIconToLatest();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001274 return true;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001275 }
1276
Grace Kloba22ac16e2009-10-07 18:00:23 -07001277 /* package */ Tab openTabToHomePage() {
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001278 return openTabAndShow(mSettings.getHomePage(), false, null);
1279 }
1280
Leon Scroggins1f005d32009-08-10 17:36:42 -04001281 /* package */ void closeCurrentWindow() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001282 final Tab current = mTabControl.getCurrentTab();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001283 if (mTabControl.getTabCount() == 1) {
Leon Scroggins30444232009-09-04 18:36:20 -04001284 // This is the last tab. Open a new one, with the home
1285 // page and close the current one.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001286 openTabToHomePage();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001287 closeTab(current);
Leon Scroggins160a7e72009-08-14 18:28:01 -04001288 return;
1289 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07001290 final Tab parent = current.getParentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04001291 int indexToShow = -1;
1292 if (parent != null) {
1293 indexToShow = mTabControl.getTabIndex(parent);
1294 } else {
Leon Scroggins160a7e72009-08-14 18:28:01 -04001295 final int currentIndex = mTabControl.getCurrentIndex();
1296 // Try to move to the tab to the right
1297 indexToShow = currentIndex + 1;
1298 if (indexToShow > mTabControl.getTabCount() - 1) {
1299 // Try to move to the tab to the left
1300 indexToShow = currentIndex - 1;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001301 }
1302 }
Leon Scroggins160a7e72009-08-14 18:28:01 -04001303 if (switchToTab(indexToShow)) {
1304 // Close window
1305 closeTab(current);
1306 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001307 }
1308
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001309 private ActiveTabsPage mActiveTabsPage;
1310
1311 /**
1312 * Remove the active tabs page.
1313 * @param needToAttach If true, the active tabs page did not attach a tab
1314 * to the content view, so we need to do that here.
1315 */
1316 /* package */ void removeActiveTabPage(boolean needToAttach) {
1317 mContentView.removeView(mActiveTabsPage);
Leon Scrogginsd746a942010-05-19 13:21:44 -04001318 mTitleBar.setVisibility(View.VISIBLE);
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001319 mActiveTabsPage = null;
1320 mMenuState = R.id.MAIN_MENU;
1321 if (needToAttach) {
1322 attachTabToContentView(mTabControl.getCurrentTab());
1323 }
1324 getTopWindow().requestFocus();
1325 }
1326
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04001327 @Override
1328 public ActionMode onStartActionMode(ActionMode.Callback callback) {
1329 ActionMode mode = super.onStartActionMode(callback);
1330 if (callback instanceof FindActionModeCallback
1331 || callback instanceof SelectActionModeCallback) {
1332 // For find and select, hide extra title bars. They will
1333 // be replaced in onEndActionMode.
1334 Tab tab = mTabControl.getCurrentTab();
1335 if (tab.getSubWebView() == null) {
1336 // If the find or select is being performed on the main webview,
1337 // remove the embedded title bar.
1338 WebView mainView = tab.getWebView();
1339 if (mainView != null) {
1340 mainView.setEmbeddedTitleBar(null);
1341 }
Cary Clark01cfcdd2010-06-04 16:36:45 -04001342 }
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04001343 hideFakeTitleBar();
1344 mActionMode = mode;
1345 } else {
1346 // Do not store other ActionModes, since we are unable to determine
1347 // when they finish.
1348 mActionMode = null;
Cary Clark01cfcdd2010-06-04 16:36:45 -04001349 }
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04001350 return mode;
Cary Clark01cfcdd2010-06-04 16:36:45 -04001351 }
1352
The Android Open Source Project0c908882009-03-03 19:32:16 -08001353 @Override
1354 public boolean onOptionsItemSelected(MenuItem item) {
Michael Kolbed217742010-08-10 17:52:34 -07001355 // check the action bar button before mCanChord check, as the prepare call
1356 // doesn't come for action bar buttons
1357 if (item.getItemId() == R.id.newtab) {
1358 bookmarksOrHistoryPicker(false, true);
1359 return true;
1360 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001361 if (!mCanChord) {
1362 // The user has already fired a shortcut with this hold down of the
1363 // menu key.
1364 return false;
1365 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001366 if (null == getTopWindow()) {
Leon Scroggins0d7ae0e2009-06-05 11:04:45 -04001367 return false;
1368 }
Grace Kloba6ee9c492009-07-13 10:04:34 -07001369 if (mMenuIsDown) {
1370 // The shortcut action consumes the MENU. Even if it is still down,
1371 // it won't trigger the next shortcut action. In the case of the
1372 // shortcut action triggering a new activity, like Bookmarks, we
1373 // won't get onKeyUp for MENU. So it is important to reset it here.
1374 mMenuIsDown = false;
1375 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001376 switch (item.getItemId()) {
1377 // -- Main menu
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001378 case R.id.new_tab_menu_id:
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001379 openTabToHomePage();
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001380 break;
1381
Leon Scroggins64b80f32009-08-07 12:03:34 -04001382 case R.id.goto_menu_id:
Leon Scroggins8ad29922010-02-16 12:33:55 -05001383 editUrl();
Leon Scrogginsb3a5bed2009-09-28 11:21:56 -04001384 break;
1385
1386 case R.id.bookmarks_menu_id:
Michael Kolb68792c82010-08-09 16:39:18 -07001387 bookmarksOrHistoryPicker(false, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001388 break;
1389
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001390 case R.id.active_tabs_menu_id:
1391 mActiveTabsPage = new ActiveTabsPage(this, mTabControl);
1392 removeTabFromContentView(mTabControl.getCurrentTab());
Leon Scrogginsd746a942010-05-19 13:21:44 -04001393 mTitleBar.setVisibility(View.GONE);
Leon Scroggins43de6162009-09-14 19:59:58 -04001394 hideFakeTitleBar();
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001395 mContentView.addView(mActiveTabsPage, COVER_SCREEN_PARAMS);
1396 mActiveTabsPage.requestFocus();
1397 mMenuState = EMPTY_MENU;
1398 break;
1399
Leon Scroggins1f005d32009-08-10 17:36:42 -04001400 case R.id.add_bookmark_menu_id:
Leon Scroggins571b3762010-05-26 10:25:01 -04001401 bookmarkCurrentPage();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001402 break;
1403
1404 case R.id.stop_reload_menu_id:
1405 if (mInLoad) {
1406 stopLoading();
1407 } else {
1408 getTopWindow().reload();
1409 }
1410 break;
1411
1412 case R.id.back_menu_id:
1413 getTopWindow().goBack();
1414 break;
1415
1416 case R.id.forward_menu_id:
1417 getTopWindow().goForward();
1418 break;
1419
1420 case R.id.close_menu_id:
1421 // Close the subwindow if it exists.
1422 if (mTabControl.getCurrentSubWindow() != null) {
1423 dismissSubWindow(mTabControl.getCurrentTab());
1424 break;
1425 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001426 closeCurrentWindow();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001427 break;
1428
1429 case R.id.homepage_menu_id:
Grace Kloba22ac16e2009-10-07 18:00:23 -07001430 Tab current = mTabControl.getCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001431 if (current != null) {
1432 dismissSubWindow(current);
Leon Scroggins92472e82010-02-17 16:32:28 -05001433 loadUrl(current.getWebView(), mSettings.getHomePage());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001434 }
1435 break;
1436
1437 case R.id.preferences_menu_id:
1438 Intent intent = new Intent(this,
1439 BrowserPreferencesPage.class);
Leon Scrogginsd5304942009-12-10 16:11:39 -05001440 intent.putExtra(BrowserPreferencesPage.CURRENT_PAGE,
1441 getTopWindow().getUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001442 startActivityForResult(intent, PREFERENCES_PAGE);
1443 break;
1444
1445 case R.id.find_menu_id:
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04001446 showFindDialog(null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001447 break;
1448
Elliott Slaughter0ced08c2010-06-30 11:40:42 -07001449 case R.id.save_webarchive_menu_id:
1450 if (LOGD_ENABLED) {
1451 Log.d(LOGTAG, "Save as Web Archive");
1452 }
1453 String directory = getExternalFilesDir(null).getAbsolutePath() + File.separator;
1454 getTopWindow().saveWebArchive(directory, true, new ValueCallback<String>() {
1455 @Override
1456 public void onReceiveValue(String value) {
1457 if (value != null) {
1458 Toast.makeText(BrowserActivity.this, R.string.webarchive_saved, Toast.LENGTH_SHORT).show();
1459 } else {
1460 Toast.makeText(BrowserActivity.this, R.string.webarchive_failed, Toast.LENGTH_SHORT).show();
1461 }
1462 }
1463 });
1464 break;
1465
The Android Open Source Project0c908882009-03-03 19:32:16 -08001466 case R.id.page_info_menu_id:
1467 showPageInfo(mTabControl.getCurrentTab(), false);
1468 break;
1469
1470 case R.id.classic_history_menu_id:
Michael Kolb68792c82010-08-09 16:39:18 -07001471 bookmarksOrHistoryPicker(true, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001472 break;
1473
Leon Scroggins96afcb12009-12-10 12:35:56 -05001474 case R.id.title_bar_share_page_url:
The Android Open Source Project0c908882009-03-03 19:32:16 -08001475 case R.id.share_page_menu_id:
Leon Scroggins96afcb12009-12-10 12:35:56 -05001476 Tab currentTab = mTabControl.getCurrentTab();
1477 if (null == currentTab) {
1478 mCanChord = false;
1479 return false;
1480 }
1481 currentTab.populatePickerData();
1482 sharePage(this, currentTab.getTitle(),
1483 currentTab.getUrl(), currentTab.getFavicon(),
Ben Murdoch87cc65d2010-06-29 20:34:10 +01001484 createScreenshot(currentTab.getWebView(), getDesiredThumbnailWidth(this),
1485 getDesiredThumbnailHeight(this)));
The Android Open Source Project0c908882009-03-03 19:32:16 -08001486 break;
1487
1488 case R.id.dump_nav_menu_id:
1489 getTopWindow().debugDump();
1490 break;
1491
Andrei Popescu7a8b88b2010-02-02 00:30:38 +00001492 case R.id.dump_counters_menu_id:
1493 getTopWindow().dumpV8Counters();
1494 break;
1495
The Android Open Source Project0c908882009-03-03 19:32:16 -08001496 case R.id.zoom_in_menu_id:
1497 getTopWindow().zoomIn();
1498 break;
1499
1500 case R.id.zoom_out_menu_id:
1501 getTopWindow().zoomOut();
1502 break;
1503
1504 case R.id.view_downloads_menu_id:
1505 viewDownloads(null);
1506 break;
1507
The Android Open Source Project0c908882009-03-03 19:32:16 -08001508 case R.id.window_one_menu_id:
1509 case R.id.window_two_menu_id:
1510 case R.id.window_three_menu_id:
1511 case R.id.window_four_menu_id:
1512 case R.id.window_five_menu_id:
1513 case R.id.window_six_menu_id:
1514 case R.id.window_seven_menu_id:
1515 case R.id.window_eight_menu_id:
1516 {
1517 int menuid = item.getItemId();
1518 for (int id = 0; id < WINDOW_SHORTCUT_ID_ARRAY.length; id++) {
1519 if (WINDOW_SHORTCUT_ID_ARRAY[id] == menuid) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001520 Tab desiredTab = mTabControl.getTab(id);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001521 if (desiredTab != null &&
1522 desiredTab != mTabControl.getCurrentTab()) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001523 switchToTab(id);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001524 }
1525 break;
1526 }
1527 }
1528 }
1529 break;
1530
1531 default:
1532 if (!super.onOptionsItemSelected(item)) {
1533 return false;
1534 }
1535 // Otherwise fall through.
1536 }
1537 mCanChord = false;
1538 return true;
1539 }
1540
Leon Scroggins571b3762010-05-26 10:25:01 -04001541 /* package */ void bookmarkCurrentPage() {
1542 Intent i = new Intent(BrowserActivity.this,
1543 AddBookmarkPage.class);
1544 WebView w = getTopWindow();
1545 i.putExtra("url", w.getUrl());
1546 i.putExtra("title", w.getTitle());
1547 i.putExtra("touch_icon_url", w.getTouchIconUrl());
Ben Murdoch87cc65d2010-06-29 20:34:10 +01001548 i.putExtra("thumbnail", createScreenshot(w, getDesiredThumbnailWidth(this),
1549 getDesiredThumbnailHeight(this)));
Ben Murdocheecb4e62010-07-06 16:30:38 +01001550 i.putExtra("url_editable", false);
Leon Scroggins571b3762010-05-26 10:25:01 -04001551 startActivity(i);
1552 }
1553
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04001554 /*
1555 * True if a custom ActionMode (i.e. find or select) is in use.
1556 */
1557 private boolean isInCustomActionMode() {
1558 return mActionMode != null;
Cary Clark01cfcdd2010-06-04 16:36:45 -04001559 }
1560
1561 /*
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04001562 * End the current ActionMode. Only works for find and select.
Cary Clark01cfcdd2010-06-04 16:36:45 -04001563 */
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04001564 void endActionMode() {
1565 if (mActionMode != null) {
1566 mActionMode.finish();
1567 }
1568 }
1569
1570 /*
1571 * Called by find and select when they are finished. Replace title bars
1572 * as necessary.
1573 */
1574 public void onEndActionMode() {
1575 if (!isInCustomActionMode()) return;
Michael Kolba2b2ba82010-08-04 17:54:03 -07001576 // If the Find was being performed in the main WebView, replace the
1577 // embedded title bar.
1578 Tab currentTab = mTabControl.getCurrentTab();
1579 if (currentTab.getSubWebView() == null) {
1580 WebView mainView = currentTab.getWebView();
1581 if (mainView != null) {
1582 mainView.setEmbeddedTitleBar(mTitleBar);
Leon Scroggins79e36d92010-04-29 16:01:46 +01001583 }
1584 }
Leon Scroggins79e36d92010-04-29 16:01:46 +01001585 if (mInLoad) {
1586 // The title bar was hidden, because otherwise it would cover up the
Michael Kolba2b2ba82010-08-04 17:54:03 -07001587 // find or select dialog. Now that the dialog has been removed,
Cary Clark01cfcdd2010-06-04 16:36:45 -04001588 // show the fake title bar once again.
Leon Scroggins79e36d92010-04-29 16:01:46 +01001589 showFakeTitleBar();
1590 }
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04001591 mActionMode = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001592 }
1593
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04001594 private FindActionModeCallback mFindCallback;
1595 private SelectActionModeCallback mSelectCallback;
1596
1597 // For select and find, we keep track of the ActionMode so that
1598 // finish() can be called as desired.
1599 private ActionMode mActionMode;
1600
1601 /*
1602 * Open the find ActionMode.
1603 * @param text If non null, will be placed in find to be searched for.
1604 */
1605 public void showFindDialog(String text) {
1606 if (null == mFindCallback) {
1607 mFindCallback = new FindActionModeCallback(this);
Cary Clark01cfcdd2010-06-04 16:36:45 -04001608 }
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04001609 WebView webView = getTopWindow();
1610 webView.setFindIsUp(true);
1611 mFindCallback.setWebView(webView);
1612 startActionMode(mFindCallback);
1613 if (text != null) mFindCallback.setText(text);
Cary Clark01cfcdd2010-06-04 16:36:45 -04001614 }
1615
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04001616 /*
1617 * Show the select ActionMode.
1618 */
Cary Clark01cfcdd2010-06-04 16:36:45 -04001619 public void showSelectDialog() {
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04001620 if (null == mSelectCallback) {
1621 mSelectCallback = new SelectActionModeCallback(this);
Cary Clark01cfcdd2010-06-04 16:36:45 -04001622 }
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04001623 WebView webView = getTopWindow();
1624 webView.setUpSelect();
1625 mSelectCallback.setWebView(webView);
1626 startActionMode(mSelectCallback);
Cary Clark01cfcdd2010-06-04 16:36:45 -04001627 }
1628
Grace Kloba22ac16e2009-10-07 18:00:23 -07001629 @Override
1630 public boolean onPrepareOptionsMenu(Menu menu) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001631 // This happens when the user begins to hold down the menu key, so
1632 // allow them to chord to get a shortcut.
1633 mCanChord = true;
1634 // Note: setVisible will decide whether an item is visible; while
1635 // setEnabled() will decide whether an item is enabled, which also means
1636 // whether the matching shortcut key will function.
1637 super.onPrepareOptionsMenu(menu);
1638 switch (mMenuState) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001639 case EMPTY_MENU:
1640 if (mCurrentMenuState != mMenuState) {
1641 menu.setGroupVisible(R.id.MAIN_MENU, false);
1642 menu.setGroupEnabled(R.id.MAIN_MENU, false);
1643 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001644 }
1645 break;
1646 default:
1647 if (mCurrentMenuState != mMenuState) {
1648 menu.setGroupVisible(R.id.MAIN_MENU, true);
1649 menu.setGroupEnabled(R.id.MAIN_MENU, true);
1650 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001651 }
1652 final WebView w = getTopWindow();
1653 boolean canGoBack = false;
1654 boolean canGoForward = false;
1655 boolean isHome = false;
1656 if (w != null) {
1657 canGoBack = w.canGoBack();
1658 canGoForward = w.canGoForward();
1659 isHome = mSettings.getHomePage().equals(w.getUrl());
1660 }
1661 final MenuItem back = menu.findItem(R.id.back_menu_id);
1662 back.setEnabled(canGoBack);
1663
1664 final MenuItem home = menu.findItem(R.id.homepage_menu_id);
1665 home.setEnabled(!isHome);
1666
Michael Kolbe0a36662010-06-29 10:37:12 -07001667 final MenuItem forward = menu.findItem(R.id.forward_menu_id);
1668 forward.setEnabled(canGoForward);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001669
Michael Kolbed217742010-08-10 17:52:34 -07001670 if (!mXLargeScreenSize) {
1671 final MenuItem newtab = menu.findItem(R.id.new_tab_menu_id);
1672 newtab.setEnabled(mTabControl.canCreateNewTab());
1673 }
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001674
The Android Open Source Project0c908882009-03-03 19:32:16 -08001675 // decide whether to show the share link option
1676 PackageManager pm = getPackageManager();
1677 Intent send = new Intent(Intent.ACTION_SEND);
1678 send.setType("text/plain");
1679 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1680 menu.findItem(R.id.share_page_menu_id).setVisible(ri != null);
1681
The Android Open Source Project0c908882009-03-03 19:32:16 -08001682 boolean isNavDump = mSettings.isNavDump();
1683 final MenuItem nav = menu.findItem(R.id.dump_nav_menu_id);
1684 nav.setVisible(isNavDump);
1685 nav.setEnabled(isNavDump);
Andrei Popescu7a8b88b2010-02-02 00:30:38 +00001686
1687 boolean showDebugSettings = mSettings.showDebugSettings();
1688 final MenuItem counter = menu.findItem(R.id.dump_counters_menu_id);
1689 counter.setVisible(showDebugSettings);
1690 counter.setEnabled(showDebugSettings);
1691
The Android Open Source Project0c908882009-03-03 19:32:16 -08001692 break;
1693 }
1694 mCurrentMenuState = mMenuState;
1695 return true;
1696 }
1697
1698 @Override
1699 public void onCreateContextMenu(ContextMenu menu, View v,
1700 ContextMenuInfo menuInfo) {
Leon Scroggins571b3762010-05-26 10:25:01 -04001701 if (v instanceof TitleBarBase) {
Leon Scroggins4e9f89b2010-02-22 16:54:14 -05001702 return;
1703 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001704 WebView webview = (WebView) v;
1705 WebView.HitTestResult result = webview.getHitTestResult();
1706 if (result == null) {
1707 return;
1708 }
1709
1710 int type = result.getType();
1711 if (type == WebView.HitTestResult.UNKNOWN_TYPE) {
1712 Log.w(LOGTAG,
1713 "We should not show context menu when nothing is touched");
1714 return;
1715 }
1716 if (type == WebView.HitTestResult.EDIT_TEXT_TYPE) {
1717 // let TextView handles context menu
1718 return;
1719 }
1720
1721 // Note, http://b/issue?id=1106666 is requesting that
1722 // an inflated menu can be used again. This is not available
1723 // yet, so inflate each time (yuk!)
1724 MenuInflater inflater = getMenuInflater();
1725 inflater.inflate(R.menu.browsercontext, menu);
1726
1727 // Show the correct menu group
Leon Scroggins III9e997c72010-05-26 13:25:16 -04001728 final String extra = result.getExtra();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001729 menu.setGroupVisible(R.id.PHONE_MENU,
1730 type == WebView.HitTestResult.PHONE_TYPE);
1731 menu.setGroupVisible(R.id.EMAIL_MENU,
1732 type == WebView.HitTestResult.EMAIL_TYPE);
1733 menu.setGroupVisible(R.id.GEO_MENU,
1734 type == WebView.HitTestResult.GEO_TYPE);
1735 menu.setGroupVisible(R.id.IMAGE_MENU,
1736 type == WebView.HitTestResult.IMAGE_TYPE
1737 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1738 menu.setGroupVisible(R.id.ANCHOR_MENU,
1739 type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1740 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1741
1742 // Setup custom handling depending on the type
1743 switch (type) {
1744 case WebView.HitTestResult.PHONE_TYPE:
1745 menu.setHeaderTitle(Uri.decode(extra));
1746 menu.findItem(R.id.dial_context_menu_id).setIntent(
1747 new Intent(Intent.ACTION_VIEW, Uri
1748 .parse(WebView.SCHEME_TEL + extra)));
1749 Intent addIntent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
1750 addIntent.putExtra(Insert.PHONE, Uri.decode(extra));
Cary Clark5e335a32009-09-22 14:53:11 -04001751 addIntent.setType(ContactsContract.Contacts.CONTENT_ITEM_TYPE);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001752 menu.findItem(R.id.add_contact_context_menu_id).setIntent(
1753 addIntent);
1754 menu.findItem(R.id.copy_phone_context_menu_id).setOnMenuItemClickListener(
1755 new Copy(extra));
1756 break;
1757
1758 case WebView.HitTestResult.EMAIL_TYPE:
1759 menu.setHeaderTitle(extra);
1760 menu.findItem(R.id.email_context_menu_id).setIntent(
1761 new Intent(Intent.ACTION_VIEW, Uri
1762 .parse(WebView.SCHEME_MAILTO + extra)));
1763 menu.findItem(R.id.copy_mail_context_menu_id).setOnMenuItemClickListener(
1764 new Copy(extra));
1765 break;
1766
1767 case WebView.HitTestResult.GEO_TYPE:
1768 menu.setHeaderTitle(extra);
1769 menu.findItem(R.id.map_context_menu_id).setIntent(
1770 new Intent(Intent.ACTION_VIEW, Uri
1771 .parse(WebView.SCHEME_GEO
1772 + URLEncoder.encode(extra))));
1773 menu.findItem(R.id.copy_geo_context_menu_id).setOnMenuItemClickListener(
1774 new Copy(extra));
1775 break;
1776
1777 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1778 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
1779 TextView titleView = (TextView) LayoutInflater.from(this)
1780 .inflate(android.R.layout.browser_link_context_header,
1781 null);
1782 titleView.setText(extra);
1783 menu.setHeaderView(titleView);
1784 // decide whether to show the open link in new tab option
Leon Scroggins III9e997c72010-05-26 13:25:16 -04001785 boolean showNewTab = mTabControl.canCreateNewTab();
1786 MenuItem newTabItem
1787 = menu.findItem(R.id.open_newtab_context_menu_id);
1788 newTabItem.setVisible(showNewTab);
1789 if (showNewTab) {
1790 newTabItem.setOnMenuItemClickListener(
1791 new MenuItem.OnMenuItemClickListener() {
1792 public boolean onMenuItemClick(MenuItem item) {
1793 final Tab parent = mTabControl.getCurrentTab();
Michael Kolb68792c82010-08-09 16:39:18 -07001794 final Tab newTab = openTab(extra, false);
Leon Scroggins III9e997c72010-05-26 13:25:16 -04001795 if (newTab != parent) {
1796 parent.addChildTab(newTab);
1797 }
1798 return true;
1799 }
1800 });
1801 }
Ben Murdochde353622009-10-12 10:29:00 +01001802 menu.findItem(R.id.bookmark_context_menu_id).setVisible(
1803 Bookmarks.urlHasAcceptableScheme(extra));
The Android Open Source Project0c908882009-03-03 19:32:16 -08001804 PackageManager pm = getPackageManager();
1805 Intent send = new Intent(Intent.ACTION_SEND);
1806 send.setType("text/plain");
1807 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1808 menu.findItem(R.id.share_link_context_menu_id).setVisible(ri != null);
1809 if (type == WebView.HitTestResult.SRC_ANCHOR_TYPE) {
1810 break;
1811 }
1812 // otherwise fall through to handle image part
1813 case WebView.HitTestResult.IMAGE_TYPE:
1814 if (type == WebView.HitTestResult.IMAGE_TYPE) {
1815 menu.setHeaderTitle(extra);
1816 }
1817 menu.findItem(R.id.view_image_context_menu_id).setIntent(
1818 new Intent(Intent.ACTION_VIEW, Uri.parse(extra)));
1819 menu.findItem(R.id.download_context_menu_id).
1820 setOnMenuItemClickListener(new Download(extra));
Ben Murdoch4f75ba22009-10-27 11:48:28 +00001821 menu.findItem(R.id.set_wallpaper_context_menu_id).
1822 setOnMenuItemClickListener(new SetAsWallpaper(extra));
The Android Open Source Project0c908882009-03-03 19:32:16 -08001823 break;
1824
1825 default:
1826 Log.w(LOGTAG, "We should not get here.");
1827 break;
1828 }
Leon Scrogginsb2b19f52009-10-09 16:10:00 -04001829 hideFakeTitleBar();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001830 }
1831
The Android Open Source Project0c908882009-03-03 19:32:16 -08001832 // Attach the given tab to the content view.
Grace Klobac928c302009-09-17 11:51:21 -07001833 // this should only be called for the current tab.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001834 private void attachTabToContentView(Tab t) {
Steve Block2bc69912009-07-30 14:45:13 +01001835 // Attach the container that contains the main WebView and any other UI
1836 // associated with the tab.
Patrick Scottd0119532009-09-17 08:00:31 -04001837 t.attachTabToContentView(mContentView);
Ben Murdochbff2d602009-07-01 20:19:05 +01001838
1839 if (mShouldShowErrorConsole) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001840 ErrorConsoleView errorConsole = t.getErrorConsole(true);
Ben Murdochbff2d602009-07-01 20:19:05 +01001841 if (errorConsole.numberOfErrors() == 0) {
1842 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
1843 } else {
1844 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
1845 }
1846
1847 mErrorConsoleContainer.addView(errorConsole,
Romain Guy15b8ec62010-01-08 15:06:43 -08001848 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
Ben Murdochbff2d602009-07-01 20:19:05 +01001849 ViewGroup.LayoutParams.WRAP_CONTENT));
1850 }
1851
Michael Kolba2b2ba82010-08-04 17:54:03 -07001852 WebView view = t.getWebView();
1853 view.setEmbeddedTitleBar(mTitleBar);
Leon Scroggins58d56c62010-01-28 15:12:40 -05001854 if (t.isInVoiceSearchMode()) {
1855 showVoiceTitleBar(t.getVoiceDisplayTitle());
1856 } else {
1857 revertVoiceTitleBar();
1858 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001859 // Request focus on the top window.
1860 t.getTopWindow().requestFocus();
Michael Kolba2b2ba82010-08-04 17:54:03 -07001861 if (mTabControl.getTabChangeListener() != null) {
1862 mTabControl.getTabChangeListener().onCurrentTab(t);
1863 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001864 }
1865
1866 // Attach a sub window to the main WebView of the given tab.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001867 void attachSubWindow(Tab t) {
Patrick Scottd0119532009-09-17 08:00:31 -04001868 t.attachSubWindow(mContentView);
1869 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001870 }
1871
1872 // Remove the given tab from the content view.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001873 private void removeTabFromContentView(Tab t) {
Steve Block2bc69912009-07-30 14:45:13 +01001874 // Remove the container that contains the main WebView.
Patrick Scottd0119532009-09-17 08:00:31 -04001875 t.removeTabFromContentView(mContentView);
Ben Murdochbff2d602009-07-01 20:19:05 +01001876
Grace Kloba22ac16e2009-10-07 18:00:23 -07001877 ErrorConsoleView errorConsole = t.getErrorConsole(false);
1878 if (errorConsole != null) {
1879 mErrorConsoleContainer.removeView(errorConsole);
Ben Murdochbff2d602009-07-01 20:19:05 +01001880 }
1881
Michael Kolba2b2ba82010-08-04 17:54:03 -07001882 WebView view = t.getWebView();
1883 if (view != null) {
1884 view.setEmbeddedTitleBar(null);
Leon Scrogginsbb85b902009-09-14 19:27:20 -04001885 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001886 }
1887
1888 // Remove the sub window if it exists. Also called by TabControl when the
1889 // user clicks the 'X' to dismiss a sub window.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001890 /* package */ void dismissSubWindow(Tab t) {
Patrick Scottd0119532009-09-17 08:00:31 -04001891 t.removeSubWindow(mContentView);
Grace Kloba22ac16e2009-10-07 18:00:23 -07001892 // dismiss the subwindow. This will destroy the WebView.
1893 t.dismissSubWindow();
Patrick Scottd0119532009-09-17 08:00:31 -04001894 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001895 }
1896
Leon Scroggins1f005d32009-08-10 17:36:42 -04001897 // A wrapper function of {@link #openTabAndShow(UrlData, boolean, String)}
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07001898 // that accepts url as string.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001899 private Tab openTabAndShow(String url, boolean closeOnExit, String appId) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001900 return openTabAndShow(new UrlData(url), closeOnExit, appId);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001901 }
1902
1903 // This method does a ton of stuff. It will attempt to create a new tab
1904 // if we haven't reached MAX_TABS. Otherwise it uses the current tab. If
Leon Scroggins1f005d32009-08-10 17:36:42 -04001905 // url isn't null, it will load the given url.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001906 /* package */Tab openTabAndShow(UrlData urlData, boolean closeOnExit,
1907 String appId) {
1908 final Tab currentTab = mTabControl.getCurrentTab();
1909 if (mTabControl.canCreateNewTab()) {
1910 final Tab tab = mTabControl.createNewTab(closeOnExit, appId,
Elliott Slaughterf0f03952010-07-14 18:10:36 -07001911 urlData.mUrl, false);
Leon Scroggins1f005d32009-08-10 17:36:42 -04001912 WebView webview = tab.getWebView();
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001913 // If the last tab was removed from the active tabs page, currentTab
1914 // will be null.
1915 if (currentTab != null) {
1916 removeTabFromContentView(currentTab);
1917 }
Patrick Scott8bbd69f2009-08-14 13:35:53 -04001918 // We must set the new tab as the current tab to reflect the old
1919 // animation behavior.
1920 mTabControl.setCurrentTab(tab);
Grace Klobaeb6eef42009-09-15 17:56:32 -07001921 attachTabToContentView(tab);
Leon Scroggins160a7e72009-08-14 18:28:01 -04001922 if (!urlData.isEmpty()) {
Patrick Scott9d53da02010-02-19 10:19:01 -05001923 loadUrlDataIn(tab, urlData);
Leon Scroggins1f005d32009-08-10 17:36:42 -04001924 }
1925 return tab;
1926 } else {
1927 // Get rid of the subwindow if it exists
1928 dismissSubWindow(currentTab);
1929 if (!urlData.isEmpty()) {
1930 // Load the given url.
Patrick Scott9d53da02010-02-19 10:19:01 -05001931 loadUrlDataIn(currentTab, urlData);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001932 }
Leon Scroggins58d56c62010-01-28 15:12:40 -05001933 return currentTab;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001934 }
1935 }
1936
Michael Kolb68792c82010-08-09 16:39:18 -07001937 private Tab openTab(String url, boolean forceForeground) {
1938 if (mSettings.openInBackground() && !forceForeground) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001939 Tab t = mTabControl.createNewTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001940 if (t != null) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001941 WebView view = t.getWebView();
Leon Scroggins92472e82010-02-17 16:32:28 -05001942 loadUrl(view, url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001943 }
Grace Klobac9181842009-04-14 08:53:22 -07001944 return t;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001945 } else {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001946 return openTabAndShow(url, false, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001947 }
1948 }
1949
Elliott Slaughterf0f03952010-07-14 18:10:36 -07001950 /* package */ Tab openIncognitoTab() {
1951 if (mTabControl.canCreateNewTab()) {
1952 Tab currentTab = mTabControl.getCurrentTab();
1953 Tab tab = mTabControl.createNewTab(false, null, null, true);
1954 if (currentTab != null) {
1955 removeTabFromContentView(currentTab);
1956 }
1957 mTabControl.setCurrentTab(tab);
1958 attachTabToContentView(tab);
1959 return tab;
1960 }
1961 return null;
1962 }
1963
The Android Open Source Project0c908882009-03-03 19:32:16 -08001964 private class Copy implements OnMenuItemClickListener {
1965 private CharSequence mText;
1966
1967 public boolean onMenuItemClick(MenuItem item) {
1968 copy(mText);
1969 return true;
1970 }
1971
1972 public Copy(CharSequence toCopy) {
1973 mText = toCopy;
1974 }
1975 }
1976
1977 private class Download implements OnMenuItemClickListener {
1978 private String mText;
1979
1980 public boolean onMenuItemClick(MenuItem item) {
1981 onDownloadStartNoStream(mText, null, null, null, -1);
1982 return true;
1983 }
1984
1985 public Download(String toDownload) {
1986 mText = toDownload;
1987 }
1988 }
1989
Ben Murdoch4f75ba22009-10-27 11:48:28 +00001990 private class SetAsWallpaper extends Thread implements
1991 OnMenuItemClickListener, DialogInterface.OnCancelListener {
1992 private URL mUrl;
1993 private ProgressDialog mWallpaperProgress;
1994 private boolean mCanceled = false;
1995
1996 public SetAsWallpaper(String url) {
1997 try {
1998 mUrl = new URL(url);
1999 } catch (MalformedURLException e) {
2000 mUrl = null;
2001 }
2002 }
2003
2004 public void onCancel(DialogInterface dialog) {
2005 mCanceled = true;
2006 }
2007
2008 public boolean onMenuItemClick(MenuItem item) {
2009 if (mUrl != null) {
2010 // The user may have tried to set a image with a large file size as their
2011 // background so it may take a few moments to perform the operation. Display
2012 // a progress spinner while it is working.
2013 mWallpaperProgress = new ProgressDialog(BrowserActivity.this);
2014 mWallpaperProgress.setIndeterminate(true);
2015 mWallpaperProgress.setMessage(getText(R.string.progress_dialog_setting_wallpaper));
2016 mWallpaperProgress.setCancelable(true);
2017 mWallpaperProgress.setOnCancelListener(this);
2018 mWallpaperProgress.show();
2019 start();
2020 }
2021 return true;
2022 }
2023
Michael Kolbe0a36662010-06-29 10:37:12 -07002024 @Override
Ben Murdoch4f75ba22009-10-27 11:48:28 +00002025 public void run() {
2026 Drawable oldWallpaper = BrowserActivity.this.getWallpaper();
2027 try {
2028 // TODO: This will cause the resource to be downloaded again, when we
2029 // should in most cases be able to grab it from the cache. To fix this
2030 // we should query WebCore to see if we can access a cached version and
2031 // instead open an input stream on that. This pattern could also be used
2032 // in the download manager where the same problem exists.
2033 InputStream inputstream = mUrl.openStream();
2034 if (inputstream != null) {
2035 setWallpaper(inputstream);
2036 }
2037 } catch (IOException e) {
2038 Log.e(LOGTAG, "Unable to set new wallpaper");
2039 // Act as though the user canceled the operation so we try to
2040 // restore the old wallpaper.
2041 mCanceled = true;
2042 }
2043
2044 if (mCanceled) {
2045 // Restore the old wallpaper if the user cancelled whilst we were setting
2046 // the new wallpaper.
2047 int width = oldWallpaper.getIntrinsicWidth();
2048 int height = oldWallpaper.getIntrinsicHeight();
2049 Bitmap bm = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
2050 Canvas canvas = new Canvas(bm);
2051 oldWallpaper.setBounds(0, 0, width, height);
2052 oldWallpaper.draw(canvas);
2053 try {
2054 setWallpaper(bm);
2055 } catch (IOException e) {
2056 Log.e(LOGTAG, "Unable to restore old wallpaper.");
2057 }
2058 mCanceled = false;
2059 }
2060
2061 if (mWallpaperProgress.isShowing()) {
2062 mWallpaperProgress.dismiss();
2063 }
2064 }
2065 }
2066
The Android Open Source Project0c908882009-03-03 19:32:16 -08002067 private void copy(CharSequence text) {
Dianne Hackborn80f32622010-08-05 14:17:53 -07002068 ClipboardManager cm = (ClipboardManager)getSystemService(Context.CLIPBOARD_SERVICE);
2069 cm.setText(text);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002070 }
2071
2072 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08002073 * Resets the browser title-view to whatever it must be
2074 * (for example, if we had a loading error)
2075 * When we have a new page, we call resetTitle, when we
2076 * have to reset the titlebar to whatever it used to be
2077 * (for example, if the user chose to stop loading), we
2078 * call resetTitleAndRevertLockIcon.
2079 */
2080 /* package */ void resetTitleAndRevertLockIcon() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002081 mTabControl.getCurrentTab().revertLockIcon();
2082 updateLockIconToLatest();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002083 resetTitleIconAndProgress();
2084 }
2085
2086 /**
2087 * Reset the title, favicon, and progress.
2088 */
2089 private void resetTitleIconAndProgress() {
2090 WebView current = mTabControl.getCurrentWebView();
2091 if (current == null) {
2092 return;
2093 }
2094 resetTitleAndIcon(current);
2095 int progress = current.getProgress();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002096 current.getWebChromeClient().onProgressChanged(current, progress);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002097 }
2098
2099 // Reset the title and the icon based on the given item.
2100 private void resetTitleAndIcon(WebView view) {
2101 WebHistoryItem item = view.copyBackForwardList().getCurrentItem();
2102 if (item != null) {
Leon Scroggins68579392009-09-15 15:31:54 -04002103 setUrlTitle(item.getUrl(), item.getTitle());
The Android Open Source Project0c908882009-03-03 19:32:16 -08002104 setFavicon(item.getFavicon());
2105 } else {
Leon Scroggins68579392009-09-15 15:31:54 -04002106 setUrlTitle(null, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002107 setFavicon(null);
2108 }
2109 }
2110
2111 /**
2112 * Sets a title composed of the URL and the title string.
2113 * @param url The URL of the site being loaded.
2114 * @param title The title of the site being loaded.
2115 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07002116 void setUrlTitle(String url, String title) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002117 mUrl = url;
2118 mTitle = title;
2119
Leon Scroggins58d56c62010-01-28 15:12:40 -05002120 // If we are in voice search mode, the title has already been set.
2121 if (mTabControl.getCurrentTab().isInVoiceSearchMode()) return;
2122 mTitleBar.setDisplayTitle(url);
Michael Kolba2b2ba82010-08-04 17:54:03 -07002123 mFakeTitleBar.setDisplayTitle(url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002124 }
2125
2126 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08002127 * @param url The URL to build a title version of the URL from.
2128 * @return The title version of the URL or null if fails.
2129 * The title version of the URL can be either the URL hostname,
2130 * or the hostname with an "https://" prefix (for secure URLs),
2131 * or an empty string if, for example, the URL in question is a
2132 * file:// URL with no hostname.
2133 */
Leon Scroggins32e14a62009-06-11 10:26:34 -04002134 /* package */ static String buildTitleUrl(String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002135 String titleUrl = null;
2136
2137 if (url != null) {
2138 try {
2139 // parse the url string
2140 URL urlObj = new URL(url);
2141 if (urlObj != null) {
2142 titleUrl = "";
2143
2144 String protocol = urlObj.getProtocol();
2145 String host = urlObj.getHost();
2146
2147 if (host != null && 0 < host.length()) {
2148 titleUrl = host;
2149 if (protocol != null) {
2150 // if a secure site, add an "https://" prefix!
2151 if (protocol.equalsIgnoreCase("https")) {
2152 titleUrl = protocol + "://" + host;
2153 }
2154 }
2155 }
2156 }
2157 } catch (MalformedURLException e) {}
2158 }
2159
2160 return titleUrl;
2161 }
2162
2163 // Set the favicon in the title bar.
Grace Kloba22ac16e2009-10-07 18:00:23 -07002164 void setFavicon(Bitmap icon) {
Leon Scroggins68579392009-09-15 15:31:54 -04002165 mTitleBar.setFavicon(icon);
Michael Kolba2b2ba82010-08-04 17:54:03 -07002166 mFakeTitleBar.setFavicon(icon);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002167 }
2168
2169 /**
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002170 * Close the tab, remove its associated title bar, and adjust mTabControl's
2171 * current tab to a valid value.
Leon Scroggins1f005d32009-08-10 17:36:42 -04002172 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07002173 /* package */ void closeTab(Tab t) {
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002174 int currentIndex = mTabControl.getCurrentIndex();
2175 int removeIndex = mTabControl.getTabIndex(t);
Leon Scroggins1f005d32009-08-10 17:36:42 -04002176 mTabControl.removeTab(t);
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002177 if (currentIndex >= removeIndex && currentIndex != 0) {
2178 currentIndex--;
2179 }
2180 mTabControl.setCurrentTab(mTabControl.getTab(currentIndex));
Andrei Popescua5bf1de2009-09-23 16:39:23 +01002181 resetTitleIconAndProgress();
Leon Scroggins654899b2010-06-25 16:25:23 -04002182 updateLockIconToLatest();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002183 }
2184
Leon Scrogginsdcc5eeb2010-02-23 17:26:37 -05002185 /* package */ void goBackOnePageOrQuit() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002186 Tab current = mTabControl.getCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002187 if (current == null) {
2188 /*
2189 * Instead of finishing the activity, simply push this to the back
2190 * of the stack and let ActivityManager to choose the foreground
2191 * activity. As BrowserActivity is singleTask, it will be always the
2192 * root of the task. So we can use either true or false for
2193 * moveTaskToBack().
2194 */
2195 moveTaskToBack(true);
Grace Kloba00d85e72009-09-23 18:50:05 -07002196 return;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002197 }
2198 WebView w = current.getWebView();
2199 if (w.canGoBack()) {
2200 w.goBack();
2201 } else {
2202 // Check to see if we are closing a window that was created by
2203 // another window. If so, we switch back to that window.
Grace Kloba22ac16e2009-10-07 18:00:23 -07002204 Tab parent = current.getParentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002205 if (parent != null) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04002206 switchToTab(mTabControl.getTabIndex(parent));
2207 // Now we close the other tab
2208 closeTab(current);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002209 } else {
2210 if (current.closeOnExit()) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002211 // force the tab's inLoad() to be false as we are going to
2212 // either finish the activity or remove the tab. This will
2213 // ensure pauseWebViewTimers() taking action.
2214 mTabControl.getCurrentTab().clearInLoad();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002215 if (mTabControl.getTabCount() == 1) {
2216 finish();
2217 return;
2218 }
Mike Reed7bfa63b2009-05-28 11:08:32 -04002219 // call pauseWebViewTimers() now, we won't be able to call
2220 // it in onPause() as the WebView won't be valid.
Grace Klobaec1b5ad2009-08-18 08:42:32 -07002221 // Temporarily change mActivityInPause to be true as
2222 // pauseWebViewTimers() will do nothing if mActivityInPause
2223 // is false.
Grace Kloba918e1d72009-08-13 14:55:06 -07002224 boolean savedState = mActivityInPause;
2225 if (savedState) {
Grace Klobaec1b5ad2009-08-18 08:42:32 -07002226 Log.e(LOGTAG, "BrowserActivity is already paused "
2227 + "while handing goBackOnePageOrQuit.");
Grace Kloba918e1d72009-08-13 14:55:06 -07002228 }
2229 mActivityInPause = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -04002230 pauseWebViewTimers();
Grace Kloba918e1d72009-08-13 14:55:06 -07002231 mActivityInPause = savedState;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002232 removeTabFromContentView(current);
2233 mTabControl.removeTab(current);
2234 }
2235 /*
2236 * Instead of finishing the activity, simply push this to the back
2237 * of the stack and let ActivityManager to choose the foreground
2238 * activity. As BrowserActivity is singleTask, it will be always the
2239 * root of the task. So we can use either true or false for
2240 * moveTaskToBack().
2241 */
2242 moveTaskToBack(true);
2243 }
2244 }
2245 }
2246
Grace Kloba22ac16e2009-10-07 18:00:23 -07002247 boolean isMenuDown() {
2248 return mMenuIsDown;
2249 }
2250
Grace Kloba5942df02009-09-18 11:48:29 -07002251 @Override
2252 public boolean onKeyDown(int keyCode, KeyEvent event) {
Leon Scrogginsf65b50d2009-12-08 10:44:28 -05002253 // Even if MENU is already held down, we need to call to super to open
2254 // the IME on long press.
2255 if (KeyEvent.KEYCODE_MENU == keyCode) {
2256 mMenuIsDown = true;
2257 return super.onKeyDown(keyCode, event);
2258 }
Grace Kloba5942df02009-09-18 11:48:29 -07002259 // The default key mode is DEFAULT_KEYS_SEARCH_LOCAL. As the MENU is
2260 // still down, we don't want to trigger the search. Pretend to consume
2261 // the key and do nothing.
2262 if (mMenuIsDown) return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002263
Grace Kloba5942df02009-09-18 11:48:29 -07002264 switch(keyCode) {
Grace Kloba5942df02009-09-18 11:48:29 -07002265 case KeyEvent.KEYCODE_SPACE:
Grace Klobada0fe552009-09-22 18:17:24 -07002266 // WebView/WebTextView handle the keys in the KeyDown. As
2267 // the Activity's shortcut keys are only handled when WebView
2268 // doesn't, have to do it in onKeyDown instead of onKeyUp.
2269 if (event.isShiftPressed()) {
2270 getTopWindow().pageUp(false);
2271 } else {
2272 getTopWindow().pageDown(false);
2273 }
Grace Kloba5942df02009-09-18 11:48:29 -07002274 return true;
2275 case KeyEvent.KEYCODE_BACK:
2276 if (event.getRepeatCount() == 0) {
2277 event.startTracking();
2278 return true;
2279 } else if (mCustomView == null && mActiveTabsPage == null
2280 && event.isLongPress()) {
Michael Kolb68792c82010-08-09 16:39:18 -07002281 bookmarksOrHistoryPicker(true, false);
Grace Kloba5942df02009-09-18 11:48:29 -07002282 return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002283 }
Grace Kloba5942df02009-09-18 11:48:29 -07002284 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002285 }
Grace Kloba5942df02009-09-18 11:48:29 -07002286 return super.onKeyDown(keyCode, event);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002287 }
2288
Grace Kloba5942df02009-09-18 11:48:29 -07002289 @Override
2290 public boolean onKeyUp(int keyCode, KeyEvent event) {
2291 switch(keyCode) {
2292 case KeyEvent.KEYCODE_MENU:
2293 mMenuIsDown = false;
2294 break;
Grace Kloba5942df02009-09-18 11:48:29 -07002295 case KeyEvent.KEYCODE_BACK:
2296 if (event.isTracking() && !event.isCanceled()) {
2297 if (mCustomView != null) {
2298 // if a custom view is showing, hide it
Grace Kloba22ac16e2009-10-07 18:00:23 -07002299 mTabControl.getCurrentWebView().getWebChromeClient()
2300 .onHideCustomView();
Grace Kloba5942df02009-09-18 11:48:29 -07002301 } else if (mActiveTabsPage != null) {
2302 // if tab page is showing, hide it
2303 removeActiveTabPage(true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002304 } else {
Grace Kloba5942df02009-09-18 11:48:29 -07002305 WebView subwindow = mTabControl.getCurrentSubWindow();
2306 if (subwindow != null) {
2307 if (subwindow.canGoBack()) {
2308 subwindow.goBack();
2309 } else {
2310 dismissSubWindow(mTabControl.getCurrentTab());
2311 }
2312 } else {
2313 goBackOnePageOrQuit();
2314 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002315 }
Grace Kloba5942df02009-09-18 11:48:29 -07002316 return true;
2317 }
2318 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002319 }
Grace Kloba5942df02009-09-18 11:48:29 -07002320 return super.onKeyUp(keyCode, event);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002321 }
2322
Leon Scroggins68579392009-09-15 15:31:54 -04002323 /* package */ void stopLoading() {
Ben Murdochb7cc8b42009-09-28 10:59:09 +01002324 mDidStopLoad = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002325 resetTitleAndRevertLockIcon();
2326 WebView w = getTopWindow();
2327 w.stopLoading();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002328 // FIXME: before refactor, it is using mWebViewClient. So I keep the
2329 // same logic here. But for subwindow case, should we call into the main
2330 // WebView's onPageFinished as we never call its onPageStarted and if
2331 // the page finishes itself, we don't call onPageFinished.
2332 mTabControl.getCurrentWebView().getWebViewClient().onPageFinished(w,
2333 w.getUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08002334
2335 cancelStopToast();
2336 mStopToast = Toast
2337 .makeText(this, R.string.stopping, Toast.LENGTH_SHORT);
2338 mStopToast.show();
2339 }
2340
Grace Kloba22ac16e2009-10-07 18:00:23 -07002341 boolean didUserStopLoading() {
2342 return mDidStopLoad;
2343 }
2344
The Android Open Source Project0c908882009-03-03 19:32:16 -08002345 private void cancelStopToast() {
2346 if (mStopToast != null) {
2347 mStopToast.cancel();
2348 mStopToast = null;
2349 }
2350 }
2351
Grace Kloba22ac16e2009-10-07 18:00:23 -07002352 // called by a UI or non-UI thread to post the message
2353 public void postMessage(int what, int arg1, int arg2, Object obj,
2354 long delayMillis) {
2355 mHandler.sendMessageDelayed(mHandler.obtainMessage(what, arg1, arg2,
2356 obj), delayMillis);
2357 }
2358
2359 // called by a UI or non-UI thread to remove the message
2360 void removeMessages(int what, Object object) {
2361 mHandler.removeMessages(what, object);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002362 }
2363
2364 // public message ids
2365 public final static int LOAD_URL = 1001;
2366 public final static int STOP_LOAD = 1002;
2367
2368 // Message Ids
2369 private static final int FOCUS_NODE_HREF = 102;
Grace Kloba92c18a52009-07-31 23:48:32 -07002370 private static final int RELEASE_WAKELOCK = 107;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002371
Grace Kloba22ac16e2009-10-07 18:00:23 -07002372 static final int UPDATE_BOOKMARK_THUMBNAIL = 108;
Ben Murdoch2694e232009-09-29 09:41:11 +01002373
Ben Murdocheecb4e62010-07-06 16:30:38 +01002374 private static final int TOUCH_ICON_DOWNLOADED = 109;
2375
The Android Open Source Project0c908882009-03-03 19:32:16 -08002376 // Private handler for handling javascript and saving passwords
2377 private Handler mHandler = new Handler() {
2378
Michael Kolbe0a36662010-06-29 10:37:12 -07002379 @Override
The Android Open Source Project0c908882009-03-03 19:32:16 -08002380 public void handleMessage(Message msg) {
2381 switch (msg.what) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002382 case FOCUS_NODE_HREF:
Ben Murdoch2694e232009-09-29 09:41:11 +01002383 {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002384 String url = (String) msg.getData().get("url");
Ben Murdoch90d088c2009-11-17 18:14:04 +00002385 String title = (String) msg.getData().get("title");
The Android Open Source Project0c908882009-03-03 19:32:16 -08002386 if (url == null || url.length() == 0) {
2387 break;
2388 }
2389 HashMap focusNodeMap = (HashMap) msg.obj;
2390 WebView view = (WebView) focusNodeMap.get("webview");
2391 // Only apply the action if the top window did not change.
2392 if (getTopWindow() != view) {
2393 break;
2394 }
2395 switch (msg.arg1) {
2396 case R.id.open_context_menu_id:
2397 case R.id.view_image_context_menu_id:
Leon Scroggins92472e82010-02-17 16:32:28 -05002398 loadUrlFromContext(getTopWindow(), url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002399 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002400 case R.id.bookmark_context_menu_id:
2401 Intent intent = new Intent(BrowserActivity.this,
2402 AddBookmarkPage.class);
2403 intent.putExtra("url", url);
Ben Murdoch90d088c2009-11-17 18:14:04 +00002404 intent.putExtra("title", title);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002405 startActivity(intent);
2406 break;
2407 case R.id.share_link_context_menu_id:
Leon Scroggins3e204452010-05-10 11:06:03 -04002408 sharePage(BrowserActivity.this, title, url, null,
Leon Scroggins96afcb12009-12-10 12:35:56 -05002409 null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002410 break;
2411 case R.id.copy_link_context_menu_id:
2412 copy(url);
2413 break;
2414 case R.id.save_link_context_menu_id:
2415 case R.id.download_context_menu_id:
2416 onDownloadStartNoStream(url, null, null, null, -1);
2417 break;
2418 }
2419 break;
Ben Murdoch2694e232009-09-29 09:41:11 +01002420 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002421
2422 case LOAD_URL:
Leon Scroggins92472e82010-02-17 16:32:28 -05002423 loadUrlFromContext(getTopWindow(), (String) msg.obj);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002424 break;
2425
2426 case STOP_LOAD:
2427 stopLoading();
2428 break;
2429
The Android Open Source Project0c908882009-03-03 19:32:16 -08002430 case RELEASE_WAKELOCK:
2431 if (mWakeLock.isHeld()) {
2432 mWakeLock.release();
Grace Kloba5d0e02e2009-10-05 15:15:36 -07002433 // if we reach here, Browser should be still in the
2434 // background loading after WAKELOCK_TIMEOUT (5-min).
2435 // To avoid burning the battery, stop loading.
2436 mTabControl.stopAllLoading();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002437 }
2438 break;
Ben Murdoch2694e232009-09-29 09:41:11 +01002439
2440 case UPDATE_BOOKMARK_THUMBNAIL:
2441 WebView view = (WebView) msg.obj;
2442 if (view != null) {
2443 updateScreenshot(view);
2444 }
2445 break;
Ben Murdocheecb4e62010-07-06 16:30:38 +01002446
2447 case TOUCH_ICON_DOWNLOADED:
2448 Bundle b = msg.getData();
2449 showSaveToHomescreenDialog(b.getString("url"),
2450 b.getString("title"),
2451 (Bitmap) b.getParcelable("touchIcon"),
2452 (Bitmap) b.getParcelable("favicon"));
2453 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002454 }
2455 }
2456 };
2457
Leon Scroggins96afcb12009-12-10 12:35:56 -05002458 /**
2459 * Share a page, providing the title, url, favicon, and a screenshot. Uses
2460 * an {@link Intent} to launch the Activity chooser.
2461 * @param c Context used to launch a new Activity.
2462 * @param title Title of the page. Stored in the Intent with
Paul Westbrook03e6d392010-02-12 10:33:29 -08002463 * {@link Intent#EXTRA_SUBJECT}
Leon Scroggins96afcb12009-12-10 12:35:56 -05002464 * @param url URL of the page. Stored in the Intent with
2465 * {@link Intent#EXTRA_TEXT}
2466 * @param favicon Bitmap of the favicon for the page. Stored in the Intent
2467 * with {@link Browser#EXTRA_SHARE_FAVICON}
2468 * @param screenshot Bitmap of a screenshot of the page. Stored in the
2469 * Intent with {@link Browser#EXTRA_SHARE_SCREENSHOT}
2470 */
2471 public static final void sharePage(Context c, String title, String url,
2472 Bitmap favicon, Bitmap screenshot) {
2473 Intent send = new Intent(Intent.ACTION_SEND);
2474 send.setType("text/plain");
2475 send.putExtra(Intent.EXTRA_TEXT, url);
Paul Westbrook03e6d392010-02-12 10:33:29 -08002476 send.putExtra(Intent.EXTRA_SUBJECT, title);
Leon Scroggins96afcb12009-12-10 12:35:56 -05002477 send.putExtra(Browser.EXTRA_SHARE_FAVICON, favicon);
2478 send.putExtra(Browser.EXTRA_SHARE_SCREENSHOT, screenshot);
2479 try {
2480 c.startActivity(Intent.createChooser(send, c.getString(
2481 R.string.choosertitle_sharevia)));
2482 } catch(android.content.ActivityNotFoundException ex) {
2483 // if no app handles it, do nothing
2484 }
2485 }
2486
Leon Scroggins89c6d362009-07-15 16:54:37 -04002487 private void updateScreenshot(WebView view) {
2488 // If this is a bookmarked site, add a screenshot to the database.
2489 // FIXME: When should we update? Every time?
2490 // FIXME: Would like to make sure there is actually something to
2491 // draw, but the API for that (WebViewCore.pictureReady()) is not
2492 // currently accessible here.
Ben Murdochaac7aa62009-09-17 16:57:40 +01002493
Ben Murdoch87cc65d2010-06-29 20:34:10 +01002494 final Bitmap bm = createScreenshot(view, getDesiredThumbnailWidth(this),
2495 getDesiredThumbnailHeight(this));
Patrick Scottcb192b52010-04-14 14:38:55 -04002496 if (bm == null) {
2497 return;
Leon Scroggins89c6d362009-07-15 16:54:37 -04002498 }
Patrick Scottcb192b52010-04-14 14:38:55 -04002499
2500 final ContentResolver cr = getContentResolver();
2501 final String url = view.getUrl();
2502 final String originalUrl = view.getOriginalUrl();
2503
2504 new AsyncTask<Void, Void, Void>() {
2505 @Override
2506 protected Void doInBackground(Void... unused) {
2507 Cursor c = null;
2508 try {
Jeff Hamilton84029622010-08-05 14:29:28 -05002509 c = Bookmarks.queryBookmarksForUrl(
Jeff Hamilton8ce956c2010-08-17 11:13:53 -05002510 cr, originalUrl, url);
Patrick Scottcb192b52010-04-14 14:38:55 -04002511 if (c != null) {
2512 if (c.moveToFirst()) {
2513 ContentValues values = new ContentValues();
2514 final ByteArrayOutputStream os
2515 = new ByteArrayOutputStream();
2516 bm.compress(Bitmap.CompressFormat.PNG, 100, os);
Jeff Hamilton8ce956c2010-08-17 11:13:53 -05002517 values.put(BrowserContract.Bookmarks.THUMBNAIL,
Patrick Scottcb192b52010-04-14 14:38:55 -04002518 os.toByteArray());
2519 do {
2520 cr.update(ContentUris.withAppendedId(
Jeff Hamilton8ce956c2010-08-17 11:13:53 -05002521 BrowserContract.Bookmarks.CONTENT_URI, c.getLong(0)),
Patrick Scottcb192b52010-04-14 14:38:55 -04002522 values, null, null);
2523 } while (c.moveToNext());
2524 }
2525 }
2526 } catch (IllegalStateException e) {
2527 // Ignore
2528 } finally {
2529 if (c != null) c.close();
2530 }
2531 return null;
2532 }
2533 }.execute();
Leon Scroggins89c6d362009-07-15 16:54:37 -04002534 }
2535
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002536 /**
Leon Scrogginsf8551612009-09-24 16:06:02 -04002537 * Values for the size of the thumbnail created when taking a screenshot.
2538 * Lazily initialized. Instead of using these directly, use
2539 * getDesiredThumbnailWidth() or getDesiredThumbnailHeight().
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002540 */
Leon Scrogginsf8551612009-09-24 16:06:02 -04002541 private static int THUMBNAIL_WIDTH = 0;
2542 private static int THUMBNAIL_HEIGHT = 0;
2543
2544 /**
2545 * Return the desired width for thumbnail screenshots, which are stored in
2546 * the database, and used on the bookmarks screen.
2547 * @param context Context for finding out the density of the screen.
2548 * @return int desired width for thumbnail screenshot.
2549 */
2550 /* package */ static int getDesiredThumbnailWidth(Context context) {
2551 if (THUMBNAIL_WIDTH == 0) {
2552 float density = context.getResources().getDisplayMetrics().density;
2553 THUMBNAIL_WIDTH = (int) (90 * density);
2554 THUMBNAIL_HEIGHT = (int) (80 * density);
2555 }
2556 return THUMBNAIL_WIDTH;
2557 }
2558
2559 /**
2560 * Return the desired height for thumbnail screenshots, which are stored in
2561 * the database, and used on the bookmarks screen.
2562 * @param context Context for finding out the density of the screen.
2563 * @return int desired height for thumbnail screenshot.
2564 */
2565 /* package */ static int getDesiredThumbnailHeight(Context context) {
2566 // To ensure that they are both initialized.
2567 getDesiredThumbnailWidth(context);
2568 return THUMBNAIL_HEIGHT;
2569 }
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002570
Ben Murdoch87cc65d2010-06-29 20:34:10 +01002571 private Bitmap createScreenshot(WebView view, int width, int height) {
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002572 Picture thumbnail = view.capturePicture();
Leon Scroggins45800572009-09-29 16:38:47 -04002573 if (thumbnail == null) {
2574 return null;
2575 }
Ben Murdoch87cc65d2010-06-29 20:34:10 +01002576 Bitmap bm = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002577 Canvas canvas = new Canvas(bm);
2578 // May need to tweak these values to determine what is the
2579 // best scale factor
Ben Murdoch2694e232009-09-29 09:41:11 +01002580 int thumbnailWidth = thumbnail.getWidth();
Ben Murdochae59c3f2009-10-20 18:30:28 +01002581 int thumbnailHeight = thumbnail.getHeight();
2582 float scaleFactorX = 1.0f;
2583 float scaleFactorY = 1.0f;
Ben Murdoch2694e232009-09-29 09:41:11 +01002584 if (thumbnailWidth > 0) {
Ben Murdoch87cc65d2010-06-29 20:34:10 +01002585 scaleFactorX = (float) width / (float)thumbnailWidth;
Ben Murdochae59c3f2009-10-20 18:30:28 +01002586 } else {
2587 return null;
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002588 }
Ben Murdochae59c3f2009-10-20 18:30:28 +01002589
2590 if (view.getWidth() > view.getHeight() &&
2591 thumbnailHeight < view.getHeight() && thumbnailHeight > 0) {
2592 // If the device is in landscape and the page is shorter
2593 // than the height of the view, stretch the thumbnail to fill the
2594 // space.
Ben Murdoch87cc65d2010-06-29 20:34:10 +01002595 scaleFactorY = (float) height / (float)thumbnailHeight;
Ben Murdochae59c3f2009-10-20 18:30:28 +01002596 } else {
2597 // In the portrait case, this looks nice.
2598 scaleFactorY = scaleFactorX;
2599 }
2600
2601 canvas.scale(scaleFactorX, scaleFactorY);
2602
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002603 thumbnail.draw(canvas);
2604 return bm;
2605 }
2606
The Android Open Source Project0c908882009-03-03 19:32:16 -08002607 // -------------------------------------------------------------------------
Grace Kloba22ac16e2009-10-07 18:00:23 -07002608 // Helper function for WebViewClient.
The Android Open Source Project0c908882009-03-03 19:32:16 -08002609 //-------------------------------------------------------------------------
2610
2611 // Use in overrideUrlLoading
2612 /* package */ final static String SCHEME_WTAI = "wtai://wp/";
2613 /* package */ final static String SCHEME_WTAI_MC = "wtai://wp/mc;";
2614 /* package */ final static String SCHEME_WTAI_SD = "wtai://wp/sd;";
2615 /* package */ final static String SCHEME_WTAI_AP = "wtai://wp/ap;";
2616
Leon Scroggins92472e82010-02-17 16:32:28 -05002617 // Keep this initial progress in sync with initialProgressValue (* 100)
2618 // in ProgressTracker.cpp
2619 private final static int INITIAL_PROGRESS = 10;
2620
Grace Kloba22ac16e2009-10-07 18:00:23 -07002621 void onPageStarted(WebView view, String url, Bitmap favicon) {
2622 // when BrowserActivity just starts, onPageStarted may be called before
2623 // onResume as it is triggered from onCreate. Call resumeWebViewTimers
2624 // to start the timer. As we won't switch tabs while an activity is in
2625 // pause state, we can ensure calling resume and pause in pair.
2626 if (mActivityInPause) resumeWebViewTimers();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002627
Grace Kloba22ac16e2009-10-07 18:00:23 -07002628 resetLockIcon(url);
2629 setUrlTitle(url, null);
2630 setFavicon(favicon);
Leon Scroggins8cf8f682009-11-04 11:13:50 -08002631 // Show some progress so that the user knows the page is beginning to
2632 // load
Leon Scroggins92472e82010-02-17 16:32:28 -05002633 onProgressChanged(view, INITIAL_PROGRESS);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002634 mDidStopLoad = false;
Grace Kloba22ac16e2009-10-07 18:00:23 -07002635 if (!mIsNetworkUp) createAndShowNetworkDialog();
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04002636 endActionMode();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002637 if (mSettings.isTracing()) {
2638 String host;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002639 try {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002640 WebAddress uri = new WebAddress(url);
2641 host = uri.mHost;
2642 } catch (android.net.ParseException ex) {
2643 host = "browser";
The Android Open Source Project0c908882009-03-03 19:32:16 -08002644 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002645 host = host.replace('.', '_');
2646 host += ".trace";
2647 mInTrace = true;
2648 Debug.startMethodTracing(host, 20 * 1024 * 1024);
2649 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002650
Grace Kloba22ac16e2009-10-07 18:00:23 -07002651 // Performance probe
2652 if (false) {
2653 mStart = SystemClock.uptimeMillis();
2654 mProcessStart = Process.getElapsedCpuTime();
2655 long[] sysCpu = new long[7];
2656 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2657 sysCpu, null)) {
2658 mUserStart = sysCpu[0] + sysCpu[1];
2659 mSystemStart = sysCpu[2];
2660 mIdleStart = sysCpu[3];
2661 mIrqStart = sysCpu[4] + sysCpu[5] + sysCpu[6];
2662 }
2663 mUiStart = SystemClock.currentThreadTimeMillis();
2664 }
2665 }
2666
2667 void onPageFinished(WebView view, String url) {
2668 // Reset the title and icon in case we stopped a provisional load.
2669 resetTitleAndIcon(view);
2670 // Update the lock icon image only once we are done loading
2671 updateLockIconToLatest();
2672 // pause the WebView timer and release the wake lock if it is finished
2673 // while BrowserActivity is in pause state.
2674 if (mActivityInPause && pauseWebViewTimers()) {
2675 if (mWakeLock.isHeld()) {
2676 mHandler.removeMessages(RELEASE_WAKELOCK);
2677 mWakeLock.release();
2678 }
2679 }
2680
2681 // Performance probe
2682 if (false) {
2683 long[] sysCpu = new long[7];
2684 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2685 sysCpu, null)) {
2686 String uiInfo = "UI thread used "
2687 + (SystemClock.currentThreadTimeMillis() - mUiStart)
2688 + " ms";
2689 if (LOGD_ENABLED) {
2690 Log.d(LOGTAG, uiInfo);
2691 }
2692 //The string that gets written to the log
2693 String performanceString = "It took total "
2694 + (SystemClock.uptimeMillis() - mStart)
2695 + " ms clock time to load the page."
2696 + "\nbrowser process used "
2697 + (Process.getElapsedCpuTime() - mProcessStart)
2698 + " ms, user processes used "
2699 + (sysCpu[0] + sysCpu[1] - mUserStart) * 10
2700 + " ms, kernel used "
2701 + (sysCpu[2] - mSystemStart) * 10
2702 + " ms, idle took " + (sysCpu[3] - mIdleStart) * 10
2703 + " ms and irq took "
2704 + (sysCpu[4] + sysCpu[5] + sysCpu[6] - mIrqStart)
2705 * 10 + " ms, " + uiInfo;
2706 if (LOGD_ENABLED) {
2707 Log.d(LOGTAG, performanceString + "\nWebpage: " + url);
2708 }
2709 if (url != null) {
2710 // strip the url to maintain consistency
2711 String newUrl = new String(url);
2712 if (newUrl.startsWith("http://www.")) {
2713 newUrl = newUrl.substring(11);
2714 } else if (newUrl.startsWith("http://")) {
2715 newUrl = newUrl.substring(7);
2716 } else if (newUrl.startsWith("https://www.")) {
2717 newUrl = newUrl.substring(12);
2718 } else if (newUrl.startsWith("https://")) {
2719 newUrl = newUrl.substring(8);
2720 }
2721 if (LOGD_ENABLED) {
2722 Log.d(LOGTAG, newUrl + " loaded");
2723 }
Grace Kloba5b078b52009-06-24 20:23:41 -07002724 }
2725 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002726 }
Grace Kloba5b078b52009-06-24 20:23:41 -07002727
Grace Kloba22ac16e2009-10-07 18:00:23 -07002728 if (mInTrace) {
2729 mInTrace = false;
2730 Debug.stopMethodTracing();
2731 }
2732 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002733
Grace Klobae7fe26b2010-06-28 16:23:33 -07002734 private void closeEmptyChildTab() {
2735 Tab current = mTabControl.getCurrentTab();
2736 if (current != null
2737 && current.getWebView().copyBackForwardList().getSize() == 0) {
2738 Tab parent = current.getParentTab();
2739 if (parent != null) {
2740 switchToTab(mTabControl.getTabIndex(parent));
2741 closeTab(current);
2742 }
2743 }
2744 }
2745
Grace Kloba22ac16e2009-10-07 18:00:23 -07002746 boolean shouldOverrideUrlLoading(WebView view, String url) {
2747 if (url.startsWith(SCHEME_WTAI)) {
2748 // wtai://wp/mc;number
2749 // number=string(phone-number)
2750 if (url.startsWith(SCHEME_WTAI_MC)) {
2751 Intent intent = new Intent(Intent.ACTION_VIEW,
2752 Uri.parse(WebView.SCHEME_TEL +
2753 url.substring(SCHEME_WTAI_MC.length())));
2754 startActivity(intent);
Grace Klobae7fe26b2010-06-28 16:23:33 -07002755 // before leaving BrowserActivity, close the empty child tab.
2756 // If a new tab is created through JavaScript open to load this
2757 // url, we would like to close it as we will load this url in a
2758 // different Activity.
2759 closeEmptyChildTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002760 return true;
2761 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002762 // wtai://wp/sd;dtmf
2763 // dtmf=string(dialstring)
2764 if (url.startsWith(SCHEME_WTAI_SD)) {
2765 // TODO: only send when there is active voice connection
2766 return false;
2767 }
2768 // wtai://wp/ap;number;name
2769 // number=string(phone-number)
2770 // name=string
2771 if (url.startsWith(SCHEME_WTAI_AP)) {
2772 // TODO
2773 return false;
2774 }
2775 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002776
Grace Kloba22ac16e2009-10-07 18:00:23 -07002777 // The "about:" schemes are internal to the browser; don't want these to
2778 // be dispatched to other apps.
2779 if (url.startsWith("about:")) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002780 return false;
2781 }
2782
Grace Kloba22ac16e2009-10-07 18:00:23 -07002783 Intent intent;
2784 // perform generic parsing of the URI to turn it into an Intent.
2785 try {
2786 intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME);
2787 } catch (URISyntaxException ex) {
2788 Log.w("Browser", "Bad URI " + url + ": " + ex.getMessage());
2789 return false;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002790 }
2791
Grace Kloba22ac16e2009-10-07 18:00:23 -07002792 // check whether the intent can be resolved. If not, we will see
2793 // whether we can download it from the Market.
2794 if (getPackageManager().resolveActivity(intent, 0) == null) {
2795 String packagename = intent.getPackage();
2796 if (packagename != null) {
2797 intent = new Intent(Intent.ACTION_VIEW, Uri
2798 .parse("market://search?q=pname:" + packagename));
2799 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2800 startActivity(intent);
Grace Klobae7fe26b2010-06-28 16:23:33 -07002801 // before leaving BrowserActivity, close the empty child tab.
2802 // If a new tab is created through JavaScript open to load this
2803 // url, we would like to close it as we will load this url in a
2804 // different Activity.
2805 closeEmptyChildTab();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002806 return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002807 } else {
2808 return false;
2809 }
2810 }
2811
Grace Kloba22ac16e2009-10-07 18:00:23 -07002812 // sanitize the Intent, ensuring web pages can not bypass browser
2813 // security (only access to BROWSABLE activities).
2814 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2815 intent.setComponent(null);
2816 try {
2817 if (startActivityIfNeeded(intent, -1)) {
Grace Klobae7fe26b2010-06-28 16:23:33 -07002818 // before leaving BrowserActivity, close the empty child tab.
2819 // If a new tab is created through JavaScript open to load this
2820 // url, we would like to close it as we will load this url in a
2821 // different Activity.
2822 closeEmptyChildTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002823 return true;
2824 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002825 } catch (ActivityNotFoundException ex) {
2826 // ignore the error. If no application can handle the URL,
2827 // eg about:blank, assume the browser can handle it.
2828 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002829
Grace Kloba22ac16e2009-10-07 18:00:23 -07002830 if (mMenuIsDown) {
Michael Kolb68792c82010-08-09 16:39:18 -07002831 openTab(url, false);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002832 closeOptionsMenu();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002833 return true;
2834 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002835 return false;
2836 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002837
Grace Kloba22ac16e2009-10-07 18:00:23 -07002838 // -------------------------------------------------------------------------
2839 // Helper function for WebChromeClient
2840 // -------------------------------------------------------------------------
The Android Open Source Project0c908882009-03-03 19:32:16 -08002841
Grace Kloba22ac16e2009-10-07 18:00:23 -07002842 void onProgressChanged(WebView view, int newProgress) {
Michael Kolba2b2ba82010-08-04 17:54:03 -07002843
2844 // On the phone, the fake title bar will always cover up the
2845 // regular title bar (or the regular one is offscreen), so only the
2846 // fake title bar needs to change its progress
2847 mFakeTitleBar.setProgress(newProgress);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002848
Grace Kloba22ac16e2009-10-07 18:00:23 -07002849 if (newProgress == 100) {
2850 // onProgressChanged() may continue to be called after the main
2851 // frame has finished loading, as any remaining sub frames continue
2852 // to load. We'll only get called once though with newProgress as
2853 // 100 when everything is loaded. (onPageFinished is called once
2854 // when the main frame completes loading regardless of the state of
2855 // any sub frames so calls to onProgressChanges may continue after
2856 // onPageFinished has executed)
2857 if (mInLoad) {
2858 mInLoad = false;
Leon Scrogginsa27ff192009-09-14 12:58:04 -04002859 updateInLoadMenuItems();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002860 // If the options menu is open, leave the title bar
2861 if (!mOptionsMenuOpen || !mIconView) {
2862 hideFakeTitleBar();
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07002863 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002864 }
Leon Scrogginsaa37e7f2010-03-05 11:51:20 -05002865 } else {
2866 if (!mInLoad) {
2867 // onPageFinished may have already been called but a subframe is
2868 // still loading and updating the progress. Reset mInLoad and
2869 // update the menu items.
2870 mInLoad = true;
2871 updateInLoadMenuItems();
2872 }
2873 // When the page first begins to load, the Activity may still be
2874 // paused, in which case showFakeTitleBar will do nothing. Call
2875 // again as the page continues to load so that it will be shown.
2876 // (Calling it will the fake title bar is already showing will also
2877 // do nothing.
Grace Kloba22ac16e2009-10-07 18:00:23 -07002878 if (!mOptionsMenuOpen || mIconView) {
2879 // This page has begun to load, so show the title bar
2880 showFakeTitleBar();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002881 }
2882 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002883 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002884
Grace Kloba22ac16e2009-10-07 18:00:23 -07002885 void onShowCustomView(View view, WebChromeClient.CustomViewCallback callback) {
Derek Sollenberger8ff57db2009-12-08 15:39:55 -05002886 // if a view already exists then immediately terminate the new one
2887 if (mCustomView != null) {
2888 callback.onCustomViewHidden();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002889 return;
Derek Sollenberger8ff57db2009-12-08 15:39:55 -05002890 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002891
2892 // Add the custom view to its container.
2893 mCustomViewContainer.addView(view, COVER_SCREEN_GRAVITY_CENTER);
2894 mCustomView = view;
2895 mCustomViewCallback = callback;
2896 // Save the menu state and set it to empty while the custom
2897 // view is showing.
2898 mOldMenuState = mMenuState;
2899 mMenuState = EMPTY_MENU;
2900 // Hide the content view.
2901 mContentView.setVisibility(View.GONE);
2902 // Finally show the custom view container.
Andrei Popescu163ab742009-10-20 17:58:23 +01002903 setStatusBarVisibility(false);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002904 mCustomViewContainer.setVisibility(View.VISIBLE);
2905 mCustomViewContainer.bringToFront();
2906 }
2907
2908 void onHideCustomView() {
2909 if (mCustomView == null)
2910 return;
2911
2912 // Hide the custom view.
2913 mCustomView.setVisibility(View.GONE);
2914 // Remove the custom view from its container.
2915 mCustomViewContainer.removeView(mCustomView);
2916 mCustomView = null;
2917 // Reset the old menu state.
2918 mMenuState = mOldMenuState;
2919 mOldMenuState = EMPTY_MENU;
2920 mCustomViewContainer.setVisibility(View.GONE);
2921 mCustomViewCallback.onCustomViewHidden();
2922 // Show the content view.
Andrei Popescu163ab742009-10-20 17:58:23 +01002923 setStatusBarVisibility(true);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002924 mContentView.setVisibility(View.VISIBLE);
2925 }
2926
2927 Bitmap getDefaultVideoPoster() {
2928 if (mDefaultVideoPoster == null) {
2929 mDefaultVideoPoster = BitmapFactory.decodeResource(
2930 getResources(), R.drawable.default_video_poster);
Patrick Scott3918d442009-08-04 13:22:29 -04002931 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002932 return mDefaultVideoPoster;
2933 }
Patrick Scott3918d442009-08-04 13:22:29 -04002934
Grace Kloba22ac16e2009-10-07 18:00:23 -07002935 View getVideoLoadingProgressView() {
2936 if (mVideoProgressView == null) {
2937 LayoutInflater inflater = LayoutInflater.from(BrowserActivity.this);
2938 mVideoProgressView = inflater.inflate(
2939 R.layout.video_loading_progress, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002940 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002941 return mVideoProgressView;
2942 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002943
Leon Scroggins8d5fa432009-10-02 15:55:59 -04002944 /*
2945 * The Object used to inform the WebView of the file to upload.
2946 */
2947 private ValueCallback<Uri> mUploadMessage;
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002948 private String mCameraFilePath;
Leon Scroggins8d5fa432009-10-02 15:55:59 -04002949
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002950 void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
2951
2952 final String imageMimeType = "image/*";
Ben Murdoch6af492a2010-06-15 12:38:17 +01002953 final String videoMimeType = "video/*";
Ben Murdoch039bd472010-07-21 21:26:57 +01002954 final String audioMimeType = "audio/*";
Ben Murdochb50d7402010-07-16 12:42:22 +01002955 final String mediaSourceKey = "capture";
Ben Murdoch6af492a2010-06-15 12:38:17 +01002956 final String mediaSourceValueCamera = "camera";
Ben Murdochb50d7402010-07-16 12:42:22 +01002957 final String mediaSourceValueFileSystem = "filesystem";
Ben Murdoch6af492a2010-06-15 12:38:17 +01002958 final String mediaSourceValueCamcorder = "camcorder";
Ben Murdoch039bd472010-07-21 21:26:57 +01002959 final String mediaSourceValueMicrophone = "microphone";
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002960
Ben Murdoch039bd472010-07-21 21:26:57 +01002961 // media source can be 'filesystem' or 'camera' or 'camcorder' or 'microphone'.
Ben Murdoch6af492a2010-06-15 12:38:17 +01002962 String mediaSource = "";
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002963
Ben Murdoch6af492a2010-06-15 12:38:17 +01002964 // We add the camera intent if there was no accept type (or '*/*' or 'image/*').
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002965 boolean addCameraIntent = true;
Ben Murdoch6af492a2010-06-15 12:38:17 +01002966 // We add the camcorder intent if there was no accept type (or '*/*' or 'video/*').
2967 boolean addCamcorderIntent = true;
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002968
Ben Murdoch6af492a2010-06-15 12:38:17 +01002969 if (mUploadMessage != null) {
2970 // Already a file picker operation in progress.
2971 return;
2972 }
2973
Grace Kloba22ac16e2009-10-07 18:00:23 -07002974 mUploadMessage = uploadMsg;
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002975
2976 // Parse the accept type.
2977 String params[] = acceptType.split(";");
2978 String mimeType = params[0];
2979
2980 for (String p : params) {
2981 String[] keyValue = p.split("=");
2982 if (keyValue.length == 2) {
2983 // Process key=value parameters.
Ben Murdoch6af492a2010-06-15 12:38:17 +01002984 if (mediaSourceKey.equals(keyValue[0])) {
2985 mediaSource = keyValue[1];
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002986 }
2987 }
2988 }
2989
2990 // This intent will display the standard OPENABLE file picker.
Grace Kloba22ac16e2009-10-07 18:00:23 -07002991 Intent i = new Intent(Intent.ACTION_GET_CONTENT);
2992 i.addCategory(Intent.CATEGORY_OPENABLE);
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002993
2994 // Create an intent to add to the standard file picker that will
2995 // capture an image from the camera. We'll combine this intent with
2996 // the standard OPENABLE picker unless the web developer specifically
2997 // requested the camera or gallery be opened by passing a parameter
2998 // in the accept type.
2999 Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
3000 File externalDataDir = Environment.getExternalStoragePublicDirectory(
3001 Environment.DIRECTORY_DCIM);
3002 File cameraDataDir = new File(externalDataDir.getAbsolutePath() +
3003 File.separator + "browser-photos");
3004 cameraDataDir.mkdirs();
3005 mCameraFilePath = cameraDataDir.getAbsolutePath() + File.separator +
3006 System.currentTimeMillis() + ".jpg";
3007 cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(mCameraFilePath)));
3008
Ben Murdoch6af492a2010-06-15 12:38:17 +01003009 Intent camcorderIntent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
3010
Ben Murdoch039bd472010-07-21 21:26:57 +01003011 Intent soundRecIntent = new Intent(MediaStore.Audio.Media.RECORD_SOUND_ACTION);
3012
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003013 if (mimeType.equals(imageMimeType)) {
3014 i.setType(imageMimeType);
Ben Murdoch6af492a2010-06-15 12:38:17 +01003015 addCamcorderIntent = false;
3016 if (mediaSource.equals(mediaSourceValueCamera)) {
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003017 // Specified 'image/*' and requested the camera, so go ahead and launch the camera
3018 // directly.
3019 BrowserActivity.this.startActivityForResult(cameraIntent, FILE_SELECTED);
3020 return;
Ben Murdochb50d7402010-07-16 12:42:22 +01003021 } else if (mediaSource.equals(mediaSourceValueFileSystem)) {
3022 // Specified filesytem as the source, so don't want to consider the camera.
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003023 addCameraIntent = false;
3024 }
Ben Murdoch6af492a2010-06-15 12:38:17 +01003025 } else if (mimeType.equals(videoMimeType)) {
3026 i.setType(videoMimeType);
3027 addCameraIntent = false;
3028 // The camcorder saves it's own file and returns it to us in the intent, so
3029 // we don't need to generate one here.
3030 mCameraFilePath = null;
3031
3032 if (mediaSource.equals(mediaSourceValueCamcorder)) {
Ben Murdoch039bd472010-07-21 21:26:57 +01003033 // Specified 'video/*' and requested the camcorder, so go ahead and launch the
3034 // camcorder directly.
Ben Murdoch6af492a2010-06-15 12:38:17 +01003035 BrowserActivity.this.startActivityForResult(camcorderIntent, FILE_SELECTED);
3036 return;
Ben Murdochb50d7402010-07-16 12:42:22 +01003037 } else if (mediaSource.equals(mediaSourceValueFileSystem)) {
3038 // Specified filesystem as the source, so don't want to consider the camcorder.
Ben Murdoch6af492a2010-06-15 12:38:17 +01003039 addCamcorderIntent = false;
3040 }
Ben Murdoch039bd472010-07-21 21:26:57 +01003041 } else if (mimeType.equals(audioMimeType)) {
3042 i.setType(audioMimeType);
3043 addCameraIntent = false;
3044 addCamcorderIntent = false;
3045 if (mediaSource.equals(mediaSourceValueMicrophone)) {
3046 // Specified 'audio/*' and requested microphone, so go ahead and launch the sound
3047 // recorder.
3048 BrowserActivity.this.startActivityForResult(soundRecIntent, FILE_SELECTED);
3049 return;
3050 }
3051 // On a default system, there is no single option to open an audio "gallery". Both the
3052 // sound recorder and music browser respond to the OPENABLE/audio/* intent unlike the
3053 // image/* and video/* OPENABLE intents where the image / video gallery are the only
3054 // respondants (and so the user is not prompted by default).
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003055 } else {
3056 i.setType("*/*");
3057 }
3058
Ben Murdoch6af492a2010-06-15 12:38:17 +01003059 // Combine the chooser and the extra choices (like camera or camcorder)
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003060 Intent chooser = new Intent(Intent.ACTION_CHOOSER);
3061 chooser.putExtra(Intent.EXTRA_INTENT, i);
3062
Ben Murdoch6af492a2010-06-15 12:38:17 +01003063 Vector<Intent> extraInitialIntents = new Vector<Intent>(0);
3064
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003065 if (addCameraIntent) {
Ben Murdoch6af492a2010-06-15 12:38:17 +01003066 extraInitialIntents.add(cameraIntent);
3067 }
3068
3069 if (addCamcorderIntent) {
3070 extraInitialIntents.add(camcorderIntent);
3071 }
3072
3073 if (extraInitialIntents.size() > 0) {
3074 Intent[] extraIntents = new Intent[extraInitialIntents.size()];
3075 chooser.putExtra(Intent.EXTRA_INITIAL_INTENTS, extraInitialIntents.toArray(extraIntents));
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003076 }
3077
3078 chooser.putExtra(Intent.EXTRA_TITLE, getString(R.string.choose_upload));
3079 BrowserActivity.this.startActivityForResult(chooser, FILE_SELECTED);
Grace Kloba22ac16e2009-10-07 18:00:23 -07003080 }
3081
3082 // -------------------------------------------------------------------------
3083 // Implement functions for DownloadListener
3084 // -------------------------------------------------------------------------
3085
The Android Open Source Project0c908882009-03-03 19:32:16 -08003086 /**
3087 * Notify the host application a download should be done, or that
3088 * the data should be streamed if a streaming viewer is available.
3089 * @param url The full url to the content that should be downloaded
3090 * @param contentDisposition Content-disposition http header, if
3091 * present.
3092 * @param mimetype The mimetype of the content reported by the server
3093 * @param contentLength The file size reported by the server
3094 */
3095 public void onDownloadStart(String url, String userAgent,
3096 String contentDisposition, String mimetype, long contentLength) {
3097 // if we're dealing wih A/V content that's not explicitly marked
3098 // for download, check if it's streamable.
3099 if (contentDisposition == null
Patrick Scotte1fb9662009-08-31 14:31:52 -04003100 || !contentDisposition.regionMatches(
3101 true, 0, "attachment", 0, 10)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003102 // query the package manager to see if there's a registered handler
3103 // that matches.
3104 Intent intent = new Intent(Intent.ACTION_VIEW);
3105 intent.setDataAndType(Uri.parse(url), mimetype);
Patrick Scotte1fb9662009-08-31 14:31:52 -04003106 ResolveInfo info = getPackageManager().resolveActivity(intent,
3107 PackageManager.MATCH_DEFAULT_ONLY);
3108 if (info != null) {
3109 ComponentName myName = getComponentName();
3110 // If we resolved to ourselves, we don't want to attempt to
3111 // load the url only to try and download it again.
3112 if (!myName.getPackageName().equals(
3113 info.activityInfo.packageName)
3114 || !myName.getClassName().equals(
3115 info.activityInfo.name)) {
3116 // someone (other than us) knows how to handle this mime
3117 // type with this scheme, don't download.
3118 try {
3119 startActivity(intent);
3120 return;
3121 } catch (ActivityNotFoundException ex) {
3122 if (LOGD_ENABLED) {
3123 Log.d(LOGTAG, "activity not found for " + mimetype
3124 + " over " + Uri.parse(url).getScheme(),
3125 ex);
3126 }
3127 // Best behavior is to fall back to a download in this
3128 // case
The Android Open Source Project0c908882009-03-03 19:32:16 -08003129 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003130 }
3131 }
3132 }
3133 onDownloadStartNoStream(url, userAgent, contentDisposition, mimetype, contentLength);
3134 }
3135
Kristian Monsenfa52d172010-03-25 18:29:21 +00003136 // This is to work around the fact that java.net.URI throws Exceptions
3137 // instead of just encoding URL's properly
3138 // Helper method for onDownloadStartNoStream
3139 private static String encodePath(String path) {
3140 char[] chars = path.toCharArray();
3141
3142 boolean needed = false;
3143 for (char c : chars) {
3144 if (c == '[' || c == ']') {
3145 needed = true;
3146 break;
3147 }
3148 }
3149 if (needed == false) {
3150 return path;
3151 }
3152
3153 StringBuilder sb = new StringBuilder("");
3154 for (char c : chars) {
3155 if (c == '[' || c == ']') {
3156 sb.append('%');
3157 sb.append(Integer.toHexString(c));
3158 } else {
3159 sb.append(c);
3160 }
3161 }
3162
3163 return sb.toString();
3164 }
3165
The Android Open Source Project0c908882009-03-03 19:32:16 -08003166 /**
3167 * Notify the host application a download should be done, even if there
3168 * is a streaming viewer available for thise type.
3169 * @param url The full url to the content that should be downloaded
3170 * @param contentDisposition Content-disposition http header, if
3171 * present.
3172 * @param mimetype The mimetype of the content reported by the server
3173 * @param contentLength The file size reported by the server
3174 */
3175 /*package */ void onDownloadStartNoStream(String url, String userAgent,
3176 String contentDisposition, String mimetype, long contentLength) {
3177
3178 String filename = URLUtil.guessFileName(url,
3179 contentDisposition, mimetype);
3180
3181 // Check to see if we have an SDCard
3182 String status = Environment.getExternalStorageState();
3183 if (!status.equals(Environment.MEDIA_MOUNTED)) {
3184 int title;
3185 String msg;
3186
3187 // Check to see if the SDCard is busy, same as the music app
3188 if (status.equals(Environment.MEDIA_SHARED)) {
3189 msg = getString(R.string.download_sdcard_busy_dlg_msg);
3190 title = R.string.download_sdcard_busy_dlg_title;
3191 } else {
3192 msg = getString(R.string.download_no_sdcard_dlg_msg, filename);
3193 title = R.string.download_no_sdcard_dlg_title;
3194 }
3195
3196 new AlertDialog.Builder(this)
3197 .setTitle(title)
3198 .setIcon(android.R.drawable.ic_dialog_alert)
3199 .setMessage(msg)
3200 .setPositiveButton(R.string.ok, null)
3201 .show();
3202 return;
3203 }
3204
Kristian Monsenfa52d172010-03-25 18:29:21 +00003205 // java.net.URI is a lot stricter than KURL so we have to encode some
3206 // extra characters. Fix for b 2538060 and b 1634719
3207 WebAddress webAddress;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003208 try {
Kristian Monsenfa52d172010-03-25 18:29:21 +00003209 webAddress = new WebAddress(url);
3210 webAddress.mPath = encodePath(webAddress.mPath);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003211 } catch (Exception e) {
Kristian Monsenfa52d172010-03-25 18:29:21 +00003212 // This only happens for very bad urls, we want to chatch the
3213 // exception here
3214 Log.e(LOGTAG, "Exception trying to parse url:" + url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003215 return;
3216 }
3217
3218 // XXX: Have to use the old url since the cookies were stored using the
3219 // old percent-encoded url.
3220 String cookies = CookieManager.getInstance().getCookie(url);
3221
3222 ContentValues values = new ContentValues();
Kristian Monsenfa52d172010-03-25 18:29:21 +00003223 values.put(Downloads.Impl.COLUMN_URI, webAddress.toString());
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08003224 values.put(Downloads.Impl.COLUMN_COOKIE_DATA, cookies);
3225 values.put(Downloads.Impl.COLUMN_USER_AGENT, userAgent);
3226 values.put(Downloads.Impl.COLUMN_NOTIFICATION_PACKAGE,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003227 getPackageName());
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08003228 values.put(Downloads.Impl.COLUMN_NOTIFICATION_CLASS,
Leon Scrogginsa563d092010-04-19 16:53:49 -04003229 OpenDownloadReceiver.class.getCanonicalName());
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08003230 values.put(Downloads.Impl.COLUMN_VISIBILITY,
3231 Downloads.Impl.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
3232 values.put(Downloads.Impl.COLUMN_MIME_TYPE, mimetype);
3233 values.put(Downloads.Impl.COLUMN_FILE_NAME_HINT, filename);
Kristian Monsenfa52d172010-03-25 18:29:21 +00003234 values.put(Downloads.Impl.COLUMN_DESCRIPTION, webAddress.mHost);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003235 if (contentLength > 0) {
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08003236 values.put(Downloads.Impl.COLUMN_TOTAL_BYTES, contentLength);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003237 }
3238 if (mimetype == null) {
3239 // We must have long pressed on a link or image to download it. We
3240 // are not sure of the mimetype in this case, so do a head request
3241 new FetchUrlMimeType(this).execute(values);
3242 } else {
3243 final Uri contentUri =
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08003244 getContentResolver().insert(Downloads.Impl.CONTENT_URI, values);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003245 }
Leon Scroggins9191a7f2010-03-18 14:44:44 -04003246 Toast.makeText(this, R.string.download_pending, Toast.LENGTH_SHORT)
3247 .show();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003248 }
3249
Grace Kloba22ac16e2009-10-07 18:00:23 -07003250 // -------------------------------------------------------------------------
3251
The Android Open Source Project0c908882009-03-03 19:32:16 -08003252 /**
3253 * Resets the lock icon. This method is called when we start a new load and
3254 * know the url to be loaded.
3255 */
3256 private void resetLockIcon(String url) {
3257 // Save the lock-icon state (we revert to it if the load gets cancelled)
Grace Kloba22ac16e2009-10-07 18:00:23 -07003258 mTabControl.getCurrentTab().resetLockIcon(url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003259 updateLockIconImage(LOCK_ICON_UNSECURE);
3260 }
3261
The Android Open Source Project0c908882009-03-03 19:32:16 -08003262 /**
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04003263 * Update the lock icon to correspond to our latest state.
3264 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003265 private void updateLockIconToLatest() {
Leon Scroggins91f65fc2010-06-29 13:52:39 -04003266 Tab t = mTabControl.getCurrentTab();
3267 if (t != null) {
3268 updateLockIconImage(t.getLockIconType());
3269 }
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04003270 }
3271
3272 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08003273 * Updates the lock-icon image in the title-bar.
3274 */
3275 private void updateLockIconImage(int lockIconType) {
3276 Drawable d = null;
3277 if (lockIconType == LOCK_ICON_SECURE) {
3278 d = mSecLockIcon;
3279 } else if (lockIconType == LOCK_ICON_MIXED) {
3280 d = mMixLockIcon;
3281 }
Leon Scroggins68579392009-09-15 15:31:54 -04003282 mTitleBar.setLock(d);
Michael Kolba2b2ba82010-08-04 17:54:03 -07003283 mFakeTitleBar.setLock(d);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003284 }
3285
3286 /**
3287 * Displays a page-info dialog.
3288 * @param tab The tab to show info about
3289 * @param fromShowSSLCertificateOnError The flag that indicates whether
3290 * this dialog was opened from the SSL-certificate-on-error dialog or
3291 * not. This is important, since we need to know whether to return to
3292 * the parent dialog or simply dismiss.
3293 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003294 private void showPageInfo(final Tab tab,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003295 final boolean fromShowSSLCertificateOnError) {
3296 final LayoutInflater factory = LayoutInflater
3297 .from(this);
3298
3299 final View pageInfoView = factory.inflate(R.layout.page_info, null);
3300
3301 final WebView view = tab.getWebView();
3302
3303 String url = null;
3304 String title = null;
3305
3306 if (view == null) {
3307 url = tab.getUrl();
3308 title = tab.getTitle();
3309 } else if (view == mTabControl.getCurrentWebView()) {
3310 // Use the cached title and url if this is the current WebView
3311 url = mUrl;
3312 title = mTitle;
3313 } else {
3314 url = view.getUrl();
3315 title = view.getTitle();
3316 }
3317
3318 if (url == null) {
3319 url = "";
3320 }
3321 if (title == null) {
3322 title = "";
3323 }
3324
3325 ((TextView) pageInfoView.findViewById(R.id.address)).setText(url);
3326 ((TextView) pageInfoView.findViewById(R.id.title)).setText(title);
3327
3328 mPageInfoView = tab;
Leon Scrogginsc7b92f82010-01-11 18:17:31 -05003329 mPageInfoFromShowSSLCertificateOnError = fromShowSSLCertificateOnError;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003330
3331 AlertDialog.Builder alertDialogBuilder =
3332 new AlertDialog.Builder(this)
3333 .setTitle(R.string.page_info).setIcon(android.R.drawable.ic_dialog_info)
3334 .setView(pageInfoView)
3335 .setPositiveButton(
3336 R.string.ok,
3337 new DialogInterface.OnClickListener() {
3338 public void onClick(DialogInterface dialog,
3339 int whichButton) {
3340 mPageInfoDialog = null;
3341 mPageInfoView = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003342
3343 // if we came here from the SSL error dialog
3344 if (fromShowSSLCertificateOnError) {
3345 // go back to the SSL error dialog
3346 showSSLCertificateOnError(
3347 mSSLCertificateOnErrorView,
3348 mSSLCertificateOnErrorHandler,
3349 mSSLCertificateOnErrorError);
3350 }
3351 }
3352 })
3353 .setOnCancelListener(
3354 new DialogInterface.OnCancelListener() {
3355 public void onCancel(DialogInterface dialog) {
3356 mPageInfoDialog = null;
3357 mPageInfoView = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003358
3359 // if we came here from the SSL error dialog
3360 if (fromShowSSLCertificateOnError) {
3361 // go back to the SSL error dialog
3362 showSSLCertificateOnError(
3363 mSSLCertificateOnErrorView,
3364 mSSLCertificateOnErrorHandler,
3365 mSSLCertificateOnErrorError);
3366 }
3367 }
3368 });
3369
3370 // if we have a main top-level page SSL certificate set or a certificate
3371 // error
3372 if (fromShowSSLCertificateOnError ||
3373 (view != null && view.getCertificate() != null)) {
3374 // add a 'View Certificate' button
3375 alertDialogBuilder.setNeutralButton(
3376 R.string.view_certificate,
3377 new DialogInterface.OnClickListener() {
3378 public void onClick(DialogInterface dialog,
3379 int whichButton) {
3380 mPageInfoDialog = null;
3381 mPageInfoView = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003382
3383 // if we came here from the SSL error dialog
3384 if (fromShowSSLCertificateOnError) {
3385 // go back to the SSL error dialog
3386 showSSLCertificateOnError(
3387 mSSLCertificateOnErrorView,
3388 mSSLCertificateOnErrorHandler,
3389 mSSLCertificateOnErrorError);
3390 } else {
3391 // otherwise, display the top-most certificate from
3392 // the chain
3393 if (view.getCertificate() != null) {
3394 showSSLCertificate(tab);
3395 }
3396 }
3397 }
3398 });
3399 }
3400
3401 mPageInfoDialog = alertDialogBuilder.show();
3402 }
3403
3404 /**
3405 * Displays the main top-level page SSL certificate dialog
3406 * (accessible from the Page-Info dialog).
3407 * @param tab The tab to show certificate for.
3408 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003409 private void showSSLCertificate(final Tab tab) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003410 final View certificateView =
3411 inflateCertificateView(tab.getWebView().getCertificate());
3412 if (certificateView == null) {
3413 return;
3414 }
3415
3416 LayoutInflater factory = LayoutInflater.from(this);
3417
3418 final LinearLayout placeholder =
3419 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3420
3421 LinearLayout ll = (LinearLayout) factory.inflate(
3422 R.layout.ssl_success, placeholder);
3423 ((TextView)ll.findViewById(R.id.success))
3424 .setText(R.string.ssl_certificate_is_valid);
3425
3426 mSSLCertificateView = tab;
3427 mSSLCertificateDialog =
3428 new AlertDialog.Builder(this)
3429 .setTitle(R.string.ssl_certificate).setIcon(
3430 R.drawable.ic_dialog_browser_certificate_secure)
3431 .setView(certificateView)
3432 .setPositiveButton(R.string.ok,
3433 new DialogInterface.OnClickListener() {
3434 public void onClick(DialogInterface dialog,
3435 int whichButton) {
3436 mSSLCertificateDialog = null;
3437 mSSLCertificateView = null;
3438
3439 showPageInfo(tab, false);
3440 }
3441 })
3442 .setOnCancelListener(
3443 new DialogInterface.OnCancelListener() {
3444 public void onCancel(DialogInterface dialog) {
3445 mSSLCertificateDialog = null;
3446 mSSLCertificateView = null;
3447
3448 showPageInfo(tab, false);
3449 }
3450 })
3451 .show();
3452 }
3453
3454 /**
3455 * Displays the SSL error certificate dialog.
3456 * @param view The target web-view.
3457 * @param handler The SSL error handler responsible for cancelling the
3458 * connection that resulted in an SSL error or proceeding per user request.
3459 * @param error The SSL error object.
3460 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003461 void showSSLCertificateOnError(
The Android Open Source Project0c908882009-03-03 19:32:16 -08003462 final WebView view, final SslErrorHandler handler, final SslError error) {
3463
3464 final View certificateView =
3465 inflateCertificateView(error.getCertificate());
3466 if (certificateView == null) {
3467 return;
3468 }
3469
3470 LayoutInflater factory = LayoutInflater.from(this);
3471
3472 final LinearLayout placeholder =
3473 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3474
3475 if (error.hasError(SslError.SSL_UNTRUSTED)) {
3476 LinearLayout ll = (LinearLayout)factory
3477 .inflate(R.layout.ssl_warning, placeholder);
3478 ((TextView)ll.findViewById(R.id.warning))
3479 .setText(R.string.ssl_untrusted);
3480 }
3481
3482 if (error.hasError(SslError.SSL_IDMISMATCH)) {
3483 LinearLayout ll = (LinearLayout)factory
3484 .inflate(R.layout.ssl_warning, placeholder);
3485 ((TextView)ll.findViewById(R.id.warning))
3486 .setText(R.string.ssl_mismatch);
3487 }
3488
3489 if (error.hasError(SslError.SSL_EXPIRED)) {
3490 LinearLayout ll = (LinearLayout)factory
3491 .inflate(R.layout.ssl_warning, placeholder);
3492 ((TextView)ll.findViewById(R.id.warning))
3493 .setText(R.string.ssl_expired);
3494 }
3495
3496 if (error.hasError(SslError.SSL_NOTYETVALID)) {
3497 LinearLayout ll = (LinearLayout)factory
3498 .inflate(R.layout.ssl_warning, placeholder);
3499 ((TextView)ll.findViewById(R.id.warning))
3500 .setText(R.string.ssl_not_yet_valid);
3501 }
3502
3503 mSSLCertificateOnErrorHandler = handler;
3504 mSSLCertificateOnErrorView = view;
3505 mSSLCertificateOnErrorError = error;
3506 mSSLCertificateOnErrorDialog =
3507 new AlertDialog.Builder(this)
3508 .setTitle(R.string.ssl_certificate).setIcon(
3509 R.drawable.ic_dialog_browser_certificate_partially_secure)
3510 .setView(certificateView)
3511 .setPositiveButton(R.string.ok,
3512 new DialogInterface.OnClickListener() {
3513 public void onClick(DialogInterface dialog,
3514 int whichButton) {
3515 mSSLCertificateOnErrorDialog = null;
3516 mSSLCertificateOnErrorView = null;
3517 mSSLCertificateOnErrorHandler = null;
3518 mSSLCertificateOnErrorError = null;
3519
Grace Kloba22ac16e2009-10-07 18:00:23 -07003520 view.getWebViewClient().onReceivedSslError(
3521 view, handler, error);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003522 }
3523 })
3524 .setNeutralButton(R.string.page_info_view,
3525 new DialogInterface.OnClickListener() {
3526 public void onClick(DialogInterface dialog,
3527 int whichButton) {
3528 mSSLCertificateOnErrorDialog = null;
3529
3530 // do not clear the dialog state: we will
3531 // need to show the dialog again once the
3532 // user is done exploring the page-info details
3533
3534 showPageInfo(mTabControl.getTabFromView(view),
3535 true);
3536 }
3537 })
3538 .setOnCancelListener(
3539 new DialogInterface.OnCancelListener() {
3540 public void onCancel(DialogInterface dialog) {
3541 mSSLCertificateOnErrorDialog = null;
3542 mSSLCertificateOnErrorView = null;
3543 mSSLCertificateOnErrorHandler = null;
3544 mSSLCertificateOnErrorError = null;
3545
Grace Kloba22ac16e2009-10-07 18:00:23 -07003546 view.getWebViewClient().onReceivedSslError(
3547 view, handler, error);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003548 }
3549 })
3550 .show();
3551 }
3552
3553 /**
3554 * Inflates the SSL certificate view (helper method).
3555 * @param certificate The SSL certificate.
3556 * @return The resultant certificate view with issued-to, issued-by,
3557 * issued-on, expires-on, and possibly other fields set.
3558 * If the input certificate is null, returns null.
3559 */
3560 private View inflateCertificateView(SslCertificate certificate) {
3561 if (certificate == null) {
3562 return null;
3563 }
3564
3565 LayoutInflater factory = LayoutInflater.from(this);
3566
3567 View certificateView = factory.inflate(
3568 R.layout.ssl_certificate, null);
3569
3570 // issued to:
3571 SslCertificate.DName issuedTo = certificate.getIssuedTo();
3572 if (issuedTo != null) {
3573 ((TextView) certificateView.findViewById(R.id.to_common))
3574 .setText(issuedTo.getCName());
3575 ((TextView) certificateView.findViewById(R.id.to_org))
3576 .setText(issuedTo.getOName());
3577 ((TextView) certificateView.findViewById(R.id.to_org_unit))
3578 .setText(issuedTo.getUName());
3579 }
3580
3581 // issued by:
3582 SslCertificate.DName issuedBy = certificate.getIssuedBy();
3583 if (issuedBy != null) {
3584 ((TextView) certificateView.findViewById(R.id.by_common))
3585 .setText(issuedBy.getCName());
3586 ((TextView) certificateView.findViewById(R.id.by_org))
3587 .setText(issuedBy.getOName());
3588 ((TextView) certificateView.findViewById(R.id.by_org_unit))
3589 .setText(issuedBy.getUName());
3590 }
3591
3592 // issued on:
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003593 String issuedOn = formatCertificateDate(
3594 certificate.getValidNotBeforeDate());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003595 ((TextView) certificateView.findViewById(R.id.issued_on))
3596 .setText(issuedOn);
3597
3598 // expires on:
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003599 String expiresOn = formatCertificateDate(
3600 certificate.getValidNotAfterDate());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003601 ((TextView) certificateView.findViewById(R.id.expires_on))
3602 .setText(expiresOn);
3603
3604 return certificateView;
3605 }
3606
3607 /**
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003608 * Formats the certificate date to a properly localized date string.
The Android Open Source Project0c908882009-03-03 19:32:16 -08003609 * @return Properly localized version of the certificate date string and
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003610 * the "" if it fails to localize.
The Android Open Source Project0c908882009-03-03 19:32:16 -08003611 */
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003612 private String formatCertificateDate(Date certificateDate) {
3613 if (certificateDate == null) {
3614 return "";
The Android Open Source Project0c908882009-03-03 19:32:16 -08003615 }
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003616 String formattedDate = DateFormat.getDateFormat(this).format(certificateDate);
3617 if (formattedDate == null) {
3618 return "";
3619 }
3620 return formattedDate;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003621 }
3622
3623 /**
3624 * Displays an http-authentication dialog.
3625 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003626 void showHttpAuthentication(final HttpAuthHandler handler,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003627 final String host, final String realm, final String title,
3628 final String name, final String password, int focusId) {
3629 LayoutInflater factory = LayoutInflater.from(this);
3630 final View v = factory
3631 .inflate(R.layout.http_authentication, null);
3632 if (name != null) {
3633 ((EditText) v.findViewById(R.id.username_edit)).setText(name);
3634 }
3635 if (password != null) {
3636 ((EditText) v.findViewById(R.id.password_edit)).setText(password);
3637 }
3638
3639 String titleText = title;
3640 if (titleText == null) {
3641 titleText = getText(R.string.sign_in_to).toString().replace(
3642 "%s1", host).replace("%s2", realm);
3643 }
3644
3645 mHttpAuthHandler = handler;
3646 AlertDialog dialog = new AlertDialog.Builder(this)
3647 .setTitle(titleText)
3648 .setIcon(android.R.drawable.ic_dialog_alert)
3649 .setView(v)
3650 .setPositiveButton(R.string.action,
3651 new DialogInterface.OnClickListener() {
3652 public void onClick(DialogInterface dialog,
3653 int whichButton) {
3654 String nm = ((EditText) v
3655 .findViewById(R.id.username_edit))
3656 .getText().toString();
3657 String pw = ((EditText) v
3658 .findViewById(R.id.password_edit))
3659 .getText().toString();
3660 BrowserActivity.this.setHttpAuthUsernamePassword
3661 (host, realm, nm, pw);
3662 handler.proceed(nm, pw);
3663 mHttpAuthenticationDialog = null;
3664 mHttpAuthHandler = null;
3665 }})
3666 .setNegativeButton(R.string.cancel,
3667 new DialogInterface.OnClickListener() {
3668 public void onClick(DialogInterface dialog,
3669 int whichButton) {
3670 handler.cancel();
3671 BrowserActivity.this.resetTitleAndRevertLockIcon();
3672 mHttpAuthenticationDialog = null;
3673 mHttpAuthHandler = null;
3674 }})
3675 .setOnCancelListener(new DialogInterface.OnCancelListener() {
3676 public void onCancel(DialogInterface dialog) {
3677 handler.cancel();
3678 BrowserActivity.this.resetTitleAndRevertLockIcon();
3679 mHttpAuthenticationDialog = null;
3680 mHttpAuthHandler = null;
3681 }})
3682 .create();
3683 // Make the IME appear when the dialog is displayed if applicable.
3684 dialog.getWindow().setSoftInputMode(
3685 WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
3686 dialog.show();
3687 if (focusId != 0) {
3688 dialog.findViewById(focusId).requestFocus();
3689 } else {
3690 v.findViewById(R.id.username_edit).requestFocus();
3691 }
3692 mHttpAuthenticationDialog = dialog;
3693 }
3694
3695 public int getProgress() {
3696 WebView w = mTabControl.getCurrentWebView();
3697 if (w != null) {
3698 return w.getProgress();
3699 } else {
3700 return 100;
3701 }
3702 }
3703
3704 /**
3705 * Set HTTP authentication password.
3706 *
3707 * @param host The host for the password
3708 * @param realm The realm for the password
3709 * @param username The username for the password. If it is null, it means
3710 * password can't be saved.
3711 * @param password The password
3712 */
3713 public void setHttpAuthUsernamePassword(String host, String realm,
3714 String username,
3715 String password) {
Steve Block95a53b22010-03-25 17:24:58 +00003716 WebView w = getTopWindow();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003717 if (w != null) {
3718 w.setHttpAuthUsernamePassword(host, realm, username, password);
3719 }
3720 }
3721
3722 /**
3723 * connectivity manager says net has come or gone... inform the user
3724 * @param up true if net has come up, false if net has gone down
3725 */
3726 public void onNetworkToggle(boolean up) {
3727 if (up == mIsNetworkUp) {
3728 return;
3729 } else if (up) {
3730 mIsNetworkUp = true;
3731 if (mAlertDialog != null) {
3732 mAlertDialog.cancel();
3733 mAlertDialog = null;
3734 }
3735 } else {
3736 mIsNetworkUp = false;
Patrick Scotteb6ab2a2009-09-16 10:00:17 -04003737 if (mInLoad) {
3738 createAndShowNetworkDialog();
3739 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003740 }
3741 WebView w = mTabControl.getCurrentWebView();
3742 if (w != null) {
3743 w.setNetworkAvailable(up);
3744 }
3745 }
3746
Grace Kloba22ac16e2009-10-07 18:00:23 -07003747 boolean isNetworkUp() {
3748 return mIsNetworkUp;
3749 }
3750
Patrick Scotteb6ab2a2009-09-16 10:00:17 -04003751 // This method shows the network dialog alerting the user that the net is
3752 // down. It will only show the dialog if mAlertDialog is null.
3753 private void createAndShowNetworkDialog() {
3754 if (mAlertDialog == null) {
3755 mAlertDialog = new AlertDialog.Builder(this)
3756 .setTitle(R.string.loadSuspendedTitle)
3757 .setMessage(R.string.loadSuspended)
3758 .setPositiveButton(R.string.ok, null)
3759 .show();
3760 }
3761 }
3762
The Android Open Source Project0c908882009-03-03 19:32:16 -08003763 @Override
3764 protected void onActivityResult(int requestCode, int resultCode,
3765 Intent intent) {
Grace Klobabb394f32009-11-19 10:26:37 -08003766 if (getTopWindow() == null) return;
3767
The Android Open Source Project0c908882009-03-03 19:32:16 -08003768 switch (requestCode) {
3769 case COMBO_PAGE:
3770 if (resultCode == RESULT_OK && intent != null) {
3771 String data = intent.getAction();
3772 Bundle extras = intent.getExtras();
3773 if (extras != null && extras.getBoolean("new_window", false)) {
Michael Kolb68792c82010-08-09 16:39:18 -07003774 openTab(data, false);
3775 } else if ((extras != null) &&
3776 extras.getBoolean(CombinedBookmarkHistoryActivity.NEWTAB_MODE)) {
3777 openTab(data, true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003778 } else {
Michael Kolb68792c82010-08-09 16:39:18 -07003779 final Tab currentTab = mTabControl.getCurrentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04003780 dismissSubWindow(currentTab);
3781 if (data != null && data.length() != 0) {
Leon Scroggins92472e82010-02-17 16:32:28 -05003782 loadUrl(getTopWindow(), data);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003783 }
3784 }
3785 }
Leon Scrogginsfde97462010-01-11 13:06:21 -05003786 // Deliberately fall through to PREFERENCES_PAGE, since the
3787 // same extra may be attached to the COMBO_PAGE
3788 case PREFERENCES_PAGE:
3789 if (resultCode == RESULT_OK && intent != null) {
3790 String action = intent.getStringExtra(Intent.EXTRA_TEXT);
3791 if (BrowserSettings.PREF_CLEAR_HISTORY.equals(action)) {
3792 mTabControl.removeParentChildRelationShips();
3793 }
3794 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003795 break;
Leon Scroggins8d5fa432009-10-02 15:55:59 -04003796 // Choose a file from the file picker.
3797 case FILE_SELECTED:
3798 if (null == mUploadMessage) break;
3799 Uri result = intent == null || resultCode != RESULT_OK ? null
3800 : intent.getData();
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003801
3802 // As we ask the camera to save the result of the user taking
3803 // a picture, the camera application does not return anything other
3804 // than RESULT_OK. So we need to check whether the file we expected
3805 // was written to disk in the in the case that we
3806 // did not get an intent returned but did get a RESULT_OK. If it was,
3807 // we assume that this result has came back from the camera.
3808 if (result == null && intent == null && resultCode == RESULT_OK) {
3809 File cameraFile = new File(mCameraFilePath);
3810 if (cameraFile.exists()) {
3811 result = Uri.fromFile(cameraFile);
Ben Murdoch07d34732010-05-27 18:34:46 +01003812 // Broadcast to the media scanner that we have a new photo
3813 // so it will be added into the gallery for the user.
3814 sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, result));
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003815 }
3816 }
Leon Scroggins8d5fa432009-10-02 15:55:59 -04003817 mUploadMessage.onReceiveValue(result);
3818 mUploadMessage = null;
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003819 mCameraFilePath = null;
Leon Scroggins8d5fa432009-10-02 15:55:59 -04003820 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003821 default:
3822 break;
3823 }
Leon Scroggins30444232009-09-04 18:36:20 -04003824 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003825 }
3826
3827 /*
3828 * This method is called as a result of the user selecting the options
Leon Scrogginsf08809b2010-01-21 09:27:46 -05003829 * menu to see the download window. It shows the download window on top of
3830 * the current window.
The Android Open Source Project0c908882009-03-03 19:32:16 -08003831 */
Leon Scrogginsf08809b2010-01-21 09:27:46 -05003832 private void viewDownloads(Uri downloadRecord) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003833 Intent intent = new Intent(this,
3834 BrowserDownloadPage.class);
3835 intent.setData(downloadRecord);
Grace Kloba22ac16e2009-10-07 18:00:23 -07003836 startActivityForResult(intent, BrowserActivity.DOWNLOAD_PAGE);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003837
3838 }
3839
Ben Murdocheecb4e62010-07-06 16:30:38 +01003840 /* package*/ void promptAddOrInstallBookmark() {
3841 final Tab current = mTabControl.getCurrentTab();
3842 Resources resources = getResources();
3843 CharSequence[] choices = {
3844 resources.getString(R.string.save_to_bookmarks),
3845 resources.getString(R.string.create_shortcut_bookmark)
3846 };
3847
3848 AlertDialog.Builder builder = new AlertDialog.Builder(this);
3849 builder.setTitle(R.string.add_new_bookmark);
3850 builder.setItems(choices, new DialogInterface.OnClickListener() {
3851 public void onClick(DialogInterface dialog, int item) {
3852 if (item == 0) {
3853 bookmarkCurrentPage();
3854 } else if (item == 1) {
3855 current.populatePickerData();
3856 String touchIconUrl = mTabControl.getCurrentWebView().getTouchIconUrl();
3857 if (touchIconUrl != null) {
3858 // Download the touch icon for this site then save it to the
3859 // homescreen.
3860 Bundle b = new Bundle();
3861 b.putString("url", current.getUrl());
3862 b.putString("title", current.getTitle());
3863 b.putParcelable("favicon", current.getFavicon());
3864 Message msg = mHandler.obtainMessage(TOUCH_ICON_DOWNLOADED);
3865 msg.setData(b);
Ben Murdochccb5de02010-07-19 18:38:17 +01003866 new DownloadTouchIcon(BrowserActivity.this, msg,
Ben Murdocheecb4e62010-07-06 16:30:38 +01003867 mTabControl.getCurrentWebView().getSettings()
3868 .getUserAgentString()).execute(touchIconUrl);
3869 } else {
3870 // add to homescreen, can do it immediately as there is no touch
3871 // icon.
3872 showSaveToHomescreenDialog(current.getUrl(), current.getTitle(),
3873 null, current.getFavicon());
3874 }
3875 }
3876 }
3877 });
3878 builder.create().show();
3879 }
3880
Leon Scroggins160a7e72009-08-14 18:28:01 -04003881 /**
3882 * Open the Go page.
3883 * @param startWithHistory If true, open starting on the history tab.
3884 * Otherwise, start with the bookmarks tab.
Leon Scroggins160a7e72009-08-14 18:28:01 -04003885 */
Michael Kolb68792c82010-08-09 16:39:18 -07003886 /* package */ void bookmarksOrHistoryPicker(boolean startWithHistory, boolean newTabMode) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003887 WebView current = mTabControl.getCurrentWebView();
3888 if (current == null) {
3889 return;
3890 }
3891 Intent intent = new Intent(this,
3892 CombinedBookmarkHistoryActivity.class);
3893 String title = current.getTitle();
3894 String url = current.getUrl();
Ben Murdoch87cc65d2010-06-29 20:34:10 +01003895 Bitmap thumbnail = createScreenshot(current, getDesiredThumbnailWidth(this),
3896 getDesiredThumbnailHeight(this));
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01003897
The Android Open Source Project0c908882009-03-03 19:32:16 -08003898 // Just in case the user opens bookmarks before a page finishes loading
3899 // so the current history item, and therefore the page, is null.
3900 if (null == url) {
3901 url = mLastEnteredUrl;
3902 // This can happen.
3903 if (null == url) {
3904 url = mSettings.getHomePage();
3905 }
3906 }
3907 // In case the web page has not yet received its associated title.
3908 if (title == null) {
3909 title = url;
3910 }
3911 intent.putExtra("title", title);
3912 intent.putExtra("url", url);
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01003913 intent.putExtra("thumbnail", thumbnail);
Leon Scroggins30444232009-09-04 18:36:20 -04003914 // Disable opening in a new window if we have maxed out the windows
Grace Kloba22ac16e2009-10-07 18:00:23 -07003915 intent.putExtra("disable_new_window", !mTabControl.canCreateNewTab());
Patrick Scott3918d442009-08-04 13:22:29 -04003916 intent.putExtra("touch_icon_url", current.getTouchIconUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003917 if (startWithHistory) {
3918 intent.putExtra(CombinedBookmarkHistoryActivity.STARTING_TAB,
3919 CombinedBookmarkHistoryActivity.HISTORY_TAB);
3920 }
Michael Kolb68792c82010-08-09 16:39:18 -07003921 if (newTabMode) {
3922 intent.putExtra(CombinedBookmarkHistoryActivity.NEWTAB_MODE, true);
3923 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003924 startActivityForResult(intent, COMBO_PAGE);
3925 }
3926
Ben Murdocheecb4e62010-07-06 16:30:38 +01003927 private void showSaveToHomescreenDialog(String url, String title, Bitmap touchIcon,
3928 Bitmap favicon) {
3929 Intent intent = new Intent(this, SaveToHomescreenDialog.class);
3930
3931 // Just in case the user tries to save before a page finishes loading
3932 // so the current history item, and therefore the page, is null.
3933 if (null == url) {
3934 url = mLastEnteredUrl;
3935 // This can happen.
3936 if (null == url) {
3937 url = mSettings.getHomePage();
3938 }
3939 }
3940
3941 // In case the web page has not yet received its associated title.
3942 if (title == null) {
3943 title = url;
3944 }
3945
3946 intent.putExtra("title", title);
3947 intent.putExtra("url", url);
3948 intent.putExtra("favicon", favicon);
3949 intent.putExtra("touchIcon", touchIcon);
3950 startActivity(intent);
3951 }
3952
3953
The Android Open Source Project0c908882009-03-03 19:32:16 -08003954 // Called when loading from context menu or LOAD_URL message
Leon Scroggins92472e82010-02-17 16:32:28 -05003955 private void loadUrlFromContext(WebView view, String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003956 // In case the user enters nothing.
3957 if (url != null && url.length() != 0 && view != null) {
3958 url = smartUrlFilter(url);
Grace Kloba22ac16e2009-10-07 18:00:23 -07003959 if (!view.getWebViewClient().shouldOverrideUrlLoading(view, url)) {
Leon Scroggins92472e82010-02-17 16:32:28 -05003960 loadUrl(view, url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003961 }
3962 }
3963 }
3964
Leon Scroggins92472e82010-02-17 16:32:28 -05003965 /**
3966 * Load the URL into the given WebView and update the title bar
3967 * to reflect the new load. Call this instead of WebView.loadUrl
3968 * directly.
3969 * @param view The WebView used to load url.
3970 * @param url The URL to load.
3971 */
3972 private void loadUrl(WebView view, String url) {
3973 updateTitleBarForNewLoad(view, url);
3974 view.loadUrl(url);
3975 }
3976
3977 /**
3978 * Load UrlData into a Tab and update the title bar to reflect the new
3979 * load. Call this instead of UrlData.loadIn directly.
3980 * @param t The Tab used to load.
3981 * @param data The UrlData being loaded.
3982 */
3983 private void loadUrlDataIn(Tab t, UrlData data) {
3984 updateTitleBarForNewLoad(t.getWebView(), data.mUrl);
3985 data.loadIn(t);
3986 }
3987
3988 /**
3989 * If the WebView is the top window, update the title bar to reflect
3990 * loading the new URL. i.e. set its text, clear the favicon (which
3991 * will be set once the page begins loading), and set the progress to
3992 * INITIAL_PROGRESS to show that the page has begun to load. Called
3993 * by loadUrl and loadUrlDataIn.
3994 * @param view The WebView that is starting a load.
3995 * @param url The URL that is being loaded.
3996 */
3997 private void updateTitleBarForNewLoad(WebView view, String url) {
3998 if (view == getTopWindow()) {
3999 setUrlTitle(url, null);
4000 setFavicon(null);
4001 onProgressChanged(view, INITIAL_PROGRESS);
4002 }
4003 }
4004
The Android Open Source Project0c908882009-03-03 19:32:16 -08004005 private String smartUrlFilter(Uri inUri) {
4006 if (inUri != null) {
4007 return smartUrlFilter(inUri.toString());
4008 }
4009 return null;
4010 }
4011
Feng Qianb34f87a2009-03-24 21:27:26 -07004012 protected static final Pattern ACCEPTED_URI_SCHEMA = Pattern.compile(
The Android Open Source Project0c908882009-03-03 19:32:16 -08004013 "(?i)" + // switch on case insensitive matching
4014 "(" + // begin group for schema
4015 "(?:http|https|file):\\/\\/" +
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004016 "|(?:inline|data|about|content|javascript):" +
The Android Open Source Project0c908882009-03-03 19:32:16 -08004017 ")" +
4018 "(.*)" );
4019
4020 /**
4021 * Attempts to determine whether user input is a URL or search
4022 * terms. Anything with a space is passed to search.
4023 *
4024 * Converts to lowercase any mistakenly uppercased schema (i.e.,
4025 * "Http://" converts to "http://"
4026 *
4027 * @return Original or modified URL
4028 *
4029 */
4030 String smartUrlFilter(String url) {
4031
4032 String inUrl = url.trim();
4033 boolean hasSpace = inUrl.indexOf(' ') != -1;
4034
4035 Matcher matcher = ACCEPTED_URI_SCHEMA.matcher(inUrl);
4036 if (matcher.matches()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08004037 // force scheme to lowercase
4038 String scheme = matcher.group(1);
4039 String lcScheme = scheme.toLowerCase();
4040 if (!lcScheme.equals(scheme)) {
Mitsuru Oshima123ecfb2009-05-18 19:11:14 -07004041 inUrl = lcScheme + matcher.group(2);
4042 }
4043 if (hasSpace) {
4044 inUrl = inUrl.replace(" ", "%20");
The Android Open Source Project0c908882009-03-03 19:32:16 -08004045 }
4046 return inUrl;
4047 }
4048 if (hasSpace) {
Satish Sampath565505b2009-05-29 15:37:27 +01004049 // FIXME: Is this the correct place to add to searches?
4050 // what if someone else calls this function?
4051 int shortcut = parseUrlShortcut(inUrl);
4052 if (shortcut != SHORTCUT_INVALID) {
4053 Browser.addSearchUrl(mResolver, inUrl);
4054 String query = inUrl.substring(2);
4055 switch (shortcut) {
4056 case SHORTCUT_GOOGLE_SEARCH:
Grace Kloba47fdfdb2009-06-30 11:15:34 -07004057 return URLUtil.composeSearchUrl(query, QuickSearch_G, QUERY_PLACE_HOLDER);
Satish Sampath565505b2009-05-29 15:37:27 +01004058 case SHORTCUT_WIKIPEDIA_SEARCH:
4059 return URLUtil.composeSearchUrl(query, QuickSearch_W, QUERY_PLACE_HOLDER);
4060 case SHORTCUT_DICTIONARY_SEARCH:
4061 return URLUtil.composeSearchUrl(query, QuickSearch_D, QUERY_PLACE_HOLDER);
4062 case SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH:
The Android Open Source Project0c908882009-03-03 19:32:16 -08004063 // FIXME: we need location in this case
Satish Sampath565505b2009-05-29 15:37:27 +01004064 return URLUtil.composeSearchUrl(query, QuickSearch_L, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004065 }
4066 }
4067 } else {
Dan Egnor5ee906c2009-11-18 12:11:49 -08004068 if (Patterns.WEB_URL.matcher(inUrl).matches()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08004069 return URLUtil.guessUrl(inUrl);
4070 }
4071 }
4072
4073 Browser.addSearchUrl(mResolver, inUrl);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07004074 return URLUtil.composeSearchUrl(inUrl, QuickSearch_G, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004075 }
4076
Ben Murdochbff2d602009-07-01 20:19:05 +01004077 /* package */ void setShouldShowErrorConsole(boolean flag) {
4078 if (flag == mShouldShowErrorConsole) {
4079 // Nothing to do.
4080 return;
4081 }
4082
4083 mShouldShowErrorConsole = flag;
4084
Grace Kloba22ac16e2009-10-07 18:00:23 -07004085 ErrorConsoleView errorConsole = mTabControl.getCurrentTab()
4086 .getErrorConsole(true);
Ben Murdochbff2d602009-07-01 20:19:05 +01004087
4088 if (flag) {
4089 // Setting the show state of the console will cause it's the layout to be inflated.
4090 if (errorConsole.numberOfErrors() > 0) {
4091 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
4092 } else {
4093 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
4094 }
4095
4096 // Now we can add it to the main view.
4097 mErrorConsoleContainer.addView(errorConsole,
Romain Guy15b8ec62010-01-08 15:06:43 -08004098 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
Ben Murdochbff2d602009-07-01 20:19:05 +01004099 ViewGroup.LayoutParams.WRAP_CONTENT));
4100 } else {
4101 mErrorConsoleContainer.removeView(errorConsole);
4102 }
4103
4104 }
4105
Grace Kloba22ac16e2009-10-07 18:00:23 -07004106 boolean shouldShowErrorConsole() {
4107 return mShouldShowErrorConsole;
4108 }
4109
Andrei Popescu163ab742009-10-20 17:58:23 +01004110 private void setStatusBarVisibility(boolean visible) {
4111 int flag = visible ? 0 : WindowManager.LayoutParams.FLAG_FULLSCREEN;
4112 getWindow().setFlags(flag, WindowManager.LayoutParams.FLAG_FULLSCREEN);
4113 }
4114
Andrei Popescu56199cc2010-01-12 22:39:16 +00004115
4116 private void sendNetworkType(String type, String subtype) {
4117 WebView w = mTabControl.getCurrentWebView();
4118 if (w != null) {
4119 w.setNetworkType(type, subtype);
4120 }
4121 }
4122
Andrei Popescu30995e72010-02-09 16:59:58 +00004123 private void packageChanged(String packageName, boolean wasAdded) {
4124 WebView w = mTabControl.getCurrentWebView();
4125 if (w == null) {
4126 return;
4127 }
4128
4129 if (wasAdded) {
4130 w.addPackageName(packageName);
4131 } else {
4132 w.removePackageName(packageName);
4133 }
4134 }
4135
4136 private void addPackageNames(Set<String> packageNames) {
4137 WebView w = mTabControl.getCurrentWebView();
4138 if (w == null) {
4139 return;
4140 }
4141
4142 w.addPackageNames(packageNames);
4143 }
4144
4145 private void getInstalledPackages() {
4146 AsyncTask<Void, Void, Set<String> > task =
4147 new AsyncTask<Void, Void, Set<String> >() {
Michael Kolbe0a36662010-06-29 10:37:12 -07004148 @Override
Andrei Popescu30995e72010-02-09 16:59:58 +00004149 protected Set<String> doInBackground(Void... unused) {
4150 Set<String> installedPackages = new HashSet<String>();
4151 PackageManager pm = BrowserActivity.this.getPackageManager();
4152 if (pm != null) {
4153 List<PackageInfo> packages = pm.getInstalledPackages(0);
4154 for (PackageInfo p : packages) {
4155 if (BrowserActivity.this.sGoogleApps.contains(p.packageName)) {
4156 installedPackages.add(p.packageName);
4157 }
4158 }
4159 }
4160
4161 return installedPackages;
4162 }
4163
4164 // Executes on the UI thread
Michael Kolbe0a36662010-06-29 10:37:12 -07004165 @Override
Andrei Popescu30995e72010-02-09 16:59:58 +00004166 protected void onPostExecute(Set<String> installedPackages) {
4167 addPackageNames(installedPackages);
4168 }
4169 };
4170 task.execute();
4171 }
4172
Grace Klobaeb6eef42009-09-15 17:56:32 -07004173 final static int LOCK_ICON_UNSECURE = 0;
4174 final static int LOCK_ICON_SECURE = 1;
4175 final static int LOCK_ICON_MIXED = 2;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004176
The Android Open Source Project0c908882009-03-03 19:32:16 -08004177 private BrowserSettings mSettings;
4178 private TabControl mTabControl;
4179 private ContentResolver mResolver;
4180 private FrameLayout mContentView;
Andrei Popescuadc008d2009-06-26 14:11:30 +01004181 private View mCustomView;
4182 private FrameLayout mCustomViewContainer;
Andrei Popescuc9b55562009-07-07 10:51:15 +01004183 private WebChromeClient.CustomViewCallback mCustomViewCallback;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004184
4185 // FIXME, temp address onPrepareMenu performance problem. When we move everything out of
4186 // view, we should rewrite this.
4187 private int mCurrentMenuState = 0;
4188 private int mMenuState = R.id.MAIN_MENU;
Andrei Popescuadc008d2009-06-26 14:11:30 +01004189 private int mOldMenuState = EMPTY_MENU;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004190 private static final int EMPTY_MENU = -1;
4191 private Menu mMenu;
4192
The Android Open Source Project0c908882009-03-03 19:32:16 -08004193 // Used to prevent chording to result in firing two shortcuts immediately
4194 // one after another. Fixes bug 1211714.
4195 boolean mCanChord;
4196
4197 private boolean mInLoad;
4198 private boolean mIsNetworkUp;
Ben Murdochb7cc8b42009-09-28 10:59:09 +01004199 private boolean mDidStopLoad;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004200
Cary Clark1f10cbf2010-03-22 11:45:23 -04004201 /* package */ boolean mActivityInPause = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004202
4203 private boolean mMenuIsDown;
4204
The Android Open Source Project0c908882009-03-03 19:32:16 -08004205 private static boolean mInTrace;
4206
4207 // Performance probe
4208 private static final int[] SYSTEM_CPU_FORMAT = new int[] {
4209 Process.PROC_SPACE_TERM | Process.PROC_COMBINE,
4210 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 1: user time
4211 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 2: nice time
4212 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 3: sys time
4213 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 4: idle time
4214 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 5: iowait time
4215 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 6: irq time
4216 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG // 7: softirq time
4217 };
4218
4219 private long mStart;
4220 private long mProcessStart;
4221 private long mUserStart;
4222 private long mSystemStart;
4223 private long mIdleStart;
4224 private long mIrqStart;
4225
4226 private long mUiStart;
4227
4228 private Drawable mMixLockIcon;
4229 private Drawable mSecLockIcon;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004230
4231 /* hold a ref so we can auto-cancel if necessary */
4232 private AlertDialog mAlertDialog;
4233
The Android Open Source Project0c908882009-03-03 19:32:16 -08004234 // The up-to-date URL and title (these can be different from those stored
4235 // in WebView, since it takes some time for the information in WebView to
4236 // get updated)
4237 private String mUrl;
4238 private String mTitle;
4239
4240 // As PageInfo has different style for landscape / portrait, we have
4241 // to re-open it when configuration changed
4242 private AlertDialog mPageInfoDialog;
Grace Kloba22ac16e2009-10-07 18:00:23 -07004243 private Tab mPageInfoView;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004244 // If the Page-Info dialog is launched from the SSL-certificate-on-error
4245 // dialog, we should not just dismiss it, but should get back to the
4246 // SSL-certificate-on-error dialog. This flag is used to store this state
Leon Scrogginsc7b92f82010-01-11 18:17:31 -05004247 private boolean mPageInfoFromShowSSLCertificateOnError;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004248
4249 // as SSLCertificateOnError has different style for landscape / portrait,
4250 // we have to re-open it when configuration changed
4251 private AlertDialog mSSLCertificateOnErrorDialog;
4252 private WebView mSSLCertificateOnErrorView;
4253 private SslErrorHandler mSSLCertificateOnErrorHandler;
4254 private SslError mSSLCertificateOnErrorError;
4255
4256 // as SSLCertificate has different style for landscape / portrait, we
4257 // have to re-open it when configuration changed
4258 private AlertDialog mSSLCertificateDialog;
Grace Kloba22ac16e2009-10-07 18:00:23 -07004259 private Tab mSSLCertificateView;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004260
4261 // as HttpAuthentication has different style for landscape / portrait, we
4262 // have to re-open it when configuration changed
4263 private AlertDialog mHttpAuthenticationDialog;
4264 private HttpAuthHandler mHttpAuthHandler;
4265
4266 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_PARAMS =
4267 new FrameLayout.LayoutParams(
Romain Guy15b8ec62010-01-08 15:06:43 -08004268 ViewGroup.LayoutParams.MATCH_PARENT,
4269 ViewGroup.LayoutParams.MATCH_PARENT);
Andrei Popescuadc008d2009-06-26 14:11:30 +01004270 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_GRAVITY_CENTER =
4271 new FrameLayout.LayoutParams(
Romain Guy15b8ec62010-01-08 15:06:43 -08004272 ViewGroup.LayoutParams.MATCH_PARENT,
4273 ViewGroup.LayoutParams.MATCH_PARENT,
Andrei Popescuadc008d2009-06-26 14:11:30 +01004274 Gravity.CENTER);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07004275 // Google search
4276 final static String QuickSearch_G = "http://www.google.com/m?q=%s";
The Android Open Source Project0c908882009-03-03 19:32:16 -08004277 // Wikipedia search
4278 final static String QuickSearch_W = "http://en.wikipedia.org/w/index.php?search=%s&go=Go";
4279 // Dictionary search
4280 final static String QuickSearch_D = "http://dictionary.reference.com/search?q=%s";
4281 // Google Mobile Local search
4282 final static String QuickSearch_L = "http://www.google.com/m/search?site=local&q=%s&near=mountain+view";
4283
4284 final static String QUERY_PLACE_HOLDER = "%s";
4285
4286 // "source" parameter for Google search through search key
4287 final static String GOOGLE_SEARCH_SOURCE_SEARCHKEY = "browser-key";
4288 // "source" parameter for Google search through goto menu
4289 final static String GOOGLE_SEARCH_SOURCE_GOTO = "browser-goto";
4290 // "source" parameter for Google search through simplily type
4291 final static String GOOGLE_SEARCH_SOURCE_TYPE = "browser-type";
4292 // "source" parameter for Google search suggested by the browser
4293 final static String GOOGLE_SEARCH_SOURCE_SUGGEST = "browser-suggest";
4294 // "source" parameter for Google search from unknown source
4295 final static String GOOGLE_SEARCH_SOURCE_UNKNOWN = "unknown";
4296
4297 private final static String LOGTAG = "browser";
4298
The Android Open Source Project0c908882009-03-03 19:32:16 -08004299 private String mLastEnteredUrl;
4300
4301 private PowerManager.WakeLock mWakeLock;
4302 private final static int WAKELOCK_TIMEOUT = 5 * 60 * 1000; // 5 minutes
4303
4304 private Toast mStopToast;
4305
Leon Scroggins571b3762010-05-26 10:25:01 -04004306 private TitleBarBase mTitleBar;
Michael Kolba2b2ba82010-08-04 17:54:03 -07004307 private TabBar mTabBar;
Leon Scroggins81db3662009-06-04 17:45:11 -04004308
Ben Murdochbff2d602009-07-01 20:19:05 +01004309 private LinearLayout mErrorConsoleContainer = null;
4310 private boolean mShouldShowErrorConsole = false;
4311
The Android Open Source Project0c908882009-03-03 19:32:16 -08004312 // As the ids are dynamically created, we can't guarantee that they will
4313 // be in sequence, so this static array maps ids to a window number.
4314 final static private int[] WINDOW_SHORTCUT_ID_ARRAY =
4315 { R.id.window_one_menu_id, R.id.window_two_menu_id, R.id.window_three_menu_id,
4316 R.id.window_four_menu_id, R.id.window_five_menu_id, R.id.window_six_menu_id,
4317 R.id.window_seven_menu_id, R.id.window_eight_menu_id };
4318
4319 // monitor platform changes
4320 private IntentFilter mNetworkStateChangedFilter;
4321 private BroadcastReceiver mNetworkStateIntentReceiver;
4322
Grace Klobab4da0ad2009-05-14 14:45:40 -07004323 private BroadcastReceiver mPackageInstallationReceiver;
4324
Bjorn Bringerta7611812010-03-24 11:12:02 +00004325 private SystemAllowGeolocationOrigins mSystemAllowGeolocationOrigins;
4326
The Android Open Source Project0c908882009-03-03 19:32:16 -08004327 // activity requestCode
Nicolas Roard78a98e42009-05-11 13:34:17 +01004328 final static int COMBO_PAGE = 1;
4329 final static int DOWNLOAD_PAGE = 2;
4330 final static int PREFERENCES_PAGE = 3;
Leon Scroggins8d5fa432009-10-02 15:55:59 -04004331 final static int FILE_SELECTED = 4;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004332
Andrei Popescu540035d2009-09-18 18:59:20 +01004333 // the default <video> poster
4334 private Bitmap mDefaultVideoPoster;
4335 // the video progress view
4336 private View mVideoProgressView;
4337
Andrei Popescu30995e72010-02-09 16:59:58 +00004338 // The Google packages we monitor for the navigator.isApplicationInstalled()
4339 // API. Add as needed.
4340 private static Set<String> sGoogleApps;
4341 static {
4342 sGoogleApps = new HashSet<String>();
4343 sGoogleApps.add("com.google.android.youtube");
4344 }
4345
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004346 /**
4347 * A UrlData class to abstract how the content will be set to WebView.
4348 * This base class uses loadUrl to show the content.
4349 */
Leon Scroggins6eac63e2010-03-15 18:19:14 -04004350 /* package */ static class UrlData {
Grace Kloba068e48b2010-01-26 18:11:27 -08004351 final String mUrl;
4352 final Map<String, String> mHeaders;
Leon Scroggins58d56c62010-01-28 15:12:40 -05004353 final Intent mVoiceIntent;
Grace Kloba60e095c2009-06-16 11:50:55 -07004354
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004355 UrlData(String url) {
4356 this.mUrl = url;
Grace Kloba068e48b2010-01-26 18:11:27 -08004357 this.mHeaders = null;
Leon Scroggins58d56c62010-01-28 15:12:40 -05004358 this.mVoiceIntent = null;
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004359 }
Grace Kloba60e095c2009-06-16 11:50:55 -07004360
Leon Scroggins58d56c62010-01-28 15:12:40 -05004361 UrlData(String url, Map<String, String> headers, Intent intent) {
Grace Kloba068e48b2010-01-26 18:11:27 -08004362 this.mUrl = url;
4363 this.mHeaders = headers;
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -05004364 if (RecognizerResultsIntent.ACTION_VOICE_SEARCH_RESULTS
4365 .equals(intent.getAction())) {
Leon Scroggins58d56c62010-01-28 15:12:40 -05004366 this.mVoiceIntent = intent;
4367 } else {
4368 this.mVoiceIntent = null;
4369 }
Grace Kloba60e095c2009-06-16 11:50:55 -07004370 }
4371
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004372 boolean isEmpty() {
Leon Scroggins58d56c62010-01-28 15:12:40 -05004373 return mVoiceIntent == null && (mUrl == null || mUrl.length() == 0);
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004374 }
4375
Leon Scroggins92472e82010-02-17 16:32:28 -05004376 /**
4377 * Load this UrlData into the given Tab. Use loadUrlDataIn to update
4378 * the title bar as well.
4379 */
Leon Scroggins58d56c62010-01-28 15:12:40 -05004380 public void loadIn(Tab t) {
4381 if (mVoiceIntent != null) {
4382 t.activateVoiceSearchMode(mVoiceIntent);
4383 } else {
4384 t.getWebView().loadUrl(mUrl, mHeaders);
4385 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004386 }
4387 };
4388
Leon Scroggins1f005d32009-08-10 17:36:42 -04004389 /* package */ static final UrlData EMPTY_URL_DATA = new UrlData(null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004390}