blob: 8b737a7af94d8a62d796ca1cbfb37740f4a183f0 [file] [log] [blame]
The Android Open Source Project0c908882009-03-03 19:32:16 -08001/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.browser;
18
Michael Kolb3f65c382010-08-20 15:31:16 -070019import com.android.browser.ScrollWebView.ScrollListener;
Bjorn Bringertd69f51d2010-09-13 14:06:41 +010020import com.android.browser.search.SearchEngine;
Michael Kolb3f65c382010-08-20 15:31:16 -070021import com.android.common.Search;
22import com.android.common.speech.LoggingEvents;
23
Michael Kolbed217742010-08-10 17:52:34 -070024import android.app.ActionBar;
The Android Open Source Project0c908882009-03-03 19:32:16 -080025import android.app.Activity;
The Android Open Source Project0c908882009-03-03 19:32:16 -080026import android.app.AlertDialog;
Michael Kolbc7485ae2010-09-03 10:10:58 -070027import android.app.Dialog;
Steve Howard5a862fc2010-09-28 12:52:06 -070028import android.app.DownloadManager;
The Android Open Source Project0c908882009-03-03 19:32:16 -080029import android.app.ProgressDialog;
30import android.app.SearchManager;
31import android.content.ActivityNotFoundException;
32import android.content.BroadcastReceiver;
Dianne Hackborn80f32622010-08-05 14:17:53 -070033import android.content.ClipboardManager;
The Android Open Source Project0c908882009-03-03 19:32:16 -080034import android.content.ComponentName;
Leon Scroggins58d56c62010-01-28 15:12:40 -050035import android.content.ContentProvider;
36import android.content.ContentProviderClient;
The Android Open Source Project0c908882009-03-03 19:32:16 -080037import android.content.ContentResolver;
38import android.content.ContentValues;
39import android.content.Context;
40import android.content.DialogInterface;
41import android.content.Intent;
42import android.content.IntentFilter;
The Android Open Source Project0c908882009-03-03 19:32:16 -080043import android.content.pm.PackageManager;
44import android.content.pm.ResolveInfo;
The Android Open Source Project0c908882009-03-03 19:32:16 -080045import android.content.res.Configuration;
46import android.content.res.Resources;
47import android.database.Cursor;
The Android Open Source Project0c908882009-03-03 19:32:16 -080048import android.graphics.Bitmap;
Andrei Popescu540035d2009-09-18 18:59:20 +010049import android.graphics.BitmapFactory;
The Android Open Source Project0c908882009-03-03 19:32:16 -080050import android.graphics.Canvas;
The Android Open Source Project0c908882009-03-03 19:32:16 -080051import android.graphics.Picture;
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -040052import android.graphics.PixelFormat;
The Android Open Source Project0c908882009-03-03 19:32:16 -080053import android.graphics.drawable.Drawable;
The Android Open Source Project0c908882009-03-03 19:32:16 -080054import android.net.ConnectivityManager;
Andrei Popescu56199cc2010-01-12 22:39:16 +000055import android.net.NetworkInfo;
The Android Open Source Project0c908882009-03-03 19:32:16 -080056import android.net.Uri;
57import android.net.WebAddress;
The Android Open Source Project0c908882009-03-03 19:32:16 -080058import android.net.http.SslCertificate;
59import android.net.http.SslError;
60import android.os.AsyncTask;
61import android.os.Bundle;
62import android.os.Debug;
63import android.os.Environment;
64import android.os.Handler;
The Android Open Source Project0c908882009-03-03 19:32:16 -080065import android.os.Message;
66import android.os.PowerManager;
67import android.os.Process;
The Android Open Source Project0c908882009-03-03 19:32:16 -080068import android.os.SystemClock;
The Android Open Source Project0c908882009-03-03 19:32:16 -080069import android.provider.Browser;
Jeff Hamilton1a805652010-09-07 12:36:30 -070070import android.provider.BrowserContract.Images;
Michael Kolbe421c242010-10-04 19:29:01 -070071import android.provider.ContactsContract;
Michael Kolba2b2ba82010-08-04 17:54:03 -070072import android.provider.ContactsContract.Intents.Insert;
The Android Open Source Project0c908882009-03-03 19:32:16 -080073import android.provider.Downloads;
74import android.provider.MediaStore;
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -050075import android.speech.RecognizerResultsIntent;
The Android Open Source Project0c908882009-03-03 19:32:16 -080076import android.text.TextUtils;
77import android.text.format.DateFormat;
The Android Open Source Project0c908882009-03-03 19:32:16 -080078import android.util.Log;
Dianne Hackborn385effd2010-02-24 20:03:04 -080079import android.util.Patterns;
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -040080import android.view.ActionMode;
The Android Open Source Project0c908882009-03-03 19:32:16 -080081import android.view.ContextMenu;
Michael Kolba2b2ba82010-08-04 17:54:03 -070082import android.view.ContextMenu.ContextMenuInfo;
The Android Open Source Project0c908882009-03-03 19:32:16 -080083import android.view.Gravity;
84import android.view.KeyEvent;
85import android.view.LayoutInflater;
86import android.view.Menu;
87import android.view.MenuInflater;
88import android.view.MenuItem;
Michael Kolba2b2ba82010-08-04 17:54:03 -070089import android.view.MenuItem.OnMenuItemClickListener;
The Android Open Source Project0c908882009-03-03 19:32:16 -080090import android.view.View;
91import android.view.ViewGroup;
92import android.view.Window;
93import android.view.WindowManager;
Svetoslav Ganov2b345992010-05-06 06:13:54 -070094import android.view.accessibility.AccessibilityManager;
The Android Open Source Project0c908882009-03-03 19:32:16 -080095import android.webkit.CookieManager;
96import android.webkit.CookieSyncManager;
97import android.webkit.DownloadListener;
98import android.webkit.HttpAuthHandler;
99import android.webkit.SslErrorHandler;
100import android.webkit.URLUtil;
Leon Clarkecb6cc862009-09-29 18:35:13 +0100101import android.webkit.ValueCallback;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800102import android.webkit.WebChromeClient;
103import android.webkit.WebHistoryItem;
104import android.webkit.WebIconDatabase;
105import android.webkit.WebView;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800106import android.widget.EditText;
107import android.widget.FrameLayout;
108import android.widget.LinearLayout;
Michael Kolbc7485ae2010-09-03 10:10:58 -0700109import android.widget.PopupMenu;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800110import android.widget.TextView;
111import android.widget.Toast;
112
Leon Scrogginsb6b7f9e2009-06-18 12:05:28 -0400113import java.io.ByteArrayOutputStream;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800114import java.io.File;
Ben Murdoch4f75ba22009-10-27 11:48:28 +0000115import java.io.IOException;
116import java.io.InputStream;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800117import java.net.MalformedURLException;
Dianne Hackborn99189432009-06-17 18:06:18 -0700118import java.net.URISyntaxException;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800119import java.net.URL;
120import java.net.URLEncoder;
Elliott Slaughter3d6df162010-08-25 13:17:44 -0700121import java.util.Calendar;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800122import java.util.Date;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800123import java.util.HashMap;
Grace Kloba00f54c52010-01-27 14:53:51 -0800124import java.util.Iterator;
Grace Kloba068e48b2010-01-26 18:11:27 -0800125import java.util.Map;
Michael Kolbfe251992010-07-08 15:41:55 -0700126import java.util.Vector;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800127import java.util.regex.Matcher;
128import java.util.regex.Pattern;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800129
130public class BrowserActivity extends Activity
Michael Kolbe421c242010-10-04 19:29:01 -0700131 implements View.OnCreateContextMenuListener, DownloadListener,
132 PopupMenu.OnMenuItemClickListener, BookmarksHistoryCallbacks {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800133
Dave Bort31a6d1c2009-04-13 15:56:49 -0700134 /* Define some aliases to make these debugging flags easier to refer to.
135 * This file imports android.provider.Browser, so we can't just refer to "Browser.DEBUG".
136 */
137 private final static boolean DEBUG = com.android.browser.Browser.DEBUG;
138 private final static boolean LOGV_ENABLED = com.android.browser.Browser.LOGV_ENABLED;
139 private final static boolean LOGD_ENABLED = com.android.browser.Browser.LOGD_ENABLED;
140
Cary Clarka9771242009-08-11 16:42:26 -0400141 private static class ClearThumbnails extends AsyncTask<File, Void, Void> {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800142 @Override
143 public Void doInBackground(File... files) {
144 if (files != null) {
145 for (File f : files) {
Cary Clarkd6be1752009-08-12 12:56:42 -0400146 if (!f.delete()) {
147 Log.e(LOGTAG, f.getPath() + " was not deleted");
148 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800149 }
150 }
151 return null;
152 }
153 }
154
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400155 /**
156 * This layout holds everything you see below the status bar, including the
157 * error console, the custom view container, and the webviews.
158 */
159 private FrameLayout mBrowserFrameLayout;
Leon Scroggins81db3662009-06-04 17:45:11 -0400160
Michael Kolbe421c242010-10-04 19:29:01 -0700161 private CombinedBookmarkHistoryView mComboView;
162
Leon Scrogginsd746a942010-05-19 13:21:44 -0400163 private boolean mXLargeScreenSize;
164
Jeff Davidson43610292010-07-16 16:03:58 -0700165 private Boolean mIsProviderPresent = null;
166 private Uri mRlzUri = null;
167
Grace Kloba22ac16e2009-10-07 18:00:23 -0700168 @Override
169 public void onCreate(Bundle icicle) {
Dave Bort31a6d1c2009-04-13 15:56:49 -0700170 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800171 Log.v(LOGTAG, this + " onStart");
172 }
173 super.onCreate(icicle);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800174 // test the browser in OpenGL
175 // requestWindowFeature(Window.FEATURE_OPENGL);
176
Mike Reedd334bf52010-01-26 15:21:44 -0500177 // enable this to test the browser in 32bit
178 if (false) {
179 getWindow().setFormat(PixelFormat.RGBX_8888);
180 BitmapFactory.setDefaultConfig(Bitmap.Config.ARGB_8888);
181 }
182
Svetoslav Ganov2b345992010-05-06 06:13:54 -0700183 if (AccessibilityManager.getInstance(this).isEnabled()) {
184 setDefaultKeyMode(DEFAULT_KEYS_DISABLE);
185 } else {
186 setDefaultKeyMode(DEFAULT_KEYS_SEARCH_LOCAL);
187 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800188
189 mResolver = getContentResolver();
190
Leon Scroggins IIIcc14c8c2010-09-27 12:45:34 -0400191 // Keep a settings instance handy.
192 mSettings = BrowserSettings.getInstance();
193
Grace Kloba0923d692009-09-23 21:37:25 -0700194 // If this was a web search request, pass it on to the default web
195 // search provider and finish this activity.
196 if (handleWebSearchIntent(getIntent())) {
197 finish();
198 return;
199 }
200
The Android Open Source Project0c908882009-03-03 19:32:16 -0800201 mSecLockIcon = Resources.getSystem().getDrawable(
202 android.R.drawable.ic_secure);
203 mMixLockIcon = Resources.getSystem().getDrawable(
204 android.R.drawable.ic_partial_secure);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800205
Michael Kolbed217742010-08-10 17:52:34 -0700206 // Create the tab control and our initial tab
207 mTabControl = new TabControl(this);
208
209 mXLargeScreenSize = (getResources().getConfiguration().screenLayout
210 & Configuration.SCREENLAYOUT_SIZE_MASK)
211 == Configuration.SCREENLAYOUT_SIZE_XLARGE;
212
Leon Scroggins81db3662009-06-04 17:45:11 -0400213 FrameLayout frameLayout = (FrameLayout) getWindow().getDecorView()
214 .findViewById(com.android.internal.R.id.content);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400215 mBrowserFrameLayout = (FrameLayout) LayoutInflater.from(this)
216 .inflate(R.layout.custom_screen, null);
217 mContentView = (FrameLayout) mBrowserFrameLayout.findViewById(
218 R.id.main_content);
219 mErrorConsoleContainer = (LinearLayout) mBrowserFrameLayout
220 .findViewById(R.id.error_console);
221 mCustomViewContainer = (FrameLayout) mBrowserFrameLayout
222 .findViewById(R.id.fullscreen_custom_content);
223 frameLayout.addView(mBrowserFrameLayout, COVER_SCREEN_PARAMS);
Michael Kolbe0a36662010-06-29 10:37:12 -0700224
Leon Scrogginsd746a942010-05-19 13:21:44 -0400225 if (mXLargeScreenSize) {
Michael Kolba2b2ba82010-08-04 17:54:03 -0700226 mTitleBar = new TitleBarXLarge(this);
227 mTitleBar.setProgress(100);
228 mFakeTitleBar = new TitleBarXLarge(this);
Michael Kolbed217742010-08-10 17:52:34 -0700229 ActionBar actionBar = getActionBar();
Michael Kolba2b2ba82010-08-04 17:54:03 -0700230 mTabBar = new TabBar(this, mTabControl, (TitleBarXLarge) mFakeTitleBar);
Michael Kolbed217742010-08-10 17:52:34 -0700231 actionBar.setCustomNavigationMode(mTabBar);
Michael Kolb68775752010-08-19 12:42:01 -0700232 // disable built in zoom controls
233 mTabControl.setDisplayZoomControls(false);
Leon Scrogginsd746a942010-05-19 13:21:44 -0400234 } else {
Leon Scroggins571b3762010-05-26 10:25:01 -0400235 mTitleBar = new TitleBar(this);
Leon Scrogginsd746a942010-05-19 13:21:44 -0400236 // mTitleBar will be always be shown in the fully loaded mode on
237 // phone
238 mTitleBar.setProgress(100);
Leon Scrogginsd746a942010-05-19 13:21:44 -0400239 mFakeTitleBar = new TitleBar(this);
240 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800241
The Android Open Source Project0c908882009-03-03 19:32:16 -0800242 // Open the icon database and retain all the bookmark urls for favicons
243 retainIconsOnStartup();
244
The Android Open Source Project0c908882009-03-03 19:32:16 -0800245 mSettings.setTabControl(mTabControl);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800246
247 PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
248 mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Browser");
249
Patrick Scott6adacc92010-03-05 08:24:51 -0500250 // Find out if the network is currently up.
251 ConnectivityManager cm = (ConnectivityManager) getSystemService(
252 Context.CONNECTIVITY_SERVICE);
253 NetworkInfo info = cm.getActiveNetworkInfo();
254 if (info != null) {
255 mIsNetworkUp = info.isAvailable();
256 }
257
Grace Klobaa34f6862009-07-31 16:28:17 -0700258 /* enables registration for changes in network status from
259 http stack */
260 mNetworkStateChangedFilter = new IntentFilter();
261 mNetworkStateChangedFilter.addAction(
262 ConnectivityManager.CONNECTIVITY_ACTION);
263 mNetworkStateIntentReceiver = new BroadcastReceiver() {
264 @Override
265 public void onReceive(Context context, Intent intent) {
266 if (intent.getAction().equals(
267 ConnectivityManager.CONNECTIVITY_ACTION)) {
Andrei Popescue4c98462010-02-19 15:44:13 +0000268
269 NetworkInfo info = intent.getParcelableExtra(
270 ConnectivityManager.EXTRA_NETWORK_INFO);
271 String typeName = info.getTypeName();
272 String subtypeName = info.getSubtypeName();
273 sendNetworkType(typeName.toLowerCase(),
274 (subtypeName != null ? subtypeName.toLowerCase() : ""));
275
276 onNetworkToggle(info.isAvailable());
Grace Klobaa34f6862009-07-31 16:28:17 -0700277 }
278 }
279 };
280
Elliott Slaughter3d6df162010-08-25 13:17:44 -0700281 // Unless the last browser usage was within 24 hours, destroy any
282 // remaining incognito tabs.
283
284 Calendar lastActiveDate = icicle != null ? (Calendar) icicle.getSerializable("lastActiveDate") : null;
285 Calendar today = Calendar.getInstance();
286 Calendar yesterday = Calendar.getInstance();
287 yesterday.add(Calendar.DATE, -1);
288
289 boolean dontRestoreIncognitoTabs = lastActiveDate == null
290 || lastActiveDate.before(yesterday)
291 || lastActiveDate.after(today);
292
293 if (!mTabControl.restoreState(icicle, dontRestoreIncognitoTabs)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800294 // clear up the thumbnail directory if we can't restore the state as
295 // none of the files in the directory are referenced any more.
296 new ClearThumbnails().execute(
297 mTabControl.getThumbnailDir().listFiles());
Grace Klobaaab3f092009-07-30 12:29:51 -0700298 // there is no quit on Android. But if we can't restore the state,
299 // we can treat it as a new Browser, remove the old session cookies.
300 CookieManager.getInstance().removeSessionCookie();
Elliott Slaughter3d6df162010-08-25 13:17:44 -0700301 // remove any incognito files
302 WebView.cleanupPrivateBrowsingFiles(this);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800303 final Intent intent = getIntent();
304 final Bundle extra = intent.getExtras();
305 // Create an initial tab.
306 // If the intent is ACTION_VIEW and data is not null, the Browser is
307 // invoked to view the content by another application. In this case,
308 // the tab will be close when exit.
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700309 UrlData urlData = getUrlDataFromIntent(intent);
310
Leon Scroggins58d56c62010-01-28 15:12:40 -0500311 String action = intent.getAction();
Grace Kloba22ac16e2009-10-07 18:00:23 -0700312 final Tab t = mTabControl.createNewTab(
Leon Scroggins58d56c62010-01-28 15:12:40 -0500313 (Intent.ACTION_VIEW.equals(action) &&
314 intent.getData() != null)
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -0500315 || RecognizerResultsIntent.ACTION_VOICE_SEARCH_RESULTS
316 .equals(action),
Elliott Slaughterf0f03952010-07-14 18:10:36 -0700317 intent.getStringExtra(Browser.EXTRA_APPLICATION_ID),
318 urlData.mUrl, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800319 mTabControl.setCurrentTab(t);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800320 attachTabToContentView(t);
321 WebView webView = t.getWebView();
322 if (extra != null) {
323 int scale = extra.getInt(Browser.INITIAL_ZOOM_LEVEL, 0);
324 if (scale > 0 && scale <= 1000) {
325 webView.setInitialScale(scale);
326 }
327 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800328
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700329 if (urlData.isEmpty()) {
Shimeng (Simon) Wang98d5fce2010-03-16 13:23:39 -0700330 loadUrl(webView, mSettings.getHomePage());
The Android Open Source Project0c908882009-03-03 19:32:16 -0800331 } else {
Patrick Scott9d53da02010-02-19 10:19:01 -0500332 loadUrlDataIn(t, urlData);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800333 }
334 } else {
Elliott Slaughter3d6df162010-08-25 13:17:44 -0700335 if (dontRestoreIncognitoTabs) {
336 WebView.cleanupPrivateBrowsingFiles(this);
337 }
338
The Android Open Source Project0c908882009-03-03 19:32:16 -0800339 // TabControl.restoreState() will create a new tab even if
Leon Scroggins1f005d32009-08-10 17:36:42 -0400340 // restoring the state fails.
The Android Open Source Project0c908882009-03-03 19:32:16 -0800341 attachTabToContentView(mTabControl.getCurrentTab());
342 }
Grace Kloba615c6c92009-08-03 10:22:44 -0700343
Cary Clarkb4b83182010-07-01 12:36:56 -0400344 // Delete old thumbnails to save space
345 File dir = mTabControl.getThumbnailDir();
346 if (dir.exists()) {
347 for (String child : dir.list()) {
348 File f = new File(dir, child);
349 f.delete();
350 }
351 }
352
Feng Qianb3c02da2009-06-29 15:58:08 -0700353 // Read JavaScript flags if it exists.
354 String jsFlags = mSettings.getJsFlags();
355 if (jsFlags.trim().length() != 0) {
356 mTabControl.getCurrentWebView().setJsFlags(jsFlags);
357 }
Bjorn Bringerta7611812010-03-24 11:12:02 +0000358
359 // Start watching the default geolocation permissions
360 mSystemAllowGeolocationOrigins
361 = new SystemAllowGeolocationOrigins(getApplicationContext());
362 mSystemAllowGeolocationOrigins.start();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800363 }
364
Michael Kolba2b2ba82010-08-04 17:54:03 -0700365 ScrollListener getScrollListener() {
366 return mTabBar;
367 }
368
Leon Scroggins58d56c62010-01-28 15:12:40 -0500369 /**
370 * Feed the previously stored results strings to the BrowserProvider so that
371 * the SearchDialog will show them instead of the standard searches.
372 * @param result String to show on the editable line of the SearchDialog.
373 */
374 /* package */ void showVoiceSearchResults(String result) {
375 ContentProviderClient client = mResolver.acquireContentProviderClient(
376 Browser.BOOKMARKS_URI);
377 ContentProvider prov = client.getLocalContentProvider();
378 BrowserProvider bp = (BrowserProvider) prov;
379 bp.setQueryResults(mTabControl.getCurrentTab().getVoiceSearchResults());
380 client.release();
381
Leon Scrogginsfbb3f152010-03-09 17:26:56 -0500382 Bundle bundle = createGoogleSearchSourceBundle(
383 GOOGLE_SEARCH_SOURCE_SEARCHKEY);
384 bundle.putBoolean(SearchManager.CONTEXT_IS_VOICE, true);
385 startSearch(result, false, bundle, false);
Leon Scroggins58d56c62010-01-28 15:12:40 -0500386 }
387
The Android Open Source Project0c908882009-03-03 19:32:16 -0800388 @Override
389 protected void onNewIntent(Intent intent) {
Grace Kloba22ac16e2009-10-07 18:00:23 -0700390 Tab current = mTabControl.getCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800391 // When a tab is closed on exit, the current tab index is set to -1.
392 // Reset before proceed as Browser requires the current tab to be set.
393 if (current == null) {
394 // Try to reset the tab in case the index was incorrect.
395 current = mTabControl.getTab(0);
396 if (current == null) {
397 // No tabs at all so just ignore this intent.
398 return;
399 }
400 mTabControl.setCurrentTab(current);
401 attachTabToContentView(current);
402 resetTitleAndIcon(current.getWebView());
403 }
404 final String action = intent.getAction();
405 final int flags = intent.getFlags();
406 if (Intent.ACTION_MAIN.equals(action) ||
407 (flags & Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY) != 0) {
408 // just resume the browser
409 return;
410 }
Leon Scrogginsb8a844d2010-03-18 15:06:15 -0400411 // In case the SearchDialog is open.
412 ((SearchManager) getSystemService(Context.SEARCH_SERVICE))
413 .stopSearch();
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -0500414 boolean activateVoiceSearch = RecognizerResultsIntent
415 .ACTION_VOICE_SEARCH_RESULTS.equals(action);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800416 if (Intent.ACTION_VIEW.equals(action)
417 || Intent.ACTION_SEARCH.equals(action)
418 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
Leon Scroggins58d56c62010-01-28 15:12:40 -0500419 || Intent.ACTION_WEB_SEARCH.equals(action)
420 || activateVoiceSearch) {
Leon Scroggins3b18ce32010-02-08 17:35:59 -0500421 if (current.isInVoiceSearchMode()) {
422 String title = current.getVoiceDisplayTitle();
423 if (title != null && title.equals(intent.getStringExtra(
424 SearchManager.QUERY))) {
425 // The user submitted the same search as the last voice
426 // search, so do nothing.
427 return;
428 }
Leon Scroggins1fe13a52010-02-09 15:31:26 -0500429 if (Intent.ACTION_SEARCH.equals(action)
430 && current.voiceSearchSourceIsGoogle()) {
431 Intent logIntent = new Intent(
432 LoggingEvents.ACTION_LOG_EVENT);
433 logIntent.putExtra(LoggingEvents.EXTRA_EVENT,
434 LoggingEvents.VoiceSearch.QUERY_UPDATED);
435 logIntent.putExtra(
436 LoggingEvents.VoiceSearch.EXTRA_QUERY_UPDATED_VALUE,
437 intent.getDataString());
438 sendBroadcast(logIntent);
439 // Note, onPageStarted will revert the voice title bar
440 // When http://b/issue?id=2379215 is fixed, we should update
441 // the title bar here.
442 }
Leon Scroggins3b18ce32010-02-08 17:35:59 -0500443 }
Satish Sampath565505b2009-05-29 15:37:27 +0100444 // If this was a search request (e.g. search query directly typed into the address bar),
445 // pass it on to the default web search provider.
446 if (handleWebSearchIntent(intent)) {
447 return;
448 }
449
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700450 UrlData urlData = getUrlDataFromIntent(intent);
451 if (urlData.isEmpty()) {
452 urlData = new UrlData(mSettings.getHomePage());
The Android Open Source Project0c908882009-03-03 19:32:16 -0800453 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700454
Grace Klobacc634032009-07-28 15:58:19 -0700455 final String appId = intent
456 .getStringExtra(Browser.EXTRA_APPLICATION_ID);
Leon Scroggins47208682010-04-07 17:59:48 -0400457 if ((Intent.ACTION_VIEW.equals(action)
458 // If a voice search has no appId, it means that it came
459 // from the browser. In that case, reuse the current tab.
460 || (activateVoiceSearch && appId != null))
Grace Klobacc634032009-07-28 15:58:19 -0700461 && !getPackageName().equals(appId)
462 && (flags & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0) {
Grace Kloba22ac16e2009-10-07 18:00:23 -0700463 Tab appTab = mTabControl.getTabFromId(appId);
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700464 if (appTab != null) {
465 Log.i(LOGTAG, "Reusing tab for " + appId);
466 // Dismiss the subwindow if applicable.
467 dismissSubWindow(appTab);
468 // Since we might kill the WebView, remove it from the
469 // content view first.
470 removeTabFromContentView(appTab);
471 // Recreate the main WebView after destroying the old one.
472 // If the WebView has the same original url and is on that
473 // page, it can be reused.
474 boolean needsLoad =
Leon Scroggins6eac63e2010-03-15 18:19:14 -0400475 mTabControl.recreateWebView(appTab, urlData);
Ben Murdochbff2d602009-07-01 20:19:05 +0100476
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700477 if (current != appTab) {
Leon Scroggins1f005d32009-08-10 17:36:42 -0400478 switchToTab(mTabControl.getTabIndex(appTab));
479 if (needsLoad) {
Patrick Scott9d53da02010-02-19 10:19:01 -0500480 loadUrlDataIn(appTab, urlData);
Leon Scroggins1f005d32009-08-10 17:36:42 -0400481 }
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700482 } else {
Leon Scroggins1f005d32009-08-10 17:36:42 -0400483 // If the tab was the current tab, we have to attach
484 // it to the view system again.
485 attachTabToContentView(appTab);
486 if (needsLoad) {
Patrick Scott9d53da02010-02-19 10:19:01 -0500487 loadUrlDataIn(appTab, urlData);
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700488 }
489 }
490 return;
Patrick Scottcd115892009-07-16 09:42:58 -0400491 } else {
492 // No matching application tab, try to find a regular tab
493 // with a matching url.
494 appTab = mTabControl.findUnusedTabWithUrl(urlData.mUrl);
Leon Scroggins25515f82009-08-19 15:31:58 -0400495 if (appTab != null) {
496 if (current != appTab) {
497 switchToTab(mTabControl.getTabIndex(appTab));
498 }
499 // Otherwise, we are already viewing the correct tab.
Patrick Scottcd115892009-07-16 09:42:58 -0400500 } else {
501 // if FLAG_ACTIVITY_BROUGHT_TO_FRONT flag is on, the url
502 // will be opened in a new tab unless we have reached
503 // MAX_TABS. Then the url will be opened in the current
504 // tab. If a new tab is created, it will have "true" for
505 // exit on close.
Leon Scroggins1f005d32009-08-10 17:36:42 -0400506 openTabAndShow(urlData, true, appId);
Patrick Scottcd115892009-07-16 09:42:58 -0400507 }
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700508 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800509 } else {
Grace Kloba638d3f42009-11-23 10:35:04 -0800510 if (!urlData.isEmpty()
511 && urlData.mUrl.startsWith("about:debug")) {
512 if ("about:debug.dom".equals(urlData.mUrl)) {
513 current.getWebView().dumpDomTree(false);
514 } else if ("about:debug.dom.file".equals(urlData.mUrl)) {
515 current.getWebView().dumpDomTree(true);
516 } else if ("about:debug.render".equals(urlData.mUrl)) {
517 current.getWebView().dumpRenderTree(false);
518 } else if ("about:debug.render.file".equals(urlData.mUrl)) {
519 current.getWebView().dumpRenderTree(true);
520 } else if ("about:debug.display".equals(urlData.mUrl)) {
521 current.getWebView().dumpDisplayTree();
Mike Reed9b78e1d2010-01-13 14:40:52 -0800522 } else if (urlData.mUrl.startsWith("about:debug.drag")) {
523 int index = urlData.mUrl.codePointAt(16) - '0';
524 if (index <= 0 || index > 9) {
525 current.getWebView().setDragTracker(null);
526 } else {
527 current.getWebView().setDragTracker(new MeshTracker(index));
528 }
Grace Kloba638d3f42009-11-23 10:35:04 -0800529 } else {
530 mSettings.toggleDebugSettings();
531 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800532 return;
533 }
Leon Scroggins1f005d32009-08-10 17:36:42 -0400534 // Get rid of the subwindow if it exists
535 dismissSubWindow(current);
Leon Scroggins8588d152010-04-15 11:01:53 -0400536 // If the current Tab is being used as an application tab,
537 // remove the association, since the new Intent means that it is
538 // no longer associated with that application.
539 current.setAppId(null);
Patrick Scott9d53da02010-02-19 10:19:01 -0500540 loadUrlDataIn(current, urlData);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800541 }
542 }
543 }
544
Satish Sampath565505b2009-05-29 15:37:27 +0100545 /**
546 * Launches the default web search activity with the query parameters if the given intent's data
547 * are identified as plain search terms and not URLs/shortcuts.
548 * @return true if the intent was handled and web search activity was launched, false if not.
549 */
550 private boolean handleWebSearchIntent(Intent intent) {
551 if (intent == null) return false;
552
553 String url = null;
554 final String action = intent.getAction();
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -0500555 if (RecognizerResultsIntent.ACTION_VOICE_SEARCH_RESULTS.equals(
556 action)) {
Leon Scroggins58d56c62010-01-28 15:12:40 -0500557 return false;
558 }
Satish Sampath565505b2009-05-29 15:37:27 +0100559 if (Intent.ACTION_VIEW.equals(action)) {
Grace Kloba1e705052009-09-29 13:13:36 -0700560 Uri data = intent.getData();
561 if (data != null) url = data.toString();
Satish Sampath565505b2009-05-29 15:37:27 +0100562 } else if (Intent.ACTION_SEARCH.equals(action)
563 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
564 || Intent.ACTION_WEB_SEARCH.equals(action)) {
565 url = intent.getStringExtra(SearchManager.QUERY);
566 }
Bjorn Bringert04851702009-09-22 10:36:01 +0100567 return handleWebSearchRequest(url, intent.getBundleExtra(SearchManager.APP_DATA),
568 intent.getStringExtra(SearchManager.EXTRA_DATA_KEY));
Satish Sampath565505b2009-05-29 15:37:27 +0100569 }
570
571 /**
572 * Launches the default web search activity with the query parameters if the given url string
573 * was identified as plain search terms and not URL/shortcut.
574 * @return true if the request was handled and web search activity was launched, false if not.
575 */
Bjorn Bringert04851702009-09-22 10:36:01 +0100576 private boolean handleWebSearchRequest(String inUrl, Bundle appData, String extraData) {
Satish Sampath565505b2009-05-29 15:37:27 +0100577 if (inUrl == null) return false;
578
579 // In general, we shouldn't modify URL from Intent.
580 // But currently, we get the user-typed URL from search box as well.
581 String url = fixUrl(inUrl).trim();
582
Leon Scroggins956cf012010-10-07 13:51:57 -0400583 // URLs are handled by the regular flow of control, so
Satish Sampath565505b2009-05-29 15:37:27 +0100584 // return early.
Dan Egnor5ee906c2009-11-18 12:11:49 -0800585 if (Patterns.WEB_URL.matcher(url).matches()
Leon Scroggins956cf012010-10-07 13:51:57 -0400586 || ACCEPTED_URI_SCHEMA.matcher(url).matches()) {
Satish Sampath565505b2009-05-29 15:37:27 +0100587 return false;
588 }
589
Leon Scroggins8d06e362010-03-24 14:45:57 -0400590 final ContentResolver cr = mResolver;
591 final String newUrl = url;
Elliott Slaughter627d96f2010-08-18 16:35:30 -0700592 if (mTabControl == null || !mTabControl.getCurrentWebView().isPrivateBrowsingEnabled()) {
Elliott Slaughterf0f03952010-07-14 18:10:36 -0700593 new AsyncTask<Void, Void, Void>() {
594 @Override
595 protected Void doInBackground(Void... unused) {
596 Browser.updateVisitedHistory(cr, newUrl, false);
597 Browser.addSearchUrl(cr, newUrl);
598 return null;
599 }
600 }.execute();
601 }
Satish Sampath565505b2009-05-29 15:37:27 +0100602
Bjorn Bringertd69f51d2010-09-13 14:06:41 +0100603 SearchEngine searchEngine = mSettings.getSearchEngine();
604 if (searchEngine == null) return false;
605 searchEngine.startSearch(this, url, appData, extraData);
Satish Sampath565505b2009-05-29 15:37:27 +0100606
607 return true;
608 }
609
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700610 private UrlData getUrlDataFromIntent(Intent intent) {
Leon Scroggins58d56c62010-01-28 15:12:40 -0500611 String url = "";
Grace Kloba068e48b2010-01-26 18:11:27 -0800612 Map<String, String> headers = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800613 if (intent != null) {
614 final String action = intent.getAction();
615 if (Intent.ACTION_VIEW.equals(action)) {
616 url = smartUrlFilter(intent.getData());
617 if (url != null && url.startsWith("content:")) {
618 /* Append mimetype so webview knows how to display */
619 String mimeType = intent.resolveType(getContentResolver());
620 if (mimeType != null) {
621 url += "?" + mimeType;
622 }
623 }
Grace Kloba068e48b2010-01-26 18:11:27 -0800624 if (url != null && url.startsWith("http")) {
Grace Kloba00f54c52010-01-27 14:53:51 -0800625 final Bundle pairs = intent
626 .getBundleExtra(Browser.EXTRA_HEADERS);
Grace Kloba2d508ed2010-01-28 11:39:15 -0800627 if (pairs != null && !pairs.isEmpty()) {
Grace Kloba00f54c52010-01-27 14:53:51 -0800628 Iterator<String> iter = pairs.keySet().iterator();
Grace Kloba068e48b2010-01-26 18:11:27 -0800629 headers = new HashMap<String, String>();
Grace Kloba00f54c52010-01-27 14:53:51 -0800630 while (iter.hasNext()) {
631 String key = iter.next();
632 headers.put(key, pairs.getString(key));
Grace Kloba068e48b2010-01-26 18:11:27 -0800633 }
634 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700635 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800636 } else if (Intent.ACTION_SEARCH.equals(action)
637 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
638 || Intent.ACTION_WEB_SEARCH.equals(action)) {
639 url = intent.getStringExtra(SearchManager.QUERY);
640 if (url != null) {
641 mLastEnteredUrl = url;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800642 // In general, we shouldn't modify URL from Intent.
643 // But currently, we get the user-typed URL from search box as well.
644 url = fixUrl(url);
645 url = smartUrlFilter(url);
Leon Scroggins8d06e362010-03-24 14:45:57 -0400646 final ContentResolver cr = mResolver;
647 final String newUrl = url;
Elliott Slaughter8389e992010-08-20 15:44:08 -0700648 if (mTabControl == null
649 || mTabControl.getCurrentWebView() == null
650 || !mTabControl.getCurrentWebView().isPrivateBrowsingEnabled()) {
651 new AsyncTask<Void, Void, Void>() {
652 @Override
653 protected Void doInBackground(Void... unused) {
654 Browser.updateVisitedHistory(cr, newUrl, false);
655 return null;
656 }
657 }.execute();
658 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800659 String searchSource = "&source=android-" + GOOGLE_SEARCH_SOURCE_SUGGEST + "&";
660 if (url.contains(searchSource)) {
661 String source = null;
662 final Bundle appData = intent.getBundleExtra(SearchManager.APP_DATA);
663 if (appData != null) {
Bjorn Bringert10d1cca2010-02-10 14:22:12 +0000664 source = appData.getString(Search.SOURCE);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800665 }
666 if (TextUtils.isEmpty(source)) {
667 source = GOOGLE_SEARCH_SOURCE_UNKNOWN;
668 }
669 url = url.replace(searchSource, "&source=android-"+source+"&");
670 }
671 }
672 }
673 }
Leon Scroggins58d56c62010-01-28 15:12:40 -0500674 return new UrlData(url, headers, intent);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800675 }
Leon Scroggins58d56c62010-01-28 15:12:40 -0500676 /* package */ void showVoiceTitleBar(String title) {
677 mTitleBar.setInVoiceMode(true);
Leon Scroggins58d56c62010-01-28 15:12:40 -0500678 mTitleBar.setDisplayTitle(title);
Michael Kolba2b2ba82010-08-04 17:54:03 -0700679 mFakeTitleBar.setInVoiceMode(true);
680 mFakeTitleBar.setDisplayTitle(title);
Leon Scroggins58d56c62010-01-28 15:12:40 -0500681 }
682 /* package */ void revertVoiceTitleBar() {
683 mTitleBar.setInVoiceMode(false);
Leon Scroggins003a5dd2010-03-10 12:13:14 -0500684 mTitleBar.setDisplayTitle(mUrl);
Michael Kolba2b2ba82010-08-04 17:54:03 -0700685 mFakeTitleBar.setInVoiceMode(false);
686 mFakeTitleBar.setDisplayTitle(mUrl);
Leon Scroggins58d56c62010-01-28 15:12:40 -0500687 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800688 /* package */ static String fixUrl(String inUrl) {
Cary Clark652ff872009-09-10 13:34:44 -0400689 // FIXME: Converting the url to lower case
690 // duplicates functionality in smartUrlFilter().
691 // However, changing all current callers of fixUrl to
692 // call smartUrlFilter in addition may have unwanted
693 // consequences, and is deferred for now.
694 int colon = inUrl.indexOf(':');
695 boolean allLower = true;
696 for (int index = 0; index < colon; index++) {
697 char ch = inUrl.charAt(index);
698 if (!Character.isLetter(ch)) {
699 break;
700 }
701 allLower &= Character.isLowerCase(ch);
702 if (index == colon - 1 && !allLower) {
703 inUrl = inUrl.substring(0, colon).toLowerCase()
704 + inUrl.substring(colon);
705 }
706 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800707 if (inUrl.startsWith("http://") || inUrl.startsWith("https://"))
708 return inUrl;
709 if (inUrl.startsWith("http:") ||
710 inUrl.startsWith("https:")) {
711 if (inUrl.startsWith("http:/") || inUrl.startsWith("https:/")) {
712 inUrl = inUrl.replaceFirst("/", "//");
713 } else inUrl = inUrl.replaceFirst(":", "://");
714 }
715 return inUrl;
716 }
717
Grace Kloba22ac16e2009-10-07 18:00:23 -0700718 @Override
719 protected void onResume() {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800720 super.onResume();
Dave Bort31a6d1c2009-04-13 15:56:49 -0700721 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800722 Log.v(LOGTAG, "BrowserActivity.onResume: this=" + this);
723 }
724
725 if (!mActivityInPause) {
726 Log.e(LOGTAG, "BrowserActivity is already resumed.");
727 return;
728 }
729
Mike Reed7bfa63b2009-05-28 11:08:32 -0400730 mTabControl.resumeCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800731 mActivityInPause = false;
Mike Reed7bfa63b2009-05-28 11:08:32 -0400732 resumeWebViewTimers();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800733
734 if (mWakeLock.isHeld()) {
735 mHandler.removeMessages(RELEASE_WAKELOCK);
736 mWakeLock.release();
737 }
738
The Android Open Source Project0c908882009-03-03 19:32:16 -0800739 registerReceiver(mNetworkStateIntentReceiver,
740 mNetworkStateChangedFilter);
741 WebView.enablePlatformNotifications();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800742 }
743
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400744 /**
745 * Since the actual title bar is embedded in the WebView, and removing it
Leon Scrogginsfe87bd32009-10-06 10:10:00 -0400746 * would change its appearance, use a different TitleBar to show overlayed
747 * at the top of the screen, when the menu is open or the page is loading.
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400748 */
Michael Kolba2b2ba82010-08-04 17:54:03 -0700749 private TitleBarBase mFakeTitleBar;
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400750
751 /**
752 * Keeps track of whether the options menu is open. This is important in
753 * determining whether to show or hide the title bar overlay.
754 */
755 private boolean mOptionsMenuOpen;
756
757 /**
758 * Only meaningful when mOptionsMenuOpen is true. This variable keeps track
759 * of whether the configuration has changed. The first onMenuOpened call
760 * after a configuration change is simply a reopening of the same menu
761 * (i.e. mIconView did not change).
762 */
763 private boolean mConfigChanged;
764
765 /**
766 * Whether or not the options menu is in its smaller, icon menu form. When
767 * true, we want the title bar overlay to be up. When false, we do not.
768 * Only meaningful if mOptionsMenuOpen is true.
769 */
770 private boolean mIconView;
771
Leon Scrogginsa81a7642009-08-31 17:05:41 -0400772 @Override
773 public boolean onMenuOpened(int featureId, Menu menu) {
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400774 if (Window.FEATURE_OPTIONS_PANEL == featureId) {
775 if (mOptionsMenuOpen) {
776 if (mConfigChanged) {
777 // We do not need to make any changes to the state of the
778 // title bar, since the only thing that happened was a
779 // change in orientation
780 mConfigChanged = false;
781 } else {
782 if (mIconView) {
783 // Switching the menu to expanded view, so hide the
784 // title bar.
785 hideFakeTitleBar();
786 mIconView = false;
787 } else {
788 // Switching the menu back to icon view, so show the
789 // title bar once again.
790 showFakeTitleBar();
791 mIconView = true;
792 }
793 }
794 } else {
795 // The options menu is closed, so open it, and show the title
796 showFakeTitleBar();
797 mOptionsMenuOpen = true;
798 mConfigChanged = false;
799 mIconView = true;
800 }
801 }
Leon Scrogginsa81a7642009-08-31 17:05:41 -0400802 return true;
803 }
804
Michael Kolba2b2ba82010-08-04 17:54:03 -0700805 void showFakeTitleBar() {
806 if (!isFakeTitleBarShowing() && mActiveTabsPage == null && !mActivityInPause) {
Grace Kloba847c25b2010-03-30 16:00:26 -0700807 WebView mainView = mTabControl.getCurrentWebView();
808 // if there is no current WebView, don't show the faked title bar;
Grace Kloba65190702010-04-02 23:37:26 -0700809 if (mainView == null) {
Cary Clarka0464552009-09-29 13:00:45 -0400810 return;
811 }
Leon Scroggins79e36d92010-04-29 16:01:46 +0100812 // Do not need to check for null, since the current tab will have
813 // at least a main WebView, or we would have returned above.
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -0400814 if (isInCustomActionMode()) {
815 // Do not show the fake title bar, while a custom ActionMode
816 // (i.e. find or select) is showing.
Leon Scroggins79e36d92010-04-29 16:01:46 +0100817 return;
818 }
Michael Kolba2b2ba82010-08-04 17:54:03 -0700819 if (mXLargeScreenSize) {
820 mContentView.addView(mFakeTitleBar);
821 mTabBar.onShowTitleBar();
822 } else {
823 WindowManager manager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400824
Michael Kolba2b2ba82010-08-04 17:54:03 -0700825 // Add the title bar to the window manager so it can receive
826 // touches
827 // while the menu is up
828 WindowManager.LayoutParams params =
829 new WindowManager.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
830 ViewGroup.LayoutParams.WRAP_CONTENT,
831 WindowManager.LayoutParams.TYPE_APPLICATION,
832 WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
833 PixelFormat.TRANSLUCENT);
834 params.gravity = Gravity.TOP;
835 boolean atTop = mainView.getScrollY() == 0;
836 params.windowAnimations = atTop ? 0 : R.style.TitleBar;
837 manager.addView(mFakeTitleBar, params);
838 }
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400839 }
840 }
841
842 @Override
843 public void onOptionsMenuClosed(Menu menu) {
844 mOptionsMenuOpen = false;
Leon Scrogginsa27ff192009-09-14 12:58:04 -0400845 if (!mInLoad) {
846 hideFakeTitleBar();
847 } else if (!mIconView) {
848 // The page is currently loading, and we are in expanded mode, so
849 // we were not showing the menu. Show it once again. It will be
850 // removed when the page finishes.
851 showFakeTitleBar();
852 }
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400853 }
Grace Kloba22ac16e2009-10-07 18:00:23 -0700854
Michael Kolba2b2ba82010-08-04 17:54:03 -0700855 void stopScrolling() {
856 ((ScrollWebView) mTabControl.getCurrentWebView()).stopScroll();
857 }
858
859 void hideFakeTitleBar() {
860 if (!isFakeTitleBarShowing()) return;
861 if (mXLargeScreenSize) {
862 mContentView.removeView(mFakeTitleBar);
863 mTabBar.onHideTitleBar();
864 } else {
865 WindowManager.LayoutParams params =
866 (WindowManager.LayoutParams) mFakeTitleBar.getLayoutParams();
867 WebView mainView = mTabControl.getCurrentWebView();
868 // Although we decided whether or not to animate based on the
869 // current
870 // scroll position, the scroll position may have changed since the
871 // fake title bar was displayed. Make sure it has the appropriate
872 // animation/lack thereof before removing.
873 params.windowAnimations =
874 mainView != null && mainView.getScrollY() == 0 ? 0 : R.style.TitleBar;
875 WindowManager manager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
876 manager.updateViewLayout(mFakeTitleBar, params);
877 manager.removeView(mFakeTitleBar);
878 }
879 }
880
881 boolean isFakeTitleBarShowing() {
882 return (mFakeTitleBar.getParent() != null);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400883 }
884
The Android Open Source Project0c908882009-03-03 19:32:16 -0800885 /**
Leon Scrogginsc6fa1102009-09-21 10:40:01 -0400886 * Special method for the fake title bar to call when displaying its context
887 * menu, since it is in its own Window, and its parent does not show a
888 * context menu.
889 */
890 /* package */ void showTitleBarContextMenu() {
Cary Clark65f4a3c2009-09-28 17:05:06 -0400891 if (null == mTitleBar.getParent()) {
892 return;
893 }
Leon Scrogginsc6fa1102009-09-21 10:40:01 -0400894 openContextMenu(mTitleBar);
895 }
896
Leon Scrogginsb2b19f52009-10-09 16:10:00 -0400897 @Override
898 public void onContextMenuClosed(Menu menu) {
899 super.onContextMenuClosed(menu);
900 if (mInLoad) {
901 showFakeTitleBar();
902 }
903 }
904
Leon Scrogginsc6fa1102009-09-21 10:40:01 -0400905 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -0800906 * onSaveInstanceState(Bundle map)
907 * onSaveInstanceState is called right before onStop(). The map contains
908 * the saved state.
909 */
Grace Kloba22ac16e2009-10-07 18:00:23 -0700910 @Override
911 protected void onSaveInstanceState(Bundle outState) {
Dave Bort31a6d1c2009-04-13 15:56:49 -0700912 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800913 Log.v(LOGTAG, "BrowserActivity.onSaveInstanceState: this=" + this);
914 }
915 // the default implementation requires each view to have an id. As the
916 // browser handles the state itself and it doesn't use id for the views,
917 // don't call the default implementation. Otherwise it will trigger the
918 // warning like this, "couldn't save which view has focus because the
919 // focused view XXX has no id".
920
921 // Save all the tabs
922 mTabControl.saveState(outState);
Elliott Slaughter3d6df162010-08-25 13:17:44 -0700923
924 // Save time so that we know how old incognito tabs (if any) are.
925 outState.putSerializable("lastActiveDate", Calendar.getInstance());
The Android Open Source Project0c908882009-03-03 19:32:16 -0800926 }
927
Grace Kloba22ac16e2009-10-07 18:00:23 -0700928 @Override
929 protected void onPause() {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800930 super.onPause();
931
932 if (mActivityInPause) {
933 Log.e(LOGTAG, "BrowserActivity is already paused.");
934 return;
935 }
936
Mike Reed7bfa63b2009-05-28 11:08:32 -0400937 mTabControl.pauseCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800938 mActivityInPause = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -0400939 if (mTabControl.getCurrentIndex() >= 0 && !pauseWebViewTimers()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800940 mWakeLock.acquire();
941 mHandler.sendMessageDelayed(mHandler
942 .obtainMessage(RELEASE_WAKELOCK), WAKELOCK_TIMEOUT);
943 }
944
Leon Scrogginsa2ab6a72009-09-11 11:49:52 -0400945 // FIXME: This removes the active tabs page and resets the menu to
946 // MAIN_MENU. A better solution might be to do this work in onNewIntent
947 // but then we would need to save it in onSaveInstanceState and restore
948 // it in onCreate/onRestoreInstanceState
949 if (mActiveTabsPage != null) {
950 removeActiveTabPage(true);
951 }
Michael Kolbe421c242010-10-04 19:29:01 -0700952 removeComboView();
Leon Scrogginsa2ab6a72009-09-11 11:49:52 -0400953
The Android Open Source Project0c908882009-03-03 19:32:16 -0800954 cancelStopToast();
955
956 // unregister network state listener
957 unregisterReceiver(mNetworkStateIntentReceiver);
958 WebView.disablePlatformNotifications();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800959 }
960
Grace Kloba22ac16e2009-10-07 18:00:23 -0700961 @Override
962 protected void onDestroy() {
Dave Bort31a6d1c2009-04-13 15:56:49 -0700963 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800964 Log.v(LOGTAG, "BrowserActivity.onDestroy: this=" + this);
965 }
966 super.onDestroy();
Grace Kloba0923d692009-09-23 21:37:25 -0700967
Leon Scroggins8d5fa432009-10-02 15:55:59 -0400968 if (mUploadMessage != null) {
969 mUploadMessage.onReceiveValue(null);
970 mUploadMessage = null;
971 }
972
Grace Kloba0923d692009-09-23 21:37:25 -0700973 if (mTabControl == null) return;
974
Grace Kloba1fc98a32009-10-21 13:23:08 -0700975 // Remove the fake title bar if it is there
976 hideFakeTitleBar();
977
The Android Open Source Project0c908882009-03-03 19:32:16 -0800978 // Remove the current tab and sub window
Grace Kloba22ac16e2009-10-07 18:00:23 -0700979 Tab t = mTabControl.getCurrentTab();
Patrick Scottfb5e77f2009-04-08 19:17:37 -0700980 if (t != null) {
981 dismissSubWindow(t);
982 removeTabFromContentView(t);
983 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800984 // Destroy all the tabs
985 mTabControl.destroy();
986 WebIconDatabase.getInstance().close();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800987
Bjorn Bringerta7611812010-03-24 11:12:02 +0000988 // Stop watching the default geolocation permissions
989 mSystemAllowGeolocationOrigins.stop();
990 mSystemAllowGeolocationOrigins = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800991 }
992
993 @Override
994 public void onConfigurationChanged(Configuration newConfig) {
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400995 mConfigChanged = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800996 super.onConfigurationChanged(newConfig);
997
998 if (mPageInfoDialog != null) {
999 mPageInfoDialog.dismiss();
1000 showPageInfo(
1001 mPageInfoView,
Leon Scrogginsc7b92f82010-01-11 18:17:31 -05001002 mPageInfoFromShowSSLCertificateOnError);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001003 }
1004 if (mSSLCertificateDialog != null) {
1005 mSSLCertificateDialog.dismiss();
1006 showSSLCertificate(
1007 mSSLCertificateView);
1008 }
1009 if (mSSLCertificateOnErrorDialog != null) {
1010 mSSLCertificateOnErrorDialog.dismiss();
1011 showSSLCertificateOnError(
1012 mSSLCertificateOnErrorView,
1013 mSSLCertificateOnErrorHandler,
1014 mSSLCertificateOnErrorError);
1015 }
1016 if (mHttpAuthenticationDialog != null) {
1017 String title = ((TextView) mHttpAuthenticationDialog
1018 .findViewById(com.android.internal.R.id.alertTitle)).getText()
1019 .toString();
1020 String name = ((TextView) mHttpAuthenticationDialog
1021 .findViewById(R.id.username_edit)).getText().toString();
1022 String password = ((TextView) mHttpAuthenticationDialog
1023 .findViewById(R.id.password_edit)).getText().toString();
1024 int focusId = mHttpAuthenticationDialog.getCurrentFocus()
1025 .getId();
1026 mHttpAuthenticationDialog.dismiss();
1027 showHttpAuthentication(mHttpAuthHandler, null, null, title,
1028 name, password, focusId);
1029 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001030 }
1031
Grace Kloba22ac16e2009-10-07 18:00:23 -07001032 @Override
1033 public void onLowMemory() {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001034 super.onLowMemory();
1035 mTabControl.freeMemory();
1036 }
1037
Cary Clarkff4d92c2010-03-25 11:17:03 -04001038 private void resumeWebViewTimers() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001039 Tab tab = mTabControl.getCurrentTab();
Cary Clarkff4d92c2010-03-25 11:17:03 -04001040 if (tab == null) return; // monkey can trigger this
Grace Kloba22ac16e2009-10-07 18:00:23 -07001041 boolean inLoad = tab.inLoad();
1042 if ((!mActivityInPause && !inLoad) || (mActivityInPause && inLoad)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001043 CookieSyncManager.getInstance().startSync();
Grace Kloba22ac16e2009-10-07 18:00:23 -07001044 WebView w = tab.getWebView();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001045 if (w != null) {
1046 w.resumeTimers();
1047 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001048 }
1049 }
1050
Mike Reed7bfa63b2009-05-28 11:08:32 -04001051 private boolean pauseWebViewTimers() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001052 Tab tab = mTabControl.getCurrentTab();
1053 boolean inLoad = tab.inLoad();
1054 if (mActivityInPause && !inLoad) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001055 CookieSyncManager.getInstance().stopSync();
1056 WebView w = mTabControl.getCurrentWebView();
1057 if (w != null) {
1058 w.pauseTimers();
1059 }
1060 return true;
1061 } else {
1062 return false;
1063 }
1064 }
1065
The Android Open Source Project0c908882009-03-03 19:32:16 -08001066 // Open the icon database and retain all the icons for visited sites.
1067 private void retainIconsOnStartup() {
1068 final WebIconDatabase db = WebIconDatabase.getInstance();
1069 db.open(getDir("icons", 0).getPath());
Leon Scroggins2c0f6112010-03-12 18:09:39 -05001070 Cursor c = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001071 try {
Leon Scroggins2c0f6112010-03-12 18:09:39 -05001072 c = Browser.getAllBookmarks(mResolver);
1073 if (c.moveToFirst()) {
1074 int urlIndex = c.getColumnIndex(Browser.BookmarkColumns.URL);
1075 do {
1076 String url = c.getString(urlIndex);
1077 db.retainIconForPageUrl(url);
1078 } while (c.moveToNext());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001079 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001080 } catch (IllegalStateException e) {
1081 Log.e(LOGTAG, "retainIconsOnStartup", e);
Leon Scroggins2c0f6112010-03-12 18:09:39 -05001082 } finally {
1083 if (c!= null) c.close();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001084 }
1085 }
1086
1087 // Helper method for getting the top window.
1088 WebView getTopWindow() {
1089 return mTabControl.getCurrentTopWebView();
1090 }
1091
Grace Kloba22ac16e2009-10-07 18:00:23 -07001092 TabControl getTabControl() {
1093 return mTabControl;
1094 }
1095
The Android Open Source Project0c908882009-03-03 19:32:16 -08001096 @Override
1097 public boolean onCreateOptionsMenu(Menu menu) {
1098 super.onCreateOptionsMenu(menu);
1099
1100 MenuInflater inflater = getMenuInflater();
1101 inflater.inflate(R.menu.browser, menu);
1102 mMenu = menu;
1103 updateInLoadMenuItems();
1104 return true;
1105 }
1106
1107 /**
1108 * As the menu can be open when loading state changes
1109 * we must manually update the state of the stop/reload menu
1110 * item
1111 */
1112 private void updateInLoadMenuItems() {
1113 if (mMenu == null) {
1114 return;
1115 }
Michael Kolbe0a36662010-06-29 10:37:12 -07001116 MenuItem dest = mMenu.findItem(R.id.stop_reload_menu_id);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001117 MenuItem src = mInLoad ?
1118 mMenu.findItem(R.id.stop_menu_id):
Michael Kolbe0a36662010-06-29 10:37:12 -07001119 mMenu.findItem(R.id.reload_menu_id);
1120 if (src != null) {
1121 dest.setIcon(src.getIcon());
1122 dest.setTitle(src.getTitle());
1123 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001124 }
1125
1126 @Override
1127 public boolean onContextItemSelected(MenuItem item) {
1128 // chording is not an issue with context menus, but we use the same
1129 // options selector, so set mCanChord to true so we can access them.
1130 mCanChord = true;
1131 int id = item.getItemId();
Leon Scroggins96afcb12009-12-10 12:35:56 -05001132 boolean result = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001133 switch (id) {
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001134 // For the context menu from the title bar
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001135 case R.id.title_bar_copy_page_url:
Leon Scroggins96afcb12009-12-10 12:35:56 -05001136 Tab currentTab = mTabControl.getCurrentTab();
1137 if (null == currentTab) {
1138 result = false;
1139 break;
1140 }
1141 WebView mainView = currentTab.getWebView();
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001142 if (null == mainView) {
Leon Scroggins96afcb12009-12-10 12:35:56 -05001143 result = false;
1144 break;
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001145 }
Leon Scroggins96afcb12009-12-10 12:35:56 -05001146 copy(mainView.getUrl());
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001147 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001148 // -- Browser context menu
1149 case R.id.open_context_menu_id:
The Android Open Source Project0c908882009-03-03 19:32:16 -08001150 case R.id.bookmark_context_menu_id:
1151 case R.id.save_link_context_menu_id:
1152 case R.id.share_link_context_menu_id:
1153 case R.id.copy_link_context_menu_id:
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001154 final WebView webView = getTopWindow();
1155 if (null == webView) {
Leon Scroggins96afcb12009-12-10 12:35:56 -05001156 result = false;
1157 break;
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001158 }
1159 final HashMap hrefMap = new HashMap();
1160 hrefMap.put("webview", webView);
1161 final Message msg = mHandler.obtainMessage(
1162 FOCUS_NODE_HREF, id, 0, hrefMap);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001163 webView.requestFocusNodeHref(msg);
1164 break;
1165
1166 default:
1167 // For other context menus
Leon Scroggins96afcb12009-12-10 12:35:56 -05001168 result = onOptionsItemSelected(item);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001169 }
1170 mCanChord = false;
Leon Scroggins96afcb12009-12-10 12:35:56 -05001171 return result;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001172 }
1173
1174 private Bundle createGoogleSearchSourceBundle(String source) {
1175 Bundle bundle = new Bundle();
Bjorn Bringert10d1cca2010-02-10 14:22:12 +00001176 bundle.putString(Search.SOURCE, source);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001177 return bundle;
1178 }
1179
Leon Scroggins8ad29922010-02-16 12:33:55 -05001180 /* package */ void editUrl() {
Leon Scroggins68579392009-09-15 15:31:54 -04001181 if (mOptionsMenuOpen) closeOptionsMenu();
Leon Scroggins5bbe9802009-07-31 13:10:55 -04001182 String url = (getTopWindow() == null) ? null : getTopWindow().getUrl();
Grace Kloba83f47342009-07-20 10:44:31 -07001183 startSearch(mSettings.getHomePage().equals(url) ? null : url, true,
Leon Scroggins8ad29922010-02-16 12:33:55 -05001184 null, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001185 }
1186
Leon Scroggins8ad29922010-02-16 12:33:55 -05001187 /**
1188 * Overriding this to insert a local information bundle
1189 */
The Android Open Source Project0c908882009-03-03 19:32:16 -08001190 @Override
1191 public void startSearch(String initialQuery, boolean selectInitialQuery,
1192 Bundle appSearchData, boolean globalSearch) {
1193 if (appSearchData == null) {
1194 appSearchData = createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_TYPE);
1195 }
Leon Scroggins III430057d2010-09-14 10:57:37 -04001196
1197 SearchEngine searchEngine = mSettings.getSearchEngine();
1198 if (searchEngine != null && !searchEngine.supportsVoiceSearch()) {
1199 appSearchData.putBoolean(SearchManager.DISABLE_VOICE_SEARCH, true);
1200 }
1201
The Android Open Source Project0c908882009-03-03 19:32:16 -08001202 super.startSearch(initialQuery, selectInitialQuery, appSearchData, globalSearch);
1203 }
1204
Leon Scroggins1f005d32009-08-10 17:36:42 -04001205 /**
1206 * Switch tabs. Called by the TitleBarSet when sliding the title bar
1207 * results in changing tabs.
Leon Scroggins160a7e72009-08-14 18:28:01 -04001208 * @param index Index of the tab to change to, as defined by
1209 * mTabControl.getTabIndex(Tab t).
1210 * @return boolean True if we successfully switched to a different tab. If
1211 * the indexth tab is null, or if that tab is the same as
1212 * the current one, return false.
Leon Scroggins1f005d32009-08-10 17:36:42 -04001213 */
Leon Scroggins160a7e72009-08-14 18:28:01 -04001214 /* package */ boolean switchToTab(int index) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001215 Tab tab = mTabControl.getTab(index);
1216 Tab currentTab = mTabControl.getCurrentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04001217 if (tab == null || tab == currentTab) {
Leon Scroggins160a7e72009-08-14 18:28:01 -04001218 return false;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001219 }
1220 if (currentTab != null) {
1221 // currentTab may be null if it was just removed. In that case,
1222 // we do not need to remove it
1223 removeTabFromContentView(currentTab);
1224 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001225 mTabControl.setCurrentTab(tab);
1226 attachTabToContentView(tab);
Grace Klobaeb6eef42009-09-15 17:56:32 -07001227 resetTitleIconAndProgress();
1228 updateLockIconToLatest();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001229 return true;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001230 }
1231
Grace Kloba22ac16e2009-10-07 18:00:23 -07001232 /* package */ Tab openTabToHomePage() {
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001233 return openTabAndShow(mSettings.getHomePage(), false, null);
1234 }
1235
Leon Scroggins1f005d32009-08-10 17:36:42 -04001236 /* package */ void closeCurrentWindow() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001237 final Tab current = mTabControl.getCurrentTab();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001238 if (mTabControl.getTabCount() == 1) {
Leon Scroggins30444232009-09-04 18:36:20 -04001239 // This is the last tab. Open a new one, with the home
1240 // page and close the current one.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001241 openTabToHomePage();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001242 closeTab(current);
Leon Scroggins160a7e72009-08-14 18:28:01 -04001243 return;
1244 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07001245 final Tab parent = current.getParentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04001246 int indexToShow = -1;
1247 if (parent != null) {
1248 indexToShow = mTabControl.getTabIndex(parent);
1249 } else {
Leon Scroggins160a7e72009-08-14 18:28:01 -04001250 final int currentIndex = mTabControl.getCurrentIndex();
1251 // Try to move to the tab to the right
1252 indexToShow = currentIndex + 1;
1253 if (indexToShow > mTabControl.getTabCount() - 1) {
1254 // Try to move to the tab to the left
1255 indexToShow = currentIndex - 1;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001256 }
1257 }
Leon Scroggins160a7e72009-08-14 18:28:01 -04001258 if (switchToTab(indexToShow)) {
1259 // Close window
1260 closeTab(current);
1261 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001262 }
1263
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001264 private ActiveTabsPage mActiveTabsPage;
1265
1266 /**
1267 * Remove the active tabs page.
1268 * @param needToAttach If true, the active tabs page did not attach a tab
1269 * to the content view, so we need to do that here.
1270 */
1271 /* package */ void removeActiveTabPage(boolean needToAttach) {
1272 mContentView.removeView(mActiveTabsPage);
Leon Scrogginsd746a942010-05-19 13:21:44 -04001273 mTitleBar.setVisibility(View.VISIBLE);
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001274 mActiveTabsPage = null;
1275 mMenuState = R.id.MAIN_MENU;
1276 if (needToAttach) {
1277 attachTabToContentView(mTabControl.getCurrentTab());
1278 }
1279 getTopWindow().requestFocus();
1280 }
1281
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04001282 @Override
1283 public ActionMode onStartActionMode(ActionMode.Callback callback) {
Leon Scroggins4fc12cb2010-08-24 14:24:05 -04001284 mActionMode = super.onStartActionMode(callback);
1285 hideFakeTitleBar();
1286 // Would like to change the MENU, but onEndActionMode may not be called
1287 return mActionMode;
Cary Clark01cfcdd2010-06-04 16:36:45 -04001288 }
1289
The Android Open Source Project0c908882009-03-03 19:32:16 -08001290 @Override
1291 public boolean onOptionsItemSelected(MenuItem item) {
Michael Kolbe421c242010-10-04 19:29:01 -07001292 // menu remains active, so ensure comboview is dismissed
1293 removeComboView();
Michael Kolbed217742010-08-10 17:52:34 -07001294 // check the action bar button before mCanChord check, as the prepare call
1295 // doesn't come for action bar buttons
1296 if (item.getItemId() == R.id.newtab) {
Michael Kolb300b7f02010-08-25 13:47:24 -07001297 openTabToHomePage();
Michael Kolbed217742010-08-10 17:52:34 -07001298 return true;
1299 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001300 if (!mCanChord) {
1301 // The user has already fired a shortcut with this hold down of the
1302 // menu key.
1303 return false;
1304 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001305 if (null == getTopWindow()) {
Leon Scroggins0d7ae0e2009-06-05 11:04:45 -04001306 return false;
1307 }
Grace Kloba6ee9c492009-07-13 10:04:34 -07001308 if (mMenuIsDown) {
1309 // The shortcut action consumes the MENU. Even if it is still down,
1310 // it won't trigger the next shortcut action. In the case of the
1311 // shortcut action triggering a new activity, like Bookmarks, we
1312 // won't get onKeyUp for MENU. So it is important to reset it here.
1313 mMenuIsDown = false;
1314 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001315 switch (item.getItemId()) {
1316 // -- Main menu
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001317 case R.id.new_tab_menu_id:
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001318 openTabToHomePage();
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001319 break;
1320
Michael Kolbae62fd42010-08-18 16:33:28 -07001321 case R.id.incognito_menu_id:
1322 openIncognitoTab();
1323 break;
1324
Leon Scroggins64b80f32009-08-07 12:03:34 -04001325 case R.id.goto_menu_id:
Leon Scroggins8ad29922010-02-16 12:33:55 -05001326 editUrl();
Leon Scrogginsb3a5bed2009-09-28 11:21:56 -04001327 break;
1328
1329 case R.id.bookmarks_menu_id:
Michael Kolbe421c242010-10-04 19:29:01 -07001330 bookmarksOrHistoryPicker(false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001331 break;
1332
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001333 case R.id.active_tabs_menu_id:
1334 mActiveTabsPage = new ActiveTabsPage(this, mTabControl);
1335 removeTabFromContentView(mTabControl.getCurrentTab());
Leon Scrogginsd746a942010-05-19 13:21:44 -04001336 mTitleBar.setVisibility(View.GONE);
Leon Scroggins43de6162009-09-14 19:59:58 -04001337 hideFakeTitleBar();
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001338 mContentView.addView(mActiveTabsPage, COVER_SCREEN_PARAMS);
1339 mActiveTabsPage.requestFocus();
1340 mMenuState = EMPTY_MENU;
1341 break;
1342
Leon Scroggins1f005d32009-08-10 17:36:42 -04001343 case R.id.add_bookmark_menu_id:
Leon Scroggins571b3762010-05-26 10:25:01 -04001344 bookmarkCurrentPage();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001345 break;
1346
1347 case R.id.stop_reload_menu_id:
1348 if (mInLoad) {
1349 stopLoading();
1350 } else {
1351 getTopWindow().reload();
1352 }
1353 break;
1354
1355 case R.id.back_menu_id:
1356 getTopWindow().goBack();
1357 break;
1358
1359 case R.id.forward_menu_id:
1360 getTopWindow().goForward();
1361 break;
1362
1363 case R.id.close_menu_id:
1364 // Close the subwindow if it exists.
1365 if (mTabControl.getCurrentSubWindow() != null) {
1366 dismissSubWindow(mTabControl.getCurrentTab());
1367 break;
1368 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001369 closeCurrentWindow();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001370 break;
1371
1372 case R.id.homepage_menu_id:
Grace Kloba22ac16e2009-10-07 18:00:23 -07001373 Tab current = mTabControl.getCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001374 if (current != null) {
1375 dismissSubWindow(current);
Leon Scroggins92472e82010-02-17 16:32:28 -05001376 loadUrl(current.getWebView(), mSettings.getHomePage());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001377 }
1378 break;
1379
1380 case R.id.preferences_menu_id:
1381 Intent intent = new Intent(this,
1382 BrowserPreferencesPage.class);
Leon Scrogginsd5304942009-12-10 16:11:39 -05001383 intent.putExtra(BrowserPreferencesPage.CURRENT_PAGE,
1384 getTopWindow().getUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001385 startActivityForResult(intent, PREFERENCES_PAGE);
1386 break;
1387
1388 case R.id.find_menu_id:
Leon Scroggins4fc12cb2010-08-24 14:24:05 -04001389 getTopWindow().showFindDialog(null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001390 break;
1391
Elliott Slaughter0ced08c2010-06-30 11:40:42 -07001392 case R.id.save_webarchive_menu_id:
1393 if (LOGD_ENABLED) {
1394 Log.d(LOGTAG, "Save as Web Archive");
1395 }
Elliott Slaughteraba242c2010-09-01 16:21:07 -07001396 String state = Environment.getExternalStorageState();
1397 if (Environment.MEDIA_MOUNTED.equals(state)) {
1398 String directory = Environment.getExternalStoragePublicDirectory(
1399 Environment.DIRECTORY_DOWNLOADS).getAbsolutePath() + File.separator;
Shimeng (Simon) Wang447c8462010-09-15 18:16:55 -07001400 File dir = new File(directory);
1401 if (!dir.exists() && !dir.mkdirs()) {
1402 Log.e(LOGTAG, "Save as Web Archive: mkdirs for " + directory + " failed!");
1403 Toast.makeText(BrowserActivity.this, R.string.webarchive_failed,
1404 Toast.LENGTH_SHORT).show();
1405 break;
1406 }
Elliott Slaughteraba242c2010-09-01 16:21:07 -07001407 getTopWindow().saveWebArchive(directory, true, new ValueCallback<String>() {
1408 @Override
1409 public void onReceiveValue(String value) {
1410 if (value != null) {
1411 Toast.makeText(BrowserActivity.this, R.string.webarchive_saved,
1412 Toast.LENGTH_SHORT).show();
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 }
Elliott Slaughteraba242c2010-09-01 16:21:07 -07001418 });
1419 } else {
1420 Toast.makeText(BrowserActivity.this, R.string.webarchive_failed,
1421 Toast.LENGTH_SHORT).show();
1422 }
Elliott Slaughter0ced08c2010-06-30 11:40:42 -07001423 break;
1424
The Android Open Source Project0c908882009-03-03 19:32:16 -08001425 case R.id.page_info_menu_id:
1426 showPageInfo(mTabControl.getCurrentTab(), false);
1427 break;
1428
1429 case R.id.classic_history_menu_id:
Michael Kolbe421c242010-10-04 19:29:01 -07001430 bookmarksOrHistoryPicker(true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001431 break;
1432
Leon Scroggins96afcb12009-12-10 12:35:56 -05001433 case R.id.title_bar_share_page_url:
The Android Open Source Project0c908882009-03-03 19:32:16 -08001434 case R.id.share_page_menu_id:
Leon Scroggins96afcb12009-12-10 12:35:56 -05001435 Tab currentTab = mTabControl.getCurrentTab();
1436 if (null == currentTab) {
1437 mCanChord = false;
1438 return false;
1439 }
1440 currentTab.populatePickerData();
1441 sharePage(this, currentTab.getTitle(),
1442 currentTab.getUrl(), currentTab.getFavicon(),
Ben Murdoch87cc65d2010-06-29 20:34:10 +01001443 createScreenshot(currentTab.getWebView(), getDesiredThumbnailWidth(this),
1444 getDesiredThumbnailHeight(this)));
The Android Open Source Project0c908882009-03-03 19:32:16 -08001445 break;
1446
1447 case R.id.dump_nav_menu_id:
1448 getTopWindow().debugDump();
1449 break;
1450
Andrei Popescu7a8b88b2010-02-02 00:30:38 +00001451 case R.id.dump_counters_menu_id:
1452 getTopWindow().dumpV8Counters();
1453 break;
1454
The Android Open Source Project0c908882009-03-03 19:32:16 -08001455 case R.id.zoom_in_menu_id:
1456 getTopWindow().zoomIn();
1457 break;
1458
1459 case R.id.zoom_out_menu_id:
1460 getTopWindow().zoomOut();
1461 break;
1462
1463 case R.id.view_downloads_menu_id:
Leon Scroggins IIIa682a3c2010-09-27 12:32:40 -04001464 viewDownloads();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001465 break;
1466
The Android Open Source Project0c908882009-03-03 19:32:16 -08001467 case R.id.window_one_menu_id:
1468 case R.id.window_two_menu_id:
1469 case R.id.window_three_menu_id:
1470 case R.id.window_four_menu_id:
1471 case R.id.window_five_menu_id:
1472 case R.id.window_six_menu_id:
1473 case R.id.window_seven_menu_id:
1474 case R.id.window_eight_menu_id:
1475 {
1476 int menuid = item.getItemId();
1477 for (int id = 0; id < WINDOW_SHORTCUT_ID_ARRAY.length; id++) {
1478 if (WINDOW_SHORTCUT_ID_ARRAY[id] == menuid) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001479 Tab desiredTab = mTabControl.getTab(id);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001480 if (desiredTab != null &&
1481 desiredTab != mTabControl.getCurrentTab()) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001482 switchToTab(id);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001483 }
1484 break;
1485 }
1486 }
1487 }
1488 break;
1489
1490 default:
1491 if (!super.onOptionsItemSelected(item)) {
1492 return false;
1493 }
1494 // Otherwise fall through.
1495 }
1496 mCanChord = false;
1497 return true;
1498 }
1499
Leon Scroggins571b3762010-05-26 10:25:01 -04001500 /* package */ void bookmarkCurrentPage() {
1501 Intent i = new Intent(BrowserActivity.this,
1502 AddBookmarkPage.class);
1503 WebView w = getTopWindow();
1504 i.putExtra("url", w.getUrl());
1505 i.putExtra("title", w.getTitle());
1506 i.putExtra("touch_icon_url", w.getTouchIconUrl());
Ben Murdoch87cc65d2010-06-29 20:34:10 +01001507 i.putExtra("thumbnail", createScreenshot(w, getDesiredThumbnailWidth(this),
1508 getDesiredThumbnailHeight(this)));
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 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001628 WebView webview = (WebView) v;
1629 WebView.HitTestResult result = webview.getHitTestResult();
1630 if (result == null) {
1631 return;
1632 }
1633
1634 int type = result.getType();
1635 if (type == WebView.HitTestResult.UNKNOWN_TYPE) {
1636 Log.w(LOGTAG,
1637 "We should not show context menu when nothing is touched");
1638 return;
1639 }
1640 if (type == WebView.HitTestResult.EDIT_TEXT_TYPE) {
1641 // let TextView handles context menu
1642 return;
1643 }
1644
1645 // Note, http://b/issue?id=1106666 is requesting that
1646 // an inflated menu can be used again. This is not available
1647 // yet, so inflate each time (yuk!)
1648 MenuInflater inflater = getMenuInflater();
1649 inflater.inflate(R.menu.browsercontext, menu);
1650
1651 // Show the correct menu group
Leon Scroggins III9e997c72010-05-26 13:25:16 -04001652 final String extra = result.getExtra();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001653 menu.setGroupVisible(R.id.PHONE_MENU,
1654 type == WebView.HitTestResult.PHONE_TYPE);
1655 menu.setGroupVisible(R.id.EMAIL_MENU,
1656 type == WebView.HitTestResult.EMAIL_TYPE);
1657 menu.setGroupVisible(R.id.GEO_MENU,
1658 type == WebView.HitTestResult.GEO_TYPE);
1659 menu.setGroupVisible(R.id.IMAGE_MENU,
1660 type == WebView.HitTestResult.IMAGE_TYPE
1661 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1662 menu.setGroupVisible(R.id.ANCHOR_MENU,
1663 type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1664 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1665
1666 // Setup custom handling depending on the type
1667 switch (type) {
1668 case WebView.HitTestResult.PHONE_TYPE:
1669 menu.setHeaderTitle(Uri.decode(extra));
1670 menu.findItem(R.id.dial_context_menu_id).setIntent(
1671 new Intent(Intent.ACTION_VIEW, Uri
1672 .parse(WebView.SCHEME_TEL + extra)));
1673 Intent addIntent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
1674 addIntent.putExtra(Insert.PHONE, Uri.decode(extra));
Cary Clark5e335a32009-09-22 14:53:11 -04001675 addIntent.setType(ContactsContract.Contacts.CONTENT_ITEM_TYPE);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001676 menu.findItem(R.id.add_contact_context_menu_id).setIntent(
1677 addIntent);
1678 menu.findItem(R.id.copy_phone_context_menu_id).setOnMenuItemClickListener(
1679 new Copy(extra));
1680 break;
1681
1682 case WebView.HitTestResult.EMAIL_TYPE:
1683 menu.setHeaderTitle(extra);
1684 menu.findItem(R.id.email_context_menu_id).setIntent(
1685 new Intent(Intent.ACTION_VIEW, Uri
1686 .parse(WebView.SCHEME_MAILTO + extra)));
1687 menu.findItem(R.id.copy_mail_context_menu_id).setOnMenuItemClickListener(
1688 new Copy(extra));
1689 break;
1690
1691 case WebView.HitTestResult.GEO_TYPE:
1692 menu.setHeaderTitle(extra);
1693 menu.findItem(R.id.map_context_menu_id).setIntent(
1694 new Intent(Intent.ACTION_VIEW, Uri
1695 .parse(WebView.SCHEME_GEO
1696 + URLEncoder.encode(extra))));
1697 menu.findItem(R.id.copy_geo_context_menu_id).setOnMenuItemClickListener(
1698 new Copy(extra));
1699 break;
1700
1701 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1702 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
1703 TextView titleView = (TextView) LayoutInflater.from(this)
1704 .inflate(android.R.layout.browser_link_context_header,
1705 null);
1706 titleView.setText(extra);
1707 menu.setHeaderView(titleView);
1708 // decide whether to show the open link in new tab option
Leon Scroggins III9e997c72010-05-26 13:25:16 -04001709 boolean showNewTab = mTabControl.canCreateNewTab();
1710 MenuItem newTabItem
1711 = menu.findItem(R.id.open_newtab_context_menu_id);
1712 newTabItem.setVisible(showNewTab);
1713 if (showNewTab) {
1714 newTabItem.setOnMenuItemClickListener(
1715 new MenuItem.OnMenuItemClickListener() {
1716 public boolean onMenuItemClick(MenuItem item) {
1717 final Tab parent = mTabControl.getCurrentTab();
Michael Kolb68792c82010-08-09 16:39:18 -07001718 final Tab newTab = openTab(extra, false);
Leon Scroggins III9e997c72010-05-26 13:25:16 -04001719 if (newTab != parent) {
1720 parent.addChildTab(newTab);
1721 }
1722 return true;
1723 }
1724 });
1725 }
Ben Murdochde353622009-10-12 10:29:00 +01001726 menu.findItem(R.id.bookmark_context_menu_id).setVisible(
1727 Bookmarks.urlHasAcceptableScheme(extra));
The Android Open Source Project0c908882009-03-03 19:32:16 -08001728 PackageManager pm = getPackageManager();
1729 Intent send = new Intent(Intent.ACTION_SEND);
1730 send.setType("text/plain");
1731 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1732 menu.findItem(R.id.share_link_context_menu_id).setVisible(ri != null);
1733 if (type == WebView.HitTestResult.SRC_ANCHOR_TYPE) {
1734 break;
1735 }
1736 // otherwise fall through to handle image part
1737 case WebView.HitTestResult.IMAGE_TYPE:
1738 if (type == WebView.HitTestResult.IMAGE_TYPE) {
1739 menu.setHeaderTitle(extra);
1740 }
1741 menu.findItem(R.id.view_image_context_menu_id).setIntent(
1742 new Intent(Intent.ACTION_VIEW, Uri.parse(extra)));
1743 menu.findItem(R.id.download_context_menu_id).
1744 setOnMenuItemClickListener(new Download(extra));
Ben Murdoch4f75ba22009-10-27 11:48:28 +00001745 menu.findItem(R.id.set_wallpaper_context_menu_id).
1746 setOnMenuItemClickListener(new SetAsWallpaper(extra));
The Android Open Source Project0c908882009-03-03 19:32:16 -08001747 break;
1748
1749 default:
1750 Log.w(LOGTAG, "We should not get here.");
1751 break;
1752 }
Leon Scrogginsb2b19f52009-10-09 16:10:00 -04001753 hideFakeTitleBar();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001754 }
1755
The Android Open Source Project0c908882009-03-03 19:32:16 -08001756 // Attach the given tab to the content view.
Grace Klobac928c302009-09-17 11:51:21 -07001757 // this should only be called for the current tab.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001758 private void attachTabToContentView(Tab t) {
Steve Block2bc69912009-07-30 14:45:13 +01001759 // Attach the container that contains the main WebView and any other UI
1760 // associated with the tab.
Patrick Scottd0119532009-09-17 08:00:31 -04001761 t.attachTabToContentView(mContentView);
Ben Murdochbff2d602009-07-01 20:19:05 +01001762
1763 if (mShouldShowErrorConsole) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001764 ErrorConsoleView errorConsole = t.getErrorConsole(true);
Ben Murdochbff2d602009-07-01 20:19:05 +01001765 if (errorConsole.numberOfErrors() == 0) {
1766 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
1767 } else {
1768 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
1769 }
1770
1771 mErrorConsoleContainer.addView(errorConsole,
Romain Guy15b8ec62010-01-08 15:06:43 -08001772 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
Ben Murdochbff2d602009-07-01 20:19:05 +01001773 ViewGroup.LayoutParams.WRAP_CONTENT));
1774 }
1775
Michael Kolba2b2ba82010-08-04 17:54:03 -07001776 WebView view = t.getWebView();
1777 view.setEmbeddedTitleBar(mTitleBar);
Leon Scroggins58d56c62010-01-28 15:12:40 -05001778 if (t.isInVoiceSearchMode()) {
1779 showVoiceTitleBar(t.getVoiceDisplayTitle());
1780 } else {
1781 revertVoiceTitleBar();
1782 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001783 // Request focus on the top window.
1784 t.getTopWindow().requestFocus();
Michael Kolba2b2ba82010-08-04 17:54:03 -07001785 if (mTabControl.getTabChangeListener() != null) {
1786 mTabControl.getTabChangeListener().onCurrentTab(t);
1787 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001788 }
1789
1790 // Attach a sub window to the main WebView of the given tab.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001791 void attachSubWindow(Tab t) {
Patrick Scottd0119532009-09-17 08:00:31 -04001792 t.attachSubWindow(mContentView);
1793 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001794 }
1795
1796 // Remove the given tab from the content view.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001797 private void removeTabFromContentView(Tab t) {
Steve Block2bc69912009-07-30 14:45:13 +01001798 // Remove the container that contains the main WebView.
Patrick Scottd0119532009-09-17 08:00:31 -04001799 t.removeTabFromContentView(mContentView);
Ben Murdochbff2d602009-07-01 20:19:05 +01001800
Grace Kloba22ac16e2009-10-07 18:00:23 -07001801 ErrorConsoleView errorConsole = t.getErrorConsole(false);
1802 if (errorConsole != null) {
1803 mErrorConsoleContainer.removeView(errorConsole);
Ben Murdochbff2d602009-07-01 20:19:05 +01001804 }
1805
Michael Kolba2b2ba82010-08-04 17:54:03 -07001806 WebView view = t.getWebView();
1807 if (view != null) {
1808 view.setEmbeddedTitleBar(null);
Leon Scrogginsbb85b902009-09-14 19:27:20 -04001809 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001810 }
1811
1812 // Remove the sub window if it exists. Also called by TabControl when the
1813 // user clicks the 'X' to dismiss a sub window.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001814 /* package */ void dismissSubWindow(Tab t) {
Patrick Scottd0119532009-09-17 08:00:31 -04001815 t.removeSubWindow(mContentView);
Grace Kloba22ac16e2009-10-07 18:00:23 -07001816 // dismiss the subwindow. This will destroy the WebView.
1817 t.dismissSubWindow();
Patrick Scottd0119532009-09-17 08:00:31 -04001818 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001819 }
1820
Leon Scroggins1f005d32009-08-10 17:36:42 -04001821 // A wrapper function of {@link #openTabAndShow(UrlData, boolean, String)}
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07001822 // that accepts url as string.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001823 private Tab openTabAndShow(String url, boolean closeOnExit, String appId) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001824 return openTabAndShow(new UrlData(url), closeOnExit, appId);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001825 }
1826
1827 // This method does a ton of stuff. It will attempt to create a new tab
1828 // if we haven't reached MAX_TABS. Otherwise it uses the current tab. If
Leon Scroggins1f005d32009-08-10 17:36:42 -04001829 // url isn't null, it will load the given url.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001830 /* package */Tab openTabAndShow(UrlData urlData, boolean closeOnExit,
1831 String appId) {
1832 final Tab currentTab = mTabControl.getCurrentTab();
1833 if (mTabControl.canCreateNewTab()) {
1834 final Tab tab = mTabControl.createNewTab(closeOnExit, appId,
Elliott Slaughterf0f03952010-07-14 18:10:36 -07001835 urlData.mUrl, false);
Leon Scroggins1f005d32009-08-10 17:36:42 -04001836 WebView webview = tab.getWebView();
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001837 // If the last tab was removed from the active tabs page, currentTab
1838 // will be null.
1839 if (currentTab != null) {
1840 removeTabFromContentView(currentTab);
1841 }
Patrick Scott8bbd69f2009-08-14 13:35:53 -04001842 // We must set the new tab as the current tab to reflect the old
1843 // animation behavior.
1844 mTabControl.setCurrentTab(tab);
Grace Klobaeb6eef42009-09-15 17:56:32 -07001845 attachTabToContentView(tab);
Leon Scroggins160a7e72009-08-14 18:28:01 -04001846 if (!urlData.isEmpty()) {
Patrick Scott9d53da02010-02-19 10:19:01 -05001847 loadUrlDataIn(tab, urlData);
Leon Scroggins1f005d32009-08-10 17:36:42 -04001848 }
1849 return tab;
1850 } else {
1851 // Get rid of the subwindow if it exists
1852 dismissSubWindow(currentTab);
1853 if (!urlData.isEmpty()) {
1854 // Load the given url.
Patrick Scott9d53da02010-02-19 10:19:01 -05001855 loadUrlDataIn(currentTab, urlData);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001856 }
Leon Scroggins58d56c62010-01-28 15:12:40 -05001857 return currentTab;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001858 }
1859 }
1860
Michael Kolb68792c82010-08-09 16:39:18 -07001861 private Tab openTab(String url, boolean forceForeground) {
1862 if (mSettings.openInBackground() && !forceForeground) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001863 Tab t = mTabControl.createNewTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001864 if (t != null) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001865 WebView view = t.getWebView();
Leon Scroggins92472e82010-02-17 16:32:28 -05001866 loadUrl(view, url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001867 }
Grace Klobac9181842009-04-14 08:53:22 -07001868 return t;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001869 } else {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001870 return openTabAndShow(url, false, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001871 }
1872 }
1873
Elliott Slaughterf0f03952010-07-14 18:10:36 -07001874 /* package */ Tab openIncognitoTab() {
1875 if (mTabControl.canCreateNewTab()) {
1876 Tab currentTab = mTabControl.getCurrentTab();
1877 Tab tab = mTabControl.createNewTab(false, null, null, true);
1878 if (currentTab != null) {
1879 removeTabFromContentView(currentTab);
1880 }
1881 mTabControl.setCurrentTab(tab);
1882 attachTabToContentView(tab);
1883 return tab;
1884 }
1885 return null;
1886 }
1887
The Android Open Source Project0c908882009-03-03 19:32:16 -08001888 private class Copy implements OnMenuItemClickListener {
1889 private CharSequence mText;
1890
1891 public boolean onMenuItemClick(MenuItem item) {
1892 copy(mText);
1893 return true;
1894 }
1895
1896 public Copy(CharSequence toCopy) {
1897 mText = toCopy;
1898 }
1899 }
1900
1901 private class Download implements OnMenuItemClickListener {
1902 private String mText;
1903
1904 public boolean onMenuItemClick(MenuItem item) {
1905 onDownloadStartNoStream(mText, null, null, null, -1);
1906 return true;
1907 }
1908
1909 public Download(String toDownload) {
1910 mText = toDownload;
1911 }
1912 }
1913
Ben Murdoch4f75ba22009-10-27 11:48:28 +00001914 private class SetAsWallpaper extends Thread implements
1915 OnMenuItemClickListener, DialogInterface.OnCancelListener {
1916 private URL mUrl;
1917 private ProgressDialog mWallpaperProgress;
1918 private boolean mCanceled = false;
1919
1920 public SetAsWallpaper(String url) {
1921 try {
1922 mUrl = new URL(url);
1923 } catch (MalformedURLException e) {
1924 mUrl = null;
1925 }
1926 }
1927
1928 public void onCancel(DialogInterface dialog) {
1929 mCanceled = true;
1930 }
1931
1932 public boolean onMenuItemClick(MenuItem item) {
1933 if (mUrl != null) {
1934 // The user may have tried to set a image with a large file size as their
1935 // background so it may take a few moments to perform the operation. Display
1936 // a progress spinner while it is working.
1937 mWallpaperProgress = new ProgressDialog(BrowserActivity.this);
1938 mWallpaperProgress.setIndeterminate(true);
1939 mWallpaperProgress.setMessage(getText(R.string.progress_dialog_setting_wallpaper));
1940 mWallpaperProgress.setCancelable(true);
1941 mWallpaperProgress.setOnCancelListener(this);
1942 mWallpaperProgress.show();
1943 start();
1944 }
1945 return true;
1946 }
1947
Michael Kolbe0a36662010-06-29 10:37:12 -07001948 @Override
Ben Murdoch4f75ba22009-10-27 11:48:28 +00001949 public void run() {
1950 Drawable oldWallpaper = BrowserActivity.this.getWallpaper();
1951 try {
1952 // TODO: This will cause the resource to be downloaded again, when we
1953 // should in most cases be able to grab it from the cache. To fix this
1954 // we should query WebCore to see if we can access a cached version and
1955 // instead open an input stream on that. This pattern could also be used
1956 // in the download manager where the same problem exists.
1957 InputStream inputstream = mUrl.openStream();
1958 if (inputstream != null) {
1959 setWallpaper(inputstream);
1960 }
1961 } catch (IOException e) {
1962 Log.e(LOGTAG, "Unable to set new wallpaper");
1963 // Act as though the user canceled the operation so we try to
1964 // restore the old wallpaper.
1965 mCanceled = true;
1966 }
1967
1968 if (mCanceled) {
1969 // Restore the old wallpaper if the user cancelled whilst we were setting
1970 // the new wallpaper.
1971 int width = oldWallpaper.getIntrinsicWidth();
1972 int height = oldWallpaper.getIntrinsicHeight();
1973 Bitmap bm = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
1974 Canvas canvas = new Canvas(bm);
1975 oldWallpaper.setBounds(0, 0, width, height);
1976 oldWallpaper.draw(canvas);
1977 try {
1978 setWallpaper(bm);
1979 } catch (IOException e) {
1980 Log.e(LOGTAG, "Unable to restore old wallpaper.");
1981 }
1982 mCanceled = false;
1983 }
1984
1985 if (mWallpaperProgress.isShowing()) {
1986 mWallpaperProgress.dismiss();
1987 }
1988 }
1989 }
1990
The Android Open Source Project0c908882009-03-03 19:32:16 -08001991 private void copy(CharSequence text) {
Dianne Hackborn80f32622010-08-05 14:17:53 -07001992 ClipboardManager cm = (ClipboardManager)getSystemService(Context.CLIPBOARD_SERVICE);
1993 cm.setText(text);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001994 }
1995
1996 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08001997 * Resets the browser title-view to whatever it must be
1998 * (for example, if we had a loading error)
1999 * When we have a new page, we call resetTitle, when we
2000 * have to reset the titlebar to whatever it used to be
2001 * (for example, if the user chose to stop loading), we
2002 * call resetTitleAndRevertLockIcon.
2003 */
2004 /* package */ void resetTitleAndRevertLockIcon() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002005 mTabControl.getCurrentTab().revertLockIcon();
2006 updateLockIconToLatest();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002007 resetTitleIconAndProgress();
2008 }
2009
2010 /**
2011 * Reset the title, favicon, and progress.
2012 */
2013 private void resetTitleIconAndProgress() {
2014 WebView current = mTabControl.getCurrentWebView();
2015 if (current == null) {
2016 return;
2017 }
2018 resetTitleAndIcon(current);
2019 int progress = current.getProgress();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002020 current.getWebChromeClient().onProgressChanged(current, progress);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002021 }
2022
2023 // Reset the title and the icon based on the given item.
2024 private void resetTitleAndIcon(WebView view) {
2025 WebHistoryItem item = view.copyBackForwardList().getCurrentItem();
2026 if (item != null) {
Leon Scroggins68579392009-09-15 15:31:54 -04002027 setUrlTitle(item.getUrl(), item.getTitle());
The Android Open Source Project0c908882009-03-03 19:32:16 -08002028 setFavicon(item.getFavicon());
2029 } else {
Leon Scroggins68579392009-09-15 15:31:54 -04002030 setUrlTitle(null, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002031 setFavicon(null);
2032 }
2033 }
2034
2035 /**
2036 * Sets a title composed of the URL and the title string.
2037 * @param url The URL of the site being loaded.
2038 * @param title The title of the site being loaded.
2039 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07002040 void setUrlTitle(String url, String title) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002041 mUrl = url;
2042 mTitle = title;
2043
Leon Scroggins58d56c62010-01-28 15:12:40 -05002044 // If we are in voice search mode, the title has already been set.
2045 if (mTabControl.getCurrentTab().isInVoiceSearchMode()) return;
2046 mTitleBar.setDisplayTitle(url);
Michael Kolba2b2ba82010-08-04 17:54:03 -07002047 mFakeTitleBar.setDisplayTitle(url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002048 }
2049
2050 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08002051 * @param url The URL to build a title version of the URL from.
2052 * @return The title version of the URL or null if fails.
2053 * The title version of the URL can be either the URL hostname,
2054 * or the hostname with an "https://" prefix (for secure URLs),
2055 * or an empty string if, for example, the URL in question is a
2056 * file:// URL with no hostname.
2057 */
Leon Scroggins32e14a62009-06-11 10:26:34 -04002058 /* package */ static String buildTitleUrl(String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002059 String titleUrl = null;
2060
2061 if (url != null) {
2062 try {
2063 // parse the url string
2064 URL urlObj = new URL(url);
2065 if (urlObj != null) {
2066 titleUrl = "";
2067
2068 String protocol = urlObj.getProtocol();
2069 String host = urlObj.getHost();
2070
2071 if (host != null && 0 < host.length()) {
2072 titleUrl = host;
2073 if (protocol != null) {
2074 // if a secure site, add an "https://" prefix!
2075 if (protocol.equalsIgnoreCase("https")) {
2076 titleUrl = protocol + "://" + host;
2077 }
2078 }
2079 }
2080 }
2081 } catch (MalformedURLException e) {}
2082 }
2083
2084 return titleUrl;
2085 }
2086
2087 // Set the favicon in the title bar.
Grace Kloba22ac16e2009-10-07 18:00:23 -07002088 void setFavicon(Bitmap icon) {
Leon Scroggins68579392009-09-15 15:31:54 -04002089 mTitleBar.setFavicon(icon);
Michael Kolba2b2ba82010-08-04 17:54:03 -07002090 mFakeTitleBar.setFavicon(icon);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002091 }
2092
2093 /**
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002094 * Close the tab, remove its associated title bar, and adjust mTabControl's
2095 * current tab to a valid value.
Leon Scroggins1f005d32009-08-10 17:36:42 -04002096 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07002097 /* package */ void closeTab(Tab t) {
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002098 int currentIndex = mTabControl.getCurrentIndex();
2099 int removeIndex = mTabControl.getTabIndex(t);
Leon Scroggins1f005d32009-08-10 17:36:42 -04002100 mTabControl.removeTab(t);
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002101 if (currentIndex >= removeIndex && currentIndex != 0) {
2102 currentIndex--;
2103 }
2104 mTabControl.setCurrentTab(mTabControl.getTab(currentIndex));
Andrei Popescua5bf1de2009-09-23 16:39:23 +01002105 resetTitleIconAndProgress();
Leon Scroggins654899b2010-06-25 16:25:23 -04002106 updateLockIconToLatest();
Elliott Slaughtere440a882010-08-20 13:54:45 -07002107
2108 if (!mTabControl.hasAnyOpenIncognitoTabs()) {
2109 WebView.cleanupPrivateBrowsingFiles(this);
2110 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002111 }
2112
Leon Scrogginsdcc5eeb2010-02-23 17:26:37 -05002113 /* package */ void goBackOnePageOrQuit() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002114 Tab current = mTabControl.getCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002115 if (current == null) {
2116 /*
2117 * Instead of finishing the activity, simply push this to the back
2118 * of the stack and let ActivityManager to choose the foreground
2119 * activity. As BrowserActivity is singleTask, it will be always the
2120 * root of the task. So we can use either true or false for
2121 * moveTaskToBack().
2122 */
2123 moveTaskToBack(true);
Grace Kloba00d85e72009-09-23 18:50:05 -07002124 return;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002125 }
2126 WebView w = current.getWebView();
2127 if (w.canGoBack()) {
2128 w.goBack();
2129 } else {
2130 // Check to see if we are closing a window that was created by
2131 // another window. If so, we switch back to that window.
Grace Kloba22ac16e2009-10-07 18:00:23 -07002132 Tab parent = current.getParentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002133 if (parent != null) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04002134 switchToTab(mTabControl.getTabIndex(parent));
2135 // Now we close the other tab
2136 closeTab(current);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002137 } else {
2138 if (current.closeOnExit()) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002139 // force the tab's inLoad() to be false as we are going to
2140 // either finish the activity or remove the tab. This will
2141 // ensure pauseWebViewTimers() taking action.
2142 mTabControl.getCurrentTab().clearInLoad();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002143 if (mTabControl.getTabCount() == 1) {
2144 finish();
2145 return;
2146 }
Mike Reed7bfa63b2009-05-28 11:08:32 -04002147 // call pauseWebViewTimers() now, we won't be able to call
2148 // it in onPause() as the WebView won't be valid.
Grace Klobaec1b5ad2009-08-18 08:42:32 -07002149 // Temporarily change mActivityInPause to be true as
2150 // pauseWebViewTimers() will do nothing if mActivityInPause
2151 // is false.
Grace Kloba918e1d72009-08-13 14:55:06 -07002152 boolean savedState = mActivityInPause;
2153 if (savedState) {
Grace Klobaec1b5ad2009-08-18 08:42:32 -07002154 Log.e(LOGTAG, "BrowserActivity is already paused "
2155 + "while handing goBackOnePageOrQuit.");
Grace Kloba918e1d72009-08-13 14:55:06 -07002156 }
2157 mActivityInPause = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -04002158 pauseWebViewTimers();
Grace Kloba918e1d72009-08-13 14:55:06 -07002159 mActivityInPause = savedState;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002160 removeTabFromContentView(current);
2161 mTabControl.removeTab(current);
2162 }
2163 /*
2164 * Instead of finishing the activity, simply push this to the back
2165 * of the stack and let ActivityManager to choose the foreground
2166 * activity. As BrowserActivity is singleTask, it will be always the
2167 * root of the task. So we can use either true or false for
2168 * moveTaskToBack().
2169 */
2170 moveTaskToBack(true);
2171 }
2172 }
2173 }
2174
Grace Kloba22ac16e2009-10-07 18:00:23 -07002175 boolean isMenuDown() {
2176 return mMenuIsDown;
2177 }
2178
Grace Kloba5942df02009-09-18 11:48:29 -07002179 @Override
2180 public boolean onKeyDown(int keyCode, KeyEvent event) {
Leon Scrogginsf65b50d2009-12-08 10:44:28 -05002181 // Even if MENU is already held down, we need to call to super to open
2182 // the IME on long press.
2183 if (KeyEvent.KEYCODE_MENU == keyCode) {
2184 mMenuIsDown = true;
2185 return super.onKeyDown(keyCode, event);
2186 }
Grace Kloba5942df02009-09-18 11:48:29 -07002187 // The default key mode is DEFAULT_KEYS_SEARCH_LOCAL. As the MENU is
2188 // still down, we don't want to trigger the search. Pretend to consume
2189 // the key and do nothing.
2190 if (mMenuIsDown) return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002191
Grace Kloba5942df02009-09-18 11:48:29 -07002192 switch(keyCode) {
Grace Kloba5942df02009-09-18 11:48:29 -07002193 case KeyEvent.KEYCODE_SPACE:
Grace Klobada0fe552009-09-22 18:17:24 -07002194 // WebView/WebTextView handle the keys in the KeyDown. As
2195 // the Activity's shortcut keys are only handled when WebView
2196 // doesn't, have to do it in onKeyDown instead of onKeyUp.
2197 if (event.isShiftPressed()) {
2198 getTopWindow().pageUp(false);
2199 } else {
2200 getTopWindow().pageDown(false);
2201 }
Grace Kloba5942df02009-09-18 11:48:29 -07002202 return true;
2203 case KeyEvent.KEYCODE_BACK:
2204 if (event.getRepeatCount() == 0) {
2205 event.startTracking();
2206 return true;
2207 } else if (mCustomView == null && mActiveTabsPage == null
Michael Kolbe421c242010-10-04 19:29:01 -07002208 && mComboView == null
Grace Kloba5942df02009-09-18 11:48:29 -07002209 && event.isLongPress()) {
Michael Kolbe421c242010-10-04 19:29:01 -07002210 bookmarksOrHistoryPicker(true);
Grace Kloba5942df02009-09-18 11:48:29 -07002211 return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002212 }
Grace Kloba5942df02009-09-18 11:48:29 -07002213 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002214 }
Grace Kloba5942df02009-09-18 11:48:29 -07002215 return super.onKeyDown(keyCode, event);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002216 }
2217
Grace Kloba5942df02009-09-18 11:48:29 -07002218 @Override
2219 public boolean onKeyUp(int keyCode, KeyEvent event) {
2220 switch(keyCode) {
2221 case KeyEvent.KEYCODE_MENU:
2222 mMenuIsDown = false;
2223 break;
Grace Kloba5942df02009-09-18 11:48:29 -07002224 case KeyEvent.KEYCODE_BACK:
2225 if (event.isTracking() && !event.isCanceled()) {
2226 if (mCustomView != null) {
2227 // if a custom view is showing, hide it
Grace Kloba22ac16e2009-10-07 18:00:23 -07002228 mTabControl.getCurrentWebView().getWebChromeClient()
2229 .onHideCustomView();
Grace Kloba5942df02009-09-18 11:48:29 -07002230 } else if (mActiveTabsPage != null) {
2231 // if tab page is showing, hide it
2232 removeActiveTabPage(true);
Michael Kolbe421c242010-10-04 19:29:01 -07002233 } else if (mComboView != null) {
2234 removeComboView();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002235 } else {
Grace Kloba5942df02009-09-18 11:48:29 -07002236 WebView subwindow = mTabControl.getCurrentSubWindow();
2237 if (subwindow != null) {
2238 if (subwindow.canGoBack()) {
2239 subwindow.goBack();
2240 } else {
2241 dismissSubWindow(mTabControl.getCurrentTab());
2242 }
2243 } else {
2244 goBackOnePageOrQuit();
2245 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002246 }
Grace Kloba5942df02009-09-18 11:48:29 -07002247 return true;
2248 }
2249 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002250 }
Grace Kloba5942df02009-09-18 11:48:29 -07002251 return super.onKeyUp(keyCode, event);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002252 }
2253
Leon Scroggins68579392009-09-15 15:31:54 -04002254 /* package */ void stopLoading() {
Ben Murdochb7cc8b42009-09-28 10:59:09 +01002255 mDidStopLoad = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002256 resetTitleAndRevertLockIcon();
2257 WebView w = getTopWindow();
2258 w.stopLoading();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002259 // FIXME: before refactor, it is using mWebViewClient. So I keep the
2260 // same logic here. But for subwindow case, should we call into the main
2261 // WebView's onPageFinished as we never call its onPageStarted and if
2262 // the page finishes itself, we don't call onPageFinished.
2263 mTabControl.getCurrentWebView().getWebViewClient().onPageFinished(w,
2264 w.getUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08002265
2266 cancelStopToast();
2267 mStopToast = Toast
2268 .makeText(this, R.string.stopping, Toast.LENGTH_SHORT);
2269 mStopToast.show();
2270 }
2271
Grace Kloba22ac16e2009-10-07 18:00:23 -07002272 boolean didUserStopLoading() {
2273 return mDidStopLoad;
2274 }
2275
The Android Open Source Project0c908882009-03-03 19:32:16 -08002276 private void cancelStopToast() {
2277 if (mStopToast != null) {
2278 mStopToast.cancel();
2279 mStopToast = null;
2280 }
2281 }
2282
Grace Kloba22ac16e2009-10-07 18:00:23 -07002283 // called by a UI or non-UI thread to post the message
2284 public void postMessage(int what, int arg1, int arg2, Object obj,
2285 long delayMillis) {
2286 mHandler.sendMessageDelayed(mHandler.obtainMessage(what, arg1, arg2,
2287 obj), delayMillis);
2288 }
2289
2290 // called by a UI or non-UI thread to remove the message
2291 void removeMessages(int what, Object object) {
2292 mHandler.removeMessages(what, object);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002293 }
2294
2295 // public message ids
2296 public final static int LOAD_URL = 1001;
2297 public final static int STOP_LOAD = 1002;
2298
2299 // Message Ids
2300 private static final int FOCUS_NODE_HREF = 102;
Grace Kloba92c18a52009-07-31 23:48:32 -07002301 private static final int RELEASE_WAKELOCK = 107;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002302
Grace Kloba22ac16e2009-10-07 18:00:23 -07002303 static final int UPDATE_BOOKMARK_THUMBNAIL = 108;
Ben Murdoch2694e232009-09-29 09:41:11 +01002304
Ben Murdocheecb4e62010-07-06 16:30:38 +01002305 private static final int TOUCH_ICON_DOWNLOADED = 109;
2306
Michael Kolb300b7f02010-08-25 13:47:24 -07002307 private static final int OPEN_BOOKMARKS = 201;
2308
The Android Open Source Project0c908882009-03-03 19:32:16 -08002309 // Private handler for handling javascript and saving passwords
2310 private Handler mHandler = new Handler() {
2311
Michael Kolbe0a36662010-06-29 10:37:12 -07002312 @Override
The Android Open Source Project0c908882009-03-03 19:32:16 -08002313 public void handleMessage(Message msg) {
2314 switch (msg.what) {
Michael Kolb300b7f02010-08-25 13:47:24 -07002315 case OPEN_BOOKMARKS:
Michael Kolbe421c242010-10-04 19:29:01 -07002316 bookmarksOrHistoryPicker(false);
Michael Kolb300b7f02010-08-25 13:47:24 -07002317 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002318 case FOCUS_NODE_HREF:
Ben Murdoch2694e232009-09-29 09:41:11 +01002319 {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002320 String url = (String) msg.getData().get("url");
Ben Murdoch90d088c2009-11-17 18:14:04 +00002321 String title = (String) msg.getData().get("title");
The Android Open Source Project0c908882009-03-03 19:32:16 -08002322 if (url == null || url.length() == 0) {
2323 break;
2324 }
2325 HashMap focusNodeMap = (HashMap) msg.obj;
2326 WebView view = (WebView) focusNodeMap.get("webview");
2327 // Only apply the action if the top window did not change.
2328 if (getTopWindow() != view) {
2329 break;
2330 }
2331 switch (msg.arg1) {
2332 case R.id.open_context_menu_id:
2333 case R.id.view_image_context_menu_id:
Leon Scroggins92472e82010-02-17 16:32:28 -05002334 loadUrlFromContext(getTopWindow(), url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002335 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002336 case R.id.bookmark_context_menu_id:
2337 Intent intent = new Intent(BrowserActivity.this,
2338 AddBookmarkPage.class);
2339 intent.putExtra("url", url);
Ben Murdoch90d088c2009-11-17 18:14:04 +00002340 intent.putExtra("title", title);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002341 startActivity(intent);
2342 break;
2343 case R.id.share_link_context_menu_id:
Leon Scroggins3e204452010-05-10 11:06:03 -04002344 sharePage(BrowserActivity.this, title, url, null,
Leon Scroggins96afcb12009-12-10 12:35:56 -05002345 null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002346 break;
2347 case R.id.copy_link_context_menu_id:
2348 copy(url);
2349 break;
2350 case R.id.save_link_context_menu_id:
2351 case R.id.download_context_menu_id:
2352 onDownloadStartNoStream(url, null, null, null, -1);
2353 break;
2354 }
2355 break;
Ben Murdoch2694e232009-09-29 09:41:11 +01002356 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002357
2358 case LOAD_URL:
Leon Scroggins92472e82010-02-17 16:32:28 -05002359 loadUrlFromContext(getTopWindow(), (String) msg.obj);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002360 break;
2361
2362 case STOP_LOAD:
2363 stopLoading();
2364 break;
2365
The Android Open Source Project0c908882009-03-03 19:32:16 -08002366 case RELEASE_WAKELOCK:
2367 if (mWakeLock.isHeld()) {
2368 mWakeLock.release();
Grace Kloba5d0e02e2009-10-05 15:15:36 -07002369 // if we reach here, Browser should be still in the
2370 // background loading after WAKELOCK_TIMEOUT (5-min).
2371 // To avoid burning the battery, stop loading.
2372 mTabControl.stopAllLoading();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002373 }
2374 break;
Ben Murdoch2694e232009-09-29 09:41:11 +01002375
2376 case UPDATE_BOOKMARK_THUMBNAIL:
2377 WebView view = (WebView) msg.obj;
2378 if (view != null) {
2379 updateScreenshot(view);
2380 }
2381 break;
Ben Murdocheecb4e62010-07-06 16:30:38 +01002382
2383 case TOUCH_ICON_DOWNLOADED:
2384 Bundle b = msg.getData();
2385 showSaveToHomescreenDialog(b.getString("url"),
2386 b.getString("title"),
2387 (Bitmap) b.getParcelable("touchIcon"),
2388 (Bitmap) b.getParcelable("favicon"));
2389 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002390 }
2391 }
2392 };
2393
Leon Scroggins96afcb12009-12-10 12:35:56 -05002394 /**
2395 * Share a page, providing the title, url, favicon, and a screenshot. Uses
2396 * an {@link Intent} to launch the Activity chooser.
2397 * @param c Context used to launch a new Activity.
2398 * @param title Title of the page. Stored in the Intent with
Paul Westbrook03e6d392010-02-12 10:33:29 -08002399 * {@link Intent#EXTRA_SUBJECT}
Leon Scroggins96afcb12009-12-10 12:35:56 -05002400 * @param url URL of the page. Stored in the Intent with
2401 * {@link Intent#EXTRA_TEXT}
2402 * @param favicon Bitmap of the favicon for the page. Stored in the Intent
2403 * with {@link Browser#EXTRA_SHARE_FAVICON}
2404 * @param screenshot Bitmap of a screenshot of the page. Stored in the
2405 * Intent with {@link Browser#EXTRA_SHARE_SCREENSHOT}
2406 */
2407 public static final void sharePage(Context c, String title, String url,
2408 Bitmap favicon, Bitmap screenshot) {
2409 Intent send = new Intent(Intent.ACTION_SEND);
2410 send.setType("text/plain");
2411 send.putExtra(Intent.EXTRA_TEXT, url);
Paul Westbrook03e6d392010-02-12 10:33:29 -08002412 send.putExtra(Intent.EXTRA_SUBJECT, title);
Leon Scroggins96afcb12009-12-10 12:35:56 -05002413 send.putExtra(Browser.EXTRA_SHARE_FAVICON, favicon);
2414 send.putExtra(Browser.EXTRA_SHARE_SCREENSHOT, screenshot);
2415 try {
2416 c.startActivity(Intent.createChooser(send, c.getString(
2417 R.string.choosertitle_sharevia)));
2418 } catch(android.content.ActivityNotFoundException ex) {
2419 // if no app handles it, do nothing
2420 }
2421 }
2422
Leon Scroggins89c6d362009-07-15 16:54:37 -04002423 private void updateScreenshot(WebView view) {
2424 // If this is a bookmarked site, add a screenshot to the database.
2425 // FIXME: When should we update? Every time?
2426 // FIXME: Would like to make sure there is actually something to
2427 // draw, but the API for that (WebViewCore.pictureReady()) is not
2428 // currently accessible here.
Ben Murdochaac7aa62009-09-17 16:57:40 +01002429
Ben Murdoch87cc65d2010-06-29 20:34:10 +01002430 final Bitmap bm = createScreenshot(view, getDesiredThumbnailWidth(this),
2431 getDesiredThumbnailHeight(this));
Patrick Scottcb192b52010-04-14 14:38:55 -04002432 if (bm == null) {
2433 return;
Leon Scroggins89c6d362009-07-15 16:54:37 -04002434 }
Patrick Scottcb192b52010-04-14 14:38:55 -04002435
2436 final ContentResolver cr = getContentResolver();
2437 final String url = view.getUrl();
2438 final String originalUrl = view.getOriginalUrl();
2439
2440 new AsyncTask<Void, Void, Void>() {
2441 @Override
2442 protected Void doInBackground(Void... unused) {
Jeff Hamilton1a805652010-09-07 12:36:30 -07002443 Cursor cursor = null;
Patrick Scottcb192b52010-04-14 14:38:55 -04002444 try {
Jeff Hamilton1a805652010-09-07 12:36:30 -07002445 cursor = Bookmarks.queryCombinedForUrl(cr, originalUrl, url);
2446 if (cursor != null && cursor.moveToFirst()) {
2447 final ByteArrayOutputStream os = new ByteArrayOutputStream();
2448 bm.compress(Bitmap.CompressFormat.PNG, 100, os);
2449
2450 ContentValues values = new ContentValues();
2451 values.put(Images.THUMBNAIL, os.toByteArray());
2452 values.put(Images.URL, cursor.getString(0));
2453
2454 do {
2455 cr.update(Images.CONTENT_URI, values, null, null);
2456 } while (cursor.moveToNext());
Patrick Scottcb192b52010-04-14 14:38:55 -04002457 }
2458 } catch (IllegalStateException e) {
2459 // Ignore
2460 } finally {
Jeff Hamilton1a805652010-09-07 12:36:30 -07002461 if (cursor != null) cursor.close();
Patrick Scottcb192b52010-04-14 14:38:55 -04002462 }
2463 return null;
2464 }
2465 }.execute();
Leon Scroggins89c6d362009-07-15 16:54:37 -04002466 }
2467
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002468 /**
Leon Scrogginsf8551612009-09-24 16:06:02 -04002469 * Return the desired width for thumbnail screenshots, which are stored in
2470 * the database, and used on the bookmarks screen.
2471 * @param context Context for finding out the density of the screen.
Jeff Hamiltonf3026372010-08-19 00:12:27 -05002472 * @return desired width for thumbnail screenshot.
Leon Scrogginsf8551612009-09-24 16:06:02 -04002473 */
2474 /* package */ static int getDesiredThumbnailWidth(Context context) {
Jeff Hamiltonf3026372010-08-19 00:12:27 -05002475 return context.getResources().getDimensionPixelOffset(R.dimen.bookmarkThumbnailWidth);
Leon Scrogginsf8551612009-09-24 16:06:02 -04002476 }
2477
2478 /**
2479 * Return the desired height for thumbnail screenshots, which are stored in
2480 * the database, and used on the bookmarks screen.
2481 * @param context Context for finding out the density of the screen.
Jeff Hamiltonf3026372010-08-19 00:12:27 -05002482 * @return desired height for thumbnail screenshot.
Leon Scrogginsf8551612009-09-24 16:06:02 -04002483 */
2484 /* package */ static int getDesiredThumbnailHeight(Context context) {
Jeff Hamiltonf3026372010-08-19 00:12:27 -05002485 return context.getResources().getDimensionPixelOffset(R.dimen.bookmarkThumbnailHeight);
Leon Scrogginsf8551612009-09-24 16:06:02 -04002486 }
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002487
Ben Murdoch87cc65d2010-06-29 20:34:10 +01002488 private Bitmap createScreenshot(WebView view, int width, int height) {
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002489 Picture thumbnail = view.capturePicture();
Leon Scroggins45800572009-09-29 16:38:47 -04002490 if (thumbnail == null) {
2491 return null;
2492 }
Ben Murdoch87cc65d2010-06-29 20:34:10 +01002493 Bitmap bm = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002494 Canvas canvas = new Canvas(bm);
2495 // May need to tweak these values to determine what is the
2496 // best scale factor
Ben Murdoch2694e232009-09-29 09:41:11 +01002497 int thumbnailWidth = thumbnail.getWidth();
Ben Murdochae59c3f2009-10-20 18:30:28 +01002498 int thumbnailHeight = thumbnail.getHeight();
2499 float scaleFactorX = 1.0f;
2500 float scaleFactorY = 1.0f;
Ben Murdoch2694e232009-09-29 09:41:11 +01002501 if (thumbnailWidth > 0) {
Ben Murdoch87cc65d2010-06-29 20:34:10 +01002502 scaleFactorX = (float) width / (float)thumbnailWidth;
Ben Murdochae59c3f2009-10-20 18:30:28 +01002503 } else {
2504 return null;
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002505 }
Ben Murdochae59c3f2009-10-20 18:30:28 +01002506
2507 if (view.getWidth() > view.getHeight() &&
2508 thumbnailHeight < view.getHeight() && thumbnailHeight > 0) {
2509 // If the device is in landscape and the page is shorter
2510 // than the height of the view, stretch the thumbnail to fill the
2511 // space.
Ben Murdoch87cc65d2010-06-29 20:34:10 +01002512 scaleFactorY = (float) height / (float)thumbnailHeight;
Ben Murdochae59c3f2009-10-20 18:30:28 +01002513 } else {
2514 // In the portrait case, this looks nice.
2515 scaleFactorY = scaleFactorX;
2516 }
2517
2518 canvas.scale(scaleFactorX, scaleFactorY);
2519
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002520 thumbnail.draw(canvas);
2521 return bm;
2522 }
2523
The Android Open Source Project0c908882009-03-03 19:32:16 -08002524 // -------------------------------------------------------------------------
Grace Kloba22ac16e2009-10-07 18:00:23 -07002525 // Helper function for WebViewClient.
The Android Open Source Project0c908882009-03-03 19:32:16 -08002526 //-------------------------------------------------------------------------
2527
2528 // Use in overrideUrlLoading
2529 /* package */ final static String SCHEME_WTAI = "wtai://wp/";
2530 /* package */ final static String SCHEME_WTAI_MC = "wtai://wp/mc;";
2531 /* package */ final static String SCHEME_WTAI_SD = "wtai://wp/sd;";
2532 /* package */ final static String SCHEME_WTAI_AP = "wtai://wp/ap;";
2533
Leon Scroggins92472e82010-02-17 16:32:28 -05002534 // Keep this initial progress in sync with initialProgressValue (* 100)
2535 // in ProgressTracker.cpp
2536 private final static int INITIAL_PROGRESS = 10;
2537
Grace Kloba22ac16e2009-10-07 18:00:23 -07002538 void onPageStarted(WebView view, String url, Bitmap favicon) {
2539 // when BrowserActivity just starts, onPageStarted may be called before
2540 // onResume as it is triggered from onCreate. Call resumeWebViewTimers
2541 // to start the timer. As we won't switch tabs while an activity is in
2542 // pause state, we can ensure calling resume and pause in pair.
2543 if (mActivityInPause) resumeWebViewTimers();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002544
Grace Kloba22ac16e2009-10-07 18:00:23 -07002545 resetLockIcon(url);
2546 setUrlTitle(url, null);
2547 setFavicon(favicon);
Leon Scroggins8cf8f682009-11-04 11:13:50 -08002548 // Show some progress so that the user knows the page is beginning to
2549 // load
Leon Scroggins92472e82010-02-17 16:32:28 -05002550 onProgressChanged(view, INITIAL_PROGRESS);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002551 mDidStopLoad = false;
Grace Kloba22ac16e2009-10-07 18:00:23 -07002552 if (!mIsNetworkUp) createAndShowNetworkDialog();
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04002553 endActionMode();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002554 if (mSettings.isTracing()) {
2555 String host;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002556 try {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002557 WebAddress uri = new WebAddress(url);
2558 host = uri.mHost;
2559 } catch (android.net.ParseException ex) {
2560 host = "browser";
The Android Open Source Project0c908882009-03-03 19:32:16 -08002561 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002562 host = host.replace('.', '_');
2563 host += ".trace";
2564 mInTrace = true;
2565 Debug.startMethodTracing(host, 20 * 1024 * 1024);
2566 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002567
Grace Kloba22ac16e2009-10-07 18:00:23 -07002568 // Performance probe
2569 if (false) {
2570 mStart = SystemClock.uptimeMillis();
2571 mProcessStart = Process.getElapsedCpuTime();
2572 long[] sysCpu = new long[7];
2573 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2574 sysCpu, null)) {
2575 mUserStart = sysCpu[0] + sysCpu[1];
2576 mSystemStart = sysCpu[2];
2577 mIdleStart = sysCpu[3];
2578 mIrqStart = sysCpu[4] + sysCpu[5] + sysCpu[6];
2579 }
2580 mUiStart = SystemClock.currentThreadTimeMillis();
2581 }
2582 }
2583
2584 void onPageFinished(WebView view, String url) {
2585 // Reset the title and icon in case we stopped a provisional load.
2586 resetTitleAndIcon(view);
2587 // Update the lock icon image only once we are done loading
2588 updateLockIconToLatest();
2589 // pause the WebView timer and release the wake lock if it is finished
2590 // while BrowserActivity is in pause state.
2591 if (mActivityInPause && pauseWebViewTimers()) {
2592 if (mWakeLock.isHeld()) {
2593 mHandler.removeMessages(RELEASE_WAKELOCK);
2594 mWakeLock.release();
2595 }
2596 }
2597
2598 // Performance probe
2599 if (false) {
2600 long[] sysCpu = new long[7];
2601 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2602 sysCpu, null)) {
2603 String uiInfo = "UI thread used "
2604 + (SystemClock.currentThreadTimeMillis() - mUiStart)
2605 + " ms";
2606 if (LOGD_ENABLED) {
2607 Log.d(LOGTAG, uiInfo);
2608 }
2609 //The string that gets written to the log
2610 String performanceString = "It took total "
2611 + (SystemClock.uptimeMillis() - mStart)
2612 + " ms clock time to load the page."
2613 + "\nbrowser process used "
2614 + (Process.getElapsedCpuTime() - mProcessStart)
2615 + " ms, user processes used "
2616 + (sysCpu[0] + sysCpu[1] - mUserStart) * 10
2617 + " ms, kernel used "
2618 + (sysCpu[2] - mSystemStart) * 10
2619 + " ms, idle took " + (sysCpu[3] - mIdleStart) * 10
2620 + " ms and irq took "
2621 + (sysCpu[4] + sysCpu[5] + sysCpu[6] - mIrqStart)
2622 * 10 + " ms, " + uiInfo;
2623 if (LOGD_ENABLED) {
2624 Log.d(LOGTAG, performanceString + "\nWebpage: " + url);
2625 }
2626 if (url != null) {
2627 // strip the url to maintain consistency
2628 String newUrl = new String(url);
2629 if (newUrl.startsWith("http://www.")) {
2630 newUrl = newUrl.substring(11);
2631 } else if (newUrl.startsWith("http://")) {
2632 newUrl = newUrl.substring(7);
2633 } else if (newUrl.startsWith("https://www.")) {
2634 newUrl = newUrl.substring(12);
2635 } else if (newUrl.startsWith("https://")) {
2636 newUrl = newUrl.substring(8);
2637 }
2638 if (LOGD_ENABLED) {
2639 Log.d(LOGTAG, newUrl + " loaded");
2640 }
Grace Kloba5b078b52009-06-24 20:23:41 -07002641 }
2642 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002643 }
Grace Kloba5b078b52009-06-24 20:23:41 -07002644
Grace Kloba22ac16e2009-10-07 18:00:23 -07002645 if (mInTrace) {
2646 mInTrace = false;
2647 Debug.stopMethodTracing();
2648 }
2649 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002650
Grace Klobae7fe26b2010-06-28 16:23:33 -07002651 private void closeEmptyChildTab() {
2652 Tab current = mTabControl.getCurrentTab();
2653 if (current != null
2654 && current.getWebView().copyBackForwardList().getSize() == 0) {
2655 Tab parent = current.getParentTab();
2656 if (parent != null) {
2657 switchToTab(mTabControl.getTabIndex(parent));
2658 closeTab(current);
2659 }
2660 }
2661 }
2662
Grace Kloba22ac16e2009-10-07 18:00:23 -07002663 boolean shouldOverrideUrlLoading(WebView view, String url) {
Jeff Hamilton47654f42010-09-07 09:57:51 -05002664 if (view.isPrivateBrowsingEnabled()) {
2665 // Don't allow urls to leave the browser app when in private browsing mode
2666 loadUrl(view, url);
2667 return true;
2668 }
2669
Grace Kloba22ac16e2009-10-07 18:00:23 -07002670 if (url.startsWith(SCHEME_WTAI)) {
2671 // wtai://wp/mc;number
2672 // number=string(phone-number)
2673 if (url.startsWith(SCHEME_WTAI_MC)) {
2674 Intent intent = new Intent(Intent.ACTION_VIEW,
2675 Uri.parse(WebView.SCHEME_TEL +
2676 url.substring(SCHEME_WTAI_MC.length())));
2677 startActivity(intent);
Grace Klobae7fe26b2010-06-28 16:23:33 -07002678 // before leaving BrowserActivity, close the empty child tab.
2679 // If a new tab is created through JavaScript open to load this
2680 // url, we would like to close it as we will load this url in a
2681 // different Activity.
2682 closeEmptyChildTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002683 return true;
2684 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002685 // wtai://wp/sd;dtmf
2686 // dtmf=string(dialstring)
2687 if (url.startsWith(SCHEME_WTAI_SD)) {
2688 // TODO: only send when there is active voice connection
2689 return false;
2690 }
2691 // wtai://wp/ap;number;name
2692 // number=string(phone-number)
2693 // name=string
2694 if (url.startsWith(SCHEME_WTAI_AP)) {
2695 // TODO
2696 return false;
2697 }
2698 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002699
Grace Kloba22ac16e2009-10-07 18:00:23 -07002700 // The "about:" schemes are internal to the browser; don't want these to
2701 // be dispatched to other apps.
2702 if (url.startsWith("about:")) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002703 return false;
2704 }
2705
Jeff Davidson43610292010-07-16 16:03:58 -07002706 // If this is a Google search, attempt to add an RLZ string (if one isn't already present).
2707 if (rlzProviderPresent()) {
2708 Uri siteUri = Uri.parse(url);
2709 if (needsRlzString(siteUri)) {
2710 String rlz = null;
2711 Cursor cur = null;
2712 try {
2713 cur = getContentResolver().query(getRlzUri(), null, null, null, null);
2714 if (cur != null && cur.moveToFirst() && !cur.isNull(0)) {
2715 url = siteUri.buildUpon()
2716 .appendQueryParameter("rlz", cur.getString(0))
2717 .build().toString();
2718 }
2719 } finally {
2720 if (cur != null) {
2721 cur.close();
2722 }
2723 }
2724 loadUrl(view, url);
2725 return true;
2726 }
2727 }
2728
Grace Kloba22ac16e2009-10-07 18:00:23 -07002729 Intent intent;
2730 // perform generic parsing of the URI to turn it into an Intent.
2731 try {
2732 intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME);
2733 } catch (URISyntaxException ex) {
2734 Log.w("Browser", "Bad URI " + url + ": " + ex.getMessage());
2735 return false;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002736 }
2737
Grace Kloba22ac16e2009-10-07 18:00:23 -07002738 // check whether the intent can be resolved. If not, we will see
2739 // whether we can download it from the Market.
2740 if (getPackageManager().resolveActivity(intent, 0) == null) {
2741 String packagename = intent.getPackage();
2742 if (packagename != null) {
2743 intent = new Intent(Intent.ACTION_VIEW, Uri
2744 .parse("market://search?q=pname:" + packagename));
2745 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2746 startActivity(intent);
Grace Klobae7fe26b2010-06-28 16:23:33 -07002747 // before leaving BrowserActivity, close the empty child tab.
2748 // If a new tab is created through JavaScript open to load this
2749 // url, we would like to close it as we will load this url in a
2750 // different Activity.
2751 closeEmptyChildTab();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002752 return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002753 } else {
2754 return false;
2755 }
2756 }
2757
Grace Kloba22ac16e2009-10-07 18:00:23 -07002758 // sanitize the Intent, ensuring web pages can not bypass browser
2759 // security (only access to BROWSABLE activities).
2760 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2761 intent.setComponent(null);
2762 try {
2763 if (startActivityIfNeeded(intent, -1)) {
Grace Klobae7fe26b2010-06-28 16:23:33 -07002764 // before leaving BrowserActivity, close the empty child tab.
2765 // If a new tab is created through JavaScript open to load this
2766 // url, we would like to close it as we will load this url in a
2767 // different Activity.
2768 closeEmptyChildTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002769 return true;
2770 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002771 } catch (ActivityNotFoundException ex) {
2772 // ignore the error. If no application can handle the URL,
2773 // eg about:blank, assume the browser can handle it.
2774 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002775
Grace Kloba22ac16e2009-10-07 18:00:23 -07002776 if (mMenuIsDown) {
Michael Kolb68792c82010-08-09 16:39:18 -07002777 openTab(url, false);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002778 closeOptionsMenu();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002779 return true;
2780 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002781 return false;
2782 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002783
Jeff Davidson43610292010-07-16 16:03:58 -07002784 // Determine whether the RLZ provider is present on the system.
2785 private boolean rlzProviderPresent() {
2786 if (mIsProviderPresent == null) {
2787 PackageManager pm = getPackageManager();
2788 mIsProviderPresent = pm.resolveContentProvider(BrowserSettings.RLZ_PROVIDER, 0) != null;
2789 }
2790 return mIsProviderPresent;
2791 }
2792
2793 // Retrieve the RLZ access point string and cache the URI used to retrieve RLZ values.
2794 private Uri getRlzUri() {
2795 if (mRlzUri == null) {
2796 String ap = getResources().getString(R.string.rlz_access_point);
2797 mRlzUri = Uri.withAppendedPath(BrowserSettings.RLZ_PROVIDER_URI, ap);
2798 }
2799 return mRlzUri;
2800 }
2801
2802 // Determine if this URI appears to be for a Google search and does not have an RLZ parameter.
2803 // Taken largely from Chrome source, src/chrome/browser/google_url_tracker.cc
2804 private static boolean needsRlzString(Uri uri) {
Bill Napierc50e71a2010-08-27 14:03:03 -07002805 String scheme = uri.getScheme();
2806 if (("http".equals(scheme) || "https".equals(scheme)) &&
2807 (uri.getQueryParameter("q") != null) && (uri.getQueryParameter("rlz") == null)) {
Jeff Davidson43610292010-07-16 16:03:58 -07002808 String host = uri.getHost();
2809 if (host == null) {
2810 return false;
2811 }
2812 String[] hostComponents = host.split("\\.");
2813
2814 if (hostComponents.length < 2) {
2815 return false;
2816 }
2817 int googleComponent = hostComponents.length - 2;
2818 String component = hostComponents[googleComponent];
2819 if (!"google".equals(component)) {
2820 if (hostComponents.length < 3 ||
2821 (!"co".equals(component) && !"com".equals(component))) {
2822 return false;
2823 }
2824 googleComponent = hostComponents.length - 3;
2825 if (!"google".equals(hostComponents[googleComponent])) {
2826 return false;
2827 }
2828 }
2829
2830 // Google corp network handling.
2831 if (googleComponent > 0 && "corp".equals(hostComponents[googleComponent - 1])) {
2832 return false;
2833 }
2834
2835 return true;
2836 }
2837 return false;
2838 }
2839
Grace Kloba22ac16e2009-10-07 18:00:23 -07002840 // -------------------------------------------------------------------------
2841 // Helper function for WebChromeClient
2842 // -------------------------------------------------------------------------
The Android Open Source Project0c908882009-03-03 19:32:16 -08002843
Grace Kloba22ac16e2009-10-07 18:00:23 -07002844 void onProgressChanged(WebView view, int newProgress) {
Michael Kolba2b2ba82010-08-04 17:54:03 -07002845
2846 // On the phone, the fake title bar will always cover up the
2847 // regular title bar (or the regular one is offscreen), so only the
2848 // fake title bar needs to change its progress
2849 mFakeTitleBar.setProgress(newProgress);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002850
Grace Kloba22ac16e2009-10-07 18:00:23 -07002851 if (newProgress == 100) {
2852 // onProgressChanged() may continue to be called after the main
2853 // frame has finished loading, as any remaining sub frames continue
2854 // to load. We'll only get called once though with newProgress as
2855 // 100 when everything is loaded. (onPageFinished is called once
2856 // when the main frame completes loading regardless of the state of
2857 // any sub frames so calls to onProgressChanges may continue after
2858 // onPageFinished has executed)
2859 if (mInLoad) {
2860 mInLoad = false;
Leon Scrogginsa27ff192009-09-14 12:58:04 -04002861 updateInLoadMenuItems();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002862 // If the options menu is open, leave the title bar
2863 if (!mOptionsMenuOpen || !mIconView) {
2864 hideFakeTitleBar();
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07002865 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002866 }
Leon Scrogginsaa37e7f2010-03-05 11:51:20 -05002867 } else {
2868 if (!mInLoad) {
2869 // onPageFinished may have already been called but a subframe is
2870 // still loading and updating the progress. Reset mInLoad and
2871 // update the menu items.
2872 mInLoad = true;
2873 updateInLoadMenuItems();
2874 }
2875 // When the page first begins to load, the Activity may still be
2876 // paused, in which case showFakeTitleBar will do nothing. Call
2877 // again as the page continues to load so that it will be shown.
2878 // (Calling it will the fake title bar is already showing will also
2879 // do nothing.
Grace Kloba22ac16e2009-10-07 18:00:23 -07002880 if (!mOptionsMenuOpen || mIconView) {
2881 // This page has begun to load, so show the title bar
2882 showFakeTitleBar();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002883 }
2884 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002885 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002886
Grace Kloba22ac16e2009-10-07 18:00:23 -07002887 void onShowCustomView(View view, WebChromeClient.CustomViewCallback callback) {
Derek Sollenberger8ff57db2009-12-08 15:39:55 -05002888 // if a view already exists then immediately terminate the new one
2889 if (mCustomView != null) {
2890 callback.onCustomViewHidden();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002891 return;
Derek Sollenberger8ff57db2009-12-08 15:39:55 -05002892 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002893
2894 // Add the custom view to its container.
2895 mCustomViewContainer.addView(view, COVER_SCREEN_GRAVITY_CENTER);
2896 mCustomView = view;
2897 mCustomViewCallback = callback;
2898 // Save the menu state and set it to empty while the custom
2899 // view is showing.
2900 mOldMenuState = mMenuState;
2901 mMenuState = EMPTY_MENU;
2902 // Hide the content view.
2903 mContentView.setVisibility(View.GONE);
2904 // Finally show the custom view container.
Andrei Popescu163ab742009-10-20 17:58:23 +01002905 setStatusBarVisibility(false);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002906 mCustomViewContainer.setVisibility(View.VISIBLE);
2907 mCustomViewContainer.bringToFront();
2908 }
2909
2910 void onHideCustomView() {
2911 if (mCustomView == null)
2912 return;
2913
2914 // Hide the custom view.
2915 mCustomView.setVisibility(View.GONE);
2916 // Remove the custom view from its container.
2917 mCustomViewContainer.removeView(mCustomView);
2918 mCustomView = null;
2919 // Reset the old menu state.
2920 mMenuState = mOldMenuState;
2921 mOldMenuState = EMPTY_MENU;
2922 mCustomViewContainer.setVisibility(View.GONE);
2923 mCustomViewCallback.onCustomViewHidden();
2924 // Show the content view.
Andrei Popescu163ab742009-10-20 17:58:23 +01002925 setStatusBarVisibility(true);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002926 mContentView.setVisibility(View.VISIBLE);
2927 }
2928
2929 Bitmap getDefaultVideoPoster() {
2930 if (mDefaultVideoPoster == null) {
2931 mDefaultVideoPoster = BitmapFactory.decodeResource(
2932 getResources(), R.drawable.default_video_poster);
Patrick Scott3918d442009-08-04 13:22:29 -04002933 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002934 return mDefaultVideoPoster;
2935 }
Patrick Scott3918d442009-08-04 13:22:29 -04002936
Grace Kloba22ac16e2009-10-07 18:00:23 -07002937 View getVideoLoadingProgressView() {
2938 if (mVideoProgressView == null) {
2939 LayoutInflater inflater = LayoutInflater.from(BrowserActivity.this);
2940 mVideoProgressView = inflater.inflate(
2941 R.layout.video_loading_progress, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002942 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002943 return mVideoProgressView;
2944 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002945
Leon Scroggins8d5fa432009-10-02 15:55:59 -04002946 /*
2947 * The Object used to inform the WebView of the file to upload.
2948 */
2949 private ValueCallback<Uri> mUploadMessage;
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002950 private String mCameraFilePath;
Leon Scroggins8d5fa432009-10-02 15:55:59 -04002951
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002952 void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
2953
2954 final String imageMimeType = "image/*";
Ben Murdoch6af492a2010-06-15 12:38:17 +01002955 final String videoMimeType = "video/*";
Ben Murdoch039bd472010-07-21 21:26:57 +01002956 final String audioMimeType = "audio/*";
Ben Murdochb50d7402010-07-16 12:42:22 +01002957 final String mediaSourceKey = "capture";
Ben Murdoch6af492a2010-06-15 12:38:17 +01002958 final String mediaSourceValueCamera = "camera";
Ben Murdochb50d7402010-07-16 12:42:22 +01002959 final String mediaSourceValueFileSystem = "filesystem";
Ben Murdoch6af492a2010-06-15 12:38:17 +01002960 final String mediaSourceValueCamcorder = "camcorder";
Ben Murdoch039bd472010-07-21 21:26:57 +01002961 final String mediaSourceValueMicrophone = "microphone";
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002962
Ben Murdoch039bd472010-07-21 21:26:57 +01002963 // media source can be 'filesystem' or 'camera' or 'camcorder' or 'microphone'.
Ben Murdoch6af492a2010-06-15 12:38:17 +01002964 String mediaSource = "";
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002965
Ben Murdoch6af492a2010-06-15 12:38:17 +01002966 // We add the camera intent if there was no accept type (or '*/*' or 'image/*').
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002967 boolean addCameraIntent = true;
Ben Murdoch6af492a2010-06-15 12:38:17 +01002968 // We add the camcorder intent if there was no accept type (or '*/*' or 'video/*').
2969 boolean addCamcorderIntent = true;
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002970
Ben Murdoch6af492a2010-06-15 12:38:17 +01002971 if (mUploadMessage != null) {
2972 // Already a file picker operation in progress.
2973 return;
2974 }
2975
Grace Kloba22ac16e2009-10-07 18:00:23 -07002976 mUploadMessage = uploadMsg;
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002977
2978 // Parse the accept type.
2979 String params[] = acceptType.split(";");
2980 String mimeType = params[0];
2981
2982 for (String p : params) {
2983 String[] keyValue = p.split("=");
2984 if (keyValue.length == 2) {
2985 // Process key=value parameters.
Ben Murdoch6af492a2010-06-15 12:38:17 +01002986 if (mediaSourceKey.equals(keyValue[0])) {
2987 mediaSource = keyValue[1];
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002988 }
2989 }
2990 }
2991
2992 // This intent will display the standard OPENABLE file picker.
Grace Kloba22ac16e2009-10-07 18:00:23 -07002993 Intent i = new Intent(Intent.ACTION_GET_CONTENT);
2994 i.addCategory(Intent.CATEGORY_OPENABLE);
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002995
2996 // Create an intent to add to the standard file picker that will
2997 // capture an image from the camera. We'll combine this intent with
2998 // the standard OPENABLE picker unless the web developer specifically
2999 // requested the camera or gallery be opened by passing a parameter
3000 // in the accept type.
3001 Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
3002 File externalDataDir = Environment.getExternalStoragePublicDirectory(
3003 Environment.DIRECTORY_DCIM);
3004 File cameraDataDir = new File(externalDataDir.getAbsolutePath() +
3005 File.separator + "browser-photos");
3006 cameraDataDir.mkdirs();
3007 mCameraFilePath = cameraDataDir.getAbsolutePath() + File.separator +
3008 System.currentTimeMillis() + ".jpg";
3009 cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(mCameraFilePath)));
3010
Ben Murdoch6af492a2010-06-15 12:38:17 +01003011 Intent camcorderIntent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
3012
Ben Murdoch039bd472010-07-21 21:26:57 +01003013 Intent soundRecIntent = new Intent(MediaStore.Audio.Media.RECORD_SOUND_ACTION);
3014
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003015 if (mimeType.equals(imageMimeType)) {
3016 i.setType(imageMimeType);
Ben Murdoch6af492a2010-06-15 12:38:17 +01003017 addCamcorderIntent = false;
3018 if (mediaSource.equals(mediaSourceValueCamera)) {
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003019 // Specified 'image/*' and requested the camera, so go ahead and launch the camera
3020 // directly.
3021 BrowserActivity.this.startActivityForResult(cameraIntent, FILE_SELECTED);
3022 return;
Ben Murdochb50d7402010-07-16 12:42:22 +01003023 } else if (mediaSource.equals(mediaSourceValueFileSystem)) {
3024 // Specified filesytem as the source, so don't want to consider the camera.
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003025 addCameraIntent = false;
3026 }
Ben Murdoch6af492a2010-06-15 12:38:17 +01003027 } else if (mimeType.equals(videoMimeType)) {
3028 i.setType(videoMimeType);
3029 addCameraIntent = false;
3030 // The camcorder saves it's own file and returns it to us in the intent, so
3031 // we don't need to generate one here.
3032 mCameraFilePath = null;
3033
3034 if (mediaSource.equals(mediaSourceValueCamcorder)) {
Ben Murdoch039bd472010-07-21 21:26:57 +01003035 // Specified 'video/*' and requested the camcorder, so go ahead and launch the
3036 // camcorder directly.
Ben Murdoch6af492a2010-06-15 12:38:17 +01003037 BrowserActivity.this.startActivityForResult(camcorderIntent, FILE_SELECTED);
3038 return;
Ben Murdochb50d7402010-07-16 12:42:22 +01003039 } else if (mediaSource.equals(mediaSourceValueFileSystem)) {
3040 // Specified filesystem as the source, so don't want to consider the camcorder.
Ben Murdoch6af492a2010-06-15 12:38:17 +01003041 addCamcorderIntent = false;
3042 }
Ben Murdoch039bd472010-07-21 21:26:57 +01003043 } else if (mimeType.equals(audioMimeType)) {
3044 i.setType(audioMimeType);
3045 addCameraIntent = false;
3046 addCamcorderIntent = false;
3047 if (mediaSource.equals(mediaSourceValueMicrophone)) {
3048 // Specified 'audio/*' and requested microphone, so go ahead and launch the sound
3049 // recorder.
3050 BrowserActivity.this.startActivityForResult(soundRecIntent, FILE_SELECTED);
3051 return;
3052 }
3053 // On a default system, there is no single option to open an audio "gallery". Both the
3054 // sound recorder and music browser respond to the OPENABLE/audio/* intent unlike the
3055 // image/* and video/* OPENABLE intents where the image / video gallery are the only
3056 // respondants (and so the user is not prompted by default).
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003057 } else {
3058 i.setType("*/*");
3059 }
3060
Ben Murdoch6af492a2010-06-15 12:38:17 +01003061 // Combine the chooser and the extra choices (like camera or camcorder)
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003062 Intent chooser = new Intent(Intent.ACTION_CHOOSER);
3063 chooser.putExtra(Intent.EXTRA_INTENT, i);
3064
Ben Murdoch6af492a2010-06-15 12:38:17 +01003065 Vector<Intent> extraInitialIntents = new Vector<Intent>(0);
3066
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003067 if (addCameraIntent) {
Ben Murdoch6af492a2010-06-15 12:38:17 +01003068 extraInitialIntents.add(cameraIntent);
3069 }
3070
3071 if (addCamcorderIntent) {
3072 extraInitialIntents.add(camcorderIntent);
3073 }
3074
3075 if (extraInitialIntents.size() > 0) {
3076 Intent[] extraIntents = new Intent[extraInitialIntents.size()];
3077 chooser.putExtra(Intent.EXTRA_INITIAL_INTENTS, extraInitialIntents.toArray(extraIntents));
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003078 }
3079
3080 chooser.putExtra(Intent.EXTRA_TITLE, getString(R.string.choose_upload));
3081 BrowserActivity.this.startActivityForResult(chooser, FILE_SELECTED);
Grace Kloba22ac16e2009-10-07 18:00:23 -07003082 }
3083
3084 // -------------------------------------------------------------------------
3085 // Implement functions for DownloadListener
3086 // -------------------------------------------------------------------------
3087
The Android Open Source Project0c908882009-03-03 19:32:16 -08003088 /**
3089 * Notify the host application a download should be done, or that
3090 * the data should be streamed if a streaming viewer is available.
3091 * @param url The full url to the content that should be downloaded
3092 * @param contentDisposition Content-disposition http header, if
3093 * present.
3094 * @param mimetype The mimetype of the content reported by the server
3095 * @param contentLength The file size reported by the server
3096 */
3097 public void onDownloadStart(String url, String userAgent,
3098 String contentDisposition, String mimetype, long contentLength) {
3099 // if we're dealing wih A/V content that's not explicitly marked
3100 // for download, check if it's streamable.
3101 if (contentDisposition == null
Patrick Scotte1fb9662009-08-31 14:31:52 -04003102 || !contentDisposition.regionMatches(
3103 true, 0, "attachment", 0, 10)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003104 // query the package manager to see if there's a registered handler
3105 // that matches.
3106 Intent intent = new Intent(Intent.ACTION_VIEW);
3107 intent.setDataAndType(Uri.parse(url), mimetype);
Patrick Scotte1fb9662009-08-31 14:31:52 -04003108 ResolveInfo info = getPackageManager().resolveActivity(intent,
3109 PackageManager.MATCH_DEFAULT_ONLY);
3110 if (info != null) {
3111 ComponentName myName = getComponentName();
3112 // If we resolved to ourselves, we don't want to attempt to
3113 // load the url only to try and download it again.
3114 if (!myName.getPackageName().equals(
3115 info.activityInfo.packageName)
3116 || !myName.getClassName().equals(
3117 info.activityInfo.name)) {
3118 // someone (other than us) knows how to handle this mime
3119 // type with this scheme, don't download.
3120 try {
3121 startActivity(intent);
3122 return;
3123 } catch (ActivityNotFoundException ex) {
3124 if (LOGD_ENABLED) {
3125 Log.d(LOGTAG, "activity not found for " + mimetype
3126 + " over " + Uri.parse(url).getScheme(),
3127 ex);
3128 }
3129 // Best behavior is to fall back to a download in this
3130 // case
The Android Open Source Project0c908882009-03-03 19:32:16 -08003131 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003132 }
3133 }
3134 }
3135 onDownloadStartNoStream(url, userAgent, contentDisposition, mimetype, contentLength);
3136 }
3137
Kristian Monsenfa52d172010-03-25 18:29:21 +00003138 // This is to work around the fact that java.net.URI throws Exceptions
3139 // instead of just encoding URL's properly
3140 // Helper method for onDownloadStartNoStream
3141 private static String encodePath(String path) {
3142 char[] chars = path.toCharArray();
3143
3144 boolean needed = false;
3145 for (char c : chars) {
3146 if (c == '[' || c == ']') {
3147 needed = true;
3148 break;
3149 }
3150 }
3151 if (needed == false) {
3152 return path;
3153 }
3154
3155 StringBuilder sb = new StringBuilder("");
3156 for (char c : chars) {
3157 if (c == '[' || c == ']') {
3158 sb.append('%');
3159 sb.append(Integer.toHexString(c));
3160 } else {
3161 sb.append(c);
3162 }
3163 }
3164
3165 return sb.toString();
3166 }
3167
The Android Open Source Project0c908882009-03-03 19:32:16 -08003168 /**
3169 * Notify the host application a download should be done, even if there
3170 * is a streaming viewer available for thise type.
3171 * @param url The full url to the content that should be downloaded
3172 * @param contentDisposition Content-disposition http header, if
3173 * present.
3174 * @param mimetype The mimetype of the content reported by the server
3175 * @param contentLength The file size reported by the server
3176 */
3177 /*package */ void onDownloadStartNoStream(String url, String userAgent,
3178 String contentDisposition, String mimetype, long contentLength) {
3179
3180 String filename = URLUtil.guessFileName(url,
3181 contentDisposition, mimetype);
3182
3183 // Check to see if we have an SDCard
3184 String status = Environment.getExternalStorageState();
3185 if (!status.equals(Environment.MEDIA_MOUNTED)) {
3186 int title;
3187 String msg;
3188
3189 // Check to see if the SDCard is busy, same as the music app
3190 if (status.equals(Environment.MEDIA_SHARED)) {
3191 msg = getString(R.string.download_sdcard_busy_dlg_msg);
3192 title = R.string.download_sdcard_busy_dlg_title;
3193 } else {
3194 msg = getString(R.string.download_no_sdcard_dlg_msg, filename);
3195 title = R.string.download_no_sdcard_dlg_title;
3196 }
3197
3198 new AlertDialog.Builder(this)
3199 .setTitle(title)
3200 .setIcon(android.R.drawable.ic_dialog_alert)
3201 .setMessage(msg)
3202 .setPositiveButton(R.string.ok, null)
3203 .show();
3204 return;
3205 }
3206
Kristian Monsenfa52d172010-03-25 18:29:21 +00003207 // java.net.URI is a lot stricter than KURL so we have to encode some
3208 // extra characters. Fix for b 2538060 and b 1634719
3209 WebAddress webAddress;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003210 try {
Kristian Monsenfa52d172010-03-25 18:29:21 +00003211 webAddress = new WebAddress(url);
3212 webAddress.mPath = encodePath(webAddress.mPath);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003213 } catch (Exception e) {
Kristian Monsenfa52d172010-03-25 18:29:21 +00003214 // This only happens for very bad urls, we want to chatch the
3215 // exception here
3216 Log.e(LOGTAG, "Exception trying to parse url:" + url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003217 return;
3218 }
3219
3220 // XXX: Have to use the old url since the cookies were stored using the
3221 // old percent-encoded url.
3222 String cookies = CookieManager.getInstance().getCookie(url);
3223
3224 ContentValues values = new ContentValues();
Kristian Monsenfa52d172010-03-25 18:29:21 +00003225 values.put(Downloads.Impl.COLUMN_URI, webAddress.toString());
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08003226 values.put(Downloads.Impl.COLUMN_COOKIE_DATA, cookies);
3227 values.put(Downloads.Impl.COLUMN_USER_AGENT, userAgent);
3228 values.put(Downloads.Impl.COLUMN_NOTIFICATION_PACKAGE,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003229 getPackageName());
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08003230 values.put(Downloads.Impl.COLUMN_NOTIFICATION_CLASS,
Leon Scrogginsa563d092010-04-19 16:53:49 -04003231 OpenDownloadReceiver.class.getCanonicalName());
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08003232 values.put(Downloads.Impl.COLUMN_VISIBILITY,
3233 Downloads.Impl.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
3234 values.put(Downloads.Impl.COLUMN_MIME_TYPE, mimetype);
3235 values.put(Downloads.Impl.COLUMN_FILE_NAME_HINT, filename);
Kristian Monsenfa52d172010-03-25 18:29:21 +00003236 values.put(Downloads.Impl.COLUMN_DESCRIPTION, webAddress.mHost);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003237 if (contentLength > 0) {
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08003238 values.put(Downloads.Impl.COLUMN_TOTAL_BYTES, contentLength);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003239 }
3240 if (mimetype == null) {
3241 // We must have long pressed on a link or image to download it. We
3242 // are not sure of the mimetype in this case, so do a head request
3243 new FetchUrlMimeType(this).execute(values);
3244 } else {
3245 final Uri contentUri =
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08003246 getContentResolver().insert(Downloads.Impl.CONTENT_URI, values);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003247 }
Leon Scroggins9191a7f2010-03-18 14:44:44 -04003248 Toast.makeText(this, R.string.download_pending, Toast.LENGTH_SHORT)
3249 .show();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003250 }
3251
Grace Kloba22ac16e2009-10-07 18:00:23 -07003252 // -------------------------------------------------------------------------
3253
The Android Open Source Project0c908882009-03-03 19:32:16 -08003254 /**
3255 * Resets the lock icon. This method is called when we start a new load and
3256 * know the url to be loaded.
3257 */
3258 private void resetLockIcon(String url) {
3259 // Save the lock-icon state (we revert to it if the load gets cancelled)
Grace Kloba22ac16e2009-10-07 18:00:23 -07003260 mTabControl.getCurrentTab().resetLockIcon(url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003261 updateLockIconImage(LOCK_ICON_UNSECURE);
3262 }
3263
The Android Open Source Project0c908882009-03-03 19:32:16 -08003264 /**
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04003265 * Update the lock icon to correspond to our latest state.
3266 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003267 private void updateLockIconToLatest() {
Leon Scroggins91f65fc2010-06-29 13:52:39 -04003268 Tab t = mTabControl.getCurrentTab();
3269 if (t != null) {
3270 updateLockIconImage(t.getLockIconType());
3271 }
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04003272 }
3273
3274 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08003275 * Updates the lock-icon image in the title-bar.
3276 */
3277 private void updateLockIconImage(int lockIconType) {
3278 Drawable d = null;
3279 if (lockIconType == LOCK_ICON_SECURE) {
3280 d = mSecLockIcon;
3281 } else if (lockIconType == LOCK_ICON_MIXED) {
3282 d = mMixLockIcon;
3283 }
Leon Scroggins68579392009-09-15 15:31:54 -04003284 mTitleBar.setLock(d);
Michael Kolba2b2ba82010-08-04 17:54:03 -07003285 mFakeTitleBar.setLock(d);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003286 }
3287
3288 /**
3289 * Displays a page-info dialog.
3290 * @param tab The tab to show info about
3291 * @param fromShowSSLCertificateOnError The flag that indicates whether
3292 * this dialog was opened from the SSL-certificate-on-error dialog or
3293 * not. This is important, since we need to know whether to return to
3294 * the parent dialog or simply dismiss.
3295 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003296 private void showPageInfo(final Tab tab,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003297 final boolean fromShowSSLCertificateOnError) {
3298 final LayoutInflater factory = LayoutInflater
3299 .from(this);
3300
3301 final View pageInfoView = factory.inflate(R.layout.page_info, null);
3302
3303 final WebView view = tab.getWebView();
3304
3305 String url = null;
3306 String title = null;
3307
3308 if (view == null) {
3309 url = tab.getUrl();
3310 title = tab.getTitle();
3311 } else if (view == mTabControl.getCurrentWebView()) {
3312 // Use the cached title and url if this is the current WebView
3313 url = mUrl;
3314 title = mTitle;
3315 } else {
3316 url = view.getUrl();
3317 title = view.getTitle();
3318 }
3319
3320 if (url == null) {
3321 url = "";
3322 }
3323 if (title == null) {
3324 title = "";
3325 }
3326
3327 ((TextView) pageInfoView.findViewById(R.id.address)).setText(url);
3328 ((TextView) pageInfoView.findViewById(R.id.title)).setText(title);
3329
3330 mPageInfoView = tab;
Leon Scrogginsc7b92f82010-01-11 18:17:31 -05003331 mPageInfoFromShowSSLCertificateOnError = fromShowSSLCertificateOnError;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003332
3333 AlertDialog.Builder alertDialogBuilder =
3334 new AlertDialog.Builder(this)
3335 .setTitle(R.string.page_info).setIcon(android.R.drawable.ic_dialog_info)
3336 .setView(pageInfoView)
3337 .setPositiveButton(
3338 R.string.ok,
3339 new DialogInterface.OnClickListener() {
3340 public void onClick(DialogInterface dialog,
3341 int whichButton) {
3342 mPageInfoDialog = null;
3343 mPageInfoView = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003344
3345 // if we came here from the SSL error dialog
3346 if (fromShowSSLCertificateOnError) {
3347 // go back to the SSL error dialog
3348 showSSLCertificateOnError(
3349 mSSLCertificateOnErrorView,
3350 mSSLCertificateOnErrorHandler,
3351 mSSLCertificateOnErrorError);
3352 }
3353 }
3354 })
3355 .setOnCancelListener(
3356 new DialogInterface.OnCancelListener() {
3357 public void onCancel(DialogInterface dialog) {
3358 mPageInfoDialog = null;
3359 mPageInfoView = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003360
3361 // if we came here from the SSL error dialog
3362 if (fromShowSSLCertificateOnError) {
3363 // go back to the SSL error dialog
3364 showSSLCertificateOnError(
3365 mSSLCertificateOnErrorView,
3366 mSSLCertificateOnErrorHandler,
3367 mSSLCertificateOnErrorError);
3368 }
3369 }
3370 });
3371
3372 // if we have a main top-level page SSL certificate set or a certificate
3373 // error
3374 if (fromShowSSLCertificateOnError ||
3375 (view != null && view.getCertificate() != null)) {
3376 // add a 'View Certificate' button
3377 alertDialogBuilder.setNeutralButton(
3378 R.string.view_certificate,
3379 new DialogInterface.OnClickListener() {
3380 public void onClick(DialogInterface dialog,
3381 int whichButton) {
3382 mPageInfoDialog = null;
3383 mPageInfoView = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003384
3385 // if we came here from the SSL error dialog
3386 if (fromShowSSLCertificateOnError) {
3387 // go back to the SSL error dialog
3388 showSSLCertificateOnError(
3389 mSSLCertificateOnErrorView,
3390 mSSLCertificateOnErrorHandler,
3391 mSSLCertificateOnErrorError);
3392 } else {
3393 // otherwise, display the top-most certificate from
3394 // the chain
3395 if (view.getCertificate() != null) {
3396 showSSLCertificate(tab);
3397 }
3398 }
3399 }
3400 });
3401 }
3402
3403 mPageInfoDialog = alertDialogBuilder.show();
3404 }
3405
3406 /**
3407 * Displays the main top-level page SSL certificate dialog
3408 * (accessible from the Page-Info dialog).
3409 * @param tab The tab to show certificate for.
3410 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003411 private void showSSLCertificate(final Tab tab) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003412 final View certificateView =
3413 inflateCertificateView(tab.getWebView().getCertificate());
3414 if (certificateView == null) {
3415 return;
3416 }
3417
3418 LayoutInflater factory = LayoutInflater.from(this);
3419
3420 final LinearLayout placeholder =
3421 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3422
3423 LinearLayout ll = (LinearLayout) factory.inflate(
3424 R.layout.ssl_success, placeholder);
3425 ((TextView)ll.findViewById(R.id.success))
3426 .setText(R.string.ssl_certificate_is_valid);
3427
3428 mSSLCertificateView = tab;
3429 mSSLCertificateDialog =
3430 new AlertDialog.Builder(this)
3431 .setTitle(R.string.ssl_certificate).setIcon(
3432 R.drawable.ic_dialog_browser_certificate_secure)
3433 .setView(certificateView)
3434 .setPositiveButton(R.string.ok,
3435 new DialogInterface.OnClickListener() {
3436 public void onClick(DialogInterface dialog,
3437 int whichButton) {
3438 mSSLCertificateDialog = null;
3439 mSSLCertificateView = null;
3440
3441 showPageInfo(tab, false);
3442 }
3443 })
3444 .setOnCancelListener(
3445 new DialogInterface.OnCancelListener() {
3446 public void onCancel(DialogInterface dialog) {
3447 mSSLCertificateDialog = null;
3448 mSSLCertificateView = null;
3449
3450 showPageInfo(tab, false);
3451 }
3452 })
3453 .show();
3454 }
3455
3456 /**
3457 * Displays the SSL error certificate dialog.
3458 * @param view The target web-view.
3459 * @param handler The SSL error handler responsible for cancelling the
3460 * connection that resulted in an SSL error or proceeding per user request.
3461 * @param error The SSL error object.
3462 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003463 void showSSLCertificateOnError(
The Android Open Source Project0c908882009-03-03 19:32:16 -08003464 final WebView view, final SslErrorHandler handler, final SslError error) {
3465
3466 final View certificateView =
3467 inflateCertificateView(error.getCertificate());
3468 if (certificateView == null) {
3469 return;
3470 }
3471
3472 LayoutInflater factory = LayoutInflater.from(this);
3473
3474 final LinearLayout placeholder =
3475 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3476
3477 if (error.hasError(SslError.SSL_UNTRUSTED)) {
3478 LinearLayout ll = (LinearLayout)factory
3479 .inflate(R.layout.ssl_warning, placeholder);
3480 ((TextView)ll.findViewById(R.id.warning))
3481 .setText(R.string.ssl_untrusted);
3482 }
3483
3484 if (error.hasError(SslError.SSL_IDMISMATCH)) {
3485 LinearLayout ll = (LinearLayout)factory
3486 .inflate(R.layout.ssl_warning, placeholder);
3487 ((TextView)ll.findViewById(R.id.warning))
3488 .setText(R.string.ssl_mismatch);
3489 }
3490
3491 if (error.hasError(SslError.SSL_EXPIRED)) {
3492 LinearLayout ll = (LinearLayout)factory
3493 .inflate(R.layout.ssl_warning, placeholder);
3494 ((TextView)ll.findViewById(R.id.warning))
3495 .setText(R.string.ssl_expired);
3496 }
3497
3498 if (error.hasError(SslError.SSL_NOTYETVALID)) {
3499 LinearLayout ll = (LinearLayout)factory
3500 .inflate(R.layout.ssl_warning, placeholder);
3501 ((TextView)ll.findViewById(R.id.warning))
3502 .setText(R.string.ssl_not_yet_valid);
3503 }
3504
3505 mSSLCertificateOnErrorHandler = handler;
3506 mSSLCertificateOnErrorView = view;
3507 mSSLCertificateOnErrorError = error;
3508 mSSLCertificateOnErrorDialog =
3509 new AlertDialog.Builder(this)
3510 .setTitle(R.string.ssl_certificate).setIcon(
3511 R.drawable.ic_dialog_browser_certificate_partially_secure)
3512 .setView(certificateView)
3513 .setPositiveButton(R.string.ok,
3514 new DialogInterface.OnClickListener() {
3515 public void onClick(DialogInterface dialog,
3516 int whichButton) {
3517 mSSLCertificateOnErrorDialog = null;
3518 mSSLCertificateOnErrorView = null;
3519 mSSLCertificateOnErrorHandler = null;
3520 mSSLCertificateOnErrorError = null;
3521
Grace Kloba22ac16e2009-10-07 18:00:23 -07003522 view.getWebViewClient().onReceivedSslError(
3523 view, handler, error);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003524 }
3525 })
3526 .setNeutralButton(R.string.page_info_view,
3527 new DialogInterface.OnClickListener() {
3528 public void onClick(DialogInterface dialog,
3529 int whichButton) {
3530 mSSLCertificateOnErrorDialog = null;
3531
3532 // do not clear the dialog state: we will
3533 // need to show the dialog again once the
3534 // user is done exploring the page-info details
3535
3536 showPageInfo(mTabControl.getTabFromView(view),
3537 true);
3538 }
3539 })
3540 .setOnCancelListener(
3541 new DialogInterface.OnCancelListener() {
3542 public void onCancel(DialogInterface dialog) {
3543 mSSLCertificateOnErrorDialog = null;
3544 mSSLCertificateOnErrorView = null;
3545 mSSLCertificateOnErrorHandler = null;
3546 mSSLCertificateOnErrorError = null;
3547
Grace Kloba22ac16e2009-10-07 18:00:23 -07003548 view.getWebViewClient().onReceivedSslError(
3549 view, handler, error);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003550 }
3551 })
3552 .show();
3553 }
3554
3555 /**
3556 * Inflates the SSL certificate view (helper method).
3557 * @param certificate The SSL certificate.
3558 * @return The resultant certificate view with issued-to, issued-by,
3559 * issued-on, expires-on, and possibly other fields set.
3560 * If the input certificate is null, returns null.
3561 */
3562 private View inflateCertificateView(SslCertificate certificate) {
3563 if (certificate == null) {
3564 return null;
3565 }
3566
3567 LayoutInflater factory = LayoutInflater.from(this);
3568
3569 View certificateView = factory.inflate(
3570 R.layout.ssl_certificate, null);
3571
3572 // issued to:
3573 SslCertificate.DName issuedTo = certificate.getIssuedTo();
3574 if (issuedTo != null) {
3575 ((TextView) certificateView.findViewById(R.id.to_common))
3576 .setText(issuedTo.getCName());
3577 ((TextView) certificateView.findViewById(R.id.to_org))
3578 .setText(issuedTo.getOName());
3579 ((TextView) certificateView.findViewById(R.id.to_org_unit))
3580 .setText(issuedTo.getUName());
3581 }
3582
3583 // issued by:
3584 SslCertificate.DName issuedBy = certificate.getIssuedBy();
3585 if (issuedBy != null) {
3586 ((TextView) certificateView.findViewById(R.id.by_common))
3587 .setText(issuedBy.getCName());
3588 ((TextView) certificateView.findViewById(R.id.by_org))
3589 .setText(issuedBy.getOName());
3590 ((TextView) certificateView.findViewById(R.id.by_org_unit))
3591 .setText(issuedBy.getUName());
3592 }
3593
3594 // issued on:
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003595 String issuedOn = formatCertificateDate(
3596 certificate.getValidNotBeforeDate());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003597 ((TextView) certificateView.findViewById(R.id.issued_on))
3598 .setText(issuedOn);
3599
3600 // expires on:
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003601 String expiresOn = formatCertificateDate(
3602 certificate.getValidNotAfterDate());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003603 ((TextView) certificateView.findViewById(R.id.expires_on))
3604 .setText(expiresOn);
3605
3606 return certificateView;
3607 }
3608
3609 /**
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003610 * Formats the certificate date to a properly localized date string.
The Android Open Source Project0c908882009-03-03 19:32:16 -08003611 * @return Properly localized version of the certificate date string and
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003612 * the "" if it fails to localize.
The Android Open Source Project0c908882009-03-03 19:32:16 -08003613 */
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003614 private String formatCertificateDate(Date certificateDate) {
3615 if (certificateDate == null) {
3616 return "";
The Android Open Source Project0c908882009-03-03 19:32:16 -08003617 }
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003618 String formattedDate = DateFormat.getDateFormat(this).format(certificateDate);
3619 if (formattedDate == null) {
3620 return "";
3621 }
3622 return formattedDate;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003623 }
3624
3625 /**
3626 * Displays an http-authentication dialog.
3627 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003628 void showHttpAuthentication(final HttpAuthHandler handler,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003629 final String host, final String realm, final String title,
3630 final String name, final String password, int focusId) {
3631 LayoutInflater factory = LayoutInflater.from(this);
3632 final View v = factory
3633 .inflate(R.layout.http_authentication, null);
3634 if (name != null) {
3635 ((EditText) v.findViewById(R.id.username_edit)).setText(name);
3636 }
3637 if (password != null) {
3638 ((EditText) v.findViewById(R.id.password_edit)).setText(password);
3639 }
3640
3641 String titleText = title;
3642 if (titleText == null) {
3643 titleText = getText(R.string.sign_in_to).toString().replace(
3644 "%s1", host).replace("%s2", realm);
3645 }
3646
3647 mHttpAuthHandler = handler;
3648 AlertDialog dialog = new AlertDialog.Builder(this)
3649 .setTitle(titleText)
3650 .setIcon(android.R.drawable.ic_dialog_alert)
3651 .setView(v)
3652 .setPositiveButton(R.string.action,
3653 new DialogInterface.OnClickListener() {
3654 public void onClick(DialogInterface dialog,
3655 int whichButton) {
3656 String nm = ((EditText) v
3657 .findViewById(R.id.username_edit))
3658 .getText().toString();
3659 String pw = ((EditText) v
3660 .findViewById(R.id.password_edit))
3661 .getText().toString();
3662 BrowserActivity.this.setHttpAuthUsernamePassword
3663 (host, realm, nm, pw);
3664 handler.proceed(nm, pw);
3665 mHttpAuthenticationDialog = null;
3666 mHttpAuthHandler = null;
3667 }})
3668 .setNegativeButton(R.string.cancel,
3669 new DialogInterface.OnClickListener() {
3670 public void onClick(DialogInterface dialog,
3671 int whichButton) {
3672 handler.cancel();
3673 BrowserActivity.this.resetTitleAndRevertLockIcon();
3674 mHttpAuthenticationDialog = null;
3675 mHttpAuthHandler = null;
3676 }})
3677 .setOnCancelListener(new DialogInterface.OnCancelListener() {
3678 public void onCancel(DialogInterface dialog) {
3679 handler.cancel();
3680 BrowserActivity.this.resetTitleAndRevertLockIcon();
3681 mHttpAuthenticationDialog = null;
3682 mHttpAuthHandler = null;
3683 }})
3684 .create();
3685 // Make the IME appear when the dialog is displayed if applicable.
3686 dialog.getWindow().setSoftInputMode(
3687 WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
3688 dialog.show();
3689 if (focusId != 0) {
3690 dialog.findViewById(focusId).requestFocus();
3691 } else {
3692 v.findViewById(R.id.username_edit).requestFocus();
3693 }
3694 mHttpAuthenticationDialog = dialog;
3695 }
3696
3697 public int getProgress() {
3698 WebView w = mTabControl.getCurrentWebView();
3699 if (w != null) {
3700 return w.getProgress();
3701 } else {
3702 return 100;
3703 }
3704 }
3705
3706 /**
3707 * Set HTTP authentication password.
3708 *
3709 * @param host The host for the password
3710 * @param realm The realm for the password
3711 * @param username The username for the password. If it is null, it means
3712 * password can't be saved.
3713 * @param password The password
3714 */
3715 public void setHttpAuthUsernamePassword(String host, String realm,
3716 String username,
3717 String password) {
Steve Block95a53b22010-03-25 17:24:58 +00003718 WebView w = getTopWindow();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003719 if (w != null) {
3720 w.setHttpAuthUsernamePassword(host, realm, username, password);
3721 }
3722 }
3723
3724 /**
3725 * connectivity manager says net has come or gone... inform the user
3726 * @param up true if net has come up, false if net has gone down
3727 */
3728 public void onNetworkToggle(boolean up) {
3729 if (up == mIsNetworkUp) {
3730 return;
3731 } else if (up) {
3732 mIsNetworkUp = true;
3733 if (mAlertDialog != null) {
3734 mAlertDialog.cancel();
3735 mAlertDialog = null;
3736 }
3737 } else {
3738 mIsNetworkUp = false;
Patrick Scotteb6ab2a2009-09-16 10:00:17 -04003739 if (mInLoad) {
3740 createAndShowNetworkDialog();
3741 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003742 }
3743 WebView w = mTabControl.getCurrentWebView();
3744 if (w != null) {
3745 w.setNetworkAvailable(up);
3746 }
3747 }
3748
Grace Kloba22ac16e2009-10-07 18:00:23 -07003749 boolean isNetworkUp() {
3750 return mIsNetworkUp;
3751 }
3752
Patrick Scotteb6ab2a2009-09-16 10:00:17 -04003753 // This method shows the network dialog alerting the user that the net is
3754 // down. It will only show the dialog if mAlertDialog is null.
3755 private void createAndShowNetworkDialog() {
3756 if (mAlertDialog == null) {
3757 mAlertDialog = new AlertDialog.Builder(this)
3758 .setTitle(R.string.loadSuspendedTitle)
3759 .setMessage(R.string.loadSuspended)
3760 .setPositiveButton(R.string.ok, null)
3761 .show();
3762 }
3763 }
3764
Michael Kolbe421c242010-10-04 19:29:01 -07003765 /**
3766 * callback from ComboPage when bookmark/history selection
3767 */
3768 @Override
3769 public void onUrlSelected(String url, boolean newTab) {
3770 removeComboView();
3771 if (!TextUtils.isEmpty(url)) {
3772 if (newTab) {
3773 openTab(url, false);
3774 } else {
3775 final Tab currentTab = mTabControl.getCurrentTab();
3776 dismissSubWindow(currentTab);
3777 loadUrl(getTopWindow(), url);
3778 }
3779 }
3780 }
3781
3782 /**
3783 * callback from ComboPage when dismissed
3784 */
3785 @Override
3786 public void onComboCanceled() {
3787 removeComboView();
3788 }
3789
3790 /**
3791 * dismiss the ComboPage
3792 */
3793 /* package */ void removeComboView() {
3794 if (mComboView != null) {
3795 mContentView.removeView(mComboView);
3796 mTitleBar.setVisibility(View.VISIBLE);
3797 mMenuState = R.id.MAIN_MENU;
3798 attachTabToContentView(mTabControl.getCurrentTab());
3799 getTopWindow().requestFocus();
3800 mComboView = null;
3801 }
3802 }
3803
3804 /**
3805 * callback from ComboPage when clear history is requested
3806 */
3807 public void onRemoveParentChildRelationships() {
3808 mTabControl.removeParentChildRelationShips();
3809 }
3810
The Android Open Source Project0c908882009-03-03 19:32:16 -08003811 @Override
3812 protected void onActivityResult(int requestCode, int resultCode,
3813 Intent intent) {
Grace Klobabb394f32009-11-19 10:26:37 -08003814 if (getTopWindow() == null) return;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003815 switch (requestCode) {
Leon Scrogginsfde97462010-01-11 13:06:21 -05003816 case PREFERENCES_PAGE:
3817 if (resultCode == RESULT_OK && intent != null) {
3818 String action = intent.getStringExtra(Intent.EXTRA_TEXT);
3819 if (BrowserSettings.PREF_CLEAR_HISTORY.equals(action)) {
3820 mTabControl.removeParentChildRelationShips();
3821 }
3822 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003823 break;
Leon Scroggins8d5fa432009-10-02 15:55:59 -04003824 // Choose a file from the file picker.
3825 case FILE_SELECTED:
3826 if (null == mUploadMessage) break;
3827 Uri result = intent == null || resultCode != RESULT_OK ? null
3828 : intent.getData();
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003829
3830 // As we ask the camera to save the result of the user taking
3831 // a picture, the camera application does not return anything other
3832 // than RESULT_OK. So we need to check whether the file we expected
3833 // was written to disk in the in the case that we
3834 // did not get an intent returned but did get a RESULT_OK. If it was,
3835 // we assume that this result has came back from the camera.
3836 if (result == null && intent == null && resultCode == RESULT_OK) {
3837 File cameraFile = new File(mCameraFilePath);
3838 if (cameraFile.exists()) {
3839 result = Uri.fromFile(cameraFile);
Ben Murdoch07d34732010-05-27 18:34:46 +01003840 // Broadcast to the media scanner that we have a new photo
3841 // so it will be added into the gallery for the user.
3842 sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, result));
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003843 }
3844 }
Leon Scroggins8d5fa432009-10-02 15:55:59 -04003845 mUploadMessage.onReceiveValue(result);
3846 mUploadMessage = null;
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003847 mCameraFilePath = null;
Leon Scroggins8d5fa432009-10-02 15:55:59 -04003848 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003849 default:
3850 break;
3851 }
Leon Scroggins30444232009-09-04 18:36:20 -04003852 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003853 }
3854
3855 /*
3856 * This method is called as a result of the user selecting the options
Leon Scrogginsf08809b2010-01-21 09:27:46 -05003857 * menu to see the download window. It shows the download window on top of
3858 * the current window.
The Android Open Source Project0c908882009-03-03 19:32:16 -08003859 */
Leon Scroggins IIIa682a3c2010-09-27 12:32:40 -04003860 private void viewDownloads() {
3861 Intent intent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
3862 startActivity(intent);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003863 }
3864
Michael Kolbc7485ae2010-09-03 10:10:58 -07003865 /* package */ void promptAddOrInstallBookmark(View anchor) {
3866 PopupMenu popup = new PopupMenu(this, anchor);
3867 popup.getMenuInflater().inflate(R.menu.bookmark_shortcut, popup.getMenu());
3868 popup.setOnMenuItemClickListener(this);
3869 popup.show();
3870 }
Michael Kolbebba8b42010-09-30 12:57:59 -07003871
Michael Kolbc7485ae2010-09-03 10:10:58 -07003872 /**
3873 * popup menu item click listener
3874 * @param item
3875 */
3876 public boolean onMenuItemClick(MenuItem item) {
3877 switch(item.getItemId()) {
3878 case R.id.add_bookmark_menu_id:
3879 bookmarkCurrentPage();
3880 return true;
3881 case R.id.shortcut_to_home_menu_id:
3882 Tab current = mTabControl.getCurrentTab();
3883 current.populatePickerData();
3884 String touchIconUrl = mTabControl.getCurrentWebView().getTouchIconUrl();
3885 if (touchIconUrl != null) {
3886 // Download the touch icon for this site then save
3887 // it to the
3888 // homescreen.
3889 Bundle b = new Bundle();
3890 b.putString("url", current.getUrl());
3891 b.putString("title", current.getTitle());
3892 b.putParcelable("favicon", current.getFavicon());
3893 Message msg = mHandler.obtainMessage(TOUCH_ICON_DOWNLOADED);
3894 msg.setData(b);
3895 new DownloadTouchIcon(BrowserActivity.this, msg,
3896 mTabControl.getCurrentWebView().getSettings().getUserAgentString())
3897 .execute(touchIconUrl);
3898 } else {
3899 // add to homescreen, can do it immediately as there
3900 // is no touch
3901 // icon.
3902 showSaveToHomescreenDialog(
3903 current.getUrl(), current.getTitle(), null, current.getFavicon());
3904 }
3905 return true;
3906 default:
3907 return false;
3908 }
3909 }
Michael Kolbebba8b42010-09-30 12:57:59 -07003910
Michael Kolbc7485ae2010-09-03 10:10:58 -07003911 /* package */Dialog makeAddOrInstallDialog() {
Ben Murdocheecb4e62010-07-06 16:30:38 +01003912 final Tab current = mTabControl.getCurrentTab();
3913 Resources resources = getResources();
Michael Kolbc7485ae2010-09-03 10:10:58 -07003914 CharSequence[] choices =
3915 {resources.getString(R.string.save_to_bookmarks),
3916 resources.getString(R.string.create_shortcut_bookmark)};
Ben Murdocheecb4e62010-07-06 16:30:38 +01003917
3918 AlertDialog.Builder builder = new AlertDialog.Builder(this);
3919 builder.setTitle(R.string.add_new_bookmark);
3920 builder.setItems(choices, new DialogInterface.OnClickListener() {
Michael Kolbc7485ae2010-09-03 10:10:58 -07003921 public void onClick(DialogInterface dialog, int item) {
3922 if (item == 0) {
3923 bookmarkCurrentPage();
3924 } else if (item == 1) {
3925 }
3926 }
Ben Murdocheecb4e62010-07-06 16:30:38 +01003927 });
Michael Kolbc7485ae2010-09-03 10:10:58 -07003928 return builder.create();
Ben Murdocheecb4e62010-07-06 16:30:38 +01003929 }
3930
Leon Scroggins160a7e72009-08-14 18:28:01 -04003931 /**
3932 * Open the Go page.
3933 * @param startWithHistory If true, open starting on the history tab.
3934 * Otherwise, start with the bookmarks tab.
Leon Scroggins160a7e72009-08-14 18:28:01 -04003935 */
Michael Kolbe421c242010-10-04 19:29:01 -07003936 /* package */ void bookmarksOrHistoryPicker(boolean startWithHistory) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003937 WebView current = mTabControl.getCurrentWebView();
3938 if (current == null) {
3939 return;
3940 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003941 String title = current.getTitle();
3942 String url = current.getUrl();
Ben Murdoch87cc65d2010-06-29 20:34:10 +01003943 Bitmap thumbnail = createScreenshot(current, getDesiredThumbnailWidth(this),
3944 getDesiredThumbnailHeight(this));
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01003945
The Android Open Source Project0c908882009-03-03 19:32:16 -08003946 // Just in case the user opens bookmarks before a page finishes loading
3947 // so the current history item, and therefore the page, is null.
3948 if (null == url) {
3949 url = mLastEnteredUrl;
3950 // This can happen.
3951 if (null == url) {
3952 url = mSettings.getHomePage();
3953 }
3954 }
3955 // In case the web page has not yet received its associated title.
3956 if (title == null) {
3957 title = url;
3958 }
Michael Kolbe421c242010-10-04 19:29:01 -07003959 Bundle extras = new Bundle();
3960 extras.putString("title", title);
3961 extras.putString("url", url);
3962 extras.putParcelable("thumbnail", thumbnail);
Leon Scroggins30444232009-09-04 18:36:20 -04003963 // Disable opening in a new window if we have maxed out the windows
Michael Kolbe421c242010-10-04 19:29:01 -07003964 extras.putBoolean("disable_new_window", !mTabControl.canCreateNewTab());
3965 extras.putString("touch_icon_url", current.getTouchIconUrl());
3966
3967 mComboView = new CombinedBookmarkHistoryView(this,
3968 startWithHistory ? CombinedBookmarkHistoryView.FRAGMENT_ID_HISTORY
3969 : CombinedBookmarkHistoryView.FRAGMENT_ID_BOOKMARKS,
3970 extras);
3971 removeTabFromContentView(mTabControl.getCurrentTab());
3972 mTitleBar.setVisibility(View.GONE);
3973 hideFakeTitleBar();
3974 mContentView.addView(mComboView, COVER_SCREEN_PARAMS);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003975 }
3976
Ben Murdocheecb4e62010-07-06 16:30:38 +01003977 private void showSaveToHomescreenDialog(String url, String title, Bitmap touchIcon,
3978 Bitmap favicon) {
3979 Intent intent = new Intent(this, SaveToHomescreenDialog.class);
3980
3981 // Just in case the user tries to save before a page finishes loading
3982 // so the current history item, and therefore the page, is null.
3983 if (null == url) {
3984 url = mLastEnteredUrl;
3985 // This can happen.
3986 if (null == url) {
3987 url = mSettings.getHomePage();
3988 }
3989 }
3990
3991 // In case the web page has not yet received its associated title.
3992 if (title == null) {
3993 title = url;
3994 }
3995
3996 intent.putExtra("title", title);
3997 intent.putExtra("url", url);
3998 intent.putExtra("favicon", favicon);
3999 intent.putExtra("touchIcon", touchIcon);
4000 startActivity(intent);
4001 }
4002
The Android Open Source Project0c908882009-03-03 19:32:16 -08004003 // Called when loading from context menu or LOAD_URL message
Leon Scroggins92472e82010-02-17 16:32:28 -05004004 private void loadUrlFromContext(WebView view, String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08004005 // In case the user enters nothing.
4006 if (url != null && url.length() != 0 && view != null) {
4007 url = smartUrlFilter(url);
Grace Kloba22ac16e2009-10-07 18:00:23 -07004008 if (!view.getWebViewClient().shouldOverrideUrlLoading(view, url)) {
Leon Scroggins92472e82010-02-17 16:32:28 -05004009 loadUrl(view, url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004010 }
4011 }
4012 }
4013
Leon Scroggins92472e82010-02-17 16:32:28 -05004014 /**
4015 * Load the URL into the given WebView and update the title bar
4016 * to reflect the new load. Call this instead of WebView.loadUrl
4017 * directly.
4018 * @param view The WebView used to load url.
4019 * @param url The URL to load.
4020 */
4021 private void loadUrl(WebView view, String url) {
4022 updateTitleBarForNewLoad(view, url);
4023 view.loadUrl(url);
4024 }
4025
4026 /**
4027 * Load UrlData into a Tab and update the title bar to reflect the new
4028 * load. Call this instead of UrlData.loadIn directly.
4029 * @param t The Tab used to load.
4030 * @param data The UrlData being loaded.
4031 */
4032 private void loadUrlDataIn(Tab t, UrlData data) {
4033 updateTitleBarForNewLoad(t.getWebView(), data.mUrl);
4034 data.loadIn(t);
4035 }
4036
4037 /**
4038 * If the WebView is the top window, update the title bar to reflect
4039 * loading the new URL. i.e. set its text, clear the favicon (which
4040 * will be set once the page begins loading), and set the progress to
4041 * INITIAL_PROGRESS to show that the page has begun to load. Called
4042 * by loadUrl and loadUrlDataIn.
4043 * @param view The WebView that is starting a load.
4044 * @param url The URL that is being loaded.
4045 */
4046 private void updateTitleBarForNewLoad(WebView view, String url) {
4047 if (view == getTopWindow()) {
4048 setUrlTitle(url, null);
4049 setFavicon(null);
4050 onProgressChanged(view, INITIAL_PROGRESS);
4051 }
4052 }
4053
The Android Open Source Project0c908882009-03-03 19:32:16 -08004054 private String smartUrlFilter(Uri inUri) {
4055 if (inUri != null) {
4056 return smartUrlFilter(inUri.toString());
4057 }
4058 return null;
4059 }
4060
Feng Qianb34f87a2009-03-24 21:27:26 -07004061 protected static final Pattern ACCEPTED_URI_SCHEMA = Pattern.compile(
The Android Open Source Project0c908882009-03-03 19:32:16 -08004062 "(?i)" + // switch on case insensitive matching
4063 "(" + // begin group for schema
4064 "(?:http|https|file):\\/\\/" +
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004065 "|(?:inline|data|about|content|javascript):" +
The Android Open Source Project0c908882009-03-03 19:32:16 -08004066 ")" +
4067 "(.*)" );
4068
4069 /**
4070 * Attempts to determine whether user input is a URL or search
4071 * terms. Anything with a space is passed to search.
4072 *
4073 * Converts to lowercase any mistakenly uppercased schema (i.e.,
4074 * "Http://" converts to "http://"
4075 *
4076 * @return Original or modified URL
4077 *
4078 */
4079 String smartUrlFilter(String url) {
4080
4081 String inUrl = url.trim();
4082 boolean hasSpace = inUrl.indexOf(' ') != -1;
4083
4084 Matcher matcher = ACCEPTED_URI_SCHEMA.matcher(inUrl);
4085 if (matcher.matches()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08004086 // force scheme to lowercase
4087 String scheme = matcher.group(1);
4088 String lcScheme = scheme.toLowerCase();
4089 if (!lcScheme.equals(scheme)) {
Mitsuru Oshima123ecfb2009-05-18 19:11:14 -07004090 inUrl = lcScheme + matcher.group(2);
4091 }
4092 if (hasSpace) {
4093 inUrl = inUrl.replace(" ", "%20");
The Android Open Source Project0c908882009-03-03 19:32:16 -08004094 }
4095 return inUrl;
4096 }
Leon Scroggins956cf012010-10-07 13:51:57 -04004097 if (!hasSpace) {
Dan Egnor5ee906c2009-11-18 12:11:49 -08004098 if (Patterns.WEB_URL.matcher(inUrl).matches()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08004099 return URLUtil.guessUrl(inUrl);
4100 }
4101 }
4102
Leon Scroggins956cf012010-10-07 13:51:57 -04004103 // FIXME: Is this the correct place to add to searches?
4104 // what if someone else calls this function?
4105
The Android Open Source Project0c908882009-03-03 19:32:16 -08004106 Browser.addSearchUrl(mResolver, inUrl);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07004107 return URLUtil.composeSearchUrl(inUrl, QuickSearch_G, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004108 }
4109
Ben Murdochbff2d602009-07-01 20:19:05 +01004110 /* package */ void setShouldShowErrorConsole(boolean flag) {
4111 if (flag == mShouldShowErrorConsole) {
4112 // Nothing to do.
4113 return;
4114 }
Leon Scroggins IIIa9e35b62010-09-16 15:30:15 -04004115 Tab t = mTabControl.getCurrentTab();
4116 if (t == null) {
4117 // There is no current tab so we cannot toggle the error console
4118 return;
4119 }
Ben Murdochbff2d602009-07-01 20:19:05 +01004120
4121 mShouldShowErrorConsole = flag;
4122
Leon Scroggins IIIa9e35b62010-09-16 15:30:15 -04004123 ErrorConsoleView errorConsole = t.getErrorConsole(true);
Ben Murdochbff2d602009-07-01 20:19:05 +01004124
4125 if (flag) {
4126 // Setting the show state of the console will cause it's the layout to be inflated.
4127 if (errorConsole.numberOfErrors() > 0) {
4128 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
4129 } else {
4130 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
4131 }
4132
4133 // Now we can add it to the main view.
4134 mErrorConsoleContainer.addView(errorConsole,
Romain Guy15b8ec62010-01-08 15:06:43 -08004135 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
Ben Murdochbff2d602009-07-01 20:19:05 +01004136 ViewGroup.LayoutParams.WRAP_CONTENT));
4137 } else {
4138 mErrorConsoleContainer.removeView(errorConsole);
4139 }
4140
4141 }
4142
Grace Kloba22ac16e2009-10-07 18:00:23 -07004143 boolean shouldShowErrorConsole() {
4144 return mShouldShowErrorConsole;
4145 }
4146
Andrei Popescu163ab742009-10-20 17:58:23 +01004147 private void setStatusBarVisibility(boolean visible) {
4148 int flag = visible ? 0 : WindowManager.LayoutParams.FLAG_FULLSCREEN;
4149 getWindow().setFlags(flag, WindowManager.LayoutParams.FLAG_FULLSCREEN);
4150 }
4151
Andrei Popescu56199cc2010-01-12 22:39:16 +00004152
4153 private void sendNetworkType(String type, String subtype) {
4154 WebView w = mTabControl.getCurrentWebView();
4155 if (w != null) {
4156 w.setNetworkType(type, subtype);
4157 }
4158 }
4159
Grace Klobaeb6eef42009-09-15 17:56:32 -07004160 final static int LOCK_ICON_UNSECURE = 0;
4161 final static int LOCK_ICON_SECURE = 1;
4162 final static int LOCK_ICON_MIXED = 2;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004163
The Android Open Source Project0c908882009-03-03 19:32:16 -08004164 private BrowserSettings mSettings;
4165 private TabControl mTabControl;
4166 private ContentResolver mResolver;
4167 private FrameLayout mContentView;
Andrei Popescuadc008d2009-06-26 14:11:30 +01004168 private View mCustomView;
4169 private FrameLayout mCustomViewContainer;
Andrei Popescuc9b55562009-07-07 10:51:15 +01004170 private WebChromeClient.CustomViewCallback mCustomViewCallback;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004171
4172 // FIXME, temp address onPrepareMenu performance problem. When we move everything out of
4173 // view, we should rewrite this.
4174 private int mCurrentMenuState = 0;
4175 private int mMenuState = R.id.MAIN_MENU;
Andrei Popescuadc008d2009-06-26 14:11:30 +01004176 private int mOldMenuState = EMPTY_MENU;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004177 private static final int EMPTY_MENU = -1;
4178 private Menu mMenu;
4179
The Android Open Source Project0c908882009-03-03 19:32:16 -08004180 // Used to prevent chording to result in firing two shortcuts immediately
4181 // one after another. Fixes bug 1211714.
4182 boolean mCanChord;
4183
4184 private boolean mInLoad;
4185 private boolean mIsNetworkUp;
Ben Murdochb7cc8b42009-09-28 10:59:09 +01004186 private boolean mDidStopLoad;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004187
Cary Clark1f10cbf2010-03-22 11:45:23 -04004188 /* package */ boolean mActivityInPause = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004189
4190 private boolean mMenuIsDown;
4191
The Android Open Source Project0c908882009-03-03 19:32:16 -08004192 private static boolean mInTrace;
4193
4194 // Performance probe
4195 private static final int[] SYSTEM_CPU_FORMAT = new int[] {
4196 Process.PROC_SPACE_TERM | Process.PROC_COMBINE,
4197 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 1: user time
4198 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 2: nice time
4199 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 3: sys time
4200 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 4: idle time
4201 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 5: iowait time
4202 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 6: irq time
4203 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG // 7: softirq time
4204 };
4205
4206 private long mStart;
4207 private long mProcessStart;
4208 private long mUserStart;
4209 private long mSystemStart;
4210 private long mIdleStart;
4211 private long mIrqStart;
4212
4213 private long mUiStart;
4214
4215 private Drawable mMixLockIcon;
4216 private Drawable mSecLockIcon;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004217
4218 /* hold a ref so we can auto-cancel if necessary */
4219 private AlertDialog mAlertDialog;
4220
The Android Open Source Project0c908882009-03-03 19:32:16 -08004221 // The up-to-date URL and title (these can be different from those stored
4222 // in WebView, since it takes some time for the information in WebView to
4223 // get updated)
4224 private String mUrl;
4225 private String mTitle;
4226
4227 // As PageInfo has different style for landscape / portrait, we have
4228 // to re-open it when configuration changed
4229 private AlertDialog mPageInfoDialog;
Grace Kloba22ac16e2009-10-07 18:00:23 -07004230 private Tab mPageInfoView;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004231 // If the Page-Info dialog is launched from the SSL-certificate-on-error
4232 // dialog, we should not just dismiss it, but should get back to the
4233 // SSL-certificate-on-error dialog. This flag is used to store this state
Leon Scrogginsc7b92f82010-01-11 18:17:31 -05004234 private boolean mPageInfoFromShowSSLCertificateOnError;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004235
4236 // as SSLCertificateOnError has different style for landscape / portrait,
4237 // we have to re-open it when configuration changed
4238 private AlertDialog mSSLCertificateOnErrorDialog;
4239 private WebView mSSLCertificateOnErrorView;
4240 private SslErrorHandler mSSLCertificateOnErrorHandler;
4241 private SslError mSSLCertificateOnErrorError;
4242
4243 // as SSLCertificate has different style for landscape / portrait, we
4244 // have to re-open it when configuration changed
4245 private AlertDialog mSSLCertificateDialog;
Grace Kloba22ac16e2009-10-07 18:00:23 -07004246 private Tab mSSLCertificateView;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004247
4248 // as HttpAuthentication has different style for landscape / portrait, we
4249 // have to re-open it when configuration changed
4250 private AlertDialog mHttpAuthenticationDialog;
4251 private HttpAuthHandler mHttpAuthHandler;
4252
4253 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_PARAMS =
4254 new FrameLayout.LayoutParams(
Romain Guy15b8ec62010-01-08 15:06:43 -08004255 ViewGroup.LayoutParams.MATCH_PARENT,
4256 ViewGroup.LayoutParams.MATCH_PARENT);
Andrei Popescuadc008d2009-06-26 14:11:30 +01004257 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_GRAVITY_CENTER =
4258 new FrameLayout.LayoutParams(
Romain Guy15b8ec62010-01-08 15:06:43 -08004259 ViewGroup.LayoutParams.MATCH_PARENT,
4260 ViewGroup.LayoutParams.MATCH_PARENT,
Andrei Popescuadc008d2009-06-26 14:11:30 +01004261 Gravity.CENTER);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07004262 // Google search
4263 final static String QuickSearch_G = "http://www.google.com/m?q=%s";
The Android Open Source Project0c908882009-03-03 19:32:16 -08004264
4265 final static String QUERY_PLACE_HOLDER = "%s";
4266
4267 // "source" parameter for Google search through search key
4268 final static String GOOGLE_SEARCH_SOURCE_SEARCHKEY = "browser-key";
4269 // "source" parameter for Google search through goto menu
4270 final static String GOOGLE_SEARCH_SOURCE_GOTO = "browser-goto";
4271 // "source" parameter for Google search through simplily type
4272 final static String GOOGLE_SEARCH_SOURCE_TYPE = "browser-type";
4273 // "source" parameter for Google search suggested by the browser
4274 final static String GOOGLE_SEARCH_SOURCE_SUGGEST = "browser-suggest";
4275 // "source" parameter for Google search from unknown source
4276 final static String GOOGLE_SEARCH_SOURCE_UNKNOWN = "unknown";
4277
4278 private final static String LOGTAG = "browser";
4279
The Android Open Source Project0c908882009-03-03 19:32:16 -08004280 private String mLastEnteredUrl;
4281
4282 private PowerManager.WakeLock mWakeLock;
4283 private final static int WAKELOCK_TIMEOUT = 5 * 60 * 1000; // 5 minutes
4284
4285 private Toast mStopToast;
4286
Leon Scroggins571b3762010-05-26 10:25:01 -04004287 private TitleBarBase mTitleBar;
Michael Kolba2b2ba82010-08-04 17:54:03 -07004288 private TabBar mTabBar;
Leon Scroggins81db3662009-06-04 17:45:11 -04004289
Ben Murdochbff2d602009-07-01 20:19:05 +01004290 private LinearLayout mErrorConsoleContainer = null;
4291 private boolean mShouldShowErrorConsole = false;
4292
The Android Open Source Project0c908882009-03-03 19:32:16 -08004293 // As the ids are dynamically created, we can't guarantee that they will
4294 // be in sequence, so this static array maps ids to a window number.
4295 final static private int[] WINDOW_SHORTCUT_ID_ARRAY =
4296 { R.id.window_one_menu_id, R.id.window_two_menu_id, R.id.window_three_menu_id,
4297 R.id.window_four_menu_id, R.id.window_five_menu_id, R.id.window_six_menu_id,
4298 R.id.window_seven_menu_id, R.id.window_eight_menu_id };
4299
4300 // monitor platform changes
4301 private IntentFilter mNetworkStateChangedFilter;
4302 private BroadcastReceiver mNetworkStateIntentReceiver;
4303
Bjorn Bringerta7611812010-03-24 11:12:02 +00004304 private SystemAllowGeolocationOrigins mSystemAllowGeolocationOrigins;
4305
The Android Open Source Project0c908882009-03-03 19:32:16 -08004306 // activity requestCode
Nicolas Roard78a98e42009-05-11 13:34:17 +01004307 final static int PREFERENCES_PAGE = 3;
Leon Scroggins8d5fa432009-10-02 15:55:59 -04004308 final static int FILE_SELECTED = 4;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004309
Andrei Popescu540035d2009-09-18 18:59:20 +01004310 // the default <video> poster
4311 private Bitmap mDefaultVideoPoster;
4312 // the video progress view
4313 private View mVideoProgressView;
4314
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004315 /**
4316 * A UrlData class to abstract how the content will be set to WebView.
4317 * This base class uses loadUrl to show the content.
4318 */
Leon Scroggins6eac63e2010-03-15 18:19:14 -04004319 /* package */ static class UrlData {
Grace Kloba068e48b2010-01-26 18:11:27 -08004320 final String mUrl;
4321 final Map<String, String> mHeaders;
Leon Scroggins58d56c62010-01-28 15:12:40 -05004322 final Intent mVoiceIntent;
Grace Kloba60e095c2009-06-16 11:50:55 -07004323
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004324 UrlData(String url) {
4325 this.mUrl = url;
Grace Kloba068e48b2010-01-26 18:11:27 -08004326 this.mHeaders = null;
Leon Scroggins58d56c62010-01-28 15:12:40 -05004327 this.mVoiceIntent = null;
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004328 }
Grace Kloba60e095c2009-06-16 11:50:55 -07004329
Leon Scroggins58d56c62010-01-28 15:12:40 -05004330 UrlData(String url, Map<String, String> headers, Intent intent) {
Grace Kloba068e48b2010-01-26 18:11:27 -08004331 this.mUrl = url;
4332 this.mHeaders = headers;
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -05004333 if (RecognizerResultsIntent.ACTION_VOICE_SEARCH_RESULTS
4334 .equals(intent.getAction())) {
Leon Scroggins58d56c62010-01-28 15:12:40 -05004335 this.mVoiceIntent = intent;
4336 } else {
4337 this.mVoiceIntent = null;
4338 }
Grace Kloba60e095c2009-06-16 11:50:55 -07004339 }
4340
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004341 boolean isEmpty() {
Leon Scroggins58d56c62010-01-28 15:12:40 -05004342 return mVoiceIntent == null && (mUrl == null || mUrl.length() == 0);
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004343 }
4344
Leon Scroggins92472e82010-02-17 16:32:28 -05004345 /**
4346 * Load this UrlData into the given Tab. Use loadUrlDataIn to update
4347 * the title bar as well.
4348 */
Leon Scroggins58d56c62010-01-28 15:12:40 -05004349 public void loadIn(Tab t) {
4350 if (mVoiceIntent != null) {
4351 t.activateVoiceSearchMode(mVoiceIntent);
4352 } else {
4353 t.getWebView().loadUrl(mUrl, mHeaders);
4354 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004355 }
4356 };
4357
Leon Scroggins1f005d32009-08-10 17:36:42 -04004358 /* package */ static final UrlData EMPTY_URL_DATA = new UrlData(null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004359}