blob: 590235c380cbf7df2eae17b75e8f0fbfeb6102db [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();
523 } else {
524 mSettings.toggleDebugSettings();
525 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800526 return;
527 }
Leon Scroggins1f005d32009-08-10 17:36:42 -0400528 // Get rid of the subwindow if it exists
529 dismissSubWindow(current);
Leon Scroggins8588d152010-04-15 11:01:53 -0400530 // If the current Tab is being used as an application tab,
531 // remove the association, since the new Intent means that it is
532 // no longer associated with that application.
533 current.setAppId(null);
Patrick Scott9d53da02010-02-19 10:19:01 -0500534 loadUrlDataIn(current, urlData);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800535 }
536 }
537 }
538
Satish Sampath565505b2009-05-29 15:37:27 +0100539 /**
540 * Launches the default web search activity with the query parameters if the given intent's data
541 * are identified as plain search terms and not URLs/shortcuts.
542 * @return true if the intent was handled and web search activity was launched, false if not.
543 */
544 private boolean handleWebSearchIntent(Intent intent) {
545 if (intent == null) return false;
546
547 String url = null;
548 final String action = intent.getAction();
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -0500549 if (RecognizerResultsIntent.ACTION_VOICE_SEARCH_RESULTS.equals(
550 action)) {
Leon Scroggins58d56c62010-01-28 15:12:40 -0500551 return false;
552 }
Satish Sampath565505b2009-05-29 15:37:27 +0100553 if (Intent.ACTION_VIEW.equals(action)) {
Grace Kloba1e705052009-09-29 13:13:36 -0700554 Uri data = intent.getData();
555 if (data != null) url = data.toString();
Satish Sampath565505b2009-05-29 15:37:27 +0100556 } else if (Intent.ACTION_SEARCH.equals(action)
557 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
558 || Intent.ACTION_WEB_SEARCH.equals(action)) {
559 url = intent.getStringExtra(SearchManager.QUERY);
560 }
Bjorn Bringert04851702009-09-22 10:36:01 +0100561 return handleWebSearchRequest(url, intent.getBundleExtra(SearchManager.APP_DATA),
562 intent.getStringExtra(SearchManager.EXTRA_DATA_KEY));
Satish Sampath565505b2009-05-29 15:37:27 +0100563 }
564
565 /**
566 * Launches the default web search activity with the query parameters if the given url string
567 * was identified as plain search terms and not URL/shortcut.
568 * @return true if the request was handled and web search activity was launched, false if not.
569 */
Bjorn Bringert04851702009-09-22 10:36:01 +0100570 private boolean handleWebSearchRequest(String inUrl, Bundle appData, String extraData) {
Satish Sampath565505b2009-05-29 15:37:27 +0100571 if (inUrl == null) return false;
572
573 // In general, we shouldn't modify URL from Intent.
574 // But currently, we get the user-typed URL from search box as well.
575 String url = fixUrl(inUrl).trim();
576
Leon Scroggins956cf012010-10-07 13:51:57 -0400577 // URLs are handled by the regular flow of control, so
Satish Sampath565505b2009-05-29 15:37:27 +0100578 // return early.
Dan Egnor5ee906c2009-11-18 12:11:49 -0800579 if (Patterns.WEB_URL.matcher(url).matches()
Leon Scroggins956cf012010-10-07 13:51:57 -0400580 || ACCEPTED_URI_SCHEMA.matcher(url).matches()) {
Satish Sampath565505b2009-05-29 15:37:27 +0100581 return false;
582 }
583
Leon Scroggins8d06e362010-03-24 14:45:57 -0400584 final ContentResolver cr = mResolver;
585 final String newUrl = url;
Elliott Slaughter627d96f2010-08-18 16:35:30 -0700586 if (mTabControl == null || !mTabControl.getCurrentWebView().isPrivateBrowsingEnabled()) {
Elliott Slaughterf0f03952010-07-14 18:10:36 -0700587 new AsyncTask<Void, Void, Void>() {
588 @Override
589 protected Void doInBackground(Void... unused) {
590 Browser.updateVisitedHistory(cr, newUrl, false);
591 Browser.addSearchUrl(cr, newUrl);
592 return null;
593 }
594 }.execute();
595 }
Satish Sampath565505b2009-05-29 15:37:27 +0100596
Bjorn Bringertd69f51d2010-09-13 14:06:41 +0100597 SearchEngine searchEngine = mSettings.getSearchEngine();
598 if (searchEngine == null) return false;
599 searchEngine.startSearch(this, url, appData, extraData);
Satish Sampath565505b2009-05-29 15:37:27 +0100600
601 return true;
602 }
603
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700604 private UrlData getUrlDataFromIntent(Intent intent) {
Leon Scroggins58d56c62010-01-28 15:12:40 -0500605 String url = "";
Grace Kloba068e48b2010-01-26 18:11:27 -0800606 Map<String, String> headers = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800607 if (intent != null) {
608 final String action = intent.getAction();
609 if (Intent.ACTION_VIEW.equals(action)) {
610 url = smartUrlFilter(intent.getData());
611 if (url != null && url.startsWith("content:")) {
612 /* Append mimetype so webview knows how to display */
613 String mimeType = intent.resolveType(getContentResolver());
614 if (mimeType != null) {
615 url += "?" + mimeType;
616 }
617 }
Grace Kloba068e48b2010-01-26 18:11:27 -0800618 if (url != null && url.startsWith("http")) {
Grace Kloba00f54c52010-01-27 14:53:51 -0800619 final Bundle pairs = intent
620 .getBundleExtra(Browser.EXTRA_HEADERS);
Grace Kloba2d508ed2010-01-28 11:39:15 -0800621 if (pairs != null && !pairs.isEmpty()) {
Grace Kloba00f54c52010-01-27 14:53:51 -0800622 Iterator<String> iter = pairs.keySet().iterator();
Grace Kloba068e48b2010-01-26 18:11:27 -0800623 headers = new HashMap<String, String>();
Grace Kloba00f54c52010-01-27 14:53:51 -0800624 while (iter.hasNext()) {
625 String key = iter.next();
626 headers.put(key, pairs.getString(key));
Grace Kloba068e48b2010-01-26 18:11:27 -0800627 }
628 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700629 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800630 } else if (Intent.ACTION_SEARCH.equals(action)
631 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
632 || Intent.ACTION_WEB_SEARCH.equals(action)) {
633 url = intent.getStringExtra(SearchManager.QUERY);
634 if (url != null) {
635 mLastEnteredUrl = url;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800636 // In general, we shouldn't modify URL from Intent.
637 // But currently, we get the user-typed URL from search box as well.
638 url = fixUrl(url);
639 url = smartUrlFilter(url);
Leon Scroggins8d06e362010-03-24 14:45:57 -0400640 final ContentResolver cr = mResolver;
641 final String newUrl = url;
Elliott Slaughter8389e992010-08-20 15:44:08 -0700642 if (mTabControl == null
643 || mTabControl.getCurrentWebView() == null
644 || !mTabControl.getCurrentWebView().isPrivateBrowsingEnabled()) {
645 new AsyncTask<Void, Void, Void>() {
646 @Override
647 protected Void doInBackground(Void... unused) {
648 Browser.updateVisitedHistory(cr, newUrl, false);
649 return null;
650 }
651 }.execute();
652 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800653 String searchSource = "&source=android-" + GOOGLE_SEARCH_SOURCE_SUGGEST + "&";
654 if (url.contains(searchSource)) {
655 String source = null;
656 final Bundle appData = intent.getBundleExtra(SearchManager.APP_DATA);
657 if (appData != null) {
Bjorn Bringert10d1cca2010-02-10 14:22:12 +0000658 source = appData.getString(Search.SOURCE);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800659 }
660 if (TextUtils.isEmpty(source)) {
661 source = GOOGLE_SEARCH_SOURCE_UNKNOWN;
662 }
663 url = url.replace(searchSource, "&source=android-"+source+"&");
664 }
665 }
666 }
667 }
Leon Scroggins58d56c62010-01-28 15:12:40 -0500668 return new UrlData(url, headers, intent);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800669 }
Leon Scroggins58d56c62010-01-28 15:12:40 -0500670 /* package */ void showVoiceTitleBar(String title) {
671 mTitleBar.setInVoiceMode(true);
Leon Scroggins58d56c62010-01-28 15:12:40 -0500672 mTitleBar.setDisplayTitle(title);
Michael Kolba2b2ba82010-08-04 17:54:03 -0700673 mFakeTitleBar.setInVoiceMode(true);
674 mFakeTitleBar.setDisplayTitle(title);
Leon Scroggins58d56c62010-01-28 15:12:40 -0500675 }
676 /* package */ void revertVoiceTitleBar() {
677 mTitleBar.setInVoiceMode(false);
Leon Scroggins003a5dd2010-03-10 12:13:14 -0500678 mTitleBar.setDisplayTitle(mUrl);
Michael Kolba2b2ba82010-08-04 17:54:03 -0700679 mFakeTitleBar.setInVoiceMode(false);
680 mFakeTitleBar.setDisplayTitle(mUrl);
Leon Scroggins58d56c62010-01-28 15:12:40 -0500681 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800682 /* package */ static String fixUrl(String inUrl) {
Cary Clark652ff872009-09-10 13:34:44 -0400683 // FIXME: Converting the url to lower case
684 // duplicates functionality in smartUrlFilter().
685 // However, changing all current callers of fixUrl to
686 // call smartUrlFilter in addition may have unwanted
687 // consequences, and is deferred for now.
688 int colon = inUrl.indexOf(':');
689 boolean allLower = true;
690 for (int index = 0; index < colon; index++) {
691 char ch = inUrl.charAt(index);
692 if (!Character.isLetter(ch)) {
693 break;
694 }
695 allLower &= Character.isLowerCase(ch);
696 if (index == colon - 1 && !allLower) {
697 inUrl = inUrl.substring(0, colon).toLowerCase()
698 + inUrl.substring(colon);
699 }
700 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800701 if (inUrl.startsWith("http://") || inUrl.startsWith("https://"))
702 return inUrl;
703 if (inUrl.startsWith("http:") ||
704 inUrl.startsWith("https:")) {
705 if (inUrl.startsWith("http:/") || inUrl.startsWith("https:/")) {
706 inUrl = inUrl.replaceFirst("/", "//");
707 } else inUrl = inUrl.replaceFirst(":", "://");
708 }
709 return inUrl;
710 }
711
Grace Kloba22ac16e2009-10-07 18:00:23 -0700712 @Override
713 protected void onResume() {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800714 super.onResume();
Dave Bort31a6d1c2009-04-13 15:56:49 -0700715 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800716 Log.v(LOGTAG, "BrowserActivity.onResume: this=" + this);
717 }
718
719 if (!mActivityInPause) {
720 Log.e(LOGTAG, "BrowserActivity is already resumed.");
721 return;
722 }
723
Mike Reed7bfa63b2009-05-28 11:08:32 -0400724 mTabControl.resumeCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800725 mActivityInPause = false;
Mike Reed7bfa63b2009-05-28 11:08:32 -0400726 resumeWebViewTimers();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800727
728 if (mWakeLock.isHeld()) {
729 mHandler.removeMessages(RELEASE_WAKELOCK);
730 mWakeLock.release();
731 }
732
The Android Open Source Project0c908882009-03-03 19:32:16 -0800733 registerReceiver(mNetworkStateIntentReceiver,
734 mNetworkStateChangedFilter);
735 WebView.enablePlatformNotifications();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800736 }
737
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400738 /**
739 * Since the actual title bar is embedded in the WebView, and removing it
Leon Scrogginsfe87bd32009-10-06 10:10:00 -0400740 * would change its appearance, use a different TitleBar to show overlayed
741 * at the top of the screen, when the menu is open or the page is loading.
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400742 */
Michael Kolba2b2ba82010-08-04 17:54:03 -0700743 private TitleBarBase mFakeTitleBar;
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400744
745 /**
746 * Keeps track of whether the options menu is open. This is important in
747 * determining whether to show or hide the title bar overlay.
748 */
749 private boolean mOptionsMenuOpen;
750
751 /**
752 * Only meaningful when mOptionsMenuOpen is true. This variable keeps track
753 * of whether the configuration has changed. The first onMenuOpened call
754 * after a configuration change is simply a reopening of the same menu
755 * (i.e. mIconView did not change).
756 */
757 private boolean mConfigChanged;
758
759 /**
760 * Whether or not the options menu is in its smaller, icon menu form. When
761 * true, we want the title bar overlay to be up. When false, we do not.
762 * Only meaningful if mOptionsMenuOpen is true.
763 */
764 private boolean mIconView;
765
Leon Scrogginsa81a7642009-08-31 17:05:41 -0400766 @Override
767 public boolean onMenuOpened(int featureId, Menu menu) {
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400768 if (Window.FEATURE_OPTIONS_PANEL == featureId) {
769 if (mOptionsMenuOpen) {
770 if (mConfigChanged) {
771 // We do not need to make any changes to the state of the
772 // title bar, since the only thing that happened was a
773 // change in orientation
774 mConfigChanged = false;
775 } else {
776 if (mIconView) {
777 // Switching the menu to expanded view, so hide the
778 // title bar.
779 hideFakeTitleBar();
780 mIconView = false;
781 } else {
782 // Switching the menu back to icon view, so show the
783 // title bar once again.
784 showFakeTitleBar();
785 mIconView = true;
786 }
787 }
788 } else {
789 // The options menu is closed, so open it, and show the title
790 showFakeTitleBar();
791 mOptionsMenuOpen = true;
792 mConfigChanged = false;
793 mIconView = true;
794 }
795 }
Leon Scrogginsa81a7642009-08-31 17:05:41 -0400796 return true;
797 }
798
Michael Kolba2b2ba82010-08-04 17:54:03 -0700799 void showFakeTitleBar() {
800 if (!isFakeTitleBarShowing() && mActiveTabsPage == null && !mActivityInPause) {
Grace Kloba847c25b2010-03-30 16:00:26 -0700801 WebView mainView = mTabControl.getCurrentWebView();
802 // if there is no current WebView, don't show the faked title bar;
Grace Kloba65190702010-04-02 23:37:26 -0700803 if (mainView == null) {
Cary Clarka0464552009-09-29 13:00:45 -0400804 return;
805 }
Leon Scroggins79e36d92010-04-29 16:01:46 +0100806 // Do not need to check for null, since the current tab will have
807 // at least a main WebView, or we would have returned above.
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -0400808 if (isInCustomActionMode()) {
809 // Do not show the fake title bar, while a custom ActionMode
810 // (i.e. find or select) is showing.
Leon Scroggins79e36d92010-04-29 16:01:46 +0100811 return;
812 }
Michael Kolba2b2ba82010-08-04 17:54:03 -0700813 if (mXLargeScreenSize) {
814 mContentView.addView(mFakeTitleBar);
815 mTabBar.onShowTitleBar();
816 } else {
817 WindowManager manager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400818
Michael Kolba2b2ba82010-08-04 17:54:03 -0700819 // Add the title bar to the window manager so it can receive
820 // touches
821 // while the menu is up
822 WindowManager.LayoutParams params =
823 new WindowManager.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
824 ViewGroup.LayoutParams.WRAP_CONTENT,
825 WindowManager.LayoutParams.TYPE_APPLICATION,
826 WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
827 PixelFormat.TRANSLUCENT);
828 params.gravity = Gravity.TOP;
829 boolean atTop = mainView.getScrollY() == 0;
830 params.windowAnimations = atTop ? 0 : R.style.TitleBar;
831 manager.addView(mFakeTitleBar, params);
832 }
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400833 }
834 }
835
836 @Override
837 public void onOptionsMenuClosed(Menu menu) {
838 mOptionsMenuOpen = false;
Leon Scrogginsa27ff192009-09-14 12:58:04 -0400839 if (!mInLoad) {
840 hideFakeTitleBar();
841 } else if (!mIconView) {
842 // The page is currently loading, and we are in expanded mode, so
843 // we were not showing the menu. Show it once again. It will be
844 // removed when the page finishes.
845 showFakeTitleBar();
846 }
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400847 }
Grace Kloba22ac16e2009-10-07 18:00:23 -0700848
Michael Kolba2b2ba82010-08-04 17:54:03 -0700849 void stopScrolling() {
850 ((ScrollWebView) mTabControl.getCurrentWebView()).stopScroll();
851 }
852
853 void hideFakeTitleBar() {
854 if (!isFakeTitleBarShowing()) return;
855 if (mXLargeScreenSize) {
856 mContentView.removeView(mFakeTitleBar);
857 mTabBar.onHideTitleBar();
858 } else {
859 WindowManager.LayoutParams params =
860 (WindowManager.LayoutParams) mFakeTitleBar.getLayoutParams();
861 WebView mainView = mTabControl.getCurrentWebView();
862 // Although we decided whether or not to animate based on the
863 // current
864 // scroll position, the scroll position may have changed since the
865 // fake title bar was displayed. Make sure it has the appropriate
866 // animation/lack thereof before removing.
867 params.windowAnimations =
868 mainView != null && mainView.getScrollY() == 0 ? 0 : R.style.TitleBar;
869 WindowManager manager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
870 manager.updateViewLayout(mFakeTitleBar, params);
871 manager.removeView(mFakeTitleBar);
872 }
873 }
874
875 boolean isFakeTitleBarShowing() {
876 return (mFakeTitleBar.getParent() != null);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400877 }
878
The Android Open Source Project0c908882009-03-03 19:32:16 -0800879 /**
Leon Scrogginsc6fa1102009-09-21 10:40:01 -0400880 * Special method for the fake title bar to call when displaying its context
881 * menu, since it is in its own Window, and its parent does not show a
882 * context menu.
883 */
884 /* package */ void showTitleBarContextMenu() {
Cary Clark65f4a3c2009-09-28 17:05:06 -0400885 if (null == mTitleBar.getParent()) {
886 return;
887 }
Leon Scrogginsc6fa1102009-09-21 10:40:01 -0400888 openContextMenu(mTitleBar);
889 }
890
Leon Scrogginsb2b19f52009-10-09 16:10:00 -0400891 @Override
892 public void onContextMenuClosed(Menu menu) {
893 super.onContextMenuClosed(menu);
894 if (mInLoad) {
895 showFakeTitleBar();
896 }
897 }
898
Leon Scrogginsc6fa1102009-09-21 10:40:01 -0400899 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -0800900 * onSaveInstanceState(Bundle map)
901 * onSaveInstanceState is called right before onStop(). The map contains
902 * the saved state.
903 */
Grace Kloba22ac16e2009-10-07 18:00:23 -0700904 @Override
905 protected void onSaveInstanceState(Bundle outState) {
Dave Bort31a6d1c2009-04-13 15:56:49 -0700906 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800907 Log.v(LOGTAG, "BrowserActivity.onSaveInstanceState: this=" + this);
908 }
909 // the default implementation requires each view to have an id. As the
910 // browser handles the state itself and it doesn't use id for the views,
911 // don't call the default implementation. Otherwise it will trigger the
912 // warning like this, "couldn't save which view has focus because the
913 // focused view XXX has no id".
914
915 // Save all the tabs
916 mTabControl.saveState(outState);
Elliott Slaughter3d6df162010-08-25 13:17:44 -0700917
918 // Save time so that we know how old incognito tabs (if any) are.
919 outState.putSerializable("lastActiveDate", Calendar.getInstance());
The Android Open Source Project0c908882009-03-03 19:32:16 -0800920 }
921
Grace Kloba22ac16e2009-10-07 18:00:23 -0700922 @Override
923 protected void onPause() {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800924 super.onPause();
925
926 if (mActivityInPause) {
927 Log.e(LOGTAG, "BrowserActivity is already paused.");
928 return;
929 }
930
Mike Reed7bfa63b2009-05-28 11:08:32 -0400931 mTabControl.pauseCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800932 mActivityInPause = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -0400933 if (mTabControl.getCurrentIndex() >= 0 && !pauseWebViewTimers()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800934 mWakeLock.acquire();
935 mHandler.sendMessageDelayed(mHandler
936 .obtainMessage(RELEASE_WAKELOCK), WAKELOCK_TIMEOUT);
937 }
938
Leon Scrogginsa2ab6a72009-09-11 11:49:52 -0400939 // FIXME: This removes the active tabs page and resets the menu to
940 // MAIN_MENU. A better solution might be to do this work in onNewIntent
941 // but then we would need to save it in onSaveInstanceState and restore
942 // it in onCreate/onRestoreInstanceState
943 if (mActiveTabsPage != null) {
944 removeActiveTabPage(true);
945 }
946
The Android Open Source Project0c908882009-03-03 19:32:16 -0800947 cancelStopToast();
948
949 // unregister network state listener
950 unregisterReceiver(mNetworkStateIntentReceiver);
951 WebView.disablePlatformNotifications();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800952 }
953
Grace Kloba22ac16e2009-10-07 18:00:23 -0700954 @Override
955 protected void onDestroy() {
Dave Bort31a6d1c2009-04-13 15:56:49 -0700956 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800957 Log.v(LOGTAG, "BrowserActivity.onDestroy: this=" + this);
958 }
959 super.onDestroy();
Grace Kloba0923d692009-09-23 21:37:25 -0700960
Leon Scroggins8d5fa432009-10-02 15:55:59 -0400961 if (mUploadMessage != null) {
962 mUploadMessage.onReceiveValue(null);
963 mUploadMessage = null;
964 }
965
Grace Kloba0923d692009-09-23 21:37:25 -0700966 if (mTabControl == null) return;
967
Grace Kloba1fc98a32009-10-21 13:23:08 -0700968 // Remove the fake title bar if it is there
969 hideFakeTitleBar();
970
The Android Open Source Project0c908882009-03-03 19:32:16 -0800971 // Remove the current tab and sub window
Grace Kloba22ac16e2009-10-07 18:00:23 -0700972 Tab t = mTabControl.getCurrentTab();
Patrick Scottfb5e77f2009-04-08 19:17:37 -0700973 if (t != null) {
974 dismissSubWindow(t);
975 removeTabFromContentView(t);
976 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800977 // Destroy all the tabs
978 mTabControl.destroy();
979 WebIconDatabase.getInstance().close();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800980
Bjorn Bringerta7611812010-03-24 11:12:02 +0000981 // Stop watching the default geolocation permissions
982 mSystemAllowGeolocationOrigins.stop();
983 mSystemAllowGeolocationOrigins = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800984 }
985
986 @Override
987 public void onConfigurationChanged(Configuration newConfig) {
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400988 mConfigChanged = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800989 super.onConfigurationChanged(newConfig);
990
991 if (mPageInfoDialog != null) {
992 mPageInfoDialog.dismiss();
993 showPageInfo(
994 mPageInfoView,
Leon Scrogginsc7b92f82010-01-11 18:17:31 -0500995 mPageInfoFromShowSSLCertificateOnError);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800996 }
997 if (mSSLCertificateDialog != null) {
998 mSSLCertificateDialog.dismiss();
999 showSSLCertificate(
1000 mSSLCertificateView);
1001 }
1002 if (mSSLCertificateOnErrorDialog != null) {
1003 mSSLCertificateOnErrorDialog.dismiss();
1004 showSSLCertificateOnError(
1005 mSSLCertificateOnErrorView,
1006 mSSLCertificateOnErrorHandler,
1007 mSSLCertificateOnErrorError);
1008 }
1009 if (mHttpAuthenticationDialog != null) {
1010 String title = ((TextView) mHttpAuthenticationDialog
1011 .findViewById(com.android.internal.R.id.alertTitle)).getText()
1012 .toString();
1013 String name = ((TextView) mHttpAuthenticationDialog
1014 .findViewById(R.id.username_edit)).getText().toString();
1015 String password = ((TextView) mHttpAuthenticationDialog
1016 .findViewById(R.id.password_edit)).getText().toString();
1017 int focusId = mHttpAuthenticationDialog.getCurrentFocus()
1018 .getId();
1019 mHttpAuthenticationDialog.dismiss();
1020 showHttpAuthentication(mHttpAuthHandler, null, null, title,
1021 name, password, focusId);
1022 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001023 }
1024
Grace Kloba22ac16e2009-10-07 18:00:23 -07001025 @Override
1026 public void onLowMemory() {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001027 super.onLowMemory();
1028 mTabControl.freeMemory();
1029 }
1030
Cary Clarkff4d92c2010-03-25 11:17:03 -04001031 private void resumeWebViewTimers() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001032 Tab tab = mTabControl.getCurrentTab();
Cary Clarkff4d92c2010-03-25 11:17:03 -04001033 if (tab == null) return; // monkey can trigger this
Grace Kloba22ac16e2009-10-07 18:00:23 -07001034 boolean inLoad = tab.inLoad();
1035 if ((!mActivityInPause && !inLoad) || (mActivityInPause && inLoad)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001036 CookieSyncManager.getInstance().startSync();
Grace Kloba22ac16e2009-10-07 18:00:23 -07001037 WebView w = tab.getWebView();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001038 if (w != null) {
1039 w.resumeTimers();
1040 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001041 }
1042 }
1043
Mike Reed7bfa63b2009-05-28 11:08:32 -04001044 private boolean pauseWebViewTimers() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001045 Tab tab = mTabControl.getCurrentTab();
1046 boolean inLoad = tab.inLoad();
1047 if (mActivityInPause && !inLoad) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001048 CookieSyncManager.getInstance().stopSync();
1049 WebView w = mTabControl.getCurrentWebView();
1050 if (w != null) {
1051 w.pauseTimers();
1052 }
1053 return true;
1054 } else {
1055 return false;
1056 }
1057 }
1058
The Android Open Source Project0c908882009-03-03 19:32:16 -08001059 // Open the icon database and retain all the icons for visited sites.
1060 private void retainIconsOnStartup() {
1061 final WebIconDatabase db = WebIconDatabase.getInstance();
1062 db.open(getDir("icons", 0).getPath());
Leon Scroggins2c0f6112010-03-12 18:09:39 -05001063 Cursor c = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001064 try {
Leon Scroggins2c0f6112010-03-12 18:09:39 -05001065 c = Browser.getAllBookmarks(mResolver);
1066 if (c.moveToFirst()) {
1067 int urlIndex = c.getColumnIndex(Browser.BookmarkColumns.URL);
1068 do {
1069 String url = c.getString(urlIndex);
1070 db.retainIconForPageUrl(url);
1071 } while (c.moveToNext());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001072 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001073 } catch (IllegalStateException e) {
1074 Log.e(LOGTAG, "retainIconsOnStartup", e);
Leon Scroggins2c0f6112010-03-12 18:09:39 -05001075 } finally {
1076 if (c!= null) c.close();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001077 }
1078 }
1079
1080 // Helper method for getting the top window.
1081 WebView getTopWindow() {
1082 return mTabControl.getCurrentTopWebView();
1083 }
1084
Grace Kloba22ac16e2009-10-07 18:00:23 -07001085 TabControl getTabControl() {
1086 return mTabControl;
1087 }
1088
The Android Open Source Project0c908882009-03-03 19:32:16 -08001089 @Override
1090 public boolean onCreateOptionsMenu(Menu menu) {
1091 super.onCreateOptionsMenu(menu);
1092
1093 MenuInflater inflater = getMenuInflater();
1094 inflater.inflate(R.menu.browser, menu);
1095 mMenu = menu;
1096 updateInLoadMenuItems();
1097 return true;
1098 }
1099
1100 /**
1101 * As the menu can be open when loading state changes
1102 * we must manually update the state of the stop/reload menu
1103 * item
1104 */
1105 private void updateInLoadMenuItems() {
1106 if (mMenu == null) {
1107 return;
1108 }
Michael Kolbe0a36662010-06-29 10:37:12 -07001109 MenuItem dest = mMenu.findItem(R.id.stop_reload_menu_id);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001110 MenuItem src = mInLoad ?
1111 mMenu.findItem(R.id.stop_menu_id):
Michael Kolbe0a36662010-06-29 10:37:12 -07001112 mMenu.findItem(R.id.reload_menu_id);
1113 if (src != null) {
1114 dest.setIcon(src.getIcon());
1115 dest.setTitle(src.getTitle());
1116 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001117 }
1118
1119 @Override
1120 public boolean onContextItemSelected(MenuItem item) {
1121 // chording is not an issue with context menus, but we use the same
1122 // options selector, so set mCanChord to true so we can access them.
1123 mCanChord = true;
1124 int id = item.getItemId();
Leon Scroggins96afcb12009-12-10 12:35:56 -05001125 boolean result = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001126 switch (id) {
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001127 // For the context menu from the title bar
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001128 case R.id.title_bar_copy_page_url:
Leon Scroggins96afcb12009-12-10 12:35:56 -05001129 Tab currentTab = mTabControl.getCurrentTab();
1130 if (null == currentTab) {
1131 result = false;
1132 break;
1133 }
1134 WebView mainView = currentTab.getWebView();
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001135 if (null == mainView) {
Leon Scroggins96afcb12009-12-10 12:35:56 -05001136 result = false;
1137 break;
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001138 }
Leon Scroggins96afcb12009-12-10 12:35:56 -05001139 copy(mainView.getUrl());
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001140 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001141 // -- Browser context menu
1142 case R.id.open_context_menu_id:
The Android Open Source Project0c908882009-03-03 19:32:16 -08001143 case R.id.bookmark_context_menu_id:
1144 case R.id.save_link_context_menu_id:
1145 case R.id.share_link_context_menu_id:
1146 case R.id.copy_link_context_menu_id:
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001147 final WebView webView = getTopWindow();
1148 if (null == webView) {
Leon Scroggins96afcb12009-12-10 12:35:56 -05001149 result = false;
1150 break;
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001151 }
1152 final HashMap hrefMap = new HashMap();
1153 hrefMap.put("webview", webView);
1154 final Message msg = mHandler.obtainMessage(
1155 FOCUS_NODE_HREF, id, 0, hrefMap);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001156 webView.requestFocusNodeHref(msg);
1157 break;
1158
1159 default:
1160 // For other context menus
Leon Scroggins96afcb12009-12-10 12:35:56 -05001161 result = onOptionsItemSelected(item);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001162 }
1163 mCanChord = false;
Leon Scroggins96afcb12009-12-10 12:35:56 -05001164 return result;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001165 }
1166
1167 private Bundle createGoogleSearchSourceBundle(String source) {
1168 Bundle bundle = new Bundle();
Bjorn Bringert10d1cca2010-02-10 14:22:12 +00001169 bundle.putString(Search.SOURCE, source);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001170 return bundle;
1171 }
1172
Leon Scroggins8ad29922010-02-16 12:33:55 -05001173 /* package */ void editUrl() {
Leon Scroggins68579392009-09-15 15:31:54 -04001174 if (mOptionsMenuOpen) closeOptionsMenu();
Leon Scroggins5bbe9802009-07-31 13:10:55 -04001175 String url = (getTopWindow() == null) ? null : getTopWindow().getUrl();
Grace Kloba83f47342009-07-20 10:44:31 -07001176 startSearch(mSettings.getHomePage().equals(url) ? null : url, true,
Leon Scroggins8ad29922010-02-16 12:33:55 -05001177 null, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001178 }
1179
Leon Scroggins8ad29922010-02-16 12:33:55 -05001180 /**
1181 * Overriding this to insert a local information bundle
1182 */
The Android Open Source Project0c908882009-03-03 19:32:16 -08001183 @Override
1184 public void startSearch(String initialQuery, boolean selectInitialQuery,
1185 Bundle appSearchData, boolean globalSearch) {
1186 if (appSearchData == null) {
1187 appSearchData = createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_TYPE);
1188 }
Leon Scroggins III430057d2010-09-14 10:57:37 -04001189
1190 SearchEngine searchEngine = mSettings.getSearchEngine();
1191 if (searchEngine != null && !searchEngine.supportsVoiceSearch()) {
1192 appSearchData.putBoolean(SearchManager.DISABLE_VOICE_SEARCH, true);
1193 }
1194
The Android Open Source Project0c908882009-03-03 19:32:16 -08001195 super.startSearch(initialQuery, selectInitialQuery, appSearchData, globalSearch);
1196 }
1197
Leon Scroggins1f005d32009-08-10 17:36:42 -04001198 /**
1199 * Switch tabs. Called by the TitleBarSet when sliding the title bar
1200 * results in changing tabs.
Leon Scroggins160a7e72009-08-14 18:28:01 -04001201 * @param index Index of the tab to change to, as defined by
1202 * mTabControl.getTabIndex(Tab t).
1203 * @return boolean True if we successfully switched to a different tab. If
1204 * the indexth tab is null, or if that tab is the same as
1205 * the current one, return false.
Leon Scroggins1f005d32009-08-10 17:36:42 -04001206 */
Leon Scroggins160a7e72009-08-14 18:28:01 -04001207 /* package */ boolean switchToTab(int index) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001208 Tab tab = mTabControl.getTab(index);
1209 Tab currentTab = mTabControl.getCurrentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04001210 if (tab == null || tab == currentTab) {
Leon Scroggins160a7e72009-08-14 18:28:01 -04001211 return false;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001212 }
1213 if (currentTab != null) {
1214 // currentTab may be null if it was just removed. In that case,
1215 // we do not need to remove it
1216 removeTabFromContentView(currentTab);
1217 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001218 mTabControl.setCurrentTab(tab);
1219 attachTabToContentView(tab);
Grace Klobaeb6eef42009-09-15 17:56:32 -07001220 resetTitleIconAndProgress();
1221 updateLockIconToLatest();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001222 return true;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001223 }
1224
Grace Kloba22ac16e2009-10-07 18:00:23 -07001225 /* package */ Tab openTabToHomePage() {
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001226 return openTabAndShow(mSettings.getHomePage(), false, null);
1227 }
1228
Leon Scroggins1f005d32009-08-10 17:36:42 -04001229 /* package */ void closeCurrentWindow() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001230 final Tab current = mTabControl.getCurrentTab();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001231 if (mTabControl.getTabCount() == 1) {
Leon Scroggins30444232009-09-04 18:36:20 -04001232 // This is the last tab. Open a new one, with the home
1233 // page and close the current one.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001234 openTabToHomePage();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001235 closeTab(current);
Leon Scroggins160a7e72009-08-14 18:28:01 -04001236 return;
1237 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07001238 final Tab parent = current.getParentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04001239 int indexToShow = -1;
1240 if (parent != null) {
1241 indexToShow = mTabControl.getTabIndex(parent);
1242 } else {
Leon Scroggins160a7e72009-08-14 18:28:01 -04001243 final int currentIndex = mTabControl.getCurrentIndex();
1244 // Try to move to the tab to the right
1245 indexToShow = currentIndex + 1;
1246 if (indexToShow > mTabControl.getTabCount() - 1) {
1247 // Try to move to the tab to the left
1248 indexToShow = currentIndex - 1;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001249 }
1250 }
Leon Scroggins160a7e72009-08-14 18:28:01 -04001251 if (switchToTab(indexToShow)) {
1252 // Close window
1253 closeTab(current);
1254 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001255 }
1256
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001257 private ActiveTabsPage mActiveTabsPage;
1258
1259 /**
1260 * Remove the active tabs page.
1261 * @param needToAttach If true, the active tabs page did not attach a tab
1262 * to the content view, so we need to do that here.
1263 */
1264 /* package */ void removeActiveTabPage(boolean needToAttach) {
1265 mContentView.removeView(mActiveTabsPage);
Leon Scrogginsd746a942010-05-19 13:21:44 -04001266 mTitleBar.setVisibility(View.VISIBLE);
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001267 mActiveTabsPage = null;
1268 mMenuState = R.id.MAIN_MENU;
1269 if (needToAttach) {
1270 attachTabToContentView(mTabControl.getCurrentTab());
1271 }
1272 getTopWindow().requestFocus();
1273 }
1274
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04001275 @Override
1276 public ActionMode onStartActionMode(ActionMode.Callback callback) {
Leon Scroggins4fc12cb2010-08-24 14:24:05 -04001277 mActionMode = super.onStartActionMode(callback);
1278 hideFakeTitleBar();
1279 // Would like to change the MENU, but onEndActionMode may not be called
1280 return mActionMode;
Cary Clark01cfcdd2010-06-04 16:36:45 -04001281 }
1282
The Android Open Source Project0c908882009-03-03 19:32:16 -08001283 @Override
1284 public boolean onOptionsItemSelected(MenuItem item) {
Michael Kolb370a4f32010-10-06 10:45:32 -07001285 if (item.getGroupId() != R.id.CONTEXT_MENU) {
1286 // menu remains active, so ensure comboview is dismissed
1287 // if main menu option is selected
1288 removeComboView();
1289 }
Michael Kolbed217742010-08-10 17:52:34 -07001290 // check the action bar button before mCanChord check, as the prepare call
1291 // doesn't come for action bar buttons
1292 if (item.getItemId() == R.id.newtab) {
Michael Kolb300b7f02010-08-25 13:47:24 -07001293 openTabToHomePage();
Michael Kolbed217742010-08-10 17:52:34 -07001294 return true;
1295 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001296 if (!mCanChord) {
1297 // The user has already fired a shortcut with this hold down of the
1298 // menu key.
1299 return false;
1300 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001301 if (null == getTopWindow()) {
Leon Scroggins0d7ae0e2009-06-05 11:04:45 -04001302 return false;
1303 }
Grace Kloba6ee9c492009-07-13 10:04:34 -07001304 if (mMenuIsDown) {
1305 // The shortcut action consumes the MENU. Even if it is still down,
1306 // it won't trigger the next shortcut action. In the case of the
1307 // shortcut action triggering a new activity, like Bookmarks, we
1308 // won't get onKeyUp for MENU. So it is important to reset it here.
1309 mMenuIsDown = false;
1310 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001311 switch (item.getItemId()) {
1312 // -- Main menu
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001313 case R.id.new_tab_menu_id:
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001314 openTabToHomePage();
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001315 break;
1316
Michael Kolbae62fd42010-08-18 16:33:28 -07001317 case R.id.incognito_menu_id:
1318 openIncognitoTab();
1319 break;
1320
Leon Scroggins64b80f32009-08-07 12:03:34 -04001321 case R.id.goto_menu_id:
Leon Scroggins8ad29922010-02-16 12:33:55 -05001322 editUrl();
Leon Scrogginsb3a5bed2009-09-28 11:21:56 -04001323 break;
1324
1325 case R.id.bookmarks_menu_id:
Michael Kolbe421c242010-10-04 19:29:01 -07001326 bookmarksOrHistoryPicker(false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001327 break;
1328
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001329 case R.id.active_tabs_menu_id:
1330 mActiveTabsPage = new ActiveTabsPage(this, mTabControl);
1331 removeTabFromContentView(mTabControl.getCurrentTab());
Leon Scrogginsd746a942010-05-19 13:21:44 -04001332 mTitleBar.setVisibility(View.GONE);
Leon Scroggins43de6162009-09-14 19:59:58 -04001333 hideFakeTitleBar();
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001334 mContentView.addView(mActiveTabsPage, COVER_SCREEN_PARAMS);
1335 mActiveTabsPage.requestFocus();
1336 mMenuState = EMPTY_MENU;
1337 break;
1338
Leon Scroggins1f005d32009-08-10 17:36:42 -04001339 case R.id.add_bookmark_menu_id:
Michael Kolb370a4f32010-10-06 10:45:32 -07001340 bookmarkCurrentPage(AddBookmarkPage.DEFAULT_FOLDER_ID);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001341 break;
1342
1343 case R.id.stop_reload_menu_id:
1344 if (mInLoad) {
1345 stopLoading();
1346 } else {
1347 getTopWindow().reload();
1348 }
1349 break;
1350
1351 case R.id.back_menu_id:
1352 getTopWindow().goBack();
1353 break;
1354
1355 case R.id.forward_menu_id:
1356 getTopWindow().goForward();
1357 break;
1358
1359 case R.id.close_menu_id:
1360 // Close the subwindow if it exists.
1361 if (mTabControl.getCurrentSubWindow() != null) {
1362 dismissSubWindow(mTabControl.getCurrentTab());
1363 break;
1364 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001365 closeCurrentWindow();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001366 break;
1367
1368 case R.id.homepage_menu_id:
Grace Kloba22ac16e2009-10-07 18:00:23 -07001369 Tab current = mTabControl.getCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001370 if (current != null) {
1371 dismissSubWindow(current);
Leon Scroggins92472e82010-02-17 16:32:28 -05001372 loadUrl(current.getWebView(), mSettings.getHomePage());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001373 }
1374 break;
1375
1376 case R.id.preferences_menu_id:
1377 Intent intent = new Intent(this,
1378 BrowserPreferencesPage.class);
Leon Scrogginsd5304942009-12-10 16:11:39 -05001379 intent.putExtra(BrowserPreferencesPage.CURRENT_PAGE,
1380 getTopWindow().getUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001381 startActivityForResult(intent, PREFERENCES_PAGE);
1382 break;
1383
1384 case R.id.find_menu_id:
Leon Scroggins4fc12cb2010-08-24 14:24:05 -04001385 getTopWindow().showFindDialog(null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001386 break;
1387
Elliott Slaughter0ced08c2010-06-30 11:40:42 -07001388 case R.id.save_webarchive_menu_id:
1389 if (LOGD_ENABLED) {
1390 Log.d(LOGTAG, "Save as Web Archive");
1391 }
Elliott Slaughteraba242c2010-09-01 16:21:07 -07001392 String state = Environment.getExternalStorageState();
1393 if (Environment.MEDIA_MOUNTED.equals(state)) {
1394 String directory = Environment.getExternalStoragePublicDirectory(
1395 Environment.DIRECTORY_DOWNLOADS).getAbsolutePath() + File.separator;
Shimeng (Simon) Wang447c8462010-09-15 18:16:55 -07001396 File dir = new File(directory);
1397 if (!dir.exists() && !dir.mkdirs()) {
1398 Log.e(LOGTAG, "Save as Web Archive: mkdirs for " + directory + " failed!");
1399 Toast.makeText(BrowserActivity.this, R.string.webarchive_failed,
1400 Toast.LENGTH_SHORT).show();
1401 break;
1402 }
Elliott Slaughteraba242c2010-09-01 16:21:07 -07001403 getTopWindow().saveWebArchive(directory, true, new ValueCallback<String>() {
1404 @Override
1405 public void onReceiveValue(String value) {
1406 if (value != null) {
1407 Toast.makeText(BrowserActivity.this, R.string.webarchive_saved,
1408 Toast.LENGTH_SHORT).show();
1409 } else {
1410 Toast.makeText(BrowserActivity.this, R.string.webarchive_failed,
1411 Toast.LENGTH_SHORT).show();
1412 }
Elliott Slaughter0ced08c2010-06-30 11:40:42 -07001413 }
Elliott Slaughteraba242c2010-09-01 16:21:07 -07001414 });
1415 } else {
1416 Toast.makeText(BrowserActivity.this, R.string.webarchive_failed,
1417 Toast.LENGTH_SHORT).show();
1418 }
Elliott Slaughter0ced08c2010-06-30 11:40:42 -07001419 break;
1420
The Android Open Source Project0c908882009-03-03 19:32:16 -08001421 case R.id.page_info_menu_id:
1422 showPageInfo(mTabControl.getCurrentTab(), false);
1423 break;
1424
1425 case R.id.classic_history_menu_id:
Michael Kolbe421c242010-10-04 19:29:01 -07001426 bookmarksOrHistoryPicker(true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001427 break;
1428
Leon Scroggins96afcb12009-12-10 12:35:56 -05001429 case R.id.title_bar_share_page_url:
The Android Open Source Project0c908882009-03-03 19:32:16 -08001430 case R.id.share_page_menu_id:
Leon Scroggins96afcb12009-12-10 12:35:56 -05001431 Tab currentTab = mTabControl.getCurrentTab();
1432 if (null == currentTab) {
1433 mCanChord = false;
1434 return false;
1435 }
1436 currentTab.populatePickerData();
1437 sharePage(this, currentTab.getTitle(),
1438 currentTab.getUrl(), currentTab.getFavicon(),
Ben Murdoch87cc65d2010-06-29 20:34:10 +01001439 createScreenshot(currentTab.getWebView(), getDesiredThumbnailWidth(this),
1440 getDesiredThumbnailHeight(this)));
The Android Open Source Project0c908882009-03-03 19:32:16 -08001441 break;
1442
1443 case R.id.dump_nav_menu_id:
1444 getTopWindow().debugDump();
1445 break;
1446
Andrei Popescu7a8b88b2010-02-02 00:30:38 +00001447 case R.id.dump_counters_menu_id:
1448 getTopWindow().dumpV8Counters();
1449 break;
1450
The Android Open Source Project0c908882009-03-03 19:32:16 -08001451 case R.id.zoom_in_menu_id:
1452 getTopWindow().zoomIn();
1453 break;
1454
1455 case R.id.zoom_out_menu_id:
1456 getTopWindow().zoomOut();
1457 break;
1458
1459 case R.id.view_downloads_menu_id:
Leon Scroggins IIIa682a3c2010-09-27 12:32:40 -04001460 viewDownloads();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001461 break;
1462
The Android Open Source Project0c908882009-03-03 19:32:16 -08001463 case R.id.window_one_menu_id:
1464 case R.id.window_two_menu_id:
1465 case R.id.window_three_menu_id:
1466 case R.id.window_four_menu_id:
1467 case R.id.window_five_menu_id:
1468 case R.id.window_six_menu_id:
1469 case R.id.window_seven_menu_id:
1470 case R.id.window_eight_menu_id:
1471 {
1472 int menuid = item.getItemId();
1473 for (int id = 0; id < WINDOW_SHORTCUT_ID_ARRAY.length; id++) {
1474 if (WINDOW_SHORTCUT_ID_ARRAY[id] == menuid) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001475 Tab desiredTab = mTabControl.getTab(id);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001476 if (desiredTab != null &&
1477 desiredTab != mTabControl.getCurrentTab()) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001478 switchToTab(id);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001479 }
1480 break;
1481 }
1482 }
1483 }
1484 break;
1485
1486 default:
1487 if (!super.onOptionsItemSelected(item)) {
1488 return false;
1489 }
1490 // Otherwise fall through.
1491 }
1492 mCanChord = false;
1493 return true;
1494 }
1495
Michael Kolb370a4f32010-10-06 10:45:32 -07001496 /**
1497 * add the current page as a bookmark to the given folder id
1498 * @param folderId use -1 for the default folder
1499 */
1500 /* package */ void bookmarkCurrentPage(long folderId) {
Leon Scroggins571b3762010-05-26 10:25:01 -04001501 Intent i = new Intent(BrowserActivity.this,
1502 AddBookmarkPage.class);
1503 WebView w = getTopWindow();
1504 i.putExtra("url", w.getUrl());
1505 i.putExtra("title", w.getTitle());
1506 i.putExtra("touch_icon_url", w.getTouchIconUrl());
Ben Murdoch87cc65d2010-06-29 20:34:10 +01001507 i.putExtra("thumbnail", createScreenshot(w, getDesiredThumbnailWidth(this),
1508 getDesiredThumbnailHeight(this)));
Michael Kolb370a4f32010-10-06 10:45:32 -07001509 i.putExtra(BrowserContract.Bookmarks.PARENT,
1510 folderId);
Leon Scroggins III76a0e9c2010-10-05 16:10:01 -04001511 // Put the dialog at the upper right of the screen, covering the
1512 // star on the title bar.
1513 i.putExtra("gravity", Gravity.RIGHT | Gravity.TOP);
Leon Scroggins571b3762010-05-26 10:25:01 -04001514 startActivity(i);
1515 }
1516
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04001517 /*
1518 * True if a custom ActionMode (i.e. find or select) is in use.
1519 */
1520 private boolean isInCustomActionMode() {
1521 return mActionMode != null;
Cary Clark01cfcdd2010-06-04 16:36:45 -04001522 }
1523
1524 /*
Leon Scroggins4fc12cb2010-08-24 14:24:05 -04001525 * End the current ActionMode.
Cary Clark01cfcdd2010-06-04 16:36:45 -04001526 */
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04001527 void endActionMode() {
1528 if (mActionMode != null) {
Leon Scroggins4fc12cb2010-08-24 14:24:05 -04001529 ActionMode mode = mActionMode;
1530 onEndActionMode();
1531 mode.finish();
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04001532 }
1533 }
1534
1535 /*
1536 * Called by find and select when they are finished. Replace title bars
1537 * as necessary.
1538 */
1539 public void onEndActionMode() {
1540 if (!isInCustomActionMode()) return;
Leon Scroggins79e36d92010-04-29 16:01:46 +01001541 if (mInLoad) {
1542 // The title bar was hidden, because otherwise it would cover up the
Michael Kolba2b2ba82010-08-04 17:54:03 -07001543 // find or select dialog. Now that the dialog has been removed,
Cary Clark01cfcdd2010-06-04 16:36:45 -04001544 // show the fake title bar once again.
Leon Scroggins79e36d92010-04-29 16:01:46 +01001545 showFakeTitleBar();
1546 }
Leon Scroggins4fc12cb2010-08-24 14:24:05 -04001547 // Would like to return the menu state to normal, but this does not
1548 // necessarily get called.
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04001549 mActionMode = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001550 }
1551
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04001552 // For select and find, we keep track of the ActionMode so that
1553 // finish() can be called as desired.
1554 private ActionMode mActionMode;
1555
Grace Kloba22ac16e2009-10-07 18:00:23 -07001556 @Override
1557 public boolean onPrepareOptionsMenu(Menu menu) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001558 // This happens when the user begins to hold down the menu key, so
1559 // allow them to chord to get a shortcut.
1560 mCanChord = true;
1561 // Note: setVisible will decide whether an item is visible; while
1562 // setEnabled() will decide whether an item is enabled, which also means
1563 // whether the matching shortcut key will function.
1564 super.onPrepareOptionsMenu(menu);
1565 switch (mMenuState) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001566 case EMPTY_MENU:
1567 if (mCurrentMenuState != mMenuState) {
1568 menu.setGroupVisible(R.id.MAIN_MENU, false);
1569 menu.setGroupEnabled(R.id.MAIN_MENU, false);
1570 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001571 }
1572 break;
1573 default:
1574 if (mCurrentMenuState != mMenuState) {
1575 menu.setGroupVisible(R.id.MAIN_MENU, true);
1576 menu.setGroupEnabled(R.id.MAIN_MENU, true);
1577 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001578 }
1579 final WebView w = getTopWindow();
1580 boolean canGoBack = false;
1581 boolean canGoForward = false;
1582 boolean isHome = false;
1583 if (w != null) {
1584 canGoBack = w.canGoBack();
1585 canGoForward = w.canGoForward();
1586 isHome = mSettings.getHomePage().equals(w.getUrl());
1587 }
1588 final MenuItem back = menu.findItem(R.id.back_menu_id);
1589 back.setEnabled(canGoBack);
1590
1591 final MenuItem home = menu.findItem(R.id.homepage_menu_id);
1592 home.setEnabled(!isHome);
1593
Michael Kolbe0a36662010-06-29 10:37:12 -07001594 final MenuItem forward = menu.findItem(R.id.forward_menu_id);
1595 forward.setEnabled(canGoForward);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001596
Michael Kolbed217742010-08-10 17:52:34 -07001597 if (!mXLargeScreenSize) {
1598 final MenuItem newtab = menu.findItem(R.id.new_tab_menu_id);
1599 newtab.setEnabled(mTabControl.canCreateNewTab());
1600 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001601 // decide whether to show the share link option
1602 PackageManager pm = getPackageManager();
1603 Intent send = new Intent(Intent.ACTION_SEND);
1604 send.setType("text/plain");
1605 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1606 menu.findItem(R.id.share_page_menu_id).setVisible(ri != null);
1607
The Android Open Source Project0c908882009-03-03 19:32:16 -08001608 boolean isNavDump = mSettings.isNavDump();
1609 final MenuItem nav = menu.findItem(R.id.dump_nav_menu_id);
1610 nav.setVisible(isNavDump);
1611 nav.setEnabled(isNavDump);
Andrei Popescu7a8b88b2010-02-02 00:30:38 +00001612
1613 boolean showDebugSettings = mSettings.showDebugSettings();
1614 final MenuItem counter = menu.findItem(R.id.dump_counters_menu_id);
1615 counter.setVisible(showDebugSettings);
1616 counter.setEnabled(showDebugSettings);
1617
The Android Open Source Project0c908882009-03-03 19:32:16 -08001618 break;
1619 }
1620 mCurrentMenuState = mMenuState;
1621 return true;
1622 }
1623
1624 @Override
1625 public void onCreateContextMenu(ContextMenu menu, View v,
1626 ContextMenuInfo menuInfo) {
Leon Scroggins571b3762010-05-26 10:25:01 -04001627 if (v instanceof TitleBarBase) {
Leon Scroggins4e9f89b2010-02-22 16:54:14 -05001628 return;
1629 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001630 WebView webview = (WebView) v;
1631 WebView.HitTestResult result = webview.getHitTestResult();
1632 if (result == null) {
1633 return;
1634 }
1635
1636 int type = result.getType();
1637 if (type == WebView.HitTestResult.UNKNOWN_TYPE) {
1638 Log.w(LOGTAG,
1639 "We should not show context menu when nothing is touched");
1640 return;
1641 }
1642 if (type == WebView.HitTestResult.EDIT_TEXT_TYPE) {
1643 // let TextView handles context menu
1644 return;
1645 }
1646
1647 // Note, http://b/issue?id=1106666 is requesting that
1648 // an inflated menu can be used again. This is not available
1649 // yet, so inflate each time (yuk!)
1650 MenuInflater inflater = getMenuInflater();
1651 inflater.inflate(R.menu.browsercontext, menu);
1652
1653 // Show the correct menu group
Leon Scroggins III9e997c72010-05-26 13:25:16 -04001654 final String extra = result.getExtra();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001655 menu.setGroupVisible(R.id.PHONE_MENU,
1656 type == WebView.HitTestResult.PHONE_TYPE);
1657 menu.setGroupVisible(R.id.EMAIL_MENU,
1658 type == WebView.HitTestResult.EMAIL_TYPE);
1659 menu.setGroupVisible(R.id.GEO_MENU,
1660 type == WebView.HitTestResult.GEO_TYPE);
1661 menu.setGroupVisible(R.id.IMAGE_MENU,
1662 type == WebView.HitTestResult.IMAGE_TYPE
1663 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1664 menu.setGroupVisible(R.id.ANCHOR_MENU,
1665 type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1666 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1667
1668 // Setup custom handling depending on the type
1669 switch (type) {
1670 case WebView.HitTestResult.PHONE_TYPE:
1671 menu.setHeaderTitle(Uri.decode(extra));
1672 menu.findItem(R.id.dial_context_menu_id).setIntent(
1673 new Intent(Intent.ACTION_VIEW, Uri
1674 .parse(WebView.SCHEME_TEL + extra)));
1675 Intent addIntent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
1676 addIntent.putExtra(Insert.PHONE, Uri.decode(extra));
Cary Clark5e335a32009-09-22 14:53:11 -04001677 addIntent.setType(ContactsContract.Contacts.CONTENT_ITEM_TYPE);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001678 menu.findItem(R.id.add_contact_context_menu_id).setIntent(
1679 addIntent);
1680 menu.findItem(R.id.copy_phone_context_menu_id).setOnMenuItemClickListener(
1681 new Copy(extra));
1682 break;
1683
1684 case WebView.HitTestResult.EMAIL_TYPE:
1685 menu.setHeaderTitle(extra);
1686 menu.findItem(R.id.email_context_menu_id).setIntent(
1687 new Intent(Intent.ACTION_VIEW, Uri
1688 .parse(WebView.SCHEME_MAILTO + extra)));
1689 menu.findItem(R.id.copy_mail_context_menu_id).setOnMenuItemClickListener(
1690 new Copy(extra));
1691 break;
1692
1693 case WebView.HitTestResult.GEO_TYPE:
1694 menu.setHeaderTitle(extra);
1695 menu.findItem(R.id.map_context_menu_id).setIntent(
1696 new Intent(Intent.ACTION_VIEW, Uri
1697 .parse(WebView.SCHEME_GEO
1698 + URLEncoder.encode(extra))));
1699 menu.findItem(R.id.copy_geo_context_menu_id).setOnMenuItemClickListener(
1700 new Copy(extra));
1701 break;
1702
1703 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1704 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
1705 TextView titleView = (TextView) LayoutInflater.from(this)
1706 .inflate(android.R.layout.browser_link_context_header,
1707 null);
1708 titleView.setText(extra);
1709 menu.setHeaderView(titleView);
1710 // decide whether to show the open link in new tab option
Leon Scroggins III9e997c72010-05-26 13:25:16 -04001711 boolean showNewTab = mTabControl.canCreateNewTab();
1712 MenuItem newTabItem
1713 = menu.findItem(R.id.open_newtab_context_menu_id);
1714 newTabItem.setVisible(showNewTab);
1715 if (showNewTab) {
1716 newTabItem.setOnMenuItemClickListener(
1717 new MenuItem.OnMenuItemClickListener() {
1718 public boolean onMenuItemClick(MenuItem item) {
1719 final Tab parent = mTabControl.getCurrentTab();
Michael Kolb68792c82010-08-09 16:39:18 -07001720 final Tab newTab = openTab(extra, false);
Leon Scroggins III9e997c72010-05-26 13:25:16 -04001721 if (newTab != parent) {
1722 parent.addChildTab(newTab);
1723 }
1724 return true;
1725 }
1726 });
1727 }
Ben Murdochde353622009-10-12 10:29:00 +01001728 menu.findItem(R.id.bookmark_context_menu_id).setVisible(
1729 Bookmarks.urlHasAcceptableScheme(extra));
The Android Open Source Project0c908882009-03-03 19:32:16 -08001730 PackageManager pm = getPackageManager();
1731 Intent send = new Intent(Intent.ACTION_SEND);
1732 send.setType("text/plain");
1733 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1734 menu.findItem(R.id.share_link_context_menu_id).setVisible(ri != null);
1735 if (type == WebView.HitTestResult.SRC_ANCHOR_TYPE) {
1736 break;
1737 }
1738 // otherwise fall through to handle image part
1739 case WebView.HitTestResult.IMAGE_TYPE:
1740 if (type == WebView.HitTestResult.IMAGE_TYPE) {
1741 menu.setHeaderTitle(extra);
1742 }
1743 menu.findItem(R.id.view_image_context_menu_id).setIntent(
1744 new Intent(Intent.ACTION_VIEW, Uri.parse(extra)));
1745 menu.findItem(R.id.download_context_menu_id).
1746 setOnMenuItemClickListener(new Download(extra));
Ben Murdoch4f75ba22009-10-27 11:48:28 +00001747 menu.findItem(R.id.set_wallpaper_context_menu_id).
1748 setOnMenuItemClickListener(new SetAsWallpaper(extra));
The Android Open Source Project0c908882009-03-03 19:32:16 -08001749 break;
1750
1751 default:
1752 Log.w(LOGTAG, "We should not get here.");
1753 break;
1754 }
Leon Scrogginsb2b19f52009-10-09 16:10:00 -04001755 hideFakeTitleBar();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001756 }
1757
The Android Open Source Project0c908882009-03-03 19:32:16 -08001758 // Attach the given tab to the content view.
Grace Klobac928c302009-09-17 11:51:21 -07001759 // this should only be called for the current tab.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001760 private void attachTabToContentView(Tab t) {
Steve Block2bc69912009-07-30 14:45:13 +01001761 // Attach the container that contains the main WebView and any other UI
1762 // associated with the tab.
Patrick Scottd0119532009-09-17 08:00:31 -04001763 t.attachTabToContentView(mContentView);
Ben Murdochbff2d602009-07-01 20:19:05 +01001764
1765 if (mShouldShowErrorConsole) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001766 ErrorConsoleView errorConsole = t.getErrorConsole(true);
Ben Murdochbff2d602009-07-01 20:19:05 +01001767 if (errorConsole.numberOfErrors() == 0) {
1768 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
1769 } else {
1770 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
1771 }
1772
1773 mErrorConsoleContainer.addView(errorConsole,
Romain Guy15b8ec62010-01-08 15:06:43 -08001774 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
Ben Murdochbff2d602009-07-01 20:19:05 +01001775 ViewGroup.LayoutParams.WRAP_CONTENT));
1776 }
1777
Michael Kolba2b2ba82010-08-04 17:54:03 -07001778 WebView view = t.getWebView();
1779 view.setEmbeddedTitleBar(mTitleBar);
Leon Scroggins58d56c62010-01-28 15:12:40 -05001780 if (t.isInVoiceSearchMode()) {
1781 showVoiceTitleBar(t.getVoiceDisplayTitle());
1782 } else {
1783 revertVoiceTitleBar();
1784 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001785 // Request focus on the top window.
1786 t.getTopWindow().requestFocus();
Michael Kolba2b2ba82010-08-04 17:54:03 -07001787 if (mTabControl.getTabChangeListener() != null) {
1788 mTabControl.getTabChangeListener().onCurrentTab(t);
1789 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001790 }
1791
1792 // Attach a sub window to the main WebView of the given tab.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001793 void attachSubWindow(Tab t) {
Patrick Scottd0119532009-09-17 08:00:31 -04001794 t.attachSubWindow(mContentView);
1795 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001796 }
1797
1798 // Remove the given tab from the content view.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001799 private void removeTabFromContentView(Tab t) {
Steve Block2bc69912009-07-30 14:45:13 +01001800 // Remove the container that contains the main WebView.
Patrick Scottd0119532009-09-17 08:00:31 -04001801 t.removeTabFromContentView(mContentView);
Ben Murdochbff2d602009-07-01 20:19:05 +01001802
Grace Kloba22ac16e2009-10-07 18:00:23 -07001803 ErrorConsoleView errorConsole = t.getErrorConsole(false);
1804 if (errorConsole != null) {
1805 mErrorConsoleContainer.removeView(errorConsole);
Ben Murdochbff2d602009-07-01 20:19:05 +01001806 }
1807
Michael Kolba2b2ba82010-08-04 17:54:03 -07001808 WebView view = t.getWebView();
1809 if (view != null) {
1810 view.setEmbeddedTitleBar(null);
Leon Scrogginsbb85b902009-09-14 19:27:20 -04001811 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001812 }
1813
1814 // Remove the sub window if it exists. Also called by TabControl when the
1815 // user clicks the 'X' to dismiss a sub window.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001816 /* package */ void dismissSubWindow(Tab t) {
Patrick Scottd0119532009-09-17 08:00:31 -04001817 t.removeSubWindow(mContentView);
Grace Kloba22ac16e2009-10-07 18:00:23 -07001818 // dismiss the subwindow. This will destroy the WebView.
1819 t.dismissSubWindow();
Patrick Scottd0119532009-09-17 08:00:31 -04001820 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001821 }
1822
Leon Scroggins1f005d32009-08-10 17:36:42 -04001823 // A wrapper function of {@link #openTabAndShow(UrlData, boolean, String)}
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07001824 // that accepts url as string.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001825 private Tab openTabAndShow(String url, boolean closeOnExit, String appId) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001826 return openTabAndShow(new UrlData(url), closeOnExit, appId);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001827 }
1828
1829 // This method does a ton of stuff. It will attempt to create a new tab
1830 // if we haven't reached MAX_TABS. Otherwise it uses the current tab. If
Leon Scroggins1f005d32009-08-10 17:36:42 -04001831 // url isn't null, it will load the given url.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001832 /* package */Tab openTabAndShow(UrlData urlData, boolean closeOnExit,
1833 String appId) {
1834 final Tab currentTab = mTabControl.getCurrentTab();
1835 if (mTabControl.canCreateNewTab()) {
1836 final Tab tab = mTabControl.createNewTab(closeOnExit, appId,
Elliott Slaughterf0f03952010-07-14 18:10:36 -07001837 urlData.mUrl, false);
Leon Scroggins1f005d32009-08-10 17:36:42 -04001838 WebView webview = tab.getWebView();
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001839 // If the last tab was removed from the active tabs page, currentTab
1840 // will be null.
1841 if (currentTab != null) {
1842 removeTabFromContentView(currentTab);
1843 }
Patrick Scott8bbd69f2009-08-14 13:35:53 -04001844 // We must set the new tab as the current tab to reflect the old
1845 // animation behavior.
1846 mTabControl.setCurrentTab(tab);
Grace Klobaeb6eef42009-09-15 17:56:32 -07001847 attachTabToContentView(tab);
Leon Scroggins160a7e72009-08-14 18:28:01 -04001848 if (!urlData.isEmpty()) {
Patrick Scott9d53da02010-02-19 10:19:01 -05001849 loadUrlDataIn(tab, urlData);
Leon Scroggins1f005d32009-08-10 17:36:42 -04001850 }
1851 return tab;
1852 } else {
1853 // Get rid of the subwindow if it exists
1854 dismissSubWindow(currentTab);
1855 if (!urlData.isEmpty()) {
1856 // Load the given url.
Patrick Scott9d53da02010-02-19 10:19:01 -05001857 loadUrlDataIn(currentTab, urlData);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001858 }
Leon Scroggins58d56c62010-01-28 15:12:40 -05001859 return currentTab;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001860 }
1861 }
1862
Michael Kolb68792c82010-08-09 16:39:18 -07001863 private Tab openTab(String url, boolean forceForeground) {
1864 if (mSettings.openInBackground() && !forceForeground) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001865 Tab t = mTabControl.createNewTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001866 if (t != null) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001867 WebView view = t.getWebView();
Leon Scroggins92472e82010-02-17 16:32:28 -05001868 loadUrl(view, url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001869 }
Grace Klobac9181842009-04-14 08:53:22 -07001870 return t;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001871 } else {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001872 return openTabAndShow(url, false, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001873 }
1874 }
1875
Elliott Slaughterf0f03952010-07-14 18:10:36 -07001876 /* package */ Tab openIncognitoTab() {
1877 if (mTabControl.canCreateNewTab()) {
1878 Tab currentTab = mTabControl.getCurrentTab();
1879 Tab tab = mTabControl.createNewTab(false, null, null, true);
1880 if (currentTab != null) {
1881 removeTabFromContentView(currentTab);
1882 }
1883 mTabControl.setCurrentTab(tab);
1884 attachTabToContentView(tab);
1885 return tab;
1886 }
1887 return null;
1888 }
1889
The Android Open Source Project0c908882009-03-03 19:32:16 -08001890 private class Copy implements OnMenuItemClickListener {
1891 private CharSequence mText;
1892
1893 public boolean onMenuItemClick(MenuItem item) {
1894 copy(mText);
1895 return true;
1896 }
1897
1898 public Copy(CharSequence toCopy) {
1899 mText = toCopy;
1900 }
1901 }
1902
1903 private class Download implements OnMenuItemClickListener {
1904 private String mText;
1905
1906 public boolean onMenuItemClick(MenuItem item) {
1907 onDownloadStartNoStream(mText, null, null, null, -1);
1908 return true;
1909 }
1910
1911 public Download(String toDownload) {
1912 mText = toDownload;
1913 }
1914 }
1915
Ben Murdoch4f75ba22009-10-27 11:48:28 +00001916 private class SetAsWallpaper extends Thread implements
1917 OnMenuItemClickListener, DialogInterface.OnCancelListener {
1918 private URL mUrl;
1919 private ProgressDialog mWallpaperProgress;
1920 private boolean mCanceled = false;
1921
1922 public SetAsWallpaper(String url) {
1923 try {
1924 mUrl = new URL(url);
1925 } catch (MalformedURLException e) {
1926 mUrl = null;
1927 }
1928 }
1929
1930 public void onCancel(DialogInterface dialog) {
1931 mCanceled = true;
1932 }
1933
1934 public boolean onMenuItemClick(MenuItem item) {
1935 if (mUrl != null) {
1936 // The user may have tried to set a image with a large file size as their
1937 // background so it may take a few moments to perform the operation. Display
1938 // a progress spinner while it is working.
1939 mWallpaperProgress = new ProgressDialog(BrowserActivity.this);
1940 mWallpaperProgress.setIndeterminate(true);
1941 mWallpaperProgress.setMessage(getText(R.string.progress_dialog_setting_wallpaper));
1942 mWallpaperProgress.setCancelable(true);
1943 mWallpaperProgress.setOnCancelListener(this);
1944 mWallpaperProgress.show();
1945 start();
1946 }
1947 return true;
1948 }
1949
Michael Kolbe0a36662010-06-29 10:37:12 -07001950 @Override
Ben Murdoch4f75ba22009-10-27 11:48:28 +00001951 public void run() {
1952 Drawable oldWallpaper = BrowserActivity.this.getWallpaper();
1953 try {
1954 // TODO: This will cause the resource to be downloaded again, when we
1955 // should in most cases be able to grab it from the cache. To fix this
1956 // we should query WebCore to see if we can access a cached version and
1957 // instead open an input stream on that. This pattern could also be used
1958 // in the download manager where the same problem exists.
1959 InputStream inputstream = mUrl.openStream();
1960 if (inputstream != null) {
1961 setWallpaper(inputstream);
1962 }
1963 } catch (IOException e) {
1964 Log.e(LOGTAG, "Unable to set new wallpaper");
1965 // Act as though the user canceled the operation so we try to
1966 // restore the old wallpaper.
1967 mCanceled = true;
1968 }
1969
1970 if (mCanceled) {
1971 // Restore the old wallpaper if the user cancelled whilst we were setting
1972 // the new wallpaper.
1973 int width = oldWallpaper.getIntrinsicWidth();
1974 int height = oldWallpaper.getIntrinsicHeight();
1975 Bitmap bm = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
1976 Canvas canvas = new Canvas(bm);
1977 oldWallpaper.setBounds(0, 0, width, height);
1978 oldWallpaper.draw(canvas);
1979 try {
1980 setWallpaper(bm);
1981 } catch (IOException e) {
1982 Log.e(LOGTAG, "Unable to restore old wallpaper.");
1983 }
1984 mCanceled = false;
1985 }
1986
1987 if (mWallpaperProgress.isShowing()) {
1988 mWallpaperProgress.dismiss();
1989 }
1990 }
1991 }
1992
The Android Open Source Project0c908882009-03-03 19:32:16 -08001993 private void copy(CharSequence text) {
Dianne Hackborn80f32622010-08-05 14:17:53 -07001994 ClipboardManager cm = (ClipboardManager)getSystemService(Context.CLIPBOARD_SERVICE);
1995 cm.setText(text);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001996 }
1997
1998 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08001999 * Resets the browser title-view to whatever it must be
2000 * (for example, if we had a loading error)
2001 * When we have a new page, we call resetTitle, when we
2002 * have to reset the titlebar to whatever it used to be
2003 * (for example, if the user chose to stop loading), we
2004 * call resetTitleAndRevertLockIcon.
2005 */
2006 /* package */ void resetTitleAndRevertLockIcon() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002007 mTabControl.getCurrentTab().revertLockIcon();
2008 updateLockIconToLatest();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002009 resetTitleIconAndProgress();
2010 }
2011
2012 /**
2013 * Reset the title, favicon, and progress.
2014 */
2015 private void resetTitleIconAndProgress() {
2016 WebView current = mTabControl.getCurrentWebView();
2017 if (current == null) {
2018 return;
2019 }
2020 resetTitleAndIcon(current);
2021 int progress = current.getProgress();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002022 current.getWebChromeClient().onProgressChanged(current, progress);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002023 }
2024
2025 // Reset the title and the icon based on the given item.
2026 private void resetTitleAndIcon(WebView view) {
2027 WebHistoryItem item = view.copyBackForwardList().getCurrentItem();
2028 if (item != null) {
Leon Scroggins68579392009-09-15 15:31:54 -04002029 setUrlTitle(item.getUrl(), item.getTitle());
The Android Open Source Project0c908882009-03-03 19:32:16 -08002030 setFavicon(item.getFavicon());
2031 } else {
Leon Scroggins68579392009-09-15 15:31:54 -04002032 setUrlTitle(null, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002033 setFavicon(null);
2034 }
2035 }
2036
2037 /**
2038 * Sets a title composed of the URL and the title string.
2039 * @param url The URL of the site being loaded.
2040 * @param title The title of the site being loaded.
2041 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07002042 void setUrlTitle(String url, String title) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002043 mUrl = url;
2044 mTitle = title;
2045
Leon Scroggins58d56c62010-01-28 15:12:40 -05002046 // If we are in voice search mode, the title has already been set.
2047 if (mTabControl.getCurrentTab().isInVoiceSearchMode()) return;
2048 mTitleBar.setDisplayTitle(url);
Michael Kolba2b2ba82010-08-04 17:54:03 -07002049 mFakeTitleBar.setDisplayTitle(url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002050 }
2051
2052 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08002053 * @param url The URL to build a title version of the URL from.
2054 * @return The title version of the URL or null if fails.
2055 * The title version of the URL can be either the URL hostname,
2056 * or the hostname with an "https://" prefix (for secure URLs),
2057 * or an empty string if, for example, the URL in question is a
2058 * file:// URL with no hostname.
2059 */
Leon Scroggins32e14a62009-06-11 10:26:34 -04002060 /* package */ static String buildTitleUrl(String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002061 String titleUrl = null;
2062
2063 if (url != null) {
2064 try {
2065 // parse the url string
2066 URL urlObj = new URL(url);
2067 if (urlObj != null) {
2068 titleUrl = "";
2069
2070 String protocol = urlObj.getProtocol();
2071 String host = urlObj.getHost();
2072
2073 if (host != null && 0 < host.length()) {
2074 titleUrl = host;
2075 if (protocol != null) {
2076 // if a secure site, add an "https://" prefix!
2077 if (protocol.equalsIgnoreCase("https")) {
2078 titleUrl = protocol + "://" + host;
2079 }
2080 }
2081 }
2082 }
2083 } catch (MalformedURLException e) {}
2084 }
2085
2086 return titleUrl;
2087 }
2088
2089 // Set the favicon in the title bar.
Grace Kloba22ac16e2009-10-07 18:00:23 -07002090 void setFavicon(Bitmap icon) {
Leon Scroggins68579392009-09-15 15:31:54 -04002091 mTitleBar.setFavicon(icon);
Michael Kolba2b2ba82010-08-04 17:54:03 -07002092 mFakeTitleBar.setFavicon(icon);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002093 }
2094
2095 /**
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002096 * Close the tab, remove its associated title bar, and adjust mTabControl's
2097 * current tab to a valid value.
Leon Scroggins1f005d32009-08-10 17:36:42 -04002098 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07002099 /* package */ void closeTab(Tab t) {
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002100 int currentIndex = mTabControl.getCurrentIndex();
2101 int removeIndex = mTabControl.getTabIndex(t);
Leon Scroggins1f005d32009-08-10 17:36:42 -04002102 mTabControl.removeTab(t);
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002103 if (currentIndex >= removeIndex && currentIndex != 0) {
2104 currentIndex--;
2105 }
2106 mTabControl.setCurrentTab(mTabControl.getTab(currentIndex));
Andrei Popescua5bf1de2009-09-23 16:39:23 +01002107 resetTitleIconAndProgress();
Leon Scroggins654899b2010-06-25 16:25:23 -04002108 updateLockIconToLatest();
Elliott Slaughtere440a882010-08-20 13:54:45 -07002109
2110 if (!mTabControl.hasAnyOpenIncognitoTabs()) {
2111 WebView.cleanupPrivateBrowsingFiles(this);
2112 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002113 }
2114
Leon Scrogginsdcc5eeb2010-02-23 17:26:37 -05002115 /* package */ void goBackOnePageOrQuit() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002116 Tab current = mTabControl.getCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002117 if (current == null) {
2118 /*
2119 * Instead of finishing the activity, simply push this to the back
2120 * of the stack and let ActivityManager to choose the foreground
2121 * activity. As BrowserActivity is singleTask, it will be always the
2122 * root of the task. So we can use either true or false for
2123 * moveTaskToBack().
2124 */
2125 moveTaskToBack(true);
Grace Kloba00d85e72009-09-23 18:50:05 -07002126 return;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002127 }
2128 WebView w = current.getWebView();
2129 if (w.canGoBack()) {
2130 w.goBack();
2131 } else {
2132 // Check to see if we are closing a window that was created by
2133 // another window. If so, we switch back to that window.
Grace Kloba22ac16e2009-10-07 18:00:23 -07002134 Tab parent = current.getParentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002135 if (parent != null) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04002136 switchToTab(mTabControl.getTabIndex(parent));
2137 // Now we close the other tab
2138 closeTab(current);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002139 } else {
2140 if (current.closeOnExit()) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002141 // force the tab's inLoad() to be false as we are going to
2142 // either finish the activity or remove the tab. This will
2143 // ensure pauseWebViewTimers() taking action.
2144 mTabControl.getCurrentTab().clearInLoad();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002145 if (mTabControl.getTabCount() == 1) {
2146 finish();
2147 return;
2148 }
Mike Reed7bfa63b2009-05-28 11:08:32 -04002149 // call pauseWebViewTimers() now, we won't be able to call
2150 // it in onPause() as the WebView won't be valid.
Grace Klobaec1b5ad2009-08-18 08:42:32 -07002151 // Temporarily change mActivityInPause to be true as
2152 // pauseWebViewTimers() will do nothing if mActivityInPause
2153 // is false.
Grace Kloba918e1d72009-08-13 14:55:06 -07002154 boolean savedState = mActivityInPause;
2155 if (savedState) {
Grace Klobaec1b5ad2009-08-18 08:42:32 -07002156 Log.e(LOGTAG, "BrowserActivity is already paused "
2157 + "while handing goBackOnePageOrQuit.");
Grace Kloba918e1d72009-08-13 14:55:06 -07002158 }
2159 mActivityInPause = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -04002160 pauseWebViewTimers();
Grace Kloba918e1d72009-08-13 14:55:06 -07002161 mActivityInPause = savedState;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002162 removeTabFromContentView(current);
2163 mTabControl.removeTab(current);
2164 }
2165 /*
2166 * Instead of finishing the activity, simply push this to the back
2167 * of the stack and let ActivityManager to choose the foreground
2168 * activity. As BrowserActivity is singleTask, it will be always the
2169 * root of the task. So we can use either true or false for
2170 * moveTaskToBack().
2171 */
2172 moveTaskToBack(true);
2173 }
2174 }
2175 }
2176
Grace Kloba22ac16e2009-10-07 18:00:23 -07002177 boolean isMenuDown() {
2178 return mMenuIsDown;
2179 }
2180
Grace Kloba5942df02009-09-18 11:48:29 -07002181 @Override
2182 public boolean onKeyDown(int keyCode, KeyEvent event) {
Leon Scrogginsf65b50d2009-12-08 10:44:28 -05002183 // Even if MENU is already held down, we need to call to super to open
2184 // the IME on long press.
2185 if (KeyEvent.KEYCODE_MENU == keyCode) {
2186 mMenuIsDown = true;
2187 return super.onKeyDown(keyCode, event);
2188 }
Grace Kloba5942df02009-09-18 11:48:29 -07002189 // The default key mode is DEFAULT_KEYS_SEARCH_LOCAL. As the MENU is
2190 // still down, we don't want to trigger the search. Pretend to consume
2191 // the key and do nothing.
2192 if (mMenuIsDown) return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002193
Grace Kloba5942df02009-09-18 11:48:29 -07002194 switch(keyCode) {
Grace Kloba5942df02009-09-18 11:48:29 -07002195 case KeyEvent.KEYCODE_SPACE:
Grace Klobada0fe552009-09-22 18:17:24 -07002196 // WebView/WebTextView handle the keys in the KeyDown. As
2197 // the Activity's shortcut keys are only handled when WebView
2198 // doesn't, have to do it in onKeyDown instead of onKeyUp.
2199 if (event.isShiftPressed()) {
2200 getTopWindow().pageUp(false);
2201 } else {
2202 getTopWindow().pageDown(false);
2203 }
Grace Kloba5942df02009-09-18 11:48:29 -07002204 return true;
2205 case KeyEvent.KEYCODE_BACK:
2206 if (event.getRepeatCount() == 0) {
2207 event.startTracking();
2208 return true;
2209 } else if (mCustomView == null && mActiveTabsPage == null
Michael Kolbe421c242010-10-04 19:29:01 -07002210 && mComboView == null
Grace Kloba5942df02009-09-18 11:48:29 -07002211 && event.isLongPress()) {
Michael Kolbe421c242010-10-04 19:29:01 -07002212 bookmarksOrHistoryPicker(true);
Grace Kloba5942df02009-09-18 11:48:29 -07002213 return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002214 }
Grace Kloba5942df02009-09-18 11:48:29 -07002215 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002216 }
Grace Kloba5942df02009-09-18 11:48:29 -07002217 return super.onKeyDown(keyCode, event);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002218 }
2219
Grace Kloba5942df02009-09-18 11:48:29 -07002220 @Override
2221 public boolean onKeyUp(int keyCode, KeyEvent event) {
2222 switch(keyCode) {
2223 case KeyEvent.KEYCODE_MENU:
2224 mMenuIsDown = false;
2225 break;
Grace Kloba5942df02009-09-18 11:48:29 -07002226 case KeyEvent.KEYCODE_BACK:
2227 if (event.isTracking() && !event.isCanceled()) {
2228 if (mCustomView != null) {
2229 // if a custom view is showing, hide it
Grace Kloba22ac16e2009-10-07 18:00:23 -07002230 mTabControl.getCurrentWebView().getWebChromeClient()
2231 .onHideCustomView();
Grace Kloba5942df02009-09-18 11:48:29 -07002232 } else if (mActiveTabsPage != null) {
2233 // if tab page is showing, hide it
2234 removeActiveTabPage(true);
Michael Kolbe421c242010-10-04 19:29:01 -07002235 } else if (mComboView != null) {
Michael Kolb370a4f32010-10-06 10:45:32 -07002236 if (!mComboView.onBackPressed()) {
2237 removeComboView();
2238 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002239 } else {
Grace Kloba5942df02009-09-18 11:48:29 -07002240 WebView subwindow = mTabControl.getCurrentSubWindow();
2241 if (subwindow != null) {
2242 if (subwindow.canGoBack()) {
2243 subwindow.goBack();
2244 } else {
2245 dismissSubWindow(mTabControl.getCurrentTab());
2246 }
2247 } else {
2248 goBackOnePageOrQuit();
2249 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002250 }
Grace Kloba5942df02009-09-18 11:48:29 -07002251 return true;
2252 }
2253 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002254 }
Grace Kloba5942df02009-09-18 11:48:29 -07002255 return super.onKeyUp(keyCode, event);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002256 }
2257
Leon Scroggins68579392009-09-15 15:31:54 -04002258 /* package */ void stopLoading() {
Ben Murdochb7cc8b42009-09-28 10:59:09 +01002259 mDidStopLoad = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002260 resetTitleAndRevertLockIcon();
2261 WebView w = getTopWindow();
2262 w.stopLoading();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002263 // FIXME: before refactor, it is using mWebViewClient. So I keep the
2264 // same logic here. But for subwindow case, should we call into the main
2265 // WebView's onPageFinished as we never call its onPageStarted and if
2266 // the page finishes itself, we don't call onPageFinished.
2267 mTabControl.getCurrentWebView().getWebViewClient().onPageFinished(w,
2268 w.getUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08002269
2270 cancelStopToast();
2271 mStopToast = Toast
2272 .makeText(this, R.string.stopping, Toast.LENGTH_SHORT);
2273 mStopToast.show();
2274 }
2275
Grace Kloba22ac16e2009-10-07 18:00:23 -07002276 boolean didUserStopLoading() {
2277 return mDidStopLoad;
2278 }
2279
The Android Open Source Project0c908882009-03-03 19:32:16 -08002280 private void cancelStopToast() {
2281 if (mStopToast != null) {
2282 mStopToast.cancel();
2283 mStopToast = null;
2284 }
2285 }
2286
Grace Kloba22ac16e2009-10-07 18:00:23 -07002287 // called by a UI or non-UI thread to post the message
2288 public void postMessage(int what, int arg1, int arg2, Object obj,
2289 long delayMillis) {
2290 mHandler.sendMessageDelayed(mHandler.obtainMessage(what, arg1, arg2,
2291 obj), delayMillis);
2292 }
2293
2294 // called by a UI or non-UI thread to remove the message
2295 void removeMessages(int what, Object object) {
2296 mHandler.removeMessages(what, object);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002297 }
2298
2299 // public message ids
2300 public final static int LOAD_URL = 1001;
2301 public final static int STOP_LOAD = 1002;
2302
2303 // Message Ids
2304 private static final int FOCUS_NODE_HREF = 102;
Grace Kloba92c18a52009-07-31 23:48:32 -07002305 private static final int RELEASE_WAKELOCK = 107;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002306
Grace Kloba22ac16e2009-10-07 18:00:23 -07002307 static final int UPDATE_BOOKMARK_THUMBNAIL = 108;
Ben Murdoch2694e232009-09-29 09:41:11 +01002308
Ben Murdocheecb4e62010-07-06 16:30:38 +01002309 private static final int TOUCH_ICON_DOWNLOADED = 109;
2310
Michael Kolb300b7f02010-08-25 13:47:24 -07002311 private static final int OPEN_BOOKMARKS = 201;
2312
The Android Open Source Project0c908882009-03-03 19:32:16 -08002313 // Private handler for handling javascript and saving passwords
2314 private Handler mHandler = new Handler() {
2315
Michael Kolbe0a36662010-06-29 10:37:12 -07002316 @Override
The Android Open Source Project0c908882009-03-03 19:32:16 -08002317 public void handleMessage(Message msg) {
2318 switch (msg.what) {
Michael Kolb300b7f02010-08-25 13:47:24 -07002319 case OPEN_BOOKMARKS:
Michael Kolbe421c242010-10-04 19:29:01 -07002320 bookmarksOrHistoryPicker(false);
Michael Kolb300b7f02010-08-25 13:47:24 -07002321 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002322 case FOCUS_NODE_HREF:
Ben Murdoch2694e232009-09-29 09:41:11 +01002323 {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002324 String url = (String) msg.getData().get("url");
Ben Murdoch90d088c2009-11-17 18:14:04 +00002325 String title = (String) msg.getData().get("title");
The Android Open Source Project0c908882009-03-03 19:32:16 -08002326 if (url == null || url.length() == 0) {
2327 break;
2328 }
2329 HashMap focusNodeMap = (HashMap) msg.obj;
2330 WebView view = (WebView) focusNodeMap.get("webview");
2331 // Only apply the action if the top window did not change.
2332 if (getTopWindow() != view) {
2333 break;
2334 }
2335 switch (msg.arg1) {
2336 case R.id.open_context_menu_id:
2337 case R.id.view_image_context_menu_id:
Leon Scroggins92472e82010-02-17 16:32:28 -05002338 loadUrlFromContext(getTopWindow(), url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002339 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002340 case R.id.bookmark_context_menu_id:
2341 Intent intent = new Intent(BrowserActivity.this,
2342 AddBookmarkPage.class);
2343 intent.putExtra("url", url);
Ben Murdoch90d088c2009-11-17 18:14:04 +00002344 intent.putExtra("title", title);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002345 startActivity(intent);
2346 break;
2347 case R.id.share_link_context_menu_id:
Leon Scroggins3e204452010-05-10 11:06:03 -04002348 sharePage(BrowserActivity.this, title, url, null,
Leon Scroggins96afcb12009-12-10 12:35:56 -05002349 null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002350 break;
2351 case R.id.copy_link_context_menu_id:
2352 copy(url);
2353 break;
2354 case R.id.save_link_context_menu_id:
2355 case R.id.download_context_menu_id:
2356 onDownloadStartNoStream(url, null, null, null, -1);
2357 break;
2358 }
2359 break;
Ben Murdoch2694e232009-09-29 09:41:11 +01002360 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002361
2362 case LOAD_URL:
Leon Scroggins92472e82010-02-17 16:32:28 -05002363 loadUrlFromContext(getTopWindow(), (String) msg.obj);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002364 break;
2365
2366 case STOP_LOAD:
2367 stopLoading();
2368 break;
2369
The Android Open Source Project0c908882009-03-03 19:32:16 -08002370 case RELEASE_WAKELOCK:
2371 if (mWakeLock.isHeld()) {
2372 mWakeLock.release();
Grace Kloba5d0e02e2009-10-05 15:15:36 -07002373 // if we reach here, Browser should be still in the
2374 // background loading after WAKELOCK_TIMEOUT (5-min).
2375 // To avoid burning the battery, stop loading.
2376 mTabControl.stopAllLoading();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002377 }
2378 break;
Ben Murdoch2694e232009-09-29 09:41:11 +01002379
2380 case UPDATE_BOOKMARK_THUMBNAIL:
2381 WebView view = (WebView) msg.obj;
2382 if (view != null) {
2383 updateScreenshot(view);
2384 }
2385 break;
Ben Murdocheecb4e62010-07-06 16:30:38 +01002386
2387 case TOUCH_ICON_DOWNLOADED:
2388 Bundle b = msg.getData();
2389 showSaveToHomescreenDialog(b.getString("url"),
2390 b.getString("title"),
2391 (Bitmap) b.getParcelable("touchIcon"),
2392 (Bitmap) b.getParcelable("favicon"));
2393 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002394 }
2395 }
2396 };
2397
Leon Scroggins96afcb12009-12-10 12:35:56 -05002398 /**
2399 * Share a page, providing the title, url, favicon, and a screenshot. Uses
2400 * an {@link Intent} to launch the Activity chooser.
2401 * @param c Context used to launch a new Activity.
2402 * @param title Title of the page. Stored in the Intent with
Paul Westbrook03e6d392010-02-12 10:33:29 -08002403 * {@link Intent#EXTRA_SUBJECT}
Leon Scroggins96afcb12009-12-10 12:35:56 -05002404 * @param url URL of the page. Stored in the Intent with
2405 * {@link Intent#EXTRA_TEXT}
2406 * @param favicon Bitmap of the favicon for the page. Stored in the Intent
2407 * with {@link Browser#EXTRA_SHARE_FAVICON}
2408 * @param screenshot Bitmap of a screenshot of the page. Stored in the
2409 * Intent with {@link Browser#EXTRA_SHARE_SCREENSHOT}
2410 */
2411 public static final void sharePage(Context c, String title, String url,
2412 Bitmap favicon, Bitmap screenshot) {
2413 Intent send = new Intent(Intent.ACTION_SEND);
2414 send.setType("text/plain");
2415 send.putExtra(Intent.EXTRA_TEXT, url);
Paul Westbrook03e6d392010-02-12 10:33:29 -08002416 send.putExtra(Intent.EXTRA_SUBJECT, title);
Leon Scroggins96afcb12009-12-10 12:35:56 -05002417 send.putExtra(Browser.EXTRA_SHARE_FAVICON, favicon);
2418 send.putExtra(Browser.EXTRA_SHARE_SCREENSHOT, screenshot);
2419 try {
2420 c.startActivity(Intent.createChooser(send, c.getString(
2421 R.string.choosertitle_sharevia)));
2422 } catch(android.content.ActivityNotFoundException ex) {
2423 // if no app handles it, do nothing
2424 }
2425 }
2426
Leon Scroggins89c6d362009-07-15 16:54:37 -04002427 private void updateScreenshot(WebView view) {
2428 // If this is a bookmarked site, add a screenshot to the database.
2429 // FIXME: When should we update? Every time?
2430 // FIXME: Would like to make sure there is actually something to
2431 // draw, but the API for that (WebViewCore.pictureReady()) is not
2432 // currently accessible here.
Ben Murdochaac7aa62009-09-17 16:57:40 +01002433
Ben Murdoch87cc65d2010-06-29 20:34:10 +01002434 final Bitmap bm = createScreenshot(view, getDesiredThumbnailWidth(this),
2435 getDesiredThumbnailHeight(this));
Patrick Scottcb192b52010-04-14 14:38:55 -04002436 if (bm == null) {
2437 return;
Leon Scroggins89c6d362009-07-15 16:54:37 -04002438 }
Patrick Scottcb192b52010-04-14 14:38:55 -04002439
2440 final ContentResolver cr = getContentResolver();
2441 final String url = view.getUrl();
2442 final String originalUrl = view.getOriginalUrl();
2443
2444 new AsyncTask<Void, Void, Void>() {
2445 @Override
2446 protected Void doInBackground(Void... unused) {
Jeff Hamilton1a805652010-09-07 12:36:30 -07002447 Cursor cursor = null;
Patrick Scottcb192b52010-04-14 14:38:55 -04002448 try {
Jeff Hamilton1a805652010-09-07 12:36:30 -07002449 cursor = Bookmarks.queryCombinedForUrl(cr, originalUrl, url);
2450 if (cursor != null && cursor.moveToFirst()) {
2451 final ByteArrayOutputStream os = new ByteArrayOutputStream();
2452 bm.compress(Bitmap.CompressFormat.PNG, 100, os);
2453
2454 ContentValues values = new ContentValues();
2455 values.put(Images.THUMBNAIL, os.toByteArray());
2456 values.put(Images.URL, cursor.getString(0));
2457
2458 do {
2459 cr.update(Images.CONTENT_URI, values, null, null);
2460 } while (cursor.moveToNext());
Patrick Scottcb192b52010-04-14 14:38:55 -04002461 }
2462 } catch (IllegalStateException e) {
2463 // Ignore
2464 } finally {
Jeff Hamilton1a805652010-09-07 12:36:30 -07002465 if (cursor != null) cursor.close();
Patrick Scottcb192b52010-04-14 14:38:55 -04002466 }
2467 return null;
2468 }
2469 }.execute();
Leon Scroggins89c6d362009-07-15 16:54:37 -04002470 }
2471
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002472 /**
Leon Scrogginsf8551612009-09-24 16:06:02 -04002473 * Return the desired width for thumbnail screenshots, which are stored in
2474 * the database, and used on the bookmarks screen.
2475 * @param context Context for finding out the density of the screen.
Jeff Hamiltonf3026372010-08-19 00:12:27 -05002476 * @return desired width for thumbnail screenshot.
Leon Scrogginsf8551612009-09-24 16:06:02 -04002477 */
2478 /* package */ static int getDesiredThumbnailWidth(Context context) {
Jeff Hamiltonf3026372010-08-19 00:12:27 -05002479 return context.getResources().getDimensionPixelOffset(R.dimen.bookmarkThumbnailWidth);
Leon Scrogginsf8551612009-09-24 16:06:02 -04002480 }
2481
2482 /**
2483 * Return the desired height for thumbnail screenshots, which are stored in
2484 * the database, and used on the bookmarks screen.
2485 * @param context Context for finding out the density of the screen.
Jeff Hamiltonf3026372010-08-19 00:12:27 -05002486 * @return desired height for thumbnail screenshot.
Leon Scrogginsf8551612009-09-24 16:06:02 -04002487 */
2488 /* package */ static int getDesiredThumbnailHeight(Context context) {
Jeff Hamiltonf3026372010-08-19 00:12:27 -05002489 return context.getResources().getDimensionPixelOffset(R.dimen.bookmarkThumbnailHeight);
Leon Scrogginsf8551612009-09-24 16:06:02 -04002490 }
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002491
Ben Murdoch87cc65d2010-06-29 20:34:10 +01002492 private Bitmap createScreenshot(WebView view, int width, int height) {
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002493 Picture thumbnail = view.capturePicture();
Leon Scroggins45800572009-09-29 16:38:47 -04002494 if (thumbnail == null) {
2495 return null;
2496 }
Ben Murdoch87cc65d2010-06-29 20:34:10 +01002497 Bitmap bm = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002498 Canvas canvas = new Canvas(bm);
2499 // May need to tweak these values to determine what is the
2500 // best scale factor
Ben Murdoch2694e232009-09-29 09:41:11 +01002501 int thumbnailWidth = thumbnail.getWidth();
Ben Murdochae59c3f2009-10-20 18:30:28 +01002502 int thumbnailHeight = thumbnail.getHeight();
2503 float scaleFactorX = 1.0f;
2504 float scaleFactorY = 1.0f;
Ben Murdoch2694e232009-09-29 09:41:11 +01002505 if (thumbnailWidth > 0) {
Ben Murdoch87cc65d2010-06-29 20:34:10 +01002506 scaleFactorX = (float) width / (float)thumbnailWidth;
Ben Murdochae59c3f2009-10-20 18:30:28 +01002507 } else {
2508 return null;
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002509 }
Ben Murdochae59c3f2009-10-20 18:30:28 +01002510
2511 if (view.getWidth() > view.getHeight() &&
2512 thumbnailHeight < view.getHeight() && thumbnailHeight > 0) {
2513 // If the device is in landscape and the page is shorter
2514 // than the height of the view, stretch the thumbnail to fill the
2515 // space.
Ben Murdoch87cc65d2010-06-29 20:34:10 +01002516 scaleFactorY = (float) height / (float)thumbnailHeight;
Ben Murdochae59c3f2009-10-20 18:30:28 +01002517 } else {
2518 // In the portrait case, this looks nice.
2519 scaleFactorY = scaleFactorX;
2520 }
2521
2522 canvas.scale(scaleFactorX, scaleFactorY);
2523
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002524 thumbnail.draw(canvas);
2525 return bm;
2526 }
2527
The Android Open Source Project0c908882009-03-03 19:32:16 -08002528 // -------------------------------------------------------------------------
Grace Kloba22ac16e2009-10-07 18:00:23 -07002529 // Helper function for WebViewClient.
The Android Open Source Project0c908882009-03-03 19:32:16 -08002530 //-------------------------------------------------------------------------
2531
2532 // Use in overrideUrlLoading
2533 /* package */ final static String SCHEME_WTAI = "wtai://wp/";
2534 /* package */ final static String SCHEME_WTAI_MC = "wtai://wp/mc;";
2535 /* package */ final static String SCHEME_WTAI_SD = "wtai://wp/sd;";
2536 /* package */ final static String SCHEME_WTAI_AP = "wtai://wp/ap;";
2537
Leon Scroggins92472e82010-02-17 16:32:28 -05002538 // Keep this initial progress in sync with initialProgressValue (* 100)
2539 // in ProgressTracker.cpp
2540 private final static int INITIAL_PROGRESS = 10;
2541
Grace Kloba22ac16e2009-10-07 18:00:23 -07002542 void onPageStarted(WebView view, String url, Bitmap favicon) {
2543 // when BrowserActivity just starts, onPageStarted may be called before
2544 // onResume as it is triggered from onCreate. Call resumeWebViewTimers
2545 // to start the timer. As we won't switch tabs while an activity is in
2546 // pause state, we can ensure calling resume and pause in pair.
2547 if (mActivityInPause) resumeWebViewTimers();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002548
Grace Kloba22ac16e2009-10-07 18:00:23 -07002549 resetLockIcon(url);
2550 setUrlTitle(url, null);
2551 setFavicon(favicon);
Leon Scroggins8cf8f682009-11-04 11:13:50 -08002552 // Show some progress so that the user knows the page is beginning to
2553 // load
Leon Scroggins92472e82010-02-17 16:32:28 -05002554 onProgressChanged(view, INITIAL_PROGRESS);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002555 mDidStopLoad = false;
Grace Kloba22ac16e2009-10-07 18:00:23 -07002556 if (!mIsNetworkUp) createAndShowNetworkDialog();
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04002557 endActionMode();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002558 if (mSettings.isTracing()) {
2559 String host;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002560 try {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002561 WebAddress uri = new WebAddress(url);
Bjorn Bringert131ab512010-10-12 16:25:47 +01002562 host = uri.getHost();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002563 } catch (android.net.ParseException ex) {
2564 host = "browser";
The Android Open Source Project0c908882009-03-03 19:32:16 -08002565 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002566 host = host.replace('.', '_');
2567 host += ".trace";
2568 mInTrace = true;
2569 Debug.startMethodTracing(host, 20 * 1024 * 1024);
2570 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002571
Grace Kloba22ac16e2009-10-07 18:00:23 -07002572 // Performance probe
2573 if (false) {
2574 mStart = SystemClock.uptimeMillis();
2575 mProcessStart = Process.getElapsedCpuTime();
2576 long[] sysCpu = new long[7];
2577 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2578 sysCpu, null)) {
2579 mUserStart = sysCpu[0] + sysCpu[1];
2580 mSystemStart = sysCpu[2];
2581 mIdleStart = sysCpu[3];
2582 mIrqStart = sysCpu[4] + sysCpu[5] + sysCpu[6];
2583 }
2584 mUiStart = SystemClock.currentThreadTimeMillis();
2585 }
2586 }
2587
2588 void onPageFinished(WebView view, String url) {
2589 // Reset the title and icon in case we stopped a provisional load.
2590 resetTitleAndIcon(view);
2591 // Update the lock icon image only once we are done loading
2592 updateLockIconToLatest();
2593 // pause the WebView timer and release the wake lock if it is finished
2594 // while BrowserActivity is in pause state.
2595 if (mActivityInPause && pauseWebViewTimers()) {
2596 if (mWakeLock.isHeld()) {
2597 mHandler.removeMessages(RELEASE_WAKELOCK);
2598 mWakeLock.release();
2599 }
2600 }
2601
2602 // Performance probe
2603 if (false) {
2604 long[] sysCpu = new long[7];
2605 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2606 sysCpu, null)) {
2607 String uiInfo = "UI thread used "
2608 + (SystemClock.currentThreadTimeMillis() - mUiStart)
2609 + " ms";
2610 if (LOGD_ENABLED) {
2611 Log.d(LOGTAG, uiInfo);
2612 }
2613 //The string that gets written to the log
2614 String performanceString = "It took total "
2615 + (SystemClock.uptimeMillis() - mStart)
2616 + " ms clock time to load the page."
2617 + "\nbrowser process used "
2618 + (Process.getElapsedCpuTime() - mProcessStart)
2619 + " ms, user processes used "
2620 + (sysCpu[0] + sysCpu[1] - mUserStart) * 10
2621 + " ms, kernel used "
2622 + (sysCpu[2] - mSystemStart) * 10
2623 + " ms, idle took " + (sysCpu[3] - mIdleStart) * 10
2624 + " ms and irq took "
2625 + (sysCpu[4] + sysCpu[5] + sysCpu[6] - mIrqStart)
2626 * 10 + " ms, " + uiInfo;
2627 if (LOGD_ENABLED) {
2628 Log.d(LOGTAG, performanceString + "\nWebpage: " + url);
2629 }
2630 if (url != null) {
2631 // strip the url to maintain consistency
2632 String newUrl = new String(url);
2633 if (newUrl.startsWith("http://www.")) {
2634 newUrl = newUrl.substring(11);
2635 } else if (newUrl.startsWith("http://")) {
2636 newUrl = newUrl.substring(7);
2637 } else if (newUrl.startsWith("https://www.")) {
2638 newUrl = newUrl.substring(12);
2639 } else if (newUrl.startsWith("https://")) {
2640 newUrl = newUrl.substring(8);
2641 }
2642 if (LOGD_ENABLED) {
2643 Log.d(LOGTAG, newUrl + " loaded");
2644 }
Grace Kloba5b078b52009-06-24 20:23:41 -07002645 }
2646 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002647 }
Grace Kloba5b078b52009-06-24 20:23:41 -07002648
Grace Kloba22ac16e2009-10-07 18:00:23 -07002649 if (mInTrace) {
2650 mInTrace = false;
2651 Debug.stopMethodTracing();
2652 }
2653 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002654
Grace Klobae7fe26b2010-06-28 16:23:33 -07002655 private void closeEmptyChildTab() {
2656 Tab current = mTabControl.getCurrentTab();
2657 if (current != null
2658 && current.getWebView().copyBackForwardList().getSize() == 0) {
2659 Tab parent = current.getParentTab();
2660 if (parent != null) {
2661 switchToTab(mTabControl.getTabIndex(parent));
2662 closeTab(current);
2663 }
2664 }
2665 }
2666
Grace Kloba22ac16e2009-10-07 18:00:23 -07002667 boolean shouldOverrideUrlLoading(WebView view, String url) {
Jeff Hamilton47654f42010-09-07 09:57:51 -05002668 if (view.isPrivateBrowsingEnabled()) {
2669 // Don't allow urls to leave the browser app when in private browsing mode
2670 loadUrl(view, url);
2671 return true;
2672 }
2673
Grace Kloba22ac16e2009-10-07 18:00:23 -07002674 if (url.startsWith(SCHEME_WTAI)) {
2675 // wtai://wp/mc;number
2676 // number=string(phone-number)
2677 if (url.startsWith(SCHEME_WTAI_MC)) {
2678 Intent intent = new Intent(Intent.ACTION_VIEW,
2679 Uri.parse(WebView.SCHEME_TEL +
2680 url.substring(SCHEME_WTAI_MC.length())));
2681 startActivity(intent);
Grace Klobae7fe26b2010-06-28 16:23:33 -07002682 // before leaving BrowserActivity, close the empty child tab.
2683 // If a new tab is created through JavaScript open to load this
2684 // url, we would like to close it as we will load this url in a
2685 // different Activity.
2686 closeEmptyChildTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002687 return true;
2688 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002689 // wtai://wp/sd;dtmf
2690 // dtmf=string(dialstring)
2691 if (url.startsWith(SCHEME_WTAI_SD)) {
2692 // TODO: only send when there is active voice connection
2693 return false;
2694 }
2695 // wtai://wp/ap;number;name
2696 // number=string(phone-number)
2697 // name=string
2698 if (url.startsWith(SCHEME_WTAI_AP)) {
2699 // TODO
2700 return false;
2701 }
2702 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002703
Grace Kloba22ac16e2009-10-07 18:00:23 -07002704 // The "about:" schemes are internal to the browser; don't want these to
2705 // be dispatched to other apps.
2706 if (url.startsWith("about:")) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002707 return false;
2708 }
2709
Jeff Davidson43610292010-07-16 16:03:58 -07002710 // If this is a Google search, attempt to add an RLZ string (if one isn't already present).
2711 if (rlzProviderPresent()) {
2712 Uri siteUri = Uri.parse(url);
2713 if (needsRlzString(siteUri)) {
2714 String rlz = null;
2715 Cursor cur = null;
2716 try {
2717 cur = getContentResolver().query(getRlzUri(), null, null, null, null);
2718 if (cur != null && cur.moveToFirst() && !cur.isNull(0)) {
2719 url = siteUri.buildUpon()
2720 .appendQueryParameter("rlz", cur.getString(0))
2721 .build().toString();
2722 }
2723 } finally {
2724 if (cur != null) {
2725 cur.close();
2726 }
2727 }
2728 loadUrl(view, url);
2729 return true;
2730 }
2731 }
2732
Grace Kloba22ac16e2009-10-07 18:00:23 -07002733 Intent intent;
2734 // perform generic parsing of the URI to turn it into an Intent.
2735 try {
2736 intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME);
2737 } catch (URISyntaxException ex) {
2738 Log.w("Browser", "Bad URI " + url + ": " + ex.getMessage());
2739 return false;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002740 }
2741
Grace Kloba22ac16e2009-10-07 18:00:23 -07002742 // check whether the intent can be resolved. If not, we will see
2743 // whether we can download it from the Market.
2744 if (getPackageManager().resolveActivity(intent, 0) == null) {
2745 String packagename = intent.getPackage();
2746 if (packagename != null) {
2747 intent = new Intent(Intent.ACTION_VIEW, Uri
2748 .parse("market://search?q=pname:" + packagename));
2749 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2750 startActivity(intent);
Grace Klobae7fe26b2010-06-28 16:23:33 -07002751 // before leaving BrowserActivity, close the empty child tab.
2752 // If a new tab is created through JavaScript open to load this
2753 // url, we would like to close it as we will load this url in a
2754 // different Activity.
2755 closeEmptyChildTab();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002756 return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002757 } else {
2758 return false;
2759 }
2760 }
2761
Grace Kloba22ac16e2009-10-07 18:00:23 -07002762 // sanitize the Intent, ensuring web pages can not bypass browser
2763 // security (only access to BROWSABLE activities).
2764 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2765 intent.setComponent(null);
2766 try {
2767 if (startActivityIfNeeded(intent, -1)) {
Grace Klobae7fe26b2010-06-28 16:23:33 -07002768 // before leaving BrowserActivity, close the empty child tab.
2769 // If a new tab is created through JavaScript open to load this
2770 // url, we would like to close it as we will load this url in a
2771 // different Activity.
2772 closeEmptyChildTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002773 return true;
2774 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002775 } catch (ActivityNotFoundException ex) {
2776 // ignore the error. If no application can handle the URL,
2777 // eg about:blank, assume the browser can handle it.
2778 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002779
Grace Kloba22ac16e2009-10-07 18:00:23 -07002780 if (mMenuIsDown) {
Michael Kolb68792c82010-08-09 16:39:18 -07002781 openTab(url, false);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002782 closeOptionsMenu();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002783 return true;
2784 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002785 return false;
2786 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002787
Jeff Davidson43610292010-07-16 16:03:58 -07002788 // Determine whether the RLZ provider is present on the system.
2789 private boolean rlzProviderPresent() {
2790 if (mIsProviderPresent == null) {
2791 PackageManager pm = getPackageManager();
2792 mIsProviderPresent = pm.resolveContentProvider(BrowserSettings.RLZ_PROVIDER, 0) != null;
2793 }
2794 return mIsProviderPresent;
2795 }
2796
2797 // Retrieve the RLZ access point string and cache the URI used to retrieve RLZ values.
2798 private Uri getRlzUri() {
2799 if (mRlzUri == null) {
2800 String ap = getResources().getString(R.string.rlz_access_point);
2801 mRlzUri = Uri.withAppendedPath(BrowserSettings.RLZ_PROVIDER_URI, ap);
2802 }
2803 return mRlzUri;
2804 }
2805
2806 // Determine if this URI appears to be for a Google search and does not have an RLZ parameter.
2807 // Taken largely from Chrome source, src/chrome/browser/google_url_tracker.cc
2808 private static boolean needsRlzString(Uri uri) {
Bill Napierc50e71a2010-08-27 14:03:03 -07002809 String scheme = uri.getScheme();
2810 if (("http".equals(scheme) || "https".equals(scheme)) &&
2811 (uri.getQueryParameter("q") != null) && (uri.getQueryParameter("rlz") == null)) {
Jeff Davidson43610292010-07-16 16:03:58 -07002812 String host = uri.getHost();
2813 if (host == null) {
2814 return false;
2815 }
2816 String[] hostComponents = host.split("\\.");
2817
2818 if (hostComponents.length < 2) {
2819 return false;
2820 }
2821 int googleComponent = hostComponents.length - 2;
2822 String component = hostComponents[googleComponent];
2823 if (!"google".equals(component)) {
2824 if (hostComponents.length < 3 ||
2825 (!"co".equals(component) && !"com".equals(component))) {
2826 return false;
2827 }
2828 googleComponent = hostComponents.length - 3;
2829 if (!"google".equals(hostComponents[googleComponent])) {
2830 return false;
2831 }
2832 }
2833
2834 // Google corp network handling.
2835 if (googleComponent > 0 && "corp".equals(hostComponents[googleComponent - 1])) {
2836 return false;
2837 }
2838
2839 return true;
2840 }
2841 return false;
2842 }
2843
Grace Kloba22ac16e2009-10-07 18:00:23 -07002844 // -------------------------------------------------------------------------
2845 // Helper function for WebChromeClient
2846 // -------------------------------------------------------------------------
The Android Open Source Project0c908882009-03-03 19:32:16 -08002847
Grace Kloba22ac16e2009-10-07 18:00:23 -07002848 void onProgressChanged(WebView view, int newProgress) {
Michael Kolba2b2ba82010-08-04 17:54:03 -07002849
2850 // On the phone, the fake title bar will always cover up the
2851 // regular title bar (or the regular one is offscreen), so only the
2852 // fake title bar needs to change its progress
2853 mFakeTitleBar.setProgress(newProgress);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002854
Grace Kloba22ac16e2009-10-07 18:00:23 -07002855 if (newProgress == 100) {
2856 // onProgressChanged() may continue to be called after the main
2857 // frame has finished loading, as any remaining sub frames continue
2858 // to load. We'll only get called once though with newProgress as
2859 // 100 when everything is loaded. (onPageFinished is called once
2860 // when the main frame completes loading regardless of the state of
2861 // any sub frames so calls to onProgressChanges may continue after
2862 // onPageFinished has executed)
2863 if (mInLoad) {
2864 mInLoad = false;
Leon Scrogginsa27ff192009-09-14 12:58:04 -04002865 updateInLoadMenuItems();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002866 // If the options menu is open, leave the title bar
2867 if (!mOptionsMenuOpen || !mIconView) {
2868 hideFakeTitleBar();
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07002869 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002870 }
Leon Scrogginsaa37e7f2010-03-05 11:51:20 -05002871 } else {
2872 if (!mInLoad) {
2873 // onPageFinished may have already been called but a subframe is
2874 // still loading and updating the progress. Reset mInLoad and
2875 // update the menu items.
2876 mInLoad = true;
2877 updateInLoadMenuItems();
2878 }
2879 // When the page first begins to load, the Activity may still be
2880 // paused, in which case showFakeTitleBar will do nothing. Call
2881 // again as the page continues to load so that it will be shown.
2882 // (Calling it will the fake title bar is already showing will also
2883 // do nothing.
Grace Kloba22ac16e2009-10-07 18:00:23 -07002884 if (!mOptionsMenuOpen || mIconView) {
2885 // This page has begun to load, so show the title bar
2886 showFakeTitleBar();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002887 }
2888 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002889 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002890
Grace Kloba22ac16e2009-10-07 18:00:23 -07002891 void onShowCustomView(View view, WebChromeClient.CustomViewCallback callback) {
Derek Sollenberger8ff57db2009-12-08 15:39:55 -05002892 // if a view already exists then immediately terminate the new one
2893 if (mCustomView != null) {
2894 callback.onCustomViewHidden();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002895 return;
Derek Sollenberger8ff57db2009-12-08 15:39:55 -05002896 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002897
2898 // Add the custom view to its container.
2899 mCustomViewContainer.addView(view, COVER_SCREEN_GRAVITY_CENTER);
2900 mCustomView = view;
2901 mCustomViewCallback = callback;
2902 // Save the menu state and set it to empty while the custom
2903 // view is showing.
2904 mOldMenuState = mMenuState;
2905 mMenuState = EMPTY_MENU;
2906 // Hide the content view.
2907 mContentView.setVisibility(View.GONE);
2908 // Finally show the custom view container.
Andrei Popescu163ab742009-10-20 17:58:23 +01002909 setStatusBarVisibility(false);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002910 mCustomViewContainer.setVisibility(View.VISIBLE);
2911 mCustomViewContainer.bringToFront();
2912 }
2913
2914 void onHideCustomView() {
2915 if (mCustomView == null)
2916 return;
2917
2918 // Hide the custom view.
2919 mCustomView.setVisibility(View.GONE);
2920 // Remove the custom view from its container.
2921 mCustomViewContainer.removeView(mCustomView);
2922 mCustomView = null;
2923 // Reset the old menu state.
2924 mMenuState = mOldMenuState;
2925 mOldMenuState = EMPTY_MENU;
2926 mCustomViewContainer.setVisibility(View.GONE);
2927 mCustomViewCallback.onCustomViewHidden();
2928 // Show the content view.
Andrei Popescu163ab742009-10-20 17:58:23 +01002929 setStatusBarVisibility(true);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002930 mContentView.setVisibility(View.VISIBLE);
2931 }
2932
2933 Bitmap getDefaultVideoPoster() {
2934 if (mDefaultVideoPoster == null) {
2935 mDefaultVideoPoster = BitmapFactory.decodeResource(
2936 getResources(), R.drawable.default_video_poster);
Patrick Scott3918d442009-08-04 13:22:29 -04002937 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002938 return mDefaultVideoPoster;
2939 }
Patrick Scott3918d442009-08-04 13:22:29 -04002940
Grace Kloba22ac16e2009-10-07 18:00:23 -07002941 View getVideoLoadingProgressView() {
2942 if (mVideoProgressView == null) {
2943 LayoutInflater inflater = LayoutInflater.from(BrowserActivity.this);
2944 mVideoProgressView = inflater.inflate(
2945 R.layout.video_loading_progress, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002946 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002947 return mVideoProgressView;
2948 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002949
Leon Scroggins8d5fa432009-10-02 15:55:59 -04002950 /*
2951 * The Object used to inform the WebView of the file to upload.
2952 */
2953 private ValueCallback<Uri> mUploadMessage;
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002954 private String mCameraFilePath;
Leon Scroggins8d5fa432009-10-02 15:55:59 -04002955
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002956 void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
2957
2958 final String imageMimeType = "image/*";
Ben Murdoch6af492a2010-06-15 12:38:17 +01002959 final String videoMimeType = "video/*";
Ben Murdoch039bd472010-07-21 21:26:57 +01002960 final String audioMimeType = "audio/*";
Ben Murdochb50d7402010-07-16 12:42:22 +01002961 final String mediaSourceKey = "capture";
Ben Murdoch6af492a2010-06-15 12:38:17 +01002962 final String mediaSourceValueCamera = "camera";
Ben Murdochb50d7402010-07-16 12:42:22 +01002963 final String mediaSourceValueFileSystem = "filesystem";
Ben Murdoch6af492a2010-06-15 12:38:17 +01002964 final String mediaSourceValueCamcorder = "camcorder";
Ben Murdoch039bd472010-07-21 21:26:57 +01002965 final String mediaSourceValueMicrophone = "microphone";
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002966
Ben Murdoch039bd472010-07-21 21:26:57 +01002967 // media source can be 'filesystem' or 'camera' or 'camcorder' or 'microphone'.
Ben Murdoch6af492a2010-06-15 12:38:17 +01002968 String mediaSource = "";
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002969
Ben Murdoch6af492a2010-06-15 12:38:17 +01002970 // We add the camera intent if there was no accept type (or '*/*' or 'image/*').
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002971 boolean addCameraIntent = true;
Ben Murdoch6af492a2010-06-15 12:38:17 +01002972 // We add the camcorder intent if there was no accept type (or '*/*' or 'video/*').
2973 boolean addCamcorderIntent = true;
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002974
Ben Murdoch6af492a2010-06-15 12:38:17 +01002975 if (mUploadMessage != null) {
2976 // Already a file picker operation in progress.
2977 return;
2978 }
2979
Grace Kloba22ac16e2009-10-07 18:00:23 -07002980 mUploadMessage = uploadMsg;
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002981
2982 // Parse the accept type.
2983 String params[] = acceptType.split(";");
2984 String mimeType = params[0];
2985
2986 for (String p : params) {
2987 String[] keyValue = p.split("=");
2988 if (keyValue.length == 2) {
2989 // Process key=value parameters.
Ben Murdoch6af492a2010-06-15 12:38:17 +01002990 if (mediaSourceKey.equals(keyValue[0])) {
2991 mediaSource = keyValue[1];
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002992 }
2993 }
2994 }
2995
2996 // This intent will display the standard OPENABLE file picker.
Grace Kloba22ac16e2009-10-07 18:00:23 -07002997 Intent i = new Intent(Intent.ACTION_GET_CONTENT);
2998 i.addCategory(Intent.CATEGORY_OPENABLE);
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002999
3000 // Create an intent to add to the standard file picker that will
3001 // capture an image from the camera. We'll combine this intent with
3002 // the standard OPENABLE picker unless the web developer specifically
3003 // requested the camera or gallery be opened by passing a parameter
3004 // in the accept type.
3005 Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
3006 File externalDataDir = Environment.getExternalStoragePublicDirectory(
3007 Environment.DIRECTORY_DCIM);
3008 File cameraDataDir = new File(externalDataDir.getAbsolutePath() +
3009 File.separator + "browser-photos");
3010 cameraDataDir.mkdirs();
3011 mCameraFilePath = cameraDataDir.getAbsolutePath() + File.separator +
3012 System.currentTimeMillis() + ".jpg";
3013 cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(mCameraFilePath)));
3014
Ben Murdoch6af492a2010-06-15 12:38:17 +01003015 Intent camcorderIntent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
3016
Ben Murdoch039bd472010-07-21 21:26:57 +01003017 Intent soundRecIntent = new Intent(MediaStore.Audio.Media.RECORD_SOUND_ACTION);
3018
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003019 if (mimeType.equals(imageMimeType)) {
3020 i.setType(imageMimeType);
Ben Murdoch6af492a2010-06-15 12:38:17 +01003021 addCamcorderIntent = false;
3022 if (mediaSource.equals(mediaSourceValueCamera)) {
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003023 // Specified 'image/*' and requested the camera, so go ahead and launch the camera
3024 // directly.
3025 BrowserActivity.this.startActivityForResult(cameraIntent, FILE_SELECTED);
3026 return;
Ben Murdochb50d7402010-07-16 12:42:22 +01003027 } else if (mediaSource.equals(mediaSourceValueFileSystem)) {
3028 // Specified filesytem as the source, so don't want to consider the camera.
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003029 addCameraIntent = false;
3030 }
Ben Murdoch6af492a2010-06-15 12:38:17 +01003031 } else if (mimeType.equals(videoMimeType)) {
3032 i.setType(videoMimeType);
3033 addCameraIntent = false;
3034 // The camcorder saves it's own file and returns it to us in the intent, so
3035 // we don't need to generate one here.
3036 mCameraFilePath = null;
3037
3038 if (mediaSource.equals(mediaSourceValueCamcorder)) {
Ben Murdoch039bd472010-07-21 21:26:57 +01003039 // Specified 'video/*' and requested the camcorder, so go ahead and launch the
3040 // camcorder directly.
Ben Murdoch6af492a2010-06-15 12:38:17 +01003041 BrowserActivity.this.startActivityForResult(camcorderIntent, FILE_SELECTED);
3042 return;
Ben Murdochb50d7402010-07-16 12:42:22 +01003043 } else if (mediaSource.equals(mediaSourceValueFileSystem)) {
3044 // Specified filesystem as the source, so don't want to consider the camcorder.
Ben Murdoch6af492a2010-06-15 12:38:17 +01003045 addCamcorderIntent = false;
3046 }
Ben Murdoch039bd472010-07-21 21:26:57 +01003047 } else if (mimeType.equals(audioMimeType)) {
3048 i.setType(audioMimeType);
3049 addCameraIntent = false;
3050 addCamcorderIntent = false;
3051 if (mediaSource.equals(mediaSourceValueMicrophone)) {
3052 // Specified 'audio/*' and requested microphone, so go ahead and launch the sound
3053 // recorder.
3054 BrowserActivity.this.startActivityForResult(soundRecIntent, FILE_SELECTED);
3055 return;
3056 }
3057 // On a default system, there is no single option to open an audio "gallery". Both the
3058 // sound recorder and music browser respond to the OPENABLE/audio/* intent unlike the
3059 // image/* and video/* OPENABLE intents where the image / video gallery are the only
3060 // respondants (and so the user is not prompted by default).
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003061 } else {
3062 i.setType("*/*");
3063 }
3064
Ben Murdoch6af492a2010-06-15 12:38:17 +01003065 // Combine the chooser and the extra choices (like camera or camcorder)
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003066 Intent chooser = new Intent(Intent.ACTION_CHOOSER);
3067 chooser.putExtra(Intent.EXTRA_INTENT, i);
3068
Ben Murdoch6af492a2010-06-15 12:38:17 +01003069 Vector<Intent> extraInitialIntents = new Vector<Intent>(0);
3070
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003071 if (addCameraIntent) {
Ben Murdoch6af492a2010-06-15 12:38:17 +01003072 extraInitialIntents.add(cameraIntent);
3073 }
3074
3075 if (addCamcorderIntent) {
3076 extraInitialIntents.add(camcorderIntent);
3077 }
3078
3079 if (extraInitialIntents.size() > 0) {
3080 Intent[] extraIntents = new Intent[extraInitialIntents.size()];
3081 chooser.putExtra(Intent.EXTRA_INITIAL_INTENTS, extraInitialIntents.toArray(extraIntents));
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003082 }
3083
3084 chooser.putExtra(Intent.EXTRA_TITLE, getString(R.string.choose_upload));
3085 BrowserActivity.this.startActivityForResult(chooser, FILE_SELECTED);
Grace Kloba22ac16e2009-10-07 18:00:23 -07003086 }
3087
3088 // -------------------------------------------------------------------------
3089 // Implement functions for DownloadListener
3090 // -------------------------------------------------------------------------
3091
The Android Open Source Project0c908882009-03-03 19:32:16 -08003092 /**
3093 * Notify the host application a download should be done, or that
3094 * the data should be streamed if a streaming viewer is available.
3095 * @param url The full url to the content that should be downloaded
3096 * @param contentDisposition Content-disposition http header, if
3097 * present.
3098 * @param mimetype The mimetype of the content reported by the server
3099 * @param contentLength The file size reported by the server
3100 */
3101 public void onDownloadStart(String url, String userAgent,
3102 String contentDisposition, String mimetype, long contentLength) {
3103 // if we're dealing wih A/V content that's not explicitly marked
3104 // for download, check if it's streamable.
3105 if (contentDisposition == null
Patrick Scotte1fb9662009-08-31 14:31:52 -04003106 || !contentDisposition.regionMatches(
3107 true, 0, "attachment", 0, 10)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003108 // query the package manager to see if there's a registered handler
3109 // that matches.
3110 Intent intent = new Intent(Intent.ACTION_VIEW);
3111 intent.setDataAndType(Uri.parse(url), mimetype);
Patrick Scotte1fb9662009-08-31 14:31:52 -04003112 ResolveInfo info = getPackageManager().resolveActivity(intent,
3113 PackageManager.MATCH_DEFAULT_ONLY);
3114 if (info != null) {
3115 ComponentName myName = getComponentName();
3116 // If we resolved to ourselves, we don't want to attempt to
3117 // load the url only to try and download it again.
3118 if (!myName.getPackageName().equals(
3119 info.activityInfo.packageName)
3120 || !myName.getClassName().equals(
3121 info.activityInfo.name)) {
3122 // someone (other than us) knows how to handle this mime
3123 // type with this scheme, don't download.
3124 try {
3125 startActivity(intent);
3126 return;
3127 } catch (ActivityNotFoundException ex) {
3128 if (LOGD_ENABLED) {
3129 Log.d(LOGTAG, "activity not found for " + mimetype
3130 + " over " + Uri.parse(url).getScheme(),
3131 ex);
3132 }
3133 // Best behavior is to fall back to a download in this
3134 // case
The Android Open Source Project0c908882009-03-03 19:32:16 -08003135 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003136 }
3137 }
3138 }
3139 onDownloadStartNoStream(url, userAgent, contentDisposition, mimetype, contentLength);
3140 }
3141
Kristian Monsenfa52d172010-03-25 18:29:21 +00003142 // This is to work around the fact that java.net.URI throws Exceptions
3143 // instead of just encoding URL's properly
3144 // Helper method for onDownloadStartNoStream
3145 private static String encodePath(String path) {
3146 char[] chars = path.toCharArray();
3147
3148 boolean needed = false;
3149 for (char c : chars) {
3150 if (c == '[' || c == ']') {
3151 needed = true;
3152 break;
3153 }
3154 }
3155 if (needed == false) {
3156 return path;
3157 }
3158
3159 StringBuilder sb = new StringBuilder("");
3160 for (char c : chars) {
3161 if (c == '[' || c == ']') {
3162 sb.append('%');
3163 sb.append(Integer.toHexString(c));
3164 } else {
3165 sb.append(c);
3166 }
3167 }
3168
3169 return sb.toString();
3170 }
3171
The Android Open Source Project0c908882009-03-03 19:32:16 -08003172 /**
3173 * Notify the host application a download should be done, even if there
3174 * is a streaming viewer available for thise type.
3175 * @param url The full url to the content that should be downloaded
3176 * @param contentDisposition Content-disposition http header, if
3177 * present.
3178 * @param mimetype The mimetype of the content reported by the server
3179 * @param contentLength The file size reported by the server
3180 */
3181 /*package */ void onDownloadStartNoStream(String url, String userAgent,
3182 String contentDisposition, String mimetype, long contentLength) {
3183
3184 String filename = URLUtil.guessFileName(url,
3185 contentDisposition, mimetype);
3186
3187 // Check to see if we have an SDCard
3188 String status = Environment.getExternalStorageState();
3189 if (!status.equals(Environment.MEDIA_MOUNTED)) {
3190 int title;
3191 String msg;
3192
3193 // Check to see if the SDCard is busy, same as the music app
3194 if (status.equals(Environment.MEDIA_SHARED)) {
3195 msg = getString(R.string.download_sdcard_busy_dlg_msg);
3196 title = R.string.download_sdcard_busy_dlg_title;
3197 } else {
3198 msg = getString(R.string.download_no_sdcard_dlg_msg, filename);
3199 title = R.string.download_no_sdcard_dlg_title;
3200 }
3201
3202 new AlertDialog.Builder(this)
3203 .setTitle(title)
3204 .setIcon(android.R.drawable.ic_dialog_alert)
3205 .setMessage(msg)
3206 .setPositiveButton(R.string.ok, null)
3207 .show();
3208 return;
3209 }
3210
Kristian Monsenfa52d172010-03-25 18:29:21 +00003211 // java.net.URI is a lot stricter than KURL so we have to encode some
3212 // extra characters. Fix for b 2538060 and b 1634719
3213 WebAddress webAddress;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003214 try {
Kristian Monsenfa52d172010-03-25 18:29:21 +00003215 webAddress = new WebAddress(url);
Bjorn Bringert131ab512010-10-12 16:25:47 +01003216 webAddress.setPath(encodePath(webAddress.getPath()));
The Android Open Source Project0c908882009-03-03 19:32:16 -08003217 } catch (Exception e) {
Kristian Monsenfa52d172010-03-25 18:29:21 +00003218 // This only happens for very bad urls, we want to chatch the
3219 // exception here
3220 Log.e(LOGTAG, "Exception trying to parse url:" + url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003221 return;
3222 }
3223
3224 // XXX: Have to use the old url since the cookies were stored using the
3225 // old percent-encoded url.
3226 String cookies = CookieManager.getInstance().getCookie(url);
3227
3228 ContentValues values = new ContentValues();
Kristian Monsenfa52d172010-03-25 18:29:21 +00003229 values.put(Downloads.Impl.COLUMN_URI, webAddress.toString());
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08003230 values.put(Downloads.Impl.COLUMN_COOKIE_DATA, cookies);
3231 values.put(Downloads.Impl.COLUMN_USER_AGENT, userAgent);
3232 values.put(Downloads.Impl.COLUMN_NOTIFICATION_PACKAGE,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003233 getPackageName());
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08003234 values.put(Downloads.Impl.COLUMN_NOTIFICATION_CLASS,
Leon Scrogginsa563d092010-04-19 16:53:49 -04003235 OpenDownloadReceiver.class.getCanonicalName());
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08003236 values.put(Downloads.Impl.COLUMN_VISIBILITY,
3237 Downloads.Impl.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
3238 values.put(Downloads.Impl.COLUMN_MIME_TYPE, mimetype);
3239 values.put(Downloads.Impl.COLUMN_FILE_NAME_HINT, filename);
Bjorn Bringert131ab512010-10-12 16:25:47 +01003240 values.put(Downloads.Impl.COLUMN_DESCRIPTION, webAddress.getHost());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003241 if (contentLength > 0) {
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08003242 values.put(Downloads.Impl.COLUMN_TOTAL_BYTES, contentLength);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003243 }
3244 if (mimetype == null) {
3245 // We must have long pressed on a link or image to download it. We
3246 // are not sure of the mimetype in this case, so do a head request
3247 new FetchUrlMimeType(this).execute(values);
3248 } else {
3249 final Uri contentUri =
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08003250 getContentResolver().insert(Downloads.Impl.CONTENT_URI, values);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003251 }
Leon Scroggins9191a7f2010-03-18 14:44:44 -04003252 Toast.makeText(this, R.string.download_pending, Toast.LENGTH_SHORT)
3253 .show();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003254 }
3255
Grace Kloba22ac16e2009-10-07 18:00:23 -07003256 // -------------------------------------------------------------------------
3257
The Android Open Source Project0c908882009-03-03 19:32:16 -08003258 /**
3259 * Resets the lock icon. This method is called when we start a new load and
3260 * know the url to be loaded.
3261 */
3262 private void resetLockIcon(String url) {
3263 // Save the lock-icon state (we revert to it if the load gets cancelled)
Grace Kloba22ac16e2009-10-07 18:00:23 -07003264 mTabControl.getCurrentTab().resetLockIcon(url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003265 updateLockIconImage(LOCK_ICON_UNSECURE);
3266 }
3267
The Android Open Source Project0c908882009-03-03 19:32:16 -08003268 /**
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04003269 * Update the lock icon to correspond to our latest state.
3270 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003271 private void updateLockIconToLatest() {
Leon Scroggins91f65fc2010-06-29 13:52:39 -04003272 Tab t = mTabControl.getCurrentTab();
3273 if (t != null) {
3274 updateLockIconImage(t.getLockIconType());
3275 }
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04003276 }
3277
3278 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08003279 * Updates the lock-icon image in the title-bar.
3280 */
3281 private void updateLockIconImage(int lockIconType) {
3282 Drawable d = null;
3283 if (lockIconType == LOCK_ICON_SECURE) {
3284 d = mSecLockIcon;
3285 } else if (lockIconType == LOCK_ICON_MIXED) {
3286 d = mMixLockIcon;
3287 }
Leon Scroggins68579392009-09-15 15:31:54 -04003288 mTitleBar.setLock(d);
Michael Kolba2b2ba82010-08-04 17:54:03 -07003289 mFakeTitleBar.setLock(d);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003290 }
3291
3292 /**
3293 * Displays a page-info dialog.
3294 * @param tab The tab to show info about
3295 * @param fromShowSSLCertificateOnError The flag that indicates whether
3296 * this dialog was opened from the SSL-certificate-on-error dialog or
3297 * not. This is important, since we need to know whether to return to
3298 * the parent dialog or simply dismiss.
3299 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003300 private void showPageInfo(final Tab tab,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003301 final boolean fromShowSSLCertificateOnError) {
3302 final LayoutInflater factory = LayoutInflater
3303 .from(this);
3304
3305 final View pageInfoView = factory.inflate(R.layout.page_info, null);
3306
3307 final WebView view = tab.getWebView();
3308
3309 String url = null;
3310 String title = null;
3311
3312 if (view == null) {
3313 url = tab.getUrl();
3314 title = tab.getTitle();
3315 } else if (view == mTabControl.getCurrentWebView()) {
3316 // Use the cached title and url if this is the current WebView
3317 url = mUrl;
3318 title = mTitle;
3319 } else {
3320 url = view.getUrl();
3321 title = view.getTitle();
3322 }
3323
3324 if (url == null) {
3325 url = "";
3326 }
3327 if (title == null) {
3328 title = "";
3329 }
3330
3331 ((TextView) pageInfoView.findViewById(R.id.address)).setText(url);
3332 ((TextView) pageInfoView.findViewById(R.id.title)).setText(title);
3333
3334 mPageInfoView = tab;
Leon Scrogginsc7b92f82010-01-11 18:17:31 -05003335 mPageInfoFromShowSSLCertificateOnError = fromShowSSLCertificateOnError;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003336
3337 AlertDialog.Builder alertDialogBuilder =
3338 new AlertDialog.Builder(this)
3339 .setTitle(R.string.page_info).setIcon(android.R.drawable.ic_dialog_info)
3340 .setView(pageInfoView)
3341 .setPositiveButton(
3342 R.string.ok,
3343 new DialogInterface.OnClickListener() {
3344 public void onClick(DialogInterface dialog,
3345 int whichButton) {
3346 mPageInfoDialog = null;
3347 mPageInfoView = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003348
3349 // if we came here from the SSL error dialog
3350 if (fromShowSSLCertificateOnError) {
3351 // go back to the SSL error dialog
3352 showSSLCertificateOnError(
3353 mSSLCertificateOnErrorView,
3354 mSSLCertificateOnErrorHandler,
3355 mSSLCertificateOnErrorError);
3356 }
3357 }
3358 })
3359 .setOnCancelListener(
3360 new DialogInterface.OnCancelListener() {
3361 public void onCancel(DialogInterface dialog) {
3362 mPageInfoDialog = null;
3363 mPageInfoView = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003364
3365 // if we came here from the SSL error dialog
3366 if (fromShowSSLCertificateOnError) {
3367 // go back to the SSL error dialog
3368 showSSLCertificateOnError(
3369 mSSLCertificateOnErrorView,
3370 mSSLCertificateOnErrorHandler,
3371 mSSLCertificateOnErrorError);
3372 }
3373 }
3374 });
3375
3376 // if we have a main top-level page SSL certificate set or a certificate
3377 // error
3378 if (fromShowSSLCertificateOnError ||
3379 (view != null && view.getCertificate() != null)) {
3380 // add a 'View Certificate' button
3381 alertDialogBuilder.setNeutralButton(
3382 R.string.view_certificate,
3383 new DialogInterface.OnClickListener() {
3384 public void onClick(DialogInterface dialog,
3385 int whichButton) {
3386 mPageInfoDialog = null;
3387 mPageInfoView = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003388
3389 // if we came here from the SSL error dialog
3390 if (fromShowSSLCertificateOnError) {
3391 // go back to the SSL error dialog
3392 showSSLCertificateOnError(
3393 mSSLCertificateOnErrorView,
3394 mSSLCertificateOnErrorHandler,
3395 mSSLCertificateOnErrorError);
3396 } else {
3397 // otherwise, display the top-most certificate from
3398 // the chain
3399 if (view.getCertificate() != null) {
3400 showSSLCertificate(tab);
3401 }
3402 }
3403 }
3404 });
3405 }
3406
3407 mPageInfoDialog = alertDialogBuilder.show();
3408 }
3409
3410 /**
3411 * Displays the main top-level page SSL certificate dialog
3412 * (accessible from the Page-Info dialog).
3413 * @param tab The tab to show certificate for.
3414 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003415 private void showSSLCertificate(final Tab tab) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003416 final View certificateView =
3417 inflateCertificateView(tab.getWebView().getCertificate());
3418 if (certificateView == null) {
3419 return;
3420 }
3421
3422 LayoutInflater factory = LayoutInflater.from(this);
3423
3424 final LinearLayout placeholder =
3425 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3426
3427 LinearLayout ll = (LinearLayout) factory.inflate(
3428 R.layout.ssl_success, placeholder);
3429 ((TextView)ll.findViewById(R.id.success))
3430 .setText(R.string.ssl_certificate_is_valid);
3431
3432 mSSLCertificateView = tab;
3433 mSSLCertificateDialog =
3434 new AlertDialog.Builder(this)
3435 .setTitle(R.string.ssl_certificate).setIcon(
3436 R.drawable.ic_dialog_browser_certificate_secure)
3437 .setView(certificateView)
3438 .setPositiveButton(R.string.ok,
3439 new DialogInterface.OnClickListener() {
3440 public void onClick(DialogInterface dialog,
3441 int whichButton) {
3442 mSSLCertificateDialog = null;
3443 mSSLCertificateView = null;
3444
3445 showPageInfo(tab, false);
3446 }
3447 })
3448 .setOnCancelListener(
3449 new DialogInterface.OnCancelListener() {
3450 public void onCancel(DialogInterface dialog) {
3451 mSSLCertificateDialog = null;
3452 mSSLCertificateView = null;
3453
3454 showPageInfo(tab, false);
3455 }
3456 })
3457 .show();
3458 }
3459
3460 /**
3461 * Displays the SSL error certificate dialog.
3462 * @param view The target web-view.
3463 * @param handler The SSL error handler responsible for cancelling the
3464 * connection that resulted in an SSL error or proceeding per user request.
3465 * @param error The SSL error object.
3466 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003467 void showSSLCertificateOnError(
The Android Open Source Project0c908882009-03-03 19:32:16 -08003468 final WebView view, final SslErrorHandler handler, final SslError error) {
3469
3470 final View certificateView =
3471 inflateCertificateView(error.getCertificate());
3472 if (certificateView == null) {
3473 return;
3474 }
3475
3476 LayoutInflater factory = LayoutInflater.from(this);
3477
3478 final LinearLayout placeholder =
3479 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3480
3481 if (error.hasError(SslError.SSL_UNTRUSTED)) {
3482 LinearLayout ll = (LinearLayout)factory
3483 .inflate(R.layout.ssl_warning, placeholder);
3484 ((TextView)ll.findViewById(R.id.warning))
3485 .setText(R.string.ssl_untrusted);
3486 }
3487
3488 if (error.hasError(SslError.SSL_IDMISMATCH)) {
3489 LinearLayout ll = (LinearLayout)factory
3490 .inflate(R.layout.ssl_warning, placeholder);
3491 ((TextView)ll.findViewById(R.id.warning))
3492 .setText(R.string.ssl_mismatch);
3493 }
3494
3495 if (error.hasError(SslError.SSL_EXPIRED)) {
3496 LinearLayout ll = (LinearLayout)factory
3497 .inflate(R.layout.ssl_warning, placeholder);
3498 ((TextView)ll.findViewById(R.id.warning))
3499 .setText(R.string.ssl_expired);
3500 }
3501
3502 if (error.hasError(SslError.SSL_NOTYETVALID)) {
3503 LinearLayout ll = (LinearLayout)factory
3504 .inflate(R.layout.ssl_warning, placeholder);
3505 ((TextView)ll.findViewById(R.id.warning))
3506 .setText(R.string.ssl_not_yet_valid);
3507 }
3508
3509 mSSLCertificateOnErrorHandler = handler;
3510 mSSLCertificateOnErrorView = view;
3511 mSSLCertificateOnErrorError = error;
3512 mSSLCertificateOnErrorDialog =
3513 new AlertDialog.Builder(this)
3514 .setTitle(R.string.ssl_certificate).setIcon(
3515 R.drawable.ic_dialog_browser_certificate_partially_secure)
3516 .setView(certificateView)
3517 .setPositiveButton(R.string.ok,
3518 new DialogInterface.OnClickListener() {
3519 public void onClick(DialogInterface dialog,
3520 int whichButton) {
3521 mSSLCertificateOnErrorDialog = null;
3522 mSSLCertificateOnErrorView = null;
3523 mSSLCertificateOnErrorHandler = null;
3524 mSSLCertificateOnErrorError = null;
3525
Grace Kloba22ac16e2009-10-07 18:00:23 -07003526 view.getWebViewClient().onReceivedSslError(
3527 view, handler, error);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003528 }
3529 })
3530 .setNeutralButton(R.string.page_info_view,
3531 new DialogInterface.OnClickListener() {
3532 public void onClick(DialogInterface dialog,
3533 int whichButton) {
3534 mSSLCertificateOnErrorDialog = null;
3535
3536 // do not clear the dialog state: we will
3537 // need to show the dialog again once the
3538 // user is done exploring the page-info details
3539
3540 showPageInfo(mTabControl.getTabFromView(view),
3541 true);
3542 }
3543 })
3544 .setOnCancelListener(
3545 new DialogInterface.OnCancelListener() {
3546 public void onCancel(DialogInterface dialog) {
3547 mSSLCertificateOnErrorDialog = null;
3548 mSSLCertificateOnErrorView = null;
3549 mSSLCertificateOnErrorHandler = null;
3550 mSSLCertificateOnErrorError = null;
3551
Grace Kloba22ac16e2009-10-07 18:00:23 -07003552 view.getWebViewClient().onReceivedSslError(
3553 view, handler, error);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003554 }
3555 })
3556 .show();
3557 }
3558
3559 /**
3560 * Inflates the SSL certificate view (helper method).
3561 * @param certificate The SSL certificate.
3562 * @return The resultant certificate view with issued-to, issued-by,
3563 * issued-on, expires-on, and possibly other fields set.
3564 * If the input certificate is null, returns null.
3565 */
3566 private View inflateCertificateView(SslCertificate certificate) {
3567 if (certificate == null) {
3568 return null;
3569 }
3570
3571 LayoutInflater factory = LayoutInflater.from(this);
3572
3573 View certificateView = factory.inflate(
3574 R.layout.ssl_certificate, null);
3575
3576 // issued to:
3577 SslCertificate.DName issuedTo = certificate.getIssuedTo();
3578 if (issuedTo != null) {
3579 ((TextView) certificateView.findViewById(R.id.to_common))
3580 .setText(issuedTo.getCName());
3581 ((TextView) certificateView.findViewById(R.id.to_org))
3582 .setText(issuedTo.getOName());
3583 ((TextView) certificateView.findViewById(R.id.to_org_unit))
3584 .setText(issuedTo.getUName());
3585 }
3586
3587 // issued by:
3588 SslCertificate.DName issuedBy = certificate.getIssuedBy();
3589 if (issuedBy != null) {
3590 ((TextView) certificateView.findViewById(R.id.by_common))
3591 .setText(issuedBy.getCName());
3592 ((TextView) certificateView.findViewById(R.id.by_org))
3593 .setText(issuedBy.getOName());
3594 ((TextView) certificateView.findViewById(R.id.by_org_unit))
3595 .setText(issuedBy.getUName());
3596 }
3597
3598 // issued on:
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003599 String issuedOn = formatCertificateDate(
3600 certificate.getValidNotBeforeDate());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003601 ((TextView) certificateView.findViewById(R.id.issued_on))
3602 .setText(issuedOn);
3603
3604 // expires on:
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003605 String expiresOn = formatCertificateDate(
3606 certificate.getValidNotAfterDate());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003607 ((TextView) certificateView.findViewById(R.id.expires_on))
3608 .setText(expiresOn);
3609
3610 return certificateView;
3611 }
3612
3613 /**
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003614 * Formats the certificate date to a properly localized date string.
The Android Open Source Project0c908882009-03-03 19:32:16 -08003615 * @return Properly localized version of the certificate date string and
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003616 * the "" if it fails to localize.
The Android Open Source Project0c908882009-03-03 19:32:16 -08003617 */
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003618 private String formatCertificateDate(Date certificateDate) {
3619 if (certificateDate == null) {
3620 return "";
The Android Open Source Project0c908882009-03-03 19:32:16 -08003621 }
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003622 String formattedDate = DateFormat.getDateFormat(this).format(certificateDate);
3623 if (formattedDate == null) {
3624 return "";
3625 }
3626 return formattedDate;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003627 }
3628
3629 /**
3630 * Displays an http-authentication dialog.
3631 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003632 void showHttpAuthentication(final HttpAuthHandler handler,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003633 final String host, final String realm, final String title,
3634 final String name, final String password, int focusId) {
3635 LayoutInflater factory = LayoutInflater.from(this);
3636 final View v = factory
3637 .inflate(R.layout.http_authentication, null);
3638 if (name != null) {
3639 ((EditText) v.findViewById(R.id.username_edit)).setText(name);
3640 }
3641 if (password != null) {
3642 ((EditText) v.findViewById(R.id.password_edit)).setText(password);
3643 }
3644
3645 String titleText = title;
3646 if (titleText == null) {
3647 titleText = getText(R.string.sign_in_to).toString().replace(
3648 "%s1", host).replace("%s2", realm);
3649 }
3650
3651 mHttpAuthHandler = handler;
3652 AlertDialog dialog = new AlertDialog.Builder(this)
3653 .setTitle(titleText)
3654 .setIcon(android.R.drawable.ic_dialog_alert)
3655 .setView(v)
3656 .setPositiveButton(R.string.action,
3657 new DialogInterface.OnClickListener() {
3658 public void onClick(DialogInterface dialog,
3659 int whichButton) {
3660 String nm = ((EditText) v
3661 .findViewById(R.id.username_edit))
3662 .getText().toString();
3663 String pw = ((EditText) v
3664 .findViewById(R.id.password_edit))
3665 .getText().toString();
3666 BrowserActivity.this.setHttpAuthUsernamePassword
3667 (host, realm, nm, pw);
3668 handler.proceed(nm, pw);
3669 mHttpAuthenticationDialog = null;
3670 mHttpAuthHandler = null;
3671 }})
3672 .setNegativeButton(R.string.cancel,
3673 new DialogInterface.OnClickListener() {
3674 public void onClick(DialogInterface dialog,
3675 int whichButton) {
3676 handler.cancel();
3677 BrowserActivity.this.resetTitleAndRevertLockIcon();
3678 mHttpAuthenticationDialog = null;
3679 mHttpAuthHandler = null;
3680 }})
3681 .setOnCancelListener(new DialogInterface.OnCancelListener() {
3682 public void onCancel(DialogInterface dialog) {
3683 handler.cancel();
3684 BrowserActivity.this.resetTitleAndRevertLockIcon();
3685 mHttpAuthenticationDialog = null;
3686 mHttpAuthHandler = null;
3687 }})
3688 .create();
3689 // Make the IME appear when the dialog is displayed if applicable.
3690 dialog.getWindow().setSoftInputMode(
3691 WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
3692 dialog.show();
3693 if (focusId != 0) {
3694 dialog.findViewById(focusId).requestFocus();
3695 } else {
3696 v.findViewById(R.id.username_edit).requestFocus();
3697 }
3698 mHttpAuthenticationDialog = dialog;
3699 }
3700
3701 public int getProgress() {
3702 WebView w = mTabControl.getCurrentWebView();
3703 if (w != null) {
3704 return w.getProgress();
3705 } else {
3706 return 100;
3707 }
3708 }
3709
3710 /**
3711 * Set HTTP authentication password.
3712 *
3713 * @param host The host for the password
3714 * @param realm The realm for the password
3715 * @param username The username for the password. If it is null, it means
3716 * password can't be saved.
3717 * @param password The password
3718 */
3719 public void setHttpAuthUsernamePassword(String host, String realm,
3720 String username,
3721 String password) {
Steve Block95a53b22010-03-25 17:24:58 +00003722 WebView w = getTopWindow();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003723 if (w != null) {
3724 w.setHttpAuthUsernamePassword(host, realm, username, password);
3725 }
3726 }
3727
3728 /**
3729 * connectivity manager says net has come or gone... inform the user
3730 * @param up true if net has come up, false if net has gone down
3731 */
3732 public void onNetworkToggle(boolean up) {
3733 if (up == mIsNetworkUp) {
3734 return;
3735 } else if (up) {
3736 mIsNetworkUp = true;
3737 if (mAlertDialog != null) {
3738 mAlertDialog.cancel();
3739 mAlertDialog = null;
3740 }
3741 } else {
3742 mIsNetworkUp = false;
Patrick Scotteb6ab2a2009-09-16 10:00:17 -04003743 if (mInLoad) {
3744 createAndShowNetworkDialog();
3745 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003746 }
3747 WebView w = mTabControl.getCurrentWebView();
3748 if (w != null) {
3749 w.setNetworkAvailable(up);
3750 }
3751 }
3752
Grace Kloba22ac16e2009-10-07 18:00:23 -07003753 boolean isNetworkUp() {
3754 return mIsNetworkUp;
3755 }
3756
Patrick Scotteb6ab2a2009-09-16 10:00:17 -04003757 // This method shows the network dialog alerting the user that the net is
3758 // down. It will only show the dialog if mAlertDialog is null.
3759 private void createAndShowNetworkDialog() {
3760 if (mAlertDialog == null) {
3761 mAlertDialog = new AlertDialog.Builder(this)
3762 .setTitle(R.string.loadSuspendedTitle)
3763 .setMessage(R.string.loadSuspended)
3764 .setPositiveButton(R.string.ok, null)
3765 .show();
3766 }
3767 }
3768
Michael Kolbe421c242010-10-04 19:29:01 -07003769 /**
3770 * callback from ComboPage when bookmark/history selection
3771 */
3772 @Override
3773 public void onUrlSelected(String url, boolean newTab) {
3774 removeComboView();
3775 if (!TextUtils.isEmpty(url)) {
3776 if (newTab) {
3777 openTab(url, false);
3778 } else {
3779 final Tab currentTab = mTabControl.getCurrentTab();
3780 dismissSubWindow(currentTab);
3781 loadUrl(getTopWindow(), url);
3782 }
3783 }
3784 }
3785
3786 /**
3787 * callback from ComboPage when dismissed
3788 */
3789 @Override
3790 public void onComboCanceled() {
3791 removeComboView();
3792 }
3793
3794 /**
3795 * dismiss the ComboPage
3796 */
3797 /* package */ void removeComboView() {
3798 if (mComboView != null) {
3799 mContentView.removeView(mComboView);
3800 mTitleBar.setVisibility(View.VISIBLE);
3801 mMenuState = R.id.MAIN_MENU;
3802 attachTabToContentView(mTabControl.getCurrentTab());
3803 getTopWindow().requestFocus();
3804 mComboView = null;
3805 }
3806 }
3807
3808 /**
3809 * callback from ComboPage when clear history is requested
3810 */
3811 public void onRemoveParentChildRelationships() {
3812 mTabControl.removeParentChildRelationShips();
3813 }
3814
The Android Open Source Project0c908882009-03-03 19:32:16 -08003815 @Override
3816 protected void onActivityResult(int requestCode, int resultCode,
3817 Intent intent) {
Grace Klobabb394f32009-11-19 10:26:37 -08003818 if (getTopWindow() == null) return;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003819 switch (requestCode) {
Leon Scrogginsfde97462010-01-11 13:06:21 -05003820 case PREFERENCES_PAGE:
3821 if (resultCode == RESULT_OK && intent != null) {
3822 String action = intent.getStringExtra(Intent.EXTRA_TEXT);
3823 if (BrowserSettings.PREF_CLEAR_HISTORY.equals(action)) {
3824 mTabControl.removeParentChildRelationShips();
3825 }
3826 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003827 break;
Leon Scroggins8d5fa432009-10-02 15:55:59 -04003828 // Choose a file from the file picker.
3829 case FILE_SELECTED:
3830 if (null == mUploadMessage) break;
3831 Uri result = intent == null || resultCode != RESULT_OK ? null
3832 : intent.getData();
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003833
3834 // As we ask the camera to save the result of the user taking
3835 // a picture, the camera application does not return anything other
3836 // than RESULT_OK. So we need to check whether the file we expected
3837 // was written to disk in the in the case that we
3838 // did not get an intent returned but did get a RESULT_OK. If it was,
3839 // we assume that this result has came back from the camera.
3840 if (result == null && intent == null && resultCode == RESULT_OK) {
3841 File cameraFile = new File(mCameraFilePath);
3842 if (cameraFile.exists()) {
3843 result = Uri.fromFile(cameraFile);
Ben Murdoch07d34732010-05-27 18:34:46 +01003844 // Broadcast to the media scanner that we have a new photo
3845 // so it will be added into the gallery for the user.
3846 sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, result));
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003847 }
3848 }
Leon Scroggins8d5fa432009-10-02 15:55:59 -04003849 mUploadMessage.onReceiveValue(result);
3850 mUploadMessage = null;
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003851 mCameraFilePath = null;
Leon Scroggins8d5fa432009-10-02 15:55:59 -04003852 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003853 default:
3854 break;
3855 }
Leon Scroggins30444232009-09-04 18:36:20 -04003856 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003857 }
3858
3859 /*
3860 * This method is called as a result of the user selecting the options
Leon Scrogginsf08809b2010-01-21 09:27:46 -05003861 * menu to see the download window. It shows the download window on top of
3862 * the current window.
The Android Open Source Project0c908882009-03-03 19:32:16 -08003863 */
Leon Scroggins IIIa682a3c2010-09-27 12:32:40 -04003864 private void viewDownloads() {
3865 Intent intent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
3866 startActivity(intent);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003867 }
3868
Michael Kolbc7485ae2010-09-03 10:10:58 -07003869 /* package */ void promptAddOrInstallBookmark(View anchor) {
3870 PopupMenu popup = new PopupMenu(this, anchor);
3871 popup.getMenuInflater().inflate(R.menu.bookmark_shortcut, popup.getMenu());
3872 popup.setOnMenuItemClickListener(this);
3873 popup.show();
3874 }
Michael Kolbebba8b42010-09-30 12:57:59 -07003875
Michael Kolbc7485ae2010-09-03 10:10:58 -07003876 /**
3877 * popup menu item click listener
3878 * @param item
3879 */
3880 public boolean onMenuItemClick(MenuItem item) {
3881 switch(item.getItemId()) {
3882 case R.id.add_bookmark_menu_id:
Michael Kolb370a4f32010-10-06 10:45:32 -07003883 bookmarkCurrentPage(AddBookmarkPage.DEFAULT_FOLDER_ID);
Michael Kolbc7485ae2010-09-03 10:10:58 -07003884 return true;
3885 case R.id.shortcut_to_home_menu_id:
3886 Tab current = mTabControl.getCurrentTab();
3887 current.populatePickerData();
3888 String touchIconUrl = mTabControl.getCurrentWebView().getTouchIconUrl();
3889 if (touchIconUrl != null) {
3890 // Download the touch icon for this site then save
3891 // it to the
3892 // homescreen.
3893 Bundle b = new Bundle();
3894 b.putString("url", current.getUrl());
3895 b.putString("title", current.getTitle());
3896 b.putParcelable("favicon", current.getFavicon());
3897 Message msg = mHandler.obtainMessage(TOUCH_ICON_DOWNLOADED);
3898 msg.setData(b);
3899 new DownloadTouchIcon(BrowserActivity.this, msg,
3900 mTabControl.getCurrentWebView().getSettings().getUserAgentString())
3901 .execute(touchIconUrl);
3902 } else {
3903 // add to homescreen, can do it immediately as there
3904 // is no touch
3905 // icon.
3906 showSaveToHomescreenDialog(
3907 current.getUrl(), current.getTitle(), null, current.getFavicon());
3908 }
3909 return true;
3910 default:
3911 return false;
3912 }
3913 }
Michael Kolbebba8b42010-09-30 12:57:59 -07003914
Michael Kolbc7485ae2010-09-03 10:10:58 -07003915 /* package */Dialog makeAddOrInstallDialog() {
Ben Murdocheecb4e62010-07-06 16:30:38 +01003916 final Tab current = mTabControl.getCurrentTab();
3917 Resources resources = getResources();
Michael Kolbc7485ae2010-09-03 10:10:58 -07003918 CharSequence[] choices =
3919 {resources.getString(R.string.save_to_bookmarks),
3920 resources.getString(R.string.create_shortcut_bookmark)};
Ben Murdocheecb4e62010-07-06 16:30:38 +01003921
3922 AlertDialog.Builder builder = new AlertDialog.Builder(this);
3923 builder.setTitle(R.string.add_new_bookmark);
3924 builder.setItems(choices, new DialogInterface.OnClickListener() {
Michael Kolbc7485ae2010-09-03 10:10:58 -07003925 public void onClick(DialogInterface dialog, int item) {
3926 if (item == 0) {
Michael Kolb370a4f32010-10-06 10:45:32 -07003927 bookmarkCurrentPage(AddBookmarkPage.DEFAULT_FOLDER_ID);
Michael Kolbc7485ae2010-09-03 10:10:58 -07003928 } else if (item == 1) {
3929 }
3930 }
Ben Murdocheecb4e62010-07-06 16:30:38 +01003931 });
Michael Kolbc7485ae2010-09-03 10:10:58 -07003932 return builder.create();
Ben Murdocheecb4e62010-07-06 16:30:38 +01003933 }
3934
Leon Scroggins160a7e72009-08-14 18:28:01 -04003935 /**
3936 * Open the Go page.
3937 * @param startWithHistory If true, open starting on the history tab.
3938 * Otherwise, start with the bookmarks tab.
Leon Scroggins160a7e72009-08-14 18:28:01 -04003939 */
Michael Kolbe421c242010-10-04 19:29:01 -07003940 /* package */ void bookmarksOrHistoryPicker(boolean startWithHistory) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003941 WebView current = mTabControl.getCurrentWebView();
3942 if (current == null) {
3943 return;
3944 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003945 String title = current.getTitle();
3946 String url = current.getUrl();
Ben Murdoch87cc65d2010-06-29 20:34:10 +01003947 Bitmap thumbnail = createScreenshot(current, getDesiredThumbnailWidth(this),
3948 getDesiredThumbnailHeight(this));
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01003949
The Android Open Source Project0c908882009-03-03 19:32:16 -08003950 // Just in case the user opens bookmarks before a page finishes loading
3951 // so the current history item, and therefore the page, is null.
3952 if (null == url) {
3953 url = mLastEnteredUrl;
3954 // This can happen.
3955 if (null == url) {
3956 url = mSettings.getHomePage();
3957 }
3958 }
3959 // In case the web page has not yet received its associated title.
3960 if (title == null) {
3961 title = url;
3962 }
Michael Kolbe421c242010-10-04 19:29:01 -07003963 Bundle extras = new Bundle();
3964 extras.putString("title", title);
3965 extras.putString("url", url);
3966 extras.putParcelable("thumbnail", thumbnail);
Leon Scroggins30444232009-09-04 18:36:20 -04003967 // Disable opening in a new window if we have maxed out the windows
Michael Kolbe421c242010-10-04 19:29:01 -07003968 extras.putBoolean("disable_new_window", !mTabControl.canCreateNewTab());
3969 extras.putString("touch_icon_url", current.getTouchIconUrl());
3970
3971 mComboView = new CombinedBookmarkHistoryView(this,
3972 startWithHistory ? CombinedBookmarkHistoryView.FRAGMENT_ID_HISTORY
3973 : CombinedBookmarkHistoryView.FRAGMENT_ID_BOOKMARKS,
3974 extras);
3975 removeTabFromContentView(mTabControl.getCurrentTab());
3976 mTitleBar.setVisibility(View.GONE);
3977 hideFakeTitleBar();
3978 mContentView.addView(mComboView, COVER_SCREEN_PARAMS);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003979 }
3980
Ben Murdocheecb4e62010-07-06 16:30:38 +01003981 private void showSaveToHomescreenDialog(String url, String title, Bitmap touchIcon,
3982 Bitmap favicon) {
3983 Intent intent = new Intent(this, SaveToHomescreenDialog.class);
3984
3985 // Just in case the user tries to save before a page finishes loading
3986 // so the current history item, and therefore the page, is null.
3987 if (null == url) {
3988 url = mLastEnteredUrl;
3989 // This can happen.
3990 if (null == url) {
3991 url = mSettings.getHomePage();
3992 }
3993 }
3994
3995 // In case the web page has not yet received its associated title.
3996 if (title == null) {
3997 title = url;
3998 }
3999
4000 intent.putExtra("title", title);
4001 intent.putExtra("url", url);
4002 intent.putExtra("favicon", favicon);
4003 intent.putExtra("touchIcon", touchIcon);
4004 startActivity(intent);
4005 }
4006
The Android Open Source Project0c908882009-03-03 19:32:16 -08004007 // Called when loading from context menu or LOAD_URL message
Leon Scroggins92472e82010-02-17 16:32:28 -05004008 private void loadUrlFromContext(WebView view, String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08004009 // In case the user enters nothing.
4010 if (url != null && url.length() != 0 && view != null) {
4011 url = smartUrlFilter(url);
Grace Kloba22ac16e2009-10-07 18:00:23 -07004012 if (!view.getWebViewClient().shouldOverrideUrlLoading(view, url)) {
Leon Scroggins92472e82010-02-17 16:32:28 -05004013 loadUrl(view, url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004014 }
4015 }
4016 }
4017
Leon Scroggins92472e82010-02-17 16:32:28 -05004018 /**
4019 * Load the URL into the given WebView and update the title bar
4020 * to reflect the new load. Call this instead of WebView.loadUrl
4021 * directly.
4022 * @param view The WebView used to load url.
4023 * @param url The URL to load.
4024 */
4025 private void loadUrl(WebView view, String url) {
4026 updateTitleBarForNewLoad(view, url);
4027 view.loadUrl(url);
4028 }
4029
4030 /**
4031 * Load UrlData into a Tab and update the title bar to reflect the new
4032 * load. Call this instead of UrlData.loadIn directly.
4033 * @param t The Tab used to load.
4034 * @param data The UrlData being loaded.
4035 */
4036 private void loadUrlDataIn(Tab t, UrlData data) {
4037 updateTitleBarForNewLoad(t.getWebView(), data.mUrl);
4038 data.loadIn(t);
4039 }
4040
4041 /**
4042 * If the WebView is the top window, update the title bar to reflect
4043 * loading the new URL. i.e. set its text, clear the favicon (which
4044 * will be set once the page begins loading), and set the progress to
4045 * INITIAL_PROGRESS to show that the page has begun to load. Called
4046 * by loadUrl and loadUrlDataIn.
4047 * @param view The WebView that is starting a load.
4048 * @param url The URL that is being loaded.
4049 */
4050 private void updateTitleBarForNewLoad(WebView view, String url) {
4051 if (view == getTopWindow()) {
4052 setUrlTitle(url, null);
4053 setFavicon(null);
4054 onProgressChanged(view, INITIAL_PROGRESS);
4055 }
4056 }
4057
The Android Open Source Project0c908882009-03-03 19:32:16 -08004058 private String smartUrlFilter(Uri inUri) {
4059 if (inUri != null) {
4060 return smartUrlFilter(inUri.toString());
4061 }
4062 return null;
4063 }
4064
Feng Qianb34f87a2009-03-24 21:27:26 -07004065 protected static final Pattern ACCEPTED_URI_SCHEMA = Pattern.compile(
The Android Open Source Project0c908882009-03-03 19:32:16 -08004066 "(?i)" + // switch on case insensitive matching
4067 "(" + // begin group for schema
4068 "(?:http|https|file):\\/\\/" +
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004069 "|(?:inline|data|about|content|javascript):" +
The Android Open Source Project0c908882009-03-03 19:32:16 -08004070 ")" +
4071 "(.*)" );
4072
4073 /**
4074 * Attempts to determine whether user input is a URL or search
4075 * terms. Anything with a space is passed to search.
4076 *
4077 * Converts to lowercase any mistakenly uppercased schema (i.e.,
4078 * "Http://" converts to "http://"
4079 *
4080 * @return Original or modified URL
4081 *
4082 */
4083 String smartUrlFilter(String url) {
4084
4085 String inUrl = url.trim();
4086 boolean hasSpace = inUrl.indexOf(' ') != -1;
4087
4088 Matcher matcher = ACCEPTED_URI_SCHEMA.matcher(inUrl);
4089 if (matcher.matches()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08004090 // force scheme to lowercase
4091 String scheme = matcher.group(1);
4092 String lcScheme = scheme.toLowerCase();
4093 if (!lcScheme.equals(scheme)) {
Mitsuru Oshima123ecfb2009-05-18 19:11:14 -07004094 inUrl = lcScheme + matcher.group(2);
4095 }
4096 if (hasSpace) {
4097 inUrl = inUrl.replace(" ", "%20");
The Android Open Source Project0c908882009-03-03 19:32:16 -08004098 }
4099 return inUrl;
4100 }
Leon Scroggins956cf012010-10-07 13:51:57 -04004101 if (!hasSpace) {
Dan Egnor5ee906c2009-11-18 12:11:49 -08004102 if (Patterns.WEB_URL.matcher(inUrl).matches()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08004103 return URLUtil.guessUrl(inUrl);
4104 }
4105 }
4106
Leon Scroggins956cf012010-10-07 13:51:57 -04004107 // FIXME: Is this the correct place to add to searches?
4108 // what if someone else calls this function?
4109
The Android Open Source Project0c908882009-03-03 19:32:16 -08004110 Browser.addSearchUrl(mResolver, inUrl);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07004111 return URLUtil.composeSearchUrl(inUrl, QuickSearch_G, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004112 }
4113
Ben Murdochbff2d602009-07-01 20:19:05 +01004114 /* package */ void setShouldShowErrorConsole(boolean flag) {
4115 if (flag == mShouldShowErrorConsole) {
4116 // Nothing to do.
4117 return;
4118 }
Leon Scroggins IIIa9e35b62010-09-16 15:30:15 -04004119 Tab t = mTabControl.getCurrentTab();
4120 if (t == null) {
4121 // There is no current tab so we cannot toggle the error console
4122 return;
4123 }
Ben Murdochbff2d602009-07-01 20:19:05 +01004124
4125 mShouldShowErrorConsole = flag;
4126
Leon Scroggins IIIa9e35b62010-09-16 15:30:15 -04004127 ErrorConsoleView errorConsole = t.getErrorConsole(true);
Ben Murdochbff2d602009-07-01 20:19:05 +01004128
4129 if (flag) {
4130 // Setting the show state of the console will cause it's the layout to be inflated.
4131 if (errorConsole.numberOfErrors() > 0) {
4132 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
4133 } else {
4134 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
4135 }
4136
4137 // Now we can add it to the main view.
4138 mErrorConsoleContainer.addView(errorConsole,
Romain Guy15b8ec62010-01-08 15:06:43 -08004139 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
Ben Murdochbff2d602009-07-01 20:19:05 +01004140 ViewGroup.LayoutParams.WRAP_CONTENT));
4141 } else {
4142 mErrorConsoleContainer.removeView(errorConsole);
4143 }
4144
4145 }
4146
Grace Kloba22ac16e2009-10-07 18:00:23 -07004147 boolean shouldShowErrorConsole() {
4148 return mShouldShowErrorConsole;
4149 }
4150
Andrei Popescu163ab742009-10-20 17:58:23 +01004151 private void setStatusBarVisibility(boolean visible) {
4152 int flag = visible ? 0 : WindowManager.LayoutParams.FLAG_FULLSCREEN;
4153 getWindow().setFlags(flag, WindowManager.LayoutParams.FLAG_FULLSCREEN);
4154 }
4155
Andrei Popescu56199cc2010-01-12 22:39:16 +00004156
4157 private void sendNetworkType(String type, String subtype) {
4158 WebView w = mTabControl.getCurrentWebView();
4159 if (w != null) {
4160 w.setNetworkType(type, subtype);
4161 }
4162 }
4163
Grace Klobaeb6eef42009-09-15 17:56:32 -07004164 final static int LOCK_ICON_UNSECURE = 0;
4165 final static int LOCK_ICON_SECURE = 1;
4166 final static int LOCK_ICON_MIXED = 2;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004167
The Android Open Source Project0c908882009-03-03 19:32:16 -08004168 private BrowserSettings mSettings;
4169 private TabControl mTabControl;
4170 private ContentResolver mResolver;
4171 private FrameLayout mContentView;
Andrei Popescuadc008d2009-06-26 14:11:30 +01004172 private View mCustomView;
4173 private FrameLayout mCustomViewContainer;
Andrei Popescuc9b55562009-07-07 10:51:15 +01004174 private WebChromeClient.CustomViewCallback mCustomViewCallback;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004175
4176 // FIXME, temp address onPrepareMenu performance problem. When we move everything out of
4177 // view, we should rewrite this.
4178 private int mCurrentMenuState = 0;
4179 private int mMenuState = R.id.MAIN_MENU;
Andrei Popescuadc008d2009-06-26 14:11:30 +01004180 private int mOldMenuState = EMPTY_MENU;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004181 private static final int EMPTY_MENU = -1;
4182 private Menu mMenu;
4183
The Android Open Source Project0c908882009-03-03 19:32:16 -08004184 // Used to prevent chording to result in firing two shortcuts immediately
4185 // one after another. Fixes bug 1211714.
4186 boolean mCanChord;
4187
4188 private boolean mInLoad;
4189 private boolean mIsNetworkUp;
Ben Murdochb7cc8b42009-09-28 10:59:09 +01004190 private boolean mDidStopLoad;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004191
Cary Clark1f10cbf2010-03-22 11:45:23 -04004192 /* package */ boolean mActivityInPause = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004193
4194 private boolean mMenuIsDown;
4195
The Android Open Source Project0c908882009-03-03 19:32:16 -08004196 private static boolean mInTrace;
4197
4198 // Performance probe
4199 private static final int[] SYSTEM_CPU_FORMAT = new int[] {
4200 Process.PROC_SPACE_TERM | Process.PROC_COMBINE,
4201 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 1: user time
4202 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 2: nice time
4203 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 3: sys time
4204 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 4: idle time
4205 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 5: iowait time
4206 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 6: irq time
4207 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG // 7: softirq time
4208 };
4209
4210 private long mStart;
4211 private long mProcessStart;
4212 private long mUserStart;
4213 private long mSystemStart;
4214 private long mIdleStart;
4215 private long mIrqStart;
4216
4217 private long mUiStart;
4218
4219 private Drawable mMixLockIcon;
4220 private Drawable mSecLockIcon;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004221
4222 /* hold a ref so we can auto-cancel if necessary */
4223 private AlertDialog mAlertDialog;
4224
The Android Open Source Project0c908882009-03-03 19:32:16 -08004225 // The up-to-date URL and title (these can be different from those stored
4226 // in WebView, since it takes some time for the information in WebView to
4227 // get updated)
4228 private String mUrl;
4229 private String mTitle;
4230
4231 // As PageInfo has different style for landscape / portrait, we have
4232 // to re-open it when configuration changed
4233 private AlertDialog mPageInfoDialog;
Grace Kloba22ac16e2009-10-07 18:00:23 -07004234 private Tab mPageInfoView;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004235 // If the Page-Info dialog is launched from the SSL-certificate-on-error
4236 // dialog, we should not just dismiss it, but should get back to the
4237 // SSL-certificate-on-error dialog. This flag is used to store this state
Leon Scrogginsc7b92f82010-01-11 18:17:31 -05004238 private boolean mPageInfoFromShowSSLCertificateOnError;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004239
4240 // as SSLCertificateOnError has different style for landscape / portrait,
4241 // we have to re-open it when configuration changed
4242 private AlertDialog mSSLCertificateOnErrorDialog;
4243 private WebView mSSLCertificateOnErrorView;
4244 private SslErrorHandler mSSLCertificateOnErrorHandler;
4245 private SslError mSSLCertificateOnErrorError;
4246
4247 // as SSLCertificate has different style for landscape / portrait, we
4248 // have to re-open it when configuration changed
4249 private AlertDialog mSSLCertificateDialog;
Grace Kloba22ac16e2009-10-07 18:00:23 -07004250 private Tab mSSLCertificateView;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004251
4252 // as HttpAuthentication has different style for landscape / portrait, we
4253 // have to re-open it when configuration changed
4254 private AlertDialog mHttpAuthenticationDialog;
4255 private HttpAuthHandler mHttpAuthHandler;
4256
4257 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_PARAMS =
4258 new FrameLayout.LayoutParams(
Romain Guy15b8ec62010-01-08 15:06:43 -08004259 ViewGroup.LayoutParams.MATCH_PARENT,
4260 ViewGroup.LayoutParams.MATCH_PARENT);
Andrei Popescuadc008d2009-06-26 14:11:30 +01004261 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_GRAVITY_CENTER =
4262 new FrameLayout.LayoutParams(
Romain Guy15b8ec62010-01-08 15:06:43 -08004263 ViewGroup.LayoutParams.MATCH_PARENT,
4264 ViewGroup.LayoutParams.MATCH_PARENT,
Andrei Popescuadc008d2009-06-26 14:11:30 +01004265 Gravity.CENTER);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07004266 // Google search
4267 final static String QuickSearch_G = "http://www.google.com/m?q=%s";
The Android Open Source Project0c908882009-03-03 19:32:16 -08004268
4269 final static String QUERY_PLACE_HOLDER = "%s";
4270
4271 // "source" parameter for Google search through search key
4272 final static String GOOGLE_SEARCH_SOURCE_SEARCHKEY = "browser-key";
4273 // "source" parameter for Google search through goto menu
4274 final static String GOOGLE_SEARCH_SOURCE_GOTO = "browser-goto";
4275 // "source" parameter for Google search through simplily type
4276 final static String GOOGLE_SEARCH_SOURCE_TYPE = "browser-type";
4277 // "source" parameter for Google search suggested by the browser
4278 final static String GOOGLE_SEARCH_SOURCE_SUGGEST = "browser-suggest";
4279 // "source" parameter for Google search from unknown source
4280 final static String GOOGLE_SEARCH_SOURCE_UNKNOWN = "unknown";
4281
4282 private final static String LOGTAG = "browser";
4283
The Android Open Source Project0c908882009-03-03 19:32:16 -08004284 private String mLastEnteredUrl;
4285
4286 private PowerManager.WakeLock mWakeLock;
4287 private final static int WAKELOCK_TIMEOUT = 5 * 60 * 1000; // 5 minutes
4288
4289 private Toast mStopToast;
4290
Leon Scroggins571b3762010-05-26 10:25:01 -04004291 private TitleBarBase mTitleBar;
Michael Kolba2b2ba82010-08-04 17:54:03 -07004292 private TabBar mTabBar;
Leon Scroggins81db3662009-06-04 17:45:11 -04004293
Ben Murdochbff2d602009-07-01 20:19:05 +01004294 private LinearLayout mErrorConsoleContainer = null;
4295 private boolean mShouldShowErrorConsole = false;
4296
The Android Open Source Project0c908882009-03-03 19:32:16 -08004297 // As the ids are dynamically created, we can't guarantee that they will
4298 // be in sequence, so this static array maps ids to a window number.
4299 final static private int[] WINDOW_SHORTCUT_ID_ARRAY =
4300 { R.id.window_one_menu_id, R.id.window_two_menu_id, R.id.window_three_menu_id,
4301 R.id.window_four_menu_id, R.id.window_five_menu_id, R.id.window_six_menu_id,
4302 R.id.window_seven_menu_id, R.id.window_eight_menu_id };
4303
4304 // monitor platform changes
4305 private IntentFilter mNetworkStateChangedFilter;
4306 private BroadcastReceiver mNetworkStateIntentReceiver;
4307
Bjorn Bringerta7611812010-03-24 11:12:02 +00004308 private SystemAllowGeolocationOrigins mSystemAllowGeolocationOrigins;
4309
The Android Open Source Project0c908882009-03-03 19:32:16 -08004310 // activity requestCode
Nicolas Roard78a98e42009-05-11 13:34:17 +01004311 final static int PREFERENCES_PAGE = 3;
Leon Scroggins8d5fa432009-10-02 15:55:59 -04004312 final static int FILE_SELECTED = 4;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004313
Andrei Popescu540035d2009-09-18 18:59:20 +01004314 // the default <video> poster
4315 private Bitmap mDefaultVideoPoster;
4316 // the video progress view
4317 private View mVideoProgressView;
4318
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004319 /**
4320 * A UrlData class to abstract how the content will be set to WebView.
4321 * This base class uses loadUrl to show the content.
4322 */
Leon Scroggins6eac63e2010-03-15 18:19:14 -04004323 /* package */ static class UrlData {
Grace Kloba068e48b2010-01-26 18:11:27 -08004324 final String mUrl;
4325 final Map<String, String> mHeaders;
Leon Scroggins58d56c62010-01-28 15:12:40 -05004326 final Intent mVoiceIntent;
Grace Kloba60e095c2009-06-16 11:50:55 -07004327
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004328 UrlData(String url) {
4329 this.mUrl = url;
Grace Kloba068e48b2010-01-26 18:11:27 -08004330 this.mHeaders = null;
Leon Scroggins58d56c62010-01-28 15:12:40 -05004331 this.mVoiceIntent = null;
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004332 }
Grace Kloba60e095c2009-06-16 11:50:55 -07004333
Leon Scroggins58d56c62010-01-28 15:12:40 -05004334 UrlData(String url, Map<String, String> headers, Intent intent) {
Grace Kloba068e48b2010-01-26 18:11:27 -08004335 this.mUrl = url;
4336 this.mHeaders = headers;
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -05004337 if (RecognizerResultsIntent.ACTION_VOICE_SEARCH_RESULTS
4338 .equals(intent.getAction())) {
Leon Scroggins58d56c62010-01-28 15:12:40 -05004339 this.mVoiceIntent = intent;
4340 } else {
4341 this.mVoiceIntent = null;
4342 }
Grace Kloba60e095c2009-06-16 11:50:55 -07004343 }
4344
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004345 boolean isEmpty() {
Leon Scroggins58d56c62010-01-28 15:12:40 -05004346 return mVoiceIntent == null && (mUrl == null || mUrl.length() == 0);
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004347 }
4348
Leon Scroggins92472e82010-02-17 16:32:28 -05004349 /**
4350 * Load this UrlData into the given Tab. Use loadUrlDataIn to update
4351 * the title bar as well.
4352 */
Leon Scroggins58d56c62010-01-28 15:12:40 -05004353 public void loadIn(Tab t) {
4354 if (mVoiceIntent != null) {
4355 t.activateVoiceSearchMode(mVoiceIntent);
4356 } else {
4357 t.getWebView().loadUrl(mUrl, mHeaders);
4358 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004359 }
4360 };
4361
Leon Scroggins1f005d32009-08-10 17:36:42 -04004362 /* package */ static final UrlData EMPTY_URL_DATA = new UrlData(null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004363}