blob: 54fb96f5d3e04e9d5a67a31b45323017ff05240d [file] [log] [blame]
The Android Open Source Project0c908882009-03-03 19:32:16 -08001/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.browser;
18
Michael Kolbed217742010-08-10 17:52:34 -070019import android.app.ActionBar;
The Android Open Source Project0c908882009-03-03 19:32:16 -080020import android.app.Activity;
The Android Open Source Project0c908882009-03-03 19:32:16 -080021import android.app.AlertDialog;
22import android.app.ProgressDialog;
23import android.app.SearchManager;
24import android.content.ActivityNotFoundException;
25import android.content.BroadcastReceiver;
Dianne Hackborn80f32622010-08-05 14:17:53 -070026import android.content.ClipboardManager;
The Android Open Source Project0c908882009-03-03 19:32:16 -080027import android.content.ComponentName;
Leon Scroggins58d56c62010-01-28 15:12:40 -050028import android.content.ContentProvider;
29import android.content.ContentProviderClient;
The Android Open Source Project0c908882009-03-03 19:32:16 -080030import android.content.ContentResolver;
Leon Scrogginsb6b7f9e2009-06-18 12:05:28 -040031import android.content.ContentUris;
The Android Open Source Project0c908882009-03-03 19:32:16 -080032import android.content.ContentValues;
33import android.content.Context;
34import android.content.DialogInterface;
35import android.content.Intent;
36import android.content.IntentFilter;
Grace Klobab4da0ad2009-05-14 14:45:40 -070037import android.content.pm.PackageInfo;
The Android Open Source Project0c908882009-03-03 19:32:16 -080038import android.content.pm.PackageManager;
39import android.content.pm.ResolveInfo;
The Android Open Source Project0c908882009-03-03 19:32:16 -080040import android.content.res.Configuration;
41import android.content.res.Resources;
42import android.database.Cursor;
The Android Open Source Project0c908882009-03-03 19:32:16 -080043import android.graphics.Bitmap;
Andrei Popescu540035d2009-09-18 18:59:20 +010044import android.graphics.BitmapFactory;
The Android Open Source Project0c908882009-03-03 19:32:16 -080045import android.graphics.Canvas;
The Android Open Source Project0c908882009-03-03 19:32:16 -080046import android.graphics.Picture;
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -040047import android.graphics.PixelFormat;
The Android Open Source Project0c908882009-03-03 19:32:16 -080048import android.graphics.drawable.Drawable;
The Android Open Source Project0c908882009-03-03 19:32:16 -080049import android.net.ConnectivityManager;
Andrei Popescu56199cc2010-01-12 22:39:16 +000050import android.net.NetworkInfo;
The Android Open Source Project0c908882009-03-03 19:32:16 -080051import android.net.Uri;
52import android.net.WebAddress;
The Android Open Source Project0c908882009-03-03 19:32:16 -080053import android.net.http.SslCertificate;
54import android.net.http.SslError;
55import android.os.AsyncTask;
56import android.os.Bundle;
57import android.os.Debug;
58import android.os.Environment;
59import android.os.Handler;
The Android Open Source Project0c908882009-03-03 19:32:16 -080060import android.os.Message;
61import android.os.PowerManager;
62import android.os.Process;
The Android Open Source Project0c908882009-03-03 19:32:16 -080063import android.os.SystemClock;
The Android Open Source Project0c908882009-03-03 19:32:16 -080064import android.provider.Browser;
Jeff Hamilton8ce956c2010-08-17 11:13:53 -050065import android.provider.BrowserContract;
Cary Clark5e335a32009-09-22 14:53:11 -040066import android.provider.ContactsContract;
Michael Kolba2b2ba82010-08-04 17:54:03 -070067import android.provider.ContactsContract.Intents.Insert;
The Android Open Source Project0c908882009-03-03 19:32:16 -080068import android.provider.Downloads;
69import android.provider.MediaStore;
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -050070import android.speech.RecognizerResultsIntent;
The Android Open Source Project0c908882009-03-03 19:32:16 -080071import android.text.TextUtils;
72import android.text.format.DateFormat;
The Android Open Source Project0c908882009-03-03 19:32:16 -080073import android.util.Log;
Dianne Hackborn385effd2010-02-24 20:03:04 -080074import android.util.Patterns;
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -040075import android.view.ActionMode;
The Android Open Source Project0c908882009-03-03 19:32:16 -080076import android.view.ContextMenu;
Michael Kolba2b2ba82010-08-04 17:54:03 -070077import android.view.ContextMenu.ContextMenuInfo;
The Android Open Source Project0c908882009-03-03 19:32:16 -080078import android.view.Gravity;
79import android.view.KeyEvent;
80import android.view.LayoutInflater;
81import android.view.Menu;
82import android.view.MenuInflater;
83import android.view.MenuItem;
Michael Kolba2b2ba82010-08-04 17:54:03 -070084import android.view.MenuItem.OnMenuItemClickListener;
The Android Open Source Project0c908882009-03-03 19:32:16 -080085import android.view.View;
86import android.view.ViewGroup;
87import android.view.Window;
88import android.view.WindowManager;
Svetoslav Ganov2b345992010-05-06 06:13:54 -070089import android.view.accessibility.AccessibilityManager;
The Android Open Source Project0c908882009-03-03 19:32:16 -080090import android.webkit.CookieManager;
91import android.webkit.CookieSyncManager;
92import android.webkit.DownloadListener;
93import android.webkit.HttpAuthHandler;
Grace Klobab4da0ad2009-05-14 14:45:40 -070094import android.webkit.PluginManager;
The Android Open Source Project0c908882009-03-03 19:32:16 -080095import android.webkit.SslErrorHandler;
96import android.webkit.URLUtil;
Leon Clarkecb6cc862009-09-29 18:35:13 +010097import android.webkit.ValueCallback;
The Android Open Source Project0c908882009-03-03 19:32:16 -080098import android.webkit.WebChromeClient;
99import android.webkit.WebHistoryItem;
100import android.webkit.WebIconDatabase;
101import android.webkit.WebView;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800102import android.widget.EditText;
103import android.widget.FrameLayout;
104import android.widget.LinearLayout;
105import android.widget.TextView;
106import android.widget.Toast;
107
Michael Kolba2b2ba82010-08-04 17:54:03 -0700108import com.android.browser.ScrollWebView.ScrollListener;
Bjorn Bringert10d1cca2010-02-10 14:22:12 +0000109import com.android.common.Search;
Leon Scroggins1fe13a52010-02-09 15:31:26 -0500110import com.android.common.speech.LoggingEvents;
Dan Egnor5ee906c2009-11-18 12:11:49 -0800111
Leon Scrogginsb6b7f9e2009-06-18 12:05:28 -0400112import java.io.ByteArrayOutputStream;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800113import java.io.File;
Ben Murdoch4f75ba22009-10-27 11:48:28 +0000114import java.io.IOException;
115import java.io.InputStream;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800116import java.net.MalformedURLException;
Dianne Hackborn99189432009-06-17 18:06:18 -0700117import java.net.URISyntaxException;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800118import java.net.URL;
119import java.net.URLEncoder;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800120import java.util.Date;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800121import java.util.HashMap;
Andrei Popescu30995e72010-02-09 16:59:58 +0000122import java.util.HashSet;
Grace Kloba00f54c52010-01-27 14:53:51 -0800123import java.util.Iterator;
Andrei Popescu30995e72010-02-09 16:59:58 +0000124import java.util.List;
Grace Kloba068e48b2010-01-26 18:11:27 -0800125import java.util.Map;
Andrei Popescu30995e72010-02-09 16:59:58 +0000126import java.util.Set;
Michael Kolbfe251992010-07-08 15:41:55 -0700127import java.util.Vector;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800128import java.util.regex.Matcher;
129import java.util.regex.Pattern;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800130
131public class BrowserActivity extends Activity
Shimeng (Simon) Wang98d5fce2010-03-16 13:23:39 -0700132 implements View.OnCreateContextMenuListener, DownloadListener {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800133
Dave Bort31a6d1c2009-04-13 15:56:49 -0700134 /* Define some aliases to make these debugging flags easier to refer to.
135 * This file imports android.provider.Browser, so we can't just refer to "Browser.DEBUG".
136 */
137 private final static boolean DEBUG = com.android.browser.Browser.DEBUG;
138 private final static boolean LOGV_ENABLED = com.android.browser.Browser.LOGV_ENABLED;
139 private final static boolean LOGD_ENABLED = com.android.browser.Browser.LOGD_ENABLED;
140
Satish Sampath565505b2009-05-29 15:37:27 +0100141 // These are single-character shortcuts for searching popular sources.
142 private static final int SHORTCUT_INVALID = 0;
143 private static final int SHORTCUT_GOOGLE_SEARCH = 1;
144 private static final int SHORTCUT_WIKIPEDIA_SEARCH = 2;
145 private static final int SHORTCUT_DICTIONARY_SEARCH = 3;
146 private static final int SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH = 4;
147
Cary Clarka9771242009-08-11 16:42:26 -0400148 private static class ClearThumbnails extends AsyncTask<File, Void, Void> {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800149 @Override
150 public Void doInBackground(File... files) {
151 if (files != null) {
152 for (File f : files) {
Cary Clarkd6be1752009-08-12 12:56:42 -0400153 if (!f.delete()) {
154 Log.e(LOGTAG, f.getPath() + " was not deleted");
155 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800156 }
157 }
158 return null;
159 }
160 }
161
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400162 /**
163 * This layout holds everything you see below the status bar, including the
164 * error console, the custom view container, and the webviews.
165 */
166 private FrameLayout mBrowserFrameLayout;
Leon Scroggins81db3662009-06-04 17:45:11 -0400167
Leon Scrogginsd746a942010-05-19 13:21:44 -0400168 private boolean mXLargeScreenSize;
169
Grace Kloba22ac16e2009-10-07 18:00:23 -0700170 @Override
171 public void onCreate(Bundle icicle) {
Dave Bort31a6d1c2009-04-13 15:56:49 -0700172 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800173 Log.v(LOGTAG, this + " onStart");
174 }
175 super.onCreate(icicle);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800176 // test the browser in OpenGL
177 // requestWindowFeature(Window.FEATURE_OPENGL);
178
Mike Reedd334bf52010-01-26 15:21:44 -0500179 // enable this to test the browser in 32bit
180 if (false) {
181 getWindow().setFormat(PixelFormat.RGBX_8888);
182 BitmapFactory.setDefaultConfig(Bitmap.Config.ARGB_8888);
183 }
184
Svetoslav Ganov2b345992010-05-06 06:13:54 -0700185 if (AccessibilityManager.getInstance(this).isEnabled()) {
186 setDefaultKeyMode(DEFAULT_KEYS_DISABLE);
187 } else {
188 setDefaultKeyMode(DEFAULT_KEYS_SEARCH_LOCAL);
189 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800190
191 mResolver = getContentResolver();
192
Grace Kloba0923d692009-09-23 21:37:25 -0700193 // If this was a web search request, pass it on to the default web
194 // search provider and finish this activity.
195 if (handleWebSearchIntent(getIntent())) {
196 finish();
197 return;
198 }
199
The Android Open Source Project0c908882009-03-03 19:32:16 -0800200 mSecLockIcon = Resources.getSystem().getDrawable(
201 android.R.drawable.ic_secure);
202 mMixLockIcon = Resources.getSystem().getDrawable(
203 android.R.drawable.ic_partial_secure);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800204
Michael Kolbed217742010-08-10 17:52:34 -0700205 // Create the tab control and our initial tab
206 mTabControl = new TabControl(this);
207
208 mXLargeScreenSize = (getResources().getConfiguration().screenLayout
209 & Configuration.SCREENLAYOUT_SIZE_MASK)
210 == Configuration.SCREENLAYOUT_SIZE_XLARGE;
211
Leon Scroggins81db3662009-06-04 17:45:11 -0400212 FrameLayout frameLayout = (FrameLayout) getWindow().getDecorView()
213 .findViewById(com.android.internal.R.id.content);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400214 mBrowserFrameLayout = (FrameLayout) LayoutInflater.from(this)
215 .inflate(R.layout.custom_screen, null);
216 mContentView = (FrameLayout) mBrowserFrameLayout.findViewById(
217 R.id.main_content);
218 mErrorConsoleContainer = (LinearLayout) mBrowserFrameLayout
219 .findViewById(R.id.error_console);
220 mCustomViewContainer = (FrameLayout) mBrowserFrameLayout
221 .findViewById(R.id.fullscreen_custom_content);
222 frameLayout.addView(mBrowserFrameLayout, COVER_SCREEN_PARAMS);
Michael Kolbe0a36662010-06-29 10:37:12 -0700223
Leon Scrogginsd746a942010-05-19 13:21:44 -0400224 if (mXLargeScreenSize) {
Michael Kolba2b2ba82010-08-04 17:54:03 -0700225 mTitleBar = new TitleBarXLarge(this);
226 mTitleBar.setProgress(100);
227 mFakeTitleBar = new TitleBarXLarge(this);
Michael Kolbed217742010-08-10 17:52:34 -0700228 ActionBar actionBar = getActionBar();
Michael Kolba2b2ba82010-08-04 17:54:03 -0700229 mTabBar = new TabBar(this, mTabControl, (TitleBarXLarge) mFakeTitleBar);
Michael Kolbed217742010-08-10 17:52:34 -0700230 actionBar.setCustomNavigationMode(mTabBar);
Leon Scrogginsd746a942010-05-19 13:21:44 -0400231 } else {
Leon Scroggins571b3762010-05-26 10:25:01 -0400232 mTitleBar = new TitleBar(this);
Leon Scrogginsd746a942010-05-19 13:21:44 -0400233 // mTitleBar will be always be shown in the fully loaded mode on
234 // phone
235 mTitleBar.setProgress(100);
Leon Scrogginsd746a942010-05-19 13:21:44 -0400236 mFakeTitleBar = new TitleBar(this);
237 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800238
The Android Open Source Project0c908882009-03-03 19:32:16 -0800239 // Open the icon database and retain all the bookmark urls for favicons
240 retainIconsOnStartup();
241
242 // Keep a settings instance handy.
243 mSettings = BrowserSettings.getInstance();
244 mSettings.setTabControl(mTabControl);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800245
246 PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
247 mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Browser");
248
Patrick Scott6adacc92010-03-05 08:24:51 -0500249 // Find out if the network is currently up.
250 ConnectivityManager cm = (ConnectivityManager) getSystemService(
251 Context.CONNECTIVITY_SERVICE);
252 NetworkInfo info = cm.getActiveNetworkInfo();
253 if (info != null) {
254 mIsNetworkUp = info.isAvailable();
255 }
256
Grace Klobaa34f6862009-07-31 16:28:17 -0700257 /* enables registration for changes in network status from
258 http stack */
259 mNetworkStateChangedFilter = new IntentFilter();
260 mNetworkStateChangedFilter.addAction(
261 ConnectivityManager.CONNECTIVITY_ACTION);
262 mNetworkStateIntentReceiver = new BroadcastReceiver() {
263 @Override
264 public void onReceive(Context context, Intent intent) {
265 if (intent.getAction().equals(
266 ConnectivityManager.CONNECTIVITY_ACTION)) {
Andrei Popescue4c98462010-02-19 15:44:13 +0000267
268 NetworkInfo info = intent.getParcelableExtra(
269 ConnectivityManager.EXTRA_NETWORK_INFO);
270 String typeName = info.getTypeName();
271 String subtypeName = info.getSubtypeName();
272 sendNetworkType(typeName.toLowerCase(),
273 (subtypeName != null ? subtypeName.toLowerCase() : ""));
274
275 onNetworkToggle(info.isAvailable());
Grace Klobaa34f6862009-07-31 16:28:17 -0700276 }
277 }
278 };
279
Grace Kloba615c6c92009-08-03 10:22:44 -0700280 IntentFilter filter = new IntentFilter(Intent.ACTION_PACKAGE_ADDED);
281 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
282 filter.addDataScheme("package");
283 mPackageInstallationReceiver = new BroadcastReceiver() {
284 @Override
285 public void onReceive(Context context, Intent intent) {
286 final String action = intent.getAction();
287 final String packageName = intent.getData()
288 .getSchemeSpecificPart();
289 final boolean replacing = intent.getBooleanExtra(
290 Intent.EXTRA_REPLACING, false);
291 if (Intent.ACTION_PACKAGE_REMOVED.equals(action) && replacing) {
292 // if it is replacing, refreshPlugins() when adding
293 return;
294 }
Andrei Popescu30995e72010-02-09 16:59:58 +0000295
296 if (sGoogleApps.contains(packageName)) {
297 BrowserActivity.this.packageChanged(packageName,
298 Intent.ACTION_PACKAGE_ADDED.equals(action));
299 }
300
Grace Kloba615c6c92009-08-03 10:22:44 -0700301 PackageManager pm = BrowserActivity.this.getPackageManager();
302 PackageInfo pkgInfo = null;
303 try {
304 pkgInfo = pm.getPackageInfo(packageName,
305 PackageManager.GET_PERMISSIONS);
306 } catch (PackageManager.NameNotFoundException e) {
307 return;
308 }
309 if (pkgInfo != null) {
310 String permissions[] = pkgInfo.requestedPermissions;
311 if (permissions == null) {
312 return;
313 }
314 boolean permissionOk = false;
315 for (String permit : permissions) {
316 if (PluginManager.PLUGIN_PERMISSION.equals(permit)) {
317 permissionOk = true;
318 break;
319 }
320 }
321 if (permissionOk) {
322 PluginManager.getInstance(BrowserActivity.this)
Grace Klobae56a0f22010-05-26 17:31:02 -0700323 .refreshPlugins(true);
Grace Kloba615c6c92009-08-03 10:22:44 -0700324 }
325 }
326 }
327 };
328 registerReceiver(mPackageInstallationReceiver, filter);
329
The Android Open Source Project0c908882009-03-03 19:32:16 -0800330 if (!mTabControl.restoreState(icicle)) {
331 // clear up the thumbnail directory if we can't restore the state as
332 // none of the files in the directory are referenced any more.
333 new ClearThumbnails().execute(
334 mTabControl.getThumbnailDir().listFiles());
Grace Klobaaab3f092009-07-30 12:29:51 -0700335 // there is no quit on Android. But if we can't restore the state,
336 // we can treat it as a new Browser, remove the old session cookies.
337 CookieManager.getInstance().removeSessionCookie();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800338 final Intent intent = getIntent();
339 final Bundle extra = intent.getExtras();
340 // Create an initial tab.
341 // If the intent is ACTION_VIEW and data is not null, the Browser is
342 // invoked to view the content by another application. In this case,
343 // the tab will be close when exit.
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700344 UrlData urlData = getUrlDataFromIntent(intent);
345
Leon Scroggins58d56c62010-01-28 15:12:40 -0500346 String action = intent.getAction();
Grace Kloba22ac16e2009-10-07 18:00:23 -0700347 final Tab t = mTabControl.createNewTab(
Leon Scroggins58d56c62010-01-28 15:12:40 -0500348 (Intent.ACTION_VIEW.equals(action) &&
349 intent.getData() != null)
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -0500350 || RecognizerResultsIntent.ACTION_VOICE_SEARCH_RESULTS
351 .equals(action),
Elliott Slaughterf0f03952010-07-14 18:10:36 -0700352 intent.getStringExtra(Browser.EXTRA_APPLICATION_ID),
353 urlData.mUrl, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800354 mTabControl.setCurrentTab(t);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800355 attachTabToContentView(t);
356 WebView webView = t.getWebView();
357 if (extra != null) {
358 int scale = extra.getInt(Browser.INITIAL_ZOOM_LEVEL, 0);
359 if (scale > 0 && scale <= 1000) {
360 webView.setInitialScale(scale);
361 }
362 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800363
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700364 if (urlData.isEmpty()) {
Shimeng (Simon) Wang98d5fce2010-03-16 13:23:39 -0700365 loadUrl(webView, mSettings.getHomePage());
The Android Open Source Project0c908882009-03-03 19:32:16 -0800366 } else {
Patrick Scott9d53da02010-02-19 10:19:01 -0500367 loadUrlDataIn(t, urlData);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800368 }
369 } else {
370 // TabControl.restoreState() will create a new tab even if
Leon Scroggins1f005d32009-08-10 17:36:42 -0400371 // restoring the state fails.
The Android Open Source Project0c908882009-03-03 19:32:16 -0800372 attachTabToContentView(mTabControl.getCurrentTab());
373 }
Grace Kloba615c6c92009-08-03 10:22:44 -0700374
Cary Clarkb4b83182010-07-01 12:36:56 -0400375 // Delete old thumbnails to save space
376 File dir = mTabControl.getThumbnailDir();
377 if (dir.exists()) {
378 for (String child : dir.list()) {
379 File f = new File(dir, child);
380 f.delete();
381 }
382 }
383
Feng Qianb3c02da2009-06-29 15:58:08 -0700384 // Read JavaScript flags if it exists.
385 String jsFlags = mSettings.getJsFlags();
386 if (jsFlags.trim().length() != 0) {
387 mTabControl.getCurrentWebView().setJsFlags(jsFlags);
388 }
Andrei Popescu30995e72010-02-09 16:59:58 +0000389 // Work out which packages are installed on the system.
390 getInstalledPackages();
Bjorn Bringerta7611812010-03-24 11:12:02 +0000391
392 // Start watching the default geolocation permissions
393 mSystemAllowGeolocationOrigins
394 = new SystemAllowGeolocationOrigins(getApplicationContext());
395 mSystemAllowGeolocationOrigins.start();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800396 }
397
Michael Kolba2b2ba82010-08-04 17:54:03 -0700398 ScrollListener getScrollListener() {
399 return mTabBar;
400 }
401
Leon Scroggins58d56c62010-01-28 15:12:40 -0500402 /**
403 * Feed the previously stored results strings to the BrowserProvider so that
404 * the SearchDialog will show them instead of the standard searches.
405 * @param result String to show on the editable line of the SearchDialog.
406 */
407 /* package */ void showVoiceSearchResults(String result) {
408 ContentProviderClient client = mResolver.acquireContentProviderClient(
409 Browser.BOOKMARKS_URI);
410 ContentProvider prov = client.getLocalContentProvider();
411 BrowserProvider bp = (BrowserProvider) prov;
412 bp.setQueryResults(mTabControl.getCurrentTab().getVoiceSearchResults());
413 client.release();
414
Leon Scrogginsfbb3f152010-03-09 17:26:56 -0500415 Bundle bundle = createGoogleSearchSourceBundle(
416 GOOGLE_SEARCH_SOURCE_SEARCHKEY);
417 bundle.putBoolean(SearchManager.CONTEXT_IS_VOICE, true);
418 startSearch(result, false, bundle, false);
Leon Scroggins58d56c62010-01-28 15:12:40 -0500419 }
420
The Android Open Source Project0c908882009-03-03 19:32:16 -0800421 @Override
422 protected void onNewIntent(Intent intent) {
Grace Kloba22ac16e2009-10-07 18:00:23 -0700423 Tab current = mTabControl.getCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800424 // When a tab is closed on exit, the current tab index is set to -1.
425 // Reset before proceed as Browser requires the current tab to be set.
426 if (current == null) {
427 // Try to reset the tab in case the index was incorrect.
428 current = mTabControl.getTab(0);
429 if (current == null) {
430 // No tabs at all so just ignore this intent.
431 return;
432 }
433 mTabControl.setCurrentTab(current);
434 attachTabToContentView(current);
435 resetTitleAndIcon(current.getWebView());
436 }
437 final String action = intent.getAction();
438 final int flags = intent.getFlags();
439 if (Intent.ACTION_MAIN.equals(action) ||
440 (flags & Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY) != 0) {
441 // just resume the browser
442 return;
443 }
Leon Scrogginsb8a844d2010-03-18 15:06:15 -0400444 // In case the SearchDialog is open.
445 ((SearchManager) getSystemService(Context.SEARCH_SERVICE))
446 .stopSearch();
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -0500447 boolean activateVoiceSearch = RecognizerResultsIntent
448 .ACTION_VOICE_SEARCH_RESULTS.equals(action);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800449 if (Intent.ACTION_VIEW.equals(action)
450 || Intent.ACTION_SEARCH.equals(action)
451 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
Leon Scroggins58d56c62010-01-28 15:12:40 -0500452 || Intent.ACTION_WEB_SEARCH.equals(action)
453 || activateVoiceSearch) {
Leon Scroggins3b18ce32010-02-08 17:35:59 -0500454 if (current.isInVoiceSearchMode()) {
455 String title = current.getVoiceDisplayTitle();
456 if (title != null && title.equals(intent.getStringExtra(
457 SearchManager.QUERY))) {
458 // The user submitted the same search as the last voice
459 // search, so do nothing.
460 return;
461 }
Leon Scroggins1fe13a52010-02-09 15:31:26 -0500462 if (Intent.ACTION_SEARCH.equals(action)
463 && current.voiceSearchSourceIsGoogle()) {
464 Intent logIntent = new Intent(
465 LoggingEvents.ACTION_LOG_EVENT);
466 logIntent.putExtra(LoggingEvents.EXTRA_EVENT,
467 LoggingEvents.VoiceSearch.QUERY_UPDATED);
468 logIntent.putExtra(
469 LoggingEvents.VoiceSearch.EXTRA_QUERY_UPDATED_VALUE,
470 intent.getDataString());
471 sendBroadcast(logIntent);
472 // Note, onPageStarted will revert the voice title bar
473 // When http://b/issue?id=2379215 is fixed, we should update
474 // the title bar here.
475 }
Leon Scroggins3b18ce32010-02-08 17:35:59 -0500476 }
Satish Sampath565505b2009-05-29 15:37:27 +0100477 // If this was a search request (e.g. search query directly typed into the address bar),
478 // pass it on to the default web search provider.
479 if (handleWebSearchIntent(intent)) {
480 return;
481 }
482
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700483 UrlData urlData = getUrlDataFromIntent(intent);
484 if (urlData.isEmpty()) {
485 urlData = new UrlData(mSettings.getHomePage());
The Android Open Source Project0c908882009-03-03 19:32:16 -0800486 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700487
Grace Klobacc634032009-07-28 15:58:19 -0700488 final String appId = intent
489 .getStringExtra(Browser.EXTRA_APPLICATION_ID);
Leon Scroggins47208682010-04-07 17:59:48 -0400490 if ((Intent.ACTION_VIEW.equals(action)
491 // If a voice search has no appId, it means that it came
492 // from the browser. In that case, reuse the current tab.
493 || (activateVoiceSearch && appId != null))
Grace Klobacc634032009-07-28 15:58:19 -0700494 && !getPackageName().equals(appId)
495 && (flags & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0) {
Grace Kloba22ac16e2009-10-07 18:00:23 -0700496 Tab appTab = mTabControl.getTabFromId(appId);
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700497 if (appTab != null) {
498 Log.i(LOGTAG, "Reusing tab for " + appId);
499 // Dismiss the subwindow if applicable.
500 dismissSubWindow(appTab);
501 // Since we might kill the WebView, remove it from the
502 // content view first.
503 removeTabFromContentView(appTab);
504 // Recreate the main WebView after destroying the old one.
505 // If the WebView has the same original url and is on that
506 // page, it can be reused.
507 boolean needsLoad =
Leon Scroggins6eac63e2010-03-15 18:19:14 -0400508 mTabControl.recreateWebView(appTab, urlData);
Ben Murdochbff2d602009-07-01 20:19:05 +0100509
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700510 if (current != appTab) {
Leon Scroggins1f005d32009-08-10 17:36:42 -0400511 switchToTab(mTabControl.getTabIndex(appTab));
512 if (needsLoad) {
Patrick Scott9d53da02010-02-19 10:19:01 -0500513 loadUrlDataIn(appTab, urlData);
Leon Scroggins1f005d32009-08-10 17:36:42 -0400514 }
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700515 } else {
Leon Scroggins1f005d32009-08-10 17:36:42 -0400516 // If the tab was the current tab, we have to attach
517 // it to the view system again.
518 attachTabToContentView(appTab);
519 if (needsLoad) {
Patrick Scott9d53da02010-02-19 10:19:01 -0500520 loadUrlDataIn(appTab, urlData);
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700521 }
522 }
523 return;
Patrick Scottcd115892009-07-16 09:42:58 -0400524 } else {
525 // No matching application tab, try to find a regular tab
526 // with a matching url.
527 appTab = mTabControl.findUnusedTabWithUrl(urlData.mUrl);
Leon Scroggins25515f82009-08-19 15:31:58 -0400528 if (appTab != null) {
529 if (current != appTab) {
530 switchToTab(mTabControl.getTabIndex(appTab));
531 }
532 // Otherwise, we are already viewing the correct tab.
Patrick Scottcd115892009-07-16 09:42:58 -0400533 } else {
534 // if FLAG_ACTIVITY_BROUGHT_TO_FRONT flag is on, the url
535 // will be opened in a new tab unless we have reached
536 // MAX_TABS. Then the url will be opened in the current
537 // tab. If a new tab is created, it will have "true" for
538 // exit on close.
Leon Scroggins1f005d32009-08-10 17:36:42 -0400539 openTabAndShow(urlData, true, appId);
Patrick Scottcd115892009-07-16 09:42:58 -0400540 }
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700541 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800542 } else {
Grace Kloba638d3f42009-11-23 10:35:04 -0800543 if (!urlData.isEmpty()
544 && urlData.mUrl.startsWith("about:debug")) {
545 if ("about:debug.dom".equals(urlData.mUrl)) {
546 current.getWebView().dumpDomTree(false);
547 } else if ("about:debug.dom.file".equals(urlData.mUrl)) {
548 current.getWebView().dumpDomTree(true);
549 } else if ("about:debug.render".equals(urlData.mUrl)) {
550 current.getWebView().dumpRenderTree(false);
551 } else if ("about:debug.render.file".equals(urlData.mUrl)) {
552 current.getWebView().dumpRenderTree(true);
553 } else if ("about:debug.display".equals(urlData.mUrl)) {
554 current.getWebView().dumpDisplayTree();
Mike Reed9b78e1d2010-01-13 14:40:52 -0800555 } else if (urlData.mUrl.startsWith("about:debug.drag")) {
556 int index = urlData.mUrl.codePointAt(16) - '0';
557 if (index <= 0 || index > 9) {
558 current.getWebView().setDragTracker(null);
559 } else {
560 current.getWebView().setDragTracker(new MeshTracker(index));
561 }
Grace Kloba638d3f42009-11-23 10:35:04 -0800562 } else {
563 mSettings.toggleDebugSettings();
564 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800565 return;
566 }
Leon Scroggins1f005d32009-08-10 17:36:42 -0400567 // Get rid of the subwindow if it exists
568 dismissSubWindow(current);
Leon Scroggins8588d152010-04-15 11:01:53 -0400569 // If the current Tab is being used as an application tab,
570 // remove the association, since the new Intent means that it is
571 // no longer associated with that application.
572 current.setAppId(null);
Patrick Scott9d53da02010-02-19 10:19:01 -0500573 loadUrlDataIn(current, urlData);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800574 }
575 }
576 }
577
Satish Sampath565505b2009-05-29 15:37:27 +0100578 private int parseUrlShortcut(String url) {
579 if (url == null) return SHORTCUT_INVALID;
580
581 // FIXME: quick search, need to be customized by setting
582 if (url.length() > 2 && url.charAt(1) == ' ') {
583 switch (url.charAt(0)) {
584 case 'g': return SHORTCUT_GOOGLE_SEARCH;
585 case 'w': return SHORTCUT_WIKIPEDIA_SEARCH;
586 case 'd': return SHORTCUT_DICTIONARY_SEARCH;
587 case 'l': return SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH;
588 }
589 }
590 return SHORTCUT_INVALID;
591 }
592
593 /**
594 * Launches the default web search activity with the query parameters if the given intent's data
595 * are identified as plain search terms and not URLs/shortcuts.
596 * @return true if the intent was handled and web search activity was launched, false if not.
597 */
598 private boolean handleWebSearchIntent(Intent intent) {
599 if (intent == null) return false;
600
601 String url = null;
602 final String action = intent.getAction();
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -0500603 if (RecognizerResultsIntent.ACTION_VOICE_SEARCH_RESULTS.equals(
604 action)) {
Leon Scroggins58d56c62010-01-28 15:12:40 -0500605 return false;
606 }
Satish Sampath565505b2009-05-29 15:37:27 +0100607 if (Intent.ACTION_VIEW.equals(action)) {
Grace Kloba1e705052009-09-29 13:13:36 -0700608 Uri data = intent.getData();
609 if (data != null) url = data.toString();
Satish Sampath565505b2009-05-29 15:37:27 +0100610 } else if (Intent.ACTION_SEARCH.equals(action)
611 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
612 || Intent.ACTION_WEB_SEARCH.equals(action)) {
613 url = intent.getStringExtra(SearchManager.QUERY);
614 }
Bjorn Bringert04851702009-09-22 10:36:01 +0100615 return handleWebSearchRequest(url, intent.getBundleExtra(SearchManager.APP_DATA),
616 intent.getStringExtra(SearchManager.EXTRA_DATA_KEY));
Satish Sampath565505b2009-05-29 15:37:27 +0100617 }
618
619 /**
620 * Launches the default web search activity with the query parameters if the given url string
621 * was identified as plain search terms and not URL/shortcut.
622 * @return true if the request was handled and web search activity was launched, false if not.
623 */
Bjorn Bringert04851702009-09-22 10:36:01 +0100624 private boolean handleWebSearchRequest(String inUrl, Bundle appData, String extraData) {
Satish Sampath565505b2009-05-29 15:37:27 +0100625 if (inUrl == null) return false;
626
627 // In general, we shouldn't modify URL from Intent.
628 // But currently, we get the user-typed URL from search box as well.
629 String url = fixUrl(inUrl).trim();
630
631 // URLs and site specific search shortcuts are handled by the regular flow of control, so
632 // return early.
Dan Egnor5ee906c2009-11-18 12:11:49 -0800633 if (Patterns.WEB_URL.matcher(url).matches()
Satish Sampathbc5b9f32009-06-04 18:21:40 +0100634 || ACCEPTED_URI_SCHEMA.matcher(url).matches()
Satish Sampath565505b2009-05-29 15:37:27 +0100635 || parseUrlShortcut(url) != SHORTCUT_INVALID) {
636 return false;
637 }
638
Leon Scroggins8d06e362010-03-24 14:45:57 -0400639 final ContentResolver cr = mResolver;
640 final String newUrl = url;
Elliott Slaughter627d96f2010-08-18 16:35:30 -0700641 if (mTabControl == null || !mTabControl.getCurrentWebView().isPrivateBrowsingEnabled()) {
Elliott Slaughterf0f03952010-07-14 18:10:36 -0700642 new AsyncTask<Void, Void, Void>() {
643 @Override
644 protected Void doInBackground(Void... unused) {
645 Browser.updateVisitedHistory(cr, newUrl, false);
646 Browser.addSearchUrl(cr, newUrl);
647 return null;
648 }
649 }.execute();
650 }
Satish Sampath565505b2009-05-29 15:37:27 +0100651
652 Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);
653 intent.addCategory(Intent.CATEGORY_DEFAULT);
654 intent.putExtra(SearchManager.QUERY, url);
Satish Sampath15e9f2d2009-06-23 22:29:49 +0100655 if (appData != null) {
656 intent.putExtra(SearchManager.APP_DATA, appData);
657 }
Bjorn Bringert04851702009-09-22 10:36:01 +0100658 if (extraData != null) {
659 intent.putExtra(SearchManager.EXTRA_DATA_KEY, extraData);
660 }
Grace Klobacc634032009-07-28 15:58:19 -0700661 intent.putExtra(Browser.EXTRA_APPLICATION_ID, getPackageName());
Satish Sampath565505b2009-05-29 15:37:27 +0100662 startActivity(intent);
663
664 return true;
665 }
666
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700667 private UrlData getUrlDataFromIntent(Intent intent) {
Leon Scroggins58d56c62010-01-28 15:12:40 -0500668 String url = "";
Grace Kloba068e48b2010-01-26 18:11:27 -0800669 Map<String, String> headers = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800670 if (intent != null) {
671 final String action = intent.getAction();
672 if (Intent.ACTION_VIEW.equals(action)) {
673 url = smartUrlFilter(intent.getData());
674 if (url != null && url.startsWith("content:")) {
675 /* Append mimetype so webview knows how to display */
676 String mimeType = intent.resolveType(getContentResolver());
677 if (mimeType != null) {
678 url += "?" + mimeType;
679 }
680 }
Grace Kloba068e48b2010-01-26 18:11:27 -0800681 if (url != null && url.startsWith("http")) {
Grace Kloba00f54c52010-01-27 14:53:51 -0800682 final Bundle pairs = intent
683 .getBundleExtra(Browser.EXTRA_HEADERS);
Grace Kloba2d508ed2010-01-28 11:39:15 -0800684 if (pairs != null && !pairs.isEmpty()) {
Grace Kloba00f54c52010-01-27 14:53:51 -0800685 Iterator<String> iter = pairs.keySet().iterator();
Grace Kloba068e48b2010-01-26 18:11:27 -0800686 headers = new HashMap<String, String>();
Grace Kloba00f54c52010-01-27 14:53:51 -0800687 while (iter.hasNext()) {
688 String key = iter.next();
689 headers.put(key, pairs.getString(key));
Grace Kloba068e48b2010-01-26 18:11:27 -0800690 }
691 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700692 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800693 } else if (Intent.ACTION_SEARCH.equals(action)
694 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
695 || Intent.ACTION_WEB_SEARCH.equals(action)) {
696 url = intent.getStringExtra(SearchManager.QUERY);
697 if (url != null) {
698 mLastEnteredUrl = url;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800699 // In general, we shouldn't modify URL from Intent.
700 // But currently, we get the user-typed URL from search box as well.
701 url = fixUrl(url);
702 url = smartUrlFilter(url);
Leon Scroggins8d06e362010-03-24 14:45:57 -0400703 final ContentResolver cr = mResolver;
704 final String newUrl = url;
705 new AsyncTask<Void, Void, Void>() {
Michael Kolbe0a36662010-06-29 10:37:12 -0700706 @Override
Leon Scroggins8d06e362010-03-24 14:45:57 -0400707 protected Void doInBackground(Void... unused) {
708 Browser.updateVisitedHistory(cr, newUrl, false);
709 return null;
710 }
711 }.execute();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800712 String searchSource = "&source=android-" + GOOGLE_SEARCH_SOURCE_SUGGEST + "&";
713 if (url.contains(searchSource)) {
714 String source = null;
715 final Bundle appData = intent.getBundleExtra(SearchManager.APP_DATA);
716 if (appData != null) {
Bjorn Bringert10d1cca2010-02-10 14:22:12 +0000717 source = appData.getString(Search.SOURCE);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800718 }
719 if (TextUtils.isEmpty(source)) {
720 source = GOOGLE_SEARCH_SOURCE_UNKNOWN;
721 }
722 url = url.replace(searchSource, "&source=android-"+source+"&");
723 }
724 }
725 }
726 }
Leon Scroggins58d56c62010-01-28 15:12:40 -0500727 return new UrlData(url, headers, intent);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800728 }
Leon Scroggins58d56c62010-01-28 15:12:40 -0500729 /* package */ void showVoiceTitleBar(String title) {
730 mTitleBar.setInVoiceMode(true);
Leon Scroggins58d56c62010-01-28 15:12:40 -0500731 mTitleBar.setDisplayTitle(title);
Michael Kolba2b2ba82010-08-04 17:54:03 -0700732 mFakeTitleBar.setInVoiceMode(true);
733 mFakeTitleBar.setDisplayTitle(title);
Leon Scroggins58d56c62010-01-28 15:12:40 -0500734 }
735 /* package */ void revertVoiceTitleBar() {
736 mTitleBar.setInVoiceMode(false);
Leon Scroggins003a5dd2010-03-10 12:13:14 -0500737 mTitleBar.setDisplayTitle(mUrl);
Michael Kolba2b2ba82010-08-04 17:54:03 -0700738 mFakeTitleBar.setInVoiceMode(false);
739 mFakeTitleBar.setDisplayTitle(mUrl);
Leon Scroggins58d56c62010-01-28 15:12:40 -0500740 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800741 /* package */ static String fixUrl(String inUrl) {
Cary Clark652ff872009-09-10 13:34:44 -0400742 // FIXME: Converting the url to lower case
743 // duplicates functionality in smartUrlFilter().
744 // However, changing all current callers of fixUrl to
745 // call smartUrlFilter in addition may have unwanted
746 // consequences, and is deferred for now.
747 int colon = inUrl.indexOf(':');
748 boolean allLower = true;
749 for (int index = 0; index < colon; index++) {
750 char ch = inUrl.charAt(index);
751 if (!Character.isLetter(ch)) {
752 break;
753 }
754 allLower &= Character.isLowerCase(ch);
755 if (index == colon - 1 && !allLower) {
756 inUrl = inUrl.substring(0, colon).toLowerCase()
757 + inUrl.substring(colon);
758 }
759 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800760 if (inUrl.startsWith("http://") || inUrl.startsWith("https://"))
761 return inUrl;
762 if (inUrl.startsWith("http:") ||
763 inUrl.startsWith("https:")) {
764 if (inUrl.startsWith("http:/") || inUrl.startsWith("https:/")) {
765 inUrl = inUrl.replaceFirst("/", "//");
766 } else inUrl = inUrl.replaceFirst(":", "://");
767 }
768 return inUrl;
769 }
770
Grace Kloba22ac16e2009-10-07 18:00:23 -0700771 @Override
772 protected void onResume() {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800773 super.onResume();
Dave Bort31a6d1c2009-04-13 15:56:49 -0700774 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800775 Log.v(LOGTAG, "BrowserActivity.onResume: this=" + this);
776 }
777
778 if (!mActivityInPause) {
779 Log.e(LOGTAG, "BrowserActivity is already resumed.");
780 return;
781 }
782
Mike Reed7bfa63b2009-05-28 11:08:32 -0400783 mTabControl.resumeCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800784 mActivityInPause = false;
Mike Reed7bfa63b2009-05-28 11:08:32 -0400785 resumeWebViewTimers();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800786
787 if (mWakeLock.isHeld()) {
788 mHandler.removeMessages(RELEASE_WAKELOCK);
789 mWakeLock.release();
790 }
791
The Android Open Source Project0c908882009-03-03 19:32:16 -0800792 registerReceiver(mNetworkStateIntentReceiver,
793 mNetworkStateChangedFilter);
794 WebView.enablePlatformNotifications();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800795 }
796
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400797 /**
798 * Since the actual title bar is embedded in the WebView, and removing it
Leon Scrogginsfe87bd32009-10-06 10:10:00 -0400799 * would change its appearance, use a different TitleBar to show overlayed
800 * at the top of the screen, when the menu is open or the page is loading.
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400801 */
Michael Kolba2b2ba82010-08-04 17:54:03 -0700802 private TitleBarBase mFakeTitleBar;
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400803
804 /**
805 * Keeps track of whether the options menu is open. This is important in
806 * determining whether to show or hide the title bar overlay.
807 */
808 private boolean mOptionsMenuOpen;
809
810 /**
811 * Only meaningful when mOptionsMenuOpen is true. This variable keeps track
812 * of whether the configuration has changed. The first onMenuOpened call
813 * after a configuration change is simply a reopening of the same menu
814 * (i.e. mIconView did not change).
815 */
816 private boolean mConfigChanged;
817
818 /**
819 * Whether or not the options menu is in its smaller, icon menu form. When
820 * true, we want the title bar overlay to be up. When false, we do not.
821 * Only meaningful if mOptionsMenuOpen is true.
822 */
823 private boolean mIconView;
824
Leon Scrogginsa81a7642009-08-31 17:05:41 -0400825 @Override
826 public boolean onMenuOpened(int featureId, Menu menu) {
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400827 if (Window.FEATURE_OPTIONS_PANEL == featureId) {
828 if (mOptionsMenuOpen) {
829 if (mConfigChanged) {
830 // We do not need to make any changes to the state of the
831 // title bar, since the only thing that happened was a
832 // change in orientation
833 mConfigChanged = false;
834 } else {
835 if (mIconView) {
836 // Switching the menu to expanded view, so hide the
837 // title bar.
838 hideFakeTitleBar();
839 mIconView = false;
840 } else {
841 // Switching the menu back to icon view, so show the
842 // title bar once again.
843 showFakeTitleBar();
844 mIconView = true;
845 }
846 }
847 } else {
848 // The options menu is closed, so open it, and show the title
849 showFakeTitleBar();
850 mOptionsMenuOpen = true;
851 mConfigChanged = false;
852 mIconView = true;
853 }
854 }
Leon Scrogginsa81a7642009-08-31 17:05:41 -0400855 return true;
856 }
857
Michael Kolba2b2ba82010-08-04 17:54:03 -0700858 void showFakeTitleBar() {
859 if (!isFakeTitleBarShowing() && mActiveTabsPage == null && !mActivityInPause) {
Grace Kloba847c25b2010-03-30 16:00:26 -0700860 WebView mainView = mTabControl.getCurrentWebView();
861 // if there is no current WebView, don't show the faked title bar;
Grace Kloba65190702010-04-02 23:37:26 -0700862 if (mainView == null) {
Cary Clarka0464552009-09-29 13:00:45 -0400863 return;
864 }
Leon Scroggins79e36d92010-04-29 16:01:46 +0100865 // Do not need to check for null, since the current tab will have
866 // at least a main WebView, or we would have returned above.
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -0400867 if (isInCustomActionMode()) {
868 // Do not show the fake title bar, while a custom ActionMode
869 // (i.e. find or select) is showing.
Leon Scroggins79e36d92010-04-29 16:01:46 +0100870 return;
871 }
Michael Kolba2b2ba82010-08-04 17:54:03 -0700872 if (mXLargeScreenSize) {
873 mContentView.addView(mFakeTitleBar);
874 mTabBar.onShowTitleBar();
875 } else {
876 WindowManager manager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400877
Michael Kolba2b2ba82010-08-04 17:54:03 -0700878 // Add the title bar to the window manager so it can receive
879 // touches
880 // while the menu is up
881 WindowManager.LayoutParams params =
882 new WindowManager.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
883 ViewGroup.LayoutParams.WRAP_CONTENT,
884 WindowManager.LayoutParams.TYPE_APPLICATION,
885 WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
886 PixelFormat.TRANSLUCENT);
887 params.gravity = Gravity.TOP;
888 boolean atTop = mainView.getScrollY() == 0;
889 params.windowAnimations = atTop ? 0 : R.style.TitleBar;
890 manager.addView(mFakeTitleBar, params);
891 }
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400892 }
893 }
894
895 @Override
896 public void onOptionsMenuClosed(Menu menu) {
897 mOptionsMenuOpen = false;
Leon Scrogginsa27ff192009-09-14 12:58:04 -0400898 if (!mInLoad) {
899 hideFakeTitleBar();
900 } else if (!mIconView) {
901 // The page is currently loading, and we are in expanded mode, so
902 // we were not showing the menu. Show it once again. It will be
903 // removed when the page finishes.
904 showFakeTitleBar();
905 }
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400906 }
Grace Kloba22ac16e2009-10-07 18:00:23 -0700907
Michael Kolba2b2ba82010-08-04 17:54:03 -0700908 void stopScrolling() {
909 ((ScrollWebView) mTabControl.getCurrentWebView()).stopScroll();
910 }
911
912 void hideFakeTitleBar() {
913 if (!isFakeTitleBarShowing()) return;
914 if (mXLargeScreenSize) {
915 mContentView.removeView(mFakeTitleBar);
916 mTabBar.onHideTitleBar();
917 } else {
918 WindowManager.LayoutParams params =
919 (WindowManager.LayoutParams) mFakeTitleBar.getLayoutParams();
920 WebView mainView = mTabControl.getCurrentWebView();
921 // Although we decided whether or not to animate based on the
922 // current
923 // scroll position, the scroll position may have changed since the
924 // fake title bar was displayed. Make sure it has the appropriate
925 // animation/lack thereof before removing.
926 params.windowAnimations =
927 mainView != null && mainView.getScrollY() == 0 ? 0 : R.style.TitleBar;
928 WindowManager manager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
929 manager.updateViewLayout(mFakeTitleBar, params);
930 manager.removeView(mFakeTitleBar);
931 }
932 }
933
934 boolean isFakeTitleBarShowing() {
935 return (mFakeTitleBar.getParent() != null);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400936 }
937
The Android Open Source Project0c908882009-03-03 19:32:16 -0800938 /**
Leon Scrogginsc6fa1102009-09-21 10:40:01 -0400939 * Special method for the fake title bar to call when displaying its context
940 * menu, since it is in its own Window, and its parent does not show a
941 * context menu.
942 */
943 /* package */ void showTitleBarContextMenu() {
Cary Clark65f4a3c2009-09-28 17:05:06 -0400944 if (null == mTitleBar.getParent()) {
945 return;
946 }
Leon Scrogginsc6fa1102009-09-21 10:40:01 -0400947 openContextMenu(mTitleBar);
948 }
949
Leon Scrogginsb2b19f52009-10-09 16:10:00 -0400950 @Override
951 public void onContextMenuClosed(Menu menu) {
952 super.onContextMenuClosed(menu);
953 if (mInLoad) {
954 showFakeTitleBar();
955 }
956 }
957
Leon Scrogginsc6fa1102009-09-21 10:40:01 -0400958 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -0800959 * onSaveInstanceState(Bundle map)
960 * onSaveInstanceState is called right before onStop(). The map contains
961 * the saved state.
962 */
Grace Kloba22ac16e2009-10-07 18:00:23 -0700963 @Override
964 protected void onSaveInstanceState(Bundle outState) {
Dave Bort31a6d1c2009-04-13 15:56:49 -0700965 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800966 Log.v(LOGTAG, "BrowserActivity.onSaveInstanceState: this=" + this);
967 }
968 // the default implementation requires each view to have an id. As the
969 // browser handles the state itself and it doesn't use id for the views,
970 // don't call the default implementation. Otherwise it will trigger the
971 // warning like this, "couldn't save which view has focus because the
972 // focused view XXX has no id".
973
974 // Save all the tabs
975 mTabControl.saveState(outState);
976 }
977
Grace Kloba22ac16e2009-10-07 18:00:23 -0700978 @Override
979 protected void onPause() {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800980 super.onPause();
981
982 if (mActivityInPause) {
983 Log.e(LOGTAG, "BrowserActivity is already paused.");
984 return;
985 }
986
Mike Reed7bfa63b2009-05-28 11:08:32 -0400987 mTabControl.pauseCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800988 mActivityInPause = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -0400989 if (mTabControl.getCurrentIndex() >= 0 && !pauseWebViewTimers()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800990 mWakeLock.acquire();
991 mHandler.sendMessageDelayed(mHandler
992 .obtainMessage(RELEASE_WAKELOCK), WAKELOCK_TIMEOUT);
993 }
994
Leon Scrogginsa2ab6a72009-09-11 11:49:52 -0400995 // FIXME: This removes the active tabs page and resets the menu to
996 // MAIN_MENU. A better solution might be to do this work in onNewIntent
997 // but then we would need to save it in onSaveInstanceState and restore
998 // it in onCreate/onRestoreInstanceState
999 if (mActiveTabsPage != null) {
1000 removeActiveTabPage(true);
1001 }
1002
The Android Open Source Project0c908882009-03-03 19:32:16 -08001003 cancelStopToast();
1004
1005 // unregister network state listener
1006 unregisterReceiver(mNetworkStateIntentReceiver);
1007 WebView.disablePlatformNotifications();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001008 }
1009
Grace Kloba22ac16e2009-10-07 18:00:23 -07001010 @Override
1011 protected void onDestroy() {
Dave Bort31a6d1c2009-04-13 15:56:49 -07001012 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001013 Log.v(LOGTAG, "BrowserActivity.onDestroy: this=" + this);
1014 }
1015 super.onDestroy();
Grace Kloba0923d692009-09-23 21:37:25 -07001016
Leon Scroggins8d5fa432009-10-02 15:55:59 -04001017 if (mUploadMessage != null) {
1018 mUploadMessage.onReceiveValue(null);
1019 mUploadMessage = null;
1020 }
1021
Grace Kloba0923d692009-09-23 21:37:25 -07001022 if (mTabControl == null) return;
1023
Grace Kloba1fc98a32009-10-21 13:23:08 -07001024 // Remove the fake title bar if it is there
1025 hideFakeTitleBar();
1026
The Android Open Source Project0c908882009-03-03 19:32:16 -08001027 // Remove the current tab and sub window
Grace Kloba22ac16e2009-10-07 18:00:23 -07001028 Tab t = mTabControl.getCurrentTab();
Patrick Scottfb5e77f2009-04-08 19:17:37 -07001029 if (t != null) {
1030 dismissSubWindow(t);
1031 removeTabFromContentView(t);
1032 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001033 // Destroy all the tabs
1034 mTabControl.destroy();
1035 WebIconDatabase.getInstance().close();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001036
Grace Klobab4da0ad2009-05-14 14:45:40 -07001037 unregisterReceiver(mPackageInstallationReceiver);
Bjorn Bringerta7611812010-03-24 11:12:02 +00001038
1039 // Stop watching the default geolocation permissions
1040 mSystemAllowGeolocationOrigins.stop();
1041 mSystemAllowGeolocationOrigins = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001042 }
1043
1044 @Override
1045 public void onConfigurationChanged(Configuration newConfig) {
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04001046 mConfigChanged = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001047 super.onConfigurationChanged(newConfig);
1048
1049 if (mPageInfoDialog != null) {
1050 mPageInfoDialog.dismiss();
1051 showPageInfo(
1052 mPageInfoView,
Leon Scrogginsc7b92f82010-01-11 18:17:31 -05001053 mPageInfoFromShowSSLCertificateOnError);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001054 }
1055 if (mSSLCertificateDialog != null) {
1056 mSSLCertificateDialog.dismiss();
1057 showSSLCertificate(
1058 mSSLCertificateView);
1059 }
1060 if (mSSLCertificateOnErrorDialog != null) {
1061 mSSLCertificateOnErrorDialog.dismiss();
1062 showSSLCertificateOnError(
1063 mSSLCertificateOnErrorView,
1064 mSSLCertificateOnErrorHandler,
1065 mSSLCertificateOnErrorError);
1066 }
1067 if (mHttpAuthenticationDialog != null) {
1068 String title = ((TextView) mHttpAuthenticationDialog
1069 .findViewById(com.android.internal.R.id.alertTitle)).getText()
1070 .toString();
1071 String name = ((TextView) mHttpAuthenticationDialog
1072 .findViewById(R.id.username_edit)).getText().toString();
1073 String password = ((TextView) mHttpAuthenticationDialog
1074 .findViewById(R.id.password_edit)).getText().toString();
1075 int focusId = mHttpAuthenticationDialog.getCurrentFocus()
1076 .getId();
1077 mHttpAuthenticationDialog.dismiss();
1078 showHttpAuthentication(mHttpAuthHandler, null, null, title,
1079 name, password, focusId);
1080 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001081 }
1082
Grace Kloba22ac16e2009-10-07 18:00:23 -07001083 @Override
1084 public void onLowMemory() {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001085 super.onLowMemory();
1086 mTabControl.freeMemory();
1087 }
1088
Cary Clarkff4d92c2010-03-25 11:17:03 -04001089 private void resumeWebViewTimers() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001090 Tab tab = mTabControl.getCurrentTab();
Cary Clarkff4d92c2010-03-25 11:17:03 -04001091 if (tab == null) return; // monkey can trigger this
Grace Kloba22ac16e2009-10-07 18:00:23 -07001092 boolean inLoad = tab.inLoad();
1093 if ((!mActivityInPause && !inLoad) || (mActivityInPause && inLoad)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001094 CookieSyncManager.getInstance().startSync();
Grace Kloba22ac16e2009-10-07 18:00:23 -07001095 WebView w = tab.getWebView();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001096 if (w != null) {
1097 w.resumeTimers();
1098 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001099 }
1100 }
1101
Mike Reed7bfa63b2009-05-28 11:08:32 -04001102 private boolean pauseWebViewTimers() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001103 Tab tab = mTabControl.getCurrentTab();
1104 boolean inLoad = tab.inLoad();
1105 if (mActivityInPause && !inLoad) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001106 CookieSyncManager.getInstance().stopSync();
1107 WebView w = mTabControl.getCurrentWebView();
1108 if (w != null) {
1109 w.pauseTimers();
1110 }
1111 return true;
1112 } else {
1113 return false;
1114 }
1115 }
1116
The Android Open Source Project0c908882009-03-03 19:32:16 -08001117 // Open the icon database and retain all the icons for visited sites.
1118 private void retainIconsOnStartup() {
1119 final WebIconDatabase db = WebIconDatabase.getInstance();
1120 db.open(getDir("icons", 0).getPath());
Leon Scroggins2c0f6112010-03-12 18:09:39 -05001121 Cursor c = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001122 try {
Leon Scroggins2c0f6112010-03-12 18:09:39 -05001123 c = Browser.getAllBookmarks(mResolver);
1124 if (c.moveToFirst()) {
1125 int urlIndex = c.getColumnIndex(Browser.BookmarkColumns.URL);
1126 do {
1127 String url = c.getString(urlIndex);
1128 db.retainIconForPageUrl(url);
1129 } while (c.moveToNext());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001130 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001131 } catch (IllegalStateException e) {
1132 Log.e(LOGTAG, "retainIconsOnStartup", e);
Leon Scroggins2c0f6112010-03-12 18:09:39 -05001133 } finally {
1134 if (c!= null) c.close();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001135 }
1136 }
1137
1138 // Helper method for getting the top window.
1139 WebView getTopWindow() {
1140 return mTabControl.getCurrentTopWebView();
1141 }
1142
Grace Kloba22ac16e2009-10-07 18:00:23 -07001143 TabControl getTabControl() {
1144 return mTabControl;
1145 }
1146
The Android Open Source Project0c908882009-03-03 19:32:16 -08001147 @Override
1148 public boolean onCreateOptionsMenu(Menu menu) {
1149 super.onCreateOptionsMenu(menu);
1150
1151 MenuInflater inflater = getMenuInflater();
1152 inflater.inflate(R.menu.browser, menu);
1153 mMenu = menu;
1154 updateInLoadMenuItems();
1155 return true;
1156 }
1157
1158 /**
1159 * As the menu can be open when loading state changes
1160 * we must manually update the state of the stop/reload menu
1161 * item
1162 */
1163 private void updateInLoadMenuItems() {
1164 if (mMenu == null) {
1165 return;
1166 }
Michael Kolbe0a36662010-06-29 10:37:12 -07001167 MenuItem dest = mMenu.findItem(R.id.stop_reload_menu_id);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001168 MenuItem src = mInLoad ?
1169 mMenu.findItem(R.id.stop_menu_id):
Michael Kolbe0a36662010-06-29 10:37:12 -07001170 mMenu.findItem(R.id.reload_menu_id);
1171 if (src != null) {
1172 dest.setIcon(src.getIcon());
1173 dest.setTitle(src.getTitle());
1174 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001175 }
1176
1177 @Override
1178 public boolean onContextItemSelected(MenuItem item) {
1179 // chording is not an issue with context menus, but we use the same
1180 // options selector, so set mCanChord to true so we can access them.
1181 mCanChord = true;
1182 int id = item.getItemId();
Leon Scroggins96afcb12009-12-10 12:35:56 -05001183 boolean result = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001184 switch (id) {
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001185 // For the context menu from the title bar
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001186 case R.id.title_bar_copy_page_url:
Leon Scroggins96afcb12009-12-10 12:35:56 -05001187 Tab currentTab = mTabControl.getCurrentTab();
1188 if (null == currentTab) {
1189 result = false;
1190 break;
1191 }
1192 WebView mainView = currentTab.getWebView();
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001193 if (null == mainView) {
Leon Scroggins96afcb12009-12-10 12:35:56 -05001194 result = false;
1195 break;
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001196 }
Leon Scroggins96afcb12009-12-10 12:35:56 -05001197 copy(mainView.getUrl());
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001198 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001199 // -- Browser context menu
1200 case R.id.open_context_menu_id:
The Android Open Source Project0c908882009-03-03 19:32:16 -08001201 case R.id.bookmark_context_menu_id:
1202 case R.id.save_link_context_menu_id:
1203 case R.id.share_link_context_menu_id:
1204 case R.id.copy_link_context_menu_id:
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001205 final WebView webView = getTopWindow();
1206 if (null == webView) {
Leon Scroggins96afcb12009-12-10 12:35:56 -05001207 result = false;
1208 break;
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001209 }
1210 final HashMap hrefMap = new HashMap();
1211 hrefMap.put("webview", webView);
1212 final Message msg = mHandler.obtainMessage(
1213 FOCUS_NODE_HREF, id, 0, hrefMap);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001214 webView.requestFocusNodeHref(msg);
1215 break;
1216
1217 default:
1218 // For other context menus
Leon Scroggins96afcb12009-12-10 12:35:56 -05001219 result = onOptionsItemSelected(item);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001220 }
1221 mCanChord = false;
Leon Scroggins96afcb12009-12-10 12:35:56 -05001222 return result;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001223 }
1224
1225 private Bundle createGoogleSearchSourceBundle(String source) {
1226 Bundle bundle = new Bundle();
Bjorn Bringert10d1cca2010-02-10 14:22:12 +00001227 bundle.putString(Search.SOURCE, source);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001228 return bundle;
1229 }
1230
Leon Scroggins8ad29922010-02-16 12:33:55 -05001231 /* package */ void editUrl() {
Leon Scroggins68579392009-09-15 15:31:54 -04001232 if (mOptionsMenuOpen) closeOptionsMenu();
Leon Scroggins5bbe9802009-07-31 13:10:55 -04001233 String url = (getTopWindow() == null) ? null : getTopWindow().getUrl();
Grace Kloba83f47342009-07-20 10:44:31 -07001234 startSearch(mSettings.getHomePage().equals(url) ? null : url, true,
Leon Scroggins8ad29922010-02-16 12:33:55 -05001235 null, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001236 }
1237
Leon Scroggins8ad29922010-02-16 12:33:55 -05001238 /**
1239 * Overriding this to insert a local information bundle
1240 */
The Android Open Source Project0c908882009-03-03 19:32:16 -08001241 @Override
1242 public void startSearch(String initialQuery, boolean selectInitialQuery,
1243 Bundle appSearchData, boolean globalSearch) {
1244 if (appSearchData == null) {
1245 appSearchData = createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_TYPE);
1246 }
1247 super.startSearch(initialQuery, selectInitialQuery, appSearchData, globalSearch);
1248 }
1249
Leon Scroggins1f005d32009-08-10 17:36:42 -04001250 /**
1251 * Switch tabs. Called by the TitleBarSet when sliding the title bar
1252 * results in changing tabs.
Leon Scroggins160a7e72009-08-14 18:28:01 -04001253 * @param index Index of the tab to change to, as defined by
1254 * mTabControl.getTabIndex(Tab t).
1255 * @return boolean True if we successfully switched to a different tab. If
1256 * the indexth tab is null, or if that tab is the same as
1257 * the current one, return false.
Leon Scroggins1f005d32009-08-10 17:36:42 -04001258 */
Leon Scroggins160a7e72009-08-14 18:28:01 -04001259 /* package */ boolean switchToTab(int index) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001260 Tab tab = mTabControl.getTab(index);
1261 Tab currentTab = mTabControl.getCurrentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04001262 if (tab == null || tab == currentTab) {
Leon Scroggins160a7e72009-08-14 18:28:01 -04001263 return false;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001264 }
1265 if (currentTab != null) {
1266 // currentTab may be null if it was just removed. In that case,
1267 // we do not need to remove it
1268 removeTabFromContentView(currentTab);
1269 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001270 mTabControl.setCurrentTab(tab);
1271 attachTabToContentView(tab);
Grace Klobaeb6eef42009-09-15 17:56:32 -07001272 resetTitleIconAndProgress();
1273 updateLockIconToLatest();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001274 return true;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001275 }
1276
Grace Kloba22ac16e2009-10-07 18:00:23 -07001277 /* package */ Tab openTabToHomePage() {
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001278 return openTabAndShow(mSettings.getHomePage(), false, null);
1279 }
1280
Leon Scroggins1f005d32009-08-10 17:36:42 -04001281 /* package */ void closeCurrentWindow() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001282 final Tab current = mTabControl.getCurrentTab();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001283 if (mTabControl.getTabCount() == 1) {
Leon Scroggins30444232009-09-04 18:36:20 -04001284 // This is the last tab. Open a new one, with the home
1285 // page and close the current one.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001286 openTabToHomePage();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001287 closeTab(current);
Leon Scroggins160a7e72009-08-14 18:28:01 -04001288 return;
1289 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07001290 final Tab parent = current.getParentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04001291 int indexToShow = -1;
1292 if (parent != null) {
1293 indexToShow = mTabControl.getTabIndex(parent);
1294 } else {
Leon Scroggins160a7e72009-08-14 18:28:01 -04001295 final int currentIndex = mTabControl.getCurrentIndex();
1296 // Try to move to the tab to the right
1297 indexToShow = currentIndex + 1;
1298 if (indexToShow > mTabControl.getTabCount() - 1) {
1299 // Try to move to the tab to the left
1300 indexToShow = currentIndex - 1;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001301 }
1302 }
Leon Scroggins160a7e72009-08-14 18:28:01 -04001303 if (switchToTab(indexToShow)) {
1304 // Close window
1305 closeTab(current);
1306 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001307 }
1308
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001309 private ActiveTabsPage mActiveTabsPage;
1310
1311 /**
1312 * Remove the active tabs page.
1313 * @param needToAttach If true, the active tabs page did not attach a tab
1314 * to the content view, so we need to do that here.
1315 */
1316 /* package */ void removeActiveTabPage(boolean needToAttach) {
1317 mContentView.removeView(mActiveTabsPage);
Leon Scrogginsd746a942010-05-19 13:21:44 -04001318 mTitleBar.setVisibility(View.VISIBLE);
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001319 mActiveTabsPage = null;
1320 mMenuState = R.id.MAIN_MENU;
1321 if (needToAttach) {
1322 attachTabToContentView(mTabControl.getCurrentTab());
1323 }
1324 getTopWindow().requestFocus();
1325 }
1326
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04001327 @Override
1328 public ActionMode onStartActionMode(ActionMode.Callback callback) {
1329 ActionMode mode = super.onStartActionMode(callback);
1330 if (callback instanceof FindActionModeCallback
1331 || callback instanceof SelectActionModeCallback) {
1332 // For find and select, hide extra title bars. They will
1333 // be replaced in onEndActionMode.
1334 Tab tab = mTabControl.getCurrentTab();
1335 if (tab.getSubWebView() == null) {
1336 // If the find or select is being performed on the main webview,
1337 // remove the embedded title bar.
1338 WebView mainView = tab.getWebView();
1339 if (mainView != null) {
1340 mainView.setEmbeddedTitleBar(null);
1341 }
Cary Clark01cfcdd2010-06-04 16:36:45 -04001342 }
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04001343 hideFakeTitleBar();
1344 mActionMode = mode;
1345 } else {
1346 // Do not store other ActionModes, since we are unable to determine
1347 // when they finish.
1348 mActionMode = null;
Cary Clark01cfcdd2010-06-04 16:36:45 -04001349 }
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04001350 return mode;
Cary Clark01cfcdd2010-06-04 16:36:45 -04001351 }
1352
The Android Open Source Project0c908882009-03-03 19:32:16 -08001353 @Override
1354 public boolean onOptionsItemSelected(MenuItem item) {
Michael Kolbed217742010-08-10 17:52:34 -07001355 // check the action bar button before mCanChord check, as the prepare call
1356 // doesn't come for action bar buttons
1357 if (item.getItemId() == R.id.newtab) {
1358 bookmarksOrHistoryPicker(false, true);
1359 return true;
1360 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001361 if (!mCanChord) {
1362 // The user has already fired a shortcut with this hold down of the
1363 // menu key.
1364 return false;
1365 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001366 if (null == getTopWindow()) {
Leon Scroggins0d7ae0e2009-06-05 11:04:45 -04001367 return false;
1368 }
Grace Kloba6ee9c492009-07-13 10:04:34 -07001369 if (mMenuIsDown) {
1370 // The shortcut action consumes the MENU. Even if it is still down,
1371 // it won't trigger the next shortcut action. In the case of the
1372 // shortcut action triggering a new activity, like Bookmarks, we
1373 // won't get onKeyUp for MENU. So it is important to reset it here.
1374 mMenuIsDown = false;
1375 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001376 switch (item.getItemId()) {
1377 // -- Main menu
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001378 case R.id.new_tab_menu_id:
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001379 openTabToHomePage();
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001380 break;
1381
Michael Kolbae62fd42010-08-18 16:33:28 -07001382 case R.id.incognito_menu_id:
1383 openIncognitoTab();
1384 break;
1385
Leon Scroggins64b80f32009-08-07 12:03:34 -04001386 case R.id.goto_menu_id:
Leon Scroggins8ad29922010-02-16 12:33:55 -05001387 editUrl();
Leon Scrogginsb3a5bed2009-09-28 11:21:56 -04001388 break;
1389
1390 case R.id.bookmarks_menu_id:
Michael Kolb68792c82010-08-09 16:39:18 -07001391 bookmarksOrHistoryPicker(false, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001392 break;
1393
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001394 case R.id.active_tabs_menu_id:
1395 mActiveTabsPage = new ActiveTabsPage(this, mTabControl);
1396 removeTabFromContentView(mTabControl.getCurrentTab());
Leon Scrogginsd746a942010-05-19 13:21:44 -04001397 mTitleBar.setVisibility(View.GONE);
Leon Scroggins43de6162009-09-14 19:59:58 -04001398 hideFakeTitleBar();
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001399 mContentView.addView(mActiveTabsPage, COVER_SCREEN_PARAMS);
1400 mActiveTabsPage.requestFocus();
1401 mMenuState = EMPTY_MENU;
1402 break;
1403
Leon Scroggins1f005d32009-08-10 17:36:42 -04001404 case R.id.add_bookmark_menu_id:
Leon Scroggins571b3762010-05-26 10:25:01 -04001405 bookmarkCurrentPage();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001406 break;
1407
1408 case R.id.stop_reload_menu_id:
1409 if (mInLoad) {
1410 stopLoading();
1411 } else {
1412 getTopWindow().reload();
1413 }
1414 break;
1415
1416 case R.id.back_menu_id:
1417 getTopWindow().goBack();
1418 break;
1419
1420 case R.id.forward_menu_id:
1421 getTopWindow().goForward();
1422 break;
1423
1424 case R.id.close_menu_id:
1425 // Close the subwindow if it exists.
1426 if (mTabControl.getCurrentSubWindow() != null) {
1427 dismissSubWindow(mTabControl.getCurrentTab());
1428 break;
1429 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001430 closeCurrentWindow();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001431 break;
1432
1433 case R.id.homepage_menu_id:
Grace Kloba22ac16e2009-10-07 18:00:23 -07001434 Tab current = mTabControl.getCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001435 if (current != null) {
1436 dismissSubWindow(current);
Leon Scroggins92472e82010-02-17 16:32:28 -05001437 loadUrl(current.getWebView(), mSettings.getHomePage());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001438 }
1439 break;
1440
1441 case R.id.preferences_menu_id:
1442 Intent intent = new Intent(this,
1443 BrowserPreferencesPage.class);
Leon Scrogginsd5304942009-12-10 16:11:39 -05001444 intent.putExtra(BrowserPreferencesPage.CURRENT_PAGE,
1445 getTopWindow().getUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001446 startActivityForResult(intent, PREFERENCES_PAGE);
1447 break;
1448
1449 case R.id.find_menu_id:
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04001450 showFindDialog(null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001451 break;
1452
Elliott Slaughter0ced08c2010-06-30 11:40:42 -07001453 case R.id.save_webarchive_menu_id:
1454 if (LOGD_ENABLED) {
1455 Log.d(LOGTAG, "Save as Web Archive");
1456 }
1457 String directory = getExternalFilesDir(null).getAbsolutePath() + File.separator;
1458 getTopWindow().saveWebArchive(directory, true, new ValueCallback<String>() {
1459 @Override
1460 public void onReceiveValue(String value) {
1461 if (value != null) {
1462 Toast.makeText(BrowserActivity.this, R.string.webarchive_saved, Toast.LENGTH_SHORT).show();
1463 } else {
1464 Toast.makeText(BrowserActivity.this, R.string.webarchive_failed, Toast.LENGTH_SHORT).show();
1465 }
1466 }
1467 });
1468 break;
1469
The Android Open Source Project0c908882009-03-03 19:32:16 -08001470 case R.id.page_info_menu_id:
1471 showPageInfo(mTabControl.getCurrentTab(), false);
1472 break;
1473
1474 case R.id.classic_history_menu_id:
Michael Kolb68792c82010-08-09 16:39:18 -07001475 bookmarksOrHistoryPicker(true, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001476 break;
1477
Leon Scroggins96afcb12009-12-10 12:35:56 -05001478 case R.id.title_bar_share_page_url:
The Android Open Source Project0c908882009-03-03 19:32:16 -08001479 case R.id.share_page_menu_id:
Leon Scroggins96afcb12009-12-10 12:35:56 -05001480 Tab currentTab = mTabControl.getCurrentTab();
1481 if (null == currentTab) {
1482 mCanChord = false;
1483 return false;
1484 }
1485 currentTab.populatePickerData();
1486 sharePage(this, currentTab.getTitle(),
1487 currentTab.getUrl(), currentTab.getFavicon(),
Ben Murdoch87cc65d2010-06-29 20:34:10 +01001488 createScreenshot(currentTab.getWebView(), getDesiredThumbnailWidth(this),
1489 getDesiredThumbnailHeight(this)));
The Android Open Source Project0c908882009-03-03 19:32:16 -08001490 break;
1491
1492 case R.id.dump_nav_menu_id:
1493 getTopWindow().debugDump();
1494 break;
1495
Andrei Popescu7a8b88b2010-02-02 00:30:38 +00001496 case R.id.dump_counters_menu_id:
1497 getTopWindow().dumpV8Counters();
1498 break;
1499
The Android Open Source Project0c908882009-03-03 19:32:16 -08001500 case R.id.zoom_in_menu_id:
1501 getTopWindow().zoomIn();
1502 break;
1503
1504 case R.id.zoom_out_menu_id:
1505 getTopWindow().zoomOut();
1506 break;
1507
1508 case R.id.view_downloads_menu_id:
1509 viewDownloads(null);
1510 break;
1511
The Android Open Source Project0c908882009-03-03 19:32:16 -08001512 case R.id.window_one_menu_id:
1513 case R.id.window_two_menu_id:
1514 case R.id.window_three_menu_id:
1515 case R.id.window_four_menu_id:
1516 case R.id.window_five_menu_id:
1517 case R.id.window_six_menu_id:
1518 case R.id.window_seven_menu_id:
1519 case R.id.window_eight_menu_id:
1520 {
1521 int menuid = item.getItemId();
1522 for (int id = 0; id < WINDOW_SHORTCUT_ID_ARRAY.length; id++) {
1523 if (WINDOW_SHORTCUT_ID_ARRAY[id] == menuid) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001524 Tab desiredTab = mTabControl.getTab(id);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001525 if (desiredTab != null &&
1526 desiredTab != mTabControl.getCurrentTab()) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001527 switchToTab(id);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001528 }
1529 break;
1530 }
1531 }
1532 }
1533 break;
1534
1535 default:
1536 if (!super.onOptionsItemSelected(item)) {
1537 return false;
1538 }
1539 // Otherwise fall through.
1540 }
1541 mCanChord = false;
1542 return true;
1543 }
1544
Leon Scroggins571b3762010-05-26 10:25:01 -04001545 /* package */ void bookmarkCurrentPage() {
1546 Intent i = new Intent(BrowserActivity.this,
1547 AddBookmarkPage.class);
1548 WebView w = getTopWindow();
1549 i.putExtra("url", w.getUrl());
1550 i.putExtra("title", w.getTitle());
1551 i.putExtra("touch_icon_url", w.getTouchIconUrl());
Ben Murdoch87cc65d2010-06-29 20:34:10 +01001552 i.putExtra("thumbnail", createScreenshot(w, getDesiredThumbnailWidth(this),
1553 getDesiredThumbnailHeight(this)));
Ben Murdocheecb4e62010-07-06 16:30:38 +01001554 i.putExtra("url_editable", false);
Leon Scroggins571b3762010-05-26 10:25:01 -04001555 startActivity(i);
1556 }
1557
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04001558 /*
1559 * True if a custom ActionMode (i.e. find or select) is in use.
1560 */
1561 private boolean isInCustomActionMode() {
1562 return mActionMode != null;
Cary Clark01cfcdd2010-06-04 16:36:45 -04001563 }
1564
1565 /*
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04001566 * End the current ActionMode. Only works for find and select.
Cary Clark01cfcdd2010-06-04 16:36:45 -04001567 */
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04001568 void endActionMode() {
1569 if (mActionMode != null) {
1570 mActionMode.finish();
1571 }
1572 }
1573
1574 /*
1575 * Called by find and select when they are finished. Replace title bars
1576 * as necessary.
1577 */
1578 public void onEndActionMode() {
1579 if (!isInCustomActionMode()) return;
Michael Kolba2b2ba82010-08-04 17:54:03 -07001580 // If the Find was being performed in the main WebView, replace the
1581 // embedded title bar.
1582 Tab currentTab = mTabControl.getCurrentTab();
1583 if (currentTab.getSubWebView() == null) {
1584 WebView mainView = currentTab.getWebView();
1585 if (mainView != null) {
1586 mainView.setEmbeddedTitleBar(mTitleBar);
Leon Scroggins79e36d92010-04-29 16:01:46 +01001587 }
1588 }
Leon Scroggins79e36d92010-04-29 16:01:46 +01001589 if (mInLoad) {
1590 // The title bar was hidden, because otherwise it would cover up the
Michael Kolba2b2ba82010-08-04 17:54:03 -07001591 // find or select dialog. Now that the dialog has been removed,
Cary Clark01cfcdd2010-06-04 16:36:45 -04001592 // show the fake title bar once again.
Leon Scroggins79e36d92010-04-29 16:01:46 +01001593 showFakeTitleBar();
1594 }
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04001595 mActionMode = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001596 }
1597
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04001598 private FindActionModeCallback mFindCallback;
1599 private SelectActionModeCallback mSelectCallback;
1600
1601 // For select and find, we keep track of the ActionMode so that
1602 // finish() can be called as desired.
1603 private ActionMode mActionMode;
1604
1605 /*
1606 * Open the find ActionMode.
1607 * @param text If non null, will be placed in find to be searched for.
1608 */
1609 public void showFindDialog(String text) {
1610 if (null == mFindCallback) {
1611 mFindCallback = new FindActionModeCallback(this);
Cary Clark01cfcdd2010-06-04 16:36:45 -04001612 }
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04001613 WebView webView = getTopWindow();
1614 webView.setFindIsUp(true);
1615 mFindCallback.setWebView(webView);
1616 startActionMode(mFindCallback);
1617 if (text != null) mFindCallback.setText(text);
Cary Clark01cfcdd2010-06-04 16:36:45 -04001618 }
1619
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04001620 /*
1621 * Show the select ActionMode.
1622 */
Cary Clark01cfcdd2010-06-04 16:36:45 -04001623 public void showSelectDialog() {
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04001624 if (null == mSelectCallback) {
1625 mSelectCallback = new SelectActionModeCallback(this);
Cary Clark01cfcdd2010-06-04 16:36:45 -04001626 }
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04001627 WebView webView = getTopWindow();
1628 webView.setUpSelect();
1629 mSelectCallback.setWebView(webView);
1630 startActionMode(mSelectCallback);
Cary Clark01cfcdd2010-06-04 16:36:45 -04001631 }
1632
Grace Kloba22ac16e2009-10-07 18:00:23 -07001633 @Override
1634 public boolean onPrepareOptionsMenu(Menu menu) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001635 // This happens when the user begins to hold down the menu key, so
1636 // allow them to chord to get a shortcut.
1637 mCanChord = true;
1638 // Note: setVisible will decide whether an item is visible; while
1639 // setEnabled() will decide whether an item is enabled, which also means
1640 // whether the matching shortcut key will function.
1641 super.onPrepareOptionsMenu(menu);
1642 switch (mMenuState) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001643 case EMPTY_MENU:
1644 if (mCurrentMenuState != mMenuState) {
1645 menu.setGroupVisible(R.id.MAIN_MENU, false);
1646 menu.setGroupEnabled(R.id.MAIN_MENU, false);
1647 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001648 }
1649 break;
1650 default:
1651 if (mCurrentMenuState != mMenuState) {
1652 menu.setGroupVisible(R.id.MAIN_MENU, true);
1653 menu.setGroupEnabled(R.id.MAIN_MENU, true);
1654 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001655 }
1656 final WebView w = getTopWindow();
1657 boolean canGoBack = false;
1658 boolean canGoForward = false;
1659 boolean isHome = false;
1660 if (w != null) {
1661 canGoBack = w.canGoBack();
1662 canGoForward = w.canGoForward();
1663 isHome = mSettings.getHomePage().equals(w.getUrl());
1664 }
1665 final MenuItem back = menu.findItem(R.id.back_menu_id);
1666 back.setEnabled(canGoBack);
1667
1668 final MenuItem home = menu.findItem(R.id.homepage_menu_id);
1669 home.setEnabled(!isHome);
1670
Michael Kolbe0a36662010-06-29 10:37:12 -07001671 final MenuItem forward = menu.findItem(R.id.forward_menu_id);
1672 forward.setEnabled(canGoForward);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001673
Michael Kolbed217742010-08-10 17:52:34 -07001674 if (!mXLargeScreenSize) {
1675 final MenuItem newtab = menu.findItem(R.id.new_tab_menu_id);
1676 newtab.setEnabled(mTabControl.canCreateNewTab());
1677 }
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001678
The Android Open Source Project0c908882009-03-03 19:32:16 -08001679 // decide whether to show the share link option
1680 PackageManager pm = getPackageManager();
1681 Intent send = new Intent(Intent.ACTION_SEND);
1682 send.setType("text/plain");
1683 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1684 menu.findItem(R.id.share_page_menu_id).setVisible(ri != null);
1685
The Android Open Source Project0c908882009-03-03 19:32:16 -08001686 boolean isNavDump = mSettings.isNavDump();
1687 final MenuItem nav = menu.findItem(R.id.dump_nav_menu_id);
1688 nav.setVisible(isNavDump);
1689 nav.setEnabled(isNavDump);
Andrei Popescu7a8b88b2010-02-02 00:30:38 +00001690
1691 boolean showDebugSettings = mSettings.showDebugSettings();
1692 final MenuItem counter = menu.findItem(R.id.dump_counters_menu_id);
1693 counter.setVisible(showDebugSettings);
1694 counter.setEnabled(showDebugSettings);
1695
The Android Open Source Project0c908882009-03-03 19:32:16 -08001696 break;
1697 }
1698 mCurrentMenuState = mMenuState;
1699 return true;
1700 }
1701
1702 @Override
1703 public void onCreateContextMenu(ContextMenu menu, View v,
1704 ContextMenuInfo menuInfo) {
Leon Scroggins571b3762010-05-26 10:25:01 -04001705 if (v instanceof TitleBarBase) {
Leon Scroggins4e9f89b2010-02-22 16:54:14 -05001706 return;
1707 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001708 WebView webview = (WebView) v;
1709 WebView.HitTestResult result = webview.getHitTestResult();
1710 if (result == null) {
1711 return;
1712 }
1713
1714 int type = result.getType();
1715 if (type == WebView.HitTestResult.UNKNOWN_TYPE) {
1716 Log.w(LOGTAG,
1717 "We should not show context menu when nothing is touched");
1718 return;
1719 }
1720 if (type == WebView.HitTestResult.EDIT_TEXT_TYPE) {
1721 // let TextView handles context menu
1722 return;
1723 }
1724
1725 // Note, http://b/issue?id=1106666 is requesting that
1726 // an inflated menu can be used again. This is not available
1727 // yet, so inflate each time (yuk!)
1728 MenuInflater inflater = getMenuInflater();
1729 inflater.inflate(R.menu.browsercontext, menu);
1730
1731 // Show the correct menu group
Leon Scroggins III9e997c72010-05-26 13:25:16 -04001732 final String extra = result.getExtra();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001733 menu.setGroupVisible(R.id.PHONE_MENU,
1734 type == WebView.HitTestResult.PHONE_TYPE);
1735 menu.setGroupVisible(R.id.EMAIL_MENU,
1736 type == WebView.HitTestResult.EMAIL_TYPE);
1737 menu.setGroupVisible(R.id.GEO_MENU,
1738 type == WebView.HitTestResult.GEO_TYPE);
1739 menu.setGroupVisible(R.id.IMAGE_MENU,
1740 type == WebView.HitTestResult.IMAGE_TYPE
1741 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1742 menu.setGroupVisible(R.id.ANCHOR_MENU,
1743 type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1744 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1745
1746 // Setup custom handling depending on the type
1747 switch (type) {
1748 case WebView.HitTestResult.PHONE_TYPE:
1749 menu.setHeaderTitle(Uri.decode(extra));
1750 menu.findItem(R.id.dial_context_menu_id).setIntent(
1751 new Intent(Intent.ACTION_VIEW, Uri
1752 .parse(WebView.SCHEME_TEL + extra)));
1753 Intent addIntent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
1754 addIntent.putExtra(Insert.PHONE, Uri.decode(extra));
Cary Clark5e335a32009-09-22 14:53:11 -04001755 addIntent.setType(ContactsContract.Contacts.CONTENT_ITEM_TYPE);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001756 menu.findItem(R.id.add_contact_context_menu_id).setIntent(
1757 addIntent);
1758 menu.findItem(R.id.copy_phone_context_menu_id).setOnMenuItemClickListener(
1759 new Copy(extra));
1760 break;
1761
1762 case WebView.HitTestResult.EMAIL_TYPE:
1763 menu.setHeaderTitle(extra);
1764 menu.findItem(R.id.email_context_menu_id).setIntent(
1765 new Intent(Intent.ACTION_VIEW, Uri
1766 .parse(WebView.SCHEME_MAILTO + extra)));
1767 menu.findItem(R.id.copy_mail_context_menu_id).setOnMenuItemClickListener(
1768 new Copy(extra));
1769 break;
1770
1771 case WebView.HitTestResult.GEO_TYPE:
1772 menu.setHeaderTitle(extra);
1773 menu.findItem(R.id.map_context_menu_id).setIntent(
1774 new Intent(Intent.ACTION_VIEW, Uri
1775 .parse(WebView.SCHEME_GEO
1776 + URLEncoder.encode(extra))));
1777 menu.findItem(R.id.copy_geo_context_menu_id).setOnMenuItemClickListener(
1778 new Copy(extra));
1779 break;
1780
1781 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1782 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
1783 TextView titleView = (TextView) LayoutInflater.from(this)
1784 .inflate(android.R.layout.browser_link_context_header,
1785 null);
1786 titleView.setText(extra);
1787 menu.setHeaderView(titleView);
1788 // decide whether to show the open link in new tab option
Leon Scroggins III9e997c72010-05-26 13:25:16 -04001789 boolean showNewTab = mTabControl.canCreateNewTab();
1790 MenuItem newTabItem
1791 = menu.findItem(R.id.open_newtab_context_menu_id);
1792 newTabItem.setVisible(showNewTab);
1793 if (showNewTab) {
1794 newTabItem.setOnMenuItemClickListener(
1795 new MenuItem.OnMenuItemClickListener() {
1796 public boolean onMenuItemClick(MenuItem item) {
1797 final Tab parent = mTabControl.getCurrentTab();
Michael Kolb68792c82010-08-09 16:39:18 -07001798 final Tab newTab = openTab(extra, false);
Leon Scroggins III9e997c72010-05-26 13:25:16 -04001799 if (newTab != parent) {
1800 parent.addChildTab(newTab);
1801 }
1802 return true;
1803 }
1804 });
1805 }
Ben Murdochde353622009-10-12 10:29:00 +01001806 menu.findItem(R.id.bookmark_context_menu_id).setVisible(
1807 Bookmarks.urlHasAcceptableScheme(extra));
The Android Open Source Project0c908882009-03-03 19:32:16 -08001808 PackageManager pm = getPackageManager();
1809 Intent send = new Intent(Intent.ACTION_SEND);
1810 send.setType("text/plain");
1811 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1812 menu.findItem(R.id.share_link_context_menu_id).setVisible(ri != null);
1813 if (type == WebView.HitTestResult.SRC_ANCHOR_TYPE) {
1814 break;
1815 }
1816 // otherwise fall through to handle image part
1817 case WebView.HitTestResult.IMAGE_TYPE:
1818 if (type == WebView.HitTestResult.IMAGE_TYPE) {
1819 menu.setHeaderTitle(extra);
1820 }
1821 menu.findItem(R.id.view_image_context_menu_id).setIntent(
1822 new Intent(Intent.ACTION_VIEW, Uri.parse(extra)));
1823 menu.findItem(R.id.download_context_menu_id).
1824 setOnMenuItemClickListener(new Download(extra));
Ben Murdoch4f75ba22009-10-27 11:48:28 +00001825 menu.findItem(R.id.set_wallpaper_context_menu_id).
1826 setOnMenuItemClickListener(new SetAsWallpaper(extra));
The Android Open Source Project0c908882009-03-03 19:32:16 -08001827 break;
1828
1829 default:
1830 Log.w(LOGTAG, "We should not get here.");
1831 break;
1832 }
Leon Scrogginsb2b19f52009-10-09 16:10:00 -04001833 hideFakeTitleBar();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001834 }
1835
The Android Open Source Project0c908882009-03-03 19:32:16 -08001836 // Attach the given tab to the content view.
Grace Klobac928c302009-09-17 11:51:21 -07001837 // this should only be called for the current tab.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001838 private void attachTabToContentView(Tab t) {
Steve Block2bc69912009-07-30 14:45:13 +01001839 // Attach the container that contains the main WebView and any other UI
1840 // associated with the tab.
Patrick Scottd0119532009-09-17 08:00:31 -04001841 t.attachTabToContentView(mContentView);
Ben Murdochbff2d602009-07-01 20:19:05 +01001842
1843 if (mShouldShowErrorConsole) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001844 ErrorConsoleView errorConsole = t.getErrorConsole(true);
Ben Murdochbff2d602009-07-01 20:19:05 +01001845 if (errorConsole.numberOfErrors() == 0) {
1846 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
1847 } else {
1848 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
1849 }
1850
1851 mErrorConsoleContainer.addView(errorConsole,
Romain Guy15b8ec62010-01-08 15:06:43 -08001852 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
Ben Murdochbff2d602009-07-01 20:19:05 +01001853 ViewGroup.LayoutParams.WRAP_CONTENT));
1854 }
1855
Michael Kolba2b2ba82010-08-04 17:54:03 -07001856 WebView view = t.getWebView();
1857 view.setEmbeddedTitleBar(mTitleBar);
Leon Scroggins58d56c62010-01-28 15:12:40 -05001858 if (t.isInVoiceSearchMode()) {
1859 showVoiceTitleBar(t.getVoiceDisplayTitle());
1860 } else {
1861 revertVoiceTitleBar();
1862 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001863 // Request focus on the top window.
1864 t.getTopWindow().requestFocus();
Michael Kolba2b2ba82010-08-04 17:54:03 -07001865 if (mTabControl.getTabChangeListener() != null) {
1866 mTabControl.getTabChangeListener().onCurrentTab(t);
1867 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001868 }
1869
1870 // Attach a sub window to the main WebView of the given tab.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001871 void attachSubWindow(Tab t) {
Patrick Scottd0119532009-09-17 08:00:31 -04001872 t.attachSubWindow(mContentView);
1873 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001874 }
1875
1876 // Remove the given tab from the content view.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001877 private void removeTabFromContentView(Tab t) {
Steve Block2bc69912009-07-30 14:45:13 +01001878 // Remove the container that contains the main WebView.
Patrick Scottd0119532009-09-17 08:00:31 -04001879 t.removeTabFromContentView(mContentView);
Ben Murdochbff2d602009-07-01 20:19:05 +01001880
Grace Kloba22ac16e2009-10-07 18:00:23 -07001881 ErrorConsoleView errorConsole = t.getErrorConsole(false);
1882 if (errorConsole != null) {
1883 mErrorConsoleContainer.removeView(errorConsole);
Ben Murdochbff2d602009-07-01 20:19:05 +01001884 }
1885
Michael Kolba2b2ba82010-08-04 17:54:03 -07001886 WebView view = t.getWebView();
1887 if (view != null) {
1888 view.setEmbeddedTitleBar(null);
Leon Scrogginsbb85b902009-09-14 19:27:20 -04001889 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001890 }
1891
1892 // Remove the sub window if it exists. Also called by TabControl when the
1893 // user clicks the 'X' to dismiss a sub window.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001894 /* package */ void dismissSubWindow(Tab t) {
Patrick Scottd0119532009-09-17 08:00:31 -04001895 t.removeSubWindow(mContentView);
Grace Kloba22ac16e2009-10-07 18:00:23 -07001896 // dismiss the subwindow. This will destroy the WebView.
1897 t.dismissSubWindow();
Patrick Scottd0119532009-09-17 08:00:31 -04001898 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001899 }
1900
Leon Scroggins1f005d32009-08-10 17:36:42 -04001901 // A wrapper function of {@link #openTabAndShow(UrlData, boolean, String)}
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07001902 // that accepts url as string.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001903 private Tab openTabAndShow(String url, boolean closeOnExit, String appId) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001904 return openTabAndShow(new UrlData(url), closeOnExit, appId);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001905 }
1906
1907 // This method does a ton of stuff. It will attempt to create a new tab
1908 // if we haven't reached MAX_TABS. Otherwise it uses the current tab. If
Leon Scroggins1f005d32009-08-10 17:36:42 -04001909 // url isn't null, it will load the given url.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001910 /* package */Tab openTabAndShow(UrlData urlData, boolean closeOnExit,
1911 String appId) {
1912 final Tab currentTab = mTabControl.getCurrentTab();
1913 if (mTabControl.canCreateNewTab()) {
1914 final Tab tab = mTabControl.createNewTab(closeOnExit, appId,
Elliott Slaughterf0f03952010-07-14 18:10:36 -07001915 urlData.mUrl, false);
Leon Scroggins1f005d32009-08-10 17:36:42 -04001916 WebView webview = tab.getWebView();
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001917 // If the last tab was removed from the active tabs page, currentTab
1918 // will be null.
1919 if (currentTab != null) {
1920 removeTabFromContentView(currentTab);
1921 }
Patrick Scott8bbd69f2009-08-14 13:35:53 -04001922 // We must set the new tab as the current tab to reflect the old
1923 // animation behavior.
1924 mTabControl.setCurrentTab(tab);
Grace Klobaeb6eef42009-09-15 17:56:32 -07001925 attachTabToContentView(tab);
Leon Scroggins160a7e72009-08-14 18:28:01 -04001926 if (!urlData.isEmpty()) {
Patrick Scott9d53da02010-02-19 10:19:01 -05001927 loadUrlDataIn(tab, urlData);
Leon Scroggins1f005d32009-08-10 17:36:42 -04001928 }
1929 return tab;
1930 } else {
1931 // Get rid of the subwindow if it exists
1932 dismissSubWindow(currentTab);
1933 if (!urlData.isEmpty()) {
1934 // Load the given url.
Patrick Scott9d53da02010-02-19 10:19:01 -05001935 loadUrlDataIn(currentTab, urlData);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001936 }
Leon Scroggins58d56c62010-01-28 15:12:40 -05001937 return currentTab;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001938 }
1939 }
1940
Michael Kolb68792c82010-08-09 16:39:18 -07001941 private Tab openTab(String url, boolean forceForeground) {
1942 if (mSettings.openInBackground() && !forceForeground) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001943 Tab t = mTabControl.createNewTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001944 if (t != null) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001945 WebView view = t.getWebView();
Leon Scroggins92472e82010-02-17 16:32:28 -05001946 loadUrl(view, url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001947 }
Grace Klobac9181842009-04-14 08:53:22 -07001948 return t;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001949 } else {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001950 return openTabAndShow(url, false, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001951 }
1952 }
1953
Elliott Slaughterf0f03952010-07-14 18:10:36 -07001954 /* package */ Tab openIncognitoTab() {
1955 if (mTabControl.canCreateNewTab()) {
1956 Tab currentTab = mTabControl.getCurrentTab();
1957 Tab tab = mTabControl.createNewTab(false, null, null, true);
1958 if (currentTab != null) {
1959 removeTabFromContentView(currentTab);
1960 }
1961 mTabControl.setCurrentTab(tab);
1962 attachTabToContentView(tab);
1963 return tab;
1964 }
1965 return null;
1966 }
1967
The Android Open Source Project0c908882009-03-03 19:32:16 -08001968 private class Copy implements OnMenuItemClickListener {
1969 private CharSequence mText;
1970
1971 public boolean onMenuItemClick(MenuItem item) {
1972 copy(mText);
1973 return true;
1974 }
1975
1976 public Copy(CharSequence toCopy) {
1977 mText = toCopy;
1978 }
1979 }
1980
1981 private class Download implements OnMenuItemClickListener {
1982 private String mText;
1983
1984 public boolean onMenuItemClick(MenuItem item) {
1985 onDownloadStartNoStream(mText, null, null, null, -1);
1986 return true;
1987 }
1988
1989 public Download(String toDownload) {
1990 mText = toDownload;
1991 }
1992 }
1993
Ben Murdoch4f75ba22009-10-27 11:48:28 +00001994 private class SetAsWallpaper extends Thread implements
1995 OnMenuItemClickListener, DialogInterface.OnCancelListener {
1996 private URL mUrl;
1997 private ProgressDialog mWallpaperProgress;
1998 private boolean mCanceled = false;
1999
2000 public SetAsWallpaper(String url) {
2001 try {
2002 mUrl = new URL(url);
2003 } catch (MalformedURLException e) {
2004 mUrl = null;
2005 }
2006 }
2007
2008 public void onCancel(DialogInterface dialog) {
2009 mCanceled = true;
2010 }
2011
2012 public boolean onMenuItemClick(MenuItem item) {
2013 if (mUrl != null) {
2014 // The user may have tried to set a image with a large file size as their
2015 // background so it may take a few moments to perform the operation. Display
2016 // a progress spinner while it is working.
2017 mWallpaperProgress = new ProgressDialog(BrowserActivity.this);
2018 mWallpaperProgress.setIndeterminate(true);
2019 mWallpaperProgress.setMessage(getText(R.string.progress_dialog_setting_wallpaper));
2020 mWallpaperProgress.setCancelable(true);
2021 mWallpaperProgress.setOnCancelListener(this);
2022 mWallpaperProgress.show();
2023 start();
2024 }
2025 return true;
2026 }
2027
Michael Kolbe0a36662010-06-29 10:37:12 -07002028 @Override
Ben Murdoch4f75ba22009-10-27 11:48:28 +00002029 public void run() {
2030 Drawable oldWallpaper = BrowserActivity.this.getWallpaper();
2031 try {
2032 // TODO: This will cause the resource to be downloaded again, when we
2033 // should in most cases be able to grab it from the cache. To fix this
2034 // we should query WebCore to see if we can access a cached version and
2035 // instead open an input stream on that. This pattern could also be used
2036 // in the download manager where the same problem exists.
2037 InputStream inputstream = mUrl.openStream();
2038 if (inputstream != null) {
2039 setWallpaper(inputstream);
2040 }
2041 } catch (IOException e) {
2042 Log.e(LOGTAG, "Unable to set new wallpaper");
2043 // Act as though the user canceled the operation so we try to
2044 // restore the old wallpaper.
2045 mCanceled = true;
2046 }
2047
2048 if (mCanceled) {
2049 // Restore the old wallpaper if the user cancelled whilst we were setting
2050 // the new wallpaper.
2051 int width = oldWallpaper.getIntrinsicWidth();
2052 int height = oldWallpaper.getIntrinsicHeight();
2053 Bitmap bm = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
2054 Canvas canvas = new Canvas(bm);
2055 oldWallpaper.setBounds(0, 0, width, height);
2056 oldWallpaper.draw(canvas);
2057 try {
2058 setWallpaper(bm);
2059 } catch (IOException e) {
2060 Log.e(LOGTAG, "Unable to restore old wallpaper.");
2061 }
2062 mCanceled = false;
2063 }
2064
2065 if (mWallpaperProgress.isShowing()) {
2066 mWallpaperProgress.dismiss();
2067 }
2068 }
2069 }
2070
The Android Open Source Project0c908882009-03-03 19:32:16 -08002071 private void copy(CharSequence text) {
Dianne Hackborn80f32622010-08-05 14:17:53 -07002072 ClipboardManager cm = (ClipboardManager)getSystemService(Context.CLIPBOARD_SERVICE);
2073 cm.setText(text);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002074 }
2075
2076 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08002077 * Resets the browser title-view to whatever it must be
2078 * (for example, if we had a loading error)
2079 * When we have a new page, we call resetTitle, when we
2080 * have to reset the titlebar to whatever it used to be
2081 * (for example, if the user chose to stop loading), we
2082 * call resetTitleAndRevertLockIcon.
2083 */
2084 /* package */ void resetTitleAndRevertLockIcon() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002085 mTabControl.getCurrentTab().revertLockIcon();
2086 updateLockIconToLatest();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002087 resetTitleIconAndProgress();
2088 }
2089
2090 /**
2091 * Reset the title, favicon, and progress.
2092 */
2093 private void resetTitleIconAndProgress() {
2094 WebView current = mTabControl.getCurrentWebView();
2095 if (current == null) {
2096 return;
2097 }
2098 resetTitleAndIcon(current);
2099 int progress = current.getProgress();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002100 current.getWebChromeClient().onProgressChanged(current, progress);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002101 }
2102
2103 // Reset the title and the icon based on the given item.
2104 private void resetTitleAndIcon(WebView view) {
2105 WebHistoryItem item = view.copyBackForwardList().getCurrentItem();
2106 if (item != null) {
Leon Scroggins68579392009-09-15 15:31:54 -04002107 setUrlTitle(item.getUrl(), item.getTitle());
The Android Open Source Project0c908882009-03-03 19:32:16 -08002108 setFavicon(item.getFavicon());
2109 } else {
Leon Scroggins68579392009-09-15 15:31:54 -04002110 setUrlTitle(null, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002111 setFavicon(null);
2112 }
2113 }
2114
2115 /**
2116 * Sets a title composed of the URL and the title string.
2117 * @param url The URL of the site being loaded.
2118 * @param title The title of the site being loaded.
2119 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07002120 void setUrlTitle(String url, String title) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002121 mUrl = url;
2122 mTitle = title;
2123
Leon Scroggins58d56c62010-01-28 15:12:40 -05002124 // If we are in voice search mode, the title has already been set.
2125 if (mTabControl.getCurrentTab().isInVoiceSearchMode()) return;
2126 mTitleBar.setDisplayTitle(url);
Michael Kolba2b2ba82010-08-04 17:54:03 -07002127 mFakeTitleBar.setDisplayTitle(url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002128 }
2129
2130 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08002131 * @param url The URL to build a title version of the URL from.
2132 * @return The title version of the URL or null if fails.
2133 * The title version of the URL can be either the URL hostname,
2134 * or the hostname with an "https://" prefix (for secure URLs),
2135 * or an empty string if, for example, the URL in question is a
2136 * file:// URL with no hostname.
2137 */
Leon Scroggins32e14a62009-06-11 10:26:34 -04002138 /* package */ static String buildTitleUrl(String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002139 String titleUrl = null;
2140
2141 if (url != null) {
2142 try {
2143 // parse the url string
2144 URL urlObj = new URL(url);
2145 if (urlObj != null) {
2146 titleUrl = "";
2147
2148 String protocol = urlObj.getProtocol();
2149 String host = urlObj.getHost();
2150
2151 if (host != null && 0 < host.length()) {
2152 titleUrl = host;
2153 if (protocol != null) {
2154 // if a secure site, add an "https://" prefix!
2155 if (protocol.equalsIgnoreCase("https")) {
2156 titleUrl = protocol + "://" + host;
2157 }
2158 }
2159 }
2160 }
2161 } catch (MalformedURLException e) {}
2162 }
2163
2164 return titleUrl;
2165 }
2166
2167 // Set the favicon in the title bar.
Grace Kloba22ac16e2009-10-07 18:00:23 -07002168 void setFavicon(Bitmap icon) {
Leon Scroggins68579392009-09-15 15:31:54 -04002169 mTitleBar.setFavicon(icon);
Michael Kolba2b2ba82010-08-04 17:54:03 -07002170 mFakeTitleBar.setFavicon(icon);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002171 }
2172
2173 /**
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002174 * Close the tab, remove its associated title bar, and adjust mTabControl's
2175 * current tab to a valid value.
Leon Scroggins1f005d32009-08-10 17:36:42 -04002176 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07002177 /* package */ void closeTab(Tab t) {
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002178 int currentIndex = mTabControl.getCurrentIndex();
2179 int removeIndex = mTabControl.getTabIndex(t);
Leon Scroggins1f005d32009-08-10 17:36:42 -04002180 mTabControl.removeTab(t);
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002181 if (currentIndex >= removeIndex && currentIndex != 0) {
2182 currentIndex--;
2183 }
2184 mTabControl.setCurrentTab(mTabControl.getTab(currentIndex));
Andrei Popescua5bf1de2009-09-23 16:39:23 +01002185 resetTitleIconAndProgress();
Leon Scroggins654899b2010-06-25 16:25:23 -04002186 updateLockIconToLatest();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002187 }
2188
Leon Scrogginsdcc5eeb2010-02-23 17:26:37 -05002189 /* package */ void goBackOnePageOrQuit() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002190 Tab current = mTabControl.getCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002191 if (current == null) {
2192 /*
2193 * Instead of finishing the activity, simply push this to the back
2194 * of the stack and let ActivityManager to choose the foreground
2195 * activity. As BrowserActivity is singleTask, it will be always the
2196 * root of the task. So we can use either true or false for
2197 * moveTaskToBack().
2198 */
2199 moveTaskToBack(true);
Grace Kloba00d85e72009-09-23 18:50:05 -07002200 return;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002201 }
2202 WebView w = current.getWebView();
2203 if (w.canGoBack()) {
2204 w.goBack();
2205 } else {
2206 // Check to see if we are closing a window that was created by
2207 // another window. If so, we switch back to that window.
Grace Kloba22ac16e2009-10-07 18:00:23 -07002208 Tab parent = current.getParentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002209 if (parent != null) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04002210 switchToTab(mTabControl.getTabIndex(parent));
2211 // Now we close the other tab
2212 closeTab(current);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002213 } else {
2214 if (current.closeOnExit()) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002215 // force the tab's inLoad() to be false as we are going to
2216 // either finish the activity or remove the tab. This will
2217 // ensure pauseWebViewTimers() taking action.
2218 mTabControl.getCurrentTab().clearInLoad();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002219 if (mTabControl.getTabCount() == 1) {
2220 finish();
2221 return;
2222 }
Mike Reed7bfa63b2009-05-28 11:08:32 -04002223 // call pauseWebViewTimers() now, we won't be able to call
2224 // it in onPause() as the WebView won't be valid.
Grace Klobaec1b5ad2009-08-18 08:42:32 -07002225 // Temporarily change mActivityInPause to be true as
2226 // pauseWebViewTimers() will do nothing if mActivityInPause
2227 // is false.
Grace Kloba918e1d72009-08-13 14:55:06 -07002228 boolean savedState = mActivityInPause;
2229 if (savedState) {
Grace Klobaec1b5ad2009-08-18 08:42:32 -07002230 Log.e(LOGTAG, "BrowserActivity is already paused "
2231 + "while handing goBackOnePageOrQuit.");
Grace Kloba918e1d72009-08-13 14:55:06 -07002232 }
2233 mActivityInPause = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -04002234 pauseWebViewTimers();
Grace Kloba918e1d72009-08-13 14:55:06 -07002235 mActivityInPause = savedState;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002236 removeTabFromContentView(current);
2237 mTabControl.removeTab(current);
2238 }
2239 /*
2240 * Instead of finishing the activity, simply push this to the back
2241 * of the stack and let ActivityManager to choose the foreground
2242 * activity. As BrowserActivity is singleTask, it will be always the
2243 * root of the task. So we can use either true or false for
2244 * moveTaskToBack().
2245 */
2246 moveTaskToBack(true);
2247 }
2248 }
2249 }
2250
Grace Kloba22ac16e2009-10-07 18:00:23 -07002251 boolean isMenuDown() {
2252 return mMenuIsDown;
2253 }
2254
Grace Kloba5942df02009-09-18 11:48:29 -07002255 @Override
2256 public boolean onKeyDown(int keyCode, KeyEvent event) {
Leon Scrogginsf65b50d2009-12-08 10:44:28 -05002257 // Even if MENU is already held down, we need to call to super to open
2258 // the IME on long press.
2259 if (KeyEvent.KEYCODE_MENU == keyCode) {
2260 mMenuIsDown = true;
2261 return super.onKeyDown(keyCode, event);
2262 }
Grace Kloba5942df02009-09-18 11:48:29 -07002263 // The default key mode is DEFAULT_KEYS_SEARCH_LOCAL. As the MENU is
2264 // still down, we don't want to trigger the search. Pretend to consume
2265 // the key and do nothing.
2266 if (mMenuIsDown) return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002267
Grace Kloba5942df02009-09-18 11:48:29 -07002268 switch(keyCode) {
Grace Kloba5942df02009-09-18 11:48:29 -07002269 case KeyEvent.KEYCODE_SPACE:
Grace Klobada0fe552009-09-22 18:17:24 -07002270 // WebView/WebTextView handle the keys in the KeyDown. As
2271 // the Activity's shortcut keys are only handled when WebView
2272 // doesn't, have to do it in onKeyDown instead of onKeyUp.
2273 if (event.isShiftPressed()) {
2274 getTopWindow().pageUp(false);
2275 } else {
2276 getTopWindow().pageDown(false);
2277 }
Grace Kloba5942df02009-09-18 11:48:29 -07002278 return true;
2279 case KeyEvent.KEYCODE_BACK:
2280 if (event.getRepeatCount() == 0) {
2281 event.startTracking();
2282 return true;
2283 } else if (mCustomView == null && mActiveTabsPage == null
2284 && event.isLongPress()) {
Michael Kolb68792c82010-08-09 16:39:18 -07002285 bookmarksOrHistoryPicker(true, false);
Grace Kloba5942df02009-09-18 11:48:29 -07002286 return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002287 }
Grace Kloba5942df02009-09-18 11:48:29 -07002288 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002289 }
Grace Kloba5942df02009-09-18 11:48:29 -07002290 return super.onKeyDown(keyCode, event);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002291 }
2292
Grace Kloba5942df02009-09-18 11:48:29 -07002293 @Override
2294 public boolean onKeyUp(int keyCode, KeyEvent event) {
2295 switch(keyCode) {
2296 case KeyEvent.KEYCODE_MENU:
2297 mMenuIsDown = false;
2298 break;
Grace Kloba5942df02009-09-18 11:48:29 -07002299 case KeyEvent.KEYCODE_BACK:
2300 if (event.isTracking() && !event.isCanceled()) {
2301 if (mCustomView != null) {
2302 // if a custom view is showing, hide it
Grace Kloba22ac16e2009-10-07 18:00:23 -07002303 mTabControl.getCurrentWebView().getWebChromeClient()
2304 .onHideCustomView();
Grace Kloba5942df02009-09-18 11:48:29 -07002305 } else if (mActiveTabsPage != null) {
2306 // if tab page is showing, hide it
2307 removeActiveTabPage(true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002308 } else {
Grace Kloba5942df02009-09-18 11:48:29 -07002309 WebView subwindow = mTabControl.getCurrentSubWindow();
2310 if (subwindow != null) {
2311 if (subwindow.canGoBack()) {
2312 subwindow.goBack();
2313 } else {
2314 dismissSubWindow(mTabControl.getCurrentTab());
2315 }
2316 } else {
2317 goBackOnePageOrQuit();
2318 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002319 }
Grace Kloba5942df02009-09-18 11:48:29 -07002320 return true;
2321 }
2322 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002323 }
Grace Kloba5942df02009-09-18 11:48:29 -07002324 return super.onKeyUp(keyCode, event);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002325 }
2326
Leon Scroggins68579392009-09-15 15:31:54 -04002327 /* package */ void stopLoading() {
Ben Murdochb7cc8b42009-09-28 10:59:09 +01002328 mDidStopLoad = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002329 resetTitleAndRevertLockIcon();
2330 WebView w = getTopWindow();
2331 w.stopLoading();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002332 // FIXME: before refactor, it is using mWebViewClient. So I keep the
2333 // same logic here. But for subwindow case, should we call into the main
2334 // WebView's onPageFinished as we never call its onPageStarted and if
2335 // the page finishes itself, we don't call onPageFinished.
2336 mTabControl.getCurrentWebView().getWebViewClient().onPageFinished(w,
2337 w.getUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08002338
2339 cancelStopToast();
2340 mStopToast = Toast
2341 .makeText(this, R.string.stopping, Toast.LENGTH_SHORT);
2342 mStopToast.show();
2343 }
2344
Grace Kloba22ac16e2009-10-07 18:00:23 -07002345 boolean didUserStopLoading() {
2346 return mDidStopLoad;
2347 }
2348
The Android Open Source Project0c908882009-03-03 19:32:16 -08002349 private void cancelStopToast() {
2350 if (mStopToast != null) {
2351 mStopToast.cancel();
2352 mStopToast = null;
2353 }
2354 }
2355
Grace Kloba22ac16e2009-10-07 18:00:23 -07002356 // called by a UI or non-UI thread to post the message
2357 public void postMessage(int what, int arg1, int arg2, Object obj,
2358 long delayMillis) {
2359 mHandler.sendMessageDelayed(mHandler.obtainMessage(what, arg1, arg2,
2360 obj), delayMillis);
2361 }
2362
2363 // called by a UI or non-UI thread to remove the message
2364 void removeMessages(int what, Object object) {
2365 mHandler.removeMessages(what, object);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002366 }
2367
2368 // public message ids
2369 public final static int LOAD_URL = 1001;
2370 public final static int STOP_LOAD = 1002;
2371
2372 // Message Ids
2373 private static final int FOCUS_NODE_HREF = 102;
Grace Kloba92c18a52009-07-31 23:48:32 -07002374 private static final int RELEASE_WAKELOCK = 107;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002375
Grace Kloba22ac16e2009-10-07 18:00:23 -07002376 static final int UPDATE_BOOKMARK_THUMBNAIL = 108;
Ben Murdoch2694e232009-09-29 09:41:11 +01002377
Ben Murdocheecb4e62010-07-06 16:30:38 +01002378 private static final int TOUCH_ICON_DOWNLOADED = 109;
2379
The Android Open Source Project0c908882009-03-03 19:32:16 -08002380 // Private handler for handling javascript and saving passwords
2381 private Handler mHandler = new Handler() {
2382
Michael Kolbe0a36662010-06-29 10:37:12 -07002383 @Override
The Android Open Source Project0c908882009-03-03 19:32:16 -08002384 public void handleMessage(Message msg) {
2385 switch (msg.what) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002386 case FOCUS_NODE_HREF:
Ben Murdoch2694e232009-09-29 09:41:11 +01002387 {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002388 String url = (String) msg.getData().get("url");
Ben Murdoch90d088c2009-11-17 18:14:04 +00002389 String title = (String) msg.getData().get("title");
The Android Open Source Project0c908882009-03-03 19:32:16 -08002390 if (url == null || url.length() == 0) {
2391 break;
2392 }
2393 HashMap focusNodeMap = (HashMap) msg.obj;
2394 WebView view = (WebView) focusNodeMap.get("webview");
2395 // Only apply the action if the top window did not change.
2396 if (getTopWindow() != view) {
2397 break;
2398 }
2399 switch (msg.arg1) {
2400 case R.id.open_context_menu_id:
2401 case R.id.view_image_context_menu_id:
Leon Scroggins92472e82010-02-17 16:32:28 -05002402 loadUrlFromContext(getTopWindow(), url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002403 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002404 case R.id.bookmark_context_menu_id:
2405 Intent intent = new Intent(BrowserActivity.this,
2406 AddBookmarkPage.class);
2407 intent.putExtra("url", url);
Ben Murdoch90d088c2009-11-17 18:14:04 +00002408 intent.putExtra("title", title);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002409 startActivity(intent);
2410 break;
2411 case R.id.share_link_context_menu_id:
Leon Scroggins3e204452010-05-10 11:06:03 -04002412 sharePage(BrowserActivity.this, title, url, null,
Leon Scroggins96afcb12009-12-10 12:35:56 -05002413 null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002414 break;
2415 case R.id.copy_link_context_menu_id:
2416 copy(url);
2417 break;
2418 case R.id.save_link_context_menu_id:
2419 case R.id.download_context_menu_id:
2420 onDownloadStartNoStream(url, null, null, null, -1);
2421 break;
2422 }
2423 break;
Ben Murdoch2694e232009-09-29 09:41:11 +01002424 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002425
2426 case LOAD_URL:
Leon Scroggins92472e82010-02-17 16:32:28 -05002427 loadUrlFromContext(getTopWindow(), (String) msg.obj);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002428 break;
2429
2430 case STOP_LOAD:
2431 stopLoading();
2432 break;
2433
The Android Open Source Project0c908882009-03-03 19:32:16 -08002434 case RELEASE_WAKELOCK:
2435 if (mWakeLock.isHeld()) {
2436 mWakeLock.release();
Grace Kloba5d0e02e2009-10-05 15:15:36 -07002437 // if we reach here, Browser should be still in the
2438 // background loading after WAKELOCK_TIMEOUT (5-min).
2439 // To avoid burning the battery, stop loading.
2440 mTabControl.stopAllLoading();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002441 }
2442 break;
Ben Murdoch2694e232009-09-29 09:41:11 +01002443
2444 case UPDATE_BOOKMARK_THUMBNAIL:
2445 WebView view = (WebView) msg.obj;
2446 if (view != null) {
2447 updateScreenshot(view);
2448 }
2449 break;
Ben Murdocheecb4e62010-07-06 16:30:38 +01002450
2451 case TOUCH_ICON_DOWNLOADED:
2452 Bundle b = msg.getData();
2453 showSaveToHomescreenDialog(b.getString("url"),
2454 b.getString("title"),
2455 (Bitmap) b.getParcelable("touchIcon"),
2456 (Bitmap) b.getParcelable("favicon"));
2457 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002458 }
2459 }
2460 };
2461
Leon Scroggins96afcb12009-12-10 12:35:56 -05002462 /**
2463 * Share a page, providing the title, url, favicon, and a screenshot. Uses
2464 * an {@link Intent} to launch the Activity chooser.
2465 * @param c Context used to launch a new Activity.
2466 * @param title Title of the page. Stored in the Intent with
Paul Westbrook03e6d392010-02-12 10:33:29 -08002467 * {@link Intent#EXTRA_SUBJECT}
Leon Scroggins96afcb12009-12-10 12:35:56 -05002468 * @param url URL of the page. Stored in the Intent with
2469 * {@link Intent#EXTRA_TEXT}
2470 * @param favicon Bitmap of the favicon for the page. Stored in the Intent
2471 * with {@link Browser#EXTRA_SHARE_FAVICON}
2472 * @param screenshot Bitmap of a screenshot of the page. Stored in the
2473 * Intent with {@link Browser#EXTRA_SHARE_SCREENSHOT}
2474 */
2475 public static final void sharePage(Context c, String title, String url,
2476 Bitmap favicon, Bitmap screenshot) {
2477 Intent send = new Intent(Intent.ACTION_SEND);
2478 send.setType("text/plain");
2479 send.putExtra(Intent.EXTRA_TEXT, url);
Paul Westbrook03e6d392010-02-12 10:33:29 -08002480 send.putExtra(Intent.EXTRA_SUBJECT, title);
Leon Scroggins96afcb12009-12-10 12:35:56 -05002481 send.putExtra(Browser.EXTRA_SHARE_FAVICON, favicon);
2482 send.putExtra(Browser.EXTRA_SHARE_SCREENSHOT, screenshot);
2483 try {
2484 c.startActivity(Intent.createChooser(send, c.getString(
2485 R.string.choosertitle_sharevia)));
2486 } catch(android.content.ActivityNotFoundException ex) {
2487 // if no app handles it, do nothing
2488 }
2489 }
2490
Leon Scroggins89c6d362009-07-15 16:54:37 -04002491 private void updateScreenshot(WebView view) {
2492 // If this is a bookmarked site, add a screenshot to the database.
2493 // FIXME: When should we update? Every time?
2494 // FIXME: Would like to make sure there is actually something to
2495 // draw, but the API for that (WebViewCore.pictureReady()) is not
2496 // currently accessible here.
Ben Murdochaac7aa62009-09-17 16:57:40 +01002497
Ben Murdoch87cc65d2010-06-29 20:34:10 +01002498 final Bitmap bm = createScreenshot(view, getDesiredThumbnailWidth(this),
2499 getDesiredThumbnailHeight(this));
Patrick Scottcb192b52010-04-14 14:38:55 -04002500 if (bm == null) {
2501 return;
Leon Scroggins89c6d362009-07-15 16:54:37 -04002502 }
Patrick Scottcb192b52010-04-14 14:38:55 -04002503
2504 final ContentResolver cr = getContentResolver();
2505 final String url = view.getUrl();
2506 final String originalUrl = view.getOriginalUrl();
2507
2508 new AsyncTask<Void, Void, Void>() {
2509 @Override
2510 protected Void doInBackground(Void... unused) {
2511 Cursor c = null;
2512 try {
Jeff Hamilton84029622010-08-05 14:29:28 -05002513 c = Bookmarks.queryBookmarksForUrl(
Jeff Hamilton8ce956c2010-08-17 11:13:53 -05002514 cr, originalUrl, url);
Patrick Scottcb192b52010-04-14 14:38:55 -04002515 if (c != null) {
2516 if (c.moveToFirst()) {
2517 ContentValues values = new ContentValues();
2518 final ByteArrayOutputStream os
2519 = new ByteArrayOutputStream();
2520 bm.compress(Bitmap.CompressFormat.PNG, 100, os);
Jeff Hamilton8ce956c2010-08-17 11:13:53 -05002521 values.put(BrowserContract.Bookmarks.THUMBNAIL,
Patrick Scottcb192b52010-04-14 14:38:55 -04002522 os.toByteArray());
2523 do {
2524 cr.update(ContentUris.withAppendedId(
Jeff Hamilton8ce956c2010-08-17 11:13:53 -05002525 BrowserContract.Bookmarks.CONTENT_URI, c.getLong(0)),
Patrick Scottcb192b52010-04-14 14:38:55 -04002526 values, null, null);
2527 } while (c.moveToNext());
2528 }
2529 }
2530 } catch (IllegalStateException e) {
2531 // Ignore
2532 } finally {
2533 if (c != null) c.close();
2534 }
2535 return null;
2536 }
2537 }.execute();
Leon Scroggins89c6d362009-07-15 16:54:37 -04002538 }
2539
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002540 /**
Leon Scrogginsf8551612009-09-24 16:06:02 -04002541 * Values for the size of the thumbnail created when taking a screenshot.
2542 * Lazily initialized. Instead of using these directly, use
2543 * getDesiredThumbnailWidth() or getDesiredThumbnailHeight().
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002544 */
Leon Scrogginsf8551612009-09-24 16:06:02 -04002545 private static int THUMBNAIL_WIDTH = 0;
2546 private static int THUMBNAIL_HEIGHT = 0;
2547
2548 /**
2549 * Return the desired width for thumbnail screenshots, which are stored in
2550 * the database, and used on the bookmarks screen.
2551 * @param context Context for finding out the density of the screen.
2552 * @return int desired width for thumbnail screenshot.
2553 */
2554 /* package */ static int getDesiredThumbnailWidth(Context context) {
2555 if (THUMBNAIL_WIDTH == 0) {
2556 float density = context.getResources().getDisplayMetrics().density;
2557 THUMBNAIL_WIDTH = (int) (90 * density);
2558 THUMBNAIL_HEIGHT = (int) (80 * density);
2559 }
2560 return THUMBNAIL_WIDTH;
2561 }
2562
2563 /**
2564 * Return the desired height for thumbnail screenshots, which are stored in
2565 * the database, and used on the bookmarks screen.
2566 * @param context Context for finding out the density of the screen.
2567 * @return int desired height for thumbnail screenshot.
2568 */
2569 /* package */ static int getDesiredThumbnailHeight(Context context) {
2570 // To ensure that they are both initialized.
2571 getDesiredThumbnailWidth(context);
2572 return THUMBNAIL_HEIGHT;
2573 }
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002574
Ben Murdoch87cc65d2010-06-29 20:34:10 +01002575 private Bitmap createScreenshot(WebView view, int width, int height) {
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002576 Picture thumbnail = view.capturePicture();
Leon Scroggins45800572009-09-29 16:38:47 -04002577 if (thumbnail == null) {
2578 return null;
2579 }
Ben Murdoch87cc65d2010-06-29 20:34:10 +01002580 Bitmap bm = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002581 Canvas canvas = new Canvas(bm);
2582 // May need to tweak these values to determine what is the
2583 // best scale factor
Ben Murdoch2694e232009-09-29 09:41:11 +01002584 int thumbnailWidth = thumbnail.getWidth();
Ben Murdochae59c3f2009-10-20 18:30:28 +01002585 int thumbnailHeight = thumbnail.getHeight();
2586 float scaleFactorX = 1.0f;
2587 float scaleFactorY = 1.0f;
Ben Murdoch2694e232009-09-29 09:41:11 +01002588 if (thumbnailWidth > 0) {
Ben Murdoch87cc65d2010-06-29 20:34:10 +01002589 scaleFactorX = (float) width / (float)thumbnailWidth;
Ben Murdochae59c3f2009-10-20 18:30:28 +01002590 } else {
2591 return null;
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002592 }
Ben Murdochae59c3f2009-10-20 18:30:28 +01002593
2594 if (view.getWidth() > view.getHeight() &&
2595 thumbnailHeight < view.getHeight() && thumbnailHeight > 0) {
2596 // If the device is in landscape and the page is shorter
2597 // than the height of the view, stretch the thumbnail to fill the
2598 // space.
Ben Murdoch87cc65d2010-06-29 20:34:10 +01002599 scaleFactorY = (float) height / (float)thumbnailHeight;
Ben Murdochae59c3f2009-10-20 18:30:28 +01002600 } else {
2601 // In the portrait case, this looks nice.
2602 scaleFactorY = scaleFactorX;
2603 }
2604
2605 canvas.scale(scaleFactorX, scaleFactorY);
2606
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002607 thumbnail.draw(canvas);
2608 return bm;
2609 }
2610
The Android Open Source Project0c908882009-03-03 19:32:16 -08002611 // -------------------------------------------------------------------------
Grace Kloba22ac16e2009-10-07 18:00:23 -07002612 // Helper function for WebViewClient.
The Android Open Source Project0c908882009-03-03 19:32:16 -08002613 //-------------------------------------------------------------------------
2614
2615 // Use in overrideUrlLoading
2616 /* package */ final static String SCHEME_WTAI = "wtai://wp/";
2617 /* package */ final static String SCHEME_WTAI_MC = "wtai://wp/mc;";
2618 /* package */ final static String SCHEME_WTAI_SD = "wtai://wp/sd;";
2619 /* package */ final static String SCHEME_WTAI_AP = "wtai://wp/ap;";
2620
Leon Scroggins92472e82010-02-17 16:32:28 -05002621 // Keep this initial progress in sync with initialProgressValue (* 100)
2622 // in ProgressTracker.cpp
2623 private final static int INITIAL_PROGRESS = 10;
2624
Grace Kloba22ac16e2009-10-07 18:00:23 -07002625 void onPageStarted(WebView view, String url, Bitmap favicon) {
2626 // when BrowserActivity just starts, onPageStarted may be called before
2627 // onResume as it is triggered from onCreate. Call resumeWebViewTimers
2628 // to start the timer. As we won't switch tabs while an activity is in
2629 // pause state, we can ensure calling resume and pause in pair.
2630 if (mActivityInPause) resumeWebViewTimers();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002631
Grace Kloba22ac16e2009-10-07 18:00:23 -07002632 resetLockIcon(url);
2633 setUrlTitle(url, null);
2634 setFavicon(favicon);
Leon Scroggins8cf8f682009-11-04 11:13:50 -08002635 // Show some progress so that the user knows the page is beginning to
2636 // load
Leon Scroggins92472e82010-02-17 16:32:28 -05002637 onProgressChanged(view, INITIAL_PROGRESS);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002638 mDidStopLoad = false;
Grace Kloba22ac16e2009-10-07 18:00:23 -07002639 if (!mIsNetworkUp) createAndShowNetworkDialog();
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04002640 endActionMode();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002641 if (mSettings.isTracing()) {
2642 String host;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002643 try {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002644 WebAddress uri = new WebAddress(url);
2645 host = uri.mHost;
2646 } catch (android.net.ParseException ex) {
2647 host = "browser";
The Android Open Source Project0c908882009-03-03 19:32:16 -08002648 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002649 host = host.replace('.', '_');
2650 host += ".trace";
2651 mInTrace = true;
2652 Debug.startMethodTracing(host, 20 * 1024 * 1024);
2653 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002654
Grace Kloba22ac16e2009-10-07 18:00:23 -07002655 // Performance probe
2656 if (false) {
2657 mStart = SystemClock.uptimeMillis();
2658 mProcessStart = Process.getElapsedCpuTime();
2659 long[] sysCpu = new long[7];
2660 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2661 sysCpu, null)) {
2662 mUserStart = sysCpu[0] + sysCpu[1];
2663 mSystemStart = sysCpu[2];
2664 mIdleStart = sysCpu[3];
2665 mIrqStart = sysCpu[4] + sysCpu[5] + sysCpu[6];
2666 }
2667 mUiStart = SystemClock.currentThreadTimeMillis();
2668 }
2669 }
2670
2671 void onPageFinished(WebView view, String url) {
2672 // Reset the title and icon in case we stopped a provisional load.
2673 resetTitleAndIcon(view);
2674 // Update the lock icon image only once we are done loading
2675 updateLockIconToLatest();
2676 // pause the WebView timer and release the wake lock if it is finished
2677 // while BrowserActivity is in pause state.
2678 if (mActivityInPause && pauseWebViewTimers()) {
2679 if (mWakeLock.isHeld()) {
2680 mHandler.removeMessages(RELEASE_WAKELOCK);
2681 mWakeLock.release();
2682 }
2683 }
2684
2685 // Performance probe
2686 if (false) {
2687 long[] sysCpu = new long[7];
2688 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2689 sysCpu, null)) {
2690 String uiInfo = "UI thread used "
2691 + (SystemClock.currentThreadTimeMillis() - mUiStart)
2692 + " ms";
2693 if (LOGD_ENABLED) {
2694 Log.d(LOGTAG, uiInfo);
2695 }
2696 //The string that gets written to the log
2697 String performanceString = "It took total "
2698 + (SystemClock.uptimeMillis() - mStart)
2699 + " ms clock time to load the page."
2700 + "\nbrowser process used "
2701 + (Process.getElapsedCpuTime() - mProcessStart)
2702 + " ms, user processes used "
2703 + (sysCpu[0] + sysCpu[1] - mUserStart) * 10
2704 + " ms, kernel used "
2705 + (sysCpu[2] - mSystemStart) * 10
2706 + " ms, idle took " + (sysCpu[3] - mIdleStart) * 10
2707 + " ms and irq took "
2708 + (sysCpu[4] + sysCpu[5] + sysCpu[6] - mIrqStart)
2709 * 10 + " ms, " + uiInfo;
2710 if (LOGD_ENABLED) {
2711 Log.d(LOGTAG, performanceString + "\nWebpage: " + url);
2712 }
2713 if (url != null) {
2714 // strip the url to maintain consistency
2715 String newUrl = new String(url);
2716 if (newUrl.startsWith("http://www.")) {
2717 newUrl = newUrl.substring(11);
2718 } else if (newUrl.startsWith("http://")) {
2719 newUrl = newUrl.substring(7);
2720 } else if (newUrl.startsWith("https://www.")) {
2721 newUrl = newUrl.substring(12);
2722 } else if (newUrl.startsWith("https://")) {
2723 newUrl = newUrl.substring(8);
2724 }
2725 if (LOGD_ENABLED) {
2726 Log.d(LOGTAG, newUrl + " loaded");
2727 }
Grace Kloba5b078b52009-06-24 20:23:41 -07002728 }
2729 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002730 }
Grace Kloba5b078b52009-06-24 20:23:41 -07002731
Grace Kloba22ac16e2009-10-07 18:00:23 -07002732 if (mInTrace) {
2733 mInTrace = false;
2734 Debug.stopMethodTracing();
2735 }
2736 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002737
Grace Klobae7fe26b2010-06-28 16:23:33 -07002738 private void closeEmptyChildTab() {
2739 Tab current = mTabControl.getCurrentTab();
2740 if (current != null
2741 && current.getWebView().copyBackForwardList().getSize() == 0) {
2742 Tab parent = current.getParentTab();
2743 if (parent != null) {
2744 switchToTab(mTabControl.getTabIndex(parent));
2745 closeTab(current);
2746 }
2747 }
2748 }
2749
Grace Kloba22ac16e2009-10-07 18:00:23 -07002750 boolean shouldOverrideUrlLoading(WebView view, String url) {
2751 if (url.startsWith(SCHEME_WTAI)) {
2752 // wtai://wp/mc;number
2753 // number=string(phone-number)
2754 if (url.startsWith(SCHEME_WTAI_MC)) {
2755 Intent intent = new Intent(Intent.ACTION_VIEW,
2756 Uri.parse(WebView.SCHEME_TEL +
2757 url.substring(SCHEME_WTAI_MC.length())));
2758 startActivity(intent);
Grace Klobae7fe26b2010-06-28 16:23:33 -07002759 // before leaving BrowserActivity, close the empty child tab.
2760 // If a new tab is created through JavaScript open to load this
2761 // url, we would like to close it as we will load this url in a
2762 // different Activity.
2763 closeEmptyChildTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002764 return true;
2765 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002766 // wtai://wp/sd;dtmf
2767 // dtmf=string(dialstring)
2768 if (url.startsWith(SCHEME_WTAI_SD)) {
2769 // TODO: only send when there is active voice connection
2770 return false;
2771 }
2772 // wtai://wp/ap;number;name
2773 // number=string(phone-number)
2774 // name=string
2775 if (url.startsWith(SCHEME_WTAI_AP)) {
2776 // TODO
2777 return false;
2778 }
2779 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002780
Grace Kloba22ac16e2009-10-07 18:00:23 -07002781 // The "about:" schemes are internal to the browser; don't want these to
2782 // be dispatched to other apps.
2783 if (url.startsWith("about:")) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002784 return false;
2785 }
2786
Grace Kloba22ac16e2009-10-07 18:00:23 -07002787 Intent intent;
2788 // perform generic parsing of the URI to turn it into an Intent.
2789 try {
2790 intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME);
2791 } catch (URISyntaxException ex) {
2792 Log.w("Browser", "Bad URI " + url + ": " + ex.getMessage());
2793 return false;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002794 }
2795
Grace Kloba22ac16e2009-10-07 18:00:23 -07002796 // check whether the intent can be resolved. If not, we will see
2797 // whether we can download it from the Market.
2798 if (getPackageManager().resolveActivity(intent, 0) == null) {
2799 String packagename = intent.getPackage();
2800 if (packagename != null) {
2801 intent = new Intent(Intent.ACTION_VIEW, Uri
2802 .parse("market://search?q=pname:" + packagename));
2803 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2804 startActivity(intent);
Grace Klobae7fe26b2010-06-28 16:23:33 -07002805 // before leaving BrowserActivity, close the empty child tab.
2806 // If a new tab is created through JavaScript open to load this
2807 // url, we would like to close it as we will load this url in a
2808 // different Activity.
2809 closeEmptyChildTab();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002810 return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002811 } else {
2812 return false;
2813 }
2814 }
2815
Grace Kloba22ac16e2009-10-07 18:00:23 -07002816 // sanitize the Intent, ensuring web pages can not bypass browser
2817 // security (only access to BROWSABLE activities).
2818 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2819 intent.setComponent(null);
2820 try {
2821 if (startActivityIfNeeded(intent, -1)) {
Grace Klobae7fe26b2010-06-28 16:23:33 -07002822 // before leaving BrowserActivity, close the empty child tab.
2823 // If a new tab is created through JavaScript open to load this
2824 // url, we would like to close it as we will load this url in a
2825 // different Activity.
2826 closeEmptyChildTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002827 return true;
2828 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002829 } catch (ActivityNotFoundException ex) {
2830 // ignore the error. If no application can handle the URL,
2831 // eg about:blank, assume the browser can handle it.
2832 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002833
Grace Kloba22ac16e2009-10-07 18:00:23 -07002834 if (mMenuIsDown) {
Michael Kolb68792c82010-08-09 16:39:18 -07002835 openTab(url, false);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002836 closeOptionsMenu();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002837 return true;
2838 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002839 return false;
2840 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002841
Grace Kloba22ac16e2009-10-07 18:00:23 -07002842 // -------------------------------------------------------------------------
2843 // Helper function for WebChromeClient
2844 // -------------------------------------------------------------------------
The Android Open Source Project0c908882009-03-03 19:32:16 -08002845
Grace Kloba22ac16e2009-10-07 18:00:23 -07002846 void onProgressChanged(WebView view, int newProgress) {
Michael Kolba2b2ba82010-08-04 17:54:03 -07002847
2848 // On the phone, the fake title bar will always cover up the
2849 // regular title bar (or the regular one is offscreen), so only the
2850 // fake title bar needs to change its progress
2851 mFakeTitleBar.setProgress(newProgress);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002852
Grace Kloba22ac16e2009-10-07 18:00:23 -07002853 if (newProgress == 100) {
2854 // onProgressChanged() may continue to be called after the main
2855 // frame has finished loading, as any remaining sub frames continue
2856 // to load. We'll only get called once though with newProgress as
2857 // 100 when everything is loaded. (onPageFinished is called once
2858 // when the main frame completes loading regardless of the state of
2859 // any sub frames so calls to onProgressChanges may continue after
2860 // onPageFinished has executed)
2861 if (mInLoad) {
2862 mInLoad = false;
Leon Scrogginsa27ff192009-09-14 12:58:04 -04002863 updateInLoadMenuItems();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002864 // If the options menu is open, leave the title bar
2865 if (!mOptionsMenuOpen || !mIconView) {
2866 hideFakeTitleBar();
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07002867 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002868 }
Leon Scrogginsaa37e7f2010-03-05 11:51:20 -05002869 } else {
2870 if (!mInLoad) {
2871 // onPageFinished may have already been called but a subframe is
2872 // still loading and updating the progress. Reset mInLoad and
2873 // update the menu items.
2874 mInLoad = true;
2875 updateInLoadMenuItems();
2876 }
2877 // When the page first begins to load, the Activity may still be
2878 // paused, in which case showFakeTitleBar will do nothing. Call
2879 // again as the page continues to load so that it will be shown.
2880 // (Calling it will the fake title bar is already showing will also
2881 // do nothing.
Grace Kloba22ac16e2009-10-07 18:00:23 -07002882 if (!mOptionsMenuOpen || mIconView) {
2883 // This page has begun to load, so show the title bar
2884 showFakeTitleBar();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002885 }
2886 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002887 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002888
Grace Kloba22ac16e2009-10-07 18:00:23 -07002889 void onShowCustomView(View view, WebChromeClient.CustomViewCallback callback) {
Derek Sollenberger8ff57db2009-12-08 15:39:55 -05002890 // if a view already exists then immediately terminate the new one
2891 if (mCustomView != null) {
2892 callback.onCustomViewHidden();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002893 return;
Derek Sollenberger8ff57db2009-12-08 15:39:55 -05002894 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002895
2896 // Add the custom view to its container.
2897 mCustomViewContainer.addView(view, COVER_SCREEN_GRAVITY_CENTER);
2898 mCustomView = view;
2899 mCustomViewCallback = callback;
2900 // Save the menu state and set it to empty while the custom
2901 // view is showing.
2902 mOldMenuState = mMenuState;
2903 mMenuState = EMPTY_MENU;
2904 // Hide the content view.
2905 mContentView.setVisibility(View.GONE);
2906 // Finally show the custom view container.
Andrei Popescu163ab742009-10-20 17:58:23 +01002907 setStatusBarVisibility(false);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002908 mCustomViewContainer.setVisibility(View.VISIBLE);
2909 mCustomViewContainer.bringToFront();
2910 }
2911
2912 void onHideCustomView() {
2913 if (mCustomView == null)
2914 return;
2915
2916 // Hide the custom view.
2917 mCustomView.setVisibility(View.GONE);
2918 // Remove the custom view from its container.
2919 mCustomViewContainer.removeView(mCustomView);
2920 mCustomView = null;
2921 // Reset the old menu state.
2922 mMenuState = mOldMenuState;
2923 mOldMenuState = EMPTY_MENU;
2924 mCustomViewContainer.setVisibility(View.GONE);
2925 mCustomViewCallback.onCustomViewHidden();
2926 // Show the content view.
Andrei Popescu163ab742009-10-20 17:58:23 +01002927 setStatusBarVisibility(true);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002928 mContentView.setVisibility(View.VISIBLE);
2929 }
2930
2931 Bitmap getDefaultVideoPoster() {
2932 if (mDefaultVideoPoster == null) {
2933 mDefaultVideoPoster = BitmapFactory.decodeResource(
2934 getResources(), R.drawable.default_video_poster);
Patrick Scott3918d442009-08-04 13:22:29 -04002935 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002936 return mDefaultVideoPoster;
2937 }
Patrick Scott3918d442009-08-04 13:22:29 -04002938
Grace Kloba22ac16e2009-10-07 18:00:23 -07002939 View getVideoLoadingProgressView() {
2940 if (mVideoProgressView == null) {
2941 LayoutInflater inflater = LayoutInflater.from(BrowserActivity.this);
2942 mVideoProgressView = inflater.inflate(
2943 R.layout.video_loading_progress, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002944 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002945 return mVideoProgressView;
2946 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002947
Leon Scroggins8d5fa432009-10-02 15:55:59 -04002948 /*
2949 * The Object used to inform the WebView of the file to upload.
2950 */
2951 private ValueCallback<Uri> mUploadMessage;
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002952 private String mCameraFilePath;
Leon Scroggins8d5fa432009-10-02 15:55:59 -04002953
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002954 void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
2955
2956 final String imageMimeType = "image/*";
Ben Murdoch6af492a2010-06-15 12:38:17 +01002957 final String videoMimeType = "video/*";
Ben Murdoch039bd472010-07-21 21:26:57 +01002958 final String audioMimeType = "audio/*";
Ben Murdochb50d7402010-07-16 12:42:22 +01002959 final String mediaSourceKey = "capture";
Ben Murdoch6af492a2010-06-15 12:38:17 +01002960 final String mediaSourceValueCamera = "camera";
Ben Murdochb50d7402010-07-16 12:42:22 +01002961 final String mediaSourceValueFileSystem = "filesystem";
Ben Murdoch6af492a2010-06-15 12:38:17 +01002962 final String mediaSourceValueCamcorder = "camcorder";
Ben Murdoch039bd472010-07-21 21:26:57 +01002963 final String mediaSourceValueMicrophone = "microphone";
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002964
Ben Murdoch039bd472010-07-21 21:26:57 +01002965 // media source can be 'filesystem' or 'camera' or 'camcorder' or 'microphone'.
Ben Murdoch6af492a2010-06-15 12:38:17 +01002966 String mediaSource = "";
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002967
Ben Murdoch6af492a2010-06-15 12:38:17 +01002968 // We add the camera intent if there was no accept type (or '*/*' or 'image/*').
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002969 boolean addCameraIntent = true;
Ben Murdoch6af492a2010-06-15 12:38:17 +01002970 // We add the camcorder intent if there was no accept type (or '*/*' or 'video/*').
2971 boolean addCamcorderIntent = true;
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002972
Ben Murdoch6af492a2010-06-15 12:38:17 +01002973 if (mUploadMessage != null) {
2974 // Already a file picker operation in progress.
2975 return;
2976 }
2977
Grace Kloba22ac16e2009-10-07 18:00:23 -07002978 mUploadMessage = uploadMsg;
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002979
2980 // Parse the accept type.
2981 String params[] = acceptType.split(";");
2982 String mimeType = params[0];
2983
2984 for (String p : params) {
2985 String[] keyValue = p.split("=");
2986 if (keyValue.length == 2) {
2987 // Process key=value parameters.
Ben Murdoch6af492a2010-06-15 12:38:17 +01002988 if (mediaSourceKey.equals(keyValue[0])) {
2989 mediaSource = keyValue[1];
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002990 }
2991 }
2992 }
2993
2994 // This intent will display the standard OPENABLE file picker.
Grace Kloba22ac16e2009-10-07 18:00:23 -07002995 Intent i = new Intent(Intent.ACTION_GET_CONTENT);
2996 i.addCategory(Intent.CATEGORY_OPENABLE);
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002997
2998 // Create an intent to add to the standard file picker that will
2999 // capture an image from the camera. We'll combine this intent with
3000 // the standard OPENABLE picker unless the web developer specifically
3001 // requested the camera or gallery be opened by passing a parameter
3002 // in the accept type.
3003 Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
3004 File externalDataDir = Environment.getExternalStoragePublicDirectory(
3005 Environment.DIRECTORY_DCIM);
3006 File cameraDataDir = new File(externalDataDir.getAbsolutePath() +
3007 File.separator + "browser-photos");
3008 cameraDataDir.mkdirs();
3009 mCameraFilePath = cameraDataDir.getAbsolutePath() + File.separator +
3010 System.currentTimeMillis() + ".jpg";
3011 cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(mCameraFilePath)));
3012
Ben Murdoch6af492a2010-06-15 12:38:17 +01003013 Intent camcorderIntent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
3014
Ben Murdoch039bd472010-07-21 21:26:57 +01003015 Intent soundRecIntent = new Intent(MediaStore.Audio.Media.RECORD_SOUND_ACTION);
3016
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003017 if (mimeType.equals(imageMimeType)) {
3018 i.setType(imageMimeType);
Ben Murdoch6af492a2010-06-15 12:38:17 +01003019 addCamcorderIntent = false;
3020 if (mediaSource.equals(mediaSourceValueCamera)) {
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003021 // Specified 'image/*' and requested the camera, so go ahead and launch the camera
3022 // directly.
3023 BrowserActivity.this.startActivityForResult(cameraIntent, FILE_SELECTED);
3024 return;
Ben Murdochb50d7402010-07-16 12:42:22 +01003025 } else if (mediaSource.equals(mediaSourceValueFileSystem)) {
3026 // Specified filesytem as the source, so don't want to consider the camera.
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003027 addCameraIntent = false;
3028 }
Ben Murdoch6af492a2010-06-15 12:38:17 +01003029 } else if (mimeType.equals(videoMimeType)) {
3030 i.setType(videoMimeType);
3031 addCameraIntent = false;
3032 // The camcorder saves it's own file and returns it to us in the intent, so
3033 // we don't need to generate one here.
3034 mCameraFilePath = null;
3035
3036 if (mediaSource.equals(mediaSourceValueCamcorder)) {
Ben Murdoch039bd472010-07-21 21:26:57 +01003037 // Specified 'video/*' and requested the camcorder, so go ahead and launch the
3038 // camcorder directly.
Ben Murdoch6af492a2010-06-15 12:38:17 +01003039 BrowserActivity.this.startActivityForResult(camcorderIntent, FILE_SELECTED);
3040 return;
Ben Murdochb50d7402010-07-16 12:42:22 +01003041 } else if (mediaSource.equals(mediaSourceValueFileSystem)) {
3042 // Specified filesystem as the source, so don't want to consider the camcorder.
Ben Murdoch6af492a2010-06-15 12:38:17 +01003043 addCamcorderIntent = false;
3044 }
Ben Murdoch039bd472010-07-21 21:26:57 +01003045 } else if (mimeType.equals(audioMimeType)) {
3046 i.setType(audioMimeType);
3047 addCameraIntent = false;
3048 addCamcorderIntent = false;
3049 if (mediaSource.equals(mediaSourceValueMicrophone)) {
3050 // Specified 'audio/*' and requested microphone, so go ahead and launch the sound
3051 // recorder.
3052 BrowserActivity.this.startActivityForResult(soundRecIntent, FILE_SELECTED);
3053 return;
3054 }
3055 // On a default system, there is no single option to open an audio "gallery". Both the
3056 // sound recorder and music browser respond to the OPENABLE/audio/* intent unlike the
3057 // image/* and video/* OPENABLE intents where the image / video gallery are the only
3058 // respondants (and so the user is not prompted by default).
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003059 } else {
3060 i.setType("*/*");
3061 }
3062
Ben Murdoch6af492a2010-06-15 12:38:17 +01003063 // Combine the chooser and the extra choices (like camera or camcorder)
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003064 Intent chooser = new Intent(Intent.ACTION_CHOOSER);
3065 chooser.putExtra(Intent.EXTRA_INTENT, i);
3066
Ben Murdoch6af492a2010-06-15 12:38:17 +01003067 Vector<Intent> extraInitialIntents = new Vector<Intent>(0);
3068
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003069 if (addCameraIntent) {
Ben Murdoch6af492a2010-06-15 12:38:17 +01003070 extraInitialIntents.add(cameraIntent);
3071 }
3072
3073 if (addCamcorderIntent) {
3074 extraInitialIntents.add(camcorderIntent);
3075 }
3076
3077 if (extraInitialIntents.size() > 0) {
3078 Intent[] extraIntents = new Intent[extraInitialIntents.size()];
3079 chooser.putExtra(Intent.EXTRA_INITIAL_INTENTS, extraInitialIntents.toArray(extraIntents));
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003080 }
3081
3082 chooser.putExtra(Intent.EXTRA_TITLE, getString(R.string.choose_upload));
3083 BrowserActivity.this.startActivityForResult(chooser, FILE_SELECTED);
Grace Kloba22ac16e2009-10-07 18:00:23 -07003084 }
3085
3086 // -------------------------------------------------------------------------
3087 // Implement functions for DownloadListener
3088 // -------------------------------------------------------------------------
3089
The Android Open Source Project0c908882009-03-03 19:32:16 -08003090 /**
3091 * Notify the host application a download should be done, or that
3092 * the data should be streamed if a streaming viewer is available.
3093 * @param url The full url to the content that should be downloaded
3094 * @param contentDisposition Content-disposition http header, if
3095 * present.
3096 * @param mimetype The mimetype of the content reported by the server
3097 * @param contentLength The file size reported by the server
3098 */
3099 public void onDownloadStart(String url, String userAgent,
3100 String contentDisposition, String mimetype, long contentLength) {
3101 // if we're dealing wih A/V content that's not explicitly marked
3102 // for download, check if it's streamable.
3103 if (contentDisposition == null
Patrick Scotte1fb9662009-08-31 14:31:52 -04003104 || !contentDisposition.regionMatches(
3105 true, 0, "attachment", 0, 10)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003106 // query the package manager to see if there's a registered handler
3107 // that matches.
3108 Intent intent = new Intent(Intent.ACTION_VIEW);
3109 intent.setDataAndType(Uri.parse(url), mimetype);
Patrick Scotte1fb9662009-08-31 14:31:52 -04003110 ResolveInfo info = getPackageManager().resolveActivity(intent,
3111 PackageManager.MATCH_DEFAULT_ONLY);
3112 if (info != null) {
3113 ComponentName myName = getComponentName();
3114 // If we resolved to ourselves, we don't want to attempt to
3115 // load the url only to try and download it again.
3116 if (!myName.getPackageName().equals(
3117 info.activityInfo.packageName)
3118 || !myName.getClassName().equals(
3119 info.activityInfo.name)) {
3120 // someone (other than us) knows how to handle this mime
3121 // type with this scheme, don't download.
3122 try {
3123 startActivity(intent);
3124 return;
3125 } catch (ActivityNotFoundException ex) {
3126 if (LOGD_ENABLED) {
3127 Log.d(LOGTAG, "activity not found for " + mimetype
3128 + " over " + Uri.parse(url).getScheme(),
3129 ex);
3130 }
3131 // Best behavior is to fall back to a download in this
3132 // case
The Android Open Source Project0c908882009-03-03 19:32:16 -08003133 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003134 }
3135 }
3136 }
3137 onDownloadStartNoStream(url, userAgent, contentDisposition, mimetype, contentLength);
3138 }
3139
Kristian Monsenfa52d172010-03-25 18:29:21 +00003140 // This is to work around the fact that java.net.URI throws Exceptions
3141 // instead of just encoding URL's properly
3142 // Helper method for onDownloadStartNoStream
3143 private static String encodePath(String path) {
3144 char[] chars = path.toCharArray();
3145
3146 boolean needed = false;
3147 for (char c : chars) {
3148 if (c == '[' || c == ']') {
3149 needed = true;
3150 break;
3151 }
3152 }
3153 if (needed == false) {
3154 return path;
3155 }
3156
3157 StringBuilder sb = new StringBuilder("");
3158 for (char c : chars) {
3159 if (c == '[' || c == ']') {
3160 sb.append('%');
3161 sb.append(Integer.toHexString(c));
3162 } else {
3163 sb.append(c);
3164 }
3165 }
3166
3167 return sb.toString();
3168 }
3169
The Android Open Source Project0c908882009-03-03 19:32:16 -08003170 /**
3171 * Notify the host application a download should be done, even if there
3172 * is a streaming viewer available for thise type.
3173 * @param url The full url to the content that should be downloaded
3174 * @param contentDisposition Content-disposition http header, if
3175 * present.
3176 * @param mimetype The mimetype of the content reported by the server
3177 * @param contentLength The file size reported by the server
3178 */
3179 /*package */ void onDownloadStartNoStream(String url, String userAgent,
3180 String contentDisposition, String mimetype, long contentLength) {
3181
3182 String filename = URLUtil.guessFileName(url,
3183 contentDisposition, mimetype);
3184
3185 // Check to see if we have an SDCard
3186 String status = Environment.getExternalStorageState();
3187 if (!status.equals(Environment.MEDIA_MOUNTED)) {
3188 int title;
3189 String msg;
3190
3191 // Check to see if the SDCard is busy, same as the music app
3192 if (status.equals(Environment.MEDIA_SHARED)) {
3193 msg = getString(R.string.download_sdcard_busy_dlg_msg);
3194 title = R.string.download_sdcard_busy_dlg_title;
3195 } else {
3196 msg = getString(R.string.download_no_sdcard_dlg_msg, filename);
3197 title = R.string.download_no_sdcard_dlg_title;
3198 }
3199
3200 new AlertDialog.Builder(this)
3201 .setTitle(title)
3202 .setIcon(android.R.drawable.ic_dialog_alert)
3203 .setMessage(msg)
3204 .setPositiveButton(R.string.ok, null)
3205 .show();
3206 return;
3207 }
3208
Kristian Monsenfa52d172010-03-25 18:29:21 +00003209 // java.net.URI is a lot stricter than KURL so we have to encode some
3210 // extra characters. Fix for b 2538060 and b 1634719
3211 WebAddress webAddress;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003212 try {
Kristian Monsenfa52d172010-03-25 18:29:21 +00003213 webAddress = new WebAddress(url);
3214 webAddress.mPath = encodePath(webAddress.mPath);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003215 } catch (Exception e) {
Kristian Monsenfa52d172010-03-25 18:29:21 +00003216 // This only happens for very bad urls, we want to chatch the
3217 // exception here
3218 Log.e(LOGTAG, "Exception trying to parse url:" + url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003219 return;
3220 }
3221
3222 // XXX: Have to use the old url since the cookies were stored using the
3223 // old percent-encoded url.
3224 String cookies = CookieManager.getInstance().getCookie(url);
3225
3226 ContentValues values = new ContentValues();
Kristian Monsenfa52d172010-03-25 18:29:21 +00003227 values.put(Downloads.Impl.COLUMN_URI, webAddress.toString());
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08003228 values.put(Downloads.Impl.COLUMN_COOKIE_DATA, cookies);
3229 values.put(Downloads.Impl.COLUMN_USER_AGENT, userAgent);
3230 values.put(Downloads.Impl.COLUMN_NOTIFICATION_PACKAGE,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003231 getPackageName());
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08003232 values.put(Downloads.Impl.COLUMN_NOTIFICATION_CLASS,
Leon Scrogginsa563d092010-04-19 16:53:49 -04003233 OpenDownloadReceiver.class.getCanonicalName());
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08003234 values.put(Downloads.Impl.COLUMN_VISIBILITY,
3235 Downloads.Impl.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
3236 values.put(Downloads.Impl.COLUMN_MIME_TYPE, mimetype);
3237 values.put(Downloads.Impl.COLUMN_FILE_NAME_HINT, filename);
Kristian Monsenfa52d172010-03-25 18:29:21 +00003238 values.put(Downloads.Impl.COLUMN_DESCRIPTION, webAddress.mHost);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003239 if (contentLength > 0) {
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08003240 values.put(Downloads.Impl.COLUMN_TOTAL_BYTES, contentLength);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003241 }
3242 if (mimetype == null) {
3243 // We must have long pressed on a link or image to download it. We
3244 // are not sure of the mimetype in this case, so do a head request
3245 new FetchUrlMimeType(this).execute(values);
3246 } else {
3247 final Uri contentUri =
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08003248 getContentResolver().insert(Downloads.Impl.CONTENT_URI, values);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003249 }
Leon Scroggins9191a7f2010-03-18 14:44:44 -04003250 Toast.makeText(this, R.string.download_pending, Toast.LENGTH_SHORT)
3251 .show();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003252 }
3253
Grace Kloba22ac16e2009-10-07 18:00:23 -07003254 // -------------------------------------------------------------------------
3255
The Android Open Source Project0c908882009-03-03 19:32:16 -08003256 /**
3257 * Resets the lock icon. This method is called when we start a new load and
3258 * know the url to be loaded.
3259 */
3260 private void resetLockIcon(String url) {
3261 // Save the lock-icon state (we revert to it if the load gets cancelled)
Grace Kloba22ac16e2009-10-07 18:00:23 -07003262 mTabControl.getCurrentTab().resetLockIcon(url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003263 updateLockIconImage(LOCK_ICON_UNSECURE);
3264 }
3265
The Android Open Source Project0c908882009-03-03 19:32:16 -08003266 /**
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04003267 * Update the lock icon to correspond to our latest state.
3268 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003269 private void updateLockIconToLatest() {
Leon Scroggins91f65fc2010-06-29 13:52:39 -04003270 Tab t = mTabControl.getCurrentTab();
3271 if (t != null) {
3272 updateLockIconImage(t.getLockIconType());
3273 }
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04003274 }
3275
3276 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08003277 * Updates the lock-icon image in the title-bar.
3278 */
3279 private void updateLockIconImage(int lockIconType) {
3280 Drawable d = null;
3281 if (lockIconType == LOCK_ICON_SECURE) {
3282 d = mSecLockIcon;
3283 } else if (lockIconType == LOCK_ICON_MIXED) {
3284 d = mMixLockIcon;
3285 }
Leon Scroggins68579392009-09-15 15:31:54 -04003286 mTitleBar.setLock(d);
Michael Kolba2b2ba82010-08-04 17:54:03 -07003287 mFakeTitleBar.setLock(d);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003288 }
3289
3290 /**
3291 * Displays a page-info dialog.
3292 * @param tab The tab to show info about
3293 * @param fromShowSSLCertificateOnError The flag that indicates whether
3294 * this dialog was opened from the SSL-certificate-on-error dialog or
3295 * not. This is important, since we need to know whether to return to
3296 * the parent dialog or simply dismiss.
3297 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003298 private void showPageInfo(final Tab tab,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003299 final boolean fromShowSSLCertificateOnError) {
3300 final LayoutInflater factory = LayoutInflater
3301 .from(this);
3302
3303 final View pageInfoView = factory.inflate(R.layout.page_info, null);
3304
3305 final WebView view = tab.getWebView();
3306
3307 String url = null;
3308 String title = null;
3309
3310 if (view == null) {
3311 url = tab.getUrl();
3312 title = tab.getTitle();
3313 } else if (view == mTabControl.getCurrentWebView()) {
3314 // Use the cached title and url if this is the current WebView
3315 url = mUrl;
3316 title = mTitle;
3317 } else {
3318 url = view.getUrl();
3319 title = view.getTitle();
3320 }
3321
3322 if (url == null) {
3323 url = "";
3324 }
3325 if (title == null) {
3326 title = "";
3327 }
3328
3329 ((TextView) pageInfoView.findViewById(R.id.address)).setText(url);
3330 ((TextView) pageInfoView.findViewById(R.id.title)).setText(title);
3331
3332 mPageInfoView = tab;
Leon Scrogginsc7b92f82010-01-11 18:17:31 -05003333 mPageInfoFromShowSSLCertificateOnError = fromShowSSLCertificateOnError;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003334
3335 AlertDialog.Builder alertDialogBuilder =
3336 new AlertDialog.Builder(this)
3337 .setTitle(R.string.page_info).setIcon(android.R.drawable.ic_dialog_info)
3338 .setView(pageInfoView)
3339 .setPositiveButton(
3340 R.string.ok,
3341 new DialogInterface.OnClickListener() {
3342 public void onClick(DialogInterface dialog,
3343 int whichButton) {
3344 mPageInfoDialog = null;
3345 mPageInfoView = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003346
3347 // if we came here from the SSL error dialog
3348 if (fromShowSSLCertificateOnError) {
3349 // go back to the SSL error dialog
3350 showSSLCertificateOnError(
3351 mSSLCertificateOnErrorView,
3352 mSSLCertificateOnErrorHandler,
3353 mSSLCertificateOnErrorError);
3354 }
3355 }
3356 })
3357 .setOnCancelListener(
3358 new DialogInterface.OnCancelListener() {
3359 public void onCancel(DialogInterface dialog) {
3360 mPageInfoDialog = null;
3361 mPageInfoView = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003362
3363 // if we came here from the SSL error dialog
3364 if (fromShowSSLCertificateOnError) {
3365 // go back to the SSL error dialog
3366 showSSLCertificateOnError(
3367 mSSLCertificateOnErrorView,
3368 mSSLCertificateOnErrorHandler,
3369 mSSLCertificateOnErrorError);
3370 }
3371 }
3372 });
3373
3374 // if we have a main top-level page SSL certificate set or a certificate
3375 // error
3376 if (fromShowSSLCertificateOnError ||
3377 (view != null && view.getCertificate() != null)) {
3378 // add a 'View Certificate' button
3379 alertDialogBuilder.setNeutralButton(
3380 R.string.view_certificate,
3381 new DialogInterface.OnClickListener() {
3382 public void onClick(DialogInterface dialog,
3383 int whichButton) {
3384 mPageInfoDialog = null;
3385 mPageInfoView = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003386
3387 // if we came here from the SSL error dialog
3388 if (fromShowSSLCertificateOnError) {
3389 // go back to the SSL error dialog
3390 showSSLCertificateOnError(
3391 mSSLCertificateOnErrorView,
3392 mSSLCertificateOnErrorHandler,
3393 mSSLCertificateOnErrorError);
3394 } else {
3395 // otherwise, display the top-most certificate from
3396 // the chain
3397 if (view.getCertificate() != null) {
3398 showSSLCertificate(tab);
3399 }
3400 }
3401 }
3402 });
3403 }
3404
3405 mPageInfoDialog = alertDialogBuilder.show();
3406 }
3407
3408 /**
3409 * Displays the main top-level page SSL certificate dialog
3410 * (accessible from the Page-Info dialog).
3411 * @param tab The tab to show certificate for.
3412 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003413 private void showSSLCertificate(final Tab tab) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003414 final View certificateView =
3415 inflateCertificateView(tab.getWebView().getCertificate());
3416 if (certificateView == null) {
3417 return;
3418 }
3419
3420 LayoutInflater factory = LayoutInflater.from(this);
3421
3422 final LinearLayout placeholder =
3423 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3424
3425 LinearLayout ll = (LinearLayout) factory.inflate(
3426 R.layout.ssl_success, placeholder);
3427 ((TextView)ll.findViewById(R.id.success))
3428 .setText(R.string.ssl_certificate_is_valid);
3429
3430 mSSLCertificateView = tab;
3431 mSSLCertificateDialog =
3432 new AlertDialog.Builder(this)
3433 .setTitle(R.string.ssl_certificate).setIcon(
3434 R.drawable.ic_dialog_browser_certificate_secure)
3435 .setView(certificateView)
3436 .setPositiveButton(R.string.ok,
3437 new DialogInterface.OnClickListener() {
3438 public void onClick(DialogInterface dialog,
3439 int whichButton) {
3440 mSSLCertificateDialog = null;
3441 mSSLCertificateView = null;
3442
3443 showPageInfo(tab, false);
3444 }
3445 })
3446 .setOnCancelListener(
3447 new DialogInterface.OnCancelListener() {
3448 public void onCancel(DialogInterface dialog) {
3449 mSSLCertificateDialog = null;
3450 mSSLCertificateView = null;
3451
3452 showPageInfo(tab, false);
3453 }
3454 })
3455 .show();
3456 }
3457
3458 /**
3459 * Displays the SSL error certificate dialog.
3460 * @param view The target web-view.
3461 * @param handler The SSL error handler responsible for cancelling the
3462 * connection that resulted in an SSL error or proceeding per user request.
3463 * @param error The SSL error object.
3464 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003465 void showSSLCertificateOnError(
The Android Open Source Project0c908882009-03-03 19:32:16 -08003466 final WebView view, final SslErrorHandler handler, final SslError error) {
3467
3468 final View certificateView =
3469 inflateCertificateView(error.getCertificate());
3470 if (certificateView == null) {
3471 return;
3472 }
3473
3474 LayoutInflater factory = LayoutInflater.from(this);
3475
3476 final LinearLayout placeholder =
3477 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3478
3479 if (error.hasError(SslError.SSL_UNTRUSTED)) {
3480 LinearLayout ll = (LinearLayout)factory
3481 .inflate(R.layout.ssl_warning, placeholder);
3482 ((TextView)ll.findViewById(R.id.warning))
3483 .setText(R.string.ssl_untrusted);
3484 }
3485
3486 if (error.hasError(SslError.SSL_IDMISMATCH)) {
3487 LinearLayout ll = (LinearLayout)factory
3488 .inflate(R.layout.ssl_warning, placeholder);
3489 ((TextView)ll.findViewById(R.id.warning))
3490 .setText(R.string.ssl_mismatch);
3491 }
3492
3493 if (error.hasError(SslError.SSL_EXPIRED)) {
3494 LinearLayout ll = (LinearLayout)factory
3495 .inflate(R.layout.ssl_warning, placeholder);
3496 ((TextView)ll.findViewById(R.id.warning))
3497 .setText(R.string.ssl_expired);
3498 }
3499
3500 if (error.hasError(SslError.SSL_NOTYETVALID)) {
3501 LinearLayout ll = (LinearLayout)factory
3502 .inflate(R.layout.ssl_warning, placeholder);
3503 ((TextView)ll.findViewById(R.id.warning))
3504 .setText(R.string.ssl_not_yet_valid);
3505 }
3506
3507 mSSLCertificateOnErrorHandler = handler;
3508 mSSLCertificateOnErrorView = view;
3509 mSSLCertificateOnErrorError = error;
3510 mSSLCertificateOnErrorDialog =
3511 new AlertDialog.Builder(this)
3512 .setTitle(R.string.ssl_certificate).setIcon(
3513 R.drawable.ic_dialog_browser_certificate_partially_secure)
3514 .setView(certificateView)
3515 .setPositiveButton(R.string.ok,
3516 new DialogInterface.OnClickListener() {
3517 public void onClick(DialogInterface dialog,
3518 int whichButton) {
3519 mSSLCertificateOnErrorDialog = null;
3520 mSSLCertificateOnErrorView = null;
3521 mSSLCertificateOnErrorHandler = null;
3522 mSSLCertificateOnErrorError = null;
3523
Grace Kloba22ac16e2009-10-07 18:00:23 -07003524 view.getWebViewClient().onReceivedSslError(
3525 view, handler, error);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003526 }
3527 })
3528 .setNeutralButton(R.string.page_info_view,
3529 new DialogInterface.OnClickListener() {
3530 public void onClick(DialogInterface dialog,
3531 int whichButton) {
3532 mSSLCertificateOnErrorDialog = null;
3533
3534 // do not clear the dialog state: we will
3535 // need to show the dialog again once the
3536 // user is done exploring the page-info details
3537
3538 showPageInfo(mTabControl.getTabFromView(view),
3539 true);
3540 }
3541 })
3542 .setOnCancelListener(
3543 new DialogInterface.OnCancelListener() {
3544 public void onCancel(DialogInterface dialog) {
3545 mSSLCertificateOnErrorDialog = null;
3546 mSSLCertificateOnErrorView = null;
3547 mSSLCertificateOnErrorHandler = null;
3548 mSSLCertificateOnErrorError = null;
3549
Grace Kloba22ac16e2009-10-07 18:00:23 -07003550 view.getWebViewClient().onReceivedSslError(
3551 view, handler, error);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003552 }
3553 })
3554 .show();
3555 }
3556
3557 /**
3558 * Inflates the SSL certificate view (helper method).
3559 * @param certificate The SSL certificate.
3560 * @return The resultant certificate view with issued-to, issued-by,
3561 * issued-on, expires-on, and possibly other fields set.
3562 * If the input certificate is null, returns null.
3563 */
3564 private View inflateCertificateView(SslCertificate certificate) {
3565 if (certificate == null) {
3566 return null;
3567 }
3568
3569 LayoutInflater factory = LayoutInflater.from(this);
3570
3571 View certificateView = factory.inflate(
3572 R.layout.ssl_certificate, null);
3573
3574 // issued to:
3575 SslCertificate.DName issuedTo = certificate.getIssuedTo();
3576 if (issuedTo != null) {
3577 ((TextView) certificateView.findViewById(R.id.to_common))
3578 .setText(issuedTo.getCName());
3579 ((TextView) certificateView.findViewById(R.id.to_org))
3580 .setText(issuedTo.getOName());
3581 ((TextView) certificateView.findViewById(R.id.to_org_unit))
3582 .setText(issuedTo.getUName());
3583 }
3584
3585 // issued by:
3586 SslCertificate.DName issuedBy = certificate.getIssuedBy();
3587 if (issuedBy != null) {
3588 ((TextView) certificateView.findViewById(R.id.by_common))
3589 .setText(issuedBy.getCName());
3590 ((TextView) certificateView.findViewById(R.id.by_org))
3591 .setText(issuedBy.getOName());
3592 ((TextView) certificateView.findViewById(R.id.by_org_unit))
3593 .setText(issuedBy.getUName());
3594 }
3595
3596 // issued on:
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003597 String issuedOn = formatCertificateDate(
3598 certificate.getValidNotBeforeDate());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003599 ((TextView) certificateView.findViewById(R.id.issued_on))
3600 .setText(issuedOn);
3601
3602 // expires on:
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003603 String expiresOn = formatCertificateDate(
3604 certificate.getValidNotAfterDate());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003605 ((TextView) certificateView.findViewById(R.id.expires_on))
3606 .setText(expiresOn);
3607
3608 return certificateView;
3609 }
3610
3611 /**
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003612 * Formats the certificate date to a properly localized date string.
The Android Open Source Project0c908882009-03-03 19:32:16 -08003613 * @return Properly localized version of the certificate date string and
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003614 * the "" if it fails to localize.
The Android Open Source Project0c908882009-03-03 19:32:16 -08003615 */
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003616 private String formatCertificateDate(Date certificateDate) {
3617 if (certificateDate == null) {
3618 return "";
The Android Open Source Project0c908882009-03-03 19:32:16 -08003619 }
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003620 String formattedDate = DateFormat.getDateFormat(this).format(certificateDate);
3621 if (formattedDate == null) {
3622 return "";
3623 }
3624 return formattedDate;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003625 }
3626
3627 /**
3628 * Displays an http-authentication dialog.
3629 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003630 void showHttpAuthentication(final HttpAuthHandler handler,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003631 final String host, final String realm, final String title,
3632 final String name, final String password, int focusId) {
3633 LayoutInflater factory = LayoutInflater.from(this);
3634 final View v = factory
3635 .inflate(R.layout.http_authentication, null);
3636 if (name != null) {
3637 ((EditText) v.findViewById(R.id.username_edit)).setText(name);
3638 }
3639 if (password != null) {
3640 ((EditText) v.findViewById(R.id.password_edit)).setText(password);
3641 }
3642
3643 String titleText = title;
3644 if (titleText == null) {
3645 titleText = getText(R.string.sign_in_to).toString().replace(
3646 "%s1", host).replace("%s2", realm);
3647 }
3648
3649 mHttpAuthHandler = handler;
3650 AlertDialog dialog = new AlertDialog.Builder(this)
3651 .setTitle(titleText)
3652 .setIcon(android.R.drawable.ic_dialog_alert)
3653 .setView(v)
3654 .setPositiveButton(R.string.action,
3655 new DialogInterface.OnClickListener() {
3656 public void onClick(DialogInterface dialog,
3657 int whichButton) {
3658 String nm = ((EditText) v
3659 .findViewById(R.id.username_edit))
3660 .getText().toString();
3661 String pw = ((EditText) v
3662 .findViewById(R.id.password_edit))
3663 .getText().toString();
3664 BrowserActivity.this.setHttpAuthUsernamePassword
3665 (host, realm, nm, pw);
3666 handler.proceed(nm, pw);
3667 mHttpAuthenticationDialog = null;
3668 mHttpAuthHandler = null;
3669 }})
3670 .setNegativeButton(R.string.cancel,
3671 new DialogInterface.OnClickListener() {
3672 public void onClick(DialogInterface dialog,
3673 int whichButton) {
3674 handler.cancel();
3675 BrowserActivity.this.resetTitleAndRevertLockIcon();
3676 mHttpAuthenticationDialog = null;
3677 mHttpAuthHandler = null;
3678 }})
3679 .setOnCancelListener(new DialogInterface.OnCancelListener() {
3680 public void onCancel(DialogInterface dialog) {
3681 handler.cancel();
3682 BrowserActivity.this.resetTitleAndRevertLockIcon();
3683 mHttpAuthenticationDialog = null;
3684 mHttpAuthHandler = null;
3685 }})
3686 .create();
3687 // Make the IME appear when the dialog is displayed if applicable.
3688 dialog.getWindow().setSoftInputMode(
3689 WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
3690 dialog.show();
3691 if (focusId != 0) {
3692 dialog.findViewById(focusId).requestFocus();
3693 } else {
3694 v.findViewById(R.id.username_edit).requestFocus();
3695 }
3696 mHttpAuthenticationDialog = dialog;
3697 }
3698
3699 public int getProgress() {
3700 WebView w = mTabControl.getCurrentWebView();
3701 if (w != null) {
3702 return w.getProgress();
3703 } else {
3704 return 100;
3705 }
3706 }
3707
3708 /**
3709 * Set HTTP authentication password.
3710 *
3711 * @param host The host for the password
3712 * @param realm The realm for the password
3713 * @param username The username for the password. If it is null, it means
3714 * password can't be saved.
3715 * @param password The password
3716 */
3717 public void setHttpAuthUsernamePassword(String host, String realm,
3718 String username,
3719 String password) {
Steve Block95a53b22010-03-25 17:24:58 +00003720 WebView w = getTopWindow();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003721 if (w != null) {
3722 w.setHttpAuthUsernamePassword(host, realm, username, password);
3723 }
3724 }
3725
3726 /**
3727 * connectivity manager says net has come or gone... inform the user
3728 * @param up true if net has come up, false if net has gone down
3729 */
3730 public void onNetworkToggle(boolean up) {
3731 if (up == mIsNetworkUp) {
3732 return;
3733 } else if (up) {
3734 mIsNetworkUp = true;
3735 if (mAlertDialog != null) {
3736 mAlertDialog.cancel();
3737 mAlertDialog = null;
3738 }
3739 } else {
3740 mIsNetworkUp = false;
Patrick Scotteb6ab2a2009-09-16 10:00:17 -04003741 if (mInLoad) {
3742 createAndShowNetworkDialog();
3743 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003744 }
3745 WebView w = mTabControl.getCurrentWebView();
3746 if (w != null) {
3747 w.setNetworkAvailable(up);
3748 }
3749 }
3750
Grace Kloba22ac16e2009-10-07 18:00:23 -07003751 boolean isNetworkUp() {
3752 return mIsNetworkUp;
3753 }
3754
Patrick Scotteb6ab2a2009-09-16 10:00:17 -04003755 // This method shows the network dialog alerting the user that the net is
3756 // down. It will only show the dialog if mAlertDialog is null.
3757 private void createAndShowNetworkDialog() {
3758 if (mAlertDialog == null) {
3759 mAlertDialog = new AlertDialog.Builder(this)
3760 .setTitle(R.string.loadSuspendedTitle)
3761 .setMessage(R.string.loadSuspended)
3762 .setPositiveButton(R.string.ok, null)
3763 .show();
3764 }
3765 }
3766
The Android Open Source Project0c908882009-03-03 19:32:16 -08003767 @Override
3768 protected void onActivityResult(int requestCode, int resultCode,
3769 Intent intent) {
Grace Klobabb394f32009-11-19 10:26:37 -08003770 if (getTopWindow() == null) return;
3771
The Android Open Source Project0c908882009-03-03 19:32:16 -08003772 switch (requestCode) {
3773 case COMBO_PAGE:
3774 if (resultCode == RESULT_OK && intent != null) {
3775 String data = intent.getAction();
3776 Bundle extras = intent.getExtras();
3777 if (extras != null && extras.getBoolean("new_window", false)) {
Michael Kolb68792c82010-08-09 16:39:18 -07003778 openTab(data, false);
3779 } else if ((extras != null) &&
3780 extras.getBoolean(CombinedBookmarkHistoryActivity.NEWTAB_MODE)) {
3781 openTab(data, true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003782 } else {
Michael Kolb68792c82010-08-09 16:39:18 -07003783 final Tab currentTab = mTabControl.getCurrentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04003784 dismissSubWindow(currentTab);
3785 if (data != null && data.length() != 0) {
Leon Scroggins92472e82010-02-17 16:32:28 -05003786 loadUrl(getTopWindow(), data);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003787 }
3788 }
3789 }
Leon Scrogginsfde97462010-01-11 13:06:21 -05003790 // Deliberately fall through to PREFERENCES_PAGE, since the
3791 // same extra may be attached to the COMBO_PAGE
3792 case PREFERENCES_PAGE:
3793 if (resultCode == RESULT_OK && intent != null) {
3794 String action = intent.getStringExtra(Intent.EXTRA_TEXT);
3795 if (BrowserSettings.PREF_CLEAR_HISTORY.equals(action)) {
3796 mTabControl.removeParentChildRelationShips();
3797 }
3798 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003799 break;
Leon Scroggins8d5fa432009-10-02 15:55:59 -04003800 // Choose a file from the file picker.
3801 case FILE_SELECTED:
3802 if (null == mUploadMessage) break;
3803 Uri result = intent == null || resultCode != RESULT_OK ? null
3804 : intent.getData();
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003805
3806 // As we ask the camera to save the result of the user taking
3807 // a picture, the camera application does not return anything other
3808 // than RESULT_OK. So we need to check whether the file we expected
3809 // was written to disk in the in the case that we
3810 // did not get an intent returned but did get a RESULT_OK. If it was,
3811 // we assume that this result has came back from the camera.
3812 if (result == null && intent == null && resultCode == RESULT_OK) {
3813 File cameraFile = new File(mCameraFilePath);
3814 if (cameraFile.exists()) {
3815 result = Uri.fromFile(cameraFile);
Ben Murdoch07d34732010-05-27 18:34:46 +01003816 // Broadcast to the media scanner that we have a new photo
3817 // so it will be added into the gallery for the user.
3818 sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, result));
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003819 }
3820 }
Leon Scroggins8d5fa432009-10-02 15:55:59 -04003821 mUploadMessage.onReceiveValue(result);
3822 mUploadMessage = null;
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003823 mCameraFilePath = null;
Leon Scroggins8d5fa432009-10-02 15:55:59 -04003824 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003825 default:
3826 break;
3827 }
Leon Scroggins30444232009-09-04 18:36:20 -04003828 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003829 }
3830
3831 /*
3832 * This method is called as a result of the user selecting the options
Leon Scrogginsf08809b2010-01-21 09:27:46 -05003833 * menu to see the download window. It shows the download window on top of
3834 * the current window.
The Android Open Source Project0c908882009-03-03 19:32:16 -08003835 */
Leon Scrogginsf08809b2010-01-21 09:27:46 -05003836 private void viewDownloads(Uri downloadRecord) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003837 Intent intent = new Intent(this,
3838 BrowserDownloadPage.class);
3839 intent.setData(downloadRecord);
Grace Kloba22ac16e2009-10-07 18:00:23 -07003840 startActivityForResult(intent, BrowserActivity.DOWNLOAD_PAGE);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003841
3842 }
3843
Ben Murdocheecb4e62010-07-06 16:30:38 +01003844 /* package*/ void promptAddOrInstallBookmark() {
3845 final Tab current = mTabControl.getCurrentTab();
3846 Resources resources = getResources();
3847 CharSequence[] choices = {
3848 resources.getString(R.string.save_to_bookmarks),
3849 resources.getString(R.string.create_shortcut_bookmark)
3850 };
3851
3852 AlertDialog.Builder builder = new AlertDialog.Builder(this);
3853 builder.setTitle(R.string.add_new_bookmark);
3854 builder.setItems(choices, new DialogInterface.OnClickListener() {
3855 public void onClick(DialogInterface dialog, int item) {
3856 if (item == 0) {
3857 bookmarkCurrentPage();
3858 } else if (item == 1) {
3859 current.populatePickerData();
3860 String touchIconUrl = mTabControl.getCurrentWebView().getTouchIconUrl();
3861 if (touchIconUrl != null) {
3862 // Download the touch icon for this site then save it to the
3863 // homescreen.
3864 Bundle b = new Bundle();
3865 b.putString("url", current.getUrl());
3866 b.putString("title", current.getTitle());
3867 b.putParcelable("favicon", current.getFavicon());
3868 Message msg = mHandler.obtainMessage(TOUCH_ICON_DOWNLOADED);
3869 msg.setData(b);
Ben Murdochccb5de02010-07-19 18:38:17 +01003870 new DownloadTouchIcon(BrowserActivity.this, msg,
Ben Murdocheecb4e62010-07-06 16:30:38 +01003871 mTabControl.getCurrentWebView().getSettings()
3872 .getUserAgentString()).execute(touchIconUrl);
3873 } else {
3874 // add to homescreen, can do it immediately as there is no touch
3875 // icon.
3876 showSaveToHomescreenDialog(current.getUrl(), current.getTitle(),
3877 null, current.getFavicon());
3878 }
3879 }
3880 }
3881 });
3882 builder.create().show();
3883 }
3884
Leon Scroggins160a7e72009-08-14 18:28:01 -04003885 /**
3886 * Open the Go page.
3887 * @param startWithHistory If true, open starting on the history tab.
3888 * Otherwise, start with the bookmarks tab.
Leon Scroggins160a7e72009-08-14 18:28:01 -04003889 */
Michael Kolb68792c82010-08-09 16:39:18 -07003890 /* package */ void bookmarksOrHistoryPicker(boolean startWithHistory, boolean newTabMode) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003891 WebView current = mTabControl.getCurrentWebView();
3892 if (current == null) {
3893 return;
3894 }
3895 Intent intent = new Intent(this,
3896 CombinedBookmarkHistoryActivity.class);
3897 String title = current.getTitle();
3898 String url = current.getUrl();
Ben Murdoch87cc65d2010-06-29 20:34:10 +01003899 Bitmap thumbnail = createScreenshot(current, getDesiredThumbnailWidth(this),
3900 getDesiredThumbnailHeight(this));
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01003901
The Android Open Source Project0c908882009-03-03 19:32:16 -08003902 // Just in case the user opens bookmarks before a page finishes loading
3903 // so the current history item, and therefore the page, is null.
3904 if (null == url) {
3905 url = mLastEnteredUrl;
3906 // This can happen.
3907 if (null == url) {
3908 url = mSettings.getHomePage();
3909 }
3910 }
3911 // In case the web page has not yet received its associated title.
3912 if (title == null) {
3913 title = url;
3914 }
3915 intent.putExtra("title", title);
3916 intent.putExtra("url", url);
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01003917 intent.putExtra("thumbnail", thumbnail);
Leon Scroggins30444232009-09-04 18:36:20 -04003918 // Disable opening in a new window if we have maxed out the windows
Grace Kloba22ac16e2009-10-07 18:00:23 -07003919 intent.putExtra("disable_new_window", !mTabControl.canCreateNewTab());
Patrick Scott3918d442009-08-04 13:22:29 -04003920 intent.putExtra("touch_icon_url", current.getTouchIconUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003921 if (startWithHistory) {
Jeff Hamilton64144e42010-08-18 16:31:59 -05003922 intent.putExtra(CombinedBookmarkHistoryActivity.STARTING_FRAGMENT,
3923 CombinedBookmarkHistoryActivity.FRAGMENT_ID_HISTORY);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003924 }
Michael Kolb68792c82010-08-09 16:39:18 -07003925 if (newTabMode) {
3926 intent.putExtra(CombinedBookmarkHistoryActivity.NEWTAB_MODE, true);
3927 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003928 startActivityForResult(intent, COMBO_PAGE);
3929 }
3930
Ben Murdocheecb4e62010-07-06 16:30:38 +01003931 private void showSaveToHomescreenDialog(String url, String title, Bitmap touchIcon,
3932 Bitmap favicon) {
3933 Intent intent = new Intent(this, SaveToHomescreenDialog.class);
3934
3935 // Just in case the user tries to save before a page finishes loading
3936 // so the current history item, and therefore the page, is null.
3937 if (null == url) {
3938 url = mLastEnteredUrl;
3939 // This can happen.
3940 if (null == url) {
3941 url = mSettings.getHomePage();
3942 }
3943 }
3944
3945 // In case the web page has not yet received its associated title.
3946 if (title == null) {
3947 title = url;
3948 }
3949
3950 intent.putExtra("title", title);
3951 intent.putExtra("url", url);
3952 intent.putExtra("favicon", favicon);
3953 intent.putExtra("touchIcon", touchIcon);
3954 startActivity(intent);
3955 }
3956
3957
The Android Open Source Project0c908882009-03-03 19:32:16 -08003958 // Called when loading from context menu or LOAD_URL message
Leon Scroggins92472e82010-02-17 16:32:28 -05003959 private void loadUrlFromContext(WebView view, String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003960 // In case the user enters nothing.
3961 if (url != null && url.length() != 0 && view != null) {
3962 url = smartUrlFilter(url);
Grace Kloba22ac16e2009-10-07 18:00:23 -07003963 if (!view.getWebViewClient().shouldOverrideUrlLoading(view, url)) {
Leon Scroggins92472e82010-02-17 16:32:28 -05003964 loadUrl(view, url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003965 }
3966 }
3967 }
3968
Leon Scroggins92472e82010-02-17 16:32:28 -05003969 /**
3970 * Load the URL into the given WebView and update the title bar
3971 * to reflect the new load. Call this instead of WebView.loadUrl
3972 * directly.
3973 * @param view The WebView used to load url.
3974 * @param url The URL to load.
3975 */
3976 private void loadUrl(WebView view, String url) {
3977 updateTitleBarForNewLoad(view, url);
3978 view.loadUrl(url);
3979 }
3980
3981 /**
3982 * Load UrlData into a Tab and update the title bar to reflect the new
3983 * load. Call this instead of UrlData.loadIn directly.
3984 * @param t The Tab used to load.
3985 * @param data The UrlData being loaded.
3986 */
3987 private void loadUrlDataIn(Tab t, UrlData data) {
3988 updateTitleBarForNewLoad(t.getWebView(), data.mUrl);
3989 data.loadIn(t);
3990 }
3991
3992 /**
3993 * If the WebView is the top window, update the title bar to reflect
3994 * loading the new URL. i.e. set its text, clear the favicon (which
3995 * will be set once the page begins loading), and set the progress to
3996 * INITIAL_PROGRESS to show that the page has begun to load. Called
3997 * by loadUrl and loadUrlDataIn.
3998 * @param view The WebView that is starting a load.
3999 * @param url The URL that is being loaded.
4000 */
4001 private void updateTitleBarForNewLoad(WebView view, String url) {
4002 if (view == getTopWindow()) {
4003 setUrlTitle(url, null);
4004 setFavicon(null);
4005 onProgressChanged(view, INITIAL_PROGRESS);
4006 }
4007 }
4008
The Android Open Source Project0c908882009-03-03 19:32:16 -08004009 private String smartUrlFilter(Uri inUri) {
4010 if (inUri != null) {
4011 return smartUrlFilter(inUri.toString());
4012 }
4013 return null;
4014 }
4015
Feng Qianb34f87a2009-03-24 21:27:26 -07004016 protected static final Pattern ACCEPTED_URI_SCHEMA = Pattern.compile(
The Android Open Source Project0c908882009-03-03 19:32:16 -08004017 "(?i)" + // switch on case insensitive matching
4018 "(" + // begin group for schema
4019 "(?:http|https|file):\\/\\/" +
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004020 "|(?:inline|data|about|content|javascript):" +
The Android Open Source Project0c908882009-03-03 19:32:16 -08004021 ")" +
4022 "(.*)" );
4023
4024 /**
4025 * Attempts to determine whether user input is a URL or search
4026 * terms. Anything with a space is passed to search.
4027 *
4028 * Converts to lowercase any mistakenly uppercased schema (i.e.,
4029 * "Http://" converts to "http://"
4030 *
4031 * @return Original or modified URL
4032 *
4033 */
4034 String smartUrlFilter(String url) {
4035
4036 String inUrl = url.trim();
4037 boolean hasSpace = inUrl.indexOf(' ') != -1;
4038
4039 Matcher matcher = ACCEPTED_URI_SCHEMA.matcher(inUrl);
4040 if (matcher.matches()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08004041 // force scheme to lowercase
4042 String scheme = matcher.group(1);
4043 String lcScheme = scheme.toLowerCase();
4044 if (!lcScheme.equals(scheme)) {
Mitsuru Oshima123ecfb2009-05-18 19:11:14 -07004045 inUrl = lcScheme + matcher.group(2);
4046 }
4047 if (hasSpace) {
4048 inUrl = inUrl.replace(" ", "%20");
The Android Open Source Project0c908882009-03-03 19:32:16 -08004049 }
4050 return inUrl;
4051 }
4052 if (hasSpace) {
Satish Sampath565505b2009-05-29 15:37:27 +01004053 // FIXME: Is this the correct place to add to searches?
4054 // what if someone else calls this function?
4055 int shortcut = parseUrlShortcut(inUrl);
4056 if (shortcut != SHORTCUT_INVALID) {
4057 Browser.addSearchUrl(mResolver, inUrl);
4058 String query = inUrl.substring(2);
4059 switch (shortcut) {
4060 case SHORTCUT_GOOGLE_SEARCH:
Grace Kloba47fdfdb2009-06-30 11:15:34 -07004061 return URLUtil.composeSearchUrl(query, QuickSearch_G, QUERY_PLACE_HOLDER);
Satish Sampath565505b2009-05-29 15:37:27 +01004062 case SHORTCUT_WIKIPEDIA_SEARCH:
4063 return URLUtil.composeSearchUrl(query, QuickSearch_W, QUERY_PLACE_HOLDER);
4064 case SHORTCUT_DICTIONARY_SEARCH:
4065 return URLUtil.composeSearchUrl(query, QuickSearch_D, QUERY_PLACE_HOLDER);
4066 case SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH:
The Android Open Source Project0c908882009-03-03 19:32:16 -08004067 // FIXME: we need location in this case
Satish Sampath565505b2009-05-29 15:37:27 +01004068 return URLUtil.composeSearchUrl(query, QuickSearch_L, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004069 }
4070 }
4071 } else {
Dan Egnor5ee906c2009-11-18 12:11:49 -08004072 if (Patterns.WEB_URL.matcher(inUrl).matches()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08004073 return URLUtil.guessUrl(inUrl);
4074 }
4075 }
4076
4077 Browser.addSearchUrl(mResolver, inUrl);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07004078 return URLUtil.composeSearchUrl(inUrl, QuickSearch_G, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004079 }
4080
Ben Murdochbff2d602009-07-01 20:19:05 +01004081 /* package */ void setShouldShowErrorConsole(boolean flag) {
4082 if (flag == mShouldShowErrorConsole) {
4083 // Nothing to do.
4084 return;
4085 }
4086
4087 mShouldShowErrorConsole = flag;
4088
Grace Kloba22ac16e2009-10-07 18:00:23 -07004089 ErrorConsoleView errorConsole = mTabControl.getCurrentTab()
4090 .getErrorConsole(true);
Ben Murdochbff2d602009-07-01 20:19:05 +01004091
4092 if (flag) {
4093 // Setting the show state of the console will cause it's the layout to be inflated.
4094 if (errorConsole.numberOfErrors() > 0) {
4095 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
4096 } else {
4097 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
4098 }
4099
4100 // Now we can add it to the main view.
4101 mErrorConsoleContainer.addView(errorConsole,
Romain Guy15b8ec62010-01-08 15:06:43 -08004102 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
Ben Murdochbff2d602009-07-01 20:19:05 +01004103 ViewGroup.LayoutParams.WRAP_CONTENT));
4104 } else {
4105 mErrorConsoleContainer.removeView(errorConsole);
4106 }
4107
4108 }
4109
Grace Kloba22ac16e2009-10-07 18:00:23 -07004110 boolean shouldShowErrorConsole() {
4111 return mShouldShowErrorConsole;
4112 }
4113
Andrei Popescu163ab742009-10-20 17:58:23 +01004114 private void setStatusBarVisibility(boolean visible) {
4115 int flag = visible ? 0 : WindowManager.LayoutParams.FLAG_FULLSCREEN;
4116 getWindow().setFlags(flag, WindowManager.LayoutParams.FLAG_FULLSCREEN);
4117 }
4118
Andrei Popescu56199cc2010-01-12 22:39:16 +00004119
4120 private void sendNetworkType(String type, String subtype) {
4121 WebView w = mTabControl.getCurrentWebView();
4122 if (w != null) {
4123 w.setNetworkType(type, subtype);
4124 }
4125 }
4126
Andrei Popescu30995e72010-02-09 16:59:58 +00004127 private void packageChanged(String packageName, boolean wasAdded) {
4128 WebView w = mTabControl.getCurrentWebView();
4129 if (w == null) {
4130 return;
4131 }
4132
4133 if (wasAdded) {
4134 w.addPackageName(packageName);
4135 } else {
4136 w.removePackageName(packageName);
4137 }
4138 }
4139
4140 private void addPackageNames(Set<String> packageNames) {
4141 WebView w = mTabControl.getCurrentWebView();
4142 if (w == null) {
4143 return;
4144 }
4145
4146 w.addPackageNames(packageNames);
4147 }
4148
4149 private void getInstalledPackages() {
4150 AsyncTask<Void, Void, Set<String> > task =
4151 new AsyncTask<Void, Void, Set<String> >() {
Michael Kolbe0a36662010-06-29 10:37:12 -07004152 @Override
Andrei Popescu30995e72010-02-09 16:59:58 +00004153 protected Set<String> doInBackground(Void... unused) {
4154 Set<String> installedPackages = new HashSet<String>();
4155 PackageManager pm = BrowserActivity.this.getPackageManager();
4156 if (pm != null) {
4157 List<PackageInfo> packages = pm.getInstalledPackages(0);
4158 for (PackageInfo p : packages) {
4159 if (BrowserActivity.this.sGoogleApps.contains(p.packageName)) {
4160 installedPackages.add(p.packageName);
4161 }
4162 }
4163 }
4164
4165 return installedPackages;
4166 }
4167
4168 // Executes on the UI thread
Michael Kolbe0a36662010-06-29 10:37:12 -07004169 @Override
Andrei Popescu30995e72010-02-09 16:59:58 +00004170 protected void onPostExecute(Set<String> installedPackages) {
4171 addPackageNames(installedPackages);
4172 }
4173 };
4174 task.execute();
4175 }
4176
Grace Klobaeb6eef42009-09-15 17:56:32 -07004177 final static int LOCK_ICON_UNSECURE = 0;
4178 final static int LOCK_ICON_SECURE = 1;
4179 final static int LOCK_ICON_MIXED = 2;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004180
The Android Open Source Project0c908882009-03-03 19:32:16 -08004181 private BrowserSettings mSettings;
4182 private TabControl mTabControl;
4183 private ContentResolver mResolver;
4184 private FrameLayout mContentView;
Andrei Popescuadc008d2009-06-26 14:11:30 +01004185 private View mCustomView;
4186 private FrameLayout mCustomViewContainer;
Andrei Popescuc9b55562009-07-07 10:51:15 +01004187 private WebChromeClient.CustomViewCallback mCustomViewCallback;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004188
4189 // FIXME, temp address onPrepareMenu performance problem. When we move everything out of
4190 // view, we should rewrite this.
4191 private int mCurrentMenuState = 0;
4192 private int mMenuState = R.id.MAIN_MENU;
Andrei Popescuadc008d2009-06-26 14:11:30 +01004193 private int mOldMenuState = EMPTY_MENU;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004194 private static final int EMPTY_MENU = -1;
4195 private Menu mMenu;
4196
The Android Open Source Project0c908882009-03-03 19:32:16 -08004197 // Used to prevent chording to result in firing two shortcuts immediately
4198 // one after another. Fixes bug 1211714.
4199 boolean mCanChord;
4200
4201 private boolean mInLoad;
4202 private boolean mIsNetworkUp;
Ben Murdochb7cc8b42009-09-28 10:59:09 +01004203 private boolean mDidStopLoad;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004204
Cary Clark1f10cbf2010-03-22 11:45:23 -04004205 /* package */ boolean mActivityInPause = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004206
4207 private boolean mMenuIsDown;
4208
The Android Open Source Project0c908882009-03-03 19:32:16 -08004209 private static boolean mInTrace;
4210
4211 // Performance probe
4212 private static final int[] SYSTEM_CPU_FORMAT = new int[] {
4213 Process.PROC_SPACE_TERM | Process.PROC_COMBINE,
4214 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 1: user time
4215 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 2: nice time
4216 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 3: sys time
4217 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 4: idle time
4218 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 5: iowait time
4219 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 6: irq time
4220 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG // 7: softirq time
4221 };
4222
4223 private long mStart;
4224 private long mProcessStart;
4225 private long mUserStart;
4226 private long mSystemStart;
4227 private long mIdleStart;
4228 private long mIrqStart;
4229
4230 private long mUiStart;
4231
4232 private Drawable mMixLockIcon;
4233 private Drawable mSecLockIcon;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004234
4235 /* hold a ref so we can auto-cancel if necessary */
4236 private AlertDialog mAlertDialog;
4237
The Android Open Source Project0c908882009-03-03 19:32:16 -08004238 // The up-to-date URL and title (these can be different from those stored
4239 // in WebView, since it takes some time for the information in WebView to
4240 // get updated)
4241 private String mUrl;
4242 private String mTitle;
4243
4244 // As PageInfo has different style for landscape / portrait, we have
4245 // to re-open it when configuration changed
4246 private AlertDialog mPageInfoDialog;
Grace Kloba22ac16e2009-10-07 18:00:23 -07004247 private Tab mPageInfoView;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004248 // If the Page-Info dialog is launched from the SSL-certificate-on-error
4249 // dialog, we should not just dismiss it, but should get back to the
4250 // SSL-certificate-on-error dialog. This flag is used to store this state
Leon Scrogginsc7b92f82010-01-11 18:17:31 -05004251 private boolean mPageInfoFromShowSSLCertificateOnError;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004252
4253 // as SSLCertificateOnError has different style for landscape / portrait,
4254 // we have to re-open it when configuration changed
4255 private AlertDialog mSSLCertificateOnErrorDialog;
4256 private WebView mSSLCertificateOnErrorView;
4257 private SslErrorHandler mSSLCertificateOnErrorHandler;
4258 private SslError mSSLCertificateOnErrorError;
4259
4260 // as SSLCertificate has different style for landscape / portrait, we
4261 // have to re-open it when configuration changed
4262 private AlertDialog mSSLCertificateDialog;
Grace Kloba22ac16e2009-10-07 18:00:23 -07004263 private Tab mSSLCertificateView;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004264
4265 // as HttpAuthentication has different style for landscape / portrait, we
4266 // have to re-open it when configuration changed
4267 private AlertDialog mHttpAuthenticationDialog;
4268 private HttpAuthHandler mHttpAuthHandler;
4269
4270 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_PARAMS =
4271 new FrameLayout.LayoutParams(
Romain Guy15b8ec62010-01-08 15:06:43 -08004272 ViewGroup.LayoutParams.MATCH_PARENT,
4273 ViewGroup.LayoutParams.MATCH_PARENT);
Andrei Popescuadc008d2009-06-26 14:11:30 +01004274 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_GRAVITY_CENTER =
4275 new FrameLayout.LayoutParams(
Romain Guy15b8ec62010-01-08 15:06:43 -08004276 ViewGroup.LayoutParams.MATCH_PARENT,
4277 ViewGroup.LayoutParams.MATCH_PARENT,
Andrei Popescuadc008d2009-06-26 14:11:30 +01004278 Gravity.CENTER);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07004279 // Google search
4280 final static String QuickSearch_G = "http://www.google.com/m?q=%s";
The Android Open Source Project0c908882009-03-03 19:32:16 -08004281 // Wikipedia search
4282 final static String QuickSearch_W = "http://en.wikipedia.org/w/index.php?search=%s&go=Go";
4283 // Dictionary search
4284 final static String QuickSearch_D = "http://dictionary.reference.com/search?q=%s";
4285 // Google Mobile Local search
4286 final static String QuickSearch_L = "http://www.google.com/m/search?site=local&q=%s&near=mountain+view";
4287
4288 final static String QUERY_PLACE_HOLDER = "%s";
4289
4290 // "source" parameter for Google search through search key
4291 final static String GOOGLE_SEARCH_SOURCE_SEARCHKEY = "browser-key";
4292 // "source" parameter for Google search through goto menu
4293 final static String GOOGLE_SEARCH_SOURCE_GOTO = "browser-goto";
4294 // "source" parameter for Google search through simplily type
4295 final static String GOOGLE_SEARCH_SOURCE_TYPE = "browser-type";
4296 // "source" parameter for Google search suggested by the browser
4297 final static String GOOGLE_SEARCH_SOURCE_SUGGEST = "browser-suggest";
4298 // "source" parameter for Google search from unknown source
4299 final static String GOOGLE_SEARCH_SOURCE_UNKNOWN = "unknown";
4300
4301 private final static String LOGTAG = "browser";
4302
The Android Open Source Project0c908882009-03-03 19:32:16 -08004303 private String mLastEnteredUrl;
4304
4305 private PowerManager.WakeLock mWakeLock;
4306 private final static int WAKELOCK_TIMEOUT = 5 * 60 * 1000; // 5 minutes
4307
4308 private Toast mStopToast;
4309
Leon Scroggins571b3762010-05-26 10:25:01 -04004310 private TitleBarBase mTitleBar;
Michael Kolba2b2ba82010-08-04 17:54:03 -07004311 private TabBar mTabBar;
Leon Scroggins81db3662009-06-04 17:45:11 -04004312
Ben Murdochbff2d602009-07-01 20:19:05 +01004313 private LinearLayout mErrorConsoleContainer = null;
4314 private boolean mShouldShowErrorConsole = false;
4315
The Android Open Source Project0c908882009-03-03 19:32:16 -08004316 // As the ids are dynamically created, we can't guarantee that they will
4317 // be in sequence, so this static array maps ids to a window number.
4318 final static private int[] WINDOW_SHORTCUT_ID_ARRAY =
4319 { R.id.window_one_menu_id, R.id.window_two_menu_id, R.id.window_three_menu_id,
4320 R.id.window_four_menu_id, R.id.window_five_menu_id, R.id.window_six_menu_id,
4321 R.id.window_seven_menu_id, R.id.window_eight_menu_id };
4322
4323 // monitor platform changes
4324 private IntentFilter mNetworkStateChangedFilter;
4325 private BroadcastReceiver mNetworkStateIntentReceiver;
4326
Grace Klobab4da0ad2009-05-14 14:45:40 -07004327 private BroadcastReceiver mPackageInstallationReceiver;
4328
Bjorn Bringerta7611812010-03-24 11:12:02 +00004329 private SystemAllowGeolocationOrigins mSystemAllowGeolocationOrigins;
4330
The Android Open Source Project0c908882009-03-03 19:32:16 -08004331 // activity requestCode
Nicolas Roard78a98e42009-05-11 13:34:17 +01004332 final static int COMBO_PAGE = 1;
4333 final static int DOWNLOAD_PAGE = 2;
4334 final static int PREFERENCES_PAGE = 3;
Leon Scroggins8d5fa432009-10-02 15:55:59 -04004335 final static int FILE_SELECTED = 4;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004336
Andrei Popescu540035d2009-09-18 18:59:20 +01004337 // the default <video> poster
4338 private Bitmap mDefaultVideoPoster;
4339 // the video progress view
4340 private View mVideoProgressView;
4341
Andrei Popescu30995e72010-02-09 16:59:58 +00004342 // The Google packages we monitor for the navigator.isApplicationInstalled()
4343 // API. Add as needed.
4344 private static Set<String> sGoogleApps;
4345 static {
4346 sGoogleApps = new HashSet<String>();
4347 sGoogleApps.add("com.google.android.youtube");
4348 }
4349
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004350 /**
4351 * A UrlData class to abstract how the content will be set to WebView.
4352 * This base class uses loadUrl to show the content.
4353 */
Leon Scroggins6eac63e2010-03-15 18:19:14 -04004354 /* package */ static class UrlData {
Grace Kloba068e48b2010-01-26 18:11:27 -08004355 final String mUrl;
4356 final Map<String, String> mHeaders;
Leon Scroggins58d56c62010-01-28 15:12:40 -05004357 final Intent mVoiceIntent;
Grace Kloba60e095c2009-06-16 11:50:55 -07004358
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004359 UrlData(String url) {
4360 this.mUrl = url;
Grace Kloba068e48b2010-01-26 18:11:27 -08004361 this.mHeaders = null;
Leon Scroggins58d56c62010-01-28 15:12:40 -05004362 this.mVoiceIntent = null;
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004363 }
Grace Kloba60e095c2009-06-16 11:50:55 -07004364
Leon Scroggins58d56c62010-01-28 15:12:40 -05004365 UrlData(String url, Map<String, String> headers, Intent intent) {
Grace Kloba068e48b2010-01-26 18:11:27 -08004366 this.mUrl = url;
4367 this.mHeaders = headers;
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -05004368 if (RecognizerResultsIntent.ACTION_VOICE_SEARCH_RESULTS
4369 .equals(intent.getAction())) {
Leon Scroggins58d56c62010-01-28 15:12:40 -05004370 this.mVoiceIntent = intent;
4371 } else {
4372 this.mVoiceIntent = null;
4373 }
Grace Kloba60e095c2009-06-16 11:50:55 -07004374 }
4375
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004376 boolean isEmpty() {
Leon Scroggins58d56c62010-01-28 15:12:40 -05004377 return mVoiceIntent == null && (mUrl == null || mUrl.length() == 0);
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004378 }
4379
Leon Scroggins92472e82010-02-17 16:32:28 -05004380 /**
4381 * Load this UrlData into the given Tab. Use loadUrlDataIn to update
4382 * the title bar as well.
4383 */
Leon Scroggins58d56c62010-01-28 15:12:40 -05004384 public void loadIn(Tab t) {
4385 if (mVoiceIntent != null) {
4386 t.activateVoiceSearchMode(mVoiceIntent);
4387 } else {
4388 t.getWebView().loadUrl(mUrl, mHeaders);
4389 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004390 }
4391 };
4392
Leon Scroggins1f005d32009-08-10 17:36:42 -04004393 /* package */ static final UrlData EMPTY_URL_DATA = new UrlData(null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004394}