blob: 558984994a7f9dc56f97f27fb1480a73d5c301b3 [file] [log] [blame]
The Android Open Source Project0c908882009-03-03 19:32:16 -08001/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.browser;
18
Michael Kolb3f65c382010-08-20 15:31:16 -070019import com.android.browser.ScrollWebView.ScrollListener;
Bjorn Bringertd69f51d2010-09-13 14:06:41 +010020import com.android.browser.search.SearchEngine;
Michael Kolb3f65c382010-08-20 15:31:16 -070021import com.android.common.Search;
22import com.android.common.speech.LoggingEvents;
23
Michael Kolbed217742010-08-10 17:52:34 -070024import android.app.ActionBar;
The Android Open Source Project0c908882009-03-03 19:32:16 -080025import android.app.Activity;
The Android Open Source Project0c908882009-03-03 19:32:16 -080026import android.app.AlertDialog;
Michael Kolbc7485ae2010-09-03 10:10:58 -070027import android.app.Dialog;
The Android Open Source Project0c908882009-03-03 19:32:16 -080028import android.app.ProgressDialog;
29import android.app.SearchManager;
30import android.content.ActivityNotFoundException;
31import android.content.BroadcastReceiver;
Dianne Hackborn80f32622010-08-05 14:17:53 -070032import android.content.ClipboardManager;
The Android Open Source Project0c908882009-03-03 19:32:16 -080033import android.content.ComponentName;
Leon Scroggins58d56c62010-01-28 15:12:40 -050034import android.content.ContentProvider;
35import android.content.ContentProviderClient;
The Android Open Source Project0c908882009-03-03 19:32:16 -080036import android.content.ContentResolver;
Leon Scrogginsb6b7f9e2009-06-18 12:05:28 -040037import android.content.ContentUris;
The Android Open Source Project0c908882009-03-03 19:32:16 -080038import android.content.ContentValues;
39import android.content.Context;
40import android.content.DialogInterface;
41import android.content.Intent;
42import android.content.IntentFilter;
The Android Open Source Project0c908882009-03-03 19:32:16 -080043import android.content.pm.PackageManager;
44import android.content.pm.ResolveInfo;
The Android Open Source Project0c908882009-03-03 19:32:16 -080045import android.content.res.Configuration;
46import android.content.res.Resources;
47import android.database.Cursor;
The Android Open Source Project0c908882009-03-03 19:32:16 -080048import android.graphics.Bitmap;
Andrei Popescu540035d2009-09-18 18:59:20 +010049import android.graphics.BitmapFactory;
The Android Open Source Project0c908882009-03-03 19:32:16 -080050import android.graphics.Canvas;
The Android Open Source Project0c908882009-03-03 19:32:16 -080051import android.graphics.Picture;
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -040052import android.graphics.PixelFormat;
The Android Open Source Project0c908882009-03-03 19:32:16 -080053import android.graphics.drawable.Drawable;
The Android Open Source Project0c908882009-03-03 19:32:16 -080054import android.net.ConnectivityManager;
Andrei Popescu56199cc2010-01-12 22:39:16 +000055import android.net.NetworkInfo;
The Android Open Source Project0c908882009-03-03 19:32:16 -080056import android.net.Uri;
57import android.net.WebAddress;
The Android Open Source Project0c908882009-03-03 19:32:16 -080058import android.net.http.SslCertificate;
59import android.net.http.SslError;
60import android.os.AsyncTask;
61import android.os.Bundle;
62import android.os.Debug;
63import android.os.Environment;
64import android.os.Handler;
The Android Open Source Project0c908882009-03-03 19:32:16 -080065import android.os.Message;
66import android.os.PowerManager;
67import android.os.Process;
The Android Open Source Project0c908882009-03-03 19:32:16 -080068import android.os.SystemClock;
The Android Open Source Project0c908882009-03-03 19:32:16 -080069import android.provider.Browser;
Jeff Hamilton8ce956c2010-08-17 11:13:53 -050070import android.provider.BrowserContract;
Cary Clark5e335a32009-09-22 14:53:11 -040071import android.provider.ContactsContract;
Michael Kolba2b2ba82010-08-04 17:54:03 -070072import android.provider.ContactsContract.Intents.Insert;
The Android Open Source Project0c908882009-03-03 19:32:16 -080073import android.provider.Downloads;
74import android.provider.MediaStore;
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -050075import android.speech.RecognizerResultsIntent;
The Android Open Source Project0c908882009-03-03 19:32:16 -080076import android.text.TextUtils;
77import android.text.format.DateFormat;
The Android Open Source Project0c908882009-03-03 19:32:16 -080078import android.util.Log;
Dianne Hackborn385effd2010-02-24 20:03:04 -080079import android.util.Patterns;
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -040080import android.view.ActionMode;
The Android Open Source Project0c908882009-03-03 19:32:16 -080081import android.view.ContextMenu;
Michael Kolba2b2ba82010-08-04 17:54:03 -070082import android.view.ContextMenu.ContextMenuInfo;
The Android Open Source Project0c908882009-03-03 19:32:16 -080083import android.view.Gravity;
84import android.view.KeyEvent;
85import android.view.LayoutInflater;
86import android.view.Menu;
87import android.view.MenuInflater;
88import android.view.MenuItem;
Michael Kolba2b2ba82010-08-04 17:54:03 -070089import android.view.MenuItem.OnMenuItemClickListener;
Michael Kolb3f65c382010-08-20 15:31:16 -070090import android.view.MotionEvent;
The Android Open Source Project0c908882009-03-03 19:32:16 -080091import android.view.View;
92import android.view.ViewGroup;
93import android.view.Window;
94import android.view.WindowManager;
Svetoslav Ganov2b345992010-05-06 06:13:54 -070095import android.view.accessibility.AccessibilityManager;
The Android Open Source Project0c908882009-03-03 19:32:16 -080096import android.webkit.CookieManager;
97import android.webkit.CookieSyncManager;
98import android.webkit.DownloadListener;
99import android.webkit.HttpAuthHandler;
100import android.webkit.SslErrorHandler;
101import android.webkit.URLUtil;
Leon Clarkecb6cc862009-09-29 18:35:13 +0100102import android.webkit.ValueCallback;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800103import android.webkit.WebChromeClient;
104import android.webkit.WebHistoryItem;
105import android.webkit.WebIconDatabase;
106import android.webkit.WebView;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800107import android.widget.EditText;
108import android.widget.FrameLayout;
109import android.widget.LinearLayout;
Michael Kolbc7485ae2010-09-03 10:10:58 -0700110import android.widget.PopupMenu;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800111import android.widget.TextView;
112import android.widget.Toast;
113
Leon Scrogginsb6b7f9e2009-06-18 12:05:28 -0400114import java.io.ByteArrayOutputStream;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800115import java.io.File;
Ben Murdoch4f75ba22009-10-27 11:48:28 +0000116import java.io.IOException;
117import java.io.InputStream;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800118import java.net.MalformedURLException;
Dianne Hackborn99189432009-06-17 18:06:18 -0700119import java.net.URISyntaxException;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800120import java.net.URL;
121import java.net.URLEncoder;
Elliott Slaughter3d6df162010-08-25 13:17:44 -0700122import java.util.Calendar;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800123import java.util.Date;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800124import java.util.HashMap;
Grace Kloba00f54c52010-01-27 14:53:51 -0800125import java.util.Iterator;
Grace Kloba068e48b2010-01-26 18:11:27 -0800126import java.util.Map;
Michael Kolbfe251992010-07-08 15:41:55 -0700127import java.util.Vector;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800128import java.util.regex.Matcher;
129import java.util.regex.Pattern;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800130
131public class BrowserActivity extends Activity
Michael Kolbc7485ae2010-09-03 10:10:58 -0700132 implements View.OnCreateContextMenuListener, DownloadListener,
133 PopupMenu.OnMenuItemClickListener {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800134
Dave Bort31a6d1c2009-04-13 15:56:49 -0700135 /* Define some aliases to make these debugging flags easier to refer to.
136 * This file imports android.provider.Browser, so we can't just refer to "Browser.DEBUG".
137 */
138 private final static boolean DEBUG = com.android.browser.Browser.DEBUG;
139 private final static boolean LOGV_ENABLED = com.android.browser.Browser.LOGV_ENABLED;
140 private final static boolean LOGD_ENABLED = com.android.browser.Browser.LOGD_ENABLED;
141
Satish Sampath565505b2009-05-29 15:37:27 +0100142 // These are single-character shortcuts for searching popular sources.
143 private static final int SHORTCUT_INVALID = 0;
144 private static final int SHORTCUT_GOOGLE_SEARCH = 1;
145 private static final int SHORTCUT_WIKIPEDIA_SEARCH = 2;
146 private static final int SHORTCUT_DICTIONARY_SEARCH = 3;
147 private static final int SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH = 4;
148
Cary Clarka9771242009-08-11 16:42:26 -0400149 private static class ClearThumbnails extends AsyncTask<File, Void, Void> {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800150 @Override
151 public Void doInBackground(File... files) {
152 if (files != null) {
153 for (File f : files) {
Cary Clarkd6be1752009-08-12 12:56:42 -0400154 if (!f.delete()) {
155 Log.e(LOGTAG, f.getPath() + " was not deleted");
156 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800157 }
158 }
159 return null;
160 }
161 }
162
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400163 /**
164 * This layout holds everything you see below the status bar, including the
165 * error console, the custom view container, and the webviews.
166 */
167 private FrameLayout mBrowserFrameLayout;
Leon Scroggins81db3662009-06-04 17:45:11 -0400168
Leon Scrogginsd746a942010-05-19 13:21:44 -0400169 private boolean mXLargeScreenSize;
170
Jeff Davidson43610292010-07-16 16:03:58 -0700171 private Boolean mIsProviderPresent = null;
172 private Uri mRlzUri = null;
173
Grace Kloba22ac16e2009-10-07 18:00:23 -0700174 @Override
175 public void onCreate(Bundle icicle) {
Dave Bort31a6d1c2009-04-13 15:56:49 -0700176 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800177 Log.v(LOGTAG, this + " onStart");
178 }
179 super.onCreate(icicle);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800180 // test the browser in OpenGL
181 // requestWindowFeature(Window.FEATURE_OPENGL);
182
Mike Reedd334bf52010-01-26 15:21:44 -0500183 // enable this to test the browser in 32bit
184 if (false) {
185 getWindow().setFormat(PixelFormat.RGBX_8888);
186 BitmapFactory.setDefaultConfig(Bitmap.Config.ARGB_8888);
187 }
188
Svetoslav Ganov2b345992010-05-06 06:13:54 -0700189 if (AccessibilityManager.getInstance(this).isEnabled()) {
190 setDefaultKeyMode(DEFAULT_KEYS_DISABLE);
191 } else {
192 setDefaultKeyMode(DEFAULT_KEYS_SEARCH_LOCAL);
193 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800194
195 mResolver = getContentResolver();
196
Grace Kloba0923d692009-09-23 21:37:25 -0700197 // If this was a web search request, pass it on to the default web
198 // search provider and finish this activity.
199 if (handleWebSearchIntent(getIntent())) {
200 finish();
201 return;
202 }
203
The Android Open Source Project0c908882009-03-03 19:32:16 -0800204 mSecLockIcon = Resources.getSystem().getDrawable(
205 android.R.drawable.ic_secure);
206 mMixLockIcon = Resources.getSystem().getDrawable(
207 android.R.drawable.ic_partial_secure);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800208
Michael Kolbed217742010-08-10 17:52:34 -0700209 // Create the tab control and our initial tab
210 mTabControl = new TabControl(this);
211
212 mXLargeScreenSize = (getResources().getConfiguration().screenLayout
213 & Configuration.SCREENLAYOUT_SIZE_MASK)
214 == Configuration.SCREENLAYOUT_SIZE_XLARGE;
215
Leon Scroggins81db3662009-06-04 17:45:11 -0400216 FrameLayout frameLayout = (FrameLayout) getWindow().getDecorView()
217 .findViewById(com.android.internal.R.id.content);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400218 mBrowserFrameLayout = (FrameLayout) LayoutInflater.from(this)
219 .inflate(R.layout.custom_screen, null);
220 mContentView = (FrameLayout) mBrowserFrameLayout.findViewById(
221 R.id.main_content);
222 mErrorConsoleContainer = (LinearLayout) mBrowserFrameLayout
223 .findViewById(R.id.error_console);
224 mCustomViewContainer = (FrameLayout) mBrowserFrameLayout
225 .findViewById(R.id.fullscreen_custom_content);
226 frameLayout.addView(mBrowserFrameLayout, COVER_SCREEN_PARAMS);
Michael Kolbe0a36662010-06-29 10:37:12 -0700227
Leon Scrogginsd746a942010-05-19 13:21:44 -0400228 if (mXLargeScreenSize) {
Michael Kolba2b2ba82010-08-04 17:54:03 -0700229 mTitleBar = new TitleBarXLarge(this);
230 mTitleBar.setProgress(100);
231 mFakeTitleBar = new TitleBarXLarge(this);
Michael Kolbed217742010-08-10 17:52:34 -0700232 ActionBar actionBar = getActionBar();
Michael Kolbc7485ae2010-09-03 10:10:58 -0700233 actionBar.setBackgroundDrawable(getResources().
234 getDrawable(R.drawable.tabbar_bg));
Michael Kolba2b2ba82010-08-04 17:54:03 -0700235 mTabBar = new TabBar(this, mTabControl, (TitleBarXLarge) mFakeTitleBar);
Michael Kolbed217742010-08-10 17:52:34 -0700236 actionBar.setCustomNavigationMode(mTabBar);
Michael Kolb68775752010-08-19 12:42:01 -0700237 // disable built in zoom controls
238 mTabControl.setDisplayZoomControls(false);
Leon Scrogginsd746a942010-05-19 13:21:44 -0400239 } else {
Leon Scroggins571b3762010-05-26 10:25:01 -0400240 mTitleBar = new TitleBar(this);
Leon Scrogginsd746a942010-05-19 13:21:44 -0400241 // mTitleBar will be always be shown in the fully loaded mode on
242 // phone
243 mTitleBar.setProgress(100);
Leon Scrogginsd746a942010-05-19 13:21:44 -0400244 mFakeTitleBar = new TitleBar(this);
245 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800246
The Android Open Source Project0c908882009-03-03 19:32:16 -0800247 // Open the icon database and retain all the bookmark urls for favicons
248 retainIconsOnStartup();
249
250 // Keep a settings instance handy.
251 mSettings = BrowserSettings.getInstance();
252 mSettings.setTabControl(mTabControl);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800253
254 PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
255 mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Browser");
256
Patrick Scott6adacc92010-03-05 08:24:51 -0500257 // Find out if the network is currently up.
258 ConnectivityManager cm = (ConnectivityManager) getSystemService(
259 Context.CONNECTIVITY_SERVICE);
260 NetworkInfo info = cm.getActiveNetworkInfo();
261 if (info != null) {
262 mIsNetworkUp = info.isAvailable();
263 }
264
Grace Klobaa34f6862009-07-31 16:28:17 -0700265 /* enables registration for changes in network status from
266 http stack */
267 mNetworkStateChangedFilter = new IntentFilter();
268 mNetworkStateChangedFilter.addAction(
269 ConnectivityManager.CONNECTIVITY_ACTION);
270 mNetworkStateIntentReceiver = new BroadcastReceiver() {
271 @Override
272 public void onReceive(Context context, Intent intent) {
273 if (intent.getAction().equals(
274 ConnectivityManager.CONNECTIVITY_ACTION)) {
Andrei Popescue4c98462010-02-19 15:44:13 +0000275
276 NetworkInfo info = intent.getParcelableExtra(
277 ConnectivityManager.EXTRA_NETWORK_INFO);
278 String typeName = info.getTypeName();
279 String subtypeName = info.getSubtypeName();
280 sendNetworkType(typeName.toLowerCase(),
281 (subtypeName != null ? subtypeName.toLowerCase() : ""));
282
283 onNetworkToggle(info.isAvailable());
Grace Klobaa34f6862009-07-31 16:28:17 -0700284 }
285 }
286 };
287
Elliott Slaughter3d6df162010-08-25 13:17:44 -0700288 // Unless the last browser usage was within 24 hours, destroy any
289 // remaining incognito tabs.
290
291 Calendar lastActiveDate = icicle != null ? (Calendar) icicle.getSerializable("lastActiveDate") : null;
292 Calendar today = Calendar.getInstance();
293 Calendar yesterday = Calendar.getInstance();
294 yesterday.add(Calendar.DATE, -1);
295
296 boolean dontRestoreIncognitoTabs = lastActiveDate == null
297 || lastActiveDate.before(yesterday)
298 || lastActiveDate.after(today);
299
300 if (!mTabControl.restoreState(icicle, dontRestoreIncognitoTabs)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800301 // clear up the thumbnail directory if we can't restore the state as
302 // none of the files in the directory are referenced any more.
303 new ClearThumbnails().execute(
304 mTabControl.getThumbnailDir().listFiles());
Grace Klobaaab3f092009-07-30 12:29:51 -0700305 // there is no quit on Android. But if we can't restore the state,
306 // we can treat it as a new Browser, remove the old session cookies.
307 CookieManager.getInstance().removeSessionCookie();
Elliott Slaughter3d6df162010-08-25 13:17:44 -0700308 // remove any incognito files
309 WebView.cleanupPrivateBrowsingFiles(this);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800310 final Intent intent = getIntent();
311 final Bundle extra = intent.getExtras();
312 // Create an initial tab.
313 // If the intent is ACTION_VIEW and data is not null, the Browser is
314 // invoked to view the content by another application. In this case,
315 // the tab will be close when exit.
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700316 UrlData urlData = getUrlDataFromIntent(intent);
317
Leon Scroggins58d56c62010-01-28 15:12:40 -0500318 String action = intent.getAction();
Grace Kloba22ac16e2009-10-07 18:00:23 -0700319 final Tab t = mTabControl.createNewTab(
Leon Scroggins58d56c62010-01-28 15:12:40 -0500320 (Intent.ACTION_VIEW.equals(action) &&
321 intent.getData() != null)
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -0500322 || RecognizerResultsIntent.ACTION_VOICE_SEARCH_RESULTS
323 .equals(action),
Elliott Slaughterf0f03952010-07-14 18:10:36 -0700324 intent.getStringExtra(Browser.EXTRA_APPLICATION_ID),
325 urlData.mUrl, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800326 mTabControl.setCurrentTab(t);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800327 attachTabToContentView(t);
328 WebView webView = t.getWebView();
329 if (extra != null) {
330 int scale = extra.getInt(Browser.INITIAL_ZOOM_LEVEL, 0);
331 if (scale > 0 && scale <= 1000) {
332 webView.setInitialScale(scale);
333 }
334 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800335
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700336 if (urlData.isEmpty()) {
Shimeng (Simon) Wang98d5fce2010-03-16 13:23:39 -0700337 loadUrl(webView, mSettings.getHomePage());
The Android Open Source Project0c908882009-03-03 19:32:16 -0800338 } else {
Patrick Scott9d53da02010-02-19 10:19:01 -0500339 loadUrlDataIn(t, urlData);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800340 }
341 } else {
Elliott Slaughter3d6df162010-08-25 13:17:44 -0700342 if (dontRestoreIncognitoTabs) {
343 WebView.cleanupPrivateBrowsingFiles(this);
344 }
345
The Android Open Source Project0c908882009-03-03 19:32:16 -0800346 // TabControl.restoreState() will create a new tab even if
Leon Scroggins1f005d32009-08-10 17:36:42 -0400347 // restoring the state fails.
The Android Open Source Project0c908882009-03-03 19:32:16 -0800348 attachTabToContentView(mTabControl.getCurrentTab());
349 }
Grace Kloba615c6c92009-08-03 10:22:44 -0700350
Cary Clarkb4b83182010-07-01 12:36:56 -0400351 // Delete old thumbnails to save space
352 File dir = mTabControl.getThumbnailDir();
353 if (dir.exists()) {
354 for (String child : dir.list()) {
355 File f = new File(dir, child);
356 f.delete();
357 }
358 }
359
Feng Qianb3c02da2009-06-29 15:58:08 -0700360 // Read JavaScript flags if it exists.
361 String jsFlags = mSettings.getJsFlags();
362 if (jsFlags.trim().length() != 0) {
363 mTabControl.getCurrentWebView().setJsFlags(jsFlags);
364 }
Bjorn Bringerta7611812010-03-24 11:12:02 +0000365
366 // Start watching the default geolocation permissions
367 mSystemAllowGeolocationOrigins
368 = new SystemAllowGeolocationOrigins(getApplicationContext());
369 mSystemAllowGeolocationOrigins.start();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800370 }
371
Michael Kolba2b2ba82010-08-04 17:54:03 -0700372 ScrollListener getScrollListener() {
373 return mTabBar;
374 }
375
Leon Scroggins58d56c62010-01-28 15:12:40 -0500376 /**
377 * Feed the previously stored results strings to the BrowserProvider so that
378 * the SearchDialog will show them instead of the standard searches.
379 * @param result String to show on the editable line of the SearchDialog.
380 */
381 /* package */ void showVoiceSearchResults(String result) {
382 ContentProviderClient client = mResolver.acquireContentProviderClient(
383 Browser.BOOKMARKS_URI);
384 ContentProvider prov = client.getLocalContentProvider();
385 BrowserProvider bp = (BrowserProvider) prov;
386 bp.setQueryResults(mTabControl.getCurrentTab().getVoiceSearchResults());
387 client.release();
388
Leon Scrogginsfbb3f152010-03-09 17:26:56 -0500389 Bundle bundle = createGoogleSearchSourceBundle(
390 GOOGLE_SEARCH_SOURCE_SEARCHKEY);
391 bundle.putBoolean(SearchManager.CONTEXT_IS_VOICE, true);
392 startSearch(result, false, bundle, false);
Leon Scroggins58d56c62010-01-28 15:12:40 -0500393 }
394
The Android Open Source Project0c908882009-03-03 19:32:16 -0800395 @Override
396 protected void onNewIntent(Intent intent) {
Grace Kloba22ac16e2009-10-07 18:00:23 -0700397 Tab current = mTabControl.getCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800398 // When a tab is closed on exit, the current tab index is set to -1.
399 // Reset before proceed as Browser requires the current tab to be set.
400 if (current == null) {
401 // Try to reset the tab in case the index was incorrect.
402 current = mTabControl.getTab(0);
403 if (current == null) {
404 // No tabs at all so just ignore this intent.
405 return;
406 }
407 mTabControl.setCurrentTab(current);
408 attachTabToContentView(current);
409 resetTitleAndIcon(current.getWebView());
410 }
411 final String action = intent.getAction();
412 final int flags = intent.getFlags();
413 if (Intent.ACTION_MAIN.equals(action) ||
414 (flags & Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY) != 0) {
415 // just resume the browser
416 return;
417 }
Leon Scrogginsb8a844d2010-03-18 15:06:15 -0400418 // In case the SearchDialog is open.
419 ((SearchManager) getSystemService(Context.SEARCH_SERVICE))
420 .stopSearch();
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -0500421 boolean activateVoiceSearch = RecognizerResultsIntent
422 .ACTION_VOICE_SEARCH_RESULTS.equals(action);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800423 if (Intent.ACTION_VIEW.equals(action)
424 || Intent.ACTION_SEARCH.equals(action)
425 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
Leon Scroggins58d56c62010-01-28 15:12:40 -0500426 || Intent.ACTION_WEB_SEARCH.equals(action)
427 || activateVoiceSearch) {
Leon Scroggins3b18ce32010-02-08 17:35:59 -0500428 if (current.isInVoiceSearchMode()) {
429 String title = current.getVoiceDisplayTitle();
430 if (title != null && title.equals(intent.getStringExtra(
431 SearchManager.QUERY))) {
432 // The user submitted the same search as the last voice
433 // search, so do nothing.
434 return;
435 }
Leon Scroggins1fe13a52010-02-09 15:31:26 -0500436 if (Intent.ACTION_SEARCH.equals(action)
437 && current.voiceSearchSourceIsGoogle()) {
438 Intent logIntent = new Intent(
439 LoggingEvents.ACTION_LOG_EVENT);
440 logIntent.putExtra(LoggingEvents.EXTRA_EVENT,
441 LoggingEvents.VoiceSearch.QUERY_UPDATED);
442 logIntent.putExtra(
443 LoggingEvents.VoiceSearch.EXTRA_QUERY_UPDATED_VALUE,
444 intent.getDataString());
445 sendBroadcast(logIntent);
446 // Note, onPageStarted will revert the voice title bar
447 // When http://b/issue?id=2379215 is fixed, we should update
448 // the title bar here.
449 }
Leon Scroggins3b18ce32010-02-08 17:35:59 -0500450 }
Satish Sampath565505b2009-05-29 15:37:27 +0100451 // If this was a search request (e.g. search query directly typed into the address bar),
452 // pass it on to the default web search provider.
453 if (handleWebSearchIntent(intent)) {
454 return;
455 }
456
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700457 UrlData urlData = getUrlDataFromIntent(intent);
458 if (urlData.isEmpty()) {
459 urlData = new UrlData(mSettings.getHomePage());
The Android Open Source Project0c908882009-03-03 19:32:16 -0800460 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700461
Grace Klobacc634032009-07-28 15:58:19 -0700462 final String appId = intent
463 .getStringExtra(Browser.EXTRA_APPLICATION_ID);
Leon Scroggins47208682010-04-07 17:59:48 -0400464 if ((Intent.ACTION_VIEW.equals(action)
465 // If a voice search has no appId, it means that it came
466 // from the browser. In that case, reuse the current tab.
467 || (activateVoiceSearch && appId != null))
Grace Klobacc634032009-07-28 15:58:19 -0700468 && !getPackageName().equals(appId)
469 && (flags & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0) {
Grace Kloba22ac16e2009-10-07 18:00:23 -0700470 Tab appTab = mTabControl.getTabFromId(appId);
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700471 if (appTab != null) {
472 Log.i(LOGTAG, "Reusing tab for " + appId);
473 // Dismiss the subwindow if applicable.
474 dismissSubWindow(appTab);
475 // Since we might kill the WebView, remove it from the
476 // content view first.
477 removeTabFromContentView(appTab);
478 // Recreate the main WebView after destroying the old one.
479 // If the WebView has the same original url and is on that
480 // page, it can be reused.
481 boolean needsLoad =
Leon Scroggins6eac63e2010-03-15 18:19:14 -0400482 mTabControl.recreateWebView(appTab, urlData);
Ben Murdochbff2d602009-07-01 20:19:05 +0100483
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700484 if (current != appTab) {
Leon Scroggins1f005d32009-08-10 17:36:42 -0400485 switchToTab(mTabControl.getTabIndex(appTab));
486 if (needsLoad) {
Patrick Scott9d53da02010-02-19 10:19:01 -0500487 loadUrlDataIn(appTab, urlData);
Leon Scroggins1f005d32009-08-10 17:36:42 -0400488 }
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700489 } else {
Leon Scroggins1f005d32009-08-10 17:36:42 -0400490 // If the tab was the current tab, we have to attach
491 // it to the view system again.
492 attachTabToContentView(appTab);
493 if (needsLoad) {
Patrick Scott9d53da02010-02-19 10:19:01 -0500494 loadUrlDataIn(appTab, urlData);
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700495 }
496 }
497 return;
Patrick Scottcd115892009-07-16 09:42:58 -0400498 } else {
499 // No matching application tab, try to find a regular tab
500 // with a matching url.
501 appTab = mTabControl.findUnusedTabWithUrl(urlData.mUrl);
Leon Scroggins25515f82009-08-19 15:31:58 -0400502 if (appTab != null) {
503 if (current != appTab) {
504 switchToTab(mTabControl.getTabIndex(appTab));
505 }
506 // Otherwise, we are already viewing the correct tab.
Patrick Scottcd115892009-07-16 09:42:58 -0400507 } else {
508 // if FLAG_ACTIVITY_BROUGHT_TO_FRONT flag is on, the url
509 // will be opened in a new tab unless we have reached
510 // MAX_TABS. Then the url will be opened in the current
511 // tab. If a new tab is created, it will have "true" for
512 // exit on close.
Leon Scroggins1f005d32009-08-10 17:36:42 -0400513 openTabAndShow(urlData, true, appId);
Patrick Scottcd115892009-07-16 09:42:58 -0400514 }
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700515 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800516 } else {
Grace Kloba638d3f42009-11-23 10:35:04 -0800517 if (!urlData.isEmpty()
518 && urlData.mUrl.startsWith("about:debug")) {
519 if ("about:debug.dom".equals(urlData.mUrl)) {
520 current.getWebView().dumpDomTree(false);
521 } else if ("about:debug.dom.file".equals(urlData.mUrl)) {
522 current.getWebView().dumpDomTree(true);
523 } else if ("about:debug.render".equals(urlData.mUrl)) {
524 current.getWebView().dumpRenderTree(false);
525 } else if ("about:debug.render.file".equals(urlData.mUrl)) {
526 current.getWebView().dumpRenderTree(true);
527 } else if ("about:debug.display".equals(urlData.mUrl)) {
528 current.getWebView().dumpDisplayTree();
Mike Reed9b78e1d2010-01-13 14:40:52 -0800529 } else if (urlData.mUrl.startsWith("about:debug.drag")) {
530 int index = urlData.mUrl.codePointAt(16) - '0';
531 if (index <= 0 || index > 9) {
532 current.getWebView().setDragTracker(null);
533 } else {
534 current.getWebView().setDragTracker(new MeshTracker(index));
535 }
Grace Kloba638d3f42009-11-23 10:35:04 -0800536 } else {
537 mSettings.toggleDebugSettings();
538 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800539 return;
540 }
Leon Scroggins1f005d32009-08-10 17:36:42 -0400541 // Get rid of the subwindow if it exists
542 dismissSubWindow(current);
Leon Scroggins8588d152010-04-15 11:01:53 -0400543 // If the current Tab is being used as an application tab,
544 // remove the association, since the new Intent means that it is
545 // no longer associated with that application.
546 current.setAppId(null);
Patrick Scott9d53da02010-02-19 10:19:01 -0500547 loadUrlDataIn(current, urlData);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800548 }
549 }
550 }
551
Satish Sampath565505b2009-05-29 15:37:27 +0100552 private int parseUrlShortcut(String url) {
553 if (url == null) return SHORTCUT_INVALID;
554
555 // FIXME: quick search, need to be customized by setting
556 if (url.length() > 2 && url.charAt(1) == ' ') {
557 switch (url.charAt(0)) {
558 case 'g': return SHORTCUT_GOOGLE_SEARCH;
559 case 'w': return SHORTCUT_WIKIPEDIA_SEARCH;
560 case 'd': return SHORTCUT_DICTIONARY_SEARCH;
561 case 'l': return SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH;
562 }
563 }
564 return SHORTCUT_INVALID;
565 }
566
567 /**
568 * Launches the default web search activity with the query parameters if the given intent's data
569 * are identified as plain search terms and not URLs/shortcuts.
570 * @return true if the intent was handled and web search activity was launched, false if not.
571 */
572 private boolean handleWebSearchIntent(Intent intent) {
573 if (intent == null) return false;
574
575 String url = null;
576 final String action = intent.getAction();
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -0500577 if (RecognizerResultsIntent.ACTION_VOICE_SEARCH_RESULTS.equals(
578 action)) {
Leon Scroggins58d56c62010-01-28 15:12:40 -0500579 return false;
580 }
Satish Sampath565505b2009-05-29 15:37:27 +0100581 if (Intent.ACTION_VIEW.equals(action)) {
Grace Kloba1e705052009-09-29 13:13:36 -0700582 Uri data = intent.getData();
583 if (data != null) url = data.toString();
Satish Sampath565505b2009-05-29 15:37:27 +0100584 } else if (Intent.ACTION_SEARCH.equals(action)
585 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
586 || Intent.ACTION_WEB_SEARCH.equals(action)) {
587 url = intent.getStringExtra(SearchManager.QUERY);
588 }
Bjorn Bringert04851702009-09-22 10:36:01 +0100589 return handleWebSearchRequest(url, intent.getBundleExtra(SearchManager.APP_DATA),
590 intent.getStringExtra(SearchManager.EXTRA_DATA_KEY));
Satish Sampath565505b2009-05-29 15:37:27 +0100591 }
592
593 /**
594 * Launches the default web search activity with the query parameters if the given url string
595 * was identified as plain search terms and not URL/shortcut.
596 * @return true if the request was handled and web search activity was launched, false if not.
597 */
Bjorn Bringert04851702009-09-22 10:36:01 +0100598 private boolean handleWebSearchRequest(String inUrl, Bundle appData, String extraData) {
Satish Sampath565505b2009-05-29 15:37:27 +0100599 if (inUrl == null) return false;
600
601 // In general, we shouldn't modify URL from Intent.
602 // But currently, we get the user-typed URL from search box as well.
603 String url = fixUrl(inUrl).trim();
604
605 // URLs and site specific search shortcuts are handled by the regular flow of control, so
606 // return early.
Dan Egnor5ee906c2009-11-18 12:11:49 -0800607 if (Patterns.WEB_URL.matcher(url).matches()
Satish Sampathbc5b9f32009-06-04 18:21:40 +0100608 || ACCEPTED_URI_SCHEMA.matcher(url).matches()
Satish Sampath565505b2009-05-29 15:37:27 +0100609 || parseUrlShortcut(url) != SHORTCUT_INVALID) {
610 return false;
611 }
612
Leon Scroggins8d06e362010-03-24 14:45:57 -0400613 final ContentResolver cr = mResolver;
614 final String newUrl = url;
Elliott Slaughter627d96f2010-08-18 16:35:30 -0700615 if (mTabControl == null || !mTabControl.getCurrentWebView().isPrivateBrowsingEnabled()) {
Elliott Slaughterf0f03952010-07-14 18:10:36 -0700616 new AsyncTask<Void, Void, Void>() {
617 @Override
618 protected Void doInBackground(Void... unused) {
619 Browser.updateVisitedHistory(cr, newUrl, false);
620 Browser.addSearchUrl(cr, newUrl);
621 return null;
622 }
623 }.execute();
624 }
Satish Sampath565505b2009-05-29 15:37:27 +0100625
Bjorn Bringertd69f51d2010-09-13 14:06:41 +0100626 SearchEngine searchEngine = mSettings.getSearchEngine();
627 if (searchEngine == null) return false;
628 searchEngine.startSearch(this, url, appData, extraData);
Satish Sampath565505b2009-05-29 15:37:27 +0100629
630 return true;
631 }
632
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700633 private UrlData getUrlDataFromIntent(Intent intent) {
Leon Scroggins58d56c62010-01-28 15:12:40 -0500634 String url = "";
Grace Kloba068e48b2010-01-26 18:11:27 -0800635 Map<String, String> headers = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800636 if (intent != null) {
637 final String action = intent.getAction();
638 if (Intent.ACTION_VIEW.equals(action)) {
639 url = smartUrlFilter(intent.getData());
640 if (url != null && url.startsWith("content:")) {
641 /* Append mimetype so webview knows how to display */
642 String mimeType = intent.resolveType(getContentResolver());
643 if (mimeType != null) {
644 url += "?" + mimeType;
645 }
646 }
Grace Kloba068e48b2010-01-26 18:11:27 -0800647 if (url != null && url.startsWith("http")) {
Grace Kloba00f54c52010-01-27 14:53:51 -0800648 final Bundle pairs = intent
649 .getBundleExtra(Browser.EXTRA_HEADERS);
Grace Kloba2d508ed2010-01-28 11:39:15 -0800650 if (pairs != null && !pairs.isEmpty()) {
Grace Kloba00f54c52010-01-27 14:53:51 -0800651 Iterator<String> iter = pairs.keySet().iterator();
Grace Kloba068e48b2010-01-26 18:11:27 -0800652 headers = new HashMap<String, String>();
Grace Kloba00f54c52010-01-27 14:53:51 -0800653 while (iter.hasNext()) {
654 String key = iter.next();
655 headers.put(key, pairs.getString(key));
Grace Kloba068e48b2010-01-26 18:11:27 -0800656 }
657 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700658 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800659 } else if (Intent.ACTION_SEARCH.equals(action)
660 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
661 || Intent.ACTION_WEB_SEARCH.equals(action)) {
662 url = intent.getStringExtra(SearchManager.QUERY);
663 if (url != null) {
664 mLastEnteredUrl = url;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800665 // In general, we shouldn't modify URL from Intent.
666 // But currently, we get the user-typed URL from search box as well.
667 url = fixUrl(url);
668 url = smartUrlFilter(url);
Leon Scroggins8d06e362010-03-24 14:45:57 -0400669 final ContentResolver cr = mResolver;
670 final String newUrl = url;
Elliott Slaughter8389e992010-08-20 15:44:08 -0700671 if (mTabControl == null
672 || mTabControl.getCurrentWebView() == null
673 || !mTabControl.getCurrentWebView().isPrivateBrowsingEnabled()) {
674 new AsyncTask<Void, Void, Void>() {
675 @Override
676 protected Void doInBackground(Void... unused) {
677 Browser.updateVisitedHistory(cr, newUrl, false);
678 return null;
679 }
680 }.execute();
681 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800682 String searchSource = "&source=android-" + GOOGLE_SEARCH_SOURCE_SUGGEST + "&";
683 if (url.contains(searchSource)) {
684 String source = null;
685 final Bundle appData = intent.getBundleExtra(SearchManager.APP_DATA);
686 if (appData != null) {
Bjorn Bringert10d1cca2010-02-10 14:22:12 +0000687 source = appData.getString(Search.SOURCE);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800688 }
689 if (TextUtils.isEmpty(source)) {
690 source = GOOGLE_SEARCH_SOURCE_UNKNOWN;
691 }
692 url = url.replace(searchSource, "&source=android-"+source+"&");
693 }
694 }
695 }
696 }
Leon Scroggins58d56c62010-01-28 15:12:40 -0500697 return new UrlData(url, headers, intent);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800698 }
Leon Scroggins58d56c62010-01-28 15:12:40 -0500699 /* package */ void showVoiceTitleBar(String title) {
700 mTitleBar.setInVoiceMode(true);
Leon Scroggins58d56c62010-01-28 15:12:40 -0500701 mTitleBar.setDisplayTitle(title);
Michael Kolba2b2ba82010-08-04 17:54:03 -0700702 mFakeTitleBar.setInVoiceMode(true);
703 mFakeTitleBar.setDisplayTitle(title);
Leon Scroggins58d56c62010-01-28 15:12:40 -0500704 }
705 /* package */ void revertVoiceTitleBar() {
706 mTitleBar.setInVoiceMode(false);
Leon Scroggins003a5dd2010-03-10 12:13:14 -0500707 mTitleBar.setDisplayTitle(mUrl);
Michael Kolba2b2ba82010-08-04 17:54:03 -0700708 mFakeTitleBar.setInVoiceMode(false);
709 mFakeTitleBar.setDisplayTitle(mUrl);
Leon Scroggins58d56c62010-01-28 15:12:40 -0500710 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800711 /* package */ static String fixUrl(String inUrl) {
Cary Clark652ff872009-09-10 13:34:44 -0400712 // FIXME: Converting the url to lower case
713 // duplicates functionality in smartUrlFilter().
714 // However, changing all current callers of fixUrl to
715 // call smartUrlFilter in addition may have unwanted
716 // consequences, and is deferred for now.
717 int colon = inUrl.indexOf(':');
718 boolean allLower = true;
719 for (int index = 0; index < colon; index++) {
720 char ch = inUrl.charAt(index);
721 if (!Character.isLetter(ch)) {
722 break;
723 }
724 allLower &= Character.isLowerCase(ch);
725 if (index == colon - 1 && !allLower) {
726 inUrl = inUrl.substring(0, colon).toLowerCase()
727 + inUrl.substring(colon);
728 }
729 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800730 if (inUrl.startsWith("http://") || inUrl.startsWith("https://"))
731 return inUrl;
732 if (inUrl.startsWith("http:") ||
733 inUrl.startsWith("https:")) {
734 if (inUrl.startsWith("http:/") || inUrl.startsWith("https:/")) {
735 inUrl = inUrl.replaceFirst("/", "//");
736 } else inUrl = inUrl.replaceFirst(":", "://");
737 }
738 return inUrl;
739 }
740
Grace Kloba22ac16e2009-10-07 18:00:23 -0700741 @Override
742 protected void onResume() {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800743 super.onResume();
Dave Bort31a6d1c2009-04-13 15:56:49 -0700744 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800745 Log.v(LOGTAG, "BrowserActivity.onResume: this=" + this);
746 }
747
748 if (!mActivityInPause) {
749 Log.e(LOGTAG, "BrowserActivity is already resumed.");
750 return;
751 }
752
Mike Reed7bfa63b2009-05-28 11:08:32 -0400753 mTabControl.resumeCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800754 mActivityInPause = false;
Mike Reed7bfa63b2009-05-28 11:08:32 -0400755 resumeWebViewTimers();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800756
757 if (mWakeLock.isHeld()) {
758 mHandler.removeMessages(RELEASE_WAKELOCK);
759 mWakeLock.release();
760 }
761
The Android Open Source Project0c908882009-03-03 19:32:16 -0800762 registerReceiver(mNetworkStateIntentReceiver,
763 mNetworkStateChangedFilter);
764 WebView.enablePlatformNotifications();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800765 }
766
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400767 /**
768 * Since the actual title bar is embedded in the WebView, and removing it
Leon Scrogginsfe87bd32009-10-06 10:10:00 -0400769 * would change its appearance, use a different TitleBar to show overlayed
770 * at the top of the screen, when the menu is open or the page is loading.
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400771 */
Michael Kolba2b2ba82010-08-04 17:54:03 -0700772 private TitleBarBase mFakeTitleBar;
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400773
774 /**
775 * Keeps track of whether the options menu is open. This is important in
776 * determining whether to show or hide the title bar overlay.
777 */
778 private boolean mOptionsMenuOpen;
779
780 /**
781 * Only meaningful when mOptionsMenuOpen is true. This variable keeps track
782 * of whether the configuration has changed. The first onMenuOpened call
783 * after a configuration change is simply a reopening of the same menu
784 * (i.e. mIconView did not change).
785 */
786 private boolean mConfigChanged;
787
788 /**
789 * Whether or not the options menu is in its smaller, icon menu form. When
790 * true, we want the title bar overlay to be up. When false, we do not.
791 * Only meaningful if mOptionsMenuOpen is true.
792 */
793 private boolean mIconView;
794
Leon Scrogginsa81a7642009-08-31 17:05:41 -0400795 @Override
796 public boolean onMenuOpened(int featureId, Menu menu) {
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400797 if (Window.FEATURE_OPTIONS_PANEL == featureId) {
798 if (mOptionsMenuOpen) {
799 if (mConfigChanged) {
800 // We do not need to make any changes to the state of the
801 // title bar, since the only thing that happened was a
802 // change in orientation
803 mConfigChanged = false;
804 } else {
805 if (mIconView) {
806 // Switching the menu to expanded view, so hide the
807 // title bar.
808 hideFakeTitleBar();
809 mIconView = false;
810 } else {
811 // Switching the menu back to icon view, so show the
812 // title bar once again.
813 showFakeTitleBar();
814 mIconView = true;
815 }
816 }
817 } else {
818 // The options menu is closed, so open it, and show the title
819 showFakeTitleBar();
820 mOptionsMenuOpen = true;
821 mConfigChanged = false;
822 mIconView = true;
823 }
824 }
Leon Scrogginsa81a7642009-08-31 17:05:41 -0400825 return true;
826 }
827
Michael Kolba2b2ba82010-08-04 17:54:03 -0700828 void showFakeTitleBar() {
829 if (!isFakeTitleBarShowing() && mActiveTabsPage == null && !mActivityInPause) {
Grace Kloba847c25b2010-03-30 16:00:26 -0700830 WebView mainView = mTabControl.getCurrentWebView();
831 // if there is no current WebView, don't show the faked title bar;
Grace Kloba65190702010-04-02 23:37:26 -0700832 if (mainView == null) {
Cary Clarka0464552009-09-29 13:00:45 -0400833 return;
834 }
Leon Scroggins79e36d92010-04-29 16:01:46 +0100835 // Do not need to check for null, since the current tab will have
836 // at least a main WebView, or we would have returned above.
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -0400837 if (isInCustomActionMode()) {
838 // Do not show the fake title bar, while a custom ActionMode
839 // (i.e. find or select) is showing.
Leon Scroggins79e36d92010-04-29 16:01:46 +0100840 return;
841 }
Michael Kolba2b2ba82010-08-04 17:54:03 -0700842 if (mXLargeScreenSize) {
843 mContentView.addView(mFakeTitleBar);
844 mTabBar.onShowTitleBar();
845 } else {
846 WindowManager manager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400847
Michael Kolba2b2ba82010-08-04 17:54:03 -0700848 // Add the title bar to the window manager so it can receive
849 // touches
850 // while the menu is up
851 WindowManager.LayoutParams params =
852 new WindowManager.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
853 ViewGroup.LayoutParams.WRAP_CONTENT,
854 WindowManager.LayoutParams.TYPE_APPLICATION,
855 WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
856 PixelFormat.TRANSLUCENT);
857 params.gravity = Gravity.TOP;
858 boolean atTop = mainView.getScrollY() == 0;
859 params.windowAnimations = atTop ? 0 : R.style.TitleBar;
860 manager.addView(mFakeTitleBar, params);
861 }
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400862 }
863 }
864
865 @Override
866 public void onOptionsMenuClosed(Menu menu) {
867 mOptionsMenuOpen = false;
Leon Scrogginsa27ff192009-09-14 12:58:04 -0400868 if (!mInLoad) {
869 hideFakeTitleBar();
870 } else if (!mIconView) {
871 // The page is currently loading, and we are in expanded mode, so
872 // we were not showing the menu. Show it once again. It will be
873 // removed when the page finishes.
874 showFakeTitleBar();
875 }
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400876 }
Grace Kloba22ac16e2009-10-07 18:00:23 -0700877
Michael Kolba2b2ba82010-08-04 17:54:03 -0700878 void stopScrolling() {
879 ((ScrollWebView) mTabControl.getCurrentWebView()).stopScroll();
880 }
881
882 void hideFakeTitleBar() {
883 if (!isFakeTitleBarShowing()) return;
884 if (mXLargeScreenSize) {
885 mContentView.removeView(mFakeTitleBar);
886 mTabBar.onHideTitleBar();
887 } else {
888 WindowManager.LayoutParams params =
889 (WindowManager.LayoutParams) mFakeTitleBar.getLayoutParams();
890 WebView mainView = mTabControl.getCurrentWebView();
891 // Although we decided whether or not to animate based on the
892 // current
893 // scroll position, the scroll position may have changed since the
894 // fake title bar was displayed. Make sure it has the appropriate
895 // animation/lack thereof before removing.
896 params.windowAnimations =
897 mainView != null && mainView.getScrollY() == 0 ? 0 : R.style.TitleBar;
898 WindowManager manager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
899 manager.updateViewLayout(mFakeTitleBar, params);
900 manager.removeView(mFakeTitleBar);
901 }
902 }
903
904 boolean isFakeTitleBarShowing() {
905 return (mFakeTitleBar.getParent() != null);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400906 }
907
The Android Open Source Project0c908882009-03-03 19:32:16 -0800908 /**
Leon Scrogginsc6fa1102009-09-21 10:40:01 -0400909 * Special method for the fake title bar to call when displaying its context
910 * menu, since it is in its own Window, and its parent does not show a
911 * context menu.
912 */
913 /* package */ void showTitleBarContextMenu() {
Cary Clark65f4a3c2009-09-28 17:05:06 -0400914 if (null == mTitleBar.getParent()) {
915 return;
916 }
Leon Scrogginsc6fa1102009-09-21 10:40:01 -0400917 openContextMenu(mTitleBar);
918 }
919
Leon Scrogginsb2b19f52009-10-09 16:10:00 -0400920 @Override
921 public void onContextMenuClosed(Menu menu) {
922 super.onContextMenuClosed(menu);
923 if (mInLoad) {
924 showFakeTitleBar();
925 }
926 }
927
Leon Scrogginsc6fa1102009-09-21 10:40:01 -0400928 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -0800929 * onSaveInstanceState(Bundle map)
930 * onSaveInstanceState is called right before onStop(). The map contains
931 * the saved state.
932 */
Grace Kloba22ac16e2009-10-07 18:00:23 -0700933 @Override
934 protected void onSaveInstanceState(Bundle outState) {
Dave Bort31a6d1c2009-04-13 15:56:49 -0700935 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800936 Log.v(LOGTAG, "BrowserActivity.onSaveInstanceState: this=" + this);
937 }
938 // the default implementation requires each view to have an id. As the
939 // browser handles the state itself and it doesn't use id for the views,
940 // don't call the default implementation. Otherwise it will trigger the
941 // warning like this, "couldn't save which view has focus because the
942 // focused view XXX has no id".
943
944 // Save all the tabs
945 mTabControl.saveState(outState);
Elliott Slaughter3d6df162010-08-25 13:17:44 -0700946
947 // Save time so that we know how old incognito tabs (if any) are.
948 outState.putSerializable("lastActiveDate", Calendar.getInstance());
The Android Open Source Project0c908882009-03-03 19:32:16 -0800949 }
950
Grace Kloba22ac16e2009-10-07 18:00:23 -0700951 @Override
952 protected void onPause() {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800953 super.onPause();
954
955 if (mActivityInPause) {
956 Log.e(LOGTAG, "BrowserActivity is already paused.");
957 return;
958 }
959
Mike Reed7bfa63b2009-05-28 11:08:32 -0400960 mTabControl.pauseCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800961 mActivityInPause = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -0400962 if (mTabControl.getCurrentIndex() >= 0 && !pauseWebViewTimers()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800963 mWakeLock.acquire();
964 mHandler.sendMessageDelayed(mHandler
965 .obtainMessage(RELEASE_WAKELOCK), WAKELOCK_TIMEOUT);
966 }
967
Leon Scrogginsa2ab6a72009-09-11 11:49:52 -0400968 // FIXME: This removes the active tabs page and resets the menu to
969 // MAIN_MENU. A better solution might be to do this work in onNewIntent
970 // but then we would need to save it in onSaveInstanceState and restore
971 // it in onCreate/onRestoreInstanceState
972 if (mActiveTabsPage != null) {
973 removeActiveTabPage(true);
974 }
975
The Android Open Source Project0c908882009-03-03 19:32:16 -0800976 cancelStopToast();
977
978 // unregister network state listener
979 unregisterReceiver(mNetworkStateIntentReceiver);
980 WebView.disablePlatformNotifications();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800981 }
982
Grace Kloba22ac16e2009-10-07 18:00:23 -0700983 @Override
984 protected void onDestroy() {
Dave Bort31a6d1c2009-04-13 15:56:49 -0700985 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800986 Log.v(LOGTAG, "BrowserActivity.onDestroy: this=" + this);
987 }
988 super.onDestroy();
Grace Kloba0923d692009-09-23 21:37:25 -0700989
Leon Scroggins8d5fa432009-10-02 15:55:59 -0400990 if (mUploadMessage != null) {
991 mUploadMessage.onReceiveValue(null);
992 mUploadMessage = null;
993 }
994
Grace Kloba0923d692009-09-23 21:37:25 -0700995 if (mTabControl == null) return;
996
Grace Kloba1fc98a32009-10-21 13:23:08 -0700997 // Remove the fake title bar if it is there
998 hideFakeTitleBar();
999
The Android Open Source Project0c908882009-03-03 19:32:16 -08001000 // Remove the current tab and sub window
Grace Kloba22ac16e2009-10-07 18:00:23 -07001001 Tab t = mTabControl.getCurrentTab();
Patrick Scottfb5e77f2009-04-08 19:17:37 -07001002 if (t != null) {
1003 dismissSubWindow(t);
1004 removeTabFromContentView(t);
1005 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001006 // Destroy all the tabs
1007 mTabControl.destroy();
1008 WebIconDatabase.getInstance().close();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001009
Bjorn Bringerta7611812010-03-24 11:12:02 +00001010 // Stop watching the default geolocation permissions
1011 mSystemAllowGeolocationOrigins.stop();
1012 mSystemAllowGeolocationOrigins = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001013 }
1014
1015 @Override
1016 public void onConfigurationChanged(Configuration newConfig) {
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04001017 mConfigChanged = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001018 super.onConfigurationChanged(newConfig);
1019
1020 if (mPageInfoDialog != null) {
1021 mPageInfoDialog.dismiss();
1022 showPageInfo(
1023 mPageInfoView,
Leon Scrogginsc7b92f82010-01-11 18:17:31 -05001024 mPageInfoFromShowSSLCertificateOnError);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001025 }
1026 if (mSSLCertificateDialog != null) {
1027 mSSLCertificateDialog.dismiss();
1028 showSSLCertificate(
1029 mSSLCertificateView);
1030 }
1031 if (mSSLCertificateOnErrorDialog != null) {
1032 mSSLCertificateOnErrorDialog.dismiss();
1033 showSSLCertificateOnError(
1034 mSSLCertificateOnErrorView,
1035 mSSLCertificateOnErrorHandler,
1036 mSSLCertificateOnErrorError);
1037 }
1038 if (mHttpAuthenticationDialog != null) {
1039 String title = ((TextView) mHttpAuthenticationDialog
1040 .findViewById(com.android.internal.R.id.alertTitle)).getText()
1041 .toString();
1042 String name = ((TextView) mHttpAuthenticationDialog
1043 .findViewById(R.id.username_edit)).getText().toString();
1044 String password = ((TextView) mHttpAuthenticationDialog
1045 .findViewById(R.id.password_edit)).getText().toString();
1046 int focusId = mHttpAuthenticationDialog.getCurrentFocus()
1047 .getId();
1048 mHttpAuthenticationDialog.dismiss();
1049 showHttpAuthentication(mHttpAuthHandler, null, null, title,
1050 name, password, focusId);
1051 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001052 }
1053
Grace Kloba22ac16e2009-10-07 18:00:23 -07001054 @Override
1055 public void onLowMemory() {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001056 super.onLowMemory();
1057 mTabControl.freeMemory();
1058 }
1059
Cary Clarkff4d92c2010-03-25 11:17:03 -04001060 private void resumeWebViewTimers() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001061 Tab tab = mTabControl.getCurrentTab();
Cary Clarkff4d92c2010-03-25 11:17:03 -04001062 if (tab == null) return; // monkey can trigger this
Grace Kloba22ac16e2009-10-07 18:00:23 -07001063 boolean inLoad = tab.inLoad();
1064 if ((!mActivityInPause && !inLoad) || (mActivityInPause && inLoad)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001065 CookieSyncManager.getInstance().startSync();
Grace Kloba22ac16e2009-10-07 18:00:23 -07001066 WebView w = tab.getWebView();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001067 if (w != null) {
1068 w.resumeTimers();
1069 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001070 }
1071 }
1072
Mike Reed7bfa63b2009-05-28 11:08:32 -04001073 private boolean pauseWebViewTimers() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001074 Tab tab = mTabControl.getCurrentTab();
1075 boolean inLoad = tab.inLoad();
1076 if (mActivityInPause && !inLoad) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001077 CookieSyncManager.getInstance().stopSync();
1078 WebView w = mTabControl.getCurrentWebView();
1079 if (w != null) {
1080 w.pauseTimers();
1081 }
1082 return true;
1083 } else {
1084 return false;
1085 }
1086 }
1087
The Android Open Source Project0c908882009-03-03 19:32:16 -08001088 // Open the icon database and retain all the icons for visited sites.
1089 private void retainIconsOnStartup() {
1090 final WebIconDatabase db = WebIconDatabase.getInstance();
1091 db.open(getDir("icons", 0).getPath());
Leon Scroggins2c0f6112010-03-12 18:09:39 -05001092 Cursor c = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001093 try {
Leon Scroggins2c0f6112010-03-12 18:09:39 -05001094 c = Browser.getAllBookmarks(mResolver);
1095 if (c.moveToFirst()) {
1096 int urlIndex = c.getColumnIndex(Browser.BookmarkColumns.URL);
1097 do {
1098 String url = c.getString(urlIndex);
1099 db.retainIconForPageUrl(url);
1100 } while (c.moveToNext());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001101 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001102 } catch (IllegalStateException e) {
1103 Log.e(LOGTAG, "retainIconsOnStartup", e);
Leon Scroggins2c0f6112010-03-12 18:09:39 -05001104 } finally {
1105 if (c!= null) c.close();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001106 }
1107 }
1108
1109 // Helper method for getting the top window.
1110 WebView getTopWindow() {
1111 return mTabControl.getCurrentTopWebView();
1112 }
1113
Grace Kloba22ac16e2009-10-07 18:00:23 -07001114 TabControl getTabControl() {
1115 return mTabControl;
1116 }
1117
The Android Open Source Project0c908882009-03-03 19:32:16 -08001118 @Override
1119 public boolean onCreateOptionsMenu(Menu menu) {
1120 super.onCreateOptionsMenu(menu);
1121
1122 MenuInflater inflater = getMenuInflater();
1123 inflater.inflate(R.menu.browser, menu);
1124 mMenu = menu;
1125 updateInLoadMenuItems();
1126 return true;
1127 }
1128
1129 /**
1130 * As the menu can be open when loading state changes
1131 * we must manually update the state of the stop/reload menu
1132 * item
1133 */
1134 private void updateInLoadMenuItems() {
1135 if (mMenu == null) {
1136 return;
1137 }
Michael Kolbe0a36662010-06-29 10:37:12 -07001138 MenuItem dest = mMenu.findItem(R.id.stop_reload_menu_id);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001139 MenuItem src = mInLoad ?
1140 mMenu.findItem(R.id.stop_menu_id):
Michael Kolbe0a36662010-06-29 10:37:12 -07001141 mMenu.findItem(R.id.reload_menu_id);
1142 if (src != null) {
1143 dest.setIcon(src.getIcon());
1144 dest.setTitle(src.getTitle());
1145 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001146 }
1147
1148 @Override
1149 public boolean onContextItemSelected(MenuItem item) {
1150 // chording is not an issue with context menus, but we use the same
1151 // options selector, so set mCanChord to true so we can access them.
1152 mCanChord = true;
1153 int id = item.getItemId();
Leon Scroggins96afcb12009-12-10 12:35:56 -05001154 boolean result = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001155 switch (id) {
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001156 // For the context menu from the title bar
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001157 case R.id.title_bar_copy_page_url:
Leon Scroggins96afcb12009-12-10 12:35:56 -05001158 Tab currentTab = mTabControl.getCurrentTab();
1159 if (null == currentTab) {
1160 result = false;
1161 break;
1162 }
1163 WebView mainView = currentTab.getWebView();
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001164 if (null == mainView) {
Leon Scroggins96afcb12009-12-10 12:35:56 -05001165 result = false;
1166 break;
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001167 }
Leon Scroggins96afcb12009-12-10 12:35:56 -05001168 copy(mainView.getUrl());
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001169 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001170 // -- Browser context menu
1171 case R.id.open_context_menu_id:
The Android Open Source Project0c908882009-03-03 19:32:16 -08001172 case R.id.bookmark_context_menu_id:
1173 case R.id.save_link_context_menu_id:
1174 case R.id.share_link_context_menu_id:
1175 case R.id.copy_link_context_menu_id:
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001176 final WebView webView = getTopWindow();
1177 if (null == webView) {
Leon Scroggins96afcb12009-12-10 12:35:56 -05001178 result = false;
1179 break;
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001180 }
1181 final HashMap hrefMap = new HashMap();
1182 hrefMap.put("webview", webView);
1183 final Message msg = mHandler.obtainMessage(
1184 FOCUS_NODE_HREF, id, 0, hrefMap);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001185 webView.requestFocusNodeHref(msg);
1186 break;
1187
1188 default:
1189 // For other context menus
Leon Scroggins96afcb12009-12-10 12:35:56 -05001190 result = onOptionsItemSelected(item);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001191 }
1192 mCanChord = false;
Leon Scroggins96afcb12009-12-10 12:35:56 -05001193 return result;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001194 }
1195
1196 private Bundle createGoogleSearchSourceBundle(String source) {
1197 Bundle bundle = new Bundle();
Bjorn Bringert10d1cca2010-02-10 14:22:12 +00001198 bundle.putString(Search.SOURCE, source);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001199 return bundle;
1200 }
1201
Leon Scroggins8ad29922010-02-16 12:33:55 -05001202 /* package */ void editUrl() {
Leon Scroggins68579392009-09-15 15:31:54 -04001203 if (mOptionsMenuOpen) closeOptionsMenu();
Leon Scroggins5bbe9802009-07-31 13:10:55 -04001204 String url = (getTopWindow() == null) ? null : getTopWindow().getUrl();
Grace Kloba83f47342009-07-20 10:44:31 -07001205 startSearch(mSettings.getHomePage().equals(url) ? null : url, true,
Leon Scroggins8ad29922010-02-16 12:33:55 -05001206 null, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001207 }
1208
Leon Scroggins8ad29922010-02-16 12:33:55 -05001209 /**
1210 * Overriding this to insert a local information bundle
1211 */
The Android Open Source Project0c908882009-03-03 19:32:16 -08001212 @Override
1213 public void startSearch(String initialQuery, boolean selectInitialQuery,
1214 Bundle appSearchData, boolean globalSearch) {
1215 if (appSearchData == null) {
1216 appSearchData = createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_TYPE);
1217 }
1218 super.startSearch(initialQuery, selectInitialQuery, appSearchData, globalSearch);
1219 }
1220
Leon Scroggins1f005d32009-08-10 17:36:42 -04001221 /**
1222 * Switch tabs. Called by the TitleBarSet when sliding the title bar
1223 * results in changing tabs.
Leon Scroggins160a7e72009-08-14 18:28:01 -04001224 * @param index Index of the tab to change to, as defined by
1225 * mTabControl.getTabIndex(Tab t).
1226 * @return boolean True if we successfully switched to a different tab. If
1227 * the indexth tab is null, or if that tab is the same as
1228 * the current one, return false.
Leon Scroggins1f005d32009-08-10 17:36:42 -04001229 */
Leon Scroggins160a7e72009-08-14 18:28:01 -04001230 /* package */ boolean switchToTab(int index) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001231 Tab tab = mTabControl.getTab(index);
1232 Tab currentTab = mTabControl.getCurrentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04001233 if (tab == null || tab == currentTab) {
Leon Scroggins160a7e72009-08-14 18:28:01 -04001234 return false;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001235 }
1236 if (currentTab != null) {
1237 // currentTab may be null if it was just removed. In that case,
1238 // we do not need to remove it
1239 removeTabFromContentView(currentTab);
1240 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001241 mTabControl.setCurrentTab(tab);
1242 attachTabToContentView(tab);
Grace Klobaeb6eef42009-09-15 17:56:32 -07001243 resetTitleIconAndProgress();
1244 updateLockIconToLatest();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001245 return true;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001246 }
1247
Grace Kloba22ac16e2009-10-07 18:00:23 -07001248 /* package */ Tab openTabToHomePage() {
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001249 return openTabAndShow(mSettings.getHomePage(), false, null);
1250 }
1251
Leon Scroggins1f005d32009-08-10 17:36:42 -04001252 /* package */ void closeCurrentWindow() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001253 final Tab current = mTabControl.getCurrentTab();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001254 if (mTabControl.getTabCount() == 1) {
Leon Scroggins30444232009-09-04 18:36:20 -04001255 // This is the last tab. Open a new one, with the home
1256 // page and close the current one.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001257 openTabToHomePage();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001258 closeTab(current);
Leon Scroggins160a7e72009-08-14 18:28:01 -04001259 return;
1260 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07001261 final Tab parent = current.getParentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04001262 int indexToShow = -1;
1263 if (parent != null) {
1264 indexToShow = mTabControl.getTabIndex(parent);
1265 } else {
Leon Scroggins160a7e72009-08-14 18:28:01 -04001266 final int currentIndex = mTabControl.getCurrentIndex();
1267 // Try to move to the tab to the right
1268 indexToShow = currentIndex + 1;
1269 if (indexToShow > mTabControl.getTabCount() - 1) {
1270 // Try to move to the tab to the left
1271 indexToShow = currentIndex - 1;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001272 }
1273 }
Leon Scroggins160a7e72009-08-14 18:28:01 -04001274 if (switchToTab(indexToShow)) {
1275 // Close window
1276 closeTab(current);
1277 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001278 }
1279
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001280 private ActiveTabsPage mActiveTabsPage;
1281
1282 /**
1283 * Remove the active tabs page.
1284 * @param needToAttach If true, the active tabs page did not attach a tab
1285 * to the content view, so we need to do that here.
1286 */
1287 /* package */ void removeActiveTabPage(boolean needToAttach) {
1288 mContentView.removeView(mActiveTabsPage);
Leon Scrogginsd746a942010-05-19 13:21:44 -04001289 mTitleBar.setVisibility(View.VISIBLE);
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001290 mActiveTabsPage = null;
1291 mMenuState = R.id.MAIN_MENU;
1292 if (needToAttach) {
1293 attachTabToContentView(mTabControl.getCurrentTab());
1294 }
1295 getTopWindow().requestFocus();
1296 }
1297
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04001298 @Override
1299 public ActionMode onStartActionMode(ActionMode.Callback callback) {
Leon Scroggins4fc12cb2010-08-24 14:24:05 -04001300 mActionMode = super.onStartActionMode(callback);
1301 hideFakeTitleBar();
1302 // Would like to change the MENU, but onEndActionMode may not be called
1303 return mActionMode;
Cary Clark01cfcdd2010-06-04 16:36:45 -04001304 }
1305
The Android Open Source Project0c908882009-03-03 19:32:16 -08001306 @Override
1307 public boolean onOptionsItemSelected(MenuItem item) {
Michael Kolbed217742010-08-10 17:52:34 -07001308 // check the action bar button before mCanChord check, as the prepare call
1309 // doesn't come for action bar buttons
1310 if (item.getItemId() == R.id.newtab) {
Michael Kolb300b7f02010-08-25 13:47:24 -07001311 openTabToHomePage();
Michael Kolbed217742010-08-10 17:52:34 -07001312 return true;
1313 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001314 if (!mCanChord) {
1315 // The user has already fired a shortcut with this hold down of the
1316 // menu key.
1317 return false;
1318 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001319 if (null == getTopWindow()) {
Leon Scroggins0d7ae0e2009-06-05 11:04:45 -04001320 return false;
1321 }
Grace Kloba6ee9c492009-07-13 10:04:34 -07001322 if (mMenuIsDown) {
1323 // The shortcut action consumes the MENU. Even if it is still down,
1324 // it won't trigger the next shortcut action. In the case of the
1325 // shortcut action triggering a new activity, like Bookmarks, we
1326 // won't get onKeyUp for MENU. So it is important to reset it here.
1327 mMenuIsDown = false;
1328 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001329 switch (item.getItemId()) {
1330 // -- Main menu
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001331 case R.id.new_tab_menu_id:
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001332 openTabToHomePage();
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001333 break;
1334
Michael Kolbae62fd42010-08-18 16:33:28 -07001335 case R.id.incognito_menu_id:
1336 openIncognitoTab();
1337 break;
1338
Leon Scroggins64b80f32009-08-07 12:03:34 -04001339 case R.id.goto_menu_id:
Leon Scroggins8ad29922010-02-16 12:33:55 -05001340 editUrl();
Leon Scrogginsb3a5bed2009-09-28 11:21:56 -04001341 break;
1342
1343 case R.id.bookmarks_menu_id:
Michael Kolb68792c82010-08-09 16:39:18 -07001344 bookmarksOrHistoryPicker(false, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001345 break;
1346
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001347 case R.id.active_tabs_menu_id:
1348 mActiveTabsPage = new ActiveTabsPage(this, mTabControl);
1349 removeTabFromContentView(mTabControl.getCurrentTab());
Leon Scrogginsd746a942010-05-19 13:21:44 -04001350 mTitleBar.setVisibility(View.GONE);
Leon Scroggins43de6162009-09-14 19:59:58 -04001351 hideFakeTitleBar();
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001352 mContentView.addView(mActiveTabsPage, COVER_SCREEN_PARAMS);
1353 mActiveTabsPage.requestFocus();
1354 mMenuState = EMPTY_MENU;
1355 break;
1356
Leon Scroggins1f005d32009-08-10 17:36:42 -04001357 case R.id.add_bookmark_menu_id:
Leon Scroggins571b3762010-05-26 10:25:01 -04001358 bookmarkCurrentPage();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001359 break;
1360
1361 case R.id.stop_reload_menu_id:
1362 if (mInLoad) {
1363 stopLoading();
1364 } else {
1365 getTopWindow().reload();
1366 }
1367 break;
1368
1369 case R.id.back_menu_id:
1370 getTopWindow().goBack();
1371 break;
1372
1373 case R.id.forward_menu_id:
1374 getTopWindow().goForward();
1375 break;
1376
1377 case R.id.close_menu_id:
1378 // Close the subwindow if it exists.
1379 if (mTabControl.getCurrentSubWindow() != null) {
1380 dismissSubWindow(mTabControl.getCurrentTab());
1381 break;
1382 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001383 closeCurrentWindow();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001384 break;
1385
1386 case R.id.homepage_menu_id:
Grace Kloba22ac16e2009-10-07 18:00:23 -07001387 Tab current = mTabControl.getCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001388 if (current != null) {
1389 dismissSubWindow(current);
Leon Scroggins92472e82010-02-17 16:32:28 -05001390 loadUrl(current.getWebView(), mSettings.getHomePage());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001391 }
1392 break;
1393
1394 case R.id.preferences_menu_id:
1395 Intent intent = new Intent(this,
1396 BrowserPreferencesPage.class);
Leon Scrogginsd5304942009-12-10 16:11:39 -05001397 intent.putExtra(BrowserPreferencesPage.CURRENT_PAGE,
1398 getTopWindow().getUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001399 startActivityForResult(intent, PREFERENCES_PAGE);
1400 break;
1401
1402 case R.id.find_menu_id:
Leon Scroggins4fc12cb2010-08-24 14:24:05 -04001403 getTopWindow().showFindDialog(null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001404 break;
1405
Elliott Slaughter0ced08c2010-06-30 11:40:42 -07001406 case R.id.save_webarchive_menu_id:
1407 if (LOGD_ENABLED) {
1408 Log.d(LOGTAG, "Save as Web Archive");
1409 }
Elliott Slaughteraba242c2010-09-01 16:21:07 -07001410 String state = Environment.getExternalStorageState();
1411 if (Environment.MEDIA_MOUNTED.equals(state)) {
1412 String directory = Environment.getExternalStoragePublicDirectory(
1413 Environment.DIRECTORY_DOWNLOADS).getAbsolutePath() + File.separator;
1414 getTopWindow().saveWebArchive(directory, true, new ValueCallback<String>() {
1415 @Override
1416 public void onReceiveValue(String value) {
1417 if (value != null) {
1418 Toast.makeText(BrowserActivity.this, R.string.webarchive_saved,
1419 Toast.LENGTH_SHORT).show();
1420 } else {
1421 Toast.makeText(BrowserActivity.this, R.string.webarchive_failed,
1422 Toast.LENGTH_SHORT).show();
1423 }
Elliott Slaughter0ced08c2010-06-30 11:40:42 -07001424 }
Elliott Slaughteraba242c2010-09-01 16:21:07 -07001425 });
1426 } else {
1427 Toast.makeText(BrowserActivity.this, R.string.webarchive_failed,
1428 Toast.LENGTH_SHORT).show();
1429 }
Elliott Slaughter0ced08c2010-06-30 11:40:42 -07001430 break;
1431
The Android Open Source Project0c908882009-03-03 19:32:16 -08001432 case R.id.page_info_menu_id:
1433 showPageInfo(mTabControl.getCurrentTab(), false);
1434 break;
1435
1436 case R.id.classic_history_menu_id:
Michael Kolb68792c82010-08-09 16:39:18 -07001437 bookmarksOrHistoryPicker(true, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001438 break;
1439
Leon Scroggins96afcb12009-12-10 12:35:56 -05001440 case R.id.title_bar_share_page_url:
The Android Open Source Project0c908882009-03-03 19:32:16 -08001441 case R.id.share_page_menu_id:
Leon Scroggins96afcb12009-12-10 12:35:56 -05001442 Tab currentTab = mTabControl.getCurrentTab();
1443 if (null == currentTab) {
1444 mCanChord = false;
1445 return false;
1446 }
1447 currentTab.populatePickerData();
1448 sharePage(this, currentTab.getTitle(),
1449 currentTab.getUrl(), currentTab.getFavicon(),
Ben Murdoch87cc65d2010-06-29 20:34:10 +01001450 createScreenshot(currentTab.getWebView(), getDesiredThumbnailWidth(this),
1451 getDesiredThumbnailHeight(this)));
The Android Open Source Project0c908882009-03-03 19:32:16 -08001452 break;
1453
1454 case R.id.dump_nav_menu_id:
1455 getTopWindow().debugDump();
1456 break;
1457
Andrei Popescu7a8b88b2010-02-02 00:30:38 +00001458 case R.id.dump_counters_menu_id:
1459 getTopWindow().dumpV8Counters();
1460 break;
1461
The Android Open Source Project0c908882009-03-03 19:32:16 -08001462 case R.id.zoom_in_menu_id:
1463 getTopWindow().zoomIn();
1464 break;
1465
1466 case R.id.zoom_out_menu_id:
1467 getTopWindow().zoomOut();
1468 break;
1469
1470 case R.id.view_downloads_menu_id:
1471 viewDownloads(null);
1472 break;
1473
The Android Open Source Project0c908882009-03-03 19:32:16 -08001474 case R.id.window_one_menu_id:
1475 case R.id.window_two_menu_id:
1476 case R.id.window_three_menu_id:
1477 case R.id.window_four_menu_id:
1478 case R.id.window_five_menu_id:
1479 case R.id.window_six_menu_id:
1480 case R.id.window_seven_menu_id:
1481 case R.id.window_eight_menu_id:
1482 {
1483 int menuid = item.getItemId();
1484 for (int id = 0; id < WINDOW_SHORTCUT_ID_ARRAY.length; id++) {
1485 if (WINDOW_SHORTCUT_ID_ARRAY[id] == menuid) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001486 Tab desiredTab = mTabControl.getTab(id);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001487 if (desiredTab != null &&
1488 desiredTab != mTabControl.getCurrentTab()) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001489 switchToTab(id);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001490 }
1491 break;
1492 }
1493 }
1494 }
1495 break;
1496
1497 default:
1498 if (!super.onOptionsItemSelected(item)) {
1499 return false;
1500 }
1501 // Otherwise fall through.
1502 }
1503 mCanChord = false;
1504 return true;
1505 }
1506
Leon Scroggins571b3762010-05-26 10:25:01 -04001507 /* package */ void bookmarkCurrentPage() {
1508 Intent i = new Intent(BrowserActivity.this,
1509 AddBookmarkPage.class);
1510 WebView w = getTopWindow();
1511 i.putExtra("url", w.getUrl());
1512 i.putExtra("title", w.getTitle());
1513 i.putExtra("touch_icon_url", w.getTouchIconUrl());
Ben Murdoch87cc65d2010-06-29 20:34:10 +01001514 i.putExtra("thumbnail", createScreenshot(w, getDesiredThumbnailWidth(this),
1515 getDesiredThumbnailHeight(this)));
Ben Murdocheecb4e62010-07-06 16:30:38 +01001516 i.putExtra("url_editable", false);
Leon Scroggins571b3762010-05-26 10:25:01 -04001517 startActivity(i);
1518 }
1519
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04001520 /*
1521 * True if a custom ActionMode (i.e. find or select) is in use.
1522 */
1523 private boolean isInCustomActionMode() {
1524 return mActionMode != null;
Cary Clark01cfcdd2010-06-04 16:36:45 -04001525 }
1526
1527 /*
Leon Scroggins4fc12cb2010-08-24 14:24:05 -04001528 * End the current ActionMode.
Cary Clark01cfcdd2010-06-04 16:36:45 -04001529 */
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04001530 void endActionMode() {
1531 if (mActionMode != null) {
Leon Scroggins4fc12cb2010-08-24 14:24:05 -04001532 ActionMode mode = mActionMode;
1533 onEndActionMode();
1534 mode.finish();
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04001535 }
1536 }
1537
1538 /*
1539 * Called by find and select when they are finished. Replace title bars
1540 * as necessary.
1541 */
1542 public void onEndActionMode() {
1543 if (!isInCustomActionMode()) return;
Leon Scroggins79e36d92010-04-29 16:01:46 +01001544 if (mInLoad) {
1545 // The title bar was hidden, because otherwise it would cover up the
Michael Kolba2b2ba82010-08-04 17:54:03 -07001546 // find or select dialog. Now that the dialog has been removed,
Cary Clark01cfcdd2010-06-04 16:36:45 -04001547 // show the fake title bar once again.
Leon Scroggins79e36d92010-04-29 16:01:46 +01001548 showFakeTitleBar();
1549 }
Leon Scroggins4fc12cb2010-08-24 14:24:05 -04001550 // Would like to return the menu state to normal, but this does not
1551 // necessarily get called.
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04001552 mActionMode = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001553 }
1554
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04001555 // For select and find, we keep track of the ActionMode so that
1556 // finish() can be called as desired.
1557 private ActionMode mActionMode;
1558
Grace Kloba22ac16e2009-10-07 18:00:23 -07001559 @Override
1560 public boolean onPrepareOptionsMenu(Menu menu) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001561 // This happens when the user begins to hold down the menu key, so
1562 // allow them to chord to get a shortcut.
1563 mCanChord = true;
1564 // Note: setVisible will decide whether an item is visible; while
1565 // setEnabled() will decide whether an item is enabled, which also means
1566 // whether the matching shortcut key will function.
1567 super.onPrepareOptionsMenu(menu);
1568 switch (mMenuState) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001569 case EMPTY_MENU:
1570 if (mCurrentMenuState != mMenuState) {
1571 menu.setGroupVisible(R.id.MAIN_MENU, false);
1572 menu.setGroupEnabled(R.id.MAIN_MENU, false);
1573 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001574 }
1575 break;
1576 default:
1577 if (mCurrentMenuState != mMenuState) {
1578 menu.setGroupVisible(R.id.MAIN_MENU, true);
1579 menu.setGroupEnabled(R.id.MAIN_MENU, true);
1580 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001581 }
1582 final WebView w = getTopWindow();
1583 boolean canGoBack = false;
1584 boolean canGoForward = false;
1585 boolean isHome = false;
1586 if (w != null) {
1587 canGoBack = w.canGoBack();
1588 canGoForward = w.canGoForward();
1589 isHome = mSettings.getHomePage().equals(w.getUrl());
1590 }
1591 final MenuItem back = menu.findItem(R.id.back_menu_id);
1592 back.setEnabled(canGoBack);
1593
1594 final MenuItem home = menu.findItem(R.id.homepage_menu_id);
1595 home.setEnabled(!isHome);
1596
Michael Kolbe0a36662010-06-29 10:37:12 -07001597 final MenuItem forward = menu.findItem(R.id.forward_menu_id);
1598 forward.setEnabled(canGoForward);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001599
Michael Kolbed217742010-08-10 17:52:34 -07001600 if (!mXLargeScreenSize) {
1601 final MenuItem newtab = menu.findItem(R.id.new_tab_menu_id);
1602 newtab.setEnabled(mTabControl.canCreateNewTab());
1603 }
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001604
The Android Open Source Project0c908882009-03-03 19:32:16 -08001605 // decide whether to show the share link option
1606 PackageManager pm = getPackageManager();
1607 Intent send = new Intent(Intent.ACTION_SEND);
1608 send.setType("text/plain");
1609 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1610 menu.findItem(R.id.share_page_menu_id).setVisible(ri != null);
1611
The Android Open Source Project0c908882009-03-03 19:32:16 -08001612 boolean isNavDump = mSettings.isNavDump();
1613 final MenuItem nav = menu.findItem(R.id.dump_nav_menu_id);
1614 nav.setVisible(isNavDump);
1615 nav.setEnabled(isNavDump);
Andrei Popescu7a8b88b2010-02-02 00:30:38 +00001616
1617 boolean showDebugSettings = mSettings.showDebugSettings();
1618 final MenuItem counter = menu.findItem(R.id.dump_counters_menu_id);
1619 counter.setVisible(showDebugSettings);
1620 counter.setEnabled(showDebugSettings);
1621
The Android Open Source Project0c908882009-03-03 19:32:16 -08001622 break;
1623 }
1624 mCurrentMenuState = mMenuState;
1625 return true;
1626 }
1627
1628 @Override
1629 public void onCreateContextMenu(ContextMenu menu, View v,
1630 ContextMenuInfo menuInfo) {
Leon Scroggins571b3762010-05-26 10:25:01 -04001631 if (v instanceof TitleBarBase) {
Leon Scroggins4e9f89b2010-02-22 16:54:14 -05001632 return;
1633 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001634 WebView webview = (WebView) v;
1635 WebView.HitTestResult result = webview.getHitTestResult();
1636 if (result == null) {
1637 return;
1638 }
1639
1640 int type = result.getType();
1641 if (type == WebView.HitTestResult.UNKNOWN_TYPE) {
1642 Log.w(LOGTAG,
1643 "We should not show context menu when nothing is touched");
1644 return;
1645 }
1646 if (type == WebView.HitTestResult.EDIT_TEXT_TYPE) {
1647 // let TextView handles context menu
1648 return;
1649 }
1650
1651 // Note, http://b/issue?id=1106666 is requesting that
1652 // an inflated menu can be used again. This is not available
1653 // yet, so inflate each time (yuk!)
1654 MenuInflater inflater = getMenuInflater();
1655 inflater.inflate(R.menu.browsercontext, menu);
1656
1657 // Show the correct menu group
Leon Scroggins III9e997c72010-05-26 13:25:16 -04001658 final String extra = result.getExtra();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001659 menu.setGroupVisible(R.id.PHONE_MENU,
1660 type == WebView.HitTestResult.PHONE_TYPE);
1661 menu.setGroupVisible(R.id.EMAIL_MENU,
1662 type == WebView.HitTestResult.EMAIL_TYPE);
1663 menu.setGroupVisible(R.id.GEO_MENU,
1664 type == WebView.HitTestResult.GEO_TYPE);
1665 menu.setGroupVisible(R.id.IMAGE_MENU,
1666 type == WebView.HitTestResult.IMAGE_TYPE
1667 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1668 menu.setGroupVisible(R.id.ANCHOR_MENU,
1669 type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1670 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1671
1672 // Setup custom handling depending on the type
1673 switch (type) {
1674 case WebView.HitTestResult.PHONE_TYPE:
1675 menu.setHeaderTitle(Uri.decode(extra));
1676 menu.findItem(R.id.dial_context_menu_id).setIntent(
1677 new Intent(Intent.ACTION_VIEW, Uri
1678 .parse(WebView.SCHEME_TEL + extra)));
1679 Intent addIntent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
1680 addIntent.putExtra(Insert.PHONE, Uri.decode(extra));
Cary Clark5e335a32009-09-22 14:53:11 -04001681 addIntent.setType(ContactsContract.Contacts.CONTENT_ITEM_TYPE);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001682 menu.findItem(R.id.add_contact_context_menu_id).setIntent(
1683 addIntent);
1684 menu.findItem(R.id.copy_phone_context_menu_id).setOnMenuItemClickListener(
1685 new Copy(extra));
1686 break;
1687
1688 case WebView.HitTestResult.EMAIL_TYPE:
1689 menu.setHeaderTitle(extra);
1690 menu.findItem(R.id.email_context_menu_id).setIntent(
1691 new Intent(Intent.ACTION_VIEW, Uri
1692 .parse(WebView.SCHEME_MAILTO + extra)));
1693 menu.findItem(R.id.copy_mail_context_menu_id).setOnMenuItemClickListener(
1694 new Copy(extra));
1695 break;
1696
1697 case WebView.HitTestResult.GEO_TYPE:
1698 menu.setHeaderTitle(extra);
1699 menu.findItem(R.id.map_context_menu_id).setIntent(
1700 new Intent(Intent.ACTION_VIEW, Uri
1701 .parse(WebView.SCHEME_GEO
1702 + URLEncoder.encode(extra))));
1703 menu.findItem(R.id.copy_geo_context_menu_id).setOnMenuItemClickListener(
1704 new Copy(extra));
1705 break;
1706
1707 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1708 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
1709 TextView titleView = (TextView) LayoutInflater.from(this)
1710 .inflate(android.R.layout.browser_link_context_header,
1711 null);
1712 titleView.setText(extra);
1713 menu.setHeaderView(titleView);
1714 // decide whether to show the open link in new tab option
Leon Scroggins III9e997c72010-05-26 13:25:16 -04001715 boolean showNewTab = mTabControl.canCreateNewTab();
1716 MenuItem newTabItem
1717 = menu.findItem(R.id.open_newtab_context_menu_id);
1718 newTabItem.setVisible(showNewTab);
1719 if (showNewTab) {
1720 newTabItem.setOnMenuItemClickListener(
1721 new MenuItem.OnMenuItemClickListener() {
1722 public boolean onMenuItemClick(MenuItem item) {
1723 final Tab parent = mTabControl.getCurrentTab();
Michael Kolb68792c82010-08-09 16:39:18 -07001724 final Tab newTab = openTab(extra, false);
Leon Scroggins III9e997c72010-05-26 13:25:16 -04001725 if (newTab != parent) {
1726 parent.addChildTab(newTab);
1727 }
1728 return true;
1729 }
1730 });
1731 }
Ben Murdochde353622009-10-12 10:29:00 +01001732 menu.findItem(R.id.bookmark_context_menu_id).setVisible(
1733 Bookmarks.urlHasAcceptableScheme(extra));
The Android Open Source Project0c908882009-03-03 19:32:16 -08001734 PackageManager pm = getPackageManager();
1735 Intent send = new Intent(Intent.ACTION_SEND);
1736 send.setType("text/plain");
1737 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1738 menu.findItem(R.id.share_link_context_menu_id).setVisible(ri != null);
1739 if (type == WebView.HitTestResult.SRC_ANCHOR_TYPE) {
1740 break;
1741 }
1742 // otherwise fall through to handle image part
1743 case WebView.HitTestResult.IMAGE_TYPE:
1744 if (type == WebView.HitTestResult.IMAGE_TYPE) {
1745 menu.setHeaderTitle(extra);
1746 }
1747 menu.findItem(R.id.view_image_context_menu_id).setIntent(
1748 new Intent(Intent.ACTION_VIEW, Uri.parse(extra)));
1749 menu.findItem(R.id.download_context_menu_id).
1750 setOnMenuItemClickListener(new Download(extra));
Ben Murdoch4f75ba22009-10-27 11:48:28 +00001751 menu.findItem(R.id.set_wallpaper_context_menu_id).
1752 setOnMenuItemClickListener(new SetAsWallpaper(extra));
The Android Open Source Project0c908882009-03-03 19:32:16 -08001753 break;
1754
1755 default:
1756 Log.w(LOGTAG, "We should not get here.");
1757 break;
1758 }
Leon Scrogginsb2b19f52009-10-09 16:10:00 -04001759 hideFakeTitleBar();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001760 }
1761
The Android Open Source Project0c908882009-03-03 19:32:16 -08001762 // Attach the given tab to the content view.
Grace Klobac928c302009-09-17 11:51:21 -07001763 // this should only be called for the current tab.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001764 private void attachTabToContentView(Tab t) {
Steve Block2bc69912009-07-30 14:45:13 +01001765 // Attach the container that contains the main WebView and any other UI
1766 // associated with the tab.
Patrick Scottd0119532009-09-17 08:00:31 -04001767 t.attachTabToContentView(mContentView);
Ben Murdochbff2d602009-07-01 20:19:05 +01001768
1769 if (mShouldShowErrorConsole) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001770 ErrorConsoleView errorConsole = t.getErrorConsole(true);
Ben Murdochbff2d602009-07-01 20:19:05 +01001771 if (errorConsole.numberOfErrors() == 0) {
1772 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
1773 } else {
1774 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
1775 }
1776
1777 mErrorConsoleContainer.addView(errorConsole,
Romain Guy15b8ec62010-01-08 15:06:43 -08001778 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
Ben Murdochbff2d602009-07-01 20:19:05 +01001779 ViewGroup.LayoutParams.WRAP_CONTENT));
1780 }
1781
Michael Kolba2b2ba82010-08-04 17:54:03 -07001782 WebView view = t.getWebView();
1783 view.setEmbeddedTitleBar(mTitleBar);
Leon Scroggins58d56c62010-01-28 15:12:40 -05001784 if (t.isInVoiceSearchMode()) {
1785 showVoiceTitleBar(t.getVoiceDisplayTitle());
1786 } else {
1787 revertVoiceTitleBar();
1788 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001789 // Request focus on the top window.
1790 t.getTopWindow().requestFocus();
Michael Kolba2b2ba82010-08-04 17:54:03 -07001791 if (mTabControl.getTabChangeListener() != null) {
1792 mTabControl.getTabChangeListener().onCurrentTab(t);
1793 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001794 }
1795
1796 // Attach a sub window to the main WebView of the given tab.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001797 void attachSubWindow(Tab t) {
Patrick Scottd0119532009-09-17 08:00:31 -04001798 t.attachSubWindow(mContentView);
1799 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001800 }
1801
1802 // Remove the given tab from the content view.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001803 private void removeTabFromContentView(Tab t) {
Steve Block2bc69912009-07-30 14:45:13 +01001804 // Remove the container that contains the main WebView.
Patrick Scottd0119532009-09-17 08:00:31 -04001805 t.removeTabFromContentView(mContentView);
Ben Murdochbff2d602009-07-01 20:19:05 +01001806
Grace Kloba22ac16e2009-10-07 18:00:23 -07001807 ErrorConsoleView errorConsole = t.getErrorConsole(false);
1808 if (errorConsole != null) {
1809 mErrorConsoleContainer.removeView(errorConsole);
Ben Murdochbff2d602009-07-01 20:19:05 +01001810 }
1811
Michael Kolba2b2ba82010-08-04 17:54:03 -07001812 WebView view = t.getWebView();
1813 if (view != null) {
1814 view.setEmbeddedTitleBar(null);
Leon Scrogginsbb85b902009-09-14 19:27:20 -04001815 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001816 }
1817
1818 // Remove the sub window if it exists. Also called by TabControl when the
1819 // user clicks the 'X' to dismiss a sub window.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001820 /* package */ void dismissSubWindow(Tab t) {
Patrick Scottd0119532009-09-17 08:00:31 -04001821 t.removeSubWindow(mContentView);
Grace Kloba22ac16e2009-10-07 18:00:23 -07001822 // dismiss the subwindow. This will destroy the WebView.
1823 t.dismissSubWindow();
Patrick Scottd0119532009-09-17 08:00:31 -04001824 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001825 }
1826
Leon Scroggins1f005d32009-08-10 17:36:42 -04001827 // A wrapper function of {@link #openTabAndShow(UrlData, boolean, String)}
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07001828 // that accepts url as string.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001829 private Tab openTabAndShow(String url, boolean closeOnExit, String appId) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001830 return openTabAndShow(new UrlData(url), closeOnExit, appId);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001831 }
1832
1833 // This method does a ton of stuff. It will attempt to create a new tab
1834 // if we haven't reached MAX_TABS. Otherwise it uses the current tab. If
Leon Scroggins1f005d32009-08-10 17:36:42 -04001835 // url isn't null, it will load the given url.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001836 /* package */Tab openTabAndShow(UrlData urlData, boolean closeOnExit,
1837 String appId) {
1838 final Tab currentTab = mTabControl.getCurrentTab();
1839 if (mTabControl.canCreateNewTab()) {
1840 final Tab tab = mTabControl.createNewTab(closeOnExit, appId,
Elliott Slaughterf0f03952010-07-14 18:10:36 -07001841 urlData.mUrl, false);
Leon Scroggins1f005d32009-08-10 17:36:42 -04001842 WebView webview = tab.getWebView();
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001843 // If the last tab was removed from the active tabs page, currentTab
1844 // will be null.
1845 if (currentTab != null) {
1846 removeTabFromContentView(currentTab);
1847 }
Patrick Scott8bbd69f2009-08-14 13:35:53 -04001848 // We must set the new tab as the current tab to reflect the old
1849 // animation behavior.
1850 mTabControl.setCurrentTab(tab);
Grace Klobaeb6eef42009-09-15 17:56:32 -07001851 attachTabToContentView(tab);
Leon Scroggins160a7e72009-08-14 18:28:01 -04001852 if (!urlData.isEmpty()) {
Patrick Scott9d53da02010-02-19 10:19:01 -05001853 loadUrlDataIn(tab, urlData);
Leon Scroggins1f005d32009-08-10 17:36:42 -04001854 }
1855 return tab;
1856 } else {
1857 // Get rid of the subwindow if it exists
1858 dismissSubWindow(currentTab);
1859 if (!urlData.isEmpty()) {
1860 // Load the given url.
Patrick Scott9d53da02010-02-19 10:19:01 -05001861 loadUrlDataIn(currentTab, urlData);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001862 }
Leon Scroggins58d56c62010-01-28 15:12:40 -05001863 return currentTab;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001864 }
1865 }
1866
Michael Kolb68792c82010-08-09 16:39:18 -07001867 private Tab openTab(String url, boolean forceForeground) {
1868 if (mSettings.openInBackground() && !forceForeground) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001869 Tab t = mTabControl.createNewTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001870 if (t != null) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001871 WebView view = t.getWebView();
Leon Scroggins92472e82010-02-17 16:32:28 -05001872 loadUrl(view, url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001873 }
Grace Klobac9181842009-04-14 08:53:22 -07001874 return t;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001875 } else {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001876 return openTabAndShow(url, false, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001877 }
1878 }
1879
Elliott Slaughterf0f03952010-07-14 18:10:36 -07001880 /* package */ Tab openIncognitoTab() {
1881 if (mTabControl.canCreateNewTab()) {
1882 Tab currentTab = mTabControl.getCurrentTab();
1883 Tab tab = mTabControl.createNewTab(false, null, null, true);
1884 if (currentTab != null) {
1885 removeTabFromContentView(currentTab);
1886 }
1887 mTabControl.setCurrentTab(tab);
1888 attachTabToContentView(tab);
1889 return tab;
1890 }
1891 return null;
1892 }
1893
The Android Open Source Project0c908882009-03-03 19:32:16 -08001894 private class Copy implements OnMenuItemClickListener {
1895 private CharSequence mText;
1896
1897 public boolean onMenuItemClick(MenuItem item) {
1898 copy(mText);
1899 return true;
1900 }
1901
1902 public Copy(CharSequence toCopy) {
1903 mText = toCopy;
1904 }
1905 }
1906
1907 private class Download implements OnMenuItemClickListener {
1908 private String mText;
1909
1910 public boolean onMenuItemClick(MenuItem item) {
1911 onDownloadStartNoStream(mText, null, null, null, -1);
1912 return true;
1913 }
1914
1915 public Download(String toDownload) {
1916 mText = toDownload;
1917 }
1918 }
1919
Ben Murdoch4f75ba22009-10-27 11:48:28 +00001920 private class SetAsWallpaper extends Thread implements
1921 OnMenuItemClickListener, DialogInterface.OnCancelListener {
1922 private URL mUrl;
1923 private ProgressDialog mWallpaperProgress;
1924 private boolean mCanceled = false;
1925
1926 public SetAsWallpaper(String url) {
1927 try {
1928 mUrl = new URL(url);
1929 } catch (MalformedURLException e) {
1930 mUrl = null;
1931 }
1932 }
1933
1934 public void onCancel(DialogInterface dialog) {
1935 mCanceled = true;
1936 }
1937
1938 public boolean onMenuItemClick(MenuItem item) {
1939 if (mUrl != null) {
1940 // The user may have tried to set a image with a large file size as their
1941 // background so it may take a few moments to perform the operation. Display
1942 // a progress spinner while it is working.
1943 mWallpaperProgress = new ProgressDialog(BrowserActivity.this);
1944 mWallpaperProgress.setIndeterminate(true);
1945 mWallpaperProgress.setMessage(getText(R.string.progress_dialog_setting_wallpaper));
1946 mWallpaperProgress.setCancelable(true);
1947 mWallpaperProgress.setOnCancelListener(this);
1948 mWallpaperProgress.show();
1949 start();
1950 }
1951 return true;
1952 }
1953
Michael Kolbe0a36662010-06-29 10:37:12 -07001954 @Override
Ben Murdoch4f75ba22009-10-27 11:48:28 +00001955 public void run() {
1956 Drawable oldWallpaper = BrowserActivity.this.getWallpaper();
1957 try {
1958 // TODO: This will cause the resource to be downloaded again, when we
1959 // should in most cases be able to grab it from the cache. To fix this
1960 // we should query WebCore to see if we can access a cached version and
1961 // instead open an input stream on that. This pattern could also be used
1962 // in the download manager where the same problem exists.
1963 InputStream inputstream = mUrl.openStream();
1964 if (inputstream != null) {
1965 setWallpaper(inputstream);
1966 }
1967 } catch (IOException e) {
1968 Log.e(LOGTAG, "Unable to set new wallpaper");
1969 // Act as though the user canceled the operation so we try to
1970 // restore the old wallpaper.
1971 mCanceled = true;
1972 }
1973
1974 if (mCanceled) {
1975 // Restore the old wallpaper if the user cancelled whilst we were setting
1976 // the new wallpaper.
1977 int width = oldWallpaper.getIntrinsicWidth();
1978 int height = oldWallpaper.getIntrinsicHeight();
1979 Bitmap bm = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
1980 Canvas canvas = new Canvas(bm);
1981 oldWallpaper.setBounds(0, 0, width, height);
1982 oldWallpaper.draw(canvas);
1983 try {
1984 setWallpaper(bm);
1985 } catch (IOException e) {
1986 Log.e(LOGTAG, "Unable to restore old wallpaper.");
1987 }
1988 mCanceled = false;
1989 }
1990
1991 if (mWallpaperProgress.isShowing()) {
1992 mWallpaperProgress.dismiss();
1993 }
1994 }
1995 }
1996
The Android Open Source Project0c908882009-03-03 19:32:16 -08001997 private void copy(CharSequence text) {
Dianne Hackborn80f32622010-08-05 14:17:53 -07001998 ClipboardManager cm = (ClipboardManager)getSystemService(Context.CLIPBOARD_SERVICE);
1999 cm.setText(text);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002000 }
2001
2002 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08002003 * Resets the browser title-view to whatever it must be
2004 * (for example, if we had a loading error)
2005 * When we have a new page, we call resetTitle, when we
2006 * have to reset the titlebar to whatever it used to be
2007 * (for example, if the user chose to stop loading), we
2008 * call resetTitleAndRevertLockIcon.
2009 */
2010 /* package */ void resetTitleAndRevertLockIcon() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002011 mTabControl.getCurrentTab().revertLockIcon();
2012 updateLockIconToLatest();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002013 resetTitleIconAndProgress();
2014 }
2015
2016 /**
2017 * Reset the title, favicon, and progress.
2018 */
2019 private void resetTitleIconAndProgress() {
2020 WebView current = mTabControl.getCurrentWebView();
2021 if (current == null) {
2022 return;
2023 }
2024 resetTitleAndIcon(current);
2025 int progress = current.getProgress();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002026 current.getWebChromeClient().onProgressChanged(current, progress);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002027 }
2028
2029 // Reset the title and the icon based on the given item.
2030 private void resetTitleAndIcon(WebView view) {
2031 WebHistoryItem item = view.copyBackForwardList().getCurrentItem();
2032 if (item != null) {
Leon Scroggins68579392009-09-15 15:31:54 -04002033 setUrlTitle(item.getUrl(), item.getTitle());
The Android Open Source Project0c908882009-03-03 19:32:16 -08002034 setFavicon(item.getFavicon());
2035 } else {
Leon Scroggins68579392009-09-15 15:31:54 -04002036 setUrlTitle(null, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002037 setFavicon(null);
2038 }
2039 }
2040
2041 /**
2042 * Sets a title composed of the URL and the title string.
2043 * @param url The URL of the site being loaded.
2044 * @param title The title of the site being loaded.
2045 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07002046 void setUrlTitle(String url, String title) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002047 mUrl = url;
2048 mTitle = title;
2049
Leon Scroggins58d56c62010-01-28 15:12:40 -05002050 // If we are in voice search mode, the title has already been set.
2051 if (mTabControl.getCurrentTab().isInVoiceSearchMode()) return;
2052 mTitleBar.setDisplayTitle(url);
Michael Kolba2b2ba82010-08-04 17:54:03 -07002053 mFakeTitleBar.setDisplayTitle(url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002054 }
2055
2056 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08002057 * @param url The URL to build a title version of the URL from.
2058 * @return The title version of the URL or null if fails.
2059 * The title version of the URL can be either the URL hostname,
2060 * or the hostname with an "https://" prefix (for secure URLs),
2061 * or an empty string if, for example, the URL in question is a
2062 * file:// URL with no hostname.
2063 */
Leon Scroggins32e14a62009-06-11 10:26:34 -04002064 /* package */ static String buildTitleUrl(String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002065 String titleUrl = null;
2066
2067 if (url != null) {
2068 try {
2069 // parse the url string
2070 URL urlObj = new URL(url);
2071 if (urlObj != null) {
2072 titleUrl = "";
2073
2074 String protocol = urlObj.getProtocol();
2075 String host = urlObj.getHost();
2076
2077 if (host != null && 0 < host.length()) {
2078 titleUrl = host;
2079 if (protocol != null) {
2080 // if a secure site, add an "https://" prefix!
2081 if (protocol.equalsIgnoreCase("https")) {
2082 titleUrl = protocol + "://" + host;
2083 }
2084 }
2085 }
2086 }
2087 } catch (MalformedURLException e) {}
2088 }
2089
2090 return titleUrl;
2091 }
2092
2093 // Set the favicon in the title bar.
Grace Kloba22ac16e2009-10-07 18:00:23 -07002094 void setFavicon(Bitmap icon) {
Leon Scroggins68579392009-09-15 15:31:54 -04002095 mTitleBar.setFavicon(icon);
Michael Kolba2b2ba82010-08-04 17:54:03 -07002096 mFakeTitleBar.setFavicon(icon);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002097 }
2098
2099 /**
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002100 * Close the tab, remove its associated title bar, and adjust mTabControl's
2101 * current tab to a valid value.
Leon Scroggins1f005d32009-08-10 17:36:42 -04002102 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07002103 /* package */ void closeTab(Tab t) {
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002104 int currentIndex = mTabControl.getCurrentIndex();
2105 int removeIndex = mTabControl.getTabIndex(t);
Leon Scroggins1f005d32009-08-10 17:36:42 -04002106 mTabControl.removeTab(t);
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002107 if (currentIndex >= removeIndex && currentIndex != 0) {
2108 currentIndex--;
2109 }
2110 mTabControl.setCurrentTab(mTabControl.getTab(currentIndex));
Andrei Popescua5bf1de2009-09-23 16:39:23 +01002111 resetTitleIconAndProgress();
Leon Scroggins654899b2010-06-25 16:25:23 -04002112 updateLockIconToLatest();
Elliott Slaughtere440a882010-08-20 13:54:45 -07002113
2114 if (!mTabControl.hasAnyOpenIncognitoTabs()) {
2115 WebView.cleanupPrivateBrowsingFiles(this);
2116 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002117 }
2118
Leon Scrogginsdcc5eeb2010-02-23 17:26:37 -05002119 /* package */ void goBackOnePageOrQuit() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002120 Tab current = mTabControl.getCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002121 if (current == null) {
2122 /*
2123 * Instead of finishing the activity, simply push this to the back
2124 * of the stack and let ActivityManager to choose the foreground
2125 * activity. As BrowserActivity is singleTask, it will be always the
2126 * root of the task. So we can use either true or false for
2127 * moveTaskToBack().
2128 */
2129 moveTaskToBack(true);
Grace Kloba00d85e72009-09-23 18:50:05 -07002130 return;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002131 }
2132 WebView w = current.getWebView();
2133 if (w.canGoBack()) {
2134 w.goBack();
2135 } else {
2136 // Check to see if we are closing a window that was created by
2137 // another window. If so, we switch back to that window.
Grace Kloba22ac16e2009-10-07 18:00:23 -07002138 Tab parent = current.getParentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002139 if (parent != null) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04002140 switchToTab(mTabControl.getTabIndex(parent));
2141 // Now we close the other tab
2142 closeTab(current);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002143 } else {
2144 if (current.closeOnExit()) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002145 // force the tab's inLoad() to be false as we are going to
2146 // either finish the activity or remove the tab. This will
2147 // ensure pauseWebViewTimers() taking action.
2148 mTabControl.getCurrentTab().clearInLoad();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002149 if (mTabControl.getTabCount() == 1) {
2150 finish();
2151 return;
2152 }
Mike Reed7bfa63b2009-05-28 11:08:32 -04002153 // call pauseWebViewTimers() now, we won't be able to call
2154 // it in onPause() as the WebView won't be valid.
Grace Klobaec1b5ad2009-08-18 08:42:32 -07002155 // Temporarily change mActivityInPause to be true as
2156 // pauseWebViewTimers() will do nothing if mActivityInPause
2157 // is false.
Grace Kloba918e1d72009-08-13 14:55:06 -07002158 boolean savedState = mActivityInPause;
2159 if (savedState) {
Grace Klobaec1b5ad2009-08-18 08:42:32 -07002160 Log.e(LOGTAG, "BrowserActivity is already paused "
2161 + "while handing goBackOnePageOrQuit.");
Grace Kloba918e1d72009-08-13 14:55:06 -07002162 }
2163 mActivityInPause = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -04002164 pauseWebViewTimers();
Grace Kloba918e1d72009-08-13 14:55:06 -07002165 mActivityInPause = savedState;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002166 removeTabFromContentView(current);
2167 mTabControl.removeTab(current);
2168 }
2169 /*
2170 * Instead of finishing the activity, simply push this to the back
2171 * of the stack and let ActivityManager to choose the foreground
2172 * activity. As BrowserActivity is singleTask, it will be always the
2173 * root of the task. So we can use either true or false for
2174 * moveTaskToBack().
2175 */
2176 moveTaskToBack(true);
2177 }
2178 }
2179 }
2180
Grace Kloba22ac16e2009-10-07 18:00:23 -07002181 boolean isMenuDown() {
2182 return mMenuIsDown;
2183 }
2184
Grace Kloba5942df02009-09-18 11:48:29 -07002185 @Override
2186 public boolean onKeyDown(int keyCode, KeyEvent event) {
Leon Scrogginsf65b50d2009-12-08 10:44:28 -05002187 // Even if MENU is already held down, we need to call to super to open
2188 // the IME on long press.
2189 if (KeyEvent.KEYCODE_MENU == keyCode) {
2190 mMenuIsDown = true;
2191 return super.onKeyDown(keyCode, event);
2192 }
Grace Kloba5942df02009-09-18 11:48:29 -07002193 // The default key mode is DEFAULT_KEYS_SEARCH_LOCAL. As the MENU is
2194 // still down, we don't want to trigger the search. Pretend to consume
2195 // the key and do nothing.
2196 if (mMenuIsDown) return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002197
Grace Kloba5942df02009-09-18 11:48:29 -07002198 switch(keyCode) {
Grace Kloba5942df02009-09-18 11:48:29 -07002199 case KeyEvent.KEYCODE_SPACE:
Grace Klobada0fe552009-09-22 18:17:24 -07002200 // WebView/WebTextView handle the keys in the KeyDown. As
2201 // the Activity's shortcut keys are only handled when WebView
2202 // doesn't, have to do it in onKeyDown instead of onKeyUp.
2203 if (event.isShiftPressed()) {
2204 getTopWindow().pageUp(false);
2205 } else {
2206 getTopWindow().pageDown(false);
2207 }
Grace Kloba5942df02009-09-18 11:48:29 -07002208 return true;
2209 case KeyEvent.KEYCODE_BACK:
2210 if (event.getRepeatCount() == 0) {
2211 event.startTracking();
2212 return true;
2213 } else if (mCustomView == null && mActiveTabsPage == null
2214 && event.isLongPress()) {
Michael Kolb68792c82010-08-09 16:39:18 -07002215 bookmarksOrHistoryPicker(true, false);
Grace Kloba5942df02009-09-18 11:48:29 -07002216 return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002217 }
Grace Kloba5942df02009-09-18 11:48:29 -07002218 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002219 }
Grace Kloba5942df02009-09-18 11:48:29 -07002220 return super.onKeyDown(keyCode, event);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002221 }
2222
Grace Kloba5942df02009-09-18 11:48:29 -07002223 @Override
2224 public boolean onKeyUp(int keyCode, KeyEvent event) {
2225 switch(keyCode) {
2226 case KeyEvent.KEYCODE_MENU:
2227 mMenuIsDown = false;
2228 break;
Grace Kloba5942df02009-09-18 11:48:29 -07002229 case KeyEvent.KEYCODE_BACK:
2230 if (event.isTracking() && !event.isCanceled()) {
2231 if (mCustomView != null) {
2232 // if a custom view is showing, hide it
Grace Kloba22ac16e2009-10-07 18:00:23 -07002233 mTabControl.getCurrentWebView().getWebChromeClient()
2234 .onHideCustomView();
Grace Kloba5942df02009-09-18 11:48:29 -07002235 } else if (mActiveTabsPage != null) {
2236 // if tab page is showing, hide it
2237 removeActiveTabPage(true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002238 } else {
Grace Kloba5942df02009-09-18 11:48:29 -07002239 WebView subwindow = mTabControl.getCurrentSubWindow();
2240 if (subwindow != null) {
2241 if (subwindow.canGoBack()) {
2242 subwindow.goBack();
2243 } else {
2244 dismissSubWindow(mTabControl.getCurrentTab());
2245 }
2246 } else {
2247 goBackOnePageOrQuit();
2248 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002249 }
Grace Kloba5942df02009-09-18 11:48:29 -07002250 return true;
2251 }
2252 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002253 }
Grace Kloba5942df02009-09-18 11:48:29 -07002254 return super.onKeyUp(keyCode, event);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002255 }
2256
Leon Scroggins68579392009-09-15 15:31:54 -04002257 /* package */ void stopLoading() {
Ben Murdochb7cc8b42009-09-28 10:59:09 +01002258 mDidStopLoad = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002259 resetTitleAndRevertLockIcon();
2260 WebView w = getTopWindow();
2261 w.stopLoading();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002262 // FIXME: before refactor, it is using mWebViewClient. So I keep the
2263 // same logic here. But for subwindow case, should we call into the main
2264 // WebView's onPageFinished as we never call its onPageStarted and if
2265 // the page finishes itself, we don't call onPageFinished.
2266 mTabControl.getCurrentWebView().getWebViewClient().onPageFinished(w,
2267 w.getUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08002268
2269 cancelStopToast();
2270 mStopToast = Toast
2271 .makeText(this, R.string.stopping, Toast.LENGTH_SHORT);
2272 mStopToast.show();
2273 }
2274
Grace Kloba22ac16e2009-10-07 18:00:23 -07002275 boolean didUserStopLoading() {
2276 return mDidStopLoad;
2277 }
2278
The Android Open Source Project0c908882009-03-03 19:32:16 -08002279 private void cancelStopToast() {
2280 if (mStopToast != null) {
2281 mStopToast.cancel();
2282 mStopToast = null;
2283 }
2284 }
2285
Grace Kloba22ac16e2009-10-07 18:00:23 -07002286 // called by a UI or non-UI thread to post the message
2287 public void postMessage(int what, int arg1, int arg2, Object obj,
2288 long delayMillis) {
2289 mHandler.sendMessageDelayed(mHandler.obtainMessage(what, arg1, arg2,
2290 obj), delayMillis);
2291 }
2292
2293 // called by a UI or non-UI thread to remove the message
2294 void removeMessages(int what, Object object) {
2295 mHandler.removeMessages(what, object);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002296 }
2297
2298 // public message ids
2299 public final static int LOAD_URL = 1001;
2300 public final static int STOP_LOAD = 1002;
2301
2302 // Message Ids
2303 private static final int FOCUS_NODE_HREF = 102;
Grace Kloba92c18a52009-07-31 23:48:32 -07002304 private static final int RELEASE_WAKELOCK = 107;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002305
Grace Kloba22ac16e2009-10-07 18:00:23 -07002306 static final int UPDATE_BOOKMARK_THUMBNAIL = 108;
Ben Murdoch2694e232009-09-29 09:41:11 +01002307
Ben Murdocheecb4e62010-07-06 16:30:38 +01002308 private static final int TOUCH_ICON_DOWNLOADED = 109;
2309
Michael Kolb300b7f02010-08-25 13:47:24 -07002310 private static final int OPEN_BOOKMARKS = 201;
2311
The Android Open Source Project0c908882009-03-03 19:32:16 -08002312 // Private handler for handling javascript and saving passwords
2313 private Handler mHandler = new Handler() {
2314
Michael Kolbe0a36662010-06-29 10:37:12 -07002315 @Override
The Android Open Source Project0c908882009-03-03 19:32:16 -08002316 public void handleMessage(Message msg) {
2317 switch (msg.what) {
Michael Kolb300b7f02010-08-25 13:47:24 -07002318 case OPEN_BOOKMARKS:
2319 bookmarksOrHistoryPicker(false, false);
2320 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002321 case FOCUS_NODE_HREF:
Ben Murdoch2694e232009-09-29 09:41:11 +01002322 {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002323 String url = (String) msg.getData().get("url");
Ben Murdoch90d088c2009-11-17 18:14:04 +00002324 String title = (String) msg.getData().get("title");
The Android Open Source Project0c908882009-03-03 19:32:16 -08002325 if (url == null || url.length() == 0) {
2326 break;
2327 }
2328 HashMap focusNodeMap = (HashMap) msg.obj;
2329 WebView view = (WebView) focusNodeMap.get("webview");
2330 // Only apply the action if the top window did not change.
2331 if (getTopWindow() != view) {
2332 break;
2333 }
2334 switch (msg.arg1) {
2335 case R.id.open_context_menu_id:
2336 case R.id.view_image_context_menu_id:
Leon Scroggins92472e82010-02-17 16:32:28 -05002337 loadUrlFromContext(getTopWindow(), url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002338 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002339 case R.id.bookmark_context_menu_id:
2340 Intent intent = new Intent(BrowserActivity.this,
2341 AddBookmarkPage.class);
2342 intent.putExtra("url", url);
Ben Murdoch90d088c2009-11-17 18:14:04 +00002343 intent.putExtra("title", title);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002344 startActivity(intent);
2345 break;
2346 case R.id.share_link_context_menu_id:
Leon Scroggins3e204452010-05-10 11:06:03 -04002347 sharePage(BrowserActivity.this, title, url, null,
Leon Scroggins96afcb12009-12-10 12:35:56 -05002348 null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002349 break;
2350 case R.id.copy_link_context_menu_id:
2351 copy(url);
2352 break;
2353 case R.id.save_link_context_menu_id:
2354 case R.id.download_context_menu_id:
2355 onDownloadStartNoStream(url, null, null, null, -1);
2356 break;
2357 }
2358 break;
Ben Murdoch2694e232009-09-29 09:41:11 +01002359 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002360
2361 case LOAD_URL:
Leon Scroggins92472e82010-02-17 16:32:28 -05002362 loadUrlFromContext(getTopWindow(), (String) msg.obj);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002363 break;
2364
2365 case STOP_LOAD:
2366 stopLoading();
2367 break;
2368
The Android Open Source Project0c908882009-03-03 19:32:16 -08002369 case RELEASE_WAKELOCK:
2370 if (mWakeLock.isHeld()) {
2371 mWakeLock.release();
Grace Kloba5d0e02e2009-10-05 15:15:36 -07002372 // if we reach here, Browser should be still in the
2373 // background loading after WAKELOCK_TIMEOUT (5-min).
2374 // To avoid burning the battery, stop loading.
2375 mTabControl.stopAllLoading();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002376 }
2377 break;
Ben Murdoch2694e232009-09-29 09:41:11 +01002378
2379 case UPDATE_BOOKMARK_THUMBNAIL:
2380 WebView view = (WebView) msg.obj;
2381 if (view != null) {
2382 updateScreenshot(view);
2383 }
2384 break;
Ben Murdocheecb4e62010-07-06 16:30:38 +01002385
2386 case TOUCH_ICON_DOWNLOADED:
2387 Bundle b = msg.getData();
2388 showSaveToHomescreenDialog(b.getString("url"),
2389 b.getString("title"),
2390 (Bitmap) b.getParcelable("touchIcon"),
2391 (Bitmap) b.getParcelable("favicon"));
2392 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002393 }
2394 }
2395 };
2396
Leon Scroggins96afcb12009-12-10 12:35:56 -05002397 /**
2398 * Share a page, providing the title, url, favicon, and a screenshot. Uses
2399 * an {@link Intent} to launch the Activity chooser.
2400 * @param c Context used to launch a new Activity.
2401 * @param title Title of the page. Stored in the Intent with
Paul Westbrook03e6d392010-02-12 10:33:29 -08002402 * {@link Intent#EXTRA_SUBJECT}
Leon Scroggins96afcb12009-12-10 12:35:56 -05002403 * @param url URL of the page. Stored in the Intent with
2404 * {@link Intent#EXTRA_TEXT}
2405 * @param favicon Bitmap of the favicon for the page. Stored in the Intent
2406 * with {@link Browser#EXTRA_SHARE_FAVICON}
2407 * @param screenshot Bitmap of a screenshot of the page. Stored in the
2408 * Intent with {@link Browser#EXTRA_SHARE_SCREENSHOT}
2409 */
2410 public static final void sharePage(Context c, String title, String url,
2411 Bitmap favicon, Bitmap screenshot) {
2412 Intent send = new Intent(Intent.ACTION_SEND);
2413 send.setType("text/plain");
2414 send.putExtra(Intent.EXTRA_TEXT, url);
Paul Westbrook03e6d392010-02-12 10:33:29 -08002415 send.putExtra(Intent.EXTRA_SUBJECT, title);
Leon Scroggins96afcb12009-12-10 12:35:56 -05002416 send.putExtra(Browser.EXTRA_SHARE_FAVICON, favicon);
2417 send.putExtra(Browser.EXTRA_SHARE_SCREENSHOT, screenshot);
2418 try {
2419 c.startActivity(Intent.createChooser(send, c.getString(
2420 R.string.choosertitle_sharevia)));
2421 } catch(android.content.ActivityNotFoundException ex) {
2422 // if no app handles it, do nothing
2423 }
2424 }
2425
Leon Scroggins89c6d362009-07-15 16:54:37 -04002426 private void updateScreenshot(WebView view) {
2427 // If this is a bookmarked site, add a screenshot to the database.
2428 // FIXME: When should we update? Every time?
2429 // FIXME: Would like to make sure there is actually something to
2430 // draw, but the API for that (WebViewCore.pictureReady()) is not
2431 // currently accessible here.
Ben Murdochaac7aa62009-09-17 16:57:40 +01002432
Ben Murdoch87cc65d2010-06-29 20:34:10 +01002433 final Bitmap bm = createScreenshot(view, getDesiredThumbnailWidth(this),
2434 getDesiredThumbnailHeight(this));
Patrick Scottcb192b52010-04-14 14:38:55 -04002435 if (bm == null) {
2436 return;
Leon Scroggins89c6d362009-07-15 16:54:37 -04002437 }
Patrick Scottcb192b52010-04-14 14:38:55 -04002438
2439 final ContentResolver cr = getContentResolver();
2440 final String url = view.getUrl();
2441 final String originalUrl = view.getOriginalUrl();
2442
2443 new AsyncTask<Void, Void, Void>() {
2444 @Override
2445 protected Void doInBackground(Void... unused) {
2446 Cursor c = null;
2447 try {
Jeff Hamilton84029622010-08-05 14:29:28 -05002448 c = Bookmarks.queryBookmarksForUrl(
Jeff Hamilton8ce956c2010-08-17 11:13:53 -05002449 cr, originalUrl, url);
Patrick Scottcb192b52010-04-14 14:38:55 -04002450 if (c != null) {
2451 if (c.moveToFirst()) {
2452 ContentValues values = new ContentValues();
2453 final ByteArrayOutputStream os
2454 = new ByteArrayOutputStream();
2455 bm.compress(Bitmap.CompressFormat.PNG, 100, os);
Jeff Hamilton8ce956c2010-08-17 11:13:53 -05002456 values.put(BrowserContract.Bookmarks.THUMBNAIL,
Patrick Scottcb192b52010-04-14 14:38:55 -04002457 os.toByteArray());
2458 do {
2459 cr.update(ContentUris.withAppendedId(
Jeff Hamilton8ce956c2010-08-17 11:13:53 -05002460 BrowserContract.Bookmarks.CONTENT_URI, c.getLong(0)),
Patrick Scottcb192b52010-04-14 14:38:55 -04002461 values, null, null);
2462 } while (c.moveToNext());
2463 }
2464 }
2465 } catch (IllegalStateException e) {
2466 // Ignore
2467 } finally {
2468 if (c != null) c.close();
2469 }
2470 return null;
2471 }
2472 }.execute();
Leon Scroggins89c6d362009-07-15 16:54:37 -04002473 }
2474
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002475 /**
Leon Scrogginsf8551612009-09-24 16:06:02 -04002476 * Return the desired width for thumbnail screenshots, which are stored in
2477 * the database, and used on the bookmarks screen.
2478 * @param context Context for finding out the density of the screen.
Jeff Hamiltonf3026372010-08-19 00:12:27 -05002479 * @return desired width for thumbnail screenshot.
Leon Scrogginsf8551612009-09-24 16:06:02 -04002480 */
2481 /* package */ static int getDesiredThumbnailWidth(Context context) {
Jeff Hamiltonf3026372010-08-19 00:12:27 -05002482 return context.getResources().getDimensionPixelOffset(R.dimen.bookmarkThumbnailWidth);
Leon Scrogginsf8551612009-09-24 16:06:02 -04002483 }
2484
2485 /**
2486 * Return the desired height for thumbnail screenshots, which are stored in
2487 * the database, and used on the bookmarks screen.
2488 * @param context Context for finding out the density of the screen.
Jeff Hamiltonf3026372010-08-19 00:12:27 -05002489 * @return desired height for thumbnail screenshot.
Leon Scrogginsf8551612009-09-24 16:06:02 -04002490 */
2491 /* package */ static int getDesiredThumbnailHeight(Context context) {
Jeff Hamiltonf3026372010-08-19 00:12:27 -05002492 return context.getResources().getDimensionPixelOffset(R.dimen.bookmarkThumbnailHeight);
Leon Scrogginsf8551612009-09-24 16:06:02 -04002493 }
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002494
Ben Murdoch87cc65d2010-06-29 20:34:10 +01002495 private Bitmap createScreenshot(WebView view, int width, int height) {
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002496 Picture thumbnail = view.capturePicture();
Leon Scroggins45800572009-09-29 16:38:47 -04002497 if (thumbnail == null) {
2498 return null;
2499 }
Ben Murdoch87cc65d2010-06-29 20:34:10 +01002500 Bitmap bm = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002501 Canvas canvas = new Canvas(bm);
2502 // May need to tweak these values to determine what is the
2503 // best scale factor
Ben Murdoch2694e232009-09-29 09:41:11 +01002504 int thumbnailWidth = thumbnail.getWidth();
Ben Murdochae59c3f2009-10-20 18:30:28 +01002505 int thumbnailHeight = thumbnail.getHeight();
2506 float scaleFactorX = 1.0f;
2507 float scaleFactorY = 1.0f;
Ben Murdoch2694e232009-09-29 09:41:11 +01002508 if (thumbnailWidth > 0) {
Ben Murdoch87cc65d2010-06-29 20:34:10 +01002509 scaleFactorX = (float) width / (float)thumbnailWidth;
Ben Murdochae59c3f2009-10-20 18:30:28 +01002510 } else {
2511 return null;
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002512 }
Ben Murdochae59c3f2009-10-20 18:30:28 +01002513
2514 if (view.getWidth() > view.getHeight() &&
2515 thumbnailHeight < view.getHeight() && thumbnailHeight > 0) {
2516 // If the device is in landscape and the page is shorter
2517 // than the height of the view, stretch the thumbnail to fill the
2518 // space.
Ben Murdoch87cc65d2010-06-29 20:34:10 +01002519 scaleFactorY = (float) height / (float)thumbnailHeight;
Ben Murdochae59c3f2009-10-20 18:30:28 +01002520 } else {
2521 // In the portrait case, this looks nice.
2522 scaleFactorY = scaleFactorX;
2523 }
2524
2525 canvas.scale(scaleFactorX, scaleFactorY);
2526
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002527 thumbnail.draw(canvas);
2528 return bm;
2529 }
2530
The Android Open Source Project0c908882009-03-03 19:32:16 -08002531 // -------------------------------------------------------------------------
Grace Kloba22ac16e2009-10-07 18:00:23 -07002532 // Helper function for WebViewClient.
The Android Open Source Project0c908882009-03-03 19:32:16 -08002533 //-------------------------------------------------------------------------
2534
2535 // Use in overrideUrlLoading
2536 /* package */ final static String SCHEME_WTAI = "wtai://wp/";
2537 /* package */ final static String SCHEME_WTAI_MC = "wtai://wp/mc;";
2538 /* package */ final static String SCHEME_WTAI_SD = "wtai://wp/sd;";
2539 /* package */ final static String SCHEME_WTAI_AP = "wtai://wp/ap;";
2540
Leon Scroggins92472e82010-02-17 16:32:28 -05002541 // Keep this initial progress in sync with initialProgressValue (* 100)
2542 // in ProgressTracker.cpp
2543 private final static int INITIAL_PROGRESS = 10;
2544
Grace Kloba22ac16e2009-10-07 18:00:23 -07002545 void onPageStarted(WebView view, String url, Bitmap favicon) {
2546 // when BrowserActivity just starts, onPageStarted may be called before
2547 // onResume as it is triggered from onCreate. Call resumeWebViewTimers
2548 // to start the timer. As we won't switch tabs while an activity is in
2549 // pause state, we can ensure calling resume and pause in pair.
2550 if (mActivityInPause) resumeWebViewTimers();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002551
Grace Kloba22ac16e2009-10-07 18:00:23 -07002552 resetLockIcon(url);
2553 setUrlTitle(url, null);
2554 setFavicon(favicon);
Leon Scroggins8cf8f682009-11-04 11:13:50 -08002555 // Show some progress so that the user knows the page is beginning to
2556 // load
Leon Scroggins92472e82010-02-17 16:32:28 -05002557 onProgressChanged(view, INITIAL_PROGRESS);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002558 mDidStopLoad = false;
Grace Kloba22ac16e2009-10-07 18:00:23 -07002559 if (!mIsNetworkUp) createAndShowNetworkDialog();
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04002560 endActionMode();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002561 if (mSettings.isTracing()) {
2562 String host;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002563 try {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002564 WebAddress uri = new WebAddress(url);
2565 host = uri.mHost;
2566 } catch (android.net.ParseException ex) {
2567 host = "browser";
The Android Open Source Project0c908882009-03-03 19:32:16 -08002568 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002569 host = host.replace('.', '_');
2570 host += ".trace";
2571 mInTrace = true;
2572 Debug.startMethodTracing(host, 20 * 1024 * 1024);
2573 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002574
Grace Kloba22ac16e2009-10-07 18:00:23 -07002575 // Performance probe
2576 if (false) {
2577 mStart = SystemClock.uptimeMillis();
2578 mProcessStart = Process.getElapsedCpuTime();
2579 long[] sysCpu = new long[7];
2580 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2581 sysCpu, null)) {
2582 mUserStart = sysCpu[0] + sysCpu[1];
2583 mSystemStart = sysCpu[2];
2584 mIdleStart = sysCpu[3];
2585 mIrqStart = sysCpu[4] + sysCpu[5] + sysCpu[6];
2586 }
2587 mUiStart = SystemClock.currentThreadTimeMillis();
2588 }
2589 }
2590
2591 void onPageFinished(WebView view, String url) {
2592 // Reset the title and icon in case we stopped a provisional load.
2593 resetTitleAndIcon(view);
2594 // Update the lock icon image only once we are done loading
2595 updateLockIconToLatest();
2596 // pause the WebView timer and release the wake lock if it is finished
2597 // while BrowserActivity is in pause state.
2598 if (mActivityInPause && pauseWebViewTimers()) {
2599 if (mWakeLock.isHeld()) {
2600 mHandler.removeMessages(RELEASE_WAKELOCK);
2601 mWakeLock.release();
2602 }
2603 }
2604
2605 // Performance probe
2606 if (false) {
2607 long[] sysCpu = new long[7];
2608 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2609 sysCpu, null)) {
2610 String uiInfo = "UI thread used "
2611 + (SystemClock.currentThreadTimeMillis() - mUiStart)
2612 + " ms";
2613 if (LOGD_ENABLED) {
2614 Log.d(LOGTAG, uiInfo);
2615 }
2616 //The string that gets written to the log
2617 String performanceString = "It took total "
2618 + (SystemClock.uptimeMillis() - mStart)
2619 + " ms clock time to load the page."
2620 + "\nbrowser process used "
2621 + (Process.getElapsedCpuTime() - mProcessStart)
2622 + " ms, user processes used "
2623 + (sysCpu[0] + sysCpu[1] - mUserStart) * 10
2624 + " ms, kernel used "
2625 + (sysCpu[2] - mSystemStart) * 10
2626 + " ms, idle took " + (sysCpu[3] - mIdleStart) * 10
2627 + " ms and irq took "
2628 + (sysCpu[4] + sysCpu[5] + sysCpu[6] - mIrqStart)
2629 * 10 + " ms, " + uiInfo;
2630 if (LOGD_ENABLED) {
2631 Log.d(LOGTAG, performanceString + "\nWebpage: " + url);
2632 }
2633 if (url != null) {
2634 // strip the url to maintain consistency
2635 String newUrl = new String(url);
2636 if (newUrl.startsWith("http://www.")) {
2637 newUrl = newUrl.substring(11);
2638 } else if (newUrl.startsWith("http://")) {
2639 newUrl = newUrl.substring(7);
2640 } else if (newUrl.startsWith("https://www.")) {
2641 newUrl = newUrl.substring(12);
2642 } else if (newUrl.startsWith("https://")) {
2643 newUrl = newUrl.substring(8);
2644 }
2645 if (LOGD_ENABLED) {
2646 Log.d(LOGTAG, newUrl + " loaded");
2647 }
Grace Kloba5b078b52009-06-24 20:23:41 -07002648 }
2649 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002650 }
Grace Kloba5b078b52009-06-24 20:23:41 -07002651
Grace Kloba22ac16e2009-10-07 18:00:23 -07002652 if (mInTrace) {
2653 mInTrace = false;
2654 Debug.stopMethodTracing();
2655 }
2656 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002657
Grace Klobae7fe26b2010-06-28 16:23:33 -07002658 private void closeEmptyChildTab() {
2659 Tab current = mTabControl.getCurrentTab();
2660 if (current != null
2661 && current.getWebView().copyBackForwardList().getSize() == 0) {
2662 Tab parent = current.getParentTab();
2663 if (parent != null) {
2664 switchToTab(mTabControl.getTabIndex(parent));
2665 closeTab(current);
2666 }
2667 }
2668 }
2669
Grace Kloba22ac16e2009-10-07 18:00:23 -07002670 boolean shouldOverrideUrlLoading(WebView view, String url) {
Jeff Hamilton47654f42010-09-07 09:57:51 -05002671 if (view.isPrivateBrowsingEnabled()) {
2672 // Don't allow urls to leave the browser app when in private browsing mode
2673 loadUrl(view, url);
2674 return true;
2675 }
2676
Grace Kloba22ac16e2009-10-07 18:00:23 -07002677 if (url.startsWith(SCHEME_WTAI)) {
2678 // wtai://wp/mc;number
2679 // number=string(phone-number)
2680 if (url.startsWith(SCHEME_WTAI_MC)) {
2681 Intent intent = new Intent(Intent.ACTION_VIEW,
2682 Uri.parse(WebView.SCHEME_TEL +
2683 url.substring(SCHEME_WTAI_MC.length())));
2684 startActivity(intent);
Grace Klobae7fe26b2010-06-28 16:23:33 -07002685 // before leaving BrowserActivity, close the empty child tab.
2686 // If a new tab is created through JavaScript open to load this
2687 // url, we would like to close it as we will load this url in a
2688 // different Activity.
2689 closeEmptyChildTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002690 return true;
2691 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002692 // wtai://wp/sd;dtmf
2693 // dtmf=string(dialstring)
2694 if (url.startsWith(SCHEME_WTAI_SD)) {
2695 // TODO: only send when there is active voice connection
2696 return false;
2697 }
2698 // wtai://wp/ap;number;name
2699 // number=string(phone-number)
2700 // name=string
2701 if (url.startsWith(SCHEME_WTAI_AP)) {
2702 // TODO
2703 return false;
2704 }
2705 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002706
Grace Kloba22ac16e2009-10-07 18:00:23 -07002707 // The "about:" schemes are internal to the browser; don't want these to
2708 // be dispatched to other apps.
2709 if (url.startsWith("about:")) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002710 return false;
2711 }
2712
Jeff Davidson43610292010-07-16 16:03:58 -07002713 // If this is a Google search, attempt to add an RLZ string (if one isn't already present).
2714 if (rlzProviderPresent()) {
2715 Uri siteUri = Uri.parse(url);
2716 if (needsRlzString(siteUri)) {
2717 String rlz = null;
2718 Cursor cur = null;
2719 try {
2720 cur = getContentResolver().query(getRlzUri(), null, null, null, null);
2721 if (cur != null && cur.moveToFirst() && !cur.isNull(0)) {
2722 url = siteUri.buildUpon()
2723 .appendQueryParameter("rlz", cur.getString(0))
2724 .build().toString();
2725 }
2726 } finally {
2727 if (cur != null) {
2728 cur.close();
2729 }
2730 }
2731 loadUrl(view, url);
2732 return true;
2733 }
2734 }
2735
Grace Kloba22ac16e2009-10-07 18:00:23 -07002736 Intent intent;
2737 // perform generic parsing of the URI to turn it into an Intent.
2738 try {
2739 intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME);
2740 } catch (URISyntaxException ex) {
2741 Log.w("Browser", "Bad URI " + url + ": " + ex.getMessage());
2742 return false;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002743 }
2744
Grace Kloba22ac16e2009-10-07 18:00:23 -07002745 // check whether the intent can be resolved. If not, we will see
2746 // whether we can download it from the Market.
2747 if (getPackageManager().resolveActivity(intent, 0) == null) {
2748 String packagename = intent.getPackage();
2749 if (packagename != null) {
2750 intent = new Intent(Intent.ACTION_VIEW, Uri
2751 .parse("market://search?q=pname:" + packagename));
2752 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2753 startActivity(intent);
Grace Klobae7fe26b2010-06-28 16:23:33 -07002754 // before leaving BrowserActivity, close the empty child tab.
2755 // If a new tab is created through JavaScript open to load this
2756 // url, we would like to close it as we will load this url in a
2757 // different Activity.
2758 closeEmptyChildTab();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002759 return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002760 } else {
2761 return false;
2762 }
2763 }
2764
Grace Kloba22ac16e2009-10-07 18:00:23 -07002765 // sanitize the Intent, ensuring web pages can not bypass browser
2766 // security (only access to BROWSABLE activities).
2767 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2768 intent.setComponent(null);
2769 try {
2770 if (startActivityIfNeeded(intent, -1)) {
Grace Klobae7fe26b2010-06-28 16:23:33 -07002771 // before leaving BrowserActivity, close the empty child tab.
2772 // If a new tab is created through JavaScript open to load this
2773 // url, we would like to close it as we will load this url in a
2774 // different Activity.
2775 closeEmptyChildTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002776 return true;
2777 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002778 } catch (ActivityNotFoundException ex) {
2779 // ignore the error. If no application can handle the URL,
2780 // eg about:blank, assume the browser can handle it.
2781 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002782
Grace Kloba22ac16e2009-10-07 18:00:23 -07002783 if (mMenuIsDown) {
Michael Kolb68792c82010-08-09 16:39:18 -07002784 openTab(url, false);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002785 closeOptionsMenu();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002786 return true;
2787 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002788 return false;
2789 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002790
Jeff Davidson43610292010-07-16 16:03:58 -07002791 // Determine whether the RLZ provider is present on the system.
2792 private boolean rlzProviderPresent() {
2793 if (mIsProviderPresent == null) {
2794 PackageManager pm = getPackageManager();
2795 mIsProviderPresent = pm.resolveContentProvider(BrowserSettings.RLZ_PROVIDER, 0) != null;
2796 }
2797 return mIsProviderPresent;
2798 }
2799
2800 // Retrieve the RLZ access point string and cache the URI used to retrieve RLZ values.
2801 private Uri getRlzUri() {
2802 if (mRlzUri == null) {
2803 String ap = getResources().getString(R.string.rlz_access_point);
2804 mRlzUri = Uri.withAppendedPath(BrowserSettings.RLZ_PROVIDER_URI, ap);
2805 }
2806 return mRlzUri;
2807 }
2808
2809 // Determine if this URI appears to be for a Google search and does not have an RLZ parameter.
2810 // Taken largely from Chrome source, src/chrome/browser/google_url_tracker.cc
2811 private static boolean needsRlzString(Uri uri) {
Bill Napierc50e71a2010-08-27 14:03:03 -07002812 String scheme = uri.getScheme();
2813 if (("http".equals(scheme) || "https".equals(scheme)) &&
2814 (uri.getQueryParameter("q") != null) && (uri.getQueryParameter("rlz") == null)) {
Jeff Davidson43610292010-07-16 16:03:58 -07002815 String host = uri.getHost();
2816 if (host == null) {
2817 return false;
2818 }
2819 String[] hostComponents = host.split("\\.");
2820
2821 if (hostComponents.length < 2) {
2822 return false;
2823 }
2824 int googleComponent = hostComponents.length - 2;
2825 String component = hostComponents[googleComponent];
2826 if (!"google".equals(component)) {
2827 if (hostComponents.length < 3 ||
2828 (!"co".equals(component) && !"com".equals(component))) {
2829 return false;
2830 }
2831 googleComponent = hostComponents.length - 3;
2832 if (!"google".equals(hostComponents[googleComponent])) {
2833 return false;
2834 }
2835 }
2836
2837 // Google corp network handling.
2838 if (googleComponent > 0 && "corp".equals(hostComponents[googleComponent - 1])) {
2839 return false;
2840 }
2841
2842 return true;
2843 }
2844 return false;
2845 }
2846
Grace Kloba22ac16e2009-10-07 18:00:23 -07002847 // -------------------------------------------------------------------------
2848 // Helper function for WebChromeClient
2849 // -------------------------------------------------------------------------
The Android Open Source Project0c908882009-03-03 19:32:16 -08002850
Grace Kloba22ac16e2009-10-07 18:00:23 -07002851 void onProgressChanged(WebView view, int newProgress) {
Michael Kolba2b2ba82010-08-04 17:54:03 -07002852
2853 // On the phone, the fake title bar will always cover up the
2854 // regular title bar (or the regular one is offscreen), so only the
2855 // fake title bar needs to change its progress
2856 mFakeTitleBar.setProgress(newProgress);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002857
Grace Kloba22ac16e2009-10-07 18:00:23 -07002858 if (newProgress == 100) {
2859 // onProgressChanged() may continue to be called after the main
2860 // frame has finished loading, as any remaining sub frames continue
2861 // to load. We'll only get called once though with newProgress as
2862 // 100 when everything is loaded. (onPageFinished is called once
2863 // when the main frame completes loading regardless of the state of
2864 // any sub frames so calls to onProgressChanges may continue after
2865 // onPageFinished has executed)
2866 if (mInLoad) {
2867 mInLoad = false;
Leon Scrogginsa27ff192009-09-14 12:58:04 -04002868 updateInLoadMenuItems();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002869 // If the options menu is open, leave the title bar
2870 if (!mOptionsMenuOpen || !mIconView) {
2871 hideFakeTitleBar();
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07002872 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002873 }
Leon Scrogginsaa37e7f2010-03-05 11:51:20 -05002874 } else {
2875 if (!mInLoad) {
2876 // onPageFinished may have already been called but a subframe is
2877 // still loading and updating the progress. Reset mInLoad and
2878 // update the menu items.
2879 mInLoad = true;
2880 updateInLoadMenuItems();
2881 }
2882 // When the page first begins to load, the Activity may still be
2883 // paused, in which case showFakeTitleBar will do nothing. Call
2884 // again as the page continues to load so that it will be shown.
2885 // (Calling it will the fake title bar is already showing will also
2886 // do nothing.
Grace Kloba22ac16e2009-10-07 18:00:23 -07002887 if (!mOptionsMenuOpen || mIconView) {
2888 // This page has begun to load, so show the title bar
2889 showFakeTitleBar();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002890 }
2891 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002892 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002893
Grace Kloba22ac16e2009-10-07 18:00:23 -07002894 void onShowCustomView(View view, WebChromeClient.CustomViewCallback callback) {
Derek Sollenberger8ff57db2009-12-08 15:39:55 -05002895 // if a view already exists then immediately terminate the new one
2896 if (mCustomView != null) {
2897 callback.onCustomViewHidden();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002898 return;
Derek Sollenberger8ff57db2009-12-08 15:39:55 -05002899 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002900
2901 // Add the custom view to its container.
2902 mCustomViewContainer.addView(view, COVER_SCREEN_GRAVITY_CENTER);
2903 mCustomView = view;
2904 mCustomViewCallback = callback;
2905 // Save the menu state and set it to empty while the custom
2906 // view is showing.
2907 mOldMenuState = mMenuState;
2908 mMenuState = EMPTY_MENU;
2909 // Hide the content view.
2910 mContentView.setVisibility(View.GONE);
2911 // Finally show the custom view container.
Andrei Popescu163ab742009-10-20 17:58:23 +01002912 setStatusBarVisibility(false);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002913 mCustomViewContainer.setVisibility(View.VISIBLE);
2914 mCustomViewContainer.bringToFront();
2915 }
2916
2917 void onHideCustomView() {
2918 if (mCustomView == null)
2919 return;
2920
2921 // Hide the custom view.
2922 mCustomView.setVisibility(View.GONE);
2923 // Remove the custom view from its container.
2924 mCustomViewContainer.removeView(mCustomView);
2925 mCustomView = null;
2926 // Reset the old menu state.
2927 mMenuState = mOldMenuState;
2928 mOldMenuState = EMPTY_MENU;
2929 mCustomViewContainer.setVisibility(View.GONE);
2930 mCustomViewCallback.onCustomViewHidden();
2931 // Show the content view.
Andrei Popescu163ab742009-10-20 17:58:23 +01002932 setStatusBarVisibility(true);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002933 mContentView.setVisibility(View.VISIBLE);
2934 }
2935
2936 Bitmap getDefaultVideoPoster() {
2937 if (mDefaultVideoPoster == null) {
2938 mDefaultVideoPoster = BitmapFactory.decodeResource(
2939 getResources(), R.drawable.default_video_poster);
Patrick Scott3918d442009-08-04 13:22:29 -04002940 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002941 return mDefaultVideoPoster;
2942 }
Patrick Scott3918d442009-08-04 13:22:29 -04002943
Grace Kloba22ac16e2009-10-07 18:00:23 -07002944 View getVideoLoadingProgressView() {
2945 if (mVideoProgressView == null) {
2946 LayoutInflater inflater = LayoutInflater.from(BrowserActivity.this);
2947 mVideoProgressView = inflater.inflate(
2948 R.layout.video_loading_progress, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002949 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002950 return mVideoProgressView;
2951 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002952
Leon Scroggins8d5fa432009-10-02 15:55:59 -04002953 /*
2954 * The Object used to inform the WebView of the file to upload.
2955 */
2956 private ValueCallback<Uri> mUploadMessage;
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002957 private String mCameraFilePath;
Leon Scroggins8d5fa432009-10-02 15:55:59 -04002958
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002959 void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
2960
2961 final String imageMimeType = "image/*";
Ben Murdoch6af492a2010-06-15 12:38:17 +01002962 final String videoMimeType = "video/*";
Ben Murdoch039bd472010-07-21 21:26:57 +01002963 final String audioMimeType = "audio/*";
Ben Murdochb50d7402010-07-16 12:42:22 +01002964 final String mediaSourceKey = "capture";
Ben Murdoch6af492a2010-06-15 12:38:17 +01002965 final String mediaSourceValueCamera = "camera";
Ben Murdochb50d7402010-07-16 12:42:22 +01002966 final String mediaSourceValueFileSystem = "filesystem";
Ben Murdoch6af492a2010-06-15 12:38:17 +01002967 final String mediaSourceValueCamcorder = "camcorder";
Ben Murdoch039bd472010-07-21 21:26:57 +01002968 final String mediaSourceValueMicrophone = "microphone";
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002969
Ben Murdoch039bd472010-07-21 21:26:57 +01002970 // media source can be 'filesystem' or 'camera' or 'camcorder' or 'microphone'.
Ben Murdoch6af492a2010-06-15 12:38:17 +01002971 String mediaSource = "";
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002972
Ben Murdoch6af492a2010-06-15 12:38:17 +01002973 // We add the camera intent if there was no accept type (or '*/*' or 'image/*').
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002974 boolean addCameraIntent = true;
Ben Murdoch6af492a2010-06-15 12:38:17 +01002975 // We add the camcorder intent if there was no accept type (or '*/*' or 'video/*').
2976 boolean addCamcorderIntent = true;
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002977
Ben Murdoch6af492a2010-06-15 12:38:17 +01002978 if (mUploadMessage != null) {
2979 // Already a file picker operation in progress.
2980 return;
2981 }
2982
Grace Kloba22ac16e2009-10-07 18:00:23 -07002983 mUploadMessage = uploadMsg;
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002984
2985 // Parse the accept type.
2986 String params[] = acceptType.split(";");
2987 String mimeType = params[0];
2988
2989 for (String p : params) {
2990 String[] keyValue = p.split("=");
2991 if (keyValue.length == 2) {
2992 // Process key=value parameters.
Ben Murdoch6af492a2010-06-15 12:38:17 +01002993 if (mediaSourceKey.equals(keyValue[0])) {
2994 mediaSource = keyValue[1];
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002995 }
2996 }
2997 }
2998
2999 // This intent will display the standard OPENABLE file picker.
Grace Kloba22ac16e2009-10-07 18:00:23 -07003000 Intent i = new Intent(Intent.ACTION_GET_CONTENT);
3001 i.addCategory(Intent.CATEGORY_OPENABLE);
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003002
3003 // Create an intent to add to the standard file picker that will
3004 // capture an image from the camera. We'll combine this intent with
3005 // the standard OPENABLE picker unless the web developer specifically
3006 // requested the camera or gallery be opened by passing a parameter
3007 // in the accept type.
3008 Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
3009 File externalDataDir = Environment.getExternalStoragePublicDirectory(
3010 Environment.DIRECTORY_DCIM);
3011 File cameraDataDir = new File(externalDataDir.getAbsolutePath() +
3012 File.separator + "browser-photos");
3013 cameraDataDir.mkdirs();
3014 mCameraFilePath = cameraDataDir.getAbsolutePath() + File.separator +
3015 System.currentTimeMillis() + ".jpg";
3016 cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(mCameraFilePath)));
3017
Ben Murdoch6af492a2010-06-15 12:38:17 +01003018 Intent camcorderIntent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
3019
Ben Murdoch039bd472010-07-21 21:26:57 +01003020 Intent soundRecIntent = new Intent(MediaStore.Audio.Media.RECORD_SOUND_ACTION);
3021
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003022 if (mimeType.equals(imageMimeType)) {
3023 i.setType(imageMimeType);
Ben Murdoch6af492a2010-06-15 12:38:17 +01003024 addCamcorderIntent = false;
3025 if (mediaSource.equals(mediaSourceValueCamera)) {
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003026 // Specified 'image/*' and requested the camera, so go ahead and launch the camera
3027 // directly.
3028 BrowserActivity.this.startActivityForResult(cameraIntent, FILE_SELECTED);
3029 return;
Ben Murdochb50d7402010-07-16 12:42:22 +01003030 } else if (mediaSource.equals(mediaSourceValueFileSystem)) {
3031 // Specified filesytem as the source, so don't want to consider the camera.
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003032 addCameraIntent = false;
3033 }
Ben Murdoch6af492a2010-06-15 12:38:17 +01003034 } else if (mimeType.equals(videoMimeType)) {
3035 i.setType(videoMimeType);
3036 addCameraIntent = false;
3037 // The camcorder saves it's own file and returns it to us in the intent, so
3038 // we don't need to generate one here.
3039 mCameraFilePath = null;
3040
3041 if (mediaSource.equals(mediaSourceValueCamcorder)) {
Ben Murdoch039bd472010-07-21 21:26:57 +01003042 // Specified 'video/*' and requested the camcorder, so go ahead and launch the
3043 // camcorder directly.
Ben Murdoch6af492a2010-06-15 12:38:17 +01003044 BrowserActivity.this.startActivityForResult(camcorderIntent, FILE_SELECTED);
3045 return;
Ben Murdochb50d7402010-07-16 12:42:22 +01003046 } else if (mediaSource.equals(mediaSourceValueFileSystem)) {
3047 // Specified filesystem as the source, so don't want to consider the camcorder.
Ben Murdoch6af492a2010-06-15 12:38:17 +01003048 addCamcorderIntent = false;
3049 }
Ben Murdoch039bd472010-07-21 21:26:57 +01003050 } else if (mimeType.equals(audioMimeType)) {
3051 i.setType(audioMimeType);
3052 addCameraIntent = false;
3053 addCamcorderIntent = false;
3054 if (mediaSource.equals(mediaSourceValueMicrophone)) {
3055 // Specified 'audio/*' and requested microphone, so go ahead and launch the sound
3056 // recorder.
3057 BrowserActivity.this.startActivityForResult(soundRecIntent, FILE_SELECTED);
3058 return;
3059 }
3060 // On a default system, there is no single option to open an audio "gallery". Both the
3061 // sound recorder and music browser respond to the OPENABLE/audio/* intent unlike the
3062 // image/* and video/* OPENABLE intents where the image / video gallery are the only
3063 // respondants (and so the user is not prompted by default).
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003064 } else {
3065 i.setType("*/*");
3066 }
3067
Ben Murdoch6af492a2010-06-15 12:38:17 +01003068 // Combine the chooser and the extra choices (like camera or camcorder)
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003069 Intent chooser = new Intent(Intent.ACTION_CHOOSER);
3070 chooser.putExtra(Intent.EXTRA_INTENT, i);
3071
Ben Murdoch6af492a2010-06-15 12:38:17 +01003072 Vector<Intent> extraInitialIntents = new Vector<Intent>(0);
3073
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003074 if (addCameraIntent) {
Ben Murdoch6af492a2010-06-15 12:38:17 +01003075 extraInitialIntents.add(cameraIntent);
3076 }
3077
3078 if (addCamcorderIntent) {
3079 extraInitialIntents.add(camcorderIntent);
3080 }
3081
3082 if (extraInitialIntents.size() > 0) {
3083 Intent[] extraIntents = new Intent[extraInitialIntents.size()];
3084 chooser.putExtra(Intent.EXTRA_INITIAL_INTENTS, extraInitialIntents.toArray(extraIntents));
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003085 }
3086
3087 chooser.putExtra(Intent.EXTRA_TITLE, getString(R.string.choose_upload));
3088 BrowserActivity.this.startActivityForResult(chooser, FILE_SELECTED);
Grace Kloba22ac16e2009-10-07 18:00:23 -07003089 }
3090
3091 // -------------------------------------------------------------------------
3092 // Implement functions for DownloadListener
3093 // -------------------------------------------------------------------------
3094
The Android Open Source Project0c908882009-03-03 19:32:16 -08003095 /**
3096 * Notify the host application a download should be done, or that
3097 * the data should be streamed if a streaming viewer is available.
3098 * @param url The full url to the content that should be downloaded
3099 * @param contentDisposition Content-disposition http header, if
3100 * present.
3101 * @param mimetype The mimetype of the content reported by the server
3102 * @param contentLength The file size reported by the server
3103 */
3104 public void onDownloadStart(String url, String userAgent,
3105 String contentDisposition, String mimetype, long contentLength) {
3106 // if we're dealing wih A/V content that's not explicitly marked
3107 // for download, check if it's streamable.
3108 if (contentDisposition == null
Patrick Scotte1fb9662009-08-31 14:31:52 -04003109 || !contentDisposition.regionMatches(
3110 true, 0, "attachment", 0, 10)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003111 // query the package manager to see if there's a registered handler
3112 // that matches.
3113 Intent intent = new Intent(Intent.ACTION_VIEW);
3114 intent.setDataAndType(Uri.parse(url), mimetype);
Patrick Scotte1fb9662009-08-31 14:31:52 -04003115 ResolveInfo info = getPackageManager().resolveActivity(intent,
3116 PackageManager.MATCH_DEFAULT_ONLY);
3117 if (info != null) {
3118 ComponentName myName = getComponentName();
3119 // If we resolved to ourselves, we don't want to attempt to
3120 // load the url only to try and download it again.
3121 if (!myName.getPackageName().equals(
3122 info.activityInfo.packageName)
3123 || !myName.getClassName().equals(
3124 info.activityInfo.name)) {
3125 // someone (other than us) knows how to handle this mime
3126 // type with this scheme, don't download.
3127 try {
3128 startActivity(intent);
3129 return;
3130 } catch (ActivityNotFoundException ex) {
3131 if (LOGD_ENABLED) {
3132 Log.d(LOGTAG, "activity not found for " + mimetype
3133 + " over " + Uri.parse(url).getScheme(),
3134 ex);
3135 }
3136 // Best behavior is to fall back to a download in this
3137 // case
The Android Open Source Project0c908882009-03-03 19:32:16 -08003138 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003139 }
3140 }
3141 }
3142 onDownloadStartNoStream(url, userAgent, contentDisposition, mimetype, contentLength);
3143 }
3144
Kristian Monsenfa52d172010-03-25 18:29:21 +00003145 // This is to work around the fact that java.net.URI throws Exceptions
3146 // instead of just encoding URL's properly
3147 // Helper method for onDownloadStartNoStream
3148 private static String encodePath(String path) {
3149 char[] chars = path.toCharArray();
3150
3151 boolean needed = false;
3152 for (char c : chars) {
3153 if (c == '[' || c == ']') {
3154 needed = true;
3155 break;
3156 }
3157 }
3158 if (needed == false) {
3159 return path;
3160 }
3161
3162 StringBuilder sb = new StringBuilder("");
3163 for (char c : chars) {
3164 if (c == '[' || c == ']') {
3165 sb.append('%');
3166 sb.append(Integer.toHexString(c));
3167 } else {
3168 sb.append(c);
3169 }
3170 }
3171
3172 return sb.toString();
3173 }
3174
The Android Open Source Project0c908882009-03-03 19:32:16 -08003175 /**
3176 * Notify the host application a download should be done, even if there
3177 * is a streaming viewer available for thise type.
3178 * @param url The full url to the content that should be downloaded
3179 * @param contentDisposition Content-disposition http header, if
3180 * present.
3181 * @param mimetype The mimetype of the content reported by the server
3182 * @param contentLength The file size reported by the server
3183 */
3184 /*package */ void onDownloadStartNoStream(String url, String userAgent,
3185 String contentDisposition, String mimetype, long contentLength) {
3186
3187 String filename = URLUtil.guessFileName(url,
3188 contentDisposition, mimetype);
3189
3190 // Check to see if we have an SDCard
3191 String status = Environment.getExternalStorageState();
3192 if (!status.equals(Environment.MEDIA_MOUNTED)) {
3193 int title;
3194 String msg;
3195
3196 // Check to see if the SDCard is busy, same as the music app
3197 if (status.equals(Environment.MEDIA_SHARED)) {
3198 msg = getString(R.string.download_sdcard_busy_dlg_msg);
3199 title = R.string.download_sdcard_busy_dlg_title;
3200 } else {
3201 msg = getString(R.string.download_no_sdcard_dlg_msg, filename);
3202 title = R.string.download_no_sdcard_dlg_title;
3203 }
3204
3205 new AlertDialog.Builder(this)
3206 .setTitle(title)
3207 .setIcon(android.R.drawable.ic_dialog_alert)
3208 .setMessage(msg)
3209 .setPositiveButton(R.string.ok, null)
3210 .show();
3211 return;
3212 }
3213
Kristian Monsenfa52d172010-03-25 18:29:21 +00003214 // java.net.URI is a lot stricter than KURL so we have to encode some
3215 // extra characters. Fix for b 2538060 and b 1634719
3216 WebAddress webAddress;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003217 try {
Kristian Monsenfa52d172010-03-25 18:29:21 +00003218 webAddress = new WebAddress(url);
3219 webAddress.mPath = encodePath(webAddress.mPath);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003220 } catch (Exception e) {
Kristian Monsenfa52d172010-03-25 18:29:21 +00003221 // This only happens for very bad urls, we want to chatch the
3222 // exception here
3223 Log.e(LOGTAG, "Exception trying to parse url:" + url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003224 return;
3225 }
3226
3227 // XXX: Have to use the old url since the cookies were stored using the
3228 // old percent-encoded url.
3229 String cookies = CookieManager.getInstance().getCookie(url);
3230
3231 ContentValues values = new ContentValues();
Kristian Monsenfa52d172010-03-25 18:29:21 +00003232 values.put(Downloads.Impl.COLUMN_URI, webAddress.toString());
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08003233 values.put(Downloads.Impl.COLUMN_COOKIE_DATA, cookies);
3234 values.put(Downloads.Impl.COLUMN_USER_AGENT, userAgent);
3235 values.put(Downloads.Impl.COLUMN_NOTIFICATION_PACKAGE,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003236 getPackageName());
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08003237 values.put(Downloads.Impl.COLUMN_NOTIFICATION_CLASS,
Leon Scrogginsa563d092010-04-19 16:53:49 -04003238 OpenDownloadReceiver.class.getCanonicalName());
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08003239 values.put(Downloads.Impl.COLUMN_VISIBILITY,
3240 Downloads.Impl.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
3241 values.put(Downloads.Impl.COLUMN_MIME_TYPE, mimetype);
3242 values.put(Downloads.Impl.COLUMN_FILE_NAME_HINT, filename);
Kristian Monsenfa52d172010-03-25 18:29:21 +00003243 values.put(Downloads.Impl.COLUMN_DESCRIPTION, webAddress.mHost);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003244 if (contentLength > 0) {
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08003245 values.put(Downloads.Impl.COLUMN_TOTAL_BYTES, contentLength);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003246 }
3247 if (mimetype == null) {
3248 // We must have long pressed on a link or image to download it. We
3249 // are not sure of the mimetype in this case, so do a head request
3250 new FetchUrlMimeType(this).execute(values);
3251 } else {
3252 final Uri contentUri =
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08003253 getContentResolver().insert(Downloads.Impl.CONTENT_URI, values);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003254 }
Leon Scroggins9191a7f2010-03-18 14:44:44 -04003255 Toast.makeText(this, R.string.download_pending, Toast.LENGTH_SHORT)
3256 .show();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003257 }
3258
Grace Kloba22ac16e2009-10-07 18:00:23 -07003259 // -------------------------------------------------------------------------
3260
The Android Open Source Project0c908882009-03-03 19:32:16 -08003261 /**
3262 * Resets the lock icon. This method is called when we start a new load and
3263 * know the url to be loaded.
3264 */
3265 private void resetLockIcon(String url) {
3266 // Save the lock-icon state (we revert to it if the load gets cancelled)
Grace Kloba22ac16e2009-10-07 18:00:23 -07003267 mTabControl.getCurrentTab().resetLockIcon(url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003268 updateLockIconImage(LOCK_ICON_UNSECURE);
3269 }
3270
The Android Open Source Project0c908882009-03-03 19:32:16 -08003271 /**
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04003272 * Update the lock icon to correspond to our latest state.
3273 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003274 private void updateLockIconToLatest() {
Leon Scroggins91f65fc2010-06-29 13:52:39 -04003275 Tab t = mTabControl.getCurrentTab();
3276 if (t != null) {
3277 updateLockIconImage(t.getLockIconType());
3278 }
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04003279 }
3280
3281 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08003282 * Updates the lock-icon image in the title-bar.
3283 */
3284 private void updateLockIconImage(int lockIconType) {
3285 Drawable d = null;
3286 if (lockIconType == LOCK_ICON_SECURE) {
3287 d = mSecLockIcon;
3288 } else if (lockIconType == LOCK_ICON_MIXED) {
3289 d = mMixLockIcon;
3290 }
Leon Scroggins68579392009-09-15 15:31:54 -04003291 mTitleBar.setLock(d);
Michael Kolba2b2ba82010-08-04 17:54:03 -07003292 mFakeTitleBar.setLock(d);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003293 }
3294
3295 /**
3296 * Displays a page-info dialog.
3297 * @param tab The tab to show info about
3298 * @param fromShowSSLCertificateOnError The flag that indicates whether
3299 * this dialog was opened from the SSL-certificate-on-error dialog or
3300 * not. This is important, since we need to know whether to return to
3301 * the parent dialog or simply dismiss.
3302 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003303 private void showPageInfo(final Tab tab,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003304 final boolean fromShowSSLCertificateOnError) {
3305 final LayoutInflater factory = LayoutInflater
3306 .from(this);
3307
3308 final View pageInfoView = factory.inflate(R.layout.page_info, null);
3309
3310 final WebView view = tab.getWebView();
3311
3312 String url = null;
3313 String title = null;
3314
3315 if (view == null) {
3316 url = tab.getUrl();
3317 title = tab.getTitle();
3318 } else if (view == mTabControl.getCurrentWebView()) {
3319 // Use the cached title and url if this is the current WebView
3320 url = mUrl;
3321 title = mTitle;
3322 } else {
3323 url = view.getUrl();
3324 title = view.getTitle();
3325 }
3326
3327 if (url == null) {
3328 url = "";
3329 }
3330 if (title == null) {
3331 title = "";
3332 }
3333
3334 ((TextView) pageInfoView.findViewById(R.id.address)).setText(url);
3335 ((TextView) pageInfoView.findViewById(R.id.title)).setText(title);
3336
3337 mPageInfoView = tab;
Leon Scrogginsc7b92f82010-01-11 18:17:31 -05003338 mPageInfoFromShowSSLCertificateOnError = fromShowSSLCertificateOnError;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003339
3340 AlertDialog.Builder alertDialogBuilder =
3341 new AlertDialog.Builder(this)
3342 .setTitle(R.string.page_info).setIcon(android.R.drawable.ic_dialog_info)
3343 .setView(pageInfoView)
3344 .setPositiveButton(
3345 R.string.ok,
3346 new DialogInterface.OnClickListener() {
3347 public void onClick(DialogInterface dialog,
3348 int whichButton) {
3349 mPageInfoDialog = null;
3350 mPageInfoView = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003351
3352 // if we came here from the SSL error dialog
3353 if (fromShowSSLCertificateOnError) {
3354 // go back to the SSL error dialog
3355 showSSLCertificateOnError(
3356 mSSLCertificateOnErrorView,
3357 mSSLCertificateOnErrorHandler,
3358 mSSLCertificateOnErrorError);
3359 }
3360 }
3361 })
3362 .setOnCancelListener(
3363 new DialogInterface.OnCancelListener() {
3364 public void onCancel(DialogInterface dialog) {
3365 mPageInfoDialog = null;
3366 mPageInfoView = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003367
3368 // if we came here from the SSL error dialog
3369 if (fromShowSSLCertificateOnError) {
3370 // go back to the SSL error dialog
3371 showSSLCertificateOnError(
3372 mSSLCertificateOnErrorView,
3373 mSSLCertificateOnErrorHandler,
3374 mSSLCertificateOnErrorError);
3375 }
3376 }
3377 });
3378
3379 // if we have a main top-level page SSL certificate set or a certificate
3380 // error
3381 if (fromShowSSLCertificateOnError ||
3382 (view != null && view.getCertificate() != null)) {
3383 // add a 'View Certificate' button
3384 alertDialogBuilder.setNeutralButton(
3385 R.string.view_certificate,
3386 new DialogInterface.OnClickListener() {
3387 public void onClick(DialogInterface dialog,
3388 int whichButton) {
3389 mPageInfoDialog = null;
3390 mPageInfoView = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003391
3392 // if we came here from the SSL error dialog
3393 if (fromShowSSLCertificateOnError) {
3394 // go back to the SSL error dialog
3395 showSSLCertificateOnError(
3396 mSSLCertificateOnErrorView,
3397 mSSLCertificateOnErrorHandler,
3398 mSSLCertificateOnErrorError);
3399 } else {
3400 // otherwise, display the top-most certificate from
3401 // the chain
3402 if (view.getCertificate() != null) {
3403 showSSLCertificate(tab);
3404 }
3405 }
3406 }
3407 });
3408 }
3409
3410 mPageInfoDialog = alertDialogBuilder.show();
3411 }
3412
3413 /**
3414 * Displays the main top-level page SSL certificate dialog
3415 * (accessible from the Page-Info dialog).
3416 * @param tab The tab to show certificate for.
3417 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003418 private void showSSLCertificate(final Tab tab) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003419 final View certificateView =
3420 inflateCertificateView(tab.getWebView().getCertificate());
3421 if (certificateView == null) {
3422 return;
3423 }
3424
3425 LayoutInflater factory = LayoutInflater.from(this);
3426
3427 final LinearLayout placeholder =
3428 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3429
3430 LinearLayout ll = (LinearLayout) factory.inflate(
3431 R.layout.ssl_success, placeholder);
3432 ((TextView)ll.findViewById(R.id.success))
3433 .setText(R.string.ssl_certificate_is_valid);
3434
3435 mSSLCertificateView = tab;
3436 mSSLCertificateDialog =
3437 new AlertDialog.Builder(this)
3438 .setTitle(R.string.ssl_certificate).setIcon(
3439 R.drawable.ic_dialog_browser_certificate_secure)
3440 .setView(certificateView)
3441 .setPositiveButton(R.string.ok,
3442 new DialogInterface.OnClickListener() {
3443 public void onClick(DialogInterface dialog,
3444 int whichButton) {
3445 mSSLCertificateDialog = null;
3446 mSSLCertificateView = null;
3447
3448 showPageInfo(tab, false);
3449 }
3450 })
3451 .setOnCancelListener(
3452 new DialogInterface.OnCancelListener() {
3453 public void onCancel(DialogInterface dialog) {
3454 mSSLCertificateDialog = null;
3455 mSSLCertificateView = null;
3456
3457 showPageInfo(tab, false);
3458 }
3459 })
3460 .show();
3461 }
3462
3463 /**
3464 * Displays the SSL error certificate dialog.
3465 * @param view The target web-view.
3466 * @param handler The SSL error handler responsible for cancelling the
3467 * connection that resulted in an SSL error or proceeding per user request.
3468 * @param error The SSL error object.
3469 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003470 void showSSLCertificateOnError(
The Android Open Source Project0c908882009-03-03 19:32:16 -08003471 final WebView view, final SslErrorHandler handler, final SslError error) {
3472
3473 final View certificateView =
3474 inflateCertificateView(error.getCertificate());
3475 if (certificateView == null) {
3476 return;
3477 }
3478
3479 LayoutInflater factory = LayoutInflater.from(this);
3480
3481 final LinearLayout placeholder =
3482 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3483
3484 if (error.hasError(SslError.SSL_UNTRUSTED)) {
3485 LinearLayout ll = (LinearLayout)factory
3486 .inflate(R.layout.ssl_warning, placeholder);
3487 ((TextView)ll.findViewById(R.id.warning))
3488 .setText(R.string.ssl_untrusted);
3489 }
3490
3491 if (error.hasError(SslError.SSL_IDMISMATCH)) {
3492 LinearLayout ll = (LinearLayout)factory
3493 .inflate(R.layout.ssl_warning, placeholder);
3494 ((TextView)ll.findViewById(R.id.warning))
3495 .setText(R.string.ssl_mismatch);
3496 }
3497
3498 if (error.hasError(SslError.SSL_EXPIRED)) {
3499 LinearLayout ll = (LinearLayout)factory
3500 .inflate(R.layout.ssl_warning, placeholder);
3501 ((TextView)ll.findViewById(R.id.warning))
3502 .setText(R.string.ssl_expired);
3503 }
3504
3505 if (error.hasError(SslError.SSL_NOTYETVALID)) {
3506 LinearLayout ll = (LinearLayout)factory
3507 .inflate(R.layout.ssl_warning, placeholder);
3508 ((TextView)ll.findViewById(R.id.warning))
3509 .setText(R.string.ssl_not_yet_valid);
3510 }
3511
3512 mSSLCertificateOnErrorHandler = handler;
3513 mSSLCertificateOnErrorView = view;
3514 mSSLCertificateOnErrorError = error;
3515 mSSLCertificateOnErrorDialog =
3516 new AlertDialog.Builder(this)
3517 .setTitle(R.string.ssl_certificate).setIcon(
3518 R.drawable.ic_dialog_browser_certificate_partially_secure)
3519 .setView(certificateView)
3520 .setPositiveButton(R.string.ok,
3521 new DialogInterface.OnClickListener() {
3522 public void onClick(DialogInterface dialog,
3523 int whichButton) {
3524 mSSLCertificateOnErrorDialog = null;
3525 mSSLCertificateOnErrorView = null;
3526 mSSLCertificateOnErrorHandler = null;
3527 mSSLCertificateOnErrorError = null;
3528
Grace Kloba22ac16e2009-10-07 18:00:23 -07003529 view.getWebViewClient().onReceivedSslError(
3530 view, handler, error);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003531 }
3532 })
3533 .setNeutralButton(R.string.page_info_view,
3534 new DialogInterface.OnClickListener() {
3535 public void onClick(DialogInterface dialog,
3536 int whichButton) {
3537 mSSLCertificateOnErrorDialog = null;
3538
3539 // do not clear the dialog state: we will
3540 // need to show the dialog again once the
3541 // user is done exploring the page-info details
3542
3543 showPageInfo(mTabControl.getTabFromView(view),
3544 true);
3545 }
3546 })
3547 .setOnCancelListener(
3548 new DialogInterface.OnCancelListener() {
3549 public void onCancel(DialogInterface dialog) {
3550 mSSLCertificateOnErrorDialog = null;
3551 mSSLCertificateOnErrorView = null;
3552 mSSLCertificateOnErrorHandler = null;
3553 mSSLCertificateOnErrorError = null;
3554
Grace Kloba22ac16e2009-10-07 18:00:23 -07003555 view.getWebViewClient().onReceivedSslError(
3556 view, handler, error);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003557 }
3558 })
3559 .show();
3560 }
3561
3562 /**
3563 * Inflates the SSL certificate view (helper method).
3564 * @param certificate The SSL certificate.
3565 * @return The resultant certificate view with issued-to, issued-by,
3566 * issued-on, expires-on, and possibly other fields set.
3567 * If the input certificate is null, returns null.
3568 */
3569 private View inflateCertificateView(SslCertificate certificate) {
3570 if (certificate == null) {
3571 return null;
3572 }
3573
3574 LayoutInflater factory = LayoutInflater.from(this);
3575
3576 View certificateView = factory.inflate(
3577 R.layout.ssl_certificate, null);
3578
3579 // issued to:
3580 SslCertificate.DName issuedTo = certificate.getIssuedTo();
3581 if (issuedTo != null) {
3582 ((TextView) certificateView.findViewById(R.id.to_common))
3583 .setText(issuedTo.getCName());
3584 ((TextView) certificateView.findViewById(R.id.to_org))
3585 .setText(issuedTo.getOName());
3586 ((TextView) certificateView.findViewById(R.id.to_org_unit))
3587 .setText(issuedTo.getUName());
3588 }
3589
3590 // issued by:
3591 SslCertificate.DName issuedBy = certificate.getIssuedBy();
3592 if (issuedBy != null) {
3593 ((TextView) certificateView.findViewById(R.id.by_common))
3594 .setText(issuedBy.getCName());
3595 ((TextView) certificateView.findViewById(R.id.by_org))
3596 .setText(issuedBy.getOName());
3597 ((TextView) certificateView.findViewById(R.id.by_org_unit))
3598 .setText(issuedBy.getUName());
3599 }
3600
3601 // issued on:
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003602 String issuedOn = formatCertificateDate(
3603 certificate.getValidNotBeforeDate());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003604 ((TextView) certificateView.findViewById(R.id.issued_on))
3605 .setText(issuedOn);
3606
3607 // expires on:
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003608 String expiresOn = formatCertificateDate(
3609 certificate.getValidNotAfterDate());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003610 ((TextView) certificateView.findViewById(R.id.expires_on))
3611 .setText(expiresOn);
3612
3613 return certificateView;
3614 }
3615
3616 /**
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003617 * Formats the certificate date to a properly localized date string.
The Android Open Source Project0c908882009-03-03 19:32:16 -08003618 * @return Properly localized version of the certificate date string and
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003619 * the "" if it fails to localize.
The Android Open Source Project0c908882009-03-03 19:32:16 -08003620 */
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003621 private String formatCertificateDate(Date certificateDate) {
3622 if (certificateDate == null) {
3623 return "";
The Android Open Source Project0c908882009-03-03 19:32:16 -08003624 }
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003625 String formattedDate = DateFormat.getDateFormat(this).format(certificateDate);
3626 if (formattedDate == null) {
3627 return "";
3628 }
3629 return formattedDate;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003630 }
3631
3632 /**
3633 * Displays an http-authentication dialog.
3634 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003635 void showHttpAuthentication(final HttpAuthHandler handler,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003636 final String host, final String realm, final String title,
3637 final String name, final String password, int focusId) {
3638 LayoutInflater factory = LayoutInflater.from(this);
3639 final View v = factory
3640 .inflate(R.layout.http_authentication, null);
3641 if (name != null) {
3642 ((EditText) v.findViewById(R.id.username_edit)).setText(name);
3643 }
3644 if (password != null) {
3645 ((EditText) v.findViewById(R.id.password_edit)).setText(password);
3646 }
3647
3648 String titleText = title;
3649 if (titleText == null) {
3650 titleText = getText(R.string.sign_in_to).toString().replace(
3651 "%s1", host).replace("%s2", realm);
3652 }
3653
3654 mHttpAuthHandler = handler;
3655 AlertDialog dialog = new AlertDialog.Builder(this)
3656 .setTitle(titleText)
3657 .setIcon(android.R.drawable.ic_dialog_alert)
3658 .setView(v)
3659 .setPositiveButton(R.string.action,
3660 new DialogInterface.OnClickListener() {
3661 public void onClick(DialogInterface dialog,
3662 int whichButton) {
3663 String nm = ((EditText) v
3664 .findViewById(R.id.username_edit))
3665 .getText().toString();
3666 String pw = ((EditText) v
3667 .findViewById(R.id.password_edit))
3668 .getText().toString();
3669 BrowserActivity.this.setHttpAuthUsernamePassword
3670 (host, realm, nm, pw);
3671 handler.proceed(nm, pw);
3672 mHttpAuthenticationDialog = null;
3673 mHttpAuthHandler = null;
3674 }})
3675 .setNegativeButton(R.string.cancel,
3676 new DialogInterface.OnClickListener() {
3677 public void onClick(DialogInterface dialog,
3678 int whichButton) {
3679 handler.cancel();
3680 BrowserActivity.this.resetTitleAndRevertLockIcon();
3681 mHttpAuthenticationDialog = null;
3682 mHttpAuthHandler = null;
3683 }})
3684 .setOnCancelListener(new DialogInterface.OnCancelListener() {
3685 public void onCancel(DialogInterface dialog) {
3686 handler.cancel();
3687 BrowserActivity.this.resetTitleAndRevertLockIcon();
3688 mHttpAuthenticationDialog = null;
3689 mHttpAuthHandler = null;
3690 }})
3691 .create();
3692 // Make the IME appear when the dialog is displayed if applicable.
3693 dialog.getWindow().setSoftInputMode(
3694 WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
3695 dialog.show();
3696 if (focusId != 0) {
3697 dialog.findViewById(focusId).requestFocus();
3698 } else {
3699 v.findViewById(R.id.username_edit).requestFocus();
3700 }
3701 mHttpAuthenticationDialog = dialog;
3702 }
3703
3704 public int getProgress() {
3705 WebView w = mTabControl.getCurrentWebView();
3706 if (w != null) {
3707 return w.getProgress();
3708 } else {
3709 return 100;
3710 }
3711 }
3712
3713 /**
3714 * Set HTTP authentication password.
3715 *
3716 * @param host The host for the password
3717 * @param realm The realm for the password
3718 * @param username The username for the password. If it is null, it means
3719 * password can't be saved.
3720 * @param password The password
3721 */
3722 public void setHttpAuthUsernamePassword(String host, String realm,
3723 String username,
3724 String password) {
Steve Block95a53b22010-03-25 17:24:58 +00003725 WebView w = getTopWindow();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003726 if (w != null) {
3727 w.setHttpAuthUsernamePassword(host, realm, username, password);
3728 }
3729 }
3730
3731 /**
3732 * connectivity manager says net has come or gone... inform the user
3733 * @param up true if net has come up, false if net has gone down
3734 */
3735 public void onNetworkToggle(boolean up) {
3736 if (up == mIsNetworkUp) {
3737 return;
3738 } else if (up) {
3739 mIsNetworkUp = true;
3740 if (mAlertDialog != null) {
3741 mAlertDialog.cancel();
3742 mAlertDialog = null;
3743 }
3744 } else {
3745 mIsNetworkUp = false;
Patrick Scotteb6ab2a2009-09-16 10:00:17 -04003746 if (mInLoad) {
3747 createAndShowNetworkDialog();
3748 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003749 }
3750 WebView w = mTabControl.getCurrentWebView();
3751 if (w != null) {
3752 w.setNetworkAvailable(up);
3753 }
3754 }
3755
Grace Kloba22ac16e2009-10-07 18:00:23 -07003756 boolean isNetworkUp() {
3757 return mIsNetworkUp;
3758 }
3759
Patrick Scotteb6ab2a2009-09-16 10:00:17 -04003760 // This method shows the network dialog alerting the user that the net is
3761 // down. It will only show the dialog if mAlertDialog is null.
3762 private void createAndShowNetworkDialog() {
3763 if (mAlertDialog == null) {
3764 mAlertDialog = new AlertDialog.Builder(this)
3765 .setTitle(R.string.loadSuspendedTitle)
3766 .setMessage(R.string.loadSuspended)
3767 .setPositiveButton(R.string.ok, null)
3768 .show();
3769 }
3770 }
3771
The Android Open Source Project0c908882009-03-03 19:32:16 -08003772 @Override
3773 protected void onActivityResult(int requestCode, int resultCode,
3774 Intent intent) {
Grace Klobabb394f32009-11-19 10:26:37 -08003775 if (getTopWindow() == null) return;
3776
The Android Open Source Project0c908882009-03-03 19:32:16 -08003777 switch (requestCode) {
3778 case COMBO_PAGE:
3779 if (resultCode == RESULT_OK && intent != null) {
3780 String data = intent.getAction();
3781 Bundle extras = intent.getExtras();
Michael Kolb300b7f02010-08-25 13:47:24 -07003782 if (extras != null &&
3783 extras.getBoolean(
3784 CombinedBookmarkHistoryActivity.EXTRA_OPEN_NEW_WINDOW,
3785 false)) {
Michael Kolb68792c82010-08-09 16:39:18 -07003786 openTab(data, false);
3787 } else if ((extras != null) &&
3788 extras.getBoolean(CombinedBookmarkHistoryActivity.NEWTAB_MODE)) {
3789 openTab(data, true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003790 } else {
Michael Kolb68792c82010-08-09 16:39:18 -07003791 final Tab currentTab = mTabControl.getCurrentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04003792 dismissSubWindow(currentTab);
3793 if (data != null && data.length() != 0) {
Leon Scroggins92472e82010-02-17 16:32:28 -05003794 loadUrl(getTopWindow(), data);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003795 }
3796 }
Michael Kolb3f65c382010-08-20 15:31:16 -07003797 } else if (resultCode == RESULT_CANCELED) {
3798 if (intent != null) {
3799 float evtx = intent.getFloatExtra(CombinedBookmarkHistoryActivity.EVT_X, -1);
3800 float evty = intent.getFloatExtra(CombinedBookmarkHistoryActivity.EVT_Y, -1);
3801 long now = System.currentTimeMillis();
3802 MotionEvent evt = MotionEvent.obtain(now, now,
3803 MotionEvent.ACTION_DOWN, evtx, evty, 0);
3804 dispatchTouchEvent(evt);
3805 MotionEvent up = MotionEvent.obtain(evt);
3806 up.setAction(MotionEvent.ACTION_UP);
3807 dispatchTouchEvent(up);
3808 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003809 }
Leon Scrogginsfde97462010-01-11 13:06:21 -05003810 // Deliberately fall through to PREFERENCES_PAGE, since the
3811 // same extra may be attached to the COMBO_PAGE
3812 case PREFERENCES_PAGE:
3813 if (resultCode == RESULT_OK && intent != null) {
3814 String action = intent.getStringExtra(Intent.EXTRA_TEXT);
3815 if (BrowserSettings.PREF_CLEAR_HISTORY.equals(action)) {
3816 mTabControl.removeParentChildRelationShips();
3817 }
3818 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003819 break;
Leon Scroggins8d5fa432009-10-02 15:55:59 -04003820 // Choose a file from the file picker.
3821 case FILE_SELECTED:
3822 if (null == mUploadMessage) break;
3823 Uri result = intent == null || resultCode != RESULT_OK ? null
3824 : intent.getData();
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003825
3826 // As we ask the camera to save the result of the user taking
3827 // a picture, the camera application does not return anything other
3828 // than RESULT_OK. So we need to check whether the file we expected
3829 // was written to disk in the in the case that we
3830 // did not get an intent returned but did get a RESULT_OK. If it was,
3831 // we assume that this result has came back from the camera.
3832 if (result == null && intent == null && resultCode == RESULT_OK) {
3833 File cameraFile = new File(mCameraFilePath);
3834 if (cameraFile.exists()) {
3835 result = Uri.fromFile(cameraFile);
Ben Murdoch07d34732010-05-27 18:34:46 +01003836 // Broadcast to the media scanner that we have a new photo
3837 // so it will be added into the gallery for the user.
3838 sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, result));
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003839 }
3840 }
Leon Scroggins8d5fa432009-10-02 15:55:59 -04003841 mUploadMessage.onReceiveValue(result);
3842 mUploadMessage = null;
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003843 mCameraFilePath = null;
Leon Scroggins8d5fa432009-10-02 15:55:59 -04003844 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003845 default:
3846 break;
3847 }
Leon Scroggins30444232009-09-04 18:36:20 -04003848 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003849 }
3850
3851 /*
3852 * This method is called as a result of the user selecting the options
Leon Scrogginsf08809b2010-01-21 09:27:46 -05003853 * menu to see the download window. It shows the download window on top of
3854 * the current window.
The Android Open Source Project0c908882009-03-03 19:32:16 -08003855 */
Leon Scrogginsf08809b2010-01-21 09:27:46 -05003856 private void viewDownloads(Uri downloadRecord) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003857 Intent intent = new Intent(this,
3858 BrowserDownloadPage.class);
3859 intent.setData(downloadRecord);
Grace Kloba22ac16e2009-10-07 18:00:23 -07003860 startActivityForResult(intent, BrowserActivity.DOWNLOAD_PAGE);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003861
3862 }
3863
Michael Kolbc7485ae2010-09-03 10:10:58 -07003864 /* package */ void promptAddOrInstallBookmark(View anchor) {
3865 PopupMenu popup = new PopupMenu(this, anchor);
3866 popup.getMenuInflater().inflate(R.menu.bookmark_shortcut, popup.getMenu());
3867 popup.setOnMenuItemClickListener(this);
3868 popup.show();
3869 }
3870
3871 /**
3872 * popup menu item click listener
3873 * @param item
3874 */
3875 public boolean onMenuItemClick(MenuItem item) {
3876 switch(item.getItemId()) {
3877 case R.id.add_bookmark_menu_id:
3878 bookmarkCurrentPage();
3879 return true;
3880 case R.id.shortcut_to_home_menu_id:
3881 Tab current = mTabControl.getCurrentTab();
3882 current.populatePickerData();
3883 String touchIconUrl = mTabControl.getCurrentWebView().getTouchIconUrl();
3884 if (touchIconUrl != null) {
3885 // Download the touch icon for this site then save
3886 // it to the
3887 // homescreen.
3888 Bundle b = new Bundle();
3889 b.putString("url", current.getUrl());
3890 b.putString("title", current.getTitle());
3891 b.putParcelable("favicon", current.getFavicon());
3892 Message msg = mHandler.obtainMessage(TOUCH_ICON_DOWNLOADED);
3893 msg.setData(b);
3894 new DownloadTouchIcon(BrowserActivity.this, msg,
3895 mTabControl.getCurrentWebView().getSettings().getUserAgentString())
3896 .execute(touchIconUrl);
3897 } else {
3898 // add to homescreen, can do it immediately as there
3899 // is no touch
3900 // icon.
3901 showSaveToHomescreenDialog(
3902 current.getUrl(), current.getTitle(), null, current.getFavicon());
3903 }
3904 return true;
3905 default:
3906 return false;
3907 }
3908 }
3909
3910 /* package */Dialog makeAddOrInstallDialog() {
Ben Murdocheecb4e62010-07-06 16:30:38 +01003911 final Tab current = mTabControl.getCurrentTab();
3912 Resources resources = getResources();
Michael Kolbc7485ae2010-09-03 10:10:58 -07003913 CharSequence[] choices =
3914 {resources.getString(R.string.save_to_bookmarks),
3915 resources.getString(R.string.create_shortcut_bookmark)};
Ben Murdocheecb4e62010-07-06 16:30:38 +01003916
3917 AlertDialog.Builder builder = new AlertDialog.Builder(this);
3918 builder.setTitle(R.string.add_new_bookmark);
3919 builder.setItems(choices, new DialogInterface.OnClickListener() {
Michael Kolbc7485ae2010-09-03 10:10:58 -07003920 public void onClick(DialogInterface dialog, int item) {
3921 if (item == 0) {
3922 bookmarkCurrentPage();
3923 } else if (item == 1) {
3924 }
3925 }
Ben Murdocheecb4e62010-07-06 16:30:38 +01003926 });
Michael Kolbc7485ae2010-09-03 10:10:58 -07003927 return builder.create();
Ben Murdocheecb4e62010-07-06 16:30:38 +01003928 }
3929
Leon Scroggins160a7e72009-08-14 18:28:01 -04003930 /**
3931 * Open the Go page.
3932 * @param startWithHistory If true, open starting on the history tab.
3933 * Otherwise, start with the bookmarks tab.
Leon Scroggins160a7e72009-08-14 18:28:01 -04003934 */
Michael Kolb68792c82010-08-09 16:39:18 -07003935 /* package */ void bookmarksOrHistoryPicker(boolean startWithHistory, boolean newTabMode) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003936 WebView current = mTabControl.getCurrentWebView();
3937 if (current == null) {
3938 return;
3939 }
3940 Intent intent = new Intent(this,
3941 CombinedBookmarkHistoryActivity.class);
3942 String title = current.getTitle();
3943 String url = current.getUrl();
Ben Murdoch87cc65d2010-06-29 20:34:10 +01003944 Bitmap thumbnail = createScreenshot(current, getDesiredThumbnailWidth(this),
3945 getDesiredThumbnailHeight(this));
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01003946
The Android Open Source Project0c908882009-03-03 19:32:16 -08003947 // Just in case the user opens bookmarks before a page finishes loading
3948 // so the current history item, and therefore the page, is null.
3949 if (null == url) {
3950 url = mLastEnteredUrl;
3951 // This can happen.
3952 if (null == url) {
3953 url = mSettings.getHomePage();
3954 }
3955 }
3956 // In case the web page has not yet received its associated title.
3957 if (title == null) {
3958 title = url;
3959 }
3960 intent.putExtra("title", title);
3961 intent.putExtra("url", url);
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01003962 intent.putExtra("thumbnail", thumbnail);
Leon Scroggins30444232009-09-04 18:36:20 -04003963 // Disable opening in a new window if we have maxed out the windows
Grace Kloba22ac16e2009-10-07 18:00:23 -07003964 intent.putExtra("disable_new_window", !mTabControl.canCreateNewTab());
Patrick Scott3918d442009-08-04 13:22:29 -04003965 intent.putExtra("touch_icon_url", current.getTouchIconUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003966 if (startWithHistory) {
Jeff Hamilton64144e42010-08-18 16:31:59 -05003967 intent.putExtra(CombinedBookmarkHistoryActivity.STARTING_FRAGMENT,
3968 CombinedBookmarkHistoryActivity.FRAGMENT_ID_HISTORY);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003969 }
Michael Kolb300b7f02010-08-25 13:47:24 -07003970 intent.putExtra(CombinedBookmarkHistoryActivity.NEWTAB_MODE, newTabMode);
Michael Kolb0998b0a2010-08-23 17:45:35 -07003971 int top = -1;
3972 int height = -1;
Michael Kolb3f65c382010-08-20 15:31:16 -07003973 if (mXLargeScreenSize) {
3974 showFakeTitleBar();
3975 int titleBarHeight = ((TitleBarXLarge)mFakeTitleBar).getHeightWithoutProgress();
Michael Kolb0998b0a2010-08-23 17:45:35 -07003976 top = mTabBar.getBottom() + titleBarHeight;
3977 height = getTopWindow().getHeight() - titleBarHeight;
Michael Kolb68792c82010-08-09 16:39:18 -07003978 }
Michael Kolb0998b0a2010-08-23 17:45:35 -07003979 intent.putExtra(CombinedBookmarkHistoryActivity.EXTRA_TOP, top);
3980 intent.putExtra(CombinedBookmarkHistoryActivity.EXTRA_HEIGHT, height);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003981 startActivityForResult(intent, COMBO_PAGE);
3982 }
3983
Ben Murdocheecb4e62010-07-06 16:30:38 +01003984 private void showSaveToHomescreenDialog(String url, String title, Bitmap touchIcon,
3985 Bitmap favicon) {
3986 Intent intent = new Intent(this, SaveToHomescreenDialog.class);
3987
3988 // Just in case the user tries to save before a page finishes loading
3989 // so the current history item, and therefore the page, is null.
3990 if (null == url) {
3991 url = mLastEnteredUrl;
3992 // This can happen.
3993 if (null == url) {
3994 url = mSettings.getHomePage();
3995 }
3996 }
3997
3998 // In case the web page has not yet received its associated title.
3999 if (title == null) {
4000 title = url;
4001 }
4002
4003 intent.putExtra("title", title);
4004 intent.putExtra("url", url);
4005 intent.putExtra("favicon", favicon);
4006 intent.putExtra("touchIcon", touchIcon);
4007 startActivity(intent);
4008 }
4009
4010
The Android Open Source Project0c908882009-03-03 19:32:16 -08004011 // Called when loading from context menu or LOAD_URL message
Leon Scroggins92472e82010-02-17 16:32:28 -05004012 private void loadUrlFromContext(WebView view, String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08004013 // In case the user enters nothing.
4014 if (url != null && url.length() != 0 && view != null) {
4015 url = smartUrlFilter(url);
Grace Kloba22ac16e2009-10-07 18:00:23 -07004016 if (!view.getWebViewClient().shouldOverrideUrlLoading(view, url)) {
Leon Scroggins92472e82010-02-17 16:32:28 -05004017 loadUrl(view, url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004018 }
4019 }
4020 }
4021
Leon Scroggins92472e82010-02-17 16:32:28 -05004022 /**
4023 * Load the URL into the given WebView and update the title bar
4024 * to reflect the new load. Call this instead of WebView.loadUrl
4025 * directly.
4026 * @param view The WebView used to load url.
4027 * @param url The URL to load.
4028 */
4029 private void loadUrl(WebView view, String url) {
4030 updateTitleBarForNewLoad(view, url);
4031 view.loadUrl(url);
4032 }
4033
4034 /**
4035 * Load UrlData into a Tab and update the title bar to reflect the new
4036 * load. Call this instead of UrlData.loadIn directly.
4037 * @param t The Tab used to load.
4038 * @param data The UrlData being loaded.
4039 */
4040 private void loadUrlDataIn(Tab t, UrlData data) {
4041 updateTitleBarForNewLoad(t.getWebView(), data.mUrl);
4042 data.loadIn(t);
4043 }
4044
4045 /**
4046 * If the WebView is the top window, update the title bar to reflect
4047 * loading the new URL. i.e. set its text, clear the favicon (which
4048 * will be set once the page begins loading), and set the progress to
4049 * INITIAL_PROGRESS to show that the page has begun to load. Called
4050 * by loadUrl and loadUrlDataIn.
4051 * @param view The WebView that is starting a load.
4052 * @param url The URL that is being loaded.
4053 */
4054 private void updateTitleBarForNewLoad(WebView view, String url) {
4055 if (view == getTopWindow()) {
4056 setUrlTitle(url, null);
4057 setFavicon(null);
4058 onProgressChanged(view, INITIAL_PROGRESS);
4059 }
4060 }
4061
The Android Open Source Project0c908882009-03-03 19:32:16 -08004062 private String smartUrlFilter(Uri inUri) {
4063 if (inUri != null) {
4064 return smartUrlFilter(inUri.toString());
4065 }
4066 return null;
4067 }
4068
Feng Qianb34f87a2009-03-24 21:27:26 -07004069 protected static final Pattern ACCEPTED_URI_SCHEMA = Pattern.compile(
The Android Open Source Project0c908882009-03-03 19:32:16 -08004070 "(?i)" + // switch on case insensitive matching
4071 "(" + // begin group for schema
4072 "(?:http|https|file):\\/\\/" +
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004073 "|(?:inline|data|about|content|javascript):" +
The Android Open Source Project0c908882009-03-03 19:32:16 -08004074 ")" +
4075 "(.*)" );
4076
4077 /**
4078 * Attempts to determine whether user input is a URL or search
4079 * terms. Anything with a space is passed to search.
4080 *
4081 * Converts to lowercase any mistakenly uppercased schema (i.e.,
4082 * "Http://" converts to "http://"
4083 *
4084 * @return Original or modified URL
4085 *
4086 */
4087 String smartUrlFilter(String url) {
4088
4089 String inUrl = url.trim();
4090 boolean hasSpace = inUrl.indexOf(' ') != -1;
4091
4092 Matcher matcher = ACCEPTED_URI_SCHEMA.matcher(inUrl);
4093 if (matcher.matches()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08004094 // force scheme to lowercase
4095 String scheme = matcher.group(1);
4096 String lcScheme = scheme.toLowerCase();
4097 if (!lcScheme.equals(scheme)) {
Mitsuru Oshima123ecfb2009-05-18 19:11:14 -07004098 inUrl = lcScheme + matcher.group(2);
4099 }
4100 if (hasSpace) {
4101 inUrl = inUrl.replace(" ", "%20");
The Android Open Source Project0c908882009-03-03 19:32:16 -08004102 }
4103 return inUrl;
4104 }
4105 if (hasSpace) {
Satish Sampath565505b2009-05-29 15:37:27 +01004106 // FIXME: Is this the correct place to add to searches?
4107 // what if someone else calls this function?
4108 int shortcut = parseUrlShortcut(inUrl);
4109 if (shortcut != SHORTCUT_INVALID) {
4110 Browser.addSearchUrl(mResolver, inUrl);
4111 String query = inUrl.substring(2);
4112 switch (shortcut) {
4113 case SHORTCUT_GOOGLE_SEARCH:
Grace Kloba47fdfdb2009-06-30 11:15:34 -07004114 return URLUtil.composeSearchUrl(query, QuickSearch_G, QUERY_PLACE_HOLDER);
Satish Sampath565505b2009-05-29 15:37:27 +01004115 case SHORTCUT_WIKIPEDIA_SEARCH:
4116 return URLUtil.composeSearchUrl(query, QuickSearch_W, QUERY_PLACE_HOLDER);
4117 case SHORTCUT_DICTIONARY_SEARCH:
4118 return URLUtil.composeSearchUrl(query, QuickSearch_D, QUERY_PLACE_HOLDER);
4119 case SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH:
The Android Open Source Project0c908882009-03-03 19:32:16 -08004120 // FIXME: we need location in this case
Satish Sampath565505b2009-05-29 15:37:27 +01004121 return URLUtil.composeSearchUrl(query, QuickSearch_L, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004122 }
4123 }
4124 } else {
Dan Egnor5ee906c2009-11-18 12:11:49 -08004125 if (Patterns.WEB_URL.matcher(inUrl).matches()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08004126 return URLUtil.guessUrl(inUrl);
4127 }
4128 }
4129
4130 Browser.addSearchUrl(mResolver, inUrl);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07004131 return URLUtil.composeSearchUrl(inUrl, QuickSearch_G, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004132 }
4133
Ben Murdochbff2d602009-07-01 20:19:05 +01004134 /* package */ void setShouldShowErrorConsole(boolean flag) {
4135 if (flag == mShouldShowErrorConsole) {
4136 // Nothing to do.
4137 return;
4138 }
4139
4140 mShouldShowErrorConsole = flag;
4141
Grace Kloba22ac16e2009-10-07 18:00:23 -07004142 ErrorConsoleView errorConsole = mTabControl.getCurrentTab()
4143 .getErrorConsole(true);
Ben Murdochbff2d602009-07-01 20:19:05 +01004144
4145 if (flag) {
4146 // Setting the show state of the console will cause it's the layout to be inflated.
4147 if (errorConsole.numberOfErrors() > 0) {
4148 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
4149 } else {
4150 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
4151 }
4152
4153 // Now we can add it to the main view.
4154 mErrorConsoleContainer.addView(errorConsole,
Romain Guy15b8ec62010-01-08 15:06:43 -08004155 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
Ben Murdochbff2d602009-07-01 20:19:05 +01004156 ViewGroup.LayoutParams.WRAP_CONTENT));
4157 } else {
4158 mErrorConsoleContainer.removeView(errorConsole);
4159 }
4160
4161 }
4162
Grace Kloba22ac16e2009-10-07 18:00:23 -07004163 boolean shouldShowErrorConsole() {
4164 return mShouldShowErrorConsole;
4165 }
4166
Andrei Popescu163ab742009-10-20 17:58:23 +01004167 private void setStatusBarVisibility(boolean visible) {
4168 int flag = visible ? 0 : WindowManager.LayoutParams.FLAG_FULLSCREEN;
4169 getWindow().setFlags(flag, WindowManager.LayoutParams.FLAG_FULLSCREEN);
4170 }
4171
Andrei Popescu56199cc2010-01-12 22:39:16 +00004172
4173 private void sendNetworkType(String type, String subtype) {
4174 WebView w = mTabControl.getCurrentWebView();
4175 if (w != null) {
4176 w.setNetworkType(type, subtype);
4177 }
4178 }
4179
Grace Klobaeb6eef42009-09-15 17:56:32 -07004180 final static int LOCK_ICON_UNSECURE = 0;
4181 final static int LOCK_ICON_SECURE = 1;
4182 final static int LOCK_ICON_MIXED = 2;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004183
The Android Open Source Project0c908882009-03-03 19:32:16 -08004184 private BrowserSettings mSettings;
4185 private TabControl mTabControl;
4186 private ContentResolver mResolver;
4187 private FrameLayout mContentView;
Andrei Popescuadc008d2009-06-26 14:11:30 +01004188 private View mCustomView;
4189 private FrameLayout mCustomViewContainer;
Andrei Popescuc9b55562009-07-07 10:51:15 +01004190 private WebChromeClient.CustomViewCallback mCustomViewCallback;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004191
4192 // FIXME, temp address onPrepareMenu performance problem. When we move everything out of
4193 // view, we should rewrite this.
4194 private int mCurrentMenuState = 0;
4195 private int mMenuState = R.id.MAIN_MENU;
Andrei Popescuadc008d2009-06-26 14:11:30 +01004196 private int mOldMenuState = EMPTY_MENU;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004197 private static final int EMPTY_MENU = -1;
4198 private Menu mMenu;
4199
The Android Open Source Project0c908882009-03-03 19:32:16 -08004200 // Used to prevent chording to result in firing two shortcuts immediately
4201 // one after another. Fixes bug 1211714.
4202 boolean mCanChord;
4203
4204 private boolean mInLoad;
4205 private boolean mIsNetworkUp;
Ben Murdochb7cc8b42009-09-28 10:59:09 +01004206 private boolean mDidStopLoad;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004207
Cary Clark1f10cbf2010-03-22 11:45:23 -04004208 /* package */ boolean mActivityInPause = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004209
4210 private boolean mMenuIsDown;
4211
The Android Open Source Project0c908882009-03-03 19:32:16 -08004212 private static boolean mInTrace;
4213
4214 // Performance probe
4215 private static final int[] SYSTEM_CPU_FORMAT = new int[] {
4216 Process.PROC_SPACE_TERM | Process.PROC_COMBINE,
4217 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 1: user time
4218 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 2: nice time
4219 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 3: sys time
4220 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 4: idle time
4221 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 5: iowait time
4222 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 6: irq time
4223 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG // 7: softirq time
4224 };
4225
4226 private long mStart;
4227 private long mProcessStart;
4228 private long mUserStart;
4229 private long mSystemStart;
4230 private long mIdleStart;
4231 private long mIrqStart;
4232
4233 private long mUiStart;
4234
4235 private Drawable mMixLockIcon;
4236 private Drawable mSecLockIcon;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004237
4238 /* hold a ref so we can auto-cancel if necessary */
4239 private AlertDialog mAlertDialog;
4240
The Android Open Source Project0c908882009-03-03 19:32:16 -08004241 // The up-to-date URL and title (these can be different from those stored
4242 // in WebView, since it takes some time for the information in WebView to
4243 // get updated)
4244 private String mUrl;
4245 private String mTitle;
4246
4247 // As PageInfo has different style for landscape / portrait, we have
4248 // to re-open it when configuration changed
4249 private AlertDialog mPageInfoDialog;
Grace Kloba22ac16e2009-10-07 18:00:23 -07004250 private Tab mPageInfoView;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004251 // If the Page-Info dialog is launched from the SSL-certificate-on-error
4252 // dialog, we should not just dismiss it, but should get back to the
4253 // SSL-certificate-on-error dialog. This flag is used to store this state
Leon Scrogginsc7b92f82010-01-11 18:17:31 -05004254 private boolean mPageInfoFromShowSSLCertificateOnError;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004255
4256 // as SSLCertificateOnError has different style for landscape / portrait,
4257 // we have to re-open it when configuration changed
4258 private AlertDialog mSSLCertificateOnErrorDialog;
4259 private WebView mSSLCertificateOnErrorView;
4260 private SslErrorHandler mSSLCertificateOnErrorHandler;
4261 private SslError mSSLCertificateOnErrorError;
4262
4263 // as SSLCertificate has different style for landscape / portrait, we
4264 // have to re-open it when configuration changed
4265 private AlertDialog mSSLCertificateDialog;
Grace Kloba22ac16e2009-10-07 18:00:23 -07004266 private Tab mSSLCertificateView;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004267
4268 // as HttpAuthentication has different style for landscape / portrait, we
4269 // have to re-open it when configuration changed
4270 private AlertDialog mHttpAuthenticationDialog;
4271 private HttpAuthHandler mHttpAuthHandler;
4272
4273 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_PARAMS =
4274 new FrameLayout.LayoutParams(
Romain Guy15b8ec62010-01-08 15:06:43 -08004275 ViewGroup.LayoutParams.MATCH_PARENT,
4276 ViewGroup.LayoutParams.MATCH_PARENT);
Andrei Popescuadc008d2009-06-26 14:11:30 +01004277 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_GRAVITY_CENTER =
4278 new FrameLayout.LayoutParams(
Romain Guy15b8ec62010-01-08 15:06:43 -08004279 ViewGroup.LayoutParams.MATCH_PARENT,
4280 ViewGroup.LayoutParams.MATCH_PARENT,
Andrei Popescuadc008d2009-06-26 14:11:30 +01004281 Gravity.CENTER);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07004282 // Google search
4283 final static String QuickSearch_G = "http://www.google.com/m?q=%s";
The Android Open Source Project0c908882009-03-03 19:32:16 -08004284 // Wikipedia search
4285 final static String QuickSearch_W = "http://en.wikipedia.org/w/index.php?search=%s&go=Go";
4286 // Dictionary search
4287 final static String QuickSearch_D = "http://dictionary.reference.com/search?q=%s";
4288 // Google Mobile Local search
4289 final static String QuickSearch_L = "http://www.google.com/m/search?site=local&q=%s&near=mountain+view";
4290
4291 final static String QUERY_PLACE_HOLDER = "%s";
4292
4293 // "source" parameter for Google search through search key
4294 final static String GOOGLE_SEARCH_SOURCE_SEARCHKEY = "browser-key";
4295 // "source" parameter for Google search through goto menu
4296 final static String GOOGLE_SEARCH_SOURCE_GOTO = "browser-goto";
4297 // "source" parameter for Google search through simplily type
4298 final static String GOOGLE_SEARCH_SOURCE_TYPE = "browser-type";
4299 // "source" parameter for Google search suggested by the browser
4300 final static String GOOGLE_SEARCH_SOURCE_SUGGEST = "browser-suggest";
4301 // "source" parameter for Google search from unknown source
4302 final static String GOOGLE_SEARCH_SOURCE_UNKNOWN = "unknown";
4303
4304 private final static String LOGTAG = "browser";
4305
The Android Open Source Project0c908882009-03-03 19:32:16 -08004306 private String mLastEnteredUrl;
4307
4308 private PowerManager.WakeLock mWakeLock;
4309 private final static int WAKELOCK_TIMEOUT = 5 * 60 * 1000; // 5 minutes
4310
4311 private Toast mStopToast;
4312
Leon Scroggins571b3762010-05-26 10:25:01 -04004313 private TitleBarBase mTitleBar;
Michael Kolba2b2ba82010-08-04 17:54:03 -07004314 private TabBar mTabBar;
Leon Scroggins81db3662009-06-04 17:45:11 -04004315
Ben Murdochbff2d602009-07-01 20:19:05 +01004316 private LinearLayout mErrorConsoleContainer = null;
4317 private boolean mShouldShowErrorConsole = false;
4318
The Android Open Source Project0c908882009-03-03 19:32:16 -08004319 // As the ids are dynamically created, we can't guarantee that they will
4320 // be in sequence, so this static array maps ids to a window number.
4321 final static private int[] WINDOW_SHORTCUT_ID_ARRAY =
4322 { R.id.window_one_menu_id, R.id.window_two_menu_id, R.id.window_three_menu_id,
4323 R.id.window_four_menu_id, R.id.window_five_menu_id, R.id.window_six_menu_id,
4324 R.id.window_seven_menu_id, R.id.window_eight_menu_id };
4325
4326 // monitor platform changes
4327 private IntentFilter mNetworkStateChangedFilter;
4328 private BroadcastReceiver mNetworkStateIntentReceiver;
4329
Bjorn Bringerta7611812010-03-24 11:12:02 +00004330 private SystemAllowGeolocationOrigins mSystemAllowGeolocationOrigins;
4331
The Android Open Source Project0c908882009-03-03 19:32:16 -08004332 // activity requestCode
Nicolas Roard78a98e42009-05-11 13:34:17 +01004333 final static int COMBO_PAGE = 1;
4334 final static int DOWNLOAD_PAGE = 2;
4335 final static int PREFERENCES_PAGE = 3;
Leon Scroggins8d5fa432009-10-02 15:55:59 -04004336 final static int FILE_SELECTED = 4;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004337
Andrei Popescu540035d2009-09-18 18:59:20 +01004338 // the default <video> poster
4339 private Bitmap mDefaultVideoPoster;
4340 // the video progress view
4341 private View mVideoProgressView;
4342
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004343 /**
4344 * A UrlData class to abstract how the content will be set to WebView.
4345 * This base class uses loadUrl to show the content.
4346 */
Leon Scroggins6eac63e2010-03-15 18:19:14 -04004347 /* package */ static class UrlData {
Grace Kloba068e48b2010-01-26 18:11:27 -08004348 final String mUrl;
4349 final Map<String, String> mHeaders;
Leon Scroggins58d56c62010-01-28 15:12:40 -05004350 final Intent mVoiceIntent;
Grace Kloba60e095c2009-06-16 11:50:55 -07004351
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004352 UrlData(String url) {
4353 this.mUrl = url;
Grace Kloba068e48b2010-01-26 18:11:27 -08004354 this.mHeaders = null;
Leon Scroggins58d56c62010-01-28 15:12:40 -05004355 this.mVoiceIntent = null;
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004356 }
Grace Kloba60e095c2009-06-16 11:50:55 -07004357
Leon Scroggins58d56c62010-01-28 15:12:40 -05004358 UrlData(String url, Map<String, String> headers, Intent intent) {
Grace Kloba068e48b2010-01-26 18:11:27 -08004359 this.mUrl = url;
4360 this.mHeaders = headers;
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -05004361 if (RecognizerResultsIntent.ACTION_VOICE_SEARCH_RESULTS
4362 .equals(intent.getAction())) {
Leon Scroggins58d56c62010-01-28 15:12:40 -05004363 this.mVoiceIntent = intent;
4364 } else {
4365 this.mVoiceIntent = null;
4366 }
Grace Kloba60e095c2009-06-16 11:50:55 -07004367 }
4368
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004369 boolean isEmpty() {
Leon Scroggins58d56c62010-01-28 15:12:40 -05004370 return mVoiceIntent == null && (mUrl == null || mUrl.length() == 0);
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004371 }
4372
Leon Scroggins92472e82010-02-17 16:32:28 -05004373 /**
4374 * Load this UrlData into the given Tab. Use loadUrlDataIn to update
4375 * the title bar as well.
4376 */
Leon Scroggins58d56c62010-01-28 15:12:40 -05004377 public void loadIn(Tab t) {
4378 if (mVoiceIntent != null) {
4379 t.activateVoiceSearchMode(mVoiceIntent);
4380 } else {
4381 t.getWebView().loadUrl(mUrl, mHeaders);
4382 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004383 }
4384 };
4385
Leon Scroggins1f005d32009-08-10 17:36:42 -04004386 /* package */ static final UrlData EMPTY_URL_DATA = new UrlData(null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004387}