blob: 10ebb56230ad828f5a63590d3394c416bd3649a1 [file] [log] [blame]
The Android Open Source Project0c908882009-03-03 19:32:16 -08001/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.browser;
18
Michael Kolb3f65c382010-08-20 15:31:16 -070019import com.android.browser.ScrollWebView.ScrollListener;
Bjorn Bringertd69f51d2010-09-13 14:06:41 +010020import com.android.browser.search.SearchEngine;
Michael Kolb3f65c382010-08-20 15:31:16 -070021import com.android.common.Search;
22import com.android.common.speech.LoggingEvents;
23
Michael Kolbed217742010-08-10 17:52:34 -070024import android.app.ActionBar;
The Android Open Source Project0c908882009-03-03 19:32:16 -080025import android.app.Activity;
The Android Open Source Project0c908882009-03-03 19:32:16 -080026import android.app.AlertDialog;
Michael Kolbc7485ae2010-09-03 10:10:58 -070027import android.app.Dialog;
Steve Howard5a862fc2010-09-28 12:52:06 -070028import android.app.DownloadManager;
The Android Open Source Project0c908882009-03-03 19:32:16 -080029import android.app.ProgressDialog;
30import android.app.SearchManager;
31import android.content.ActivityNotFoundException;
32import android.content.BroadcastReceiver;
Dianne Hackborn80f32622010-08-05 14:17:53 -070033import android.content.ClipboardManager;
The Android Open Source Project0c908882009-03-03 19:32:16 -080034import android.content.ComponentName;
Leon Scroggins58d56c62010-01-28 15:12:40 -050035import android.content.ContentProvider;
36import android.content.ContentProviderClient;
The Android Open Source Project0c908882009-03-03 19:32:16 -080037import android.content.ContentResolver;
38import android.content.ContentValues;
39import android.content.Context;
40import android.content.DialogInterface;
41import android.content.Intent;
42import android.content.IntentFilter;
The Android Open Source Project0c908882009-03-03 19:32:16 -080043import android.content.pm.PackageManager;
44import android.content.pm.ResolveInfo;
The Android Open Source Project0c908882009-03-03 19:32:16 -080045import android.content.res.Configuration;
46import android.content.res.Resources;
47import android.database.Cursor;
The Android Open Source Project0c908882009-03-03 19:32:16 -080048import android.graphics.Bitmap;
Andrei Popescu540035d2009-09-18 18:59:20 +010049import android.graphics.BitmapFactory;
The Android Open Source Project0c908882009-03-03 19:32:16 -080050import android.graphics.Canvas;
The Android Open Source Project0c908882009-03-03 19:32:16 -080051import android.graphics.Picture;
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -040052import android.graphics.PixelFormat;
The Android Open Source Project0c908882009-03-03 19:32:16 -080053import android.graphics.drawable.Drawable;
The Android Open Source Project0c908882009-03-03 19:32:16 -080054import android.net.ConnectivityManager;
Andrei Popescu56199cc2010-01-12 22:39:16 +000055import android.net.NetworkInfo;
The Android Open Source Project0c908882009-03-03 19:32:16 -080056import android.net.Uri;
57import android.net.WebAddress;
The Android Open Source Project0c908882009-03-03 19:32:16 -080058import android.net.http.SslCertificate;
59import android.net.http.SslError;
60import android.os.AsyncTask;
61import android.os.Bundle;
62import android.os.Debug;
63import android.os.Environment;
64import android.os.Handler;
The Android Open Source Project0c908882009-03-03 19:32:16 -080065import android.os.Message;
66import android.os.PowerManager;
67import android.os.Process;
The Android Open Source Project0c908882009-03-03 19:32:16 -080068import android.os.SystemClock;
The Android Open Source Project0c908882009-03-03 19:32:16 -080069import android.provider.Browser;
Jeff Hamilton1a805652010-09-07 12:36:30 -070070import android.provider.BrowserContract.Images;
Michael Kolbe421c242010-10-04 19:29:01 -070071import 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;
The Android Open Source Project0c908882009-03-03 19:32:16 -080090import android.view.View;
91import android.view.ViewGroup;
92import android.view.Window;
93import android.view.WindowManager;
Svetoslav Ganov2b345992010-05-06 06:13:54 -070094import android.view.accessibility.AccessibilityManager;
The Android Open Source Project0c908882009-03-03 19:32:16 -080095import android.webkit.CookieManager;
96import android.webkit.CookieSyncManager;
97import android.webkit.DownloadListener;
98import android.webkit.HttpAuthHandler;
99import android.webkit.SslErrorHandler;
100import android.webkit.URLUtil;
Leon Clarkecb6cc862009-09-29 18:35:13 +0100101import android.webkit.ValueCallback;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800102import android.webkit.WebChromeClient;
103import android.webkit.WebHistoryItem;
104import android.webkit.WebIconDatabase;
105import android.webkit.WebView;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800106import android.widget.EditText;
107import android.widget.FrameLayout;
108import android.widget.LinearLayout;
Michael Kolbc7485ae2010-09-03 10:10:58 -0700109import android.widget.PopupMenu;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800110import android.widget.TextView;
111import android.widget.Toast;
112
Leon Scrogginsb6b7f9e2009-06-18 12:05:28 -0400113import java.io.ByteArrayOutputStream;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800114import java.io.File;
Ben Murdoch4f75ba22009-10-27 11:48:28 +0000115import java.io.IOException;
116import java.io.InputStream;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800117import java.net.MalformedURLException;
Dianne Hackborn99189432009-06-17 18:06:18 -0700118import java.net.URISyntaxException;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800119import java.net.URL;
120import java.net.URLEncoder;
Elliott Slaughter3d6df162010-08-25 13:17:44 -0700121import java.util.Calendar;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800122import java.util.Date;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800123import java.util.HashMap;
Grace Kloba00f54c52010-01-27 14:53:51 -0800124import java.util.Iterator;
Grace Kloba068e48b2010-01-26 18:11:27 -0800125import java.util.Map;
Michael Kolbfe251992010-07-08 15:41:55 -0700126import java.util.Vector;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800127import java.util.regex.Matcher;
128import java.util.regex.Pattern;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800129
130public class BrowserActivity extends Activity
Michael Kolbe421c242010-10-04 19:29:01 -0700131 implements View.OnCreateContextMenuListener, DownloadListener,
132 PopupMenu.OnMenuItemClickListener, BookmarksHistoryCallbacks {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800133
Dave Bort31a6d1c2009-04-13 15:56:49 -0700134 /* Define some aliases to make these debugging flags easier to refer to.
135 * This file imports android.provider.Browser, so we can't just refer to "Browser.DEBUG".
136 */
137 private final static boolean DEBUG = com.android.browser.Browser.DEBUG;
138 private final static boolean LOGV_ENABLED = com.android.browser.Browser.LOGV_ENABLED;
139 private final static boolean LOGD_ENABLED = com.android.browser.Browser.LOGD_ENABLED;
140
Satish Sampath565505b2009-05-29 15:37:27 +0100141 // These are single-character shortcuts for searching popular sources.
142 private static final int SHORTCUT_INVALID = 0;
143 private static final int SHORTCUT_GOOGLE_SEARCH = 1;
144 private static final int SHORTCUT_WIKIPEDIA_SEARCH = 2;
145 private static final int SHORTCUT_DICTIONARY_SEARCH = 3;
146 private static final int SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH = 4;
147
Cary Clarka9771242009-08-11 16:42:26 -0400148 private static class ClearThumbnails extends AsyncTask<File, Void, Void> {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800149 @Override
150 public Void doInBackground(File... files) {
151 if (files != null) {
152 for (File f : files) {
Cary Clarkd6be1752009-08-12 12:56:42 -0400153 if (!f.delete()) {
154 Log.e(LOGTAG, f.getPath() + " was not deleted");
155 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800156 }
157 }
158 return null;
159 }
160 }
161
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400162 /**
163 * This layout holds everything you see below the status bar, including the
164 * error console, the custom view container, and the webviews.
165 */
166 private FrameLayout mBrowserFrameLayout;
Leon Scroggins81db3662009-06-04 17:45:11 -0400167
Michael Kolbe421c242010-10-04 19:29:01 -0700168 private CombinedBookmarkHistoryView mComboView;
169
Leon Scrogginsd746a942010-05-19 13:21:44 -0400170 private boolean mXLargeScreenSize;
171
Jeff Davidson43610292010-07-16 16:03:58 -0700172 private Boolean mIsProviderPresent = null;
173 private Uri mRlzUri = null;
174
Grace Kloba22ac16e2009-10-07 18:00:23 -0700175 @Override
176 public void onCreate(Bundle icicle) {
Dave Bort31a6d1c2009-04-13 15:56:49 -0700177 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800178 Log.v(LOGTAG, this + " onStart");
179 }
180 super.onCreate(icicle);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800181 // test the browser in OpenGL
182 // requestWindowFeature(Window.FEATURE_OPENGL);
183
Mike Reedd334bf52010-01-26 15:21:44 -0500184 // enable this to test the browser in 32bit
185 if (false) {
186 getWindow().setFormat(PixelFormat.RGBX_8888);
187 BitmapFactory.setDefaultConfig(Bitmap.Config.ARGB_8888);
188 }
189
Svetoslav Ganov2b345992010-05-06 06:13:54 -0700190 if (AccessibilityManager.getInstance(this).isEnabled()) {
191 setDefaultKeyMode(DEFAULT_KEYS_DISABLE);
192 } else {
193 setDefaultKeyMode(DEFAULT_KEYS_SEARCH_LOCAL);
194 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800195
196 mResolver = getContentResolver();
197
Leon Scroggins IIIcc14c8c2010-09-27 12:45:34 -0400198 // Keep a settings instance handy.
199 mSettings = BrowserSettings.getInstance();
200
Grace Kloba0923d692009-09-23 21:37:25 -0700201 // If this was a web search request, pass it on to the default web
202 // search provider and finish this activity.
203 if (handleWebSearchIntent(getIntent())) {
204 finish();
205 return;
206 }
207
The Android Open Source Project0c908882009-03-03 19:32:16 -0800208 mSecLockIcon = Resources.getSystem().getDrawable(
209 android.R.drawable.ic_secure);
210 mMixLockIcon = Resources.getSystem().getDrawable(
211 android.R.drawable.ic_partial_secure);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800212
Michael Kolbed217742010-08-10 17:52:34 -0700213 // Create the tab control and our initial tab
214 mTabControl = new TabControl(this);
215
216 mXLargeScreenSize = (getResources().getConfiguration().screenLayout
217 & Configuration.SCREENLAYOUT_SIZE_MASK)
218 == Configuration.SCREENLAYOUT_SIZE_XLARGE;
219
Leon Scroggins81db3662009-06-04 17:45:11 -0400220 FrameLayout frameLayout = (FrameLayout) getWindow().getDecorView()
221 .findViewById(com.android.internal.R.id.content);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400222 mBrowserFrameLayout = (FrameLayout) LayoutInflater.from(this)
223 .inflate(R.layout.custom_screen, null);
224 mContentView = (FrameLayout) mBrowserFrameLayout.findViewById(
225 R.id.main_content);
226 mErrorConsoleContainer = (LinearLayout) mBrowserFrameLayout
227 .findViewById(R.id.error_console);
228 mCustomViewContainer = (FrameLayout) mBrowserFrameLayout
229 .findViewById(R.id.fullscreen_custom_content);
230 frameLayout.addView(mBrowserFrameLayout, COVER_SCREEN_PARAMS);
Michael Kolbe0a36662010-06-29 10:37:12 -0700231
Leon Scrogginsd746a942010-05-19 13:21:44 -0400232 if (mXLargeScreenSize) {
Michael Kolba2b2ba82010-08-04 17:54:03 -0700233 mTitleBar = new TitleBarXLarge(this);
234 mTitleBar.setProgress(100);
235 mFakeTitleBar = new TitleBarXLarge(this);
Michael Kolbed217742010-08-10 17:52:34 -0700236 ActionBar actionBar = getActionBar();
Michael Kolba2b2ba82010-08-04 17:54:03 -0700237 mTabBar = new TabBar(this, mTabControl, (TitleBarXLarge) mFakeTitleBar);
Michael Kolbed217742010-08-10 17:52:34 -0700238 actionBar.setCustomNavigationMode(mTabBar);
Michael Kolb68775752010-08-19 12:42:01 -0700239 // disable built in zoom controls
240 mTabControl.setDisplayZoomControls(false);
Leon Scrogginsd746a942010-05-19 13:21:44 -0400241 } else {
Leon Scroggins571b3762010-05-26 10:25:01 -0400242 mTitleBar = new TitleBar(this);
Leon Scrogginsd746a942010-05-19 13:21:44 -0400243 // mTitleBar will be always be shown in the fully loaded mode on
244 // phone
245 mTitleBar.setProgress(100);
Leon Scrogginsd746a942010-05-19 13:21:44 -0400246 mFakeTitleBar = new TitleBar(this);
247 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800248
The Android Open Source Project0c908882009-03-03 19:32:16 -0800249 // Open the icon database and retain all the bookmark urls for favicons
250 retainIconsOnStartup();
251
The Android Open Source Project0c908882009-03-03 19:32:16 -0800252 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 }
Michael Kolbe421c242010-10-04 19:29:01 -0700975 removeComboView();
Leon Scrogginsa2ab6a72009-09-11 11:49:52 -0400976
The Android Open Source Project0c908882009-03-03 19:32:16 -0800977 cancelStopToast();
978
979 // unregister network state listener
980 unregisterReceiver(mNetworkStateIntentReceiver);
981 WebView.disablePlatformNotifications();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800982 }
983
Grace Kloba22ac16e2009-10-07 18:00:23 -0700984 @Override
985 protected void onDestroy() {
Dave Bort31a6d1c2009-04-13 15:56:49 -0700986 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800987 Log.v(LOGTAG, "BrowserActivity.onDestroy: this=" + this);
988 }
989 super.onDestroy();
Grace Kloba0923d692009-09-23 21:37:25 -0700990
Leon Scroggins8d5fa432009-10-02 15:55:59 -0400991 if (mUploadMessage != null) {
992 mUploadMessage.onReceiveValue(null);
993 mUploadMessage = null;
994 }
995
Grace Kloba0923d692009-09-23 21:37:25 -0700996 if (mTabControl == null) return;
997
Grace Kloba1fc98a32009-10-21 13:23:08 -0700998 // Remove the fake title bar if it is there
999 hideFakeTitleBar();
1000
The Android Open Source Project0c908882009-03-03 19:32:16 -08001001 // Remove the current tab and sub window
Grace Kloba22ac16e2009-10-07 18:00:23 -07001002 Tab t = mTabControl.getCurrentTab();
Patrick Scottfb5e77f2009-04-08 19:17:37 -07001003 if (t != null) {
1004 dismissSubWindow(t);
1005 removeTabFromContentView(t);
1006 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001007 // Destroy all the tabs
1008 mTabControl.destroy();
1009 WebIconDatabase.getInstance().close();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001010
Bjorn Bringerta7611812010-03-24 11:12:02 +00001011 // Stop watching the default geolocation permissions
1012 mSystemAllowGeolocationOrigins.stop();
1013 mSystemAllowGeolocationOrigins = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001014 }
1015
1016 @Override
1017 public void onConfigurationChanged(Configuration newConfig) {
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04001018 mConfigChanged = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001019 super.onConfigurationChanged(newConfig);
1020
1021 if (mPageInfoDialog != null) {
1022 mPageInfoDialog.dismiss();
1023 showPageInfo(
1024 mPageInfoView,
Leon Scrogginsc7b92f82010-01-11 18:17:31 -05001025 mPageInfoFromShowSSLCertificateOnError);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001026 }
1027 if (mSSLCertificateDialog != null) {
1028 mSSLCertificateDialog.dismiss();
1029 showSSLCertificate(
1030 mSSLCertificateView);
1031 }
1032 if (mSSLCertificateOnErrorDialog != null) {
1033 mSSLCertificateOnErrorDialog.dismiss();
1034 showSSLCertificateOnError(
1035 mSSLCertificateOnErrorView,
1036 mSSLCertificateOnErrorHandler,
1037 mSSLCertificateOnErrorError);
1038 }
1039 if (mHttpAuthenticationDialog != null) {
1040 String title = ((TextView) mHttpAuthenticationDialog
1041 .findViewById(com.android.internal.R.id.alertTitle)).getText()
1042 .toString();
1043 String name = ((TextView) mHttpAuthenticationDialog
1044 .findViewById(R.id.username_edit)).getText().toString();
1045 String password = ((TextView) mHttpAuthenticationDialog
1046 .findViewById(R.id.password_edit)).getText().toString();
1047 int focusId = mHttpAuthenticationDialog.getCurrentFocus()
1048 .getId();
1049 mHttpAuthenticationDialog.dismiss();
1050 showHttpAuthentication(mHttpAuthHandler, null, null, title,
1051 name, password, focusId);
1052 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001053 }
1054
Grace Kloba22ac16e2009-10-07 18:00:23 -07001055 @Override
1056 public void onLowMemory() {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001057 super.onLowMemory();
1058 mTabControl.freeMemory();
1059 }
1060
Cary Clarkff4d92c2010-03-25 11:17:03 -04001061 private void resumeWebViewTimers() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001062 Tab tab = mTabControl.getCurrentTab();
Cary Clarkff4d92c2010-03-25 11:17:03 -04001063 if (tab == null) return; // monkey can trigger this
Grace Kloba22ac16e2009-10-07 18:00:23 -07001064 boolean inLoad = tab.inLoad();
1065 if ((!mActivityInPause && !inLoad) || (mActivityInPause && inLoad)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001066 CookieSyncManager.getInstance().startSync();
Grace Kloba22ac16e2009-10-07 18:00:23 -07001067 WebView w = tab.getWebView();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001068 if (w != null) {
1069 w.resumeTimers();
1070 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001071 }
1072 }
1073
Mike Reed7bfa63b2009-05-28 11:08:32 -04001074 private boolean pauseWebViewTimers() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001075 Tab tab = mTabControl.getCurrentTab();
1076 boolean inLoad = tab.inLoad();
1077 if (mActivityInPause && !inLoad) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001078 CookieSyncManager.getInstance().stopSync();
1079 WebView w = mTabControl.getCurrentWebView();
1080 if (w != null) {
1081 w.pauseTimers();
1082 }
1083 return true;
1084 } else {
1085 return false;
1086 }
1087 }
1088
The Android Open Source Project0c908882009-03-03 19:32:16 -08001089 // Open the icon database and retain all the icons for visited sites.
1090 private void retainIconsOnStartup() {
1091 final WebIconDatabase db = WebIconDatabase.getInstance();
1092 db.open(getDir("icons", 0).getPath());
Leon Scroggins2c0f6112010-03-12 18:09:39 -05001093 Cursor c = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001094 try {
Leon Scroggins2c0f6112010-03-12 18:09:39 -05001095 c = Browser.getAllBookmarks(mResolver);
1096 if (c.moveToFirst()) {
1097 int urlIndex = c.getColumnIndex(Browser.BookmarkColumns.URL);
1098 do {
1099 String url = c.getString(urlIndex);
1100 db.retainIconForPageUrl(url);
1101 } while (c.moveToNext());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001102 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001103 } catch (IllegalStateException e) {
1104 Log.e(LOGTAG, "retainIconsOnStartup", e);
Leon Scroggins2c0f6112010-03-12 18:09:39 -05001105 } finally {
1106 if (c!= null) c.close();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001107 }
1108 }
1109
1110 // Helper method for getting the top window.
1111 WebView getTopWindow() {
1112 return mTabControl.getCurrentTopWebView();
1113 }
1114
Grace Kloba22ac16e2009-10-07 18:00:23 -07001115 TabControl getTabControl() {
1116 return mTabControl;
1117 }
1118
The Android Open Source Project0c908882009-03-03 19:32:16 -08001119 @Override
1120 public boolean onCreateOptionsMenu(Menu menu) {
1121 super.onCreateOptionsMenu(menu);
1122
1123 MenuInflater inflater = getMenuInflater();
1124 inflater.inflate(R.menu.browser, menu);
1125 mMenu = menu;
1126 updateInLoadMenuItems();
1127 return true;
1128 }
1129
1130 /**
1131 * As the menu can be open when loading state changes
1132 * we must manually update the state of the stop/reload menu
1133 * item
1134 */
1135 private void updateInLoadMenuItems() {
1136 if (mMenu == null) {
1137 return;
1138 }
Michael Kolbe0a36662010-06-29 10:37:12 -07001139 MenuItem dest = mMenu.findItem(R.id.stop_reload_menu_id);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001140 MenuItem src = mInLoad ?
1141 mMenu.findItem(R.id.stop_menu_id):
Michael Kolbe0a36662010-06-29 10:37:12 -07001142 mMenu.findItem(R.id.reload_menu_id);
1143 if (src != null) {
1144 dest.setIcon(src.getIcon());
1145 dest.setTitle(src.getTitle());
1146 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001147 }
1148
1149 @Override
1150 public boolean onContextItemSelected(MenuItem item) {
1151 // chording is not an issue with context menus, but we use the same
1152 // options selector, so set mCanChord to true so we can access them.
1153 mCanChord = true;
1154 int id = item.getItemId();
Leon Scroggins96afcb12009-12-10 12:35:56 -05001155 boolean result = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001156 switch (id) {
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001157 // For the context menu from the title bar
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001158 case R.id.title_bar_copy_page_url:
Leon Scroggins96afcb12009-12-10 12:35:56 -05001159 Tab currentTab = mTabControl.getCurrentTab();
1160 if (null == currentTab) {
1161 result = false;
1162 break;
1163 }
1164 WebView mainView = currentTab.getWebView();
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001165 if (null == mainView) {
Leon Scroggins96afcb12009-12-10 12:35:56 -05001166 result = false;
1167 break;
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001168 }
Leon Scroggins96afcb12009-12-10 12:35:56 -05001169 copy(mainView.getUrl());
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001170 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001171 // -- Browser context menu
1172 case R.id.open_context_menu_id:
The Android Open Source Project0c908882009-03-03 19:32:16 -08001173 case R.id.bookmark_context_menu_id:
1174 case R.id.save_link_context_menu_id:
1175 case R.id.share_link_context_menu_id:
1176 case R.id.copy_link_context_menu_id:
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001177 final WebView webView = getTopWindow();
1178 if (null == webView) {
Leon Scroggins96afcb12009-12-10 12:35:56 -05001179 result = false;
1180 break;
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001181 }
1182 final HashMap hrefMap = new HashMap();
1183 hrefMap.put("webview", webView);
1184 final Message msg = mHandler.obtainMessage(
1185 FOCUS_NODE_HREF, id, 0, hrefMap);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001186 webView.requestFocusNodeHref(msg);
1187 break;
1188
1189 default:
1190 // For other context menus
Leon Scroggins96afcb12009-12-10 12:35:56 -05001191 result = onOptionsItemSelected(item);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001192 }
1193 mCanChord = false;
Leon Scroggins96afcb12009-12-10 12:35:56 -05001194 return result;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001195 }
1196
1197 private Bundle createGoogleSearchSourceBundle(String source) {
1198 Bundle bundle = new Bundle();
Bjorn Bringert10d1cca2010-02-10 14:22:12 +00001199 bundle.putString(Search.SOURCE, source);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001200 return bundle;
1201 }
1202
Leon Scroggins8ad29922010-02-16 12:33:55 -05001203 /* package */ void editUrl() {
Leon Scroggins68579392009-09-15 15:31:54 -04001204 if (mOptionsMenuOpen) closeOptionsMenu();
Leon Scroggins5bbe9802009-07-31 13:10:55 -04001205 String url = (getTopWindow() == null) ? null : getTopWindow().getUrl();
Grace Kloba83f47342009-07-20 10:44:31 -07001206 startSearch(mSettings.getHomePage().equals(url) ? null : url, true,
Leon Scroggins8ad29922010-02-16 12:33:55 -05001207 null, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001208 }
1209
Leon Scroggins8ad29922010-02-16 12:33:55 -05001210 /**
1211 * Overriding this to insert a local information bundle
1212 */
The Android Open Source Project0c908882009-03-03 19:32:16 -08001213 @Override
1214 public void startSearch(String initialQuery, boolean selectInitialQuery,
1215 Bundle appSearchData, boolean globalSearch) {
1216 if (appSearchData == null) {
1217 appSearchData = createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_TYPE);
1218 }
Leon Scroggins III430057d2010-09-14 10:57:37 -04001219
1220 SearchEngine searchEngine = mSettings.getSearchEngine();
1221 if (searchEngine != null && !searchEngine.supportsVoiceSearch()) {
1222 appSearchData.putBoolean(SearchManager.DISABLE_VOICE_SEARCH, true);
1223 }
1224
The Android Open Source Project0c908882009-03-03 19:32:16 -08001225 super.startSearch(initialQuery, selectInitialQuery, appSearchData, globalSearch);
1226 }
1227
Leon Scroggins1f005d32009-08-10 17:36:42 -04001228 /**
1229 * Switch tabs. Called by the TitleBarSet when sliding the title bar
1230 * results in changing tabs.
Leon Scroggins160a7e72009-08-14 18:28:01 -04001231 * @param index Index of the tab to change to, as defined by
1232 * mTabControl.getTabIndex(Tab t).
1233 * @return boolean True if we successfully switched to a different tab. If
1234 * the indexth tab is null, or if that tab is the same as
1235 * the current one, return false.
Leon Scroggins1f005d32009-08-10 17:36:42 -04001236 */
Leon Scroggins160a7e72009-08-14 18:28:01 -04001237 /* package */ boolean switchToTab(int index) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001238 Tab tab = mTabControl.getTab(index);
1239 Tab currentTab = mTabControl.getCurrentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04001240 if (tab == null || tab == currentTab) {
Leon Scroggins160a7e72009-08-14 18:28:01 -04001241 return false;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001242 }
1243 if (currentTab != null) {
1244 // currentTab may be null if it was just removed. In that case,
1245 // we do not need to remove it
1246 removeTabFromContentView(currentTab);
1247 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001248 mTabControl.setCurrentTab(tab);
1249 attachTabToContentView(tab);
Grace Klobaeb6eef42009-09-15 17:56:32 -07001250 resetTitleIconAndProgress();
1251 updateLockIconToLatest();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001252 return true;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001253 }
1254
Grace Kloba22ac16e2009-10-07 18:00:23 -07001255 /* package */ Tab openTabToHomePage() {
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001256 return openTabAndShow(mSettings.getHomePage(), false, null);
1257 }
1258
Leon Scroggins1f005d32009-08-10 17:36:42 -04001259 /* package */ void closeCurrentWindow() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001260 final Tab current = mTabControl.getCurrentTab();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001261 if (mTabControl.getTabCount() == 1) {
Leon Scroggins30444232009-09-04 18:36:20 -04001262 // This is the last tab. Open a new one, with the home
1263 // page and close the current one.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001264 openTabToHomePage();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001265 closeTab(current);
Leon Scroggins160a7e72009-08-14 18:28:01 -04001266 return;
1267 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07001268 final Tab parent = current.getParentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04001269 int indexToShow = -1;
1270 if (parent != null) {
1271 indexToShow = mTabControl.getTabIndex(parent);
1272 } else {
Leon Scroggins160a7e72009-08-14 18:28:01 -04001273 final int currentIndex = mTabControl.getCurrentIndex();
1274 // Try to move to the tab to the right
1275 indexToShow = currentIndex + 1;
1276 if (indexToShow > mTabControl.getTabCount() - 1) {
1277 // Try to move to the tab to the left
1278 indexToShow = currentIndex - 1;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001279 }
1280 }
Leon Scroggins160a7e72009-08-14 18:28:01 -04001281 if (switchToTab(indexToShow)) {
1282 // Close window
1283 closeTab(current);
1284 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001285 }
1286
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001287 private ActiveTabsPage mActiveTabsPage;
1288
1289 /**
1290 * Remove the active tabs page.
1291 * @param needToAttach If true, the active tabs page did not attach a tab
1292 * to the content view, so we need to do that here.
1293 */
1294 /* package */ void removeActiveTabPage(boolean needToAttach) {
1295 mContentView.removeView(mActiveTabsPage);
Leon Scrogginsd746a942010-05-19 13:21:44 -04001296 mTitleBar.setVisibility(View.VISIBLE);
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001297 mActiveTabsPage = null;
1298 mMenuState = R.id.MAIN_MENU;
1299 if (needToAttach) {
1300 attachTabToContentView(mTabControl.getCurrentTab());
1301 }
1302 getTopWindow().requestFocus();
1303 }
1304
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04001305 @Override
1306 public ActionMode onStartActionMode(ActionMode.Callback callback) {
Leon Scroggins4fc12cb2010-08-24 14:24:05 -04001307 mActionMode = super.onStartActionMode(callback);
1308 hideFakeTitleBar();
1309 // Would like to change the MENU, but onEndActionMode may not be called
1310 return mActionMode;
Cary Clark01cfcdd2010-06-04 16:36:45 -04001311 }
1312
The Android Open Source Project0c908882009-03-03 19:32:16 -08001313 @Override
1314 public boolean onOptionsItemSelected(MenuItem item) {
Michael Kolbe421c242010-10-04 19:29:01 -07001315 // menu remains active, so ensure comboview is dismissed
1316 removeComboView();
Michael Kolbed217742010-08-10 17:52:34 -07001317 // check the action bar button before mCanChord check, as the prepare call
1318 // doesn't come for action bar buttons
1319 if (item.getItemId() == R.id.newtab) {
Michael Kolb300b7f02010-08-25 13:47:24 -07001320 openTabToHomePage();
Michael Kolbed217742010-08-10 17:52:34 -07001321 return true;
1322 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001323 if (!mCanChord) {
1324 // The user has already fired a shortcut with this hold down of the
1325 // menu key.
1326 return false;
1327 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001328 if (null == getTopWindow()) {
Leon Scroggins0d7ae0e2009-06-05 11:04:45 -04001329 return false;
1330 }
Grace Kloba6ee9c492009-07-13 10:04:34 -07001331 if (mMenuIsDown) {
1332 // The shortcut action consumes the MENU. Even if it is still down,
1333 // it won't trigger the next shortcut action. In the case of the
1334 // shortcut action triggering a new activity, like Bookmarks, we
1335 // won't get onKeyUp for MENU. So it is important to reset it here.
1336 mMenuIsDown = false;
1337 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001338 switch (item.getItemId()) {
1339 // -- Main menu
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001340 case R.id.new_tab_menu_id:
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001341 openTabToHomePage();
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001342 break;
1343
Michael Kolbae62fd42010-08-18 16:33:28 -07001344 case R.id.incognito_menu_id:
1345 openIncognitoTab();
1346 break;
1347
Leon Scroggins64b80f32009-08-07 12:03:34 -04001348 case R.id.goto_menu_id:
Leon Scroggins8ad29922010-02-16 12:33:55 -05001349 editUrl();
Leon Scrogginsb3a5bed2009-09-28 11:21:56 -04001350 break;
1351
1352 case R.id.bookmarks_menu_id:
Michael Kolbe421c242010-10-04 19:29:01 -07001353 bookmarksOrHistoryPicker(false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001354 break;
1355
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001356 case R.id.active_tabs_menu_id:
1357 mActiveTabsPage = new ActiveTabsPage(this, mTabControl);
1358 removeTabFromContentView(mTabControl.getCurrentTab());
Leon Scrogginsd746a942010-05-19 13:21:44 -04001359 mTitleBar.setVisibility(View.GONE);
Leon Scroggins43de6162009-09-14 19:59:58 -04001360 hideFakeTitleBar();
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001361 mContentView.addView(mActiveTabsPage, COVER_SCREEN_PARAMS);
1362 mActiveTabsPage.requestFocus();
1363 mMenuState = EMPTY_MENU;
1364 break;
1365
Leon Scroggins1f005d32009-08-10 17:36:42 -04001366 case R.id.add_bookmark_menu_id:
Leon Scroggins571b3762010-05-26 10:25:01 -04001367 bookmarkCurrentPage();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001368 break;
1369
1370 case R.id.stop_reload_menu_id:
1371 if (mInLoad) {
1372 stopLoading();
1373 } else {
1374 getTopWindow().reload();
1375 }
1376 break;
1377
1378 case R.id.back_menu_id:
1379 getTopWindow().goBack();
1380 break;
1381
1382 case R.id.forward_menu_id:
1383 getTopWindow().goForward();
1384 break;
1385
1386 case R.id.close_menu_id:
1387 // Close the subwindow if it exists.
1388 if (mTabControl.getCurrentSubWindow() != null) {
1389 dismissSubWindow(mTabControl.getCurrentTab());
1390 break;
1391 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001392 closeCurrentWindow();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001393 break;
1394
1395 case R.id.homepage_menu_id:
Grace Kloba22ac16e2009-10-07 18:00:23 -07001396 Tab current = mTabControl.getCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001397 if (current != null) {
1398 dismissSubWindow(current);
Leon Scroggins92472e82010-02-17 16:32:28 -05001399 loadUrl(current.getWebView(), mSettings.getHomePage());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001400 }
1401 break;
1402
1403 case R.id.preferences_menu_id:
1404 Intent intent = new Intent(this,
1405 BrowserPreferencesPage.class);
Leon Scrogginsd5304942009-12-10 16:11:39 -05001406 intent.putExtra(BrowserPreferencesPage.CURRENT_PAGE,
1407 getTopWindow().getUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001408 startActivityForResult(intent, PREFERENCES_PAGE);
1409 break;
1410
1411 case R.id.find_menu_id:
Leon Scroggins4fc12cb2010-08-24 14:24:05 -04001412 getTopWindow().showFindDialog(null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001413 break;
1414
Elliott Slaughter0ced08c2010-06-30 11:40:42 -07001415 case R.id.save_webarchive_menu_id:
1416 if (LOGD_ENABLED) {
1417 Log.d(LOGTAG, "Save as Web Archive");
1418 }
Elliott Slaughteraba242c2010-09-01 16:21:07 -07001419 String state = Environment.getExternalStorageState();
1420 if (Environment.MEDIA_MOUNTED.equals(state)) {
1421 String directory = Environment.getExternalStoragePublicDirectory(
1422 Environment.DIRECTORY_DOWNLOADS).getAbsolutePath() + File.separator;
Shimeng (Simon) Wang447c8462010-09-15 18:16:55 -07001423 File dir = new File(directory);
1424 if (!dir.exists() && !dir.mkdirs()) {
1425 Log.e(LOGTAG, "Save as Web Archive: mkdirs for " + directory + " failed!");
1426 Toast.makeText(BrowserActivity.this, R.string.webarchive_failed,
1427 Toast.LENGTH_SHORT).show();
1428 break;
1429 }
Elliott Slaughteraba242c2010-09-01 16:21:07 -07001430 getTopWindow().saveWebArchive(directory, true, new ValueCallback<String>() {
1431 @Override
1432 public void onReceiveValue(String value) {
1433 if (value != null) {
1434 Toast.makeText(BrowserActivity.this, R.string.webarchive_saved,
1435 Toast.LENGTH_SHORT).show();
1436 } else {
1437 Toast.makeText(BrowserActivity.this, R.string.webarchive_failed,
1438 Toast.LENGTH_SHORT).show();
1439 }
Elliott Slaughter0ced08c2010-06-30 11:40:42 -07001440 }
Elliott Slaughteraba242c2010-09-01 16:21:07 -07001441 });
1442 } else {
1443 Toast.makeText(BrowserActivity.this, R.string.webarchive_failed,
1444 Toast.LENGTH_SHORT).show();
1445 }
Elliott Slaughter0ced08c2010-06-30 11:40:42 -07001446 break;
1447
The Android Open Source Project0c908882009-03-03 19:32:16 -08001448 case R.id.page_info_menu_id:
1449 showPageInfo(mTabControl.getCurrentTab(), false);
1450 break;
1451
1452 case R.id.classic_history_menu_id:
Michael Kolbe421c242010-10-04 19:29:01 -07001453 bookmarksOrHistoryPicker(true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001454 break;
1455
Leon Scroggins96afcb12009-12-10 12:35:56 -05001456 case R.id.title_bar_share_page_url:
The Android Open Source Project0c908882009-03-03 19:32:16 -08001457 case R.id.share_page_menu_id:
Leon Scroggins96afcb12009-12-10 12:35:56 -05001458 Tab currentTab = mTabControl.getCurrentTab();
1459 if (null == currentTab) {
1460 mCanChord = false;
1461 return false;
1462 }
1463 currentTab.populatePickerData();
1464 sharePage(this, currentTab.getTitle(),
1465 currentTab.getUrl(), currentTab.getFavicon(),
Ben Murdoch87cc65d2010-06-29 20:34:10 +01001466 createScreenshot(currentTab.getWebView(), getDesiredThumbnailWidth(this),
1467 getDesiredThumbnailHeight(this)));
The Android Open Source Project0c908882009-03-03 19:32:16 -08001468 break;
1469
1470 case R.id.dump_nav_menu_id:
1471 getTopWindow().debugDump();
1472 break;
1473
Andrei Popescu7a8b88b2010-02-02 00:30:38 +00001474 case R.id.dump_counters_menu_id:
1475 getTopWindow().dumpV8Counters();
1476 break;
1477
The Android Open Source Project0c908882009-03-03 19:32:16 -08001478 case R.id.zoom_in_menu_id:
1479 getTopWindow().zoomIn();
1480 break;
1481
1482 case R.id.zoom_out_menu_id:
1483 getTopWindow().zoomOut();
1484 break;
1485
1486 case R.id.view_downloads_menu_id:
Leon Scroggins IIIa682a3c2010-09-27 12:32:40 -04001487 viewDownloads();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001488 break;
1489
The Android Open Source Project0c908882009-03-03 19:32:16 -08001490 case R.id.window_one_menu_id:
1491 case R.id.window_two_menu_id:
1492 case R.id.window_three_menu_id:
1493 case R.id.window_four_menu_id:
1494 case R.id.window_five_menu_id:
1495 case R.id.window_six_menu_id:
1496 case R.id.window_seven_menu_id:
1497 case R.id.window_eight_menu_id:
1498 {
1499 int menuid = item.getItemId();
1500 for (int id = 0; id < WINDOW_SHORTCUT_ID_ARRAY.length; id++) {
1501 if (WINDOW_SHORTCUT_ID_ARRAY[id] == menuid) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001502 Tab desiredTab = mTabControl.getTab(id);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001503 if (desiredTab != null &&
1504 desiredTab != mTabControl.getCurrentTab()) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001505 switchToTab(id);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001506 }
1507 break;
1508 }
1509 }
1510 }
1511 break;
1512
1513 default:
1514 if (!super.onOptionsItemSelected(item)) {
1515 return false;
1516 }
1517 // Otherwise fall through.
1518 }
1519 mCanChord = false;
1520 return true;
1521 }
1522
Leon Scroggins571b3762010-05-26 10:25:01 -04001523 /* package */ void bookmarkCurrentPage() {
1524 Intent i = new Intent(BrowserActivity.this,
1525 AddBookmarkPage.class);
1526 WebView w = getTopWindow();
1527 i.putExtra("url", w.getUrl());
1528 i.putExtra("title", w.getTitle());
1529 i.putExtra("touch_icon_url", w.getTouchIconUrl());
Ben Murdoch87cc65d2010-06-29 20:34:10 +01001530 i.putExtra("thumbnail", createScreenshot(w, getDesiredThumbnailWidth(this),
1531 getDesiredThumbnailHeight(this)));
Leon Scroggins III76a0e9c2010-10-05 16:10:01 -04001532 // Put the dialog at the upper right of the screen, covering the
1533 // star on the title bar.
1534 i.putExtra("gravity", Gravity.RIGHT | Gravity.TOP);
Leon Scroggins571b3762010-05-26 10:25:01 -04001535 startActivity(i);
1536 }
1537
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04001538 /*
1539 * True if a custom ActionMode (i.e. find or select) is in use.
1540 */
1541 private boolean isInCustomActionMode() {
1542 return mActionMode != null;
Cary Clark01cfcdd2010-06-04 16:36:45 -04001543 }
1544
1545 /*
Leon Scroggins4fc12cb2010-08-24 14:24:05 -04001546 * End the current ActionMode.
Cary Clark01cfcdd2010-06-04 16:36:45 -04001547 */
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04001548 void endActionMode() {
1549 if (mActionMode != null) {
Leon Scroggins4fc12cb2010-08-24 14:24:05 -04001550 ActionMode mode = mActionMode;
1551 onEndActionMode();
1552 mode.finish();
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04001553 }
1554 }
1555
1556 /*
1557 * Called by find and select when they are finished. Replace title bars
1558 * as necessary.
1559 */
1560 public void onEndActionMode() {
1561 if (!isInCustomActionMode()) return;
Leon Scroggins79e36d92010-04-29 16:01:46 +01001562 if (mInLoad) {
1563 // The title bar was hidden, because otherwise it would cover up the
Michael Kolba2b2ba82010-08-04 17:54:03 -07001564 // find or select dialog. Now that the dialog has been removed,
Cary Clark01cfcdd2010-06-04 16:36:45 -04001565 // show the fake title bar once again.
Leon Scroggins79e36d92010-04-29 16:01:46 +01001566 showFakeTitleBar();
1567 }
Leon Scroggins4fc12cb2010-08-24 14:24:05 -04001568 // Would like to return the menu state to normal, but this does not
1569 // necessarily get called.
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04001570 mActionMode = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001571 }
1572
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04001573 // For select and find, we keep track of the ActionMode so that
1574 // finish() can be called as desired.
1575 private ActionMode mActionMode;
1576
Grace Kloba22ac16e2009-10-07 18:00:23 -07001577 @Override
1578 public boolean onPrepareOptionsMenu(Menu menu) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001579 // This happens when the user begins to hold down the menu key, so
1580 // allow them to chord to get a shortcut.
1581 mCanChord = true;
1582 // Note: setVisible will decide whether an item is visible; while
1583 // setEnabled() will decide whether an item is enabled, which also means
1584 // whether the matching shortcut key will function.
1585 super.onPrepareOptionsMenu(menu);
1586 switch (mMenuState) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001587 case EMPTY_MENU:
1588 if (mCurrentMenuState != mMenuState) {
1589 menu.setGroupVisible(R.id.MAIN_MENU, false);
1590 menu.setGroupEnabled(R.id.MAIN_MENU, false);
1591 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001592 }
1593 break;
1594 default:
1595 if (mCurrentMenuState != mMenuState) {
1596 menu.setGroupVisible(R.id.MAIN_MENU, true);
1597 menu.setGroupEnabled(R.id.MAIN_MENU, true);
1598 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001599 }
1600 final WebView w = getTopWindow();
1601 boolean canGoBack = false;
1602 boolean canGoForward = false;
1603 boolean isHome = false;
1604 if (w != null) {
1605 canGoBack = w.canGoBack();
1606 canGoForward = w.canGoForward();
1607 isHome = mSettings.getHomePage().equals(w.getUrl());
1608 }
1609 final MenuItem back = menu.findItem(R.id.back_menu_id);
1610 back.setEnabled(canGoBack);
1611
1612 final MenuItem home = menu.findItem(R.id.homepage_menu_id);
1613 home.setEnabled(!isHome);
1614
Michael Kolbe0a36662010-06-29 10:37:12 -07001615 final MenuItem forward = menu.findItem(R.id.forward_menu_id);
1616 forward.setEnabled(canGoForward);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001617
Michael Kolbed217742010-08-10 17:52:34 -07001618 if (!mXLargeScreenSize) {
1619 final MenuItem newtab = menu.findItem(R.id.new_tab_menu_id);
1620 newtab.setEnabled(mTabControl.canCreateNewTab());
1621 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001622 // decide whether to show the share link option
1623 PackageManager pm = getPackageManager();
1624 Intent send = new Intent(Intent.ACTION_SEND);
1625 send.setType("text/plain");
1626 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1627 menu.findItem(R.id.share_page_menu_id).setVisible(ri != null);
1628
The Android Open Source Project0c908882009-03-03 19:32:16 -08001629 boolean isNavDump = mSettings.isNavDump();
1630 final MenuItem nav = menu.findItem(R.id.dump_nav_menu_id);
1631 nav.setVisible(isNavDump);
1632 nav.setEnabled(isNavDump);
Andrei Popescu7a8b88b2010-02-02 00:30:38 +00001633
1634 boolean showDebugSettings = mSettings.showDebugSettings();
1635 final MenuItem counter = menu.findItem(R.id.dump_counters_menu_id);
1636 counter.setVisible(showDebugSettings);
1637 counter.setEnabled(showDebugSettings);
1638
The Android Open Source Project0c908882009-03-03 19:32:16 -08001639 break;
1640 }
1641 mCurrentMenuState = mMenuState;
1642 return true;
1643 }
1644
1645 @Override
1646 public void onCreateContextMenu(ContextMenu menu, View v,
1647 ContextMenuInfo menuInfo) {
Leon Scroggins571b3762010-05-26 10:25:01 -04001648 if (v instanceof TitleBarBase) {
Leon Scroggins4e9f89b2010-02-22 16:54:14 -05001649 return;
1650 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001651 WebView webview = (WebView) v;
1652 WebView.HitTestResult result = webview.getHitTestResult();
1653 if (result == null) {
1654 return;
1655 }
1656
1657 int type = result.getType();
1658 if (type == WebView.HitTestResult.UNKNOWN_TYPE) {
1659 Log.w(LOGTAG,
1660 "We should not show context menu when nothing is touched");
1661 return;
1662 }
1663 if (type == WebView.HitTestResult.EDIT_TEXT_TYPE) {
1664 // let TextView handles context menu
1665 return;
1666 }
1667
1668 // Note, http://b/issue?id=1106666 is requesting that
1669 // an inflated menu can be used again. This is not available
1670 // yet, so inflate each time (yuk!)
1671 MenuInflater inflater = getMenuInflater();
1672 inflater.inflate(R.menu.browsercontext, menu);
1673
1674 // Show the correct menu group
Leon Scroggins III9e997c72010-05-26 13:25:16 -04001675 final String extra = result.getExtra();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001676 menu.setGroupVisible(R.id.PHONE_MENU,
1677 type == WebView.HitTestResult.PHONE_TYPE);
1678 menu.setGroupVisible(R.id.EMAIL_MENU,
1679 type == WebView.HitTestResult.EMAIL_TYPE);
1680 menu.setGroupVisible(R.id.GEO_MENU,
1681 type == WebView.HitTestResult.GEO_TYPE);
1682 menu.setGroupVisible(R.id.IMAGE_MENU,
1683 type == WebView.HitTestResult.IMAGE_TYPE
1684 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1685 menu.setGroupVisible(R.id.ANCHOR_MENU,
1686 type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1687 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1688
1689 // Setup custom handling depending on the type
1690 switch (type) {
1691 case WebView.HitTestResult.PHONE_TYPE:
1692 menu.setHeaderTitle(Uri.decode(extra));
1693 menu.findItem(R.id.dial_context_menu_id).setIntent(
1694 new Intent(Intent.ACTION_VIEW, Uri
1695 .parse(WebView.SCHEME_TEL + extra)));
1696 Intent addIntent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
1697 addIntent.putExtra(Insert.PHONE, Uri.decode(extra));
Cary Clark5e335a32009-09-22 14:53:11 -04001698 addIntent.setType(ContactsContract.Contacts.CONTENT_ITEM_TYPE);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001699 menu.findItem(R.id.add_contact_context_menu_id).setIntent(
1700 addIntent);
1701 menu.findItem(R.id.copy_phone_context_menu_id).setOnMenuItemClickListener(
1702 new Copy(extra));
1703 break;
1704
1705 case WebView.HitTestResult.EMAIL_TYPE:
1706 menu.setHeaderTitle(extra);
1707 menu.findItem(R.id.email_context_menu_id).setIntent(
1708 new Intent(Intent.ACTION_VIEW, Uri
1709 .parse(WebView.SCHEME_MAILTO + extra)));
1710 menu.findItem(R.id.copy_mail_context_menu_id).setOnMenuItemClickListener(
1711 new Copy(extra));
1712 break;
1713
1714 case WebView.HitTestResult.GEO_TYPE:
1715 menu.setHeaderTitle(extra);
1716 menu.findItem(R.id.map_context_menu_id).setIntent(
1717 new Intent(Intent.ACTION_VIEW, Uri
1718 .parse(WebView.SCHEME_GEO
1719 + URLEncoder.encode(extra))));
1720 menu.findItem(R.id.copy_geo_context_menu_id).setOnMenuItemClickListener(
1721 new Copy(extra));
1722 break;
1723
1724 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1725 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
1726 TextView titleView = (TextView) LayoutInflater.from(this)
1727 .inflate(android.R.layout.browser_link_context_header,
1728 null);
1729 titleView.setText(extra);
1730 menu.setHeaderView(titleView);
1731 // decide whether to show the open link in new tab option
Leon Scroggins III9e997c72010-05-26 13:25:16 -04001732 boolean showNewTab = mTabControl.canCreateNewTab();
1733 MenuItem newTabItem
1734 = menu.findItem(R.id.open_newtab_context_menu_id);
1735 newTabItem.setVisible(showNewTab);
1736 if (showNewTab) {
1737 newTabItem.setOnMenuItemClickListener(
1738 new MenuItem.OnMenuItemClickListener() {
1739 public boolean onMenuItemClick(MenuItem item) {
1740 final Tab parent = mTabControl.getCurrentTab();
Michael Kolb68792c82010-08-09 16:39:18 -07001741 final Tab newTab = openTab(extra, false);
Leon Scroggins III9e997c72010-05-26 13:25:16 -04001742 if (newTab != parent) {
1743 parent.addChildTab(newTab);
1744 }
1745 return true;
1746 }
1747 });
1748 }
Ben Murdochde353622009-10-12 10:29:00 +01001749 menu.findItem(R.id.bookmark_context_menu_id).setVisible(
1750 Bookmarks.urlHasAcceptableScheme(extra));
The Android Open Source Project0c908882009-03-03 19:32:16 -08001751 PackageManager pm = getPackageManager();
1752 Intent send = new Intent(Intent.ACTION_SEND);
1753 send.setType("text/plain");
1754 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1755 menu.findItem(R.id.share_link_context_menu_id).setVisible(ri != null);
1756 if (type == WebView.HitTestResult.SRC_ANCHOR_TYPE) {
1757 break;
1758 }
1759 // otherwise fall through to handle image part
1760 case WebView.HitTestResult.IMAGE_TYPE:
1761 if (type == WebView.HitTestResult.IMAGE_TYPE) {
1762 menu.setHeaderTitle(extra);
1763 }
1764 menu.findItem(R.id.view_image_context_menu_id).setIntent(
1765 new Intent(Intent.ACTION_VIEW, Uri.parse(extra)));
1766 menu.findItem(R.id.download_context_menu_id).
1767 setOnMenuItemClickListener(new Download(extra));
Ben Murdoch4f75ba22009-10-27 11:48:28 +00001768 menu.findItem(R.id.set_wallpaper_context_menu_id).
1769 setOnMenuItemClickListener(new SetAsWallpaper(extra));
The Android Open Source Project0c908882009-03-03 19:32:16 -08001770 break;
1771
1772 default:
1773 Log.w(LOGTAG, "We should not get here.");
1774 break;
1775 }
Leon Scrogginsb2b19f52009-10-09 16:10:00 -04001776 hideFakeTitleBar();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001777 }
1778
The Android Open Source Project0c908882009-03-03 19:32:16 -08001779 // Attach the given tab to the content view.
Grace Klobac928c302009-09-17 11:51:21 -07001780 // this should only be called for the current tab.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001781 private void attachTabToContentView(Tab t) {
Steve Block2bc69912009-07-30 14:45:13 +01001782 // Attach the container that contains the main WebView and any other UI
1783 // associated with the tab.
Patrick Scottd0119532009-09-17 08:00:31 -04001784 t.attachTabToContentView(mContentView);
Ben Murdochbff2d602009-07-01 20:19:05 +01001785
1786 if (mShouldShowErrorConsole) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001787 ErrorConsoleView errorConsole = t.getErrorConsole(true);
Ben Murdochbff2d602009-07-01 20:19:05 +01001788 if (errorConsole.numberOfErrors() == 0) {
1789 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
1790 } else {
1791 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
1792 }
1793
1794 mErrorConsoleContainer.addView(errorConsole,
Romain Guy15b8ec62010-01-08 15:06:43 -08001795 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
Ben Murdochbff2d602009-07-01 20:19:05 +01001796 ViewGroup.LayoutParams.WRAP_CONTENT));
1797 }
1798
Michael Kolba2b2ba82010-08-04 17:54:03 -07001799 WebView view = t.getWebView();
1800 view.setEmbeddedTitleBar(mTitleBar);
Leon Scroggins58d56c62010-01-28 15:12:40 -05001801 if (t.isInVoiceSearchMode()) {
1802 showVoiceTitleBar(t.getVoiceDisplayTitle());
1803 } else {
1804 revertVoiceTitleBar();
1805 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001806 // Request focus on the top window.
1807 t.getTopWindow().requestFocus();
Michael Kolba2b2ba82010-08-04 17:54:03 -07001808 if (mTabControl.getTabChangeListener() != null) {
1809 mTabControl.getTabChangeListener().onCurrentTab(t);
1810 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001811 }
1812
1813 // Attach a sub window to the main WebView of the given tab.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001814 void attachSubWindow(Tab t) {
Patrick Scottd0119532009-09-17 08:00:31 -04001815 t.attachSubWindow(mContentView);
1816 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001817 }
1818
1819 // Remove the given tab from the content view.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001820 private void removeTabFromContentView(Tab t) {
Steve Block2bc69912009-07-30 14:45:13 +01001821 // Remove the container that contains the main WebView.
Patrick Scottd0119532009-09-17 08:00:31 -04001822 t.removeTabFromContentView(mContentView);
Ben Murdochbff2d602009-07-01 20:19:05 +01001823
Grace Kloba22ac16e2009-10-07 18:00:23 -07001824 ErrorConsoleView errorConsole = t.getErrorConsole(false);
1825 if (errorConsole != null) {
1826 mErrorConsoleContainer.removeView(errorConsole);
Ben Murdochbff2d602009-07-01 20:19:05 +01001827 }
1828
Michael Kolba2b2ba82010-08-04 17:54:03 -07001829 WebView view = t.getWebView();
1830 if (view != null) {
1831 view.setEmbeddedTitleBar(null);
Leon Scrogginsbb85b902009-09-14 19:27:20 -04001832 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001833 }
1834
1835 // Remove the sub window if it exists. Also called by TabControl when the
1836 // user clicks the 'X' to dismiss a sub window.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001837 /* package */ void dismissSubWindow(Tab t) {
Patrick Scottd0119532009-09-17 08:00:31 -04001838 t.removeSubWindow(mContentView);
Grace Kloba22ac16e2009-10-07 18:00:23 -07001839 // dismiss the subwindow. This will destroy the WebView.
1840 t.dismissSubWindow();
Patrick Scottd0119532009-09-17 08:00:31 -04001841 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001842 }
1843
Leon Scroggins1f005d32009-08-10 17:36:42 -04001844 // A wrapper function of {@link #openTabAndShow(UrlData, boolean, String)}
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07001845 // that accepts url as string.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001846 private Tab openTabAndShow(String url, boolean closeOnExit, String appId) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001847 return openTabAndShow(new UrlData(url), closeOnExit, appId);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001848 }
1849
1850 // This method does a ton of stuff. It will attempt to create a new tab
1851 // if we haven't reached MAX_TABS. Otherwise it uses the current tab. If
Leon Scroggins1f005d32009-08-10 17:36:42 -04001852 // url isn't null, it will load the given url.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001853 /* package */Tab openTabAndShow(UrlData urlData, boolean closeOnExit,
1854 String appId) {
1855 final Tab currentTab = mTabControl.getCurrentTab();
1856 if (mTabControl.canCreateNewTab()) {
1857 final Tab tab = mTabControl.createNewTab(closeOnExit, appId,
Elliott Slaughterf0f03952010-07-14 18:10:36 -07001858 urlData.mUrl, false);
Leon Scroggins1f005d32009-08-10 17:36:42 -04001859 WebView webview = tab.getWebView();
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001860 // If the last tab was removed from the active tabs page, currentTab
1861 // will be null.
1862 if (currentTab != null) {
1863 removeTabFromContentView(currentTab);
1864 }
Patrick Scott8bbd69f2009-08-14 13:35:53 -04001865 // We must set the new tab as the current tab to reflect the old
1866 // animation behavior.
1867 mTabControl.setCurrentTab(tab);
Grace Klobaeb6eef42009-09-15 17:56:32 -07001868 attachTabToContentView(tab);
Leon Scroggins160a7e72009-08-14 18:28:01 -04001869 if (!urlData.isEmpty()) {
Patrick Scott9d53da02010-02-19 10:19:01 -05001870 loadUrlDataIn(tab, urlData);
Leon Scroggins1f005d32009-08-10 17:36:42 -04001871 }
1872 return tab;
1873 } else {
1874 // Get rid of the subwindow if it exists
1875 dismissSubWindow(currentTab);
1876 if (!urlData.isEmpty()) {
1877 // Load the given url.
Patrick Scott9d53da02010-02-19 10:19:01 -05001878 loadUrlDataIn(currentTab, urlData);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001879 }
Leon Scroggins58d56c62010-01-28 15:12:40 -05001880 return currentTab;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001881 }
1882 }
1883
Michael Kolb68792c82010-08-09 16:39:18 -07001884 private Tab openTab(String url, boolean forceForeground) {
1885 if (mSettings.openInBackground() && !forceForeground) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001886 Tab t = mTabControl.createNewTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001887 if (t != null) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001888 WebView view = t.getWebView();
Leon Scroggins92472e82010-02-17 16:32:28 -05001889 loadUrl(view, url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001890 }
Grace Klobac9181842009-04-14 08:53:22 -07001891 return t;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001892 } else {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001893 return openTabAndShow(url, false, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001894 }
1895 }
1896
Elliott Slaughterf0f03952010-07-14 18:10:36 -07001897 /* package */ Tab openIncognitoTab() {
1898 if (mTabControl.canCreateNewTab()) {
1899 Tab currentTab = mTabControl.getCurrentTab();
1900 Tab tab = mTabControl.createNewTab(false, null, null, true);
1901 if (currentTab != null) {
1902 removeTabFromContentView(currentTab);
1903 }
1904 mTabControl.setCurrentTab(tab);
1905 attachTabToContentView(tab);
1906 return tab;
1907 }
1908 return null;
1909 }
1910
The Android Open Source Project0c908882009-03-03 19:32:16 -08001911 private class Copy implements OnMenuItemClickListener {
1912 private CharSequence mText;
1913
1914 public boolean onMenuItemClick(MenuItem item) {
1915 copy(mText);
1916 return true;
1917 }
1918
1919 public Copy(CharSequence toCopy) {
1920 mText = toCopy;
1921 }
1922 }
1923
1924 private class Download implements OnMenuItemClickListener {
1925 private String mText;
1926
1927 public boolean onMenuItemClick(MenuItem item) {
1928 onDownloadStartNoStream(mText, null, null, null, -1);
1929 return true;
1930 }
1931
1932 public Download(String toDownload) {
1933 mText = toDownload;
1934 }
1935 }
1936
Ben Murdoch4f75ba22009-10-27 11:48:28 +00001937 private class SetAsWallpaper extends Thread implements
1938 OnMenuItemClickListener, DialogInterface.OnCancelListener {
1939 private URL mUrl;
1940 private ProgressDialog mWallpaperProgress;
1941 private boolean mCanceled = false;
1942
1943 public SetAsWallpaper(String url) {
1944 try {
1945 mUrl = new URL(url);
1946 } catch (MalformedURLException e) {
1947 mUrl = null;
1948 }
1949 }
1950
1951 public void onCancel(DialogInterface dialog) {
1952 mCanceled = true;
1953 }
1954
1955 public boolean onMenuItemClick(MenuItem item) {
1956 if (mUrl != null) {
1957 // The user may have tried to set a image with a large file size as their
1958 // background so it may take a few moments to perform the operation. Display
1959 // a progress spinner while it is working.
1960 mWallpaperProgress = new ProgressDialog(BrowserActivity.this);
1961 mWallpaperProgress.setIndeterminate(true);
1962 mWallpaperProgress.setMessage(getText(R.string.progress_dialog_setting_wallpaper));
1963 mWallpaperProgress.setCancelable(true);
1964 mWallpaperProgress.setOnCancelListener(this);
1965 mWallpaperProgress.show();
1966 start();
1967 }
1968 return true;
1969 }
1970
Michael Kolbe0a36662010-06-29 10:37:12 -07001971 @Override
Ben Murdoch4f75ba22009-10-27 11:48:28 +00001972 public void run() {
1973 Drawable oldWallpaper = BrowserActivity.this.getWallpaper();
1974 try {
1975 // TODO: This will cause the resource to be downloaded again, when we
1976 // should in most cases be able to grab it from the cache. To fix this
1977 // we should query WebCore to see if we can access a cached version and
1978 // instead open an input stream on that. This pattern could also be used
1979 // in the download manager where the same problem exists.
1980 InputStream inputstream = mUrl.openStream();
1981 if (inputstream != null) {
1982 setWallpaper(inputstream);
1983 }
1984 } catch (IOException e) {
1985 Log.e(LOGTAG, "Unable to set new wallpaper");
1986 // Act as though the user canceled the operation so we try to
1987 // restore the old wallpaper.
1988 mCanceled = true;
1989 }
1990
1991 if (mCanceled) {
1992 // Restore the old wallpaper if the user cancelled whilst we were setting
1993 // the new wallpaper.
1994 int width = oldWallpaper.getIntrinsicWidth();
1995 int height = oldWallpaper.getIntrinsicHeight();
1996 Bitmap bm = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
1997 Canvas canvas = new Canvas(bm);
1998 oldWallpaper.setBounds(0, 0, width, height);
1999 oldWallpaper.draw(canvas);
2000 try {
2001 setWallpaper(bm);
2002 } catch (IOException e) {
2003 Log.e(LOGTAG, "Unable to restore old wallpaper.");
2004 }
2005 mCanceled = false;
2006 }
2007
2008 if (mWallpaperProgress.isShowing()) {
2009 mWallpaperProgress.dismiss();
2010 }
2011 }
2012 }
2013
The Android Open Source Project0c908882009-03-03 19:32:16 -08002014 private void copy(CharSequence text) {
Dianne Hackborn80f32622010-08-05 14:17:53 -07002015 ClipboardManager cm = (ClipboardManager)getSystemService(Context.CLIPBOARD_SERVICE);
2016 cm.setText(text);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002017 }
2018
2019 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08002020 * Resets the browser title-view to whatever it must be
2021 * (for example, if we had a loading error)
2022 * When we have a new page, we call resetTitle, when we
2023 * have to reset the titlebar to whatever it used to be
2024 * (for example, if the user chose to stop loading), we
2025 * call resetTitleAndRevertLockIcon.
2026 */
2027 /* package */ void resetTitleAndRevertLockIcon() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002028 mTabControl.getCurrentTab().revertLockIcon();
2029 updateLockIconToLatest();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002030 resetTitleIconAndProgress();
2031 }
2032
2033 /**
2034 * Reset the title, favicon, and progress.
2035 */
2036 private void resetTitleIconAndProgress() {
2037 WebView current = mTabControl.getCurrentWebView();
2038 if (current == null) {
2039 return;
2040 }
2041 resetTitleAndIcon(current);
2042 int progress = current.getProgress();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002043 current.getWebChromeClient().onProgressChanged(current, progress);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002044 }
2045
2046 // Reset the title and the icon based on the given item.
2047 private void resetTitleAndIcon(WebView view) {
2048 WebHistoryItem item = view.copyBackForwardList().getCurrentItem();
2049 if (item != null) {
Leon Scroggins68579392009-09-15 15:31:54 -04002050 setUrlTitle(item.getUrl(), item.getTitle());
The Android Open Source Project0c908882009-03-03 19:32:16 -08002051 setFavicon(item.getFavicon());
2052 } else {
Leon Scroggins68579392009-09-15 15:31:54 -04002053 setUrlTitle(null, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002054 setFavicon(null);
2055 }
2056 }
2057
2058 /**
2059 * Sets a title composed of the URL and the title string.
2060 * @param url The URL of the site being loaded.
2061 * @param title The title of the site being loaded.
2062 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07002063 void setUrlTitle(String url, String title) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002064 mUrl = url;
2065 mTitle = title;
2066
Leon Scroggins58d56c62010-01-28 15:12:40 -05002067 // If we are in voice search mode, the title has already been set.
2068 if (mTabControl.getCurrentTab().isInVoiceSearchMode()) return;
2069 mTitleBar.setDisplayTitle(url);
Michael Kolba2b2ba82010-08-04 17:54:03 -07002070 mFakeTitleBar.setDisplayTitle(url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002071 }
2072
2073 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08002074 * @param url The URL to build a title version of the URL from.
2075 * @return The title version of the URL or null if fails.
2076 * The title version of the URL can be either the URL hostname,
2077 * or the hostname with an "https://" prefix (for secure URLs),
2078 * or an empty string if, for example, the URL in question is a
2079 * file:// URL with no hostname.
2080 */
Leon Scroggins32e14a62009-06-11 10:26:34 -04002081 /* package */ static String buildTitleUrl(String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002082 String titleUrl = null;
2083
2084 if (url != null) {
2085 try {
2086 // parse the url string
2087 URL urlObj = new URL(url);
2088 if (urlObj != null) {
2089 titleUrl = "";
2090
2091 String protocol = urlObj.getProtocol();
2092 String host = urlObj.getHost();
2093
2094 if (host != null && 0 < host.length()) {
2095 titleUrl = host;
2096 if (protocol != null) {
2097 // if a secure site, add an "https://" prefix!
2098 if (protocol.equalsIgnoreCase("https")) {
2099 titleUrl = protocol + "://" + host;
2100 }
2101 }
2102 }
2103 }
2104 } catch (MalformedURLException e) {}
2105 }
2106
2107 return titleUrl;
2108 }
2109
2110 // Set the favicon in the title bar.
Grace Kloba22ac16e2009-10-07 18:00:23 -07002111 void setFavicon(Bitmap icon) {
Leon Scroggins68579392009-09-15 15:31:54 -04002112 mTitleBar.setFavicon(icon);
Michael Kolba2b2ba82010-08-04 17:54:03 -07002113 mFakeTitleBar.setFavicon(icon);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002114 }
2115
2116 /**
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002117 * Close the tab, remove its associated title bar, and adjust mTabControl's
2118 * current tab to a valid value.
Leon Scroggins1f005d32009-08-10 17:36:42 -04002119 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07002120 /* package */ void closeTab(Tab t) {
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002121 int currentIndex = mTabControl.getCurrentIndex();
2122 int removeIndex = mTabControl.getTabIndex(t);
Leon Scroggins1f005d32009-08-10 17:36:42 -04002123 mTabControl.removeTab(t);
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002124 if (currentIndex >= removeIndex && currentIndex != 0) {
2125 currentIndex--;
2126 }
2127 mTabControl.setCurrentTab(mTabControl.getTab(currentIndex));
Andrei Popescua5bf1de2009-09-23 16:39:23 +01002128 resetTitleIconAndProgress();
Leon Scroggins654899b2010-06-25 16:25:23 -04002129 updateLockIconToLatest();
Elliott Slaughtere440a882010-08-20 13:54:45 -07002130
2131 if (!mTabControl.hasAnyOpenIncognitoTabs()) {
2132 WebView.cleanupPrivateBrowsingFiles(this);
2133 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002134 }
2135
Leon Scrogginsdcc5eeb2010-02-23 17:26:37 -05002136 /* package */ void goBackOnePageOrQuit() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002137 Tab current = mTabControl.getCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002138 if (current == null) {
2139 /*
2140 * Instead of finishing the activity, simply push this to the back
2141 * of the stack and let ActivityManager to choose the foreground
2142 * activity. As BrowserActivity is singleTask, it will be always the
2143 * root of the task. So we can use either true or false for
2144 * moveTaskToBack().
2145 */
2146 moveTaskToBack(true);
Grace Kloba00d85e72009-09-23 18:50:05 -07002147 return;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002148 }
2149 WebView w = current.getWebView();
2150 if (w.canGoBack()) {
2151 w.goBack();
2152 } else {
2153 // Check to see if we are closing a window that was created by
2154 // another window. If so, we switch back to that window.
Grace Kloba22ac16e2009-10-07 18:00:23 -07002155 Tab parent = current.getParentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002156 if (parent != null) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04002157 switchToTab(mTabControl.getTabIndex(parent));
2158 // Now we close the other tab
2159 closeTab(current);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002160 } else {
2161 if (current.closeOnExit()) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002162 // force the tab's inLoad() to be false as we are going to
2163 // either finish the activity or remove the tab. This will
2164 // ensure pauseWebViewTimers() taking action.
2165 mTabControl.getCurrentTab().clearInLoad();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002166 if (mTabControl.getTabCount() == 1) {
2167 finish();
2168 return;
2169 }
Mike Reed7bfa63b2009-05-28 11:08:32 -04002170 // call pauseWebViewTimers() now, we won't be able to call
2171 // it in onPause() as the WebView won't be valid.
Grace Klobaec1b5ad2009-08-18 08:42:32 -07002172 // Temporarily change mActivityInPause to be true as
2173 // pauseWebViewTimers() will do nothing if mActivityInPause
2174 // is false.
Grace Kloba918e1d72009-08-13 14:55:06 -07002175 boolean savedState = mActivityInPause;
2176 if (savedState) {
Grace Klobaec1b5ad2009-08-18 08:42:32 -07002177 Log.e(LOGTAG, "BrowserActivity is already paused "
2178 + "while handing goBackOnePageOrQuit.");
Grace Kloba918e1d72009-08-13 14:55:06 -07002179 }
2180 mActivityInPause = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -04002181 pauseWebViewTimers();
Grace Kloba918e1d72009-08-13 14:55:06 -07002182 mActivityInPause = savedState;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002183 removeTabFromContentView(current);
2184 mTabControl.removeTab(current);
2185 }
2186 /*
2187 * Instead of finishing the activity, simply push this to the back
2188 * of the stack and let ActivityManager to choose the foreground
2189 * activity. As BrowserActivity is singleTask, it will be always the
2190 * root of the task. So we can use either true or false for
2191 * moveTaskToBack().
2192 */
2193 moveTaskToBack(true);
2194 }
2195 }
2196 }
2197
Grace Kloba22ac16e2009-10-07 18:00:23 -07002198 boolean isMenuDown() {
2199 return mMenuIsDown;
2200 }
2201
Grace Kloba5942df02009-09-18 11:48:29 -07002202 @Override
2203 public boolean onKeyDown(int keyCode, KeyEvent event) {
Leon Scrogginsf65b50d2009-12-08 10:44:28 -05002204 // Even if MENU is already held down, we need to call to super to open
2205 // the IME on long press.
2206 if (KeyEvent.KEYCODE_MENU == keyCode) {
2207 mMenuIsDown = true;
2208 return super.onKeyDown(keyCode, event);
2209 }
Grace Kloba5942df02009-09-18 11:48:29 -07002210 // The default key mode is DEFAULT_KEYS_SEARCH_LOCAL. As the MENU is
2211 // still down, we don't want to trigger the search. Pretend to consume
2212 // the key and do nothing.
2213 if (mMenuIsDown) return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002214
Grace Kloba5942df02009-09-18 11:48:29 -07002215 switch(keyCode) {
Grace Kloba5942df02009-09-18 11:48:29 -07002216 case KeyEvent.KEYCODE_SPACE:
Grace Klobada0fe552009-09-22 18:17:24 -07002217 // WebView/WebTextView handle the keys in the KeyDown. As
2218 // the Activity's shortcut keys are only handled when WebView
2219 // doesn't, have to do it in onKeyDown instead of onKeyUp.
2220 if (event.isShiftPressed()) {
2221 getTopWindow().pageUp(false);
2222 } else {
2223 getTopWindow().pageDown(false);
2224 }
Grace Kloba5942df02009-09-18 11:48:29 -07002225 return true;
2226 case KeyEvent.KEYCODE_BACK:
2227 if (event.getRepeatCount() == 0) {
2228 event.startTracking();
2229 return true;
2230 } else if (mCustomView == null && mActiveTabsPage == null
Michael Kolbe421c242010-10-04 19:29:01 -07002231 && mComboView == null
Grace Kloba5942df02009-09-18 11:48:29 -07002232 && event.isLongPress()) {
Michael Kolbe421c242010-10-04 19:29:01 -07002233 bookmarksOrHistoryPicker(true);
Grace Kloba5942df02009-09-18 11:48:29 -07002234 return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002235 }
Grace Kloba5942df02009-09-18 11:48:29 -07002236 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002237 }
Grace Kloba5942df02009-09-18 11:48:29 -07002238 return super.onKeyDown(keyCode, event);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002239 }
2240
Grace Kloba5942df02009-09-18 11:48:29 -07002241 @Override
2242 public boolean onKeyUp(int keyCode, KeyEvent event) {
2243 switch(keyCode) {
2244 case KeyEvent.KEYCODE_MENU:
2245 mMenuIsDown = false;
2246 break;
Grace Kloba5942df02009-09-18 11:48:29 -07002247 case KeyEvent.KEYCODE_BACK:
2248 if (event.isTracking() && !event.isCanceled()) {
2249 if (mCustomView != null) {
2250 // if a custom view is showing, hide it
Grace Kloba22ac16e2009-10-07 18:00:23 -07002251 mTabControl.getCurrentWebView().getWebChromeClient()
2252 .onHideCustomView();
Grace Kloba5942df02009-09-18 11:48:29 -07002253 } else if (mActiveTabsPage != null) {
2254 // if tab page is showing, hide it
2255 removeActiveTabPage(true);
Michael Kolbe421c242010-10-04 19:29:01 -07002256 } else if (mComboView != null) {
2257 removeComboView();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002258 } else {
Grace Kloba5942df02009-09-18 11:48:29 -07002259 WebView subwindow = mTabControl.getCurrentSubWindow();
2260 if (subwindow != null) {
2261 if (subwindow.canGoBack()) {
2262 subwindow.goBack();
2263 } else {
2264 dismissSubWindow(mTabControl.getCurrentTab());
2265 }
2266 } else {
2267 goBackOnePageOrQuit();
2268 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002269 }
Grace Kloba5942df02009-09-18 11:48:29 -07002270 return true;
2271 }
2272 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002273 }
Grace Kloba5942df02009-09-18 11:48:29 -07002274 return super.onKeyUp(keyCode, event);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002275 }
2276
Leon Scroggins68579392009-09-15 15:31:54 -04002277 /* package */ void stopLoading() {
Ben Murdochb7cc8b42009-09-28 10:59:09 +01002278 mDidStopLoad = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002279 resetTitleAndRevertLockIcon();
2280 WebView w = getTopWindow();
2281 w.stopLoading();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002282 // FIXME: before refactor, it is using mWebViewClient. So I keep the
2283 // same logic here. But for subwindow case, should we call into the main
2284 // WebView's onPageFinished as we never call its onPageStarted and if
2285 // the page finishes itself, we don't call onPageFinished.
2286 mTabControl.getCurrentWebView().getWebViewClient().onPageFinished(w,
2287 w.getUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08002288
2289 cancelStopToast();
2290 mStopToast = Toast
2291 .makeText(this, R.string.stopping, Toast.LENGTH_SHORT);
2292 mStopToast.show();
2293 }
2294
Grace Kloba22ac16e2009-10-07 18:00:23 -07002295 boolean didUserStopLoading() {
2296 return mDidStopLoad;
2297 }
2298
The Android Open Source Project0c908882009-03-03 19:32:16 -08002299 private void cancelStopToast() {
2300 if (mStopToast != null) {
2301 mStopToast.cancel();
2302 mStopToast = null;
2303 }
2304 }
2305
Grace Kloba22ac16e2009-10-07 18:00:23 -07002306 // called by a UI or non-UI thread to post the message
2307 public void postMessage(int what, int arg1, int arg2, Object obj,
2308 long delayMillis) {
2309 mHandler.sendMessageDelayed(mHandler.obtainMessage(what, arg1, arg2,
2310 obj), delayMillis);
2311 }
2312
2313 // called by a UI or non-UI thread to remove the message
2314 void removeMessages(int what, Object object) {
2315 mHandler.removeMessages(what, object);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002316 }
2317
2318 // public message ids
2319 public final static int LOAD_URL = 1001;
2320 public final static int STOP_LOAD = 1002;
2321
2322 // Message Ids
2323 private static final int FOCUS_NODE_HREF = 102;
Grace Kloba92c18a52009-07-31 23:48:32 -07002324 private static final int RELEASE_WAKELOCK = 107;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002325
Grace Kloba22ac16e2009-10-07 18:00:23 -07002326 static final int UPDATE_BOOKMARK_THUMBNAIL = 108;
Ben Murdoch2694e232009-09-29 09:41:11 +01002327
Ben Murdocheecb4e62010-07-06 16:30:38 +01002328 private static final int TOUCH_ICON_DOWNLOADED = 109;
2329
Michael Kolb300b7f02010-08-25 13:47:24 -07002330 private static final int OPEN_BOOKMARKS = 201;
2331
The Android Open Source Project0c908882009-03-03 19:32:16 -08002332 // Private handler for handling javascript and saving passwords
2333 private Handler mHandler = new Handler() {
2334
Michael Kolbe0a36662010-06-29 10:37:12 -07002335 @Override
The Android Open Source Project0c908882009-03-03 19:32:16 -08002336 public void handleMessage(Message msg) {
2337 switch (msg.what) {
Michael Kolb300b7f02010-08-25 13:47:24 -07002338 case OPEN_BOOKMARKS:
Michael Kolbe421c242010-10-04 19:29:01 -07002339 bookmarksOrHistoryPicker(false);
Michael Kolb300b7f02010-08-25 13:47:24 -07002340 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002341 case FOCUS_NODE_HREF:
Ben Murdoch2694e232009-09-29 09:41:11 +01002342 {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002343 String url = (String) msg.getData().get("url");
Ben Murdoch90d088c2009-11-17 18:14:04 +00002344 String title = (String) msg.getData().get("title");
The Android Open Source Project0c908882009-03-03 19:32:16 -08002345 if (url == null || url.length() == 0) {
2346 break;
2347 }
2348 HashMap focusNodeMap = (HashMap) msg.obj;
2349 WebView view = (WebView) focusNodeMap.get("webview");
2350 // Only apply the action if the top window did not change.
2351 if (getTopWindow() != view) {
2352 break;
2353 }
2354 switch (msg.arg1) {
2355 case R.id.open_context_menu_id:
2356 case R.id.view_image_context_menu_id:
Leon Scroggins92472e82010-02-17 16:32:28 -05002357 loadUrlFromContext(getTopWindow(), url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002358 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002359 case R.id.bookmark_context_menu_id:
2360 Intent intent = new Intent(BrowserActivity.this,
2361 AddBookmarkPage.class);
2362 intent.putExtra("url", url);
Ben Murdoch90d088c2009-11-17 18:14:04 +00002363 intent.putExtra("title", title);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002364 startActivity(intent);
2365 break;
2366 case R.id.share_link_context_menu_id:
Leon Scroggins3e204452010-05-10 11:06:03 -04002367 sharePage(BrowserActivity.this, title, url, null,
Leon Scroggins96afcb12009-12-10 12:35:56 -05002368 null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002369 break;
2370 case R.id.copy_link_context_menu_id:
2371 copy(url);
2372 break;
2373 case R.id.save_link_context_menu_id:
2374 case R.id.download_context_menu_id:
2375 onDownloadStartNoStream(url, null, null, null, -1);
2376 break;
2377 }
2378 break;
Ben Murdoch2694e232009-09-29 09:41:11 +01002379 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002380
2381 case LOAD_URL:
Leon Scroggins92472e82010-02-17 16:32:28 -05002382 loadUrlFromContext(getTopWindow(), (String) msg.obj);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002383 break;
2384
2385 case STOP_LOAD:
2386 stopLoading();
2387 break;
2388
The Android Open Source Project0c908882009-03-03 19:32:16 -08002389 case RELEASE_WAKELOCK:
2390 if (mWakeLock.isHeld()) {
2391 mWakeLock.release();
Grace Kloba5d0e02e2009-10-05 15:15:36 -07002392 // if we reach here, Browser should be still in the
2393 // background loading after WAKELOCK_TIMEOUT (5-min).
2394 // To avoid burning the battery, stop loading.
2395 mTabControl.stopAllLoading();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002396 }
2397 break;
Ben Murdoch2694e232009-09-29 09:41:11 +01002398
2399 case UPDATE_BOOKMARK_THUMBNAIL:
2400 WebView view = (WebView) msg.obj;
2401 if (view != null) {
2402 updateScreenshot(view);
2403 }
2404 break;
Ben Murdocheecb4e62010-07-06 16:30:38 +01002405
2406 case TOUCH_ICON_DOWNLOADED:
2407 Bundle b = msg.getData();
2408 showSaveToHomescreenDialog(b.getString("url"),
2409 b.getString("title"),
2410 (Bitmap) b.getParcelable("touchIcon"),
2411 (Bitmap) b.getParcelable("favicon"));
2412 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002413 }
2414 }
2415 };
2416
Leon Scroggins96afcb12009-12-10 12:35:56 -05002417 /**
2418 * Share a page, providing the title, url, favicon, and a screenshot. Uses
2419 * an {@link Intent} to launch the Activity chooser.
2420 * @param c Context used to launch a new Activity.
2421 * @param title Title of the page. Stored in the Intent with
Paul Westbrook03e6d392010-02-12 10:33:29 -08002422 * {@link Intent#EXTRA_SUBJECT}
Leon Scroggins96afcb12009-12-10 12:35:56 -05002423 * @param url URL of the page. Stored in the Intent with
2424 * {@link Intent#EXTRA_TEXT}
2425 * @param favicon Bitmap of the favicon for the page. Stored in the Intent
2426 * with {@link Browser#EXTRA_SHARE_FAVICON}
2427 * @param screenshot Bitmap of a screenshot of the page. Stored in the
2428 * Intent with {@link Browser#EXTRA_SHARE_SCREENSHOT}
2429 */
2430 public static final void sharePage(Context c, String title, String url,
2431 Bitmap favicon, Bitmap screenshot) {
2432 Intent send = new Intent(Intent.ACTION_SEND);
2433 send.setType("text/plain");
2434 send.putExtra(Intent.EXTRA_TEXT, url);
Paul Westbrook03e6d392010-02-12 10:33:29 -08002435 send.putExtra(Intent.EXTRA_SUBJECT, title);
Leon Scroggins96afcb12009-12-10 12:35:56 -05002436 send.putExtra(Browser.EXTRA_SHARE_FAVICON, favicon);
2437 send.putExtra(Browser.EXTRA_SHARE_SCREENSHOT, screenshot);
2438 try {
2439 c.startActivity(Intent.createChooser(send, c.getString(
2440 R.string.choosertitle_sharevia)));
2441 } catch(android.content.ActivityNotFoundException ex) {
2442 // if no app handles it, do nothing
2443 }
2444 }
2445
Leon Scroggins89c6d362009-07-15 16:54:37 -04002446 private void updateScreenshot(WebView view) {
2447 // If this is a bookmarked site, add a screenshot to the database.
2448 // FIXME: When should we update? Every time?
2449 // FIXME: Would like to make sure there is actually something to
2450 // draw, but the API for that (WebViewCore.pictureReady()) is not
2451 // currently accessible here.
Ben Murdochaac7aa62009-09-17 16:57:40 +01002452
Ben Murdoch87cc65d2010-06-29 20:34:10 +01002453 final Bitmap bm = createScreenshot(view, getDesiredThumbnailWidth(this),
2454 getDesiredThumbnailHeight(this));
Patrick Scottcb192b52010-04-14 14:38:55 -04002455 if (bm == null) {
2456 return;
Leon Scroggins89c6d362009-07-15 16:54:37 -04002457 }
Patrick Scottcb192b52010-04-14 14:38:55 -04002458
2459 final ContentResolver cr = getContentResolver();
2460 final String url = view.getUrl();
2461 final String originalUrl = view.getOriginalUrl();
2462
2463 new AsyncTask<Void, Void, Void>() {
2464 @Override
2465 protected Void doInBackground(Void... unused) {
Jeff Hamilton1a805652010-09-07 12:36:30 -07002466 Cursor cursor = null;
Patrick Scottcb192b52010-04-14 14:38:55 -04002467 try {
Jeff Hamilton1a805652010-09-07 12:36:30 -07002468 cursor = Bookmarks.queryCombinedForUrl(cr, originalUrl, url);
2469 if (cursor != null && cursor.moveToFirst()) {
2470 final ByteArrayOutputStream os = new ByteArrayOutputStream();
2471 bm.compress(Bitmap.CompressFormat.PNG, 100, os);
2472
2473 ContentValues values = new ContentValues();
2474 values.put(Images.THUMBNAIL, os.toByteArray());
2475 values.put(Images.URL, cursor.getString(0));
2476
2477 do {
2478 cr.update(Images.CONTENT_URI, values, null, null);
2479 } while (cursor.moveToNext());
Patrick Scottcb192b52010-04-14 14:38:55 -04002480 }
2481 } catch (IllegalStateException e) {
2482 // Ignore
2483 } finally {
Jeff Hamilton1a805652010-09-07 12:36:30 -07002484 if (cursor != null) cursor.close();
Patrick Scottcb192b52010-04-14 14:38:55 -04002485 }
2486 return null;
2487 }
2488 }.execute();
Leon Scroggins89c6d362009-07-15 16:54:37 -04002489 }
2490
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002491 /**
Leon Scrogginsf8551612009-09-24 16:06:02 -04002492 * Return the desired width for thumbnail screenshots, which are stored in
2493 * the database, and used on the bookmarks screen.
2494 * @param context Context for finding out the density of the screen.
Jeff Hamiltonf3026372010-08-19 00:12:27 -05002495 * @return desired width for thumbnail screenshot.
Leon Scrogginsf8551612009-09-24 16:06:02 -04002496 */
2497 /* package */ static int getDesiredThumbnailWidth(Context context) {
Jeff Hamiltonf3026372010-08-19 00:12:27 -05002498 return context.getResources().getDimensionPixelOffset(R.dimen.bookmarkThumbnailWidth);
Leon Scrogginsf8551612009-09-24 16:06:02 -04002499 }
2500
2501 /**
2502 * Return the desired height for thumbnail screenshots, which are stored in
2503 * the database, and used on the bookmarks screen.
2504 * @param context Context for finding out the density of the screen.
Jeff Hamiltonf3026372010-08-19 00:12:27 -05002505 * @return desired height for thumbnail screenshot.
Leon Scrogginsf8551612009-09-24 16:06:02 -04002506 */
2507 /* package */ static int getDesiredThumbnailHeight(Context context) {
Jeff Hamiltonf3026372010-08-19 00:12:27 -05002508 return context.getResources().getDimensionPixelOffset(R.dimen.bookmarkThumbnailHeight);
Leon Scrogginsf8551612009-09-24 16:06:02 -04002509 }
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002510
Ben Murdoch87cc65d2010-06-29 20:34:10 +01002511 private Bitmap createScreenshot(WebView view, int width, int height) {
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002512 Picture thumbnail = view.capturePicture();
Leon Scroggins45800572009-09-29 16:38:47 -04002513 if (thumbnail == null) {
2514 return null;
2515 }
Ben Murdoch87cc65d2010-06-29 20:34:10 +01002516 Bitmap bm = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002517 Canvas canvas = new Canvas(bm);
2518 // May need to tweak these values to determine what is the
2519 // best scale factor
Ben Murdoch2694e232009-09-29 09:41:11 +01002520 int thumbnailWidth = thumbnail.getWidth();
Ben Murdochae59c3f2009-10-20 18:30:28 +01002521 int thumbnailHeight = thumbnail.getHeight();
2522 float scaleFactorX = 1.0f;
2523 float scaleFactorY = 1.0f;
Ben Murdoch2694e232009-09-29 09:41:11 +01002524 if (thumbnailWidth > 0) {
Ben Murdoch87cc65d2010-06-29 20:34:10 +01002525 scaleFactorX = (float) width / (float)thumbnailWidth;
Ben Murdochae59c3f2009-10-20 18:30:28 +01002526 } else {
2527 return null;
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002528 }
Ben Murdochae59c3f2009-10-20 18:30:28 +01002529
2530 if (view.getWidth() > view.getHeight() &&
2531 thumbnailHeight < view.getHeight() && thumbnailHeight > 0) {
2532 // If the device is in landscape and the page is shorter
2533 // than the height of the view, stretch the thumbnail to fill the
2534 // space.
Ben Murdoch87cc65d2010-06-29 20:34:10 +01002535 scaleFactorY = (float) height / (float)thumbnailHeight;
Ben Murdochae59c3f2009-10-20 18:30:28 +01002536 } else {
2537 // In the portrait case, this looks nice.
2538 scaleFactorY = scaleFactorX;
2539 }
2540
2541 canvas.scale(scaleFactorX, scaleFactorY);
2542
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002543 thumbnail.draw(canvas);
2544 return bm;
2545 }
2546
The Android Open Source Project0c908882009-03-03 19:32:16 -08002547 // -------------------------------------------------------------------------
Grace Kloba22ac16e2009-10-07 18:00:23 -07002548 // Helper function for WebViewClient.
The Android Open Source Project0c908882009-03-03 19:32:16 -08002549 //-------------------------------------------------------------------------
2550
2551 // Use in overrideUrlLoading
2552 /* package */ final static String SCHEME_WTAI = "wtai://wp/";
2553 /* package */ final static String SCHEME_WTAI_MC = "wtai://wp/mc;";
2554 /* package */ final static String SCHEME_WTAI_SD = "wtai://wp/sd;";
2555 /* package */ final static String SCHEME_WTAI_AP = "wtai://wp/ap;";
2556
Leon Scroggins92472e82010-02-17 16:32:28 -05002557 // Keep this initial progress in sync with initialProgressValue (* 100)
2558 // in ProgressTracker.cpp
2559 private final static int INITIAL_PROGRESS = 10;
2560
Grace Kloba22ac16e2009-10-07 18:00:23 -07002561 void onPageStarted(WebView view, String url, Bitmap favicon) {
2562 // when BrowserActivity just starts, onPageStarted may be called before
2563 // onResume as it is triggered from onCreate. Call resumeWebViewTimers
2564 // to start the timer. As we won't switch tabs while an activity is in
2565 // pause state, we can ensure calling resume and pause in pair.
2566 if (mActivityInPause) resumeWebViewTimers();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002567
Grace Kloba22ac16e2009-10-07 18:00:23 -07002568 resetLockIcon(url);
2569 setUrlTitle(url, null);
2570 setFavicon(favicon);
Leon Scroggins8cf8f682009-11-04 11:13:50 -08002571 // Show some progress so that the user knows the page is beginning to
2572 // load
Leon Scroggins92472e82010-02-17 16:32:28 -05002573 onProgressChanged(view, INITIAL_PROGRESS);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002574 mDidStopLoad = false;
Grace Kloba22ac16e2009-10-07 18:00:23 -07002575 if (!mIsNetworkUp) createAndShowNetworkDialog();
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04002576 endActionMode();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002577 if (mSettings.isTracing()) {
2578 String host;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002579 try {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002580 WebAddress uri = new WebAddress(url);
2581 host = uri.mHost;
2582 } catch (android.net.ParseException ex) {
2583 host = "browser";
The Android Open Source Project0c908882009-03-03 19:32:16 -08002584 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002585 host = host.replace('.', '_');
2586 host += ".trace";
2587 mInTrace = true;
2588 Debug.startMethodTracing(host, 20 * 1024 * 1024);
2589 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002590
Grace Kloba22ac16e2009-10-07 18:00:23 -07002591 // Performance probe
2592 if (false) {
2593 mStart = SystemClock.uptimeMillis();
2594 mProcessStart = Process.getElapsedCpuTime();
2595 long[] sysCpu = new long[7];
2596 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2597 sysCpu, null)) {
2598 mUserStart = sysCpu[0] + sysCpu[1];
2599 mSystemStart = sysCpu[2];
2600 mIdleStart = sysCpu[3];
2601 mIrqStart = sysCpu[4] + sysCpu[5] + sysCpu[6];
2602 }
2603 mUiStart = SystemClock.currentThreadTimeMillis();
2604 }
2605 }
2606
2607 void onPageFinished(WebView view, String url) {
2608 // Reset the title and icon in case we stopped a provisional load.
2609 resetTitleAndIcon(view);
2610 // Update the lock icon image only once we are done loading
2611 updateLockIconToLatest();
2612 // pause the WebView timer and release the wake lock if it is finished
2613 // while BrowserActivity is in pause state.
2614 if (mActivityInPause && pauseWebViewTimers()) {
2615 if (mWakeLock.isHeld()) {
2616 mHandler.removeMessages(RELEASE_WAKELOCK);
2617 mWakeLock.release();
2618 }
2619 }
2620
2621 // Performance probe
2622 if (false) {
2623 long[] sysCpu = new long[7];
2624 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2625 sysCpu, null)) {
2626 String uiInfo = "UI thread used "
2627 + (SystemClock.currentThreadTimeMillis() - mUiStart)
2628 + " ms";
2629 if (LOGD_ENABLED) {
2630 Log.d(LOGTAG, uiInfo);
2631 }
2632 //The string that gets written to the log
2633 String performanceString = "It took total "
2634 + (SystemClock.uptimeMillis() - mStart)
2635 + " ms clock time to load the page."
2636 + "\nbrowser process used "
2637 + (Process.getElapsedCpuTime() - mProcessStart)
2638 + " ms, user processes used "
2639 + (sysCpu[0] + sysCpu[1] - mUserStart) * 10
2640 + " ms, kernel used "
2641 + (sysCpu[2] - mSystemStart) * 10
2642 + " ms, idle took " + (sysCpu[3] - mIdleStart) * 10
2643 + " ms and irq took "
2644 + (sysCpu[4] + sysCpu[5] + sysCpu[6] - mIrqStart)
2645 * 10 + " ms, " + uiInfo;
2646 if (LOGD_ENABLED) {
2647 Log.d(LOGTAG, performanceString + "\nWebpage: " + url);
2648 }
2649 if (url != null) {
2650 // strip the url to maintain consistency
2651 String newUrl = new String(url);
2652 if (newUrl.startsWith("http://www.")) {
2653 newUrl = newUrl.substring(11);
2654 } else if (newUrl.startsWith("http://")) {
2655 newUrl = newUrl.substring(7);
2656 } else if (newUrl.startsWith("https://www.")) {
2657 newUrl = newUrl.substring(12);
2658 } else if (newUrl.startsWith("https://")) {
2659 newUrl = newUrl.substring(8);
2660 }
2661 if (LOGD_ENABLED) {
2662 Log.d(LOGTAG, newUrl + " loaded");
2663 }
Grace Kloba5b078b52009-06-24 20:23:41 -07002664 }
2665 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002666 }
Grace Kloba5b078b52009-06-24 20:23:41 -07002667
Grace Kloba22ac16e2009-10-07 18:00:23 -07002668 if (mInTrace) {
2669 mInTrace = false;
2670 Debug.stopMethodTracing();
2671 }
2672 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002673
Grace Klobae7fe26b2010-06-28 16:23:33 -07002674 private void closeEmptyChildTab() {
2675 Tab current = mTabControl.getCurrentTab();
2676 if (current != null
2677 && current.getWebView().copyBackForwardList().getSize() == 0) {
2678 Tab parent = current.getParentTab();
2679 if (parent != null) {
2680 switchToTab(mTabControl.getTabIndex(parent));
2681 closeTab(current);
2682 }
2683 }
2684 }
2685
Grace Kloba22ac16e2009-10-07 18:00:23 -07002686 boolean shouldOverrideUrlLoading(WebView view, String url) {
Jeff Hamilton47654f42010-09-07 09:57:51 -05002687 if (view.isPrivateBrowsingEnabled()) {
2688 // Don't allow urls to leave the browser app when in private browsing mode
2689 loadUrl(view, url);
2690 return true;
2691 }
2692
Grace Kloba22ac16e2009-10-07 18:00:23 -07002693 if (url.startsWith(SCHEME_WTAI)) {
2694 // wtai://wp/mc;number
2695 // number=string(phone-number)
2696 if (url.startsWith(SCHEME_WTAI_MC)) {
2697 Intent intent = new Intent(Intent.ACTION_VIEW,
2698 Uri.parse(WebView.SCHEME_TEL +
2699 url.substring(SCHEME_WTAI_MC.length())));
2700 startActivity(intent);
Grace Klobae7fe26b2010-06-28 16:23:33 -07002701 // before leaving BrowserActivity, close the empty child tab.
2702 // If a new tab is created through JavaScript open to load this
2703 // url, we would like to close it as we will load this url in a
2704 // different Activity.
2705 closeEmptyChildTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002706 return true;
2707 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002708 // wtai://wp/sd;dtmf
2709 // dtmf=string(dialstring)
2710 if (url.startsWith(SCHEME_WTAI_SD)) {
2711 // TODO: only send when there is active voice connection
2712 return false;
2713 }
2714 // wtai://wp/ap;number;name
2715 // number=string(phone-number)
2716 // name=string
2717 if (url.startsWith(SCHEME_WTAI_AP)) {
2718 // TODO
2719 return false;
2720 }
2721 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002722
Grace Kloba22ac16e2009-10-07 18:00:23 -07002723 // The "about:" schemes are internal to the browser; don't want these to
2724 // be dispatched to other apps.
2725 if (url.startsWith("about:")) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002726 return false;
2727 }
2728
Jeff Davidson43610292010-07-16 16:03:58 -07002729 // If this is a Google search, attempt to add an RLZ string (if one isn't already present).
2730 if (rlzProviderPresent()) {
2731 Uri siteUri = Uri.parse(url);
2732 if (needsRlzString(siteUri)) {
2733 String rlz = null;
2734 Cursor cur = null;
2735 try {
2736 cur = getContentResolver().query(getRlzUri(), null, null, null, null);
2737 if (cur != null && cur.moveToFirst() && !cur.isNull(0)) {
2738 url = siteUri.buildUpon()
2739 .appendQueryParameter("rlz", cur.getString(0))
2740 .build().toString();
2741 }
2742 } finally {
2743 if (cur != null) {
2744 cur.close();
2745 }
2746 }
2747 loadUrl(view, url);
2748 return true;
2749 }
2750 }
2751
Grace Kloba22ac16e2009-10-07 18:00:23 -07002752 Intent intent;
2753 // perform generic parsing of the URI to turn it into an Intent.
2754 try {
2755 intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME);
2756 } catch (URISyntaxException ex) {
2757 Log.w("Browser", "Bad URI " + url + ": " + ex.getMessage());
2758 return false;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002759 }
2760
Grace Kloba22ac16e2009-10-07 18:00:23 -07002761 // check whether the intent can be resolved. If not, we will see
2762 // whether we can download it from the Market.
2763 if (getPackageManager().resolveActivity(intent, 0) == null) {
2764 String packagename = intent.getPackage();
2765 if (packagename != null) {
2766 intent = new Intent(Intent.ACTION_VIEW, Uri
2767 .parse("market://search?q=pname:" + packagename));
2768 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2769 startActivity(intent);
Grace Klobae7fe26b2010-06-28 16:23:33 -07002770 // before leaving BrowserActivity, close the empty child tab.
2771 // If a new tab is created through JavaScript open to load this
2772 // url, we would like to close it as we will load this url in a
2773 // different Activity.
2774 closeEmptyChildTab();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002775 return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002776 } else {
2777 return false;
2778 }
2779 }
2780
Grace Kloba22ac16e2009-10-07 18:00:23 -07002781 // sanitize the Intent, ensuring web pages can not bypass browser
2782 // security (only access to BROWSABLE activities).
2783 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2784 intent.setComponent(null);
2785 try {
2786 if (startActivityIfNeeded(intent, -1)) {
Grace Klobae7fe26b2010-06-28 16:23:33 -07002787 // before leaving BrowserActivity, close the empty child tab.
2788 // If a new tab is created through JavaScript open to load this
2789 // url, we would like to close it as we will load this url in a
2790 // different Activity.
2791 closeEmptyChildTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002792 return true;
2793 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002794 } catch (ActivityNotFoundException ex) {
2795 // ignore the error. If no application can handle the URL,
2796 // eg about:blank, assume the browser can handle it.
2797 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002798
Grace Kloba22ac16e2009-10-07 18:00:23 -07002799 if (mMenuIsDown) {
Michael Kolb68792c82010-08-09 16:39:18 -07002800 openTab(url, false);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002801 closeOptionsMenu();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002802 return true;
2803 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002804 return false;
2805 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002806
Jeff Davidson43610292010-07-16 16:03:58 -07002807 // Determine whether the RLZ provider is present on the system.
2808 private boolean rlzProviderPresent() {
2809 if (mIsProviderPresent == null) {
2810 PackageManager pm = getPackageManager();
2811 mIsProviderPresent = pm.resolveContentProvider(BrowserSettings.RLZ_PROVIDER, 0) != null;
2812 }
2813 return mIsProviderPresent;
2814 }
2815
2816 // Retrieve the RLZ access point string and cache the URI used to retrieve RLZ values.
2817 private Uri getRlzUri() {
2818 if (mRlzUri == null) {
2819 String ap = getResources().getString(R.string.rlz_access_point);
2820 mRlzUri = Uri.withAppendedPath(BrowserSettings.RLZ_PROVIDER_URI, ap);
2821 }
2822 return mRlzUri;
2823 }
2824
2825 // Determine if this URI appears to be for a Google search and does not have an RLZ parameter.
2826 // Taken largely from Chrome source, src/chrome/browser/google_url_tracker.cc
2827 private static boolean needsRlzString(Uri uri) {
Bill Napierc50e71a2010-08-27 14:03:03 -07002828 String scheme = uri.getScheme();
2829 if (("http".equals(scheme) || "https".equals(scheme)) &&
2830 (uri.getQueryParameter("q") != null) && (uri.getQueryParameter("rlz") == null)) {
Jeff Davidson43610292010-07-16 16:03:58 -07002831 String host = uri.getHost();
2832 if (host == null) {
2833 return false;
2834 }
2835 String[] hostComponents = host.split("\\.");
2836
2837 if (hostComponents.length < 2) {
2838 return false;
2839 }
2840 int googleComponent = hostComponents.length - 2;
2841 String component = hostComponents[googleComponent];
2842 if (!"google".equals(component)) {
2843 if (hostComponents.length < 3 ||
2844 (!"co".equals(component) && !"com".equals(component))) {
2845 return false;
2846 }
2847 googleComponent = hostComponents.length - 3;
2848 if (!"google".equals(hostComponents[googleComponent])) {
2849 return false;
2850 }
2851 }
2852
2853 // Google corp network handling.
2854 if (googleComponent > 0 && "corp".equals(hostComponents[googleComponent - 1])) {
2855 return false;
2856 }
2857
2858 return true;
2859 }
2860 return false;
2861 }
2862
Grace Kloba22ac16e2009-10-07 18:00:23 -07002863 // -------------------------------------------------------------------------
2864 // Helper function for WebChromeClient
2865 // -------------------------------------------------------------------------
The Android Open Source Project0c908882009-03-03 19:32:16 -08002866
Grace Kloba22ac16e2009-10-07 18:00:23 -07002867 void onProgressChanged(WebView view, int newProgress) {
Michael Kolba2b2ba82010-08-04 17:54:03 -07002868
2869 // On the phone, the fake title bar will always cover up the
2870 // regular title bar (or the regular one is offscreen), so only the
2871 // fake title bar needs to change its progress
2872 mFakeTitleBar.setProgress(newProgress);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002873
Grace Kloba22ac16e2009-10-07 18:00:23 -07002874 if (newProgress == 100) {
2875 // onProgressChanged() may continue to be called after the main
2876 // frame has finished loading, as any remaining sub frames continue
2877 // to load. We'll only get called once though with newProgress as
2878 // 100 when everything is loaded. (onPageFinished is called once
2879 // when the main frame completes loading regardless of the state of
2880 // any sub frames so calls to onProgressChanges may continue after
2881 // onPageFinished has executed)
2882 if (mInLoad) {
2883 mInLoad = false;
Leon Scrogginsa27ff192009-09-14 12:58:04 -04002884 updateInLoadMenuItems();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002885 // If the options menu is open, leave the title bar
2886 if (!mOptionsMenuOpen || !mIconView) {
2887 hideFakeTitleBar();
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07002888 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002889 }
Leon Scrogginsaa37e7f2010-03-05 11:51:20 -05002890 } else {
2891 if (!mInLoad) {
2892 // onPageFinished may have already been called but a subframe is
2893 // still loading and updating the progress. Reset mInLoad and
2894 // update the menu items.
2895 mInLoad = true;
2896 updateInLoadMenuItems();
2897 }
2898 // When the page first begins to load, the Activity may still be
2899 // paused, in which case showFakeTitleBar will do nothing. Call
2900 // again as the page continues to load so that it will be shown.
2901 // (Calling it will the fake title bar is already showing will also
2902 // do nothing.
Grace Kloba22ac16e2009-10-07 18:00:23 -07002903 if (!mOptionsMenuOpen || mIconView) {
2904 // This page has begun to load, so show the title bar
2905 showFakeTitleBar();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002906 }
2907 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002908 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002909
Grace Kloba22ac16e2009-10-07 18:00:23 -07002910 void onShowCustomView(View view, WebChromeClient.CustomViewCallback callback) {
Derek Sollenberger8ff57db2009-12-08 15:39:55 -05002911 // if a view already exists then immediately terminate the new one
2912 if (mCustomView != null) {
2913 callback.onCustomViewHidden();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002914 return;
Derek Sollenberger8ff57db2009-12-08 15:39:55 -05002915 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002916
2917 // Add the custom view to its container.
2918 mCustomViewContainer.addView(view, COVER_SCREEN_GRAVITY_CENTER);
2919 mCustomView = view;
2920 mCustomViewCallback = callback;
2921 // Save the menu state and set it to empty while the custom
2922 // view is showing.
2923 mOldMenuState = mMenuState;
2924 mMenuState = EMPTY_MENU;
2925 // Hide the content view.
2926 mContentView.setVisibility(View.GONE);
2927 // Finally show the custom view container.
Andrei Popescu163ab742009-10-20 17:58:23 +01002928 setStatusBarVisibility(false);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002929 mCustomViewContainer.setVisibility(View.VISIBLE);
2930 mCustomViewContainer.bringToFront();
2931 }
2932
2933 void onHideCustomView() {
2934 if (mCustomView == null)
2935 return;
2936
2937 // Hide the custom view.
2938 mCustomView.setVisibility(View.GONE);
2939 // Remove the custom view from its container.
2940 mCustomViewContainer.removeView(mCustomView);
2941 mCustomView = null;
2942 // Reset the old menu state.
2943 mMenuState = mOldMenuState;
2944 mOldMenuState = EMPTY_MENU;
2945 mCustomViewContainer.setVisibility(View.GONE);
2946 mCustomViewCallback.onCustomViewHidden();
2947 // Show the content view.
Andrei Popescu163ab742009-10-20 17:58:23 +01002948 setStatusBarVisibility(true);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002949 mContentView.setVisibility(View.VISIBLE);
2950 }
2951
2952 Bitmap getDefaultVideoPoster() {
2953 if (mDefaultVideoPoster == null) {
2954 mDefaultVideoPoster = BitmapFactory.decodeResource(
2955 getResources(), R.drawable.default_video_poster);
Patrick Scott3918d442009-08-04 13:22:29 -04002956 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002957 return mDefaultVideoPoster;
2958 }
Patrick Scott3918d442009-08-04 13:22:29 -04002959
Grace Kloba22ac16e2009-10-07 18:00:23 -07002960 View getVideoLoadingProgressView() {
2961 if (mVideoProgressView == null) {
2962 LayoutInflater inflater = LayoutInflater.from(BrowserActivity.this);
2963 mVideoProgressView = inflater.inflate(
2964 R.layout.video_loading_progress, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002965 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002966 return mVideoProgressView;
2967 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002968
Leon Scroggins8d5fa432009-10-02 15:55:59 -04002969 /*
2970 * The Object used to inform the WebView of the file to upload.
2971 */
2972 private ValueCallback<Uri> mUploadMessage;
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002973 private String mCameraFilePath;
Leon Scroggins8d5fa432009-10-02 15:55:59 -04002974
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002975 void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
2976
2977 final String imageMimeType = "image/*";
Ben Murdoch6af492a2010-06-15 12:38:17 +01002978 final String videoMimeType = "video/*";
Ben Murdoch039bd472010-07-21 21:26:57 +01002979 final String audioMimeType = "audio/*";
Ben Murdochb50d7402010-07-16 12:42:22 +01002980 final String mediaSourceKey = "capture";
Ben Murdoch6af492a2010-06-15 12:38:17 +01002981 final String mediaSourceValueCamera = "camera";
Ben Murdochb50d7402010-07-16 12:42:22 +01002982 final String mediaSourceValueFileSystem = "filesystem";
Ben Murdoch6af492a2010-06-15 12:38:17 +01002983 final String mediaSourceValueCamcorder = "camcorder";
Ben Murdoch039bd472010-07-21 21:26:57 +01002984 final String mediaSourceValueMicrophone = "microphone";
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002985
Ben Murdoch039bd472010-07-21 21:26:57 +01002986 // media source can be 'filesystem' or 'camera' or 'camcorder' or 'microphone'.
Ben Murdoch6af492a2010-06-15 12:38:17 +01002987 String mediaSource = "";
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002988
Ben Murdoch6af492a2010-06-15 12:38:17 +01002989 // We add the camera intent if there was no accept type (or '*/*' or 'image/*').
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002990 boolean addCameraIntent = true;
Ben Murdoch6af492a2010-06-15 12:38:17 +01002991 // We add the camcorder intent if there was no accept type (or '*/*' or 'video/*').
2992 boolean addCamcorderIntent = true;
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002993
Ben Murdoch6af492a2010-06-15 12:38:17 +01002994 if (mUploadMessage != null) {
2995 // Already a file picker operation in progress.
2996 return;
2997 }
2998
Grace Kloba22ac16e2009-10-07 18:00:23 -07002999 mUploadMessage = uploadMsg;
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003000
3001 // Parse the accept type.
3002 String params[] = acceptType.split(";");
3003 String mimeType = params[0];
3004
3005 for (String p : params) {
3006 String[] keyValue = p.split("=");
3007 if (keyValue.length == 2) {
3008 // Process key=value parameters.
Ben Murdoch6af492a2010-06-15 12:38:17 +01003009 if (mediaSourceKey.equals(keyValue[0])) {
3010 mediaSource = keyValue[1];
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003011 }
3012 }
3013 }
3014
3015 // This intent will display the standard OPENABLE file picker.
Grace Kloba22ac16e2009-10-07 18:00:23 -07003016 Intent i = new Intent(Intent.ACTION_GET_CONTENT);
3017 i.addCategory(Intent.CATEGORY_OPENABLE);
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003018
3019 // Create an intent to add to the standard file picker that will
3020 // capture an image from the camera. We'll combine this intent with
3021 // the standard OPENABLE picker unless the web developer specifically
3022 // requested the camera or gallery be opened by passing a parameter
3023 // in the accept type.
3024 Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
3025 File externalDataDir = Environment.getExternalStoragePublicDirectory(
3026 Environment.DIRECTORY_DCIM);
3027 File cameraDataDir = new File(externalDataDir.getAbsolutePath() +
3028 File.separator + "browser-photos");
3029 cameraDataDir.mkdirs();
3030 mCameraFilePath = cameraDataDir.getAbsolutePath() + File.separator +
3031 System.currentTimeMillis() + ".jpg";
3032 cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(mCameraFilePath)));
3033
Ben Murdoch6af492a2010-06-15 12:38:17 +01003034 Intent camcorderIntent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
3035
Ben Murdoch039bd472010-07-21 21:26:57 +01003036 Intent soundRecIntent = new Intent(MediaStore.Audio.Media.RECORD_SOUND_ACTION);
3037
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003038 if (mimeType.equals(imageMimeType)) {
3039 i.setType(imageMimeType);
Ben Murdoch6af492a2010-06-15 12:38:17 +01003040 addCamcorderIntent = false;
3041 if (mediaSource.equals(mediaSourceValueCamera)) {
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003042 // Specified 'image/*' and requested the camera, so go ahead and launch the camera
3043 // directly.
3044 BrowserActivity.this.startActivityForResult(cameraIntent, FILE_SELECTED);
3045 return;
Ben Murdochb50d7402010-07-16 12:42:22 +01003046 } else if (mediaSource.equals(mediaSourceValueFileSystem)) {
3047 // Specified filesytem as the source, so don't want to consider the camera.
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003048 addCameraIntent = false;
3049 }
Ben Murdoch6af492a2010-06-15 12:38:17 +01003050 } else if (mimeType.equals(videoMimeType)) {
3051 i.setType(videoMimeType);
3052 addCameraIntent = false;
3053 // The camcorder saves it's own file and returns it to us in the intent, so
3054 // we don't need to generate one here.
3055 mCameraFilePath = null;
3056
3057 if (mediaSource.equals(mediaSourceValueCamcorder)) {
Ben Murdoch039bd472010-07-21 21:26:57 +01003058 // Specified 'video/*' and requested the camcorder, so go ahead and launch the
3059 // camcorder directly.
Ben Murdoch6af492a2010-06-15 12:38:17 +01003060 BrowserActivity.this.startActivityForResult(camcorderIntent, FILE_SELECTED);
3061 return;
Ben Murdochb50d7402010-07-16 12:42:22 +01003062 } else if (mediaSource.equals(mediaSourceValueFileSystem)) {
3063 // Specified filesystem as the source, so don't want to consider the camcorder.
Ben Murdoch6af492a2010-06-15 12:38:17 +01003064 addCamcorderIntent = false;
3065 }
Ben Murdoch039bd472010-07-21 21:26:57 +01003066 } else if (mimeType.equals(audioMimeType)) {
3067 i.setType(audioMimeType);
3068 addCameraIntent = false;
3069 addCamcorderIntent = false;
3070 if (mediaSource.equals(mediaSourceValueMicrophone)) {
3071 // Specified 'audio/*' and requested microphone, so go ahead and launch the sound
3072 // recorder.
3073 BrowserActivity.this.startActivityForResult(soundRecIntent, FILE_SELECTED);
3074 return;
3075 }
3076 // On a default system, there is no single option to open an audio "gallery". Both the
3077 // sound recorder and music browser respond to the OPENABLE/audio/* intent unlike the
3078 // image/* and video/* OPENABLE intents where the image / video gallery are the only
3079 // respondants (and so the user is not prompted by default).
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003080 } else {
3081 i.setType("*/*");
3082 }
3083
Ben Murdoch6af492a2010-06-15 12:38:17 +01003084 // Combine the chooser and the extra choices (like camera or camcorder)
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003085 Intent chooser = new Intent(Intent.ACTION_CHOOSER);
3086 chooser.putExtra(Intent.EXTRA_INTENT, i);
3087
Ben Murdoch6af492a2010-06-15 12:38:17 +01003088 Vector<Intent> extraInitialIntents = new Vector<Intent>(0);
3089
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003090 if (addCameraIntent) {
Ben Murdoch6af492a2010-06-15 12:38:17 +01003091 extraInitialIntents.add(cameraIntent);
3092 }
3093
3094 if (addCamcorderIntent) {
3095 extraInitialIntents.add(camcorderIntent);
3096 }
3097
3098 if (extraInitialIntents.size() > 0) {
3099 Intent[] extraIntents = new Intent[extraInitialIntents.size()];
3100 chooser.putExtra(Intent.EXTRA_INITIAL_INTENTS, extraInitialIntents.toArray(extraIntents));
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003101 }
3102
3103 chooser.putExtra(Intent.EXTRA_TITLE, getString(R.string.choose_upload));
3104 BrowserActivity.this.startActivityForResult(chooser, FILE_SELECTED);
Grace Kloba22ac16e2009-10-07 18:00:23 -07003105 }
3106
3107 // -------------------------------------------------------------------------
3108 // Implement functions for DownloadListener
3109 // -------------------------------------------------------------------------
3110
The Android Open Source Project0c908882009-03-03 19:32:16 -08003111 /**
3112 * Notify the host application a download should be done, or that
3113 * the data should be streamed if a streaming viewer is available.
3114 * @param url The full url to the content that should be downloaded
3115 * @param contentDisposition Content-disposition http header, if
3116 * present.
3117 * @param mimetype The mimetype of the content reported by the server
3118 * @param contentLength The file size reported by the server
3119 */
3120 public void onDownloadStart(String url, String userAgent,
3121 String contentDisposition, String mimetype, long contentLength) {
3122 // if we're dealing wih A/V content that's not explicitly marked
3123 // for download, check if it's streamable.
3124 if (contentDisposition == null
Patrick Scotte1fb9662009-08-31 14:31:52 -04003125 || !contentDisposition.regionMatches(
3126 true, 0, "attachment", 0, 10)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003127 // query the package manager to see if there's a registered handler
3128 // that matches.
3129 Intent intent = new Intent(Intent.ACTION_VIEW);
3130 intent.setDataAndType(Uri.parse(url), mimetype);
Patrick Scotte1fb9662009-08-31 14:31:52 -04003131 ResolveInfo info = getPackageManager().resolveActivity(intent,
3132 PackageManager.MATCH_DEFAULT_ONLY);
3133 if (info != null) {
3134 ComponentName myName = getComponentName();
3135 // If we resolved to ourselves, we don't want to attempt to
3136 // load the url only to try and download it again.
3137 if (!myName.getPackageName().equals(
3138 info.activityInfo.packageName)
3139 || !myName.getClassName().equals(
3140 info.activityInfo.name)) {
3141 // someone (other than us) knows how to handle this mime
3142 // type with this scheme, don't download.
3143 try {
3144 startActivity(intent);
3145 return;
3146 } catch (ActivityNotFoundException ex) {
3147 if (LOGD_ENABLED) {
3148 Log.d(LOGTAG, "activity not found for " + mimetype
3149 + " over " + Uri.parse(url).getScheme(),
3150 ex);
3151 }
3152 // Best behavior is to fall back to a download in this
3153 // case
The Android Open Source Project0c908882009-03-03 19:32:16 -08003154 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003155 }
3156 }
3157 }
3158 onDownloadStartNoStream(url, userAgent, contentDisposition, mimetype, contentLength);
3159 }
3160
Kristian Monsenfa52d172010-03-25 18:29:21 +00003161 // This is to work around the fact that java.net.URI throws Exceptions
3162 // instead of just encoding URL's properly
3163 // Helper method for onDownloadStartNoStream
3164 private static String encodePath(String path) {
3165 char[] chars = path.toCharArray();
3166
3167 boolean needed = false;
3168 for (char c : chars) {
3169 if (c == '[' || c == ']') {
3170 needed = true;
3171 break;
3172 }
3173 }
3174 if (needed == false) {
3175 return path;
3176 }
3177
3178 StringBuilder sb = new StringBuilder("");
3179 for (char c : chars) {
3180 if (c == '[' || c == ']') {
3181 sb.append('%');
3182 sb.append(Integer.toHexString(c));
3183 } else {
3184 sb.append(c);
3185 }
3186 }
3187
3188 return sb.toString();
3189 }
3190
The Android Open Source Project0c908882009-03-03 19:32:16 -08003191 /**
3192 * Notify the host application a download should be done, even if there
3193 * is a streaming viewer available for thise type.
3194 * @param url The full url to the content that should be downloaded
3195 * @param contentDisposition Content-disposition http header, if
3196 * present.
3197 * @param mimetype The mimetype of the content reported by the server
3198 * @param contentLength The file size reported by the server
3199 */
3200 /*package */ void onDownloadStartNoStream(String url, String userAgent,
3201 String contentDisposition, String mimetype, long contentLength) {
3202
3203 String filename = URLUtil.guessFileName(url,
3204 contentDisposition, mimetype);
3205
3206 // Check to see if we have an SDCard
3207 String status = Environment.getExternalStorageState();
3208 if (!status.equals(Environment.MEDIA_MOUNTED)) {
3209 int title;
3210 String msg;
3211
3212 // Check to see if the SDCard is busy, same as the music app
3213 if (status.equals(Environment.MEDIA_SHARED)) {
3214 msg = getString(R.string.download_sdcard_busy_dlg_msg);
3215 title = R.string.download_sdcard_busy_dlg_title;
3216 } else {
3217 msg = getString(R.string.download_no_sdcard_dlg_msg, filename);
3218 title = R.string.download_no_sdcard_dlg_title;
3219 }
3220
3221 new AlertDialog.Builder(this)
3222 .setTitle(title)
3223 .setIcon(android.R.drawable.ic_dialog_alert)
3224 .setMessage(msg)
3225 .setPositiveButton(R.string.ok, null)
3226 .show();
3227 return;
3228 }
3229
Kristian Monsenfa52d172010-03-25 18:29:21 +00003230 // java.net.URI is a lot stricter than KURL so we have to encode some
3231 // extra characters. Fix for b 2538060 and b 1634719
3232 WebAddress webAddress;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003233 try {
Kristian Monsenfa52d172010-03-25 18:29:21 +00003234 webAddress = new WebAddress(url);
3235 webAddress.mPath = encodePath(webAddress.mPath);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003236 } catch (Exception e) {
Kristian Monsenfa52d172010-03-25 18:29:21 +00003237 // This only happens for very bad urls, we want to chatch the
3238 // exception here
3239 Log.e(LOGTAG, "Exception trying to parse url:" + url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003240 return;
3241 }
3242
3243 // XXX: Have to use the old url since the cookies were stored using the
3244 // old percent-encoded url.
3245 String cookies = CookieManager.getInstance().getCookie(url);
3246
3247 ContentValues values = new ContentValues();
Kristian Monsenfa52d172010-03-25 18:29:21 +00003248 values.put(Downloads.Impl.COLUMN_URI, webAddress.toString());
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08003249 values.put(Downloads.Impl.COLUMN_COOKIE_DATA, cookies);
3250 values.put(Downloads.Impl.COLUMN_USER_AGENT, userAgent);
3251 values.put(Downloads.Impl.COLUMN_NOTIFICATION_PACKAGE,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003252 getPackageName());
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08003253 values.put(Downloads.Impl.COLUMN_NOTIFICATION_CLASS,
Leon Scrogginsa563d092010-04-19 16:53:49 -04003254 OpenDownloadReceiver.class.getCanonicalName());
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08003255 values.put(Downloads.Impl.COLUMN_VISIBILITY,
3256 Downloads.Impl.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
3257 values.put(Downloads.Impl.COLUMN_MIME_TYPE, mimetype);
3258 values.put(Downloads.Impl.COLUMN_FILE_NAME_HINT, filename);
Kristian Monsenfa52d172010-03-25 18:29:21 +00003259 values.put(Downloads.Impl.COLUMN_DESCRIPTION, webAddress.mHost);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003260 if (contentLength > 0) {
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08003261 values.put(Downloads.Impl.COLUMN_TOTAL_BYTES, contentLength);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003262 }
3263 if (mimetype == null) {
3264 // We must have long pressed on a link or image to download it. We
3265 // are not sure of the mimetype in this case, so do a head request
3266 new FetchUrlMimeType(this).execute(values);
3267 } else {
3268 final Uri contentUri =
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08003269 getContentResolver().insert(Downloads.Impl.CONTENT_URI, values);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003270 }
Leon Scroggins9191a7f2010-03-18 14:44:44 -04003271 Toast.makeText(this, R.string.download_pending, Toast.LENGTH_SHORT)
3272 .show();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003273 }
3274
Grace Kloba22ac16e2009-10-07 18:00:23 -07003275 // -------------------------------------------------------------------------
3276
The Android Open Source Project0c908882009-03-03 19:32:16 -08003277 /**
3278 * Resets the lock icon. This method is called when we start a new load and
3279 * know the url to be loaded.
3280 */
3281 private void resetLockIcon(String url) {
3282 // Save the lock-icon state (we revert to it if the load gets cancelled)
Grace Kloba22ac16e2009-10-07 18:00:23 -07003283 mTabControl.getCurrentTab().resetLockIcon(url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003284 updateLockIconImage(LOCK_ICON_UNSECURE);
3285 }
3286
The Android Open Source Project0c908882009-03-03 19:32:16 -08003287 /**
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04003288 * Update the lock icon to correspond to our latest state.
3289 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003290 private void updateLockIconToLatest() {
Leon Scroggins91f65fc2010-06-29 13:52:39 -04003291 Tab t = mTabControl.getCurrentTab();
3292 if (t != null) {
3293 updateLockIconImage(t.getLockIconType());
3294 }
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04003295 }
3296
3297 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08003298 * Updates the lock-icon image in the title-bar.
3299 */
3300 private void updateLockIconImage(int lockIconType) {
3301 Drawable d = null;
3302 if (lockIconType == LOCK_ICON_SECURE) {
3303 d = mSecLockIcon;
3304 } else if (lockIconType == LOCK_ICON_MIXED) {
3305 d = mMixLockIcon;
3306 }
Leon Scroggins68579392009-09-15 15:31:54 -04003307 mTitleBar.setLock(d);
Michael Kolba2b2ba82010-08-04 17:54:03 -07003308 mFakeTitleBar.setLock(d);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003309 }
3310
3311 /**
3312 * Displays a page-info dialog.
3313 * @param tab The tab to show info about
3314 * @param fromShowSSLCertificateOnError The flag that indicates whether
3315 * this dialog was opened from the SSL-certificate-on-error dialog or
3316 * not. This is important, since we need to know whether to return to
3317 * the parent dialog or simply dismiss.
3318 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003319 private void showPageInfo(final Tab tab,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003320 final boolean fromShowSSLCertificateOnError) {
3321 final LayoutInflater factory = LayoutInflater
3322 .from(this);
3323
3324 final View pageInfoView = factory.inflate(R.layout.page_info, null);
3325
3326 final WebView view = tab.getWebView();
3327
3328 String url = null;
3329 String title = null;
3330
3331 if (view == null) {
3332 url = tab.getUrl();
3333 title = tab.getTitle();
3334 } else if (view == mTabControl.getCurrentWebView()) {
3335 // Use the cached title and url if this is the current WebView
3336 url = mUrl;
3337 title = mTitle;
3338 } else {
3339 url = view.getUrl();
3340 title = view.getTitle();
3341 }
3342
3343 if (url == null) {
3344 url = "";
3345 }
3346 if (title == null) {
3347 title = "";
3348 }
3349
3350 ((TextView) pageInfoView.findViewById(R.id.address)).setText(url);
3351 ((TextView) pageInfoView.findViewById(R.id.title)).setText(title);
3352
3353 mPageInfoView = tab;
Leon Scrogginsc7b92f82010-01-11 18:17:31 -05003354 mPageInfoFromShowSSLCertificateOnError = fromShowSSLCertificateOnError;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003355
3356 AlertDialog.Builder alertDialogBuilder =
3357 new AlertDialog.Builder(this)
3358 .setTitle(R.string.page_info).setIcon(android.R.drawable.ic_dialog_info)
3359 .setView(pageInfoView)
3360 .setPositiveButton(
3361 R.string.ok,
3362 new DialogInterface.OnClickListener() {
3363 public void onClick(DialogInterface dialog,
3364 int whichButton) {
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 .setOnCancelListener(
3379 new DialogInterface.OnCancelListener() {
3380 public void onCancel(DialogInterface dialog) {
3381 mPageInfoDialog = null;
3382 mPageInfoView = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003383
3384 // if we came here from the SSL error dialog
3385 if (fromShowSSLCertificateOnError) {
3386 // go back to the SSL error dialog
3387 showSSLCertificateOnError(
3388 mSSLCertificateOnErrorView,
3389 mSSLCertificateOnErrorHandler,
3390 mSSLCertificateOnErrorError);
3391 }
3392 }
3393 });
3394
3395 // if we have a main top-level page SSL certificate set or a certificate
3396 // error
3397 if (fromShowSSLCertificateOnError ||
3398 (view != null && view.getCertificate() != null)) {
3399 // add a 'View Certificate' button
3400 alertDialogBuilder.setNeutralButton(
3401 R.string.view_certificate,
3402 new DialogInterface.OnClickListener() {
3403 public void onClick(DialogInterface dialog,
3404 int whichButton) {
3405 mPageInfoDialog = null;
3406 mPageInfoView = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003407
3408 // if we came here from the SSL error dialog
3409 if (fromShowSSLCertificateOnError) {
3410 // go back to the SSL error dialog
3411 showSSLCertificateOnError(
3412 mSSLCertificateOnErrorView,
3413 mSSLCertificateOnErrorHandler,
3414 mSSLCertificateOnErrorError);
3415 } else {
3416 // otherwise, display the top-most certificate from
3417 // the chain
3418 if (view.getCertificate() != null) {
3419 showSSLCertificate(tab);
3420 }
3421 }
3422 }
3423 });
3424 }
3425
3426 mPageInfoDialog = alertDialogBuilder.show();
3427 }
3428
3429 /**
3430 * Displays the main top-level page SSL certificate dialog
3431 * (accessible from the Page-Info dialog).
3432 * @param tab The tab to show certificate for.
3433 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003434 private void showSSLCertificate(final Tab tab) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003435 final View certificateView =
3436 inflateCertificateView(tab.getWebView().getCertificate());
3437 if (certificateView == null) {
3438 return;
3439 }
3440
3441 LayoutInflater factory = LayoutInflater.from(this);
3442
3443 final LinearLayout placeholder =
3444 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3445
3446 LinearLayout ll = (LinearLayout) factory.inflate(
3447 R.layout.ssl_success, placeholder);
3448 ((TextView)ll.findViewById(R.id.success))
3449 .setText(R.string.ssl_certificate_is_valid);
3450
3451 mSSLCertificateView = tab;
3452 mSSLCertificateDialog =
3453 new AlertDialog.Builder(this)
3454 .setTitle(R.string.ssl_certificate).setIcon(
3455 R.drawable.ic_dialog_browser_certificate_secure)
3456 .setView(certificateView)
3457 .setPositiveButton(R.string.ok,
3458 new DialogInterface.OnClickListener() {
3459 public void onClick(DialogInterface dialog,
3460 int whichButton) {
3461 mSSLCertificateDialog = null;
3462 mSSLCertificateView = null;
3463
3464 showPageInfo(tab, false);
3465 }
3466 })
3467 .setOnCancelListener(
3468 new DialogInterface.OnCancelListener() {
3469 public void onCancel(DialogInterface dialog) {
3470 mSSLCertificateDialog = null;
3471 mSSLCertificateView = null;
3472
3473 showPageInfo(tab, false);
3474 }
3475 })
3476 .show();
3477 }
3478
3479 /**
3480 * Displays the SSL error certificate dialog.
3481 * @param view The target web-view.
3482 * @param handler The SSL error handler responsible for cancelling the
3483 * connection that resulted in an SSL error or proceeding per user request.
3484 * @param error The SSL error object.
3485 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003486 void showSSLCertificateOnError(
The Android Open Source Project0c908882009-03-03 19:32:16 -08003487 final WebView view, final SslErrorHandler handler, final SslError error) {
3488
3489 final View certificateView =
3490 inflateCertificateView(error.getCertificate());
3491 if (certificateView == null) {
3492 return;
3493 }
3494
3495 LayoutInflater factory = LayoutInflater.from(this);
3496
3497 final LinearLayout placeholder =
3498 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3499
3500 if (error.hasError(SslError.SSL_UNTRUSTED)) {
3501 LinearLayout ll = (LinearLayout)factory
3502 .inflate(R.layout.ssl_warning, placeholder);
3503 ((TextView)ll.findViewById(R.id.warning))
3504 .setText(R.string.ssl_untrusted);
3505 }
3506
3507 if (error.hasError(SslError.SSL_IDMISMATCH)) {
3508 LinearLayout ll = (LinearLayout)factory
3509 .inflate(R.layout.ssl_warning, placeholder);
3510 ((TextView)ll.findViewById(R.id.warning))
3511 .setText(R.string.ssl_mismatch);
3512 }
3513
3514 if (error.hasError(SslError.SSL_EXPIRED)) {
3515 LinearLayout ll = (LinearLayout)factory
3516 .inflate(R.layout.ssl_warning, placeholder);
3517 ((TextView)ll.findViewById(R.id.warning))
3518 .setText(R.string.ssl_expired);
3519 }
3520
3521 if (error.hasError(SslError.SSL_NOTYETVALID)) {
3522 LinearLayout ll = (LinearLayout)factory
3523 .inflate(R.layout.ssl_warning, placeholder);
3524 ((TextView)ll.findViewById(R.id.warning))
3525 .setText(R.string.ssl_not_yet_valid);
3526 }
3527
3528 mSSLCertificateOnErrorHandler = handler;
3529 mSSLCertificateOnErrorView = view;
3530 mSSLCertificateOnErrorError = error;
3531 mSSLCertificateOnErrorDialog =
3532 new AlertDialog.Builder(this)
3533 .setTitle(R.string.ssl_certificate).setIcon(
3534 R.drawable.ic_dialog_browser_certificate_partially_secure)
3535 .setView(certificateView)
3536 .setPositiveButton(R.string.ok,
3537 new DialogInterface.OnClickListener() {
3538 public void onClick(DialogInterface dialog,
3539 int whichButton) {
3540 mSSLCertificateOnErrorDialog = null;
3541 mSSLCertificateOnErrorView = null;
3542 mSSLCertificateOnErrorHandler = null;
3543 mSSLCertificateOnErrorError = null;
3544
Grace Kloba22ac16e2009-10-07 18:00:23 -07003545 view.getWebViewClient().onReceivedSslError(
3546 view, handler, error);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003547 }
3548 })
3549 .setNeutralButton(R.string.page_info_view,
3550 new DialogInterface.OnClickListener() {
3551 public void onClick(DialogInterface dialog,
3552 int whichButton) {
3553 mSSLCertificateOnErrorDialog = null;
3554
3555 // do not clear the dialog state: we will
3556 // need to show the dialog again once the
3557 // user is done exploring the page-info details
3558
3559 showPageInfo(mTabControl.getTabFromView(view),
3560 true);
3561 }
3562 })
3563 .setOnCancelListener(
3564 new DialogInterface.OnCancelListener() {
3565 public void onCancel(DialogInterface dialog) {
3566 mSSLCertificateOnErrorDialog = null;
3567 mSSLCertificateOnErrorView = null;
3568 mSSLCertificateOnErrorHandler = null;
3569 mSSLCertificateOnErrorError = null;
3570
Grace Kloba22ac16e2009-10-07 18:00:23 -07003571 view.getWebViewClient().onReceivedSslError(
3572 view, handler, error);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003573 }
3574 })
3575 .show();
3576 }
3577
3578 /**
3579 * Inflates the SSL certificate view (helper method).
3580 * @param certificate The SSL certificate.
3581 * @return The resultant certificate view with issued-to, issued-by,
3582 * issued-on, expires-on, and possibly other fields set.
3583 * If the input certificate is null, returns null.
3584 */
3585 private View inflateCertificateView(SslCertificate certificate) {
3586 if (certificate == null) {
3587 return null;
3588 }
3589
3590 LayoutInflater factory = LayoutInflater.from(this);
3591
3592 View certificateView = factory.inflate(
3593 R.layout.ssl_certificate, null);
3594
3595 // issued to:
3596 SslCertificate.DName issuedTo = certificate.getIssuedTo();
3597 if (issuedTo != null) {
3598 ((TextView) certificateView.findViewById(R.id.to_common))
3599 .setText(issuedTo.getCName());
3600 ((TextView) certificateView.findViewById(R.id.to_org))
3601 .setText(issuedTo.getOName());
3602 ((TextView) certificateView.findViewById(R.id.to_org_unit))
3603 .setText(issuedTo.getUName());
3604 }
3605
3606 // issued by:
3607 SslCertificate.DName issuedBy = certificate.getIssuedBy();
3608 if (issuedBy != null) {
3609 ((TextView) certificateView.findViewById(R.id.by_common))
3610 .setText(issuedBy.getCName());
3611 ((TextView) certificateView.findViewById(R.id.by_org))
3612 .setText(issuedBy.getOName());
3613 ((TextView) certificateView.findViewById(R.id.by_org_unit))
3614 .setText(issuedBy.getUName());
3615 }
3616
3617 // issued on:
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003618 String issuedOn = formatCertificateDate(
3619 certificate.getValidNotBeforeDate());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003620 ((TextView) certificateView.findViewById(R.id.issued_on))
3621 .setText(issuedOn);
3622
3623 // expires on:
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003624 String expiresOn = formatCertificateDate(
3625 certificate.getValidNotAfterDate());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003626 ((TextView) certificateView.findViewById(R.id.expires_on))
3627 .setText(expiresOn);
3628
3629 return certificateView;
3630 }
3631
3632 /**
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003633 * Formats the certificate date to a properly localized date string.
The Android Open Source Project0c908882009-03-03 19:32:16 -08003634 * @return Properly localized version of the certificate date string and
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003635 * the "" if it fails to localize.
The Android Open Source Project0c908882009-03-03 19:32:16 -08003636 */
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003637 private String formatCertificateDate(Date certificateDate) {
3638 if (certificateDate == null) {
3639 return "";
The Android Open Source Project0c908882009-03-03 19:32:16 -08003640 }
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003641 String formattedDate = DateFormat.getDateFormat(this).format(certificateDate);
3642 if (formattedDate == null) {
3643 return "";
3644 }
3645 return formattedDate;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003646 }
3647
3648 /**
3649 * Displays an http-authentication dialog.
3650 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003651 void showHttpAuthentication(final HttpAuthHandler handler,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003652 final String host, final String realm, final String title,
3653 final String name, final String password, int focusId) {
3654 LayoutInflater factory = LayoutInflater.from(this);
3655 final View v = factory
3656 .inflate(R.layout.http_authentication, null);
3657 if (name != null) {
3658 ((EditText) v.findViewById(R.id.username_edit)).setText(name);
3659 }
3660 if (password != null) {
3661 ((EditText) v.findViewById(R.id.password_edit)).setText(password);
3662 }
3663
3664 String titleText = title;
3665 if (titleText == null) {
3666 titleText = getText(R.string.sign_in_to).toString().replace(
3667 "%s1", host).replace("%s2", realm);
3668 }
3669
3670 mHttpAuthHandler = handler;
3671 AlertDialog dialog = new AlertDialog.Builder(this)
3672 .setTitle(titleText)
3673 .setIcon(android.R.drawable.ic_dialog_alert)
3674 .setView(v)
3675 .setPositiveButton(R.string.action,
3676 new DialogInterface.OnClickListener() {
3677 public void onClick(DialogInterface dialog,
3678 int whichButton) {
3679 String nm = ((EditText) v
3680 .findViewById(R.id.username_edit))
3681 .getText().toString();
3682 String pw = ((EditText) v
3683 .findViewById(R.id.password_edit))
3684 .getText().toString();
3685 BrowserActivity.this.setHttpAuthUsernamePassword
3686 (host, realm, nm, pw);
3687 handler.proceed(nm, pw);
3688 mHttpAuthenticationDialog = null;
3689 mHttpAuthHandler = null;
3690 }})
3691 .setNegativeButton(R.string.cancel,
3692 new DialogInterface.OnClickListener() {
3693 public void onClick(DialogInterface dialog,
3694 int whichButton) {
3695 handler.cancel();
3696 BrowserActivity.this.resetTitleAndRevertLockIcon();
3697 mHttpAuthenticationDialog = null;
3698 mHttpAuthHandler = null;
3699 }})
3700 .setOnCancelListener(new DialogInterface.OnCancelListener() {
3701 public void onCancel(DialogInterface dialog) {
3702 handler.cancel();
3703 BrowserActivity.this.resetTitleAndRevertLockIcon();
3704 mHttpAuthenticationDialog = null;
3705 mHttpAuthHandler = null;
3706 }})
3707 .create();
3708 // Make the IME appear when the dialog is displayed if applicable.
3709 dialog.getWindow().setSoftInputMode(
3710 WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
3711 dialog.show();
3712 if (focusId != 0) {
3713 dialog.findViewById(focusId).requestFocus();
3714 } else {
3715 v.findViewById(R.id.username_edit).requestFocus();
3716 }
3717 mHttpAuthenticationDialog = dialog;
3718 }
3719
3720 public int getProgress() {
3721 WebView w = mTabControl.getCurrentWebView();
3722 if (w != null) {
3723 return w.getProgress();
3724 } else {
3725 return 100;
3726 }
3727 }
3728
3729 /**
3730 * Set HTTP authentication password.
3731 *
3732 * @param host The host for the password
3733 * @param realm The realm for the password
3734 * @param username The username for the password. If it is null, it means
3735 * password can't be saved.
3736 * @param password The password
3737 */
3738 public void setHttpAuthUsernamePassword(String host, String realm,
3739 String username,
3740 String password) {
Steve Block95a53b22010-03-25 17:24:58 +00003741 WebView w = getTopWindow();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003742 if (w != null) {
3743 w.setHttpAuthUsernamePassword(host, realm, username, password);
3744 }
3745 }
3746
3747 /**
3748 * connectivity manager says net has come or gone... inform the user
3749 * @param up true if net has come up, false if net has gone down
3750 */
3751 public void onNetworkToggle(boolean up) {
3752 if (up == mIsNetworkUp) {
3753 return;
3754 } else if (up) {
3755 mIsNetworkUp = true;
3756 if (mAlertDialog != null) {
3757 mAlertDialog.cancel();
3758 mAlertDialog = null;
3759 }
3760 } else {
3761 mIsNetworkUp = false;
Patrick Scotteb6ab2a2009-09-16 10:00:17 -04003762 if (mInLoad) {
3763 createAndShowNetworkDialog();
3764 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003765 }
3766 WebView w = mTabControl.getCurrentWebView();
3767 if (w != null) {
3768 w.setNetworkAvailable(up);
3769 }
3770 }
3771
Grace Kloba22ac16e2009-10-07 18:00:23 -07003772 boolean isNetworkUp() {
3773 return mIsNetworkUp;
3774 }
3775
Patrick Scotteb6ab2a2009-09-16 10:00:17 -04003776 // This method shows the network dialog alerting the user that the net is
3777 // down. It will only show the dialog if mAlertDialog is null.
3778 private void createAndShowNetworkDialog() {
3779 if (mAlertDialog == null) {
3780 mAlertDialog = new AlertDialog.Builder(this)
3781 .setTitle(R.string.loadSuspendedTitle)
3782 .setMessage(R.string.loadSuspended)
3783 .setPositiveButton(R.string.ok, null)
3784 .show();
3785 }
3786 }
3787
Michael Kolbe421c242010-10-04 19:29:01 -07003788 /**
3789 * callback from ComboPage when bookmark/history selection
3790 */
3791 @Override
3792 public void onUrlSelected(String url, boolean newTab) {
3793 removeComboView();
3794 if (!TextUtils.isEmpty(url)) {
3795 if (newTab) {
3796 openTab(url, false);
3797 } else {
3798 final Tab currentTab = mTabControl.getCurrentTab();
3799 dismissSubWindow(currentTab);
3800 loadUrl(getTopWindow(), url);
3801 }
3802 }
3803 }
3804
3805 /**
3806 * callback from ComboPage when dismissed
3807 */
3808 @Override
3809 public void onComboCanceled() {
3810 removeComboView();
3811 }
3812
3813 /**
3814 * dismiss the ComboPage
3815 */
3816 /* package */ void removeComboView() {
3817 if (mComboView != null) {
3818 mContentView.removeView(mComboView);
3819 mTitleBar.setVisibility(View.VISIBLE);
3820 mMenuState = R.id.MAIN_MENU;
3821 attachTabToContentView(mTabControl.getCurrentTab());
3822 getTopWindow().requestFocus();
3823 mComboView = null;
3824 }
3825 }
3826
3827 /**
3828 * callback from ComboPage when clear history is requested
3829 */
3830 public void onRemoveParentChildRelationships() {
3831 mTabControl.removeParentChildRelationShips();
3832 }
3833
The Android Open Source Project0c908882009-03-03 19:32:16 -08003834 @Override
3835 protected void onActivityResult(int requestCode, int resultCode,
3836 Intent intent) {
Grace Klobabb394f32009-11-19 10:26:37 -08003837 if (getTopWindow() == null) return;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003838 switch (requestCode) {
Leon Scrogginsfde97462010-01-11 13:06:21 -05003839 case PREFERENCES_PAGE:
3840 if (resultCode == RESULT_OK && intent != null) {
3841 String action = intent.getStringExtra(Intent.EXTRA_TEXT);
3842 if (BrowserSettings.PREF_CLEAR_HISTORY.equals(action)) {
3843 mTabControl.removeParentChildRelationShips();
3844 }
3845 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003846 break;
Leon Scroggins8d5fa432009-10-02 15:55:59 -04003847 // Choose a file from the file picker.
3848 case FILE_SELECTED:
3849 if (null == mUploadMessage) break;
3850 Uri result = intent == null || resultCode != RESULT_OK ? null
3851 : intent.getData();
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003852
3853 // As we ask the camera to save the result of the user taking
3854 // a picture, the camera application does not return anything other
3855 // than RESULT_OK. So we need to check whether the file we expected
3856 // was written to disk in the in the case that we
3857 // did not get an intent returned but did get a RESULT_OK. If it was,
3858 // we assume that this result has came back from the camera.
3859 if (result == null && intent == null && resultCode == RESULT_OK) {
3860 File cameraFile = new File(mCameraFilePath);
3861 if (cameraFile.exists()) {
3862 result = Uri.fromFile(cameraFile);
Ben Murdoch07d34732010-05-27 18:34:46 +01003863 // Broadcast to the media scanner that we have a new photo
3864 // so it will be added into the gallery for the user.
3865 sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, result));
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003866 }
3867 }
Leon Scroggins8d5fa432009-10-02 15:55:59 -04003868 mUploadMessage.onReceiveValue(result);
3869 mUploadMessage = null;
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003870 mCameraFilePath = null;
Leon Scroggins8d5fa432009-10-02 15:55:59 -04003871 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003872 default:
3873 break;
3874 }
Leon Scroggins30444232009-09-04 18:36:20 -04003875 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003876 }
3877
3878 /*
3879 * This method is called as a result of the user selecting the options
Leon Scrogginsf08809b2010-01-21 09:27:46 -05003880 * menu to see the download window. It shows the download window on top of
3881 * the current window.
The Android Open Source Project0c908882009-03-03 19:32:16 -08003882 */
Leon Scroggins IIIa682a3c2010-09-27 12:32:40 -04003883 private void viewDownloads() {
3884 Intent intent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
3885 startActivity(intent);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003886 }
3887
Michael Kolbc7485ae2010-09-03 10:10:58 -07003888 /* package */ void promptAddOrInstallBookmark(View anchor) {
3889 PopupMenu popup = new PopupMenu(this, anchor);
3890 popup.getMenuInflater().inflate(R.menu.bookmark_shortcut, popup.getMenu());
3891 popup.setOnMenuItemClickListener(this);
3892 popup.show();
3893 }
Michael Kolbebba8b42010-09-30 12:57:59 -07003894
Michael Kolbc7485ae2010-09-03 10:10:58 -07003895 /**
3896 * popup menu item click listener
3897 * @param item
3898 */
3899 public boolean onMenuItemClick(MenuItem item) {
3900 switch(item.getItemId()) {
3901 case R.id.add_bookmark_menu_id:
3902 bookmarkCurrentPage();
3903 return true;
3904 case R.id.shortcut_to_home_menu_id:
3905 Tab current = mTabControl.getCurrentTab();
3906 current.populatePickerData();
3907 String touchIconUrl = mTabControl.getCurrentWebView().getTouchIconUrl();
3908 if (touchIconUrl != null) {
3909 // Download the touch icon for this site then save
3910 // it to the
3911 // homescreen.
3912 Bundle b = new Bundle();
3913 b.putString("url", current.getUrl());
3914 b.putString("title", current.getTitle());
3915 b.putParcelable("favicon", current.getFavicon());
3916 Message msg = mHandler.obtainMessage(TOUCH_ICON_DOWNLOADED);
3917 msg.setData(b);
3918 new DownloadTouchIcon(BrowserActivity.this, msg,
3919 mTabControl.getCurrentWebView().getSettings().getUserAgentString())
3920 .execute(touchIconUrl);
3921 } else {
3922 // add to homescreen, can do it immediately as there
3923 // is no touch
3924 // icon.
3925 showSaveToHomescreenDialog(
3926 current.getUrl(), current.getTitle(), null, current.getFavicon());
3927 }
3928 return true;
3929 default:
3930 return false;
3931 }
3932 }
Michael Kolbebba8b42010-09-30 12:57:59 -07003933
Michael Kolbc7485ae2010-09-03 10:10:58 -07003934 /* package */Dialog makeAddOrInstallDialog() {
Ben Murdocheecb4e62010-07-06 16:30:38 +01003935 final Tab current = mTabControl.getCurrentTab();
3936 Resources resources = getResources();
Michael Kolbc7485ae2010-09-03 10:10:58 -07003937 CharSequence[] choices =
3938 {resources.getString(R.string.save_to_bookmarks),
3939 resources.getString(R.string.create_shortcut_bookmark)};
Ben Murdocheecb4e62010-07-06 16:30:38 +01003940
3941 AlertDialog.Builder builder = new AlertDialog.Builder(this);
3942 builder.setTitle(R.string.add_new_bookmark);
3943 builder.setItems(choices, new DialogInterface.OnClickListener() {
Michael Kolbc7485ae2010-09-03 10:10:58 -07003944 public void onClick(DialogInterface dialog, int item) {
3945 if (item == 0) {
3946 bookmarkCurrentPage();
3947 } else if (item == 1) {
3948 }
3949 }
Ben Murdocheecb4e62010-07-06 16:30:38 +01003950 });
Michael Kolbc7485ae2010-09-03 10:10:58 -07003951 return builder.create();
Ben Murdocheecb4e62010-07-06 16:30:38 +01003952 }
3953
Leon Scroggins160a7e72009-08-14 18:28:01 -04003954 /**
3955 * Open the Go page.
3956 * @param startWithHistory If true, open starting on the history tab.
3957 * Otherwise, start with the bookmarks tab.
Leon Scroggins160a7e72009-08-14 18:28:01 -04003958 */
Michael Kolbe421c242010-10-04 19:29:01 -07003959 /* package */ void bookmarksOrHistoryPicker(boolean startWithHistory) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003960 WebView current = mTabControl.getCurrentWebView();
3961 if (current == null) {
3962 return;
3963 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003964 String title = current.getTitle();
3965 String url = current.getUrl();
Ben Murdoch87cc65d2010-06-29 20:34:10 +01003966 Bitmap thumbnail = createScreenshot(current, getDesiredThumbnailWidth(this),
3967 getDesiredThumbnailHeight(this));
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01003968
The Android Open Source Project0c908882009-03-03 19:32:16 -08003969 // Just in case the user opens bookmarks before a page finishes loading
3970 // so the current history item, and therefore the page, is null.
3971 if (null == url) {
3972 url = mLastEnteredUrl;
3973 // This can happen.
3974 if (null == url) {
3975 url = mSettings.getHomePage();
3976 }
3977 }
3978 // In case the web page has not yet received its associated title.
3979 if (title == null) {
3980 title = url;
3981 }
Michael Kolbe421c242010-10-04 19:29:01 -07003982 Bundle extras = new Bundle();
3983 extras.putString("title", title);
3984 extras.putString("url", url);
3985 extras.putParcelable("thumbnail", thumbnail);
Leon Scroggins30444232009-09-04 18:36:20 -04003986 // Disable opening in a new window if we have maxed out the windows
Michael Kolbe421c242010-10-04 19:29:01 -07003987 extras.putBoolean("disable_new_window", !mTabControl.canCreateNewTab());
3988 extras.putString("touch_icon_url", current.getTouchIconUrl());
3989
3990 mComboView = new CombinedBookmarkHistoryView(this,
3991 startWithHistory ? CombinedBookmarkHistoryView.FRAGMENT_ID_HISTORY
3992 : CombinedBookmarkHistoryView.FRAGMENT_ID_BOOKMARKS,
3993 extras);
3994 removeTabFromContentView(mTabControl.getCurrentTab());
3995 mTitleBar.setVisibility(View.GONE);
3996 hideFakeTitleBar();
3997 mContentView.addView(mComboView, COVER_SCREEN_PARAMS);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003998 }
3999
Ben Murdocheecb4e62010-07-06 16:30:38 +01004000 private void showSaveToHomescreenDialog(String url, String title, Bitmap touchIcon,
4001 Bitmap favicon) {
4002 Intent intent = new Intent(this, SaveToHomescreenDialog.class);
4003
4004 // Just in case the user tries to save before a page finishes loading
4005 // so the current history item, and therefore the page, is null.
4006 if (null == url) {
4007 url = mLastEnteredUrl;
4008 // This can happen.
4009 if (null == url) {
4010 url = mSettings.getHomePage();
4011 }
4012 }
4013
4014 // In case the web page has not yet received its associated title.
4015 if (title == null) {
4016 title = url;
4017 }
4018
4019 intent.putExtra("title", title);
4020 intent.putExtra("url", url);
4021 intent.putExtra("favicon", favicon);
4022 intent.putExtra("touchIcon", touchIcon);
4023 startActivity(intent);
4024 }
4025
The Android Open Source Project0c908882009-03-03 19:32:16 -08004026 // Called when loading from context menu or LOAD_URL message
Leon Scroggins92472e82010-02-17 16:32:28 -05004027 private void loadUrlFromContext(WebView view, String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08004028 // In case the user enters nothing.
4029 if (url != null && url.length() != 0 && view != null) {
4030 url = smartUrlFilter(url);
Grace Kloba22ac16e2009-10-07 18:00:23 -07004031 if (!view.getWebViewClient().shouldOverrideUrlLoading(view, url)) {
Leon Scroggins92472e82010-02-17 16:32:28 -05004032 loadUrl(view, url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004033 }
4034 }
4035 }
4036
Leon Scroggins92472e82010-02-17 16:32:28 -05004037 /**
4038 * Load the URL into the given WebView and update the title bar
4039 * to reflect the new load. Call this instead of WebView.loadUrl
4040 * directly.
4041 * @param view The WebView used to load url.
4042 * @param url The URL to load.
4043 */
4044 private void loadUrl(WebView view, String url) {
4045 updateTitleBarForNewLoad(view, url);
4046 view.loadUrl(url);
4047 }
4048
4049 /**
4050 * Load UrlData into a Tab and update the title bar to reflect the new
4051 * load. Call this instead of UrlData.loadIn directly.
4052 * @param t The Tab used to load.
4053 * @param data The UrlData being loaded.
4054 */
4055 private void loadUrlDataIn(Tab t, UrlData data) {
4056 updateTitleBarForNewLoad(t.getWebView(), data.mUrl);
4057 data.loadIn(t);
4058 }
4059
4060 /**
4061 * If the WebView is the top window, update the title bar to reflect
4062 * loading the new URL. i.e. set its text, clear the favicon (which
4063 * will be set once the page begins loading), and set the progress to
4064 * INITIAL_PROGRESS to show that the page has begun to load. Called
4065 * by loadUrl and loadUrlDataIn.
4066 * @param view The WebView that is starting a load.
4067 * @param url The URL that is being loaded.
4068 */
4069 private void updateTitleBarForNewLoad(WebView view, String url) {
4070 if (view == getTopWindow()) {
4071 setUrlTitle(url, null);
4072 setFavicon(null);
4073 onProgressChanged(view, INITIAL_PROGRESS);
4074 }
4075 }
4076
The Android Open Source Project0c908882009-03-03 19:32:16 -08004077 private String smartUrlFilter(Uri inUri) {
4078 if (inUri != null) {
4079 return smartUrlFilter(inUri.toString());
4080 }
4081 return null;
4082 }
4083
Feng Qianb34f87a2009-03-24 21:27:26 -07004084 protected static final Pattern ACCEPTED_URI_SCHEMA = Pattern.compile(
The Android Open Source Project0c908882009-03-03 19:32:16 -08004085 "(?i)" + // switch on case insensitive matching
4086 "(" + // begin group for schema
4087 "(?:http|https|file):\\/\\/" +
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004088 "|(?:inline|data|about|content|javascript):" +
The Android Open Source Project0c908882009-03-03 19:32:16 -08004089 ")" +
4090 "(.*)" );
4091
4092 /**
4093 * Attempts to determine whether user input is a URL or search
4094 * terms. Anything with a space is passed to search.
4095 *
4096 * Converts to lowercase any mistakenly uppercased schema (i.e.,
4097 * "Http://" converts to "http://"
4098 *
4099 * @return Original or modified URL
4100 *
4101 */
4102 String smartUrlFilter(String url) {
4103
4104 String inUrl = url.trim();
4105 boolean hasSpace = inUrl.indexOf(' ') != -1;
4106
4107 Matcher matcher = ACCEPTED_URI_SCHEMA.matcher(inUrl);
4108 if (matcher.matches()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08004109 // force scheme to lowercase
4110 String scheme = matcher.group(1);
4111 String lcScheme = scheme.toLowerCase();
4112 if (!lcScheme.equals(scheme)) {
Mitsuru Oshima123ecfb2009-05-18 19:11:14 -07004113 inUrl = lcScheme + matcher.group(2);
4114 }
4115 if (hasSpace) {
4116 inUrl = inUrl.replace(" ", "%20");
The Android Open Source Project0c908882009-03-03 19:32:16 -08004117 }
4118 return inUrl;
4119 }
4120 if (hasSpace) {
Satish Sampath565505b2009-05-29 15:37:27 +01004121 // FIXME: Is this the correct place to add to searches?
4122 // what if someone else calls this function?
4123 int shortcut = parseUrlShortcut(inUrl);
4124 if (shortcut != SHORTCUT_INVALID) {
4125 Browser.addSearchUrl(mResolver, inUrl);
4126 String query = inUrl.substring(2);
4127 switch (shortcut) {
4128 case SHORTCUT_GOOGLE_SEARCH:
Grace Kloba47fdfdb2009-06-30 11:15:34 -07004129 return URLUtil.composeSearchUrl(query, QuickSearch_G, QUERY_PLACE_HOLDER);
Satish Sampath565505b2009-05-29 15:37:27 +01004130 case SHORTCUT_WIKIPEDIA_SEARCH:
4131 return URLUtil.composeSearchUrl(query, QuickSearch_W, QUERY_PLACE_HOLDER);
4132 case SHORTCUT_DICTIONARY_SEARCH:
4133 return URLUtil.composeSearchUrl(query, QuickSearch_D, QUERY_PLACE_HOLDER);
4134 case SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH:
The Android Open Source Project0c908882009-03-03 19:32:16 -08004135 // FIXME: we need location in this case
Satish Sampath565505b2009-05-29 15:37:27 +01004136 return URLUtil.composeSearchUrl(query, QuickSearch_L, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004137 }
4138 }
4139 } else {
Dan Egnor5ee906c2009-11-18 12:11:49 -08004140 if (Patterns.WEB_URL.matcher(inUrl).matches()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08004141 return URLUtil.guessUrl(inUrl);
4142 }
4143 }
4144
4145 Browser.addSearchUrl(mResolver, inUrl);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07004146 return URLUtil.composeSearchUrl(inUrl, QuickSearch_G, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004147 }
4148
Ben Murdochbff2d602009-07-01 20:19:05 +01004149 /* package */ void setShouldShowErrorConsole(boolean flag) {
4150 if (flag == mShouldShowErrorConsole) {
4151 // Nothing to do.
4152 return;
4153 }
Leon Scroggins IIIa9e35b62010-09-16 15:30:15 -04004154 Tab t = mTabControl.getCurrentTab();
4155 if (t == null) {
4156 // There is no current tab so we cannot toggle the error console
4157 return;
4158 }
Ben Murdochbff2d602009-07-01 20:19:05 +01004159
4160 mShouldShowErrorConsole = flag;
4161
Leon Scroggins IIIa9e35b62010-09-16 15:30:15 -04004162 ErrorConsoleView errorConsole = t.getErrorConsole(true);
Ben Murdochbff2d602009-07-01 20:19:05 +01004163
4164 if (flag) {
4165 // Setting the show state of the console will cause it's the layout to be inflated.
4166 if (errorConsole.numberOfErrors() > 0) {
4167 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
4168 } else {
4169 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
4170 }
4171
4172 // Now we can add it to the main view.
4173 mErrorConsoleContainer.addView(errorConsole,
Romain Guy15b8ec62010-01-08 15:06:43 -08004174 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
Ben Murdochbff2d602009-07-01 20:19:05 +01004175 ViewGroup.LayoutParams.WRAP_CONTENT));
4176 } else {
4177 mErrorConsoleContainer.removeView(errorConsole);
4178 }
4179
4180 }
4181
Grace Kloba22ac16e2009-10-07 18:00:23 -07004182 boolean shouldShowErrorConsole() {
4183 return mShouldShowErrorConsole;
4184 }
4185
Andrei Popescu163ab742009-10-20 17:58:23 +01004186 private void setStatusBarVisibility(boolean visible) {
4187 int flag = visible ? 0 : WindowManager.LayoutParams.FLAG_FULLSCREEN;
4188 getWindow().setFlags(flag, WindowManager.LayoutParams.FLAG_FULLSCREEN);
4189 }
4190
Andrei Popescu56199cc2010-01-12 22:39:16 +00004191
4192 private void sendNetworkType(String type, String subtype) {
4193 WebView w = mTabControl.getCurrentWebView();
4194 if (w != null) {
4195 w.setNetworkType(type, subtype);
4196 }
4197 }
4198
Grace Klobaeb6eef42009-09-15 17:56:32 -07004199 final static int LOCK_ICON_UNSECURE = 0;
4200 final static int LOCK_ICON_SECURE = 1;
4201 final static int LOCK_ICON_MIXED = 2;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004202
The Android Open Source Project0c908882009-03-03 19:32:16 -08004203 private BrowserSettings mSettings;
4204 private TabControl mTabControl;
4205 private ContentResolver mResolver;
4206 private FrameLayout mContentView;
Andrei Popescuadc008d2009-06-26 14:11:30 +01004207 private View mCustomView;
4208 private FrameLayout mCustomViewContainer;
Andrei Popescuc9b55562009-07-07 10:51:15 +01004209 private WebChromeClient.CustomViewCallback mCustomViewCallback;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004210
4211 // FIXME, temp address onPrepareMenu performance problem. When we move everything out of
4212 // view, we should rewrite this.
4213 private int mCurrentMenuState = 0;
4214 private int mMenuState = R.id.MAIN_MENU;
Andrei Popescuadc008d2009-06-26 14:11:30 +01004215 private int mOldMenuState = EMPTY_MENU;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004216 private static final int EMPTY_MENU = -1;
4217 private Menu mMenu;
4218
The Android Open Source Project0c908882009-03-03 19:32:16 -08004219 // Used to prevent chording to result in firing two shortcuts immediately
4220 // one after another. Fixes bug 1211714.
4221 boolean mCanChord;
4222
4223 private boolean mInLoad;
4224 private boolean mIsNetworkUp;
Ben Murdochb7cc8b42009-09-28 10:59:09 +01004225 private boolean mDidStopLoad;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004226
Cary Clark1f10cbf2010-03-22 11:45:23 -04004227 /* package */ boolean mActivityInPause = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004228
4229 private boolean mMenuIsDown;
4230
The Android Open Source Project0c908882009-03-03 19:32:16 -08004231 private static boolean mInTrace;
4232
4233 // Performance probe
4234 private static final int[] SYSTEM_CPU_FORMAT = new int[] {
4235 Process.PROC_SPACE_TERM | Process.PROC_COMBINE,
4236 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 1: user time
4237 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 2: nice time
4238 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 3: sys time
4239 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 4: idle time
4240 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 5: iowait time
4241 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 6: irq time
4242 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG // 7: softirq time
4243 };
4244
4245 private long mStart;
4246 private long mProcessStart;
4247 private long mUserStart;
4248 private long mSystemStart;
4249 private long mIdleStart;
4250 private long mIrqStart;
4251
4252 private long mUiStart;
4253
4254 private Drawable mMixLockIcon;
4255 private Drawable mSecLockIcon;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004256
4257 /* hold a ref so we can auto-cancel if necessary */
4258 private AlertDialog mAlertDialog;
4259
The Android Open Source Project0c908882009-03-03 19:32:16 -08004260 // The up-to-date URL and title (these can be different from those stored
4261 // in WebView, since it takes some time for the information in WebView to
4262 // get updated)
4263 private String mUrl;
4264 private String mTitle;
4265
4266 // As PageInfo has different style for landscape / portrait, we have
4267 // to re-open it when configuration changed
4268 private AlertDialog mPageInfoDialog;
Grace Kloba22ac16e2009-10-07 18:00:23 -07004269 private Tab mPageInfoView;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004270 // If the Page-Info dialog is launched from the SSL-certificate-on-error
4271 // dialog, we should not just dismiss it, but should get back to the
4272 // SSL-certificate-on-error dialog. This flag is used to store this state
Leon Scrogginsc7b92f82010-01-11 18:17:31 -05004273 private boolean mPageInfoFromShowSSLCertificateOnError;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004274
4275 // as SSLCertificateOnError has different style for landscape / portrait,
4276 // we have to re-open it when configuration changed
4277 private AlertDialog mSSLCertificateOnErrorDialog;
4278 private WebView mSSLCertificateOnErrorView;
4279 private SslErrorHandler mSSLCertificateOnErrorHandler;
4280 private SslError mSSLCertificateOnErrorError;
4281
4282 // as SSLCertificate has different style for landscape / portrait, we
4283 // have to re-open it when configuration changed
4284 private AlertDialog mSSLCertificateDialog;
Grace Kloba22ac16e2009-10-07 18:00:23 -07004285 private Tab mSSLCertificateView;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004286
4287 // as HttpAuthentication has different style for landscape / portrait, we
4288 // have to re-open it when configuration changed
4289 private AlertDialog mHttpAuthenticationDialog;
4290 private HttpAuthHandler mHttpAuthHandler;
4291
4292 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_PARAMS =
4293 new FrameLayout.LayoutParams(
Romain Guy15b8ec62010-01-08 15:06:43 -08004294 ViewGroup.LayoutParams.MATCH_PARENT,
4295 ViewGroup.LayoutParams.MATCH_PARENT);
Andrei Popescuadc008d2009-06-26 14:11:30 +01004296 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_GRAVITY_CENTER =
4297 new FrameLayout.LayoutParams(
Romain Guy15b8ec62010-01-08 15:06:43 -08004298 ViewGroup.LayoutParams.MATCH_PARENT,
4299 ViewGroup.LayoutParams.MATCH_PARENT,
Andrei Popescuadc008d2009-06-26 14:11:30 +01004300 Gravity.CENTER);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07004301 // Google search
4302 final static String QuickSearch_G = "http://www.google.com/m?q=%s";
The Android Open Source Project0c908882009-03-03 19:32:16 -08004303 // Wikipedia search
4304 final static String QuickSearch_W = "http://en.wikipedia.org/w/index.php?search=%s&go=Go";
4305 // Dictionary search
4306 final static String QuickSearch_D = "http://dictionary.reference.com/search?q=%s";
4307 // Google Mobile Local search
4308 final static String QuickSearch_L = "http://www.google.com/m/search?site=local&q=%s&near=mountain+view";
4309
4310 final static String QUERY_PLACE_HOLDER = "%s";
4311
4312 // "source" parameter for Google search through search key
4313 final static String GOOGLE_SEARCH_SOURCE_SEARCHKEY = "browser-key";
4314 // "source" parameter for Google search through goto menu
4315 final static String GOOGLE_SEARCH_SOURCE_GOTO = "browser-goto";
4316 // "source" parameter for Google search through simplily type
4317 final static String GOOGLE_SEARCH_SOURCE_TYPE = "browser-type";
4318 // "source" parameter for Google search suggested by the browser
4319 final static String GOOGLE_SEARCH_SOURCE_SUGGEST = "browser-suggest";
4320 // "source" parameter for Google search from unknown source
4321 final static String GOOGLE_SEARCH_SOURCE_UNKNOWN = "unknown";
4322
4323 private final static String LOGTAG = "browser";
4324
The Android Open Source Project0c908882009-03-03 19:32:16 -08004325 private String mLastEnteredUrl;
4326
4327 private PowerManager.WakeLock mWakeLock;
4328 private final static int WAKELOCK_TIMEOUT = 5 * 60 * 1000; // 5 minutes
4329
4330 private Toast mStopToast;
4331
Leon Scroggins571b3762010-05-26 10:25:01 -04004332 private TitleBarBase mTitleBar;
Michael Kolba2b2ba82010-08-04 17:54:03 -07004333 private TabBar mTabBar;
Leon Scroggins81db3662009-06-04 17:45:11 -04004334
Ben Murdochbff2d602009-07-01 20:19:05 +01004335 private LinearLayout mErrorConsoleContainer = null;
4336 private boolean mShouldShowErrorConsole = false;
4337
The Android Open Source Project0c908882009-03-03 19:32:16 -08004338 // As the ids are dynamically created, we can't guarantee that they will
4339 // be in sequence, so this static array maps ids to a window number.
4340 final static private int[] WINDOW_SHORTCUT_ID_ARRAY =
4341 { R.id.window_one_menu_id, R.id.window_two_menu_id, R.id.window_three_menu_id,
4342 R.id.window_four_menu_id, R.id.window_five_menu_id, R.id.window_six_menu_id,
4343 R.id.window_seven_menu_id, R.id.window_eight_menu_id };
4344
4345 // monitor platform changes
4346 private IntentFilter mNetworkStateChangedFilter;
4347 private BroadcastReceiver mNetworkStateIntentReceiver;
4348
Bjorn Bringerta7611812010-03-24 11:12:02 +00004349 private SystemAllowGeolocationOrigins mSystemAllowGeolocationOrigins;
4350
The Android Open Source Project0c908882009-03-03 19:32:16 -08004351 // activity requestCode
Nicolas Roard78a98e42009-05-11 13:34:17 +01004352 final static int PREFERENCES_PAGE = 3;
Leon Scroggins8d5fa432009-10-02 15:55:59 -04004353 final static int FILE_SELECTED = 4;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004354
Andrei Popescu540035d2009-09-18 18:59:20 +01004355 // the default <video> poster
4356 private Bitmap mDefaultVideoPoster;
4357 // the video progress view
4358 private View mVideoProgressView;
4359
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004360 /**
4361 * A UrlData class to abstract how the content will be set to WebView.
4362 * This base class uses loadUrl to show the content.
4363 */
Leon Scroggins6eac63e2010-03-15 18:19:14 -04004364 /* package */ static class UrlData {
Grace Kloba068e48b2010-01-26 18:11:27 -08004365 final String mUrl;
4366 final Map<String, String> mHeaders;
Leon Scroggins58d56c62010-01-28 15:12:40 -05004367 final Intent mVoiceIntent;
Grace Kloba60e095c2009-06-16 11:50:55 -07004368
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004369 UrlData(String url) {
4370 this.mUrl = url;
Grace Kloba068e48b2010-01-26 18:11:27 -08004371 this.mHeaders = null;
Leon Scroggins58d56c62010-01-28 15:12:40 -05004372 this.mVoiceIntent = null;
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004373 }
Grace Kloba60e095c2009-06-16 11:50:55 -07004374
Leon Scroggins58d56c62010-01-28 15:12:40 -05004375 UrlData(String url, Map<String, String> headers, Intent intent) {
Grace Kloba068e48b2010-01-26 18:11:27 -08004376 this.mUrl = url;
4377 this.mHeaders = headers;
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -05004378 if (RecognizerResultsIntent.ACTION_VOICE_SEARCH_RESULTS
4379 .equals(intent.getAction())) {
Leon Scroggins58d56c62010-01-28 15:12:40 -05004380 this.mVoiceIntent = intent;
4381 } else {
4382 this.mVoiceIntent = null;
4383 }
Grace Kloba60e095c2009-06-16 11:50:55 -07004384 }
4385
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004386 boolean isEmpty() {
Leon Scroggins58d56c62010-01-28 15:12:40 -05004387 return mVoiceIntent == null && (mUrl == null || mUrl.length() == 0);
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004388 }
4389
Leon Scroggins92472e82010-02-17 16:32:28 -05004390 /**
4391 * Load this UrlData into the given Tab. Use loadUrlDataIn to update
4392 * the title bar as well.
4393 */
Leon Scroggins58d56c62010-01-28 15:12:40 -05004394 public void loadIn(Tab t) {
4395 if (mVoiceIntent != null) {
4396 t.activateVoiceSearchMode(mVoiceIntent);
4397 } else {
4398 t.getWebView().loadUrl(mUrl, mHeaders);
4399 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004400 }
4401 };
4402
Leon Scroggins1f005d32009-08-10 17:36:42 -04004403 /* package */ static final UrlData EMPTY_URL_DATA = new UrlData(null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004404}