blob: 24796a6028f9827bf3af644a3c55e927254718e2 [file] [log] [blame]
The Android Open Source Project0c908882009-03-03 19:32:16 -08001/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.browser;
18
Michael Kolb3f65c382010-08-20 15:31:16 -070019import com.android.browser.ScrollWebView.ScrollListener;
20import com.android.common.Search;
21import com.android.common.speech.LoggingEvents;
22
Michael Kolbed217742010-08-10 17:52:34 -070023import android.app.ActionBar;
The Android Open Source Project0c908882009-03-03 19:32:16 -080024import android.app.Activity;
The Android Open Source Project0c908882009-03-03 19:32:16 -080025import android.app.AlertDialog;
26import android.app.ProgressDialog;
27import android.app.SearchManager;
28import android.content.ActivityNotFoundException;
29import android.content.BroadcastReceiver;
Dianne Hackborn80f32622010-08-05 14:17:53 -070030import android.content.ClipboardManager;
The Android Open Source Project0c908882009-03-03 19:32:16 -080031import android.content.ComponentName;
Leon Scroggins58d56c62010-01-28 15:12:40 -050032import android.content.ContentProvider;
33import android.content.ContentProviderClient;
The Android Open Source Project0c908882009-03-03 19:32:16 -080034import android.content.ContentResolver;
Leon Scrogginsb6b7f9e2009-06-18 12:05:28 -040035import android.content.ContentUris;
The Android Open Source Project0c908882009-03-03 19:32:16 -080036import android.content.ContentValues;
37import android.content.Context;
38import android.content.DialogInterface;
39import android.content.Intent;
40import android.content.IntentFilter;
The Android Open Source Project0c908882009-03-03 19:32:16 -080041import android.content.pm.PackageManager;
42import android.content.pm.ResolveInfo;
The Android Open Source Project0c908882009-03-03 19:32:16 -080043import android.content.res.Configuration;
44import android.content.res.Resources;
45import android.database.Cursor;
The Android Open Source Project0c908882009-03-03 19:32:16 -080046import android.graphics.Bitmap;
Andrei Popescu540035d2009-09-18 18:59:20 +010047import android.graphics.BitmapFactory;
The Android Open Source Project0c908882009-03-03 19:32:16 -080048import android.graphics.Canvas;
The Android Open Source Project0c908882009-03-03 19:32:16 -080049import android.graphics.Picture;
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -040050import android.graphics.PixelFormat;
The Android Open Source Project0c908882009-03-03 19:32:16 -080051import android.graphics.drawable.Drawable;
The Android Open Source Project0c908882009-03-03 19:32:16 -080052import android.net.ConnectivityManager;
Andrei Popescu56199cc2010-01-12 22:39:16 +000053import android.net.NetworkInfo;
The Android Open Source Project0c908882009-03-03 19:32:16 -080054import android.net.Uri;
55import android.net.WebAddress;
The Android Open Source Project0c908882009-03-03 19:32:16 -080056import android.net.http.SslCertificate;
57import android.net.http.SslError;
58import android.os.AsyncTask;
59import android.os.Bundle;
60import android.os.Debug;
61import android.os.Environment;
62import android.os.Handler;
The Android Open Source Project0c908882009-03-03 19:32:16 -080063import android.os.Message;
64import android.os.PowerManager;
65import android.os.Process;
The Android Open Source Project0c908882009-03-03 19:32:16 -080066import android.os.SystemClock;
The Android Open Source Project0c908882009-03-03 19:32:16 -080067import android.provider.Browser;
Jeff Hamilton8ce956c2010-08-17 11:13:53 -050068import android.provider.BrowserContract;
Cary Clark5e335a32009-09-22 14:53:11 -040069import android.provider.ContactsContract;
Michael Kolba2b2ba82010-08-04 17:54:03 -070070import android.provider.ContactsContract.Intents.Insert;
The Android Open Source Project0c908882009-03-03 19:32:16 -080071import android.provider.Downloads;
72import android.provider.MediaStore;
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -050073import android.speech.RecognizerResultsIntent;
The Android Open Source Project0c908882009-03-03 19:32:16 -080074import android.text.TextUtils;
75import android.text.format.DateFormat;
The Android Open Source Project0c908882009-03-03 19:32:16 -080076import android.util.Log;
Dianne Hackborn385effd2010-02-24 20:03:04 -080077import android.util.Patterns;
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -040078import android.view.ActionMode;
The Android Open Source Project0c908882009-03-03 19:32:16 -080079import android.view.ContextMenu;
Michael Kolba2b2ba82010-08-04 17:54:03 -070080import android.view.ContextMenu.ContextMenuInfo;
The Android Open Source Project0c908882009-03-03 19:32:16 -080081import android.view.Gravity;
82import android.view.KeyEvent;
83import android.view.LayoutInflater;
84import android.view.Menu;
85import android.view.MenuInflater;
86import android.view.MenuItem;
Michael Kolba2b2ba82010-08-04 17:54:03 -070087import android.view.MenuItem.OnMenuItemClickListener;
Michael Kolb3f65c382010-08-20 15:31:16 -070088import android.view.MotionEvent;
The Android Open Source Project0c908882009-03-03 19:32:16 -080089import android.view.View;
90import android.view.ViewGroup;
91import android.view.Window;
92import android.view.WindowManager;
Svetoslav Ganov2b345992010-05-06 06:13:54 -070093import android.view.accessibility.AccessibilityManager;
The Android Open Source Project0c908882009-03-03 19:32:16 -080094import android.webkit.CookieManager;
95import android.webkit.CookieSyncManager;
96import android.webkit.DownloadListener;
97import android.webkit.HttpAuthHandler;
98import android.webkit.SslErrorHandler;
99import android.webkit.URLUtil;
Leon Clarkecb6cc862009-09-29 18:35:13 +0100100import android.webkit.ValueCallback;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800101import android.webkit.WebChromeClient;
102import android.webkit.WebHistoryItem;
103import android.webkit.WebIconDatabase;
104import android.webkit.WebView;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800105import android.widget.EditText;
106import android.widget.FrameLayout;
107import android.widget.LinearLayout;
108import android.widget.TextView;
109import android.widget.Toast;
110
Leon Scrogginsb6b7f9e2009-06-18 12:05:28 -0400111import java.io.ByteArrayOutputStream;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800112import java.io.File;
Ben Murdoch4f75ba22009-10-27 11:48:28 +0000113import java.io.IOException;
114import java.io.InputStream;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800115import java.net.MalformedURLException;
Dianne Hackborn99189432009-06-17 18:06:18 -0700116import java.net.URISyntaxException;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800117import java.net.URL;
118import java.net.URLEncoder;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800119import java.util.Date;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800120import java.util.HashMap;
Grace Kloba00f54c52010-01-27 14:53:51 -0800121import java.util.Iterator;
Grace Kloba068e48b2010-01-26 18:11:27 -0800122import java.util.Map;
Michael Kolbfe251992010-07-08 15:41:55 -0700123import java.util.Vector;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800124import java.util.regex.Matcher;
125import java.util.regex.Pattern;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800126
127public class BrowserActivity extends Activity
Shimeng (Simon) Wang98d5fce2010-03-16 13:23:39 -0700128 implements View.OnCreateContextMenuListener, DownloadListener {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800129
Dave Bort31a6d1c2009-04-13 15:56:49 -0700130 /* Define some aliases to make these debugging flags easier to refer to.
131 * This file imports android.provider.Browser, so we can't just refer to "Browser.DEBUG".
132 */
133 private final static boolean DEBUG = com.android.browser.Browser.DEBUG;
134 private final static boolean LOGV_ENABLED = com.android.browser.Browser.LOGV_ENABLED;
135 private final static boolean LOGD_ENABLED = com.android.browser.Browser.LOGD_ENABLED;
136
Satish Sampath565505b2009-05-29 15:37:27 +0100137 // These are single-character shortcuts for searching popular sources.
138 private static final int SHORTCUT_INVALID = 0;
139 private static final int SHORTCUT_GOOGLE_SEARCH = 1;
140 private static final int SHORTCUT_WIKIPEDIA_SEARCH = 2;
141 private static final int SHORTCUT_DICTIONARY_SEARCH = 3;
142 private static final int SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH = 4;
143
Cary Clarka9771242009-08-11 16:42:26 -0400144 private static class ClearThumbnails extends AsyncTask<File, Void, Void> {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800145 @Override
146 public Void doInBackground(File... files) {
147 if (files != null) {
148 for (File f : files) {
Cary Clarkd6be1752009-08-12 12:56:42 -0400149 if (!f.delete()) {
150 Log.e(LOGTAG, f.getPath() + " was not deleted");
151 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800152 }
153 }
154 return null;
155 }
156 }
157
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400158 /**
159 * This layout holds everything you see below the status bar, including the
160 * error console, the custom view container, and the webviews.
161 */
162 private FrameLayout mBrowserFrameLayout;
Leon Scroggins81db3662009-06-04 17:45:11 -0400163
Leon Scrogginsd746a942010-05-19 13:21:44 -0400164 private boolean mXLargeScreenSize;
165
Jeff Davidson43610292010-07-16 16:03:58 -0700166 private Boolean mIsProviderPresent = null;
167 private Uri mRlzUri = null;
168
Grace Kloba22ac16e2009-10-07 18:00:23 -0700169 @Override
170 public void onCreate(Bundle icicle) {
Dave Bort31a6d1c2009-04-13 15:56:49 -0700171 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800172 Log.v(LOGTAG, this + " onStart");
173 }
174 super.onCreate(icicle);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800175 // test the browser in OpenGL
176 // requestWindowFeature(Window.FEATURE_OPENGL);
177
Mike Reedd334bf52010-01-26 15:21:44 -0500178 // enable this to test the browser in 32bit
179 if (false) {
180 getWindow().setFormat(PixelFormat.RGBX_8888);
181 BitmapFactory.setDefaultConfig(Bitmap.Config.ARGB_8888);
182 }
183
Svetoslav Ganov2b345992010-05-06 06:13:54 -0700184 if (AccessibilityManager.getInstance(this).isEnabled()) {
185 setDefaultKeyMode(DEFAULT_KEYS_DISABLE);
186 } else {
187 setDefaultKeyMode(DEFAULT_KEYS_SEARCH_LOCAL);
188 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800189
190 mResolver = getContentResolver();
191
Grace Kloba0923d692009-09-23 21:37:25 -0700192 // If this was a web search request, pass it on to the default web
193 // search provider and finish this activity.
194 if (handleWebSearchIntent(getIntent())) {
195 finish();
196 return;
197 }
198
The Android Open Source Project0c908882009-03-03 19:32:16 -0800199 mSecLockIcon = Resources.getSystem().getDrawable(
200 android.R.drawable.ic_secure);
201 mMixLockIcon = Resources.getSystem().getDrawable(
202 android.R.drawable.ic_partial_secure);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800203
Michael Kolbed217742010-08-10 17:52:34 -0700204 // Create the tab control and our initial tab
205 mTabControl = new TabControl(this);
206
207 mXLargeScreenSize = (getResources().getConfiguration().screenLayout
208 & Configuration.SCREENLAYOUT_SIZE_MASK)
209 == Configuration.SCREENLAYOUT_SIZE_XLARGE;
210
Leon Scroggins81db3662009-06-04 17:45:11 -0400211 FrameLayout frameLayout = (FrameLayout) getWindow().getDecorView()
212 .findViewById(com.android.internal.R.id.content);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400213 mBrowserFrameLayout = (FrameLayout) LayoutInflater.from(this)
214 .inflate(R.layout.custom_screen, null);
215 mContentView = (FrameLayout) mBrowserFrameLayout.findViewById(
216 R.id.main_content);
217 mErrorConsoleContainer = (LinearLayout) mBrowserFrameLayout
218 .findViewById(R.id.error_console);
219 mCustomViewContainer = (FrameLayout) mBrowserFrameLayout
220 .findViewById(R.id.fullscreen_custom_content);
221 frameLayout.addView(mBrowserFrameLayout, COVER_SCREEN_PARAMS);
Michael Kolbe0a36662010-06-29 10:37:12 -0700222
Leon Scrogginsd746a942010-05-19 13:21:44 -0400223 if (mXLargeScreenSize) {
Michael Kolba2b2ba82010-08-04 17:54:03 -0700224 mTitleBar = new TitleBarXLarge(this);
225 mTitleBar.setProgress(100);
226 mFakeTitleBar = new TitleBarXLarge(this);
Michael Kolbed217742010-08-10 17:52:34 -0700227 ActionBar actionBar = getActionBar();
Michael Kolba2b2ba82010-08-04 17:54:03 -0700228 mTabBar = new TabBar(this, mTabControl, (TitleBarXLarge) mFakeTitleBar);
Michael Kolbed217742010-08-10 17:52:34 -0700229 actionBar.setCustomNavigationMode(mTabBar);
Leon Scrogginsd746a942010-05-19 13:21:44 -0400230 } else {
Leon Scroggins571b3762010-05-26 10:25:01 -0400231 mTitleBar = new TitleBar(this);
Leon Scrogginsd746a942010-05-19 13:21:44 -0400232 // mTitleBar will be always be shown in the fully loaded mode on
233 // phone
234 mTitleBar.setProgress(100);
Leon Scrogginsd746a942010-05-19 13:21:44 -0400235 mFakeTitleBar = new TitleBar(this);
236 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800237
The Android Open Source Project0c908882009-03-03 19:32:16 -0800238 // Open the icon database and retain all the bookmark urls for favicons
239 retainIconsOnStartup();
240
241 // Keep a settings instance handy.
242 mSettings = BrowserSettings.getInstance();
243 mSettings.setTabControl(mTabControl);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800244
245 PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
246 mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Browser");
247
Patrick Scott6adacc92010-03-05 08:24:51 -0500248 // Find out if the network is currently up.
249 ConnectivityManager cm = (ConnectivityManager) getSystemService(
250 Context.CONNECTIVITY_SERVICE);
251 NetworkInfo info = cm.getActiveNetworkInfo();
252 if (info != null) {
253 mIsNetworkUp = info.isAvailable();
254 }
255
Grace Klobaa34f6862009-07-31 16:28:17 -0700256 /* enables registration for changes in network status from
257 http stack */
258 mNetworkStateChangedFilter = new IntentFilter();
259 mNetworkStateChangedFilter.addAction(
260 ConnectivityManager.CONNECTIVITY_ACTION);
261 mNetworkStateIntentReceiver = new BroadcastReceiver() {
262 @Override
263 public void onReceive(Context context, Intent intent) {
264 if (intent.getAction().equals(
265 ConnectivityManager.CONNECTIVITY_ACTION)) {
Andrei Popescue4c98462010-02-19 15:44:13 +0000266
267 NetworkInfo info = intent.getParcelableExtra(
268 ConnectivityManager.EXTRA_NETWORK_INFO);
269 String typeName = info.getTypeName();
270 String subtypeName = info.getSubtypeName();
271 sendNetworkType(typeName.toLowerCase(),
272 (subtypeName != null ? subtypeName.toLowerCase() : ""));
273
274 onNetworkToggle(info.isAvailable());
Grace Klobaa34f6862009-07-31 16:28:17 -0700275 }
276 }
277 };
278
The Android Open Source Project0c908882009-03-03 19:32:16 -0800279 if (!mTabControl.restoreState(icicle)) {
280 // clear up the thumbnail directory if we can't restore the state as
281 // none of the files in the directory are referenced any more.
282 new ClearThumbnails().execute(
283 mTabControl.getThumbnailDir().listFiles());
Grace Klobaaab3f092009-07-30 12:29:51 -0700284 // there is no quit on Android. But if we can't restore the state,
285 // we can treat it as a new Browser, remove the old session cookies.
286 CookieManager.getInstance().removeSessionCookie();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800287 final Intent intent = getIntent();
288 final Bundle extra = intent.getExtras();
289 // Create an initial tab.
290 // If the intent is ACTION_VIEW and data is not null, the Browser is
291 // invoked to view the content by another application. In this case,
292 // the tab will be close when exit.
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700293 UrlData urlData = getUrlDataFromIntent(intent);
294
Leon Scroggins58d56c62010-01-28 15:12:40 -0500295 String action = intent.getAction();
Grace Kloba22ac16e2009-10-07 18:00:23 -0700296 final Tab t = mTabControl.createNewTab(
Leon Scroggins58d56c62010-01-28 15:12:40 -0500297 (Intent.ACTION_VIEW.equals(action) &&
298 intent.getData() != null)
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -0500299 || RecognizerResultsIntent.ACTION_VOICE_SEARCH_RESULTS
300 .equals(action),
Elliott Slaughterf0f03952010-07-14 18:10:36 -0700301 intent.getStringExtra(Browser.EXTRA_APPLICATION_ID),
302 urlData.mUrl, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800303 mTabControl.setCurrentTab(t);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800304 attachTabToContentView(t);
305 WebView webView = t.getWebView();
306 if (extra != null) {
307 int scale = extra.getInt(Browser.INITIAL_ZOOM_LEVEL, 0);
308 if (scale > 0 && scale <= 1000) {
309 webView.setInitialScale(scale);
310 }
311 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800312
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700313 if (urlData.isEmpty()) {
Shimeng (Simon) Wang98d5fce2010-03-16 13:23:39 -0700314 loadUrl(webView, mSettings.getHomePage());
The Android Open Source Project0c908882009-03-03 19:32:16 -0800315 } else {
Patrick Scott9d53da02010-02-19 10:19:01 -0500316 loadUrlDataIn(t, urlData);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800317 }
318 } else {
319 // TabControl.restoreState() will create a new tab even if
Leon Scroggins1f005d32009-08-10 17:36:42 -0400320 // restoring the state fails.
The Android Open Source Project0c908882009-03-03 19:32:16 -0800321 attachTabToContentView(mTabControl.getCurrentTab());
322 }
Grace Kloba615c6c92009-08-03 10:22:44 -0700323
Cary Clarkb4b83182010-07-01 12:36:56 -0400324 // Delete old thumbnails to save space
325 File dir = mTabControl.getThumbnailDir();
326 if (dir.exists()) {
327 for (String child : dir.list()) {
328 File f = new File(dir, child);
329 f.delete();
330 }
331 }
332
Feng Qianb3c02da2009-06-29 15:58:08 -0700333 // Read JavaScript flags if it exists.
334 String jsFlags = mSettings.getJsFlags();
335 if (jsFlags.trim().length() != 0) {
336 mTabControl.getCurrentWebView().setJsFlags(jsFlags);
337 }
Bjorn Bringerta7611812010-03-24 11:12:02 +0000338
339 // Start watching the default geolocation permissions
340 mSystemAllowGeolocationOrigins
341 = new SystemAllowGeolocationOrigins(getApplicationContext());
342 mSystemAllowGeolocationOrigins.start();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800343 }
344
Michael Kolba2b2ba82010-08-04 17:54:03 -0700345 ScrollListener getScrollListener() {
346 return mTabBar;
347 }
348
Leon Scroggins58d56c62010-01-28 15:12:40 -0500349 /**
350 * Feed the previously stored results strings to the BrowserProvider so that
351 * the SearchDialog will show them instead of the standard searches.
352 * @param result String to show on the editable line of the SearchDialog.
353 */
354 /* package */ void showVoiceSearchResults(String result) {
355 ContentProviderClient client = mResolver.acquireContentProviderClient(
356 Browser.BOOKMARKS_URI);
357 ContentProvider prov = client.getLocalContentProvider();
358 BrowserProvider bp = (BrowserProvider) prov;
359 bp.setQueryResults(mTabControl.getCurrentTab().getVoiceSearchResults());
360 client.release();
361
Leon Scrogginsfbb3f152010-03-09 17:26:56 -0500362 Bundle bundle = createGoogleSearchSourceBundle(
363 GOOGLE_SEARCH_SOURCE_SEARCHKEY);
364 bundle.putBoolean(SearchManager.CONTEXT_IS_VOICE, true);
365 startSearch(result, false, bundle, false);
Leon Scroggins58d56c62010-01-28 15:12:40 -0500366 }
367
The Android Open Source Project0c908882009-03-03 19:32:16 -0800368 @Override
369 protected void onNewIntent(Intent intent) {
Grace Kloba22ac16e2009-10-07 18:00:23 -0700370 Tab current = mTabControl.getCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800371 // When a tab is closed on exit, the current tab index is set to -1.
372 // Reset before proceed as Browser requires the current tab to be set.
373 if (current == null) {
374 // Try to reset the tab in case the index was incorrect.
375 current = mTabControl.getTab(0);
376 if (current == null) {
377 // No tabs at all so just ignore this intent.
378 return;
379 }
380 mTabControl.setCurrentTab(current);
381 attachTabToContentView(current);
382 resetTitleAndIcon(current.getWebView());
383 }
384 final String action = intent.getAction();
385 final int flags = intent.getFlags();
386 if (Intent.ACTION_MAIN.equals(action) ||
387 (flags & Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY) != 0) {
388 // just resume the browser
389 return;
390 }
Leon Scrogginsb8a844d2010-03-18 15:06:15 -0400391 // In case the SearchDialog is open.
392 ((SearchManager) getSystemService(Context.SEARCH_SERVICE))
393 .stopSearch();
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -0500394 boolean activateVoiceSearch = RecognizerResultsIntent
395 .ACTION_VOICE_SEARCH_RESULTS.equals(action);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800396 if (Intent.ACTION_VIEW.equals(action)
397 || Intent.ACTION_SEARCH.equals(action)
398 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
Leon Scroggins58d56c62010-01-28 15:12:40 -0500399 || Intent.ACTION_WEB_SEARCH.equals(action)
400 || activateVoiceSearch) {
Leon Scroggins3b18ce32010-02-08 17:35:59 -0500401 if (current.isInVoiceSearchMode()) {
402 String title = current.getVoiceDisplayTitle();
403 if (title != null && title.equals(intent.getStringExtra(
404 SearchManager.QUERY))) {
405 // The user submitted the same search as the last voice
406 // search, so do nothing.
407 return;
408 }
Leon Scroggins1fe13a52010-02-09 15:31:26 -0500409 if (Intent.ACTION_SEARCH.equals(action)
410 && current.voiceSearchSourceIsGoogle()) {
411 Intent logIntent = new Intent(
412 LoggingEvents.ACTION_LOG_EVENT);
413 logIntent.putExtra(LoggingEvents.EXTRA_EVENT,
414 LoggingEvents.VoiceSearch.QUERY_UPDATED);
415 logIntent.putExtra(
416 LoggingEvents.VoiceSearch.EXTRA_QUERY_UPDATED_VALUE,
417 intent.getDataString());
418 sendBroadcast(logIntent);
419 // Note, onPageStarted will revert the voice title bar
420 // When http://b/issue?id=2379215 is fixed, we should update
421 // the title bar here.
422 }
Leon Scroggins3b18ce32010-02-08 17:35:59 -0500423 }
Satish Sampath565505b2009-05-29 15:37:27 +0100424 // If this was a search request (e.g. search query directly typed into the address bar),
425 // pass it on to the default web search provider.
426 if (handleWebSearchIntent(intent)) {
427 return;
428 }
429
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700430 UrlData urlData = getUrlDataFromIntent(intent);
431 if (urlData.isEmpty()) {
432 urlData = new UrlData(mSettings.getHomePage());
The Android Open Source Project0c908882009-03-03 19:32:16 -0800433 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700434
Grace Klobacc634032009-07-28 15:58:19 -0700435 final String appId = intent
436 .getStringExtra(Browser.EXTRA_APPLICATION_ID);
Leon Scroggins47208682010-04-07 17:59:48 -0400437 if ((Intent.ACTION_VIEW.equals(action)
438 // If a voice search has no appId, it means that it came
439 // from the browser. In that case, reuse the current tab.
440 || (activateVoiceSearch && appId != null))
Grace Klobacc634032009-07-28 15:58:19 -0700441 && !getPackageName().equals(appId)
442 && (flags & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0) {
Grace Kloba22ac16e2009-10-07 18:00:23 -0700443 Tab appTab = mTabControl.getTabFromId(appId);
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700444 if (appTab != null) {
445 Log.i(LOGTAG, "Reusing tab for " + appId);
446 // Dismiss the subwindow if applicable.
447 dismissSubWindow(appTab);
448 // Since we might kill the WebView, remove it from the
449 // content view first.
450 removeTabFromContentView(appTab);
451 // Recreate the main WebView after destroying the old one.
452 // If the WebView has the same original url and is on that
453 // page, it can be reused.
454 boolean needsLoad =
Leon Scroggins6eac63e2010-03-15 18:19:14 -0400455 mTabControl.recreateWebView(appTab, urlData);
Ben Murdochbff2d602009-07-01 20:19:05 +0100456
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700457 if (current != appTab) {
Leon Scroggins1f005d32009-08-10 17:36:42 -0400458 switchToTab(mTabControl.getTabIndex(appTab));
459 if (needsLoad) {
Patrick Scott9d53da02010-02-19 10:19:01 -0500460 loadUrlDataIn(appTab, urlData);
Leon Scroggins1f005d32009-08-10 17:36:42 -0400461 }
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700462 } else {
Leon Scroggins1f005d32009-08-10 17:36:42 -0400463 // If the tab was the current tab, we have to attach
464 // it to the view system again.
465 attachTabToContentView(appTab);
466 if (needsLoad) {
Patrick Scott9d53da02010-02-19 10:19:01 -0500467 loadUrlDataIn(appTab, urlData);
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700468 }
469 }
470 return;
Patrick Scottcd115892009-07-16 09:42:58 -0400471 } else {
472 // No matching application tab, try to find a regular tab
473 // with a matching url.
474 appTab = mTabControl.findUnusedTabWithUrl(urlData.mUrl);
Leon Scroggins25515f82009-08-19 15:31:58 -0400475 if (appTab != null) {
476 if (current != appTab) {
477 switchToTab(mTabControl.getTabIndex(appTab));
478 }
479 // Otherwise, we are already viewing the correct tab.
Patrick Scottcd115892009-07-16 09:42:58 -0400480 } else {
481 // if FLAG_ACTIVITY_BROUGHT_TO_FRONT flag is on, the url
482 // will be opened in a new tab unless we have reached
483 // MAX_TABS. Then the url will be opened in the current
484 // tab. If a new tab is created, it will have "true" for
485 // exit on close.
Leon Scroggins1f005d32009-08-10 17:36:42 -0400486 openTabAndShow(urlData, true, appId);
Patrick Scottcd115892009-07-16 09:42:58 -0400487 }
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700488 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800489 } else {
Grace Kloba638d3f42009-11-23 10:35:04 -0800490 if (!urlData.isEmpty()
491 && urlData.mUrl.startsWith("about:debug")) {
492 if ("about:debug.dom".equals(urlData.mUrl)) {
493 current.getWebView().dumpDomTree(false);
494 } else if ("about:debug.dom.file".equals(urlData.mUrl)) {
495 current.getWebView().dumpDomTree(true);
496 } else if ("about:debug.render".equals(urlData.mUrl)) {
497 current.getWebView().dumpRenderTree(false);
498 } else if ("about:debug.render.file".equals(urlData.mUrl)) {
499 current.getWebView().dumpRenderTree(true);
500 } else if ("about:debug.display".equals(urlData.mUrl)) {
501 current.getWebView().dumpDisplayTree();
Mike Reed9b78e1d2010-01-13 14:40:52 -0800502 } else if (urlData.mUrl.startsWith("about:debug.drag")) {
503 int index = urlData.mUrl.codePointAt(16) - '0';
504 if (index <= 0 || index > 9) {
505 current.getWebView().setDragTracker(null);
506 } else {
507 current.getWebView().setDragTracker(new MeshTracker(index));
508 }
Grace Kloba638d3f42009-11-23 10:35:04 -0800509 } else {
510 mSettings.toggleDebugSettings();
511 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800512 return;
513 }
Leon Scroggins1f005d32009-08-10 17:36:42 -0400514 // Get rid of the subwindow if it exists
515 dismissSubWindow(current);
Leon Scroggins8588d152010-04-15 11:01:53 -0400516 // If the current Tab is being used as an application tab,
517 // remove the association, since the new Intent means that it is
518 // no longer associated with that application.
519 current.setAppId(null);
Patrick Scott9d53da02010-02-19 10:19:01 -0500520 loadUrlDataIn(current, urlData);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800521 }
522 }
523 }
524
Satish Sampath565505b2009-05-29 15:37:27 +0100525 private int parseUrlShortcut(String url) {
526 if (url == null) return SHORTCUT_INVALID;
527
528 // FIXME: quick search, need to be customized by setting
529 if (url.length() > 2 && url.charAt(1) == ' ') {
530 switch (url.charAt(0)) {
531 case 'g': return SHORTCUT_GOOGLE_SEARCH;
532 case 'w': return SHORTCUT_WIKIPEDIA_SEARCH;
533 case 'd': return SHORTCUT_DICTIONARY_SEARCH;
534 case 'l': return SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH;
535 }
536 }
537 return SHORTCUT_INVALID;
538 }
539
540 /**
541 * Launches the default web search activity with the query parameters if the given intent's data
542 * are identified as plain search terms and not URLs/shortcuts.
543 * @return true if the intent was handled and web search activity was launched, false if not.
544 */
545 private boolean handleWebSearchIntent(Intent intent) {
546 if (intent == null) return false;
547
548 String url = null;
549 final String action = intent.getAction();
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -0500550 if (RecognizerResultsIntent.ACTION_VOICE_SEARCH_RESULTS.equals(
551 action)) {
Leon Scroggins58d56c62010-01-28 15:12:40 -0500552 return false;
553 }
Satish Sampath565505b2009-05-29 15:37:27 +0100554 if (Intent.ACTION_VIEW.equals(action)) {
Grace Kloba1e705052009-09-29 13:13:36 -0700555 Uri data = intent.getData();
556 if (data != null) url = data.toString();
Satish Sampath565505b2009-05-29 15:37:27 +0100557 } else if (Intent.ACTION_SEARCH.equals(action)
558 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
559 || Intent.ACTION_WEB_SEARCH.equals(action)) {
560 url = intent.getStringExtra(SearchManager.QUERY);
561 }
Bjorn Bringert04851702009-09-22 10:36:01 +0100562 return handleWebSearchRequest(url, intent.getBundleExtra(SearchManager.APP_DATA),
563 intent.getStringExtra(SearchManager.EXTRA_DATA_KEY));
Satish Sampath565505b2009-05-29 15:37:27 +0100564 }
565
566 /**
567 * Launches the default web search activity with the query parameters if the given url string
568 * was identified as plain search terms and not URL/shortcut.
569 * @return true if the request was handled and web search activity was launched, false if not.
570 */
Bjorn Bringert04851702009-09-22 10:36:01 +0100571 private boolean handleWebSearchRequest(String inUrl, Bundle appData, String extraData) {
Satish Sampath565505b2009-05-29 15:37:27 +0100572 if (inUrl == null) return false;
573
574 // In general, we shouldn't modify URL from Intent.
575 // But currently, we get the user-typed URL from search box as well.
576 String url = fixUrl(inUrl).trim();
577
578 // URLs and site specific search shortcuts are handled by the regular flow of control, so
579 // return early.
Dan Egnor5ee906c2009-11-18 12:11:49 -0800580 if (Patterns.WEB_URL.matcher(url).matches()
Satish Sampathbc5b9f32009-06-04 18:21:40 +0100581 || ACCEPTED_URI_SCHEMA.matcher(url).matches()
Satish Sampath565505b2009-05-29 15:37:27 +0100582 || parseUrlShortcut(url) != SHORTCUT_INVALID) {
583 return false;
584 }
585
Leon Scroggins8d06e362010-03-24 14:45:57 -0400586 final ContentResolver cr = mResolver;
587 final String newUrl = url;
Elliott Slaughter627d96f2010-08-18 16:35:30 -0700588 if (mTabControl == null || !mTabControl.getCurrentWebView().isPrivateBrowsingEnabled()) {
Elliott Slaughterf0f03952010-07-14 18:10:36 -0700589 new AsyncTask<Void, Void, Void>() {
590 @Override
591 protected Void doInBackground(Void... unused) {
592 Browser.updateVisitedHistory(cr, newUrl, false);
593 Browser.addSearchUrl(cr, newUrl);
594 return null;
595 }
596 }.execute();
597 }
Satish Sampath565505b2009-05-29 15:37:27 +0100598
599 Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);
600 intent.addCategory(Intent.CATEGORY_DEFAULT);
601 intent.putExtra(SearchManager.QUERY, url);
Satish Sampath15e9f2d2009-06-23 22:29:49 +0100602 if (appData != null) {
603 intent.putExtra(SearchManager.APP_DATA, appData);
604 }
Bjorn Bringert04851702009-09-22 10:36:01 +0100605 if (extraData != null) {
606 intent.putExtra(SearchManager.EXTRA_DATA_KEY, extraData);
607 }
Grace Klobacc634032009-07-28 15:58:19 -0700608 intent.putExtra(Browser.EXTRA_APPLICATION_ID, getPackageName());
Mattias Falk552751e2010-08-23 12:03:57 +0200609
610 // can't be sure there is an activity for the Intent
611 try {
612 startActivity(intent);
613 } catch (ActivityNotFoundException ex) {
614 return false;
615 }
Satish Sampath565505b2009-05-29 15:37:27 +0100616
617 return true;
618 }
619
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700620 private UrlData getUrlDataFromIntent(Intent intent) {
Leon Scroggins58d56c62010-01-28 15:12:40 -0500621 String url = "";
Grace Kloba068e48b2010-01-26 18:11:27 -0800622 Map<String, String> headers = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800623 if (intent != null) {
624 final String action = intent.getAction();
625 if (Intent.ACTION_VIEW.equals(action)) {
626 url = smartUrlFilter(intent.getData());
627 if (url != null && url.startsWith("content:")) {
628 /* Append mimetype so webview knows how to display */
629 String mimeType = intent.resolveType(getContentResolver());
630 if (mimeType != null) {
631 url += "?" + mimeType;
632 }
633 }
Grace Kloba068e48b2010-01-26 18:11:27 -0800634 if (url != null && url.startsWith("http")) {
Grace Kloba00f54c52010-01-27 14:53:51 -0800635 final Bundle pairs = intent
636 .getBundleExtra(Browser.EXTRA_HEADERS);
Grace Kloba2d508ed2010-01-28 11:39:15 -0800637 if (pairs != null && !pairs.isEmpty()) {
Grace Kloba00f54c52010-01-27 14:53:51 -0800638 Iterator<String> iter = pairs.keySet().iterator();
Grace Kloba068e48b2010-01-26 18:11:27 -0800639 headers = new HashMap<String, String>();
Grace Kloba00f54c52010-01-27 14:53:51 -0800640 while (iter.hasNext()) {
641 String key = iter.next();
642 headers.put(key, pairs.getString(key));
Grace Kloba068e48b2010-01-26 18:11:27 -0800643 }
644 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700645 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800646 } else if (Intent.ACTION_SEARCH.equals(action)
647 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
648 || Intent.ACTION_WEB_SEARCH.equals(action)) {
649 url = intent.getStringExtra(SearchManager.QUERY);
650 if (url != null) {
651 mLastEnteredUrl = url;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800652 // In general, we shouldn't modify URL from Intent.
653 // But currently, we get the user-typed URL from search box as well.
654 url = fixUrl(url);
655 url = smartUrlFilter(url);
Leon Scroggins8d06e362010-03-24 14:45:57 -0400656 final ContentResolver cr = mResolver;
657 final String newUrl = url;
Elliott Slaughter8389e992010-08-20 15:44:08 -0700658 if (mTabControl == null
659 || mTabControl.getCurrentWebView() == null
660 || !mTabControl.getCurrentWebView().isPrivateBrowsingEnabled()) {
661 new AsyncTask<Void, Void, Void>() {
662 @Override
663 protected Void doInBackground(Void... unused) {
664 Browser.updateVisitedHistory(cr, newUrl, false);
665 return null;
666 }
667 }.execute();
668 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800669 String searchSource = "&source=android-" + GOOGLE_SEARCH_SOURCE_SUGGEST + "&";
670 if (url.contains(searchSource)) {
671 String source = null;
672 final Bundle appData = intent.getBundleExtra(SearchManager.APP_DATA);
673 if (appData != null) {
Bjorn Bringert10d1cca2010-02-10 14:22:12 +0000674 source = appData.getString(Search.SOURCE);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800675 }
676 if (TextUtils.isEmpty(source)) {
677 source = GOOGLE_SEARCH_SOURCE_UNKNOWN;
678 }
679 url = url.replace(searchSource, "&source=android-"+source+"&");
680 }
681 }
682 }
683 }
Leon Scroggins58d56c62010-01-28 15:12:40 -0500684 return new UrlData(url, headers, intent);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800685 }
Leon Scroggins58d56c62010-01-28 15:12:40 -0500686 /* package */ void showVoiceTitleBar(String title) {
687 mTitleBar.setInVoiceMode(true);
Leon Scroggins58d56c62010-01-28 15:12:40 -0500688 mTitleBar.setDisplayTitle(title);
Michael Kolba2b2ba82010-08-04 17:54:03 -0700689 mFakeTitleBar.setInVoiceMode(true);
690 mFakeTitleBar.setDisplayTitle(title);
Leon Scroggins58d56c62010-01-28 15:12:40 -0500691 }
692 /* package */ void revertVoiceTitleBar() {
693 mTitleBar.setInVoiceMode(false);
Leon Scroggins003a5dd2010-03-10 12:13:14 -0500694 mTitleBar.setDisplayTitle(mUrl);
Michael Kolba2b2ba82010-08-04 17:54:03 -0700695 mFakeTitleBar.setInVoiceMode(false);
696 mFakeTitleBar.setDisplayTitle(mUrl);
Leon Scroggins58d56c62010-01-28 15:12:40 -0500697 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800698 /* package */ static String fixUrl(String inUrl) {
Cary Clark652ff872009-09-10 13:34:44 -0400699 // FIXME: Converting the url to lower case
700 // duplicates functionality in smartUrlFilter().
701 // However, changing all current callers of fixUrl to
702 // call smartUrlFilter in addition may have unwanted
703 // consequences, and is deferred for now.
704 int colon = inUrl.indexOf(':');
705 boolean allLower = true;
706 for (int index = 0; index < colon; index++) {
707 char ch = inUrl.charAt(index);
708 if (!Character.isLetter(ch)) {
709 break;
710 }
711 allLower &= Character.isLowerCase(ch);
712 if (index == colon - 1 && !allLower) {
713 inUrl = inUrl.substring(0, colon).toLowerCase()
714 + inUrl.substring(colon);
715 }
716 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800717 if (inUrl.startsWith("http://") || inUrl.startsWith("https://"))
718 return inUrl;
719 if (inUrl.startsWith("http:") ||
720 inUrl.startsWith("https:")) {
721 if (inUrl.startsWith("http:/") || inUrl.startsWith("https:/")) {
722 inUrl = inUrl.replaceFirst("/", "//");
723 } else inUrl = inUrl.replaceFirst(":", "://");
724 }
725 return inUrl;
726 }
727
Grace Kloba22ac16e2009-10-07 18:00:23 -0700728 @Override
729 protected void onResume() {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800730 super.onResume();
Dave Bort31a6d1c2009-04-13 15:56:49 -0700731 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800732 Log.v(LOGTAG, "BrowserActivity.onResume: this=" + this);
733 }
734
735 if (!mActivityInPause) {
736 Log.e(LOGTAG, "BrowserActivity is already resumed.");
737 return;
738 }
739
Mike Reed7bfa63b2009-05-28 11:08:32 -0400740 mTabControl.resumeCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800741 mActivityInPause = false;
Mike Reed7bfa63b2009-05-28 11:08:32 -0400742 resumeWebViewTimers();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800743
744 if (mWakeLock.isHeld()) {
745 mHandler.removeMessages(RELEASE_WAKELOCK);
746 mWakeLock.release();
747 }
748
The Android Open Source Project0c908882009-03-03 19:32:16 -0800749 registerReceiver(mNetworkStateIntentReceiver,
750 mNetworkStateChangedFilter);
751 WebView.enablePlatformNotifications();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800752 }
753
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400754 /**
755 * Since the actual title bar is embedded in the WebView, and removing it
Leon Scrogginsfe87bd32009-10-06 10:10:00 -0400756 * would change its appearance, use a different TitleBar to show overlayed
757 * at the top of the screen, when the menu is open or the page is loading.
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400758 */
Michael Kolba2b2ba82010-08-04 17:54:03 -0700759 private TitleBarBase mFakeTitleBar;
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400760
761 /**
762 * Keeps track of whether the options menu is open. This is important in
763 * determining whether to show or hide the title bar overlay.
764 */
765 private boolean mOptionsMenuOpen;
766
767 /**
768 * Only meaningful when mOptionsMenuOpen is true. This variable keeps track
769 * of whether the configuration has changed. The first onMenuOpened call
770 * after a configuration change is simply a reopening of the same menu
771 * (i.e. mIconView did not change).
772 */
773 private boolean mConfigChanged;
774
775 /**
776 * Whether or not the options menu is in its smaller, icon menu form. When
777 * true, we want the title bar overlay to be up. When false, we do not.
778 * Only meaningful if mOptionsMenuOpen is true.
779 */
780 private boolean mIconView;
781
Leon Scrogginsa81a7642009-08-31 17:05:41 -0400782 @Override
783 public boolean onMenuOpened(int featureId, Menu menu) {
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400784 if (Window.FEATURE_OPTIONS_PANEL == featureId) {
785 if (mOptionsMenuOpen) {
786 if (mConfigChanged) {
787 // We do not need to make any changes to the state of the
788 // title bar, since the only thing that happened was a
789 // change in orientation
790 mConfigChanged = false;
791 } else {
792 if (mIconView) {
793 // Switching the menu to expanded view, so hide the
794 // title bar.
795 hideFakeTitleBar();
796 mIconView = false;
797 } else {
798 // Switching the menu back to icon view, so show the
799 // title bar once again.
800 showFakeTitleBar();
801 mIconView = true;
802 }
803 }
804 } else {
805 // The options menu is closed, so open it, and show the title
806 showFakeTitleBar();
807 mOptionsMenuOpen = true;
808 mConfigChanged = false;
809 mIconView = true;
810 }
811 }
Leon Scrogginsa81a7642009-08-31 17:05:41 -0400812 return true;
813 }
814
Michael Kolba2b2ba82010-08-04 17:54:03 -0700815 void showFakeTitleBar() {
816 if (!isFakeTitleBarShowing() && mActiveTabsPage == null && !mActivityInPause) {
Grace Kloba847c25b2010-03-30 16:00:26 -0700817 WebView mainView = mTabControl.getCurrentWebView();
818 // if there is no current WebView, don't show the faked title bar;
Grace Kloba65190702010-04-02 23:37:26 -0700819 if (mainView == null) {
Cary Clarka0464552009-09-29 13:00:45 -0400820 return;
821 }
Leon Scroggins79e36d92010-04-29 16:01:46 +0100822 // Do not need to check for null, since the current tab will have
823 // at least a main WebView, or we would have returned above.
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -0400824 if (isInCustomActionMode()) {
825 // Do not show the fake title bar, while a custom ActionMode
826 // (i.e. find or select) is showing.
Leon Scroggins79e36d92010-04-29 16:01:46 +0100827 return;
828 }
Michael Kolba2b2ba82010-08-04 17:54:03 -0700829 if (mXLargeScreenSize) {
830 mContentView.addView(mFakeTitleBar);
831 mTabBar.onShowTitleBar();
832 } else {
833 WindowManager manager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400834
Michael Kolba2b2ba82010-08-04 17:54:03 -0700835 // Add the title bar to the window manager so it can receive
836 // touches
837 // while the menu is up
838 WindowManager.LayoutParams params =
839 new WindowManager.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
840 ViewGroup.LayoutParams.WRAP_CONTENT,
841 WindowManager.LayoutParams.TYPE_APPLICATION,
842 WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
843 PixelFormat.TRANSLUCENT);
844 params.gravity = Gravity.TOP;
845 boolean atTop = mainView.getScrollY() == 0;
846 params.windowAnimations = atTop ? 0 : R.style.TitleBar;
847 manager.addView(mFakeTitleBar, params);
848 }
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400849 }
850 }
851
852 @Override
853 public void onOptionsMenuClosed(Menu menu) {
854 mOptionsMenuOpen = false;
Leon Scrogginsa27ff192009-09-14 12:58:04 -0400855 if (!mInLoad) {
856 hideFakeTitleBar();
857 } else if (!mIconView) {
858 // The page is currently loading, and we are in expanded mode, so
859 // we were not showing the menu. Show it once again. It will be
860 // removed when the page finishes.
861 showFakeTitleBar();
862 }
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400863 }
Grace Kloba22ac16e2009-10-07 18:00:23 -0700864
Michael Kolba2b2ba82010-08-04 17:54:03 -0700865 void stopScrolling() {
866 ((ScrollWebView) mTabControl.getCurrentWebView()).stopScroll();
867 }
868
869 void hideFakeTitleBar() {
870 if (!isFakeTitleBarShowing()) return;
871 if (mXLargeScreenSize) {
872 mContentView.removeView(mFakeTitleBar);
873 mTabBar.onHideTitleBar();
874 } else {
875 WindowManager.LayoutParams params =
876 (WindowManager.LayoutParams) mFakeTitleBar.getLayoutParams();
877 WebView mainView = mTabControl.getCurrentWebView();
878 // Although we decided whether or not to animate based on the
879 // current
880 // scroll position, the scroll position may have changed since the
881 // fake title bar was displayed. Make sure it has the appropriate
882 // animation/lack thereof before removing.
883 params.windowAnimations =
884 mainView != null && mainView.getScrollY() == 0 ? 0 : R.style.TitleBar;
885 WindowManager manager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
886 manager.updateViewLayout(mFakeTitleBar, params);
887 manager.removeView(mFakeTitleBar);
888 }
889 }
890
891 boolean isFakeTitleBarShowing() {
892 return (mFakeTitleBar.getParent() != null);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400893 }
894
The Android Open Source Project0c908882009-03-03 19:32:16 -0800895 /**
Leon Scrogginsc6fa1102009-09-21 10:40:01 -0400896 * Special method for the fake title bar to call when displaying its context
897 * menu, since it is in its own Window, and its parent does not show a
898 * context menu.
899 */
900 /* package */ void showTitleBarContextMenu() {
Cary Clark65f4a3c2009-09-28 17:05:06 -0400901 if (null == mTitleBar.getParent()) {
902 return;
903 }
Leon Scrogginsc6fa1102009-09-21 10:40:01 -0400904 openContextMenu(mTitleBar);
905 }
906
Leon Scrogginsb2b19f52009-10-09 16:10:00 -0400907 @Override
908 public void onContextMenuClosed(Menu menu) {
909 super.onContextMenuClosed(menu);
910 if (mInLoad) {
911 showFakeTitleBar();
912 }
913 }
914
Leon Scrogginsc6fa1102009-09-21 10:40:01 -0400915 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -0800916 * onSaveInstanceState(Bundle map)
917 * onSaveInstanceState is called right before onStop(). The map contains
918 * the saved state.
919 */
Grace Kloba22ac16e2009-10-07 18:00:23 -0700920 @Override
921 protected void onSaveInstanceState(Bundle outState) {
Dave Bort31a6d1c2009-04-13 15:56:49 -0700922 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800923 Log.v(LOGTAG, "BrowserActivity.onSaveInstanceState: this=" + this);
924 }
925 // the default implementation requires each view to have an id. As the
926 // browser handles the state itself and it doesn't use id for the views,
927 // don't call the default implementation. Otherwise it will trigger the
928 // warning like this, "couldn't save which view has focus because the
929 // focused view XXX has no id".
930
931 // Save all the tabs
932 mTabControl.saveState(outState);
933 }
934
Grace Kloba22ac16e2009-10-07 18:00:23 -0700935 @Override
936 protected void onPause() {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800937 super.onPause();
938
939 if (mActivityInPause) {
940 Log.e(LOGTAG, "BrowserActivity is already paused.");
941 return;
942 }
943
Mike Reed7bfa63b2009-05-28 11:08:32 -0400944 mTabControl.pauseCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800945 mActivityInPause = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -0400946 if (mTabControl.getCurrentIndex() >= 0 && !pauseWebViewTimers()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800947 mWakeLock.acquire();
948 mHandler.sendMessageDelayed(mHandler
949 .obtainMessage(RELEASE_WAKELOCK), WAKELOCK_TIMEOUT);
950 }
951
Leon Scrogginsa2ab6a72009-09-11 11:49:52 -0400952 // FIXME: This removes the active tabs page and resets the menu to
953 // MAIN_MENU. A better solution might be to do this work in onNewIntent
954 // but then we would need to save it in onSaveInstanceState and restore
955 // it in onCreate/onRestoreInstanceState
956 if (mActiveTabsPage != null) {
957 removeActiveTabPage(true);
958 }
959
The Android Open Source Project0c908882009-03-03 19:32:16 -0800960 cancelStopToast();
961
962 // unregister network state listener
963 unregisterReceiver(mNetworkStateIntentReceiver);
964 WebView.disablePlatformNotifications();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800965 }
966
Grace Kloba22ac16e2009-10-07 18:00:23 -0700967 @Override
968 protected void onDestroy() {
Dave Bort31a6d1c2009-04-13 15:56:49 -0700969 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800970 Log.v(LOGTAG, "BrowserActivity.onDestroy: this=" + this);
971 }
972 super.onDestroy();
Grace Kloba0923d692009-09-23 21:37:25 -0700973
Leon Scroggins8d5fa432009-10-02 15:55:59 -0400974 if (mUploadMessage != null) {
975 mUploadMessage.onReceiveValue(null);
976 mUploadMessage = null;
977 }
978
Grace Kloba0923d692009-09-23 21:37:25 -0700979 if (mTabControl == null) return;
980
Grace Kloba1fc98a32009-10-21 13:23:08 -0700981 // Remove the fake title bar if it is there
982 hideFakeTitleBar();
983
The Android Open Source Project0c908882009-03-03 19:32:16 -0800984 // Remove the current tab and sub window
Grace Kloba22ac16e2009-10-07 18:00:23 -0700985 Tab t = mTabControl.getCurrentTab();
Patrick Scottfb5e77f2009-04-08 19:17:37 -0700986 if (t != null) {
987 dismissSubWindow(t);
988 removeTabFromContentView(t);
989 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800990 // Destroy all the tabs
991 mTabControl.destroy();
992 WebIconDatabase.getInstance().close();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800993
Bjorn Bringerta7611812010-03-24 11:12:02 +0000994 // Stop watching the default geolocation permissions
995 mSystemAllowGeolocationOrigins.stop();
996 mSystemAllowGeolocationOrigins = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800997 }
998
999 @Override
1000 public void onConfigurationChanged(Configuration newConfig) {
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04001001 mConfigChanged = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001002 super.onConfigurationChanged(newConfig);
1003
1004 if (mPageInfoDialog != null) {
1005 mPageInfoDialog.dismiss();
1006 showPageInfo(
1007 mPageInfoView,
Leon Scrogginsc7b92f82010-01-11 18:17:31 -05001008 mPageInfoFromShowSSLCertificateOnError);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001009 }
1010 if (mSSLCertificateDialog != null) {
1011 mSSLCertificateDialog.dismiss();
1012 showSSLCertificate(
1013 mSSLCertificateView);
1014 }
1015 if (mSSLCertificateOnErrorDialog != null) {
1016 mSSLCertificateOnErrorDialog.dismiss();
1017 showSSLCertificateOnError(
1018 mSSLCertificateOnErrorView,
1019 mSSLCertificateOnErrorHandler,
1020 mSSLCertificateOnErrorError);
1021 }
1022 if (mHttpAuthenticationDialog != null) {
1023 String title = ((TextView) mHttpAuthenticationDialog
1024 .findViewById(com.android.internal.R.id.alertTitle)).getText()
1025 .toString();
1026 String name = ((TextView) mHttpAuthenticationDialog
1027 .findViewById(R.id.username_edit)).getText().toString();
1028 String password = ((TextView) mHttpAuthenticationDialog
1029 .findViewById(R.id.password_edit)).getText().toString();
1030 int focusId = mHttpAuthenticationDialog.getCurrentFocus()
1031 .getId();
1032 mHttpAuthenticationDialog.dismiss();
1033 showHttpAuthentication(mHttpAuthHandler, null, null, title,
1034 name, password, focusId);
1035 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001036 }
1037
Grace Kloba22ac16e2009-10-07 18:00:23 -07001038 @Override
1039 public void onLowMemory() {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001040 super.onLowMemory();
1041 mTabControl.freeMemory();
1042 }
1043
Cary Clarkff4d92c2010-03-25 11:17:03 -04001044 private void resumeWebViewTimers() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001045 Tab tab = mTabControl.getCurrentTab();
Cary Clarkff4d92c2010-03-25 11:17:03 -04001046 if (tab == null) return; // monkey can trigger this
Grace Kloba22ac16e2009-10-07 18:00:23 -07001047 boolean inLoad = tab.inLoad();
1048 if ((!mActivityInPause && !inLoad) || (mActivityInPause && inLoad)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001049 CookieSyncManager.getInstance().startSync();
Grace Kloba22ac16e2009-10-07 18:00:23 -07001050 WebView w = tab.getWebView();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001051 if (w != null) {
1052 w.resumeTimers();
1053 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001054 }
1055 }
1056
Mike Reed7bfa63b2009-05-28 11:08:32 -04001057 private boolean pauseWebViewTimers() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001058 Tab tab = mTabControl.getCurrentTab();
1059 boolean inLoad = tab.inLoad();
1060 if (mActivityInPause && !inLoad) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001061 CookieSyncManager.getInstance().stopSync();
1062 WebView w = mTabControl.getCurrentWebView();
1063 if (w != null) {
1064 w.pauseTimers();
1065 }
1066 return true;
1067 } else {
1068 return false;
1069 }
1070 }
1071
The Android Open Source Project0c908882009-03-03 19:32:16 -08001072 // Open the icon database and retain all the icons for visited sites.
1073 private void retainIconsOnStartup() {
1074 final WebIconDatabase db = WebIconDatabase.getInstance();
1075 db.open(getDir("icons", 0).getPath());
Leon Scroggins2c0f6112010-03-12 18:09:39 -05001076 Cursor c = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001077 try {
Leon Scroggins2c0f6112010-03-12 18:09:39 -05001078 c = Browser.getAllBookmarks(mResolver);
1079 if (c.moveToFirst()) {
1080 int urlIndex = c.getColumnIndex(Browser.BookmarkColumns.URL);
1081 do {
1082 String url = c.getString(urlIndex);
1083 db.retainIconForPageUrl(url);
1084 } while (c.moveToNext());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001085 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001086 } catch (IllegalStateException e) {
1087 Log.e(LOGTAG, "retainIconsOnStartup", e);
Leon Scroggins2c0f6112010-03-12 18:09:39 -05001088 } finally {
1089 if (c!= null) c.close();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001090 }
1091 }
1092
1093 // Helper method for getting the top window.
1094 WebView getTopWindow() {
1095 return mTabControl.getCurrentTopWebView();
1096 }
1097
Grace Kloba22ac16e2009-10-07 18:00:23 -07001098 TabControl getTabControl() {
1099 return mTabControl;
1100 }
1101
The Android Open Source Project0c908882009-03-03 19:32:16 -08001102 @Override
1103 public boolean onCreateOptionsMenu(Menu menu) {
1104 super.onCreateOptionsMenu(menu);
1105
1106 MenuInflater inflater = getMenuInflater();
1107 inflater.inflate(R.menu.browser, menu);
1108 mMenu = menu;
1109 updateInLoadMenuItems();
1110 return true;
1111 }
1112
1113 /**
1114 * As the menu can be open when loading state changes
1115 * we must manually update the state of the stop/reload menu
1116 * item
1117 */
1118 private void updateInLoadMenuItems() {
1119 if (mMenu == null) {
1120 return;
1121 }
Michael Kolbe0a36662010-06-29 10:37:12 -07001122 MenuItem dest = mMenu.findItem(R.id.stop_reload_menu_id);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001123 MenuItem src = mInLoad ?
1124 mMenu.findItem(R.id.stop_menu_id):
Michael Kolbe0a36662010-06-29 10:37:12 -07001125 mMenu.findItem(R.id.reload_menu_id);
1126 if (src != null) {
1127 dest.setIcon(src.getIcon());
1128 dest.setTitle(src.getTitle());
1129 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001130 }
1131
1132 @Override
1133 public boolean onContextItemSelected(MenuItem item) {
1134 // chording is not an issue with context menus, but we use the same
1135 // options selector, so set mCanChord to true so we can access them.
1136 mCanChord = true;
1137 int id = item.getItemId();
Leon Scroggins96afcb12009-12-10 12:35:56 -05001138 boolean result = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001139 switch (id) {
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001140 // For the context menu from the title bar
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001141 case R.id.title_bar_copy_page_url:
Leon Scroggins96afcb12009-12-10 12:35:56 -05001142 Tab currentTab = mTabControl.getCurrentTab();
1143 if (null == currentTab) {
1144 result = false;
1145 break;
1146 }
1147 WebView mainView = currentTab.getWebView();
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001148 if (null == mainView) {
Leon Scroggins96afcb12009-12-10 12:35:56 -05001149 result = false;
1150 break;
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001151 }
Leon Scroggins96afcb12009-12-10 12:35:56 -05001152 copy(mainView.getUrl());
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001153 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001154 // -- Browser context menu
1155 case R.id.open_context_menu_id:
The Android Open Source Project0c908882009-03-03 19:32:16 -08001156 case R.id.bookmark_context_menu_id:
1157 case R.id.save_link_context_menu_id:
1158 case R.id.share_link_context_menu_id:
1159 case R.id.copy_link_context_menu_id:
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001160 final WebView webView = getTopWindow();
1161 if (null == webView) {
Leon Scroggins96afcb12009-12-10 12:35:56 -05001162 result = false;
1163 break;
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001164 }
1165 final HashMap hrefMap = new HashMap();
1166 hrefMap.put("webview", webView);
1167 final Message msg = mHandler.obtainMessage(
1168 FOCUS_NODE_HREF, id, 0, hrefMap);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001169 webView.requestFocusNodeHref(msg);
1170 break;
1171
1172 default:
1173 // For other context menus
Leon Scroggins96afcb12009-12-10 12:35:56 -05001174 result = onOptionsItemSelected(item);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001175 }
1176 mCanChord = false;
Leon Scroggins96afcb12009-12-10 12:35:56 -05001177 return result;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001178 }
1179
1180 private Bundle createGoogleSearchSourceBundle(String source) {
1181 Bundle bundle = new Bundle();
Bjorn Bringert10d1cca2010-02-10 14:22:12 +00001182 bundle.putString(Search.SOURCE, source);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001183 return bundle;
1184 }
1185
Leon Scroggins8ad29922010-02-16 12:33:55 -05001186 /* package */ void editUrl() {
Leon Scroggins68579392009-09-15 15:31:54 -04001187 if (mOptionsMenuOpen) closeOptionsMenu();
Leon Scroggins5bbe9802009-07-31 13:10:55 -04001188 String url = (getTopWindow() == null) ? null : getTopWindow().getUrl();
Grace Kloba83f47342009-07-20 10:44:31 -07001189 startSearch(mSettings.getHomePage().equals(url) ? null : url, true,
Leon Scroggins8ad29922010-02-16 12:33:55 -05001190 null, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001191 }
1192
Leon Scroggins8ad29922010-02-16 12:33:55 -05001193 /**
1194 * Overriding this to insert a local information bundle
1195 */
The Android Open Source Project0c908882009-03-03 19:32:16 -08001196 @Override
1197 public void startSearch(String initialQuery, boolean selectInitialQuery,
1198 Bundle appSearchData, boolean globalSearch) {
1199 if (appSearchData == null) {
1200 appSearchData = createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_TYPE);
1201 }
1202 super.startSearch(initialQuery, selectInitialQuery, appSearchData, globalSearch);
1203 }
1204
Leon Scroggins1f005d32009-08-10 17:36:42 -04001205 /**
1206 * Switch tabs. Called by the TitleBarSet when sliding the title bar
1207 * results in changing tabs.
Leon Scroggins160a7e72009-08-14 18:28:01 -04001208 * @param index Index of the tab to change to, as defined by
1209 * mTabControl.getTabIndex(Tab t).
1210 * @return boolean True if we successfully switched to a different tab. If
1211 * the indexth tab is null, or if that tab is the same as
1212 * the current one, return false.
Leon Scroggins1f005d32009-08-10 17:36:42 -04001213 */
Leon Scroggins160a7e72009-08-14 18:28:01 -04001214 /* package */ boolean switchToTab(int index) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001215 Tab tab = mTabControl.getTab(index);
1216 Tab currentTab = mTabControl.getCurrentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04001217 if (tab == null || tab == currentTab) {
Leon Scroggins160a7e72009-08-14 18:28:01 -04001218 return false;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001219 }
1220 if (currentTab != null) {
1221 // currentTab may be null if it was just removed. In that case,
1222 // we do not need to remove it
1223 removeTabFromContentView(currentTab);
1224 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001225 mTabControl.setCurrentTab(tab);
1226 attachTabToContentView(tab);
Grace Klobaeb6eef42009-09-15 17:56:32 -07001227 resetTitleIconAndProgress();
1228 updateLockIconToLatest();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001229 return true;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001230 }
1231
Grace Kloba22ac16e2009-10-07 18:00:23 -07001232 /* package */ Tab openTabToHomePage() {
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001233 return openTabAndShow(mSettings.getHomePage(), false, null);
1234 }
1235
Leon Scroggins1f005d32009-08-10 17:36:42 -04001236 /* package */ void closeCurrentWindow() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001237 final Tab current = mTabControl.getCurrentTab();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001238 if (mTabControl.getTabCount() == 1) {
Leon Scroggins30444232009-09-04 18:36:20 -04001239 // This is the last tab. Open a new one, with the home
1240 // page and close the current one.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001241 openTabToHomePage();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001242 closeTab(current);
Leon Scroggins160a7e72009-08-14 18:28:01 -04001243 return;
1244 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07001245 final Tab parent = current.getParentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04001246 int indexToShow = -1;
1247 if (parent != null) {
1248 indexToShow = mTabControl.getTabIndex(parent);
1249 } else {
Leon Scroggins160a7e72009-08-14 18:28:01 -04001250 final int currentIndex = mTabControl.getCurrentIndex();
1251 // Try to move to the tab to the right
1252 indexToShow = currentIndex + 1;
1253 if (indexToShow > mTabControl.getTabCount() - 1) {
1254 // Try to move to the tab to the left
1255 indexToShow = currentIndex - 1;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001256 }
1257 }
Leon Scroggins160a7e72009-08-14 18:28:01 -04001258 if (switchToTab(indexToShow)) {
1259 // Close window
1260 closeTab(current);
1261 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001262 }
1263
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001264 private ActiveTabsPage mActiveTabsPage;
1265
1266 /**
1267 * Remove the active tabs page.
1268 * @param needToAttach If true, the active tabs page did not attach a tab
1269 * to the content view, so we need to do that here.
1270 */
1271 /* package */ void removeActiveTabPage(boolean needToAttach) {
1272 mContentView.removeView(mActiveTabsPage);
Leon Scrogginsd746a942010-05-19 13:21:44 -04001273 mTitleBar.setVisibility(View.VISIBLE);
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001274 mActiveTabsPage = null;
1275 mMenuState = R.id.MAIN_MENU;
1276 if (needToAttach) {
1277 attachTabToContentView(mTabControl.getCurrentTab());
1278 }
1279 getTopWindow().requestFocus();
1280 }
1281
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04001282 @Override
1283 public ActionMode onStartActionMode(ActionMode.Callback callback) {
Leon Scroggins4fc12cb2010-08-24 14:24:05 -04001284 mActionMode = super.onStartActionMode(callback);
1285 hideFakeTitleBar();
1286 // Would like to change the MENU, but onEndActionMode may not be called
1287 return mActionMode;
Cary Clark01cfcdd2010-06-04 16:36:45 -04001288 }
1289
The Android Open Source Project0c908882009-03-03 19:32:16 -08001290 @Override
1291 public boolean onOptionsItemSelected(MenuItem item) {
Michael Kolbed217742010-08-10 17:52:34 -07001292 // check the action bar button before mCanChord check, as the prepare call
1293 // doesn't come for action bar buttons
1294 if (item.getItemId() == R.id.newtab) {
Michael Kolb300b7f02010-08-25 13:47:24 -07001295 openTabToHomePage();
1296 mHandler.sendMessage(mHandler.obtainMessage(OPEN_BOOKMARKS));
Michael Kolbed217742010-08-10 17:52:34 -07001297 return true;
1298 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001299 if (!mCanChord) {
1300 // The user has already fired a shortcut with this hold down of the
1301 // menu key.
1302 return false;
1303 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001304 if (null == getTopWindow()) {
Leon Scroggins0d7ae0e2009-06-05 11:04:45 -04001305 return false;
1306 }
Grace Kloba6ee9c492009-07-13 10:04:34 -07001307 if (mMenuIsDown) {
1308 // The shortcut action consumes the MENU. Even if it is still down,
1309 // it won't trigger the next shortcut action. In the case of the
1310 // shortcut action triggering a new activity, like Bookmarks, we
1311 // won't get onKeyUp for MENU. So it is important to reset it here.
1312 mMenuIsDown = false;
1313 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001314 switch (item.getItemId()) {
1315 // -- Main menu
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001316 case R.id.new_tab_menu_id:
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001317 openTabToHomePage();
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001318 break;
1319
Michael Kolbae62fd42010-08-18 16:33:28 -07001320 case R.id.incognito_menu_id:
1321 openIncognitoTab();
1322 break;
1323
Leon Scroggins64b80f32009-08-07 12:03:34 -04001324 case R.id.goto_menu_id:
Leon Scroggins8ad29922010-02-16 12:33:55 -05001325 editUrl();
Leon Scrogginsb3a5bed2009-09-28 11:21:56 -04001326 break;
1327
1328 case R.id.bookmarks_menu_id:
Michael Kolb68792c82010-08-09 16:39:18 -07001329 bookmarksOrHistoryPicker(false, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001330 break;
1331
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001332 case R.id.active_tabs_menu_id:
1333 mActiveTabsPage = new ActiveTabsPage(this, mTabControl);
1334 removeTabFromContentView(mTabControl.getCurrentTab());
Leon Scrogginsd746a942010-05-19 13:21:44 -04001335 mTitleBar.setVisibility(View.GONE);
Leon Scroggins43de6162009-09-14 19:59:58 -04001336 hideFakeTitleBar();
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001337 mContentView.addView(mActiveTabsPage, COVER_SCREEN_PARAMS);
1338 mActiveTabsPage.requestFocus();
1339 mMenuState = EMPTY_MENU;
1340 break;
1341
Leon Scroggins1f005d32009-08-10 17:36:42 -04001342 case R.id.add_bookmark_menu_id:
Leon Scroggins571b3762010-05-26 10:25:01 -04001343 bookmarkCurrentPage();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001344 break;
1345
1346 case R.id.stop_reload_menu_id:
1347 if (mInLoad) {
1348 stopLoading();
1349 } else {
1350 getTopWindow().reload();
1351 }
1352 break;
1353
1354 case R.id.back_menu_id:
1355 getTopWindow().goBack();
1356 break;
1357
1358 case R.id.forward_menu_id:
1359 getTopWindow().goForward();
1360 break;
1361
1362 case R.id.close_menu_id:
1363 // Close the subwindow if it exists.
1364 if (mTabControl.getCurrentSubWindow() != null) {
1365 dismissSubWindow(mTabControl.getCurrentTab());
1366 break;
1367 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001368 closeCurrentWindow();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001369 break;
1370
1371 case R.id.homepage_menu_id:
Grace Kloba22ac16e2009-10-07 18:00:23 -07001372 Tab current = mTabControl.getCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001373 if (current != null) {
1374 dismissSubWindow(current);
Leon Scroggins92472e82010-02-17 16:32:28 -05001375 loadUrl(current.getWebView(), mSettings.getHomePage());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001376 }
1377 break;
1378
1379 case R.id.preferences_menu_id:
1380 Intent intent = new Intent(this,
1381 BrowserPreferencesPage.class);
Leon Scrogginsd5304942009-12-10 16:11:39 -05001382 intent.putExtra(BrowserPreferencesPage.CURRENT_PAGE,
1383 getTopWindow().getUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001384 startActivityForResult(intent, PREFERENCES_PAGE);
1385 break;
1386
1387 case R.id.find_menu_id:
Leon Scroggins4fc12cb2010-08-24 14:24:05 -04001388 getTopWindow().showFindDialog(null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001389 break;
1390
Elliott Slaughter0ced08c2010-06-30 11:40:42 -07001391 case R.id.save_webarchive_menu_id:
1392 if (LOGD_ENABLED) {
1393 Log.d(LOGTAG, "Save as Web Archive");
1394 }
1395 String directory = getExternalFilesDir(null).getAbsolutePath() + File.separator;
1396 getTopWindow().saveWebArchive(directory, true, new ValueCallback<String>() {
1397 @Override
1398 public void onReceiveValue(String value) {
1399 if (value != null) {
1400 Toast.makeText(BrowserActivity.this, R.string.webarchive_saved, Toast.LENGTH_SHORT).show();
1401 } else {
1402 Toast.makeText(BrowserActivity.this, R.string.webarchive_failed, Toast.LENGTH_SHORT).show();
1403 }
1404 }
1405 });
1406 break;
1407
The Android Open Source Project0c908882009-03-03 19:32:16 -08001408 case R.id.page_info_menu_id:
1409 showPageInfo(mTabControl.getCurrentTab(), false);
1410 break;
1411
1412 case R.id.classic_history_menu_id:
Michael Kolb68792c82010-08-09 16:39:18 -07001413 bookmarksOrHistoryPicker(true, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001414 break;
1415
Leon Scroggins96afcb12009-12-10 12:35:56 -05001416 case R.id.title_bar_share_page_url:
The Android Open Source Project0c908882009-03-03 19:32:16 -08001417 case R.id.share_page_menu_id:
Leon Scroggins96afcb12009-12-10 12:35:56 -05001418 Tab currentTab = mTabControl.getCurrentTab();
1419 if (null == currentTab) {
1420 mCanChord = false;
1421 return false;
1422 }
1423 currentTab.populatePickerData();
1424 sharePage(this, currentTab.getTitle(),
1425 currentTab.getUrl(), currentTab.getFavicon(),
Ben Murdoch87cc65d2010-06-29 20:34:10 +01001426 createScreenshot(currentTab.getWebView(), getDesiredThumbnailWidth(this),
1427 getDesiredThumbnailHeight(this)));
The Android Open Source Project0c908882009-03-03 19:32:16 -08001428 break;
1429
1430 case R.id.dump_nav_menu_id:
1431 getTopWindow().debugDump();
1432 break;
1433
Andrei Popescu7a8b88b2010-02-02 00:30:38 +00001434 case R.id.dump_counters_menu_id:
1435 getTopWindow().dumpV8Counters();
1436 break;
1437
The Android Open Source Project0c908882009-03-03 19:32:16 -08001438 case R.id.zoom_in_menu_id:
1439 getTopWindow().zoomIn();
1440 break;
1441
1442 case R.id.zoom_out_menu_id:
1443 getTopWindow().zoomOut();
1444 break;
1445
1446 case R.id.view_downloads_menu_id:
1447 viewDownloads(null);
1448 break;
1449
The Android Open Source Project0c908882009-03-03 19:32:16 -08001450 case R.id.window_one_menu_id:
1451 case R.id.window_two_menu_id:
1452 case R.id.window_three_menu_id:
1453 case R.id.window_four_menu_id:
1454 case R.id.window_five_menu_id:
1455 case R.id.window_six_menu_id:
1456 case R.id.window_seven_menu_id:
1457 case R.id.window_eight_menu_id:
1458 {
1459 int menuid = item.getItemId();
1460 for (int id = 0; id < WINDOW_SHORTCUT_ID_ARRAY.length; id++) {
1461 if (WINDOW_SHORTCUT_ID_ARRAY[id] == menuid) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001462 Tab desiredTab = mTabControl.getTab(id);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001463 if (desiredTab != null &&
1464 desiredTab != mTabControl.getCurrentTab()) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001465 switchToTab(id);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001466 }
1467 break;
1468 }
1469 }
1470 }
1471 break;
1472
1473 default:
1474 if (!super.onOptionsItemSelected(item)) {
1475 return false;
1476 }
1477 // Otherwise fall through.
1478 }
1479 mCanChord = false;
1480 return true;
1481 }
1482
Leon Scroggins571b3762010-05-26 10:25:01 -04001483 /* package */ void bookmarkCurrentPage() {
1484 Intent i = new Intent(BrowserActivity.this,
1485 AddBookmarkPage.class);
1486 WebView w = getTopWindow();
1487 i.putExtra("url", w.getUrl());
1488 i.putExtra("title", w.getTitle());
1489 i.putExtra("touch_icon_url", w.getTouchIconUrl());
Ben Murdoch87cc65d2010-06-29 20:34:10 +01001490 i.putExtra("thumbnail", createScreenshot(w, getDesiredThumbnailWidth(this),
1491 getDesiredThumbnailHeight(this)));
Ben Murdocheecb4e62010-07-06 16:30:38 +01001492 i.putExtra("url_editable", false);
Leon Scroggins571b3762010-05-26 10:25:01 -04001493 startActivity(i);
1494 }
1495
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04001496 /*
1497 * True if a custom ActionMode (i.e. find or select) is in use.
1498 */
1499 private boolean isInCustomActionMode() {
1500 return mActionMode != null;
Cary Clark01cfcdd2010-06-04 16:36:45 -04001501 }
1502
1503 /*
Leon Scroggins4fc12cb2010-08-24 14:24:05 -04001504 * End the current ActionMode.
Cary Clark01cfcdd2010-06-04 16:36:45 -04001505 */
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04001506 void endActionMode() {
1507 if (mActionMode != null) {
Leon Scroggins4fc12cb2010-08-24 14:24:05 -04001508 ActionMode mode = mActionMode;
1509 onEndActionMode();
1510 mode.finish();
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04001511 }
1512 }
1513
1514 /*
1515 * Called by find and select when they are finished. Replace title bars
1516 * as necessary.
1517 */
1518 public void onEndActionMode() {
1519 if (!isInCustomActionMode()) return;
Leon Scroggins79e36d92010-04-29 16:01:46 +01001520 if (mInLoad) {
1521 // The title bar was hidden, because otherwise it would cover up the
Michael Kolba2b2ba82010-08-04 17:54:03 -07001522 // find or select dialog. Now that the dialog has been removed,
Cary Clark01cfcdd2010-06-04 16:36:45 -04001523 // show the fake title bar once again.
Leon Scroggins79e36d92010-04-29 16:01:46 +01001524 showFakeTitleBar();
1525 }
Leon Scroggins4fc12cb2010-08-24 14:24:05 -04001526 // Would like to return the menu state to normal, but this does not
1527 // necessarily get called.
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04001528 mActionMode = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001529 }
1530
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04001531 // For select and find, we keep track of the ActionMode so that
1532 // finish() can be called as desired.
1533 private ActionMode mActionMode;
1534
Grace Kloba22ac16e2009-10-07 18:00:23 -07001535 @Override
1536 public boolean onPrepareOptionsMenu(Menu menu) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001537 // This happens when the user begins to hold down the menu key, so
1538 // allow them to chord to get a shortcut.
1539 mCanChord = true;
1540 // Note: setVisible will decide whether an item is visible; while
1541 // setEnabled() will decide whether an item is enabled, which also means
1542 // whether the matching shortcut key will function.
1543 super.onPrepareOptionsMenu(menu);
1544 switch (mMenuState) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001545 case EMPTY_MENU:
1546 if (mCurrentMenuState != mMenuState) {
1547 menu.setGroupVisible(R.id.MAIN_MENU, false);
1548 menu.setGroupEnabled(R.id.MAIN_MENU, false);
1549 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001550 }
1551 break;
1552 default:
1553 if (mCurrentMenuState != mMenuState) {
1554 menu.setGroupVisible(R.id.MAIN_MENU, true);
1555 menu.setGroupEnabled(R.id.MAIN_MENU, true);
1556 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001557 }
1558 final WebView w = getTopWindow();
1559 boolean canGoBack = false;
1560 boolean canGoForward = false;
1561 boolean isHome = false;
1562 if (w != null) {
1563 canGoBack = w.canGoBack();
1564 canGoForward = w.canGoForward();
1565 isHome = mSettings.getHomePage().equals(w.getUrl());
1566 }
1567 final MenuItem back = menu.findItem(R.id.back_menu_id);
1568 back.setEnabled(canGoBack);
1569
1570 final MenuItem home = menu.findItem(R.id.homepage_menu_id);
1571 home.setEnabled(!isHome);
1572
Michael Kolbe0a36662010-06-29 10:37:12 -07001573 final MenuItem forward = menu.findItem(R.id.forward_menu_id);
1574 forward.setEnabled(canGoForward);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001575
Michael Kolbed217742010-08-10 17:52:34 -07001576 if (!mXLargeScreenSize) {
1577 final MenuItem newtab = menu.findItem(R.id.new_tab_menu_id);
1578 newtab.setEnabled(mTabControl.canCreateNewTab());
1579 }
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001580
The Android Open Source Project0c908882009-03-03 19:32:16 -08001581 // decide whether to show the share link option
1582 PackageManager pm = getPackageManager();
1583 Intent send = new Intent(Intent.ACTION_SEND);
1584 send.setType("text/plain");
1585 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1586 menu.findItem(R.id.share_page_menu_id).setVisible(ri != null);
1587
The Android Open Source Project0c908882009-03-03 19:32:16 -08001588 boolean isNavDump = mSettings.isNavDump();
1589 final MenuItem nav = menu.findItem(R.id.dump_nav_menu_id);
1590 nav.setVisible(isNavDump);
1591 nav.setEnabled(isNavDump);
Andrei Popescu7a8b88b2010-02-02 00:30:38 +00001592
1593 boolean showDebugSettings = mSettings.showDebugSettings();
1594 final MenuItem counter = menu.findItem(R.id.dump_counters_menu_id);
1595 counter.setVisible(showDebugSettings);
1596 counter.setEnabled(showDebugSettings);
1597
The Android Open Source Project0c908882009-03-03 19:32:16 -08001598 break;
1599 }
1600 mCurrentMenuState = mMenuState;
1601 return true;
1602 }
1603
1604 @Override
1605 public void onCreateContextMenu(ContextMenu menu, View v,
1606 ContextMenuInfo menuInfo) {
Leon Scroggins571b3762010-05-26 10:25:01 -04001607 if (v instanceof TitleBarBase) {
Leon Scroggins4e9f89b2010-02-22 16:54:14 -05001608 return;
1609 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001610 WebView webview = (WebView) v;
1611 WebView.HitTestResult result = webview.getHitTestResult();
1612 if (result == null) {
1613 return;
1614 }
1615
1616 int type = result.getType();
1617 if (type == WebView.HitTestResult.UNKNOWN_TYPE) {
1618 Log.w(LOGTAG,
1619 "We should not show context menu when nothing is touched");
1620 return;
1621 }
1622 if (type == WebView.HitTestResult.EDIT_TEXT_TYPE) {
1623 // let TextView handles context menu
1624 return;
1625 }
1626
1627 // Note, http://b/issue?id=1106666 is requesting that
1628 // an inflated menu can be used again. This is not available
1629 // yet, so inflate each time (yuk!)
1630 MenuInflater inflater = getMenuInflater();
1631 inflater.inflate(R.menu.browsercontext, menu);
1632
1633 // Show the correct menu group
Leon Scroggins III9e997c72010-05-26 13:25:16 -04001634 final String extra = result.getExtra();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001635 menu.setGroupVisible(R.id.PHONE_MENU,
1636 type == WebView.HitTestResult.PHONE_TYPE);
1637 menu.setGroupVisible(R.id.EMAIL_MENU,
1638 type == WebView.HitTestResult.EMAIL_TYPE);
1639 menu.setGroupVisible(R.id.GEO_MENU,
1640 type == WebView.HitTestResult.GEO_TYPE);
1641 menu.setGroupVisible(R.id.IMAGE_MENU,
1642 type == WebView.HitTestResult.IMAGE_TYPE
1643 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1644 menu.setGroupVisible(R.id.ANCHOR_MENU,
1645 type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1646 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1647
1648 // Setup custom handling depending on the type
1649 switch (type) {
1650 case WebView.HitTestResult.PHONE_TYPE:
1651 menu.setHeaderTitle(Uri.decode(extra));
1652 menu.findItem(R.id.dial_context_menu_id).setIntent(
1653 new Intent(Intent.ACTION_VIEW, Uri
1654 .parse(WebView.SCHEME_TEL + extra)));
1655 Intent addIntent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
1656 addIntent.putExtra(Insert.PHONE, Uri.decode(extra));
Cary Clark5e335a32009-09-22 14:53:11 -04001657 addIntent.setType(ContactsContract.Contacts.CONTENT_ITEM_TYPE);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001658 menu.findItem(R.id.add_contact_context_menu_id).setIntent(
1659 addIntent);
1660 menu.findItem(R.id.copy_phone_context_menu_id).setOnMenuItemClickListener(
1661 new Copy(extra));
1662 break;
1663
1664 case WebView.HitTestResult.EMAIL_TYPE:
1665 menu.setHeaderTitle(extra);
1666 menu.findItem(R.id.email_context_menu_id).setIntent(
1667 new Intent(Intent.ACTION_VIEW, Uri
1668 .parse(WebView.SCHEME_MAILTO + extra)));
1669 menu.findItem(R.id.copy_mail_context_menu_id).setOnMenuItemClickListener(
1670 new Copy(extra));
1671 break;
1672
1673 case WebView.HitTestResult.GEO_TYPE:
1674 menu.setHeaderTitle(extra);
1675 menu.findItem(R.id.map_context_menu_id).setIntent(
1676 new Intent(Intent.ACTION_VIEW, Uri
1677 .parse(WebView.SCHEME_GEO
1678 + URLEncoder.encode(extra))));
1679 menu.findItem(R.id.copy_geo_context_menu_id).setOnMenuItemClickListener(
1680 new Copy(extra));
1681 break;
1682
1683 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1684 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
1685 TextView titleView = (TextView) LayoutInflater.from(this)
1686 .inflate(android.R.layout.browser_link_context_header,
1687 null);
1688 titleView.setText(extra);
1689 menu.setHeaderView(titleView);
1690 // decide whether to show the open link in new tab option
Leon Scroggins III9e997c72010-05-26 13:25:16 -04001691 boolean showNewTab = mTabControl.canCreateNewTab();
1692 MenuItem newTabItem
1693 = menu.findItem(R.id.open_newtab_context_menu_id);
1694 newTabItem.setVisible(showNewTab);
1695 if (showNewTab) {
1696 newTabItem.setOnMenuItemClickListener(
1697 new MenuItem.OnMenuItemClickListener() {
1698 public boolean onMenuItemClick(MenuItem item) {
1699 final Tab parent = mTabControl.getCurrentTab();
Michael Kolb68792c82010-08-09 16:39:18 -07001700 final Tab newTab = openTab(extra, false);
Leon Scroggins III9e997c72010-05-26 13:25:16 -04001701 if (newTab != parent) {
1702 parent.addChildTab(newTab);
1703 }
1704 return true;
1705 }
1706 });
1707 }
Ben Murdochde353622009-10-12 10:29:00 +01001708 menu.findItem(R.id.bookmark_context_menu_id).setVisible(
1709 Bookmarks.urlHasAcceptableScheme(extra));
The Android Open Source Project0c908882009-03-03 19:32:16 -08001710 PackageManager pm = getPackageManager();
1711 Intent send = new Intent(Intent.ACTION_SEND);
1712 send.setType("text/plain");
1713 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1714 menu.findItem(R.id.share_link_context_menu_id).setVisible(ri != null);
1715 if (type == WebView.HitTestResult.SRC_ANCHOR_TYPE) {
1716 break;
1717 }
1718 // otherwise fall through to handle image part
1719 case WebView.HitTestResult.IMAGE_TYPE:
1720 if (type == WebView.HitTestResult.IMAGE_TYPE) {
1721 menu.setHeaderTitle(extra);
1722 }
1723 menu.findItem(R.id.view_image_context_menu_id).setIntent(
1724 new Intent(Intent.ACTION_VIEW, Uri.parse(extra)));
1725 menu.findItem(R.id.download_context_menu_id).
1726 setOnMenuItemClickListener(new Download(extra));
Ben Murdoch4f75ba22009-10-27 11:48:28 +00001727 menu.findItem(R.id.set_wallpaper_context_menu_id).
1728 setOnMenuItemClickListener(new SetAsWallpaper(extra));
The Android Open Source Project0c908882009-03-03 19:32:16 -08001729 break;
1730
1731 default:
1732 Log.w(LOGTAG, "We should not get here.");
1733 break;
1734 }
Leon Scrogginsb2b19f52009-10-09 16:10:00 -04001735 hideFakeTitleBar();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001736 }
1737
The Android Open Source Project0c908882009-03-03 19:32:16 -08001738 // Attach the given tab to the content view.
Grace Klobac928c302009-09-17 11:51:21 -07001739 // this should only be called for the current tab.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001740 private void attachTabToContentView(Tab t) {
Steve Block2bc69912009-07-30 14:45:13 +01001741 // Attach the container that contains the main WebView and any other UI
1742 // associated with the tab.
Patrick Scottd0119532009-09-17 08:00:31 -04001743 t.attachTabToContentView(mContentView);
Ben Murdochbff2d602009-07-01 20:19:05 +01001744
1745 if (mShouldShowErrorConsole) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001746 ErrorConsoleView errorConsole = t.getErrorConsole(true);
Ben Murdochbff2d602009-07-01 20:19:05 +01001747 if (errorConsole.numberOfErrors() == 0) {
1748 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
1749 } else {
1750 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
1751 }
1752
1753 mErrorConsoleContainer.addView(errorConsole,
Romain Guy15b8ec62010-01-08 15:06:43 -08001754 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
Ben Murdochbff2d602009-07-01 20:19:05 +01001755 ViewGroup.LayoutParams.WRAP_CONTENT));
1756 }
1757
Michael Kolba2b2ba82010-08-04 17:54:03 -07001758 WebView view = t.getWebView();
1759 view.setEmbeddedTitleBar(mTitleBar);
Leon Scroggins58d56c62010-01-28 15:12:40 -05001760 if (t.isInVoiceSearchMode()) {
1761 showVoiceTitleBar(t.getVoiceDisplayTitle());
1762 } else {
1763 revertVoiceTitleBar();
1764 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001765 // Request focus on the top window.
1766 t.getTopWindow().requestFocus();
Michael Kolba2b2ba82010-08-04 17:54:03 -07001767 if (mTabControl.getTabChangeListener() != null) {
1768 mTabControl.getTabChangeListener().onCurrentTab(t);
1769 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001770 }
1771
1772 // Attach a sub window to the main WebView of the given tab.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001773 void attachSubWindow(Tab t) {
Patrick Scottd0119532009-09-17 08:00:31 -04001774 t.attachSubWindow(mContentView);
1775 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001776 }
1777
1778 // Remove the given tab from the content view.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001779 private void removeTabFromContentView(Tab t) {
Steve Block2bc69912009-07-30 14:45:13 +01001780 // Remove the container that contains the main WebView.
Patrick Scottd0119532009-09-17 08:00:31 -04001781 t.removeTabFromContentView(mContentView);
Ben Murdochbff2d602009-07-01 20:19:05 +01001782
Grace Kloba22ac16e2009-10-07 18:00:23 -07001783 ErrorConsoleView errorConsole = t.getErrorConsole(false);
1784 if (errorConsole != null) {
1785 mErrorConsoleContainer.removeView(errorConsole);
Ben Murdochbff2d602009-07-01 20:19:05 +01001786 }
1787
Michael Kolba2b2ba82010-08-04 17:54:03 -07001788 WebView view = t.getWebView();
1789 if (view != null) {
1790 view.setEmbeddedTitleBar(null);
Leon Scrogginsbb85b902009-09-14 19:27:20 -04001791 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001792 }
1793
1794 // Remove the sub window if it exists. Also called by TabControl when the
1795 // user clicks the 'X' to dismiss a sub window.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001796 /* package */ void dismissSubWindow(Tab t) {
Patrick Scottd0119532009-09-17 08:00:31 -04001797 t.removeSubWindow(mContentView);
Grace Kloba22ac16e2009-10-07 18:00:23 -07001798 // dismiss the subwindow. This will destroy the WebView.
1799 t.dismissSubWindow();
Patrick Scottd0119532009-09-17 08:00:31 -04001800 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001801 }
1802
Leon Scroggins1f005d32009-08-10 17:36:42 -04001803 // A wrapper function of {@link #openTabAndShow(UrlData, boolean, String)}
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07001804 // that accepts url as string.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001805 private Tab openTabAndShow(String url, boolean closeOnExit, String appId) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001806 return openTabAndShow(new UrlData(url), closeOnExit, appId);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001807 }
1808
1809 // This method does a ton of stuff. It will attempt to create a new tab
1810 // if we haven't reached MAX_TABS. Otherwise it uses the current tab. If
Leon Scroggins1f005d32009-08-10 17:36:42 -04001811 // url isn't null, it will load the given url.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001812 /* package */Tab openTabAndShow(UrlData urlData, boolean closeOnExit,
1813 String appId) {
1814 final Tab currentTab = mTabControl.getCurrentTab();
1815 if (mTabControl.canCreateNewTab()) {
1816 final Tab tab = mTabControl.createNewTab(closeOnExit, appId,
Elliott Slaughterf0f03952010-07-14 18:10:36 -07001817 urlData.mUrl, false);
Leon Scroggins1f005d32009-08-10 17:36:42 -04001818 WebView webview = tab.getWebView();
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001819 // If the last tab was removed from the active tabs page, currentTab
1820 // will be null.
1821 if (currentTab != null) {
1822 removeTabFromContentView(currentTab);
1823 }
Patrick Scott8bbd69f2009-08-14 13:35:53 -04001824 // We must set the new tab as the current tab to reflect the old
1825 // animation behavior.
1826 mTabControl.setCurrentTab(tab);
Grace Klobaeb6eef42009-09-15 17:56:32 -07001827 attachTabToContentView(tab);
Leon Scroggins160a7e72009-08-14 18:28:01 -04001828 if (!urlData.isEmpty()) {
Patrick Scott9d53da02010-02-19 10:19:01 -05001829 loadUrlDataIn(tab, urlData);
Leon Scroggins1f005d32009-08-10 17:36:42 -04001830 }
1831 return tab;
1832 } else {
1833 // Get rid of the subwindow if it exists
1834 dismissSubWindow(currentTab);
1835 if (!urlData.isEmpty()) {
1836 // Load the given url.
Patrick Scott9d53da02010-02-19 10:19:01 -05001837 loadUrlDataIn(currentTab, urlData);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001838 }
Leon Scroggins58d56c62010-01-28 15:12:40 -05001839 return currentTab;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001840 }
1841 }
1842
Michael Kolb68792c82010-08-09 16:39:18 -07001843 private Tab openTab(String url, boolean forceForeground) {
1844 if (mSettings.openInBackground() && !forceForeground) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001845 Tab t = mTabControl.createNewTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001846 if (t != null) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001847 WebView view = t.getWebView();
Leon Scroggins92472e82010-02-17 16:32:28 -05001848 loadUrl(view, url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001849 }
Grace Klobac9181842009-04-14 08:53:22 -07001850 return t;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001851 } else {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001852 return openTabAndShow(url, false, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001853 }
1854 }
1855
Elliott Slaughterf0f03952010-07-14 18:10:36 -07001856 /* package */ Tab openIncognitoTab() {
1857 if (mTabControl.canCreateNewTab()) {
1858 Tab currentTab = mTabControl.getCurrentTab();
1859 Tab tab = mTabControl.createNewTab(false, null, null, true);
1860 if (currentTab != null) {
1861 removeTabFromContentView(currentTab);
1862 }
1863 mTabControl.setCurrentTab(tab);
1864 attachTabToContentView(tab);
1865 return tab;
1866 }
1867 return null;
1868 }
1869
The Android Open Source Project0c908882009-03-03 19:32:16 -08001870 private class Copy implements OnMenuItemClickListener {
1871 private CharSequence mText;
1872
1873 public boolean onMenuItemClick(MenuItem item) {
1874 copy(mText);
1875 return true;
1876 }
1877
1878 public Copy(CharSequence toCopy) {
1879 mText = toCopy;
1880 }
1881 }
1882
1883 private class Download implements OnMenuItemClickListener {
1884 private String mText;
1885
1886 public boolean onMenuItemClick(MenuItem item) {
1887 onDownloadStartNoStream(mText, null, null, null, -1);
1888 return true;
1889 }
1890
1891 public Download(String toDownload) {
1892 mText = toDownload;
1893 }
1894 }
1895
Ben Murdoch4f75ba22009-10-27 11:48:28 +00001896 private class SetAsWallpaper extends Thread implements
1897 OnMenuItemClickListener, DialogInterface.OnCancelListener {
1898 private URL mUrl;
1899 private ProgressDialog mWallpaperProgress;
1900 private boolean mCanceled = false;
1901
1902 public SetAsWallpaper(String url) {
1903 try {
1904 mUrl = new URL(url);
1905 } catch (MalformedURLException e) {
1906 mUrl = null;
1907 }
1908 }
1909
1910 public void onCancel(DialogInterface dialog) {
1911 mCanceled = true;
1912 }
1913
1914 public boolean onMenuItemClick(MenuItem item) {
1915 if (mUrl != null) {
1916 // The user may have tried to set a image with a large file size as their
1917 // background so it may take a few moments to perform the operation. Display
1918 // a progress spinner while it is working.
1919 mWallpaperProgress = new ProgressDialog(BrowserActivity.this);
1920 mWallpaperProgress.setIndeterminate(true);
1921 mWallpaperProgress.setMessage(getText(R.string.progress_dialog_setting_wallpaper));
1922 mWallpaperProgress.setCancelable(true);
1923 mWallpaperProgress.setOnCancelListener(this);
1924 mWallpaperProgress.show();
1925 start();
1926 }
1927 return true;
1928 }
1929
Michael Kolbe0a36662010-06-29 10:37:12 -07001930 @Override
Ben Murdoch4f75ba22009-10-27 11:48:28 +00001931 public void run() {
1932 Drawable oldWallpaper = BrowserActivity.this.getWallpaper();
1933 try {
1934 // TODO: This will cause the resource to be downloaded again, when we
1935 // should in most cases be able to grab it from the cache. To fix this
1936 // we should query WebCore to see if we can access a cached version and
1937 // instead open an input stream on that. This pattern could also be used
1938 // in the download manager where the same problem exists.
1939 InputStream inputstream = mUrl.openStream();
1940 if (inputstream != null) {
1941 setWallpaper(inputstream);
1942 }
1943 } catch (IOException e) {
1944 Log.e(LOGTAG, "Unable to set new wallpaper");
1945 // Act as though the user canceled the operation so we try to
1946 // restore the old wallpaper.
1947 mCanceled = true;
1948 }
1949
1950 if (mCanceled) {
1951 // Restore the old wallpaper if the user cancelled whilst we were setting
1952 // the new wallpaper.
1953 int width = oldWallpaper.getIntrinsicWidth();
1954 int height = oldWallpaper.getIntrinsicHeight();
1955 Bitmap bm = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
1956 Canvas canvas = new Canvas(bm);
1957 oldWallpaper.setBounds(0, 0, width, height);
1958 oldWallpaper.draw(canvas);
1959 try {
1960 setWallpaper(bm);
1961 } catch (IOException e) {
1962 Log.e(LOGTAG, "Unable to restore old wallpaper.");
1963 }
1964 mCanceled = false;
1965 }
1966
1967 if (mWallpaperProgress.isShowing()) {
1968 mWallpaperProgress.dismiss();
1969 }
1970 }
1971 }
1972
The Android Open Source Project0c908882009-03-03 19:32:16 -08001973 private void copy(CharSequence text) {
Dianne Hackborn80f32622010-08-05 14:17:53 -07001974 ClipboardManager cm = (ClipboardManager)getSystemService(Context.CLIPBOARD_SERVICE);
1975 cm.setText(text);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001976 }
1977
1978 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08001979 * Resets the browser title-view to whatever it must be
1980 * (for example, if we had a loading error)
1981 * When we have a new page, we call resetTitle, when we
1982 * have to reset the titlebar to whatever it used to be
1983 * (for example, if the user chose to stop loading), we
1984 * call resetTitleAndRevertLockIcon.
1985 */
1986 /* package */ void resetTitleAndRevertLockIcon() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001987 mTabControl.getCurrentTab().revertLockIcon();
1988 updateLockIconToLatest();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001989 resetTitleIconAndProgress();
1990 }
1991
1992 /**
1993 * Reset the title, favicon, and progress.
1994 */
1995 private void resetTitleIconAndProgress() {
1996 WebView current = mTabControl.getCurrentWebView();
1997 if (current == null) {
1998 return;
1999 }
2000 resetTitleAndIcon(current);
2001 int progress = current.getProgress();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002002 current.getWebChromeClient().onProgressChanged(current, progress);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002003 }
2004
2005 // Reset the title and the icon based on the given item.
2006 private void resetTitleAndIcon(WebView view) {
2007 WebHistoryItem item = view.copyBackForwardList().getCurrentItem();
2008 if (item != null) {
Leon Scroggins68579392009-09-15 15:31:54 -04002009 setUrlTitle(item.getUrl(), item.getTitle());
The Android Open Source Project0c908882009-03-03 19:32:16 -08002010 setFavicon(item.getFavicon());
2011 } else {
Leon Scroggins68579392009-09-15 15:31:54 -04002012 setUrlTitle(null, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002013 setFavicon(null);
2014 }
2015 }
2016
2017 /**
2018 * Sets a title composed of the URL and the title string.
2019 * @param url The URL of the site being loaded.
2020 * @param title The title of the site being loaded.
2021 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07002022 void setUrlTitle(String url, String title) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002023 mUrl = url;
2024 mTitle = title;
2025
Leon Scroggins58d56c62010-01-28 15:12:40 -05002026 // If we are in voice search mode, the title has already been set.
2027 if (mTabControl.getCurrentTab().isInVoiceSearchMode()) return;
2028 mTitleBar.setDisplayTitle(url);
Michael Kolba2b2ba82010-08-04 17:54:03 -07002029 mFakeTitleBar.setDisplayTitle(url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002030 }
2031
2032 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08002033 * @param url The URL to build a title version of the URL from.
2034 * @return The title version of the URL or null if fails.
2035 * The title version of the URL can be either the URL hostname,
2036 * or the hostname with an "https://" prefix (for secure URLs),
2037 * or an empty string if, for example, the URL in question is a
2038 * file:// URL with no hostname.
2039 */
Leon Scroggins32e14a62009-06-11 10:26:34 -04002040 /* package */ static String buildTitleUrl(String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002041 String titleUrl = null;
2042
2043 if (url != null) {
2044 try {
2045 // parse the url string
2046 URL urlObj = new URL(url);
2047 if (urlObj != null) {
2048 titleUrl = "";
2049
2050 String protocol = urlObj.getProtocol();
2051 String host = urlObj.getHost();
2052
2053 if (host != null && 0 < host.length()) {
2054 titleUrl = host;
2055 if (protocol != null) {
2056 // if a secure site, add an "https://" prefix!
2057 if (protocol.equalsIgnoreCase("https")) {
2058 titleUrl = protocol + "://" + host;
2059 }
2060 }
2061 }
2062 }
2063 } catch (MalformedURLException e) {}
2064 }
2065
2066 return titleUrl;
2067 }
2068
2069 // Set the favicon in the title bar.
Grace Kloba22ac16e2009-10-07 18:00:23 -07002070 void setFavicon(Bitmap icon) {
Leon Scroggins68579392009-09-15 15:31:54 -04002071 mTitleBar.setFavicon(icon);
Michael Kolba2b2ba82010-08-04 17:54:03 -07002072 mFakeTitleBar.setFavicon(icon);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002073 }
2074
2075 /**
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002076 * Close the tab, remove its associated title bar, and adjust mTabControl's
2077 * current tab to a valid value.
Leon Scroggins1f005d32009-08-10 17:36:42 -04002078 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07002079 /* package */ void closeTab(Tab t) {
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002080 int currentIndex = mTabControl.getCurrentIndex();
2081 int removeIndex = mTabControl.getTabIndex(t);
Leon Scroggins1f005d32009-08-10 17:36:42 -04002082 mTabControl.removeTab(t);
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002083 if (currentIndex >= removeIndex && currentIndex != 0) {
2084 currentIndex--;
2085 }
2086 mTabControl.setCurrentTab(mTabControl.getTab(currentIndex));
Andrei Popescua5bf1de2009-09-23 16:39:23 +01002087 resetTitleIconAndProgress();
Leon Scroggins654899b2010-06-25 16:25:23 -04002088 updateLockIconToLatest();
Elliott Slaughtere440a882010-08-20 13:54:45 -07002089
2090 if (!mTabControl.hasAnyOpenIncognitoTabs()) {
2091 WebView.cleanupPrivateBrowsingFiles(this);
2092 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002093 }
2094
Leon Scrogginsdcc5eeb2010-02-23 17:26:37 -05002095 /* package */ void goBackOnePageOrQuit() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002096 Tab current = mTabControl.getCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002097 if (current == null) {
2098 /*
2099 * Instead of finishing the activity, simply push this to the back
2100 * of the stack and let ActivityManager to choose the foreground
2101 * activity. As BrowserActivity is singleTask, it will be always the
2102 * root of the task. So we can use either true or false for
2103 * moveTaskToBack().
2104 */
2105 moveTaskToBack(true);
Grace Kloba00d85e72009-09-23 18:50:05 -07002106 return;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002107 }
2108 WebView w = current.getWebView();
2109 if (w.canGoBack()) {
2110 w.goBack();
2111 } else {
2112 // Check to see if we are closing a window that was created by
2113 // another window. If so, we switch back to that window.
Grace Kloba22ac16e2009-10-07 18:00:23 -07002114 Tab parent = current.getParentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002115 if (parent != null) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04002116 switchToTab(mTabControl.getTabIndex(parent));
2117 // Now we close the other tab
2118 closeTab(current);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002119 } else {
2120 if (current.closeOnExit()) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002121 // force the tab's inLoad() to be false as we are going to
2122 // either finish the activity or remove the tab. This will
2123 // ensure pauseWebViewTimers() taking action.
2124 mTabControl.getCurrentTab().clearInLoad();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002125 if (mTabControl.getTabCount() == 1) {
2126 finish();
2127 return;
2128 }
Mike Reed7bfa63b2009-05-28 11:08:32 -04002129 // call pauseWebViewTimers() now, we won't be able to call
2130 // it in onPause() as the WebView won't be valid.
Grace Klobaec1b5ad2009-08-18 08:42:32 -07002131 // Temporarily change mActivityInPause to be true as
2132 // pauseWebViewTimers() will do nothing if mActivityInPause
2133 // is false.
Grace Kloba918e1d72009-08-13 14:55:06 -07002134 boolean savedState = mActivityInPause;
2135 if (savedState) {
Grace Klobaec1b5ad2009-08-18 08:42:32 -07002136 Log.e(LOGTAG, "BrowserActivity is already paused "
2137 + "while handing goBackOnePageOrQuit.");
Grace Kloba918e1d72009-08-13 14:55:06 -07002138 }
2139 mActivityInPause = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -04002140 pauseWebViewTimers();
Grace Kloba918e1d72009-08-13 14:55:06 -07002141 mActivityInPause = savedState;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002142 removeTabFromContentView(current);
2143 mTabControl.removeTab(current);
2144 }
2145 /*
2146 * Instead of finishing the activity, simply push this to the back
2147 * of the stack and let ActivityManager to choose the foreground
2148 * activity. As BrowserActivity is singleTask, it will be always the
2149 * root of the task. So we can use either true or false for
2150 * moveTaskToBack().
2151 */
2152 moveTaskToBack(true);
2153 }
2154 }
2155 }
2156
Grace Kloba22ac16e2009-10-07 18:00:23 -07002157 boolean isMenuDown() {
2158 return mMenuIsDown;
2159 }
2160
Grace Kloba5942df02009-09-18 11:48:29 -07002161 @Override
2162 public boolean onKeyDown(int keyCode, KeyEvent event) {
Leon Scrogginsf65b50d2009-12-08 10:44:28 -05002163 // Even if MENU is already held down, we need to call to super to open
2164 // the IME on long press.
2165 if (KeyEvent.KEYCODE_MENU == keyCode) {
2166 mMenuIsDown = true;
2167 return super.onKeyDown(keyCode, event);
2168 }
Grace Kloba5942df02009-09-18 11:48:29 -07002169 // The default key mode is DEFAULT_KEYS_SEARCH_LOCAL. As the MENU is
2170 // still down, we don't want to trigger the search. Pretend to consume
2171 // the key and do nothing.
2172 if (mMenuIsDown) return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002173
Grace Kloba5942df02009-09-18 11:48:29 -07002174 switch(keyCode) {
Grace Kloba5942df02009-09-18 11:48:29 -07002175 case KeyEvent.KEYCODE_SPACE:
Grace Klobada0fe552009-09-22 18:17:24 -07002176 // WebView/WebTextView handle the keys in the KeyDown. As
2177 // the Activity's shortcut keys are only handled when WebView
2178 // doesn't, have to do it in onKeyDown instead of onKeyUp.
2179 if (event.isShiftPressed()) {
2180 getTopWindow().pageUp(false);
2181 } else {
2182 getTopWindow().pageDown(false);
2183 }
Grace Kloba5942df02009-09-18 11:48:29 -07002184 return true;
2185 case KeyEvent.KEYCODE_BACK:
2186 if (event.getRepeatCount() == 0) {
2187 event.startTracking();
2188 return true;
2189 } else if (mCustomView == null && mActiveTabsPage == null
2190 && event.isLongPress()) {
Michael Kolb68792c82010-08-09 16:39:18 -07002191 bookmarksOrHistoryPicker(true, false);
Grace Kloba5942df02009-09-18 11:48:29 -07002192 return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002193 }
Grace Kloba5942df02009-09-18 11:48:29 -07002194 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002195 }
Grace Kloba5942df02009-09-18 11:48:29 -07002196 return super.onKeyDown(keyCode, event);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002197 }
2198
Grace Kloba5942df02009-09-18 11:48:29 -07002199 @Override
2200 public boolean onKeyUp(int keyCode, KeyEvent event) {
2201 switch(keyCode) {
2202 case KeyEvent.KEYCODE_MENU:
2203 mMenuIsDown = false;
2204 break;
Grace Kloba5942df02009-09-18 11:48:29 -07002205 case KeyEvent.KEYCODE_BACK:
2206 if (event.isTracking() && !event.isCanceled()) {
2207 if (mCustomView != null) {
2208 // if a custom view is showing, hide it
Grace Kloba22ac16e2009-10-07 18:00:23 -07002209 mTabControl.getCurrentWebView().getWebChromeClient()
2210 .onHideCustomView();
Grace Kloba5942df02009-09-18 11:48:29 -07002211 } else if (mActiveTabsPage != null) {
2212 // if tab page is showing, hide it
2213 removeActiveTabPage(true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002214 } else {
Grace Kloba5942df02009-09-18 11:48:29 -07002215 WebView subwindow = mTabControl.getCurrentSubWindow();
2216 if (subwindow != null) {
2217 if (subwindow.canGoBack()) {
2218 subwindow.goBack();
2219 } else {
2220 dismissSubWindow(mTabControl.getCurrentTab());
2221 }
2222 } else {
2223 goBackOnePageOrQuit();
2224 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002225 }
Grace Kloba5942df02009-09-18 11:48:29 -07002226 return true;
2227 }
2228 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002229 }
Grace Kloba5942df02009-09-18 11:48:29 -07002230 return super.onKeyUp(keyCode, event);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002231 }
2232
Leon Scroggins68579392009-09-15 15:31:54 -04002233 /* package */ void stopLoading() {
Ben Murdochb7cc8b42009-09-28 10:59:09 +01002234 mDidStopLoad = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002235 resetTitleAndRevertLockIcon();
2236 WebView w = getTopWindow();
2237 w.stopLoading();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002238 // FIXME: before refactor, it is using mWebViewClient. So I keep the
2239 // same logic here. But for subwindow case, should we call into the main
2240 // WebView's onPageFinished as we never call its onPageStarted and if
2241 // the page finishes itself, we don't call onPageFinished.
2242 mTabControl.getCurrentWebView().getWebViewClient().onPageFinished(w,
2243 w.getUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08002244
2245 cancelStopToast();
2246 mStopToast = Toast
2247 .makeText(this, R.string.stopping, Toast.LENGTH_SHORT);
2248 mStopToast.show();
2249 }
2250
Grace Kloba22ac16e2009-10-07 18:00:23 -07002251 boolean didUserStopLoading() {
2252 return mDidStopLoad;
2253 }
2254
The Android Open Source Project0c908882009-03-03 19:32:16 -08002255 private void cancelStopToast() {
2256 if (mStopToast != null) {
2257 mStopToast.cancel();
2258 mStopToast = null;
2259 }
2260 }
2261
Grace Kloba22ac16e2009-10-07 18:00:23 -07002262 // called by a UI or non-UI thread to post the message
2263 public void postMessage(int what, int arg1, int arg2, Object obj,
2264 long delayMillis) {
2265 mHandler.sendMessageDelayed(mHandler.obtainMessage(what, arg1, arg2,
2266 obj), delayMillis);
2267 }
2268
2269 // called by a UI or non-UI thread to remove the message
2270 void removeMessages(int what, Object object) {
2271 mHandler.removeMessages(what, object);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002272 }
2273
2274 // public message ids
2275 public final static int LOAD_URL = 1001;
2276 public final static int STOP_LOAD = 1002;
2277
2278 // Message Ids
2279 private static final int FOCUS_NODE_HREF = 102;
Grace Kloba92c18a52009-07-31 23:48:32 -07002280 private static final int RELEASE_WAKELOCK = 107;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002281
Grace Kloba22ac16e2009-10-07 18:00:23 -07002282 static final int UPDATE_BOOKMARK_THUMBNAIL = 108;
Ben Murdoch2694e232009-09-29 09:41:11 +01002283
Ben Murdocheecb4e62010-07-06 16:30:38 +01002284 private static final int TOUCH_ICON_DOWNLOADED = 109;
2285
Michael Kolb300b7f02010-08-25 13:47:24 -07002286 private static final int OPEN_BOOKMARKS = 201;
2287
The Android Open Source Project0c908882009-03-03 19:32:16 -08002288 // Private handler for handling javascript and saving passwords
2289 private Handler mHandler = new Handler() {
2290
Michael Kolbe0a36662010-06-29 10:37:12 -07002291 @Override
The Android Open Source Project0c908882009-03-03 19:32:16 -08002292 public void handleMessage(Message msg) {
2293 switch (msg.what) {
Michael Kolb300b7f02010-08-25 13:47:24 -07002294 case OPEN_BOOKMARKS:
2295 bookmarksOrHistoryPicker(false, false);
2296 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002297 case FOCUS_NODE_HREF:
Ben Murdoch2694e232009-09-29 09:41:11 +01002298 {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002299 String url = (String) msg.getData().get("url");
Ben Murdoch90d088c2009-11-17 18:14:04 +00002300 String title = (String) msg.getData().get("title");
The Android Open Source Project0c908882009-03-03 19:32:16 -08002301 if (url == null || url.length() == 0) {
2302 break;
2303 }
2304 HashMap focusNodeMap = (HashMap) msg.obj;
2305 WebView view = (WebView) focusNodeMap.get("webview");
2306 // Only apply the action if the top window did not change.
2307 if (getTopWindow() != view) {
2308 break;
2309 }
2310 switch (msg.arg1) {
2311 case R.id.open_context_menu_id:
2312 case R.id.view_image_context_menu_id:
Leon Scroggins92472e82010-02-17 16:32:28 -05002313 loadUrlFromContext(getTopWindow(), url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002314 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002315 case R.id.bookmark_context_menu_id:
2316 Intent intent = new Intent(BrowserActivity.this,
2317 AddBookmarkPage.class);
2318 intent.putExtra("url", url);
Ben Murdoch90d088c2009-11-17 18:14:04 +00002319 intent.putExtra("title", title);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002320 startActivity(intent);
2321 break;
2322 case R.id.share_link_context_menu_id:
Leon Scroggins3e204452010-05-10 11:06:03 -04002323 sharePage(BrowserActivity.this, title, url, null,
Leon Scroggins96afcb12009-12-10 12:35:56 -05002324 null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002325 break;
2326 case R.id.copy_link_context_menu_id:
2327 copy(url);
2328 break;
2329 case R.id.save_link_context_menu_id:
2330 case R.id.download_context_menu_id:
2331 onDownloadStartNoStream(url, null, null, null, -1);
2332 break;
2333 }
2334 break;
Ben Murdoch2694e232009-09-29 09:41:11 +01002335 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002336
2337 case LOAD_URL:
Leon Scroggins92472e82010-02-17 16:32:28 -05002338 loadUrlFromContext(getTopWindow(), (String) msg.obj);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002339 break;
2340
2341 case STOP_LOAD:
2342 stopLoading();
2343 break;
2344
The Android Open Source Project0c908882009-03-03 19:32:16 -08002345 case RELEASE_WAKELOCK:
2346 if (mWakeLock.isHeld()) {
2347 mWakeLock.release();
Grace Kloba5d0e02e2009-10-05 15:15:36 -07002348 // if we reach here, Browser should be still in the
2349 // background loading after WAKELOCK_TIMEOUT (5-min).
2350 // To avoid burning the battery, stop loading.
2351 mTabControl.stopAllLoading();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002352 }
2353 break;
Ben Murdoch2694e232009-09-29 09:41:11 +01002354
2355 case UPDATE_BOOKMARK_THUMBNAIL:
2356 WebView view = (WebView) msg.obj;
2357 if (view != null) {
2358 updateScreenshot(view);
2359 }
2360 break;
Ben Murdocheecb4e62010-07-06 16:30:38 +01002361
2362 case TOUCH_ICON_DOWNLOADED:
2363 Bundle b = msg.getData();
2364 showSaveToHomescreenDialog(b.getString("url"),
2365 b.getString("title"),
2366 (Bitmap) b.getParcelable("touchIcon"),
2367 (Bitmap) b.getParcelable("favicon"));
2368 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002369 }
2370 }
2371 };
2372
Leon Scroggins96afcb12009-12-10 12:35:56 -05002373 /**
2374 * Share a page, providing the title, url, favicon, and a screenshot. Uses
2375 * an {@link Intent} to launch the Activity chooser.
2376 * @param c Context used to launch a new Activity.
2377 * @param title Title of the page. Stored in the Intent with
Paul Westbrook03e6d392010-02-12 10:33:29 -08002378 * {@link Intent#EXTRA_SUBJECT}
Leon Scroggins96afcb12009-12-10 12:35:56 -05002379 * @param url URL of the page. Stored in the Intent with
2380 * {@link Intent#EXTRA_TEXT}
2381 * @param favicon Bitmap of the favicon for the page. Stored in the Intent
2382 * with {@link Browser#EXTRA_SHARE_FAVICON}
2383 * @param screenshot Bitmap of a screenshot of the page. Stored in the
2384 * Intent with {@link Browser#EXTRA_SHARE_SCREENSHOT}
2385 */
2386 public static final void sharePage(Context c, String title, String url,
2387 Bitmap favicon, Bitmap screenshot) {
2388 Intent send = new Intent(Intent.ACTION_SEND);
2389 send.setType("text/plain");
2390 send.putExtra(Intent.EXTRA_TEXT, url);
Paul Westbrook03e6d392010-02-12 10:33:29 -08002391 send.putExtra(Intent.EXTRA_SUBJECT, title);
Leon Scroggins96afcb12009-12-10 12:35:56 -05002392 send.putExtra(Browser.EXTRA_SHARE_FAVICON, favicon);
2393 send.putExtra(Browser.EXTRA_SHARE_SCREENSHOT, screenshot);
2394 try {
2395 c.startActivity(Intent.createChooser(send, c.getString(
2396 R.string.choosertitle_sharevia)));
2397 } catch(android.content.ActivityNotFoundException ex) {
2398 // if no app handles it, do nothing
2399 }
2400 }
2401
Leon Scroggins89c6d362009-07-15 16:54:37 -04002402 private void updateScreenshot(WebView view) {
2403 // If this is a bookmarked site, add a screenshot to the database.
2404 // FIXME: When should we update? Every time?
2405 // FIXME: Would like to make sure there is actually something to
2406 // draw, but the API for that (WebViewCore.pictureReady()) is not
2407 // currently accessible here.
Ben Murdochaac7aa62009-09-17 16:57:40 +01002408
Ben Murdoch87cc65d2010-06-29 20:34:10 +01002409 final Bitmap bm = createScreenshot(view, getDesiredThumbnailWidth(this),
2410 getDesiredThumbnailHeight(this));
Patrick Scottcb192b52010-04-14 14:38:55 -04002411 if (bm == null) {
2412 return;
Leon Scroggins89c6d362009-07-15 16:54:37 -04002413 }
Patrick Scottcb192b52010-04-14 14:38:55 -04002414
2415 final ContentResolver cr = getContentResolver();
2416 final String url = view.getUrl();
2417 final String originalUrl = view.getOriginalUrl();
2418
2419 new AsyncTask<Void, Void, Void>() {
2420 @Override
2421 protected Void doInBackground(Void... unused) {
2422 Cursor c = null;
2423 try {
Jeff Hamilton84029622010-08-05 14:29:28 -05002424 c = Bookmarks.queryBookmarksForUrl(
Jeff Hamilton8ce956c2010-08-17 11:13:53 -05002425 cr, originalUrl, url);
Patrick Scottcb192b52010-04-14 14:38:55 -04002426 if (c != null) {
2427 if (c.moveToFirst()) {
2428 ContentValues values = new ContentValues();
2429 final ByteArrayOutputStream os
2430 = new ByteArrayOutputStream();
2431 bm.compress(Bitmap.CompressFormat.PNG, 100, os);
Jeff Hamilton8ce956c2010-08-17 11:13:53 -05002432 values.put(BrowserContract.Bookmarks.THUMBNAIL,
Patrick Scottcb192b52010-04-14 14:38:55 -04002433 os.toByteArray());
2434 do {
2435 cr.update(ContentUris.withAppendedId(
Jeff Hamilton8ce956c2010-08-17 11:13:53 -05002436 BrowserContract.Bookmarks.CONTENT_URI, c.getLong(0)),
Patrick Scottcb192b52010-04-14 14:38:55 -04002437 values, null, null);
2438 } while (c.moveToNext());
2439 }
2440 }
2441 } catch (IllegalStateException e) {
2442 // Ignore
2443 } finally {
2444 if (c != null) c.close();
2445 }
2446 return null;
2447 }
2448 }.execute();
Leon Scroggins89c6d362009-07-15 16:54:37 -04002449 }
2450
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002451 /**
Leon Scrogginsf8551612009-09-24 16:06:02 -04002452 * Values for the size of the thumbnail created when taking a screenshot.
2453 * Lazily initialized. Instead of using these directly, use
2454 * getDesiredThumbnailWidth() or getDesiredThumbnailHeight().
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002455 */
Leon Scrogginsf8551612009-09-24 16:06:02 -04002456 private static int THUMBNAIL_WIDTH = 0;
2457 private static int THUMBNAIL_HEIGHT = 0;
2458
2459 /**
2460 * Return the desired width for thumbnail screenshots, which are stored in
2461 * the database, and used on the bookmarks screen.
2462 * @param context Context for finding out the density of the screen.
2463 * @return int desired width for thumbnail screenshot.
2464 */
2465 /* package */ static int getDesiredThumbnailWidth(Context context) {
2466 if (THUMBNAIL_WIDTH == 0) {
2467 float density = context.getResources().getDisplayMetrics().density;
2468 THUMBNAIL_WIDTH = (int) (90 * density);
2469 THUMBNAIL_HEIGHT = (int) (80 * density);
2470 }
2471 return THUMBNAIL_WIDTH;
2472 }
2473
2474 /**
2475 * Return the desired height for thumbnail screenshots, which are stored in
2476 * the database, and used on the bookmarks screen.
2477 * @param context Context for finding out the density of the screen.
2478 * @return int desired height for thumbnail screenshot.
2479 */
2480 /* package */ static int getDesiredThumbnailHeight(Context context) {
2481 // To ensure that they are both initialized.
2482 getDesiredThumbnailWidth(context);
2483 return THUMBNAIL_HEIGHT;
2484 }
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002485
Ben Murdoch87cc65d2010-06-29 20:34:10 +01002486 private Bitmap createScreenshot(WebView view, int width, int height) {
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002487 Picture thumbnail = view.capturePicture();
Leon Scroggins45800572009-09-29 16:38:47 -04002488 if (thumbnail == null) {
2489 return null;
2490 }
Ben Murdoch87cc65d2010-06-29 20:34:10 +01002491 Bitmap bm = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002492 Canvas canvas = new Canvas(bm);
2493 // May need to tweak these values to determine what is the
2494 // best scale factor
Ben Murdoch2694e232009-09-29 09:41:11 +01002495 int thumbnailWidth = thumbnail.getWidth();
Ben Murdochae59c3f2009-10-20 18:30:28 +01002496 int thumbnailHeight = thumbnail.getHeight();
2497 float scaleFactorX = 1.0f;
2498 float scaleFactorY = 1.0f;
Ben Murdoch2694e232009-09-29 09:41:11 +01002499 if (thumbnailWidth > 0) {
Ben Murdoch87cc65d2010-06-29 20:34:10 +01002500 scaleFactorX = (float) width / (float)thumbnailWidth;
Ben Murdochae59c3f2009-10-20 18:30:28 +01002501 } else {
2502 return null;
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002503 }
Ben Murdochae59c3f2009-10-20 18:30:28 +01002504
2505 if (view.getWidth() > view.getHeight() &&
2506 thumbnailHeight < view.getHeight() && thumbnailHeight > 0) {
2507 // If the device is in landscape and the page is shorter
2508 // than the height of the view, stretch the thumbnail to fill the
2509 // space.
Ben Murdoch87cc65d2010-06-29 20:34:10 +01002510 scaleFactorY = (float) height / (float)thumbnailHeight;
Ben Murdochae59c3f2009-10-20 18:30:28 +01002511 } else {
2512 // In the portrait case, this looks nice.
2513 scaleFactorY = scaleFactorX;
2514 }
2515
2516 canvas.scale(scaleFactorX, scaleFactorY);
2517
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002518 thumbnail.draw(canvas);
2519 return bm;
2520 }
2521
The Android Open Source Project0c908882009-03-03 19:32:16 -08002522 // -------------------------------------------------------------------------
Grace Kloba22ac16e2009-10-07 18:00:23 -07002523 // Helper function for WebViewClient.
The Android Open Source Project0c908882009-03-03 19:32:16 -08002524 //-------------------------------------------------------------------------
2525
2526 // Use in overrideUrlLoading
2527 /* package */ final static String SCHEME_WTAI = "wtai://wp/";
2528 /* package */ final static String SCHEME_WTAI_MC = "wtai://wp/mc;";
2529 /* package */ final static String SCHEME_WTAI_SD = "wtai://wp/sd;";
2530 /* package */ final static String SCHEME_WTAI_AP = "wtai://wp/ap;";
2531
Leon Scroggins92472e82010-02-17 16:32:28 -05002532 // Keep this initial progress in sync with initialProgressValue (* 100)
2533 // in ProgressTracker.cpp
2534 private final static int INITIAL_PROGRESS = 10;
2535
Grace Kloba22ac16e2009-10-07 18:00:23 -07002536 void onPageStarted(WebView view, String url, Bitmap favicon) {
2537 // when BrowserActivity just starts, onPageStarted may be called before
2538 // onResume as it is triggered from onCreate. Call resumeWebViewTimers
2539 // to start the timer. As we won't switch tabs while an activity is in
2540 // pause state, we can ensure calling resume and pause in pair.
2541 if (mActivityInPause) resumeWebViewTimers();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002542
Grace Kloba22ac16e2009-10-07 18:00:23 -07002543 resetLockIcon(url);
2544 setUrlTitle(url, null);
2545 setFavicon(favicon);
Leon Scroggins8cf8f682009-11-04 11:13:50 -08002546 // Show some progress so that the user knows the page is beginning to
2547 // load
Leon Scroggins92472e82010-02-17 16:32:28 -05002548 onProgressChanged(view, INITIAL_PROGRESS);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002549 mDidStopLoad = false;
Grace Kloba22ac16e2009-10-07 18:00:23 -07002550 if (!mIsNetworkUp) createAndShowNetworkDialog();
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04002551 endActionMode();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002552 if (mSettings.isTracing()) {
2553 String host;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002554 try {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002555 WebAddress uri = new WebAddress(url);
2556 host = uri.mHost;
2557 } catch (android.net.ParseException ex) {
2558 host = "browser";
The Android Open Source Project0c908882009-03-03 19:32:16 -08002559 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002560 host = host.replace('.', '_');
2561 host += ".trace";
2562 mInTrace = true;
2563 Debug.startMethodTracing(host, 20 * 1024 * 1024);
2564 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002565
Grace Kloba22ac16e2009-10-07 18:00:23 -07002566 // Performance probe
2567 if (false) {
2568 mStart = SystemClock.uptimeMillis();
2569 mProcessStart = Process.getElapsedCpuTime();
2570 long[] sysCpu = new long[7];
2571 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2572 sysCpu, null)) {
2573 mUserStart = sysCpu[0] + sysCpu[1];
2574 mSystemStart = sysCpu[2];
2575 mIdleStart = sysCpu[3];
2576 mIrqStart = sysCpu[4] + sysCpu[5] + sysCpu[6];
2577 }
2578 mUiStart = SystemClock.currentThreadTimeMillis();
2579 }
2580 }
2581
2582 void onPageFinished(WebView view, String url) {
2583 // Reset the title and icon in case we stopped a provisional load.
2584 resetTitleAndIcon(view);
2585 // Update the lock icon image only once we are done loading
2586 updateLockIconToLatest();
2587 // pause the WebView timer and release the wake lock if it is finished
2588 // while BrowserActivity is in pause state.
2589 if (mActivityInPause && pauseWebViewTimers()) {
2590 if (mWakeLock.isHeld()) {
2591 mHandler.removeMessages(RELEASE_WAKELOCK);
2592 mWakeLock.release();
2593 }
2594 }
2595
2596 // Performance probe
2597 if (false) {
2598 long[] sysCpu = new long[7];
2599 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2600 sysCpu, null)) {
2601 String uiInfo = "UI thread used "
2602 + (SystemClock.currentThreadTimeMillis() - mUiStart)
2603 + " ms";
2604 if (LOGD_ENABLED) {
2605 Log.d(LOGTAG, uiInfo);
2606 }
2607 //The string that gets written to the log
2608 String performanceString = "It took total "
2609 + (SystemClock.uptimeMillis() - mStart)
2610 + " ms clock time to load the page."
2611 + "\nbrowser process used "
2612 + (Process.getElapsedCpuTime() - mProcessStart)
2613 + " ms, user processes used "
2614 + (sysCpu[0] + sysCpu[1] - mUserStart) * 10
2615 + " ms, kernel used "
2616 + (sysCpu[2] - mSystemStart) * 10
2617 + " ms, idle took " + (sysCpu[3] - mIdleStart) * 10
2618 + " ms and irq took "
2619 + (sysCpu[4] + sysCpu[5] + sysCpu[6] - mIrqStart)
2620 * 10 + " ms, " + uiInfo;
2621 if (LOGD_ENABLED) {
2622 Log.d(LOGTAG, performanceString + "\nWebpage: " + url);
2623 }
2624 if (url != null) {
2625 // strip the url to maintain consistency
2626 String newUrl = new String(url);
2627 if (newUrl.startsWith("http://www.")) {
2628 newUrl = newUrl.substring(11);
2629 } else if (newUrl.startsWith("http://")) {
2630 newUrl = newUrl.substring(7);
2631 } else if (newUrl.startsWith("https://www.")) {
2632 newUrl = newUrl.substring(12);
2633 } else if (newUrl.startsWith("https://")) {
2634 newUrl = newUrl.substring(8);
2635 }
2636 if (LOGD_ENABLED) {
2637 Log.d(LOGTAG, newUrl + " loaded");
2638 }
Grace Kloba5b078b52009-06-24 20:23:41 -07002639 }
2640 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002641 }
Grace Kloba5b078b52009-06-24 20:23:41 -07002642
Grace Kloba22ac16e2009-10-07 18:00:23 -07002643 if (mInTrace) {
2644 mInTrace = false;
2645 Debug.stopMethodTracing();
2646 }
2647 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002648
Grace Klobae7fe26b2010-06-28 16:23:33 -07002649 private void closeEmptyChildTab() {
2650 Tab current = mTabControl.getCurrentTab();
2651 if (current != null
2652 && current.getWebView().copyBackForwardList().getSize() == 0) {
2653 Tab parent = current.getParentTab();
2654 if (parent != null) {
2655 switchToTab(mTabControl.getTabIndex(parent));
2656 closeTab(current);
2657 }
2658 }
2659 }
2660
Grace Kloba22ac16e2009-10-07 18:00:23 -07002661 boolean shouldOverrideUrlLoading(WebView view, String url) {
2662 if (url.startsWith(SCHEME_WTAI)) {
2663 // wtai://wp/mc;number
2664 // number=string(phone-number)
2665 if (url.startsWith(SCHEME_WTAI_MC)) {
2666 Intent intent = new Intent(Intent.ACTION_VIEW,
2667 Uri.parse(WebView.SCHEME_TEL +
2668 url.substring(SCHEME_WTAI_MC.length())));
2669 startActivity(intent);
Grace Klobae7fe26b2010-06-28 16:23:33 -07002670 // before leaving BrowserActivity, close the empty child tab.
2671 // If a new tab is created through JavaScript open to load this
2672 // url, we would like to close it as we will load this url in a
2673 // different Activity.
2674 closeEmptyChildTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002675 return true;
2676 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002677 // wtai://wp/sd;dtmf
2678 // dtmf=string(dialstring)
2679 if (url.startsWith(SCHEME_WTAI_SD)) {
2680 // TODO: only send when there is active voice connection
2681 return false;
2682 }
2683 // wtai://wp/ap;number;name
2684 // number=string(phone-number)
2685 // name=string
2686 if (url.startsWith(SCHEME_WTAI_AP)) {
2687 // TODO
2688 return false;
2689 }
2690 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002691
Grace Kloba22ac16e2009-10-07 18:00:23 -07002692 // The "about:" schemes are internal to the browser; don't want these to
2693 // be dispatched to other apps.
2694 if (url.startsWith("about:")) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002695 return false;
2696 }
2697
Jeff Davidson43610292010-07-16 16:03:58 -07002698 // If this is a Google search, attempt to add an RLZ string (if one isn't already present).
2699 if (rlzProviderPresent()) {
2700 Uri siteUri = Uri.parse(url);
2701 if (needsRlzString(siteUri)) {
2702 String rlz = null;
2703 Cursor cur = null;
2704 try {
2705 cur = getContentResolver().query(getRlzUri(), null, null, null, null);
2706 if (cur != null && cur.moveToFirst() && !cur.isNull(0)) {
2707 url = siteUri.buildUpon()
2708 .appendQueryParameter("rlz", cur.getString(0))
2709 .build().toString();
2710 }
2711 } finally {
2712 if (cur != null) {
2713 cur.close();
2714 }
2715 }
2716 loadUrl(view, url);
2717 return true;
2718 }
2719 }
2720
Grace Kloba22ac16e2009-10-07 18:00:23 -07002721 Intent intent;
2722 // perform generic parsing of the URI to turn it into an Intent.
2723 try {
2724 intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME);
2725 } catch (URISyntaxException ex) {
2726 Log.w("Browser", "Bad URI " + url + ": " + ex.getMessage());
2727 return false;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002728 }
2729
Grace Kloba22ac16e2009-10-07 18:00:23 -07002730 // check whether the intent can be resolved. If not, we will see
2731 // whether we can download it from the Market.
2732 if (getPackageManager().resolveActivity(intent, 0) == null) {
2733 String packagename = intent.getPackage();
2734 if (packagename != null) {
2735 intent = new Intent(Intent.ACTION_VIEW, Uri
2736 .parse("market://search?q=pname:" + packagename));
2737 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2738 startActivity(intent);
Grace Klobae7fe26b2010-06-28 16:23:33 -07002739 // before leaving BrowserActivity, close the empty child tab.
2740 // If a new tab is created through JavaScript open to load this
2741 // url, we would like to close it as we will load this url in a
2742 // different Activity.
2743 closeEmptyChildTab();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002744 return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002745 } else {
2746 return false;
2747 }
2748 }
2749
Grace Kloba22ac16e2009-10-07 18:00:23 -07002750 // sanitize the Intent, ensuring web pages can not bypass browser
2751 // security (only access to BROWSABLE activities).
2752 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2753 intent.setComponent(null);
2754 try {
2755 if (startActivityIfNeeded(intent, -1)) {
Grace Klobae7fe26b2010-06-28 16:23:33 -07002756 // before leaving BrowserActivity, close the empty child tab.
2757 // If a new tab is created through JavaScript open to load this
2758 // url, we would like to close it as we will load this url in a
2759 // different Activity.
2760 closeEmptyChildTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002761 return true;
2762 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002763 } catch (ActivityNotFoundException ex) {
2764 // ignore the error. If no application can handle the URL,
2765 // eg about:blank, assume the browser can handle it.
2766 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002767
Grace Kloba22ac16e2009-10-07 18:00:23 -07002768 if (mMenuIsDown) {
Michael Kolb68792c82010-08-09 16:39:18 -07002769 openTab(url, false);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002770 closeOptionsMenu();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002771 return true;
2772 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002773 return false;
2774 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002775
Jeff Davidson43610292010-07-16 16:03:58 -07002776 // Determine whether the RLZ provider is present on the system.
2777 private boolean rlzProviderPresent() {
2778 if (mIsProviderPresent == null) {
2779 PackageManager pm = getPackageManager();
2780 mIsProviderPresent = pm.resolveContentProvider(BrowserSettings.RLZ_PROVIDER, 0) != null;
2781 }
2782 return mIsProviderPresent;
2783 }
2784
2785 // Retrieve the RLZ access point string and cache the URI used to retrieve RLZ values.
2786 private Uri getRlzUri() {
2787 if (mRlzUri == null) {
2788 String ap = getResources().getString(R.string.rlz_access_point);
2789 mRlzUri = Uri.withAppendedPath(BrowserSettings.RLZ_PROVIDER_URI, ap);
2790 }
2791 return mRlzUri;
2792 }
2793
2794 // Determine if this URI appears to be for a Google search and does not have an RLZ parameter.
2795 // Taken largely from Chrome source, src/chrome/browser/google_url_tracker.cc
2796 private static boolean needsRlzString(Uri uri) {
Bill Napierc50e71a2010-08-27 14:03:03 -07002797 String scheme = uri.getScheme();
2798 if (("http".equals(scheme) || "https".equals(scheme)) &&
2799 (uri.getQueryParameter("q") != null) && (uri.getQueryParameter("rlz") == null)) {
Jeff Davidson43610292010-07-16 16:03:58 -07002800 String host = uri.getHost();
2801 if (host == null) {
2802 return false;
2803 }
2804 String[] hostComponents = host.split("\\.");
2805
2806 if (hostComponents.length < 2) {
2807 return false;
2808 }
2809 int googleComponent = hostComponents.length - 2;
2810 String component = hostComponents[googleComponent];
2811 if (!"google".equals(component)) {
2812 if (hostComponents.length < 3 ||
2813 (!"co".equals(component) && !"com".equals(component))) {
2814 return false;
2815 }
2816 googleComponent = hostComponents.length - 3;
2817 if (!"google".equals(hostComponents[googleComponent])) {
2818 return false;
2819 }
2820 }
2821
2822 // Google corp network handling.
2823 if (googleComponent > 0 && "corp".equals(hostComponents[googleComponent - 1])) {
2824 return false;
2825 }
2826
2827 return true;
2828 }
2829 return false;
2830 }
2831
Grace Kloba22ac16e2009-10-07 18:00:23 -07002832 // -------------------------------------------------------------------------
2833 // Helper function for WebChromeClient
2834 // -------------------------------------------------------------------------
The Android Open Source Project0c908882009-03-03 19:32:16 -08002835
Grace Kloba22ac16e2009-10-07 18:00:23 -07002836 void onProgressChanged(WebView view, int newProgress) {
Michael Kolba2b2ba82010-08-04 17:54:03 -07002837
2838 // On the phone, the fake title bar will always cover up the
2839 // regular title bar (or the regular one is offscreen), so only the
2840 // fake title bar needs to change its progress
2841 mFakeTitleBar.setProgress(newProgress);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002842
Grace Kloba22ac16e2009-10-07 18:00:23 -07002843 if (newProgress == 100) {
2844 // onProgressChanged() may continue to be called after the main
2845 // frame has finished loading, as any remaining sub frames continue
2846 // to load. We'll only get called once though with newProgress as
2847 // 100 when everything is loaded. (onPageFinished is called once
2848 // when the main frame completes loading regardless of the state of
2849 // any sub frames so calls to onProgressChanges may continue after
2850 // onPageFinished has executed)
2851 if (mInLoad) {
2852 mInLoad = false;
Leon Scrogginsa27ff192009-09-14 12:58:04 -04002853 updateInLoadMenuItems();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002854 // If the options menu is open, leave the title bar
2855 if (!mOptionsMenuOpen || !mIconView) {
2856 hideFakeTitleBar();
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07002857 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002858 }
Leon Scrogginsaa37e7f2010-03-05 11:51:20 -05002859 } else {
2860 if (!mInLoad) {
2861 // onPageFinished may have already been called but a subframe is
2862 // still loading and updating the progress. Reset mInLoad and
2863 // update the menu items.
2864 mInLoad = true;
2865 updateInLoadMenuItems();
2866 }
2867 // When the page first begins to load, the Activity may still be
2868 // paused, in which case showFakeTitleBar will do nothing. Call
2869 // again as the page continues to load so that it will be shown.
2870 // (Calling it will the fake title bar is already showing will also
2871 // do nothing.
Grace Kloba22ac16e2009-10-07 18:00:23 -07002872 if (!mOptionsMenuOpen || mIconView) {
2873 // This page has begun to load, so show the title bar
2874 showFakeTitleBar();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002875 }
2876 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002877 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002878
Grace Kloba22ac16e2009-10-07 18:00:23 -07002879 void onShowCustomView(View view, WebChromeClient.CustomViewCallback callback) {
Derek Sollenberger8ff57db2009-12-08 15:39:55 -05002880 // if a view already exists then immediately terminate the new one
2881 if (mCustomView != null) {
2882 callback.onCustomViewHidden();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002883 return;
Derek Sollenberger8ff57db2009-12-08 15:39:55 -05002884 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002885
2886 // Add the custom view to its container.
2887 mCustomViewContainer.addView(view, COVER_SCREEN_GRAVITY_CENTER);
2888 mCustomView = view;
2889 mCustomViewCallback = callback;
2890 // Save the menu state and set it to empty while the custom
2891 // view is showing.
2892 mOldMenuState = mMenuState;
2893 mMenuState = EMPTY_MENU;
2894 // Hide the content view.
2895 mContentView.setVisibility(View.GONE);
2896 // Finally show the custom view container.
Andrei Popescu163ab742009-10-20 17:58:23 +01002897 setStatusBarVisibility(false);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002898 mCustomViewContainer.setVisibility(View.VISIBLE);
2899 mCustomViewContainer.bringToFront();
2900 }
2901
2902 void onHideCustomView() {
2903 if (mCustomView == null)
2904 return;
2905
2906 // Hide the custom view.
2907 mCustomView.setVisibility(View.GONE);
2908 // Remove the custom view from its container.
2909 mCustomViewContainer.removeView(mCustomView);
2910 mCustomView = null;
2911 // Reset the old menu state.
2912 mMenuState = mOldMenuState;
2913 mOldMenuState = EMPTY_MENU;
2914 mCustomViewContainer.setVisibility(View.GONE);
2915 mCustomViewCallback.onCustomViewHidden();
2916 // Show the content view.
Andrei Popescu163ab742009-10-20 17:58:23 +01002917 setStatusBarVisibility(true);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002918 mContentView.setVisibility(View.VISIBLE);
2919 }
2920
2921 Bitmap getDefaultVideoPoster() {
2922 if (mDefaultVideoPoster == null) {
2923 mDefaultVideoPoster = BitmapFactory.decodeResource(
2924 getResources(), R.drawable.default_video_poster);
Patrick Scott3918d442009-08-04 13:22:29 -04002925 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002926 return mDefaultVideoPoster;
2927 }
Patrick Scott3918d442009-08-04 13:22:29 -04002928
Grace Kloba22ac16e2009-10-07 18:00:23 -07002929 View getVideoLoadingProgressView() {
2930 if (mVideoProgressView == null) {
2931 LayoutInflater inflater = LayoutInflater.from(BrowserActivity.this);
2932 mVideoProgressView = inflater.inflate(
2933 R.layout.video_loading_progress, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002934 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002935 return mVideoProgressView;
2936 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002937
Leon Scroggins8d5fa432009-10-02 15:55:59 -04002938 /*
2939 * The Object used to inform the WebView of the file to upload.
2940 */
2941 private ValueCallback<Uri> mUploadMessage;
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002942 private String mCameraFilePath;
Leon Scroggins8d5fa432009-10-02 15:55:59 -04002943
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002944 void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
2945
2946 final String imageMimeType = "image/*";
Ben Murdoch6af492a2010-06-15 12:38:17 +01002947 final String videoMimeType = "video/*";
Ben Murdoch039bd472010-07-21 21:26:57 +01002948 final String audioMimeType = "audio/*";
Ben Murdochb50d7402010-07-16 12:42:22 +01002949 final String mediaSourceKey = "capture";
Ben Murdoch6af492a2010-06-15 12:38:17 +01002950 final String mediaSourceValueCamera = "camera";
Ben Murdochb50d7402010-07-16 12:42:22 +01002951 final String mediaSourceValueFileSystem = "filesystem";
Ben Murdoch6af492a2010-06-15 12:38:17 +01002952 final String mediaSourceValueCamcorder = "camcorder";
Ben Murdoch039bd472010-07-21 21:26:57 +01002953 final String mediaSourceValueMicrophone = "microphone";
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002954
Ben Murdoch039bd472010-07-21 21:26:57 +01002955 // media source can be 'filesystem' or 'camera' or 'camcorder' or 'microphone'.
Ben Murdoch6af492a2010-06-15 12:38:17 +01002956 String mediaSource = "";
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002957
Ben Murdoch6af492a2010-06-15 12:38:17 +01002958 // We add the camera intent if there was no accept type (or '*/*' or 'image/*').
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002959 boolean addCameraIntent = true;
Ben Murdoch6af492a2010-06-15 12:38:17 +01002960 // We add the camcorder intent if there was no accept type (or '*/*' or 'video/*').
2961 boolean addCamcorderIntent = true;
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002962
Ben Murdoch6af492a2010-06-15 12:38:17 +01002963 if (mUploadMessage != null) {
2964 // Already a file picker operation in progress.
2965 return;
2966 }
2967
Grace Kloba22ac16e2009-10-07 18:00:23 -07002968 mUploadMessage = uploadMsg;
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002969
2970 // Parse the accept type.
2971 String params[] = acceptType.split(";");
2972 String mimeType = params[0];
2973
2974 for (String p : params) {
2975 String[] keyValue = p.split("=");
2976 if (keyValue.length == 2) {
2977 // Process key=value parameters.
Ben Murdoch6af492a2010-06-15 12:38:17 +01002978 if (mediaSourceKey.equals(keyValue[0])) {
2979 mediaSource = keyValue[1];
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002980 }
2981 }
2982 }
2983
2984 // This intent will display the standard OPENABLE file picker.
Grace Kloba22ac16e2009-10-07 18:00:23 -07002985 Intent i = new Intent(Intent.ACTION_GET_CONTENT);
2986 i.addCategory(Intent.CATEGORY_OPENABLE);
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002987
2988 // Create an intent to add to the standard file picker that will
2989 // capture an image from the camera. We'll combine this intent with
2990 // the standard OPENABLE picker unless the web developer specifically
2991 // requested the camera or gallery be opened by passing a parameter
2992 // in the accept type.
2993 Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
2994 File externalDataDir = Environment.getExternalStoragePublicDirectory(
2995 Environment.DIRECTORY_DCIM);
2996 File cameraDataDir = new File(externalDataDir.getAbsolutePath() +
2997 File.separator + "browser-photos");
2998 cameraDataDir.mkdirs();
2999 mCameraFilePath = cameraDataDir.getAbsolutePath() + File.separator +
3000 System.currentTimeMillis() + ".jpg";
3001 cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(mCameraFilePath)));
3002
Ben Murdoch6af492a2010-06-15 12:38:17 +01003003 Intent camcorderIntent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
3004
Ben Murdoch039bd472010-07-21 21:26:57 +01003005 Intent soundRecIntent = new Intent(MediaStore.Audio.Media.RECORD_SOUND_ACTION);
3006
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003007 if (mimeType.equals(imageMimeType)) {
3008 i.setType(imageMimeType);
Ben Murdoch6af492a2010-06-15 12:38:17 +01003009 addCamcorderIntent = false;
3010 if (mediaSource.equals(mediaSourceValueCamera)) {
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003011 // Specified 'image/*' and requested the camera, so go ahead and launch the camera
3012 // directly.
3013 BrowserActivity.this.startActivityForResult(cameraIntent, FILE_SELECTED);
3014 return;
Ben Murdochb50d7402010-07-16 12:42:22 +01003015 } else if (mediaSource.equals(mediaSourceValueFileSystem)) {
3016 // Specified filesytem as the source, so don't want to consider the camera.
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003017 addCameraIntent = false;
3018 }
Ben Murdoch6af492a2010-06-15 12:38:17 +01003019 } else if (mimeType.equals(videoMimeType)) {
3020 i.setType(videoMimeType);
3021 addCameraIntent = false;
3022 // The camcorder saves it's own file and returns it to us in the intent, so
3023 // we don't need to generate one here.
3024 mCameraFilePath = null;
3025
3026 if (mediaSource.equals(mediaSourceValueCamcorder)) {
Ben Murdoch039bd472010-07-21 21:26:57 +01003027 // Specified 'video/*' and requested the camcorder, so go ahead and launch the
3028 // camcorder directly.
Ben Murdoch6af492a2010-06-15 12:38:17 +01003029 BrowserActivity.this.startActivityForResult(camcorderIntent, FILE_SELECTED);
3030 return;
Ben Murdochb50d7402010-07-16 12:42:22 +01003031 } else if (mediaSource.equals(mediaSourceValueFileSystem)) {
3032 // Specified filesystem as the source, so don't want to consider the camcorder.
Ben Murdoch6af492a2010-06-15 12:38:17 +01003033 addCamcorderIntent = false;
3034 }
Ben Murdoch039bd472010-07-21 21:26:57 +01003035 } else if (mimeType.equals(audioMimeType)) {
3036 i.setType(audioMimeType);
3037 addCameraIntent = false;
3038 addCamcorderIntent = false;
3039 if (mediaSource.equals(mediaSourceValueMicrophone)) {
3040 // Specified 'audio/*' and requested microphone, so go ahead and launch the sound
3041 // recorder.
3042 BrowserActivity.this.startActivityForResult(soundRecIntent, FILE_SELECTED);
3043 return;
3044 }
3045 // On a default system, there is no single option to open an audio "gallery". Both the
3046 // sound recorder and music browser respond to the OPENABLE/audio/* intent unlike the
3047 // image/* and video/* OPENABLE intents where the image / video gallery are the only
3048 // respondants (and so the user is not prompted by default).
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003049 } else {
3050 i.setType("*/*");
3051 }
3052
Ben Murdoch6af492a2010-06-15 12:38:17 +01003053 // Combine the chooser and the extra choices (like camera or camcorder)
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003054 Intent chooser = new Intent(Intent.ACTION_CHOOSER);
3055 chooser.putExtra(Intent.EXTRA_INTENT, i);
3056
Ben Murdoch6af492a2010-06-15 12:38:17 +01003057 Vector<Intent> extraInitialIntents = new Vector<Intent>(0);
3058
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003059 if (addCameraIntent) {
Ben Murdoch6af492a2010-06-15 12:38:17 +01003060 extraInitialIntents.add(cameraIntent);
3061 }
3062
3063 if (addCamcorderIntent) {
3064 extraInitialIntents.add(camcorderIntent);
3065 }
3066
3067 if (extraInitialIntents.size() > 0) {
3068 Intent[] extraIntents = new Intent[extraInitialIntents.size()];
3069 chooser.putExtra(Intent.EXTRA_INITIAL_INTENTS, extraInitialIntents.toArray(extraIntents));
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003070 }
3071
3072 chooser.putExtra(Intent.EXTRA_TITLE, getString(R.string.choose_upload));
3073 BrowserActivity.this.startActivityForResult(chooser, FILE_SELECTED);
Grace Kloba22ac16e2009-10-07 18:00:23 -07003074 }
3075
3076 // -------------------------------------------------------------------------
3077 // Implement functions for DownloadListener
3078 // -------------------------------------------------------------------------
3079
The Android Open Source Project0c908882009-03-03 19:32:16 -08003080 /**
3081 * Notify the host application a download should be done, or that
3082 * the data should be streamed if a streaming viewer is available.
3083 * @param url The full url to the content that should be downloaded
3084 * @param contentDisposition Content-disposition http header, if
3085 * present.
3086 * @param mimetype The mimetype of the content reported by the server
3087 * @param contentLength The file size reported by the server
3088 */
3089 public void onDownloadStart(String url, String userAgent,
3090 String contentDisposition, String mimetype, long contentLength) {
3091 // if we're dealing wih A/V content that's not explicitly marked
3092 // for download, check if it's streamable.
3093 if (contentDisposition == null
Patrick Scotte1fb9662009-08-31 14:31:52 -04003094 || !contentDisposition.regionMatches(
3095 true, 0, "attachment", 0, 10)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003096 // query the package manager to see if there's a registered handler
3097 // that matches.
3098 Intent intent = new Intent(Intent.ACTION_VIEW);
3099 intent.setDataAndType(Uri.parse(url), mimetype);
Patrick Scotte1fb9662009-08-31 14:31:52 -04003100 ResolveInfo info = getPackageManager().resolveActivity(intent,
3101 PackageManager.MATCH_DEFAULT_ONLY);
3102 if (info != null) {
3103 ComponentName myName = getComponentName();
3104 // If we resolved to ourselves, we don't want to attempt to
3105 // load the url only to try and download it again.
3106 if (!myName.getPackageName().equals(
3107 info.activityInfo.packageName)
3108 || !myName.getClassName().equals(
3109 info.activityInfo.name)) {
3110 // someone (other than us) knows how to handle this mime
3111 // type with this scheme, don't download.
3112 try {
3113 startActivity(intent);
3114 return;
3115 } catch (ActivityNotFoundException ex) {
3116 if (LOGD_ENABLED) {
3117 Log.d(LOGTAG, "activity not found for " + mimetype
3118 + " over " + Uri.parse(url).getScheme(),
3119 ex);
3120 }
3121 // Best behavior is to fall back to a download in this
3122 // case
The Android Open Source Project0c908882009-03-03 19:32:16 -08003123 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003124 }
3125 }
3126 }
3127 onDownloadStartNoStream(url, userAgent, contentDisposition, mimetype, contentLength);
3128 }
3129
Kristian Monsenfa52d172010-03-25 18:29:21 +00003130 // This is to work around the fact that java.net.URI throws Exceptions
3131 // instead of just encoding URL's properly
3132 // Helper method for onDownloadStartNoStream
3133 private static String encodePath(String path) {
3134 char[] chars = path.toCharArray();
3135
3136 boolean needed = false;
3137 for (char c : chars) {
3138 if (c == '[' || c == ']') {
3139 needed = true;
3140 break;
3141 }
3142 }
3143 if (needed == false) {
3144 return path;
3145 }
3146
3147 StringBuilder sb = new StringBuilder("");
3148 for (char c : chars) {
3149 if (c == '[' || c == ']') {
3150 sb.append('%');
3151 sb.append(Integer.toHexString(c));
3152 } else {
3153 sb.append(c);
3154 }
3155 }
3156
3157 return sb.toString();
3158 }
3159
The Android Open Source Project0c908882009-03-03 19:32:16 -08003160 /**
3161 * Notify the host application a download should be done, even if there
3162 * is a streaming viewer available for thise type.
3163 * @param url The full url to the content that should be downloaded
3164 * @param contentDisposition Content-disposition http header, if
3165 * present.
3166 * @param mimetype The mimetype of the content reported by the server
3167 * @param contentLength The file size reported by the server
3168 */
3169 /*package */ void onDownloadStartNoStream(String url, String userAgent,
3170 String contentDisposition, String mimetype, long contentLength) {
3171
3172 String filename = URLUtil.guessFileName(url,
3173 contentDisposition, mimetype);
3174
3175 // Check to see if we have an SDCard
3176 String status = Environment.getExternalStorageState();
3177 if (!status.equals(Environment.MEDIA_MOUNTED)) {
3178 int title;
3179 String msg;
3180
3181 // Check to see if the SDCard is busy, same as the music app
3182 if (status.equals(Environment.MEDIA_SHARED)) {
3183 msg = getString(R.string.download_sdcard_busy_dlg_msg);
3184 title = R.string.download_sdcard_busy_dlg_title;
3185 } else {
3186 msg = getString(R.string.download_no_sdcard_dlg_msg, filename);
3187 title = R.string.download_no_sdcard_dlg_title;
3188 }
3189
3190 new AlertDialog.Builder(this)
3191 .setTitle(title)
3192 .setIcon(android.R.drawable.ic_dialog_alert)
3193 .setMessage(msg)
3194 .setPositiveButton(R.string.ok, null)
3195 .show();
3196 return;
3197 }
3198
Kristian Monsenfa52d172010-03-25 18:29:21 +00003199 // java.net.URI is a lot stricter than KURL so we have to encode some
3200 // extra characters. Fix for b 2538060 and b 1634719
3201 WebAddress webAddress;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003202 try {
Kristian Monsenfa52d172010-03-25 18:29:21 +00003203 webAddress = new WebAddress(url);
3204 webAddress.mPath = encodePath(webAddress.mPath);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003205 } catch (Exception e) {
Kristian Monsenfa52d172010-03-25 18:29:21 +00003206 // This only happens for very bad urls, we want to chatch the
3207 // exception here
3208 Log.e(LOGTAG, "Exception trying to parse url:" + url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003209 return;
3210 }
3211
3212 // XXX: Have to use the old url since the cookies were stored using the
3213 // old percent-encoded url.
3214 String cookies = CookieManager.getInstance().getCookie(url);
3215
3216 ContentValues values = new ContentValues();
Kristian Monsenfa52d172010-03-25 18:29:21 +00003217 values.put(Downloads.Impl.COLUMN_URI, webAddress.toString());
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08003218 values.put(Downloads.Impl.COLUMN_COOKIE_DATA, cookies);
3219 values.put(Downloads.Impl.COLUMN_USER_AGENT, userAgent);
3220 values.put(Downloads.Impl.COLUMN_NOTIFICATION_PACKAGE,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003221 getPackageName());
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08003222 values.put(Downloads.Impl.COLUMN_NOTIFICATION_CLASS,
Leon Scrogginsa563d092010-04-19 16:53:49 -04003223 OpenDownloadReceiver.class.getCanonicalName());
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08003224 values.put(Downloads.Impl.COLUMN_VISIBILITY,
3225 Downloads.Impl.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
3226 values.put(Downloads.Impl.COLUMN_MIME_TYPE, mimetype);
3227 values.put(Downloads.Impl.COLUMN_FILE_NAME_HINT, filename);
Kristian Monsenfa52d172010-03-25 18:29:21 +00003228 values.put(Downloads.Impl.COLUMN_DESCRIPTION, webAddress.mHost);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003229 if (contentLength > 0) {
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08003230 values.put(Downloads.Impl.COLUMN_TOTAL_BYTES, contentLength);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003231 }
3232 if (mimetype == null) {
3233 // We must have long pressed on a link or image to download it. We
3234 // are not sure of the mimetype in this case, so do a head request
3235 new FetchUrlMimeType(this).execute(values);
3236 } else {
3237 final Uri contentUri =
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08003238 getContentResolver().insert(Downloads.Impl.CONTENT_URI, values);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003239 }
Leon Scroggins9191a7f2010-03-18 14:44:44 -04003240 Toast.makeText(this, R.string.download_pending, Toast.LENGTH_SHORT)
3241 .show();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003242 }
3243
Grace Kloba22ac16e2009-10-07 18:00:23 -07003244 // -------------------------------------------------------------------------
3245
The Android Open Source Project0c908882009-03-03 19:32:16 -08003246 /**
3247 * Resets the lock icon. This method is called when we start a new load and
3248 * know the url to be loaded.
3249 */
3250 private void resetLockIcon(String url) {
3251 // Save the lock-icon state (we revert to it if the load gets cancelled)
Grace Kloba22ac16e2009-10-07 18:00:23 -07003252 mTabControl.getCurrentTab().resetLockIcon(url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003253 updateLockIconImage(LOCK_ICON_UNSECURE);
3254 }
3255
The Android Open Source Project0c908882009-03-03 19:32:16 -08003256 /**
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04003257 * Update the lock icon to correspond to our latest state.
3258 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003259 private void updateLockIconToLatest() {
Leon Scroggins91f65fc2010-06-29 13:52:39 -04003260 Tab t = mTabControl.getCurrentTab();
3261 if (t != null) {
3262 updateLockIconImage(t.getLockIconType());
3263 }
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04003264 }
3265
3266 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08003267 * Updates the lock-icon image in the title-bar.
3268 */
3269 private void updateLockIconImage(int lockIconType) {
3270 Drawable d = null;
3271 if (lockIconType == LOCK_ICON_SECURE) {
3272 d = mSecLockIcon;
3273 } else if (lockIconType == LOCK_ICON_MIXED) {
3274 d = mMixLockIcon;
3275 }
Leon Scroggins68579392009-09-15 15:31:54 -04003276 mTitleBar.setLock(d);
Michael Kolba2b2ba82010-08-04 17:54:03 -07003277 mFakeTitleBar.setLock(d);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003278 }
3279
3280 /**
3281 * Displays a page-info dialog.
3282 * @param tab The tab to show info about
3283 * @param fromShowSSLCertificateOnError The flag that indicates whether
3284 * this dialog was opened from the SSL-certificate-on-error dialog or
3285 * not. This is important, since we need to know whether to return to
3286 * the parent dialog or simply dismiss.
3287 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003288 private void showPageInfo(final Tab tab,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003289 final boolean fromShowSSLCertificateOnError) {
3290 final LayoutInflater factory = LayoutInflater
3291 .from(this);
3292
3293 final View pageInfoView = factory.inflate(R.layout.page_info, null);
3294
3295 final WebView view = tab.getWebView();
3296
3297 String url = null;
3298 String title = null;
3299
3300 if (view == null) {
3301 url = tab.getUrl();
3302 title = tab.getTitle();
3303 } else if (view == mTabControl.getCurrentWebView()) {
3304 // Use the cached title and url if this is the current WebView
3305 url = mUrl;
3306 title = mTitle;
3307 } else {
3308 url = view.getUrl();
3309 title = view.getTitle();
3310 }
3311
3312 if (url == null) {
3313 url = "";
3314 }
3315 if (title == null) {
3316 title = "";
3317 }
3318
3319 ((TextView) pageInfoView.findViewById(R.id.address)).setText(url);
3320 ((TextView) pageInfoView.findViewById(R.id.title)).setText(title);
3321
3322 mPageInfoView = tab;
Leon Scrogginsc7b92f82010-01-11 18:17:31 -05003323 mPageInfoFromShowSSLCertificateOnError = fromShowSSLCertificateOnError;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003324
3325 AlertDialog.Builder alertDialogBuilder =
3326 new AlertDialog.Builder(this)
3327 .setTitle(R.string.page_info).setIcon(android.R.drawable.ic_dialog_info)
3328 .setView(pageInfoView)
3329 .setPositiveButton(
3330 R.string.ok,
3331 new DialogInterface.OnClickListener() {
3332 public void onClick(DialogInterface dialog,
3333 int whichButton) {
3334 mPageInfoDialog = null;
3335 mPageInfoView = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003336
3337 // if we came here from the SSL error dialog
3338 if (fromShowSSLCertificateOnError) {
3339 // go back to the SSL error dialog
3340 showSSLCertificateOnError(
3341 mSSLCertificateOnErrorView,
3342 mSSLCertificateOnErrorHandler,
3343 mSSLCertificateOnErrorError);
3344 }
3345 }
3346 })
3347 .setOnCancelListener(
3348 new DialogInterface.OnCancelListener() {
3349 public void onCancel(DialogInterface dialog) {
3350 mPageInfoDialog = null;
3351 mPageInfoView = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003352
3353 // if we came here from the SSL error dialog
3354 if (fromShowSSLCertificateOnError) {
3355 // go back to the SSL error dialog
3356 showSSLCertificateOnError(
3357 mSSLCertificateOnErrorView,
3358 mSSLCertificateOnErrorHandler,
3359 mSSLCertificateOnErrorError);
3360 }
3361 }
3362 });
3363
3364 // if we have a main top-level page SSL certificate set or a certificate
3365 // error
3366 if (fromShowSSLCertificateOnError ||
3367 (view != null && view.getCertificate() != null)) {
3368 // add a 'View Certificate' button
3369 alertDialogBuilder.setNeutralButton(
3370 R.string.view_certificate,
3371 new DialogInterface.OnClickListener() {
3372 public void onClick(DialogInterface dialog,
3373 int whichButton) {
3374 mPageInfoDialog = null;
3375 mPageInfoView = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003376
3377 // if we came here from the SSL error dialog
3378 if (fromShowSSLCertificateOnError) {
3379 // go back to the SSL error dialog
3380 showSSLCertificateOnError(
3381 mSSLCertificateOnErrorView,
3382 mSSLCertificateOnErrorHandler,
3383 mSSLCertificateOnErrorError);
3384 } else {
3385 // otherwise, display the top-most certificate from
3386 // the chain
3387 if (view.getCertificate() != null) {
3388 showSSLCertificate(tab);
3389 }
3390 }
3391 }
3392 });
3393 }
3394
3395 mPageInfoDialog = alertDialogBuilder.show();
3396 }
3397
3398 /**
3399 * Displays the main top-level page SSL certificate dialog
3400 * (accessible from the Page-Info dialog).
3401 * @param tab The tab to show certificate for.
3402 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003403 private void showSSLCertificate(final Tab tab) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003404 final View certificateView =
3405 inflateCertificateView(tab.getWebView().getCertificate());
3406 if (certificateView == null) {
3407 return;
3408 }
3409
3410 LayoutInflater factory = LayoutInflater.from(this);
3411
3412 final LinearLayout placeholder =
3413 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3414
3415 LinearLayout ll = (LinearLayout) factory.inflate(
3416 R.layout.ssl_success, placeholder);
3417 ((TextView)ll.findViewById(R.id.success))
3418 .setText(R.string.ssl_certificate_is_valid);
3419
3420 mSSLCertificateView = tab;
3421 mSSLCertificateDialog =
3422 new AlertDialog.Builder(this)
3423 .setTitle(R.string.ssl_certificate).setIcon(
3424 R.drawable.ic_dialog_browser_certificate_secure)
3425 .setView(certificateView)
3426 .setPositiveButton(R.string.ok,
3427 new DialogInterface.OnClickListener() {
3428 public void onClick(DialogInterface dialog,
3429 int whichButton) {
3430 mSSLCertificateDialog = null;
3431 mSSLCertificateView = null;
3432
3433 showPageInfo(tab, false);
3434 }
3435 })
3436 .setOnCancelListener(
3437 new DialogInterface.OnCancelListener() {
3438 public void onCancel(DialogInterface dialog) {
3439 mSSLCertificateDialog = null;
3440 mSSLCertificateView = null;
3441
3442 showPageInfo(tab, false);
3443 }
3444 })
3445 .show();
3446 }
3447
3448 /**
3449 * Displays the SSL error certificate dialog.
3450 * @param view The target web-view.
3451 * @param handler The SSL error handler responsible for cancelling the
3452 * connection that resulted in an SSL error or proceeding per user request.
3453 * @param error The SSL error object.
3454 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003455 void showSSLCertificateOnError(
The Android Open Source Project0c908882009-03-03 19:32:16 -08003456 final WebView view, final SslErrorHandler handler, final SslError error) {
3457
3458 final View certificateView =
3459 inflateCertificateView(error.getCertificate());
3460 if (certificateView == null) {
3461 return;
3462 }
3463
3464 LayoutInflater factory = LayoutInflater.from(this);
3465
3466 final LinearLayout placeholder =
3467 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3468
3469 if (error.hasError(SslError.SSL_UNTRUSTED)) {
3470 LinearLayout ll = (LinearLayout)factory
3471 .inflate(R.layout.ssl_warning, placeholder);
3472 ((TextView)ll.findViewById(R.id.warning))
3473 .setText(R.string.ssl_untrusted);
3474 }
3475
3476 if (error.hasError(SslError.SSL_IDMISMATCH)) {
3477 LinearLayout ll = (LinearLayout)factory
3478 .inflate(R.layout.ssl_warning, placeholder);
3479 ((TextView)ll.findViewById(R.id.warning))
3480 .setText(R.string.ssl_mismatch);
3481 }
3482
3483 if (error.hasError(SslError.SSL_EXPIRED)) {
3484 LinearLayout ll = (LinearLayout)factory
3485 .inflate(R.layout.ssl_warning, placeholder);
3486 ((TextView)ll.findViewById(R.id.warning))
3487 .setText(R.string.ssl_expired);
3488 }
3489
3490 if (error.hasError(SslError.SSL_NOTYETVALID)) {
3491 LinearLayout ll = (LinearLayout)factory
3492 .inflate(R.layout.ssl_warning, placeholder);
3493 ((TextView)ll.findViewById(R.id.warning))
3494 .setText(R.string.ssl_not_yet_valid);
3495 }
3496
3497 mSSLCertificateOnErrorHandler = handler;
3498 mSSLCertificateOnErrorView = view;
3499 mSSLCertificateOnErrorError = error;
3500 mSSLCertificateOnErrorDialog =
3501 new AlertDialog.Builder(this)
3502 .setTitle(R.string.ssl_certificate).setIcon(
3503 R.drawable.ic_dialog_browser_certificate_partially_secure)
3504 .setView(certificateView)
3505 .setPositiveButton(R.string.ok,
3506 new DialogInterface.OnClickListener() {
3507 public void onClick(DialogInterface dialog,
3508 int whichButton) {
3509 mSSLCertificateOnErrorDialog = null;
3510 mSSLCertificateOnErrorView = null;
3511 mSSLCertificateOnErrorHandler = null;
3512 mSSLCertificateOnErrorError = null;
3513
Grace Kloba22ac16e2009-10-07 18:00:23 -07003514 view.getWebViewClient().onReceivedSslError(
3515 view, handler, error);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003516 }
3517 })
3518 .setNeutralButton(R.string.page_info_view,
3519 new DialogInterface.OnClickListener() {
3520 public void onClick(DialogInterface dialog,
3521 int whichButton) {
3522 mSSLCertificateOnErrorDialog = null;
3523
3524 // do not clear the dialog state: we will
3525 // need to show the dialog again once the
3526 // user is done exploring the page-info details
3527
3528 showPageInfo(mTabControl.getTabFromView(view),
3529 true);
3530 }
3531 })
3532 .setOnCancelListener(
3533 new DialogInterface.OnCancelListener() {
3534 public void onCancel(DialogInterface dialog) {
3535 mSSLCertificateOnErrorDialog = null;
3536 mSSLCertificateOnErrorView = null;
3537 mSSLCertificateOnErrorHandler = null;
3538 mSSLCertificateOnErrorError = null;
3539
Grace Kloba22ac16e2009-10-07 18:00:23 -07003540 view.getWebViewClient().onReceivedSslError(
3541 view, handler, error);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003542 }
3543 })
3544 .show();
3545 }
3546
3547 /**
3548 * Inflates the SSL certificate view (helper method).
3549 * @param certificate The SSL certificate.
3550 * @return The resultant certificate view with issued-to, issued-by,
3551 * issued-on, expires-on, and possibly other fields set.
3552 * If the input certificate is null, returns null.
3553 */
3554 private View inflateCertificateView(SslCertificate certificate) {
3555 if (certificate == null) {
3556 return null;
3557 }
3558
3559 LayoutInflater factory = LayoutInflater.from(this);
3560
3561 View certificateView = factory.inflate(
3562 R.layout.ssl_certificate, null);
3563
3564 // issued to:
3565 SslCertificate.DName issuedTo = certificate.getIssuedTo();
3566 if (issuedTo != null) {
3567 ((TextView) certificateView.findViewById(R.id.to_common))
3568 .setText(issuedTo.getCName());
3569 ((TextView) certificateView.findViewById(R.id.to_org))
3570 .setText(issuedTo.getOName());
3571 ((TextView) certificateView.findViewById(R.id.to_org_unit))
3572 .setText(issuedTo.getUName());
3573 }
3574
3575 // issued by:
3576 SslCertificate.DName issuedBy = certificate.getIssuedBy();
3577 if (issuedBy != null) {
3578 ((TextView) certificateView.findViewById(R.id.by_common))
3579 .setText(issuedBy.getCName());
3580 ((TextView) certificateView.findViewById(R.id.by_org))
3581 .setText(issuedBy.getOName());
3582 ((TextView) certificateView.findViewById(R.id.by_org_unit))
3583 .setText(issuedBy.getUName());
3584 }
3585
3586 // issued on:
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003587 String issuedOn = formatCertificateDate(
3588 certificate.getValidNotBeforeDate());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003589 ((TextView) certificateView.findViewById(R.id.issued_on))
3590 .setText(issuedOn);
3591
3592 // expires on:
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003593 String expiresOn = formatCertificateDate(
3594 certificate.getValidNotAfterDate());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003595 ((TextView) certificateView.findViewById(R.id.expires_on))
3596 .setText(expiresOn);
3597
3598 return certificateView;
3599 }
3600
3601 /**
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003602 * Formats the certificate date to a properly localized date string.
The Android Open Source Project0c908882009-03-03 19:32:16 -08003603 * @return Properly localized version of the certificate date string and
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003604 * the "" if it fails to localize.
The Android Open Source Project0c908882009-03-03 19:32:16 -08003605 */
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003606 private String formatCertificateDate(Date certificateDate) {
3607 if (certificateDate == null) {
3608 return "";
The Android Open Source Project0c908882009-03-03 19:32:16 -08003609 }
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003610 String formattedDate = DateFormat.getDateFormat(this).format(certificateDate);
3611 if (formattedDate == null) {
3612 return "";
3613 }
3614 return formattedDate;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003615 }
3616
3617 /**
3618 * Displays an http-authentication dialog.
3619 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003620 void showHttpAuthentication(final HttpAuthHandler handler,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003621 final String host, final String realm, final String title,
3622 final String name, final String password, int focusId) {
3623 LayoutInflater factory = LayoutInflater.from(this);
3624 final View v = factory
3625 .inflate(R.layout.http_authentication, null);
3626 if (name != null) {
3627 ((EditText) v.findViewById(R.id.username_edit)).setText(name);
3628 }
3629 if (password != null) {
3630 ((EditText) v.findViewById(R.id.password_edit)).setText(password);
3631 }
3632
3633 String titleText = title;
3634 if (titleText == null) {
3635 titleText = getText(R.string.sign_in_to).toString().replace(
3636 "%s1", host).replace("%s2", realm);
3637 }
3638
3639 mHttpAuthHandler = handler;
3640 AlertDialog dialog = new AlertDialog.Builder(this)
3641 .setTitle(titleText)
3642 .setIcon(android.R.drawable.ic_dialog_alert)
3643 .setView(v)
3644 .setPositiveButton(R.string.action,
3645 new DialogInterface.OnClickListener() {
3646 public void onClick(DialogInterface dialog,
3647 int whichButton) {
3648 String nm = ((EditText) v
3649 .findViewById(R.id.username_edit))
3650 .getText().toString();
3651 String pw = ((EditText) v
3652 .findViewById(R.id.password_edit))
3653 .getText().toString();
3654 BrowserActivity.this.setHttpAuthUsernamePassword
3655 (host, realm, nm, pw);
3656 handler.proceed(nm, pw);
3657 mHttpAuthenticationDialog = null;
3658 mHttpAuthHandler = null;
3659 }})
3660 .setNegativeButton(R.string.cancel,
3661 new DialogInterface.OnClickListener() {
3662 public void onClick(DialogInterface dialog,
3663 int whichButton) {
3664 handler.cancel();
3665 BrowserActivity.this.resetTitleAndRevertLockIcon();
3666 mHttpAuthenticationDialog = null;
3667 mHttpAuthHandler = null;
3668 }})
3669 .setOnCancelListener(new DialogInterface.OnCancelListener() {
3670 public void onCancel(DialogInterface dialog) {
3671 handler.cancel();
3672 BrowserActivity.this.resetTitleAndRevertLockIcon();
3673 mHttpAuthenticationDialog = null;
3674 mHttpAuthHandler = null;
3675 }})
3676 .create();
3677 // Make the IME appear when the dialog is displayed if applicable.
3678 dialog.getWindow().setSoftInputMode(
3679 WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
3680 dialog.show();
3681 if (focusId != 0) {
3682 dialog.findViewById(focusId).requestFocus();
3683 } else {
3684 v.findViewById(R.id.username_edit).requestFocus();
3685 }
3686 mHttpAuthenticationDialog = dialog;
3687 }
3688
3689 public int getProgress() {
3690 WebView w = mTabControl.getCurrentWebView();
3691 if (w != null) {
3692 return w.getProgress();
3693 } else {
3694 return 100;
3695 }
3696 }
3697
3698 /**
3699 * Set HTTP authentication password.
3700 *
3701 * @param host The host for the password
3702 * @param realm The realm for the password
3703 * @param username The username for the password. If it is null, it means
3704 * password can't be saved.
3705 * @param password The password
3706 */
3707 public void setHttpAuthUsernamePassword(String host, String realm,
3708 String username,
3709 String password) {
Steve Block95a53b22010-03-25 17:24:58 +00003710 WebView w = getTopWindow();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003711 if (w != null) {
3712 w.setHttpAuthUsernamePassword(host, realm, username, password);
3713 }
3714 }
3715
3716 /**
3717 * connectivity manager says net has come or gone... inform the user
3718 * @param up true if net has come up, false if net has gone down
3719 */
3720 public void onNetworkToggle(boolean up) {
3721 if (up == mIsNetworkUp) {
3722 return;
3723 } else if (up) {
3724 mIsNetworkUp = true;
3725 if (mAlertDialog != null) {
3726 mAlertDialog.cancel();
3727 mAlertDialog = null;
3728 }
3729 } else {
3730 mIsNetworkUp = false;
Patrick Scotteb6ab2a2009-09-16 10:00:17 -04003731 if (mInLoad) {
3732 createAndShowNetworkDialog();
3733 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003734 }
3735 WebView w = mTabControl.getCurrentWebView();
3736 if (w != null) {
3737 w.setNetworkAvailable(up);
3738 }
3739 }
3740
Grace Kloba22ac16e2009-10-07 18:00:23 -07003741 boolean isNetworkUp() {
3742 return mIsNetworkUp;
3743 }
3744
Patrick Scotteb6ab2a2009-09-16 10:00:17 -04003745 // This method shows the network dialog alerting the user that the net is
3746 // down. It will only show the dialog if mAlertDialog is null.
3747 private void createAndShowNetworkDialog() {
3748 if (mAlertDialog == null) {
3749 mAlertDialog = new AlertDialog.Builder(this)
3750 .setTitle(R.string.loadSuspendedTitle)
3751 .setMessage(R.string.loadSuspended)
3752 .setPositiveButton(R.string.ok, null)
3753 .show();
3754 }
3755 }
3756
The Android Open Source Project0c908882009-03-03 19:32:16 -08003757 @Override
3758 protected void onActivityResult(int requestCode, int resultCode,
3759 Intent intent) {
Grace Klobabb394f32009-11-19 10:26:37 -08003760 if (getTopWindow() == null) return;
3761
The Android Open Source Project0c908882009-03-03 19:32:16 -08003762 switch (requestCode) {
3763 case COMBO_PAGE:
3764 if (resultCode == RESULT_OK && intent != null) {
3765 String data = intent.getAction();
3766 Bundle extras = intent.getExtras();
Michael Kolb300b7f02010-08-25 13:47:24 -07003767 if (extras != null &&
3768 extras.getBoolean(
3769 CombinedBookmarkHistoryActivity.EXTRA_OPEN_NEW_WINDOW,
3770 false)) {
Michael Kolb68792c82010-08-09 16:39:18 -07003771 openTab(data, false);
3772 } else if ((extras != null) &&
3773 extras.getBoolean(CombinedBookmarkHistoryActivity.NEWTAB_MODE)) {
3774 openTab(data, true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003775 } else {
Michael Kolb68792c82010-08-09 16:39:18 -07003776 final Tab currentTab = mTabControl.getCurrentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04003777 dismissSubWindow(currentTab);
3778 if (data != null && data.length() != 0) {
Leon Scroggins92472e82010-02-17 16:32:28 -05003779 loadUrl(getTopWindow(), data);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003780 }
3781 }
Michael Kolb3f65c382010-08-20 15:31:16 -07003782 } else if (resultCode == RESULT_CANCELED) {
3783 if (intent != null) {
3784 float evtx = intent.getFloatExtra(CombinedBookmarkHistoryActivity.EVT_X, -1);
3785 float evty = intent.getFloatExtra(CombinedBookmarkHistoryActivity.EVT_Y, -1);
3786 long now = System.currentTimeMillis();
3787 MotionEvent evt = MotionEvent.obtain(now, now,
3788 MotionEvent.ACTION_DOWN, evtx, evty, 0);
3789 dispatchTouchEvent(evt);
3790 MotionEvent up = MotionEvent.obtain(evt);
3791 up.setAction(MotionEvent.ACTION_UP);
3792 dispatchTouchEvent(up);
3793 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003794 }
Leon Scrogginsfde97462010-01-11 13:06:21 -05003795 // Deliberately fall through to PREFERENCES_PAGE, since the
3796 // same extra may be attached to the COMBO_PAGE
3797 case PREFERENCES_PAGE:
3798 if (resultCode == RESULT_OK && intent != null) {
3799 String action = intent.getStringExtra(Intent.EXTRA_TEXT);
3800 if (BrowserSettings.PREF_CLEAR_HISTORY.equals(action)) {
3801 mTabControl.removeParentChildRelationShips();
3802 }
3803 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003804 break;
Leon Scroggins8d5fa432009-10-02 15:55:59 -04003805 // Choose a file from the file picker.
3806 case FILE_SELECTED:
3807 if (null == mUploadMessage) break;
3808 Uri result = intent == null || resultCode != RESULT_OK ? null
3809 : intent.getData();
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003810
3811 // As we ask the camera to save the result of the user taking
3812 // a picture, the camera application does not return anything other
3813 // than RESULT_OK. So we need to check whether the file we expected
3814 // was written to disk in the in the case that we
3815 // did not get an intent returned but did get a RESULT_OK. If it was,
3816 // we assume that this result has came back from the camera.
3817 if (result == null && intent == null && resultCode == RESULT_OK) {
3818 File cameraFile = new File(mCameraFilePath);
3819 if (cameraFile.exists()) {
3820 result = Uri.fromFile(cameraFile);
Ben Murdoch07d34732010-05-27 18:34:46 +01003821 // Broadcast to the media scanner that we have a new photo
3822 // so it will be added into the gallery for the user.
3823 sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, result));
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003824 }
3825 }
Leon Scroggins8d5fa432009-10-02 15:55:59 -04003826 mUploadMessage.onReceiveValue(result);
3827 mUploadMessage = null;
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003828 mCameraFilePath = null;
Leon Scroggins8d5fa432009-10-02 15:55:59 -04003829 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003830 default:
3831 break;
3832 }
Leon Scroggins30444232009-09-04 18:36:20 -04003833 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003834 }
3835
3836 /*
3837 * This method is called as a result of the user selecting the options
Leon Scrogginsf08809b2010-01-21 09:27:46 -05003838 * menu to see the download window. It shows the download window on top of
3839 * the current window.
The Android Open Source Project0c908882009-03-03 19:32:16 -08003840 */
Leon Scrogginsf08809b2010-01-21 09:27:46 -05003841 private void viewDownloads(Uri downloadRecord) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003842 Intent intent = new Intent(this,
3843 BrowserDownloadPage.class);
3844 intent.setData(downloadRecord);
Grace Kloba22ac16e2009-10-07 18:00:23 -07003845 startActivityForResult(intent, BrowserActivity.DOWNLOAD_PAGE);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003846
3847 }
3848
Ben Murdocheecb4e62010-07-06 16:30:38 +01003849 /* package*/ void promptAddOrInstallBookmark() {
3850 final Tab current = mTabControl.getCurrentTab();
3851 Resources resources = getResources();
3852 CharSequence[] choices = {
3853 resources.getString(R.string.save_to_bookmarks),
3854 resources.getString(R.string.create_shortcut_bookmark)
3855 };
3856
3857 AlertDialog.Builder builder = new AlertDialog.Builder(this);
3858 builder.setTitle(R.string.add_new_bookmark);
3859 builder.setItems(choices, new DialogInterface.OnClickListener() {
3860 public void onClick(DialogInterface dialog, int item) {
3861 if (item == 0) {
3862 bookmarkCurrentPage();
3863 } else if (item == 1) {
3864 current.populatePickerData();
3865 String touchIconUrl = mTabControl.getCurrentWebView().getTouchIconUrl();
3866 if (touchIconUrl != null) {
3867 // Download the touch icon for this site then save it to the
3868 // homescreen.
3869 Bundle b = new Bundle();
3870 b.putString("url", current.getUrl());
3871 b.putString("title", current.getTitle());
3872 b.putParcelable("favicon", current.getFavicon());
3873 Message msg = mHandler.obtainMessage(TOUCH_ICON_DOWNLOADED);
3874 msg.setData(b);
Ben Murdochccb5de02010-07-19 18:38:17 +01003875 new DownloadTouchIcon(BrowserActivity.this, msg,
Ben Murdocheecb4e62010-07-06 16:30:38 +01003876 mTabControl.getCurrentWebView().getSettings()
3877 .getUserAgentString()).execute(touchIconUrl);
3878 } else {
3879 // add to homescreen, can do it immediately as there is no touch
3880 // icon.
3881 showSaveToHomescreenDialog(current.getUrl(), current.getTitle(),
3882 null, current.getFavicon());
3883 }
3884 }
3885 }
3886 });
3887 builder.create().show();
3888 }
3889
Leon Scroggins160a7e72009-08-14 18:28:01 -04003890 /**
3891 * Open the Go page.
3892 * @param startWithHistory If true, open starting on the history tab.
3893 * Otherwise, start with the bookmarks tab.
Leon Scroggins160a7e72009-08-14 18:28:01 -04003894 */
Michael Kolb68792c82010-08-09 16:39:18 -07003895 /* package */ void bookmarksOrHistoryPicker(boolean startWithHistory, boolean newTabMode) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003896 WebView current = mTabControl.getCurrentWebView();
3897 if (current == null) {
3898 return;
3899 }
3900 Intent intent = new Intent(this,
3901 CombinedBookmarkHistoryActivity.class);
3902 String title = current.getTitle();
3903 String url = current.getUrl();
Ben Murdoch87cc65d2010-06-29 20:34:10 +01003904 Bitmap thumbnail = createScreenshot(current, getDesiredThumbnailWidth(this),
3905 getDesiredThumbnailHeight(this));
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01003906
The Android Open Source Project0c908882009-03-03 19:32:16 -08003907 // Just in case the user opens bookmarks before a page finishes loading
3908 // so the current history item, and therefore the page, is null.
3909 if (null == url) {
3910 url = mLastEnteredUrl;
3911 // This can happen.
3912 if (null == url) {
3913 url = mSettings.getHomePage();
3914 }
3915 }
3916 // In case the web page has not yet received its associated title.
3917 if (title == null) {
3918 title = url;
3919 }
3920 intent.putExtra("title", title);
3921 intent.putExtra("url", url);
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01003922 intent.putExtra("thumbnail", thumbnail);
Leon Scroggins30444232009-09-04 18:36:20 -04003923 // Disable opening in a new window if we have maxed out the windows
Grace Kloba22ac16e2009-10-07 18:00:23 -07003924 intent.putExtra("disable_new_window", !mTabControl.canCreateNewTab());
Patrick Scott3918d442009-08-04 13:22:29 -04003925 intent.putExtra("touch_icon_url", current.getTouchIconUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003926 if (startWithHistory) {
Jeff Hamilton64144e42010-08-18 16:31:59 -05003927 intent.putExtra(CombinedBookmarkHistoryActivity.STARTING_FRAGMENT,
3928 CombinedBookmarkHistoryActivity.FRAGMENT_ID_HISTORY);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003929 }
Michael Kolb300b7f02010-08-25 13:47:24 -07003930 intent.putExtra(CombinedBookmarkHistoryActivity.NEWTAB_MODE, newTabMode);
Michael Kolb0998b0a2010-08-23 17:45:35 -07003931 int top = -1;
3932 int height = -1;
Michael Kolb3f65c382010-08-20 15:31:16 -07003933 if (mXLargeScreenSize) {
3934 showFakeTitleBar();
3935 int titleBarHeight = ((TitleBarXLarge)mFakeTitleBar).getHeightWithoutProgress();
Michael Kolb0998b0a2010-08-23 17:45:35 -07003936 top = mTabBar.getBottom() + titleBarHeight;
3937 height = getTopWindow().getHeight() - titleBarHeight;
Michael Kolb68792c82010-08-09 16:39:18 -07003938 }
Michael Kolb0998b0a2010-08-23 17:45:35 -07003939 intent.putExtra(CombinedBookmarkHistoryActivity.EXTRA_TOP, top);
3940 intent.putExtra(CombinedBookmarkHistoryActivity.EXTRA_HEIGHT, height);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003941 startActivityForResult(intent, COMBO_PAGE);
3942 }
3943
Ben Murdocheecb4e62010-07-06 16:30:38 +01003944 private void showSaveToHomescreenDialog(String url, String title, Bitmap touchIcon,
3945 Bitmap favicon) {
3946 Intent intent = new Intent(this, SaveToHomescreenDialog.class);
3947
3948 // Just in case the user tries to save before a page finishes loading
3949 // so the current history item, and therefore the page, is null.
3950 if (null == url) {
3951 url = mLastEnteredUrl;
3952 // This can happen.
3953 if (null == url) {
3954 url = mSettings.getHomePage();
3955 }
3956 }
3957
3958 // In case the web page has not yet received its associated title.
3959 if (title == null) {
3960 title = url;
3961 }
3962
3963 intent.putExtra("title", title);
3964 intent.putExtra("url", url);
3965 intent.putExtra("favicon", favicon);
3966 intent.putExtra("touchIcon", touchIcon);
3967 startActivity(intent);
3968 }
3969
3970
The Android Open Source Project0c908882009-03-03 19:32:16 -08003971 // Called when loading from context menu or LOAD_URL message
Leon Scroggins92472e82010-02-17 16:32:28 -05003972 private void loadUrlFromContext(WebView view, String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003973 // In case the user enters nothing.
3974 if (url != null && url.length() != 0 && view != null) {
3975 url = smartUrlFilter(url);
Grace Kloba22ac16e2009-10-07 18:00:23 -07003976 if (!view.getWebViewClient().shouldOverrideUrlLoading(view, url)) {
Leon Scroggins92472e82010-02-17 16:32:28 -05003977 loadUrl(view, url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003978 }
3979 }
3980 }
3981
Leon Scroggins92472e82010-02-17 16:32:28 -05003982 /**
3983 * Load the URL into the given WebView and update the title bar
3984 * to reflect the new load. Call this instead of WebView.loadUrl
3985 * directly.
3986 * @param view The WebView used to load url.
3987 * @param url The URL to load.
3988 */
3989 private void loadUrl(WebView view, String url) {
3990 updateTitleBarForNewLoad(view, url);
3991 view.loadUrl(url);
3992 }
3993
3994 /**
3995 * Load UrlData into a Tab and update the title bar to reflect the new
3996 * load. Call this instead of UrlData.loadIn directly.
3997 * @param t The Tab used to load.
3998 * @param data The UrlData being loaded.
3999 */
4000 private void loadUrlDataIn(Tab t, UrlData data) {
4001 updateTitleBarForNewLoad(t.getWebView(), data.mUrl);
4002 data.loadIn(t);
4003 }
4004
4005 /**
4006 * If the WebView is the top window, update the title bar to reflect
4007 * loading the new URL. i.e. set its text, clear the favicon (which
4008 * will be set once the page begins loading), and set the progress to
4009 * INITIAL_PROGRESS to show that the page has begun to load. Called
4010 * by loadUrl and loadUrlDataIn.
4011 * @param view The WebView that is starting a load.
4012 * @param url The URL that is being loaded.
4013 */
4014 private void updateTitleBarForNewLoad(WebView view, String url) {
4015 if (view == getTopWindow()) {
4016 setUrlTitle(url, null);
4017 setFavicon(null);
4018 onProgressChanged(view, INITIAL_PROGRESS);
4019 }
4020 }
4021
The Android Open Source Project0c908882009-03-03 19:32:16 -08004022 private String smartUrlFilter(Uri inUri) {
4023 if (inUri != null) {
4024 return smartUrlFilter(inUri.toString());
4025 }
4026 return null;
4027 }
4028
Feng Qianb34f87a2009-03-24 21:27:26 -07004029 protected static final Pattern ACCEPTED_URI_SCHEMA = Pattern.compile(
The Android Open Source Project0c908882009-03-03 19:32:16 -08004030 "(?i)" + // switch on case insensitive matching
4031 "(" + // begin group for schema
4032 "(?:http|https|file):\\/\\/" +
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004033 "|(?:inline|data|about|content|javascript):" +
The Android Open Source Project0c908882009-03-03 19:32:16 -08004034 ")" +
4035 "(.*)" );
4036
4037 /**
4038 * Attempts to determine whether user input is a URL or search
4039 * terms. Anything with a space is passed to search.
4040 *
4041 * Converts to lowercase any mistakenly uppercased schema (i.e.,
4042 * "Http://" converts to "http://"
4043 *
4044 * @return Original or modified URL
4045 *
4046 */
4047 String smartUrlFilter(String url) {
4048
4049 String inUrl = url.trim();
4050 boolean hasSpace = inUrl.indexOf(' ') != -1;
4051
4052 Matcher matcher = ACCEPTED_URI_SCHEMA.matcher(inUrl);
4053 if (matcher.matches()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08004054 // force scheme to lowercase
4055 String scheme = matcher.group(1);
4056 String lcScheme = scheme.toLowerCase();
4057 if (!lcScheme.equals(scheme)) {
Mitsuru Oshima123ecfb2009-05-18 19:11:14 -07004058 inUrl = lcScheme + matcher.group(2);
4059 }
4060 if (hasSpace) {
4061 inUrl = inUrl.replace(" ", "%20");
The Android Open Source Project0c908882009-03-03 19:32:16 -08004062 }
4063 return inUrl;
4064 }
4065 if (hasSpace) {
Satish Sampath565505b2009-05-29 15:37:27 +01004066 // FIXME: Is this the correct place to add to searches?
4067 // what if someone else calls this function?
4068 int shortcut = parseUrlShortcut(inUrl);
4069 if (shortcut != SHORTCUT_INVALID) {
4070 Browser.addSearchUrl(mResolver, inUrl);
4071 String query = inUrl.substring(2);
4072 switch (shortcut) {
4073 case SHORTCUT_GOOGLE_SEARCH:
Grace Kloba47fdfdb2009-06-30 11:15:34 -07004074 return URLUtil.composeSearchUrl(query, QuickSearch_G, QUERY_PLACE_HOLDER);
Satish Sampath565505b2009-05-29 15:37:27 +01004075 case SHORTCUT_WIKIPEDIA_SEARCH:
4076 return URLUtil.composeSearchUrl(query, QuickSearch_W, QUERY_PLACE_HOLDER);
4077 case SHORTCUT_DICTIONARY_SEARCH:
4078 return URLUtil.composeSearchUrl(query, QuickSearch_D, QUERY_PLACE_HOLDER);
4079 case SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH:
The Android Open Source Project0c908882009-03-03 19:32:16 -08004080 // FIXME: we need location in this case
Satish Sampath565505b2009-05-29 15:37:27 +01004081 return URLUtil.composeSearchUrl(query, QuickSearch_L, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004082 }
4083 }
4084 } else {
Dan Egnor5ee906c2009-11-18 12:11:49 -08004085 if (Patterns.WEB_URL.matcher(inUrl).matches()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08004086 return URLUtil.guessUrl(inUrl);
4087 }
4088 }
4089
4090 Browser.addSearchUrl(mResolver, inUrl);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07004091 return URLUtil.composeSearchUrl(inUrl, QuickSearch_G, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004092 }
4093
Ben Murdochbff2d602009-07-01 20:19:05 +01004094 /* package */ void setShouldShowErrorConsole(boolean flag) {
4095 if (flag == mShouldShowErrorConsole) {
4096 // Nothing to do.
4097 return;
4098 }
4099
4100 mShouldShowErrorConsole = flag;
4101
Grace Kloba22ac16e2009-10-07 18:00:23 -07004102 ErrorConsoleView errorConsole = mTabControl.getCurrentTab()
4103 .getErrorConsole(true);
Ben Murdochbff2d602009-07-01 20:19:05 +01004104
4105 if (flag) {
4106 // Setting the show state of the console will cause it's the layout to be inflated.
4107 if (errorConsole.numberOfErrors() > 0) {
4108 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
4109 } else {
4110 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
4111 }
4112
4113 // Now we can add it to the main view.
4114 mErrorConsoleContainer.addView(errorConsole,
Romain Guy15b8ec62010-01-08 15:06:43 -08004115 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
Ben Murdochbff2d602009-07-01 20:19:05 +01004116 ViewGroup.LayoutParams.WRAP_CONTENT));
4117 } else {
4118 mErrorConsoleContainer.removeView(errorConsole);
4119 }
4120
4121 }
4122
Grace Kloba22ac16e2009-10-07 18:00:23 -07004123 boolean shouldShowErrorConsole() {
4124 return mShouldShowErrorConsole;
4125 }
4126
Andrei Popescu163ab742009-10-20 17:58:23 +01004127 private void setStatusBarVisibility(boolean visible) {
4128 int flag = visible ? 0 : WindowManager.LayoutParams.FLAG_FULLSCREEN;
4129 getWindow().setFlags(flag, WindowManager.LayoutParams.FLAG_FULLSCREEN);
4130 }
4131
Andrei Popescu56199cc2010-01-12 22:39:16 +00004132
4133 private void sendNetworkType(String type, String subtype) {
4134 WebView w = mTabControl.getCurrentWebView();
4135 if (w != null) {
4136 w.setNetworkType(type, subtype);
4137 }
4138 }
4139
Grace Klobaeb6eef42009-09-15 17:56:32 -07004140 final static int LOCK_ICON_UNSECURE = 0;
4141 final static int LOCK_ICON_SECURE = 1;
4142 final static int LOCK_ICON_MIXED = 2;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004143
The Android Open Source Project0c908882009-03-03 19:32:16 -08004144 private BrowserSettings mSettings;
4145 private TabControl mTabControl;
4146 private ContentResolver mResolver;
4147 private FrameLayout mContentView;
Andrei Popescuadc008d2009-06-26 14:11:30 +01004148 private View mCustomView;
4149 private FrameLayout mCustomViewContainer;
Andrei Popescuc9b55562009-07-07 10:51:15 +01004150 private WebChromeClient.CustomViewCallback mCustomViewCallback;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004151
4152 // FIXME, temp address onPrepareMenu performance problem. When we move everything out of
4153 // view, we should rewrite this.
4154 private int mCurrentMenuState = 0;
4155 private int mMenuState = R.id.MAIN_MENU;
Andrei Popescuadc008d2009-06-26 14:11:30 +01004156 private int mOldMenuState = EMPTY_MENU;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004157 private static final int EMPTY_MENU = -1;
4158 private Menu mMenu;
4159
The Android Open Source Project0c908882009-03-03 19:32:16 -08004160 // Used to prevent chording to result in firing two shortcuts immediately
4161 // one after another. Fixes bug 1211714.
4162 boolean mCanChord;
4163
4164 private boolean mInLoad;
4165 private boolean mIsNetworkUp;
Ben Murdochb7cc8b42009-09-28 10:59:09 +01004166 private boolean mDidStopLoad;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004167
Cary Clark1f10cbf2010-03-22 11:45:23 -04004168 /* package */ boolean mActivityInPause = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004169
4170 private boolean mMenuIsDown;
4171
The Android Open Source Project0c908882009-03-03 19:32:16 -08004172 private static boolean mInTrace;
4173
4174 // Performance probe
4175 private static final int[] SYSTEM_CPU_FORMAT = new int[] {
4176 Process.PROC_SPACE_TERM | Process.PROC_COMBINE,
4177 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 1: user time
4178 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 2: nice time
4179 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 3: sys time
4180 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 4: idle time
4181 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 5: iowait time
4182 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 6: irq time
4183 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG // 7: softirq time
4184 };
4185
4186 private long mStart;
4187 private long mProcessStart;
4188 private long mUserStart;
4189 private long mSystemStart;
4190 private long mIdleStart;
4191 private long mIrqStart;
4192
4193 private long mUiStart;
4194
4195 private Drawable mMixLockIcon;
4196 private Drawable mSecLockIcon;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004197
4198 /* hold a ref so we can auto-cancel if necessary */
4199 private AlertDialog mAlertDialog;
4200
The Android Open Source Project0c908882009-03-03 19:32:16 -08004201 // The up-to-date URL and title (these can be different from those stored
4202 // in WebView, since it takes some time for the information in WebView to
4203 // get updated)
4204 private String mUrl;
4205 private String mTitle;
4206
4207 // As PageInfo has different style for landscape / portrait, we have
4208 // to re-open it when configuration changed
4209 private AlertDialog mPageInfoDialog;
Grace Kloba22ac16e2009-10-07 18:00:23 -07004210 private Tab mPageInfoView;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004211 // If the Page-Info dialog is launched from the SSL-certificate-on-error
4212 // dialog, we should not just dismiss it, but should get back to the
4213 // SSL-certificate-on-error dialog. This flag is used to store this state
Leon Scrogginsc7b92f82010-01-11 18:17:31 -05004214 private boolean mPageInfoFromShowSSLCertificateOnError;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004215
4216 // as SSLCertificateOnError has different style for landscape / portrait,
4217 // we have to re-open it when configuration changed
4218 private AlertDialog mSSLCertificateOnErrorDialog;
4219 private WebView mSSLCertificateOnErrorView;
4220 private SslErrorHandler mSSLCertificateOnErrorHandler;
4221 private SslError mSSLCertificateOnErrorError;
4222
4223 // as SSLCertificate has different style for landscape / portrait, we
4224 // have to re-open it when configuration changed
4225 private AlertDialog mSSLCertificateDialog;
Grace Kloba22ac16e2009-10-07 18:00:23 -07004226 private Tab mSSLCertificateView;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004227
4228 // as HttpAuthentication has different style for landscape / portrait, we
4229 // have to re-open it when configuration changed
4230 private AlertDialog mHttpAuthenticationDialog;
4231 private HttpAuthHandler mHttpAuthHandler;
4232
4233 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_PARAMS =
4234 new FrameLayout.LayoutParams(
Romain Guy15b8ec62010-01-08 15:06:43 -08004235 ViewGroup.LayoutParams.MATCH_PARENT,
4236 ViewGroup.LayoutParams.MATCH_PARENT);
Andrei Popescuadc008d2009-06-26 14:11:30 +01004237 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_GRAVITY_CENTER =
4238 new FrameLayout.LayoutParams(
Romain Guy15b8ec62010-01-08 15:06:43 -08004239 ViewGroup.LayoutParams.MATCH_PARENT,
4240 ViewGroup.LayoutParams.MATCH_PARENT,
Andrei Popescuadc008d2009-06-26 14:11:30 +01004241 Gravity.CENTER);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07004242 // Google search
4243 final static String QuickSearch_G = "http://www.google.com/m?q=%s";
The Android Open Source Project0c908882009-03-03 19:32:16 -08004244 // Wikipedia search
4245 final static String QuickSearch_W = "http://en.wikipedia.org/w/index.php?search=%s&go=Go";
4246 // Dictionary search
4247 final static String QuickSearch_D = "http://dictionary.reference.com/search?q=%s";
4248 // Google Mobile Local search
4249 final static String QuickSearch_L = "http://www.google.com/m/search?site=local&q=%s&near=mountain+view";
4250
4251 final static String QUERY_PLACE_HOLDER = "%s";
4252
4253 // "source" parameter for Google search through search key
4254 final static String GOOGLE_SEARCH_SOURCE_SEARCHKEY = "browser-key";
4255 // "source" parameter for Google search through goto menu
4256 final static String GOOGLE_SEARCH_SOURCE_GOTO = "browser-goto";
4257 // "source" parameter for Google search through simplily type
4258 final static String GOOGLE_SEARCH_SOURCE_TYPE = "browser-type";
4259 // "source" parameter for Google search suggested by the browser
4260 final static String GOOGLE_SEARCH_SOURCE_SUGGEST = "browser-suggest";
4261 // "source" parameter for Google search from unknown source
4262 final static String GOOGLE_SEARCH_SOURCE_UNKNOWN = "unknown";
4263
4264 private final static String LOGTAG = "browser";
4265
The Android Open Source Project0c908882009-03-03 19:32:16 -08004266 private String mLastEnteredUrl;
4267
4268 private PowerManager.WakeLock mWakeLock;
4269 private final static int WAKELOCK_TIMEOUT = 5 * 60 * 1000; // 5 minutes
4270
4271 private Toast mStopToast;
4272
Leon Scroggins571b3762010-05-26 10:25:01 -04004273 private TitleBarBase mTitleBar;
Michael Kolba2b2ba82010-08-04 17:54:03 -07004274 private TabBar mTabBar;
Leon Scroggins81db3662009-06-04 17:45:11 -04004275
Ben Murdochbff2d602009-07-01 20:19:05 +01004276 private LinearLayout mErrorConsoleContainer = null;
4277 private boolean mShouldShowErrorConsole = false;
4278
The Android Open Source Project0c908882009-03-03 19:32:16 -08004279 // As the ids are dynamically created, we can't guarantee that they will
4280 // be in sequence, so this static array maps ids to a window number.
4281 final static private int[] WINDOW_SHORTCUT_ID_ARRAY =
4282 { R.id.window_one_menu_id, R.id.window_two_menu_id, R.id.window_three_menu_id,
4283 R.id.window_four_menu_id, R.id.window_five_menu_id, R.id.window_six_menu_id,
4284 R.id.window_seven_menu_id, R.id.window_eight_menu_id };
4285
4286 // monitor platform changes
4287 private IntentFilter mNetworkStateChangedFilter;
4288 private BroadcastReceiver mNetworkStateIntentReceiver;
4289
Bjorn Bringerta7611812010-03-24 11:12:02 +00004290 private SystemAllowGeolocationOrigins mSystemAllowGeolocationOrigins;
4291
The Android Open Source Project0c908882009-03-03 19:32:16 -08004292 // activity requestCode
Nicolas Roard78a98e42009-05-11 13:34:17 +01004293 final static int COMBO_PAGE = 1;
4294 final static int DOWNLOAD_PAGE = 2;
4295 final static int PREFERENCES_PAGE = 3;
Leon Scroggins8d5fa432009-10-02 15:55:59 -04004296 final static int FILE_SELECTED = 4;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004297
Andrei Popescu540035d2009-09-18 18:59:20 +01004298 // the default <video> poster
4299 private Bitmap mDefaultVideoPoster;
4300 // the video progress view
4301 private View mVideoProgressView;
4302
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004303 /**
4304 * A UrlData class to abstract how the content will be set to WebView.
4305 * This base class uses loadUrl to show the content.
4306 */
Leon Scroggins6eac63e2010-03-15 18:19:14 -04004307 /* package */ static class UrlData {
Grace Kloba068e48b2010-01-26 18:11:27 -08004308 final String mUrl;
4309 final Map<String, String> mHeaders;
Leon Scroggins58d56c62010-01-28 15:12:40 -05004310 final Intent mVoiceIntent;
Grace Kloba60e095c2009-06-16 11:50:55 -07004311
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004312 UrlData(String url) {
4313 this.mUrl = url;
Grace Kloba068e48b2010-01-26 18:11:27 -08004314 this.mHeaders = null;
Leon Scroggins58d56c62010-01-28 15:12:40 -05004315 this.mVoiceIntent = null;
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004316 }
Grace Kloba60e095c2009-06-16 11:50:55 -07004317
Leon Scroggins58d56c62010-01-28 15:12:40 -05004318 UrlData(String url, Map<String, String> headers, Intent intent) {
Grace Kloba068e48b2010-01-26 18:11:27 -08004319 this.mUrl = url;
4320 this.mHeaders = headers;
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -05004321 if (RecognizerResultsIntent.ACTION_VOICE_SEARCH_RESULTS
4322 .equals(intent.getAction())) {
Leon Scroggins58d56c62010-01-28 15:12:40 -05004323 this.mVoiceIntent = intent;
4324 } else {
4325 this.mVoiceIntent = null;
4326 }
Grace Kloba60e095c2009-06-16 11:50:55 -07004327 }
4328
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004329 boolean isEmpty() {
Leon Scroggins58d56c62010-01-28 15:12:40 -05004330 return mVoiceIntent == null && (mUrl == null || mUrl.length() == 0);
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004331 }
4332
Leon Scroggins92472e82010-02-17 16:32:28 -05004333 /**
4334 * Load this UrlData into the given Tab. Use loadUrlDataIn to update
4335 * the title bar as well.
4336 */
Leon Scroggins58d56c62010-01-28 15:12:40 -05004337 public void loadIn(Tab t) {
4338 if (mVoiceIntent != null) {
4339 t.activateVoiceSearchMode(mVoiceIntent);
4340 } else {
4341 t.getWebView().loadUrl(mUrl, mHeaders);
4342 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004343 }
4344 };
4345
Leon Scroggins1f005d32009-08-10 17:36:42 -04004346 /* package */ static final UrlData EMPTY_URL_DATA = new UrlData(null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004347}