blob: 36be5e4b7f451dbcf89ff38d946a8fbaaea4ab23 [file] [log] [blame]
The Android Open Source Project0c908882009-03-03 19:32:16 -08001/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.browser;
18
Michael Kolbed217742010-08-10 17:52:34 -070019import android.app.ActionBar;
The Android Open Source Project0c908882009-03-03 19:32:16 -080020import android.app.Activity;
The Android Open Source Project0c908882009-03-03 19:32:16 -080021import android.app.AlertDialog;
22import android.app.ProgressDialog;
23import android.app.SearchManager;
24import android.content.ActivityNotFoundException;
25import android.content.BroadcastReceiver;
Dianne Hackborn80f32622010-08-05 14:17:53 -070026import android.content.ClipboardManager;
The Android Open Source Project0c908882009-03-03 19:32:16 -080027import android.content.ComponentName;
Leon Scroggins58d56c62010-01-28 15:12:40 -050028import android.content.ContentProvider;
29import android.content.ContentProviderClient;
The Android Open Source Project0c908882009-03-03 19:32:16 -080030import android.content.ContentResolver;
Leon Scrogginsb6b7f9e2009-06-18 12:05:28 -040031import android.content.ContentUris;
The Android Open Source Project0c908882009-03-03 19:32:16 -080032import android.content.ContentValues;
33import android.content.Context;
34import android.content.DialogInterface;
35import android.content.Intent;
36import android.content.IntentFilter;
Grace Klobab4da0ad2009-05-14 14:45:40 -070037import android.content.pm.PackageInfo;
The Android Open Source Project0c908882009-03-03 19:32:16 -080038import android.content.pm.PackageManager;
39import android.content.pm.ResolveInfo;
The Android Open Source Project0c908882009-03-03 19:32:16 -080040import android.content.res.Configuration;
41import android.content.res.Resources;
42import android.database.Cursor;
The Android Open Source Project0c908882009-03-03 19:32:16 -080043import android.graphics.Bitmap;
Andrei Popescu540035d2009-09-18 18:59:20 +010044import android.graphics.BitmapFactory;
The Android Open Source Project0c908882009-03-03 19:32:16 -080045import android.graphics.Canvas;
The Android Open Source Project0c908882009-03-03 19:32:16 -080046import android.graphics.Picture;
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -040047import android.graphics.PixelFormat;
The Android Open Source Project0c908882009-03-03 19:32:16 -080048import android.graphics.drawable.Drawable;
The Android Open Source Project0c908882009-03-03 19:32:16 -080049import android.net.ConnectivityManager;
Andrei Popescu56199cc2010-01-12 22:39:16 +000050import android.net.NetworkInfo;
The Android Open Source Project0c908882009-03-03 19:32:16 -080051import android.net.Uri;
52import android.net.WebAddress;
The Android Open Source Project0c908882009-03-03 19:32:16 -080053import android.net.http.SslCertificate;
54import android.net.http.SslError;
55import android.os.AsyncTask;
56import android.os.Bundle;
57import android.os.Debug;
58import android.os.Environment;
59import android.os.Handler;
The Android Open Source Project0c908882009-03-03 19:32:16 -080060import android.os.Message;
61import android.os.PowerManager;
62import android.os.Process;
The Android Open Source Project0c908882009-03-03 19:32:16 -080063import android.os.SystemClock;
The Android Open Source Project0c908882009-03-03 19:32:16 -080064import android.provider.Browser;
Cary Clark5e335a32009-09-22 14:53:11 -040065import android.provider.ContactsContract;
Michael Kolba2b2ba82010-08-04 17:54:03 -070066import android.provider.ContactsContract.Intents.Insert;
The Android Open Source Project0c908882009-03-03 19:32:16 -080067import android.provider.Downloads;
68import android.provider.MediaStore;
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -050069import android.speech.RecognizerResultsIntent;
The Android Open Source Project0c908882009-03-03 19:32:16 -080070import android.text.TextUtils;
71import android.text.format.DateFormat;
The Android Open Source Project0c908882009-03-03 19:32:16 -080072import android.util.Log;
Dianne Hackborn385effd2010-02-24 20:03:04 -080073import android.util.Patterns;
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -040074import android.view.ActionMode;
The Android Open Source Project0c908882009-03-03 19:32:16 -080075import android.view.ContextMenu;
Michael Kolba2b2ba82010-08-04 17:54:03 -070076import android.view.ContextMenu.ContextMenuInfo;
The Android Open Source Project0c908882009-03-03 19:32:16 -080077import android.view.Gravity;
78import android.view.KeyEvent;
79import android.view.LayoutInflater;
80import android.view.Menu;
81import android.view.MenuInflater;
82import android.view.MenuItem;
Michael Kolba2b2ba82010-08-04 17:54:03 -070083import android.view.MenuItem.OnMenuItemClickListener;
The Android Open Source Project0c908882009-03-03 19:32:16 -080084import android.view.View;
85import android.view.ViewGroup;
86import android.view.Window;
87import android.view.WindowManager;
Svetoslav Ganov2b345992010-05-06 06:13:54 -070088import android.view.accessibility.AccessibilityManager;
The Android Open Source Project0c908882009-03-03 19:32:16 -080089import android.webkit.CookieManager;
90import android.webkit.CookieSyncManager;
91import android.webkit.DownloadListener;
92import android.webkit.HttpAuthHandler;
Grace Klobab4da0ad2009-05-14 14:45:40 -070093import android.webkit.PluginManager;
The Android Open Source Project0c908882009-03-03 19:32:16 -080094import android.webkit.SslErrorHandler;
95import android.webkit.URLUtil;
Leon Clarkecb6cc862009-09-29 18:35:13 +010096import android.webkit.ValueCallback;
The Android Open Source Project0c908882009-03-03 19:32:16 -080097import android.webkit.WebChromeClient;
98import android.webkit.WebHistoryItem;
99import android.webkit.WebIconDatabase;
100import android.webkit.WebView;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800101import android.widget.EditText;
102import android.widget.FrameLayout;
103import android.widget.LinearLayout;
104import android.widget.TextView;
105import android.widget.Toast;
106
Michael Kolba2b2ba82010-08-04 17:54:03 -0700107import com.android.browser.ScrollWebView.ScrollListener;
Bjorn Bringert10d1cca2010-02-10 14:22:12 +0000108import com.android.common.Search;
Leon Scroggins1fe13a52010-02-09 15:31:26 -0500109import com.android.common.speech.LoggingEvents;
Dan Egnor5ee906c2009-11-18 12:11:49 -0800110
Leon Scrogginsb6b7f9e2009-06-18 12:05:28 -0400111import java.io.ByteArrayOutputStream;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800112import java.io.File;
Ben Murdoch4f75ba22009-10-27 11:48:28 +0000113import java.io.IOException;
114import java.io.InputStream;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800115import java.net.MalformedURLException;
Dianne Hackborn99189432009-06-17 18:06:18 -0700116import java.net.URISyntaxException;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800117import java.net.URL;
118import java.net.URLEncoder;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800119import java.util.Date;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800120import java.util.HashMap;
Andrei Popescu30995e72010-02-09 16:59:58 +0000121import java.util.HashSet;
Grace Kloba00f54c52010-01-27 14:53:51 -0800122import java.util.Iterator;
Andrei Popescu30995e72010-02-09 16:59:58 +0000123import java.util.List;
Grace Kloba068e48b2010-01-26 18:11:27 -0800124import java.util.Map;
Andrei Popescu30995e72010-02-09 16:59:58 +0000125import java.util.Set;
Michael Kolbfe251992010-07-08 15:41:55 -0700126import java.util.Vector;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800127import java.util.regex.Matcher;
128import java.util.regex.Pattern;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800129
130public class BrowserActivity extends Activity
Shimeng (Simon) Wang98d5fce2010-03-16 13:23:39 -0700131 implements View.OnCreateContextMenuListener, DownloadListener {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800132
Dave Bort31a6d1c2009-04-13 15:56:49 -0700133 /* Define some aliases to make these debugging flags easier to refer to.
134 * This file imports android.provider.Browser, so we can't just refer to "Browser.DEBUG".
135 */
136 private final static boolean DEBUG = com.android.browser.Browser.DEBUG;
137 private final static boolean LOGV_ENABLED = com.android.browser.Browser.LOGV_ENABLED;
138 private final static boolean LOGD_ENABLED = com.android.browser.Browser.LOGD_ENABLED;
139
Satish Sampath565505b2009-05-29 15:37:27 +0100140 // These are single-character shortcuts for searching popular sources.
141 private static final int SHORTCUT_INVALID = 0;
142 private static final int SHORTCUT_GOOGLE_SEARCH = 1;
143 private static final int SHORTCUT_WIKIPEDIA_SEARCH = 2;
144 private static final int SHORTCUT_DICTIONARY_SEARCH = 3;
145 private static final int SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH = 4;
146
Cary Clarka9771242009-08-11 16:42:26 -0400147 private static class ClearThumbnails extends AsyncTask<File, Void, Void> {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800148 @Override
149 public Void doInBackground(File... files) {
150 if (files != null) {
151 for (File f : files) {
Cary Clarkd6be1752009-08-12 12:56:42 -0400152 if (!f.delete()) {
153 Log.e(LOGTAG, f.getPath() + " was not deleted");
154 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800155 }
156 }
157 return null;
158 }
159 }
160
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400161 /**
162 * This layout holds everything you see below the status bar, including the
163 * error console, the custom view container, and the webviews.
164 */
165 private FrameLayout mBrowserFrameLayout;
Leon Scroggins81db3662009-06-04 17:45:11 -0400166
Leon Scrogginsd746a942010-05-19 13:21:44 -0400167 private boolean mXLargeScreenSize;
168
Grace Kloba22ac16e2009-10-07 18:00:23 -0700169 @Override
170 public void onCreate(Bundle icicle) {
Dave Bort31a6d1c2009-04-13 15:56:49 -0700171 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800172 Log.v(LOGTAG, this + " onStart");
173 }
174 super.onCreate(icicle);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800175 // test the browser in OpenGL
176 // requestWindowFeature(Window.FEATURE_OPENGL);
177
Mike Reedd334bf52010-01-26 15:21:44 -0500178 // enable this to test the browser in 32bit
179 if (false) {
180 getWindow().setFormat(PixelFormat.RGBX_8888);
181 BitmapFactory.setDefaultConfig(Bitmap.Config.ARGB_8888);
182 }
183
Svetoslav Ganov2b345992010-05-06 06:13:54 -0700184 if (AccessibilityManager.getInstance(this).isEnabled()) {
185 setDefaultKeyMode(DEFAULT_KEYS_DISABLE);
186 } else {
187 setDefaultKeyMode(DEFAULT_KEYS_SEARCH_LOCAL);
188 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800189
190 mResolver = getContentResolver();
191
Grace Kloba0923d692009-09-23 21:37:25 -0700192 // If this was a web search request, pass it on to the default web
193 // search provider and finish this activity.
194 if (handleWebSearchIntent(getIntent())) {
195 finish();
196 return;
197 }
198
The Android Open Source Project0c908882009-03-03 19:32:16 -0800199 mSecLockIcon = Resources.getSystem().getDrawable(
200 android.R.drawable.ic_secure);
201 mMixLockIcon = Resources.getSystem().getDrawable(
202 android.R.drawable.ic_partial_secure);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800203
Michael Kolbed217742010-08-10 17:52:34 -0700204 // Create the tab control and our initial tab
205 mTabControl = new TabControl(this);
206
207 mXLargeScreenSize = (getResources().getConfiguration().screenLayout
208 & Configuration.SCREENLAYOUT_SIZE_MASK)
209 == Configuration.SCREENLAYOUT_SIZE_XLARGE;
210
Leon Scroggins81db3662009-06-04 17:45:11 -0400211 FrameLayout frameLayout = (FrameLayout) getWindow().getDecorView()
212 .findViewById(com.android.internal.R.id.content);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400213 mBrowserFrameLayout = (FrameLayout) LayoutInflater.from(this)
214 .inflate(R.layout.custom_screen, null);
215 mContentView = (FrameLayout) mBrowserFrameLayout.findViewById(
216 R.id.main_content);
217 mErrorConsoleContainer = (LinearLayout) mBrowserFrameLayout
218 .findViewById(R.id.error_console);
219 mCustomViewContainer = (FrameLayout) mBrowserFrameLayout
220 .findViewById(R.id.fullscreen_custom_content);
221 frameLayout.addView(mBrowserFrameLayout, COVER_SCREEN_PARAMS);
Michael Kolbe0a36662010-06-29 10:37:12 -0700222
Leon Scrogginsd746a942010-05-19 13:21:44 -0400223 if (mXLargeScreenSize) {
Michael Kolba2b2ba82010-08-04 17:54:03 -0700224 mTitleBar = new TitleBarXLarge(this);
225 mTitleBar.setProgress(100);
226 mFakeTitleBar = new TitleBarXLarge(this);
Michael Kolbed217742010-08-10 17:52:34 -0700227 ActionBar actionBar = getActionBar();
Michael Kolba2b2ba82010-08-04 17:54:03 -0700228 mTabBar = new TabBar(this, mTabControl, (TitleBarXLarge) mFakeTitleBar);
Michael Kolbed217742010-08-10 17:52:34 -0700229 actionBar.setCustomNavigationMode(mTabBar);
Leon Scrogginsd746a942010-05-19 13:21:44 -0400230 } else {
Leon Scroggins571b3762010-05-26 10:25:01 -0400231 mTitleBar = new TitleBar(this);
Leon Scrogginsd746a942010-05-19 13:21:44 -0400232 // mTitleBar will be always be shown in the fully loaded mode on
233 // phone
234 mTitleBar.setProgress(100);
Leon Scrogginsd746a942010-05-19 13:21:44 -0400235 mFakeTitleBar = new TitleBar(this);
236 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800237
The Android Open Source Project0c908882009-03-03 19:32:16 -0800238 // Open the icon database and retain all the bookmark urls for favicons
239 retainIconsOnStartup();
240
241 // Keep a settings instance handy.
242 mSettings = BrowserSettings.getInstance();
243 mSettings.setTabControl(mTabControl);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800244
245 PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
246 mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Browser");
247
Patrick Scott6adacc92010-03-05 08:24:51 -0500248 // Find out if the network is currently up.
249 ConnectivityManager cm = (ConnectivityManager) getSystemService(
250 Context.CONNECTIVITY_SERVICE);
251 NetworkInfo info = cm.getActiveNetworkInfo();
252 if (info != null) {
253 mIsNetworkUp = info.isAvailable();
254 }
255
Grace Klobaa34f6862009-07-31 16:28:17 -0700256 /* enables registration for changes in network status from
257 http stack */
258 mNetworkStateChangedFilter = new IntentFilter();
259 mNetworkStateChangedFilter.addAction(
260 ConnectivityManager.CONNECTIVITY_ACTION);
261 mNetworkStateIntentReceiver = new BroadcastReceiver() {
262 @Override
263 public void onReceive(Context context, Intent intent) {
264 if (intent.getAction().equals(
265 ConnectivityManager.CONNECTIVITY_ACTION)) {
Andrei Popescue4c98462010-02-19 15:44:13 +0000266
267 NetworkInfo info = intent.getParcelableExtra(
268 ConnectivityManager.EXTRA_NETWORK_INFO);
269 String typeName = info.getTypeName();
270 String subtypeName = info.getSubtypeName();
271 sendNetworkType(typeName.toLowerCase(),
272 (subtypeName != null ? subtypeName.toLowerCase() : ""));
273
274 onNetworkToggle(info.isAvailable());
Grace Klobaa34f6862009-07-31 16:28:17 -0700275 }
276 }
277 };
278
Grace Kloba615c6c92009-08-03 10:22:44 -0700279 IntentFilter filter = new IntentFilter(Intent.ACTION_PACKAGE_ADDED);
280 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
281 filter.addDataScheme("package");
282 mPackageInstallationReceiver = new BroadcastReceiver() {
283 @Override
284 public void onReceive(Context context, Intent intent) {
285 final String action = intent.getAction();
286 final String packageName = intent.getData()
287 .getSchemeSpecificPart();
288 final boolean replacing = intent.getBooleanExtra(
289 Intent.EXTRA_REPLACING, false);
290 if (Intent.ACTION_PACKAGE_REMOVED.equals(action) && replacing) {
291 // if it is replacing, refreshPlugins() when adding
292 return;
293 }
Andrei Popescu30995e72010-02-09 16:59:58 +0000294
295 if (sGoogleApps.contains(packageName)) {
296 BrowserActivity.this.packageChanged(packageName,
297 Intent.ACTION_PACKAGE_ADDED.equals(action));
298 }
299
Grace Kloba615c6c92009-08-03 10:22:44 -0700300 PackageManager pm = BrowserActivity.this.getPackageManager();
301 PackageInfo pkgInfo = null;
302 try {
303 pkgInfo = pm.getPackageInfo(packageName,
304 PackageManager.GET_PERMISSIONS);
305 } catch (PackageManager.NameNotFoundException e) {
306 return;
307 }
308 if (pkgInfo != null) {
309 String permissions[] = pkgInfo.requestedPermissions;
310 if (permissions == null) {
311 return;
312 }
313 boolean permissionOk = false;
314 for (String permit : permissions) {
315 if (PluginManager.PLUGIN_PERMISSION.equals(permit)) {
316 permissionOk = true;
317 break;
318 }
319 }
320 if (permissionOk) {
321 PluginManager.getInstance(BrowserActivity.this)
Grace Klobae56a0f22010-05-26 17:31:02 -0700322 .refreshPlugins(true);
Grace Kloba615c6c92009-08-03 10:22:44 -0700323 }
324 }
325 }
326 };
327 registerReceiver(mPackageInstallationReceiver, filter);
328
The Android Open Source Project0c908882009-03-03 19:32:16 -0800329 if (!mTabControl.restoreState(icicle)) {
330 // clear up the thumbnail directory if we can't restore the state as
331 // none of the files in the directory are referenced any more.
332 new ClearThumbnails().execute(
333 mTabControl.getThumbnailDir().listFiles());
Grace Klobaaab3f092009-07-30 12:29:51 -0700334 // there is no quit on Android. But if we can't restore the state,
335 // we can treat it as a new Browser, remove the old session cookies.
336 CookieManager.getInstance().removeSessionCookie();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800337 final Intent intent = getIntent();
338 final Bundle extra = intent.getExtras();
339 // Create an initial tab.
340 // If the intent is ACTION_VIEW and data is not null, the Browser is
341 // invoked to view the content by another application. In this case,
342 // the tab will be close when exit.
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700343 UrlData urlData = getUrlDataFromIntent(intent);
344
Leon Scroggins58d56c62010-01-28 15:12:40 -0500345 String action = intent.getAction();
Grace Kloba22ac16e2009-10-07 18:00:23 -0700346 final Tab t = mTabControl.createNewTab(
Leon Scroggins58d56c62010-01-28 15:12:40 -0500347 (Intent.ACTION_VIEW.equals(action) &&
348 intent.getData() != null)
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -0500349 || RecognizerResultsIntent.ACTION_VOICE_SEARCH_RESULTS
350 .equals(action),
Elliott Slaughterf0f03952010-07-14 18:10:36 -0700351 intent.getStringExtra(Browser.EXTRA_APPLICATION_ID),
352 urlData.mUrl, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800353 mTabControl.setCurrentTab(t);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800354 attachTabToContentView(t);
355 WebView webView = t.getWebView();
356 if (extra != null) {
357 int scale = extra.getInt(Browser.INITIAL_ZOOM_LEVEL, 0);
358 if (scale > 0 && scale <= 1000) {
359 webView.setInitialScale(scale);
360 }
361 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800362
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700363 if (urlData.isEmpty()) {
Shimeng (Simon) Wang98d5fce2010-03-16 13:23:39 -0700364 loadUrl(webView, mSettings.getHomePage());
The Android Open Source Project0c908882009-03-03 19:32:16 -0800365 } else {
Patrick Scott9d53da02010-02-19 10:19:01 -0500366 loadUrlDataIn(t, urlData);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800367 }
368 } else {
369 // TabControl.restoreState() will create a new tab even if
Leon Scroggins1f005d32009-08-10 17:36:42 -0400370 // restoring the state fails.
The Android Open Source Project0c908882009-03-03 19:32:16 -0800371 attachTabToContentView(mTabControl.getCurrentTab());
372 }
Grace Kloba615c6c92009-08-03 10:22:44 -0700373
Cary Clarkb4b83182010-07-01 12:36:56 -0400374 // Delete old thumbnails to save space
375 File dir = mTabControl.getThumbnailDir();
376 if (dir.exists()) {
377 for (String child : dir.list()) {
378 File f = new File(dir, child);
379 f.delete();
380 }
381 }
382
Feng Qianb3c02da2009-06-29 15:58:08 -0700383 // Read JavaScript flags if it exists.
384 String jsFlags = mSettings.getJsFlags();
385 if (jsFlags.trim().length() != 0) {
386 mTabControl.getCurrentWebView().setJsFlags(jsFlags);
387 }
Andrei Popescu30995e72010-02-09 16:59:58 +0000388 // Work out which packages are installed on the system.
389 getInstalledPackages();
Bjorn Bringerta7611812010-03-24 11:12:02 +0000390
391 // Start watching the default geolocation permissions
392 mSystemAllowGeolocationOrigins
393 = new SystemAllowGeolocationOrigins(getApplicationContext());
394 mSystemAllowGeolocationOrigins.start();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800395 }
396
Michael Kolba2b2ba82010-08-04 17:54:03 -0700397 ScrollListener getScrollListener() {
398 return mTabBar;
399 }
400
Leon Scroggins58d56c62010-01-28 15:12:40 -0500401 /**
402 * Feed the previously stored results strings to the BrowserProvider so that
403 * the SearchDialog will show them instead of the standard searches.
404 * @param result String to show on the editable line of the SearchDialog.
405 */
406 /* package */ void showVoiceSearchResults(String result) {
407 ContentProviderClient client = mResolver.acquireContentProviderClient(
408 Browser.BOOKMARKS_URI);
409 ContentProvider prov = client.getLocalContentProvider();
410 BrowserProvider bp = (BrowserProvider) prov;
411 bp.setQueryResults(mTabControl.getCurrentTab().getVoiceSearchResults());
412 client.release();
413
Leon Scrogginsfbb3f152010-03-09 17:26:56 -0500414 Bundle bundle = createGoogleSearchSourceBundle(
415 GOOGLE_SEARCH_SOURCE_SEARCHKEY);
416 bundle.putBoolean(SearchManager.CONTEXT_IS_VOICE, true);
417 startSearch(result, false, bundle, false);
Leon Scroggins58d56c62010-01-28 15:12:40 -0500418 }
419
The Android Open Source Project0c908882009-03-03 19:32:16 -0800420 @Override
421 protected void onNewIntent(Intent intent) {
Grace Kloba22ac16e2009-10-07 18:00:23 -0700422 Tab current = mTabControl.getCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800423 // When a tab is closed on exit, the current tab index is set to -1.
424 // Reset before proceed as Browser requires the current tab to be set.
425 if (current == null) {
426 // Try to reset the tab in case the index was incorrect.
427 current = mTabControl.getTab(0);
428 if (current == null) {
429 // No tabs at all so just ignore this intent.
430 return;
431 }
432 mTabControl.setCurrentTab(current);
433 attachTabToContentView(current);
434 resetTitleAndIcon(current.getWebView());
435 }
436 final String action = intent.getAction();
437 final int flags = intent.getFlags();
438 if (Intent.ACTION_MAIN.equals(action) ||
439 (flags & Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY) != 0) {
440 // just resume the browser
441 return;
442 }
Leon Scrogginsb8a844d2010-03-18 15:06:15 -0400443 // In case the SearchDialog is open.
444 ((SearchManager) getSystemService(Context.SEARCH_SERVICE))
445 .stopSearch();
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -0500446 boolean activateVoiceSearch = RecognizerResultsIntent
447 .ACTION_VOICE_SEARCH_RESULTS.equals(action);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800448 if (Intent.ACTION_VIEW.equals(action)
449 || Intent.ACTION_SEARCH.equals(action)
450 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
Leon Scroggins58d56c62010-01-28 15:12:40 -0500451 || Intent.ACTION_WEB_SEARCH.equals(action)
452 || activateVoiceSearch) {
Leon Scroggins3b18ce32010-02-08 17:35:59 -0500453 if (current.isInVoiceSearchMode()) {
454 String title = current.getVoiceDisplayTitle();
455 if (title != null && title.equals(intent.getStringExtra(
456 SearchManager.QUERY))) {
457 // The user submitted the same search as the last voice
458 // search, so do nothing.
459 return;
460 }
Leon Scroggins1fe13a52010-02-09 15:31:26 -0500461 if (Intent.ACTION_SEARCH.equals(action)
462 && current.voiceSearchSourceIsGoogle()) {
463 Intent logIntent = new Intent(
464 LoggingEvents.ACTION_LOG_EVENT);
465 logIntent.putExtra(LoggingEvents.EXTRA_EVENT,
466 LoggingEvents.VoiceSearch.QUERY_UPDATED);
467 logIntent.putExtra(
468 LoggingEvents.VoiceSearch.EXTRA_QUERY_UPDATED_VALUE,
469 intent.getDataString());
470 sendBroadcast(logIntent);
471 // Note, onPageStarted will revert the voice title bar
472 // When http://b/issue?id=2379215 is fixed, we should update
473 // the title bar here.
474 }
Leon Scroggins3b18ce32010-02-08 17:35:59 -0500475 }
Satish Sampath565505b2009-05-29 15:37:27 +0100476 // If this was a search request (e.g. search query directly typed into the address bar),
477 // pass it on to the default web search provider.
478 if (handleWebSearchIntent(intent)) {
479 return;
480 }
481
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700482 UrlData urlData = getUrlDataFromIntent(intent);
483 if (urlData.isEmpty()) {
484 urlData = new UrlData(mSettings.getHomePage());
The Android Open Source Project0c908882009-03-03 19:32:16 -0800485 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700486
Grace Klobacc634032009-07-28 15:58:19 -0700487 final String appId = intent
488 .getStringExtra(Browser.EXTRA_APPLICATION_ID);
Leon Scroggins47208682010-04-07 17:59:48 -0400489 if ((Intent.ACTION_VIEW.equals(action)
490 // If a voice search has no appId, it means that it came
491 // from the browser. In that case, reuse the current tab.
492 || (activateVoiceSearch && appId != null))
Grace Klobacc634032009-07-28 15:58:19 -0700493 && !getPackageName().equals(appId)
494 && (flags & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0) {
Grace Kloba22ac16e2009-10-07 18:00:23 -0700495 Tab appTab = mTabControl.getTabFromId(appId);
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700496 if (appTab != null) {
497 Log.i(LOGTAG, "Reusing tab for " + appId);
498 // Dismiss the subwindow if applicable.
499 dismissSubWindow(appTab);
500 // Since we might kill the WebView, remove it from the
501 // content view first.
502 removeTabFromContentView(appTab);
503 // Recreate the main WebView after destroying the old one.
504 // If the WebView has the same original url and is on that
505 // page, it can be reused.
506 boolean needsLoad =
Leon Scroggins6eac63e2010-03-15 18:19:14 -0400507 mTabControl.recreateWebView(appTab, urlData);
Ben Murdochbff2d602009-07-01 20:19:05 +0100508
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700509 if (current != appTab) {
Leon Scroggins1f005d32009-08-10 17:36:42 -0400510 switchToTab(mTabControl.getTabIndex(appTab));
511 if (needsLoad) {
Patrick Scott9d53da02010-02-19 10:19:01 -0500512 loadUrlDataIn(appTab, urlData);
Leon Scroggins1f005d32009-08-10 17:36:42 -0400513 }
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700514 } else {
Leon Scroggins1f005d32009-08-10 17:36:42 -0400515 // If the tab was the current tab, we have to attach
516 // it to the view system again.
517 attachTabToContentView(appTab);
518 if (needsLoad) {
Patrick Scott9d53da02010-02-19 10:19:01 -0500519 loadUrlDataIn(appTab, urlData);
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700520 }
521 }
522 return;
Patrick Scottcd115892009-07-16 09:42:58 -0400523 } else {
524 // No matching application tab, try to find a regular tab
525 // with a matching url.
526 appTab = mTabControl.findUnusedTabWithUrl(urlData.mUrl);
Leon Scroggins25515f82009-08-19 15:31:58 -0400527 if (appTab != null) {
528 if (current != appTab) {
529 switchToTab(mTabControl.getTabIndex(appTab));
530 }
531 // Otherwise, we are already viewing the correct tab.
Patrick Scottcd115892009-07-16 09:42:58 -0400532 } else {
533 // if FLAG_ACTIVITY_BROUGHT_TO_FRONT flag is on, the url
534 // will be opened in a new tab unless we have reached
535 // MAX_TABS. Then the url will be opened in the current
536 // tab. If a new tab is created, it will have "true" for
537 // exit on close.
Leon Scroggins1f005d32009-08-10 17:36:42 -0400538 openTabAndShow(urlData, true, appId);
Patrick Scottcd115892009-07-16 09:42:58 -0400539 }
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700540 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800541 } else {
Grace Kloba638d3f42009-11-23 10:35:04 -0800542 if (!urlData.isEmpty()
543 && urlData.mUrl.startsWith("about:debug")) {
544 if ("about:debug.dom".equals(urlData.mUrl)) {
545 current.getWebView().dumpDomTree(false);
546 } else if ("about:debug.dom.file".equals(urlData.mUrl)) {
547 current.getWebView().dumpDomTree(true);
548 } else if ("about:debug.render".equals(urlData.mUrl)) {
549 current.getWebView().dumpRenderTree(false);
550 } else if ("about:debug.render.file".equals(urlData.mUrl)) {
551 current.getWebView().dumpRenderTree(true);
552 } else if ("about:debug.display".equals(urlData.mUrl)) {
553 current.getWebView().dumpDisplayTree();
Mike Reed9b78e1d2010-01-13 14:40:52 -0800554 } else if (urlData.mUrl.startsWith("about:debug.drag")) {
555 int index = urlData.mUrl.codePointAt(16) - '0';
556 if (index <= 0 || index > 9) {
557 current.getWebView().setDragTracker(null);
558 } else {
559 current.getWebView().setDragTracker(new MeshTracker(index));
560 }
Grace Kloba638d3f42009-11-23 10:35:04 -0800561 } else {
562 mSettings.toggleDebugSettings();
563 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800564 return;
565 }
Leon Scroggins1f005d32009-08-10 17:36:42 -0400566 // Get rid of the subwindow if it exists
567 dismissSubWindow(current);
Leon Scroggins8588d152010-04-15 11:01:53 -0400568 // If the current Tab is being used as an application tab,
569 // remove the association, since the new Intent means that it is
570 // no longer associated with that application.
571 current.setAppId(null);
Patrick Scott9d53da02010-02-19 10:19:01 -0500572 loadUrlDataIn(current, urlData);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800573 }
574 }
575 }
576
Satish Sampath565505b2009-05-29 15:37:27 +0100577 private int parseUrlShortcut(String url) {
578 if (url == null) return SHORTCUT_INVALID;
579
580 // FIXME: quick search, need to be customized by setting
581 if (url.length() > 2 && url.charAt(1) == ' ') {
582 switch (url.charAt(0)) {
583 case 'g': return SHORTCUT_GOOGLE_SEARCH;
584 case 'w': return SHORTCUT_WIKIPEDIA_SEARCH;
585 case 'd': return SHORTCUT_DICTIONARY_SEARCH;
586 case 'l': return SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH;
587 }
588 }
589 return SHORTCUT_INVALID;
590 }
591
592 /**
593 * Launches the default web search activity with the query parameters if the given intent's data
594 * are identified as plain search terms and not URLs/shortcuts.
595 * @return true if the intent was handled and web search activity was launched, false if not.
596 */
597 private boolean handleWebSearchIntent(Intent intent) {
598 if (intent == null) return false;
599
600 String url = null;
601 final String action = intent.getAction();
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -0500602 if (RecognizerResultsIntent.ACTION_VOICE_SEARCH_RESULTS.equals(
603 action)) {
Leon Scroggins58d56c62010-01-28 15:12:40 -0500604 return false;
605 }
Satish Sampath565505b2009-05-29 15:37:27 +0100606 if (Intent.ACTION_VIEW.equals(action)) {
Grace Kloba1e705052009-09-29 13:13:36 -0700607 Uri data = intent.getData();
608 if (data != null) url = data.toString();
Satish Sampath565505b2009-05-29 15:37:27 +0100609 } else if (Intent.ACTION_SEARCH.equals(action)
610 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
611 || Intent.ACTION_WEB_SEARCH.equals(action)) {
612 url = intent.getStringExtra(SearchManager.QUERY);
613 }
Bjorn Bringert04851702009-09-22 10:36:01 +0100614 return handleWebSearchRequest(url, intent.getBundleExtra(SearchManager.APP_DATA),
615 intent.getStringExtra(SearchManager.EXTRA_DATA_KEY));
Satish Sampath565505b2009-05-29 15:37:27 +0100616 }
617
618 /**
619 * Launches the default web search activity with the query parameters if the given url string
620 * was identified as plain search terms and not URL/shortcut.
621 * @return true if the request was handled and web search activity was launched, false if not.
622 */
Bjorn Bringert04851702009-09-22 10:36:01 +0100623 private boolean handleWebSearchRequest(String inUrl, Bundle appData, String extraData) {
Satish Sampath565505b2009-05-29 15:37:27 +0100624 if (inUrl == null) return false;
625
626 // In general, we shouldn't modify URL from Intent.
627 // But currently, we get the user-typed URL from search box as well.
628 String url = fixUrl(inUrl).trim();
629
630 // URLs and site specific search shortcuts are handled by the regular flow of control, so
631 // return early.
Dan Egnor5ee906c2009-11-18 12:11:49 -0800632 if (Patterns.WEB_URL.matcher(url).matches()
Satish Sampathbc5b9f32009-06-04 18:21:40 +0100633 || ACCEPTED_URI_SCHEMA.matcher(url).matches()
Satish Sampath565505b2009-05-29 15:37:27 +0100634 || parseUrlShortcut(url) != SHORTCUT_INVALID) {
635 return false;
636 }
637
Leon Scroggins8d06e362010-03-24 14:45:57 -0400638 final ContentResolver cr = mResolver;
639 final String newUrl = url;
Elliott Slaughterf0f03952010-07-14 18:10:36 -0700640 if (!mTabControl.getCurrentWebView().isPrivateBrowsingEnabled()) {
641 new AsyncTask<Void, Void, Void>() {
642 @Override
643 protected Void doInBackground(Void... unused) {
644 Browser.updateVisitedHistory(cr, newUrl, false);
645 Browser.addSearchUrl(cr, newUrl);
646 return null;
647 }
648 }.execute();
649 }
Satish Sampath565505b2009-05-29 15:37:27 +0100650
651 Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);
652 intent.addCategory(Intent.CATEGORY_DEFAULT);
653 intent.putExtra(SearchManager.QUERY, url);
Satish Sampath15e9f2d2009-06-23 22:29:49 +0100654 if (appData != null) {
655 intent.putExtra(SearchManager.APP_DATA, appData);
656 }
Bjorn Bringert04851702009-09-22 10:36:01 +0100657 if (extraData != null) {
658 intent.putExtra(SearchManager.EXTRA_DATA_KEY, extraData);
659 }
Grace Klobacc634032009-07-28 15:58:19 -0700660 intent.putExtra(Browser.EXTRA_APPLICATION_ID, getPackageName());
Satish Sampath565505b2009-05-29 15:37:27 +0100661 startActivity(intent);
662
663 return true;
664 }
665
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700666 private UrlData getUrlDataFromIntent(Intent intent) {
Leon Scroggins58d56c62010-01-28 15:12:40 -0500667 String url = "";
Grace Kloba068e48b2010-01-26 18:11:27 -0800668 Map<String, String> headers = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800669 if (intent != null) {
670 final String action = intent.getAction();
671 if (Intent.ACTION_VIEW.equals(action)) {
672 url = smartUrlFilter(intent.getData());
673 if (url != null && url.startsWith("content:")) {
674 /* Append mimetype so webview knows how to display */
675 String mimeType = intent.resolveType(getContentResolver());
676 if (mimeType != null) {
677 url += "?" + mimeType;
678 }
679 }
Grace Kloba068e48b2010-01-26 18:11:27 -0800680 if (url != null && url.startsWith("http")) {
Grace Kloba00f54c52010-01-27 14:53:51 -0800681 final Bundle pairs = intent
682 .getBundleExtra(Browser.EXTRA_HEADERS);
Grace Kloba2d508ed2010-01-28 11:39:15 -0800683 if (pairs != null && !pairs.isEmpty()) {
Grace Kloba00f54c52010-01-27 14:53:51 -0800684 Iterator<String> iter = pairs.keySet().iterator();
Grace Kloba068e48b2010-01-26 18:11:27 -0800685 headers = new HashMap<String, String>();
Grace Kloba00f54c52010-01-27 14:53:51 -0800686 while (iter.hasNext()) {
687 String key = iter.next();
688 headers.put(key, pairs.getString(key));
Grace Kloba068e48b2010-01-26 18:11:27 -0800689 }
690 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700691 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800692 } else if (Intent.ACTION_SEARCH.equals(action)
693 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
694 || Intent.ACTION_WEB_SEARCH.equals(action)) {
695 url = intent.getStringExtra(SearchManager.QUERY);
696 if (url != null) {
697 mLastEnteredUrl = url;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800698 // In general, we shouldn't modify URL from Intent.
699 // But currently, we get the user-typed URL from search box as well.
700 url = fixUrl(url);
701 url = smartUrlFilter(url);
Leon Scroggins8d06e362010-03-24 14:45:57 -0400702 final ContentResolver cr = mResolver;
703 final String newUrl = url;
704 new AsyncTask<Void, Void, Void>() {
Michael Kolbe0a36662010-06-29 10:37:12 -0700705 @Override
Leon Scroggins8d06e362010-03-24 14:45:57 -0400706 protected Void doInBackground(Void... unused) {
707 Browser.updateVisitedHistory(cr, newUrl, false);
708 return null;
709 }
710 }.execute();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800711 String searchSource = "&source=android-" + GOOGLE_SEARCH_SOURCE_SUGGEST + "&";
712 if (url.contains(searchSource)) {
713 String source = null;
714 final Bundle appData = intent.getBundleExtra(SearchManager.APP_DATA);
715 if (appData != null) {
Bjorn Bringert10d1cca2010-02-10 14:22:12 +0000716 source = appData.getString(Search.SOURCE);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800717 }
718 if (TextUtils.isEmpty(source)) {
719 source = GOOGLE_SEARCH_SOURCE_UNKNOWN;
720 }
721 url = url.replace(searchSource, "&source=android-"+source+"&");
722 }
723 }
724 }
725 }
Leon Scroggins58d56c62010-01-28 15:12:40 -0500726 return new UrlData(url, headers, intent);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800727 }
Leon Scroggins58d56c62010-01-28 15:12:40 -0500728 /* package */ void showVoiceTitleBar(String title) {
729 mTitleBar.setInVoiceMode(true);
Leon Scroggins58d56c62010-01-28 15:12:40 -0500730 mTitleBar.setDisplayTitle(title);
Michael Kolba2b2ba82010-08-04 17:54:03 -0700731 mFakeTitleBar.setInVoiceMode(true);
732 mFakeTitleBar.setDisplayTitle(title);
Leon Scroggins58d56c62010-01-28 15:12:40 -0500733 }
734 /* package */ void revertVoiceTitleBar() {
735 mTitleBar.setInVoiceMode(false);
Leon Scroggins003a5dd2010-03-10 12:13:14 -0500736 mTitleBar.setDisplayTitle(mUrl);
Michael Kolba2b2ba82010-08-04 17:54:03 -0700737 mFakeTitleBar.setInVoiceMode(false);
738 mFakeTitleBar.setDisplayTitle(mUrl);
Leon Scroggins58d56c62010-01-28 15:12:40 -0500739 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800740 /* package */ static String fixUrl(String inUrl) {
Cary Clark652ff872009-09-10 13:34:44 -0400741 // FIXME: Converting the url to lower case
742 // duplicates functionality in smartUrlFilter().
743 // However, changing all current callers of fixUrl to
744 // call smartUrlFilter in addition may have unwanted
745 // consequences, and is deferred for now.
746 int colon = inUrl.indexOf(':');
747 boolean allLower = true;
748 for (int index = 0; index < colon; index++) {
749 char ch = inUrl.charAt(index);
750 if (!Character.isLetter(ch)) {
751 break;
752 }
753 allLower &= Character.isLowerCase(ch);
754 if (index == colon - 1 && !allLower) {
755 inUrl = inUrl.substring(0, colon).toLowerCase()
756 + inUrl.substring(colon);
757 }
758 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800759 if (inUrl.startsWith("http://") || inUrl.startsWith("https://"))
760 return inUrl;
761 if (inUrl.startsWith("http:") ||
762 inUrl.startsWith("https:")) {
763 if (inUrl.startsWith("http:/") || inUrl.startsWith("https:/")) {
764 inUrl = inUrl.replaceFirst("/", "//");
765 } else inUrl = inUrl.replaceFirst(":", "://");
766 }
767 return inUrl;
768 }
769
Grace Kloba22ac16e2009-10-07 18:00:23 -0700770 @Override
771 protected void onResume() {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800772 super.onResume();
Dave Bort31a6d1c2009-04-13 15:56:49 -0700773 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800774 Log.v(LOGTAG, "BrowserActivity.onResume: this=" + this);
775 }
776
777 if (!mActivityInPause) {
778 Log.e(LOGTAG, "BrowserActivity is already resumed.");
779 return;
780 }
781
Mike Reed7bfa63b2009-05-28 11:08:32 -0400782 mTabControl.resumeCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800783 mActivityInPause = false;
Mike Reed7bfa63b2009-05-28 11:08:32 -0400784 resumeWebViewTimers();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800785
786 if (mWakeLock.isHeld()) {
787 mHandler.removeMessages(RELEASE_WAKELOCK);
788 mWakeLock.release();
789 }
790
The Android Open Source Project0c908882009-03-03 19:32:16 -0800791 registerReceiver(mNetworkStateIntentReceiver,
792 mNetworkStateChangedFilter);
793 WebView.enablePlatformNotifications();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800794 }
795
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400796 /**
797 * Since the actual title bar is embedded in the WebView, and removing it
Leon Scrogginsfe87bd32009-10-06 10:10:00 -0400798 * would change its appearance, use a different TitleBar to show overlayed
799 * at the top of the screen, when the menu is open or the page is loading.
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400800 */
Michael Kolba2b2ba82010-08-04 17:54:03 -0700801 private TitleBarBase mFakeTitleBar;
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400802
803 /**
804 * Keeps track of whether the options menu is open. This is important in
805 * determining whether to show or hide the title bar overlay.
806 */
807 private boolean mOptionsMenuOpen;
808
809 /**
810 * Only meaningful when mOptionsMenuOpen is true. This variable keeps track
811 * of whether the configuration has changed. The first onMenuOpened call
812 * after a configuration change is simply a reopening of the same menu
813 * (i.e. mIconView did not change).
814 */
815 private boolean mConfigChanged;
816
817 /**
818 * Whether or not the options menu is in its smaller, icon menu form. When
819 * true, we want the title bar overlay to be up. When false, we do not.
820 * Only meaningful if mOptionsMenuOpen is true.
821 */
822 private boolean mIconView;
823
Leon Scrogginsa81a7642009-08-31 17:05:41 -0400824 @Override
825 public boolean onMenuOpened(int featureId, Menu menu) {
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400826 if (Window.FEATURE_OPTIONS_PANEL == featureId) {
827 if (mOptionsMenuOpen) {
828 if (mConfigChanged) {
829 // We do not need to make any changes to the state of the
830 // title bar, since the only thing that happened was a
831 // change in orientation
832 mConfigChanged = false;
833 } else {
834 if (mIconView) {
835 // Switching the menu to expanded view, so hide the
836 // title bar.
837 hideFakeTitleBar();
838 mIconView = false;
839 } else {
840 // Switching the menu back to icon view, so show the
841 // title bar once again.
842 showFakeTitleBar();
843 mIconView = true;
844 }
845 }
846 } else {
847 // The options menu is closed, so open it, and show the title
848 showFakeTitleBar();
849 mOptionsMenuOpen = true;
850 mConfigChanged = false;
851 mIconView = true;
852 }
853 }
Leon Scrogginsa81a7642009-08-31 17:05:41 -0400854 return true;
855 }
856
Michael Kolba2b2ba82010-08-04 17:54:03 -0700857 void showFakeTitleBar() {
858 if (!isFakeTitleBarShowing() && mActiveTabsPage == null && !mActivityInPause) {
Grace Kloba847c25b2010-03-30 16:00:26 -0700859 WebView mainView = mTabControl.getCurrentWebView();
860 // if there is no current WebView, don't show the faked title bar;
Grace Kloba65190702010-04-02 23:37:26 -0700861 if (mainView == null) {
Cary Clarka0464552009-09-29 13:00:45 -0400862 return;
863 }
Leon Scroggins79e36d92010-04-29 16:01:46 +0100864 // Do not need to check for null, since the current tab will have
865 // at least a main WebView, or we would have returned above.
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -0400866 if (isInCustomActionMode()) {
867 // Do not show the fake title bar, while a custom ActionMode
868 // (i.e. find or select) is showing.
Leon Scroggins79e36d92010-04-29 16:01:46 +0100869 return;
870 }
Michael Kolba2b2ba82010-08-04 17:54:03 -0700871 if (mXLargeScreenSize) {
872 mContentView.addView(mFakeTitleBar);
873 mTabBar.onShowTitleBar();
874 } else {
875 WindowManager manager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400876
Michael Kolba2b2ba82010-08-04 17:54:03 -0700877 // Add the title bar to the window manager so it can receive
878 // touches
879 // while the menu is up
880 WindowManager.LayoutParams params =
881 new WindowManager.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
882 ViewGroup.LayoutParams.WRAP_CONTENT,
883 WindowManager.LayoutParams.TYPE_APPLICATION,
884 WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
885 PixelFormat.TRANSLUCENT);
886 params.gravity = Gravity.TOP;
887 boolean atTop = mainView.getScrollY() == 0;
888 params.windowAnimations = atTop ? 0 : R.style.TitleBar;
889 manager.addView(mFakeTitleBar, params);
890 }
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400891 }
892 }
893
894 @Override
895 public void onOptionsMenuClosed(Menu menu) {
896 mOptionsMenuOpen = false;
Leon Scrogginsa27ff192009-09-14 12:58:04 -0400897 if (!mInLoad) {
898 hideFakeTitleBar();
899 } else if (!mIconView) {
900 // The page is currently loading, and we are in expanded mode, so
901 // we were not showing the menu. Show it once again. It will be
902 // removed when the page finishes.
903 showFakeTitleBar();
904 }
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400905 }
Grace Kloba22ac16e2009-10-07 18:00:23 -0700906
Michael Kolba2b2ba82010-08-04 17:54:03 -0700907 void stopScrolling() {
908 ((ScrollWebView) mTabControl.getCurrentWebView()).stopScroll();
909 }
910
911 void hideFakeTitleBar() {
912 if (!isFakeTitleBarShowing()) return;
913 if (mXLargeScreenSize) {
914 mContentView.removeView(mFakeTitleBar);
915 mTabBar.onHideTitleBar();
916 } else {
917 WindowManager.LayoutParams params =
918 (WindowManager.LayoutParams) mFakeTitleBar.getLayoutParams();
919 WebView mainView = mTabControl.getCurrentWebView();
920 // Although we decided whether or not to animate based on the
921 // current
922 // scroll position, the scroll position may have changed since the
923 // fake title bar was displayed. Make sure it has the appropriate
924 // animation/lack thereof before removing.
925 params.windowAnimations =
926 mainView != null && mainView.getScrollY() == 0 ? 0 : R.style.TitleBar;
927 WindowManager manager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
928 manager.updateViewLayout(mFakeTitleBar, params);
929 manager.removeView(mFakeTitleBar);
930 }
931 }
932
933 boolean isFakeTitleBarShowing() {
934 return (mFakeTitleBar.getParent() != null);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400935 }
936
The Android Open Source Project0c908882009-03-03 19:32:16 -0800937 /**
Leon Scrogginsc6fa1102009-09-21 10:40:01 -0400938 * Special method for the fake title bar to call when displaying its context
939 * menu, since it is in its own Window, and its parent does not show a
940 * context menu.
941 */
942 /* package */ void showTitleBarContextMenu() {
Cary Clark65f4a3c2009-09-28 17:05:06 -0400943 if (null == mTitleBar.getParent()) {
944 return;
945 }
Leon Scrogginsc6fa1102009-09-21 10:40:01 -0400946 openContextMenu(mTitleBar);
947 }
948
Leon Scrogginsb2b19f52009-10-09 16:10:00 -0400949 @Override
950 public void onContextMenuClosed(Menu menu) {
951 super.onContextMenuClosed(menu);
952 if (mInLoad) {
953 showFakeTitleBar();
954 }
955 }
956
Leon Scrogginsc6fa1102009-09-21 10:40:01 -0400957 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -0800958 * onSaveInstanceState(Bundle map)
959 * onSaveInstanceState is called right before onStop(). The map contains
960 * the saved state.
961 */
Grace Kloba22ac16e2009-10-07 18:00:23 -0700962 @Override
963 protected void onSaveInstanceState(Bundle outState) {
Dave Bort31a6d1c2009-04-13 15:56:49 -0700964 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800965 Log.v(LOGTAG, "BrowserActivity.onSaveInstanceState: this=" + this);
966 }
967 // the default implementation requires each view to have an id. As the
968 // browser handles the state itself and it doesn't use id for the views,
969 // don't call the default implementation. Otherwise it will trigger the
970 // warning like this, "couldn't save which view has focus because the
971 // focused view XXX has no id".
972
973 // Save all the tabs
974 mTabControl.saveState(outState);
975 }
976
Grace Kloba22ac16e2009-10-07 18:00:23 -0700977 @Override
978 protected void onPause() {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800979 super.onPause();
980
981 if (mActivityInPause) {
982 Log.e(LOGTAG, "BrowserActivity is already paused.");
983 return;
984 }
985
Mike Reed7bfa63b2009-05-28 11:08:32 -0400986 mTabControl.pauseCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800987 mActivityInPause = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -0400988 if (mTabControl.getCurrentIndex() >= 0 && !pauseWebViewTimers()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800989 mWakeLock.acquire();
990 mHandler.sendMessageDelayed(mHandler
991 .obtainMessage(RELEASE_WAKELOCK), WAKELOCK_TIMEOUT);
992 }
993
Leon Scrogginsa2ab6a72009-09-11 11:49:52 -0400994 // FIXME: This removes the active tabs page and resets the menu to
995 // MAIN_MENU. A better solution might be to do this work in onNewIntent
996 // but then we would need to save it in onSaveInstanceState and restore
997 // it in onCreate/onRestoreInstanceState
998 if (mActiveTabsPage != null) {
999 removeActiveTabPage(true);
1000 }
1001
The Android Open Source Project0c908882009-03-03 19:32:16 -08001002 cancelStopToast();
1003
1004 // unregister network state listener
1005 unregisterReceiver(mNetworkStateIntentReceiver);
1006 WebView.disablePlatformNotifications();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001007 }
1008
Grace Kloba22ac16e2009-10-07 18:00:23 -07001009 @Override
1010 protected void onDestroy() {
Dave Bort31a6d1c2009-04-13 15:56:49 -07001011 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001012 Log.v(LOGTAG, "BrowserActivity.onDestroy: this=" + this);
1013 }
1014 super.onDestroy();
Grace Kloba0923d692009-09-23 21:37:25 -07001015
Leon Scroggins8d5fa432009-10-02 15:55:59 -04001016 if (mUploadMessage != null) {
1017 mUploadMessage.onReceiveValue(null);
1018 mUploadMessage = null;
1019 }
1020
Grace Kloba0923d692009-09-23 21:37:25 -07001021 if (mTabControl == null) return;
1022
Grace Kloba1fc98a32009-10-21 13:23:08 -07001023 // Remove the fake title bar if it is there
1024 hideFakeTitleBar();
1025
The Android Open Source Project0c908882009-03-03 19:32:16 -08001026 // Remove the current tab and sub window
Grace Kloba22ac16e2009-10-07 18:00:23 -07001027 Tab t = mTabControl.getCurrentTab();
Patrick Scottfb5e77f2009-04-08 19:17:37 -07001028 if (t != null) {
1029 dismissSubWindow(t);
1030 removeTabFromContentView(t);
1031 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001032 // Destroy all the tabs
1033 mTabControl.destroy();
1034 WebIconDatabase.getInstance().close();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001035
Grace Klobab4da0ad2009-05-14 14:45:40 -07001036 unregisterReceiver(mPackageInstallationReceiver);
Bjorn Bringerta7611812010-03-24 11:12:02 +00001037
1038 // Stop watching the default geolocation permissions
1039 mSystemAllowGeolocationOrigins.stop();
1040 mSystemAllowGeolocationOrigins = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001041 }
1042
1043 @Override
1044 public void onConfigurationChanged(Configuration newConfig) {
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04001045 mConfigChanged = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001046 super.onConfigurationChanged(newConfig);
1047
1048 if (mPageInfoDialog != null) {
1049 mPageInfoDialog.dismiss();
1050 showPageInfo(
1051 mPageInfoView,
Leon Scrogginsc7b92f82010-01-11 18:17:31 -05001052 mPageInfoFromShowSSLCertificateOnError);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001053 }
1054 if (mSSLCertificateDialog != null) {
1055 mSSLCertificateDialog.dismiss();
1056 showSSLCertificate(
1057 mSSLCertificateView);
1058 }
1059 if (mSSLCertificateOnErrorDialog != null) {
1060 mSSLCertificateOnErrorDialog.dismiss();
1061 showSSLCertificateOnError(
1062 mSSLCertificateOnErrorView,
1063 mSSLCertificateOnErrorHandler,
1064 mSSLCertificateOnErrorError);
1065 }
1066 if (mHttpAuthenticationDialog != null) {
1067 String title = ((TextView) mHttpAuthenticationDialog
1068 .findViewById(com.android.internal.R.id.alertTitle)).getText()
1069 .toString();
1070 String name = ((TextView) mHttpAuthenticationDialog
1071 .findViewById(R.id.username_edit)).getText().toString();
1072 String password = ((TextView) mHttpAuthenticationDialog
1073 .findViewById(R.id.password_edit)).getText().toString();
1074 int focusId = mHttpAuthenticationDialog.getCurrentFocus()
1075 .getId();
1076 mHttpAuthenticationDialog.dismiss();
1077 showHttpAuthentication(mHttpAuthHandler, null, null, title,
1078 name, password, focusId);
1079 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001080 }
1081
Grace Kloba22ac16e2009-10-07 18:00:23 -07001082 @Override
1083 public void onLowMemory() {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001084 super.onLowMemory();
1085 mTabControl.freeMemory();
1086 }
1087
Cary Clarkff4d92c2010-03-25 11:17:03 -04001088 private void resumeWebViewTimers() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001089 Tab tab = mTabControl.getCurrentTab();
Cary Clarkff4d92c2010-03-25 11:17:03 -04001090 if (tab == null) return; // monkey can trigger this
Grace Kloba22ac16e2009-10-07 18:00:23 -07001091 boolean inLoad = tab.inLoad();
1092 if ((!mActivityInPause && !inLoad) || (mActivityInPause && inLoad)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001093 CookieSyncManager.getInstance().startSync();
Grace Kloba22ac16e2009-10-07 18:00:23 -07001094 WebView w = tab.getWebView();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001095 if (w != null) {
1096 w.resumeTimers();
1097 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001098 }
1099 }
1100
Mike Reed7bfa63b2009-05-28 11:08:32 -04001101 private boolean pauseWebViewTimers() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001102 Tab tab = mTabControl.getCurrentTab();
1103 boolean inLoad = tab.inLoad();
1104 if (mActivityInPause && !inLoad) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001105 CookieSyncManager.getInstance().stopSync();
1106 WebView w = mTabControl.getCurrentWebView();
1107 if (w != null) {
1108 w.pauseTimers();
1109 }
1110 return true;
1111 } else {
1112 return false;
1113 }
1114 }
1115
The Android Open Source Project0c908882009-03-03 19:32:16 -08001116 // Open the icon database and retain all the icons for visited sites.
1117 private void retainIconsOnStartup() {
1118 final WebIconDatabase db = WebIconDatabase.getInstance();
1119 db.open(getDir("icons", 0).getPath());
Leon Scroggins2c0f6112010-03-12 18:09:39 -05001120 Cursor c = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001121 try {
Leon Scroggins2c0f6112010-03-12 18:09:39 -05001122 c = Browser.getAllBookmarks(mResolver);
1123 if (c.moveToFirst()) {
1124 int urlIndex = c.getColumnIndex(Browser.BookmarkColumns.URL);
1125 do {
1126 String url = c.getString(urlIndex);
1127 db.retainIconForPageUrl(url);
1128 } while (c.moveToNext());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001129 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001130 } catch (IllegalStateException e) {
1131 Log.e(LOGTAG, "retainIconsOnStartup", e);
Leon Scroggins2c0f6112010-03-12 18:09:39 -05001132 } finally {
1133 if (c!= null) c.close();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001134 }
1135 }
1136
1137 // Helper method for getting the top window.
1138 WebView getTopWindow() {
1139 return mTabControl.getCurrentTopWebView();
1140 }
1141
Grace Kloba22ac16e2009-10-07 18:00:23 -07001142 TabControl getTabControl() {
1143 return mTabControl;
1144 }
1145
The Android Open Source Project0c908882009-03-03 19:32:16 -08001146 @Override
1147 public boolean onCreateOptionsMenu(Menu menu) {
1148 super.onCreateOptionsMenu(menu);
1149
1150 MenuInflater inflater = getMenuInflater();
1151 inflater.inflate(R.menu.browser, menu);
1152 mMenu = menu;
1153 updateInLoadMenuItems();
1154 return true;
1155 }
1156
1157 /**
1158 * As the menu can be open when loading state changes
1159 * we must manually update the state of the stop/reload menu
1160 * item
1161 */
1162 private void updateInLoadMenuItems() {
1163 if (mMenu == null) {
1164 return;
1165 }
Michael Kolbe0a36662010-06-29 10:37:12 -07001166 MenuItem dest = mMenu.findItem(R.id.stop_reload_menu_id);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001167 MenuItem src = mInLoad ?
1168 mMenu.findItem(R.id.stop_menu_id):
Michael Kolbe0a36662010-06-29 10:37:12 -07001169 mMenu.findItem(R.id.reload_menu_id);
1170 if (src != null) {
1171 dest.setIcon(src.getIcon());
1172 dest.setTitle(src.getTitle());
1173 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001174 }
1175
1176 @Override
1177 public boolean onContextItemSelected(MenuItem item) {
1178 // chording is not an issue with context menus, but we use the same
1179 // options selector, so set mCanChord to true so we can access them.
1180 mCanChord = true;
1181 int id = item.getItemId();
Leon Scroggins96afcb12009-12-10 12:35:56 -05001182 boolean result = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001183 switch (id) {
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001184 // For the context menu from the title bar
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001185 case R.id.title_bar_copy_page_url:
Leon Scroggins96afcb12009-12-10 12:35:56 -05001186 Tab currentTab = mTabControl.getCurrentTab();
1187 if (null == currentTab) {
1188 result = false;
1189 break;
1190 }
1191 WebView mainView = currentTab.getWebView();
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001192 if (null == mainView) {
Leon Scroggins96afcb12009-12-10 12:35:56 -05001193 result = false;
1194 break;
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001195 }
Leon Scroggins96afcb12009-12-10 12:35:56 -05001196 copy(mainView.getUrl());
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001197 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001198 // -- Browser context menu
1199 case R.id.open_context_menu_id:
The Android Open Source Project0c908882009-03-03 19:32:16 -08001200 case R.id.bookmark_context_menu_id:
1201 case R.id.save_link_context_menu_id:
1202 case R.id.share_link_context_menu_id:
1203 case R.id.copy_link_context_menu_id:
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001204 final WebView webView = getTopWindow();
1205 if (null == webView) {
Leon Scroggins96afcb12009-12-10 12:35:56 -05001206 result = false;
1207 break;
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001208 }
1209 final HashMap hrefMap = new HashMap();
1210 hrefMap.put("webview", webView);
1211 final Message msg = mHandler.obtainMessage(
1212 FOCUS_NODE_HREF, id, 0, hrefMap);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001213 webView.requestFocusNodeHref(msg);
1214 break;
1215
1216 default:
1217 // For other context menus
Leon Scroggins96afcb12009-12-10 12:35:56 -05001218 result = onOptionsItemSelected(item);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001219 }
1220 mCanChord = false;
Leon Scroggins96afcb12009-12-10 12:35:56 -05001221 return result;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001222 }
1223
1224 private Bundle createGoogleSearchSourceBundle(String source) {
1225 Bundle bundle = new Bundle();
Bjorn Bringert10d1cca2010-02-10 14:22:12 +00001226 bundle.putString(Search.SOURCE, source);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001227 return bundle;
1228 }
1229
Leon Scroggins8ad29922010-02-16 12:33:55 -05001230 /* package */ void editUrl() {
Leon Scroggins68579392009-09-15 15:31:54 -04001231 if (mOptionsMenuOpen) closeOptionsMenu();
Leon Scroggins5bbe9802009-07-31 13:10:55 -04001232 String url = (getTopWindow() == null) ? null : getTopWindow().getUrl();
Grace Kloba83f47342009-07-20 10:44:31 -07001233 startSearch(mSettings.getHomePage().equals(url) ? null : url, true,
Leon Scroggins8ad29922010-02-16 12:33:55 -05001234 null, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001235 }
1236
Leon Scroggins8ad29922010-02-16 12:33:55 -05001237 /**
1238 * Overriding this to insert a local information bundle
1239 */
The Android Open Source Project0c908882009-03-03 19:32:16 -08001240 @Override
1241 public void startSearch(String initialQuery, boolean selectInitialQuery,
1242 Bundle appSearchData, boolean globalSearch) {
1243 if (appSearchData == null) {
1244 appSearchData = createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_TYPE);
1245 }
1246 super.startSearch(initialQuery, selectInitialQuery, appSearchData, globalSearch);
1247 }
1248
Leon Scroggins1f005d32009-08-10 17:36:42 -04001249 /**
1250 * Switch tabs. Called by the TitleBarSet when sliding the title bar
1251 * results in changing tabs.
Leon Scroggins160a7e72009-08-14 18:28:01 -04001252 * @param index Index of the tab to change to, as defined by
1253 * mTabControl.getTabIndex(Tab t).
1254 * @return boolean True if we successfully switched to a different tab. If
1255 * the indexth tab is null, or if that tab is the same as
1256 * the current one, return false.
Leon Scroggins1f005d32009-08-10 17:36:42 -04001257 */
Leon Scroggins160a7e72009-08-14 18:28:01 -04001258 /* package */ boolean switchToTab(int index) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001259 Tab tab = mTabControl.getTab(index);
1260 Tab currentTab = mTabControl.getCurrentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04001261 if (tab == null || tab == currentTab) {
Leon Scroggins160a7e72009-08-14 18:28:01 -04001262 return false;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001263 }
1264 if (currentTab != null) {
1265 // currentTab may be null if it was just removed. In that case,
1266 // we do not need to remove it
1267 removeTabFromContentView(currentTab);
1268 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001269 mTabControl.setCurrentTab(tab);
1270 attachTabToContentView(tab);
Grace Klobaeb6eef42009-09-15 17:56:32 -07001271 resetTitleIconAndProgress();
1272 updateLockIconToLatest();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001273 return true;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001274 }
1275
Grace Kloba22ac16e2009-10-07 18:00:23 -07001276 /* package */ Tab openTabToHomePage() {
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001277 return openTabAndShow(mSettings.getHomePage(), false, null);
1278 }
1279
Leon Scroggins1f005d32009-08-10 17:36:42 -04001280 /* package */ void closeCurrentWindow() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001281 final Tab current = mTabControl.getCurrentTab();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001282 if (mTabControl.getTabCount() == 1) {
Leon Scroggins30444232009-09-04 18:36:20 -04001283 // This is the last tab. Open a new one, with the home
1284 // page and close the current one.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001285 openTabToHomePage();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001286 closeTab(current);
Leon Scroggins160a7e72009-08-14 18:28:01 -04001287 return;
1288 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07001289 final Tab parent = current.getParentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04001290 int indexToShow = -1;
1291 if (parent != null) {
1292 indexToShow = mTabControl.getTabIndex(parent);
1293 } else {
Leon Scroggins160a7e72009-08-14 18:28:01 -04001294 final int currentIndex = mTabControl.getCurrentIndex();
1295 // Try to move to the tab to the right
1296 indexToShow = currentIndex + 1;
1297 if (indexToShow > mTabControl.getTabCount() - 1) {
1298 // Try to move to the tab to the left
1299 indexToShow = currentIndex - 1;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001300 }
1301 }
Leon Scroggins160a7e72009-08-14 18:28:01 -04001302 if (switchToTab(indexToShow)) {
1303 // Close window
1304 closeTab(current);
1305 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001306 }
1307
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001308 private ActiveTabsPage mActiveTabsPage;
1309
1310 /**
1311 * Remove the active tabs page.
1312 * @param needToAttach If true, the active tabs page did not attach a tab
1313 * to the content view, so we need to do that here.
1314 */
1315 /* package */ void removeActiveTabPage(boolean needToAttach) {
1316 mContentView.removeView(mActiveTabsPage);
Leon Scrogginsd746a942010-05-19 13:21:44 -04001317 mTitleBar.setVisibility(View.VISIBLE);
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001318 mActiveTabsPage = null;
1319 mMenuState = R.id.MAIN_MENU;
1320 if (needToAttach) {
1321 attachTabToContentView(mTabControl.getCurrentTab());
1322 }
1323 getTopWindow().requestFocus();
1324 }
1325
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04001326 @Override
1327 public ActionMode onStartActionMode(ActionMode.Callback callback) {
1328 ActionMode mode = super.onStartActionMode(callback);
1329 if (callback instanceof FindActionModeCallback
1330 || callback instanceof SelectActionModeCallback) {
1331 // For find and select, hide extra title bars. They will
1332 // be replaced in onEndActionMode.
1333 Tab tab = mTabControl.getCurrentTab();
1334 if (tab.getSubWebView() == null) {
1335 // If the find or select is being performed on the main webview,
1336 // remove the embedded title bar.
1337 WebView mainView = tab.getWebView();
1338 if (mainView != null) {
1339 mainView.setEmbeddedTitleBar(null);
1340 }
Cary Clark01cfcdd2010-06-04 16:36:45 -04001341 }
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04001342 hideFakeTitleBar();
1343 mActionMode = mode;
1344 } else {
1345 // Do not store other ActionModes, since we are unable to determine
1346 // when they finish.
1347 mActionMode = null;
Cary Clark01cfcdd2010-06-04 16:36:45 -04001348 }
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04001349 return mode;
Cary Clark01cfcdd2010-06-04 16:36:45 -04001350 }
1351
The Android Open Source Project0c908882009-03-03 19:32:16 -08001352 @Override
1353 public boolean onOptionsItemSelected(MenuItem item) {
Michael Kolbed217742010-08-10 17:52:34 -07001354 // check the action bar button before mCanChord check, as the prepare call
1355 // doesn't come for action bar buttons
1356 if (item.getItemId() == R.id.newtab) {
1357 bookmarksOrHistoryPicker(false, true);
1358 return true;
1359 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001360 if (!mCanChord) {
1361 // The user has already fired a shortcut with this hold down of the
1362 // menu key.
1363 return false;
1364 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001365 if (null == getTopWindow()) {
Leon Scroggins0d7ae0e2009-06-05 11:04:45 -04001366 return false;
1367 }
Grace Kloba6ee9c492009-07-13 10:04:34 -07001368 if (mMenuIsDown) {
1369 // The shortcut action consumes the MENU. Even if it is still down,
1370 // it won't trigger the next shortcut action. In the case of the
1371 // shortcut action triggering a new activity, like Bookmarks, we
1372 // won't get onKeyUp for MENU. So it is important to reset it here.
1373 mMenuIsDown = false;
1374 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001375 switch (item.getItemId()) {
1376 // -- Main menu
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001377 case R.id.new_tab_menu_id:
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001378 openTabToHomePage();
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001379 break;
1380
Leon Scroggins64b80f32009-08-07 12:03:34 -04001381 case R.id.goto_menu_id:
Leon Scroggins8ad29922010-02-16 12:33:55 -05001382 editUrl();
Leon Scrogginsb3a5bed2009-09-28 11:21:56 -04001383 break;
1384
1385 case R.id.bookmarks_menu_id:
Michael Kolb68792c82010-08-09 16:39:18 -07001386 bookmarksOrHistoryPicker(false, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001387 break;
1388
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001389 case R.id.active_tabs_menu_id:
1390 mActiveTabsPage = new ActiveTabsPage(this, mTabControl);
1391 removeTabFromContentView(mTabControl.getCurrentTab());
Leon Scrogginsd746a942010-05-19 13:21:44 -04001392 mTitleBar.setVisibility(View.GONE);
Leon Scroggins43de6162009-09-14 19:59:58 -04001393 hideFakeTitleBar();
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001394 mContentView.addView(mActiveTabsPage, COVER_SCREEN_PARAMS);
1395 mActiveTabsPage.requestFocus();
1396 mMenuState = EMPTY_MENU;
1397 break;
1398
Leon Scroggins1f005d32009-08-10 17:36:42 -04001399 case R.id.add_bookmark_menu_id:
Leon Scroggins571b3762010-05-26 10:25:01 -04001400 bookmarkCurrentPage();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001401 break;
1402
1403 case R.id.stop_reload_menu_id:
1404 if (mInLoad) {
1405 stopLoading();
1406 } else {
1407 getTopWindow().reload();
1408 }
1409 break;
1410
1411 case R.id.back_menu_id:
1412 getTopWindow().goBack();
1413 break;
1414
1415 case R.id.forward_menu_id:
1416 getTopWindow().goForward();
1417 break;
1418
1419 case R.id.close_menu_id:
1420 // Close the subwindow if it exists.
1421 if (mTabControl.getCurrentSubWindow() != null) {
1422 dismissSubWindow(mTabControl.getCurrentTab());
1423 break;
1424 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001425 closeCurrentWindow();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001426 break;
1427
1428 case R.id.homepage_menu_id:
Grace Kloba22ac16e2009-10-07 18:00:23 -07001429 Tab current = mTabControl.getCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001430 if (current != null) {
1431 dismissSubWindow(current);
Leon Scroggins92472e82010-02-17 16:32:28 -05001432 loadUrl(current.getWebView(), mSettings.getHomePage());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001433 }
1434 break;
1435
1436 case R.id.preferences_menu_id:
1437 Intent intent = new Intent(this,
1438 BrowserPreferencesPage.class);
Leon Scrogginsd5304942009-12-10 16:11:39 -05001439 intent.putExtra(BrowserPreferencesPage.CURRENT_PAGE,
1440 getTopWindow().getUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001441 startActivityForResult(intent, PREFERENCES_PAGE);
1442 break;
1443
1444 case R.id.find_menu_id:
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04001445 showFindDialog(null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001446 break;
1447
Elliott Slaughter0ced08c2010-06-30 11:40:42 -07001448 case R.id.save_webarchive_menu_id:
1449 if (LOGD_ENABLED) {
1450 Log.d(LOGTAG, "Save as Web Archive");
1451 }
1452 String directory = getExternalFilesDir(null).getAbsolutePath() + File.separator;
1453 getTopWindow().saveWebArchive(directory, true, new ValueCallback<String>() {
1454 @Override
1455 public void onReceiveValue(String value) {
1456 if (value != null) {
1457 Toast.makeText(BrowserActivity.this, R.string.webarchive_saved, Toast.LENGTH_SHORT).show();
1458 } else {
1459 Toast.makeText(BrowserActivity.this, R.string.webarchive_failed, Toast.LENGTH_SHORT).show();
1460 }
1461 }
1462 });
1463 break;
1464
The Android Open Source Project0c908882009-03-03 19:32:16 -08001465 case R.id.page_info_menu_id:
1466 showPageInfo(mTabControl.getCurrentTab(), false);
1467 break;
1468
1469 case R.id.classic_history_menu_id:
Michael Kolb68792c82010-08-09 16:39:18 -07001470 bookmarksOrHistoryPicker(true, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001471 break;
1472
Leon Scroggins96afcb12009-12-10 12:35:56 -05001473 case R.id.title_bar_share_page_url:
The Android Open Source Project0c908882009-03-03 19:32:16 -08001474 case R.id.share_page_menu_id:
Leon Scroggins96afcb12009-12-10 12:35:56 -05001475 Tab currentTab = mTabControl.getCurrentTab();
1476 if (null == currentTab) {
1477 mCanChord = false;
1478 return false;
1479 }
1480 currentTab.populatePickerData();
1481 sharePage(this, currentTab.getTitle(),
1482 currentTab.getUrl(), currentTab.getFavicon(),
Ben Murdoch87cc65d2010-06-29 20:34:10 +01001483 createScreenshot(currentTab.getWebView(), getDesiredThumbnailWidth(this),
1484 getDesiredThumbnailHeight(this)));
The Android Open Source Project0c908882009-03-03 19:32:16 -08001485 break;
1486
1487 case R.id.dump_nav_menu_id:
1488 getTopWindow().debugDump();
1489 break;
1490
Andrei Popescu7a8b88b2010-02-02 00:30:38 +00001491 case R.id.dump_counters_menu_id:
1492 getTopWindow().dumpV8Counters();
1493 break;
1494
The Android Open Source Project0c908882009-03-03 19:32:16 -08001495 case R.id.zoom_in_menu_id:
1496 getTopWindow().zoomIn();
1497 break;
1498
1499 case R.id.zoom_out_menu_id:
1500 getTopWindow().zoomOut();
1501 break;
1502
1503 case R.id.view_downloads_menu_id:
1504 viewDownloads(null);
1505 break;
1506
The Android Open Source Project0c908882009-03-03 19:32:16 -08001507 case R.id.window_one_menu_id:
1508 case R.id.window_two_menu_id:
1509 case R.id.window_three_menu_id:
1510 case R.id.window_four_menu_id:
1511 case R.id.window_five_menu_id:
1512 case R.id.window_six_menu_id:
1513 case R.id.window_seven_menu_id:
1514 case R.id.window_eight_menu_id:
1515 {
1516 int menuid = item.getItemId();
1517 for (int id = 0; id < WINDOW_SHORTCUT_ID_ARRAY.length; id++) {
1518 if (WINDOW_SHORTCUT_ID_ARRAY[id] == menuid) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001519 Tab desiredTab = mTabControl.getTab(id);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001520 if (desiredTab != null &&
1521 desiredTab != mTabControl.getCurrentTab()) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001522 switchToTab(id);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001523 }
1524 break;
1525 }
1526 }
1527 }
1528 break;
1529
1530 default:
1531 if (!super.onOptionsItemSelected(item)) {
1532 return false;
1533 }
1534 // Otherwise fall through.
1535 }
1536 mCanChord = false;
1537 return true;
1538 }
1539
Leon Scroggins571b3762010-05-26 10:25:01 -04001540 /* package */ void bookmarkCurrentPage() {
1541 Intent i = new Intent(BrowserActivity.this,
1542 AddBookmarkPage.class);
1543 WebView w = getTopWindow();
1544 i.putExtra("url", w.getUrl());
1545 i.putExtra("title", w.getTitle());
1546 i.putExtra("touch_icon_url", w.getTouchIconUrl());
Ben Murdoch87cc65d2010-06-29 20:34:10 +01001547 i.putExtra("thumbnail", createScreenshot(w, getDesiredThumbnailWidth(this),
1548 getDesiredThumbnailHeight(this)));
Ben Murdocheecb4e62010-07-06 16:30:38 +01001549 i.putExtra("url_editable", false);
Leon Scroggins571b3762010-05-26 10:25:01 -04001550 startActivity(i);
1551 }
1552
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04001553 /*
1554 * True if a custom ActionMode (i.e. find or select) is in use.
1555 */
1556 private boolean isInCustomActionMode() {
1557 return mActionMode != null;
Cary Clark01cfcdd2010-06-04 16:36:45 -04001558 }
1559
1560 /*
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04001561 * End the current ActionMode. Only works for find and select.
Cary Clark01cfcdd2010-06-04 16:36:45 -04001562 */
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04001563 void endActionMode() {
1564 if (mActionMode != null) {
1565 mActionMode.finish();
1566 }
1567 }
1568
1569 /*
1570 * Called by find and select when they are finished. Replace title bars
1571 * as necessary.
1572 */
1573 public void onEndActionMode() {
1574 if (!isInCustomActionMode()) return;
Michael Kolba2b2ba82010-08-04 17:54:03 -07001575 // If the Find was being performed in the main WebView, replace the
1576 // embedded title bar.
1577 Tab currentTab = mTabControl.getCurrentTab();
1578 if (currentTab.getSubWebView() == null) {
1579 WebView mainView = currentTab.getWebView();
1580 if (mainView != null) {
1581 mainView.setEmbeddedTitleBar(mTitleBar);
Leon Scroggins79e36d92010-04-29 16:01:46 +01001582 }
1583 }
Leon Scroggins79e36d92010-04-29 16:01:46 +01001584 if (mInLoad) {
1585 // The title bar was hidden, because otherwise it would cover up the
Michael Kolba2b2ba82010-08-04 17:54:03 -07001586 // find or select dialog. Now that the dialog has been removed,
Cary Clark01cfcdd2010-06-04 16:36:45 -04001587 // show the fake title bar once again.
Leon Scroggins79e36d92010-04-29 16:01:46 +01001588 showFakeTitleBar();
1589 }
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04001590 mActionMode = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001591 }
1592
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04001593 private FindActionModeCallback mFindCallback;
1594 private SelectActionModeCallback mSelectCallback;
1595
1596 // For select and find, we keep track of the ActionMode so that
1597 // finish() can be called as desired.
1598 private ActionMode mActionMode;
1599
1600 /*
1601 * Open the find ActionMode.
1602 * @param text If non null, will be placed in find to be searched for.
1603 */
1604 public void showFindDialog(String text) {
1605 if (null == mFindCallback) {
1606 mFindCallback = new FindActionModeCallback(this);
Cary Clark01cfcdd2010-06-04 16:36:45 -04001607 }
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04001608 WebView webView = getTopWindow();
1609 webView.setFindIsUp(true);
1610 mFindCallback.setWebView(webView);
1611 startActionMode(mFindCallback);
1612 if (text != null) mFindCallback.setText(text);
Cary Clark01cfcdd2010-06-04 16:36:45 -04001613 }
1614
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04001615 /*
1616 * Show the select ActionMode.
1617 */
Cary Clark01cfcdd2010-06-04 16:36:45 -04001618 public void showSelectDialog() {
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04001619 if (null == mSelectCallback) {
1620 mSelectCallback = new SelectActionModeCallback(this);
Cary Clark01cfcdd2010-06-04 16:36:45 -04001621 }
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04001622 WebView webView = getTopWindow();
1623 webView.setUpSelect();
1624 mSelectCallback.setWebView(webView);
1625 startActionMode(mSelectCallback);
Cary Clark01cfcdd2010-06-04 16:36:45 -04001626 }
1627
Grace Kloba22ac16e2009-10-07 18:00:23 -07001628 @Override
1629 public boolean onPrepareOptionsMenu(Menu menu) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001630 // This happens when the user begins to hold down the menu key, so
1631 // allow them to chord to get a shortcut.
1632 mCanChord = true;
1633 // Note: setVisible will decide whether an item is visible; while
1634 // setEnabled() will decide whether an item is enabled, which also means
1635 // whether the matching shortcut key will function.
1636 super.onPrepareOptionsMenu(menu);
1637 switch (mMenuState) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001638 case EMPTY_MENU:
1639 if (mCurrentMenuState != mMenuState) {
1640 menu.setGroupVisible(R.id.MAIN_MENU, false);
1641 menu.setGroupEnabled(R.id.MAIN_MENU, false);
1642 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001643 }
1644 break;
1645 default:
1646 if (mCurrentMenuState != mMenuState) {
1647 menu.setGroupVisible(R.id.MAIN_MENU, true);
1648 menu.setGroupEnabled(R.id.MAIN_MENU, true);
1649 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001650 }
1651 final WebView w = getTopWindow();
1652 boolean canGoBack = false;
1653 boolean canGoForward = false;
1654 boolean isHome = false;
1655 if (w != null) {
1656 canGoBack = w.canGoBack();
1657 canGoForward = w.canGoForward();
1658 isHome = mSettings.getHomePage().equals(w.getUrl());
1659 }
1660 final MenuItem back = menu.findItem(R.id.back_menu_id);
1661 back.setEnabled(canGoBack);
1662
1663 final MenuItem home = menu.findItem(R.id.homepage_menu_id);
1664 home.setEnabled(!isHome);
1665
Michael Kolbe0a36662010-06-29 10:37:12 -07001666 final MenuItem forward = menu.findItem(R.id.forward_menu_id);
1667 forward.setEnabled(canGoForward);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001668
Michael Kolbed217742010-08-10 17:52:34 -07001669 if (!mXLargeScreenSize) {
1670 final MenuItem newtab = menu.findItem(R.id.new_tab_menu_id);
1671 newtab.setEnabled(mTabControl.canCreateNewTab());
1672 }
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001673
The Android Open Source Project0c908882009-03-03 19:32:16 -08001674 // decide whether to show the share link option
1675 PackageManager pm = getPackageManager();
1676 Intent send = new Intent(Intent.ACTION_SEND);
1677 send.setType("text/plain");
1678 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1679 menu.findItem(R.id.share_page_menu_id).setVisible(ri != null);
1680
The Android Open Source Project0c908882009-03-03 19:32:16 -08001681 boolean isNavDump = mSettings.isNavDump();
1682 final MenuItem nav = menu.findItem(R.id.dump_nav_menu_id);
1683 nav.setVisible(isNavDump);
1684 nav.setEnabled(isNavDump);
Andrei Popescu7a8b88b2010-02-02 00:30:38 +00001685
1686 boolean showDebugSettings = mSettings.showDebugSettings();
1687 final MenuItem counter = menu.findItem(R.id.dump_counters_menu_id);
1688 counter.setVisible(showDebugSettings);
1689 counter.setEnabled(showDebugSettings);
1690
The Android Open Source Project0c908882009-03-03 19:32:16 -08001691 break;
1692 }
1693 mCurrentMenuState = mMenuState;
1694 return true;
1695 }
1696
1697 @Override
1698 public void onCreateContextMenu(ContextMenu menu, View v,
1699 ContextMenuInfo menuInfo) {
Leon Scroggins571b3762010-05-26 10:25:01 -04001700 if (v instanceof TitleBarBase) {
Leon Scroggins4e9f89b2010-02-22 16:54:14 -05001701 return;
1702 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001703 WebView webview = (WebView) v;
1704 WebView.HitTestResult result = webview.getHitTestResult();
1705 if (result == null) {
1706 return;
1707 }
1708
1709 int type = result.getType();
1710 if (type == WebView.HitTestResult.UNKNOWN_TYPE) {
1711 Log.w(LOGTAG,
1712 "We should not show context menu when nothing is touched");
1713 return;
1714 }
1715 if (type == WebView.HitTestResult.EDIT_TEXT_TYPE) {
1716 // let TextView handles context menu
1717 return;
1718 }
1719
1720 // Note, http://b/issue?id=1106666 is requesting that
1721 // an inflated menu can be used again. This is not available
1722 // yet, so inflate each time (yuk!)
1723 MenuInflater inflater = getMenuInflater();
1724 inflater.inflate(R.menu.browsercontext, menu);
1725
1726 // Show the correct menu group
Leon Scroggins III9e997c72010-05-26 13:25:16 -04001727 final String extra = result.getExtra();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001728 menu.setGroupVisible(R.id.PHONE_MENU,
1729 type == WebView.HitTestResult.PHONE_TYPE);
1730 menu.setGroupVisible(R.id.EMAIL_MENU,
1731 type == WebView.HitTestResult.EMAIL_TYPE);
1732 menu.setGroupVisible(R.id.GEO_MENU,
1733 type == WebView.HitTestResult.GEO_TYPE);
1734 menu.setGroupVisible(R.id.IMAGE_MENU,
1735 type == WebView.HitTestResult.IMAGE_TYPE
1736 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1737 menu.setGroupVisible(R.id.ANCHOR_MENU,
1738 type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1739 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1740
1741 // Setup custom handling depending on the type
1742 switch (type) {
1743 case WebView.HitTestResult.PHONE_TYPE:
1744 menu.setHeaderTitle(Uri.decode(extra));
1745 menu.findItem(R.id.dial_context_menu_id).setIntent(
1746 new Intent(Intent.ACTION_VIEW, Uri
1747 .parse(WebView.SCHEME_TEL + extra)));
1748 Intent addIntent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
1749 addIntent.putExtra(Insert.PHONE, Uri.decode(extra));
Cary Clark5e335a32009-09-22 14:53:11 -04001750 addIntent.setType(ContactsContract.Contacts.CONTENT_ITEM_TYPE);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001751 menu.findItem(R.id.add_contact_context_menu_id).setIntent(
1752 addIntent);
1753 menu.findItem(R.id.copy_phone_context_menu_id).setOnMenuItemClickListener(
1754 new Copy(extra));
1755 break;
1756
1757 case WebView.HitTestResult.EMAIL_TYPE:
1758 menu.setHeaderTitle(extra);
1759 menu.findItem(R.id.email_context_menu_id).setIntent(
1760 new Intent(Intent.ACTION_VIEW, Uri
1761 .parse(WebView.SCHEME_MAILTO + extra)));
1762 menu.findItem(R.id.copy_mail_context_menu_id).setOnMenuItemClickListener(
1763 new Copy(extra));
1764 break;
1765
1766 case WebView.HitTestResult.GEO_TYPE:
1767 menu.setHeaderTitle(extra);
1768 menu.findItem(R.id.map_context_menu_id).setIntent(
1769 new Intent(Intent.ACTION_VIEW, Uri
1770 .parse(WebView.SCHEME_GEO
1771 + URLEncoder.encode(extra))));
1772 menu.findItem(R.id.copy_geo_context_menu_id).setOnMenuItemClickListener(
1773 new Copy(extra));
1774 break;
1775
1776 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1777 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
1778 TextView titleView = (TextView) LayoutInflater.from(this)
1779 .inflate(android.R.layout.browser_link_context_header,
1780 null);
1781 titleView.setText(extra);
1782 menu.setHeaderView(titleView);
1783 // decide whether to show the open link in new tab option
Leon Scroggins III9e997c72010-05-26 13:25:16 -04001784 boolean showNewTab = mTabControl.canCreateNewTab();
1785 MenuItem newTabItem
1786 = menu.findItem(R.id.open_newtab_context_menu_id);
1787 newTabItem.setVisible(showNewTab);
1788 if (showNewTab) {
1789 newTabItem.setOnMenuItemClickListener(
1790 new MenuItem.OnMenuItemClickListener() {
1791 public boolean onMenuItemClick(MenuItem item) {
1792 final Tab parent = mTabControl.getCurrentTab();
Michael Kolb68792c82010-08-09 16:39:18 -07001793 final Tab newTab = openTab(extra, false);
Leon Scroggins III9e997c72010-05-26 13:25:16 -04001794 if (newTab != parent) {
1795 parent.addChildTab(newTab);
1796 }
1797 return true;
1798 }
1799 });
1800 }
Ben Murdochde353622009-10-12 10:29:00 +01001801 menu.findItem(R.id.bookmark_context_menu_id).setVisible(
1802 Bookmarks.urlHasAcceptableScheme(extra));
The Android Open Source Project0c908882009-03-03 19:32:16 -08001803 PackageManager pm = getPackageManager();
1804 Intent send = new Intent(Intent.ACTION_SEND);
1805 send.setType("text/plain");
1806 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1807 menu.findItem(R.id.share_link_context_menu_id).setVisible(ri != null);
1808 if (type == WebView.HitTestResult.SRC_ANCHOR_TYPE) {
1809 break;
1810 }
1811 // otherwise fall through to handle image part
1812 case WebView.HitTestResult.IMAGE_TYPE:
1813 if (type == WebView.HitTestResult.IMAGE_TYPE) {
1814 menu.setHeaderTitle(extra);
1815 }
1816 menu.findItem(R.id.view_image_context_menu_id).setIntent(
1817 new Intent(Intent.ACTION_VIEW, Uri.parse(extra)));
1818 menu.findItem(R.id.download_context_menu_id).
1819 setOnMenuItemClickListener(new Download(extra));
Ben Murdoch4f75ba22009-10-27 11:48:28 +00001820 menu.findItem(R.id.set_wallpaper_context_menu_id).
1821 setOnMenuItemClickListener(new SetAsWallpaper(extra));
The Android Open Source Project0c908882009-03-03 19:32:16 -08001822 break;
1823
1824 default:
1825 Log.w(LOGTAG, "We should not get here.");
1826 break;
1827 }
Leon Scrogginsb2b19f52009-10-09 16:10:00 -04001828 hideFakeTitleBar();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001829 }
1830
The Android Open Source Project0c908882009-03-03 19:32:16 -08001831 // Attach the given tab to the content view.
Grace Klobac928c302009-09-17 11:51:21 -07001832 // this should only be called for the current tab.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001833 private void attachTabToContentView(Tab t) {
Steve Block2bc69912009-07-30 14:45:13 +01001834 // Attach the container that contains the main WebView and any other UI
1835 // associated with the tab.
Patrick Scottd0119532009-09-17 08:00:31 -04001836 t.attachTabToContentView(mContentView);
Ben Murdochbff2d602009-07-01 20:19:05 +01001837
1838 if (mShouldShowErrorConsole) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001839 ErrorConsoleView errorConsole = t.getErrorConsole(true);
Ben Murdochbff2d602009-07-01 20:19:05 +01001840 if (errorConsole.numberOfErrors() == 0) {
1841 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
1842 } else {
1843 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
1844 }
1845
1846 mErrorConsoleContainer.addView(errorConsole,
Romain Guy15b8ec62010-01-08 15:06:43 -08001847 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
Ben Murdochbff2d602009-07-01 20:19:05 +01001848 ViewGroup.LayoutParams.WRAP_CONTENT));
1849 }
1850
Michael Kolba2b2ba82010-08-04 17:54:03 -07001851 WebView view = t.getWebView();
1852 view.setEmbeddedTitleBar(mTitleBar);
Leon Scroggins58d56c62010-01-28 15:12:40 -05001853 if (t.isInVoiceSearchMode()) {
1854 showVoiceTitleBar(t.getVoiceDisplayTitle());
1855 } else {
1856 revertVoiceTitleBar();
1857 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001858 // Request focus on the top window.
1859 t.getTopWindow().requestFocus();
Michael Kolba2b2ba82010-08-04 17:54:03 -07001860 if (mTabControl.getTabChangeListener() != null) {
1861 mTabControl.getTabChangeListener().onCurrentTab(t);
1862 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001863 }
1864
1865 // Attach a sub window to the main WebView of the given tab.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001866 void attachSubWindow(Tab t) {
Patrick Scottd0119532009-09-17 08:00:31 -04001867 t.attachSubWindow(mContentView);
1868 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001869 }
1870
1871 // Remove the given tab from the content view.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001872 private void removeTabFromContentView(Tab t) {
Steve Block2bc69912009-07-30 14:45:13 +01001873 // Remove the container that contains the main WebView.
Patrick Scottd0119532009-09-17 08:00:31 -04001874 t.removeTabFromContentView(mContentView);
Ben Murdochbff2d602009-07-01 20:19:05 +01001875
Grace Kloba22ac16e2009-10-07 18:00:23 -07001876 ErrorConsoleView errorConsole = t.getErrorConsole(false);
1877 if (errorConsole != null) {
1878 mErrorConsoleContainer.removeView(errorConsole);
Ben Murdochbff2d602009-07-01 20:19:05 +01001879 }
1880
Michael Kolba2b2ba82010-08-04 17:54:03 -07001881 WebView view = t.getWebView();
1882 if (view != null) {
1883 view.setEmbeddedTitleBar(null);
Leon Scrogginsbb85b902009-09-14 19:27:20 -04001884 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001885 }
1886
1887 // Remove the sub window if it exists. Also called by TabControl when the
1888 // user clicks the 'X' to dismiss a sub window.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001889 /* package */ void dismissSubWindow(Tab t) {
Patrick Scottd0119532009-09-17 08:00:31 -04001890 t.removeSubWindow(mContentView);
Grace Kloba22ac16e2009-10-07 18:00:23 -07001891 // dismiss the subwindow. This will destroy the WebView.
1892 t.dismissSubWindow();
Patrick Scottd0119532009-09-17 08:00:31 -04001893 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001894 }
1895
Leon Scroggins1f005d32009-08-10 17:36:42 -04001896 // A wrapper function of {@link #openTabAndShow(UrlData, boolean, String)}
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07001897 // that accepts url as string.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001898 private Tab openTabAndShow(String url, boolean closeOnExit, String appId) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001899 return openTabAndShow(new UrlData(url), closeOnExit, appId);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001900 }
1901
1902 // This method does a ton of stuff. It will attempt to create a new tab
1903 // if we haven't reached MAX_TABS. Otherwise it uses the current tab. If
Leon Scroggins1f005d32009-08-10 17:36:42 -04001904 // url isn't null, it will load the given url.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001905 /* package */Tab openTabAndShow(UrlData urlData, boolean closeOnExit,
1906 String appId) {
1907 final Tab currentTab = mTabControl.getCurrentTab();
1908 if (mTabControl.canCreateNewTab()) {
1909 final Tab tab = mTabControl.createNewTab(closeOnExit, appId,
Elliott Slaughterf0f03952010-07-14 18:10:36 -07001910 urlData.mUrl, false);
Leon Scroggins1f005d32009-08-10 17:36:42 -04001911 WebView webview = tab.getWebView();
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001912 // If the last tab was removed from the active tabs page, currentTab
1913 // will be null.
1914 if (currentTab != null) {
1915 removeTabFromContentView(currentTab);
1916 }
Patrick Scott8bbd69f2009-08-14 13:35:53 -04001917 // We must set the new tab as the current tab to reflect the old
1918 // animation behavior.
1919 mTabControl.setCurrentTab(tab);
Grace Klobaeb6eef42009-09-15 17:56:32 -07001920 attachTabToContentView(tab);
Leon Scroggins160a7e72009-08-14 18:28:01 -04001921 if (!urlData.isEmpty()) {
Patrick Scott9d53da02010-02-19 10:19:01 -05001922 loadUrlDataIn(tab, urlData);
Leon Scroggins1f005d32009-08-10 17:36:42 -04001923 }
1924 return tab;
1925 } else {
1926 // Get rid of the subwindow if it exists
1927 dismissSubWindow(currentTab);
1928 if (!urlData.isEmpty()) {
1929 // Load the given url.
Patrick Scott9d53da02010-02-19 10:19:01 -05001930 loadUrlDataIn(currentTab, urlData);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001931 }
Leon Scroggins58d56c62010-01-28 15:12:40 -05001932 return currentTab;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001933 }
1934 }
1935
Michael Kolb68792c82010-08-09 16:39:18 -07001936 private Tab openTab(String url, boolean forceForeground) {
1937 if (mSettings.openInBackground() && !forceForeground) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001938 Tab t = mTabControl.createNewTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001939 if (t != null) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001940 WebView view = t.getWebView();
Leon Scroggins92472e82010-02-17 16:32:28 -05001941 loadUrl(view, url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001942 }
Grace Klobac9181842009-04-14 08:53:22 -07001943 return t;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001944 } else {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001945 return openTabAndShow(url, false, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001946 }
1947 }
1948
Elliott Slaughterf0f03952010-07-14 18:10:36 -07001949 /* package */ Tab openIncognitoTab() {
1950 if (mTabControl.canCreateNewTab()) {
1951 Tab currentTab = mTabControl.getCurrentTab();
1952 Tab tab = mTabControl.createNewTab(false, null, null, true);
1953 if (currentTab != null) {
1954 removeTabFromContentView(currentTab);
1955 }
1956 mTabControl.setCurrentTab(tab);
1957 attachTabToContentView(tab);
1958 return tab;
1959 }
1960 return null;
1961 }
1962
The Android Open Source Project0c908882009-03-03 19:32:16 -08001963 private class Copy implements OnMenuItemClickListener {
1964 private CharSequence mText;
1965
1966 public boolean onMenuItemClick(MenuItem item) {
1967 copy(mText);
1968 return true;
1969 }
1970
1971 public Copy(CharSequence toCopy) {
1972 mText = toCopy;
1973 }
1974 }
1975
1976 private class Download implements OnMenuItemClickListener {
1977 private String mText;
1978
1979 public boolean onMenuItemClick(MenuItem item) {
1980 onDownloadStartNoStream(mText, null, null, null, -1);
1981 return true;
1982 }
1983
1984 public Download(String toDownload) {
1985 mText = toDownload;
1986 }
1987 }
1988
Ben Murdoch4f75ba22009-10-27 11:48:28 +00001989 private class SetAsWallpaper extends Thread implements
1990 OnMenuItemClickListener, DialogInterface.OnCancelListener {
1991 private URL mUrl;
1992 private ProgressDialog mWallpaperProgress;
1993 private boolean mCanceled = false;
1994
1995 public SetAsWallpaper(String url) {
1996 try {
1997 mUrl = new URL(url);
1998 } catch (MalformedURLException e) {
1999 mUrl = null;
2000 }
2001 }
2002
2003 public void onCancel(DialogInterface dialog) {
2004 mCanceled = true;
2005 }
2006
2007 public boolean onMenuItemClick(MenuItem item) {
2008 if (mUrl != null) {
2009 // The user may have tried to set a image with a large file size as their
2010 // background so it may take a few moments to perform the operation. Display
2011 // a progress spinner while it is working.
2012 mWallpaperProgress = new ProgressDialog(BrowserActivity.this);
2013 mWallpaperProgress.setIndeterminate(true);
2014 mWallpaperProgress.setMessage(getText(R.string.progress_dialog_setting_wallpaper));
2015 mWallpaperProgress.setCancelable(true);
2016 mWallpaperProgress.setOnCancelListener(this);
2017 mWallpaperProgress.show();
2018 start();
2019 }
2020 return true;
2021 }
2022
Michael Kolbe0a36662010-06-29 10:37:12 -07002023 @Override
Ben Murdoch4f75ba22009-10-27 11:48:28 +00002024 public void run() {
2025 Drawable oldWallpaper = BrowserActivity.this.getWallpaper();
2026 try {
2027 // TODO: This will cause the resource to be downloaded again, when we
2028 // should in most cases be able to grab it from the cache. To fix this
2029 // we should query WebCore to see if we can access a cached version and
2030 // instead open an input stream on that. This pattern could also be used
2031 // in the download manager where the same problem exists.
2032 InputStream inputstream = mUrl.openStream();
2033 if (inputstream != null) {
2034 setWallpaper(inputstream);
2035 }
2036 } catch (IOException e) {
2037 Log.e(LOGTAG, "Unable to set new wallpaper");
2038 // Act as though the user canceled the operation so we try to
2039 // restore the old wallpaper.
2040 mCanceled = true;
2041 }
2042
2043 if (mCanceled) {
2044 // Restore the old wallpaper if the user cancelled whilst we were setting
2045 // the new wallpaper.
2046 int width = oldWallpaper.getIntrinsicWidth();
2047 int height = oldWallpaper.getIntrinsicHeight();
2048 Bitmap bm = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
2049 Canvas canvas = new Canvas(bm);
2050 oldWallpaper.setBounds(0, 0, width, height);
2051 oldWallpaper.draw(canvas);
2052 try {
2053 setWallpaper(bm);
2054 } catch (IOException e) {
2055 Log.e(LOGTAG, "Unable to restore old wallpaper.");
2056 }
2057 mCanceled = false;
2058 }
2059
2060 if (mWallpaperProgress.isShowing()) {
2061 mWallpaperProgress.dismiss();
2062 }
2063 }
2064 }
2065
The Android Open Source Project0c908882009-03-03 19:32:16 -08002066 private void copy(CharSequence text) {
Dianne Hackborn80f32622010-08-05 14:17:53 -07002067 ClipboardManager cm = (ClipboardManager)getSystemService(Context.CLIPBOARD_SERVICE);
2068 cm.setText(text);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002069 }
2070
2071 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08002072 * Resets the browser title-view to whatever it must be
2073 * (for example, if we had a loading error)
2074 * When we have a new page, we call resetTitle, when we
2075 * have to reset the titlebar to whatever it used to be
2076 * (for example, if the user chose to stop loading), we
2077 * call resetTitleAndRevertLockIcon.
2078 */
2079 /* package */ void resetTitleAndRevertLockIcon() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002080 mTabControl.getCurrentTab().revertLockIcon();
2081 updateLockIconToLatest();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002082 resetTitleIconAndProgress();
2083 }
2084
2085 /**
2086 * Reset the title, favicon, and progress.
2087 */
2088 private void resetTitleIconAndProgress() {
2089 WebView current = mTabControl.getCurrentWebView();
2090 if (current == null) {
2091 return;
2092 }
2093 resetTitleAndIcon(current);
2094 int progress = current.getProgress();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002095 current.getWebChromeClient().onProgressChanged(current, progress);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002096 }
2097
2098 // Reset the title and the icon based on the given item.
2099 private void resetTitleAndIcon(WebView view) {
2100 WebHistoryItem item = view.copyBackForwardList().getCurrentItem();
2101 if (item != null) {
Leon Scroggins68579392009-09-15 15:31:54 -04002102 setUrlTitle(item.getUrl(), item.getTitle());
The Android Open Source Project0c908882009-03-03 19:32:16 -08002103 setFavicon(item.getFavicon());
2104 } else {
Leon Scroggins68579392009-09-15 15:31:54 -04002105 setUrlTitle(null, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002106 setFavicon(null);
2107 }
2108 }
2109
2110 /**
2111 * Sets a title composed of the URL and the title string.
2112 * @param url The URL of the site being loaded.
2113 * @param title The title of the site being loaded.
2114 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07002115 void setUrlTitle(String url, String title) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002116 mUrl = url;
2117 mTitle = title;
2118
Leon Scroggins58d56c62010-01-28 15:12:40 -05002119 // If we are in voice search mode, the title has already been set.
2120 if (mTabControl.getCurrentTab().isInVoiceSearchMode()) return;
2121 mTitleBar.setDisplayTitle(url);
Michael Kolba2b2ba82010-08-04 17:54:03 -07002122 mFakeTitleBar.setDisplayTitle(url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002123 }
2124
2125 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08002126 * @param url The URL to build a title version of the URL from.
2127 * @return The title version of the URL or null if fails.
2128 * The title version of the URL can be either the URL hostname,
2129 * or the hostname with an "https://" prefix (for secure URLs),
2130 * or an empty string if, for example, the URL in question is a
2131 * file:// URL with no hostname.
2132 */
Leon Scroggins32e14a62009-06-11 10:26:34 -04002133 /* package */ static String buildTitleUrl(String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002134 String titleUrl = null;
2135
2136 if (url != null) {
2137 try {
2138 // parse the url string
2139 URL urlObj = new URL(url);
2140 if (urlObj != null) {
2141 titleUrl = "";
2142
2143 String protocol = urlObj.getProtocol();
2144 String host = urlObj.getHost();
2145
2146 if (host != null && 0 < host.length()) {
2147 titleUrl = host;
2148 if (protocol != null) {
2149 // if a secure site, add an "https://" prefix!
2150 if (protocol.equalsIgnoreCase("https")) {
2151 titleUrl = protocol + "://" + host;
2152 }
2153 }
2154 }
2155 }
2156 } catch (MalformedURLException e) {}
2157 }
2158
2159 return titleUrl;
2160 }
2161
2162 // Set the favicon in the title bar.
Grace Kloba22ac16e2009-10-07 18:00:23 -07002163 void setFavicon(Bitmap icon) {
Leon Scroggins68579392009-09-15 15:31:54 -04002164 mTitleBar.setFavicon(icon);
Michael Kolba2b2ba82010-08-04 17:54:03 -07002165 mFakeTitleBar.setFavicon(icon);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002166 }
2167
2168 /**
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002169 * Close the tab, remove its associated title bar, and adjust mTabControl's
2170 * current tab to a valid value.
Leon Scroggins1f005d32009-08-10 17:36:42 -04002171 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07002172 /* package */ void closeTab(Tab t) {
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002173 int currentIndex = mTabControl.getCurrentIndex();
2174 int removeIndex = mTabControl.getTabIndex(t);
Leon Scroggins1f005d32009-08-10 17:36:42 -04002175 mTabControl.removeTab(t);
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002176 if (currentIndex >= removeIndex && currentIndex != 0) {
2177 currentIndex--;
2178 }
2179 mTabControl.setCurrentTab(mTabControl.getTab(currentIndex));
Andrei Popescua5bf1de2009-09-23 16:39:23 +01002180 resetTitleIconAndProgress();
Leon Scroggins654899b2010-06-25 16:25:23 -04002181 updateLockIconToLatest();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002182 }
2183
Leon Scrogginsdcc5eeb2010-02-23 17:26:37 -05002184 /* package */ void goBackOnePageOrQuit() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002185 Tab current = mTabControl.getCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002186 if (current == null) {
2187 /*
2188 * Instead of finishing the activity, simply push this to the back
2189 * of the stack and let ActivityManager to choose the foreground
2190 * activity. As BrowserActivity is singleTask, it will be always the
2191 * root of the task. So we can use either true or false for
2192 * moveTaskToBack().
2193 */
2194 moveTaskToBack(true);
Grace Kloba00d85e72009-09-23 18:50:05 -07002195 return;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002196 }
2197 WebView w = current.getWebView();
2198 if (w.canGoBack()) {
2199 w.goBack();
2200 } else {
2201 // Check to see if we are closing a window that was created by
2202 // another window. If so, we switch back to that window.
Grace Kloba22ac16e2009-10-07 18:00:23 -07002203 Tab parent = current.getParentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002204 if (parent != null) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04002205 switchToTab(mTabControl.getTabIndex(parent));
2206 // Now we close the other tab
2207 closeTab(current);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002208 } else {
2209 if (current.closeOnExit()) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002210 // force the tab's inLoad() to be false as we are going to
2211 // either finish the activity or remove the tab. This will
2212 // ensure pauseWebViewTimers() taking action.
2213 mTabControl.getCurrentTab().clearInLoad();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002214 if (mTabControl.getTabCount() == 1) {
2215 finish();
2216 return;
2217 }
Mike Reed7bfa63b2009-05-28 11:08:32 -04002218 // call pauseWebViewTimers() now, we won't be able to call
2219 // it in onPause() as the WebView won't be valid.
Grace Klobaec1b5ad2009-08-18 08:42:32 -07002220 // Temporarily change mActivityInPause to be true as
2221 // pauseWebViewTimers() will do nothing if mActivityInPause
2222 // is false.
Grace Kloba918e1d72009-08-13 14:55:06 -07002223 boolean savedState = mActivityInPause;
2224 if (savedState) {
Grace Klobaec1b5ad2009-08-18 08:42:32 -07002225 Log.e(LOGTAG, "BrowserActivity is already paused "
2226 + "while handing goBackOnePageOrQuit.");
Grace Kloba918e1d72009-08-13 14:55:06 -07002227 }
2228 mActivityInPause = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -04002229 pauseWebViewTimers();
Grace Kloba918e1d72009-08-13 14:55:06 -07002230 mActivityInPause = savedState;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002231 removeTabFromContentView(current);
2232 mTabControl.removeTab(current);
2233 }
2234 /*
2235 * Instead of finishing the activity, simply push this to the back
2236 * of the stack and let ActivityManager to choose the foreground
2237 * activity. As BrowserActivity is singleTask, it will be always the
2238 * root of the task. So we can use either true or false for
2239 * moveTaskToBack().
2240 */
2241 moveTaskToBack(true);
2242 }
2243 }
2244 }
2245
Grace Kloba22ac16e2009-10-07 18:00:23 -07002246 boolean isMenuDown() {
2247 return mMenuIsDown;
2248 }
2249
Grace Kloba5942df02009-09-18 11:48:29 -07002250 @Override
2251 public boolean onKeyDown(int keyCode, KeyEvent event) {
Leon Scrogginsf65b50d2009-12-08 10:44:28 -05002252 // Even if MENU is already held down, we need to call to super to open
2253 // the IME on long press.
2254 if (KeyEvent.KEYCODE_MENU == keyCode) {
2255 mMenuIsDown = true;
2256 return super.onKeyDown(keyCode, event);
2257 }
Grace Kloba5942df02009-09-18 11:48:29 -07002258 // The default key mode is DEFAULT_KEYS_SEARCH_LOCAL. As the MENU is
2259 // still down, we don't want to trigger the search. Pretend to consume
2260 // the key and do nothing.
2261 if (mMenuIsDown) return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002262
Grace Kloba5942df02009-09-18 11:48:29 -07002263 switch(keyCode) {
Grace Kloba5942df02009-09-18 11:48:29 -07002264 case KeyEvent.KEYCODE_SPACE:
Grace Klobada0fe552009-09-22 18:17:24 -07002265 // WebView/WebTextView handle the keys in the KeyDown. As
2266 // the Activity's shortcut keys are only handled when WebView
2267 // doesn't, have to do it in onKeyDown instead of onKeyUp.
2268 if (event.isShiftPressed()) {
2269 getTopWindow().pageUp(false);
2270 } else {
2271 getTopWindow().pageDown(false);
2272 }
Grace Kloba5942df02009-09-18 11:48:29 -07002273 return true;
2274 case KeyEvent.KEYCODE_BACK:
2275 if (event.getRepeatCount() == 0) {
2276 event.startTracking();
2277 return true;
2278 } else if (mCustomView == null && mActiveTabsPage == null
2279 && event.isLongPress()) {
Michael Kolb68792c82010-08-09 16:39:18 -07002280 bookmarksOrHistoryPicker(true, false);
Grace Kloba5942df02009-09-18 11:48:29 -07002281 return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002282 }
Grace Kloba5942df02009-09-18 11:48:29 -07002283 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002284 }
Grace Kloba5942df02009-09-18 11:48:29 -07002285 return super.onKeyDown(keyCode, event);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002286 }
2287
Grace Kloba5942df02009-09-18 11:48:29 -07002288 @Override
2289 public boolean onKeyUp(int keyCode, KeyEvent event) {
2290 switch(keyCode) {
2291 case KeyEvent.KEYCODE_MENU:
2292 mMenuIsDown = false;
2293 break;
Grace Kloba5942df02009-09-18 11:48:29 -07002294 case KeyEvent.KEYCODE_BACK:
2295 if (event.isTracking() && !event.isCanceled()) {
2296 if (mCustomView != null) {
2297 // if a custom view is showing, hide it
Grace Kloba22ac16e2009-10-07 18:00:23 -07002298 mTabControl.getCurrentWebView().getWebChromeClient()
2299 .onHideCustomView();
Grace Kloba5942df02009-09-18 11:48:29 -07002300 } else if (mActiveTabsPage != null) {
2301 // if tab page is showing, hide it
2302 removeActiveTabPage(true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002303 } else {
Grace Kloba5942df02009-09-18 11:48:29 -07002304 WebView subwindow = mTabControl.getCurrentSubWindow();
2305 if (subwindow != null) {
2306 if (subwindow.canGoBack()) {
2307 subwindow.goBack();
2308 } else {
2309 dismissSubWindow(mTabControl.getCurrentTab());
2310 }
2311 } else {
2312 goBackOnePageOrQuit();
2313 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002314 }
Grace Kloba5942df02009-09-18 11:48:29 -07002315 return true;
2316 }
2317 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002318 }
Grace Kloba5942df02009-09-18 11:48:29 -07002319 return super.onKeyUp(keyCode, event);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002320 }
2321
Leon Scroggins68579392009-09-15 15:31:54 -04002322 /* package */ void stopLoading() {
Ben Murdochb7cc8b42009-09-28 10:59:09 +01002323 mDidStopLoad = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002324 resetTitleAndRevertLockIcon();
2325 WebView w = getTopWindow();
2326 w.stopLoading();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002327 // FIXME: before refactor, it is using mWebViewClient. So I keep the
2328 // same logic here. But for subwindow case, should we call into the main
2329 // WebView's onPageFinished as we never call its onPageStarted and if
2330 // the page finishes itself, we don't call onPageFinished.
2331 mTabControl.getCurrentWebView().getWebViewClient().onPageFinished(w,
2332 w.getUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08002333
2334 cancelStopToast();
2335 mStopToast = Toast
2336 .makeText(this, R.string.stopping, Toast.LENGTH_SHORT);
2337 mStopToast.show();
2338 }
2339
Grace Kloba22ac16e2009-10-07 18:00:23 -07002340 boolean didUserStopLoading() {
2341 return mDidStopLoad;
2342 }
2343
The Android Open Source Project0c908882009-03-03 19:32:16 -08002344 private void cancelStopToast() {
2345 if (mStopToast != null) {
2346 mStopToast.cancel();
2347 mStopToast = null;
2348 }
2349 }
2350
Grace Kloba22ac16e2009-10-07 18:00:23 -07002351 // called by a UI or non-UI thread to post the message
2352 public void postMessage(int what, int arg1, int arg2, Object obj,
2353 long delayMillis) {
2354 mHandler.sendMessageDelayed(mHandler.obtainMessage(what, arg1, arg2,
2355 obj), delayMillis);
2356 }
2357
2358 // called by a UI or non-UI thread to remove the message
2359 void removeMessages(int what, Object object) {
2360 mHandler.removeMessages(what, object);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002361 }
2362
2363 // public message ids
2364 public final static int LOAD_URL = 1001;
2365 public final static int STOP_LOAD = 1002;
2366
2367 // Message Ids
2368 private static final int FOCUS_NODE_HREF = 102;
Grace Kloba92c18a52009-07-31 23:48:32 -07002369 private static final int RELEASE_WAKELOCK = 107;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002370
Grace Kloba22ac16e2009-10-07 18:00:23 -07002371 static final int UPDATE_BOOKMARK_THUMBNAIL = 108;
Ben Murdoch2694e232009-09-29 09:41:11 +01002372
Ben Murdocheecb4e62010-07-06 16:30:38 +01002373 private static final int TOUCH_ICON_DOWNLOADED = 109;
2374
The Android Open Source Project0c908882009-03-03 19:32:16 -08002375 // Private handler for handling javascript and saving passwords
2376 private Handler mHandler = new Handler() {
2377
Michael Kolbe0a36662010-06-29 10:37:12 -07002378 @Override
The Android Open Source Project0c908882009-03-03 19:32:16 -08002379 public void handleMessage(Message msg) {
2380 switch (msg.what) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002381 case FOCUS_NODE_HREF:
Ben Murdoch2694e232009-09-29 09:41:11 +01002382 {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002383 String url = (String) msg.getData().get("url");
Ben Murdoch90d088c2009-11-17 18:14:04 +00002384 String title = (String) msg.getData().get("title");
The Android Open Source Project0c908882009-03-03 19:32:16 -08002385 if (url == null || url.length() == 0) {
2386 break;
2387 }
2388 HashMap focusNodeMap = (HashMap) msg.obj;
2389 WebView view = (WebView) focusNodeMap.get("webview");
2390 // Only apply the action if the top window did not change.
2391 if (getTopWindow() != view) {
2392 break;
2393 }
2394 switch (msg.arg1) {
2395 case R.id.open_context_menu_id:
2396 case R.id.view_image_context_menu_id:
Leon Scroggins92472e82010-02-17 16:32:28 -05002397 loadUrlFromContext(getTopWindow(), url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002398 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002399 case R.id.bookmark_context_menu_id:
2400 Intent intent = new Intent(BrowserActivity.this,
2401 AddBookmarkPage.class);
2402 intent.putExtra("url", url);
Ben Murdoch90d088c2009-11-17 18:14:04 +00002403 intent.putExtra("title", title);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002404 startActivity(intent);
2405 break;
2406 case R.id.share_link_context_menu_id:
Leon Scroggins3e204452010-05-10 11:06:03 -04002407 sharePage(BrowserActivity.this, title, url, null,
Leon Scroggins96afcb12009-12-10 12:35:56 -05002408 null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002409 break;
2410 case R.id.copy_link_context_menu_id:
2411 copy(url);
2412 break;
2413 case R.id.save_link_context_menu_id:
2414 case R.id.download_context_menu_id:
2415 onDownloadStartNoStream(url, null, null, null, -1);
2416 break;
2417 }
2418 break;
Ben Murdoch2694e232009-09-29 09:41:11 +01002419 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002420
2421 case LOAD_URL:
Leon Scroggins92472e82010-02-17 16:32:28 -05002422 loadUrlFromContext(getTopWindow(), (String) msg.obj);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002423 break;
2424
2425 case STOP_LOAD:
2426 stopLoading();
2427 break;
2428
The Android Open Source Project0c908882009-03-03 19:32:16 -08002429 case RELEASE_WAKELOCK:
2430 if (mWakeLock.isHeld()) {
2431 mWakeLock.release();
Grace Kloba5d0e02e2009-10-05 15:15:36 -07002432 // if we reach here, Browser should be still in the
2433 // background loading after WAKELOCK_TIMEOUT (5-min).
2434 // To avoid burning the battery, stop loading.
2435 mTabControl.stopAllLoading();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002436 }
2437 break;
Ben Murdoch2694e232009-09-29 09:41:11 +01002438
2439 case UPDATE_BOOKMARK_THUMBNAIL:
2440 WebView view = (WebView) msg.obj;
2441 if (view != null) {
2442 updateScreenshot(view);
2443 }
2444 break;
Ben Murdocheecb4e62010-07-06 16:30:38 +01002445
2446 case TOUCH_ICON_DOWNLOADED:
2447 Bundle b = msg.getData();
2448 showSaveToHomescreenDialog(b.getString("url"),
2449 b.getString("title"),
2450 (Bitmap) b.getParcelable("touchIcon"),
2451 (Bitmap) b.getParcelable("favicon"));
2452 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002453 }
2454 }
2455 };
2456
Leon Scroggins96afcb12009-12-10 12:35:56 -05002457 /**
2458 * Share a page, providing the title, url, favicon, and a screenshot. Uses
2459 * an {@link Intent} to launch the Activity chooser.
2460 * @param c Context used to launch a new Activity.
2461 * @param title Title of the page. Stored in the Intent with
Paul Westbrook03e6d392010-02-12 10:33:29 -08002462 * {@link Intent#EXTRA_SUBJECT}
Leon Scroggins96afcb12009-12-10 12:35:56 -05002463 * @param url URL of the page. Stored in the Intent with
2464 * {@link Intent#EXTRA_TEXT}
2465 * @param favicon Bitmap of the favicon for the page. Stored in the Intent
2466 * with {@link Browser#EXTRA_SHARE_FAVICON}
2467 * @param screenshot Bitmap of a screenshot of the page. Stored in the
2468 * Intent with {@link Browser#EXTRA_SHARE_SCREENSHOT}
2469 */
2470 public static final void sharePage(Context c, String title, String url,
2471 Bitmap favicon, Bitmap screenshot) {
2472 Intent send = new Intent(Intent.ACTION_SEND);
2473 send.setType("text/plain");
2474 send.putExtra(Intent.EXTRA_TEXT, url);
Paul Westbrook03e6d392010-02-12 10:33:29 -08002475 send.putExtra(Intent.EXTRA_SUBJECT, title);
Leon Scroggins96afcb12009-12-10 12:35:56 -05002476 send.putExtra(Browser.EXTRA_SHARE_FAVICON, favicon);
2477 send.putExtra(Browser.EXTRA_SHARE_SCREENSHOT, screenshot);
2478 try {
2479 c.startActivity(Intent.createChooser(send, c.getString(
2480 R.string.choosertitle_sharevia)));
2481 } catch(android.content.ActivityNotFoundException ex) {
2482 // if no app handles it, do nothing
2483 }
2484 }
2485
Leon Scroggins89c6d362009-07-15 16:54:37 -04002486 private void updateScreenshot(WebView view) {
2487 // If this is a bookmarked site, add a screenshot to the database.
2488 // FIXME: When should we update? Every time?
2489 // FIXME: Would like to make sure there is actually something to
2490 // draw, but the API for that (WebViewCore.pictureReady()) is not
2491 // currently accessible here.
Ben Murdochaac7aa62009-09-17 16:57:40 +01002492
Ben Murdoch87cc65d2010-06-29 20:34:10 +01002493 final Bitmap bm = createScreenshot(view, getDesiredThumbnailWidth(this),
2494 getDesiredThumbnailHeight(this));
Patrick Scottcb192b52010-04-14 14:38:55 -04002495 if (bm == null) {
2496 return;
Leon Scroggins89c6d362009-07-15 16:54:37 -04002497 }
Patrick Scottcb192b52010-04-14 14:38:55 -04002498
2499 final ContentResolver cr = getContentResolver();
2500 final String url = view.getUrl();
2501 final String originalUrl = view.getOriginalUrl();
2502
2503 new AsyncTask<Void, Void, Void>() {
2504 @Override
2505 protected Void doInBackground(Void... unused) {
2506 Cursor c = null;
2507 try {
Jeff Hamilton84029622010-08-05 14:29:28 -05002508 c = Bookmarks.queryBookmarksForUrl(
Patrick Scottcb192b52010-04-14 14:38:55 -04002509 cr, originalUrl, url, true);
2510 if (c != null) {
2511 if (c.moveToFirst()) {
2512 ContentValues values = new ContentValues();
2513 final ByteArrayOutputStream os
2514 = new ByteArrayOutputStream();
2515 bm.compress(Bitmap.CompressFormat.PNG, 100, os);
2516 values.put(Browser.BookmarkColumns.THUMBNAIL,
2517 os.toByteArray());
2518 do {
2519 cr.update(ContentUris.withAppendedId(
2520 Browser.BOOKMARKS_URI, c.getInt(0)),
2521 values, null, null);
2522 } while (c.moveToNext());
2523 }
2524 }
2525 } catch (IllegalStateException e) {
2526 // Ignore
2527 } finally {
2528 if (c != null) c.close();
2529 }
2530 return null;
2531 }
2532 }.execute();
Leon Scroggins89c6d362009-07-15 16:54:37 -04002533 }
2534
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002535 /**
Leon Scrogginsf8551612009-09-24 16:06:02 -04002536 * Values for the size of the thumbnail created when taking a screenshot.
2537 * Lazily initialized. Instead of using these directly, use
2538 * getDesiredThumbnailWidth() or getDesiredThumbnailHeight().
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002539 */
Leon Scrogginsf8551612009-09-24 16:06:02 -04002540 private static int THUMBNAIL_WIDTH = 0;
2541 private static int THUMBNAIL_HEIGHT = 0;
2542
2543 /**
2544 * Return the desired width for thumbnail screenshots, which are stored in
2545 * the database, and used on the bookmarks screen.
2546 * @param context Context for finding out the density of the screen.
2547 * @return int desired width for thumbnail screenshot.
2548 */
2549 /* package */ static int getDesiredThumbnailWidth(Context context) {
2550 if (THUMBNAIL_WIDTH == 0) {
2551 float density = context.getResources().getDisplayMetrics().density;
2552 THUMBNAIL_WIDTH = (int) (90 * density);
2553 THUMBNAIL_HEIGHT = (int) (80 * density);
2554 }
2555 return THUMBNAIL_WIDTH;
2556 }
2557
2558 /**
2559 * Return the desired height for thumbnail screenshots, which are stored in
2560 * the database, and used on the bookmarks screen.
2561 * @param context Context for finding out the density of the screen.
2562 * @return int desired height for thumbnail screenshot.
2563 */
2564 /* package */ static int getDesiredThumbnailHeight(Context context) {
2565 // To ensure that they are both initialized.
2566 getDesiredThumbnailWidth(context);
2567 return THUMBNAIL_HEIGHT;
2568 }
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002569
Ben Murdoch87cc65d2010-06-29 20:34:10 +01002570 private Bitmap createScreenshot(WebView view, int width, int height) {
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002571 Picture thumbnail = view.capturePicture();
Leon Scroggins45800572009-09-29 16:38:47 -04002572 if (thumbnail == null) {
2573 return null;
2574 }
Ben Murdoch87cc65d2010-06-29 20:34:10 +01002575 Bitmap bm = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002576 Canvas canvas = new Canvas(bm);
2577 // May need to tweak these values to determine what is the
2578 // best scale factor
Ben Murdoch2694e232009-09-29 09:41:11 +01002579 int thumbnailWidth = thumbnail.getWidth();
Ben Murdochae59c3f2009-10-20 18:30:28 +01002580 int thumbnailHeight = thumbnail.getHeight();
2581 float scaleFactorX = 1.0f;
2582 float scaleFactorY = 1.0f;
Ben Murdoch2694e232009-09-29 09:41:11 +01002583 if (thumbnailWidth > 0) {
Ben Murdoch87cc65d2010-06-29 20:34:10 +01002584 scaleFactorX = (float) width / (float)thumbnailWidth;
Ben Murdochae59c3f2009-10-20 18:30:28 +01002585 } else {
2586 return null;
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002587 }
Ben Murdochae59c3f2009-10-20 18:30:28 +01002588
2589 if (view.getWidth() > view.getHeight() &&
2590 thumbnailHeight < view.getHeight() && thumbnailHeight > 0) {
2591 // If the device is in landscape and the page is shorter
2592 // than the height of the view, stretch the thumbnail to fill the
2593 // space.
Ben Murdoch87cc65d2010-06-29 20:34:10 +01002594 scaleFactorY = (float) height / (float)thumbnailHeight;
Ben Murdochae59c3f2009-10-20 18:30:28 +01002595 } else {
2596 // In the portrait case, this looks nice.
2597 scaleFactorY = scaleFactorX;
2598 }
2599
2600 canvas.scale(scaleFactorX, scaleFactorY);
2601
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002602 thumbnail.draw(canvas);
2603 return bm;
2604 }
2605
The Android Open Source Project0c908882009-03-03 19:32:16 -08002606 // -------------------------------------------------------------------------
Grace Kloba22ac16e2009-10-07 18:00:23 -07002607 // Helper function for WebViewClient.
The Android Open Source Project0c908882009-03-03 19:32:16 -08002608 //-------------------------------------------------------------------------
2609
2610 // Use in overrideUrlLoading
2611 /* package */ final static String SCHEME_WTAI = "wtai://wp/";
2612 /* package */ final static String SCHEME_WTAI_MC = "wtai://wp/mc;";
2613 /* package */ final static String SCHEME_WTAI_SD = "wtai://wp/sd;";
2614 /* package */ final static String SCHEME_WTAI_AP = "wtai://wp/ap;";
2615
Leon Scroggins92472e82010-02-17 16:32:28 -05002616 // Keep this initial progress in sync with initialProgressValue (* 100)
2617 // in ProgressTracker.cpp
2618 private final static int INITIAL_PROGRESS = 10;
2619
Grace Kloba22ac16e2009-10-07 18:00:23 -07002620 void onPageStarted(WebView view, String url, Bitmap favicon) {
2621 // when BrowserActivity just starts, onPageStarted may be called before
2622 // onResume as it is triggered from onCreate. Call resumeWebViewTimers
2623 // to start the timer. As we won't switch tabs while an activity is in
2624 // pause state, we can ensure calling resume and pause in pair.
2625 if (mActivityInPause) resumeWebViewTimers();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002626
Grace Kloba22ac16e2009-10-07 18:00:23 -07002627 resetLockIcon(url);
2628 setUrlTitle(url, null);
2629 setFavicon(favicon);
Leon Scroggins8cf8f682009-11-04 11:13:50 -08002630 // Show some progress so that the user knows the page is beginning to
2631 // load
Leon Scroggins92472e82010-02-17 16:32:28 -05002632 onProgressChanged(view, INITIAL_PROGRESS);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002633 mDidStopLoad = false;
Grace Kloba22ac16e2009-10-07 18:00:23 -07002634 if (!mIsNetworkUp) createAndShowNetworkDialog();
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04002635 endActionMode();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002636 if (mSettings.isTracing()) {
2637 String host;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002638 try {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002639 WebAddress uri = new WebAddress(url);
2640 host = uri.mHost;
2641 } catch (android.net.ParseException ex) {
2642 host = "browser";
The Android Open Source Project0c908882009-03-03 19:32:16 -08002643 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002644 host = host.replace('.', '_');
2645 host += ".trace";
2646 mInTrace = true;
2647 Debug.startMethodTracing(host, 20 * 1024 * 1024);
2648 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002649
Grace Kloba22ac16e2009-10-07 18:00:23 -07002650 // Performance probe
2651 if (false) {
2652 mStart = SystemClock.uptimeMillis();
2653 mProcessStart = Process.getElapsedCpuTime();
2654 long[] sysCpu = new long[7];
2655 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2656 sysCpu, null)) {
2657 mUserStart = sysCpu[0] + sysCpu[1];
2658 mSystemStart = sysCpu[2];
2659 mIdleStart = sysCpu[3];
2660 mIrqStart = sysCpu[4] + sysCpu[5] + sysCpu[6];
2661 }
2662 mUiStart = SystemClock.currentThreadTimeMillis();
2663 }
2664 }
2665
2666 void onPageFinished(WebView view, String url) {
2667 // Reset the title and icon in case we stopped a provisional load.
2668 resetTitleAndIcon(view);
2669 // Update the lock icon image only once we are done loading
2670 updateLockIconToLatest();
2671 // pause the WebView timer and release the wake lock if it is finished
2672 // while BrowserActivity is in pause state.
2673 if (mActivityInPause && pauseWebViewTimers()) {
2674 if (mWakeLock.isHeld()) {
2675 mHandler.removeMessages(RELEASE_WAKELOCK);
2676 mWakeLock.release();
2677 }
2678 }
2679
2680 // Performance probe
2681 if (false) {
2682 long[] sysCpu = new long[7];
2683 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2684 sysCpu, null)) {
2685 String uiInfo = "UI thread used "
2686 + (SystemClock.currentThreadTimeMillis() - mUiStart)
2687 + " ms";
2688 if (LOGD_ENABLED) {
2689 Log.d(LOGTAG, uiInfo);
2690 }
2691 //The string that gets written to the log
2692 String performanceString = "It took total "
2693 + (SystemClock.uptimeMillis() - mStart)
2694 + " ms clock time to load the page."
2695 + "\nbrowser process used "
2696 + (Process.getElapsedCpuTime() - mProcessStart)
2697 + " ms, user processes used "
2698 + (sysCpu[0] + sysCpu[1] - mUserStart) * 10
2699 + " ms, kernel used "
2700 + (sysCpu[2] - mSystemStart) * 10
2701 + " ms, idle took " + (sysCpu[3] - mIdleStart) * 10
2702 + " ms and irq took "
2703 + (sysCpu[4] + sysCpu[5] + sysCpu[6] - mIrqStart)
2704 * 10 + " ms, " + uiInfo;
2705 if (LOGD_ENABLED) {
2706 Log.d(LOGTAG, performanceString + "\nWebpage: " + url);
2707 }
2708 if (url != null) {
2709 // strip the url to maintain consistency
2710 String newUrl = new String(url);
2711 if (newUrl.startsWith("http://www.")) {
2712 newUrl = newUrl.substring(11);
2713 } else if (newUrl.startsWith("http://")) {
2714 newUrl = newUrl.substring(7);
2715 } else if (newUrl.startsWith("https://www.")) {
2716 newUrl = newUrl.substring(12);
2717 } else if (newUrl.startsWith("https://")) {
2718 newUrl = newUrl.substring(8);
2719 }
2720 if (LOGD_ENABLED) {
2721 Log.d(LOGTAG, newUrl + " loaded");
2722 }
Grace Kloba5b078b52009-06-24 20:23:41 -07002723 }
2724 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002725 }
Grace Kloba5b078b52009-06-24 20:23:41 -07002726
Grace Kloba22ac16e2009-10-07 18:00:23 -07002727 if (mInTrace) {
2728 mInTrace = false;
2729 Debug.stopMethodTracing();
2730 }
2731 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002732
Grace Klobae7fe26b2010-06-28 16:23:33 -07002733 private void closeEmptyChildTab() {
2734 Tab current = mTabControl.getCurrentTab();
2735 if (current != null
2736 && current.getWebView().copyBackForwardList().getSize() == 0) {
2737 Tab parent = current.getParentTab();
2738 if (parent != null) {
2739 switchToTab(mTabControl.getTabIndex(parent));
2740 closeTab(current);
2741 }
2742 }
2743 }
2744
Grace Kloba22ac16e2009-10-07 18:00:23 -07002745 boolean shouldOverrideUrlLoading(WebView view, String url) {
2746 if (url.startsWith(SCHEME_WTAI)) {
2747 // wtai://wp/mc;number
2748 // number=string(phone-number)
2749 if (url.startsWith(SCHEME_WTAI_MC)) {
2750 Intent intent = new Intent(Intent.ACTION_VIEW,
2751 Uri.parse(WebView.SCHEME_TEL +
2752 url.substring(SCHEME_WTAI_MC.length())));
2753 startActivity(intent);
Grace Klobae7fe26b2010-06-28 16:23:33 -07002754 // before leaving BrowserActivity, close the empty child tab.
2755 // If a new tab is created through JavaScript open to load this
2756 // url, we would like to close it as we will load this url in a
2757 // different Activity.
2758 closeEmptyChildTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002759 return true;
2760 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002761 // wtai://wp/sd;dtmf
2762 // dtmf=string(dialstring)
2763 if (url.startsWith(SCHEME_WTAI_SD)) {
2764 // TODO: only send when there is active voice connection
2765 return false;
2766 }
2767 // wtai://wp/ap;number;name
2768 // number=string(phone-number)
2769 // name=string
2770 if (url.startsWith(SCHEME_WTAI_AP)) {
2771 // TODO
2772 return false;
2773 }
2774 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002775
Grace Kloba22ac16e2009-10-07 18:00:23 -07002776 // The "about:" schemes are internal to the browser; don't want these to
2777 // be dispatched to other apps.
2778 if (url.startsWith("about:")) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002779 return false;
2780 }
2781
Grace Kloba22ac16e2009-10-07 18:00:23 -07002782 Intent intent;
2783 // perform generic parsing of the URI to turn it into an Intent.
2784 try {
2785 intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME);
2786 } catch (URISyntaxException ex) {
2787 Log.w("Browser", "Bad URI " + url + ": " + ex.getMessage());
2788 return false;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002789 }
2790
Grace Kloba22ac16e2009-10-07 18:00:23 -07002791 // check whether the intent can be resolved. If not, we will see
2792 // whether we can download it from the Market.
2793 if (getPackageManager().resolveActivity(intent, 0) == null) {
2794 String packagename = intent.getPackage();
2795 if (packagename != null) {
2796 intent = new Intent(Intent.ACTION_VIEW, Uri
2797 .parse("market://search?q=pname:" + packagename));
2798 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2799 startActivity(intent);
Grace Klobae7fe26b2010-06-28 16:23:33 -07002800 // before leaving BrowserActivity, close the empty child tab.
2801 // If a new tab is created through JavaScript open to load this
2802 // url, we would like to close it as we will load this url in a
2803 // different Activity.
2804 closeEmptyChildTab();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002805 return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002806 } else {
2807 return false;
2808 }
2809 }
2810
Grace Kloba22ac16e2009-10-07 18:00:23 -07002811 // sanitize the Intent, ensuring web pages can not bypass browser
2812 // security (only access to BROWSABLE activities).
2813 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2814 intent.setComponent(null);
2815 try {
2816 if (startActivityIfNeeded(intent, -1)) {
Grace Klobae7fe26b2010-06-28 16:23:33 -07002817 // before leaving BrowserActivity, close the empty child tab.
2818 // If a new tab is created through JavaScript open to load this
2819 // url, we would like to close it as we will load this url in a
2820 // different Activity.
2821 closeEmptyChildTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002822 return true;
2823 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002824 } catch (ActivityNotFoundException ex) {
2825 // ignore the error. If no application can handle the URL,
2826 // eg about:blank, assume the browser can handle it.
2827 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002828
Grace Kloba22ac16e2009-10-07 18:00:23 -07002829 if (mMenuIsDown) {
Michael Kolb68792c82010-08-09 16:39:18 -07002830 openTab(url, false);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002831 closeOptionsMenu();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002832 return true;
2833 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002834 return false;
2835 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002836
Grace Kloba22ac16e2009-10-07 18:00:23 -07002837 // -------------------------------------------------------------------------
2838 // Helper function for WebChromeClient
2839 // -------------------------------------------------------------------------
The Android Open Source Project0c908882009-03-03 19:32:16 -08002840
Grace Kloba22ac16e2009-10-07 18:00:23 -07002841 void onProgressChanged(WebView view, int newProgress) {
Michael Kolba2b2ba82010-08-04 17:54:03 -07002842
2843 // On the phone, the fake title bar will always cover up the
2844 // regular title bar (or the regular one is offscreen), so only the
2845 // fake title bar needs to change its progress
2846 mFakeTitleBar.setProgress(newProgress);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002847
Grace Kloba22ac16e2009-10-07 18:00:23 -07002848 if (newProgress == 100) {
2849 // onProgressChanged() may continue to be called after the main
2850 // frame has finished loading, as any remaining sub frames continue
2851 // to load. We'll only get called once though with newProgress as
2852 // 100 when everything is loaded. (onPageFinished is called once
2853 // when the main frame completes loading regardless of the state of
2854 // any sub frames so calls to onProgressChanges may continue after
2855 // onPageFinished has executed)
2856 if (mInLoad) {
2857 mInLoad = false;
Leon Scrogginsa27ff192009-09-14 12:58:04 -04002858 updateInLoadMenuItems();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002859 // If the options menu is open, leave the title bar
2860 if (!mOptionsMenuOpen || !mIconView) {
2861 hideFakeTitleBar();
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07002862 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002863 }
Leon Scrogginsaa37e7f2010-03-05 11:51:20 -05002864 } else {
2865 if (!mInLoad) {
2866 // onPageFinished may have already been called but a subframe is
2867 // still loading and updating the progress. Reset mInLoad and
2868 // update the menu items.
2869 mInLoad = true;
2870 updateInLoadMenuItems();
2871 }
2872 // When the page first begins to load, the Activity may still be
2873 // paused, in which case showFakeTitleBar will do nothing. Call
2874 // again as the page continues to load so that it will be shown.
2875 // (Calling it will the fake title bar is already showing will also
2876 // do nothing.
Grace Kloba22ac16e2009-10-07 18:00:23 -07002877 if (!mOptionsMenuOpen || mIconView) {
2878 // This page has begun to load, so show the title bar
2879 showFakeTitleBar();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002880 }
2881 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002882 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002883
Grace Kloba22ac16e2009-10-07 18:00:23 -07002884 void onShowCustomView(View view, WebChromeClient.CustomViewCallback callback) {
Derek Sollenberger8ff57db2009-12-08 15:39:55 -05002885 // if a view already exists then immediately terminate the new one
2886 if (mCustomView != null) {
2887 callback.onCustomViewHidden();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002888 return;
Derek Sollenberger8ff57db2009-12-08 15:39:55 -05002889 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002890
2891 // Add the custom view to its container.
2892 mCustomViewContainer.addView(view, COVER_SCREEN_GRAVITY_CENTER);
2893 mCustomView = view;
2894 mCustomViewCallback = callback;
2895 // Save the menu state and set it to empty while the custom
2896 // view is showing.
2897 mOldMenuState = mMenuState;
2898 mMenuState = EMPTY_MENU;
2899 // Hide the content view.
2900 mContentView.setVisibility(View.GONE);
2901 // Finally show the custom view container.
Andrei Popescu163ab742009-10-20 17:58:23 +01002902 setStatusBarVisibility(false);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002903 mCustomViewContainer.setVisibility(View.VISIBLE);
2904 mCustomViewContainer.bringToFront();
2905 }
2906
2907 void onHideCustomView() {
2908 if (mCustomView == null)
2909 return;
2910
2911 // Hide the custom view.
2912 mCustomView.setVisibility(View.GONE);
2913 // Remove the custom view from its container.
2914 mCustomViewContainer.removeView(mCustomView);
2915 mCustomView = null;
2916 // Reset the old menu state.
2917 mMenuState = mOldMenuState;
2918 mOldMenuState = EMPTY_MENU;
2919 mCustomViewContainer.setVisibility(View.GONE);
2920 mCustomViewCallback.onCustomViewHidden();
2921 // Show the content view.
Andrei Popescu163ab742009-10-20 17:58:23 +01002922 setStatusBarVisibility(true);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002923 mContentView.setVisibility(View.VISIBLE);
2924 }
2925
2926 Bitmap getDefaultVideoPoster() {
2927 if (mDefaultVideoPoster == null) {
2928 mDefaultVideoPoster = BitmapFactory.decodeResource(
2929 getResources(), R.drawable.default_video_poster);
Patrick Scott3918d442009-08-04 13:22:29 -04002930 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002931 return mDefaultVideoPoster;
2932 }
Patrick Scott3918d442009-08-04 13:22:29 -04002933
Grace Kloba22ac16e2009-10-07 18:00:23 -07002934 View getVideoLoadingProgressView() {
2935 if (mVideoProgressView == null) {
2936 LayoutInflater inflater = LayoutInflater.from(BrowserActivity.this);
2937 mVideoProgressView = inflater.inflate(
2938 R.layout.video_loading_progress, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002939 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002940 return mVideoProgressView;
2941 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002942
Leon Scroggins8d5fa432009-10-02 15:55:59 -04002943 /*
2944 * The Object used to inform the WebView of the file to upload.
2945 */
2946 private ValueCallback<Uri> mUploadMessage;
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002947 private String mCameraFilePath;
Leon Scroggins8d5fa432009-10-02 15:55:59 -04002948
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002949 void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
2950
2951 final String imageMimeType = "image/*";
Ben Murdoch6af492a2010-06-15 12:38:17 +01002952 final String videoMimeType = "video/*";
Ben Murdoch039bd472010-07-21 21:26:57 +01002953 final String audioMimeType = "audio/*";
Ben Murdochb50d7402010-07-16 12:42:22 +01002954 final String mediaSourceKey = "capture";
Ben Murdoch6af492a2010-06-15 12:38:17 +01002955 final String mediaSourceValueCamera = "camera";
Ben Murdochb50d7402010-07-16 12:42:22 +01002956 final String mediaSourceValueFileSystem = "filesystem";
Ben Murdoch6af492a2010-06-15 12:38:17 +01002957 final String mediaSourceValueCamcorder = "camcorder";
Ben Murdoch039bd472010-07-21 21:26:57 +01002958 final String mediaSourceValueMicrophone = "microphone";
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002959
Ben Murdoch039bd472010-07-21 21:26:57 +01002960 // media source can be 'filesystem' or 'camera' or 'camcorder' or 'microphone'.
Ben Murdoch6af492a2010-06-15 12:38:17 +01002961 String mediaSource = "";
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002962
Ben Murdoch6af492a2010-06-15 12:38:17 +01002963 // We add the camera intent if there was no accept type (or '*/*' or 'image/*').
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002964 boolean addCameraIntent = true;
Ben Murdoch6af492a2010-06-15 12:38:17 +01002965 // We add the camcorder intent if there was no accept type (or '*/*' or 'video/*').
2966 boolean addCamcorderIntent = true;
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002967
Ben Murdoch6af492a2010-06-15 12:38:17 +01002968 if (mUploadMessage != null) {
2969 // Already a file picker operation in progress.
2970 return;
2971 }
2972
Grace Kloba22ac16e2009-10-07 18:00:23 -07002973 mUploadMessage = uploadMsg;
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002974
2975 // Parse the accept type.
2976 String params[] = acceptType.split(";");
2977 String mimeType = params[0];
2978
2979 for (String p : params) {
2980 String[] keyValue = p.split("=");
2981 if (keyValue.length == 2) {
2982 // Process key=value parameters.
Ben Murdoch6af492a2010-06-15 12:38:17 +01002983 if (mediaSourceKey.equals(keyValue[0])) {
2984 mediaSource = keyValue[1];
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002985 }
2986 }
2987 }
2988
2989 // This intent will display the standard OPENABLE file picker.
Grace Kloba22ac16e2009-10-07 18:00:23 -07002990 Intent i = new Intent(Intent.ACTION_GET_CONTENT);
2991 i.addCategory(Intent.CATEGORY_OPENABLE);
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002992
2993 // Create an intent to add to the standard file picker that will
2994 // capture an image from the camera. We'll combine this intent with
2995 // the standard OPENABLE picker unless the web developer specifically
2996 // requested the camera or gallery be opened by passing a parameter
2997 // in the accept type.
2998 Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
2999 File externalDataDir = Environment.getExternalStoragePublicDirectory(
3000 Environment.DIRECTORY_DCIM);
3001 File cameraDataDir = new File(externalDataDir.getAbsolutePath() +
3002 File.separator + "browser-photos");
3003 cameraDataDir.mkdirs();
3004 mCameraFilePath = cameraDataDir.getAbsolutePath() + File.separator +
3005 System.currentTimeMillis() + ".jpg";
3006 cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(mCameraFilePath)));
3007
Ben Murdoch6af492a2010-06-15 12:38:17 +01003008 Intent camcorderIntent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
3009
Ben Murdoch039bd472010-07-21 21:26:57 +01003010 Intent soundRecIntent = new Intent(MediaStore.Audio.Media.RECORD_SOUND_ACTION);
3011
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003012 if (mimeType.equals(imageMimeType)) {
3013 i.setType(imageMimeType);
Ben Murdoch6af492a2010-06-15 12:38:17 +01003014 addCamcorderIntent = false;
3015 if (mediaSource.equals(mediaSourceValueCamera)) {
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003016 // Specified 'image/*' and requested the camera, so go ahead and launch the camera
3017 // directly.
3018 BrowserActivity.this.startActivityForResult(cameraIntent, FILE_SELECTED);
3019 return;
Ben Murdochb50d7402010-07-16 12:42:22 +01003020 } else if (mediaSource.equals(mediaSourceValueFileSystem)) {
3021 // Specified filesytem as the source, so don't want to consider the camera.
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003022 addCameraIntent = false;
3023 }
Ben Murdoch6af492a2010-06-15 12:38:17 +01003024 } else if (mimeType.equals(videoMimeType)) {
3025 i.setType(videoMimeType);
3026 addCameraIntent = false;
3027 // The camcorder saves it's own file and returns it to us in the intent, so
3028 // we don't need to generate one here.
3029 mCameraFilePath = null;
3030
3031 if (mediaSource.equals(mediaSourceValueCamcorder)) {
Ben Murdoch039bd472010-07-21 21:26:57 +01003032 // Specified 'video/*' and requested the camcorder, so go ahead and launch the
3033 // camcorder directly.
Ben Murdoch6af492a2010-06-15 12:38:17 +01003034 BrowserActivity.this.startActivityForResult(camcorderIntent, FILE_SELECTED);
3035 return;
Ben Murdochb50d7402010-07-16 12:42:22 +01003036 } else if (mediaSource.equals(mediaSourceValueFileSystem)) {
3037 // Specified filesystem as the source, so don't want to consider the camcorder.
Ben Murdoch6af492a2010-06-15 12:38:17 +01003038 addCamcorderIntent = false;
3039 }
Ben Murdoch039bd472010-07-21 21:26:57 +01003040 } else if (mimeType.equals(audioMimeType)) {
3041 i.setType(audioMimeType);
3042 addCameraIntent = false;
3043 addCamcorderIntent = false;
3044 if (mediaSource.equals(mediaSourceValueMicrophone)) {
3045 // Specified 'audio/*' and requested microphone, so go ahead and launch the sound
3046 // recorder.
3047 BrowserActivity.this.startActivityForResult(soundRecIntent, FILE_SELECTED);
3048 return;
3049 }
3050 // On a default system, there is no single option to open an audio "gallery". Both the
3051 // sound recorder and music browser respond to the OPENABLE/audio/* intent unlike the
3052 // image/* and video/* OPENABLE intents where the image / video gallery are the only
3053 // respondants (and so the user is not prompted by default).
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003054 } else {
3055 i.setType("*/*");
3056 }
3057
Ben Murdoch6af492a2010-06-15 12:38:17 +01003058 // Combine the chooser and the extra choices (like camera or camcorder)
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003059 Intent chooser = new Intent(Intent.ACTION_CHOOSER);
3060 chooser.putExtra(Intent.EXTRA_INTENT, i);
3061
Ben Murdoch6af492a2010-06-15 12:38:17 +01003062 Vector<Intent> extraInitialIntents = new Vector<Intent>(0);
3063
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003064 if (addCameraIntent) {
Ben Murdoch6af492a2010-06-15 12:38:17 +01003065 extraInitialIntents.add(cameraIntent);
3066 }
3067
3068 if (addCamcorderIntent) {
3069 extraInitialIntents.add(camcorderIntent);
3070 }
3071
3072 if (extraInitialIntents.size() > 0) {
3073 Intent[] extraIntents = new Intent[extraInitialIntents.size()];
3074 chooser.putExtra(Intent.EXTRA_INITIAL_INTENTS, extraInitialIntents.toArray(extraIntents));
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003075 }
3076
3077 chooser.putExtra(Intent.EXTRA_TITLE, getString(R.string.choose_upload));
3078 BrowserActivity.this.startActivityForResult(chooser, FILE_SELECTED);
Grace Kloba22ac16e2009-10-07 18:00:23 -07003079 }
3080
3081 // -------------------------------------------------------------------------
3082 // Implement functions for DownloadListener
3083 // -------------------------------------------------------------------------
3084
The Android Open Source Project0c908882009-03-03 19:32:16 -08003085 /**
3086 * Notify the host application a download should be done, or that
3087 * the data should be streamed if a streaming viewer is available.
3088 * @param url The full url to the content that should be downloaded
3089 * @param contentDisposition Content-disposition http header, if
3090 * present.
3091 * @param mimetype The mimetype of the content reported by the server
3092 * @param contentLength The file size reported by the server
3093 */
3094 public void onDownloadStart(String url, String userAgent,
3095 String contentDisposition, String mimetype, long contentLength) {
3096 // if we're dealing wih A/V content that's not explicitly marked
3097 // for download, check if it's streamable.
3098 if (contentDisposition == null
Patrick Scotte1fb9662009-08-31 14:31:52 -04003099 || !contentDisposition.regionMatches(
3100 true, 0, "attachment", 0, 10)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003101 // query the package manager to see if there's a registered handler
3102 // that matches.
3103 Intent intent = new Intent(Intent.ACTION_VIEW);
3104 intent.setDataAndType(Uri.parse(url), mimetype);
Patrick Scotte1fb9662009-08-31 14:31:52 -04003105 ResolveInfo info = getPackageManager().resolveActivity(intent,
3106 PackageManager.MATCH_DEFAULT_ONLY);
3107 if (info != null) {
3108 ComponentName myName = getComponentName();
3109 // If we resolved to ourselves, we don't want to attempt to
3110 // load the url only to try and download it again.
3111 if (!myName.getPackageName().equals(
3112 info.activityInfo.packageName)
3113 || !myName.getClassName().equals(
3114 info.activityInfo.name)) {
3115 // someone (other than us) knows how to handle this mime
3116 // type with this scheme, don't download.
3117 try {
3118 startActivity(intent);
3119 return;
3120 } catch (ActivityNotFoundException ex) {
3121 if (LOGD_ENABLED) {
3122 Log.d(LOGTAG, "activity not found for " + mimetype
3123 + " over " + Uri.parse(url).getScheme(),
3124 ex);
3125 }
3126 // Best behavior is to fall back to a download in this
3127 // case
The Android Open Source Project0c908882009-03-03 19:32:16 -08003128 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003129 }
3130 }
3131 }
3132 onDownloadStartNoStream(url, userAgent, contentDisposition, mimetype, contentLength);
3133 }
3134
Kristian Monsenfa52d172010-03-25 18:29:21 +00003135 // This is to work around the fact that java.net.URI throws Exceptions
3136 // instead of just encoding URL's properly
3137 // Helper method for onDownloadStartNoStream
3138 private static String encodePath(String path) {
3139 char[] chars = path.toCharArray();
3140
3141 boolean needed = false;
3142 for (char c : chars) {
3143 if (c == '[' || c == ']') {
3144 needed = true;
3145 break;
3146 }
3147 }
3148 if (needed == false) {
3149 return path;
3150 }
3151
3152 StringBuilder sb = new StringBuilder("");
3153 for (char c : chars) {
3154 if (c == '[' || c == ']') {
3155 sb.append('%');
3156 sb.append(Integer.toHexString(c));
3157 } else {
3158 sb.append(c);
3159 }
3160 }
3161
3162 return sb.toString();
3163 }
3164
The Android Open Source Project0c908882009-03-03 19:32:16 -08003165 /**
3166 * Notify the host application a download should be done, even if there
3167 * is a streaming viewer available for thise type.
3168 * @param url The full url to the content that should be downloaded
3169 * @param contentDisposition Content-disposition http header, if
3170 * present.
3171 * @param mimetype The mimetype of the content reported by the server
3172 * @param contentLength The file size reported by the server
3173 */
3174 /*package */ void onDownloadStartNoStream(String url, String userAgent,
3175 String contentDisposition, String mimetype, long contentLength) {
3176
3177 String filename = URLUtil.guessFileName(url,
3178 contentDisposition, mimetype);
3179
3180 // Check to see if we have an SDCard
3181 String status = Environment.getExternalStorageState();
3182 if (!status.equals(Environment.MEDIA_MOUNTED)) {
3183 int title;
3184 String msg;
3185
3186 // Check to see if the SDCard is busy, same as the music app
3187 if (status.equals(Environment.MEDIA_SHARED)) {
3188 msg = getString(R.string.download_sdcard_busy_dlg_msg);
3189 title = R.string.download_sdcard_busy_dlg_title;
3190 } else {
3191 msg = getString(R.string.download_no_sdcard_dlg_msg, filename);
3192 title = R.string.download_no_sdcard_dlg_title;
3193 }
3194
3195 new AlertDialog.Builder(this)
3196 .setTitle(title)
3197 .setIcon(android.R.drawable.ic_dialog_alert)
3198 .setMessage(msg)
3199 .setPositiveButton(R.string.ok, null)
3200 .show();
3201 return;
3202 }
3203
Kristian Monsenfa52d172010-03-25 18:29:21 +00003204 // java.net.URI is a lot stricter than KURL so we have to encode some
3205 // extra characters. Fix for b 2538060 and b 1634719
3206 WebAddress webAddress;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003207 try {
Kristian Monsenfa52d172010-03-25 18:29:21 +00003208 webAddress = new WebAddress(url);
3209 webAddress.mPath = encodePath(webAddress.mPath);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003210 } catch (Exception e) {
Kristian Monsenfa52d172010-03-25 18:29:21 +00003211 // This only happens for very bad urls, we want to chatch the
3212 // exception here
3213 Log.e(LOGTAG, "Exception trying to parse url:" + url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003214 return;
3215 }
3216
3217 // XXX: Have to use the old url since the cookies were stored using the
3218 // old percent-encoded url.
3219 String cookies = CookieManager.getInstance().getCookie(url);
3220
3221 ContentValues values = new ContentValues();
Kristian Monsenfa52d172010-03-25 18:29:21 +00003222 values.put(Downloads.Impl.COLUMN_URI, webAddress.toString());
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08003223 values.put(Downloads.Impl.COLUMN_COOKIE_DATA, cookies);
3224 values.put(Downloads.Impl.COLUMN_USER_AGENT, userAgent);
3225 values.put(Downloads.Impl.COLUMN_NOTIFICATION_PACKAGE,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003226 getPackageName());
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08003227 values.put(Downloads.Impl.COLUMN_NOTIFICATION_CLASS,
Leon Scrogginsa563d092010-04-19 16:53:49 -04003228 OpenDownloadReceiver.class.getCanonicalName());
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08003229 values.put(Downloads.Impl.COLUMN_VISIBILITY,
3230 Downloads.Impl.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
3231 values.put(Downloads.Impl.COLUMN_MIME_TYPE, mimetype);
3232 values.put(Downloads.Impl.COLUMN_FILE_NAME_HINT, filename);
Kristian Monsenfa52d172010-03-25 18:29:21 +00003233 values.put(Downloads.Impl.COLUMN_DESCRIPTION, webAddress.mHost);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003234 if (contentLength > 0) {
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08003235 values.put(Downloads.Impl.COLUMN_TOTAL_BYTES, contentLength);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003236 }
3237 if (mimetype == null) {
3238 // We must have long pressed on a link or image to download it. We
3239 // are not sure of the mimetype in this case, so do a head request
3240 new FetchUrlMimeType(this).execute(values);
3241 } else {
3242 final Uri contentUri =
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08003243 getContentResolver().insert(Downloads.Impl.CONTENT_URI, values);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003244 }
Leon Scroggins9191a7f2010-03-18 14:44:44 -04003245 Toast.makeText(this, R.string.download_pending, Toast.LENGTH_SHORT)
3246 .show();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003247 }
3248
Grace Kloba22ac16e2009-10-07 18:00:23 -07003249 // -------------------------------------------------------------------------
3250
The Android Open Source Project0c908882009-03-03 19:32:16 -08003251 /**
3252 * Resets the lock icon. This method is called when we start a new load and
3253 * know the url to be loaded.
3254 */
3255 private void resetLockIcon(String url) {
3256 // Save the lock-icon state (we revert to it if the load gets cancelled)
Grace Kloba22ac16e2009-10-07 18:00:23 -07003257 mTabControl.getCurrentTab().resetLockIcon(url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003258 updateLockIconImage(LOCK_ICON_UNSECURE);
3259 }
3260
The Android Open Source Project0c908882009-03-03 19:32:16 -08003261 /**
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04003262 * Update the lock icon to correspond to our latest state.
3263 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003264 private void updateLockIconToLatest() {
Leon Scroggins91f65fc2010-06-29 13:52:39 -04003265 Tab t = mTabControl.getCurrentTab();
3266 if (t != null) {
3267 updateLockIconImage(t.getLockIconType());
3268 }
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04003269 }
3270
3271 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08003272 * Updates the lock-icon image in the title-bar.
3273 */
3274 private void updateLockIconImage(int lockIconType) {
3275 Drawable d = null;
3276 if (lockIconType == LOCK_ICON_SECURE) {
3277 d = mSecLockIcon;
3278 } else if (lockIconType == LOCK_ICON_MIXED) {
3279 d = mMixLockIcon;
3280 }
Leon Scroggins68579392009-09-15 15:31:54 -04003281 mTitleBar.setLock(d);
Michael Kolba2b2ba82010-08-04 17:54:03 -07003282 mFakeTitleBar.setLock(d);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003283 }
3284
3285 /**
3286 * Displays a page-info dialog.
3287 * @param tab The tab to show info about
3288 * @param fromShowSSLCertificateOnError The flag that indicates whether
3289 * this dialog was opened from the SSL-certificate-on-error dialog or
3290 * not. This is important, since we need to know whether to return to
3291 * the parent dialog or simply dismiss.
3292 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003293 private void showPageInfo(final Tab tab,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003294 final boolean fromShowSSLCertificateOnError) {
3295 final LayoutInflater factory = LayoutInflater
3296 .from(this);
3297
3298 final View pageInfoView = factory.inflate(R.layout.page_info, null);
3299
3300 final WebView view = tab.getWebView();
3301
3302 String url = null;
3303 String title = null;
3304
3305 if (view == null) {
3306 url = tab.getUrl();
3307 title = tab.getTitle();
3308 } else if (view == mTabControl.getCurrentWebView()) {
3309 // Use the cached title and url if this is the current WebView
3310 url = mUrl;
3311 title = mTitle;
3312 } else {
3313 url = view.getUrl();
3314 title = view.getTitle();
3315 }
3316
3317 if (url == null) {
3318 url = "";
3319 }
3320 if (title == null) {
3321 title = "";
3322 }
3323
3324 ((TextView) pageInfoView.findViewById(R.id.address)).setText(url);
3325 ((TextView) pageInfoView.findViewById(R.id.title)).setText(title);
3326
3327 mPageInfoView = tab;
Leon Scrogginsc7b92f82010-01-11 18:17:31 -05003328 mPageInfoFromShowSSLCertificateOnError = fromShowSSLCertificateOnError;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003329
3330 AlertDialog.Builder alertDialogBuilder =
3331 new AlertDialog.Builder(this)
3332 .setTitle(R.string.page_info).setIcon(android.R.drawable.ic_dialog_info)
3333 .setView(pageInfoView)
3334 .setPositiveButton(
3335 R.string.ok,
3336 new DialogInterface.OnClickListener() {
3337 public void onClick(DialogInterface dialog,
3338 int whichButton) {
3339 mPageInfoDialog = null;
3340 mPageInfoView = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003341
3342 // if we came here from the SSL error dialog
3343 if (fromShowSSLCertificateOnError) {
3344 // go back to the SSL error dialog
3345 showSSLCertificateOnError(
3346 mSSLCertificateOnErrorView,
3347 mSSLCertificateOnErrorHandler,
3348 mSSLCertificateOnErrorError);
3349 }
3350 }
3351 })
3352 .setOnCancelListener(
3353 new DialogInterface.OnCancelListener() {
3354 public void onCancel(DialogInterface dialog) {
3355 mPageInfoDialog = null;
3356 mPageInfoView = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003357
3358 // if we came here from the SSL error dialog
3359 if (fromShowSSLCertificateOnError) {
3360 // go back to the SSL error dialog
3361 showSSLCertificateOnError(
3362 mSSLCertificateOnErrorView,
3363 mSSLCertificateOnErrorHandler,
3364 mSSLCertificateOnErrorError);
3365 }
3366 }
3367 });
3368
3369 // if we have a main top-level page SSL certificate set or a certificate
3370 // error
3371 if (fromShowSSLCertificateOnError ||
3372 (view != null && view.getCertificate() != null)) {
3373 // add a 'View Certificate' button
3374 alertDialogBuilder.setNeutralButton(
3375 R.string.view_certificate,
3376 new DialogInterface.OnClickListener() {
3377 public void onClick(DialogInterface dialog,
3378 int whichButton) {
3379 mPageInfoDialog = null;
3380 mPageInfoView = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003381
3382 // if we came here from the SSL error dialog
3383 if (fromShowSSLCertificateOnError) {
3384 // go back to the SSL error dialog
3385 showSSLCertificateOnError(
3386 mSSLCertificateOnErrorView,
3387 mSSLCertificateOnErrorHandler,
3388 mSSLCertificateOnErrorError);
3389 } else {
3390 // otherwise, display the top-most certificate from
3391 // the chain
3392 if (view.getCertificate() != null) {
3393 showSSLCertificate(tab);
3394 }
3395 }
3396 }
3397 });
3398 }
3399
3400 mPageInfoDialog = alertDialogBuilder.show();
3401 }
3402
3403 /**
3404 * Displays the main top-level page SSL certificate dialog
3405 * (accessible from the Page-Info dialog).
3406 * @param tab The tab to show certificate for.
3407 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003408 private void showSSLCertificate(final Tab tab) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003409 final View certificateView =
3410 inflateCertificateView(tab.getWebView().getCertificate());
3411 if (certificateView == null) {
3412 return;
3413 }
3414
3415 LayoutInflater factory = LayoutInflater.from(this);
3416
3417 final LinearLayout placeholder =
3418 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3419
3420 LinearLayout ll = (LinearLayout) factory.inflate(
3421 R.layout.ssl_success, placeholder);
3422 ((TextView)ll.findViewById(R.id.success))
3423 .setText(R.string.ssl_certificate_is_valid);
3424
3425 mSSLCertificateView = tab;
3426 mSSLCertificateDialog =
3427 new AlertDialog.Builder(this)
3428 .setTitle(R.string.ssl_certificate).setIcon(
3429 R.drawable.ic_dialog_browser_certificate_secure)
3430 .setView(certificateView)
3431 .setPositiveButton(R.string.ok,
3432 new DialogInterface.OnClickListener() {
3433 public void onClick(DialogInterface dialog,
3434 int whichButton) {
3435 mSSLCertificateDialog = null;
3436 mSSLCertificateView = null;
3437
3438 showPageInfo(tab, false);
3439 }
3440 })
3441 .setOnCancelListener(
3442 new DialogInterface.OnCancelListener() {
3443 public void onCancel(DialogInterface dialog) {
3444 mSSLCertificateDialog = null;
3445 mSSLCertificateView = null;
3446
3447 showPageInfo(tab, false);
3448 }
3449 })
3450 .show();
3451 }
3452
3453 /**
3454 * Displays the SSL error certificate dialog.
3455 * @param view The target web-view.
3456 * @param handler The SSL error handler responsible for cancelling the
3457 * connection that resulted in an SSL error or proceeding per user request.
3458 * @param error The SSL error object.
3459 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003460 void showSSLCertificateOnError(
The Android Open Source Project0c908882009-03-03 19:32:16 -08003461 final WebView view, final SslErrorHandler handler, final SslError error) {
3462
3463 final View certificateView =
3464 inflateCertificateView(error.getCertificate());
3465 if (certificateView == null) {
3466 return;
3467 }
3468
3469 LayoutInflater factory = LayoutInflater.from(this);
3470
3471 final LinearLayout placeholder =
3472 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3473
3474 if (error.hasError(SslError.SSL_UNTRUSTED)) {
3475 LinearLayout ll = (LinearLayout)factory
3476 .inflate(R.layout.ssl_warning, placeholder);
3477 ((TextView)ll.findViewById(R.id.warning))
3478 .setText(R.string.ssl_untrusted);
3479 }
3480
3481 if (error.hasError(SslError.SSL_IDMISMATCH)) {
3482 LinearLayout ll = (LinearLayout)factory
3483 .inflate(R.layout.ssl_warning, placeholder);
3484 ((TextView)ll.findViewById(R.id.warning))
3485 .setText(R.string.ssl_mismatch);
3486 }
3487
3488 if (error.hasError(SslError.SSL_EXPIRED)) {
3489 LinearLayout ll = (LinearLayout)factory
3490 .inflate(R.layout.ssl_warning, placeholder);
3491 ((TextView)ll.findViewById(R.id.warning))
3492 .setText(R.string.ssl_expired);
3493 }
3494
3495 if (error.hasError(SslError.SSL_NOTYETVALID)) {
3496 LinearLayout ll = (LinearLayout)factory
3497 .inflate(R.layout.ssl_warning, placeholder);
3498 ((TextView)ll.findViewById(R.id.warning))
3499 .setText(R.string.ssl_not_yet_valid);
3500 }
3501
3502 mSSLCertificateOnErrorHandler = handler;
3503 mSSLCertificateOnErrorView = view;
3504 mSSLCertificateOnErrorError = error;
3505 mSSLCertificateOnErrorDialog =
3506 new AlertDialog.Builder(this)
3507 .setTitle(R.string.ssl_certificate).setIcon(
3508 R.drawable.ic_dialog_browser_certificate_partially_secure)
3509 .setView(certificateView)
3510 .setPositiveButton(R.string.ok,
3511 new DialogInterface.OnClickListener() {
3512 public void onClick(DialogInterface dialog,
3513 int whichButton) {
3514 mSSLCertificateOnErrorDialog = null;
3515 mSSLCertificateOnErrorView = null;
3516 mSSLCertificateOnErrorHandler = null;
3517 mSSLCertificateOnErrorError = null;
3518
Grace Kloba22ac16e2009-10-07 18:00:23 -07003519 view.getWebViewClient().onReceivedSslError(
3520 view, handler, error);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003521 }
3522 })
3523 .setNeutralButton(R.string.page_info_view,
3524 new DialogInterface.OnClickListener() {
3525 public void onClick(DialogInterface dialog,
3526 int whichButton) {
3527 mSSLCertificateOnErrorDialog = null;
3528
3529 // do not clear the dialog state: we will
3530 // need to show the dialog again once the
3531 // user is done exploring the page-info details
3532
3533 showPageInfo(mTabControl.getTabFromView(view),
3534 true);
3535 }
3536 })
3537 .setOnCancelListener(
3538 new DialogInterface.OnCancelListener() {
3539 public void onCancel(DialogInterface dialog) {
3540 mSSLCertificateOnErrorDialog = null;
3541 mSSLCertificateOnErrorView = null;
3542 mSSLCertificateOnErrorHandler = null;
3543 mSSLCertificateOnErrorError = null;
3544
Grace Kloba22ac16e2009-10-07 18:00:23 -07003545 view.getWebViewClient().onReceivedSslError(
3546 view, handler, error);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003547 }
3548 })
3549 .show();
3550 }
3551
3552 /**
3553 * Inflates the SSL certificate view (helper method).
3554 * @param certificate The SSL certificate.
3555 * @return The resultant certificate view with issued-to, issued-by,
3556 * issued-on, expires-on, and possibly other fields set.
3557 * If the input certificate is null, returns null.
3558 */
3559 private View inflateCertificateView(SslCertificate certificate) {
3560 if (certificate == null) {
3561 return null;
3562 }
3563
3564 LayoutInflater factory = LayoutInflater.from(this);
3565
3566 View certificateView = factory.inflate(
3567 R.layout.ssl_certificate, null);
3568
3569 // issued to:
3570 SslCertificate.DName issuedTo = certificate.getIssuedTo();
3571 if (issuedTo != null) {
3572 ((TextView) certificateView.findViewById(R.id.to_common))
3573 .setText(issuedTo.getCName());
3574 ((TextView) certificateView.findViewById(R.id.to_org))
3575 .setText(issuedTo.getOName());
3576 ((TextView) certificateView.findViewById(R.id.to_org_unit))
3577 .setText(issuedTo.getUName());
3578 }
3579
3580 // issued by:
3581 SslCertificate.DName issuedBy = certificate.getIssuedBy();
3582 if (issuedBy != null) {
3583 ((TextView) certificateView.findViewById(R.id.by_common))
3584 .setText(issuedBy.getCName());
3585 ((TextView) certificateView.findViewById(R.id.by_org))
3586 .setText(issuedBy.getOName());
3587 ((TextView) certificateView.findViewById(R.id.by_org_unit))
3588 .setText(issuedBy.getUName());
3589 }
3590
3591 // issued on:
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003592 String issuedOn = formatCertificateDate(
3593 certificate.getValidNotBeforeDate());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003594 ((TextView) certificateView.findViewById(R.id.issued_on))
3595 .setText(issuedOn);
3596
3597 // expires on:
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003598 String expiresOn = formatCertificateDate(
3599 certificate.getValidNotAfterDate());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003600 ((TextView) certificateView.findViewById(R.id.expires_on))
3601 .setText(expiresOn);
3602
3603 return certificateView;
3604 }
3605
3606 /**
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003607 * Formats the certificate date to a properly localized date string.
The Android Open Source Project0c908882009-03-03 19:32:16 -08003608 * @return Properly localized version of the certificate date string and
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003609 * the "" if it fails to localize.
The Android Open Source Project0c908882009-03-03 19:32:16 -08003610 */
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003611 private String formatCertificateDate(Date certificateDate) {
3612 if (certificateDate == null) {
3613 return "";
The Android Open Source Project0c908882009-03-03 19:32:16 -08003614 }
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003615 String formattedDate = DateFormat.getDateFormat(this).format(certificateDate);
3616 if (formattedDate == null) {
3617 return "";
3618 }
3619 return formattedDate;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003620 }
3621
3622 /**
3623 * Displays an http-authentication dialog.
3624 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003625 void showHttpAuthentication(final HttpAuthHandler handler,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003626 final String host, final String realm, final String title,
3627 final String name, final String password, int focusId) {
3628 LayoutInflater factory = LayoutInflater.from(this);
3629 final View v = factory
3630 .inflate(R.layout.http_authentication, null);
3631 if (name != null) {
3632 ((EditText) v.findViewById(R.id.username_edit)).setText(name);
3633 }
3634 if (password != null) {
3635 ((EditText) v.findViewById(R.id.password_edit)).setText(password);
3636 }
3637
3638 String titleText = title;
3639 if (titleText == null) {
3640 titleText = getText(R.string.sign_in_to).toString().replace(
3641 "%s1", host).replace("%s2", realm);
3642 }
3643
3644 mHttpAuthHandler = handler;
3645 AlertDialog dialog = new AlertDialog.Builder(this)
3646 .setTitle(titleText)
3647 .setIcon(android.R.drawable.ic_dialog_alert)
3648 .setView(v)
3649 .setPositiveButton(R.string.action,
3650 new DialogInterface.OnClickListener() {
3651 public void onClick(DialogInterface dialog,
3652 int whichButton) {
3653 String nm = ((EditText) v
3654 .findViewById(R.id.username_edit))
3655 .getText().toString();
3656 String pw = ((EditText) v
3657 .findViewById(R.id.password_edit))
3658 .getText().toString();
3659 BrowserActivity.this.setHttpAuthUsernamePassword
3660 (host, realm, nm, pw);
3661 handler.proceed(nm, pw);
3662 mHttpAuthenticationDialog = null;
3663 mHttpAuthHandler = null;
3664 }})
3665 .setNegativeButton(R.string.cancel,
3666 new DialogInterface.OnClickListener() {
3667 public void onClick(DialogInterface dialog,
3668 int whichButton) {
3669 handler.cancel();
3670 BrowserActivity.this.resetTitleAndRevertLockIcon();
3671 mHttpAuthenticationDialog = null;
3672 mHttpAuthHandler = null;
3673 }})
3674 .setOnCancelListener(new DialogInterface.OnCancelListener() {
3675 public void onCancel(DialogInterface dialog) {
3676 handler.cancel();
3677 BrowserActivity.this.resetTitleAndRevertLockIcon();
3678 mHttpAuthenticationDialog = null;
3679 mHttpAuthHandler = null;
3680 }})
3681 .create();
3682 // Make the IME appear when the dialog is displayed if applicable.
3683 dialog.getWindow().setSoftInputMode(
3684 WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
3685 dialog.show();
3686 if (focusId != 0) {
3687 dialog.findViewById(focusId).requestFocus();
3688 } else {
3689 v.findViewById(R.id.username_edit).requestFocus();
3690 }
3691 mHttpAuthenticationDialog = dialog;
3692 }
3693
3694 public int getProgress() {
3695 WebView w = mTabControl.getCurrentWebView();
3696 if (w != null) {
3697 return w.getProgress();
3698 } else {
3699 return 100;
3700 }
3701 }
3702
3703 /**
3704 * Set HTTP authentication password.
3705 *
3706 * @param host The host for the password
3707 * @param realm The realm for the password
3708 * @param username The username for the password. If it is null, it means
3709 * password can't be saved.
3710 * @param password The password
3711 */
3712 public void setHttpAuthUsernamePassword(String host, String realm,
3713 String username,
3714 String password) {
Steve Block95a53b22010-03-25 17:24:58 +00003715 WebView w = getTopWindow();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003716 if (w != null) {
3717 w.setHttpAuthUsernamePassword(host, realm, username, password);
3718 }
3719 }
3720
3721 /**
3722 * connectivity manager says net has come or gone... inform the user
3723 * @param up true if net has come up, false if net has gone down
3724 */
3725 public void onNetworkToggle(boolean up) {
3726 if (up == mIsNetworkUp) {
3727 return;
3728 } else if (up) {
3729 mIsNetworkUp = true;
3730 if (mAlertDialog != null) {
3731 mAlertDialog.cancel();
3732 mAlertDialog = null;
3733 }
3734 } else {
3735 mIsNetworkUp = false;
Patrick Scotteb6ab2a2009-09-16 10:00:17 -04003736 if (mInLoad) {
3737 createAndShowNetworkDialog();
3738 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003739 }
3740 WebView w = mTabControl.getCurrentWebView();
3741 if (w != null) {
3742 w.setNetworkAvailable(up);
3743 }
3744 }
3745
Grace Kloba22ac16e2009-10-07 18:00:23 -07003746 boolean isNetworkUp() {
3747 return mIsNetworkUp;
3748 }
3749
Patrick Scotteb6ab2a2009-09-16 10:00:17 -04003750 // This method shows the network dialog alerting the user that the net is
3751 // down. It will only show the dialog if mAlertDialog is null.
3752 private void createAndShowNetworkDialog() {
3753 if (mAlertDialog == null) {
3754 mAlertDialog = new AlertDialog.Builder(this)
3755 .setTitle(R.string.loadSuspendedTitle)
3756 .setMessage(R.string.loadSuspended)
3757 .setPositiveButton(R.string.ok, null)
3758 .show();
3759 }
3760 }
3761
The Android Open Source Project0c908882009-03-03 19:32:16 -08003762 @Override
3763 protected void onActivityResult(int requestCode, int resultCode,
3764 Intent intent) {
Grace Klobabb394f32009-11-19 10:26:37 -08003765 if (getTopWindow() == null) return;
3766
The Android Open Source Project0c908882009-03-03 19:32:16 -08003767 switch (requestCode) {
3768 case COMBO_PAGE:
3769 if (resultCode == RESULT_OK && intent != null) {
3770 String data = intent.getAction();
3771 Bundle extras = intent.getExtras();
3772 if (extras != null && extras.getBoolean("new_window", false)) {
Michael Kolb68792c82010-08-09 16:39:18 -07003773 openTab(data, false);
3774 } else if ((extras != null) &&
3775 extras.getBoolean(CombinedBookmarkHistoryActivity.NEWTAB_MODE)) {
3776 openTab(data, true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003777 } else {
Michael Kolb68792c82010-08-09 16:39:18 -07003778 final Tab currentTab = mTabControl.getCurrentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04003779 dismissSubWindow(currentTab);
3780 if (data != null && data.length() != 0) {
Leon Scroggins92472e82010-02-17 16:32:28 -05003781 loadUrl(getTopWindow(), data);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003782 }
3783 }
3784 }
Leon Scrogginsfde97462010-01-11 13:06:21 -05003785 // Deliberately fall through to PREFERENCES_PAGE, since the
3786 // same extra may be attached to the COMBO_PAGE
3787 case PREFERENCES_PAGE:
3788 if (resultCode == RESULT_OK && intent != null) {
3789 String action = intent.getStringExtra(Intent.EXTRA_TEXT);
3790 if (BrowserSettings.PREF_CLEAR_HISTORY.equals(action)) {
3791 mTabControl.removeParentChildRelationShips();
3792 }
3793 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003794 break;
Leon Scroggins8d5fa432009-10-02 15:55:59 -04003795 // Choose a file from the file picker.
3796 case FILE_SELECTED:
3797 if (null == mUploadMessage) break;
3798 Uri result = intent == null || resultCode != RESULT_OK ? null
3799 : intent.getData();
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003800
3801 // As we ask the camera to save the result of the user taking
3802 // a picture, the camera application does not return anything other
3803 // than RESULT_OK. So we need to check whether the file we expected
3804 // was written to disk in the in the case that we
3805 // did not get an intent returned but did get a RESULT_OK. If it was,
3806 // we assume that this result has came back from the camera.
3807 if (result == null && intent == null && resultCode == RESULT_OK) {
3808 File cameraFile = new File(mCameraFilePath);
3809 if (cameraFile.exists()) {
3810 result = Uri.fromFile(cameraFile);
Ben Murdoch07d34732010-05-27 18:34:46 +01003811 // Broadcast to the media scanner that we have a new photo
3812 // so it will be added into the gallery for the user.
3813 sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, result));
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003814 }
3815 }
Leon Scroggins8d5fa432009-10-02 15:55:59 -04003816 mUploadMessage.onReceiveValue(result);
3817 mUploadMessage = null;
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003818 mCameraFilePath = null;
Leon Scroggins8d5fa432009-10-02 15:55:59 -04003819 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003820 default:
3821 break;
3822 }
Leon Scroggins30444232009-09-04 18:36:20 -04003823 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003824 }
3825
3826 /*
3827 * This method is called as a result of the user selecting the options
Leon Scrogginsf08809b2010-01-21 09:27:46 -05003828 * menu to see the download window. It shows the download window on top of
3829 * the current window.
The Android Open Source Project0c908882009-03-03 19:32:16 -08003830 */
Leon Scrogginsf08809b2010-01-21 09:27:46 -05003831 private void viewDownloads(Uri downloadRecord) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003832 Intent intent = new Intent(this,
3833 BrowserDownloadPage.class);
3834 intent.setData(downloadRecord);
Grace Kloba22ac16e2009-10-07 18:00:23 -07003835 startActivityForResult(intent, BrowserActivity.DOWNLOAD_PAGE);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003836
3837 }
3838
Ben Murdocheecb4e62010-07-06 16:30:38 +01003839 /* package*/ void promptAddOrInstallBookmark() {
3840 final Tab current = mTabControl.getCurrentTab();
3841 Resources resources = getResources();
3842 CharSequence[] choices = {
3843 resources.getString(R.string.save_to_bookmarks),
3844 resources.getString(R.string.create_shortcut_bookmark)
3845 };
3846
3847 AlertDialog.Builder builder = new AlertDialog.Builder(this);
3848 builder.setTitle(R.string.add_new_bookmark);
3849 builder.setItems(choices, new DialogInterface.OnClickListener() {
3850 public void onClick(DialogInterface dialog, int item) {
3851 if (item == 0) {
3852 bookmarkCurrentPage();
3853 } else if (item == 1) {
3854 current.populatePickerData();
3855 String touchIconUrl = mTabControl.getCurrentWebView().getTouchIconUrl();
3856 if (touchIconUrl != null) {
3857 // Download the touch icon for this site then save it to the
3858 // homescreen.
3859 Bundle b = new Bundle();
3860 b.putString("url", current.getUrl());
3861 b.putString("title", current.getTitle());
3862 b.putParcelable("favicon", current.getFavicon());
3863 Message msg = mHandler.obtainMessage(TOUCH_ICON_DOWNLOADED);
3864 msg.setData(b);
Ben Murdochccb5de02010-07-19 18:38:17 +01003865 new DownloadTouchIcon(BrowserActivity.this, msg,
Ben Murdocheecb4e62010-07-06 16:30:38 +01003866 mTabControl.getCurrentWebView().getSettings()
3867 .getUserAgentString()).execute(touchIconUrl);
3868 } else {
3869 // add to homescreen, can do it immediately as there is no touch
3870 // icon.
3871 showSaveToHomescreenDialog(current.getUrl(), current.getTitle(),
3872 null, current.getFavicon());
3873 }
3874 }
3875 }
3876 });
3877 builder.create().show();
3878 }
3879
Leon Scroggins160a7e72009-08-14 18:28:01 -04003880 /**
3881 * Open the Go page.
3882 * @param startWithHistory If true, open starting on the history tab.
3883 * Otherwise, start with the bookmarks tab.
Leon Scroggins160a7e72009-08-14 18:28:01 -04003884 */
Michael Kolb68792c82010-08-09 16:39:18 -07003885 /* package */ void bookmarksOrHistoryPicker(boolean startWithHistory, boolean newTabMode) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003886 WebView current = mTabControl.getCurrentWebView();
3887 if (current == null) {
3888 return;
3889 }
3890 Intent intent = new Intent(this,
3891 CombinedBookmarkHistoryActivity.class);
3892 String title = current.getTitle();
3893 String url = current.getUrl();
Ben Murdoch87cc65d2010-06-29 20:34:10 +01003894 Bitmap thumbnail = createScreenshot(current, getDesiredThumbnailWidth(this),
3895 getDesiredThumbnailHeight(this));
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01003896
The Android Open Source Project0c908882009-03-03 19:32:16 -08003897 // Just in case the user opens bookmarks before a page finishes loading
3898 // so the current history item, and therefore the page, is null.
3899 if (null == url) {
3900 url = mLastEnteredUrl;
3901 // This can happen.
3902 if (null == url) {
3903 url = mSettings.getHomePage();
3904 }
3905 }
3906 // In case the web page has not yet received its associated title.
3907 if (title == null) {
3908 title = url;
3909 }
3910 intent.putExtra("title", title);
3911 intent.putExtra("url", url);
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01003912 intent.putExtra("thumbnail", thumbnail);
Leon Scroggins30444232009-09-04 18:36:20 -04003913 // Disable opening in a new window if we have maxed out the windows
Grace Kloba22ac16e2009-10-07 18:00:23 -07003914 intent.putExtra("disable_new_window", !mTabControl.canCreateNewTab());
Patrick Scott3918d442009-08-04 13:22:29 -04003915 intent.putExtra("touch_icon_url", current.getTouchIconUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003916 if (startWithHistory) {
3917 intent.putExtra(CombinedBookmarkHistoryActivity.STARTING_TAB,
3918 CombinedBookmarkHistoryActivity.HISTORY_TAB);
3919 }
Michael Kolb68792c82010-08-09 16:39:18 -07003920 if (newTabMode) {
3921 intent.putExtra(CombinedBookmarkHistoryActivity.NEWTAB_MODE, true);
3922 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003923 startActivityForResult(intent, COMBO_PAGE);
3924 }
3925
Ben Murdocheecb4e62010-07-06 16:30:38 +01003926 private void showSaveToHomescreenDialog(String url, String title, Bitmap touchIcon,
3927 Bitmap favicon) {
3928 Intent intent = new Intent(this, SaveToHomescreenDialog.class);
3929
3930 // Just in case the user tries to save before a page finishes loading
3931 // so the current history item, and therefore the page, is null.
3932 if (null == url) {
3933 url = mLastEnteredUrl;
3934 // This can happen.
3935 if (null == url) {
3936 url = mSettings.getHomePage();
3937 }
3938 }
3939
3940 // In case the web page has not yet received its associated title.
3941 if (title == null) {
3942 title = url;
3943 }
3944
3945 intent.putExtra("title", title);
3946 intent.putExtra("url", url);
3947 intent.putExtra("favicon", favicon);
3948 intent.putExtra("touchIcon", touchIcon);
3949 startActivity(intent);
3950 }
3951
3952
The Android Open Source Project0c908882009-03-03 19:32:16 -08003953 // Called when loading from context menu or LOAD_URL message
Leon Scroggins92472e82010-02-17 16:32:28 -05003954 private void loadUrlFromContext(WebView view, String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003955 // In case the user enters nothing.
3956 if (url != null && url.length() != 0 && view != null) {
3957 url = smartUrlFilter(url);
Grace Kloba22ac16e2009-10-07 18:00:23 -07003958 if (!view.getWebViewClient().shouldOverrideUrlLoading(view, url)) {
Leon Scroggins92472e82010-02-17 16:32:28 -05003959 loadUrl(view, url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003960 }
3961 }
3962 }
3963
Leon Scroggins92472e82010-02-17 16:32:28 -05003964 /**
3965 * Load the URL into the given WebView and update the title bar
3966 * to reflect the new load. Call this instead of WebView.loadUrl
3967 * directly.
3968 * @param view The WebView used to load url.
3969 * @param url The URL to load.
3970 */
3971 private void loadUrl(WebView view, String url) {
3972 updateTitleBarForNewLoad(view, url);
3973 view.loadUrl(url);
3974 }
3975
3976 /**
3977 * Load UrlData into a Tab and update the title bar to reflect the new
3978 * load. Call this instead of UrlData.loadIn directly.
3979 * @param t The Tab used to load.
3980 * @param data The UrlData being loaded.
3981 */
3982 private void loadUrlDataIn(Tab t, UrlData data) {
3983 updateTitleBarForNewLoad(t.getWebView(), data.mUrl);
3984 data.loadIn(t);
3985 }
3986
3987 /**
3988 * If the WebView is the top window, update the title bar to reflect
3989 * loading the new URL. i.e. set its text, clear the favicon (which
3990 * will be set once the page begins loading), and set the progress to
3991 * INITIAL_PROGRESS to show that the page has begun to load. Called
3992 * by loadUrl and loadUrlDataIn.
3993 * @param view The WebView that is starting a load.
3994 * @param url The URL that is being loaded.
3995 */
3996 private void updateTitleBarForNewLoad(WebView view, String url) {
3997 if (view == getTopWindow()) {
3998 setUrlTitle(url, null);
3999 setFavicon(null);
4000 onProgressChanged(view, INITIAL_PROGRESS);
4001 }
4002 }
4003
The Android Open Source Project0c908882009-03-03 19:32:16 -08004004 private String smartUrlFilter(Uri inUri) {
4005 if (inUri != null) {
4006 return smartUrlFilter(inUri.toString());
4007 }
4008 return null;
4009 }
4010
Feng Qianb34f87a2009-03-24 21:27:26 -07004011 protected static final Pattern ACCEPTED_URI_SCHEMA = Pattern.compile(
The Android Open Source Project0c908882009-03-03 19:32:16 -08004012 "(?i)" + // switch on case insensitive matching
4013 "(" + // begin group for schema
4014 "(?:http|https|file):\\/\\/" +
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004015 "|(?:inline|data|about|content|javascript):" +
The Android Open Source Project0c908882009-03-03 19:32:16 -08004016 ")" +
4017 "(.*)" );
4018
4019 /**
4020 * Attempts to determine whether user input is a URL or search
4021 * terms. Anything with a space is passed to search.
4022 *
4023 * Converts to lowercase any mistakenly uppercased schema (i.e.,
4024 * "Http://" converts to "http://"
4025 *
4026 * @return Original or modified URL
4027 *
4028 */
4029 String smartUrlFilter(String url) {
4030
4031 String inUrl = url.trim();
4032 boolean hasSpace = inUrl.indexOf(' ') != -1;
4033
4034 Matcher matcher = ACCEPTED_URI_SCHEMA.matcher(inUrl);
4035 if (matcher.matches()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08004036 // force scheme to lowercase
4037 String scheme = matcher.group(1);
4038 String lcScheme = scheme.toLowerCase();
4039 if (!lcScheme.equals(scheme)) {
Mitsuru Oshima123ecfb2009-05-18 19:11:14 -07004040 inUrl = lcScheme + matcher.group(2);
4041 }
4042 if (hasSpace) {
4043 inUrl = inUrl.replace(" ", "%20");
The Android Open Source Project0c908882009-03-03 19:32:16 -08004044 }
4045 return inUrl;
4046 }
4047 if (hasSpace) {
Satish Sampath565505b2009-05-29 15:37:27 +01004048 // FIXME: Is this the correct place to add to searches?
4049 // what if someone else calls this function?
4050 int shortcut = parseUrlShortcut(inUrl);
4051 if (shortcut != SHORTCUT_INVALID) {
4052 Browser.addSearchUrl(mResolver, inUrl);
4053 String query = inUrl.substring(2);
4054 switch (shortcut) {
4055 case SHORTCUT_GOOGLE_SEARCH:
Grace Kloba47fdfdb2009-06-30 11:15:34 -07004056 return URLUtil.composeSearchUrl(query, QuickSearch_G, QUERY_PLACE_HOLDER);
Satish Sampath565505b2009-05-29 15:37:27 +01004057 case SHORTCUT_WIKIPEDIA_SEARCH:
4058 return URLUtil.composeSearchUrl(query, QuickSearch_W, QUERY_PLACE_HOLDER);
4059 case SHORTCUT_DICTIONARY_SEARCH:
4060 return URLUtil.composeSearchUrl(query, QuickSearch_D, QUERY_PLACE_HOLDER);
4061 case SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH:
The Android Open Source Project0c908882009-03-03 19:32:16 -08004062 // FIXME: we need location in this case
Satish Sampath565505b2009-05-29 15:37:27 +01004063 return URLUtil.composeSearchUrl(query, QuickSearch_L, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004064 }
4065 }
4066 } else {
Dan Egnor5ee906c2009-11-18 12:11:49 -08004067 if (Patterns.WEB_URL.matcher(inUrl).matches()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08004068 return URLUtil.guessUrl(inUrl);
4069 }
4070 }
4071
4072 Browser.addSearchUrl(mResolver, inUrl);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07004073 return URLUtil.composeSearchUrl(inUrl, QuickSearch_G, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004074 }
4075
Ben Murdochbff2d602009-07-01 20:19:05 +01004076 /* package */ void setShouldShowErrorConsole(boolean flag) {
4077 if (flag == mShouldShowErrorConsole) {
4078 // Nothing to do.
4079 return;
4080 }
4081
4082 mShouldShowErrorConsole = flag;
4083
Grace Kloba22ac16e2009-10-07 18:00:23 -07004084 ErrorConsoleView errorConsole = mTabControl.getCurrentTab()
4085 .getErrorConsole(true);
Ben Murdochbff2d602009-07-01 20:19:05 +01004086
4087 if (flag) {
4088 // Setting the show state of the console will cause it's the layout to be inflated.
4089 if (errorConsole.numberOfErrors() > 0) {
4090 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
4091 } else {
4092 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
4093 }
4094
4095 // Now we can add it to the main view.
4096 mErrorConsoleContainer.addView(errorConsole,
Romain Guy15b8ec62010-01-08 15:06:43 -08004097 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
Ben Murdochbff2d602009-07-01 20:19:05 +01004098 ViewGroup.LayoutParams.WRAP_CONTENT));
4099 } else {
4100 mErrorConsoleContainer.removeView(errorConsole);
4101 }
4102
4103 }
4104
Grace Kloba22ac16e2009-10-07 18:00:23 -07004105 boolean shouldShowErrorConsole() {
4106 return mShouldShowErrorConsole;
4107 }
4108
Andrei Popescu163ab742009-10-20 17:58:23 +01004109 private void setStatusBarVisibility(boolean visible) {
4110 int flag = visible ? 0 : WindowManager.LayoutParams.FLAG_FULLSCREEN;
4111 getWindow().setFlags(flag, WindowManager.LayoutParams.FLAG_FULLSCREEN);
4112 }
4113
Andrei Popescu56199cc2010-01-12 22:39:16 +00004114
4115 private void sendNetworkType(String type, String subtype) {
4116 WebView w = mTabControl.getCurrentWebView();
4117 if (w != null) {
4118 w.setNetworkType(type, subtype);
4119 }
4120 }
4121
Andrei Popescu30995e72010-02-09 16:59:58 +00004122 private void packageChanged(String packageName, boolean wasAdded) {
4123 WebView w = mTabControl.getCurrentWebView();
4124 if (w == null) {
4125 return;
4126 }
4127
4128 if (wasAdded) {
4129 w.addPackageName(packageName);
4130 } else {
4131 w.removePackageName(packageName);
4132 }
4133 }
4134
4135 private void addPackageNames(Set<String> packageNames) {
4136 WebView w = mTabControl.getCurrentWebView();
4137 if (w == null) {
4138 return;
4139 }
4140
4141 w.addPackageNames(packageNames);
4142 }
4143
4144 private void getInstalledPackages() {
4145 AsyncTask<Void, Void, Set<String> > task =
4146 new AsyncTask<Void, Void, Set<String> >() {
Michael Kolbe0a36662010-06-29 10:37:12 -07004147 @Override
Andrei Popescu30995e72010-02-09 16:59:58 +00004148 protected Set<String> doInBackground(Void... unused) {
4149 Set<String> installedPackages = new HashSet<String>();
4150 PackageManager pm = BrowserActivity.this.getPackageManager();
4151 if (pm != null) {
4152 List<PackageInfo> packages = pm.getInstalledPackages(0);
4153 for (PackageInfo p : packages) {
4154 if (BrowserActivity.this.sGoogleApps.contains(p.packageName)) {
4155 installedPackages.add(p.packageName);
4156 }
4157 }
4158 }
4159
4160 return installedPackages;
4161 }
4162
4163 // Executes on the UI thread
Michael Kolbe0a36662010-06-29 10:37:12 -07004164 @Override
Andrei Popescu30995e72010-02-09 16:59:58 +00004165 protected void onPostExecute(Set<String> installedPackages) {
4166 addPackageNames(installedPackages);
4167 }
4168 };
4169 task.execute();
4170 }
4171
Grace Klobaeb6eef42009-09-15 17:56:32 -07004172 final static int LOCK_ICON_UNSECURE = 0;
4173 final static int LOCK_ICON_SECURE = 1;
4174 final static int LOCK_ICON_MIXED = 2;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004175
The Android Open Source Project0c908882009-03-03 19:32:16 -08004176 private BrowserSettings mSettings;
4177 private TabControl mTabControl;
4178 private ContentResolver mResolver;
4179 private FrameLayout mContentView;
Andrei Popescuadc008d2009-06-26 14:11:30 +01004180 private View mCustomView;
4181 private FrameLayout mCustomViewContainer;
Andrei Popescuc9b55562009-07-07 10:51:15 +01004182 private WebChromeClient.CustomViewCallback mCustomViewCallback;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004183
4184 // FIXME, temp address onPrepareMenu performance problem. When we move everything out of
4185 // view, we should rewrite this.
4186 private int mCurrentMenuState = 0;
4187 private int mMenuState = R.id.MAIN_MENU;
Andrei Popescuadc008d2009-06-26 14:11:30 +01004188 private int mOldMenuState = EMPTY_MENU;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004189 private static final int EMPTY_MENU = -1;
4190 private Menu mMenu;
4191
The Android Open Source Project0c908882009-03-03 19:32:16 -08004192 // Used to prevent chording to result in firing two shortcuts immediately
4193 // one after another. Fixes bug 1211714.
4194 boolean mCanChord;
4195
4196 private boolean mInLoad;
4197 private boolean mIsNetworkUp;
Ben Murdochb7cc8b42009-09-28 10:59:09 +01004198 private boolean mDidStopLoad;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004199
Cary Clark1f10cbf2010-03-22 11:45:23 -04004200 /* package */ boolean mActivityInPause = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004201
4202 private boolean mMenuIsDown;
4203
The Android Open Source Project0c908882009-03-03 19:32:16 -08004204 private static boolean mInTrace;
4205
4206 // Performance probe
4207 private static final int[] SYSTEM_CPU_FORMAT = new int[] {
4208 Process.PROC_SPACE_TERM | Process.PROC_COMBINE,
4209 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 1: user time
4210 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 2: nice time
4211 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 3: sys time
4212 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 4: idle time
4213 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 5: iowait time
4214 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 6: irq time
4215 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG // 7: softirq time
4216 };
4217
4218 private long mStart;
4219 private long mProcessStart;
4220 private long mUserStart;
4221 private long mSystemStart;
4222 private long mIdleStart;
4223 private long mIrqStart;
4224
4225 private long mUiStart;
4226
4227 private Drawable mMixLockIcon;
4228 private Drawable mSecLockIcon;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004229
4230 /* hold a ref so we can auto-cancel if necessary */
4231 private AlertDialog mAlertDialog;
4232
The Android Open Source Project0c908882009-03-03 19:32:16 -08004233 // The up-to-date URL and title (these can be different from those stored
4234 // in WebView, since it takes some time for the information in WebView to
4235 // get updated)
4236 private String mUrl;
4237 private String mTitle;
4238
4239 // As PageInfo has different style for landscape / portrait, we have
4240 // to re-open it when configuration changed
4241 private AlertDialog mPageInfoDialog;
Grace Kloba22ac16e2009-10-07 18:00:23 -07004242 private Tab mPageInfoView;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004243 // If the Page-Info dialog is launched from the SSL-certificate-on-error
4244 // dialog, we should not just dismiss it, but should get back to the
4245 // SSL-certificate-on-error dialog. This flag is used to store this state
Leon Scrogginsc7b92f82010-01-11 18:17:31 -05004246 private boolean mPageInfoFromShowSSLCertificateOnError;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004247
4248 // as SSLCertificateOnError has different style for landscape / portrait,
4249 // we have to re-open it when configuration changed
4250 private AlertDialog mSSLCertificateOnErrorDialog;
4251 private WebView mSSLCertificateOnErrorView;
4252 private SslErrorHandler mSSLCertificateOnErrorHandler;
4253 private SslError mSSLCertificateOnErrorError;
4254
4255 // as SSLCertificate has different style for landscape / portrait, we
4256 // have to re-open it when configuration changed
4257 private AlertDialog mSSLCertificateDialog;
Grace Kloba22ac16e2009-10-07 18:00:23 -07004258 private Tab mSSLCertificateView;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004259
4260 // as HttpAuthentication has different style for landscape / portrait, we
4261 // have to re-open it when configuration changed
4262 private AlertDialog mHttpAuthenticationDialog;
4263 private HttpAuthHandler mHttpAuthHandler;
4264
4265 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_PARAMS =
4266 new FrameLayout.LayoutParams(
Romain Guy15b8ec62010-01-08 15:06:43 -08004267 ViewGroup.LayoutParams.MATCH_PARENT,
4268 ViewGroup.LayoutParams.MATCH_PARENT);
Andrei Popescuadc008d2009-06-26 14:11:30 +01004269 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_GRAVITY_CENTER =
4270 new FrameLayout.LayoutParams(
Romain Guy15b8ec62010-01-08 15:06:43 -08004271 ViewGroup.LayoutParams.MATCH_PARENT,
4272 ViewGroup.LayoutParams.MATCH_PARENT,
Andrei Popescuadc008d2009-06-26 14:11:30 +01004273 Gravity.CENTER);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07004274 // Google search
4275 final static String QuickSearch_G = "http://www.google.com/m?q=%s";
The Android Open Source Project0c908882009-03-03 19:32:16 -08004276 // Wikipedia search
4277 final static String QuickSearch_W = "http://en.wikipedia.org/w/index.php?search=%s&go=Go";
4278 // Dictionary search
4279 final static String QuickSearch_D = "http://dictionary.reference.com/search?q=%s";
4280 // Google Mobile Local search
4281 final static String QuickSearch_L = "http://www.google.com/m/search?site=local&q=%s&near=mountain+view";
4282
4283 final static String QUERY_PLACE_HOLDER = "%s";
4284
4285 // "source" parameter for Google search through search key
4286 final static String GOOGLE_SEARCH_SOURCE_SEARCHKEY = "browser-key";
4287 // "source" parameter for Google search through goto menu
4288 final static String GOOGLE_SEARCH_SOURCE_GOTO = "browser-goto";
4289 // "source" parameter for Google search through simplily type
4290 final static String GOOGLE_SEARCH_SOURCE_TYPE = "browser-type";
4291 // "source" parameter for Google search suggested by the browser
4292 final static String GOOGLE_SEARCH_SOURCE_SUGGEST = "browser-suggest";
4293 // "source" parameter for Google search from unknown source
4294 final static String GOOGLE_SEARCH_SOURCE_UNKNOWN = "unknown";
4295
4296 private final static String LOGTAG = "browser";
4297
The Android Open Source Project0c908882009-03-03 19:32:16 -08004298 private String mLastEnteredUrl;
4299
4300 private PowerManager.WakeLock mWakeLock;
4301 private final static int WAKELOCK_TIMEOUT = 5 * 60 * 1000; // 5 minutes
4302
4303 private Toast mStopToast;
4304
Leon Scroggins571b3762010-05-26 10:25:01 -04004305 private TitleBarBase mTitleBar;
Michael Kolba2b2ba82010-08-04 17:54:03 -07004306 private TabBar mTabBar;
Leon Scroggins81db3662009-06-04 17:45:11 -04004307
Ben Murdochbff2d602009-07-01 20:19:05 +01004308 private LinearLayout mErrorConsoleContainer = null;
4309 private boolean mShouldShowErrorConsole = false;
4310
The Android Open Source Project0c908882009-03-03 19:32:16 -08004311 // As the ids are dynamically created, we can't guarantee that they will
4312 // be in sequence, so this static array maps ids to a window number.
4313 final static private int[] WINDOW_SHORTCUT_ID_ARRAY =
4314 { R.id.window_one_menu_id, R.id.window_two_menu_id, R.id.window_three_menu_id,
4315 R.id.window_four_menu_id, R.id.window_five_menu_id, R.id.window_six_menu_id,
4316 R.id.window_seven_menu_id, R.id.window_eight_menu_id };
4317
4318 // monitor platform changes
4319 private IntentFilter mNetworkStateChangedFilter;
4320 private BroadcastReceiver mNetworkStateIntentReceiver;
4321
Grace Klobab4da0ad2009-05-14 14:45:40 -07004322 private BroadcastReceiver mPackageInstallationReceiver;
4323
Bjorn Bringerta7611812010-03-24 11:12:02 +00004324 private SystemAllowGeolocationOrigins mSystemAllowGeolocationOrigins;
4325
The Android Open Source Project0c908882009-03-03 19:32:16 -08004326 // activity requestCode
Nicolas Roard78a98e42009-05-11 13:34:17 +01004327 final static int COMBO_PAGE = 1;
4328 final static int DOWNLOAD_PAGE = 2;
4329 final static int PREFERENCES_PAGE = 3;
Leon Scroggins8d5fa432009-10-02 15:55:59 -04004330 final static int FILE_SELECTED = 4;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004331
Andrei Popescu540035d2009-09-18 18:59:20 +01004332 // the default <video> poster
4333 private Bitmap mDefaultVideoPoster;
4334 // the video progress view
4335 private View mVideoProgressView;
4336
Andrei Popescu30995e72010-02-09 16:59:58 +00004337 // The Google packages we monitor for the navigator.isApplicationInstalled()
4338 // API. Add as needed.
4339 private static Set<String> sGoogleApps;
4340 static {
4341 sGoogleApps = new HashSet<String>();
4342 sGoogleApps.add("com.google.android.youtube");
4343 }
4344
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004345 /**
4346 * A UrlData class to abstract how the content will be set to WebView.
4347 * This base class uses loadUrl to show the content.
4348 */
Leon Scroggins6eac63e2010-03-15 18:19:14 -04004349 /* package */ static class UrlData {
Grace Kloba068e48b2010-01-26 18:11:27 -08004350 final String mUrl;
4351 final Map<String, String> mHeaders;
Leon Scroggins58d56c62010-01-28 15:12:40 -05004352 final Intent mVoiceIntent;
Grace Kloba60e095c2009-06-16 11:50:55 -07004353
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004354 UrlData(String url) {
4355 this.mUrl = url;
Grace Kloba068e48b2010-01-26 18:11:27 -08004356 this.mHeaders = null;
Leon Scroggins58d56c62010-01-28 15:12:40 -05004357 this.mVoiceIntent = null;
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004358 }
Grace Kloba60e095c2009-06-16 11:50:55 -07004359
Leon Scroggins58d56c62010-01-28 15:12:40 -05004360 UrlData(String url, Map<String, String> headers, Intent intent) {
Grace Kloba068e48b2010-01-26 18:11:27 -08004361 this.mUrl = url;
4362 this.mHeaders = headers;
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -05004363 if (RecognizerResultsIntent.ACTION_VOICE_SEARCH_RESULTS
4364 .equals(intent.getAction())) {
Leon Scroggins58d56c62010-01-28 15:12:40 -05004365 this.mVoiceIntent = intent;
4366 } else {
4367 this.mVoiceIntent = null;
4368 }
Grace Kloba60e095c2009-06-16 11:50:55 -07004369 }
4370
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004371 boolean isEmpty() {
Leon Scroggins58d56c62010-01-28 15:12:40 -05004372 return mVoiceIntent == null && (mUrl == null || mUrl.length() == 0);
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004373 }
4374
Leon Scroggins92472e82010-02-17 16:32:28 -05004375 /**
4376 * Load this UrlData into the given Tab. Use loadUrlDataIn to update
4377 * the title bar as well.
4378 */
Leon Scroggins58d56c62010-01-28 15:12:40 -05004379 public void loadIn(Tab t) {
4380 if (mVoiceIntent != null) {
4381 t.activateVoiceSearchMode(mVoiceIntent);
4382 } else {
4383 t.getWebView().loadUrl(mUrl, mHeaders);
4384 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004385 }
4386 };
4387
Leon Scroggins1f005d32009-08-10 17:36:42 -04004388 /* package */ static final UrlData EMPTY_URL_DATA = new UrlData(null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004389}