blob: e1e1e18a3dedc4e8ce3684d47462d4084bec18f9 [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;
Bjorn Bringertd69f51d2010-09-13 14:06:41 +010020import com.android.browser.search.SearchEngine;
Michael Kolb3f65c382010-08-20 15:31:16 -070021import com.android.common.Search;
22import com.android.common.speech.LoggingEvents;
23
Michael Kolbed217742010-08-10 17:52:34 -070024import android.app.ActionBar;
The Android Open Source Project0c908882009-03-03 19:32:16 -080025import android.app.Activity;
The Android Open Source Project0c908882009-03-03 19:32:16 -080026import android.app.AlertDialog;
Michael Kolbc7485ae2010-09-03 10:10:58 -070027import android.app.Dialog;
The Android Open Source Project0c908882009-03-03 19:32:16 -080028import android.app.ProgressDialog;
29import android.app.SearchManager;
30import android.content.ActivityNotFoundException;
31import android.content.BroadcastReceiver;
Dianne Hackborn80f32622010-08-05 14:17:53 -070032import android.content.ClipboardManager;
The Android Open Source Project0c908882009-03-03 19:32:16 -080033import android.content.ComponentName;
Leon Scroggins58d56c62010-01-28 15:12:40 -050034import android.content.ContentProvider;
35import android.content.ContentProviderClient;
The Android Open Source Project0c908882009-03-03 19:32:16 -080036import android.content.ContentResolver;
Leon Scrogginsb6b7f9e2009-06-18 12:05:28 -040037import android.content.ContentUris;
The Android Open Source Project0c908882009-03-03 19:32:16 -080038import android.content.ContentValues;
39import android.content.Context;
40import android.content.DialogInterface;
41import android.content.Intent;
42import android.content.IntentFilter;
The Android Open Source Project0c908882009-03-03 19:32:16 -080043import android.content.pm.PackageManager;
44import android.content.pm.ResolveInfo;
The Android Open Source Project0c908882009-03-03 19:32:16 -080045import android.content.res.Configuration;
46import android.content.res.Resources;
47import android.database.Cursor;
The Android Open Source Project0c908882009-03-03 19:32:16 -080048import android.graphics.Bitmap;
Andrei Popescu540035d2009-09-18 18:59:20 +010049import android.graphics.BitmapFactory;
The Android Open Source Project0c908882009-03-03 19:32:16 -080050import android.graphics.Canvas;
The Android Open Source Project0c908882009-03-03 19:32:16 -080051import android.graphics.Picture;
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -040052import android.graphics.PixelFormat;
The Android Open Source Project0c908882009-03-03 19:32:16 -080053import android.graphics.drawable.Drawable;
The Android Open Source Project0c908882009-03-03 19:32:16 -080054import android.net.ConnectivityManager;
Andrei Popescu56199cc2010-01-12 22:39:16 +000055import android.net.NetworkInfo;
The Android Open Source Project0c908882009-03-03 19:32:16 -080056import android.net.Uri;
57import android.net.WebAddress;
The Android Open Source Project0c908882009-03-03 19:32:16 -080058import android.net.http.SslCertificate;
59import android.net.http.SslError;
60import android.os.AsyncTask;
61import android.os.Bundle;
62import android.os.Debug;
63import android.os.Environment;
64import android.os.Handler;
The Android Open Source Project0c908882009-03-03 19:32:16 -080065import android.os.Message;
66import android.os.PowerManager;
67import android.os.Process;
The Android Open Source Project0c908882009-03-03 19:32:16 -080068import android.os.SystemClock;
The Android Open Source Project0c908882009-03-03 19:32:16 -080069import android.provider.Browser;
Jeff Hamilton8ce956c2010-08-17 11:13:53 -050070import android.provider.BrowserContract;
Cary Clark5e335a32009-09-22 14:53:11 -040071import android.provider.ContactsContract;
Michael Kolba2b2ba82010-08-04 17:54:03 -070072import android.provider.ContactsContract.Intents.Insert;
The Android Open Source Project0c908882009-03-03 19:32:16 -080073import android.provider.Downloads;
74import android.provider.MediaStore;
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -050075import android.speech.RecognizerResultsIntent;
The Android Open Source Project0c908882009-03-03 19:32:16 -080076import android.text.TextUtils;
77import android.text.format.DateFormat;
The Android Open Source Project0c908882009-03-03 19:32:16 -080078import android.util.Log;
Dianne Hackborn385effd2010-02-24 20:03:04 -080079import android.util.Patterns;
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -040080import android.view.ActionMode;
The Android Open Source Project0c908882009-03-03 19:32:16 -080081import android.view.ContextMenu;
Michael Kolba2b2ba82010-08-04 17:54:03 -070082import android.view.ContextMenu.ContextMenuInfo;
The Android Open Source Project0c908882009-03-03 19:32:16 -080083import android.view.Gravity;
84import android.view.KeyEvent;
85import android.view.LayoutInflater;
86import android.view.Menu;
87import android.view.MenuInflater;
88import android.view.MenuItem;
Michael Kolba2b2ba82010-08-04 17:54:03 -070089import android.view.MenuItem.OnMenuItemClickListener;
Michael Kolb3f65c382010-08-20 15:31:16 -070090import android.view.MotionEvent;
The Android Open Source Project0c908882009-03-03 19:32:16 -080091import android.view.View;
92import android.view.ViewGroup;
93import android.view.Window;
94import android.view.WindowManager;
Svetoslav Ganov2b345992010-05-06 06:13:54 -070095import android.view.accessibility.AccessibilityManager;
The Android Open Source Project0c908882009-03-03 19:32:16 -080096import android.webkit.CookieManager;
97import android.webkit.CookieSyncManager;
98import android.webkit.DownloadListener;
99import android.webkit.HttpAuthHandler;
100import 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;
Michael Kolbc7485ae2010-09-03 10:10:58 -0700110import android.widget.PopupMenu;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800111import android.widget.TextView;
112import android.widget.Toast;
113
Leon Scrogginsb6b7f9e2009-06-18 12:05:28 -0400114import java.io.ByteArrayOutputStream;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800115import java.io.File;
Ben Murdoch4f75ba22009-10-27 11:48:28 +0000116import java.io.IOException;
117import java.io.InputStream;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800118import java.net.MalformedURLException;
Dianne Hackborn99189432009-06-17 18:06:18 -0700119import java.net.URISyntaxException;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800120import java.net.URL;
121import java.net.URLEncoder;
Elliott Slaughter3d6df162010-08-25 13:17:44 -0700122import java.util.Calendar;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800123import java.util.Date;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800124import java.util.HashMap;
Grace Kloba00f54c52010-01-27 14:53:51 -0800125import java.util.Iterator;
Grace Kloba068e48b2010-01-26 18:11:27 -0800126import java.util.Map;
Michael Kolbfe251992010-07-08 15:41:55 -0700127import java.util.Vector;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800128import java.util.regex.Matcher;
129import java.util.regex.Pattern;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800130
131public class BrowserActivity extends Activity
Michael Kolbc7485ae2010-09-03 10:10:58 -0700132 implements View.OnCreateContextMenuListener, DownloadListener,
133 PopupMenu.OnMenuItemClickListener {
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 Kolbc7485ae2010-09-03 10:10:58 -0700233 actionBar.setBackgroundDrawable(getResources().
234 getDrawable(R.drawable.tabbar_bg));
Michael Kolba2b2ba82010-08-04 17:54:03 -0700235 mTabBar = new TabBar(this, mTabControl, (TitleBarXLarge) mFakeTitleBar);
Michael Kolbed217742010-08-10 17:52:34 -0700236 actionBar.setCustomNavigationMode(mTabBar);
Michael Kolb68775752010-08-19 12:42:01 -0700237 // disable built in zoom controls
238 mTabControl.setDisplayZoomControls(false);
Leon Scrogginsd746a942010-05-19 13:21:44 -0400239 } else {
Leon Scroggins571b3762010-05-26 10:25:01 -0400240 mTitleBar = new TitleBar(this);
Leon Scrogginsd746a942010-05-19 13:21:44 -0400241 // mTitleBar will be always be shown in the fully loaded mode on
242 // phone
243 mTitleBar.setProgress(100);
Leon Scrogginsd746a942010-05-19 13:21:44 -0400244 mFakeTitleBar = new TitleBar(this);
245 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800246
The Android Open Source Project0c908882009-03-03 19:32:16 -0800247 // Open the icon database and retain all the bookmark urls for favicons
248 retainIconsOnStartup();
249
250 // Keep a settings instance handy.
251 mSettings = BrowserSettings.getInstance();
252 mSettings.setTabControl(mTabControl);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800253
254 PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
255 mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Browser");
256
Patrick Scott6adacc92010-03-05 08:24:51 -0500257 // Find out if the network is currently up.
258 ConnectivityManager cm = (ConnectivityManager) getSystemService(
259 Context.CONNECTIVITY_SERVICE);
260 NetworkInfo info = cm.getActiveNetworkInfo();
261 if (info != null) {
262 mIsNetworkUp = info.isAvailable();
263 }
264
Grace Klobaa34f6862009-07-31 16:28:17 -0700265 /* enables registration for changes in network status from
266 http stack */
267 mNetworkStateChangedFilter = new IntentFilter();
268 mNetworkStateChangedFilter.addAction(
269 ConnectivityManager.CONNECTIVITY_ACTION);
270 mNetworkStateIntentReceiver = new BroadcastReceiver() {
271 @Override
272 public void onReceive(Context context, Intent intent) {
273 if (intent.getAction().equals(
274 ConnectivityManager.CONNECTIVITY_ACTION)) {
Andrei Popescue4c98462010-02-19 15:44:13 +0000275
276 NetworkInfo info = intent.getParcelableExtra(
277 ConnectivityManager.EXTRA_NETWORK_INFO);
278 String typeName = info.getTypeName();
279 String subtypeName = info.getSubtypeName();
280 sendNetworkType(typeName.toLowerCase(),
281 (subtypeName != null ? subtypeName.toLowerCase() : ""));
282
283 onNetworkToggle(info.isAvailable());
Grace Klobaa34f6862009-07-31 16:28:17 -0700284 }
285 }
286 };
287
Elliott Slaughter3d6df162010-08-25 13:17:44 -0700288 // Unless the last browser usage was within 24 hours, destroy any
289 // remaining incognito tabs.
290
291 Calendar lastActiveDate = icicle != null ? (Calendar) icicle.getSerializable("lastActiveDate") : null;
292 Calendar today = Calendar.getInstance();
293 Calendar yesterday = Calendar.getInstance();
294 yesterday.add(Calendar.DATE, -1);
295
296 boolean dontRestoreIncognitoTabs = lastActiveDate == null
297 || lastActiveDate.before(yesterday)
298 || lastActiveDate.after(today);
299
300 if (!mTabControl.restoreState(icicle, dontRestoreIncognitoTabs)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800301 // clear up the thumbnail directory if we can't restore the state as
302 // none of the files in the directory are referenced any more.
303 new ClearThumbnails().execute(
304 mTabControl.getThumbnailDir().listFiles());
Grace Klobaaab3f092009-07-30 12:29:51 -0700305 // there is no quit on Android. But if we can't restore the state,
306 // we can treat it as a new Browser, remove the old session cookies.
307 CookieManager.getInstance().removeSessionCookie();
Elliott Slaughter3d6df162010-08-25 13:17:44 -0700308 // remove any incognito files
309 WebView.cleanupPrivateBrowsingFiles(this);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800310 final Intent intent = getIntent();
311 final Bundle extra = intent.getExtras();
312 // Create an initial tab.
313 // If the intent is ACTION_VIEW and data is not null, the Browser is
314 // invoked to view the content by another application. In this case,
315 // the tab will be close when exit.
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700316 UrlData urlData = getUrlDataFromIntent(intent);
317
Leon Scroggins58d56c62010-01-28 15:12:40 -0500318 String action = intent.getAction();
Grace Kloba22ac16e2009-10-07 18:00:23 -0700319 final Tab t = mTabControl.createNewTab(
Leon Scroggins58d56c62010-01-28 15:12:40 -0500320 (Intent.ACTION_VIEW.equals(action) &&
321 intent.getData() != null)
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -0500322 || RecognizerResultsIntent.ACTION_VOICE_SEARCH_RESULTS
323 .equals(action),
Elliott Slaughterf0f03952010-07-14 18:10:36 -0700324 intent.getStringExtra(Browser.EXTRA_APPLICATION_ID),
325 urlData.mUrl, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800326 mTabControl.setCurrentTab(t);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800327 attachTabToContentView(t);
328 WebView webView = t.getWebView();
329 if (extra != null) {
330 int scale = extra.getInt(Browser.INITIAL_ZOOM_LEVEL, 0);
331 if (scale > 0 && scale <= 1000) {
332 webView.setInitialScale(scale);
333 }
334 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800335
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700336 if (urlData.isEmpty()) {
Shimeng (Simon) Wang98d5fce2010-03-16 13:23:39 -0700337 loadUrl(webView, mSettings.getHomePage());
The Android Open Source Project0c908882009-03-03 19:32:16 -0800338 } else {
Patrick Scott9d53da02010-02-19 10:19:01 -0500339 loadUrlDataIn(t, urlData);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800340 }
341 } else {
Elliott Slaughter3d6df162010-08-25 13:17:44 -0700342 if (dontRestoreIncognitoTabs) {
343 WebView.cleanupPrivateBrowsingFiles(this);
344 }
345
The Android Open Source Project0c908882009-03-03 19:32:16 -0800346 // TabControl.restoreState() will create a new tab even if
Leon Scroggins1f005d32009-08-10 17:36:42 -0400347 // restoring the state fails.
The Android Open Source Project0c908882009-03-03 19:32:16 -0800348 attachTabToContentView(mTabControl.getCurrentTab());
349 }
Grace Kloba615c6c92009-08-03 10:22:44 -0700350
Cary Clarkb4b83182010-07-01 12:36:56 -0400351 // Delete old thumbnails to save space
352 File dir = mTabControl.getThumbnailDir();
353 if (dir.exists()) {
354 for (String child : dir.list()) {
355 File f = new File(dir, child);
356 f.delete();
357 }
358 }
359
Feng Qianb3c02da2009-06-29 15:58:08 -0700360 // Read JavaScript flags if it exists.
361 String jsFlags = mSettings.getJsFlags();
362 if (jsFlags.trim().length() != 0) {
363 mTabControl.getCurrentWebView().setJsFlags(jsFlags);
364 }
Bjorn Bringerta7611812010-03-24 11:12:02 +0000365
366 // Start watching the default geolocation permissions
367 mSystemAllowGeolocationOrigins
368 = new SystemAllowGeolocationOrigins(getApplicationContext());
369 mSystemAllowGeolocationOrigins.start();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800370 }
371
Michael Kolba2b2ba82010-08-04 17:54:03 -0700372 ScrollListener getScrollListener() {
373 return mTabBar;
374 }
375
Leon Scroggins58d56c62010-01-28 15:12:40 -0500376 /**
377 * Feed the previously stored results strings to the BrowserProvider so that
378 * the SearchDialog will show them instead of the standard searches.
379 * @param result String to show on the editable line of the SearchDialog.
380 */
381 /* package */ void showVoiceSearchResults(String result) {
382 ContentProviderClient client = mResolver.acquireContentProviderClient(
383 Browser.BOOKMARKS_URI);
384 ContentProvider prov = client.getLocalContentProvider();
385 BrowserProvider bp = (BrowserProvider) prov;
386 bp.setQueryResults(mTabControl.getCurrentTab().getVoiceSearchResults());
387 client.release();
388
Leon Scrogginsfbb3f152010-03-09 17:26:56 -0500389 Bundle bundle = createGoogleSearchSourceBundle(
390 GOOGLE_SEARCH_SOURCE_SEARCHKEY);
391 bundle.putBoolean(SearchManager.CONTEXT_IS_VOICE, true);
392 startSearch(result, false, bundle, false);
Leon Scroggins58d56c62010-01-28 15:12:40 -0500393 }
394
The Android Open Source Project0c908882009-03-03 19:32:16 -0800395 @Override
396 protected void onNewIntent(Intent intent) {
Grace Kloba22ac16e2009-10-07 18:00:23 -0700397 Tab current = mTabControl.getCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800398 // When a tab is closed on exit, the current tab index is set to -1.
399 // Reset before proceed as Browser requires the current tab to be set.
400 if (current == null) {
401 // Try to reset the tab in case the index was incorrect.
402 current = mTabControl.getTab(0);
403 if (current == null) {
404 // No tabs at all so just ignore this intent.
405 return;
406 }
407 mTabControl.setCurrentTab(current);
408 attachTabToContentView(current);
409 resetTitleAndIcon(current.getWebView());
410 }
411 final String action = intent.getAction();
412 final int flags = intent.getFlags();
413 if (Intent.ACTION_MAIN.equals(action) ||
414 (flags & Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY) != 0) {
415 // just resume the browser
416 return;
417 }
Leon Scrogginsb8a844d2010-03-18 15:06:15 -0400418 // In case the SearchDialog is open.
419 ((SearchManager) getSystemService(Context.SEARCH_SERVICE))
420 .stopSearch();
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -0500421 boolean activateVoiceSearch = RecognizerResultsIntent
422 .ACTION_VOICE_SEARCH_RESULTS.equals(action);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800423 if (Intent.ACTION_VIEW.equals(action)
424 || Intent.ACTION_SEARCH.equals(action)
425 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
Leon Scroggins58d56c62010-01-28 15:12:40 -0500426 || Intent.ACTION_WEB_SEARCH.equals(action)
427 || activateVoiceSearch) {
Leon Scroggins3b18ce32010-02-08 17:35:59 -0500428 if (current.isInVoiceSearchMode()) {
429 String title = current.getVoiceDisplayTitle();
430 if (title != null && title.equals(intent.getStringExtra(
431 SearchManager.QUERY))) {
432 // The user submitted the same search as the last voice
433 // search, so do nothing.
434 return;
435 }
Leon Scroggins1fe13a52010-02-09 15:31:26 -0500436 if (Intent.ACTION_SEARCH.equals(action)
437 && current.voiceSearchSourceIsGoogle()) {
438 Intent logIntent = new Intent(
439 LoggingEvents.ACTION_LOG_EVENT);
440 logIntent.putExtra(LoggingEvents.EXTRA_EVENT,
441 LoggingEvents.VoiceSearch.QUERY_UPDATED);
442 logIntent.putExtra(
443 LoggingEvents.VoiceSearch.EXTRA_QUERY_UPDATED_VALUE,
444 intent.getDataString());
445 sendBroadcast(logIntent);
446 // Note, onPageStarted will revert the voice title bar
447 // When http://b/issue?id=2379215 is fixed, we should update
448 // the title bar here.
449 }
Leon Scroggins3b18ce32010-02-08 17:35:59 -0500450 }
Satish Sampath565505b2009-05-29 15:37:27 +0100451 // If this was a search request (e.g. search query directly typed into the address bar),
452 // pass it on to the default web search provider.
453 if (handleWebSearchIntent(intent)) {
454 return;
455 }
456
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700457 UrlData urlData = getUrlDataFromIntent(intent);
458 if (urlData.isEmpty()) {
459 urlData = new UrlData(mSettings.getHomePage());
The Android Open Source Project0c908882009-03-03 19:32:16 -0800460 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700461
Grace Klobacc634032009-07-28 15:58:19 -0700462 final String appId = intent
463 .getStringExtra(Browser.EXTRA_APPLICATION_ID);
Leon Scroggins47208682010-04-07 17:59:48 -0400464 if ((Intent.ACTION_VIEW.equals(action)
465 // If a voice search has no appId, it means that it came
466 // from the browser. In that case, reuse the current tab.
467 || (activateVoiceSearch && appId != null))
Grace Klobacc634032009-07-28 15:58:19 -0700468 && !getPackageName().equals(appId)
469 && (flags & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0) {
Grace Kloba22ac16e2009-10-07 18:00:23 -0700470 Tab appTab = mTabControl.getTabFromId(appId);
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700471 if (appTab != null) {
472 Log.i(LOGTAG, "Reusing tab for " + appId);
473 // Dismiss the subwindow if applicable.
474 dismissSubWindow(appTab);
475 // Since we might kill the WebView, remove it from the
476 // content view first.
477 removeTabFromContentView(appTab);
478 // Recreate the main WebView after destroying the old one.
479 // If the WebView has the same original url and is on that
480 // page, it can be reused.
481 boolean needsLoad =
Leon Scroggins6eac63e2010-03-15 18:19:14 -0400482 mTabControl.recreateWebView(appTab, urlData);
Ben Murdochbff2d602009-07-01 20:19:05 +0100483
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700484 if (current != appTab) {
Leon Scroggins1f005d32009-08-10 17:36:42 -0400485 switchToTab(mTabControl.getTabIndex(appTab));
486 if (needsLoad) {
Patrick Scott9d53da02010-02-19 10:19:01 -0500487 loadUrlDataIn(appTab, urlData);
Leon Scroggins1f005d32009-08-10 17:36:42 -0400488 }
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700489 } else {
Leon Scroggins1f005d32009-08-10 17:36:42 -0400490 // If the tab was the current tab, we have to attach
491 // it to the view system again.
492 attachTabToContentView(appTab);
493 if (needsLoad) {
Patrick Scott9d53da02010-02-19 10:19:01 -0500494 loadUrlDataIn(appTab, urlData);
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700495 }
496 }
497 return;
Patrick Scottcd115892009-07-16 09:42:58 -0400498 } else {
499 // No matching application tab, try to find a regular tab
500 // with a matching url.
501 appTab = mTabControl.findUnusedTabWithUrl(urlData.mUrl);
Leon Scroggins25515f82009-08-19 15:31:58 -0400502 if (appTab != null) {
503 if (current != appTab) {
504 switchToTab(mTabControl.getTabIndex(appTab));
505 }
506 // Otherwise, we are already viewing the correct tab.
Patrick Scottcd115892009-07-16 09:42:58 -0400507 } else {
508 // if FLAG_ACTIVITY_BROUGHT_TO_FRONT flag is on, the url
509 // will be opened in a new tab unless we have reached
510 // MAX_TABS. Then the url will be opened in the current
511 // tab. If a new tab is created, it will have "true" for
512 // exit on close.
Leon Scroggins1f005d32009-08-10 17:36:42 -0400513 openTabAndShow(urlData, true, appId);
Patrick Scottcd115892009-07-16 09:42:58 -0400514 }
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700515 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800516 } else {
Grace Kloba638d3f42009-11-23 10:35:04 -0800517 if (!urlData.isEmpty()
518 && urlData.mUrl.startsWith("about:debug")) {
519 if ("about:debug.dom".equals(urlData.mUrl)) {
520 current.getWebView().dumpDomTree(false);
521 } else if ("about:debug.dom.file".equals(urlData.mUrl)) {
522 current.getWebView().dumpDomTree(true);
523 } else if ("about:debug.render".equals(urlData.mUrl)) {
524 current.getWebView().dumpRenderTree(false);
525 } else if ("about:debug.render.file".equals(urlData.mUrl)) {
526 current.getWebView().dumpRenderTree(true);
527 } else if ("about:debug.display".equals(urlData.mUrl)) {
528 current.getWebView().dumpDisplayTree();
Mike Reed9b78e1d2010-01-13 14:40:52 -0800529 } else if (urlData.mUrl.startsWith("about:debug.drag")) {
530 int index = urlData.mUrl.codePointAt(16) - '0';
531 if (index <= 0 || index > 9) {
532 current.getWebView().setDragTracker(null);
533 } else {
534 current.getWebView().setDragTracker(new MeshTracker(index));
535 }
Grace Kloba638d3f42009-11-23 10:35:04 -0800536 } else {
537 mSettings.toggleDebugSettings();
538 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800539 return;
540 }
Leon Scroggins1f005d32009-08-10 17:36:42 -0400541 // Get rid of the subwindow if it exists
542 dismissSubWindow(current);
Leon Scroggins8588d152010-04-15 11:01:53 -0400543 // If the current Tab is being used as an application tab,
544 // remove the association, since the new Intent means that it is
545 // no longer associated with that application.
546 current.setAppId(null);
Patrick Scott9d53da02010-02-19 10:19:01 -0500547 loadUrlDataIn(current, urlData);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800548 }
549 }
550 }
551
Satish Sampath565505b2009-05-29 15:37:27 +0100552 private int parseUrlShortcut(String url) {
553 if (url == null) return SHORTCUT_INVALID;
554
555 // FIXME: quick search, need to be customized by setting
556 if (url.length() > 2 && url.charAt(1) == ' ') {
557 switch (url.charAt(0)) {
558 case 'g': return SHORTCUT_GOOGLE_SEARCH;
559 case 'w': return SHORTCUT_WIKIPEDIA_SEARCH;
560 case 'd': return SHORTCUT_DICTIONARY_SEARCH;
561 case 'l': return SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH;
562 }
563 }
564 return SHORTCUT_INVALID;
565 }
566
567 /**
568 * Launches the default web search activity with the query parameters if the given intent's data
569 * are identified as plain search terms and not URLs/shortcuts.
570 * @return true if the intent was handled and web search activity was launched, false if not.
571 */
572 private boolean handleWebSearchIntent(Intent intent) {
573 if (intent == null) return false;
574
575 String url = null;
576 final String action = intent.getAction();
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -0500577 if (RecognizerResultsIntent.ACTION_VOICE_SEARCH_RESULTS.equals(
578 action)) {
Leon Scroggins58d56c62010-01-28 15:12:40 -0500579 return false;
580 }
Satish Sampath565505b2009-05-29 15:37:27 +0100581 if (Intent.ACTION_VIEW.equals(action)) {
Grace Kloba1e705052009-09-29 13:13:36 -0700582 Uri data = intent.getData();
583 if (data != null) url = data.toString();
Satish Sampath565505b2009-05-29 15:37:27 +0100584 } else if (Intent.ACTION_SEARCH.equals(action)
585 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
586 || Intent.ACTION_WEB_SEARCH.equals(action)) {
587 url = intent.getStringExtra(SearchManager.QUERY);
588 }
Bjorn Bringert04851702009-09-22 10:36:01 +0100589 return handleWebSearchRequest(url, intent.getBundleExtra(SearchManager.APP_DATA),
590 intent.getStringExtra(SearchManager.EXTRA_DATA_KEY));
Satish Sampath565505b2009-05-29 15:37:27 +0100591 }
592
593 /**
594 * Launches the default web search activity with the query parameters if the given url string
595 * was identified as plain search terms and not URL/shortcut.
596 * @return true if the request was handled and web search activity was launched, false if not.
597 */
Bjorn Bringert04851702009-09-22 10:36:01 +0100598 private boolean handleWebSearchRequest(String inUrl, Bundle appData, String extraData) {
Satish Sampath565505b2009-05-29 15:37:27 +0100599 if (inUrl == null) return false;
600
601 // In general, we shouldn't modify URL from Intent.
602 // But currently, we get the user-typed URL from search box as well.
603 String url = fixUrl(inUrl).trim();
604
605 // URLs and site specific search shortcuts are handled by the regular flow of control, so
606 // return early.
Dan Egnor5ee906c2009-11-18 12:11:49 -0800607 if (Patterns.WEB_URL.matcher(url).matches()
Satish Sampathbc5b9f32009-06-04 18:21:40 +0100608 || ACCEPTED_URI_SCHEMA.matcher(url).matches()
Satish Sampath565505b2009-05-29 15:37:27 +0100609 || parseUrlShortcut(url) != SHORTCUT_INVALID) {
610 return false;
611 }
612
Leon Scroggins8d06e362010-03-24 14:45:57 -0400613 final ContentResolver cr = mResolver;
614 final String newUrl = url;
Elliott Slaughter627d96f2010-08-18 16:35:30 -0700615 if (mTabControl == null || !mTabControl.getCurrentWebView().isPrivateBrowsingEnabled()) {
Elliott Slaughterf0f03952010-07-14 18:10:36 -0700616 new AsyncTask<Void, Void, Void>() {
617 @Override
618 protected Void doInBackground(Void... unused) {
619 Browser.updateVisitedHistory(cr, newUrl, false);
620 Browser.addSearchUrl(cr, newUrl);
621 return null;
622 }
623 }.execute();
624 }
Satish Sampath565505b2009-05-29 15:37:27 +0100625
Bjorn Bringertd69f51d2010-09-13 14:06:41 +0100626 SearchEngine searchEngine = mSettings.getSearchEngine();
627 if (searchEngine == null) return false;
628 searchEngine.startSearch(this, url, appData, extraData);
Satish Sampath565505b2009-05-29 15:37:27 +0100629
630 return true;
631 }
632
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700633 private UrlData getUrlDataFromIntent(Intent intent) {
Leon Scroggins58d56c62010-01-28 15:12:40 -0500634 String url = "";
Grace Kloba068e48b2010-01-26 18:11:27 -0800635 Map<String, String> headers = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800636 if (intent != null) {
637 final String action = intent.getAction();
638 if (Intent.ACTION_VIEW.equals(action)) {
639 url = smartUrlFilter(intent.getData());
640 if (url != null && url.startsWith("content:")) {
641 /* Append mimetype so webview knows how to display */
642 String mimeType = intent.resolveType(getContentResolver());
643 if (mimeType != null) {
644 url += "?" + mimeType;
645 }
646 }
Grace Kloba068e48b2010-01-26 18:11:27 -0800647 if (url != null && url.startsWith("http")) {
Grace Kloba00f54c52010-01-27 14:53:51 -0800648 final Bundle pairs = intent
649 .getBundleExtra(Browser.EXTRA_HEADERS);
Grace Kloba2d508ed2010-01-28 11:39:15 -0800650 if (pairs != null && !pairs.isEmpty()) {
Grace Kloba00f54c52010-01-27 14:53:51 -0800651 Iterator<String> iter = pairs.keySet().iterator();
Grace Kloba068e48b2010-01-26 18:11:27 -0800652 headers = new HashMap<String, String>();
Grace Kloba00f54c52010-01-27 14:53:51 -0800653 while (iter.hasNext()) {
654 String key = iter.next();
655 headers.put(key, pairs.getString(key));
Grace Kloba068e48b2010-01-26 18:11:27 -0800656 }
657 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700658 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800659 } else if (Intent.ACTION_SEARCH.equals(action)
660 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
661 || Intent.ACTION_WEB_SEARCH.equals(action)) {
662 url = intent.getStringExtra(SearchManager.QUERY);
663 if (url != null) {
664 mLastEnteredUrl = url;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800665 // In general, we shouldn't modify URL from Intent.
666 // But currently, we get the user-typed URL from search box as well.
667 url = fixUrl(url);
668 url = smartUrlFilter(url);
Leon Scroggins8d06e362010-03-24 14:45:57 -0400669 final ContentResolver cr = mResolver;
670 final String newUrl = url;
Elliott Slaughter8389e992010-08-20 15:44:08 -0700671 if (mTabControl == null
672 || mTabControl.getCurrentWebView() == null
673 || !mTabControl.getCurrentWebView().isPrivateBrowsingEnabled()) {
674 new AsyncTask<Void, Void, Void>() {
675 @Override
676 protected Void doInBackground(Void... unused) {
677 Browser.updateVisitedHistory(cr, newUrl, false);
678 return null;
679 }
680 }.execute();
681 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800682 String searchSource = "&source=android-" + GOOGLE_SEARCH_SOURCE_SUGGEST + "&";
683 if (url.contains(searchSource)) {
684 String source = null;
685 final Bundle appData = intent.getBundleExtra(SearchManager.APP_DATA);
686 if (appData != null) {
Bjorn Bringert10d1cca2010-02-10 14:22:12 +0000687 source = appData.getString(Search.SOURCE);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800688 }
689 if (TextUtils.isEmpty(source)) {
690 source = GOOGLE_SEARCH_SOURCE_UNKNOWN;
691 }
692 url = url.replace(searchSource, "&source=android-"+source+"&");
693 }
694 }
695 }
696 }
Leon Scroggins58d56c62010-01-28 15:12:40 -0500697 return new UrlData(url, headers, intent);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800698 }
Leon Scroggins58d56c62010-01-28 15:12:40 -0500699 /* package */ void showVoiceTitleBar(String title) {
700 mTitleBar.setInVoiceMode(true);
Leon Scroggins58d56c62010-01-28 15:12:40 -0500701 mTitleBar.setDisplayTitle(title);
Michael Kolba2b2ba82010-08-04 17:54:03 -0700702 mFakeTitleBar.setInVoiceMode(true);
703 mFakeTitleBar.setDisplayTitle(title);
Leon Scroggins58d56c62010-01-28 15:12:40 -0500704 }
705 /* package */ void revertVoiceTitleBar() {
706 mTitleBar.setInVoiceMode(false);
Leon Scroggins003a5dd2010-03-10 12:13:14 -0500707 mTitleBar.setDisplayTitle(mUrl);
Michael Kolba2b2ba82010-08-04 17:54:03 -0700708 mFakeTitleBar.setInVoiceMode(false);
709 mFakeTitleBar.setDisplayTitle(mUrl);
Leon Scroggins58d56c62010-01-28 15:12:40 -0500710 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800711 /* package */ static String fixUrl(String inUrl) {
Cary Clark652ff872009-09-10 13:34:44 -0400712 // FIXME: Converting the url to lower case
713 // duplicates functionality in smartUrlFilter().
714 // However, changing all current callers of fixUrl to
715 // call smartUrlFilter in addition may have unwanted
716 // consequences, and is deferred for now.
717 int colon = inUrl.indexOf(':');
718 boolean allLower = true;
719 for (int index = 0; index < colon; index++) {
720 char ch = inUrl.charAt(index);
721 if (!Character.isLetter(ch)) {
722 break;
723 }
724 allLower &= Character.isLowerCase(ch);
725 if (index == colon - 1 && !allLower) {
726 inUrl = inUrl.substring(0, colon).toLowerCase()
727 + inUrl.substring(colon);
728 }
729 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800730 if (inUrl.startsWith("http://") || inUrl.startsWith("https://"))
731 return inUrl;
732 if (inUrl.startsWith("http:") ||
733 inUrl.startsWith("https:")) {
734 if (inUrl.startsWith("http:/") || inUrl.startsWith("https:/")) {
735 inUrl = inUrl.replaceFirst("/", "//");
736 } else inUrl = inUrl.replaceFirst(":", "://");
737 }
738 return inUrl;
739 }
740
Grace Kloba22ac16e2009-10-07 18:00:23 -0700741 @Override
742 protected void onResume() {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800743 super.onResume();
Dave Bort31a6d1c2009-04-13 15:56:49 -0700744 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800745 Log.v(LOGTAG, "BrowserActivity.onResume: this=" + this);
746 }
747
748 if (!mActivityInPause) {
749 Log.e(LOGTAG, "BrowserActivity is already resumed.");
750 return;
751 }
752
Mike Reed7bfa63b2009-05-28 11:08:32 -0400753 mTabControl.resumeCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800754 mActivityInPause = false;
Mike Reed7bfa63b2009-05-28 11:08:32 -0400755 resumeWebViewTimers();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800756
757 if (mWakeLock.isHeld()) {
758 mHandler.removeMessages(RELEASE_WAKELOCK);
759 mWakeLock.release();
760 }
761
The Android Open Source Project0c908882009-03-03 19:32:16 -0800762 registerReceiver(mNetworkStateIntentReceiver,
763 mNetworkStateChangedFilter);
764 WebView.enablePlatformNotifications();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800765 }
766
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400767 /**
768 * Since the actual title bar is embedded in the WebView, and removing it
Leon Scrogginsfe87bd32009-10-06 10:10:00 -0400769 * would change its appearance, use a different TitleBar to show overlayed
770 * at the top of the screen, when the menu is open or the page is loading.
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400771 */
Michael Kolba2b2ba82010-08-04 17:54:03 -0700772 private TitleBarBase mFakeTitleBar;
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400773
774 /**
775 * Keeps track of whether the options menu is open. This is important in
776 * determining whether to show or hide the title bar overlay.
777 */
778 private boolean mOptionsMenuOpen;
779
780 /**
781 * Only meaningful when mOptionsMenuOpen is true. This variable keeps track
782 * of whether the configuration has changed. The first onMenuOpened call
783 * after a configuration change is simply a reopening of the same menu
784 * (i.e. mIconView did not change).
785 */
786 private boolean mConfigChanged;
787
788 /**
789 * Whether or not the options menu is in its smaller, icon menu form. When
790 * true, we want the title bar overlay to be up. When false, we do not.
791 * Only meaningful if mOptionsMenuOpen is true.
792 */
793 private boolean mIconView;
794
Leon Scrogginsa81a7642009-08-31 17:05:41 -0400795 @Override
796 public boolean onMenuOpened(int featureId, Menu menu) {
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400797 if (Window.FEATURE_OPTIONS_PANEL == featureId) {
798 if (mOptionsMenuOpen) {
799 if (mConfigChanged) {
800 // We do not need to make any changes to the state of the
801 // title bar, since the only thing that happened was a
802 // change in orientation
803 mConfigChanged = false;
804 } else {
805 if (mIconView) {
806 // Switching the menu to expanded view, so hide the
807 // title bar.
808 hideFakeTitleBar();
809 mIconView = false;
810 } else {
811 // Switching the menu back to icon view, so show the
812 // title bar once again.
813 showFakeTitleBar();
814 mIconView = true;
815 }
816 }
817 } else {
818 // The options menu is closed, so open it, and show the title
819 showFakeTitleBar();
820 mOptionsMenuOpen = true;
821 mConfigChanged = false;
822 mIconView = true;
823 }
824 }
Leon Scrogginsa81a7642009-08-31 17:05:41 -0400825 return true;
826 }
827
Michael Kolba2b2ba82010-08-04 17:54:03 -0700828 void showFakeTitleBar() {
829 if (!isFakeTitleBarShowing() && mActiveTabsPage == null && !mActivityInPause) {
Grace Kloba847c25b2010-03-30 16:00:26 -0700830 WebView mainView = mTabControl.getCurrentWebView();
831 // if there is no current WebView, don't show the faked title bar;
Grace Kloba65190702010-04-02 23:37:26 -0700832 if (mainView == null) {
Cary Clarka0464552009-09-29 13:00:45 -0400833 return;
834 }
Leon Scroggins79e36d92010-04-29 16:01:46 +0100835 // Do not need to check for null, since the current tab will have
836 // at least a main WebView, or we would have returned above.
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -0400837 if (isInCustomActionMode()) {
838 // Do not show the fake title bar, while a custom ActionMode
839 // (i.e. find or select) is showing.
Leon Scroggins79e36d92010-04-29 16:01:46 +0100840 return;
841 }
Michael Kolba2b2ba82010-08-04 17:54:03 -0700842 if (mXLargeScreenSize) {
843 mContentView.addView(mFakeTitleBar);
844 mTabBar.onShowTitleBar();
845 } else {
846 WindowManager manager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400847
Michael Kolba2b2ba82010-08-04 17:54:03 -0700848 // Add the title bar to the window manager so it can receive
849 // touches
850 // while the menu is up
851 WindowManager.LayoutParams params =
852 new WindowManager.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
853 ViewGroup.LayoutParams.WRAP_CONTENT,
854 WindowManager.LayoutParams.TYPE_APPLICATION,
855 WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
856 PixelFormat.TRANSLUCENT);
857 params.gravity = Gravity.TOP;
858 boolean atTop = mainView.getScrollY() == 0;
859 params.windowAnimations = atTop ? 0 : R.style.TitleBar;
860 manager.addView(mFakeTitleBar, params);
861 }
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400862 }
863 }
864
865 @Override
866 public void onOptionsMenuClosed(Menu menu) {
867 mOptionsMenuOpen = false;
Leon Scrogginsa27ff192009-09-14 12:58:04 -0400868 if (!mInLoad) {
869 hideFakeTitleBar();
870 } else if (!mIconView) {
871 // The page is currently loading, and we are in expanded mode, so
872 // we were not showing the menu. Show it once again. It will be
873 // removed when the page finishes.
874 showFakeTitleBar();
875 }
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400876 }
Grace Kloba22ac16e2009-10-07 18:00:23 -0700877
Michael Kolba2b2ba82010-08-04 17:54:03 -0700878 void stopScrolling() {
879 ((ScrollWebView) mTabControl.getCurrentWebView()).stopScroll();
880 }
881
882 void hideFakeTitleBar() {
883 if (!isFakeTitleBarShowing()) return;
884 if (mXLargeScreenSize) {
885 mContentView.removeView(mFakeTitleBar);
886 mTabBar.onHideTitleBar();
887 } else {
888 WindowManager.LayoutParams params =
889 (WindowManager.LayoutParams) mFakeTitleBar.getLayoutParams();
890 WebView mainView = mTabControl.getCurrentWebView();
891 // Although we decided whether or not to animate based on the
892 // current
893 // scroll position, the scroll position may have changed since the
894 // fake title bar was displayed. Make sure it has the appropriate
895 // animation/lack thereof before removing.
896 params.windowAnimations =
897 mainView != null && mainView.getScrollY() == 0 ? 0 : R.style.TitleBar;
898 WindowManager manager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
899 manager.updateViewLayout(mFakeTitleBar, params);
900 manager.removeView(mFakeTitleBar);
901 }
902 }
903
904 boolean isFakeTitleBarShowing() {
905 return (mFakeTitleBar.getParent() != null);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400906 }
907
The Android Open Source Project0c908882009-03-03 19:32:16 -0800908 /**
Leon Scrogginsc6fa1102009-09-21 10:40:01 -0400909 * Special method for the fake title bar to call when displaying its context
910 * menu, since it is in its own Window, and its parent does not show a
911 * context menu.
912 */
913 /* package */ void showTitleBarContextMenu() {
Cary Clark65f4a3c2009-09-28 17:05:06 -0400914 if (null == mTitleBar.getParent()) {
915 return;
916 }
Leon Scrogginsc6fa1102009-09-21 10:40:01 -0400917 openContextMenu(mTitleBar);
918 }
919
Leon Scrogginsb2b19f52009-10-09 16:10:00 -0400920 @Override
921 public void onContextMenuClosed(Menu menu) {
922 super.onContextMenuClosed(menu);
923 if (mInLoad) {
924 showFakeTitleBar();
925 }
926 }
927
Leon Scrogginsc6fa1102009-09-21 10:40:01 -0400928 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -0800929 * onSaveInstanceState(Bundle map)
930 * onSaveInstanceState is called right before onStop(). The map contains
931 * the saved state.
932 */
Grace Kloba22ac16e2009-10-07 18:00:23 -0700933 @Override
934 protected void onSaveInstanceState(Bundle outState) {
Dave Bort31a6d1c2009-04-13 15:56:49 -0700935 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800936 Log.v(LOGTAG, "BrowserActivity.onSaveInstanceState: this=" + this);
937 }
938 // the default implementation requires each view to have an id. As the
939 // browser handles the state itself and it doesn't use id for the views,
940 // don't call the default implementation. Otherwise it will trigger the
941 // warning like this, "couldn't save which view has focus because the
942 // focused view XXX has no id".
943
944 // Save all the tabs
945 mTabControl.saveState(outState);
Elliott Slaughter3d6df162010-08-25 13:17:44 -0700946
947 // Save time so that we know how old incognito tabs (if any) are.
948 outState.putSerializable("lastActiveDate", Calendar.getInstance());
The Android Open Source Project0c908882009-03-03 19:32:16 -0800949 }
950
Grace Kloba22ac16e2009-10-07 18:00:23 -0700951 @Override
952 protected void onPause() {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800953 super.onPause();
954
955 if (mActivityInPause) {
956 Log.e(LOGTAG, "BrowserActivity is already paused.");
957 return;
958 }
959
Mike Reed7bfa63b2009-05-28 11:08:32 -0400960 mTabControl.pauseCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800961 mActivityInPause = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -0400962 if (mTabControl.getCurrentIndex() >= 0 && !pauseWebViewTimers()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800963 mWakeLock.acquire();
964 mHandler.sendMessageDelayed(mHandler
965 .obtainMessage(RELEASE_WAKELOCK), WAKELOCK_TIMEOUT);
966 }
967
Leon Scrogginsa2ab6a72009-09-11 11:49:52 -0400968 // FIXME: This removes the active tabs page and resets the menu to
969 // MAIN_MENU. A better solution might be to do this work in onNewIntent
970 // but then we would need to save it in onSaveInstanceState and restore
971 // it in onCreate/onRestoreInstanceState
972 if (mActiveTabsPage != null) {
973 removeActiveTabPage(true);
974 }
975
The Android Open Source Project0c908882009-03-03 19:32:16 -0800976 cancelStopToast();
977
978 // unregister network state listener
979 unregisterReceiver(mNetworkStateIntentReceiver);
980 WebView.disablePlatformNotifications();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800981 }
982
Grace Kloba22ac16e2009-10-07 18:00:23 -0700983 @Override
984 protected void onDestroy() {
Dave Bort31a6d1c2009-04-13 15:56:49 -0700985 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800986 Log.v(LOGTAG, "BrowserActivity.onDestroy: this=" + this);
987 }
988 super.onDestroy();
Grace Kloba0923d692009-09-23 21:37:25 -0700989
Leon Scroggins8d5fa432009-10-02 15:55:59 -0400990 if (mUploadMessage != null) {
991 mUploadMessage.onReceiveValue(null);
992 mUploadMessage = null;
993 }
994
Grace Kloba0923d692009-09-23 21:37:25 -0700995 if (mTabControl == null) return;
996
Grace Kloba1fc98a32009-10-21 13:23:08 -0700997 // Remove the fake title bar if it is there
998 hideFakeTitleBar();
999
The Android Open Source Project0c908882009-03-03 19:32:16 -08001000 // Remove the current tab and sub window
Grace Kloba22ac16e2009-10-07 18:00:23 -07001001 Tab t = mTabControl.getCurrentTab();
Patrick Scottfb5e77f2009-04-08 19:17:37 -07001002 if (t != null) {
1003 dismissSubWindow(t);
1004 removeTabFromContentView(t);
1005 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001006 // Destroy all the tabs
1007 mTabControl.destroy();
1008 WebIconDatabase.getInstance().close();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001009
Bjorn Bringerta7611812010-03-24 11:12:02 +00001010 // Stop watching the default geolocation permissions
1011 mSystemAllowGeolocationOrigins.stop();
1012 mSystemAllowGeolocationOrigins = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001013 }
1014
1015 @Override
1016 public void onConfigurationChanged(Configuration newConfig) {
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04001017 mConfigChanged = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001018 super.onConfigurationChanged(newConfig);
1019
1020 if (mPageInfoDialog != null) {
1021 mPageInfoDialog.dismiss();
1022 showPageInfo(
1023 mPageInfoView,
Leon Scrogginsc7b92f82010-01-11 18:17:31 -05001024 mPageInfoFromShowSSLCertificateOnError);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001025 }
1026 if (mSSLCertificateDialog != null) {
1027 mSSLCertificateDialog.dismiss();
1028 showSSLCertificate(
1029 mSSLCertificateView);
1030 }
1031 if (mSSLCertificateOnErrorDialog != null) {
1032 mSSLCertificateOnErrorDialog.dismiss();
1033 showSSLCertificateOnError(
1034 mSSLCertificateOnErrorView,
1035 mSSLCertificateOnErrorHandler,
1036 mSSLCertificateOnErrorError);
1037 }
1038 if (mHttpAuthenticationDialog != null) {
1039 String title = ((TextView) mHttpAuthenticationDialog
1040 .findViewById(com.android.internal.R.id.alertTitle)).getText()
1041 .toString();
1042 String name = ((TextView) mHttpAuthenticationDialog
1043 .findViewById(R.id.username_edit)).getText().toString();
1044 String password = ((TextView) mHttpAuthenticationDialog
1045 .findViewById(R.id.password_edit)).getText().toString();
1046 int focusId = mHttpAuthenticationDialog.getCurrentFocus()
1047 .getId();
1048 mHttpAuthenticationDialog.dismiss();
1049 showHttpAuthentication(mHttpAuthHandler, null, null, title,
1050 name, password, focusId);
1051 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001052 }
1053
Grace Kloba22ac16e2009-10-07 18:00:23 -07001054 @Override
1055 public void onLowMemory() {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001056 super.onLowMemory();
1057 mTabControl.freeMemory();
1058 }
1059
Cary Clarkff4d92c2010-03-25 11:17:03 -04001060 private void resumeWebViewTimers() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001061 Tab tab = mTabControl.getCurrentTab();
Cary Clarkff4d92c2010-03-25 11:17:03 -04001062 if (tab == null) return; // monkey can trigger this
Grace Kloba22ac16e2009-10-07 18:00:23 -07001063 boolean inLoad = tab.inLoad();
1064 if ((!mActivityInPause && !inLoad) || (mActivityInPause && inLoad)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001065 CookieSyncManager.getInstance().startSync();
Grace Kloba22ac16e2009-10-07 18:00:23 -07001066 WebView w = tab.getWebView();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001067 if (w != null) {
1068 w.resumeTimers();
1069 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001070 }
1071 }
1072
Mike Reed7bfa63b2009-05-28 11:08:32 -04001073 private boolean pauseWebViewTimers() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001074 Tab tab = mTabControl.getCurrentTab();
1075 boolean inLoad = tab.inLoad();
1076 if (mActivityInPause && !inLoad) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001077 CookieSyncManager.getInstance().stopSync();
1078 WebView w = mTabControl.getCurrentWebView();
1079 if (w != null) {
1080 w.pauseTimers();
1081 }
1082 return true;
1083 } else {
1084 return false;
1085 }
1086 }
1087
The Android Open Source Project0c908882009-03-03 19:32:16 -08001088 // Open the icon database and retain all the icons for visited sites.
1089 private void retainIconsOnStartup() {
1090 final WebIconDatabase db = WebIconDatabase.getInstance();
1091 db.open(getDir("icons", 0).getPath());
Leon Scroggins2c0f6112010-03-12 18:09:39 -05001092 Cursor c = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001093 try {
Leon Scroggins2c0f6112010-03-12 18:09:39 -05001094 c = Browser.getAllBookmarks(mResolver);
1095 if (c.moveToFirst()) {
1096 int urlIndex = c.getColumnIndex(Browser.BookmarkColumns.URL);
1097 do {
1098 String url = c.getString(urlIndex);
1099 db.retainIconForPageUrl(url);
1100 } while (c.moveToNext());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001101 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001102 } catch (IllegalStateException e) {
1103 Log.e(LOGTAG, "retainIconsOnStartup", e);
Leon Scroggins2c0f6112010-03-12 18:09:39 -05001104 } finally {
1105 if (c!= null) c.close();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001106 }
1107 }
1108
1109 // Helper method for getting the top window.
1110 WebView getTopWindow() {
1111 return mTabControl.getCurrentTopWebView();
1112 }
1113
Grace Kloba22ac16e2009-10-07 18:00:23 -07001114 TabControl getTabControl() {
1115 return mTabControl;
1116 }
1117
The Android Open Source Project0c908882009-03-03 19:32:16 -08001118 @Override
1119 public boolean onCreateOptionsMenu(Menu menu) {
1120 super.onCreateOptionsMenu(menu);
1121
1122 MenuInflater inflater = getMenuInflater();
1123 inflater.inflate(R.menu.browser, menu);
1124 mMenu = menu;
1125 updateInLoadMenuItems();
1126 return true;
1127 }
1128
1129 /**
1130 * As the menu can be open when loading state changes
1131 * we must manually update the state of the stop/reload menu
1132 * item
1133 */
1134 private void updateInLoadMenuItems() {
1135 if (mMenu == null) {
1136 return;
1137 }
Michael Kolbe0a36662010-06-29 10:37:12 -07001138 MenuItem dest = mMenu.findItem(R.id.stop_reload_menu_id);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001139 MenuItem src = mInLoad ?
1140 mMenu.findItem(R.id.stop_menu_id):
Michael Kolbe0a36662010-06-29 10:37:12 -07001141 mMenu.findItem(R.id.reload_menu_id);
1142 if (src != null) {
1143 dest.setIcon(src.getIcon());
1144 dest.setTitle(src.getTitle());
1145 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001146 }
1147
1148 @Override
1149 public boolean onContextItemSelected(MenuItem item) {
1150 // chording is not an issue with context menus, but we use the same
1151 // options selector, so set mCanChord to true so we can access them.
1152 mCanChord = true;
1153 int id = item.getItemId();
Leon Scroggins96afcb12009-12-10 12:35:56 -05001154 boolean result = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001155 switch (id) {
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001156 // For the context menu from the title bar
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001157 case R.id.title_bar_copy_page_url:
Leon Scroggins96afcb12009-12-10 12:35:56 -05001158 Tab currentTab = mTabControl.getCurrentTab();
1159 if (null == currentTab) {
1160 result = false;
1161 break;
1162 }
1163 WebView mainView = currentTab.getWebView();
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001164 if (null == mainView) {
Leon Scroggins96afcb12009-12-10 12:35:56 -05001165 result = false;
1166 break;
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001167 }
Leon Scroggins96afcb12009-12-10 12:35:56 -05001168 copy(mainView.getUrl());
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001169 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001170 // -- Browser context menu
1171 case R.id.open_context_menu_id:
The Android Open Source Project0c908882009-03-03 19:32:16 -08001172 case R.id.bookmark_context_menu_id:
1173 case R.id.save_link_context_menu_id:
1174 case R.id.share_link_context_menu_id:
1175 case R.id.copy_link_context_menu_id:
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001176 final WebView webView = getTopWindow();
1177 if (null == webView) {
Leon Scroggins96afcb12009-12-10 12:35:56 -05001178 result = false;
1179 break;
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001180 }
1181 final HashMap hrefMap = new HashMap();
1182 hrefMap.put("webview", webView);
1183 final Message msg = mHandler.obtainMessage(
1184 FOCUS_NODE_HREF, id, 0, hrefMap);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001185 webView.requestFocusNodeHref(msg);
1186 break;
1187
1188 default:
1189 // For other context menus
Leon Scroggins96afcb12009-12-10 12:35:56 -05001190 result = onOptionsItemSelected(item);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001191 }
1192 mCanChord = false;
Leon Scroggins96afcb12009-12-10 12:35:56 -05001193 return result;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001194 }
1195
1196 private Bundle createGoogleSearchSourceBundle(String source) {
1197 Bundle bundle = new Bundle();
Bjorn Bringert10d1cca2010-02-10 14:22:12 +00001198 bundle.putString(Search.SOURCE, source);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001199 return bundle;
1200 }
1201
Leon Scroggins8ad29922010-02-16 12:33:55 -05001202 /* package */ void editUrl() {
Leon Scroggins68579392009-09-15 15:31:54 -04001203 if (mOptionsMenuOpen) closeOptionsMenu();
Leon Scroggins5bbe9802009-07-31 13:10:55 -04001204 String url = (getTopWindow() == null) ? null : getTopWindow().getUrl();
Grace Kloba83f47342009-07-20 10:44:31 -07001205 startSearch(mSettings.getHomePage().equals(url) ? null : url, true,
Leon Scroggins8ad29922010-02-16 12:33:55 -05001206 null, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001207 }
1208
Leon Scroggins8ad29922010-02-16 12:33:55 -05001209 /**
1210 * Overriding this to insert a local information bundle
1211 */
The Android Open Source Project0c908882009-03-03 19:32:16 -08001212 @Override
1213 public void startSearch(String initialQuery, boolean selectInitialQuery,
1214 Bundle appSearchData, boolean globalSearch) {
1215 if (appSearchData == null) {
1216 appSearchData = createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_TYPE);
1217 }
Leon Scroggins III430057d2010-09-14 10:57:37 -04001218
1219 SearchEngine searchEngine = mSettings.getSearchEngine();
1220 if (searchEngine != null && !searchEngine.supportsVoiceSearch()) {
1221 appSearchData.putBoolean(SearchManager.DISABLE_VOICE_SEARCH, true);
1222 }
1223
The Android Open Source Project0c908882009-03-03 19:32:16 -08001224 super.startSearch(initialQuery, selectInitialQuery, appSearchData, globalSearch);
1225 }
1226
Leon Scroggins1f005d32009-08-10 17:36:42 -04001227 /**
1228 * Switch tabs. Called by the TitleBarSet when sliding the title bar
1229 * results in changing tabs.
Leon Scroggins160a7e72009-08-14 18:28:01 -04001230 * @param index Index of the tab to change to, as defined by
1231 * mTabControl.getTabIndex(Tab t).
1232 * @return boolean True if we successfully switched to a different tab. If
1233 * the indexth tab is null, or if that tab is the same as
1234 * the current one, return false.
Leon Scroggins1f005d32009-08-10 17:36:42 -04001235 */
Leon Scroggins160a7e72009-08-14 18:28:01 -04001236 /* package */ boolean switchToTab(int index) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001237 Tab tab = mTabControl.getTab(index);
1238 Tab currentTab = mTabControl.getCurrentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04001239 if (tab == null || tab == currentTab) {
Leon Scroggins160a7e72009-08-14 18:28:01 -04001240 return false;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001241 }
1242 if (currentTab != null) {
1243 // currentTab may be null if it was just removed. In that case,
1244 // we do not need to remove it
1245 removeTabFromContentView(currentTab);
1246 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001247 mTabControl.setCurrentTab(tab);
1248 attachTabToContentView(tab);
Grace Klobaeb6eef42009-09-15 17:56:32 -07001249 resetTitleIconAndProgress();
1250 updateLockIconToLatest();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001251 return true;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001252 }
1253
Grace Kloba22ac16e2009-10-07 18:00:23 -07001254 /* package */ Tab openTabToHomePage() {
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001255 return openTabAndShow(mSettings.getHomePage(), false, null);
1256 }
1257
Leon Scroggins1f005d32009-08-10 17:36:42 -04001258 /* package */ void closeCurrentWindow() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001259 final Tab current = mTabControl.getCurrentTab();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001260 if (mTabControl.getTabCount() == 1) {
Leon Scroggins30444232009-09-04 18:36:20 -04001261 // This is the last tab. Open a new one, with the home
1262 // page and close the current one.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001263 openTabToHomePage();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001264 closeTab(current);
Leon Scroggins160a7e72009-08-14 18:28:01 -04001265 return;
1266 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07001267 final Tab parent = current.getParentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04001268 int indexToShow = -1;
1269 if (parent != null) {
1270 indexToShow = mTabControl.getTabIndex(parent);
1271 } else {
Leon Scroggins160a7e72009-08-14 18:28:01 -04001272 final int currentIndex = mTabControl.getCurrentIndex();
1273 // Try to move to the tab to the right
1274 indexToShow = currentIndex + 1;
1275 if (indexToShow > mTabControl.getTabCount() - 1) {
1276 // Try to move to the tab to the left
1277 indexToShow = currentIndex - 1;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001278 }
1279 }
Leon Scroggins160a7e72009-08-14 18:28:01 -04001280 if (switchToTab(indexToShow)) {
1281 // Close window
1282 closeTab(current);
1283 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001284 }
1285
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001286 private ActiveTabsPage mActiveTabsPage;
1287
1288 /**
1289 * Remove the active tabs page.
1290 * @param needToAttach If true, the active tabs page did not attach a tab
1291 * to the content view, so we need to do that here.
1292 */
1293 /* package */ void removeActiveTabPage(boolean needToAttach) {
1294 mContentView.removeView(mActiveTabsPage);
Leon Scrogginsd746a942010-05-19 13:21:44 -04001295 mTitleBar.setVisibility(View.VISIBLE);
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001296 mActiveTabsPage = null;
1297 mMenuState = R.id.MAIN_MENU;
1298 if (needToAttach) {
1299 attachTabToContentView(mTabControl.getCurrentTab());
1300 }
1301 getTopWindow().requestFocus();
1302 }
1303
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04001304 @Override
1305 public ActionMode onStartActionMode(ActionMode.Callback callback) {
Leon Scroggins4fc12cb2010-08-24 14:24:05 -04001306 mActionMode = super.onStartActionMode(callback);
1307 hideFakeTitleBar();
1308 // Would like to change the MENU, but onEndActionMode may not be called
1309 return mActionMode;
Cary Clark01cfcdd2010-06-04 16:36:45 -04001310 }
1311
The Android Open Source Project0c908882009-03-03 19:32:16 -08001312 @Override
1313 public boolean onOptionsItemSelected(MenuItem item) {
Michael Kolbed217742010-08-10 17:52:34 -07001314 // check the action bar button before mCanChord check, as the prepare call
1315 // doesn't come for action bar buttons
1316 if (item.getItemId() == R.id.newtab) {
Michael Kolb300b7f02010-08-25 13:47:24 -07001317 openTabToHomePage();
Michael Kolbed217742010-08-10 17:52:34 -07001318 return true;
1319 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001320 if (!mCanChord) {
1321 // The user has already fired a shortcut with this hold down of the
1322 // menu key.
1323 return false;
1324 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001325 if (null == getTopWindow()) {
Leon Scroggins0d7ae0e2009-06-05 11:04:45 -04001326 return false;
1327 }
Grace Kloba6ee9c492009-07-13 10:04:34 -07001328 if (mMenuIsDown) {
1329 // The shortcut action consumes the MENU. Even if it is still down,
1330 // it won't trigger the next shortcut action. In the case of the
1331 // shortcut action triggering a new activity, like Bookmarks, we
1332 // won't get onKeyUp for MENU. So it is important to reset it here.
1333 mMenuIsDown = false;
1334 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001335 switch (item.getItemId()) {
1336 // -- Main menu
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001337 case R.id.new_tab_menu_id:
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001338 openTabToHomePage();
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001339 break;
1340
Michael Kolbae62fd42010-08-18 16:33:28 -07001341 case R.id.incognito_menu_id:
1342 openIncognitoTab();
1343 break;
1344
Leon Scroggins64b80f32009-08-07 12:03:34 -04001345 case R.id.goto_menu_id:
Leon Scroggins8ad29922010-02-16 12:33:55 -05001346 editUrl();
Leon Scrogginsb3a5bed2009-09-28 11:21:56 -04001347 break;
1348
1349 case R.id.bookmarks_menu_id:
Michael Kolb68792c82010-08-09 16:39:18 -07001350 bookmarksOrHistoryPicker(false, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001351 break;
1352
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001353 case R.id.active_tabs_menu_id:
1354 mActiveTabsPage = new ActiveTabsPage(this, mTabControl);
1355 removeTabFromContentView(mTabControl.getCurrentTab());
Leon Scrogginsd746a942010-05-19 13:21:44 -04001356 mTitleBar.setVisibility(View.GONE);
Leon Scroggins43de6162009-09-14 19:59:58 -04001357 hideFakeTitleBar();
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001358 mContentView.addView(mActiveTabsPage, COVER_SCREEN_PARAMS);
1359 mActiveTabsPage.requestFocus();
1360 mMenuState = EMPTY_MENU;
1361 break;
1362
Leon Scroggins1f005d32009-08-10 17:36:42 -04001363 case R.id.add_bookmark_menu_id:
Leon Scroggins571b3762010-05-26 10:25:01 -04001364 bookmarkCurrentPage();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001365 break;
1366
1367 case R.id.stop_reload_menu_id:
1368 if (mInLoad) {
1369 stopLoading();
1370 } else {
1371 getTopWindow().reload();
1372 }
1373 break;
1374
1375 case R.id.back_menu_id:
1376 getTopWindow().goBack();
1377 break;
1378
1379 case R.id.forward_menu_id:
1380 getTopWindow().goForward();
1381 break;
1382
1383 case R.id.close_menu_id:
1384 // Close the subwindow if it exists.
1385 if (mTabControl.getCurrentSubWindow() != null) {
1386 dismissSubWindow(mTabControl.getCurrentTab());
1387 break;
1388 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001389 closeCurrentWindow();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001390 break;
1391
1392 case R.id.homepage_menu_id:
Grace Kloba22ac16e2009-10-07 18:00:23 -07001393 Tab current = mTabControl.getCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001394 if (current != null) {
1395 dismissSubWindow(current);
Leon Scroggins92472e82010-02-17 16:32:28 -05001396 loadUrl(current.getWebView(), mSettings.getHomePage());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001397 }
1398 break;
1399
1400 case R.id.preferences_menu_id:
1401 Intent intent = new Intent(this,
1402 BrowserPreferencesPage.class);
Leon Scrogginsd5304942009-12-10 16:11:39 -05001403 intent.putExtra(BrowserPreferencesPage.CURRENT_PAGE,
1404 getTopWindow().getUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001405 startActivityForResult(intent, PREFERENCES_PAGE);
1406 break;
1407
1408 case R.id.find_menu_id:
Leon Scroggins4fc12cb2010-08-24 14:24:05 -04001409 getTopWindow().showFindDialog(null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001410 break;
1411
Elliott Slaughter0ced08c2010-06-30 11:40:42 -07001412 case R.id.save_webarchive_menu_id:
1413 if (LOGD_ENABLED) {
1414 Log.d(LOGTAG, "Save as Web Archive");
1415 }
Elliott Slaughteraba242c2010-09-01 16:21:07 -07001416 String state = Environment.getExternalStorageState();
1417 if (Environment.MEDIA_MOUNTED.equals(state)) {
1418 String directory = Environment.getExternalStoragePublicDirectory(
1419 Environment.DIRECTORY_DOWNLOADS).getAbsolutePath() + File.separator;
1420 getTopWindow().saveWebArchive(directory, true, new ValueCallback<String>() {
1421 @Override
1422 public void onReceiveValue(String value) {
1423 if (value != null) {
1424 Toast.makeText(BrowserActivity.this, R.string.webarchive_saved,
1425 Toast.LENGTH_SHORT).show();
1426 } else {
1427 Toast.makeText(BrowserActivity.this, R.string.webarchive_failed,
1428 Toast.LENGTH_SHORT).show();
1429 }
Elliott Slaughter0ced08c2010-06-30 11:40:42 -07001430 }
Elliott Slaughteraba242c2010-09-01 16:21:07 -07001431 });
1432 } else {
1433 Toast.makeText(BrowserActivity.this, R.string.webarchive_failed,
1434 Toast.LENGTH_SHORT).show();
1435 }
Elliott Slaughter0ced08c2010-06-30 11:40:42 -07001436 break;
1437
The Android Open Source Project0c908882009-03-03 19:32:16 -08001438 case R.id.page_info_menu_id:
1439 showPageInfo(mTabControl.getCurrentTab(), false);
1440 break;
1441
1442 case R.id.classic_history_menu_id:
Michael Kolb68792c82010-08-09 16:39:18 -07001443 bookmarksOrHistoryPicker(true, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001444 break;
1445
Leon Scroggins96afcb12009-12-10 12:35:56 -05001446 case R.id.title_bar_share_page_url:
The Android Open Source Project0c908882009-03-03 19:32:16 -08001447 case R.id.share_page_menu_id:
Leon Scroggins96afcb12009-12-10 12:35:56 -05001448 Tab currentTab = mTabControl.getCurrentTab();
1449 if (null == currentTab) {
1450 mCanChord = false;
1451 return false;
1452 }
1453 currentTab.populatePickerData();
1454 sharePage(this, currentTab.getTitle(),
1455 currentTab.getUrl(), currentTab.getFavicon(),
Ben Murdoch87cc65d2010-06-29 20:34:10 +01001456 createScreenshot(currentTab.getWebView(), getDesiredThumbnailWidth(this),
1457 getDesiredThumbnailHeight(this)));
The Android Open Source Project0c908882009-03-03 19:32:16 -08001458 break;
1459
1460 case R.id.dump_nav_menu_id:
1461 getTopWindow().debugDump();
1462 break;
1463
Andrei Popescu7a8b88b2010-02-02 00:30:38 +00001464 case R.id.dump_counters_menu_id:
1465 getTopWindow().dumpV8Counters();
1466 break;
1467
The Android Open Source Project0c908882009-03-03 19:32:16 -08001468 case R.id.zoom_in_menu_id:
1469 getTopWindow().zoomIn();
1470 break;
1471
1472 case R.id.zoom_out_menu_id:
1473 getTopWindow().zoomOut();
1474 break;
1475
1476 case R.id.view_downloads_menu_id:
1477 viewDownloads(null);
1478 break;
1479
The Android Open Source Project0c908882009-03-03 19:32:16 -08001480 case R.id.window_one_menu_id:
1481 case R.id.window_two_menu_id:
1482 case R.id.window_three_menu_id:
1483 case R.id.window_four_menu_id:
1484 case R.id.window_five_menu_id:
1485 case R.id.window_six_menu_id:
1486 case R.id.window_seven_menu_id:
1487 case R.id.window_eight_menu_id:
1488 {
1489 int menuid = item.getItemId();
1490 for (int id = 0; id < WINDOW_SHORTCUT_ID_ARRAY.length; id++) {
1491 if (WINDOW_SHORTCUT_ID_ARRAY[id] == menuid) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001492 Tab desiredTab = mTabControl.getTab(id);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001493 if (desiredTab != null &&
1494 desiredTab != mTabControl.getCurrentTab()) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001495 switchToTab(id);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001496 }
1497 break;
1498 }
1499 }
1500 }
1501 break;
1502
1503 default:
1504 if (!super.onOptionsItemSelected(item)) {
1505 return false;
1506 }
1507 // Otherwise fall through.
1508 }
1509 mCanChord = false;
1510 return true;
1511 }
1512
Leon Scroggins571b3762010-05-26 10:25:01 -04001513 /* package */ void bookmarkCurrentPage() {
1514 Intent i = new Intent(BrowserActivity.this,
1515 AddBookmarkPage.class);
1516 WebView w = getTopWindow();
1517 i.putExtra("url", w.getUrl());
1518 i.putExtra("title", w.getTitle());
1519 i.putExtra("touch_icon_url", w.getTouchIconUrl());
Ben Murdoch87cc65d2010-06-29 20:34:10 +01001520 i.putExtra("thumbnail", createScreenshot(w, getDesiredThumbnailWidth(this),
1521 getDesiredThumbnailHeight(this)));
Ben Murdocheecb4e62010-07-06 16:30:38 +01001522 i.putExtra("url_editable", false);
Leon Scroggins571b3762010-05-26 10:25:01 -04001523 startActivity(i);
1524 }
1525
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04001526 /*
1527 * True if a custom ActionMode (i.e. find or select) is in use.
1528 */
1529 private boolean isInCustomActionMode() {
1530 return mActionMode != null;
Cary Clark01cfcdd2010-06-04 16:36:45 -04001531 }
1532
1533 /*
Leon Scroggins4fc12cb2010-08-24 14:24:05 -04001534 * End the current ActionMode.
Cary Clark01cfcdd2010-06-04 16:36:45 -04001535 */
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04001536 void endActionMode() {
1537 if (mActionMode != null) {
Leon Scroggins4fc12cb2010-08-24 14:24:05 -04001538 ActionMode mode = mActionMode;
1539 onEndActionMode();
1540 mode.finish();
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04001541 }
1542 }
1543
1544 /*
1545 * Called by find and select when they are finished. Replace title bars
1546 * as necessary.
1547 */
1548 public void onEndActionMode() {
1549 if (!isInCustomActionMode()) return;
Leon Scroggins79e36d92010-04-29 16:01:46 +01001550 if (mInLoad) {
1551 // The title bar was hidden, because otherwise it would cover up the
Michael Kolba2b2ba82010-08-04 17:54:03 -07001552 // find or select dialog. Now that the dialog has been removed,
Cary Clark01cfcdd2010-06-04 16:36:45 -04001553 // show the fake title bar once again.
Leon Scroggins79e36d92010-04-29 16:01:46 +01001554 showFakeTitleBar();
1555 }
Leon Scroggins4fc12cb2010-08-24 14:24:05 -04001556 // Would like to return the menu state to normal, but this does not
1557 // necessarily get called.
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04001558 mActionMode = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001559 }
1560
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04001561 // For select and find, we keep track of the ActionMode so that
1562 // finish() can be called as desired.
1563 private ActionMode mActionMode;
1564
Grace Kloba22ac16e2009-10-07 18:00:23 -07001565 @Override
1566 public boolean onPrepareOptionsMenu(Menu menu) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001567 // This happens when the user begins to hold down the menu key, so
1568 // allow them to chord to get a shortcut.
1569 mCanChord = true;
1570 // Note: setVisible will decide whether an item is visible; while
1571 // setEnabled() will decide whether an item is enabled, which also means
1572 // whether the matching shortcut key will function.
1573 super.onPrepareOptionsMenu(menu);
1574 switch (mMenuState) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001575 case EMPTY_MENU:
1576 if (mCurrentMenuState != mMenuState) {
1577 menu.setGroupVisible(R.id.MAIN_MENU, false);
1578 menu.setGroupEnabled(R.id.MAIN_MENU, false);
1579 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001580 }
1581 break;
1582 default:
1583 if (mCurrentMenuState != mMenuState) {
1584 menu.setGroupVisible(R.id.MAIN_MENU, true);
1585 menu.setGroupEnabled(R.id.MAIN_MENU, true);
1586 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001587 }
1588 final WebView w = getTopWindow();
1589 boolean canGoBack = false;
1590 boolean canGoForward = false;
1591 boolean isHome = false;
1592 if (w != null) {
1593 canGoBack = w.canGoBack();
1594 canGoForward = w.canGoForward();
1595 isHome = mSettings.getHomePage().equals(w.getUrl());
1596 }
1597 final MenuItem back = menu.findItem(R.id.back_menu_id);
1598 back.setEnabled(canGoBack);
1599
1600 final MenuItem home = menu.findItem(R.id.homepage_menu_id);
1601 home.setEnabled(!isHome);
1602
Michael Kolbe0a36662010-06-29 10:37:12 -07001603 final MenuItem forward = menu.findItem(R.id.forward_menu_id);
1604 forward.setEnabled(canGoForward);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001605
Michael Kolbed217742010-08-10 17:52:34 -07001606 if (!mXLargeScreenSize) {
1607 final MenuItem newtab = menu.findItem(R.id.new_tab_menu_id);
1608 newtab.setEnabled(mTabControl.canCreateNewTab());
1609 }
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001610
The Android Open Source Project0c908882009-03-03 19:32:16 -08001611 // decide whether to show the share link option
1612 PackageManager pm = getPackageManager();
1613 Intent send = new Intent(Intent.ACTION_SEND);
1614 send.setType("text/plain");
1615 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1616 menu.findItem(R.id.share_page_menu_id).setVisible(ri != null);
1617
The Android Open Source Project0c908882009-03-03 19:32:16 -08001618 boolean isNavDump = mSettings.isNavDump();
1619 final MenuItem nav = menu.findItem(R.id.dump_nav_menu_id);
1620 nav.setVisible(isNavDump);
1621 nav.setEnabled(isNavDump);
Andrei Popescu7a8b88b2010-02-02 00:30:38 +00001622
1623 boolean showDebugSettings = mSettings.showDebugSettings();
1624 final MenuItem counter = menu.findItem(R.id.dump_counters_menu_id);
1625 counter.setVisible(showDebugSettings);
1626 counter.setEnabled(showDebugSettings);
1627
The Android Open Source Project0c908882009-03-03 19:32:16 -08001628 break;
1629 }
1630 mCurrentMenuState = mMenuState;
1631 return true;
1632 }
1633
1634 @Override
1635 public void onCreateContextMenu(ContextMenu menu, View v,
1636 ContextMenuInfo menuInfo) {
Leon Scroggins571b3762010-05-26 10:25:01 -04001637 if (v instanceof TitleBarBase) {
Leon Scroggins4e9f89b2010-02-22 16:54:14 -05001638 return;
1639 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001640 WebView webview = (WebView) v;
1641 WebView.HitTestResult result = webview.getHitTestResult();
1642 if (result == null) {
1643 return;
1644 }
1645
1646 int type = result.getType();
1647 if (type == WebView.HitTestResult.UNKNOWN_TYPE) {
1648 Log.w(LOGTAG,
1649 "We should not show context menu when nothing is touched");
1650 return;
1651 }
1652 if (type == WebView.HitTestResult.EDIT_TEXT_TYPE) {
1653 // let TextView handles context menu
1654 return;
1655 }
1656
1657 // Note, http://b/issue?id=1106666 is requesting that
1658 // an inflated menu can be used again. This is not available
1659 // yet, so inflate each time (yuk!)
1660 MenuInflater inflater = getMenuInflater();
1661 inflater.inflate(R.menu.browsercontext, menu);
1662
1663 // Show the correct menu group
Leon Scroggins III9e997c72010-05-26 13:25:16 -04001664 final String extra = result.getExtra();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001665 menu.setGroupVisible(R.id.PHONE_MENU,
1666 type == WebView.HitTestResult.PHONE_TYPE);
1667 menu.setGroupVisible(R.id.EMAIL_MENU,
1668 type == WebView.HitTestResult.EMAIL_TYPE);
1669 menu.setGroupVisible(R.id.GEO_MENU,
1670 type == WebView.HitTestResult.GEO_TYPE);
1671 menu.setGroupVisible(R.id.IMAGE_MENU,
1672 type == WebView.HitTestResult.IMAGE_TYPE
1673 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1674 menu.setGroupVisible(R.id.ANCHOR_MENU,
1675 type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1676 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1677
1678 // Setup custom handling depending on the type
1679 switch (type) {
1680 case WebView.HitTestResult.PHONE_TYPE:
1681 menu.setHeaderTitle(Uri.decode(extra));
1682 menu.findItem(R.id.dial_context_menu_id).setIntent(
1683 new Intent(Intent.ACTION_VIEW, Uri
1684 .parse(WebView.SCHEME_TEL + extra)));
1685 Intent addIntent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
1686 addIntent.putExtra(Insert.PHONE, Uri.decode(extra));
Cary Clark5e335a32009-09-22 14:53:11 -04001687 addIntent.setType(ContactsContract.Contacts.CONTENT_ITEM_TYPE);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001688 menu.findItem(R.id.add_contact_context_menu_id).setIntent(
1689 addIntent);
1690 menu.findItem(R.id.copy_phone_context_menu_id).setOnMenuItemClickListener(
1691 new Copy(extra));
1692 break;
1693
1694 case WebView.HitTestResult.EMAIL_TYPE:
1695 menu.setHeaderTitle(extra);
1696 menu.findItem(R.id.email_context_menu_id).setIntent(
1697 new Intent(Intent.ACTION_VIEW, Uri
1698 .parse(WebView.SCHEME_MAILTO + extra)));
1699 menu.findItem(R.id.copy_mail_context_menu_id).setOnMenuItemClickListener(
1700 new Copy(extra));
1701 break;
1702
1703 case WebView.HitTestResult.GEO_TYPE:
1704 menu.setHeaderTitle(extra);
1705 menu.findItem(R.id.map_context_menu_id).setIntent(
1706 new Intent(Intent.ACTION_VIEW, Uri
1707 .parse(WebView.SCHEME_GEO
1708 + URLEncoder.encode(extra))));
1709 menu.findItem(R.id.copy_geo_context_menu_id).setOnMenuItemClickListener(
1710 new Copy(extra));
1711 break;
1712
1713 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1714 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
1715 TextView titleView = (TextView) LayoutInflater.from(this)
1716 .inflate(android.R.layout.browser_link_context_header,
1717 null);
1718 titleView.setText(extra);
1719 menu.setHeaderView(titleView);
1720 // decide whether to show the open link in new tab option
Leon Scroggins III9e997c72010-05-26 13:25:16 -04001721 boolean showNewTab = mTabControl.canCreateNewTab();
1722 MenuItem newTabItem
1723 = menu.findItem(R.id.open_newtab_context_menu_id);
1724 newTabItem.setVisible(showNewTab);
1725 if (showNewTab) {
1726 newTabItem.setOnMenuItemClickListener(
1727 new MenuItem.OnMenuItemClickListener() {
1728 public boolean onMenuItemClick(MenuItem item) {
1729 final Tab parent = mTabControl.getCurrentTab();
Michael Kolb68792c82010-08-09 16:39:18 -07001730 final Tab newTab = openTab(extra, false);
Leon Scroggins III9e997c72010-05-26 13:25:16 -04001731 if (newTab != parent) {
1732 parent.addChildTab(newTab);
1733 }
1734 return true;
1735 }
1736 });
1737 }
Ben Murdochde353622009-10-12 10:29:00 +01001738 menu.findItem(R.id.bookmark_context_menu_id).setVisible(
1739 Bookmarks.urlHasAcceptableScheme(extra));
The Android Open Source Project0c908882009-03-03 19:32:16 -08001740 PackageManager pm = getPackageManager();
1741 Intent send = new Intent(Intent.ACTION_SEND);
1742 send.setType("text/plain");
1743 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1744 menu.findItem(R.id.share_link_context_menu_id).setVisible(ri != null);
1745 if (type == WebView.HitTestResult.SRC_ANCHOR_TYPE) {
1746 break;
1747 }
1748 // otherwise fall through to handle image part
1749 case WebView.HitTestResult.IMAGE_TYPE:
1750 if (type == WebView.HitTestResult.IMAGE_TYPE) {
1751 menu.setHeaderTitle(extra);
1752 }
1753 menu.findItem(R.id.view_image_context_menu_id).setIntent(
1754 new Intent(Intent.ACTION_VIEW, Uri.parse(extra)));
1755 menu.findItem(R.id.download_context_menu_id).
1756 setOnMenuItemClickListener(new Download(extra));
Ben Murdoch4f75ba22009-10-27 11:48:28 +00001757 menu.findItem(R.id.set_wallpaper_context_menu_id).
1758 setOnMenuItemClickListener(new SetAsWallpaper(extra));
The Android Open Source Project0c908882009-03-03 19:32:16 -08001759 break;
1760
1761 default:
1762 Log.w(LOGTAG, "We should not get here.");
1763 break;
1764 }
Leon Scrogginsb2b19f52009-10-09 16:10:00 -04001765 hideFakeTitleBar();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001766 }
1767
The Android Open Source Project0c908882009-03-03 19:32:16 -08001768 // Attach the given tab to the content view.
Grace Klobac928c302009-09-17 11:51:21 -07001769 // this should only be called for the current tab.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001770 private void attachTabToContentView(Tab t) {
Steve Block2bc69912009-07-30 14:45:13 +01001771 // Attach the container that contains the main WebView and any other UI
1772 // associated with the tab.
Patrick Scottd0119532009-09-17 08:00:31 -04001773 t.attachTabToContentView(mContentView);
Ben Murdochbff2d602009-07-01 20:19:05 +01001774
1775 if (mShouldShowErrorConsole) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001776 ErrorConsoleView errorConsole = t.getErrorConsole(true);
Ben Murdochbff2d602009-07-01 20:19:05 +01001777 if (errorConsole.numberOfErrors() == 0) {
1778 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
1779 } else {
1780 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
1781 }
1782
1783 mErrorConsoleContainer.addView(errorConsole,
Romain Guy15b8ec62010-01-08 15:06:43 -08001784 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
Ben Murdochbff2d602009-07-01 20:19:05 +01001785 ViewGroup.LayoutParams.WRAP_CONTENT));
1786 }
1787
Michael Kolba2b2ba82010-08-04 17:54:03 -07001788 WebView view = t.getWebView();
1789 view.setEmbeddedTitleBar(mTitleBar);
Leon Scroggins58d56c62010-01-28 15:12:40 -05001790 if (t.isInVoiceSearchMode()) {
1791 showVoiceTitleBar(t.getVoiceDisplayTitle());
1792 } else {
1793 revertVoiceTitleBar();
1794 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001795 // Request focus on the top window.
1796 t.getTopWindow().requestFocus();
Michael Kolba2b2ba82010-08-04 17:54:03 -07001797 if (mTabControl.getTabChangeListener() != null) {
1798 mTabControl.getTabChangeListener().onCurrentTab(t);
1799 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001800 }
1801
1802 // Attach a sub window to the main WebView of the given tab.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001803 void attachSubWindow(Tab t) {
Patrick Scottd0119532009-09-17 08:00:31 -04001804 t.attachSubWindow(mContentView);
1805 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001806 }
1807
1808 // Remove the given tab from the content view.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001809 private void removeTabFromContentView(Tab t) {
Steve Block2bc69912009-07-30 14:45:13 +01001810 // Remove the container that contains the main WebView.
Patrick Scottd0119532009-09-17 08:00:31 -04001811 t.removeTabFromContentView(mContentView);
Ben Murdochbff2d602009-07-01 20:19:05 +01001812
Grace Kloba22ac16e2009-10-07 18:00:23 -07001813 ErrorConsoleView errorConsole = t.getErrorConsole(false);
1814 if (errorConsole != null) {
1815 mErrorConsoleContainer.removeView(errorConsole);
Ben Murdochbff2d602009-07-01 20:19:05 +01001816 }
1817
Michael Kolba2b2ba82010-08-04 17:54:03 -07001818 WebView view = t.getWebView();
1819 if (view != null) {
1820 view.setEmbeddedTitleBar(null);
Leon Scrogginsbb85b902009-09-14 19:27:20 -04001821 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001822 }
1823
1824 // Remove the sub window if it exists. Also called by TabControl when the
1825 // user clicks the 'X' to dismiss a sub window.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001826 /* package */ void dismissSubWindow(Tab t) {
Patrick Scottd0119532009-09-17 08:00:31 -04001827 t.removeSubWindow(mContentView);
Grace Kloba22ac16e2009-10-07 18:00:23 -07001828 // dismiss the subwindow. This will destroy the WebView.
1829 t.dismissSubWindow();
Patrick Scottd0119532009-09-17 08:00:31 -04001830 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001831 }
1832
Leon Scroggins1f005d32009-08-10 17:36:42 -04001833 // A wrapper function of {@link #openTabAndShow(UrlData, boolean, String)}
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07001834 // that accepts url as string.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001835 private Tab openTabAndShow(String url, boolean closeOnExit, String appId) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001836 return openTabAndShow(new UrlData(url), closeOnExit, appId);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001837 }
1838
1839 // This method does a ton of stuff. It will attempt to create a new tab
1840 // if we haven't reached MAX_TABS. Otherwise it uses the current tab. If
Leon Scroggins1f005d32009-08-10 17:36:42 -04001841 // url isn't null, it will load the given url.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001842 /* package */Tab openTabAndShow(UrlData urlData, boolean closeOnExit,
1843 String appId) {
1844 final Tab currentTab = mTabControl.getCurrentTab();
1845 if (mTabControl.canCreateNewTab()) {
1846 final Tab tab = mTabControl.createNewTab(closeOnExit, appId,
Elliott Slaughterf0f03952010-07-14 18:10:36 -07001847 urlData.mUrl, false);
Leon Scroggins1f005d32009-08-10 17:36:42 -04001848 WebView webview = tab.getWebView();
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001849 // If the last tab was removed from the active tabs page, currentTab
1850 // will be null.
1851 if (currentTab != null) {
1852 removeTabFromContentView(currentTab);
1853 }
Patrick Scott8bbd69f2009-08-14 13:35:53 -04001854 // We must set the new tab as the current tab to reflect the old
1855 // animation behavior.
1856 mTabControl.setCurrentTab(tab);
Grace Klobaeb6eef42009-09-15 17:56:32 -07001857 attachTabToContentView(tab);
Leon Scroggins160a7e72009-08-14 18:28:01 -04001858 if (!urlData.isEmpty()) {
Patrick Scott9d53da02010-02-19 10:19:01 -05001859 loadUrlDataIn(tab, urlData);
Leon Scroggins1f005d32009-08-10 17:36:42 -04001860 }
1861 return tab;
1862 } else {
1863 // Get rid of the subwindow if it exists
1864 dismissSubWindow(currentTab);
1865 if (!urlData.isEmpty()) {
1866 // Load the given url.
Patrick Scott9d53da02010-02-19 10:19:01 -05001867 loadUrlDataIn(currentTab, urlData);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001868 }
Leon Scroggins58d56c62010-01-28 15:12:40 -05001869 return currentTab;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001870 }
1871 }
1872
Michael Kolb68792c82010-08-09 16:39:18 -07001873 private Tab openTab(String url, boolean forceForeground) {
1874 if (mSettings.openInBackground() && !forceForeground) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001875 Tab t = mTabControl.createNewTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001876 if (t != null) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001877 WebView view = t.getWebView();
Leon Scroggins92472e82010-02-17 16:32:28 -05001878 loadUrl(view, url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001879 }
Grace Klobac9181842009-04-14 08:53:22 -07001880 return t;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001881 } else {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001882 return openTabAndShow(url, false, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001883 }
1884 }
1885
Elliott Slaughterf0f03952010-07-14 18:10:36 -07001886 /* package */ Tab openIncognitoTab() {
1887 if (mTabControl.canCreateNewTab()) {
1888 Tab currentTab = mTabControl.getCurrentTab();
1889 Tab tab = mTabControl.createNewTab(false, null, null, true);
1890 if (currentTab != null) {
1891 removeTabFromContentView(currentTab);
1892 }
1893 mTabControl.setCurrentTab(tab);
1894 attachTabToContentView(tab);
1895 return tab;
1896 }
1897 return null;
1898 }
1899
The Android Open Source Project0c908882009-03-03 19:32:16 -08001900 private class Copy implements OnMenuItemClickListener {
1901 private CharSequence mText;
1902
1903 public boolean onMenuItemClick(MenuItem item) {
1904 copy(mText);
1905 return true;
1906 }
1907
1908 public Copy(CharSequence toCopy) {
1909 mText = toCopy;
1910 }
1911 }
1912
1913 private class Download implements OnMenuItemClickListener {
1914 private String mText;
1915
1916 public boolean onMenuItemClick(MenuItem item) {
1917 onDownloadStartNoStream(mText, null, null, null, -1);
1918 return true;
1919 }
1920
1921 public Download(String toDownload) {
1922 mText = toDownload;
1923 }
1924 }
1925
Ben Murdoch4f75ba22009-10-27 11:48:28 +00001926 private class SetAsWallpaper extends Thread implements
1927 OnMenuItemClickListener, DialogInterface.OnCancelListener {
1928 private URL mUrl;
1929 private ProgressDialog mWallpaperProgress;
1930 private boolean mCanceled = false;
1931
1932 public SetAsWallpaper(String url) {
1933 try {
1934 mUrl = new URL(url);
1935 } catch (MalformedURLException e) {
1936 mUrl = null;
1937 }
1938 }
1939
1940 public void onCancel(DialogInterface dialog) {
1941 mCanceled = true;
1942 }
1943
1944 public boolean onMenuItemClick(MenuItem item) {
1945 if (mUrl != null) {
1946 // The user may have tried to set a image with a large file size as their
1947 // background so it may take a few moments to perform the operation. Display
1948 // a progress spinner while it is working.
1949 mWallpaperProgress = new ProgressDialog(BrowserActivity.this);
1950 mWallpaperProgress.setIndeterminate(true);
1951 mWallpaperProgress.setMessage(getText(R.string.progress_dialog_setting_wallpaper));
1952 mWallpaperProgress.setCancelable(true);
1953 mWallpaperProgress.setOnCancelListener(this);
1954 mWallpaperProgress.show();
1955 start();
1956 }
1957 return true;
1958 }
1959
Michael Kolbe0a36662010-06-29 10:37:12 -07001960 @Override
Ben Murdoch4f75ba22009-10-27 11:48:28 +00001961 public void run() {
1962 Drawable oldWallpaper = BrowserActivity.this.getWallpaper();
1963 try {
1964 // TODO: This will cause the resource to be downloaded again, when we
1965 // should in most cases be able to grab it from the cache. To fix this
1966 // we should query WebCore to see if we can access a cached version and
1967 // instead open an input stream on that. This pattern could also be used
1968 // in the download manager where the same problem exists.
1969 InputStream inputstream = mUrl.openStream();
1970 if (inputstream != null) {
1971 setWallpaper(inputstream);
1972 }
1973 } catch (IOException e) {
1974 Log.e(LOGTAG, "Unable to set new wallpaper");
1975 // Act as though the user canceled the operation so we try to
1976 // restore the old wallpaper.
1977 mCanceled = true;
1978 }
1979
1980 if (mCanceled) {
1981 // Restore the old wallpaper if the user cancelled whilst we were setting
1982 // the new wallpaper.
1983 int width = oldWallpaper.getIntrinsicWidth();
1984 int height = oldWallpaper.getIntrinsicHeight();
1985 Bitmap bm = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
1986 Canvas canvas = new Canvas(bm);
1987 oldWallpaper.setBounds(0, 0, width, height);
1988 oldWallpaper.draw(canvas);
1989 try {
1990 setWallpaper(bm);
1991 } catch (IOException e) {
1992 Log.e(LOGTAG, "Unable to restore old wallpaper.");
1993 }
1994 mCanceled = false;
1995 }
1996
1997 if (mWallpaperProgress.isShowing()) {
1998 mWallpaperProgress.dismiss();
1999 }
2000 }
2001 }
2002
The Android Open Source Project0c908882009-03-03 19:32:16 -08002003 private void copy(CharSequence text) {
Dianne Hackborn80f32622010-08-05 14:17:53 -07002004 ClipboardManager cm = (ClipboardManager)getSystemService(Context.CLIPBOARD_SERVICE);
2005 cm.setText(text);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002006 }
2007
2008 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08002009 * Resets the browser title-view to whatever it must be
2010 * (for example, if we had a loading error)
2011 * When we have a new page, we call resetTitle, when we
2012 * have to reset the titlebar to whatever it used to be
2013 * (for example, if the user chose to stop loading), we
2014 * call resetTitleAndRevertLockIcon.
2015 */
2016 /* package */ void resetTitleAndRevertLockIcon() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002017 mTabControl.getCurrentTab().revertLockIcon();
2018 updateLockIconToLatest();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002019 resetTitleIconAndProgress();
2020 }
2021
2022 /**
2023 * Reset the title, favicon, and progress.
2024 */
2025 private void resetTitleIconAndProgress() {
2026 WebView current = mTabControl.getCurrentWebView();
2027 if (current == null) {
2028 return;
2029 }
2030 resetTitleAndIcon(current);
2031 int progress = current.getProgress();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002032 current.getWebChromeClient().onProgressChanged(current, progress);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002033 }
2034
2035 // Reset the title and the icon based on the given item.
2036 private void resetTitleAndIcon(WebView view) {
2037 WebHistoryItem item = view.copyBackForwardList().getCurrentItem();
2038 if (item != null) {
Leon Scroggins68579392009-09-15 15:31:54 -04002039 setUrlTitle(item.getUrl(), item.getTitle());
The Android Open Source Project0c908882009-03-03 19:32:16 -08002040 setFavicon(item.getFavicon());
2041 } else {
Leon Scroggins68579392009-09-15 15:31:54 -04002042 setUrlTitle(null, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002043 setFavicon(null);
2044 }
2045 }
2046
2047 /**
2048 * Sets a title composed of the URL and the title string.
2049 * @param url The URL of the site being loaded.
2050 * @param title The title of the site being loaded.
2051 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07002052 void setUrlTitle(String url, String title) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002053 mUrl = url;
2054 mTitle = title;
2055
Leon Scroggins58d56c62010-01-28 15:12:40 -05002056 // If we are in voice search mode, the title has already been set.
2057 if (mTabControl.getCurrentTab().isInVoiceSearchMode()) return;
2058 mTitleBar.setDisplayTitle(url);
Michael Kolba2b2ba82010-08-04 17:54:03 -07002059 mFakeTitleBar.setDisplayTitle(url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002060 }
2061
2062 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08002063 * @param url The URL to build a title version of the URL from.
2064 * @return The title version of the URL or null if fails.
2065 * The title version of the URL can be either the URL hostname,
2066 * or the hostname with an "https://" prefix (for secure URLs),
2067 * or an empty string if, for example, the URL in question is a
2068 * file:// URL with no hostname.
2069 */
Leon Scroggins32e14a62009-06-11 10:26:34 -04002070 /* package */ static String buildTitleUrl(String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002071 String titleUrl = null;
2072
2073 if (url != null) {
2074 try {
2075 // parse the url string
2076 URL urlObj = new URL(url);
2077 if (urlObj != null) {
2078 titleUrl = "";
2079
2080 String protocol = urlObj.getProtocol();
2081 String host = urlObj.getHost();
2082
2083 if (host != null && 0 < host.length()) {
2084 titleUrl = host;
2085 if (protocol != null) {
2086 // if a secure site, add an "https://" prefix!
2087 if (protocol.equalsIgnoreCase("https")) {
2088 titleUrl = protocol + "://" + host;
2089 }
2090 }
2091 }
2092 }
2093 } catch (MalformedURLException e) {}
2094 }
2095
2096 return titleUrl;
2097 }
2098
2099 // Set the favicon in the title bar.
Grace Kloba22ac16e2009-10-07 18:00:23 -07002100 void setFavicon(Bitmap icon) {
Leon Scroggins68579392009-09-15 15:31:54 -04002101 mTitleBar.setFavicon(icon);
Michael Kolba2b2ba82010-08-04 17:54:03 -07002102 mFakeTitleBar.setFavicon(icon);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002103 }
2104
2105 /**
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002106 * Close the tab, remove its associated title bar, and adjust mTabControl's
2107 * current tab to a valid value.
Leon Scroggins1f005d32009-08-10 17:36:42 -04002108 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07002109 /* package */ void closeTab(Tab t) {
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002110 int currentIndex = mTabControl.getCurrentIndex();
2111 int removeIndex = mTabControl.getTabIndex(t);
Leon Scroggins1f005d32009-08-10 17:36:42 -04002112 mTabControl.removeTab(t);
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002113 if (currentIndex >= removeIndex && currentIndex != 0) {
2114 currentIndex--;
2115 }
2116 mTabControl.setCurrentTab(mTabControl.getTab(currentIndex));
Andrei Popescua5bf1de2009-09-23 16:39:23 +01002117 resetTitleIconAndProgress();
Leon Scroggins654899b2010-06-25 16:25:23 -04002118 updateLockIconToLatest();
Elliott Slaughtere440a882010-08-20 13:54:45 -07002119
2120 if (!mTabControl.hasAnyOpenIncognitoTabs()) {
2121 WebView.cleanupPrivateBrowsingFiles(this);
2122 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002123 }
2124
Leon Scrogginsdcc5eeb2010-02-23 17:26:37 -05002125 /* package */ void goBackOnePageOrQuit() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002126 Tab current = mTabControl.getCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002127 if (current == null) {
2128 /*
2129 * Instead of finishing the activity, simply push this to the back
2130 * of the stack and let ActivityManager to choose the foreground
2131 * activity. As BrowserActivity is singleTask, it will be always the
2132 * root of the task. So we can use either true or false for
2133 * moveTaskToBack().
2134 */
2135 moveTaskToBack(true);
Grace Kloba00d85e72009-09-23 18:50:05 -07002136 return;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002137 }
2138 WebView w = current.getWebView();
2139 if (w.canGoBack()) {
2140 w.goBack();
2141 } else {
2142 // Check to see if we are closing a window that was created by
2143 // another window. If so, we switch back to that window.
Grace Kloba22ac16e2009-10-07 18:00:23 -07002144 Tab parent = current.getParentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002145 if (parent != null) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04002146 switchToTab(mTabControl.getTabIndex(parent));
2147 // Now we close the other tab
2148 closeTab(current);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002149 } else {
2150 if (current.closeOnExit()) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002151 // force the tab's inLoad() to be false as we are going to
2152 // either finish the activity or remove the tab. This will
2153 // ensure pauseWebViewTimers() taking action.
2154 mTabControl.getCurrentTab().clearInLoad();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002155 if (mTabControl.getTabCount() == 1) {
2156 finish();
2157 return;
2158 }
Mike Reed7bfa63b2009-05-28 11:08:32 -04002159 // call pauseWebViewTimers() now, we won't be able to call
2160 // it in onPause() as the WebView won't be valid.
Grace Klobaec1b5ad2009-08-18 08:42:32 -07002161 // Temporarily change mActivityInPause to be true as
2162 // pauseWebViewTimers() will do nothing if mActivityInPause
2163 // is false.
Grace Kloba918e1d72009-08-13 14:55:06 -07002164 boolean savedState = mActivityInPause;
2165 if (savedState) {
Grace Klobaec1b5ad2009-08-18 08:42:32 -07002166 Log.e(LOGTAG, "BrowserActivity is already paused "
2167 + "while handing goBackOnePageOrQuit.");
Grace Kloba918e1d72009-08-13 14:55:06 -07002168 }
2169 mActivityInPause = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -04002170 pauseWebViewTimers();
Grace Kloba918e1d72009-08-13 14:55:06 -07002171 mActivityInPause = savedState;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002172 removeTabFromContentView(current);
2173 mTabControl.removeTab(current);
2174 }
2175 /*
2176 * Instead of finishing the activity, simply push this to the back
2177 * of the stack and let ActivityManager to choose the foreground
2178 * activity. As BrowserActivity is singleTask, it will be always the
2179 * root of the task. So we can use either true or false for
2180 * moveTaskToBack().
2181 */
2182 moveTaskToBack(true);
2183 }
2184 }
2185 }
2186
Grace Kloba22ac16e2009-10-07 18:00:23 -07002187 boolean isMenuDown() {
2188 return mMenuIsDown;
2189 }
2190
Grace Kloba5942df02009-09-18 11:48:29 -07002191 @Override
2192 public boolean onKeyDown(int keyCode, KeyEvent event) {
Leon Scrogginsf65b50d2009-12-08 10:44:28 -05002193 // Even if MENU is already held down, we need to call to super to open
2194 // the IME on long press.
2195 if (KeyEvent.KEYCODE_MENU == keyCode) {
2196 mMenuIsDown = true;
2197 return super.onKeyDown(keyCode, event);
2198 }
Grace Kloba5942df02009-09-18 11:48:29 -07002199 // The default key mode is DEFAULT_KEYS_SEARCH_LOCAL. As the MENU is
2200 // still down, we don't want to trigger the search. Pretend to consume
2201 // the key and do nothing.
2202 if (mMenuIsDown) return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002203
Grace Kloba5942df02009-09-18 11:48:29 -07002204 switch(keyCode) {
Grace Kloba5942df02009-09-18 11:48:29 -07002205 case KeyEvent.KEYCODE_SPACE:
Grace Klobada0fe552009-09-22 18:17:24 -07002206 // WebView/WebTextView handle the keys in the KeyDown. As
2207 // the Activity's shortcut keys are only handled when WebView
2208 // doesn't, have to do it in onKeyDown instead of onKeyUp.
2209 if (event.isShiftPressed()) {
2210 getTopWindow().pageUp(false);
2211 } else {
2212 getTopWindow().pageDown(false);
2213 }
Grace Kloba5942df02009-09-18 11:48:29 -07002214 return true;
2215 case KeyEvent.KEYCODE_BACK:
2216 if (event.getRepeatCount() == 0) {
2217 event.startTracking();
2218 return true;
2219 } else if (mCustomView == null && mActiveTabsPage == null
2220 && event.isLongPress()) {
Michael Kolb68792c82010-08-09 16:39:18 -07002221 bookmarksOrHistoryPicker(true, false);
Grace Kloba5942df02009-09-18 11:48:29 -07002222 return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002223 }
Grace Kloba5942df02009-09-18 11:48:29 -07002224 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002225 }
Grace Kloba5942df02009-09-18 11:48:29 -07002226 return super.onKeyDown(keyCode, event);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002227 }
2228
Grace Kloba5942df02009-09-18 11:48:29 -07002229 @Override
2230 public boolean onKeyUp(int keyCode, KeyEvent event) {
2231 switch(keyCode) {
2232 case KeyEvent.KEYCODE_MENU:
2233 mMenuIsDown = false;
2234 break;
Grace Kloba5942df02009-09-18 11:48:29 -07002235 case KeyEvent.KEYCODE_BACK:
2236 if (event.isTracking() && !event.isCanceled()) {
2237 if (mCustomView != null) {
2238 // if a custom view is showing, hide it
Grace Kloba22ac16e2009-10-07 18:00:23 -07002239 mTabControl.getCurrentWebView().getWebChromeClient()
2240 .onHideCustomView();
Grace Kloba5942df02009-09-18 11:48:29 -07002241 } else if (mActiveTabsPage != null) {
2242 // if tab page is showing, hide it
2243 removeActiveTabPage(true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002244 } else {
Grace Kloba5942df02009-09-18 11:48:29 -07002245 WebView subwindow = mTabControl.getCurrentSubWindow();
2246 if (subwindow != null) {
2247 if (subwindow.canGoBack()) {
2248 subwindow.goBack();
2249 } else {
2250 dismissSubWindow(mTabControl.getCurrentTab());
2251 }
2252 } else {
2253 goBackOnePageOrQuit();
2254 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002255 }
Grace Kloba5942df02009-09-18 11:48:29 -07002256 return true;
2257 }
2258 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002259 }
Grace Kloba5942df02009-09-18 11:48:29 -07002260 return super.onKeyUp(keyCode, event);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002261 }
2262
Leon Scroggins68579392009-09-15 15:31:54 -04002263 /* package */ void stopLoading() {
Ben Murdochb7cc8b42009-09-28 10:59:09 +01002264 mDidStopLoad = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002265 resetTitleAndRevertLockIcon();
2266 WebView w = getTopWindow();
2267 w.stopLoading();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002268 // FIXME: before refactor, it is using mWebViewClient. So I keep the
2269 // same logic here. But for subwindow case, should we call into the main
2270 // WebView's onPageFinished as we never call its onPageStarted and if
2271 // the page finishes itself, we don't call onPageFinished.
2272 mTabControl.getCurrentWebView().getWebViewClient().onPageFinished(w,
2273 w.getUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08002274
2275 cancelStopToast();
2276 mStopToast = Toast
2277 .makeText(this, R.string.stopping, Toast.LENGTH_SHORT);
2278 mStopToast.show();
2279 }
2280
Grace Kloba22ac16e2009-10-07 18:00:23 -07002281 boolean didUserStopLoading() {
2282 return mDidStopLoad;
2283 }
2284
The Android Open Source Project0c908882009-03-03 19:32:16 -08002285 private void cancelStopToast() {
2286 if (mStopToast != null) {
2287 mStopToast.cancel();
2288 mStopToast = null;
2289 }
2290 }
2291
Grace Kloba22ac16e2009-10-07 18:00:23 -07002292 // called by a UI or non-UI thread to post the message
2293 public void postMessage(int what, int arg1, int arg2, Object obj,
2294 long delayMillis) {
2295 mHandler.sendMessageDelayed(mHandler.obtainMessage(what, arg1, arg2,
2296 obj), delayMillis);
2297 }
2298
2299 // called by a UI or non-UI thread to remove the message
2300 void removeMessages(int what, Object object) {
2301 mHandler.removeMessages(what, object);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002302 }
2303
2304 // public message ids
2305 public final static int LOAD_URL = 1001;
2306 public final static int STOP_LOAD = 1002;
2307
2308 // Message Ids
2309 private static final int FOCUS_NODE_HREF = 102;
Grace Kloba92c18a52009-07-31 23:48:32 -07002310 private static final int RELEASE_WAKELOCK = 107;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002311
Grace Kloba22ac16e2009-10-07 18:00:23 -07002312 static final int UPDATE_BOOKMARK_THUMBNAIL = 108;
Ben Murdoch2694e232009-09-29 09:41:11 +01002313
Ben Murdocheecb4e62010-07-06 16:30:38 +01002314 private static final int TOUCH_ICON_DOWNLOADED = 109;
2315
Michael Kolb300b7f02010-08-25 13:47:24 -07002316 private static final int OPEN_BOOKMARKS = 201;
2317
The Android Open Source Project0c908882009-03-03 19:32:16 -08002318 // Private handler for handling javascript and saving passwords
2319 private Handler mHandler = new Handler() {
2320
Michael Kolbe0a36662010-06-29 10:37:12 -07002321 @Override
The Android Open Source Project0c908882009-03-03 19:32:16 -08002322 public void handleMessage(Message msg) {
2323 switch (msg.what) {
Michael Kolb300b7f02010-08-25 13:47:24 -07002324 case OPEN_BOOKMARKS:
2325 bookmarksOrHistoryPicker(false, false);
2326 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002327 case FOCUS_NODE_HREF:
Ben Murdoch2694e232009-09-29 09:41:11 +01002328 {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002329 String url = (String) msg.getData().get("url");
Ben Murdoch90d088c2009-11-17 18:14:04 +00002330 String title = (String) msg.getData().get("title");
The Android Open Source Project0c908882009-03-03 19:32:16 -08002331 if (url == null || url.length() == 0) {
2332 break;
2333 }
2334 HashMap focusNodeMap = (HashMap) msg.obj;
2335 WebView view = (WebView) focusNodeMap.get("webview");
2336 // Only apply the action if the top window did not change.
2337 if (getTopWindow() != view) {
2338 break;
2339 }
2340 switch (msg.arg1) {
2341 case R.id.open_context_menu_id:
2342 case R.id.view_image_context_menu_id:
Leon Scroggins92472e82010-02-17 16:32:28 -05002343 loadUrlFromContext(getTopWindow(), url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002344 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002345 case R.id.bookmark_context_menu_id:
2346 Intent intent = new Intent(BrowserActivity.this,
2347 AddBookmarkPage.class);
2348 intent.putExtra("url", url);
Ben Murdoch90d088c2009-11-17 18:14:04 +00002349 intent.putExtra("title", title);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002350 startActivity(intent);
2351 break;
2352 case R.id.share_link_context_menu_id:
Leon Scroggins3e204452010-05-10 11:06:03 -04002353 sharePage(BrowserActivity.this, title, url, null,
Leon Scroggins96afcb12009-12-10 12:35:56 -05002354 null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002355 break;
2356 case R.id.copy_link_context_menu_id:
2357 copy(url);
2358 break;
2359 case R.id.save_link_context_menu_id:
2360 case R.id.download_context_menu_id:
2361 onDownloadStartNoStream(url, null, null, null, -1);
2362 break;
2363 }
2364 break;
Ben Murdoch2694e232009-09-29 09:41:11 +01002365 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002366
2367 case LOAD_URL:
Leon Scroggins92472e82010-02-17 16:32:28 -05002368 loadUrlFromContext(getTopWindow(), (String) msg.obj);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002369 break;
2370
2371 case STOP_LOAD:
2372 stopLoading();
2373 break;
2374
The Android Open Source Project0c908882009-03-03 19:32:16 -08002375 case RELEASE_WAKELOCK:
2376 if (mWakeLock.isHeld()) {
2377 mWakeLock.release();
Grace Kloba5d0e02e2009-10-05 15:15:36 -07002378 // if we reach here, Browser should be still in the
2379 // background loading after WAKELOCK_TIMEOUT (5-min).
2380 // To avoid burning the battery, stop loading.
2381 mTabControl.stopAllLoading();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002382 }
2383 break;
Ben Murdoch2694e232009-09-29 09:41:11 +01002384
2385 case UPDATE_BOOKMARK_THUMBNAIL:
2386 WebView view = (WebView) msg.obj;
2387 if (view != null) {
2388 updateScreenshot(view);
2389 }
2390 break;
Ben Murdocheecb4e62010-07-06 16:30:38 +01002391
2392 case TOUCH_ICON_DOWNLOADED:
2393 Bundle b = msg.getData();
2394 showSaveToHomescreenDialog(b.getString("url"),
2395 b.getString("title"),
2396 (Bitmap) b.getParcelable("touchIcon"),
2397 (Bitmap) b.getParcelable("favicon"));
2398 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002399 }
2400 }
2401 };
2402
Leon Scroggins96afcb12009-12-10 12:35:56 -05002403 /**
2404 * Share a page, providing the title, url, favicon, and a screenshot. Uses
2405 * an {@link Intent} to launch the Activity chooser.
2406 * @param c Context used to launch a new Activity.
2407 * @param title Title of the page. Stored in the Intent with
Paul Westbrook03e6d392010-02-12 10:33:29 -08002408 * {@link Intent#EXTRA_SUBJECT}
Leon Scroggins96afcb12009-12-10 12:35:56 -05002409 * @param url URL of the page. Stored in the Intent with
2410 * {@link Intent#EXTRA_TEXT}
2411 * @param favicon Bitmap of the favicon for the page. Stored in the Intent
2412 * with {@link Browser#EXTRA_SHARE_FAVICON}
2413 * @param screenshot Bitmap of a screenshot of the page. Stored in the
2414 * Intent with {@link Browser#EXTRA_SHARE_SCREENSHOT}
2415 */
2416 public static final void sharePage(Context c, String title, String url,
2417 Bitmap favicon, Bitmap screenshot) {
2418 Intent send = new Intent(Intent.ACTION_SEND);
2419 send.setType("text/plain");
2420 send.putExtra(Intent.EXTRA_TEXT, url);
Paul Westbrook03e6d392010-02-12 10:33:29 -08002421 send.putExtra(Intent.EXTRA_SUBJECT, title);
Leon Scroggins96afcb12009-12-10 12:35:56 -05002422 send.putExtra(Browser.EXTRA_SHARE_FAVICON, favicon);
2423 send.putExtra(Browser.EXTRA_SHARE_SCREENSHOT, screenshot);
2424 try {
2425 c.startActivity(Intent.createChooser(send, c.getString(
2426 R.string.choosertitle_sharevia)));
2427 } catch(android.content.ActivityNotFoundException ex) {
2428 // if no app handles it, do nothing
2429 }
2430 }
2431
Leon Scroggins89c6d362009-07-15 16:54:37 -04002432 private void updateScreenshot(WebView view) {
2433 // If this is a bookmarked site, add a screenshot to the database.
2434 // FIXME: When should we update? Every time?
2435 // FIXME: Would like to make sure there is actually something to
2436 // draw, but the API for that (WebViewCore.pictureReady()) is not
2437 // currently accessible here.
Ben Murdochaac7aa62009-09-17 16:57:40 +01002438
Ben Murdoch87cc65d2010-06-29 20:34:10 +01002439 final Bitmap bm = createScreenshot(view, getDesiredThumbnailWidth(this),
2440 getDesiredThumbnailHeight(this));
Patrick Scottcb192b52010-04-14 14:38:55 -04002441 if (bm == null) {
2442 return;
Leon Scroggins89c6d362009-07-15 16:54:37 -04002443 }
Patrick Scottcb192b52010-04-14 14:38:55 -04002444
2445 final ContentResolver cr = getContentResolver();
2446 final String url = view.getUrl();
2447 final String originalUrl = view.getOriginalUrl();
2448
2449 new AsyncTask<Void, Void, Void>() {
2450 @Override
2451 protected Void doInBackground(Void... unused) {
2452 Cursor c = null;
2453 try {
Jeff Hamilton84029622010-08-05 14:29:28 -05002454 c = Bookmarks.queryBookmarksForUrl(
Jeff Hamilton8ce956c2010-08-17 11:13:53 -05002455 cr, originalUrl, url);
Patrick Scottcb192b52010-04-14 14:38:55 -04002456 if (c != null) {
2457 if (c.moveToFirst()) {
2458 ContentValues values = new ContentValues();
2459 final ByteArrayOutputStream os
2460 = new ByteArrayOutputStream();
2461 bm.compress(Bitmap.CompressFormat.PNG, 100, os);
Jeff Hamilton8ce956c2010-08-17 11:13:53 -05002462 values.put(BrowserContract.Bookmarks.THUMBNAIL,
Patrick Scottcb192b52010-04-14 14:38:55 -04002463 os.toByteArray());
2464 do {
2465 cr.update(ContentUris.withAppendedId(
Jeff Hamilton8ce956c2010-08-17 11:13:53 -05002466 BrowserContract.Bookmarks.CONTENT_URI, c.getLong(0)),
Patrick Scottcb192b52010-04-14 14:38:55 -04002467 values, null, null);
2468 } while (c.moveToNext());
2469 }
2470 }
2471 } catch (IllegalStateException e) {
2472 // Ignore
2473 } finally {
2474 if (c != null) c.close();
2475 }
2476 return null;
2477 }
2478 }.execute();
Leon Scroggins89c6d362009-07-15 16:54:37 -04002479 }
2480
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002481 /**
Leon Scrogginsf8551612009-09-24 16:06:02 -04002482 * Return the desired width for thumbnail screenshots, which are stored in
2483 * the database, and used on the bookmarks screen.
2484 * @param context Context for finding out the density of the screen.
Jeff Hamiltonf3026372010-08-19 00:12:27 -05002485 * @return desired width for thumbnail screenshot.
Leon Scrogginsf8551612009-09-24 16:06:02 -04002486 */
2487 /* package */ static int getDesiredThumbnailWidth(Context context) {
Jeff Hamiltonf3026372010-08-19 00:12:27 -05002488 return context.getResources().getDimensionPixelOffset(R.dimen.bookmarkThumbnailWidth);
Leon Scrogginsf8551612009-09-24 16:06:02 -04002489 }
2490
2491 /**
2492 * Return the desired height for thumbnail screenshots, which are stored in
2493 * the database, and used on the bookmarks screen.
2494 * @param context Context for finding out the density of the screen.
Jeff Hamiltonf3026372010-08-19 00:12:27 -05002495 * @return desired height for thumbnail screenshot.
Leon Scrogginsf8551612009-09-24 16:06:02 -04002496 */
2497 /* package */ static int getDesiredThumbnailHeight(Context context) {
Jeff Hamiltonf3026372010-08-19 00:12:27 -05002498 return context.getResources().getDimensionPixelOffset(R.dimen.bookmarkThumbnailHeight);
Leon Scrogginsf8551612009-09-24 16:06:02 -04002499 }
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002500
Ben Murdoch87cc65d2010-06-29 20:34:10 +01002501 private Bitmap createScreenshot(WebView view, int width, int height) {
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002502 Picture thumbnail = view.capturePicture();
Leon Scroggins45800572009-09-29 16:38:47 -04002503 if (thumbnail == null) {
2504 return null;
2505 }
Ben Murdoch87cc65d2010-06-29 20:34:10 +01002506 Bitmap bm = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002507 Canvas canvas = new Canvas(bm);
2508 // May need to tweak these values to determine what is the
2509 // best scale factor
Ben Murdoch2694e232009-09-29 09:41:11 +01002510 int thumbnailWidth = thumbnail.getWidth();
Ben Murdochae59c3f2009-10-20 18:30:28 +01002511 int thumbnailHeight = thumbnail.getHeight();
2512 float scaleFactorX = 1.0f;
2513 float scaleFactorY = 1.0f;
Ben Murdoch2694e232009-09-29 09:41:11 +01002514 if (thumbnailWidth > 0) {
Ben Murdoch87cc65d2010-06-29 20:34:10 +01002515 scaleFactorX = (float) width / (float)thumbnailWidth;
Ben Murdochae59c3f2009-10-20 18:30:28 +01002516 } else {
2517 return null;
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002518 }
Ben Murdochae59c3f2009-10-20 18:30:28 +01002519
2520 if (view.getWidth() > view.getHeight() &&
2521 thumbnailHeight < view.getHeight() && thumbnailHeight > 0) {
2522 // If the device is in landscape and the page is shorter
2523 // than the height of the view, stretch the thumbnail to fill the
2524 // space.
Ben Murdoch87cc65d2010-06-29 20:34:10 +01002525 scaleFactorY = (float) height / (float)thumbnailHeight;
Ben Murdochae59c3f2009-10-20 18:30:28 +01002526 } else {
2527 // In the portrait case, this looks nice.
2528 scaleFactorY = scaleFactorX;
2529 }
2530
2531 canvas.scale(scaleFactorX, scaleFactorY);
2532
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002533 thumbnail.draw(canvas);
2534 return bm;
2535 }
2536
The Android Open Source Project0c908882009-03-03 19:32:16 -08002537 // -------------------------------------------------------------------------
Grace Kloba22ac16e2009-10-07 18:00:23 -07002538 // Helper function for WebViewClient.
The Android Open Source Project0c908882009-03-03 19:32:16 -08002539 //-------------------------------------------------------------------------
2540
2541 // Use in overrideUrlLoading
2542 /* package */ final static String SCHEME_WTAI = "wtai://wp/";
2543 /* package */ final static String SCHEME_WTAI_MC = "wtai://wp/mc;";
2544 /* package */ final static String SCHEME_WTAI_SD = "wtai://wp/sd;";
2545 /* package */ final static String SCHEME_WTAI_AP = "wtai://wp/ap;";
2546
Leon Scroggins92472e82010-02-17 16:32:28 -05002547 // Keep this initial progress in sync with initialProgressValue (* 100)
2548 // in ProgressTracker.cpp
2549 private final static int INITIAL_PROGRESS = 10;
2550
Grace Kloba22ac16e2009-10-07 18:00:23 -07002551 void onPageStarted(WebView view, String url, Bitmap favicon) {
2552 // when BrowserActivity just starts, onPageStarted may be called before
2553 // onResume as it is triggered from onCreate. Call resumeWebViewTimers
2554 // to start the timer. As we won't switch tabs while an activity is in
2555 // pause state, we can ensure calling resume and pause in pair.
2556 if (mActivityInPause) resumeWebViewTimers();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002557
Grace Kloba22ac16e2009-10-07 18:00:23 -07002558 resetLockIcon(url);
2559 setUrlTitle(url, null);
2560 setFavicon(favicon);
Leon Scroggins8cf8f682009-11-04 11:13:50 -08002561 // Show some progress so that the user knows the page is beginning to
2562 // load
Leon Scroggins92472e82010-02-17 16:32:28 -05002563 onProgressChanged(view, INITIAL_PROGRESS);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002564 mDidStopLoad = false;
Grace Kloba22ac16e2009-10-07 18:00:23 -07002565 if (!mIsNetworkUp) createAndShowNetworkDialog();
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04002566 endActionMode();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002567 if (mSettings.isTracing()) {
2568 String host;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002569 try {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002570 WebAddress uri = new WebAddress(url);
2571 host = uri.mHost;
2572 } catch (android.net.ParseException ex) {
2573 host = "browser";
The Android Open Source Project0c908882009-03-03 19:32:16 -08002574 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002575 host = host.replace('.', '_');
2576 host += ".trace";
2577 mInTrace = true;
2578 Debug.startMethodTracing(host, 20 * 1024 * 1024);
2579 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002580
Grace Kloba22ac16e2009-10-07 18:00:23 -07002581 // Performance probe
2582 if (false) {
2583 mStart = SystemClock.uptimeMillis();
2584 mProcessStart = Process.getElapsedCpuTime();
2585 long[] sysCpu = new long[7];
2586 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2587 sysCpu, null)) {
2588 mUserStart = sysCpu[0] + sysCpu[1];
2589 mSystemStart = sysCpu[2];
2590 mIdleStart = sysCpu[3];
2591 mIrqStart = sysCpu[4] + sysCpu[5] + sysCpu[6];
2592 }
2593 mUiStart = SystemClock.currentThreadTimeMillis();
2594 }
2595 }
2596
2597 void onPageFinished(WebView view, String url) {
2598 // Reset the title and icon in case we stopped a provisional load.
2599 resetTitleAndIcon(view);
2600 // Update the lock icon image only once we are done loading
2601 updateLockIconToLatest();
2602 // pause the WebView timer and release the wake lock if it is finished
2603 // while BrowserActivity is in pause state.
2604 if (mActivityInPause && pauseWebViewTimers()) {
2605 if (mWakeLock.isHeld()) {
2606 mHandler.removeMessages(RELEASE_WAKELOCK);
2607 mWakeLock.release();
2608 }
2609 }
2610
2611 // Performance probe
2612 if (false) {
2613 long[] sysCpu = new long[7];
2614 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2615 sysCpu, null)) {
2616 String uiInfo = "UI thread used "
2617 + (SystemClock.currentThreadTimeMillis() - mUiStart)
2618 + " ms";
2619 if (LOGD_ENABLED) {
2620 Log.d(LOGTAG, uiInfo);
2621 }
2622 //The string that gets written to the log
2623 String performanceString = "It took total "
2624 + (SystemClock.uptimeMillis() - mStart)
2625 + " ms clock time to load the page."
2626 + "\nbrowser process used "
2627 + (Process.getElapsedCpuTime() - mProcessStart)
2628 + " ms, user processes used "
2629 + (sysCpu[0] + sysCpu[1] - mUserStart) * 10
2630 + " ms, kernel used "
2631 + (sysCpu[2] - mSystemStart) * 10
2632 + " ms, idle took " + (sysCpu[3] - mIdleStart) * 10
2633 + " ms and irq took "
2634 + (sysCpu[4] + sysCpu[5] + sysCpu[6] - mIrqStart)
2635 * 10 + " ms, " + uiInfo;
2636 if (LOGD_ENABLED) {
2637 Log.d(LOGTAG, performanceString + "\nWebpage: " + url);
2638 }
2639 if (url != null) {
2640 // strip the url to maintain consistency
2641 String newUrl = new String(url);
2642 if (newUrl.startsWith("http://www.")) {
2643 newUrl = newUrl.substring(11);
2644 } else if (newUrl.startsWith("http://")) {
2645 newUrl = newUrl.substring(7);
2646 } else if (newUrl.startsWith("https://www.")) {
2647 newUrl = newUrl.substring(12);
2648 } else if (newUrl.startsWith("https://")) {
2649 newUrl = newUrl.substring(8);
2650 }
2651 if (LOGD_ENABLED) {
2652 Log.d(LOGTAG, newUrl + " loaded");
2653 }
Grace Kloba5b078b52009-06-24 20:23:41 -07002654 }
2655 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002656 }
Grace Kloba5b078b52009-06-24 20:23:41 -07002657
Grace Kloba22ac16e2009-10-07 18:00:23 -07002658 if (mInTrace) {
2659 mInTrace = false;
2660 Debug.stopMethodTracing();
2661 }
2662 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002663
Grace Klobae7fe26b2010-06-28 16:23:33 -07002664 private void closeEmptyChildTab() {
2665 Tab current = mTabControl.getCurrentTab();
2666 if (current != null
2667 && current.getWebView().copyBackForwardList().getSize() == 0) {
2668 Tab parent = current.getParentTab();
2669 if (parent != null) {
2670 switchToTab(mTabControl.getTabIndex(parent));
2671 closeTab(current);
2672 }
2673 }
2674 }
2675
Grace Kloba22ac16e2009-10-07 18:00:23 -07002676 boolean shouldOverrideUrlLoading(WebView view, String url) {
Jeff Hamilton47654f42010-09-07 09:57:51 -05002677 if (view.isPrivateBrowsingEnabled()) {
2678 // Don't allow urls to leave the browser app when in private browsing mode
2679 loadUrl(view, url);
2680 return true;
2681 }
2682
Grace Kloba22ac16e2009-10-07 18:00:23 -07002683 if (url.startsWith(SCHEME_WTAI)) {
2684 // wtai://wp/mc;number
2685 // number=string(phone-number)
2686 if (url.startsWith(SCHEME_WTAI_MC)) {
2687 Intent intent = new Intent(Intent.ACTION_VIEW,
2688 Uri.parse(WebView.SCHEME_TEL +
2689 url.substring(SCHEME_WTAI_MC.length())));
2690 startActivity(intent);
Grace Klobae7fe26b2010-06-28 16:23:33 -07002691 // before leaving BrowserActivity, close the empty child tab.
2692 // If a new tab is created through JavaScript open to load this
2693 // url, we would like to close it as we will load this url in a
2694 // different Activity.
2695 closeEmptyChildTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002696 return true;
2697 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002698 // wtai://wp/sd;dtmf
2699 // dtmf=string(dialstring)
2700 if (url.startsWith(SCHEME_WTAI_SD)) {
2701 // TODO: only send when there is active voice connection
2702 return false;
2703 }
2704 // wtai://wp/ap;number;name
2705 // number=string(phone-number)
2706 // name=string
2707 if (url.startsWith(SCHEME_WTAI_AP)) {
2708 // TODO
2709 return false;
2710 }
2711 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002712
Grace Kloba22ac16e2009-10-07 18:00:23 -07002713 // The "about:" schemes are internal to the browser; don't want these to
2714 // be dispatched to other apps.
2715 if (url.startsWith("about:")) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002716 return false;
2717 }
2718
Jeff Davidson43610292010-07-16 16:03:58 -07002719 // If this is a Google search, attempt to add an RLZ string (if one isn't already present).
2720 if (rlzProviderPresent()) {
2721 Uri siteUri = Uri.parse(url);
2722 if (needsRlzString(siteUri)) {
2723 String rlz = null;
2724 Cursor cur = null;
2725 try {
2726 cur = getContentResolver().query(getRlzUri(), null, null, null, null);
2727 if (cur != null && cur.moveToFirst() && !cur.isNull(0)) {
2728 url = siteUri.buildUpon()
2729 .appendQueryParameter("rlz", cur.getString(0))
2730 .build().toString();
2731 }
2732 } finally {
2733 if (cur != null) {
2734 cur.close();
2735 }
2736 }
2737 loadUrl(view, url);
2738 return true;
2739 }
2740 }
2741
Grace Kloba22ac16e2009-10-07 18:00:23 -07002742 Intent intent;
2743 // perform generic parsing of the URI to turn it into an Intent.
2744 try {
2745 intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME);
2746 } catch (URISyntaxException ex) {
2747 Log.w("Browser", "Bad URI " + url + ": " + ex.getMessage());
2748 return false;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002749 }
2750
Grace Kloba22ac16e2009-10-07 18:00:23 -07002751 // check whether the intent can be resolved. If not, we will see
2752 // whether we can download it from the Market.
2753 if (getPackageManager().resolveActivity(intent, 0) == null) {
2754 String packagename = intent.getPackage();
2755 if (packagename != null) {
2756 intent = new Intent(Intent.ACTION_VIEW, Uri
2757 .parse("market://search?q=pname:" + packagename));
2758 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2759 startActivity(intent);
Grace Klobae7fe26b2010-06-28 16:23:33 -07002760 // before leaving BrowserActivity, close the empty child tab.
2761 // If a new tab is created through JavaScript open to load this
2762 // url, we would like to close it as we will load this url in a
2763 // different Activity.
2764 closeEmptyChildTab();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002765 return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002766 } else {
2767 return false;
2768 }
2769 }
2770
Grace Kloba22ac16e2009-10-07 18:00:23 -07002771 // sanitize the Intent, ensuring web pages can not bypass browser
2772 // security (only access to BROWSABLE activities).
2773 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2774 intent.setComponent(null);
2775 try {
2776 if (startActivityIfNeeded(intent, -1)) {
Grace Klobae7fe26b2010-06-28 16:23:33 -07002777 // before leaving BrowserActivity, close the empty child tab.
2778 // If a new tab is created through JavaScript open to load this
2779 // url, we would like to close it as we will load this url in a
2780 // different Activity.
2781 closeEmptyChildTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002782 return true;
2783 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002784 } catch (ActivityNotFoundException ex) {
2785 // ignore the error. If no application can handle the URL,
2786 // eg about:blank, assume the browser can handle it.
2787 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002788
Grace Kloba22ac16e2009-10-07 18:00:23 -07002789 if (mMenuIsDown) {
Michael Kolb68792c82010-08-09 16:39:18 -07002790 openTab(url, false);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002791 closeOptionsMenu();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002792 return true;
2793 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002794 return false;
2795 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002796
Jeff Davidson43610292010-07-16 16:03:58 -07002797 // Determine whether the RLZ provider is present on the system.
2798 private boolean rlzProviderPresent() {
2799 if (mIsProviderPresent == null) {
2800 PackageManager pm = getPackageManager();
2801 mIsProviderPresent = pm.resolveContentProvider(BrowserSettings.RLZ_PROVIDER, 0) != null;
2802 }
2803 return mIsProviderPresent;
2804 }
2805
2806 // Retrieve the RLZ access point string and cache the URI used to retrieve RLZ values.
2807 private Uri getRlzUri() {
2808 if (mRlzUri == null) {
2809 String ap = getResources().getString(R.string.rlz_access_point);
2810 mRlzUri = Uri.withAppendedPath(BrowserSettings.RLZ_PROVIDER_URI, ap);
2811 }
2812 return mRlzUri;
2813 }
2814
2815 // Determine if this URI appears to be for a Google search and does not have an RLZ parameter.
2816 // Taken largely from Chrome source, src/chrome/browser/google_url_tracker.cc
2817 private static boolean needsRlzString(Uri uri) {
Bill Napierc50e71a2010-08-27 14:03:03 -07002818 String scheme = uri.getScheme();
2819 if (("http".equals(scheme) || "https".equals(scheme)) &&
2820 (uri.getQueryParameter("q") != null) && (uri.getQueryParameter("rlz") == null)) {
Jeff Davidson43610292010-07-16 16:03:58 -07002821 String host = uri.getHost();
2822 if (host == null) {
2823 return false;
2824 }
2825 String[] hostComponents = host.split("\\.");
2826
2827 if (hostComponents.length < 2) {
2828 return false;
2829 }
2830 int googleComponent = hostComponents.length - 2;
2831 String component = hostComponents[googleComponent];
2832 if (!"google".equals(component)) {
2833 if (hostComponents.length < 3 ||
2834 (!"co".equals(component) && !"com".equals(component))) {
2835 return false;
2836 }
2837 googleComponent = hostComponents.length - 3;
2838 if (!"google".equals(hostComponents[googleComponent])) {
2839 return false;
2840 }
2841 }
2842
2843 // Google corp network handling.
2844 if (googleComponent > 0 && "corp".equals(hostComponents[googleComponent - 1])) {
2845 return false;
2846 }
2847
2848 return true;
2849 }
2850 return false;
2851 }
2852
Grace Kloba22ac16e2009-10-07 18:00:23 -07002853 // -------------------------------------------------------------------------
2854 // Helper function for WebChromeClient
2855 // -------------------------------------------------------------------------
The Android Open Source Project0c908882009-03-03 19:32:16 -08002856
Grace Kloba22ac16e2009-10-07 18:00:23 -07002857 void onProgressChanged(WebView view, int newProgress) {
Michael Kolba2b2ba82010-08-04 17:54:03 -07002858
2859 // On the phone, the fake title bar will always cover up the
2860 // regular title bar (or the regular one is offscreen), so only the
2861 // fake title bar needs to change its progress
2862 mFakeTitleBar.setProgress(newProgress);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002863
Grace Kloba22ac16e2009-10-07 18:00:23 -07002864 if (newProgress == 100) {
2865 // onProgressChanged() may continue to be called after the main
2866 // frame has finished loading, as any remaining sub frames continue
2867 // to load. We'll only get called once though with newProgress as
2868 // 100 when everything is loaded. (onPageFinished is called once
2869 // when the main frame completes loading regardless of the state of
2870 // any sub frames so calls to onProgressChanges may continue after
2871 // onPageFinished has executed)
2872 if (mInLoad) {
2873 mInLoad = false;
Leon Scrogginsa27ff192009-09-14 12:58:04 -04002874 updateInLoadMenuItems();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002875 // If the options menu is open, leave the title bar
2876 if (!mOptionsMenuOpen || !mIconView) {
2877 hideFakeTitleBar();
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07002878 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002879 }
Leon Scrogginsaa37e7f2010-03-05 11:51:20 -05002880 } else {
2881 if (!mInLoad) {
2882 // onPageFinished may have already been called but a subframe is
2883 // still loading and updating the progress. Reset mInLoad and
2884 // update the menu items.
2885 mInLoad = true;
2886 updateInLoadMenuItems();
2887 }
2888 // When the page first begins to load, the Activity may still be
2889 // paused, in which case showFakeTitleBar will do nothing. Call
2890 // again as the page continues to load so that it will be shown.
2891 // (Calling it will the fake title bar is already showing will also
2892 // do nothing.
Grace Kloba22ac16e2009-10-07 18:00:23 -07002893 if (!mOptionsMenuOpen || mIconView) {
2894 // This page has begun to load, so show the title bar
2895 showFakeTitleBar();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002896 }
2897 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002898 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002899
Grace Kloba22ac16e2009-10-07 18:00:23 -07002900 void onShowCustomView(View view, WebChromeClient.CustomViewCallback callback) {
Derek Sollenberger8ff57db2009-12-08 15:39:55 -05002901 // if a view already exists then immediately terminate the new one
2902 if (mCustomView != null) {
2903 callback.onCustomViewHidden();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002904 return;
Derek Sollenberger8ff57db2009-12-08 15:39:55 -05002905 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002906
2907 // Add the custom view to its container.
2908 mCustomViewContainer.addView(view, COVER_SCREEN_GRAVITY_CENTER);
2909 mCustomView = view;
2910 mCustomViewCallback = callback;
2911 // Save the menu state and set it to empty while the custom
2912 // view is showing.
2913 mOldMenuState = mMenuState;
2914 mMenuState = EMPTY_MENU;
2915 // Hide the content view.
2916 mContentView.setVisibility(View.GONE);
2917 // Finally show the custom view container.
Andrei Popescu163ab742009-10-20 17:58:23 +01002918 setStatusBarVisibility(false);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002919 mCustomViewContainer.setVisibility(View.VISIBLE);
2920 mCustomViewContainer.bringToFront();
2921 }
2922
2923 void onHideCustomView() {
2924 if (mCustomView == null)
2925 return;
2926
2927 // Hide the custom view.
2928 mCustomView.setVisibility(View.GONE);
2929 // Remove the custom view from its container.
2930 mCustomViewContainer.removeView(mCustomView);
2931 mCustomView = null;
2932 // Reset the old menu state.
2933 mMenuState = mOldMenuState;
2934 mOldMenuState = EMPTY_MENU;
2935 mCustomViewContainer.setVisibility(View.GONE);
2936 mCustomViewCallback.onCustomViewHidden();
2937 // Show the content view.
Andrei Popescu163ab742009-10-20 17:58:23 +01002938 setStatusBarVisibility(true);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002939 mContentView.setVisibility(View.VISIBLE);
2940 }
2941
2942 Bitmap getDefaultVideoPoster() {
2943 if (mDefaultVideoPoster == null) {
2944 mDefaultVideoPoster = BitmapFactory.decodeResource(
2945 getResources(), R.drawable.default_video_poster);
Patrick Scott3918d442009-08-04 13:22:29 -04002946 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002947 return mDefaultVideoPoster;
2948 }
Patrick Scott3918d442009-08-04 13:22:29 -04002949
Grace Kloba22ac16e2009-10-07 18:00:23 -07002950 View getVideoLoadingProgressView() {
2951 if (mVideoProgressView == null) {
2952 LayoutInflater inflater = LayoutInflater.from(BrowserActivity.this);
2953 mVideoProgressView = inflater.inflate(
2954 R.layout.video_loading_progress, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002955 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002956 return mVideoProgressView;
2957 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002958
Leon Scroggins8d5fa432009-10-02 15:55:59 -04002959 /*
2960 * The Object used to inform the WebView of the file to upload.
2961 */
2962 private ValueCallback<Uri> mUploadMessage;
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002963 private String mCameraFilePath;
Leon Scroggins8d5fa432009-10-02 15:55:59 -04002964
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002965 void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
2966
2967 final String imageMimeType = "image/*";
Ben Murdoch6af492a2010-06-15 12:38:17 +01002968 final String videoMimeType = "video/*";
Ben Murdoch039bd472010-07-21 21:26:57 +01002969 final String audioMimeType = "audio/*";
Ben Murdochb50d7402010-07-16 12:42:22 +01002970 final String mediaSourceKey = "capture";
Ben Murdoch6af492a2010-06-15 12:38:17 +01002971 final String mediaSourceValueCamera = "camera";
Ben Murdochb50d7402010-07-16 12:42:22 +01002972 final String mediaSourceValueFileSystem = "filesystem";
Ben Murdoch6af492a2010-06-15 12:38:17 +01002973 final String mediaSourceValueCamcorder = "camcorder";
Ben Murdoch039bd472010-07-21 21:26:57 +01002974 final String mediaSourceValueMicrophone = "microphone";
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002975
Ben Murdoch039bd472010-07-21 21:26:57 +01002976 // media source can be 'filesystem' or 'camera' or 'camcorder' or 'microphone'.
Ben Murdoch6af492a2010-06-15 12:38:17 +01002977 String mediaSource = "";
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002978
Ben Murdoch6af492a2010-06-15 12:38:17 +01002979 // We add the camera intent if there was no accept type (or '*/*' or 'image/*').
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002980 boolean addCameraIntent = true;
Ben Murdoch6af492a2010-06-15 12:38:17 +01002981 // We add the camcorder intent if there was no accept type (or '*/*' or 'video/*').
2982 boolean addCamcorderIntent = true;
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002983
Ben Murdoch6af492a2010-06-15 12:38:17 +01002984 if (mUploadMessage != null) {
2985 // Already a file picker operation in progress.
2986 return;
2987 }
2988
Grace Kloba22ac16e2009-10-07 18:00:23 -07002989 mUploadMessage = uploadMsg;
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002990
2991 // Parse the accept type.
2992 String params[] = acceptType.split(";");
2993 String mimeType = params[0];
2994
2995 for (String p : params) {
2996 String[] keyValue = p.split("=");
2997 if (keyValue.length == 2) {
2998 // Process key=value parameters.
Ben Murdoch6af492a2010-06-15 12:38:17 +01002999 if (mediaSourceKey.equals(keyValue[0])) {
3000 mediaSource = keyValue[1];
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003001 }
3002 }
3003 }
3004
3005 // This intent will display the standard OPENABLE file picker.
Grace Kloba22ac16e2009-10-07 18:00:23 -07003006 Intent i = new Intent(Intent.ACTION_GET_CONTENT);
3007 i.addCategory(Intent.CATEGORY_OPENABLE);
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003008
3009 // Create an intent to add to the standard file picker that will
3010 // capture an image from the camera. We'll combine this intent with
3011 // the standard OPENABLE picker unless the web developer specifically
3012 // requested the camera or gallery be opened by passing a parameter
3013 // in the accept type.
3014 Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
3015 File externalDataDir = Environment.getExternalStoragePublicDirectory(
3016 Environment.DIRECTORY_DCIM);
3017 File cameraDataDir = new File(externalDataDir.getAbsolutePath() +
3018 File.separator + "browser-photos");
3019 cameraDataDir.mkdirs();
3020 mCameraFilePath = cameraDataDir.getAbsolutePath() + File.separator +
3021 System.currentTimeMillis() + ".jpg";
3022 cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(mCameraFilePath)));
3023
Ben Murdoch6af492a2010-06-15 12:38:17 +01003024 Intent camcorderIntent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
3025
Ben Murdoch039bd472010-07-21 21:26:57 +01003026 Intent soundRecIntent = new Intent(MediaStore.Audio.Media.RECORD_SOUND_ACTION);
3027
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003028 if (mimeType.equals(imageMimeType)) {
3029 i.setType(imageMimeType);
Ben Murdoch6af492a2010-06-15 12:38:17 +01003030 addCamcorderIntent = false;
3031 if (mediaSource.equals(mediaSourceValueCamera)) {
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003032 // Specified 'image/*' and requested the camera, so go ahead and launch the camera
3033 // directly.
3034 BrowserActivity.this.startActivityForResult(cameraIntent, FILE_SELECTED);
3035 return;
Ben Murdochb50d7402010-07-16 12:42:22 +01003036 } else if (mediaSource.equals(mediaSourceValueFileSystem)) {
3037 // Specified filesytem as the source, so don't want to consider the camera.
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003038 addCameraIntent = false;
3039 }
Ben Murdoch6af492a2010-06-15 12:38:17 +01003040 } else if (mimeType.equals(videoMimeType)) {
3041 i.setType(videoMimeType);
3042 addCameraIntent = false;
3043 // The camcorder saves it's own file and returns it to us in the intent, so
3044 // we don't need to generate one here.
3045 mCameraFilePath = null;
3046
3047 if (mediaSource.equals(mediaSourceValueCamcorder)) {
Ben Murdoch039bd472010-07-21 21:26:57 +01003048 // Specified 'video/*' and requested the camcorder, so go ahead and launch the
3049 // camcorder directly.
Ben Murdoch6af492a2010-06-15 12:38:17 +01003050 BrowserActivity.this.startActivityForResult(camcorderIntent, FILE_SELECTED);
3051 return;
Ben Murdochb50d7402010-07-16 12:42:22 +01003052 } else if (mediaSource.equals(mediaSourceValueFileSystem)) {
3053 // Specified filesystem as the source, so don't want to consider the camcorder.
Ben Murdoch6af492a2010-06-15 12:38:17 +01003054 addCamcorderIntent = false;
3055 }
Ben Murdoch039bd472010-07-21 21:26:57 +01003056 } else if (mimeType.equals(audioMimeType)) {
3057 i.setType(audioMimeType);
3058 addCameraIntent = false;
3059 addCamcorderIntent = false;
3060 if (mediaSource.equals(mediaSourceValueMicrophone)) {
3061 // Specified 'audio/*' and requested microphone, so go ahead and launch the sound
3062 // recorder.
3063 BrowserActivity.this.startActivityForResult(soundRecIntent, FILE_SELECTED);
3064 return;
3065 }
3066 // On a default system, there is no single option to open an audio "gallery". Both the
3067 // sound recorder and music browser respond to the OPENABLE/audio/* intent unlike the
3068 // image/* and video/* OPENABLE intents where the image / video gallery are the only
3069 // respondants (and so the user is not prompted by default).
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003070 } else {
3071 i.setType("*/*");
3072 }
3073
Ben Murdoch6af492a2010-06-15 12:38:17 +01003074 // Combine the chooser and the extra choices (like camera or camcorder)
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003075 Intent chooser = new Intent(Intent.ACTION_CHOOSER);
3076 chooser.putExtra(Intent.EXTRA_INTENT, i);
3077
Ben Murdoch6af492a2010-06-15 12:38:17 +01003078 Vector<Intent> extraInitialIntents = new Vector<Intent>(0);
3079
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003080 if (addCameraIntent) {
Ben Murdoch6af492a2010-06-15 12:38:17 +01003081 extraInitialIntents.add(cameraIntent);
3082 }
3083
3084 if (addCamcorderIntent) {
3085 extraInitialIntents.add(camcorderIntent);
3086 }
3087
3088 if (extraInitialIntents.size() > 0) {
3089 Intent[] extraIntents = new Intent[extraInitialIntents.size()];
3090 chooser.putExtra(Intent.EXTRA_INITIAL_INTENTS, extraInitialIntents.toArray(extraIntents));
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003091 }
3092
3093 chooser.putExtra(Intent.EXTRA_TITLE, getString(R.string.choose_upload));
3094 BrowserActivity.this.startActivityForResult(chooser, FILE_SELECTED);
Grace Kloba22ac16e2009-10-07 18:00:23 -07003095 }
3096
3097 // -------------------------------------------------------------------------
3098 // Implement functions for DownloadListener
3099 // -------------------------------------------------------------------------
3100
The Android Open Source Project0c908882009-03-03 19:32:16 -08003101 /**
3102 * Notify the host application a download should be done, or that
3103 * the data should be streamed if a streaming viewer is available.
3104 * @param url The full url to the content that should be downloaded
3105 * @param contentDisposition Content-disposition http header, if
3106 * present.
3107 * @param mimetype The mimetype of the content reported by the server
3108 * @param contentLength The file size reported by the server
3109 */
3110 public void onDownloadStart(String url, String userAgent,
3111 String contentDisposition, String mimetype, long contentLength) {
3112 // if we're dealing wih A/V content that's not explicitly marked
3113 // for download, check if it's streamable.
3114 if (contentDisposition == null
Patrick Scotte1fb9662009-08-31 14:31:52 -04003115 || !contentDisposition.regionMatches(
3116 true, 0, "attachment", 0, 10)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003117 // query the package manager to see if there's a registered handler
3118 // that matches.
3119 Intent intent = new Intent(Intent.ACTION_VIEW);
3120 intent.setDataAndType(Uri.parse(url), mimetype);
Patrick Scotte1fb9662009-08-31 14:31:52 -04003121 ResolveInfo info = getPackageManager().resolveActivity(intent,
3122 PackageManager.MATCH_DEFAULT_ONLY);
3123 if (info != null) {
3124 ComponentName myName = getComponentName();
3125 // If we resolved to ourselves, we don't want to attempt to
3126 // load the url only to try and download it again.
3127 if (!myName.getPackageName().equals(
3128 info.activityInfo.packageName)
3129 || !myName.getClassName().equals(
3130 info.activityInfo.name)) {
3131 // someone (other than us) knows how to handle this mime
3132 // type with this scheme, don't download.
3133 try {
3134 startActivity(intent);
3135 return;
3136 } catch (ActivityNotFoundException ex) {
3137 if (LOGD_ENABLED) {
3138 Log.d(LOGTAG, "activity not found for " + mimetype
3139 + " over " + Uri.parse(url).getScheme(),
3140 ex);
3141 }
3142 // Best behavior is to fall back to a download in this
3143 // case
The Android Open Source Project0c908882009-03-03 19:32:16 -08003144 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003145 }
3146 }
3147 }
3148 onDownloadStartNoStream(url, userAgent, contentDisposition, mimetype, contentLength);
3149 }
3150
Kristian Monsenfa52d172010-03-25 18:29:21 +00003151 // This is to work around the fact that java.net.URI throws Exceptions
3152 // instead of just encoding URL's properly
3153 // Helper method for onDownloadStartNoStream
3154 private static String encodePath(String path) {
3155 char[] chars = path.toCharArray();
3156
3157 boolean needed = false;
3158 for (char c : chars) {
3159 if (c == '[' || c == ']') {
3160 needed = true;
3161 break;
3162 }
3163 }
3164 if (needed == false) {
3165 return path;
3166 }
3167
3168 StringBuilder sb = new StringBuilder("");
3169 for (char c : chars) {
3170 if (c == '[' || c == ']') {
3171 sb.append('%');
3172 sb.append(Integer.toHexString(c));
3173 } else {
3174 sb.append(c);
3175 }
3176 }
3177
3178 return sb.toString();
3179 }
3180
The Android Open Source Project0c908882009-03-03 19:32:16 -08003181 /**
3182 * Notify the host application a download should be done, even if there
3183 * is a streaming viewer available for thise type.
3184 * @param url The full url to the content that should be downloaded
3185 * @param contentDisposition Content-disposition http header, if
3186 * present.
3187 * @param mimetype The mimetype of the content reported by the server
3188 * @param contentLength The file size reported by the server
3189 */
3190 /*package */ void onDownloadStartNoStream(String url, String userAgent,
3191 String contentDisposition, String mimetype, long contentLength) {
3192
3193 String filename = URLUtil.guessFileName(url,
3194 contentDisposition, mimetype);
3195
3196 // Check to see if we have an SDCard
3197 String status = Environment.getExternalStorageState();
3198 if (!status.equals(Environment.MEDIA_MOUNTED)) {
3199 int title;
3200 String msg;
3201
3202 // Check to see if the SDCard is busy, same as the music app
3203 if (status.equals(Environment.MEDIA_SHARED)) {
3204 msg = getString(R.string.download_sdcard_busy_dlg_msg);
3205 title = R.string.download_sdcard_busy_dlg_title;
3206 } else {
3207 msg = getString(R.string.download_no_sdcard_dlg_msg, filename);
3208 title = R.string.download_no_sdcard_dlg_title;
3209 }
3210
3211 new AlertDialog.Builder(this)
3212 .setTitle(title)
3213 .setIcon(android.R.drawable.ic_dialog_alert)
3214 .setMessage(msg)
3215 .setPositiveButton(R.string.ok, null)
3216 .show();
3217 return;
3218 }
3219
Kristian Monsenfa52d172010-03-25 18:29:21 +00003220 // java.net.URI is a lot stricter than KURL so we have to encode some
3221 // extra characters. Fix for b 2538060 and b 1634719
3222 WebAddress webAddress;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003223 try {
Kristian Monsenfa52d172010-03-25 18:29:21 +00003224 webAddress = new WebAddress(url);
3225 webAddress.mPath = encodePath(webAddress.mPath);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003226 } catch (Exception e) {
Kristian Monsenfa52d172010-03-25 18:29:21 +00003227 // This only happens for very bad urls, we want to chatch the
3228 // exception here
3229 Log.e(LOGTAG, "Exception trying to parse url:" + url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003230 return;
3231 }
3232
3233 // XXX: Have to use the old url since the cookies were stored using the
3234 // old percent-encoded url.
3235 String cookies = CookieManager.getInstance().getCookie(url);
3236
3237 ContentValues values = new ContentValues();
Kristian Monsenfa52d172010-03-25 18:29:21 +00003238 values.put(Downloads.Impl.COLUMN_URI, webAddress.toString());
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08003239 values.put(Downloads.Impl.COLUMN_COOKIE_DATA, cookies);
3240 values.put(Downloads.Impl.COLUMN_USER_AGENT, userAgent);
3241 values.put(Downloads.Impl.COLUMN_NOTIFICATION_PACKAGE,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003242 getPackageName());
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08003243 values.put(Downloads.Impl.COLUMN_NOTIFICATION_CLASS,
Leon Scrogginsa563d092010-04-19 16:53:49 -04003244 OpenDownloadReceiver.class.getCanonicalName());
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08003245 values.put(Downloads.Impl.COLUMN_VISIBILITY,
3246 Downloads.Impl.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
3247 values.put(Downloads.Impl.COLUMN_MIME_TYPE, mimetype);
3248 values.put(Downloads.Impl.COLUMN_FILE_NAME_HINT, filename);
Kristian Monsenfa52d172010-03-25 18:29:21 +00003249 values.put(Downloads.Impl.COLUMN_DESCRIPTION, webAddress.mHost);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003250 if (contentLength > 0) {
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08003251 values.put(Downloads.Impl.COLUMN_TOTAL_BYTES, contentLength);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003252 }
3253 if (mimetype == null) {
3254 // We must have long pressed on a link or image to download it. We
3255 // are not sure of the mimetype in this case, so do a head request
3256 new FetchUrlMimeType(this).execute(values);
3257 } else {
3258 final Uri contentUri =
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08003259 getContentResolver().insert(Downloads.Impl.CONTENT_URI, values);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003260 }
Leon Scroggins9191a7f2010-03-18 14:44:44 -04003261 Toast.makeText(this, R.string.download_pending, Toast.LENGTH_SHORT)
3262 .show();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003263 }
3264
Grace Kloba22ac16e2009-10-07 18:00:23 -07003265 // -------------------------------------------------------------------------
3266
The Android Open Source Project0c908882009-03-03 19:32:16 -08003267 /**
3268 * Resets the lock icon. This method is called when we start a new load and
3269 * know the url to be loaded.
3270 */
3271 private void resetLockIcon(String url) {
3272 // Save the lock-icon state (we revert to it if the load gets cancelled)
Grace Kloba22ac16e2009-10-07 18:00:23 -07003273 mTabControl.getCurrentTab().resetLockIcon(url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003274 updateLockIconImage(LOCK_ICON_UNSECURE);
3275 }
3276
The Android Open Source Project0c908882009-03-03 19:32:16 -08003277 /**
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04003278 * Update the lock icon to correspond to our latest state.
3279 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003280 private void updateLockIconToLatest() {
Leon Scroggins91f65fc2010-06-29 13:52:39 -04003281 Tab t = mTabControl.getCurrentTab();
3282 if (t != null) {
3283 updateLockIconImage(t.getLockIconType());
3284 }
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04003285 }
3286
3287 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08003288 * Updates the lock-icon image in the title-bar.
3289 */
3290 private void updateLockIconImage(int lockIconType) {
3291 Drawable d = null;
3292 if (lockIconType == LOCK_ICON_SECURE) {
3293 d = mSecLockIcon;
3294 } else if (lockIconType == LOCK_ICON_MIXED) {
3295 d = mMixLockIcon;
3296 }
Leon Scroggins68579392009-09-15 15:31:54 -04003297 mTitleBar.setLock(d);
Michael Kolba2b2ba82010-08-04 17:54:03 -07003298 mFakeTitleBar.setLock(d);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003299 }
3300
3301 /**
3302 * Displays a page-info dialog.
3303 * @param tab The tab to show info about
3304 * @param fromShowSSLCertificateOnError The flag that indicates whether
3305 * this dialog was opened from the SSL-certificate-on-error dialog or
3306 * not. This is important, since we need to know whether to return to
3307 * the parent dialog or simply dismiss.
3308 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003309 private void showPageInfo(final Tab tab,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003310 final boolean fromShowSSLCertificateOnError) {
3311 final LayoutInflater factory = LayoutInflater
3312 .from(this);
3313
3314 final View pageInfoView = factory.inflate(R.layout.page_info, null);
3315
3316 final WebView view = tab.getWebView();
3317
3318 String url = null;
3319 String title = null;
3320
3321 if (view == null) {
3322 url = tab.getUrl();
3323 title = tab.getTitle();
3324 } else if (view == mTabControl.getCurrentWebView()) {
3325 // Use the cached title and url if this is the current WebView
3326 url = mUrl;
3327 title = mTitle;
3328 } else {
3329 url = view.getUrl();
3330 title = view.getTitle();
3331 }
3332
3333 if (url == null) {
3334 url = "";
3335 }
3336 if (title == null) {
3337 title = "";
3338 }
3339
3340 ((TextView) pageInfoView.findViewById(R.id.address)).setText(url);
3341 ((TextView) pageInfoView.findViewById(R.id.title)).setText(title);
3342
3343 mPageInfoView = tab;
Leon Scrogginsc7b92f82010-01-11 18:17:31 -05003344 mPageInfoFromShowSSLCertificateOnError = fromShowSSLCertificateOnError;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003345
3346 AlertDialog.Builder alertDialogBuilder =
3347 new AlertDialog.Builder(this)
3348 .setTitle(R.string.page_info).setIcon(android.R.drawable.ic_dialog_info)
3349 .setView(pageInfoView)
3350 .setPositiveButton(
3351 R.string.ok,
3352 new DialogInterface.OnClickListener() {
3353 public void onClick(DialogInterface dialog,
3354 int whichButton) {
3355 mPageInfoDialog = null;
3356 mPageInfoView = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003357
3358 // if we came here from the SSL error dialog
3359 if (fromShowSSLCertificateOnError) {
3360 // go back to the SSL error dialog
3361 showSSLCertificateOnError(
3362 mSSLCertificateOnErrorView,
3363 mSSLCertificateOnErrorHandler,
3364 mSSLCertificateOnErrorError);
3365 }
3366 }
3367 })
3368 .setOnCancelListener(
3369 new DialogInterface.OnCancelListener() {
3370 public void onCancel(DialogInterface dialog) {
3371 mPageInfoDialog = null;
3372 mPageInfoView = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003373
3374 // if we came here from the SSL error dialog
3375 if (fromShowSSLCertificateOnError) {
3376 // go back to the SSL error dialog
3377 showSSLCertificateOnError(
3378 mSSLCertificateOnErrorView,
3379 mSSLCertificateOnErrorHandler,
3380 mSSLCertificateOnErrorError);
3381 }
3382 }
3383 });
3384
3385 // if we have a main top-level page SSL certificate set or a certificate
3386 // error
3387 if (fromShowSSLCertificateOnError ||
3388 (view != null && view.getCertificate() != null)) {
3389 // add a 'View Certificate' button
3390 alertDialogBuilder.setNeutralButton(
3391 R.string.view_certificate,
3392 new DialogInterface.OnClickListener() {
3393 public void onClick(DialogInterface dialog,
3394 int whichButton) {
3395 mPageInfoDialog = null;
3396 mPageInfoView = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003397
3398 // if we came here from the SSL error dialog
3399 if (fromShowSSLCertificateOnError) {
3400 // go back to the SSL error dialog
3401 showSSLCertificateOnError(
3402 mSSLCertificateOnErrorView,
3403 mSSLCertificateOnErrorHandler,
3404 mSSLCertificateOnErrorError);
3405 } else {
3406 // otherwise, display the top-most certificate from
3407 // the chain
3408 if (view.getCertificate() != null) {
3409 showSSLCertificate(tab);
3410 }
3411 }
3412 }
3413 });
3414 }
3415
3416 mPageInfoDialog = alertDialogBuilder.show();
3417 }
3418
3419 /**
3420 * Displays the main top-level page SSL certificate dialog
3421 * (accessible from the Page-Info dialog).
3422 * @param tab The tab to show certificate for.
3423 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003424 private void showSSLCertificate(final Tab tab) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003425 final View certificateView =
3426 inflateCertificateView(tab.getWebView().getCertificate());
3427 if (certificateView == null) {
3428 return;
3429 }
3430
3431 LayoutInflater factory = LayoutInflater.from(this);
3432
3433 final LinearLayout placeholder =
3434 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3435
3436 LinearLayout ll = (LinearLayout) factory.inflate(
3437 R.layout.ssl_success, placeholder);
3438 ((TextView)ll.findViewById(R.id.success))
3439 .setText(R.string.ssl_certificate_is_valid);
3440
3441 mSSLCertificateView = tab;
3442 mSSLCertificateDialog =
3443 new AlertDialog.Builder(this)
3444 .setTitle(R.string.ssl_certificate).setIcon(
3445 R.drawable.ic_dialog_browser_certificate_secure)
3446 .setView(certificateView)
3447 .setPositiveButton(R.string.ok,
3448 new DialogInterface.OnClickListener() {
3449 public void onClick(DialogInterface dialog,
3450 int whichButton) {
3451 mSSLCertificateDialog = null;
3452 mSSLCertificateView = null;
3453
3454 showPageInfo(tab, false);
3455 }
3456 })
3457 .setOnCancelListener(
3458 new DialogInterface.OnCancelListener() {
3459 public void onCancel(DialogInterface dialog) {
3460 mSSLCertificateDialog = null;
3461 mSSLCertificateView = null;
3462
3463 showPageInfo(tab, false);
3464 }
3465 })
3466 .show();
3467 }
3468
3469 /**
3470 * Displays the SSL error certificate dialog.
3471 * @param view The target web-view.
3472 * @param handler The SSL error handler responsible for cancelling the
3473 * connection that resulted in an SSL error or proceeding per user request.
3474 * @param error The SSL error object.
3475 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003476 void showSSLCertificateOnError(
The Android Open Source Project0c908882009-03-03 19:32:16 -08003477 final WebView view, final SslErrorHandler handler, final SslError error) {
3478
3479 final View certificateView =
3480 inflateCertificateView(error.getCertificate());
3481 if (certificateView == null) {
3482 return;
3483 }
3484
3485 LayoutInflater factory = LayoutInflater.from(this);
3486
3487 final LinearLayout placeholder =
3488 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3489
3490 if (error.hasError(SslError.SSL_UNTRUSTED)) {
3491 LinearLayout ll = (LinearLayout)factory
3492 .inflate(R.layout.ssl_warning, placeholder);
3493 ((TextView)ll.findViewById(R.id.warning))
3494 .setText(R.string.ssl_untrusted);
3495 }
3496
3497 if (error.hasError(SslError.SSL_IDMISMATCH)) {
3498 LinearLayout ll = (LinearLayout)factory
3499 .inflate(R.layout.ssl_warning, placeholder);
3500 ((TextView)ll.findViewById(R.id.warning))
3501 .setText(R.string.ssl_mismatch);
3502 }
3503
3504 if (error.hasError(SslError.SSL_EXPIRED)) {
3505 LinearLayout ll = (LinearLayout)factory
3506 .inflate(R.layout.ssl_warning, placeholder);
3507 ((TextView)ll.findViewById(R.id.warning))
3508 .setText(R.string.ssl_expired);
3509 }
3510
3511 if (error.hasError(SslError.SSL_NOTYETVALID)) {
3512 LinearLayout ll = (LinearLayout)factory
3513 .inflate(R.layout.ssl_warning, placeholder);
3514 ((TextView)ll.findViewById(R.id.warning))
3515 .setText(R.string.ssl_not_yet_valid);
3516 }
3517
3518 mSSLCertificateOnErrorHandler = handler;
3519 mSSLCertificateOnErrorView = view;
3520 mSSLCertificateOnErrorError = error;
3521 mSSLCertificateOnErrorDialog =
3522 new AlertDialog.Builder(this)
3523 .setTitle(R.string.ssl_certificate).setIcon(
3524 R.drawable.ic_dialog_browser_certificate_partially_secure)
3525 .setView(certificateView)
3526 .setPositiveButton(R.string.ok,
3527 new DialogInterface.OnClickListener() {
3528 public void onClick(DialogInterface dialog,
3529 int whichButton) {
3530 mSSLCertificateOnErrorDialog = null;
3531 mSSLCertificateOnErrorView = null;
3532 mSSLCertificateOnErrorHandler = null;
3533 mSSLCertificateOnErrorError = null;
3534
Grace Kloba22ac16e2009-10-07 18:00:23 -07003535 view.getWebViewClient().onReceivedSslError(
3536 view, handler, error);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003537 }
3538 })
3539 .setNeutralButton(R.string.page_info_view,
3540 new DialogInterface.OnClickListener() {
3541 public void onClick(DialogInterface dialog,
3542 int whichButton) {
3543 mSSLCertificateOnErrorDialog = null;
3544
3545 // do not clear the dialog state: we will
3546 // need to show the dialog again once the
3547 // user is done exploring the page-info details
3548
3549 showPageInfo(mTabControl.getTabFromView(view),
3550 true);
3551 }
3552 })
3553 .setOnCancelListener(
3554 new DialogInterface.OnCancelListener() {
3555 public void onCancel(DialogInterface dialog) {
3556 mSSLCertificateOnErrorDialog = null;
3557 mSSLCertificateOnErrorView = null;
3558 mSSLCertificateOnErrorHandler = null;
3559 mSSLCertificateOnErrorError = null;
3560
Grace Kloba22ac16e2009-10-07 18:00:23 -07003561 view.getWebViewClient().onReceivedSslError(
3562 view, handler, error);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003563 }
3564 })
3565 .show();
3566 }
3567
3568 /**
3569 * Inflates the SSL certificate view (helper method).
3570 * @param certificate The SSL certificate.
3571 * @return The resultant certificate view with issued-to, issued-by,
3572 * issued-on, expires-on, and possibly other fields set.
3573 * If the input certificate is null, returns null.
3574 */
3575 private View inflateCertificateView(SslCertificate certificate) {
3576 if (certificate == null) {
3577 return null;
3578 }
3579
3580 LayoutInflater factory = LayoutInflater.from(this);
3581
3582 View certificateView = factory.inflate(
3583 R.layout.ssl_certificate, null);
3584
3585 // issued to:
3586 SslCertificate.DName issuedTo = certificate.getIssuedTo();
3587 if (issuedTo != null) {
3588 ((TextView) certificateView.findViewById(R.id.to_common))
3589 .setText(issuedTo.getCName());
3590 ((TextView) certificateView.findViewById(R.id.to_org))
3591 .setText(issuedTo.getOName());
3592 ((TextView) certificateView.findViewById(R.id.to_org_unit))
3593 .setText(issuedTo.getUName());
3594 }
3595
3596 // issued by:
3597 SslCertificate.DName issuedBy = certificate.getIssuedBy();
3598 if (issuedBy != null) {
3599 ((TextView) certificateView.findViewById(R.id.by_common))
3600 .setText(issuedBy.getCName());
3601 ((TextView) certificateView.findViewById(R.id.by_org))
3602 .setText(issuedBy.getOName());
3603 ((TextView) certificateView.findViewById(R.id.by_org_unit))
3604 .setText(issuedBy.getUName());
3605 }
3606
3607 // issued on:
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003608 String issuedOn = formatCertificateDate(
3609 certificate.getValidNotBeforeDate());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003610 ((TextView) certificateView.findViewById(R.id.issued_on))
3611 .setText(issuedOn);
3612
3613 // expires on:
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003614 String expiresOn = formatCertificateDate(
3615 certificate.getValidNotAfterDate());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003616 ((TextView) certificateView.findViewById(R.id.expires_on))
3617 .setText(expiresOn);
3618
3619 return certificateView;
3620 }
3621
3622 /**
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003623 * Formats the certificate date to a properly localized date string.
The Android Open Source Project0c908882009-03-03 19:32:16 -08003624 * @return Properly localized version of the certificate date string and
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003625 * the "" if it fails to localize.
The Android Open Source Project0c908882009-03-03 19:32:16 -08003626 */
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003627 private String formatCertificateDate(Date certificateDate) {
3628 if (certificateDate == null) {
3629 return "";
The Android Open Source Project0c908882009-03-03 19:32:16 -08003630 }
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003631 String formattedDate = DateFormat.getDateFormat(this).format(certificateDate);
3632 if (formattedDate == null) {
3633 return "";
3634 }
3635 return formattedDate;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003636 }
3637
3638 /**
3639 * Displays an http-authentication dialog.
3640 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003641 void showHttpAuthentication(final HttpAuthHandler handler,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003642 final String host, final String realm, final String title,
3643 final String name, final String password, int focusId) {
3644 LayoutInflater factory = LayoutInflater.from(this);
3645 final View v = factory
3646 .inflate(R.layout.http_authentication, null);
3647 if (name != null) {
3648 ((EditText) v.findViewById(R.id.username_edit)).setText(name);
3649 }
3650 if (password != null) {
3651 ((EditText) v.findViewById(R.id.password_edit)).setText(password);
3652 }
3653
3654 String titleText = title;
3655 if (titleText == null) {
3656 titleText = getText(R.string.sign_in_to).toString().replace(
3657 "%s1", host).replace("%s2", realm);
3658 }
3659
3660 mHttpAuthHandler = handler;
3661 AlertDialog dialog = new AlertDialog.Builder(this)
3662 .setTitle(titleText)
3663 .setIcon(android.R.drawable.ic_dialog_alert)
3664 .setView(v)
3665 .setPositiveButton(R.string.action,
3666 new DialogInterface.OnClickListener() {
3667 public void onClick(DialogInterface dialog,
3668 int whichButton) {
3669 String nm = ((EditText) v
3670 .findViewById(R.id.username_edit))
3671 .getText().toString();
3672 String pw = ((EditText) v
3673 .findViewById(R.id.password_edit))
3674 .getText().toString();
3675 BrowserActivity.this.setHttpAuthUsernamePassword
3676 (host, realm, nm, pw);
3677 handler.proceed(nm, pw);
3678 mHttpAuthenticationDialog = null;
3679 mHttpAuthHandler = null;
3680 }})
3681 .setNegativeButton(R.string.cancel,
3682 new DialogInterface.OnClickListener() {
3683 public void onClick(DialogInterface dialog,
3684 int whichButton) {
3685 handler.cancel();
3686 BrowserActivity.this.resetTitleAndRevertLockIcon();
3687 mHttpAuthenticationDialog = null;
3688 mHttpAuthHandler = null;
3689 }})
3690 .setOnCancelListener(new DialogInterface.OnCancelListener() {
3691 public void onCancel(DialogInterface dialog) {
3692 handler.cancel();
3693 BrowserActivity.this.resetTitleAndRevertLockIcon();
3694 mHttpAuthenticationDialog = null;
3695 mHttpAuthHandler = null;
3696 }})
3697 .create();
3698 // Make the IME appear when the dialog is displayed if applicable.
3699 dialog.getWindow().setSoftInputMode(
3700 WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
3701 dialog.show();
3702 if (focusId != 0) {
3703 dialog.findViewById(focusId).requestFocus();
3704 } else {
3705 v.findViewById(R.id.username_edit).requestFocus();
3706 }
3707 mHttpAuthenticationDialog = dialog;
3708 }
3709
3710 public int getProgress() {
3711 WebView w = mTabControl.getCurrentWebView();
3712 if (w != null) {
3713 return w.getProgress();
3714 } else {
3715 return 100;
3716 }
3717 }
3718
3719 /**
3720 * Set HTTP authentication password.
3721 *
3722 * @param host The host for the password
3723 * @param realm The realm for the password
3724 * @param username The username for the password. If it is null, it means
3725 * password can't be saved.
3726 * @param password The password
3727 */
3728 public void setHttpAuthUsernamePassword(String host, String realm,
3729 String username,
3730 String password) {
Steve Block95a53b22010-03-25 17:24:58 +00003731 WebView w = getTopWindow();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003732 if (w != null) {
3733 w.setHttpAuthUsernamePassword(host, realm, username, password);
3734 }
3735 }
3736
3737 /**
3738 * connectivity manager says net has come or gone... inform the user
3739 * @param up true if net has come up, false if net has gone down
3740 */
3741 public void onNetworkToggle(boolean up) {
3742 if (up == mIsNetworkUp) {
3743 return;
3744 } else if (up) {
3745 mIsNetworkUp = true;
3746 if (mAlertDialog != null) {
3747 mAlertDialog.cancel();
3748 mAlertDialog = null;
3749 }
3750 } else {
3751 mIsNetworkUp = false;
Patrick Scotteb6ab2a2009-09-16 10:00:17 -04003752 if (mInLoad) {
3753 createAndShowNetworkDialog();
3754 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003755 }
3756 WebView w = mTabControl.getCurrentWebView();
3757 if (w != null) {
3758 w.setNetworkAvailable(up);
3759 }
3760 }
3761
Grace Kloba22ac16e2009-10-07 18:00:23 -07003762 boolean isNetworkUp() {
3763 return mIsNetworkUp;
3764 }
3765
Patrick Scotteb6ab2a2009-09-16 10:00:17 -04003766 // This method shows the network dialog alerting the user that the net is
3767 // down. It will only show the dialog if mAlertDialog is null.
3768 private void createAndShowNetworkDialog() {
3769 if (mAlertDialog == null) {
3770 mAlertDialog = new AlertDialog.Builder(this)
3771 .setTitle(R.string.loadSuspendedTitle)
3772 .setMessage(R.string.loadSuspended)
3773 .setPositiveButton(R.string.ok, null)
3774 .show();
3775 }
3776 }
3777
The Android Open Source Project0c908882009-03-03 19:32:16 -08003778 @Override
3779 protected void onActivityResult(int requestCode, int resultCode,
3780 Intent intent) {
Grace Klobabb394f32009-11-19 10:26:37 -08003781 if (getTopWindow() == null) return;
3782
The Android Open Source Project0c908882009-03-03 19:32:16 -08003783 switch (requestCode) {
3784 case COMBO_PAGE:
3785 if (resultCode == RESULT_OK && intent != null) {
3786 String data = intent.getAction();
3787 Bundle extras = intent.getExtras();
Michael Kolb300b7f02010-08-25 13:47:24 -07003788 if (extras != null &&
3789 extras.getBoolean(
3790 CombinedBookmarkHistoryActivity.EXTRA_OPEN_NEW_WINDOW,
3791 false)) {
Michael Kolb68792c82010-08-09 16:39:18 -07003792 openTab(data, false);
3793 } else if ((extras != null) &&
3794 extras.getBoolean(CombinedBookmarkHistoryActivity.NEWTAB_MODE)) {
3795 openTab(data, true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003796 } else {
Michael Kolb68792c82010-08-09 16:39:18 -07003797 final Tab currentTab = mTabControl.getCurrentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04003798 dismissSubWindow(currentTab);
3799 if (data != null && data.length() != 0) {
Leon Scroggins92472e82010-02-17 16:32:28 -05003800 loadUrl(getTopWindow(), data);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003801 }
3802 }
Michael Kolb3f65c382010-08-20 15:31:16 -07003803 } else if (resultCode == RESULT_CANCELED) {
3804 if (intent != null) {
3805 float evtx = intent.getFloatExtra(CombinedBookmarkHistoryActivity.EVT_X, -1);
3806 float evty = intent.getFloatExtra(CombinedBookmarkHistoryActivity.EVT_Y, -1);
3807 long now = System.currentTimeMillis();
3808 MotionEvent evt = MotionEvent.obtain(now, now,
3809 MotionEvent.ACTION_DOWN, evtx, evty, 0);
3810 dispatchTouchEvent(evt);
3811 MotionEvent up = MotionEvent.obtain(evt);
3812 up.setAction(MotionEvent.ACTION_UP);
3813 dispatchTouchEvent(up);
3814 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003815 }
Leon Scrogginsfde97462010-01-11 13:06:21 -05003816 // Deliberately fall through to PREFERENCES_PAGE, since the
3817 // same extra may be attached to the COMBO_PAGE
3818 case PREFERENCES_PAGE:
3819 if (resultCode == RESULT_OK && intent != null) {
3820 String action = intent.getStringExtra(Intent.EXTRA_TEXT);
3821 if (BrowserSettings.PREF_CLEAR_HISTORY.equals(action)) {
3822 mTabControl.removeParentChildRelationShips();
3823 }
3824 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003825 break;
Leon Scroggins8d5fa432009-10-02 15:55:59 -04003826 // Choose a file from the file picker.
3827 case FILE_SELECTED:
3828 if (null == mUploadMessage) break;
3829 Uri result = intent == null || resultCode != RESULT_OK ? null
3830 : intent.getData();
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003831
3832 // As we ask the camera to save the result of the user taking
3833 // a picture, the camera application does not return anything other
3834 // than RESULT_OK. So we need to check whether the file we expected
3835 // was written to disk in the in the case that we
3836 // did not get an intent returned but did get a RESULT_OK. If it was,
3837 // we assume that this result has came back from the camera.
3838 if (result == null && intent == null && resultCode == RESULT_OK) {
3839 File cameraFile = new File(mCameraFilePath);
3840 if (cameraFile.exists()) {
3841 result = Uri.fromFile(cameraFile);
Ben Murdoch07d34732010-05-27 18:34:46 +01003842 // Broadcast to the media scanner that we have a new photo
3843 // so it will be added into the gallery for the user.
3844 sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, result));
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003845 }
3846 }
Leon Scroggins8d5fa432009-10-02 15:55:59 -04003847 mUploadMessage.onReceiveValue(result);
3848 mUploadMessage = null;
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003849 mCameraFilePath = null;
Leon Scroggins8d5fa432009-10-02 15:55:59 -04003850 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003851 default:
3852 break;
3853 }
Leon Scroggins30444232009-09-04 18:36:20 -04003854 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003855 }
3856
3857 /*
3858 * This method is called as a result of the user selecting the options
Leon Scrogginsf08809b2010-01-21 09:27:46 -05003859 * menu to see the download window. It shows the download window on top of
3860 * the current window.
The Android Open Source Project0c908882009-03-03 19:32:16 -08003861 */
Leon Scrogginsf08809b2010-01-21 09:27:46 -05003862 private void viewDownloads(Uri downloadRecord) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003863 Intent intent = new Intent(this,
3864 BrowserDownloadPage.class);
3865 intent.setData(downloadRecord);
Grace Kloba22ac16e2009-10-07 18:00:23 -07003866 startActivityForResult(intent, BrowserActivity.DOWNLOAD_PAGE);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003867
3868 }
3869
Michael Kolbc7485ae2010-09-03 10:10:58 -07003870 /* package */ void promptAddOrInstallBookmark(View anchor) {
3871 PopupMenu popup = new PopupMenu(this, anchor);
3872 popup.getMenuInflater().inflate(R.menu.bookmark_shortcut, popup.getMenu());
3873 popup.setOnMenuItemClickListener(this);
3874 popup.show();
3875 }
3876
3877 /**
3878 * popup menu item click listener
3879 * @param item
3880 */
3881 public boolean onMenuItemClick(MenuItem item) {
3882 switch(item.getItemId()) {
3883 case R.id.add_bookmark_menu_id:
3884 bookmarkCurrentPage();
3885 return true;
3886 case R.id.shortcut_to_home_menu_id:
3887 Tab current = mTabControl.getCurrentTab();
3888 current.populatePickerData();
3889 String touchIconUrl = mTabControl.getCurrentWebView().getTouchIconUrl();
3890 if (touchIconUrl != null) {
3891 // Download the touch icon for this site then save
3892 // it to the
3893 // homescreen.
3894 Bundle b = new Bundle();
3895 b.putString("url", current.getUrl());
3896 b.putString("title", current.getTitle());
3897 b.putParcelable("favicon", current.getFavicon());
3898 Message msg = mHandler.obtainMessage(TOUCH_ICON_DOWNLOADED);
3899 msg.setData(b);
3900 new DownloadTouchIcon(BrowserActivity.this, msg,
3901 mTabControl.getCurrentWebView().getSettings().getUserAgentString())
3902 .execute(touchIconUrl);
3903 } else {
3904 // add to homescreen, can do it immediately as there
3905 // is no touch
3906 // icon.
3907 showSaveToHomescreenDialog(
3908 current.getUrl(), current.getTitle(), null, current.getFavicon());
3909 }
3910 return true;
3911 default:
3912 return false;
3913 }
3914 }
3915
3916 /* package */Dialog makeAddOrInstallDialog() {
Ben Murdocheecb4e62010-07-06 16:30:38 +01003917 final Tab current = mTabControl.getCurrentTab();
3918 Resources resources = getResources();
Michael Kolbc7485ae2010-09-03 10:10:58 -07003919 CharSequence[] choices =
3920 {resources.getString(R.string.save_to_bookmarks),
3921 resources.getString(R.string.create_shortcut_bookmark)};
Ben Murdocheecb4e62010-07-06 16:30:38 +01003922
3923 AlertDialog.Builder builder = new AlertDialog.Builder(this);
3924 builder.setTitle(R.string.add_new_bookmark);
3925 builder.setItems(choices, new DialogInterface.OnClickListener() {
Michael Kolbc7485ae2010-09-03 10:10:58 -07003926 public void onClick(DialogInterface dialog, int item) {
3927 if (item == 0) {
3928 bookmarkCurrentPage();
3929 } else if (item == 1) {
3930 }
3931 }
Ben Murdocheecb4e62010-07-06 16:30:38 +01003932 });
Michael Kolbc7485ae2010-09-03 10:10:58 -07003933 return builder.create();
Ben Murdocheecb4e62010-07-06 16:30:38 +01003934 }
3935
Leon Scroggins160a7e72009-08-14 18:28:01 -04003936 /**
3937 * Open the Go page.
3938 * @param startWithHistory If true, open starting on the history tab.
3939 * Otherwise, start with the bookmarks tab.
Leon Scroggins160a7e72009-08-14 18:28:01 -04003940 */
Michael Kolb68792c82010-08-09 16:39:18 -07003941 /* package */ void bookmarksOrHistoryPicker(boolean startWithHistory, boolean newTabMode) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003942 WebView current = mTabControl.getCurrentWebView();
3943 if (current == null) {
3944 return;
3945 }
3946 Intent intent = new Intent(this,
3947 CombinedBookmarkHistoryActivity.class);
3948 String title = current.getTitle();
3949 String url = current.getUrl();
Ben Murdoch87cc65d2010-06-29 20:34:10 +01003950 Bitmap thumbnail = createScreenshot(current, getDesiredThumbnailWidth(this),
3951 getDesiredThumbnailHeight(this));
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01003952
The Android Open Source Project0c908882009-03-03 19:32:16 -08003953 // Just in case the user opens bookmarks before a page finishes loading
3954 // so the current history item, and therefore the page, is null.
3955 if (null == url) {
3956 url = mLastEnteredUrl;
3957 // This can happen.
3958 if (null == url) {
3959 url = mSettings.getHomePage();
3960 }
3961 }
3962 // In case the web page has not yet received its associated title.
3963 if (title == null) {
3964 title = url;
3965 }
3966 intent.putExtra("title", title);
3967 intent.putExtra("url", url);
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01003968 intent.putExtra("thumbnail", thumbnail);
Leon Scroggins30444232009-09-04 18:36:20 -04003969 // Disable opening in a new window if we have maxed out the windows
Grace Kloba22ac16e2009-10-07 18:00:23 -07003970 intent.putExtra("disable_new_window", !mTabControl.canCreateNewTab());
Patrick Scott3918d442009-08-04 13:22:29 -04003971 intent.putExtra("touch_icon_url", current.getTouchIconUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003972 if (startWithHistory) {
Jeff Hamilton64144e42010-08-18 16:31:59 -05003973 intent.putExtra(CombinedBookmarkHistoryActivity.STARTING_FRAGMENT,
3974 CombinedBookmarkHistoryActivity.FRAGMENT_ID_HISTORY);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003975 }
Michael Kolb300b7f02010-08-25 13:47:24 -07003976 intent.putExtra(CombinedBookmarkHistoryActivity.NEWTAB_MODE, newTabMode);
Michael Kolb0998b0a2010-08-23 17:45:35 -07003977 int top = -1;
3978 int height = -1;
Michael Kolb3f65c382010-08-20 15:31:16 -07003979 if (mXLargeScreenSize) {
3980 showFakeTitleBar();
3981 int titleBarHeight = ((TitleBarXLarge)mFakeTitleBar).getHeightWithoutProgress();
Michael Kolb0998b0a2010-08-23 17:45:35 -07003982 top = mTabBar.getBottom() + titleBarHeight;
3983 height = getTopWindow().getHeight() - titleBarHeight;
Michael Kolb68792c82010-08-09 16:39:18 -07003984 }
Michael Kolb0998b0a2010-08-23 17:45:35 -07003985 intent.putExtra(CombinedBookmarkHistoryActivity.EXTRA_TOP, top);
3986 intent.putExtra(CombinedBookmarkHistoryActivity.EXTRA_HEIGHT, height);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003987 startActivityForResult(intent, COMBO_PAGE);
3988 }
3989
Ben Murdocheecb4e62010-07-06 16:30:38 +01003990 private void showSaveToHomescreenDialog(String url, String title, Bitmap touchIcon,
3991 Bitmap favicon) {
3992 Intent intent = new Intent(this, SaveToHomescreenDialog.class);
3993
3994 // Just in case the user tries to save before a page finishes loading
3995 // so the current history item, and therefore the page, is null.
3996 if (null == url) {
3997 url = mLastEnteredUrl;
3998 // This can happen.
3999 if (null == url) {
4000 url = mSettings.getHomePage();
4001 }
4002 }
4003
4004 // In case the web page has not yet received its associated title.
4005 if (title == null) {
4006 title = url;
4007 }
4008
4009 intent.putExtra("title", title);
4010 intent.putExtra("url", url);
4011 intent.putExtra("favicon", favicon);
4012 intent.putExtra("touchIcon", touchIcon);
4013 startActivity(intent);
4014 }
4015
4016
The Android Open Source Project0c908882009-03-03 19:32:16 -08004017 // Called when loading from context menu or LOAD_URL message
Leon Scroggins92472e82010-02-17 16:32:28 -05004018 private void loadUrlFromContext(WebView view, String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08004019 // In case the user enters nothing.
4020 if (url != null && url.length() != 0 && view != null) {
4021 url = smartUrlFilter(url);
Grace Kloba22ac16e2009-10-07 18:00:23 -07004022 if (!view.getWebViewClient().shouldOverrideUrlLoading(view, url)) {
Leon Scroggins92472e82010-02-17 16:32:28 -05004023 loadUrl(view, url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004024 }
4025 }
4026 }
4027
Leon Scroggins92472e82010-02-17 16:32:28 -05004028 /**
4029 * Load the URL into the given WebView and update the title bar
4030 * to reflect the new load. Call this instead of WebView.loadUrl
4031 * directly.
4032 * @param view The WebView used to load url.
4033 * @param url The URL to load.
4034 */
4035 private void loadUrl(WebView view, String url) {
4036 updateTitleBarForNewLoad(view, url);
4037 view.loadUrl(url);
4038 }
4039
4040 /**
4041 * Load UrlData into a Tab and update the title bar to reflect the new
4042 * load. Call this instead of UrlData.loadIn directly.
4043 * @param t The Tab used to load.
4044 * @param data The UrlData being loaded.
4045 */
4046 private void loadUrlDataIn(Tab t, UrlData data) {
4047 updateTitleBarForNewLoad(t.getWebView(), data.mUrl);
4048 data.loadIn(t);
4049 }
4050
4051 /**
4052 * If the WebView is the top window, update the title bar to reflect
4053 * loading the new URL. i.e. set its text, clear the favicon (which
4054 * will be set once the page begins loading), and set the progress to
4055 * INITIAL_PROGRESS to show that the page has begun to load. Called
4056 * by loadUrl and loadUrlDataIn.
4057 * @param view The WebView that is starting a load.
4058 * @param url The URL that is being loaded.
4059 */
4060 private void updateTitleBarForNewLoad(WebView view, String url) {
4061 if (view == getTopWindow()) {
4062 setUrlTitle(url, null);
4063 setFavicon(null);
4064 onProgressChanged(view, INITIAL_PROGRESS);
4065 }
4066 }
4067
The Android Open Source Project0c908882009-03-03 19:32:16 -08004068 private String smartUrlFilter(Uri inUri) {
4069 if (inUri != null) {
4070 return smartUrlFilter(inUri.toString());
4071 }
4072 return null;
4073 }
4074
Feng Qianb34f87a2009-03-24 21:27:26 -07004075 protected static final Pattern ACCEPTED_URI_SCHEMA = Pattern.compile(
The Android Open Source Project0c908882009-03-03 19:32:16 -08004076 "(?i)" + // switch on case insensitive matching
4077 "(" + // begin group for schema
4078 "(?:http|https|file):\\/\\/" +
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004079 "|(?:inline|data|about|content|javascript):" +
The Android Open Source Project0c908882009-03-03 19:32:16 -08004080 ")" +
4081 "(.*)" );
4082
4083 /**
4084 * Attempts to determine whether user input is a URL or search
4085 * terms. Anything with a space is passed to search.
4086 *
4087 * Converts to lowercase any mistakenly uppercased schema (i.e.,
4088 * "Http://" converts to "http://"
4089 *
4090 * @return Original or modified URL
4091 *
4092 */
4093 String smartUrlFilter(String url) {
4094
4095 String inUrl = url.trim();
4096 boolean hasSpace = inUrl.indexOf(' ') != -1;
4097
4098 Matcher matcher = ACCEPTED_URI_SCHEMA.matcher(inUrl);
4099 if (matcher.matches()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08004100 // force scheme to lowercase
4101 String scheme = matcher.group(1);
4102 String lcScheme = scheme.toLowerCase();
4103 if (!lcScheme.equals(scheme)) {
Mitsuru Oshima123ecfb2009-05-18 19:11:14 -07004104 inUrl = lcScheme + matcher.group(2);
4105 }
4106 if (hasSpace) {
4107 inUrl = inUrl.replace(" ", "%20");
The Android Open Source Project0c908882009-03-03 19:32:16 -08004108 }
4109 return inUrl;
4110 }
4111 if (hasSpace) {
Satish Sampath565505b2009-05-29 15:37:27 +01004112 // FIXME: Is this the correct place to add to searches?
4113 // what if someone else calls this function?
4114 int shortcut = parseUrlShortcut(inUrl);
4115 if (shortcut != SHORTCUT_INVALID) {
4116 Browser.addSearchUrl(mResolver, inUrl);
4117 String query = inUrl.substring(2);
4118 switch (shortcut) {
4119 case SHORTCUT_GOOGLE_SEARCH:
Grace Kloba47fdfdb2009-06-30 11:15:34 -07004120 return URLUtil.composeSearchUrl(query, QuickSearch_G, QUERY_PLACE_HOLDER);
Satish Sampath565505b2009-05-29 15:37:27 +01004121 case SHORTCUT_WIKIPEDIA_SEARCH:
4122 return URLUtil.composeSearchUrl(query, QuickSearch_W, QUERY_PLACE_HOLDER);
4123 case SHORTCUT_DICTIONARY_SEARCH:
4124 return URLUtil.composeSearchUrl(query, QuickSearch_D, QUERY_PLACE_HOLDER);
4125 case SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH:
The Android Open Source Project0c908882009-03-03 19:32:16 -08004126 // FIXME: we need location in this case
Satish Sampath565505b2009-05-29 15:37:27 +01004127 return URLUtil.composeSearchUrl(query, QuickSearch_L, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004128 }
4129 }
4130 } else {
Dan Egnor5ee906c2009-11-18 12:11:49 -08004131 if (Patterns.WEB_URL.matcher(inUrl).matches()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08004132 return URLUtil.guessUrl(inUrl);
4133 }
4134 }
4135
4136 Browser.addSearchUrl(mResolver, inUrl);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07004137 return URLUtil.composeSearchUrl(inUrl, QuickSearch_G, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004138 }
4139
Ben Murdochbff2d602009-07-01 20:19:05 +01004140 /* package */ void setShouldShowErrorConsole(boolean flag) {
4141 if (flag == mShouldShowErrorConsole) {
4142 // Nothing to do.
4143 return;
4144 }
4145
4146 mShouldShowErrorConsole = flag;
4147
Grace Kloba22ac16e2009-10-07 18:00:23 -07004148 ErrorConsoleView errorConsole = mTabControl.getCurrentTab()
4149 .getErrorConsole(true);
Ben Murdochbff2d602009-07-01 20:19:05 +01004150
4151 if (flag) {
4152 // Setting the show state of the console will cause it's the layout to be inflated.
4153 if (errorConsole.numberOfErrors() > 0) {
4154 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
4155 } else {
4156 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
4157 }
4158
4159 // Now we can add it to the main view.
4160 mErrorConsoleContainer.addView(errorConsole,
Romain Guy15b8ec62010-01-08 15:06:43 -08004161 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
Ben Murdochbff2d602009-07-01 20:19:05 +01004162 ViewGroup.LayoutParams.WRAP_CONTENT));
4163 } else {
4164 mErrorConsoleContainer.removeView(errorConsole);
4165 }
4166
4167 }
4168
Grace Kloba22ac16e2009-10-07 18:00:23 -07004169 boolean shouldShowErrorConsole() {
4170 return mShouldShowErrorConsole;
4171 }
4172
Andrei Popescu163ab742009-10-20 17:58:23 +01004173 private void setStatusBarVisibility(boolean visible) {
4174 int flag = visible ? 0 : WindowManager.LayoutParams.FLAG_FULLSCREEN;
4175 getWindow().setFlags(flag, WindowManager.LayoutParams.FLAG_FULLSCREEN);
4176 }
4177
Andrei Popescu56199cc2010-01-12 22:39:16 +00004178
4179 private void sendNetworkType(String type, String subtype) {
4180 WebView w = mTabControl.getCurrentWebView();
4181 if (w != null) {
4182 w.setNetworkType(type, subtype);
4183 }
4184 }
4185
Grace Klobaeb6eef42009-09-15 17:56:32 -07004186 final static int LOCK_ICON_UNSECURE = 0;
4187 final static int LOCK_ICON_SECURE = 1;
4188 final static int LOCK_ICON_MIXED = 2;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004189
The Android Open Source Project0c908882009-03-03 19:32:16 -08004190 private BrowserSettings mSettings;
4191 private TabControl mTabControl;
4192 private ContentResolver mResolver;
4193 private FrameLayout mContentView;
Andrei Popescuadc008d2009-06-26 14:11:30 +01004194 private View mCustomView;
4195 private FrameLayout mCustomViewContainer;
Andrei Popescuc9b55562009-07-07 10:51:15 +01004196 private WebChromeClient.CustomViewCallback mCustomViewCallback;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004197
4198 // FIXME, temp address onPrepareMenu performance problem. When we move everything out of
4199 // view, we should rewrite this.
4200 private int mCurrentMenuState = 0;
4201 private int mMenuState = R.id.MAIN_MENU;
Andrei Popescuadc008d2009-06-26 14:11:30 +01004202 private int mOldMenuState = EMPTY_MENU;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004203 private static final int EMPTY_MENU = -1;
4204 private Menu mMenu;
4205
The Android Open Source Project0c908882009-03-03 19:32:16 -08004206 // Used to prevent chording to result in firing two shortcuts immediately
4207 // one after another. Fixes bug 1211714.
4208 boolean mCanChord;
4209
4210 private boolean mInLoad;
4211 private boolean mIsNetworkUp;
Ben Murdochb7cc8b42009-09-28 10:59:09 +01004212 private boolean mDidStopLoad;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004213
Cary Clark1f10cbf2010-03-22 11:45:23 -04004214 /* package */ boolean mActivityInPause = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004215
4216 private boolean mMenuIsDown;
4217
The Android Open Source Project0c908882009-03-03 19:32:16 -08004218 private static boolean mInTrace;
4219
4220 // Performance probe
4221 private static final int[] SYSTEM_CPU_FORMAT = new int[] {
4222 Process.PROC_SPACE_TERM | Process.PROC_COMBINE,
4223 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 1: user time
4224 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 2: nice time
4225 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 3: sys time
4226 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 4: idle time
4227 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 5: iowait time
4228 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 6: irq time
4229 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG // 7: softirq time
4230 };
4231
4232 private long mStart;
4233 private long mProcessStart;
4234 private long mUserStart;
4235 private long mSystemStart;
4236 private long mIdleStart;
4237 private long mIrqStart;
4238
4239 private long mUiStart;
4240
4241 private Drawable mMixLockIcon;
4242 private Drawable mSecLockIcon;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004243
4244 /* hold a ref so we can auto-cancel if necessary */
4245 private AlertDialog mAlertDialog;
4246
The Android Open Source Project0c908882009-03-03 19:32:16 -08004247 // The up-to-date URL and title (these can be different from those stored
4248 // in WebView, since it takes some time for the information in WebView to
4249 // get updated)
4250 private String mUrl;
4251 private String mTitle;
4252
4253 // As PageInfo has different style for landscape / portrait, we have
4254 // to re-open it when configuration changed
4255 private AlertDialog mPageInfoDialog;
Grace Kloba22ac16e2009-10-07 18:00:23 -07004256 private Tab mPageInfoView;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004257 // If the Page-Info dialog is launched from the SSL-certificate-on-error
4258 // dialog, we should not just dismiss it, but should get back to the
4259 // SSL-certificate-on-error dialog. This flag is used to store this state
Leon Scrogginsc7b92f82010-01-11 18:17:31 -05004260 private boolean mPageInfoFromShowSSLCertificateOnError;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004261
4262 // as SSLCertificateOnError has different style for landscape / portrait,
4263 // we have to re-open it when configuration changed
4264 private AlertDialog mSSLCertificateOnErrorDialog;
4265 private WebView mSSLCertificateOnErrorView;
4266 private SslErrorHandler mSSLCertificateOnErrorHandler;
4267 private SslError mSSLCertificateOnErrorError;
4268
4269 // as SSLCertificate has different style for landscape / portrait, we
4270 // have to re-open it when configuration changed
4271 private AlertDialog mSSLCertificateDialog;
Grace Kloba22ac16e2009-10-07 18:00:23 -07004272 private Tab mSSLCertificateView;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004273
4274 // as HttpAuthentication has different style for landscape / portrait, we
4275 // have to re-open it when configuration changed
4276 private AlertDialog mHttpAuthenticationDialog;
4277 private HttpAuthHandler mHttpAuthHandler;
4278
4279 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_PARAMS =
4280 new FrameLayout.LayoutParams(
Romain Guy15b8ec62010-01-08 15:06:43 -08004281 ViewGroup.LayoutParams.MATCH_PARENT,
4282 ViewGroup.LayoutParams.MATCH_PARENT);
Andrei Popescuadc008d2009-06-26 14:11:30 +01004283 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_GRAVITY_CENTER =
4284 new FrameLayout.LayoutParams(
Romain Guy15b8ec62010-01-08 15:06:43 -08004285 ViewGroup.LayoutParams.MATCH_PARENT,
4286 ViewGroup.LayoutParams.MATCH_PARENT,
Andrei Popescuadc008d2009-06-26 14:11:30 +01004287 Gravity.CENTER);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07004288 // Google search
4289 final static String QuickSearch_G = "http://www.google.com/m?q=%s";
The Android Open Source Project0c908882009-03-03 19:32:16 -08004290 // Wikipedia search
4291 final static String QuickSearch_W = "http://en.wikipedia.org/w/index.php?search=%s&go=Go";
4292 // Dictionary search
4293 final static String QuickSearch_D = "http://dictionary.reference.com/search?q=%s";
4294 // Google Mobile Local search
4295 final static String QuickSearch_L = "http://www.google.com/m/search?site=local&q=%s&near=mountain+view";
4296
4297 final static String QUERY_PLACE_HOLDER = "%s";
4298
4299 // "source" parameter for Google search through search key
4300 final static String GOOGLE_SEARCH_SOURCE_SEARCHKEY = "browser-key";
4301 // "source" parameter for Google search through goto menu
4302 final static String GOOGLE_SEARCH_SOURCE_GOTO = "browser-goto";
4303 // "source" parameter for Google search through simplily type
4304 final static String GOOGLE_SEARCH_SOURCE_TYPE = "browser-type";
4305 // "source" parameter for Google search suggested by the browser
4306 final static String GOOGLE_SEARCH_SOURCE_SUGGEST = "browser-suggest";
4307 // "source" parameter for Google search from unknown source
4308 final static String GOOGLE_SEARCH_SOURCE_UNKNOWN = "unknown";
4309
4310 private final static String LOGTAG = "browser";
4311
The Android Open Source Project0c908882009-03-03 19:32:16 -08004312 private String mLastEnteredUrl;
4313
4314 private PowerManager.WakeLock mWakeLock;
4315 private final static int WAKELOCK_TIMEOUT = 5 * 60 * 1000; // 5 minutes
4316
4317 private Toast mStopToast;
4318
Leon Scroggins571b3762010-05-26 10:25:01 -04004319 private TitleBarBase mTitleBar;
Michael Kolba2b2ba82010-08-04 17:54:03 -07004320 private TabBar mTabBar;
Leon Scroggins81db3662009-06-04 17:45:11 -04004321
Ben Murdochbff2d602009-07-01 20:19:05 +01004322 private LinearLayout mErrorConsoleContainer = null;
4323 private boolean mShouldShowErrorConsole = false;
4324
The Android Open Source Project0c908882009-03-03 19:32:16 -08004325 // As the ids are dynamically created, we can't guarantee that they will
4326 // be in sequence, so this static array maps ids to a window number.
4327 final static private int[] WINDOW_SHORTCUT_ID_ARRAY =
4328 { R.id.window_one_menu_id, R.id.window_two_menu_id, R.id.window_three_menu_id,
4329 R.id.window_four_menu_id, R.id.window_five_menu_id, R.id.window_six_menu_id,
4330 R.id.window_seven_menu_id, R.id.window_eight_menu_id };
4331
4332 // monitor platform changes
4333 private IntentFilter mNetworkStateChangedFilter;
4334 private BroadcastReceiver mNetworkStateIntentReceiver;
4335
Bjorn Bringerta7611812010-03-24 11:12:02 +00004336 private SystemAllowGeolocationOrigins mSystemAllowGeolocationOrigins;
4337
The Android Open Source Project0c908882009-03-03 19:32:16 -08004338 // activity requestCode
Nicolas Roard78a98e42009-05-11 13:34:17 +01004339 final static int COMBO_PAGE = 1;
4340 final static int DOWNLOAD_PAGE = 2;
4341 final static int PREFERENCES_PAGE = 3;
Leon Scroggins8d5fa432009-10-02 15:55:59 -04004342 final static int FILE_SELECTED = 4;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004343
Andrei Popescu540035d2009-09-18 18:59:20 +01004344 // the default <video> poster
4345 private Bitmap mDefaultVideoPoster;
4346 // the video progress view
4347 private View mVideoProgressView;
4348
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004349 /**
4350 * A UrlData class to abstract how the content will be set to WebView.
4351 * This base class uses loadUrl to show the content.
4352 */
Leon Scroggins6eac63e2010-03-15 18:19:14 -04004353 /* package */ static class UrlData {
Grace Kloba068e48b2010-01-26 18:11:27 -08004354 final String mUrl;
4355 final Map<String, String> mHeaders;
Leon Scroggins58d56c62010-01-28 15:12:40 -05004356 final Intent mVoiceIntent;
Grace Kloba60e095c2009-06-16 11:50:55 -07004357
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004358 UrlData(String url) {
4359 this.mUrl = url;
Grace Kloba068e48b2010-01-26 18:11:27 -08004360 this.mHeaders = null;
Leon Scroggins58d56c62010-01-28 15:12:40 -05004361 this.mVoiceIntent = null;
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004362 }
Grace Kloba60e095c2009-06-16 11:50:55 -07004363
Leon Scroggins58d56c62010-01-28 15:12:40 -05004364 UrlData(String url, Map<String, String> headers, Intent intent) {
Grace Kloba068e48b2010-01-26 18:11:27 -08004365 this.mUrl = url;
4366 this.mHeaders = headers;
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -05004367 if (RecognizerResultsIntent.ACTION_VOICE_SEARCH_RESULTS
4368 .equals(intent.getAction())) {
Leon Scroggins58d56c62010-01-28 15:12:40 -05004369 this.mVoiceIntent = intent;
4370 } else {
4371 this.mVoiceIntent = null;
4372 }
Grace Kloba60e095c2009-06-16 11:50:55 -07004373 }
4374
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004375 boolean isEmpty() {
Leon Scroggins58d56c62010-01-28 15:12:40 -05004376 return mVoiceIntent == null && (mUrl == null || mUrl.length() == 0);
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004377 }
4378
Leon Scroggins92472e82010-02-17 16:32:28 -05004379 /**
4380 * Load this UrlData into the given Tab. Use loadUrlDataIn to update
4381 * the title bar as well.
4382 */
Leon Scroggins58d56c62010-01-28 15:12:40 -05004383 public void loadIn(Tab t) {
4384 if (mVoiceIntent != null) {
4385 t.activateVoiceSearchMode(mVoiceIntent);
4386 } else {
4387 t.getWebView().loadUrl(mUrl, mHeaders);
4388 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004389 }
4390 };
4391
Leon Scroggins1f005d32009-08-10 17:36:42 -04004392 /* package */ static final UrlData EMPTY_URL_DATA = new UrlData(null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004393}