blob: e144f99f074c216e3bda70c2cf2d88b1c0e3073f [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 Kolb3f65c382010-08-20 15:31:16 -070019import com.android.browser.ScrollWebView.ScrollListener;
20import com.android.common.Search;
21import com.android.common.speech.LoggingEvents;
22
Michael Kolbed217742010-08-10 17:52:34 -070023import android.app.ActionBar;
The Android Open Source Project0c908882009-03-03 19:32:16 -080024import android.app.Activity;
The Android Open Source Project0c908882009-03-03 19:32:16 -080025import android.app.AlertDialog;
26import android.app.ProgressDialog;
27import android.app.SearchManager;
28import android.content.ActivityNotFoundException;
29import android.content.BroadcastReceiver;
Dianne Hackborn80f32622010-08-05 14:17:53 -070030import android.content.ClipboardManager;
The Android Open Source Project0c908882009-03-03 19:32:16 -080031import android.content.ComponentName;
Leon Scroggins58d56c62010-01-28 15:12:40 -050032import android.content.ContentProvider;
33import android.content.ContentProviderClient;
The Android Open Source Project0c908882009-03-03 19:32:16 -080034import android.content.ContentResolver;
Leon Scrogginsb6b7f9e2009-06-18 12:05:28 -040035import android.content.ContentUris;
The Android Open Source Project0c908882009-03-03 19:32:16 -080036import android.content.ContentValues;
37import android.content.Context;
38import android.content.DialogInterface;
39import android.content.Intent;
40import android.content.IntentFilter;
Grace Klobab4da0ad2009-05-14 14:45:40 -070041import android.content.pm.PackageInfo;
The Android Open Source Project0c908882009-03-03 19:32:16 -080042import android.content.pm.PackageManager;
43import android.content.pm.ResolveInfo;
The Android Open Source Project0c908882009-03-03 19:32:16 -080044import android.content.res.Configuration;
45import android.content.res.Resources;
46import android.database.Cursor;
The Android Open Source Project0c908882009-03-03 19:32:16 -080047import android.graphics.Bitmap;
Andrei Popescu540035d2009-09-18 18:59:20 +010048import android.graphics.BitmapFactory;
The Android Open Source Project0c908882009-03-03 19:32:16 -080049import android.graphics.Canvas;
The Android Open Source Project0c908882009-03-03 19:32:16 -080050import android.graphics.Picture;
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -040051import android.graphics.PixelFormat;
The Android Open Source Project0c908882009-03-03 19:32:16 -080052import android.graphics.drawable.Drawable;
The Android Open Source Project0c908882009-03-03 19:32:16 -080053import android.net.ConnectivityManager;
Andrei Popescu56199cc2010-01-12 22:39:16 +000054import android.net.NetworkInfo;
The Android Open Source Project0c908882009-03-03 19:32:16 -080055import android.net.Uri;
56import android.net.WebAddress;
The Android Open Source Project0c908882009-03-03 19:32:16 -080057import android.net.http.SslCertificate;
58import android.net.http.SslError;
59import android.os.AsyncTask;
60import android.os.Bundle;
61import android.os.Debug;
62import android.os.Environment;
63import android.os.Handler;
The Android Open Source Project0c908882009-03-03 19:32:16 -080064import android.os.Message;
65import android.os.PowerManager;
66import android.os.Process;
The Android Open Source Project0c908882009-03-03 19:32:16 -080067import android.os.SystemClock;
The Android Open Source Project0c908882009-03-03 19:32:16 -080068import android.provider.Browser;
Jeff Hamilton8ce956c2010-08-17 11:13:53 -050069import android.provider.BrowserContract;
Cary Clark5e335a32009-09-22 14:53:11 -040070import android.provider.ContactsContract;
Michael Kolba2b2ba82010-08-04 17:54:03 -070071import android.provider.ContactsContract.Intents.Insert;
The Android Open Source Project0c908882009-03-03 19:32:16 -080072import android.provider.Downloads;
73import android.provider.MediaStore;
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -050074import android.speech.RecognizerResultsIntent;
The Android Open Source Project0c908882009-03-03 19:32:16 -080075import android.text.TextUtils;
76import android.text.format.DateFormat;
The Android Open Source Project0c908882009-03-03 19:32:16 -080077import android.util.Log;
Dianne Hackborn385effd2010-02-24 20:03:04 -080078import android.util.Patterns;
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -040079import android.view.ActionMode;
The Android Open Source Project0c908882009-03-03 19:32:16 -080080import android.view.ContextMenu;
Michael Kolba2b2ba82010-08-04 17:54:03 -070081import android.view.ContextMenu.ContextMenuInfo;
The Android Open Source Project0c908882009-03-03 19:32:16 -080082import android.view.Gravity;
83import android.view.KeyEvent;
84import android.view.LayoutInflater;
85import android.view.Menu;
86import android.view.MenuInflater;
87import android.view.MenuItem;
Michael Kolba2b2ba82010-08-04 17:54:03 -070088import android.view.MenuItem.OnMenuItemClickListener;
Michael Kolb3f65c382010-08-20 15:31:16 -070089import android.view.MotionEvent;
The Android Open Source Project0c908882009-03-03 19:32:16 -080090import android.view.View;
91import android.view.ViewGroup;
92import android.view.Window;
93import android.view.WindowManager;
Svetoslav Ganov2b345992010-05-06 06:13:54 -070094import android.view.accessibility.AccessibilityManager;
The Android Open Source Project0c908882009-03-03 19:32:16 -080095import android.webkit.CookieManager;
96import android.webkit.CookieSyncManager;
97import android.webkit.DownloadListener;
98import android.webkit.HttpAuthHandler;
Grace Klobab4da0ad2009-05-14 14:45:40 -070099import android.webkit.PluginManager;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800100import android.webkit.SslErrorHandler;
101import android.webkit.URLUtil;
Leon Clarkecb6cc862009-09-29 18:35:13 +0100102import android.webkit.ValueCallback;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800103import android.webkit.WebChromeClient;
104import android.webkit.WebHistoryItem;
105import android.webkit.WebIconDatabase;
106import android.webkit.WebView;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800107import android.widget.EditText;
108import android.widget.FrameLayout;
109import android.widget.LinearLayout;
110import android.widget.TextView;
111import android.widget.Toast;
112
Leon Scrogginsb6b7f9e2009-06-18 12:05:28 -0400113import java.io.ByteArrayOutputStream;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800114import java.io.File;
Ben Murdoch4f75ba22009-10-27 11:48:28 +0000115import java.io.IOException;
116import java.io.InputStream;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800117import java.net.MalformedURLException;
Dianne Hackborn99189432009-06-17 18:06:18 -0700118import java.net.URISyntaxException;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800119import java.net.URL;
120import java.net.URLEncoder;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800121import java.util.Date;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800122import java.util.HashMap;
Andrei Popescu30995e72010-02-09 16:59:58 +0000123import java.util.HashSet;
Grace Kloba00f54c52010-01-27 14:53:51 -0800124import java.util.Iterator;
Andrei Popescu30995e72010-02-09 16:59:58 +0000125import java.util.List;
Grace Kloba068e48b2010-01-26 18:11:27 -0800126import java.util.Map;
Andrei Popescu30995e72010-02-09 16:59:58 +0000127import java.util.Set;
Michael Kolbfe251992010-07-08 15:41:55 -0700128import java.util.Vector;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800129import java.util.regex.Matcher;
130import java.util.regex.Pattern;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800131
132public class BrowserActivity extends Activity
Shimeng (Simon) Wang98d5fce2010-03-16 13:23:39 -0700133 implements View.OnCreateContextMenuListener, DownloadListener {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800134
Dave Bort31a6d1c2009-04-13 15:56:49 -0700135 /* Define some aliases to make these debugging flags easier to refer to.
136 * This file imports android.provider.Browser, so we can't just refer to "Browser.DEBUG".
137 */
138 private final static boolean DEBUG = com.android.browser.Browser.DEBUG;
139 private final static boolean LOGV_ENABLED = com.android.browser.Browser.LOGV_ENABLED;
140 private final static boolean LOGD_ENABLED = com.android.browser.Browser.LOGD_ENABLED;
141
Satish Sampath565505b2009-05-29 15:37:27 +0100142 // These are single-character shortcuts for searching popular sources.
143 private static final int SHORTCUT_INVALID = 0;
144 private static final int SHORTCUT_GOOGLE_SEARCH = 1;
145 private static final int SHORTCUT_WIKIPEDIA_SEARCH = 2;
146 private static final int SHORTCUT_DICTIONARY_SEARCH = 3;
147 private static final int SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH = 4;
148
Cary Clarka9771242009-08-11 16:42:26 -0400149 private static class ClearThumbnails extends AsyncTask<File, Void, Void> {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800150 @Override
151 public Void doInBackground(File... files) {
152 if (files != null) {
153 for (File f : files) {
Cary Clarkd6be1752009-08-12 12:56:42 -0400154 if (!f.delete()) {
155 Log.e(LOGTAG, f.getPath() + " was not deleted");
156 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800157 }
158 }
159 return null;
160 }
161 }
162
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400163 /**
164 * This layout holds everything you see below the status bar, including the
165 * error console, the custom view container, and the webviews.
166 */
167 private FrameLayout mBrowserFrameLayout;
Leon Scroggins81db3662009-06-04 17:45:11 -0400168
Leon Scrogginsd746a942010-05-19 13:21:44 -0400169 private boolean mXLargeScreenSize;
170
Jeff Davidson43610292010-07-16 16:03:58 -0700171 private Boolean mIsProviderPresent = null;
172 private Uri mRlzUri = null;
173
Grace Kloba22ac16e2009-10-07 18:00:23 -0700174 @Override
175 public void onCreate(Bundle icicle) {
Dave Bort31a6d1c2009-04-13 15:56:49 -0700176 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800177 Log.v(LOGTAG, this + " onStart");
178 }
179 super.onCreate(icicle);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800180 // test the browser in OpenGL
181 // requestWindowFeature(Window.FEATURE_OPENGL);
182
Mike Reedd334bf52010-01-26 15:21:44 -0500183 // enable this to test the browser in 32bit
184 if (false) {
185 getWindow().setFormat(PixelFormat.RGBX_8888);
186 BitmapFactory.setDefaultConfig(Bitmap.Config.ARGB_8888);
187 }
188
Svetoslav Ganov2b345992010-05-06 06:13:54 -0700189 if (AccessibilityManager.getInstance(this).isEnabled()) {
190 setDefaultKeyMode(DEFAULT_KEYS_DISABLE);
191 } else {
192 setDefaultKeyMode(DEFAULT_KEYS_SEARCH_LOCAL);
193 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800194
195 mResolver = getContentResolver();
196
Grace Kloba0923d692009-09-23 21:37:25 -0700197 // If this was a web search request, pass it on to the default web
198 // search provider and finish this activity.
199 if (handleWebSearchIntent(getIntent())) {
200 finish();
201 return;
202 }
203
The Android Open Source Project0c908882009-03-03 19:32:16 -0800204 mSecLockIcon = Resources.getSystem().getDrawable(
205 android.R.drawable.ic_secure);
206 mMixLockIcon = Resources.getSystem().getDrawable(
207 android.R.drawable.ic_partial_secure);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800208
Michael Kolbed217742010-08-10 17:52:34 -0700209 // Create the tab control and our initial tab
210 mTabControl = new TabControl(this);
211
212 mXLargeScreenSize = (getResources().getConfiguration().screenLayout
213 & Configuration.SCREENLAYOUT_SIZE_MASK)
214 == Configuration.SCREENLAYOUT_SIZE_XLARGE;
215
Leon Scroggins81db3662009-06-04 17:45:11 -0400216 FrameLayout frameLayout = (FrameLayout) getWindow().getDecorView()
217 .findViewById(com.android.internal.R.id.content);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400218 mBrowserFrameLayout = (FrameLayout) LayoutInflater.from(this)
219 .inflate(R.layout.custom_screen, null);
220 mContentView = (FrameLayout) mBrowserFrameLayout.findViewById(
221 R.id.main_content);
222 mErrorConsoleContainer = (LinearLayout) mBrowserFrameLayout
223 .findViewById(R.id.error_console);
224 mCustomViewContainer = (FrameLayout) mBrowserFrameLayout
225 .findViewById(R.id.fullscreen_custom_content);
226 frameLayout.addView(mBrowserFrameLayout, COVER_SCREEN_PARAMS);
Michael Kolbe0a36662010-06-29 10:37:12 -0700227
Leon Scrogginsd746a942010-05-19 13:21:44 -0400228 if (mXLargeScreenSize) {
Michael Kolba2b2ba82010-08-04 17:54:03 -0700229 mTitleBar = new TitleBarXLarge(this);
230 mTitleBar.setProgress(100);
231 mFakeTitleBar = new TitleBarXLarge(this);
Michael Kolbed217742010-08-10 17:52:34 -0700232 ActionBar actionBar = getActionBar();
Michael Kolba2b2ba82010-08-04 17:54:03 -0700233 mTabBar = new TabBar(this, mTabControl, (TitleBarXLarge) mFakeTitleBar);
Michael Kolbed217742010-08-10 17:52:34 -0700234 actionBar.setCustomNavigationMode(mTabBar);
Leon Scrogginsd746a942010-05-19 13:21:44 -0400235 } else {
Leon Scroggins571b3762010-05-26 10:25:01 -0400236 mTitleBar = new TitleBar(this);
Leon Scrogginsd746a942010-05-19 13:21:44 -0400237 // mTitleBar will be always be shown in the fully loaded mode on
238 // phone
239 mTitleBar.setProgress(100);
Leon Scrogginsd746a942010-05-19 13:21:44 -0400240 mFakeTitleBar = new TitleBar(this);
241 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800242
The Android Open Source Project0c908882009-03-03 19:32:16 -0800243 // Open the icon database and retain all the bookmark urls for favicons
244 retainIconsOnStartup();
245
246 // Keep a settings instance handy.
247 mSettings = BrowserSettings.getInstance();
248 mSettings.setTabControl(mTabControl);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800249
250 PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
251 mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Browser");
252
Patrick Scott6adacc92010-03-05 08:24:51 -0500253 // Find out if the network is currently up.
254 ConnectivityManager cm = (ConnectivityManager) getSystemService(
255 Context.CONNECTIVITY_SERVICE);
256 NetworkInfo info = cm.getActiveNetworkInfo();
257 if (info != null) {
258 mIsNetworkUp = info.isAvailable();
259 }
260
Grace Klobaa34f6862009-07-31 16:28:17 -0700261 /* enables registration for changes in network status from
262 http stack */
263 mNetworkStateChangedFilter = new IntentFilter();
264 mNetworkStateChangedFilter.addAction(
265 ConnectivityManager.CONNECTIVITY_ACTION);
266 mNetworkStateIntentReceiver = new BroadcastReceiver() {
267 @Override
268 public void onReceive(Context context, Intent intent) {
269 if (intent.getAction().equals(
270 ConnectivityManager.CONNECTIVITY_ACTION)) {
Andrei Popescue4c98462010-02-19 15:44:13 +0000271
272 NetworkInfo info = intent.getParcelableExtra(
273 ConnectivityManager.EXTRA_NETWORK_INFO);
274 String typeName = info.getTypeName();
275 String subtypeName = info.getSubtypeName();
276 sendNetworkType(typeName.toLowerCase(),
277 (subtypeName != null ? subtypeName.toLowerCase() : ""));
278
279 onNetworkToggle(info.isAvailable());
Grace Klobaa34f6862009-07-31 16:28:17 -0700280 }
281 }
282 };
283
Grace Kloba615c6c92009-08-03 10:22:44 -0700284 IntentFilter filter = new IntentFilter(Intent.ACTION_PACKAGE_ADDED);
285 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
286 filter.addDataScheme("package");
287 mPackageInstallationReceiver = new BroadcastReceiver() {
288 @Override
289 public void onReceive(Context context, Intent intent) {
290 final String action = intent.getAction();
291 final String packageName = intent.getData()
292 .getSchemeSpecificPart();
293 final boolean replacing = intent.getBooleanExtra(
294 Intent.EXTRA_REPLACING, false);
295 if (Intent.ACTION_PACKAGE_REMOVED.equals(action) && replacing) {
296 // if it is replacing, refreshPlugins() when adding
297 return;
298 }
Andrei Popescu30995e72010-02-09 16:59:58 +0000299
300 if (sGoogleApps.contains(packageName)) {
301 BrowserActivity.this.packageChanged(packageName,
302 Intent.ACTION_PACKAGE_ADDED.equals(action));
303 }
304
Grace Kloba615c6c92009-08-03 10:22:44 -0700305 PackageManager pm = BrowserActivity.this.getPackageManager();
306 PackageInfo pkgInfo = null;
307 try {
308 pkgInfo = pm.getPackageInfo(packageName,
309 PackageManager.GET_PERMISSIONS);
310 } catch (PackageManager.NameNotFoundException e) {
311 return;
312 }
313 if (pkgInfo != null) {
314 String permissions[] = pkgInfo.requestedPermissions;
315 if (permissions == null) {
316 return;
317 }
318 boolean permissionOk = false;
319 for (String permit : permissions) {
320 if (PluginManager.PLUGIN_PERMISSION.equals(permit)) {
321 permissionOk = true;
322 break;
323 }
324 }
325 if (permissionOk) {
326 PluginManager.getInstance(BrowserActivity.this)
Grace Klobae56a0f22010-05-26 17:31:02 -0700327 .refreshPlugins(true);
Grace Kloba615c6c92009-08-03 10:22:44 -0700328 }
329 }
330 }
331 };
332 registerReceiver(mPackageInstallationReceiver, filter);
333
The Android Open Source Project0c908882009-03-03 19:32:16 -0800334 if (!mTabControl.restoreState(icicle)) {
335 // clear up the thumbnail directory if we can't restore the state as
336 // none of the files in the directory are referenced any more.
337 new ClearThumbnails().execute(
338 mTabControl.getThumbnailDir().listFiles());
Grace Klobaaab3f092009-07-30 12:29:51 -0700339 // there is no quit on Android. But if we can't restore the state,
340 // we can treat it as a new Browser, remove the old session cookies.
341 CookieManager.getInstance().removeSessionCookie();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800342 final Intent intent = getIntent();
343 final Bundle extra = intent.getExtras();
344 // Create an initial tab.
345 // If the intent is ACTION_VIEW and data is not null, the Browser is
346 // invoked to view the content by another application. In this case,
347 // the tab will be close when exit.
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700348 UrlData urlData = getUrlDataFromIntent(intent);
349
Leon Scroggins58d56c62010-01-28 15:12:40 -0500350 String action = intent.getAction();
Grace Kloba22ac16e2009-10-07 18:00:23 -0700351 final Tab t = mTabControl.createNewTab(
Leon Scroggins58d56c62010-01-28 15:12:40 -0500352 (Intent.ACTION_VIEW.equals(action) &&
353 intent.getData() != null)
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -0500354 || RecognizerResultsIntent.ACTION_VOICE_SEARCH_RESULTS
355 .equals(action),
Elliott Slaughterf0f03952010-07-14 18:10:36 -0700356 intent.getStringExtra(Browser.EXTRA_APPLICATION_ID),
357 urlData.mUrl, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800358 mTabControl.setCurrentTab(t);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800359 attachTabToContentView(t);
360 WebView webView = t.getWebView();
361 if (extra != null) {
362 int scale = extra.getInt(Browser.INITIAL_ZOOM_LEVEL, 0);
363 if (scale > 0 && scale <= 1000) {
364 webView.setInitialScale(scale);
365 }
366 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800367
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700368 if (urlData.isEmpty()) {
Shimeng (Simon) Wang98d5fce2010-03-16 13:23:39 -0700369 loadUrl(webView, mSettings.getHomePage());
The Android Open Source Project0c908882009-03-03 19:32:16 -0800370 } else {
Patrick Scott9d53da02010-02-19 10:19:01 -0500371 loadUrlDataIn(t, urlData);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800372 }
373 } else {
374 // TabControl.restoreState() will create a new tab even if
Leon Scroggins1f005d32009-08-10 17:36:42 -0400375 // restoring the state fails.
The Android Open Source Project0c908882009-03-03 19:32:16 -0800376 attachTabToContentView(mTabControl.getCurrentTab());
377 }
Grace Kloba615c6c92009-08-03 10:22:44 -0700378
Cary Clarkb4b83182010-07-01 12:36:56 -0400379 // Delete old thumbnails to save space
380 File dir = mTabControl.getThumbnailDir();
381 if (dir.exists()) {
382 for (String child : dir.list()) {
383 File f = new File(dir, child);
384 f.delete();
385 }
386 }
387
Feng Qianb3c02da2009-06-29 15:58:08 -0700388 // Read JavaScript flags if it exists.
389 String jsFlags = mSettings.getJsFlags();
390 if (jsFlags.trim().length() != 0) {
391 mTabControl.getCurrentWebView().setJsFlags(jsFlags);
392 }
Andrei Popescu30995e72010-02-09 16:59:58 +0000393 // Work out which packages are installed on the system.
394 getInstalledPackages();
Bjorn Bringerta7611812010-03-24 11:12:02 +0000395
396 // Start watching the default geolocation permissions
397 mSystemAllowGeolocationOrigins
398 = new SystemAllowGeolocationOrigins(getApplicationContext());
399 mSystemAllowGeolocationOrigins.start();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800400 }
401
Michael Kolba2b2ba82010-08-04 17:54:03 -0700402 ScrollListener getScrollListener() {
403 return mTabBar;
404 }
405
Leon Scroggins58d56c62010-01-28 15:12:40 -0500406 /**
407 * Feed the previously stored results strings to the BrowserProvider so that
408 * the SearchDialog will show them instead of the standard searches.
409 * @param result String to show on the editable line of the SearchDialog.
410 */
411 /* package */ void showVoiceSearchResults(String result) {
412 ContentProviderClient client = mResolver.acquireContentProviderClient(
413 Browser.BOOKMARKS_URI);
414 ContentProvider prov = client.getLocalContentProvider();
415 BrowserProvider bp = (BrowserProvider) prov;
416 bp.setQueryResults(mTabControl.getCurrentTab().getVoiceSearchResults());
417 client.release();
418
Leon Scrogginsfbb3f152010-03-09 17:26:56 -0500419 Bundle bundle = createGoogleSearchSourceBundle(
420 GOOGLE_SEARCH_SOURCE_SEARCHKEY);
421 bundle.putBoolean(SearchManager.CONTEXT_IS_VOICE, true);
422 startSearch(result, false, bundle, false);
Leon Scroggins58d56c62010-01-28 15:12:40 -0500423 }
424
The Android Open Source Project0c908882009-03-03 19:32:16 -0800425 @Override
426 protected void onNewIntent(Intent intent) {
Grace Kloba22ac16e2009-10-07 18:00:23 -0700427 Tab current = mTabControl.getCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800428 // When a tab is closed on exit, the current tab index is set to -1.
429 // Reset before proceed as Browser requires the current tab to be set.
430 if (current == null) {
431 // Try to reset the tab in case the index was incorrect.
432 current = mTabControl.getTab(0);
433 if (current == null) {
434 // No tabs at all so just ignore this intent.
435 return;
436 }
437 mTabControl.setCurrentTab(current);
438 attachTabToContentView(current);
439 resetTitleAndIcon(current.getWebView());
440 }
441 final String action = intent.getAction();
442 final int flags = intent.getFlags();
443 if (Intent.ACTION_MAIN.equals(action) ||
444 (flags & Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY) != 0) {
445 // just resume the browser
446 return;
447 }
Leon Scrogginsb8a844d2010-03-18 15:06:15 -0400448 // In case the SearchDialog is open.
449 ((SearchManager) getSystemService(Context.SEARCH_SERVICE))
450 .stopSearch();
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -0500451 boolean activateVoiceSearch = RecognizerResultsIntent
452 .ACTION_VOICE_SEARCH_RESULTS.equals(action);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800453 if (Intent.ACTION_VIEW.equals(action)
454 || Intent.ACTION_SEARCH.equals(action)
455 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
Leon Scroggins58d56c62010-01-28 15:12:40 -0500456 || Intent.ACTION_WEB_SEARCH.equals(action)
457 || activateVoiceSearch) {
Leon Scroggins3b18ce32010-02-08 17:35:59 -0500458 if (current.isInVoiceSearchMode()) {
459 String title = current.getVoiceDisplayTitle();
460 if (title != null && title.equals(intent.getStringExtra(
461 SearchManager.QUERY))) {
462 // The user submitted the same search as the last voice
463 // search, so do nothing.
464 return;
465 }
Leon Scroggins1fe13a52010-02-09 15:31:26 -0500466 if (Intent.ACTION_SEARCH.equals(action)
467 && current.voiceSearchSourceIsGoogle()) {
468 Intent logIntent = new Intent(
469 LoggingEvents.ACTION_LOG_EVENT);
470 logIntent.putExtra(LoggingEvents.EXTRA_EVENT,
471 LoggingEvents.VoiceSearch.QUERY_UPDATED);
472 logIntent.putExtra(
473 LoggingEvents.VoiceSearch.EXTRA_QUERY_UPDATED_VALUE,
474 intent.getDataString());
475 sendBroadcast(logIntent);
476 // Note, onPageStarted will revert the voice title bar
477 // When http://b/issue?id=2379215 is fixed, we should update
478 // the title bar here.
479 }
Leon Scroggins3b18ce32010-02-08 17:35:59 -0500480 }
Satish Sampath565505b2009-05-29 15:37:27 +0100481 // If this was a search request (e.g. search query directly typed into the address bar),
482 // pass it on to the default web search provider.
483 if (handleWebSearchIntent(intent)) {
484 return;
485 }
486
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700487 UrlData urlData = getUrlDataFromIntent(intent);
488 if (urlData.isEmpty()) {
489 urlData = new UrlData(mSettings.getHomePage());
The Android Open Source Project0c908882009-03-03 19:32:16 -0800490 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700491
Grace Klobacc634032009-07-28 15:58:19 -0700492 final String appId = intent
493 .getStringExtra(Browser.EXTRA_APPLICATION_ID);
Leon Scroggins47208682010-04-07 17:59:48 -0400494 if ((Intent.ACTION_VIEW.equals(action)
495 // If a voice search has no appId, it means that it came
496 // from the browser. In that case, reuse the current tab.
497 || (activateVoiceSearch && appId != null))
Grace Klobacc634032009-07-28 15:58:19 -0700498 && !getPackageName().equals(appId)
499 && (flags & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0) {
Grace Kloba22ac16e2009-10-07 18:00:23 -0700500 Tab appTab = mTabControl.getTabFromId(appId);
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700501 if (appTab != null) {
502 Log.i(LOGTAG, "Reusing tab for " + appId);
503 // Dismiss the subwindow if applicable.
504 dismissSubWindow(appTab);
505 // Since we might kill the WebView, remove it from the
506 // content view first.
507 removeTabFromContentView(appTab);
508 // Recreate the main WebView after destroying the old one.
509 // If the WebView has the same original url and is on that
510 // page, it can be reused.
511 boolean needsLoad =
Leon Scroggins6eac63e2010-03-15 18:19:14 -0400512 mTabControl.recreateWebView(appTab, urlData);
Ben Murdochbff2d602009-07-01 20:19:05 +0100513
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700514 if (current != appTab) {
Leon Scroggins1f005d32009-08-10 17:36:42 -0400515 switchToTab(mTabControl.getTabIndex(appTab));
516 if (needsLoad) {
Patrick Scott9d53da02010-02-19 10:19:01 -0500517 loadUrlDataIn(appTab, urlData);
Leon Scroggins1f005d32009-08-10 17:36:42 -0400518 }
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700519 } else {
Leon Scroggins1f005d32009-08-10 17:36:42 -0400520 // If the tab was the current tab, we have to attach
521 // it to the view system again.
522 attachTabToContentView(appTab);
523 if (needsLoad) {
Patrick Scott9d53da02010-02-19 10:19:01 -0500524 loadUrlDataIn(appTab, urlData);
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700525 }
526 }
527 return;
Patrick Scottcd115892009-07-16 09:42:58 -0400528 } else {
529 // No matching application tab, try to find a regular tab
530 // with a matching url.
531 appTab = mTabControl.findUnusedTabWithUrl(urlData.mUrl);
Leon Scroggins25515f82009-08-19 15:31:58 -0400532 if (appTab != null) {
533 if (current != appTab) {
534 switchToTab(mTabControl.getTabIndex(appTab));
535 }
536 // Otherwise, we are already viewing the correct tab.
Patrick Scottcd115892009-07-16 09:42:58 -0400537 } else {
538 // if FLAG_ACTIVITY_BROUGHT_TO_FRONT flag is on, the url
539 // will be opened in a new tab unless we have reached
540 // MAX_TABS. Then the url will be opened in the current
541 // tab. If a new tab is created, it will have "true" for
542 // exit on close.
Leon Scroggins1f005d32009-08-10 17:36:42 -0400543 openTabAndShow(urlData, true, appId);
Patrick Scottcd115892009-07-16 09:42:58 -0400544 }
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700545 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800546 } else {
Grace Kloba638d3f42009-11-23 10:35:04 -0800547 if (!urlData.isEmpty()
548 && urlData.mUrl.startsWith("about:debug")) {
549 if ("about:debug.dom".equals(urlData.mUrl)) {
550 current.getWebView().dumpDomTree(false);
551 } else if ("about:debug.dom.file".equals(urlData.mUrl)) {
552 current.getWebView().dumpDomTree(true);
553 } else if ("about:debug.render".equals(urlData.mUrl)) {
554 current.getWebView().dumpRenderTree(false);
555 } else if ("about:debug.render.file".equals(urlData.mUrl)) {
556 current.getWebView().dumpRenderTree(true);
557 } else if ("about:debug.display".equals(urlData.mUrl)) {
558 current.getWebView().dumpDisplayTree();
Mike Reed9b78e1d2010-01-13 14:40:52 -0800559 } else if (urlData.mUrl.startsWith("about:debug.drag")) {
560 int index = urlData.mUrl.codePointAt(16) - '0';
561 if (index <= 0 || index > 9) {
562 current.getWebView().setDragTracker(null);
563 } else {
564 current.getWebView().setDragTracker(new MeshTracker(index));
565 }
Grace Kloba638d3f42009-11-23 10:35:04 -0800566 } else {
567 mSettings.toggleDebugSettings();
568 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800569 return;
570 }
Leon Scroggins1f005d32009-08-10 17:36:42 -0400571 // Get rid of the subwindow if it exists
572 dismissSubWindow(current);
Leon Scroggins8588d152010-04-15 11:01:53 -0400573 // If the current Tab is being used as an application tab,
574 // remove the association, since the new Intent means that it is
575 // no longer associated with that application.
576 current.setAppId(null);
Patrick Scott9d53da02010-02-19 10:19:01 -0500577 loadUrlDataIn(current, urlData);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800578 }
579 }
580 }
581
Satish Sampath565505b2009-05-29 15:37:27 +0100582 private int parseUrlShortcut(String url) {
583 if (url == null) return SHORTCUT_INVALID;
584
585 // FIXME: quick search, need to be customized by setting
586 if (url.length() > 2 && url.charAt(1) == ' ') {
587 switch (url.charAt(0)) {
588 case 'g': return SHORTCUT_GOOGLE_SEARCH;
589 case 'w': return SHORTCUT_WIKIPEDIA_SEARCH;
590 case 'd': return SHORTCUT_DICTIONARY_SEARCH;
591 case 'l': return SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH;
592 }
593 }
594 return SHORTCUT_INVALID;
595 }
596
597 /**
598 * Launches the default web search activity with the query parameters if the given intent's data
599 * are identified as plain search terms and not URLs/shortcuts.
600 * @return true if the intent was handled and web search activity was launched, false if not.
601 */
602 private boolean handleWebSearchIntent(Intent intent) {
603 if (intent == null) return false;
604
605 String url = null;
606 final String action = intent.getAction();
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -0500607 if (RecognizerResultsIntent.ACTION_VOICE_SEARCH_RESULTS.equals(
608 action)) {
Leon Scroggins58d56c62010-01-28 15:12:40 -0500609 return false;
610 }
Satish Sampath565505b2009-05-29 15:37:27 +0100611 if (Intent.ACTION_VIEW.equals(action)) {
Grace Kloba1e705052009-09-29 13:13:36 -0700612 Uri data = intent.getData();
613 if (data != null) url = data.toString();
Satish Sampath565505b2009-05-29 15:37:27 +0100614 } else if (Intent.ACTION_SEARCH.equals(action)
615 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
616 || Intent.ACTION_WEB_SEARCH.equals(action)) {
617 url = intent.getStringExtra(SearchManager.QUERY);
618 }
Bjorn Bringert04851702009-09-22 10:36:01 +0100619 return handleWebSearchRequest(url, intent.getBundleExtra(SearchManager.APP_DATA),
620 intent.getStringExtra(SearchManager.EXTRA_DATA_KEY));
Satish Sampath565505b2009-05-29 15:37:27 +0100621 }
622
623 /**
624 * Launches the default web search activity with the query parameters if the given url string
625 * was identified as plain search terms and not URL/shortcut.
626 * @return true if the request was handled and web search activity was launched, false if not.
627 */
Bjorn Bringert04851702009-09-22 10:36:01 +0100628 private boolean handleWebSearchRequest(String inUrl, Bundle appData, String extraData) {
Satish Sampath565505b2009-05-29 15:37:27 +0100629 if (inUrl == null) return false;
630
631 // In general, we shouldn't modify URL from Intent.
632 // But currently, we get the user-typed URL from search box as well.
633 String url = fixUrl(inUrl).trim();
634
635 // URLs and site specific search shortcuts are handled by the regular flow of control, so
636 // return early.
Dan Egnor5ee906c2009-11-18 12:11:49 -0800637 if (Patterns.WEB_URL.matcher(url).matches()
Satish Sampathbc5b9f32009-06-04 18:21:40 +0100638 || ACCEPTED_URI_SCHEMA.matcher(url).matches()
Satish Sampath565505b2009-05-29 15:37:27 +0100639 || parseUrlShortcut(url) != SHORTCUT_INVALID) {
640 return false;
641 }
642
Leon Scroggins8d06e362010-03-24 14:45:57 -0400643 final ContentResolver cr = mResolver;
644 final String newUrl = url;
Elliott Slaughter627d96f2010-08-18 16:35:30 -0700645 if (mTabControl == null || !mTabControl.getCurrentWebView().isPrivateBrowsingEnabled()) {
Elliott Slaughterf0f03952010-07-14 18:10:36 -0700646 new AsyncTask<Void, Void, Void>() {
647 @Override
648 protected Void doInBackground(Void... unused) {
649 Browser.updateVisitedHistory(cr, newUrl, false);
650 Browser.addSearchUrl(cr, newUrl);
651 return null;
652 }
653 }.execute();
654 }
Satish Sampath565505b2009-05-29 15:37:27 +0100655
656 Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);
657 intent.addCategory(Intent.CATEGORY_DEFAULT);
658 intent.putExtra(SearchManager.QUERY, url);
Satish Sampath15e9f2d2009-06-23 22:29:49 +0100659 if (appData != null) {
660 intent.putExtra(SearchManager.APP_DATA, appData);
661 }
Bjorn Bringert04851702009-09-22 10:36:01 +0100662 if (extraData != null) {
663 intent.putExtra(SearchManager.EXTRA_DATA_KEY, extraData);
664 }
Grace Klobacc634032009-07-28 15:58:19 -0700665 intent.putExtra(Browser.EXTRA_APPLICATION_ID, getPackageName());
Satish Sampath565505b2009-05-29 15:37:27 +0100666 startActivity(intent);
667
668 return true;
669 }
670
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700671 private UrlData getUrlDataFromIntent(Intent intent) {
Leon Scroggins58d56c62010-01-28 15:12:40 -0500672 String url = "";
Grace Kloba068e48b2010-01-26 18:11:27 -0800673 Map<String, String> headers = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800674 if (intent != null) {
675 final String action = intent.getAction();
676 if (Intent.ACTION_VIEW.equals(action)) {
677 url = smartUrlFilter(intent.getData());
678 if (url != null && url.startsWith("content:")) {
679 /* Append mimetype so webview knows how to display */
680 String mimeType = intent.resolveType(getContentResolver());
681 if (mimeType != null) {
682 url += "?" + mimeType;
683 }
684 }
Grace Kloba068e48b2010-01-26 18:11:27 -0800685 if (url != null && url.startsWith("http")) {
Grace Kloba00f54c52010-01-27 14:53:51 -0800686 final Bundle pairs = intent
687 .getBundleExtra(Browser.EXTRA_HEADERS);
Grace Kloba2d508ed2010-01-28 11:39:15 -0800688 if (pairs != null && !pairs.isEmpty()) {
Grace Kloba00f54c52010-01-27 14:53:51 -0800689 Iterator<String> iter = pairs.keySet().iterator();
Grace Kloba068e48b2010-01-26 18:11:27 -0800690 headers = new HashMap<String, String>();
Grace Kloba00f54c52010-01-27 14:53:51 -0800691 while (iter.hasNext()) {
692 String key = iter.next();
693 headers.put(key, pairs.getString(key));
Grace Kloba068e48b2010-01-26 18:11:27 -0800694 }
695 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700696 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800697 } else if (Intent.ACTION_SEARCH.equals(action)
698 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
699 || Intent.ACTION_WEB_SEARCH.equals(action)) {
700 url = intent.getStringExtra(SearchManager.QUERY);
701 if (url != null) {
702 mLastEnteredUrl = url;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800703 // In general, we shouldn't modify URL from Intent.
704 // But currently, we get the user-typed URL from search box as well.
705 url = fixUrl(url);
706 url = smartUrlFilter(url);
Leon Scroggins8d06e362010-03-24 14:45:57 -0400707 final ContentResolver cr = mResolver;
708 final String newUrl = url;
709 new AsyncTask<Void, Void, Void>() {
Michael Kolbe0a36662010-06-29 10:37:12 -0700710 @Override
Leon Scroggins8d06e362010-03-24 14:45:57 -0400711 protected Void doInBackground(Void... unused) {
712 Browser.updateVisitedHistory(cr, newUrl, false);
713 return null;
714 }
715 }.execute();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800716 String searchSource = "&source=android-" + GOOGLE_SEARCH_SOURCE_SUGGEST + "&";
717 if (url.contains(searchSource)) {
718 String source = null;
719 final Bundle appData = intent.getBundleExtra(SearchManager.APP_DATA);
720 if (appData != null) {
Bjorn Bringert10d1cca2010-02-10 14:22:12 +0000721 source = appData.getString(Search.SOURCE);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800722 }
723 if (TextUtils.isEmpty(source)) {
724 source = GOOGLE_SEARCH_SOURCE_UNKNOWN;
725 }
726 url = url.replace(searchSource, "&source=android-"+source+"&");
727 }
728 }
729 }
730 }
Leon Scroggins58d56c62010-01-28 15:12:40 -0500731 return new UrlData(url, headers, intent);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800732 }
Leon Scroggins58d56c62010-01-28 15:12:40 -0500733 /* package */ void showVoiceTitleBar(String title) {
734 mTitleBar.setInVoiceMode(true);
Leon Scroggins58d56c62010-01-28 15:12:40 -0500735 mTitleBar.setDisplayTitle(title);
Michael Kolba2b2ba82010-08-04 17:54:03 -0700736 mFakeTitleBar.setInVoiceMode(true);
737 mFakeTitleBar.setDisplayTitle(title);
Leon Scroggins58d56c62010-01-28 15:12:40 -0500738 }
739 /* package */ void revertVoiceTitleBar() {
740 mTitleBar.setInVoiceMode(false);
Leon Scroggins003a5dd2010-03-10 12:13:14 -0500741 mTitleBar.setDisplayTitle(mUrl);
Michael Kolba2b2ba82010-08-04 17:54:03 -0700742 mFakeTitleBar.setInVoiceMode(false);
743 mFakeTitleBar.setDisplayTitle(mUrl);
Leon Scroggins58d56c62010-01-28 15:12:40 -0500744 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800745 /* package */ static String fixUrl(String inUrl) {
Cary Clark652ff872009-09-10 13:34:44 -0400746 // FIXME: Converting the url to lower case
747 // duplicates functionality in smartUrlFilter().
748 // However, changing all current callers of fixUrl to
749 // call smartUrlFilter in addition may have unwanted
750 // consequences, and is deferred for now.
751 int colon = inUrl.indexOf(':');
752 boolean allLower = true;
753 for (int index = 0; index < colon; index++) {
754 char ch = inUrl.charAt(index);
755 if (!Character.isLetter(ch)) {
756 break;
757 }
758 allLower &= Character.isLowerCase(ch);
759 if (index == colon - 1 && !allLower) {
760 inUrl = inUrl.substring(0, colon).toLowerCase()
761 + inUrl.substring(colon);
762 }
763 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800764 if (inUrl.startsWith("http://") || inUrl.startsWith("https://"))
765 return inUrl;
766 if (inUrl.startsWith("http:") ||
767 inUrl.startsWith("https:")) {
768 if (inUrl.startsWith("http:/") || inUrl.startsWith("https:/")) {
769 inUrl = inUrl.replaceFirst("/", "//");
770 } else inUrl = inUrl.replaceFirst(":", "://");
771 }
772 return inUrl;
773 }
774
Grace Kloba22ac16e2009-10-07 18:00:23 -0700775 @Override
776 protected void onResume() {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800777 super.onResume();
Dave Bort31a6d1c2009-04-13 15:56:49 -0700778 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800779 Log.v(LOGTAG, "BrowserActivity.onResume: this=" + this);
780 }
781
782 if (!mActivityInPause) {
783 Log.e(LOGTAG, "BrowserActivity is already resumed.");
784 return;
785 }
786
Mike Reed7bfa63b2009-05-28 11:08:32 -0400787 mTabControl.resumeCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800788 mActivityInPause = false;
Mike Reed7bfa63b2009-05-28 11:08:32 -0400789 resumeWebViewTimers();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800790
791 if (mWakeLock.isHeld()) {
792 mHandler.removeMessages(RELEASE_WAKELOCK);
793 mWakeLock.release();
794 }
795
The Android Open Source Project0c908882009-03-03 19:32:16 -0800796 registerReceiver(mNetworkStateIntentReceiver,
797 mNetworkStateChangedFilter);
798 WebView.enablePlatformNotifications();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800799 }
800
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400801 /**
802 * Since the actual title bar is embedded in the WebView, and removing it
Leon Scrogginsfe87bd32009-10-06 10:10:00 -0400803 * would change its appearance, use a different TitleBar to show overlayed
804 * at the top of the screen, when the menu is open or the page is loading.
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400805 */
Michael Kolba2b2ba82010-08-04 17:54:03 -0700806 private TitleBarBase mFakeTitleBar;
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400807
808 /**
809 * Keeps track of whether the options menu is open. This is important in
810 * determining whether to show or hide the title bar overlay.
811 */
812 private boolean mOptionsMenuOpen;
813
814 /**
815 * Only meaningful when mOptionsMenuOpen is true. This variable keeps track
816 * of whether the configuration has changed. The first onMenuOpened call
817 * after a configuration change is simply a reopening of the same menu
818 * (i.e. mIconView did not change).
819 */
820 private boolean mConfigChanged;
821
822 /**
823 * Whether or not the options menu is in its smaller, icon menu form. When
824 * true, we want the title bar overlay to be up. When false, we do not.
825 * Only meaningful if mOptionsMenuOpen is true.
826 */
827 private boolean mIconView;
828
Leon Scrogginsa81a7642009-08-31 17:05:41 -0400829 @Override
830 public boolean onMenuOpened(int featureId, Menu menu) {
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400831 if (Window.FEATURE_OPTIONS_PANEL == featureId) {
832 if (mOptionsMenuOpen) {
833 if (mConfigChanged) {
834 // We do not need to make any changes to the state of the
835 // title bar, since the only thing that happened was a
836 // change in orientation
837 mConfigChanged = false;
838 } else {
839 if (mIconView) {
840 // Switching the menu to expanded view, so hide the
841 // title bar.
842 hideFakeTitleBar();
843 mIconView = false;
844 } else {
845 // Switching the menu back to icon view, so show the
846 // title bar once again.
847 showFakeTitleBar();
848 mIconView = true;
849 }
850 }
851 } else {
852 // The options menu is closed, so open it, and show the title
853 showFakeTitleBar();
854 mOptionsMenuOpen = true;
855 mConfigChanged = false;
856 mIconView = true;
857 }
858 }
Leon Scrogginsa81a7642009-08-31 17:05:41 -0400859 return true;
860 }
861
Michael Kolba2b2ba82010-08-04 17:54:03 -0700862 void showFakeTitleBar() {
863 if (!isFakeTitleBarShowing() && mActiveTabsPage == null && !mActivityInPause) {
Grace Kloba847c25b2010-03-30 16:00:26 -0700864 WebView mainView = mTabControl.getCurrentWebView();
865 // if there is no current WebView, don't show the faked title bar;
Grace Kloba65190702010-04-02 23:37:26 -0700866 if (mainView == null) {
Cary Clarka0464552009-09-29 13:00:45 -0400867 return;
868 }
Leon Scroggins79e36d92010-04-29 16:01:46 +0100869 // Do not need to check for null, since the current tab will have
870 // at least a main WebView, or we would have returned above.
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -0400871 if (isInCustomActionMode()) {
872 // Do not show the fake title bar, while a custom ActionMode
873 // (i.e. find or select) is showing.
Leon Scroggins79e36d92010-04-29 16:01:46 +0100874 return;
875 }
Michael Kolba2b2ba82010-08-04 17:54:03 -0700876 if (mXLargeScreenSize) {
877 mContentView.addView(mFakeTitleBar);
878 mTabBar.onShowTitleBar();
879 } else {
880 WindowManager manager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400881
Michael Kolba2b2ba82010-08-04 17:54:03 -0700882 // Add the title bar to the window manager so it can receive
883 // touches
884 // while the menu is up
885 WindowManager.LayoutParams params =
886 new WindowManager.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
887 ViewGroup.LayoutParams.WRAP_CONTENT,
888 WindowManager.LayoutParams.TYPE_APPLICATION,
889 WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
890 PixelFormat.TRANSLUCENT);
891 params.gravity = Gravity.TOP;
892 boolean atTop = mainView.getScrollY() == 0;
893 params.windowAnimations = atTop ? 0 : R.style.TitleBar;
894 manager.addView(mFakeTitleBar, params);
895 }
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400896 }
897 }
898
899 @Override
900 public void onOptionsMenuClosed(Menu menu) {
901 mOptionsMenuOpen = false;
Leon Scrogginsa27ff192009-09-14 12:58:04 -0400902 if (!mInLoad) {
903 hideFakeTitleBar();
904 } else if (!mIconView) {
905 // The page is currently loading, and we are in expanded mode, so
906 // we were not showing the menu. Show it once again. It will be
907 // removed when the page finishes.
908 showFakeTitleBar();
909 }
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400910 }
Grace Kloba22ac16e2009-10-07 18:00:23 -0700911
Michael Kolba2b2ba82010-08-04 17:54:03 -0700912 void stopScrolling() {
913 ((ScrollWebView) mTabControl.getCurrentWebView()).stopScroll();
914 }
915
916 void hideFakeTitleBar() {
917 if (!isFakeTitleBarShowing()) return;
918 if (mXLargeScreenSize) {
919 mContentView.removeView(mFakeTitleBar);
920 mTabBar.onHideTitleBar();
921 } else {
922 WindowManager.LayoutParams params =
923 (WindowManager.LayoutParams) mFakeTitleBar.getLayoutParams();
924 WebView mainView = mTabControl.getCurrentWebView();
925 // Although we decided whether or not to animate based on the
926 // current
927 // scroll position, the scroll position may have changed since the
928 // fake title bar was displayed. Make sure it has the appropriate
929 // animation/lack thereof before removing.
930 params.windowAnimations =
931 mainView != null && mainView.getScrollY() == 0 ? 0 : R.style.TitleBar;
932 WindowManager manager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
933 manager.updateViewLayout(mFakeTitleBar, params);
934 manager.removeView(mFakeTitleBar);
935 }
936 }
937
938 boolean isFakeTitleBarShowing() {
939 return (mFakeTitleBar.getParent() != null);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400940 }
941
The Android Open Source Project0c908882009-03-03 19:32:16 -0800942 /**
Leon Scrogginsc6fa1102009-09-21 10:40:01 -0400943 * Special method for the fake title bar to call when displaying its context
944 * menu, since it is in its own Window, and its parent does not show a
945 * context menu.
946 */
947 /* package */ void showTitleBarContextMenu() {
Cary Clark65f4a3c2009-09-28 17:05:06 -0400948 if (null == mTitleBar.getParent()) {
949 return;
950 }
Leon Scrogginsc6fa1102009-09-21 10:40:01 -0400951 openContextMenu(mTitleBar);
952 }
953
Leon Scrogginsb2b19f52009-10-09 16:10:00 -0400954 @Override
955 public void onContextMenuClosed(Menu menu) {
956 super.onContextMenuClosed(menu);
957 if (mInLoad) {
958 showFakeTitleBar();
959 }
960 }
961
Leon Scrogginsc6fa1102009-09-21 10:40:01 -0400962 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -0800963 * onSaveInstanceState(Bundle map)
964 * onSaveInstanceState is called right before onStop(). The map contains
965 * the saved state.
966 */
Grace Kloba22ac16e2009-10-07 18:00:23 -0700967 @Override
968 protected void onSaveInstanceState(Bundle outState) {
Dave Bort31a6d1c2009-04-13 15:56:49 -0700969 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800970 Log.v(LOGTAG, "BrowserActivity.onSaveInstanceState: this=" + this);
971 }
972 // the default implementation requires each view to have an id. As the
973 // browser handles the state itself and it doesn't use id for the views,
974 // don't call the default implementation. Otherwise it will trigger the
975 // warning like this, "couldn't save which view has focus because the
976 // focused view XXX has no id".
977
978 // Save all the tabs
979 mTabControl.saveState(outState);
980 }
981
Grace Kloba22ac16e2009-10-07 18:00:23 -0700982 @Override
983 protected void onPause() {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800984 super.onPause();
985
986 if (mActivityInPause) {
987 Log.e(LOGTAG, "BrowserActivity is already paused.");
988 return;
989 }
990
Mike Reed7bfa63b2009-05-28 11:08:32 -0400991 mTabControl.pauseCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800992 mActivityInPause = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -0400993 if (mTabControl.getCurrentIndex() >= 0 && !pauseWebViewTimers()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800994 mWakeLock.acquire();
995 mHandler.sendMessageDelayed(mHandler
996 .obtainMessage(RELEASE_WAKELOCK), WAKELOCK_TIMEOUT);
997 }
998
Leon Scrogginsa2ab6a72009-09-11 11:49:52 -0400999 // FIXME: This removes the active tabs page and resets the menu to
1000 // MAIN_MENU. A better solution might be to do this work in onNewIntent
1001 // but then we would need to save it in onSaveInstanceState and restore
1002 // it in onCreate/onRestoreInstanceState
1003 if (mActiveTabsPage != null) {
1004 removeActiveTabPage(true);
1005 }
1006
The Android Open Source Project0c908882009-03-03 19:32:16 -08001007 cancelStopToast();
1008
1009 // unregister network state listener
1010 unregisterReceiver(mNetworkStateIntentReceiver);
1011 WebView.disablePlatformNotifications();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001012 }
1013
Grace Kloba22ac16e2009-10-07 18:00:23 -07001014 @Override
1015 protected void onDestroy() {
Dave Bort31a6d1c2009-04-13 15:56:49 -07001016 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001017 Log.v(LOGTAG, "BrowserActivity.onDestroy: this=" + this);
1018 }
1019 super.onDestroy();
Grace Kloba0923d692009-09-23 21:37:25 -07001020
Leon Scroggins8d5fa432009-10-02 15:55:59 -04001021 if (mUploadMessage != null) {
1022 mUploadMessage.onReceiveValue(null);
1023 mUploadMessage = null;
1024 }
1025
Grace Kloba0923d692009-09-23 21:37:25 -07001026 if (mTabControl == null) return;
1027
Grace Kloba1fc98a32009-10-21 13:23:08 -07001028 // Remove the fake title bar if it is there
1029 hideFakeTitleBar();
1030
The Android Open Source Project0c908882009-03-03 19:32:16 -08001031 // Remove the current tab and sub window
Grace Kloba22ac16e2009-10-07 18:00:23 -07001032 Tab t = mTabControl.getCurrentTab();
Patrick Scottfb5e77f2009-04-08 19:17:37 -07001033 if (t != null) {
1034 dismissSubWindow(t);
1035 removeTabFromContentView(t);
1036 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001037 // Destroy all the tabs
1038 mTabControl.destroy();
1039 WebIconDatabase.getInstance().close();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001040
Grace Klobab4da0ad2009-05-14 14:45:40 -07001041 unregisterReceiver(mPackageInstallationReceiver);
Bjorn Bringerta7611812010-03-24 11:12:02 +00001042
1043 // Stop watching the default geolocation permissions
1044 mSystemAllowGeolocationOrigins.stop();
1045 mSystemAllowGeolocationOrigins = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001046 }
1047
1048 @Override
1049 public void onConfigurationChanged(Configuration newConfig) {
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04001050 mConfigChanged = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001051 super.onConfigurationChanged(newConfig);
1052
1053 if (mPageInfoDialog != null) {
1054 mPageInfoDialog.dismiss();
1055 showPageInfo(
1056 mPageInfoView,
Leon Scrogginsc7b92f82010-01-11 18:17:31 -05001057 mPageInfoFromShowSSLCertificateOnError);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001058 }
1059 if (mSSLCertificateDialog != null) {
1060 mSSLCertificateDialog.dismiss();
1061 showSSLCertificate(
1062 mSSLCertificateView);
1063 }
1064 if (mSSLCertificateOnErrorDialog != null) {
1065 mSSLCertificateOnErrorDialog.dismiss();
1066 showSSLCertificateOnError(
1067 mSSLCertificateOnErrorView,
1068 mSSLCertificateOnErrorHandler,
1069 mSSLCertificateOnErrorError);
1070 }
1071 if (mHttpAuthenticationDialog != null) {
1072 String title = ((TextView) mHttpAuthenticationDialog
1073 .findViewById(com.android.internal.R.id.alertTitle)).getText()
1074 .toString();
1075 String name = ((TextView) mHttpAuthenticationDialog
1076 .findViewById(R.id.username_edit)).getText().toString();
1077 String password = ((TextView) mHttpAuthenticationDialog
1078 .findViewById(R.id.password_edit)).getText().toString();
1079 int focusId = mHttpAuthenticationDialog.getCurrentFocus()
1080 .getId();
1081 mHttpAuthenticationDialog.dismiss();
1082 showHttpAuthentication(mHttpAuthHandler, null, null, title,
1083 name, password, focusId);
1084 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001085 }
1086
Grace Kloba22ac16e2009-10-07 18:00:23 -07001087 @Override
1088 public void onLowMemory() {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001089 super.onLowMemory();
1090 mTabControl.freeMemory();
1091 }
1092
Cary Clarkff4d92c2010-03-25 11:17:03 -04001093 private void resumeWebViewTimers() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001094 Tab tab = mTabControl.getCurrentTab();
Cary Clarkff4d92c2010-03-25 11:17:03 -04001095 if (tab == null) return; // monkey can trigger this
Grace Kloba22ac16e2009-10-07 18:00:23 -07001096 boolean inLoad = tab.inLoad();
1097 if ((!mActivityInPause && !inLoad) || (mActivityInPause && inLoad)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001098 CookieSyncManager.getInstance().startSync();
Grace Kloba22ac16e2009-10-07 18:00:23 -07001099 WebView w = tab.getWebView();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001100 if (w != null) {
1101 w.resumeTimers();
1102 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001103 }
1104 }
1105
Mike Reed7bfa63b2009-05-28 11:08:32 -04001106 private boolean pauseWebViewTimers() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001107 Tab tab = mTabControl.getCurrentTab();
1108 boolean inLoad = tab.inLoad();
1109 if (mActivityInPause && !inLoad) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001110 CookieSyncManager.getInstance().stopSync();
1111 WebView w = mTabControl.getCurrentWebView();
1112 if (w != null) {
1113 w.pauseTimers();
1114 }
1115 return true;
1116 } else {
1117 return false;
1118 }
1119 }
1120
The Android Open Source Project0c908882009-03-03 19:32:16 -08001121 // Open the icon database and retain all the icons for visited sites.
1122 private void retainIconsOnStartup() {
1123 final WebIconDatabase db = WebIconDatabase.getInstance();
1124 db.open(getDir("icons", 0).getPath());
Leon Scroggins2c0f6112010-03-12 18:09:39 -05001125 Cursor c = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001126 try {
Leon Scroggins2c0f6112010-03-12 18:09:39 -05001127 c = Browser.getAllBookmarks(mResolver);
1128 if (c.moveToFirst()) {
1129 int urlIndex = c.getColumnIndex(Browser.BookmarkColumns.URL);
1130 do {
1131 String url = c.getString(urlIndex);
1132 db.retainIconForPageUrl(url);
1133 } while (c.moveToNext());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001134 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001135 } catch (IllegalStateException e) {
1136 Log.e(LOGTAG, "retainIconsOnStartup", e);
Leon Scroggins2c0f6112010-03-12 18:09:39 -05001137 } finally {
1138 if (c!= null) c.close();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001139 }
1140 }
1141
1142 // Helper method for getting the top window.
1143 WebView getTopWindow() {
1144 return mTabControl.getCurrentTopWebView();
1145 }
1146
Grace Kloba22ac16e2009-10-07 18:00:23 -07001147 TabControl getTabControl() {
1148 return mTabControl;
1149 }
1150
The Android Open Source Project0c908882009-03-03 19:32:16 -08001151 @Override
1152 public boolean onCreateOptionsMenu(Menu menu) {
1153 super.onCreateOptionsMenu(menu);
1154
1155 MenuInflater inflater = getMenuInflater();
1156 inflater.inflate(R.menu.browser, menu);
1157 mMenu = menu;
1158 updateInLoadMenuItems();
1159 return true;
1160 }
1161
1162 /**
1163 * As the menu can be open when loading state changes
1164 * we must manually update the state of the stop/reload menu
1165 * item
1166 */
1167 private void updateInLoadMenuItems() {
1168 if (mMenu == null) {
1169 return;
1170 }
Michael Kolbe0a36662010-06-29 10:37:12 -07001171 MenuItem dest = mMenu.findItem(R.id.stop_reload_menu_id);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001172 MenuItem src = mInLoad ?
1173 mMenu.findItem(R.id.stop_menu_id):
Michael Kolbe0a36662010-06-29 10:37:12 -07001174 mMenu.findItem(R.id.reload_menu_id);
1175 if (src != null) {
1176 dest.setIcon(src.getIcon());
1177 dest.setTitle(src.getTitle());
1178 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001179 }
1180
1181 @Override
1182 public boolean onContextItemSelected(MenuItem item) {
1183 // chording is not an issue with context menus, but we use the same
1184 // options selector, so set mCanChord to true so we can access them.
1185 mCanChord = true;
1186 int id = item.getItemId();
Leon Scroggins96afcb12009-12-10 12:35:56 -05001187 boolean result = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001188 switch (id) {
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001189 // For the context menu from the title bar
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001190 case R.id.title_bar_copy_page_url:
Leon Scroggins96afcb12009-12-10 12:35:56 -05001191 Tab currentTab = mTabControl.getCurrentTab();
1192 if (null == currentTab) {
1193 result = false;
1194 break;
1195 }
1196 WebView mainView = currentTab.getWebView();
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001197 if (null == mainView) {
Leon Scroggins96afcb12009-12-10 12:35:56 -05001198 result = false;
1199 break;
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001200 }
Leon Scroggins96afcb12009-12-10 12:35:56 -05001201 copy(mainView.getUrl());
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001202 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001203 // -- Browser context menu
1204 case R.id.open_context_menu_id:
The Android Open Source Project0c908882009-03-03 19:32:16 -08001205 case R.id.bookmark_context_menu_id:
1206 case R.id.save_link_context_menu_id:
1207 case R.id.share_link_context_menu_id:
1208 case R.id.copy_link_context_menu_id:
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001209 final WebView webView = getTopWindow();
1210 if (null == webView) {
Leon Scroggins96afcb12009-12-10 12:35:56 -05001211 result = false;
1212 break;
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001213 }
1214 final HashMap hrefMap = new HashMap();
1215 hrefMap.put("webview", webView);
1216 final Message msg = mHandler.obtainMessage(
1217 FOCUS_NODE_HREF, id, 0, hrefMap);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001218 webView.requestFocusNodeHref(msg);
1219 break;
1220
1221 default:
1222 // For other context menus
Leon Scroggins96afcb12009-12-10 12:35:56 -05001223 result = onOptionsItemSelected(item);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001224 }
1225 mCanChord = false;
Leon Scroggins96afcb12009-12-10 12:35:56 -05001226 return result;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001227 }
1228
1229 private Bundle createGoogleSearchSourceBundle(String source) {
1230 Bundle bundle = new Bundle();
Bjorn Bringert10d1cca2010-02-10 14:22:12 +00001231 bundle.putString(Search.SOURCE, source);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001232 return bundle;
1233 }
1234
Leon Scroggins8ad29922010-02-16 12:33:55 -05001235 /* package */ void editUrl() {
Leon Scroggins68579392009-09-15 15:31:54 -04001236 if (mOptionsMenuOpen) closeOptionsMenu();
Leon Scroggins5bbe9802009-07-31 13:10:55 -04001237 String url = (getTopWindow() == null) ? null : getTopWindow().getUrl();
Grace Kloba83f47342009-07-20 10:44:31 -07001238 startSearch(mSettings.getHomePage().equals(url) ? null : url, true,
Leon Scroggins8ad29922010-02-16 12:33:55 -05001239 null, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001240 }
1241
Leon Scroggins8ad29922010-02-16 12:33:55 -05001242 /**
1243 * Overriding this to insert a local information bundle
1244 */
The Android Open Source Project0c908882009-03-03 19:32:16 -08001245 @Override
1246 public void startSearch(String initialQuery, boolean selectInitialQuery,
1247 Bundle appSearchData, boolean globalSearch) {
1248 if (appSearchData == null) {
1249 appSearchData = createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_TYPE);
1250 }
1251 super.startSearch(initialQuery, selectInitialQuery, appSearchData, globalSearch);
1252 }
1253
Leon Scroggins1f005d32009-08-10 17:36:42 -04001254 /**
1255 * Switch tabs. Called by the TitleBarSet when sliding the title bar
1256 * results in changing tabs.
Leon Scroggins160a7e72009-08-14 18:28:01 -04001257 * @param index Index of the tab to change to, as defined by
1258 * mTabControl.getTabIndex(Tab t).
1259 * @return boolean True if we successfully switched to a different tab. If
1260 * the indexth tab is null, or if that tab is the same as
1261 * the current one, return false.
Leon Scroggins1f005d32009-08-10 17:36:42 -04001262 */
Leon Scroggins160a7e72009-08-14 18:28:01 -04001263 /* package */ boolean switchToTab(int index) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001264 Tab tab = mTabControl.getTab(index);
1265 Tab currentTab = mTabControl.getCurrentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04001266 if (tab == null || tab == currentTab) {
Leon Scroggins160a7e72009-08-14 18:28:01 -04001267 return false;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001268 }
1269 if (currentTab != null) {
1270 // currentTab may be null if it was just removed. In that case,
1271 // we do not need to remove it
1272 removeTabFromContentView(currentTab);
1273 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001274 mTabControl.setCurrentTab(tab);
1275 attachTabToContentView(tab);
Grace Klobaeb6eef42009-09-15 17:56:32 -07001276 resetTitleIconAndProgress();
1277 updateLockIconToLatest();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001278 return true;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001279 }
1280
Grace Kloba22ac16e2009-10-07 18:00:23 -07001281 /* package */ Tab openTabToHomePage() {
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001282 return openTabAndShow(mSettings.getHomePage(), false, null);
1283 }
1284
Leon Scroggins1f005d32009-08-10 17:36:42 -04001285 /* package */ void closeCurrentWindow() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001286 final Tab current = mTabControl.getCurrentTab();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001287 if (mTabControl.getTabCount() == 1) {
Leon Scroggins30444232009-09-04 18:36:20 -04001288 // This is the last tab. Open a new one, with the home
1289 // page and close the current one.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001290 openTabToHomePage();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001291 closeTab(current);
Leon Scroggins160a7e72009-08-14 18:28:01 -04001292 return;
1293 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07001294 final Tab parent = current.getParentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04001295 int indexToShow = -1;
1296 if (parent != null) {
1297 indexToShow = mTabControl.getTabIndex(parent);
1298 } else {
Leon Scroggins160a7e72009-08-14 18:28:01 -04001299 final int currentIndex = mTabControl.getCurrentIndex();
1300 // Try to move to the tab to the right
1301 indexToShow = currentIndex + 1;
1302 if (indexToShow > mTabControl.getTabCount() - 1) {
1303 // Try to move to the tab to the left
1304 indexToShow = currentIndex - 1;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001305 }
1306 }
Leon Scroggins160a7e72009-08-14 18:28:01 -04001307 if (switchToTab(indexToShow)) {
1308 // Close window
1309 closeTab(current);
1310 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001311 }
1312
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001313 private ActiveTabsPage mActiveTabsPage;
1314
1315 /**
1316 * Remove the active tabs page.
1317 * @param needToAttach If true, the active tabs page did not attach a tab
1318 * to the content view, so we need to do that here.
1319 */
1320 /* package */ void removeActiveTabPage(boolean needToAttach) {
1321 mContentView.removeView(mActiveTabsPage);
Leon Scrogginsd746a942010-05-19 13:21:44 -04001322 mTitleBar.setVisibility(View.VISIBLE);
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001323 mActiveTabsPage = null;
1324 mMenuState = R.id.MAIN_MENU;
1325 if (needToAttach) {
1326 attachTabToContentView(mTabControl.getCurrentTab());
1327 }
1328 getTopWindow().requestFocus();
1329 }
1330
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04001331 @Override
1332 public ActionMode onStartActionMode(ActionMode.Callback callback) {
1333 ActionMode mode = super.onStartActionMode(callback);
1334 if (callback instanceof FindActionModeCallback
1335 || callback instanceof SelectActionModeCallback) {
1336 // For find and select, hide extra title bars. They will
1337 // be replaced in onEndActionMode.
1338 Tab tab = mTabControl.getCurrentTab();
1339 if (tab.getSubWebView() == null) {
1340 // If the find or select is being performed on the main webview,
1341 // remove the embedded title bar.
1342 WebView mainView = tab.getWebView();
1343 if (mainView != null) {
1344 mainView.setEmbeddedTitleBar(null);
1345 }
Cary Clark01cfcdd2010-06-04 16:36:45 -04001346 }
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04001347 hideFakeTitleBar();
1348 mActionMode = mode;
1349 } else {
1350 // Do not store other ActionModes, since we are unable to determine
1351 // when they finish.
1352 mActionMode = null;
Cary Clark01cfcdd2010-06-04 16:36:45 -04001353 }
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04001354 return mode;
Cary Clark01cfcdd2010-06-04 16:36:45 -04001355 }
1356
The Android Open Source Project0c908882009-03-03 19:32:16 -08001357 @Override
1358 public boolean onOptionsItemSelected(MenuItem item) {
Michael Kolbed217742010-08-10 17:52:34 -07001359 // check the action bar button before mCanChord check, as the prepare call
1360 // doesn't come for action bar buttons
1361 if (item.getItemId() == R.id.newtab) {
1362 bookmarksOrHistoryPicker(false, true);
1363 return true;
1364 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001365 if (!mCanChord) {
1366 // The user has already fired a shortcut with this hold down of the
1367 // menu key.
1368 return false;
1369 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001370 if (null == getTopWindow()) {
Leon Scroggins0d7ae0e2009-06-05 11:04:45 -04001371 return false;
1372 }
Grace Kloba6ee9c492009-07-13 10:04:34 -07001373 if (mMenuIsDown) {
1374 // The shortcut action consumes the MENU. Even if it is still down,
1375 // it won't trigger the next shortcut action. In the case of the
1376 // shortcut action triggering a new activity, like Bookmarks, we
1377 // won't get onKeyUp for MENU. So it is important to reset it here.
1378 mMenuIsDown = false;
1379 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001380 switch (item.getItemId()) {
1381 // -- Main menu
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001382 case R.id.new_tab_menu_id:
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001383 openTabToHomePage();
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001384 break;
1385
Michael Kolbae62fd42010-08-18 16:33:28 -07001386 case R.id.incognito_menu_id:
1387 openIncognitoTab();
1388 break;
1389
Leon Scroggins64b80f32009-08-07 12:03:34 -04001390 case R.id.goto_menu_id:
Leon Scroggins8ad29922010-02-16 12:33:55 -05001391 editUrl();
Leon Scrogginsb3a5bed2009-09-28 11:21:56 -04001392 break;
1393
1394 case R.id.bookmarks_menu_id:
Michael Kolb68792c82010-08-09 16:39:18 -07001395 bookmarksOrHistoryPicker(false, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001396 break;
1397
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001398 case R.id.active_tabs_menu_id:
1399 mActiveTabsPage = new ActiveTabsPage(this, mTabControl);
1400 removeTabFromContentView(mTabControl.getCurrentTab());
Leon Scrogginsd746a942010-05-19 13:21:44 -04001401 mTitleBar.setVisibility(View.GONE);
Leon Scroggins43de6162009-09-14 19:59:58 -04001402 hideFakeTitleBar();
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001403 mContentView.addView(mActiveTabsPage, COVER_SCREEN_PARAMS);
1404 mActiveTabsPage.requestFocus();
1405 mMenuState = EMPTY_MENU;
1406 break;
1407
Leon Scroggins1f005d32009-08-10 17:36:42 -04001408 case R.id.add_bookmark_menu_id:
Leon Scroggins571b3762010-05-26 10:25:01 -04001409 bookmarkCurrentPage();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001410 break;
1411
1412 case R.id.stop_reload_menu_id:
1413 if (mInLoad) {
1414 stopLoading();
1415 } else {
1416 getTopWindow().reload();
1417 }
1418 break;
1419
1420 case R.id.back_menu_id:
1421 getTopWindow().goBack();
1422 break;
1423
1424 case R.id.forward_menu_id:
1425 getTopWindow().goForward();
1426 break;
1427
1428 case R.id.close_menu_id:
1429 // Close the subwindow if it exists.
1430 if (mTabControl.getCurrentSubWindow() != null) {
1431 dismissSubWindow(mTabControl.getCurrentTab());
1432 break;
1433 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001434 closeCurrentWindow();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001435 break;
1436
1437 case R.id.homepage_menu_id:
Grace Kloba22ac16e2009-10-07 18:00:23 -07001438 Tab current = mTabControl.getCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001439 if (current != null) {
1440 dismissSubWindow(current);
Leon Scroggins92472e82010-02-17 16:32:28 -05001441 loadUrl(current.getWebView(), mSettings.getHomePage());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001442 }
1443 break;
1444
1445 case R.id.preferences_menu_id:
1446 Intent intent = new Intent(this,
1447 BrowserPreferencesPage.class);
Leon Scrogginsd5304942009-12-10 16:11:39 -05001448 intent.putExtra(BrowserPreferencesPage.CURRENT_PAGE,
1449 getTopWindow().getUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001450 startActivityForResult(intent, PREFERENCES_PAGE);
1451 break;
1452
1453 case R.id.find_menu_id:
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04001454 showFindDialog(null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001455 break;
1456
Elliott Slaughter0ced08c2010-06-30 11:40:42 -07001457 case R.id.save_webarchive_menu_id:
1458 if (LOGD_ENABLED) {
1459 Log.d(LOGTAG, "Save as Web Archive");
1460 }
1461 String directory = getExternalFilesDir(null).getAbsolutePath() + File.separator;
1462 getTopWindow().saveWebArchive(directory, true, new ValueCallback<String>() {
1463 @Override
1464 public void onReceiveValue(String value) {
1465 if (value != null) {
1466 Toast.makeText(BrowserActivity.this, R.string.webarchive_saved, Toast.LENGTH_SHORT).show();
1467 } else {
1468 Toast.makeText(BrowserActivity.this, R.string.webarchive_failed, Toast.LENGTH_SHORT).show();
1469 }
1470 }
1471 });
1472 break;
1473
The Android Open Source Project0c908882009-03-03 19:32:16 -08001474 case R.id.page_info_menu_id:
1475 showPageInfo(mTabControl.getCurrentTab(), false);
1476 break;
1477
1478 case R.id.classic_history_menu_id:
Michael Kolb68792c82010-08-09 16:39:18 -07001479 bookmarksOrHistoryPicker(true, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001480 break;
1481
Leon Scroggins96afcb12009-12-10 12:35:56 -05001482 case R.id.title_bar_share_page_url:
The Android Open Source Project0c908882009-03-03 19:32:16 -08001483 case R.id.share_page_menu_id:
Leon Scroggins96afcb12009-12-10 12:35:56 -05001484 Tab currentTab = mTabControl.getCurrentTab();
1485 if (null == currentTab) {
1486 mCanChord = false;
1487 return false;
1488 }
1489 currentTab.populatePickerData();
1490 sharePage(this, currentTab.getTitle(),
1491 currentTab.getUrl(), currentTab.getFavicon(),
Ben Murdoch87cc65d2010-06-29 20:34:10 +01001492 createScreenshot(currentTab.getWebView(), getDesiredThumbnailWidth(this),
1493 getDesiredThumbnailHeight(this)));
The Android Open Source Project0c908882009-03-03 19:32:16 -08001494 break;
1495
1496 case R.id.dump_nav_menu_id:
1497 getTopWindow().debugDump();
1498 break;
1499
Andrei Popescu7a8b88b2010-02-02 00:30:38 +00001500 case R.id.dump_counters_menu_id:
1501 getTopWindow().dumpV8Counters();
1502 break;
1503
The Android Open Source Project0c908882009-03-03 19:32:16 -08001504 case R.id.zoom_in_menu_id:
1505 getTopWindow().zoomIn();
1506 break;
1507
1508 case R.id.zoom_out_menu_id:
1509 getTopWindow().zoomOut();
1510 break;
1511
1512 case R.id.view_downloads_menu_id:
1513 viewDownloads(null);
1514 break;
1515
The Android Open Source Project0c908882009-03-03 19:32:16 -08001516 case R.id.window_one_menu_id:
1517 case R.id.window_two_menu_id:
1518 case R.id.window_three_menu_id:
1519 case R.id.window_four_menu_id:
1520 case R.id.window_five_menu_id:
1521 case R.id.window_six_menu_id:
1522 case R.id.window_seven_menu_id:
1523 case R.id.window_eight_menu_id:
1524 {
1525 int menuid = item.getItemId();
1526 for (int id = 0; id < WINDOW_SHORTCUT_ID_ARRAY.length; id++) {
1527 if (WINDOW_SHORTCUT_ID_ARRAY[id] == menuid) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001528 Tab desiredTab = mTabControl.getTab(id);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001529 if (desiredTab != null &&
1530 desiredTab != mTabControl.getCurrentTab()) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001531 switchToTab(id);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001532 }
1533 break;
1534 }
1535 }
1536 }
1537 break;
1538
1539 default:
1540 if (!super.onOptionsItemSelected(item)) {
1541 return false;
1542 }
1543 // Otherwise fall through.
1544 }
1545 mCanChord = false;
1546 return true;
1547 }
1548
Leon Scroggins571b3762010-05-26 10:25:01 -04001549 /* package */ void bookmarkCurrentPage() {
1550 Intent i = new Intent(BrowserActivity.this,
1551 AddBookmarkPage.class);
1552 WebView w = getTopWindow();
1553 i.putExtra("url", w.getUrl());
1554 i.putExtra("title", w.getTitle());
1555 i.putExtra("touch_icon_url", w.getTouchIconUrl());
Ben Murdoch87cc65d2010-06-29 20:34:10 +01001556 i.putExtra("thumbnail", createScreenshot(w, getDesiredThumbnailWidth(this),
1557 getDesiredThumbnailHeight(this)));
Ben Murdocheecb4e62010-07-06 16:30:38 +01001558 i.putExtra("url_editable", false);
Leon Scroggins571b3762010-05-26 10:25:01 -04001559 startActivity(i);
1560 }
1561
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04001562 /*
1563 * True if a custom ActionMode (i.e. find or select) is in use.
1564 */
1565 private boolean isInCustomActionMode() {
1566 return mActionMode != null;
Cary Clark01cfcdd2010-06-04 16:36:45 -04001567 }
1568
1569 /*
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04001570 * End the current ActionMode. Only works for find and select.
Cary Clark01cfcdd2010-06-04 16:36:45 -04001571 */
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04001572 void endActionMode() {
1573 if (mActionMode != null) {
1574 mActionMode.finish();
1575 }
1576 }
1577
1578 /*
1579 * Called by find and select when they are finished. Replace title bars
1580 * as necessary.
1581 */
1582 public void onEndActionMode() {
1583 if (!isInCustomActionMode()) return;
Michael Kolba2b2ba82010-08-04 17:54:03 -07001584 // If the Find was being performed in the main WebView, replace the
1585 // embedded title bar.
1586 Tab currentTab = mTabControl.getCurrentTab();
1587 if (currentTab.getSubWebView() == null) {
1588 WebView mainView = currentTab.getWebView();
1589 if (mainView != null) {
1590 mainView.setEmbeddedTitleBar(mTitleBar);
Leon Scroggins79e36d92010-04-29 16:01:46 +01001591 }
1592 }
Leon Scroggins79e36d92010-04-29 16:01:46 +01001593 if (mInLoad) {
1594 // The title bar was hidden, because otherwise it would cover up the
Michael Kolba2b2ba82010-08-04 17:54:03 -07001595 // find or select dialog. Now that the dialog has been removed,
Cary Clark01cfcdd2010-06-04 16:36:45 -04001596 // show the fake title bar once again.
Leon Scroggins79e36d92010-04-29 16:01:46 +01001597 showFakeTitleBar();
1598 }
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04001599 mActionMode = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001600 }
1601
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04001602 private FindActionModeCallback mFindCallback;
1603 private SelectActionModeCallback mSelectCallback;
1604
1605 // For select and find, we keep track of the ActionMode so that
1606 // finish() can be called as desired.
1607 private ActionMode mActionMode;
1608
1609 /*
1610 * Open the find ActionMode.
1611 * @param text If non null, will be placed in find to be searched for.
1612 */
1613 public void showFindDialog(String text) {
1614 if (null == mFindCallback) {
1615 mFindCallback = new FindActionModeCallback(this);
Cary Clark01cfcdd2010-06-04 16:36:45 -04001616 }
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04001617 WebView webView = getTopWindow();
1618 webView.setFindIsUp(true);
1619 mFindCallback.setWebView(webView);
1620 startActionMode(mFindCallback);
1621 if (text != null) mFindCallback.setText(text);
Cary Clark01cfcdd2010-06-04 16:36:45 -04001622 }
1623
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04001624 /*
1625 * Show the select ActionMode.
1626 */
Cary Clark01cfcdd2010-06-04 16:36:45 -04001627 public void showSelectDialog() {
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04001628 if (null == mSelectCallback) {
1629 mSelectCallback = new SelectActionModeCallback(this);
Cary Clark01cfcdd2010-06-04 16:36:45 -04001630 }
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04001631 WebView webView = getTopWindow();
1632 webView.setUpSelect();
1633 mSelectCallback.setWebView(webView);
1634 startActionMode(mSelectCallback);
Cary Clark01cfcdd2010-06-04 16:36:45 -04001635 }
1636
Grace Kloba22ac16e2009-10-07 18:00:23 -07001637 @Override
1638 public boolean onPrepareOptionsMenu(Menu menu) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001639 // This happens when the user begins to hold down the menu key, so
1640 // allow them to chord to get a shortcut.
1641 mCanChord = true;
1642 // Note: setVisible will decide whether an item is visible; while
1643 // setEnabled() will decide whether an item is enabled, which also means
1644 // whether the matching shortcut key will function.
1645 super.onPrepareOptionsMenu(menu);
1646 switch (mMenuState) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001647 case EMPTY_MENU:
1648 if (mCurrentMenuState != mMenuState) {
1649 menu.setGroupVisible(R.id.MAIN_MENU, false);
1650 menu.setGroupEnabled(R.id.MAIN_MENU, false);
1651 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001652 }
1653 break;
1654 default:
1655 if (mCurrentMenuState != mMenuState) {
1656 menu.setGroupVisible(R.id.MAIN_MENU, true);
1657 menu.setGroupEnabled(R.id.MAIN_MENU, true);
1658 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001659 }
1660 final WebView w = getTopWindow();
1661 boolean canGoBack = false;
1662 boolean canGoForward = false;
1663 boolean isHome = false;
1664 if (w != null) {
1665 canGoBack = w.canGoBack();
1666 canGoForward = w.canGoForward();
1667 isHome = mSettings.getHomePage().equals(w.getUrl());
1668 }
1669 final MenuItem back = menu.findItem(R.id.back_menu_id);
1670 back.setEnabled(canGoBack);
1671
1672 final MenuItem home = menu.findItem(R.id.homepage_menu_id);
1673 home.setEnabled(!isHome);
1674
Michael Kolbe0a36662010-06-29 10:37:12 -07001675 final MenuItem forward = menu.findItem(R.id.forward_menu_id);
1676 forward.setEnabled(canGoForward);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001677
Michael Kolbed217742010-08-10 17:52:34 -07001678 if (!mXLargeScreenSize) {
1679 final MenuItem newtab = menu.findItem(R.id.new_tab_menu_id);
1680 newtab.setEnabled(mTabControl.canCreateNewTab());
1681 }
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001682
The Android Open Source Project0c908882009-03-03 19:32:16 -08001683 // decide whether to show the share link option
1684 PackageManager pm = getPackageManager();
1685 Intent send = new Intent(Intent.ACTION_SEND);
1686 send.setType("text/plain");
1687 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1688 menu.findItem(R.id.share_page_menu_id).setVisible(ri != null);
1689
The Android Open Source Project0c908882009-03-03 19:32:16 -08001690 boolean isNavDump = mSettings.isNavDump();
1691 final MenuItem nav = menu.findItem(R.id.dump_nav_menu_id);
1692 nav.setVisible(isNavDump);
1693 nav.setEnabled(isNavDump);
Andrei Popescu7a8b88b2010-02-02 00:30:38 +00001694
1695 boolean showDebugSettings = mSettings.showDebugSettings();
1696 final MenuItem counter = menu.findItem(R.id.dump_counters_menu_id);
1697 counter.setVisible(showDebugSettings);
1698 counter.setEnabled(showDebugSettings);
1699
The Android Open Source Project0c908882009-03-03 19:32:16 -08001700 break;
1701 }
1702 mCurrentMenuState = mMenuState;
1703 return true;
1704 }
1705
1706 @Override
1707 public void onCreateContextMenu(ContextMenu menu, View v,
1708 ContextMenuInfo menuInfo) {
Leon Scroggins571b3762010-05-26 10:25:01 -04001709 if (v instanceof TitleBarBase) {
Leon Scroggins4e9f89b2010-02-22 16:54:14 -05001710 return;
1711 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001712 WebView webview = (WebView) v;
1713 WebView.HitTestResult result = webview.getHitTestResult();
1714 if (result == null) {
1715 return;
1716 }
1717
1718 int type = result.getType();
1719 if (type == WebView.HitTestResult.UNKNOWN_TYPE) {
1720 Log.w(LOGTAG,
1721 "We should not show context menu when nothing is touched");
1722 return;
1723 }
1724 if (type == WebView.HitTestResult.EDIT_TEXT_TYPE) {
1725 // let TextView handles context menu
1726 return;
1727 }
1728
1729 // Note, http://b/issue?id=1106666 is requesting that
1730 // an inflated menu can be used again. This is not available
1731 // yet, so inflate each time (yuk!)
1732 MenuInflater inflater = getMenuInflater();
1733 inflater.inflate(R.menu.browsercontext, menu);
1734
1735 // Show the correct menu group
Leon Scroggins III9e997c72010-05-26 13:25:16 -04001736 final String extra = result.getExtra();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001737 menu.setGroupVisible(R.id.PHONE_MENU,
1738 type == WebView.HitTestResult.PHONE_TYPE);
1739 menu.setGroupVisible(R.id.EMAIL_MENU,
1740 type == WebView.HitTestResult.EMAIL_TYPE);
1741 menu.setGroupVisible(R.id.GEO_MENU,
1742 type == WebView.HitTestResult.GEO_TYPE);
1743 menu.setGroupVisible(R.id.IMAGE_MENU,
1744 type == WebView.HitTestResult.IMAGE_TYPE
1745 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1746 menu.setGroupVisible(R.id.ANCHOR_MENU,
1747 type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1748 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1749
1750 // Setup custom handling depending on the type
1751 switch (type) {
1752 case WebView.HitTestResult.PHONE_TYPE:
1753 menu.setHeaderTitle(Uri.decode(extra));
1754 menu.findItem(R.id.dial_context_menu_id).setIntent(
1755 new Intent(Intent.ACTION_VIEW, Uri
1756 .parse(WebView.SCHEME_TEL + extra)));
1757 Intent addIntent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
1758 addIntent.putExtra(Insert.PHONE, Uri.decode(extra));
Cary Clark5e335a32009-09-22 14:53:11 -04001759 addIntent.setType(ContactsContract.Contacts.CONTENT_ITEM_TYPE);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001760 menu.findItem(R.id.add_contact_context_menu_id).setIntent(
1761 addIntent);
1762 menu.findItem(R.id.copy_phone_context_menu_id).setOnMenuItemClickListener(
1763 new Copy(extra));
1764 break;
1765
1766 case WebView.HitTestResult.EMAIL_TYPE:
1767 menu.setHeaderTitle(extra);
1768 menu.findItem(R.id.email_context_menu_id).setIntent(
1769 new Intent(Intent.ACTION_VIEW, Uri
1770 .parse(WebView.SCHEME_MAILTO + extra)));
1771 menu.findItem(R.id.copy_mail_context_menu_id).setOnMenuItemClickListener(
1772 new Copy(extra));
1773 break;
1774
1775 case WebView.HitTestResult.GEO_TYPE:
1776 menu.setHeaderTitle(extra);
1777 menu.findItem(R.id.map_context_menu_id).setIntent(
1778 new Intent(Intent.ACTION_VIEW, Uri
1779 .parse(WebView.SCHEME_GEO
1780 + URLEncoder.encode(extra))));
1781 menu.findItem(R.id.copy_geo_context_menu_id).setOnMenuItemClickListener(
1782 new Copy(extra));
1783 break;
1784
1785 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1786 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
1787 TextView titleView = (TextView) LayoutInflater.from(this)
1788 .inflate(android.R.layout.browser_link_context_header,
1789 null);
1790 titleView.setText(extra);
1791 menu.setHeaderView(titleView);
1792 // decide whether to show the open link in new tab option
Leon Scroggins III9e997c72010-05-26 13:25:16 -04001793 boolean showNewTab = mTabControl.canCreateNewTab();
1794 MenuItem newTabItem
1795 = menu.findItem(R.id.open_newtab_context_menu_id);
1796 newTabItem.setVisible(showNewTab);
1797 if (showNewTab) {
1798 newTabItem.setOnMenuItemClickListener(
1799 new MenuItem.OnMenuItemClickListener() {
1800 public boolean onMenuItemClick(MenuItem item) {
1801 final Tab parent = mTabControl.getCurrentTab();
Michael Kolb68792c82010-08-09 16:39:18 -07001802 final Tab newTab = openTab(extra, false);
Leon Scroggins III9e997c72010-05-26 13:25:16 -04001803 if (newTab != parent) {
1804 parent.addChildTab(newTab);
1805 }
1806 return true;
1807 }
1808 });
1809 }
Ben Murdochde353622009-10-12 10:29:00 +01001810 menu.findItem(R.id.bookmark_context_menu_id).setVisible(
1811 Bookmarks.urlHasAcceptableScheme(extra));
The Android Open Source Project0c908882009-03-03 19:32:16 -08001812 PackageManager pm = getPackageManager();
1813 Intent send = new Intent(Intent.ACTION_SEND);
1814 send.setType("text/plain");
1815 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1816 menu.findItem(R.id.share_link_context_menu_id).setVisible(ri != null);
1817 if (type == WebView.HitTestResult.SRC_ANCHOR_TYPE) {
1818 break;
1819 }
1820 // otherwise fall through to handle image part
1821 case WebView.HitTestResult.IMAGE_TYPE:
1822 if (type == WebView.HitTestResult.IMAGE_TYPE) {
1823 menu.setHeaderTitle(extra);
1824 }
1825 menu.findItem(R.id.view_image_context_menu_id).setIntent(
1826 new Intent(Intent.ACTION_VIEW, Uri.parse(extra)));
1827 menu.findItem(R.id.download_context_menu_id).
1828 setOnMenuItemClickListener(new Download(extra));
Ben Murdoch4f75ba22009-10-27 11:48:28 +00001829 menu.findItem(R.id.set_wallpaper_context_menu_id).
1830 setOnMenuItemClickListener(new SetAsWallpaper(extra));
The Android Open Source Project0c908882009-03-03 19:32:16 -08001831 break;
1832
1833 default:
1834 Log.w(LOGTAG, "We should not get here.");
1835 break;
1836 }
Leon Scrogginsb2b19f52009-10-09 16:10:00 -04001837 hideFakeTitleBar();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001838 }
1839
The Android Open Source Project0c908882009-03-03 19:32:16 -08001840 // Attach the given tab to the content view.
Grace Klobac928c302009-09-17 11:51:21 -07001841 // this should only be called for the current tab.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001842 private void attachTabToContentView(Tab t) {
Steve Block2bc69912009-07-30 14:45:13 +01001843 // Attach the container that contains the main WebView and any other UI
1844 // associated with the tab.
Patrick Scottd0119532009-09-17 08:00:31 -04001845 t.attachTabToContentView(mContentView);
Ben Murdochbff2d602009-07-01 20:19:05 +01001846
1847 if (mShouldShowErrorConsole) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001848 ErrorConsoleView errorConsole = t.getErrorConsole(true);
Ben Murdochbff2d602009-07-01 20:19:05 +01001849 if (errorConsole.numberOfErrors() == 0) {
1850 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
1851 } else {
1852 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
1853 }
1854
1855 mErrorConsoleContainer.addView(errorConsole,
Romain Guy15b8ec62010-01-08 15:06:43 -08001856 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
Ben Murdochbff2d602009-07-01 20:19:05 +01001857 ViewGroup.LayoutParams.WRAP_CONTENT));
1858 }
1859
Michael Kolba2b2ba82010-08-04 17:54:03 -07001860 WebView view = t.getWebView();
1861 view.setEmbeddedTitleBar(mTitleBar);
Leon Scroggins58d56c62010-01-28 15:12:40 -05001862 if (t.isInVoiceSearchMode()) {
1863 showVoiceTitleBar(t.getVoiceDisplayTitle());
1864 } else {
1865 revertVoiceTitleBar();
1866 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001867 // Request focus on the top window.
1868 t.getTopWindow().requestFocus();
Michael Kolba2b2ba82010-08-04 17:54:03 -07001869 if (mTabControl.getTabChangeListener() != null) {
1870 mTabControl.getTabChangeListener().onCurrentTab(t);
1871 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001872 }
1873
1874 // Attach a sub window to the main WebView of the given tab.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001875 void attachSubWindow(Tab t) {
Patrick Scottd0119532009-09-17 08:00:31 -04001876 t.attachSubWindow(mContentView);
1877 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001878 }
1879
1880 // Remove the given tab from the content view.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001881 private void removeTabFromContentView(Tab t) {
Steve Block2bc69912009-07-30 14:45:13 +01001882 // Remove the container that contains the main WebView.
Patrick Scottd0119532009-09-17 08:00:31 -04001883 t.removeTabFromContentView(mContentView);
Ben Murdochbff2d602009-07-01 20:19:05 +01001884
Grace Kloba22ac16e2009-10-07 18:00:23 -07001885 ErrorConsoleView errorConsole = t.getErrorConsole(false);
1886 if (errorConsole != null) {
1887 mErrorConsoleContainer.removeView(errorConsole);
Ben Murdochbff2d602009-07-01 20:19:05 +01001888 }
1889
Michael Kolba2b2ba82010-08-04 17:54:03 -07001890 WebView view = t.getWebView();
1891 if (view != null) {
1892 view.setEmbeddedTitleBar(null);
Leon Scrogginsbb85b902009-09-14 19:27:20 -04001893 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001894 }
1895
1896 // Remove the sub window if it exists. Also called by TabControl when the
1897 // user clicks the 'X' to dismiss a sub window.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001898 /* package */ void dismissSubWindow(Tab t) {
Patrick Scottd0119532009-09-17 08:00:31 -04001899 t.removeSubWindow(mContentView);
Grace Kloba22ac16e2009-10-07 18:00:23 -07001900 // dismiss the subwindow. This will destroy the WebView.
1901 t.dismissSubWindow();
Patrick Scottd0119532009-09-17 08:00:31 -04001902 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001903 }
1904
Leon Scroggins1f005d32009-08-10 17:36:42 -04001905 // A wrapper function of {@link #openTabAndShow(UrlData, boolean, String)}
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07001906 // that accepts url as string.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001907 private Tab openTabAndShow(String url, boolean closeOnExit, String appId) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001908 return openTabAndShow(new UrlData(url), closeOnExit, appId);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001909 }
1910
1911 // This method does a ton of stuff. It will attempt to create a new tab
1912 // if we haven't reached MAX_TABS. Otherwise it uses the current tab. If
Leon Scroggins1f005d32009-08-10 17:36:42 -04001913 // url isn't null, it will load the given url.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001914 /* package */Tab openTabAndShow(UrlData urlData, boolean closeOnExit,
1915 String appId) {
1916 final Tab currentTab = mTabControl.getCurrentTab();
1917 if (mTabControl.canCreateNewTab()) {
1918 final Tab tab = mTabControl.createNewTab(closeOnExit, appId,
Elliott Slaughterf0f03952010-07-14 18:10:36 -07001919 urlData.mUrl, false);
Leon Scroggins1f005d32009-08-10 17:36:42 -04001920 WebView webview = tab.getWebView();
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001921 // If the last tab was removed from the active tabs page, currentTab
1922 // will be null.
1923 if (currentTab != null) {
1924 removeTabFromContentView(currentTab);
1925 }
Patrick Scott8bbd69f2009-08-14 13:35:53 -04001926 // We must set the new tab as the current tab to reflect the old
1927 // animation behavior.
1928 mTabControl.setCurrentTab(tab);
Grace Klobaeb6eef42009-09-15 17:56:32 -07001929 attachTabToContentView(tab);
Leon Scroggins160a7e72009-08-14 18:28:01 -04001930 if (!urlData.isEmpty()) {
Patrick Scott9d53da02010-02-19 10:19:01 -05001931 loadUrlDataIn(tab, urlData);
Leon Scroggins1f005d32009-08-10 17:36:42 -04001932 }
1933 return tab;
1934 } else {
1935 // Get rid of the subwindow if it exists
1936 dismissSubWindow(currentTab);
1937 if (!urlData.isEmpty()) {
1938 // Load the given url.
Patrick Scott9d53da02010-02-19 10:19:01 -05001939 loadUrlDataIn(currentTab, urlData);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001940 }
Leon Scroggins58d56c62010-01-28 15:12:40 -05001941 return currentTab;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001942 }
1943 }
1944
Michael Kolb68792c82010-08-09 16:39:18 -07001945 private Tab openTab(String url, boolean forceForeground) {
1946 if (mSettings.openInBackground() && !forceForeground) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001947 Tab t = mTabControl.createNewTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001948 if (t != null) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001949 WebView view = t.getWebView();
Leon Scroggins92472e82010-02-17 16:32:28 -05001950 loadUrl(view, url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001951 }
Grace Klobac9181842009-04-14 08:53:22 -07001952 return t;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001953 } else {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001954 return openTabAndShow(url, false, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001955 }
1956 }
1957
Elliott Slaughterf0f03952010-07-14 18:10:36 -07001958 /* package */ Tab openIncognitoTab() {
1959 if (mTabControl.canCreateNewTab()) {
1960 Tab currentTab = mTabControl.getCurrentTab();
1961 Tab tab = mTabControl.createNewTab(false, null, null, true);
1962 if (currentTab != null) {
1963 removeTabFromContentView(currentTab);
1964 }
1965 mTabControl.setCurrentTab(tab);
1966 attachTabToContentView(tab);
1967 return tab;
1968 }
1969 return null;
1970 }
1971
The Android Open Source Project0c908882009-03-03 19:32:16 -08001972 private class Copy implements OnMenuItemClickListener {
1973 private CharSequence mText;
1974
1975 public boolean onMenuItemClick(MenuItem item) {
1976 copy(mText);
1977 return true;
1978 }
1979
1980 public Copy(CharSequence toCopy) {
1981 mText = toCopy;
1982 }
1983 }
1984
1985 private class Download implements OnMenuItemClickListener {
1986 private String mText;
1987
1988 public boolean onMenuItemClick(MenuItem item) {
1989 onDownloadStartNoStream(mText, null, null, null, -1);
1990 return true;
1991 }
1992
1993 public Download(String toDownload) {
1994 mText = toDownload;
1995 }
1996 }
1997
Ben Murdoch4f75ba22009-10-27 11:48:28 +00001998 private class SetAsWallpaper extends Thread implements
1999 OnMenuItemClickListener, DialogInterface.OnCancelListener {
2000 private URL mUrl;
2001 private ProgressDialog mWallpaperProgress;
2002 private boolean mCanceled = false;
2003
2004 public SetAsWallpaper(String url) {
2005 try {
2006 mUrl = new URL(url);
2007 } catch (MalformedURLException e) {
2008 mUrl = null;
2009 }
2010 }
2011
2012 public void onCancel(DialogInterface dialog) {
2013 mCanceled = true;
2014 }
2015
2016 public boolean onMenuItemClick(MenuItem item) {
2017 if (mUrl != null) {
2018 // The user may have tried to set a image with a large file size as their
2019 // background so it may take a few moments to perform the operation. Display
2020 // a progress spinner while it is working.
2021 mWallpaperProgress = new ProgressDialog(BrowserActivity.this);
2022 mWallpaperProgress.setIndeterminate(true);
2023 mWallpaperProgress.setMessage(getText(R.string.progress_dialog_setting_wallpaper));
2024 mWallpaperProgress.setCancelable(true);
2025 mWallpaperProgress.setOnCancelListener(this);
2026 mWallpaperProgress.show();
2027 start();
2028 }
2029 return true;
2030 }
2031
Michael Kolbe0a36662010-06-29 10:37:12 -07002032 @Override
Ben Murdoch4f75ba22009-10-27 11:48:28 +00002033 public void run() {
2034 Drawable oldWallpaper = BrowserActivity.this.getWallpaper();
2035 try {
2036 // TODO: This will cause the resource to be downloaded again, when we
2037 // should in most cases be able to grab it from the cache. To fix this
2038 // we should query WebCore to see if we can access a cached version and
2039 // instead open an input stream on that. This pattern could also be used
2040 // in the download manager where the same problem exists.
2041 InputStream inputstream = mUrl.openStream();
2042 if (inputstream != null) {
2043 setWallpaper(inputstream);
2044 }
2045 } catch (IOException e) {
2046 Log.e(LOGTAG, "Unable to set new wallpaper");
2047 // Act as though the user canceled the operation so we try to
2048 // restore the old wallpaper.
2049 mCanceled = true;
2050 }
2051
2052 if (mCanceled) {
2053 // Restore the old wallpaper if the user cancelled whilst we were setting
2054 // the new wallpaper.
2055 int width = oldWallpaper.getIntrinsicWidth();
2056 int height = oldWallpaper.getIntrinsicHeight();
2057 Bitmap bm = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
2058 Canvas canvas = new Canvas(bm);
2059 oldWallpaper.setBounds(0, 0, width, height);
2060 oldWallpaper.draw(canvas);
2061 try {
2062 setWallpaper(bm);
2063 } catch (IOException e) {
2064 Log.e(LOGTAG, "Unable to restore old wallpaper.");
2065 }
2066 mCanceled = false;
2067 }
2068
2069 if (mWallpaperProgress.isShowing()) {
2070 mWallpaperProgress.dismiss();
2071 }
2072 }
2073 }
2074
The Android Open Source Project0c908882009-03-03 19:32:16 -08002075 private void copy(CharSequence text) {
Dianne Hackborn80f32622010-08-05 14:17:53 -07002076 ClipboardManager cm = (ClipboardManager)getSystemService(Context.CLIPBOARD_SERVICE);
2077 cm.setText(text);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002078 }
2079
2080 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08002081 * Resets the browser title-view to whatever it must be
2082 * (for example, if we had a loading error)
2083 * When we have a new page, we call resetTitle, when we
2084 * have to reset the titlebar to whatever it used to be
2085 * (for example, if the user chose to stop loading), we
2086 * call resetTitleAndRevertLockIcon.
2087 */
2088 /* package */ void resetTitleAndRevertLockIcon() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002089 mTabControl.getCurrentTab().revertLockIcon();
2090 updateLockIconToLatest();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002091 resetTitleIconAndProgress();
2092 }
2093
2094 /**
2095 * Reset the title, favicon, and progress.
2096 */
2097 private void resetTitleIconAndProgress() {
2098 WebView current = mTabControl.getCurrentWebView();
2099 if (current == null) {
2100 return;
2101 }
2102 resetTitleAndIcon(current);
2103 int progress = current.getProgress();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002104 current.getWebChromeClient().onProgressChanged(current, progress);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002105 }
2106
2107 // Reset the title and the icon based on the given item.
2108 private void resetTitleAndIcon(WebView view) {
2109 WebHistoryItem item = view.copyBackForwardList().getCurrentItem();
2110 if (item != null) {
Leon Scroggins68579392009-09-15 15:31:54 -04002111 setUrlTitle(item.getUrl(), item.getTitle());
The Android Open Source Project0c908882009-03-03 19:32:16 -08002112 setFavicon(item.getFavicon());
2113 } else {
Leon Scroggins68579392009-09-15 15:31:54 -04002114 setUrlTitle(null, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002115 setFavicon(null);
2116 }
2117 }
2118
2119 /**
2120 * Sets a title composed of the URL and the title string.
2121 * @param url The URL of the site being loaded.
2122 * @param title The title of the site being loaded.
2123 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07002124 void setUrlTitle(String url, String title) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002125 mUrl = url;
2126 mTitle = title;
2127
Leon Scroggins58d56c62010-01-28 15:12:40 -05002128 // If we are in voice search mode, the title has already been set.
2129 if (mTabControl.getCurrentTab().isInVoiceSearchMode()) return;
2130 mTitleBar.setDisplayTitle(url);
Michael Kolba2b2ba82010-08-04 17:54:03 -07002131 mFakeTitleBar.setDisplayTitle(url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002132 }
2133
2134 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08002135 * @param url The URL to build a title version of the URL from.
2136 * @return The title version of the URL or null if fails.
2137 * The title version of the URL can be either the URL hostname,
2138 * or the hostname with an "https://" prefix (for secure URLs),
2139 * or an empty string if, for example, the URL in question is a
2140 * file:// URL with no hostname.
2141 */
Leon Scroggins32e14a62009-06-11 10:26:34 -04002142 /* package */ static String buildTitleUrl(String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002143 String titleUrl = null;
2144
2145 if (url != null) {
2146 try {
2147 // parse the url string
2148 URL urlObj = new URL(url);
2149 if (urlObj != null) {
2150 titleUrl = "";
2151
2152 String protocol = urlObj.getProtocol();
2153 String host = urlObj.getHost();
2154
2155 if (host != null && 0 < host.length()) {
2156 titleUrl = host;
2157 if (protocol != null) {
2158 // if a secure site, add an "https://" prefix!
2159 if (protocol.equalsIgnoreCase("https")) {
2160 titleUrl = protocol + "://" + host;
2161 }
2162 }
2163 }
2164 }
2165 } catch (MalformedURLException e) {}
2166 }
2167
2168 return titleUrl;
2169 }
2170
2171 // Set the favicon in the title bar.
Grace Kloba22ac16e2009-10-07 18:00:23 -07002172 void setFavicon(Bitmap icon) {
Leon Scroggins68579392009-09-15 15:31:54 -04002173 mTitleBar.setFavicon(icon);
Michael Kolba2b2ba82010-08-04 17:54:03 -07002174 mFakeTitleBar.setFavicon(icon);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002175 }
2176
2177 /**
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002178 * Close the tab, remove its associated title bar, and adjust mTabControl's
2179 * current tab to a valid value.
Leon Scroggins1f005d32009-08-10 17:36:42 -04002180 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07002181 /* package */ void closeTab(Tab t) {
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002182 int currentIndex = mTabControl.getCurrentIndex();
2183 int removeIndex = mTabControl.getTabIndex(t);
Leon Scroggins1f005d32009-08-10 17:36:42 -04002184 mTabControl.removeTab(t);
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002185 if (currentIndex >= removeIndex && currentIndex != 0) {
2186 currentIndex--;
2187 }
2188 mTabControl.setCurrentTab(mTabControl.getTab(currentIndex));
Andrei Popescua5bf1de2009-09-23 16:39:23 +01002189 resetTitleIconAndProgress();
Leon Scroggins654899b2010-06-25 16:25:23 -04002190 updateLockIconToLatest();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002191 }
2192
Leon Scrogginsdcc5eeb2010-02-23 17:26:37 -05002193 /* package */ void goBackOnePageOrQuit() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002194 Tab current = mTabControl.getCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002195 if (current == null) {
2196 /*
2197 * Instead of finishing the activity, simply push this to the back
2198 * of the stack and let ActivityManager to choose the foreground
2199 * activity. As BrowserActivity is singleTask, it will be always the
2200 * root of the task. So we can use either true or false for
2201 * moveTaskToBack().
2202 */
2203 moveTaskToBack(true);
Grace Kloba00d85e72009-09-23 18:50:05 -07002204 return;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002205 }
2206 WebView w = current.getWebView();
2207 if (w.canGoBack()) {
2208 w.goBack();
2209 } else {
2210 // Check to see if we are closing a window that was created by
2211 // another window. If so, we switch back to that window.
Grace Kloba22ac16e2009-10-07 18:00:23 -07002212 Tab parent = current.getParentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002213 if (parent != null) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04002214 switchToTab(mTabControl.getTabIndex(parent));
2215 // Now we close the other tab
2216 closeTab(current);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002217 } else {
2218 if (current.closeOnExit()) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002219 // force the tab's inLoad() to be false as we are going to
2220 // either finish the activity or remove the tab. This will
2221 // ensure pauseWebViewTimers() taking action.
2222 mTabControl.getCurrentTab().clearInLoad();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002223 if (mTabControl.getTabCount() == 1) {
2224 finish();
2225 return;
2226 }
Mike Reed7bfa63b2009-05-28 11:08:32 -04002227 // call pauseWebViewTimers() now, we won't be able to call
2228 // it in onPause() as the WebView won't be valid.
Grace Klobaec1b5ad2009-08-18 08:42:32 -07002229 // Temporarily change mActivityInPause to be true as
2230 // pauseWebViewTimers() will do nothing if mActivityInPause
2231 // is false.
Grace Kloba918e1d72009-08-13 14:55:06 -07002232 boolean savedState = mActivityInPause;
2233 if (savedState) {
Grace Klobaec1b5ad2009-08-18 08:42:32 -07002234 Log.e(LOGTAG, "BrowserActivity is already paused "
2235 + "while handing goBackOnePageOrQuit.");
Grace Kloba918e1d72009-08-13 14:55:06 -07002236 }
2237 mActivityInPause = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -04002238 pauseWebViewTimers();
Grace Kloba918e1d72009-08-13 14:55:06 -07002239 mActivityInPause = savedState;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002240 removeTabFromContentView(current);
2241 mTabControl.removeTab(current);
2242 }
2243 /*
2244 * Instead of finishing the activity, simply push this to the back
2245 * of the stack and let ActivityManager to choose the foreground
2246 * activity. As BrowserActivity is singleTask, it will be always the
2247 * root of the task. So we can use either true or false for
2248 * moveTaskToBack().
2249 */
2250 moveTaskToBack(true);
2251 }
2252 }
2253 }
2254
Grace Kloba22ac16e2009-10-07 18:00:23 -07002255 boolean isMenuDown() {
2256 return mMenuIsDown;
2257 }
2258
Grace Kloba5942df02009-09-18 11:48:29 -07002259 @Override
2260 public boolean onKeyDown(int keyCode, KeyEvent event) {
Leon Scrogginsf65b50d2009-12-08 10:44:28 -05002261 // Even if MENU is already held down, we need to call to super to open
2262 // the IME on long press.
2263 if (KeyEvent.KEYCODE_MENU == keyCode) {
2264 mMenuIsDown = true;
2265 return super.onKeyDown(keyCode, event);
2266 }
Grace Kloba5942df02009-09-18 11:48:29 -07002267 // The default key mode is DEFAULT_KEYS_SEARCH_LOCAL. As the MENU is
2268 // still down, we don't want to trigger the search. Pretend to consume
2269 // the key and do nothing.
2270 if (mMenuIsDown) return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002271
Grace Kloba5942df02009-09-18 11:48:29 -07002272 switch(keyCode) {
Grace Kloba5942df02009-09-18 11:48:29 -07002273 case KeyEvent.KEYCODE_SPACE:
Grace Klobada0fe552009-09-22 18:17:24 -07002274 // WebView/WebTextView handle the keys in the KeyDown. As
2275 // the Activity's shortcut keys are only handled when WebView
2276 // doesn't, have to do it in onKeyDown instead of onKeyUp.
2277 if (event.isShiftPressed()) {
2278 getTopWindow().pageUp(false);
2279 } else {
2280 getTopWindow().pageDown(false);
2281 }
Grace Kloba5942df02009-09-18 11:48:29 -07002282 return true;
2283 case KeyEvent.KEYCODE_BACK:
2284 if (event.getRepeatCount() == 0) {
2285 event.startTracking();
2286 return true;
2287 } else if (mCustomView == null && mActiveTabsPage == null
2288 && event.isLongPress()) {
Michael Kolb68792c82010-08-09 16:39:18 -07002289 bookmarksOrHistoryPicker(true, false);
Grace Kloba5942df02009-09-18 11:48:29 -07002290 return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002291 }
Grace Kloba5942df02009-09-18 11:48:29 -07002292 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002293 }
Grace Kloba5942df02009-09-18 11:48:29 -07002294 return super.onKeyDown(keyCode, event);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002295 }
2296
Grace Kloba5942df02009-09-18 11:48:29 -07002297 @Override
2298 public boolean onKeyUp(int keyCode, KeyEvent event) {
2299 switch(keyCode) {
2300 case KeyEvent.KEYCODE_MENU:
2301 mMenuIsDown = false;
2302 break;
Grace Kloba5942df02009-09-18 11:48:29 -07002303 case KeyEvent.KEYCODE_BACK:
2304 if (event.isTracking() && !event.isCanceled()) {
2305 if (mCustomView != null) {
2306 // if a custom view is showing, hide it
Grace Kloba22ac16e2009-10-07 18:00:23 -07002307 mTabControl.getCurrentWebView().getWebChromeClient()
2308 .onHideCustomView();
Grace Kloba5942df02009-09-18 11:48:29 -07002309 } else if (mActiveTabsPage != null) {
2310 // if tab page is showing, hide it
2311 removeActiveTabPage(true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002312 } else {
Grace Kloba5942df02009-09-18 11:48:29 -07002313 WebView subwindow = mTabControl.getCurrentSubWindow();
2314 if (subwindow != null) {
2315 if (subwindow.canGoBack()) {
2316 subwindow.goBack();
2317 } else {
2318 dismissSubWindow(mTabControl.getCurrentTab());
2319 }
2320 } else {
2321 goBackOnePageOrQuit();
2322 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002323 }
Grace Kloba5942df02009-09-18 11:48:29 -07002324 return true;
2325 }
2326 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002327 }
Grace Kloba5942df02009-09-18 11:48:29 -07002328 return super.onKeyUp(keyCode, event);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002329 }
2330
Leon Scroggins68579392009-09-15 15:31:54 -04002331 /* package */ void stopLoading() {
Ben Murdochb7cc8b42009-09-28 10:59:09 +01002332 mDidStopLoad = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002333 resetTitleAndRevertLockIcon();
2334 WebView w = getTopWindow();
2335 w.stopLoading();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002336 // FIXME: before refactor, it is using mWebViewClient. So I keep the
2337 // same logic here. But for subwindow case, should we call into the main
2338 // WebView's onPageFinished as we never call its onPageStarted and if
2339 // the page finishes itself, we don't call onPageFinished.
2340 mTabControl.getCurrentWebView().getWebViewClient().onPageFinished(w,
2341 w.getUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08002342
2343 cancelStopToast();
2344 mStopToast = Toast
2345 .makeText(this, R.string.stopping, Toast.LENGTH_SHORT);
2346 mStopToast.show();
2347 }
2348
Grace Kloba22ac16e2009-10-07 18:00:23 -07002349 boolean didUserStopLoading() {
2350 return mDidStopLoad;
2351 }
2352
The Android Open Source Project0c908882009-03-03 19:32:16 -08002353 private void cancelStopToast() {
2354 if (mStopToast != null) {
2355 mStopToast.cancel();
2356 mStopToast = null;
2357 }
2358 }
2359
Grace Kloba22ac16e2009-10-07 18:00:23 -07002360 // called by a UI or non-UI thread to post the message
2361 public void postMessage(int what, int arg1, int arg2, Object obj,
2362 long delayMillis) {
2363 mHandler.sendMessageDelayed(mHandler.obtainMessage(what, arg1, arg2,
2364 obj), delayMillis);
2365 }
2366
2367 // called by a UI or non-UI thread to remove the message
2368 void removeMessages(int what, Object object) {
2369 mHandler.removeMessages(what, object);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002370 }
2371
2372 // public message ids
2373 public final static int LOAD_URL = 1001;
2374 public final static int STOP_LOAD = 1002;
2375
2376 // Message Ids
2377 private static final int FOCUS_NODE_HREF = 102;
Grace Kloba92c18a52009-07-31 23:48:32 -07002378 private static final int RELEASE_WAKELOCK = 107;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002379
Grace Kloba22ac16e2009-10-07 18:00:23 -07002380 static final int UPDATE_BOOKMARK_THUMBNAIL = 108;
Ben Murdoch2694e232009-09-29 09:41:11 +01002381
Ben Murdocheecb4e62010-07-06 16:30:38 +01002382 private static final int TOUCH_ICON_DOWNLOADED = 109;
2383
The Android Open Source Project0c908882009-03-03 19:32:16 -08002384 // Private handler for handling javascript and saving passwords
2385 private Handler mHandler = new Handler() {
2386
Michael Kolbe0a36662010-06-29 10:37:12 -07002387 @Override
The Android Open Source Project0c908882009-03-03 19:32:16 -08002388 public void handleMessage(Message msg) {
2389 switch (msg.what) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002390 case FOCUS_NODE_HREF:
Ben Murdoch2694e232009-09-29 09:41:11 +01002391 {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002392 String url = (String) msg.getData().get("url");
Ben Murdoch90d088c2009-11-17 18:14:04 +00002393 String title = (String) msg.getData().get("title");
The Android Open Source Project0c908882009-03-03 19:32:16 -08002394 if (url == null || url.length() == 0) {
2395 break;
2396 }
2397 HashMap focusNodeMap = (HashMap) msg.obj;
2398 WebView view = (WebView) focusNodeMap.get("webview");
2399 // Only apply the action if the top window did not change.
2400 if (getTopWindow() != view) {
2401 break;
2402 }
2403 switch (msg.arg1) {
2404 case R.id.open_context_menu_id:
2405 case R.id.view_image_context_menu_id:
Leon Scroggins92472e82010-02-17 16:32:28 -05002406 loadUrlFromContext(getTopWindow(), url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002407 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002408 case R.id.bookmark_context_menu_id:
2409 Intent intent = new Intent(BrowserActivity.this,
2410 AddBookmarkPage.class);
2411 intent.putExtra("url", url);
Ben Murdoch90d088c2009-11-17 18:14:04 +00002412 intent.putExtra("title", title);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002413 startActivity(intent);
2414 break;
2415 case R.id.share_link_context_menu_id:
Leon Scroggins3e204452010-05-10 11:06:03 -04002416 sharePage(BrowserActivity.this, title, url, null,
Leon Scroggins96afcb12009-12-10 12:35:56 -05002417 null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002418 break;
2419 case R.id.copy_link_context_menu_id:
2420 copy(url);
2421 break;
2422 case R.id.save_link_context_menu_id:
2423 case R.id.download_context_menu_id:
2424 onDownloadStartNoStream(url, null, null, null, -1);
2425 break;
2426 }
2427 break;
Ben Murdoch2694e232009-09-29 09:41:11 +01002428 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002429
2430 case LOAD_URL:
Leon Scroggins92472e82010-02-17 16:32:28 -05002431 loadUrlFromContext(getTopWindow(), (String) msg.obj);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002432 break;
2433
2434 case STOP_LOAD:
2435 stopLoading();
2436 break;
2437
The Android Open Source Project0c908882009-03-03 19:32:16 -08002438 case RELEASE_WAKELOCK:
2439 if (mWakeLock.isHeld()) {
2440 mWakeLock.release();
Grace Kloba5d0e02e2009-10-05 15:15:36 -07002441 // if we reach here, Browser should be still in the
2442 // background loading after WAKELOCK_TIMEOUT (5-min).
2443 // To avoid burning the battery, stop loading.
2444 mTabControl.stopAllLoading();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002445 }
2446 break;
Ben Murdoch2694e232009-09-29 09:41:11 +01002447
2448 case UPDATE_BOOKMARK_THUMBNAIL:
2449 WebView view = (WebView) msg.obj;
2450 if (view != null) {
2451 updateScreenshot(view);
2452 }
2453 break;
Ben Murdocheecb4e62010-07-06 16:30:38 +01002454
2455 case TOUCH_ICON_DOWNLOADED:
2456 Bundle b = msg.getData();
2457 showSaveToHomescreenDialog(b.getString("url"),
2458 b.getString("title"),
2459 (Bitmap) b.getParcelable("touchIcon"),
2460 (Bitmap) b.getParcelable("favicon"));
2461 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002462 }
2463 }
2464 };
2465
Leon Scroggins96afcb12009-12-10 12:35:56 -05002466 /**
2467 * Share a page, providing the title, url, favicon, and a screenshot. Uses
2468 * an {@link Intent} to launch the Activity chooser.
2469 * @param c Context used to launch a new Activity.
2470 * @param title Title of the page. Stored in the Intent with
Paul Westbrook03e6d392010-02-12 10:33:29 -08002471 * {@link Intent#EXTRA_SUBJECT}
Leon Scroggins96afcb12009-12-10 12:35:56 -05002472 * @param url URL of the page. Stored in the Intent with
2473 * {@link Intent#EXTRA_TEXT}
2474 * @param favicon Bitmap of the favicon for the page. Stored in the Intent
2475 * with {@link Browser#EXTRA_SHARE_FAVICON}
2476 * @param screenshot Bitmap of a screenshot of the page. Stored in the
2477 * Intent with {@link Browser#EXTRA_SHARE_SCREENSHOT}
2478 */
2479 public static final void sharePage(Context c, String title, String url,
2480 Bitmap favicon, Bitmap screenshot) {
2481 Intent send = new Intent(Intent.ACTION_SEND);
2482 send.setType("text/plain");
2483 send.putExtra(Intent.EXTRA_TEXT, url);
Paul Westbrook03e6d392010-02-12 10:33:29 -08002484 send.putExtra(Intent.EXTRA_SUBJECT, title);
Leon Scroggins96afcb12009-12-10 12:35:56 -05002485 send.putExtra(Browser.EXTRA_SHARE_FAVICON, favicon);
2486 send.putExtra(Browser.EXTRA_SHARE_SCREENSHOT, screenshot);
2487 try {
2488 c.startActivity(Intent.createChooser(send, c.getString(
2489 R.string.choosertitle_sharevia)));
2490 } catch(android.content.ActivityNotFoundException ex) {
2491 // if no app handles it, do nothing
2492 }
2493 }
2494
Leon Scroggins89c6d362009-07-15 16:54:37 -04002495 private void updateScreenshot(WebView view) {
2496 // If this is a bookmarked site, add a screenshot to the database.
2497 // FIXME: When should we update? Every time?
2498 // FIXME: Would like to make sure there is actually something to
2499 // draw, but the API for that (WebViewCore.pictureReady()) is not
2500 // currently accessible here.
Ben Murdochaac7aa62009-09-17 16:57:40 +01002501
Ben Murdoch87cc65d2010-06-29 20:34:10 +01002502 final Bitmap bm = createScreenshot(view, getDesiredThumbnailWidth(this),
2503 getDesiredThumbnailHeight(this));
Patrick Scottcb192b52010-04-14 14:38:55 -04002504 if (bm == null) {
2505 return;
Leon Scroggins89c6d362009-07-15 16:54:37 -04002506 }
Patrick Scottcb192b52010-04-14 14:38:55 -04002507
2508 final ContentResolver cr = getContentResolver();
2509 final String url = view.getUrl();
2510 final String originalUrl = view.getOriginalUrl();
2511
2512 new AsyncTask<Void, Void, Void>() {
2513 @Override
2514 protected Void doInBackground(Void... unused) {
2515 Cursor c = null;
2516 try {
Jeff Hamilton84029622010-08-05 14:29:28 -05002517 c = Bookmarks.queryBookmarksForUrl(
Jeff Hamilton8ce956c2010-08-17 11:13:53 -05002518 cr, originalUrl, url);
Patrick Scottcb192b52010-04-14 14:38:55 -04002519 if (c != null) {
2520 if (c.moveToFirst()) {
2521 ContentValues values = new ContentValues();
2522 final ByteArrayOutputStream os
2523 = new ByteArrayOutputStream();
2524 bm.compress(Bitmap.CompressFormat.PNG, 100, os);
Jeff Hamilton8ce956c2010-08-17 11:13:53 -05002525 values.put(BrowserContract.Bookmarks.THUMBNAIL,
Patrick Scottcb192b52010-04-14 14:38:55 -04002526 os.toByteArray());
2527 do {
2528 cr.update(ContentUris.withAppendedId(
Jeff Hamilton8ce956c2010-08-17 11:13:53 -05002529 BrowserContract.Bookmarks.CONTENT_URI, c.getLong(0)),
Patrick Scottcb192b52010-04-14 14:38:55 -04002530 values, null, null);
2531 } while (c.moveToNext());
2532 }
2533 }
2534 } catch (IllegalStateException e) {
2535 // Ignore
2536 } finally {
2537 if (c != null) c.close();
2538 }
2539 return null;
2540 }
2541 }.execute();
Leon Scroggins89c6d362009-07-15 16:54:37 -04002542 }
2543
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002544 /**
Leon Scrogginsf8551612009-09-24 16:06:02 -04002545 * Values for the size of the thumbnail created when taking a screenshot.
2546 * Lazily initialized. Instead of using these directly, use
2547 * getDesiredThumbnailWidth() or getDesiredThumbnailHeight().
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002548 */
Leon Scrogginsf8551612009-09-24 16:06:02 -04002549 private static int THUMBNAIL_WIDTH = 0;
2550 private static int THUMBNAIL_HEIGHT = 0;
2551
2552 /**
2553 * Return the desired width for thumbnail screenshots, which are stored in
2554 * the database, and used on the bookmarks screen.
2555 * @param context Context for finding out the density of the screen.
2556 * @return int desired width for thumbnail screenshot.
2557 */
2558 /* package */ static int getDesiredThumbnailWidth(Context context) {
2559 if (THUMBNAIL_WIDTH == 0) {
2560 float density = context.getResources().getDisplayMetrics().density;
2561 THUMBNAIL_WIDTH = (int) (90 * density);
2562 THUMBNAIL_HEIGHT = (int) (80 * density);
2563 }
2564 return THUMBNAIL_WIDTH;
2565 }
2566
2567 /**
2568 * Return the desired height for thumbnail screenshots, which are stored in
2569 * the database, and used on the bookmarks screen.
2570 * @param context Context for finding out the density of the screen.
2571 * @return int desired height for thumbnail screenshot.
2572 */
2573 /* package */ static int getDesiredThumbnailHeight(Context context) {
2574 // To ensure that they are both initialized.
2575 getDesiredThumbnailWidth(context);
2576 return THUMBNAIL_HEIGHT;
2577 }
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002578
Ben Murdoch87cc65d2010-06-29 20:34:10 +01002579 private Bitmap createScreenshot(WebView view, int width, int height) {
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002580 Picture thumbnail = view.capturePicture();
Leon Scroggins45800572009-09-29 16:38:47 -04002581 if (thumbnail == null) {
2582 return null;
2583 }
Ben Murdoch87cc65d2010-06-29 20:34:10 +01002584 Bitmap bm = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002585 Canvas canvas = new Canvas(bm);
2586 // May need to tweak these values to determine what is the
2587 // best scale factor
Ben Murdoch2694e232009-09-29 09:41:11 +01002588 int thumbnailWidth = thumbnail.getWidth();
Ben Murdochae59c3f2009-10-20 18:30:28 +01002589 int thumbnailHeight = thumbnail.getHeight();
2590 float scaleFactorX = 1.0f;
2591 float scaleFactorY = 1.0f;
Ben Murdoch2694e232009-09-29 09:41:11 +01002592 if (thumbnailWidth > 0) {
Ben Murdoch87cc65d2010-06-29 20:34:10 +01002593 scaleFactorX = (float) width / (float)thumbnailWidth;
Ben Murdochae59c3f2009-10-20 18:30:28 +01002594 } else {
2595 return null;
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002596 }
Ben Murdochae59c3f2009-10-20 18:30:28 +01002597
2598 if (view.getWidth() > view.getHeight() &&
2599 thumbnailHeight < view.getHeight() && thumbnailHeight > 0) {
2600 // If the device is in landscape and the page is shorter
2601 // than the height of the view, stretch the thumbnail to fill the
2602 // space.
Ben Murdoch87cc65d2010-06-29 20:34:10 +01002603 scaleFactorY = (float) height / (float)thumbnailHeight;
Ben Murdochae59c3f2009-10-20 18:30:28 +01002604 } else {
2605 // In the portrait case, this looks nice.
2606 scaleFactorY = scaleFactorX;
2607 }
2608
2609 canvas.scale(scaleFactorX, scaleFactorY);
2610
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002611 thumbnail.draw(canvas);
2612 return bm;
2613 }
2614
The Android Open Source Project0c908882009-03-03 19:32:16 -08002615 // -------------------------------------------------------------------------
Grace Kloba22ac16e2009-10-07 18:00:23 -07002616 // Helper function for WebViewClient.
The Android Open Source Project0c908882009-03-03 19:32:16 -08002617 //-------------------------------------------------------------------------
2618
2619 // Use in overrideUrlLoading
2620 /* package */ final static String SCHEME_WTAI = "wtai://wp/";
2621 /* package */ final static String SCHEME_WTAI_MC = "wtai://wp/mc;";
2622 /* package */ final static String SCHEME_WTAI_SD = "wtai://wp/sd;";
2623 /* package */ final static String SCHEME_WTAI_AP = "wtai://wp/ap;";
2624
Leon Scroggins92472e82010-02-17 16:32:28 -05002625 // Keep this initial progress in sync with initialProgressValue (* 100)
2626 // in ProgressTracker.cpp
2627 private final static int INITIAL_PROGRESS = 10;
2628
Grace Kloba22ac16e2009-10-07 18:00:23 -07002629 void onPageStarted(WebView view, String url, Bitmap favicon) {
2630 // when BrowserActivity just starts, onPageStarted may be called before
2631 // onResume as it is triggered from onCreate. Call resumeWebViewTimers
2632 // to start the timer. As we won't switch tabs while an activity is in
2633 // pause state, we can ensure calling resume and pause in pair.
2634 if (mActivityInPause) resumeWebViewTimers();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002635
Grace Kloba22ac16e2009-10-07 18:00:23 -07002636 resetLockIcon(url);
2637 setUrlTitle(url, null);
2638 setFavicon(favicon);
Leon Scroggins8cf8f682009-11-04 11:13:50 -08002639 // Show some progress so that the user knows the page is beginning to
2640 // load
Leon Scroggins92472e82010-02-17 16:32:28 -05002641 onProgressChanged(view, INITIAL_PROGRESS);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002642 mDidStopLoad = false;
Grace Kloba22ac16e2009-10-07 18:00:23 -07002643 if (!mIsNetworkUp) createAndShowNetworkDialog();
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04002644 endActionMode();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002645 if (mSettings.isTracing()) {
2646 String host;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002647 try {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002648 WebAddress uri = new WebAddress(url);
2649 host = uri.mHost;
2650 } catch (android.net.ParseException ex) {
2651 host = "browser";
The Android Open Source Project0c908882009-03-03 19:32:16 -08002652 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002653 host = host.replace('.', '_');
2654 host += ".trace";
2655 mInTrace = true;
2656 Debug.startMethodTracing(host, 20 * 1024 * 1024);
2657 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002658
Grace Kloba22ac16e2009-10-07 18:00:23 -07002659 // Performance probe
2660 if (false) {
2661 mStart = SystemClock.uptimeMillis();
2662 mProcessStart = Process.getElapsedCpuTime();
2663 long[] sysCpu = new long[7];
2664 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2665 sysCpu, null)) {
2666 mUserStart = sysCpu[0] + sysCpu[1];
2667 mSystemStart = sysCpu[2];
2668 mIdleStart = sysCpu[3];
2669 mIrqStart = sysCpu[4] + sysCpu[5] + sysCpu[6];
2670 }
2671 mUiStart = SystemClock.currentThreadTimeMillis();
2672 }
2673 }
2674
2675 void onPageFinished(WebView view, String url) {
2676 // Reset the title and icon in case we stopped a provisional load.
2677 resetTitleAndIcon(view);
2678 // Update the lock icon image only once we are done loading
2679 updateLockIconToLatest();
2680 // pause the WebView timer and release the wake lock if it is finished
2681 // while BrowserActivity is in pause state.
2682 if (mActivityInPause && pauseWebViewTimers()) {
2683 if (mWakeLock.isHeld()) {
2684 mHandler.removeMessages(RELEASE_WAKELOCK);
2685 mWakeLock.release();
2686 }
2687 }
2688
2689 // Performance probe
2690 if (false) {
2691 long[] sysCpu = new long[7];
2692 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2693 sysCpu, null)) {
2694 String uiInfo = "UI thread used "
2695 + (SystemClock.currentThreadTimeMillis() - mUiStart)
2696 + " ms";
2697 if (LOGD_ENABLED) {
2698 Log.d(LOGTAG, uiInfo);
2699 }
2700 //The string that gets written to the log
2701 String performanceString = "It took total "
2702 + (SystemClock.uptimeMillis() - mStart)
2703 + " ms clock time to load the page."
2704 + "\nbrowser process used "
2705 + (Process.getElapsedCpuTime() - mProcessStart)
2706 + " ms, user processes used "
2707 + (sysCpu[0] + sysCpu[1] - mUserStart) * 10
2708 + " ms, kernel used "
2709 + (sysCpu[2] - mSystemStart) * 10
2710 + " ms, idle took " + (sysCpu[3] - mIdleStart) * 10
2711 + " ms and irq took "
2712 + (sysCpu[4] + sysCpu[5] + sysCpu[6] - mIrqStart)
2713 * 10 + " ms, " + uiInfo;
2714 if (LOGD_ENABLED) {
2715 Log.d(LOGTAG, performanceString + "\nWebpage: " + url);
2716 }
2717 if (url != null) {
2718 // strip the url to maintain consistency
2719 String newUrl = new String(url);
2720 if (newUrl.startsWith("http://www.")) {
2721 newUrl = newUrl.substring(11);
2722 } else if (newUrl.startsWith("http://")) {
2723 newUrl = newUrl.substring(7);
2724 } else if (newUrl.startsWith("https://www.")) {
2725 newUrl = newUrl.substring(12);
2726 } else if (newUrl.startsWith("https://")) {
2727 newUrl = newUrl.substring(8);
2728 }
2729 if (LOGD_ENABLED) {
2730 Log.d(LOGTAG, newUrl + " loaded");
2731 }
Grace Kloba5b078b52009-06-24 20:23:41 -07002732 }
2733 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002734 }
Grace Kloba5b078b52009-06-24 20:23:41 -07002735
Grace Kloba22ac16e2009-10-07 18:00:23 -07002736 if (mInTrace) {
2737 mInTrace = false;
2738 Debug.stopMethodTracing();
2739 }
2740 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002741
Grace Klobae7fe26b2010-06-28 16:23:33 -07002742 private void closeEmptyChildTab() {
2743 Tab current = mTabControl.getCurrentTab();
2744 if (current != null
2745 && current.getWebView().copyBackForwardList().getSize() == 0) {
2746 Tab parent = current.getParentTab();
2747 if (parent != null) {
2748 switchToTab(mTabControl.getTabIndex(parent));
2749 closeTab(current);
2750 }
2751 }
2752 }
2753
Grace Kloba22ac16e2009-10-07 18:00:23 -07002754 boolean shouldOverrideUrlLoading(WebView view, String url) {
2755 if (url.startsWith(SCHEME_WTAI)) {
2756 // wtai://wp/mc;number
2757 // number=string(phone-number)
2758 if (url.startsWith(SCHEME_WTAI_MC)) {
2759 Intent intent = new Intent(Intent.ACTION_VIEW,
2760 Uri.parse(WebView.SCHEME_TEL +
2761 url.substring(SCHEME_WTAI_MC.length())));
2762 startActivity(intent);
Grace Klobae7fe26b2010-06-28 16:23:33 -07002763 // before leaving BrowserActivity, close the empty child tab.
2764 // If a new tab is created through JavaScript open to load this
2765 // url, we would like to close it as we will load this url in a
2766 // different Activity.
2767 closeEmptyChildTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002768 return true;
2769 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002770 // wtai://wp/sd;dtmf
2771 // dtmf=string(dialstring)
2772 if (url.startsWith(SCHEME_WTAI_SD)) {
2773 // TODO: only send when there is active voice connection
2774 return false;
2775 }
2776 // wtai://wp/ap;number;name
2777 // number=string(phone-number)
2778 // name=string
2779 if (url.startsWith(SCHEME_WTAI_AP)) {
2780 // TODO
2781 return false;
2782 }
2783 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002784
Grace Kloba22ac16e2009-10-07 18:00:23 -07002785 // The "about:" schemes are internal to the browser; don't want these to
2786 // be dispatched to other apps.
2787 if (url.startsWith("about:")) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002788 return false;
2789 }
2790
Jeff Davidson43610292010-07-16 16:03:58 -07002791 // If this is a Google search, attempt to add an RLZ string (if one isn't already present).
2792 if (rlzProviderPresent()) {
2793 Uri siteUri = Uri.parse(url);
2794 if (needsRlzString(siteUri)) {
2795 String rlz = null;
2796 Cursor cur = null;
2797 try {
2798 cur = getContentResolver().query(getRlzUri(), null, null, null, null);
2799 if (cur != null && cur.moveToFirst() && !cur.isNull(0)) {
2800 url = siteUri.buildUpon()
2801 .appendQueryParameter("rlz", cur.getString(0))
2802 .build().toString();
2803 }
2804 } finally {
2805 if (cur != null) {
2806 cur.close();
2807 }
2808 }
2809 loadUrl(view, url);
2810 return true;
2811 }
2812 }
2813
Grace Kloba22ac16e2009-10-07 18:00:23 -07002814 Intent intent;
2815 // perform generic parsing of the URI to turn it into an Intent.
2816 try {
2817 intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME);
2818 } catch (URISyntaxException ex) {
2819 Log.w("Browser", "Bad URI " + url + ": " + ex.getMessage());
2820 return false;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002821 }
2822
Grace Kloba22ac16e2009-10-07 18:00:23 -07002823 // check whether the intent can be resolved. If not, we will see
2824 // whether we can download it from the Market.
2825 if (getPackageManager().resolveActivity(intent, 0) == null) {
2826 String packagename = intent.getPackage();
2827 if (packagename != null) {
2828 intent = new Intent(Intent.ACTION_VIEW, Uri
2829 .parse("market://search?q=pname:" + packagename));
2830 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2831 startActivity(intent);
Grace Klobae7fe26b2010-06-28 16:23:33 -07002832 // before leaving BrowserActivity, close the empty child tab.
2833 // If a new tab is created through JavaScript open to load this
2834 // url, we would like to close it as we will load this url in a
2835 // different Activity.
2836 closeEmptyChildTab();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002837 return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002838 } else {
2839 return false;
2840 }
2841 }
2842
Grace Kloba22ac16e2009-10-07 18:00:23 -07002843 // sanitize the Intent, ensuring web pages can not bypass browser
2844 // security (only access to BROWSABLE activities).
2845 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2846 intent.setComponent(null);
2847 try {
2848 if (startActivityIfNeeded(intent, -1)) {
Grace Klobae7fe26b2010-06-28 16:23:33 -07002849 // before leaving BrowserActivity, close the empty child tab.
2850 // If a new tab is created through JavaScript open to load this
2851 // url, we would like to close it as we will load this url in a
2852 // different Activity.
2853 closeEmptyChildTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002854 return true;
2855 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002856 } catch (ActivityNotFoundException ex) {
2857 // ignore the error. If no application can handle the URL,
2858 // eg about:blank, assume the browser can handle it.
2859 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002860
Grace Kloba22ac16e2009-10-07 18:00:23 -07002861 if (mMenuIsDown) {
Michael Kolb68792c82010-08-09 16:39:18 -07002862 openTab(url, false);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002863 closeOptionsMenu();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002864 return true;
2865 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002866 return false;
2867 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002868
Jeff Davidson43610292010-07-16 16:03:58 -07002869 // Determine whether the RLZ provider is present on the system.
2870 private boolean rlzProviderPresent() {
2871 if (mIsProviderPresent == null) {
2872 PackageManager pm = getPackageManager();
2873 mIsProviderPresent = pm.resolveContentProvider(BrowserSettings.RLZ_PROVIDER, 0) != null;
2874 }
2875 return mIsProviderPresent;
2876 }
2877
2878 // Retrieve the RLZ access point string and cache the URI used to retrieve RLZ values.
2879 private Uri getRlzUri() {
2880 if (mRlzUri == null) {
2881 String ap = getResources().getString(R.string.rlz_access_point);
2882 mRlzUri = Uri.withAppendedPath(BrowserSettings.RLZ_PROVIDER_URI, ap);
2883 }
2884 return mRlzUri;
2885 }
2886
2887 // Determine if this URI appears to be for a Google search and does not have an RLZ parameter.
2888 // Taken largely from Chrome source, src/chrome/browser/google_url_tracker.cc
2889 private static boolean needsRlzString(Uri uri) {
2890 if ((uri.getQueryParameter("q") != null) && (uri.getQueryParameter("rlz") == null)) {
2891 String host = uri.getHost();
2892 if (host == null) {
2893 return false;
2894 }
2895 String[] hostComponents = host.split("\\.");
2896
2897 if (hostComponents.length < 2) {
2898 return false;
2899 }
2900 int googleComponent = hostComponents.length - 2;
2901 String component = hostComponents[googleComponent];
2902 if (!"google".equals(component)) {
2903 if (hostComponents.length < 3 ||
2904 (!"co".equals(component) && !"com".equals(component))) {
2905 return false;
2906 }
2907 googleComponent = hostComponents.length - 3;
2908 if (!"google".equals(hostComponents[googleComponent])) {
2909 return false;
2910 }
2911 }
2912
2913 // Google corp network handling.
2914 if (googleComponent > 0 && "corp".equals(hostComponents[googleComponent - 1])) {
2915 return false;
2916 }
2917
2918 return true;
2919 }
2920 return false;
2921 }
2922
Grace Kloba22ac16e2009-10-07 18:00:23 -07002923 // -------------------------------------------------------------------------
2924 // Helper function for WebChromeClient
2925 // -------------------------------------------------------------------------
The Android Open Source Project0c908882009-03-03 19:32:16 -08002926
Grace Kloba22ac16e2009-10-07 18:00:23 -07002927 void onProgressChanged(WebView view, int newProgress) {
Michael Kolba2b2ba82010-08-04 17:54:03 -07002928
2929 // On the phone, the fake title bar will always cover up the
2930 // regular title bar (or the regular one is offscreen), so only the
2931 // fake title bar needs to change its progress
2932 mFakeTitleBar.setProgress(newProgress);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002933
Grace Kloba22ac16e2009-10-07 18:00:23 -07002934 if (newProgress == 100) {
2935 // onProgressChanged() may continue to be called after the main
2936 // frame has finished loading, as any remaining sub frames continue
2937 // to load. We'll only get called once though with newProgress as
2938 // 100 when everything is loaded. (onPageFinished is called once
2939 // when the main frame completes loading regardless of the state of
2940 // any sub frames so calls to onProgressChanges may continue after
2941 // onPageFinished has executed)
2942 if (mInLoad) {
2943 mInLoad = false;
Leon Scrogginsa27ff192009-09-14 12:58:04 -04002944 updateInLoadMenuItems();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002945 // If the options menu is open, leave the title bar
2946 if (!mOptionsMenuOpen || !mIconView) {
2947 hideFakeTitleBar();
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07002948 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002949 }
Leon Scrogginsaa37e7f2010-03-05 11:51:20 -05002950 } else {
2951 if (!mInLoad) {
2952 // onPageFinished may have already been called but a subframe is
2953 // still loading and updating the progress. Reset mInLoad and
2954 // update the menu items.
2955 mInLoad = true;
2956 updateInLoadMenuItems();
2957 }
2958 // When the page first begins to load, the Activity may still be
2959 // paused, in which case showFakeTitleBar will do nothing. Call
2960 // again as the page continues to load so that it will be shown.
2961 // (Calling it will the fake title bar is already showing will also
2962 // do nothing.
Grace Kloba22ac16e2009-10-07 18:00:23 -07002963 if (!mOptionsMenuOpen || mIconView) {
2964 // This page has begun to load, so show the title bar
2965 showFakeTitleBar();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002966 }
2967 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002968 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002969
Grace Kloba22ac16e2009-10-07 18:00:23 -07002970 void onShowCustomView(View view, WebChromeClient.CustomViewCallback callback) {
Derek Sollenberger8ff57db2009-12-08 15:39:55 -05002971 // if a view already exists then immediately terminate the new one
2972 if (mCustomView != null) {
2973 callback.onCustomViewHidden();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002974 return;
Derek Sollenberger8ff57db2009-12-08 15:39:55 -05002975 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002976
2977 // Add the custom view to its container.
2978 mCustomViewContainer.addView(view, COVER_SCREEN_GRAVITY_CENTER);
2979 mCustomView = view;
2980 mCustomViewCallback = callback;
2981 // Save the menu state and set it to empty while the custom
2982 // view is showing.
2983 mOldMenuState = mMenuState;
2984 mMenuState = EMPTY_MENU;
2985 // Hide the content view.
2986 mContentView.setVisibility(View.GONE);
2987 // Finally show the custom view container.
Andrei Popescu163ab742009-10-20 17:58:23 +01002988 setStatusBarVisibility(false);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002989 mCustomViewContainer.setVisibility(View.VISIBLE);
2990 mCustomViewContainer.bringToFront();
2991 }
2992
2993 void onHideCustomView() {
2994 if (mCustomView == null)
2995 return;
2996
2997 // Hide the custom view.
2998 mCustomView.setVisibility(View.GONE);
2999 // Remove the custom view from its container.
3000 mCustomViewContainer.removeView(mCustomView);
3001 mCustomView = null;
3002 // Reset the old menu state.
3003 mMenuState = mOldMenuState;
3004 mOldMenuState = EMPTY_MENU;
3005 mCustomViewContainer.setVisibility(View.GONE);
3006 mCustomViewCallback.onCustomViewHidden();
3007 // Show the content view.
Andrei Popescu163ab742009-10-20 17:58:23 +01003008 setStatusBarVisibility(true);
Grace Kloba22ac16e2009-10-07 18:00:23 -07003009 mContentView.setVisibility(View.VISIBLE);
3010 }
3011
3012 Bitmap getDefaultVideoPoster() {
3013 if (mDefaultVideoPoster == null) {
3014 mDefaultVideoPoster = BitmapFactory.decodeResource(
3015 getResources(), R.drawable.default_video_poster);
Patrick Scott3918d442009-08-04 13:22:29 -04003016 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07003017 return mDefaultVideoPoster;
3018 }
Patrick Scott3918d442009-08-04 13:22:29 -04003019
Grace Kloba22ac16e2009-10-07 18:00:23 -07003020 View getVideoLoadingProgressView() {
3021 if (mVideoProgressView == null) {
3022 LayoutInflater inflater = LayoutInflater.from(BrowserActivity.this);
3023 mVideoProgressView = inflater.inflate(
3024 R.layout.video_loading_progress, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003025 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07003026 return mVideoProgressView;
3027 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003028
Leon Scroggins8d5fa432009-10-02 15:55:59 -04003029 /*
3030 * The Object used to inform the WebView of the file to upload.
3031 */
3032 private ValueCallback<Uri> mUploadMessage;
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003033 private String mCameraFilePath;
Leon Scroggins8d5fa432009-10-02 15:55:59 -04003034
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003035 void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
3036
3037 final String imageMimeType = "image/*";
Ben Murdoch6af492a2010-06-15 12:38:17 +01003038 final String videoMimeType = "video/*";
Ben Murdoch039bd472010-07-21 21:26:57 +01003039 final String audioMimeType = "audio/*";
Ben Murdochb50d7402010-07-16 12:42:22 +01003040 final String mediaSourceKey = "capture";
Ben Murdoch6af492a2010-06-15 12:38:17 +01003041 final String mediaSourceValueCamera = "camera";
Ben Murdochb50d7402010-07-16 12:42:22 +01003042 final String mediaSourceValueFileSystem = "filesystem";
Ben Murdoch6af492a2010-06-15 12:38:17 +01003043 final String mediaSourceValueCamcorder = "camcorder";
Ben Murdoch039bd472010-07-21 21:26:57 +01003044 final String mediaSourceValueMicrophone = "microphone";
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003045
Ben Murdoch039bd472010-07-21 21:26:57 +01003046 // media source can be 'filesystem' or 'camera' or 'camcorder' or 'microphone'.
Ben Murdoch6af492a2010-06-15 12:38:17 +01003047 String mediaSource = "";
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003048
Ben Murdoch6af492a2010-06-15 12:38:17 +01003049 // We add the camera intent if there was no accept type (or '*/*' or 'image/*').
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003050 boolean addCameraIntent = true;
Ben Murdoch6af492a2010-06-15 12:38:17 +01003051 // We add the camcorder intent if there was no accept type (or '*/*' or 'video/*').
3052 boolean addCamcorderIntent = true;
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003053
Ben Murdoch6af492a2010-06-15 12:38:17 +01003054 if (mUploadMessage != null) {
3055 // Already a file picker operation in progress.
3056 return;
3057 }
3058
Grace Kloba22ac16e2009-10-07 18:00:23 -07003059 mUploadMessage = uploadMsg;
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003060
3061 // Parse the accept type.
3062 String params[] = acceptType.split(";");
3063 String mimeType = params[0];
3064
3065 for (String p : params) {
3066 String[] keyValue = p.split("=");
3067 if (keyValue.length == 2) {
3068 // Process key=value parameters.
Ben Murdoch6af492a2010-06-15 12:38:17 +01003069 if (mediaSourceKey.equals(keyValue[0])) {
3070 mediaSource = keyValue[1];
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003071 }
3072 }
3073 }
3074
3075 // This intent will display the standard OPENABLE file picker.
Grace Kloba22ac16e2009-10-07 18:00:23 -07003076 Intent i = new Intent(Intent.ACTION_GET_CONTENT);
3077 i.addCategory(Intent.CATEGORY_OPENABLE);
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003078
3079 // Create an intent to add to the standard file picker that will
3080 // capture an image from the camera. We'll combine this intent with
3081 // the standard OPENABLE picker unless the web developer specifically
3082 // requested the camera or gallery be opened by passing a parameter
3083 // in the accept type.
3084 Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
3085 File externalDataDir = Environment.getExternalStoragePublicDirectory(
3086 Environment.DIRECTORY_DCIM);
3087 File cameraDataDir = new File(externalDataDir.getAbsolutePath() +
3088 File.separator + "browser-photos");
3089 cameraDataDir.mkdirs();
3090 mCameraFilePath = cameraDataDir.getAbsolutePath() + File.separator +
3091 System.currentTimeMillis() + ".jpg";
3092 cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(mCameraFilePath)));
3093
Ben Murdoch6af492a2010-06-15 12:38:17 +01003094 Intent camcorderIntent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
3095
Ben Murdoch039bd472010-07-21 21:26:57 +01003096 Intent soundRecIntent = new Intent(MediaStore.Audio.Media.RECORD_SOUND_ACTION);
3097
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003098 if (mimeType.equals(imageMimeType)) {
3099 i.setType(imageMimeType);
Ben Murdoch6af492a2010-06-15 12:38:17 +01003100 addCamcorderIntent = false;
3101 if (mediaSource.equals(mediaSourceValueCamera)) {
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003102 // Specified 'image/*' and requested the camera, so go ahead and launch the camera
3103 // directly.
3104 BrowserActivity.this.startActivityForResult(cameraIntent, FILE_SELECTED);
3105 return;
Ben Murdochb50d7402010-07-16 12:42:22 +01003106 } else if (mediaSource.equals(mediaSourceValueFileSystem)) {
3107 // Specified filesytem as the source, so don't want to consider the camera.
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003108 addCameraIntent = false;
3109 }
Ben Murdoch6af492a2010-06-15 12:38:17 +01003110 } else if (mimeType.equals(videoMimeType)) {
3111 i.setType(videoMimeType);
3112 addCameraIntent = false;
3113 // The camcorder saves it's own file and returns it to us in the intent, so
3114 // we don't need to generate one here.
3115 mCameraFilePath = null;
3116
3117 if (mediaSource.equals(mediaSourceValueCamcorder)) {
Ben Murdoch039bd472010-07-21 21:26:57 +01003118 // Specified 'video/*' and requested the camcorder, so go ahead and launch the
3119 // camcorder directly.
Ben Murdoch6af492a2010-06-15 12:38:17 +01003120 BrowserActivity.this.startActivityForResult(camcorderIntent, FILE_SELECTED);
3121 return;
Ben Murdochb50d7402010-07-16 12:42:22 +01003122 } else if (mediaSource.equals(mediaSourceValueFileSystem)) {
3123 // Specified filesystem as the source, so don't want to consider the camcorder.
Ben Murdoch6af492a2010-06-15 12:38:17 +01003124 addCamcorderIntent = false;
3125 }
Ben Murdoch039bd472010-07-21 21:26:57 +01003126 } else if (mimeType.equals(audioMimeType)) {
3127 i.setType(audioMimeType);
3128 addCameraIntent = false;
3129 addCamcorderIntent = false;
3130 if (mediaSource.equals(mediaSourceValueMicrophone)) {
3131 // Specified 'audio/*' and requested microphone, so go ahead and launch the sound
3132 // recorder.
3133 BrowserActivity.this.startActivityForResult(soundRecIntent, FILE_SELECTED);
3134 return;
3135 }
3136 // On a default system, there is no single option to open an audio "gallery". Both the
3137 // sound recorder and music browser respond to the OPENABLE/audio/* intent unlike the
3138 // image/* and video/* OPENABLE intents where the image / video gallery are the only
3139 // respondants (and so the user is not prompted by default).
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003140 } else {
3141 i.setType("*/*");
3142 }
3143
Ben Murdoch6af492a2010-06-15 12:38:17 +01003144 // Combine the chooser and the extra choices (like camera or camcorder)
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003145 Intent chooser = new Intent(Intent.ACTION_CHOOSER);
3146 chooser.putExtra(Intent.EXTRA_INTENT, i);
3147
Ben Murdoch6af492a2010-06-15 12:38:17 +01003148 Vector<Intent> extraInitialIntents = new Vector<Intent>(0);
3149
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003150 if (addCameraIntent) {
Ben Murdoch6af492a2010-06-15 12:38:17 +01003151 extraInitialIntents.add(cameraIntent);
3152 }
3153
3154 if (addCamcorderIntent) {
3155 extraInitialIntents.add(camcorderIntent);
3156 }
3157
3158 if (extraInitialIntents.size() > 0) {
3159 Intent[] extraIntents = new Intent[extraInitialIntents.size()];
3160 chooser.putExtra(Intent.EXTRA_INITIAL_INTENTS, extraInitialIntents.toArray(extraIntents));
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003161 }
3162
3163 chooser.putExtra(Intent.EXTRA_TITLE, getString(R.string.choose_upload));
3164 BrowserActivity.this.startActivityForResult(chooser, FILE_SELECTED);
Grace Kloba22ac16e2009-10-07 18:00:23 -07003165 }
3166
3167 // -------------------------------------------------------------------------
3168 // Implement functions for DownloadListener
3169 // -------------------------------------------------------------------------
3170
The Android Open Source Project0c908882009-03-03 19:32:16 -08003171 /**
3172 * Notify the host application a download should be done, or that
3173 * the data should be streamed if a streaming viewer is available.
3174 * @param url The full url to the content that should be downloaded
3175 * @param contentDisposition Content-disposition http header, if
3176 * present.
3177 * @param mimetype The mimetype of the content reported by the server
3178 * @param contentLength The file size reported by the server
3179 */
3180 public void onDownloadStart(String url, String userAgent,
3181 String contentDisposition, String mimetype, long contentLength) {
3182 // if we're dealing wih A/V content that's not explicitly marked
3183 // for download, check if it's streamable.
3184 if (contentDisposition == null
Patrick Scotte1fb9662009-08-31 14:31:52 -04003185 || !contentDisposition.regionMatches(
3186 true, 0, "attachment", 0, 10)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003187 // query the package manager to see if there's a registered handler
3188 // that matches.
3189 Intent intent = new Intent(Intent.ACTION_VIEW);
3190 intent.setDataAndType(Uri.parse(url), mimetype);
Patrick Scotte1fb9662009-08-31 14:31:52 -04003191 ResolveInfo info = getPackageManager().resolveActivity(intent,
3192 PackageManager.MATCH_DEFAULT_ONLY);
3193 if (info != null) {
3194 ComponentName myName = getComponentName();
3195 // If we resolved to ourselves, we don't want to attempt to
3196 // load the url only to try and download it again.
3197 if (!myName.getPackageName().equals(
3198 info.activityInfo.packageName)
3199 || !myName.getClassName().equals(
3200 info.activityInfo.name)) {
3201 // someone (other than us) knows how to handle this mime
3202 // type with this scheme, don't download.
3203 try {
3204 startActivity(intent);
3205 return;
3206 } catch (ActivityNotFoundException ex) {
3207 if (LOGD_ENABLED) {
3208 Log.d(LOGTAG, "activity not found for " + mimetype
3209 + " over " + Uri.parse(url).getScheme(),
3210 ex);
3211 }
3212 // Best behavior is to fall back to a download in this
3213 // case
The Android Open Source Project0c908882009-03-03 19:32:16 -08003214 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003215 }
3216 }
3217 }
3218 onDownloadStartNoStream(url, userAgent, contentDisposition, mimetype, contentLength);
3219 }
3220
Kristian Monsenfa52d172010-03-25 18:29:21 +00003221 // This is to work around the fact that java.net.URI throws Exceptions
3222 // instead of just encoding URL's properly
3223 // Helper method for onDownloadStartNoStream
3224 private static String encodePath(String path) {
3225 char[] chars = path.toCharArray();
3226
3227 boolean needed = false;
3228 for (char c : chars) {
3229 if (c == '[' || c == ']') {
3230 needed = true;
3231 break;
3232 }
3233 }
3234 if (needed == false) {
3235 return path;
3236 }
3237
3238 StringBuilder sb = new StringBuilder("");
3239 for (char c : chars) {
3240 if (c == '[' || c == ']') {
3241 sb.append('%');
3242 sb.append(Integer.toHexString(c));
3243 } else {
3244 sb.append(c);
3245 }
3246 }
3247
3248 return sb.toString();
3249 }
3250
The Android Open Source Project0c908882009-03-03 19:32:16 -08003251 /**
3252 * Notify the host application a download should be done, even if there
3253 * is a streaming viewer available for thise type.
3254 * @param url The full url to the content that should be downloaded
3255 * @param contentDisposition Content-disposition http header, if
3256 * present.
3257 * @param mimetype The mimetype of the content reported by the server
3258 * @param contentLength The file size reported by the server
3259 */
3260 /*package */ void onDownloadStartNoStream(String url, String userAgent,
3261 String contentDisposition, String mimetype, long contentLength) {
3262
3263 String filename = URLUtil.guessFileName(url,
3264 contentDisposition, mimetype);
3265
3266 // Check to see if we have an SDCard
3267 String status = Environment.getExternalStorageState();
3268 if (!status.equals(Environment.MEDIA_MOUNTED)) {
3269 int title;
3270 String msg;
3271
3272 // Check to see if the SDCard is busy, same as the music app
3273 if (status.equals(Environment.MEDIA_SHARED)) {
3274 msg = getString(R.string.download_sdcard_busy_dlg_msg);
3275 title = R.string.download_sdcard_busy_dlg_title;
3276 } else {
3277 msg = getString(R.string.download_no_sdcard_dlg_msg, filename);
3278 title = R.string.download_no_sdcard_dlg_title;
3279 }
3280
3281 new AlertDialog.Builder(this)
3282 .setTitle(title)
3283 .setIcon(android.R.drawable.ic_dialog_alert)
3284 .setMessage(msg)
3285 .setPositiveButton(R.string.ok, null)
3286 .show();
3287 return;
3288 }
3289
Kristian Monsenfa52d172010-03-25 18:29:21 +00003290 // java.net.URI is a lot stricter than KURL so we have to encode some
3291 // extra characters. Fix for b 2538060 and b 1634719
3292 WebAddress webAddress;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003293 try {
Kristian Monsenfa52d172010-03-25 18:29:21 +00003294 webAddress = new WebAddress(url);
3295 webAddress.mPath = encodePath(webAddress.mPath);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003296 } catch (Exception e) {
Kristian Monsenfa52d172010-03-25 18:29:21 +00003297 // This only happens for very bad urls, we want to chatch the
3298 // exception here
3299 Log.e(LOGTAG, "Exception trying to parse url:" + url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003300 return;
3301 }
3302
3303 // XXX: Have to use the old url since the cookies were stored using the
3304 // old percent-encoded url.
3305 String cookies = CookieManager.getInstance().getCookie(url);
3306
3307 ContentValues values = new ContentValues();
Kristian Monsenfa52d172010-03-25 18:29:21 +00003308 values.put(Downloads.Impl.COLUMN_URI, webAddress.toString());
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08003309 values.put(Downloads.Impl.COLUMN_COOKIE_DATA, cookies);
3310 values.put(Downloads.Impl.COLUMN_USER_AGENT, userAgent);
3311 values.put(Downloads.Impl.COLUMN_NOTIFICATION_PACKAGE,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003312 getPackageName());
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08003313 values.put(Downloads.Impl.COLUMN_NOTIFICATION_CLASS,
Leon Scrogginsa563d092010-04-19 16:53:49 -04003314 OpenDownloadReceiver.class.getCanonicalName());
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08003315 values.put(Downloads.Impl.COLUMN_VISIBILITY,
3316 Downloads.Impl.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
3317 values.put(Downloads.Impl.COLUMN_MIME_TYPE, mimetype);
3318 values.put(Downloads.Impl.COLUMN_FILE_NAME_HINT, filename);
Kristian Monsenfa52d172010-03-25 18:29:21 +00003319 values.put(Downloads.Impl.COLUMN_DESCRIPTION, webAddress.mHost);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003320 if (contentLength > 0) {
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08003321 values.put(Downloads.Impl.COLUMN_TOTAL_BYTES, contentLength);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003322 }
3323 if (mimetype == null) {
3324 // We must have long pressed on a link or image to download it. We
3325 // are not sure of the mimetype in this case, so do a head request
3326 new FetchUrlMimeType(this).execute(values);
3327 } else {
3328 final Uri contentUri =
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08003329 getContentResolver().insert(Downloads.Impl.CONTENT_URI, values);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003330 }
Leon Scroggins9191a7f2010-03-18 14:44:44 -04003331 Toast.makeText(this, R.string.download_pending, Toast.LENGTH_SHORT)
3332 .show();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003333 }
3334
Grace Kloba22ac16e2009-10-07 18:00:23 -07003335 // -------------------------------------------------------------------------
3336
The Android Open Source Project0c908882009-03-03 19:32:16 -08003337 /**
3338 * Resets the lock icon. This method is called when we start a new load and
3339 * know the url to be loaded.
3340 */
3341 private void resetLockIcon(String url) {
3342 // Save the lock-icon state (we revert to it if the load gets cancelled)
Grace Kloba22ac16e2009-10-07 18:00:23 -07003343 mTabControl.getCurrentTab().resetLockIcon(url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003344 updateLockIconImage(LOCK_ICON_UNSECURE);
3345 }
3346
The Android Open Source Project0c908882009-03-03 19:32:16 -08003347 /**
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04003348 * Update the lock icon to correspond to our latest state.
3349 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003350 private void updateLockIconToLatest() {
Leon Scroggins91f65fc2010-06-29 13:52:39 -04003351 Tab t = mTabControl.getCurrentTab();
3352 if (t != null) {
3353 updateLockIconImage(t.getLockIconType());
3354 }
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04003355 }
3356
3357 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08003358 * Updates the lock-icon image in the title-bar.
3359 */
3360 private void updateLockIconImage(int lockIconType) {
3361 Drawable d = null;
3362 if (lockIconType == LOCK_ICON_SECURE) {
3363 d = mSecLockIcon;
3364 } else if (lockIconType == LOCK_ICON_MIXED) {
3365 d = mMixLockIcon;
3366 }
Leon Scroggins68579392009-09-15 15:31:54 -04003367 mTitleBar.setLock(d);
Michael Kolba2b2ba82010-08-04 17:54:03 -07003368 mFakeTitleBar.setLock(d);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003369 }
3370
3371 /**
3372 * Displays a page-info dialog.
3373 * @param tab The tab to show info about
3374 * @param fromShowSSLCertificateOnError The flag that indicates whether
3375 * this dialog was opened from the SSL-certificate-on-error dialog or
3376 * not. This is important, since we need to know whether to return to
3377 * the parent dialog or simply dismiss.
3378 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003379 private void showPageInfo(final Tab tab,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003380 final boolean fromShowSSLCertificateOnError) {
3381 final LayoutInflater factory = LayoutInflater
3382 .from(this);
3383
3384 final View pageInfoView = factory.inflate(R.layout.page_info, null);
3385
3386 final WebView view = tab.getWebView();
3387
3388 String url = null;
3389 String title = null;
3390
3391 if (view == null) {
3392 url = tab.getUrl();
3393 title = tab.getTitle();
3394 } else if (view == mTabControl.getCurrentWebView()) {
3395 // Use the cached title and url if this is the current WebView
3396 url = mUrl;
3397 title = mTitle;
3398 } else {
3399 url = view.getUrl();
3400 title = view.getTitle();
3401 }
3402
3403 if (url == null) {
3404 url = "";
3405 }
3406 if (title == null) {
3407 title = "";
3408 }
3409
3410 ((TextView) pageInfoView.findViewById(R.id.address)).setText(url);
3411 ((TextView) pageInfoView.findViewById(R.id.title)).setText(title);
3412
3413 mPageInfoView = tab;
Leon Scrogginsc7b92f82010-01-11 18:17:31 -05003414 mPageInfoFromShowSSLCertificateOnError = fromShowSSLCertificateOnError;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003415
3416 AlertDialog.Builder alertDialogBuilder =
3417 new AlertDialog.Builder(this)
3418 .setTitle(R.string.page_info).setIcon(android.R.drawable.ic_dialog_info)
3419 .setView(pageInfoView)
3420 .setPositiveButton(
3421 R.string.ok,
3422 new DialogInterface.OnClickListener() {
3423 public void onClick(DialogInterface dialog,
3424 int whichButton) {
3425 mPageInfoDialog = null;
3426 mPageInfoView = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003427
3428 // if we came here from the SSL error dialog
3429 if (fromShowSSLCertificateOnError) {
3430 // go back to the SSL error dialog
3431 showSSLCertificateOnError(
3432 mSSLCertificateOnErrorView,
3433 mSSLCertificateOnErrorHandler,
3434 mSSLCertificateOnErrorError);
3435 }
3436 }
3437 })
3438 .setOnCancelListener(
3439 new DialogInterface.OnCancelListener() {
3440 public void onCancel(DialogInterface dialog) {
3441 mPageInfoDialog = null;
3442 mPageInfoView = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003443
3444 // if we came here from the SSL error dialog
3445 if (fromShowSSLCertificateOnError) {
3446 // go back to the SSL error dialog
3447 showSSLCertificateOnError(
3448 mSSLCertificateOnErrorView,
3449 mSSLCertificateOnErrorHandler,
3450 mSSLCertificateOnErrorError);
3451 }
3452 }
3453 });
3454
3455 // if we have a main top-level page SSL certificate set or a certificate
3456 // error
3457 if (fromShowSSLCertificateOnError ||
3458 (view != null && view.getCertificate() != null)) {
3459 // add a 'View Certificate' button
3460 alertDialogBuilder.setNeutralButton(
3461 R.string.view_certificate,
3462 new DialogInterface.OnClickListener() {
3463 public void onClick(DialogInterface dialog,
3464 int whichButton) {
3465 mPageInfoDialog = null;
3466 mPageInfoView = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003467
3468 // if we came here from the SSL error dialog
3469 if (fromShowSSLCertificateOnError) {
3470 // go back to the SSL error dialog
3471 showSSLCertificateOnError(
3472 mSSLCertificateOnErrorView,
3473 mSSLCertificateOnErrorHandler,
3474 mSSLCertificateOnErrorError);
3475 } else {
3476 // otherwise, display the top-most certificate from
3477 // the chain
3478 if (view.getCertificate() != null) {
3479 showSSLCertificate(tab);
3480 }
3481 }
3482 }
3483 });
3484 }
3485
3486 mPageInfoDialog = alertDialogBuilder.show();
3487 }
3488
3489 /**
3490 * Displays the main top-level page SSL certificate dialog
3491 * (accessible from the Page-Info dialog).
3492 * @param tab The tab to show certificate for.
3493 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003494 private void showSSLCertificate(final Tab tab) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003495 final View certificateView =
3496 inflateCertificateView(tab.getWebView().getCertificate());
3497 if (certificateView == null) {
3498 return;
3499 }
3500
3501 LayoutInflater factory = LayoutInflater.from(this);
3502
3503 final LinearLayout placeholder =
3504 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3505
3506 LinearLayout ll = (LinearLayout) factory.inflate(
3507 R.layout.ssl_success, placeholder);
3508 ((TextView)ll.findViewById(R.id.success))
3509 .setText(R.string.ssl_certificate_is_valid);
3510
3511 mSSLCertificateView = tab;
3512 mSSLCertificateDialog =
3513 new AlertDialog.Builder(this)
3514 .setTitle(R.string.ssl_certificate).setIcon(
3515 R.drawable.ic_dialog_browser_certificate_secure)
3516 .setView(certificateView)
3517 .setPositiveButton(R.string.ok,
3518 new DialogInterface.OnClickListener() {
3519 public void onClick(DialogInterface dialog,
3520 int whichButton) {
3521 mSSLCertificateDialog = null;
3522 mSSLCertificateView = null;
3523
3524 showPageInfo(tab, false);
3525 }
3526 })
3527 .setOnCancelListener(
3528 new DialogInterface.OnCancelListener() {
3529 public void onCancel(DialogInterface dialog) {
3530 mSSLCertificateDialog = null;
3531 mSSLCertificateView = null;
3532
3533 showPageInfo(tab, false);
3534 }
3535 })
3536 .show();
3537 }
3538
3539 /**
3540 * Displays the SSL error certificate dialog.
3541 * @param view The target web-view.
3542 * @param handler The SSL error handler responsible for cancelling the
3543 * connection that resulted in an SSL error or proceeding per user request.
3544 * @param error The SSL error object.
3545 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003546 void showSSLCertificateOnError(
The Android Open Source Project0c908882009-03-03 19:32:16 -08003547 final WebView view, final SslErrorHandler handler, final SslError error) {
3548
3549 final View certificateView =
3550 inflateCertificateView(error.getCertificate());
3551 if (certificateView == null) {
3552 return;
3553 }
3554
3555 LayoutInflater factory = LayoutInflater.from(this);
3556
3557 final LinearLayout placeholder =
3558 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3559
3560 if (error.hasError(SslError.SSL_UNTRUSTED)) {
3561 LinearLayout ll = (LinearLayout)factory
3562 .inflate(R.layout.ssl_warning, placeholder);
3563 ((TextView)ll.findViewById(R.id.warning))
3564 .setText(R.string.ssl_untrusted);
3565 }
3566
3567 if (error.hasError(SslError.SSL_IDMISMATCH)) {
3568 LinearLayout ll = (LinearLayout)factory
3569 .inflate(R.layout.ssl_warning, placeholder);
3570 ((TextView)ll.findViewById(R.id.warning))
3571 .setText(R.string.ssl_mismatch);
3572 }
3573
3574 if (error.hasError(SslError.SSL_EXPIRED)) {
3575 LinearLayout ll = (LinearLayout)factory
3576 .inflate(R.layout.ssl_warning, placeholder);
3577 ((TextView)ll.findViewById(R.id.warning))
3578 .setText(R.string.ssl_expired);
3579 }
3580
3581 if (error.hasError(SslError.SSL_NOTYETVALID)) {
3582 LinearLayout ll = (LinearLayout)factory
3583 .inflate(R.layout.ssl_warning, placeholder);
3584 ((TextView)ll.findViewById(R.id.warning))
3585 .setText(R.string.ssl_not_yet_valid);
3586 }
3587
3588 mSSLCertificateOnErrorHandler = handler;
3589 mSSLCertificateOnErrorView = view;
3590 mSSLCertificateOnErrorError = error;
3591 mSSLCertificateOnErrorDialog =
3592 new AlertDialog.Builder(this)
3593 .setTitle(R.string.ssl_certificate).setIcon(
3594 R.drawable.ic_dialog_browser_certificate_partially_secure)
3595 .setView(certificateView)
3596 .setPositiveButton(R.string.ok,
3597 new DialogInterface.OnClickListener() {
3598 public void onClick(DialogInterface dialog,
3599 int whichButton) {
3600 mSSLCertificateOnErrorDialog = null;
3601 mSSLCertificateOnErrorView = null;
3602 mSSLCertificateOnErrorHandler = null;
3603 mSSLCertificateOnErrorError = null;
3604
Grace Kloba22ac16e2009-10-07 18:00:23 -07003605 view.getWebViewClient().onReceivedSslError(
3606 view, handler, error);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003607 }
3608 })
3609 .setNeutralButton(R.string.page_info_view,
3610 new DialogInterface.OnClickListener() {
3611 public void onClick(DialogInterface dialog,
3612 int whichButton) {
3613 mSSLCertificateOnErrorDialog = null;
3614
3615 // do not clear the dialog state: we will
3616 // need to show the dialog again once the
3617 // user is done exploring the page-info details
3618
3619 showPageInfo(mTabControl.getTabFromView(view),
3620 true);
3621 }
3622 })
3623 .setOnCancelListener(
3624 new DialogInterface.OnCancelListener() {
3625 public void onCancel(DialogInterface dialog) {
3626 mSSLCertificateOnErrorDialog = null;
3627 mSSLCertificateOnErrorView = null;
3628 mSSLCertificateOnErrorHandler = null;
3629 mSSLCertificateOnErrorError = null;
3630
Grace Kloba22ac16e2009-10-07 18:00:23 -07003631 view.getWebViewClient().onReceivedSslError(
3632 view, handler, error);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003633 }
3634 })
3635 .show();
3636 }
3637
3638 /**
3639 * Inflates the SSL certificate view (helper method).
3640 * @param certificate The SSL certificate.
3641 * @return The resultant certificate view with issued-to, issued-by,
3642 * issued-on, expires-on, and possibly other fields set.
3643 * If the input certificate is null, returns null.
3644 */
3645 private View inflateCertificateView(SslCertificate certificate) {
3646 if (certificate == null) {
3647 return null;
3648 }
3649
3650 LayoutInflater factory = LayoutInflater.from(this);
3651
3652 View certificateView = factory.inflate(
3653 R.layout.ssl_certificate, null);
3654
3655 // issued to:
3656 SslCertificate.DName issuedTo = certificate.getIssuedTo();
3657 if (issuedTo != null) {
3658 ((TextView) certificateView.findViewById(R.id.to_common))
3659 .setText(issuedTo.getCName());
3660 ((TextView) certificateView.findViewById(R.id.to_org))
3661 .setText(issuedTo.getOName());
3662 ((TextView) certificateView.findViewById(R.id.to_org_unit))
3663 .setText(issuedTo.getUName());
3664 }
3665
3666 // issued by:
3667 SslCertificate.DName issuedBy = certificate.getIssuedBy();
3668 if (issuedBy != null) {
3669 ((TextView) certificateView.findViewById(R.id.by_common))
3670 .setText(issuedBy.getCName());
3671 ((TextView) certificateView.findViewById(R.id.by_org))
3672 .setText(issuedBy.getOName());
3673 ((TextView) certificateView.findViewById(R.id.by_org_unit))
3674 .setText(issuedBy.getUName());
3675 }
3676
3677 // issued on:
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003678 String issuedOn = formatCertificateDate(
3679 certificate.getValidNotBeforeDate());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003680 ((TextView) certificateView.findViewById(R.id.issued_on))
3681 .setText(issuedOn);
3682
3683 // expires on:
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003684 String expiresOn = formatCertificateDate(
3685 certificate.getValidNotAfterDate());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003686 ((TextView) certificateView.findViewById(R.id.expires_on))
3687 .setText(expiresOn);
3688
3689 return certificateView;
3690 }
3691
3692 /**
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003693 * Formats the certificate date to a properly localized date string.
The Android Open Source Project0c908882009-03-03 19:32:16 -08003694 * @return Properly localized version of the certificate date string and
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003695 * the "" if it fails to localize.
The Android Open Source Project0c908882009-03-03 19:32:16 -08003696 */
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003697 private String formatCertificateDate(Date certificateDate) {
3698 if (certificateDate == null) {
3699 return "";
The Android Open Source Project0c908882009-03-03 19:32:16 -08003700 }
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003701 String formattedDate = DateFormat.getDateFormat(this).format(certificateDate);
3702 if (formattedDate == null) {
3703 return "";
3704 }
3705 return formattedDate;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003706 }
3707
3708 /**
3709 * Displays an http-authentication dialog.
3710 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003711 void showHttpAuthentication(final HttpAuthHandler handler,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003712 final String host, final String realm, final String title,
3713 final String name, final String password, int focusId) {
3714 LayoutInflater factory = LayoutInflater.from(this);
3715 final View v = factory
3716 .inflate(R.layout.http_authentication, null);
3717 if (name != null) {
3718 ((EditText) v.findViewById(R.id.username_edit)).setText(name);
3719 }
3720 if (password != null) {
3721 ((EditText) v.findViewById(R.id.password_edit)).setText(password);
3722 }
3723
3724 String titleText = title;
3725 if (titleText == null) {
3726 titleText = getText(R.string.sign_in_to).toString().replace(
3727 "%s1", host).replace("%s2", realm);
3728 }
3729
3730 mHttpAuthHandler = handler;
3731 AlertDialog dialog = new AlertDialog.Builder(this)
3732 .setTitle(titleText)
3733 .setIcon(android.R.drawable.ic_dialog_alert)
3734 .setView(v)
3735 .setPositiveButton(R.string.action,
3736 new DialogInterface.OnClickListener() {
3737 public void onClick(DialogInterface dialog,
3738 int whichButton) {
3739 String nm = ((EditText) v
3740 .findViewById(R.id.username_edit))
3741 .getText().toString();
3742 String pw = ((EditText) v
3743 .findViewById(R.id.password_edit))
3744 .getText().toString();
3745 BrowserActivity.this.setHttpAuthUsernamePassword
3746 (host, realm, nm, pw);
3747 handler.proceed(nm, pw);
3748 mHttpAuthenticationDialog = null;
3749 mHttpAuthHandler = null;
3750 }})
3751 .setNegativeButton(R.string.cancel,
3752 new DialogInterface.OnClickListener() {
3753 public void onClick(DialogInterface dialog,
3754 int whichButton) {
3755 handler.cancel();
3756 BrowserActivity.this.resetTitleAndRevertLockIcon();
3757 mHttpAuthenticationDialog = null;
3758 mHttpAuthHandler = null;
3759 }})
3760 .setOnCancelListener(new DialogInterface.OnCancelListener() {
3761 public void onCancel(DialogInterface dialog) {
3762 handler.cancel();
3763 BrowserActivity.this.resetTitleAndRevertLockIcon();
3764 mHttpAuthenticationDialog = null;
3765 mHttpAuthHandler = null;
3766 }})
3767 .create();
3768 // Make the IME appear when the dialog is displayed if applicable.
3769 dialog.getWindow().setSoftInputMode(
3770 WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
3771 dialog.show();
3772 if (focusId != 0) {
3773 dialog.findViewById(focusId).requestFocus();
3774 } else {
3775 v.findViewById(R.id.username_edit).requestFocus();
3776 }
3777 mHttpAuthenticationDialog = dialog;
3778 }
3779
3780 public int getProgress() {
3781 WebView w = mTabControl.getCurrentWebView();
3782 if (w != null) {
3783 return w.getProgress();
3784 } else {
3785 return 100;
3786 }
3787 }
3788
3789 /**
3790 * Set HTTP authentication password.
3791 *
3792 * @param host The host for the password
3793 * @param realm The realm for the password
3794 * @param username The username for the password. If it is null, it means
3795 * password can't be saved.
3796 * @param password The password
3797 */
3798 public void setHttpAuthUsernamePassword(String host, String realm,
3799 String username,
3800 String password) {
Steve Block95a53b22010-03-25 17:24:58 +00003801 WebView w = getTopWindow();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003802 if (w != null) {
3803 w.setHttpAuthUsernamePassword(host, realm, username, password);
3804 }
3805 }
3806
3807 /**
3808 * connectivity manager says net has come or gone... inform the user
3809 * @param up true if net has come up, false if net has gone down
3810 */
3811 public void onNetworkToggle(boolean up) {
3812 if (up == mIsNetworkUp) {
3813 return;
3814 } else if (up) {
3815 mIsNetworkUp = true;
3816 if (mAlertDialog != null) {
3817 mAlertDialog.cancel();
3818 mAlertDialog = null;
3819 }
3820 } else {
3821 mIsNetworkUp = false;
Patrick Scotteb6ab2a2009-09-16 10:00:17 -04003822 if (mInLoad) {
3823 createAndShowNetworkDialog();
3824 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003825 }
3826 WebView w = mTabControl.getCurrentWebView();
3827 if (w != null) {
3828 w.setNetworkAvailable(up);
3829 }
3830 }
3831
Grace Kloba22ac16e2009-10-07 18:00:23 -07003832 boolean isNetworkUp() {
3833 return mIsNetworkUp;
3834 }
3835
Patrick Scotteb6ab2a2009-09-16 10:00:17 -04003836 // This method shows the network dialog alerting the user that the net is
3837 // down. It will only show the dialog if mAlertDialog is null.
3838 private void createAndShowNetworkDialog() {
3839 if (mAlertDialog == null) {
3840 mAlertDialog = new AlertDialog.Builder(this)
3841 .setTitle(R.string.loadSuspendedTitle)
3842 .setMessage(R.string.loadSuspended)
3843 .setPositiveButton(R.string.ok, null)
3844 .show();
3845 }
3846 }
3847
The Android Open Source Project0c908882009-03-03 19:32:16 -08003848 @Override
3849 protected void onActivityResult(int requestCode, int resultCode,
3850 Intent intent) {
Grace Klobabb394f32009-11-19 10:26:37 -08003851 if (getTopWindow() == null) return;
3852
The Android Open Source Project0c908882009-03-03 19:32:16 -08003853 switch (requestCode) {
3854 case COMBO_PAGE:
3855 if (resultCode == RESULT_OK && intent != null) {
3856 String data = intent.getAction();
3857 Bundle extras = intent.getExtras();
3858 if (extras != null && extras.getBoolean("new_window", false)) {
Michael Kolb68792c82010-08-09 16:39:18 -07003859 openTab(data, false);
3860 } else if ((extras != null) &&
3861 extras.getBoolean(CombinedBookmarkHistoryActivity.NEWTAB_MODE)) {
3862 openTab(data, true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003863 } else {
Michael Kolb68792c82010-08-09 16:39:18 -07003864 final Tab currentTab = mTabControl.getCurrentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04003865 dismissSubWindow(currentTab);
3866 if (data != null && data.length() != 0) {
Leon Scroggins92472e82010-02-17 16:32:28 -05003867 loadUrl(getTopWindow(), data);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003868 }
3869 }
Michael Kolb3f65c382010-08-20 15:31:16 -07003870 } else if (resultCode == RESULT_CANCELED) {
3871 if (intent != null) {
3872 float evtx = intent.getFloatExtra(CombinedBookmarkHistoryActivity.EVT_X, -1);
3873 float evty = intent.getFloatExtra(CombinedBookmarkHistoryActivity.EVT_Y, -1);
3874 long now = System.currentTimeMillis();
3875 MotionEvent evt = MotionEvent.obtain(now, now,
3876 MotionEvent.ACTION_DOWN, evtx, evty, 0);
3877 dispatchTouchEvent(evt);
3878 MotionEvent up = MotionEvent.obtain(evt);
3879 up.setAction(MotionEvent.ACTION_UP);
3880 dispatchTouchEvent(up);
3881 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003882 }
Leon Scrogginsfde97462010-01-11 13:06:21 -05003883 // Deliberately fall through to PREFERENCES_PAGE, since the
3884 // same extra may be attached to the COMBO_PAGE
3885 case PREFERENCES_PAGE:
3886 if (resultCode == RESULT_OK && intent != null) {
3887 String action = intent.getStringExtra(Intent.EXTRA_TEXT);
3888 if (BrowserSettings.PREF_CLEAR_HISTORY.equals(action)) {
3889 mTabControl.removeParentChildRelationShips();
3890 }
3891 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003892 break;
Leon Scroggins8d5fa432009-10-02 15:55:59 -04003893 // Choose a file from the file picker.
3894 case FILE_SELECTED:
3895 if (null == mUploadMessage) break;
3896 Uri result = intent == null || resultCode != RESULT_OK ? null
3897 : intent.getData();
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003898
3899 // As we ask the camera to save the result of the user taking
3900 // a picture, the camera application does not return anything other
3901 // than RESULT_OK. So we need to check whether the file we expected
3902 // was written to disk in the in the case that we
3903 // did not get an intent returned but did get a RESULT_OK. If it was,
3904 // we assume that this result has came back from the camera.
3905 if (result == null && intent == null && resultCode == RESULT_OK) {
3906 File cameraFile = new File(mCameraFilePath);
3907 if (cameraFile.exists()) {
3908 result = Uri.fromFile(cameraFile);
Ben Murdoch07d34732010-05-27 18:34:46 +01003909 // Broadcast to the media scanner that we have a new photo
3910 // so it will be added into the gallery for the user.
3911 sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, result));
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003912 }
3913 }
Leon Scroggins8d5fa432009-10-02 15:55:59 -04003914 mUploadMessage.onReceiveValue(result);
3915 mUploadMessage = null;
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003916 mCameraFilePath = null;
Leon Scroggins8d5fa432009-10-02 15:55:59 -04003917 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003918 default:
3919 break;
3920 }
Leon Scroggins30444232009-09-04 18:36:20 -04003921 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003922 }
3923
3924 /*
3925 * This method is called as a result of the user selecting the options
Leon Scrogginsf08809b2010-01-21 09:27:46 -05003926 * menu to see the download window. It shows the download window on top of
3927 * the current window.
The Android Open Source Project0c908882009-03-03 19:32:16 -08003928 */
Leon Scrogginsf08809b2010-01-21 09:27:46 -05003929 private void viewDownloads(Uri downloadRecord) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003930 Intent intent = new Intent(this,
3931 BrowserDownloadPage.class);
3932 intent.setData(downloadRecord);
Grace Kloba22ac16e2009-10-07 18:00:23 -07003933 startActivityForResult(intent, BrowserActivity.DOWNLOAD_PAGE);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003934
3935 }
3936
Ben Murdocheecb4e62010-07-06 16:30:38 +01003937 /* package*/ void promptAddOrInstallBookmark() {
3938 final Tab current = mTabControl.getCurrentTab();
3939 Resources resources = getResources();
3940 CharSequence[] choices = {
3941 resources.getString(R.string.save_to_bookmarks),
3942 resources.getString(R.string.create_shortcut_bookmark)
3943 };
3944
3945 AlertDialog.Builder builder = new AlertDialog.Builder(this);
3946 builder.setTitle(R.string.add_new_bookmark);
3947 builder.setItems(choices, new DialogInterface.OnClickListener() {
3948 public void onClick(DialogInterface dialog, int item) {
3949 if (item == 0) {
3950 bookmarkCurrentPage();
3951 } else if (item == 1) {
3952 current.populatePickerData();
3953 String touchIconUrl = mTabControl.getCurrentWebView().getTouchIconUrl();
3954 if (touchIconUrl != null) {
3955 // Download the touch icon for this site then save it to the
3956 // homescreen.
3957 Bundle b = new Bundle();
3958 b.putString("url", current.getUrl());
3959 b.putString("title", current.getTitle());
3960 b.putParcelable("favicon", current.getFavicon());
3961 Message msg = mHandler.obtainMessage(TOUCH_ICON_DOWNLOADED);
3962 msg.setData(b);
Ben Murdochccb5de02010-07-19 18:38:17 +01003963 new DownloadTouchIcon(BrowserActivity.this, msg,
Ben Murdocheecb4e62010-07-06 16:30:38 +01003964 mTabControl.getCurrentWebView().getSettings()
3965 .getUserAgentString()).execute(touchIconUrl);
3966 } else {
3967 // add to homescreen, can do it immediately as there is no touch
3968 // icon.
3969 showSaveToHomescreenDialog(current.getUrl(), current.getTitle(),
3970 null, current.getFavicon());
3971 }
3972 }
3973 }
3974 });
3975 builder.create().show();
3976 }
3977
Leon Scroggins160a7e72009-08-14 18:28:01 -04003978 /**
3979 * Open the Go page.
3980 * @param startWithHistory If true, open starting on the history tab.
3981 * Otherwise, start with the bookmarks tab.
Leon Scroggins160a7e72009-08-14 18:28:01 -04003982 */
Michael Kolb68792c82010-08-09 16:39:18 -07003983 /* package */ void bookmarksOrHistoryPicker(boolean startWithHistory, boolean newTabMode) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003984 WebView current = mTabControl.getCurrentWebView();
3985 if (current == null) {
3986 return;
3987 }
3988 Intent intent = new Intent(this,
3989 CombinedBookmarkHistoryActivity.class);
3990 String title = current.getTitle();
3991 String url = current.getUrl();
Ben Murdoch87cc65d2010-06-29 20:34:10 +01003992 Bitmap thumbnail = createScreenshot(current, getDesiredThumbnailWidth(this),
3993 getDesiredThumbnailHeight(this));
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01003994
The Android Open Source Project0c908882009-03-03 19:32:16 -08003995 // Just in case the user opens bookmarks before a page finishes loading
3996 // so the current history item, and therefore the page, is null.
3997 if (null == url) {
3998 url = mLastEnteredUrl;
3999 // This can happen.
4000 if (null == url) {
4001 url = mSettings.getHomePage();
4002 }
4003 }
4004 // In case the web page has not yet received its associated title.
4005 if (title == null) {
4006 title = url;
4007 }
4008 intent.putExtra("title", title);
4009 intent.putExtra("url", url);
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01004010 intent.putExtra("thumbnail", thumbnail);
Leon Scroggins30444232009-09-04 18:36:20 -04004011 // Disable opening in a new window if we have maxed out the windows
Grace Kloba22ac16e2009-10-07 18:00:23 -07004012 intent.putExtra("disable_new_window", !mTabControl.canCreateNewTab());
Patrick Scott3918d442009-08-04 13:22:29 -04004013 intent.putExtra("touch_icon_url", current.getTouchIconUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08004014 if (startWithHistory) {
Jeff Hamilton64144e42010-08-18 16:31:59 -05004015 intent.putExtra(CombinedBookmarkHistoryActivity.STARTING_FRAGMENT,
4016 CombinedBookmarkHistoryActivity.FRAGMENT_ID_HISTORY);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004017 }
Michael Kolb3f65c382010-08-20 15:31:16 -07004018 if (mXLargeScreenSize) {
4019 showFakeTitleBar();
4020 int titleBarHeight = ((TitleBarXLarge)mFakeTitleBar).getHeightWithoutProgress();
4021 intent.putExtra(CombinedBookmarkHistoryActivity.EXTRA_TOP,
4022 mTabBar.getBottom() + titleBarHeight);
4023 intent.putExtra(CombinedBookmarkHistoryActivity.EXTRA_HEIGHT,
4024 getTopWindow().getHeight() - titleBarHeight);
Michael Kolb68792c82010-08-09 16:39:18 -07004025 intent.putExtra(CombinedBookmarkHistoryActivity.NEWTAB_MODE, true);
4026 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08004027 startActivityForResult(intent, COMBO_PAGE);
4028 }
4029
Ben Murdocheecb4e62010-07-06 16:30:38 +01004030 private void showSaveToHomescreenDialog(String url, String title, Bitmap touchIcon,
4031 Bitmap favicon) {
4032 Intent intent = new Intent(this, SaveToHomescreenDialog.class);
4033
4034 // Just in case the user tries to save before a page finishes loading
4035 // so the current history item, and therefore the page, is null.
4036 if (null == url) {
4037 url = mLastEnteredUrl;
4038 // This can happen.
4039 if (null == url) {
4040 url = mSettings.getHomePage();
4041 }
4042 }
4043
4044 // In case the web page has not yet received its associated title.
4045 if (title == null) {
4046 title = url;
4047 }
4048
4049 intent.putExtra("title", title);
4050 intent.putExtra("url", url);
4051 intent.putExtra("favicon", favicon);
4052 intent.putExtra("touchIcon", touchIcon);
4053 startActivity(intent);
4054 }
4055
4056
The Android Open Source Project0c908882009-03-03 19:32:16 -08004057 // Called when loading from context menu or LOAD_URL message
Leon Scroggins92472e82010-02-17 16:32:28 -05004058 private void loadUrlFromContext(WebView view, String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08004059 // In case the user enters nothing.
4060 if (url != null && url.length() != 0 && view != null) {
4061 url = smartUrlFilter(url);
Grace Kloba22ac16e2009-10-07 18:00:23 -07004062 if (!view.getWebViewClient().shouldOverrideUrlLoading(view, url)) {
Leon Scroggins92472e82010-02-17 16:32:28 -05004063 loadUrl(view, url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004064 }
4065 }
4066 }
4067
Leon Scroggins92472e82010-02-17 16:32:28 -05004068 /**
4069 * Load the URL into the given WebView and update the title bar
4070 * to reflect the new load. Call this instead of WebView.loadUrl
4071 * directly.
4072 * @param view The WebView used to load url.
4073 * @param url The URL to load.
4074 */
4075 private void loadUrl(WebView view, String url) {
4076 updateTitleBarForNewLoad(view, url);
4077 view.loadUrl(url);
4078 }
4079
4080 /**
4081 * Load UrlData into a Tab and update the title bar to reflect the new
4082 * load. Call this instead of UrlData.loadIn directly.
4083 * @param t The Tab used to load.
4084 * @param data The UrlData being loaded.
4085 */
4086 private void loadUrlDataIn(Tab t, UrlData data) {
4087 updateTitleBarForNewLoad(t.getWebView(), data.mUrl);
4088 data.loadIn(t);
4089 }
4090
4091 /**
4092 * If the WebView is the top window, update the title bar to reflect
4093 * loading the new URL. i.e. set its text, clear the favicon (which
4094 * will be set once the page begins loading), and set the progress to
4095 * INITIAL_PROGRESS to show that the page has begun to load. Called
4096 * by loadUrl and loadUrlDataIn.
4097 * @param view The WebView that is starting a load.
4098 * @param url The URL that is being loaded.
4099 */
4100 private void updateTitleBarForNewLoad(WebView view, String url) {
4101 if (view == getTopWindow()) {
4102 setUrlTitle(url, null);
4103 setFavicon(null);
4104 onProgressChanged(view, INITIAL_PROGRESS);
4105 }
4106 }
4107
The Android Open Source Project0c908882009-03-03 19:32:16 -08004108 private String smartUrlFilter(Uri inUri) {
4109 if (inUri != null) {
4110 return smartUrlFilter(inUri.toString());
4111 }
4112 return null;
4113 }
4114
Feng Qianb34f87a2009-03-24 21:27:26 -07004115 protected static final Pattern ACCEPTED_URI_SCHEMA = Pattern.compile(
The Android Open Source Project0c908882009-03-03 19:32:16 -08004116 "(?i)" + // switch on case insensitive matching
4117 "(" + // begin group for schema
4118 "(?:http|https|file):\\/\\/" +
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004119 "|(?:inline|data|about|content|javascript):" +
The Android Open Source Project0c908882009-03-03 19:32:16 -08004120 ")" +
4121 "(.*)" );
4122
4123 /**
4124 * Attempts to determine whether user input is a URL or search
4125 * terms. Anything with a space is passed to search.
4126 *
4127 * Converts to lowercase any mistakenly uppercased schema (i.e.,
4128 * "Http://" converts to "http://"
4129 *
4130 * @return Original or modified URL
4131 *
4132 */
4133 String smartUrlFilter(String url) {
4134
4135 String inUrl = url.trim();
4136 boolean hasSpace = inUrl.indexOf(' ') != -1;
4137
4138 Matcher matcher = ACCEPTED_URI_SCHEMA.matcher(inUrl);
4139 if (matcher.matches()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08004140 // force scheme to lowercase
4141 String scheme = matcher.group(1);
4142 String lcScheme = scheme.toLowerCase();
4143 if (!lcScheme.equals(scheme)) {
Mitsuru Oshima123ecfb2009-05-18 19:11:14 -07004144 inUrl = lcScheme + matcher.group(2);
4145 }
4146 if (hasSpace) {
4147 inUrl = inUrl.replace(" ", "%20");
The Android Open Source Project0c908882009-03-03 19:32:16 -08004148 }
4149 return inUrl;
4150 }
4151 if (hasSpace) {
Satish Sampath565505b2009-05-29 15:37:27 +01004152 // FIXME: Is this the correct place to add to searches?
4153 // what if someone else calls this function?
4154 int shortcut = parseUrlShortcut(inUrl);
4155 if (shortcut != SHORTCUT_INVALID) {
4156 Browser.addSearchUrl(mResolver, inUrl);
4157 String query = inUrl.substring(2);
4158 switch (shortcut) {
4159 case SHORTCUT_GOOGLE_SEARCH:
Grace Kloba47fdfdb2009-06-30 11:15:34 -07004160 return URLUtil.composeSearchUrl(query, QuickSearch_G, QUERY_PLACE_HOLDER);
Satish Sampath565505b2009-05-29 15:37:27 +01004161 case SHORTCUT_WIKIPEDIA_SEARCH:
4162 return URLUtil.composeSearchUrl(query, QuickSearch_W, QUERY_PLACE_HOLDER);
4163 case SHORTCUT_DICTIONARY_SEARCH:
4164 return URLUtil.composeSearchUrl(query, QuickSearch_D, QUERY_PLACE_HOLDER);
4165 case SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH:
The Android Open Source Project0c908882009-03-03 19:32:16 -08004166 // FIXME: we need location in this case
Satish Sampath565505b2009-05-29 15:37:27 +01004167 return URLUtil.composeSearchUrl(query, QuickSearch_L, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004168 }
4169 }
4170 } else {
Dan Egnor5ee906c2009-11-18 12:11:49 -08004171 if (Patterns.WEB_URL.matcher(inUrl).matches()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08004172 return URLUtil.guessUrl(inUrl);
4173 }
4174 }
4175
4176 Browser.addSearchUrl(mResolver, inUrl);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07004177 return URLUtil.composeSearchUrl(inUrl, QuickSearch_G, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004178 }
4179
Ben Murdochbff2d602009-07-01 20:19:05 +01004180 /* package */ void setShouldShowErrorConsole(boolean flag) {
4181 if (flag == mShouldShowErrorConsole) {
4182 // Nothing to do.
4183 return;
4184 }
4185
4186 mShouldShowErrorConsole = flag;
4187
Grace Kloba22ac16e2009-10-07 18:00:23 -07004188 ErrorConsoleView errorConsole = mTabControl.getCurrentTab()
4189 .getErrorConsole(true);
Ben Murdochbff2d602009-07-01 20:19:05 +01004190
4191 if (flag) {
4192 // Setting the show state of the console will cause it's the layout to be inflated.
4193 if (errorConsole.numberOfErrors() > 0) {
4194 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
4195 } else {
4196 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
4197 }
4198
4199 // Now we can add it to the main view.
4200 mErrorConsoleContainer.addView(errorConsole,
Romain Guy15b8ec62010-01-08 15:06:43 -08004201 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
Ben Murdochbff2d602009-07-01 20:19:05 +01004202 ViewGroup.LayoutParams.WRAP_CONTENT));
4203 } else {
4204 mErrorConsoleContainer.removeView(errorConsole);
4205 }
4206
4207 }
4208
Grace Kloba22ac16e2009-10-07 18:00:23 -07004209 boolean shouldShowErrorConsole() {
4210 return mShouldShowErrorConsole;
4211 }
4212
Andrei Popescu163ab742009-10-20 17:58:23 +01004213 private void setStatusBarVisibility(boolean visible) {
4214 int flag = visible ? 0 : WindowManager.LayoutParams.FLAG_FULLSCREEN;
4215 getWindow().setFlags(flag, WindowManager.LayoutParams.FLAG_FULLSCREEN);
4216 }
4217
Andrei Popescu56199cc2010-01-12 22:39:16 +00004218
4219 private void sendNetworkType(String type, String subtype) {
4220 WebView w = mTabControl.getCurrentWebView();
4221 if (w != null) {
4222 w.setNetworkType(type, subtype);
4223 }
4224 }
4225
Andrei Popescu30995e72010-02-09 16:59:58 +00004226 private void packageChanged(String packageName, boolean wasAdded) {
4227 WebView w = mTabControl.getCurrentWebView();
4228 if (w == null) {
4229 return;
4230 }
4231
4232 if (wasAdded) {
4233 w.addPackageName(packageName);
4234 } else {
4235 w.removePackageName(packageName);
4236 }
4237 }
4238
4239 private void addPackageNames(Set<String> packageNames) {
4240 WebView w = mTabControl.getCurrentWebView();
4241 if (w == null) {
4242 return;
4243 }
4244
4245 w.addPackageNames(packageNames);
4246 }
4247
4248 private void getInstalledPackages() {
4249 AsyncTask<Void, Void, Set<String> > task =
4250 new AsyncTask<Void, Void, Set<String> >() {
Michael Kolbe0a36662010-06-29 10:37:12 -07004251 @Override
Andrei Popescu30995e72010-02-09 16:59:58 +00004252 protected Set<String> doInBackground(Void... unused) {
4253 Set<String> installedPackages = new HashSet<String>();
4254 PackageManager pm = BrowserActivity.this.getPackageManager();
4255 if (pm != null) {
4256 List<PackageInfo> packages = pm.getInstalledPackages(0);
4257 for (PackageInfo p : packages) {
4258 if (BrowserActivity.this.sGoogleApps.contains(p.packageName)) {
4259 installedPackages.add(p.packageName);
4260 }
4261 }
4262 }
4263
4264 return installedPackages;
4265 }
4266
4267 // Executes on the UI thread
Michael Kolbe0a36662010-06-29 10:37:12 -07004268 @Override
Andrei Popescu30995e72010-02-09 16:59:58 +00004269 protected void onPostExecute(Set<String> installedPackages) {
4270 addPackageNames(installedPackages);
4271 }
4272 };
4273 task.execute();
4274 }
4275
Grace Klobaeb6eef42009-09-15 17:56:32 -07004276 final static int LOCK_ICON_UNSECURE = 0;
4277 final static int LOCK_ICON_SECURE = 1;
4278 final static int LOCK_ICON_MIXED = 2;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004279
The Android Open Source Project0c908882009-03-03 19:32:16 -08004280 private BrowserSettings mSettings;
4281 private TabControl mTabControl;
4282 private ContentResolver mResolver;
4283 private FrameLayout mContentView;
Andrei Popescuadc008d2009-06-26 14:11:30 +01004284 private View mCustomView;
4285 private FrameLayout mCustomViewContainer;
Andrei Popescuc9b55562009-07-07 10:51:15 +01004286 private WebChromeClient.CustomViewCallback mCustomViewCallback;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004287
4288 // FIXME, temp address onPrepareMenu performance problem. When we move everything out of
4289 // view, we should rewrite this.
4290 private int mCurrentMenuState = 0;
4291 private int mMenuState = R.id.MAIN_MENU;
Andrei Popescuadc008d2009-06-26 14:11:30 +01004292 private int mOldMenuState = EMPTY_MENU;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004293 private static final int EMPTY_MENU = -1;
4294 private Menu mMenu;
4295
The Android Open Source Project0c908882009-03-03 19:32:16 -08004296 // Used to prevent chording to result in firing two shortcuts immediately
4297 // one after another. Fixes bug 1211714.
4298 boolean mCanChord;
4299
4300 private boolean mInLoad;
4301 private boolean mIsNetworkUp;
Ben Murdochb7cc8b42009-09-28 10:59:09 +01004302 private boolean mDidStopLoad;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004303
Cary Clark1f10cbf2010-03-22 11:45:23 -04004304 /* package */ boolean mActivityInPause = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004305
4306 private boolean mMenuIsDown;
4307
The Android Open Source Project0c908882009-03-03 19:32:16 -08004308 private static boolean mInTrace;
4309
4310 // Performance probe
4311 private static final int[] SYSTEM_CPU_FORMAT = new int[] {
4312 Process.PROC_SPACE_TERM | Process.PROC_COMBINE,
4313 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 1: user time
4314 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 2: nice time
4315 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 3: sys time
4316 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 4: idle time
4317 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 5: iowait time
4318 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 6: irq time
4319 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG // 7: softirq time
4320 };
4321
4322 private long mStart;
4323 private long mProcessStart;
4324 private long mUserStart;
4325 private long mSystemStart;
4326 private long mIdleStart;
4327 private long mIrqStart;
4328
4329 private long mUiStart;
4330
4331 private Drawable mMixLockIcon;
4332 private Drawable mSecLockIcon;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004333
4334 /* hold a ref so we can auto-cancel if necessary */
4335 private AlertDialog mAlertDialog;
4336
The Android Open Source Project0c908882009-03-03 19:32:16 -08004337 // The up-to-date URL and title (these can be different from those stored
4338 // in WebView, since it takes some time for the information in WebView to
4339 // get updated)
4340 private String mUrl;
4341 private String mTitle;
4342
4343 // As PageInfo has different style for landscape / portrait, we have
4344 // to re-open it when configuration changed
4345 private AlertDialog mPageInfoDialog;
Grace Kloba22ac16e2009-10-07 18:00:23 -07004346 private Tab mPageInfoView;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004347 // If the Page-Info dialog is launched from the SSL-certificate-on-error
4348 // dialog, we should not just dismiss it, but should get back to the
4349 // SSL-certificate-on-error dialog. This flag is used to store this state
Leon Scrogginsc7b92f82010-01-11 18:17:31 -05004350 private boolean mPageInfoFromShowSSLCertificateOnError;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004351
4352 // as SSLCertificateOnError has different style for landscape / portrait,
4353 // we have to re-open it when configuration changed
4354 private AlertDialog mSSLCertificateOnErrorDialog;
4355 private WebView mSSLCertificateOnErrorView;
4356 private SslErrorHandler mSSLCertificateOnErrorHandler;
4357 private SslError mSSLCertificateOnErrorError;
4358
4359 // as SSLCertificate has different style for landscape / portrait, we
4360 // have to re-open it when configuration changed
4361 private AlertDialog mSSLCertificateDialog;
Grace Kloba22ac16e2009-10-07 18:00:23 -07004362 private Tab mSSLCertificateView;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004363
4364 // as HttpAuthentication has different style for landscape / portrait, we
4365 // have to re-open it when configuration changed
4366 private AlertDialog mHttpAuthenticationDialog;
4367 private HttpAuthHandler mHttpAuthHandler;
4368
4369 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_PARAMS =
4370 new FrameLayout.LayoutParams(
Romain Guy15b8ec62010-01-08 15:06:43 -08004371 ViewGroup.LayoutParams.MATCH_PARENT,
4372 ViewGroup.LayoutParams.MATCH_PARENT);
Andrei Popescuadc008d2009-06-26 14:11:30 +01004373 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_GRAVITY_CENTER =
4374 new FrameLayout.LayoutParams(
Romain Guy15b8ec62010-01-08 15:06:43 -08004375 ViewGroup.LayoutParams.MATCH_PARENT,
4376 ViewGroup.LayoutParams.MATCH_PARENT,
Andrei Popescuadc008d2009-06-26 14:11:30 +01004377 Gravity.CENTER);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07004378 // Google search
4379 final static String QuickSearch_G = "http://www.google.com/m?q=%s";
The Android Open Source Project0c908882009-03-03 19:32:16 -08004380 // Wikipedia search
4381 final static String QuickSearch_W = "http://en.wikipedia.org/w/index.php?search=%s&go=Go";
4382 // Dictionary search
4383 final static String QuickSearch_D = "http://dictionary.reference.com/search?q=%s";
4384 // Google Mobile Local search
4385 final static String QuickSearch_L = "http://www.google.com/m/search?site=local&q=%s&near=mountain+view";
4386
4387 final static String QUERY_PLACE_HOLDER = "%s";
4388
4389 // "source" parameter for Google search through search key
4390 final static String GOOGLE_SEARCH_SOURCE_SEARCHKEY = "browser-key";
4391 // "source" parameter for Google search through goto menu
4392 final static String GOOGLE_SEARCH_SOURCE_GOTO = "browser-goto";
4393 // "source" parameter for Google search through simplily type
4394 final static String GOOGLE_SEARCH_SOURCE_TYPE = "browser-type";
4395 // "source" parameter for Google search suggested by the browser
4396 final static String GOOGLE_SEARCH_SOURCE_SUGGEST = "browser-suggest";
4397 // "source" parameter for Google search from unknown source
4398 final static String GOOGLE_SEARCH_SOURCE_UNKNOWN = "unknown";
4399
4400 private final static String LOGTAG = "browser";
4401
The Android Open Source Project0c908882009-03-03 19:32:16 -08004402 private String mLastEnteredUrl;
4403
4404 private PowerManager.WakeLock mWakeLock;
4405 private final static int WAKELOCK_TIMEOUT = 5 * 60 * 1000; // 5 minutes
4406
4407 private Toast mStopToast;
4408
Leon Scroggins571b3762010-05-26 10:25:01 -04004409 private TitleBarBase mTitleBar;
Michael Kolba2b2ba82010-08-04 17:54:03 -07004410 private TabBar mTabBar;
Leon Scroggins81db3662009-06-04 17:45:11 -04004411
Ben Murdochbff2d602009-07-01 20:19:05 +01004412 private LinearLayout mErrorConsoleContainer = null;
4413 private boolean mShouldShowErrorConsole = false;
4414
The Android Open Source Project0c908882009-03-03 19:32:16 -08004415 // As the ids are dynamically created, we can't guarantee that they will
4416 // be in sequence, so this static array maps ids to a window number.
4417 final static private int[] WINDOW_SHORTCUT_ID_ARRAY =
4418 { R.id.window_one_menu_id, R.id.window_two_menu_id, R.id.window_three_menu_id,
4419 R.id.window_four_menu_id, R.id.window_five_menu_id, R.id.window_six_menu_id,
4420 R.id.window_seven_menu_id, R.id.window_eight_menu_id };
4421
4422 // monitor platform changes
4423 private IntentFilter mNetworkStateChangedFilter;
4424 private BroadcastReceiver mNetworkStateIntentReceiver;
4425
Grace Klobab4da0ad2009-05-14 14:45:40 -07004426 private BroadcastReceiver mPackageInstallationReceiver;
4427
Bjorn Bringerta7611812010-03-24 11:12:02 +00004428 private SystemAllowGeolocationOrigins mSystemAllowGeolocationOrigins;
4429
The Android Open Source Project0c908882009-03-03 19:32:16 -08004430 // activity requestCode
Nicolas Roard78a98e42009-05-11 13:34:17 +01004431 final static int COMBO_PAGE = 1;
4432 final static int DOWNLOAD_PAGE = 2;
4433 final static int PREFERENCES_PAGE = 3;
Leon Scroggins8d5fa432009-10-02 15:55:59 -04004434 final static int FILE_SELECTED = 4;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004435
Andrei Popescu540035d2009-09-18 18:59:20 +01004436 // the default <video> poster
4437 private Bitmap mDefaultVideoPoster;
4438 // the video progress view
4439 private View mVideoProgressView;
4440
Andrei Popescu30995e72010-02-09 16:59:58 +00004441 // The Google packages we monitor for the navigator.isApplicationInstalled()
4442 // API. Add as needed.
4443 private static Set<String> sGoogleApps;
4444 static {
4445 sGoogleApps = new HashSet<String>();
4446 sGoogleApps.add("com.google.android.youtube");
4447 }
4448
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004449 /**
4450 * A UrlData class to abstract how the content will be set to WebView.
4451 * This base class uses loadUrl to show the content.
4452 */
Leon Scroggins6eac63e2010-03-15 18:19:14 -04004453 /* package */ static class UrlData {
Grace Kloba068e48b2010-01-26 18:11:27 -08004454 final String mUrl;
4455 final Map<String, String> mHeaders;
Leon Scroggins58d56c62010-01-28 15:12:40 -05004456 final Intent mVoiceIntent;
Grace Kloba60e095c2009-06-16 11:50:55 -07004457
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004458 UrlData(String url) {
4459 this.mUrl = url;
Grace Kloba068e48b2010-01-26 18:11:27 -08004460 this.mHeaders = null;
Leon Scroggins58d56c62010-01-28 15:12:40 -05004461 this.mVoiceIntent = null;
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004462 }
Grace Kloba60e095c2009-06-16 11:50:55 -07004463
Leon Scroggins58d56c62010-01-28 15:12:40 -05004464 UrlData(String url, Map<String, String> headers, Intent intent) {
Grace Kloba068e48b2010-01-26 18:11:27 -08004465 this.mUrl = url;
4466 this.mHeaders = headers;
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -05004467 if (RecognizerResultsIntent.ACTION_VOICE_SEARCH_RESULTS
4468 .equals(intent.getAction())) {
Leon Scroggins58d56c62010-01-28 15:12:40 -05004469 this.mVoiceIntent = intent;
4470 } else {
4471 this.mVoiceIntent = null;
4472 }
Grace Kloba60e095c2009-06-16 11:50:55 -07004473 }
4474
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004475 boolean isEmpty() {
Leon Scroggins58d56c62010-01-28 15:12:40 -05004476 return mVoiceIntent == null && (mUrl == null || mUrl.length() == 0);
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004477 }
4478
Leon Scroggins92472e82010-02-17 16:32:28 -05004479 /**
4480 * Load this UrlData into the given Tab. Use loadUrlDataIn to update
4481 * the title bar as well.
4482 */
Leon Scroggins58d56c62010-01-28 15:12:40 -05004483 public void loadIn(Tab t) {
4484 if (mVoiceIntent != null) {
4485 t.activateVoiceSearchMode(mVoiceIntent);
4486 } else {
4487 t.getWebView().loadUrl(mUrl, mHeaders);
4488 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004489 }
4490 };
4491
Leon Scroggins1f005d32009-08-10 17:36:42 -04004492 /* package */ static final UrlData EMPTY_URL_DATA = new UrlData(null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004493}