blob: 5fe62b140723f74a4ead1ddd886b4fcaafa8d14d [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;
Grace Klobab4da0ad2009-05-14 14:45:40 -070041import android.content.pm.PackageInfo;
The Android Open Source Project0c908882009-03-03 19:32:16 -080042import android.content.pm.PackageManager;
43import android.content.pm.ResolveInfo;
The Android Open Source Project0c908882009-03-03 19:32:16 -080044import android.content.res.Configuration;
45import android.content.res.Resources;
46import android.database.Cursor;
The Android Open Source Project0c908882009-03-03 19:32:16 -080047import android.graphics.Bitmap;
Andrei Popescu540035d2009-09-18 18:59:20 +010048import android.graphics.BitmapFactory;
The Android Open Source Project0c908882009-03-03 19:32:16 -080049import android.graphics.Canvas;
The Android Open Source Project0c908882009-03-03 19:32:16 -080050import android.graphics.Picture;
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -040051import android.graphics.PixelFormat;
The Android Open Source Project0c908882009-03-03 19:32:16 -080052import android.graphics.drawable.Drawable;
The Android Open Source Project0c908882009-03-03 19:32:16 -080053import android.net.ConnectivityManager;
Andrei Popescu56199cc2010-01-12 22:39:16 +000054import android.net.NetworkInfo;
The Android Open Source Project0c908882009-03-03 19:32:16 -080055import android.net.Uri;
56import android.net.WebAddress;
The Android Open Source Project0c908882009-03-03 19:32:16 -080057import android.net.http.SslCertificate;
58import android.net.http.SslError;
59import android.os.AsyncTask;
60import android.os.Bundle;
61import android.os.Debug;
62import android.os.Environment;
63import android.os.Handler;
The Android Open Source Project0c908882009-03-03 19:32:16 -080064import android.os.Message;
65import android.os.PowerManager;
66import android.os.Process;
The Android Open Source Project0c908882009-03-03 19:32:16 -080067import android.os.SystemClock;
The Android Open Source Project0c908882009-03-03 19:32:16 -080068import android.provider.Browser;
Jeff Hamilton8ce956c2010-08-17 11:13:53 -050069import android.provider.BrowserContract;
Cary Clark5e335a32009-09-22 14:53:11 -040070import android.provider.ContactsContract;
Michael Kolba2b2ba82010-08-04 17:54:03 -070071import android.provider.ContactsContract.Intents.Insert;
The Android Open Source Project0c908882009-03-03 19:32:16 -080072import android.provider.Downloads;
73import android.provider.MediaStore;
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -050074import android.speech.RecognizerResultsIntent;
The Android Open Source Project0c908882009-03-03 19:32:16 -080075import android.text.TextUtils;
76import android.text.format.DateFormat;
The Android Open Source Project0c908882009-03-03 19:32:16 -080077import android.util.Log;
Dianne Hackborn385effd2010-02-24 20:03:04 -080078import android.util.Patterns;
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -040079import android.view.ActionMode;
The Android Open Source Project0c908882009-03-03 19:32:16 -080080import android.view.ContextMenu;
Michael Kolba2b2ba82010-08-04 17:54:03 -070081import android.view.ContextMenu.ContextMenuInfo;
The Android Open Source Project0c908882009-03-03 19:32:16 -080082import android.view.Gravity;
83import android.view.KeyEvent;
84import android.view.LayoutInflater;
85import android.view.Menu;
86import android.view.MenuInflater;
87import android.view.MenuItem;
Michael Kolba2b2ba82010-08-04 17:54:03 -070088import android.view.MenuItem.OnMenuItemClickListener;
Michael Kolb3f65c382010-08-20 15:31:16 -070089import android.view.MotionEvent;
The Android Open Source Project0c908882009-03-03 19:32:16 -080090import android.view.View;
91import android.view.ViewGroup;
92import android.view.Window;
93import android.view.WindowManager;
Svetoslav Ganov2b345992010-05-06 06:13:54 -070094import android.view.accessibility.AccessibilityManager;
The Android Open Source Project0c908882009-03-03 19:32:16 -080095import android.webkit.CookieManager;
96import android.webkit.CookieSyncManager;
97import android.webkit.DownloadListener;
98import android.webkit.HttpAuthHandler;
Grace Klobab4da0ad2009-05-14 14:45:40 -070099import android.webkit.PluginManager;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800100import android.webkit.SslErrorHandler;
101import android.webkit.URLUtil;
Leon Clarkecb6cc862009-09-29 18:35:13 +0100102import android.webkit.ValueCallback;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800103import android.webkit.WebChromeClient;
104import android.webkit.WebHistoryItem;
105import android.webkit.WebIconDatabase;
106import android.webkit.WebView;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800107import android.widget.EditText;
108import android.widget.FrameLayout;
109import android.widget.LinearLayout;
110import android.widget.TextView;
111import android.widget.Toast;
112
Leon Scrogginsb6b7f9e2009-06-18 12:05:28 -0400113import java.io.ByteArrayOutputStream;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800114import java.io.File;
Ben Murdoch4f75ba22009-10-27 11:48:28 +0000115import java.io.IOException;
116import java.io.InputStream;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800117import java.net.MalformedURLException;
Dianne Hackborn99189432009-06-17 18:06:18 -0700118import java.net.URISyntaxException;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800119import java.net.URL;
120import java.net.URLEncoder;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800121import java.util.Date;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800122import java.util.HashMap;
Andrei Popescu30995e72010-02-09 16:59:58 +0000123import java.util.HashSet;
Grace Kloba00f54c52010-01-27 14:53:51 -0800124import java.util.Iterator;
Andrei Popescu30995e72010-02-09 16:59:58 +0000125import java.util.List;
Grace Kloba068e48b2010-01-26 18:11:27 -0800126import java.util.Map;
Andrei Popescu30995e72010-02-09 16:59:58 +0000127import java.util.Set;
Michael Kolbfe251992010-07-08 15:41:55 -0700128import java.util.Vector;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800129import java.util.regex.Matcher;
130import java.util.regex.Pattern;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800131
132public class BrowserActivity extends Activity
Shimeng (Simon) Wang98d5fce2010-03-16 13:23:39 -0700133 implements View.OnCreateContextMenuListener, DownloadListener {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800134
Dave Bort31a6d1c2009-04-13 15:56:49 -0700135 /* Define some aliases to make these debugging flags easier to refer to.
136 * This file imports android.provider.Browser, so we can't just refer to "Browser.DEBUG".
137 */
138 private final static boolean DEBUG = com.android.browser.Browser.DEBUG;
139 private final static boolean LOGV_ENABLED = com.android.browser.Browser.LOGV_ENABLED;
140 private final static boolean LOGD_ENABLED = com.android.browser.Browser.LOGD_ENABLED;
141
Satish Sampath565505b2009-05-29 15:37:27 +0100142 // These are single-character shortcuts for searching popular sources.
143 private static final int SHORTCUT_INVALID = 0;
144 private static final int SHORTCUT_GOOGLE_SEARCH = 1;
145 private static final int SHORTCUT_WIKIPEDIA_SEARCH = 2;
146 private static final int SHORTCUT_DICTIONARY_SEARCH = 3;
147 private static final int SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH = 4;
148
Cary Clarka9771242009-08-11 16:42:26 -0400149 private static class ClearThumbnails extends AsyncTask<File, Void, Void> {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800150 @Override
151 public Void doInBackground(File... files) {
152 if (files != null) {
153 for (File f : files) {
Cary Clarkd6be1752009-08-12 12:56:42 -0400154 if (!f.delete()) {
155 Log.e(LOGTAG, f.getPath() + " was not deleted");
156 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800157 }
158 }
159 return null;
160 }
161 }
162
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400163 /**
164 * This layout holds everything you see below the status bar, including the
165 * error console, the custom view container, and the webviews.
166 */
167 private FrameLayout mBrowserFrameLayout;
Leon Scroggins81db3662009-06-04 17:45:11 -0400168
Leon Scrogginsd746a942010-05-19 13:21:44 -0400169 private boolean mXLargeScreenSize;
170
Jeff Davidson43610292010-07-16 16:03:58 -0700171 private Boolean mIsProviderPresent = null;
172 private Uri mRlzUri = null;
173
Grace Kloba22ac16e2009-10-07 18:00:23 -0700174 @Override
175 public void onCreate(Bundle icicle) {
Dave Bort31a6d1c2009-04-13 15:56:49 -0700176 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800177 Log.v(LOGTAG, this + " onStart");
178 }
179 super.onCreate(icicle);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800180 // test the browser in OpenGL
181 // requestWindowFeature(Window.FEATURE_OPENGL);
182
Mike Reedd334bf52010-01-26 15:21:44 -0500183 // enable this to test the browser in 32bit
184 if (false) {
185 getWindow().setFormat(PixelFormat.RGBX_8888);
186 BitmapFactory.setDefaultConfig(Bitmap.Config.ARGB_8888);
187 }
188
Svetoslav Ganov2b345992010-05-06 06:13:54 -0700189 if (AccessibilityManager.getInstance(this).isEnabled()) {
190 setDefaultKeyMode(DEFAULT_KEYS_DISABLE);
191 } else {
192 setDefaultKeyMode(DEFAULT_KEYS_SEARCH_LOCAL);
193 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800194
195 mResolver = getContentResolver();
196
Grace Kloba0923d692009-09-23 21:37:25 -0700197 // If this was a web search request, pass it on to the default web
198 // search provider and finish this activity.
199 if (handleWebSearchIntent(getIntent())) {
200 finish();
201 return;
202 }
203
The Android Open Source Project0c908882009-03-03 19:32:16 -0800204 mSecLockIcon = Resources.getSystem().getDrawable(
205 android.R.drawable.ic_secure);
206 mMixLockIcon = Resources.getSystem().getDrawable(
207 android.R.drawable.ic_partial_secure);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800208
Michael Kolbed217742010-08-10 17:52:34 -0700209 // Create the tab control and our initial tab
210 mTabControl = new TabControl(this);
211
212 mXLargeScreenSize = (getResources().getConfiguration().screenLayout
213 & Configuration.SCREENLAYOUT_SIZE_MASK)
214 == Configuration.SCREENLAYOUT_SIZE_XLARGE;
215
Leon Scroggins81db3662009-06-04 17:45:11 -0400216 FrameLayout frameLayout = (FrameLayout) getWindow().getDecorView()
217 .findViewById(com.android.internal.R.id.content);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400218 mBrowserFrameLayout = (FrameLayout) LayoutInflater.from(this)
219 .inflate(R.layout.custom_screen, null);
220 mContentView = (FrameLayout) mBrowserFrameLayout.findViewById(
221 R.id.main_content);
222 mErrorConsoleContainer = (LinearLayout) mBrowserFrameLayout
223 .findViewById(R.id.error_console);
224 mCustomViewContainer = (FrameLayout) mBrowserFrameLayout
225 .findViewById(R.id.fullscreen_custom_content);
226 frameLayout.addView(mBrowserFrameLayout, COVER_SCREEN_PARAMS);
Michael Kolbe0a36662010-06-29 10:37:12 -0700227
Leon Scrogginsd746a942010-05-19 13:21:44 -0400228 if (mXLargeScreenSize) {
Michael Kolba2b2ba82010-08-04 17:54:03 -0700229 mTitleBar = new TitleBarXLarge(this);
230 mTitleBar.setProgress(100);
231 mFakeTitleBar = new TitleBarXLarge(this);
Michael Kolbed217742010-08-10 17:52:34 -0700232 ActionBar actionBar = getActionBar();
Michael Kolba2b2ba82010-08-04 17:54:03 -0700233 mTabBar = new TabBar(this, mTabControl, (TitleBarXLarge) mFakeTitleBar);
Michael Kolbed217742010-08-10 17:52:34 -0700234 actionBar.setCustomNavigationMode(mTabBar);
Leon Scrogginsd746a942010-05-19 13:21:44 -0400235 } else {
Leon Scroggins571b3762010-05-26 10:25:01 -0400236 mTitleBar = new TitleBar(this);
Leon Scrogginsd746a942010-05-19 13:21:44 -0400237 // mTitleBar will be always be shown in the fully loaded mode on
238 // phone
239 mTitleBar.setProgress(100);
Leon Scrogginsd746a942010-05-19 13:21:44 -0400240 mFakeTitleBar = new TitleBar(this);
241 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800242
The Android Open Source Project0c908882009-03-03 19:32:16 -0800243 // Open the icon database and retain all the bookmark urls for favicons
244 retainIconsOnStartup();
245
246 // Keep a settings instance handy.
247 mSettings = BrowserSettings.getInstance();
248 mSettings.setTabControl(mTabControl);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800249
250 PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
251 mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Browser");
252
Patrick Scott6adacc92010-03-05 08:24:51 -0500253 // Find out if the network is currently up.
254 ConnectivityManager cm = (ConnectivityManager) getSystemService(
255 Context.CONNECTIVITY_SERVICE);
256 NetworkInfo info = cm.getActiveNetworkInfo();
257 if (info != null) {
258 mIsNetworkUp = info.isAvailable();
259 }
260
Grace Klobaa34f6862009-07-31 16:28:17 -0700261 /* enables registration for changes in network status from
262 http stack */
263 mNetworkStateChangedFilter = new IntentFilter();
264 mNetworkStateChangedFilter.addAction(
265 ConnectivityManager.CONNECTIVITY_ACTION);
266 mNetworkStateIntentReceiver = new BroadcastReceiver() {
267 @Override
268 public void onReceive(Context context, Intent intent) {
269 if (intent.getAction().equals(
270 ConnectivityManager.CONNECTIVITY_ACTION)) {
Andrei Popescue4c98462010-02-19 15:44:13 +0000271
272 NetworkInfo info = intent.getParcelableExtra(
273 ConnectivityManager.EXTRA_NETWORK_INFO);
274 String typeName = info.getTypeName();
275 String subtypeName = info.getSubtypeName();
276 sendNetworkType(typeName.toLowerCase(),
277 (subtypeName != null ? subtypeName.toLowerCase() : ""));
278
279 onNetworkToggle(info.isAvailable());
Grace Klobaa34f6862009-07-31 16:28:17 -0700280 }
281 }
282 };
283
The Android Open Source Project0c908882009-03-03 19:32:16 -0800284 if (!mTabControl.restoreState(icicle)) {
285 // clear up the thumbnail directory if we can't restore the state as
286 // none of the files in the directory are referenced any more.
287 new ClearThumbnails().execute(
288 mTabControl.getThumbnailDir().listFiles());
Grace Klobaaab3f092009-07-30 12:29:51 -0700289 // there is no quit on Android. But if we can't restore the state,
290 // we can treat it as a new Browser, remove the old session cookies.
291 CookieManager.getInstance().removeSessionCookie();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800292 final Intent intent = getIntent();
293 final Bundle extra = intent.getExtras();
294 // Create an initial tab.
295 // If the intent is ACTION_VIEW and data is not null, the Browser is
296 // invoked to view the content by another application. In this case,
297 // the tab will be close when exit.
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700298 UrlData urlData = getUrlDataFromIntent(intent);
299
Leon Scroggins58d56c62010-01-28 15:12:40 -0500300 String action = intent.getAction();
Grace Kloba22ac16e2009-10-07 18:00:23 -0700301 final Tab t = mTabControl.createNewTab(
Leon Scroggins58d56c62010-01-28 15:12:40 -0500302 (Intent.ACTION_VIEW.equals(action) &&
303 intent.getData() != null)
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -0500304 || RecognizerResultsIntent.ACTION_VOICE_SEARCH_RESULTS
305 .equals(action),
Elliott Slaughterf0f03952010-07-14 18:10:36 -0700306 intent.getStringExtra(Browser.EXTRA_APPLICATION_ID),
307 urlData.mUrl, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800308 mTabControl.setCurrentTab(t);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800309 attachTabToContentView(t);
310 WebView webView = t.getWebView();
311 if (extra != null) {
312 int scale = extra.getInt(Browser.INITIAL_ZOOM_LEVEL, 0);
313 if (scale > 0 && scale <= 1000) {
314 webView.setInitialScale(scale);
315 }
316 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800317
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700318 if (urlData.isEmpty()) {
Shimeng (Simon) Wang98d5fce2010-03-16 13:23:39 -0700319 loadUrl(webView, mSettings.getHomePage());
The Android Open Source Project0c908882009-03-03 19:32:16 -0800320 } else {
Patrick Scott9d53da02010-02-19 10:19:01 -0500321 loadUrlDataIn(t, urlData);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800322 }
323 } else {
324 // TabControl.restoreState() will create a new tab even if
Leon Scroggins1f005d32009-08-10 17:36:42 -0400325 // restoring the state fails.
The Android Open Source Project0c908882009-03-03 19:32:16 -0800326 attachTabToContentView(mTabControl.getCurrentTab());
327 }
Grace Kloba615c6c92009-08-03 10:22:44 -0700328
Cary Clarkb4b83182010-07-01 12:36:56 -0400329 // Delete old thumbnails to save space
330 File dir = mTabControl.getThumbnailDir();
331 if (dir.exists()) {
332 for (String child : dir.list()) {
333 File f = new File(dir, child);
334 f.delete();
335 }
336 }
337
Feng Qianb3c02da2009-06-29 15:58:08 -0700338 // Read JavaScript flags if it exists.
339 String jsFlags = mSettings.getJsFlags();
340 if (jsFlags.trim().length() != 0) {
341 mTabControl.getCurrentWebView().setJsFlags(jsFlags);
342 }
Bjorn Bringerta7611812010-03-24 11:12:02 +0000343
344 // Start watching the default geolocation permissions
345 mSystemAllowGeolocationOrigins
346 = new SystemAllowGeolocationOrigins(getApplicationContext());
347 mSystemAllowGeolocationOrigins.start();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800348 }
349
Michael Kolba2b2ba82010-08-04 17:54:03 -0700350 ScrollListener getScrollListener() {
351 return mTabBar;
352 }
353
Leon Scroggins58d56c62010-01-28 15:12:40 -0500354 /**
355 * Feed the previously stored results strings to the BrowserProvider so that
356 * the SearchDialog will show them instead of the standard searches.
357 * @param result String to show on the editable line of the SearchDialog.
358 */
359 /* package */ void showVoiceSearchResults(String result) {
360 ContentProviderClient client = mResolver.acquireContentProviderClient(
361 Browser.BOOKMARKS_URI);
362 ContentProvider prov = client.getLocalContentProvider();
363 BrowserProvider bp = (BrowserProvider) prov;
364 bp.setQueryResults(mTabControl.getCurrentTab().getVoiceSearchResults());
365 client.release();
366
Leon Scrogginsfbb3f152010-03-09 17:26:56 -0500367 Bundle bundle = createGoogleSearchSourceBundle(
368 GOOGLE_SEARCH_SOURCE_SEARCHKEY);
369 bundle.putBoolean(SearchManager.CONTEXT_IS_VOICE, true);
370 startSearch(result, false, bundle, false);
Leon Scroggins58d56c62010-01-28 15:12:40 -0500371 }
372
The Android Open Source Project0c908882009-03-03 19:32:16 -0800373 @Override
374 protected void onNewIntent(Intent intent) {
Grace Kloba22ac16e2009-10-07 18:00:23 -0700375 Tab current = mTabControl.getCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800376 // When a tab is closed on exit, the current tab index is set to -1.
377 // Reset before proceed as Browser requires the current tab to be set.
378 if (current == null) {
379 // Try to reset the tab in case the index was incorrect.
380 current = mTabControl.getTab(0);
381 if (current == null) {
382 // No tabs at all so just ignore this intent.
383 return;
384 }
385 mTabControl.setCurrentTab(current);
386 attachTabToContentView(current);
387 resetTitleAndIcon(current.getWebView());
388 }
389 final String action = intent.getAction();
390 final int flags = intent.getFlags();
391 if (Intent.ACTION_MAIN.equals(action) ||
392 (flags & Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY) != 0) {
393 // just resume the browser
394 return;
395 }
Leon Scrogginsb8a844d2010-03-18 15:06:15 -0400396 // In case the SearchDialog is open.
397 ((SearchManager) getSystemService(Context.SEARCH_SERVICE))
398 .stopSearch();
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -0500399 boolean activateVoiceSearch = RecognizerResultsIntent
400 .ACTION_VOICE_SEARCH_RESULTS.equals(action);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800401 if (Intent.ACTION_VIEW.equals(action)
402 || Intent.ACTION_SEARCH.equals(action)
403 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
Leon Scroggins58d56c62010-01-28 15:12:40 -0500404 || Intent.ACTION_WEB_SEARCH.equals(action)
405 || activateVoiceSearch) {
Leon Scroggins3b18ce32010-02-08 17:35:59 -0500406 if (current.isInVoiceSearchMode()) {
407 String title = current.getVoiceDisplayTitle();
408 if (title != null && title.equals(intent.getStringExtra(
409 SearchManager.QUERY))) {
410 // The user submitted the same search as the last voice
411 // search, so do nothing.
412 return;
413 }
Leon Scroggins1fe13a52010-02-09 15:31:26 -0500414 if (Intent.ACTION_SEARCH.equals(action)
415 && current.voiceSearchSourceIsGoogle()) {
416 Intent logIntent = new Intent(
417 LoggingEvents.ACTION_LOG_EVENT);
418 logIntent.putExtra(LoggingEvents.EXTRA_EVENT,
419 LoggingEvents.VoiceSearch.QUERY_UPDATED);
420 logIntent.putExtra(
421 LoggingEvents.VoiceSearch.EXTRA_QUERY_UPDATED_VALUE,
422 intent.getDataString());
423 sendBroadcast(logIntent);
424 // Note, onPageStarted will revert the voice title bar
425 // When http://b/issue?id=2379215 is fixed, we should update
426 // the title bar here.
427 }
Leon Scroggins3b18ce32010-02-08 17:35:59 -0500428 }
Satish Sampath565505b2009-05-29 15:37:27 +0100429 // If this was a search request (e.g. search query directly typed into the address bar),
430 // pass it on to the default web search provider.
431 if (handleWebSearchIntent(intent)) {
432 return;
433 }
434
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700435 UrlData urlData = getUrlDataFromIntent(intent);
436 if (urlData.isEmpty()) {
437 urlData = new UrlData(mSettings.getHomePage());
The Android Open Source Project0c908882009-03-03 19:32:16 -0800438 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700439
Grace Klobacc634032009-07-28 15:58:19 -0700440 final String appId = intent
441 .getStringExtra(Browser.EXTRA_APPLICATION_ID);
Leon Scroggins47208682010-04-07 17:59:48 -0400442 if ((Intent.ACTION_VIEW.equals(action)
443 // If a voice search has no appId, it means that it came
444 // from the browser. In that case, reuse the current tab.
445 || (activateVoiceSearch && appId != null))
Grace Klobacc634032009-07-28 15:58:19 -0700446 && !getPackageName().equals(appId)
447 && (flags & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0) {
Grace Kloba22ac16e2009-10-07 18:00:23 -0700448 Tab appTab = mTabControl.getTabFromId(appId);
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700449 if (appTab != null) {
450 Log.i(LOGTAG, "Reusing tab for " + appId);
451 // Dismiss the subwindow if applicable.
452 dismissSubWindow(appTab);
453 // Since we might kill the WebView, remove it from the
454 // content view first.
455 removeTabFromContentView(appTab);
456 // Recreate the main WebView after destroying the old one.
457 // If the WebView has the same original url and is on that
458 // page, it can be reused.
459 boolean needsLoad =
Leon Scroggins6eac63e2010-03-15 18:19:14 -0400460 mTabControl.recreateWebView(appTab, urlData);
Ben Murdochbff2d602009-07-01 20:19:05 +0100461
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700462 if (current != appTab) {
Leon Scroggins1f005d32009-08-10 17:36:42 -0400463 switchToTab(mTabControl.getTabIndex(appTab));
464 if (needsLoad) {
Patrick Scott9d53da02010-02-19 10:19:01 -0500465 loadUrlDataIn(appTab, urlData);
Leon Scroggins1f005d32009-08-10 17:36:42 -0400466 }
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700467 } else {
Leon Scroggins1f005d32009-08-10 17:36:42 -0400468 // If the tab was the current tab, we have to attach
469 // it to the view system again.
470 attachTabToContentView(appTab);
471 if (needsLoad) {
Patrick Scott9d53da02010-02-19 10:19:01 -0500472 loadUrlDataIn(appTab, urlData);
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700473 }
474 }
475 return;
Patrick Scottcd115892009-07-16 09:42:58 -0400476 } else {
477 // No matching application tab, try to find a regular tab
478 // with a matching url.
479 appTab = mTabControl.findUnusedTabWithUrl(urlData.mUrl);
Leon Scroggins25515f82009-08-19 15:31:58 -0400480 if (appTab != null) {
481 if (current != appTab) {
482 switchToTab(mTabControl.getTabIndex(appTab));
483 }
484 // Otherwise, we are already viewing the correct tab.
Patrick Scottcd115892009-07-16 09:42:58 -0400485 } else {
486 // if FLAG_ACTIVITY_BROUGHT_TO_FRONT flag is on, the url
487 // will be opened in a new tab unless we have reached
488 // MAX_TABS. Then the url will be opened in the current
489 // tab. If a new tab is created, it will have "true" for
490 // exit on close.
Leon Scroggins1f005d32009-08-10 17:36:42 -0400491 openTabAndShow(urlData, true, appId);
Patrick Scottcd115892009-07-16 09:42:58 -0400492 }
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700493 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800494 } else {
Grace Kloba638d3f42009-11-23 10:35:04 -0800495 if (!urlData.isEmpty()
496 && urlData.mUrl.startsWith("about:debug")) {
497 if ("about:debug.dom".equals(urlData.mUrl)) {
498 current.getWebView().dumpDomTree(false);
499 } else if ("about:debug.dom.file".equals(urlData.mUrl)) {
500 current.getWebView().dumpDomTree(true);
501 } else if ("about:debug.render".equals(urlData.mUrl)) {
502 current.getWebView().dumpRenderTree(false);
503 } else if ("about:debug.render.file".equals(urlData.mUrl)) {
504 current.getWebView().dumpRenderTree(true);
505 } else if ("about:debug.display".equals(urlData.mUrl)) {
506 current.getWebView().dumpDisplayTree();
Mike Reed9b78e1d2010-01-13 14:40:52 -0800507 } else if (urlData.mUrl.startsWith("about:debug.drag")) {
508 int index = urlData.mUrl.codePointAt(16) - '0';
509 if (index <= 0 || index > 9) {
510 current.getWebView().setDragTracker(null);
511 } else {
512 current.getWebView().setDragTracker(new MeshTracker(index));
513 }
Grace Kloba638d3f42009-11-23 10:35:04 -0800514 } else {
515 mSettings.toggleDebugSettings();
516 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800517 return;
518 }
Leon Scroggins1f005d32009-08-10 17:36:42 -0400519 // Get rid of the subwindow if it exists
520 dismissSubWindow(current);
Leon Scroggins8588d152010-04-15 11:01:53 -0400521 // If the current Tab is being used as an application tab,
522 // remove the association, since the new Intent means that it is
523 // no longer associated with that application.
524 current.setAppId(null);
Patrick Scott9d53da02010-02-19 10:19:01 -0500525 loadUrlDataIn(current, urlData);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800526 }
527 }
528 }
529
Satish Sampath565505b2009-05-29 15:37:27 +0100530 private int parseUrlShortcut(String url) {
531 if (url == null) return SHORTCUT_INVALID;
532
533 // FIXME: quick search, need to be customized by setting
534 if (url.length() > 2 && url.charAt(1) == ' ') {
535 switch (url.charAt(0)) {
536 case 'g': return SHORTCUT_GOOGLE_SEARCH;
537 case 'w': return SHORTCUT_WIKIPEDIA_SEARCH;
538 case 'd': return SHORTCUT_DICTIONARY_SEARCH;
539 case 'l': return SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH;
540 }
541 }
542 return SHORTCUT_INVALID;
543 }
544
545 /**
546 * Launches the default web search activity with the query parameters if the given intent's data
547 * are identified as plain search terms and not URLs/shortcuts.
548 * @return true if the intent was handled and web search activity was launched, false if not.
549 */
550 private boolean handleWebSearchIntent(Intent intent) {
551 if (intent == null) return false;
552
553 String url = null;
554 final String action = intent.getAction();
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -0500555 if (RecognizerResultsIntent.ACTION_VOICE_SEARCH_RESULTS.equals(
556 action)) {
Leon Scroggins58d56c62010-01-28 15:12:40 -0500557 return false;
558 }
Satish Sampath565505b2009-05-29 15:37:27 +0100559 if (Intent.ACTION_VIEW.equals(action)) {
Grace Kloba1e705052009-09-29 13:13:36 -0700560 Uri data = intent.getData();
561 if (data != null) url = data.toString();
Satish Sampath565505b2009-05-29 15:37:27 +0100562 } else if (Intent.ACTION_SEARCH.equals(action)
563 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
564 || Intent.ACTION_WEB_SEARCH.equals(action)) {
565 url = intent.getStringExtra(SearchManager.QUERY);
566 }
Bjorn Bringert04851702009-09-22 10:36:01 +0100567 return handleWebSearchRequest(url, intent.getBundleExtra(SearchManager.APP_DATA),
568 intent.getStringExtra(SearchManager.EXTRA_DATA_KEY));
Satish Sampath565505b2009-05-29 15:37:27 +0100569 }
570
571 /**
572 * Launches the default web search activity with the query parameters if the given url string
573 * was identified as plain search terms and not URL/shortcut.
574 * @return true if the request was handled and web search activity was launched, false if not.
575 */
Bjorn Bringert04851702009-09-22 10:36:01 +0100576 private boolean handleWebSearchRequest(String inUrl, Bundle appData, String extraData) {
Satish Sampath565505b2009-05-29 15:37:27 +0100577 if (inUrl == null) return false;
578
579 // In general, we shouldn't modify URL from Intent.
580 // But currently, we get the user-typed URL from search box as well.
581 String url = fixUrl(inUrl).trim();
582
583 // URLs and site specific search shortcuts are handled by the regular flow of control, so
584 // return early.
Dan Egnor5ee906c2009-11-18 12:11:49 -0800585 if (Patterns.WEB_URL.matcher(url).matches()
Satish Sampathbc5b9f32009-06-04 18:21:40 +0100586 || ACCEPTED_URI_SCHEMA.matcher(url).matches()
Satish Sampath565505b2009-05-29 15:37:27 +0100587 || parseUrlShortcut(url) != SHORTCUT_INVALID) {
588 return false;
589 }
590
Leon Scroggins8d06e362010-03-24 14:45:57 -0400591 final ContentResolver cr = mResolver;
592 final String newUrl = url;
Elliott Slaughter627d96f2010-08-18 16:35:30 -0700593 if (mTabControl == null || !mTabControl.getCurrentWebView().isPrivateBrowsingEnabled()) {
Elliott Slaughterf0f03952010-07-14 18:10:36 -0700594 new AsyncTask<Void, Void, Void>() {
595 @Override
596 protected Void doInBackground(Void... unused) {
597 Browser.updateVisitedHistory(cr, newUrl, false);
598 Browser.addSearchUrl(cr, newUrl);
599 return null;
600 }
601 }.execute();
602 }
Satish Sampath565505b2009-05-29 15:37:27 +0100603
604 Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);
605 intent.addCategory(Intent.CATEGORY_DEFAULT);
606 intent.putExtra(SearchManager.QUERY, url);
Satish Sampath15e9f2d2009-06-23 22:29:49 +0100607 if (appData != null) {
608 intent.putExtra(SearchManager.APP_DATA, appData);
609 }
Bjorn Bringert04851702009-09-22 10:36:01 +0100610 if (extraData != null) {
611 intent.putExtra(SearchManager.EXTRA_DATA_KEY, extraData);
612 }
Grace Klobacc634032009-07-28 15:58:19 -0700613 intent.putExtra(Browser.EXTRA_APPLICATION_ID, getPackageName());
Satish Sampath565505b2009-05-29 15:37:27 +0100614 startActivity(intent);
615
616 return true;
617 }
618
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700619 private UrlData getUrlDataFromIntent(Intent intent) {
Leon Scroggins58d56c62010-01-28 15:12:40 -0500620 String url = "";
Grace Kloba068e48b2010-01-26 18:11:27 -0800621 Map<String, String> headers = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800622 if (intent != null) {
623 final String action = intent.getAction();
624 if (Intent.ACTION_VIEW.equals(action)) {
625 url = smartUrlFilter(intent.getData());
626 if (url != null && url.startsWith("content:")) {
627 /* Append mimetype so webview knows how to display */
628 String mimeType = intent.resolveType(getContentResolver());
629 if (mimeType != null) {
630 url += "?" + mimeType;
631 }
632 }
Grace Kloba068e48b2010-01-26 18:11:27 -0800633 if (url != null && url.startsWith("http")) {
Grace Kloba00f54c52010-01-27 14:53:51 -0800634 final Bundle pairs = intent
635 .getBundleExtra(Browser.EXTRA_HEADERS);
Grace Kloba2d508ed2010-01-28 11:39:15 -0800636 if (pairs != null && !pairs.isEmpty()) {
Grace Kloba00f54c52010-01-27 14:53:51 -0800637 Iterator<String> iter = pairs.keySet().iterator();
Grace Kloba068e48b2010-01-26 18:11:27 -0800638 headers = new HashMap<String, String>();
Grace Kloba00f54c52010-01-27 14:53:51 -0800639 while (iter.hasNext()) {
640 String key = iter.next();
641 headers.put(key, pairs.getString(key));
Grace Kloba068e48b2010-01-26 18:11:27 -0800642 }
643 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700644 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800645 } else if (Intent.ACTION_SEARCH.equals(action)
646 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
647 || Intent.ACTION_WEB_SEARCH.equals(action)) {
648 url = intent.getStringExtra(SearchManager.QUERY);
649 if (url != null) {
650 mLastEnteredUrl = url;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800651 // In general, we shouldn't modify URL from Intent.
652 // But currently, we get the user-typed URL from search box as well.
653 url = fixUrl(url);
654 url = smartUrlFilter(url);
Leon Scroggins8d06e362010-03-24 14:45:57 -0400655 final ContentResolver cr = mResolver;
656 final String newUrl = url;
Elliott Slaughter8389e992010-08-20 15:44:08 -0700657 if (mTabControl == null
658 || mTabControl.getCurrentWebView() == null
659 || !mTabControl.getCurrentWebView().isPrivateBrowsingEnabled()) {
660 new AsyncTask<Void, Void, Void>() {
661 @Override
662 protected Void doInBackground(Void... unused) {
663 Browser.updateVisitedHistory(cr, newUrl, false);
664 return null;
665 }
666 }.execute();
667 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800668 String searchSource = "&source=android-" + GOOGLE_SEARCH_SOURCE_SUGGEST + "&";
669 if (url.contains(searchSource)) {
670 String source = null;
671 final Bundle appData = intent.getBundleExtra(SearchManager.APP_DATA);
672 if (appData != null) {
Bjorn Bringert10d1cca2010-02-10 14:22:12 +0000673 source = appData.getString(Search.SOURCE);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800674 }
675 if (TextUtils.isEmpty(source)) {
676 source = GOOGLE_SEARCH_SOURCE_UNKNOWN;
677 }
678 url = url.replace(searchSource, "&source=android-"+source+"&");
679 }
680 }
681 }
682 }
Leon Scroggins58d56c62010-01-28 15:12:40 -0500683 return new UrlData(url, headers, intent);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800684 }
Leon Scroggins58d56c62010-01-28 15:12:40 -0500685 /* package */ void showVoiceTitleBar(String title) {
686 mTitleBar.setInVoiceMode(true);
Leon Scroggins58d56c62010-01-28 15:12:40 -0500687 mTitleBar.setDisplayTitle(title);
Michael Kolba2b2ba82010-08-04 17:54:03 -0700688 mFakeTitleBar.setInVoiceMode(true);
689 mFakeTitleBar.setDisplayTitle(title);
Leon Scroggins58d56c62010-01-28 15:12:40 -0500690 }
691 /* package */ void revertVoiceTitleBar() {
692 mTitleBar.setInVoiceMode(false);
Leon Scroggins003a5dd2010-03-10 12:13:14 -0500693 mTitleBar.setDisplayTitle(mUrl);
Michael Kolba2b2ba82010-08-04 17:54:03 -0700694 mFakeTitleBar.setInVoiceMode(false);
695 mFakeTitleBar.setDisplayTitle(mUrl);
Leon Scroggins58d56c62010-01-28 15:12:40 -0500696 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800697 /* package */ static String fixUrl(String inUrl) {
Cary Clark652ff872009-09-10 13:34:44 -0400698 // FIXME: Converting the url to lower case
699 // duplicates functionality in smartUrlFilter().
700 // However, changing all current callers of fixUrl to
701 // call smartUrlFilter in addition may have unwanted
702 // consequences, and is deferred for now.
703 int colon = inUrl.indexOf(':');
704 boolean allLower = true;
705 for (int index = 0; index < colon; index++) {
706 char ch = inUrl.charAt(index);
707 if (!Character.isLetter(ch)) {
708 break;
709 }
710 allLower &= Character.isLowerCase(ch);
711 if (index == colon - 1 && !allLower) {
712 inUrl = inUrl.substring(0, colon).toLowerCase()
713 + inUrl.substring(colon);
714 }
715 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800716 if (inUrl.startsWith("http://") || inUrl.startsWith("https://"))
717 return inUrl;
718 if (inUrl.startsWith("http:") ||
719 inUrl.startsWith("https:")) {
720 if (inUrl.startsWith("http:/") || inUrl.startsWith("https:/")) {
721 inUrl = inUrl.replaceFirst("/", "//");
722 } else inUrl = inUrl.replaceFirst(":", "://");
723 }
724 return inUrl;
725 }
726
Grace Kloba22ac16e2009-10-07 18:00:23 -0700727 @Override
728 protected void onResume() {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800729 super.onResume();
Dave Bort31a6d1c2009-04-13 15:56:49 -0700730 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800731 Log.v(LOGTAG, "BrowserActivity.onResume: this=" + this);
732 }
733
734 if (!mActivityInPause) {
735 Log.e(LOGTAG, "BrowserActivity is already resumed.");
736 return;
737 }
738
Mike Reed7bfa63b2009-05-28 11:08:32 -0400739 mTabControl.resumeCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800740 mActivityInPause = false;
Mike Reed7bfa63b2009-05-28 11:08:32 -0400741 resumeWebViewTimers();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800742
743 if (mWakeLock.isHeld()) {
744 mHandler.removeMessages(RELEASE_WAKELOCK);
745 mWakeLock.release();
746 }
747
The Android Open Source Project0c908882009-03-03 19:32:16 -0800748 registerReceiver(mNetworkStateIntentReceiver,
749 mNetworkStateChangedFilter);
750 WebView.enablePlatformNotifications();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800751 }
752
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400753 /**
754 * Since the actual title bar is embedded in the WebView, and removing it
Leon Scrogginsfe87bd32009-10-06 10:10:00 -0400755 * would change its appearance, use a different TitleBar to show overlayed
756 * at the top of the screen, when the menu is open or the page is loading.
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400757 */
Michael Kolba2b2ba82010-08-04 17:54:03 -0700758 private TitleBarBase mFakeTitleBar;
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400759
760 /**
761 * Keeps track of whether the options menu is open. This is important in
762 * determining whether to show or hide the title bar overlay.
763 */
764 private boolean mOptionsMenuOpen;
765
766 /**
767 * Only meaningful when mOptionsMenuOpen is true. This variable keeps track
768 * of whether the configuration has changed. The first onMenuOpened call
769 * after a configuration change is simply a reopening of the same menu
770 * (i.e. mIconView did not change).
771 */
772 private boolean mConfigChanged;
773
774 /**
775 * Whether or not the options menu is in its smaller, icon menu form. When
776 * true, we want the title bar overlay to be up. When false, we do not.
777 * Only meaningful if mOptionsMenuOpen is true.
778 */
779 private boolean mIconView;
780
Leon Scrogginsa81a7642009-08-31 17:05:41 -0400781 @Override
782 public boolean onMenuOpened(int featureId, Menu menu) {
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400783 if (Window.FEATURE_OPTIONS_PANEL == featureId) {
784 if (mOptionsMenuOpen) {
785 if (mConfigChanged) {
786 // We do not need to make any changes to the state of the
787 // title bar, since the only thing that happened was a
788 // change in orientation
789 mConfigChanged = false;
790 } else {
791 if (mIconView) {
792 // Switching the menu to expanded view, so hide the
793 // title bar.
794 hideFakeTitleBar();
795 mIconView = false;
796 } else {
797 // Switching the menu back to icon view, so show the
798 // title bar once again.
799 showFakeTitleBar();
800 mIconView = true;
801 }
802 }
803 } else {
804 // The options menu is closed, so open it, and show the title
805 showFakeTitleBar();
806 mOptionsMenuOpen = true;
807 mConfigChanged = false;
808 mIconView = true;
809 }
810 }
Leon Scrogginsa81a7642009-08-31 17:05:41 -0400811 return true;
812 }
813
Michael Kolba2b2ba82010-08-04 17:54:03 -0700814 void showFakeTitleBar() {
815 if (!isFakeTitleBarShowing() && mActiveTabsPage == null && !mActivityInPause) {
Grace Kloba847c25b2010-03-30 16:00:26 -0700816 WebView mainView = mTabControl.getCurrentWebView();
817 // if there is no current WebView, don't show the faked title bar;
Grace Kloba65190702010-04-02 23:37:26 -0700818 if (mainView == null) {
Cary Clarka0464552009-09-29 13:00:45 -0400819 return;
820 }
Leon Scroggins79e36d92010-04-29 16:01:46 +0100821 // Do not need to check for null, since the current tab will have
822 // at least a main WebView, or we would have returned above.
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -0400823 if (isInCustomActionMode()) {
824 // Do not show the fake title bar, while a custom ActionMode
825 // (i.e. find or select) is showing.
Leon Scroggins79e36d92010-04-29 16:01:46 +0100826 return;
827 }
Michael Kolba2b2ba82010-08-04 17:54:03 -0700828 if (mXLargeScreenSize) {
829 mContentView.addView(mFakeTitleBar);
830 mTabBar.onShowTitleBar();
831 } else {
832 WindowManager manager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400833
Michael Kolba2b2ba82010-08-04 17:54:03 -0700834 // Add the title bar to the window manager so it can receive
835 // touches
836 // while the menu is up
837 WindowManager.LayoutParams params =
838 new WindowManager.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
839 ViewGroup.LayoutParams.WRAP_CONTENT,
840 WindowManager.LayoutParams.TYPE_APPLICATION,
841 WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
842 PixelFormat.TRANSLUCENT);
843 params.gravity = Gravity.TOP;
844 boolean atTop = mainView.getScrollY() == 0;
845 params.windowAnimations = atTop ? 0 : R.style.TitleBar;
846 manager.addView(mFakeTitleBar, params);
847 }
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400848 }
849 }
850
851 @Override
852 public void onOptionsMenuClosed(Menu menu) {
853 mOptionsMenuOpen = false;
Leon Scrogginsa27ff192009-09-14 12:58:04 -0400854 if (!mInLoad) {
855 hideFakeTitleBar();
856 } else if (!mIconView) {
857 // The page is currently loading, and we are in expanded mode, so
858 // we were not showing the menu. Show it once again. It will be
859 // removed when the page finishes.
860 showFakeTitleBar();
861 }
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400862 }
Grace Kloba22ac16e2009-10-07 18:00:23 -0700863
Michael Kolba2b2ba82010-08-04 17:54:03 -0700864 void stopScrolling() {
865 ((ScrollWebView) mTabControl.getCurrentWebView()).stopScroll();
866 }
867
868 void hideFakeTitleBar() {
869 if (!isFakeTitleBarShowing()) return;
870 if (mXLargeScreenSize) {
871 mContentView.removeView(mFakeTitleBar);
872 mTabBar.onHideTitleBar();
873 } else {
874 WindowManager.LayoutParams params =
875 (WindowManager.LayoutParams) mFakeTitleBar.getLayoutParams();
876 WebView mainView = mTabControl.getCurrentWebView();
877 // Although we decided whether or not to animate based on the
878 // current
879 // scroll position, the scroll position may have changed since the
880 // fake title bar was displayed. Make sure it has the appropriate
881 // animation/lack thereof before removing.
882 params.windowAnimations =
883 mainView != null && mainView.getScrollY() == 0 ? 0 : R.style.TitleBar;
884 WindowManager manager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
885 manager.updateViewLayout(mFakeTitleBar, params);
886 manager.removeView(mFakeTitleBar);
887 }
888 }
889
890 boolean isFakeTitleBarShowing() {
891 return (mFakeTitleBar.getParent() != null);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400892 }
893
The Android Open Source Project0c908882009-03-03 19:32:16 -0800894 /**
Leon Scrogginsc6fa1102009-09-21 10:40:01 -0400895 * Special method for the fake title bar to call when displaying its context
896 * menu, since it is in its own Window, and its parent does not show a
897 * context menu.
898 */
899 /* package */ void showTitleBarContextMenu() {
Cary Clark65f4a3c2009-09-28 17:05:06 -0400900 if (null == mTitleBar.getParent()) {
901 return;
902 }
Leon Scrogginsc6fa1102009-09-21 10:40:01 -0400903 openContextMenu(mTitleBar);
904 }
905
Leon Scrogginsb2b19f52009-10-09 16:10:00 -0400906 @Override
907 public void onContextMenuClosed(Menu menu) {
908 super.onContextMenuClosed(menu);
909 if (mInLoad) {
910 showFakeTitleBar();
911 }
912 }
913
Leon Scrogginsc6fa1102009-09-21 10:40:01 -0400914 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -0800915 * onSaveInstanceState(Bundle map)
916 * onSaveInstanceState is called right before onStop(). The map contains
917 * the saved state.
918 */
Grace Kloba22ac16e2009-10-07 18:00:23 -0700919 @Override
920 protected void onSaveInstanceState(Bundle outState) {
Dave Bort31a6d1c2009-04-13 15:56:49 -0700921 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800922 Log.v(LOGTAG, "BrowserActivity.onSaveInstanceState: this=" + this);
923 }
924 // the default implementation requires each view to have an id. As the
925 // browser handles the state itself and it doesn't use id for the views,
926 // don't call the default implementation. Otherwise it will trigger the
927 // warning like this, "couldn't save which view has focus because the
928 // focused view XXX has no id".
929
930 // Save all the tabs
931 mTabControl.saveState(outState);
932 }
933
Grace Kloba22ac16e2009-10-07 18:00:23 -0700934 @Override
935 protected void onPause() {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800936 super.onPause();
937
938 if (mActivityInPause) {
939 Log.e(LOGTAG, "BrowserActivity is already paused.");
940 return;
941 }
942
Mike Reed7bfa63b2009-05-28 11:08:32 -0400943 mTabControl.pauseCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800944 mActivityInPause = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -0400945 if (mTabControl.getCurrentIndex() >= 0 && !pauseWebViewTimers()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800946 mWakeLock.acquire();
947 mHandler.sendMessageDelayed(mHandler
948 .obtainMessage(RELEASE_WAKELOCK), WAKELOCK_TIMEOUT);
949 }
950
Leon Scrogginsa2ab6a72009-09-11 11:49:52 -0400951 // FIXME: This removes the active tabs page and resets the menu to
952 // MAIN_MENU. A better solution might be to do this work in onNewIntent
953 // but then we would need to save it in onSaveInstanceState and restore
954 // it in onCreate/onRestoreInstanceState
955 if (mActiveTabsPage != null) {
956 removeActiveTabPage(true);
957 }
958
The Android Open Source Project0c908882009-03-03 19:32:16 -0800959 cancelStopToast();
960
961 // unregister network state listener
962 unregisterReceiver(mNetworkStateIntentReceiver);
963 WebView.disablePlatformNotifications();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800964 }
965
Grace Kloba22ac16e2009-10-07 18:00:23 -0700966 @Override
967 protected void onDestroy() {
Dave Bort31a6d1c2009-04-13 15:56:49 -0700968 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800969 Log.v(LOGTAG, "BrowserActivity.onDestroy: this=" + this);
970 }
971 super.onDestroy();
Grace Kloba0923d692009-09-23 21:37:25 -0700972
Leon Scroggins8d5fa432009-10-02 15:55:59 -0400973 if (mUploadMessage != null) {
974 mUploadMessage.onReceiveValue(null);
975 mUploadMessage = null;
976 }
977
Grace Kloba0923d692009-09-23 21:37:25 -0700978 if (mTabControl == null) return;
979
Grace Kloba1fc98a32009-10-21 13:23:08 -0700980 // Remove the fake title bar if it is there
981 hideFakeTitleBar();
982
The Android Open Source Project0c908882009-03-03 19:32:16 -0800983 // Remove the current tab and sub window
Grace Kloba22ac16e2009-10-07 18:00:23 -0700984 Tab t = mTabControl.getCurrentTab();
Patrick Scottfb5e77f2009-04-08 19:17:37 -0700985 if (t != null) {
986 dismissSubWindow(t);
987 removeTabFromContentView(t);
988 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800989 // Destroy all the tabs
990 mTabControl.destroy();
991 WebIconDatabase.getInstance().close();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800992
Grace Klobab4da0ad2009-05-14 14:45:40 -0700993 unregisterReceiver(mPackageInstallationReceiver);
Bjorn Bringerta7611812010-03-24 11:12:02 +0000994
995 // Stop watching the default geolocation permissions
996 mSystemAllowGeolocationOrigins.stop();
997 mSystemAllowGeolocationOrigins = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800998 }
999
1000 @Override
1001 public void onConfigurationChanged(Configuration newConfig) {
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04001002 mConfigChanged = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001003 super.onConfigurationChanged(newConfig);
1004
1005 if (mPageInfoDialog != null) {
1006 mPageInfoDialog.dismiss();
1007 showPageInfo(
1008 mPageInfoView,
Leon Scrogginsc7b92f82010-01-11 18:17:31 -05001009 mPageInfoFromShowSSLCertificateOnError);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001010 }
1011 if (mSSLCertificateDialog != null) {
1012 mSSLCertificateDialog.dismiss();
1013 showSSLCertificate(
1014 mSSLCertificateView);
1015 }
1016 if (mSSLCertificateOnErrorDialog != null) {
1017 mSSLCertificateOnErrorDialog.dismiss();
1018 showSSLCertificateOnError(
1019 mSSLCertificateOnErrorView,
1020 mSSLCertificateOnErrorHandler,
1021 mSSLCertificateOnErrorError);
1022 }
1023 if (mHttpAuthenticationDialog != null) {
1024 String title = ((TextView) mHttpAuthenticationDialog
1025 .findViewById(com.android.internal.R.id.alertTitle)).getText()
1026 .toString();
1027 String name = ((TextView) mHttpAuthenticationDialog
1028 .findViewById(R.id.username_edit)).getText().toString();
1029 String password = ((TextView) mHttpAuthenticationDialog
1030 .findViewById(R.id.password_edit)).getText().toString();
1031 int focusId = mHttpAuthenticationDialog.getCurrentFocus()
1032 .getId();
1033 mHttpAuthenticationDialog.dismiss();
1034 showHttpAuthentication(mHttpAuthHandler, null, null, title,
1035 name, password, focusId);
1036 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001037 }
1038
Grace Kloba22ac16e2009-10-07 18:00:23 -07001039 @Override
1040 public void onLowMemory() {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001041 super.onLowMemory();
1042 mTabControl.freeMemory();
1043 }
1044
Cary Clarkff4d92c2010-03-25 11:17:03 -04001045 private void resumeWebViewTimers() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001046 Tab tab = mTabControl.getCurrentTab();
Cary Clarkff4d92c2010-03-25 11:17:03 -04001047 if (tab == null) return; // monkey can trigger this
Grace Kloba22ac16e2009-10-07 18:00:23 -07001048 boolean inLoad = tab.inLoad();
1049 if ((!mActivityInPause && !inLoad) || (mActivityInPause && inLoad)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001050 CookieSyncManager.getInstance().startSync();
Grace Kloba22ac16e2009-10-07 18:00:23 -07001051 WebView w = tab.getWebView();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001052 if (w != null) {
1053 w.resumeTimers();
1054 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001055 }
1056 }
1057
Mike Reed7bfa63b2009-05-28 11:08:32 -04001058 private boolean pauseWebViewTimers() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001059 Tab tab = mTabControl.getCurrentTab();
1060 boolean inLoad = tab.inLoad();
1061 if (mActivityInPause && !inLoad) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001062 CookieSyncManager.getInstance().stopSync();
1063 WebView w = mTabControl.getCurrentWebView();
1064 if (w != null) {
1065 w.pauseTimers();
1066 }
1067 return true;
1068 } else {
1069 return false;
1070 }
1071 }
1072
The Android Open Source Project0c908882009-03-03 19:32:16 -08001073 // Open the icon database and retain all the icons for visited sites.
1074 private void retainIconsOnStartup() {
1075 final WebIconDatabase db = WebIconDatabase.getInstance();
1076 db.open(getDir("icons", 0).getPath());
Leon Scroggins2c0f6112010-03-12 18:09:39 -05001077 Cursor c = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001078 try {
Leon Scroggins2c0f6112010-03-12 18:09:39 -05001079 c = Browser.getAllBookmarks(mResolver);
1080 if (c.moveToFirst()) {
1081 int urlIndex = c.getColumnIndex(Browser.BookmarkColumns.URL);
1082 do {
1083 String url = c.getString(urlIndex);
1084 db.retainIconForPageUrl(url);
1085 } while (c.moveToNext());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001086 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001087 } catch (IllegalStateException e) {
1088 Log.e(LOGTAG, "retainIconsOnStartup", e);
Leon Scroggins2c0f6112010-03-12 18:09:39 -05001089 } finally {
1090 if (c!= null) c.close();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001091 }
1092 }
1093
1094 // Helper method for getting the top window.
1095 WebView getTopWindow() {
1096 return mTabControl.getCurrentTopWebView();
1097 }
1098
Grace Kloba22ac16e2009-10-07 18:00:23 -07001099 TabControl getTabControl() {
1100 return mTabControl;
1101 }
1102
The Android Open Source Project0c908882009-03-03 19:32:16 -08001103 @Override
1104 public boolean onCreateOptionsMenu(Menu menu) {
1105 super.onCreateOptionsMenu(menu);
1106
1107 MenuInflater inflater = getMenuInflater();
1108 inflater.inflate(R.menu.browser, menu);
1109 mMenu = menu;
1110 updateInLoadMenuItems();
1111 return true;
1112 }
1113
1114 /**
1115 * As the menu can be open when loading state changes
1116 * we must manually update the state of the stop/reload menu
1117 * item
1118 */
1119 private void updateInLoadMenuItems() {
1120 if (mMenu == null) {
1121 return;
1122 }
Michael Kolbe0a36662010-06-29 10:37:12 -07001123 MenuItem dest = mMenu.findItem(R.id.stop_reload_menu_id);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001124 MenuItem src = mInLoad ?
1125 mMenu.findItem(R.id.stop_menu_id):
Michael Kolbe0a36662010-06-29 10:37:12 -07001126 mMenu.findItem(R.id.reload_menu_id);
1127 if (src != null) {
1128 dest.setIcon(src.getIcon());
1129 dest.setTitle(src.getTitle());
1130 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001131 }
1132
1133 @Override
1134 public boolean onContextItemSelected(MenuItem item) {
1135 // chording is not an issue with context menus, but we use the same
1136 // options selector, so set mCanChord to true so we can access them.
1137 mCanChord = true;
1138 int id = item.getItemId();
Leon Scroggins96afcb12009-12-10 12:35:56 -05001139 boolean result = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001140 switch (id) {
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001141 // For the context menu from the title bar
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001142 case R.id.title_bar_copy_page_url:
Leon Scroggins96afcb12009-12-10 12:35:56 -05001143 Tab currentTab = mTabControl.getCurrentTab();
1144 if (null == currentTab) {
1145 result = false;
1146 break;
1147 }
1148 WebView mainView = currentTab.getWebView();
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001149 if (null == mainView) {
Leon Scroggins96afcb12009-12-10 12:35:56 -05001150 result = false;
1151 break;
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001152 }
Leon Scroggins96afcb12009-12-10 12:35:56 -05001153 copy(mainView.getUrl());
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001154 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001155 // -- Browser context menu
1156 case R.id.open_context_menu_id:
The Android Open Source Project0c908882009-03-03 19:32:16 -08001157 case R.id.bookmark_context_menu_id:
1158 case R.id.save_link_context_menu_id:
1159 case R.id.share_link_context_menu_id:
1160 case R.id.copy_link_context_menu_id:
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001161 final WebView webView = getTopWindow();
1162 if (null == webView) {
Leon Scroggins96afcb12009-12-10 12:35:56 -05001163 result = false;
1164 break;
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001165 }
1166 final HashMap hrefMap = new HashMap();
1167 hrefMap.put("webview", webView);
1168 final Message msg = mHandler.obtainMessage(
1169 FOCUS_NODE_HREF, id, 0, hrefMap);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001170 webView.requestFocusNodeHref(msg);
1171 break;
1172
1173 default:
1174 // For other context menus
Leon Scroggins96afcb12009-12-10 12:35:56 -05001175 result = onOptionsItemSelected(item);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001176 }
1177 mCanChord = false;
Leon Scroggins96afcb12009-12-10 12:35:56 -05001178 return result;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001179 }
1180
1181 private Bundle createGoogleSearchSourceBundle(String source) {
1182 Bundle bundle = new Bundle();
Bjorn Bringert10d1cca2010-02-10 14:22:12 +00001183 bundle.putString(Search.SOURCE, source);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001184 return bundle;
1185 }
1186
Leon Scroggins8ad29922010-02-16 12:33:55 -05001187 /* package */ void editUrl() {
Leon Scroggins68579392009-09-15 15:31:54 -04001188 if (mOptionsMenuOpen) closeOptionsMenu();
Leon Scroggins5bbe9802009-07-31 13:10:55 -04001189 String url = (getTopWindow() == null) ? null : getTopWindow().getUrl();
Grace Kloba83f47342009-07-20 10:44:31 -07001190 startSearch(mSettings.getHomePage().equals(url) ? null : url, true,
Leon Scroggins8ad29922010-02-16 12:33:55 -05001191 null, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001192 }
1193
Leon Scroggins8ad29922010-02-16 12:33:55 -05001194 /**
1195 * Overriding this to insert a local information bundle
1196 */
The Android Open Source Project0c908882009-03-03 19:32:16 -08001197 @Override
1198 public void startSearch(String initialQuery, boolean selectInitialQuery,
1199 Bundle appSearchData, boolean globalSearch) {
1200 if (appSearchData == null) {
1201 appSearchData = createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_TYPE);
1202 }
1203 super.startSearch(initialQuery, selectInitialQuery, appSearchData, globalSearch);
1204 }
1205
Leon Scroggins1f005d32009-08-10 17:36:42 -04001206 /**
1207 * Switch tabs. Called by the TitleBarSet when sliding the title bar
1208 * results in changing tabs.
Leon Scroggins160a7e72009-08-14 18:28:01 -04001209 * @param index Index of the tab to change to, as defined by
1210 * mTabControl.getTabIndex(Tab t).
1211 * @return boolean True if we successfully switched to a different tab. If
1212 * the indexth tab is null, or if that tab is the same as
1213 * the current one, return false.
Leon Scroggins1f005d32009-08-10 17:36:42 -04001214 */
Leon Scroggins160a7e72009-08-14 18:28:01 -04001215 /* package */ boolean switchToTab(int index) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001216 Tab tab = mTabControl.getTab(index);
1217 Tab currentTab = mTabControl.getCurrentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04001218 if (tab == null || tab == currentTab) {
Leon Scroggins160a7e72009-08-14 18:28:01 -04001219 return false;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001220 }
1221 if (currentTab != null) {
1222 // currentTab may be null if it was just removed. In that case,
1223 // we do not need to remove it
1224 removeTabFromContentView(currentTab);
1225 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001226 mTabControl.setCurrentTab(tab);
1227 attachTabToContentView(tab);
Grace Klobaeb6eef42009-09-15 17:56:32 -07001228 resetTitleIconAndProgress();
1229 updateLockIconToLatest();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001230 return true;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001231 }
1232
Grace Kloba22ac16e2009-10-07 18:00:23 -07001233 /* package */ Tab openTabToHomePage() {
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001234 return openTabAndShow(mSettings.getHomePage(), false, null);
1235 }
1236
Leon Scroggins1f005d32009-08-10 17:36:42 -04001237 /* package */ void closeCurrentWindow() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001238 final Tab current = mTabControl.getCurrentTab();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001239 if (mTabControl.getTabCount() == 1) {
Leon Scroggins30444232009-09-04 18:36:20 -04001240 // This is the last tab. Open a new one, with the home
1241 // page and close the current one.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001242 openTabToHomePage();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001243 closeTab(current);
Leon Scroggins160a7e72009-08-14 18:28:01 -04001244 return;
1245 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07001246 final Tab parent = current.getParentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04001247 int indexToShow = -1;
1248 if (parent != null) {
1249 indexToShow = mTabControl.getTabIndex(parent);
1250 } else {
Leon Scroggins160a7e72009-08-14 18:28:01 -04001251 final int currentIndex = mTabControl.getCurrentIndex();
1252 // Try to move to the tab to the right
1253 indexToShow = currentIndex + 1;
1254 if (indexToShow > mTabControl.getTabCount() - 1) {
1255 // Try to move to the tab to the left
1256 indexToShow = currentIndex - 1;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001257 }
1258 }
Leon Scroggins160a7e72009-08-14 18:28:01 -04001259 if (switchToTab(indexToShow)) {
1260 // Close window
1261 closeTab(current);
1262 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001263 }
1264
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001265 private ActiveTabsPage mActiveTabsPage;
1266
1267 /**
1268 * Remove the active tabs page.
1269 * @param needToAttach If true, the active tabs page did not attach a tab
1270 * to the content view, so we need to do that here.
1271 */
1272 /* package */ void removeActiveTabPage(boolean needToAttach) {
1273 mContentView.removeView(mActiveTabsPage);
Leon Scrogginsd746a942010-05-19 13:21:44 -04001274 mTitleBar.setVisibility(View.VISIBLE);
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001275 mActiveTabsPage = null;
1276 mMenuState = R.id.MAIN_MENU;
1277 if (needToAttach) {
1278 attachTabToContentView(mTabControl.getCurrentTab());
1279 }
1280 getTopWindow().requestFocus();
1281 }
1282
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04001283 @Override
1284 public ActionMode onStartActionMode(ActionMode.Callback callback) {
1285 ActionMode mode = super.onStartActionMode(callback);
1286 if (callback instanceof FindActionModeCallback
1287 || callback instanceof SelectActionModeCallback) {
1288 // For find and select, hide extra title bars. They will
1289 // be replaced in onEndActionMode.
1290 Tab tab = mTabControl.getCurrentTab();
1291 if (tab.getSubWebView() == null) {
1292 // If the find or select is being performed on the main webview,
1293 // remove the embedded title bar.
1294 WebView mainView = tab.getWebView();
1295 if (mainView != null) {
1296 mainView.setEmbeddedTitleBar(null);
1297 }
Cary Clark01cfcdd2010-06-04 16:36:45 -04001298 }
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04001299 hideFakeTitleBar();
1300 mActionMode = mode;
1301 } else {
1302 // Do not store other ActionModes, since we are unable to determine
1303 // when they finish.
1304 mActionMode = null;
Cary Clark01cfcdd2010-06-04 16:36:45 -04001305 }
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04001306 return mode;
Cary Clark01cfcdd2010-06-04 16:36:45 -04001307 }
1308
The Android Open Source Project0c908882009-03-03 19:32:16 -08001309 @Override
1310 public boolean onOptionsItemSelected(MenuItem item) {
Michael Kolbed217742010-08-10 17:52:34 -07001311 // check the action bar button before mCanChord check, as the prepare call
1312 // doesn't come for action bar buttons
1313 if (item.getItemId() == R.id.newtab) {
1314 bookmarksOrHistoryPicker(false, true);
1315 return true;
1316 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001317 if (!mCanChord) {
1318 // The user has already fired a shortcut with this hold down of the
1319 // menu key.
1320 return false;
1321 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001322 if (null == getTopWindow()) {
Leon Scroggins0d7ae0e2009-06-05 11:04:45 -04001323 return false;
1324 }
Grace Kloba6ee9c492009-07-13 10:04:34 -07001325 if (mMenuIsDown) {
1326 // The shortcut action consumes the MENU. Even if it is still down,
1327 // it won't trigger the next shortcut action. In the case of the
1328 // shortcut action triggering a new activity, like Bookmarks, we
1329 // won't get onKeyUp for MENU. So it is important to reset it here.
1330 mMenuIsDown = false;
1331 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001332 switch (item.getItemId()) {
1333 // -- Main menu
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001334 case R.id.new_tab_menu_id:
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001335 openTabToHomePage();
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001336 break;
1337
Michael Kolbae62fd42010-08-18 16:33:28 -07001338 case R.id.incognito_menu_id:
1339 openIncognitoTab();
1340 break;
1341
Leon Scroggins64b80f32009-08-07 12:03:34 -04001342 case R.id.goto_menu_id:
Leon Scroggins8ad29922010-02-16 12:33:55 -05001343 editUrl();
Leon Scrogginsb3a5bed2009-09-28 11:21:56 -04001344 break;
1345
1346 case R.id.bookmarks_menu_id:
Michael Kolb68792c82010-08-09 16:39:18 -07001347 bookmarksOrHistoryPicker(false, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001348 break;
1349
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001350 case R.id.active_tabs_menu_id:
1351 mActiveTabsPage = new ActiveTabsPage(this, mTabControl);
1352 removeTabFromContentView(mTabControl.getCurrentTab());
Leon Scrogginsd746a942010-05-19 13:21:44 -04001353 mTitleBar.setVisibility(View.GONE);
Leon Scroggins43de6162009-09-14 19:59:58 -04001354 hideFakeTitleBar();
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001355 mContentView.addView(mActiveTabsPage, COVER_SCREEN_PARAMS);
1356 mActiveTabsPage.requestFocus();
1357 mMenuState = EMPTY_MENU;
1358 break;
1359
Leon Scroggins1f005d32009-08-10 17:36:42 -04001360 case R.id.add_bookmark_menu_id:
Leon Scroggins571b3762010-05-26 10:25:01 -04001361 bookmarkCurrentPage();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001362 break;
1363
1364 case R.id.stop_reload_menu_id:
1365 if (mInLoad) {
1366 stopLoading();
1367 } else {
1368 getTopWindow().reload();
1369 }
1370 break;
1371
1372 case R.id.back_menu_id:
1373 getTopWindow().goBack();
1374 break;
1375
1376 case R.id.forward_menu_id:
1377 getTopWindow().goForward();
1378 break;
1379
1380 case R.id.close_menu_id:
1381 // Close the subwindow if it exists.
1382 if (mTabControl.getCurrentSubWindow() != null) {
1383 dismissSubWindow(mTabControl.getCurrentTab());
1384 break;
1385 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001386 closeCurrentWindow();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001387 break;
1388
1389 case R.id.homepage_menu_id:
Grace Kloba22ac16e2009-10-07 18:00:23 -07001390 Tab current = mTabControl.getCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001391 if (current != null) {
1392 dismissSubWindow(current);
Leon Scroggins92472e82010-02-17 16:32:28 -05001393 loadUrl(current.getWebView(), mSettings.getHomePage());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001394 }
1395 break;
1396
1397 case R.id.preferences_menu_id:
1398 Intent intent = new Intent(this,
1399 BrowserPreferencesPage.class);
Leon Scrogginsd5304942009-12-10 16:11:39 -05001400 intent.putExtra(BrowserPreferencesPage.CURRENT_PAGE,
1401 getTopWindow().getUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001402 startActivityForResult(intent, PREFERENCES_PAGE);
1403 break;
1404
1405 case R.id.find_menu_id:
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04001406 showFindDialog(null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001407 break;
1408
Elliott Slaughter0ced08c2010-06-30 11:40:42 -07001409 case R.id.save_webarchive_menu_id:
1410 if (LOGD_ENABLED) {
1411 Log.d(LOGTAG, "Save as Web Archive");
1412 }
1413 String directory = getExternalFilesDir(null).getAbsolutePath() + File.separator;
1414 getTopWindow().saveWebArchive(directory, true, new ValueCallback<String>() {
1415 @Override
1416 public void onReceiveValue(String value) {
1417 if (value != null) {
1418 Toast.makeText(BrowserActivity.this, R.string.webarchive_saved, Toast.LENGTH_SHORT).show();
1419 } else {
1420 Toast.makeText(BrowserActivity.this, R.string.webarchive_failed, Toast.LENGTH_SHORT).show();
1421 }
1422 }
1423 });
1424 break;
1425
The Android Open Source Project0c908882009-03-03 19:32:16 -08001426 case R.id.page_info_menu_id:
1427 showPageInfo(mTabControl.getCurrentTab(), false);
1428 break;
1429
1430 case R.id.classic_history_menu_id:
Michael Kolb68792c82010-08-09 16:39:18 -07001431 bookmarksOrHistoryPicker(true, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001432 break;
1433
Leon Scroggins96afcb12009-12-10 12:35:56 -05001434 case R.id.title_bar_share_page_url:
The Android Open Source Project0c908882009-03-03 19:32:16 -08001435 case R.id.share_page_menu_id:
Leon Scroggins96afcb12009-12-10 12:35:56 -05001436 Tab currentTab = mTabControl.getCurrentTab();
1437 if (null == currentTab) {
1438 mCanChord = false;
1439 return false;
1440 }
1441 currentTab.populatePickerData();
1442 sharePage(this, currentTab.getTitle(),
1443 currentTab.getUrl(), currentTab.getFavicon(),
Ben Murdoch87cc65d2010-06-29 20:34:10 +01001444 createScreenshot(currentTab.getWebView(), getDesiredThumbnailWidth(this),
1445 getDesiredThumbnailHeight(this)));
The Android Open Source Project0c908882009-03-03 19:32:16 -08001446 break;
1447
1448 case R.id.dump_nav_menu_id:
1449 getTopWindow().debugDump();
1450 break;
1451
Andrei Popescu7a8b88b2010-02-02 00:30:38 +00001452 case R.id.dump_counters_menu_id:
1453 getTopWindow().dumpV8Counters();
1454 break;
1455
The Android Open Source Project0c908882009-03-03 19:32:16 -08001456 case R.id.zoom_in_menu_id:
1457 getTopWindow().zoomIn();
1458 break;
1459
1460 case R.id.zoom_out_menu_id:
1461 getTopWindow().zoomOut();
1462 break;
1463
1464 case R.id.view_downloads_menu_id:
1465 viewDownloads(null);
1466 break;
1467
The Android Open Source Project0c908882009-03-03 19:32:16 -08001468 case R.id.window_one_menu_id:
1469 case R.id.window_two_menu_id:
1470 case R.id.window_three_menu_id:
1471 case R.id.window_four_menu_id:
1472 case R.id.window_five_menu_id:
1473 case R.id.window_six_menu_id:
1474 case R.id.window_seven_menu_id:
1475 case R.id.window_eight_menu_id:
1476 {
1477 int menuid = item.getItemId();
1478 for (int id = 0; id < WINDOW_SHORTCUT_ID_ARRAY.length; id++) {
1479 if (WINDOW_SHORTCUT_ID_ARRAY[id] == menuid) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001480 Tab desiredTab = mTabControl.getTab(id);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001481 if (desiredTab != null &&
1482 desiredTab != mTabControl.getCurrentTab()) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001483 switchToTab(id);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001484 }
1485 break;
1486 }
1487 }
1488 }
1489 break;
1490
1491 default:
1492 if (!super.onOptionsItemSelected(item)) {
1493 return false;
1494 }
1495 // Otherwise fall through.
1496 }
1497 mCanChord = false;
1498 return true;
1499 }
1500
Leon Scroggins571b3762010-05-26 10:25:01 -04001501 /* package */ void bookmarkCurrentPage() {
1502 Intent i = new Intent(BrowserActivity.this,
1503 AddBookmarkPage.class);
1504 WebView w = getTopWindow();
1505 i.putExtra("url", w.getUrl());
1506 i.putExtra("title", w.getTitle());
1507 i.putExtra("touch_icon_url", w.getTouchIconUrl());
Ben Murdoch87cc65d2010-06-29 20:34:10 +01001508 i.putExtra("thumbnail", createScreenshot(w, getDesiredThumbnailWidth(this),
1509 getDesiredThumbnailHeight(this)));
Ben Murdocheecb4e62010-07-06 16:30:38 +01001510 i.putExtra("url_editable", false);
Leon Scroggins571b3762010-05-26 10:25:01 -04001511 startActivity(i);
1512 }
1513
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04001514 /*
1515 * True if a custom ActionMode (i.e. find or select) is in use.
1516 */
1517 private boolean isInCustomActionMode() {
1518 return mActionMode != null;
Cary Clark01cfcdd2010-06-04 16:36:45 -04001519 }
1520
1521 /*
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04001522 * End the current ActionMode. Only works for find and select.
Cary Clark01cfcdd2010-06-04 16:36:45 -04001523 */
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04001524 void endActionMode() {
1525 if (mActionMode != null) {
1526 mActionMode.finish();
1527 }
1528 }
1529
1530 /*
1531 * Called by find and select when they are finished. Replace title bars
1532 * as necessary.
1533 */
1534 public void onEndActionMode() {
1535 if (!isInCustomActionMode()) return;
Michael Kolba2b2ba82010-08-04 17:54:03 -07001536 // If the Find was being performed in the main WebView, replace the
1537 // embedded title bar.
1538 Tab currentTab = mTabControl.getCurrentTab();
1539 if (currentTab.getSubWebView() == null) {
1540 WebView mainView = currentTab.getWebView();
1541 if (mainView != null) {
1542 mainView.setEmbeddedTitleBar(mTitleBar);
Leon Scroggins79e36d92010-04-29 16:01:46 +01001543 }
1544 }
Leon Scroggins79e36d92010-04-29 16:01:46 +01001545 if (mInLoad) {
1546 // The title bar was hidden, because otherwise it would cover up the
Michael Kolba2b2ba82010-08-04 17:54:03 -07001547 // find or select dialog. Now that the dialog has been removed,
Cary Clark01cfcdd2010-06-04 16:36:45 -04001548 // show the fake title bar once again.
Leon Scroggins79e36d92010-04-29 16:01:46 +01001549 showFakeTitleBar();
1550 }
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04001551 mActionMode = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001552 }
1553
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04001554 private FindActionModeCallback mFindCallback;
1555 private SelectActionModeCallback mSelectCallback;
1556
1557 // For select and find, we keep track of the ActionMode so that
1558 // finish() can be called as desired.
1559 private ActionMode mActionMode;
1560
1561 /*
1562 * Open the find ActionMode.
1563 * @param text If non null, will be placed in find to be searched for.
1564 */
1565 public void showFindDialog(String text) {
1566 if (null == mFindCallback) {
1567 mFindCallback = new FindActionModeCallback(this);
Cary Clark01cfcdd2010-06-04 16:36:45 -04001568 }
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04001569 WebView webView = getTopWindow();
1570 webView.setFindIsUp(true);
1571 mFindCallback.setWebView(webView);
1572 startActionMode(mFindCallback);
1573 if (text != null) mFindCallback.setText(text);
Cary Clark01cfcdd2010-06-04 16:36:45 -04001574 }
1575
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04001576 /*
1577 * Show the select ActionMode.
1578 */
Cary Clark01cfcdd2010-06-04 16:36:45 -04001579 public void showSelectDialog() {
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04001580 if (null == mSelectCallback) {
1581 mSelectCallback = new SelectActionModeCallback(this);
Cary Clark01cfcdd2010-06-04 16:36:45 -04001582 }
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04001583 WebView webView = getTopWindow();
1584 webView.setUpSelect();
1585 mSelectCallback.setWebView(webView);
1586 startActionMode(mSelectCallback);
Cary Clark01cfcdd2010-06-04 16:36:45 -04001587 }
1588
Grace Kloba22ac16e2009-10-07 18:00:23 -07001589 @Override
1590 public boolean onPrepareOptionsMenu(Menu menu) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001591 // This happens when the user begins to hold down the menu key, so
1592 // allow them to chord to get a shortcut.
1593 mCanChord = true;
1594 // Note: setVisible will decide whether an item is visible; while
1595 // setEnabled() will decide whether an item is enabled, which also means
1596 // whether the matching shortcut key will function.
1597 super.onPrepareOptionsMenu(menu);
1598 switch (mMenuState) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001599 case EMPTY_MENU:
1600 if (mCurrentMenuState != mMenuState) {
1601 menu.setGroupVisible(R.id.MAIN_MENU, false);
1602 menu.setGroupEnabled(R.id.MAIN_MENU, false);
1603 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001604 }
1605 break;
1606 default:
1607 if (mCurrentMenuState != mMenuState) {
1608 menu.setGroupVisible(R.id.MAIN_MENU, true);
1609 menu.setGroupEnabled(R.id.MAIN_MENU, true);
1610 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001611 }
1612 final WebView w = getTopWindow();
1613 boolean canGoBack = false;
1614 boolean canGoForward = false;
1615 boolean isHome = false;
1616 if (w != null) {
1617 canGoBack = w.canGoBack();
1618 canGoForward = w.canGoForward();
1619 isHome = mSettings.getHomePage().equals(w.getUrl());
1620 }
1621 final MenuItem back = menu.findItem(R.id.back_menu_id);
1622 back.setEnabled(canGoBack);
1623
1624 final MenuItem home = menu.findItem(R.id.homepage_menu_id);
1625 home.setEnabled(!isHome);
1626
Michael Kolbe0a36662010-06-29 10:37:12 -07001627 final MenuItem forward = menu.findItem(R.id.forward_menu_id);
1628 forward.setEnabled(canGoForward);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001629
Michael Kolbed217742010-08-10 17:52:34 -07001630 if (!mXLargeScreenSize) {
1631 final MenuItem newtab = menu.findItem(R.id.new_tab_menu_id);
1632 newtab.setEnabled(mTabControl.canCreateNewTab());
1633 }
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001634
The Android Open Source Project0c908882009-03-03 19:32:16 -08001635 // decide whether to show the share link option
1636 PackageManager pm = getPackageManager();
1637 Intent send = new Intent(Intent.ACTION_SEND);
1638 send.setType("text/plain");
1639 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1640 menu.findItem(R.id.share_page_menu_id).setVisible(ri != null);
1641
The Android Open Source Project0c908882009-03-03 19:32:16 -08001642 boolean isNavDump = mSettings.isNavDump();
1643 final MenuItem nav = menu.findItem(R.id.dump_nav_menu_id);
1644 nav.setVisible(isNavDump);
1645 nav.setEnabled(isNavDump);
Andrei Popescu7a8b88b2010-02-02 00:30:38 +00001646
1647 boolean showDebugSettings = mSettings.showDebugSettings();
1648 final MenuItem counter = menu.findItem(R.id.dump_counters_menu_id);
1649 counter.setVisible(showDebugSettings);
1650 counter.setEnabled(showDebugSettings);
1651
The Android Open Source Project0c908882009-03-03 19:32:16 -08001652 break;
1653 }
1654 mCurrentMenuState = mMenuState;
1655 return true;
1656 }
1657
1658 @Override
1659 public void onCreateContextMenu(ContextMenu menu, View v,
1660 ContextMenuInfo menuInfo) {
Leon Scroggins571b3762010-05-26 10:25:01 -04001661 if (v instanceof TitleBarBase) {
Leon Scroggins4e9f89b2010-02-22 16:54:14 -05001662 return;
1663 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001664 WebView webview = (WebView) v;
1665 WebView.HitTestResult result = webview.getHitTestResult();
1666 if (result == null) {
1667 return;
1668 }
1669
1670 int type = result.getType();
1671 if (type == WebView.HitTestResult.UNKNOWN_TYPE) {
1672 Log.w(LOGTAG,
1673 "We should not show context menu when nothing is touched");
1674 return;
1675 }
1676 if (type == WebView.HitTestResult.EDIT_TEXT_TYPE) {
1677 // let TextView handles context menu
1678 return;
1679 }
1680
1681 // Note, http://b/issue?id=1106666 is requesting that
1682 // an inflated menu can be used again. This is not available
1683 // yet, so inflate each time (yuk!)
1684 MenuInflater inflater = getMenuInflater();
1685 inflater.inflate(R.menu.browsercontext, menu);
1686
1687 // Show the correct menu group
Leon Scroggins III9e997c72010-05-26 13:25:16 -04001688 final String extra = result.getExtra();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001689 menu.setGroupVisible(R.id.PHONE_MENU,
1690 type == WebView.HitTestResult.PHONE_TYPE);
1691 menu.setGroupVisible(R.id.EMAIL_MENU,
1692 type == WebView.HitTestResult.EMAIL_TYPE);
1693 menu.setGroupVisible(R.id.GEO_MENU,
1694 type == WebView.HitTestResult.GEO_TYPE);
1695 menu.setGroupVisible(R.id.IMAGE_MENU,
1696 type == WebView.HitTestResult.IMAGE_TYPE
1697 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1698 menu.setGroupVisible(R.id.ANCHOR_MENU,
1699 type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1700 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1701
1702 // Setup custom handling depending on the type
1703 switch (type) {
1704 case WebView.HitTestResult.PHONE_TYPE:
1705 menu.setHeaderTitle(Uri.decode(extra));
1706 menu.findItem(R.id.dial_context_menu_id).setIntent(
1707 new Intent(Intent.ACTION_VIEW, Uri
1708 .parse(WebView.SCHEME_TEL + extra)));
1709 Intent addIntent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
1710 addIntent.putExtra(Insert.PHONE, Uri.decode(extra));
Cary Clark5e335a32009-09-22 14:53:11 -04001711 addIntent.setType(ContactsContract.Contacts.CONTENT_ITEM_TYPE);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001712 menu.findItem(R.id.add_contact_context_menu_id).setIntent(
1713 addIntent);
1714 menu.findItem(R.id.copy_phone_context_menu_id).setOnMenuItemClickListener(
1715 new Copy(extra));
1716 break;
1717
1718 case WebView.HitTestResult.EMAIL_TYPE:
1719 menu.setHeaderTitle(extra);
1720 menu.findItem(R.id.email_context_menu_id).setIntent(
1721 new Intent(Intent.ACTION_VIEW, Uri
1722 .parse(WebView.SCHEME_MAILTO + extra)));
1723 menu.findItem(R.id.copy_mail_context_menu_id).setOnMenuItemClickListener(
1724 new Copy(extra));
1725 break;
1726
1727 case WebView.HitTestResult.GEO_TYPE:
1728 menu.setHeaderTitle(extra);
1729 menu.findItem(R.id.map_context_menu_id).setIntent(
1730 new Intent(Intent.ACTION_VIEW, Uri
1731 .parse(WebView.SCHEME_GEO
1732 + URLEncoder.encode(extra))));
1733 menu.findItem(R.id.copy_geo_context_menu_id).setOnMenuItemClickListener(
1734 new Copy(extra));
1735 break;
1736
1737 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1738 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
1739 TextView titleView = (TextView) LayoutInflater.from(this)
1740 .inflate(android.R.layout.browser_link_context_header,
1741 null);
1742 titleView.setText(extra);
1743 menu.setHeaderView(titleView);
1744 // decide whether to show the open link in new tab option
Leon Scroggins III9e997c72010-05-26 13:25:16 -04001745 boolean showNewTab = mTabControl.canCreateNewTab();
1746 MenuItem newTabItem
1747 = menu.findItem(R.id.open_newtab_context_menu_id);
1748 newTabItem.setVisible(showNewTab);
1749 if (showNewTab) {
1750 newTabItem.setOnMenuItemClickListener(
1751 new MenuItem.OnMenuItemClickListener() {
1752 public boolean onMenuItemClick(MenuItem item) {
1753 final Tab parent = mTabControl.getCurrentTab();
Michael Kolb68792c82010-08-09 16:39:18 -07001754 final Tab newTab = openTab(extra, false);
Leon Scroggins III9e997c72010-05-26 13:25:16 -04001755 if (newTab != parent) {
1756 parent.addChildTab(newTab);
1757 }
1758 return true;
1759 }
1760 });
1761 }
Ben Murdochde353622009-10-12 10:29:00 +01001762 menu.findItem(R.id.bookmark_context_menu_id).setVisible(
1763 Bookmarks.urlHasAcceptableScheme(extra));
The Android Open Source Project0c908882009-03-03 19:32:16 -08001764 PackageManager pm = getPackageManager();
1765 Intent send = new Intent(Intent.ACTION_SEND);
1766 send.setType("text/plain");
1767 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1768 menu.findItem(R.id.share_link_context_menu_id).setVisible(ri != null);
1769 if (type == WebView.HitTestResult.SRC_ANCHOR_TYPE) {
1770 break;
1771 }
1772 // otherwise fall through to handle image part
1773 case WebView.HitTestResult.IMAGE_TYPE:
1774 if (type == WebView.HitTestResult.IMAGE_TYPE) {
1775 menu.setHeaderTitle(extra);
1776 }
1777 menu.findItem(R.id.view_image_context_menu_id).setIntent(
1778 new Intent(Intent.ACTION_VIEW, Uri.parse(extra)));
1779 menu.findItem(R.id.download_context_menu_id).
1780 setOnMenuItemClickListener(new Download(extra));
Ben Murdoch4f75ba22009-10-27 11:48:28 +00001781 menu.findItem(R.id.set_wallpaper_context_menu_id).
1782 setOnMenuItemClickListener(new SetAsWallpaper(extra));
The Android Open Source Project0c908882009-03-03 19:32:16 -08001783 break;
1784
1785 default:
1786 Log.w(LOGTAG, "We should not get here.");
1787 break;
1788 }
Leon Scrogginsb2b19f52009-10-09 16:10:00 -04001789 hideFakeTitleBar();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001790 }
1791
The Android Open Source Project0c908882009-03-03 19:32:16 -08001792 // Attach the given tab to the content view.
Grace Klobac928c302009-09-17 11:51:21 -07001793 // this should only be called for the current tab.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001794 private void attachTabToContentView(Tab t) {
Steve Block2bc69912009-07-30 14:45:13 +01001795 // Attach the container that contains the main WebView and any other UI
1796 // associated with the tab.
Patrick Scottd0119532009-09-17 08:00:31 -04001797 t.attachTabToContentView(mContentView);
Ben Murdochbff2d602009-07-01 20:19:05 +01001798
1799 if (mShouldShowErrorConsole) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001800 ErrorConsoleView errorConsole = t.getErrorConsole(true);
Ben Murdochbff2d602009-07-01 20:19:05 +01001801 if (errorConsole.numberOfErrors() == 0) {
1802 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
1803 } else {
1804 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
1805 }
1806
1807 mErrorConsoleContainer.addView(errorConsole,
Romain Guy15b8ec62010-01-08 15:06:43 -08001808 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
Ben Murdochbff2d602009-07-01 20:19:05 +01001809 ViewGroup.LayoutParams.WRAP_CONTENT));
1810 }
1811
Michael Kolba2b2ba82010-08-04 17:54:03 -07001812 WebView view = t.getWebView();
1813 view.setEmbeddedTitleBar(mTitleBar);
Leon Scroggins58d56c62010-01-28 15:12:40 -05001814 if (t.isInVoiceSearchMode()) {
1815 showVoiceTitleBar(t.getVoiceDisplayTitle());
1816 } else {
1817 revertVoiceTitleBar();
1818 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001819 // Request focus on the top window.
1820 t.getTopWindow().requestFocus();
Michael Kolba2b2ba82010-08-04 17:54:03 -07001821 if (mTabControl.getTabChangeListener() != null) {
1822 mTabControl.getTabChangeListener().onCurrentTab(t);
1823 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001824 }
1825
1826 // Attach a sub window to the main WebView of the given tab.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001827 void attachSubWindow(Tab t) {
Patrick Scottd0119532009-09-17 08:00:31 -04001828 t.attachSubWindow(mContentView);
1829 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001830 }
1831
1832 // Remove the given tab from the content view.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001833 private void removeTabFromContentView(Tab t) {
Steve Block2bc69912009-07-30 14:45:13 +01001834 // Remove the container that contains the main WebView.
Patrick Scottd0119532009-09-17 08:00:31 -04001835 t.removeTabFromContentView(mContentView);
Ben Murdochbff2d602009-07-01 20:19:05 +01001836
Grace Kloba22ac16e2009-10-07 18:00:23 -07001837 ErrorConsoleView errorConsole = t.getErrorConsole(false);
1838 if (errorConsole != null) {
1839 mErrorConsoleContainer.removeView(errorConsole);
Ben Murdochbff2d602009-07-01 20:19:05 +01001840 }
1841
Michael Kolba2b2ba82010-08-04 17:54:03 -07001842 WebView view = t.getWebView();
1843 if (view != null) {
1844 view.setEmbeddedTitleBar(null);
Leon Scrogginsbb85b902009-09-14 19:27:20 -04001845 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001846 }
1847
1848 // Remove the sub window if it exists. Also called by TabControl when the
1849 // user clicks the 'X' to dismiss a sub window.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001850 /* package */ void dismissSubWindow(Tab t) {
Patrick Scottd0119532009-09-17 08:00:31 -04001851 t.removeSubWindow(mContentView);
Grace Kloba22ac16e2009-10-07 18:00:23 -07001852 // dismiss the subwindow. This will destroy the WebView.
1853 t.dismissSubWindow();
Patrick Scottd0119532009-09-17 08:00:31 -04001854 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001855 }
1856
Leon Scroggins1f005d32009-08-10 17:36:42 -04001857 // A wrapper function of {@link #openTabAndShow(UrlData, boolean, String)}
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07001858 // that accepts url as string.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001859 private Tab openTabAndShow(String url, boolean closeOnExit, String appId) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001860 return openTabAndShow(new UrlData(url), closeOnExit, appId);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001861 }
1862
1863 // This method does a ton of stuff. It will attempt to create a new tab
1864 // if we haven't reached MAX_TABS. Otherwise it uses the current tab. If
Leon Scroggins1f005d32009-08-10 17:36:42 -04001865 // url isn't null, it will load the given url.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001866 /* package */Tab openTabAndShow(UrlData urlData, boolean closeOnExit,
1867 String appId) {
1868 final Tab currentTab = mTabControl.getCurrentTab();
1869 if (mTabControl.canCreateNewTab()) {
1870 final Tab tab = mTabControl.createNewTab(closeOnExit, appId,
Elliott Slaughterf0f03952010-07-14 18:10:36 -07001871 urlData.mUrl, false);
Leon Scroggins1f005d32009-08-10 17:36:42 -04001872 WebView webview = tab.getWebView();
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001873 // If the last tab was removed from the active tabs page, currentTab
1874 // will be null.
1875 if (currentTab != null) {
1876 removeTabFromContentView(currentTab);
1877 }
Patrick Scott8bbd69f2009-08-14 13:35:53 -04001878 // We must set the new tab as the current tab to reflect the old
1879 // animation behavior.
1880 mTabControl.setCurrentTab(tab);
Grace Klobaeb6eef42009-09-15 17:56:32 -07001881 attachTabToContentView(tab);
Leon Scroggins160a7e72009-08-14 18:28:01 -04001882 if (!urlData.isEmpty()) {
Patrick Scott9d53da02010-02-19 10:19:01 -05001883 loadUrlDataIn(tab, urlData);
Leon Scroggins1f005d32009-08-10 17:36:42 -04001884 }
1885 return tab;
1886 } else {
1887 // Get rid of the subwindow if it exists
1888 dismissSubWindow(currentTab);
1889 if (!urlData.isEmpty()) {
1890 // Load the given url.
Patrick Scott9d53da02010-02-19 10:19:01 -05001891 loadUrlDataIn(currentTab, urlData);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001892 }
Leon Scroggins58d56c62010-01-28 15:12:40 -05001893 return currentTab;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001894 }
1895 }
1896
Michael Kolb68792c82010-08-09 16:39:18 -07001897 private Tab openTab(String url, boolean forceForeground) {
1898 if (mSettings.openInBackground() && !forceForeground) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001899 Tab t = mTabControl.createNewTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001900 if (t != null) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001901 WebView view = t.getWebView();
Leon Scroggins92472e82010-02-17 16:32:28 -05001902 loadUrl(view, url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001903 }
Grace Klobac9181842009-04-14 08:53:22 -07001904 return t;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001905 } else {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001906 return openTabAndShow(url, false, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001907 }
1908 }
1909
Elliott Slaughterf0f03952010-07-14 18:10:36 -07001910 /* package */ Tab openIncognitoTab() {
1911 if (mTabControl.canCreateNewTab()) {
1912 Tab currentTab = mTabControl.getCurrentTab();
1913 Tab tab = mTabControl.createNewTab(false, null, null, true);
1914 if (currentTab != null) {
1915 removeTabFromContentView(currentTab);
1916 }
1917 mTabControl.setCurrentTab(tab);
1918 attachTabToContentView(tab);
1919 return tab;
1920 }
1921 return null;
1922 }
1923
The Android Open Source Project0c908882009-03-03 19:32:16 -08001924 private class Copy implements OnMenuItemClickListener {
1925 private CharSequence mText;
1926
1927 public boolean onMenuItemClick(MenuItem item) {
1928 copy(mText);
1929 return true;
1930 }
1931
1932 public Copy(CharSequence toCopy) {
1933 mText = toCopy;
1934 }
1935 }
1936
1937 private class Download implements OnMenuItemClickListener {
1938 private String mText;
1939
1940 public boolean onMenuItemClick(MenuItem item) {
1941 onDownloadStartNoStream(mText, null, null, null, -1);
1942 return true;
1943 }
1944
1945 public Download(String toDownload) {
1946 mText = toDownload;
1947 }
1948 }
1949
Ben Murdoch4f75ba22009-10-27 11:48:28 +00001950 private class SetAsWallpaper extends Thread implements
1951 OnMenuItemClickListener, DialogInterface.OnCancelListener {
1952 private URL mUrl;
1953 private ProgressDialog mWallpaperProgress;
1954 private boolean mCanceled = false;
1955
1956 public SetAsWallpaper(String url) {
1957 try {
1958 mUrl = new URL(url);
1959 } catch (MalformedURLException e) {
1960 mUrl = null;
1961 }
1962 }
1963
1964 public void onCancel(DialogInterface dialog) {
1965 mCanceled = true;
1966 }
1967
1968 public boolean onMenuItemClick(MenuItem item) {
1969 if (mUrl != null) {
1970 // The user may have tried to set a image with a large file size as their
1971 // background so it may take a few moments to perform the operation. Display
1972 // a progress spinner while it is working.
1973 mWallpaperProgress = new ProgressDialog(BrowserActivity.this);
1974 mWallpaperProgress.setIndeterminate(true);
1975 mWallpaperProgress.setMessage(getText(R.string.progress_dialog_setting_wallpaper));
1976 mWallpaperProgress.setCancelable(true);
1977 mWallpaperProgress.setOnCancelListener(this);
1978 mWallpaperProgress.show();
1979 start();
1980 }
1981 return true;
1982 }
1983
Michael Kolbe0a36662010-06-29 10:37:12 -07001984 @Override
Ben Murdoch4f75ba22009-10-27 11:48:28 +00001985 public void run() {
1986 Drawable oldWallpaper = BrowserActivity.this.getWallpaper();
1987 try {
1988 // TODO: This will cause the resource to be downloaded again, when we
1989 // should in most cases be able to grab it from the cache. To fix this
1990 // we should query WebCore to see if we can access a cached version and
1991 // instead open an input stream on that. This pattern could also be used
1992 // in the download manager where the same problem exists.
1993 InputStream inputstream = mUrl.openStream();
1994 if (inputstream != null) {
1995 setWallpaper(inputstream);
1996 }
1997 } catch (IOException e) {
1998 Log.e(LOGTAG, "Unable to set new wallpaper");
1999 // Act as though the user canceled the operation so we try to
2000 // restore the old wallpaper.
2001 mCanceled = true;
2002 }
2003
2004 if (mCanceled) {
2005 // Restore the old wallpaper if the user cancelled whilst we were setting
2006 // the new wallpaper.
2007 int width = oldWallpaper.getIntrinsicWidth();
2008 int height = oldWallpaper.getIntrinsicHeight();
2009 Bitmap bm = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
2010 Canvas canvas = new Canvas(bm);
2011 oldWallpaper.setBounds(0, 0, width, height);
2012 oldWallpaper.draw(canvas);
2013 try {
2014 setWallpaper(bm);
2015 } catch (IOException e) {
2016 Log.e(LOGTAG, "Unable to restore old wallpaper.");
2017 }
2018 mCanceled = false;
2019 }
2020
2021 if (mWallpaperProgress.isShowing()) {
2022 mWallpaperProgress.dismiss();
2023 }
2024 }
2025 }
2026
The Android Open Source Project0c908882009-03-03 19:32:16 -08002027 private void copy(CharSequence text) {
Dianne Hackborn80f32622010-08-05 14:17:53 -07002028 ClipboardManager cm = (ClipboardManager)getSystemService(Context.CLIPBOARD_SERVICE);
2029 cm.setText(text);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002030 }
2031
2032 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08002033 * Resets the browser title-view to whatever it must be
2034 * (for example, if we had a loading error)
2035 * When we have a new page, we call resetTitle, when we
2036 * have to reset the titlebar to whatever it used to be
2037 * (for example, if the user chose to stop loading), we
2038 * call resetTitleAndRevertLockIcon.
2039 */
2040 /* package */ void resetTitleAndRevertLockIcon() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002041 mTabControl.getCurrentTab().revertLockIcon();
2042 updateLockIconToLatest();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002043 resetTitleIconAndProgress();
2044 }
2045
2046 /**
2047 * Reset the title, favicon, and progress.
2048 */
2049 private void resetTitleIconAndProgress() {
2050 WebView current = mTabControl.getCurrentWebView();
2051 if (current == null) {
2052 return;
2053 }
2054 resetTitleAndIcon(current);
2055 int progress = current.getProgress();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002056 current.getWebChromeClient().onProgressChanged(current, progress);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002057 }
2058
2059 // Reset the title and the icon based on the given item.
2060 private void resetTitleAndIcon(WebView view) {
2061 WebHistoryItem item = view.copyBackForwardList().getCurrentItem();
2062 if (item != null) {
Leon Scroggins68579392009-09-15 15:31:54 -04002063 setUrlTitle(item.getUrl(), item.getTitle());
The Android Open Source Project0c908882009-03-03 19:32:16 -08002064 setFavicon(item.getFavicon());
2065 } else {
Leon Scroggins68579392009-09-15 15:31:54 -04002066 setUrlTitle(null, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002067 setFavicon(null);
2068 }
2069 }
2070
2071 /**
2072 * Sets a title composed of the URL and the title string.
2073 * @param url The URL of the site being loaded.
2074 * @param title The title of the site being loaded.
2075 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07002076 void setUrlTitle(String url, String title) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002077 mUrl = url;
2078 mTitle = title;
2079
Leon Scroggins58d56c62010-01-28 15:12:40 -05002080 // If we are in voice search mode, the title has already been set.
2081 if (mTabControl.getCurrentTab().isInVoiceSearchMode()) return;
2082 mTitleBar.setDisplayTitle(url);
Michael Kolba2b2ba82010-08-04 17:54:03 -07002083 mFakeTitleBar.setDisplayTitle(url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002084 }
2085
2086 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08002087 * @param url The URL to build a title version of the URL from.
2088 * @return The title version of the URL or null if fails.
2089 * The title version of the URL can be either the URL hostname,
2090 * or the hostname with an "https://" prefix (for secure URLs),
2091 * or an empty string if, for example, the URL in question is a
2092 * file:// URL with no hostname.
2093 */
Leon Scroggins32e14a62009-06-11 10:26:34 -04002094 /* package */ static String buildTitleUrl(String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002095 String titleUrl = null;
2096
2097 if (url != null) {
2098 try {
2099 // parse the url string
2100 URL urlObj = new URL(url);
2101 if (urlObj != null) {
2102 titleUrl = "";
2103
2104 String protocol = urlObj.getProtocol();
2105 String host = urlObj.getHost();
2106
2107 if (host != null && 0 < host.length()) {
2108 titleUrl = host;
2109 if (protocol != null) {
2110 // if a secure site, add an "https://" prefix!
2111 if (protocol.equalsIgnoreCase("https")) {
2112 titleUrl = protocol + "://" + host;
2113 }
2114 }
2115 }
2116 }
2117 } catch (MalformedURLException e) {}
2118 }
2119
2120 return titleUrl;
2121 }
2122
2123 // Set the favicon in the title bar.
Grace Kloba22ac16e2009-10-07 18:00:23 -07002124 void setFavicon(Bitmap icon) {
Leon Scroggins68579392009-09-15 15:31:54 -04002125 mTitleBar.setFavicon(icon);
Michael Kolba2b2ba82010-08-04 17:54:03 -07002126 mFakeTitleBar.setFavicon(icon);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002127 }
2128
2129 /**
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002130 * Close the tab, remove its associated title bar, and adjust mTabControl's
2131 * current tab to a valid value.
Leon Scroggins1f005d32009-08-10 17:36:42 -04002132 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07002133 /* package */ void closeTab(Tab t) {
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002134 int currentIndex = mTabControl.getCurrentIndex();
2135 int removeIndex = mTabControl.getTabIndex(t);
Leon Scroggins1f005d32009-08-10 17:36:42 -04002136 mTabControl.removeTab(t);
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002137 if (currentIndex >= removeIndex && currentIndex != 0) {
2138 currentIndex--;
2139 }
2140 mTabControl.setCurrentTab(mTabControl.getTab(currentIndex));
Andrei Popescua5bf1de2009-09-23 16:39:23 +01002141 resetTitleIconAndProgress();
Leon Scroggins654899b2010-06-25 16:25:23 -04002142 updateLockIconToLatest();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002143 }
2144
Leon Scrogginsdcc5eeb2010-02-23 17:26:37 -05002145 /* package */ void goBackOnePageOrQuit() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002146 Tab current = mTabControl.getCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002147 if (current == null) {
2148 /*
2149 * Instead of finishing the activity, simply push this to the back
2150 * of the stack and let ActivityManager to choose the foreground
2151 * activity. As BrowserActivity is singleTask, it will be always the
2152 * root of the task. So we can use either true or false for
2153 * moveTaskToBack().
2154 */
2155 moveTaskToBack(true);
Grace Kloba00d85e72009-09-23 18:50:05 -07002156 return;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002157 }
2158 WebView w = current.getWebView();
2159 if (w.canGoBack()) {
2160 w.goBack();
2161 } else {
2162 // Check to see if we are closing a window that was created by
2163 // another window. If so, we switch back to that window.
Grace Kloba22ac16e2009-10-07 18:00:23 -07002164 Tab parent = current.getParentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002165 if (parent != null) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04002166 switchToTab(mTabControl.getTabIndex(parent));
2167 // Now we close the other tab
2168 closeTab(current);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002169 } else {
2170 if (current.closeOnExit()) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002171 // force the tab's inLoad() to be false as we are going to
2172 // either finish the activity or remove the tab. This will
2173 // ensure pauseWebViewTimers() taking action.
2174 mTabControl.getCurrentTab().clearInLoad();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002175 if (mTabControl.getTabCount() == 1) {
2176 finish();
2177 return;
2178 }
Mike Reed7bfa63b2009-05-28 11:08:32 -04002179 // call pauseWebViewTimers() now, we won't be able to call
2180 // it in onPause() as the WebView won't be valid.
Grace Klobaec1b5ad2009-08-18 08:42:32 -07002181 // Temporarily change mActivityInPause to be true as
2182 // pauseWebViewTimers() will do nothing if mActivityInPause
2183 // is false.
Grace Kloba918e1d72009-08-13 14:55:06 -07002184 boolean savedState = mActivityInPause;
2185 if (savedState) {
Grace Klobaec1b5ad2009-08-18 08:42:32 -07002186 Log.e(LOGTAG, "BrowserActivity is already paused "
2187 + "while handing goBackOnePageOrQuit.");
Grace Kloba918e1d72009-08-13 14:55:06 -07002188 }
2189 mActivityInPause = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -04002190 pauseWebViewTimers();
Grace Kloba918e1d72009-08-13 14:55:06 -07002191 mActivityInPause = savedState;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002192 removeTabFromContentView(current);
2193 mTabControl.removeTab(current);
2194 }
2195 /*
2196 * Instead of finishing the activity, simply push this to the back
2197 * of the stack and let ActivityManager to choose the foreground
2198 * activity. As BrowserActivity is singleTask, it will be always the
2199 * root of the task. So we can use either true or false for
2200 * moveTaskToBack().
2201 */
2202 moveTaskToBack(true);
2203 }
2204 }
2205 }
2206
Grace Kloba22ac16e2009-10-07 18:00:23 -07002207 boolean isMenuDown() {
2208 return mMenuIsDown;
2209 }
2210
Grace Kloba5942df02009-09-18 11:48:29 -07002211 @Override
2212 public boolean onKeyDown(int keyCode, KeyEvent event) {
Leon Scrogginsf65b50d2009-12-08 10:44:28 -05002213 // Even if MENU is already held down, we need to call to super to open
2214 // the IME on long press.
2215 if (KeyEvent.KEYCODE_MENU == keyCode) {
2216 mMenuIsDown = true;
2217 return super.onKeyDown(keyCode, event);
2218 }
Grace Kloba5942df02009-09-18 11:48:29 -07002219 // The default key mode is DEFAULT_KEYS_SEARCH_LOCAL. As the MENU is
2220 // still down, we don't want to trigger the search. Pretend to consume
2221 // the key and do nothing.
2222 if (mMenuIsDown) return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002223
Grace Kloba5942df02009-09-18 11:48:29 -07002224 switch(keyCode) {
Grace Kloba5942df02009-09-18 11:48:29 -07002225 case KeyEvent.KEYCODE_SPACE:
Grace Klobada0fe552009-09-22 18:17:24 -07002226 // WebView/WebTextView handle the keys in the KeyDown. As
2227 // the Activity's shortcut keys are only handled when WebView
2228 // doesn't, have to do it in onKeyDown instead of onKeyUp.
2229 if (event.isShiftPressed()) {
2230 getTopWindow().pageUp(false);
2231 } else {
2232 getTopWindow().pageDown(false);
2233 }
Grace Kloba5942df02009-09-18 11:48:29 -07002234 return true;
2235 case KeyEvent.KEYCODE_BACK:
2236 if (event.getRepeatCount() == 0) {
2237 event.startTracking();
2238 return true;
2239 } else if (mCustomView == null && mActiveTabsPage == null
2240 && event.isLongPress()) {
Michael Kolb68792c82010-08-09 16:39:18 -07002241 bookmarksOrHistoryPicker(true, false);
Grace Kloba5942df02009-09-18 11:48:29 -07002242 return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002243 }
Grace Kloba5942df02009-09-18 11:48:29 -07002244 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002245 }
Grace Kloba5942df02009-09-18 11:48:29 -07002246 return super.onKeyDown(keyCode, event);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002247 }
2248
Grace Kloba5942df02009-09-18 11:48:29 -07002249 @Override
2250 public boolean onKeyUp(int keyCode, KeyEvent event) {
2251 switch(keyCode) {
2252 case KeyEvent.KEYCODE_MENU:
2253 mMenuIsDown = false;
2254 break;
Grace Kloba5942df02009-09-18 11:48:29 -07002255 case KeyEvent.KEYCODE_BACK:
2256 if (event.isTracking() && !event.isCanceled()) {
2257 if (mCustomView != null) {
2258 // if a custom view is showing, hide it
Grace Kloba22ac16e2009-10-07 18:00:23 -07002259 mTabControl.getCurrentWebView().getWebChromeClient()
2260 .onHideCustomView();
Grace Kloba5942df02009-09-18 11:48:29 -07002261 } else if (mActiveTabsPage != null) {
2262 // if tab page is showing, hide it
2263 removeActiveTabPage(true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002264 } else {
Grace Kloba5942df02009-09-18 11:48:29 -07002265 WebView subwindow = mTabControl.getCurrentSubWindow();
2266 if (subwindow != null) {
2267 if (subwindow.canGoBack()) {
2268 subwindow.goBack();
2269 } else {
2270 dismissSubWindow(mTabControl.getCurrentTab());
2271 }
2272 } else {
2273 goBackOnePageOrQuit();
2274 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002275 }
Grace Kloba5942df02009-09-18 11:48:29 -07002276 return true;
2277 }
2278 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002279 }
Grace Kloba5942df02009-09-18 11:48:29 -07002280 return super.onKeyUp(keyCode, event);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002281 }
2282
Leon Scroggins68579392009-09-15 15:31:54 -04002283 /* package */ void stopLoading() {
Ben Murdochb7cc8b42009-09-28 10:59:09 +01002284 mDidStopLoad = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002285 resetTitleAndRevertLockIcon();
2286 WebView w = getTopWindow();
2287 w.stopLoading();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002288 // FIXME: before refactor, it is using mWebViewClient. So I keep the
2289 // same logic here. But for subwindow case, should we call into the main
2290 // WebView's onPageFinished as we never call its onPageStarted and if
2291 // the page finishes itself, we don't call onPageFinished.
2292 mTabControl.getCurrentWebView().getWebViewClient().onPageFinished(w,
2293 w.getUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08002294
2295 cancelStopToast();
2296 mStopToast = Toast
2297 .makeText(this, R.string.stopping, Toast.LENGTH_SHORT);
2298 mStopToast.show();
2299 }
2300
Grace Kloba22ac16e2009-10-07 18:00:23 -07002301 boolean didUserStopLoading() {
2302 return mDidStopLoad;
2303 }
2304
The Android Open Source Project0c908882009-03-03 19:32:16 -08002305 private void cancelStopToast() {
2306 if (mStopToast != null) {
2307 mStopToast.cancel();
2308 mStopToast = null;
2309 }
2310 }
2311
Grace Kloba22ac16e2009-10-07 18:00:23 -07002312 // called by a UI or non-UI thread to post the message
2313 public void postMessage(int what, int arg1, int arg2, Object obj,
2314 long delayMillis) {
2315 mHandler.sendMessageDelayed(mHandler.obtainMessage(what, arg1, arg2,
2316 obj), delayMillis);
2317 }
2318
2319 // called by a UI or non-UI thread to remove the message
2320 void removeMessages(int what, Object object) {
2321 mHandler.removeMessages(what, object);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002322 }
2323
2324 // public message ids
2325 public final static int LOAD_URL = 1001;
2326 public final static int STOP_LOAD = 1002;
2327
2328 // Message Ids
2329 private static final int FOCUS_NODE_HREF = 102;
Grace Kloba92c18a52009-07-31 23:48:32 -07002330 private static final int RELEASE_WAKELOCK = 107;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002331
Grace Kloba22ac16e2009-10-07 18:00:23 -07002332 static final int UPDATE_BOOKMARK_THUMBNAIL = 108;
Ben Murdoch2694e232009-09-29 09:41:11 +01002333
Ben Murdocheecb4e62010-07-06 16:30:38 +01002334 private static final int TOUCH_ICON_DOWNLOADED = 109;
2335
The Android Open Source Project0c908882009-03-03 19:32:16 -08002336 // Private handler for handling javascript and saving passwords
2337 private Handler mHandler = new Handler() {
2338
Michael Kolbe0a36662010-06-29 10:37:12 -07002339 @Override
The Android Open Source Project0c908882009-03-03 19:32:16 -08002340 public void handleMessage(Message msg) {
2341 switch (msg.what) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002342 case FOCUS_NODE_HREF:
Ben Murdoch2694e232009-09-29 09:41:11 +01002343 {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002344 String url = (String) msg.getData().get("url");
Ben Murdoch90d088c2009-11-17 18:14:04 +00002345 String title = (String) msg.getData().get("title");
The Android Open Source Project0c908882009-03-03 19:32:16 -08002346 if (url == null || url.length() == 0) {
2347 break;
2348 }
2349 HashMap focusNodeMap = (HashMap) msg.obj;
2350 WebView view = (WebView) focusNodeMap.get("webview");
2351 // Only apply the action if the top window did not change.
2352 if (getTopWindow() != view) {
2353 break;
2354 }
2355 switch (msg.arg1) {
2356 case R.id.open_context_menu_id:
2357 case R.id.view_image_context_menu_id:
Leon Scroggins92472e82010-02-17 16:32:28 -05002358 loadUrlFromContext(getTopWindow(), url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002359 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002360 case R.id.bookmark_context_menu_id:
2361 Intent intent = new Intent(BrowserActivity.this,
2362 AddBookmarkPage.class);
2363 intent.putExtra("url", url);
Ben Murdoch90d088c2009-11-17 18:14:04 +00002364 intent.putExtra("title", title);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002365 startActivity(intent);
2366 break;
2367 case R.id.share_link_context_menu_id:
Leon Scroggins3e204452010-05-10 11:06:03 -04002368 sharePage(BrowserActivity.this, title, url, null,
Leon Scroggins96afcb12009-12-10 12:35:56 -05002369 null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002370 break;
2371 case R.id.copy_link_context_menu_id:
2372 copy(url);
2373 break;
2374 case R.id.save_link_context_menu_id:
2375 case R.id.download_context_menu_id:
2376 onDownloadStartNoStream(url, null, null, null, -1);
2377 break;
2378 }
2379 break;
Ben Murdoch2694e232009-09-29 09:41:11 +01002380 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002381
2382 case LOAD_URL:
Leon Scroggins92472e82010-02-17 16:32:28 -05002383 loadUrlFromContext(getTopWindow(), (String) msg.obj);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002384 break;
2385
2386 case STOP_LOAD:
2387 stopLoading();
2388 break;
2389
The Android Open Source Project0c908882009-03-03 19:32:16 -08002390 case RELEASE_WAKELOCK:
2391 if (mWakeLock.isHeld()) {
2392 mWakeLock.release();
Grace Kloba5d0e02e2009-10-05 15:15:36 -07002393 // if we reach here, Browser should be still in the
2394 // background loading after WAKELOCK_TIMEOUT (5-min).
2395 // To avoid burning the battery, stop loading.
2396 mTabControl.stopAllLoading();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002397 }
2398 break;
Ben Murdoch2694e232009-09-29 09:41:11 +01002399
2400 case UPDATE_BOOKMARK_THUMBNAIL:
2401 WebView view = (WebView) msg.obj;
2402 if (view != null) {
2403 updateScreenshot(view);
2404 }
2405 break;
Ben Murdocheecb4e62010-07-06 16:30:38 +01002406
2407 case TOUCH_ICON_DOWNLOADED:
2408 Bundle b = msg.getData();
2409 showSaveToHomescreenDialog(b.getString("url"),
2410 b.getString("title"),
2411 (Bitmap) b.getParcelable("touchIcon"),
2412 (Bitmap) b.getParcelable("favicon"));
2413 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002414 }
2415 }
2416 };
2417
Leon Scroggins96afcb12009-12-10 12:35:56 -05002418 /**
2419 * Share a page, providing the title, url, favicon, and a screenshot. Uses
2420 * an {@link Intent} to launch the Activity chooser.
2421 * @param c Context used to launch a new Activity.
2422 * @param title Title of the page. Stored in the Intent with
Paul Westbrook03e6d392010-02-12 10:33:29 -08002423 * {@link Intent#EXTRA_SUBJECT}
Leon Scroggins96afcb12009-12-10 12:35:56 -05002424 * @param url URL of the page. Stored in the Intent with
2425 * {@link Intent#EXTRA_TEXT}
2426 * @param favicon Bitmap of the favicon for the page. Stored in the Intent
2427 * with {@link Browser#EXTRA_SHARE_FAVICON}
2428 * @param screenshot Bitmap of a screenshot of the page. Stored in the
2429 * Intent with {@link Browser#EXTRA_SHARE_SCREENSHOT}
2430 */
2431 public static final void sharePage(Context c, String title, String url,
2432 Bitmap favicon, Bitmap screenshot) {
2433 Intent send = new Intent(Intent.ACTION_SEND);
2434 send.setType("text/plain");
2435 send.putExtra(Intent.EXTRA_TEXT, url);
Paul Westbrook03e6d392010-02-12 10:33:29 -08002436 send.putExtra(Intent.EXTRA_SUBJECT, title);
Leon Scroggins96afcb12009-12-10 12:35:56 -05002437 send.putExtra(Browser.EXTRA_SHARE_FAVICON, favicon);
2438 send.putExtra(Browser.EXTRA_SHARE_SCREENSHOT, screenshot);
2439 try {
2440 c.startActivity(Intent.createChooser(send, c.getString(
2441 R.string.choosertitle_sharevia)));
2442 } catch(android.content.ActivityNotFoundException ex) {
2443 // if no app handles it, do nothing
2444 }
2445 }
2446
Leon Scroggins89c6d362009-07-15 16:54:37 -04002447 private void updateScreenshot(WebView view) {
2448 // If this is a bookmarked site, add a screenshot to the database.
2449 // FIXME: When should we update? Every time?
2450 // FIXME: Would like to make sure there is actually something to
2451 // draw, but the API for that (WebViewCore.pictureReady()) is not
2452 // currently accessible here.
Ben Murdochaac7aa62009-09-17 16:57:40 +01002453
Ben Murdoch87cc65d2010-06-29 20:34:10 +01002454 final Bitmap bm = createScreenshot(view, getDesiredThumbnailWidth(this),
2455 getDesiredThumbnailHeight(this));
Patrick Scottcb192b52010-04-14 14:38:55 -04002456 if (bm == null) {
2457 return;
Leon Scroggins89c6d362009-07-15 16:54:37 -04002458 }
Patrick Scottcb192b52010-04-14 14:38:55 -04002459
2460 final ContentResolver cr = getContentResolver();
2461 final String url = view.getUrl();
2462 final String originalUrl = view.getOriginalUrl();
2463
2464 new AsyncTask<Void, Void, Void>() {
2465 @Override
2466 protected Void doInBackground(Void... unused) {
2467 Cursor c = null;
2468 try {
Jeff Hamilton84029622010-08-05 14:29:28 -05002469 c = Bookmarks.queryBookmarksForUrl(
Jeff Hamilton8ce956c2010-08-17 11:13:53 -05002470 cr, originalUrl, url);
Patrick Scottcb192b52010-04-14 14:38:55 -04002471 if (c != null) {
2472 if (c.moveToFirst()) {
2473 ContentValues values = new ContentValues();
2474 final ByteArrayOutputStream os
2475 = new ByteArrayOutputStream();
2476 bm.compress(Bitmap.CompressFormat.PNG, 100, os);
Jeff Hamilton8ce956c2010-08-17 11:13:53 -05002477 values.put(BrowserContract.Bookmarks.THUMBNAIL,
Patrick Scottcb192b52010-04-14 14:38:55 -04002478 os.toByteArray());
2479 do {
2480 cr.update(ContentUris.withAppendedId(
Jeff Hamilton8ce956c2010-08-17 11:13:53 -05002481 BrowserContract.Bookmarks.CONTENT_URI, c.getLong(0)),
Patrick Scottcb192b52010-04-14 14:38:55 -04002482 values, null, null);
2483 } while (c.moveToNext());
2484 }
2485 }
2486 } catch (IllegalStateException e) {
2487 // Ignore
2488 } finally {
2489 if (c != null) c.close();
2490 }
2491 return null;
2492 }
2493 }.execute();
Leon Scroggins89c6d362009-07-15 16:54:37 -04002494 }
2495
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002496 /**
Leon Scrogginsf8551612009-09-24 16:06:02 -04002497 * Values for the size of the thumbnail created when taking a screenshot.
2498 * Lazily initialized. Instead of using these directly, use
2499 * getDesiredThumbnailWidth() or getDesiredThumbnailHeight().
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002500 */
Leon Scrogginsf8551612009-09-24 16:06:02 -04002501 private static int THUMBNAIL_WIDTH = 0;
2502 private static int THUMBNAIL_HEIGHT = 0;
2503
2504 /**
2505 * Return the desired width for thumbnail screenshots, which are stored in
2506 * the database, and used on the bookmarks screen.
2507 * @param context Context for finding out the density of the screen.
2508 * @return int desired width for thumbnail screenshot.
2509 */
2510 /* package */ static int getDesiredThumbnailWidth(Context context) {
2511 if (THUMBNAIL_WIDTH == 0) {
2512 float density = context.getResources().getDisplayMetrics().density;
2513 THUMBNAIL_WIDTH = (int) (90 * density);
2514 THUMBNAIL_HEIGHT = (int) (80 * density);
2515 }
2516 return THUMBNAIL_WIDTH;
2517 }
2518
2519 /**
2520 * Return the desired height for thumbnail screenshots, which are stored in
2521 * the database, and used on the bookmarks screen.
2522 * @param context Context for finding out the density of the screen.
2523 * @return int desired height for thumbnail screenshot.
2524 */
2525 /* package */ static int getDesiredThumbnailHeight(Context context) {
2526 // To ensure that they are both initialized.
2527 getDesiredThumbnailWidth(context);
2528 return THUMBNAIL_HEIGHT;
2529 }
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002530
Ben Murdoch87cc65d2010-06-29 20:34:10 +01002531 private Bitmap createScreenshot(WebView view, int width, int height) {
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002532 Picture thumbnail = view.capturePicture();
Leon Scroggins45800572009-09-29 16:38:47 -04002533 if (thumbnail == null) {
2534 return null;
2535 }
Ben Murdoch87cc65d2010-06-29 20:34:10 +01002536 Bitmap bm = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002537 Canvas canvas = new Canvas(bm);
2538 // May need to tweak these values to determine what is the
2539 // best scale factor
Ben Murdoch2694e232009-09-29 09:41:11 +01002540 int thumbnailWidth = thumbnail.getWidth();
Ben Murdochae59c3f2009-10-20 18:30:28 +01002541 int thumbnailHeight = thumbnail.getHeight();
2542 float scaleFactorX = 1.0f;
2543 float scaleFactorY = 1.0f;
Ben Murdoch2694e232009-09-29 09:41:11 +01002544 if (thumbnailWidth > 0) {
Ben Murdoch87cc65d2010-06-29 20:34:10 +01002545 scaleFactorX = (float) width / (float)thumbnailWidth;
Ben Murdochae59c3f2009-10-20 18:30:28 +01002546 } else {
2547 return null;
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002548 }
Ben Murdochae59c3f2009-10-20 18:30:28 +01002549
2550 if (view.getWidth() > view.getHeight() &&
2551 thumbnailHeight < view.getHeight() && thumbnailHeight > 0) {
2552 // If the device is in landscape and the page is shorter
2553 // than the height of the view, stretch the thumbnail to fill the
2554 // space.
Ben Murdoch87cc65d2010-06-29 20:34:10 +01002555 scaleFactorY = (float) height / (float)thumbnailHeight;
Ben Murdochae59c3f2009-10-20 18:30:28 +01002556 } else {
2557 // In the portrait case, this looks nice.
2558 scaleFactorY = scaleFactorX;
2559 }
2560
2561 canvas.scale(scaleFactorX, scaleFactorY);
2562
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002563 thumbnail.draw(canvas);
2564 return bm;
2565 }
2566
The Android Open Source Project0c908882009-03-03 19:32:16 -08002567 // -------------------------------------------------------------------------
Grace Kloba22ac16e2009-10-07 18:00:23 -07002568 // Helper function for WebViewClient.
The Android Open Source Project0c908882009-03-03 19:32:16 -08002569 //-------------------------------------------------------------------------
2570
2571 // Use in overrideUrlLoading
2572 /* package */ final static String SCHEME_WTAI = "wtai://wp/";
2573 /* package */ final static String SCHEME_WTAI_MC = "wtai://wp/mc;";
2574 /* package */ final static String SCHEME_WTAI_SD = "wtai://wp/sd;";
2575 /* package */ final static String SCHEME_WTAI_AP = "wtai://wp/ap;";
2576
Leon Scroggins92472e82010-02-17 16:32:28 -05002577 // Keep this initial progress in sync with initialProgressValue (* 100)
2578 // in ProgressTracker.cpp
2579 private final static int INITIAL_PROGRESS = 10;
2580
Grace Kloba22ac16e2009-10-07 18:00:23 -07002581 void onPageStarted(WebView view, String url, Bitmap favicon) {
2582 // when BrowserActivity just starts, onPageStarted may be called before
2583 // onResume as it is triggered from onCreate. Call resumeWebViewTimers
2584 // to start the timer. As we won't switch tabs while an activity is in
2585 // pause state, we can ensure calling resume and pause in pair.
2586 if (mActivityInPause) resumeWebViewTimers();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002587
Grace Kloba22ac16e2009-10-07 18:00:23 -07002588 resetLockIcon(url);
2589 setUrlTitle(url, null);
2590 setFavicon(favicon);
Leon Scroggins8cf8f682009-11-04 11:13:50 -08002591 // Show some progress so that the user knows the page is beginning to
2592 // load
Leon Scroggins92472e82010-02-17 16:32:28 -05002593 onProgressChanged(view, INITIAL_PROGRESS);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002594 mDidStopLoad = false;
Grace Kloba22ac16e2009-10-07 18:00:23 -07002595 if (!mIsNetworkUp) createAndShowNetworkDialog();
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04002596 endActionMode();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002597 if (mSettings.isTracing()) {
2598 String host;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002599 try {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002600 WebAddress uri = new WebAddress(url);
2601 host = uri.mHost;
2602 } catch (android.net.ParseException ex) {
2603 host = "browser";
The Android Open Source Project0c908882009-03-03 19:32:16 -08002604 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002605 host = host.replace('.', '_');
2606 host += ".trace";
2607 mInTrace = true;
2608 Debug.startMethodTracing(host, 20 * 1024 * 1024);
2609 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002610
Grace Kloba22ac16e2009-10-07 18:00:23 -07002611 // Performance probe
2612 if (false) {
2613 mStart = SystemClock.uptimeMillis();
2614 mProcessStart = Process.getElapsedCpuTime();
2615 long[] sysCpu = new long[7];
2616 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2617 sysCpu, null)) {
2618 mUserStart = sysCpu[0] + sysCpu[1];
2619 mSystemStart = sysCpu[2];
2620 mIdleStart = sysCpu[3];
2621 mIrqStart = sysCpu[4] + sysCpu[5] + sysCpu[6];
2622 }
2623 mUiStart = SystemClock.currentThreadTimeMillis();
2624 }
2625 }
2626
2627 void onPageFinished(WebView view, String url) {
2628 // Reset the title and icon in case we stopped a provisional load.
2629 resetTitleAndIcon(view);
2630 // Update the lock icon image only once we are done loading
2631 updateLockIconToLatest();
2632 // pause the WebView timer and release the wake lock if it is finished
2633 // while BrowserActivity is in pause state.
2634 if (mActivityInPause && pauseWebViewTimers()) {
2635 if (mWakeLock.isHeld()) {
2636 mHandler.removeMessages(RELEASE_WAKELOCK);
2637 mWakeLock.release();
2638 }
2639 }
2640
2641 // Performance probe
2642 if (false) {
2643 long[] sysCpu = new long[7];
2644 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2645 sysCpu, null)) {
2646 String uiInfo = "UI thread used "
2647 + (SystemClock.currentThreadTimeMillis() - mUiStart)
2648 + " ms";
2649 if (LOGD_ENABLED) {
2650 Log.d(LOGTAG, uiInfo);
2651 }
2652 //The string that gets written to the log
2653 String performanceString = "It took total "
2654 + (SystemClock.uptimeMillis() - mStart)
2655 + " ms clock time to load the page."
2656 + "\nbrowser process used "
2657 + (Process.getElapsedCpuTime() - mProcessStart)
2658 + " ms, user processes used "
2659 + (sysCpu[0] + sysCpu[1] - mUserStart) * 10
2660 + " ms, kernel used "
2661 + (sysCpu[2] - mSystemStart) * 10
2662 + " ms, idle took " + (sysCpu[3] - mIdleStart) * 10
2663 + " ms and irq took "
2664 + (sysCpu[4] + sysCpu[5] + sysCpu[6] - mIrqStart)
2665 * 10 + " ms, " + uiInfo;
2666 if (LOGD_ENABLED) {
2667 Log.d(LOGTAG, performanceString + "\nWebpage: " + url);
2668 }
2669 if (url != null) {
2670 // strip the url to maintain consistency
2671 String newUrl = new String(url);
2672 if (newUrl.startsWith("http://www.")) {
2673 newUrl = newUrl.substring(11);
2674 } else if (newUrl.startsWith("http://")) {
2675 newUrl = newUrl.substring(7);
2676 } else if (newUrl.startsWith("https://www.")) {
2677 newUrl = newUrl.substring(12);
2678 } else if (newUrl.startsWith("https://")) {
2679 newUrl = newUrl.substring(8);
2680 }
2681 if (LOGD_ENABLED) {
2682 Log.d(LOGTAG, newUrl + " loaded");
2683 }
Grace Kloba5b078b52009-06-24 20:23:41 -07002684 }
2685 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002686 }
Grace Kloba5b078b52009-06-24 20:23:41 -07002687
Grace Kloba22ac16e2009-10-07 18:00:23 -07002688 if (mInTrace) {
2689 mInTrace = false;
2690 Debug.stopMethodTracing();
2691 }
2692 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002693
Grace Klobae7fe26b2010-06-28 16:23:33 -07002694 private void closeEmptyChildTab() {
2695 Tab current = mTabControl.getCurrentTab();
2696 if (current != null
2697 && current.getWebView().copyBackForwardList().getSize() == 0) {
2698 Tab parent = current.getParentTab();
2699 if (parent != null) {
2700 switchToTab(mTabControl.getTabIndex(parent));
2701 closeTab(current);
2702 }
2703 }
2704 }
2705
Grace Kloba22ac16e2009-10-07 18:00:23 -07002706 boolean shouldOverrideUrlLoading(WebView view, String url) {
2707 if (url.startsWith(SCHEME_WTAI)) {
2708 // wtai://wp/mc;number
2709 // number=string(phone-number)
2710 if (url.startsWith(SCHEME_WTAI_MC)) {
2711 Intent intent = new Intent(Intent.ACTION_VIEW,
2712 Uri.parse(WebView.SCHEME_TEL +
2713 url.substring(SCHEME_WTAI_MC.length())));
2714 startActivity(intent);
Grace Klobae7fe26b2010-06-28 16:23:33 -07002715 // before leaving BrowserActivity, close the empty child tab.
2716 // If a new tab is created through JavaScript open to load this
2717 // url, we would like to close it as we will load this url in a
2718 // different Activity.
2719 closeEmptyChildTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002720 return true;
2721 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002722 // wtai://wp/sd;dtmf
2723 // dtmf=string(dialstring)
2724 if (url.startsWith(SCHEME_WTAI_SD)) {
2725 // TODO: only send when there is active voice connection
2726 return false;
2727 }
2728 // wtai://wp/ap;number;name
2729 // number=string(phone-number)
2730 // name=string
2731 if (url.startsWith(SCHEME_WTAI_AP)) {
2732 // TODO
2733 return false;
2734 }
2735 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002736
Grace Kloba22ac16e2009-10-07 18:00:23 -07002737 // The "about:" schemes are internal to the browser; don't want these to
2738 // be dispatched to other apps.
2739 if (url.startsWith("about:")) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002740 return false;
2741 }
2742
Jeff Davidson43610292010-07-16 16:03:58 -07002743 // If this is a Google search, attempt to add an RLZ string (if one isn't already present).
2744 if (rlzProviderPresent()) {
2745 Uri siteUri = Uri.parse(url);
2746 if (needsRlzString(siteUri)) {
2747 String rlz = null;
2748 Cursor cur = null;
2749 try {
2750 cur = getContentResolver().query(getRlzUri(), null, null, null, null);
2751 if (cur != null && cur.moveToFirst() && !cur.isNull(0)) {
2752 url = siteUri.buildUpon()
2753 .appendQueryParameter("rlz", cur.getString(0))
2754 .build().toString();
2755 }
2756 } finally {
2757 if (cur != null) {
2758 cur.close();
2759 }
2760 }
2761 loadUrl(view, url);
2762 return true;
2763 }
2764 }
2765
Grace Kloba22ac16e2009-10-07 18:00:23 -07002766 Intent intent;
2767 // perform generic parsing of the URI to turn it into an Intent.
2768 try {
2769 intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME);
2770 } catch (URISyntaxException ex) {
2771 Log.w("Browser", "Bad URI " + url + ": " + ex.getMessage());
2772 return false;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002773 }
2774
Grace Kloba22ac16e2009-10-07 18:00:23 -07002775 // check whether the intent can be resolved. If not, we will see
2776 // whether we can download it from the Market.
2777 if (getPackageManager().resolveActivity(intent, 0) == null) {
2778 String packagename = intent.getPackage();
2779 if (packagename != null) {
2780 intent = new Intent(Intent.ACTION_VIEW, Uri
2781 .parse("market://search?q=pname:" + packagename));
2782 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2783 startActivity(intent);
Grace Klobae7fe26b2010-06-28 16:23:33 -07002784 // before leaving BrowserActivity, close the empty child tab.
2785 // If a new tab is created through JavaScript open to load this
2786 // url, we would like to close it as we will load this url in a
2787 // different Activity.
2788 closeEmptyChildTab();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002789 return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002790 } else {
2791 return false;
2792 }
2793 }
2794
Grace Kloba22ac16e2009-10-07 18:00:23 -07002795 // sanitize the Intent, ensuring web pages can not bypass browser
2796 // security (only access to BROWSABLE activities).
2797 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2798 intent.setComponent(null);
2799 try {
2800 if (startActivityIfNeeded(intent, -1)) {
Grace Klobae7fe26b2010-06-28 16:23:33 -07002801 // before leaving BrowserActivity, close the empty child tab.
2802 // If a new tab is created through JavaScript open to load this
2803 // url, we would like to close it as we will load this url in a
2804 // different Activity.
2805 closeEmptyChildTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002806 return true;
2807 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002808 } catch (ActivityNotFoundException ex) {
2809 // ignore the error. If no application can handle the URL,
2810 // eg about:blank, assume the browser can handle it.
2811 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002812
Grace Kloba22ac16e2009-10-07 18:00:23 -07002813 if (mMenuIsDown) {
Michael Kolb68792c82010-08-09 16:39:18 -07002814 openTab(url, false);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002815 closeOptionsMenu();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002816 return true;
2817 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002818 return false;
2819 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002820
Jeff Davidson43610292010-07-16 16:03:58 -07002821 // Determine whether the RLZ provider is present on the system.
2822 private boolean rlzProviderPresent() {
2823 if (mIsProviderPresent == null) {
2824 PackageManager pm = getPackageManager();
2825 mIsProviderPresent = pm.resolveContentProvider(BrowserSettings.RLZ_PROVIDER, 0) != null;
2826 }
2827 return mIsProviderPresent;
2828 }
2829
2830 // Retrieve the RLZ access point string and cache the URI used to retrieve RLZ values.
2831 private Uri getRlzUri() {
2832 if (mRlzUri == null) {
2833 String ap = getResources().getString(R.string.rlz_access_point);
2834 mRlzUri = Uri.withAppendedPath(BrowserSettings.RLZ_PROVIDER_URI, ap);
2835 }
2836 return mRlzUri;
2837 }
2838
2839 // Determine if this URI appears to be for a Google search and does not have an RLZ parameter.
2840 // Taken largely from Chrome source, src/chrome/browser/google_url_tracker.cc
2841 private static boolean needsRlzString(Uri uri) {
2842 if ((uri.getQueryParameter("q") != null) && (uri.getQueryParameter("rlz") == null)) {
2843 String host = uri.getHost();
2844 if (host == null) {
2845 return false;
2846 }
2847 String[] hostComponents = host.split("\\.");
2848
2849 if (hostComponents.length < 2) {
2850 return false;
2851 }
2852 int googleComponent = hostComponents.length - 2;
2853 String component = hostComponents[googleComponent];
2854 if (!"google".equals(component)) {
2855 if (hostComponents.length < 3 ||
2856 (!"co".equals(component) && !"com".equals(component))) {
2857 return false;
2858 }
2859 googleComponent = hostComponents.length - 3;
2860 if (!"google".equals(hostComponents[googleComponent])) {
2861 return false;
2862 }
2863 }
2864
2865 // Google corp network handling.
2866 if (googleComponent > 0 && "corp".equals(hostComponents[googleComponent - 1])) {
2867 return false;
2868 }
2869
2870 return true;
2871 }
2872 return false;
2873 }
2874
Grace Kloba22ac16e2009-10-07 18:00:23 -07002875 // -------------------------------------------------------------------------
2876 // Helper function for WebChromeClient
2877 // -------------------------------------------------------------------------
The Android Open Source Project0c908882009-03-03 19:32:16 -08002878
Grace Kloba22ac16e2009-10-07 18:00:23 -07002879 void onProgressChanged(WebView view, int newProgress) {
Michael Kolba2b2ba82010-08-04 17:54:03 -07002880
2881 // On the phone, the fake title bar will always cover up the
2882 // regular title bar (or the regular one is offscreen), so only the
2883 // fake title bar needs to change its progress
2884 mFakeTitleBar.setProgress(newProgress);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002885
Grace Kloba22ac16e2009-10-07 18:00:23 -07002886 if (newProgress == 100) {
2887 // onProgressChanged() may continue to be called after the main
2888 // frame has finished loading, as any remaining sub frames continue
2889 // to load. We'll only get called once though with newProgress as
2890 // 100 when everything is loaded. (onPageFinished is called once
2891 // when the main frame completes loading regardless of the state of
2892 // any sub frames so calls to onProgressChanges may continue after
2893 // onPageFinished has executed)
2894 if (mInLoad) {
2895 mInLoad = false;
Leon Scrogginsa27ff192009-09-14 12:58:04 -04002896 updateInLoadMenuItems();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002897 // If the options menu is open, leave the title bar
2898 if (!mOptionsMenuOpen || !mIconView) {
2899 hideFakeTitleBar();
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07002900 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002901 }
Leon Scrogginsaa37e7f2010-03-05 11:51:20 -05002902 } else {
2903 if (!mInLoad) {
2904 // onPageFinished may have already been called but a subframe is
2905 // still loading and updating the progress. Reset mInLoad and
2906 // update the menu items.
2907 mInLoad = true;
2908 updateInLoadMenuItems();
2909 }
2910 // When the page first begins to load, the Activity may still be
2911 // paused, in which case showFakeTitleBar will do nothing. Call
2912 // again as the page continues to load so that it will be shown.
2913 // (Calling it will the fake title bar is already showing will also
2914 // do nothing.
Grace Kloba22ac16e2009-10-07 18:00:23 -07002915 if (!mOptionsMenuOpen || mIconView) {
2916 // This page has begun to load, so show the title bar
2917 showFakeTitleBar();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002918 }
2919 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002920 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002921
Grace Kloba22ac16e2009-10-07 18:00:23 -07002922 void onShowCustomView(View view, WebChromeClient.CustomViewCallback callback) {
Derek Sollenberger8ff57db2009-12-08 15:39:55 -05002923 // if a view already exists then immediately terminate the new one
2924 if (mCustomView != null) {
2925 callback.onCustomViewHidden();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002926 return;
Derek Sollenberger8ff57db2009-12-08 15:39:55 -05002927 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002928
2929 // Add the custom view to its container.
2930 mCustomViewContainer.addView(view, COVER_SCREEN_GRAVITY_CENTER);
2931 mCustomView = view;
2932 mCustomViewCallback = callback;
2933 // Save the menu state and set it to empty while the custom
2934 // view is showing.
2935 mOldMenuState = mMenuState;
2936 mMenuState = EMPTY_MENU;
2937 // Hide the content view.
2938 mContentView.setVisibility(View.GONE);
2939 // Finally show the custom view container.
Andrei Popescu163ab742009-10-20 17:58:23 +01002940 setStatusBarVisibility(false);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002941 mCustomViewContainer.setVisibility(View.VISIBLE);
2942 mCustomViewContainer.bringToFront();
2943 }
2944
2945 void onHideCustomView() {
2946 if (mCustomView == null)
2947 return;
2948
2949 // Hide the custom view.
2950 mCustomView.setVisibility(View.GONE);
2951 // Remove the custom view from its container.
2952 mCustomViewContainer.removeView(mCustomView);
2953 mCustomView = null;
2954 // Reset the old menu state.
2955 mMenuState = mOldMenuState;
2956 mOldMenuState = EMPTY_MENU;
2957 mCustomViewContainer.setVisibility(View.GONE);
2958 mCustomViewCallback.onCustomViewHidden();
2959 // Show the content view.
Andrei Popescu163ab742009-10-20 17:58:23 +01002960 setStatusBarVisibility(true);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002961 mContentView.setVisibility(View.VISIBLE);
2962 }
2963
2964 Bitmap getDefaultVideoPoster() {
2965 if (mDefaultVideoPoster == null) {
2966 mDefaultVideoPoster = BitmapFactory.decodeResource(
2967 getResources(), R.drawable.default_video_poster);
Patrick Scott3918d442009-08-04 13:22:29 -04002968 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002969 return mDefaultVideoPoster;
2970 }
Patrick Scott3918d442009-08-04 13:22:29 -04002971
Grace Kloba22ac16e2009-10-07 18:00:23 -07002972 View getVideoLoadingProgressView() {
2973 if (mVideoProgressView == null) {
2974 LayoutInflater inflater = LayoutInflater.from(BrowserActivity.this);
2975 mVideoProgressView = inflater.inflate(
2976 R.layout.video_loading_progress, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002977 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002978 return mVideoProgressView;
2979 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002980
Leon Scroggins8d5fa432009-10-02 15:55:59 -04002981 /*
2982 * The Object used to inform the WebView of the file to upload.
2983 */
2984 private ValueCallback<Uri> mUploadMessage;
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002985 private String mCameraFilePath;
Leon Scroggins8d5fa432009-10-02 15:55:59 -04002986
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002987 void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
2988
2989 final String imageMimeType = "image/*";
Ben Murdoch6af492a2010-06-15 12:38:17 +01002990 final String videoMimeType = "video/*";
Ben Murdoch039bd472010-07-21 21:26:57 +01002991 final String audioMimeType = "audio/*";
Ben Murdochb50d7402010-07-16 12:42:22 +01002992 final String mediaSourceKey = "capture";
Ben Murdoch6af492a2010-06-15 12:38:17 +01002993 final String mediaSourceValueCamera = "camera";
Ben Murdochb50d7402010-07-16 12:42:22 +01002994 final String mediaSourceValueFileSystem = "filesystem";
Ben Murdoch6af492a2010-06-15 12:38:17 +01002995 final String mediaSourceValueCamcorder = "camcorder";
Ben Murdoch039bd472010-07-21 21:26:57 +01002996 final String mediaSourceValueMicrophone = "microphone";
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002997
Ben Murdoch039bd472010-07-21 21:26:57 +01002998 // media source can be 'filesystem' or 'camera' or 'camcorder' or 'microphone'.
Ben Murdoch6af492a2010-06-15 12:38:17 +01002999 String mediaSource = "";
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003000
Ben Murdoch6af492a2010-06-15 12:38:17 +01003001 // We add the camera intent if there was no accept type (or '*/*' or 'image/*').
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003002 boolean addCameraIntent = true;
Ben Murdoch6af492a2010-06-15 12:38:17 +01003003 // We add the camcorder intent if there was no accept type (or '*/*' or 'video/*').
3004 boolean addCamcorderIntent = true;
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003005
Ben Murdoch6af492a2010-06-15 12:38:17 +01003006 if (mUploadMessage != null) {
3007 // Already a file picker operation in progress.
3008 return;
3009 }
3010
Grace Kloba22ac16e2009-10-07 18:00:23 -07003011 mUploadMessage = uploadMsg;
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003012
3013 // Parse the accept type.
3014 String params[] = acceptType.split(";");
3015 String mimeType = params[0];
3016
3017 for (String p : params) {
3018 String[] keyValue = p.split("=");
3019 if (keyValue.length == 2) {
3020 // Process key=value parameters.
Ben Murdoch6af492a2010-06-15 12:38:17 +01003021 if (mediaSourceKey.equals(keyValue[0])) {
3022 mediaSource = keyValue[1];
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003023 }
3024 }
3025 }
3026
3027 // This intent will display the standard OPENABLE file picker.
Grace Kloba22ac16e2009-10-07 18:00:23 -07003028 Intent i = new Intent(Intent.ACTION_GET_CONTENT);
3029 i.addCategory(Intent.CATEGORY_OPENABLE);
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003030
3031 // Create an intent to add to the standard file picker that will
3032 // capture an image from the camera. We'll combine this intent with
3033 // the standard OPENABLE picker unless the web developer specifically
3034 // requested the camera or gallery be opened by passing a parameter
3035 // in the accept type.
3036 Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
3037 File externalDataDir = Environment.getExternalStoragePublicDirectory(
3038 Environment.DIRECTORY_DCIM);
3039 File cameraDataDir = new File(externalDataDir.getAbsolutePath() +
3040 File.separator + "browser-photos");
3041 cameraDataDir.mkdirs();
3042 mCameraFilePath = cameraDataDir.getAbsolutePath() + File.separator +
3043 System.currentTimeMillis() + ".jpg";
3044 cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(mCameraFilePath)));
3045
Ben Murdoch6af492a2010-06-15 12:38:17 +01003046 Intent camcorderIntent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
3047
Ben Murdoch039bd472010-07-21 21:26:57 +01003048 Intent soundRecIntent = new Intent(MediaStore.Audio.Media.RECORD_SOUND_ACTION);
3049
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003050 if (mimeType.equals(imageMimeType)) {
3051 i.setType(imageMimeType);
Ben Murdoch6af492a2010-06-15 12:38:17 +01003052 addCamcorderIntent = false;
3053 if (mediaSource.equals(mediaSourceValueCamera)) {
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003054 // Specified 'image/*' and requested the camera, so go ahead and launch the camera
3055 // directly.
3056 BrowserActivity.this.startActivityForResult(cameraIntent, FILE_SELECTED);
3057 return;
Ben Murdochb50d7402010-07-16 12:42:22 +01003058 } else if (mediaSource.equals(mediaSourceValueFileSystem)) {
3059 // Specified filesytem as the source, so don't want to consider the camera.
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003060 addCameraIntent = false;
3061 }
Ben Murdoch6af492a2010-06-15 12:38:17 +01003062 } else if (mimeType.equals(videoMimeType)) {
3063 i.setType(videoMimeType);
3064 addCameraIntent = false;
3065 // The camcorder saves it's own file and returns it to us in the intent, so
3066 // we don't need to generate one here.
3067 mCameraFilePath = null;
3068
3069 if (mediaSource.equals(mediaSourceValueCamcorder)) {
Ben Murdoch039bd472010-07-21 21:26:57 +01003070 // Specified 'video/*' and requested the camcorder, so go ahead and launch the
3071 // camcorder directly.
Ben Murdoch6af492a2010-06-15 12:38:17 +01003072 BrowserActivity.this.startActivityForResult(camcorderIntent, FILE_SELECTED);
3073 return;
Ben Murdochb50d7402010-07-16 12:42:22 +01003074 } else if (mediaSource.equals(mediaSourceValueFileSystem)) {
3075 // Specified filesystem as the source, so don't want to consider the camcorder.
Ben Murdoch6af492a2010-06-15 12:38:17 +01003076 addCamcorderIntent = false;
3077 }
Ben Murdoch039bd472010-07-21 21:26:57 +01003078 } else if (mimeType.equals(audioMimeType)) {
3079 i.setType(audioMimeType);
3080 addCameraIntent = false;
3081 addCamcorderIntent = false;
3082 if (mediaSource.equals(mediaSourceValueMicrophone)) {
3083 // Specified 'audio/*' and requested microphone, so go ahead and launch the sound
3084 // recorder.
3085 BrowserActivity.this.startActivityForResult(soundRecIntent, FILE_SELECTED);
3086 return;
3087 }
3088 // On a default system, there is no single option to open an audio "gallery". Both the
3089 // sound recorder and music browser respond to the OPENABLE/audio/* intent unlike the
3090 // image/* and video/* OPENABLE intents where the image / video gallery are the only
3091 // respondants (and so the user is not prompted by default).
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003092 } else {
3093 i.setType("*/*");
3094 }
3095
Ben Murdoch6af492a2010-06-15 12:38:17 +01003096 // Combine the chooser and the extra choices (like camera or camcorder)
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003097 Intent chooser = new Intent(Intent.ACTION_CHOOSER);
3098 chooser.putExtra(Intent.EXTRA_INTENT, i);
3099
Ben Murdoch6af492a2010-06-15 12:38:17 +01003100 Vector<Intent> extraInitialIntents = new Vector<Intent>(0);
3101
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003102 if (addCameraIntent) {
Ben Murdoch6af492a2010-06-15 12:38:17 +01003103 extraInitialIntents.add(cameraIntent);
3104 }
3105
3106 if (addCamcorderIntent) {
3107 extraInitialIntents.add(camcorderIntent);
3108 }
3109
3110 if (extraInitialIntents.size() > 0) {
3111 Intent[] extraIntents = new Intent[extraInitialIntents.size()];
3112 chooser.putExtra(Intent.EXTRA_INITIAL_INTENTS, extraInitialIntents.toArray(extraIntents));
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003113 }
3114
3115 chooser.putExtra(Intent.EXTRA_TITLE, getString(R.string.choose_upload));
3116 BrowserActivity.this.startActivityForResult(chooser, FILE_SELECTED);
Grace Kloba22ac16e2009-10-07 18:00:23 -07003117 }
3118
3119 // -------------------------------------------------------------------------
3120 // Implement functions for DownloadListener
3121 // -------------------------------------------------------------------------
3122
The Android Open Source Project0c908882009-03-03 19:32:16 -08003123 /**
3124 * Notify the host application a download should be done, or that
3125 * the data should be streamed if a streaming viewer is available.
3126 * @param url The full url to the content that should be downloaded
3127 * @param contentDisposition Content-disposition http header, if
3128 * present.
3129 * @param mimetype The mimetype of the content reported by the server
3130 * @param contentLength The file size reported by the server
3131 */
3132 public void onDownloadStart(String url, String userAgent,
3133 String contentDisposition, String mimetype, long contentLength) {
3134 // if we're dealing wih A/V content that's not explicitly marked
3135 // for download, check if it's streamable.
3136 if (contentDisposition == null
Patrick Scotte1fb9662009-08-31 14:31:52 -04003137 || !contentDisposition.regionMatches(
3138 true, 0, "attachment", 0, 10)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003139 // query the package manager to see if there's a registered handler
3140 // that matches.
3141 Intent intent = new Intent(Intent.ACTION_VIEW);
3142 intent.setDataAndType(Uri.parse(url), mimetype);
Patrick Scotte1fb9662009-08-31 14:31:52 -04003143 ResolveInfo info = getPackageManager().resolveActivity(intent,
3144 PackageManager.MATCH_DEFAULT_ONLY);
3145 if (info != null) {
3146 ComponentName myName = getComponentName();
3147 // If we resolved to ourselves, we don't want to attempt to
3148 // load the url only to try and download it again.
3149 if (!myName.getPackageName().equals(
3150 info.activityInfo.packageName)
3151 || !myName.getClassName().equals(
3152 info.activityInfo.name)) {
3153 // someone (other than us) knows how to handle this mime
3154 // type with this scheme, don't download.
3155 try {
3156 startActivity(intent);
3157 return;
3158 } catch (ActivityNotFoundException ex) {
3159 if (LOGD_ENABLED) {
3160 Log.d(LOGTAG, "activity not found for " + mimetype
3161 + " over " + Uri.parse(url).getScheme(),
3162 ex);
3163 }
3164 // Best behavior is to fall back to a download in this
3165 // case
The Android Open Source Project0c908882009-03-03 19:32:16 -08003166 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003167 }
3168 }
3169 }
3170 onDownloadStartNoStream(url, userAgent, contentDisposition, mimetype, contentLength);
3171 }
3172
Kristian Monsenfa52d172010-03-25 18:29:21 +00003173 // This is to work around the fact that java.net.URI throws Exceptions
3174 // instead of just encoding URL's properly
3175 // Helper method for onDownloadStartNoStream
3176 private static String encodePath(String path) {
3177 char[] chars = path.toCharArray();
3178
3179 boolean needed = false;
3180 for (char c : chars) {
3181 if (c == '[' || c == ']') {
3182 needed = true;
3183 break;
3184 }
3185 }
3186 if (needed == false) {
3187 return path;
3188 }
3189
3190 StringBuilder sb = new StringBuilder("");
3191 for (char c : chars) {
3192 if (c == '[' || c == ']') {
3193 sb.append('%');
3194 sb.append(Integer.toHexString(c));
3195 } else {
3196 sb.append(c);
3197 }
3198 }
3199
3200 return sb.toString();
3201 }
3202
The Android Open Source Project0c908882009-03-03 19:32:16 -08003203 /**
3204 * Notify the host application a download should be done, even if there
3205 * is a streaming viewer available for thise type.
3206 * @param url The full url to the content that should be downloaded
3207 * @param contentDisposition Content-disposition http header, if
3208 * present.
3209 * @param mimetype The mimetype of the content reported by the server
3210 * @param contentLength The file size reported by the server
3211 */
3212 /*package */ void onDownloadStartNoStream(String url, String userAgent,
3213 String contentDisposition, String mimetype, long contentLength) {
3214
3215 String filename = URLUtil.guessFileName(url,
3216 contentDisposition, mimetype);
3217
3218 // Check to see if we have an SDCard
3219 String status = Environment.getExternalStorageState();
3220 if (!status.equals(Environment.MEDIA_MOUNTED)) {
3221 int title;
3222 String msg;
3223
3224 // Check to see if the SDCard is busy, same as the music app
3225 if (status.equals(Environment.MEDIA_SHARED)) {
3226 msg = getString(R.string.download_sdcard_busy_dlg_msg);
3227 title = R.string.download_sdcard_busy_dlg_title;
3228 } else {
3229 msg = getString(R.string.download_no_sdcard_dlg_msg, filename);
3230 title = R.string.download_no_sdcard_dlg_title;
3231 }
3232
3233 new AlertDialog.Builder(this)
3234 .setTitle(title)
3235 .setIcon(android.R.drawable.ic_dialog_alert)
3236 .setMessage(msg)
3237 .setPositiveButton(R.string.ok, null)
3238 .show();
3239 return;
3240 }
3241
Kristian Monsenfa52d172010-03-25 18:29:21 +00003242 // java.net.URI is a lot stricter than KURL so we have to encode some
3243 // extra characters. Fix for b 2538060 and b 1634719
3244 WebAddress webAddress;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003245 try {
Kristian Monsenfa52d172010-03-25 18:29:21 +00003246 webAddress = new WebAddress(url);
3247 webAddress.mPath = encodePath(webAddress.mPath);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003248 } catch (Exception e) {
Kristian Monsenfa52d172010-03-25 18:29:21 +00003249 // This only happens for very bad urls, we want to chatch the
3250 // exception here
3251 Log.e(LOGTAG, "Exception trying to parse url:" + url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003252 return;
3253 }
3254
3255 // XXX: Have to use the old url since the cookies were stored using the
3256 // old percent-encoded url.
3257 String cookies = CookieManager.getInstance().getCookie(url);
3258
3259 ContentValues values = new ContentValues();
Kristian Monsenfa52d172010-03-25 18:29:21 +00003260 values.put(Downloads.Impl.COLUMN_URI, webAddress.toString());
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08003261 values.put(Downloads.Impl.COLUMN_COOKIE_DATA, cookies);
3262 values.put(Downloads.Impl.COLUMN_USER_AGENT, userAgent);
3263 values.put(Downloads.Impl.COLUMN_NOTIFICATION_PACKAGE,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003264 getPackageName());
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08003265 values.put(Downloads.Impl.COLUMN_NOTIFICATION_CLASS,
Leon Scrogginsa563d092010-04-19 16:53:49 -04003266 OpenDownloadReceiver.class.getCanonicalName());
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08003267 values.put(Downloads.Impl.COLUMN_VISIBILITY,
3268 Downloads.Impl.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
3269 values.put(Downloads.Impl.COLUMN_MIME_TYPE, mimetype);
3270 values.put(Downloads.Impl.COLUMN_FILE_NAME_HINT, filename);
Kristian Monsenfa52d172010-03-25 18:29:21 +00003271 values.put(Downloads.Impl.COLUMN_DESCRIPTION, webAddress.mHost);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003272 if (contentLength > 0) {
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08003273 values.put(Downloads.Impl.COLUMN_TOTAL_BYTES, contentLength);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003274 }
3275 if (mimetype == null) {
3276 // We must have long pressed on a link or image to download it. We
3277 // are not sure of the mimetype in this case, so do a head request
3278 new FetchUrlMimeType(this).execute(values);
3279 } else {
3280 final Uri contentUri =
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08003281 getContentResolver().insert(Downloads.Impl.CONTENT_URI, values);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003282 }
Leon Scroggins9191a7f2010-03-18 14:44:44 -04003283 Toast.makeText(this, R.string.download_pending, Toast.LENGTH_SHORT)
3284 .show();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003285 }
3286
Grace Kloba22ac16e2009-10-07 18:00:23 -07003287 // -------------------------------------------------------------------------
3288
The Android Open Source Project0c908882009-03-03 19:32:16 -08003289 /**
3290 * Resets the lock icon. This method is called when we start a new load and
3291 * know the url to be loaded.
3292 */
3293 private void resetLockIcon(String url) {
3294 // Save the lock-icon state (we revert to it if the load gets cancelled)
Grace Kloba22ac16e2009-10-07 18:00:23 -07003295 mTabControl.getCurrentTab().resetLockIcon(url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003296 updateLockIconImage(LOCK_ICON_UNSECURE);
3297 }
3298
The Android Open Source Project0c908882009-03-03 19:32:16 -08003299 /**
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04003300 * Update the lock icon to correspond to our latest state.
3301 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003302 private void updateLockIconToLatest() {
Leon Scroggins91f65fc2010-06-29 13:52:39 -04003303 Tab t = mTabControl.getCurrentTab();
3304 if (t != null) {
3305 updateLockIconImage(t.getLockIconType());
3306 }
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04003307 }
3308
3309 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08003310 * Updates the lock-icon image in the title-bar.
3311 */
3312 private void updateLockIconImage(int lockIconType) {
3313 Drawable d = null;
3314 if (lockIconType == LOCK_ICON_SECURE) {
3315 d = mSecLockIcon;
3316 } else if (lockIconType == LOCK_ICON_MIXED) {
3317 d = mMixLockIcon;
3318 }
Leon Scroggins68579392009-09-15 15:31:54 -04003319 mTitleBar.setLock(d);
Michael Kolba2b2ba82010-08-04 17:54:03 -07003320 mFakeTitleBar.setLock(d);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003321 }
3322
3323 /**
3324 * Displays a page-info dialog.
3325 * @param tab The tab to show info about
3326 * @param fromShowSSLCertificateOnError The flag that indicates whether
3327 * this dialog was opened from the SSL-certificate-on-error dialog or
3328 * not. This is important, since we need to know whether to return to
3329 * the parent dialog or simply dismiss.
3330 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003331 private void showPageInfo(final Tab tab,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003332 final boolean fromShowSSLCertificateOnError) {
3333 final LayoutInflater factory = LayoutInflater
3334 .from(this);
3335
3336 final View pageInfoView = factory.inflate(R.layout.page_info, null);
3337
3338 final WebView view = tab.getWebView();
3339
3340 String url = null;
3341 String title = null;
3342
3343 if (view == null) {
3344 url = tab.getUrl();
3345 title = tab.getTitle();
3346 } else if (view == mTabControl.getCurrentWebView()) {
3347 // Use the cached title and url if this is the current WebView
3348 url = mUrl;
3349 title = mTitle;
3350 } else {
3351 url = view.getUrl();
3352 title = view.getTitle();
3353 }
3354
3355 if (url == null) {
3356 url = "";
3357 }
3358 if (title == null) {
3359 title = "";
3360 }
3361
3362 ((TextView) pageInfoView.findViewById(R.id.address)).setText(url);
3363 ((TextView) pageInfoView.findViewById(R.id.title)).setText(title);
3364
3365 mPageInfoView = tab;
Leon Scrogginsc7b92f82010-01-11 18:17:31 -05003366 mPageInfoFromShowSSLCertificateOnError = fromShowSSLCertificateOnError;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003367
3368 AlertDialog.Builder alertDialogBuilder =
3369 new AlertDialog.Builder(this)
3370 .setTitle(R.string.page_info).setIcon(android.R.drawable.ic_dialog_info)
3371 .setView(pageInfoView)
3372 .setPositiveButton(
3373 R.string.ok,
3374 new DialogInterface.OnClickListener() {
3375 public void onClick(DialogInterface dialog,
3376 int whichButton) {
3377 mPageInfoDialog = null;
3378 mPageInfoView = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003379
3380 // if we came here from the SSL error dialog
3381 if (fromShowSSLCertificateOnError) {
3382 // go back to the SSL error dialog
3383 showSSLCertificateOnError(
3384 mSSLCertificateOnErrorView,
3385 mSSLCertificateOnErrorHandler,
3386 mSSLCertificateOnErrorError);
3387 }
3388 }
3389 })
3390 .setOnCancelListener(
3391 new DialogInterface.OnCancelListener() {
3392 public void onCancel(DialogInterface dialog) {
3393 mPageInfoDialog = null;
3394 mPageInfoView = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003395
3396 // if we came here from the SSL error dialog
3397 if (fromShowSSLCertificateOnError) {
3398 // go back to the SSL error dialog
3399 showSSLCertificateOnError(
3400 mSSLCertificateOnErrorView,
3401 mSSLCertificateOnErrorHandler,
3402 mSSLCertificateOnErrorError);
3403 }
3404 }
3405 });
3406
3407 // if we have a main top-level page SSL certificate set or a certificate
3408 // error
3409 if (fromShowSSLCertificateOnError ||
3410 (view != null && view.getCertificate() != null)) {
3411 // add a 'View Certificate' button
3412 alertDialogBuilder.setNeutralButton(
3413 R.string.view_certificate,
3414 new DialogInterface.OnClickListener() {
3415 public void onClick(DialogInterface dialog,
3416 int whichButton) {
3417 mPageInfoDialog = null;
3418 mPageInfoView = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003419
3420 // if we came here from the SSL error dialog
3421 if (fromShowSSLCertificateOnError) {
3422 // go back to the SSL error dialog
3423 showSSLCertificateOnError(
3424 mSSLCertificateOnErrorView,
3425 mSSLCertificateOnErrorHandler,
3426 mSSLCertificateOnErrorError);
3427 } else {
3428 // otherwise, display the top-most certificate from
3429 // the chain
3430 if (view.getCertificate() != null) {
3431 showSSLCertificate(tab);
3432 }
3433 }
3434 }
3435 });
3436 }
3437
3438 mPageInfoDialog = alertDialogBuilder.show();
3439 }
3440
3441 /**
3442 * Displays the main top-level page SSL certificate dialog
3443 * (accessible from the Page-Info dialog).
3444 * @param tab The tab to show certificate for.
3445 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003446 private void showSSLCertificate(final Tab tab) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003447 final View certificateView =
3448 inflateCertificateView(tab.getWebView().getCertificate());
3449 if (certificateView == null) {
3450 return;
3451 }
3452
3453 LayoutInflater factory = LayoutInflater.from(this);
3454
3455 final LinearLayout placeholder =
3456 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3457
3458 LinearLayout ll = (LinearLayout) factory.inflate(
3459 R.layout.ssl_success, placeholder);
3460 ((TextView)ll.findViewById(R.id.success))
3461 .setText(R.string.ssl_certificate_is_valid);
3462
3463 mSSLCertificateView = tab;
3464 mSSLCertificateDialog =
3465 new AlertDialog.Builder(this)
3466 .setTitle(R.string.ssl_certificate).setIcon(
3467 R.drawable.ic_dialog_browser_certificate_secure)
3468 .setView(certificateView)
3469 .setPositiveButton(R.string.ok,
3470 new DialogInterface.OnClickListener() {
3471 public void onClick(DialogInterface dialog,
3472 int whichButton) {
3473 mSSLCertificateDialog = null;
3474 mSSLCertificateView = null;
3475
3476 showPageInfo(tab, false);
3477 }
3478 })
3479 .setOnCancelListener(
3480 new DialogInterface.OnCancelListener() {
3481 public void onCancel(DialogInterface dialog) {
3482 mSSLCertificateDialog = null;
3483 mSSLCertificateView = null;
3484
3485 showPageInfo(tab, false);
3486 }
3487 })
3488 .show();
3489 }
3490
3491 /**
3492 * Displays the SSL error certificate dialog.
3493 * @param view The target web-view.
3494 * @param handler The SSL error handler responsible for cancelling the
3495 * connection that resulted in an SSL error or proceeding per user request.
3496 * @param error The SSL error object.
3497 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003498 void showSSLCertificateOnError(
The Android Open Source Project0c908882009-03-03 19:32:16 -08003499 final WebView view, final SslErrorHandler handler, final SslError error) {
3500
3501 final View certificateView =
3502 inflateCertificateView(error.getCertificate());
3503 if (certificateView == null) {
3504 return;
3505 }
3506
3507 LayoutInflater factory = LayoutInflater.from(this);
3508
3509 final LinearLayout placeholder =
3510 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3511
3512 if (error.hasError(SslError.SSL_UNTRUSTED)) {
3513 LinearLayout ll = (LinearLayout)factory
3514 .inflate(R.layout.ssl_warning, placeholder);
3515 ((TextView)ll.findViewById(R.id.warning))
3516 .setText(R.string.ssl_untrusted);
3517 }
3518
3519 if (error.hasError(SslError.SSL_IDMISMATCH)) {
3520 LinearLayout ll = (LinearLayout)factory
3521 .inflate(R.layout.ssl_warning, placeholder);
3522 ((TextView)ll.findViewById(R.id.warning))
3523 .setText(R.string.ssl_mismatch);
3524 }
3525
3526 if (error.hasError(SslError.SSL_EXPIRED)) {
3527 LinearLayout ll = (LinearLayout)factory
3528 .inflate(R.layout.ssl_warning, placeholder);
3529 ((TextView)ll.findViewById(R.id.warning))
3530 .setText(R.string.ssl_expired);
3531 }
3532
3533 if (error.hasError(SslError.SSL_NOTYETVALID)) {
3534 LinearLayout ll = (LinearLayout)factory
3535 .inflate(R.layout.ssl_warning, placeholder);
3536 ((TextView)ll.findViewById(R.id.warning))
3537 .setText(R.string.ssl_not_yet_valid);
3538 }
3539
3540 mSSLCertificateOnErrorHandler = handler;
3541 mSSLCertificateOnErrorView = view;
3542 mSSLCertificateOnErrorError = error;
3543 mSSLCertificateOnErrorDialog =
3544 new AlertDialog.Builder(this)
3545 .setTitle(R.string.ssl_certificate).setIcon(
3546 R.drawable.ic_dialog_browser_certificate_partially_secure)
3547 .setView(certificateView)
3548 .setPositiveButton(R.string.ok,
3549 new DialogInterface.OnClickListener() {
3550 public void onClick(DialogInterface dialog,
3551 int whichButton) {
3552 mSSLCertificateOnErrorDialog = null;
3553 mSSLCertificateOnErrorView = null;
3554 mSSLCertificateOnErrorHandler = null;
3555 mSSLCertificateOnErrorError = null;
3556
Grace Kloba22ac16e2009-10-07 18:00:23 -07003557 view.getWebViewClient().onReceivedSslError(
3558 view, handler, error);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003559 }
3560 })
3561 .setNeutralButton(R.string.page_info_view,
3562 new DialogInterface.OnClickListener() {
3563 public void onClick(DialogInterface dialog,
3564 int whichButton) {
3565 mSSLCertificateOnErrorDialog = null;
3566
3567 // do not clear the dialog state: we will
3568 // need to show the dialog again once the
3569 // user is done exploring the page-info details
3570
3571 showPageInfo(mTabControl.getTabFromView(view),
3572 true);
3573 }
3574 })
3575 .setOnCancelListener(
3576 new DialogInterface.OnCancelListener() {
3577 public void onCancel(DialogInterface dialog) {
3578 mSSLCertificateOnErrorDialog = null;
3579 mSSLCertificateOnErrorView = null;
3580 mSSLCertificateOnErrorHandler = null;
3581 mSSLCertificateOnErrorError = null;
3582
Grace Kloba22ac16e2009-10-07 18:00:23 -07003583 view.getWebViewClient().onReceivedSslError(
3584 view, handler, error);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003585 }
3586 })
3587 .show();
3588 }
3589
3590 /**
3591 * Inflates the SSL certificate view (helper method).
3592 * @param certificate The SSL certificate.
3593 * @return The resultant certificate view with issued-to, issued-by,
3594 * issued-on, expires-on, and possibly other fields set.
3595 * If the input certificate is null, returns null.
3596 */
3597 private View inflateCertificateView(SslCertificate certificate) {
3598 if (certificate == null) {
3599 return null;
3600 }
3601
3602 LayoutInflater factory = LayoutInflater.from(this);
3603
3604 View certificateView = factory.inflate(
3605 R.layout.ssl_certificate, null);
3606
3607 // issued to:
3608 SslCertificate.DName issuedTo = certificate.getIssuedTo();
3609 if (issuedTo != null) {
3610 ((TextView) certificateView.findViewById(R.id.to_common))
3611 .setText(issuedTo.getCName());
3612 ((TextView) certificateView.findViewById(R.id.to_org))
3613 .setText(issuedTo.getOName());
3614 ((TextView) certificateView.findViewById(R.id.to_org_unit))
3615 .setText(issuedTo.getUName());
3616 }
3617
3618 // issued by:
3619 SslCertificate.DName issuedBy = certificate.getIssuedBy();
3620 if (issuedBy != null) {
3621 ((TextView) certificateView.findViewById(R.id.by_common))
3622 .setText(issuedBy.getCName());
3623 ((TextView) certificateView.findViewById(R.id.by_org))
3624 .setText(issuedBy.getOName());
3625 ((TextView) certificateView.findViewById(R.id.by_org_unit))
3626 .setText(issuedBy.getUName());
3627 }
3628
3629 // issued on:
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003630 String issuedOn = formatCertificateDate(
3631 certificate.getValidNotBeforeDate());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003632 ((TextView) certificateView.findViewById(R.id.issued_on))
3633 .setText(issuedOn);
3634
3635 // expires on:
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003636 String expiresOn = formatCertificateDate(
3637 certificate.getValidNotAfterDate());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003638 ((TextView) certificateView.findViewById(R.id.expires_on))
3639 .setText(expiresOn);
3640
3641 return certificateView;
3642 }
3643
3644 /**
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003645 * Formats the certificate date to a properly localized date string.
The Android Open Source Project0c908882009-03-03 19:32:16 -08003646 * @return Properly localized version of the certificate date string and
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003647 * the "" if it fails to localize.
The Android Open Source Project0c908882009-03-03 19:32:16 -08003648 */
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003649 private String formatCertificateDate(Date certificateDate) {
3650 if (certificateDate == null) {
3651 return "";
The Android Open Source Project0c908882009-03-03 19:32:16 -08003652 }
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003653 String formattedDate = DateFormat.getDateFormat(this).format(certificateDate);
3654 if (formattedDate == null) {
3655 return "";
3656 }
3657 return formattedDate;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003658 }
3659
3660 /**
3661 * Displays an http-authentication dialog.
3662 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003663 void showHttpAuthentication(final HttpAuthHandler handler,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003664 final String host, final String realm, final String title,
3665 final String name, final String password, int focusId) {
3666 LayoutInflater factory = LayoutInflater.from(this);
3667 final View v = factory
3668 .inflate(R.layout.http_authentication, null);
3669 if (name != null) {
3670 ((EditText) v.findViewById(R.id.username_edit)).setText(name);
3671 }
3672 if (password != null) {
3673 ((EditText) v.findViewById(R.id.password_edit)).setText(password);
3674 }
3675
3676 String titleText = title;
3677 if (titleText == null) {
3678 titleText = getText(R.string.sign_in_to).toString().replace(
3679 "%s1", host).replace("%s2", realm);
3680 }
3681
3682 mHttpAuthHandler = handler;
3683 AlertDialog dialog = new AlertDialog.Builder(this)
3684 .setTitle(titleText)
3685 .setIcon(android.R.drawable.ic_dialog_alert)
3686 .setView(v)
3687 .setPositiveButton(R.string.action,
3688 new DialogInterface.OnClickListener() {
3689 public void onClick(DialogInterface dialog,
3690 int whichButton) {
3691 String nm = ((EditText) v
3692 .findViewById(R.id.username_edit))
3693 .getText().toString();
3694 String pw = ((EditText) v
3695 .findViewById(R.id.password_edit))
3696 .getText().toString();
3697 BrowserActivity.this.setHttpAuthUsernamePassword
3698 (host, realm, nm, pw);
3699 handler.proceed(nm, pw);
3700 mHttpAuthenticationDialog = null;
3701 mHttpAuthHandler = null;
3702 }})
3703 .setNegativeButton(R.string.cancel,
3704 new DialogInterface.OnClickListener() {
3705 public void onClick(DialogInterface dialog,
3706 int whichButton) {
3707 handler.cancel();
3708 BrowserActivity.this.resetTitleAndRevertLockIcon();
3709 mHttpAuthenticationDialog = null;
3710 mHttpAuthHandler = null;
3711 }})
3712 .setOnCancelListener(new DialogInterface.OnCancelListener() {
3713 public void onCancel(DialogInterface dialog) {
3714 handler.cancel();
3715 BrowserActivity.this.resetTitleAndRevertLockIcon();
3716 mHttpAuthenticationDialog = null;
3717 mHttpAuthHandler = null;
3718 }})
3719 .create();
3720 // Make the IME appear when the dialog is displayed if applicable.
3721 dialog.getWindow().setSoftInputMode(
3722 WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
3723 dialog.show();
3724 if (focusId != 0) {
3725 dialog.findViewById(focusId).requestFocus();
3726 } else {
3727 v.findViewById(R.id.username_edit).requestFocus();
3728 }
3729 mHttpAuthenticationDialog = dialog;
3730 }
3731
3732 public int getProgress() {
3733 WebView w = mTabControl.getCurrentWebView();
3734 if (w != null) {
3735 return w.getProgress();
3736 } else {
3737 return 100;
3738 }
3739 }
3740
3741 /**
3742 * Set HTTP authentication password.
3743 *
3744 * @param host The host for the password
3745 * @param realm The realm for the password
3746 * @param username The username for the password. If it is null, it means
3747 * password can't be saved.
3748 * @param password The password
3749 */
3750 public void setHttpAuthUsernamePassword(String host, String realm,
3751 String username,
3752 String password) {
Steve Block95a53b22010-03-25 17:24:58 +00003753 WebView w = getTopWindow();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003754 if (w != null) {
3755 w.setHttpAuthUsernamePassword(host, realm, username, password);
3756 }
3757 }
3758
3759 /**
3760 * connectivity manager says net has come or gone... inform the user
3761 * @param up true if net has come up, false if net has gone down
3762 */
3763 public void onNetworkToggle(boolean up) {
3764 if (up == mIsNetworkUp) {
3765 return;
3766 } else if (up) {
3767 mIsNetworkUp = true;
3768 if (mAlertDialog != null) {
3769 mAlertDialog.cancel();
3770 mAlertDialog = null;
3771 }
3772 } else {
3773 mIsNetworkUp = false;
Patrick Scotteb6ab2a2009-09-16 10:00:17 -04003774 if (mInLoad) {
3775 createAndShowNetworkDialog();
3776 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003777 }
3778 WebView w = mTabControl.getCurrentWebView();
3779 if (w != null) {
3780 w.setNetworkAvailable(up);
3781 }
3782 }
3783
Grace Kloba22ac16e2009-10-07 18:00:23 -07003784 boolean isNetworkUp() {
3785 return mIsNetworkUp;
3786 }
3787
Patrick Scotteb6ab2a2009-09-16 10:00:17 -04003788 // This method shows the network dialog alerting the user that the net is
3789 // down. It will only show the dialog if mAlertDialog is null.
3790 private void createAndShowNetworkDialog() {
3791 if (mAlertDialog == null) {
3792 mAlertDialog = new AlertDialog.Builder(this)
3793 .setTitle(R.string.loadSuspendedTitle)
3794 .setMessage(R.string.loadSuspended)
3795 .setPositiveButton(R.string.ok, null)
3796 .show();
3797 }
3798 }
3799
The Android Open Source Project0c908882009-03-03 19:32:16 -08003800 @Override
3801 protected void onActivityResult(int requestCode, int resultCode,
3802 Intent intent) {
Grace Klobabb394f32009-11-19 10:26:37 -08003803 if (getTopWindow() == null) return;
3804
The Android Open Source Project0c908882009-03-03 19:32:16 -08003805 switch (requestCode) {
3806 case COMBO_PAGE:
3807 if (resultCode == RESULT_OK && intent != null) {
3808 String data = intent.getAction();
3809 Bundle extras = intent.getExtras();
3810 if (extras != null && extras.getBoolean("new_window", false)) {
Michael Kolb68792c82010-08-09 16:39:18 -07003811 openTab(data, false);
3812 } else if ((extras != null) &&
3813 extras.getBoolean(CombinedBookmarkHistoryActivity.NEWTAB_MODE)) {
3814 openTab(data, true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003815 } else {
Michael Kolb68792c82010-08-09 16:39:18 -07003816 final Tab currentTab = mTabControl.getCurrentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04003817 dismissSubWindow(currentTab);
3818 if (data != null && data.length() != 0) {
Leon Scroggins92472e82010-02-17 16:32:28 -05003819 loadUrl(getTopWindow(), data);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003820 }
3821 }
Michael Kolb3f65c382010-08-20 15:31:16 -07003822 } else if (resultCode == RESULT_CANCELED) {
3823 if (intent != null) {
3824 float evtx = intent.getFloatExtra(CombinedBookmarkHistoryActivity.EVT_X, -1);
3825 float evty = intent.getFloatExtra(CombinedBookmarkHistoryActivity.EVT_Y, -1);
3826 long now = System.currentTimeMillis();
3827 MotionEvent evt = MotionEvent.obtain(now, now,
3828 MotionEvent.ACTION_DOWN, evtx, evty, 0);
3829 dispatchTouchEvent(evt);
3830 MotionEvent up = MotionEvent.obtain(evt);
3831 up.setAction(MotionEvent.ACTION_UP);
3832 dispatchTouchEvent(up);
3833 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003834 }
Leon Scrogginsfde97462010-01-11 13:06:21 -05003835 // Deliberately fall through to PREFERENCES_PAGE, since the
3836 // same extra may be attached to the COMBO_PAGE
3837 case PREFERENCES_PAGE:
3838 if (resultCode == RESULT_OK && intent != null) {
3839 String action = intent.getStringExtra(Intent.EXTRA_TEXT);
3840 if (BrowserSettings.PREF_CLEAR_HISTORY.equals(action)) {
3841 mTabControl.removeParentChildRelationShips();
3842 }
3843 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003844 break;
Leon Scroggins8d5fa432009-10-02 15:55:59 -04003845 // Choose a file from the file picker.
3846 case FILE_SELECTED:
3847 if (null == mUploadMessage) break;
3848 Uri result = intent == null || resultCode != RESULT_OK ? null
3849 : intent.getData();
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003850
3851 // As we ask the camera to save the result of the user taking
3852 // a picture, the camera application does not return anything other
3853 // than RESULT_OK. So we need to check whether the file we expected
3854 // was written to disk in the in the case that we
3855 // did not get an intent returned but did get a RESULT_OK. If it was,
3856 // we assume that this result has came back from the camera.
3857 if (result == null && intent == null && resultCode == RESULT_OK) {
3858 File cameraFile = new File(mCameraFilePath);
3859 if (cameraFile.exists()) {
3860 result = Uri.fromFile(cameraFile);
Ben Murdoch07d34732010-05-27 18:34:46 +01003861 // Broadcast to the media scanner that we have a new photo
3862 // so it will be added into the gallery for the user.
3863 sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, result));
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003864 }
3865 }
Leon Scroggins8d5fa432009-10-02 15:55:59 -04003866 mUploadMessage.onReceiveValue(result);
3867 mUploadMessage = null;
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003868 mCameraFilePath = null;
Leon Scroggins8d5fa432009-10-02 15:55:59 -04003869 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003870 default:
3871 break;
3872 }
Leon Scroggins30444232009-09-04 18:36:20 -04003873 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003874 }
3875
3876 /*
3877 * This method is called as a result of the user selecting the options
Leon Scrogginsf08809b2010-01-21 09:27:46 -05003878 * menu to see the download window. It shows the download window on top of
3879 * the current window.
The Android Open Source Project0c908882009-03-03 19:32:16 -08003880 */
Leon Scrogginsf08809b2010-01-21 09:27:46 -05003881 private void viewDownloads(Uri downloadRecord) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003882 Intent intent = new Intent(this,
3883 BrowserDownloadPage.class);
3884 intent.setData(downloadRecord);
Grace Kloba22ac16e2009-10-07 18:00:23 -07003885 startActivityForResult(intent, BrowserActivity.DOWNLOAD_PAGE);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003886
3887 }
3888
Ben Murdocheecb4e62010-07-06 16:30:38 +01003889 /* package*/ void promptAddOrInstallBookmark() {
3890 final Tab current = mTabControl.getCurrentTab();
3891 Resources resources = getResources();
3892 CharSequence[] choices = {
3893 resources.getString(R.string.save_to_bookmarks),
3894 resources.getString(R.string.create_shortcut_bookmark)
3895 };
3896
3897 AlertDialog.Builder builder = new AlertDialog.Builder(this);
3898 builder.setTitle(R.string.add_new_bookmark);
3899 builder.setItems(choices, new DialogInterface.OnClickListener() {
3900 public void onClick(DialogInterface dialog, int item) {
3901 if (item == 0) {
3902 bookmarkCurrentPage();
3903 } else if (item == 1) {
3904 current.populatePickerData();
3905 String touchIconUrl = mTabControl.getCurrentWebView().getTouchIconUrl();
3906 if (touchIconUrl != null) {
3907 // Download the touch icon for this site then save it to the
3908 // homescreen.
3909 Bundle b = new Bundle();
3910 b.putString("url", current.getUrl());
3911 b.putString("title", current.getTitle());
3912 b.putParcelable("favicon", current.getFavicon());
3913 Message msg = mHandler.obtainMessage(TOUCH_ICON_DOWNLOADED);
3914 msg.setData(b);
Ben Murdochccb5de02010-07-19 18:38:17 +01003915 new DownloadTouchIcon(BrowserActivity.this, msg,
Ben Murdocheecb4e62010-07-06 16:30:38 +01003916 mTabControl.getCurrentWebView().getSettings()
3917 .getUserAgentString()).execute(touchIconUrl);
3918 } else {
3919 // add to homescreen, can do it immediately as there is no touch
3920 // icon.
3921 showSaveToHomescreenDialog(current.getUrl(), current.getTitle(),
3922 null, current.getFavicon());
3923 }
3924 }
3925 }
3926 });
3927 builder.create().show();
3928 }
3929
Leon Scroggins160a7e72009-08-14 18:28:01 -04003930 /**
3931 * Open the Go page.
3932 * @param startWithHistory If true, open starting on the history tab.
3933 * Otherwise, start with the bookmarks tab.
Leon Scroggins160a7e72009-08-14 18:28:01 -04003934 */
Michael Kolb68792c82010-08-09 16:39:18 -07003935 /* package */ void bookmarksOrHistoryPicker(boolean startWithHistory, boolean newTabMode) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003936 WebView current = mTabControl.getCurrentWebView();
3937 if (current == null) {
3938 return;
3939 }
3940 Intent intent = new Intent(this,
3941 CombinedBookmarkHistoryActivity.class);
3942 String title = current.getTitle();
3943 String url = current.getUrl();
Ben Murdoch87cc65d2010-06-29 20:34:10 +01003944 Bitmap thumbnail = createScreenshot(current, getDesiredThumbnailWidth(this),
3945 getDesiredThumbnailHeight(this));
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01003946
The Android Open Source Project0c908882009-03-03 19:32:16 -08003947 // Just in case the user opens bookmarks before a page finishes loading
3948 // so the current history item, and therefore the page, is null.
3949 if (null == url) {
3950 url = mLastEnteredUrl;
3951 // This can happen.
3952 if (null == url) {
3953 url = mSettings.getHomePage();
3954 }
3955 }
3956 // In case the web page has not yet received its associated title.
3957 if (title == null) {
3958 title = url;
3959 }
3960 intent.putExtra("title", title);
3961 intent.putExtra("url", url);
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01003962 intent.putExtra("thumbnail", thumbnail);
Leon Scroggins30444232009-09-04 18:36:20 -04003963 // Disable opening in a new window if we have maxed out the windows
Grace Kloba22ac16e2009-10-07 18:00:23 -07003964 intent.putExtra("disable_new_window", !mTabControl.canCreateNewTab());
Patrick Scott3918d442009-08-04 13:22:29 -04003965 intent.putExtra("touch_icon_url", current.getTouchIconUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003966 if (startWithHistory) {
Jeff Hamilton64144e42010-08-18 16:31:59 -05003967 intent.putExtra(CombinedBookmarkHistoryActivity.STARTING_FRAGMENT,
3968 CombinedBookmarkHistoryActivity.FRAGMENT_ID_HISTORY);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003969 }
Michael Kolb0998b0a2010-08-23 17:45:35 -07003970 int top = -1;
3971 int height = -1;
Michael Kolb3f65c382010-08-20 15:31:16 -07003972 if (mXLargeScreenSize) {
3973 showFakeTitleBar();
3974 int titleBarHeight = ((TitleBarXLarge)mFakeTitleBar).getHeightWithoutProgress();
Michael Kolb0998b0a2010-08-23 17:45:35 -07003975 top = mTabBar.getBottom() + titleBarHeight;
3976 height = getTopWindow().getHeight() - titleBarHeight;
Michael Kolb68792c82010-08-09 16:39:18 -07003977 intent.putExtra(CombinedBookmarkHistoryActivity.NEWTAB_MODE, true);
3978 }
Michael Kolb0998b0a2010-08-23 17:45:35 -07003979 intent.putExtra(CombinedBookmarkHistoryActivity.EXTRA_TOP, top);
3980 intent.putExtra(CombinedBookmarkHistoryActivity.EXTRA_HEIGHT, height);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003981 startActivityForResult(intent, COMBO_PAGE);
3982 }
3983
Ben Murdocheecb4e62010-07-06 16:30:38 +01003984 private void showSaveToHomescreenDialog(String url, String title, Bitmap touchIcon,
3985 Bitmap favicon) {
3986 Intent intent = new Intent(this, SaveToHomescreenDialog.class);
3987
3988 // Just in case the user tries to save before a page finishes loading
3989 // so the current history item, and therefore the page, is null.
3990 if (null == url) {
3991 url = mLastEnteredUrl;
3992 // This can happen.
3993 if (null == url) {
3994 url = mSettings.getHomePage();
3995 }
3996 }
3997
3998 // In case the web page has not yet received its associated title.
3999 if (title == null) {
4000 title = url;
4001 }
4002
4003 intent.putExtra("title", title);
4004 intent.putExtra("url", url);
4005 intent.putExtra("favicon", favicon);
4006 intent.putExtra("touchIcon", touchIcon);
4007 startActivity(intent);
4008 }
4009
4010
The Android Open Source Project0c908882009-03-03 19:32:16 -08004011 // Called when loading from context menu or LOAD_URL message
Leon Scroggins92472e82010-02-17 16:32:28 -05004012 private void loadUrlFromContext(WebView view, String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08004013 // In case the user enters nothing.
4014 if (url != null && url.length() != 0 && view != null) {
4015 url = smartUrlFilter(url);
Grace Kloba22ac16e2009-10-07 18:00:23 -07004016 if (!view.getWebViewClient().shouldOverrideUrlLoading(view, url)) {
Leon Scroggins92472e82010-02-17 16:32:28 -05004017 loadUrl(view, url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004018 }
4019 }
4020 }
4021
Leon Scroggins92472e82010-02-17 16:32:28 -05004022 /**
4023 * Load the URL into the given WebView and update the title bar
4024 * to reflect the new load. Call this instead of WebView.loadUrl
4025 * directly.
4026 * @param view The WebView used to load url.
4027 * @param url The URL to load.
4028 */
4029 private void loadUrl(WebView view, String url) {
4030 updateTitleBarForNewLoad(view, url);
4031 view.loadUrl(url);
4032 }
4033
4034 /**
4035 * Load UrlData into a Tab and update the title bar to reflect the new
4036 * load. Call this instead of UrlData.loadIn directly.
4037 * @param t The Tab used to load.
4038 * @param data The UrlData being loaded.
4039 */
4040 private void loadUrlDataIn(Tab t, UrlData data) {
4041 updateTitleBarForNewLoad(t.getWebView(), data.mUrl);
4042 data.loadIn(t);
4043 }
4044
4045 /**
4046 * If the WebView is the top window, update the title bar to reflect
4047 * loading the new URL. i.e. set its text, clear the favicon (which
4048 * will be set once the page begins loading), and set the progress to
4049 * INITIAL_PROGRESS to show that the page has begun to load. Called
4050 * by loadUrl and loadUrlDataIn.
4051 * @param view The WebView that is starting a load.
4052 * @param url The URL that is being loaded.
4053 */
4054 private void updateTitleBarForNewLoad(WebView view, String url) {
4055 if (view == getTopWindow()) {
4056 setUrlTitle(url, null);
4057 setFavicon(null);
4058 onProgressChanged(view, INITIAL_PROGRESS);
4059 }
4060 }
4061
The Android Open Source Project0c908882009-03-03 19:32:16 -08004062 private String smartUrlFilter(Uri inUri) {
4063 if (inUri != null) {
4064 return smartUrlFilter(inUri.toString());
4065 }
4066 return null;
4067 }
4068
Feng Qianb34f87a2009-03-24 21:27:26 -07004069 protected static final Pattern ACCEPTED_URI_SCHEMA = Pattern.compile(
The Android Open Source Project0c908882009-03-03 19:32:16 -08004070 "(?i)" + // switch on case insensitive matching
4071 "(" + // begin group for schema
4072 "(?:http|https|file):\\/\\/" +
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004073 "|(?:inline|data|about|content|javascript):" +
The Android Open Source Project0c908882009-03-03 19:32:16 -08004074 ")" +
4075 "(.*)" );
4076
4077 /**
4078 * Attempts to determine whether user input is a URL or search
4079 * terms. Anything with a space is passed to search.
4080 *
4081 * Converts to lowercase any mistakenly uppercased schema (i.e.,
4082 * "Http://" converts to "http://"
4083 *
4084 * @return Original or modified URL
4085 *
4086 */
4087 String smartUrlFilter(String url) {
4088
4089 String inUrl = url.trim();
4090 boolean hasSpace = inUrl.indexOf(' ') != -1;
4091
4092 Matcher matcher = ACCEPTED_URI_SCHEMA.matcher(inUrl);
4093 if (matcher.matches()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08004094 // force scheme to lowercase
4095 String scheme = matcher.group(1);
4096 String lcScheme = scheme.toLowerCase();
4097 if (!lcScheme.equals(scheme)) {
Mitsuru Oshima123ecfb2009-05-18 19:11:14 -07004098 inUrl = lcScheme + matcher.group(2);
4099 }
4100 if (hasSpace) {
4101 inUrl = inUrl.replace(" ", "%20");
The Android Open Source Project0c908882009-03-03 19:32:16 -08004102 }
4103 return inUrl;
4104 }
4105 if (hasSpace) {
Satish Sampath565505b2009-05-29 15:37:27 +01004106 // FIXME: Is this the correct place to add to searches?
4107 // what if someone else calls this function?
4108 int shortcut = parseUrlShortcut(inUrl);
4109 if (shortcut != SHORTCUT_INVALID) {
4110 Browser.addSearchUrl(mResolver, inUrl);
4111 String query = inUrl.substring(2);
4112 switch (shortcut) {
4113 case SHORTCUT_GOOGLE_SEARCH:
Grace Kloba47fdfdb2009-06-30 11:15:34 -07004114 return URLUtil.composeSearchUrl(query, QuickSearch_G, QUERY_PLACE_HOLDER);
Satish Sampath565505b2009-05-29 15:37:27 +01004115 case SHORTCUT_WIKIPEDIA_SEARCH:
4116 return URLUtil.composeSearchUrl(query, QuickSearch_W, QUERY_PLACE_HOLDER);
4117 case SHORTCUT_DICTIONARY_SEARCH:
4118 return URLUtil.composeSearchUrl(query, QuickSearch_D, QUERY_PLACE_HOLDER);
4119 case SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH:
The Android Open Source Project0c908882009-03-03 19:32:16 -08004120 // FIXME: we need location in this case
Satish Sampath565505b2009-05-29 15:37:27 +01004121 return URLUtil.composeSearchUrl(query, QuickSearch_L, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004122 }
4123 }
4124 } else {
Dan Egnor5ee906c2009-11-18 12:11:49 -08004125 if (Patterns.WEB_URL.matcher(inUrl).matches()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08004126 return URLUtil.guessUrl(inUrl);
4127 }
4128 }
4129
4130 Browser.addSearchUrl(mResolver, inUrl);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07004131 return URLUtil.composeSearchUrl(inUrl, QuickSearch_G, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004132 }
4133
Ben Murdochbff2d602009-07-01 20:19:05 +01004134 /* package */ void setShouldShowErrorConsole(boolean flag) {
4135 if (flag == mShouldShowErrorConsole) {
4136 // Nothing to do.
4137 return;
4138 }
4139
4140 mShouldShowErrorConsole = flag;
4141
Grace Kloba22ac16e2009-10-07 18:00:23 -07004142 ErrorConsoleView errorConsole = mTabControl.getCurrentTab()
4143 .getErrorConsole(true);
Ben Murdochbff2d602009-07-01 20:19:05 +01004144
4145 if (flag) {
4146 // Setting the show state of the console will cause it's the layout to be inflated.
4147 if (errorConsole.numberOfErrors() > 0) {
4148 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
4149 } else {
4150 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
4151 }
4152
4153 // Now we can add it to the main view.
4154 mErrorConsoleContainer.addView(errorConsole,
Romain Guy15b8ec62010-01-08 15:06:43 -08004155 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
Ben Murdochbff2d602009-07-01 20:19:05 +01004156 ViewGroup.LayoutParams.WRAP_CONTENT));
4157 } else {
4158 mErrorConsoleContainer.removeView(errorConsole);
4159 }
4160
4161 }
4162
Grace Kloba22ac16e2009-10-07 18:00:23 -07004163 boolean shouldShowErrorConsole() {
4164 return mShouldShowErrorConsole;
4165 }
4166
Andrei Popescu163ab742009-10-20 17:58:23 +01004167 private void setStatusBarVisibility(boolean visible) {
4168 int flag = visible ? 0 : WindowManager.LayoutParams.FLAG_FULLSCREEN;
4169 getWindow().setFlags(flag, WindowManager.LayoutParams.FLAG_FULLSCREEN);
4170 }
4171
Andrei Popescu56199cc2010-01-12 22:39:16 +00004172
4173 private void sendNetworkType(String type, String subtype) {
4174 WebView w = mTabControl.getCurrentWebView();
4175 if (w != null) {
4176 w.setNetworkType(type, subtype);
4177 }
4178 }
4179
Grace Klobaeb6eef42009-09-15 17:56:32 -07004180 final static int LOCK_ICON_UNSECURE = 0;
4181 final static int LOCK_ICON_SECURE = 1;
4182 final static int LOCK_ICON_MIXED = 2;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004183
The Android Open Source Project0c908882009-03-03 19:32:16 -08004184 private BrowserSettings mSettings;
4185 private TabControl mTabControl;
4186 private ContentResolver mResolver;
4187 private FrameLayout mContentView;
Andrei Popescuadc008d2009-06-26 14:11:30 +01004188 private View mCustomView;
4189 private FrameLayout mCustomViewContainer;
Andrei Popescuc9b55562009-07-07 10:51:15 +01004190 private WebChromeClient.CustomViewCallback mCustomViewCallback;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004191
4192 // FIXME, temp address onPrepareMenu performance problem. When we move everything out of
4193 // view, we should rewrite this.
4194 private int mCurrentMenuState = 0;
4195 private int mMenuState = R.id.MAIN_MENU;
Andrei Popescuadc008d2009-06-26 14:11:30 +01004196 private int mOldMenuState = EMPTY_MENU;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004197 private static final int EMPTY_MENU = -1;
4198 private Menu mMenu;
4199
The Android Open Source Project0c908882009-03-03 19:32:16 -08004200 // Used to prevent chording to result in firing two shortcuts immediately
4201 // one after another. Fixes bug 1211714.
4202 boolean mCanChord;
4203
4204 private boolean mInLoad;
4205 private boolean mIsNetworkUp;
Ben Murdochb7cc8b42009-09-28 10:59:09 +01004206 private boolean mDidStopLoad;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004207
Cary Clark1f10cbf2010-03-22 11:45:23 -04004208 /* package */ boolean mActivityInPause = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004209
4210 private boolean mMenuIsDown;
4211
The Android Open Source Project0c908882009-03-03 19:32:16 -08004212 private static boolean mInTrace;
4213
4214 // Performance probe
4215 private static final int[] SYSTEM_CPU_FORMAT = new int[] {
4216 Process.PROC_SPACE_TERM | Process.PROC_COMBINE,
4217 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 1: user time
4218 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 2: nice time
4219 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 3: sys time
4220 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 4: idle time
4221 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 5: iowait time
4222 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 6: irq time
4223 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG // 7: softirq time
4224 };
4225
4226 private long mStart;
4227 private long mProcessStart;
4228 private long mUserStart;
4229 private long mSystemStart;
4230 private long mIdleStart;
4231 private long mIrqStart;
4232
4233 private long mUiStart;
4234
4235 private Drawable mMixLockIcon;
4236 private Drawable mSecLockIcon;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004237
4238 /* hold a ref so we can auto-cancel if necessary */
4239 private AlertDialog mAlertDialog;
4240
The Android Open Source Project0c908882009-03-03 19:32:16 -08004241 // The up-to-date URL and title (these can be different from those stored
4242 // in WebView, since it takes some time for the information in WebView to
4243 // get updated)
4244 private String mUrl;
4245 private String mTitle;
4246
4247 // As PageInfo has different style for landscape / portrait, we have
4248 // to re-open it when configuration changed
4249 private AlertDialog mPageInfoDialog;
Grace Kloba22ac16e2009-10-07 18:00:23 -07004250 private Tab mPageInfoView;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004251 // If the Page-Info dialog is launched from the SSL-certificate-on-error
4252 // dialog, we should not just dismiss it, but should get back to the
4253 // SSL-certificate-on-error dialog. This flag is used to store this state
Leon Scrogginsc7b92f82010-01-11 18:17:31 -05004254 private boolean mPageInfoFromShowSSLCertificateOnError;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004255
4256 // as SSLCertificateOnError has different style for landscape / portrait,
4257 // we have to re-open it when configuration changed
4258 private AlertDialog mSSLCertificateOnErrorDialog;
4259 private WebView mSSLCertificateOnErrorView;
4260 private SslErrorHandler mSSLCertificateOnErrorHandler;
4261 private SslError mSSLCertificateOnErrorError;
4262
4263 // as SSLCertificate has different style for landscape / portrait, we
4264 // have to re-open it when configuration changed
4265 private AlertDialog mSSLCertificateDialog;
Grace Kloba22ac16e2009-10-07 18:00:23 -07004266 private Tab mSSLCertificateView;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004267
4268 // as HttpAuthentication has different style for landscape / portrait, we
4269 // have to re-open it when configuration changed
4270 private AlertDialog mHttpAuthenticationDialog;
4271 private HttpAuthHandler mHttpAuthHandler;
4272
4273 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_PARAMS =
4274 new FrameLayout.LayoutParams(
Romain Guy15b8ec62010-01-08 15:06:43 -08004275 ViewGroup.LayoutParams.MATCH_PARENT,
4276 ViewGroup.LayoutParams.MATCH_PARENT);
Andrei Popescuadc008d2009-06-26 14:11:30 +01004277 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_GRAVITY_CENTER =
4278 new FrameLayout.LayoutParams(
Romain Guy15b8ec62010-01-08 15:06:43 -08004279 ViewGroup.LayoutParams.MATCH_PARENT,
4280 ViewGroup.LayoutParams.MATCH_PARENT,
Andrei Popescuadc008d2009-06-26 14:11:30 +01004281 Gravity.CENTER);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07004282 // Google search
4283 final static String QuickSearch_G = "http://www.google.com/m?q=%s";
The Android Open Source Project0c908882009-03-03 19:32:16 -08004284 // Wikipedia search
4285 final static String QuickSearch_W = "http://en.wikipedia.org/w/index.php?search=%s&go=Go";
4286 // Dictionary search
4287 final static String QuickSearch_D = "http://dictionary.reference.com/search?q=%s";
4288 // Google Mobile Local search
4289 final static String QuickSearch_L = "http://www.google.com/m/search?site=local&q=%s&near=mountain+view";
4290
4291 final static String QUERY_PLACE_HOLDER = "%s";
4292
4293 // "source" parameter for Google search through search key
4294 final static String GOOGLE_SEARCH_SOURCE_SEARCHKEY = "browser-key";
4295 // "source" parameter for Google search through goto menu
4296 final static String GOOGLE_SEARCH_SOURCE_GOTO = "browser-goto";
4297 // "source" parameter for Google search through simplily type
4298 final static String GOOGLE_SEARCH_SOURCE_TYPE = "browser-type";
4299 // "source" parameter for Google search suggested by the browser
4300 final static String GOOGLE_SEARCH_SOURCE_SUGGEST = "browser-suggest";
4301 // "source" parameter for Google search from unknown source
4302 final static String GOOGLE_SEARCH_SOURCE_UNKNOWN = "unknown";
4303
4304 private final static String LOGTAG = "browser";
4305
The Android Open Source Project0c908882009-03-03 19:32:16 -08004306 private String mLastEnteredUrl;
4307
4308 private PowerManager.WakeLock mWakeLock;
4309 private final static int WAKELOCK_TIMEOUT = 5 * 60 * 1000; // 5 minutes
4310
4311 private Toast mStopToast;
4312
Leon Scroggins571b3762010-05-26 10:25:01 -04004313 private TitleBarBase mTitleBar;
Michael Kolba2b2ba82010-08-04 17:54:03 -07004314 private TabBar mTabBar;
Leon Scroggins81db3662009-06-04 17:45:11 -04004315
Ben Murdochbff2d602009-07-01 20:19:05 +01004316 private LinearLayout mErrorConsoleContainer = null;
4317 private boolean mShouldShowErrorConsole = false;
4318
The Android Open Source Project0c908882009-03-03 19:32:16 -08004319 // As the ids are dynamically created, we can't guarantee that they will
4320 // be in sequence, so this static array maps ids to a window number.
4321 final static private int[] WINDOW_SHORTCUT_ID_ARRAY =
4322 { R.id.window_one_menu_id, R.id.window_two_menu_id, R.id.window_three_menu_id,
4323 R.id.window_four_menu_id, R.id.window_five_menu_id, R.id.window_six_menu_id,
4324 R.id.window_seven_menu_id, R.id.window_eight_menu_id };
4325
4326 // monitor platform changes
4327 private IntentFilter mNetworkStateChangedFilter;
4328 private BroadcastReceiver mNetworkStateIntentReceiver;
4329
Grace Klobab4da0ad2009-05-14 14:45:40 -07004330 private BroadcastReceiver mPackageInstallationReceiver;
4331
Bjorn Bringerta7611812010-03-24 11:12:02 +00004332 private SystemAllowGeolocationOrigins mSystemAllowGeolocationOrigins;
4333
The Android Open Source Project0c908882009-03-03 19:32:16 -08004334 // activity requestCode
Nicolas Roard78a98e42009-05-11 13:34:17 +01004335 final static int COMBO_PAGE = 1;
4336 final static int DOWNLOAD_PAGE = 2;
4337 final static int PREFERENCES_PAGE = 3;
Leon Scroggins8d5fa432009-10-02 15:55:59 -04004338 final static int FILE_SELECTED = 4;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004339
Andrei Popescu540035d2009-09-18 18:59:20 +01004340 // the default <video> poster
4341 private Bitmap mDefaultVideoPoster;
4342 // the video progress view
4343 private View mVideoProgressView;
4344
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004345 /**
4346 * A UrlData class to abstract how the content will be set to WebView.
4347 * This base class uses loadUrl to show the content.
4348 */
Leon Scroggins6eac63e2010-03-15 18:19:14 -04004349 /* package */ static class UrlData {
Grace Kloba068e48b2010-01-26 18:11:27 -08004350 final String mUrl;
4351 final Map<String, String> mHeaders;
Leon Scroggins58d56c62010-01-28 15:12:40 -05004352 final Intent mVoiceIntent;
Grace Kloba60e095c2009-06-16 11:50:55 -07004353
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004354 UrlData(String url) {
4355 this.mUrl = url;
Grace Kloba068e48b2010-01-26 18:11:27 -08004356 this.mHeaders = null;
Leon Scroggins58d56c62010-01-28 15:12:40 -05004357 this.mVoiceIntent = null;
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004358 }
Grace Kloba60e095c2009-06-16 11:50:55 -07004359
Leon Scroggins58d56c62010-01-28 15:12:40 -05004360 UrlData(String url, Map<String, String> headers, Intent intent) {
Grace Kloba068e48b2010-01-26 18:11:27 -08004361 this.mUrl = url;
4362 this.mHeaders = headers;
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -05004363 if (RecognizerResultsIntent.ACTION_VOICE_SEARCH_RESULTS
4364 .equals(intent.getAction())) {
Leon Scroggins58d56c62010-01-28 15:12:40 -05004365 this.mVoiceIntent = intent;
4366 } else {
4367 this.mVoiceIntent = null;
4368 }
Grace Kloba60e095c2009-06-16 11:50:55 -07004369 }
4370
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004371 boolean isEmpty() {
Leon Scroggins58d56c62010-01-28 15:12:40 -05004372 return mVoiceIntent == null && (mUrl == null || mUrl.length() == 0);
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004373 }
4374
Leon Scroggins92472e82010-02-17 16:32:28 -05004375 /**
4376 * Load this UrlData into the given Tab. Use loadUrlDataIn to update
4377 * the title bar as well.
4378 */
Leon Scroggins58d56c62010-01-28 15:12:40 -05004379 public void loadIn(Tab t) {
4380 if (mVoiceIntent != null) {
4381 t.activateVoiceSearchMode(mVoiceIntent);
4382 } else {
4383 t.getWebView().loadUrl(mUrl, mHeaders);
4384 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004385 }
4386 };
4387
Leon Scroggins1f005d32009-08-10 17:36:42 -04004388 /* package */ static final UrlData EMPTY_URL_DATA = new UrlData(null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004389}