blob: df2d0ea379f84e592df7d35d14d002d74ec579c0 [file] [log] [blame]
The Android Open Source Project0c908882009-03-03 19:32:16 -08001/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.browser;
18
Michael Kolb3f65c382010-08-20 15:31:16 -070019import com.android.browser.ScrollWebView.ScrollListener;
Bjorn Bringertd69f51d2010-09-13 14:06:41 +010020import com.android.browser.search.SearchEngine;
Michael Kolb3f65c382010-08-20 15:31:16 -070021import com.android.common.Search;
22import com.android.common.speech.LoggingEvents;
23
Michael Kolbed217742010-08-10 17:52:34 -070024import android.app.ActionBar;
The Android Open Source Project0c908882009-03-03 19:32:16 -080025import android.app.Activity;
The Android Open Source Project0c908882009-03-03 19:32:16 -080026import android.app.AlertDialog;
Michael Kolbc7485ae2010-09-03 10:10:58 -070027import android.app.Dialog;
Steve Howard5a862fc2010-09-28 12:52:06 -070028import android.app.DownloadManager;
The Android Open Source Project0c908882009-03-03 19:32:16 -080029import android.app.ProgressDialog;
30import android.app.SearchManager;
31import android.content.ActivityNotFoundException;
32import android.content.BroadcastReceiver;
Dianne Hackborn80f32622010-08-05 14:17:53 -070033import android.content.ClipboardManager;
The Android Open Source Project0c908882009-03-03 19:32:16 -080034import android.content.ComponentName;
Leon Scroggins58d56c62010-01-28 15:12:40 -050035import android.content.ContentProvider;
36import android.content.ContentProviderClient;
The Android Open Source Project0c908882009-03-03 19:32:16 -080037import android.content.ContentResolver;
38import android.content.ContentValues;
39import android.content.Context;
40import android.content.DialogInterface;
41import android.content.Intent;
42import android.content.IntentFilter;
The Android Open Source Project0c908882009-03-03 19:32:16 -080043import android.content.pm.PackageManager;
44import android.content.pm.ResolveInfo;
The Android Open Source Project0c908882009-03-03 19:32:16 -080045import android.content.res.Configuration;
46import android.content.res.Resources;
47import android.database.Cursor;
The Android Open Source Project0c908882009-03-03 19:32:16 -080048import android.graphics.Bitmap;
Andrei Popescu540035d2009-09-18 18:59:20 +010049import android.graphics.BitmapFactory;
The Android Open Source Project0c908882009-03-03 19:32:16 -080050import android.graphics.Canvas;
The Android Open Source Project0c908882009-03-03 19:32:16 -080051import android.graphics.Picture;
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -040052import android.graphics.PixelFormat;
The Android Open Source Project0c908882009-03-03 19:32:16 -080053import android.graphics.drawable.Drawable;
The Android Open Source Project0c908882009-03-03 19:32:16 -080054import android.net.ConnectivityManager;
Andrei Popescu56199cc2010-01-12 22:39:16 +000055import android.net.NetworkInfo;
The Android Open Source Project0c908882009-03-03 19:32:16 -080056import android.net.Uri;
57import android.net.WebAddress;
The Android Open Source Project0c908882009-03-03 19:32:16 -080058import android.net.http.SslCertificate;
59import android.net.http.SslError;
60import android.os.AsyncTask;
61import android.os.Bundle;
62import android.os.Debug;
63import android.os.Environment;
64import android.os.Handler;
The Android Open Source Project0c908882009-03-03 19:32:16 -080065import android.os.Message;
66import android.os.PowerManager;
67import android.os.Process;
The Android Open Source Project0c908882009-03-03 19:32:16 -080068import android.os.SystemClock;
The Android Open Source Project0c908882009-03-03 19:32:16 -080069import android.provider.Browser;
Michael Kolb370a4f32010-10-06 10:45:32 -070070import android.provider.BrowserContract;
Jeff Hamilton1a805652010-09-07 12:36:30 -070071import android.provider.BrowserContract.Images;
Michael Kolbe421c242010-10-04 19:29:01 -070072import android.provider.ContactsContract;
Michael Kolba2b2ba82010-08-04 17:54:03 -070073import android.provider.ContactsContract.Intents.Insert;
The Android Open Source Project0c908882009-03-03 19:32:16 -080074import android.provider.Downloads;
75import android.provider.MediaStore;
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -050076import android.speech.RecognizerResultsIntent;
The Android Open Source Project0c908882009-03-03 19:32:16 -080077import android.text.TextUtils;
78import android.text.format.DateFormat;
The Android Open Source Project0c908882009-03-03 19:32:16 -080079import android.util.Log;
Dianne Hackborn385effd2010-02-24 20:03:04 -080080import android.util.Patterns;
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -040081import android.view.ActionMode;
The Android Open Source Project0c908882009-03-03 19:32:16 -080082import android.view.ContextMenu;
Michael Kolba2b2ba82010-08-04 17:54:03 -070083import android.view.ContextMenu.ContextMenuInfo;
The Android Open Source Project0c908882009-03-03 19:32:16 -080084import android.view.Gravity;
85import android.view.KeyEvent;
86import android.view.LayoutInflater;
87import android.view.Menu;
88import android.view.MenuInflater;
89import android.view.MenuItem;
Michael Kolba2b2ba82010-08-04 17:54:03 -070090import android.view.MenuItem.OnMenuItemClickListener;
The Android Open Source Project0c908882009-03-03 19:32:16 -080091import android.view.View;
92import android.view.ViewGroup;
93import android.view.Window;
94import android.view.WindowManager;
Svetoslav Ganov2b345992010-05-06 06:13:54 -070095import android.view.accessibility.AccessibilityManager;
The Android Open Source Project0c908882009-03-03 19:32:16 -080096import android.webkit.CookieManager;
97import android.webkit.CookieSyncManager;
98import android.webkit.DownloadListener;
99import android.webkit.HttpAuthHandler;
100import android.webkit.SslErrorHandler;
101import android.webkit.URLUtil;
Leon Clarkecb6cc862009-09-29 18:35:13 +0100102import android.webkit.ValueCallback;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800103import android.webkit.WebChromeClient;
104import android.webkit.WebHistoryItem;
105import android.webkit.WebIconDatabase;
106import android.webkit.WebView;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800107import android.widget.EditText;
108import android.widget.FrameLayout;
109import android.widget.LinearLayout;
Michael Kolbc7485ae2010-09-03 10:10:58 -0700110import android.widget.PopupMenu;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800111import android.widget.TextView;
112import android.widget.Toast;
113
Leon Scrogginsb6b7f9e2009-06-18 12:05:28 -0400114import java.io.ByteArrayOutputStream;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800115import java.io.File;
Ben Murdoch4f75ba22009-10-27 11:48:28 +0000116import java.io.IOException;
117import java.io.InputStream;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800118import java.net.MalformedURLException;
Dianne Hackborn99189432009-06-17 18:06:18 -0700119import java.net.URISyntaxException;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800120import java.net.URL;
121import java.net.URLEncoder;
Elliott Slaughter3d6df162010-08-25 13:17:44 -0700122import java.util.Calendar;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800123import java.util.Date;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800124import java.util.HashMap;
Grace Kloba00f54c52010-01-27 14:53:51 -0800125import java.util.Iterator;
Grace Kloba068e48b2010-01-26 18:11:27 -0800126import java.util.Map;
Michael Kolbfe251992010-07-08 15:41:55 -0700127import java.util.Vector;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800128import java.util.regex.Matcher;
129import java.util.regex.Pattern;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800130
131public class BrowserActivity extends Activity
Michael Kolbe421c242010-10-04 19:29:01 -0700132 implements View.OnCreateContextMenuListener, DownloadListener,
133 PopupMenu.OnMenuItemClickListener, BookmarksHistoryCallbacks {
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
Cary Clarka9771242009-08-11 16:42:26 -0400142 private static class ClearThumbnails extends AsyncTask<File, Void, Void> {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800143 @Override
144 public Void doInBackground(File... files) {
145 if (files != null) {
146 for (File f : files) {
Cary Clarkd6be1752009-08-12 12:56:42 -0400147 if (!f.delete()) {
148 Log.e(LOGTAG, f.getPath() + " was not deleted");
149 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800150 }
151 }
152 return null;
153 }
154 }
155
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400156 /**
157 * This layout holds everything you see below the status bar, including the
158 * error console, the custom view container, and the webviews.
159 */
160 private FrameLayout mBrowserFrameLayout;
Leon Scroggins81db3662009-06-04 17:45:11 -0400161
Michael Kolbe421c242010-10-04 19:29:01 -0700162 private CombinedBookmarkHistoryView mComboView;
163
Leon Scrogginsd746a942010-05-19 13:21:44 -0400164 private boolean mXLargeScreenSize;
165
Jeff Davidson43610292010-07-16 16:03:58 -0700166 private Boolean mIsProviderPresent = null;
167 private Uri mRlzUri = null;
168
Grace Kloba22ac16e2009-10-07 18:00:23 -0700169 @Override
170 public void onCreate(Bundle icicle) {
Dave Bort31a6d1c2009-04-13 15:56:49 -0700171 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800172 Log.v(LOGTAG, this + " onStart");
173 }
174 super.onCreate(icicle);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800175 // test the browser in OpenGL
176 // requestWindowFeature(Window.FEATURE_OPENGL);
177
Mike Reedd334bf52010-01-26 15:21:44 -0500178 // enable this to test the browser in 32bit
179 if (false) {
180 getWindow().setFormat(PixelFormat.RGBX_8888);
181 BitmapFactory.setDefaultConfig(Bitmap.Config.ARGB_8888);
182 }
183
Bjorn Bringertb1402a52010-10-12 10:53:12 +0100184 if (((AccessibilityManager) getSystemService(ACCESSIBILITY_SERVICE)).isEnabled()) {
Svetoslav Ganov2b345992010-05-06 06:13:54 -0700185 setDefaultKeyMode(DEFAULT_KEYS_DISABLE);
186 } else {
187 setDefaultKeyMode(DEFAULT_KEYS_SEARCH_LOCAL);
188 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800189
190 mResolver = getContentResolver();
191
Leon Scroggins IIIcc14c8c2010-09-27 12:45:34 -0400192 // Keep a settings instance handy.
193 mSettings = BrowserSettings.getInstance();
194
Grace Kloba0923d692009-09-23 21:37:25 -0700195 // If this was a web search request, pass it on to the default web
196 // search provider and finish this activity.
197 if (handleWebSearchIntent(getIntent())) {
198 finish();
199 return;
200 }
201
Michael Kolb0506f2d2010-10-14 16:20:16 -0700202 mSecLockIcon = getResources().getDrawable(R.drawable.ic_secure);
203 mMixLockIcon = getResources().getDrawable(R.drawable.ic_partial_secure);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800204
Michael Kolbed217742010-08-10 17:52:34 -0700205 // Create the tab control and our initial tab
206 mTabControl = new TabControl(this);
207
208 mXLargeScreenSize = (getResources().getConfiguration().screenLayout
209 & Configuration.SCREENLAYOUT_SIZE_MASK)
210 == Configuration.SCREENLAYOUT_SIZE_XLARGE;
211
Leon Scroggins81db3662009-06-04 17:45:11 -0400212 FrameLayout frameLayout = (FrameLayout) getWindow().getDecorView()
Bjorn Bringertb1402a52010-10-12 10:53:12 +0100213 .findViewById(android.R.id.content);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400214 mBrowserFrameLayout = (FrameLayout) LayoutInflater.from(this)
215 .inflate(R.layout.custom_screen, null);
216 mContentView = (FrameLayout) mBrowserFrameLayout.findViewById(
217 R.id.main_content);
218 mErrorConsoleContainer = (LinearLayout) mBrowserFrameLayout
219 .findViewById(R.id.error_console);
220 mCustomViewContainer = (FrameLayout) mBrowserFrameLayout
221 .findViewById(R.id.fullscreen_custom_content);
222 frameLayout.addView(mBrowserFrameLayout, COVER_SCREEN_PARAMS);
Michael Kolbe0a36662010-06-29 10:37:12 -0700223
Leon Scrogginsd746a942010-05-19 13:21:44 -0400224 if (mXLargeScreenSize) {
Michael Kolba2b2ba82010-08-04 17:54:03 -0700225 mTitleBar = new TitleBarXLarge(this);
226 mTitleBar.setProgress(100);
227 mFakeTitleBar = new TitleBarXLarge(this);
Michael Kolbed217742010-08-10 17:52:34 -0700228 ActionBar actionBar = getActionBar();
Michael Kolba2b2ba82010-08-04 17:54:03 -0700229 mTabBar = new TabBar(this, mTabControl, (TitleBarXLarge) mFakeTitleBar);
Michael Kolbed217742010-08-10 17:52:34 -0700230 actionBar.setCustomNavigationMode(mTabBar);
Michael Kolb68775752010-08-19 12:42:01 -0700231 // disable built in zoom controls
232 mTabControl.setDisplayZoomControls(false);
Leon Scrogginsd746a942010-05-19 13:21:44 -0400233 } else {
Leon Scroggins571b3762010-05-26 10:25:01 -0400234 mTitleBar = new TitleBar(this);
Leon Scrogginsd746a942010-05-19 13:21:44 -0400235 // mTitleBar will be always be shown in the fully loaded mode on
236 // phone
237 mTitleBar.setProgress(100);
Leon Scrogginsd746a942010-05-19 13:21:44 -0400238 mFakeTitleBar = new TitleBar(this);
239 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800240
The Android Open Source Project0c908882009-03-03 19:32:16 -0800241 // Open the icon database and retain all the bookmark urls for favicons
242 retainIconsOnStartup();
243
The Android Open Source Project0c908882009-03-03 19:32:16 -0800244 mSettings.setTabControl(mTabControl);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800245
246 PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
247 mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Browser");
248
Patrick Scott6adacc92010-03-05 08:24:51 -0500249 // Find out if the network is currently up.
250 ConnectivityManager cm = (ConnectivityManager) getSystemService(
251 Context.CONNECTIVITY_SERVICE);
252 NetworkInfo info = cm.getActiveNetworkInfo();
253 if (info != null) {
254 mIsNetworkUp = info.isAvailable();
255 }
256
Grace Klobaa34f6862009-07-31 16:28:17 -0700257 /* enables registration for changes in network status from
258 http stack */
259 mNetworkStateChangedFilter = new IntentFilter();
260 mNetworkStateChangedFilter.addAction(
261 ConnectivityManager.CONNECTIVITY_ACTION);
262 mNetworkStateIntentReceiver = new BroadcastReceiver() {
263 @Override
264 public void onReceive(Context context, Intent intent) {
265 if (intent.getAction().equals(
266 ConnectivityManager.CONNECTIVITY_ACTION)) {
Andrei Popescue4c98462010-02-19 15:44:13 +0000267
268 NetworkInfo info = intent.getParcelableExtra(
269 ConnectivityManager.EXTRA_NETWORK_INFO);
270 String typeName = info.getTypeName();
271 String subtypeName = info.getSubtypeName();
272 sendNetworkType(typeName.toLowerCase(),
273 (subtypeName != null ? subtypeName.toLowerCase() : ""));
274
275 onNetworkToggle(info.isAvailable());
Grace Klobaa34f6862009-07-31 16:28:17 -0700276 }
277 }
278 };
279
Elliott Slaughter3d6df162010-08-25 13:17:44 -0700280 // Unless the last browser usage was within 24 hours, destroy any
281 // remaining incognito tabs.
282
283 Calendar lastActiveDate = icicle != null ? (Calendar) icicle.getSerializable("lastActiveDate") : null;
284 Calendar today = Calendar.getInstance();
285 Calendar yesterday = Calendar.getInstance();
286 yesterday.add(Calendar.DATE, -1);
287
288 boolean dontRestoreIncognitoTabs = lastActiveDate == null
289 || lastActiveDate.before(yesterday)
290 || lastActiveDate.after(today);
291
292 if (!mTabControl.restoreState(icicle, dontRestoreIncognitoTabs)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800293 // clear up the thumbnail directory if we can't restore the state as
294 // none of the files in the directory are referenced any more.
295 new ClearThumbnails().execute(
296 mTabControl.getThumbnailDir().listFiles());
Grace Klobaaab3f092009-07-30 12:29:51 -0700297 // there is no quit on Android. But if we can't restore the state,
298 // we can treat it as a new Browser, remove the old session cookies.
299 CookieManager.getInstance().removeSessionCookie();
Elliott Slaughter3d6df162010-08-25 13:17:44 -0700300 // remove any incognito files
301 WebView.cleanupPrivateBrowsingFiles(this);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800302 final Intent intent = getIntent();
303 final Bundle extra = intent.getExtras();
304 // Create an initial tab.
305 // If the intent is ACTION_VIEW and data is not null, the Browser is
306 // invoked to view the content by another application. In this case,
307 // the tab will be close when exit.
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700308 UrlData urlData = getUrlDataFromIntent(intent);
309
Leon Scroggins58d56c62010-01-28 15:12:40 -0500310 String action = intent.getAction();
Grace Kloba22ac16e2009-10-07 18:00:23 -0700311 final Tab t = mTabControl.createNewTab(
Leon Scroggins58d56c62010-01-28 15:12:40 -0500312 (Intent.ACTION_VIEW.equals(action) &&
313 intent.getData() != null)
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -0500314 || RecognizerResultsIntent.ACTION_VOICE_SEARCH_RESULTS
315 .equals(action),
Elliott Slaughterf0f03952010-07-14 18:10:36 -0700316 intent.getStringExtra(Browser.EXTRA_APPLICATION_ID),
317 urlData.mUrl, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800318 mTabControl.setCurrentTab(t);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800319 attachTabToContentView(t);
320 WebView webView = t.getWebView();
321 if (extra != null) {
322 int scale = extra.getInt(Browser.INITIAL_ZOOM_LEVEL, 0);
323 if (scale > 0 && scale <= 1000) {
324 webView.setInitialScale(scale);
325 }
326 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800327
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700328 if (urlData.isEmpty()) {
Shimeng (Simon) Wang98d5fce2010-03-16 13:23:39 -0700329 loadUrl(webView, mSettings.getHomePage());
The Android Open Source Project0c908882009-03-03 19:32:16 -0800330 } else {
Patrick Scott9d53da02010-02-19 10:19:01 -0500331 loadUrlDataIn(t, urlData);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800332 }
333 } else {
Elliott Slaughter3d6df162010-08-25 13:17:44 -0700334 if (dontRestoreIncognitoTabs) {
335 WebView.cleanupPrivateBrowsingFiles(this);
336 }
337
The Android Open Source Project0c908882009-03-03 19:32:16 -0800338 // TabControl.restoreState() will create a new tab even if
Leon Scroggins1f005d32009-08-10 17:36:42 -0400339 // restoring the state fails.
The Android Open Source Project0c908882009-03-03 19:32:16 -0800340 attachTabToContentView(mTabControl.getCurrentTab());
341 }
Grace Kloba615c6c92009-08-03 10:22:44 -0700342
Cary Clarkb4b83182010-07-01 12:36:56 -0400343 // Delete old thumbnails to save space
344 File dir = mTabControl.getThumbnailDir();
345 if (dir.exists()) {
346 for (String child : dir.list()) {
347 File f = new File(dir, child);
348 f.delete();
349 }
350 }
351
Feng Qianb3c02da2009-06-29 15:58:08 -0700352 // Read JavaScript flags if it exists.
353 String jsFlags = mSettings.getJsFlags();
354 if (jsFlags.trim().length() != 0) {
355 mTabControl.getCurrentWebView().setJsFlags(jsFlags);
356 }
Bjorn Bringerta7611812010-03-24 11:12:02 +0000357
358 // Start watching the default geolocation permissions
359 mSystemAllowGeolocationOrigins
360 = new SystemAllowGeolocationOrigins(getApplicationContext());
361 mSystemAllowGeolocationOrigins.start();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800362 }
363
Michael Kolba2b2ba82010-08-04 17:54:03 -0700364 ScrollListener getScrollListener() {
365 return mTabBar;
366 }
367
Leon Scroggins58d56c62010-01-28 15:12:40 -0500368 /**
369 * Feed the previously stored results strings to the BrowserProvider so that
370 * the SearchDialog will show them instead of the standard searches.
371 * @param result String to show on the editable line of the SearchDialog.
372 */
373 /* package */ void showVoiceSearchResults(String result) {
374 ContentProviderClient client = mResolver.acquireContentProviderClient(
375 Browser.BOOKMARKS_URI);
376 ContentProvider prov = client.getLocalContentProvider();
377 BrowserProvider bp = (BrowserProvider) prov;
378 bp.setQueryResults(mTabControl.getCurrentTab().getVoiceSearchResults());
379 client.release();
380
Leon Scrogginsfbb3f152010-03-09 17:26:56 -0500381 Bundle bundle = createGoogleSearchSourceBundle(
382 GOOGLE_SEARCH_SOURCE_SEARCHKEY);
383 bundle.putBoolean(SearchManager.CONTEXT_IS_VOICE, true);
384 startSearch(result, false, bundle, false);
Leon Scroggins58d56c62010-01-28 15:12:40 -0500385 }
386
The Android Open Source Project0c908882009-03-03 19:32:16 -0800387 @Override
388 protected void onNewIntent(Intent intent) {
Grace Kloba22ac16e2009-10-07 18:00:23 -0700389 Tab current = mTabControl.getCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800390 // When a tab is closed on exit, the current tab index is set to -1.
391 // Reset before proceed as Browser requires the current tab to be set.
392 if (current == null) {
393 // Try to reset the tab in case the index was incorrect.
394 current = mTabControl.getTab(0);
395 if (current == null) {
396 // No tabs at all so just ignore this intent.
397 return;
398 }
399 mTabControl.setCurrentTab(current);
400 attachTabToContentView(current);
401 resetTitleAndIcon(current.getWebView());
402 }
403 final String action = intent.getAction();
404 final int flags = intent.getFlags();
405 if (Intent.ACTION_MAIN.equals(action) ||
406 (flags & Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY) != 0) {
407 // just resume the browser
408 return;
409 }
Leon Scrogginsb8a844d2010-03-18 15:06:15 -0400410 // In case the SearchDialog is open.
411 ((SearchManager) getSystemService(Context.SEARCH_SERVICE))
412 .stopSearch();
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -0500413 boolean activateVoiceSearch = RecognizerResultsIntent
414 .ACTION_VOICE_SEARCH_RESULTS.equals(action);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800415 if (Intent.ACTION_VIEW.equals(action)
416 || Intent.ACTION_SEARCH.equals(action)
417 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
Leon Scroggins58d56c62010-01-28 15:12:40 -0500418 || Intent.ACTION_WEB_SEARCH.equals(action)
419 || activateVoiceSearch) {
Leon Scroggins3b18ce32010-02-08 17:35:59 -0500420 if (current.isInVoiceSearchMode()) {
421 String title = current.getVoiceDisplayTitle();
422 if (title != null && title.equals(intent.getStringExtra(
423 SearchManager.QUERY))) {
424 // The user submitted the same search as the last voice
425 // search, so do nothing.
426 return;
427 }
Leon Scroggins1fe13a52010-02-09 15:31:26 -0500428 if (Intent.ACTION_SEARCH.equals(action)
429 && current.voiceSearchSourceIsGoogle()) {
430 Intent logIntent = new Intent(
431 LoggingEvents.ACTION_LOG_EVENT);
432 logIntent.putExtra(LoggingEvents.EXTRA_EVENT,
433 LoggingEvents.VoiceSearch.QUERY_UPDATED);
434 logIntent.putExtra(
435 LoggingEvents.VoiceSearch.EXTRA_QUERY_UPDATED_VALUE,
436 intent.getDataString());
437 sendBroadcast(logIntent);
438 // Note, onPageStarted will revert the voice title bar
439 // When http://b/issue?id=2379215 is fixed, we should update
440 // the title bar here.
441 }
Leon Scroggins3b18ce32010-02-08 17:35:59 -0500442 }
Satish Sampath565505b2009-05-29 15:37:27 +0100443 // If this was a search request (e.g. search query directly typed into the address bar),
444 // pass it on to the default web search provider.
445 if (handleWebSearchIntent(intent)) {
446 return;
447 }
448
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700449 UrlData urlData = getUrlDataFromIntent(intent);
450 if (urlData.isEmpty()) {
451 urlData = new UrlData(mSettings.getHomePage());
The Android Open Source Project0c908882009-03-03 19:32:16 -0800452 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700453
Grace Klobacc634032009-07-28 15:58:19 -0700454 final String appId = intent
455 .getStringExtra(Browser.EXTRA_APPLICATION_ID);
Leon Scroggins47208682010-04-07 17:59:48 -0400456 if ((Intent.ACTION_VIEW.equals(action)
457 // If a voice search has no appId, it means that it came
458 // from the browser. In that case, reuse the current tab.
459 || (activateVoiceSearch && appId != null))
Grace Klobacc634032009-07-28 15:58:19 -0700460 && !getPackageName().equals(appId)
461 && (flags & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0) {
Grace Kloba22ac16e2009-10-07 18:00:23 -0700462 Tab appTab = mTabControl.getTabFromId(appId);
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700463 if (appTab != null) {
464 Log.i(LOGTAG, "Reusing tab for " + appId);
465 // Dismiss the subwindow if applicable.
466 dismissSubWindow(appTab);
467 // Since we might kill the WebView, remove it from the
468 // content view first.
469 removeTabFromContentView(appTab);
470 // Recreate the main WebView after destroying the old one.
471 // If the WebView has the same original url and is on that
472 // page, it can be reused.
473 boolean needsLoad =
Leon Scroggins6eac63e2010-03-15 18:19:14 -0400474 mTabControl.recreateWebView(appTab, urlData);
Ben Murdochbff2d602009-07-01 20:19:05 +0100475
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700476 if (current != appTab) {
Leon Scroggins1f005d32009-08-10 17:36:42 -0400477 switchToTab(mTabControl.getTabIndex(appTab));
478 if (needsLoad) {
Patrick Scott9d53da02010-02-19 10:19:01 -0500479 loadUrlDataIn(appTab, urlData);
Leon Scroggins1f005d32009-08-10 17:36:42 -0400480 }
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700481 } else {
Leon Scroggins1f005d32009-08-10 17:36:42 -0400482 // If the tab was the current tab, we have to attach
483 // it to the view system again.
484 attachTabToContentView(appTab);
485 if (needsLoad) {
Patrick Scott9d53da02010-02-19 10:19:01 -0500486 loadUrlDataIn(appTab, urlData);
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700487 }
488 }
489 return;
Patrick Scottcd115892009-07-16 09:42:58 -0400490 } else {
491 // No matching application tab, try to find a regular tab
492 // with a matching url.
493 appTab = mTabControl.findUnusedTabWithUrl(urlData.mUrl);
Leon Scroggins25515f82009-08-19 15:31:58 -0400494 if (appTab != null) {
495 if (current != appTab) {
496 switchToTab(mTabControl.getTabIndex(appTab));
497 }
498 // Otherwise, we are already viewing the correct tab.
Patrick Scottcd115892009-07-16 09:42:58 -0400499 } else {
500 // if FLAG_ACTIVITY_BROUGHT_TO_FRONT flag is on, the url
501 // will be opened in a new tab unless we have reached
502 // MAX_TABS. Then the url will be opened in the current
503 // tab. If a new tab is created, it will have "true" for
504 // exit on close.
Leon Scroggins1f005d32009-08-10 17:36:42 -0400505 openTabAndShow(urlData, true, appId);
Patrick Scottcd115892009-07-16 09:42:58 -0400506 }
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700507 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800508 } else {
Grace Kloba638d3f42009-11-23 10:35:04 -0800509 if (!urlData.isEmpty()
510 && urlData.mUrl.startsWith("about:debug")) {
511 if ("about:debug.dom".equals(urlData.mUrl)) {
512 current.getWebView().dumpDomTree(false);
513 } else if ("about:debug.dom.file".equals(urlData.mUrl)) {
514 current.getWebView().dumpDomTree(true);
515 } else if ("about:debug.render".equals(urlData.mUrl)) {
516 current.getWebView().dumpRenderTree(false);
517 } else if ("about:debug.render.file".equals(urlData.mUrl)) {
518 current.getWebView().dumpRenderTree(true);
519 } else if ("about:debug.display".equals(urlData.mUrl)) {
520 current.getWebView().dumpDisplayTree();
521 } else {
522 mSettings.toggleDebugSettings();
523 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800524 return;
525 }
Leon Scroggins1f005d32009-08-10 17:36:42 -0400526 // Get rid of the subwindow if it exists
527 dismissSubWindow(current);
Leon Scroggins8588d152010-04-15 11:01:53 -0400528 // If the current Tab is being used as an application tab,
529 // remove the association, since the new Intent means that it is
530 // no longer associated with that application.
531 current.setAppId(null);
Patrick Scott9d53da02010-02-19 10:19:01 -0500532 loadUrlDataIn(current, urlData);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800533 }
534 }
535 }
536
Satish Sampath565505b2009-05-29 15:37:27 +0100537 /**
538 * Launches the default web search activity with the query parameters if the given intent's data
539 * are identified as plain search terms and not URLs/shortcuts.
540 * @return true if the intent was handled and web search activity was launched, false if not.
541 */
542 private boolean handleWebSearchIntent(Intent intent) {
543 if (intent == null) return false;
544
545 String url = null;
546 final String action = intent.getAction();
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -0500547 if (RecognizerResultsIntent.ACTION_VOICE_SEARCH_RESULTS.equals(
548 action)) {
Leon Scroggins58d56c62010-01-28 15:12:40 -0500549 return false;
550 }
Satish Sampath565505b2009-05-29 15:37:27 +0100551 if (Intent.ACTION_VIEW.equals(action)) {
Grace Kloba1e705052009-09-29 13:13:36 -0700552 Uri data = intent.getData();
553 if (data != null) url = data.toString();
Satish Sampath565505b2009-05-29 15:37:27 +0100554 } else if (Intent.ACTION_SEARCH.equals(action)
555 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
556 || Intent.ACTION_WEB_SEARCH.equals(action)) {
557 url = intent.getStringExtra(SearchManager.QUERY);
558 }
Bjorn Bringert04851702009-09-22 10:36:01 +0100559 return handleWebSearchRequest(url, intent.getBundleExtra(SearchManager.APP_DATA),
560 intent.getStringExtra(SearchManager.EXTRA_DATA_KEY));
Satish Sampath565505b2009-05-29 15:37:27 +0100561 }
562
563 /**
564 * Launches the default web search activity with the query parameters if the given url string
565 * was identified as plain search terms and not URL/shortcut.
566 * @return true if the request was handled and web search activity was launched, false if not.
567 */
Bjorn Bringert04851702009-09-22 10:36:01 +0100568 private boolean handleWebSearchRequest(String inUrl, Bundle appData, String extraData) {
Satish Sampath565505b2009-05-29 15:37:27 +0100569 if (inUrl == null) return false;
570
571 // In general, we shouldn't modify URL from Intent.
572 // But currently, we get the user-typed URL from search box as well.
573 String url = fixUrl(inUrl).trim();
574
Leon Scroggins956cf012010-10-07 13:51:57 -0400575 // URLs are handled by the regular flow of control, so
Satish Sampath565505b2009-05-29 15:37:27 +0100576 // return early.
Dan Egnor5ee906c2009-11-18 12:11:49 -0800577 if (Patterns.WEB_URL.matcher(url).matches()
Leon Scroggins956cf012010-10-07 13:51:57 -0400578 || ACCEPTED_URI_SCHEMA.matcher(url).matches()) {
Satish Sampath565505b2009-05-29 15:37:27 +0100579 return false;
580 }
581
Leon Scroggins8d06e362010-03-24 14:45:57 -0400582 final ContentResolver cr = mResolver;
583 final String newUrl = url;
Elliott Slaughter627d96f2010-08-18 16:35:30 -0700584 if (mTabControl == null || !mTabControl.getCurrentWebView().isPrivateBrowsingEnabled()) {
Elliott Slaughterf0f03952010-07-14 18:10:36 -0700585 new AsyncTask<Void, Void, Void>() {
586 @Override
587 protected Void doInBackground(Void... unused) {
588 Browser.updateVisitedHistory(cr, newUrl, false);
589 Browser.addSearchUrl(cr, newUrl);
590 return null;
591 }
592 }.execute();
593 }
Satish Sampath565505b2009-05-29 15:37:27 +0100594
Bjorn Bringertd69f51d2010-09-13 14:06:41 +0100595 SearchEngine searchEngine = mSettings.getSearchEngine();
596 if (searchEngine == null) return false;
597 searchEngine.startSearch(this, url, appData, extraData);
Satish Sampath565505b2009-05-29 15:37:27 +0100598
599 return true;
600 }
601
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700602 private UrlData getUrlDataFromIntent(Intent intent) {
Leon Scroggins58d56c62010-01-28 15:12:40 -0500603 String url = "";
Grace Kloba068e48b2010-01-26 18:11:27 -0800604 Map<String, String> headers = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800605 if (intent != null) {
606 final String action = intent.getAction();
607 if (Intent.ACTION_VIEW.equals(action)) {
608 url = smartUrlFilter(intent.getData());
609 if (url != null && url.startsWith("content:")) {
610 /* Append mimetype so webview knows how to display */
611 String mimeType = intent.resolveType(getContentResolver());
612 if (mimeType != null) {
613 url += "?" + mimeType;
614 }
615 }
Grace Kloba068e48b2010-01-26 18:11:27 -0800616 if (url != null && url.startsWith("http")) {
Grace Kloba00f54c52010-01-27 14:53:51 -0800617 final Bundle pairs = intent
618 .getBundleExtra(Browser.EXTRA_HEADERS);
Grace Kloba2d508ed2010-01-28 11:39:15 -0800619 if (pairs != null && !pairs.isEmpty()) {
Grace Kloba00f54c52010-01-27 14:53:51 -0800620 Iterator<String> iter = pairs.keySet().iterator();
Grace Kloba068e48b2010-01-26 18:11:27 -0800621 headers = new HashMap<String, String>();
Grace Kloba00f54c52010-01-27 14:53:51 -0800622 while (iter.hasNext()) {
623 String key = iter.next();
624 headers.put(key, pairs.getString(key));
Grace Kloba068e48b2010-01-26 18:11:27 -0800625 }
626 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700627 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800628 } else if (Intent.ACTION_SEARCH.equals(action)
629 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
630 || Intent.ACTION_WEB_SEARCH.equals(action)) {
631 url = intent.getStringExtra(SearchManager.QUERY);
632 if (url != null) {
633 mLastEnteredUrl = url;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800634 // In general, we shouldn't modify URL from Intent.
635 // But currently, we get the user-typed URL from search box as well.
636 url = fixUrl(url);
637 url = smartUrlFilter(url);
Leon Scroggins8d06e362010-03-24 14:45:57 -0400638 final ContentResolver cr = mResolver;
639 final String newUrl = url;
Elliott Slaughter8389e992010-08-20 15:44:08 -0700640 if (mTabControl == null
641 || mTabControl.getCurrentWebView() == null
642 || !mTabControl.getCurrentWebView().isPrivateBrowsingEnabled()) {
643 new AsyncTask<Void, Void, Void>() {
644 @Override
645 protected Void doInBackground(Void... unused) {
646 Browser.updateVisitedHistory(cr, newUrl, false);
647 return null;
648 }
649 }.execute();
650 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800651 String searchSource = "&source=android-" + GOOGLE_SEARCH_SOURCE_SUGGEST + "&";
652 if (url.contains(searchSource)) {
653 String source = null;
654 final Bundle appData = intent.getBundleExtra(SearchManager.APP_DATA);
655 if (appData != null) {
Bjorn Bringert10d1cca2010-02-10 14:22:12 +0000656 source = appData.getString(Search.SOURCE);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800657 }
658 if (TextUtils.isEmpty(source)) {
659 source = GOOGLE_SEARCH_SOURCE_UNKNOWN;
660 }
661 url = url.replace(searchSource, "&source=android-"+source+"&");
662 }
663 }
664 }
665 }
Leon Scroggins58d56c62010-01-28 15:12:40 -0500666 return new UrlData(url, headers, intent);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800667 }
Leon Scroggins58d56c62010-01-28 15:12:40 -0500668 /* package */ void showVoiceTitleBar(String title) {
669 mTitleBar.setInVoiceMode(true);
Leon Scroggins58d56c62010-01-28 15:12:40 -0500670 mTitleBar.setDisplayTitle(title);
Michael Kolba2b2ba82010-08-04 17:54:03 -0700671 mFakeTitleBar.setInVoiceMode(true);
672 mFakeTitleBar.setDisplayTitle(title);
Leon Scroggins58d56c62010-01-28 15:12:40 -0500673 }
674 /* package */ void revertVoiceTitleBar() {
675 mTitleBar.setInVoiceMode(false);
Leon Scroggins003a5dd2010-03-10 12:13:14 -0500676 mTitleBar.setDisplayTitle(mUrl);
Michael Kolba2b2ba82010-08-04 17:54:03 -0700677 mFakeTitleBar.setInVoiceMode(false);
678 mFakeTitleBar.setDisplayTitle(mUrl);
Leon Scroggins58d56c62010-01-28 15:12:40 -0500679 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800680 /* package */ static String fixUrl(String inUrl) {
Cary Clark652ff872009-09-10 13:34:44 -0400681 // FIXME: Converting the url to lower case
682 // duplicates functionality in smartUrlFilter().
683 // However, changing all current callers of fixUrl to
684 // call smartUrlFilter in addition may have unwanted
685 // consequences, and is deferred for now.
686 int colon = inUrl.indexOf(':');
687 boolean allLower = true;
688 for (int index = 0; index < colon; index++) {
689 char ch = inUrl.charAt(index);
690 if (!Character.isLetter(ch)) {
691 break;
692 }
693 allLower &= Character.isLowerCase(ch);
694 if (index == colon - 1 && !allLower) {
695 inUrl = inUrl.substring(0, colon).toLowerCase()
696 + inUrl.substring(colon);
697 }
698 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800699 if (inUrl.startsWith("http://") || inUrl.startsWith("https://"))
700 return inUrl;
701 if (inUrl.startsWith("http:") ||
702 inUrl.startsWith("https:")) {
703 if (inUrl.startsWith("http:/") || inUrl.startsWith("https:/")) {
704 inUrl = inUrl.replaceFirst("/", "//");
705 } else inUrl = inUrl.replaceFirst(":", "://");
706 }
707 return inUrl;
708 }
709
Grace Kloba22ac16e2009-10-07 18:00:23 -0700710 @Override
711 protected void onResume() {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800712 super.onResume();
Dave Bort31a6d1c2009-04-13 15:56:49 -0700713 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800714 Log.v(LOGTAG, "BrowserActivity.onResume: this=" + this);
715 }
716
717 if (!mActivityInPause) {
718 Log.e(LOGTAG, "BrowserActivity is already resumed.");
719 return;
720 }
721
Mike Reed7bfa63b2009-05-28 11:08:32 -0400722 mTabControl.resumeCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800723 mActivityInPause = false;
Mike Reed7bfa63b2009-05-28 11:08:32 -0400724 resumeWebViewTimers();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800725
726 if (mWakeLock.isHeld()) {
727 mHandler.removeMessages(RELEASE_WAKELOCK);
728 mWakeLock.release();
729 }
730
The Android Open Source Project0c908882009-03-03 19:32:16 -0800731 registerReceiver(mNetworkStateIntentReceiver,
732 mNetworkStateChangedFilter);
733 WebView.enablePlatformNotifications();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800734 }
735
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400736 /**
737 * Since the actual title bar is embedded in the WebView, and removing it
Leon Scrogginsfe87bd32009-10-06 10:10:00 -0400738 * would change its appearance, use a different TitleBar to show overlayed
739 * at the top of the screen, when the menu is open or the page is loading.
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400740 */
Michael Kolba2b2ba82010-08-04 17:54:03 -0700741 private TitleBarBase mFakeTitleBar;
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400742
743 /**
744 * Keeps track of whether the options menu is open. This is important in
745 * determining whether to show or hide the title bar overlay.
746 */
747 private boolean mOptionsMenuOpen;
748
749 /**
750 * Only meaningful when mOptionsMenuOpen is true. This variable keeps track
751 * of whether the configuration has changed. The first onMenuOpened call
752 * after a configuration change is simply a reopening of the same menu
753 * (i.e. mIconView did not change).
754 */
755 private boolean mConfigChanged;
756
757 /**
758 * Whether or not the options menu is in its smaller, icon menu form. When
759 * true, we want the title bar overlay to be up. When false, we do not.
760 * Only meaningful if mOptionsMenuOpen is true.
761 */
762 private boolean mIconView;
763
Leon Scrogginsa81a7642009-08-31 17:05:41 -0400764 @Override
765 public boolean onMenuOpened(int featureId, Menu menu) {
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400766 if (Window.FEATURE_OPTIONS_PANEL == featureId) {
767 if (mOptionsMenuOpen) {
768 if (mConfigChanged) {
769 // We do not need to make any changes to the state of the
770 // title bar, since the only thing that happened was a
771 // change in orientation
772 mConfigChanged = false;
773 } else {
774 if (mIconView) {
775 // Switching the menu to expanded view, so hide the
776 // title bar.
777 hideFakeTitleBar();
778 mIconView = false;
779 } else {
780 // Switching the menu back to icon view, so show the
781 // title bar once again.
782 showFakeTitleBar();
783 mIconView = true;
784 }
785 }
786 } else {
787 // The options menu is closed, so open it, and show the title
788 showFakeTitleBar();
789 mOptionsMenuOpen = true;
790 mConfigChanged = false;
791 mIconView = true;
792 }
793 }
Leon Scrogginsa81a7642009-08-31 17:05:41 -0400794 return true;
795 }
796
Michael Kolba2b2ba82010-08-04 17:54:03 -0700797 void showFakeTitleBar() {
798 if (!isFakeTitleBarShowing() && mActiveTabsPage == null && !mActivityInPause) {
Grace Kloba847c25b2010-03-30 16:00:26 -0700799 WebView mainView = mTabControl.getCurrentWebView();
800 // if there is no current WebView, don't show the faked title bar;
Grace Kloba65190702010-04-02 23:37:26 -0700801 if (mainView == null) {
Cary Clarka0464552009-09-29 13:00:45 -0400802 return;
803 }
Leon Scroggins79e36d92010-04-29 16:01:46 +0100804 // Do not need to check for null, since the current tab will have
805 // at least a main WebView, or we would have returned above.
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -0400806 if (isInCustomActionMode()) {
807 // Do not show the fake title bar, while a custom ActionMode
808 // (i.e. find or select) is showing.
Leon Scroggins79e36d92010-04-29 16:01:46 +0100809 return;
810 }
Michael Kolba2b2ba82010-08-04 17:54:03 -0700811 if (mXLargeScreenSize) {
812 mContentView.addView(mFakeTitleBar);
813 mTabBar.onShowTitleBar();
814 } else {
815 WindowManager manager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400816
Michael Kolba2b2ba82010-08-04 17:54:03 -0700817 // Add the title bar to the window manager so it can receive
818 // touches
819 // while the menu is up
820 WindowManager.LayoutParams params =
821 new WindowManager.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
822 ViewGroup.LayoutParams.WRAP_CONTENT,
823 WindowManager.LayoutParams.TYPE_APPLICATION,
824 WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
825 PixelFormat.TRANSLUCENT);
826 params.gravity = Gravity.TOP;
827 boolean atTop = mainView.getScrollY() == 0;
828 params.windowAnimations = atTop ? 0 : R.style.TitleBar;
829 manager.addView(mFakeTitleBar, params);
830 }
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400831 }
832 }
833
834 @Override
835 public void onOptionsMenuClosed(Menu menu) {
836 mOptionsMenuOpen = false;
Leon Scrogginsa27ff192009-09-14 12:58:04 -0400837 if (!mInLoad) {
838 hideFakeTitleBar();
839 } else if (!mIconView) {
840 // The page is currently loading, and we are in expanded mode, so
841 // we were not showing the menu. Show it once again. It will be
842 // removed when the page finishes.
843 showFakeTitleBar();
844 }
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400845 }
Grace Kloba22ac16e2009-10-07 18:00:23 -0700846
Michael Kolba2b2ba82010-08-04 17:54:03 -0700847 void stopScrolling() {
848 ((ScrollWebView) mTabControl.getCurrentWebView()).stopScroll();
849 }
850
851 void hideFakeTitleBar() {
852 if (!isFakeTitleBarShowing()) return;
853 if (mXLargeScreenSize) {
854 mContentView.removeView(mFakeTitleBar);
855 mTabBar.onHideTitleBar();
856 } else {
857 WindowManager.LayoutParams params =
858 (WindowManager.LayoutParams) mFakeTitleBar.getLayoutParams();
859 WebView mainView = mTabControl.getCurrentWebView();
860 // Although we decided whether or not to animate based on the
861 // current
862 // scroll position, the scroll position may have changed since the
863 // fake title bar was displayed. Make sure it has the appropriate
864 // animation/lack thereof before removing.
865 params.windowAnimations =
866 mainView != null && mainView.getScrollY() == 0 ? 0 : R.style.TitleBar;
867 WindowManager manager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
868 manager.updateViewLayout(mFakeTitleBar, params);
869 manager.removeView(mFakeTitleBar);
870 }
871 }
872
873 boolean isFakeTitleBarShowing() {
874 return (mFakeTitleBar.getParent() != null);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400875 }
876
The Android Open Source Project0c908882009-03-03 19:32:16 -0800877 /**
Leon Scrogginsc6fa1102009-09-21 10:40:01 -0400878 * Special method for the fake title bar to call when displaying its context
879 * menu, since it is in its own Window, and its parent does not show a
880 * context menu.
881 */
882 /* package */ void showTitleBarContextMenu() {
Cary Clark65f4a3c2009-09-28 17:05:06 -0400883 if (null == mTitleBar.getParent()) {
884 return;
885 }
Leon Scrogginsc6fa1102009-09-21 10:40:01 -0400886 openContextMenu(mTitleBar);
887 }
888
Leon Scrogginsb2b19f52009-10-09 16:10:00 -0400889 @Override
890 public void onContextMenuClosed(Menu menu) {
891 super.onContextMenuClosed(menu);
892 if (mInLoad) {
893 showFakeTitleBar();
894 }
895 }
896
Leon Scrogginsc6fa1102009-09-21 10:40:01 -0400897 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -0800898 * onSaveInstanceState(Bundle map)
899 * onSaveInstanceState is called right before onStop(). The map contains
900 * the saved state.
901 */
Grace Kloba22ac16e2009-10-07 18:00:23 -0700902 @Override
903 protected void onSaveInstanceState(Bundle outState) {
Dave Bort31a6d1c2009-04-13 15:56:49 -0700904 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800905 Log.v(LOGTAG, "BrowserActivity.onSaveInstanceState: this=" + this);
906 }
907 // the default implementation requires each view to have an id. As the
908 // browser handles the state itself and it doesn't use id for the views,
909 // don't call the default implementation. Otherwise it will trigger the
910 // warning like this, "couldn't save which view has focus because the
911 // focused view XXX has no id".
912
913 // Save all the tabs
914 mTabControl.saveState(outState);
Elliott Slaughter3d6df162010-08-25 13:17:44 -0700915
916 // Save time so that we know how old incognito tabs (if any) are.
917 outState.putSerializable("lastActiveDate", Calendar.getInstance());
The Android Open Source Project0c908882009-03-03 19:32:16 -0800918 }
919
Grace Kloba22ac16e2009-10-07 18:00:23 -0700920 @Override
921 protected void onPause() {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800922 super.onPause();
923
924 if (mActivityInPause) {
925 Log.e(LOGTAG, "BrowserActivity is already paused.");
926 return;
927 }
928
Mike Reed7bfa63b2009-05-28 11:08:32 -0400929 mTabControl.pauseCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800930 mActivityInPause = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -0400931 if (mTabControl.getCurrentIndex() >= 0 && !pauseWebViewTimers()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800932 mWakeLock.acquire();
933 mHandler.sendMessageDelayed(mHandler
934 .obtainMessage(RELEASE_WAKELOCK), WAKELOCK_TIMEOUT);
935 }
936
Leon Scrogginsa2ab6a72009-09-11 11:49:52 -0400937 // FIXME: This removes the active tabs page and resets the menu to
938 // MAIN_MENU. A better solution might be to do this work in onNewIntent
939 // but then we would need to save it in onSaveInstanceState and restore
940 // it in onCreate/onRestoreInstanceState
941 if (mActiveTabsPage != null) {
942 removeActiveTabPage(true);
943 }
944
The Android Open Source Project0c908882009-03-03 19:32:16 -0800945 cancelStopToast();
946
947 // unregister network state listener
948 unregisterReceiver(mNetworkStateIntentReceiver);
949 WebView.disablePlatformNotifications();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800950 }
951
Grace Kloba22ac16e2009-10-07 18:00:23 -0700952 @Override
953 protected void onDestroy() {
Dave Bort31a6d1c2009-04-13 15:56:49 -0700954 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800955 Log.v(LOGTAG, "BrowserActivity.onDestroy: this=" + this);
956 }
957 super.onDestroy();
Grace Kloba0923d692009-09-23 21:37:25 -0700958
Leon Scroggins8d5fa432009-10-02 15:55:59 -0400959 if (mUploadMessage != null) {
960 mUploadMessage.onReceiveValue(null);
961 mUploadMessage = null;
962 }
963
Grace Kloba0923d692009-09-23 21:37:25 -0700964 if (mTabControl == null) return;
965
Grace Kloba1fc98a32009-10-21 13:23:08 -0700966 // Remove the fake title bar if it is there
967 hideFakeTitleBar();
968
The Android Open Source Project0c908882009-03-03 19:32:16 -0800969 // Remove the current tab and sub window
Grace Kloba22ac16e2009-10-07 18:00:23 -0700970 Tab t = mTabControl.getCurrentTab();
Patrick Scottfb5e77f2009-04-08 19:17:37 -0700971 if (t != null) {
972 dismissSubWindow(t);
973 removeTabFromContentView(t);
974 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800975 // Destroy all the tabs
976 mTabControl.destroy();
977 WebIconDatabase.getInstance().close();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800978
Bjorn Bringerta7611812010-03-24 11:12:02 +0000979 // Stop watching the default geolocation permissions
980 mSystemAllowGeolocationOrigins.stop();
981 mSystemAllowGeolocationOrigins = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800982 }
983
984 @Override
985 public void onConfigurationChanged(Configuration newConfig) {
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400986 mConfigChanged = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800987 super.onConfigurationChanged(newConfig);
988
989 if (mPageInfoDialog != null) {
990 mPageInfoDialog.dismiss();
991 showPageInfo(
992 mPageInfoView,
Leon Scrogginsc7b92f82010-01-11 18:17:31 -0500993 mPageInfoFromShowSSLCertificateOnError);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800994 }
995 if (mSSLCertificateDialog != null) {
996 mSSLCertificateDialog.dismiss();
997 showSSLCertificate(
998 mSSLCertificateView);
999 }
1000 if (mSSLCertificateOnErrorDialog != null) {
1001 mSSLCertificateOnErrorDialog.dismiss();
1002 showSSLCertificateOnError(
1003 mSSLCertificateOnErrorView,
1004 mSSLCertificateOnErrorHandler,
1005 mSSLCertificateOnErrorError);
1006 }
1007 if (mHttpAuthenticationDialog != null) {
1008 String title = ((TextView) mHttpAuthenticationDialog
1009 .findViewById(com.android.internal.R.id.alertTitle)).getText()
1010 .toString();
1011 String name = ((TextView) mHttpAuthenticationDialog
1012 .findViewById(R.id.username_edit)).getText().toString();
1013 String password = ((TextView) mHttpAuthenticationDialog
1014 .findViewById(R.id.password_edit)).getText().toString();
1015 int focusId = mHttpAuthenticationDialog.getCurrentFocus()
1016 .getId();
1017 mHttpAuthenticationDialog.dismiss();
1018 showHttpAuthentication(mHttpAuthHandler, null, null, title,
1019 name, password, focusId);
1020 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001021 }
1022
Grace Kloba22ac16e2009-10-07 18:00:23 -07001023 @Override
1024 public void onLowMemory() {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001025 super.onLowMemory();
1026 mTabControl.freeMemory();
1027 }
1028
Cary Clarkff4d92c2010-03-25 11:17:03 -04001029 private void resumeWebViewTimers() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001030 Tab tab = mTabControl.getCurrentTab();
Cary Clarkff4d92c2010-03-25 11:17:03 -04001031 if (tab == null) return; // monkey can trigger this
Grace Kloba22ac16e2009-10-07 18:00:23 -07001032 boolean inLoad = tab.inLoad();
1033 if ((!mActivityInPause && !inLoad) || (mActivityInPause && inLoad)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001034 CookieSyncManager.getInstance().startSync();
Grace Kloba22ac16e2009-10-07 18:00:23 -07001035 WebView w = tab.getWebView();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001036 if (w != null) {
1037 w.resumeTimers();
1038 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001039 }
1040 }
1041
Mike Reed7bfa63b2009-05-28 11:08:32 -04001042 private boolean pauseWebViewTimers() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001043 Tab tab = mTabControl.getCurrentTab();
1044 boolean inLoad = tab.inLoad();
1045 if (mActivityInPause && !inLoad) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001046 CookieSyncManager.getInstance().stopSync();
1047 WebView w = mTabControl.getCurrentWebView();
1048 if (w != null) {
1049 w.pauseTimers();
1050 }
1051 return true;
1052 } else {
1053 return false;
1054 }
1055 }
1056
The Android Open Source Project0c908882009-03-03 19:32:16 -08001057 // Open the icon database and retain all the icons for visited sites.
1058 private void retainIconsOnStartup() {
1059 final WebIconDatabase db = WebIconDatabase.getInstance();
1060 db.open(getDir("icons", 0).getPath());
Leon Scroggins2c0f6112010-03-12 18:09:39 -05001061 Cursor c = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001062 try {
Leon Scroggins2c0f6112010-03-12 18:09:39 -05001063 c = Browser.getAllBookmarks(mResolver);
1064 if (c.moveToFirst()) {
1065 int urlIndex = c.getColumnIndex(Browser.BookmarkColumns.URL);
1066 do {
1067 String url = c.getString(urlIndex);
1068 db.retainIconForPageUrl(url);
1069 } while (c.moveToNext());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001070 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001071 } catch (IllegalStateException e) {
1072 Log.e(LOGTAG, "retainIconsOnStartup", e);
Leon Scroggins2c0f6112010-03-12 18:09:39 -05001073 } finally {
1074 if (c!= null) c.close();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001075 }
1076 }
1077
1078 // Helper method for getting the top window.
1079 WebView getTopWindow() {
1080 return mTabControl.getCurrentTopWebView();
1081 }
1082
Grace Kloba22ac16e2009-10-07 18:00:23 -07001083 TabControl getTabControl() {
1084 return mTabControl;
1085 }
1086
The Android Open Source Project0c908882009-03-03 19:32:16 -08001087 @Override
1088 public boolean onCreateOptionsMenu(Menu menu) {
1089 super.onCreateOptionsMenu(menu);
1090
1091 MenuInflater inflater = getMenuInflater();
1092 inflater.inflate(R.menu.browser, menu);
1093 mMenu = menu;
1094 updateInLoadMenuItems();
1095 return true;
1096 }
1097
1098 /**
1099 * As the menu can be open when loading state changes
1100 * we must manually update the state of the stop/reload menu
1101 * item
1102 */
1103 private void updateInLoadMenuItems() {
1104 if (mMenu == null) {
1105 return;
1106 }
Michael Kolbe0a36662010-06-29 10:37:12 -07001107 MenuItem dest = mMenu.findItem(R.id.stop_reload_menu_id);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001108 MenuItem src = mInLoad ?
1109 mMenu.findItem(R.id.stop_menu_id):
Michael Kolbe0a36662010-06-29 10:37:12 -07001110 mMenu.findItem(R.id.reload_menu_id);
1111 if (src != null) {
1112 dest.setIcon(src.getIcon());
1113 dest.setTitle(src.getTitle());
1114 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001115 }
1116
1117 @Override
1118 public boolean onContextItemSelected(MenuItem item) {
1119 // chording is not an issue with context menus, but we use the same
1120 // options selector, so set mCanChord to true so we can access them.
1121 mCanChord = true;
1122 int id = item.getItemId();
Leon Scroggins96afcb12009-12-10 12:35:56 -05001123 boolean result = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001124 switch (id) {
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001125 // For the context menu from the title bar
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001126 case R.id.title_bar_copy_page_url:
Leon Scroggins96afcb12009-12-10 12:35:56 -05001127 Tab currentTab = mTabControl.getCurrentTab();
1128 if (null == currentTab) {
1129 result = false;
1130 break;
1131 }
1132 WebView mainView = currentTab.getWebView();
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001133 if (null == mainView) {
Leon Scroggins96afcb12009-12-10 12:35:56 -05001134 result = false;
1135 break;
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001136 }
Leon Scroggins96afcb12009-12-10 12:35:56 -05001137 copy(mainView.getUrl());
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001138 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001139 // -- Browser context menu
1140 case R.id.open_context_menu_id:
The Android Open Source Project0c908882009-03-03 19:32:16 -08001141 case R.id.bookmark_context_menu_id:
1142 case R.id.save_link_context_menu_id:
1143 case R.id.share_link_context_menu_id:
1144 case R.id.copy_link_context_menu_id:
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001145 final WebView webView = getTopWindow();
1146 if (null == webView) {
Leon Scroggins96afcb12009-12-10 12:35:56 -05001147 result = false;
1148 break;
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001149 }
1150 final HashMap hrefMap = new HashMap();
1151 hrefMap.put("webview", webView);
1152 final Message msg = mHandler.obtainMessage(
1153 FOCUS_NODE_HREF, id, 0, hrefMap);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001154 webView.requestFocusNodeHref(msg);
1155 break;
1156
1157 default:
1158 // For other context menus
Leon Scroggins96afcb12009-12-10 12:35:56 -05001159 result = onOptionsItemSelected(item);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001160 }
1161 mCanChord = false;
Leon Scroggins96afcb12009-12-10 12:35:56 -05001162 return result;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001163 }
1164
1165 private Bundle createGoogleSearchSourceBundle(String source) {
1166 Bundle bundle = new Bundle();
Bjorn Bringert10d1cca2010-02-10 14:22:12 +00001167 bundle.putString(Search.SOURCE, source);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001168 return bundle;
1169 }
1170
Leon Scroggins8ad29922010-02-16 12:33:55 -05001171 /* package */ void editUrl() {
Leon Scroggins68579392009-09-15 15:31:54 -04001172 if (mOptionsMenuOpen) closeOptionsMenu();
Leon Scroggins5bbe9802009-07-31 13:10:55 -04001173 String url = (getTopWindow() == null) ? null : getTopWindow().getUrl();
Grace Kloba83f47342009-07-20 10:44:31 -07001174 startSearch(mSettings.getHomePage().equals(url) ? null : url, true,
Leon Scroggins8ad29922010-02-16 12:33:55 -05001175 null, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001176 }
1177
Leon Scroggins8ad29922010-02-16 12:33:55 -05001178 /**
1179 * Overriding this to insert a local information bundle
1180 */
The Android Open Source Project0c908882009-03-03 19:32:16 -08001181 @Override
1182 public void startSearch(String initialQuery, boolean selectInitialQuery,
1183 Bundle appSearchData, boolean globalSearch) {
1184 if (appSearchData == null) {
1185 appSearchData = createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_TYPE);
1186 }
Leon Scroggins III430057d2010-09-14 10:57:37 -04001187
1188 SearchEngine searchEngine = mSettings.getSearchEngine();
1189 if (searchEngine != null && !searchEngine.supportsVoiceSearch()) {
1190 appSearchData.putBoolean(SearchManager.DISABLE_VOICE_SEARCH, true);
1191 }
1192
The Android Open Source Project0c908882009-03-03 19:32:16 -08001193 super.startSearch(initialQuery, selectInitialQuery, appSearchData, globalSearch);
1194 }
1195
Leon Scroggins1f005d32009-08-10 17:36:42 -04001196 /**
1197 * Switch tabs. Called by the TitleBarSet when sliding the title bar
1198 * results in changing tabs.
Leon Scroggins160a7e72009-08-14 18:28:01 -04001199 * @param index Index of the tab to change to, as defined by
1200 * mTabControl.getTabIndex(Tab t).
1201 * @return boolean True if we successfully switched to a different tab. If
1202 * the indexth tab is null, or if that tab is the same as
1203 * the current one, return false.
Leon Scroggins1f005d32009-08-10 17:36:42 -04001204 */
Leon Scroggins160a7e72009-08-14 18:28:01 -04001205 /* package */ boolean switchToTab(int index) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001206 Tab tab = mTabControl.getTab(index);
1207 Tab currentTab = mTabControl.getCurrentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04001208 if (tab == null || tab == currentTab) {
Leon Scroggins160a7e72009-08-14 18:28:01 -04001209 return false;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001210 }
1211 if (currentTab != null) {
1212 // currentTab may be null if it was just removed. In that case,
1213 // we do not need to remove it
1214 removeTabFromContentView(currentTab);
1215 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001216 mTabControl.setCurrentTab(tab);
1217 attachTabToContentView(tab);
Grace Klobaeb6eef42009-09-15 17:56:32 -07001218 resetTitleIconAndProgress();
1219 updateLockIconToLatest();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001220 return true;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001221 }
1222
Grace Kloba22ac16e2009-10-07 18:00:23 -07001223 /* package */ Tab openTabToHomePage() {
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001224 return openTabAndShow(mSettings.getHomePage(), false, null);
1225 }
1226
Leon Scroggins1f005d32009-08-10 17:36:42 -04001227 /* package */ void closeCurrentWindow() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001228 final Tab current = mTabControl.getCurrentTab();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001229 if (mTabControl.getTabCount() == 1) {
Leon Scroggins30444232009-09-04 18:36:20 -04001230 // This is the last tab. Open a new one, with the home
1231 // page and close the current one.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001232 openTabToHomePage();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001233 closeTab(current);
Leon Scroggins160a7e72009-08-14 18:28:01 -04001234 return;
1235 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07001236 final Tab parent = current.getParentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04001237 int indexToShow = -1;
1238 if (parent != null) {
1239 indexToShow = mTabControl.getTabIndex(parent);
1240 } else {
Leon Scroggins160a7e72009-08-14 18:28:01 -04001241 final int currentIndex = mTabControl.getCurrentIndex();
1242 // Try to move to the tab to the right
1243 indexToShow = currentIndex + 1;
1244 if (indexToShow > mTabControl.getTabCount() - 1) {
1245 // Try to move to the tab to the left
1246 indexToShow = currentIndex - 1;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001247 }
1248 }
Leon Scroggins160a7e72009-08-14 18:28:01 -04001249 if (switchToTab(indexToShow)) {
1250 // Close window
1251 closeTab(current);
1252 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001253 }
1254
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001255 private ActiveTabsPage mActiveTabsPage;
1256
1257 /**
1258 * Remove the active tabs page.
1259 * @param needToAttach If true, the active tabs page did not attach a tab
1260 * to the content view, so we need to do that here.
1261 */
1262 /* package */ void removeActiveTabPage(boolean needToAttach) {
1263 mContentView.removeView(mActiveTabsPage);
Leon Scrogginsd746a942010-05-19 13:21:44 -04001264 mTitleBar.setVisibility(View.VISIBLE);
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001265 mActiveTabsPage = null;
1266 mMenuState = R.id.MAIN_MENU;
1267 if (needToAttach) {
1268 attachTabToContentView(mTabControl.getCurrentTab());
1269 }
1270 getTopWindow().requestFocus();
1271 }
1272
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04001273 @Override
1274 public ActionMode onStartActionMode(ActionMode.Callback callback) {
Leon Scroggins4fc12cb2010-08-24 14:24:05 -04001275 mActionMode = super.onStartActionMode(callback);
1276 hideFakeTitleBar();
1277 // Would like to change the MENU, but onEndActionMode may not be called
1278 return mActionMode;
Cary Clark01cfcdd2010-06-04 16:36:45 -04001279 }
1280
The Android Open Source Project0c908882009-03-03 19:32:16 -08001281 @Override
1282 public boolean onOptionsItemSelected(MenuItem item) {
Michael Kolb370a4f32010-10-06 10:45:32 -07001283 if (item.getGroupId() != R.id.CONTEXT_MENU) {
1284 // menu remains active, so ensure comboview is dismissed
1285 // if main menu option is selected
1286 removeComboView();
1287 }
Michael Kolbed217742010-08-10 17:52:34 -07001288 // check the action bar button before mCanChord check, as the prepare call
1289 // doesn't come for action bar buttons
1290 if (item.getItemId() == R.id.newtab) {
Michael Kolb300b7f02010-08-25 13:47:24 -07001291 openTabToHomePage();
Michael Kolbed217742010-08-10 17:52:34 -07001292 return true;
1293 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001294 if (!mCanChord) {
1295 // The user has already fired a shortcut with this hold down of the
1296 // menu key.
1297 return false;
1298 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001299 if (null == getTopWindow()) {
Leon Scroggins0d7ae0e2009-06-05 11:04:45 -04001300 return false;
1301 }
Grace Kloba6ee9c492009-07-13 10:04:34 -07001302 if (mMenuIsDown) {
1303 // The shortcut action consumes the MENU. Even if it is still down,
1304 // it won't trigger the next shortcut action. In the case of the
1305 // shortcut action triggering a new activity, like Bookmarks, we
1306 // won't get onKeyUp for MENU. So it is important to reset it here.
1307 mMenuIsDown = false;
1308 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001309 switch (item.getItemId()) {
1310 // -- Main menu
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001311 case R.id.new_tab_menu_id:
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001312 openTabToHomePage();
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001313 break;
1314
Michael Kolbae62fd42010-08-18 16:33:28 -07001315 case R.id.incognito_menu_id:
1316 openIncognitoTab();
1317 break;
1318
Leon Scroggins64b80f32009-08-07 12:03:34 -04001319 case R.id.goto_menu_id:
Leon Scroggins8ad29922010-02-16 12:33:55 -05001320 editUrl();
Leon Scrogginsb3a5bed2009-09-28 11:21:56 -04001321 break;
1322
1323 case R.id.bookmarks_menu_id:
Michael Kolbe421c242010-10-04 19:29:01 -07001324 bookmarksOrHistoryPicker(false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001325 break;
1326
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001327 case R.id.active_tabs_menu_id:
1328 mActiveTabsPage = new ActiveTabsPage(this, mTabControl);
1329 removeTabFromContentView(mTabControl.getCurrentTab());
Leon Scrogginsd746a942010-05-19 13:21:44 -04001330 mTitleBar.setVisibility(View.GONE);
Leon Scroggins43de6162009-09-14 19:59:58 -04001331 hideFakeTitleBar();
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001332 mContentView.addView(mActiveTabsPage, COVER_SCREEN_PARAMS);
1333 mActiveTabsPage.requestFocus();
1334 mMenuState = EMPTY_MENU;
1335 break;
1336
Leon Scroggins1f005d32009-08-10 17:36:42 -04001337 case R.id.add_bookmark_menu_id:
Michael Kolb370a4f32010-10-06 10:45:32 -07001338 bookmarkCurrentPage(AddBookmarkPage.DEFAULT_FOLDER_ID);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001339 break;
1340
1341 case R.id.stop_reload_menu_id:
1342 if (mInLoad) {
1343 stopLoading();
1344 } else {
1345 getTopWindow().reload();
1346 }
1347 break;
1348
1349 case R.id.back_menu_id:
1350 getTopWindow().goBack();
1351 break;
1352
1353 case R.id.forward_menu_id:
1354 getTopWindow().goForward();
1355 break;
1356
1357 case R.id.close_menu_id:
1358 // Close the subwindow if it exists.
1359 if (mTabControl.getCurrentSubWindow() != null) {
1360 dismissSubWindow(mTabControl.getCurrentTab());
1361 break;
1362 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001363 closeCurrentWindow();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001364 break;
1365
1366 case R.id.homepage_menu_id:
Grace Kloba22ac16e2009-10-07 18:00:23 -07001367 Tab current = mTabControl.getCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001368 if (current != null) {
1369 dismissSubWindow(current);
Leon Scroggins92472e82010-02-17 16:32:28 -05001370 loadUrl(current.getWebView(), mSettings.getHomePage());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001371 }
1372 break;
1373
1374 case R.id.preferences_menu_id:
1375 Intent intent = new Intent(this,
1376 BrowserPreferencesPage.class);
Leon Scrogginsd5304942009-12-10 16:11:39 -05001377 intent.putExtra(BrowserPreferencesPage.CURRENT_PAGE,
1378 getTopWindow().getUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001379 startActivityForResult(intent, PREFERENCES_PAGE);
1380 break;
1381
1382 case R.id.find_menu_id:
Leon Scroggins4fc12cb2010-08-24 14:24:05 -04001383 getTopWindow().showFindDialog(null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001384 break;
1385
Elliott Slaughter0ced08c2010-06-30 11:40:42 -07001386 case R.id.save_webarchive_menu_id:
1387 if (LOGD_ENABLED) {
1388 Log.d(LOGTAG, "Save as Web Archive");
1389 }
Elliott Slaughteraba242c2010-09-01 16:21:07 -07001390 String state = Environment.getExternalStorageState();
1391 if (Environment.MEDIA_MOUNTED.equals(state)) {
1392 String directory = Environment.getExternalStoragePublicDirectory(
1393 Environment.DIRECTORY_DOWNLOADS).getAbsolutePath() + File.separator;
Shimeng (Simon) Wang447c8462010-09-15 18:16:55 -07001394 File dir = new File(directory);
1395 if (!dir.exists() && !dir.mkdirs()) {
1396 Log.e(LOGTAG, "Save as Web Archive: mkdirs for " + directory + " failed!");
1397 Toast.makeText(BrowserActivity.this, R.string.webarchive_failed,
1398 Toast.LENGTH_SHORT).show();
1399 break;
1400 }
Elliott Slaughteraba242c2010-09-01 16:21:07 -07001401 getTopWindow().saveWebArchive(directory, true, new ValueCallback<String>() {
1402 @Override
1403 public void onReceiveValue(String value) {
1404 if (value != null) {
1405 Toast.makeText(BrowserActivity.this, R.string.webarchive_saved,
1406 Toast.LENGTH_SHORT).show();
1407 } else {
1408 Toast.makeText(BrowserActivity.this, R.string.webarchive_failed,
1409 Toast.LENGTH_SHORT).show();
1410 }
Elliott Slaughter0ced08c2010-06-30 11:40:42 -07001411 }
Elliott Slaughteraba242c2010-09-01 16:21:07 -07001412 });
1413 } else {
1414 Toast.makeText(BrowserActivity.this, R.string.webarchive_failed,
1415 Toast.LENGTH_SHORT).show();
1416 }
Elliott Slaughter0ced08c2010-06-30 11:40:42 -07001417 break;
1418
The Android Open Source Project0c908882009-03-03 19:32:16 -08001419 case R.id.page_info_menu_id:
1420 showPageInfo(mTabControl.getCurrentTab(), false);
1421 break;
1422
1423 case R.id.classic_history_menu_id:
Michael Kolbe421c242010-10-04 19:29:01 -07001424 bookmarksOrHistoryPicker(true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001425 break;
1426
Leon Scroggins96afcb12009-12-10 12:35:56 -05001427 case R.id.title_bar_share_page_url:
The Android Open Source Project0c908882009-03-03 19:32:16 -08001428 case R.id.share_page_menu_id:
Leon Scroggins96afcb12009-12-10 12:35:56 -05001429 Tab currentTab = mTabControl.getCurrentTab();
1430 if (null == currentTab) {
1431 mCanChord = false;
1432 return false;
1433 }
1434 currentTab.populatePickerData();
1435 sharePage(this, currentTab.getTitle(),
1436 currentTab.getUrl(), currentTab.getFavicon(),
Ben Murdoch87cc65d2010-06-29 20:34:10 +01001437 createScreenshot(currentTab.getWebView(), getDesiredThumbnailWidth(this),
1438 getDesiredThumbnailHeight(this)));
The Android Open Source Project0c908882009-03-03 19:32:16 -08001439 break;
1440
1441 case R.id.dump_nav_menu_id:
1442 getTopWindow().debugDump();
1443 break;
1444
Andrei Popescu7a8b88b2010-02-02 00:30:38 +00001445 case R.id.dump_counters_menu_id:
1446 getTopWindow().dumpV8Counters();
1447 break;
1448
The Android Open Source Project0c908882009-03-03 19:32:16 -08001449 case R.id.zoom_in_menu_id:
1450 getTopWindow().zoomIn();
1451 break;
1452
1453 case R.id.zoom_out_menu_id:
1454 getTopWindow().zoomOut();
1455 break;
1456
1457 case R.id.view_downloads_menu_id:
Leon Scroggins IIIa682a3c2010-09-27 12:32:40 -04001458 viewDownloads();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001459 break;
1460
The Android Open Source Project0c908882009-03-03 19:32:16 -08001461 case R.id.window_one_menu_id:
1462 case R.id.window_two_menu_id:
1463 case R.id.window_three_menu_id:
1464 case R.id.window_four_menu_id:
1465 case R.id.window_five_menu_id:
1466 case R.id.window_six_menu_id:
1467 case R.id.window_seven_menu_id:
1468 case R.id.window_eight_menu_id:
1469 {
1470 int menuid = item.getItemId();
1471 for (int id = 0; id < WINDOW_SHORTCUT_ID_ARRAY.length; id++) {
1472 if (WINDOW_SHORTCUT_ID_ARRAY[id] == menuid) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001473 Tab desiredTab = mTabControl.getTab(id);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001474 if (desiredTab != null &&
1475 desiredTab != mTabControl.getCurrentTab()) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001476 switchToTab(id);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001477 }
1478 break;
1479 }
1480 }
1481 }
1482 break;
1483
1484 default:
1485 if (!super.onOptionsItemSelected(item)) {
1486 return false;
1487 }
1488 // Otherwise fall through.
1489 }
1490 mCanChord = false;
1491 return true;
1492 }
1493
Michael Kolb370a4f32010-10-06 10:45:32 -07001494 /**
1495 * add the current page as a bookmark to the given folder id
1496 * @param folderId use -1 for the default folder
1497 */
1498 /* package */ void bookmarkCurrentPage(long folderId) {
Leon Scroggins571b3762010-05-26 10:25:01 -04001499 Intent i = new Intent(BrowserActivity.this,
1500 AddBookmarkPage.class);
1501 WebView w = getTopWindow();
1502 i.putExtra("url", w.getUrl());
1503 i.putExtra("title", w.getTitle());
1504 i.putExtra("touch_icon_url", w.getTouchIconUrl());
Ben Murdoch87cc65d2010-06-29 20:34:10 +01001505 i.putExtra("thumbnail", createScreenshot(w, getDesiredThumbnailWidth(this),
1506 getDesiredThumbnailHeight(this)));
Michael Kolb370a4f32010-10-06 10:45:32 -07001507 i.putExtra(BrowserContract.Bookmarks.PARENT,
1508 folderId);
Leon Scroggins III76a0e9c2010-10-05 16:10:01 -04001509 // Put the dialog at the upper right of the screen, covering the
1510 // star on the title bar.
1511 i.putExtra("gravity", Gravity.RIGHT | Gravity.TOP);
Leon Scroggins571b3762010-05-26 10:25:01 -04001512 startActivity(i);
1513 }
1514
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04001515 /*
1516 * True if a custom ActionMode (i.e. find or select) is in use.
1517 */
1518 private boolean isInCustomActionMode() {
1519 return mActionMode != null;
Cary Clark01cfcdd2010-06-04 16:36:45 -04001520 }
1521
1522 /*
Leon Scroggins4fc12cb2010-08-24 14:24:05 -04001523 * End the current ActionMode.
Cary Clark01cfcdd2010-06-04 16:36:45 -04001524 */
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04001525 void endActionMode() {
1526 if (mActionMode != null) {
Leon Scroggins4fc12cb2010-08-24 14:24:05 -04001527 ActionMode mode = mActionMode;
1528 onEndActionMode();
1529 mode.finish();
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04001530 }
1531 }
1532
1533 /*
1534 * Called by find and select when they are finished. Replace title bars
1535 * as necessary.
1536 */
1537 public void onEndActionMode() {
1538 if (!isInCustomActionMode()) return;
Leon Scroggins79e36d92010-04-29 16:01:46 +01001539 if (mInLoad) {
1540 // The title bar was hidden, because otherwise it would cover up the
Michael Kolba2b2ba82010-08-04 17:54:03 -07001541 // find or select dialog. Now that the dialog has been removed,
Cary Clark01cfcdd2010-06-04 16:36:45 -04001542 // show the fake title bar once again.
Leon Scroggins79e36d92010-04-29 16:01:46 +01001543 showFakeTitleBar();
1544 }
Leon Scroggins4fc12cb2010-08-24 14:24:05 -04001545 // Would like to return the menu state to normal, but this does not
1546 // necessarily get called.
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04001547 mActionMode = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001548 }
1549
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04001550 // For select and find, we keep track of the ActionMode so that
1551 // finish() can be called as desired.
1552 private ActionMode mActionMode;
1553
Grace Kloba22ac16e2009-10-07 18:00:23 -07001554 @Override
1555 public boolean onPrepareOptionsMenu(Menu menu) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001556 // This happens when the user begins to hold down the menu key, so
1557 // allow them to chord to get a shortcut.
1558 mCanChord = true;
1559 // Note: setVisible will decide whether an item is visible; while
1560 // setEnabled() will decide whether an item is enabled, which also means
1561 // whether the matching shortcut key will function.
1562 super.onPrepareOptionsMenu(menu);
1563 switch (mMenuState) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001564 case EMPTY_MENU:
1565 if (mCurrentMenuState != mMenuState) {
1566 menu.setGroupVisible(R.id.MAIN_MENU, false);
1567 menu.setGroupEnabled(R.id.MAIN_MENU, false);
1568 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001569 }
1570 break;
1571 default:
1572 if (mCurrentMenuState != mMenuState) {
1573 menu.setGroupVisible(R.id.MAIN_MENU, true);
1574 menu.setGroupEnabled(R.id.MAIN_MENU, true);
1575 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001576 }
1577 final WebView w = getTopWindow();
1578 boolean canGoBack = false;
1579 boolean canGoForward = false;
1580 boolean isHome = false;
1581 if (w != null) {
1582 canGoBack = w.canGoBack();
1583 canGoForward = w.canGoForward();
1584 isHome = mSettings.getHomePage().equals(w.getUrl());
1585 }
1586 final MenuItem back = menu.findItem(R.id.back_menu_id);
1587 back.setEnabled(canGoBack);
1588
1589 final MenuItem home = menu.findItem(R.id.homepage_menu_id);
1590 home.setEnabled(!isHome);
1591
Michael Kolbe0a36662010-06-29 10:37:12 -07001592 final MenuItem forward = menu.findItem(R.id.forward_menu_id);
1593 forward.setEnabled(canGoForward);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001594
Michael Kolbed217742010-08-10 17:52:34 -07001595 if (!mXLargeScreenSize) {
1596 final MenuItem newtab = menu.findItem(R.id.new_tab_menu_id);
1597 newtab.setEnabled(mTabControl.canCreateNewTab());
1598 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001599 // decide whether to show the share link option
1600 PackageManager pm = getPackageManager();
1601 Intent send = new Intent(Intent.ACTION_SEND);
1602 send.setType("text/plain");
1603 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1604 menu.findItem(R.id.share_page_menu_id).setVisible(ri != null);
1605
The Android Open Source Project0c908882009-03-03 19:32:16 -08001606 boolean isNavDump = mSettings.isNavDump();
1607 final MenuItem nav = menu.findItem(R.id.dump_nav_menu_id);
1608 nav.setVisible(isNavDump);
1609 nav.setEnabled(isNavDump);
Andrei Popescu7a8b88b2010-02-02 00:30:38 +00001610
1611 boolean showDebugSettings = mSettings.showDebugSettings();
1612 final MenuItem counter = menu.findItem(R.id.dump_counters_menu_id);
1613 counter.setVisible(showDebugSettings);
1614 counter.setEnabled(showDebugSettings);
1615
The Android Open Source Project0c908882009-03-03 19:32:16 -08001616 break;
1617 }
1618 mCurrentMenuState = mMenuState;
1619 return true;
1620 }
1621
1622 @Override
1623 public void onCreateContextMenu(ContextMenu menu, View v,
1624 ContextMenuInfo menuInfo) {
Leon Scroggins571b3762010-05-26 10:25:01 -04001625 if (v instanceof TitleBarBase) {
Leon Scroggins4e9f89b2010-02-22 16:54:14 -05001626 return;
1627 }
Michael Kolb772927a2010-10-13 19:23:42 -07001628 if (!(v instanceof WebView)) {
1629 return;
1630 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001631 WebView webview = (WebView) v;
1632 WebView.HitTestResult result = webview.getHitTestResult();
1633 if (result == null) {
1634 return;
1635 }
1636
1637 int type = result.getType();
1638 if (type == WebView.HitTestResult.UNKNOWN_TYPE) {
1639 Log.w(LOGTAG,
1640 "We should not show context menu when nothing is touched");
1641 return;
1642 }
1643 if (type == WebView.HitTestResult.EDIT_TEXT_TYPE) {
1644 // let TextView handles context menu
1645 return;
1646 }
1647
1648 // Note, http://b/issue?id=1106666 is requesting that
1649 // an inflated menu can be used again. This is not available
1650 // yet, so inflate each time (yuk!)
1651 MenuInflater inflater = getMenuInflater();
1652 inflater.inflate(R.menu.browsercontext, menu);
1653
1654 // Show the correct menu group
Leon Scroggins III9e997c72010-05-26 13:25:16 -04001655 final String extra = result.getExtra();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001656 menu.setGroupVisible(R.id.PHONE_MENU,
1657 type == WebView.HitTestResult.PHONE_TYPE);
1658 menu.setGroupVisible(R.id.EMAIL_MENU,
1659 type == WebView.HitTestResult.EMAIL_TYPE);
1660 menu.setGroupVisible(R.id.GEO_MENU,
1661 type == WebView.HitTestResult.GEO_TYPE);
1662 menu.setGroupVisible(R.id.IMAGE_MENU,
1663 type == WebView.HitTestResult.IMAGE_TYPE
1664 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1665 menu.setGroupVisible(R.id.ANCHOR_MENU,
1666 type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1667 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1668
1669 // Setup custom handling depending on the type
1670 switch (type) {
1671 case WebView.HitTestResult.PHONE_TYPE:
1672 menu.setHeaderTitle(Uri.decode(extra));
1673 menu.findItem(R.id.dial_context_menu_id).setIntent(
1674 new Intent(Intent.ACTION_VIEW, Uri
1675 .parse(WebView.SCHEME_TEL + extra)));
1676 Intent addIntent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
1677 addIntent.putExtra(Insert.PHONE, Uri.decode(extra));
Cary Clark5e335a32009-09-22 14:53:11 -04001678 addIntent.setType(ContactsContract.Contacts.CONTENT_ITEM_TYPE);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001679 menu.findItem(R.id.add_contact_context_menu_id).setIntent(
1680 addIntent);
1681 menu.findItem(R.id.copy_phone_context_menu_id).setOnMenuItemClickListener(
1682 new Copy(extra));
1683 break;
1684
1685 case WebView.HitTestResult.EMAIL_TYPE:
1686 menu.setHeaderTitle(extra);
1687 menu.findItem(R.id.email_context_menu_id).setIntent(
1688 new Intent(Intent.ACTION_VIEW, Uri
1689 .parse(WebView.SCHEME_MAILTO + extra)));
1690 menu.findItem(R.id.copy_mail_context_menu_id).setOnMenuItemClickListener(
1691 new Copy(extra));
1692 break;
1693
1694 case WebView.HitTestResult.GEO_TYPE:
1695 menu.setHeaderTitle(extra);
1696 menu.findItem(R.id.map_context_menu_id).setIntent(
1697 new Intent(Intent.ACTION_VIEW, Uri
1698 .parse(WebView.SCHEME_GEO
1699 + URLEncoder.encode(extra))));
1700 menu.findItem(R.id.copy_geo_context_menu_id).setOnMenuItemClickListener(
1701 new Copy(extra));
1702 break;
1703
1704 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1705 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
1706 TextView titleView = (TextView) LayoutInflater.from(this)
1707 .inflate(android.R.layout.browser_link_context_header,
1708 null);
1709 titleView.setText(extra);
1710 menu.setHeaderView(titleView);
1711 // decide whether to show the open link in new tab option
Leon Scroggins III9e997c72010-05-26 13:25:16 -04001712 boolean showNewTab = mTabControl.canCreateNewTab();
1713 MenuItem newTabItem
1714 = menu.findItem(R.id.open_newtab_context_menu_id);
1715 newTabItem.setVisible(showNewTab);
1716 if (showNewTab) {
1717 newTabItem.setOnMenuItemClickListener(
1718 new MenuItem.OnMenuItemClickListener() {
1719 public boolean onMenuItemClick(MenuItem item) {
1720 final Tab parent = mTabControl.getCurrentTab();
Michael Kolb68792c82010-08-09 16:39:18 -07001721 final Tab newTab = openTab(extra, false);
Leon Scroggins III9e997c72010-05-26 13:25:16 -04001722 if (newTab != parent) {
1723 parent.addChildTab(newTab);
1724 }
1725 return true;
1726 }
1727 });
1728 }
Ben Murdochde353622009-10-12 10:29:00 +01001729 menu.findItem(R.id.bookmark_context_menu_id).setVisible(
1730 Bookmarks.urlHasAcceptableScheme(extra));
The Android Open Source Project0c908882009-03-03 19:32:16 -08001731 PackageManager pm = getPackageManager();
1732 Intent send = new Intent(Intent.ACTION_SEND);
1733 send.setType("text/plain");
1734 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1735 menu.findItem(R.id.share_link_context_menu_id).setVisible(ri != null);
1736 if (type == WebView.HitTestResult.SRC_ANCHOR_TYPE) {
1737 break;
1738 }
1739 // otherwise fall through to handle image part
1740 case WebView.HitTestResult.IMAGE_TYPE:
1741 if (type == WebView.HitTestResult.IMAGE_TYPE) {
1742 menu.setHeaderTitle(extra);
1743 }
1744 menu.findItem(R.id.view_image_context_menu_id).setIntent(
1745 new Intent(Intent.ACTION_VIEW, Uri.parse(extra)));
1746 menu.findItem(R.id.download_context_menu_id).
1747 setOnMenuItemClickListener(new Download(extra));
Ben Murdoch4f75ba22009-10-27 11:48:28 +00001748 menu.findItem(R.id.set_wallpaper_context_menu_id).
1749 setOnMenuItemClickListener(new SetAsWallpaper(extra));
The Android Open Source Project0c908882009-03-03 19:32:16 -08001750 break;
1751
1752 default:
1753 Log.w(LOGTAG, "We should not get here.");
1754 break;
1755 }
Leon Scrogginsb2b19f52009-10-09 16:10:00 -04001756 hideFakeTitleBar();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001757 }
1758
The Android Open Source Project0c908882009-03-03 19:32:16 -08001759 // Attach the given tab to the content view.
Grace Klobac928c302009-09-17 11:51:21 -07001760 // this should only be called for the current tab.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001761 private void attachTabToContentView(Tab t) {
Steve Block2bc69912009-07-30 14:45:13 +01001762 // Attach the container that contains the main WebView and any other UI
1763 // associated with the tab.
Patrick Scottd0119532009-09-17 08:00:31 -04001764 t.attachTabToContentView(mContentView);
Ben Murdochbff2d602009-07-01 20:19:05 +01001765
1766 if (mShouldShowErrorConsole) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001767 ErrorConsoleView errorConsole = t.getErrorConsole(true);
Ben Murdochbff2d602009-07-01 20:19:05 +01001768 if (errorConsole.numberOfErrors() == 0) {
1769 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
1770 } else {
1771 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
1772 }
1773
1774 mErrorConsoleContainer.addView(errorConsole,
Romain Guy15b8ec62010-01-08 15:06:43 -08001775 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
Ben Murdochbff2d602009-07-01 20:19:05 +01001776 ViewGroup.LayoutParams.WRAP_CONTENT));
1777 }
1778
Michael Kolba2b2ba82010-08-04 17:54:03 -07001779 WebView view = t.getWebView();
1780 view.setEmbeddedTitleBar(mTitleBar);
Leon Scroggins58d56c62010-01-28 15:12:40 -05001781 if (t.isInVoiceSearchMode()) {
1782 showVoiceTitleBar(t.getVoiceDisplayTitle());
1783 } else {
1784 revertVoiceTitleBar();
1785 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001786 // Request focus on the top window.
1787 t.getTopWindow().requestFocus();
Michael Kolba2b2ba82010-08-04 17:54:03 -07001788 if (mTabControl.getTabChangeListener() != null) {
1789 mTabControl.getTabChangeListener().onCurrentTab(t);
1790 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001791 }
1792
1793 // Attach a sub window to the main WebView of the given tab.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001794 void attachSubWindow(Tab t) {
Patrick Scottd0119532009-09-17 08:00:31 -04001795 t.attachSubWindow(mContentView);
1796 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001797 }
1798
1799 // Remove the given tab from the content view.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001800 private void removeTabFromContentView(Tab t) {
Steve Block2bc69912009-07-30 14:45:13 +01001801 // Remove the container that contains the main WebView.
Patrick Scottd0119532009-09-17 08:00:31 -04001802 t.removeTabFromContentView(mContentView);
Ben Murdochbff2d602009-07-01 20:19:05 +01001803
Grace Kloba22ac16e2009-10-07 18:00:23 -07001804 ErrorConsoleView errorConsole = t.getErrorConsole(false);
1805 if (errorConsole != null) {
1806 mErrorConsoleContainer.removeView(errorConsole);
Ben Murdochbff2d602009-07-01 20:19:05 +01001807 }
1808
Michael Kolba2b2ba82010-08-04 17:54:03 -07001809 WebView view = t.getWebView();
1810 if (view != null) {
1811 view.setEmbeddedTitleBar(null);
Leon Scrogginsbb85b902009-09-14 19:27:20 -04001812 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001813 }
1814
1815 // Remove the sub window if it exists. Also called by TabControl when the
1816 // user clicks the 'X' to dismiss a sub window.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001817 /* package */ void dismissSubWindow(Tab t) {
Patrick Scottd0119532009-09-17 08:00:31 -04001818 t.removeSubWindow(mContentView);
Grace Kloba22ac16e2009-10-07 18:00:23 -07001819 // dismiss the subwindow. This will destroy the WebView.
1820 t.dismissSubWindow();
Patrick Scottd0119532009-09-17 08:00:31 -04001821 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001822 }
1823
Leon Scroggins1f005d32009-08-10 17:36:42 -04001824 // A wrapper function of {@link #openTabAndShow(UrlData, boolean, String)}
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07001825 // that accepts url as string.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001826 private Tab openTabAndShow(String url, boolean closeOnExit, String appId) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001827 return openTabAndShow(new UrlData(url), closeOnExit, appId);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001828 }
1829
1830 // This method does a ton of stuff. It will attempt to create a new tab
1831 // if we haven't reached MAX_TABS. Otherwise it uses the current tab. If
Leon Scroggins1f005d32009-08-10 17:36:42 -04001832 // url isn't null, it will load the given url.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001833 /* package */Tab openTabAndShow(UrlData urlData, boolean closeOnExit,
1834 String appId) {
1835 final Tab currentTab = mTabControl.getCurrentTab();
1836 if (mTabControl.canCreateNewTab()) {
1837 final Tab tab = mTabControl.createNewTab(closeOnExit, appId,
Elliott Slaughterf0f03952010-07-14 18:10:36 -07001838 urlData.mUrl, false);
Leon Scroggins1f005d32009-08-10 17:36:42 -04001839 WebView webview = tab.getWebView();
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001840 // If the last tab was removed from the active tabs page, currentTab
1841 // will be null.
1842 if (currentTab != null) {
1843 removeTabFromContentView(currentTab);
1844 }
Patrick Scott8bbd69f2009-08-14 13:35:53 -04001845 // We must set the new tab as the current tab to reflect the old
1846 // animation behavior.
1847 mTabControl.setCurrentTab(tab);
Grace Klobaeb6eef42009-09-15 17:56:32 -07001848 attachTabToContentView(tab);
Leon Scroggins160a7e72009-08-14 18:28:01 -04001849 if (!urlData.isEmpty()) {
Patrick Scott9d53da02010-02-19 10:19:01 -05001850 loadUrlDataIn(tab, urlData);
Leon Scroggins1f005d32009-08-10 17:36:42 -04001851 }
1852 return tab;
1853 } else {
1854 // Get rid of the subwindow if it exists
1855 dismissSubWindow(currentTab);
1856 if (!urlData.isEmpty()) {
1857 // Load the given url.
Patrick Scott9d53da02010-02-19 10:19:01 -05001858 loadUrlDataIn(currentTab, urlData);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001859 }
Leon Scroggins58d56c62010-01-28 15:12:40 -05001860 return currentTab;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001861 }
1862 }
1863
Michael Kolb68792c82010-08-09 16:39:18 -07001864 private Tab openTab(String url, boolean forceForeground) {
1865 if (mSettings.openInBackground() && !forceForeground) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001866 Tab t = mTabControl.createNewTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001867 if (t != null) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001868 WebView view = t.getWebView();
Leon Scroggins92472e82010-02-17 16:32:28 -05001869 loadUrl(view, url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001870 }
Grace Klobac9181842009-04-14 08:53:22 -07001871 return t;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001872 } else {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001873 return openTabAndShow(url, false, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001874 }
1875 }
1876
Elliott Slaughterf0f03952010-07-14 18:10:36 -07001877 /* package */ Tab openIncognitoTab() {
1878 if (mTabControl.canCreateNewTab()) {
1879 Tab currentTab = mTabControl.getCurrentTab();
1880 Tab tab = mTabControl.createNewTab(false, null, null, true);
1881 if (currentTab != null) {
1882 removeTabFromContentView(currentTab);
1883 }
1884 mTabControl.setCurrentTab(tab);
1885 attachTabToContentView(tab);
1886 return tab;
1887 }
1888 return null;
1889 }
1890
The Android Open Source Project0c908882009-03-03 19:32:16 -08001891 private class Copy implements OnMenuItemClickListener {
1892 private CharSequence mText;
1893
1894 public boolean onMenuItemClick(MenuItem item) {
1895 copy(mText);
1896 return true;
1897 }
1898
1899 public Copy(CharSequence toCopy) {
1900 mText = toCopy;
1901 }
1902 }
1903
1904 private class Download implements OnMenuItemClickListener {
1905 private String mText;
1906
1907 public boolean onMenuItemClick(MenuItem item) {
1908 onDownloadStartNoStream(mText, null, null, null, -1);
1909 return true;
1910 }
1911
1912 public Download(String toDownload) {
1913 mText = toDownload;
1914 }
1915 }
1916
Ben Murdoch4f75ba22009-10-27 11:48:28 +00001917 private class SetAsWallpaper extends Thread implements
1918 OnMenuItemClickListener, DialogInterface.OnCancelListener {
1919 private URL mUrl;
1920 private ProgressDialog mWallpaperProgress;
1921 private boolean mCanceled = false;
1922
1923 public SetAsWallpaper(String url) {
1924 try {
1925 mUrl = new URL(url);
1926 } catch (MalformedURLException e) {
1927 mUrl = null;
1928 }
1929 }
1930
1931 public void onCancel(DialogInterface dialog) {
1932 mCanceled = true;
1933 }
1934
1935 public boolean onMenuItemClick(MenuItem item) {
1936 if (mUrl != null) {
1937 // The user may have tried to set a image with a large file size as their
1938 // background so it may take a few moments to perform the operation. Display
1939 // a progress spinner while it is working.
1940 mWallpaperProgress = new ProgressDialog(BrowserActivity.this);
1941 mWallpaperProgress.setIndeterminate(true);
1942 mWallpaperProgress.setMessage(getText(R.string.progress_dialog_setting_wallpaper));
1943 mWallpaperProgress.setCancelable(true);
1944 mWallpaperProgress.setOnCancelListener(this);
1945 mWallpaperProgress.show();
1946 start();
1947 }
1948 return true;
1949 }
1950
Michael Kolbe0a36662010-06-29 10:37:12 -07001951 @Override
Ben Murdoch4f75ba22009-10-27 11:48:28 +00001952 public void run() {
1953 Drawable oldWallpaper = BrowserActivity.this.getWallpaper();
1954 try {
1955 // TODO: This will cause the resource to be downloaded again, when we
1956 // should in most cases be able to grab it from the cache. To fix this
1957 // we should query WebCore to see if we can access a cached version and
1958 // instead open an input stream on that. This pattern could also be used
1959 // in the download manager where the same problem exists.
1960 InputStream inputstream = mUrl.openStream();
1961 if (inputstream != null) {
1962 setWallpaper(inputstream);
1963 }
1964 } catch (IOException e) {
1965 Log.e(LOGTAG, "Unable to set new wallpaper");
1966 // Act as though the user canceled the operation so we try to
1967 // restore the old wallpaper.
1968 mCanceled = true;
1969 }
1970
1971 if (mCanceled) {
1972 // Restore the old wallpaper if the user cancelled whilst we were setting
1973 // the new wallpaper.
1974 int width = oldWallpaper.getIntrinsicWidth();
1975 int height = oldWallpaper.getIntrinsicHeight();
1976 Bitmap bm = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
1977 Canvas canvas = new Canvas(bm);
1978 oldWallpaper.setBounds(0, 0, width, height);
1979 oldWallpaper.draw(canvas);
1980 try {
1981 setWallpaper(bm);
1982 } catch (IOException e) {
1983 Log.e(LOGTAG, "Unable to restore old wallpaper.");
1984 }
1985 mCanceled = false;
1986 }
1987
1988 if (mWallpaperProgress.isShowing()) {
1989 mWallpaperProgress.dismiss();
1990 }
1991 }
1992 }
1993
The Android Open Source Project0c908882009-03-03 19:32:16 -08001994 private void copy(CharSequence text) {
Dianne Hackborn80f32622010-08-05 14:17:53 -07001995 ClipboardManager cm = (ClipboardManager)getSystemService(Context.CLIPBOARD_SERVICE);
1996 cm.setText(text);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001997 }
1998
1999 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08002000 * Resets the browser title-view to whatever it must be
2001 * (for example, if we had a loading error)
2002 * When we have a new page, we call resetTitle, when we
2003 * have to reset the titlebar to whatever it used to be
2004 * (for example, if the user chose to stop loading), we
2005 * call resetTitleAndRevertLockIcon.
2006 */
2007 /* package */ void resetTitleAndRevertLockIcon() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002008 mTabControl.getCurrentTab().revertLockIcon();
2009 updateLockIconToLatest();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002010 resetTitleIconAndProgress();
2011 }
2012
2013 /**
2014 * Reset the title, favicon, and progress.
2015 */
2016 private void resetTitleIconAndProgress() {
2017 WebView current = mTabControl.getCurrentWebView();
2018 if (current == null) {
2019 return;
2020 }
2021 resetTitleAndIcon(current);
2022 int progress = current.getProgress();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002023 current.getWebChromeClient().onProgressChanged(current, progress);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002024 }
2025
2026 // Reset the title and the icon based on the given item.
2027 private void resetTitleAndIcon(WebView view) {
2028 WebHistoryItem item = view.copyBackForwardList().getCurrentItem();
2029 if (item != null) {
Leon Scroggins68579392009-09-15 15:31:54 -04002030 setUrlTitle(item.getUrl(), item.getTitle());
The Android Open Source Project0c908882009-03-03 19:32:16 -08002031 setFavicon(item.getFavicon());
2032 } else {
Leon Scroggins68579392009-09-15 15:31:54 -04002033 setUrlTitle(null, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002034 setFavicon(null);
2035 }
2036 }
2037
2038 /**
2039 * Sets a title composed of the URL and the title string.
2040 * @param url The URL of the site being loaded.
2041 * @param title The title of the site being loaded.
2042 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07002043 void setUrlTitle(String url, String title) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002044 mUrl = url;
2045 mTitle = title;
2046
Leon Scroggins58d56c62010-01-28 15:12:40 -05002047 // If we are in voice search mode, the title has already been set.
2048 if (mTabControl.getCurrentTab().isInVoiceSearchMode()) return;
2049 mTitleBar.setDisplayTitle(url);
Michael Kolba2b2ba82010-08-04 17:54:03 -07002050 mFakeTitleBar.setDisplayTitle(url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002051 }
2052
2053 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08002054 * @param url The URL to build a title version of the URL from.
2055 * @return The title version of the URL or null if fails.
2056 * The title version of the URL can be either the URL hostname,
2057 * or the hostname with an "https://" prefix (for secure URLs),
2058 * or an empty string if, for example, the URL in question is a
2059 * file:// URL with no hostname.
2060 */
Leon Scroggins32e14a62009-06-11 10:26:34 -04002061 /* package */ static String buildTitleUrl(String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002062 String titleUrl = null;
2063
2064 if (url != null) {
2065 try {
2066 // parse the url string
2067 URL urlObj = new URL(url);
2068 if (urlObj != null) {
2069 titleUrl = "";
2070
2071 String protocol = urlObj.getProtocol();
2072 String host = urlObj.getHost();
2073
2074 if (host != null && 0 < host.length()) {
2075 titleUrl = host;
2076 if (protocol != null) {
2077 // if a secure site, add an "https://" prefix!
2078 if (protocol.equalsIgnoreCase("https")) {
2079 titleUrl = protocol + "://" + host;
2080 }
2081 }
2082 }
2083 }
2084 } catch (MalformedURLException e) {}
2085 }
2086
2087 return titleUrl;
2088 }
2089
2090 // Set the favicon in the title bar.
Grace Kloba22ac16e2009-10-07 18:00:23 -07002091 void setFavicon(Bitmap icon) {
Leon Scroggins68579392009-09-15 15:31:54 -04002092 mTitleBar.setFavicon(icon);
Michael Kolba2b2ba82010-08-04 17:54:03 -07002093 mFakeTitleBar.setFavicon(icon);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002094 }
2095
2096 /**
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002097 * Close the tab, remove its associated title bar, and adjust mTabControl's
2098 * current tab to a valid value.
Leon Scroggins1f005d32009-08-10 17:36:42 -04002099 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07002100 /* package */ void closeTab(Tab t) {
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002101 int currentIndex = mTabControl.getCurrentIndex();
2102 int removeIndex = mTabControl.getTabIndex(t);
Leon Scroggins1f005d32009-08-10 17:36:42 -04002103 mTabControl.removeTab(t);
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002104 if (currentIndex >= removeIndex && currentIndex != 0) {
2105 currentIndex--;
2106 }
2107 mTabControl.setCurrentTab(mTabControl.getTab(currentIndex));
Andrei Popescua5bf1de2009-09-23 16:39:23 +01002108 resetTitleIconAndProgress();
Leon Scroggins654899b2010-06-25 16:25:23 -04002109 updateLockIconToLatest();
Elliott Slaughtere440a882010-08-20 13:54:45 -07002110
2111 if (!mTabControl.hasAnyOpenIncognitoTabs()) {
2112 WebView.cleanupPrivateBrowsingFiles(this);
2113 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002114 }
2115
Leon Scrogginsdcc5eeb2010-02-23 17:26:37 -05002116 /* package */ void goBackOnePageOrQuit() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002117 Tab current = mTabControl.getCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002118 if (current == null) {
2119 /*
2120 * Instead of finishing the activity, simply push this to the back
2121 * of the stack and let ActivityManager to choose the foreground
2122 * activity. As BrowserActivity is singleTask, it will be always the
2123 * root of the task. So we can use either true or false for
2124 * moveTaskToBack().
2125 */
2126 moveTaskToBack(true);
Grace Kloba00d85e72009-09-23 18:50:05 -07002127 return;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002128 }
2129 WebView w = current.getWebView();
2130 if (w.canGoBack()) {
2131 w.goBack();
2132 } else {
2133 // Check to see if we are closing a window that was created by
2134 // another window. If so, we switch back to that window.
Grace Kloba22ac16e2009-10-07 18:00:23 -07002135 Tab parent = current.getParentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002136 if (parent != null) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04002137 switchToTab(mTabControl.getTabIndex(parent));
2138 // Now we close the other tab
2139 closeTab(current);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002140 } else {
2141 if (current.closeOnExit()) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002142 // force the tab's inLoad() to be false as we are going to
2143 // either finish the activity or remove the tab. This will
2144 // ensure pauseWebViewTimers() taking action.
2145 mTabControl.getCurrentTab().clearInLoad();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002146 if (mTabControl.getTabCount() == 1) {
2147 finish();
2148 return;
2149 }
Mike Reed7bfa63b2009-05-28 11:08:32 -04002150 // call pauseWebViewTimers() now, we won't be able to call
2151 // it in onPause() as the WebView won't be valid.
Grace Klobaec1b5ad2009-08-18 08:42:32 -07002152 // Temporarily change mActivityInPause to be true as
2153 // pauseWebViewTimers() will do nothing if mActivityInPause
2154 // is false.
Grace Kloba918e1d72009-08-13 14:55:06 -07002155 boolean savedState = mActivityInPause;
2156 if (savedState) {
Grace Klobaec1b5ad2009-08-18 08:42:32 -07002157 Log.e(LOGTAG, "BrowserActivity is already paused "
2158 + "while handing goBackOnePageOrQuit.");
Grace Kloba918e1d72009-08-13 14:55:06 -07002159 }
2160 mActivityInPause = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -04002161 pauseWebViewTimers();
Grace Kloba918e1d72009-08-13 14:55:06 -07002162 mActivityInPause = savedState;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002163 removeTabFromContentView(current);
2164 mTabControl.removeTab(current);
2165 }
2166 /*
2167 * Instead of finishing the activity, simply push this to the back
2168 * of the stack and let ActivityManager to choose the foreground
2169 * activity. As BrowserActivity is singleTask, it will be always the
2170 * root of the task. So we can use either true or false for
2171 * moveTaskToBack().
2172 */
2173 moveTaskToBack(true);
2174 }
2175 }
2176 }
2177
Grace Kloba22ac16e2009-10-07 18:00:23 -07002178 boolean isMenuDown() {
2179 return mMenuIsDown;
2180 }
2181
Grace Kloba5942df02009-09-18 11:48:29 -07002182 @Override
2183 public boolean onKeyDown(int keyCode, KeyEvent event) {
Leon Scrogginsf65b50d2009-12-08 10:44:28 -05002184 // Even if MENU is already held down, we need to call to super to open
2185 // the IME on long press.
2186 if (KeyEvent.KEYCODE_MENU == keyCode) {
2187 mMenuIsDown = true;
2188 return super.onKeyDown(keyCode, event);
2189 }
Grace Kloba5942df02009-09-18 11:48:29 -07002190 // The default key mode is DEFAULT_KEYS_SEARCH_LOCAL. As the MENU is
2191 // still down, we don't want to trigger the search. Pretend to consume
2192 // the key and do nothing.
2193 if (mMenuIsDown) return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002194
Grace Kloba5942df02009-09-18 11:48:29 -07002195 switch(keyCode) {
Grace Kloba5942df02009-09-18 11:48:29 -07002196 case KeyEvent.KEYCODE_SPACE:
Grace Klobada0fe552009-09-22 18:17:24 -07002197 // WebView/WebTextView handle the keys in the KeyDown. As
2198 // the Activity's shortcut keys are only handled when WebView
2199 // doesn't, have to do it in onKeyDown instead of onKeyUp.
2200 if (event.isShiftPressed()) {
2201 getTopWindow().pageUp(false);
2202 } else {
2203 getTopWindow().pageDown(false);
2204 }
Grace Kloba5942df02009-09-18 11:48:29 -07002205 return true;
2206 case KeyEvent.KEYCODE_BACK:
2207 if (event.getRepeatCount() == 0) {
2208 event.startTracking();
2209 return true;
2210 } else if (mCustomView == null && mActiveTabsPage == null
Michael Kolbe421c242010-10-04 19:29:01 -07002211 && mComboView == null
Grace Kloba5942df02009-09-18 11:48:29 -07002212 && event.isLongPress()) {
Michael Kolbe421c242010-10-04 19:29:01 -07002213 bookmarksOrHistoryPicker(true);
Grace Kloba5942df02009-09-18 11:48:29 -07002214 return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002215 }
Grace Kloba5942df02009-09-18 11:48:29 -07002216 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002217 }
Grace Kloba5942df02009-09-18 11:48:29 -07002218 return super.onKeyDown(keyCode, event);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002219 }
2220
Grace Kloba5942df02009-09-18 11:48:29 -07002221 @Override
2222 public boolean onKeyUp(int keyCode, KeyEvent event) {
2223 switch(keyCode) {
2224 case KeyEvent.KEYCODE_MENU:
2225 mMenuIsDown = false;
2226 break;
Grace Kloba5942df02009-09-18 11:48:29 -07002227 case KeyEvent.KEYCODE_BACK:
2228 if (event.isTracking() && !event.isCanceled()) {
2229 if (mCustomView != null) {
2230 // if a custom view is showing, hide it
Grace Kloba22ac16e2009-10-07 18:00:23 -07002231 mTabControl.getCurrentWebView().getWebChromeClient()
2232 .onHideCustomView();
Grace Kloba5942df02009-09-18 11:48:29 -07002233 } else if (mActiveTabsPage != null) {
2234 // if tab page is showing, hide it
2235 removeActiveTabPage(true);
Michael Kolbe421c242010-10-04 19:29:01 -07002236 } else if (mComboView != null) {
Michael Kolb370a4f32010-10-06 10:45:32 -07002237 if (!mComboView.onBackPressed()) {
2238 removeComboView();
2239 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002240 } else {
Grace Kloba5942df02009-09-18 11:48:29 -07002241 WebView subwindow = mTabControl.getCurrentSubWindow();
2242 if (subwindow != null) {
2243 if (subwindow.canGoBack()) {
2244 subwindow.goBack();
2245 } else {
2246 dismissSubWindow(mTabControl.getCurrentTab());
2247 }
2248 } else {
2249 goBackOnePageOrQuit();
2250 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002251 }
Grace Kloba5942df02009-09-18 11:48:29 -07002252 return true;
2253 }
2254 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002255 }
Grace Kloba5942df02009-09-18 11:48:29 -07002256 return super.onKeyUp(keyCode, event);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002257 }
2258
Leon Scroggins68579392009-09-15 15:31:54 -04002259 /* package */ void stopLoading() {
Ben Murdochb7cc8b42009-09-28 10:59:09 +01002260 mDidStopLoad = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002261 resetTitleAndRevertLockIcon();
2262 WebView w = getTopWindow();
2263 w.stopLoading();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002264 // FIXME: before refactor, it is using mWebViewClient. So I keep the
2265 // same logic here. But for subwindow case, should we call into the main
2266 // WebView's onPageFinished as we never call its onPageStarted and if
2267 // the page finishes itself, we don't call onPageFinished.
2268 mTabControl.getCurrentWebView().getWebViewClient().onPageFinished(w,
2269 w.getUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08002270
2271 cancelStopToast();
2272 mStopToast = Toast
2273 .makeText(this, R.string.stopping, Toast.LENGTH_SHORT);
2274 mStopToast.show();
2275 }
2276
Grace Kloba22ac16e2009-10-07 18:00:23 -07002277 boolean didUserStopLoading() {
2278 return mDidStopLoad;
2279 }
2280
The Android Open Source Project0c908882009-03-03 19:32:16 -08002281 private void cancelStopToast() {
2282 if (mStopToast != null) {
2283 mStopToast.cancel();
2284 mStopToast = null;
2285 }
2286 }
2287
Grace Kloba22ac16e2009-10-07 18:00:23 -07002288 // called by a UI or non-UI thread to post the message
2289 public void postMessage(int what, int arg1, int arg2, Object obj,
2290 long delayMillis) {
2291 mHandler.sendMessageDelayed(mHandler.obtainMessage(what, arg1, arg2,
2292 obj), delayMillis);
2293 }
2294
2295 // called by a UI or non-UI thread to remove the message
2296 void removeMessages(int what, Object object) {
2297 mHandler.removeMessages(what, object);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002298 }
2299
2300 // public message ids
2301 public final static int LOAD_URL = 1001;
2302 public final static int STOP_LOAD = 1002;
2303
2304 // Message Ids
2305 private static final int FOCUS_NODE_HREF = 102;
Grace Kloba92c18a52009-07-31 23:48:32 -07002306 private static final int RELEASE_WAKELOCK = 107;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002307
Grace Kloba22ac16e2009-10-07 18:00:23 -07002308 static final int UPDATE_BOOKMARK_THUMBNAIL = 108;
Ben Murdoch2694e232009-09-29 09:41:11 +01002309
Ben Murdocheecb4e62010-07-06 16:30:38 +01002310 private static final int TOUCH_ICON_DOWNLOADED = 109;
2311
Michael Kolb300b7f02010-08-25 13:47:24 -07002312 private static final int OPEN_BOOKMARKS = 201;
2313
The Android Open Source Project0c908882009-03-03 19:32:16 -08002314 // Private handler for handling javascript and saving passwords
2315 private Handler mHandler = new Handler() {
2316
Michael Kolbe0a36662010-06-29 10:37:12 -07002317 @Override
The Android Open Source Project0c908882009-03-03 19:32:16 -08002318 public void handleMessage(Message msg) {
2319 switch (msg.what) {
Michael Kolb300b7f02010-08-25 13:47:24 -07002320 case OPEN_BOOKMARKS:
Michael Kolbe421c242010-10-04 19:29:01 -07002321 bookmarksOrHistoryPicker(false);
Michael Kolb300b7f02010-08-25 13:47:24 -07002322 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002323 case FOCUS_NODE_HREF:
Ben Murdoch2694e232009-09-29 09:41:11 +01002324 {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002325 String url = (String) msg.getData().get("url");
Ben Murdoch90d088c2009-11-17 18:14:04 +00002326 String title = (String) msg.getData().get("title");
The Android Open Source Project0c908882009-03-03 19:32:16 -08002327 if (url == null || url.length() == 0) {
2328 break;
2329 }
2330 HashMap focusNodeMap = (HashMap) msg.obj;
2331 WebView view = (WebView) focusNodeMap.get("webview");
2332 // Only apply the action if the top window did not change.
2333 if (getTopWindow() != view) {
2334 break;
2335 }
2336 switch (msg.arg1) {
2337 case R.id.open_context_menu_id:
2338 case R.id.view_image_context_menu_id:
Leon Scroggins92472e82010-02-17 16:32:28 -05002339 loadUrlFromContext(getTopWindow(), url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002340 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002341 case R.id.bookmark_context_menu_id:
2342 Intent intent = new Intent(BrowserActivity.this,
2343 AddBookmarkPage.class);
2344 intent.putExtra("url", url);
Ben Murdoch90d088c2009-11-17 18:14:04 +00002345 intent.putExtra("title", title);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002346 startActivity(intent);
2347 break;
2348 case R.id.share_link_context_menu_id:
Leon Scroggins3e204452010-05-10 11:06:03 -04002349 sharePage(BrowserActivity.this, title, url, null,
Leon Scroggins96afcb12009-12-10 12:35:56 -05002350 null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002351 break;
2352 case R.id.copy_link_context_menu_id:
2353 copy(url);
2354 break;
2355 case R.id.save_link_context_menu_id:
2356 case R.id.download_context_menu_id:
2357 onDownloadStartNoStream(url, null, null, null, -1);
2358 break;
2359 }
2360 break;
Ben Murdoch2694e232009-09-29 09:41:11 +01002361 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002362
2363 case LOAD_URL:
Leon Scroggins92472e82010-02-17 16:32:28 -05002364 loadUrlFromContext(getTopWindow(), (String) msg.obj);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002365 break;
2366
2367 case STOP_LOAD:
2368 stopLoading();
2369 break;
2370
The Android Open Source Project0c908882009-03-03 19:32:16 -08002371 case RELEASE_WAKELOCK:
2372 if (mWakeLock.isHeld()) {
2373 mWakeLock.release();
Grace Kloba5d0e02e2009-10-05 15:15:36 -07002374 // if we reach here, Browser should be still in the
2375 // background loading after WAKELOCK_TIMEOUT (5-min).
2376 // To avoid burning the battery, stop loading.
2377 mTabControl.stopAllLoading();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002378 }
2379 break;
Ben Murdoch2694e232009-09-29 09:41:11 +01002380
2381 case UPDATE_BOOKMARK_THUMBNAIL:
2382 WebView view = (WebView) msg.obj;
2383 if (view != null) {
2384 updateScreenshot(view);
2385 }
2386 break;
Ben Murdocheecb4e62010-07-06 16:30:38 +01002387
2388 case TOUCH_ICON_DOWNLOADED:
2389 Bundle b = msg.getData();
2390 showSaveToHomescreenDialog(b.getString("url"),
2391 b.getString("title"),
2392 (Bitmap) b.getParcelable("touchIcon"),
2393 (Bitmap) b.getParcelable("favicon"));
2394 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002395 }
2396 }
2397 };
2398
Leon Scroggins96afcb12009-12-10 12:35:56 -05002399 /**
2400 * Share a page, providing the title, url, favicon, and a screenshot. Uses
2401 * an {@link Intent} to launch the Activity chooser.
2402 * @param c Context used to launch a new Activity.
2403 * @param title Title of the page. Stored in the Intent with
Paul Westbrook03e6d392010-02-12 10:33:29 -08002404 * {@link Intent#EXTRA_SUBJECT}
Leon Scroggins96afcb12009-12-10 12:35:56 -05002405 * @param url URL of the page. Stored in the Intent with
2406 * {@link Intent#EXTRA_TEXT}
2407 * @param favicon Bitmap of the favicon for the page. Stored in the Intent
2408 * with {@link Browser#EXTRA_SHARE_FAVICON}
2409 * @param screenshot Bitmap of a screenshot of the page. Stored in the
2410 * Intent with {@link Browser#EXTRA_SHARE_SCREENSHOT}
2411 */
2412 public static final void sharePage(Context c, String title, String url,
2413 Bitmap favicon, Bitmap screenshot) {
2414 Intent send = new Intent(Intent.ACTION_SEND);
2415 send.setType("text/plain");
2416 send.putExtra(Intent.EXTRA_TEXT, url);
Paul Westbrook03e6d392010-02-12 10:33:29 -08002417 send.putExtra(Intent.EXTRA_SUBJECT, title);
Leon Scroggins96afcb12009-12-10 12:35:56 -05002418 send.putExtra(Browser.EXTRA_SHARE_FAVICON, favicon);
2419 send.putExtra(Browser.EXTRA_SHARE_SCREENSHOT, screenshot);
2420 try {
2421 c.startActivity(Intent.createChooser(send, c.getString(
2422 R.string.choosertitle_sharevia)));
2423 } catch(android.content.ActivityNotFoundException ex) {
2424 // if no app handles it, do nothing
2425 }
2426 }
2427
Leon Scroggins89c6d362009-07-15 16:54:37 -04002428 private void updateScreenshot(WebView view) {
2429 // If this is a bookmarked site, add a screenshot to the database.
2430 // FIXME: When should we update? Every time?
2431 // FIXME: Would like to make sure there is actually something to
2432 // draw, but the API for that (WebViewCore.pictureReady()) is not
2433 // currently accessible here.
Ben Murdochaac7aa62009-09-17 16:57:40 +01002434
Ben Murdoch87cc65d2010-06-29 20:34:10 +01002435 final Bitmap bm = createScreenshot(view, getDesiredThumbnailWidth(this),
2436 getDesiredThumbnailHeight(this));
Patrick Scottcb192b52010-04-14 14:38:55 -04002437 if (bm == null) {
2438 return;
Leon Scroggins89c6d362009-07-15 16:54:37 -04002439 }
Patrick Scottcb192b52010-04-14 14:38:55 -04002440
2441 final ContentResolver cr = getContentResolver();
2442 final String url = view.getUrl();
2443 final String originalUrl = view.getOriginalUrl();
2444
2445 new AsyncTask<Void, Void, Void>() {
2446 @Override
2447 protected Void doInBackground(Void... unused) {
Jeff Hamilton1a805652010-09-07 12:36:30 -07002448 Cursor cursor = null;
Patrick Scottcb192b52010-04-14 14:38:55 -04002449 try {
Jeff Hamilton1a805652010-09-07 12:36:30 -07002450 cursor = Bookmarks.queryCombinedForUrl(cr, originalUrl, url);
2451 if (cursor != null && cursor.moveToFirst()) {
2452 final ByteArrayOutputStream os = new ByteArrayOutputStream();
2453 bm.compress(Bitmap.CompressFormat.PNG, 100, os);
2454
2455 ContentValues values = new ContentValues();
2456 values.put(Images.THUMBNAIL, os.toByteArray());
2457 values.put(Images.URL, cursor.getString(0));
2458
2459 do {
2460 cr.update(Images.CONTENT_URI, values, null, null);
2461 } while (cursor.moveToNext());
Patrick Scottcb192b52010-04-14 14:38:55 -04002462 }
2463 } catch (IllegalStateException e) {
2464 // Ignore
2465 } finally {
Jeff Hamilton1a805652010-09-07 12:36:30 -07002466 if (cursor != null) cursor.close();
Patrick Scottcb192b52010-04-14 14:38:55 -04002467 }
2468 return null;
2469 }
2470 }.execute();
Leon Scroggins89c6d362009-07-15 16:54:37 -04002471 }
2472
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002473 /**
Leon Scrogginsf8551612009-09-24 16:06:02 -04002474 * Return the desired width for thumbnail screenshots, which are stored in
2475 * the database, and used on the bookmarks screen.
2476 * @param context Context for finding out the density of the screen.
Jeff Hamiltonf3026372010-08-19 00:12:27 -05002477 * @return desired width for thumbnail screenshot.
Leon Scrogginsf8551612009-09-24 16:06:02 -04002478 */
2479 /* package */ static int getDesiredThumbnailWidth(Context context) {
Jeff Hamiltonf3026372010-08-19 00:12:27 -05002480 return context.getResources().getDimensionPixelOffset(R.dimen.bookmarkThumbnailWidth);
Leon Scrogginsf8551612009-09-24 16:06:02 -04002481 }
2482
2483 /**
2484 * Return the desired height for thumbnail screenshots, which are stored in
2485 * the database, and used on the bookmarks screen.
2486 * @param context Context for finding out the density of the screen.
Jeff Hamiltonf3026372010-08-19 00:12:27 -05002487 * @return desired height for thumbnail screenshot.
Leon Scrogginsf8551612009-09-24 16:06:02 -04002488 */
2489 /* package */ static int getDesiredThumbnailHeight(Context context) {
Jeff Hamiltonf3026372010-08-19 00:12:27 -05002490 return context.getResources().getDimensionPixelOffset(R.dimen.bookmarkThumbnailHeight);
Leon Scrogginsf8551612009-09-24 16:06:02 -04002491 }
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002492
Ben Murdoch87cc65d2010-06-29 20:34:10 +01002493 private Bitmap createScreenshot(WebView view, int width, int height) {
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002494 Picture thumbnail = view.capturePicture();
Leon Scroggins45800572009-09-29 16:38:47 -04002495 if (thumbnail == null) {
2496 return null;
2497 }
Ben Murdoch87cc65d2010-06-29 20:34:10 +01002498 Bitmap bm = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002499 Canvas canvas = new Canvas(bm);
2500 // May need to tweak these values to determine what is the
2501 // best scale factor
Ben Murdoch2694e232009-09-29 09:41:11 +01002502 int thumbnailWidth = thumbnail.getWidth();
Ben Murdochae59c3f2009-10-20 18:30:28 +01002503 int thumbnailHeight = thumbnail.getHeight();
2504 float scaleFactorX = 1.0f;
2505 float scaleFactorY = 1.0f;
Ben Murdoch2694e232009-09-29 09:41:11 +01002506 if (thumbnailWidth > 0) {
Ben Murdoch87cc65d2010-06-29 20:34:10 +01002507 scaleFactorX = (float) width / (float)thumbnailWidth;
Ben Murdochae59c3f2009-10-20 18:30:28 +01002508 } else {
2509 return null;
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002510 }
Ben Murdochae59c3f2009-10-20 18:30:28 +01002511
2512 if (view.getWidth() > view.getHeight() &&
2513 thumbnailHeight < view.getHeight() && thumbnailHeight > 0) {
2514 // If the device is in landscape and the page is shorter
2515 // than the height of the view, stretch the thumbnail to fill the
2516 // space.
Ben Murdoch87cc65d2010-06-29 20:34:10 +01002517 scaleFactorY = (float) height / (float)thumbnailHeight;
Ben Murdochae59c3f2009-10-20 18:30:28 +01002518 } else {
2519 // In the portrait case, this looks nice.
2520 scaleFactorY = scaleFactorX;
2521 }
2522
2523 canvas.scale(scaleFactorX, scaleFactorY);
2524
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002525 thumbnail.draw(canvas);
2526 return bm;
2527 }
2528
The Android Open Source Project0c908882009-03-03 19:32:16 -08002529 // -------------------------------------------------------------------------
Grace Kloba22ac16e2009-10-07 18:00:23 -07002530 // Helper function for WebViewClient.
The Android Open Source Project0c908882009-03-03 19:32:16 -08002531 //-------------------------------------------------------------------------
2532
2533 // Use in overrideUrlLoading
2534 /* package */ final static String SCHEME_WTAI = "wtai://wp/";
2535 /* package */ final static String SCHEME_WTAI_MC = "wtai://wp/mc;";
2536 /* package */ final static String SCHEME_WTAI_SD = "wtai://wp/sd;";
2537 /* package */ final static String SCHEME_WTAI_AP = "wtai://wp/ap;";
2538
Leon Scroggins92472e82010-02-17 16:32:28 -05002539 // Keep this initial progress in sync with initialProgressValue (* 100)
2540 // in ProgressTracker.cpp
2541 private final static int INITIAL_PROGRESS = 10;
2542
Grace Kloba22ac16e2009-10-07 18:00:23 -07002543 void onPageStarted(WebView view, String url, Bitmap favicon) {
2544 // when BrowserActivity just starts, onPageStarted may be called before
2545 // onResume as it is triggered from onCreate. Call resumeWebViewTimers
2546 // to start the timer. As we won't switch tabs while an activity is in
2547 // pause state, we can ensure calling resume and pause in pair.
2548 if (mActivityInPause) resumeWebViewTimers();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002549
Grace Kloba22ac16e2009-10-07 18:00:23 -07002550 resetLockIcon(url);
2551 setUrlTitle(url, null);
2552 setFavicon(favicon);
Leon Scroggins8cf8f682009-11-04 11:13:50 -08002553 // Show some progress so that the user knows the page is beginning to
2554 // load
Leon Scroggins92472e82010-02-17 16:32:28 -05002555 onProgressChanged(view, INITIAL_PROGRESS);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002556 mDidStopLoad = false;
Grace Kloba22ac16e2009-10-07 18:00:23 -07002557 if (!mIsNetworkUp) createAndShowNetworkDialog();
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04002558 endActionMode();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002559 if (mSettings.isTracing()) {
2560 String host;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002561 try {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002562 WebAddress uri = new WebAddress(url);
Bjorn Bringert131ab512010-10-12 16:25:47 +01002563 host = uri.getHost();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002564 } catch (android.net.ParseException ex) {
2565 host = "browser";
The Android Open Source Project0c908882009-03-03 19:32:16 -08002566 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002567 host = host.replace('.', '_');
2568 host += ".trace";
2569 mInTrace = true;
2570 Debug.startMethodTracing(host, 20 * 1024 * 1024);
2571 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002572
Grace Kloba22ac16e2009-10-07 18:00:23 -07002573 // Performance probe
2574 if (false) {
2575 mStart = SystemClock.uptimeMillis();
2576 mProcessStart = Process.getElapsedCpuTime();
2577 long[] sysCpu = new long[7];
2578 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2579 sysCpu, null)) {
2580 mUserStart = sysCpu[0] + sysCpu[1];
2581 mSystemStart = sysCpu[2];
2582 mIdleStart = sysCpu[3];
2583 mIrqStart = sysCpu[4] + sysCpu[5] + sysCpu[6];
2584 }
2585 mUiStart = SystemClock.currentThreadTimeMillis();
2586 }
2587 }
2588
2589 void onPageFinished(WebView view, String url) {
2590 // Reset the title and icon in case we stopped a provisional load.
2591 resetTitleAndIcon(view);
2592 // Update the lock icon image only once we are done loading
2593 updateLockIconToLatest();
2594 // pause the WebView timer and release the wake lock if it is finished
2595 // while BrowserActivity is in pause state.
2596 if (mActivityInPause && pauseWebViewTimers()) {
2597 if (mWakeLock.isHeld()) {
2598 mHandler.removeMessages(RELEASE_WAKELOCK);
2599 mWakeLock.release();
2600 }
2601 }
2602
2603 // Performance probe
2604 if (false) {
2605 long[] sysCpu = new long[7];
2606 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2607 sysCpu, null)) {
2608 String uiInfo = "UI thread used "
2609 + (SystemClock.currentThreadTimeMillis() - mUiStart)
2610 + " ms";
2611 if (LOGD_ENABLED) {
2612 Log.d(LOGTAG, uiInfo);
2613 }
2614 //The string that gets written to the log
2615 String performanceString = "It took total "
2616 + (SystemClock.uptimeMillis() - mStart)
2617 + " ms clock time to load the page."
2618 + "\nbrowser process used "
2619 + (Process.getElapsedCpuTime() - mProcessStart)
2620 + " ms, user processes used "
2621 + (sysCpu[0] + sysCpu[1] - mUserStart) * 10
2622 + " ms, kernel used "
2623 + (sysCpu[2] - mSystemStart) * 10
2624 + " ms, idle took " + (sysCpu[3] - mIdleStart) * 10
2625 + " ms and irq took "
2626 + (sysCpu[4] + sysCpu[5] + sysCpu[6] - mIrqStart)
2627 * 10 + " ms, " + uiInfo;
2628 if (LOGD_ENABLED) {
2629 Log.d(LOGTAG, performanceString + "\nWebpage: " + url);
2630 }
2631 if (url != null) {
2632 // strip the url to maintain consistency
2633 String newUrl = new String(url);
2634 if (newUrl.startsWith("http://www.")) {
2635 newUrl = newUrl.substring(11);
2636 } else if (newUrl.startsWith("http://")) {
2637 newUrl = newUrl.substring(7);
2638 } else if (newUrl.startsWith("https://www.")) {
2639 newUrl = newUrl.substring(12);
2640 } else if (newUrl.startsWith("https://")) {
2641 newUrl = newUrl.substring(8);
2642 }
2643 if (LOGD_ENABLED) {
2644 Log.d(LOGTAG, newUrl + " loaded");
2645 }
Grace Kloba5b078b52009-06-24 20:23:41 -07002646 }
2647 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002648 }
Grace Kloba5b078b52009-06-24 20:23:41 -07002649
Grace Kloba22ac16e2009-10-07 18:00:23 -07002650 if (mInTrace) {
2651 mInTrace = false;
2652 Debug.stopMethodTracing();
2653 }
2654 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002655
Grace Klobae7fe26b2010-06-28 16:23:33 -07002656 private void closeEmptyChildTab() {
2657 Tab current = mTabControl.getCurrentTab();
2658 if (current != null
2659 && current.getWebView().copyBackForwardList().getSize() == 0) {
2660 Tab parent = current.getParentTab();
2661 if (parent != null) {
2662 switchToTab(mTabControl.getTabIndex(parent));
2663 closeTab(current);
2664 }
2665 }
2666 }
2667
Grace Kloba22ac16e2009-10-07 18:00:23 -07002668 boolean shouldOverrideUrlLoading(WebView view, String url) {
Jeff Hamilton47654f42010-09-07 09:57:51 -05002669 if (view.isPrivateBrowsingEnabled()) {
2670 // Don't allow urls to leave the browser app when in private browsing mode
2671 loadUrl(view, url);
2672 return true;
2673 }
2674
Grace Kloba22ac16e2009-10-07 18:00:23 -07002675 if (url.startsWith(SCHEME_WTAI)) {
2676 // wtai://wp/mc;number
2677 // number=string(phone-number)
2678 if (url.startsWith(SCHEME_WTAI_MC)) {
2679 Intent intent = new Intent(Intent.ACTION_VIEW,
2680 Uri.parse(WebView.SCHEME_TEL +
2681 url.substring(SCHEME_WTAI_MC.length())));
2682 startActivity(intent);
Grace Klobae7fe26b2010-06-28 16:23:33 -07002683 // before leaving BrowserActivity, close the empty child tab.
2684 // If a new tab is created through JavaScript open to load this
2685 // url, we would like to close it as we will load this url in a
2686 // different Activity.
2687 closeEmptyChildTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002688 return true;
2689 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002690 // wtai://wp/sd;dtmf
2691 // dtmf=string(dialstring)
2692 if (url.startsWith(SCHEME_WTAI_SD)) {
2693 // TODO: only send when there is active voice connection
2694 return false;
2695 }
2696 // wtai://wp/ap;number;name
2697 // number=string(phone-number)
2698 // name=string
2699 if (url.startsWith(SCHEME_WTAI_AP)) {
2700 // TODO
2701 return false;
2702 }
2703 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002704
Grace Kloba22ac16e2009-10-07 18:00:23 -07002705 // The "about:" schemes are internal to the browser; don't want these to
2706 // be dispatched to other apps.
2707 if (url.startsWith("about:")) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002708 return false;
2709 }
2710
Jeff Davidson43610292010-07-16 16:03:58 -07002711 // If this is a Google search, attempt to add an RLZ string (if one isn't already present).
2712 if (rlzProviderPresent()) {
2713 Uri siteUri = Uri.parse(url);
2714 if (needsRlzString(siteUri)) {
2715 String rlz = null;
2716 Cursor cur = null;
2717 try {
2718 cur = getContentResolver().query(getRlzUri(), null, null, null, null);
2719 if (cur != null && cur.moveToFirst() && !cur.isNull(0)) {
2720 url = siteUri.buildUpon()
2721 .appendQueryParameter("rlz", cur.getString(0))
2722 .build().toString();
2723 }
2724 } finally {
2725 if (cur != null) {
2726 cur.close();
2727 }
2728 }
2729 loadUrl(view, url);
2730 return true;
2731 }
2732 }
2733
Grace Kloba22ac16e2009-10-07 18:00:23 -07002734 Intent intent;
2735 // perform generic parsing of the URI to turn it into an Intent.
2736 try {
2737 intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME);
2738 } catch (URISyntaxException ex) {
2739 Log.w("Browser", "Bad URI " + url + ": " + ex.getMessage());
2740 return false;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002741 }
2742
Grace Kloba22ac16e2009-10-07 18:00:23 -07002743 // check whether the intent can be resolved. If not, we will see
2744 // whether we can download it from the Market.
2745 if (getPackageManager().resolveActivity(intent, 0) == null) {
2746 String packagename = intent.getPackage();
2747 if (packagename != null) {
2748 intent = new Intent(Intent.ACTION_VIEW, Uri
2749 .parse("market://search?q=pname:" + packagename));
2750 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2751 startActivity(intent);
Grace Klobae7fe26b2010-06-28 16:23:33 -07002752 // before leaving BrowserActivity, close the empty child tab.
2753 // If a new tab is created through JavaScript open to load this
2754 // url, we would like to close it as we will load this url in a
2755 // different Activity.
2756 closeEmptyChildTab();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002757 return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002758 } else {
2759 return false;
2760 }
2761 }
2762
Grace Kloba22ac16e2009-10-07 18:00:23 -07002763 // sanitize the Intent, ensuring web pages can not bypass browser
2764 // security (only access to BROWSABLE activities).
2765 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2766 intent.setComponent(null);
2767 try {
2768 if (startActivityIfNeeded(intent, -1)) {
Grace Klobae7fe26b2010-06-28 16:23:33 -07002769 // before leaving BrowserActivity, close the empty child tab.
2770 // If a new tab is created through JavaScript open to load this
2771 // url, we would like to close it as we will load this url in a
2772 // different Activity.
2773 closeEmptyChildTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002774 return true;
2775 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002776 } catch (ActivityNotFoundException ex) {
2777 // ignore the error. If no application can handle the URL,
2778 // eg about:blank, assume the browser can handle it.
2779 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002780
Grace Kloba22ac16e2009-10-07 18:00:23 -07002781 if (mMenuIsDown) {
Michael Kolb68792c82010-08-09 16:39:18 -07002782 openTab(url, false);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002783 closeOptionsMenu();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002784 return true;
2785 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002786 return false;
2787 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002788
Jeff Davidson43610292010-07-16 16:03:58 -07002789 // Determine whether the RLZ provider is present on the system.
2790 private boolean rlzProviderPresent() {
2791 if (mIsProviderPresent == null) {
2792 PackageManager pm = getPackageManager();
2793 mIsProviderPresent = pm.resolveContentProvider(BrowserSettings.RLZ_PROVIDER, 0) != null;
2794 }
2795 return mIsProviderPresent;
2796 }
2797
2798 // Retrieve the RLZ access point string and cache the URI used to retrieve RLZ values.
2799 private Uri getRlzUri() {
2800 if (mRlzUri == null) {
2801 String ap = getResources().getString(R.string.rlz_access_point);
2802 mRlzUri = Uri.withAppendedPath(BrowserSettings.RLZ_PROVIDER_URI, ap);
2803 }
2804 return mRlzUri;
2805 }
2806
2807 // Determine if this URI appears to be for a Google search and does not have an RLZ parameter.
2808 // Taken largely from Chrome source, src/chrome/browser/google_url_tracker.cc
2809 private static boolean needsRlzString(Uri uri) {
Bill Napierc50e71a2010-08-27 14:03:03 -07002810 String scheme = uri.getScheme();
2811 if (("http".equals(scheme) || "https".equals(scheme)) &&
2812 (uri.getQueryParameter("q") != null) && (uri.getQueryParameter("rlz") == null)) {
Jeff Davidson43610292010-07-16 16:03:58 -07002813 String host = uri.getHost();
2814 if (host == null) {
2815 return false;
2816 }
2817 String[] hostComponents = host.split("\\.");
2818
2819 if (hostComponents.length < 2) {
2820 return false;
2821 }
2822 int googleComponent = hostComponents.length - 2;
2823 String component = hostComponents[googleComponent];
2824 if (!"google".equals(component)) {
2825 if (hostComponents.length < 3 ||
2826 (!"co".equals(component) && !"com".equals(component))) {
2827 return false;
2828 }
2829 googleComponent = hostComponents.length - 3;
2830 if (!"google".equals(hostComponents[googleComponent])) {
2831 return false;
2832 }
2833 }
2834
2835 // Google corp network handling.
2836 if (googleComponent > 0 && "corp".equals(hostComponents[googleComponent - 1])) {
2837 return false;
2838 }
2839
2840 return true;
2841 }
2842 return false;
2843 }
2844
Grace Kloba22ac16e2009-10-07 18:00:23 -07002845 // -------------------------------------------------------------------------
2846 // Helper function for WebChromeClient
2847 // -------------------------------------------------------------------------
The Android Open Source Project0c908882009-03-03 19:32:16 -08002848
Grace Kloba22ac16e2009-10-07 18:00:23 -07002849 void onProgressChanged(WebView view, int newProgress) {
Michael Kolba2b2ba82010-08-04 17:54:03 -07002850
2851 // On the phone, the fake title bar will always cover up the
2852 // regular title bar (or the regular one is offscreen), so only the
2853 // fake title bar needs to change its progress
2854 mFakeTitleBar.setProgress(newProgress);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002855
Grace Kloba22ac16e2009-10-07 18:00:23 -07002856 if (newProgress == 100) {
2857 // onProgressChanged() may continue to be called after the main
2858 // frame has finished loading, as any remaining sub frames continue
2859 // to load. We'll only get called once though with newProgress as
2860 // 100 when everything is loaded. (onPageFinished is called once
2861 // when the main frame completes loading regardless of the state of
2862 // any sub frames so calls to onProgressChanges may continue after
2863 // onPageFinished has executed)
2864 if (mInLoad) {
2865 mInLoad = false;
Leon Scrogginsa27ff192009-09-14 12:58:04 -04002866 updateInLoadMenuItems();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002867 // If the options menu is open, leave the title bar
2868 if (!mOptionsMenuOpen || !mIconView) {
2869 hideFakeTitleBar();
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07002870 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002871 }
Leon Scrogginsaa37e7f2010-03-05 11:51:20 -05002872 } else {
2873 if (!mInLoad) {
2874 // onPageFinished may have already been called but a subframe is
2875 // still loading and updating the progress. Reset mInLoad and
2876 // update the menu items.
2877 mInLoad = true;
2878 updateInLoadMenuItems();
2879 }
2880 // When the page first begins to load, the Activity may still be
2881 // paused, in which case showFakeTitleBar will do nothing. Call
2882 // again as the page continues to load so that it will be shown.
2883 // (Calling it will the fake title bar is already showing will also
2884 // do nothing.
Grace Kloba22ac16e2009-10-07 18:00:23 -07002885 if (!mOptionsMenuOpen || mIconView) {
2886 // This page has begun to load, so show the title bar
2887 showFakeTitleBar();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002888 }
2889 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002890 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002891
Grace Kloba22ac16e2009-10-07 18:00:23 -07002892 void onShowCustomView(View view, WebChromeClient.CustomViewCallback callback) {
Derek Sollenberger8ff57db2009-12-08 15:39:55 -05002893 // if a view already exists then immediately terminate the new one
2894 if (mCustomView != null) {
2895 callback.onCustomViewHidden();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002896 return;
Derek Sollenberger8ff57db2009-12-08 15:39:55 -05002897 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002898
2899 // Add the custom view to its container.
2900 mCustomViewContainer.addView(view, COVER_SCREEN_GRAVITY_CENTER);
2901 mCustomView = view;
2902 mCustomViewCallback = callback;
2903 // Save the menu state and set it to empty while the custom
2904 // view is showing.
2905 mOldMenuState = mMenuState;
2906 mMenuState = EMPTY_MENU;
2907 // Hide the content view.
2908 mContentView.setVisibility(View.GONE);
2909 // Finally show the custom view container.
Andrei Popescu163ab742009-10-20 17:58:23 +01002910 setStatusBarVisibility(false);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002911 mCustomViewContainer.setVisibility(View.VISIBLE);
2912 mCustomViewContainer.bringToFront();
2913 }
2914
2915 void onHideCustomView() {
2916 if (mCustomView == null)
2917 return;
2918
2919 // Hide the custom view.
2920 mCustomView.setVisibility(View.GONE);
2921 // Remove the custom view from its container.
2922 mCustomViewContainer.removeView(mCustomView);
2923 mCustomView = null;
2924 // Reset the old menu state.
2925 mMenuState = mOldMenuState;
2926 mOldMenuState = EMPTY_MENU;
2927 mCustomViewContainer.setVisibility(View.GONE);
2928 mCustomViewCallback.onCustomViewHidden();
2929 // Show the content view.
Andrei Popescu163ab742009-10-20 17:58:23 +01002930 setStatusBarVisibility(true);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002931 mContentView.setVisibility(View.VISIBLE);
2932 }
2933
2934 Bitmap getDefaultVideoPoster() {
2935 if (mDefaultVideoPoster == null) {
2936 mDefaultVideoPoster = BitmapFactory.decodeResource(
2937 getResources(), R.drawable.default_video_poster);
Patrick Scott3918d442009-08-04 13:22:29 -04002938 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002939 return mDefaultVideoPoster;
2940 }
Patrick Scott3918d442009-08-04 13:22:29 -04002941
Grace Kloba22ac16e2009-10-07 18:00:23 -07002942 View getVideoLoadingProgressView() {
2943 if (mVideoProgressView == null) {
2944 LayoutInflater inflater = LayoutInflater.from(BrowserActivity.this);
2945 mVideoProgressView = inflater.inflate(
2946 R.layout.video_loading_progress, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002947 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002948 return mVideoProgressView;
2949 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002950
Leon Scroggins8d5fa432009-10-02 15:55:59 -04002951 /*
2952 * The Object used to inform the WebView of the file to upload.
2953 */
2954 private ValueCallback<Uri> mUploadMessage;
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002955 private String mCameraFilePath;
Leon Scroggins8d5fa432009-10-02 15:55:59 -04002956
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002957 void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
2958
2959 final String imageMimeType = "image/*";
Ben Murdoch6af492a2010-06-15 12:38:17 +01002960 final String videoMimeType = "video/*";
Ben Murdoch039bd472010-07-21 21:26:57 +01002961 final String audioMimeType = "audio/*";
Ben Murdochb50d7402010-07-16 12:42:22 +01002962 final String mediaSourceKey = "capture";
Ben Murdoch6af492a2010-06-15 12:38:17 +01002963 final String mediaSourceValueCamera = "camera";
Ben Murdochb50d7402010-07-16 12:42:22 +01002964 final String mediaSourceValueFileSystem = "filesystem";
Ben Murdoch6af492a2010-06-15 12:38:17 +01002965 final String mediaSourceValueCamcorder = "camcorder";
Ben Murdoch039bd472010-07-21 21:26:57 +01002966 final String mediaSourceValueMicrophone = "microphone";
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002967
Ben Murdoch039bd472010-07-21 21:26:57 +01002968 // media source can be 'filesystem' or 'camera' or 'camcorder' or 'microphone'.
Ben Murdoch6af492a2010-06-15 12:38:17 +01002969 String mediaSource = "";
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002970
Ben Murdoch6af492a2010-06-15 12:38:17 +01002971 // We add the camera intent if there was no accept type (or '*/*' or 'image/*').
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002972 boolean addCameraIntent = true;
Ben Murdoch6af492a2010-06-15 12:38:17 +01002973 // We add the camcorder intent if there was no accept type (or '*/*' or 'video/*').
2974 boolean addCamcorderIntent = true;
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002975
Ben Murdoch6af492a2010-06-15 12:38:17 +01002976 if (mUploadMessage != null) {
2977 // Already a file picker operation in progress.
2978 return;
2979 }
2980
Grace Kloba22ac16e2009-10-07 18:00:23 -07002981 mUploadMessage = uploadMsg;
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002982
2983 // Parse the accept type.
2984 String params[] = acceptType.split(";");
2985 String mimeType = params[0];
2986
2987 for (String p : params) {
2988 String[] keyValue = p.split("=");
2989 if (keyValue.length == 2) {
2990 // Process key=value parameters.
Ben Murdoch6af492a2010-06-15 12:38:17 +01002991 if (mediaSourceKey.equals(keyValue[0])) {
2992 mediaSource = keyValue[1];
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002993 }
2994 }
2995 }
2996
2997 // This intent will display the standard OPENABLE file picker.
Grace Kloba22ac16e2009-10-07 18:00:23 -07002998 Intent i = new Intent(Intent.ACTION_GET_CONTENT);
2999 i.addCategory(Intent.CATEGORY_OPENABLE);
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003000
3001 // Create an intent to add to the standard file picker that will
3002 // capture an image from the camera. We'll combine this intent with
3003 // the standard OPENABLE picker unless the web developer specifically
3004 // requested the camera or gallery be opened by passing a parameter
3005 // in the accept type.
3006 Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
3007 File externalDataDir = Environment.getExternalStoragePublicDirectory(
3008 Environment.DIRECTORY_DCIM);
3009 File cameraDataDir = new File(externalDataDir.getAbsolutePath() +
3010 File.separator + "browser-photos");
3011 cameraDataDir.mkdirs();
3012 mCameraFilePath = cameraDataDir.getAbsolutePath() + File.separator +
3013 System.currentTimeMillis() + ".jpg";
3014 cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(mCameraFilePath)));
3015
Ben Murdoch6af492a2010-06-15 12:38:17 +01003016 Intent camcorderIntent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
3017
Ben Murdoch039bd472010-07-21 21:26:57 +01003018 Intent soundRecIntent = new Intent(MediaStore.Audio.Media.RECORD_SOUND_ACTION);
3019
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003020 if (mimeType.equals(imageMimeType)) {
3021 i.setType(imageMimeType);
Ben Murdoch6af492a2010-06-15 12:38:17 +01003022 addCamcorderIntent = false;
3023 if (mediaSource.equals(mediaSourceValueCamera)) {
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003024 // Specified 'image/*' and requested the camera, so go ahead and launch the camera
3025 // directly.
3026 BrowserActivity.this.startActivityForResult(cameraIntent, FILE_SELECTED);
3027 return;
Ben Murdochb50d7402010-07-16 12:42:22 +01003028 } else if (mediaSource.equals(mediaSourceValueFileSystem)) {
3029 // Specified filesytem as the source, so don't want to consider the camera.
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003030 addCameraIntent = false;
3031 }
Ben Murdoch6af492a2010-06-15 12:38:17 +01003032 } else if (mimeType.equals(videoMimeType)) {
3033 i.setType(videoMimeType);
3034 addCameraIntent = false;
3035 // The camcorder saves it's own file and returns it to us in the intent, so
3036 // we don't need to generate one here.
3037 mCameraFilePath = null;
3038
3039 if (mediaSource.equals(mediaSourceValueCamcorder)) {
Ben Murdoch039bd472010-07-21 21:26:57 +01003040 // Specified 'video/*' and requested the camcorder, so go ahead and launch the
3041 // camcorder directly.
Ben Murdoch6af492a2010-06-15 12:38:17 +01003042 BrowserActivity.this.startActivityForResult(camcorderIntent, FILE_SELECTED);
3043 return;
Ben Murdochb50d7402010-07-16 12:42:22 +01003044 } else if (mediaSource.equals(mediaSourceValueFileSystem)) {
3045 // Specified filesystem as the source, so don't want to consider the camcorder.
Ben Murdoch6af492a2010-06-15 12:38:17 +01003046 addCamcorderIntent = false;
3047 }
Ben Murdoch039bd472010-07-21 21:26:57 +01003048 } else if (mimeType.equals(audioMimeType)) {
3049 i.setType(audioMimeType);
3050 addCameraIntent = false;
3051 addCamcorderIntent = false;
3052 if (mediaSource.equals(mediaSourceValueMicrophone)) {
3053 // Specified 'audio/*' and requested microphone, so go ahead and launch the sound
3054 // recorder.
3055 BrowserActivity.this.startActivityForResult(soundRecIntent, FILE_SELECTED);
3056 return;
3057 }
3058 // On a default system, there is no single option to open an audio "gallery". Both the
3059 // sound recorder and music browser respond to the OPENABLE/audio/* intent unlike the
3060 // image/* and video/* OPENABLE intents where the image / video gallery are the only
3061 // respondants (and so the user is not prompted by default).
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003062 } else {
3063 i.setType("*/*");
3064 }
3065
Ben Murdoch6af492a2010-06-15 12:38:17 +01003066 // Combine the chooser and the extra choices (like camera or camcorder)
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003067 Intent chooser = new Intent(Intent.ACTION_CHOOSER);
3068 chooser.putExtra(Intent.EXTRA_INTENT, i);
3069
Ben Murdoch6af492a2010-06-15 12:38:17 +01003070 Vector<Intent> extraInitialIntents = new Vector<Intent>(0);
3071
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003072 if (addCameraIntent) {
Ben Murdoch6af492a2010-06-15 12:38:17 +01003073 extraInitialIntents.add(cameraIntent);
3074 }
3075
3076 if (addCamcorderIntent) {
3077 extraInitialIntents.add(camcorderIntent);
3078 }
3079
3080 if (extraInitialIntents.size() > 0) {
3081 Intent[] extraIntents = new Intent[extraInitialIntents.size()];
3082 chooser.putExtra(Intent.EXTRA_INITIAL_INTENTS, extraInitialIntents.toArray(extraIntents));
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003083 }
3084
3085 chooser.putExtra(Intent.EXTRA_TITLE, getString(R.string.choose_upload));
3086 BrowserActivity.this.startActivityForResult(chooser, FILE_SELECTED);
Grace Kloba22ac16e2009-10-07 18:00:23 -07003087 }
3088
3089 // -------------------------------------------------------------------------
3090 // Implement functions for DownloadListener
3091 // -------------------------------------------------------------------------
3092
The Android Open Source Project0c908882009-03-03 19:32:16 -08003093 /**
3094 * Notify the host application a download should be done, or that
3095 * the data should be streamed if a streaming viewer is available.
3096 * @param url The full url to the content that should be downloaded
3097 * @param contentDisposition Content-disposition http header, if
3098 * present.
3099 * @param mimetype The mimetype of the content reported by the server
3100 * @param contentLength The file size reported by the server
3101 */
3102 public void onDownloadStart(String url, String userAgent,
3103 String contentDisposition, String mimetype, long contentLength) {
3104 // if we're dealing wih A/V content that's not explicitly marked
3105 // for download, check if it's streamable.
3106 if (contentDisposition == null
Patrick Scotte1fb9662009-08-31 14:31:52 -04003107 || !contentDisposition.regionMatches(
3108 true, 0, "attachment", 0, 10)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003109 // query the package manager to see if there's a registered handler
3110 // that matches.
3111 Intent intent = new Intent(Intent.ACTION_VIEW);
3112 intent.setDataAndType(Uri.parse(url), mimetype);
Patrick Scotte1fb9662009-08-31 14:31:52 -04003113 ResolveInfo info = getPackageManager().resolveActivity(intent,
3114 PackageManager.MATCH_DEFAULT_ONLY);
3115 if (info != null) {
3116 ComponentName myName = getComponentName();
3117 // If we resolved to ourselves, we don't want to attempt to
3118 // load the url only to try and download it again.
3119 if (!myName.getPackageName().equals(
3120 info.activityInfo.packageName)
3121 || !myName.getClassName().equals(
3122 info.activityInfo.name)) {
3123 // someone (other than us) knows how to handle this mime
3124 // type with this scheme, don't download.
3125 try {
3126 startActivity(intent);
3127 return;
3128 } catch (ActivityNotFoundException ex) {
3129 if (LOGD_ENABLED) {
3130 Log.d(LOGTAG, "activity not found for " + mimetype
3131 + " over " + Uri.parse(url).getScheme(),
3132 ex);
3133 }
3134 // Best behavior is to fall back to a download in this
3135 // case
The Android Open Source Project0c908882009-03-03 19:32:16 -08003136 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003137 }
3138 }
3139 }
3140 onDownloadStartNoStream(url, userAgent, contentDisposition, mimetype, contentLength);
3141 }
3142
Kristian Monsenfa52d172010-03-25 18:29:21 +00003143 // This is to work around the fact that java.net.URI throws Exceptions
3144 // instead of just encoding URL's properly
3145 // Helper method for onDownloadStartNoStream
3146 private static String encodePath(String path) {
3147 char[] chars = path.toCharArray();
3148
3149 boolean needed = false;
3150 for (char c : chars) {
3151 if (c == '[' || c == ']') {
3152 needed = true;
3153 break;
3154 }
3155 }
3156 if (needed == false) {
3157 return path;
3158 }
3159
3160 StringBuilder sb = new StringBuilder("");
3161 for (char c : chars) {
3162 if (c == '[' || c == ']') {
3163 sb.append('%');
3164 sb.append(Integer.toHexString(c));
3165 } else {
3166 sb.append(c);
3167 }
3168 }
3169
3170 return sb.toString();
3171 }
3172
The Android Open Source Project0c908882009-03-03 19:32:16 -08003173 /**
3174 * Notify the host application a download should be done, even if there
3175 * is a streaming viewer available for thise type.
3176 * @param url The full url to the content that should be downloaded
3177 * @param contentDisposition Content-disposition http header, if
3178 * present.
3179 * @param mimetype The mimetype of the content reported by the server
3180 * @param contentLength The file size reported by the server
3181 */
3182 /*package */ void onDownloadStartNoStream(String url, String userAgent,
3183 String contentDisposition, String mimetype, long contentLength) {
3184
3185 String filename = URLUtil.guessFileName(url,
3186 contentDisposition, mimetype);
3187
3188 // Check to see if we have an SDCard
3189 String status = Environment.getExternalStorageState();
3190 if (!status.equals(Environment.MEDIA_MOUNTED)) {
3191 int title;
3192 String msg;
3193
3194 // Check to see if the SDCard is busy, same as the music app
3195 if (status.equals(Environment.MEDIA_SHARED)) {
3196 msg = getString(R.string.download_sdcard_busy_dlg_msg);
3197 title = R.string.download_sdcard_busy_dlg_title;
3198 } else {
3199 msg = getString(R.string.download_no_sdcard_dlg_msg, filename);
3200 title = R.string.download_no_sdcard_dlg_title;
3201 }
3202
3203 new AlertDialog.Builder(this)
3204 .setTitle(title)
3205 .setIcon(android.R.drawable.ic_dialog_alert)
3206 .setMessage(msg)
3207 .setPositiveButton(R.string.ok, null)
3208 .show();
3209 return;
3210 }
3211
Kristian Monsenfa52d172010-03-25 18:29:21 +00003212 // java.net.URI is a lot stricter than KURL so we have to encode some
3213 // extra characters. Fix for b 2538060 and b 1634719
3214 WebAddress webAddress;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003215 try {
Kristian Monsenfa52d172010-03-25 18:29:21 +00003216 webAddress = new WebAddress(url);
Bjorn Bringert131ab512010-10-12 16:25:47 +01003217 webAddress.setPath(encodePath(webAddress.getPath()));
The Android Open Source Project0c908882009-03-03 19:32:16 -08003218 } catch (Exception e) {
Kristian Monsenfa52d172010-03-25 18:29:21 +00003219 // This only happens for very bad urls, we want to chatch the
3220 // exception here
3221 Log.e(LOGTAG, "Exception trying to parse url:" + url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003222 return;
3223 }
3224
3225 // XXX: Have to use the old url since the cookies were stored using the
3226 // old percent-encoded url.
3227 String cookies = CookieManager.getInstance().getCookie(url);
3228
3229 ContentValues values = new ContentValues();
Kristian Monsenfa52d172010-03-25 18:29:21 +00003230 values.put(Downloads.Impl.COLUMN_URI, webAddress.toString());
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08003231 values.put(Downloads.Impl.COLUMN_COOKIE_DATA, cookies);
3232 values.put(Downloads.Impl.COLUMN_USER_AGENT, userAgent);
3233 values.put(Downloads.Impl.COLUMN_NOTIFICATION_PACKAGE,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003234 getPackageName());
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08003235 values.put(Downloads.Impl.COLUMN_NOTIFICATION_CLASS,
Leon Scrogginsa563d092010-04-19 16:53:49 -04003236 OpenDownloadReceiver.class.getCanonicalName());
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08003237 values.put(Downloads.Impl.COLUMN_VISIBILITY,
3238 Downloads.Impl.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
3239 values.put(Downloads.Impl.COLUMN_MIME_TYPE, mimetype);
3240 values.put(Downloads.Impl.COLUMN_FILE_NAME_HINT, filename);
Bjorn Bringert131ab512010-10-12 16:25:47 +01003241 values.put(Downloads.Impl.COLUMN_DESCRIPTION, webAddress.getHost());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003242 if (contentLength > 0) {
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08003243 values.put(Downloads.Impl.COLUMN_TOTAL_BYTES, contentLength);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003244 }
3245 if (mimetype == null) {
3246 // We must have long pressed on a link or image to download it. We
3247 // are not sure of the mimetype in this case, so do a head request
3248 new FetchUrlMimeType(this).execute(values);
3249 } else {
3250 final Uri contentUri =
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08003251 getContentResolver().insert(Downloads.Impl.CONTENT_URI, values);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003252 }
Leon Scroggins9191a7f2010-03-18 14:44:44 -04003253 Toast.makeText(this, R.string.download_pending, Toast.LENGTH_SHORT)
3254 .show();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003255 }
3256
Grace Kloba22ac16e2009-10-07 18:00:23 -07003257 // -------------------------------------------------------------------------
3258
The Android Open Source Project0c908882009-03-03 19:32:16 -08003259 /**
3260 * Resets the lock icon. This method is called when we start a new load and
3261 * know the url to be loaded.
3262 */
3263 private void resetLockIcon(String url) {
3264 // Save the lock-icon state (we revert to it if the load gets cancelled)
Grace Kloba22ac16e2009-10-07 18:00:23 -07003265 mTabControl.getCurrentTab().resetLockIcon(url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003266 updateLockIconImage(LOCK_ICON_UNSECURE);
3267 }
3268
The Android Open Source Project0c908882009-03-03 19:32:16 -08003269 /**
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04003270 * Update the lock icon to correspond to our latest state.
3271 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003272 private void updateLockIconToLatest() {
Leon Scroggins91f65fc2010-06-29 13:52:39 -04003273 Tab t = mTabControl.getCurrentTab();
3274 if (t != null) {
3275 updateLockIconImage(t.getLockIconType());
3276 }
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04003277 }
3278
3279 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08003280 * Updates the lock-icon image in the title-bar.
3281 */
3282 private void updateLockIconImage(int lockIconType) {
3283 Drawable d = null;
3284 if (lockIconType == LOCK_ICON_SECURE) {
3285 d = mSecLockIcon;
3286 } else if (lockIconType == LOCK_ICON_MIXED) {
3287 d = mMixLockIcon;
3288 }
Leon Scroggins68579392009-09-15 15:31:54 -04003289 mTitleBar.setLock(d);
Michael Kolba2b2ba82010-08-04 17:54:03 -07003290 mFakeTitleBar.setLock(d);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003291 }
3292
3293 /**
3294 * Displays a page-info dialog.
3295 * @param tab The tab to show info about
3296 * @param fromShowSSLCertificateOnError The flag that indicates whether
3297 * this dialog was opened from the SSL-certificate-on-error dialog or
3298 * not. This is important, since we need to know whether to return to
3299 * the parent dialog or simply dismiss.
3300 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003301 private void showPageInfo(final Tab tab,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003302 final boolean fromShowSSLCertificateOnError) {
3303 final LayoutInflater factory = LayoutInflater
3304 .from(this);
3305
3306 final View pageInfoView = factory.inflate(R.layout.page_info, null);
3307
3308 final WebView view = tab.getWebView();
3309
3310 String url = null;
3311 String title = null;
3312
3313 if (view == null) {
3314 url = tab.getUrl();
3315 title = tab.getTitle();
3316 } else if (view == mTabControl.getCurrentWebView()) {
3317 // Use the cached title and url if this is the current WebView
3318 url = mUrl;
3319 title = mTitle;
3320 } else {
3321 url = view.getUrl();
3322 title = view.getTitle();
3323 }
3324
3325 if (url == null) {
3326 url = "";
3327 }
3328 if (title == null) {
3329 title = "";
3330 }
3331
3332 ((TextView) pageInfoView.findViewById(R.id.address)).setText(url);
3333 ((TextView) pageInfoView.findViewById(R.id.title)).setText(title);
3334
3335 mPageInfoView = tab;
Leon Scrogginsc7b92f82010-01-11 18:17:31 -05003336 mPageInfoFromShowSSLCertificateOnError = fromShowSSLCertificateOnError;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003337
3338 AlertDialog.Builder alertDialogBuilder =
3339 new AlertDialog.Builder(this)
3340 .setTitle(R.string.page_info).setIcon(android.R.drawable.ic_dialog_info)
3341 .setView(pageInfoView)
3342 .setPositiveButton(
3343 R.string.ok,
3344 new DialogInterface.OnClickListener() {
3345 public void onClick(DialogInterface dialog,
3346 int whichButton) {
3347 mPageInfoDialog = null;
3348 mPageInfoView = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003349
3350 // if we came here from the SSL error dialog
3351 if (fromShowSSLCertificateOnError) {
3352 // go back to the SSL error dialog
3353 showSSLCertificateOnError(
3354 mSSLCertificateOnErrorView,
3355 mSSLCertificateOnErrorHandler,
3356 mSSLCertificateOnErrorError);
3357 }
3358 }
3359 })
3360 .setOnCancelListener(
3361 new DialogInterface.OnCancelListener() {
3362 public void onCancel(DialogInterface dialog) {
3363 mPageInfoDialog = null;
3364 mPageInfoView = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003365
3366 // if we came here from the SSL error dialog
3367 if (fromShowSSLCertificateOnError) {
3368 // go back to the SSL error dialog
3369 showSSLCertificateOnError(
3370 mSSLCertificateOnErrorView,
3371 mSSLCertificateOnErrorHandler,
3372 mSSLCertificateOnErrorError);
3373 }
3374 }
3375 });
3376
3377 // if we have a main top-level page SSL certificate set or a certificate
3378 // error
3379 if (fromShowSSLCertificateOnError ||
3380 (view != null && view.getCertificate() != null)) {
3381 // add a 'View Certificate' button
3382 alertDialogBuilder.setNeutralButton(
3383 R.string.view_certificate,
3384 new DialogInterface.OnClickListener() {
3385 public void onClick(DialogInterface dialog,
3386 int whichButton) {
3387 mPageInfoDialog = null;
3388 mPageInfoView = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003389
3390 // if we came here from the SSL error dialog
3391 if (fromShowSSLCertificateOnError) {
3392 // go back to the SSL error dialog
3393 showSSLCertificateOnError(
3394 mSSLCertificateOnErrorView,
3395 mSSLCertificateOnErrorHandler,
3396 mSSLCertificateOnErrorError);
3397 } else {
3398 // otherwise, display the top-most certificate from
3399 // the chain
3400 if (view.getCertificate() != null) {
3401 showSSLCertificate(tab);
3402 }
3403 }
3404 }
3405 });
3406 }
3407
3408 mPageInfoDialog = alertDialogBuilder.show();
3409 }
3410
3411 /**
3412 * Displays the main top-level page SSL certificate dialog
3413 * (accessible from the Page-Info dialog).
3414 * @param tab The tab to show certificate for.
3415 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003416 private void showSSLCertificate(final Tab tab) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003417 final View certificateView =
3418 inflateCertificateView(tab.getWebView().getCertificate());
3419 if (certificateView == null) {
3420 return;
3421 }
3422
3423 LayoutInflater factory = LayoutInflater.from(this);
3424
3425 final LinearLayout placeholder =
3426 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3427
3428 LinearLayout ll = (LinearLayout) factory.inflate(
3429 R.layout.ssl_success, placeholder);
3430 ((TextView)ll.findViewById(R.id.success))
3431 .setText(R.string.ssl_certificate_is_valid);
3432
3433 mSSLCertificateView = tab;
3434 mSSLCertificateDialog =
3435 new AlertDialog.Builder(this)
3436 .setTitle(R.string.ssl_certificate).setIcon(
3437 R.drawable.ic_dialog_browser_certificate_secure)
3438 .setView(certificateView)
3439 .setPositiveButton(R.string.ok,
3440 new DialogInterface.OnClickListener() {
3441 public void onClick(DialogInterface dialog,
3442 int whichButton) {
3443 mSSLCertificateDialog = null;
3444 mSSLCertificateView = null;
3445
3446 showPageInfo(tab, false);
3447 }
3448 })
3449 .setOnCancelListener(
3450 new DialogInterface.OnCancelListener() {
3451 public void onCancel(DialogInterface dialog) {
3452 mSSLCertificateDialog = null;
3453 mSSLCertificateView = null;
3454
3455 showPageInfo(tab, false);
3456 }
3457 })
3458 .show();
3459 }
3460
3461 /**
3462 * Displays the SSL error certificate dialog.
3463 * @param view The target web-view.
3464 * @param handler The SSL error handler responsible for cancelling the
3465 * connection that resulted in an SSL error or proceeding per user request.
3466 * @param error The SSL error object.
3467 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003468 void showSSLCertificateOnError(
The Android Open Source Project0c908882009-03-03 19:32:16 -08003469 final WebView view, final SslErrorHandler handler, final SslError error) {
3470
3471 final View certificateView =
3472 inflateCertificateView(error.getCertificate());
3473 if (certificateView == null) {
3474 return;
3475 }
3476
3477 LayoutInflater factory = LayoutInflater.from(this);
3478
3479 final LinearLayout placeholder =
3480 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3481
3482 if (error.hasError(SslError.SSL_UNTRUSTED)) {
3483 LinearLayout ll = (LinearLayout)factory
3484 .inflate(R.layout.ssl_warning, placeholder);
3485 ((TextView)ll.findViewById(R.id.warning))
3486 .setText(R.string.ssl_untrusted);
3487 }
3488
3489 if (error.hasError(SslError.SSL_IDMISMATCH)) {
3490 LinearLayout ll = (LinearLayout)factory
3491 .inflate(R.layout.ssl_warning, placeholder);
3492 ((TextView)ll.findViewById(R.id.warning))
3493 .setText(R.string.ssl_mismatch);
3494 }
3495
3496 if (error.hasError(SslError.SSL_EXPIRED)) {
3497 LinearLayout ll = (LinearLayout)factory
3498 .inflate(R.layout.ssl_warning, placeholder);
3499 ((TextView)ll.findViewById(R.id.warning))
3500 .setText(R.string.ssl_expired);
3501 }
3502
3503 if (error.hasError(SslError.SSL_NOTYETVALID)) {
3504 LinearLayout ll = (LinearLayout)factory
3505 .inflate(R.layout.ssl_warning, placeholder);
3506 ((TextView)ll.findViewById(R.id.warning))
3507 .setText(R.string.ssl_not_yet_valid);
3508 }
3509
3510 mSSLCertificateOnErrorHandler = handler;
3511 mSSLCertificateOnErrorView = view;
3512 mSSLCertificateOnErrorError = error;
3513 mSSLCertificateOnErrorDialog =
3514 new AlertDialog.Builder(this)
3515 .setTitle(R.string.ssl_certificate).setIcon(
3516 R.drawable.ic_dialog_browser_certificate_partially_secure)
3517 .setView(certificateView)
3518 .setPositiveButton(R.string.ok,
3519 new DialogInterface.OnClickListener() {
3520 public void onClick(DialogInterface dialog,
3521 int whichButton) {
3522 mSSLCertificateOnErrorDialog = null;
3523 mSSLCertificateOnErrorView = null;
3524 mSSLCertificateOnErrorHandler = null;
3525 mSSLCertificateOnErrorError = null;
3526
Grace Kloba22ac16e2009-10-07 18:00:23 -07003527 view.getWebViewClient().onReceivedSslError(
3528 view, handler, error);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003529 }
3530 })
3531 .setNeutralButton(R.string.page_info_view,
3532 new DialogInterface.OnClickListener() {
3533 public void onClick(DialogInterface dialog,
3534 int whichButton) {
3535 mSSLCertificateOnErrorDialog = null;
3536
3537 // do not clear the dialog state: we will
3538 // need to show the dialog again once the
3539 // user is done exploring the page-info details
3540
3541 showPageInfo(mTabControl.getTabFromView(view),
3542 true);
3543 }
3544 })
3545 .setOnCancelListener(
3546 new DialogInterface.OnCancelListener() {
3547 public void onCancel(DialogInterface dialog) {
3548 mSSLCertificateOnErrorDialog = null;
3549 mSSLCertificateOnErrorView = null;
3550 mSSLCertificateOnErrorHandler = null;
3551 mSSLCertificateOnErrorError = null;
3552
Grace Kloba22ac16e2009-10-07 18:00:23 -07003553 view.getWebViewClient().onReceivedSslError(
3554 view, handler, error);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003555 }
3556 })
3557 .show();
3558 }
3559
3560 /**
3561 * Inflates the SSL certificate view (helper method).
3562 * @param certificate The SSL certificate.
3563 * @return The resultant certificate view with issued-to, issued-by,
3564 * issued-on, expires-on, and possibly other fields set.
3565 * If the input certificate is null, returns null.
3566 */
3567 private View inflateCertificateView(SslCertificate certificate) {
3568 if (certificate == null) {
3569 return null;
3570 }
3571
3572 LayoutInflater factory = LayoutInflater.from(this);
3573
3574 View certificateView = factory.inflate(
3575 R.layout.ssl_certificate, null);
3576
3577 // issued to:
3578 SslCertificate.DName issuedTo = certificate.getIssuedTo();
3579 if (issuedTo != null) {
3580 ((TextView) certificateView.findViewById(R.id.to_common))
3581 .setText(issuedTo.getCName());
3582 ((TextView) certificateView.findViewById(R.id.to_org))
3583 .setText(issuedTo.getOName());
3584 ((TextView) certificateView.findViewById(R.id.to_org_unit))
3585 .setText(issuedTo.getUName());
3586 }
3587
3588 // issued by:
3589 SslCertificate.DName issuedBy = certificate.getIssuedBy();
3590 if (issuedBy != null) {
3591 ((TextView) certificateView.findViewById(R.id.by_common))
3592 .setText(issuedBy.getCName());
3593 ((TextView) certificateView.findViewById(R.id.by_org))
3594 .setText(issuedBy.getOName());
3595 ((TextView) certificateView.findViewById(R.id.by_org_unit))
3596 .setText(issuedBy.getUName());
3597 }
3598
3599 // issued on:
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003600 String issuedOn = formatCertificateDate(
3601 certificate.getValidNotBeforeDate());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003602 ((TextView) certificateView.findViewById(R.id.issued_on))
3603 .setText(issuedOn);
3604
3605 // expires on:
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003606 String expiresOn = formatCertificateDate(
3607 certificate.getValidNotAfterDate());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003608 ((TextView) certificateView.findViewById(R.id.expires_on))
3609 .setText(expiresOn);
3610
3611 return certificateView;
3612 }
3613
3614 /**
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003615 * Formats the certificate date to a properly localized date string.
The Android Open Source Project0c908882009-03-03 19:32:16 -08003616 * @return Properly localized version of the certificate date string and
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003617 * the "" if it fails to localize.
The Android Open Source Project0c908882009-03-03 19:32:16 -08003618 */
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003619 private String formatCertificateDate(Date certificateDate) {
3620 if (certificateDate == null) {
3621 return "";
The Android Open Source Project0c908882009-03-03 19:32:16 -08003622 }
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003623 String formattedDate = DateFormat.getDateFormat(this).format(certificateDate);
3624 if (formattedDate == null) {
3625 return "";
3626 }
3627 return formattedDate;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003628 }
3629
3630 /**
3631 * Displays an http-authentication dialog.
3632 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003633 void showHttpAuthentication(final HttpAuthHandler handler,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003634 final String host, final String realm, final String title,
3635 final String name, final String password, int focusId) {
3636 LayoutInflater factory = LayoutInflater.from(this);
3637 final View v = factory
3638 .inflate(R.layout.http_authentication, null);
3639 if (name != null) {
3640 ((EditText) v.findViewById(R.id.username_edit)).setText(name);
3641 }
3642 if (password != null) {
3643 ((EditText) v.findViewById(R.id.password_edit)).setText(password);
3644 }
3645
3646 String titleText = title;
3647 if (titleText == null) {
3648 titleText = getText(R.string.sign_in_to).toString().replace(
3649 "%s1", host).replace("%s2", realm);
3650 }
3651
3652 mHttpAuthHandler = handler;
3653 AlertDialog dialog = new AlertDialog.Builder(this)
3654 .setTitle(titleText)
3655 .setIcon(android.R.drawable.ic_dialog_alert)
3656 .setView(v)
3657 .setPositiveButton(R.string.action,
3658 new DialogInterface.OnClickListener() {
3659 public void onClick(DialogInterface dialog,
3660 int whichButton) {
3661 String nm = ((EditText) v
3662 .findViewById(R.id.username_edit))
3663 .getText().toString();
3664 String pw = ((EditText) v
3665 .findViewById(R.id.password_edit))
3666 .getText().toString();
3667 BrowserActivity.this.setHttpAuthUsernamePassword
3668 (host, realm, nm, pw);
3669 handler.proceed(nm, pw);
3670 mHttpAuthenticationDialog = null;
3671 mHttpAuthHandler = null;
3672 }})
3673 .setNegativeButton(R.string.cancel,
3674 new DialogInterface.OnClickListener() {
3675 public void onClick(DialogInterface dialog,
3676 int whichButton) {
3677 handler.cancel();
3678 BrowserActivity.this.resetTitleAndRevertLockIcon();
3679 mHttpAuthenticationDialog = null;
3680 mHttpAuthHandler = null;
3681 }})
3682 .setOnCancelListener(new DialogInterface.OnCancelListener() {
3683 public void onCancel(DialogInterface dialog) {
3684 handler.cancel();
3685 BrowserActivity.this.resetTitleAndRevertLockIcon();
3686 mHttpAuthenticationDialog = null;
3687 mHttpAuthHandler = null;
3688 }})
3689 .create();
3690 // Make the IME appear when the dialog is displayed if applicable.
3691 dialog.getWindow().setSoftInputMode(
3692 WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
3693 dialog.show();
3694 if (focusId != 0) {
3695 dialog.findViewById(focusId).requestFocus();
3696 } else {
3697 v.findViewById(R.id.username_edit).requestFocus();
3698 }
3699 mHttpAuthenticationDialog = dialog;
3700 }
3701
3702 public int getProgress() {
3703 WebView w = mTabControl.getCurrentWebView();
3704 if (w != null) {
3705 return w.getProgress();
3706 } else {
3707 return 100;
3708 }
3709 }
3710
3711 /**
3712 * Set HTTP authentication password.
3713 *
3714 * @param host The host for the password
3715 * @param realm The realm for the password
3716 * @param username The username for the password. If it is null, it means
3717 * password can't be saved.
3718 * @param password The password
3719 */
3720 public void setHttpAuthUsernamePassword(String host, String realm,
3721 String username,
3722 String password) {
Steve Block95a53b22010-03-25 17:24:58 +00003723 WebView w = getTopWindow();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003724 if (w != null) {
3725 w.setHttpAuthUsernamePassword(host, realm, username, password);
3726 }
3727 }
3728
3729 /**
3730 * connectivity manager says net has come or gone... inform the user
3731 * @param up true if net has come up, false if net has gone down
3732 */
3733 public void onNetworkToggle(boolean up) {
3734 if (up == mIsNetworkUp) {
3735 return;
3736 } else if (up) {
3737 mIsNetworkUp = true;
3738 if (mAlertDialog != null) {
3739 mAlertDialog.cancel();
3740 mAlertDialog = null;
3741 }
3742 } else {
3743 mIsNetworkUp = false;
Patrick Scotteb6ab2a2009-09-16 10:00:17 -04003744 if (mInLoad) {
3745 createAndShowNetworkDialog();
3746 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003747 }
3748 WebView w = mTabControl.getCurrentWebView();
3749 if (w != null) {
3750 w.setNetworkAvailable(up);
3751 }
3752 }
3753
Grace Kloba22ac16e2009-10-07 18:00:23 -07003754 boolean isNetworkUp() {
3755 return mIsNetworkUp;
3756 }
3757
Patrick Scotteb6ab2a2009-09-16 10:00:17 -04003758 // This method shows the network dialog alerting the user that the net is
3759 // down. It will only show the dialog if mAlertDialog is null.
3760 private void createAndShowNetworkDialog() {
3761 if (mAlertDialog == null) {
3762 mAlertDialog = new AlertDialog.Builder(this)
3763 .setTitle(R.string.loadSuspendedTitle)
3764 .setMessage(R.string.loadSuspended)
3765 .setPositiveButton(R.string.ok, null)
3766 .show();
3767 }
3768 }
3769
Michael Kolbe421c242010-10-04 19:29:01 -07003770 /**
3771 * callback from ComboPage when bookmark/history selection
3772 */
3773 @Override
3774 public void onUrlSelected(String url, boolean newTab) {
3775 removeComboView();
3776 if (!TextUtils.isEmpty(url)) {
3777 if (newTab) {
3778 openTab(url, false);
3779 } else {
3780 final Tab currentTab = mTabControl.getCurrentTab();
3781 dismissSubWindow(currentTab);
3782 loadUrl(getTopWindow(), url);
3783 }
3784 }
3785 }
3786
3787 /**
3788 * callback from ComboPage when dismissed
3789 */
3790 @Override
3791 public void onComboCanceled() {
3792 removeComboView();
3793 }
3794
3795 /**
3796 * dismiss the ComboPage
3797 */
3798 /* package */ void removeComboView() {
3799 if (mComboView != null) {
3800 mContentView.removeView(mComboView);
3801 mTitleBar.setVisibility(View.VISIBLE);
3802 mMenuState = R.id.MAIN_MENU;
3803 attachTabToContentView(mTabControl.getCurrentTab());
3804 getTopWindow().requestFocus();
3805 mComboView = null;
3806 }
3807 }
3808
3809 /**
3810 * callback from ComboPage when clear history is requested
3811 */
3812 public void onRemoveParentChildRelationships() {
3813 mTabControl.removeParentChildRelationShips();
3814 }
3815
The Android Open Source Project0c908882009-03-03 19:32:16 -08003816 @Override
3817 protected void onActivityResult(int requestCode, int resultCode,
3818 Intent intent) {
Grace Klobabb394f32009-11-19 10:26:37 -08003819 if (getTopWindow() == null) return;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003820 switch (requestCode) {
Leon Scrogginsfde97462010-01-11 13:06:21 -05003821 case PREFERENCES_PAGE:
3822 if (resultCode == RESULT_OK && intent != null) {
3823 String action = intent.getStringExtra(Intent.EXTRA_TEXT);
3824 if (BrowserSettings.PREF_CLEAR_HISTORY.equals(action)) {
3825 mTabControl.removeParentChildRelationShips();
3826 }
3827 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003828 break;
Leon Scroggins8d5fa432009-10-02 15:55:59 -04003829 // Choose a file from the file picker.
3830 case FILE_SELECTED:
3831 if (null == mUploadMessage) break;
3832 Uri result = intent == null || resultCode != RESULT_OK ? null
3833 : intent.getData();
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003834
3835 // As we ask the camera to save the result of the user taking
3836 // a picture, the camera application does not return anything other
3837 // than RESULT_OK. So we need to check whether the file we expected
3838 // was written to disk in the in the case that we
3839 // did not get an intent returned but did get a RESULT_OK. If it was,
3840 // we assume that this result has came back from the camera.
3841 if (result == null && intent == null && resultCode == RESULT_OK) {
3842 File cameraFile = new File(mCameraFilePath);
3843 if (cameraFile.exists()) {
3844 result = Uri.fromFile(cameraFile);
Ben Murdoch07d34732010-05-27 18:34:46 +01003845 // Broadcast to the media scanner that we have a new photo
3846 // so it will be added into the gallery for the user.
3847 sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, result));
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003848 }
3849 }
Leon Scroggins8d5fa432009-10-02 15:55:59 -04003850 mUploadMessage.onReceiveValue(result);
3851 mUploadMessage = null;
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003852 mCameraFilePath = null;
Leon Scroggins8d5fa432009-10-02 15:55:59 -04003853 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003854 default:
3855 break;
3856 }
Leon Scroggins30444232009-09-04 18:36:20 -04003857 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003858 }
3859
3860 /*
3861 * This method is called as a result of the user selecting the options
Leon Scrogginsf08809b2010-01-21 09:27:46 -05003862 * menu to see the download window. It shows the download window on top of
3863 * the current window.
The Android Open Source Project0c908882009-03-03 19:32:16 -08003864 */
Leon Scroggins IIIa682a3c2010-09-27 12:32:40 -04003865 private void viewDownloads() {
3866 Intent intent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
3867 startActivity(intent);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003868 }
3869
Michael Kolbc7485ae2010-09-03 10:10:58 -07003870 /* package */ void promptAddOrInstallBookmark(View anchor) {
3871 PopupMenu popup = new PopupMenu(this, anchor);
3872 popup.getMenuInflater().inflate(R.menu.bookmark_shortcut, popup.getMenu());
3873 popup.setOnMenuItemClickListener(this);
3874 popup.show();
3875 }
Michael Kolbebba8b42010-09-30 12:57:59 -07003876
Michael Kolbc7485ae2010-09-03 10:10:58 -07003877 /**
3878 * popup menu item click listener
3879 * @param item
3880 */
3881 public boolean onMenuItemClick(MenuItem item) {
3882 switch(item.getItemId()) {
3883 case R.id.add_bookmark_menu_id:
Michael Kolb370a4f32010-10-06 10:45:32 -07003884 bookmarkCurrentPage(AddBookmarkPage.DEFAULT_FOLDER_ID);
Michael Kolbc7485ae2010-09-03 10:10:58 -07003885 return true;
3886 case R.id.shortcut_to_home_menu_id:
3887 Tab current = mTabControl.getCurrentTab();
3888 current.populatePickerData();
3889 String touchIconUrl = mTabControl.getCurrentWebView().getTouchIconUrl();
3890 if (touchIconUrl != null) {
3891 // Download the touch icon for this site then save
3892 // it to the
3893 // homescreen.
3894 Bundle b = new Bundle();
3895 b.putString("url", current.getUrl());
3896 b.putString("title", current.getTitle());
3897 b.putParcelable("favicon", current.getFavicon());
3898 Message msg = mHandler.obtainMessage(TOUCH_ICON_DOWNLOADED);
3899 msg.setData(b);
3900 new DownloadTouchIcon(BrowserActivity.this, msg,
3901 mTabControl.getCurrentWebView().getSettings().getUserAgentString())
3902 .execute(touchIconUrl);
3903 } else {
3904 // add to homescreen, can do it immediately as there
3905 // is no touch
3906 // icon.
3907 showSaveToHomescreenDialog(
3908 current.getUrl(), current.getTitle(), null, current.getFavicon());
3909 }
3910 return true;
3911 default:
3912 return false;
3913 }
3914 }
Michael Kolbebba8b42010-09-30 12:57:59 -07003915
Michael Kolbc7485ae2010-09-03 10:10:58 -07003916 /* package */Dialog makeAddOrInstallDialog() {
Ben Murdocheecb4e62010-07-06 16:30:38 +01003917 final Tab current = mTabControl.getCurrentTab();
3918 Resources resources = getResources();
Michael Kolbc7485ae2010-09-03 10:10:58 -07003919 CharSequence[] choices =
3920 {resources.getString(R.string.save_to_bookmarks),
3921 resources.getString(R.string.create_shortcut_bookmark)};
Ben Murdocheecb4e62010-07-06 16:30:38 +01003922
3923 AlertDialog.Builder builder = new AlertDialog.Builder(this);
3924 builder.setTitle(R.string.add_new_bookmark);
3925 builder.setItems(choices, new DialogInterface.OnClickListener() {
Michael Kolbc7485ae2010-09-03 10:10:58 -07003926 public void onClick(DialogInterface dialog, int item) {
3927 if (item == 0) {
Michael Kolb370a4f32010-10-06 10:45:32 -07003928 bookmarkCurrentPage(AddBookmarkPage.DEFAULT_FOLDER_ID);
Michael Kolbc7485ae2010-09-03 10:10:58 -07003929 } else if (item == 1) {
3930 }
3931 }
Ben Murdocheecb4e62010-07-06 16:30:38 +01003932 });
Michael Kolbc7485ae2010-09-03 10:10:58 -07003933 return builder.create();
Ben Murdocheecb4e62010-07-06 16:30:38 +01003934 }
3935
Leon Scroggins160a7e72009-08-14 18:28:01 -04003936 /**
3937 * Open the Go page.
3938 * @param startWithHistory If true, open starting on the history tab.
3939 * Otherwise, start with the bookmarks tab.
Leon Scroggins160a7e72009-08-14 18:28:01 -04003940 */
Michael Kolbe421c242010-10-04 19:29:01 -07003941 /* package */ void bookmarksOrHistoryPicker(boolean startWithHistory) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003942 WebView current = mTabControl.getCurrentWebView();
3943 if (current == null) {
3944 return;
3945 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003946 String title = current.getTitle();
3947 String url = current.getUrl();
Ben Murdoch87cc65d2010-06-29 20:34:10 +01003948 Bitmap thumbnail = createScreenshot(current, getDesiredThumbnailWidth(this),
3949 getDesiredThumbnailHeight(this));
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01003950
The Android Open Source Project0c908882009-03-03 19:32:16 -08003951 // Just in case the user opens bookmarks before a page finishes loading
3952 // so the current history item, and therefore the page, is null.
3953 if (null == url) {
3954 url = mLastEnteredUrl;
3955 // This can happen.
3956 if (null == url) {
3957 url = mSettings.getHomePage();
3958 }
3959 }
3960 // In case the web page has not yet received its associated title.
3961 if (title == null) {
3962 title = url;
3963 }
Michael Kolbe421c242010-10-04 19:29:01 -07003964 Bundle extras = new Bundle();
3965 extras.putString("title", title);
3966 extras.putString("url", url);
3967 extras.putParcelable("thumbnail", thumbnail);
Leon Scroggins30444232009-09-04 18:36:20 -04003968 // Disable opening in a new window if we have maxed out the windows
Michael Kolbe421c242010-10-04 19:29:01 -07003969 extras.putBoolean("disable_new_window", !mTabControl.canCreateNewTab());
3970 extras.putString("touch_icon_url", current.getTouchIconUrl());
3971
3972 mComboView = new CombinedBookmarkHistoryView(this,
3973 startWithHistory ? CombinedBookmarkHistoryView.FRAGMENT_ID_HISTORY
3974 : CombinedBookmarkHistoryView.FRAGMENT_ID_BOOKMARKS,
3975 extras);
3976 removeTabFromContentView(mTabControl.getCurrentTab());
3977 mTitleBar.setVisibility(View.GONE);
3978 hideFakeTitleBar();
3979 mContentView.addView(mComboView, COVER_SCREEN_PARAMS);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003980 }
3981
Ben Murdocheecb4e62010-07-06 16:30:38 +01003982 private void showSaveToHomescreenDialog(String url, String title, Bitmap touchIcon,
3983 Bitmap favicon) {
3984 Intent intent = new Intent(this, SaveToHomescreenDialog.class);
3985
3986 // Just in case the user tries to save before a page finishes loading
3987 // so the current history item, and therefore the page, is null.
3988 if (null == url) {
3989 url = mLastEnteredUrl;
3990 // This can happen.
3991 if (null == url) {
3992 url = mSettings.getHomePage();
3993 }
3994 }
3995
3996 // In case the web page has not yet received its associated title.
3997 if (title == null) {
3998 title = url;
3999 }
4000
4001 intent.putExtra("title", title);
4002 intent.putExtra("url", url);
4003 intent.putExtra("favicon", favicon);
4004 intent.putExtra("touchIcon", touchIcon);
4005 startActivity(intent);
4006 }
4007
The Android Open Source Project0c908882009-03-03 19:32:16 -08004008 // Called when loading from context menu or LOAD_URL message
Leon Scroggins92472e82010-02-17 16:32:28 -05004009 private void loadUrlFromContext(WebView view, String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08004010 // In case the user enters nothing.
4011 if (url != null && url.length() != 0 && view != null) {
4012 url = smartUrlFilter(url);
Grace Kloba22ac16e2009-10-07 18:00:23 -07004013 if (!view.getWebViewClient().shouldOverrideUrlLoading(view, url)) {
Leon Scroggins92472e82010-02-17 16:32:28 -05004014 loadUrl(view, url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004015 }
4016 }
4017 }
4018
Leon Scroggins92472e82010-02-17 16:32:28 -05004019 /**
4020 * Load the URL into the given WebView and update the title bar
4021 * to reflect the new load. Call this instead of WebView.loadUrl
4022 * directly.
4023 * @param view The WebView used to load url.
4024 * @param url The URL to load.
4025 */
4026 private void loadUrl(WebView view, String url) {
4027 updateTitleBarForNewLoad(view, url);
4028 view.loadUrl(url);
4029 }
4030
4031 /**
4032 * Load UrlData into a Tab and update the title bar to reflect the new
4033 * load. Call this instead of UrlData.loadIn directly.
4034 * @param t The Tab used to load.
4035 * @param data The UrlData being loaded.
4036 */
4037 private void loadUrlDataIn(Tab t, UrlData data) {
4038 updateTitleBarForNewLoad(t.getWebView(), data.mUrl);
4039 data.loadIn(t);
4040 }
4041
4042 /**
4043 * If the WebView is the top window, update the title bar to reflect
4044 * loading the new URL. i.e. set its text, clear the favicon (which
4045 * will be set once the page begins loading), and set the progress to
4046 * INITIAL_PROGRESS to show that the page has begun to load. Called
4047 * by loadUrl and loadUrlDataIn.
4048 * @param view The WebView that is starting a load.
4049 * @param url The URL that is being loaded.
4050 */
4051 private void updateTitleBarForNewLoad(WebView view, String url) {
4052 if (view == getTopWindow()) {
4053 setUrlTitle(url, null);
4054 setFavicon(null);
4055 onProgressChanged(view, INITIAL_PROGRESS);
4056 }
4057 }
4058
The Android Open Source Project0c908882009-03-03 19:32:16 -08004059 private String smartUrlFilter(Uri inUri) {
4060 if (inUri != null) {
4061 return smartUrlFilter(inUri.toString());
4062 }
4063 return null;
4064 }
4065
Feng Qianb34f87a2009-03-24 21:27:26 -07004066 protected static final Pattern ACCEPTED_URI_SCHEMA = Pattern.compile(
The Android Open Source Project0c908882009-03-03 19:32:16 -08004067 "(?i)" + // switch on case insensitive matching
4068 "(" + // begin group for schema
4069 "(?:http|https|file):\\/\\/" +
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004070 "|(?:inline|data|about|content|javascript):" +
The Android Open Source Project0c908882009-03-03 19:32:16 -08004071 ")" +
4072 "(.*)" );
4073
4074 /**
4075 * Attempts to determine whether user input is a URL or search
4076 * terms. Anything with a space is passed to search.
4077 *
4078 * Converts to lowercase any mistakenly uppercased schema (i.e.,
4079 * "Http://" converts to "http://"
4080 *
4081 * @return Original or modified URL
4082 *
4083 */
4084 String smartUrlFilter(String url) {
4085
4086 String inUrl = url.trim();
4087 boolean hasSpace = inUrl.indexOf(' ') != -1;
4088
4089 Matcher matcher = ACCEPTED_URI_SCHEMA.matcher(inUrl);
4090 if (matcher.matches()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08004091 // force scheme to lowercase
4092 String scheme = matcher.group(1);
4093 String lcScheme = scheme.toLowerCase();
4094 if (!lcScheme.equals(scheme)) {
Mitsuru Oshima123ecfb2009-05-18 19:11:14 -07004095 inUrl = lcScheme + matcher.group(2);
4096 }
4097 if (hasSpace) {
4098 inUrl = inUrl.replace(" ", "%20");
The Android Open Source Project0c908882009-03-03 19:32:16 -08004099 }
4100 return inUrl;
4101 }
Leon Scroggins956cf012010-10-07 13:51:57 -04004102 if (!hasSpace) {
Dan Egnor5ee906c2009-11-18 12:11:49 -08004103 if (Patterns.WEB_URL.matcher(inUrl).matches()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08004104 return URLUtil.guessUrl(inUrl);
4105 }
4106 }
4107
Leon Scroggins956cf012010-10-07 13:51:57 -04004108 // FIXME: Is this the correct place to add to searches?
4109 // what if someone else calls this function?
4110
The Android Open Source Project0c908882009-03-03 19:32:16 -08004111 Browser.addSearchUrl(mResolver, inUrl);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07004112 return URLUtil.composeSearchUrl(inUrl, QuickSearch_G, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004113 }
4114
Ben Murdochbff2d602009-07-01 20:19:05 +01004115 /* package */ void setShouldShowErrorConsole(boolean flag) {
4116 if (flag == mShouldShowErrorConsole) {
4117 // Nothing to do.
4118 return;
4119 }
Leon Scroggins IIIa9e35b62010-09-16 15:30:15 -04004120 Tab t = mTabControl.getCurrentTab();
4121 if (t == null) {
4122 // There is no current tab so we cannot toggle the error console
4123 return;
4124 }
Ben Murdochbff2d602009-07-01 20:19:05 +01004125
4126 mShouldShowErrorConsole = flag;
4127
Leon Scroggins IIIa9e35b62010-09-16 15:30:15 -04004128 ErrorConsoleView errorConsole = t.getErrorConsole(true);
Ben Murdochbff2d602009-07-01 20:19:05 +01004129
4130 if (flag) {
4131 // Setting the show state of the console will cause it's the layout to be inflated.
4132 if (errorConsole.numberOfErrors() > 0) {
4133 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
4134 } else {
4135 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
4136 }
4137
4138 // Now we can add it to the main view.
4139 mErrorConsoleContainer.addView(errorConsole,
Romain Guy15b8ec62010-01-08 15:06:43 -08004140 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
Ben Murdochbff2d602009-07-01 20:19:05 +01004141 ViewGroup.LayoutParams.WRAP_CONTENT));
4142 } else {
4143 mErrorConsoleContainer.removeView(errorConsole);
4144 }
4145
4146 }
4147
Grace Kloba22ac16e2009-10-07 18:00:23 -07004148 boolean shouldShowErrorConsole() {
4149 return mShouldShowErrorConsole;
4150 }
4151
Andrei Popescu163ab742009-10-20 17:58:23 +01004152 private void setStatusBarVisibility(boolean visible) {
4153 int flag = visible ? 0 : WindowManager.LayoutParams.FLAG_FULLSCREEN;
4154 getWindow().setFlags(flag, WindowManager.LayoutParams.FLAG_FULLSCREEN);
4155 }
4156
Andrei Popescu56199cc2010-01-12 22:39:16 +00004157
4158 private void sendNetworkType(String type, String subtype) {
4159 WebView w = mTabControl.getCurrentWebView();
4160 if (w != null) {
4161 w.setNetworkType(type, subtype);
4162 }
4163 }
4164
Grace Klobaeb6eef42009-09-15 17:56:32 -07004165 final static int LOCK_ICON_UNSECURE = 0;
4166 final static int LOCK_ICON_SECURE = 1;
4167 final static int LOCK_ICON_MIXED = 2;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004168
The Android Open Source Project0c908882009-03-03 19:32:16 -08004169 private BrowserSettings mSettings;
4170 private TabControl mTabControl;
4171 private ContentResolver mResolver;
4172 private FrameLayout mContentView;
Andrei Popescuadc008d2009-06-26 14:11:30 +01004173 private View mCustomView;
4174 private FrameLayout mCustomViewContainer;
Andrei Popescuc9b55562009-07-07 10:51:15 +01004175 private WebChromeClient.CustomViewCallback mCustomViewCallback;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004176
4177 // FIXME, temp address onPrepareMenu performance problem. When we move everything out of
4178 // view, we should rewrite this.
4179 private int mCurrentMenuState = 0;
4180 private int mMenuState = R.id.MAIN_MENU;
Andrei Popescuadc008d2009-06-26 14:11:30 +01004181 private int mOldMenuState = EMPTY_MENU;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004182 private static final int EMPTY_MENU = -1;
4183 private Menu mMenu;
4184
The Android Open Source Project0c908882009-03-03 19:32:16 -08004185 // Used to prevent chording to result in firing two shortcuts immediately
4186 // one after another. Fixes bug 1211714.
4187 boolean mCanChord;
4188
4189 private boolean mInLoad;
4190 private boolean mIsNetworkUp;
Ben Murdochb7cc8b42009-09-28 10:59:09 +01004191 private boolean mDidStopLoad;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004192
Cary Clark1f10cbf2010-03-22 11:45:23 -04004193 /* package */ boolean mActivityInPause = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004194
4195 private boolean mMenuIsDown;
4196
The Android Open Source Project0c908882009-03-03 19:32:16 -08004197 private static boolean mInTrace;
4198
4199 // Performance probe
4200 private static final int[] SYSTEM_CPU_FORMAT = new int[] {
4201 Process.PROC_SPACE_TERM | Process.PROC_COMBINE,
4202 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 1: user time
4203 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 2: nice time
4204 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 3: sys time
4205 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 4: idle time
4206 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 5: iowait time
4207 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 6: irq time
4208 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG // 7: softirq time
4209 };
4210
4211 private long mStart;
4212 private long mProcessStart;
4213 private long mUserStart;
4214 private long mSystemStart;
4215 private long mIdleStart;
4216 private long mIrqStart;
4217
4218 private long mUiStart;
4219
4220 private Drawable mMixLockIcon;
4221 private Drawable mSecLockIcon;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004222
4223 /* hold a ref so we can auto-cancel if necessary */
4224 private AlertDialog mAlertDialog;
4225
The Android Open Source Project0c908882009-03-03 19:32:16 -08004226 // The up-to-date URL and title (these can be different from those stored
4227 // in WebView, since it takes some time for the information in WebView to
4228 // get updated)
4229 private String mUrl;
4230 private String mTitle;
4231
4232 // As PageInfo has different style for landscape / portrait, we have
4233 // to re-open it when configuration changed
4234 private AlertDialog mPageInfoDialog;
Grace Kloba22ac16e2009-10-07 18:00:23 -07004235 private Tab mPageInfoView;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004236 // If the Page-Info dialog is launched from the SSL-certificate-on-error
4237 // dialog, we should not just dismiss it, but should get back to the
4238 // SSL-certificate-on-error dialog. This flag is used to store this state
Leon Scrogginsc7b92f82010-01-11 18:17:31 -05004239 private boolean mPageInfoFromShowSSLCertificateOnError;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004240
4241 // as SSLCertificateOnError has different style for landscape / portrait,
4242 // we have to re-open it when configuration changed
4243 private AlertDialog mSSLCertificateOnErrorDialog;
4244 private WebView mSSLCertificateOnErrorView;
4245 private SslErrorHandler mSSLCertificateOnErrorHandler;
4246 private SslError mSSLCertificateOnErrorError;
4247
4248 // as SSLCertificate has different style for landscape / portrait, we
4249 // have to re-open it when configuration changed
4250 private AlertDialog mSSLCertificateDialog;
Grace Kloba22ac16e2009-10-07 18:00:23 -07004251 private Tab mSSLCertificateView;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004252
4253 // as HttpAuthentication has different style for landscape / portrait, we
4254 // have to re-open it when configuration changed
4255 private AlertDialog mHttpAuthenticationDialog;
4256 private HttpAuthHandler mHttpAuthHandler;
4257
4258 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_PARAMS =
4259 new FrameLayout.LayoutParams(
Romain Guy15b8ec62010-01-08 15:06:43 -08004260 ViewGroup.LayoutParams.MATCH_PARENT,
4261 ViewGroup.LayoutParams.MATCH_PARENT);
Andrei Popescuadc008d2009-06-26 14:11:30 +01004262 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_GRAVITY_CENTER =
4263 new FrameLayout.LayoutParams(
Romain Guy15b8ec62010-01-08 15:06:43 -08004264 ViewGroup.LayoutParams.MATCH_PARENT,
4265 ViewGroup.LayoutParams.MATCH_PARENT,
Andrei Popescuadc008d2009-06-26 14:11:30 +01004266 Gravity.CENTER);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07004267 // Google search
4268 final static String QuickSearch_G = "http://www.google.com/m?q=%s";
The Android Open Source Project0c908882009-03-03 19:32:16 -08004269
4270 final static String QUERY_PLACE_HOLDER = "%s";
4271
4272 // "source" parameter for Google search through search key
4273 final static String GOOGLE_SEARCH_SOURCE_SEARCHKEY = "browser-key";
4274 // "source" parameter for Google search through goto menu
4275 final static String GOOGLE_SEARCH_SOURCE_GOTO = "browser-goto";
4276 // "source" parameter for Google search through simplily type
4277 final static String GOOGLE_SEARCH_SOURCE_TYPE = "browser-type";
4278 // "source" parameter for Google search suggested by the browser
4279 final static String GOOGLE_SEARCH_SOURCE_SUGGEST = "browser-suggest";
4280 // "source" parameter for Google search from unknown source
4281 final static String GOOGLE_SEARCH_SOURCE_UNKNOWN = "unknown";
4282
4283 private final static String LOGTAG = "browser";
4284
The Android Open Source Project0c908882009-03-03 19:32:16 -08004285 private String mLastEnteredUrl;
4286
4287 private PowerManager.WakeLock mWakeLock;
4288 private final static int WAKELOCK_TIMEOUT = 5 * 60 * 1000; // 5 minutes
4289
4290 private Toast mStopToast;
4291
Leon Scroggins571b3762010-05-26 10:25:01 -04004292 private TitleBarBase mTitleBar;
Michael Kolba2b2ba82010-08-04 17:54:03 -07004293 private TabBar mTabBar;
Leon Scroggins81db3662009-06-04 17:45:11 -04004294
Ben Murdochbff2d602009-07-01 20:19:05 +01004295 private LinearLayout mErrorConsoleContainer = null;
4296 private boolean mShouldShowErrorConsole = false;
4297
The Android Open Source Project0c908882009-03-03 19:32:16 -08004298 // As the ids are dynamically created, we can't guarantee that they will
4299 // be in sequence, so this static array maps ids to a window number.
4300 final static private int[] WINDOW_SHORTCUT_ID_ARRAY =
4301 { R.id.window_one_menu_id, R.id.window_two_menu_id, R.id.window_three_menu_id,
4302 R.id.window_four_menu_id, R.id.window_five_menu_id, R.id.window_six_menu_id,
4303 R.id.window_seven_menu_id, R.id.window_eight_menu_id };
4304
4305 // monitor platform changes
4306 private IntentFilter mNetworkStateChangedFilter;
4307 private BroadcastReceiver mNetworkStateIntentReceiver;
4308
Bjorn Bringerta7611812010-03-24 11:12:02 +00004309 private SystemAllowGeolocationOrigins mSystemAllowGeolocationOrigins;
4310
The Android Open Source Project0c908882009-03-03 19:32:16 -08004311 // activity requestCode
Nicolas Roard78a98e42009-05-11 13:34:17 +01004312 final static int PREFERENCES_PAGE = 3;
Leon Scroggins8d5fa432009-10-02 15:55:59 -04004313 final static int FILE_SELECTED = 4;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004314
Andrei Popescu540035d2009-09-18 18:59:20 +01004315 // the default <video> poster
4316 private Bitmap mDefaultVideoPoster;
4317 // the video progress view
4318 private View mVideoProgressView;
4319
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004320 /**
4321 * A UrlData class to abstract how the content will be set to WebView.
4322 * This base class uses loadUrl to show the content.
4323 */
Leon Scroggins6eac63e2010-03-15 18:19:14 -04004324 /* package */ static class UrlData {
Grace Kloba068e48b2010-01-26 18:11:27 -08004325 final String mUrl;
4326 final Map<String, String> mHeaders;
Leon Scroggins58d56c62010-01-28 15:12:40 -05004327 final Intent mVoiceIntent;
Grace Kloba60e095c2009-06-16 11:50:55 -07004328
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004329 UrlData(String url) {
4330 this.mUrl = url;
Grace Kloba068e48b2010-01-26 18:11:27 -08004331 this.mHeaders = null;
Leon Scroggins58d56c62010-01-28 15:12:40 -05004332 this.mVoiceIntent = null;
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004333 }
Grace Kloba60e095c2009-06-16 11:50:55 -07004334
Leon Scroggins58d56c62010-01-28 15:12:40 -05004335 UrlData(String url, Map<String, String> headers, Intent intent) {
Grace Kloba068e48b2010-01-26 18:11:27 -08004336 this.mUrl = url;
4337 this.mHeaders = headers;
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -05004338 if (RecognizerResultsIntent.ACTION_VOICE_SEARCH_RESULTS
4339 .equals(intent.getAction())) {
Leon Scroggins58d56c62010-01-28 15:12:40 -05004340 this.mVoiceIntent = intent;
4341 } else {
4342 this.mVoiceIntent = null;
4343 }
Grace Kloba60e095c2009-06-16 11:50:55 -07004344 }
4345
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004346 boolean isEmpty() {
Leon Scroggins58d56c62010-01-28 15:12:40 -05004347 return mVoiceIntent == null && (mUrl == null || mUrl.length() == 0);
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004348 }
4349
Leon Scroggins92472e82010-02-17 16:32:28 -05004350 /**
4351 * Load this UrlData into the given Tab. Use loadUrlDataIn to update
4352 * the title bar as well.
4353 */
Leon Scroggins58d56c62010-01-28 15:12:40 -05004354 public void loadIn(Tab t) {
4355 if (mVoiceIntent != null) {
4356 t.activateVoiceSearchMode(mVoiceIntent);
4357 } else {
4358 t.getWebView().loadUrl(mUrl, mHeaders);
4359 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004360 }
4361 };
4362
Leon Scroggins1f005d32009-08-10 17:36:42 -04004363 /* package */ static final UrlData EMPTY_URL_DATA = new UrlData(null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004364}