blob: ec4a78a0bb18ea5680ef358e8158bf4a6594e8bf [file] [log] [blame]
The Android Open Source Project0c908882009-03-03 19:32:16 -08001/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.browser;
18
Michael Kolb3f65c382010-08-20 15:31:16 -070019import com.android.browser.ScrollWebView.ScrollListener;
Bjorn Bringertd69f51d2010-09-13 14:06:41 +010020import com.android.browser.search.SearchEngine;
Michael Kolb3f65c382010-08-20 15:31:16 -070021import com.android.common.Search;
22import com.android.common.speech.LoggingEvents;
23
Michael Kolbed217742010-08-10 17:52:34 -070024import android.app.ActionBar;
The Android Open Source Project0c908882009-03-03 19:32:16 -080025import android.app.Activity;
The Android Open Source Project0c908882009-03-03 19:32:16 -080026import android.app.AlertDialog;
Michael Kolbc7485ae2010-09-03 10:10:58 -070027import android.app.Dialog;
Steve Howard5a862fc2010-09-28 12:52:06 -070028import android.app.DownloadManager;
The Android Open Source Project0c908882009-03-03 19:32:16 -080029import android.app.ProgressDialog;
30import android.app.SearchManager;
31import android.content.ActivityNotFoundException;
32import android.content.BroadcastReceiver;
Dianne Hackborn80f32622010-08-05 14:17:53 -070033import android.content.ClipboardManager;
The Android Open Source Project0c908882009-03-03 19:32:16 -080034import android.content.ComponentName;
Leon Scroggins58d56c62010-01-28 15:12:40 -050035import android.content.ContentProvider;
36import android.content.ContentProviderClient;
The Android Open Source Project0c908882009-03-03 19:32:16 -080037import android.content.ContentResolver;
38import android.content.ContentValues;
39import android.content.Context;
40import android.content.DialogInterface;
41import android.content.Intent;
42import android.content.IntentFilter;
The Android Open Source Project0c908882009-03-03 19:32:16 -080043import android.content.pm.PackageManager;
44import android.content.pm.ResolveInfo;
The Android Open Source Project0c908882009-03-03 19:32:16 -080045import android.content.res.Configuration;
46import android.content.res.Resources;
47import android.database.Cursor;
The Android Open Source Project0c908882009-03-03 19:32:16 -080048import android.graphics.Bitmap;
Andrei Popescu540035d2009-09-18 18:59:20 +010049import android.graphics.BitmapFactory;
The Android Open Source Project0c908882009-03-03 19:32:16 -080050import android.graphics.Canvas;
The Android Open Source Project0c908882009-03-03 19:32:16 -080051import android.graphics.Picture;
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -040052import android.graphics.PixelFormat;
The Android Open Source Project0c908882009-03-03 19:32:16 -080053import android.graphics.drawable.Drawable;
The Android Open Source Project0c908882009-03-03 19:32:16 -080054import android.net.ConnectivityManager;
Andrei Popescu56199cc2010-01-12 22:39:16 +000055import android.net.NetworkInfo;
The Android Open Source Project0c908882009-03-03 19:32:16 -080056import android.net.Uri;
57import android.net.WebAddress;
The Android Open Source Project0c908882009-03-03 19:32:16 -080058import android.net.http.SslCertificate;
59import android.net.http.SslError;
60import android.os.AsyncTask;
61import android.os.Bundle;
62import android.os.Debug;
63import android.os.Environment;
64import android.os.Handler;
The Android Open Source Project0c908882009-03-03 19:32:16 -080065import android.os.Message;
66import android.os.PowerManager;
67import android.os.Process;
The Android Open Source Project0c908882009-03-03 19:32:16 -080068import android.os.SystemClock;
The Android Open Source Project0c908882009-03-03 19:32:16 -080069import android.provider.Browser;
Michael Kolb370a4f32010-10-06 10:45:32 -070070import android.provider.BrowserContract;
Jeff Hamilton1a805652010-09-07 12:36:30 -070071import android.provider.BrowserContract.Images;
Michael Kolbe421c242010-10-04 19:29:01 -070072import android.provider.ContactsContract;
Michael Kolba2b2ba82010-08-04 17:54:03 -070073import android.provider.ContactsContract.Intents.Insert;
The Android Open Source Project0c908882009-03-03 19:32:16 -080074import android.provider.Downloads;
75import android.provider.MediaStore;
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -050076import android.speech.RecognizerResultsIntent;
The Android Open Source Project0c908882009-03-03 19:32:16 -080077import android.text.TextUtils;
78import android.text.format.DateFormat;
The Android Open Source Project0c908882009-03-03 19:32:16 -080079import android.util.Log;
Dianne Hackborn385effd2010-02-24 20:03:04 -080080import android.util.Patterns;
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -040081import android.view.ActionMode;
The Android Open Source Project0c908882009-03-03 19:32:16 -080082import android.view.ContextMenu;
Michael Kolba2b2ba82010-08-04 17:54:03 -070083import android.view.ContextMenu.ContextMenuInfo;
The Android Open Source Project0c908882009-03-03 19:32:16 -080084import android.view.Gravity;
85import android.view.KeyEvent;
86import android.view.LayoutInflater;
87import android.view.Menu;
88import android.view.MenuInflater;
89import android.view.MenuItem;
Michael Kolba2b2ba82010-08-04 17:54:03 -070090import android.view.MenuItem.OnMenuItemClickListener;
The Android Open Source Project0c908882009-03-03 19:32:16 -080091import android.view.View;
92import android.view.ViewGroup;
93import android.view.Window;
94import android.view.WindowManager;
Svetoslav Ganov2b345992010-05-06 06:13:54 -070095import android.view.accessibility.AccessibilityManager;
The Android Open Source Project0c908882009-03-03 19:32:16 -080096import android.webkit.CookieManager;
97import android.webkit.CookieSyncManager;
98import android.webkit.DownloadListener;
99import android.webkit.HttpAuthHandler;
100import android.webkit.SslErrorHandler;
101import android.webkit.URLUtil;
Leon Clarkecb6cc862009-09-29 18:35:13 +0100102import android.webkit.ValueCallback;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800103import android.webkit.WebChromeClient;
104import android.webkit.WebHistoryItem;
105import android.webkit.WebIconDatabase;
106import android.webkit.WebView;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800107import android.widget.EditText;
108import android.widget.FrameLayout;
109import android.widget.LinearLayout;
Michael Kolbc7485ae2010-09-03 10:10:58 -0700110import android.widget.PopupMenu;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800111import android.widget.TextView;
112import android.widget.Toast;
113
Leon Scrogginsb6b7f9e2009-06-18 12:05:28 -0400114import java.io.ByteArrayOutputStream;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800115import java.io.File;
Ben Murdoch4f75ba22009-10-27 11:48:28 +0000116import java.io.IOException;
117import java.io.InputStream;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800118import java.net.MalformedURLException;
Dianne Hackborn99189432009-06-17 18:06:18 -0700119import java.net.URISyntaxException;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800120import java.net.URL;
121import java.net.URLEncoder;
Elliott Slaughter3d6df162010-08-25 13:17:44 -0700122import java.util.Calendar;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800123import java.util.Date;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800124import java.util.HashMap;
Grace Kloba00f54c52010-01-27 14:53:51 -0800125import java.util.Iterator;
Grace Kloba068e48b2010-01-26 18:11:27 -0800126import java.util.Map;
Michael Kolbfe251992010-07-08 15:41:55 -0700127import java.util.Vector;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800128import java.util.regex.Matcher;
129import java.util.regex.Pattern;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800130
131public class BrowserActivity extends Activity
Michael Kolbe421c242010-10-04 19:29:01 -0700132 implements View.OnCreateContextMenuListener, DownloadListener,
133 PopupMenu.OnMenuItemClickListener, BookmarksHistoryCallbacks {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800134
Dave Bort31a6d1c2009-04-13 15:56:49 -0700135 /* Define some aliases to make these debugging flags easier to refer to.
136 * This file imports android.provider.Browser, so we can't just refer to "Browser.DEBUG".
137 */
138 private final static boolean DEBUG = com.android.browser.Browser.DEBUG;
139 private final static boolean LOGV_ENABLED = com.android.browser.Browser.LOGV_ENABLED;
140 private final static boolean LOGD_ENABLED = com.android.browser.Browser.LOGD_ENABLED;
141
Cary Clarka9771242009-08-11 16:42:26 -0400142 private static class ClearThumbnails extends AsyncTask<File, Void, Void> {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800143 @Override
144 public Void doInBackground(File... files) {
145 if (files != null) {
146 for (File f : files) {
Cary Clarkd6be1752009-08-12 12:56:42 -0400147 if (!f.delete()) {
148 Log.e(LOGTAG, f.getPath() + " was not deleted");
149 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800150 }
151 }
152 return null;
153 }
154 }
155
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400156 /**
157 * This layout holds everything you see below the status bar, including the
158 * error console, the custom view container, and the webviews.
159 */
160 private FrameLayout mBrowserFrameLayout;
Leon Scroggins81db3662009-06-04 17:45:11 -0400161
Michael Kolbe421c242010-10-04 19:29:01 -0700162 private CombinedBookmarkHistoryView mComboView;
163
Leon Scrogginsd746a942010-05-19 13:21:44 -0400164 private boolean mXLargeScreenSize;
165
Jeff Davidson43610292010-07-16 16:03:58 -0700166 private Boolean mIsProviderPresent = null;
167 private Uri mRlzUri = null;
168
Grace Kloba22ac16e2009-10-07 18:00:23 -0700169 @Override
170 public void onCreate(Bundle icicle) {
Dave Bort31a6d1c2009-04-13 15:56:49 -0700171 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800172 Log.v(LOGTAG, this + " onStart");
173 }
174 super.onCreate(icicle);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800175 // test the browser in OpenGL
176 // requestWindowFeature(Window.FEATURE_OPENGL);
177
Mike Reedd334bf52010-01-26 15:21:44 -0500178 // enable this to test the browser in 32bit
179 if (false) {
180 getWindow().setFormat(PixelFormat.RGBX_8888);
181 BitmapFactory.setDefaultConfig(Bitmap.Config.ARGB_8888);
182 }
183
Bjorn Bringertb1402a52010-10-12 10:53:12 +0100184 if (((AccessibilityManager) getSystemService(ACCESSIBILITY_SERVICE)).isEnabled()) {
Svetoslav Ganov2b345992010-05-06 06:13:54 -0700185 setDefaultKeyMode(DEFAULT_KEYS_DISABLE);
186 } else {
187 setDefaultKeyMode(DEFAULT_KEYS_SEARCH_LOCAL);
188 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800189
190 mResolver = getContentResolver();
191
Leon Scroggins IIIcc14c8c2010-09-27 12:45:34 -0400192 // Keep a settings instance handy.
193 mSettings = BrowserSettings.getInstance();
194
Grace Kloba0923d692009-09-23 21:37:25 -0700195 // If this was a web search request, pass it on to the default web
196 // search provider and finish this activity.
197 if (handleWebSearchIntent(getIntent())) {
198 finish();
199 return;
200 }
201
The Android Open Source Project0c908882009-03-03 19:32:16 -0800202 mSecLockIcon = Resources.getSystem().getDrawable(
203 android.R.drawable.ic_secure);
204 mMixLockIcon = Resources.getSystem().getDrawable(
205 android.R.drawable.ic_partial_secure);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800206
Michael Kolbed217742010-08-10 17:52:34 -0700207 // Create the tab control and our initial tab
208 mTabControl = new TabControl(this);
209
210 mXLargeScreenSize = (getResources().getConfiguration().screenLayout
211 & Configuration.SCREENLAYOUT_SIZE_MASK)
212 == Configuration.SCREENLAYOUT_SIZE_XLARGE;
213
Leon Scroggins81db3662009-06-04 17:45:11 -0400214 FrameLayout frameLayout = (FrameLayout) getWindow().getDecorView()
Bjorn Bringertb1402a52010-10-12 10:53:12 +0100215 .findViewById(android.R.id.content);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400216 mBrowserFrameLayout = (FrameLayout) LayoutInflater.from(this)
217 .inflate(R.layout.custom_screen, null);
218 mContentView = (FrameLayout) mBrowserFrameLayout.findViewById(
219 R.id.main_content);
220 mErrorConsoleContainer = (LinearLayout) mBrowserFrameLayout
221 .findViewById(R.id.error_console);
222 mCustomViewContainer = (FrameLayout) mBrowserFrameLayout
223 .findViewById(R.id.fullscreen_custom_content);
224 frameLayout.addView(mBrowserFrameLayout, COVER_SCREEN_PARAMS);
Michael Kolbe0a36662010-06-29 10:37:12 -0700225
Leon Scrogginsd746a942010-05-19 13:21:44 -0400226 if (mXLargeScreenSize) {
Michael Kolba2b2ba82010-08-04 17:54:03 -0700227 mTitleBar = new TitleBarXLarge(this);
228 mTitleBar.setProgress(100);
229 mFakeTitleBar = new TitleBarXLarge(this);
Michael Kolbed217742010-08-10 17:52:34 -0700230 ActionBar actionBar = getActionBar();
Michael Kolba2b2ba82010-08-04 17:54:03 -0700231 mTabBar = new TabBar(this, mTabControl, (TitleBarXLarge) mFakeTitleBar);
Michael Kolbed217742010-08-10 17:52:34 -0700232 actionBar.setCustomNavigationMode(mTabBar);
Michael Kolb68775752010-08-19 12:42:01 -0700233 // disable built in zoom controls
234 mTabControl.setDisplayZoomControls(false);
Leon Scrogginsd746a942010-05-19 13:21:44 -0400235 } else {
Leon Scroggins571b3762010-05-26 10:25:01 -0400236 mTitleBar = new TitleBar(this);
Leon Scrogginsd746a942010-05-19 13:21:44 -0400237 // mTitleBar will be always be shown in the fully loaded mode on
238 // phone
239 mTitleBar.setProgress(100);
Leon Scrogginsd746a942010-05-19 13:21:44 -0400240 mFakeTitleBar = new TitleBar(this);
241 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800242
The Android Open Source Project0c908882009-03-03 19:32:16 -0800243 // Open the icon database and retain all the bookmark urls for favicons
244 retainIconsOnStartup();
245
The Android Open Source Project0c908882009-03-03 19:32:16 -0800246 mSettings.setTabControl(mTabControl);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800247
248 PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
249 mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Browser");
250
Patrick Scott6adacc92010-03-05 08:24:51 -0500251 // Find out if the network is currently up.
252 ConnectivityManager cm = (ConnectivityManager) getSystemService(
253 Context.CONNECTIVITY_SERVICE);
254 NetworkInfo info = cm.getActiveNetworkInfo();
255 if (info != null) {
256 mIsNetworkUp = info.isAvailable();
257 }
258
Grace Klobaa34f6862009-07-31 16:28:17 -0700259 /* enables registration for changes in network status from
260 http stack */
261 mNetworkStateChangedFilter = new IntentFilter();
262 mNetworkStateChangedFilter.addAction(
263 ConnectivityManager.CONNECTIVITY_ACTION);
264 mNetworkStateIntentReceiver = new BroadcastReceiver() {
265 @Override
266 public void onReceive(Context context, Intent intent) {
267 if (intent.getAction().equals(
268 ConnectivityManager.CONNECTIVITY_ACTION)) {
Andrei Popescue4c98462010-02-19 15:44:13 +0000269
270 NetworkInfo info = intent.getParcelableExtra(
271 ConnectivityManager.EXTRA_NETWORK_INFO);
272 String typeName = info.getTypeName();
273 String subtypeName = info.getSubtypeName();
274 sendNetworkType(typeName.toLowerCase(),
275 (subtypeName != null ? subtypeName.toLowerCase() : ""));
276
277 onNetworkToggle(info.isAvailable());
Grace Klobaa34f6862009-07-31 16:28:17 -0700278 }
279 }
280 };
281
Elliott Slaughter3d6df162010-08-25 13:17:44 -0700282 // Unless the last browser usage was within 24 hours, destroy any
283 // remaining incognito tabs.
284
285 Calendar lastActiveDate = icicle != null ? (Calendar) icicle.getSerializable("lastActiveDate") : null;
286 Calendar today = Calendar.getInstance();
287 Calendar yesterday = Calendar.getInstance();
288 yesterday.add(Calendar.DATE, -1);
289
290 boolean dontRestoreIncognitoTabs = lastActiveDate == null
291 || lastActiveDate.before(yesterday)
292 || lastActiveDate.after(today);
293
294 if (!mTabControl.restoreState(icicle, dontRestoreIncognitoTabs)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800295 // clear up the thumbnail directory if we can't restore the state as
296 // none of the files in the directory are referenced any more.
297 new ClearThumbnails().execute(
298 mTabControl.getThumbnailDir().listFiles());
Grace Klobaaab3f092009-07-30 12:29:51 -0700299 // there is no quit on Android. But if we can't restore the state,
300 // we can treat it as a new Browser, remove the old session cookies.
301 CookieManager.getInstance().removeSessionCookie();
Elliott Slaughter3d6df162010-08-25 13:17:44 -0700302 // remove any incognito files
303 WebView.cleanupPrivateBrowsingFiles(this);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800304 final Intent intent = getIntent();
305 final Bundle extra = intent.getExtras();
306 // Create an initial tab.
307 // If the intent is ACTION_VIEW and data is not null, the Browser is
308 // invoked to view the content by another application. In this case,
309 // the tab will be close when exit.
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700310 UrlData urlData = getUrlDataFromIntent(intent);
311
Leon Scroggins58d56c62010-01-28 15:12:40 -0500312 String action = intent.getAction();
Grace Kloba22ac16e2009-10-07 18:00:23 -0700313 final Tab t = mTabControl.createNewTab(
Leon Scroggins58d56c62010-01-28 15:12:40 -0500314 (Intent.ACTION_VIEW.equals(action) &&
315 intent.getData() != null)
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -0500316 || RecognizerResultsIntent.ACTION_VOICE_SEARCH_RESULTS
317 .equals(action),
Elliott Slaughterf0f03952010-07-14 18:10:36 -0700318 intent.getStringExtra(Browser.EXTRA_APPLICATION_ID),
319 urlData.mUrl, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800320 mTabControl.setCurrentTab(t);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800321 attachTabToContentView(t);
322 WebView webView = t.getWebView();
323 if (extra != null) {
324 int scale = extra.getInt(Browser.INITIAL_ZOOM_LEVEL, 0);
325 if (scale > 0 && scale <= 1000) {
326 webView.setInitialScale(scale);
327 }
328 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800329
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700330 if (urlData.isEmpty()) {
Shimeng (Simon) Wang98d5fce2010-03-16 13:23:39 -0700331 loadUrl(webView, mSettings.getHomePage());
The Android Open Source Project0c908882009-03-03 19:32:16 -0800332 } else {
Patrick Scott9d53da02010-02-19 10:19:01 -0500333 loadUrlDataIn(t, urlData);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800334 }
335 } else {
Elliott Slaughter3d6df162010-08-25 13:17:44 -0700336 if (dontRestoreIncognitoTabs) {
337 WebView.cleanupPrivateBrowsingFiles(this);
338 }
339
The Android Open Source Project0c908882009-03-03 19:32:16 -0800340 // TabControl.restoreState() will create a new tab even if
Leon Scroggins1f005d32009-08-10 17:36:42 -0400341 // restoring the state fails.
The Android Open Source Project0c908882009-03-03 19:32:16 -0800342 attachTabToContentView(mTabControl.getCurrentTab());
343 }
Grace Kloba615c6c92009-08-03 10:22:44 -0700344
Cary Clarkb4b83182010-07-01 12:36:56 -0400345 // Delete old thumbnails to save space
346 File dir = mTabControl.getThumbnailDir();
347 if (dir.exists()) {
348 for (String child : dir.list()) {
349 File f = new File(dir, child);
350 f.delete();
351 }
352 }
353
Feng Qianb3c02da2009-06-29 15:58:08 -0700354 // Read JavaScript flags if it exists.
355 String jsFlags = mSettings.getJsFlags();
356 if (jsFlags.trim().length() != 0) {
357 mTabControl.getCurrentWebView().setJsFlags(jsFlags);
358 }
Bjorn Bringerta7611812010-03-24 11:12:02 +0000359
360 // Start watching the default geolocation permissions
361 mSystemAllowGeolocationOrigins
362 = new SystemAllowGeolocationOrigins(getApplicationContext());
363 mSystemAllowGeolocationOrigins.start();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800364 }
365
Michael Kolba2b2ba82010-08-04 17:54:03 -0700366 ScrollListener getScrollListener() {
367 return mTabBar;
368 }
369
Leon Scroggins58d56c62010-01-28 15:12:40 -0500370 /**
371 * Feed the previously stored results strings to the BrowserProvider so that
372 * the SearchDialog will show them instead of the standard searches.
373 * @param result String to show on the editable line of the SearchDialog.
374 */
375 /* package */ void showVoiceSearchResults(String result) {
376 ContentProviderClient client = mResolver.acquireContentProviderClient(
377 Browser.BOOKMARKS_URI);
378 ContentProvider prov = client.getLocalContentProvider();
379 BrowserProvider bp = (BrowserProvider) prov;
380 bp.setQueryResults(mTabControl.getCurrentTab().getVoiceSearchResults());
381 client.release();
382
Leon Scrogginsfbb3f152010-03-09 17:26:56 -0500383 Bundle bundle = createGoogleSearchSourceBundle(
384 GOOGLE_SEARCH_SOURCE_SEARCHKEY);
385 bundle.putBoolean(SearchManager.CONTEXT_IS_VOICE, true);
386 startSearch(result, false, bundle, false);
Leon Scroggins58d56c62010-01-28 15:12:40 -0500387 }
388
The Android Open Source Project0c908882009-03-03 19:32:16 -0800389 @Override
390 protected void onNewIntent(Intent intent) {
Grace Kloba22ac16e2009-10-07 18:00:23 -0700391 Tab current = mTabControl.getCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800392 // When a tab is closed on exit, the current tab index is set to -1.
393 // Reset before proceed as Browser requires the current tab to be set.
394 if (current == null) {
395 // Try to reset the tab in case the index was incorrect.
396 current = mTabControl.getTab(0);
397 if (current == null) {
398 // No tabs at all so just ignore this intent.
399 return;
400 }
401 mTabControl.setCurrentTab(current);
402 attachTabToContentView(current);
403 resetTitleAndIcon(current.getWebView());
404 }
405 final String action = intent.getAction();
406 final int flags = intent.getFlags();
407 if (Intent.ACTION_MAIN.equals(action) ||
408 (flags & Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY) != 0) {
409 // just resume the browser
410 return;
411 }
Leon Scrogginsb8a844d2010-03-18 15:06:15 -0400412 // In case the SearchDialog is open.
413 ((SearchManager) getSystemService(Context.SEARCH_SERVICE))
414 .stopSearch();
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -0500415 boolean activateVoiceSearch = RecognizerResultsIntent
416 .ACTION_VOICE_SEARCH_RESULTS.equals(action);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800417 if (Intent.ACTION_VIEW.equals(action)
418 || Intent.ACTION_SEARCH.equals(action)
419 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
Leon Scroggins58d56c62010-01-28 15:12:40 -0500420 || Intent.ACTION_WEB_SEARCH.equals(action)
421 || activateVoiceSearch) {
Leon Scroggins3b18ce32010-02-08 17:35:59 -0500422 if (current.isInVoiceSearchMode()) {
423 String title = current.getVoiceDisplayTitle();
424 if (title != null && title.equals(intent.getStringExtra(
425 SearchManager.QUERY))) {
426 // The user submitted the same search as the last voice
427 // search, so do nothing.
428 return;
429 }
Leon Scroggins1fe13a52010-02-09 15:31:26 -0500430 if (Intent.ACTION_SEARCH.equals(action)
431 && current.voiceSearchSourceIsGoogle()) {
432 Intent logIntent = new Intent(
433 LoggingEvents.ACTION_LOG_EVENT);
434 logIntent.putExtra(LoggingEvents.EXTRA_EVENT,
435 LoggingEvents.VoiceSearch.QUERY_UPDATED);
436 logIntent.putExtra(
437 LoggingEvents.VoiceSearch.EXTRA_QUERY_UPDATED_VALUE,
438 intent.getDataString());
439 sendBroadcast(logIntent);
440 // Note, onPageStarted will revert the voice title bar
441 // When http://b/issue?id=2379215 is fixed, we should update
442 // the title bar here.
443 }
Leon Scroggins3b18ce32010-02-08 17:35:59 -0500444 }
Satish Sampath565505b2009-05-29 15:37:27 +0100445 // If this was a search request (e.g. search query directly typed into the address bar),
446 // pass it on to the default web search provider.
447 if (handleWebSearchIntent(intent)) {
448 return;
449 }
450
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700451 UrlData urlData = getUrlDataFromIntent(intent);
452 if (urlData.isEmpty()) {
453 urlData = new UrlData(mSettings.getHomePage());
The Android Open Source Project0c908882009-03-03 19:32:16 -0800454 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700455
Grace Klobacc634032009-07-28 15:58:19 -0700456 final String appId = intent
457 .getStringExtra(Browser.EXTRA_APPLICATION_ID);
Leon Scroggins47208682010-04-07 17:59:48 -0400458 if ((Intent.ACTION_VIEW.equals(action)
459 // If a voice search has no appId, it means that it came
460 // from the browser. In that case, reuse the current tab.
461 || (activateVoiceSearch && appId != null))
Grace Klobacc634032009-07-28 15:58:19 -0700462 && !getPackageName().equals(appId)
463 && (flags & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0) {
Grace Kloba22ac16e2009-10-07 18:00:23 -0700464 Tab appTab = mTabControl.getTabFromId(appId);
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700465 if (appTab != null) {
466 Log.i(LOGTAG, "Reusing tab for " + appId);
467 // Dismiss the subwindow if applicable.
468 dismissSubWindow(appTab);
469 // Since we might kill the WebView, remove it from the
470 // content view first.
471 removeTabFromContentView(appTab);
472 // Recreate the main WebView after destroying the old one.
473 // If the WebView has the same original url and is on that
474 // page, it can be reused.
475 boolean needsLoad =
Leon Scroggins6eac63e2010-03-15 18:19:14 -0400476 mTabControl.recreateWebView(appTab, urlData);
Ben Murdochbff2d602009-07-01 20:19:05 +0100477
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700478 if (current != appTab) {
Leon Scroggins1f005d32009-08-10 17:36:42 -0400479 switchToTab(mTabControl.getTabIndex(appTab));
480 if (needsLoad) {
Patrick Scott9d53da02010-02-19 10:19:01 -0500481 loadUrlDataIn(appTab, urlData);
Leon Scroggins1f005d32009-08-10 17:36:42 -0400482 }
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700483 } else {
Leon Scroggins1f005d32009-08-10 17:36:42 -0400484 // If the tab was the current tab, we have to attach
485 // it to the view system again.
486 attachTabToContentView(appTab);
487 if (needsLoad) {
Patrick Scott9d53da02010-02-19 10:19:01 -0500488 loadUrlDataIn(appTab, urlData);
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700489 }
490 }
491 return;
Patrick Scottcd115892009-07-16 09:42:58 -0400492 } else {
493 // No matching application tab, try to find a regular tab
494 // with a matching url.
495 appTab = mTabControl.findUnusedTabWithUrl(urlData.mUrl);
Leon Scroggins25515f82009-08-19 15:31:58 -0400496 if (appTab != null) {
497 if (current != appTab) {
498 switchToTab(mTabControl.getTabIndex(appTab));
499 }
500 // Otherwise, we are already viewing the correct tab.
Patrick Scottcd115892009-07-16 09:42:58 -0400501 } else {
502 // if FLAG_ACTIVITY_BROUGHT_TO_FRONT flag is on, the url
503 // will be opened in a new tab unless we have reached
504 // MAX_TABS. Then the url will be opened in the current
505 // tab. If a new tab is created, it will have "true" for
506 // exit on close.
Leon Scroggins1f005d32009-08-10 17:36:42 -0400507 openTabAndShow(urlData, true, appId);
Patrick Scottcd115892009-07-16 09:42:58 -0400508 }
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700509 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800510 } else {
Grace Kloba638d3f42009-11-23 10:35:04 -0800511 if (!urlData.isEmpty()
512 && urlData.mUrl.startsWith("about:debug")) {
513 if ("about:debug.dom".equals(urlData.mUrl)) {
514 current.getWebView().dumpDomTree(false);
515 } else if ("about:debug.dom.file".equals(urlData.mUrl)) {
516 current.getWebView().dumpDomTree(true);
517 } else if ("about:debug.render".equals(urlData.mUrl)) {
518 current.getWebView().dumpRenderTree(false);
519 } else if ("about:debug.render.file".equals(urlData.mUrl)) {
520 current.getWebView().dumpRenderTree(true);
521 } else if ("about:debug.display".equals(urlData.mUrl)) {
522 current.getWebView().dumpDisplayTree();
Mike Reed9b78e1d2010-01-13 14:40:52 -0800523 } else if (urlData.mUrl.startsWith("about:debug.drag")) {
524 int index = urlData.mUrl.codePointAt(16) - '0';
525 if (index <= 0 || index > 9) {
526 current.getWebView().setDragTracker(null);
527 } else {
528 current.getWebView().setDragTracker(new MeshTracker(index));
529 }
Grace Kloba638d3f42009-11-23 10:35:04 -0800530 } else {
531 mSettings.toggleDebugSettings();
532 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800533 return;
534 }
Leon Scroggins1f005d32009-08-10 17:36:42 -0400535 // Get rid of the subwindow if it exists
536 dismissSubWindow(current);
Leon Scroggins8588d152010-04-15 11:01:53 -0400537 // If the current Tab is being used as an application tab,
538 // remove the association, since the new Intent means that it is
539 // no longer associated with that application.
540 current.setAppId(null);
Patrick Scott9d53da02010-02-19 10:19:01 -0500541 loadUrlDataIn(current, urlData);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800542 }
543 }
544 }
545
Satish Sampath565505b2009-05-29 15:37:27 +0100546 /**
547 * Launches the default web search activity with the query parameters if the given intent's data
548 * are identified as plain search terms and not URLs/shortcuts.
549 * @return true if the intent was handled and web search activity was launched, false if not.
550 */
551 private boolean handleWebSearchIntent(Intent intent) {
552 if (intent == null) return false;
553
554 String url = null;
555 final String action = intent.getAction();
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -0500556 if (RecognizerResultsIntent.ACTION_VOICE_SEARCH_RESULTS.equals(
557 action)) {
Leon Scroggins58d56c62010-01-28 15:12:40 -0500558 return false;
559 }
Satish Sampath565505b2009-05-29 15:37:27 +0100560 if (Intent.ACTION_VIEW.equals(action)) {
Grace Kloba1e705052009-09-29 13:13:36 -0700561 Uri data = intent.getData();
562 if (data != null) url = data.toString();
Satish Sampath565505b2009-05-29 15:37:27 +0100563 } else if (Intent.ACTION_SEARCH.equals(action)
564 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
565 || Intent.ACTION_WEB_SEARCH.equals(action)) {
566 url = intent.getStringExtra(SearchManager.QUERY);
567 }
Bjorn Bringert04851702009-09-22 10:36:01 +0100568 return handleWebSearchRequest(url, intent.getBundleExtra(SearchManager.APP_DATA),
569 intent.getStringExtra(SearchManager.EXTRA_DATA_KEY));
Satish Sampath565505b2009-05-29 15:37:27 +0100570 }
571
572 /**
573 * Launches the default web search activity with the query parameters if the given url string
574 * was identified as plain search terms and not URL/shortcut.
575 * @return true if the request was handled and web search activity was launched, false if not.
576 */
Bjorn Bringert04851702009-09-22 10:36:01 +0100577 private boolean handleWebSearchRequest(String inUrl, Bundle appData, String extraData) {
Satish Sampath565505b2009-05-29 15:37:27 +0100578 if (inUrl == null) return false;
579
580 // In general, we shouldn't modify URL from Intent.
581 // But currently, we get the user-typed URL from search box as well.
582 String url = fixUrl(inUrl).trim();
583
Leon Scroggins956cf012010-10-07 13:51:57 -0400584 // URLs are handled by the regular flow of control, so
Satish Sampath565505b2009-05-29 15:37:27 +0100585 // return early.
Dan Egnor5ee906c2009-11-18 12:11:49 -0800586 if (Patterns.WEB_URL.matcher(url).matches()
Leon Scroggins956cf012010-10-07 13:51:57 -0400587 || ACCEPTED_URI_SCHEMA.matcher(url).matches()) {
Satish Sampath565505b2009-05-29 15:37:27 +0100588 return false;
589 }
590
Leon Scroggins8d06e362010-03-24 14:45:57 -0400591 final ContentResolver cr = mResolver;
592 final String newUrl = url;
Elliott Slaughter627d96f2010-08-18 16:35:30 -0700593 if (mTabControl == null || !mTabControl.getCurrentWebView().isPrivateBrowsingEnabled()) {
Elliott Slaughterf0f03952010-07-14 18:10:36 -0700594 new AsyncTask<Void, Void, Void>() {
595 @Override
596 protected Void doInBackground(Void... unused) {
597 Browser.updateVisitedHistory(cr, newUrl, false);
598 Browser.addSearchUrl(cr, newUrl);
599 return null;
600 }
601 }.execute();
602 }
Satish Sampath565505b2009-05-29 15:37:27 +0100603
Bjorn Bringertd69f51d2010-09-13 14:06:41 +0100604 SearchEngine searchEngine = mSettings.getSearchEngine();
605 if (searchEngine == null) return false;
606 searchEngine.startSearch(this, url, appData, extraData);
Satish Sampath565505b2009-05-29 15:37:27 +0100607
608 return true;
609 }
610
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700611 private UrlData getUrlDataFromIntent(Intent intent) {
Leon Scroggins58d56c62010-01-28 15:12:40 -0500612 String url = "";
Grace Kloba068e48b2010-01-26 18:11:27 -0800613 Map<String, String> headers = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800614 if (intent != null) {
615 final String action = intent.getAction();
616 if (Intent.ACTION_VIEW.equals(action)) {
617 url = smartUrlFilter(intent.getData());
618 if (url != null && url.startsWith("content:")) {
619 /* Append mimetype so webview knows how to display */
620 String mimeType = intent.resolveType(getContentResolver());
621 if (mimeType != null) {
622 url += "?" + mimeType;
623 }
624 }
Grace Kloba068e48b2010-01-26 18:11:27 -0800625 if (url != null && url.startsWith("http")) {
Grace Kloba00f54c52010-01-27 14:53:51 -0800626 final Bundle pairs = intent
627 .getBundleExtra(Browser.EXTRA_HEADERS);
Grace Kloba2d508ed2010-01-28 11:39:15 -0800628 if (pairs != null && !pairs.isEmpty()) {
Grace Kloba00f54c52010-01-27 14:53:51 -0800629 Iterator<String> iter = pairs.keySet().iterator();
Grace Kloba068e48b2010-01-26 18:11:27 -0800630 headers = new HashMap<String, String>();
Grace Kloba00f54c52010-01-27 14:53:51 -0800631 while (iter.hasNext()) {
632 String key = iter.next();
633 headers.put(key, pairs.getString(key));
Grace Kloba068e48b2010-01-26 18:11:27 -0800634 }
635 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700636 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800637 } else if (Intent.ACTION_SEARCH.equals(action)
638 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
639 || Intent.ACTION_WEB_SEARCH.equals(action)) {
640 url = intent.getStringExtra(SearchManager.QUERY);
641 if (url != null) {
642 mLastEnteredUrl = url;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800643 // In general, we shouldn't modify URL from Intent.
644 // But currently, we get the user-typed URL from search box as well.
645 url = fixUrl(url);
646 url = smartUrlFilter(url);
Leon Scroggins8d06e362010-03-24 14:45:57 -0400647 final ContentResolver cr = mResolver;
648 final String newUrl = url;
Elliott Slaughter8389e992010-08-20 15:44:08 -0700649 if (mTabControl == null
650 || mTabControl.getCurrentWebView() == null
651 || !mTabControl.getCurrentWebView().isPrivateBrowsingEnabled()) {
652 new AsyncTask<Void, Void, Void>() {
653 @Override
654 protected Void doInBackground(Void... unused) {
655 Browser.updateVisitedHistory(cr, newUrl, false);
656 return null;
657 }
658 }.execute();
659 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800660 String searchSource = "&source=android-" + GOOGLE_SEARCH_SOURCE_SUGGEST + "&";
661 if (url.contains(searchSource)) {
662 String source = null;
663 final Bundle appData = intent.getBundleExtra(SearchManager.APP_DATA);
664 if (appData != null) {
Bjorn Bringert10d1cca2010-02-10 14:22:12 +0000665 source = appData.getString(Search.SOURCE);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800666 }
667 if (TextUtils.isEmpty(source)) {
668 source = GOOGLE_SEARCH_SOURCE_UNKNOWN;
669 }
670 url = url.replace(searchSource, "&source=android-"+source+"&");
671 }
672 }
673 }
674 }
Leon Scroggins58d56c62010-01-28 15:12:40 -0500675 return new UrlData(url, headers, intent);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800676 }
Leon Scroggins58d56c62010-01-28 15:12:40 -0500677 /* package */ void showVoiceTitleBar(String title) {
678 mTitleBar.setInVoiceMode(true);
Leon Scroggins58d56c62010-01-28 15:12:40 -0500679 mTitleBar.setDisplayTitle(title);
Michael Kolba2b2ba82010-08-04 17:54:03 -0700680 mFakeTitleBar.setInVoiceMode(true);
681 mFakeTitleBar.setDisplayTitle(title);
Leon Scroggins58d56c62010-01-28 15:12:40 -0500682 }
683 /* package */ void revertVoiceTitleBar() {
684 mTitleBar.setInVoiceMode(false);
Leon Scroggins003a5dd2010-03-10 12:13:14 -0500685 mTitleBar.setDisplayTitle(mUrl);
Michael Kolba2b2ba82010-08-04 17:54:03 -0700686 mFakeTitleBar.setInVoiceMode(false);
687 mFakeTitleBar.setDisplayTitle(mUrl);
Leon Scroggins58d56c62010-01-28 15:12:40 -0500688 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800689 /* package */ static String fixUrl(String inUrl) {
Cary Clark652ff872009-09-10 13:34:44 -0400690 // FIXME: Converting the url to lower case
691 // duplicates functionality in smartUrlFilter().
692 // However, changing all current callers of fixUrl to
693 // call smartUrlFilter in addition may have unwanted
694 // consequences, and is deferred for now.
695 int colon = inUrl.indexOf(':');
696 boolean allLower = true;
697 for (int index = 0; index < colon; index++) {
698 char ch = inUrl.charAt(index);
699 if (!Character.isLetter(ch)) {
700 break;
701 }
702 allLower &= Character.isLowerCase(ch);
703 if (index == colon - 1 && !allLower) {
704 inUrl = inUrl.substring(0, colon).toLowerCase()
705 + inUrl.substring(colon);
706 }
707 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800708 if (inUrl.startsWith("http://") || inUrl.startsWith("https://"))
709 return inUrl;
710 if (inUrl.startsWith("http:") ||
711 inUrl.startsWith("https:")) {
712 if (inUrl.startsWith("http:/") || inUrl.startsWith("https:/")) {
713 inUrl = inUrl.replaceFirst("/", "//");
714 } else inUrl = inUrl.replaceFirst(":", "://");
715 }
716 return inUrl;
717 }
718
Grace Kloba22ac16e2009-10-07 18:00:23 -0700719 @Override
720 protected void onResume() {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800721 super.onResume();
Dave Bort31a6d1c2009-04-13 15:56:49 -0700722 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800723 Log.v(LOGTAG, "BrowserActivity.onResume: this=" + this);
724 }
725
726 if (!mActivityInPause) {
727 Log.e(LOGTAG, "BrowserActivity is already resumed.");
728 return;
729 }
730
Mike Reed7bfa63b2009-05-28 11:08:32 -0400731 mTabControl.resumeCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800732 mActivityInPause = false;
Mike Reed7bfa63b2009-05-28 11:08:32 -0400733 resumeWebViewTimers();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800734
735 if (mWakeLock.isHeld()) {
736 mHandler.removeMessages(RELEASE_WAKELOCK);
737 mWakeLock.release();
738 }
739
The Android Open Source Project0c908882009-03-03 19:32:16 -0800740 registerReceiver(mNetworkStateIntentReceiver,
741 mNetworkStateChangedFilter);
742 WebView.enablePlatformNotifications();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800743 }
744
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400745 /**
746 * Since the actual title bar is embedded in the WebView, and removing it
Leon Scrogginsfe87bd32009-10-06 10:10:00 -0400747 * would change its appearance, use a different TitleBar to show overlayed
748 * at the top of the screen, when the menu is open or the page is loading.
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400749 */
Michael Kolba2b2ba82010-08-04 17:54:03 -0700750 private TitleBarBase mFakeTitleBar;
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400751
752 /**
753 * Keeps track of whether the options menu is open. This is important in
754 * determining whether to show or hide the title bar overlay.
755 */
756 private boolean mOptionsMenuOpen;
757
758 /**
759 * Only meaningful when mOptionsMenuOpen is true. This variable keeps track
760 * of whether the configuration has changed. The first onMenuOpened call
761 * after a configuration change is simply a reopening of the same menu
762 * (i.e. mIconView did not change).
763 */
764 private boolean mConfigChanged;
765
766 /**
767 * Whether or not the options menu is in its smaller, icon menu form. When
768 * true, we want the title bar overlay to be up. When false, we do not.
769 * Only meaningful if mOptionsMenuOpen is true.
770 */
771 private boolean mIconView;
772
Leon Scrogginsa81a7642009-08-31 17:05:41 -0400773 @Override
774 public boolean onMenuOpened(int featureId, Menu menu) {
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400775 if (Window.FEATURE_OPTIONS_PANEL == featureId) {
776 if (mOptionsMenuOpen) {
777 if (mConfigChanged) {
778 // We do not need to make any changes to the state of the
779 // title bar, since the only thing that happened was a
780 // change in orientation
781 mConfigChanged = false;
782 } else {
783 if (mIconView) {
784 // Switching the menu to expanded view, so hide the
785 // title bar.
786 hideFakeTitleBar();
787 mIconView = false;
788 } else {
789 // Switching the menu back to icon view, so show the
790 // title bar once again.
791 showFakeTitleBar();
792 mIconView = true;
793 }
794 }
795 } else {
796 // The options menu is closed, so open it, and show the title
797 showFakeTitleBar();
798 mOptionsMenuOpen = true;
799 mConfigChanged = false;
800 mIconView = true;
801 }
802 }
Leon Scrogginsa81a7642009-08-31 17:05:41 -0400803 return true;
804 }
805
Michael Kolba2b2ba82010-08-04 17:54:03 -0700806 void showFakeTitleBar() {
807 if (!isFakeTitleBarShowing() && mActiveTabsPage == null && !mActivityInPause) {
Grace Kloba847c25b2010-03-30 16:00:26 -0700808 WebView mainView = mTabControl.getCurrentWebView();
809 // if there is no current WebView, don't show the faked title bar;
Grace Kloba65190702010-04-02 23:37:26 -0700810 if (mainView == null) {
Cary Clarka0464552009-09-29 13:00:45 -0400811 return;
812 }
Leon Scroggins79e36d92010-04-29 16:01:46 +0100813 // Do not need to check for null, since the current tab will have
814 // at least a main WebView, or we would have returned above.
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -0400815 if (isInCustomActionMode()) {
816 // Do not show the fake title bar, while a custom ActionMode
817 // (i.e. find or select) is showing.
Leon Scroggins79e36d92010-04-29 16:01:46 +0100818 return;
819 }
Michael Kolba2b2ba82010-08-04 17:54:03 -0700820 if (mXLargeScreenSize) {
821 mContentView.addView(mFakeTitleBar);
822 mTabBar.onShowTitleBar();
823 } else {
824 WindowManager manager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400825
Michael Kolba2b2ba82010-08-04 17:54:03 -0700826 // Add the title bar to the window manager so it can receive
827 // touches
828 // while the menu is up
829 WindowManager.LayoutParams params =
830 new WindowManager.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
831 ViewGroup.LayoutParams.WRAP_CONTENT,
832 WindowManager.LayoutParams.TYPE_APPLICATION,
833 WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
834 PixelFormat.TRANSLUCENT);
835 params.gravity = Gravity.TOP;
836 boolean atTop = mainView.getScrollY() == 0;
837 params.windowAnimations = atTop ? 0 : R.style.TitleBar;
838 manager.addView(mFakeTitleBar, params);
839 }
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400840 }
841 }
842
843 @Override
844 public void onOptionsMenuClosed(Menu menu) {
845 mOptionsMenuOpen = false;
Leon Scrogginsa27ff192009-09-14 12:58:04 -0400846 if (!mInLoad) {
847 hideFakeTitleBar();
848 } else if (!mIconView) {
849 // The page is currently loading, and we are in expanded mode, so
850 // we were not showing the menu. Show it once again. It will be
851 // removed when the page finishes.
852 showFakeTitleBar();
853 }
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400854 }
Grace Kloba22ac16e2009-10-07 18:00:23 -0700855
Michael Kolba2b2ba82010-08-04 17:54:03 -0700856 void stopScrolling() {
857 ((ScrollWebView) mTabControl.getCurrentWebView()).stopScroll();
858 }
859
860 void hideFakeTitleBar() {
861 if (!isFakeTitleBarShowing()) return;
862 if (mXLargeScreenSize) {
863 mContentView.removeView(mFakeTitleBar);
864 mTabBar.onHideTitleBar();
865 } else {
866 WindowManager.LayoutParams params =
867 (WindowManager.LayoutParams) mFakeTitleBar.getLayoutParams();
868 WebView mainView = mTabControl.getCurrentWebView();
869 // Although we decided whether or not to animate based on the
870 // current
871 // scroll position, the scroll position may have changed since the
872 // fake title bar was displayed. Make sure it has the appropriate
873 // animation/lack thereof before removing.
874 params.windowAnimations =
875 mainView != null && mainView.getScrollY() == 0 ? 0 : R.style.TitleBar;
876 WindowManager manager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
877 manager.updateViewLayout(mFakeTitleBar, params);
878 manager.removeView(mFakeTitleBar);
879 }
880 }
881
882 boolean isFakeTitleBarShowing() {
883 return (mFakeTitleBar.getParent() != null);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400884 }
885
The Android Open Source Project0c908882009-03-03 19:32:16 -0800886 /**
Leon Scrogginsc6fa1102009-09-21 10:40:01 -0400887 * Special method for the fake title bar to call when displaying its context
888 * menu, since it is in its own Window, and its parent does not show a
889 * context menu.
890 */
891 /* package */ void showTitleBarContextMenu() {
Cary Clark65f4a3c2009-09-28 17:05:06 -0400892 if (null == mTitleBar.getParent()) {
893 return;
894 }
Leon Scrogginsc6fa1102009-09-21 10:40:01 -0400895 openContextMenu(mTitleBar);
896 }
897
Leon Scrogginsb2b19f52009-10-09 16:10:00 -0400898 @Override
899 public void onContextMenuClosed(Menu menu) {
900 super.onContextMenuClosed(menu);
901 if (mInLoad) {
902 showFakeTitleBar();
903 }
904 }
905
Leon Scrogginsc6fa1102009-09-21 10:40:01 -0400906 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -0800907 * onSaveInstanceState(Bundle map)
908 * onSaveInstanceState is called right before onStop(). The map contains
909 * the saved state.
910 */
Grace Kloba22ac16e2009-10-07 18:00:23 -0700911 @Override
912 protected void onSaveInstanceState(Bundle outState) {
Dave Bort31a6d1c2009-04-13 15:56:49 -0700913 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800914 Log.v(LOGTAG, "BrowserActivity.onSaveInstanceState: this=" + this);
915 }
916 // the default implementation requires each view to have an id. As the
917 // browser handles the state itself and it doesn't use id for the views,
918 // don't call the default implementation. Otherwise it will trigger the
919 // warning like this, "couldn't save which view has focus because the
920 // focused view XXX has no id".
921
922 // Save all the tabs
923 mTabControl.saveState(outState);
Elliott Slaughter3d6df162010-08-25 13:17:44 -0700924
925 // Save time so that we know how old incognito tabs (if any) are.
926 outState.putSerializable("lastActiveDate", Calendar.getInstance());
The Android Open Source Project0c908882009-03-03 19:32:16 -0800927 }
928
Grace Kloba22ac16e2009-10-07 18:00:23 -0700929 @Override
930 protected void onPause() {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800931 super.onPause();
932
933 if (mActivityInPause) {
934 Log.e(LOGTAG, "BrowserActivity is already paused.");
935 return;
936 }
937
Mike Reed7bfa63b2009-05-28 11:08:32 -0400938 mTabControl.pauseCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800939 mActivityInPause = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -0400940 if (mTabControl.getCurrentIndex() >= 0 && !pauseWebViewTimers()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800941 mWakeLock.acquire();
942 mHandler.sendMessageDelayed(mHandler
943 .obtainMessage(RELEASE_WAKELOCK), WAKELOCK_TIMEOUT);
944 }
945
Leon Scrogginsa2ab6a72009-09-11 11:49:52 -0400946 // FIXME: This removes the active tabs page and resets the menu to
947 // MAIN_MENU. A better solution might be to do this work in onNewIntent
948 // but then we would need to save it in onSaveInstanceState and restore
949 // it in onCreate/onRestoreInstanceState
950 if (mActiveTabsPage != null) {
951 removeActiveTabPage(true);
952 }
953
The Android Open Source Project0c908882009-03-03 19:32:16 -0800954 cancelStopToast();
955
956 // unregister network state listener
957 unregisterReceiver(mNetworkStateIntentReceiver);
958 WebView.disablePlatformNotifications();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800959 }
960
Grace Kloba22ac16e2009-10-07 18:00:23 -0700961 @Override
962 protected void onDestroy() {
Dave Bort31a6d1c2009-04-13 15:56:49 -0700963 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800964 Log.v(LOGTAG, "BrowserActivity.onDestroy: this=" + this);
965 }
966 super.onDestroy();
Grace Kloba0923d692009-09-23 21:37:25 -0700967
Leon Scroggins8d5fa432009-10-02 15:55:59 -0400968 if (mUploadMessage != null) {
969 mUploadMessage.onReceiveValue(null);
970 mUploadMessage = null;
971 }
972
Grace Kloba0923d692009-09-23 21:37:25 -0700973 if (mTabControl == null) return;
974
Grace Kloba1fc98a32009-10-21 13:23:08 -0700975 // Remove the fake title bar if it is there
976 hideFakeTitleBar();
977
The Android Open Source Project0c908882009-03-03 19:32:16 -0800978 // Remove the current tab and sub window
Grace Kloba22ac16e2009-10-07 18:00:23 -0700979 Tab t = mTabControl.getCurrentTab();
Patrick Scottfb5e77f2009-04-08 19:17:37 -0700980 if (t != null) {
981 dismissSubWindow(t);
982 removeTabFromContentView(t);
983 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800984 // Destroy all the tabs
985 mTabControl.destroy();
986 WebIconDatabase.getInstance().close();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800987
Bjorn Bringerta7611812010-03-24 11:12:02 +0000988 // Stop watching the default geolocation permissions
989 mSystemAllowGeolocationOrigins.stop();
990 mSystemAllowGeolocationOrigins = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800991 }
992
993 @Override
994 public void onConfigurationChanged(Configuration newConfig) {
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400995 mConfigChanged = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800996 super.onConfigurationChanged(newConfig);
997
998 if (mPageInfoDialog != null) {
999 mPageInfoDialog.dismiss();
1000 showPageInfo(
1001 mPageInfoView,
Leon Scrogginsc7b92f82010-01-11 18:17:31 -05001002 mPageInfoFromShowSSLCertificateOnError);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001003 }
1004 if (mSSLCertificateDialog != null) {
1005 mSSLCertificateDialog.dismiss();
1006 showSSLCertificate(
1007 mSSLCertificateView);
1008 }
1009 if (mSSLCertificateOnErrorDialog != null) {
1010 mSSLCertificateOnErrorDialog.dismiss();
1011 showSSLCertificateOnError(
1012 mSSLCertificateOnErrorView,
1013 mSSLCertificateOnErrorHandler,
1014 mSSLCertificateOnErrorError);
1015 }
1016 if (mHttpAuthenticationDialog != null) {
1017 String title = ((TextView) mHttpAuthenticationDialog
1018 .findViewById(com.android.internal.R.id.alertTitle)).getText()
1019 .toString();
1020 String name = ((TextView) mHttpAuthenticationDialog
1021 .findViewById(R.id.username_edit)).getText().toString();
1022 String password = ((TextView) mHttpAuthenticationDialog
1023 .findViewById(R.id.password_edit)).getText().toString();
1024 int focusId = mHttpAuthenticationDialog.getCurrentFocus()
1025 .getId();
1026 mHttpAuthenticationDialog.dismiss();
1027 showHttpAuthentication(mHttpAuthHandler, null, null, title,
1028 name, password, focusId);
1029 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001030 }
1031
Grace Kloba22ac16e2009-10-07 18:00:23 -07001032 @Override
1033 public void onLowMemory() {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001034 super.onLowMemory();
1035 mTabControl.freeMemory();
1036 }
1037
Cary Clarkff4d92c2010-03-25 11:17:03 -04001038 private void resumeWebViewTimers() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001039 Tab tab = mTabControl.getCurrentTab();
Cary Clarkff4d92c2010-03-25 11:17:03 -04001040 if (tab == null) return; // monkey can trigger this
Grace Kloba22ac16e2009-10-07 18:00:23 -07001041 boolean inLoad = tab.inLoad();
1042 if ((!mActivityInPause && !inLoad) || (mActivityInPause && inLoad)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001043 CookieSyncManager.getInstance().startSync();
Grace Kloba22ac16e2009-10-07 18:00:23 -07001044 WebView w = tab.getWebView();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001045 if (w != null) {
1046 w.resumeTimers();
1047 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001048 }
1049 }
1050
Mike Reed7bfa63b2009-05-28 11:08:32 -04001051 private boolean pauseWebViewTimers() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001052 Tab tab = mTabControl.getCurrentTab();
1053 boolean inLoad = tab.inLoad();
1054 if (mActivityInPause && !inLoad) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001055 CookieSyncManager.getInstance().stopSync();
1056 WebView w = mTabControl.getCurrentWebView();
1057 if (w != null) {
1058 w.pauseTimers();
1059 }
1060 return true;
1061 } else {
1062 return false;
1063 }
1064 }
1065
The Android Open Source Project0c908882009-03-03 19:32:16 -08001066 // Open the icon database and retain all the icons for visited sites.
1067 private void retainIconsOnStartup() {
1068 final WebIconDatabase db = WebIconDatabase.getInstance();
1069 db.open(getDir("icons", 0).getPath());
Leon Scroggins2c0f6112010-03-12 18:09:39 -05001070 Cursor c = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001071 try {
Leon Scroggins2c0f6112010-03-12 18:09:39 -05001072 c = Browser.getAllBookmarks(mResolver);
1073 if (c.moveToFirst()) {
1074 int urlIndex = c.getColumnIndex(Browser.BookmarkColumns.URL);
1075 do {
1076 String url = c.getString(urlIndex);
1077 db.retainIconForPageUrl(url);
1078 } while (c.moveToNext());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001079 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001080 } catch (IllegalStateException e) {
1081 Log.e(LOGTAG, "retainIconsOnStartup", e);
Leon Scroggins2c0f6112010-03-12 18:09:39 -05001082 } finally {
1083 if (c!= null) c.close();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001084 }
1085 }
1086
1087 // Helper method for getting the top window.
1088 WebView getTopWindow() {
1089 return mTabControl.getCurrentTopWebView();
1090 }
1091
Grace Kloba22ac16e2009-10-07 18:00:23 -07001092 TabControl getTabControl() {
1093 return mTabControl;
1094 }
1095
The Android Open Source Project0c908882009-03-03 19:32:16 -08001096 @Override
1097 public boolean onCreateOptionsMenu(Menu menu) {
1098 super.onCreateOptionsMenu(menu);
1099
1100 MenuInflater inflater = getMenuInflater();
1101 inflater.inflate(R.menu.browser, menu);
1102 mMenu = menu;
1103 updateInLoadMenuItems();
1104 return true;
1105 }
1106
1107 /**
1108 * As the menu can be open when loading state changes
1109 * we must manually update the state of the stop/reload menu
1110 * item
1111 */
1112 private void updateInLoadMenuItems() {
1113 if (mMenu == null) {
1114 return;
1115 }
Michael Kolbe0a36662010-06-29 10:37:12 -07001116 MenuItem dest = mMenu.findItem(R.id.stop_reload_menu_id);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001117 MenuItem src = mInLoad ?
1118 mMenu.findItem(R.id.stop_menu_id):
Michael Kolbe0a36662010-06-29 10:37:12 -07001119 mMenu.findItem(R.id.reload_menu_id);
1120 if (src != null) {
1121 dest.setIcon(src.getIcon());
1122 dest.setTitle(src.getTitle());
1123 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001124 }
1125
1126 @Override
1127 public boolean onContextItemSelected(MenuItem item) {
1128 // chording is not an issue with context menus, but we use the same
1129 // options selector, so set mCanChord to true so we can access them.
1130 mCanChord = true;
1131 int id = item.getItemId();
Leon Scroggins96afcb12009-12-10 12:35:56 -05001132 boolean result = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001133 switch (id) {
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001134 // For the context menu from the title bar
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001135 case R.id.title_bar_copy_page_url:
Leon Scroggins96afcb12009-12-10 12:35:56 -05001136 Tab currentTab = mTabControl.getCurrentTab();
1137 if (null == currentTab) {
1138 result = false;
1139 break;
1140 }
1141 WebView mainView = currentTab.getWebView();
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001142 if (null == mainView) {
Leon Scroggins96afcb12009-12-10 12:35:56 -05001143 result = false;
1144 break;
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001145 }
Leon Scroggins96afcb12009-12-10 12:35:56 -05001146 copy(mainView.getUrl());
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001147 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001148 // -- Browser context menu
1149 case R.id.open_context_menu_id:
The Android Open Source Project0c908882009-03-03 19:32:16 -08001150 case R.id.bookmark_context_menu_id:
1151 case R.id.save_link_context_menu_id:
1152 case R.id.share_link_context_menu_id:
1153 case R.id.copy_link_context_menu_id:
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001154 final WebView webView = getTopWindow();
1155 if (null == webView) {
Leon Scroggins96afcb12009-12-10 12:35:56 -05001156 result = false;
1157 break;
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001158 }
1159 final HashMap hrefMap = new HashMap();
1160 hrefMap.put("webview", webView);
1161 final Message msg = mHandler.obtainMessage(
1162 FOCUS_NODE_HREF, id, 0, hrefMap);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001163 webView.requestFocusNodeHref(msg);
1164 break;
1165
1166 default:
1167 // For other context menus
Leon Scroggins96afcb12009-12-10 12:35:56 -05001168 result = onOptionsItemSelected(item);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001169 }
1170 mCanChord = false;
Leon Scroggins96afcb12009-12-10 12:35:56 -05001171 return result;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001172 }
1173
1174 private Bundle createGoogleSearchSourceBundle(String source) {
1175 Bundle bundle = new Bundle();
Bjorn Bringert10d1cca2010-02-10 14:22:12 +00001176 bundle.putString(Search.SOURCE, source);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001177 return bundle;
1178 }
1179
Leon Scroggins8ad29922010-02-16 12:33:55 -05001180 /* package */ void editUrl() {
Leon Scroggins68579392009-09-15 15:31:54 -04001181 if (mOptionsMenuOpen) closeOptionsMenu();
Leon Scroggins5bbe9802009-07-31 13:10:55 -04001182 String url = (getTopWindow() == null) ? null : getTopWindow().getUrl();
Grace Kloba83f47342009-07-20 10:44:31 -07001183 startSearch(mSettings.getHomePage().equals(url) ? null : url, true,
Leon Scroggins8ad29922010-02-16 12:33:55 -05001184 null, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001185 }
1186
Leon Scroggins8ad29922010-02-16 12:33:55 -05001187 /**
1188 * Overriding this to insert a local information bundle
1189 */
The Android Open Source Project0c908882009-03-03 19:32:16 -08001190 @Override
1191 public void startSearch(String initialQuery, boolean selectInitialQuery,
1192 Bundle appSearchData, boolean globalSearch) {
1193 if (appSearchData == null) {
1194 appSearchData = createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_TYPE);
1195 }
Leon Scroggins III430057d2010-09-14 10:57:37 -04001196
1197 SearchEngine searchEngine = mSettings.getSearchEngine();
1198 if (searchEngine != null && !searchEngine.supportsVoiceSearch()) {
1199 appSearchData.putBoolean(SearchManager.DISABLE_VOICE_SEARCH, true);
1200 }
1201
The Android Open Source Project0c908882009-03-03 19:32:16 -08001202 super.startSearch(initialQuery, selectInitialQuery, appSearchData, globalSearch);
1203 }
1204
Leon Scroggins1f005d32009-08-10 17:36:42 -04001205 /**
1206 * Switch tabs. Called by the TitleBarSet when sliding the title bar
1207 * results in changing tabs.
Leon Scroggins160a7e72009-08-14 18:28:01 -04001208 * @param index Index of the tab to change to, as defined by
1209 * mTabControl.getTabIndex(Tab t).
1210 * @return boolean True if we successfully switched to a different tab. If
1211 * the indexth tab is null, or if that tab is the same as
1212 * the current one, return false.
Leon Scroggins1f005d32009-08-10 17:36:42 -04001213 */
Leon Scroggins160a7e72009-08-14 18:28:01 -04001214 /* package */ boolean switchToTab(int index) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001215 Tab tab = mTabControl.getTab(index);
1216 Tab currentTab = mTabControl.getCurrentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04001217 if (tab == null || tab == currentTab) {
Leon Scroggins160a7e72009-08-14 18:28:01 -04001218 return false;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001219 }
1220 if (currentTab != null) {
1221 // currentTab may be null if it was just removed. In that case,
1222 // we do not need to remove it
1223 removeTabFromContentView(currentTab);
1224 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001225 mTabControl.setCurrentTab(tab);
1226 attachTabToContentView(tab);
Grace Klobaeb6eef42009-09-15 17:56:32 -07001227 resetTitleIconAndProgress();
1228 updateLockIconToLatest();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001229 return true;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001230 }
1231
Grace Kloba22ac16e2009-10-07 18:00:23 -07001232 /* package */ Tab openTabToHomePage() {
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001233 return openTabAndShow(mSettings.getHomePage(), false, null);
1234 }
1235
Leon Scroggins1f005d32009-08-10 17:36:42 -04001236 /* package */ void closeCurrentWindow() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001237 final Tab current = mTabControl.getCurrentTab();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001238 if (mTabControl.getTabCount() == 1) {
Leon Scroggins30444232009-09-04 18:36:20 -04001239 // This is the last tab. Open a new one, with the home
1240 // page and close the current one.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001241 openTabToHomePage();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001242 closeTab(current);
Leon Scroggins160a7e72009-08-14 18:28:01 -04001243 return;
1244 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07001245 final Tab parent = current.getParentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04001246 int indexToShow = -1;
1247 if (parent != null) {
1248 indexToShow = mTabControl.getTabIndex(parent);
1249 } else {
Leon Scroggins160a7e72009-08-14 18:28:01 -04001250 final int currentIndex = mTabControl.getCurrentIndex();
1251 // Try to move to the tab to the right
1252 indexToShow = currentIndex + 1;
1253 if (indexToShow > mTabControl.getTabCount() - 1) {
1254 // Try to move to the tab to the left
1255 indexToShow = currentIndex - 1;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001256 }
1257 }
Leon Scroggins160a7e72009-08-14 18:28:01 -04001258 if (switchToTab(indexToShow)) {
1259 // Close window
1260 closeTab(current);
1261 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001262 }
1263
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001264 private ActiveTabsPage mActiveTabsPage;
1265
1266 /**
1267 * Remove the active tabs page.
1268 * @param needToAttach If true, the active tabs page did not attach a tab
1269 * to the content view, so we need to do that here.
1270 */
1271 /* package */ void removeActiveTabPage(boolean needToAttach) {
1272 mContentView.removeView(mActiveTabsPage);
Leon Scrogginsd746a942010-05-19 13:21:44 -04001273 mTitleBar.setVisibility(View.VISIBLE);
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001274 mActiveTabsPage = null;
1275 mMenuState = R.id.MAIN_MENU;
1276 if (needToAttach) {
1277 attachTabToContentView(mTabControl.getCurrentTab());
1278 }
1279 getTopWindow().requestFocus();
1280 }
1281
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04001282 @Override
1283 public ActionMode onStartActionMode(ActionMode.Callback callback) {
Leon Scroggins4fc12cb2010-08-24 14:24:05 -04001284 mActionMode = super.onStartActionMode(callback);
1285 hideFakeTitleBar();
1286 // Would like to change the MENU, but onEndActionMode may not be called
1287 return mActionMode;
Cary Clark01cfcdd2010-06-04 16:36:45 -04001288 }
1289
The Android Open Source Project0c908882009-03-03 19:32:16 -08001290 @Override
1291 public boolean onOptionsItemSelected(MenuItem item) {
Michael Kolb370a4f32010-10-06 10:45:32 -07001292 if (item.getGroupId() != R.id.CONTEXT_MENU) {
1293 // menu remains active, so ensure comboview is dismissed
1294 // if main menu option is selected
1295 removeComboView();
1296 }
Michael Kolbed217742010-08-10 17:52:34 -07001297 // check the action bar button before mCanChord check, as the prepare call
1298 // doesn't come for action bar buttons
1299 if (item.getItemId() == R.id.newtab) {
Michael Kolb300b7f02010-08-25 13:47:24 -07001300 openTabToHomePage();
Michael Kolbed217742010-08-10 17:52:34 -07001301 return true;
1302 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001303 if (!mCanChord) {
1304 // The user has already fired a shortcut with this hold down of the
1305 // menu key.
1306 return false;
1307 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001308 if (null == getTopWindow()) {
Leon Scroggins0d7ae0e2009-06-05 11:04:45 -04001309 return false;
1310 }
Grace Kloba6ee9c492009-07-13 10:04:34 -07001311 if (mMenuIsDown) {
1312 // The shortcut action consumes the MENU. Even if it is still down,
1313 // it won't trigger the next shortcut action. In the case of the
1314 // shortcut action triggering a new activity, like Bookmarks, we
1315 // won't get onKeyUp for MENU. So it is important to reset it here.
1316 mMenuIsDown = false;
1317 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001318 switch (item.getItemId()) {
1319 // -- Main menu
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001320 case R.id.new_tab_menu_id:
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001321 openTabToHomePage();
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001322 break;
1323
Michael Kolbae62fd42010-08-18 16:33:28 -07001324 case R.id.incognito_menu_id:
1325 openIncognitoTab();
1326 break;
1327
Leon Scroggins64b80f32009-08-07 12:03:34 -04001328 case R.id.goto_menu_id:
Leon Scroggins8ad29922010-02-16 12:33:55 -05001329 editUrl();
Leon Scrogginsb3a5bed2009-09-28 11:21:56 -04001330 break;
1331
1332 case R.id.bookmarks_menu_id:
Michael Kolbe421c242010-10-04 19:29:01 -07001333 bookmarksOrHistoryPicker(false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001334 break;
1335
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001336 case R.id.active_tabs_menu_id:
1337 mActiveTabsPage = new ActiveTabsPage(this, mTabControl);
1338 removeTabFromContentView(mTabControl.getCurrentTab());
Leon Scrogginsd746a942010-05-19 13:21:44 -04001339 mTitleBar.setVisibility(View.GONE);
Leon Scroggins43de6162009-09-14 19:59:58 -04001340 hideFakeTitleBar();
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001341 mContentView.addView(mActiveTabsPage, COVER_SCREEN_PARAMS);
1342 mActiveTabsPage.requestFocus();
1343 mMenuState = EMPTY_MENU;
1344 break;
1345
Leon Scroggins1f005d32009-08-10 17:36:42 -04001346 case R.id.add_bookmark_menu_id:
Michael Kolb370a4f32010-10-06 10:45:32 -07001347 bookmarkCurrentPage(AddBookmarkPage.DEFAULT_FOLDER_ID);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001348 break;
1349
1350 case R.id.stop_reload_menu_id:
1351 if (mInLoad) {
1352 stopLoading();
1353 } else {
1354 getTopWindow().reload();
1355 }
1356 break;
1357
1358 case R.id.back_menu_id:
1359 getTopWindow().goBack();
1360 break;
1361
1362 case R.id.forward_menu_id:
1363 getTopWindow().goForward();
1364 break;
1365
1366 case R.id.close_menu_id:
1367 // Close the subwindow if it exists.
1368 if (mTabControl.getCurrentSubWindow() != null) {
1369 dismissSubWindow(mTabControl.getCurrentTab());
1370 break;
1371 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001372 closeCurrentWindow();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001373 break;
1374
1375 case R.id.homepage_menu_id:
Grace Kloba22ac16e2009-10-07 18:00:23 -07001376 Tab current = mTabControl.getCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001377 if (current != null) {
1378 dismissSubWindow(current);
Leon Scroggins92472e82010-02-17 16:32:28 -05001379 loadUrl(current.getWebView(), mSettings.getHomePage());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001380 }
1381 break;
1382
1383 case R.id.preferences_menu_id:
1384 Intent intent = new Intent(this,
1385 BrowserPreferencesPage.class);
Leon Scrogginsd5304942009-12-10 16:11:39 -05001386 intent.putExtra(BrowserPreferencesPage.CURRENT_PAGE,
1387 getTopWindow().getUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001388 startActivityForResult(intent, PREFERENCES_PAGE);
1389 break;
1390
1391 case R.id.find_menu_id:
Leon Scroggins4fc12cb2010-08-24 14:24:05 -04001392 getTopWindow().showFindDialog(null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001393 break;
1394
Elliott Slaughter0ced08c2010-06-30 11:40:42 -07001395 case R.id.save_webarchive_menu_id:
1396 if (LOGD_ENABLED) {
1397 Log.d(LOGTAG, "Save as Web Archive");
1398 }
Elliott Slaughteraba242c2010-09-01 16:21:07 -07001399 String state = Environment.getExternalStorageState();
1400 if (Environment.MEDIA_MOUNTED.equals(state)) {
1401 String directory = Environment.getExternalStoragePublicDirectory(
1402 Environment.DIRECTORY_DOWNLOADS).getAbsolutePath() + File.separator;
Shimeng (Simon) Wang447c8462010-09-15 18:16:55 -07001403 File dir = new File(directory);
1404 if (!dir.exists() && !dir.mkdirs()) {
1405 Log.e(LOGTAG, "Save as Web Archive: mkdirs for " + directory + " failed!");
1406 Toast.makeText(BrowserActivity.this, R.string.webarchive_failed,
1407 Toast.LENGTH_SHORT).show();
1408 break;
1409 }
Elliott Slaughteraba242c2010-09-01 16:21:07 -07001410 getTopWindow().saveWebArchive(directory, true, new ValueCallback<String>() {
1411 @Override
1412 public void onReceiveValue(String value) {
1413 if (value != null) {
1414 Toast.makeText(BrowserActivity.this, R.string.webarchive_saved,
1415 Toast.LENGTH_SHORT).show();
1416 } else {
1417 Toast.makeText(BrowserActivity.this, R.string.webarchive_failed,
1418 Toast.LENGTH_SHORT).show();
1419 }
Elliott Slaughter0ced08c2010-06-30 11:40:42 -07001420 }
Elliott Slaughteraba242c2010-09-01 16:21:07 -07001421 });
1422 } else {
1423 Toast.makeText(BrowserActivity.this, R.string.webarchive_failed,
1424 Toast.LENGTH_SHORT).show();
1425 }
Elliott Slaughter0ced08c2010-06-30 11:40:42 -07001426 break;
1427
The Android Open Source Project0c908882009-03-03 19:32:16 -08001428 case R.id.page_info_menu_id:
1429 showPageInfo(mTabControl.getCurrentTab(), false);
1430 break;
1431
1432 case R.id.classic_history_menu_id:
Michael Kolbe421c242010-10-04 19:29:01 -07001433 bookmarksOrHistoryPicker(true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001434 break;
1435
Leon Scroggins96afcb12009-12-10 12:35:56 -05001436 case R.id.title_bar_share_page_url:
The Android Open Source Project0c908882009-03-03 19:32:16 -08001437 case R.id.share_page_menu_id:
Leon Scroggins96afcb12009-12-10 12:35:56 -05001438 Tab currentTab = mTabControl.getCurrentTab();
1439 if (null == currentTab) {
1440 mCanChord = false;
1441 return false;
1442 }
1443 currentTab.populatePickerData();
1444 sharePage(this, currentTab.getTitle(),
1445 currentTab.getUrl(), currentTab.getFavicon(),
Ben Murdoch87cc65d2010-06-29 20:34:10 +01001446 createScreenshot(currentTab.getWebView(), getDesiredThumbnailWidth(this),
1447 getDesiredThumbnailHeight(this)));
The Android Open Source Project0c908882009-03-03 19:32:16 -08001448 break;
1449
1450 case R.id.dump_nav_menu_id:
1451 getTopWindow().debugDump();
1452 break;
1453
Andrei Popescu7a8b88b2010-02-02 00:30:38 +00001454 case R.id.dump_counters_menu_id:
1455 getTopWindow().dumpV8Counters();
1456 break;
1457
The Android Open Source Project0c908882009-03-03 19:32:16 -08001458 case R.id.zoom_in_menu_id:
1459 getTopWindow().zoomIn();
1460 break;
1461
1462 case R.id.zoom_out_menu_id:
1463 getTopWindow().zoomOut();
1464 break;
1465
1466 case R.id.view_downloads_menu_id:
Leon Scroggins IIIa682a3c2010-09-27 12:32:40 -04001467 viewDownloads();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001468 break;
1469
The Android Open Source Project0c908882009-03-03 19:32:16 -08001470 case R.id.window_one_menu_id:
1471 case R.id.window_two_menu_id:
1472 case R.id.window_three_menu_id:
1473 case R.id.window_four_menu_id:
1474 case R.id.window_five_menu_id:
1475 case R.id.window_six_menu_id:
1476 case R.id.window_seven_menu_id:
1477 case R.id.window_eight_menu_id:
1478 {
1479 int menuid = item.getItemId();
1480 for (int id = 0; id < WINDOW_SHORTCUT_ID_ARRAY.length; id++) {
1481 if (WINDOW_SHORTCUT_ID_ARRAY[id] == menuid) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001482 Tab desiredTab = mTabControl.getTab(id);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001483 if (desiredTab != null &&
1484 desiredTab != mTabControl.getCurrentTab()) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001485 switchToTab(id);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001486 }
1487 break;
1488 }
1489 }
1490 }
1491 break;
1492
1493 default:
1494 if (!super.onOptionsItemSelected(item)) {
1495 return false;
1496 }
1497 // Otherwise fall through.
1498 }
1499 mCanChord = false;
1500 return true;
1501 }
1502
Michael Kolb370a4f32010-10-06 10:45:32 -07001503 /**
1504 * add the current page as a bookmark to the given folder id
1505 * @param folderId use -1 for the default folder
1506 */
1507 /* package */ void bookmarkCurrentPage(long folderId) {
Leon Scroggins571b3762010-05-26 10:25:01 -04001508 Intent i = new Intent(BrowserActivity.this,
1509 AddBookmarkPage.class);
1510 WebView w = getTopWindow();
1511 i.putExtra("url", w.getUrl());
1512 i.putExtra("title", w.getTitle());
1513 i.putExtra("touch_icon_url", w.getTouchIconUrl());
Ben Murdoch87cc65d2010-06-29 20:34:10 +01001514 i.putExtra("thumbnail", createScreenshot(w, getDesiredThumbnailWidth(this),
1515 getDesiredThumbnailHeight(this)));
Michael Kolb370a4f32010-10-06 10:45:32 -07001516 i.putExtra(BrowserContract.Bookmarks.PARENT,
1517 folderId);
Leon Scroggins III76a0e9c2010-10-05 16:10:01 -04001518 // Put the dialog at the upper right of the screen, covering the
1519 // star on the title bar.
1520 i.putExtra("gravity", Gravity.RIGHT | Gravity.TOP);
Leon Scroggins571b3762010-05-26 10:25:01 -04001521 startActivity(i);
1522 }
1523
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04001524 /*
1525 * True if a custom ActionMode (i.e. find or select) is in use.
1526 */
1527 private boolean isInCustomActionMode() {
1528 return mActionMode != null;
Cary Clark01cfcdd2010-06-04 16:36:45 -04001529 }
1530
1531 /*
Leon Scroggins4fc12cb2010-08-24 14:24:05 -04001532 * End the current ActionMode.
Cary Clark01cfcdd2010-06-04 16:36:45 -04001533 */
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04001534 void endActionMode() {
1535 if (mActionMode != null) {
Leon Scroggins4fc12cb2010-08-24 14:24:05 -04001536 ActionMode mode = mActionMode;
1537 onEndActionMode();
1538 mode.finish();
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04001539 }
1540 }
1541
1542 /*
1543 * Called by find and select when they are finished. Replace title bars
1544 * as necessary.
1545 */
1546 public void onEndActionMode() {
1547 if (!isInCustomActionMode()) return;
Leon Scroggins79e36d92010-04-29 16:01:46 +01001548 if (mInLoad) {
1549 // The title bar was hidden, because otherwise it would cover up the
Michael Kolba2b2ba82010-08-04 17:54:03 -07001550 // find or select dialog. Now that the dialog has been removed,
Cary Clark01cfcdd2010-06-04 16:36:45 -04001551 // show the fake title bar once again.
Leon Scroggins79e36d92010-04-29 16:01:46 +01001552 showFakeTitleBar();
1553 }
Leon Scroggins4fc12cb2010-08-24 14:24:05 -04001554 // Would like to return the menu state to normal, but this does not
1555 // necessarily get called.
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04001556 mActionMode = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001557 }
1558
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04001559 // For select and find, we keep track of the ActionMode so that
1560 // finish() can be called as desired.
1561 private ActionMode mActionMode;
1562
Grace Kloba22ac16e2009-10-07 18:00:23 -07001563 @Override
1564 public boolean onPrepareOptionsMenu(Menu menu) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001565 // This happens when the user begins to hold down the menu key, so
1566 // allow them to chord to get a shortcut.
1567 mCanChord = true;
1568 // Note: setVisible will decide whether an item is visible; while
1569 // setEnabled() will decide whether an item is enabled, which also means
1570 // whether the matching shortcut key will function.
1571 super.onPrepareOptionsMenu(menu);
1572 switch (mMenuState) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001573 case EMPTY_MENU:
1574 if (mCurrentMenuState != mMenuState) {
1575 menu.setGroupVisible(R.id.MAIN_MENU, false);
1576 menu.setGroupEnabled(R.id.MAIN_MENU, false);
1577 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001578 }
1579 break;
1580 default:
1581 if (mCurrentMenuState != mMenuState) {
1582 menu.setGroupVisible(R.id.MAIN_MENU, true);
1583 menu.setGroupEnabled(R.id.MAIN_MENU, true);
1584 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001585 }
1586 final WebView w = getTopWindow();
1587 boolean canGoBack = false;
1588 boolean canGoForward = false;
1589 boolean isHome = false;
1590 if (w != null) {
1591 canGoBack = w.canGoBack();
1592 canGoForward = w.canGoForward();
1593 isHome = mSettings.getHomePage().equals(w.getUrl());
1594 }
1595 final MenuItem back = menu.findItem(R.id.back_menu_id);
1596 back.setEnabled(canGoBack);
1597
1598 final MenuItem home = menu.findItem(R.id.homepage_menu_id);
1599 home.setEnabled(!isHome);
1600
Michael Kolbe0a36662010-06-29 10:37:12 -07001601 final MenuItem forward = menu.findItem(R.id.forward_menu_id);
1602 forward.setEnabled(canGoForward);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001603
Michael Kolbed217742010-08-10 17:52:34 -07001604 if (!mXLargeScreenSize) {
1605 final MenuItem newtab = menu.findItem(R.id.new_tab_menu_id);
1606 newtab.setEnabled(mTabControl.canCreateNewTab());
1607 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001608 // decide whether to show the share link option
1609 PackageManager pm = getPackageManager();
1610 Intent send = new Intent(Intent.ACTION_SEND);
1611 send.setType("text/plain");
1612 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1613 menu.findItem(R.id.share_page_menu_id).setVisible(ri != null);
1614
The Android Open Source Project0c908882009-03-03 19:32:16 -08001615 boolean isNavDump = mSettings.isNavDump();
1616 final MenuItem nav = menu.findItem(R.id.dump_nav_menu_id);
1617 nav.setVisible(isNavDump);
1618 nav.setEnabled(isNavDump);
Andrei Popescu7a8b88b2010-02-02 00:30:38 +00001619
1620 boolean showDebugSettings = mSettings.showDebugSettings();
1621 final MenuItem counter = menu.findItem(R.id.dump_counters_menu_id);
1622 counter.setVisible(showDebugSettings);
1623 counter.setEnabled(showDebugSettings);
1624
The Android Open Source Project0c908882009-03-03 19:32:16 -08001625 break;
1626 }
1627 mCurrentMenuState = mMenuState;
1628 return true;
1629 }
1630
1631 @Override
1632 public void onCreateContextMenu(ContextMenu menu, View v,
1633 ContextMenuInfo menuInfo) {
Leon Scroggins571b3762010-05-26 10:25:01 -04001634 if (v instanceof TitleBarBase) {
Leon Scroggins4e9f89b2010-02-22 16:54:14 -05001635 return;
1636 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001637 WebView webview = (WebView) v;
1638 WebView.HitTestResult result = webview.getHitTestResult();
1639 if (result == null) {
1640 return;
1641 }
1642
1643 int type = result.getType();
1644 if (type == WebView.HitTestResult.UNKNOWN_TYPE) {
1645 Log.w(LOGTAG,
1646 "We should not show context menu when nothing is touched");
1647 return;
1648 }
1649 if (type == WebView.HitTestResult.EDIT_TEXT_TYPE) {
1650 // let TextView handles context menu
1651 return;
1652 }
1653
1654 // Note, http://b/issue?id=1106666 is requesting that
1655 // an inflated menu can be used again. This is not available
1656 // yet, so inflate each time (yuk!)
1657 MenuInflater inflater = getMenuInflater();
1658 inflater.inflate(R.menu.browsercontext, menu);
1659
1660 // Show the correct menu group
Leon Scroggins III9e997c72010-05-26 13:25:16 -04001661 final String extra = result.getExtra();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001662 menu.setGroupVisible(R.id.PHONE_MENU,
1663 type == WebView.HitTestResult.PHONE_TYPE);
1664 menu.setGroupVisible(R.id.EMAIL_MENU,
1665 type == WebView.HitTestResult.EMAIL_TYPE);
1666 menu.setGroupVisible(R.id.GEO_MENU,
1667 type == WebView.HitTestResult.GEO_TYPE);
1668 menu.setGroupVisible(R.id.IMAGE_MENU,
1669 type == WebView.HitTestResult.IMAGE_TYPE
1670 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1671 menu.setGroupVisible(R.id.ANCHOR_MENU,
1672 type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1673 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1674
1675 // Setup custom handling depending on the type
1676 switch (type) {
1677 case WebView.HitTestResult.PHONE_TYPE:
1678 menu.setHeaderTitle(Uri.decode(extra));
1679 menu.findItem(R.id.dial_context_menu_id).setIntent(
1680 new Intent(Intent.ACTION_VIEW, Uri
1681 .parse(WebView.SCHEME_TEL + extra)));
1682 Intent addIntent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
1683 addIntent.putExtra(Insert.PHONE, Uri.decode(extra));
Cary Clark5e335a32009-09-22 14:53:11 -04001684 addIntent.setType(ContactsContract.Contacts.CONTENT_ITEM_TYPE);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001685 menu.findItem(R.id.add_contact_context_menu_id).setIntent(
1686 addIntent);
1687 menu.findItem(R.id.copy_phone_context_menu_id).setOnMenuItemClickListener(
1688 new Copy(extra));
1689 break;
1690
1691 case WebView.HitTestResult.EMAIL_TYPE:
1692 menu.setHeaderTitle(extra);
1693 menu.findItem(R.id.email_context_menu_id).setIntent(
1694 new Intent(Intent.ACTION_VIEW, Uri
1695 .parse(WebView.SCHEME_MAILTO + extra)));
1696 menu.findItem(R.id.copy_mail_context_menu_id).setOnMenuItemClickListener(
1697 new Copy(extra));
1698 break;
1699
1700 case WebView.HitTestResult.GEO_TYPE:
1701 menu.setHeaderTitle(extra);
1702 menu.findItem(R.id.map_context_menu_id).setIntent(
1703 new Intent(Intent.ACTION_VIEW, Uri
1704 .parse(WebView.SCHEME_GEO
1705 + URLEncoder.encode(extra))));
1706 menu.findItem(R.id.copy_geo_context_menu_id).setOnMenuItemClickListener(
1707 new Copy(extra));
1708 break;
1709
1710 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1711 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
1712 TextView titleView = (TextView) LayoutInflater.from(this)
1713 .inflate(android.R.layout.browser_link_context_header,
1714 null);
1715 titleView.setText(extra);
1716 menu.setHeaderView(titleView);
1717 // decide whether to show the open link in new tab option
Leon Scroggins III9e997c72010-05-26 13:25:16 -04001718 boolean showNewTab = mTabControl.canCreateNewTab();
1719 MenuItem newTabItem
1720 = menu.findItem(R.id.open_newtab_context_menu_id);
1721 newTabItem.setVisible(showNewTab);
1722 if (showNewTab) {
1723 newTabItem.setOnMenuItemClickListener(
1724 new MenuItem.OnMenuItemClickListener() {
1725 public boolean onMenuItemClick(MenuItem item) {
1726 final Tab parent = mTabControl.getCurrentTab();
Michael Kolb68792c82010-08-09 16:39:18 -07001727 final Tab newTab = openTab(extra, false);
Leon Scroggins III9e997c72010-05-26 13:25:16 -04001728 if (newTab != parent) {
1729 parent.addChildTab(newTab);
1730 }
1731 return true;
1732 }
1733 });
1734 }
Ben Murdochde353622009-10-12 10:29:00 +01001735 menu.findItem(R.id.bookmark_context_menu_id).setVisible(
1736 Bookmarks.urlHasAcceptableScheme(extra));
The Android Open Source Project0c908882009-03-03 19:32:16 -08001737 PackageManager pm = getPackageManager();
1738 Intent send = new Intent(Intent.ACTION_SEND);
1739 send.setType("text/plain");
1740 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1741 menu.findItem(R.id.share_link_context_menu_id).setVisible(ri != null);
1742 if (type == WebView.HitTestResult.SRC_ANCHOR_TYPE) {
1743 break;
1744 }
1745 // otherwise fall through to handle image part
1746 case WebView.HitTestResult.IMAGE_TYPE:
1747 if (type == WebView.HitTestResult.IMAGE_TYPE) {
1748 menu.setHeaderTitle(extra);
1749 }
1750 menu.findItem(R.id.view_image_context_menu_id).setIntent(
1751 new Intent(Intent.ACTION_VIEW, Uri.parse(extra)));
1752 menu.findItem(R.id.download_context_menu_id).
1753 setOnMenuItemClickListener(new Download(extra));
Ben Murdoch4f75ba22009-10-27 11:48:28 +00001754 menu.findItem(R.id.set_wallpaper_context_menu_id).
1755 setOnMenuItemClickListener(new SetAsWallpaper(extra));
The Android Open Source Project0c908882009-03-03 19:32:16 -08001756 break;
1757
1758 default:
1759 Log.w(LOGTAG, "We should not get here.");
1760 break;
1761 }
Leon Scrogginsb2b19f52009-10-09 16:10:00 -04001762 hideFakeTitleBar();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001763 }
1764
The Android Open Source Project0c908882009-03-03 19:32:16 -08001765 // Attach the given tab to the content view.
Grace Klobac928c302009-09-17 11:51:21 -07001766 // this should only be called for the current tab.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001767 private void attachTabToContentView(Tab t) {
Steve Block2bc69912009-07-30 14:45:13 +01001768 // Attach the container that contains the main WebView and any other UI
1769 // associated with the tab.
Patrick Scottd0119532009-09-17 08:00:31 -04001770 t.attachTabToContentView(mContentView);
Ben Murdochbff2d602009-07-01 20:19:05 +01001771
1772 if (mShouldShowErrorConsole) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001773 ErrorConsoleView errorConsole = t.getErrorConsole(true);
Ben Murdochbff2d602009-07-01 20:19:05 +01001774 if (errorConsole.numberOfErrors() == 0) {
1775 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
1776 } else {
1777 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
1778 }
1779
1780 mErrorConsoleContainer.addView(errorConsole,
Romain Guy15b8ec62010-01-08 15:06:43 -08001781 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
Ben Murdochbff2d602009-07-01 20:19:05 +01001782 ViewGroup.LayoutParams.WRAP_CONTENT));
1783 }
1784
Michael Kolba2b2ba82010-08-04 17:54:03 -07001785 WebView view = t.getWebView();
1786 view.setEmbeddedTitleBar(mTitleBar);
Leon Scroggins58d56c62010-01-28 15:12:40 -05001787 if (t.isInVoiceSearchMode()) {
1788 showVoiceTitleBar(t.getVoiceDisplayTitle());
1789 } else {
1790 revertVoiceTitleBar();
1791 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001792 // Request focus on the top window.
1793 t.getTopWindow().requestFocus();
Michael Kolba2b2ba82010-08-04 17:54:03 -07001794 if (mTabControl.getTabChangeListener() != null) {
1795 mTabControl.getTabChangeListener().onCurrentTab(t);
1796 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001797 }
1798
1799 // Attach a sub window to the main WebView of the given tab.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001800 void attachSubWindow(Tab t) {
Patrick Scottd0119532009-09-17 08:00:31 -04001801 t.attachSubWindow(mContentView);
1802 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001803 }
1804
1805 // Remove the given tab from the content view.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001806 private void removeTabFromContentView(Tab t) {
Steve Block2bc69912009-07-30 14:45:13 +01001807 // Remove the container that contains the main WebView.
Patrick Scottd0119532009-09-17 08:00:31 -04001808 t.removeTabFromContentView(mContentView);
Ben Murdochbff2d602009-07-01 20:19:05 +01001809
Grace Kloba22ac16e2009-10-07 18:00:23 -07001810 ErrorConsoleView errorConsole = t.getErrorConsole(false);
1811 if (errorConsole != null) {
1812 mErrorConsoleContainer.removeView(errorConsole);
Ben Murdochbff2d602009-07-01 20:19:05 +01001813 }
1814
Michael Kolba2b2ba82010-08-04 17:54:03 -07001815 WebView view = t.getWebView();
1816 if (view != null) {
1817 view.setEmbeddedTitleBar(null);
Leon Scrogginsbb85b902009-09-14 19:27:20 -04001818 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001819 }
1820
1821 // Remove the sub window if it exists. Also called by TabControl when the
1822 // user clicks the 'X' to dismiss a sub window.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001823 /* package */ void dismissSubWindow(Tab t) {
Patrick Scottd0119532009-09-17 08:00:31 -04001824 t.removeSubWindow(mContentView);
Grace Kloba22ac16e2009-10-07 18:00:23 -07001825 // dismiss the subwindow. This will destroy the WebView.
1826 t.dismissSubWindow();
Patrick Scottd0119532009-09-17 08:00:31 -04001827 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001828 }
1829
Leon Scroggins1f005d32009-08-10 17:36:42 -04001830 // A wrapper function of {@link #openTabAndShow(UrlData, boolean, String)}
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07001831 // that accepts url as string.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001832 private Tab openTabAndShow(String url, boolean closeOnExit, String appId) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001833 return openTabAndShow(new UrlData(url), closeOnExit, appId);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001834 }
1835
1836 // This method does a ton of stuff. It will attempt to create a new tab
1837 // if we haven't reached MAX_TABS. Otherwise it uses the current tab. If
Leon Scroggins1f005d32009-08-10 17:36:42 -04001838 // url isn't null, it will load the given url.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001839 /* package */Tab openTabAndShow(UrlData urlData, boolean closeOnExit,
1840 String appId) {
1841 final Tab currentTab = mTabControl.getCurrentTab();
1842 if (mTabControl.canCreateNewTab()) {
1843 final Tab tab = mTabControl.createNewTab(closeOnExit, appId,
Elliott Slaughterf0f03952010-07-14 18:10:36 -07001844 urlData.mUrl, false);
Leon Scroggins1f005d32009-08-10 17:36:42 -04001845 WebView webview = tab.getWebView();
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001846 // If the last tab was removed from the active tabs page, currentTab
1847 // will be null.
1848 if (currentTab != null) {
1849 removeTabFromContentView(currentTab);
1850 }
Patrick Scott8bbd69f2009-08-14 13:35:53 -04001851 // We must set the new tab as the current tab to reflect the old
1852 // animation behavior.
1853 mTabControl.setCurrentTab(tab);
Grace Klobaeb6eef42009-09-15 17:56:32 -07001854 attachTabToContentView(tab);
Leon Scroggins160a7e72009-08-14 18:28:01 -04001855 if (!urlData.isEmpty()) {
Patrick Scott9d53da02010-02-19 10:19:01 -05001856 loadUrlDataIn(tab, urlData);
Leon Scroggins1f005d32009-08-10 17:36:42 -04001857 }
1858 return tab;
1859 } else {
1860 // Get rid of the subwindow if it exists
1861 dismissSubWindow(currentTab);
1862 if (!urlData.isEmpty()) {
1863 // Load the given url.
Patrick Scott9d53da02010-02-19 10:19:01 -05001864 loadUrlDataIn(currentTab, urlData);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001865 }
Leon Scroggins58d56c62010-01-28 15:12:40 -05001866 return currentTab;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001867 }
1868 }
1869
Michael Kolb68792c82010-08-09 16:39:18 -07001870 private Tab openTab(String url, boolean forceForeground) {
1871 if (mSettings.openInBackground() && !forceForeground) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001872 Tab t = mTabControl.createNewTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001873 if (t != null) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001874 WebView view = t.getWebView();
Leon Scroggins92472e82010-02-17 16:32:28 -05001875 loadUrl(view, url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001876 }
Grace Klobac9181842009-04-14 08:53:22 -07001877 return t;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001878 } else {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001879 return openTabAndShow(url, false, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001880 }
1881 }
1882
Elliott Slaughterf0f03952010-07-14 18:10:36 -07001883 /* package */ Tab openIncognitoTab() {
1884 if (mTabControl.canCreateNewTab()) {
1885 Tab currentTab = mTabControl.getCurrentTab();
1886 Tab tab = mTabControl.createNewTab(false, null, null, true);
1887 if (currentTab != null) {
1888 removeTabFromContentView(currentTab);
1889 }
1890 mTabControl.setCurrentTab(tab);
1891 attachTabToContentView(tab);
1892 return tab;
1893 }
1894 return null;
1895 }
1896
The Android Open Source Project0c908882009-03-03 19:32:16 -08001897 private class Copy implements OnMenuItemClickListener {
1898 private CharSequence mText;
1899
1900 public boolean onMenuItemClick(MenuItem item) {
1901 copy(mText);
1902 return true;
1903 }
1904
1905 public Copy(CharSequence toCopy) {
1906 mText = toCopy;
1907 }
1908 }
1909
1910 private class Download implements OnMenuItemClickListener {
1911 private String mText;
1912
1913 public boolean onMenuItemClick(MenuItem item) {
1914 onDownloadStartNoStream(mText, null, null, null, -1);
1915 return true;
1916 }
1917
1918 public Download(String toDownload) {
1919 mText = toDownload;
1920 }
1921 }
1922
Ben Murdoch4f75ba22009-10-27 11:48:28 +00001923 private class SetAsWallpaper extends Thread implements
1924 OnMenuItemClickListener, DialogInterface.OnCancelListener {
1925 private URL mUrl;
1926 private ProgressDialog mWallpaperProgress;
1927 private boolean mCanceled = false;
1928
1929 public SetAsWallpaper(String url) {
1930 try {
1931 mUrl = new URL(url);
1932 } catch (MalformedURLException e) {
1933 mUrl = null;
1934 }
1935 }
1936
1937 public void onCancel(DialogInterface dialog) {
1938 mCanceled = true;
1939 }
1940
1941 public boolean onMenuItemClick(MenuItem item) {
1942 if (mUrl != null) {
1943 // The user may have tried to set a image with a large file size as their
1944 // background so it may take a few moments to perform the operation. Display
1945 // a progress spinner while it is working.
1946 mWallpaperProgress = new ProgressDialog(BrowserActivity.this);
1947 mWallpaperProgress.setIndeterminate(true);
1948 mWallpaperProgress.setMessage(getText(R.string.progress_dialog_setting_wallpaper));
1949 mWallpaperProgress.setCancelable(true);
1950 mWallpaperProgress.setOnCancelListener(this);
1951 mWallpaperProgress.show();
1952 start();
1953 }
1954 return true;
1955 }
1956
Michael Kolbe0a36662010-06-29 10:37:12 -07001957 @Override
Ben Murdoch4f75ba22009-10-27 11:48:28 +00001958 public void run() {
1959 Drawable oldWallpaper = BrowserActivity.this.getWallpaper();
1960 try {
1961 // TODO: This will cause the resource to be downloaded again, when we
1962 // should in most cases be able to grab it from the cache. To fix this
1963 // we should query WebCore to see if we can access a cached version and
1964 // instead open an input stream on that. This pattern could also be used
1965 // in the download manager where the same problem exists.
1966 InputStream inputstream = mUrl.openStream();
1967 if (inputstream != null) {
1968 setWallpaper(inputstream);
1969 }
1970 } catch (IOException e) {
1971 Log.e(LOGTAG, "Unable to set new wallpaper");
1972 // Act as though the user canceled the operation so we try to
1973 // restore the old wallpaper.
1974 mCanceled = true;
1975 }
1976
1977 if (mCanceled) {
1978 // Restore the old wallpaper if the user cancelled whilst we were setting
1979 // the new wallpaper.
1980 int width = oldWallpaper.getIntrinsicWidth();
1981 int height = oldWallpaper.getIntrinsicHeight();
1982 Bitmap bm = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
1983 Canvas canvas = new Canvas(bm);
1984 oldWallpaper.setBounds(0, 0, width, height);
1985 oldWallpaper.draw(canvas);
1986 try {
1987 setWallpaper(bm);
1988 } catch (IOException e) {
1989 Log.e(LOGTAG, "Unable to restore old wallpaper.");
1990 }
1991 mCanceled = false;
1992 }
1993
1994 if (mWallpaperProgress.isShowing()) {
1995 mWallpaperProgress.dismiss();
1996 }
1997 }
1998 }
1999
The Android Open Source Project0c908882009-03-03 19:32:16 -08002000 private void copy(CharSequence text) {
Dianne Hackborn80f32622010-08-05 14:17:53 -07002001 ClipboardManager cm = (ClipboardManager)getSystemService(Context.CLIPBOARD_SERVICE);
2002 cm.setText(text);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002003 }
2004
2005 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08002006 * Resets the browser title-view to whatever it must be
2007 * (for example, if we had a loading error)
2008 * When we have a new page, we call resetTitle, when we
2009 * have to reset the titlebar to whatever it used to be
2010 * (for example, if the user chose to stop loading), we
2011 * call resetTitleAndRevertLockIcon.
2012 */
2013 /* package */ void resetTitleAndRevertLockIcon() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002014 mTabControl.getCurrentTab().revertLockIcon();
2015 updateLockIconToLatest();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002016 resetTitleIconAndProgress();
2017 }
2018
2019 /**
2020 * Reset the title, favicon, and progress.
2021 */
2022 private void resetTitleIconAndProgress() {
2023 WebView current = mTabControl.getCurrentWebView();
2024 if (current == null) {
2025 return;
2026 }
2027 resetTitleAndIcon(current);
2028 int progress = current.getProgress();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002029 current.getWebChromeClient().onProgressChanged(current, progress);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002030 }
2031
2032 // Reset the title and the icon based on the given item.
2033 private void resetTitleAndIcon(WebView view) {
2034 WebHistoryItem item = view.copyBackForwardList().getCurrentItem();
2035 if (item != null) {
Leon Scroggins68579392009-09-15 15:31:54 -04002036 setUrlTitle(item.getUrl(), item.getTitle());
The Android Open Source Project0c908882009-03-03 19:32:16 -08002037 setFavicon(item.getFavicon());
2038 } else {
Leon Scroggins68579392009-09-15 15:31:54 -04002039 setUrlTitle(null, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002040 setFavicon(null);
2041 }
2042 }
2043
2044 /**
2045 * Sets a title composed of the URL and the title string.
2046 * @param url The URL of the site being loaded.
2047 * @param title The title of the site being loaded.
2048 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07002049 void setUrlTitle(String url, String title) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002050 mUrl = url;
2051 mTitle = title;
2052
Leon Scroggins58d56c62010-01-28 15:12:40 -05002053 // If we are in voice search mode, the title has already been set.
2054 if (mTabControl.getCurrentTab().isInVoiceSearchMode()) return;
2055 mTitleBar.setDisplayTitle(url);
Michael Kolba2b2ba82010-08-04 17:54:03 -07002056 mFakeTitleBar.setDisplayTitle(url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002057 }
2058
2059 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08002060 * @param url The URL to build a title version of the URL from.
2061 * @return The title version of the URL or null if fails.
2062 * The title version of the URL can be either the URL hostname,
2063 * or the hostname with an "https://" prefix (for secure URLs),
2064 * or an empty string if, for example, the URL in question is a
2065 * file:// URL with no hostname.
2066 */
Leon Scroggins32e14a62009-06-11 10:26:34 -04002067 /* package */ static String buildTitleUrl(String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002068 String titleUrl = null;
2069
2070 if (url != null) {
2071 try {
2072 // parse the url string
2073 URL urlObj = new URL(url);
2074 if (urlObj != null) {
2075 titleUrl = "";
2076
2077 String protocol = urlObj.getProtocol();
2078 String host = urlObj.getHost();
2079
2080 if (host != null && 0 < host.length()) {
2081 titleUrl = host;
2082 if (protocol != null) {
2083 // if a secure site, add an "https://" prefix!
2084 if (protocol.equalsIgnoreCase("https")) {
2085 titleUrl = protocol + "://" + host;
2086 }
2087 }
2088 }
2089 }
2090 } catch (MalformedURLException e) {}
2091 }
2092
2093 return titleUrl;
2094 }
2095
2096 // Set the favicon in the title bar.
Grace Kloba22ac16e2009-10-07 18:00:23 -07002097 void setFavicon(Bitmap icon) {
Leon Scroggins68579392009-09-15 15:31:54 -04002098 mTitleBar.setFavicon(icon);
Michael Kolba2b2ba82010-08-04 17:54:03 -07002099 mFakeTitleBar.setFavicon(icon);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002100 }
2101
2102 /**
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002103 * Close the tab, remove its associated title bar, and adjust mTabControl's
2104 * current tab to a valid value.
Leon Scroggins1f005d32009-08-10 17:36:42 -04002105 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07002106 /* package */ void closeTab(Tab t) {
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002107 int currentIndex = mTabControl.getCurrentIndex();
2108 int removeIndex = mTabControl.getTabIndex(t);
Leon Scroggins1f005d32009-08-10 17:36:42 -04002109 mTabControl.removeTab(t);
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002110 if (currentIndex >= removeIndex && currentIndex != 0) {
2111 currentIndex--;
2112 }
2113 mTabControl.setCurrentTab(mTabControl.getTab(currentIndex));
Andrei Popescua5bf1de2009-09-23 16:39:23 +01002114 resetTitleIconAndProgress();
Leon Scroggins654899b2010-06-25 16:25:23 -04002115 updateLockIconToLatest();
Elliott Slaughtere440a882010-08-20 13:54:45 -07002116
2117 if (!mTabControl.hasAnyOpenIncognitoTabs()) {
2118 WebView.cleanupPrivateBrowsingFiles(this);
2119 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002120 }
2121
Leon Scrogginsdcc5eeb2010-02-23 17:26:37 -05002122 /* package */ void goBackOnePageOrQuit() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002123 Tab current = mTabControl.getCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002124 if (current == null) {
2125 /*
2126 * Instead of finishing the activity, simply push this to the back
2127 * of the stack and let ActivityManager to choose the foreground
2128 * activity. As BrowserActivity is singleTask, it will be always the
2129 * root of the task. So we can use either true or false for
2130 * moveTaskToBack().
2131 */
2132 moveTaskToBack(true);
Grace Kloba00d85e72009-09-23 18:50:05 -07002133 return;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002134 }
2135 WebView w = current.getWebView();
2136 if (w.canGoBack()) {
2137 w.goBack();
2138 } else {
2139 // Check to see if we are closing a window that was created by
2140 // another window. If so, we switch back to that window.
Grace Kloba22ac16e2009-10-07 18:00:23 -07002141 Tab parent = current.getParentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002142 if (parent != null) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04002143 switchToTab(mTabControl.getTabIndex(parent));
2144 // Now we close the other tab
2145 closeTab(current);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002146 } else {
2147 if (current.closeOnExit()) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002148 // force the tab's inLoad() to be false as we are going to
2149 // either finish the activity or remove the tab. This will
2150 // ensure pauseWebViewTimers() taking action.
2151 mTabControl.getCurrentTab().clearInLoad();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002152 if (mTabControl.getTabCount() == 1) {
2153 finish();
2154 return;
2155 }
Mike Reed7bfa63b2009-05-28 11:08:32 -04002156 // call pauseWebViewTimers() now, we won't be able to call
2157 // it in onPause() as the WebView won't be valid.
Grace Klobaec1b5ad2009-08-18 08:42:32 -07002158 // Temporarily change mActivityInPause to be true as
2159 // pauseWebViewTimers() will do nothing if mActivityInPause
2160 // is false.
Grace Kloba918e1d72009-08-13 14:55:06 -07002161 boolean savedState = mActivityInPause;
2162 if (savedState) {
Grace Klobaec1b5ad2009-08-18 08:42:32 -07002163 Log.e(LOGTAG, "BrowserActivity is already paused "
2164 + "while handing goBackOnePageOrQuit.");
Grace Kloba918e1d72009-08-13 14:55:06 -07002165 }
2166 mActivityInPause = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -04002167 pauseWebViewTimers();
Grace Kloba918e1d72009-08-13 14:55:06 -07002168 mActivityInPause = savedState;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002169 removeTabFromContentView(current);
2170 mTabControl.removeTab(current);
2171 }
2172 /*
2173 * Instead of finishing the activity, simply push this to the back
2174 * of the stack and let ActivityManager to choose the foreground
2175 * activity. As BrowserActivity is singleTask, it will be always the
2176 * root of the task. So we can use either true or false for
2177 * moveTaskToBack().
2178 */
2179 moveTaskToBack(true);
2180 }
2181 }
2182 }
2183
Grace Kloba22ac16e2009-10-07 18:00:23 -07002184 boolean isMenuDown() {
2185 return mMenuIsDown;
2186 }
2187
Grace Kloba5942df02009-09-18 11:48:29 -07002188 @Override
2189 public boolean onKeyDown(int keyCode, KeyEvent event) {
Leon Scrogginsf65b50d2009-12-08 10:44:28 -05002190 // Even if MENU is already held down, we need to call to super to open
2191 // the IME on long press.
2192 if (KeyEvent.KEYCODE_MENU == keyCode) {
2193 mMenuIsDown = true;
2194 return super.onKeyDown(keyCode, event);
2195 }
Grace Kloba5942df02009-09-18 11:48:29 -07002196 // The default key mode is DEFAULT_KEYS_SEARCH_LOCAL. As the MENU is
2197 // still down, we don't want to trigger the search. Pretend to consume
2198 // the key and do nothing.
2199 if (mMenuIsDown) return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002200
Grace Kloba5942df02009-09-18 11:48:29 -07002201 switch(keyCode) {
Grace Kloba5942df02009-09-18 11:48:29 -07002202 case KeyEvent.KEYCODE_SPACE:
Grace Klobada0fe552009-09-22 18:17:24 -07002203 // WebView/WebTextView handle the keys in the KeyDown. As
2204 // the Activity's shortcut keys are only handled when WebView
2205 // doesn't, have to do it in onKeyDown instead of onKeyUp.
2206 if (event.isShiftPressed()) {
2207 getTopWindow().pageUp(false);
2208 } else {
2209 getTopWindow().pageDown(false);
2210 }
Grace Kloba5942df02009-09-18 11:48:29 -07002211 return true;
2212 case KeyEvent.KEYCODE_BACK:
2213 if (event.getRepeatCount() == 0) {
2214 event.startTracking();
2215 return true;
2216 } else if (mCustomView == null && mActiveTabsPage == null
Michael Kolbe421c242010-10-04 19:29:01 -07002217 && mComboView == null
Grace Kloba5942df02009-09-18 11:48:29 -07002218 && event.isLongPress()) {
Michael Kolbe421c242010-10-04 19:29:01 -07002219 bookmarksOrHistoryPicker(true);
Grace Kloba5942df02009-09-18 11:48:29 -07002220 return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002221 }
Grace Kloba5942df02009-09-18 11:48:29 -07002222 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002223 }
Grace Kloba5942df02009-09-18 11:48:29 -07002224 return super.onKeyDown(keyCode, event);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002225 }
2226
Grace Kloba5942df02009-09-18 11:48:29 -07002227 @Override
2228 public boolean onKeyUp(int keyCode, KeyEvent event) {
2229 switch(keyCode) {
2230 case KeyEvent.KEYCODE_MENU:
2231 mMenuIsDown = false;
2232 break;
Grace Kloba5942df02009-09-18 11:48:29 -07002233 case KeyEvent.KEYCODE_BACK:
2234 if (event.isTracking() && !event.isCanceled()) {
2235 if (mCustomView != null) {
2236 // if a custom view is showing, hide it
Grace Kloba22ac16e2009-10-07 18:00:23 -07002237 mTabControl.getCurrentWebView().getWebChromeClient()
2238 .onHideCustomView();
Grace Kloba5942df02009-09-18 11:48:29 -07002239 } else if (mActiveTabsPage != null) {
2240 // if tab page is showing, hide it
2241 removeActiveTabPage(true);
Michael Kolbe421c242010-10-04 19:29:01 -07002242 } else if (mComboView != null) {
Michael Kolb370a4f32010-10-06 10:45:32 -07002243 if (!mComboView.onBackPressed()) {
2244 removeComboView();
2245 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002246 } else {
Grace Kloba5942df02009-09-18 11:48:29 -07002247 WebView subwindow = mTabControl.getCurrentSubWindow();
2248 if (subwindow != null) {
2249 if (subwindow.canGoBack()) {
2250 subwindow.goBack();
2251 } else {
2252 dismissSubWindow(mTabControl.getCurrentTab());
2253 }
2254 } else {
2255 goBackOnePageOrQuit();
2256 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002257 }
Grace Kloba5942df02009-09-18 11:48:29 -07002258 return true;
2259 }
2260 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002261 }
Grace Kloba5942df02009-09-18 11:48:29 -07002262 return super.onKeyUp(keyCode, event);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002263 }
2264
Leon Scroggins68579392009-09-15 15:31:54 -04002265 /* package */ void stopLoading() {
Ben Murdochb7cc8b42009-09-28 10:59:09 +01002266 mDidStopLoad = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002267 resetTitleAndRevertLockIcon();
2268 WebView w = getTopWindow();
2269 w.stopLoading();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002270 // FIXME: before refactor, it is using mWebViewClient. So I keep the
2271 // same logic here. But for subwindow case, should we call into the main
2272 // WebView's onPageFinished as we never call its onPageStarted and if
2273 // the page finishes itself, we don't call onPageFinished.
2274 mTabControl.getCurrentWebView().getWebViewClient().onPageFinished(w,
2275 w.getUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08002276
2277 cancelStopToast();
2278 mStopToast = Toast
2279 .makeText(this, R.string.stopping, Toast.LENGTH_SHORT);
2280 mStopToast.show();
2281 }
2282
Grace Kloba22ac16e2009-10-07 18:00:23 -07002283 boolean didUserStopLoading() {
2284 return mDidStopLoad;
2285 }
2286
The Android Open Source Project0c908882009-03-03 19:32:16 -08002287 private void cancelStopToast() {
2288 if (mStopToast != null) {
2289 mStopToast.cancel();
2290 mStopToast = null;
2291 }
2292 }
2293
Grace Kloba22ac16e2009-10-07 18:00:23 -07002294 // called by a UI or non-UI thread to post the message
2295 public void postMessage(int what, int arg1, int arg2, Object obj,
2296 long delayMillis) {
2297 mHandler.sendMessageDelayed(mHandler.obtainMessage(what, arg1, arg2,
2298 obj), delayMillis);
2299 }
2300
2301 // called by a UI or non-UI thread to remove the message
2302 void removeMessages(int what, Object object) {
2303 mHandler.removeMessages(what, object);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002304 }
2305
2306 // public message ids
2307 public final static int LOAD_URL = 1001;
2308 public final static int STOP_LOAD = 1002;
2309
2310 // Message Ids
2311 private static final int FOCUS_NODE_HREF = 102;
Grace Kloba92c18a52009-07-31 23:48:32 -07002312 private static final int RELEASE_WAKELOCK = 107;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002313
Grace Kloba22ac16e2009-10-07 18:00:23 -07002314 static final int UPDATE_BOOKMARK_THUMBNAIL = 108;
Ben Murdoch2694e232009-09-29 09:41:11 +01002315
Ben Murdocheecb4e62010-07-06 16:30:38 +01002316 private static final int TOUCH_ICON_DOWNLOADED = 109;
2317
Michael Kolb300b7f02010-08-25 13:47:24 -07002318 private static final int OPEN_BOOKMARKS = 201;
2319
The Android Open Source Project0c908882009-03-03 19:32:16 -08002320 // Private handler for handling javascript and saving passwords
2321 private Handler mHandler = new Handler() {
2322
Michael Kolbe0a36662010-06-29 10:37:12 -07002323 @Override
The Android Open Source Project0c908882009-03-03 19:32:16 -08002324 public void handleMessage(Message msg) {
2325 switch (msg.what) {
Michael Kolb300b7f02010-08-25 13:47:24 -07002326 case OPEN_BOOKMARKS:
Michael Kolbe421c242010-10-04 19:29:01 -07002327 bookmarksOrHistoryPicker(false);
Michael Kolb300b7f02010-08-25 13:47:24 -07002328 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002329 case FOCUS_NODE_HREF:
Ben Murdoch2694e232009-09-29 09:41:11 +01002330 {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002331 String url = (String) msg.getData().get("url");
Ben Murdoch90d088c2009-11-17 18:14:04 +00002332 String title = (String) msg.getData().get("title");
The Android Open Source Project0c908882009-03-03 19:32:16 -08002333 if (url == null || url.length() == 0) {
2334 break;
2335 }
2336 HashMap focusNodeMap = (HashMap) msg.obj;
2337 WebView view = (WebView) focusNodeMap.get("webview");
2338 // Only apply the action if the top window did not change.
2339 if (getTopWindow() != view) {
2340 break;
2341 }
2342 switch (msg.arg1) {
2343 case R.id.open_context_menu_id:
2344 case R.id.view_image_context_menu_id:
Leon Scroggins92472e82010-02-17 16:32:28 -05002345 loadUrlFromContext(getTopWindow(), url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002346 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002347 case R.id.bookmark_context_menu_id:
2348 Intent intent = new Intent(BrowserActivity.this,
2349 AddBookmarkPage.class);
2350 intent.putExtra("url", url);
Ben Murdoch90d088c2009-11-17 18:14:04 +00002351 intent.putExtra("title", title);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002352 startActivity(intent);
2353 break;
2354 case R.id.share_link_context_menu_id:
Leon Scroggins3e204452010-05-10 11:06:03 -04002355 sharePage(BrowserActivity.this, title, url, null,
Leon Scroggins96afcb12009-12-10 12:35:56 -05002356 null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002357 break;
2358 case R.id.copy_link_context_menu_id:
2359 copy(url);
2360 break;
2361 case R.id.save_link_context_menu_id:
2362 case R.id.download_context_menu_id:
2363 onDownloadStartNoStream(url, null, null, null, -1);
2364 break;
2365 }
2366 break;
Ben Murdoch2694e232009-09-29 09:41:11 +01002367 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002368
2369 case LOAD_URL:
Leon Scroggins92472e82010-02-17 16:32:28 -05002370 loadUrlFromContext(getTopWindow(), (String) msg.obj);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002371 break;
2372
2373 case STOP_LOAD:
2374 stopLoading();
2375 break;
2376
The Android Open Source Project0c908882009-03-03 19:32:16 -08002377 case RELEASE_WAKELOCK:
2378 if (mWakeLock.isHeld()) {
2379 mWakeLock.release();
Grace Kloba5d0e02e2009-10-05 15:15:36 -07002380 // if we reach here, Browser should be still in the
2381 // background loading after WAKELOCK_TIMEOUT (5-min).
2382 // To avoid burning the battery, stop loading.
2383 mTabControl.stopAllLoading();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002384 }
2385 break;
Ben Murdoch2694e232009-09-29 09:41:11 +01002386
2387 case UPDATE_BOOKMARK_THUMBNAIL:
2388 WebView view = (WebView) msg.obj;
2389 if (view != null) {
2390 updateScreenshot(view);
2391 }
2392 break;
Ben Murdocheecb4e62010-07-06 16:30:38 +01002393
2394 case TOUCH_ICON_DOWNLOADED:
2395 Bundle b = msg.getData();
2396 showSaveToHomescreenDialog(b.getString("url"),
2397 b.getString("title"),
2398 (Bitmap) b.getParcelable("touchIcon"),
2399 (Bitmap) b.getParcelable("favicon"));
2400 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002401 }
2402 }
2403 };
2404
Leon Scroggins96afcb12009-12-10 12:35:56 -05002405 /**
2406 * Share a page, providing the title, url, favicon, and a screenshot. Uses
2407 * an {@link Intent} to launch the Activity chooser.
2408 * @param c Context used to launch a new Activity.
2409 * @param title Title of the page. Stored in the Intent with
Paul Westbrook03e6d392010-02-12 10:33:29 -08002410 * {@link Intent#EXTRA_SUBJECT}
Leon Scroggins96afcb12009-12-10 12:35:56 -05002411 * @param url URL of the page. Stored in the Intent with
2412 * {@link Intent#EXTRA_TEXT}
2413 * @param favicon Bitmap of the favicon for the page. Stored in the Intent
2414 * with {@link Browser#EXTRA_SHARE_FAVICON}
2415 * @param screenshot Bitmap of a screenshot of the page. Stored in the
2416 * Intent with {@link Browser#EXTRA_SHARE_SCREENSHOT}
2417 */
2418 public static final void sharePage(Context c, String title, String url,
2419 Bitmap favicon, Bitmap screenshot) {
2420 Intent send = new Intent(Intent.ACTION_SEND);
2421 send.setType("text/plain");
2422 send.putExtra(Intent.EXTRA_TEXT, url);
Paul Westbrook03e6d392010-02-12 10:33:29 -08002423 send.putExtra(Intent.EXTRA_SUBJECT, title);
Leon Scroggins96afcb12009-12-10 12:35:56 -05002424 send.putExtra(Browser.EXTRA_SHARE_FAVICON, favicon);
2425 send.putExtra(Browser.EXTRA_SHARE_SCREENSHOT, screenshot);
2426 try {
2427 c.startActivity(Intent.createChooser(send, c.getString(
2428 R.string.choosertitle_sharevia)));
2429 } catch(android.content.ActivityNotFoundException ex) {
2430 // if no app handles it, do nothing
2431 }
2432 }
2433
Leon Scroggins89c6d362009-07-15 16:54:37 -04002434 private void updateScreenshot(WebView view) {
2435 // If this is a bookmarked site, add a screenshot to the database.
2436 // FIXME: When should we update? Every time?
2437 // FIXME: Would like to make sure there is actually something to
2438 // draw, but the API for that (WebViewCore.pictureReady()) is not
2439 // currently accessible here.
Ben Murdochaac7aa62009-09-17 16:57:40 +01002440
Ben Murdoch87cc65d2010-06-29 20:34:10 +01002441 final Bitmap bm = createScreenshot(view, getDesiredThumbnailWidth(this),
2442 getDesiredThumbnailHeight(this));
Patrick Scottcb192b52010-04-14 14:38:55 -04002443 if (bm == null) {
2444 return;
Leon Scroggins89c6d362009-07-15 16:54:37 -04002445 }
Patrick Scottcb192b52010-04-14 14:38:55 -04002446
2447 final ContentResolver cr = getContentResolver();
2448 final String url = view.getUrl();
2449 final String originalUrl = view.getOriginalUrl();
2450
2451 new AsyncTask<Void, Void, Void>() {
2452 @Override
2453 protected Void doInBackground(Void... unused) {
Jeff Hamilton1a805652010-09-07 12:36:30 -07002454 Cursor cursor = null;
Patrick Scottcb192b52010-04-14 14:38:55 -04002455 try {
Jeff Hamilton1a805652010-09-07 12:36:30 -07002456 cursor = Bookmarks.queryCombinedForUrl(cr, originalUrl, url);
2457 if (cursor != null && cursor.moveToFirst()) {
2458 final ByteArrayOutputStream os = new ByteArrayOutputStream();
2459 bm.compress(Bitmap.CompressFormat.PNG, 100, os);
2460
2461 ContentValues values = new ContentValues();
2462 values.put(Images.THUMBNAIL, os.toByteArray());
2463 values.put(Images.URL, cursor.getString(0));
2464
2465 do {
2466 cr.update(Images.CONTENT_URI, values, null, null);
2467 } while (cursor.moveToNext());
Patrick Scottcb192b52010-04-14 14:38:55 -04002468 }
2469 } catch (IllegalStateException e) {
2470 // Ignore
2471 } finally {
Jeff Hamilton1a805652010-09-07 12:36:30 -07002472 if (cursor != null) cursor.close();
Patrick Scottcb192b52010-04-14 14:38:55 -04002473 }
2474 return null;
2475 }
2476 }.execute();
Leon Scroggins89c6d362009-07-15 16:54:37 -04002477 }
2478
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002479 /**
Leon Scrogginsf8551612009-09-24 16:06:02 -04002480 * Return the desired width for thumbnail screenshots, which are stored in
2481 * the database, and used on the bookmarks screen.
2482 * @param context Context for finding out the density of the screen.
Jeff Hamiltonf3026372010-08-19 00:12:27 -05002483 * @return desired width for thumbnail screenshot.
Leon Scrogginsf8551612009-09-24 16:06:02 -04002484 */
2485 /* package */ static int getDesiredThumbnailWidth(Context context) {
Jeff Hamiltonf3026372010-08-19 00:12:27 -05002486 return context.getResources().getDimensionPixelOffset(R.dimen.bookmarkThumbnailWidth);
Leon Scrogginsf8551612009-09-24 16:06:02 -04002487 }
2488
2489 /**
2490 * Return the desired height for thumbnail screenshots, which are stored in
2491 * the database, and used on the bookmarks screen.
2492 * @param context Context for finding out the density of the screen.
Jeff Hamiltonf3026372010-08-19 00:12:27 -05002493 * @return desired height for thumbnail screenshot.
Leon Scrogginsf8551612009-09-24 16:06:02 -04002494 */
2495 /* package */ static int getDesiredThumbnailHeight(Context context) {
Jeff Hamiltonf3026372010-08-19 00:12:27 -05002496 return context.getResources().getDimensionPixelOffset(R.dimen.bookmarkThumbnailHeight);
Leon Scrogginsf8551612009-09-24 16:06:02 -04002497 }
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002498
Ben Murdoch87cc65d2010-06-29 20:34:10 +01002499 private Bitmap createScreenshot(WebView view, int width, int height) {
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002500 Picture thumbnail = view.capturePicture();
Leon Scroggins45800572009-09-29 16:38:47 -04002501 if (thumbnail == null) {
2502 return null;
2503 }
Ben Murdoch87cc65d2010-06-29 20:34:10 +01002504 Bitmap bm = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002505 Canvas canvas = new Canvas(bm);
2506 // May need to tweak these values to determine what is the
2507 // best scale factor
Ben Murdoch2694e232009-09-29 09:41:11 +01002508 int thumbnailWidth = thumbnail.getWidth();
Ben Murdochae59c3f2009-10-20 18:30:28 +01002509 int thumbnailHeight = thumbnail.getHeight();
2510 float scaleFactorX = 1.0f;
2511 float scaleFactorY = 1.0f;
Ben Murdoch2694e232009-09-29 09:41:11 +01002512 if (thumbnailWidth > 0) {
Ben Murdoch87cc65d2010-06-29 20:34:10 +01002513 scaleFactorX = (float) width / (float)thumbnailWidth;
Ben Murdochae59c3f2009-10-20 18:30:28 +01002514 } else {
2515 return null;
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002516 }
Ben Murdochae59c3f2009-10-20 18:30:28 +01002517
2518 if (view.getWidth() > view.getHeight() &&
2519 thumbnailHeight < view.getHeight() && thumbnailHeight > 0) {
2520 // If the device is in landscape and the page is shorter
2521 // than the height of the view, stretch the thumbnail to fill the
2522 // space.
Ben Murdoch87cc65d2010-06-29 20:34:10 +01002523 scaleFactorY = (float) height / (float)thumbnailHeight;
Ben Murdochae59c3f2009-10-20 18:30:28 +01002524 } else {
2525 // In the portrait case, this looks nice.
2526 scaleFactorY = scaleFactorX;
2527 }
2528
2529 canvas.scale(scaleFactorX, scaleFactorY);
2530
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002531 thumbnail.draw(canvas);
2532 return bm;
2533 }
2534
The Android Open Source Project0c908882009-03-03 19:32:16 -08002535 // -------------------------------------------------------------------------
Grace Kloba22ac16e2009-10-07 18:00:23 -07002536 // Helper function for WebViewClient.
The Android Open Source Project0c908882009-03-03 19:32:16 -08002537 //-------------------------------------------------------------------------
2538
2539 // Use in overrideUrlLoading
2540 /* package */ final static String SCHEME_WTAI = "wtai://wp/";
2541 /* package */ final static String SCHEME_WTAI_MC = "wtai://wp/mc;";
2542 /* package */ final static String SCHEME_WTAI_SD = "wtai://wp/sd;";
2543 /* package */ final static String SCHEME_WTAI_AP = "wtai://wp/ap;";
2544
Leon Scroggins92472e82010-02-17 16:32:28 -05002545 // Keep this initial progress in sync with initialProgressValue (* 100)
2546 // in ProgressTracker.cpp
2547 private final static int INITIAL_PROGRESS = 10;
2548
Grace Kloba22ac16e2009-10-07 18:00:23 -07002549 void onPageStarted(WebView view, String url, Bitmap favicon) {
2550 // when BrowserActivity just starts, onPageStarted may be called before
2551 // onResume as it is triggered from onCreate. Call resumeWebViewTimers
2552 // to start the timer. As we won't switch tabs while an activity is in
2553 // pause state, we can ensure calling resume and pause in pair.
2554 if (mActivityInPause) resumeWebViewTimers();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002555
Grace Kloba22ac16e2009-10-07 18:00:23 -07002556 resetLockIcon(url);
2557 setUrlTitle(url, null);
2558 setFavicon(favicon);
Leon Scroggins8cf8f682009-11-04 11:13:50 -08002559 // Show some progress so that the user knows the page is beginning to
2560 // load
Leon Scroggins92472e82010-02-17 16:32:28 -05002561 onProgressChanged(view, INITIAL_PROGRESS);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002562 mDidStopLoad = false;
Grace Kloba22ac16e2009-10-07 18:00:23 -07002563 if (!mIsNetworkUp) createAndShowNetworkDialog();
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04002564 endActionMode();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002565 if (mSettings.isTracing()) {
2566 String host;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002567 try {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002568 WebAddress uri = new WebAddress(url);
Bjorn Bringert131ab512010-10-12 16:25:47 +01002569 host = uri.getHost();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002570 } catch (android.net.ParseException ex) {
2571 host = "browser";
The Android Open Source Project0c908882009-03-03 19:32:16 -08002572 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002573 host = host.replace('.', '_');
2574 host += ".trace";
2575 mInTrace = true;
2576 Debug.startMethodTracing(host, 20 * 1024 * 1024);
2577 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002578
Grace Kloba22ac16e2009-10-07 18:00:23 -07002579 // Performance probe
2580 if (false) {
2581 mStart = SystemClock.uptimeMillis();
2582 mProcessStart = Process.getElapsedCpuTime();
2583 long[] sysCpu = new long[7];
2584 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2585 sysCpu, null)) {
2586 mUserStart = sysCpu[0] + sysCpu[1];
2587 mSystemStart = sysCpu[2];
2588 mIdleStart = sysCpu[3];
2589 mIrqStart = sysCpu[4] + sysCpu[5] + sysCpu[6];
2590 }
2591 mUiStart = SystemClock.currentThreadTimeMillis();
2592 }
2593 }
2594
2595 void onPageFinished(WebView view, String url) {
2596 // Reset the title and icon in case we stopped a provisional load.
2597 resetTitleAndIcon(view);
2598 // Update the lock icon image only once we are done loading
2599 updateLockIconToLatest();
2600 // pause the WebView timer and release the wake lock if it is finished
2601 // while BrowserActivity is in pause state.
2602 if (mActivityInPause && pauseWebViewTimers()) {
2603 if (mWakeLock.isHeld()) {
2604 mHandler.removeMessages(RELEASE_WAKELOCK);
2605 mWakeLock.release();
2606 }
2607 }
2608
2609 // Performance probe
2610 if (false) {
2611 long[] sysCpu = new long[7];
2612 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2613 sysCpu, null)) {
2614 String uiInfo = "UI thread used "
2615 + (SystemClock.currentThreadTimeMillis() - mUiStart)
2616 + " ms";
2617 if (LOGD_ENABLED) {
2618 Log.d(LOGTAG, uiInfo);
2619 }
2620 //The string that gets written to the log
2621 String performanceString = "It took total "
2622 + (SystemClock.uptimeMillis() - mStart)
2623 + " ms clock time to load the page."
2624 + "\nbrowser process used "
2625 + (Process.getElapsedCpuTime() - mProcessStart)
2626 + " ms, user processes used "
2627 + (sysCpu[0] + sysCpu[1] - mUserStart) * 10
2628 + " ms, kernel used "
2629 + (sysCpu[2] - mSystemStart) * 10
2630 + " ms, idle took " + (sysCpu[3] - mIdleStart) * 10
2631 + " ms and irq took "
2632 + (sysCpu[4] + sysCpu[5] + sysCpu[6] - mIrqStart)
2633 * 10 + " ms, " + uiInfo;
2634 if (LOGD_ENABLED) {
2635 Log.d(LOGTAG, performanceString + "\nWebpage: " + url);
2636 }
2637 if (url != null) {
2638 // strip the url to maintain consistency
2639 String newUrl = new String(url);
2640 if (newUrl.startsWith("http://www.")) {
2641 newUrl = newUrl.substring(11);
2642 } else if (newUrl.startsWith("http://")) {
2643 newUrl = newUrl.substring(7);
2644 } else if (newUrl.startsWith("https://www.")) {
2645 newUrl = newUrl.substring(12);
2646 } else if (newUrl.startsWith("https://")) {
2647 newUrl = newUrl.substring(8);
2648 }
2649 if (LOGD_ENABLED) {
2650 Log.d(LOGTAG, newUrl + " loaded");
2651 }
Grace Kloba5b078b52009-06-24 20:23:41 -07002652 }
2653 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002654 }
Grace Kloba5b078b52009-06-24 20:23:41 -07002655
Grace Kloba22ac16e2009-10-07 18:00:23 -07002656 if (mInTrace) {
2657 mInTrace = false;
2658 Debug.stopMethodTracing();
2659 }
2660 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002661
Grace Klobae7fe26b2010-06-28 16:23:33 -07002662 private void closeEmptyChildTab() {
2663 Tab current = mTabControl.getCurrentTab();
2664 if (current != null
2665 && current.getWebView().copyBackForwardList().getSize() == 0) {
2666 Tab parent = current.getParentTab();
2667 if (parent != null) {
2668 switchToTab(mTabControl.getTabIndex(parent));
2669 closeTab(current);
2670 }
2671 }
2672 }
2673
Grace Kloba22ac16e2009-10-07 18:00:23 -07002674 boolean shouldOverrideUrlLoading(WebView view, String url) {
Jeff Hamilton47654f42010-09-07 09:57:51 -05002675 if (view.isPrivateBrowsingEnabled()) {
2676 // Don't allow urls to leave the browser app when in private browsing mode
2677 loadUrl(view, url);
2678 return true;
2679 }
2680
Grace Kloba22ac16e2009-10-07 18:00:23 -07002681 if (url.startsWith(SCHEME_WTAI)) {
2682 // wtai://wp/mc;number
2683 // number=string(phone-number)
2684 if (url.startsWith(SCHEME_WTAI_MC)) {
2685 Intent intent = new Intent(Intent.ACTION_VIEW,
2686 Uri.parse(WebView.SCHEME_TEL +
2687 url.substring(SCHEME_WTAI_MC.length())));
2688 startActivity(intent);
Grace Klobae7fe26b2010-06-28 16:23:33 -07002689 // before leaving BrowserActivity, close the empty child tab.
2690 // If a new tab is created through JavaScript open to load this
2691 // url, we would like to close it as we will load this url in a
2692 // different Activity.
2693 closeEmptyChildTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002694 return true;
2695 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002696 // wtai://wp/sd;dtmf
2697 // dtmf=string(dialstring)
2698 if (url.startsWith(SCHEME_WTAI_SD)) {
2699 // TODO: only send when there is active voice connection
2700 return false;
2701 }
2702 // wtai://wp/ap;number;name
2703 // number=string(phone-number)
2704 // name=string
2705 if (url.startsWith(SCHEME_WTAI_AP)) {
2706 // TODO
2707 return false;
2708 }
2709 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002710
Grace Kloba22ac16e2009-10-07 18:00:23 -07002711 // The "about:" schemes are internal to the browser; don't want these to
2712 // be dispatched to other apps.
2713 if (url.startsWith("about:")) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002714 return false;
2715 }
2716
Jeff Davidson43610292010-07-16 16:03:58 -07002717 // If this is a Google search, attempt to add an RLZ string (if one isn't already present).
2718 if (rlzProviderPresent()) {
2719 Uri siteUri = Uri.parse(url);
2720 if (needsRlzString(siteUri)) {
2721 String rlz = null;
2722 Cursor cur = null;
2723 try {
2724 cur = getContentResolver().query(getRlzUri(), null, null, null, null);
2725 if (cur != null && cur.moveToFirst() && !cur.isNull(0)) {
2726 url = siteUri.buildUpon()
2727 .appendQueryParameter("rlz", cur.getString(0))
2728 .build().toString();
2729 }
2730 } finally {
2731 if (cur != null) {
2732 cur.close();
2733 }
2734 }
2735 loadUrl(view, url);
2736 return true;
2737 }
2738 }
2739
Grace Kloba22ac16e2009-10-07 18:00:23 -07002740 Intent intent;
2741 // perform generic parsing of the URI to turn it into an Intent.
2742 try {
2743 intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME);
2744 } catch (URISyntaxException ex) {
2745 Log.w("Browser", "Bad URI " + url + ": " + ex.getMessage());
2746 return false;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002747 }
2748
Grace Kloba22ac16e2009-10-07 18:00:23 -07002749 // check whether the intent can be resolved. If not, we will see
2750 // whether we can download it from the Market.
2751 if (getPackageManager().resolveActivity(intent, 0) == null) {
2752 String packagename = intent.getPackage();
2753 if (packagename != null) {
2754 intent = new Intent(Intent.ACTION_VIEW, Uri
2755 .parse("market://search?q=pname:" + packagename));
2756 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2757 startActivity(intent);
Grace Klobae7fe26b2010-06-28 16:23:33 -07002758 // before leaving BrowserActivity, close the empty child tab.
2759 // If a new tab is created through JavaScript open to load this
2760 // url, we would like to close it as we will load this url in a
2761 // different Activity.
2762 closeEmptyChildTab();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002763 return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002764 } else {
2765 return false;
2766 }
2767 }
2768
Grace Kloba22ac16e2009-10-07 18:00:23 -07002769 // sanitize the Intent, ensuring web pages can not bypass browser
2770 // security (only access to BROWSABLE activities).
2771 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2772 intent.setComponent(null);
2773 try {
2774 if (startActivityIfNeeded(intent, -1)) {
Grace Klobae7fe26b2010-06-28 16:23:33 -07002775 // before leaving BrowserActivity, close the empty child tab.
2776 // If a new tab is created through JavaScript open to load this
2777 // url, we would like to close it as we will load this url in a
2778 // different Activity.
2779 closeEmptyChildTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002780 return true;
2781 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002782 } catch (ActivityNotFoundException ex) {
2783 // ignore the error. If no application can handle the URL,
2784 // eg about:blank, assume the browser can handle it.
2785 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002786
Grace Kloba22ac16e2009-10-07 18:00:23 -07002787 if (mMenuIsDown) {
Michael Kolb68792c82010-08-09 16:39:18 -07002788 openTab(url, false);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002789 closeOptionsMenu();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002790 return true;
2791 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002792 return false;
2793 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002794
Jeff Davidson43610292010-07-16 16:03:58 -07002795 // Determine whether the RLZ provider is present on the system.
2796 private boolean rlzProviderPresent() {
2797 if (mIsProviderPresent == null) {
2798 PackageManager pm = getPackageManager();
2799 mIsProviderPresent = pm.resolveContentProvider(BrowserSettings.RLZ_PROVIDER, 0) != null;
2800 }
2801 return mIsProviderPresent;
2802 }
2803
2804 // Retrieve the RLZ access point string and cache the URI used to retrieve RLZ values.
2805 private Uri getRlzUri() {
2806 if (mRlzUri == null) {
2807 String ap = getResources().getString(R.string.rlz_access_point);
2808 mRlzUri = Uri.withAppendedPath(BrowserSettings.RLZ_PROVIDER_URI, ap);
2809 }
2810 return mRlzUri;
2811 }
2812
2813 // Determine if this URI appears to be for a Google search and does not have an RLZ parameter.
2814 // Taken largely from Chrome source, src/chrome/browser/google_url_tracker.cc
2815 private static boolean needsRlzString(Uri uri) {
Bill Napierc50e71a2010-08-27 14:03:03 -07002816 String scheme = uri.getScheme();
2817 if (("http".equals(scheme) || "https".equals(scheme)) &&
2818 (uri.getQueryParameter("q") != null) && (uri.getQueryParameter("rlz") == null)) {
Jeff Davidson43610292010-07-16 16:03:58 -07002819 String host = uri.getHost();
2820 if (host == null) {
2821 return false;
2822 }
2823 String[] hostComponents = host.split("\\.");
2824
2825 if (hostComponents.length < 2) {
2826 return false;
2827 }
2828 int googleComponent = hostComponents.length - 2;
2829 String component = hostComponents[googleComponent];
2830 if (!"google".equals(component)) {
2831 if (hostComponents.length < 3 ||
2832 (!"co".equals(component) && !"com".equals(component))) {
2833 return false;
2834 }
2835 googleComponent = hostComponents.length - 3;
2836 if (!"google".equals(hostComponents[googleComponent])) {
2837 return false;
2838 }
2839 }
2840
2841 // Google corp network handling.
2842 if (googleComponent > 0 && "corp".equals(hostComponents[googleComponent - 1])) {
2843 return false;
2844 }
2845
2846 return true;
2847 }
2848 return false;
2849 }
2850
Grace Kloba22ac16e2009-10-07 18:00:23 -07002851 // -------------------------------------------------------------------------
2852 // Helper function for WebChromeClient
2853 // -------------------------------------------------------------------------
The Android Open Source Project0c908882009-03-03 19:32:16 -08002854
Grace Kloba22ac16e2009-10-07 18:00:23 -07002855 void onProgressChanged(WebView view, int newProgress) {
Michael Kolba2b2ba82010-08-04 17:54:03 -07002856
2857 // On the phone, the fake title bar will always cover up the
2858 // regular title bar (or the regular one is offscreen), so only the
2859 // fake title bar needs to change its progress
2860 mFakeTitleBar.setProgress(newProgress);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002861
Grace Kloba22ac16e2009-10-07 18:00:23 -07002862 if (newProgress == 100) {
2863 // onProgressChanged() may continue to be called after the main
2864 // frame has finished loading, as any remaining sub frames continue
2865 // to load. We'll only get called once though with newProgress as
2866 // 100 when everything is loaded. (onPageFinished is called once
2867 // when the main frame completes loading regardless of the state of
2868 // any sub frames so calls to onProgressChanges may continue after
2869 // onPageFinished has executed)
2870 if (mInLoad) {
2871 mInLoad = false;
Leon Scrogginsa27ff192009-09-14 12:58:04 -04002872 updateInLoadMenuItems();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002873 // If the options menu is open, leave the title bar
2874 if (!mOptionsMenuOpen || !mIconView) {
2875 hideFakeTitleBar();
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07002876 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002877 }
Leon Scrogginsaa37e7f2010-03-05 11:51:20 -05002878 } else {
2879 if (!mInLoad) {
2880 // onPageFinished may have already been called but a subframe is
2881 // still loading and updating the progress. Reset mInLoad and
2882 // update the menu items.
2883 mInLoad = true;
2884 updateInLoadMenuItems();
2885 }
2886 // When the page first begins to load, the Activity may still be
2887 // paused, in which case showFakeTitleBar will do nothing. Call
2888 // again as the page continues to load so that it will be shown.
2889 // (Calling it will the fake title bar is already showing will also
2890 // do nothing.
Grace Kloba22ac16e2009-10-07 18:00:23 -07002891 if (!mOptionsMenuOpen || mIconView) {
2892 // This page has begun to load, so show the title bar
2893 showFakeTitleBar();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002894 }
2895 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002896 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002897
Grace Kloba22ac16e2009-10-07 18:00:23 -07002898 void onShowCustomView(View view, WebChromeClient.CustomViewCallback callback) {
Derek Sollenberger8ff57db2009-12-08 15:39:55 -05002899 // if a view already exists then immediately terminate the new one
2900 if (mCustomView != null) {
2901 callback.onCustomViewHidden();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002902 return;
Derek Sollenberger8ff57db2009-12-08 15:39:55 -05002903 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002904
2905 // Add the custom view to its container.
2906 mCustomViewContainer.addView(view, COVER_SCREEN_GRAVITY_CENTER);
2907 mCustomView = view;
2908 mCustomViewCallback = callback;
2909 // Save the menu state and set it to empty while the custom
2910 // view is showing.
2911 mOldMenuState = mMenuState;
2912 mMenuState = EMPTY_MENU;
2913 // Hide the content view.
2914 mContentView.setVisibility(View.GONE);
2915 // Finally show the custom view container.
Andrei Popescu163ab742009-10-20 17:58:23 +01002916 setStatusBarVisibility(false);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002917 mCustomViewContainer.setVisibility(View.VISIBLE);
2918 mCustomViewContainer.bringToFront();
2919 }
2920
2921 void onHideCustomView() {
2922 if (mCustomView == null)
2923 return;
2924
2925 // Hide the custom view.
2926 mCustomView.setVisibility(View.GONE);
2927 // Remove the custom view from its container.
2928 mCustomViewContainer.removeView(mCustomView);
2929 mCustomView = null;
2930 // Reset the old menu state.
2931 mMenuState = mOldMenuState;
2932 mOldMenuState = EMPTY_MENU;
2933 mCustomViewContainer.setVisibility(View.GONE);
2934 mCustomViewCallback.onCustomViewHidden();
2935 // Show the content view.
Andrei Popescu163ab742009-10-20 17:58:23 +01002936 setStatusBarVisibility(true);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002937 mContentView.setVisibility(View.VISIBLE);
2938 }
2939
2940 Bitmap getDefaultVideoPoster() {
2941 if (mDefaultVideoPoster == null) {
2942 mDefaultVideoPoster = BitmapFactory.decodeResource(
2943 getResources(), R.drawable.default_video_poster);
Patrick Scott3918d442009-08-04 13:22:29 -04002944 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002945 return mDefaultVideoPoster;
2946 }
Patrick Scott3918d442009-08-04 13:22:29 -04002947
Grace Kloba22ac16e2009-10-07 18:00:23 -07002948 View getVideoLoadingProgressView() {
2949 if (mVideoProgressView == null) {
2950 LayoutInflater inflater = LayoutInflater.from(BrowserActivity.this);
2951 mVideoProgressView = inflater.inflate(
2952 R.layout.video_loading_progress, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002953 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002954 return mVideoProgressView;
2955 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002956
Leon Scroggins8d5fa432009-10-02 15:55:59 -04002957 /*
2958 * The Object used to inform the WebView of the file to upload.
2959 */
2960 private ValueCallback<Uri> mUploadMessage;
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002961 private String mCameraFilePath;
Leon Scroggins8d5fa432009-10-02 15:55:59 -04002962
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002963 void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
2964
2965 final String imageMimeType = "image/*";
Ben Murdoch6af492a2010-06-15 12:38:17 +01002966 final String videoMimeType = "video/*";
Ben Murdoch039bd472010-07-21 21:26:57 +01002967 final String audioMimeType = "audio/*";
Ben Murdochb50d7402010-07-16 12:42:22 +01002968 final String mediaSourceKey = "capture";
Ben Murdoch6af492a2010-06-15 12:38:17 +01002969 final String mediaSourceValueCamera = "camera";
Ben Murdochb50d7402010-07-16 12:42:22 +01002970 final String mediaSourceValueFileSystem = "filesystem";
Ben Murdoch6af492a2010-06-15 12:38:17 +01002971 final String mediaSourceValueCamcorder = "camcorder";
Ben Murdoch039bd472010-07-21 21:26:57 +01002972 final String mediaSourceValueMicrophone = "microphone";
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002973
Ben Murdoch039bd472010-07-21 21:26:57 +01002974 // media source can be 'filesystem' or 'camera' or 'camcorder' or 'microphone'.
Ben Murdoch6af492a2010-06-15 12:38:17 +01002975 String mediaSource = "";
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002976
Ben Murdoch6af492a2010-06-15 12:38:17 +01002977 // We add the camera intent if there was no accept type (or '*/*' or 'image/*').
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002978 boolean addCameraIntent = true;
Ben Murdoch6af492a2010-06-15 12:38:17 +01002979 // We add the camcorder intent if there was no accept type (or '*/*' or 'video/*').
2980 boolean addCamcorderIntent = true;
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002981
Ben Murdoch6af492a2010-06-15 12:38:17 +01002982 if (mUploadMessage != null) {
2983 // Already a file picker operation in progress.
2984 return;
2985 }
2986
Grace Kloba22ac16e2009-10-07 18:00:23 -07002987 mUploadMessage = uploadMsg;
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002988
2989 // Parse the accept type.
2990 String params[] = acceptType.split(";");
2991 String mimeType = params[0];
2992
2993 for (String p : params) {
2994 String[] keyValue = p.split("=");
2995 if (keyValue.length == 2) {
2996 // Process key=value parameters.
Ben Murdoch6af492a2010-06-15 12:38:17 +01002997 if (mediaSourceKey.equals(keyValue[0])) {
2998 mediaSource = keyValue[1];
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002999 }
3000 }
3001 }
3002
3003 // This intent will display the standard OPENABLE file picker.
Grace Kloba22ac16e2009-10-07 18:00:23 -07003004 Intent i = new Intent(Intent.ACTION_GET_CONTENT);
3005 i.addCategory(Intent.CATEGORY_OPENABLE);
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003006
3007 // Create an intent to add to the standard file picker that will
3008 // capture an image from the camera. We'll combine this intent with
3009 // the standard OPENABLE picker unless the web developer specifically
3010 // requested the camera or gallery be opened by passing a parameter
3011 // in the accept type.
3012 Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
3013 File externalDataDir = Environment.getExternalStoragePublicDirectory(
3014 Environment.DIRECTORY_DCIM);
3015 File cameraDataDir = new File(externalDataDir.getAbsolutePath() +
3016 File.separator + "browser-photos");
3017 cameraDataDir.mkdirs();
3018 mCameraFilePath = cameraDataDir.getAbsolutePath() + File.separator +
3019 System.currentTimeMillis() + ".jpg";
3020 cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(mCameraFilePath)));
3021
Ben Murdoch6af492a2010-06-15 12:38:17 +01003022 Intent camcorderIntent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
3023
Ben Murdoch039bd472010-07-21 21:26:57 +01003024 Intent soundRecIntent = new Intent(MediaStore.Audio.Media.RECORD_SOUND_ACTION);
3025
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003026 if (mimeType.equals(imageMimeType)) {
3027 i.setType(imageMimeType);
Ben Murdoch6af492a2010-06-15 12:38:17 +01003028 addCamcorderIntent = false;
3029 if (mediaSource.equals(mediaSourceValueCamera)) {
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003030 // Specified 'image/*' and requested the camera, so go ahead and launch the camera
3031 // directly.
3032 BrowserActivity.this.startActivityForResult(cameraIntent, FILE_SELECTED);
3033 return;
Ben Murdochb50d7402010-07-16 12:42:22 +01003034 } else if (mediaSource.equals(mediaSourceValueFileSystem)) {
3035 // Specified filesytem as the source, so don't want to consider the camera.
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003036 addCameraIntent = false;
3037 }
Ben Murdoch6af492a2010-06-15 12:38:17 +01003038 } else if (mimeType.equals(videoMimeType)) {
3039 i.setType(videoMimeType);
3040 addCameraIntent = false;
3041 // The camcorder saves it's own file and returns it to us in the intent, so
3042 // we don't need to generate one here.
3043 mCameraFilePath = null;
3044
3045 if (mediaSource.equals(mediaSourceValueCamcorder)) {
Ben Murdoch039bd472010-07-21 21:26:57 +01003046 // Specified 'video/*' and requested the camcorder, so go ahead and launch the
3047 // camcorder directly.
Ben Murdoch6af492a2010-06-15 12:38:17 +01003048 BrowserActivity.this.startActivityForResult(camcorderIntent, FILE_SELECTED);
3049 return;
Ben Murdochb50d7402010-07-16 12:42:22 +01003050 } else if (mediaSource.equals(mediaSourceValueFileSystem)) {
3051 // Specified filesystem as the source, so don't want to consider the camcorder.
Ben Murdoch6af492a2010-06-15 12:38:17 +01003052 addCamcorderIntent = false;
3053 }
Ben Murdoch039bd472010-07-21 21:26:57 +01003054 } else if (mimeType.equals(audioMimeType)) {
3055 i.setType(audioMimeType);
3056 addCameraIntent = false;
3057 addCamcorderIntent = false;
3058 if (mediaSource.equals(mediaSourceValueMicrophone)) {
3059 // Specified 'audio/*' and requested microphone, so go ahead and launch the sound
3060 // recorder.
3061 BrowserActivity.this.startActivityForResult(soundRecIntent, FILE_SELECTED);
3062 return;
3063 }
3064 // On a default system, there is no single option to open an audio "gallery". Both the
3065 // sound recorder and music browser respond to the OPENABLE/audio/* intent unlike the
3066 // image/* and video/* OPENABLE intents where the image / video gallery are the only
3067 // respondants (and so the user is not prompted by default).
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003068 } else {
3069 i.setType("*/*");
3070 }
3071
Ben Murdoch6af492a2010-06-15 12:38:17 +01003072 // Combine the chooser and the extra choices (like camera or camcorder)
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003073 Intent chooser = new Intent(Intent.ACTION_CHOOSER);
3074 chooser.putExtra(Intent.EXTRA_INTENT, i);
3075
Ben Murdoch6af492a2010-06-15 12:38:17 +01003076 Vector<Intent> extraInitialIntents = new Vector<Intent>(0);
3077
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003078 if (addCameraIntent) {
Ben Murdoch6af492a2010-06-15 12:38:17 +01003079 extraInitialIntents.add(cameraIntent);
3080 }
3081
3082 if (addCamcorderIntent) {
3083 extraInitialIntents.add(camcorderIntent);
3084 }
3085
3086 if (extraInitialIntents.size() > 0) {
3087 Intent[] extraIntents = new Intent[extraInitialIntents.size()];
3088 chooser.putExtra(Intent.EXTRA_INITIAL_INTENTS, extraInitialIntents.toArray(extraIntents));
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003089 }
3090
3091 chooser.putExtra(Intent.EXTRA_TITLE, getString(R.string.choose_upload));
3092 BrowserActivity.this.startActivityForResult(chooser, FILE_SELECTED);
Grace Kloba22ac16e2009-10-07 18:00:23 -07003093 }
3094
3095 // -------------------------------------------------------------------------
3096 // Implement functions for DownloadListener
3097 // -------------------------------------------------------------------------
3098
The Android Open Source Project0c908882009-03-03 19:32:16 -08003099 /**
3100 * Notify the host application a download should be done, or that
3101 * the data should be streamed if a streaming viewer is available.
3102 * @param url The full url to the content that should be downloaded
3103 * @param contentDisposition Content-disposition http header, if
3104 * present.
3105 * @param mimetype The mimetype of the content reported by the server
3106 * @param contentLength The file size reported by the server
3107 */
3108 public void onDownloadStart(String url, String userAgent,
3109 String contentDisposition, String mimetype, long contentLength) {
3110 // if we're dealing wih A/V content that's not explicitly marked
3111 // for download, check if it's streamable.
3112 if (contentDisposition == null
Patrick Scotte1fb9662009-08-31 14:31:52 -04003113 || !contentDisposition.regionMatches(
3114 true, 0, "attachment", 0, 10)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003115 // query the package manager to see if there's a registered handler
3116 // that matches.
3117 Intent intent = new Intent(Intent.ACTION_VIEW);
3118 intent.setDataAndType(Uri.parse(url), mimetype);
Patrick Scotte1fb9662009-08-31 14:31:52 -04003119 ResolveInfo info = getPackageManager().resolveActivity(intent,
3120 PackageManager.MATCH_DEFAULT_ONLY);
3121 if (info != null) {
3122 ComponentName myName = getComponentName();
3123 // If we resolved to ourselves, we don't want to attempt to
3124 // load the url only to try and download it again.
3125 if (!myName.getPackageName().equals(
3126 info.activityInfo.packageName)
3127 || !myName.getClassName().equals(
3128 info.activityInfo.name)) {
3129 // someone (other than us) knows how to handle this mime
3130 // type with this scheme, don't download.
3131 try {
3132 startActivity(intent);
3133 return;
3134 } catch (ActivityNotFoundException ex) {
3135 if (LOGD_ENABLED) {
3136 Log.d(LOGTAG, "activity not found for " + mimetype
3137 + " over " + Uri.parse(url).getScheme(),
3138 ex);
3139 }
3140 // Best behavior is to fall back to a download in this
3141 // case
The Android Open Source Project0c908882009-03-03 19:32:16 -08003142 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003143 }
3144 }
3145 }
3146 onDownloadStartNoStream(url, userAgent, contentDisposition, mimetype, contentLength);
3147 }
3148
Kristian Monsenfa52d172010-03-25 18:29:21 +00003149 // This is to work around the fact that java.net.URI throws Exceptions
3150 // instead of just encoding URL's properly
3151 // Helper method for onDownloadStartNoStream
3152 private static String encodePath(String path) {
3153 char[] chars = path.toCharArray();
3154
3155 boolean needed = false;
3156 for (char c : chars) {
3157 if (c == '[' || c == ']') {
3158 needed = true;
3159 break;
3160 }
3161 }
3162 if (needed == false) {
3163 return path;
3164 }
3165
3166 StringBuilder sb = new StringBuilder("");
3167 for (char c : chars) {
3168 if (c == '[' || c == ']') {
3169 sb.append('%');
3170 sb.append(Integer.toHexString(c));
3171 } else {
3172 sb.append(c);
3173 }
3174 }
3175
3176 return sb.toString();
3177 }
3178
The Android Open Source Project0c908882009-03-03 19:32:16 -08003179 /**
3180 * Notify the host application a download should be done, even if there
3181 * is a streaming viewer available for thise type.
3182 * @param url The full url to the content that should be downloaded
3183 * @param contentDisposition Content-disposition http header, if
3184 * present.
3185 * @param mimetype The mimetype of the content reported by the server
3186 * @param contentLength The file size reported by the server
3187 */
3188 /*package */ void onDownloadStartNoStream(String url, String userAgent,
3189 String contentDisposition, String mimetype, long contentLength) {
3190
3191 String filename = URLUtil.guessFileName(url,
3192 contentDisposition, mimetype);
3193
3194 // Check to see if we have an SDCard
3195 String status = Environment.getExternalStorageState();
3196 if (!status.equals(Environment.MEDIA_MOUNTED)) {
3197 int title;
3198 String msg;
3199
3200 // Check to see if the SDCard is busy, same as the music app
3201 if (status.equals(Environment.MEDIA_SHARED)) {
3202 msg = getString(R.string.download_sdcard_busy_dlg_msg);
3203 title = R.string.download_sdcard_busy_dlg_title;
3204 } else {
3205 msg = getString(R.string.download_no_sdcard_dlg_msg, filename);
3206 title = R.string.download_no_sdcard_dlg_title;
3207 }
3208
3209 new AlertDialog.Builder(this)
3210 .setTitle(title)
3211 .setIcon(android.R.drawable.ic_dialog_alert)
3212 .setMessage(msg)
3213 .setPositiveButton(R.string.ok, null)
3214 .show();
3215 return;
3216 }
3217
Kristian Monsenfa52d172010-03-25 18:29:21 +00003218 // java.net.URI is a lot stricter than KURL so we have to encode some
3219 // extra characters. Fix for b 2538060 and b 1634719
3220 WebAddress webAddress;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003221 try {
Kristian Monsenfa52d172010-03-25 18:29:21 +00003222 webAddress = new WebAddress(url);
Bjorn Bringert131ab512010-10-12 16:25:47 +01003223 webAddress.setPath(encodePath(webAddress.getPath()));
The Android Open Source Project0c908882009-03-03 19:32:16 -08003224 } catch (Exception e) {
Kristian Monsenfa52d172010-03-25 18:29:21 +00003225 // This only happens for very bad urls, we want to chatch the
3226 // exception here
3227 Log.e(LOGTAG, "Exception trying to parse url:" + url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003228 return;
3229 }
3230
3231 // XXX: Have to use the old url since the cookies were stored using the
3232 // old percent-encoded url.
3233 String cookies = CookieManager.getInstance().getCookie(url);
3234
3235 ContentValues values = new ContentValues();
Kristian Monsenfa52d172010-03-25 18:29:21 +00003236 values.put(Downloads.Impl.COLUMN_URI, webAddress.toString());
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08003237 values.put(Downloads.Impl.COLUMN_COOKIE_DATA, cookies);
3238 values.put(Downloads.Impl.COLUMN_USER_AGENT, userAgent);
3239 values.put(Downloads.Impl.COLUMN_NOTIFICATION_PACKAGE,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003240 getPackageName());
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08003241 values.put(Downloads.Impl.COLUMN_NOTIFICATION_CLASS,
Leon Scrogginsa563d092010-04-19 16:53:49 -04003242 OpenDownloadReceiver.class.getCanonicalName());
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08003243 values.put(Downloads.Impl.COLUMN_VISIBILITY,
3244 Downloads.Impl.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
3245 values.put(Downloads.Impl.COLUMN_MIME_TYPE, mimetype);
3246 values.put(Downloads.Impl.COLUMN_FILE_NAME_HINT, filename);
Bjorn Bringert131ab512010-10-12 16:25:47 +01003247 values.put(Downloads.Impl.COLUMN_DESCRIPTION, webAddress.getHost());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003248 if (contentLength > 0) {
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08003249 values.put(Downloads.Impl.COLUMN_TOTAL_BYTES, contentLength);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003250 }
3251 if (mimetype == null) {
3252 // We must have long pressed on a link or image to download it. We
3253 // are not sure of the mimetype in this case, so do a head request
3254 new FetchUrlMimeType(this).execute(values);
3255 } else {
3256 final Uri contentUri =
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08003257 getContentResolver().insert(Downloads.Impl.CONTENT_URI, values);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003258 }
Leon Scroggins9191a7f2010-03-18 14:44:44 -04003259 Toast.makeText(this, R.string.download_pending, Toast.LENGTH_SHORT)
3260 .show();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003261 }
3262
Grace Kloba22ac16e2009-10-07 18:00:23 -07003263 // -------------------------------------------------------------------------
3264
The Android Open Source Project0c908882009-03-03 19:32:16 -08003265 /**
3266 * Resets the lock icon. This method is called when we start a new load and
3267 * know the url to be loaded.
3268 */
3269 private void resetLockIcon(String url) {
3270 // Save the lock-icon state (we revert to it if the load gets cancelled)
Grace Kloba22ac16e2009-10-07 18:00:23 -07003271 mTabControl.getCurrentTab().resetLockIcon(url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003272 updateLockIconImage(LOCK_ICON_UNSECURE);
3273 }
3274
The Android Open Source Project0c908882009-03-03 19:32:16 -08003275 /**
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04003276 * Update the lock icon to correspond to our latest state.
3277 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003278 private void updateLockIconToLatest() {
Leon Scroggins91f65fc2010-06-29 13:52:39 -04003279 Tab t = mTabControl.getCurrentTab();
3280 if (t != null) {
3281 updateLockIconImage(t.getLockIconType());
3282 }
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04003283 }
3284
3285 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08003286 * Updates the lock-icon image in the title-bar.
3287 */
3288 private void updateLockIconImage(int lockIconType) {
3289 Drawable d = null;
3290 if (lockIconType == LOCK_ICON_SECURE) {
3291 d = mSecLockIcon;
3292 } else if (lockIconType == LOCK_ICON_MIXED) {
3293 d = mMixLockIcon;
3294 }
Leon Scroggins68579392009-09-15 15:31:54 -04003295 mTitleBar.setLock(d);
Michael Kolba2b2ba82010-08-04 17:54:03 -07003296 mFakeTitleBar.setLock(d);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003297 }
3298
3299 /**
3300 * Displays a page-info dialog.
3301 * @param tab The tab to show info about
3302 * @param fromShowSSLCertificateOnError The flag that indicates whether
3303 * this dialog was opened from the SSL-certificate-on-error dialog or
3304 * not. This is important, since we need to know whether to return to
3305 * the parent dialog or simply dismiss.
3306 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003307 private void showPageInfo(final Tab tab,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003308 final boolean fromShowSSLCertificateOnError) {
3309 final LayoutInflater factory = LayoutInflater
3310 .from(this);
3311
3312 final View pageInfoView = factory.inflate(R.layout.page_info, null);
3313
3314 final WebView view = tab.getWebView();
3315
3316 String url = null;
3317 String title = null;
3318
3319 if (view == null) {
3320 url = tab.getUrl();
3321 title = tab.getTitle();
3322 } else if (view == mTabControl.getCurrentWebView()) {
3323 // Use the cached title and url if this is the current WebView
3324 url = mUrl;
3325 title = mTitle;
3326 } else {
3327 url = view.getUrl();
3328 title = view.getTitle();
3329 }
3330
3331 if (url == null) {
3332 url = "";
3333 }
3334 if (title == null) {
3335 title = "";
3336 }
3337
3338 ((TextView) pageInfoView.findViewById(R.id.address)).setText(url);
3339 ((TextView) pageInfoView.findViewById(R.id.title)).setText(title);
3340
3341 mPageInfoView = tab;
Leon Scrogginsc7b92f82010-01-11 18:17:31 -05003342 mPageInfoFromShowSSLCertificateOnError = fromShowSSLCertificateOnError;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003343
3344 AlertDialog.Builder alertDialogBuilder =
3345 new AlertDialog.Builder(this)
3346 .setTitle(R.string.page_info).setIcon(android.R.drawable.ic_dialog_info)
3347 .setView(pageInfoView)
3348 .setPositiveButton(
3349 R.string.ok,
3350 new DialogInterface.OnClickListener() {
3351 public void onClick(DialogInterface dialog,
3352 int whichButton) {
3353 mPageInfoDialog = null;
3354 mPageInfoView = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003355
3356 // if we came here from the SSL error dialog
3357 if (fromShowSSLCertificateOnError) {
3358 // go back to the SSL error dialog
3359 showSSLCertificateOnError(
3360 mSSLCertificateOnErrorView,
3361 mSSLCertificateOnErrorHandler,
3362 mSSLCertificateOnErrorError);
3363 }
3364 }
3365 })
3366 .setOnCancelListener(
3367 new DialogInterface.OnCancelListener() {
3368 public void onCancel(DialogInterface dialog) {
3369 mPageInfoDialog = null;
3370 mPageInfoView = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003371
3372 // if we came here from the SSL error dialog
3373 if (fromShowSSLCertificateOnError) {
3374 // go back to the SSL error dialog
3375 showSSLCertificateOnError(
3376 mSSLCertificateOnErrorView,
3377 mSSLCertificateOnErrorHandler,
3378 mSSLCertificateOnErrorError);
3379 }
3380 }
3381 });
3382
3383 // if we have a main top-level page SSL certificate set or a certificate
3384 // error
3385 if (fromShowSSLCertificateOnError ||
3386 (view != null && view.getCertificate() != null)) {
3387 // add a 'View Certificate' button
3388 alertDialogBuilder.setNeutralButton(
3389 R.string.view_certificate,
3390 new DialogInterface.OnClickListener() {
3391 public void onClick(DialogInterface dialog,
3392 int whichButton) {
3393 mPageInfoDialog = null;
3394 mPageInfoView = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003395
3396 // if we came here from the SSL error dialog
3397 if (fromShowSSLCertificateOnError) {
3398 // go back to the SSL error dialog
3399 showSSLCertificateOnError(
3400 mSSLCertificateOnErrorView,
3401 mSSLCertificateOnErrorHandler,
3402 mSSLCertificateOnErrorError);
3403 } else {
3404 // otherwise, display the top-most certificate from
3405 // the chain
3406 if (view.getCertificate() != null) {
3407 showSSLCertificate(tab);
3408 }
3409 }
3410 }
3411 });
3412 }
3413
3414 mPageInfoDialog = alertDialogBuilder.show();
3415 }
3416
3417 /**
3418 * Displays the main top-level page SSL certificate dialog
3419 * (accessible from the Page-Info dialog).
3420 * @param tab The tab to show certificate for.
3421 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003422 private void showSSLCertificate(final Tab tab) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003423 final View certificateView =
3424 inflateCertificateView(tab.getWebView().getCertificate());
3425 if (certificateView == null) {
3426 return;
3427 }
3428
3429 LayoutInflater factory = LayoutInflater.from(this);
3430
3431 final LinearLayout placeholder =
3432 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3433
3434 LinearLayout ll = (LinearLayout) factory.inflate(
3435 R.layout.ssl_success, placeholder);
3436 ((TextView)ll.findViewById(R.id.success))
3437 .setText(R.string.ssl_certificate_is_valid);
3438
3439 mSSLCertificateView = tab;
3440 mSSLCertificateDialog =
3441 new AlertDialog.Builder(this)
3442 .setTitle(R.string.ssl_certificate).setIcon(
3443 R.drawable.ic_dialog_browser_certificate_secure)
3444 .setView(certificateView)
3445 .setPositiveButton(R.string.ok,
3446 new DialogInterface.OnClickListener() {
3447 public void onClick(DialogInterface dialog,
3448 int whichButton) {
3449 mSSLCertificateDialog = null;
3450 mSSLCertificateView = null;
3451
3452 showPageInfo(tab, false);
3453 }
3454 })
3455 .setOnCancelListener(
3456 new DialogInterface.OnCancelListener() {
3457 public void onCancel(DialogInterface dialog) {
3458 mSSLCertificateDialog = null;
3459 mSSLCertificateView = null;
3460
3461 showPageInfo(tab, false);
3462 }
3463 })
3464 .show();
3465 }
3466
3467 /**
3468 * Displays the SSL error certificate dialog.
3469 * @param view The target web-view.
3470 * @param handler The SSL error handler responsible for cancelling the
3471 * connection that resulted in an SSL error or proceeding per user request.
3472 * @param error The SSL error object.
3473 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003474 void showSSLCertificateOnError(
The Android Open Source Project0c908882009-03-03 19:32:16 -08003475 final WebView view, final SslErrorHandler handler, final SslError error) {
3476
3477 final View certificateView =
3478 inflateCertificateView(error.getCertificate());
3479 if (certificateView == null) {
3480 return;
3481 }
3482
3483 LayoutInflater factory = LayoutInflater.from(this);
3484
3485 final LinearLayout placeholder =
3486 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3487
3488 if (error.hasError(SslError.SSL_UNTRUSTED)) {
3489 LinearLayout ll = (LinearLayout)factory
3490 .inflate(R.layout.ssl_warning, placeholder);
3491 ((TextView)ll.findViewById(R.id.warning))
3492 .setText(R.string.ssl_untrusted);
3493 }
3494
3495 if (error.hasError(SslError.SSL_IDMISMATCH)) {
3496 LinearLayout ll = (LinearLayout)factory
3497 .inflate(R.layout.ssl_warning, placeholder);
3498 ((TextView)ll.findViewById(R.id.warning))
3499 .setText(R.string.ssl_mismatch);
3500 }
3501
3502 if (error.hasError(SslError.SSL_EXPIRED)) {
3503 LinearLayout ll = (LinearLayout)factory
3504 .inflate(R.layout.ssl_warning, placeholder);
3505 ((TextView)ll.findViewById(R.id.warning))
3506 .setText(R.string.ssl_expired);
3507 }
3508
3509 if (error.hasError(SslError.SSL_NOTYETVALID)) {
3510 LinearLayout ll = (LinearLayout)factory
3511 .inflate(R.layout.ssl_warning, placeholder);
3512 ((TextView)ll.findViewById(R.id.warning))
3513 .setText(R.string.ssl_not_yet_valid);
3514 }
3515
3516 mSSLCertificateOnErrorHandler = handler;
3517 mSSLCertificateOnErrorView = view;
3518 mSSLCertificateOnErrorError = error;
3519 mSSLCertificateOnErrorDialog =
3520 new AlertDialog.Builder(this)
3521 .setTitle(R.string.ssl_certificate).setIcon(
3522 R.drawable.ic_dialog_browser_certificate_partially_secure)
3523 .setView(certificateView)
3524 .setPositiveButton(R.string.ok,
3525 new DialogInterface.OnClickListener() {
3526 public void onClick(DialogInterface dialog,
3527 int whichButton) {
3528 mSSLCertificateOnErrorDialog = null;
3529 mSSLCertificateOnErrorView = null;
3530 mSSLCertificateOnErrorHandler = null;
3531 mSSLCertificateOnErrorError = null;
3532
Grace Kloba22ac16e2009-10-07 18:00:23 -07003533 view.getWebViewClient().onReceivedSslError(
3534 view, handler, error);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003535 }
3536 })
3537 .setNeutralButton(R.string.page_info_view,
3538 new DialogInterface.OnClickListener() {
3539 public void onClick(DialogInterface dialog,
3540 int whichButton) {
3541 mSSLCertificateOnErrorDialog = null;
3542
3543 // do not clear the dialog state: we will
3544 // need to show the dialog again once the
3545 // user is done exploring the page-info details
3546
3547 showPageInfo(mTabControl.getTabFromView(view),
3548 true);
3549 }
3550 })
3551 .setOnCancelListener(
3552 new DialogInterface.OnCancelListener() {
3553 public void onCancel(DialogInterface dialog) {
3554 mSSLCertificateOnErrorDialog = null;
3555 mSSLCertificateOnErrorView = null;
3556 mSSLCertificateOnErrorHandler = null;
3557 mSSLCertificateOnErrorError = null;
3558
Grace Kloba22ac16e2009-10-07 18:00:23 -07003559 view.getWebViewClient().onReceivedSslError(
3560 view, handler, error);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003561 }
3562 })
3563 .show();
3564 }
3565
3566 /**
3567 * Inflates the SSL certificate view (helper method).
3568 * @param certificate The SSL certificate.
3569 * @return The resultant certificate view with issued-to, issued-by,
3570 * issued-on, expires-on, and possibly other fields set.
3571 * If the input certificate is null, returns null.
3572 */
3573 private View inflateCertificateView(SslCertificate certificate) {
3574 if (certificate == null) {
3575 return null;
3576 }
3577
3578 LayoutInflater factory = LayoutInflater.from(this);
3579
3580 View certificateView = factory.inflate(
3581 R.layout.ssl_certificate, null);
3582
3583 // issued to:
3584 SslCertificate.DName issuedTo = certificate.getIssuedTo();
3585 if (issuedTo != null) {
3586 ((TextView) certificateView.findViewById(R.id.to_common))
3587 .setText(issuedTo.getCName());
3588 ((TextView) certificateView.findViewById(R.id.to_org))
3589 .setText(issuedTo.getOName());
3590 ((TextView) certificateView.findViewById(R.id.to_org_unit))
3591 .setText(issuedTo.getUName());
3592 }
3593
3594 // issued by:
3595 SslCertificate.DName issuedBy = certificate.getIssuedBy();
3596 if (issuedBy != null) {
3597 ((TextView) certificateView.findViewById(R.id.by_common))
3598 .setText(issuedBy.getCName());
3599 ((TextView) certificateView.findViewById(R.id.by_org))
3600 .setText(issuedBy.getOName());
3601 ((TextView) certificateView.findViewById(R.id.by_org_unit))
3602 .setText(issuedBy.getUName());
3603 }
3604
3605 // issued on:
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003606 String issuedOn = formatCertificateDate(
3607 certificate.getValidNotBeforeDate());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003608 ((TextView) certificateView.findViewById(R.id.issued_on))
3609 .setText(issuedOn);
3610
3611 // expires on:
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003612 String expiresOn = formatCertificateDate(
3613 certificate.getValidNotAfterDate());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003614 ((TextView) certificateView.findViewById(R.id.expires_on))
3615 .setText(expiresOn);
3616
3617 return certificateView;
3618 }
3619
3620 /**
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003621 * Formats the certificate date to a properly localized date string.
The Android Open Source Project0c908882009-03-03 19:32:16 -08003622 * @return Properly localized version of the certificate date string and
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003623 * the "" if it fails to localize.
The Android Open Source Project0c908882009-03-03 19:32:16 -08003624 */
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003625 private String formatCertificateDate(Date certificateDate) {
3626 if (certificateDate == null) {
3627 return "";
The Android Open Source Project0c908882009-03-03 19:32:16 -08003628 }
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003629 String formattedDate = DateFormat.getDateFormat(this).format(certificateDate);
3630 if (formattedDate == null) {
3631 return "";
3632 }
3633 return formattedDate;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003634 }
3635
3636 /**
3637 * Displays an http-authentication dialog.
3638 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003639 void showHttpAuthentication(final HttpAuthHandler handler,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003640 final String host, final String realm, final String title,
3641 final String name, final String password, int focusId) {
3642 LayoutInflater factory = LayoutInflater.from(this);
3643 final View v = factory
3644 .inflate(R.layout.http_authentication, null);
3645 if (name != null) {
3646 ((EditText) v.findViewById(R.id.username_edit)).setText(name);
3647 }
3648 if (password != null) {
3649 ((EditText) v.findViewById(R.id.password_edit)).setText(password);
3650 }
3651
3652 String titleText = title;
3653 if (titleText == null) {
3654 titleText = getText(R.string.sign_in_to).toString().replace(
3655 "%s1", host).replace("%s2", realm);
3656 }
3657
3658 mHttpAuthHandler = handler;
3659 AlertDialog dialog = new AlertDialog.Builder(this)
3660 .setTitle(titleText)
3661 .setIcon(android.R.drawable.ic_dialog_alert)
3662 .setView(v)
3663 .setPositiveButton(R.string.action,
3664 new DialogInterface.OnClickListener() {
3665 public void onClick(DialogInterface dialog,
3666 int whichButton) {
3667 String nm = ((EditText) v
3668 .findViewById(R.id.username_edit))
3669 .getText().toString();
3670 String pw = ((EditText) v
3671 .findViewById(R.id.password_edit))
3672 .getText().toString();
3673 BrowserActivity.this.setHttpAuthUsernamePassword
3674 (host, realm, nm, pw);
3675 handler.proceed(nm, pw);
3676 mHttpAuthenticationDialog = null;
3677 mHttpAuthHandler = null;
3678 }})
3679 .setNegativeButton(R.string.cancel,
3680 new DialogInterface.OnClickListener() {
3681 public void onClick(DialogInterface dialog,
3682 int whichButton) {
3683 handler.cancel();
3684 BrowserActivity.this.resetTitleAndRevertLockIcon();
3685 mHttpAuthenticationDialog = null;
3686 mHttpAuthHandler = null;
3687 }})
3688 .setOnCancelListener(new DialogInterface.OnCancelListener() {
3689 public void onCancel(DialogInterface dialog) {
3690 handler.cancel();
3691 BrowserActivity.this.resetTitleAndRevertLockIcon();
3692 mHttpAuthenticationDialog = null;
3693 mHttpAuthHandler = null;
3694 }})
3695 .create();
3696 // Make the IME appear when the dialog is displayed if applicable.
3697 dialog.getWindow().setSoftInputMode(
3698 WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
3699 dialog.show();
3700 if (focusId != 0) {
3701 dialog.findViewById(focusId).requestFocus();
3702 } else {
3703 v.findViewById(R.id.username_edit).requestFocus();
3704 }
3705 mHttpAuthenticationDialog = dialog;
3706 }
3707
3708 public int getProgress() {
3709 WebView w = mTabControl.getCurrentWebView();
3710 if (w != null) {
3711 return w.getProgress();
3712 } else {
3713 return 100;
3714 }
3715 }
3716
3717 /**
3718 * Set HTTP authentication password.
3719 *
3720 * @param host The host for the password
3721 * @param realm The realm for the password
3722 * @param username The username for the password. If it is null, it means
3723 * password can't be saved.
3724 * @param password The password
3725 */
3726 public void setHttpAuthUsernamePassword(String host, String realm,
3727 String username,
3728 String password) {
Steve Block95a53b22010-03-25 17:24:58 +00003729 WebView w = getTopWindow();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003730 if (w != null) {
3731 w.setHttpAuthUsernamePassword(host, realm, username, password);
3732 }
3733 }
3734
3735 /**
3736 * connectivity manager says net has come or gone... inform the user
3737 * @param up true if net has come up, false if net has gone down
3738 */
3739 public void onNetworkToggle(boolean up) {
3740 if (up == mIsNetworkUp) {
3741 return;
3742 } else if (up) {
3743 mIsNetworkUp = true;
3744 if (mAlertDialog != null) {
3745 mAlertDialog.cancel();
3746 mAlertDialog = null;
3747 }
3748 } else {
3749 mIsNetworkUp = false;
Patrick Scotteb6ab2a2009-09-16 10:00:17 -04003750 if (mInLoad) {
3751 createAndShowNetworkDialog();
3752 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003753 }
3754 WebView w = mTabControl.getCurrentWebView();
3755 if (w != null) {
3756 w.setNetworkAvailable(up);
3757 }
3758 }
3759
Grace Kloba22ac16e2009-10-07 18:00:23 -07003760 boolean isNetworkUp() {
3761 return mIsNetworkUp;
3762 }
3763
Patrick Scotteb6ab2a2009-09-16 10:00:17 -04003764 // This method shows the network dialog alerting the user that the net is
3765 // down. It will only show the dialog if mAlertDialog is null.
3766 private void createAndShowNetworkDialog() {
3767 if (mAlertDialog == null) {
3768 mAlertDialog = new AlertDialog.Builder(this)
3769 .setTitle(R.string.loadSuspendedTitle)
3770 .setMessage(R.string.loadSuspended)
3771 .setPositiveButton(R.string.ok, null)
3772 .show();
3773 }
3774 }
3775
Michael Kolbe421c242010-10-04 19:29:01 -07003776 /**
3777 * callback from ComboPage when bookmark/history selection
3778 */
3779 @Override
3780 public void onUrlSelected(String url, boolean newTab) {
3781 removeComboView();
3782 if (!TextUtils.isEmpty(url)) {
3783 if (newTab) {
3784 openTab(url, false);
3785 } else {
3786 final Tab currentTab = mTabControl.getCurrentTab();
3787 dismissSubWindow(currentTab);
3788 loadUrl(getTopWindow(), url);
3789 }
3790 }
3791 }
3792
3793 /**
3794 * callback from ComboPage when dismissed
3795 */
3796 @Override
3797 public void onComboCanceled() {
3798 removeComboView();
3799 }
3800
3801 /**
3802 * dismiss the ComboPage
3803 */
3804 /* package */ void removeComboView() {
3805 if (mComboView != null) {
3806 mContentView.removeView(mComboView);
3807 mTitleBar.setVisibility(View.VISIBLE);
3808 mMenuState = R.id.MAIN_MENU;
3809 attachTabToContentView(mTabControl.getCurrentTab());
3810 getTopWindow().requestFocus();
3811 mComboView = null;
3812 }
3813 }
3814
3815 /**
3816 * callback from ComboPage when clear history is requested
3817 */
3818 public void onRemoveParentChildRelationships() {
3819 mTabControl.removeParentChildRelationShips();
3820 }
3821
The Android Open Source Project0c908882009-03-03 19:32:16 -08003822 @Override
3823 protected void onActivityResult(int requestCode, int resultCode,
3824 Intent intent) {
Grace Klobabb394f32009-11-19 10:26:37 -08003825 if (getTopWindow() == null) return;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003826 switch (requestCode) {
Leon Scrogginsfde97462010-01-11 13:06:21 -05003827 case PREFERENCES_PAGE:
3828 if (resultCode == RESULT_OK && intent != null) {
3829 String action = intent.getStringExtra(Intent.EXTRA_TEXT);
3830 if (BrowserSettings.PREF_CLEAR_HISTORY.equals(action)) {
3831 mTabControl.removeParentChildRelationShips();
3832 }
3833 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003834 break;
Leon Scroggins8d5fa432009-10-02 15:55:59 -04003835 // Choose a file from the file picker.
3836 case FILE_SELECTED:
3837 if (null == mUploadMessage) break;
3838 Uri result = intent == null || resultCode != RESULT_OK ? null
3839 : intent.getData();
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003840
3841 // As we ask the camera to save the result of the user taking
3842 // a picture, the camera application does not return anything other
3843 // than RESULT_OK. So we need to check whether the file we expected
3844 // was written to disk in the in the case that we
3845 // did not get an intent returned but did get a RESULT_OK. If it was,
3846 // we assume that this result has came back from the camera.
3847 if (result == null && intent == null && resultCode == RESULT_OK) {
3848 File cameraFile = new File(mCameraFilePath);
3849 if (cameraFile.exists()) {
3850 result = Uri.fromFile(cameraFile);
Ben Murdoch07d34732010-05-27 18:34:46 +01003851 // Broadcast to the media scanner that we have a new photo
3852 // so it will be added into the gallery for the user.
3853 sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, result));
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003854 }
3855 }
Leon Scroggins8d5fa432009-10-02 15:55:59 -04003856 mUploadMessage.onReceiveValue(result);
3857 mUploadMessage = null;
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003858 mCameraFilePath = null;
Leon Scroggins8d5fa432009-10-02 15:55:59 -04003859 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003860 default:
3861 break;
3862 }
Leon Scroggins30444232009-09-04 18:36:20 -04003863 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003864 }
3865
3866 /*
3867 * This method is called as a result of the user selecting the options
Leon Scrogginsf08809b2010-01-21 09:27:46 -05003868 * menu to see the download window. It shows the download window on top of
3869 * the current window.
The Android Open Source Project0c908882009-03-03 19:32:16 -08003870 */
Leon Scroggins IIIa682a3c2010-09-27 12:32:40 -04003871 private void viewDownloads() {
3872 Intent intent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
3873 startActivity(intent);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003874 }
3875
Michael Kolbc7485ae2010-09-03 10:10:58 -07003876 /* package */ void promptAddOrInstallBookmark(View anchor) {
3877 PopupMenu popup = new PopupMenu(this, anchor);
3878 popup.getMenuInflater().inflate(R.menu.bookmark_shortcut, popup.getMenu());
3879 popup.setOnMenuItemClickListener(this);
3880 popup.show();
3881 }
Michael Kolbebba8b42010-09-30 12:57:59 -07003882
Michael Kolbc7485ae2010-09-03 10:10:58 -07003883 /**
3884 * popup menu item click listener
3885 * @param item
3886 */
3887 public boolean onMenuItemClick(MenuItem item) {
3888 switch(item.getItemId()) {
3889 case R.id.add_bookmark_menu_id:
Michael Kolb370a4f32010-10-06 10:45:32 -07003890 bookmarkCurrentPage(AddBookmarkPage.DEFAULT_FOLDER_ID);
Michael Kolbc7485ae2010-09-03 10:10:58 -07003891 return true;
3892 case R.id.shortcut_to_home_menu_id:
3893 Tab current = mTabControl.getCurrentTab();
3894 current.populatePickerData();
3895 String touchIconUrl = mTabControl.getCurrentWebView().getTouchIconUrl();
3896 if (touchIconUrl != null) {
3897 // Download the touch icon for this site then save
3898 // it to the
3899 // homescreen.
3900 Bundle b = new Bundle();
3901 b.putString("url", current.getUrl());
3902 b.putString("title", current.getTitle());
3903 b.putParcelable("favicon", current.getFavicon());
3904 Message msg = mHandler.obtainMessage(TOUCH_ICON_DOWNLOADED);
3905 msg.setData(b);
3906 new DownloadTouchIcon(BrowserActivity.this, msg,
3907 mTabControl.getCurrentWebView().getSettings().getUserAgentString())
3908 .execute(touchIconUrl);
3909 } else {
3910 // add to homescreen, can do it immediately as there
3911 // is no touch
3912 // icon.
3913 showSaveToHomescreenDialog(
3914 current.getUrl(), current.getTitle(), null, current.getFavicon());
3915 }
3916 return true;
3917 default:
3918 return false;
3919 }
3920 }
Michael Kolbebba8b42010-09-30 12:57:59 -07003921
Michael Kolbc7485ae2010-09-03 10:10:58 -07003922 /* package */Dialog makeAddOrInstallDialog() {
Ben Murdocheecb4e62010-07-06 16:30:38 +01003923 final Tab current = mTabControl.getCurrentTab();
3924 Resources resources = getResources();
Michael Kolbc7485ae2010-09-03 10:10:58 -07003925 CharSequence[] choices =
3926 {resources.getString(R.string.save_to_bookmarks),
3927 resources.getString(R.string.create_shortcut_bookmark)};
Ben Murdocheecb4e62010-07-06 16:30:38 +01003928
3929 AlertDialog.Builder builder = new AlertDialog.Builder(this);
3930 builder.setTitle(R.string.add_new_bookmark);
3931 builder.setItems(choices, new DialogInterface.OnClickListener() {
Michael Kolbc7485ae2010-09-03 10:10:58 -07003932 public void onClick(DialogInterface dialog, int item) {
3933 if (item == 0) {
Michael Kolb370a4f32010-10-06 10:45:32 -07003934 bookmarkCurrentPage(AddBookmarkPage.DEFAULT_FOLDER_ID);
Michael Kolbc7485ae2010-09-03 10:10:58 -07003935 } else if (item == 1) {
3936 }
3937 }
Ben Murdocheecb4e62010-07-06 16:30:38 +01003938 });
Michael Kolbc7485ae2010-09-03 10:10:58 -07003939 return builder.create();
Ben Murdocheecb4e62010-07-06 16:30:38 +01003940 }
3941
Leon Scroggins160a7e72009-08-14 18:28:01 -04003942 /**
3943 * Open the Go page.
3944 * @param startWithHistory If true, open starting on the history tab.
3945 * Otherwise, start with the bookmarks tab.
Leon Scroggins160a7e72009-08-14 18:28:01 -04003946 */
Michael Kolbe421c242010-10-04 19:29:01 -07003947 /* package */ void bookmarksOrHistoryPicker(boolean startWithHistory) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003948 WebView current = mTabControl.getCurrentWebView();
3949 if (current == null) {
3950 return;
3951 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003952 String title = current.getTitle();
3953 String url = current.getUrl();
Ben Murdoch87cc65d2010-06-29 20:34:10 +01003954 Bitmap thumbnail = createScreenshot(current, getDesiredThumbnailWidth(this),
3955 getDesiredThumbnailHeight(this));
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01003956
The Android Open Source Project0c908882009-03-03 19:32:16 -08003957 // Just in case the user opens bookmarks before a page finishes loading
3958 // so the current history item, and therefore the page, is null.
3959 if (null == url) {
3960 url = mLastEnteredUrl;
3961 // This can happen.
3962 if (null == url) {
3963 url = mSettings.getHomePage();
3964 }
3965 }
3966 // In case the web page has not yet received its associated title.
3967 if (title == null) {
3968 title = url;
3969 }
Michael Kolbe421c242010-10-04 19:29:01 -07003970 Bundle extras = new Bundle();
3971 extras.putString("title", title);
3972 extras.putString("url", url);
3973 extras.putParcelable("thumbnail", thumbnail);
Leon Scroggins30444232009-09-04 18:36:20 -04003974 // Disable opening in a new window if we have maxed out the windows
Michael Kolbe421c242010-10-04 19:29:01 -07003975 extras.putBoolean("disable_new_window", !mTabControl.canCreateNewTab());
3976 extras.putString("touch_icon_url", current.getTouchIconUrl());
3977
3978 mComboView = new CombinedBookmarkHistoryView(this,
3979 startWithHistory ? CombinedBookmarkHistoryView.FRAGMENT_ID_HISTORY
3980 : CombinedBookmarkHistoryView.FRAGMENT_ID_BOOKMARKS,
3981 extras);
3982 removeTabFromContentView(mTabControl.getCurrentTab());
3983 mTitleBar.setVisibility(View.GONE);
3984 hideFakeTitleBar();
3985 mContentView.addView(mComboView, COVER_SCREEN_PARAMS);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003986 }
3987
Ben Murdocheecb4e62010-07-06 16:30:38 +01003988 private void showSaveToHomescreenDialog(String url, String title, Bitmap touchIcon,
3989 Bitmap favicon) {
3990 Intent intent = new Intent(this, SaveToHomescreenDialog.class);
3991
3992 // Just in case the user tries to save before a page finishes loading
3993 // so the current history item, and therefore the page, is null.
3994 if (null == url) {
3995 url = mLastEnteredUrl;
3996 // This can happen.
3997 if (null == url) {
3998 url = mSettings.getHomePage();
3999 }
4000 }
4001
4002 // In case the web page has not yet received its associated title.
4003 if (title == null) {
4004 title = url;
4005 }
4006
4007 intent.putExtra("title", title);
4008 intent.putExtra("url", url);
4009 intent.putExtra("favicon", favicon);
4010 intent.putExtra("touchIcon", touchIcon);
4011 startActivity(intent);
4012 }
4013
The Android Open Source Project0c908882009-03-03 19:32:16 -08004014 // Called when loading from context menu or LOAD_URL message
Leon Scroggins92472e82010-02-17 16:32:28 -05004015 private void loadUrlFromContext(WebView view, String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08004016 // In case the user enters nothing.
4017 if (url != null && url.length() != 0 && view != null) {
4018 url = smartUrlFilter(url);
Grace Kloba22ac16e2009-10-07 18:00:23 -07004019 if (!view.getWebViewClient().shouldOverrideUrlLoading(view, url)) {
Leon Scroggins92472e82010-02-17 16:32:28 -05004020 loadUrl(view, url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004021 }
4022 }
4023 }
4024
Leon Scroggins92472e82010-02-17 16:32:28 -05004025 /**
4026 * Load the URL into the given WebView and update the title bar
4027 * to reflect the new load. Call this instead of WebView.loadUrl
4028 * directly.
4029 * @param view The WebView used to load url.
4030 * @param url The URL to load.
4031 */
4032 private void loadUrl(WebView view, String url) {
4033 updateTitleBarForNewLoad(view, url);
4034 view.loadUrl(url);
4035 }
4036
4037 /**
4038 * Load UrlData into a Tab and update the title bar to reflect the new
4039 * load. Call this instead of UrlData.loadIn directly.
4040 * @param t The Tab used to load.
4041 * @param data The UrlData being loaded.
4042 */
4043 private void loadUrlDataIn(Tab t, UrlData data) {
4044 updateTitleBarForNewLoad(t.getWebView(), data.mUrl);
4045 data.loadIn(t);
4046 }
4047
4048 /**
4049 * If the WebView is the top window, update the title bar to reflect
4050 * loading the new URL. i.e. set its text, clear the favicon (which
4051 * will be set once the page begins loading), and set the progress to
4052 * INITIAL_PROGRESS to show that the page has begun to load. Called
4053 * by loadUrl and loadUrlDataIn.
4054 * @param view The WebView that is starting a load.
4055 * @param url The URL that is being loaded.
4056 */
4057 private void updateTitleBarForNewLoad(WebView view, String url) {
4058 if (view == getTopWindow()) {
4059 setUrlTitle(url, null);
4060 setFavicon(null);
4061 onProgressChanged(view, INITIAL_PROGRESS);
4062 }
4063 }
4064
The Android Open Source Project0c908882009-03-03 19:32:16 -08004065 private String smartUrlFilter(Uri inUri) {
4066 if (inUri != null) {
4067 return smartUrlFilter(inUri.toString());
4068 }
4069 return null;
4070 }
4071
Feng Qianb34f87a2009-03-24 21:27:26 -07004072 protected static final Pattern ACCEPTED_URI_SCHEMA = Pattern.compile(
The Android Open Source Project0c908882009-03-03 19:32:16 -08004073 "(?i)" + // switch on case insensitive matching
4074 "(" + // begin group for schema
4075 "(?:http|https|file):\\/\\/" +
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004076 "|(?:inline|data|about|content|javascript):" +
The Android Open Source Project0c908882009-03-03 19:32:16 -08004077 ")" +
4078 "(.*)" );
4079
4080 /**
4081 * Attempts to determine whether user input is a URL or search
4082 * terms. Anything with a space is passed to search.
4083 *
4084 * Converts to lowercase any mistakenly uppercased schema (i.e.,
4085 * "Http://" converts to "http://"
4086 *
4087 * @return Original or modified URL
4088 *
4089 */
4090 String smartUrlFilter(String url) {
4091
4092 String inUrl = url.trim();
4093 boolean hasSpace = inUrl.indexOf(' ') != -1;
4094
4095 Matcher matcher = ACCEPTED_URI_SCHEMA.matcher(inUrl);
4096 if (matcher.matches()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08004097 // force scheme to lowercase
4098 String scheme = matcher.group(1);
4099 String lcScheme = scheme.toLowerCase();
4100 if (!lcScheme.equals(scheme)) {
Mitsuru Oshima123ecfb2009-05-18 19:11:14 -07004101 inUrl = lcScheme + matcher.group(2);
4102 }
4103 if (hasSpace) {
4104 inUrl = inUrl.replace(" ", "%20");
The Android Open Source Project0c908882009-03-03 19:32:16 -08004105 }
4106 return inUrl;
4107 }
Leon Scroggins956cf012010-10-07 13:51:57 -04004108 if (!hasSpace) {
Dan Egnor5ee906c2009-11-18 12:11:49 -08004109 if (Patterns.WEB_URL.matcher(inUrl).matches()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08004110 return URLUtil.guessUrl(inUrl);
4111 }
4112 }
4113
Leon Scroggins956cf012010-10-07 13:51:57 -04004114 // FIXME: Is this the correct place to add to searches?
4115 // what if someone else calls this function?
4116
The Android Open Source Project0c908882009-03-03 19:32:16 -08004117 Browser.addSearchUrl(mResolver, inUrl);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07004118 return URLUtil.composeSearchUrl(inUrl, QuickSearch_G, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004119 }
4120
Ben Murdochbff2d602009-07-01 20:19:05 +01004121 /* package */ void setShouldShowErrorConsole(boolean flag) {
4122 if (flag == mShouldShowErrorConsole) {
4123 // Nothing to do.
4124 return;
4125 }
Leon Scroggins IIIa9e35b62010-09-16 15:30:15 -04004126 Tab t = mTabControl.getCurrentTab();
4127 if (t == null) {
4128 // There is no current tab so we cannot toggle the error console
4129 return;
4130 }
Ben Murdochbff2d602009-07-01 20:19:05 +01004131
4132 mShouldShowErrorConsole = flag;
4133
Leon Scroggins IIIa9e35b62010-09-16 15:30:15 -04004134 ErrorConsoleView errorConsole = t.getErrorConsole(true);
Ben Murdochbff2d602009-07-01 20:19:05 +01004135
4136 if (flag) {
4137 // Setting the show state of the console will cause it's the layout to be inflated.
4138 if (errorConsole.numberOfErrors() > 0) {
4139 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
4140 } else {
4141 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
4142 }
4143
4144 // Now we can add it to the main view.
4145 mErrorConsoleContainer.addView(errorConsole,
Romain Guy15b8ec62010-01-08 15:06:43 -08004146 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
Ben Murdochbff2d602009-07-01 20:19:05 +01004147 ViewGroup.LayoutParams.WRAP_CONTENT));
4148 } else {
4149 mErrorConsoleContainer.removeView(errorConsole);
4150 }
4151
4152 }
4153
Grace Kloba22ac16e2009-10-07 18:00:23 -07004154 boolean shouldShowErrorConsole() {
4155 return mShouldShowErrorConsole;
4156 }
4157
Andrei Popescu163ab742009-10-20 17:58:23 +01004158 private void setStatusBarVisibility(boolean visible) {
4159 int flag = visible ? 0 : WindowManager.LayoutParams.FLAG_FULLSCREEN;
4160 getWindow().setFlags(flag, WindowManager.LayoutParams.FLAG_FULLSCREEN);
4161 }
4162
Andrei Popescu56199cc2010-01-12 22:39:16 +00004163
4164 private void sendNetworkType(String type, String subtype) {
4165 WebView w = mTabControl.getCurrentWebView();
4166 if (w != null) {
4167 w.setNetworkType(type, subtype);
4168 }
4169 }
4170
Grace Klobaeb6eef42009-09-15 17:56:32 -07004171 final static int LOCK_ICON_UNSECURE = 0;
4172 final static int LOCK_ICON_SECURE = 1;
4173 final static int LOCK_ICON_MIXED = 2;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004174
The Android Open Source Project0c908882009-03-03 19:32:16 -08004175 private BrowserSettings mSettings;
4176 private TabControl mTabControl;
4177 private ContentResolver mResolver;
4178 private FrameLayout mContentView;
Andrei Popescuadc008d2009-06-26 14:11:30 +01004179 private View mCustomView;
4180 private FrameLayout mCustomViewContainer;
Andrei Popescuc9b55562009-07-07 10:51:15 +01004181 private WebChromeClient.CustomViewCallback mCustomViewCallback;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004182
4183 // FIXME, temp address onPrepareMenu performance problem. When we move everything out of
4184 // view, we should rewrite this.
4185 private int mCurrentMenuState = 0;
4186 private int mMenuState = R.id.MAIN_MENU;
Andrei Popescuadc008d2009-06-26 14:11:30 +01004187 private int mOldMenuState = EMPTY_MENU;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004188 private static final int EMPTY_MENU = -1;
4189 private Menu mMenu;
4190
The Android Open Source Project0c908882009-03-03 19:32:16 -08004191 // Used to prevent chording to result in firing two shortcuts immediately
4192 // one after another. Fixes bug 1211714.
4193 boolean mCanChord;
4194
4195 private boolean mInLoad;
4196 private boolean mIsNetworkUp;
Ben Murdochb7cc8b42009-09-28 10:59:09 +01004197 private boolean mDidStopLoad;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004198
Cary Clark1f10cbf2010-03-22 11:45:23 -04004199 /* package */ boolean mActivityInPause = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004200
4201 private boolean mMenuIsDown;
4202
The Android Open Source Project0c908882009-03-03 19:32:16 -08004203 private static boolean mInTrace;
4204
4205 // Performance probe
4206 private static final int[] SYSTEM_CPU_FORMAT = new int[] {
4207 Process.PROC_SPACE_TERM | Process.PROC_COMBINE,
4208 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 1: user time
4209 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 2: nice time
4210 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 3: sys time
4211 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 4: idle time
4212 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 5: iowait time
4213 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 6: irq time
4214 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG // 7: softirq time
4215 };
4216
4217 private long mStart;
4218 private long mProcessStart;
4219 private long mUserStart;
4220 private long mSystemStart;
4221 private long mIdleStart;
4222 private long mIrqStart;
4223
4224 private long mUiStart;
4225
4226 private Drawable mMixLockIcon;
4227 private Drawable mSecLockIcon;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004228
4229 /* hold a ref so we can auto-cancel if necessary */
4230 private AlertDialog mAlertDialog;
4231
The Android Open Source Project0c908882009-03-03 19:32:16 -08004232 // The up-to-date URL and title (these can be different from those stored
4233 // in WebView, since it takes some time for the information in WebView to
4234 // get updated)
4235 private String mUrl;
4236 private String mTitle;
4237
4238 // As PageInfo has different style for landscape / portrait, we have
4239 // to re-open it when configuration changed
4240 private AlertDialog mPageInfoDialog;
Grace Kloba22ac16e2009-10-07 18:00:23 -07004241 private Tab mPageInfoView;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004242 // If the Page-Info dialog is launched from the SSL-certificate-on-error
4243 // dialog, we should not just dismiss it, but should get back to the
4244 // SSL-certificate-on-error dialog. This flag is used to store this state
Leon Scrogginsc7b92f82010-01-11 18:17:31 -05004245 private boolean mPageInfoFromShowSSLCertificateOnError;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004246
4247 // as SSLCertificateOnError has different style for landscape / portrait,
4248 // we have to re-open it when configuration changed
4249 private AlertDialog mSSLCertificateOnErrorDialog;
4250 private WebView mSSLCertificateOnErrorView;
4251 private SslErrorHandler mSSLCertificateOnErrorHandler;
4252 private SslError mSSLCertificateOnErrorError;
4253
4254 // as SSLCertificate has different style for landscape / portrait, we
4255 // have to re-open it when configuration changed
4256 private AlertDialog mSSLCertificateDialog;
Grace Kloba22ac16e2009-10-07 18:00:23 -07004257 private Tab mSSLCertificateView;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004258
4259 // as HttpAuthentication has different style for landscape / portrait, we
4260 // have to re-open it when configuration changed
4261 private AlertDialog mHttpAuthenticationDialog;
4262 private HttpAuthHandler mHttpAuthHandler;
4263
4264 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_PARAMS =
4265 new FrameLayout.LayoutParams(
Romain Guy15b8ec62010-01-08 15:06:43 -08004266 ViewGroup.LayoutParams.MATCH_PARENT,
4267 ViewGroup.LayoutParams.MATCH_PARENT);
Andrei Popescuadc008d2009-06-26 14:11:30 +01004268 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_GRAVITY_CENTER =
4269 new FrameLayout.LayoutParams(
Romain Guy15b8ec62010-01-08 15:06:43 -08004270 ViewGroup.LayoutParams.MATCH_PARENT,
4271 ViewGroup.LayoutParams.MATCH_PARENT,
Andrei Popescuadc008d2009-06-26 14:11:30 +01004272 Gravity.CENTER);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07004273 // Google search
4274 final static String QuickSearch_G = "http://www.google.com/m?q=%s";
The Android Open Source Project0c908882009-03-03 19:32:16 -08004275
4276 final static String QUERY_PLACE_HOLDER = "%s";
4277
4278 // "source" parameter for Google search through search key
4279 final static String GOOGLE_SEARCH_SOURCE_SEARCHKEY = "browser-key";
4280 // "source" parameter for Google search through goto menu
4281 final static String GOOGLE_SEARCH_SOURCE_GOTO = "browser-goto";
4282 // "source" parameter for Google search through simplily type
4283 final static String GOOGLE_SEARCH_SOURCE_TYPE = "browser-type";
4284 // "source" parameter for Google search suggested by the browser
4285 final static String GOOGLE_SEARCH_SOURCE_SUGGEST = "browser-suggest";
4286 // "source" parameter for Google search from unknown source
4287 final static String GOOGLE_SEARCH_SOURCE_UNKNOWN = "unknown";
4288
4289 private final static String LOGTAG = "browser";
4290
The Android Open Source Project0c908882009-03-03 19:32:16 -08004291 private String mLastEnteredUrl;
4292
4293 private PowerManager.WakeLock mWakeLock;
4294 private final static int WAKELOCK_TIMEOUT = 5 * 60 * 1000; // 5 minutes
4295
4296 private Toast mStopToast;
4297
Leon Scroggins571b3762010-05-26 10:25:01 -04004298 private TitleBarBase mTitleBar;
Michael Kolba2b2ba82010-08-04 17:54:03 -07004299 private TabBar mTabBar;
Leon Scroggins81db3662009-06-04 17:45:11 -04004300
Ben Murdochbff2d602009-07-01 20:19:05 +01004301 private LinearLayout mErrorConsoleContainer = null;
4302 private boolean mShouldShowErrorConsole = false;
4303
The Android Open Source Project0c908882009-03-03 19:32:16 -08004304 // As the ids are dynamically created, we can't guarantee that they will
4305 // be in sequence, so this static array maps ids to a window number.
4306 final static private int[] WINDOW_SHORTCUT_ID_ARRAY =
4307 { R.id.window_one_menu_id, R.id.window_two_menu_id, R.id.window_three_menu_id,
4308 R.id.window_four_menu_id, R.id.window_five_menu_id, R.id.window_six_menu_id,
4309 R.id.window_seven_menu_id, R.id.window_eight_menu_id };
4310
4311 // monitor platform changes
4312 private IntentFilter mNetworkStateChangedFilter;
4313 private BroadcastReceiver mNetworkStateIntentReceiver;
4314
Bjorn Bringerta7611812010-03-24 11:12:02 +00004315 private SystemAllowGeolocationOrigins mSystemAllowGeolocationOrigins;
4316
The Android Open Source Project0c908882009-03-03 19:32:16 -08004317 // activity requestCode
Nicolas Roard78a98e42009-05-11 13:34:17 +01004318 final static int PREFERENCES_PAGE = 3;
Leon Scroggins8d5fa432009-10-02 15:55:59 -04004319 final static int FILE_SELECTED = 4;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004320
Andrei Popescu540035d2009-09-18 18:59:20 +01004321 // the default <video> poster
4322 private Bitmap mDefaultVideoPoster;
4323 // the video progress view
4324 private View mVideoProgressView;
4325
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004326 /**
4327 * A UrlData class to abstract how the content will be set to WebView.
4328 * This base class uses loadUrl to show the content.
4329 */
Leon Scroggins6eac63e2010-03-15 18:19:14 -04004330 /* package */ static class UrlData {
Grace Kloba068e48b2010-01-26 18:11:27 -08004331 final String mUrl;
4332 final Map<String, String> mHeaders;
Leon Scroggins58d56c62010-01-28 15:12:40 -05004333 final Intent mVoiceIntent;
Grace Kloba60e095c2009-06-16 11:50:55 -07004334
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004335 UrlData(String url) {
4336 this.mUrl = url;
Grace Kloba068e48b2010-01-26 18:11:27 -08004337 this.mHeaders = null;
Leon Scroggins58d56c62010-01-28 15:12:40 -05004338 this.mVoiceIntent = null;
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004339 }
Grace Kloba60e095c2009-06-16 11:50:55 -07004340
Leon Scroggins58d56c62010-01-28 15:12:40 -05004341 UrlData(String url, Map<String, String> headers, Intent intent) {
Grace Kloba068e48b2010-01-26 18:11:27 -08004342 this.mUrl = url;
4343 this.mHeaders = headers;
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -05004344 if (RecognizerResultsIntent.ACTION_VOICE_SEARCH_RESULTS
4345 .equals(intent.getAction())) {
Leon Scroggins58d56c62010-01-28 15:12:40 -05004346 this.mVoiceIntent = intent;
4347 } else {
4348 this.mVoiceIntent = null;
4349 }
Grace Kloba60e095c2009-06-16 11:50:55 -07004350 }
4351
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004352 boolean isEmpty() {
Leon Scroggins58d56c62010-01-28 15:12:40 -05004353 return mVoiceIntent == null && (mUrl == null || mUrl.length() == 0);
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004354 }
4355
Leon Scroggins92472e82010-02-17 16:32:28 -05004356 /**
4357 * Load this UrlData into the given Tab. Use loadUrlDataIn to update
4358 * the title bar as well.
4359 */
Leon Scroggins58d56c62010-01-28 15:12:40 -05004360 public void loadIn(Tab t) {
4361 if (mVoiceIntent != null) {
4362 t.activateVoiceSearchMode(mVoiceIntent);
4363 } else {
4364 t.getWebView().loadUrl(mUrl, mHeaders);
4365 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004366 }
4367 };
4368
Leon Scroggins1f005d32009-08-10 17:36:42 -04004369 /* package */ static final UrlData EMPTY_URL_DATA = new UrlData(null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004370}