blob: e6cb4730fb04d338f9cdd4d1cbe30f59bbb919cd [file] [log] [blame]
The Android Open Source Project0c908882009-03-03 19:32:16 -08001/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.browser;
18
Michael Kolb3f65c382010-08-20 15:31:16 -070019import com.android.browser.ScrollWebView.ScrollListener;
20import com.android.common.Search;
21import com.android.common.speech.LoggingEvents;
22
Michael Kolbed217742010-08-10 17:52:34 -070023import android.app.ActionBar;
The Android Open Source Project0c908882009-03-03 19:32:16 -080024import android.app.Activity;
The Android Open Source Project0c908882009-03-03 19:32:16 -080025import android.app.AlertDialog;
Michael Kolbc7485ae2010-09-03 10:10:58 -070026import android.app.Dialog;
The Android Open Source Project0c908882009-03-03 19:32:16 -080027import android.app.ProgressDialog;
28import android.app.SearchManager;
29import android.content.ActivityNotFoundException;
30import android.content.BroadcastReceiver;
Dianne Hackborn80f32622010-08-05 14:17:53 -070031import android.content.ClipboardManager;
The Android Open Source Project0c908882009-03-03 19:32:16 -080032import android.content.ComponentName;
Leon Scroggins58d56c62010-01-28 15:12:40 -050033import android.content.ContentProvider;
34import android.content.ContentProviderClient;
The Android Open Source Project0c908882009-03-03 19:32:16 -080035import android.content.ContentResolver;
Leon Scrogginsb6b7f9e2009-06-18 12:05:28 -040036import android.content.ContentUris;
The Android Open Source Project0c908882009-03-03 19:32:16 -080037import android.content.ContentValues;
38import android.content.Context;
39import android.content.DialogInterface;
40import android.content.Intent;
41import android.content.IntentFilter;
The Android Open Source Project0c908882009-03-03 19:32:16 -080042import android.content.pm.PackageManager;
43import android.content.pm.ResolveInfo;
The Android Open Source Project0c908882009-03-03 19:32:16 -080044import android.content.res.Configuration;
45import android.content.res.Resources;
46import android.database.Cursor;
The Android Open Source Project0c908882009-03-03 19:32:16 -080047import android.graphics.Bitmap;
Andrei Popescu540035d2009-09-18 18:59:20 +010048import android.graphics.BitmapFactory;
The Android Open Source Project0c908882009-03-03 19:32:16 -080049import android.graphics.Canvas;
The Android Open Source Project0c908882009-03-03 19:32:16 -080050import android.graphics.Picture;
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -040051import android.graphics.PixelFormat;
The Android Open Source Project0c908882009-03-03 19:32:16 -080052import android.graphics.drawable.Drawable;
The Android Open Source Project0c908882009-03-03 19:32:16 -080053import android.net.ConnectivityManager;
Andrei Popescu56199cc2010-01-12 22:39:16 +000054import android.net.NetworkInfo;
The Android Open Source Project0c908882009-03-03 19:32:16 -080055import android.net.Uri;
56import android.net.WebAddress;
The Android Open Source Project0c908882009-03-03 19:32:16 -080057import android.net.http.SslCertificate;
58import android.net.http.SslError;
59import android.os.AsyncTask;
60import android.os.Bundle;
61import android.os.Debug;
62import android.os.Environment;
63import android.os.Handler;
The Android Open Source Project0c908882009-03-03 19:32:16 -080064import android.os.Message;
65import android.os.PowerManager;
66import android.os.Process;
The Android Open Source Project0c908882009-03-03 19:32:16 -080067import android.os.SystemClock;
The Android Open Source Project0c908882009-03-03 19:32:16 -080068import android.provider.Browser;
Jeff Hamilton8ce956c2010-08-17 11:13:53 -050069import android.provider.BrowserContract;
Cary Clark5e335a32009-09-22 14:53:11 -040070import android.provider.ContactsContract;
Michael Kolba2b2ba82010-08-04 17:54:03 -070071import android.provider.ContactsContract.Intents.Insert;
The Android Open Source Project0c908882009-03-03 19:32:16 -080072import android.provider.Downloads;
73import android.provider.MediaStore;
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -050074import android.speech.RecognizerResultsIntent;
The Android Open Source Project0c908882009-03-03 19:32:16 -080075import android.text.TextUtils;
76import android.text.format.DateFormat;
The Android Open Source Project0c908882009-03-03 19:32:16 -080077import android.util.Log;
Dianne Hackborn385effd2010-02-24 20:03:04 -080078import android.util.Patterns;
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -040079import android.view.ActionMode;
The Android Open Source Project0c908882009-03-03 19:32:16 -080080import android.view.ContextMenu;
Michael Kolba2b2ba82010-08-04 17:54:03 -070081import android.view.ContextMenu.ContextMenuInfo;
The Android Open Source Project0c908882009-03-03 19:32:16 -080082import android.view.Gravity;
83import android.view.KeyEvent;
84import android.view.LayoutInflater;
85import android.view.Menu;
86import android.view.MenuInflater;
87import android.view.MenuItem;
Michael Kolba2b2ba82010-08-04 17:54:03 -070088import android.view.MenuItem.OnMenuItemClickListener;
Michael Kolb3f65c382010-08-20 15:31:16 -070089import android.view.MotionEvent;
The Android Open Source Project0c908882009-03-03 19:32:16 -080090import android.view.View;
91import android.view.ViewGroup;
92import android.view.Window;
93import android.view.WindowManager;
Svetoslav Ganov2b345992010-05-06 06:13:54 -070094import android.view.accessibility.AccessibilityManager;
The Android Open Source Project0c908882009-03-03 19:32:16 -080095import android.webkit.CookieManager;
96import android.webkit.CookieSyncManager;
97import android.webkit.DownloadListener;
98import android.webkit.HttpAuthHandler;
99import android.webkit.SslErrorHandler;
100import android.webkit.URLUtil;
Leon Clarkecb6cc862009-09-29 18:35:13 +0100101import android.webkit.ValueCallback;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800102import android.webkit.WebChromeClient;
103import android.webkit.WebHistoryItem;
104import android.webkit.WebIconDatabase;
105import android.webkit.WebView;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800106import android.widget.EditText;
107import android.widget.FrameLayout;
108import android.widget.LinearLayout;
Michael Kolbc7485ae2010-09-03 10:10:58 -0700109import android.widget.PopupMenu;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800110import android.widget.TextView;
111import android.widget.Toast;
112
Leon Scrogginsb6b7f9e2009-06-18 12:05:28 -0400113import java.io.ByteArrayOutputStream;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800114import java.io.File;
Ben Murdoch4f75ba22009-10-27 11:48:28 +0000115import java.io.IOException;
116import java.io.InputStream;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800117import java.net.MalformedURLException;
Dianne Hackborn99189432009-06-17 18:06:18 -0700118import java.net.URISyntaxException;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800119import java.net.URL;
120import java.net.URLEncoder;
Elliott Slaughter3d6df162010-08-25 13:17:44 -0700121import java.util.Calendar;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800122import java.util.Date;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800123import java.util.HashMap;
Grace Kloba00f54c52010-01-27 14:53:51 -0800124import java.util.Iterator;
Grace Kloba068e48b2010-01-26 18:11:27 -0800125import java.util.Map;
Michael Kolbfe251992010-07-08 15:41:55 -0700126import java.util.Vector;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800127import java.util.regex.Matcher;
128import java.util.regex.Pattern;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800129
130public class BrowserActivity extends Activity
Michael Kolbc7485ae2010-09-03 10:10:58 -0700131 implements View.OnCreateContextMenuListener, DownloadListener,
132 PopupMenu.OnMenuItemClickListener {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800133
Dave Bort31a6d1c2009-04-13 15:56:49 -0700134 /* Define some aliases to make these debugging flags easier to refer to.
135 * This file imports android.provider.Browser, so we can't just refer to "Browser.DEBUG".
136 */
137 private final static boolean DEBUG = com.android.browser.Browser.DEBUG;
138 private final static boolean LOGV_ENABLED = com.android.browser.Browser.LOGV_ENABLED;
139 private final static boolean LOGD_ENABLED = com.android.browser.Browser.LOGD_ENABLED;
140
Satish Sampath565505b2009-05-29 15:37:27 +0100141 // These are single-character shortcuts for searching popular sources.
142 private static final int SHORTCUT_INVALID = 0;
143 private static final int SHORTCUT_GOOGLE_SEARCH = 1;
144 private static final int SHORTCUT_WIKIPEDIA_SEARCH = 2;
145 private static final int SHORTCUT_DICTIONARY_SEARCH = 3;
146 private static final int SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH = 4;
147
Cary Clarka9771242009-08-11 16:42:26 -0400148 private static class ClearThumbnails extends AsyncTask<File, Void, Void> {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800149 @Override
150 public Void doInBackground(File... files) {
151 if (files != null) {
152 for (File f : files) {
Cary Clarkd6be1752009-08-12 12:56:42 -0400153 if (!f.delete()) {
154 Log.e(LOGTAG, f.getPath() + " was not deleted");
155 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800156 }
157 }
158 return null;
159 }
160 }
161
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400162 /**
163 * This layout holds everything you see below the status bar, including the
164 * error console, the custom view container, and the webviews.
165 */
166 private FrameLayout mBrowserFrameLayout;
Leon Scroggins81db3662009-06-04 17:45:11 -0400167
Leon Scrogginsd746a942010-05-19 13:21:44 -0400168 private boolean mXLargeScreenSize;
169
Jeff Davidson43610292010-07-16 16:03:58 -0700170 private Boolean mIsProviderPresent = null;
171 private Uri mRlzUri = null;
172
Grace Kloba22ac16e2009-10-07 18:00:23 -0700173 @Override
174 public void onCreate(Bundle icicle) {
Dave Bort31a6d1c2009-04-13 15:56:49 -0700175 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800176 Log.v(LOGTAG, this + " onStart");
177 }
178 super.onCreate(icicle);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800179 // test the browser in OpenGL
180 // requestWindowFeature(Window.FEATURE_OPENGL);
181
Mike Reedd334bf52010-01-26 15:21:44 -0500182 // enable this to test the browser in 32bit
183 if (false) {
184 getWindow().setFormat(PixelFormat.RGBX_8888);
185 BitmapFactory.setDefaultConfig(Bitmap.Config.ARGB_8888);
186 }
187
Svetoslav Ganov2b345992010-05-06 06:13:54 -0700188 if (AccessibilityManager.getInstance(this).isEnabled()) {
189 setDefaultKeyMode(DEFAULT_KEYS_DISABLE);
190 } else {
191 setDefaultKeyMode(DEFAULT_KEYS_SEARCH_LOCAL);
192 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800193
194 mResolver = getContentResolver();
195
Grace Kloba0923d692009-09-23 21:37:25 -0700196 // If this was a web search request, pass it on to the default web
197 // search provider and finish this activity.
198 if (handleWebSearchIntent(getIntent())) {
199 finish();
200 return;
201 }
202
The Android Open Source Project0c908882009-03-03 19:32:16 -0800203 mSecLockIcon = Resources.getSystem().getDrawable(
204 android.R.drawable.ic_secure);
205 mMixLockIcon = Resources.getSystem().getDrawable(
206 android.R.drawable.ic_partial_secure);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800207
Michael Kolbed217742010-08-10 17:52:34 -0700208 // Create the tab control and our initial tab
209 mTabControl = new TabControl(this);
210
211 mXLargeScreenSize = (getResources().getConfiguration().screenLayout
212 & Configuration.SCREENLAYOUT_SIZE_MASK)
213 == Configuration.SCREENLAYOUT_SIZE_XLARGE;
214
Leon Scroggins81db3662009-06-04 17:45:11 -0400215 FrameLayout frameLayout = (FrameLayout) getWindow().getDecorView()
216 .findViewById(com.android.internal.R.id.content);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400217 mBrowserFrameLayout = (FrameLayout) LayoutInflater.from(this)
218 .inflate(R.layout.custom_screen, null);
219 mContentView = (FrameLayout) mBrowserFrameLayout.findViewById(
220 R.id.main_content);
221 mErrorConsoleContainer = (LinearLayout) mBrowserFrameLayout
222 .findViewById(R.id.error_console);
223 mCustomViewContainer = (FrameLayout) mBrowserFrameLayout
224 .findViewById(R.id.fullscreen_custom_content);
225 frameLayout.addView(mBrowserFrameLayout, COVER_SCREEN_PARAMS);
Michael Kolbe0a36662010-06-29 10:37:12 -0700226
Leon Scrogginsd746a942010-05-19 13:21:44 -0400227 if (mXLargeScreenSize) {
Michael Kolba2b2ba82010-08-04 17:54:03 -0700228 mTitleBar = new TitleBarXLarge(this);
229 mTitleBar.setProgress(100);
230 mFakeTitleBar = new TitleBarXLarge(this);
Michael Kolbed217742010-08-10 17:52:34 -0700231 ActionBar actionBar = getActionBar();
Michael Kolbc7485ae2010-09-03 10:10:58 -0700232 actionBar.setBackgroundDrawable(getResources().
233 getDrawable(R.drawable.tabbar_bg));
Michael Kolba2b2ba82010-08-04 17:54:03 -0700234 mTabBar = new TabBar(this, mTabControl, (TitleBarXLarge) mFakeTitleBar);
Michael Kolbed217742010-08-10 17:52:34 -0700235 actionBar.setCustomNavigationMode(mTabBar);
Michael Kolb68775752010-08-19 12:42:01 -0700236 // disable built in zoom controls
237 mTabControl.setDisplayZoomControls(false);
Leon Scrogginsd746a942010-05-19 13:21:44 -0400238 } else {
Leon Scroggins571b3762010-05-26 10:25:01 -0400239 mTitleBar = new TitleBar(this);
Leon Scrogginsd746a942010-05-19 13:21:44 -0400240 // mTitleBar will be always be shown in the fully loaded mode on
241 // phone
242 mTitleBar.setProgress(100);
Leon Scrogginsd746a942010-05-19 13:21:44 -0400243 mFakeTitleBar = new TitleBar(this);
244 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800245
The Android Open Source Project0c908882009-03-03 19:32:16 -0800246 // Open the icon database and retain all the bookmark urls for favicons
247 retainIconsOnStartup();
248
249 // Keep a settings instance handy.
250 mSettings = BrowserSettings.getInstance();
251 mSettings.setTabControl(mTabControl);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800252
253 PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
254 mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Browser");
255
Patrick Scott6adacc92010-03-05 08:24:51 -0500256 // Find out if the network is currently up.
257 ConnectivityManager cm = (ConnectivityManager) getSystemService(
258 Context.CONNECTIVITY_SERVICE);
259 NetworkInfo info = cm.getActiveNetworkInfo();
260 if (info != null) {
261 mIsNetworkUp = info.isAvailable();
262 }
263
Grace Klobaa34f6862009-07-31 16:28:17 -0700264 /* enables registration for changes in network status from
265 http stack */
266 mNetworkStateChangedFilter = new IntentFilter();
267 mNetworkStateChangedFilter.addAction(
268 ConnectivityManager.CONNECTIVITY_ACTION);
269 mNetworkStateIntentReceiver = new BroadcastReceiver() {
270 @Override
271 public void onReceive(Context context, Intent intent) {
272 if (intent.getAction().equals(
273 ConnectivityManager.CONNECTIVITY_ACTION)) {
Andrei Popescue4c98462010-02-19 15:44:13 +0000274
275 NetworkInfo info = intent.getParcelableExtra(
276 ConnectivityManager.EXTRA_NETWORK_INFO);
277 String typeName = info.getTypeName();
278 String subtypeName = info.getSubtypeName();
279 sendNetworkType(typeName.toLowerCase(),
280 (subtypeName != null ? subtypeName.toLowerCase() : ""));
281
282 onNetworkToggle(info.isAvailable());
Grace Klobaa34f6862009-07-31 16:28:17 -0700283 }
284 }
285 };
286
Elliott Slaughter3d6df162010-08-25 13:17:44 -0700287 // Unless the last browser usage was within 24 hours, destroy any
288 // remaining incognito tabs.
289
290 Calendar lastActiveDate = icicle != null ? (Calendar) icicle.getSerializable("lastActiveDate") : null;
291 Calendar today = Calendar.getInstance();
292 Calendar yesterday = Calendar.getInstance();
293 yesterday.add(Calendar.DATE, -1);
294
295 boolean dontRestoreIncognitoTabs = lastActiveDate == null
296 || lastActiveDate.before(yesterday)
297 || lastActiveDate.after(today);
298
299 if (!mTabControl.restoreState(icicle, dontRestoreIncognitoTabs)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800300 // clear up the thumbnail directory if we can't restore the state as
301 // none of the files in the directory are referenced any more.
302 new ClearThumbnails().execute(
303 mTabControl.getThumbnailDir().listFiles());
Grace Klobaaab3f092009-07-30 12:29:51 -0700304 // there is no quit on Android. But if we can't restore the state,
305 // we can treat it as a new Browser, remove the old session cookies.
306 CookieManager.getInstance().removeSessionCookie();
Elliott Slaughter3d6df162010-08-25 13:17:44 -0700307 // remove any incognito files
308 WebView.cleanupPrivateBrowsingFiles(this);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800309 final Intent intent = getIntent();
310 final Bundle extra = intent.getExtras();
311 // Create an initial tab.
312 // If the intent is ACTION_VIEW and data is not null, the Browser is
313 // invoked to view the content by another application. In this case,
314 // the tab will be close when exit.
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700315 UrlData urlData = getUrlDataFromIntent(intent);
316
Leon Scroggins58d56c62010-01-28 15:12:40 -0500317 String action = intent.getAction();
Grace Kloba22ac16e2009-10-07 18:00:23 -0700318 final Tab t = mTabControl.createNewTab(
Leon Scroggins58d56c62010-01-28 15:12:40 -0500319 (Intent.ACTION_VIEW.equals(action) &&
320 intent.getData() != null)
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -0500321 || RecognizerResultsIntent.ACTION_VOICE_SEARCH_RESULTS
322 .equals(action),
Elliott Slaughterf0f03952010-07-14 18:10:36 -0700323 intent.getStringExtra(Browser.EXTRA_APPLICATION_ID),
324 urlData.mUrl, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800325 mTabControl.setCurrentTab(t);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800326 attachTabToContentView(t);
327 WebView webView = t.getWebView();
328 if (extra != null) {
329 int scale = extra.getInt(Browser.INITIAL_ZOOM_LEVEL, 0);
330 if (scale > 0 && scale <= 1000) {
331 webView.setInitialScale(scale);
332 }
333 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800334
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700335 if (urlData.isEmpty()) {
Shimeng (Simon) Wang98d5fce2010-03-16 13:23:39 -0700336 loadUrl(webView, mSettings.getHomePage());
The Android Open Source Project0c908882009-03-03 19:32:16 -0800337 } else {
Patrick Scott9d53da02010-02-19 10:19:01 -0500338 loadUrlDataIn(t, urlData);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800339 }
340 } else {
Elliott Slaughter3d6df162010-08-25 13:17:44 -0700341 if (dontRestoreIncognitoTabs) {
342 WebView.cleanupPrivateBrowsingFiles(this);
343 }
344
The Android Open Source Project0c908882009-03-03 19:32:16 -0800345 // TabControl.restoreState() will create a new tab even if
Leon Scroggins1f005d32009-08-10 17:36:42 -0400346 // restoring the state fails.
The Android Open Source Project0c908882009-03-03 19:32:16 -0800347 attachTabToContentView(mTabControl.getCurrentTab());
348 }
Grace Kloba615c6c92009-08-03 10:22:44 -0700349
Cary Clarkb4b83182010-07-01 12:36:56 -0400350 // Delete old thumbnails to save space
351 File dir = mTabControl.getThumbnailDir();
352 if (dir.exists()) {
353 for (String child : dir.list()) {
354 File f = new File(dir, child);
355 f.delete();
356 }
357 }
358
Feng Qianb3c02da2009-06-29 15:58:08 -0700359 // Read JavaScript flags if it exists.
360 String jsFlags = mSettings.getJsFlags();
361 if (jsFlags.trim().length() != 0) {
362 mTabControl.getCurrentWebView().setJsFlags(jsFlags);
363 }
Bjorn Bringerta7611812010-03-24 11:12:02 +0000364
365 // Start watching the default geolocation permissions
366 mSystemAllowGeolocationOrigins
367 = new SystemAllowGeolocationOrigins(getApplicationContext());
368 mSystemAllowGeolocationOrigins.start();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800369 }
370
Michael Kolba2b2ba82010-08-04 17:54:03 -0700371 ScrollListener getScrollListener() {
372 return mTabBar;
373 }
374
Leon Scroggins58d56c62010-01-28 15:12:40 -0500375 /**
376 * Feed the previously stored results strings to the BrowserProvider so that
377 * the SearchDialog will show them instead of the standard searches.
378 * @param result String to show on the editable line of the SearchDialog.
379 */
380 /* package */ void showVoiceSearchResults(String result) {
381 ContentProviderClient client = mResolver.acquireContentProviderClient(
382 Browser.BOOKMARKS_URI);
383 ContentProvider prov = client.getLocalContentProvider();
384 BrowserProvider bp = (BrowserProvider) prov;
385 bp.setQueryResults(mTabControl.getCurrentTab().getVoiceSearchResults());
386 client.release();
387
Leon Scrogginsfbb3f152010-03-09 17:26:56 -0500388 Bundle bundle = createGoogleSearchSourceBundle(
389 GOOGLE_SEARCH_SOURCE_SEARCHKEY);
390 bundle.putBoolean(SearchManager.CONTEXT_IS_VOICE, true);
391 startSearch(result, false, bundle, false);
Leon Scroggins58d56c62010-01-28 15:12:40 -0500392 }
393
The Android Open Source Project0c908882009-03-03 19:32:16 -0800394 @Override
395 protected void onNewIntent(Intent intent) {
Grace Kloba22ac16e2009-10-07 18:00:23 -0700396 Tab current = mTabControl.getCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800397 // When a tab is closed on exit, the current tab index is set to -1.
398 // Reset before proceed as Browser requires the current tab to be set.
399 if (current == null) {
400 // Try to reset the tab in case the index was incorrect.
401 current = mTabControl.getTab(0);
402 if (current == null) {
403 // No tabs at all so just ignore this intent.
404 return;
405 }
406 mTabControl.setCurrentTab(current);
407 attachTabToContentView(current);
408 resetTitleAndIcon(current.getWebView());
409 }
410 final String action = intent.getAction();
411 final int flags = intent.getFlags();
412 if (Intent.ACTION_MAIN.equals(action) ||
413 (flags & Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY) != 0) {
414 // just resume the browser
415 return;
416 }
Leon Scrogginsb8a844d2010-03-18 15:06:15 -0400417 // In case the SearchDialog is open.
418 ((SearchManager) getSystemService(Context.SEARCH_SERVICE))
419 .stopSearch();
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -0500420 boolean activateVoiceSearch = RecognizerResultsIntent
421 .ACTION_VOICE_SEARCH_RESULTS.equals(action);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800422 if (Intent.ACTION_VIEW.equals(action)
423 || Intent.ACTION_SEARCH.equals(action)
424 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
Leon Scroggins58d56c62010-01-28 15:12:40 -0500425 || Intent.ACTION_WEB_SEARCH.equals(action)
426 || activateVoiceSearch) {
Leon Scroggins3b18ce32010-02-08 17:35:59 -0500427 if (current.isInVoiceSearchMode()) {
428 String title = current.getVoiceDisplayTitle();
429 if (title != null && title.equals(intent.getStringExtra(
430 SearchManager.QUERY))) {
431 // The user submitted the same search as the last voice
432 // search, so do nothing.
433 return;
434 }
Leon Scroggins1fe13a52010-02-09 15:31:26 -0500435 if (Intent.ACTION_SEARCH.equals(action)
436 && current.voiceSearchSourceIsGoogle()) {
437 Intent logIntent = new Intent(
438 LoggingEvents.ACTION_LOG_EVENT);
439 logIntent.putExtra(LoggingEvents.EXTRA_EVENT,
440 LoggingEvents.VoiceSearch.QUERY_UPDATED);
441 logIntent.putExtra(
442 LoggingEvents.VoiceSearch.EXTRA_QUERY_UPDATED_VALUE,
443 intent.getDataString());
444 sendBroadcast(logIntent);
445 // Note, onPageStarted will revert the voice title bar
446 // When http://b/issue?id=2379215 is fixed, we should update
447 // the title bar here.
448 }
Leon Scroggins3b18ce32010-02-08 17:35:59 -0500449 }
Satish Sampath565505b2009-05-29 15:37:27 +0100450 // If this was a search request (e.g. search query directly typed into the address bar),
451 // pass it on to the default web search provider.
452 if (handleWebSearchIntent(intent)) {
453 return;
454 }
455
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700456 UrlData urlData = getUrlDataFromIntent(intent);
457 if (urlData.isEmpty()) {
458 urlData = new UrlData(mSettings.getHomePage());
The Android Open Source Project0c908882009-03-03 19:32:16 -0800459 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700460
Grace Klobacc634032009-07-28 15:58:19 -0700461 final String appId = intent
462 .getStringExtra(Browser.EXTRA_APPLICATION_ID);
Leon Scroggins47208682010-04-07 17:59:48 -0400463 if ((Intent.ACTION_VIEW.equals(action)
464 // If a voice search has no appId, it means that it came
465 // from the browser. In that case, reuse the current tab.
466 || (activateVoiceSearch && appId != null))
Grace Klobacc634032009-07-28 15:58:19 -0700467 && !getPackageName().equals(appId)
468 && (flags & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0) {
Grace Kloba22ac16e2009-10-07 18:00:23 -0700469 Tab appTab = mTabControl.getTabFromId(appId);
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700470 if (appTab != null) {
471 Log.i(LOGTAG, "Reusing tab for " + appId);
472 // Dismiss the subwindow if applicable.
473 dismissSubWindow(appTab);
474 // Since we might kill the WebView, remove it from the
475 // content view first.
476 removeTabFromContentView(appTab);
477 // Recreate the main WebView after destroying the old one.
478 // If the WebView has the same original url and is on that
479 // page, it can be reused.
480 boolean needsLoad =
Leon Scroggins6eac63e2010-03-15 18:19:14 -0400481 mTabControl.recreateWebView(appTab, urlData);
Ben Murdochbff2d602009-07-01 20:19:05 +0100482
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700483 if (current != appTab) {
Leon Scroggins1f005d32009-08-10 17:36:42 -0400484 switchToTab(mTabControl.getTabIndex(appTab));
485 if (needsLoad) {
Patrick Scott9d53da02010-02-19 10:19:01 -0500486 loadUrlDataIn(appTab, urlData);
Leon Scroggins1f005d32009-08-10 17:36:42 -0400487 }
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700488 } else {
Leon Scroggins1f005d32009-08-10 17:36:42 -0400489 // If the tab was the current tab, we have to attach
490 // it to the view system again.
491 attachTabToContentView(appTab);
492 if (needsLoad) {
Patrick Scott9d53da02010-02-19 10:19:01 -0500493 loadUrlDataIn(appTab, urlData);
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700494 }
495 }
496 return;
Patrick Scottcd115892009-07-16 09:42:58 -0400497 } else {
498 // No matching application tab, try to find a regular tab
499 // with a matching url.
500 appTab = mTabControl.findUnusedTabWithUrl(urlData.mUrl);
Leon Scroggins25515f82009-08-19 15:31:58 -0400501 if (appTab != null) {
502 if (current != appTab) {
503 switchToTab(mTabControl.getTabIndex(appTab));
504 }
505 // Otherwise, we are already viewing the correct tab.
Patrick Scottcd115892009-07-16 09:42:58 -0400506 } else {
507 // if FLAG_ACTIVITY_BROUGHT_TO_FRONT flag is on, the url
508 // will be opened in a new tab unless we have reached
509 // MAX_TABS. Then the url will be opened in the current
510 // tab. If a new tab is created, it will have "true" for
511 // exit on close.
Leon Scroggins1f005d32009-08-10 17:36:42 -0400512 openTabAndShow(urlData, true, appId);
Patrick Scottcd115892009-07-16 09:42:58 -0400513 }
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700514 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800515 } else {
Grace Kloba638d3f42009-11-23 10:35:04 -0800516 if (!urlData.isEmpty()
517 && urlData.mUrl.startsWith("about:debug")) {
518 if ("about:debug.dom".equals(urlData.mUrl)) {
519 current.getWebView().dumpDomTree(false);
520 } else if ("about:debug.dom.file".equals(urlData.mUrl)) {
521 current.getWebView().dumpDomTree(true);
522 } else if ("about:debug.render".equals(urlData.mUrl)) {
523 current.getWebView().dumpRenderTree(false);
524 } else if ("about:debug.render.file".equals(urlData.mUrl)) {
525 current.getWebView().dumpRenderTree(true);
526 } else if ("about:debug.display".equals(urlData.mUrl)) {
527 current.getWebView().dumpDisplayTree();
Mike Reed9b78e1d2010-01-13 14:40:52 -0800528 } else if (urlData.mUrl.startsWith("about:debug.drag")) {
529 int index = urlData.mUrl.codePointAt(16) - '0';
530 if (index <= 0 || index > 9) {
531 current.getWebView().setDragTracker(null);
532 } else {
533 current.getWebView().setDragTracker(new MeshTracker(index));
534 }
Grace Kloba638d3f42009-11-23 10:35:04 -0800535 } else {
536 mSettings.toggleDebugSettings();
537 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800538 return;
539 }
Leon Scroggins1f005d32009-08-10 17:36:42 -0400540 // Get rid of the subwindow if it exists
541 dismissSubWindow(current);
Leon Scroggins8588d152010-04-15 11:01:53 -0400542 // If the current Tab is being used as an application tab,
543 // remove the association, since the new Intent means that it is
544 // no longer associated with that application.
545 current.setAppId(null);
Patrick Scott9d53da02010-02-19 10:19:01 -0500546 loadUrlDataIn(current, urlData);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800547 }
548 }
549 }
550
Satish Sampath565505b2009-05-29 15:37:27 +0100551 private int parseUrlShortcut(String url) {
552 if (url == null) return SHORTCUT_INVALID;
553
554 // FIXME: quick search, need to be customized by setting
555 if (url.length() > 2 && url.charAt(1) == ' ') {
556 switch (url.charAt(0)) {
557 case 'g': return SHORTCUT_GOOGLE_SEARCH;
558 case 'w': return SHORTCUT_WIKIPEDIA_SEARCH;
559 case 'd': return SHORTCUT_DICTIONARY_SEARCH;
560 case 'l': return SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH;
561 }
562 }
563 return SHORTCUT_INVALID;
564 }
565
566 /**
567 * Launches the default web search activity with the query parameters if the given intent's data
568 * are identified as plain search terms and not URLs/shortcuts.
569 * @return true if the intent was handled and web search activity was launched, false if not.
570 */
571 private boolean handleWebSearchIntent(Intent intent) {
572 if (intent == null) return false;
573
574 String url = null;
575 final String action = intent.getAction();
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -0500576 if (RecognizerResultsIntent.ACTION_VOICE_SEARCH_RESULTS.equals(
577 action)) {
Leon Scroggins58d56c62010-01-28 15:12:40 -0500578 return false;
579 }
Satish Sampath565505b2009-05-29 15:37:27 +0100580 if (Intent.ACTION_VIEW.equals(action)) {
Grace Kloba1e705052009-09-29 13:13:36 -0700581 Uri data = intent.getData();
582 if (data != null) url = data.toString();
Satish Sampath565505b2009-05-29 15:37:27 +0100583 } else if (Intent.ACTION_SEARCH.equals(action)
584 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
585 || Intent.ACTION_WEB_SEARCH.equals(action)) {
586 url = intent.getStringExtra(SearchManager.QUERY);
587 }
Bjorn Bringert04851702009-09-22 10:36:01 +0100588 return handleWebSearchRequest(url, intent.getBundleExtra(SearchManager.APP_DATA),
589 intent.getStringExtra(SearchManager.EXTRA_DATA_KEY));
Satish Sampath565505b2009-05-29 15:37:27 +0100590 }
591
592 /**
593 * Launches the default web search activity with the query parameters if the given url string
594 * was identified as plain search terms and not URL/shortcut.
595 * @return true if the request was handled and web search activity was launched, false if not.
596 */
Bjorn Bringert04851702009-09-22 10:36:01 +0100597 private boolean handleWebSearchRequest(String inUrl, Bundle appData, String extraData) {
Satish Sampath565505b2009-05-29 15:37:27 +0100598 if (inUrl == null) return false;
599
600 // In general, we shouldn't modify URL from Intent.
601 // But currently, we get the user-typed URL from search box as well.
602 String url = fixUrl(inUrl).trim();
603
604 // URLs and site specific search shortcuts are handled by the regular flow of control, so
605 // return early.
Dan Egnor5ee906c2009-11-18 12:11:49 -0800606 if (Patterns.WEB_URL.matcher(url).matches()
Satish Sampathbc5b9f32009-06-04 18:21:40 +0100607 || ACCEPTED_URI_SCHEMA.matcher(url).matches()
Satish Sampath565505b2009-05-29 15:37:27 +0100608 || parseUrlShortcut(url) != SHORTCUT_INVALID) {
609 return false;
610 }
611
Leon Scroggins8d06e362010-03-24 14:45:57 -0400612 final ContentResolver cr = mResolver;
613 final String newUrl = url;
Elliott Slaughter627d96f2010-08-18 16:35:30 -0700614 if (mTabControl == null || !mTabControl.getCurrentWebView().isPrivateBrowsingEnabled()) {
Elliott Slaughterf0f03952010-07-14 18:10:36 -0700615 new AsyncTask<Void, Void, Void>() {
616 @Override
617 protected Void doInBackground(Void... unused) {
618 Browser.updateVisitedHistory(cr, newUrl, false);
619 Browser.addSearchUrl(cr, newUrl);
620 return null;
621 }
622 }.execute();
623 }
Satish Sampath565505b2009-05-29 15:37:27 +0100624
625 Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);
626 intent.addCategory(Intent.CATEGORY_DEFAULT);
627 intent.putExtra(SearchManager.QUERY, url);
Satish Sampath15e9f2d2009-06-23 22:29:49 +0100628 if (appData != null) {
629 intent.putExtra(SearchManager.APP_DATA, appData);
630 }
Bjorn Bringert04851702009-09-22 10:36:01 +0100631 if (extraData != null) {
632 intent.putExtra(SearchManager.EXTRA_DATA_KEY, extraData);
633 }
Grace Klobacc634032009-07-28 15:58:19 -0700634 intent.putExtra(Browser.EXTRA_APPLICATION_ID, getPackageName());
Mattias Falk552751e2010-08-23 12:03:57 +0200635
636 // can't be sure there is an activity for the Intent
637 try {
638 startActivity(intent);
639 } catch (ActivityNotFoundException ex) {
640 return false;
641 }
Satish Sampath565505b2009-05-29 15:37:27 +0100642
643 return true;
644 }
645
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700646 private UrlData getUrlDataFromIntent(Intent intent) {
Leon Scroggins58d56c62010-01-28 15:12:40 -0500647 String url = "";
Grace Kloba068e48b2010-01-26 18:11:27 -0800648 Map<String, String> headers = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800649 if (intent != null) {
650 final String action = intent.getAction();
651 if (Intent.ACTION_VIEW.equals(action)) {
652 url = smartUrlFilter(intent.getData());
653 if (url != null && url.startsWith("content:")) {
654 /* Append mimetype so webview knows how to display */
655 String mimeType = intent.resolveType(getContentResolver());
656 if (mimeType != null) {
657 url += "?" + mimeType;
658 }
659 }
Grace Kloba068e48b2010-01-26 18:11:27 -0800660 if (url != null && url.startsWith("http")) {
Grace Kloba00f54c52010-01-27 14:53:51 -0800661 final Bundle pairs = intent
662 .getBundleExtra(Browser.EXTRA_HEADERS);
Grace Kloba2d508ed2010-01-28 11:39:15 -0800663 if (pairs != null && !pairs.isEmpty()) {
Grace Kloba00f54c52010-01-27 14:53:51 -0800664 Iterator<String> iter = pairs.keySet().iterator();
Grace Kloba068e48b2010-01-26 18:11:27 -0800665 headers = new HashMap<String, String>();
Grace Kloba00f54c52010-01-27 14:53:51 -0800666 while (iter.hasNext()) {
667 String key = iter.next();
668 headers.put(key, pairs.getString(key));
Grace Kloba068e48b2010-01-26 18:11:27 -0800669 }
670 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700671 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800672 } else if (Intent.ACTION_SEARCH.equals(action)
673 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
674 || Intent.ACTION_WEB_SEARCH.equals(action)) {
675 url = intent.getStringExtra(SearchManager.QUERY);
676 if (url != null) {
677 mLastEnteredUrl = url;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800678 // In general, we shouldn't modify URL from Intent.
679 // But currently, we get the user-typed URL from search box as well.
680 url = fixUrl(url);
681 url = smartUrlFilter(url);
Leon Scroggins8d06e362010-03-24 14:45:57 -0400682 final ContentResolver cr = mResolver;
683 final String newUrl = url;
Elliott Slaughter8389e992010-08-20 15:44:08 -0700684 if (mTabControl == null
685 || mTabControl.getCurrentWebView() == null
686 || !mTabControl.getCurrentWebView().isPrivateBrowsingEnabled()) {
687 new AsyncTask<Void, Void, Void>() {
688 @Override
689 protected Void doInBackground(Void... unused) {
690 Browser.updateVisitedHistory(cr, newUrl, false);
691 return null;
692 }
693 }.execute();
694 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800695 String searchSource = "&source=android-" + GOOGLE_SEARCH_SOURCE_SUGGEST + "&";
696 if (url.contains(searchSource)) {
697 String source = null;
698 final Bundle appData = intent.getBundleExtra(SearchManager.APP_DATA);
699 if (appData != null) {
Bjorn Bringert10d1cca2010-02-10 14:22:12 +0000700 source = appData.getString(Search.SOURCE);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800701 }
702 if (TextUtils.isEmpty(source)) {
703 source = GOOGLE_SEARCH_SOURCE_UNKNOWN;
704 }
705 url = url.replace(searchSource, "&source=android-"+source+"&");
706 }
707 }
708 }
709 }
Leon Scroggins58d56c62010-01-28 15:12:40 -0500710 return new UrlData(url, headers, intent);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800711 }
Leon Scroggins58d56c62010-01-28 15:12:40 -0500712 /* package */ void showVoiceTitleBar(String title) {
713 mTitleBar.setInVoiceMode(true);
Leon Scroggins58d56c62010-01-28 15:12:40 -0500714 mTitleBar.setDisplayTitle(title);
Michael Kolba2b2ba82010-08-04 17:54:03 -0700715 mFakeTitleBar.setInVoiceMode(true);
716 mFakeTitleBar.setDisplayTitle(title);
Leon Scroggins58d56c62010-01-28 15:12:40 -0500717 }
718 /* package */ void revertVoiceTitleBar() {
719 mTitleBar.setInVoiceMode(false);
Leon Scroggins003a5dd2010-03-10 12:13:14 -0500720 mTitleBar.setDisplayTitle(mUrl);
Michael Kolba2b2ba82010-08-04 17:54:03 -0700721 mFakeTitleBar.setInVoiceMode(false);
722 mFakeTitleBar.setDisplayTitle(mUrl);
Leon Scroggins58d56c62010-01-28 15:12:40 -0500723 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800724 /* package */ static String fixUrl(String inUrl) {
Cary Clark652ff872009-09-10 13:34:44 -0400725 // FIXME: Converting the url to lower case
726 // duplicates functionality in smartUrlFilter().
727 // However, changing all current callers of fixUrl to
728 // call smartUrlFilter in addition may have unwanted
729 // consequences, and is deferred for now.
730 int colon = inUrl.indexOf(':');
731 boolean allLower = true;
732 for (int index = 0; index < colon; index++) {
733 char ch = inUrl.charAt(index);
734 if (!Character.isLetter(ch)) {
735 break;
736 }
737 allLower &= Character.isLowerCase(ch);
738 if (index == colon - 1 && !allLower) {
739 inUrl = inUrl.substring(0, colon).toLowerCase()
740 + inUrl.substring(colon);
741 }
742 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800743 if (inUrl.startsWith("http://") || inUrl.startsWith("https://"))
744 return inUrl;
745 if (inUrl.startsWith("http:") ||
746 inUrl.startsWith("https:")) {
747 if (inUrl.startsWith("http:/") || inUrl.startsWith("https:/")) {
748 inUrl = inUrl.replaceFirst("/", "//");
749 } else inUrl = inUrl.replaceFirst(":", "://");
750 }
751 return inUrl;
752 }
753
Grace Kloba22ac16e2009-10-07 18:00:23 -0700754 @Override
755 protected void onResume() {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800756 super.onResume();
Dave Bort31a6d1c2009-04-13 15:56:49 -0700757 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800758 Log.v(LOGTAG, "BrowserActivity.onResume: this=" + this);
759 }
760
761 if (!mActivityInPause) {
762 Log.e(LOGTAG, "BrowserActivity is already resumed.");
763 return;
764 }
765
Mike Reed7bfa63b2009-05-28 11:08:32 -0400766 mTabControl.resumeCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800767 mActivityInPause = false;
Mike Reed7bfa63b2009-05-28 11:08:32 -0400768 resumeWebViewTimers();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800769
770 if (mWakeLock.isHeld()) {
771 mHandler.removeMessages(RELEASE_WAKELOCK);
772 mWakeLock.release();
773 }
774
The Android Open Source Project0c908882009-03-03 19:32:16 -0800775 registerReceiver(mNetworkStateIntentReceiver,
776 mNetworkStateChangedFilter);
777 WebView.enablePlatformNotifications();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800778 }
779
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400780 /**
781 * Since the actual title bar is embedded in the WebView, and removing it
Leon Scrogginsfe87bd32009-10-06 10:10:00 -0400782 * would change its appearance, use a different TitleBar to show overlayed
783 * at the top of the screen, when the menu is open or the page is loading.
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400784 */
Michael Kolba2b2ba82010-08-04 17:54:03 -0700785 private TitleBarBase mFakeTitleBar;
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400786
787 /**
788 * Keeps track of whether the options menu is open. This is important in
789 * determining whether to show or hide the title bar overlay.
790 */
791 private boolean mOptionsMenuOpen;
792
793 /**
794 * Only meaningful when mOptionsMenuOpen is true. This variable keeps track
795 * of whether the configuration has changed. The first onMenuOpened call
796 * after a configuration change is simply a reopening of the same menu
797 * (i.e. mIconView did not change).
798 */
799 private boolean mConfigChanged;
800
801 /**
802 * Whether or not the options menu is in its smaller, icon menu form. When
803 * true, we want the title bar overlay to be up. When false, we do not.
804 * Only meaningful if mOptionsMenuOpen is true.
805 */
806 private boolean mIconView;
807
Leon Scrogginsa81a7642009-08-31 17:05:41 -0400808 @Override
809 public boolean onMenuOpened(int featureId, Menu menu) {
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400810 if (Window.FEATURE_OPTIONS_PANEL == featureId) {
811 if (mOptionsMenuOpen) {
812 if (mConfigChanged) {
813 // We do not need to make any changes to the state of the
814 // title bar, since the only thing that happened was a
815 // change in orientation
816 mConfigChanged = false;
817 } else {
818 if (mIconView) {
819 // Switching the menu to expanded view, so hide the
820 // title bar.
821 hideFakeTitleBar();
822 mIconView = false;
823 } else {
824 // Switching the menu back to icon view, so show the
825 // title bar once again.
826 showFakeTitleBar();
827 mIconView = true;
828 }
829 }
830 } else {
831 // The options menu is closed, so open it, and show the title
832 showFakeTitleBar();
833 mOptionsMenuOpen = true;
834 mConfigChanged = false;
835 mIconView = true;
836 }
837 }
Leon Scrogginsa81a7642009-08-31 17:05:41 -0400838 return true;
839 }
840
Michael Kolba2b2ba82010-08-04 17:54:03 -0700841 void showFakeTitleBar() {
842 if (!isFakeTitleBarShowing() && mActiveTabsPage == null && !mActivityInPause) {
Grace Kloba847c25b2010-03-30 16:00:26 -0700843 WebView mainView = mTabControl.getCurrentWebView();
844 // if there is no current WebView, don't show the faked title bar;
Grace Kloba65190702010-04-02 23:37:26 -0700845 if (mainView == null) {
Cary Clarka0464552009-09-29 13:00:45 -0400846 return;
847 }
Leon Scroggins79e36d92010-04-29 16:01:46 +0100848 // Do not need to check for null, since the current tab will have
849 // at least a main WebView, or we would have returned above.
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -0400850 if (isInCustomActionMode()) {
851 // Do not show the fake title bar, while a custom ActionMode
852 // (i.e. find or select) is showing.
Leon Scroggins79e36d92010-04-29 16:01:46 +0100853 return;
854 }
Michael Kolba2b2ba82010-08-04 17:54:03 -0700855 if (mXLargeScreenSize) {
856 mContentView.addView(mFakeTitleBar);
857 mTabBar.onShowTitleBar();
858 } else {
859 WindowManager manager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400860
Michael Kolba2b2ba82010-08-04 17:54:03 -0700861 // Add the title bar to the window manager so it can receive
862 // touches
863 // while the menu is up
864 WindowManager.LayoutParams params =
865 new WindowManager.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
866 ViewGroup.LayoutParams.WRAP_CONTENT,
867 WindowManager.LayoutParams.TYPE_APPLICATION,
868 WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
869 PixelFormat.TRANSLUCENT);
870 params.gravity = Gravity.TOP;
871 boolean atTop = mainView.getScrollY() == 0;
872 params.windowAnimations = atTop ? 0 : R.style.TitleBar;
873 manager.addView(mFakeTitleBar, params);
874 }
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400875 }
876 }
877
878 @Override
879 public void onOptionsMenuClosed(Menu menu) {
880 mOptionsMenuOpen = false;
Leon Scrogginsa27ff192009-09-14 12:58:04 -0400881 if (!mInLoad) {
882 hideFakeTitleBar();
883 } else if (!mIconView) {
884 // The page is currently loading, and we are in expanded mode, so
885 // we were not showing the menu. Show it once again. It will be
886 // removed when the page finishes.
887 showFakeTitleBar();
888 }
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400889 }
Grace Kloba22ac16e2009-10-07 18:00:23 -0700890
Michael Kolba2b2ba82010-08-04 17:54:03 -0700891 void stopScrolling() {
892 ((ScrollWebView) mTabControl.getCurrentWebView()).stopScroll();
893 }
894
895 void hideFakeTitleBar() {
896 if (!isFakeTitleBarShowing()) return;
897 if (mXLargeScreenSize) {
898 mContentView.removeView(mFakeTitleBar);
899 mTabBar.onHideTitleBar();
900 } else {
901 WindowManager.LayoutParams params =
902 (WindowManager.LayoutParams) mFakeTitleBar.getLayoutParams();
903 WebView mainView = mTabControl.getCurrentWebView();
904 // Although we decided whether or not to animate based on the
905 // current
906 // scroll position, the scroll position may have changed since the
907 // fake title bar was displayed. Make sure it has the appropriate
908 // animation/lack thereof before removing.
909 params.windowAnimations =
910 mainView != null && mainView.getScrollY() == 0 ? 0 : R.style.TitleBar;
911 WindowManager manager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
912 manager.updateViewLayout(mFakeTitleBar, params);
913 manager.removeView(mFakeTitleBar);
914 }
915 }
916
917 boolean isFakeTitleBarShowing() {
918 return (mFakeTitleBar.getParent() != null);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400919 }
920
The Android Open Source Project0c908882009-03-03 19:32:16 -0800921 /**
Leon Scrogginsc6fa1102009-09-21 10:40:01 -0400922 * Special method for the fake title bar to call when displaying its context
923 * menu, since it is in its own Window, and its parent does not show a
924 * context menu.
925 */
926 /* package */ void showTitleBarContextMenu() {
Cary Clark65f4a3c2009-09-28 17:05:06 -0400927 if (null == mTitleBar.getParent()) {
928 return;
929 }
Leon Scrogginsc6fa1102009-09-21 10:40:01 -0400930 openContextMenu(mTitleBar);
931 }
932
Leon Scrogginsb2b19f52009-10-09 16:10:00 -0400933 @Override
934 public void onContextMenuClosed(Menu menu) {
935 super.onContextMenuClosed(menu);
936 if (mInLoad) {
937 showFakeTitleBar();
938 }
939 }
940
Leon Scrogginsc6fa1102009-09-21 10:40:01 -0400941 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -0800942 * onSaveInstanceState(Bundle map)
943 * onSaveInstanceState is called right before onStop(). The map contains
944 * the saved state.
945 */
Grace Kloba22ac16e2009-10-07 18:00:23 -0700946 @Override
947 protected void onSaveInstanceState(Bundle outState) {
Dave Bort31a6d1c2009-04-13 15:56:49 -0700948 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800949 Log.v(LOGTAG, "BrowserActivity.onSaveInstanceState: this=" + this);
950 }
951 // the default implementation requires each view to have an id. As the
952 // browser handles the state itself and it doesn't use id for the views,
953 // don't call the default implementation. Otherwise it will trigger the
954 // warning like this, "couldn't save which view has focus because the
955 // focused view XXX has no id".
956
957 // Save all the tabs
958 mTabControl.saveState(outState);
Elliott Slaughter3d6df162010-08-25 13:17:44 -0700959
960 // Save time so that we know how old incognito tabs (if any) are.
961 outState.putSerializable("lastActiveDate", Calendar.getInstance());
The Android Open Source Project0c908882009-03-03 19:32:16 -0800962 }
963
Grace Kloba22ac16e2009-10-07 18:00:23 -0700964 @Override
965 protected void onPause() {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800966 super.onPause();
967
968 if (mActivityInPause) {
969 Log.e(LOGTAG, "BrowserActivity is already paused.");
970 return;
971 }
972
Mike Reed7bfa63b2009-05-28 11:08:32 -0400973 mTabControl.pauseCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800974 mActivityInPause = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -0400975 if (mTabControl.getCurrentIndex() >= 0 && !pauseWebViewTimers()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800976 mWakeLock.acquire();
977 mHandler.sendMessageDelayed(mHandler
978 .obtainMessage(RELEASE_WAKELOCK), WAKELOCK_TIMEOUT);
979 }
980
Leon Scrogginsa2ab6a72009-09-11 11:49:52 -0400981 // FIXME: This removes the active tabs page and resets the menu to
982 // MAIN_MENU. A better solution might be to do this work in onNewIntent
983 // but then we would need to save it in onSaveInstanceState and restore
984 // it in onCreate/onRestoreInstanceState
985 if (mActiveTabsPage != null) {
986 removeActiveTabPage(true);
987 }
988
The Android Open Source Project0c908882009-03-03 19:32:16 -0800989 cancelStopToast();
990
991 // unregister network state listener
992 unregisterReceiver(mNetworkStateIntentReceiver);
993 WebView.disablePlatformNotifications();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800994 }
995
Grace Kloba22ac16e2009-10-07 18:00:23 -0700996 @Override
997 protected void onDestroy() {
Dave Bort31a6d1c2009-04-13 15:56:49 -0700998 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800999 Log.v(LOGTAG, "BrowserActivity.onDestroy: this=" + this);
1000 }
1001 super.onDestroy();
Grace Kloba0923d692009-09-23 21:37:25 -07001002
Leon Scroggins8d5fa432009-10-02 15:55:59 -04001003 if (mUploadMessage != null) {
1004 mUploadMessage.onReceiveValue(null);
1005 mUploadMessage = null;
1006 }
1007
Grace Kloba0923d692009-09-23 21:37:25 -07001008 if (mTabControl == null) return;
1009
Grace Kloba1fc98a32009-10-21 13:23:08 -07001010 // Remove the fake title bar if it is there
1011 hideFakeTitleBar();
1012
The Android Open Source Project0c908882009-03-03 19:32:16 -08001013 // Remove the current tab and sub window
Grace Kloba22ac16e2009-10-07 18:00:23 -07001014 Tab t = mTabControl.getCurrentTab();
Patrick Scottfb5e77f2009-04-08 19:17:37 -07001015 if (t != null) {
1016 dismissSubWindow(t);
1017 removeTabFromContentView(t);
1018 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001019 // Destroy all the tabs
1020 mTabControl.destroy();
1021 WebIconDatabase.getInstance().close();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001022
Bjorn Bringerta7611812010-03-24 11:12:02 +00001023 // Stop watching the default geolocation permissions
1024 mSystemAllowGeolocationOrigins.stop();
1025 mSystemAllowGeolocationOrigins = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001026 }
1027
1028 @Override
1029 public void onConfigurationChanged(Configuration newConfig) {
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04001030 mConfigChanged = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001031 super.onConfigurationChanged(newConfig);
1032
1033 if (mPageInfoDialog != null) {
1034 mPageInfoDialog.dismiss();
1035 showPageInfo(
1036 mPageInfoView,
Leon Scrogginsc7b92f82010-01-11 18:17:31 -05001037 mPageInfoFromShowSSLCertificateOnError);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001038 }
1039 if (mSSLCertificateDialog != null) {
1040 mSSLCertificateDialog.dismiss();
1041 showSSLCertificate(
1042 mSSLCertificateView);
1043 }
1044 if (mSSLCertificateOnErrorDialog != null) {
1045 mSSLCertificateOnErrorDialog.dismiss();
1046 showSSLCertificateOnError(
1047 mSSLCertificateOnErrorView,
1048 mSSLCertificateOnErrorHandler,
1049 mSSLCertificateOnErrorError);
1050 }
1051 if (mHttpAuthenticationDialog != null) {
1052 String title = ((TextView) mHttpAuthenticationDialog
1053 .findViewById(com.android.internal.R.id.alertTitle)).getText()
1054 .toString();
1055 String name = ((TextView) mHttpAuthenticationDialog
1056 .findViewById(R.id.username_edit)).getText().toString();
1057 String password = ((TextView) mHttpAuthenticationDialog
1058 .findViewById(R.id.password_edit)).getText().toString();
1059 int focusId = mHttpAuthenticationDialog.getCurrentFocus()
1060 .getId();
1061 mHttpAuthenticationDialog.dismiss();
1062 showHttpAuthentication(mHttpAuthHandler, null, null, title,
1063 name, password, focusId);
1064 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001065 }
1066
Grace Kloba22ac16e2009-10-07 18:00:23 -07001067 @Override
1068 public void onLowMemory() {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001069 super.onLowMemory();
1070 mTabControl.freeMemory();
1071 }
1072
Cary Clarkff4d92c2010-03-25 11:17:03 -04001073 private void resumeWebViewTimers() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001074 Tab tab = mTabControl.getCurrentTab();
Cary Clarkff4d92c2010-03-25 11:17:03 -04001075 if (tab == null) return; // monkey can trigger this
Grace Kloba22ac16e2009-10-07 18:00:23 -07001076 boolean inLoad = tab.inLoad();
1077 if ((!mActivityInPause && !inLoad) || (mActivityInPause && inLoad)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001078 CookieSyncManager.getInstance().startSync();
Grace Kloba22ac16e2009-10-07 18:00:23 -07001079 WebView w = tab.getWebView();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001080 if (w != null) {
1081 w.resumeTimers();
1082 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001083 }
1084 }
1085
Mike Reed7bfa63b2009-05-28 11:08:32 -04001086 private boolean pauseWebViewTimers() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001087 Tab tab = mTabControl.getCurrentTab();
1088 boolean inLoad = tab.inLoad();
1089 if (mActivityInPause && !inLoad) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001090 CookieSyncManager.getInstance().stopSync();
1091 WebView w = mTabControl.getCurrentWebView();
1092 if (w != null) {
1093 w.pauseTimers();
1094 }
1095 return true;
1096 } else {
1097 return false;
1098 }
1099 }
1100
The Android Open Source Project0c908882009-03-03 19:32:16 -08001101 // Open the icon database and retain all the icons for visited sites.
1102 private void retainIconsOnStartup() {
1103 final WebIconDatabase db = WebIconDatabase.getInstance();
1104 db.open(getDir("icons", 0).getPath());
Leon Scroggins2c0f6112010-03-12 18:09:39 -05001105 Cursor c = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001106 try {
Leon Scroggins2c0f6112010-03-12 18:09:39 -05001107 c = Browser.getAllBookmarks(mResolver);
1108 if (c.moveToFirst()) {
1109 int urlIndex = c.getColumnIndex(Browser.BookmarkColumns.URL);
1110 do {
1111 String url = c.getString(urlIndex);
1112 db.retainIconForPageUrl(url);
1113 } while (c.moveToNext());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001114 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001115 } catch (IllegalStateException e) {
1116 Log.e(LOGTAG, "retainIconsOnStartup", e);
Leon Scroggins2c0f6112010-03-12 18:09:39 -05001117 } finally {
1118 if (c!= null) c.close();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001119 }
1120 }
1121
1122 // Helper method for getting the top window.
1123 WebView getTopWindow() {
1124 return mTabControl.getCurrentTopWebView();
1125 }
1126
Grace Kloba22ac16e2009-10-07 18:00:23 -07001127 TabControl getTabControl() {
1128 return mTabControl;
1129 }
1130
The Android Open Source Project0c908882009-03-03 19:32:16 -08001131 @Override
1132 public boolean onCreateOptionsMenu(Menu menu) {
1133 super.onCreateOptionsMenu(menu);
1134
1135 MenuInflater inflater = getMenuInflater();
1136 inflater.inflate(R.menu.browser, menu);
1137 mMenu = menu;
1138 updateInLoadMenuItems();
1139 return true;
1140 }
1141
1142 /**
1143 * As the menu can be open when loading state changes
1144 * we must manually update the state of the stop/reload menu
1145 * item
1146 */
1147 private void updateInLoadMenuItems() {
1148 if (mMenu == null) {
1149 return;
1150 }
Michael Kolbe0a36662010-06-29 10:37:12 -07001151 MenuItem dest = mMenu.findItem(R.id.stop_reload_menu_id);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001152 MenuItem src = mInLoad ?
1153 mMenu.findItem(R.id.stop_menu_id):
Michael Kolbe0a36662010-06-29 10:37:12 -07001154 mMenu.findItem(R.id.reload_menu_id);
1155 if (src != null) {
1156 dest.setIcon(src.getIcon());
1157 dest.setTitle(src.getTitle());
1158 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001159 }
1160
1161 @Override
1162 public boolean onContextItemSelected(MenuItem item) {
1163 // chording is not an issue with context menus, but we use the same
1164 // options selector, so set mCanChord to true so we can access them.
1165 mCanChord = true;
1166 int id = item.getItemId();
Leon Scroggins96afcb12009-12-10 12:35:56 -05001167 boolean result = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001168 switch (id) {
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001169 // For the context menu from the title bar
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001170 case R.id.title_bar_copy_page_url:
Leon Scroggins96afcb12009-12-10 12:35:56 -05001171 Tab currentTab = mTabControl.getCurrentTab();
1172 if (null == currentTab) {
1173 result = false;
1174 break;
1175 }
1176 WebView mainView = currentTab.getWebView();
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001177 if (null == mainView) {
Leon Scroggins96afcb12009-12-10 12:35:56 -05001178 result = false;
1179 break;
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001180 }
Leon Scroggins96afcb12009-12-10 12:35:56 -05001181 copy(mainView.getUrl());
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001182 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001183 // -- Browser context menu
1184 case R.id.open_context_menu_id:
The Android Open Source Project0c908882009-03-03 19:32:16 -08001185 case R.id.bookmark_context_menu_id:
1186 case R.id.save_link_context_menu_id:
1187 case R.id.share_link_context_menu_id:
1188 case R.id.copy_link_context_menu_id:
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001189 final WebView webView = getTopWindow();
1190 if (null == webView) {
Leon Scroggins96afcb12009-12-10 12:35:56 -05001191 result = false;
1192 break;
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001193 }
1194 final HashMap hrefMap = new HashMap();
1195 hrefMap.put("webview", webView);
1196 final Message msg = mHandler.obtainMessage(
1197 FOCUS_NODE_HREF, id, 0, hrefMap);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001198 webView.requestFocusNodeHref(msg);
1199 break;
1200
1201 default:
1202 // For other context menus
Leon Scroggins96afcb12009-12-10 12:35:56 -05001203 result = onOptionsItemSelected(item);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001204 }
1205 mCanChord = false;
Leon Scroggins96afcb12009-12-10 12:35:56 -05001206 return result;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001207 }
1208
1209 private Bundle createGoogleSearchSourceBundle(String source) {
1210 Bundle bundle = new Bundle();
Bjorn Bringert10d1cca2010-02-10 14:22:12 +00001211 bundle.putString(Search.SOURCE, source);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001212 return bundle;
1213 }
1214
Leon Scroggins8ad29922010-02-16 12:33:55 -05001215 /* package */ void editUrl() {
Leon Scroggins68579392009-09-15 15:31:54 -04001216 if (mOptionsMenuOpen) closeOptionsMenu();
Leon Scroggins5bbe9802009-07-31 13:10:55 -04001217 String url = (getTopWindow() == null) ? null : getTopWindow().getUrl();
Grace Kloba83f47342009-07-20 10:44:31 -07001218 startSearch(mSettings.getHomePage().equals(url) ? null : url, true,
Leon Scroggins8ad29922010-02-16 12:33:55 -05001219 null, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001220 }
1221
Leon Scroggins8ad29922010-02-16 12:33:55 -05001222 /**
1223 * Overriding this to insert a local information bundle
1224 */
The Android Open Source Project0c908882009-03-03 19:32:16 -08001225 @Override
1226 public void startSearch(String initialQuery, boolean selectInitialQuery,
1227 Bundle appSearchData, boolean globalSearch) {
1228 if (appSearchData == null) {
1229 appSearchData = createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_TYPE);
1230 }
1231 super.startSearch(initialQuery, selectInitialQuery, appSearchData, globalSearch);
1232 }
1233
Leon Scroggins1f005d32009-08-10 17:36:42 -04001234 /**
1235 * Switch tabs. Called by the TitleBarSet when sliding the title bar
1236 * results in changing tabs.
Leon Scroggins160a7e72009-08-14 18:28:01 -04001237 * @param index Index of the tab to change to, as defined by
1238 * mTabControl.getTabIndex(Tab t).
1239 * @return boolean True if we successfully switched to a different tab. If
1240 * the indexth tab is null, or if that tab is the same as
1241 * the current one, return false.
Leon Scroggins1f005d32009-08-10 17:36:42 -04001242 */
Leon Scroggins160a7e72009-08-14 18:28:01 -04001243 /* package */ boolean switchToTab(int index) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001244 Tab tab = mTabControl.getTab(index);
1245 Tab currentTab = mTabControl.getCurrentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04001246 if (tab == null || tab == currentTab) {
Leon Scroggins160a7e72009-08-14 18:28:01 -04001247 return false;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001248 }
1249 if (currentTab != null) {
1250 // currentTab may be null if it was just removed. In that case,
1251 // we do not need to remove it
1252 removeTabFromContentView(currentTab);
1253 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001254 mTabControl.setCurrentTab(tab);
1255 attachTabToContentView(tab);
Grace Klobaeb6eef42009-09-15 17:56:32 -07001256 resetTitleIconAndProgress();
1257 updateLockIconToLatest();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001258 return true;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001259 }
1260
Grace Kloba22ac16e2009-10-07 18:00:23 -07001261 /* package */ Tab openTabToHomePage() {
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001262 return openTabAndShow(mSettings.getHomePage(), false, null);
1263 }
1264
Leon Scroggins1f005d32009-08-10 17:36:42 -04001265 /* package */ void closeCurrentWindow() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001266 final Tab current = mTabControl.getCurrentTab();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001267 if (mTabControl.getTabCount() == 1) {
Leon Scroggins30444232009-09-04 18:36:20 -04001268 // This is the last tab. Open a new one, with the home
1269 // page and close the current one.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001270 openTabToHomePage();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001271 closeTab(current);
Leon Scroggins160a7e72009-08-14 18:28:01 -04001272 return;
1273 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07001274 final Tab parent = current.getParentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04001275 int indexToShow = -1;
1276 if (parent != null) {
1277 indexToShow = mTabControl.getTabIndex(parent);
1278 } else {
Leon Scroggins160a7e72009-08-14 18:28:01 -04001279 final int currentIndex = mTabControl.getCurrentIndex();
1280 // Try to move to the tab to the right
1281 indexToShow = currentIndex + 1;
1282 if (indexToShow > mTabControl.getTabCount() - 1) {
1283 // Try to move to the tab to the left
1284 indexToShow = currentIndex - 1;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001285 }
1286 }
Leon Scroggins160a7e72009-08-14 18:28:01 -04001287 if (switchToTab(indexToShow)) {
1288 // Close window
1289 closeTab(current);
1290 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001291 }
1292
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001293 private ActiveTabsPage mActiveTabsPage;
1294
1295 /**
1296 * Remove the active tabs page.
1297 * @param needToAttach If true, the active tabs page did not attach a tab
1298 * to the content view, so we need to do that here.
1299 */
1300 /* package */ void removeActiveTabPage(boolean needToAttach) {
1301 mContentView.removeView(mActiveTabsPage);
Leon Scrogginsd746a942010-05-19 13:21:44 -04001302 mTitleBar.setVisibility(View.VISIBLE);
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001303 mActiveTabsPage = null;
1304 mMenuState = R.id.MAIN_MENU;
1305 if (needToAttach) {
1306 attachTabToContentView(mTabControl.getCurrentTab());
1307 }
1308 getTopWindow().requestFocus();
1309 }
1310
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04001311 @Override
1312 public ActionMode onStartActionMode(ActionMode.Callback callback) {
Leon Scroggins4fc12cb2010-08-24 14:24:05 -04001313 mActionMode = super.onStartActionMode(callback);
1314 hideFakeTitleBar();
1315 // Would like to change the MENU, but onEndActionMode may not be called
1316 return mActionMode;
Cary Clark01cfcdd2010-06-04 16:36:45 -04001317 }
1318
The Android Open Source Project0c908882009-03-03 19:32:16 -08001319 @Override
1320 public boolean onOptionsItemSelected(MenuItem item) {
Michael Kolbed217742010-08-10 17:52:34 -07001321 // check the action bar button before mCanChord check, as the prepare call
1322 // doesn't come for action bar buttons
1323 if (item.getItemId() == R.id.newtab) {
Michael Kolb300b7f02010-08-25 13:47:24 -07001324 openTabToHomePage();
Michael Kolbed217742010-08-10 17:52:34 -07001325 return true;
1326 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001327 if (!mCanChord) {
1328 // The user has already fired a shortcut with this hold down of the
1329 // menu key.
1330 return false;
1331 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001332 if (null == getTopWindow()) {
Leon Scroggins0d7ae0e2009-06-05 11:04:45 -04001333 return false;
1334 }
Grace Kloba6ee9c492009-07-13 10:04:34 -07001335 if (mMenuIsDown) {
1336 // The shortcut action consumes the MENU. Even if it is still down,
1337 // it won't trigger the next shortcut action. In the case of the
1338 // shortcut action triggering a new activity, like Bookmarks, we
1339 // won't get onKeyUp for MENU. So it is important to reset it here.
1340 mMenuIsDown = false;
1341 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001342 switch (item.getItemId()) {
1343 // -- Main menu
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001344 case R.id.new_tab_menu_id:
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001345 openTabToHomePage();
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001346 break;
1347
Michael Kolbae62fd42010-08-18 16:33:28 -07001348 case R.id.incognito_menu_id:
1349 openIncognitoTab();
1350 break;
1351
Leon Scroggins64b80f32009-08-07 12:03:34 -04001352 case R.id.goto_menu_id:
Leon Scroggins8ad29922010-02-16 12:33:55 -05001353 editUrl();
Leon Scrogginsb3a5bed2009-09-28 11:21:56 -04001354 break;
1355
1356 case R.id.bookmarks_menu_id:
Michael Kolb68792c82010-08-09 16:39:18 -07001357 bookmarksOrHistoryPicker(false, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001358 break;
1359
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001360 case R.id.active_tabs_menu_id:
1361 mActiveTabsPage = new ActiveTabsPage(this, mTabControl);
1362 removeTabFromContentView(mTabControl.getCurrentTab());
Leon Scrogginsd746a942010-05-19 13:21:44 -04001363 mTitleBar.setVisibility(View.GONE);
Leon Scroggins43de6162009-09-14 19:59:58 -04001364 hideFakeTitleBar();
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001365 mContentView.addView(mActiveTabsPage, COVER_SCREEN_PARAMS);
1366 mActiveTabsPage.requestFocus();
1367 mMenuState = EMPTY_MENU;
1368 break;
1369
Leon Scroggins1f005d32009-08-10 17:36:42 -04001370 case R.id.add_bookmark_menu_id:
Leon Scroggins571b3762010-05-26 10:25:01 -04001371 bookmarkCurrentPage();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001372 break;
1373
1374 case R.id.stop_reload_menu_id:
1375 if (mInLoad) {
1376 stopLoading();
1377 } else {
1378 getTopWindow().reload();
1379 }
1380 break;
1381
1382 case R.id.back_menu_id:
1383 getTopWindow().goBack();
1384 break;
1385
1386 case R.id.forward_menu_id:
1387 getTopWindow().goForward();
1388 break;
1389
1390 case R.id.close_menu_id:
1391 // Close the subwindow if it exists.
1392 if (mTabControl.getCurrentSubWindow() != null) {
1393 dismissSubWindow(mTabControl.getCurrentTab());
1394 break;
1395 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001396 closeCurrentWindow();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001397 break;
1398
1399 case R.id.homepage_menu_id:
Grace Kloba22ac16e2009-10-07 18:00:23 -07001400 Tab current = mTabControl.getCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001401 if (current != null) {
1402 dismissSubWindow(current);
Leon Scroggins92472e82010-02-17 16:32:28 -05001403 loadUrl(current.getWebView(), mSettings.getHomePage());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001404 }
1405 break;
1406
1407 case R.id.preferences_menu_id:
1408 Intent intent = new Intent(this,
1409 BrowserPreferencesPage.class);
Leon Scrogginsd5304942009-12-10 16:11:39 -05001410 intent.putExtra(BrowserPreferencesPage.CURRENT_PAGE,
1411 getTopWindow().getUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001412 startActivityForResult(intent, PREFERENCES_PAGE);
1413 break;
1414
1415 case R.id.find_menu_id:
Leon Scroggins4fc12cb2010-08-24 14:24:05 -04001416 getTopWindow().showFindDialog(null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001417 break;
1418
Elliott Slaughter0ced08c2010-06-30 11:40:42 -07001419 case R.id.save_webarchive_menu_id:
1420 if (LOGD_ENABLED) {
1421 Log.d(LOGTAG, "Save as Web Archive");
1422 }
Elliott Slaughteraba242c2010-09-01 16:21:07 -07001423 String state = Environment.getExternalStorageState();
1424 if (Environment.MEDIA_MOUNTED.equals(state)) {
1425 String directory = Environment.getExternalStoragePublicDirectory(
1426 Environment.DIRECTORY_DOWNLOADS).getAbsolutePath() + File.separator;
1427 getTopWindow().saveWebArchive(directory, true, new ValueCallback<String>() {
1428 @Override
1429 public void onReceiveValue(String value) {
1430 if (value != null) {
1431 Toast.makeText(BrowserActivity.this, R.string.webarchive_saved,
1432 Toast.LENGTH_SHORT).show();
1433 } else {
1434 Toast.makeText(BrowserActivity.this, R.string.webarchive_failed,
1435 Toast.LENGTH_SHORT).show();
1436 }
Elliott Slaughter0ced08c2010-06-30 11:40:42 -07001437 }
Elliott Slaughteraba242c2010-09-01 16:21:07 -07001438 });
1439 } else {
1440 Toast.makeText(BrowserActivity.this, R.string.webarchive_failed,
1441 Toast.LENGTH_SHORT).show();
1442 }
Elliott Slaughter0ced08c2010-06-30 11:40:42 -07001443 break;
1444
The Android Open Source Project0c908882009-03-03 19:32:16 -08001445 case R.id.page_info_menu_id:
1446 showPageInfo(mTabControl.getCurrentTab(), false);
1447 break;
1448
1449 case R.id.classic_history_menu_id:
Michael Kolb68792c82010-08-09 16:39:18 -07001450 bookmarksOrHistoryPicker(true, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001451 break;
1452
Leon Scroggins96afcb12009-12-10 12:35:56 -05001453 case R.id.title_bar_share_page_url:
The Android Open Source Project0c908882009-03-03 19:32:16 -08001454 case R.id.share_page_menu_id:
Leon Scroggins96afcb12009-12-10 12:35:56 -05001455 Tab currentTab = mTabControl.getCurrentTab();
1456 if (null == currentTab) {
1457 mCanChord = false;
1458 return false;
1459 }
1460 currentTab.populatePickerData();
1461 sharePage(this, currentTab.getTitle(),
1462 currentTab.getUrl(), currentTab.getFavicon(),
Ben Murdoch87cc65d2010-06-29 20:34:10 +01001463 createScreenshot(currentTab.getWebView(), getDesiredThumbnailWidth(this),
1464 getDesiredThumbnailHeight(this)));
The Android Open Source Project0c908882009-03-03 19:32:16 -08001465 break;
1466
1467 case R.id.dump_nav_menu_id:
1468 getTopWindow().debugDump();
1469 break;
1470
Andrei Popescu7a8b88b2010-02-02 00:30:38 +00001471 case R.id.dump_counters_menu_id:
1472 getTopWindow().dumpV8Counters();
1473 break;
1474
The Android Open Source Project0c908882009-03-03 19:32:16 -08001475 case R.id.zoom_in_menu_id:
1476 getTopWindow().zoomIn();
1477 break;
1478
1479 case R.id.zoom_out_menu_id:
1480 getTopWindow().zoomOut();
1481 break;
1482
1483 case R.id.view_downloads_menu_id:
1484 viewDownloads(null);
1485 break;
1486
The Android Open Source Project0c908882009-03-03 19:32:16 -08001487 case R.id.window_one_menu_id:
1488 case R.id.window_two_menu_id:
1489 case R.id.window_three_menu_id:
1490 case R.id.window_four_menu_id:
1491 case R.id.window_five_menu_id:
1492 case R.id.window_six_menu_id:
1493 case R.id.window_seven_menu_id:
1494 case R.id.window_eight_menu_id:
1495 {
1496 int menuid = item.getItemId();
1497 for (int id = 0; id < WINDOW_SHORTCUT_ID_ARRAY.length; id++) {
1498 if (WINDOW_SHORTCUT_ID_ARRAY[id] == menuid) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001499 Tab desiredTab = mTabControl.getTab(id);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001500 if (desiredTab != null &&
1501 desiredTab != mTabControl.getCurrentTab()) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001502 switchToTab(id);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001503 }
1504 break;
1505 }
1506 }
1507 }
1508 break;
1509
1510 default:
1511 if (!super.onOptionsItemSelected(item)) {
1512 return false;
1513 }
1514 // Otherwise fall through.
1515 }
1516 mCanChord = false;
1517 return true;
1518 }
1519
Leon Scroggins571b3762010-05-26 10:25:01 -04001520 /* package */ void bookmarkCurrentPage() {
1521 Intent i = new Intent(BrowserActivity.this,
1522 AddBookmarkPage.class);
1523 WebView w = getTopWindow();
1524 i.putExtra("url", w.getUrl());
1525 i.putExtra("title", w.getTitle());
1526 i.putExtra("touch_icon_url", w.getTouchIconUrl());
Ben Murdoch87cc65d2010-06-29 20:34:10 +01001527 i.putExtra("thumbnail", createScreenshot(w, getDesiredThumbnailWidth(this),
1528 getDesiredThumbnailHeight(this)));
Ben Murdocheecb4e62010-07-06 16:30:38 +01001529 i.putExtra("url_editable", false);
Leon Scroggins571b3762010-05-26 10:25:01 -04001530 startActivity(i);
1531 }
1532
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04001533 /*
1534 * True if a custom ActionMode (i.e. find or select) is in use.
1535 */
1536 private boolean isInCustomActionMode() {
1537 return mActionMode != null;
Cary Clark01cfcdd2010-06-04 16:36:45 -04001538 }
1539
1540 /*
Leon Scroggins4fc12cb2010-08-24 14:24:05 -04001541 * End the current ActionMode.
Cary Clark01cfcdd2010-06-04 16:36:45 -04001542 */
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04001543 void endActionMode() {
1544 if (mActionMode != null) {
Leon Scroggins4fc12cb2010-08-24 14:24:05 -04001545 ActionMode mode = mActionMode;
1546 onEndActionMode();
1547 mode.finish();
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04001548 }
1549 }
1550
1551 /*
1552 * Called by find and select when they are finished. Replace title bars
1553 * as necessary.
1554 */
1555 public void onEndActionMode() {
1556 if (!isInCustomActionMode()) return;
Leon Scroggins79e36d92010-04-29 16:01:46 +01001557 if (mInLoad) {
1558 // The title bar was hidden, because otherwise it would cover up the
Michael Kolba2b2ba82010-08-04 17:54:03 -07001559 // find or select dialog. Now that the dialog has been removed,
Cary Clark01cfcdd2010-06-04 16:36:45 -04001560 // show the fake title bar once again.
Leon Scroggins79e36d92010-04-29 16:01:46 +01001561 showFakeTitleBar();
1562 }
Leon Scroggins4fc12cb2010-08-24 14:24:05 -04001563 // Would like to return the menu state to normal, but this does not
1564 // necessarily get called.
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04001565 mActionMode = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001566 }
1567
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04001568 // For select and find, we keep track of the ActionMode so that
1569 // finish() can be called as desired.
1570 private ActionMode mActionMode;
1571
Grace Kloba22ac16e2009-10-07 18:00:23 -07001572 @Override
1573 public boolean onPrepareOptionsMenu(Menu menu) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001574 // This happens when the user begins to hold down the menu key, so
1575 // allow them to chord to get a shortcut.
1576 mCanChord = true;
1577 // Note: setVisible will decide whether an item is visible; while
1578 // setEnabled() will decide whether an item is enabled, which also means
1579 // whether the matching shortcut key will function.
1580 super.onPrepareOptionsMenu(menu);
1581 switch (mMenuState) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001582 case EMPTY_MENU:
1583 if (mCurrentMenuState != mMenuState) {
1584 menu.setGroupVisible(R.id.MAIN_MENU, false);
1585 menu.setGroupEnabled(R.id.MAIN_MENU, false);
1586 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001587 }
1588 break;
1589 default:
1590 if (mCurrentMenuState != mMenuState) {
1591 menu.setGroupVisible(R.id.MAIN_MENU, true);
1592 menu.setGroupEnabled(R.id.MAIN_MENU, true);
1593 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001594 }
1595 final WebView w = getTopWindow();
1596 boolean canGoBack = false;
1597 boolean canGoForward = false;
1598 boolean isHome = false;
1599 if (w != null) {
1600 canGoBack = w.canGoBack();
1601 canGoForward = w.canGoForward();
1602 isHome = mSettings.getHomePage().equals(w.getUrl());
1603 }
1604 final MenuItem back = menu.findItem(R.id.back_menu_id);
1605 back.setEnabled(canGoBack);
1606
1607 final MenuItem home = menu.findItem(R.id.homepage_menu_id);
1608 home.setEnabled(!isHome);
1609
Michael Kolbe0a36662010-06-29 10:37:12 -07001610 final MenuItem forward = menu.findItem(R.id.forward_menu_id);
1611 forward.setEnabled(canGoForward);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001612
Michael Kolbed217742010-08-10 17:52:34 -07001613 if (!mXLargeScreenSize) {
1614 final MenuItem newtab = menu.findItem(R.id.new_tab_menu_id);
1615 newtab.setEnabled(mTabControl.canCreateNewTab());
1616 }
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001617
The Android Open Source Project0c908882009-03-03 19:32:16 -08001618 // decide whether to show the share link option
1619 PackageManager pm = getPackageManager();
1620 Intent send = new Intent(Intent.ACTION_SEND);
1621 send.setType("text/plain");
1622 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1623 menu.findItem(R.id.share_page_menu_id).setVisible(ri != null);
1624
The Android Open Source Project0c908882009-03-03 19:32:16 -08001625 boolean isNavDump = mSettings.isNavDump();
1626 final MenuItem nav = menu.findItem(R.id.dump_nav_menu_id);
1627 nav.setVisible(isNavDump);
1628 nav.setEnabled(isNavDump);
Andrei Popescu7a8b88b2010-02-02 00:30:38 +00001629
1630 boolean showDebugSettings = mSettings.showDebugSettings();
1631 final MenuItem counter = menu.findItem(R.id.dump_counters_menu_id);
1632 counter.setVisible(showDebugSettings);
1633 counter.setEnabled(showDebugSettings);
1634
The Android Open Source Project0c908882009-03-03 19:32:16 -08001635 break;
1636 }
1637 mCurrentMenuState = mMenuState;
1638 return true;
1639 }
1640
1641 @Override
1642 public void onCreateContextMenu(ContextMenu menu, View v,
1643 ContextMenuInfo menuInfo) {
Leon Scroggins571b3762010-05-26 10:25:01 -04001644 if (v instanceof TitleBarBase) {
Leon Scroggins4e9f89b2010-02-22 16:54:14 -05001645 return;
1646 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001647 WebView webview = (WebView) v;
1648 WebView.HitTestResult result = webview.getHitTestResult();
1649 if (result == null) {
1650 return;
1651 }
1652
1653 int type = result.getType();
1654 if (type == WebView.HitTestResult.UNKNOWN_TYPE) {
1655 Log.w(LOGTAG,
1656 "We should not show context menu when nothing is touched");
1657 return;
1658 }
1659 if (type == WebView.HitTestResult.EDIT_TEXT_TYPE) {
1660 // let TextView handles context menu
1661 return;
1662 }
1663
1664 // Note, http://b/issue?id=1106666 is requesting that
1665 // an inflated menu can be used again. This is not available
1666 // yet, so inflate each time (yuk!)
1667 MenuInflater inflater = getMenuInflater();
1668 inflater.inflate(R.menu.browsercontext, menu);
1669
1670 // Show the correct menu group
Leon Scroggins III9e997c72010-05-26 13:25:16 -04001671 final String extra = result.getExtra();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001672 menu.setGroupVisible(R.id.PHONE_MENU,
1673 type == WebView.HitTestResult.PHONE_TYPE);
1674 menu.setGroupVisible(R.id.EMAIL_MENU,
1675 type == WebView.HitTestResult.EMAIL_TYPE);
1676 menu.setGroupVisible(R.id.GEO_MENU,
1677 type == WebView.HitTestResult.GEO_TYPE);
1678 menu.setGroupVisible(R.id.IMAGE_MENU,
1679 type == WebView.HitTestResult.IMAGE_TYPE
1680 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1681 menu.setGroupVisible(R.id.ANCHOR_MENU,
1682 type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1683 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1684
1685 // Setup custom handling depending on the type
1686 switch (type) {
1687 case WebView.HitTestResult.PHONE_TYPE:
1688 menu.setHeaderTitle(Uri.decode(extra));
1689 menu.findItem(R.id.dial_context_menu_id).setIntent(
1690 new Intent(Intent.ACTION_VIEW, Uri
1691 .parse(WebView.SCHEME_TEL + extra)));
1692 Intent addIntent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
1693 addIntent.putExtra(Insert.PHONE, Uri.decode(extra));
Cary Clark5e335a32009-09-22 14:53:11 -04001694 addIntent.setType(ContactsContract.Contacts.CONTENT_ITEM_TYPE);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001695 menu.findItem(R.id.add_contact_context_menu_id).setIntent(
1696 addIntent);
1697 menu.findItem(R.id.copy_phone_context_menu_id).setOnMenuItemClickListener(
1698 new Copy(extra));
1699 break;
1700
1701 case WebView.HitTestResult.EMAIL_TYPE:
1702 menu.setHeaderTitle(extra);
1703 menu.findItem(R.id.email_context_menu_id).setIntent(
1704 new Intent(Intent.ACTION_VIEW, Uri
1705 .parse(WebView.SCHEME_MAILTO + extra)));
1706 menu.findItem(R.id.copy_mail_context_menu_id).setOnMenuItemClickListener(
1707 new Copy(extra));
1708 break;
1709
1710 case WebView.HitTestResult.GEO_TYPE:
1711 menu.setHeaderTitle(extra);
1712 menu.findItem(R.id.map_context_menu_id).setIntent(
1713 new Intent(Intent.ACTION_VIEW, Uri
1714 .parse(WebView.SCHEME_GEO
1715 + URLEncoder.encode(extra))));
1716 menu.findItem(R.id.copy_geo_context_menu_id).setOnMenuItemClickListener(
1717 new Copy(extra));
1718 break;
1719
1720 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1721 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
1722 TextView titleView = (TextView) LayoutInflater.from(this)
1723 .inflate(android.R.layout.browser_link_context_header,
1724 null);
1725 titleView.setText(extra);
1726 menu.setHeaderView(titleView);
1727 // decide whether to show the open link in new tab option
Leon Scroggins III9e997c72010-05-26 13:25:16 -04001728 boolean showNewTab = mTabControl.canCreateNewTab();
1729 MenuItem newTabItem
1730 = menu.findItem(R.id.open_newtab_context_menu_id);
1731 newTabItem.setVisible(showNewTab);
1732 if (showNewTab) {
1733 newTabItem.setOnMenuItemClickListener(
1734 new MenuItem.OnMenuItemClickListener() {
1735 public boolean onMenuItemClick(MenuItem item) {
1736 final Tab parent = mTabControl.getCurrentTab();
Michael Kolb68792c82010-08-09 16:39:18 -07001737 final Tab newTab = openTab(extra, false);
Leon Scroggins III9e997c72010-05-26 13:25:16 -04001738 if (newTab != parent) {
1739 parent.addChildTab(newTab);
1740 }
1741 return true;
1742 }
1743 });
1744 }
Ben Murdochde353622009-10-12 10:29:00 +01001745 menu.findItem(R.id.bookmark_context_menu_id).setVisible(
1746 Bookmarks.urlHasAcceptableScheme(extra));
The Android Open Source Project0c908882009-03-03 19:32:16 -08001747 PackageManager pm = getPackageManager();
1748 Intent send = new Intent(Intent.ACTION_SEND);
1749 send.setType("text/plain");
1750 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1751 menu.findItem(R.id.share_link_context_menu_id).setVisible(ri != null);
1752 if (type == WebView.HitTestResult.SRC_ANCHOR_TYPE) {
1753 break;
1754 }
1755 // otherwise fall through to handle image part
1756 case WebView.HitTestResult.IMAGE_TYPE:
1757 if (type == WebView.HitTestResult.IMAGE_TYPE) {
1758 menu.setHeaderTitle(extra);
1759 }
1760 menu.findItem(R.id.view_image_context_menu_id).setIntent(
1761 new Intent(Intent.ACTION_VIEW, Uri.parse(extra)));
1762 menu.findItem(R.id.download_context_menu_id).
1763 setOnMenuItemClickListener(new Download(extra));
Ben Murdoch4f75ba22009-10-27 11:48:28 +00001764 menu.findItem(R.id.set_wallpaper_context_menu_id).
1765 setOnMenuItemClickListener(new SetAsWallpaper(extra));
The Android Open Source Project0c908882009-03-03 19:32:16 -08001766 break;
1767
1768 default:
1769 Log.w(LOGTAG, "We should not get here.");
1770 break;
1771 }
Leon Scrogginsb2b19f52009-10-09 16:10:00 -04001772 hideFakeTitleBar();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001773 }
1774
The Android Open Source Project0c908882009-03-03 19:32:16 -08001775 // Attach the given tab to the content view.
Grace Klobac928c302009-09-17 11:51:21 -07001776 // this should only be called for the current tab.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001777 private void attachTabToContentView(Tab t) {
Steve Block2bc69912009-07-30 14:45:13 +01001778 // Attach the container that contains the main WebView and any other UI
1779 // associated with the tab.
Patrick Scottd0119532009-09-17 08:00:31 -04001780 t.attachTabToContentView(mContentView);
Ben Murdochbff2d602009-07-01 20:19:05 +01001781
1782 if (mShouldShowErrorConsole) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001783 ErrorConsoleView errorConsole = t.getErrorConsole(true);
Ben Murdochbff2d602009-07-01 20:19:05 +01001784 if (errorConsole.numberOfErrors() == 0) {
1785 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
1786 } else {
1787 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
1788 }
1789
1790 mErrorConsoleContainer.addView(errorConsole,
Romain Guy15b8ec62010-01-08 15:06:43 -08001791 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
Ben Murdochbff2d602009-07-01 20:19:05 +01001792 ViewGroup.LayoutParams.WRAP_CONTENT));
1793 }
1794
Michael Kolba2b2ba82010-08-04 17:54:03 -07001795 WebView view = t.getWebView();
1796 view.setEmbeddedTitleBar(mTitleBar);
Leon Scroggins58d56c62010-01-28 15:12:40 -05001797 if (t.isInVoiceSearchMode()) {
1798 showVoiceTitleBar(t.getVoiceDisplayTitle());
1799 } else {
1800 revertVoiceTitleBar();
1801 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001802 // Request focus on the top window.
1803 t.getTopWindow().requestFocus();
Michael Kolba2b2ba82010-08-04 17:54:03 -07001804 if (mTabControl.getTabChangeListener() != null) {
1805 mTabControl.getTabChangeListener().onCurrentTab(t);
1806 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001807 }
1808
1809 // Attach a sub window to the main WebView of the given tab.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001810 void attachSubWindow(Tab t) {
Patrick Scottd0119532009-09-17 08:00:31 -04001811 t.attachSubWindow(mContentView);
1812 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001813 }
1814
1815 // Remove the given tab from the content view.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001816 private void removeTabFromContentView(Tab t) {
Steve Block2bc69912009-07-30 14:45:13 +01001817 // Remove the container that contains the main WebView.
Patrick Scottd0119532009-09-17 08:00:31 -04001818 t.removeTabFromContentView(mContentView);
Ben Murdochbff2d602009-07-01 20:19:05 +01001819
Grace Kloba22ac16e2009-10-07 18:00:23 -07001820 ErrorConsoleView errorConsole = t.getErrorConsole(false);
1821 if (errorConsole != null) {
1822 mErrorConsoleContainer.removeView(errorConsole);
Ben Murdochbff2d602009-07-01 20:19:05 +01001823 }
1824
Michael Kolba2b2ba82010-08-04 17:54:03 -07001825 WebView view = t.getWebView();
1826 if (view != null) {
1827 view.setEmbeddedTitleBar(null);
Leon Scrogginsbb85b902009-09-14 19:27:20 -04001828 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001829 }
1830
1831 // Remove the sub window if it exists. Also called by TabControl when the
1832 // user clicks the 'X' to dismiss a sub window.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001833 /* package */ void dismissSubWindow(Tab t) {
Patrick Scottd0119532009-09-17 08:00:31 -04001834 t.removeSubWindow(mContentView);
Grace Kloba22ac16e2009-10-07 18:00:23 -07001835 // dismiss the subwindow. This will destroy the WebView.
1836 t.dismissSubWindow();
Patrick Scottd0119532009-09-17 08:00:31 -04001837 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001838 }
1839
Leon Scroggins1f005d32009-08-10 17:36:42 -04001840 // A wrapper function of {@link #openTabAndShow(UrlData, boolean, String)}
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07001841 // that accepts url as string.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001842 private Tab openTabAndShow(String url, boolean closeOnExit, String appId) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001843 return openTabAndShow(new UrlData(url), closeOnExit, appId);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001844 }
1845
1846 // This method does a ton of stuff. It will attempt to create a new tab
1847 // if we haven't reached MAX_TABS. Otherwise it uses the current tab. If
Leon Scroggins1f005d32009-08-10 17:36:42 -04001848 // url isn't null, it will load the given url.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001849 /* package */Tab openTabAndShow(UrlData urlData, boolean closeOnExit,
1850 String appId) {
1851 final Tab currentTab = mTabControl.getCurrentTab();
1852 if (mTabControl.canCreateNewTab()) {
1853 final Tab tab = mTabControl.createNewTab(closeOnExit, appId,
Elliott Slaughterf0f03952010-07-14 18:10:36 -07001854 urlData.mUrl, false);
Leon Scroggins1f005d32009-08-10 17:36:42 -04001855 WebView webview = tab.getWebView();
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001856 // If the last tab was removed from the active tabs page, currentTab
1857 // will be null.
1858 if (currentTab != null) {
1859 removeTabFromContentView(currentTab);
1860 }
Patrick Scott8bbd69f2009-08-14 13:35:53 -04001861 // We must set the new tab as the current tab to reflect the old
1862 // animation behavior.
1863 mTabControl.setCurrentTab(tab);
Grace Klobaeb6eef42009-09-15 17:56:32 -07001864 attachTabToContentView(tab);
Leon Scroggins160a7e72009-08-14 18:28:01 -04001865 if (!urlData.isEmpty()) {
Patrick Scott9d53da02010-02-19 10:19:01 -05001866 loadUrlDataIn(tab, urlData);
Leon Scroggins1f005d32009-08-10 17:36:42 -04001867 }
1868 return tab;
1869 } else {
1870 // Get rid of the subwindow if it exists
1871 dismissSubWindow(currentTab);
1872 if (!urlData.isEmpty()) {
1873 // Load the given url.
Patrick Scott9d53da02010-02-19 10:19:01 -05001874 loadUrlDataIn(currentTab, urlData);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001875 }
Leon Scroggins58d56c62010-01-28 15:12:40 -05001876 return currentTab;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001877 }
1878 }
1879
Michael Kolb68792c82010-08-09 16:39:18 -07001880 private Tab openTab(String url, boolean forceForeground) {
1881 if (mSettings.openInBackground() && !forceForeground) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001882 Tab t = mTabControl.createNewTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001883 if (t != null) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001884 WebView view = t.getWebView();
Leon Scroggins92472e82010-02-17 16:32:28 -05001885 loadUrl(view, url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001886 }
Grace Klobac9181842009-04-14 08:53:22 -07001887 return t;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001888 } else {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001889 return openTabAndShow(url, false, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001890 }
1891 }
1892
Elliott Slaughterf0f03952010-07-14 18:10:36 -07001893 /* package */ Tab openIncognitoTab() {
1894 if (mTabControl.canCreateNewTab()) {
1895 Tab currentTab = mTabControl.getCurrentTab();
1896 Tab tab = mTabControl.createNewTab(false, null, null, true);
1897 if (currentTab != null) {
1898 removeTabFromContentView(currentTab);
1899 }
1900 mTabControl.setCurrentTab(tab);
1901 attachTabToContentView(tab);
1902 return tab;
1903 }
1904 return null;
1905 }
1906
The Android Open Source Project0c908882009-03-03 19:32:16 -08001907 private class Copy implements OnMenuItemClickListener {
1908 private CharSequence mText;
1909
1910 public boolean onMenuItemClick(MenuItem item) {
1911 copy(mText);
1912 return true;
1913 }
1914
1915 public Copy(CharSequence toCopy) {
1916 mText = toCopy;
1917 }
1918 }
1919
1920 private class Download implements OnMenuItemClickListener {
1921 private String mText;
1922
1923 public boolean onMenuItemClick(MenuItem item) {
1924 onDownloadStartNoStream(mText, null, null, null, -1);
1925 return true;
1926 }
1927
1928 public Download(String toDownload) {
1929 mText = toDownload;
1930 }
1931 }
1932
Ben Murdoch4f75ba22009-10-27 11:48:28 +00001933 private class SetAsWallpaper extends Thread implements
1934 OnMenuItemClickListener, DialogInterface.OnCancelListener {
1935 private URL mUrl;
1936 private ProgressDialog mWallpaperProgress;
1937 private boolean mCanceled = false;
1938
1939 public SetAsWallpaper(String url) {
1940 try {
1941 mUrl = new URL(url);
1942 } catch (MalformedURLException e) {
1943 mUrl = null;
1944 }
1945 }
1946
1947 public void onCancel(DialogInterface dialog) {
1948 mCanceled = true;
1949 }
1950
1951 public boolean onMenuItemClick(MenuItem item) {
1952 if (mUrl != null) {
1953 // The user may have tried to set a image with a large file size as their
1954 // background so it may take a few moments to perform the operation. Display
1955 // a progress spinner while it is working.
1956 mWallpaperProgress = new ProgressDialog(BrowserActivity.this);
1957 mWallpaperProgress.setIndeterminate(true);
1958 mWallpaperProgress.setMessage(getText(R.string.progress_dialog_setting_wallpaper));
1959 mWallpaperProgress.setCancelable(true);
1960 mWallpaperProgress.setOnCancelListener(this);
1961 mWallpaperProgress.show();
1962 start();
1963 }
1964 return true;
1965 }
1966
Michael Kolbe0a36662010-06-29 10:37:12 -07001967 @Override
Ben Murdoch4f75ba22009-10-27 11:48:28 +00001968 public void run() {
1969 Drawable oldWallpaper = BrowserActivity.this.getWallpaper();
1970 try {
1971 // TODO: This will cause the resource to be downloaded again, when we
1972 // should in most cases be able to grab it from the cache. To fix this
1973 // we should query WebCore to see if we can access a cached version and
1974 // instead open an input stream on that. This pattern could also be used
1975 // in the download manager where the same problem exists.
1976 InputStream inputstream = mUrl.openStream();
1977 if (inputstream != null) {
1978 setWallpaper(inputstream);
1979 }
1980 } catch (IOException e) {
1981 Log.e(LOGTAG, "Unable to set new wallpaper");
1982 // Act as though the user canceled the operation so we try to
1983 // restore the old wallpaper.
1984 mCanceled = true;
1985 }
1986
1987 if (mCanceled) {
1988 // Restore the old wallpaper if the user cancelled whilst we were setting
1989 // the new wallpaper.
1990 int width = oldWallpaper.getIntrinsicWidth();
1991 int height = oldWallpaper.getIntrinsicHeight();
1992 Bitmap bm = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
1993 Canvas canvas = new Canvas(bm);
1994 oldWallpaper.setBounds(0, 0, width, height);
1995 oldWallpaper.draw(canvas);
1996 try {
1997 setWallpaper(bm);
1998 } catch (IOException e) {
1999 Log.e(LOGTAG, "Unable to restore old wallpaper.");
2000 }
2001 mCanceled = false;
2002 }
2003
2004 if (mWallpaperProgress.isShowing()) {
2005 mWallpaperProgress.dismiss();
2006 }
2007 }
2008 }
2009
The Android Open Source Project0c908882009-03-03 19:32:16 -08002010 private void copy(CharSequence text) {
Dianne Hackborn80f32622010-08-05 14:17:53 -07002011 ClipboardManager cm = (ClipboardManager)getSystemService(Context.CLIPBOARD_SERVICE);
2012 cm.setText(text);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002013 }
2014
2015 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08002016 * Resets the browser title-view to whatever it must be
2017 * (for example, if we had a loading error)
2018 * When we have a new page, we call resetTitle, when we
2019 * have to reset the titlebar to whatever it used to be
2020 * (for example, if the user chose to stop loading), we
2021 * call resetTitleAndRevertLockIcon.
2022 */
2023 /* package */ void resetTitleAndRevertLockIcon() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002024 mTabControl.getCurrentTab().revertLockIcon();
2025 updateLockIconToLatest();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002026 resetTitleIconAndProgress();
2027 }
2028
2029 /**
2030 * Reset the title, favicon, and progress.
2031 */
2032 private void resetTitleIconAndProgress() {
2033 WebView current = mTabControl.getCurrentWebView();
2034 if (current == null) {
2035 return;
2036 }
2037 resetTitleAndIcon(current);
2038 int progress = current.getProgress();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002039 current.getWebChromeClient().onProgressChanged(current, progress);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002040 }
2041
2042 // Reset the title and the icon based on the given item.
2043 private void resetTitleAndIcon(WebView view) {
2044 WebHistoryItem item = view.copyBackForwardList().getCurrentItem();
2045 if (item != null) {
Leon Scroggins68579392009-09-15 15:31:54 -04002046 setUrlTitle(item.getUrl(), item.getTitle());
The Android Open Source Project0c908882009-03-03 19:32:16 -08002047 setFavicon(item.getFavicon());
2048 } else {
Leon Scroggins68579392009-09-15 15:31:54 -04002049 setUrlTitle(null, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002050 setFavicon(null);
2051 }
2052 }
2053
2054 /**
2055 * Sets a title composed of the URL and the title string.
2056 * @param url The URL of the site being loaded.
2057 * @param title The title of the site being loaded.
2058 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07002059 void setUrlTitle(String url, String title) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002060 mUrl = url;
2061 mTitle = title;
2062
Leon Scroggins58d56c62010-01-28 15:12:40 -05002063 // If we are in voice search mode, the title has already been set.
2064 if (mTabControl.getCurrentTab().isInVoiceSearchMode()) return;
2065 mTitleBar.setDisplayTitle(url);
Michael Kolba2b2ba82010-08-04 17:54:03 -07002066 mFakeTitleBar.setDisplayTitle(url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002067 }
2068
2069 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08002070 * @param url The URL to build a title version of the URL from.
2071 * @return The title version of the URL or null if fails.
2072 * The title version of the URL can be either the URL hostname,
2073 * or the hostname with an "https://" prefix (for secure URLs),
2074 * or an empty string if, for example, the URL in question is a
2075 * file:// URL with no hostname.
2076 */
Leon Scroggins32e14a62009-06-11 10:26:34 -04002077 /* package */ static String buildTitleUrl(String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002078 String titleUrl = null;
2079
2080 if (url != null) {
2081 try {
2082 // parse the url string
2083 URL urlObj = new URL(url);
2084 if (urlObj != null) {
2085 titleUrl = "";
2086
2087 String protocol = urlObj.getProtocol();
2088 String host = urlObj.getHost();
2089
2090 if (host != null && 0 < host.length()) {
2091 titleUrl = host;
2092 if (protocol != null) {
2093 // if a secure site, add an "https://" prefix!
2094 if (protocol.equalsIgnoreCase("https")) {
2095 titleUrl = protocol + "://" + host;
2096 }
2097 }
2098 }
2099 }
2100 } catch (MalformedURLException e) {}
2101 }
2102
2103 return titleUrl;
2104 }
2105
2106 // Set the favicon in the title bar.
Grace Kloba22ac16e2009-10-07 18:00:23 -07002107 void setFavicon(Bitmap icon) {
Leon Scroggins68579392009-09-15 15:31:54 -04002108 mTitleBar.setFavicon(icon);
Michael Kolba2b2ba82010-08-04 17:54:03 -07002109 mFakeTitleBar.setFavicon(icon);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002110 }
2111
2112 /**
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002113 * Close the tab, remove its associated title bar, and adjust mTabControl's
2114 * current tab to a valid value.
Leon Scroggins1f005d32009-08-10 17:36:42 -04002115 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07002116 /* package */ void closeTab(Tab t) {
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002117 int currentIndex = mTabControl.getCurrentIndex();
2118 int removeIndex = mTabControl.getTabIndex(t);
Leon Scroggins1f005d32009-08-10 17:36:42 -04002119 mTabControl.removeTab(t);
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002120 if (currentIndex >= removeIndex && currentIndex != 0) {
2121 currentIndex--;
2122 }
2123 mTabControl.setCurrentTab(mTabControl.getTab(currentIndex));
Andrei Popescua5bf1de2009-09-23 16:39:23 +01002124 resetTitleIconAndProgress();
Leon Scroggins654899b2010-06-25 16:25:23 -04002125 updateLockIconToLatest();
Elliott Slaughtere440a882010-08-20 13:54:45 -07002126
2127 if (!mTabControl.hasAnyOpenIncognitoTabs()) {
2128 WebView.cleanupPrivateBrowsingFiles(this);
2129 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002130 }
2131
Leon Scrogginsdcc5eeb2010-02-23 17:26:37 -05002132 /* package */ void goBackOnePageOrQuit() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002133 Tab current = mTabControl.getCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002134 if (current == null) {
2135 /*
2136 * Instead of finishing the activity, simply push this to the back
2137 * of the stack and let ActivityManager to choose the foreground
2138 * activity. As BrowserActivity is singleTask, it will be always the
2139 * root of the task. So we can use either true or false for
2140 * moveTaskToBack().
2141 */
2142 moveTaskToBack(true);
Grace Kloba00d85e72009-09-23 18:50:05 -07002143 return;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002144 }
2145 WebView w = current.getWebView();
2146 if (w.canGoBack()) {
2147 w.goBack();
2148 } else {
2149 // Check to see if we are closing a window that was created by
2150 // another window. If so, we switch back to that window.
Grace Kloba22ac16e2009-10-07 18:00:23 -07002151 Tab parent = current.getParentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002152 if (parent != null) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04002153 switchToTab(mTabControl.getTabIndex(parent));
2154 // Now we close the other tab
2155 closeTab(current);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002156 } else {
2157 if (current.closeOnExit()) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002158 // force the tab's inLoad() to be false as we are going to
2159 // either finish the activity or remove the tab. This will
2160 // ensure pauseWebViewTimers() taking action.
2161 mTabControl.getCurrentTab().clearInLoad();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002162 if (mTabControl.getTabCount() == 1) {
2163 finish();
2164 return;
2165 }
Mike Reed7bfa63b2009-05-28 11:08:32 -04002166 // call pauseWebViewTimers() now, we won't be able to call
2167 // it in onPause() as the WebView won't be valid.
Grace Klobaec1b5ad2009-08-18 08:42:32 -07002168 // Temporarily change mActivityInPause to be true as
2169 // pauseWebViewTimers() will do nothing if mActivityInPause
2170 // is false.
Grace Kloba918e1d72009-08-13 14:55:06 -07002171 boolean savedState = mActivityInPause;
2172 if (savedState) {
Grace Klobaec1b5ad2009-08-18 08:42:32 -07002173 Log.e(LOGTAG, "BrowserActivity is already paused "
2174 + "while handing goBackOnePageOrQuit.");
Grace Kloba918e1d72009-08-13 14:55:06 -07002175 }
2176 mActivityInPause = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -04002177 pauseWebViewTimers();
Grace Kloba918e1d72009-08-13 14:55:06 -07002178 mActivityInPause = savedState;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002179 removeTabFromContentView(current);
2180 mTabControl.removeTab(current);
2181 }
2182 /*
2183 * Instead of finishing the activity, simply push this to the back
2184 * of the stack and let ActivityManager to choose the foreground
2185 * activity. As BrowserActivity is singleTask, it will be always the
2186 * root of the task. So we can use either true or false for
2187 * moveTaskToBack().
2188 */
2189 moveTaskToBack(true);
2190 }
2191 }
2192 }
2193
Grace Kloba22ac16e2009-10-07 18:00:23 -07002194 boolean isMenuDown() {
2195 return mMenuIsDown;
2196 }
2197
Grace Kloba5942df02009-09-18 11:48:29 -07002198 @Override
2199 public boolean onKeyDown(int keyCode, KeyEvent event) {
Leon Scrogginsf65b50d2009-12-08 10:44:28 -05002200 // Even if MENU is already held down, we need to call to super to open
2201 // the IME on long press.
2202 if (KeyEvent.KEYCODE_MENU == keyCode) {
2203 mMenuIsDown = true;
2204 return super.onKeyDown(keyCode, event);
2205 }
Grace Kloba5942df02009-09-18 11:48:29 -07002206 // The default key mode is DEFAULT_KEYS_SEARCH_LOCAL. As the MENU is
2207 // still down, we don't want to trigger the search. Pretend to consume
2208 // the key and do nothing.
2209 if (mMenuIsDown) return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002210
Grace Kloba5942df02009-09-18 11:48:29 -07002211 switch(keyCode) {
Grace Kloba5942df02009-09-18 11:48:29 -07002212 case KeyEvent.KEYCODE_SPACE:
Grace Klobada0fe552009-09-22 18:17:24 -07002213 // WebView/WebTextView handle the keys in the KeyDown. As
2214 // the Activity's shortcut keys are only handled when WebView
2215 // doesn't, have to do it in onKeyDown instead of onKeyUp.
2216 if (event.isShiftPressed()) {
2217 getTopWindow().pageUp(false);
2218 } else {
2219 getTopWindow().pageDown(false);
2220 }
Grace Kloba5942df02009-09-18 11:48:29 -07002221 return true;
2222 case KeyEvent.KEYCODE_BACK:
2223 if (event.getRepeatCount() == 0) {
2224 event.startTracking();
2225 return true;
2226 } else if (mCustomView == null && mActiveTabsPage == null
2227 && event.isLongPress()) {
Michael Kolb68792c82010-08-09 16:39:18 -07002228 bookmarksOrHistoryPicker(true, false);
Grace Kloba5942df02009-09-18 11:48:29 -07002229 return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002230 }
Grace Kloba5942df02009-09-18 11:48:29 -07002231 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002232 }
Grace Kloba5942df02009-09-18 11:48:29 -07002233 return super.onKeyDown(keyCode, event);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002234 }
2235
Grace Kloba5942df02009-09-18 11:48:29 -07002236 @Override
2237 public boolean onKeyUp(int keyCode, KeyEvent event) {
2238 switch(keyCode) {
2239 case KeyEvent.KEYCODE_MENU:
2240 mMenuIsDown = false;
2241 break;
Grace Kloba5942df02009-09-18 11:48:29 -07002242 case KeyEvent.KEYCODE_BACK:
2243 if (event.isTracking() && !event.isCanceled()) {
2244 if (mCustomView != null) {
2245 // if a custom view is showing, hide it
Grace Kloba22ac16e2009-10-07 18:00:23 -07002246 mTabControl.getCurrentWebView().getWebChromeClient()
2247 .onHideCustomView();
Grace Kloba5942df02009-09-18 11:48:29 -07002248 } else if (mActiveTabsPage != null) {
2249 // if tab page is showing, hide it
2250 removeActiveTabPage(true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002251 } else {
Grace Kloba5942df02009-09-18 11:48:29 -07002252 WebView subwindow = mTabControl.getCurrentSubWindow();
2253 if (subwindow != null) {
2254 if (subwindow.canGoBack()) {
2255 subwindow.goBack();
2256 } else {
2257 dismissSubWindow(mTabControl.getCurrentTab());
2258 }
2259 } else {
2260 goBackOnePageOrQuit();
2261 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002262 }
Grace Kloba5942df02009-09-18 11:48:29 -07002263 return true;
2264 }
2265 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002266 }
Grace Kloba5942df02009-09-18 11:48:29 -07002267 return super.onKeyUp(keyCode, event);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002268 }
2269
Leon Scroggins68579392009-09-15 15:31:54 -04002270 /* package */ void stopLoading() {
Ben Murdochb7cc8b42009-09-28 10:59:09 +01002271 mDidStopLoad = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002272 resetTitleAndRevertLockIcon();
2273 WebView w = getTopWindow();
2274 w.stopLoading();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002275 // FIXME: before refactor, it is using mWebViewClient. So I keep the
2276 // same logic here. But for subwindow case, should we call into the main
2277 // WebView's onPageFinished as we never call its onPageStarted and if
2278 // the page finishes itself, we don't call onPageFinished.
2279 mTabControl.getCurrentWebView().getWebViewClient().onPageFinished(w,
2280 w.getUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08002281
2282 cancelStopToast();
2283 mStopToast = Toast
2284 .makeText(this, R.string.stopping, Toast.LENGTH_SHORT);
2285 mStopToast.show();
2286 }
2287
Grace Kloba22ac16e2009-10-07 18:00:23 -07002288 boolean didUserStopLoading() {
2289 return mDidStopLoad;
2290 }
2291
The Android Open Source Project0c908882009-03-03 19:32:16 -08002292 private void cancelStopToast() {
2293 if (mStopToast != null) {
2294 mStopToast.cancel();
2295 mStopToast = null;
2296 }
2297 }
2298
Grace Kloba22ac16e2009-10-07 18:00:23 -07002299 // called by a UI or non-UI thread to post the message
2300 public void postMessage(int what, int arg1, int arg2, Object obj,
2301 long delayMillis) {
2302 mHandler.sendMessageDelayed(mHandler.obtainMessage(what, arg1, arg2,
2303 obj), delayMillis);
2304 }
2305
2306 // called by a UI or non-UI thread to remove the message
2307 void removeMessages(int what, Object object) {
2308 mHandler.removeMessages(what, object);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002309 }
2310
2311 // public message ids
2312 public final static int LOAD_URL = 1001;
2313 public final static int STOP_LOAD = 1002;
2314
2315 // Message Ids
2316 private static final int FOCUS_NODE_HREF = 102;
Grace Kloba92c18a52009-07-31 23:48:32 -07002317 private static final int RELEASE_WAKELOCK = 107;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002318
Grace Kloba22ac16e2009-10-07 18:00:23 -07002319 static final int UPDATE_BOOKMARK_THUMBNAIL = 108;
Ben Murdoch2694e232009-09-29 09:41:11 +01002320
Ben Murdocheecb4e62010-07-06 16:30:38 +01002321 private static final int TOUCH_ICON_DOWNLOADED = 109;
2322
Michael Kolb300b7f02010-08-25 13:47:24 -07002323 private static final int OPEN_BOOKMARKS = 201;
2324
The Android Open Source Project0c908882009-03-03 19:32:16 -08002325 // Private handler for handling javascript and saving passwords
2326 private Handler mHandler = new Handler() {
2327
Michael Kolbe0a36662010-06-29 10:37:12 -07002328 @Override
The Android Open Source Project0c908882009-03-03 19:32:16 -08002329 public void handleMessage(Message msg) {
2330 switch (msg.what) {
Michael Kolb300b7f02010-08-25 13:47:24 -07002331 case OPEN_BOOKMARKS:
2332 bookmarksOrHistoryPicker(false, false);
2333 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002334 case FOCUS_NODE_HREF:
Ben Murdoch2694e232009-09-29 09:41:11 +01002335 {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002336 String url = (String) msg.getData().get("url");
Ben Murdoch90d088c2009-11-17 18:14:04 +00002337 String title = (String) msg.getData().get("title");
The Android Open Source Project0c908882009-03-03 19:32:16 -08002338 if (url == null || url.length() == 0) {
2339 break;
2340 }
2341 HashMap focusNodeMap = (HashMap) msg.obj;
2342 WebView view = (WebView) focusNodeMap.get("webview");
2343 // Only apply the action if the top window did not change.
2344 if (getTopWindow() != view) {
2345 break;
2346 }
2347 switch (msg.arg1) {
2348 case R.id.open_context_menu_id:
2349 case R.id.view_image_context_menu_id:
Leon Scroggins92472e82010-02-17 16:32:28 -05002350 loadUrlFromContext(getTopWindow(), url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002351 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002352 case R.id.bookmark_context_menu_id:
2353 Intent intent = new Intent(BrowserActivity.this,
2354 AddBookmarkPage.class);
2355 intent.putExtra("url", url);
Ben Murdoch90d088c2009-11-17 18:14:04 +00002356 intent.putExtra("title", title);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002357 startActivity(intent);
2358 break;
2359 case R.id.share_link_context_menu_id:
Leon Scroggins3e204452010-05-10 11:06:03 -04002360 sharePage(BrowserActivity.this, title, url, null,
Leon Scroggins96afcb12009-12-10 12:35:56 -05002361 null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002362 break;
2363 case R.id.copy_link_context_menu_id:
2364 copy(url);
2365 break;
2366 case R.id.save_link_context_menu_id:
2367 case R.id.download_context_menu_id:
2368 onDownloadStartNoStream(url, null, null, null, -1);
2369 break;
2370 }
2371 break;
Ben Murdoch2694e232009-09-29 09:41:11 +01002372 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002373
2374 case LOAD_URL:
Leon Scroggins92472e82010-02-17 16:32:28 -05002375 loadUrlFromContext(getTopWindow(), (String) msg.obj);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002376 break;
2377
2378 case STOP_LOAD:
2379 stopLoading();
2380 break;
2381
The Android Open Source Project0c908882009-03-03 19:32:16 -08002382 case RELEASE_WAKELOCK:
2383 if (mWakeLock.isHeld()) {
2384 mWakeLock.release();
Grace Kloba5d0e02e2009-10-05 15:15:36 -07002385 // if we reach here, Browser should be still in the
2386 // background loading after WAKELOCK_TIMEOUT (5-min).
2387 // To avoid burning the battery, stop loading.
2388 mTabControl.stopAllLoading();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002389 }
2390 break;
Ben Murdoch2694e232009-09-29 09:41:11 +01002391
2392 case UPDATE_BOOKMARK_THUMBNAIL:
2393 WebView view = (WebView) msg.obj;
2394 if (view != null) {
2395 updateScreenshot(view);
2396 }
2397 break;
Ben Murdocheecb4e62010-07-06 16:30:38 +01002398
2399 case TOUCH_ICON_DOWNLOADED:
2400 Bundle b = msg.getData();
2401 showSaveToHomescreenDialog(b.getString("url"),
2402 b.getString("title"),
2403 (Bitmap) b.getParcelable("touchIcon"),
2404 (Bitmap) b.getParcelable("favicon"));
2405 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002406 }
2407 }
2408 };
2409
Leon Scroggins96afcb12009-12-10 12:35:56 -05002410 /**
2411 * Share a page, providing the title, url, favicon, and a screenshot. Uses
2412 * an {@link Intent} to launch the Activity chooser.
2413 * @param c Context used to launch a new Activity.
2414 * @param title Title of the page. Stored in the Intent with
Paul Westbrook03e6d392010-02-12 10:33:29 -08002415 * {@link Intent#EXTRA_SUBJECT}
Leon Scroggins96afcb12009-12-10 12:35:56 -05002416 * @param url URL of the page. Stored in the Intent with
2417 * {@link Intent#EXTRA_TEXT}
2418 * @param favicon Bitmap of the favicon for the page. Stored in the Intent
2419 * with {@link Browser#EXTRA_SHARE_FAVICON}
2420 * @param screenshot Bitmap of a screenshot of the page. Stored in the
2421 * Intent with {@link Browser#EXTRA_SHARE_SCREENSHOT}
2422 */
2423 public static final void sharePage(Context c, String title, String url,
2424 Bitmap favicon, Bitmap screenshot) {
2425 Intent send = new Intent(Intent.ACTION_SEND);
2426 send.setType("text/plain");
2427 send.putExtra(Intent.EXTRA_TEXT, url);
Paul Westbrook03e6d392010-02-12 10:33:29 -08002428 send.putExtra(Intent.EXTRA_SUBJECT, title);
Leon Scroggins96afcb12009-12-10 12:35:56 -05002429 send.putExtra(Browser.EXTRA_SHARE_FAVICON, favicon);
2430 send.putExtra(Browser.EXTRA_SHARE_SCREENSHOT, screenshot);
2431 try {
2432 c.startActivity(Intent.createChooser(send, c.getString(
2433 R.string.choosertitle_sharevia)));
2434 } catch(android.content.ActivityNotFoundException ex) {
2435 // if no app handles it, do nothing
2436 }
2437 }
2438
Leon Scroggins89c6d362009-07-15 16:54:37 -04002439 private void updateScreenshot(WebView view) {
2440 // If this is a bookmarked site, add a screenshot to the database.
2441 // FIXME: When should we update? Every time?
2442 // FIXME: Would like to make sure there is actually something to
2443 // draw, but the API for that (WebViewCore.pictureReady()) is not
2444 // currently accessible here.
Ben Murdochaac7aa62009-09-17 16:57:40 +01002445
Ben Murdoch87cc65d2010-06-29 20:34:10 +01002446 final Bitmap bm = createScreenshot(view, getDesiredThumbnailWidth(this),
2447 getDesiredThumbnailHeight(this));
Patrick Scottcb192b52010-04-14 14:38:55 -04002448 if (bm == null) {
2449 return;
Leon Scroggins89c6d362009-07-15 16:54:37 -04002450 }
Patrick Scottcb192b52010-04-14 14:38:55 -04002451
2452 final ContentResolver cr = getContentResolver();
2453 final String url = view.getUrl();
2454 final String originalUrl = view.getOriginalUrl();
2455
2456 new AsyncTask<Void, Void, Void>() {
2457 @Override
2458 protected Void doInBackground(Void... unused) {
2459 Cursor c = null;
2460 try {
Jeff Hamilton84029622010-08-05 14:29:28 -05002461 c = Bookmarks.queryBookmarksForUrl(
Jeff Hamilton8ce956c2010-08-17 11:13:53 -05002462 cr, originalUrl, url);
Patrick Scottcb192b52010-04-14 14:38:55 -04002463 if (c != null) {
2464 if (c.moveToFirst()) {
2465 ContentValues values = new ContentValues();
2466 final ByteArrayOutputStream os
2467 = new ByteArrayOutputStream();
2468 bm.compress(Bitmap.CompressFormat.PNG, 100, os);
Jeff Hamilton8ce956c2010-08-17 11:13:53 -05002469 values.put(BrowserContract.Bookmarks.THUMBNAIL,
Patrick Scottcb192b52010-04-14 14:38:55 -04002470 os.toByteArray());
2471 do {
2472 cr.update(ContentUris.withAppendedId(
Jeff Hamilton8ce956c2010-08-17 11:13:53 -05002473 BrowserContract.Bookmarks.CONTENT_URI, c.getLong(0)),
Patrick Scottcb192b52010-04-14 14:38:55 -04002474 values, null, null);
2475 } while (c.moveToNext());
2476 }
2477 }
2478 } catch (IllegalStateException e) {
2479 // Ignore
2480 } finally {
2481 if (c != null) c.close();
2482 }
2483 return null;
2484 }
2485 }.execute();
Leon Scroggins89c6d362009-07-15 16:54:37 -04002486 }
2487
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002488 /**
Leon Scrogginsf8551612009-09-24 16:06:02 -04002489 * Return the desired width for thumbnail screenshots, which are stored in
2490 * the database, and used on the bookmarks screen.
2491 * @param context Context for finding out the density of the screen.
Jeff Hamiltonf3026372010-08-19 00:12:27 -05002492 * @return desired width for thumbnail screenshot.
Leon Scrogginsf8551612009-09-24 16:06:02 -04002493 */
2494 /* package */ static int getDesiredThumbnailWidth(Context context) {
Jeff Hamiltonf3026372010-08-19 00:12:27 -05002495 return context.getResources().getDimensionPixelOffset(R.dimen.bookmarkThumbnailWidth);
Leon Scrogginsf8551612009-09-24 16:06:02 -04002496 }
2497
2498 /**
2499 * Return the desired height for thumbnail screenshots, which are stored in
2500 * the database, and used on the bookmarks screen.
2501 * @param context Context for finding out the density of the screen.
Jeff Hamiltonf3026372010-08-19 00:12:27 -05002502 * @return desired height for thumbnail screenshot.
Leon Scrogginsf8551612009-09-24 16:06:02 -04002503 */
2504 /* package */ static int getDesiredThumbnailHeight(Context context) {
Jeff Hamiltonf3026372010-08-19 00:12:27 -05002505 return context.getResources().getDimensionPixelOffset(R.dimen.bookmarkThumbnailHeight);
Leon Scrogginsf8551612009-09-24 16:06:02 -04002506 }
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002507
Ben Murdoch87cc65d2010-06-29 20:34:10 +01002508 private Bitmap createScreenshot(WebView view, int width, int height) {
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002509 Picture thumbnail = view.capturePicture();
Leon Scroggins45800572009-09-29 16:38:47 -04002510 if (thumbnail == null) {
2511 return null;
2512 }
Ben Murdoch87cc65d2010-06-29 20:34:10 +01002513 Bitmap bm = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002514 Canvas canvas = new Canvas(bm);
2515 // May need to tweak these values to determine what is the
2516 // best scale factor
Ben Murdoch2694e232009-09-29 09:41:11 +01002517 int thumbnailWidth = thumbnail.getWidth();
Ben Murdochae59c3f2009-10-20 18:30:28 +01002518 int thumbnailHeight = thumbnail.getHeight();
2519 float scaleFactorX = 1.0f;
2520 float scaleFactorY = 1.0f;
Ben Murdoch2694e232009-09-29 09:41:11 +01002521 if (thumbnailWidth > 0) {
Ben Murdoch87cc65d2010-06-29 20:34:10 +01002522 scaleFactorX = (float) width / (float)thumbnailWidth;
Ben Murdochae59c3f2009-10-20 18:30:28 +01002523 } else {
2524 return null;
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002525 }
Ben Murdochae59c3f2009-10-20 18:30:28 +01002526
2527 if (view.getWidth() > view.getHeight() &&
2528 thumbnailHeight < view.getHeight() && thumbnailHeight > 0) {
2529 // If the device is in landscape and the page is shorter
2530 // than the height of the view, stretch the thumbnail to fill the
2531 // space.
Ben Murdoch87cc65d2010-06-29 20:34:10 +01002532 scaleFactorY = (float) height / (float)thumbnailHeight;
Ben Murdochae59c3f2009-10-20 18:30:28 +01002533 } else {
2534 // In the portrait case, this looks nice.
2535 scaleFactorY = scaleFactorX;
2536 }
2537
2538 canvas.scale(scaleFactorX, scaleFactorY);
2539
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002540 thumbnail.draw(canvas);
2541 return bm;
2542 }
2543
The Android Open Source Project0c908882009-03-03 19:32:16 -08002544 // -------------------------------------------------------------------------
Grace Kloba22ac16e2009-10-07 18:00:23 -07002545 // Helper function for WebViewClient.
The Android Open Source Project0c908882009-03-03 19:32:16 -08002546 //-------------------------------------------------------------------------
2547
2548 // Use in overrideUrlLoading
2549 /* package */ final static String SCHEME_WTAI = "wtai://wp/";
2550 /* package */ final static String SCHEME_WTAI_MC = "wtai://wp/mc;";
2551 /* package */ final static String SCHEME_WTAI_SD = "wtai://wp/sd;";
2552 /* package */ final static String SCHEME_WTAI_AP = "wtai://wp/ap;";
2553
Leon Scroggins92472e82010-02-17 16:32:28 -05002554 // Keep this initial progress in sync with initialProgressValue (* 100)
2555 // in ProgressTracker.cpp
2556 private final static int INITIAL_PROGRESS = 10;
2557
Grace Kloba22ac16e2009-10-07 18:00:23 -07002558 void onPageStarted(WebView view, String url, Bitmap favicon) {
2559 // when BrowserActivity just starts, onPageStarted may be called before
2560 // onResume as it is triggered from onCreate. Call resumeWebViewTimers
2561 // to start the timer. As we won't switch tabs while an activity is in
2562 // pause state, we can ensure calling resume and pause in pair.
2563 if (mActivityInPause) resumeWebViewTimers();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002564
Grace Kloba22ac16e2009-10-07 18:00:23 -07002565 resetLockIcon(url);
2566 setUrlTitle(url, null);
2567 setFavicon(favicon);
Leon Scroggins8cf8f682009-11-04 11:13:50 -08002568 // Show some progress so that the user knows the page is beginning to
2569 // load
Leon Scroggins92472e82010-02-17 16:32:28 -05002570 onProgressChanged(view, INITIAL_PROGRESS);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002571 mDidStopLoad = false;
Grace Kloba22ac16e2009-10-07 18:00:23 -07002572 if (!mIsNetworkUp) createAndShowNetworkDialog();
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04002573 endActionMode();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002574 if (mSettings.isTracing()) {
2575 String host;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002576 try {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002577 WebAddress uri = new WebAddress(url);
2578 host = uri.mHost;
2579 } catch (android.net.ParseException ex) {
2580 host = "browser";
The Android Open Source Project0c908882009-03-03 19:32:16 -08002581 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002582 host = host.replace('.', '_');
2583 host += ".trace";
2584 mInTrace = true;
2585 Debug.startMethodTracing(host, 20 * 1024 * 1024);
2586 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002587
Grace Kloba22ac16e2009-10-07 18:00:23 -07002588 // Performance probe
2589 if (false) {
2590 mStart = SystemClock.uptimeMillis();
2591 mProcessStart = Process.getElapsedCpuTime();
2592 long[] sysCpu = new long[7];
2593 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2594 sysCpu, null)) {
2595 mUserStart = sysCpu[0] + sysCpu[1];
2596 mSystemStart = sysCpu[2];
2597 mIdleStart = sysCpu[3];
2598 mIrqStart = sysCpu[4] + sysCpu[5] + sysCpu[6];
2599 }
2600 mUiStart = SystemClock.currentThreadTimeMillis();
2601 }
2602 }
2603
2604 void onPageFinished(WebView view, String url) {
2605 // Reset the title and icon in case we stopped a provisional load.
2606 resetTitleAndIcon(view);
2607 // Update the lock icon image only once we are done loading
2608 updateLockIconToLatest();
2609 // pause the WebView timer and release the wake lock if it is finished
2610 // while BrowserActivity is in pause state.
2611 if (mActivityInPause && pauseWebViewTimers()) {
2612 if (mWakeLock.isHeld()) {
2613 mHandler.removeMessages(RELEASE_WAKELOCK);
2614 mWakeLock.release();
2615 }
2616 }
2617
2618 // Performance probe
2619 if (false) {
2620 long[] sysCpu = new long[7];
2621 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2622 sysCpu, null)) {
2623 String uiInfo = "UI thread used "
2624 + (SystemClock.currentThreadTimeMillis() - mUiStart)
2625 + " ms";
2626 if (LOGD_ENABLED) {
2627 Log.d(LOGTAG, uiInfo);
2628 }
2629 //The string that gets written to the log
2630 String performanceString = "It took total "
2631 + (SystemClock.uptimeMillis() - mStart)
2632 + " ms clock time to load the page."
2633 + "\nbrowser process used "
2634 + (Process.getElapsedCpuTime() - mProcessStart)
2635 + " ms, user processes used "
2636 + (sysCpu[0] + sysCpu[1] - mUserStart) * 10
2637 + " ms, kernel used "
2638 + (sysCpu[2] - mSystemStart) * 10
2639 + " ms, idle took " + (sysCpu[3] - mIdleStart) * 10
2640 + " ms and irq took "
2641 + (sysCpu[4] + sysCpu[5] + sysCpu[6] - mIrqStart)
2642 * 10 + " ms, " + uiInfo;
2643 if (LOGD_ENABLED) {
2644 Log.d(LOGTAG, performanceString + "\nWebpage: " + url);
2645 }
2646 if (url != null) {
2647 // strip the url to maintain consistency
2648 String newUrl = new String(url);
2649 if (newUrl.startsWith("http://www.")) {
2650 newUrl = newUrl.substring(11);
2651 } else if (newUrl.startsWith("http://")) {
2652 newUrl = newUrl.substring(7);
2653 } else if (newUrl.startsWith("https://www.")) {
2654 newUrl = newUrl.substring(12);
2655 } else if (newUrl.startsWith("https://")) {
2656 newUrl = newUrl.substring(8);
2657 }
2658 if (LOGD_ENABLED) {
2659 Log.d(LOGTAG, newUrl + " loaded");
2660 }
Grace Kloba5b078b52009-06-24 20:23:41 -07002661 }
2662 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002663 }
Grace Kloba5b078b52009-06-24 20:23:41 -07002664
Grace Kloba22ac16e2009-10-07 18:00:23 -07002665 if (mInTrace) {
2666 mInTrace = false;
2667 Debug.stopMethodTracing();
2668 }
2669 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002670
Grace Klobae7fe26b2010-06-28 16:23:33 -07002671 private void closeEmptyChildTab() {
2672 Tab current = mTabControl.getCurrentTab();
2673 if (current != null
2674 && current.getWebView().copyBackForwardList().getSize() == 0) {
2675 Tab parent = current.getParentTab();
2676 if (parent != null) {
2677 switchToTab(mTabControl.getTabIndex(parent));
2678 closeTab(current);
2679 }
2680 }
2681 }
2682
Grace Kloba22ac16e2009-10-07 18:00:23 -07002683 boolean shouldOverrideUrlLoading(WebView view, String url) {
Jeff Hamilton47654f42010-09-07 09:57:51 -05002684 if (view.isPrivateBrowsingEnabled()) {
2685 // Don't allow urls to leave the browser app when in private browsing mode
2686 loadUrl(view, url);
2687 return true;
2688 }
2689
Grace Kloba22ac16e2009-10-07 18:00:23 -07002690 if (url.startsWith(SCHEME_WTAI)) {
2691 // wtai://wp/mc;number
2692 // number=string(phone-number)
2693 if (url.startsWith(SCHEME_WTAI_MC)) {
2694 Intent intent = new Intent(Intent.ACTION_VIEW,
2695 Uri.parse(WebView.SCHEME_TEL +
2696 url.substring(SCHEME_WTAI_MC.length())));
2697 startActivity(intent);
Grace Klobae7fe26b2010-06-28 16:23:33 -07002698 // before leaving BrowserActivity, close the empty child tab.
2699 // If a new tab is created through JavaScript open to load this
2700 // url, we would like to close it as we will load this url in a
2701 // different Activity.
2702 closeEmptyChildTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002703 return true;
2704 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002705 // wtai://wp/sd;dtmf
2706 // dtmf=string(dialstring)
2707 if (url.startsWith(SCHEME_WTAI_SD)) {
2708 // TODO: only send when there is active voice connection
2709 return false;
2710 }
2711 // wtai://wp/ap;number;name
2712 // number=string(phone-number)
2713 // name=string
2714 if (url.startsWith(SCHEME_WTAI_AP)) {
2715 // TODO
2716 return false;
2717 }
2718 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002719
Grace Kloba22ac16e2009-10-07 18:00:23 -07002720 // The "about:" schemes are internal to the browser; don't want these to
2721 // be dispatched to other apps.
2722 if (url.startsWith("about:")) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002723 return false;
2724 }
2725
Jeff Davidson43610292010-07-16 16:03:58 -07002726 // If this is a Google search, attempt to add an RLZ string (if one isn't already present).
2727 if (rlzProviderPresent()) {
2728 Uri siteUri = Uri.parse(url);
2729 if (needsRlzString(siteUri)) {
2730 String rlz = null;
2731 Cursor cur = null;
2732 try {
2733 cur = getContentResolver().query(getRlzUri(), null, null, null, null);
2734 if (cur != null && cur.moveToFirst() && !cur.isNull(0)) {
2735 url = siteUri.buildUpon()
2736 .appendQueryParameter("rlz", cur.getString(0))
2737 .build().toString();
2738 }
2739 } finally {
2740 if (cur != null) {
2741 cur.close();
2742 }
2743 }
2744 loadUrl(view, url);
2745 return true;
2746 }
2747 }
2748
Grace Kloba22ac16e2009-10-07 18:00:23 -07002749 Intent intent;
2750 // perform generic parsing of the URI to turn it into an Intent.
2751 try {
2752 intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME);
2753 } catch (URISyntaxException ex) {
2754 Log.w("Browser", "Bad URI " + url + ": " + ex.getMessage());
2755 return false;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002756 }
2757
Grace Kloba22ac16e2009-10-07 18:00:23 -07002758 // check whether the intent can be resolved. If not, we will see
2759 // whether we can download it from the Market.
2760 if (getPackageManager().resolveActivity(intent, 0) == null) {
2761 String packagename = intent.getPackage();
2762 if (packagename != null) {
2763 intent = new Intent(Intent.ACTION_VIEW, Uri
2764 .parse("market://search?q=pname:" + packagename));
2765 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2766 startActivity(intent);
Grace Klobae7fe26b2010-06-28 16:23:33 -07002767 // before leaving BrowserActivity, close the empty child tab.
2768 // If a new tab is created through JavaScript open to load this
2769 // url, we would like to close it as we will load this url in a
2770 // different Activity.
2771 closeEmptyChildTab();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002772 return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002773 } else {
2774 return false;
2775 }
2776 }
2777
Grace Kloba22ac16e2009-10-07 18:00:23 -07002778 // sanitize the Intent, ensuring web pages can not bypass browser
2779 // security (only access to BROWSABLE activities).
2780 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2781 intent.setComponent(null);
2782 try {
2783 if (startActivityIfNeeded(intent, -1)) {
Grace Klobae7fe26b2010-06-28 16:23:33 -07002784 // before leaving BrowserActivity, close the empty child tab.
2785 // If a new tab is created through JavaScript open to load this
2786 // url, we would like to close it as we will load this url in a
2787 // different Activity.
2788 closeEmptyChildTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002789 return true;
2790 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002791 } catch (ActivityNotFoundException ex) {
2792 // ignore the error. If no application can handle the URL,
2793 // eg about:blank, assume the browser can handle it.
2794 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002795
Grace Kloba22ac16e2009-10-07 18:00:23 -07002796 if (mMenuIsDown) {
Michael Kolb68792c82010-08-09 16:39:18 -07002797 openTab(url, false);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002798 closeOptionsMenu();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002799 return true;
2800 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002801 return false;
2802 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002803
Jeff Davidson43610292010-07-16 16:03:58 -07002804 // Determine whether the RLZ provider is present on the system.
2805 private boolean rlzProviderPresent() {
2806 if (mIsProviderPresent == null) {
2807 PackageManager pm = getPackageManager();
2808 mIsProviderPresent = pm.resolveContentProvider(BrowserSettings.RLZ_PROVIDER, 0) != null;
2809 }
2810 return mIsProviderPresent;
2811 }
2812
2813 // Retrieve the RLZ access point string and cache the URI used to retrieve RLZ values.
2814 private Uri getRlzUri() {
2815 if (mRlzUri == null) {
2816 String ap = getResources().getString(R.string.rlz_access_point);
2817 mRlzUri = Uri.withAppendedPath(BrowserSettings.RLZ_PROVIDER_URI, ap);
2818 }
2819 return mRlzUri;
2820 }
2821
2822 // Determine if this URI appears to be for a Google search and does not have an RLZ parameter.
2823 // Taken largely from Chrome source, src/chrome/browser/google_url_tracker.cc
2824 private static boolean needsRlzString(Uri uri) {
Bill Napierc50e71a2010-08-27 14:03:03 -07002825 String scheme = uri.getScheme();
2826 if (("http".equals(scheme) || "https".equals(scheme)) &&
2827 (uri.getQueryParameter("q") != null) && (uri.getQueryParameter("rlz") == null)) {
Jeff Davidson43610292010-07-16 16:03:58 -07002828 String host = uri.getHost();
2829 if (host == null) {
2830 return false;
2831 }
2832 String[] hostComponents = host.split("\\.");
2833
2834 if (hostComponents.length < 2) {
2835 return false;
2836 }
2837 int googleComponent = hostComponents.length - 2;
2838 String component = hostComponents[googleComponent];
2839 if (!"google".equals(component)) {
2840 if (hostComponents.length < 3 ||
2841 (!"co".equals(component) && !"com".equals(component))) {
2842 return false;
2843 }
2844 googleComponent = hostComponents.length - 3;
2845 if (!"google".equals(hostComponents[googleComponent])) {
2846 return false;
2847 }
2848 }
2849
2850 // Google corp network handling.
2851 if (googleComponent > 0 && "corp".equals(hostComponents[googleComponent - 1])) {
2852 return false;
2853 }
2854
2855 return true;
2856 }
2857 return false;
2858 }
2859
Grace Kloba22ac16e2009-10-07 18:00:23 -07002860 // -------------------------------------------------------------------------
2861 // Helper function for WebChromeClient
2862 // -------------------------------------------------------------------------
The Android Open Source Project0c908882009-03-03 19:32:16 -08002863
Grace Kloba22ac16e2009-10-07 18:00:23 -07002864 void onProgressChanged(WebView view, int newProgress) {
Michael Kolba2b2ba82010-08-04 17:54:03 -07002865
2866 // On the phone, the fake title bar will always cover up the
2867 // regular title bar (or the regular one is offscreen), so only the
2868 // fake title bar needs to change its progress
2869 mFakeTitleBar.setProgress(newProgress);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002870
Grace Kloba22ac16e2009-10-07 18:00:23 -07002871 if (newProgress == 100) {
2872 // onProgressChanged() may continue to be called after the main
2873 // frame has finished loading, as any remaining sub frames continue
2874 // to load. We'll only get called once though with newProgress as
2875 // 100 when everything is loaded. (onPageFinished is called once
2876 // when the main frame completes loading regardless of the state of
2877 // any sub frames so calls to onProgressChanges may continue after
2878 // onPageFinished has executed)
2879 if (mInLoad) {
2880 mInLoad = false;
Leon Scrogginsa27ff192009-09-14 12:58:04 -04002881 updateInLoadMenuItems();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002882 // If the options menu is open, leave the title bar
2883 if (!mOptionsMenuOpen || !mIconView) {
2884 hideFakeTitleBar();
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07002885 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002886 }
Leon Scrogginsaa37e7f2010-03-05 11:51:20 -05002887 } else {
2888 if (!mInLoad) {
2889 // onPageFinished may have already been called but a subframe is
2890 // still loading and updating the progress. Reset mInLoad and
2891 // update the menu items.
2892 mInLoad = true;
2893 updateInLoadMenuItems();
2894 }
2895 // When the page first begins to load, the Activity may still be
2896 // paused, in which case showFakeTitleBar will do nothing. Call
2897 // again as the page continues to load so that it will be shown.
2898 // (Calling it will the fake title bar is already showing will also
2899 // do nothing.
Grace Kloba22ac16e2009-10-07 18:00:23 -07002900 if (!mOptionsMenuOpen || mIconView) {
2901 // This page has begun to load, so show the title bar
2902 showFakeTitleBar();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002903 }
2904 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002905 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002906
Grace Kloba22ac16e2009-10-07 18:00:23 -07002907 void onShowCustomView(View view, WebChromeClient.CustomViewCallback callback) {
Derek Sollenberger8ff57db2009-12-08 15:39:55 -05002908 // if a view already exists then immediately terminate the new one
2909 if (mCustomView != null) {
2910 callback.onCustomViewHidden();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002911 return;
Derek Sollenberger8ff57db2009-12-08 15:39:55 -05002912 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002913
2914 // Add the custom view to its container.
2915 mCustomViewContainer.addView(view, COVER_SCREEN_GRAVITY_CENTER);
2916 mCustomView = view;
2917 mCustomViewCallback = callback;
2918 // Save the menu state and set it to empty while the custom
2919 // view is showing.
2920 mOldMenuState = mMenuState;
2921 mMenuState = EMPTY_MENU;
2922 // Hide the content view.
2923 mContentView.setVisibility(View.GONE);
2924 // Finally show the custom view container.
Andrei Popescu163ab742009-10-20 17:58:23 +01002925 setStatusBarVisibility(false);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002926 mCustomViewContainer.setVisibility(View.VISIBLE);
2927 mCustomViewContainer.bringToFront();
2928 }
2929
2930 void onHideCustomView() {
2931 if (mCustomView == null)
2932 return;
2933
2934 // Hide the custom view.
2935 mCustomView.setVisibility(View.GONE);
2936 // Remove the custom view from its container.
2937 mCustomViewContainer.removeView(mCustomView);
2938 mCustomView = null;
2939 // Reset the old menu state.
2940 mMenuState = mOldMenuState;
2941 mOldMenuState = EMPTY_MENU;
2942 mCustomViewContainer.setVisibility(View.GONE);
2943 mCustomViewCallback.onCustomViewHidden();
2944 // Show the content view.
Andrei Popescu163ab742009-10-20 17:58:23 +01002945 setStatusBarVisibility(true);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002946 mContentView.setVisibility(View.VISIBLE);
2947 }
2948
2949 Bitmap getDefaultVideoPoster() {
2950 if (mDefaultVideoPoster == null) {
2951 mDefaultVideoPoster = BitmapFactory.decodeResource(
2952 getResources(), R.drawable.default_video_poster);
Patrick Scott3918d442009-08-04 13:22:29 -04002953 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002954 return mDefaultVideoPoster;
2955 }
Patrick Scott3918d442009-08-04 13:22:29 -04002956
Grace Kloba22ac16e2009-10-07 18:00:23 -07002957 View getVideoLoadingProgressView() {
2958 if (mVideoProgressView == null) {
2959 LayoutInflater inflater = LayoutInflater.from(BrowserActivity.this);
2960 mVideoProgressView = inflater.inflate(
2961 R.layout.video_loading_progress, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002962 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002963 return mVideoProgressView;
2964 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002965
Leon Scroggins8d5fa432009-10-02 15:55:59 -04002966 /*
2967 * The Object used to inform the WebView of the file to upload.
2968 */
2969 private ValueCallback<Uri> mUploadMessage;
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002970 private String mCameraFilePath;
Leon Scroggins8d5fa432009-10-02 15:55:59 -04002971
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002972 void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
2973
2974 final String imageMimeType = "image/*";
Ben Murdoch6af492a2010-06-15 12:38:17 +01002975 final String videoMimeType = "video/*";
Ben Murdoch039bd472010-07-21 21:26:57 +01002976 final String audioMimeType = "audio/*";
Ben Murdochb50d7402010-07-16 12:42:22 +01002977 final String mediaSourceKey = "capture";
Ben Murdoch6af492a2010-06-15 12:38:17 +01002978 final String mediaSourceValueCamera = "camera";
Ben Murdochb50d7402010-07-16 12:42:22 +01002979 final String mediaSourceValueFileSystem = "filesystem";
Ben Murdoch6af492a2010-06-15 12:38:17 +01002980 final String mediaSourceValueCamcorder = "camcorder";
Ben Murdoch039bd472010-07-21 21:26:57 +01002981 final String mediaSourceValueMicrophone = "microphone";
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002982
Ben Murdoch039bd472010-07-21 21:26:57 +01002983 // media source can be 'filesystem' or 'camera' or 'camcorder' or 'microphone'.
Ben Murdoch6af492a2010-06-15 12:38:17 +01002984 String mediaSource = "";
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002985
Ben Murdoch6af492a2010-06-15 12:38:17 +01002986 // We add the camera intent if there was no accept type (or '*/*' or 'image/*').
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002987 boolean addCameraIntent = true;
Ben Murdoch6af492a2010-06-15 12:38:17 +01002988 // We add the camcorder intent if there was no accept type (or '*/*' or 'video/*').
2989 boolean addCamcorderIntent = true;
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002990
Ben Murdoch6af492a2010-06-15 12:38:17 +01002991 if (mUploadMessage != null) {
2992 // Already a file picker operation in progress.
2993 return;
2994 }
2995
Grace Kloba22ac16e2009-10-07 18:00:23 -07002996 mUploadMessage = uploadMsg;
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002997
2998 // Parse the accept type.
2999 String params[] = acceptType.split(";");
3000 String mimeType = params[0];
3001
3002 for (String p : params) {
3003 String[] keyValue = p.split("=");
3004 if (keyValue.length == 2) {
3005 // Process key=value parameters.
Ben Murdoch6af492a2010-06-15 12:38:17 +01003006 if (mediaSourceKey.equals(keyValue[0])) {
3007 mediaSource = keyValue[1];
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003008 }
3009 }
3010 }
3011
3012 // This intent will display the standard OPENABLE file picker.
Grace Kloba22ac16e2009-10-07 18:00:23 -07003013 Intent i = new Intent(Intent.ACTION_GET_CONTENT);
3014 i.addCategory(Intent.CATEGORY_OPENABLE);
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003015
3016 // Create an intent to add to the standard file picker that will
3017 // capture an image from the camera. We'll combine this intent with
3018 // the standard OPENABLE picker unless the web developer specifically
3019 // requested the camera or gallery be opened by passing a parameter
3020 // in the accept type.
3021 Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
3022 File externalDataDir = Environment.getExternalStoragePublicDirectory(
3023 Environment.DIRECTORY_DCIM);
3024 File cameraDataDir = new File(externalDataDir.getAbsolutePath() +
3025 File.separator + "browser-photos");
3026 cameraDataDir.mkdirs();
3027 mCameraFilePath = cameraDataDir.getAbsolutePath() + File.separator +
3028 System.currentTimeMillis() + ".jpg";
3029 cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(mCameraFilePath)));
3030
Ben Murdoch6af492a2010-06-15 12:38:17 +01003031 Intent camcorderIntent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
3032
Ben Murdoch039bd472010-07-21 21:26:57 +01003033 Intent soundRecIntent = new Intent(MediaStore.Audio.Media.RECORD_SOUND_ACTION);
3034
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003035 if (mimeType.equals(imageMimeType)) {
3036 i.setType(imageMimeType);
Ben Murdoch6af492a2010-06-15 12:38:17 +01003037 addCamcorderIntent = false;
3038 if (mediaSource.equals(mediaSourceValueCamera)) {
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003039 // Specified 'image/*' and requested the camera, so go ahead and launch the camera
3040 // directly.
3041 BrowserActivity.this.startActivityForResult(cameraIntent, FILE_SELECTED);
3042 return;
Ben Murdochb50d7402010-07-16 12:42:22 +01003043 } else if (mediaSource.equals(mediaSourceValueFileSystem)) {
3044 // Specified filesytem as the source, so don't want to consider the camera.
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003045 addCameraIntent = false;
3046 }
Ben Murdoch6af492a2010-06-15 12:38:17 +01003047 } else if (mimeType.equals(videoMimeType)) {
3048 i.setType(videoMimeType);
3049 addCameraIntent = false;
3050 // The camcorder saves it's own file and returns it to us in the intent, so
3051 // we don't need to generate one here.
3052 mCameraFilePath = null;
3053
3054 if (mediaSource.equals(mediaSourceValueCamcorder)) {
Ben Murdoch039bd472010-07-21 21:26:57 +01003055 // Specified 'video/*' and requested the camcorder, so go ahead and launch the
3056 // camcorder directly.
Ben Murdoch6af492a2010-06-15 12:38:17 +01003057 BrowserActivity.this.startActivityForResult(camcorderIntent, FILE_SELECTED);
3058 return;
Ben Murdochb50d7402010-07-16 12:42:22 +01003059 } else if (mediaSource.equals(mediaSourceValueFileSystem)) {
3060 // Specified filesystem as the source, so don't want to consider the camcorder.
Ben Murdoch6af492a2010-06-15 12:38:17 +01003061 addCamcorderIntent = false;
3062 }
Ben Murdoch039bd472010-07-21 21:26:57 +01003063 } else if (mimeType.equals(audioMimeType)) {
3064 i.setType(audioMimeType);
3065 addCameraIntent = false;
3066 addCamcorderIntent = false;
3067 if (mediaSource.equals(mediaSourceValueMicrophone)) {
3068 // Specified 'audio/*' and requested microphone, so go ahead and launch the sound
3069 // recorder.
3070 BrowserActivity.this.startActivityForResult(soundRecIntent, FILE_SELECTED);
3071 return;
3072 }
3073 // On a default system, there is no single option to open an audio "gallery". Both the
3074 // sound recorder and music browser respond to the OPENABLE/audio/* intent unlike the
3075 // image/* and video/* OPENABLE intents where the image / video gallery are the only
3076 // respondants (and so the user is not prompted by default).
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003077 } else {
3078 i.setType("*/*");
3079 }
3080
Ben Murdoch6af492a2010-06-15 12:38:17 +01003081 // Combine the chooser and the extra choices (like camera or camcorder)
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003082 Intent chooser = new Intent(Intent.ACTION_CHOOSER);
3083 chooser.putExtra(Intent.EXTRA_INTENT, i);
3084
Ben Murdoch6af492a2010-06-15 12:38:17 +01003085 Vector<Intent> extraInitialIntents = new Vector<Intent>(0);
3086
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003087 if (addCameraIntent) {
Ben Murdoch6af492a2010-06-15 12:38:17 +01003088 extraInitialIntents.add(cameraIntent);
3089 }
3090
3091 if (addCamcorderIntent) {
3092 extraInitialIntents.add(camcorderIntent);
3093 }
3094
3095 if (extraInitialIntents.size() > 0) {
3096 Intent[] extraIntents = new Intent[extraInitialIntents.size()];
3097 chooser.putExtra(Intent.EXTRA_INITIAL_INTENTS, extraInitialIntents.toArray(extraIntents));
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003098 }
3099
3100 chooser.putExtra(Intent.EXTRA_TITLE, getString(R.string.choose_upload));
3101 BrowserActivity.this.startActivityForResult(chooser, FILE_SELECTED);
Grace Kloba22ac16e2009-10-07 18:00:23 -07003102 }
3103
3104 // -------------------------------------------------------------------------
3105 // Implement functions for DownloadListener
3106 // -------------------------------------------------------------------------
3107
The Android Open Source Project0c908882009-03-03 19:32:16 -08003108 /**
3109 * Notify the host application a download should be done, or that
3110 * the data should be streamed if a streaming viewer is available.
3111 * @param url The full url to the content that should be downloaded
3112 * @param contentDisposition Content-disposition http header, if
3113 * present.
3114 * @param mimetype The mimetype of the content reported by the server
3115 * @param contentLength The file size reported by the server
3116 */
3117 public void onDownloadStart(String url, String userAgent,
3118 String contentDisposition, String mimetype, long contentLength) {
3119 // if we're dealing wih A/V content that's not explicitly marked
3120 // for download, check if it's streamable.
3121 if (contentDisposition == null
Patrick Scotte1fb9662009-08-31 14:31:52 -04003122 || !contentDisposition.regionMatches(
3123 true, 0, "attachment", 0, 10)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003124 // query the package manager to see if there's a registered handler
3125 // that matches.
3126 Intent intent = new Intent(Intent.ACTION_VIEW);
3127 intent.setDataAndType(Uri.parse(url), mimetype);
Patrick Scotte1fb9662009-08-31 14:31:52 -04003128 ResolveInfo info = getPackageManager().resolveActivity(intent,
3129 PackageManager.MATCH_DEFAULT_ONLY);
3130 if (info != null) {
3131 ComponentName myName = getComponentName();
3132 // If we resolved to ourselves, we don't want to attempt to
3133 // load the url only to try and download it again.
3134 if (!myName.getPackageName().equals(
3135 info.activityInfo.packageName)
3136 || !myName.getClassName().equals(
3137 info.activityInfo.name)) {
3138 // someone (other than us) knows how to handle this mime
3139 // type with this scheme, don't download.
3140 try {
3141 startActivity(intent);
3142 return;
3143 } catch (ActivityNotFoundException ex) {
3144 if (LOGD_ENABLED) {
3145 Log.d(LOGTAG, "activity not found for " + mimetype
3146 + " over " + Uri.parse(url).getScheme(),
3147 ex);
3148 }
3149 // Best behavior is to fall back to a download in this
3150 // case
The Android Open Source Project0c908882009-03-03 19:32:16 -08003151 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003152 }
3153 }
3154 }
3155 onDownloadStartNoStream(url, userAgent, contentDisposition, mimetype, contentLength);
3156 }
3157
Kristian Monsenfa52d172010-03-25 18:29:21 +00003158 // This is to work around the fact that java.net.URI throws Exceptions
3159 // instead of just encoding URL's properly
3160 // Helper method for onDownloadStartNoStream
3161 private static String encodePath(String path) {
3162 char[] chars = path.toCharArray();
3163
3164 boolean needed = false;
3165 for (char c : chars) {
3166 if (c == '[' || c == ']') {
3167 needed = true;
3168 break;
3169 }
3170 }
3171 if (needed == false) {
3172 return path;
3173 }
3174
3175 StringBuilder sb = new StringBuilder("");
3176 for (char c : chars) {
3177 if (c == '[' || c == ']') {
3178 sb.append('%');
3179 sb.append(Integer.toHexString(c));
3180 } else {
3181 sb.append(c);
3182 }
3183 }
3184
3185 return sb.toString();
3186 }
3187
The Android Open Source Project0c908882009-03-03 19:32:16 -08003188 /**
3189 * Notify the host application a download should be done, even if there
3190 * is a streaming viewer available for thise type.
3191 * @param url The full url to the content that should be downloaded
3192 * @param contentDisposition Content-disposition http header, if
3193 * present.
3194 * @param mimetype The mimetype of the content reported by the server
3195 * @param contentLength The file size reported by the server
3196 */
3197 /*package */ void onDownloadStartNoStream(String url, String userAgent,
3198 String contentDisposition, String mimetype, long contentLength) {
3199
3200 String filename = URLUtil.guessFileName(url,
3201 contentDisposition, mimetype);
3202
3203 // Check to see if we have an SDCard
3204 String status = Environment.getExternalStorageState();
3205 if (!status.equals(Environment.MEDIA_MOUNTED)) {
3206 int title;
3207 String msg;
3208
3209 // Check to see if the SDCard is busy, same as the music app
3210 if (status.equals(Environment.MEDIA_SHARED)) {
3211 msg = getString(R.string.download_sdcard_busy_dlg_msg);
3212 title = R.string.download_sdcard_busy_dlg_title;
3213 } else {
3214 msg = getString(R.string.download_no_sdcard_dlg_msg, filename);
3215 title = R.string.download_no_sdcard_dlg_title;
3216 }
3217
3218 new AlertDialog.Builder(this)
3219 .setTitle(title)
3220 .setIcon(android.R.drawable.ic_dialog_alert)
3221 .setMessage(msg)
3222 .setPositiveButton(R.string.ok, null)
3223 .show();
3224 return;
3225 }
3226
Kristian Monsenfa52d172010-03-25 18:29:21 +00003227 // java.net.URI is a lot stricter than KURL so we have to encode some
3228 // extra characters. Fix for b 2538060 and b 1634719
3229 WebAddress webAddress;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003230 try {
Kristian Monsenfa52d172010-03-25 18:29:21 +00003231 webAddress = new WebAddress(url);
3232 webAddress.mPath = encodePath(webAddress.mPath);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003233 } catch (Exception e) {
Kristian Monsenfa52d172010-03-25 18:29:21 +00003234 // This only happens for very bad urls, we want to chatch the
3235 // exception here
3236 Log.e(LOGTAG, "Exception trying to parse url:" + url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003237 return;
3238 }
3239
3240 // XXX: Have to use the old url since the cookies were stored using the
3241 // old percent-encoded url.
3242 String cookies = CookieManager.getInstance().getCookie(url);
3243
3244 ContentValues values = new ContentValues();
Kristian Monsenfa52d172010-03-25 18:29:21 +00003245 values.put(Downloads.Impl.COLUMN_URI, webAddress.toString());
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08003246 values.put(Downloads.Impl.COLUMN_COOKIE_DATA, cookies);
3247 values.put(Downloads.Impl.COLUMN_USER_AGENT, userAgent);
3248 values.put(Downloads.Impl.COLUMN_NOTIFICATION_PACKAGE,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003249 getPackageName());
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08003250 values.put(Downloads.Impl.COLUMN_NOTIFICATION_CLASS,
Leon Scrogginsa563d092010-04-19 16:53:49 -04003251 OpenDownloadReceiver.class.getCanonicalName());
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08003252 values.put(Downloads.Impl.COLUMN_VISIBILITY,
3253 Downloads.Impl.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
3254 values.put(Downloads.Impl.COLUMN_MIME_TYPE, mimetype);
3255 values.put(Downloads.Impl.COLUMN_FILE_NAME_HINT, filename);
Kristian Monsenfa52d172010-03-25 18:29:21 +00003256 values.put(Downloads.Impl.COLUMN_DESCRIPTION, webAddress.mHost);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003257 if (contentLength > 0) {
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08003258 values.put(Downloads.Impl.COLUMN_TOTAL_BYTES, contentLength);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003259 }
3260 if (mimetype == null) {
3261 // We must have long pressed on a link or image to download it. We
3262 // are not sure of the mimetype in this case, so do a head request
3263 new FetchUrlMimeType(this).execute(values);
3264 } else {
3265 final Uri contentUri =
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08003266 getContentResolver().insert(Downloads.Impl.CONTENT_URI, values);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003267 }
Leon Scroggins9191a7f2010-03-18 14:44:44 -04003268 Toast.makeText(this, R.string.download_pending, Toast.LENGTH_SHORT)
3269 .show();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003270 }
3271
Grace Kloba22ac16e2009-10-07 18:00:23 -07003272 // -------------------------------------------------------------------------
3273
The Android Open Source Project0c908882009-03-03 19:32:16 -08003274 /**
3275 * Resets the lock icon. This method is called when we start a new load and
3276 * know the url to be loaded.
3277 */
3278 private void resetLockIcon(String url) {
3279 // Save the lock-icon state (we revert to it if the load gets cancelled)
Grace Kloba22ac16e2009-10-07 18:00:23 -07003280 mTabControl.getCurrentTab().resetLockIcon(url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003281 updateLockIconImage(LOCK_ICON_UNSECURE);
3282 }
3283
The Android Open Source Project0c908882009-03-03 19:32:16 -08003284 /**
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04003285 * Update the lock icon to correspond to our latest state.
3286 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003287 private void updateLockIconToLatest() {
Leon Scroggins91f65fc2010-06-29 13:52:39 -04003288 Tab t = mTabControl.getCurrentTab();
3289 if (t != null) {
3290 updateLockIconImage(t.getLockIconType());
3291 }
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04003292 }
3293
3294 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08003295 * Updates the lock-icon image in the title-bar.
3296 */
3297 private void updateLockIconImage(int lockIconType) {
3298 Drawable d = null;
3299 if (lockIconType == LOCK_ICON_SECURE) {
3300 d = mSecLockIcon;
3301 } else if (lockIconType == LOCK_ICON_MIXED) {
3302 d = mMixLockIcon;
3303 }
Leon Scroggins68579392009-09-15 15:31:54 -04003304 mTitleBar.setLock(d);
Michael Kolba2b2ba82010-08-04 17:54:03 -07003305 mFakeTitleBar.setLock(d);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003306 }
3307
3308 /**
3309 * Displays a page-info dialog.
3310 * @param tab The tab to show info about
3311 * @param fromShowSSLCertificateOnError The flag that indicates whether
3312 * this dialog was opened from the SSL-certificate-on-error dialog or
3313 * not. This is important, since we need to know whether to return to
3314 * the parent dialog or simply dismiss.
3315 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003316 private void showPageInfo(final Tab tab,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003317 final boolean fromShowSSLCertificateOnError) {
3318 final LayoutInflater factory = LayoutInflater
3319 .from(this);
3320
3321 final View pageInfoView = factory.inflate(R.layout.page_info, null);
3322
3323 final WebView view = tab.getWebView();
3324
3325 String url = null;
3326 String title = null;
3327
3328 if (view == null) {
3329 url = tab.getUrl();
3330 title = tab.getTitle();
3331 } else if (view == mTabControl.getCurrentWebView()) {
3332 // Use the cached title and url if this is the current WebView
3333 url = mUrl;
3334 title = mTitle;
3335 } else {
3336 url = view.getUrl();
3337 title = view.getTitle();
3338 }
3339
3340 if (url == null) {
3341 url = "";
3342 }
3343 if (title == null) {
3344 title = "";
3345 }
3346
3347 ((TextView) pageInfoView.findViewById(R.id.address)).setText(url);
3348 ((TextView) pageInfoView.findViewById(R.id.title)).setText(title);
3349
3350 mPageInfoView = tab;
Leon Scrogginsc7b92f82010-01-11 18:17:31 -05003351 mPageInfoFromShowSSLCertificateOnError = fromShowSSLCertificateOnError;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003352
3353 AlertDialog.Builder alertDialogBuilder =
3354 new AlertDialog.Builder(this)
3355 .setTitle(R.string.page_info).setIcon(android.R.drawable.ic_dialog_info)
3356 .setView(pageInfoView)
3357 .setPositiveButton(
3358 R.string.ok,
3359 new DialogInterface.OnClickListener() {
3360 public void onClick(DialogInterface dialog,
3361 int whichButton) {
3362 mPageInfoDialog = null;
3363 mPageInfoView = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003364
3365 // if we came here from the SSL error dialog
3366 if (fromShowSSLCertificateOnError) {
3367 // go back to the SSL error dialog
3368 showSSLCertificateOnError(
3369 mSSLCertificateOnErrorView,
3370 mSSLCertificateOnErrorHandler,
3371 mSSLCertificateOnErrorError);
3372 }
3373 }
3374 })
3375 .setOnCancelListener(
3376 new DialogInterface.OnCancelListener() {
3377 public void onCancel(DialogInterface dialog) {
3378 mPageInfoDialog = null;
3379 mPageInfoView = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003380
3381 // if we came here from the SSL error dialog
3382 if (fromShowSSLCertificateOnError) {
3383 // go back to the SSL error dialog
3384 showSSLCertificateOnError(
3385 mSSLCertificateOnErrorView,
3386 mSSLCertificateOnErrorHandler,
3387 mSSLCertificateOnErrorError);
3388 }
3389 }
3390 });
3391
3392 // if we have a main top-level page SSL certificate set or a certificate
3393 // error
3394 if (fromShowSSLCertificateOnError ||
3395 (view != null && view.getCertificate() != null)) {
3396 // add a 'View Certificate' button
3397 alertDialogBuilder.setNeutralButton(
3398 R.string.view_certificate,
3399 new DialogInterface.OnClickListener() {
3400 public void onClick(DialogInterface dialog,
3401 int whichButton) {
3402 mPageInfoDialog = null;
3403 mPageInfoView = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003404
3405 // if we came here from the SSL error dialog
3406 if (fromShowSSLCertificateOnError) {
3407 // go back to the SSL error dialog
3408 showSSLCertificateOnError(
3409 mSSLCertificateOnErrorView,
3410 mSSLCertificateOnErrorHandler,
3411 mSSLCertificateOnErrorError);
3412 } else {
3413 // otherwise, display the top-most certificate from
3414 // the chain
3415 if (view.getCertificate() != null) {
3416 showSSLCertificate(tab);
3417 }
3418 }
3419 }
3420 });
3421 }
3422
3423 mPageInfoDialog = alertDialogBuilder.show();
3424 }
3425
3426 /**
3427 * Displays the main top-level page SSL certificate dialog
3428 * (accessible from the Page-Info dialog).
3429 * @param tab The tab to show certificate for.
3430 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003431 private void showSSLCertificate(final Tab tab) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003432 final View certificateView =
3433 inflateCertificateView(tab.getWebView().getCertificate());
3434 if (certificateView == null) {
3435 return;
3436 }
3437
3438 LayoutInflater factory = LayoutInflater.from(this);
3439
3440 final LinearLayout placeholder =
3441 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3442
3443 LinearLayout ll = (LinearLayout) factory.inflate(
3444 R.layout.ssl_success, placeholder);
3445 ((TextView)ll.findViewById(R.id.success))
3446 .setText(R.string.ssl_certificate_is_valid);
3447
3448 mSSLCertificateView = tab;
3449 mSSLCertificateDialog =
3450 new AlertDialog.Builder(this)
3451 .setTitle(R.string.ssl_certificate).setIcon(
3452 R.drawable.ic_dialog_browser_certificate_secure)
3453 .setView(certificateView)
3454 .setPositiveButton(R.string.ok,
3455 new DialogInterface.OnClickListener() {
3456 public void onClick(DialogInterface dialog,
3457 int whichButton) {
3458 mSSLCertificateDialog = null;
3459 mSSLCertificateView = null;
3460
3461 showPageInfo(tab, false);
3462 }
3463 })
3464 .setOnCancelListener(
3465 new DialogInterface.OnCancelListener() {
3466 public void onCancel(DialogInterface dialog) {
3467 mSSLCertificateDialog = null;
3468 mSSLCertificateView = null;
3469
3470 showPageInfo(tab, false);
3471 }
3472 })
3473 .show();
3474 }
3475
3476 /**
3477 * Displays the SSL error certificate dialog.
3478 * @param view The target web-view.
3479 * @param handler The SSL error handler responsible for cancelling the
3480 * connection that resulted in an SSL error or proceeding per user request.
3481 * @param error The SSL error object.
3482 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003483 void showSSLCertificateOnError(
The Android Open Source Project0c908882009-03-03 19:32:16 -08003484 final WebView view, final SslErrorHandler handler, final SslError error) {
3485
3486 final View certificateView =
3487 inflateCertificateView(error.getCertificate());
3488 if (certificateView == null) {
3489 return;
3490 }
3491
3492 LayoutInflater factory = LayoutInflater.from(this);
3493
3494 final LinearLayout placeholder =
3495 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3496
3497 if (error.hasError(SslError.SSL_UNTRUSTED)) {
3498 LinearLayout ll = (LinearLayout)factory
3499 .inflate(R.layout.ssl_warning, placeholder);
3500 ((TextView)ll.findViewById(R.id.warning))
3501 .setText(R.string.ssl_untrusted);
3502 }
3503
3504 if (error.hasError(SslError.SSL_IDMISMATCH)) {
3505 LinearLayout ll = (LinearLayout)factory
3506 .inflate(R.layout.ssl_warning, placeholder);
3507 ((TextView)ll.findViewById(R.id.warning))
3508 .setText(R.string.ssl_mismatch);
3509 }
3510
3511 if (error.hasError(SslError.SSL_EXPIRED)) {
3512 LinearLayout ll = (LinearLayout)factory
3513 .inflate(R.layout.ssl_warning, placeholder);
3514 ((TextView)ll.findViewById(R.id.warning))
3515 .setText(R.string.ssl_expired);
3516 }
3517
3518 if (error.hasError(SslError.SSL_NOTYETVALID)) {
3519 LinearLayout ll = (LinearLayout)factory
3520 .inflate(R.layout.ssl_warning, placeholder);
3521 ((TextView)ll.findViewById(R.id.warning))
3522 .setText(R.string.ssl_not_yet_valid);
3523 }
3524
3525 mSSLCertificateOnErrorHandler = handler;
3526 mSSLCertificateOnErrorView = view;
3527 mSSLCertificateOnErrorError = error;
3528 mSSLCertificateOnErrorDialog =
3529 new AlertDialog.Builder(this)
3530 .setTitle(R.string.ssl_certificate).setIcon(
3531 R.drawable.ic_dialog_browser_certificate_partially_secure)
3532 .setView(certificateView)
3533 .setPositiveButton(R.string.ok,
3534 new DialogInterface.OnClickListener() {
3535 public void onClick(DialogInterface dialog,
3536 int whichButton) {
3537 mSSLCertificateOnErrorDialog = null;
3538 mSSLCertificateOnErrorView = null;
3539 mSSLCertificateOnErrorHandler = null;
3540 mSSLCertificateOnErrorError = null;
3541
Grace Kloba22ac16e2009-10-07 18:00:23 -07003542 view.getWebViewClient().onReceivedSslError(
3543 view, handler, error);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003544 }
3545 })
3546 .setNeutralButton(R.string.page_info_view,
3547 new DialogInterface.OnClickListener() {
3548 public void onClick(DialogInterface dialog,
3549 int whichButton) {
3550 mSSLCertificateOnErrorDialog = null;
3551
3552 // do not clear the dialog state: we will
3553 // need to show the dialog again once the
3554 // user is done exploring the page-info details
3555
3556 showPageInfo(mTabControl.getTabFromView(view),
3557 true);
3558 }
3559 })
3560 .setOnCancelListener(
3561 new DialogInterface.OnCancelListener() {
3562 public void onCancel(DialogInterface dialog) {
3563 mSSLCertificateOnErrorDialog = null;
3564 mSSLCertificateOnErrorView = null;
3565 mSSLCertificateOnErrorHandler = null;
3566 mSSLCertificateOnErrorError = null;
3567
Grace Kloba22ac16e2009-10-07 18:00:23 -07003568 view.getWebViewClient().onReceivedSslError(
3569 view, handler, error);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003570 }
3571 })
3572 .show();
3573 }
3574
3575 /**
3576 * Inflates the SSL certificate view (helper method).
3577 * @param certificate The SSL certificate.
3578 * @return The resultant certificate view with issued-to, issued-by,
3579 * issued-on, expires-on, and possibly other fields set.
3580 * If the input certificate is null, returns null.
3581 */
3582 private View inflateCertificateView(SslCertificate certificate) {
3583 if (certificate == null) {
3584 return null;
3585 }
3586
3587 LayoutInflater factory = LayoutInflater.from(this);
3588
3589 View certificateView = factory.inflate(
3590 R.layout.ssl_certificate, null);
3591
3592 // issued to:
3593 SslCertificate.DName issuedTo = certificate.getIssuedTo();
3594 if (issuedTo != null) {
3595 ((TextView) certificateView.findViewById(R.id.to_common))
3596 .setText(issuedTo.getCName());
3597 ((TextView) certificateView.findViewById(R.id.to_org))
3598 .setText(issuedTo.getOName());
3599 ((TextView) certificateView.findViewById(R.id.to_org_unit))
3600 .setText(issuedTo.getUName());
3601 }
3602
3603 // issued by:
3604 SslCertificate.DName issuedBy = certificate.getIssuedBy();
3605 if (issuedBy != null) {
3606 ((TextView) certificateView.findViewById(R.id.by_common))
3607 .setText(issuedBy.getCName());
3608 ((TextView) certificateView.findViewById(R.id.by_org))
3609 .setText(issuedBy.getOName());
3610 ((TextView) certificateView.findViewById(R.id.by_org_unit))
3611 .setText(issuedBy.getUName());
3612 }
3613
3614 // issued on:
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003615 String issuedOn = formatCertificateDate(
3616 certificate.getValidNotBeforeDate());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003617 ((TextView) certificateView.findViewById(R.id.issued_on))
3618 .setText(issuedOn);
3619
3620 // expires on:
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003621 String expiresOn = formatCertificateDate(
3622 certificate.getValidNotAfterDate());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003623 ((TextView) certificateView.findViewById(R.id.expires_on))
3624 .setText(expiresOn);
3625
3626 return certificateView;
3627 }
3628
3629 /**
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003630 * Formats the certificate date to a properly localized date string.
The Android Open Source Project0c908882009-03-03 19:32:16 -08003631 * @return Properly localized version of the certificate date string and
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003632 * the "" if it fails to localize.
The Android Open Source Project0c908882009-03-03 19:32:16 -08003633 */
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003634 private String formatCertificateDate(Date certificateDate) {
3635 if (certificateDate == null) {
3636 return "";
The Android Open Source Project0c908882009-03-03 19:32:16 -08003637 }
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003638 String formattedDate = DateFormat.getDateFormat(this).format(certificateDate);
3639 if (formattedDate == null) {
3640 return "";
3641 }
3642 return formattedDate;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003643 }
3644
3645 /**
3646 * Displays an http-authentication dialog.
3647 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003648 void showHttpAuthentication(final HttpAuthHandler handler,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003649 final String host, final String realm, final String title,
3650 final String name, final String password, int focusId) {
3651 LayoutInflater factory = LayoutInflater.from(this);
3652 final View v = factory
3653 .inflate(R.layout.http_authentication, null);
3654 if (name != null) {
3655 ((EditText) v.findViewById(R.id.username_edit)).setText(name);
3656 }
3657 if (password != null) {
3658 ((EditText) v.findViewById(R.id.password_edit)).setText(password);
3659 }
3660
3661 String titleText = title;
3662 if (titleText == null) {
3663 titleText = getText(R.string.sign_in_to).toString().replace(
3664 "%s1", host).replace("%s2", realm);
3665 }
3666
3667 mHttpAuthHandler = handler;
3668 AlertDialog dialog = new AlertDialog.Builder(this)
3669 .setTitle(titleText)
3670 .setIcon(android.R.drawable.ic_dialog_alert)
3671 .setView(v)
3672 .setPositiveButton(R.string.action,
3673 new DialogInterface.OnClickListener() {
3674 public void onClick(DialogInterface dialog,
3675 int whichButton) {
3676 String nm = ((EditText) v
3677 .findViewById(R.id.username_edit))
3678 .getText().toString();
3679 String pw = ((EditText) v
3680 .findViewById(R.id.password_edit))
3681 .getText().toString();
3682 BrowserActivity.this.setHttpAuthUsernamePassword
3683 (host, realm, nm, pw);
3684 handler.proceed(nm, pw);
3685 mHttpAuthenticationDialog = null;
3686 mHttpAuthHandler = null;
3687 }})
3688 .setNegativeButton(R.string.cancel,
3689 new DialogInterface.OnClickListener() {
3690 public void onClick(DialogInterface dialog,
3691 int whichButton) {
3692 handler.cancel();
3693 BrowserActivity.this.resetTitleAndRevertLockIcon();
3694 mHttpAuthenticationDialog = null;
3695 mHttpAuthHandler = null;
3696 }})
3697 .setOnCancelListener(new DialogInterface.OnCancelListener() {
3698 public void onCancel(DialogInterface dialog) {
3699 handler.cancel();
3700 BrowserActivity.this.resetTitleAndRevertLockIcon();
3701 mHttpAuthenticationDialog = null;
3702 mHttpAuthHandler = null;
3703 }})
3704 .create();
3705 // Make the IME appear when the dialog is displayed if applicable.
3706 dialog.getWindow().setSoftInputMode(
3707 WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
3708 dialog.show();
3709 if (focusId != 0) {
3710 dialog.findViewById(focusId).requestFocus();
3711 } else {
3712 v.findViewById(R.id.username_edit).requestFocus();
3713 }
3714 mHttpAuthenticationDialog = dialog;
3715 }
3716
3717 public int getProgress() {
3718 WebView w = mTabControl.getCurrentWebView();
3719 if (w != null) {
3720 return w.getProgress();
3721 } else {
3722 return 100;
3723 }
3724 }
3725
3726 /**
3727 * Set HTTP authentication password.
3728 *
3729 * @param host The host for the password
3730 * @param realm The realm for the password
3731 * @param username The username for the password. If it is null, it means
3732 * password can't be saved.
3733 * @param password The password
3734 */
3735 public void setHttpAuthUsernamePassword(String host, String realm,
3736 String username,
3737 String password) {
Steve Block95a53b22010-03-25 17:24:58 +00003738 WebView w = getTopWindow();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003739 if (w != null) {
3740 w.setHttpAuthUsernamePassword(host, realm, username, password);
3741 }
3742 }
3743
3744 /**
3745 * connectivity manager says net has come or gone... inform the user
3746 * @param up true if net has come up, false if net has gone down
3747 */
3748 public void onNetworkToggle(boolean up) {
3749 if (up == mIsNetworkUp) {
3750 return;
3751 } else if (up) {
3752 mIsNetworkUp = true;
3753 if (mAlertDialog != null) {
3754 mAlertDialog.cancel();
3755 mAlertDialog = null;
3756 }
3757 } else {
3758 mIsNetworkUp = false;
Patrick Scotteb6ab2a2009-09-16 10:00:17 -04003759 if (mInLoad) {
3760 createAndShowNetworkDialog();
3761 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003762 }
3763 WebView w = mTabControl.getCurrentWebView();
3764 if (w != null) {
3765 w.setNetworkAvailable(up);
3766 }
3767 }
3768
Grace Kloba22ac16e2009-10-07 18:00:23 -07003769 boolean isNetworkUp() {
3770 return mIsNetworkUp;
3771 }
3772
Patrick Scotteb6ab2a2009-09-16 10:00:17 -04003773 // This method shows the network dialog alerting the user that the net is
3774 // down. It will only show the dialog if mAlertDialog is null.
3775 private void createAndShowNetworkDialog() {
3776 if (mAlertDialog == null) {
3777 mAlertDialog = new AlertDialog.Builder(this)
3778 .setTitle(R.string.loadSuspendedTitle)
3779 .setMessage(R.string.loadSuspended)
3780 .setPositiveButton(R.string.ok, null)
3781 .show();
3782 }
3783 }
3784
The Android Open Source Project0c908882009-03-03 19:32:16 -08003785 @Override
3786 protected void onActivityResult(int requestCode, int resultCode,
3787 Intent intent) {
Grace Klobabb394f32009-11-19 10:26:37 -08003788 if (getTopWindow() == null) return;
3789
The Android Open Source Project0c908882009-03-03 19:32:16 -08003790 switch (requestCode) {
3791 case COMBO_PAGE:
3792 if (resultCode == RESULT_OK && intent != null) {
3793 String data = intent.getAction();
3794 Bundle extras = intent.getExtras();
Michael Kolb300b7f02010-08-25 13:47:24 -07003795 if (extras != null &&
3796 extras.getBoolean(
3797 CombinedBookmarkHistoryActivity.EXTRA_OPEN_NEW_WINDOW,
3798 false)) {
Michael Kolb68792c82010-08-09 16:39:18 -07003799 openTab(data, false);
3800 } else if ((extras != null) &&
3801 extras.getBoolean(CombinedBookmarkHistoryActivity.NEWTAB_MODE)) {
3802 openTab(data, true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003803 } else {
Michael Kolb68792c82010-08-09 16:39:18 -07003804 final Tab currentTab = mTabControl.getCurrentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04003805 dismissSubWindow(currentTab);
3806 if (data != null && data.length() != 0) {
Leon Scroggins92472e82010-02-17 16:32:28 -05003807 loadUrl(getTopWindow(), data);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003808 }
3809 }
Michael Kolb3f65c382010-08-20 15:31:16 -07003810 } else if (resultCode == RESULT_CANCELED) {
3811 if (intent != null) {
3812 float evtx = intent.getFloatExtra(CombinedBookmarkHistoryActivity.EVT_X, -1);
3813 float evty = intent.getFloatExtra(CombinedBookmarkHistoryActivity.EVT_Y, -1);
3814 long now = System.currentTimeMillis();
3815 MotionEvent evt = MotionEvent.obtain(now, now,
3816 MotionEvent.ACTION_DOWN, evtx, evty, 0);
3817 dispatchTouchEvent(evt);
3818 MotionEvent up = MotionEvent.obtain(evt);
3819 up.setAction(MotionEvent.ACTION_UP);
3820 dispatchTouchEvent(up);
3821 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003822 }
Leon Scrogginsfde97462010-01-11 13:06:21 -05003823 // Deliberately fall through to PREFERENCES_PAGE, since the
3824 // same extra may be attached to the COMBO_PAGE
3825 case PREFERENCES_PAGE:
3826 if (resultCode == RESULT_OK && intent != null) {
3827 String action = intent.getStringExtra(Intent.EXTRA_TEXT);
3828 if (BrowserSettings.PREF_CLEAR_HISTORY.equals(action)) {
3829 mTabControl.removeParentChildRelationShips();
3830 }
3831 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003832 break;
Leon Scroggins8d5fa432009-10-02 15:55:59 -04003833 // Choose a file from the file picker.
3834 case FILE_SELECTED:
3835 if (null == mUploadMessage) break;
3836 Uri result = intent == null || resultCode != RESULT_OK ? null
3837 : intent.getData();
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003838
3839 // As we ask the camera to save the result of the user taking
3840 // a picture, the camera application does not return anything other
3841 // than RESULT_OK. So we need to check whether the file we expected
3842 // was written to disk in the in the case that we
3843 // did not get an intent returned but did get a RESULT_OK. If it was,
3844 // we assume that this result has came back from the camera.
3845 if (result == null && intent == null && resultCode == RESULT_OK) {
3846 File cameraFile = new File(mCameraFilePath);
3847 if (cameraFile.exists()) {
3848 result = Uri.fromFile(cameraFile);
Ben Murdoch07d34732010-05-27 18:34:46 +01003849 // Broadcast to the media scanner that we have a new photo
3850 // so it will be added into the gallery for the user.
3851 sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, result));
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003852 }
3853 }
Leon Scroggins8d5fa432009-10-02 15:55:59 -04003854 mUploadMessage.onReceiveValue(result);
3855 mUploadMessage = null;
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003856 mCameraFilePath = null;
Leon Scroggins8d5fa432009-10-02 15:55:59 -04003857 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003858 default:
3859 break;
3860 }
Leon Scroggins30444232009-09-04 18:36:20 -04003861 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003862 }
3863
3864 /*
3865 * This method is called as a result of the user selecting the options
Leon Scrogginsf08809b2010-01-21 09:27:46 -05003866 * menu to see the download window. It shows the download window on top of
3867 * the current window.
The Android Open Source Project0c908882009-03-03 19:32:16 -08003868 */
Leon Scrogginsf08809b2010-01-21 09:27:46 -05003869 private void viewDownloads(Uri downloadRecord) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003870 Intent intent = new Intent(this,
3871 BrowserDownloadPage.class);
3872 intent.setData(downloadRecord);
Grace Kloba22ac16e2009-10-07 18:00:23 -07003873 startActivityForResult(intent, BrowserActivity.DOWNLOAD_PAGE);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003874
3875 }
3876
Michael Kolbc7485ae2010-09-03 10:10:58 -07003877 /* package */ void promptAddOrInstallBookmark(View anchor) {
3878 PopupMenu popup = new PopupMenu(this, anchor);
3879 popup.getMenuInflater().inflate(R.menu.bookmark_shortcut, popup.getMenu());
3880 popup.setOnMenuItemClickListener(this);
3881 popup.show();
3882 }
3883
3884 /**
3885 * popup menu item click listener
3886 * @param item
3887 */
3888 public boolean onMenuItemClick(MenuItem item) {
3889 switch(item.getItemId()) {
3890 case R.id.add_bookmark_menu_id:
3891 bookmarkCurrentPage();
3892 return true;
3893 case R.id.shortcut_to_home_menu_id:
3894 Tab current = mTabControl.getCurrentTab();
3895 current.populatePickerData();
3896 String touchIconUrl = mTabControl.getCurrentWebView().getTouchIconUrl();
3897 if (touchIconUrl != null) {
3898 // Download the touch icon for this site then save
3899 // it to the
3900 // homescreen.
3901 Bundle b = new Bundle();
3902 b.putString("url", current.getUrl());
3903 b.putString("title", current.getTitle());
3904 b.putParcelable("favicon", current.getFavicon());
3905 Message msg = mHandler.obtainMessage(TOUCH_ICON_DOWNLOADED);
3906 msg.setData(b);
3907 new DownloadTouchIcon(BrowserActivity.this, msg,
3908 mTabControl.getCurrentWebView().getSettings().getUserAgentString())
3909 .execute(touchIconUrl);
3910 } else {
3911 // add to homescreen, can do it immediately as there
3912 // is no touch
3913 // icon.
3914 showSaveToHomescreenDialog(
3915 current.getUrl(), current.getTitle(), null, current.getFavicon());
3916 }
3917 return true;
3918 default:
3919 return false;
3920 }
3921 }
3922
3923 /* package */Dialog makeAddOrInstallDialog() {
Ben Murdocheecb4e62010-07-06 16:30:38 +01003924 final Tab current = mTabControl.getCurrentTab();
3925 Resources resources = getResources();
Michael Kolbc7485ae2010-09-03 10:10:58 -07003926 CharSequence[] choices =
3927 {resources.getString(R.string.save_to_bookmarks),
3928 resources.getString(R.string.create_shortcut_bookmark)};
Ben Murdocheecb4e62010-07-06 16:30:38 +01003929
3930 AlertDialog.Builder builder = new AlertDialog.Builder(this);
3931 builder.setTitle(R.string.add_new_bookmark);
3932 builder.setItems(choices, new DialogInterface.OnClickListener() {
Michael Kolbc7485ae2010-09-03 10:10:58 -07003933 public void onClick(DialogInterface dialog, int item) {
3934 if (item == 0) {
3935 bookmarkCurrentPage();
3936 } else if (item == 1) {
3937 }
3938 }
Ben Murdocheecb4e62010-07-06 16:30:38 +01003939 });
Michael Kolbc7485ae2010-09-03 10:10:58 -07003940 return builder.create();
Ben Murdocheecb4e62010-07-06 16:30:38 +01003941 }
3942
Leon Scroggins160a7e72009-08-14 18:28:01 -04003943 /**
3944 * Open the Go page.
3945 * @param startWithHistory If true, open starting on the history tab.
3946 * Otherwise, start with the bookmarks tab.
Leon Scroggins160a7e72009-08-14 18:28:01 -04003947 */
Michael Kolb68792c82010-08-09 16:39:18 -07003948 /* package */ void bookmarksOrHistoryPicker(boolean startWithHistory, boolean newTabMode) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003949 WebView current = mTabControl.getCurrentWebView();
3950 if (current == null) {
3951 return;
3952 }
3953 Intent intent = new Intent(this,
3954 CombinedBookmarkHistoryActivity.class);
3955 String title = current.getTitle();
3956 String url = current.getUrl();
Ben Murdoch87cc65d2010-06-29 20:34:10 +01003957 Bitmap thumbnail = createScreenshot(current, getDesiredThumbnailWidth(this),
3958 getDesiredThumbnailHeight(this));
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01003959
The Android Open Source Project0c908882009-03-03 19:32:16 -08003960 // Just in case the user opens bookmarks before a page finishes loading
3961 // so the current history item, and therefore the page, is null.
3962 if (null == url) {
3963 url = mLastEnteredUrl;
3964 // This can happen.
3965 if (null == url) {
3966 url = mSettings.getHomePage();
3967 }
3968 }
3969 // In case the web page has not yet received its associated title.
3970 if (title == null) {
3971 title = url;
3972 }
3973 intent.putExtra("title", title);
3974 intent.putExtra("url", url);
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01003975 intent.putExtra("thumbnail", thumbnail);
Leon Scroggins30444232009-09-04 18:36:20 -04003976 // Disable opening in a new window if we have maxed out the windows
Grace Kloba22ac16e2009-10-07 18:00:23 -07003977 intent.putExtra("disable_new_window", !mTabControl.canCreateNewTab());
Patrick Scott3918d442009-08-04 13:22:29 -04003978 intent.putExtra("touch_icon_url", current.getTouchIconUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003979 if (startWithHistory) {
Jeff Hamilton64144e42010-08-18 16:31:59 -05003980 intent.putExtra(CombinedBookmarkHistoryActivity.STARTING_FRAGMENT,
3981 CombinedBookmarkHistoryActivity.FRAGMENT_ID_HISTORY);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003982 }
Michael Kolb300b7f02010-08-25 13:47:24 -07003983 intent.putExtra(CombinedBookmarkHistoryActivity.NEWTAB_MODE, newTabMode);
Michael Kolb0998b0a2010-08-23 17:45:35 -07003984 int top = -1;
3985 int height = -1;
Michael Kolb3f65c382010-08-20 15:31:16 -07003986 if (mXLargeScreenSize) {
3987 showFakeTitleBar();
3988 int titleBarHeight = ((TitleBarXLarge)mFakeTitleBar).getHeightWithoutProgress();
Michael Kolb0998b0a2010-08-23 17:45:35 -07003989 top = mTabBar.getBottom() + titleBarHeight;
3990 height = getTopWindow().getHeight() - titleBarHeight;
Michael Kolb68792c82010-08-09 16:39:18 -07003991 }
Michael Kolb0998b0a2010-08-23 17:45:35 -07003992 intent.putExtra(CombinedBookmarkHistoryActivity.EXTRA_TOP, top);
3993 intent.putExtra(CombinedBookmarkHistoryActivity.EXTRA_HEIGHT, height);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003994 startActivityForResult(intent, COMBO_PAGE);
3995 }
3996
Ben Murdocheecb4e62010-07-06 16:30:38 +01003997 private void showSaveToHomescreenDialog(String url, String title, Bitmap touchIcon,
3998 Bitmap favicon) {
3999 Intent intent = new Intent(this, SaveToHomescreenDialog.class);
4000
4001 // Just in case the user tries to save before a page finishes loading
4002 // so the current history item, and therefore the page, is null.
4003 if (null == url) {
4004 url = mLastEnteredUrl;
4005 // This can happen.
4006 if (null == url) {
4007 url = mSettings.getHomePage();
4008 }
4009 }
4010
4011 // In case the web page has not yet received its associated title.
4012 if (title == null) {
4013 title = url;
4014 }
4015
4016 intent.putExtra("title", title);
4017 intent.putExtra("url", url);
4018 intent.putExtra("favicon", favicon);
4019 intent.putExtra("touchIcon", touchIcon);
4020 startActivity(intent);
4021 }
4022
4023
The Android Open Source Project0c908882009-03-03 19:32:16 -08004024 // Called when loading from context menu or LOAD_URL message
Leon Scroggins92472e82010-02-17 16:32:28 -05004025 private void loadUrlFromContext(WebView view, String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08004026 // In case the user enters nothing.
4027 if (url != null && url.length() != 0 && view != null) {
4028 url = smartUrlFilter(url);
Grace Kloba22ac16e2009-10-07 18:00:23 -07004029 if (!view.getWebViewClient().shouldOverrideUrlLoading(view, url)) {
Leon Scroggins92472e82010-02-17 16:32:28 -05004030 loadUrl(view, url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004031 }
4032 }
4033 }
4034
Leon Scroggins92472e82010-02-17 16:32:28 -05004035 /**
4036 * Load the URL into the given WebView and update the title bar
4037 * to reflect the new load. Call this instead of WebView.loadUrl
4038 * directly.
4039 * @param view The WebView used to load url.
4040 * @param url The URL to load.
4041 */
4042 private void loadUrl(WebView view, String url) {
4043 updateTitleBarForNewLoad(view, url);
4044 view.loadUrl(url);
4045 }
4046
4047 /**
4048 * Load UrlData into a Tab and update the title bar to reflect the new
4049 * load. Call this instead of UrlData.loadIn directly.
4050 * @param t The Tab used to load.
4051 * @param data The UrlData being loaded.
4052 */
4053 private void loadUrlDataIn(Tab t, UrlData data) {
4054 updateTitleBarForNewLoad(t.getWebView(), data.mUrl);
4055 data.loadIn(t);
4056 }
4057
4058 /**
4059 * If the WebView is the top window, update the title bar to reflect
4060 * loading the new URL. i.e. set its text, clear the favicon (which
4061 * will be set once the page begins loading), and set the progress to
4062 * INITIAL_PROGRESS to show that the page has begun to load. Called
4063 * by loadUrl and loadUrlDataIn.
4064 * @param view The WebView that is starting a load.
4065 * @param url The URL that is being loaded.
4066 */
4067 private void updateTitleBarForNewLoad(WebView view, String url) {
4068 if (view == getTopWindow()) {
4069 setUrlTitle(url, null);
4070 setFavicon(null);
4071 onProgressChanged(view, INITIAL_PROGRESS);
4072 }
4073 }
4074
The Android Open Source Project0c908882009-03-03 19:32:16 -08004075 private String smartUrlFilter(Uri inUri) {
4076 if (inUri != null) {
4077 return smartUrlFilter(inUri.toString());
4078 }
4079 return null;
4080 }
4081
Feng Qianb34f87a2009-03-24 21:27:26 -07004082 protected static final Pattern ACCEPTED_URI_SCHEMA = Pattern.compile(
The Android Open Source Project0c908882009-03-03 19:32:16 -08004083 "(?i)" + // switch on case insensitive matching
4084 "(" + // begin group for schema
4085 "(?:http|https|file):\\/\\/" +
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004086 "|(?:inline|data|about|content|javascript):" +
The Android Open Source Project0c908882009-03-03 19:32:16 -08004087 ")" +
4088 "(.*)" );
4089
4090 /**
4091 * Attempts to determine whether user input is a URL or search
4092 * terms. Anything with a space is passed to search.
4093 *
4094 * Converts to lowercase any mistakenly uppercased schema (i.e.,
4095 * "Http://" converts to "http://"
4096 *
4097 * @return Original or modified URL
4098 *
4099 */
4100 String smartUrlFilter(String url) {
4101
4102 String inUrl = url.trim();
4103 boolean hasSpace = inUrl.indexOf(' ') != -1;
4104
4105 Matcher matcher = ACCEPTED_URI_SCHEMA.matcher(inUrl);
4106 if (matcher.matches()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08004107 // force scheme to lowercase
4108 String scheme = matcher.group(1);
4109 String lcScheme = scheme.toLowerCase();
4110 if (!lcScheme.equals(scheme)) {
Mitsuru Oshima123ecfb2009-05-18 19:11:14 -07004111 inUrl = lcScheme + matcher.group(2);
4112 }
4113 if (hasSpace) {
4114 inUrl = inUrl.replace(" ", "%20");
The Android Open Source Project0c908882009-03-03 19:32:16 -08004115 }
4116 return inUrl;
4117 }
4118 if (hasSpace) {
Satish Sampath565505b2009-05-29 15:37:27 +01004119 // FIXME: Is this the correct place to add to searches?
4120 // what if someone else calls this function?
4121 int shortcut = parseUrlShortcut(inUrl);
4122 if (shortcut != SHORTCUT_INVALID) {
4123 Browser.addSearchUrl(mResolver, inUrl);
4124 String query = inUrl.substring(2);
4125 switch (shortcut) {
4126 case SHORTCUT_GOOGLE_SEARCH:
Grace Kloba47fdfdb2009-06-30 11:15:34 -07004127 return URLUtil.composeSearchUrl(query, QuickSearch_G, QUERY_PLACE_HOLDER);
Satish Sampath565505b2009-05-29 15:37:27 +01004128 case SHORTCUT_WIKIPEDIA_SEARCH:
4129 return URLUtil.composeSearchUrl(query, QuickSearch_W, QUERY_PLACE_HOLDER);
4130 case SHORTCUT_DICTIONARY_SEARCH:
4131 return URLUtil.composeSearchUrl(query, QuickSearch_D, QUERY_PLACE_HOLDER);
4132 case SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH:
The Android Open Source Project0c908882009-03-03 19:32:16 -08004133 // FIXME: we need location in this case
Satish Sampath565505b2009-05-29 15:37:27 +01004134 return URLUtil.composeSearchUrl(query, QuickSearch_L, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004135 }
4136 }
4137 } else {
Dan Egnor5ee906c2009-11-18 12:11:49 -08004138 if (Patterns.WEB_URL.matcher(inUrl).matches()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08004139 return URLUtil.guessUrl(inUrl);
4140 }
4141 }
4142
4143 Browser.addSearchUrl(mResolver, inUrl);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07004144 return URLUtil.composeSearchUrl(inUrl, QuickSearch_G, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004145 }
4146
Ben Murdochbff2d602009-07-01 20:19:05 +01004147 /* package */ void setShouldShowErrorConsole(boolean flag) {
4148 if (flag == mShouldShowErrorConsole) {
4149 // Nothing to do.
4150 return;
4151 }
4152
4153 mShouldShowErrorConsole = flag;
4154
Grace Kloba22ac16e2009-10-07 18:00:23 -07004155 ErrorConsoleView errorConsole = mTabControl.getCurrentTab()
4156 .getErrorConsole(true);
Ben Murdochbff2d602009-07-01 20:19:05 +01004157
4158 if (flag) {
4159 // Setting the show state of the console will cause it's the layout to be inflated.
4160 if (errorConsole.numberOfErrors() > 0) {
4161 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
4162 } else {
4163 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
4164 }
4165
4166 // Now we can add it to the main view.
4167 mErrorConsoleContainer.addView(errorConsole,
Romain Guy15b8ec62010-01-08 15:06:43 -08004168 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
Ben Murdochbff2d602009-07-01 20:19:05 +01004169 ViewGroup.LayoutParams.WRAP_CONTENT));
4170 } else {
4171 mErrorConsoleContainer.removeView(errorConsole);
4172 }
4173
4174 }
4175
Grace Kloba22ac16e2009-10-07 18:00:23 -07004176 boolean shouldShowErrorConsole() {
4177 return mShouldShowErrorConsole;
4178 }
4179
Andrei Popescu163ab742009-10-20 17:58:23 +01004180 private void setStatusBarVisibility(boolean visible) {
4181 int flag = visible ? 0 : WindowManager.LayoutParams.FLAG_FULLSCREEN;
4182 getWindow().setFlags(flag, WindowManager.LayoutParams.FLAG_FULLSCREEN);
4183 }
4184
Andrei Popescu56199cc2010-01-12 22:39:16 +00004185
4186 private void sendNetworkType(String type, String subtype) {
4187 WebView w = mTabControl.getCurrentWebView();
4188 if (w != null) {
4189 w.setNetworkType(type, subtype);
4190 }
4191 }
4192
Grace Klobaeb6eef42009-09-15 17:56:32 -07004193 final static int LOCK_ICON_UNSECURE = 0;
4194 final static int LOCK_ICON_SECURE = 1;
4195 final static int LOCK_ICON_MIXED = 2;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004196
The Android Open Source Project0c908882009-03-03 19:32:16 -08004197 private BrowserSettings mSettings;
4198 private TabControl mTabControl;
4199 private ContentResolver mResolver;
4200 private FrameLayout mContentView;
Andrei Popescuadc008d2009-06-26 14:11:30 +01004201 private View mCustomView;
4202 private FrameLayout mCustomViewContainer;
Andrei Popescuc9b55562009-07-07 10:51:15 +01004203 private WebChromeClient.CustomViewCallback mCustomViewCallback;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004204
4205 // FIXME, temp address onPrepareMenu performance problem. When we move everything out of
4206 // view, we should rewrite this.
4207 private int mCurrentMenuState = 0;
4208 private int mMenuState = R.id.MAIN_MENU;
Andrei Popescuadc008d2009-06-26 14:11:30 +01004209 private int mOldMenuState = EMPTY_MENU;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004210 private static final int EMPTY_MENU = -1;
4211 private Menu mMenu;
4212
The Android Open Source Project0c908882009-03-03 19:32:16 -08004213 // Used to prevent chording to result in firing two shortcuts immediately
4214 // one after another. Fixes bug 1211714.
4215 boolean mCanChord;
4216
4217 private boolean mInLoad;
4218 private boolean mIsNetworkUp;
Ben Murdochb7cc8b42009-09-28 10:59:09 +01004219 private boolean mDidStopLoad;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004220
Cary Clark1f10cbf2010-03-22 11:45:23 -04004221 /* package */ boolean mActivityInPause = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004222
4223 private boolean mMenuIsDown;
4224
The Android Open Source Project0c908882009-03-03 19:32:16 -08004225 private static boolean mInTrace;
4226
4227 // Performance probe
4228 private static final int[] SYSTEM_CPU_FORMAT = new int[] {
4229 Process.PROC_SPACE_TERM | Process.PROC_COMBINE,
4230 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 1: user time
4231 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 2: nice time
4232 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 3: sys time
4233 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 4: idle time
4234 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 5: iowait time
4235 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 6: irq time
4236 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG // 7: softirq time
4237 };
4238
4239 private long mStart;
4240 private long mProcessStart;
4241 private long mUserStart;
4242 private long mSystemStart;
4243 private long mIdleStart;
4244 private long mIrqStart;
4245
4246 private long mUiStart;
4247
4248 private Drawable mMixLockIcon;
4249 private Drawable mSecLockIcon;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004250
4251 /* hold a ref so we can auto-cancel if necessary */
4252 private AlertDialog mAlertDialog;
4253
The Android Open Source Project0c908882009-03-03 19:32:16 -08004254 // The up-to-date URL and title (these can be different from those stored
4255 // in WebView, since it takes some time for the information in WebView to
4256 // get updated)
4257 private String mUrl;
4258 private String mTitle;
4259
4260 // As PageInfo has different style for landscape / portrait, we have
4261 // to re-open it when configuration changed
4262 private AlertDialog mPageInfoDialog;
Grace Kloba22ac16e2009-10-07 18:00:23 -07004263 private Tab mPageInfoView;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004264 // If the Page-Info dialog is launched from the SSL-certificate-on-error
4265 // dialog, we should not just dismiss it, but should get back to the
4266 // SSL-certificate-on-error dialog. This flag is used to store this state
Leon Scrogginsc7b92f82010-01-11 18:17:31 -05004267 private boolean mPageInfoFromShowSSLCertificateOnError;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004268
4269 // as SSLCertificateOnError has different style for landscape / portrait,
4270 // we have to re-open it when configuration changed
4271 private AlertDialog mSSLCertificateOnErrorDialog;
4272 private WebView mSSLCertificateOnErrorView;
4273 private SslErrorHandler mSSLCertificateOnErrorHandler;
4274 private SslError mSSLCertificateOnErrorError;
4275
4276 // as SSLCertificate has different style for landscape / portrait, we
4277 // have to re-open it when configuration changed
4278 private AlertDialog mSSLCertificateDialog;
Grace Kloba22ac16e2009-10-07 18:00:23 -07004279 private Tab mSSLCertificateView;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004280
4281 // as HttpAuthentication has different style for landscape / portrait, we
4282 // have to re-open it when configuration changed
4283 private AlertDialog mHttpAuthenticationDialog;
4284 private HttpAuthHandler mHttpAuthHandler;
4285
4286 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_PARAMS =
4287 new FrameLayout.LayoutParams(
Romain Guy15b8ec62010-01-08 15:06:43 -08004288 ViewGroup.LayoutParams.MATCH_PARENT,
4289 ViewGroup.LayoutParams.MATCH_PARENT);
Andrei Popescuadc008d2009-06-26 14:11:30 +01004290 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_GRAVITY_CENTER =
4291 new FrameLayout.LayoutParams(
Romain Guy15b8ec62010-01-08 15:06:43 -08004292 ViewGroup.LayoutParams.MATCH_PARENT,
4293 ViewGroup.LayoutParams.MATCH_PARENT,
Andrei Popescuadc008d2009-06-26 14:11:30 +01004294 Gravity.CENTER);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07004295 // Google search
4296 final static String QuickSearch_G = "http://www.google.com/m?q=%s";
The Android Open Source Project0c908882009-03-03 19:32:16 -08004297 // Wikipedia search
4298 final static String QuickSearch_W = "http://en.wikipedia.org/w/index.php?search=%s&go=Go";
4299 // Dictionary search
4300 final static String QuickSearch_D = "http://dictionary.reference.com/search?q=%s";
4301 // Google Mobile Local search
4302 final static String QuickSearch_L = "http://www.google.com/m/search?site=local&q=%s&near=mountain+view";
4303
4304 final static String QUERY_PLACE_HOLDER = "%s";
4305
4306 // "source" parameter for Google search through search key
4307 final static String GOOGLE_SEARCH_SOURCE_SEARCHKEY = "browser-key";
4308 // "source" parameter for Google search through goto menu
4309 final static String GOOGLE_SEARCH_SOURCE_GOTO = "browser-goto";
4310 // "source" parameter for Google search through simplily type
4311 final static String GOOGLE_SEARCH_SOURCE_TYPE = "browser-type";
4312 // "source" parameter for Google search suggested by the browser
4313 final static String GOOGLE_SEARCH_SOURCE_SUGGEST = "browser-suggest";
4314 // "source" parameter for Google search from unknown source
4315 final static String GOOGLE_SEARCH_SOURCE_UNKNOWN = "unknown";
4316
4317 private final static String LOGTAG = "browser";
4318
The Android Open Source Project0c908882009-03-03 19:32:16 -08004319 private String mLastEnteredUrl;
4320
4321 private PowerManager.WakeLock mWakeLock;
4322 private final static int WAKELOCK_TIMEOUT = 5 * 60 * 1000; // 5 minutes
4323
4324 private Toast mStopToast;
4325
Leon Scroggins571b3762010-05-26 10:25:01 -04004326 private TitleBarBase mTitleBar;
Michael Kolba2b2ba82010-08-04 17:54:03 -07004327 private TabBar mTabBar;
Leon Scroggins81db3662009-06-04 17:45:11 -04004328
Ben Murdochbff2d602009-07-01 20:19:05 +01004329 private LinearLayout mErrorConsoleContainer = null;
4330 private boolean mShouldShowErrorConsole = false;
4331
The Android Open Source Project0c908882009-03-03 19:32:16 -08004332 // As the ids are dynamically created, we can't guarantee that they will
4333 // be in sequence, so this static array maps ids to a window number.
4334 final static private int[] WINDOW_SHORTCUT_ID_ARRAY =
4335 { R.id.window_one_menu_id, R.id.window_two_menu_id, R.id.window_three_menu_id,
4336 R.id.window_four_menu_id, R.id.window_five_menu_id, R.id.window_six_menu_id,
4337 R.id.window_seven_menu_id, R.id.window_eight_menu_id };
4338
4339 // monitor platform changes
4340 private IntentFilter mNetworkStateChangedFilter;
4341 private BroadcastReceiver mNetworkStateIntentReceiver;
4342
Bjorn Bringerta7611812010-03-24 11:12:02 +00004343 private SystemAllowGeolocationOrigins mSystemAllowGeolocationOrigins;
4344
The Android Open Source Project0c908882009-03-03 19:32:16 -08004345 // activity requestCode
Nicolas Roard78a98e42009-05-11 13:34:17 +01004346 final static int COMBO_PAGE = 1;
4347 final static int DOWNLOAD_PAGE = 2;
4348 final static int PREFERENCES_PAGE = 3;
Leon Scroggins8d5fa432009-10-02 15:55:59 -04004349 final static int FILE_SELECTED = 4;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004350
Andrei Popescu540035d2009-09-18 18:59:20 +01004351 // the default <video> poster
4352 private Bitmap mDefaultVideoPoster;
4353 // the video progress view
4354 private View mVideoProgressView;
4355
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004356 /**
4357 * A UrlData class to abstract how the content will be set to WebView.
4358 * This base class uses loadUrl to show the content.
4359 */
Leon Scroggins6eac63e2010-03-15 18:19:14 -04004360 /* package */ static class UrlData {
Grace Kloba068e48b2010-01-26 18:11:27 -08004361 final String mUrl;
4362 final Map<String, String> mHeaders;
Leon Scroggins58d56c62010-01-28 15:12:40 -05004363 final Intent mVoiceIntent;
Grace Kloba60e095c2009-06-16 11:50:55 -07004364
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004365 UrlData(String url) {
4366 this.mUrl = url;
Grace Kloba068e48b2010-01-26 18:11:27 -08004367 this.mHeaders = null;
Leon Scroggins58d56c62010-01-28 15:12:40 -05004368 this.mVoiceIntent = null;
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004369 }
Grace Kloba60e095c2009-06-16 11:50:55 -07004370
Leon Scroggins58d56c62010-01-28 15:12:40 -05004371 UrlData(String url, Map<String, String> headers, Intent intent) {
Grace Kloba068e48b2010-01-26 18:11:27 -08004372 this.mUrl = url;
4373 this.mHeaders = headers;
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -05004374 if (RecognizerResultsIntent.ACTION_VOICE_SEARCH_RESULTS
4375 .equals(intent.getAction())) {
Leon Scroggins58d56c62010-01-28 15:12:40 -05004376 this.mVoiceIntent = intent;
4377 } else {
4378 this.mVoiceIntent = null;
4379 }
Grace Kloba60e095c2009-06-16 11:50:55 -07004380 }
4381
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004382 boolean isEmpty() {
Leon Scroggins58d56c62010-01-28 15:12:40 -05004383 return mVoiceIntent == null && (mUrl == null || mUrl.length() == 0);
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004384 }
4385
Leon Scroggins92472e82010-02-17 16:32:28 -05004386 /**
4387 * Load this UrlData into the given Tab. Use loadUrlDataIn to update
4388 * the title bar as well.
4389 */
Leon Scroggins58d56c62010-01-28 15:12:40 -05004390 public void loadIn(Tab t) {
4391 if (mVoiceIntent != null) {
4392 t.activateVoiceSearchMode(mVoiceIntent);
4393 } else {
4394 t.getWebView().loadUrl(mUrl, mHeaders);
4395 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004396 }
4397 };
4398
Leon Scroggins1f005d32009-08-10 17:36:42 -04004399 /* package */ static final UrlData EMPTY_URL_DATA = new UrlData(null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004400}