blob: fcc1a8df3de13778b7659622e2f0c3add0e052ef [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());
Satish Sampath565505b2009-05-29 15:37:27 +0100609 startActivity(intent);
610
611 return true;
612 }
613
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700614 private UrlData getUrlDataFromIntent(Intent intent) {
Leon Scroggins58d56c62010-01-28 15:12:40 -0500615 String url = "";
Grace Kloba068e48b2010-01-26 18:11:27 -0800616 Map<String, String> headers = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800617 if (intent != null) {
618 final String action = intent.getAction();
619 if (Intent.ACTION_VIEW.equals(action)) {
620 url = smartUrlFilter(intent.getData());
621 if (url != null && url.startsWith("content:")) {
622 /* Append mimetype so webview knows how to display */
623 String mimeType = intent.resolveType(getContentResolver());
624 if (mimeType != null) {
625 url += "?" + mimeType;
626 }
627 }
Grace Kloba068e48b2010-01-26 18:11:27 -0800628 if (url != null && url.startsWith("http")) {
Grace Kloba00f54c52010-01-27 14:53:51 -0800629 final Bundle pairs = intent
630 .getBundleExtra(Browser.EXTRA_HEADERS);
Grace Kloba2d508ed2010-01-28 11:39:15 -0800631 if (pairs != null && !pairs.isEmpty()) {
Grace Kloba00f54c52010-01-27 14:53:51 -0800632 Iterator<String> iter = pairs.keySet().iterator();
Grace Kloba068e48b2010-01-26 18:11:27 -0800633 headers = new HashMap<String, String>();
Grace Kloba00f54c52010-01-27 14:53:51 -0800634 while (iter.hasNext()) {
635 String key = iter.next();
636 headers.put(key, pairs.getString(key));
Grace Kloba068e48b2010-01-26 18:11:27 -0800637 }
638 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700639 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800640 } else if (Intent.ACTION_SEARCH.equals(action)
641 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
642 || Intent.ACTION_WEB_SEARCH.equals(action)) {
643 url = intent.getStringExtra(SearchManager.QUERY);
644 if (url != null) {
645 mLastEnteredUrl = url;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800646 // In general, we shouldn't modify URL from Intent.
647 // But currently, we get the user-typed URL from search box as well.
648 url = fixUrl(url);
649 url = smartUrlFilter(url);
Leon Scroggins8d06e362010-03-24 14:45:57 -0400650 final ContentResolver cr = mResolver;
651 final String newUrl = url;
Elliott Slaughter8389e992010-08-20 15:44:08 -0700652 if (mTabControl == null
653 || mTabControl.getCurrentWebView() == null
654 || !mTabControl.getCurrentWebView().isPrivateBrowsingEnabled()) {
655 new AsyncTask<Void, Void, Void>() {
656 @Override
657 protected Void doInBackground(Void... unused) {
658 Browser.updateVisitedHistory(cr, newUrl, false);
659 return null;
660 }
661 }.execute();
662 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800663 String searchSource = "&source=android-" + GOOGLE_SEARCH_SOURCE_SUGGEST + "&";
664 if (url.contains(searchSource)) {
665 String source = null;
666 final Bundle appData = intent.getBundleExtra(SearchManager.APP_DATA);
667 if (appData != null) {
Bjorn Bringert10d1cca2010-02-10 14:22:12 +0000668 source = appData.getString(Search.SOURCE);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800669 }
670 if (TextUtils.isEmpty(source)) {
671 source = GOOGLE_SEARCH_SOURCE_UNKNOWN;
672 }
673 url = url.replace(searchSource, "&source=android-"+source+"&");
674 }
675 }
676 }
677 }
Leon Scroggins58d56c62010-01-28 15:12:40 -0500678 return new UrlData(url, headers, intent);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800679 }
Leon Scroggins58d56c62010-01-28 15:12:40 -0500680 /* package */ void showVoiceTitleBar(String title) {
681 mTitleBar.setInVoiceMode(true);
Leon Scroggins58d56c62010-01-28 15:12:40 -0500682 mTitleBar.setDisplayTitle(title);
Michael Kolba2b2ba82010-08-04 17:54:03 -0700683 mFakeTitleBar.setInVoiceMode(true);
684 mFakeTitleBar.setDisplayTitle(title);
Leon Scroggins58d56c62010-01-28 15:12:40 -0500685 }
686 /* package */ void revertVoiceTitleBar() {
687 mTitleBar.setInVoiceMode(false);
Leon Scroggins003a5dd2010-03-10 12:13:14 -0500688 mTitleBar.setDisplayTitle(mUrl);
Michael Kolba2b2ba82010-08-04 17:54:03 -0700689 mFakeTitleBar.setInVoiceMode(false);
690 mFakeTitleBar.setDisplayTitle(mUrl);
Leon Scroggins58d56c62010-01-28 15:12:40 -0500691 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800692 /* package */ static String fixUrl(String inUrl) {
Cary Clark652ff872009-09-10 13:34:44 -0400693 // FIXME: Converting the url to lower case
694 // duplicates functionality in smartUrlFilter().
695 // However, changing all current callers of fixUrl to
696 // call smartUrlFilter in addition may have unwanted
697 // consequences, and is deferred for now.
698 int colon = inUrl.indexOf(':');
699 boolean allLower = true;
700 for (int index = 0; index < colon; index++) {
701 char ch = inUrl.charAt(index);
702 if (!Character.isLetter(ch)) {
703 break;
704 }
705 allLower &= Character.isLowerCase(ch);
706 if (index == colon - 1 && !allLower) {
707 inUrl = inUrl.substring(0, colon).toLowerCase()
708 + inUrl.substring(colon);
709 }
710 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800711 if (inUrl.startsWith("http://") || inUrl.startsWith("https://"))
712 return inUrl;
713 if (inUrl.startsWith("http:") ||
714 inUrl.startsWith("https:")) {
715 if (inUrl.startsWith("http:/") || inUrl.startsWith("https:/")) {
716 inUrl = inUrl.replaceFirst("/", "//");
717 } else inUrl = inUrl.replaceFirst(":", "://");
718 }
719 return inUrl;
720 }
721
Grace Kloba22ac16e2009-10-07 18:00:23 -0700722 @Override
723 protected void onResume() {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800724 super.onResume();
Dave Bort31a6d1c2009-04-13 15:56:49 -0700725 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800726 Log.v(LOGTAG, "BrowserActivity.onResume: this=" + this);
727 }
728
729 if (!mActivityInPause) {
730 Log.e(LOGTAG, "BrowserActivity is already resumed.");
731 return;
732 }
733
Mike Reed7bfa63b2009-05-28 11:08:32 -0400734 mTabControl.resumeCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800735 mActivityInPause = false;
Mike Reed7bfa63b2009-05-28 11:08:32 -0400736 resumeWebViewTimers();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800737
738 if (mWakeLock.isHeld()) {
739 mHandler.removeMessages(RELEASE_WAKELOCK);
740 mWakeLock.release();
741 }
742
The Android Open Source Project0c908882009-03-03 19:32:16 -0800743 registerReceiver(mNetworkStateIntentReceiver,
744 mNetworkStateChangedFilter);
745 WebView.enablePlatformNotifications();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800746 }
747
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400748 /**
749 * Since the actual title bar is embedded in the WebView, and removing it
Leon Scrogginsfe87bd32009-10-06 10:10:00 -0400750 * would change its appearance, use a different TitleBar to show overlayed
751 * at the top of the screen, when the menu is open or the page is loading.
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400752 */
Michael Kolba2b2ba82010-08-04 17:54:03 -0700753 private TitleBarBase mFakeTitleBar;
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400754
755 /**
756 * Keeps track of whether the options menu is open. This is important in
757 * determining whether to show or hide the title bar overlay.
758 */
759 private boolean mOptionsMenuOpen;
760
761 /**
762 * Only meaningful when mOptionsMenuOpen is true. This variable keeps track
763 * of whether the configuration has changed. The first onMenuOpened call
764 * after a configuration change is simply a reopening of the same menu
765 * (i.e. mIconView did not change).
766 */
767 private boolean mConfigChanged;
768
769 /**
770 * Whether or not the options menu is in its smaller, icon menu form. When
771 * true, we want the title bar overlay to be up. When false, we do not.
772 * Only meaningful if mOptionsMenuOpen is true.
773 */
774 private boolean mIconView;
775
Leon Scrogginsa81a7642009-08-31 17:05:41 -0400776 @Override
777 public boolean onMenuOpened(int featureId, Menu menu) {
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400778 if (Window.FEATURE_OPTIONS_PANEL == featureId) {
779 if (mOptionsMenuOpen) {
780 if (mConfigChanged) {
781 // We do not need to make any changes to the state of the
782 // title bar, since the only thing that happened was a
783 // change in orientation
784 mConfigChanged = false;
785 } else {
786 if (mIconView) {
787 // Switching the menu to expanded view, so hide the
788 // title bar.
789 hideFakeTitleBar();
790 mIconView = false;
791 } else {
792 // Switching the menu back to icon view, so show the
793 // title bar once again.
794 showFakeTitleBar();
795 mIconView = true;
796 }
797 }
798 } else {
799 // The options menu is closed, so open it, and show the title
800 showFakeTitleBar();
801 mOptionsMenuOpen = true;
802 mConfigChanged = false;
803 mIconView = true;
804 }
805 }
Leon Scrogginsa81a7642009-08-31 17:05:41 -0400806 return true;
807 }
808
Michael Kolba2b2ba82010-08-04 17:54:03 -0700809 void showFakeTitleBar() {
810 if (!isFakeTitleBarShowing() && mActiveTabsPage == null && !mActivityInPause) {
Grace Kloba847c25b2010-03-30 16:00:26 -0700811 WebView mainView = mTabControl.getCurrentWebView();
812 // if there is no current WebView, don't show the faked title bar;
Grace Kloba65190702010-04-02 23:37:26 -0700813 if (mainView == null) {
Cary Clarka0464552009-09-29 13:00:45 -0400814 return;
815 }
Leon Scroggins79e36d92010-04-29 16:01:46 +0100816 // Do not need to check for null, since the current tab will have
817 // at least a main WebView, or we would have returned above.
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -0400818 if (isInCustomActionMode()) {
819 // Do not show the fake title bar, while a custom ActionMode
820 // (i.e. find or select) is showing.
Leon Scroggins79e36d92010-04-29 16:01:46 +0100821 return;
822 }
Michael Kolba2b2ba82010-08-04 17:54:03 -0700823 if (mXLargeScreenSize) {
824 mContentView.addView(mFakeTitleBar);
825 mTabBar.onShowTitleBar();
826 } else {
827 WindowManager manager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400828
Michael Kolba2b2ba82010-08-04 17:54:03 -0700829 // Add the title bar to the window manager so it can receive
830 // touches
831 // while the menu is up
832 WindowManager.LayoutParams params =
833 new WindowManager.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
834 ViewGroup.LayoutParams.WRAP_CONTENT,
835 WindowManager.LayoutParams.TYPE_APPLICATION,
836 WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
837 PixelFormat.TRANSLUCENT);
838 params.gravity = Gravity.TOP;
839 boolean atTop = mainView.getScrollY() == 0;
840 params.windowAnimations = atTop ? 0 : R.style.TitleBar;
841 manager.addView(mFakeTitleBar, params);
842 }
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400843 }
844 }
845
846 @Override
847 public void onOptionsMenuClosed(Menu menu) {
848 mOptionsMenuOpen = false;
Leon Scrogginsa27ff192009-09-14 12:58:04 -0400849 if (!mInLoad) {
850 hideFakeTitleBar();
851 } else if (!mIconView) {
852 // The page is currently loading, and we are in expanded mode, so
853 // we were not showing the menu. Show it once again. It will be
854 // removed when the page finishes.
855 showFakeTitleBar();
856 }
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400857 }
Grace Kloba22ac16e2009-10-07 18:00:23 -0700858
Michael Kolba2b2ba82010-08-04 17:54:03 -0700859 void stopScrolling() {
860 ((ScrollWebView) mTabControl.getCurrentWebView()).stopScroll();
861 }
862
863 void hideFakeTitleBar() {
864 if (!isFakeTitleBarShowing()) return;
865 if (mXLargeScreenSize) {
866 mContentView.removeView(mFakeTitleBar);
867 mTabBar.onHideTitleBar();
868 } else {
869 WindowManager.LayoutParams params =
870 (WindowManager.LayoutParams) mFakeTitleBar.getLayoutParams();
871 WebView mainView = mTabControl.getCurrentWebView();
872 // Although we decided whether or not to animate based on the
873 // current
874 // scroll position, the scroll position may have changed since the
875 // fake title bar was displayed. Make sure it has the appropriate
876 // animation/lack thereof before removing.
877 params.windowAnimations =
878 mainView != null && mainView.getScrollY() == 0 ? 0 : R.style.TitleBar;
879 WindowManager manager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
880 manager.updateViewLayout(mFakeTitleBar, params);
881 manager.removeView(mFakeTitleBar);
882 }
883 }
884
885 boolean isFakeTitleBarShowing() {
886 return (mFakeTitleBar.getParent() != null);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400887 }
888
The Android Open Source Project0c908882009-03-03 19:32:16 -0800889 /**
Leon Scrogginsc6fa1102009-09-21 10:40:01 -0400890 * Special method for the fake title bar to call when displaying its context
891 * menu, since it is in its own Window, and its parent does not show a
892 * context menu.
893 */
894 /* package */ void showTitleBarContextMenu() {
Cary Clark65f4a3c2009-09-28 17:05:06 -0400895 if (null == mTitleBar.getParent()) {
896 return;
897 }
Leon Scrogginsc6fa1102009-09-21 10:40:01 -0400898 openContextMenu(mTitleBar);
899 }
900
Leon Scrogginsb2b19f52009-10-09 16:10:00 -0400901 @Override
902 public void onContextMenuClosed(Menu menu) {
903 super.onContextMenuClosed(menu);
904 if (mInLoad) {
905 showFakeTitleBar();
906 }
907 }
908
Leon Scrogginsc6fa1102009-09-21 10:40:01 -0400909 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -0800910 * onSaveInstanceState(Bundle map)
911 * onSaveInstanceState is called right before onStop(). The map contains
912 * the saved state.
913 */
Grace Kloba22ac16e2009-10-07 18:00:23 -0700914 @Override
915 protected void onSaveInstanceState(Bundle outState) {
Dave Bort31a6d1c2009-04-13 15:56:49 -0700916 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800917 Log.v(LOGTAG, "BrowserActivity.onSaveInstanceState: this=" + this);
918 }
919 // the default implementation requires each view to have an id. As the
920 // browser handles the state itself and it doesn't use id for the views,
921 // don't call the default implementation. Otherwise it will trigger the
922 // warning like this, "couldn't save which view has focus because the
923 // focused view XXX has no id".
924
925 // Save all the tabs
926 mTabControl.saveState(outState);
927 }
928
Grace Kloba22ac16e2009-10-07 18:00:23 -0700929 @Override
930 protected void onPause() {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800931 super.onPause();
932
933 if (mActivityInPause) {
934 Log.e(LOGTAG, "BrowserActivity is already paused.");
935 return;
936 }
937
Mike Reed7bfa63b2009-05-28 11:08:32 -0400938 mTabControl.pauseCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800939 mActivityInPause = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -0400940 if (mTabControl.getCurrentIndex() >= 0 && !pauseWebViewTimers()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800941 mWakeLock.acquire();
942 mHandler.sendMessageDelayed(mHandler
943 .obtainMessage(RELEASE_WAKELOCK), WAKELOCK_TIMEOUT);
944 }
945
Leon Scrogginsa2ab6a72009-09-11 11:49:52 -0400946 // FIXME: This removes the active tabs page and resets the menu to
947 // MAIN_MENU. A better solution might be to do this work in onNewIntent
948 // but then we would need to save it in onSaveInstanceState and restore
949 // it in onCreate/onRestoreInstanceState
950 if (mActiveTabsPage != null) {
951 removeActiveTabPage(true);
952 }
953
The Android Open Source Project0c908882009-03-03 19:32:16 -0800954 cancelStopToast();
955
956 // unregister network state listener
957 unregisterReceiver(mNetworkStateIntentReceiver);
958 WebView.disablePlatformNotifications();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800959 }
960
Grace Kloba22ac16e2009-10-07 18:00:23 -0700961 @Override
962 protected void onDestroy() {
Dave Bort31a6d1c2009-04-13 15:56:49 -0700963 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800964 Log.v(LOGTAG, "BrowserActivity.onDestroy: this=" + this);
965 }
966 super.onDestroy();
Grace Kloba0923d692009-09-23 21:37:25 -0700967
Leon Scroggins8d5fa432009-10-02 15:55:59 -0400968 if (mUploadMessage != null) {
969 mUploadMessage.onReceiveValue(null);
970 mUploadMessage = null;
971 }
972
Grace Kloba0923d692009-09-23 21:37:25 -0700973 if (mTabControl == null) return;
974
Grace Kloba1fc98a32009-10-21 13:23:08 -0700975 // Remove the fake title bar if it is there
976 hideFakeTitleBar();
977
The Android Open Source Project0c908882009-03-03 19:32:16 -0800978 // Remove the current tab and sub window
Grace Kloba22ac16e2009-10-07 18:00:23 -0700979 Tab t = mTabControl.getCurrentTab();
Patrick Scottfb5e77f2009-04-08 19:17:37 -0700980 if (t != null) {
981 dismissSubWindow(t);
982 removeTabFromContentView(t);
983 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800984 // Destroy all the tabs
985 mTabControl.destroy();
986 WebIconDatabase.getInstance().close();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800987
Grace Klobab4da0ad2009-05-14 14:45:40 -0700988 unregisterReceiver(mPackageInstallationReceiver);
Bjorn Bringerta7611812010-03-24 11:12:02 +0000989
990 // Stop watching the default geolocation permissions
991 mSystemAllowGeolocationOrigins.stop();
992 mSystemAllowGeolocationOrigins = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800993 }
994
995 @Override
996 public void onConfigurationChanged(Configuration newConfig) {
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400997 mConfigChanged = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800998 super.onConfigurationChanged(newConfig);
999
1000 if (mPageInfoDialog != null) {
1001 mPageInfoDialog.dismiss();
1002 showPageInfo(
1003 mPageInfoView,
Leon Scrogginsc7b92f82010-01-11 18:17:31 -05001004 mPageInfoFromShowSSLCertificateOnError);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001005 }
1006 if (mSSLCertificateDialog != null) {
1007 mSSLCertificateDialog.dismiss();
1008 showSSLCertificate(
1009 mSSLCertificateView);
1010 }
1011 if (mSSLCertificateOnErrorDialog != null) {
1012 mSSLCertificateOnErrorDialog.dismiss();
1013 showSSLCertificateOnError(
1014 mSSLCertificateOnErrorView,
1015 mSSLCertificateOnErrorHandler,
1016 mSSLCertificateOnErrorError);
1017 }
1018 if (mHttpAuthenticationDialog != null) {
1019 String title = ((TextView) mHttpAuthenticationDialog
1020 .findViewById(com.android.internal.R.id.alertTitle)).getText()
1021 .toString();
1022 String name = ((TextView) mHttpAuthenticationDialog
1023 .findViewById(R.id.username_edit)).getText().toString();
1024 String password = ((TextView) mHttpAuthenticationDialog
1025 .findViewById(R.id.password_edit)).getText().toString();
1026 int focusId = mHttpAuthenticationDialog.getCurrentFocus()
1027 .getId();
1028 mHttpAuthenticationDialog.dismiss();
1029 showHttpAuthentication(mHttpAuthHandler, null, null, title,
1030 name, password, focusId);
1031 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001032 }
1033
Grace Kloba22ac16e2009-10-07 18:00:23 -07001034 @Override
1035 public void onLowMemory() {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001036 super.onLowMemory();
1037 mTabControl.freeMemory();
1038 }
1039
Cary Clarkff4d92c2010-03-25 11:17:03 -04001040 private void resumeWebViewTimers() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001041 Tab tab = mTabControl.getCurrentTab();
Cary Clarkff4d92c2010-03-25 11:17:03 -04001042 if (tab == null) return; // monkey can trigger this
Grace Kloba22ac16e2009-10-07 18:00:23 -07001043 boolean inLoad = tab.inLoad();
1044 if ((!mActivityInPause && !inLoad) || (mActivityInPause && inLoad)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001045 CookieSyncManager.getInstance().startSync();
Grace Kloba22ac16e2009-10-07 18:00:23 -07001046 WebView w = tab.getWebView();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001047 if (w != null) {
1048 w.resumeTimers();
1049 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001050 }
1051 }
1052
Mike Reed7bfa63b2009-05-28 11:08:32 -04001053 private boolean pauseWebViewTimers() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001054 Tab tab = mTabControl.getCurrentTab();
1055 boolean inLoad = tab.inLoad();
1056 if (mActivityInPause && !inLoad) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001057 CookieSyncManager.getInstance().stopSync();
1058 WebView w = mTabControl.getCurrentWebView();
1059 if (w != null) {
1060 w.pauseTimers();
1061 }
1062 return true;
1063 } else {
1064 return false;
1065 }
1066 }
1067
The Android Open Source Project0c908882009-03-03 19:32:16 -08001068 // Open the icon database and retain all the icons for visited sites.
1069 private void retainIconsOnStartup() {
1070 final WebIconDatabase db = WebIconDatabase.getInstance();
1071 db.open(getDir("icons", 0).getPath());
Leon Scroggins2c0f6112010-03-12 18:09:39 -05001072 Cursor c = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001073 try {
Leon Scroggins2c0f6112010-03-12 18:09:39 -05001074 c = Browser.getAllBookmarks(mResolver);
1075 if (c.moveToFirst()) {
1076 int urlIndex = c.getColumnIndex(Browser.BookmarkColumns.URL);
1077 do {
1078 String url = c.getString(urlIndex);
1079 db.retainIconForPageUrl(url);
1080 } while (c.moveToNext());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001081 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001082 } catch (IllegalStateException e) {
1083 Log.e(LOGTAG, "retainIconsOnStartup", e);
Leon Scroggins2c0f6112010-03-12 18:09:39 -05001084 } finally {
1085 if (c!= null) c.close();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001086 }
1087 }
1088
1089 // Helper method for getting the top window.
1090 WebView getTopWindow() {
1091 return mTabControl.getCurrentTopWebView();
1092 }
1093
Grace Kloba22ac16e2009-10-07 18:00:23 -07001094 TabControl getTabControl() {
1095 return mTabControl;
1096 }
1097
The Android Open Source Project0c908882009-03-03 19:32:16 -08001098 @Override
1099 public boolean onCreateOptionsMenu(Menu menu) {
1100 super.onCreateOptionsMenu(menu);
1101
1102 MenuInflater inflater = getMenuInflater();
1103 inflater.inflate(R.menu.browser, menu);
1104 mMenu = menu;
1105 updateInLoadMenuItems();
1106 return true;
1107 }
1108
1109 /**
1110 * As the menu can be open when loading state changes
1111 * we must manually update the state of the stop/reload menu
1112 * item
1113 */
1114 private void updateInLoadMenuItems() {
1115 if (mMenu == null) {
1116 return;
1117 }
Michael Kolbe0a36662010-06-29 10:37:12 -07001118 MenuItem dest = mMenu.findItem(R.id.stop_reload_menu_id);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001119 MenuItem src = mInLoad ?
1120 mMenu.findItem(R.id.stop_menu_id):
Michael Kolbe0a36662010-06-29 10:37:12 -07001121 mMenu.findItem(R.id.reload_menu_id);
1122 if (src != null) {
1123 dest.setIcon(src.getIcon());
1124 dest.setTitle(src.getTitle());
1125 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001126 }
1127
1128 @Override
1129 public boolean onContextItemSelected(MenuItem item) {
1130 // chording is not an issue with context menus, but we use the same
1131 // options selector, so set mCanChord to true so we can access them.
1132 mCanChord = true;
1133 int id = item.getItemId();
Leon Scroggins96afcb12009-12-10 12:35:56 -05001134 boolean result = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001135 switch (id) {
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001136 // For the context menu from the title bar
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001137 case R.id.title_bar_copy_page_url:
Leon Scroggins96afcb12009-12-10 12:35:56 -05001138 Tab currentTab = mTabControl.getCurrentTab();
1139 if (null == currentTab) {
1140 result = false;
1141 break;
1142 }
1143 WebView mainView = currentTab.getWebView();
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001144 if (null == mainView) {
Leon Scroggins96afcb12009-12-10 12:35:56 -05001145 result = false;
1146 break;
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001147 }
Leon Scroggins96afcb12009-12-10 12:35:56 -05001148 copy(mainView.getUrl());
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001149 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001150 // -- Browser context menu
1151 case R.id.open_context_menu_id:
The Android Open Source Project0c908882009-03-03 19:32:16 -08001152 case R.id.bookmark_context_menu_id:
1153 case R.id.save_link_context_menu_id:
1154 case R.id.share_link_context_menu_id:
1155 case R.id.copy_link_context_menu_id:
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001156 final WebView webView = getTopWindow();
1157 if (null == webView) {
Leon Scroggins96afcb12009-12-10 12:35:56 -05001158 result = false;
1159 break;
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001160 }
1161 final HashMap hrefMap = new HashMap();
1162 hrefMap.put("webview", webView);
1163 final Message msg = mHandler.obtainMessage(
1164 FOCUS_NODE_HREF, id, 0, hrefMap);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001165 webView.requestFocusNodeHref(msg);
1166 break;
1167
1168 default:
1169 // For other context menus
Leon Scroggins96afcb12009-12-10 12:35:56 -05001170 result = onOptionsItemSelected(item);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001171 }
1172 mCanChord = false;
Leon Scroggins96afcb12009-12-10 12:35:56 -05001173 return result;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001174 }
1175
1176 private Bundle createGoogleSearchSourceBundle(String source) {
1177 Bundle bundle = new Bundle();
Bjorn Bringert10d1cca2010-02-10 14:22:12 +00001178 bundle.putString(Search.SOURCE, source);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001179 return bundle;
1180 }
1181
Leon Scroggins8ad29922010-02-16 12:33:55 -05001182 /* package */ void editUrl() {
Leon Scroggins68579392009-09-15 15:31:54 -04001183 if (mOptionsMenuOpen) closeOptionsMenu();
Leon Scroggins5bbe9802009-07-31 13:10:55 -04001184 String url = (getTopWindow() == null) ? null : getTopWindow().getUrl();
Grace Kloba83f47342009-07-20 10:44:31 -07001185 startSearch(mSettings.getHomePage().equals(url) ? null : url, true,
Leon Scroggins8ad29922010-02-16 12:33:55 -05001186 null, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001187 }
1188
Leon Scroggins8ad29922010-02-16 12:33:55 -05001189 /**
1190 * Overriding this to insert a local information bundle
1191 */
The Android Open Source Project0c908882009-03-03 19:32:16 -08001192 @Override
1193 public void startSearch(String initialQuery, boolean selectInitialQuery,
1194 Bundle appSearchData, boolean globalSearch) {
1195 if (appSearchData == null) {
1196 appSearchData = createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_TYPE);
1197 }
1198 super.startSearch(initialQuery, selectInitialQuery, appSearchData, globalSearch);
1199 }
1200
Leon Scroggins1f005d32009-08-10 17:36:42 -04001201 /**
1202 * Switch tabs. Called by the TitleBarSet when sliding the title bar
1203 * results in changing tabs.
Leon Scroggins160a7e72009-08-14 18:28:01 -04001204 * @param index Index of the tab to change to, as defined by
1205 * mTabControl.getTabIndex(Tab t).
1206 * @return boolean True if we successfully switched to a different tab. If
1207 * the indexth tab is null, or if that tab is the same as
1208 * the current one, return false.
Leon Scroggins1f005d32009-08-10 17:36:42 -04001209 */
Leon Scroggins160a7e72009-08-14 18:28:01 -04001210 /* package */ boolean switchToTab(int index) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001211 Tab tab = mTabControl.getTab(index);
1212 Tab currentTab = mTabControl.getCurrentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04001213 if (tab == null || tab == currentTab) {
Leon Scroggins160a7e72009-08-14 18:28:01 -04001214 return false;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001215 }
1216 if (currentTab != null) {
1217 // currentTab may be null if it was just removed. In that case,
1218 // we do not need to remove it
1219 removeTabFromContentView(currentTab);
1220 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001221 mTabControl.setCurrentTab(tab);
1222 attachTabToContentView(tab);
Grace Klobaeb6eef42009-09-15 17:56:32 -07001223 resetTitleIconAndProgress();
1224 updateLockIconToLatest();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001225 return true;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001226 }
1227
Grace Kloba22ac16e2009-10-07 18:00:23 -07001228 /* package */ Tab openTabToHomePage() {
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001229 return openTabAndShow(mSettings.getHomePage(), false, null);
1230 }
1231
Leon Scroggins1f005d32009-08-10 17:36:42 -04001232 /* package */ void closeCurrentWindow() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001233 final Tab current = mTabControl.getCurrentTab();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001234 if (mTabControl.getTabCount() == 1) {
Leon Scroggins30444232009-09-04 18:36:20 -04001235 // This is the last tab. Open a new one, with the home
1236 // page and close the current one.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001237 openTabToHomePage();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001238 closeTab(current);
Leon Scroggins160a7e72009-08-14 18:28:01 -04001239 return;
1240 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07001241 final Tab parent = current.getParentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04001242 int indexToShow = -1;
1243 if (parent != null) {
1244 indexToShow = mTabControl.getTabIndex(parent);
1245 } else {
Leon Scroggins160a7e72009-08-14 18:28:01 -04001246 final int currentIndex = mTabControl.getCurrentIndex();
1247 // Try to move to the tab to the right
1248 indexToShow = currentIndex + 1;
1249 if (indexToShow > mTabControl.getTabCount() - 1) {
1250 // Try to move to the tab to the left
1251 indexToShow = currentIndex - 1;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001252 }
1253 }
Leon Scroggins160a7e72009-08-14 18:28:01 -04001254 if (switchToTab(indexToShow)) {
1255 // Close window
1256 closeTab(current);
1257 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001258 }
1259
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001260 private ActiveTabsPage mActiveTabsPage;
1261
1262 /**
1263 * Remove the active tabs page.
1264 * @param needToAttach If true, the active tabs page did not attach a tab
1265 * to the content view, so we need to do that here.
1266 */
1267 /* package */ void removeActiveTabPage(boolean needToAttach) {
1268 mContentView.removeView(mActiveTabsPage);
Leon Scrogginsd746a942010-05-19 13:21:44 -04001269 mTitleBar.setVisibility(View.VISIBLE);
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001270 mActiveTabsPage = null;
1271 mMenuState = R.id.MAIN_MENU;
1272 if (needToAttach) {
1273 attachTabToContentView(mTabControl.getCurrentTab());
1274 }
1275 getTopWindow().requestFocus();
1276 }
1277
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04001278 @Override
1279 public ActionMode onStartActionMode(ActionMode.Callback callback) {
1280 ActionMode mode = super.onStartActionMode(callback);
1281 if (callback instanceof FindActionModeCallback
1282 || callback instanceof SelectActionModeCallback) {
1283 // For find and select, hide extra title bars. They will
1284 // be replaced in onEndActionMode.
1285 Tab tab = mTabControl.getCurrentTab();
1286 if (tab.getSubWebView() == null) {
1287 // If the find or select is being performed on the main webview,
1288 // remove the embedded title bar.
1289 WebView mainView = tab.getWebView();
1290 if (mainView != null) {
1291 mainView.setEmbeddedTitleBar(null);
1292 }
Cary Clark01cfcdd2010-06-04 16:36:45 -04001293 }
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04001294 hideFakeTitleBar();
1295 mActionMode = mode;
1296 } else {
1297 // Do not store other ActionModes, since we are unable to determine
1298 // when they finish.
1299 mActionMode = null;
Cary Clark01cfcdd2010-06-04 16:36:45 -04001300 }
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04001301 return mode;
Cary Clark01cfcdd2010-06-04 16:36:45 -04001302 }
1303
The Android Open Source Project0c908882009-03-03 19:32:16 -08001304 @Override
1305 public boolean onOptionsItemSelected(MenuItem item) {
Michael Kolbed217742010-08-10 17:52:34 -07001306 // check the action bar button before mCanChord check, as the prepare call
1307 // doesn't come for action bar buttons
1308 if (item.getItemId() == R.id.newtab) {
Michael Kolb300b7f02010-08-25 13:47:24 -07001309 openTabToHomePage();
1310 mHandler.sendMessage(mHandler.obtainMessage(OPEN_BOOKMARKS));
Michael Kolbed217742010-08-10 17:52:34 -07001311 return true;
1312 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001313 if (!mCanChord) {
1314 // The user has already fired a shortcut with this hold down of the
1315 // menu key.
1316 return false;
1317 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001318 if (null == getTopWindow()) {
Leon Scroggins0d7ae0e2009-06-05 11:04:45 -04001319 return false;
1320 }
Grace Kloba6ee9c492009-07-13 10:04:34 -07001321 if (mMenuIsDown) {
1322 // The shortcut action consumes the MENU. Even if it is still down,
1323 // it won't trigger the next shortcut action. In the case of the
1324 // shortcut action triggering a new activity, like Bookmarks, we
1325 // won't get onKeyUp for MENU. So it is important to reset it here.
1326 mMenuIsDown = false;
1327 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001328 switch (item.getItemId()) {
1329 // -- Main menu
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001330 case R.id.new_tab_menu_id:
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001331 openTabToHomePage();
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001332 break;
1333
Michael Kolbae62fd42010-08-18 16:33:28 -07001334 case R.id.incognito_menu_id:
1335 openIncognitoTab();
1336 break;
1337
Leon Scroggins64b80f32009-08-07 12:03:34 -04001338 case R.id.goto_menu_id:
Leon Scroggins8ad29922010-02-16 12:33:55 -05001339 editUrl();
Leon Scrogginsb3a5bed2009-09-28 11:21:56 -04001340 break;
1341
1342 case R.id.bookmarks_menu_id:
Michael Kolb68792c82010-08-09 16:39:18 -07001343 bookmarksOrHistoryPicker(false, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001344 break;
1345
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001346 case R.id.active_tabs_menu_id:
1347 mActiveTabsPage = new ActiveTabsPage(this, mTabControl);
1348 removeTabFromContentView(mTabControl.getCurrentTab());
Leon Scrogginsd746a942010-05-19 13:21:44 -04001349 mTitleBar.setVisibility(View.GONE);
Leon Scroggins43de6162009-09-14 19:59:58 -04001350 hideFakeTitleBar();
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001351 mContentView.addView(mActiveTabsPage, COVER_SCREEN_PARAMS);
1352 mActiveTabsPage.requestFocus();
1353 mMenuState = EMPTY_MENU;
1354 break;
1355
Leon Scroggins1f005d32009-08-10 17:36:42 -04001356 case R.id.add_bookmark_menu_id:
Leon Scroggins571b3762010-05-26 10:25:01 -04001357 bookmarkCurrentPage();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001358 break;
1359
1360 case R.id.stop_reload_menu_id:
1361 if (mInLoad) {
1362 stopLoading();
1363 } else {
1364 getTopWindow().reload();
1365 }
1366 break;
1367
1368 case R.id.back_menu_id:
1369 getTopWindow().goBack();
1370 break;
1371
1372 case R.id.forward_menu_id:
1373 getTopWindow().goForward();
1374 break;
1375
1376 case R.id.close_menu_id:
1377 // Close the subwindow if it exists.
1378 if (mTabControl.getCurrentSubWindow() != null) {
1379 dismissSubWindow(mTabControl.getCurrentTab());
1380 break;
1381 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001382 closeCurrentWindow();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001383 break;
1384
1385 case R.id.homepage_menu_id:
Grace Kloba22ac16e2009-10-07 18:00:23 -07001386 Tab current = mTabControl.getCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001387 if (current != null) {
1388 dismissSubWindow(current);
Leon Scroggins92472e82010-02-17 16:32:28 -05001389 loadUrl(current.getWebView(), mSettings.getHomePage());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001390 }
1391 break;
1392
1393 case R.id.preferences_menu_id:
1394 Intent intent = new Intent(this,
1395 BrowserPreferencesPage.class);
Leon Scrogginsd5304942009-12-10 16:11:39 -05001396 intent.putExtra(BrowserPreferencesPage.CURRENT_PAGE,
1397 getTopWindow().getUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001398 startActivityForResult(intent, PREFERENCES_PAGE);
1399 break;
1400
1401 case R.id.find_menu_id:
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04001402 showFindDialog(null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001403 break;
1404
Elliott Slaughter0ced08c2010-06-30 11:40:42 -07001405 case R.id.save_webarchive_menu_id:
1406 if (LOGD_ENABLED) {
1407 Log.d(LOGTAG, "Save as Web Archive");
1408 }
1409 String directory = getExternalFilesDir(null).getAbsolutePath() + File.separator;
1410 getTopWindow().saveWebArchive(directory, true, new ValueCallback<String>() {
1411 @Override
1412 public void onReceiveValue(String value) {
1413 if (value != null) {
1414 Toast.makeText(BrowserActivity.this, R.string.webarchive_saved, Toast.LENGTH_SHORT).show();
1415 } else {
1416 Toast.makeText(BrowserActivity.this, R.string.webarchive_failed, Toast.LENGTH_SHORT).show();
1417 }
1418 }
1419 });
1420 break;
1421
The Android Open Source Project0c908882009-03-03 19:32:16 -08001422 case R.id.page_info_menu_id:
1423 showPageInfo(mTabControl.getCurrentTab(), false);
1424 break;
1425
1426 case R.id.classic_history_menu_id:
Michael Kolb68792c82010-08-09 16:39:18 -07001427 bookmarksOrHistoryPicker(true, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001428 break;
1429
Leon Scroggins96afcb12009-12-10 12:35:56 -05001430 case R.id.title_bar_share_page_url:
The Android Open Source Project0c908882009-03-03 19:32:16 -08001431 case R.id.share_page_menu_id:
Leon Scroggins96afcb12009-12-10 12:35:56 -05001432 Tab currentTab = mTabControl.getCurrentTab();
1433 if (null == currentTab) {
1434 mCanChord = false;
1435 return false;
1436 }
1437 currentTab.populatePickerData();
1438 sharePage(this, currentTab.getTitle(),
1439 currentTab.getUrl(), currentTab.getFavicon(),
Ben Murdoch87cc65d2010-06-29 20:34:10 +01001440 createScreenshot(currentTab.getWebView(), getDesiredThumbnailWidth(this),
1441 getDesiredThumbnailHeight(this)));
The Android Open Source Project0c908882009-03-03 19:32:16 -08001442 break;
1443
1444 case R.id.dump_nav_menu_id:
1445 getTopWindow().debugDump();
1446 break;
1447
Andrei Popescu7a8b88b2010-02-02 00:30:38 +00001448 case R.id.dump_counters_menu_id:
1449 getTopWindow().dumpV8Counters();
1450 break;
1451
The Android Open Source Project0c908882009-03-03 19:32:16 -08001452 case R.id.zoom_in_menu_id:
1453 getTopWindow().zoomIn();
1454 break;
1455
1456 case R.id.zoom_out_menu_id:
1457 getTopWindow().zoomOut();
1458 break;
1459
1460 case R.id.view_downloads_menu_id:
1461 viewDownloads(null);
1462 break;
1463
The Android Open Source Project0c908882009-03-03 19:32:16 -08001464 case R.id.window_one_menu_id:
1465 case R.id.window_two_menu_id:
1466 case R.id.window_three_menu_id:
1467 case R.id.window_four_menu_id:
1468 case R.id.window_five_menu_id:
1469 case R.id.window_six_menu_id:
1470 case R.id.window_seven_menu_id:
1471 case R.id.window_eight_menu_id:
1472 {
1473 int menuid = item.getItemId();
1474 for (int id = 0; id < WINDOW_SHORTCUT_ID_ARRAY.length; id++) {
1475 if (WINDOW_SHORTCUT_ID_ARRAY[id] == menuid) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001476 Tab desiredTab = mTabControl.getTab(id);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001477 if (desiredTab != null &&
1478 desiredTab != mTabControl.getCurrentTab()) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001479 switchToTab(id);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001480 }
1481 break;
1482 }
1483 }
1484 }
1485 break;
1486
1487 default:
1488 if (!super.onOptionsItemSelected(item)) {
1489 return false;
1490 }
1491 // Otherwise fall through.
1492 }
1493 mCanChord = false;
1494 return true;
1495 }
1496
Leon Scroggins571b3762010-05-26 10:25:01 -04001497 /* package */ void bookmarkCurrentPage() {
1498 Intent i = new Intent(BrowserActivity.this,
1499 AddBookmarkPage.class);
1500 WebView w = getTopWindow();
1501 i.putExtra("url", w.getUrl());
1502 i.putExtra("title", w.getTitle());
1503 i.putExtra("touch_icon_url", w.getTouchIconUrl());
Ben Murdoch87cc65d2010-06-29 20:34:10 +01001504 i.putExtra("thumbnail", createScreenshot(w, getDesiredThumbnailWidth(this),
1505 getDesiredThumbnailHeight(this)));
Ben Murdocheecb4e62010-07-06 16:30:38 +01001506 i.putExtra("url_editable", false);
Leon Scroggins571b3762010-05-26 10:25:01 -04001507 startActivity(i);
1508 }
1509
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04001510 /*
1511 * True if a custom ActionMode (i.e. find or select) is in use.
1512 */
1513 private boolean isInCustomActionMode() {
1514 return mActionMode != null;
Cary Clark01cfcdd2010-06-04 16:36:45 -04001515 }
1516
1517 /*
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04001518 * End the current ActionMode. Only works for find and select.
Cary Clark01cfcdd2010-06-04 16:36:45 -04001519 */
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04001520 void endActionMode() {
1521 if (mActionMode != null) {
1522 mActionMode.finish();
1523 }
1524 }
1525
1526 /*
1527 * Called by find and select when they are finished. Replace title bars
1528 * as necessary.
1529 */
1530 public void onEndActionMode() {
1531 if (!isInCustomActionMode()) return;
Michael Kolba2b2ba82010-08-04 17:54:03 -07001532 // If the Find was being performed in the main WebView, replace the
1533 // embedded title bar.
1534 Tab currentTab = mTabControl.getCurrentTab();
1535 if (currentTab.getSubWebView() == null) {
1536 WebView mainView = currentTab.getWebView();
1537 if (mainView != null) {
1538 mainView.setEmbeddedTitleBar(mTitleBar);
Leon Scroggins79e36d92010-04-29 16:01:46 +01001539 }
1540 }
Leon Scroggins79e36d92010-04-29 16:01:46 +01001541 if (mInLoad) {
1542 // The title bar was hidden, because otherwise it would cover up the
Michael Kolba2b2ba82010-08-04 17:54:03 -07001543 // find or select dialog. Now that the dialog has been removed,
Cary Clark01cfcdd2010-06-04 16:36:45 -04001544 // show the fake title bar once again.
Leon Scroggins79e36d92010-04-29 16:01:46 +01001545 showFakeTitleBar();
1546 }
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04001547 mActionMode = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001548 }
1549
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04001550 private FindActionModeCallback mFindCallback;
1551 private SelectActionModeCallback mSelectCallback;
1552
1553 // For select and find, we keep track of the ActionMode so that
1554 // finish() can be called as desired.
1555 private ActionMode mActionMode;
1556
1557 /*
1558 * Open the find ActionMode.
1559 * @param text If non null, will be placed in find to be searched for.
1560 */
1561 public void showFindDialog(String text) {
1562 if (null == mFindCallback) {
1563 mFindCallback = new FindActionModeCallback(this);
Cary Clark01cfcdd2010-06-04 16:36:45 -04001564 }
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04001565 WebView webView = getTopWindow();
1566 webView.setFindIsUp(true);
1567 mFindCallback.setWebView(webView);
1568 startActionMode(mFindCallback);
1569 if (text != null) mFindCallback.setText(text);
Cary Clark01cfcdd2010-06-04 16:36:45 -04001570 }
1571
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04001572 /*
1573 * Show the select ActionMode.
1574 */
Cary Clark01cfcdd2010-06-04 16:36:45 -04001575 public void showSelectDialog() {
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04001576 if (null == mSelectCallback) {
1577 mSelectCallback = new SelectActionModeCallback(this);
Cary Clark01cfcdd2010-06-04 16:36:45 -04001578 }
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04001579 WebView webView = getTopWindow();
1580 webView.setUpSelect();
1581 mSelectCallback.setWebView(webView);
1582 startActionMode(mSelectCallback);
Cary Clark01cfcdd2010-06-04 16:36:45 -04001583 }
1584
Grace Kloba22ac16e2009-10-07 18:00:23 -07001585 @Override
1586 public boolean onPrepareOptionsMenu(Menu menu) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001587 // This happens when the user begins to hold down the menu key, so
1588 // allow them to chord to get a shortcut.
1589 mCanChord = true;
1590 // Note: setVisible will decide whether an item is visible; while
1591 // setEnabled() will decide whether an item is enabled, which also means
1592 // whether the matching shortcut key will function.
1593 super.onPrepareOptionsMenu(menu);
1594 switch (mMenuState) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001595 case EMPTY_MENU:
1596 if (mCurrentMenuState != mMenuState) {
1597 menu.setGroupVisible(R.id.MAIN_MENU, false);
1598 menu.setGroupEnabled(R.id.MAIN_MENU, false);
1599 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001600 }
1601 break;
1602 default:
1603 if (mCurrentMenuState != mMenuState) {
1604 menu.setGroupVisible(R.id.MAIN_MENU, true);
1605 menu.setGroupEnabled(R.id.MAIN_MENU, true);
1606 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001607 }
1608 final WebView w = getTopWindow();
1609 boolean canGoBack = false;
1610 boolean canGoForward = false;
1611 boolean isHome = false;
1612 if (w != null) {
1613 canGoBack = w.canGoBack();
1614 canGoForward = w.canGoForward();
1615 isHome = mSettings.getHomePage().equals(w.getUrl());
1616 }
1617 final MenuItem back = menu.findItem(R.id.back_menu_id);
1618 back.setEnabled(canGoBack);
1619
1620 final MenuItem home = menu.findItem(R.id.homepage_menu_id);
1621 home.setEnabled(!isHome);
1622
Michael Kolbe0a36662010-06-29 10:37:12 -07001623 final MenuItem forward = menu.findItem(R.id.forward_menu_id);
1624 forward.setEnabled(canGoForward);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001625
Michael Kolbed217742010-08-10 17:52:34 -07001626 if (!mXLargeScreenSize) {
1627 final MenuItem newtab = menu.findItem(R.id.new_tab_menu_id);
1628 newtab.setEnabled(mTabControl.canCreateNewTab());
1629 }
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001630
The Android Open Source Project0c908882009-03-03 19:32:16 -08001631 // decide whether to show the share link option
1632 PackageManager pm = getPackageManager();
1633 Intent send = new Intent(Intent.ACTION_SEND);
1634 send.setType("text/plain");
1635 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1636 menu.findItem(R.id.share_page_menu_id).setVisible(ri != null);
1637
The Android Open Source Project0c908882009-03-03 19:32:16 -08001638 boolean isNavDump = mSettings.isNavDump();
1639 final MenuItem nav = menu.findItem(R.id.dump_nav_menu_id);
1640 nav.setVisible(isNavDump);
1641 nav.setEnabled(isNavDump);
Andrei Popescu7a8b88b2010-02-02 00:30:38 +00001642
1643 boolean showDebugSettings = mSettings.showDebugSettings();
1644 final MenuItem counter = menu.findItem(R.id.dump_counters_menu_id);
1645 counter.setVisible(showDebugSettings);
1646 counter.setEnabled(showDebugSettings);
1647
The Android Open Source Project0c908882009-03-03 19:32:16 -08001648 break;
1649 }
1650 mCurrentMenuState = mMenuState;
1651 return true;
1652 }
1653
1654 @Override
1655 public void onCreateContextMenu(ContextMenu menu, View v,
1656 ContextMenuInfo menuInfo) {
Leon Scroggins571b3762010-05-26 10:25:01 -04001657 if (v instanceof TitleBarBase) {
Leon Scroggins4e9f89b2010-02-22 16:54:14 -05001658 return;
1659 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001660 WebView webview = (WebView) v;
1661 WebView.HitTestResult result = webview.getHitTestResult();
1662 if (result == null) {
1663 return;
1664 }
1665
1666 int type = result.getType();
1667 if (type == WebView.HitTestResult.UNKNOWN_TYPE) {
1668 Log.w(LOGTAG,
1669 "We should not show context menu when nothing is touched");
1670 return;
1671 }
1672 if (type == WebView.HitTestResult.EDIT_TEXT_TYPE) {
1673 // let TextView handles context menu
1674 return;
1675 }
1676
1677 // Note, http://b/issue?id=1106666 is requesting that
1678 // an inflated menu can be used again. This is not available
1679 // yet, so inflate each time (yuk!)
1680 MenuInflater inflater = getMenuInflater();
1681 inflater.inflate(R.menu.browsercontext, menu);
1682
1683 // Show the correct menu group
Leon Scroggins III9e997c72010-05-26 13:25:16 -04001684 final String extra = result.getExtra();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001685 menu.setGroupVisible(R.id.PHONE_MENU,
1686 type == WebView.HitTestResult.PHONE_TYPE);
1687 menu.setGroupVisible(R.id.EMAIL_MENU,
1688 type == WebView.HitTestResult.EMAIL_TYPE);
1689 menu.setGroupVisible(R.id.GEO_MENU,
1690 type == WebView.HitTestResult.GEO_TYPE);
1691 menu.setGroupVisible(R.id.IMAGE_MENU,
1692 type == WebView.HitTestResult.IMAGE_TYPE
1693 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1694 menu.setGroupVisible(R.id.ANCHOR_MENU,
1695 type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1696 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1697
1698 // Setup custom handling depending on the type
1699 switch (type) {
1700 case WebView.HitTestResult.PHONE_TYPE:
1701 menu.setHeaderTitle(Uri.decode(extra));
1702 menu.findItem(R.id.dial_context_menu_id).setIntent(
1703 new Intent(Intent.ACTION_VIEW, Uri
1704 .parse(WebView.SCHEME_TEL + extra)));
1705 Intent addIntent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
1706 addIntent.putExtra(Insert.PHONE, Uri.decode(extra));
Cary Clark5e335a32009-09-22 14:53:11 -04001707 addIntent.setType(ContactsContract.Contacts.CONTENT_ITEM_TYPE);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001708 menu.findItem(R.id.add_contact_context_menu_id).setIntent(
1709 addIntent);
1710 menu.findItem(R.id.copy_phone_context_menu_id).setOnMenuItemClickListener(
1711 new Copy(extra));
1712 break;
1713
1714 case WebView.HitTestResult.EMAIL_TYPE:
1715 menu.setHeaderTitle(extra);
1716 menu.findItem(R.id.email_context_menu_id).setIntent(
1717 new Intent(Intent.ACTION_VIEW, Uri
1718 .parse(WebView.SCHEME_MAILTO + extra)));
1719 menu.findItem(R.id.copy_mail_context_menu_id).setOnMenuItemClickListener(
1720 new Copy(extra));
1721 break;
1722
1723 case WebView.HitTestResult.GEO_TYPE:
1724 menu.setHeaderTitle(extra);
1725 menu.findItem(R.id.map_context_menu_id).setIntent(
1726 new Intent(Intent.ACTION_VIEW, Uri
1727 .parse(WebView.SCHEME_GEO
1728 + URLEncoder.encode(extra))));
1729 menu.findItem(R.id.copy_geo_context_menu_id).setOnMenuItemClickListener(
1730 new Copy(extra));
1731 break;
1732
1733 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1734 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
1735 TextView titleView = (TextView) LayoutInflater.from(this)
1736 .inflate(android.R.layout.browser_link_context_header,
1737 null);
1738 titleView.setText(extra);
1739 menu.setHeaderView(titleView);
1740 // decide whether to show the open link in new tab option
Leon Scroggins III9e997c72010-05-26 13:25:16 -04001741 boolean showNewTab = mTabControl.canCreateNewTab();
1742 MenuItem newTabItem
1743 = menu.findItem(R.id.open_newtab_context_menu_id);
1744 newTabItem.setVisible(showNewTab);
1745 if (showNewTab) {
1746 newTabItem.setOnMenuItemClickListener(
1747 new MenuItem.OnMenuItemClickListener() {
1748 public boolean onMenuItemClick(MenuItem item) {
1749 final Tab parent = mTabControl.getCurrentTab();
Michael Kolb68792c82010-08-09 16:39:18 -07001750 final Tab newTab = openTab(extra, false);
Leon Scroggins III9e997c72010-05-26 13:25:16 -04001751 if (newTab != parent) {
1752 parent.addChildTab(newTab);
1753 }
1754 return true;
1755 }
1756 });
1757 }
Ben Murdochde353622009-10-12 10:29:00 +01001758 menu.findItem(R.id.bookmark_context_menu_id).setVisible(
1759 Bookmarks.urlHasAcceptableScheme(extra));
The Android Open Source Project0c908882009-03-03 19:32:16 -08001760 PackageManager pm = getPackageManager();
1761 Intent send = new Intent(Intent.ACTION_SEND);
1762 send.setType("text/plain");
1763 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1764 menu.findItem(R.id.share_link_context_menu_id).setVisible(ri != null);
1765 if (type == WebView.HitTestResult.SRC_ANCHOR_TYPE) {
1766 break;
1767 }
1768 // otherwise fall through to handle image part
1769 case WebView.HitTestResult.IMAGE_TYPE:
1770 if (type == WebView.HitTestResult.IMAGE_TYPE) {
1771 menu.setHeaderTitle(extra);
1772 }
1773 menu.findItem(R.id.view_image_context_menu_id).setIntent(
1774 new Intent(Intent.ACTION_VIEW, Uri.parse(extra)));
1775 menu.findItem(R.id.download_context_menu_id).
1776 setOnMenuItemClickListener(new Download(extra));
Ben Murdoch4f75ba22009-10-27 11:48:28 +00001777 menu.findItem(R.id.set_wallpaper_context_menu_id).
1778 setOnMenuItemClickListener(new SetAsWallpaper(extra));
The Android Open Source Project0c908882009-03-03 19:32:16 -08001779 break;
1780
1781 default:
1782 Log.w(LOGTAG, "We should not get here.");
1783 break;
1784 }
Leon Scrogginsb2b19f52009-10-09 16:10:00 -04001785 hideFakeTitleBar();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001786 }
1787
The Android Open Source Project0c908882009-03-03 19:32:16 -08001788 // Attach the given tab to the content view.
Grace Klobac928c302009-09-17 11:51:21 -07001789 // this should only be called for the current tab.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001790 private void attachTabToContentView(Tab t) {
Steve Block2bc69912009-07-30 14:45:13 +01001791 // Attach the container that contains the main WebView and any other UI
1792 // associated with the tab.
Patrick Scottd0119532009-09-17 08:00:31 -04001793 t.attachTabToContentView(mContentView);
Ben Murdochbff2d602009-07-01 20:19:05 +01001794
1795 if (mShouldShowErrorConsole) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001796 ErrorConsoleView errorConsole = t.getErrorConsole(true);
Ben Murdochbff2d602009-07-01 20:19:05 +01001797 if (errorConsole.numberOfErrors() == 0) {
1798 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
1799 } else {
1800 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
1801 }
1802
1803 mErrorConsoleContainer.addView(errorConsole,
Romain Guy15b8ec62010-01-08 15:06:43 -08001804 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
Ben Murdochbff2d602009-07-01 20:19:05 +01001805 ViewGroup.LayoutParams.WRAP_CONTENT));
1806 }
1807
Michael Kolba2b2ba82010-08-04 17:54:03 -07001808 WebView view = t.getWebView();
1809 view.setEmbeddedTitleBar(mTitleBar);
Leon Scroggins58d56c62010-01-28 15:12:40 -05001810 if (t.isInVoiceSearchMode()) {
1811 showVoiceTitleBar(t.getVoiceDisplayTitle());
1812 } else {
1813 revertVoiceTitleBar();
1814 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001815 // Request focus on the top window.
1816 t.getTopWindow().requestFocus();
Michael Kolba2b2ba82010-08-04 17:54:03 -07001817 if (mTabControl.getTabChangeListener() != null) {
1818 mTabControl.getTabChangeListener().onCurrentTab(t);
1819 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001820 }
1821
1822 // Attach a sub window to the main WebView of the given tab.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001823 void attachSubWindow(Tab t) {
Patrick Scottd0119532009-09-17 08:00:31 -04001824 t.attachSubWindow(mContentView);
1825 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001826 }
1827
1828 // Remove the given tab from the content view.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001829 private void removeTabFromContentView(Tab t) {
Steve Block2bc69912009-07-30 14:45:13 +01001830 // Remove the container that contains the main WebView.
Patrick Scottd0119532009-09-17 08:00:31 -04001831 t.removeTabFromContentView(mContentView);
Ben Murdochbff2d602009-07-01 20:19:05 +01001832
Grace Kloba22ac16e2009-10-07 18:00:23 -07001833 ErrorConsoleView errorConsole = t.getErrorConsole(false);
1834 if (errorConsole != null) {
1835 mErrorConsoleContainer.removeView(errorConsole);
Ben Murdochbff2d602009-07-01 20:19:05 +01001836 }
1837
Michael Kolba2b2ba82010-08-04 17:54:03 -07001838 WebView view = t.getWebView();
1839 if (view != null) {
1840 view.setEmbeddedTitleBar(null);
Leon Scrogginsbb85b902009-09-14 19:27:20 -04001841 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001842 }
1843
1844 // Remove the sub window if it exists. Also called by TabControl when the
1845 // user clicks the 'X' to dismiss a sub window.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001846 /* package */ void dismissSubWindow(Tab t) {
Patrick Scottd0119532009-09-17 08:00:31 -04001847 t.removeSubWindow(mContentView);
Grace Kloba22ac16e2009-10-07 18:00:23 -07001848 // dismiss the subwindow. This will destroy the WebView.
1849 t.dismissSubWindow();
Patrick Scottd0119532009-09-17 08:00:31 -04001850 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001851 }
1852
Leon Scroggins1f005d32009-08-10 17:36:42 -04001853 // A wrapper function of {@link #openTabAndShow(UrlData, boolean, String)}
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07001854 // that accepts url as string.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001855 private Tab openTabAndShow(String url, boolean closeOnExit, String appId) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001856 return openTabAndShow(new UrlData(url), closeOnExit, appId);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001857 }
1858
1859 // This method does a ton of stuff. It will attempt to create a new tab
1860 // if we haven't reached MAX_TABS. Otherwise it uses the current tab. If
Leon Scroggins1f005d32009-08-10 17:36:42 -04001861 // url isn't null, it will load the given url.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001862 /* package */Tab openTabAndShow(UrlData urlData, boolean closeOnExit,
1863 String appId) {
1864 final Tab currentTab = mTabControl.getCurrentTab();
1865 if (mTabControl.canCreateNewTab()) {
1866 final Tab tab = mTabControl.createNewTab(closeOnExit, appId,
Elliott Slaughterf0f03952010-07-14 18:10:36 -07001867 urlData.mUrl, false);
Leon Scroggins1f005d32009-08-10 17:36:42 -04001868 WebView webview = tab.getWebView();
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001869 // If the last tab was removed from the active tabs page, currentTab
1870 // will be null.
1871 if (currentTab != null) {
1872 removeTabFromContentView(currentTab);
1873 }
Patrick Scott8bbd69f2009-08-14 13:35:53 -04001874 // We must set the new tab as the current tab to reflect the old
1875 // animation behavior.
1876 mTabControl.setCurrentTab(tab);
Grace Klobaeb6eef42009-09-15 17:56:32 -07001877 attachTabToContentView(tab);
Leon Scroggins160a7e72009-08-14 18:28:01 -04001878 if (!urlData.isEmpty()) {
Patrick Scott9d53da02010-02-19 10:19:01 -05001879 loadUrlDataIn(tab, urlData);
Leon Scroggins1f005d32009-08-10 17:36:42 -04001880 }
1881 return tab;
1882 } else {
1883 // Get rid of the subwindow if it exists
1884 dismissSubWindow(currentTab);
1885 if (!urlData.isEmpty()) {
1886 // Load the given url.
Patrick Scott9d53da02010-02-19 10:19:01 -05001887 loadUrlDataIn(currentTab, urlData);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001888 }
Leon Scroggins58d56c62010-01-28 15:12:40 -05001889 return currentTab;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001890 }
1891 }
1892
Michael Kolb68792c82010-08-09 16:39:18 -07001893 private Tab openTab(String url, boolean forceForeground) {
1894 if (mSettings.openInBackground() && !forceForeground) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001895 Tab t = mTabControl.createNewTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001896 if (t != null) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001897 WebView view = t.getWebView();
Leon Scroggins92472e82010-02-17 16:32:28 -05001898 loadUrl(view, url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001899 }
Grace Klobac9181842009-04-14 08:53:22 -07001900 return t;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001901 } else {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001902 return openTabAndShow(url, false, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001903 }
1904 }
1905
Elliott Slaughterf0f03952010-07-14 18:10:36 -07001906 /* package */ Tab openIncognitoTab() {
1907 if (mTabControl.canCreateNewTab()) {
1908 Tab currentTab = mTabControl.getCurrentTab();
1909 Tab tab = mTabControl.createNewTab(false, null, null, true);
1910 if (currentTab != null) {
1911 removeTabFromContentView(currentTab);
1912 }
1913 mTabControl.setCurrentTab(tab);
1914 attachTabToContentView(tab);
1915 return tab;
1916 }
1917 return null;
1918 }
1919
The Android Open Source Project0c908882009-03-03 19:32:16 -08001920 private class Copy implements OnMenuItemClickListener {
1921 private CharSequence mText;
1922
1923 public boolean onMenuItemClick(MenuItem item) {
1924 copy(mText);
1925 return true;
1926 }
1927
1928 public Copy(CharSequence toCopy) {
1929 mText = toCopy;
1930 }
1931 }
1932
1933 private class Download implements OnMenuItemClickListener {
1934 private String mText;
1935
1936 public boolean onMenuItemClick(MenuItem item) {
1937 onDownloadStartNoStream(mText, null, null, null, -1);
1938 return true;
1939 }
1940
1941 public Download(String toDownload) {
1942 mText = toDownload;
1943 }
1944 }
1945
Ben Murdoch4f75ba22009-10-27 11:48:28 +00001946 private class SetAsWallpaper extends Thread implements
1947 OnMenuItemClickListener, DialogInterface.OnCancelListener {
1948 private URL mUrl;
1949 private ProgressDialog mWallpaperProgress;
1950 private boolean mCanceled = false;
1951
1952 public SetAsWallpaper(String url) {
1953 try {
1954 mUrl = new URL(url);
1955 } catch (MalformedURLException e) {
1956 mUrl = null;
1957 }
1958 }
1959
1960 public void onCancel(DialogInterface dialog) {
1961 mCanceled = true;
1962 }
1963
1964 public boolean onMenuItemClick(MenuItem item) {
1965 if (mUrl != null) {
1966 // The user may have tried to set a image with a large file size as their
1967 // background so it may take a few moments to perform the operation. Display
1968 // a progress spinner while it is working.
1969 mWallpaperProgress = new ProgressDialog(BrowserActivity.this);
1970 mWallpaperProgress.setIndeterminate(true);
1971 mWallpaperProgress.setMessage(getText(R.string.progress_dialog_setting_wallpaper));
1972 mWallpaperProgress.setCancelable(true);
1973 mWallpaperProgress.setOnCancelListener(this);
1974 mWallpaperProgress.show();
1975 start();
1976 }
1977 return true;
1978 }
1979
Michael Kolbe0a36662010-06-29 10:37:12 -07001980 @Override
Ben Murdoch4f75ba22009-10-27 11:48:28 +00001981 public void run() {
1982 Drawable oldWallpaper = BrowserActivity.this.getWallpaper();
1983 try {
1984 // TODO: This will cause the resource to be downloaded again, when we
1985 // should in most cases be able to grab it from the cache. To fix this
1986 // we should query WebCore to see if we can access a cached version and
1987 // instead open an input stream on that. This pattern could also be used
1988 // in the download manager where the same problem exists.
1989 InputStream inputstream = mUrl.openStream();
1990 if (inputstream != null) {
1991 setWallpaper(inputstream);
1992 }
1993 } catch (IOException e) {
1994 Log.e(LOGTAG, "Unable to set new wallpaper");
1995 // Act as though the user canceled the operation so we try to
1996 // restore the old wallpaper.
1997 mCanceled = true;
1998 }
1999
2000 if (mCanceled) {
2001 // Restore the old wallpaper if the user cancelled whilst we were setting
2002 // the new wallpaper.
2003 int width = oldWallpaper.getIntrinsicWidth();
2004 int height = oldWallpaper.getIntrinsicHeight();
2005 Bitmap bm = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
2006 Canvas canvas = new Canvas(bm);
2007 oldWallpaper.setBounds(0, 0, width, height);
2008 oldWallpaper.draw(canvas);
2009 try {
2010 setWallpaper(bm);
2011 } catch (IOException e) {
2012 Log.e(LOGTAG, "Unable to restore old wallpaper.");
2013 }
2014 mCanceled = false;
2015 }
2016
2017 if (mWallpaperProgress.isShowing()) {
2018 mWallpaperProgress.dismiss();
2019 }
2020 }
2021 }
2022
The Android Open Source Project0c908882009-03-03 19:32:16 -08002023 private void copy(CharSequence text) {
Dianne Hackborn80f32622010-08-05 14:17:53 -07002024 ClipboardManager cm = (ClipboardManager)getSystemService(Context.CLIPBOARD_SERVICE);
2025 cm.setText(text);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002026 }
2027
2028 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08002029 * Resets the browser title-view to whatever it must be
2030 * (for example, if we had a loading error)
2031 * When we have a new page, we call resetTitle, when we
2032 * have to reset the titlebar to whatever it used to be
2033 * (for example, if the user chose to stop loading), we
2034 * call resetTitleAndRevertLockIcon.
2035 */
2036 /* package */ void resetTitleAndRevertLockIcon() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002037 mTabControl.getCurrentTab().revertLockIcon();
2038 updateLockIconToLatest();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002039 resetTitleIconAndProgress();
2040 }
2041
2042 /**
2043 * Reset the title, favicon, and progress.
2044 */
2045 private void resetTitleIconAndProgress() {
2046 WebView current = mTabControl.getCurrentWebView();
2047 if (current == null) {
2048 return;
2049 }
2050 resetTitleAndIcon(current);
2051 int progress = current.getProgress();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002052 current.getWebChromeClient().onProgressChanged(current, progress);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002053 }
2054
2055 // Reset the title and the icon based on the given item.
2056 private void resetTitleAndIcon(WebView view) {
2057 WebHistoryItem item = view.copyBackForwardList().getCurrentItem();
2058 if (item != null) {
Leon Scroggins68579392009-09-15 15:31:54 -04002059 setUrlTitle(item.getUrl(), item.getTitle());
The Android Open Source Project0c908882009-03-03 19:32:16 -08002060 setFavicon(item.getFavicon());
2061 } else {
Leon Scroggins68579392009-09-15 15:31:54 -04002062 setUrlTitle(null, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002063 setFavicon(null);
2064 }
2065 }
2066
2067 /**
2068 * Sets a title composed of the URL and the title string.
2069 * @param url The URL of the site being loaded.
2070 * @param title The title of the site being loaded.
2071 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07002072 void setUrlTitle(String url, String title) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002073 mUrl = url;
2074 mTitle = title;
2075
Leon Scroggins58d56c62010-01-28 15:12:40 -05002076 // If we are in voice search mode, the title has already been set.
2077 if (mTabControl.getCurrentTab().isInVoiceSearchMode()) return;
2078 mTitleBar.setDisplayTitle(url);
Michael Kolba2b2ba82010-08-04 17:54:03 -07002079 mFakeTitleBar.setDisplayTitle(url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002080 }
2081
2082 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08002083 * @param url The URL to build a title version of the URL from.
2084 * @return The title version of the URL or null if fails.
2085 * The title version of the URL can be either the URL hostname,
2086 * or the hostname with an "https://" prefix (for secure URLs),
2087 * or an empty string if, for example, the URL in question is a
2088 * file:// URL with no hostname.
2089 */
Leon Scroggins32e14a62009-06-11 10:26:34 -04002090 /* package */ static String buildTitleUrl(String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002091 String titleUrl = null;
2092
2093 if (url != null) {
2094 try {
2095 // parse the url string
2096 URL urlObj = new URL(url);
2097 if (urlObj != null) {
2098 titleUrl = "";
2099
2100 String protocol = urlObj.getProtocol();
2101 String host = urlObj.getHost();
2102
2103 if (host != null && 0 < host.length()) {
2104 titleUrl = host;
2105 if (protocol != null) {
2106 // if a secure site, add an "https://" prefix!
2107 if (protocol.equalsIgnoreCase("https")) {
2108 titleUrl = protocol + "://" + host;
2109 }
2110 }
2111 }
2112 }
2113 } catch (MalformedURLException e) {}
2114 }
2115
2116 return titleUrl;
2117 }
2118
2119 // Set the favicon in the title bar.
Grace Kloba22ac16e2009-10-07 18:00:23 -07002120 void setFavicon(Bitmap icon) {
Leon Scroggins68579392009-09-15 15:31:54 -04002121 mTitleBar.setFavicon(icon);
Michael Kolba2b2ba82010-08-04 17:54:03 -07002122 mFakeTitleBar.setFavicon(icon);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002123 }
2124
2125 /**
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002126 * Close the tab, remove its associated title bar, and adjust mTabControl's
2127 * current tab to a valid value.
Leon Scroggins1f005d32009-08-10 17:36:42 -04002128 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07002129 /* package */ void closeTab(Tab t) {
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002130 int currentIndex = mTabControl.getCurrentIndex();
2131 int removeIndex = mTabControl.getTabIndex(t);
Leon Scroggins1f005d32009-08-10 17:36:42 -04002132 mTabControl.removeTab(t);
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002133 if (currentIndex >= removeIndex && currentIndex != 0) {
2134 currentIndex--;
2135 }
2136 mTabControl.setCurrentTab(mTabControl.getTab(currentIndex));
Andrei Popescua5bf1de2009-09-23 16:39:23 +01002137 resetTitleIconAndProgress();
Leon Scroggins654899b2010-06-25 16:25:23 -04002138 updateLockIconToLatest();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002139 }
2140
Leon Scrogginsdcc5eeb2010-02-23 17:26:37 -05002141 /* package */ void goBackOnePageOrQuit() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002142 Tab current = mTabControl.getCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002143 if (current == null) {
2144 /*
2145 * Instead of finishing the activity, simply push this to the back
2146 * of the stack and let ActivityManager to choose the foreground
2147 * activity. As BrowserActivity is singleTask, it will be always the
2148 * root of the task. So we can use either true or false for
2149 * moveTaskToBack().
2150 */
2151 moveTaskToBack(true);
Grace Kloba00d85e72009-09-23 18:50:05 -07002152 return;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002153 }
2154 WebView w = current.getWebView();
2155 if (w.canGoBack()) {
2156 w.goBack();
2157 } else {
2158 // Check to see if we are closing a window that was created by
2159 // another window. If so, we switch back to that window.
Grace Kloba22ac16e2009-10-07 18:00:23 -07002160 Tab parent = current.getParentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002161 if (parent != null) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04002162 switchToTab(mTabControl.getTabIndex(parent));
2163 // Now we close the other tab
2164 closeTab(current);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002165 } else {
2166 if (current.closeOnExit()) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002167 // force the tab's inLoad() to be false as we are going to
2168 // either finish the activity or remove the tab. This will
2169 // ensure pauseWebViewTimers() taking action.
2170 mTabControl.getCurrentTab().clearInLoad();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002171 if (mTabControl.getTabCount() == 1) {
2172 finish();
2173 return;
2174 }
Mike Reed7bfa63b2009-05-28 11:08:32 -04002175 // call pauseWebViewTimers() now, we won't be able to call
2176 // it in onPause() as the WebView won't be valid.
Grace Klobaec1b5ad2009-08-18 08:42:32 -07002177 // Temporarily change mActivityInPause to be true as
2178 // pauseWebViewTimers() will do nothing if mActivityInPause
2179 // is false.
Grace Kloba918e1d72009-08-13 14:55:06 -07002180 boolean savedState = mActivityInPause;
2181 if (savedState) {
Grace Klobaec1b5ad2009-08-18 08:42:32 -07002182 Log.e(LOGTAG, "BrowserActivity is already paused "
2183 + "while handing goBackOnePageOrQuit.");
Grace Kloba918e1d72009-08-13 14:55:06 -07002184 }
2185 mActivityInPause = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -04002186 pauseWebViewTimers();
Grace Kloba918e1d72009-08-13 14:55:06 -07002187 mActivityInPause = savedState;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002188 removeTabFromContentView(current);
2189 mTabControl.removeTab(current);
2190 }
2191 /*
2192 * Instead of finishing the activity, simply push this to the back
2193 * of the stack and let ActivityManager to choose the foreground
2194 * activity. As BrowserActivity is singleTask, it will be always the
2195 * root of the task. So we can use either true or false for
2196 * moveTaskToBack().
2197 */
2198 moveTaskToBack(true);
2199 }
2200 }
2201 }
2202
Grace Kloba22ac16e2009-10-07 18:00:23 -07002203 boolean isMenuDown() {
2204 return mMenuIsDown;
2205 }
2206
Grace Kloba5942df02009-09-18 11:48:29 -07002207 @Override
2208 public boolean onKeyDown(int keyCode, KeyEvent event) {
Leon Scrogginsf65b50d2009-12-08 10:44:28 -05002209 // Even if MENU is already held down, we need to call to super to open
2210 // the IME on long press.
2211 if (KeyEvent.KEYCODE_MENU == keyCode) {
2212 mMenuIsDown = true;
2213 return super.onKeyDown(keyCode, event);
2214 }
Grace Kloba5942df02009-09-18 11:48:29 -07002215 // The default key mode is DEFAULT_KEYS_SEARCH_LOCAL. As the MENU is
2216 // still down, we don't want to trigger the search. Pretend to consume
2217 // the key and do nothing.
2218 if (mMenuIsDown) return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002219
Grace Kloba5942df02009-09-18 11:48:29 -07002220 switch(keyCode) {
Grace Kloba5942df02009-09-18 11:48:29 -07002221 case KeyEvent.KEYCODE_SPACE:
Grace Klobada0fe552009-09-22 18:17:24 -07002222 // WebView/WebTextView handle the keys in the KeyDown. As
2223 // the Activity's shortcut keys are only handled when WebView
2224 // doesn't, have to do it in onKeyDown instead of onKeyUp.
2225 if (event.isShiftPressed()) {
2226 getTopWindow().pageUp(false);
2227 } else {
2228 getTopWindow().pageDown(false);
2229 }
Grace Kloba5942df02009-09-18 11:48:29 -07002230 return true;
2231 case KeyEvent.KEYCODE_BACK:
2232 if (event.getRepeatCount() == 0) {
2233 event.startTracking();
2234 return true;
2235 } else if (mCustomView == null && mActiveTabsPage == null
2236 && event.isLongPress()) {
Michael Kolb68792c82010-08-09 16:39:18 -07002237 bookmarksOrHistoryPicker(true, false);
Grace Kloba5942df02009-09-18 11:48:29 -07002238 return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002239 }
Grace Kloba5942df02009-09-18 11:48:29 -07002240 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002241 }
Grace Kloba5942df02009-09-18 11:48:29 -07002242 return super.onKeyDown(keyCode, event);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002243 }
2244
Grace Kloba5942df02009-09-18 11:48:29 -07002245 @Override
2246 public boolean onKeyUp(int keyCode, KeyEvent event) {
2247 switch(keyCode) {
2248 case KeyEvent.KEYCODE_MENU:
2249 mMenuIsDown = false;
2250 break;
Grace Kloba5942df02009-09-18 11:48:29 -07002251 case KeyEvent.KEYCODE_BACK:
2252 if (event.isTracking() && !event.isCanceled()) {
2253 if (mCustomView != null) {
2254 // if a custom view is showing, hide it
Grace Kloba22ac16e2009-10-07 18:00:23 -07002255 mTabControl.getCurrentWebView().getWebChromeClient()
2256 .onHideCustomView();
Grace Kloba5942df02009-09-18 11:48:29 -07002257 } else if (mActiveTabsPage != null) {
2258 // if tab page is showing, hide it
2259 removeActiveTabPage(true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002260 } else {
Grace Kloba5942df02009-09-18 11:48:29 -07002261 WebView subwindow = mTabControl.getCurrentSubWindow();
2262 if (subwindow != null) {
2263 if (subwindow.canGoBack()) {
2264 subwindow.goBack();
2265 } else {
2266 dismissSubWindow(mTabControl.getCurrentTab());
2267 }
2268 } else {
2269 goBackOnePageOrQuit();
2270 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002271 }
Grace Kloba5942df02009-09-18 11:48:29 -07002272 return true;
2273 }
2274 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002275 }
Grace Kloba5942df02009-09-18 11:48:29 -07002276 return super.onKeyUp(keyCode, event);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002277 }
2278
Leon Scroggins68579392009-09-15 15:31:54 -04002279 /* package */ void stopLoading() {
Ben Murdochb7cc8b42009-09-28 10:59:09 +01002280 mDidStopLoad = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002281 resetTitleAndRevertLockIcon();
2282 WebView w = getTopWindow();
2283 w.stopLoading();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002284 // FIXME: before refactor, it is using mWebViewClient. So I keep the
2285 // same logic here. But for subwindow case, should we call into the main
2286 // WebView's onPageFinished as we never call its onPageStarted and if
2287 // the page finishes itself, we don't call onPageFinished.
2288 mTabControl.getCurrentWebView().getWebViewClient().onPageFinished(w,
2289 w.getUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08002290
2291 cancelStopToast();
2292 mStopToast = Toast
2293 .makeText(this, R.string.stopping, Toast.LENGTH_SHORT);
2294 mStopToast.show();
2295 }
2296
Grace Kloba22ac16e2009-10-07 18:00:23 -07002297 boolean didUserStopLoading() {
2298 return mDidStopLoad;
2299 }
2300
The Android Open Source Project0c908882009-03-03 19:32:16 -08002301 private void cancelStopToast() {
2302 if (mStopToast != null) {
2303 mStopToast.cancel();
2304 mStopToast = null;
2305 }
2306 }
2307
Grace Kloba22ac16e2009-10-07 18:00:23 -07002308 // called by a UI or non-UI thread to post the message
2309 public void postMessage(int what, int arg1, int arg2, Object obj,
2310 long delayMillis) {
2311 mHandler.sendMessageDelayed(mHandler.obtainMessage(what, arg1, arg2,
2312 obj), delayMillis);
2313 }
2314
2315 // called by a UI or non-UI thread to remove the message
2316 void removeMessages(int what, Object object) {
2317 mHandler.removeMessages(what, object);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002318 }
2319
2320 // public message ids
2321 public final static int LOAD_URL = 1001;
2322 public final static int STOP_LOAD = 1002;
2323
2324 // Message Ids
2325 private static final int FOCUS_NODE_HREF = 102;
Grace Kloba92c18a52009-07-31 23:48:32 -07002326 private static final int RELEASE_WAKELOCK = 107;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002327
Grace Kloba22ac16e2009-10-07 18:00:23 -07002328 static final int UPDATE_BOOKMARK_THUMBNAIL = 108;
Ben Murdoch2694e232009-09-29 09:41:11 +01002329
Ben Murdocheecb4e62010-07-06 16:30:38 +01002330 private static final int TOUCH_ICON_DOWNLOADED = 109;
2331
Michael Kolb300b7f02010-08-25 13:47:24 -07002332 private static final int OPEN_BOOKMARKS = 201;
2333
The Android Open Source Project0c908882009-03-03 19:32:16 -08002334 // Private handler for handling javascript and saving passwords
2335 private Handler mHandler = new Handler() {
2336
Michael Kolbe0a36662010-06-29 10:37:12 -07002337 @Override
The Android Open Source Project0c908882009-03-03 19:32:16 -08002338 public void handleMessage(Message msg) {
2339 switch (msg.what) {
Michael Kolb300b7f02010-08-25 13:47:24 -07002340 case OPEN_BOOKMARKS:
2341 bookmarksOrHistoryPicker(false, false);
2342 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002343 case FOCUS_NODE_HREF:
Ben Murdoch2694e232009-09-29 09:41:11 +01002344 {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002345 String url = (String) msg.getData().get("url");
Ben Murdoch90d088c2009-11-17 18:14:04 +00002346 String title = (String) msg.getData().get("title");
The Android Open Source Project0c908882009-03-03 19:32:16 -08002347 if (url == null || url.length() == 0) {
2348 break;
2349 }
2350 HashMap focusNodeMap = (HashMap) msg.obj;
2351 WebView view = (WebView) focusNodeMap.get("webview");
2352 // Only apply the action if the top window did not change.
2353 if (getTopWindow() != view) {
2354 break;
2355 }
2356 switch (msg.arg1) {
2357 case R.id.open_context_menu_id:
2358 case R.id.view_image_context_menu_id:
Leon Scroggins92472e82010-02-17 16:32:28 -05002359 loadUrlFromContext(getTopWindow(), url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002360 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002361 case R.id.bookmark_context_menu_id:
2362 Intent intent = new Intent(BrowserActivity.this,
2363 AddBookmarkPage.class);
2364 intent.putExtra("url", url);
Ben Murdoch90d088c2009-11-17 18:14:04 +00002365 intent.putExtra("title", title);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002366 startActivity(intent);
2367 break;
2368 case R.id.share_link_context_menu_id:
Leon Scroggins3e204452010-05-10 11:06:03 -04002369 sharePage(BrowserActivity.this, title, url, null,
Leon Scroggins96afcb12009-12-10 12:35:56 -05002370 null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002371 break;
2372 case R.id.copy_link_context_menu_id:
2373 copy(url);
2374 break;
2375 case R.id.save_link_context_menu_id:
2376 case R.id.download_context_menu_id:
2377 onDownloadStartNoStream(url, null, null, null, -1);
2378 break;
2379 }
2380 break;
Ben Murdoch2694e232009-09-29 09:41:11 +01002381 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002382
2383 case LOAD_URL:
Leon Scroggins92472e82010-02-17 16:32:28 -05002384 loadUrlFromContext(getTopWindow(), (String) msg.obj);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002385 break;
2386
2387 case STOP_LOAD:
2388 stopLoading();
2389 break;
2390
The Android Open Source Project0c908882009-03-03 19:32:16 -08002391 case RELEASE_WAKELOCK:
2392 if (mWakeLock.isHeld()) {
2393 mWakeLock.release();
Grace Kloba5d0e02e2009-10-05 15:15:36 -07002394 // if we reach here, Browser should be still in the
2395 // background loading after WAKELOCK_TIMEOUT (5-min).
2396 // To avoid burning the battery, stop loading.
2397 mTabControl.stopAllLoading();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002398 }
2399 break;
Ben Murdoch2694e232009-09-29 09:41:11 +01002400
2401 case UPDATE_BOOKMARK_THUMBNAIL:
2402 WebView view = (WebView) msg.obj;
2403 if (view != null) {
2404 updateScreenshot(view);
2405 }
2406 break;
Ben Murdocheecb4e62010-07-06 16:30:38 +01002407
2408 case TOUCH_ICON_DOWNLOADED:
2409 Bundle b = msg.getData();
2410 showSaveToHomescreenDialog(b.getString("url"),
2411 b.getString("title"),
2412 (Bitmap) b.getParcelable("touchIcon"),
2413 (Bitmap) b.getParcelable("favicon"));
2414 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002415 }
2416 }
2417 };
2418
Leon Scroggins96afcb12009-12-10 12:35:56 -05002419 /**
2420 * Share a page, providing the title, url, favicon, and a screenshot. Uses
2421 * an {@link Intent} to launch the Activity chooser.
2422 * @param c Context used to launch a new Activity.
2423 * @param title Title of the page. Stored in the Intent with
Paul Westbrook03e6d392010-02-12 10:33:29 -08002424 * {@link Intent#EXTRA_SUBJECT}
Leon Scroggins96afcb12009-12-10 12:35:56 -05002425 * @param url URL of the page. Stored in the Intent with
2426 * {@link Intent#EXTRA_TEXT}
2427 * @param favicon Bitmap of the favicon for the page. Stored in the Intent
2428 * with {@link Browser#EXTRA_SHARE_FAVICON}
2429 * @param screenshot Bitmap of a screenshot of the page. Stored in the
2430 * Intent with {@link Browser#EXTRA_SHARE_SCREENSHOT}
2431 */
2432 public static final void sharePage(Context c, String title, String url,
2433 Bitmap favicon, Bitmap screenshot) {
2434 Intent send = new Intent(Intent.ACTION_SEND);
2435 send.setType("text/plain");
2436 send.putExtra(Intent.EXTRA_TEXT, url);
Paul Westbrook03e6d392010-02-12 10:33:29 -08002437 send.putExtra(Intent.EXTRA_SUBJECT, title);
Leon Scroggins96afcb12009-12-10 12:35:56 -05002438 send.putExtra(Browser.EXTRA_SHARE_FAVICON, favicon);
2439 send.putExtra(Browser.EXTRA_SHARE_SCREENSHOT, screenshot);
2440 try {
2441 c.startActivity(Intent.createChooser(send, c.getString(
2442 R.string.choosertitle_sharevia)));
2443 } catch(android.content.ActivityNotFoundException ex) {
2444 // if no app handles it, do nothing
2445 }
2446 }
2447
Leon Scroggins89c6d362009-07-15 16:54:37 -04002448 private void updateScreenshot(WebView view) {
2449 // If this is a bookmarked site, add a screenshot to the database.
2450 // FIXME: When should we update? Every time?
2451 // FIXME: Would like to make sure there is actually something to
2452 // draw, but the API for that (WebViewCore.pictureReady()) is not
2453 // currently accessible here.
Ben Murdochaac7aa62009-09-17 16:57:40 +01002454
Ben Murdoch87cc65d2010-06-29 20:34:10 +01002455 final Bitmap bm = createScreenshot(view, getDesiredThumbnailWidth(this),
2456 getDesiredThumbnailHeight(this));
Patrick Scottcb192b52010-04-14 14:38:55 -04002457 if (bm == null) {
2458 return;
Leon Scroggins89c6d362009-07-15 16:54:37 -04002459 }
Patrick Scottcb192b52010-04-14 14:38:55 -04002460
2461 final ContentResolver cr = getContentResolver();
2462 final String url = view.getUrl();
2463 final String originalUrl = view.getOriginalUrl();
2464
2465 new AsyncTask<Void, Void, Void>() {
2466 @Override
2467 protected Void doInBackground(Void... unused) {
2468 Cursor c = null;
2469 try {
Jeff Hamilton84029622010-08-05 14:29:28 -05002470 c = Bookmarks.queryBookmarksForUrl(
Jeff Hamilton8ce956c2010-08-17 11:13:53 -05002471 cr, originalUrl, url);
Patrick Scottcb192b52010-04-14 14:38:55 -04002472 if (c != null) {
2473 if (c.moveToFirst()) {
2474 ContentValues values = new ContentValues();
2475 final ByteArrayOutputStream os
2476 = new ByteArrayOutputStream();
2477 bm.compress(Bitmap.CompressFormat.PNG, 100, os);
Jeff Hamilton8ce956c2010-08-17 11:13:53 -05002478 values.put(BrowserContract.Bookmarks.THUMBNAIL,
Patrick Scottcb192b52010-04-14 14:38:55 -04002479 os.toByteArray());
2480 do {
2481 cr.update(ContentUris.withAppendedId(
Jeff Hamilton8ce956c2010-08-17 11:13:53 -05002482 BrowserContract.Bookmarks.CONTENT_URI, c.getLong(0)),
Patrick Scottcb192b52010-04-14 14:38:55 -04002483 values, null, null);
2484 } while (c.moveToNext());
2485 }
2486 }
2487 } catch (IllegalStateException e) {
2488 // Ignore
2489 } finally {
2490 if (c != null) c.close();
2491 }
2492 return null;
2493 }
2494 }.execute();
Leon Scroggins89c6d362009-07-15 16:54:37 -04002495 }
2496
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002497 /**
Leon Scrogginsf8551612009-09-24 16:06:02 -04002498 * Values for the size of the thumbnail created when taking a screenshot.
2499 * Lazily initialized. Instead of using these directly, use
2500 * getDesiredThumbnailWidth() or getDesiredThumbnailHeight().
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002501 */
Leon Scrogginsf8551612009-09-24 16:06:02 -04002502 private static int THUMBNAIL_WIDTH = 0;
2503 private static int THUMBNAIL_HEIGHT = 0;
2504
2505 /**
2506 * Return the desired width for thumbnail screenshots, which are stored in
2507 * the database, and used on the bookmarks screen.
2508 * @param context Context for finding out the density of the screen.
2509 * @return int desired width for thumbnail screenshot.
2510 */
2511 /* package */ static int getDesiredThumbnailWidth(Context context) {
2512 if (THUMBNAIL_WIDTH == 0) {
2513 float density = context.getResources().getDisplayMetrics().density;
2514 THUMBNAIL_WIDTH = (int) (90 * density);
2515 THUMBNAIL_HEIGHT = (int) (80 * density);
2516 }
2517 return THUMBNAIL_WIDTH;
2518 }
2519
2520 /**
2521 * Return the desired height for thumbnail screenshots, which are stored in
2522 * the database, and used on the bookmarks screen.
2523 * @param context Context for finding out the density of the screen.
2524 * @return int desired height for thumbnail screenshot.
2525 */
2526 /* package */ static int getDesiredThumbnailHeight(Context context) {
2527 // To ensure that they are both initialized.
2528 getDesiredThumbnailWidth(context);
2529 return THUMBNAIL_HEIGHT;
2530 }
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002531
Ben Murdoch87cc65d2010-06-29 20:34:10 +01002532 private Bitmap createScreenshot(WebView view, int width, int height) {
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002533 Picture thumbnail = view.capturePicture();
Leon Scroggins45800572009-09-29 16:38:47 -04002534 if (thumbnail == null) {
2535 return null;
2536 }
Ben Murdoch87cc65d2010-06-29 20:34:10 +01002537 Bitmap bm = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002538 Canvas canvas = new Canvas(bm);
2539 // May need to tweak these values to determine what is the
2540 // best scale factor
Ben Murdoch2694e232009-09-29 09:41:11 +01002541 int thumbnailWidth = thumbnail.getWidth();
Ben Murdochae59c3f2009-10-20 18:30:28 +01002542 int thumbnailHeight = thumbnail.getHeight();
2543 float scaleFactorX = 1.0f;
2544 float scaleFactorY = 1.0f;
Ben Murdoch2694e232009-09-29 09:41:11 +01002545 if (thumbnailWidth > 0) {
Ben Murdoch87cc65d2010-06-29 20:34:10 +01002546 scaleFactorX = (float) width / (float)thumbnailWidth;
Ben Murdochae59c3f2009-10-20 18:30:28 +01002547 } else {
2548 return null;
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002549 }
Ben Murdochae59c3f2009-10-20 18:30:28 +01002550
2551 if (view.getWidth() > view.getHeight() &&
2552 thumbnailHeight < view.getHeight() && thumbnailHeight > 0) {
2553 // If the device is in landscape and the page is shorter
2554 // than the height of the view, stretch the thumbnail to fill the
2555 // space.
Ben Murdoch87cc65d2010-06-29 20:34:10 +01002556 scaleFactorY = (float) height / (float)thumbnailHeight;
Ben Murdochae59c3f2009-10-20 18:30:28 +01002557 } else {
2558 // In the portrait case, this looks nice.
2559 scaleFactorY = scaleFactorX;
2560 }
2561
2562 canvas.scale(scaleFactorX, scaleFactorY);
2563
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002564 thumbnail.draw(canvas);
2565 return bm;
2566 }
2567
The Android Open Source Project0c908882009-03-03 19:32:16 -08002568 // -------------------------------------------------------------------------
Grace Kloba22ac16e2009-10-07 18:00:23 -07002569 // Helper function for WebViewClient.
The Android Open Source Project0c908882009-03-03 19:32:16 -08002570 //-------------------------------------------------------------------------
2571
2572 // Use in overrideUrlLoading
2573 /* package */ final static String SCHEME_WTAI = "wtai://wp/";
2574 /* package */ final static String SCHEME_WTAI_MC = "wtai://wp/mc;";
2575 /* package */ final static String SCHEME_WTAI_SD = "wtai://wp/sd;";
2576 /* package */ final static String SCHEME_WTAI_AP = "wtai://wp/ap;";
2577
Leon Scroggins92472e82010-02-17 16:32:28 -05002578 // Keep this initial progress in sync with initialProgressValue (* 100)
2579 // in ProgressTracker.cpp
2580 private final static int INITIAL_PROGRESS = 10;
2581
Grace Kloba22ac16e2009-10-07 18:00:23 -07002582 void onPageStarted(WebView view, String url, Bitmap favicon) {
2583 // when BrowserActivity just starts, onPageStarted may be called before
2584 // onResume as it is triggered from onCreate. Call resumeWebViewTimers
2585 // to start the timer. As we won't switch tabs while an activity is in
2586 // pause state, we can ensure calling resume and pause in pair.
2587 if (mActivityInPause) resumeWebViewTimers();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002588
Grace Kloba22ac16e2009-10-07 18:00:23 -07002589 resetLockIcon(url);
2590 setUrlTitle(url, null);
2591 setFavicon(favicon);
Leon Scroggins8cf8f682009-11-04 11:13:50 -08002592 // Show some progress so that the user knows the page is beginning to
2593 // load
Leon Scroggins92472e82010-02-17 16:32:28 -05002594 onProgressChanged(view, INITIAL_PROGRESS);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002595 mDidStopLoad = false;
Grace Kloba22ac16e2009-10-07 18:00:23 -07002596 if (!mIsNetworkUp) createAndShowNetworkDialog();
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04002597 endActionMode();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002598 if (mSettings.isTracing()) {
2599 String host;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002600 try {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002601 WebAddress uri = new WebAddress(url);
2602 host = uri.mHost;
2603 } catch (android.net.ParseException ex) {
2604 host = "browser";
The Android Open Source Project0c908882009-03-03 19:32:16 -08002605 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002606 host = host.replace('.', '_');
2607 host += ".trace";
2608 mInTrace = true;
2609 Debug.startMethodTracing(host, 20 * 1024 * 1024);
2610 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002611
Grace Kloba22ac16e2009-10-07 18:00:23 -07002612 // Performance probe
2613 if (false) {
2614 mStart = SystemClock.uptimeMillis();
2615 mProcessStart = Process.getElapsedCpuTime();
2616 long[] sysCpu = new long[7];
2617 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2618 sysCpu, null)) {
2619 mUserStart = sysCpu[0] + sysCpu[1];
2620 mSystemStart = sysCpu[2];
2621 mIdleStart = sysCpu[3];
2622 mIrqStart = sysCpu[4] + sysCpu[5] + sysCpu[6];
2623 }
2624 mUiStart = SystemClock.currentThreadTimeMillis();
2625 }
2626 }
2627
2628 void onPageFinished(WebView view, String url) {
2629 // Reset the title and icon in case we stopped a provisional load.
2630 resetTitleAndIcon(view);
2631 // Update the lock icon image only once we are done loading
2632 updateLockIconToLatest();
2633 // pause the WebView timer and release the wake lock if it is finished
2634 // while BrowserActivity is in pause state.
2635 if (mActivityInPause && pauseWebViewTimers()) {
2636 if (mWakeLock.isHeld()) {
2637 mHandler.removeMessages(RELEASE_WAKELOCK);
2638 mWakeLock.release();
2639 }
2640 }
2641
2642 // Performance probe
2643 if (false) {
2644 long[] sysCpu = new long[7];
2645 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2646 sysCpu, null)) {
2647 String uiInfo = "UI thread used "
2648 + (SystemClock.currentThreadTimeMillis() - mUiStart)
2649 + " ms";
2650 if (LOGD_ENABLED) {
2651 Log.d(LOGTAG, uiInfo);
2652 }
2653 //The string that gets written to the log
2654 String performanceString = "It took total "
2655 + (SystemClock.uptimeMillis() - mStart)
2656 + " ms clock time to load the page."
2657 + "\nbrowser process used "
2658 + (Process.getElapsedCpuTime() - mProcessStart)
2659 + " ms, user processes used "
2660 + (sysCpu[0] + sysCpu[1] - mUserStart) * 10
2661 + " ms, kernel used "
2662 + (sysCpu[2] - mSystemStart) * 10
2663 + " ms, idle took " + (sysCpu[3] - mIdleStart) * 10
2664 + " ms and irq took "
2665 + (sysCpu[4] + sysCpu[5] + sysCpu[6] - mIrqStart)
2666 * 10 + " ms, " + uiInfo;
2667 if (LOGD_ENABLED) {
2668 Log.d(LOGTAG, performanceString + "\nWebpage: " + url);
2669 }
2670 if (url != null) {
2671 // strip the url to maintain consistency
2672 String newUrl = new String(url);
2673 if (newUrl.startsWith("http://www.")) {
2674 newUrl = newUrl.substring(11);
2675 } else if (newUrl.startsWith("http://")) {
2676 newUrl = newUrl.substring(7);
2677 } else if (newUrl.startsWith("https://www.")) {
2678 newUrl = newUrl.substring(12);
2679 } else if (newUrl.startsWith("https://")) {
2680 newUrl = newUrl.substring(8);
2681 }
2682 if (LOGD_ENABLED) {
2683 Log.d(LOGTAG, newUrl + " loaded");
2684 }
Grace Kloba5b078b52009-06-24 20:23:41 -07002685 }
2686 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002687 }
Grace Kloba5b078b52009-06-24 20:23:41 -07002688
Grace Kloba22ac16e2009-10-07 18:00:23 -07002689 if (mInTrace) {
2690 mInTrace = false;
2691 Debug.stopMethodTracing();
2692 }
2693 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002694
Grace Klobae7fe26b2010-06-28 16:23:33 -07002695 private void closeEmptyChildTab() {
2696 Tab current = mTabControl.getCurrentTab();
2697 if (current != null
2698 && current.getWebView().copyBackForwardList().getSize() == 0) {
2699 Tab parent = current.getParentTab();
2700 if (parent != null) {
2701 switchToTab(mTabControl.getTabIndex(parent));
2702 closeTab(current);
2703 }
2704 }
2705 }
2706
Grace Kloba22ac16e2009-10-07 18:00:23 -07002707 boolean shouldOverrideUrlLoading(WebView view, String url) {
2708 if (url.startsWith(SCHEME_WTAI)) {
2709 // wtai://wp/mc;number
2710 // number=string(phone-number)
2711 if (url.startsWith(SCHEME_WTAI_MC)) {
2712 Intent intent = new Intent(Intent.ACTION_VIEW,
2713 Uri.parse(WebView.SCHEME_TEL +
2714 url.substring(SCHEME_WTAI_MC.length())));
2715 startActivity(intent);
Grace Klobae7fe26b2010-06-28 16:23:33 -07002716 // before leaving BrowserActivity, close the empty child tab.
2717 // If a new tab is created through JavaScript open to load this
2718 // url, we would like to close it as we will load this url in a
2719 // different Activity.
2720 closeEmptyChildTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002721 return true;
2722 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002723 // wtai://wp/sd;dtmf
2724 // dtmf=string(dialstring)
2725 if (url.startsWith(SCHEME_WTAI_SD)) {
2726 // TODO: only send when there is active voice connection
2727 return false;
2728 }
2729 // wtai://wp/ap;number;name
2730 // number=string(phone-number)
2731 // name=string
2732 if (url.startsWith(SCHEME_WTAI_AP)) {
2733 // TODO
2734 return false;
2735 }
2736 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002737
Grace Kloba22ac16e2009-10-07 18:00:23 -07002738 // The "about:" schemes are internal to the browser; don't want these to
2739 // be dispatched to other apps.
2740 if (url.startsWith("about:")) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002741 return false;
2742 }
2743
Jeff Davidson43610292010-07-16 16:03:58 -07002744 // If this is a Google search, attempt to add an RLZ string (if one isn't already present).
2745 if (rlzProviderPresent()) {
2746 Uri siteUri = Uri.parse(url);
2747 if (needsRlzString(siteUri)) {
2748 String rlz = null;
2749 Cursor cur = null;
2750 try {
2751 cur = getContentResolver().query(getRlzUri(), null, null, null, null);
2752 if (cur != null && cur.moveToFirst() && !cur.isNull(0)) {
2753 url = siteUri.buildUpon()
2754 .appendQueryParameter("rlz", cur.getString(0))
2755 .build().toString();
2756 }
2757 } finally {
2758 if (cur != null) {
2759 cur.close();
2760 }
2761 }
2762 loadUrl(view, url);
2763 return true;
2764 }
2765 }
2766
Grace Kloba22ac16e2009-10-07 18:00:23 -07002767 Intent intent;
2768 // perform generic parsing of the URI to turn it into an Intent.
2769 try {
2770 intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME);
2771 } catch (URISyntaxException ex) {
2772 Log.w("Browser", "Bad URI " + url + ": " + ex.getMessage());
2773 return false;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002774 }
2775
Grace Kloba22ac16e2009-10-07 18:00:23 -07002776 // check whether the intent can be resolved. If not, we will see
2777 // whether we can download it from the Market.
2778 if (getPackageManager().resolveActivity(intent, 0) == null) {
2779 String packagename = intent.getPackage();
2780 if (packagename != null) {
2781 intent = new Intent(Intent.ACTION_VIEW, Uri
2782 .parse("market://search?q=pname:" + packagename));
2783 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2784 startActivity(intent);
Grace Klobae7fe26b2010-06-28 16:23:33 -07002785 // before leaving BrowserActivity, close the empty child tab.
2786 // If a new tab is created through JavaScript open to load this
2787 // url, we would like to close it as we will load this url in a
2788 // different Activity.
2789 closeEmptyChildTab();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002790 return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002791 } else {
2792 return false;
2793 }
2794 }
2795
Grace Kloba22ac16e2009-10-07 18:00:23 -07002796 // sanitize the Intent, ensuring web pages can not bypass browser
2797 // security (only access to BROWSABLE activities).
2798 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2799 intent.setComponent(null);
2800 try {
2801 if (startActivityIfNeeded(intent, -1)) {
Grace Klobae7fe26b2010-06-28 16:23:33 -07002802 // before leaving BrowserActivity, close the empty child tab.
2803 // If a new tab is created through JavaScript open to load this
2804 // url, we would like to close it as we will load this url in a
2805 // different Activity.
2806 closeEmptyChildTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002807 return true;
2808 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002809 } catch (ActivityNotFoundException ex) {
2810 // ignore the error. If no application can handle the URL,
2811 // eg about:blank, assume the browser can handle it.
2812 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002813
Grace Kloba22ac16e2009-10-07 18:00:23 -07002814 if (mMenuIsDown) {
Michael Kolb68792c82010-08-09 16:39:18 -07002815 openTab(url, false);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002816 closeOptionsMenu();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002817 return true;
2818 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002819 return false;
2820 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002821
Jeff Davidson43610292010-07-16 16:03:58 -07002822 // Determine whether the RLZ provider is present on the system.
2823 private boolean rlzProviderPresent() {
2824 if (mIsProviderPresent == null) {
2825 PackageManager pm = getPackageManager();
2826 mIsProviderPresent = pm.resolveContentProvider(BrowserSettings.RLZ_PROVIDER, 0) != null;
2827 }
2828 return mIsProviderPresent;
2829 }
2830
2831 // Retrieve the RLZ access point string and cache the URI used to retrieve RLZ values.
2832 private Uri getRlzUri() {
2833 if (mRlzUri == null) {
2834 String ap = getResources().getString(R.string.rlz_access_point);
2835 mRlzUri = Uri.withAppendedPath(BrowserSettings.RLZ_PROVIDER_URI, ap);
2836 }
2837 return mRlzUri;
2838 }
2839
2840 // Determine if this URI appears to be for a Google search and does not have an RLZ parameter.
2841 // Taken largely from Chrome source, src/chrome/browser/google_url_tracker.cc
2842 private static boolean needsRlzString(Uri uri) {
2843 if ((uri.getQueryParameter("q") != null) && (uri.getQueryParameter("rlz") == null)) {
2844 String host = uri.getHost();
2845 if (host == null) {
2846 return false;
2847 }
2848 String[] hostComponents = host.split("\\.");
2849
2850 if (hostComponents.length < 2) {
2851 return false;
2852 }
2853 int googleComponent = hostComponents.length - 2;
2854 String component = hostComponents[googleComponent];
2855 if (!"google".equals(component)) {
2856 if (hostComponents.length < 3 ||
2857 (!"co".equals(component) && !"com".equals(component))) {
2858 return false;
2859 }
2860 googleComponent = hostComponents.length - 3;
2861 if (!"google".equals(hostComponents[googleComponent])) {
2862 return false;
2863 }
2864 }
2865
2866 // Google corp network handling.
2867 if (googleComponent > 0 && "corp".equals(hostComponents[googleComponent - 1])) {
2868 return false;
2869 }
2870
2871 return true;
2872 }
2873 return false;
2874 }
2875
Grace Kloba22ac16e2009-10-07 18:00:23 -07002876 // -------------------------------------------------------------------------
2877 // Helper function for WebChromeClient
2878 // -------------------------------------------------------------------------
The Android Open Source Project0c908882009-03-03 19:32:16 -08002879
Grace Kloba22ac16e2009-10-07 18:00:23 -07002880 void onProgressChanged(WebView view, int newProgress) {
Michael Kolba2b2ba82010-08-04 17:54:03 -07002881
2882 // On the phone, the fake title bar will always cover up the
2883 // regular title bar (or the regular one is offscreen), so only the
2884 // fake title bar needs to change its progress
2885 mFakeTitleBar.setProgress(newProgress);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002886
Grace Kloba22ac16e2009-10-07 18:00:23 -07002887 if (newProgress == 100) {
2888 // onProgressChanged() may continue to be called after the main
2889 // frame has finished loading, as any remaining sub frames continue
2890 // to load. We'll only get called once though with newProgress as
2891 // 100 when everything is loaded. (onPageFinished is called once
2892 // when the main frame completes loading regardless of the state of
2893 // any sub frames so calls to onProgressChanges may continue after
2894 // onPageFinished has executed)
2895 if (mInLoad) {
2896 mInLoad = false;
Leon Scrogginsa27ff192009-09-14 12:58:04 -04002897 updateInLoadMenuItems();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002898 // If the options menu is open, leave the title bar
2899 if (!mOptionsMenuOpen || !mIconView) {
2900 hideFakeTitleBar();
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07002901 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002902 }
Leon Scrogginsaa37e7f2010-03-05 11:51:20 -05002903 } else {
2904 if (!mInLoad) {
2905 // onPageFinished may have already been called but a subframe is
2906 // still loading and updating the progress. Reset mInLoad and
2907 // update the menu items.
2908 mInLoad = true;
2909 updateInLoadMenuItems();
2910 }
2911 // When the page first begins to load, the Activity may still be
2912 // paused, in which case showFakeTitleBar will do nothing. Call
2913 // again as the page continues to load so that it will be shown.
2914 // (Calling it will the fake title bar is already showing will also
2915 // do nothing.
Grace Kloba22ac16e2009-10-07 18:00:23 -07002916 if (!mOptionsMenuOpen || mIconView) {
2917 // This page has begun to load, so show the title bar
2918 showFakeTitleBar();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002919 }
2920 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002921 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002922
Grace Kloba22ac16e2009-10-07 18:00:23 -07002923 void onShowCustomView(View view, WebChromeClient.CustomViewCallback callback) {
Derek Sollenberger8ff57db2009-12-08 15:39:55 -05002924 // if a view already exists then immediately terminate the new one
2925 if (mCustomView != null) {
2926 callback.onCustomViewHidden();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002927 return;
Derek Sollenberger8ff57db2009-12-08 15:39:55 -05002928 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002929
2930 // Add the custom view to its container.
2931 mCustomViewContainer.addView(view, COVER_SCREEN_GRAVITY_CENTER);
2932 mCustomView = view;
2933 mCustomViewCallback = callback;
2934 // Save the menu state and set it to empty while the custom
2935 // view is showing.
2936 mOldMenuState = mMenuState;
2937 mMenuState = EMPTY_MENU;
2938 // Hide the content view.
2939 mContentView.setVisibility(View.GONE);
2940 // Finally show the custom view container.
Andrei Popescu163ab742009-10-20 17:58:23 +01002941 setStatusBarVisibility(false);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002942 mCustomViewContainer.setVisibility(View.VISIBLE);
2943 mCustomViewContainer.bringToFront();
2944 }
2945
2946 void onHideCustomView() {
2947 if (mCustomView == null)
2948 return;
2949
2950 // Hide the custom view.
2951 mCustomView.setVisibility(View.GONE);
2952 // Remove the custom view from its container.
2953 mCustomViewContainer.removeView(mCustomView);
2954 mCustomView = null;
2955 // Reset the old menu state.
2956 mMenuState = mOldMenuState;
2957 mOldMenuState = EMPTY_MENU;
2958 mCustomViewContainer.setVisibility(View.GONE);
2959 mCustomViewCallback.onCustomViewHidden();
2960 // Show the content view.
Andrei Popescu163ab742009-10-20 17:58:23 +01002961 setStatusBarVisibility(true);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002962 mContentView.setVisibility(View.VISIBLE);
2963 }
2964
2965 Bitmap getDefaultVideoPoster() {
2966 if (mDefaultVideoPoster == null) {
2967 mDefaultVideoPoster = BitmapFactory.decodeResource(
2968 getResources(), R.drawable.default_video_poster);
Patrick Scott3918d442009-08-04 13:22:29 -04002969 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002970 return mDefaultVideoPoster;
2971 }
Patrick Scott3918d442009-08-04 13:22:29 -04002972
Grace Kloba22ac16e2009-10-07 18:00:23 -07002973 View getVideoLoadingProgressView() {
2974 if (mVideoProgressView == null) {
2975 LayoutInflater inflater = LayoutInflater.from(BrowserActivity.this);
2976 mVideoProgressView = inflater.inflate(
2977 R.layout.video_loading_progress, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002978 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002979 return mVideoProgressView;
2980 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002981
Leon Scroggins8d5fa432009-10-02 15:55:59 -04002982 /*
2983 * The Object used to inform the WebView of the file to upload.
2984 */
2985 private ValueCallback<Uri> mUploadMessage;
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002986 private String mCameraFilePath;
Leon Scroggins8d5fa432009-10-02 15:55:59 -04002987
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002988 void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
2989
2990 final String imageMimeType = "image/*";
Ben Murdoch6af492a2010-06-15 12:38:17 +01002991 final String videoMimeType = "video/*";
Ben Murdoch039bd472010-07-21 21:26:57 +01002992 final String audioMimeType = "audio/*";
Ben Murdochb50d7402010-07-16 12:42:22 +01002993 final String mediaSourceKey = "capture";
Ben Murdoch6af492a2010-06-15 12:38:17 +01002994 final String mediaSourceValueCamera = "camera";
Ben Murdochb50d7402010-07-16 12:42:22 +01002995 final String mediaSourceValueFileSystem = "filesystem";
Ben Murdoch6af492a2010-06-15 12:38:17 +01002996 final String mediaSourceValueCamcorder = "camcorder";
Ben Murdoch039bd472010-07-21 21:26:57 +01002997 final String mediaSourceValueMicrophone = "microphone";
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002998
Ben Murdoch039bd472010-07-21 21:26:57 +01002999 // media source can be 'filesystem' or 'camera' or 'camcorder' or 'microphone'.
Ben Murdoch6af492a2010-06-15 12:38:17 +01003000 String mediaSource = "";
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003001
Ben Murdoch6af492a2010-06-15 12:38:17 +01003002 // We add the camera intent if there was no accept type (or '*/*' or 'image/*').
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003003 boolean addCameraIntent = true;
Ben Murdoch6af492a2010-06-15 12:38:17 +01003004 // We add the camcorder intent if there was no accept type (or '*/*' or 'video/*').
3005 boolean addCamcorderIntent = true;
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003006
Ben Murdoch6af492a2010-06-15 12:38:17 +01003007 if (mUploadMessage != null) {
3008 // Already a file picker operation in progress.
3009 return;
3010 }
3011
Grace Kloba22ac16e2009-10-07 18:00:23 -07003012 mUploadMessage = uploadMsg;
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003013
3014 // Parse the accept type.
3015 String params[] = acceptType.split(";");
3016 String mimeType = params[0];
3017
3018 for (String p : params) {
3019 String[] keyValue = p.split("=");
3020 if (keyValue.length == 2) {
3021 // Process key=value parameters.
Ben Murdoch6af492a2010-06-15 12:38:17 +01003022 if (mediaSourceKey.equals(keyValue[0])) {
3023 mediaSource = keyValue[1];
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003024 }
3025 }
3026 }
3027
3028 // This intent will display the standard OPENABLE file picker.
Grace Kloba22ac16e2009-10-07 18:00:23 -07003029 Intent i = new Intent(Intent.ACTION_GET_CONTENT);
3030 i.addCategory(Intent.CATEGORY_OPENABLE);
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003031
3032 // Create an intent to add to the standard file picker that will
3033 // capture an image from the camera. We'll combine this intent with
3034 // the standard OPENABLE picker unless the web developer specifically
3035 // requested the camera or gallery be opened by passing a parameter
3036 // in the accept type.
3037 Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
3038 File externalDataDir = Environment.getExternalStoragePublicDirectory(
3039 Environment.DIRECTORY_DCIM);
3040 File cameraDataDir = new File(externalDataDir.getAbsolutePath() +
3041 File.separator + "browser-photos");
3042 cameraDataDir.mkdirs();
3043 mCameraFilePath = cameraDataDir.getAbsolutePath() + File.separator +
3044 System.currentTimeMillis() + ".jpg";
3045 cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(mCameraFilePath)));
3046
Ben Murdoch6af492a2010-06-15 12:38:17 +01003047 Intent camcorderIntent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
3048
Ben Murdoch039bd472010-07-21 21:26:57 +01003049 Intent soundRecIntent = new Intent(MediaStore.Audio.Media.RECORD_SOUND_ACTION);
3050
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003051 if (mimeType.equals(imageMimeType)) {
3052 i.setType(imageMimeType);
Ben Murdoch6af492a2010-06-15 12:38:17 +01003053 addCamcorderIntent = false;
3054 if (mediaSource.equals(mediaSourceValueCamera)) {
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003055 // Specified 'image/*' and requested the camera, so go ahead and launch the camera
3056 // directly.
3057 BrowserActivity.this.startActivityForResult(cameraIntent, FILE_SELECTED);
3058 return;
Ben Murdochb50d7402010-07-16 12:42:22 +01003059 } else if (mediaSource.equals(mediaSourceValueFileSystem)) {
3060 // Specified filesytem as the source, so don't want to consider the camera.
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003061 addCameraIntent = false;
3062 }
Ben Murdoch6af492a2010-06-15 12:38:17 +01003063 } else if (mimeType.equals(videoMimeType)) {
3064 i.setType(videoMimeType);
3065 addCameraIntent = false;
3066 // The camcorder saves it's own file and returns it to us in the intent, so
3067 // we don't need to generate one here.
3068 mCameraFilePath = null;
3069
3070 if (mediaSource.equals(mediaSourceValueCamcorder)) {
Ben Murdoch039bd472010-07-21 21:26:57 +01003071 // Specified 'video/*' and requested the camcorder, so go ahead and launch the
3072 // camcorder directly.
Ben Murdoch6af492a2010-06-15 12:38:17 +01003073 BrowserActivity.this.startActivityForResult(camcorderIntent, FILE_SELECTED);
3074 return;
Ben Murdochb50d7402010-07-16 12:42:22 +01003075 } else if (mediaSource.equals(mediaSourceValueFileSystem)) {
3076 // Specified filesystem as the source, so don't want to consider the camcorder.
Ben Murdoch6af492a2010-06-15 12:38:17 +01003077 addCamcorderIntent = false;
3078 }
Ben Murdoch039bd472010-07-21 21:26:57 +01003079 } else if (mimeType.equals(audioMimeType)) {
3080 i.setType(audioMimeType);
3081 addCameraIntent = false;
3082 addCamcorderIntent = false;
3083 if (mediaSource.equals(mediaSourceValueMicrophone)) {
3084 // Specified 'audio/*' and requested microphone, so go ahead and launch the sound
3085 // recorder.
3086 BrowserActivity.this.startActivityForResult(soundRecIntent, FILE_SELECTED);
3087 return;
3088 }
3089 // On a default system, there is no single option to open an audio "gallery". Both the
3090 // sound recorder and music browser respond to the OPENABLE/audio/* intent unlike the
3091 // image/* and video/* OPENABLE intents where the image / video gallery are the only
3092 // respondants (and so the user is not prompted by default).
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003093 } else {
3094 i.setType("*/*");
3095 }
3096
Ben Murdoch6af492a2010-06-15 12:38:17 +01003097 // Combine the chooser and the extra choices (like camera or camcorder)
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003098 Intent chooser = new Intent(Intent.ACTION_CHOOSER);
3099 chooser.putExtra(Intent.EXTRA_INTENT, i);
3100
Ben Murdoch6af492a2010-06-15 12:38:17 +01003101 Vector<Intent> extraInitialIntents = new Vector<Intent>(0);
3102
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003103 if (addCameraIntent) {
Ben Murdoch6af492a2010-06-15 12:38:17 +01003104 extraInitialIntents.add(cameraIntent);
3105 }
3106
3107 if (addCamcorderIntent) {
3108 extraInitialIntents.add(camcorderIntent);
3109 }
3110
3111 if (extraInitialIntents.size() > 0) {
3112 Intent[] extraIntents = new Intent[extraInitialIntents.size()];
3113 chooser.putExtra(Intent.EXTRA_INITIAL_INTENTS, extraInitialIntents.toArray(extraIntents));
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003114 }
3115
3116 chooser.putExtra(Intent.EXTRA_TITLE, getString(R.string.choose_upload));
3117 BrowserActivity.this.startActivityForResult(chooser, FILE_SELECTED);
Grace Kloba22ac16e2009-10-07 18:00:23 -07003118 }
3119
3120 // -------------------------------------------------------------------------
3121 // Implement functions for DownloadListener
3122 // -------------------------------------------------------------------------
3123
The Android Open Source Project0c908882009-03-03 19:32:16 -08003124 /**
3125 * Notify the host application a download should be done, or that
3126 * the data should be streamed if a streaming viewer is available.
3127 * @param url The full url to the content that should be downloaded
3128 * @param contentDisposition Content-disposition http header, if
3129 * present.
3130 * @param mimetype The mimetype of the content reported by the server
3131 * @param contentLength The file size reported by the server
3132 */
3133 public void onDownloadStart(String url, String userAgent,
3134 String contentDisposition, String mimetype, long contentLength) {
3135 // if we're dealing wih A/V content that's not explicitly marked
3136 // for download, check if it's streamable.
3137 if (contentDisposition == null
Patrick Scotte1fb9662009-08-31 14:31:52 -04003138 || !contentDisposition.regionMatches(
3139 true, 0, "attachment", 0, 10)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003140 // query the package manager to see if there's a registered handler
3141 // that matches.
3142 Intent intent = new Intent(Intent.ACTION_VIEW);
3143 intent.setDataAndType(Uri.parse(url), mimetype);
Patrick Scotte1fb9662009-08-31 14:31:52 -04003144 ResolveInfo info = getPackageManager().resolveActivity(intent,
3145 PackageManager.MATCH_DEFAULT_ONLY);
3146 if (info != null) {
3147 ComponentName myName = getComponentName();
3148 // If we resolved to ourselves, we don't want to attempt to
3149 // load the url only to try and download it again.
3150 if (!myName.getPackageName().equals(
3151 info.activityInfo.packageName)
3152 || !myName.getClassName().equals(
3153 info.activityInfo.name)) {
3154 // someone (other than us) knows how to handle this mime
3155 // type with this scheme, don't download.
3156 try {
3157 startActivity(intent);
3158 return;
3159 } catch (ActivityNotFoundException ex) {
3160 if (LOGD_ENABLED) {
3161 Log.d(LOGTAG, "activity not found for " + mimetype
3162 + " over " + Uri.parse(url).getScheme(),
3163 ex);
3164 }
3165 // Best behavior is to fall back to a download in this
3166 // case
The Android Open Source Project0c908882009-03-03 19:32:16 -08003167 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003168 }
3169 }
3170 }
3171 onDownloadStartNoStream(url, userAgent, contentDisposition, mimetype, contentLength);
3172 }
3173
Kristian Monsenfa52d172010-03-25 18:29:21 +00003174 // This is to work around the fact that java.net.URI throws Exceptions
3175 // instead of just encoding URL's properly
3176 // Helper method for onDownloadStartNoStream
3177 private static String encodePath(String path) {
3178 char[] chars = path.toCharArray();
3179
3180 boolean needed = false;
3181 for (char c : chars) {
3182 if (c == '[' || c == ']') {
3183 needed = true;
3184 break;
3185 }
3186 }
3187 if (needed == false) {
3188 return path;
3189 }
3190
3191 StringBuilder sb = new StringBuilder("");
3192 for (char c : chars) {
3193 if (c == '[' || c == ']') {
3194 sb.append('%');
3195 sb.append(Integer.toHexString(c));
3196 } else {
3197 sb.append(c);
3198 }
3199 }
3200
3201 return sb.toString();
3202 }
3203
The Android Open Source Project0c908882009-03-03 19:32:16 -08003204 /**
3205 * Notify the host application a download should be done, even if there
3206 * is a streaming viewer available for thise type.
3207 * @param url The full url to the content that should be downloaded
3208 * @param contentDisposition Content-disposition http header, if
3209 * present.
3210 * @param mimetype The mimetype of the content reported by the server
3211 * @param contentLength The file size reported by the server
3212 */
3213 /*package */ void onDownloadStartNoStream(String url, String userAgent,
3214 String contentDisposition, String mimetype, long contentLength) {
3215
3216 String filename = URLUtil.guessFileName(url,
3217 contentDisposition, mimetype);
3218
3219 // Check to see if we have an SDCard
3220 String status = Environment.getExternalStorageState();
3221 if (!status.equals(Environment.MEDIA_MOUNTED)) {
3222 int title;
3223 String msg;
3224
3225 // Check to see if the SDCard is busy, same as the music app
3226 if (status.equals(Environment.MEDIA_SHARED)) {
3227 msg = getString(R.string.download_sdcard_busy_dlg_msg);
3228 title = R.string.download_sdcard_busy_dlg_title;
3229 } else {
3230 msg = getString(R.string.download_no_sdcard_dlg_msg, filename);
3231 title = R.string.download_no_sdcard_dlg_title;
3232 }
3233
3234 new AlertDialog.Builder(this)
3235 .setTitle(title)
3236 .setIcon(android.R.drawable.ic_dialog_alert)
3237 .setMessage(msg)
3238 .setPositiveButton(R.string.ok, null)
3239 .show();
3240 return;
3241 }
3242
Kristian Monsenfa52d172010-03-25 18:29:21 +00003243 // java.net.URI is a lot stricter than KURL so we have to encode some
3244 // extra characters. Fix for b 2538060 and b 1634719
3245 WebAddress webAddress;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003246 try {
Kristian Monsenfa52d172010-03-25 18:29:21 +00003247 webAddress = new WebAddress(url);
3248 webAddress.mPath = encodePath(webAddress.mPath);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003249 } catch (Exception e) {
Kristian Monsenfa52d172010-03-25 18:29:21 +00003250 // This only happens for very bad urls, we want to chatch the
3251 // exception here
3252 Log.e(LOGTAG, "Exception trying to parse url:" + url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003253 return;
3254 }
3255
3256 // XXX: Have to use the old url since the cookies were stored using the
3257 // old percent-encoded url.
3258 String cookies = CookieManager.getInstance().getCookie(url);
3259
3260 ContentValues values = new ContentValues();
Kristian Monsenfa52d172010-03-25 18:29:21 +00003261 values.put(Downloads.Impl.COLUMN_URI, webAddress.toString());
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08003262 values.put(Downloads.Impl.COLUMN_COOKIE_DATA, cookies);
3263 values.put(Downloads.Impl.COLUMN_USER_AGENT, userAgent);
3264 values.put(Downloads.Impl.COLUMN_NOTIFICATION_PACKAGE,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003265 getPackageName());
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08003266 values.put(Downloads.Impl.COLUMN_NOTIFICATION_CLASS,
Leon Scrogginsa563d092010-04-19 16:53:49 -04003267 OpenDownloadReceiver.class.getCanonicalName());
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08003268 values.put(Downloads.Impl.COLUMN_VISIBILITY,
3269 Downloads.Impl.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
3270 values.put(Downloads.Impl.COLUMN_MIME_TYPE, mimetype);
3271 values.put(Downloads.Impl.COLUMN_FILE_NAME_HINT, filename);
Kristian Monsenfa52d172010-03-25 18:29:21 +00003272 values.put(Downloads.Impl.COLUMN_DESCRIPTION, webAddress.mHost);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003273 if (contentLength > 0) {
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08003274 values.put(Downloads.Impl.COLUMN_TOTAL_BYTES, contentLength);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003275 }
3276 if (mimetype == null) {
3277 // We must have long pressed on a link or image to download it. We
3278 // are not sure of the mimetype in this case, so do a head request
3279 new FetchUrlMimeType(this).execute(values);
3280 } else {
3281 final Uri contentUri =
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08003282 getContentResolver().insert(Downloads.Impl.CONTENT_URI, values);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003283 }
Leon Scroggins9191a7f2010-03-18 14:44:44 -04003284 Toast.makeText(this, R.string.download_pending, Toast.LENGTH_SHORT)
3285 .show();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003286 }
3287
Grace Kloba22ac16e2009-10-07 18:00:23 -07003288 // -------------------------------------------------------------------------
3289
The Android Open Source Project0c908882009-03-03 19:32:16 -08003290 /**
3291 * Resets the lock icon. This method is called when we start a new load and
3292 * know the url to be loaded.
3293 */
3294 private void resetLockIcon(String url) {
3295 // Save the lock-icon state (we revert to it if the load gets cancelled)
Grace Kloba22ac16e2009-10-07 18:00:23 -07003296 mTabControl.getCurrentTab().resetLockIcon(url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003297 updateLockIconImage(LOCK_ICON_UNSECURE);
3298 }
3299
The Android Open Source Project0c908882009-03-03 19:32:16 -08003300 /**
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04003301 * Update the lock icon to correspond to our latest state.
3302 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003303 private void updateLockIconToLatest() {
Leon Scroggins91f65fc2010-06-29 13:52:39 -04003304 Tab t = mTabControl.getCurrentTab();
3305 if (t != null) {
3306 updateLockIconImage(t.getLockIconType());
3307 }
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04003308 }
3309
3310 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08003311 * Updates the lock-icon image in the title-bar.
3312 */
3313 private void updateLockIconImage(int lockIconType) {
3314 Drawable d = null;
3315 if (lockIconType == LOCK_ICON_SECURE) {
3316 d = mSecLockIcon;
3317 } else if (lockIconType == LOCK_ICON_MIXED) {
3318 d = mMixLockIcon;
3319 }
Leon Scroggins68579392009-09-15 15:31:54 -04003320 mTitleBar.setLock(d);
Michael Kolba2b2ba82010-08-04 17:54:03 -07003321 mFakeTitleBar.setLock(d);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003322 }
3323
3324 /**
3325 * Displays a page-info dialog.
3326 * @param tab The tab to show info about
3327 * @param fromShowSSLCertificateOnError The flag that indicates whether
3328 * this dialog was opened from the SSL-certificate-on-error dialog or
3329 * not. This is important, since we need to know whether to return to
3330 * the parent dialog or simply dismiss.
3331 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003332 private void showPageInfo(final Tab tab,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003333 final boolean fromShowSSLCertificateOnError) {
3334 final LayoutInflater factory = LayoutInflater
3335 .from(this);
3336
3337 final View pageInfoView = factory.inflate(R.layout.page_info, null);
3338
3339 final WebView view = tab.getWebView();
3340
3341 String url = null;
3342 String title = null;
3343
3344 if (view == null) {
3345 url = tab.getUrl();
3346 title = tab.getTitle();
3347 } else if (view == mTabControl.getCurrentWebView()) {
3348 // Use the cached title and url if this is the current WebView
3349 url = mUrl;
3350 title = mTitle;
3351 } else {
3352 url = view.getUrl();
3353 title = view.getTitle();
3354 }
3355
3356 if (url == null) {
3357 url = "";
3358 }
3359 if (title == null) {
3360 title = "";
3361 }
3362
3363 ((TextView) pageInfoView.findViewById(R.id.address)).setText(url);
3364 ((TextView) pageInfoView.findViewById(R.id.title)).setText(title);
3365
3366 mPageInfoView = tab;
Leon Scrogginsc7b92f82010-01-11 18:17:31 -05003367 mPageInfoFromShowSSLCertificateOnError = fromShowSSLCertificateOnError;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003368
3369 AlertDialog.Builder alertDialogBuilder =
3370 new AlertDialog.Builder(this)
3371 .setTitle(R.string.page_info).setIcon(android.R.drawable.ic_dialog_info)
3372 .setView(pageInfoView)
3373 .setPositiveButton(
3374 R.string.ok,
3375 new DialogInterface.OnClickListener() {
3376 public void onClick(DialogInterface dialog,
3377 int whichButton) {
3378 mPageInfoDialog = null;
3379 mPageInfoView = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003380
3381 // if we came here from the SSL error dialog
3382 if (fromShowSSLCertificateOnError) {
3383 // go back to the SSL error dialog
3384 showSSLCertificateOnError(
3385 mSSLCertificateOnErrorView,
3386 mSSLCertificateOnErrorHandler,
3387 mSSLCertificateOnErrorError);
3388 }
3389 }
3390 })
3391 .setOnCancelListener(
3392 new DialogInterface.OnCancelListener() {
3393 public void onCancel(DialogInterface dialog) {
3394 mPageInfoDialog = null;
3395 mPageInfoView = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003396
3397 // if we came here from the SSL error dialog
3398 if (fromShowSSLCertificateOnError) {
3399 // go back to the SSL error dialog
3400 showSSLCertificateOnError(
3401 mSSLCertificateOnErrorView,
3402 mSSLCertificateOnErrorHandler,
3403 mSSLCertificateOnErrorError);
3404 }
3405 }
3406 });
3407
3408 // if we have a main top-level page SSL certificate set or a certificate
3409 // error
3410 if (fromShowSSLCertificateOnError ||
3411 (view != null && view.getCertificate() != null)) {
3412 // add a 'View Certificate' button
3413 alertDialogBuilder.setNeutralButton(
3414 R.string.view_certificate,
3415 new DialogInterface.OnClickListener() {
3416 public void onClick(DialogInterface dialog,
3417 int whichButton) {
3418 mPageInfoDialog = null;
3419 mPageInfoView = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003420
3421 // if we came here from the SSL error dialog
3422 if (fromShowSSLCertificateOnError) {
3423 // go back to the SSL error dialog
3424 showSSLCertificateOnError(
3425 mSSLCertificateOnErrorView,
3426 mSSLCertificateOnErrorHandler,
3427 mSSLCertificateOnErrorError);
3428 } else {
3429 // otherwise, display the top-most certificate from
3430 // the chain
3431 if (view.getCertificate() != null) {
3432 showSSLCertificate(tab);
3433 }
3434 }
3435 }
3436 });
3437 }
3438
3439 mPageInfoDialog = alertDialogBuilder.show();
3440 }
3441
3442 /**
3443 * Displays the main top-level page SSL certificate dialog
3444 * (accessible from the Page-Info dialog).
3445 * @param tab The tab to show certificate for.
3446 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003447 private void showSSLCertificate(final Tab tab) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003448 final View certificateView =
3449 inflateCertificateView(tab.getWebView().getCertificate());
3450 if (certificateView == null) {
3451 return;
3452 }
3453
3454 LayoutInflater factory = LayoutInflater.from(this);
3455
3456 final LinearLayout placeholder =
3457 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3458
3459 LinearLayout ll = (LinearLayout) factory.inflate(
3460 R.layout.ssl_success, placeholder);
3461 ((TextView)ll.findViewById(R.id.success))
3462 .setText(R.string.ssl_certificate_is_valid);
3463
3464 mSSLCertificateView = tab;
3465 mSSLCertificateDialog =
3466 new AlertDialog.Builder(this)
3467 .setTitle(R.string.ssl_certificate).setIcon(
3468 R.drawable.ic_dialog_browser_certificate_secure)
3469 .setView(certificateView)
3470 .setPositiveButton(R.string.ok,
3471 new DialogInterface.OnClickListener() {
3472 public void onClick(DialogInterface dialog,
3473 int whichButton) {
3474 mSSLCertificateDialog = null;
3475 mSSLCertificateView = null;
3476
3477 showPageInfo(tab, false);
3478 }
3479 })
3480 .setOnCancelListener(
3481 new DialogInterface.OnCancelListener() {
3482 public void onCancel(DialogInterface dialog) {
3483 mSSLCertificateDialog = null;
3484 mSSLCertificateView = null;
3485
3486 showPageInfo(tab, false);
3487 }
3488 })
3489 .show();
3490 }
3491
3492 /**
3493 * Displays the SSL error certificate dialog.
3494 * @param view The target web-view.
3495 * @param handler The SSL error handler responsible for cancelling the
3496 * connection that resulted in an SSL error or proceeding per user request.
3497 * @param error The SSL error object.
3498 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003499 void showSSLCertificateOnError(
The Android Open Source Project0c908882009-03-03 19:32:16 -08003500 final WebView view, final SslErrorHandler handler, final SslError error) {
3501
3502 final View certificateView =
3503 inflateCertificateView(error.getCertificate());
3504 if (certificateView == null) {
3505 return;
3506 }
3507
3508 LayoutInflater factory = LayoutInflater.from(this);
3509
3510 final LinearLayout placeholder =
3511 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3512
3513 if (error.hasError(SslError.SSL_UNTRUSTED)) {
3514 LinearLayout ll = (LinearLayout)factory
3515 .inflate(R.layout.ssl_warning, placeholder);
3516 ((TextView)ll.findViewById(R.id.warning))
3517 .setText(R.string.ssl_untrusted);
3518 }
3519
3520 if (error.hasError(SslError.SSL_IDMISMATCH)) {
3521 LinearLayout ll = (LinearLayout)factory
3522 .inflate(R.layout.ssl_warning, placeholder);
3523 ((TextView)ll.findViewById(R.id.warning))
3524 .setText(R.string.ssl_mismatch);
3525 }
3526
3527 if (error.hasError(SslError.SSL_EXPIRED)) {
3528 LinearLayout ll = (LinearLayout)factory
3529 .inflate(R.layout.ssl_warning, placeholder);
3530 ((TextView)ll.findViewById(R.id.warning))
3531 .setText(R.string.ssl_expired);
3532 }
3533
3534 if (error.hasError(SslError.SSL_NOTYETVALID)) {
3535 LinearLayout ll = (LinearLayout)factory
3536 .inflate(R.layout.ssl_warning, placeholder);
3537 ((TextView)ll.findViewById(R.id.warning))
3538 .setText(R.string.ssl_not_yet_valid);
3539 }
3540
3541 mSSLCertificateOnErrorHandler = handler;
3542 mSSLCertificateOnErrorView = view;
3543 mSSLCertificateOnErrorError = error;
3544 mSSLCertificateOnErrorDialog =
3545 new AlertDialog.Builder(this)
3546 .setTitle(R.string.ssl_certificate).setIcon(
3547 R.drawable.ic_dialog_browser_certificate_partially_secure)
3548 .setView(certificateView)
3549 .setPositiveButton(R.string.ok,
3550 new DialogInterface.OnClickListener() {
3551 public void onClick(DialogInterface dialog,
3552 int whichButton) {
3553 mSSLCertificateOnErrorDialog = null;
3554 mSSLCertificateOnErrorView = null;
3555 mSSLCertificateOnErrorHandler = null;
3556 mSSLCertificateOnErrorError = null;
3557
Grace Kloba22ac16e2009-10-07 18:00:23 -07003558 view.getWebViewClient().onReceivedSslError(
3559 view, handler, error);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003560 }
3561 })
3562 .setNeutralButton(R.string.page_info_view,
3563 new DialogInterface.OnClickListener() {
3564 public void onClick(DialogInterface dialog,
3565 int whichButton) {
3566 mSSLCertificateOnErrorDialog = null;
3567
3568 // do not clear the dialog state: we will
3569 // need to show the dialog again once the
3570 // user is done exploring the page-info details
3571
3572 showPageInfo(mTabControl.getTabFromView(view),
3573 true);
3574 }
3575 })
3576 .setOnCancelListener(
3577 new DialogInterface.OnCancelListener() {
3578 public void onCancel(DialogInterface dialog) {
3579 mSSLCertificateOnErrorDialog = null;
3580 mSSLCertificateOnErrorView = null;
3581 mSSLCertificateOnErrorHandler = null;
3582 mSSLCertificateOnErrorError = null;
3583
Grace Kloba22ac16e2009-10-07 18:00:23 -07003584 view.getWebViewClient().onReceivedSslError(
3585 view, handler, error);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003586 }
3587 })
3588 .show();
3589 }
3590
3591 /**
3592 * Inflates the SSL certificate view (helper method).
3593 * @param certificate The SSL certificate.
3594 * @return The resultant certificate view with issued-to, issued-by,
3595 * issued-on, expires-on, and possibly other fields set.
3596 * If the input certificate is null, returns null.
3597 */
3598 private View inflateCertificateView(SslCertificate certificate) {
3599 if (certificate == null) {
3600 return null;
3601 }
3602
3603 LayoutInflater factory = LayoutInflater.from(this);
3604
3605 View certificateView = factory.inflate(
3606 R.layout.ssl_certificate, null);
3607
3608 // issued to:
3609 SslCertificate.DName issuedTo = certificate.getIssuedTo();
3610 if (issuedTo != null) {
3611 ((TextView) certificateView.findViewById(R.id.to_common))
3612 .setText(issuedTo.getCName());
3613 ((TextView) certificateView.findViewById(R.id.to_org))
3614 .setText(issuedTo.getOName());
3615 ((TextView) certificateView.findViewById(R.id.to_org_unit))
3616 .setText(issuedTo.getUName());
3617 }
3618
3619 // issued by:
3620 SslCertificate.DName issuedBy = certificate.getIssuedBy();
3621 if (issuedBy != null) {
3622 ((TextView) certificateView.findViewById(R.id.by_common))
3623 .setText(issuedBy.getCName());
3624 ((TextView) certificateView.findViewById(R.id.by_org))
3625 .setText(issuedBy.getOName());
3626 ((TextView) certificateView.findViewById(R.id.by_org_unit))
3627 .setText(issuedBy.getUName());
3628 }
3629
3630 // issued on:
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003631 String issuedOn = formatCertificateDate(
3632 certificate.getValidNotBeforeDate());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003633 ((TextView) certificateView.findViewById(R.id.issued_on))
3634 .setText(issuedOn);
3635
3636 // expires on:
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003637 String expiresOn = formatCertificateDate(
3638 certificate.getValidNotAfterDate());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003639 ((TextView) certificateView.findViewById(R.id.expires_on))
3640 .setText(expiresOn);
3641
3642 return certificateView;
3643 }
3644
3645 /**
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003646 * Formats the certificate date to a properly localized date string.
The Android Open Source Project0c908882009-03-03 19:32:16 -08003647 * @return Properly localized version of the certificate date string and
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003648 * the "" if it fails to localize.
The Android Open Source Project0c908882009-03-03 19:32:16 -08003649 */
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003650 private String formatCertificateDate(Date certificateDate) {
3651 if (certificateDate == null) {
3652 return "";
The Android Open Source Project0c908882009-03-03 19:32:16 -08003653 }
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003654 String formattedDate = DateFormat.getDateFormat(this).format(certificateDate);
3655 if (formattedDate == null) {
3656 return "";
3657 }
3658 return formattedDate;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003659 }
3660
3661 /**
3662 * Displays an http-authentication dialog.
3663 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003664 void showHttpAuthentication(final HttpAuthHandler handler,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003665 final String host, final String realm, final String title,
3666 final String name, final String password, int focusId) {
3667 LayoutInflater factory = LayoutInflater.from(this);
3668 final View v = factory
3669 .inflate(R.layout.http_authentication, null);
3670 if (name != null) {
3671 ((EditText) v.findViewById(R.id.username_edit)).setText(name);
3672 }
3673 if (password != null) {
3674 ((EditText) v.findViewById(R.id.password_edit)).setText(password);
3675 }
3676
3677 String titleText = title;
3678 if (titleText == null) {
3679 titleText = getText(R.string.sign_in_to).toString().replace(
3680 "%s1", host).replace("%s2", realm);
3681 }
3682
3683 mHttpAuthHandler = handler;
3684 AlertDialog dialog = new AlertDialog.Builder(this)
3685 .setTitle(titleText)
3686 .setIcon(android.R.drawable.ic_dialog_alert)
3687 .setView(v)
3688 .setPositiveButton(R.string.action,
3689 new DialogInterface.OnClickListener() {
3690 public void onClick(DialogInterface dialog,
3691 int whichButton) {
3692 String nm = ((EditText) v
3693 .findViewById(R.id.username_edit))
3694 .getText().toString();
3695 String pw = ((EditText) v
3696 .findViewById(R.id.password_edit))
3697 .getText().toString();
3698 BrowserActivity.this.setHttpAuthUsernamePassword
3699 (host, realm, nm, pw);
3700 handler.proceed(nm, pw);
3701 mHttpAuthenticationDialog = null;
3702 mHttpAuthHandler = null;
3703 }})
3704 .setNegativeButton(R.string.cancel,
3705 new DialogInterface.OnClickListener() {
3706 public void onClick(DialogInterface dialog,
3707 int whichButton) {
3708 handler.cancel();
3709 BrowserActivity.this.resetTitleAndRevertLockIcon();
3710 mHttpAuthenticationDialog = null;
3711 mHttpAuthHandler = null;
3712 }})
3713 .setOnCancelListener(new DialogInterface.OnCancelListener() {
3714 public void onCancel(DialogInterface dialog) {
3715 handler.cancel();
3716 BrowserActivity.this.resetTitleAndRevertLockIcon();
3717 mHttpAuthenticationDialog = null;
3718 mHttpAuthHandler = null;
3719 }})
3720 .create();
3721 // Make the IME appear when the dialog is displayed if applicable.
3722 dialog.getWindow().setSoftInputMode(
3723 WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
3724 dialog.show();
3725 if (focusId != 0) {
3726 dialog.findViewById(focusId).requestFocus();
3727 } else {
3728 v.findViewById(R.id.username_edit).requestFocus();
3729 }
3730 mHttpAuthenticationDialog = dialog;
3731 }
3732
3733 public int getProgress() {
3734 WebView w = mTabControl.getCurrentWebView();
3735 if (w != null) {
3736 return w.getProgress();
3737 } else {
3738 return 100;
3739 }
3740 }
3741
3742 /**
3743 * Set HTTP authentication password.
3744 *
3745 * @param host The host for the password
3746 * @param realm The realm for the password
3747 * @param username The username for the password. If it is null, it means
3748 * password can't be saved.
3749 * @param password The password
3750 */
3751 public void setHttpAuthUsernamePassword(String host, String realm,
3752 String username,
3753 String password) {
Steve Block95a53b22010-03-25 17:24:58 +00003754 WebView w = getTopWindow();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003755 if (w != null) {
3756 w.setHttpAuthUsernamePassword(host, realm, username, password);
3757 }
3758 }
3759
3760 /**
3761 * connectivity manager says net has come or gone... inform the user
3762 * @param up true if net has come up, false if net has gone down
3763 */
3764 public void onNetworkToggle(boolean up) {
3765 if (up == mIsNetworkUp) {
3766 return;
3767 } else if (up) {
3768 mIsNetworkUp = true;
3769 if (mAlertDialog != null) {
3770 mAlertDialog.cancel();
3771 mAlertDialog = null;
3772 }
3773 } else {
3774 mIsNetworkUp = false;
Patrick Scotteb6ab2a2009-09-16 10:00:17 -04003775 if (mInLoad) {
3776 createAndShowNetworkDialog();
3777 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003778 }
3779 WebView w = mTabControl.getCurrentWebView();
3780 if (w != null) {
3781 w.setNetworkAvailable(up);
3782 }
3783 }
3784
Grace Kloba22ac16e2009-10-07 18:00:23 -07003785 boolean isNetworkUp() {
3786 return mIsNetworkUp;
3787 }
3788
Patrick Scotteb6ab2a2009-09-16 10:00:17 -04003789 // This method shows the network dialog alerting the user that the net is
3790 // down. It will only show the dialog if mAlertDialog is null.
3791 private void createAndShowNetworkDialog() {
3792 if (mAlertDialog == null) {
3793 mAlertDialog = new AlertDialog.Builder(this)
3794 .setTitle(R.string.loadSuspendedTitle)
3795 .setMessage(R.string.loadSuspended)
3796 .setPositiveButton(R.string.ok, null)
3797 .show();
3798 }
3799 }
3800
The Android Open Source Project0c908882009-03-03 19:32:16 -08003801 @Override
3802 protected void onActivityResult(int requestCode, int resultCode,
3803 Intent intent) {
Grace Klobabb394f32009-11-19 10:26:37 -08003804 if (getTopWindow() == null) return;
3805
The Android Open Source Project0c908882009-03-03 19:32:16 -08003806 switch (requestCode) {
3807 case COMBO_PAGE:
3808 if (resultCode == RESULT_OK && intent != null) {
3809 String data = intent.getAction();
3810 Bundle extras = intent.getExtras();
Michael Kolb300b7f02010-08-25 13:47:24 -07003811 if (extras != null &&
3812 extras.getBoolean(
3813 CombinedBookmarkHistoryActivity.EXTRA_OPEN_NEW_WINDOW,
3814 false)) {
Michael Kolb68792c82010-08-09 16:39:18 -07003815 openTab(data, false);
3816 } else if ((extras != null) &&
3817 extras.getBoolean(CombinedBookmarkHistoryActivity.NEWTAB_MODE)) {
3818 openTab(data, true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003819 } else {
Michael Kolb68792c82010-08-09 16:39:18 -07003820 final Tab currentTab = mTabControl.getCurrentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04003821 dismissSubWindow(currentTab);
3822 if (data != null && data.length() != 0) {
Leon Scroggins92472e82010-02-17 16:32:28 -05003823 loadUrl(getTopWindow(), data);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003824 }
3825 }
Michael Kolb3f65c382010-08-20 15:31:16 -07003826 } else if (resultCode == RESULT_CANCELED) {
3827 if (intent != null) {
3828 float evtx = intent.getFloatExtra(CombinedBookmarkHistoryActivity.EVT_X, -1);
3829 float evty = intent.getFloatExtra(CombinedBookmarkHistoryActivity.EVT_Y, -1);
3830 long now = System.currentTimeMillis();
3831 MotionEvent evt = MotionEvent.obtain(now, now,
3832 MotionEvent.ACTION_DOWN, evtx, evty, 0);
3833 dispatchTouchEvent(evt);
3834 MotionEvent up = MotionEvent.obtain(evt);
3835 up.setAction(MotionEvent.ACTION_UP);
3836 dispatchTouchEvent(up);
3837 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003838 }
Leon Scrogginsfde97462010-01-11 13:06:21 -05003839 // Deliberately fall through to PREFERENCES_PAGE, since the
3840 // same extra may be attached to the COMBO_PAGE
3841 case PREFERENCES_PAGE:
3842 if (resultCode == RESULT_OK && intent != null) {
3843 String action = intent.getStringExtra(Intent.EXTRA_TEXT);
3844 if (BrowserSettings.PREF_CLEAR_HISTORY.equals(action)) {
3845 mTabControl.removeParentChildRelationShips();
3846 }
3847 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003848 break;
Leon Scroggins8d5fa432009-10-02 15:55:59 -04003849 // Choose a file from the file picker.
3850 case FILE_SELECTED:
3851 if (null == mUploadMessage) break;
3852 Uri result = intent == null || resultCode != RESULT_OK ? null
3853 : intent.getData();
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003854
3855 // As we ask the camera to save the result of the user taking
3856 // a picture, the camera application does not return anything other
3857 // than RESULT_OK. So we need to check whether the file we expected
3858 // was written to disk in the in the case that we
3859 // did not get an intent returned but did get a RESULT_OK. If it was,
3860 // we assume that this result has came back from the camera.
3861 if (result == null && intent == null && resultCode == RESULT_OK) {
3862 File cameraFile = new File(mCameraFilePath);
3863 if (cameraFile.exists()) {
3864 result = Uri.fromFile(cameraFile);
Ben Murdoch07d34732010-05-27 18:34:46 +01003865 // Broadcast to the media scanner that we have a new photo
3866 // so it will be added into the gallery for the user.
3867 sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, result));
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003868 }
3869 }
Leon Scroggins8d5fa432009-10-02 15:55:59 -04003870 mUploadMessage.onReceiveValue(result);
3871 mUploadMessage = null;
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003872 mCameraFilePath = null;
Leon Scroggins8d5fa432009-10-02 15:55:59 -04003873 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003874 default:
3875 break;
3876 }
Leon Scroggins30444232009-09-04 18:36:20 -04003877 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003878 }
3879
3880 /*
3881 * This method is called as a result of the user selecting the options
Leon Scrogginsf08809b2010-01-21 09:27:46 -05003882 * menu to see the download window. It shows the download window on top of
3883 * the current window.
The Android Open Source Project0c908882009-03-03 19:32:16 -08003884 */
Leon Scrogginsf08809b2010-01-21 09:27:46 -05003885 private void viewDownloads(Uri downloadRecord) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003886 Intent intent = new Intent(this,
3887 BrowserDownloadPage.class);
3888 intent.setData(downloadRecord);
Grace Kloba22ac16e2009-10-07 18:00:23 -07003889 startActivityForResult(intent, BrowserActivity.DOWNLOAD_PAGE);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003890
3891 }
3892
Ben Murdocheecb4e62010-07-06 16:30:38 +01003893 /* package*/ void promptAddOrInstallBookmark() {
3894 final Tab current = mTabControl.getCurrentTab();
3895 Resources resources = getResources();
3896 CharSequence[] choices = {
3897 resources.getString(R.string.save_to_bookmarks),
3898 resources.getString(R.string.create_shortcut_bookmark)
3899 };
3900
3901 AlertDialog.Builder builder = new AlertDialog.Builder(this);
3902 builder.setTitle(R.string.add_new_bookmark);
3903 builder.setItems(choices, new DialogInterface.OnClickListener() {
3904 public void onClick(DialogInterface dialog, int item) {
3905 if (item == 0) {
3906 bookmarkCurrentPage();
3907 } else if (item == 1) {
3908 current.populatePickerData();
3909 String touchIconUrl = mTabControl.getCurrentWebView().getTouchIconUrl();
3910 if (touchIconUrl != null) {
3911 // Download the touch icon for this site then save it to the
3912 // homescreen.
3913 Bundle b = new Bundle();
3914 b.putString("url", current.getUrl());
3915 b.putString("title", current.getTitle());
3916 b.putParcelable("favicon", current.getFavicon());
3917 Message msg = mHandler.obtainMessage(TOUCH_ICON_DOWNLOADED);
3918 msg.setData(b);
Ben Murdochccb5de02010-07-19 18:38:17 +01003919 new DownloadTouchIcon(BrowserActivity.this, msg,
Ben Murdocheecb4e62010-07-06 16:30:38 +01003920 mTabControl.getCurrentWebView().getSettings()
3921 .getUserAgentString()).execute(touchIconUrl);
3922 } else {
3923 // add to homescreen, can do it immediately as there is no touch
3924 // icon.
3925 showSaveToHomescreenDialog(current.getUrl(), current.getTitle(),
3926 null, current.getFavicon());
3927 }
3928 }
3929 }
3930 });
3931 builder.create().show();
3932 }
3933
Leon Scroggins160a7e72009-08-14 18:28:01 -04003934 /**
3935 * Open the Go page.
3936 * @param startWithHistory If true, open starting on the history tab.
3937 * Otherwise, start with the bookmarks tab.
Leon Scroggins160a7e72009-08-14 18:28:01 -04003938 */
Michael Kolb68792c82010-08-09 16:39:18 -07003939 /* package */ void bookmarksOrHistoryPicker(boolean startWithHistory, boolean newTabMode) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003940 WebView current = mTabControl.getCurrentWebView();
3941 if (current == null) {
3942 return;
3943 }
3944 Intent intent = new Intent(this,
3945 CombinedBookmarkHistoryActivity.class);
3946 String title = current.getTitle();
3947 String url = current.getUrl();
Ben Murdoch87cc65d2010-06-29 20:34:10 +01003948 Bitmap thumbnail = createScreenshot(current, getDesiredThumbnailWidth(this),
3949 getDesiredThumbnailHeight(this));
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01003950
The Android Open Source Project0c908882009-03-03 19:32:16 -08003951 // Just in case the user opens bookmarks before a page finishes loading
3952 // so the current history item, and therefore the page, is null.
3953 if (null == url) {
3954 url = mLastEnteredUrl;
3955 // This can happen.
3956 if (null == url) {
3957 url = mSettings.getHomePage();
3958 }
3959 }
3960 // In case the web page has not yet received its associated title.
3961 if (title == null) {
3962 title = url;
3963 }
3964 intent.putExtra("title", title);
3965 intent.putExtra("url", url);
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01003966 intent.putExtra("thumbnail", thumbnail);
Leon Scroggins30444232009-09-04 18:36:20 -04003967 // Disable opening in a new window if we have maxed out the windows
Grace Kloba22ac16e2009-10-07 18:00:23 -07003968 intent.putExtra("disable_new_window", !mTabControl.canCreateNewTab());
Patrick Scott3918d442009-08-04 13:22:29 -04003969 intent.putExtra("touch_icon_url", current.getTouchIconUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003970 if (startWithHistory) {
Jeff Hamilton64144e42010-08-18 16:31:59 -05003971 intent.putExtra(CombinedBookmarkHistoryActivity.STARTING_FRAGMENT,
3972 CombinedBookmarkHistoryActivity.FRAGMENT_ID_HISTORY);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003973 }
Michael Kolb300b7f02010-08-25 13:47:24 -07003974 intent.putExtra(CombinedBookmarkHistoryActivity.NEWTAB_MODE, newTabMode);
Michael Kolb0998b0a2010-08-23 17:45:35 -07003975 int top = -1;
3976 int height = -1;
Michael Kolb3f65c382010-08-20 15:31:16 -07003977 if (mXLargeScreenSize) {
3978 showFakeTitleBar();
3979 int titleBarHeight = ((TitleBarXLarge)mFakeTitleBar).getHeightWithoutProgress();
Michael Kolb0998b0a2010-08-23 17:45:35 -07003980 top = mTabBar.getBottom() + titleBarHeight;
3981 height = getTopWindow().getHeight() - titleBarHeight;
Michael Kolb68792c82010-08-09 16:39:18 -07003982 }
Michael Kolb0998b0a2010-08-23 17:45:35 -07003983 intent.putExtra(CombinedBookmarkHistoryActivity.EXTRA_TOP, top);
3984 intent.putExtra(CombinedBookmarkHistoryActivity.EXTRA_HEIGHT, height);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003985 startActivityForResult(intent, COMBO_PAGE);
3986 }
3987
Ben Murdocheecb4e62010-07-06 16:30:38 +01003988 private void showSaveToHomescreenDialog(String url, String title, Bitmap touchIcon,
3989 Bitmap favicon) {
3990 Intent intent = new Intent(this, SaveToHomescreenDialog.class);
3991
3992 // Just in case the user tries to save before a page finishes loading
3993 // so the current history item, and therefore the page, is null.
3994 if (null == url) {
3995 url = mLastEnteredUrl;
3996 // This can happen.
3997 if (null == url) {
3998 url = mSettings.getHomePage();
3999 }
4000 }
4001
4002 // In case the web page has not yet received its associated title.
4003 if (title == null) {
4004 title = url;
4005 }
4006
4007 intent.putExtra("title", title);
4008 intent.putExtra("url", url);
4009 intent.putExtra("favicon", favicon);
4010 intent.putExtra("touchIcon", touchIcon);
4011 startActivity(intent);
4012 }
4013
4014
The Android Open Source Project0c908882009-03-03 19:32:16 -08004015 // Called when loading from context menu or LOAD_URL message
Leon Scroggins92472e82010-02-17 16:32:28 -05004016 private void loadUrlFromContext(WebView view, String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08004017 // In case the user enters nothing.
4018 if (url != null && url.length() != 0 && view != null) {
4019 url = smartUrlFilter(url);
Grace Kloba22ac16e2009-10-07 18:00:23 -07004020 if (!view.getWebViewClient().shouldOverrideUrlLoading(view, url)) {
Leon Scroggins92472e82010-02-17 16:32:28 -05004021 loadUrl(view, url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004022 }
4023 }
4024 }
4025
Leon Scroggins92472e82010-02-17 16:32:28 -05004026 /**
4027 * Load the URL into the given WebView and update the title bar
4028 * to reflect the new load. Call this instead of WebView.loadUrl
4029 * directly.
4030 * @param view The WebView used to load url.
4031 * @param url The URL to load.
4032 */
4033 private void loadUrl(WebView view, String url) {
4034 updateTitleBarForNewLoad(view, url);
4035 view.loadUrl(url);
4036 }
4037
4038 /**
4039 * Load UrlData into a Tab and update the title bar to reflect the new
4040 * load. Call this instead of UrlData.loadIn directly.
4041 * @param t The Tab used to load.
4042 * @param data The UrlData being loaded.
4043 */
4044 private void loadUrlDataIn(Tab t, UrlData data) {
4045 updateTitleBarForNewLoad(t.getWebView(), data.mUrl);
4046 data.loadIn(t);
4047 }
4048
4049 /**
4050 * If the WebView is the top window, update the title bar to reflect
4051 * loading the new URL. i.e. set its text, clear the favicon (which
4052 * will be set once the page begins loading), and set the progress to
4053 * INITIAL_PROGRESS to show that the page has begun to load. Called
4054 * by loadUrl and loadUrlDataIn.
4055 * @param view The WebView that is starting a load.
4056 * @param url The URL that is being loaded.
4057 */
4058 private void updateTitleBarForNewLoad(WebView view, String url) {
4059 if (view == getTopWindow()) {
4060 setUrlTitle(url, null);
4061 setFavicon(null);
4062 onProgressChanged(view, INITIAL_PROGRESS);
4063 }
4064 }
4065
The Android Open Source Project0c908882009-03-03 19:32:16 -08004066 private String smartUrlFilter(Uri inUri) {
4067 if (inUri != null) {
4068 return smartUrlFilter(inUri.toString());
4069 }
4070 return null;
4071 }
4072
Feng Qianb34f87a2009-03-24 21:27:26 -07004073 protected static final Pattern ACCEPTED_URI_SCHEMA = Pattern.compile(
The Android Open Source Project0c908882009-03-03 19:32:16 -08004074 "(?i)" + // switch on case insensitive matching
4075 "(" + // begin group for schema
4076 "(?:http|https|file):\\/\\/" +
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004077 "|(?:inline|data|about|content|javascript):" +
The Android Open Source Project0c908882009-03-03 19:32:16 -08004078 ")" +
4079 "(.*)" );
4080
4081 /**
4082 * Attempts to determine whether user input is a URL or search
4083 * terms. Anything with a space is passed to search.
4084 *
4085 * Converts to lowercase any mistakenly uppercased schema (i.e.,
4086 * "Http://" converts to "http://"
4087 *
4088 * @return Original or modified URL
4089 *
4090 */
4091 String smartUrlFilter(String url) {
4092
4093 String inUrl = url.trim();
4094 boolean hasSpace = inUrl.indexOf(' ') != -1;
4095
4096 Matcher matcher = ACCEPTED_URI_SCHEMA.matcher(inUrl);
4097 if (matcher.matches()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08004098 // force scheme to lowercase
4099 String scheme = matcher.group(1);
4100 String lcScheme = scheme.toLowerCase();
4101 if (!lcScheme.equals(scheme)) {
Mitsuru Oshima123ecfb2009-05-18 19:11:14 -07004102 inUrl = lcScheme + matcher.group(2);
4103 }
4104 if (hasSpace) {
4105 inUrl = inUrl.replace(" ", "%20");
The Android Open Source Project0c908882009-03-03 19:32:16 -08004106 }
4107 return inUrl;
4108 }
4109 if (hasSpace) {
Satish Sampath565505b2009-05-29 15:37:27 +01004110 // FIXME: Is this the correct place to add to searches?
4111 // what if someone else calls this function?
4112 int shortcut = parseUrlShortcut(inUrl);
4113 if (shortcut != SHORTCUT_INVALID) {
4114 Browser.addSearchUrl(mResolver, inUrl);
4115 String query = inUrl.substring(2);
4116 switch (shortcut) {
4117 case SHORTCUT_GOOGLE_SEARCH:
Grace Kloba47fdfdb2009-06-30 11:15:34 -07004118 return URLUtil.composeSearchUrl(query, QuickSearch_G, QUERY_PLACE_HOLDER);
Satish Sampath565505b2009-05-29 15:37:27 +01004119 case SHORTCUT_WIKIPEDIA_SEARCH:
4120 return URLUtil.composeSearchUrl(query, QuickSearch_W, QUERY_PLACE_HOLDER);
4121 case SHORTCUT_DICTIONARY_SEARCH:
4122 return URLUtil.composeSearchUrl(query, QuickSearch_D, QUERY_PLACE_HOLDER);
4123 case SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH:
The Android Open Source Project0c908882009-03-03 19:32:16 -08004124 // FIXME: we need location in this case
Satish Sampath565505b2009-05-29 15:37:27 +01004125 return URLUtil.composeSearchUrl(query, QuickSearch_L, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004126 }
4127 }
4128 } else {
Dan Egnor5ee906c2009-11-18 12:11:49 -08004129 if (Patterns.WEB_URL.matcher(inUrl).matches()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08004130 return URLUtil.guessUrl(inUrl);
4131 }
4132 }
4133
4134 Browser.addSearchUrl(mResolver, inUrl);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07004135 return URLUtil.composeSearchUrl(inUrl, QuickSearch_G, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004136 }
4137
Ben Murdochbff2d602009-07-01 20:19:05 +01004138 /* package */ void setShouldShowErrorConsole(boolean flag) {
4139 if (flag == mShouldShowErrorConsole) {
4140 // Nothing to do.
4141 return;
4142 }
4143
4144 mShouldShowErrorConsole = flag;
4145
Grace Kloba22ac16e2009-10-07 18:00:23 -07004146 ErrorConsoleView errorConsole = mTabControl.getCurrentTab()
4147 .getErrorConsole(true);
Ben Murdochbff2d602009-07-01 20:19:05 +01004148
4149 if (flag) {
4150 // Setting the show state of the console will cause it's the layout to be inflated.
4151 if (errorConsole.numberOfErrors() > 0) {
4152 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
4153 } else {
4154 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
4155 }
4156
4157 // Now we can add it to the main view.
4158 mErrorConsoleContainer.addView(errorConsole,
Romain Guy15b8ec62010-01-08 15:06:43 -08004159 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
Ben Murdochbff2d602009-07-01 20:19:05 +01004160 ViewGroup.LayoutParams.WRAP_CONTENT));
4161 } else {
4162 mErrorConsoleContainer.removeView(errorConsole);
4163 }
4164
4165 }
4166
Grace Kloba22ac16e2009-10-07 18:00:23 -07004167 boolean shouldShowErrorConsole() {
4168 return mShouldShowErrorConsole;
4169 }
4170
Andrei Popescu163ab742009-10-20 17:58:23 +01004171 private void setStatusBarVisibility(boolean visible) {
4172 int flag = visible ? 0 : WindowManager.LayoutParams.FLAG_FULLSCREEN;
4173 getWindow().setFlags(flag, WindowManager.LayoutParams.FLAG_FULLSCREEN);
4174 }
4175
Andrei Popescu56199cc2010-01-12 22:39:16 +00004176
4177 private void sendNetworkType(String type, String subtype) {
4178 WebView w = mTabControl.getCurrentWebView();
4179 if (w != null) {
4180 w.setNetworkType(type, subtype);
4181 }
4182 }
4183
Grace Klobaeb6eef42009-09-15 17:56:32 -07004184 final static int LOCK_ICON_UNSECURE = 0;
4185 final static int LOCK_ICON_SECURE = 1;
4186 final static int LOCK_ICON_MIXED = 2;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004187
The Android Open Source Project0c908882009-03-03 19:32:16 -08004188 private BrowserSettings mSettings;
4189 private TabControl mTabControl;
4190 private ContentResolver mResolver;
4191 private FrameLayout mContentView;
Andrei Popescuadc008d2009-06-26 14:11:30 +01004192 private View mCustomView;
4193 private FrameLayout mCustomViewContainer;
Andrei Popescuc9b55562009-07-07 10:51:15 +01004194 private WebChromeClient.CustomViewCallback mCustomViewCallback;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004195
4196 // FIXME, temp address onPrepareMenu performance problem. When we move everything out of
4197 // view, we should rewrite this.
4198 private int mCurrentMenuState = 0;
4199 private int mMenuState = R.id.MAIN_MENU;
Andrei Popescuadc008d2009-06-26 14:11:30 +01004200 private int mOldMenuState = EMPTY_MENU;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004201 private static final int EMPTY_MENU = -1;
4202 private Menu mMenu;
4203
The Android Open Source Project0c908882009-03-03 19:32:16 -08004204 // Used to prevent chording to result in firing two shortcuts immediately
4205 // one after another. Fixes bug 1211714.
4206 boolean mCanChord;
4207
4208 private boolean mInLoad;
4209 private boolean mIsNetworkUp;
Ben Murdochb7cc8b42009-09-28 10:59:09 +01004210 private boolean mDidStopLoad;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004211
Cary Clark1f10cbf2010-03-22 11:45:23 -04004212 /* package */ boolean mActivityInPause = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004213
4214 private boolean mMenuIsDown;
4215
The Android Open Source Project0c908882009-03-03 19:32:16 -08004216 private static boolean mInTrace;
4217
4218 // Performance probe
4219 private static final int[] SYSTEM_CPU_FORMAT = new int[] {
4220 Process.PROC_SPACE_TERM | Process.PROC_COMBINE,
4221 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 1: user time
4222 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 2: nice time
4223 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 3: sys time
4224 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 4: idle time
4225 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 5: iowait time
4226 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 6: irq time
4227 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG // 7: softirq time
4228 };
4229
4230 private long mStart;
4231 private long mProcessStart;
4232 private long mUserStart;
4233 private long mSystemStart;
4234 private long mIdleStart;
4235 private long mIrqStart;
4236
4237 private long mUiStart;
4238
4239 private Drawable mMixLockIcon;
4240 private Drawable mSecLockIcon;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004241
4242 /* hold a ref so we can auto-cancel if necessary */
4243 private AlertDialog mAlertDialog;
4244
The Android Open Source Project0c908882009-03-03 19:32:16 -08004245 // The up-to-date URL and title (these can be different from those stored
4246 // in WebView, since it takes some time for the information in WebView to
4247 // get updated)
4248 private String mUrl;
4249 private String mTitle;
4250
4251 // As PageInfo has different style for landscape / portrait, we have
4252 // to re-open it when configuration changed
4253 private AlertDialog mPageInfoDialog;
Grace Kloba22ac16e2009-10-07 18:00:23 -07004254 private Tab mPageInfoView;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004255 // If the Page-Info dialog is launched from the SSL-certificate-on-error
4256 // dialog, we should not just dismiss it, but should get back to the
4257 // SSL-certificate-on-error dialog. This flag is used to store this state
Leon Scrogginsc7b92f82010-01-11 18:17:31 -05004258 private boolean mPageInfoFromShowSSLCertificateOnError;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004259
4260 // as SSLCertificateOnError has different style for landscape / portrait,
4261 // we have to re-open it when configuration changed
4262 private AlertDialog mSSLCertificateOnErrorDialog;
4263 private WebView mSSLCertificateOnErrorView;
4264 private SslErrorHandler mSSLCertificateOnErrorHandler;
4265 private SslError mSSLCertificateOnErrorError;
4266
4267 // as SSLCertificate has different style for landscape / portrait, we
4268 // have to re-open it when configuration changed
4269 private AlertDialog mSSLCertificateDialog;
Grace Kloba22ac16e2009-10-07 18:00:23 -07004270 private Tab mSSLCertificateView;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004271
4272 // as HttpAuthentication has different style for landscape / portrait, we
4273 // have to re-open it when configuration changed
4274 private AlertDialog mHttpAuthenticationDialog;
4275 private HttpAuthHandler mHttpAuthHandler;
4276
4277 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_PARAMS =
4278 new FrameLayout.LayoutParams(
Romain Guy15b8ec62010-01-08 15:06:43 -08004279 ViewGroup.LayoutParams.MATCH_PARENT,
4280 ViewGroup.LayoutParams.MATCH_PARENT);
Andrei Popescuadc008d2009-06-26 14:11:30 +01004281 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_GRAVITY_CENTER =
4282 new FrameLayout.LayoutParams(
Romain Guy15b8ec62010-01-08 15:06:43 -08004283 ViewGroup.LayoutParams.MATCH_PARENT,
4284 ViewGroup.LayoutParams.MATCH_PARENT,
Andrei Popescuadc008d2009-06-26 14:11:30 +01004285 Gravity.CENTER);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07004286 // Google search
4287 final static String QuickSearch_G = "http://www.google.com/m?q=%s";
The Android Open Source Project0c908882009-03-03 19:32:16 -08004288 // Wikipedia search
4289 final static String QuickSearch_W = "http://en.wikipedia.org/w/index.php?search=%s&go=Go";
4290 // Dictionary search
4291 final static String QuickSearch_D = "http://dictionary.reference.com/search?q=%s";
4292 // Google Mobile Local search
4293 final static String QuickSearch_L = "http://www.google.com/m/search?site=local&q=%s&near=mountain+view";
4294
4295 final static String QUERY_PLACE_HOLDER = "%s";
4296
4297 // "source" parameter for Google search through search key
4298 final static String GOOGLE_SEARCH_SOURCE_SEARCHKEY = "browser-key";
4299 // "source" parameter for Google search through goto menu
4300 final static String GOOGLE_SEARCH_SOURCE_GOTO = "browser-goto";
4301 // "source" parameter for Google search through simplily type
4302 final static String GOOGLE_SEARCH_SOURCE_TYPE = "browser-type";
4303 // "source" parameter for Google search suggested by the browser
4304 final static String GOOGLE_SEARCH_SOURCE_SUGGEST = "browser-suggest";
4305 // "source" parameter for Google search from unknown source
4306 final static String GOOGLE_SEARCH_SOURCE_UNKNOWN = "unknown";
4307
4308 private final static String LOGTAG = "browser";
4309
The Android Open Source Project0c908882009-03-03 19:32:16 -08004310 private String mLastEnteredUrl;
4311
4312 private PowerManager.WakeLock mWakeLock;
4313 private final static int WAKELOCK_TIMEOUT = 5 * 60 * 1000; // 5 minutes
4314
4315 private Toast mStopToast;
4316
Leon Scroggins571b3762010-05-26 10:25:01 -04004317 private TitleBarBase mTitleBar;
Michael Kolba2b2ba82010-08-04 17:54:03 -07004318 private TabBar mTabBar;
Leon Scroggins81db3662009-06-04 17:45:11 -04004319
Ben Murdochbff2d602009-07-01 20:19:05 +01004320 private LinearLayout mErrorConsoleContainer = null;
4321 private boolean mShouldShowErrorConsole = false;
4322
The Android Open Source Project0c908882009-03-03 19:32:16 -08004323 // As the ids are dynamically created, we can't guarantee that they will
4324 // be in sequence, so this static array maps ids to a window number.
4325 final static private int[] WINDOW_SHORTCUT_ID_ARRAY =
4326 { R.id.window_one_menu_id, R.id.window_two_menu_id, R.id.window_three_menu_id,
4327 R.id.window_four_menu_id, R.id.window_five_menu_id, R.id.window_six_menu_id,
4328 R.id.window_seven_menu_id, R.id.window_eight_menu_id };
4329
4330 // monitor platform changes
4331 private IntentFilter mNetworkStateChangedFilter;
4332 private BroadcastReceiver mNetworkStateIntentReceiver;
4333
Grace Klobab4da0ad2009-05-14 14:45:40 -07004334 private BroadcastReceiver mPackageInstallationReceiver;
4335
Bjorn Bringerta7611812010-03-24 11:12:02 +00004336 private SystemAllowGeolocationOrigins mSystemAllowGeolocationOrigins;
4337
The Android Open Source Project0c908882009-03-03 19:32:16 -08004338 // activity requestCode
Nicolas Roard78a98e42009-05-11 13:34:17 +01004339 final static int COMBO_PAGE = 1;
4340 final static int DOWNLOAD_PAGE = 2;
4341 final static int PREFERENCES_PAGE = 3;
Leon Scroggins8d5fa432009-10-02 15:55:59 -04004342 final static int FILE_SELECTED = 4;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004343
Andrei Popescu540035d2009-09-18 18:59:20 +01004344 // the default <video> poster
4345 private Bitmap mDefaultVideoPoster;
4346 // the video progress view
4347 private View mVideoProgressView;
4348
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004349 /**
4350 * A UrlData class to abstract how the content will be set to WebView.
4351 * This base class uses loadUrl to show the content.
4352 */
Leon Scroggins6eac63e2010-03-15 18:19:14 -04004353 /* package */ static class UrlData {
Grace Kloba068e48b2010-01-26 18:11:27 -08004354 final String mUrl;
4355 final Map<String, String> mHeaders;
Leon Scroggins58d56c62010-01-28 15:12:40 -05004356 final Intent mVoiceIntent;
Grace Kloba60e095c2009-06-16 11:50:55 -07004357
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004358 UrlData(String url) {
4359 this.mUrl = url;
Grace Kloba068e48b2010-01-26 18:11:27 -08004360 this.mHeaders = null;
Leon Scroggins58d56c62010-01-28 15:12:40 -05004361 this.mVoiceIntent = null;
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004362 }
Grace Kloba60e095c2009-06-16 11:50:55 -07004363
Leon Scroggins58d56c62010-01-28 15:12:40 -05004364 UrlData(String url, Map<String, String> headers, Intent intent) {
Grace Kloba068e48b2010-01-26 18:11:27 -08004365 this.mUrl = url;
4366 this.mHeaders = headers;
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -05004367 if (RecognizerResultsIntent.ACTION_VOICE_SEARCH_RESULTS
4368 .equals(intent.getAction())) {
Leon Scroggins58d56c62010-01-28 15:12:40 -05004369 this.mVoiceIntent = intent;
4370 } else {
4371 this.mVoiceIntent = null;
4372 }
Grace Kloba60e095c2009-06-16 11:50:55 -07004373 }
4374
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004375 boolean isEmpty() {
Leon Scroggins58d56c62010-01-28 15:12:40 -05004376 return mVoiceIntent == null && (mUrl == null || mUrl.length() == 0);
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004377 }
4378
Leon Scroggins92472e82010-02-17 16:32:28 -05004379 /**
4380 * Load this UrlData into the given Tab. Use loadUrlDataIn to update
4381 * the title bar as well.
4382 */
Leon Scroggins58d56c62010-01-28 15:12:40 -05004383 public void loadIn(Tab t) {
4384 if (mVoiceIntent != null) {
4385 t.activateVoiceSearchMode(mVoiceIntent);
4386 } else {
4387 t.getWebView().loadUrl(mUrl, mHeaders);
4388 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004389 }
4390 };
4391
Leon Scroggins1f005d32009-08-10 17:36:42 -04004392 /* package */ static final UrlData EMPTY_URL_DATA = new UrlData(null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004393}