blob: f38071175eb31614d29fc00fe64d575c6293ec64 [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;
Elliott Slaughter8389e992010-08-20 15:44:08 -0700709 if (mTabControl == null
710 || mTabControl.getCurrentWebView() == null
711 || !mTabControl.getCurrentWebView().isPrivateBrowsingEnabled()) {
712 new AsyncTask<Void, Void, Void>() {
713 @Override
714 protected Void doInBackground(Void... unused) {
715 Browser.updateVisitedHistory(cr, newUrl, false);
716 return null;
717 }
718 }.execute();
719 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800720 String searchSource = "&source=android-" + GOOGLE_SEARCH_SOURCE_SUGGEST + "&";
721 if (url.contains(searchSource)) {
722 String source = null;
723 final Bundle appData = intent.getBundleExtra(SearchManager.APP_DATA);
724 if (appData != null) {
Bjorn Bringert10d1cca2010-02-10 14:22:12 +0000725 source = appData.getString(Search.SOURCE);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800726 }
727 if (TextUtils.isEmpty(source)) {
728 source = GOOGLE_SEARCH_SOURCE_UNKNOWN;
729 }
730 url = url.replace(searchSource, "&source=android-"+source+"&");
731 }
732 }
733 }
734 }
Leon Scroggins58d56c62010-01-28 15:12:40 -0500735 return new UrlData(url, headers, intent);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800736 }
Leon Scroggins58d56c62010-01-28 15:12:40 -0500737 /* package */ void showVoiceTitleBar(String title) {
738 mTitleBar.setInVoiceMode(true);
Leon Scroggins58d56c62010-01-28 15:12:40 -0500739 mTitleBar.setDisplayTitle(title);
Michael Kolba2b2ba82010-08-04 17:54:03 -0700740 mFakeTitleBar.setInVoiceMode(true);
741 mFakeTitleBar.setDisplayTitle(title);
Leon Scroggins58d56c62010-01-28 15:12:40 -0500742 }
743 /* package */ void revertVoiceTitleBar() {
744 mTitleBar.setInVoiceMode(false);
Leon Scroggins003a5dd2010-03-10 12:13:14 -0500745 mTitleBar.setDisplayTitle(mUrl);
Michael Kolba2b2ba82010-08-04 17:54:03 -0700746 mFakeTitleBar.setInVoiceMode(false);
747 mFakeTitleBar.setDisplayTitle(mUrl);
Leon Scroggins58d56c62010-01-28 15:12:40 -0500748 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800749 /* package */ static String fixUrl(String inUrl) {
Cary Clark652ff872009-09-10 13:34:44 -0400750 // FIXME: Converting the url to lower case
751 // duplicates functionality in smartUrlFilter().
752 // However, changing all current callers of fixUrl to
753 // call smartUrlFilter in addition may have unwanted
754 // consequences, and is deferred for now.
755 int colon = inUrl.indexOf(':');
756 boolean allLower = true;
757 for (int index = 0; index < colon; index++) {
758 char ch = inUrl.charAt(index);
759 if (!Character.isLetter(ch)) {
760 break;
761 }
762 allLower &= Character.isLowerCase(ch);
763 if (index == colon - 1 && !allLower) {
764 inUrl = inUrl.substring(0, colon).toLowerCase()
765 + inUrl.substring(colon);
766 }
767 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800768 if (inUrl.startsWith("http://") || inUrl.startsWith("https://"))
769 return inUrl;
770 if (inUrl.startsWith("http:") ||
771 inUrl.startsWith("https:")) {
772 if (inUrl.startsWith("http:/") || inUrl.startsWith("https:/")) {
773 inUrl = inUrl.replaceFirst("/", "//");
774 } else inUrl = inUrl.replaceFirst(":", "://");
775 }
776 return inUrl;
777 }
778
Grace Kloba22ac16e2009-10-07 18:00:23 -0700779 @Override
780 protected void onResume() {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800781 super.onResume();
Dave Bort31a6d1c2009-04-13 15:56:49 -0700782 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800783 Log.v(LOGTAG, "BrowserActivity.onResume: this=" + this);
784 }
785
786 if (!mActivityInPause) {
787 Log.e(LOGTAG, "BrowserActivity is already resumed.");
788 return;
789 }
790
Mike Reed7bfa63b2009-05-28 11:08:32 -0400791 mTabControl.resumeCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800792 mActivityInPause = false;
Mike Reed7bfa63b2009-05-28 11:08:32 -0400793 resumeWebViewTimers();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800794
795 if (mWakeLock.isHeld()) {
796 mHandler.removeMessages(RELEASE_WAKELOCK);
797 mWakeLock.release();
798 }
799
The Android Open Source Project0c908882009-03-03 19:32:16 -0800800 registerReceiver(mNetworkStateIntentReceiver,
801 mNetworkStateChangedFilter);
802 WebView.enablePlatformNotifications();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800803 }
804
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400805 /**
806 * Since the actual title bar is embedded in the WebView, and removing it
Leon Scrogginsfe87bd32009-10-06 10:10:00 -0400807 * would change its appearance, use a different TitleBar to show overlayed
808 * at the top of the screen, when the menu is open or the page is loading.
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400809 */
Michael Kolba2b2ba82010-08-04 17:54:03 -0700810 private TitleBarBase mFakeTitleBar;
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400811
812 /**
813 * Keeps track of whether the options menu is open. This is important in
814 * determining whether to show or hide the title bar overlay.
815 */
816 private boolean mOptionsMenuOpen;
817
818 /**
819 * Only meaningful when mOptionsMenuOpen is true. This variable keeps track
820 * of whether the configuration has changed. The first onMenuOpened call
821 * after a configuration change is simply a reopening of the same menu
822 * (i.e. mIconView did not change).
823 */
824 private boolean mConfigChanged;
825
826 /**
827 * Whether or not the options menu is in its smaller, icon menu form. When
828 * true, we want the title bar overlay to be up. When false, we do not.
829 * Only meaningful if mOptionsMenuOpen is true.
830 */
831 private boolean mIconView;
832
Leon Scrogginsa81a7642009-08-31 17:05:41 -0400833 @Override
834 public boolean onMenuOpened(int featureId, Menu menu) {
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400835 if (Window.FEATURE_OPTIONS_PANEL == featureId) {
836 if (mOptionsMenuOpen) {
837 if (mConfigChanged) {
838 // We do not need to make any changes to the state of the
839 // title bar, since the only thing that happened was a
840 // change in orientation
841 mConfigChanged = false;
842 } else {
843 if (mIconView) {
844 // Switching the menu to expanded view, so hide the
845 // title bar.
846 hideFakeTitleBar();
847 mIconView = false;
848 } else {
849 // Switching the menu back to icon view, so show the
850 // title bar once again.
851 showFakeTitleBar();
852 mIconView = true;
853 }
854 }
855 } else {
856 // The options menu is closed, so open it, and show the title
857 showFakeTitleBar();
858 mOptionsMenuOpen = true;
859 mConfigChanged = false;
860 mIconView = true;
861 }
862 }
Leon Scrogginsa81a7642009-08-31 17:05:41 -0400863 return true;
864 }
865
Michael Kolba2b2ba82010-08-04 17:54:03 -0700866 void showFakeTitleBar() {
867 if (!isFakeTitleBarShowing() && mActiveTabsPage == null && !mActivityInPause) {
Grace Kloba847c25b2010-03-30 16:00:26 -0700868 WebView mainView = mTabControl.getCurrentWebView();
869 // if there is no current WebView, don't show the faked title bar;
Grace Kloba65190702010-04-02 23:37:26 -0700870 if (mainView == null) {
Cary Clarka0464552009-09-29 13:00:45 -0400871 return;
872 }
Leon Scroggins79e36d92010-04-29 16:01:46 +0100873 // Do not need to check for null, since the current tab will have
874 // at least a main WebView, or we would have returned above.
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -0400875 if (isInCustomActionMode()) {
876 // Do not show the fake title bar, while a custom ActionMode
877 // (i.e. find or select) is showing.
Leon Scroggins79e36d92010-04-29 16:01:46 +0100878 return;
879 }
Michael Kolba2b2ba82010-08-04 17:54:03 -0700880 if (mXLargeScreenSize) {
881 mContentView.addView(mFakeTitleBar);
882 mTabBar.onShowTitleBar();
883 } else {
884 WindowManager manager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400885
Michael Kolba2b2ba82010-08-04 17:54:03 -0700886 // Add the title bar to the window manager so it can receive
887 // touches
888 // while the menu is up
889 WindowManager.LayoutParams params =
890 new WindowManager.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
891 ViewGroup.LayoutParams.WRAP_CONTENT,
892 WindowManager.LayoutParams.TYPE_APPLICATION,
893 WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
894 PixelFormat.TRANSLUCENT);
895 params.gravity = Gravity.TOP;
896 boolean atTop = mainView.getScrollY() == 0;
897 params.windowAnimations = atTop ? 0 : R.style.TitleBar;
898 manager.addView(mFakeTitleBar, params);
899 }
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400900 }
901 }
902
903 @Override
904 public void onOptionsMenuClosed(Menu menu) {
905 mOptionsMenuOpen = false;
Leon Scrogginsa27ff192009-09-14 12:58:04 -0400906 if (!mInLoad) {
907 hideFakeTitleBar();
908 } else if (!mIconView) {
909 // The page is currently loading, and we are in expanded mode, so
910 // we were not showing the menu. Show it once again. It will be
911 // removed when the page finishes.
912 showFakeTitleBar();
913 }
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400914 }
Grace Kloba22ac16e2009-10-07 18:00:23 -0700915
Michael Kolba2b2ba82010-08-04 17:54:03 -0700916 void stopScrolling() {
917 ((ScrollWebView) mTabControl.getCurrentWebView()).stopScroll();
918 }
919
920 void hideFakeTitleBar() {
921 if (!isFakeTitleBarShowing()) return;
922 if (mXLargeScreenSize) {
923 mContentView.removeView(mFakeTitleBar);
924 mTabBar.onHideTitleBar();
925 } else {
926 WindowManager.LayoutParams params =
927 (WindowManager.LayoutParams) mFakeTitleBar.getLayoutParams();
928 WebView mainView = mTabControl.getCurrentWebView();
929 // Although we decided whether or not to animate based on the
930 // current
931 // scroll position, the scroll position may have changed since the
932 // fake title bar was displayed. Make sure it has the appropriate
933 // animation/lack thereof before removing.
934 params.windowAnimations =
935 mainView != null && mainView.getScrollY() == 0 ? 0 : R.style.TitleBar;
936 WindowManager manager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
937 manager.updateViewLayout(mFakeTitleBar, params);
938 manager.removeView(mFakeTitleBar);
939 }
940 }
941
942 boolean isFakeTitleBarShowing() {
943 return (mFakeTitleBar.getParent() != null);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400944 }
945
The Android Open Source Project0c908882009-03-03 19:32:16 -0800946 /**
Leon Scrogginsc6fa1102009-09-21 10:40:01 -0400947 * Special method for the fake title bar to call when displaying its context
948 * menu, since it is in its own Window, and its parent does not show a
949 * context menu.
950 */
951 /* package */ void showTitleBarContextMenu() {
Cary Clark65f4a3c2009-09-28 17:05:06 -0400952 if (null == mTitleBar.getParent()) {
953 return;
954 }
Leon Scrogginsc6fa1102009-09-21 10:40:01 -0400955 openContextMenu(mTitleBar);
956 }
957
Leon Scrogginsb2b19f52009-10-09 16:10:00 -0400958 @Override
959 public void onContextMenuClosed(Menu menu) {
960 super.onContextMenuClosed(menu);
961 if (mInLoad) {
962 showFakeTitleBar();
963 }
964 }
965
Leon Scrogginsc6fa1102009-09-21 10:40:01 -0400966 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -0800967 * onSaveInstanceState(Bundle map)
968 * onSaveInstanceState is called right before onStop(). The map contains
969 * the saved state.
970 */
Grace Kloba22ac16e2009-10-07 18:00:23 -0700971 @Override
972 protected void onSaveInstanceState(Bundle outState) {
Dave Bort31a6d1c2009-04-13 15:56:49 -0700973 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800974 Log.v(LOGTAG, "BrowserActivity.onSaveInstanceState: this=" + this);
975 }
976 // the default implementation requires each view to have an id. As the
977 // browser handles the state itself and it doesn't use id for the views,
978 // don't call the default implementation. Otherwise it will trigger the
979 // warning like this, "couldn't save which view has focus because the
980 // focused view XXX has no id".
981
982 // Save all the tabs
983 mTabControl.saveState(outState);
984 }
985
Grace Kloba22ac16e2009-10-07 18:00:23 -0700986 @Override
987 protected void onPause() {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800988 super.onPause();
989
990 if (mActivityInPause) {
991 Log.e(LOGTAG, "BrowserActivity is already paused.");
992 return;
993 }
994
Mike Reed7bfa63b2009-05-28 11:08:32 -0400995 mTabControl.pauseCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800996 mActivityInPause = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -0400997 if (mTabControl.getCurrentIndex() >= 0 && !pauseWebViewTimers()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800998 mWakeLock.acquire();
999 mHandler.sendMessageDelayed(mHandler
1000 .obtainMessage(RELEASE_WAKELOCK), WAKELOCK_TIMEOUT);
1001 }
1002
Leon Scrogginsa2ab6a72009-09-11 11:49:52 -04001003 // FIXME: This removes the active tabs page and resets the menu to
1004 // MAIN_MENU. A better solution might be to do this work in onNewIntent
1005 // but then we would need to save it in onSaveInstanceState and restore
1006 // it in onCreate/onRestoreInstanceState
1007 if (mActiveTabsPage != null) {
1008 removeActiveTabPage(true);
1009 }
1010
The Android Open Source Project0c908882009-03-03 19:32:16 -08001011 cancelStopToast();
1012
1013 // unregister network state listener
1014 unregisterReceiver(mNetworkStateIntentReceiver);
1015 WebView.disablePlatformNotifications();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001016 }
1017
Grace Kloba22ac16e2009-10-07 18:00:23 -07001018 @Override
1019 protected void onDestroy() {
Dave Bort31a6d1c2009-04-13 15:56:49 -07001020 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001021 Log.v(LOGTAG, "BrowserActivity.onDestroy: this=" + this);
1022 }
1023 super.onDestroy();
Grace Kloba0923d692009-09-23 21:37:25 -07001024
Leon Scroggins8d5fa432009-10-02 15:55:59 -04001025 if (mUploadMessage != null) {
1026 mUploadMessage.onReceiveValue(null);
1027 mUploadMessage = null;
1028 }
1029
Grace Kloba0923d692009-09-23 21:37:25 -07001030 if (mTabControl == null) return;
1031
Grace Kloba1fc98a32009-10-21 13:23:08 -07001032 // Remove the fake title bar if it is there
1033 hideFakeTitleBar();
1034
The Android Open Source Project0c908882009-03-03 19:32:16 -08001035 // Remove the current tab and sub window
Grace Kloba22ac16e2009-10-07 18:00:23 -07001036 Tab t = mTabControl.getCurrentTab();
Patrick Scottfb5e77f2009-04-08 19:17:37 -07001037 if (t != null) {
1038 dismissSubWindow(t);
1039 removeTabFromContentView(t);
1040 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001041 // Destroy all the tabs
1042 mTabControl.destroy();
1043 WebIconDatabase.getInstance().close();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001044
Grace Klobab4da0ad2009-05-14 14:45:40 -07001045 unregisterReceiver(mPackageInstallationReceiver);
Bjorn Bringerta7611812010-03-24 11:12:02 +00001046
1047 // Stop watching the default geolocation permissions
1048 mSystemAllowGeolocationOrigins.stop();
1049 mSystemAllowGeolocationOrigins = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001050 }
1051
1052 @Override
1053 public void onConfigurationChanged(Configuration newConfig) {
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04001054 mConfigChanged = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001055 super.onConfigurationChanged(newConfig);
1056
1057 if (mPageInfoDialog != null) {
1058 mPageInfoDialog.dismiss();
1059 showPageInfo(
1060 mPageInfoView,
Leon Scrogginsc7b92f82010-01-11 18:17:31 -05001061 mPageInfoFromShowSSLCertificateOnError);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001062 }
1063 if (mSSLCertificateDialog != null) {
1064 mSSLCertificateDialog.dismiss();
1065 showSSLCertificate(
1066 mSSLCertificateView);
1067 }
1068 if (mSSLCertificateOnErrorDialog != null) {
1069 mSSLCertificateOnErrorDialog.dismiss();
1070 showSSLCertificateOnError(
1071 mSSLCertificateOnErrorView,
1072 mSSLCertificateOnErrorHandler,
1073 mSSLCertificateOnErrorError);
1074 }
1075 if (mHttpAuthenticationDialog != null) {
1076 String title = ((TextView) mHttpAuthenticationDialog
1077 .findViewById(com.android.internal.R.id.alertTitle)).getText()
1078 .toString();
1079 String name = ((TextView) mHttpAuthenticationDialog
1080 .findViewById(R.id.username_edit)).getText().toString();
1081 String password = ((TextView) mHttpAuthenticationDialog
1082 .findViewById(R.id.password_edit)).getText().toString();
1083 int focusId = mHttpAuthenticationDialog.getCurrentFocus()
1084 .getId();
1085 mHttpAuthenticationDialog.dismiss();
1086 showHttpAuthentication(mHttpAuthHandler, null, null, title,
1087 name, password, focusId);
1088 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001089 }
1090
Grace Kloba22ac16e2009-10-07 18:00:23 -07001091 @Override
1092 public void onLowMemory() {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001093 super.onLowMemory();
1094 mTabControl.freeMemory();
1095 }
1096
Cary Clarkff4d92c2010-03-25 11:17:03 -04001097 private void resumeWebViewTimers() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001098 Tab tab = mTabControl.getCurrentTab();
Cary Clarkff4d92c2010-03-25 11:17:03 -04001099 if (tab == null) return; // monkey can trigger this
Grace Kloba22ac16e2009-10-07 18:00:23 -07001100 boolean inLoad = tab.inLoad();
1101 if ((!mActivityInPause && !inLoad) || (mActivityInPause && inLoad)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001102 CookieSyncManager.getInstance().startSync();
Grace Kloba22ac16e2009-10-07 18:00:23 -07001103 WebView w = tab.getWebView();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001104 if (w != null) {
1105 w.resumeTimers();
1106 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001107 }
1108 }
1109
Mike Reed7bfa63b2009-05-28 11:08:32 -04001110 private boolean pauseWebViewTimers() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001111 Tab tab = mTabControl.getCurrentTab();
1112 boolean inLoad = tab.inLoad();
1113 if (mActivityInPause && !inLoad) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001114 CookieSyncManager.getInstance().stopSync();
1115 WebView w = mTabControl.getCurrentWebView();
1116 if (w != null) {
1117 w.pauseTimers();
1118 }
1119 return true;
1120 } else {
1121 return false;
1122 }
1123 }
1124
The Android Open Source Project0c908882009-03-03 19:32:16 -08001125 // Open the icon database and retain all the icons for visited sites.
1126 private void retainIconsOnStartup() {
1127 final WebIconDatabase db = WebIconDatabase.getInstance();
1128 db.open(getDir("icons", 0).getPath());
Leon Scroggins2c0f6112010-03-12 18:09:39 -05001129 Cursor c = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001130 try {
Leon Scroggins2c0f6112010-03-12 18:09:39 -05001131 c = Browser.getAllBookmarks(mResolver);
1132 if (c.moveToFirst()) {
1133 int urlIndex = c.getColumnIndex(Browser.BookmarkColumns.URL);
1134 do {
1135 String url = c.getString(urlIndex);
1136 db.retainIconForPageUrl(url);
1137 } while (c.moveToNext());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001138 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001139 } catch (IllegalStateException e) {
1140 Log.e(LOGTAG, "retainIconsOnStartup", e);
Leon Scroggins2c0f6112010-03-12 18:09:39 -05001141 } finally {
1142 if (c!= null) c.close();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001143 }
1144 }
1145
1146 // Helper method for getting the top window.
1147 WebView getTopWindow() {
1148 return mTabControl.getCurrentTopWebView();
1149 }
1150
Grace Kloba22ac16e2009-10-07 18:00:23 -07001151 TabControl getTabControl() {
1152 return mTabControl;
1153 }
1154
The Android Open Source Project0c908882009-03-03 19:32:16 -08001155 @Override
1156 public boolean onCreateOptionsMenu(Menu menu) {
1157 super.onCreateOptionsMenu(menu);
1158
1159 MenuInflater inflater = getMenuInflater();
1160 inflater.inflate(R.menu.browser, menu);
1161 mMenu = menu;
1162 updateInLoadMenuItems();
1163 return true;
1164 }
1165
1166 /**
1167 * As the menu can be open when loading state changes
1168 * we must manually update the state of the stop/reload menu
1169 * item
1170 */
1171 private void updateInLoadMenuItems() {
1172 if (mMenu == null) {
1173 return;
1174 }
Michael Kolbe0a36662010-06-29 10:37:12 -07001175 MenuItem dest = mMenu.findItem(R.id.stop_reload_menu_id);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001176 MenuItem src = mInLoad ?
1177 mMenu.findItem(R.id.stop_menu_id):
Michael Kolbe0a36662010-06-29 10:37:12 -07001178 mMenu.findItem(R.id.reload_menu_id);
1179 if (src != null) {
1180 dest.setIcon(src.getIcon());
1181 dest.setTitle(src.getTitle());
1182 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001183 }
1184
1185 @Override
1186 public boolean onContextItemSelected(MenuItem item) {
1187 // chording is not an issue with context menus, but we use the same
1188 // options selector, so set mCanChord to true so we can access them.
1189 mCanChord = true;
1190 int id = item.getItemId();
Leon Scroggins96afcb12009-12-10 12:35:56 -05001191 boolean result = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001192 switch (id) {
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001193 // For the context menu from the title bar
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001194 case R.id.title_bar_copy_page_url:
Leon Scroggins96afcb12009-12-10 12:35:56 -05001195 Tab currentTab = mTabControl.getCurrentTab();
1196 if (null == currentTab) {
1197 result = false;
1198 break;
1199 }
1200 WebView mainView = currentTab.getWebView();
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001201 if (null == mainView) {
Leon Scroggins96afcb12009-12-10 12:35:56 -05001202 result = false;
1203 break;
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001204 }
Leon Scroggins96afcb12009-12-10 12:35:56 -05001205 copy(mainView.getUrl());
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001206 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001207 // -- Browser context menu
1208 case R.id.open_context_menu_id:
The Android Open Source Project0c908882009-03-03 19:32:16 -08001209 case R.id.bookmark_context_menu_id:
1210 case R.id.save_link_context_menu_id:
1211 case R.id.share_link_context_menu_id:
1212 case R.id.copy_link_context_menu_id:
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001213 final WebView webView = getTopWindow();
1214 if (null == webView) {
Leon Scroggins96afcb12009-12-10 12:35:56 -05001215 result = false;
1216 break;
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001217 }
1218 final HashMap hrefMap = new HashMap();
1219 hrefMap.put("webview", webView);
1220 final Message msg = mHandler.obtainMessage(
1221 FOCUS_NODE_HREF, id, 0, hrefMap);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001222 webView.requestFocusNodeHref(msg);
1223 break;
1224
1225 default:
1226 // For other context menus
Leon Scroggins96afcb12009-12-10 12:35:56 -05001227 result = onOptionsItemSelected(item);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001228 }
1229 mCanChord = false;
Leon Scroggins96afcb12009-12-10 12:35:56 -05001230 return result;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001231 }
1232
1233 private Bundle createGoogleSearchSourceBundle(String source) {
1234 Bundle bundle = new Bundle();
Bjorn Bringert10d1cca2010-02-10 14:22:12 +00001235 bundle.putString(Search.SOURCE, source);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001236 return bundle;
1237 }
1238
Leon Scroggins8ad29922010-02-16 12:33:55 -05001239 /* package */ void editUrl() {
Leon Scroggins68579392009-09-15 15:31:54 -04001240 if (mOptionsMenuOpen) closeOptionsMenu();
Leon Scroggins5bbe9802009-07-31 13:10:55 -04001241 String url = (getTopWindow() == null) ? null : getTopWindow().getUrl();
Grace Kloba83f47342009-07-20 10:44:31 -07001242 startSearch(mSettings.getHomePage().equals(url) ? null : url, true,
Leon Scroggins8ad29922010-02-16 12:33:55 -05001243 null, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001244 }
1245
Leon Scroggins8ad29922010-02-16 12:33:55 -05001246 /**
1247 * Overriding this to insert a local information bundle
1248 */
The Android Open Source Project0c908882009-03-03 19:32:16 -08001249 @Override
1250 public void startSearch(String initialQuery, boolean selectInitialQuery,
1251 Bundle appSearchData, boolean globalSearch) {
1252 if (appSearchData == null) {
1253 appSearchData = createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_TYPE);
1254 }
1255 super.startSearch(initialQuery, selectInitialQuery, appSearchData, globalSearch);
1256 }
1257
Leon Scroggins1f005d32009-08-10 17:36:42 -04001258 /**
1259 * Switch tabs. Called by the TitleBarSet when sliding the title bar
1260 * results in changing tabs.
Leon Scroggins160a7e72009-08-14 18:28:01 -04001261 * @param index Index of the tab to change to, as defined by
1262 * mTabControl.getTabIndex(Tab t).
1263 * @return boolean True if we successfully switched to a different tab. If
1264 * the indexth tab is null, or if that tab is the same as
1265 * the current one, return false.
Leon Scroggins1f005d32009-08-10 17:36:42 -04001266 */
Leon Scroggins160a7e72009-08-14 18:28:01 -04001267 /* package */ boolean switchToTab(int index) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001268 Tab tab = mTabControl.getTab(index);
1269 Tab currentTab = mTabControl.getCurrentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04001270 if (tab == null || tab == currentTab) {
Leon Scroggins160a7e72009-08-14 18:28:01 -04001271 return false;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001272 }
1273 if (currentTab != null) {
1274 // currentTab may be null if it was just removed. In that case,
1275 // we do not need to remove it
1276 removeTabFromContentView(currentTab);
1277 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001278 mTabControl.setCurrentTab(tab);
1279 attachTabToContentView(tab);
Grace Klobaeb6eef42009-09-15 17:56:32 -07001280 resetTitleIconAndProgress();
1281 updateLockIconToLatest();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001282 return true;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001283 }
1284
Grace Kloba22ac16e2009-10-07 18:00:23 -07001285 /* package */ Tab openTabToHomePage() {
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001286 return openTabAndShow(mSettings.getHomePage(), false, null);
1287 }
1288
Leon Scroggins1f005d32009-08-10 17:36:42 -04001289 /* package */ void closeCurrentWindow() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001290 final Tab current = mTabControl.getCurrentTab();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001291 if (mTabControl.getTabCount() == 1) {
Leon Scroggins30444232009-09-04 18:36:20 -04001292 // This is the last tab. Open a new one, with the home
1293 // page and close the current one.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001294 openTabToHomePage();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001295 closeTab(current);
Leon Scroggins160a7e72009-08-14 18:28:01 -04001296 return;
1297 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07001298 final Tab parent = current.getParentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04001299 int indexToShow = -1;
1300 if (parent != null) {
1301 indexToShow = mTabControl.getTabIndex(parent);
1302 } else {
Leon Scroggins160a7e72009-08-14 18:28:01 -04001303 final int currentIndex = mTabControl.getCurrentIndex();
1304 // Try to move to the tab to the right
1305 indexToShow = currentIndex + 1;
1306 if (indexToShow > mTabControl.getTabCount() - 1) {
1307 // Try to move to the tab to the left
1308 indexToShow = currentIndex - 1;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001309 }
1310 }
Leon Scroggins160a7e72009-08-14 18:28:01 -04001311 if (switchToTab(indexToShow)) {
1312 // Close window
1313 closeTab(current);
1314 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001315 }
1316
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001317 private ActiveTabsPage mActiveTabsPage;
1318
1319 /**
1320 * Remove the active tabs page.
1321 * @param needToAttach If true, the active tabs page did not attach a tab
1322 * to the content view, so we need to do that here.
1323 */
1324 /* package */ void removeActiveTabPage(boolean needToAttach) {
1325 mContentView.removeView(mActiveTabsPage);
Leon Scrogginsd746a942010-05-19 13:21:44 -04001326 mTitleBar.setVisibility(View.VISIBLE);
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001327 mActiveTabsPage = null;
1328 mMenuState = R.id.MAIN_MENU;
1329 if (needToAttach) {
1330 attachTabToContentView(mTabControl.getCurrentTab());
1331 }
1332 getTopWindow().requestFocus();
1333 }
1334
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04001335 @Override
1336 public ActionMode onStartActionMode(ActionMode.Callback callback) {
1337 ActionMode mode = super.onStartActionMode(callback);
1338 if (callback instanceof FindActionModeCallback
1339 || callback instanceof SelectActionModeCallback) {
1340 // For find and select, hide extra title bars. They will
1341 // be replaced in onEndActionMode.
1342 Tab tab = mTabControl.getCurrentTab();
1343 if (tab.getSubWebView() == null) {
1344 // If the find or select is being performed on the main webview,
1345 // remove the embedded title bar.
1346 WebView mainView = tab.getWebView();
1347 if (mainView != null) {
1348 mainView.setEmbeddedTitleBar(null);
1349 }
Cary Clark01cfcdd2010-06-04 16:36:45 -04001350 }
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04001351 hideFakeTitleBar();
1352 mActionMode = mode;
1353 } else {
1354 // Do not store other ActionModes, since we are unable to determine
1355 // when they finish.
1356 mActionMode = null;
Cary Clark01cfcdd2010-06-04 16:36:45 -04001357 }
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04001358 return mode;
Cary Clark01cfcdd2010-06-04 16:36:45 -04001359 }
1360
The Android Open Source Project0c908882009-03-03 19:32:16 -08001361 @Override
1362 public boolean onOptionsItemSelected(MenuItem item) {
Michael Kolbed217742010-08-10 17:52:34 -07001363 // check the action bar button before mCanChord check, as the prepare call
1364 // doesn't come for action bar buttons
1365 if (item.getItemId() == R.id.newtab) {
1366 bookmarksOrHistoryPicker(false, true);
1367 return true;
1368 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001369 if (!mCanChord) {
1370 // The user has already fired a shortcut with this hold down of the
1371 // menu key.
1372 return false;
1373 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001374 if (null == getTopWindow()) {
Leon Scroggins0d7ae0e2009-06-05 11:04:45 -04001375 return false;
1376 }
Grace Kloba6ee9c492009-07-13 10:04:34 -07001377 if (mMenuIsDown) {
1378 // The shortcut action consumes the MENU. Even if it is still down,
1379 // it won't trigger the next shortcut action. In the case of the
1380 // shortcut action triggering a new activity, like Bookmarks, we
1381 // won't get onKeyUp for MENU. So it is important to reset it here.
1382 mMenuIsDown = false;
1383 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001384 switch (item.getItemId()) {
1385 // -- Main menu
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001386 case R.id.new_tab_menu_id:
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001387 openTabToHomePage();
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001388 break;
1389
Michael Kolbae62fd42010-08-18 16:33:28 -07001390 case R.id.incognito_menu_id:
1391 openIncognitoTab();
1392 break;
1393
Leon Scroggins64b80f32009-08-07 12:03:34 -04001394 case R.id.goto_menu_id:
Leon Scroggins8ad29922010-02-16 12:33:55 -05001395 editUrl();
Leon Scrogginsb3a5bed2009-09-28 11:21:56 -04001396 break;
1397
1398 case R.id.bookmarks_menu_id:
Michael Kolb68792c82010-08-09 16:39:18 -07001399 bookmarksOrHistoryPicker(false, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001400 break;
1401
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001402 case R.id.active_tabs_menu_id:
1403 mActiveTabsPage = new ActiveTabsPage(this, mTabControl);
1404 removeTabFromContentView(mTabControl.getCurrentTab());
Leon Scrogginsd746a942010-05-19 13:21:44 -04001405 mTitleBar.setVisibility(View.GONE);
Leon Scroggins43de6162009-09-14 19:59:58 -04001406 hideFakeTitleBar();
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001407 mContentView.addView(mActiveTabsPage, COVER_SCREEN_PARAMS);
1408 mActiveTabsPage.requestFocus();
1409 mMenuState = EMPTY_MENU;
1410 break;
1411
Leon Scroggins1f005d32009-08-10 17:36:42 -04001412 case R.id.add_bookmark_menu_id:
Leon Scroggins571b3762010-05-26 10:25:01 -04001413 bookmarkCurrentPage();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001414 break;
1415
1416 case R.id.stop_reload_menu_id:
1417 if (mInLoad) {
1418 stopLoading();
1419 } else {
1420 getTopWindow().reload();
1421 }
1422 break;
1423
1424 case R.id.back_menu_id:
1425 getTopWindow().goBack();
1426 break;
1427
1428 case R.id.forward_menu_id:
1429 getTopWindow().goForward();
1430 break;
1431
1432 case R.id.close_menu_id:
1433 // Close the subwindow if it exists.
1434 if (mTabControl.getCurrentSubWindow() != null) {
1435 dismissSubWindow(mTabControl.getCurrentTab());
1436 break;
1437 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001438 closeCurrentWindow();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001439 break;
1440
1441 case R.id.homepage_menu_id:
Grace Kloba22ac16e2009-10-07 18:00:23 -07001442 Tab current = mTabControl.getCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001443 if (current != null) {
1444 dismissSubWindow(current);
Leon Scroggins92472e82010-02-17 16:32:28 -05001445 loadUrl(current.getWebView(), mSettings.getHomePage());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001446 }
1447 break;
1448
1449 case R.id.preferences_menu_id:
1450 Intent intent = new Intent(this,
1451 BrowserPreferencesPage.class);
Leon Scrogginsd5304942009-12-10 16:11:39 -05001452 intent.putExtra(BrowserPreferencesPage.CURRENT_PAGE,
1453 getTopWindow().getUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001454 startActivityForResult(intent, PREFERENCES_PAGE);
1455 break;
1456
1457 case R.id.find_menu_id:
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04001458 showFindDialog(null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001459 break;
1460
Elliott Slaughter0ced08c2010-06-30 11:40:42 -07001461 case R.id.save_webarchive_menu_id:
1462 if (LOGD_ENABLED) {
1463 Log.d(LOGTAG, "Save as Web Archive");
1464 }
1465 String directory = getExternalFilesDir(null).getAbsolutePath() + File.separator;
1466 getTopWindow().saveWebArchive(directory, true, new ValueCallback<String>() {
1467 @Override
1468 public void onReceiveValue(String value) {
1469 if (value != null) {
1470 Toast.makeText(BrowserActivity.this, R.string.webarchive_saved, Toast.LENGTH_SHORT).show();
1471 } else {
1472 Toast.makeText(BrowserActivity.this, R.string.webarchive_failed, Toast.LENGTH_SHORT).show();
1473 }
1474 }
1475 });
1476 break;
1477
The Android Open Source Project0c908882009-03-03 19:32:16 -08001478 case R.id.page_info_menu_id:
1479 showPageInfo(mTabControl.getCurrentTab(), false);
1480 break;
1481
1482 case R.id.classic_history_menu_id:
Michael Kolb68792c82010-08-09 16:39:18 -07001483 bookmarksOrHistoryPicker(true, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001484 break;
1485
Leon Scroggins96afcb12009-12-10 12:35:56 -05001486 case R.id.title_bar_share_page_url:
The Android Open Source Project0c908882009-03-03 19:32:16 -08001487 case R.id.share_page_menu_id:
Leon Scroggins96afcb12009-12-10 12:35:56 -05001488 Tab currentTab = mTabControl.getCurrentTab();
1489 if (null == currentTab) {
1490 mCanChord = false;
1491 return false;
1492 }
1493 currentTab.populatePickerData();
1494 sharePage(this, currentTab.getTitle(),
1495 currentTab.getUrl(), currentTab.getFavicon(),
Ben Murdoch87cc65d2010-06-29 20:34:10 +01001496 createScreenshot(currentTab.getWebView(), getDesiredThumbnailWidth(this),
1497 getDesiredThumbnailHeight(this)));
The Android Open Source Project0c908882009-03-03 19:32:16 -08001498 break;
1499
1500 case R.id.dump_nav_menu_id:
1501 getTopWindow().debugDump();
1502 break;
1503
Andrei Popescu7a8b88b2010-02-02 00:30:38 +00001504 case R.id.dump_counters_menu_id:
1505 getTopWindow().dumpV8Counters();
1506 break;
1507
The Android Open Source Project0c908882009-03-03 19:32:16 -08001508 case R.id.zoom_in_menu_id:
1509 getTopWindow().zoomIn();
1510 break;
1511
1512 case R.id.zoom_out_menu_id:
1513 getTopWindow().zoomOut();
1514 break;
1515
1516 case R.id.view_downloads_menu_id:
1517 viewDownloads(null);
1518 break;
1519
The Android Open Source Project0c908882009-03-03 19:32:16 -08001520 case R.id.window_one_menu_id:
1521 case R.id.window_two_menu_id:
1522 case R.id.window_three_menu_id:
1523 case R.id.window_four_menu_id:
1524 case R.id.window_five_menu_id:
1525 case R.id.window_six_menu_id:
1526 case R.id.window_seven_menu_id:
1527 case R.id.window_eight_menu_id:
1528 {
1529 int menuid = item.getItemId();
1530 for (int id = 0; id < WINDOW_SHORTCUT_ID_ARRAY.length; id++) {
1531 if (WINDOW_SHORTCUT_ID_ARRAY[id] == menuid) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001532 Tab desiredTab = mTabControl.getTab(id);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001533 if (desiredTab != null &&
1534 desiredTab != mTabControl.getCurrentTab()) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001535 switchToTab(id);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001536 }
1537 break;
1538 }
1539 }
1540 }
1541 break;
1542
1543 default:
1544 if (!super.onOptionsItemSelected(item)) {
1545 return false;
1546 }
1547 // Otherwise fall through.
1548 }
1549 mCanChord = false;
1550 return true;
1551 }
1552
Leon Scroggins571b3762010-05-26 10:25:01 -04001553 /* package */ void bookmarkCurrentPage() {
1554 Intent i = new Intent(BrowserActivity.this,
1555 AddBookmarkPage.class);
1556 WebView w = getTopWindow();
1557 i.putExtra("url", w.getUrl());
1558 i.putExtra("title", w.getTitle());
1559 i.putExtra("touch_icon_url", w.getTouchIconUrl());
Ben Murdoch87cc65d2010-06-29 20:34:10 +01001560 i.putExtra("thumbnail", createScreenshot(w, getDesiredThumbnailWidth(this),
1561 getDesiredThumbnailHeight(this)));
Ben Murdocheecb4e62010-07-06 16:30:38 +01001562 i.putExtra("url_editable", false);
Leon Scroggins571b3762010-05-26 10:25:01 -04001563 startActivity(i);
1564 }
1565
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04001566 /*
1567 * True if a custom ActionMode (i.e. find or select) is in use.
1568 */
1569 private boolean isInCustomActionMode() {
1570 return mActionMode != null;
Cary Clark01cfcdd2010-06-04 16:36:45 -04001571 }
1572
1573 /*
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04001574 * End the current ActionMode. Only works for find and select.
Cary Clark01cfcdd2010-06-04 16:36:45 -04001575 */
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04001576 void endActionMode() {
1577 if (mActionMode != null) {
1578 mActionMode.finish();
1579 }
1580 }
1581
1582 /*
1583 * Called by find and select when they are finished. Replace title bars
1584 * as necessary.
1585 */
1586 public void onEndActionMode() {
1587 if (!isInCustomActionMode()) return;
Michael Kolba2b2ba82010-08-04 17:54:03 -07001588 // If the Find was being performed in the main WebView, replace the
1589 // embedded title bar.
1590 Tab currentTab = mTabControl.getCurrentTab();
1591 if (currentTab.getSubWebView() == null) {
1592 WebView mainView = currentTab.getWebView();
1593 if (mainView != null) {
1594 mainView.setEmbeddedTitleBar(mTitleBar);
Leon Scroggins79e36d92010-04-29 16:01:46 +01001595 }
1596 }
Leon Scroggins79e36d92010-04-29 16:01:46 +01001597 if (mInLoad) {
1598 // The title bar was hidden, because otherwise it would cover up the
Michael Kolba2b2ba82010-08-04 17:54:03 -07001599 // find or select dialog. Now that the dialog has been removed,
Cary Clark01cfcdd2010-06-04 16:36:45 -04001600 // show the fake title bar once again.
Leon Scroggins79e36d92010-04-29 16:01:46 +01001601 showFakeTitleBar();
1602 }
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04001603 mActionMode = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001604 }
1605
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04001606 private FindActionModeCallback mFindCallback;
1607 private SelectActionModeCallback mSelectCallback;
1608
1609 // For select and find, we keep track of the ActionMode so that
1610 // finish() can be called as desired.
1611 private ActionMode mActionMode;
1612
1613 /*
1614 * Open the find ActionMode.
1615 * @param text If non null, will be placed in find to be searched for.
1616 */
1617 public void showFindDialog(String text) {
1618 if (null == mFindCallback) {
1619 mFindCallback = new FindActionModeCallback(this);
Cary Clark01cfcdd2010-06-04 16:36:45 -04001620 }
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04001621 WebView webView = getTopWindow();
1622 webView.setFindIsUp(true);
1623 mFindCallback.setWebView(webView);
1624 startActionMode(mFindCallback);
1625 if (text != null) mFindCallback.setText(text);
Cary Clark01cfcdd2010-06-04 16:36:45 -04001626 }
1627
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04001628 /*
1629 * Show the select ActionMode.
1630 */
Cary Clark01cfcdd2010-06-04 16:36:45 -04001631 public void showSelectDialog() {
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04001632 if (null == mSelectCallback) {
1633 mSelectCallback = new SelectActionModeCallback(this);
Cary Clark01cfcdd2010-06-04 16:36:45 -04001634 }
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04001635 WebView webView = getTopWindow();
1636 webView.setUpSelect();
1637 mSelectCallback.setWebView(webView);
1638 startActionMode(mSelectCallback);
Cary Clark01cfcdd2010-06-04 16:36:45 -04001639 }
1640
Grace Kloba22ac16e2009-10-07 18:00:23 -07001641 @Override
1642 public boolean onPrepareOptionsMenu(Menu menu) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001643 // This happens when the user begins to hold down the menu key, so
1644 // allow them to chord to get a shortcut.
1645 mCanChord = true;
1646 // Note: setVisible will decide whether an item is visible; while
1647 // setEnabled() will decide whether an item is enabled, which also means
1648 // whether the matching shortcut key will function.
1649 super.onPrepareOptionsMenu(menu);
1650 switch (mMenuState) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001651 case EMPTY_MENU:
1652 if (mCurrentMenuState != mMenuState) {
1653 menu.setGroupVisible(R.id.MAIN_MENU, false);
1654 menu.setGroupEnabled(R.id.MAIN_MENU, false);
1655 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001656 }
1657 break;
1658 default:
1659 if (mCurrentMenuState != mMenuState) {
1660 menu.setGroupVisible(R.id.MAIN_MENU, true);
1661 menu.setGroupEnabled(R.id.MAIN_MENU, true);
1662 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001663 }
1664 final WebView w = getTopWindow();
1665 boolean canGoBack = false;
1666 boolean canGoForward = false;
1667 boolean isHome = false;
1668 if (w != null) {
1669 canGoBack = w.canGoBack();
1670 canGoForward = w.canGoForward();
1671 isHome = mSettings.getHomePage().equals(w.getUrl());
1672 }
1673 final MenuItem back = menu.findItem(R.id.back_menu_id);
1674 back.setEnabled(canGoBack);
1675
1676 final MenuItem home = menu.findItem(R.id.homepage_menu_id);
1677 home.setEnabled(!isHome);
1678
Michael Kolbe0a36662010-06-29 10:37:12 -07001679 final MenuItem forward = menu.findItem(R.id.forward_menu_id);
1680 forward.setEnabled(canGoForward);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001681
Michael Kolbed217742010-08-10 17:52:34 -07001682 if (!mXLargeScreenSize) {
1683 final MenuItem newtab = menu.findItem(R.id.new_tab_menu_id);
1684 newtab.setEnabled(mTabControl.canCreateNewTab());
1685 }
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001686
The Android Open Source Project0c908882009-03-03 19:32:16 -08001687 // decide whether to show the share link option
1688 PackageManager pm = getPackageManager();
1689 Intent send = new Intent(Intent.ACTION_SEND);
1690 send.setType("text/plain");
1691 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1692 menu.findItem(R.id.share_page_menu_id).setVisible(ri != null);
1693
The Android Open Source Project0c908882009-03-03 19:32:16 -08001694 boolean isNavDump = mSettings.isNavDump();
1695 final MenuItem nav = menu.findItem(R.id.dump_nav_menu_id);
1696 nav.setVisible(isNavDump);
1697 nav.setEnabled(isNavDump);
Andrei Popescu7a8b88b2010-02-02 00:30:38 +00001698
1699 boolean showDebugSettings = mSettings.showDebugSettings();
1700 final MenuItem counter = menu.findItem(R.id.dump_counters_menu_id);
1701 counter.setVisible(showDebugSettings);
1702 counter.setEnabled(showDebugSettings);
1703
The Android Open Source Project0c908882009-03-03 19:32:16 -08001704 break;
1705 }
1706 mCurrentMenuState = mMenuState;
1707 return true;
1708 }
1709
1710 @Override
1711 public void onCreateContextMenu(ContextMenu menu, View v,
1712 ContextMenuInfo menuInfo) {
Leon Scroggins571b3762010-05-26 10:25:01 -04001713 if (v instanceof TitleBarBase) {
Leon Scroggins4e9f89b2010-02-22 16:54:14 -05001714 return;
1715 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001716 WebView webview = (WebView) v;
1717 WebView.HitTestResult result = webview.getHitTestResult();
1718 if (result == null) {
1719 return;
1720 }
1721
1722 int type = result.getType();
1723 if (type == WebView.HitTestResult.UNKNOWN_TYPE) {
1724 Log.w(LOGTAG,
1725 "We should not show context menu when nothing is touched");
1726 return;
1727 }
1728 if (type == WebView.HitTestResult.EDIT_TEXT_TYPE) {
1729 // let TextView handles context menu
1730 return;
1731 }
1732
1733 // Note, http://b/issue?id=1106666 is requesting that
1734 // an inflated menu can be used again. This is not available
1735 // yet, so inflate each time (yuk!)
1736 MenuInflater inflater = getMenuInflater();
1737 inflater.inflate(R.menu.browsercontext, menu);
1738
1739 // Show the correct menu group
Leon Scroggins III9e997c72010-05-26 13:25:16 -04001740 final String extra = result.getExtra();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001741 menu.setGroupVisible(R.id.PHONE_MENU,
1742 type == WebView.HitTestResult.PHONE_TYPE);
1743 menu.setGroupVisible(R.id.EMAIL_MENU,
1744 type == WebView.HitTestResult.EMAIL_TYPE);
1745 menu.setGroupVisible(R.id.GEO_MENU,
1746 type == WebView.HitTestResult.GEO_TYPE);
1747 menu.setGroupVisible(R.id.IMAGE_MENU,
1748 type == WebView.HitTestResult.IMAGE_TYPE
1749 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1750 menu.setGroupVisible(R.id.ANCHOR_MENU,
1751 type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1752 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1753
1754 // Setup custom handling depending on the type
1755 switch (type) {
1756 case WebView.HitTestResult.PHONE_TYPE:
1757 menu.setHeaderTitle(Uri.decode(extra));
1758 menu.findItem(R.id.dial_context_menu_id).setIntent(
1759 new Intent(Intent.ACTION_VIEW, Uri
1760 .parse(WebView.SCHEME_TEL + extra)));
1761 Intent addIntent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
1762 addIntent.putExtra(Insert.PHONE, Uri.decode(extra));
Cary Clark5e335a32009-09-22 14:53:11 -04001763 addIntent.setType(ContactsContract.Contacts.CONTENT_ITEM_TYPE);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001764 menu.findItem(R.id.add_contact_context_menu_id).setIntent(
1765 addIntent);
1766 menu.findItem(R.id.copy_phone_context_menu_id).setOnMenuItemClickListener(
1767 new Copy(extra));
1768 break;
1769
1770 case WebView.HitTestResult.EMAIL_TYPE:
1771 menu.setHeaderTitle(extra);
1772 menu.findItem(R.id.email_context_menu_id).setIntent(
1773 new Intent(Intent.ACTION_VIEW, Uri
1774 .parse(WebView.SCHEME_MAILTO + extra)));
1775 menu.findItem(R.id.copy_mail_context_menu_id).setOnMenuItemClickListener(
1776 new Copy(extra));
1777 break;
1778
1779 case WebView.HitTestResult.GEO_TYPE:
1780 menu.setHeaderTitle(extra);
1781 menu.findItem(R.id.map_context_menu_id).setIntent(
1782 new Intent(Intent.ACTION_VIEW, Uri
1783 .parse(WebView.SCHEME_GEO
1784 + URLEncoder.encode(extra))));
1785 menu.findItem(R.id.copy_geo_context_menu_id).setOnMenuItemClickListener(
1786 new Copy(extra));
1787 break;
1788
1789 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1790 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
1791 TextView titleView = (TextView) LayoutInflater.from(this)
1792 .inflate(android.R.layout.browser_link_context_header,
1793 null);
1794 titleView.setText(extra);
1795 menu.setHeaderView(titleView);
1796 // decide whether to show the open link in new tab option
Leon Scroggins III9e997c72010-05-26 13:25:16 -04001797 boolean showNewTab = mTabControl.canCreateNewTab();
1798 MenuItem newTabItem
1799 = menu.findItem(R.id.open_newtab_context_menu_id);
1800 newTabItem.setVisible(showNewTab);
1801 if (showNewTab) {
1802 newTabItem.setOnMenuItemClickListener(
1803 new MenuItem.OnMenuItemClickListener() {
1804 public boolean onMenuItemClick(MenuItem item) {
1805 final Tab parent = mTabControl.getCurrentTab();
Michael Kolb68792c82010-08-09 16:39:18 -07001806 final Tab newTab = openTab(extra, false);
Leon Scroggins III9e997c72010-05-26 13:25:16 -04001807 if (newTab != parent) {
1808 parent.addChildTab(newTab);
1809 }
1810 return true;
1811 }
1812 });
1813 }
Ben Murdochde353622009-10-12 10:29:00 +01001814 menu.findItem(R.id.bookmark_context_menu_id).setVisible(
1815 Bookmarks.urlHasAcceptableScheme(extra));
The Android Open Source Project0c908882009-03-03 19:32:16 -08001816 PackageManager pm = getPackageManager();
1817 Intent send = new Intent(Intent.ACTION_SEND);
1818 send.setType("text/plain");
1819 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1820 menu.findItem(R.id.share_link_context_menu_id).setVisible(ri != null);
1821 if (type == WebView.HitTestResult.SRC_ANCHOR_TYPE) {
1822 break;
1823 }
1824 // otherwise fall through to handle image part
1825 case WebView.HitTestResult.IMAGE_TYPE:
1826 if (type == WebView.HitTestResult.IMAGE_TYPE) {
1827 menu.setHeaderTitle(extra);
1828 }
1829 menu.findItem(R.id.view_image_context_menu_id).setIntent(
1830 new Intent(Intent.ACTION_VIEW, Uri.parse(extra)));
1831 menu.findItem(R.id.download_context_menu_id).
1832 setOnMenuItemClickListener(new Download(extra));
Ben Murdoch4f75ba22009-10-27 11:48:28 +00001833 menu.findItem(R.id.set_wallpaper_context_menu_id).
1834 setOnMenuItemClickListener(new SetAsWallpaper(extra));
The Android Open Source Project0c908882009-03-03 19:32:16 -08001835 break;
1836
1837 default:
1838 Log.w(LOGTAG, "We should not get here.");
1839 break;
1840 }
Leon Scrogginsb2b19f52009-10-09 16:10:00 -04001841 hideFakeTitleBar();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001842 }
1843
The Android Open Source Project0c908882009-03-03 19:32:16 -08001844 // Attach the given tab to the content view.
Grace Klobac928c302009-09-17 11:51:21 -07001845 // this should only be called for the current tab.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001846 private void attachTabToContentView(Tab t) {
Steve Block2bc69912009-07-30 14:45:13 +01001847 // Attach the container that contains the main WebView and any other UI
1848 // associated with the tab.
Patrick Scottd0119532009-09-17 08:00:31 -04001849 t.attachTabToContentView(mContentView);
Ben Murdochbff2d602009-07-01 20:19:05 +01001850
1851 if (mShouldShowErrorConsole) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001852 ErrorConsoleView errorConsole = t.getErrorConsole(true);
Ben Murdochbff2d602009-07-01 20:19:05 +01001853 if (errorConsole.numberOfErrors() == 0) {
1854 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
1855 } else {
1856 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
1857 }
1858
1859 mErrorConsoleContainer.addView(errorConsole,
Romain Guy15b8ec62010-01-08 15:06:43 -08001860 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
Ben Murdochbff2d602009-07-01 20:19:05 +01001861 ViewGroup.LayoutParams.WRAP_CONTENT));
1862 }
1863
Michael Kolba2b2ba82010-08-04 17:54:03 -07001864 WebView view = t.getWebView();
1865 view.setEmbeddedTitleBar(mTitleBar);
Leon Scroggins58d56c62010-01-28 15:12:40 -05001866 if (t.isInVoiceSearchMode()) {
1867 showVoiceTitleBar(t.getVoiceDisplayTitle());
1868 } else {
1869 revertVoiceTitleBar();
1870 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001871 // Request focus on the top window.
1872 t.getTopWindow().requestFocus();
Michael Kolba2b2ba82010-08-04 17:54:03 -07001873 if (mTabControl.getTabChangeListener() != null) {
1874 mTabControl.getTabChangeListener().onCurrentTab(t);
1875 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001876 }
1877
1878 // Attach a sub window to the main WebView of the given tab.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001879 void attachSubWindow(Tab t) {
Patrick Scottd0119532009-09-17 08:00:31 -04001880 t.attachSubWindow(mContentView);
1881 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001882 }
1883
1884 // Remove the given tab from the content view.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001885 private void removeTabFromContentView(Tab t) {
Steve Block2bc69912009-07-30 14:45:13 +01001886 // Remove the container that contains the main WebView.
Patrick Scottd0119532009-09-17 08:00:31 -04001887 t.removeTabFromContentView(mContentView);
Ben Murdochbff2d602009-07-01 20:19:05 +01001888
Grace Kloba22ac16e2009-10-07 18:00:23 -07001889 ErrorConsoleView errorConsole = t.getErrorConsole(false);
1890 if (errorConsole != null) {
1891 mErrorConsoleContainer.removeView(errorConsole);
Ben Murdochbff2d602009-07-01 20:19:05 +01001892 }
1893
Michael Kolba2b2ba82010-08-04 17:54:03 -07001894 WebView view = t.getWebView();
1895 if (view != null) {
1896 view.setEmbeddedTitleBar(null);
Leon Scrogginsbb85b902009-09-14 19:27:20 -04001897 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001898 }
1899
1900 // Remove the sub window if it exists. Also called by TabControl when the
1901 // user clicks the 'X' to dismiss a sub window.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001902 /* package */ void dismissSubWindow(Tab t) {
Patrick Scottd0119532009-09-17 08:00:31 -04001903 t.removeSubWindow(mContentView);
Grace Kloba22ac16e2009-10-07 18:00:23 -07001904 // dismiss the subwindow. This will destroy the WebView.
1905 t.dismissSubWindow();
Patrick Scottd0119532009-09-17 08:00:31 -04001906 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001907 }
1908
Leon Scroggins1f005d32009-08-10 17:36:42 -04001909 // A wrapper function of {@link #openTabAndShow(UrlData, boolean, String)}
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07001910 // that accepts url as string.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001911 private Tab openTabAndShow(String url, boolean closeOnExit, String appId) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001912 return openTabAndShow(new UrlData(url), closeOnExit, appId);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001913 }
1914
1915 // This method does a ton of stuff. It will attempt to create a new tab
1916 // if we haven't reached MAX_TABS. Otherwise it uses the current tab. If
Leon Scroggins1f005d32009-08-10 17:36:42 -04001917 // url isn't null, it will load the given url.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001918 /* package */Tab openTabAndShow(UrlData urlData, boolean closeOnExit,
1919 String appId) {
1920 final Tab currentTab = mTabControl.getCurrentTab();
1921 if (mTabControl.canCreateNewTab()) {
1922 final Tab tab = mTabControl.createNewTab(closeOnExit, appId,
Elliott Slaughterf0f03952010-07-14 18:10:36 -07001923 urlData.mUrl, false);
Leon Scroggins1f005d32009-08-10 17:36:42 -04001924 WebView webview = tab.getWebView();
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001925 // If the last tab was removed from the active tabs page, currentTab
1926 // will be null.
1927 if (currentTab != null) {
1928 removeTabFromContentView(currentTab);
1929 }
Patrick Scott8bbd69f2009-08-14 13:35:53 -04001930 // We must set the new tab as the current tab to reflect the old
1931 // animation behavior.
1932 mTabControl.setCurrentTab(tab);
Grace Klobaeb6eef42009-09-15 17:56:32 -07001933 attachTabToContentView(tab);
Leon Scroggins160a7e72009-08-14 18:28:01 -04001934 if (!urlData.isEmpty()) {
Patrick Scott9d53da02010-02-19 10:19:01 -05001935 loadUrlDataIn(tab, urlData);
Leon Scroggins1f005d32009-08-10 17:36:42 -04001936 }
1937 return tab;
1938 } else {
1939 // Get rid of the subwindow if it exists
1940 dismissSubWindow(currentTab);
1941 if (!urlData.isEmpty()) {
1942 // Load the given url.
Patrick Scott9d53da02010-02-19 10:19:01 -05001943 loadUrlDataIn(currentTab, urlData);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001944 }
Leon Scroggins58d56c62010-01-28 15:12:40 -05001945 return currentTab;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001946 }
1947 }
1948
Michael Kolb68792c82010-08-09 16:39:18 -07001949 private Tab openTab(String url, boolean forceForeground) {
1950 if (mSettings.openInBackground() && !forceForeground) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001951 Tab t = mTabControl.createNewTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001952 if (t != null) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001953 WebView view = t.getWebView();
Leon Scroggins92472e82010-02-17 16:32:28 -05001954 loadUrl(view, url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001955 }
Grace Klobac9181842009-04-14 08:53:22 -07001956 return t;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001957 } else {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001958 return openTabAndShow(url, false, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001959 }
1960 }
1961
Elliott Slaughterf0f03952010-07-14 18:10:36 -07001962 /* package */ Tab openIncognitoTab() {
1963 if (mTabControl.canCreateNewTab()) {
1964 Tab currentTab = mTabControl.getCurrentTab();
1965 Tab tab = mTabControl.createNewTab(false, null, null, true);
1966 if (currentTab != null) {
1967 removeTabFromContentView(currentTab);
1968 }
1969 mTabControl.setCurrentTab(tab);
1970 attachTabToContentView(tab);
1971 return tab;
1972 }
1973 return null;
1974 }
1975
The Android Open Source Project0c908882009-03-03 19:32:16 -08001976 private class Copy implements OnMenuItemClickListener {
1977 private CharSequence mText;
1978
1979 public boolean onMenuItemClick(MenuItem item) {
1980 copy(mText);
1981 return true;
1982 }
1983
1984 public Copy(CharSequence toCopy) {
1985 mText = toCopy;
1986 }
1987 }
1988
1989 private class Download implements OnMenuItemClickListener {
1990 private String mText;
1991
1992 public boolean onMenuItemClick(MenuItem item) {
1993 onDownloadStartNoStream(mText, null, null, null, -1);
1994 return true;
1995 }
1996
1997 public Download(String toDownload) {
1998 mText = toDownload;
1999 }
2000 }
2001
Ben Murdoch4f75ba22009-10-27 11:48:28 +00002002 private class SetAsWallpaper extends Thread implements
2003 OnMenuItemClickListener, DialogInterface.OnCancelListener {
2004 private URL mUrl;
2005 private ProgressDialog mWallpaperProgress;
2006 private boolean mCanceled = false;
2007
2008 public SetAsWallpaper(String url) {
2009 try {
2010 mUrl = new URL(url);
2011 } catch (MalformedURLException e) {
2012 mUrl = null;
2013 }
2014 }
2015
2016 public void onCancel(DialogInterface dialog) {
2017 mCanceled = true;
2018 }
2019
2020 public boolean onMenuItemClick(MenuItem item) {
2021 if (mUrl != null) {
2022 // The user may have tried to set a image with a large file size as their
2023 // background so it may take a few moments to perform the operation. Display
2024 // a progress spinner while it is working.
2025 mWallpaperProgress = new ProgressDialog(BrowserActivity.this);
2026 mWallpaperProgress.setIndeterminate(true);
2027 mWallpaperProgress.setMessage(getText(R.string.progress_dialog_setting_wallpaper));
2028 mWallpaperProgress.setCancelable(true);
2029 mWallpaperProgress.setOnCancelListener(this);
2030 mWallpaperProgress.show();
2031 start();
2032 }
2033 return true;
2034 }
2035
Michael Kolbe0a36662010-06-29 10:37:12 -07002036 @Override
Ben Murdoch4f75ba22009-10-27 11:48:28 +00002037 public void run() {
2038 Drawable oldWallpaper = BrowserActivity.this.getWallpaper();
2039 try {
2040 // TODO: This will cause the resource to be downloaded again, when we
2041 // should in most cases be able to grab it from the cache. To fix this
2042 // we should query WebCore to see if we can access a cached version and
2043 // instead open an input stream on that. This pattern could also be used
2044 // in the download manager where the same problem exists.
2045 InputStream inputstream = mUrl.openStream();
2046 if (inputstream != null) {
2047 setWallpaper(inputstream);
2048 }
2049 } catch (IOException e) {
2050 Log.e(LOGTAG, "Unable to set new wallpaper");
2051 // Act as though the user canceled the operation so we try to
2052 // restore the old wallpaper.
2053 mCanceled = true;
2054 }
2055
2056 if (mCanceled) {
2057 // Restore the old wallpaper if the user cancelled whilst we were setting
2058 // the new wallpaper.
2059 int width = oldWallpaper.getIntrinsicWidth();
2060 int height = oldWallpaper.getIntrinsicHeight();
2061 Bitmap bm = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
2062 Canvas canvas = new Canvas(bm);
2063 oldWallpaper.setBounds(0, 0, width, height);
2064 oldWallpaper.draw(canvas);
2065 try {
2066 setWallpaper(bm);
2067 } catch (IOException e) {
2068 Log.e(LOGTAG, "Unable to restore old wallpaper.");
2069 }
2070 mCanceled = false;
2071 }
2072
2073 if (mWallpaperProgress.isShowing()) {
2074 mWallpaperProgress.dismiss();
2075 }
2076 }
2077 }
2078
The Android Open Source Project0c908882009-03-03 19:32:16 -08002079 private void copy(CharSequence text) {
Dianne Hackborn80f32622010-08-05 14:17:53 -07002080 ClipboardManager cm = (ClipboardManager)getSystemService(Context.CLIPBOARD_SERVICE);
2081 cm.setText(text);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002082 }
2083
2084 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08002085 * Resets the browser title-view to whatever it must be
2086 * (for example, if we had a loading error)
2087 * When we have a new page, we call resetTitle, when we
2088 * have to reset the titlebar to whatever it used to be
2089 * (for example, if the user chose to stop loading), we
2090 * call resetTitleAndRevertLockIcon.
2091 */
2092 /* package */ void resetTitleAndRevertLockIcon() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002093 mTabControl.getCurrentTab().revertLockIcon();
2094 updateLockIconToLatest();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002095 resetTitleIconAndProgress();
2096 }
2097
2098 /**
2099 * Reset the title, favicon, and progress.
2100 */
2101 private void resetTitleIconAndProgress() {
2102 WebView current = mTabControl.getCurrentWebView();
2103 if (current == null) {
2104 return;
2105 }
2106 resetTitleAndIcon(current);
2107 int progress = current.getProgress();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002108 current.getWebChromeClient().onProgressChanged(current, progress);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002109 }
2110
2111 // Reset the title and the icon based on the given item.
2112 private void resetTitleAndIcon(WebView view) {
2113 WebHistoryItem item = view.copyBackForwardList().getCurrentItem();
2114 if (item != null) {
Leon Scroggins68579392009-09-15 15:31:54 -04002115 setUrlTitle(item.getUrl(), item.getTitle());
The Android Open Source Project0c908882009-03-03 19:32:16 -08002116 setFavicon(item.getFavicon());
2117 } else {
Leon Scroggins68579392009-09-15 15:31:54 -04002118 setUrlTitle(null, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002119 setFavicon(null);
2120 }
2121 }
2122
2123 /**
2124 * Sets a title composed of the URL and the title string.
2125 * @param url The URL of the site being loaded.
2126 * @param title The title of the site being loaded.
2127 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07002128 void setUrlTitle(String url, String title) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002129 mUrl = url;
2130 mTitle = title;
2131
Leon Scroggins58d56c62010-01-28 15:12:40 -05002132 // If we are in voice search mode, the title has already been set.
2133 if (mTabControl.getCurrentTab().isInVoiceSearchMode()) return;
2134 mTitleBar.setDisplayTitle(url);
Michael Kolba2b2ba82010-08-04 17:54:03 -07002135 mFakeTitleBar.setDisplayTitle(url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002136 }
2137
2138 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08002139 * @param url The URL to build a title version of the URL from.
2140 * @return The title version of the URL or null if fails.
2141 * The title version of the URL can be either the URL hostname,
2142 * or the hostname with an "https://" prefix (for secure URLs),
2143 * or an empty string if, for example, the URL in question is a
2144 * file:// URL with no hostname.
2145 */
Leon Scroggins32e14a62009-06-11 10:26:34 -04002146 /* package */ static String buildTitleUrl(String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002147 String titleUrl = null;
2148
2149 if (url != null) {
2150 try {
2151 // parse the url string
2152 URL urlObj = new URL(url);
2153 if (urlObj != null) {
2154 titleUrl = "";
2155
2156 String protocol = urlObj.getProtocol();
2157 String host = urlObj.getHost();
2158
2159 if (host != null && 0 < host.length()) {
2160 titleUrl = host;
2161 if (protocol != null) {
2162 // if a secure site, add an "https://" prefix!
2163 if (protocol.equalsIgnoreCase("https")) {
2164 titleUrl = protocol + "://" + host;
2165 }
2166 }
2167 }
2168 }
2169 } catch (MalformedURLException e) {}
2170 }
2171
2172 return titleUrl;
2173 }
2174
2175 // Set the favicon in the title bar.
Grace Kloba22ac16e2009-10-07 18:00:23 -07002176 void setFavicon(Bitmap icon) {
Leon Scroggins68579392009-09-15 15:31:54 -04002177 mTitleBar.setFavicon(icon);
Michael Kolba2b2ba82010-08-04 17:54:03 -07002178 mFakeTitleBar.setFavicon(icon);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002179 }
2180
2181 /**
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002182 * Close the tab, remove its associated title bar, and adjust mTabControl's
2183 * current tab to a valid value.
Leon Scroggins1f005d32009-08-10 17:36:42 -04002184 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07002185 /* package */ void closeTab(Tab t) {
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002186 int currentIndex = mTabControl.getCurrentIndex();
2187 int removeIndex = mTabControl.getTabIndex(t);
Leon Scroggins1f005d32009-08-10 17:36:42 -04002188 mTabControl.removeTab(t);
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002189 if (currentIndex >= removeIndex && currentIndex != 0) {
2190 currentIndex--;
2191 }
2192 mTabControl.setCurrentTab(mTabControl.getTab(currentIndex));
Andrei Popescua5bf1de2009-09-23 16:39:23 +01002193 resetTitleIconAndProgress();
Leon Scroggins654899b2010-06-25 16:25:23 -04002194 updateLockIconToLatest();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002195 }
2196
Leon Scrogginsdcc5eeb2010-02-23 17:26:37 -05002197 /* package */ void goBackOnePageOrQuit() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002198 Tab current = mTabControl.getCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002199 if (current == null) {
2200 /*
2201 * Instead of finishing the activity, simply push this to the back
2202 * of the stack and let ActivityManager to choose the foreground
2203 * activity. As BrowserActivity is singleTask, it will be always the
2204 * root of the task. So we can use either true or false for
2205 * moveTaskToBack().
2206 */
2207 moveTaskToBack(true);
Grace Kloba00d85e72009-09-23 18:50:05 -07002208 return;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002209 }
2210 WebView w = current.getWebView();
2211 if (w.canGoBack()) {
2212 w.goBack();
2213 } else {
2214 // Check to see if we are closing a window that was created by
2215 // another window. If so, we switch back to that window.
Grace Kloba22ac16e2009-10-07 18:00:23 -07002216 Tab parent = current.getParentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002217 if (parent != null) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04002218 switchToTab(mTabControl.getTabIndex(parent));
2219 // Now we close the other tab
2220 closeTab(current);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002221 } else {
2222 if (current.closeOnExit()) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002223 // force the tab's inLoad() to be false as we are going to
2224 // either finish the activity or remove the tab. This will
2225 // ensure pauseWebViewTimers() taking action.
2226 mTabControl.getCurrentTab().clearInLoad();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002227 if (mTabControl.getTabCount() == 1) {
2228 finish();
2229 return;
2230 }
Mike Reed7bfa63b2009-05-28 11:08:32 -04002231 // call pauseWebViewTimers() now, we won't be able to call
2232 // it in onPause() as the WebView won't be valid.
Grace Klobaec1b5ad2009-08-18 08:42:32 -07002233 // Temporarily change mActivityInPause to be true as
2234 // pauseWebViewTimers() will do nothing if mActivityInPause
2235 // is false.
Grace Kloba918e1d72009-08-13 14:55:06 -07002236 boolean savedState = mActivityInPause;
2237 if (savedState) {
Grace Klobaec1b5ad2009-08-18 08:42:32 -07002238 Log.e(LOGTAG, "BrowserActivity is already paused "
2239 + "while handing goBackOnePageOrQuit.");
Grace Kloba918e1d72009-08-13 14:55:06 -07002240 }
2241 mActivityInPause = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -04002242 pauseWebViewTimers();
Grace Kloba918e1d72009-08-13 14:55:06 -07002243 mActivityInPause = savedState;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002244 removeTabFromContentView(current);
2245 mTabControl.removeTab(current);
2246 }
2247 /*
2248 * Instead of finishing the activity, simply push this to the back
2249 * of the stack and let ActivityManager to choose the foreground
2250 * activity. As BrowserActivity is singleTask, it will be always the
2251 * root of the task. So we can use either true or false for
2252 * moveTaskToBack().
2253 */
2254 moveTaskToBack(true);
2255 }
2256 }
2257 }
2258
Grace Kloba22ac16e2009-10-07 18:00:23 -07002259 boolean isMenuDown() {
2260 return mMenuIsDown;
2261 }
2262
Grace Kloba5942df02009-09-18 11:48:29 -07002263 @Override
2264 public boolean onKeyDown(int keyCode, KeyEvent event) {
Leon Scrogginsf65b50d2009-12-08 10:44:28 -05002265 // Even if MENU is already held down, we need to call to super to open
2266 // the IME on long press.
2267 if (KeyEvent.KEYCODE_MENU == keyCode) {
2268 mMenuIsDown = true;
2269 return super.onKeyDown(keyCode, event);
2270 }
Grace Kloba5942df02009-09-18 11:48:29 -07002271 // The default key mode is DEFAULT_KEYS_SEARCH_LOCAL. As the MENU is
2272 // still down, we don't want to trigger the search. Pretend to consume
2273 // the key and do nothing.
2274 if (mMenuIsDown) return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002275
Grace Kloba5942df02009-09-18 11:48:29 -07002276 switch(keyCode) {
Grace Kloba5942df02009-09-18 11:48:29 -07002277 case KeyEvent.KEYCODE_SPACE:
Grace Klobada0fe552009-09-22 18:17:24 -07002278 // WebView/WebTextView handle the keys in the KeyDown. As
2279 // the Activity's shortcut keys are only handled when WebView
2280 // doesn't, have to do it in onKeyDown instead of onKeyUp.
2281 if (event.isShiftPressed()) {
2282 getTopWindow().pageUp(false);
2283 } else {
2284 getTopWindow().pageDown(false);
2285 }
Grace Kloba5942df02009-09-18 11:48:29 -07002286 return true;
2287 case KeyEvent.KEYCODE_BACK:
2288 if (event.getRepeatCount() == 0) {
2289 event.startTracking();
2290 return true;
2291 } else if (mCustomView == null && mActiveTabsPage == null
2292 && event.isLongPress()) {
Michael Kolb68792c82010-08-09 16:39:18 -07002293 bookmarksOrHistoryPicker(true, false);
Grace Kloba5942df02009-09-18 11:48:29 -07002294 return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002295 }
Grace Kloba5942df02009-09-18 11:48:29 -07002296 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002297 }
Grace Kloba5942df02009-09-18 11:48:29 -07002298 return super.onKeyDown(keyCode, event);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002299 }
2300
Grace Kloba5942df02009-09-18 11:48:29 -07002301 @Override
2302 public boolean onKeyUp(int keyCode, KeyEvent event) {
2303 switch(keyCode) {
2304 case KeyEvent.KEYCODE_MENU:
2305 mMenuIsDown = false;
2306 break;
Grace Kloba5942df02009-09-18 11:48:29 -07002307 case KeyEvent.KEYCODE_BACK:
2308 if (event.isTracking() && !event.isCanceled()) {
2309 if (mCustomView != null) {
2310 // if a custom view is showing, hide it
Grace Kloba22ac16e2009-10-07 18:00:23 -07002311 mTabControl.getCurrentWebView().getWebChromeClient()
2312 .onHideCustomView();
Grace Kloba5942df02009-09-18 11:48:29 -07002313 } else if (mActiveTabsPage != null) {
2314 // if tab page is showing, hide it
2315 removeActiveTabPage(true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002316 } else {
Grace Kloba5942df02009-09-18 11:48:29 -07002317 WebView subwindow = mTabControl.getCurrentSubWindow();
2318 if (subwindow != null) {
2319 if (subwindow.canGoBack()) {
2320 subwindow.goBack();
2321 } else {
2322 dismissSubWindow(mTabControl.getCurrentTab());
2323 }
2324 } else {
2325 goBackOnePageOrQuit();
2326 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002327 }
Grace Kloba5942df02009-09-18 11:48:29 -07002328 return true;
2329 }
2330 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002331 }
Grace Kloba5942df02009-09-18 11:48:29 -07002332 return super.onKeyUp(keyCode, event);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002333 }
2334
Leon Scroggins68579392009-09-15 15:31:54 -04002335 /* package */ void stopLoading() {
Ben Murdochb7cc8b42009-09-28 10:59:09 +01002336 mDidStopLoad = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002337 resetTitleAndRevertLockIcon();
2338 WebView w = getTopWindow();
2339 w.stopLoading();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002340 // FIXME: before refactor, it is using mWebViewClient. So I keep the
2341 // same logic here. But for subwindow case, should we call into the main
2342 // WebView's onPageFinished as we never call its onPageStarted and if
2343 // the page finishes itself, we don't call onPageFinished.
2344 mTabControl.getCurrentWebView().getWebViewClient().onPageFinished(w,
2345 w.getUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08002346
2347 cancelStopToast();
2348 mStopToast = Toast
2349 .makeText(this, R.string.stopping, Toast.LENGTH_SHORT);
2350 mStopToast.show();
2351 }
2352
Grace Kloba22ac16e2009-10-07 18:00:23 -07002353 boolean didUserStopLoading() {
2354 return mDidStopLoad;
2355 }
2356
The Android Open Source Project0c908882009-03-03 19:32:16 -08002357 private void cancelStopToast() {
2358 if (mStopToast != null) {
2359 mStopToast.cancel();
2360 mStopToast = null;
2361 }
2362 }
2363
Grace Kloba22ac16e2009-10-07 18:00:23 -07002364 // called by a UI or non-UI thread to post the message
2365 public void postMessage(int what, int arg1, int arg2, Object obj,
2366 long delayMillis) {
2367 mHandler.sendMessageDelayed(mHandler.obtainMessage(what, arg1, arg2,
2368 obj), delayMillis);
2369 }
2370
2371 // called by a UI or non-UI thread to remove the message
2372 void removeMessages(int what, Object object) {
2373 mHandler.removeMessages(what, object);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002374 }
2375
2376 // public message ids
2377 public final static int LOAD_URL = 1001;
2378 public final static int STOP_LOAD = 1002;
2379
2380 // Message Ids
2381 private static final int FOCUS_NODE_HREF = 102;
Grace Kloba92c18a52009-07-31 23:48:32 -07002382 private static final int RELEASE_WAKELOCK = 107;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002383
Grace Kloba22ac16e2009-10-07 18:00:23 -07002384 static final int UPDATE_BOOKMARK_THUMBNAIL = 108;
Ben Murdoch2694e232009-09-29 09:41:11 +01002385
Ben Murdocheecb4e62010-07-06 16:30:38 +01002386 private static final int TOUCH_ICON_DOWNLOADED = 109;
2387
The Android Open Source Project0c908882009-03-03 19:32:16 -08002388 // Private handler for handling javascript and saving passwords
2389 private Handler mHandler = new Handler() {
2390
Michael Kolbe0a36662010-06-29 10:37:12 -07002391 @Override
The Android Open Source Project0c908882009-03-03 19:32:16 -08002392 public void handleMessage(Message msg) {
2393 switch (msg.what) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002394 case FOCUS_NODE_HREF:
Ben Murdoch2694e232009-09-29 09:41:11 +01002395 {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002396 String url = (String) msg.getData().get("url");
Ben Murdoch90d088c2009-11-17 18:14:04 +00002397 String title = (String) msg.getData().get("title");
The Android Open Source Project0c908882009-03-03 19:32:16 -08002398 if (url == null || url.length() == 0) {
2399 break;
2400 }
2401 HashMap focusNodeMap = (HashMap) msg.obj;
2402 WebView view = (WebView) focusNodeMap.get("webview");
2403 // Only apply the action if the top window did not change.
2404 if (getTopWindow() != view) {
2405 break;
2406 }
2407 switch (msg.arg1) {
2408 case R.id.open_context_menu_id:
2409 case R.id.view_image_context_menu_id:
Leon Scroggins92472e82010-02-17 16:32:28 -05002410 loadUrlFromContext(getTopWindow(), url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002411 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002412 case R.id.bookmark_context_menu_id:
2413 Intent intent = new Intent(BrowserActivity.this,
2414 AddBookmarkPage.class);
2415 intent.putExtra("url", url);
Ben Murdoch90d088c2009-11-17 18:14:04 +00002416 intent.putExtra("title", title);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002417 startActivity(intent);
2418 break;
2419 case R.id.share_link_context_menu_id:
Leon Scroggins3e204452010-05-10 11:06:03 -04002420 sharePage(BrowserActivity.this, title, url, null,
Leon Scroggins96afcb12009-12-10 12:35:56 -05002421 null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002422 break;
2423 case R.id.copy_link_context_menu_id:
2424 copy(url);
2425 break;
2426 case R.id.save_link_context_menu_id:
2427 case R.id.download_context_menu_id:
2428 onDownloadStartNoStream(url, null, null, null, -1);
2429 break;
2430 }
2431 break;
Ben Murdoch2694e232009-09-29 09:41:11 +01002432 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002433
2434 case LOAD_URL:
Leon Scroggins92472e82010-02-17 16:32:28 -05002435 loadUrlFromContext(getTopWindow(), (String) msg.obj);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002436 break;
2437
2438 case STOP_LOAD:
2439 stopLoading();
2440 break;
2441
The Android Open Source Project0c908882009-03-03 19:32:16 -08002442 case RELEASE_WAKELOCK:
2443 if (mWakeLock.isHeld()) {
2444 mWakeLock.release();
Grace Kloba5d0e02e2009-10-05 15:15:36 -07002445 // if we reach here, Browser should be still in the
2446 // background loading after WAKELOCK_TIMEOUT (5-min).
2447 // To avoid burning the battery, stop loading.
2448 mTabControl.stopAllLoading();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002449 }
2450 break;
Ben Murdoch2694e232009-09-29 09:41:11 +01002451
2452 case UPDATE_BOOKMARK_THUMBNAIL:
2453 WebView view = (WebView) msg.obj;
2454 if (view != null) {
2455 updateScreenshot(view);
2456 }
2457 break;
Ben Murdocheecb4e62010-07-06 16:30:38 +01002458
2459 case TOUCH_ICON_DOWNLOADED:
2460 Bundle b = msg.getData();
2461 showSaveToHomescreenDialog(b.getString("url"),
2462 b.getString("title"),
2463 (Bitmap) b.getParcelable("touchIcon"),
2464 (Bitmap) b.getParcelable("favicon"));
2465 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002466 }
2467 }
2468 };
2469
Leon Scroggins96afcb12009-12-10 12:35:56 -05002470 /**
2471 * Share a page, providing the title, url, favicon, and a screenshot. Uses
2472 * an {@link Intent} to launch the Activity chooser.
2473 * @param c Context used to launch a new Activity.
2474 * @param title Title of the page. Stored in the Intent with
Paul Westbrook03e6d392010-02-12 10:33:29 -08002475 * {@link Intent#EXTRA_SUBJECT}
Leon Scroggins96afcb12009-12-10 12:35:56 -05002476 * @param url URL of the page. Stored in the Intent with
2477 * {@link Intent#EXTRA_TEXT}
2478 * @param favicon Bitmap of the favicon for the page. Stored in the Intent
2479 * with {@link Browser#EXTRA_SHARE_FAVICON}
2480 * @param screenshot Bitmap of a screenshot of the page. Stored in the
2481 * Intent with {@link Browser#EXTRA_SHARE_SCREENSHOT}
2482 */
2483 public static final void sharePage(Context c, String title, String url,
2484 Bitmap favicon, Bitmap screenshot) {
2485 Intent send = new Intent(Intent.ACTION_SEND);
2486 send.setType("text/plain");
2487 send.putExtra(Intent.EXTRA_TEXT, url);
Paul Westbrook03e6d392010-02-12 10:33:29 -08002488 send.putExtra(Intent.EXTRA_SUBJECT, title);
Leon Scroggins96afcb12009-12-10 12:35:56 -05002489 send.putExtra(Browser.EXTRA_SHARE_FAVICON, favicon);
2490 send.putExtra(Browser.EXTRA_SHARE_SCREENSHOT, screenshot);
2491 try {
2492 c.startActivity(Intent.createChooser(send, c.getString(
2493 R.string.choosertitle_sharevia)));
2494 } catch(android.content.ActivityNotFoundException ex) {
2495 // if no app handles it, do nothing
2496 }
2497 }
2498
Leon Scroggins89c6d362009-07-15 16:54:37 -04002499 private void updateScreenshot(WebView view) {
2500 // If this is a bookmarked site, add a screenshot to the database.
2501 // FIXME: When should we update? Every time?
2502 // FIXME: Would like to make sure there is actually something to
2503 // draw, but the API for that (WebViewCore.pictureReady()) is not
2504 // currently accessible here.
Ben Murdochaac7aa62009-09-17 16:57:40 +01002505
Ben Murdoch87cc65d2010-06-29 20:34:10 +01002506 final Bitmap bm = createScreenshot(view, getDesiredThumbnailWidth(this),
2507 getDesiredThumbnailHeight(this));
Patrick Scottcb192b52010-04-14 14:38:55 -04002508 if (bm == null) {
2509 return;
Leon Scroggins89c6d362009-07-15 16:54:37 -04002510 }
Patrick Scottcb192b52010-04-14 14:38:55 -04002511
2512 final ContentResolver cr = getContentResolver();
2513 final String url = view.getUrl();
2514 final String originalUrl = view.getOriginalUrl();
2515
2516 new AsyncTask<Void, Void, Void>() {
2517 @Override
2518 protected Void doInBackground(Void... unused) {
2519 Cursor c = null;
2520 try {
Jeff Hamilton84029622010-08-05 14:29:28 -05002521 c = Bookmarks.queryBookmarksForUrl(
Jeff Hamilton8ce956c2010-08-17 11:13:53 -05002522 cr, originalUrl, url);
Patrick Scottcb192b52010-04-14 14:38:55 -04002523 if (c != null) {
2524 if (c.moveToFirst()) {
2525 ContentValues values = new ContentValues();
2526 final ByteArrayOutputStream os
2527 = new ByteArrayOutputStream();
2528 bm.compress(Bitmap.CompressFormat.PNG, 100, os);
Jeff Hamilton8ce956c2010-08-17 11:13:53 -05002529 values.put(BrowserContract.Bookmarks.THUMBNAIL,
Patrick Scottcb192b52010-04-14 14:38:55 -04002530 os.toByteArray());
2531 do {
2532 cr.update(ContentUris.withAppendedId(
Jeff Hamilton8ce956c2010-08-17 11:13:53 -05002533 BrowserContract.Bookmarks.CONTENT_URI, c.getLong(0)),
Patrick Scottcb192b52010-04-14 14:38:55 -04002534 values, null, null);
2535 } while (c.moveToNext());
2536 }
2537 }
2538 } catch (IllegalStateException e) {
2539 // Ignore
2540 } finally {
2541 if (c != null) c.close();
2542 }
2543 return null;
2544 }
2545 }.execute();
Leon Scroggins89c6d362009-07-15 16:54:37 -04002546 }
2547
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002548 /**
Leon Scrogginsf8551612009-09-24 16:06:02 -04002549 * Values for the size of the thumbnail created when taking a screenshot.
2550 * Lazily initialized. Instead of using these directly, use
2551 * getDesiredThumbnailWidth() or getDesiredThumbnailHeight().
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002552 */
Leon Scrogginsf8551612009-09-24 16:06:02 -04002553 private static int THUMBNAIL_WIDTH = 0;
2554 private static int THUMBNAIL_HEIGHT = 0;
2555
2556 /**
2557 * Return the desired width for thumbnail screenshots, which are stored in
2558 * the database, and used on the bookmarks screen.
2559 * @param context Context for finding out the density of the screen.
2560 * @return int desired width for thumbnail screenshot.
2561 */
2562 /* package */ static int getDesiredThumbnailWidth(Context context) {
2563 if (THUMBNAIL_WIDTH == 0) {
2564 float density = context.getResources().getDisplayMetrics().density;
2565 THUMBNAIL_WIDTH = (int) (90 * density);
2566 THUMBNAIL_HEIGHT = (int) (80 * density);
2567 }
2568 return THUMBNAIL_WIDTH;
2569 }
2570
2571 /**
2572 * Return the desired height for thumbnail screenshots, which are stored in
2573 * the database, and used on the bookmarks screen.
2574 * @param context Context for finding out the density of the screen.
2575 * @return int desired height for thumbnail screenshot.
2576 */
2577 /* package */ static int getDesiredThumbnailHeight(Context context) {
2578 // To ensure that they are both initialized.
2579 getDesiredThumbnailWidth(context);
2580 return THUMBNAIL_HEIGHT;
2581 }
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002582
Ben Murdoch87cc65d2010-06-29 20:34:10 +01002583 private Bitmap createScreenshot(WebView view, int width, int height) {
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002584 Picture thumbnail = view.capturePicture();
Leon Scroggins45800572009-09-29 16:38:47 -04002585 if (thumbnail == null) {
2586 return null;
2587 }
Ben Murdoch87cc65d2010-06-29 20:34:10 +01002588 Bitmap bm = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002589 Canvas canvas = new Canvas(bm);
2590 // May need to tweak these values to determine what is the
2591 // best scale factor
Ben Murdoch2694e232009-09-29 09:41:11 +01002592 int thumbnailWidth = thumbnail.getWidth();
Ben Murdochae59c3f2009-10-20 18:30:28 +01002593 int thumbnailHeight = thumbnail.getHeight();
2594 float scaleFactorX = 1.0f;
2595 float scaleFactorY = 1.0f;
Ben Murdoch2694e232009-09-29 09:41:11 +01002596 if (thumbnailWidth > 0) {
Ben Murdoch87cc65d2010-06-29 20:34:10 +01002597 scaleFactorX = (float) width / (float)thumbnailWidth;
Ben Murdochae59c3f2009-10-20 18:30:28 +01002598 } else {
2599 return null;
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002600 }
Ben Murdochae59c3f2009-10-20 18:30:28 +01002601
2602 if (view.getWidth() > view.getHeight() &&
2603 thumbnailHeight < view.getHeight() && thumbnailHeight > 0) {
2604 // If the device is in landscape and the page is shorter
2605 // than the height of the view, stretch the thumbnail to fill the
2606 // space.
Ben Murdoch87cc65d2010-06-29 20:34:10 +01002607 scaleFactorY = (float) height / (float)thumbnailHeight;
Ben Murdochae59c3f2009-10-20 18:30:28 +01002608 } else {
2609 // In the portrait case, this looks nice.
2610 scaleFactorY = scaleFactorX;
2611 }
2612
2613 canvas.scale(scaleFactorX, scaleFactorY);
2614
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002615 thumbnail.draw(canvas);
2616 return bm;
2617 }
2618
The Android Open Source Project0c908882009-03-03 19:32:16 -08002619 // -------------------------------------------------------------------------
Grace Kloba22ac16e2009-10-07 18:00:23 -07002620 // Helper function for WebViewClient.
The Android Open Source Project0c908882009-03-03 19:32:16 -08002621 //-------------------------------------------------------------------------
2622
2623 // Use in overrideUrlLoading
2624 /* package */ final static String SCHEME_WTAI = "wtai://wp/";
2625 /* package */ final static String SCHEME_WTAI_MC = "wtai://wp/mc;";
2626 /* package */ final static String SCHEME_WTAI_SD = "wtai://wp/sd;";
2627 /* package */ final static String SCHEME_WTAI_AP = "wtai://wp/ap;";
2628
Leon Scroggins92472e82010-02-17 16:32:28 -05002629 // Keep this initial progress in sync with initialProgressValue (* 100)
2630 // in ProgressTracker.cpp
2631 private final static int INITIAL_PROGRESS = 10;
2632
Grace Kloba22ac16e2009-10-07 18:00:23 -07002633 void onPageStarted(WebView view, String url, Bitmap favicon) {
2634 // when BrowserActivity just starts, onPageStarted may be called before
2635 // onResume as it is triggered from onCreate. Call resumeWebViewTimers
2636 // to start the timer. As we won't switch tabs while an activity is in
2637 // pause state, we can ensure calling resume and pause in pair.
2638 if (mActivityInPause) resumeWebViewTimers();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002639
Grace Kloba22ac16e2009-10-07 18:00:23 -07002640 resetLockIcon(url);
2641 setUrlTitle(url, null);
2642 setFavicon(favicon);
Leon Scroggins8cf8f682009-11-04 11:13:50 -08002643 // Show some progress so that the user knows the page is beginning to
2644 // load
Leon Scroggins92472e82010-02-17 16:32:28 -05002645 onProgressChanged(view, INITIAL_PROGRESS);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002646 mDidStopLoad = false;
Grace Kloba22ac16e2009-10-07 18:00:23 -07002647 if (!mIsNetworkUp) createAndShowNetworkDialog();
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04002648 endActionMode();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002649 if (mSettings.isTracing()) {
2650 String host;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002651 try {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002652 WebAddress uri = new WebAddress(url);
2653 host = uri.mHost;
2654 } catch (android.net.ParseException ex) {
2655 host = "browser";
The Android Open Source Project0c908882009-03-03 19:32:16 -08002656 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002657 host = host.replace('.', '_');
2658 host += ".trace";
2659 mInTrace = true;
2660 Debug.startMethodTracing(host, 20 * 1024 * 1024);
2661 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002662
Grace Kloba22ac16e2009-10-07 18:00:23 -07002663 // Performance probe
2664 if (false) {
2665 mStart = SystemClock.uptimeMillis();
2666 mProcessStart = Process.getElapsedCpuTime();
2667 long[] sysCpu = new long[7];
2668 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2669 sysCpu, null)) {
2670 mUserStart = sysCpu[0] + sysCpu[1];
2671 mSystemStart = sysCpu[2];
2672 mIdleStart = sysCpu[3];
2673 mIrqStart = sysCpu[4] + sysCpu[5] + sysCpu[6];
2674 }
2675 mUiStart = SystemClock.currentThreadTimeMillis();
2676 }
2677 }
2678
2679 void onPageFinished(WebView view, String url) {
2680 // Reset the title and icon in case we stopped a provisional load.
2681 resetTitleAndIcon(view);
2682 // Update the lock icon image only once we are done loading
2683 updateLockIconToLatest();
2684 // pause the WebView timer and release the wake lock if it is finished
2685 // while BrowserActivity is in pause state.
2686 if (mActivityInPause && pauseWebViewTimers()) {
2687 if (mWakeLock.isHeld()) {
2688 mHandler.removeMessages(RELEASE_WAKELOCK);
2689 mWakeLock.release();
2690 }
2691 }
2692
2693 // Performance probe
2694 if (false) {
2695 long[] sysCpu = new long[7];
2696 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2697 sysCpu, null)) {
2698 String uiInfo = "UI thread used "
2699 + (SystemClock.currentThreadTimeMillis() - mUiStart)
2700 + " ms";
2701 if (LOGD_ENABLED) {
2702 Log.d(LOGTAG, uiInfo);
2703 }
2704 //The string that gets written to the log
2705 String performanceString = "It took total "
2706 + (SystemClock.uptimeMillis() - mStart)
2707 + " ms clock time to load the page."
2708 + "\nbrowser process used "
2709 + (Process.getElapsedCpuTime() - mProcessStart)
2710 + " ms, user processes used "
2711 + (sysCpu[0] + sysCpu[1] - mUserStart) * 10
2712 + " ms, kernel used "
2713 + (sysCpu[2] - mSystemStart) * 10
2714 + " ms, idle took " + (sysCpu[3] - mIdleStart) * 10
2715 + " ms and irq took "
2716 + (sysCpu[4] + sysCpu[5] + sysCpu[6] - mIrqStart)
2717 * 10 + " ms, " + uiInfo;
2718 if (LOGD_ENABLED) {
2719 Log.d(LOGTAG, performanceString + "\nWebpage: " + url);
2720 }
2721 if (url != null) {
2722 // strip the url to maintain consistency
2723 String newUrl = new String(url);
2724 if (newUrl.startsWith("http://www.")) {
2725 newUrl = newUrl.substring(11);
2726 } else if (newUrl.startsWith("http://")) {
2727 newUrl = newUrl.substring(7);
2728 } else if (newUrl.startsWith("https://www.")) {
2729 newUrl = newUrl.substring(12);
2730 } else if (newUrl.startsWith("https://")) {
2731 newUrl = newUrl.substring(8);
2732 }
2733 if (LOGD_ENABLED) {
2734 Log.d(LOGTAG, newUrl + " loaded");
2735 }
Grace Kloba5b078b52009-06-24 20:23:41 -07002736 }
2737 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002738 }
Grace Kloba5b078b52009-06-24 20:23:41 -07002739
Grace Kloba22ac16e2009-10-07 18:00:23 -07002740 if (mInTrace) {
2741 mInTrace = false;
2742 Debug.stopMethodTracing();
2743 }
2744 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002745
Grace Klobae7fe26b2010-06-28 16:23:33 -07002746 private void closeEmptyChildTab() {
2747 Tab current = mTabControl.getCurrentTab();
2748 if (current != null
2749 && current.getWebView().copyBackForwardList().getSize() == 0) {
2750 Tab parent = current.getParentTab();
2751 if (parent != null) {
2752 switchToTab(mTabControl.getTabIndex(parent));
2753 closeTab(current);
2754 }
2755 }
2756 }
2757
Grace Kloba22ac16e2009-10-07 18:00:23 -07002758 boolean shouldOverrideUrlLoading(WebView view, String url) {
2759 if (url.startsWith(SCHEME_WTAI)) {
2760 // wtai://wp/mc;number
2761 // number=string(phone-number)
2762 if (url.startsWith(SCHEME_WTAI_MC)) {
2763 Intent intent = new Intent(Intent.ACTION_VIEW,
2764 Uri.parse(WebView.SCHEME_TEL +
2765 url.substring(SCHEME_WTAI_MC.length())));
2766 startActivity(intent);
Grace Klobae7fe26b2010-06-28 16:23:33 -07002767 // before leaving BrowserActivity, close the empty child tab.
2768 // If a new tab is created through JavaScript open to load this
2769 // url, we would like to close it as we will load this url in a
2770 // different Activity.
2771 closeEmptyChildTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002772 return true;
2773 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002774 // wtai://wp/sd;dtmf
2775 // dtmf=string(dialstring)
2776 if (url.startsWith(SCHEME_WTAI_SD)) {
2777 // TODO: only send when there is active voice connection
2778 return false;
2779 }
2780 // wtai://wp/ap;number;name
2781 // number=string(phone-number)
2782 // name=string
2783 if (url.startsWith(SCHEME_WTAI_AP)) {
2784 // TODO
2785 return false;
2786 }
2787 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002788
Grace Kloba22ac16e2009-10-07 18:00:23 -07002789 // The "about:" schemes are internal to the browser; don't want these to
2790 // be dispatched to other apps.
2791 if (url.startsWith("about:")) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002792 return false;
2793 }
2794
Jeff Davidson43610292010-07-16 16:03:58 -07002795 // If this is a Google search, attempt to add an RLZ string (if one isn't already present).
2796 if (rlzProviderPresent()) {
2797 Uri siteUri = Uri.parse(url);
2798 if (needsRlzString(siteUri)) {
2799 String rlz = null;
2800 Cursor cur = null;
2801 try {
2802 cur = getContentResolver().query(getRlzUri(), null, null, null, null);
2803 if (cur != null && cur.moveToFirst() && !cur.isNull(0)) {
2804 url = siteUri.buildUpon()
2805 .appendQueryParameter("rlz", cur.getString(0))
2806 .build().toString();
2807 }
2808 } finally {
2809 if (cur != null) {
2810 cur.close();
2811 }
2812 }
2813 loadUrl(view, url);
2814 return true;
2815 }
2816 }
2817
Grace Kloba22ac16e2009-10-07 18:00:23 -07002818 Intent intent;
2819 // perform generic parsing of the URI to turn it into an Intent.
2820 try {
2821 intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME);
2822 } catch (URISyntaxException ex) {
2823 Log.w("Browser", "Bad URI " + url + ": " + ex.getMessage());
2824 return false;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002825 }
2826
Grace Kloba22ac16e2009-10-07 18:00:23 -07002827 // check whether the intent can be resolved. If not, we will see
2828 // whether we can download it from the Market.
2829 if (getPackageManager().resolveActivity(intent, 0) == null) {
2830 String packagename = intent.getPackage();
2831 if (packagename != null) {
2832 intent = new Intent(Intent.ACTION_VIEW, Uri
2833 .parse("market://search?q=pname:" + packagename));
2834 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2835 startActivity(intent);
Grace Klobae7fe26b2010-06-28 16:23:33 -07002836 // before leaving BrowserActivity, close the empty child tab.
2837 // If a new tab is created through JavaScript open to load this
2838 // url, we would like to close it as we will load this url in a
2839 // different Activity.
2840 closeEmptyChildTab();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002841 return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002842 } else {
2843 return false;
2844 }
2845 }
2846
Grace Kloba22ac16e2009-10-07 18:00:23 -07002847 // sanitize the Intent, ensuring web pages can not bypass browser
2848 // security (only access to BROWSABLE activities).
2849 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2850 intent.setComponent(null);
2851 try {
2852 if (startActivityIfNeeded(intent, -1)) {
Grace Klobae7fe26b2010-06-28 16:23:33 -07002853 // before leaving BrowserActivity, close the empty child tab.
2854 // If a new tab is created through JavaScript open to load this
2855 // url, we would like to close it as we will load this url in a
2856 // different Activity.
2857 closeEmptyChildTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002858 return true;
2859 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002860 } catch (ActivityNotFoundException ex) {
2861 // ignore the error. If no application can handle the URL,
2862 // eg about:blank, assume the browser can handle it.
2863 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002864
Grace Kloba22ac16e2009-10-07 18:00:23 -07002865 if (mMenuIsDown) {
Michael Kolb68792c82010-08-09 16:39:18 -07002866 openTab(url, false);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002867 closeOptionsMenu();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002868 return true;
2869 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002870 return false;
2871 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002872
Jeff Davidson43610292010-07-16 16:03:58 -07002873 // Determine whether the RLZ provider is present on the system.
2874 private boolean rlzProviderPresent() {
2875 if (mIsProviderPresent == null) {
2876 PackageManager pm = getPackageManager();
2877 mIsProviderPresent = pm.resolveContentProvider(BrowserSettings.RLZ_PROVIDER, 0) != null;
2878 }
2879 return mIsProviderPresent;
2880 }
2881
2882 // Retrieve the RLZ access point string and cache the URI used to retrieve RLZ values.
2883 private Uri getRlzUri() {
2884 if (mRlzUri == null) {
2885 String ap = getResources().getString(R.string.rlz_access_point);
2886 mRlzUri = Uri.withAppendedPath(BrowserSettings.RLZ_PROVIDER_URI, ap);
2887 }
2888 return mRlzUri;
2889 }
2890
2891 // Determine if this URI appears to be for a Google search and does not have an RLZ parameter.
2892 // Taken largely from Chrome source, src/chrome/browser/google_url_tracker.cc
2893 private static boolean needsRlzString(Uri uri) {
2894 if ((uri.getQueryParameter("q") != null) && (uri.getQueryParameter("rlz") == null)) {
2895 String host = uri.getHost();
2896 if (host == null) {
2897 return false;
2898 }
2899 String[] hostComponents = host.split("\\.");
2900
2901 if (hostComponents.length < 2) {
2902 return false;
2903 }
2904 int googleComponent = hostComponents.length - 2;
2905 String component = hostComponents[googleComponent];
2906 if (!"google".equals(component)) {
2907 if (hostComponents.length < 3 ||
2908 (!"co".equals(component) && !"com".equals(component))) {
2909 return false;
2910 }
2911 googleComponent = hostComponents.length - 3;
2912 if (!"google".equals(hostComponents[googleComponent])) {
2913 return false;
2914 }
2915 }
2916
2917 // Google corp network handling.
2918 if (googleComponent > 0 && "corp".equals(hostComponents[googleComponent - 1])) {
2919 return false;
2920 }
2921
2922 return true;
2923 }
2924 return false;
2925 }
2926
Grace Kloba22ac16e2009-10-07 18:00:23 -07002927 // -------------------------------------------------------------------------
2928 // Helper function for WebChromeClient
2929 // -------------------------------------------------------------------------
The Android Open Source Project0c908882009-03-03 19:32:16 -08002930
Grace Kloba22ac16e2009-10-07 18:00:23 -07002931 void onProgressChanged(WebView view, int newProgress) {
Michael Kolba2b2ba82010-08-04 17:54:03 -07002932
2933 // On the phone, the fake title bar will always cover up the
2934 // regular title bar (or the regular one is offscreen), so only the
2935 // fake title bar needs to change its progress
2936 mFakeTitleBar.setProgress(newProgress);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002937
Grace Kloba22ac16e2009-10-07 18:00:23 -07002938 if (newProgress == 100) {
2939 // onProgressChanged() may continue to be called after the main
2940 // frame has finished loading, as any remaining sub frames continue
2941 // to load. We'll only get called once though with newProgress as
2942 // 100 when everything is loaded. (onPageFinished is called once
2943 // when the main frame completes loading regardless of the state of
2944 // any sub frames so calls to onProgressChanges may continue after
2945 // onPageFinished has executed)
2946 if (mInLoad) {
2947 mInLoad = false;
Leon Scrogginsa27ff192009-09-14 12:58:04 -04002948 updateInLoadMenuItems();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002949 // If the options menu is open, leave the title bar
2950 if (!mOptionsMenuOpen || !mIconView) {
2951 hideFakeTitleBar();
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07002952 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002953 }
Leon Scrogginsaa37e7f2010-03-05 11:51:20 -05002954 } else {
2955 if (!mInLoad) {
2956 // onPageFinished may have already been called but a subframe is
2957 // still loading and updating the progress. Reset mInLoad and
2958 // update the menu items.
2959 mInLoad = true;
2960 updateInLoadMenuItems();
2961 }
2962 // When the page first begins to load, the Activity may still be
2963 // paused, in which case showFakeTitleBar will do nothing. Call
2964 // again as the page continues to load so that it will be shown.
2965 // (Calling it will the fake title bar is already showing will also
2966 // do nothing.
Grace Kloba22ac16e2009-10-07 18:00:23 -07002967 if (!mOptionsMenuOpen || mIconView) {
2968 // This page has begun to load, so show the title bar
2969 showFakeTitleBar();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002970 }
2971 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002972 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002973
Grace Kloba22ac16e2009-10-07 18:00:23 -07002974 void onShowCustomView(View view, WebChromeClient.CustomViewCallback callback) {
Derek Sollenberger8ff57db2009-12-08 15:39:55 -05002975 // if a view already exists then immediately terminate the new one
2976 if (mCustomView != null) {
2977 callback.onCustomViewHidden();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002978 return;
Derek Sollenberger8ff57db2009-12-08 15:39:55 -05002979 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002980
2981 // Add the custom view to its container.
2982 mCustomViewContainer.addView(view, COVER_SCREEN_GRAVITY_CENTER);
2983 mCustomView = view;
2984 mCustomViewCallback = callback;
2985 // Save the menu state and set it to empty while the custom
2986 // view is showing.
2987 mOldMenuState = mMenuState;
2988 mMenuState = EMPTY_MENU;
2989 // Hide the content view.
2990 mContentView.setVisibility(View.GONE);
2991 // Finally show the custom view container.
Andrei Popescu163ab742009-10-20 17:58:23 +01002992 setStatusBarVisibility(false);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002993 mCustomViewContainer.setVisibility(View.VISIBLE);
2994 mCustomViewContainer.bringToFront();
2995 }
2996
2997 void onHideCustomView() {
2998 if (mCustomView == null)
2999 return;
3000
3001 // Hide the custom view.
3002 mCustomView.setVisibility(View.GONE);
3003 // Remove the custom view from its container.
3004 mCustomViewContainer.removeView(mCustomView);
3005 mCustomView = null;
3006 // Reset the old menu state.
3007 mMenuState = mOldMenuState;
3008 mOldMenuState = EMPTY_MENU;
3009 mCustomViewContainer.setVisibility(View.GONE);
3010 mCustomViewCallback.onCustomViewHidden();
3011 // Show the content view.
Andrei Popescu163ab742009-10-20 17:58:23 +01003012 setStatusBarVisibility(true);
Grace Kloba22ac16e2009-10-07 18:00:23 -07003013 mContentView.setVisibility(View.VISIBLE);
3014 }
3015
3016 Bitmap getDefaultVideoPoster() {
3017 if (mDefaultVideoPoster == null) {
3018 mDefaultVideoPoster = BitmapFactory.decodeResource(
3019 getResources(), R.drawable.default_video_poster);
Patrick Scott3918d442009-08-04 13:22:29 -04003020 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07003021 return mDefaultVideoPoster;
3022 }
Patrick Scott3918d442009-08-04 13:22:29 -04003023
Grace Kloba22ac16e2009-10-07 18:00:23 -07003024 View getVideoLoadingProgressView() {
3025 if (mVideoProgressView == null) {
3026 LayoutInflater inflater = LayoutInflater.from(BrowserActivity.this);
3027 mVideoProgressView = inflater.inflate(
3028 R.layout.video_loading_progress, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003029 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07003030 return mVideoProgressView;
3031 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003032
Leon Scroggins8d5fa432009-10-02 15:55:59 -04003033 /*
3034 * The Object used to inform the WebView of the file to upload.
3035 */
3036 private ValueCallback<Uri> mUploadMessage;
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003037 private String mCameraFilePath;
Leon Scroggins8d5fa432009-10-02 15:55:59 -04003038
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003039 void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
3040
3041 final String imageMimeType = "image/*";
Ben Murdoch6af492a2010-06-15 12:38:17 +01003042 final String videoMimeType = "video/*";
Ben Murdoch039bd472010-07-21 21:26:57 +01003043 final String audioMimeType = "audio/*";
Ben Murdochb50d7402010-07-16 12:42:22 +01003044 final String mediaSourceKey = "capture";
Ben Murdoch6af492a2010-06-15 12:38:17 +01003045 final String mediaSourceValueCamera = "camera";
Ben Murdochb50d7402010-07-16 12:42:22 +01003046 final String mediaSourceValueFileSystem = "filesystem";
Ben Murdoch6af492a2010-06-15 12:38:17 +01003047 final String mediaSourceValueCamcorder = "camcorder";
Ben Murdoch039bd472010-07-21 21:26:57 +01003048 final String mediaSourceValueMicrophone = "microphone";
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003049
Ben Murdoch039bd472010-07-21 21:26:57 +01003050 // media source can be 'filesystem' or 'camera' or 'camcorder' or 'microphone'.
Ben Murdoch6af492a2010-06-15 12:38:17 +01003051 String mediaSource = "";
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003052
Ben Murdoch6af492a2010-06-15 12:38:17 +01003053 // We add the camera intent if there was no accept type (or '*/*' or 'image/*').
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003054 boolean addCameraIntent = true;
Ben Murdoch6af492a2010-06-15 12:38:17 +01003055 // We add the camcorder intent if there was no accept type (or '*/*' or 'video/*').
3056 boolean addCamcorderIntent = true;
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003057
Ben Murdoch6af492a2010-06-15 12:38:17 +01003058 if (mUploadMessage != null) {
3059 // Already a file picker operation in progress.
3060 return;
3061 }
3062
Grace Kloba22ac16e2009-10-07 18:00:23 -07003063 mUploadMessage = uploadMsg;
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003064
3065 // Parse the accept type.
3066 String params[] = acceptType.split(";");
3067 String mimeType = params[0];
3068
3069 for (String p : params) {
3070 String[] keyValue = p.split("=");
3071 if (keyValue.length == 2) {
3072 // Process key=value parameters.
Ben Murdoch6af492a2010-06-15 12:38:17 +01003073 if (mediaSourceKey.equals(keyValue[0])) {
3074 mediaSource = keyValue[1];
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003075 }
3076 }
3077 }
3078
3079 // This intent will display the standard OPENABLE file picker.
Grace Kloba22ac16e2009-10-07 18:00:23 -07003080 Intent i = new Intent(Intent.ACTION_GET_CONTENT);
3081 i.addCategory(Intent.CATEGORY_OPENABLE);
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003082
3083 // Create an intent to add to the standard file picker that will
3084 // capture an image from the camera. We'll combine this intent with
3085 // the standard OPENABLE picker unless the web developer specifically
3086 // requested the camera or gallery be opened by passing a parameter
3087 // in the accept type.
3088 Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
3089 File externalDataDir = Environment.getExternalStoragePublicDirectory(
3090 Environment.DIRECTORY_DCIM);
3091 File cameraDataDir = new File(externalDataDir.getAbsolutePath() +
3092 File.separator + "browser-photos");
3093 cameraDataDir.mkdirs();
3094 mCameraFilePath = cameraDataDir.getAbsolutePath() + File.separator +
3095 System.currentTimeMillis() + ".jpg";
3096 cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(mCameraFilePath)));
3097
Ben Murdoch6af492a2010-06-15 12:38:17 +01003098 Intent camcorderIntent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
3099
Ben Murdoch039bd472010-07-21 21:26:57 +01003100 Intent soundRecIntent = new Intent(MediaStore.Audio.Media.RECORD_SOUND_ACTION);
3101
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003102 if (mimeType.equals(imageMimeType)) {
3103 i.setType(imageMimeType);
Ben Murdoch6af492a2010-06-15 12:38:17 +01003104 addCamcorderIntent = false;
3105 if (mediaSource.equals(mediaSourceValueCamera)) {
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003106 // Specified 'image/*' and requested the camera, so go ahead and launch the camera
3107 // directly.
3108 BrowserActivity.this.startActivityForResult(cameraIntent, FILE_SELECTED);
3109 return;
Ben Murdochb50d7402010-07-16 12:42:22 +01003110 } else if (mediaSource.equals(mediaSourceValueFileSystem)) {
3111 // Specified filesytem as the source, so don't want to consider the camera.
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003112 addCameraIntent = false;
3113 }
Ben Murdoch6af492a2010-06-15 12:38:17 +01003114 } else if (mimeType.equals(videoMimeType)) {
3115 i.setType(videoMimeType);
3116 addCameraIntent = false;
3117 // The camcorder saves it's own file and returns it to us in the intent, so
3118 // we don't need to generate one here.
3119 mCameraFilePath = null;
3120
3121 if (mediaSource.equals(mediaSourceValueCamcorder)) {
Ben Murdoch039bd472010-07-21 21:26:57 +01003122 // Specified 'video/*' and requested the camcorder, so go ahead and launch the
3123 // camcorder directly.
Ben Murdoch6af492a2010-06-15 12:38:17 +01003124 BrowserActivity.this.startActivityForResult(camcorderIntent, FILE_SELECTED);
3125 return;
Ben Murdochb50d7402010-07-16 12:42:22 +01003126 } else if (mediaSource.equals(mediaSourceValueFileSystem)) {
3127 // Specified filesystem as the source, so don't want to consider the camcorder.
Ben Murdoch6af492a2010-06-15 12:38:17 +01003128 addCamcorderIntent = false;
3129 }
Ben Murdoch039bd472010-07-21 21:26:57 +01003130 } else if (mimeType.equals(audioMimeType)) {
3131 i.setType(audioMimeType);
3132 addCameraIntent = false;
3133 addCamcorderIntent = false;
3134 if (mediaSource.equals(mediaSourceValueMicrophone)) {
3135 // Specified 'audio/*' and requested microphone, so go ahead and launch the sound
3136 // recorder.
3137 BrowserActivity.this.startActivityForResult(soundRecIntent, FILE_SELECTED);
3138 return;
3139 }
3140 // On a default system, there is no single option to open an audio "gallery". Both the
3141 // sound recorder and music browser respond to the OPENABLE/audio/* intent unlike the
3142 // image/* and video/* OPENABLE intents where the image / video gallery are the only
3143 // respondants (and so the user is not prompted by default).
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003144 } else {
3145 i.setType("*/*");
3146 }
3147
Ben Murdoch6af492a2010-06-15 12:38:17 +01003148 // Combine the chooser and the extra choices (like camera or camcorder)
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003149 Intent chooser = new Intent(Intent.ACTION_CHOOSER);
3150 chooser.putExtra(Intent.EXTRA_INTENT, i);
3151
Ben Murdoch6af492a2010-06-15 12:38:17 +01003152 Vector<Intent> extraInitialIntents = new Vector<Intent>(0);
3153
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003154 if (addCameraIntent) {
Ben Murdoch6af492a2010-06-15 12:38:17 +01003155 extraInitialIntents.add(cameraIntent);
3156 }
3157
3158 if (addCamcorderIntent) {
3159 extraInitialIntents.add(camcorderIntent);
3160 }
3161
3162 if (extraInitialIntents.size() > 0) {
3163 Intent[] extraIntents = new Intent[extraInitialIntents.size()];
3164 chooser.putExtra(Intent.EXTRA_INITIAL_INTENTS, extraInitialIntents.toArray(extraIntents));
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003165 }
3166
3167 chooser.putExtra(Intent.EXTRA_TITLE, getString(R.string.choose_upload));
3168 BrowserActivity.this.startActivityForResult(chooser, FILE_SELECTED);
Grace Kloba22ac16e2009-10-07 18:00:23 -07003169 }
3170
3171 // -------------------------------------------------------------------------
3172 // Implement functions for DownloadListener
3173 // -------------------------------------------------------------------------
3174
The Android Open Source Project0c908882009-03-03 19:32:16 -08003175 /**
3176 * Notify the host application a download should be done, or that
3177 * the data should be streamed if a streaming viewer is available.
3178 * @param url The full url to the content that should be downloaded
3179 * @param contentDisposition Content-disposition http header, if
3180 * present.
3181 * @param mimetype The mimetype of the content reported by the server
3182 * @param contentLength The file size reported by the server
3183 */
3184 public void onDownloadStart(String url, String userAgent,
3185 String contentDisposition, String mimetype, long contentLength) {
3186 // if we're dealing wih A/V content that's not explicitly marked
3187 // for download, check if it's streamable.
3188 if (contentDisposition == null
Patrick Scotte1fb9662009-08-31 14:31:52 -04003189 || !contentDisposition.regionMatches(
3190 true, 0, "attachment", 0, 10)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003191 // query the package manager to see if there's a registered handler
3192 // that matches.
3193 Intent intent = new Intent(Intent.ACTION_VIEW);
3194 intent.setDataAndType(Uri.parse(url), mimetype);
Patrick Scotte1fb9662009-08-31 14:31:52 -04003195 ResolveInfo info = getPackageManager().resolveActivity(intent,
3196 PackageManager.MATCH_DEFAULT_ONLY);
3197 if (info != null) {
3198 ComponentName myName = getComponentName();
3199 // If we resolved to ourselves, we don't want to attempt to
3200 // load the url only to try and download it again.
3201 if (!myName.getPackageName().equals(
3202 info.activityInfo.packageName)
3203 || !myName.getClassName().equals(
3204 info.activityInfo.name)) {
3205 // someone (other than us) knows how to handle this mime
3206 // type with this scheme, don't download.
3207 try {
3208 startActivity(intent);
3209 return;
3210 } catch (ActivityNotFoundException ex) {
3211 if (LOGD_ENABLED) {
3212 Log.d(LOGTAG, "activity not found for " + mimetype
3213 + " over " + Uri.parse(url).getScheme(),
3214 ex);
3215 }
3216 // Best behavior is to fall back to a download in this
3217 // case
The Android Open Source Project0c908882009-03-03 19:32:16 -08003218 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003219 }
3220 }
3221 }
3222 onDownloadStartNoStream(url, userAgent, contentDisposition, mimetype, contentLength);
3223 }
3224
Kristian Monsenfa52d172010-03-25 18:29:21 +00003225 // This is to work around the fact that java.net.URI throws Exceptions
3226 // instead of just encoding URL's properly
3227 // Helper method for onDownloadStartNoStream
3228 private static String encodePath(String path) {
3229 char[] chars = path.toCharArray();
3230
3231 boolean needed = false;
3232 for (char c : chars) {
3233 if (c == '[' || c == ']') {
3234 needed = true;
3235 break;
3236 }
3237 }
3238 if (needed == false) {
3239 return path;
3240 }
3241
3242 StringBuilder sb = new StringBuilder("");
3243 for (char c : chars) {
3244 if (c == '[' || c == ']') {
3245 sb.append('%');
3246 sb.append(Integer.toHexString(c));
3247 } else {
3248 sb.append(c);
3249 }
3250 }
3251
3252 return sb.toString();
3253 }
3254
The Android Open Source Project0c908882009-03-03 19:32:16 -08003255 /**
3256 * Notify the host application a download should be done, even if there
3257 * is a streaming viewer available for thise type.
3258 * @param url The full url to the content that should be downloaded
3259 * @param contentDisposition Content-disposition http header, if
3260 * present.
3261 * @param mimetype The mimetype of the content reported by the server
3262 * @param contentLength The file size reported by the server
3263 */
3264 /*package */ void onDownloadStartNoStream(String url, String userAgent,
3265 String contentDisposition, String mimetype, long contentLength) {
3266
3267 String filename = URLUtil.guessFileName(url,
3268 contentDisposition, mimetype);
3269
3270 // Check to see if we have an SDCard
3271 String status = Environment.getExternalStorageState();
3272 if (!status.equals(Environment.MEDIA_MOUNTED)) {
3273 int title;
3274 String msg;
3275
3276 // Check to see if the SDCard is busy, same as the music app
3277 if (status.equals(Environment.MEDIA_SHARED)) {
3278 msg = getString(R.string.download_sdcard_busy_dlg_msg);
3279 title = R.string.download_sdcard_busy_dlg_title;
3280 } else {
3281 msg = getString(R.string.download_no_sdcard_dlg_msg, filename);
3282 title = R.string.download_no_sdcard_dlg_title;
3283 }
3284
3285 new AlertDialog.Builder(this)
3286 .setTitle(title)
3287 .setIcon(android.R.drawable.ic_dialog_alert)
3288 .setMessage(msg)
3289 .setPositiveButton(R.string.ok, null)
3290 .show();
3291 return;
3292 }
3293
Kristian Monsenfa52d172010-03-25 18:29:21 +00003294 // java.net.URI is a lot stricter than KURL so we have to encode some
3295 // extra characters. Fix for b 2538060 and b 1634719
3296 WebAddress webAddress;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003297 try {
Kristian Monsenfa52d172010-03-25 18:29:21 +00003298 webAddress = new WebAddress(url);
3299 webAddress.mPath = encodePath(webAddress.mPath);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003300 } catch (Exception e) {
Kristian Monsenfa52d172010-03-25 18:29:21 +00003301 // This only happens for very bad urls, we want to chatch the
3302 // exception here
3303 Log.e(LOGTAG, "Exception trying to parse url:" + url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003304 return;
3305 }
3306
3307 // XXX: Have to use the old url since the cookies were stored using the
3308 // old percent-encoded url.
3309 String cookies = CookieManager.getInstance().getCookie(url);
3310
3311 ContentValues values = new ContentValues();
Kristian Monsenfa52d172010-03-25 18:29:21 +00003312 values.put(Downloads.Impl.COLUMN_URI, webAddress.toString());
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08003313 values.put(Downloads.Impl.COLUMN_COOKIE_DATA, cookies);
3314 values.put(Downloads.Impl.COLUMN_USER_AGENT, userAgent);
3315 values.put(Downloads.Impl.COLUMN_NOTIFICATION_PACKAGE,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003316 getPackageName());
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08003317 values.put(Downloads.Impl.COLUMN_NOTIFICATION_CLASS,
Leon Scrogginsa563d092010-04-19 16:53:49 -04003318 OpenDownloadReceiver.class.getCanonicalName());
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08003319 values.put(Downloads.Impl.COLUMN_VISIBILITY,
3320 Downloads.Impl.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
3321 values.put(Downloads.Impl.COLUMN_MIME_TYPE, mimetype);
3322 values.put(Downloads.Impl.COLUMN_FILE_NAME_HINT, filename);
Kristian Monsenfa52d172010-03-25 18:29:21 +00003323 values.put(Downloads.Impl.COLUMN_DESCRIPTION, webAddress.mHost);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003324 if (contentLength > 0) {
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08003325 values.put(Downloads.Impl.COLUMN_TOTAL_BYTES, contentLength);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003326 }
3327 if (mimetype == null) {
3328 // We must have long pressed on a link or image to download it. We
3329 // are not sure of the mimetype in this case, so do a head request
3330 new FetchUrlMimeType(this).execute(values);
3331 } else {
3332 final Uri contentUri =
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08003333 getContentResolver().insert(Downloads.Impl.CONTENT_URI, values);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003334 }
Leon Scroggins9191a7f2010-03-18 14:44:44 -04003335 Toast.makeText(this, R.string.download_pending, Toast.LENGTH_SHORT)
3336 .show();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003337 }
3338
Grace Kloba22ac16e2009-10-07 18:00:23 -07003339 // -------------------------------------------------------------------------
3340
The Android Open Source Project0c908882009-03-03 19:32:16 -08003341 /**
3342 * Resets the lock icon. This method is called when we start a new load and
3343 * know the url to be loaded.
3344 */
3345 private void resetLockIcon(String url) {
3346 // Save the lock-icon state (we revert to it if the load gets cancelled)
Grace Kloba22ac16e2009-10-07 18:00:23 -07003347 mTabControl.getCurrentTab().resetLockIcon(url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003348 updateLockIconImage(LOCK_ICON_UNSECURE);
3349 }
3350
The Android Open Source Project0c908882009-03-03 19:32:16 -08003351 /**
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04003352 * Update the lock icon to correspond to our latest state.
3353 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003354 private void updateLockIconToLatest() {
Leon Scroggins91f65fc2010-06-29 13:52:39 -04003355 Tab t = mTabControl.getCurrentTab();
3356 if (t != null) {
3357 updateLockIconImage(t.getLockIconType());
3358 }
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04003359 }
3360
3361 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08003362 * Updates the lock-icon image in the title-bar.
3363 */
3364 private void updateLockIconImage(int lockIconType) {
3365 Drawable d = null;
3366 if (lockIconType == LOCK_ICON_SECURE) {
3367 d = mSecLockIcon;
3368 } else if (lockIconType == LOCK_ICON_MIXED) {
3369 d = mMixLockIcon;
3370 }
Leon Scroggins68579392009-09-15 15:31:54 -04003371 mTitleBar.setLock(d);
Michael Kolba2b2ba82010-08-04 17:54:03 -07003372 mFakeTitleBar.setLock(d);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003373 }
3374
3375 /**
3376 * Displays a page-info dialog.
3377 * @param tab The tab to show info about
3378 * @param fromShowSSLCertificateOnError The flag that indicates whether
3379 * this dialog was opened from the SSL-certificate-on-error dialog or
3380 * not. This is important, since we need to know whether to return to
3381 * the parent dialog or simply dismiss.
3382 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003383 private void showPageInfo(final Tab tab,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003384 final boolean fromShowSSLCertificateOnError) {
3385 final LayoutInflater factory = LayoutInflater
3386 .from(this);
3387
3388 final View pageInfoView = factory.inflate(R.layout.page_info, null);
3389
3390 final WebView view = tab.getWebView();
3391
3392 String url = null;
3393 String title = null;
3394
3395 if (view == null) {
3396 url = tab.getUrl();
3397 title = tab.getTitle();
3398 } else if (view == mTabControl.getCurrentWebView()) {
3399 // Use the cached title and url if this is the current WebView
3400 url = mUrl;
3401 title = mTitle;
3402 } else {
3403 url = view.getUrl();
3404 title = view.getTitle();
3405 }
3406
3407 if (url == null) {
3408 url = "";
3409 }
3410 if (title == null) {
3411 title = "";
3412 }
3413
3414 ((TextView) pageInfoView.findViewById(R.id.address)).setText(url);
3415 ((TextView) pageInfoView.findViewById(R.id.title)).setText(title);
3416
3417 mPageInfoView = tab;
Leon Scrogginsc7b92f82010-01-11 18:17:31 -05003418 mPageInfoFromShowSSLCertificateOnError = fromShowSSLCertificateOnError;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003419
3420 AlertDialog.Builder alertDialogBuilder =
3421 new AlertDialog.Builder(this)
3422 .setTitle(R.string.page_info).setIcon(android.R.drawable.ic_dialog_info)
3423 .setView(pageInfoView)
3424 .setPositiveButton(
3425 R.string.ok,
3426 new DialogInterface.OnClickListener() {
3427 public void onClick(DialogInterface dialog,
3428 int whichButton) {
3429 mPageInfoDialog = null;
3430 mPageInfoView = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003431
3432 // if we came here from the SSL error dialog
3433 if (fromShowSSLCertificateOnError) {
3434 // go back to the SSL error dialog
3435 showSSLCertificateOnError(
3436 mSSLCertificateOnErrorView,
3437 mSSLCertificateOnErrorHandler,
3438 mSSLCertificateOnErrorError);
3439 }
3440 }
3441 })
3442 .setOnCancelListener(
3443 new DialogInterface.OnCancelListener() {
3444 public void onCancel(DialogInterface dialog) {
3445 mPageInfoDialog = null;
3446 mPageInfoView = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003447
3448 // if we came here from the SSL error dialog
3449 if (fromShowSSLCertificateOnError) {
3450 // go back to the SSL error dialog
3451 showSSLCertificateOnError(
3452 mSSLCertificateOnErrorView,
3453 mSSLCertificateOnErrorHandler,
3454 mSSLCertificateOnErrorError);
3455 }
3456 }
3457 });
3458
3459 // if we have a main top-level page SSL certificate set or a certificate
3460 // error
3461 if (fromShowSSLCertificateOnError ||
3462 (view != null && view.getCertificate() != null)) {
3463 // add a 'View Certificate' button
3464 alertDialogBuilder.setNeutralButton(
3465 R.string.view_certificate,
3466 new DialogInterface.OnClickListener() {
3467 public void onClick(DialogInterface dialog,
3468 int whichButton) {
3469 mPageInfoDialog = null;
3470 mPageInfoView = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003471
3472 // if we came here from the SSL error dialog
3473 if (fromShowSSLCertificateOnError) {
3474 // go back to the SSL error dialog
3475 showSSLCertificateOnError(
3476 mSSLCertificateOnErrorView,
3477 mSSLCertificateOnErrorHandler,
3478 mSSLCertificateOnErrorError);
3479 } else {
3480 // otherwise, display the top-most certificate from
3481 // the chain
3482 if (view.getCertificate() != null) {
3483 showSSLCertificate(tab);
3484 }
3485 }
3486 }
3487 });
3488 }
3489
3490 mPageInfoDialog = alertDialogBuilder.show();
3491 }
3492
3493 /**
3494 * Displays the main top-level page SSL certificate dialog
3495 * (accessible from the Page-Info dialog).
3496 * @param tab The tab to show certificate for.
3497 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003498 private void showSSLCertificate(final Tab tab) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003499 final View certificateView =
3500 inflateCertificateView(tab.getWebView().getCertificate());
3501 if (certificateView == null) {
3502 return;
3503 }
3504
3505 LayoutInflater factory = LayoutInflater.from(this);
3506
3507 final LinearLayout placeholder =
3508 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3509
3510 LinearLayout ll = (LinearLayout) factory.inflate(
3511 R.layout.ssl_success, placeholder);
3512 ((TextView)ll.findViewById(R.id.success))
3513 .setText(R.string.ssl_certificate_is_valid);
3514
3515 mSSLCertificateView = tab;
3516 mSSLCertificateDialog =
3517 new AlertDialog.Builder(this)
3518 .setTitle(R.string.ssl_certificate).setIcon(
3519 R.drawable.ic_dialog_browser_certificate_secure)
3520 .setView(certificateView)
3521 .setPositiveButton(R.string.ok,
3522 new DialogInterface.OnClickListener() {
3523 public void onClick(DialogInterface dialog,
3524 int whichButton) {
3525 mSSLCertificateDialog = null;
3526 mSSLCertificateView = null;
3527
3528 showPageInfo(tab, false);
3529 }
3530 })
3531 .setOnCancelListener(
3532 new DialogInterface.OnCancelListener() {
3533 public void onCancel(DialogInterface dialog) {
3534 mSSLCertificateDialog = null;
3535 mSSLCertificateView = null;
3536
3537 showPageInfo(tab, false);
3538 }
3539 })
3540 .show();
3541 }
3542
3543 /**
3544 * Displays the SSL error certificate dialog.
3545 * @param view The target web-view.
3546 * @param handler The SSL error handler responsible for cancelling the
3547 * connection that resulted in an SSL error or proceeding per user request.
3548 * @param error The SSL error object.
3549 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003550 void showSSLCertificateOnError(
The Android Open Source Project0c908882009-03-03 19:32:16 -08003551 final WebView view, final SslErrorHandler handler, final SslError error) {
3552
3553 final View certificateView =
3554 inflateCertificateView(error.getCertificate());
3555 if (certificateView == null) {
3556 return;
3557 }
3558
3559 LayoutInflater factory = LayoutInflater.from(this);
3560
3561 final LinearLayout placeholder =
3562 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3563
3564 if (error.hasError(SslError.SSL_UNTRUSTED)) {
3565 LinearLayout ll = (LinearLayout)factory
3566 .inflate(R.layout.ssl_warning, placeholder);
3567 ((TextView)ll.findViewById(R.id.warning))
3568 .setText(R.string.ssl_untrusted);
3569 }
3570
3571 if (error.hasError(SslError.SSL_IDMISMATCH)) {
3572 LinearLayout ll = (LinearLayout)factory
3573 .inflate(R.layout.ssl_warning, placeholder);
3574 ((TextView)ll.findViewById(R.id.warning))
3575 .setText(R.string.ssl_mismatch);
3576 }
3577
3578 if (error.hasError(SslError.SSL_EXPIRED)) {
3579 LinearLayout ll = (LinearLayout)factory
3580 .inflate(R.layout.ssl_warning, placeholder);
3581 ((TextView)ll.findViewById(R.id.warning))
3582 .setText(R.string.ssl_expired);
3583 }
3584
3585 if (error.hasError(SslError.SSL_NOTYETVALID)) {
3586 LinearLayout ll = (LinearLayout)factory
3587 .inflate(R.layout.ssl_warning, placeholder);
3588 ((TextView)ll.findViewById(R.id.warning))
3589 .setText(R.string.ssl_not_yet_valid);
3590 }
3591
3592 mSSLCertificateOnErrorHandler = handler;
3593 mSSLCertificateOnErrorView = view;
3594 mSSLCertificateOnErrorError = error;
3595 mSSLCertificateOnErrorDialog =
3596 new AlertDialog.Builder(this)
3597 .setTitle(R.string.ssl_certificate).setIcon(
3598 R.drawable.ic_dialog_browser_certificate_partially_secure)
3599 .setView(certificateView)
3600 .setPositiveButton(R.string.ok,
3601 new DialogInterface.OnClickListener() {
3602 public void onClick(DialogInterface dialog,
3603 int whichButton) {
3604 mSSLCertificateOnErrorDialog = null;
3605 mSSLCertificateOnErrorView = null;
3606 mSSLCertificateOnErrorHandler = null;
3607 mSSLCertificateOnErrorError = null;
3608
Grace Kloba22ac16e2009-10-07 18:00:23 -07003609 view.getWebViewClient().onReceivedSslError(
3610 view, handler, error);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003611 }
3612 })
3613 .setNeutralButton(R.string.page_info_view,
3614 new DialogInterface.OnClickListener() {
3615 public void onClick(DialogInterface dialog,
3616 int whichButton) {
3617 mSSLCertificateOnErrorDialog = null;
3618
3619 // do not clear the dialog state: we will
3620 // need to show the dialog again once the
3621 // user is done exploring the page-info details
3622
3623 showPageInfo(mTabControl.getTabFromView(view),
3624 true);
3625 }
3626 })
3627 .setOnCancelListener(
3628 new DialogInterface.OnCancelListener() {
3629 public void onCancel(DialogInterface dialog) {
3630 mSSLCertificateOnErrorDialog = null;
3631 mSSLCertificateOnErrorView = null;
3632 mSSLCertificateOnErrorHandler = null;
3633 mSSLCertificateOnErrorError = null;
3634
Grace Kloba22ac16e2009-10-07 18:00:23 -07003635 view.getWebViewClient().onReceivedSslError(
3636 view, handler, error);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003637 }
3638 })
3639 .show();
3640 }
3641
3642 /**
3643 * Inflates the SSL certificate view (helper method).
3644 * @param certificate The SSL certificate.
3645 * @return The resultant certificate view with issued-to, issued-by,
3646 * issued-on, expires-on, and possibly other fields set.
3647 * If the input certificate is null, returns null.
3648 */
3649 private View inflateCertificateView(SslCertificate certificate) {
3650 if (certificate == null) {
3651 return null;
3652 }
3653
3654 LayoutInflater factory = LayoutInflater.from(this);
3655
3656 View certificateView = factory.inflate(
3657 R.layout.ssl_certificate, null);
3658
3659 // issued to:
3660 SslCertificate.DName issuedTo = certificate.getIssuedTo();
3661 if (issuedTo != null) {
3662 ((TextView) certificateView.findViewById(R.id.to_common))
3663 .setText(issuedTo.getCName());
3664 ((TextView) certificateView.findViewById(R.id.to_org))
3665 .setText(issuedTo.getOName());
3666 ((TextView) certificateView.findViewById(R.id.to_org_unit))
3667 .setText(issuedTo.getUName());
3668 }
3669
3670 // issued by:
3671 SslCertificate.DName issuedBy = certificate.getIssuedBy();
3672 if (issuedBy != null) {
3673 ((TextView) certificateView.findViewById(R.id.by_common))
3674 .setText(issuedBy.getCName());
3675 ((TextView) certificateView.findViewById(R.id.by_org))
3676 .setText(issuedBy.getOName());
3677 ((TextView) certificateView.findViewById(R.id.by_org_unit))
3678 .setText(issuedBy.getUName());
3679 }
3680
3681 // issued on:
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003682 String issuedOn = formatCertificateDate(
3683 certificate.getValidNotBeforeDate());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003684 ((TextView) certificateView.findViewById(R.id.issued_on))
3685 .setText(issuedOn);
3686
3687 // expires on:
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003688 String expiresOn = formatCertificateDate(
3689 certificate.getValidNotAfterDate());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003690 ((TextView) certificateView.findViewById(R.id.expires_on))
3691 .setText(expiresOn);
3692
3693 return certificateView;
3694 }
3695
3696 /**
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003697 * Formats the certificate date to a properly localized date string.
The Android Open Source Project0c908882009-03-03 19:32:16 -08003698 * @return Properly localized version of the certificate date string and
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003699 * the "" if it fails to localize.
The Android Open Source Project0c908882009-03-03 19:32:16 -08003700 */
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003701 private String formatCertificateDate(Date certificateDate) {
3702 if (certificateDate == null) {
3703 return "";
The Android Open Source Project0c908882009-03-03 19:32:16 -08003704 }
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003705 String formattedDate = DateFormat.getDateFormat(this).format(certificateDate);
3706 if (formattedDate == null) {
3707 return "";
3708 }
3709 return formattedDate;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003710 }
3711
3712 /**
3713 * Displays an http-authentication dialog.
3714 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003715 void showHttpAuthentication(final HttpAuthHandler handler,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003716 final String host, final String realm, final String title,
3717 final String name, final String password, int focusId) {
3718 LayoutInflater factory = LayoutInflater.from(this);
3719 final View v = factory
3720 .inflate(R.layout.http_authentication, null);
3721 if (name != null) {
3722 ((EditText) v.findViewById(R.id.username_edit)).setText(name);
3723 }
3724 if (password != null) {
3725 ((EditText) v.findViewById(R.id.password_edit)).setText(password);
3726 }
3727
3728 String titleText = title;
3729 if (titleText == null) {
3730 titleText = getText(R.string.sign_in_to).toString().replace(
3731 "%s1", host).replace("%s2", realm);
3732 }
3733
3734 mHttpAuthHandler = handler;
3735 AlertDialog dialog = new AlertDialog.Builder(this)
3736 .setTitle(titleText)
3737 .setIcon(android.R.drawable.ic_dialog_alert)
3738 .setView(v)
3739 .setPositiveButton(R.string.action,
3740 new DialogInterface.OnClickListener() {
3741 public void onClick(DialogInterface dialog,
3742 int whichButton) {
3743 String nm = ((EditText) v
3744 .findViewById(R.id.username_edit))
3745 .getText().toString();
3746 String pw = ((EditText) v
3747 .findViewById(R.id.password_edit))
3748 .getText().toString();
3749 BrowserActivity.this.setHttpAuthUsernamePassword
3750 (host, realm, nm, pw);
3751 handler.proceed(nm, pw);
3752 mHttpAuthenticationDialog = null;
3753 mHttpAuthHandler = null;
3754 }})
3755 .setNegativeButton(R.string.cancel,
3756 new DialogInterface.OnClickListener() {
3757 public void onClick(DialogInterface dialog,
3758 int whichButton) {
3759 handler.cancel();
3760 BrowserActivity.this.resetTitleAndRevertLockIcon();
3761 mHttpAuthenticationDialog = null;
3762 mHttpAuthHandler = null;
3763 }})
3764 .setOnCancelListener(new DialogInterface.OnCancelListener() {
3765 public void onCancel(DialogInterface dialog) {
3766 handler.cancel();
3767 BrowserActivity.this.resetTitleAndRevertLockIcon();
3768 mHttpAuthenticationDialog = null;
3769 mHttpAuthHandler = null;
3770 }})
3771 .create();
3772 // Make the IME appear when the dialog is displayed if applicable.
3773 dialog.getWindow().setSoftInputMode(
3774 WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
3775 dialog.show();
3776 if (focusId != 0) {
3777 dialog.findViewById(focusId).requestFocus();
3778 } else {
3779 v.findViewById(R.id.username_edit).requestFocus();
3780 }
3781 mHttpAuthenticationDialog = dialog;
3782 }
3783
3784 public int getProgress() {
3785 WebView w = mTabControl.getCurrentWebView();
3786 if (w != null) {
3787 return w.getProgress();
3788 } else {
3789 return 100;
3790 }
3791 }
3792
3793 /**
3794 * Set HTTP authentication password.
3795 *
3796 * @param host The host for the password
3797 * @param realm The realm for the password
3798 * @param username The username for the password. If it is null, it means
3799 * password can't be saved.
3800 * @param password The password
3801 */
3802 public void setHttpAuthUsernamePassword(String host, String realm,
3803 String username,
3804 String password) {
Steve Block95a53b22010-03-25 17:24:58 +00003805 WebView w = getTopWindow();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003806 if (w != null) {
3807 w.setHttpAuthUsernamePassword(host, realm, username, password);
3808 }
3809 }
3810
3811 /**
3812 * connectivity manager says net has come or gone... inform the user
3813 * @param up true if net has come up, false if net has gone down
3814 */
3815 public void onNetworkToggle(boolean up) {
3816 if (up == mIsNetworkUp) {
3817 return;
3818 } else if (up) {
3819 mIsNetworkUp = true;
3820 if (mAlertDialog != null) {
3821 mAlertDialog.cancel();
3822 mAlertDialog = null;
3823 }
3824 } else {
3825 mIsNetworkUp = false;
Patrick Scotteb6ab2a2009-09-16 10:00:17 -04003826 if (mInLoad) {
3827 createAndShowNetworkDialog();
3828 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003829 }
3830 WebView w = mTabControl.getCurrentWebView();
3831 if (w != null) {
3832 w.setNetworkAvailable(up);
3833 }
3834 }
3835
Grace Kloba22ac16e2009-10-07 18:00:23 -07003836 boolean isNetworkUp() {
3837 return mIsNetworkUp;
3838 }
3839
Patrick Scotteb6ab2a2009-09-16 10:00:17 -04003840 // This method shows the network dialog alerting the user that the net is
3841 // down. It will only show the dialog if mAlertDialog is null.
3842 private void createAndShowNetworkDialog() {
3843 if (mAlertDialog == null) {
3844 mAlertDialog = new AlertDialog.Builder(this)
3845 .setTitle(R.string.loadSuspendedTitle)
3846 .setMessage(R.string.loadSuspended)
3847 .setPositiveButton(R.string.ok, null)
3848 .show();
3849 }
3850 }
3851
The Android Open Source Project0c908882009-03-03 19:32:16 -08003852 @Override
3853 protected void onActivityResult(int requestCode, int resultCode,
3854 Intent intent) {
Grace Klobabb394f32009-11-19 10:26:37 -08003855 if (getTopWindow() == null) return;
3856
The Android Open Source Project0c908882009-03-03 19:32:16 -08003857 switch (requestCode) {
3858 case COMBO_PAGE:
3859 if (resultCode == RESULT_OK && intent != null) {
3860 String data = intent.getAction();
3861 Bundle extras = intent.getExtras();
3862 if (extras != null && extras.getBoolean("new_window", false)) {
Michael Kolb68792c82010-08-09 16:39:18 -07003863 openTab(data, false);
3864 } else if ((extras != null) &&
3865 extras.getBoolean(CombinedBookmarkHistoryActivity.NEWTAB_MODE)) {
3866 openTab(data, true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003867 } else {
Michael Kolb68792c82010-08-09 16:39:18 -07003868 final Tab currentTab = mTabControl.getCurrentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04003869 dismissSubWindow(currentTab);
3870 if (data != null && data.length() != 0) {
Leon Scroggins92472e82010-02-17 16:32:28 -05003871 loadUrl(getTopWindow(), data);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003872 }
3873 }
Michael Kolb3f65c382010-08-20 15:31:16 -07003874 } else if (resultCode == RESULT_CANCELED) {
3875 if (intent != null) {
3876 float evtx = intent.getFloatExtra(CombinedBookmarkHistoryActivity.EVT_X, -1);
3877 float evty = intent.getFloatExtra(CombinedBookmarkHistoryActivity.EVT_Y, -1);
3878 long now = System.currentTimeMillis();
3879 MotionEvent evt = MotionEvent.obtain(now, now,
3880 MotionEvent.ACTION_DOWN, evtx, evty, 0);
3881 dispatchTouchEvent(evt);
3882 MotionEvent up = MotionEvent.obtain(evt);
3883 up.setAction(MotionEvent.ACTION_UP);
3884 dispatchTouchEvent(up);
3885 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003886 }
Leon Scrogginsfde97462010-01-11 13:06:21 -05003887 // Deliberately fall through to PREFERENCES_PAGE, since the
3888 // same extra may be attached to the COMBO_PAGE
3889 case PREFERENCES_PAGE:
3890 if (resultCode == RESULT_OK && intent != null) {
3891 String action = intent.getStringExtra(Intent.EXTRA_TEXT);
3892 if (BrowserSettings.PREF_CLEAR_HISTORY.equals(action)) {
3893 mTabControl.removeParentChildRelationShips();
3894 }
3895 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003896 break;
Leon Scroggins8d5fa432009-10-02 15:55:59 -04003897 // Choose a file from the file picker.
3898 case FILE_SELECTED:
3899 if (null == mUploadMessage) break;
3900 Uri result = intent == null || resultCode != RESULT_OK ? null
3901 : intent.getData();
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003902
3903 // As we ask the camera to save the result of the user taking
3904 // a picture, the camera application does not return anything other
3905 // than RESULT_OK. So we need to check whether the file we expected
3906 // was written to disk in the in the case that we
3907 // did not get an intent returned but did get a RESULT_OK. If it was,
3908 // we assume that this result has came back from the camera.
3909 if (result == null && intent == null && resultCode == RESULT_OK) {
3910 File cameraFile = new File(mCameraFilePath);
3911 if (cameraFile.exists()) {
3912 result = Uri.fromFile(cameraFile);
Ben Murdoch07d34732010-05-27 18:34:46 +01003913 // Broadcast to the media scanner that we have a new photo
3914 // so it will be added into the gallery for the user.
3915 sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, result));
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003916 }
3917 }
Leon Scroggins8d5fa432009-10-02 15:55:59 -04003918 mUploadMessage.onReceiveValue(result);
3919 mUploadMessage = null;
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003920 mCameraFilePath = null;
Leon Scroggins8d5fa432009-10-02 15:55:59 -04003921 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003922 default:
3923 break;
3924 }
Leon Scroggins30444232009-09-04 18:36:20 -04003925 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003926 }
3927
3928 /*
3929 * This method is called as a result of the user selecting the options
Leon Scrogginsf08809b2010-01-21 09:27:46 -05003930 * menu to see the download window. It shows the download window on top of
3931 * the current window.
The Android Open Source Project0c908882009-03-03 19:32:16 -08003932 */
Leon Scrogginsf08809b2010-01-21 09:27:46 -05003933 private void viewDownloads(Uri downloadRecord) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003934 Intent intent = new Intent(this,
3935 BrowserDownloadPage.class);
3936 intent.setData(downloadRecord);
Grace Kloba22ac16e2009-10-07 18:00:23 -07003937 startActivityForResult(intent, BrowserActivity.DOWNLOAD_PAGE);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003938
3939 }
3940
Ben Murdocheecb4e62010-07-06 16:30:38 +01003941 /* package*/ void promptAddOrInstallBookmark() {
3942 final Tab current = mTabControl.getCurrentTab();
3943 Resources resources = getResources();
3944 CharSequence[] choices = {
3945 resources.getString(R.string.save_to_bookmarks),
3946 resources.getString(R.string.create_shortcut_bookmark)
3947 };
3948
3949 AlertDialog.Builder builder = new AlertDialog.Builder(this);
3950 builder.setTitle(R.string.add_new_bookmark);
3951 builder.setItems(choices, new DialogInterface.OnClickListener() {
3952 public void onClick(DialogInterface dialog, int item) {
3953 if (item == 0) {
3954 bookmarkCurrentPage();
3955 } else if (item == 1) {
3956 current.populatePickerData();
3957 String touchIconUrl = mTabControl.getCurrentWebView().getTouchIconUrl();
3958 if (touchIconUrl != null) {
3959 // Download the touch icon for this site then save it to the
3960 // homescreen.
3961 Bundle b = new Bundle();
3962 b.putString("url", current.getUrl());
3963 b.putString("title", current.getTitle());
3964 b.putParcelable("favicon", current.getFavicon());
3965 Message msg = mHandler.obtainMessage(TOUCH_ICON_DOWNLOADED);
3966 msg.setData(b);
Ben Murdochccb5de02010-07-19 18:38:17 +01003967 new DownloadTouchIcon(BrowserActivity.this, msg,
Ben Murdocheecb4e62010-07-06 16:30:38 +01003968 mTabControl.getCurrentWebView().getSettings()
3969 .getUserAgentString()).execute(touchIconUrl);
3970 } else {
3971 // add to homescreen, can do it immediately as there is no touch
3972 // icon.
3973 showSaveToHomescreenDialog(current.getUrl(), current.getTitle(),
3974 null, current.getFavicon());
3975 }
3976 }
3977 }
3978 });
3979 builder.create().show();
3980 }
3981
Leon Scroggins160a7e72009-08-14 18:28:01 -04003982 /**
3983 * Open the Go page.
3984 * @param startWithHistory If true, open starting on the history tab.
3985 * Otherwise, start with the bookmarks tab.
Leon Scroggins160a7e72009-08-14 18:28:01 -04003986 */
Michael Kolb68792c82010-08-09 16:39:18 -07003987 /* package */ void bookmarksOrHistoryPicker(boolean startWithHistory, boolean newTabMode) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003988 WebView current = mTabControl.getCurrentWebView();
3989 if (current == null) {
3990 return;
3991 }
3992 Intent intent = new Intent(this,
3993 CombinedBookmarkHistoryActivity.class);
3994 String title = current.getTitle();
3995 String url = current.getUrl();
Ben Murdoch87cc65d2010-06-29 20:34:10 +01003996 Bitmap thumbnail = createScreenshot(current, getDesiredThumbnailWidth(this),
3997 getDesiredThumbnailHeight(this));
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01003998
The Android Open Source Project0c908882009-03-03 19:32:16 -08003999 // Just in case the user opens bookmarks before a page finishes loading
4000 // so the current history item, and therefore the page, is null.
4001 if (null == url) {
4002 url = mLastEnteredUrl;
4003 // This can happen.
4004 if (null == url) {
4005 url = mSettings.getHomePage();
4006 }
4007 }
4008 // In case the web page has not yet received its associated title.
4009 if (title == null) {
4010 title = url;
4011 }
4012 intent.putExtra("title", title);
4013 intent.putExtra("url", url);
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01004014 intent.putExtra("thumbnail", thumbnail);
Leon Scroggins30444232009-09-04 18:36:20 -04004015 // Disable opening in a new window if we have maxed out the windows
Grace Kloba22ac16e2009-10-07 18:00:23 -07004016 intent.putExtra("disable_new_window", !mTabControl.canCreateNewTab());
Patrick Scott3918d442009-08-04 13:22:29 -04004017 intent.putExtra("touch_icon_url", current.getTouchIconUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08004018 if (startWithHistory) {
Jeff Hamilton64144e42010-08-18 16:31:59 -05004019 intent.putExtra(CombinedBookmarkHistoryActivity.STARTING_FRAGMENT,
4020 CombinedBookmarkHistoryActivity.FRAGMENT_ID_HISTORY);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004021 }
Michael Kolb3f65c382010-08-20 15:31:16 -07004022 if (mXLargeScreenSize) {
4023 showFakeTitleBar();
4024 int titleBarHeight = ((TitleBarXLarge)mFakeTitleBar).getHeightWithoutProgress();
4025 intent.putExtra(CombinedBookmarkHistoryActivity.EXTRA_TOP,
4026 mTabBar.getBottom() + titleBarHeight);
4027 intent.putExtra(CombinedBookmarkHistoryActivity.EXTRA_HEIGHT,
4028 getTopWindow().getHeight() - titleBarHeight);
Michael Kolb68792c82010-08-09 16:39:18 -07004029 intent.putExtra(CombinedBookmarkHistoryActivity.NEWTAB_MODE, true);
4030 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08004031 startActivityForResult(intent, COMBO_PAGE);
4032 }
4033
Ben Murdocheecb4e62010-07-06 16:30:38 +01004034 private void showSaveToHomescreenDialog(String url, String title, Bitmap touchIcon,
4035 Bitmap favicon) {
4036 Intent intent = new Intent(this, SaveToHomescreenDialog.class);
4037
4038 // Just in case the user tries to save before a page finishes loading
4039 // so the current history item, and therefore the page, is null.
4040 if (null == url) {
4041 url = mLastEnteredUrl;
4042 // This can happen.
4043 if (null == url) {
4044 url = mSettings.getHomePage();
4045 }
4046 }
4047
4048 // In case the web page has not yet received its associated title.
4049 if (title == null) {
4050 title = url;
4051 }
4052
4053 intent.putExtra("title", title);
4054 intent.putExtra("url", url);
4055 intent.putExtra("favicon", favicon);
4056 intent.putExtra("touchIcon", touchIcon);
4057 startActivity(intent);
4058 }
4059
4060
The Android Open Source Project0c908882009-03-03 19:32:16 -08004061 // Called when loading from context menu or LOAD_URL message
Leon Scroggins92472e82010-02-17 16:32:28 -05004062 private void loadUrlFromContext(WebView view, String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08004063 // In case the user enters nothing.
4064 if (url != null && url.length() != 0 && view != null) {
4065 url = smartUrlFilter(url);
Grace Kloba22ac16e2009-10-07 18:00:23 -07004066 if (!view.getWebViewClient().shouldOverrideUrlLoading(view, url)) {
Leon Scroggins92472e82010-02-17 16:32:28 -05004067 loadUrl(view, url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004068 }
4069 }
4070 }
4071
Leon Scroggins92472e82010-02-17 16:32:28 -05004072 /**
4073 * Load the URL into the given WebView and update the title bar
4074 * to reflect the new load. Call this instead of WebView.loadUrl
4075 * directly.
4076 * @param view The WebView used to load url.
4077 * @param url The URL to load.
4078 */
4079 private void loadUrl(WebView view, String url) {
4080 updateTitleBarForNewLoad(view, url);
4081 view.loadUrl(url);
4082 }
4083
4084 /**
4085 * Load UrlData into a Tab and update the title bar to reflect the new
4086 * load. Call this instead of UrlData.loadIn directly.
4087 * @param t The Tab used to load.
4088 * @param data The UrlData being loaded.
4089 */
4090 private void loadUrlDataIn(Tab t, UrlData data) {
4091 updateTitleBarForNewLoad(t.getWebView(), data.mUrl);
4092 data.loadIn(t);
4093 }
4094
4095 /**
4096 * If the WebView is the top window, update the title bar to reflect
4097 * loading the new URL. i.e. set its text, clear the favicon (which
4098 * will be set once the page begins loading), and set the progress to
4099 * INITIAL_PROGRESS to show that the page has begun to load. Called
4100 * by loadUrl and loadUrlDataIn.
4101 * @param view The WebView that is starting a load.
4102 * @param url The URL that is being loaded.
4103 */
4104 private void updateTitleBarForNewLoad(WebView view, String url) {
4105 if (view == getTopWindow()) {
4106 setUrlTitle(url, null);
4107 setFavicon(null);
4108 onProgressChanged(view, INITIAL_PROGRESS);
4109 }
4110 }
4111
The Android Open Source Project0c908882009-03-03 19:32:16 -08004112 private String smartUrlFilter(Uri inUri) {
4113 if (inUri != null) {
4114 return smartUrlFilter(inUri.toString());
4115 }
4116 return null;
4117 }
4118
Feng Qianb34f87a2009-03-24 21:27:26 -07004119 protected static final Pattern ACCEPTED_URI_SCHEMA = Pattern.compile(
The Android Open Source Project0c908882009-03-03 19:32:16 -08004120 "(?i)" + // switch on case insensitive matching
4121 "(" + // begin group for schema
4122 "(?:http|https|file):\\/\\/" +
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004123 "|(?:inline|data|about|content|javascript):" +
The Android Open Source Project0c908882009-03-03 19:32:16 -08004124 ")" +
4125 "(.*)" );
4126
4127 /**
4128 * Attempts to determine whether user input is a URL or search
4129 * terms. Anything with a space is passed to search.
4130 *
4131 * Converts to lowercase any mistakenly uppercased schema (i.e.,
4132 * "Http://" converts to "http://"
4133 *
4134 * @return Original or modified URL
4135 *
4136 */
4137 String smartUrlFilter(String url) {
4138
4139 String inUrl = url.trim();
4140 boolean hasSpace = inUrl.indexOf(' ') != -1;
4141
4142 Matcher matcher = ACCEPTED_URI_SCHEMA.matcher(inUrl);
4143 if (matcher.matches()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08004144 // force scheme to lowercase
4145 String scheme = matcher.group(1);
4146 String lcScheme = scheme.toLowerCase();
4147 if (!lcScheme.equals(scheme)) {
Mitsuru Oshima123ecfb2009-05-18 19:11:14 -07004148 inUrl = lcScheme + matcher.group(2);
4149 }
4150 if (hasSpace) {
4151 inUrl = inUrl.replace(" ", "%20");
The Android Open Source Project0c908882009-03-03 19:32:16 -08004152 }
4153 return inUrl;
4154 }
4155 if (hasSpace) {
Satish Sampath565505b2009-05-29 15:37:27 +01004156 // FIXME: Is this the correct place to add to searches?
4157 // what if someone else calls this function?
4158 int shortcut = parseUrlShortcut(inUrl);
4159 if (shortcut != SHORTCUT_INVALID) {
4160 Browser.addSearchUrl(mResolver, inUrl);
4161 String query = inUrl.substring(2);
4162 switch (shortcut) {
4163 case SHORTCUT_GOOGLE_SEARCH:
Grace Kloba47fdfdb2009-06-30 11:15:34 -07004164 return URLUtil.composeSearchUrl(query, QuickSearch_G, QUERY_PLACE_HOLDER);
Satish Sampath565505b2009-05-29 15:37:27 +01004165 case SHORTCUT_WIKIPEDIA_SEARCH:
4166 return URLUtil.composeSearchUrl(query, QuickSearch_W, QUERY_PLACE_HOLDER);
4167 case SHORTCUT_DICTIONARY_SEARCH:
4168 return URLUtil.composeSearchUrl(query, QuickSearch_D, QUERY_PLACE_HOLDER);
4169 case SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH:
The Android Open Source Project0c908882009-03-03 19:32:16 -08004170 // FIXME: we need location in this case
Satish Sampath565505b2009-05-29 15:37:27 +01004171 return URLUtil.composeSearchUrl(query, QuickSearch_L, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004172 }
4173 }
4174 } else {
Dan Egnor5ee906c2009-11-18 12:11:49 -08004175 if (Patterns.WEB_URL.matcher(inUrl).matches()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08004176 return URLUtil.guessUrl(inUrl);
4177 }
4178 }
4179
4180 Browser.addSearchUrl(mResolver, inUrl);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07004181 return URLUtil.composeSearchUrl(inUrl, QuickSearch_G, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004182 }
4183
Ben Murdochbff2d602009-07-01 20:19:05 +01004184 /* package */ void setShouldShowErrorConsole(boolean flag) {
4185 if (flag == mShouldShowErrorConsole) {
4186 // Nothing to do.
4187 return;
4188 }
4189
4190 mShouldShowErrorConsole = flag;
4191
Grace Kloba22ac16e2009-10-07 18:00:23 -07004192 ErrorConsoleView errorConsole = mTabControl.getCurrentTab()
4193 .getErrorConsole(true);
Ben Murdochbff2d602009-07-01 20:19:05 +01004194
4195 if (flag) {
4196 // Setting the show state of the console will cause it's the layout to be inflated.
4197 if (errorConsole.numberOfErrors() > 0) {
4198 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
4199 } else {
4200 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
4201 }
4202
4203 // Now we can add it to the main view.
4204 mErrorConsoleContainer.addView(errorConsole,
Romain Guy15b8ec62010-01-08 15:06:43 -08004205 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
Ben Murdochbff2d602009-07-01 20:19:05 +01004206 ViewGroup.LayoutParams.WRAP_CONTENT));
4207 } else {
4208 mErrorConsoleContainer.removeView(errorConsole);
4209 }
4210
4211 }
4212
Grace Kloba22ac16e2009-10-07 18:00:23 -07004213 boolean shouldShowErrorConsole() {
4214 return mShouldShowErrorConsole;
4215 }
4216
Andrei Popescu163ab742009-10-20 17:58:23 +01004217 private void setStatusBarVisibility(boolean visible) {
4218 int flag = visible ? 0 : WindowManager.LayoutParams.FLAG_FULLSCREEN;
4219 getWindow().setFlags(flag, WindowManager.LayoutParams.FLAG_FULLSCREEN);
4220 }
4221
Andrei Popescu56199cc2010-01-12 22:39:16 +00004222
4223 private void sendNetworkType(String type, String subtype) {
4224 WebView w = mTabControl.getCurrentWebView();
4225 if (w != null) {
4226 w.setNetworkType(type, subtype);
4227 }
4228 }
4229
Andrei Popescu30995e72010-02-09 16:59:58 +00004230 private void packageChanged(String packageName, boolean wasAdded) {
4231 WebView w = mTabControl.getCurrentWebView();
4232 if (w == null) {
4233 return;
4234 }
4235
4236 if (wasAdded) {
4237 w.addPackageName(packageName);
4238 } else {
4239 w.removePackageName(packageName);
4240 }
4241 }
4242
4243 private void addPackageNames(Set<String> packageNames) {
4244 WebView w = mTabControl.getCurrentWebView();
4245 if (w == null) {
4246 return;
4247 }
4248
4249 w.addPackageNames(packageNames);
4250 }
4251
4252 private void getInstalledPackages() {
4253 AsyncTask<Void, Void, Set<String> > task =
4254 new AsyncTask<Void, Void, Set<String> >() {
Michael Kolbe0a36662010-06-29 10:37:12 -07004255 @Override
Andrei Popescu30995e72010-02-09 16:59:58 +00004256 protected Set<String> doInBackground(Void... unused) {
4257 Set<String> installedPackages = new HashSet<String>();
4258 PackageManager pm = BrowserActivity.this.getPackageManager();
4259 if (pm != null) {
4260 List<PackageInfo> packages = pm.getInstalledPackages(0);
4261 for (PackageInfo p : packages) {
4262 if (BrowserActivity.this.sGoogleApps.contains(p.packageName)) {
4263 installedPackages.add(p.packageName);
4264 }
4265 }
4266 }
4267
4268 return installedPackages;
4269 }
4270
4271 // Executes on the UI thread
Michael Kolbe0a36662010-06-29 10:37:12 -07004272 @Override
Andrei Popescu30995e72010-02-09 16:59:58 +00004273 protected void onPostExecute(Set<String> installedPackages) {
4274 addPackageNames(installedPackages);
4275 }
4276 };
4277 task.execute();
4278 }
4279
Grace Klobaeb6eef42009-09-15 17:56:32 -07004280 final static int LOCK_ICON_UNSECURE = 0;
4281 final static int LOCK_ICON_SECURE = 1;
4282 final static int LOCK_ICON_MIXED = 2;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004283
The Android Open Source Project0c908882009-03-03 19:32:16 -08004284 private BrowserSettings mSettings;
4285 private TabControl mTabControl;
4286 private ContentResolver mResolver;
4287 private FrameLayout mContentView;
Andrei Popescuadc008d2009-06-26 14:11:30 +01004288 private View mCustomView;
4289 private FrameLayout mCustomViewContainer;
Andrei Popescuc9b55562009-07-07 10:51:15 +01004290 private WebChromeClient.CustomViewCallback mCustomViewCallback;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004291
4292 // FIXME, temp address onPrepareMenu performance problem. When we move everything out of
4293 // view, we should rewrite this.
4294 private int mCurrentMenuState = 0;
4295 private int mMenuState = R.id.MAIN_MENU;
Andrei Popescuadc008d2009-06-26 14:11:30 +01004296 private int mOldMenuState = EMPTY_MENU;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004297 private static final int EMPTY_MENU = -1;
4298 private Menu mMenu;
4299
The Android Open Source Project0c908882009-03-03 19:32:16 -08004300 // Used to prevent chording to result in firing two shortcuts immediately
4301 // one after another. Fixes bug 1211714.
4302 boolean mCanChord;
4303
4304 private boolean mInLoad;
4305 private boolean mIsNetworkUp;
Ben Murdochb7cc8b42009-09-28 10:59:09 +01004306 private boolean mDidStopLoad;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004307
Cary Clark1f10cbf2010-03-22 11:45:23 -04004308 /* package */ boolean mActivityInPause = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004309
4310 private boolean mMenuIsDown;
4311
The Android Open Source Project0c908882009-03-03 19:32:16 -08004312 private static boolean mInTrace;
4313
4314 // Performance probe
4315 private static final int[] SYSTEM_CPU_FORMAT = new int[] {
4316 Process.PROC_SPACE_TERM | Process.PROC_COMBINE,
4317 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 1: user time
4318 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 2: nice time
4319 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 3: sys time
4320 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 4: idle time
4321 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 5: iowait time
4322 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 6: irq time
4323 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG // 7: softirq time
4324 };
4325
4326 private long mStart;
4327 private long mProcessStart;
4328 private long mUserStart;
4329 private long mSystemStart;
4330 private long mIdleStart;
4331 private long mIrqStart;
4332
4333 private long mUiStart;
4334
4335 private Drawable mMixLockIcon;
4336 private Drawable mSecLockIcon;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004337
4338 /* hold a ref so we can auto-cancel if necessary */
4339 private AlertDialog mAlertDialog;
4340
The Android Open Source Project0c908882009-03-03 19:32:16 -08004341 // The up-to-date URL and title (these can be different from those stored
4342 // in WebView, since it takes some time for the information in WebView to
4343 // get updated)
4344 private String mUrl;
4345 private String mTitle;
4346
4347 // As PageInfo has different style for landscape / portrait, we have
4348 // to re-open it when configuration changed
4349 private AlertDialog mPageInfoDialog;
Grace Kloba22ac16e2009-10-07 18:00:23 -07004350 private Tab mPageInfoView;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004351 // If the Page-Info dialog is launched from the SSL-certificate-on-error
4352 // dialog, we should not just dismiss it, but should get back to the
4353 // SSL-certificate-on-error dialog. This flag is used to store this state
Leon Scrogginsc7b92f82010-01-11 18:17:31 -05004354 private boolean mPageInfoFromShowSSLCertificateOnError;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004355
4356 // as SSLCertificateOnError has different style for landscape / portrait,
4357 // we have to re-open it when configuration changed
4358 private AlertDialog mSSLCertificateOnErrorDialog;
4359 private WebView mSSLCertificateOnErrorView;
4360 private SslErrorHandler mSSLCertificateOnErrorHandler;
4361 private SslError mSSLCertificateOnErrorError;
4362
4363 // as SSLCertificate has different style for landscape / portrait, we
4364 // have to re-open it when configuration changed
4365 private AlertDialog mSSLCertificateDialog;
Grace Kloba22ac16e2009-10-07 18:00:23 -07004366 private Tab mSSLCertificateView;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004367
4368 // as HttpAuthentication has different style for landscape / portrait, we
4369 // have to re-open it when configuration changed
4370 private AlertDialog mHttpAuthenticationDialog;
4371 private HttpAuthHandler mHttpAuthHandler;
4372
4373 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_PARAMS =
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 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_GRAVITY_CENTER =
4378 new FrameLayout.LayoutParams(
Romain Guy15b8ec62010-01-08 15:06:43 -08004379 ViewGroup.LayoutParams.MATCH_PARENT,
4380 ViewGroup.LayoutParams.MATCH_PARENT,
Andrei Popescuadc008d2009-06-26 14:11:30 +01004381 Gravity.CENTER);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07004382 // Google search
4383 final static String QuickSearch_G = "http://www.google.com/m?q=%s";
The Android Open Source Project0c908882009-03-03 19:32:16 -08004384 // Wikipedia search
4385 final static String QuickSearch_W = "http://en.wikipedia.org/w/index.php?search=%s&go=Go";
4386 // Dictionary search
4387 final static String QuickSearch_D = "http://dictionary.reference.com/search?q=%s";
4388 // Google Mobile Local search
4389 final static String QuickSearch_L = "http://www.google.com/m/search?site=local&q=%s&near=mountain+view";
4390
4391 final static String QUERY_PLACE_HOLDER = "%s";
4392
4393 // "source" parameter for Google search through search key
4394 final static String GOOGLE_SEARCH_SOURCE_SEARCHKEY = "browser-key";
4395 // "source" parameter for Google search through goto menu
4396 final static String GOOGLE_SEARCH_SOURCE_GOTO = "browser-goto";
4397 // "source" parameter for Google search through simplily type
4398 final static String GOOGLE_SEARCH_SOURCE_TYPE = "browser-type";
4399 // "source" parameter for Google search suggested by the browser
4400 final static String GOOGLE_SEARCH_SOURCE_SUGGEST = "browser-suggest";
4401 // "source" parameter for Google search from unknown source
4402 final static String GOOGLE_SEARCH_SOURCE_UNKNOWN = "unknown";
4403
4404 private final static String LOGTAG = "browser";
4405
The Android Open Source Project0c908882009-03-03 19:32:16 -08004406 private String mLastEnteredUrl;
4407
4408 private PowerManager.WakeLock mWakeLock;
4409 private final static int WAKELOCK_TIMEOUT = 5 * 60 * 1000; // 5 minutes
4410
4411 private Toast mStopToast;
4412
Leon Scroggins571b3762010-05-26 10:25:01 -04004413 private TitleBarBase mTitleBar;
Michael Kolba2b2ba82010-08-04 17:54:03 -07004414 private TabBar mTabBar;
Leon Scroggins81db3662009-06-04 17:45:11 -04004415
Ben Murdochbff2d602009-07-01 20:19:05 +01004416 private LinearLayout mErrorConsoleContainer = null;
4417 private boolean mShouldShowErrorConsole = false;
4418
The Android Open Source Project0c908882009-03-03 19:32:16 -08004419 // As the ids are dynamically created, we can't guarantee that they will
4420 // be in sequence, so this static array maps ids to a window number.
4421 final static private int[] WINDOW_SHORTCUT_ID_ARRAY =
4422 { R.id.window_one_menu_id, R.id.window_two_menu_id, R.id.window_three_menu_id,
4423 R.id.window_four_menu_id, R.id.window_five_menu_id, R.id.window_six_menu_id,
4424 R.id.window_seven_menu_id, R.id.window_eight_menu_id };
4425
4426 // monitor platform changes
4427 private IntentFilter mNetworkStateChangedFilter;
4428 private BroadcastReceiver mNetworkStateIntentReceiver;
4429
Grace Klobab4da0ad2009-05-14 14:45:40 -07004430 private BroadcastReceiver mPackageInstallationReceiver;
4431
Bjorn Bringerta7611812010-03-24 11:12:02 +00004432 private SystemAllowGeolocationOrigins mSystemAllowGeolocationOrigins;
4433
The Android Open Source Project0c908882009-03-03 19:32:16 -08004434 // activity requestCode
Nicolas Roard78a98e42009-05-11 13:34:17 +01004435 final static int COMBO_PAGE = 1;
4436 final static int DOWNLOAD_PAGE = 2;
4437 final static int PREFERENCES_PAGE = 3;
Leon Scroggins8d5fa432009-10-02 15:55:59 -04004438 final static int FILE_SELECTED = 4;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004439
Andrei Popescu540035d2009-09-18 18:59:20 +01004440 // the default <video> poster
4441 private Bitmap mDefaultVideoPoster;
4442 // the video progress view
4443 private View mVideoProgressView;
4444
Andrei Popescu30995e72010-02-09 16:59:58 +00004445 // The Google packages we monitor for the navigator.isApplicationInstalled()
4446 // API. Add as needed.
4447 private static Set<String> sGoogleApps;
4448 static {
4449 sGoogleApps = new HashSet<String>();
4450 sGoogleApps.add("com.google.android.youtube");
4451 }
4452
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004453 /**
4454 * A UrlData class to abstract how the content will be set to WebView.
4455 * This base class uses loadUrl to show the content.
4456 */
Leon Scroggins6eac63e2010-03-15 18:19:14 -04004457 /* package */ static class UrlData {
Grace Kloba068e48b2010-01-26 18:11:27 -08004458 final String mUrl;
4459 final Map<String, String> mHeaders;
Leon Scroggins58d56c62010-01-28 15:12:40 -05004460 final Intent mVoiceIntent;
Grace Kloba60e095c2009-06-16 11:50:55 -07004461
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004462 UrlData(String url) {
4463 this.mUrl = url;
Grace Kloba068e48b2010-01-26 18:11:27 -08004464 this.mHeaders = null;
Leon Scroggins58d56c62010-01-28 15:12:40 -05004465 this.mVoiceIntent = null;
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004466 }
Grace Kloba60e095c2009-06-16 11:50:55 -07004467
Leon Scroggins58d56c62010-01-28 15:12:40 -05004468 UrlData(String url, Map<String, String> headers, Intent intent) {
Grace Kloba068e48b2010-01-26 18:11:27 -08004469 this.mUrl = url;
4470 this.mHeaders = headers;
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -05004471 if (RecognizerResultsIntent.ACTION_VOICE_SEARCH_RESULTS
4472 .equals(intent.getAction())) {
Leon Scroggins58d56c62010-01-28 15:12:40 -05004473 this.mVoiceIntent = intent;
4474 } else {
4475 this.mVoiceIntent = null;
4476 }
Grace Kloba60e095c2009-06-16 11:50:55 -07004477 }
4478
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004479 boolean isEmpty() {
Leon Scroggins58d56c62010-01-28 15:12:40 -05004480 return mVoiceIntent == null && (mUrl == null || mUrl.length() == 0);
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004481 }
4482
Leon Scroggins92472e82010-02-17 16:32:28 -05004483 /**
4484 * Load this UrlData into the given Tab. Use loadUrlDataIn to update
4485 * the title bar as well.
4486 */
Leon Scroggins58d56c62010-01-28 15:12:40 -05004487 public void loadIn(Tab t) {
4488 if (mVoiceIntent != null) {
4489 t.activateVoiceSearchMode(mVoiceIntent);
4490 } else {
4491 t.getWebView().loadUrl(mUrl, mHeaders);
4492 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004493 }
4494 };
4495
Leon Scroggins1f005d32009-08-10 17:36:42 -04004496 /* package */ static final UrlData EMPTY_URL_DATA = new UrlData(null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004497}