blob: 9f1f3ba68aac842801a8219adf86f41985219723 [file] [log] [blame]
The Android Open Source Project0c908882009-03-03 19:32:16 -08001/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.browser;
18
Michael Kolb3f65c382010-08-20 15:31:16 -070019import com.android.browser.ScrollWebView.ScrollListener;
20import com.android.common.Search;
21import com.android.common.speech.LoggingEvents;
22
Michael Kolbed217742010-08-10 17:52:34 -070023import android.app.ActionBar;
The Android Open Source Project0c908882009-03-03 19:32:16 -080024import android.app.Activity;
The Android Open Source Project0c908882009-03-03 19:32:16 -080025import android.app.AlertDialog;
26import android.app.ProgressDialog;
27import android.app.SearchManager;
28import android.content.ActivityNotFoundException;
29import android.content.BroadcastReceiver;
Dianne Hackborn80f32622010-08-05 14:17:53 -070030import android.content.ClipboardManager;
The Android Open Source Project0c908882009-03-03 19:32:16 -080031import android.content.ComponentName;
Leon Scroggins58d56c62010-01-28 15:12:40 -050032import android.content.ContentProvider;
33import android.content.ContentProviderClient;
The Android Open Source Project0c908882009-03-03 19:32:16 -080034import android.content.ContentResolver;
Leon Scrogginsb6b7f9e2009-06-18 12:05:28 -040035import android.content.ContentUris;
The Android Open Source Project0c908882009-03-03 19:32:16 -080036import android.content.ContentValues;
37import android.content.Context;
38import android.content.DialogInterface;
39import android.content.Intent;
40import android.content.IntentFilter;
The Android Open Source Project0c908882009-03-03 19:32:16 -080041import android.content.pm.PackageManager;
42import android.content.pm.ResolveInfo;
The Android Open Source Project0c908882009-03-03 19:32:16 -080043import android.content.res.Configuration;
44import android.content.res.Resources;
45import android.database.Cursor;
The Android Open Source Project0c908882009-03-03 19:32:16 -080046import android.graphics.Bitmap;
Andrei Popescu540035d2009-09-18 18:59:20 +010047import android.graphics.BitmapFactory;
The Android Open Source Project0c908882009-03-03 19:32:16 -080048import android.graphics.Canvas;
The Android Open Source Project0c908882009-03-03 19:32:16 -080049import android.graphics.Picture;
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -040050import android.graphics.PixelFormat;
The Android Open Source Project0c908882009-03-03 19:32:16 -080051import android.graphics.drawable.Drawable;
The Android Open Source Project0c908882009-03-03 19:32:16 -080052import android.net.ConnectivityManager;
Andrei Popescu56199cc2010-01-12 22:39:16 +000053import android.net.NetworkInfo;
The Android Open Source Project0c908882009-03-03 19:32:16 -080054import android.net.Uri;
55import android.net.WebAddress;
The Android Open Source Project0c908882009-03-03 19:32:16 -080056import android.net.http.SslCertificate;
57import android.net.http.SslError;
58import android.os.AsyncTask;
59import android.os.Bundle;
60import android.os.Debug;
61import android.os.Environment;
62import android.os.Handler;
The Android Open Source Project0c908882009-03-03 19:32:16 -080063import android.os.Message;
64import android.os.PowerManager;
65import android.os.Process;
The Android Open Source Project0c908882009-03-03 19:32:16 -080066import android.os.SystemClock;
The Android Open Source Project0c908882009-03-03 19:32:16 -080067import android.provider.Browser;
Jeff Hamilton8ce956c2010-08-17 11:13:53 -050068import android.provider.BrowserContract;
Cary Clark5e335a32009-09-22 14:53:11 -040069import android.provider.ContactsContract;
Michael Kolba2b2ba82010-08-04 17:54:03 -070070import android.provider.ContactsContract.Intents.Insert;
The Android Open Source Project0c908882009-03-03 19:32:16 -080071import android.provider.Downloads;
72import android.provider.MediaStore;
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -050073import android.speech.RecognizerResultsIntent;
The Android Open Source Project0c908882009-03-03 19:32:16 -080074import android.text.TextUtils;
75import android.text.format.DateFormat;
The Android Open Source Project0c908882009-03-03 19:32:16 -080076import android.util.Log;
Dianne Hackborn385effd2010-02-24 20:03:04 -080077import android.util.Patterns;
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -040078import android.view.ActionMode;
The Android Open Source Project0c908882009-03-03 19:32:16 -080079import android.view.ContextMenu;
Michael Kolba2b2ba82010-08-04 17:54:03 -070080import android.view.ContextMenu.ContextMenuInfo;
The Android Open Source Project0c908882009-03-03 19:32:16 -080081import android.view.Gravity;
82import android.view.KeyEvent;
83import android.view.LayoutInflater;
84import android.view.Menu;
85import android.view.MenuInflater;
86import android.view.MenuItem;
Michael Kolba2b2ba82010-08-04 17:54:03 -070087import android.view.MenuItem.OnMenuItemClickListener;
Michael Kolb3f65c382010-08-20 15:31:16 -070088import android.view.MotionEvent;
The Android Open Source Project0c908882009-03-03 19:32:16 -080089import android.view.View;
90import android.view.ViewGroup;
91import android.view.Window;
92import android.view.WindowManager;
Svetoslav Ganov2b345992010-05-06 06:13:54 -070093import android.view.accessibility.AccessibilityManager;
The Android Open Source Project0c908882009-03-03 19:32:16 -080094import android.webkit.CookieManager;
95import android.webkit.CookieSyncManager;
96import android.webkit.DownloadListener;
97import android.webkit.HttpAuthHandler;
98import android.webkit.SslErrorHandler;
99import android.webkit.URLUtil;
Leon Clarkecb6cc862009-09-29 18:35:13 +0100100import android.webkit.ValueCallback;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800101import android.webkit.WebChromeClient;
102import android.webkit.WebHistoryItem;
103import android.webkit.WebIconDatabase;
104import android.webkit.WebView;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800105import android.widget.EditText;
106import android.widget.FrameLayout;
107import android.widget.LinearLayout;
108import android.widget.TextView;
109import android.widget.Toast;
110
Leon Scrogginsb6b7f9e2009-06-18 12:05:28 -0400111import java.io.ByteArrayOutputStream;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800112import java.io.File;
Ben Murdoch4f75ba22009-10-27 11:48:28 +0000113import java.io.IOException;
114import java.io.InputStream;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800115import java.net.MalformedURLException;
Dianne Hackborn99189432009-06-17 18:06:18 -0700116import java.net.URISyntaxException;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800117import java.net.URL;
118import java.net.URLEncoder;
Elliott Slaughter3d6df162010-08-25 13:17:44 -0700119import java.util.Calendar;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800120import java.util.Date;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800121import java.util.HashMap;
Grace Kloba00f54c52010-01-27 14:53:51 -0800122import java.util.Iterator;
Grace Kloba068e48b2010-01-26 18:11:27 -0800123import java.util.Map;
Michael Kolbfe251992010-07-08 15:41:55 -0700124import java.util.Vector;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800125import java.util.regex.Matcher;
126import java.util.regex.Pattern;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800127
128public class BrowserActivity extends Activity
Shimeng (Simon) Wang98d5fce2010-03-16 13:23:39 -0700129 implements View.OnCreateContextMenuListener, DownloadListener {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800130
Dave Bort31a6d1c2009-04-13 15:56:49 -0700131 /* Define some aliases to make these debugging flags easier to refer to.
132 * This file imports android.provider.Browser, so we can't just refer to "Browser.DEBUG".
133 */
134 private final static boolean DEBUG = com.android.browser.Browser.DEBUG;
135 private final static boolean LOGV_ENABLED = com.android.browser.Browser.LOGV_ENABLED;
136 private final static boolean LOGD_ENABLED = com.android.browser.Browser.LOGD_ENABLED;
137
Satish Sampath565505b2009-05-29 15:37:27 +0100138 // These are single-character shortcuts for searching popular sources.
139 private static final int SHORTCUT_INVALID = 0;
140 private static final int SHORTCUT_GOOGLE_SEARCH = 1;
141 private static final int SHORTCUT_WIKIPEDIA_SEARCH = 2;
142 private static final int SHORTCUT_DICTIONARY_SEARCH = 3;
143 private static final int SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH = 4;
144
Cary Clarka9771242009-08-11 16:42:26 -0400145 private static class ClearThumbnails extends AsyncTask<File, Void, Void> {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800146 @Override
147 public Void doInBackground(File... files) {
148 if (files != null) {
149 for (File f : files) {
Cary Clarkd6be1752009-08-12 12:56:42 -0400150 if (!f.delete()) {
151 Log.e(LOGTAG, f.getPath() + " was not deleted");
152 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800153 }
154 }
155 return null;
156 }
157 }
158
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400159 /**
160 * This layout holds everything you see below the status bar, including the
161 * error console, the custom view container, and the webviews.
162 */
163 private FrameLayout mBrowserFrameLayout;
Leon Scroggins81db3662009-06-04 17:45:11 -0400164
Leon Scrogginsd746a942010-05-19 13:21:44 -0400165 private boolean mXLargeScreenSize;
166
Jeff Davidson43610292010-07-16 16:03:58 -0700167 private Boolean mIsProviderPresent = null;
168 private Uri mRlzUri = null;
169
Grace Kloba22ac16e2009-10-07 18:00:23 -0700170 @Override
171 public void onCreate(Bundle icicle) {
Dave Bort31a6d1c2009-04-13 15:56:49 -0700172 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800173 Log.v(LOGTAG, this + " onStart");
174 }
175 super.onCreate(icicle);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800176 // test the browser in OpenGL
177 // requestWindowFeature(Window.FEATURE_OPENGL);
178
Mike Reedd334bf52010-01-26 15:21:44 -0500179 // enable this to test the browser in 32bit
180 if (false) {
181 getWindow().setFormat(PixelFormat.RGBX_8888);
182 BitmapFactory.setDefaultConfig(Bitmap.Config.ARGB_8888);
183 }
184
Svetoslav Ganov2b345992010-05-06 06:13:54 -0700185 if (AccessibilityManager.getInstance(this).isEnabled()) {
186 setDefaultKeyMode(DEFAULT_KEYS_DISABLE);
187 } else {
188 setDefaultKeyMode(DEFAULT_KEYS_SEARCH_LOCAL);
189 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800190
191 mResolver = getContentResolver();
192
Grace Kloba0923d692009-09-23 21:37:25 -0700193 // If this was a web search request, pass it on to the default web
194 // search provider and finish this activity.
195 if (handleWebSearchIntent(getIntent())) {
196 finish();
197 return;
198 }
199
The Android Open Source Project0c908882009-03-03 19:32:16 -0800200 mSecLockIcon = Resources.getSystem().getDrawable(
201 android.R.drawable.ic_secure);
202 mMixLockIcon = Resources.getSystem().getDrawable(
203 android.R.drawable.ic_partial_secure);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800204
Michael Kolbed217742010-08-10 17:52:34 -0700205 // Create the tab control and our initial tab
206 mTabControl = new TabControl(this);
207
208 mXLargeScreenSize = (getResources().getConfiguration().screenLayout
209 & Configuration.SCREENLAYOUT_SIZE_MASK)
210 == Configuration.SCREENLAYOUT_SIZE_XLARGE;
211
Leon Scroggins81db3662009-06-04 17:45:11 -0400212 FrameLayout frameLayout = (FrameLayout) getWindow().getDecorView()
213 .findViewById(com.android.internal.R.id.content);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400214 mBrowserFrameLayout = (FrameLayout) LayoutInflater.from(this)
215 .inflate(R.layout.custom_screen, null);
216 mContentView = (FrameLayout) mBrowserFrameLayout.findViewById(
217 R.id.main_content);
218 mErrorConsoleContainer = (LinearLayout) mBrowserFrameLayout
219 .findViewById(R.id.error_console);
220 mCustomViewContainer = (FrameLayout) mBrowserFrameLayout
221 .findViewById(R.id.fullscreen_custom_content);
222 frameLayout.addView(mBrowserFrameLayout, COVER_SCREEN_PARAMS);
Michael Kolbe0a36662010-06-29 10:37:12 -0700223
Leon Scrogginsd746a942010-05-19 13:21:44 -0400224 if (mXLargeScreenSize) {
Michael Kolba2b2ba82010-08-04 17:54:03 -0700225 mTitleBar = new TitleBarXLarge(this);
226 mTitleBar.setProgress(100);
227 mFakeTitleBar = new TitleBarXLarge(this);
Michael Kolbed217742010-08-10 17:52:34 -0700228 ActionBar actionBar = getActionBar();
Michael Kolba2b2ba82010-08-04 17:54:03 -0700229 mTabBar = new TabBar(this, mTabControl, (TitleBarXLarge) mFakeTitleBar);
Michael Kolbed217742010-08-10 17:52:34 -0700230 actionBar.setCustomNavigationMode(mTabBar);
Michael Kolb68775752010-08-19 12:42:01 -0700231 // disable built in zoom controls
232 mTabControl.setDisplayZoomControls(false);
Leon Scrogginsd746a942010-05-19 13:21:44 -0400233 } else {
Leon Scroggins571b3762010-05-26 10:25:01 -0400234 mTitleBar = new TitleBar(this);
Leon Scrogginsd746a942010-05-19 13:21:44 -0400235 // mTitleBar will be always be shown in the fully loaded mode on
236 // phone
237 mTitleBar.setProgress(100);
Leon Scrogginsd746a942010-05-19 13:21:44 -0400238 mFakeTitleBar = new TitleBar(this);
239 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800240
The Android Open Source Project0c908882009-03-03 19:32:16 -0800241 // Open the icon database and retain all the bookmark urls for favicons
242 retainIconsOnStartup();
243
244 // Keep a settings instance handy.
245 mSettings = BrowserSettings.getInstance();
246 mSettings.setTabControl(mTabControl);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800247
248 PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
249 mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Browser");
250
Patrick Scott6adacc92010-03-05 08:24:51 -0500251 // Find out if the network is currently up.
252 ConnectivityManager cm = (ConnectivityManager) getSystemService(
253 Context.CONNECTIVITY_SERVICE);
254 NetworkInfo info = cm.getActiveNetworkInfo();
255 if (info != null) {
256 mIsNetworkUp = info.isAvailable();
257 }
258
Grace Klobaa34f6862009-07-31 16:28:17 -0700259 /* enables registration for changes in network status from
260 http stack */
261 mNetworkStateChangedFilter = new IntentFilter();
262 mNetworkStateChangedFilter.addAction(
263 ConnectivityManager.CONNECTIVITY_ACTION);
264 mNetworkStateIntentReceiver = new BroadcastReceiver() {
265 @Override
266 public void onReceive(Context context, Intent intent) {
267 if (intent.getAction().equals(
268 ConnectivityManager.CONNECTIVITY_ACTION)) {
Andrei Popescue4c98462010-02-19 15:44:13 +0000269
270 NetworkInfo info = intent.getParcelableExtra(
271 ConnectivityManager.EXTRA_NETWORK_INFO);
272 String typeName = info.getTypeName();
273 String subtypeName = info.getSubtypeName();
274 sendNetworkType(typeName.toLowerCase(),
275 (subtypeName != null ? subtypeName.toLowerCase() : ""));
276
277 onNetworkToggle(info.isAvailable());
Grace Klobaa34f6862009-07-31 16:28:17 -0700278 }
279 }
280 };
281
Elliott Slaughter3d6df162010-08-25 13:17:44 -0700282 // Unless the last browser usage was within 24 hours, destroy any
283 // remaining incognito tabs.
284
285 Calendar lastActiveDate = icicle != null ? (Calendar) icicle.getSerializable("lastActiveDate") : null;
286 Calendar today = Calendar.getInstance();
287 Calendar yesterday = Calendar.getInstance();
288 yesterday.add(Calendar.DATE, -1);
289
290 boolean dontRestoreIncognitoTabs = lastActiveDate == null
291 || lastActiveDate.before(yesterday)
292 || lastActiveDate.after(today);
293
294 if (!mTabControl.restoreState(icicle, dontRestoreIncognitoTabs)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800295 // clear up the thumbnail directory if we can't restore the state as
296 // none of the files in the directory are referenced any more.
297 new ClearThumbnails().execute(
298 mTabControl.getThumbnailDir().listFiles());
Grace Klobaaab3f092009-07-30 12:29:51 -0700299 // there is no quit on Android. But if we can't restore the state,
300 // we can treat it as a new Browser, remove the old session cookies.
301 CookieManager.getInstance().removeSessionCookie();
Elliott Slaughter3d6df162010-08-25 13:17:44 -0700302 // remove any incognito files
303 WebView.cleanupPrivateBrowsingFiles(this);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800304 final Intent intent = getIntent();
305 final Bundle extra = intent.getExtras();
306 // Create an initial tab.
307 // If the intent is ACTION_VIEW and data is not null, the Browser is
308 // invoked to view the content by another application. In this case,
309 // the tab will be close when exit.
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700310 UrlData urlData = getUrlDataFromIntent(intent);
311
Leon Scroggins58d56c62010-01-28 15:12:40 -0500312 String action = intent.getAction();
Grace Kloba22ac16e2009-10-07 18:00:23 -0700313 final Tab t = mTabControl.createNewTab(
Leon Scroggins58d56c62010-01-28 15:12:40 -0500314 (Intent.ACTION_VIEW.equals(action) &&
315 intent.getData() != null)
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -0500316 || RecognizerResultsIntent.ACTION_VOICE_SEARCH_RESULTS
317 .equals(action),
Elliott Slaughterf0f03952010-07-14 18:10:36 -0700318 intent.getStringExtra(Browser.EXTRA_APPLICATION_ID),
319 urlData.mUrl, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800320 mTabControl.setCurrentTab(t);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800321 attachTabToContentView(t);
322 WebView webView = t.getWebView();
323 if (extra != null) {
324 int scale = extra.getInt(Browser.INITIAL_ZOOM_LEVEL, 0);
325 if (scale > 0 && scale <= 1000) {
326 webView.setInitialScale(scale);
327 }
328 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800329
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700330 if (urlData.isEmpty()) {
Shimeng (Simon) Wang98d5fce2010-03-16 13:23:39 -0700331 loadUrl(webView, mSettings.getHomePage());
The Android Open Source Project0c908882009-03-03 19:32:16 -0800332 } else {
Patrick Scott9d53da02010-02-19 10:19:01 -0500333 loadUrlDataIn(t, urlData);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800334 }
335 } else {
Elliott Slaughter3d6df162010-08-25 13:17:44 -0700336 if (dontRestoreIncognitoTabs) {
337 WebView.cleanupPrivateBrowsingFiles(this);
338 }
339
The Android Open Source Project0c908882009-03-03 19:32:16 -0800340 // TabControl.restoreState() will create a new tab even if
Leon Scroggins1f005d32009-08-10 17:36:42 -0400341 // restoring the state fails.
The Android Open Source Project0c908882009-03-03 19:32:16 -0800342 attachTabToContentView(mTabControl.getCurrentTab());
343 }
Grace Kloba615c6c92009-08-03 10:22:44 -0700344
Cary Clarkb4b83182010-07-01 12:36:56 -0400345 // Delete old thumbnails to save space
346 File dir = mTabControl.getThumbnailDir();
347 if (dir.exists()) {
348 for (String child : dir.list()) {
349 File f = new File(dir, child);
350 f.delete();
351 }
352 }
353
Feng Qianb3c02da2009-06-29 15:58:08 -0700354 // Read JavaScript flags if it exists.
355 String jsFlags = mSettings.getJsFlags();
356 if (jsFlags.trim().length() != 0) {
357 mTabControl.getCurrentWebView().setJsFlags(jsFlags);
358 }
Bjorn Bringerta7611812010-03-24 11:12:02 +0000359
360 // Start watching the default geolocation permissions
361 mSystemAllowGeolocationOrigins
362 = new SystemAllowGeolocationOrigins(getApplicationContext());
363 mSystemAllowGeolocationOrigins.start();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800364 }
365
Michael Kolba2b2ba82010-08-04 17:54:03 -0700366 ScrollListener getScrollListener() {
367 return mTabBar;
368 }
369
Leon Scroggins58d56c62010-01-28 15:12:40 -0500370 /**
371 * Feed the previously stored results strings to the BrowserProvider so that
372 * the SearchDialog will show them instead of the standard searches.
373 * @param result String to show on the editable line of the SearchDialog.
374 */
375 /* package */ void showVoiceSearchResults(String result) {
376 ContentProviderClient client = mResolver.acquireContentProviderClient(
377 Browser.BOOKMARKS_URI);
378 ContentProvider prov = client.getLocalContentProvider();
379 BrowserProvider bp = (BrowserProvider) prov;
380 bp.setQueryResults(mTabControl.getCurrentTab().getVoiceSearchResults());
381 client.release();
382
Leon Scrogginsfbb3f152010-03-09 17:26:56 -0500383 Bundle bundle = createGoogleSearchSourceBundle(
384 GOOGLE_SEARCH_SOURCE_SEARCHKEY);
385 bundle.putBoolean(SearchManager.CONTEXT_IS_VOICE, true);
386 startSearch(result, false, bundle, false);
Leon Scroggins58d56c62010-01-28 15:12:40 -0500387 }
388
The Android Open Source Project0c908882009-03-03 19:32:16 -0800389 @Override
390 protected void onNewIntent(Intent intent) {
Grace Kloba22ac16e2009-10-07 18:00:23 -0700391 Tab current = mTabControl.getCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800392 // When a tab is closed on exit, the current tab index is set to -1.
393 // Reset before proceed as Browser requires the current tab to be set.
394 if (current == null) {
395 // Try to reset the tab in case the index was incorrect.
396 current = mTabControl.getTab(0);
397 if (current == null) {
398 // No tabs at all so just ignore this intent.
399 return;
400 }
401 mTabControl.setCurrentTab(current);
402 attachTabToContentView(current);
403 resetTitleAndIcon(current.getWebView());
404 }
405 final String action = intent.getAction();
406 final int flags = intent.getFlags();
407 if (Intent.ACTION_MAIN.equals(action) ||
408 (flags & Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY) != 0) {
409 // just resume the browser
410 return;
411 }
Leon Scrogginsb8a844d2010-03-18 15:06:15 -0400412 // In case the SearchDialog is open.
413 ((SearchManager) getSystemService(Context.SEARCH_SERVICE))
414 .stopSearch();
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -0500415 boolean activateVoiceSearch = RecognizerResultsIntent
416 .ACTION_VOICE_SEARCH_RESULTS.equals(action);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800417 if (Intent.ACTION_VIEW.equals(action)
418 || Intent.ACTION_SEARCH.equals(action)
419 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
Leon Scroggins58d56c62010-01-28 15:12:40 -0500420 || Intent.ACTION_WEB_SEARCH.equals(action)
421 || activateVoiceSearch) {
Leon Scroggins3b18ce32010-02-08 17:35:59 -0500422 if (current.isInVoiceSearchMode()) {
423 String title = current.getVoiceDisplayTitle();
424 if (title != null && title.equals(intent.getStringExtra(
425 SearchManager.QUERY))) {
426 // The user submitted the same search as the last voice
427 // search, so do nothing.
428 return;
429 }
Leon Scroggins1fe13a52010-02-09 15:31:26 -0500430 if (Intent.ACTION_SEARCH.equals(action)
431 && current.voiceSearchSourceIsGoogle()) {
432 Intent logIntent = new Intent(
433 LoggingEvents.ACTION_LOG_EVENT);
434 logIntent.putExtra(LoggingEvents.EXTRA_EVENT,
435 LoggingEvents.VoiceSearch.QUERY_UPDATED);
436 logIntent.putExtra(
437 LoggingEvents.VoiceSearch.EXTRA_QUERY_UPDATED_VALUE,
438 intent.getDataString());
439 sendBroadcast(logIntent);
440 // Note, onPageStarted will revert the voice title bar
441 // When http://b/issue?id=2379215 is fixed, we should update
442 // the title bar here.
443 }
Leon Scroggins3b18ce32010-02-08 17:35:59 -0500444 }
Satish Sampath565505b2009-05-29 15:37:27 +0100445 // If this was a search request (e.g. search query directly typed into the address bar),
446 // pass it on to the default web search provider.
447 if (handleWebSearchIntent(intent)) {
448 return;
449 }
450
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700451 UrlData urlData = getUrlDataFromIntent(intent);
452 if (urlData.isEmpty()) {
453 urlData = new UrlData(mSettings.getHomePage());
The Android Open Source Project0c908882009-03-03 19:32:16 -0800454 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700455
Grace Klobacc634032009-07-28 15:58:19 -0700456 final String appId = intent
457 .getStringExtra(Browser.EXTRA_APPLICATION_ID);
Leon Scroggins47208682010-04-07 17:59:48 -0400458 if ((Intent.ACTION_VIEW.equals(action)
459 // If a voice search has no appId, it means that it came
460 // from the browser. In that case, reuse the current tab.
461 || (activateVoiceSearch && appId != null))
Grace Klobacc634032009-07-28 15:58:19 -0700462 && !getPackageName().equals(appId)
463 && (flags & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0) {
Grace Kloba22ac16e2009-10-07 18:00:23 -0700464 Tab appTab = mTabControl.getTabFromId(appId);
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700465 if (appTab != null) {
466 Log.i(LOGTAG, "Reusing tab for " + appId);
467 // Dismiss the subwindow if applicable.
468 dismissSubWindow(appTab);
469 // Since we might kill the WebView, remove it from the
470 // content view first.
471 removeTabFromContentView(appTab);
472 // Recreate the main WebView after destroying the old one.
473 // If the WebView has the same original url and is on that
474 // page, it can be reused.
475 boolean needsLoad =
Leon Scroggins6eac63e2010-03-15 18:19:14 -0400476 mTabControl.recreateWebView(appTab, urlData);
Ben Murdochbff2d602009-07-01 20:19:05 +0100477
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700478 if (current != appTab) {
Leon Scroggins1f005d32009-08-10 17:36:42 -0400479 switchToTab(mTabControl.getTabIndex(appTab));
480 if (needsLoad) {
Patrick Scott9d53da02010-02-19 10:19:01 -0500481 loadUrlDataIn(appTab, urlData);
Leon Scroggins1f005d32009-08-10 17:36:42 -0400482 }
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700483 } else {
Leon Scroggins1f005d32009-08-10 17:36:42 -0400484 // If the tab was the current tab, we have to attach
485 // it to the view system again.
486 attachTabToContentView(appTab);
487 if (needsLoad) {
Patrick Scott9d53da02010-02-19 10:19:01 -0500488 loadUrlDataIn(appTab, urlData);
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700489 }
490 }
491 return;
Patrick Scottcd115892009-07-16 09:42:58 -0400492 } else {
493 // No matching application tab, try to find a regular tab
494 // with a matching url.
495 appTab = mTabControl.findUnusedTabWithUrl(urlData.mUrl);
Leon Scroggins25515f82009-08-19 15:31:58 -0400496 if (appTab != null) {
497 if (current != appTab) {
498 switchToTab(mTabControl.getTabIndex(appTab));
499 }
500 // Otherwise, we are already viewing the correct tab.
Patrick Scottcd115892009-07-16 09:42:58 -0400501 } else {
502 // if FLAG_ACTIVITY_BROUGHT_TO_FRONT flag is on, the url
503 // will be opened in a new tab unless we have reached
504 // MAX_TABS. Then the url will be opened in the current
505 // tab. If a new tab is created, it will have "true" for
506 // exit on close.
Leon Scroggins1f005d32009-08-10 17:36:42 -0400507 openTabAndShow(urlData, true, appId);
Patrick Scottcd115892009-07-16 09:42:58 -0400508 }
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700509 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800510 } else {
Grace Kloba638d3f42009-11-23 10:35:04 -0800511 if (!urlData.isEmpty()
512 && urlData.mUrl.startsWith("about:debug")) {
513 if ("about:debug.dom".equals(urlData.mUrl)) {
514 current.getWebView().dumpDomTree(false);
515 } else if ("about:debug.dom.file".equals(urlData.mUrl)) {
516 current.getWebView().dumpDomTree(true);
517 } else if ("about:debug.render".equals(urlData.mUrl)) {
518 current.getWebView().dumpRenderTree(false);
519 } else if ("about:debug.render.file".equals(urlData.mUrl)) {
520 current.getWebView().dumpRenderTree(true);
521 } else if ("about:debug.display".equals(urlData.mUrl)) {
522 current.getWebView().dumpDisplayTree();
Mike Reed9b78e1d2010-01-13 14:40:52 -0800523 } else if (urlData.mUrl.startsWith("about:debug.drag")) {
524 int index = urlData.mUrl.codePointAt(16) - '0';
525 if (index <= 0 || index > 9) {
526 current.getWebView().setDragTracker(null);
527 } else {
528 current.getWebView().setDragTracker(new MeshTracker(index));
529 }
Grace Kloba638d3f42009-11-23 10:35:04 -0800530 } else {
531 mSettings.toggleDebugSettings();
532 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800533 return;
534 }
Leon Scroggins1f005d32009-08-10 17:36:42 -0400535 // Get rid of the subwindow if it exists
536 dismissSubWindow(current);
Leon Scroggins8588d152010-04-15 11:01:53 -0400537 // If the current Tab is being used as an application tab,
538 // remove the association, since the new Intent means that it is
539 // no longer associated with that application.
540 current.setAppId(null);
Patrick Scott9d53da02010-02-19 10:19:01 -0500541 loadUrlDataIn(current, urlData);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800542 }
543 }
544 }
545
Satish Sampath565505b2009-05-29 15:37:27 +0100546 private int parseUrlShortcut(String url) {
547 if (url == null) return SHORTCUT_INVALID;
548
549 // FIXME: quick search, need to be customized by setting
550 if (url.length() > 2 && url.charAt(1) == ' ') {
551 switch (url.charAt(0)) {
552 case 'g': return SHORTCUT_GOOGLE_SEARCH;
553 case 'w': return SHORTCUT_WIKIPEDIA_SEARCH;
554 case 'd': return SHORTCUT_DICTIONARY_SEARCH;
555 case 'l': return SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH;
556 }
557 }
558 return SHORTCUT_INVALID;
559 }
560
561 /**
562 * Launches the default web search activity with the query parameters if the given intent's data
563 * are identified as plain search terms and not URLs/shortcuts.
564 * @return true if the intent was handled and web search activity was launched, false if not.
565 */
566 private boolean handleWebSearchIntent(Intent intent) {
567 if (intent == null) return false;
568
569 String url = null;
570 final String action = intent.getAction();
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -0500571 if (RecognizerResultsIntent.ACTION_VOICE_SEARCH_RESULTS.equals(
572 action)) {
Leon Scroggins58d56c62010-01-28 15:12:40 -0500573 return false;
574 }
Satish Sampath565505b2009-05-29 15:37:27 +0100575 if (Intent.ACTION_VIEW.equals(action)) {
Grace Kloba1e705052009-09-29 13:13:36 -0700576 Uri data = intent.getData();
577 if (data != null) url = data.toString();
Satish Sampath565505b2009-05-29 15:37:27 +0100578 } else if (Intent.ACTION_SEARCH.equals(action)
579 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
580 || Intent.ACTION_WEB_SEARCH.equals(action)) {
581 url = intent.getStringExtra(SearchManager.QUERY);
582 }
Bjorn Bringert04851702009-09-22 10:36:01 +0100583 return handleWebSearchRequest(url, intent.getBundleExtra(SearchManager.APP_DATA),
584 intent.getStringExtra(SearchManager.EXTRA_DATA_KEY));
Satish Sampath565505b2009-05-29 15:37:27 +0100585 }
586
587 /**
588 * Launches the default web search activity with the query parameters if the given url string
589 * was identified as plain search terms and not URL/shortcut.
590 * @return true if the request was handled and web search activity was launched, false if not.
591 */
Bjorn Bringert04851702009-09-22 10:36:01 +0100592 private boolean handleWebSearchRequest(String inUrl, Bundle appData, String extraData) {
Satish Sampath565505b2009-05-29 15:37:27 +0100593 if (inUrl == null) return false;
594
595 // In general, we shouldn't modify URL from Intent.
596 // But currently, we get the user-typed URL from search box as well.
597 String url = fixUrl(inUrl).trim();
598
599 // URLs and site specific search shortcuts are handled by the regular flow of control, so
600 // return early.
Dan Egnor5ee906c2009-11-18 12:11:49 -0800601 if (Patterns.WEB_URL.matcher(url).matches()
Satish Sampathbc5b9f32009-06-04 18:21:40 +0100602 || ACCEPTED_URI_SCHEMA.matcher(url).matches()
Satish Sampath565505b2009-05-29 15:37:27 +0100603 || parseUrlShortcut(url) != SHORTCUT_INVALID) {
604 return false;
605 }
606
Leon Scroggins8d06e362010-03-24 14:45:57 -0400607 final ContentResolver cr = mResolver;
608 final String newUrl = url;
Elliott Slaughter627d96f2010-08-18 16:35:30 -0700609 if (mTabControl == null || !mTabControl.getCurrentWebView().isPrivateBrowsingEnabled()) {
Elliott Slaughterf0f03952010-07-14 18:10:36 -0700610 new AsyncTask<Void, Void, Void>() {
611 @Override
612 protected Void doInBackground(Void... unused) {
613 Browser.updateVisitedHistory(cr, newUrl, false);
614 Browser.addSearchUrl(cr, newUrl);
615 return null;
616 }
617 }.execute();
618 }
Satish Sampath565505b2009-05-29 15:37:27 +0100619
620 Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);
621 intent.addCategory(Intent.CATEGORY_DEFAULT);
622 intent.putExtra(SearchManager.QUERY, url);
Satish Sampath15e9f2d2009-06-23 22:29:49 +0100623 if (appData != null) {
624 intent.putExtra(SearchManager.APP_DATA, appData);
625 }
Bjorn Bringert04851702009-09-22 10:36:01 +0100626 if (extraData != null) {
627 intent.putExtra(SearchManager.EXTRA_DATA_KEY, extraData);
628 }
Grace Klobacc634032009-07-28 15:58:19 -0700629 intent.putExtra(Browser.EXTRA_APPLICATION_ID, getPackageName());
Mattias Falk552751e2010-08-23 12:03:57 +0200630
631 // can't be sure there is an activity for the Intent
632 try {
633 startActivity(intent);
634 } catch (ActivityNotFoundException ex) {
635 return false;
636 }
Satish Sampath565505b2009-05-29 15:37:27 +0100637
638 return true;
639 }
640
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700641 private UrlData getUrlDataFromIntent(Intent intent) {
Leon Scroggins58d56c62010-01-28 15:12:40 -0500642 String url = "";
Grace Kloba068e48b2010-01-26 18:11:27 -0800643 Map<String, String> headers = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800644 if (intent != null) {
645 final String action = intent.getAction();
646 if (Intent.ACTION_VIEW.equals(action)) {
647 url = smartUrlFilter(intent.getData());
648 if (url != null && url.startsWith("content:")) {
649 /* Append mimetype so webview knows how to display */
650 String mimeType = intent.resolveType(getContentResolver());
651 if (mimeType != null) {
652 url += "?" + mimeType;
653 }
654 }
Grace Kloba068e48b2010-01-26 18:11:27 -0800655 if (url != null && url.startsWith("http")) {
Grace Kloba00f54c52010-01-27 14:53:51 -0800656 final Bundle pairs = intent
657 .getBundleExtra(Browser.EXTRA_HEADERS);
Grace Kloba2d508ed2010-01-28 11:39:15 -0800658 if (pairs != null && !pairs.isEmpty()) {
Grace Kloba00f54c52010-01-27 14:53:51 -0800659 Iterator<String> iter = pairs.keySet().iterator();
Grace Kloba068e48b2010-01-26 18:11:27 -0800660 headers = new HashMap<String, String>();
Grace Kloba00f54c52010-01-27 14:53:51 -0800661 while (iter.hasNext()) {
662 String key = iter.next();
663 headers.put(key, pairs.getString(key));
Grace Kloba068e48b2010-01-26 18:11:27 -0800664 }
665 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700666 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800667 } else if (Intent.ACTION_SEARCH.equals(action)
668 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
669 || Intent.ACTION_WEB_SEARCH.equals(action)) {
670 url = intent.getStringExtra(SearchManager.QUERY);
671 if (url != null) {
672 mLastEnteredUrl = url;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800673 // In general, we shouldn't modify URL from Intent.
674 // But currently, we get the user-typed URL from search box as well.
675 url = fixUrl(url);
676 url = smartUrlFilter(url);
Leon Scroggins8d06e362010-03-24 14:45:57 -0400677 final ContentResolver cr = mResolver;
678 final String newUrl = url;
Elliott Slaughter8389e992010-08-20 15:44:08 -0700679 if (mTabControl == null
680 || mTabControl.getCurrentWebView() == null
681 || !mTabControl.getCurrentWebView().isPrivateBrowsingEnabled()) {
682 new AsyncTask<Void, Void, Void>() {
683 @Override
684 protected Void doInBackground(Void... unused) {
685 Browser.updateVisitedHistory(cr, newUrl, false);
686 return null;
687 }
688 }.execute();
689 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800690 String searchSource = "&source=android-" + GOOGLE_SEARCH_SOURCE_SUGGEST + "&";
691 if (url.contains(searchSource)) {
692 String source = null;
693 final Bundle appData = intent.getBundleExtra(SearchManager.APP_DATA);
694 if (appData != null) {
Bjorn Bringert10d1cca2010-02-10 14:22:12 +0000695 source = appData.getString(Search.SOURCE);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800696 }
697 if (TextUtils.isEmpty(source)) {
698 source = GOOGLE_SEARCH_SOURCE_UNKNOWN;
699 }
700 url = url.replace(searchSource, "&source=android-"+source+"&");
701 }
702 }
703 }
704 }
Leon Scroggins58d56c62010-01-28 15:12:40 -0500705 return new UrlData(url, headers, intent);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800706 }
Leon Scroggins58d56c62010-01-28 15:12:40 -0500707 /* package */ void showVoiceTitleBar(String title) {
708 mTitleBar.setInVoiceMode(true);
Leon Scroggins58d56c62010-01-28 15:12:40 -0500709 mTitleBar.setDisplayTitle(title);
Michael Kolba2b2ba82010-08-04 17:54:03 -0700710 mFakeTitleBar.setInVoiceMode(true);
711 mFakeTitleBar.setDisplayTitle(title);
Leon Scroggins58d56c62010-01-28 15:12:40 -0500712 }
713 /* package */ void revertVoiceTitleBar() {
714 mTitleBar.setInVoiceMode(false);
Leon Scroggins003a5dd2010-03-10 12:13:14 -0500715 mTitleBar.setDisplayTitle(mUrl);
Michael Kolba2b2ba82010-08-04 17:54:03 -0700716 mFakeTitleBar.setInVoiceMode(false);
717 mFakeTitleBar.setDisplayTitle(mUrl);
Leon Scroggins58d56c62010-01-28 15:12:40 -0500718 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800719 /* package */ static String fixUrl(String inUrl) {
Cary Clark652ff872009-09-10 13:34:44 -0400720 // FIXME: Converting the url to lower case
721 // duplicates functionality in smartUrlFilter().
722 // However, changing all current callers of fixUrl to
723 // call smartUrlFilter in addition may have unwanted
724 // consequences, and is deferred for now.
725 int colon = inUrl.indexOf(':');
726 boolean allLower = true;
727 for (int index = 0; index < colon; index++) {
728 char ch = inUrl.charAt(index);
729 if (!Character.isLetter(ch)) {
730 break;
731 }
732 allLower &= Character.isLowerCase(ch);
733 if (index == colon - 1 && !allLower) {
734 inUrl = inUrl.substring(0, colon).toLowerCase()
735 + inUrl.substring(colon);
736 }
737 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800738 if (inUrl.startsWith("http://") || inUrl.startsWith("https://"))
739 return inUrl;
740 if (inUrl.startsWith("http:") ||
741 inUrl.startsWith("https:")) {
742 if (inUrl.startsWith("http:/") || inUrl.startsWith("https:/")) {
743 inUrl = inUrl.replaceFirst("/", "//");
744 } else inUrl = inUrl.replaceFirst(":", "://");
745 }
746 return inUrl;
747 }
748
Grace Kloba22ac16e2009-10-07 18:00:23 -0700749 @Override
750 protected void onResume() {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800751 super.onResume();
Dave Bort31a6d1c2009-04-13 15:56:49 -0700752 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800753 Log.v(LOGTAG, "BrowserActivity.onResume: this=" + this);
754 }
755
756 if (!mActivityInPause) {
757 Log.e(LOGTAG, "BrowserActivity is already resumed.");
758 return;
759 }
760
Mike Reed7bfa63b2009-05-28 11:08:32 -0400761 mTabControl.resumeCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800762 mActivityInPause = false;
Mike Reed7bfa63b2009-05-28 11:08:32 -0400763 resumeWebViewTimers();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800764
765 if (mWakeLock.isHeld()) {
766 mHandler.removeMessages(RELEASE_WAKELOCK);
767 mWakeLock.release();
768 }
769
The Android Open Source Project0c908882009-03-03 19:32:16 -0800770 registerReceiver(mNetworkStateIntentReceiver,
771 mNetworkStateChangedFilter);
772 WebView.enablePlatformNotifications();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800773 }
774
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400775 /**
776 * Since the actual title bar is embedded in the WebView, and removing it
Leon Scrogginsfe87bd32009-10-06 10:10:00 -0400777 * would change its appearance, use a different TitleBar to show overlayed
778 * at the top of the screen, when the menu is open or the page is loading.
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400779 */
Michael Kolba2b2ba82010-08-04 17:54:03 -0700780 private TitleBarBase mFakeTitleBar;
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400781
782 /**
783 * Keeps track of whether the options menu is open. This is important in
784 * determining whether to show or hide the title bar overlay.
785 */
786 private boolean mOptionsMenuOpen;
787
788 /**
789 * Only meaningful when mOptionsMenuOpen is true. This variable keeps track
790 * of whether the configuration has changed. The first onMenuOpened call
791 * after a configuration change is simply a reopening of the same menu
792 * (i.e. mIconView did not change).
793 */
794 private boolean mConfigChanged;
795
796 /**
797 * Whether or not the options menu is in its smaller, icon menu form. When
798 * true, we want the title bar overlay to be up. When false, we do not.
799 * Only meaningful if mOptionsMenuOpen is true.
800 */
801 private boolean mIconView;
802
Leon Scrogginsa81a7642009-08-31 17:05:41 -0400803 @Override
804 public boolean onMenuOpened(int featureId, Menu menu) {
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400805 if (Window.FEATURE_OPTIONS_PANEL == featureId) {
806 if (mOptionsMenuOpen) {
807 if (mConfigChanged) {
808 // We do not need to make any changes to the state of the
809 // title bar, since the only thing that happened was a
810 // change in orientation
811 mConfigChanged = false;
812 } else {
813 if (mIconView) {
814 // Switching the menu to expanded view, so hide the
815 // title bar.
816 hideFakeTitleBar();
817 mIconView = false;
818 } else {
819 // Switching the menu back to icon view, so show the
820 // title bar once again.
821 showFakeTitleBar();
822 mIconView = true;
823 }
824 }
825 } else {
826 // The options menu is closed, so open it, and show the title
827 showFakeTitleBar();
828 mOptionsMenuOpen = true;
829 mConfigChanged = false;
830 mIconView = true;
831 }
832 }
Leon Scrogginsa81a7642009-08-31 17:05:41 -0400833 return true;
834 }
835
Michael Kolba2b2ba82010-08-04 17:54:03 -0700836 void showFakeTitleBar() {
837 if (!isFakeTitleBarShowing() && mActiveTabsPage == null && !mActivityInPause) {
Grace Kloba847c25b2010-03-30 16:00:26 -0700838 WebView mainView = mTabControl.getCurrentWebView();
839 // if there is no current WebView, don't show the faked title bar;
Grace Kloba65190702010-04-02 23:37:26 -0700840 if (mainView == null) {
Cary Clarka0464552009-09-29 13:00:45 -0400841 return;
842 }
Leon Scroggins79e36d92010-04-29 16:01:46 +0100843 // Do not need to check for null, since the current tab will have
844 // at least a main WebView, or we would have returned above.
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -0400845 if (isInCustomActionMode()) {
846 // Do not show the fake title bar, while a custom ActionMode
847 // (i.e. find or select) is showing.
Leon Scroggins79e36d92010-04-29 16:01:46 +0100848 return;
849 }
Michael Kolba2b2ba82010-08-04 17:54:03 -0700850 if (mXLargeScreenSize) {
851 mContentView.addView(mFakeTitleBar);
852 mTabBar.onShowTitleBar();
853 } else {
854 WindowManager manager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400855
Michael Kolba2b2ba82010-08-04 17:54:03 -0700856 // Add the title bar to the window manager so it can receive
857 // touches
858 // while the menu is up
859 WindowManager.LayoutParams params =
860 new WindowManager.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
861 ViewGroup.LayoutParams.WRAP_CONTENT,
862 WindowManager.LayoutParams.TYPE_APPLICATION,
863 WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
864 PixelFormat.TRANSLUCENT);
865 params.gravity = Gravity.TOP;
866 boolean atTop = mainView.getScrollY() == 0;
867 params.windowAnimations = atTop ? 0 : R.style.TitleBar;
868 manager.addView(mFakeTitleBar, params);
869 }
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400870 }
871 }
872
873 @Override
874 public void onOptionsMenuClosed(Menu menu) {
875 mOptionsMenuOpen = false;
Leon Scrogginsa27ff192009-09-14 12:58:04 -0400876 if (!mInLoad) {
877 hideFakeTitleBar();
878 } else if (!mIconView) {
879 // The page is currently loading, and we are in expanded mode, so
880 // we were not showing the menu. Show it once again. It will be
881 // removed when the page finishes.
882 showFakeTitleBar();
883 }
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400884 }
Grace Kloba22ac16e2009-10-07 18:00:23 -0700885
Michael Kolba2b2ba82010-08-04 17:54:03 -0700886 void stopScrolling() {
887 ((ScrollWebView) mTabControl.getCurrentWebView()).stopScroll();
888 }
889
890 void hideFakeTitleBar() {
891 if (!isFakeTitleBarShowing()) return;
892 if (mXLargeScreenSize) {
893 mContentView.removeView(mFakeTitleBar);
894 mTabBar.onHideTitleBar();
895 } else {
896 WindowManager.LayoutParams params =
897 (WindowManager.LayoutParams) mFakeTitleBar.getLayoutParams();
898 WebView mainView = mTabControl.getCurrentWebView();
899 // Although we decided whether or not to animate based on the
900 // current
901 // scroll position, the scroll position may have changed since the
902 // fake title bar was displayed. Make sure it has the appropriate
903 // animation/lack thereof before removing.
904 params.windowAnimations =
905 mainView != null && mainView.getScrollY() == 0 ? 0 : R.style.TitleBar;
906 WindowManager manager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
907 manager.updateViewLayout(mFakeTitleBar, params);
908 manager.removeView(mFakeTitleBar);
909 }
910 }
911
912 boolean isFakeTitleBarShowing() {
913 return (mFakeTitleBar.getParent() != null);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400914 }
915
The Android Open Source Project0c908882009-03-03 19:32:16 -0800916 /**
Leon Scrogginsc6fa1102009-09-21 10:40:01 -0400917 * Special method for the fake title bar to call when displaying its context
918 * menu, since it is in its own Window, and its parent does not show a
919 * context menu.
920 */
921 /* package */ void showTitleBarContextMenu() {
Cary Clark65f4a3c2009-09-28 17:05:06 -0400922 if (null == mTitleBar.getParent()) {
923 return;
924 }
Leon Scrogginsc6fa1102009-09-21 10:40:01 -0400925 openContextMenu(mTitleBar);
926 }
927
Leon Scrogginsb2b19f52009-10-09 16:10:00 -0400928 @Override
929 public void onContextMenuClosed(Menu menu) {
930 super.onContextMenuClosed(menu);
931 if (mInLoad) {
932 showFakeTitleBar();
933 }
934 }
935
Leon Scrogginsc6fa1102009-09-21 10:40:01 -0400936 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -0800937 * onSaveInstanceState(Bundle map)
938 * onSaveInstanceState is called right before onStop(). The map contains
939 * the saved state.
940 */
Grace Kloba22ac16e2009-10-07 18:00:23 -0700941 @Override
942 protected void onSaveInstanceState(Bundle outState) {
Dave Bort31a6d1c2009-04-13 15:56:49 -0700943 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800944 Log.v(LOGTAG, "BrowserActivity.onSaveInstanceState: this=" + this);
945 }
946 // the default implementation requires each view to have an id. As the
947 // browser handles the state itself and it doesn't use id for the views,
948 // don't call the default implementation. Otherwise it will trigger the
949 // warning like this, "couldn't save which view has focus because the
950 // focused view XXX has no id".
951
952 // Save all the tabs
953 mTabControl.saveState(outState);
Elliott Slaughter3d6df162010-08-25 13:17:44 -0700954
955 // Save time so that we know how old incognito tabs (if any) are.
956 outState.putSerializable("lastActiveDate", Calendar.getInstance());
The Android Open Source Project0c908882009-03-03 19:32:16 -0800957 }
958
Grace Kloba22ac16e2009-10-07 18:00:23 -0700959 @Override
960 protected void onPause() {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800961 super.onPause();
962
963 if (mActivityInPause) {
964 Log.e(LOGTAG, "BrowserActivity is already paused.");
965 return;
966 }
967
Mike Reed7bfa63b2009-05-28 11:08:32 -0400968 mTabControl.pauseCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800969 mActivityInPause = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -0400970 if (mTabControl.getCurrentIndex() >= 0 && !pauseWebViewTimers()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800971 mWakeLock.acquire();
972 mHandler.sendMessageDelayed(mHandler
973 .obtainMessage(RELEASE_WAKELOCK), WAKELOCK_TIMEOUT);
974 }
975
Leon Scrogginsa2ab6a72009-09-11 11:49:52 -0400976 // FIXME: This removes the active tabs page and resets the menu to
977 // MAIN_MENU. A better solution might be to do this work in onNewIntent
978 // but then we would need to save it in onSaveInstanceState and restore
979 // it in onCreate/onRestoreInstanceState
980 if (mActiveTabsPage != null) {
981 removeActiveTabPage(true);
982 }
983
The Android Open Source Project0c908882009-03-03 19:32:16 -0800984 cancelStopToast();
985
986 // unregister network state listener
987 unregisterReceiver(mNetworkStateIntentReceiver);
988 WebView.disablePlatformNotifications();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800989 }
990
Grace Kloba22ac16e2009-10-07 18:00:23 -0700991 @Override
992 protected void onDestroy() {
Dave Bort31a6d1c2009-04-13 15:56:49 -0700993 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800994 Log.v(LOGTAG, "BrowserActivity.onDestroy: this=" + this);
995 }
996 super.onDestroy();
Grace Kloba0923d692009-09-23 21:37:25 -0700997
Leon Scroggins8d5fa432009-10-02 15:55:59 -0400998 if (mUploadMessage != null) {
999 mUploadMessage.onReceiveValue(null);
1000 mUploadMessage = null;
1001 }
1002
Grace Kloba0923d692009-09-23 21:37:25 -07001003 if (mTabControl == null) return;
1004
Grace Kloba1fc98a32009-10-21 13:23:08 -07001005 // Remove the fake title bar if it is there
1006 hideFakeTitleBar();
1007
The Android Open Source Project0c908882009-03-03 19:32:16 -08001008 // Remove the current tab and sub window
Grace Kloba22ac16e2009-10-07 18:00:23 -07001009 Tab t = mTabControl.getCurrentTab();
Patrick Scottfb5e77f2009-04-08 19:17:37 -07001010 if (t != null) {
1011 dismissSubWindow(t);
1012 removeTabFromContentView(t);
1013 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001014 // Destroy all the tabs
1015 mTabControl.destroy();
1016 WebIconDatabase.getInstance().close();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001017
Bjorn Bringerta7611812010-03-24 11:12:02 +00001018 // Stop watching the default geolocation permissions
1019 mSystemAllowGeolocationOrigins.stop();
1020 mSystemAllowGeolocationOrigins = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001021 }
1022
1023 @Override
1024 public void onConfigurationChanged(Configuration newConfig) {
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04001025 mConfigChanged = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001026 super.onConfigurationChanged(newConfig);
1027
1028 if (mPageInfoDialog != null) {
1029 mPageInfoDialog.dismiss();
1030 showPageInfo(
1031 mPageInfoView,
Leon Scrogginsc7b92f82010-01-11 18:17:31 -05001032 mPageInfoFromShowSSLCertificateOnError);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001033 }
1034 if (mSSLCertificateDialog != null) {
1035 mSSLCertificateDialog.dismiss();
1036 showSSLCertificate(
1037 mSSLCertificateView);
1038 }
1039 if (mSSLCertificateOnErrorDialog != null) {
1040 mSSLCertificateOnErrorDialog.dismiss();
1041 showSSLCertificateOnError(
1042 mSSLCertificateOnErrorView,
1043 mSSLCertificateOnErrorHandler,
1044 mSSLCertificateOnErrorError);
1045 }
1046 if (mHttpAuthenticationDialog != null) {
1047 String title = ((TextView) mHttpAuthenticationDialog
1048 .findViewById(com.android.internal.R.id.alertTitle)).getText()
1049 .toString();
1050 String name = ((TextView) mHttpAuthenticationDialog
1051 .findViewById(R.id.username_edit)).getText().toString();
1052 String password = ((TextView) mHttpAuthenticationDialog
1053 .findViewById(R.id.password_edit)).getText().toString();
1054 int focusId = mHttpAuthenticationDialog.getCurrentFocus()
1055 .getId();
1056 mHttpAuthenticationDialog.dismiss();
1057 showHttpAuthentication(mHttpAuthHandler, null, null, title,
1058 name, password, focusId);
1059 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001060 }
1061
Grace Kloba22ac16e2009-10-07 18:00:23 -07001062 @Override
1063 public void onLowMemory() {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001064 super.onLowMemory();
1065 mTabControl.freeMemory();
1066 }
1067
Cary Clarkff4d92c2010-03-25 11:17:03 -04001068 private void resumeWebViewTimers() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001069 Tab tab = mTabControl.getCurrentTab();
Cary Clarkff4d92c2010-03-25 11:17:03 -04001070 if (tab == null) return; // monkey can trigger this
Grace Kloba22ac16e2009-10-07 18:00:23 -07001071 boolean inLoad = tab.inLoad();
1072 if ((!mActivityInPause && !inLoad) || (mActivityInPause && inLoad)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001073 CookieSyncManager.getInstance().startSync();
Grace Kloba22ac16e2009-10-07 18:00:23 -07001074 WebView w = tab.getWebView();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001075 if (w != null) {
1076 w.resumeTimers();
1077 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001078 }
1079 }
1080
Mike Reed7bfa63b2009-05-28 11:08:32 -04001081 private boolean pauseWebViewTimers() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001082 Tab tab = mTabControl.getCurrentTab();
1083 boolean inLoad = tab.inLoad();
1084 if (mActivityInPause && !inLoad) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001085 CookieSyncManager.getInstance().stopSync();
1086 WebView w = mTabControl.getCurrentWebView();
1087 if (w != null) {
1088 w.pauseTimers();
1089 }
1090 return true;
1091 } else {
1092 return false;
1093 }
1094 }
1095
The Android Open Source Project0c908882009-03-03 19:32:16 -08001096 // Open the icon database and retain all the icons for visited sites.
1097 private void retainIconsOnStartup() {
1098 final WebIconDatabase db = WebIconDatabase.getInstance();
1099 db.open(getDir("icons", 0).getPath());
Leon Scroggins2c0f6112010-03-12 18:09:39 -05001100 Cursor c = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001101 try {
Leon Scroggins2c0f6112010-03-12 18:09:39 -05001102 c = Browser.getAllBookmarks(mResolver);
1103 if (c.moveToFirst()) {
1104 int urlIndex = c.getColumnIndex(Browser.BookmarkColumns.URL);
1105 do {
1106 String url = c.getString(urlIndex);
1107 db.retainIconForPageUrl(url);
1108 } while (c.moveToNext());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001109 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001110 } catch (IllegalStateException e) {
1111 Log.e(LOGTAG, "retainIconsOnStartup", e);
Leon Scroggins2c0f6112010-03-12 18:09:39 -05001112 } finally {
1113 if (c!= null) c.close();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001114 }
1115 }
1116
1117 // Helper method for getting the top window.
1118 WebView getTopWindow() {
1119 return mTabControl.getCurrentTopWebView();
1120 }
1121
Grace Kloba22ac16e2009-10-07 18:00:23 -07001122 TabControl getTabControl() {
1123 return mTabControl;
1124 }
1125
The Android Open Source Project0c908882009-03-03 19:32:16 -08001126 @Override
1127 public boolean onCreateOptionsMenu(Menu menu) {
1128 super.onCreateOptionsMenu(menu);
1129
1130 MenuInflater inflater = getMenuInflater();
1131 inflater.inflate(R.menu.browser, menu);
1132 mMenu = menu;
1133 updateInLoadMenuItems();
1134 return true;
1135 }
1136
1137 /**
1138 * As the menu can be open when loading state changes
1139 * we must manually update the state of the stop/reload menu
1140 * item
1141 */
1142 private void updateInLoadMenuItems() {
1143 if (mMenu == null) {
1144 return;
1145 }
Michael Kolbe0a36662010-06-29 10:37:12 -07001146 MenuItem dest = mMenu.findItem(R.id.stop_reload_menu_id);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001147 MenuItem src = mInLoad ?
1148 mMenu.findItem(R.id.stop_menu_id):
Michael Kolbe0a36662010-06-29 10:37:12 -07001149 mMenu.findItem(R.id.reload_menu_id);
1150 if (src != null) {
1151 dest.setIcon(src.getIcon());
1152 dest.setTitle(src.getTitle());
1153 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001154 }
1155
1156 @Override
1157 public boolean onContextItemSelected(MenuItem item) {
1158 // chording is not an issue with context menus, but we use the same
1159 // options selector, so set mCanChord to true so we can access them.
1160 mCanChord = true;
1161 int id = item.getItemId();
Leon Scroggins96afcb12009-12-10 12:35:56 -05001162 boolean result = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001163 switch (id) {
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001164 // For the context menu from the title bar
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001165 case R.id.title_bar_copy_page_url:
Leon Scroggins96afcb12009-12-10 12:35:56 -05001166 Tab currentTab = mTabControl.getCurrentTab();
1167 if (null == currentTab) {
1168 result = false;
1169 break;
1170 }
1171 WebView mainView = currentTab.getWebView();
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001172 if (null == mainView) {
Leon Scroggins96afcb12009-12-10 12:35:56 -05001173 result = false;
1174 break;
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001175 }
Leon Scroggins96afcb12009-12-10 12:35:56 -05001176 copy(mainView.getUrl());
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001177 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001178 // -- Browser context menu
1179 case R.id.open_context_menu_id:
The Android Open Source Project0c908882009-03-03 19:32:16 -08001180 case R.id.bookmark_context_menu_id:
1181 case R.id.save_link_context_menu_id:
1182 case R.id.share_link_context_menu_id:
1183 case R.id.copy_link_context_menu_id:
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001184 final WebView webView = getTopWindow();
1185 if (null == webView) {
Leon Scroggins96afcb12009-12-10 12:35:56 -05001186 result = false;
1187 break;
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001188 }
1189 final HashMap hrefMap = new HashMap();
1190 hrefMap.put("webview", webView);
1191 final Message msg = mHandler.obtainMessage(
1192 FOCUS_NODE_HREF, id, 0, hrefMap);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001193 webView.requestFocusNodeHref(msg);
1194 break;
1195
1196 default:
1197 // For other context menus
Leon Scroggins96afcb12009-12-10 12:35:56 -05001198 result = onOptionsItemSelected(item);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001199 }
1200 mCanChord = false;
Leon Scroggins96afcb12009-12-10 12:35:56 -05001201 return result;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001202 }
1203
1204 private Bundle createGoogleSearchSourceBundle(String source) {
1205 Bundle bundle = new Bundle();
Bjorn Bringert10d1cca2010-02-10 14:22:12 +00001206 bundle.putString(Search.SOURCE, source);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001207 return bundle;
1208 }
1209
Leon Scroggins8ad29922010-02-16 12:33:55 -05001210 /* package */ void editUrl() {
Leon Scroggins68579392009-09-15 15:31:54 -04001211 if (mOptionsMenuOpen) closeOptionsMenu();
Leon Scroggins5bbe9802009-07-31 13:10:55 -04001212 String url = (getTopWindow() == null) ? null : getTopWindow().getUrl();
Grace Kloba83f47342009-07-20 10:44:31 -07001213 startSearch(mSettings.getHomePage().equals(url) ? null : url, true,
Leon Scroggins8ad29922010-02-16 12:33:55 -05001214 null, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001215 }
1216
Leon Scroggins8ad29922010-02-16 12:33:55 -05001217 /**
1218 * Overriding this to insert a local information bundle
1219 */
The Android Open Source Project0c908882009-03-03 19:32:16 -08001220 @Override
1221 public void startSearch(String initialQuery, boolean selectInitialQuery,
1222 Bundle appSearchData, boolean globalSearch) {
1223 if (appSearchData == null) {
1224 appSearchData = createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_TYPE);
1225 }
1226 super.startSearch(initialQuery, selectInitialQuery, appSearchData, globalSearch);
1227 }
1228
Leon Scroggins1f005d32009-08-10 17:36:42 -04001229 /**
1230 * Switch tabs. Called by the TitleBarSet when sliding the title bar
1231 * results in changing tabs.
Leon Scroggins160a7e72009-08-14 18:28:01 -04001232 * @param index Index of the tab to change to, as defined by
1233 * mTabControl.getTabIndex(Tab t).
1234 * @return boolean True if we successfully switched to a different tab. If
1235 * the indexth tab is null, or if that tab is the same as
1236 * the current one, return false.
Leon Scroggins1f005d32009-08-10 17:36:42 -04001237 */
Leon Scroggins160a7e72009-08-14 18:28:01 -04001238 /* package */ boolean switchToTab(int index) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001239 Tab tab = mTabControl.getTab(index);
1240 Tab currentTab = mTabControl.getCurrentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04001241 if (tab == null || tab == currentTab) {
Leon Scroggins160a7e72009-08-14 18:28:01 -04001242 return false;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001243 }
1244 if (currentTab != null) {
1245 // currentTab may be null if it was just removed. In that case,
1246 // we do not need to remove it
1247 removeTabFromContentView(currentTab);
1248 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001249 mTabControl.setCurrentTab(tab);
1250 attachTabToContentView(tab);
Grace Klobaeb6eef42009-09-15 17:56:32 -07001251 resetTitleIconAndProgress();
1252 updateLockIconToLatest();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001253 return true;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001254 }
1255
Grace Kloba22ac16e2009-10-07 18:00:23 -07001256 /* package */ Tab openTabToHomePage() {
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001257 return openTabAndShow(mSettings.getHomePage(), false, null);
1258 }
1259
Leon Scroggins1f005d32009-08-10 17:36:42 -04001260 /* package */ void closeCurrentWindow() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001261 final Tab current = mTabControl.getCurrentTab();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001262 if (mTabControl.getTabCount() == 1) {
Leon Scroggins30444232009-09-04 18:36:20 -04001263 // This is the last tab. Open a new one, with the home
1264 // page and close the current one.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001265 openTabToHomePage();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001266 closeTab(current);
Leon Scroggins160a7e72009-08-14 18:28:01 -04001267 return;
1268 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07001269 final Tab parent = current.getParentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04001270 int indexToShow = -1;
1271 if (parent != null) {
1272 indexToShow = mTabControl.getTabIndex(parent);
1273 } else {
Leon Scroggins160a7e72009-08-14 18:28:01 -04001274 final int currentIndex = mTabControl.getCurrentIndex();
1275 // Try to move to the tab to the right
1276 indexToShow = currentIndex + 1;
1277 if (indexToShow > mTabControl.getTabCount() - 1) {
1278 // Try to move to the tab to the left
1279 indexToShow = currentIndex - 1;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001280 }
1281 }
Leon Scroggins160a7e72009-08-14 18:28:01 -04001282 if (switchToTab(indexToShow)) {
1283 // Close window
1284 closeTab(current);
1285 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001286 }
1287
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001288 private ActiveTabsPage mActiveTabsPage;
1289
1290 /**
1291 * Remove the active tabs page.
1292 * @param needToAttach If true, the active tabs page did not attach a tab
1293 * to the content view, so we need to do that here.
1294 */
1295 /* package */ void removeActiveTabPage(boolean needToAttach) {
1296 mContentView.removeView(mActiveTabsPage);
Leon Scrogginsd746a942010-05-19 13:21:44 -04001297 mTitleBar.setVisibility(View.VISIBLE);
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001298 mActiveTabsPage = null;
1299 mMenuState = R.id.MAIN_MENU;
1300 if (needToAttach) {
1301 attachTabToContentView(mTabControl.getCurrentTab());
1302 }
1303 getTopWindow().requestFocus();
1304 }
1305
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04001306 @Override
1307 public ActionMode onStartActionMode(ActionMode.Callback callback) {
Leon Scroggins4fc12cb2010-08-24 14:24:05 -04001308 mActionMode = super.onStartActionMode(callback);
1309 hideFakeTitleBar();
1310 // Would like to change the MENU, but onEndActionMode may not be called
1311 return mActionMode;
Cary Clark01cfcdd2010-06-04 16:36:45 -04001312 }
1313
The Android Open Source Project0c908882009-03-03 19:32:16 -08001314 @Override
1315 public boolean onOptionsItemSelected(MenuItem item) {
Michael Kolbed217742010-08-10 17:52:34 -07001316 // check the action bar button before mCanChord check, as the prepare call
1317 // doesn't come for action bar buttons
1318 if (item.getItemId() == R.id.newtab) {
Michael Kolb300b7f02010-08-25 13:47:24 -07001319 openTabToHomePage();
1320 mHandler.sendMessage(mHandler.obtainMessage(OPEN_BOOKMARKS));
Michael Kolbed217742010-08-10 17:52:34 -07001321 return true;
1322 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001323 if (!mCanChord) {
1324 // The user has already fired a shortcut with this hold down of the
1325 // menu key.
1326 return false;
1327 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001328 if (null == getTopWindow()) {
Leon Scroggins0d7ae0e2009-06-05 11:04:45 -04001329 return false;
1330 }
Grace Kloba6ee9c492009-07-13 10:04:34 -07001331 if (mMenuIsDown) {
1332 // The shortcut action consumes the MENU. Even if it is still down,
1333 // it won't trigger the next shortcut action. In the case of the
1334 // shortcut action triggering a new activity, like Bookmarks, we
1335 // won't get onKeyUp for MENU. So it is important to reset it here.
1336 mMenuIsDown = false;
1337 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001338 switch (item.getItemId()) {
1339 // -- Main menu
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001340 case R.id.new_tab_menu_id:
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001341 openTabToHomePage();
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001342 break;
1343
Michael Kolbae62fd42010-08-18 16:33:28 -07001344 case R.id.incognito_menu_id:
1345 openIncognitoTab();
1346 break;
1347
Leon Scroggins64b80f32009-08-07 12:03:34 -04001348 case R.id.goto_menu_id:
Leon Scroggins8ad29922010-02-16 12:33:55 -05001349 editUrl();
Leon Scrogginsb3a5bed2009-09-28 11:21:56 -04001350 break;
1351
1352 case R.id.bookmarks_menu_id:
Michael Kolb68792c82010-08-09 16:39:18 -07001353 bookmarksOrHistoryPicker(false, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001354 break;
1355
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001356 case R.id.active_tabs_menu_id:
1357 mActiveTabsPage = new ActiveTabsPage(this, mTabControl);
1358 removeTabFromContentView(mTabControl.getCurrentTab());
Leon Scrogginsd746a942010-05-19 13:21:44 -04001359 mTitleBar.setVisibility(View.GONE);
Leon Scroggins43de6162009-09-14 19:59:58 -04001360 hideFakeTitleBar();
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001361 mContentView.addView(mActiveTabsPage, COVER_SCREEN_PARAMS);
1362 mActiveTabsPage.requestFocus();
1363 mMenuState = EMPTY_MENU;
1364 break;
1365
Leon Scroggins1f005d32009-08-10 17:36:42 -04001366 case R.id.add_bookmark_menu_id:
Leon Scroggins571b3762010-05-26 10:25:01 -04001367 bookmarkCurrentPage();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001368 break;
1369
1370 case R.id.stop_reload_menu_id:
1371 if (mInLoad) {
1372 stopLoading();
1373 } else {
1374 getTopWindow().reload();
1375 }
1376 break;
1377
1378 case R.id.back_menu_id:
1379 getTopWindow().goBack();
1380 break;
1381
1382 case R.id.forward_menu_id:
1383 getTopWindow().goForward();
1384 break;
1385
1386 case R.id.close_menu_id:
1387 // Close the subwindow if it exists.
1388 if (mTabControl.getCurrentSubWindow() != null) {
1389 dismissSubWindow(mTabControl.getCurrentTab());
1390 break;
1391 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001392 closeCurrentWindow();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001393 break;
1394
1395 case R.id.homepage_menu_id:
Grace Kloba22ac16e2009-10-07 18:00:23 -07001396 Tab current = mTabControl.getCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001397 if (current != null) {
1398 dismissSubWindow(current);
Leon Scroggins92472e82010-02-17 16:32:28 -05001399 loadUrl(current.getWebView(), mSettings.getHomePage());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001400 }
1401 break;
1402
1403 case R.id.preferences_menu_id:
1404 Intent intent = new Intent(this,
1405 BrowserPreferencesPage.class);
Leon Scrogginsd5304942009-12-10 16:11:39 -05001406 intent.putExtra(BrowserPreferencesPage.CURRENT_PAGE,
1407 getTopWindow().getUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001408 startActivityForResult(intent, PREFERENCES_PAGE);
1409 break;
1410
1411 case R.id.find_menu_id:
Leon Scroggins4fc12cb2010-08-24 14:24:05 -04001412 getTopWindow().showFindDialog(null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001413 break;
1414
Elliott Slaughter0ced08c2010-06-30 11:40:42 -07001415 case R.id.save_webarchive_menu_id:
1416 if (LOGD_ENABLED) {
1417 Log.d(LOGTAG, "Save as Web Archive");
1418 }
Elliott Slaughteraba242c2010-09-01 16:21:07 -07001419 String state = Environment.getExternalStorageState();
1420 if (Environment.MEDIA_MOUNTED.equals(state)) {
1421 String directory = Environment.getExternalStoragePublicDirectory(
1422 Environment.DIRECTORY_DOWNLOADS).getAbsolutePath() + File.separator;
1423 getTopWindow().saveWebArchive(directory, true, new ValueCallback<String>() {
1424 @Override
1425 public void onReceiveValue(String value) {
1426 if (value != null) {
1427 Toast.makeText(BrowserActivity.this, R.string.webarchive_saved,
1428 Toast.LENGTH_SHORT).show();
1429 } else {
1430 Toast.makeText(BrowserActivity.this, R.string.webarchive_failed,
1431 Toast.LENGTH_SHORT).show();
1432 }
Elliott Slaughter0ced08c2010-06-30 11:40:42 -07001433 }
Elliott Slaughteraba242c2010-09-01 16:21:07 -07001434 });
1435 } else {
1436 Toast.makeText(BrowserActivity.this, R.string.webarchive_failed,
1437 Toast.LENGTH_SHORT).show();
1438 }
Elliott Slaughter0ced08c2010-06-30 11:40:42 -07001439 break;
1440
The Android Open Source Project0c908882009-03-03 19:32:16 -08001441 case R.id.page_info_menu_id:
1442 showPageInfo(mTabControl.getCurrentTab(), false);
1443 break;
1444
1445 case R.id.classic_history_menu_id:
Michael Kolb68792c82010-08-09 16:39:18 -07001446 bookmarksOrHistoryPicker(true, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001447 break;
1448
Leon Scroggins96afcb12009-12-10 12:35:56 -05001449 case R.id.title_bar_share_page_url:
The Android Open Source Project0c908882009-03-03 19:32:16 -08001450 case R.id.share_page_menu_id:
Leon Scroggins96afcb12009-12-10 12:35:56 -05001451 Tab currentTab = mTabControl.getCurrentTab();
1452 if (null == currentTab) {
1453 mCanChord = false;
1454 return false;
1455 }
1456 currentTab.populatePickerData();
1457 sharePage(this, currentTab.getTitle(),
1458 currentTab.getUrl(), currentTab.getFavicon(),
Ben Murdoch87cc65d2010-06-29 20:34:10 +01001459 createScreenshot(currentTab.getWebView(), getDesiredThumbnailWidth(this),
1460 getDesiredThumbnailHeight(this)));
The Android Open Source Project0c908882009-03-03 19:32:16 -08001461 break;
1462
1463 case R.id.dump_nav_menu_id:
1464 getTopWindow().debugDump();
1465 break;
1466
Andrei Popescu7a8b88b2010-02-02 00:30:38 +00001467 case R.id.dump_counters_menu_id:
1468 getTopWindow().dumpV8Counters();
1469 break;
1470
The Android Open Source Project0c908882009-03-03 19:32:16 -08001471 case R.id.zoom_in_menu_id:
1472 getTopWindow().zoomIn();
1473 break;
1474
1475 case R.id.zoom_out_menu_id:
1476 getTopWindow().zoomOut();
1477 break;
1478
1479 case R.id.view_downloads_menu_id:
1480 viewDownloads(null);
1481 break;
1482
The Android Open Source Project0c908882009-03-03 19:32:16 -08001483 case R.id.window_one_menu_id:
1484 case R.id.window_two_menu_id:
1485 case R.id.window_three_menu_id:
1486 case R.id.window_four_menu_id:
1487 case R.id.window_five_menu_id:
1488 case R.id.window_six_menu_id:
1489 case R.id.window_seven_menu_id:
1490 case R.id.window_eight_menu_id:
1491 {
1492 int menuid = item.getItemId();
1493 for (int id = 0; id < WINDOW_SHORTCUT_ID_ARRAY.length; id++) {
1494 if (WINDOW_SHORTCUT_ID_ARRAY[id] == menuid) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001495 Tab desiredTab = mTabControl.getTab(id);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001496 if (desiredTab != null &&
1497 desiredTab != mTabControl.getCurrentTab()) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001498 switchToTab(id);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001499 }
1500 break;
1501 }
1502 }
1503 }
1504 break;
1505
1506 default:
1507 if (!super.onOptionsItemSelected(item)) {
1508 return false;
1509 }
1510 // Otherwise fall through.
1511 }
1512 mCanChord = false;
1513 return true;
1514 }
1515
Leon Scroggins571b3762010-05-26 10:25:01 -04001516 /* package */ void bookmarkCurrentPage() {
1517 Intent i = new Intent(BrowserActivity.this,
1518 AddBookmarkPage.class);
1519 WebView w = getTopWindow();
1520 i.putExtra("url", w.getUrl());
1521 i.putExtra("title", w.getTitle());
1522 i.putExtra("touch_icon_url", w.getTouchIconUrl());
Ben Murdoch87cc65d2010-06-29 20:34:10 +01001523 i.putExtra("thumbnail", createScreenshot(w, getDesiredThumbnailWidth(this),
1524 getDesiredThumbnailHeight(this)));
Ben Murdocheecb4e62010-07-06 16:30:38 +01001525 i.putExtra("url_editable", false);
Leon Scroggins571b3762010-05-26 10:25:01 -04001526 startActivity(i);
1527 }
1528
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04001529 /*
1530 * True if a custom ActionMode (i.e. find or select) is in use.
1531 */
1532 private boolean isInCustomActionMode() {
1533 return mActionMode != null;
Cary Clark01cfcdd2010-06-04 16:36:45 -04001534 }
1535
1536 /*
Leon Scroggins4fc12cb2010-08-24 14:24:05 -04001537 * End the current ActionMode.
Cary Clark01cfcdd2010-06-04 16:36:45 -04001538 */
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04001539 void endActionMode() {
1540 if (mActionMode != null) {
Leon Scroggins4fc12cb2010-08-24 14:24:05 -04001541 ActionMode mode = mActionMode;
1542 onEndActionMode();
1543 mode.finish();
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04001544 }
1545 }
1546
1547 /*
1548 * Called by find and select when they are finished. Replace title bars
1549 * as necessary.
1550 */
1551 public void onEndActionMode() {
1552 if (!isInCustomActionMode()) return;
Leon Scroggins79e36d92010-04-29 16:01:46 +01001553 if (mInLoad) {
1554 // The title bar was hidden, because otherwise it would cover up the
Michael Kolba2b2ba82010-08-04 17:54:03 -07001555 // find or select dialog. Now that the dialog has been removed,
Cary Clark01cfcdd2010-06-04 16:36:45 -04001556 // show the fake title bar once again.
Leon Scroggins79e36d92010-04-29 16:01:46 +01001557 showFakeTitleBar();
1558 }
Leon Scroggins4fc12cb2010-08-24 14:24:05 -04001559 // Would like to return the menu state to normal, but this does not
1560 // necessarily get called.
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04001561 mActionMode = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001562 }
1563
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04001564 // For select and find, we keep track of the ActionMode so that
1565 // finish() can be called as desired.
1566 private ActionMode mActionMode;
1567
Grace Kloba22ac16e2009-10-07 18:00:23 -07001568 @Override
1569 public boolean onPrepareOptionsMenu(Menu menu) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001570 // This happens when the user begins to hold down the menu key, so
1571 // allow them to chord to get a shortcut.
1572 mCanChord = true;
1573 // Note: setVisible will decide whether an item is visible; while
1574 // setEnabled() will decide whether an item is enabled, which also means
1575 // whether the matching shortcut key will function.
1576 super.onPrepareOptionsMenu(menu);
1577 switch (mMenuState) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001578 case EMPTY_MENU:
1579 if (mCurrentMenuState != mMenuState) {
1580 menu.setGroupVisible(R.id.MAIN_MENU, false);
1581 menu.setGroupEnabled(R.id.MAIN_MENU, false);
1582 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001583 }
1584 break;
1585 default:
1586 if (mCurrentMenuState != mMenuState) {
1587 menu.setGroupVisible(R.id.MAIN_MENU, true);
1588 menu.setGroupEnabled(R.id.MAIN_MENU, true);
1589 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001590 }
1591 final WebView w = getTopWindow();
1592 boolean canGoBack = false;
1593 boolean canGoForward = false;
1594 boolean isHome = false;
1595 if (w != null) {
1596 canGoBack = w.canGoBack();
1597 canGoForward = w.canGoForward();
1598 isHome = mSettings.getHomePage().equals(w.getUrl());
1599 }
1600 final MenuItem back = menu.findItem(R.id.back_menu_id);
1601 back.setEnabled(canGoBack);
1602
1603 final MenuItem home = menu.findItem(R.id.homepage_menu_id);
1604 home.setEnabled(!isHome);
1605
Michael Kolbe0a36662010-06-29 10:37:12 -07001606 final MenuItem forward = menu.findItem(R.id.forward_menu_id);
1607 forward.setEnabled(canGoForward);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001608
Michael Kolbed217742010-08-10 17:52:34 -07001609 if (!mXLargeScreenSize) {
1610 final MenuItem newtab = menu.findItem(R.id.new_tab_menu_id);
1611 newtab.setEnabled(mTabControl.canCreateNewTab());
1612 }
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001613
The Android Open Source Project0c908882009-03-03 19:32:16 -08001614 // decide whether to show the share link option
1615 PackageManager pm = getPackageManager();
1616 Intent send = new Intent(Intent.ACTION_SEND);
1617 send.setType("text/plain");
1618 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1619 menu.findItem(R.id.share_page_menu_id).setVisible(ri != null);
1620
The Android Open Source Project0c908882009-03-03 19:32:16 -08001621 boolean isNavDump = mSettings.isNavDump();
1622 final MenuItem nav = menu.findItem(R.id.dump_nav_menu_id);
1623 nav.setVisible(isNavDump);
1624 nav.setEnabled(isNavDump);
Andrei Popescu7a8b88b2010-02-02 00:30:38 +00001625
1626 boolean showDebugSettings = mSettings.showDebugSettings();
1627 final MenuItem counter = menu.findItem(R.id.dump_counters_menu_id);
1628 counter.setVisible(showDebugSettings);
1629 counter.setEnabled(showDebugSettings);
1630
The Android Open Source Project0c908882009-03-03 19:32:16 -08001631 break;
1632 }
1633 mCurrentMenuState = mMenuState;
1634 return true;
1635 }
1636
1637 @Override
1638 public void onCreateContextMenu(ContextMenu menu, View v,
1639 ContextMenuInfo menuInfo) {
Leon Scroggins571b3762010-05-26 10:25:01 -04001640 if (v instanceof TitleBarBase) {
Leon Scroggins4e9f89b2010-02-22 16:54:14 -05001641 return;
1642 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001643 WebView webview = (WebView) v;
1644 WebView.HitTestResult result = webview.getHitTestResult();
1645 if (result == null) {
1646 return;
1647 }
1648
1649 int type = result.getType();
1650 if (type == WebView.HitTestResult.UNKNOWN_TYPE) {
1651 Log.w(LOGTAG,
1652 "We should not show context menu when nothing is touched");
1653 return;
1654 }
1655 if (type == WebView.HitTestResult.EDIT_TEXT_TYPE) {
1656 // let TextView handles context menu
1657 return;
1658 }
1659
1660 // Note, http://b/issue?id=1106666 is requesting that
1661 // an inflated menu can be used again. This is not available
1662 // yet, so inflate each time (yuk!)
1663 MenuInflater inflater = getMenuInflater();
1664 inflater.inflate(R.menu.browsercontext, menu);
1665
1666 // Show the correct menu group
Leon Scroggins III9e997c72010-05-26 13:25:16 -04001667 final String extra = result.getExtra();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001668 menu.setGroupVisible(R.id.PHONE_MENU,
1669 type == WebView.HitTestResult.PHONE_TYPE);
1670 menu.setGroupVisible(R.id.EMAIL_MENU,
1671 type == WebView.HitTestResult.EMAIL_TYPE);
1672 menu.setGroupVisible(R.id.GEO_MENU,
1673 type == WebView.HitTestResult.GEO_TYPE);
1674 menu.setGroupVisible(R.id.IMAGE_MENU,
1675 type == WebView.HitTestResult.IMAGE_TYPE
1676 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1677 menu.setGroupVisible(R.id.ANCHOR_MENU,
1678 type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1679 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1680
1681 // Setup custom handling depending on the type
1682 switch (type) {
1683 case WebView.HitTestResult.PHONE_TYPE:
1684 menu.setHeaderTitle(Uri.decode(extra));
1685 menu.findItem(R.id.dial_context_menu_id).setIntent(
1686 new Intent(Intent.ACTION_VIEW, Uri
1687 .parse(WebView.SCHEME_TEL + extra)));
1688 Intent addIntent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
1689 addIntent.putExtra(Insert.PHONE, Uri.decode(extra));
Cary Clark5e335a32009-09-22 14:53:11 -04001690 addIntent.setType(ContactsContract.Contacts.CONTENT_ITEM_TYPE);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001691 menu.findItem(R.id.add_contact_context_menu_id).setIntent(
1692 addIntent);
1693 menu.findItem(R.id.copy_phone_context_menu_id).setOnMenuItemClickListener(
1694 new Copy(extra));
1695 break;
1696
1697 case WebView.HitTestResult.EMAIL_TYPE:
1698 menu.setHeaderTitle(extra);
1699 menu.findItem(R.id.email_context_menu_id).setIntent(
1700 new Intent(Intent.ACTION_VIEW, Uri
1701 .parse(WebView.SCHEME_MAILTO + extra)));
1702 menu.findItem(R.id.copy_mail_context_menu_id).setOnMenuItemClickListener(
1703 new Copy(extra));
1704 break;
1705
1706 case WebView.HitTestResult.GEO_TYPE:
1707 menu.setHeaderTitle(extra);
1708 menu.findItem(R.id.map_context_menu_id).setIntent(
1709 new Intent(Intent.ACTION_VIEW, Uri
1710 .parse(WebView.SCHEME_GEO
1711 + URLEncoder.encode(extra))));
1712 menu.findItem(R.id.copy_geo_context_menu_id).setOnMenuItemClickListener(
1713 new Copy(extra));
1714 break;
1715
1716 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1717 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
1718 TextView titleView = (TextView) LayoutInflater.from(this)
1719 .inflate(android.R.layout.browser_link_context_header,
1720 null);
1721 titleView.setText(extra);
1722 menu.setHeaderView(titleView);
1723 // decide whether to show the open link in new tab option
Leon Scroggins III9e997c72010-05-26 13:25:16 -04001724 boolean showNewTab = mTabControl.canCreateNewTab();
1725 MenuItem newTabItem
1726 = menu.findItem(R.id.open_newtab_context_menu_id);
1727 newTabItem.setVisible(showNewTab);
1728 if (showNewTab) {
1729 newTabItem.setOnMenuItemClickListener(
1730 new MenuItem.OnMenuItemClickListener() {
1731 public boolean onMenuItemClick(MenuItem item) {
1732 final Tab parent = mTabControl.getCurrentTab();
Michael Kolb68792c82010-08-09 16:39:18 -07001733 final Tab newTab = openTab(extra, false);
Leon Scroggins III9e997c72010-05-26 13:25:16 -04001734 if (newTab != parent) {
1735 parent.addChildTab(newTab);
1736 }
1737 return true;
1738 }
1739 });
1740 }
Ben Murdochde353622009-10-12 10:29:00 +01001741 menu.findItem(R.id.bookmark_context_menu_id).setVisible(
1742 Bookmarks.urlHasAcceptableScheme(extra));
The Android Open Source Project0c908882009-03-03 19:32:16 -08001743 PackageManager pm = getPackageManager();
1744 Intent send = new Intent(Intent.ACTION_SEND);
1745 send.setType("text/plain");
1746 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1747 menu.findItem(R.id.share_link_context_menu_id).setVisible(ri != null);
1748 if (type == WebView.HitTestResult.SRC_ANCHOR_TYPE) {
1749 break;
1750 }
1751 // otherwise fall through to handle image part
1752 case WebView.HitTestResult.IMAGE_TYPE:
1753 if (type == WebView.HitTestResult.IMAGE_TYPE) {
1754 menu.setHeaderTitle(extra);
1755 }
1756 menu.findItem(R.id.view_image_context_menu_id).setIntent(
1757 new Intent(Intent.ACTION_VIEW, Uri.parse(extra)));
1758 menu.findItem(R.id.download_context_menu_id).
1759 setOnMenuItemClickListener(new Download(extra));
Ben Murdoch4f75ba22009-10-27 11:48:28 +00001760 menu.findItem(R.id.set_wallpaper_context_menu_id).
1761 setOnMenuItemClickListener(new SetAsWallpaper(extra));
The Android Open Source Project0c908882009-03-03 19:32:16 -08001762 break;
1763
1764 default:
1765 Log.w(LOGTAG, "We should not get here.");
1766 break;
1767 }
Leon Scrogginsb2b19f52009-10-09 16:10:00 -04001768 hideFakeTitleBar();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001769 }
1770
The Android Open Source Project0c908882009-03-03 19:32:16 -08001771 // Attach the given tab to the content view.
Grace Klobac928c302009-09-17 11:51:21 -07001772 // this should only be called for the current tab.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001773 private void attachTabToContentView(Tab t) {
Steve Block2bc69912009-07-30 14:45:13 +01001774 // Attach the container that contains the main WebView and any other UI
1775 // associated with the tab.
Patrick Scottd0119532009-09-17 08:00:31 -04001776 t.attachTabToContentView(mContentView);
Ben Murdochbff2d602009-07-01 20:19:05 +01001777
1778 if (mShouldShowErrorConsole) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001779 ErrorConsoleView errorConsole = t.getErrorConsole(true);
Ben Murdochbff2d602009-07-01 20:19:05 +01001780 if (errorConsole.numberOfErrors() == 0) {
1781 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
1782 } else {
1783 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
1784 }
1785
1786 mErrorConsoleContainer.addView(errorConsole,
Romain Guy15b8ec62010-01-08 15:06:43 -08001787 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
Ben Murdochbff2d602009-07-01 20:19:05 +01001788 ViewGroup.LayoutParams.WRAP_CONTENT));
1789 }
1790
Michael Kolba2b2ba82010-08-04 17:54:03 -07001791 WebView view = t.getWebView();
1792 view.setEmbeddedTitleBar(mTitleBar);
Leon Scroggins58d56c62010-01-28 15:12:40 -05001793 if (t.isInVoiceSearchMode()) {
1794 showVoiceTitleBar(t.getVoiceDisplayTitle());
1795 } else {
1796 revertVoiceTitleBar();
1797 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001798 // Request focus on the top window.
1799 t.getTopWindow().requestFocus();
Michael Kolba2b2ba82010-08-04 17:54:03 -07001800 if (mTabControl.getTabChangeListener() != null) {
1801 mTabControl.getTabChangeListener().onCurrentTab(t);
1802 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001803 }
1804
1805 // Attach a sub window to the main WebView of the given tab.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001806 void attachSubWindow(Tab t) {
Patrick Scottd0119532009-09-17 08:00:31 -04001807 t.attachSubWindow(mContentView);
1808 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001809 }
1810
1811 // Remove the given tab from the content view.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001812 private void removeTabFromContentView(Tab t) {
Steve Block2bc69912009-07-30 14:45:13 +01001813 // Remove the container that contains the main WebView.
Patrick Scottd0119532009-09-17 08:00:31 -04001814 t.removeTabFromContentView(mContentView);
Ben Murdochbff2d602009-07-01 20:19:05 +01001815
Grace Kloba22ac16e2009-10-07 18:00:23 -07001816 ErrorConsoleView errorConsole = t.getErrorConsole(false);
1817 if (errorConsole != null) {
1818 mErrorConsoleContainer.removeView(errorConsole);
Ben Murdochbff2d602009-07-01 20:19:05 +01001819 }
1820
Michael Kolba2b2ba82010-08-04 17:54:03 -07001821 WebView view = t.getWebView();
1822 if (view != null) {
1823 view.setEmbeddedTitleBar(null);
Leon Scrogginsbb85b902009-09-14 19:27:20 -04001824 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001825 }
1826
1827 // Remove the sub window if it exists. Also called by TabControl when the
1828 // user clicks the 'X' to dismiss a sub window.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001829 /* package */ void dismissSubWindow(Tab t) {
Patrick Scottd0119532009-09-17 08:00:31 -04001830 t.removeSubWindow(mContentView);
Grace Kloba22ac16e2009-10-07 18:00:23 -07001831 // dismiss the subwindow. This will destroy the WebView.
1832 t.dismissSubWindow();
Patrick Scottd0119532009-09-17 08:00:31 -04001833 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001834 }
1835
Leon Scroggins1f005d32009-08-10 17:36:42 -04001836 // A wrapper function of {@link #openTabAndShow(UrlData, boolean, String)}
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07001837 // that accepts url as string.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001838 private Tab openTabAndShow(String url, boolean closeOnExit, String appId) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001839 return openTabAndShow(new UrlData(url), closeOnExit, appId);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001840 }
1841
1842 // This method does a ton of stuff. It will attempt to create a new tab
1843 // if we haven't reached MAX_TABS. Otherwise it uses the current tab. If
Leon Scroggins1f005d32009-08-10 17:36:42 -04001844 // url isn't null, it will load the given url.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001845 /* package */Tab openTabAndShow(UrlData urlData, boolean closeOnExit,
1846 String appId) {
1847 final Tab currentTab = mTabControl.getCurrentTab();
1848 if (mTabControl.canCreateNewTab()) {
1849 final Tab tab = mTabControl.createNewTab(closeOnExit, appId,
Elliott Slaughterf0f03952010-07-14 18:10:36 -07001850 urlData.mUrl, false);
Leon Scroggins1f005d32009-08-10 17:36:42 -04001851 WebView webview = tab.getWebView();
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001852 // If the last tab was removed from the active tabs page, currentTab
1853 // will be null.
1854 if (currentTab != null) {
1855 removeTabFromContentView(currentTab);
1856 }
Patrick Scott8bbd69f2009-08-14 13:35:53 -04001857 // We must set the new tab as the current tab to reflect the old
1858 // animation behavior.
1859 mTabControl.setCurrentTab(tab);
Grace Klobaeb6eef42009-09-15 17:56:32 -07001860 attachTabToContentView(tab);
Leon Scroggins160a7e72009-08-14 18:28:01 -04001861 if (!urlData.isEmpty()) {
Patrick Scott9d53da02010-02-19 10:19:01 -05001862 loadUrlDataIn(tab, urlData);
Leon Scroggins1f005d32009-08-10 17:36:42 -04001863 }
1864 return tab;
1865 } else {
1866 // Get rid of the subwindow if it exists
1867 dismissSubWindow(currentTab);
1868 if (!urlData.isEmpty()) {
1869 // Load the given url.
Patrick Scott9d53da02010-02-19 10:19:01 -05001870 loadUrlDataIn(currentTab, urlData);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001871 }
Leon Scroggins58d56c62010-01-28 15:12:40 -05001872 return currentTab;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001873 }
1874 }
1875
Michael Kolb68792c82010-08-09 16:39:18 -07001876 private Tab openTab(String url, boolean forceForeground) {
1877 if (mSettings.openInBackground() && !forceForeground) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001878 Tab t = mTabControl.createNewTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001879 if (t != null) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001880 WebView view = t.getWebView();
Leon Scroggins92472e82010-02-17 16:32:28 -05001881 loadUrl(view, url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001882 }
Grace Klobac9181842009-04-14 08:53:22 -07001883 return t;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001884 } else {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001885 return openTabAndShow(url, false, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001886 }
1887 }
1888
Elliott Slaughterf0f03952010-07-14 18:10:36 -07001889 /* package */ Tab openIncognitoTab() {
1890 if (mTabControl.canCreateNewTab()) {
1891 Tab currentTab = mTabControl.getCurrentTab();
1892 Tab tab = mTabControl.createNewTab(false, null, null, true);
1893 if (currentTab != null) {
1894 removeTabFromContentView(currentTab);
1895 }
1896 mTabControl.setCurrentTab(tab);
1897 attachTabToContentView(tab);
1898 return tab;
1899 }
1900 return null;
1901 }
1902
The Android Open Source Project0c908882009-03-03 19:32:16 -08001903 private class Copy implements OnMenuItemClickListener {
1904 private CharSequence mText;
1905
1906 public boolean onMenuItemClick(MenuItem item) {
1907 copy(mText);
1908 return true;
1909 }
1910
1911 public Copy(CharSequence toCopy) {
1912 mText = toCopy;
1913 }
1914 }
1915
1916 private class Download implements OnMenuItemClickListener {
1917 private String mText;
1918
1919 public boolean onMenuItemClick(MenuItem item) {
1920 onDownloadStartNoStream(mText, null, null, null, -1);
1921 return true;
1922 }
1923
1924 public Download(String toDownload) {
1925 mText = toDownload;
1926 }
1927 }
1928
Ben Murdoch4f75ba22009-10-27 11:48:28 +00001929 private class SetAsWallpaper extends Thread implements
1930 OnMenuItemClickListener, DialogInterface.OnCancelListener {
1931 private URL mUrl;
1932 private ProgressDialog mWallpaperProgress;
1933 private boolean mCanceled = false;
1934
1935 public SetAsWallpaper(String url) {
1936 try {
1937 mUrl = new URL(url);
1938 } catch (MalformedURLException e) {
1939 mUrl = null;
1940 }
1941 }
1942
1943 public void onCancel(DialogInterface dialog) {
1944 mCanceled = true;
1945 }
1946
1947 public boolean onMenuItemClick(MenuItem item) {
1948 if (mUrl != null) {
1949 // The user may have tried to set a image with a large file size as their
1950 // background so it may take a few moments to perform the operation. Display
1951 // a progress spinner while it is working.
1952 mWallpaperProgress = new ProgressDialog(BrowserActivity.this);
1953 mWallpaperProgress.setIndeterminate(true);
1954 mWallpaperProgress.setMessage(getText(R.string.progress_dialog_setting_wallpaper));
1955 mWallpaperProgress.setCancelable(true);
1956 mWallpaperProgress.setOnCancelListener(this);
1957 mWallpaperProgress.show();
1958 start();
1959 }
1960 return true;
1961 }
1962
Michael Kolbe0a36662010-06-29 10:37:12 -07001963 @Override
Ben Murdoch4f75ba22009-10-27 11:48:28 +00001964 public void run() {
1965 Drawable oldWallpaper = BrowserActivity.this.getWallpaper();
1966 try {
1967 // TODO: This will cause the resource to be downloaded again, when we
1968 // should in most cases be able to grab it from the cache. To fix this
1969 // we should query WebCore to see if we can access a cached version and
1970 // instead open an input stream on that. This pattern could also be used
1971 // in the download manager where the same problem exists.
1972 InputStream inputstream = mUrl.openStream();
1973 if (inputstream != null) {
1974 setWallpaper(inputstream);
1975 }
1976 } catch (IOException e) {
1977 Log.e(LOGTAG, "Unable to set new wallpaper");
1978 // Act as though the user canceled the operation so we try to
1979 // restore the old wallpaper.
1980 mCanceled = true;
1981 }
1982
1983 if (mCanceled) {
1984 // Restore the old wallpaper if the user cancelled whilst we were setting
1985 // the new wallpaper.
1986 int width = oldWallpaper.getIntrinsicWidth();
1987 int height = oldWallpaper.getIntrinsicHeight();
1988 Bitmap bm = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
1989 Canvas canvas = new Canvas(bm);
1990 oldWallpaper.setBounds(0, 0, width, height);
1991 oldWallpaper.draw(canvas);
1992 try {
1993 setWallpaper(bm);
1994 } catch (IOException e) {
1995 Log.e(LOGTAG, "Unable to restore old wallpaper.");
1996 }
1997 mCanceled = false;
1998 }
1999
2000 if (mWallpaperProgress.isShowing()) {
2001 mWallpaperProgress.dismiss();
2002 }
2003 }
2004 }
2005
The Android Open Source Project0c908882009-03-03 19:32:16 -08002006 private void copy(CharSequence text) {
Dianne Hackborn80f32622010-08-05 14:17:53 -07002007 ClipboardManager cm = (ClipboardManager)getSystemService(Context.CLIPBOARD_SERVICE);
2008 cm.setText(text);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002009 }
2010
2011 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08002012 * Resets the browser title-view to whatever it must be
2013 * (for example, if we had a loading error)
2014 * When we have a new page, we call resetTitle, when we
2015 * have to reset the titlebar to whatever it used to be
2016 * (for example, if the user chose to stop loading), we
2017 * call resetTitleAndRevertLockIcon.
2018 */
2019 /* package */ void resetTitleAndRevertLockIcon() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002020 mTabControl.getCurrentTab().revertLockIcon();
2021 updateLockIconToLatest();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002022 resetTitleIconAndProgress();
2023 }
2024
2025 /**
2026 * Reset the title, favicon, and progress.
2027 */
2028 private void resetTitleIconAndProgress() {
2029 WebView current = mTabControl.getCurrentWebView();
2030 if (current == null) {
2031 return;
2032 }
2033 resetTitleAndIcon(current);
2034 int progress = current.getProgress();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002035 current.getWebChromeClient().onProgressChanged(current, progress);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002036 }
2037
2038 // Reset the title and the icon based on the given item.
2039 private void resetTitleAndIcon(WebView view) {
2040 WebHistoryItem item = view.copyBackForwardList().getCurrentItem();
2041 if (item != null) {
Leon Scroggins68579392009-09-15 15:31:54 -04002042 setUrlTitle(item.getUrl(), item.getTitle());
The Android Open Source Project0c908882009-03-03 19:32:16 -08002043 setFavicon(item.getFavicon());
2044 } else {
Leon Scroggins68579392009-09-15 15:31:54 -04002045 setUrlTitle(null, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002046 setFavicon(null);
2047 }
2048 }
2049
2050 /**
2051 * Sets a title composed of the URL and the title string.
2052 * @param url The URL of the site being loaded.
2053 * @param title The title of the site being loaded.
2054 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07002055 void setUrlTitle(String url, String title) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002056 mUrl = url;
2057 mTitle = title;
2058
Leon Scroggins58d56c62010-01-28 15:12:40 -05002059 // If we are in voice search mode, the title has already been set.
2060 if (mTabControl.getCurrentTab().isInVoiceSearchMode()) return;
2061 mTitleBar.setDisplayTitle(url);
Michael Kolba2b2ba82010-08-04 17:54:03 -07002062 mFakeTitleBar.setDisplayTitle(url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002063 }
2064
2065 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08002066 * @param url The URL to build a title version of the URL from.
2067 * @return The title version of the URL or null if fails.
2068 * The title version of the URL can be either the URL hostname,
2069 * or the hostname with an "https://" prefix (for secure URLs),
2070 * or an empty string if, for example, the URL in question is a
2071 * file:// URL with no hostname.
2072 */
Leon Scroggins32e14a62009-06-11 10:26:34 -04002073 /* package */ static String buildTitleUrl(String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002074 String titleUrl = null;
2075
2076 if (url != null) {
2077 try {
2078 // parse the url string
2079 URL urlObj = new URL(url);
2080 if (urlObj != null) {
2081 titleUrl = "";
2082
2083 String protocol = urlObj.getProtocol();
2084 String host = urlObj.getHost();
2085
2086 if (host != null && 0 < host.length()) {
2087 titleUrl = host;
2088 if (protocol != null) {
2089 // if a secure site, add an "https://" prefix!
2090 if (protocol.equalsIgnoreCase("https")) {
2091 titleUrl = protocol + "://" + host;
2092 }
2093 }
2094 }
2095 }
2096 } catch (MalformedURLException e) {}
2097 }
2098
2099 return titleUrl;
2100 }
2101
2102 // Set the favicon in the title bar.
Grace Kloba22ac16e2009-10-07 18:00:23 -07002103 void setFavicon(Bitmap icon) {
Leon Scroggins68579392009-09-15 15:31:54 -04002104 mTitleBar.setFavicon(icon);
Michael Kolba2b2ba82010-08-04 17:54:03 -07002105 mFakeTitleBar.setFavicon(icon);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002106 }
2107
2108 /**
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002109 * Close the tab, remove its associated title bar, and adjust mTabControl's
2110 * current tab to a valid value.
Leon Scroggins1f005d32009-08-10 17:36:42 -04002111 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07002112 /* package */ void closeTab(Tab t) {
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002113 int currentIndex = mTabControl.getCurrentIndex();
2114 int removeIndex = mTabControl.getTabIndex(t);
Leon Scroggins1f005d32009-08-10 17:36:42 -04002115 mTabControl.removeTab(t);
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002116 if (currentIndex >= removeIndex && currentIndex != 0) {
2117 currentIndex--;
2118 }
2119 mTabControl.setCurrentTab(mTabControl.getTab(currentIndex));
Andrei Popescua5bf1de2009-09-23 16:39:23 +01002120 resetTitleIconAndProgress();
Leon Scroggins654899b2010-06-25 16:25:23 -04002121 updateLockIconToLatest();
Elliott Slaughtere440a882010-08-20 13:54:45 -07002122
2123 if (!mTabControl.hasAnyOpenIncognitoTabs()) {
2124 WebView.cleanupPrivateBrowsingFiles(this);
2125 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002126 }
2127
Leon Scrogginsdcc5eeb2010-02-23 17:26:37 -05002128 /* package */ void goBackOnePageOrQuit() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002129 Tab current = mTabControl.getCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002130 if (current == null) {
2131 /*
2132 * Instead of finishing the activity, simply push this to the back
2133 * of the stack and let ActivityManager to choose the foreground
2134 * activity. As BrowserActivity is singleTask, it will be always the
2135 * root of the task. So we can use either true or false for
2136 * moveTaskToBack().
2137 */
2138 moveTaskToBack(true);
Grace Kloba00d85e72009-09-23 18:50:05 -07002139 return;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002140 }
2141 WebView w = current.getWebView();
2142 if (w.canGoBack()) {
2143 w.goBack();
2144 } else {
2145 // Check to see if we are closing a window that was created by
2146 // another window. If so, we switch back to that window.
Grace Kloba22ac16e2009-10-07 18:00:23 -07002147 Tab parent = current.getParentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002148 if (parent != null) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04002149 switchToTab(mTabControl.getTabIndex(parent));
2150 // Now we close the other tab
2151 closeTab(current);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002152 } else {
2153 if (current.closeOnExit()) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002154 // force the tab's inLoad() to be false as we are going to
2155 // either finish the activity or remove the tab. This will
2156 // ensure pauseWebViewTimers() taking action.
2157 mTabControl.getCurrentTab().clearInLoad();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002158 if (mTabControl.getTabCount() == 1) {
2159 finish();
2160 return;
2161 }
Mike Reed7bfa63b2009-05-28 11:08:32 -04002162 // call pauseWebViewTimers() now, we won't be able to call
2163 // it in onPause() as the WebView won't be valid.
Grace Klobaec1b5ad2009-08-18 08:42:32 -07002164 // Temporarily change mActivityInPause to be true as
2165 // pauseWebViewTimers() will do nothing if mActivityInPause
2166 // is false.
Grace Kloba918e1d72009-08-13 14:55:06 -07002167 boolean savedState = mActivityInPause;
2168 if (savedState) {
Grace Klobaec1b5ad2009-08-18 08:42:32 -07002169 Log.e(LOGTAG, "BrowserActivity is already paused "
2170 + "while handing goBackOnePageOrQuit.");
Grace Kloba918e1d72009-08-13 14:55:06 -07002171 }
2172 mActivityInPause = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -04002173 pauseWebViewTimers();
Grace Kloba918e1d72009-08-13 14:55:06 -07002174 mActivityInPause = savedState;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002175 removeTabFromContentView(current);
2176 mTabControl.removeTab(current);
2177 }
2178 /*
2179 * Instead of finishing the activity, simply push this to the back
2180 * of the stack and let ActivityManager to choose the foreground
2181 * activity. As BrowserActivity is singleTask, it will be always the
2182 * root of the task. So we can use either true or false for
2183 * moveTaskToBack().
2184 */
2185 moveTaskToBack(true);
2186 }
2187 }
2188 }
2189
Grace Kloba22ac16e2009-10-07 18:00:23 -07002190 boolean isMenuDown() {
2191 return mMenuIsDown;
2192 }
2193
Grace Kloba5942df02009-09-18 11:48:29 -07002194 @Override
2195 public boolean onKeyDown(int keyCode, KeyEvent event) {
Leon Scrogginsf65b50d2009-12-08 10:44:28 -05002196 // Even if MENU is already held down, we need to call to super to open
2197 // the IME on long press.
2198 if (KeyEvent.KEYCODE_MENU == keyCode) {
2199 mMenuIsDown = true;
2200 return super.onKeyDown(keyCode, event);
2201 }
Grace Kloba5942df02009-09-18 11:48:29 -07002202 // The default key mode is DEFAULT_KEYS_SEARCH_LOCAL. As the MENU is
2203 // still down, we don't want to trigger the search. Pretend to consume
2204 // the key and do nothing.
2205 if (mMenuIsDown) return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002206
Grace Kloba5942df02009-09-18 11:48:29 -07002207 switch(keyCode) {
Grace Kloba5942df02009-09-18 11:48:29 -07002208 case KeyEvent.KEYCODE_SPACE:
Grace Klobada0fe552009-09-22 18:17:24 -07002209 // WebView/WebTextView handle the keys in the KeyDown. As
2210 // the Activity's shortcut keys are only handled when WebView
2211 // doesn't, have to do it in onKeyDown instead of onKeyUp.
2212 if (event.isShiftPressed()) {
2213 getTopWindow().pageUp(false);
2214 } else {
2215 getTopWindow().pageDown(false);
2216 }
Grace Kloba5942df02009-09-18 11:48:29 -07002217 return true;
2218 case KeyEvent.KEYCODE_BACK:
2219 if (event.getRepeatCount() == 0) {
2220 event.startTracking();
2221 return true;
2222 } else if (mCustomView == null && mActiveTabsPage == null
2223 && event.isLongPress()) {
Michael Kolb68792c82010-08-09 16:39:18 -07002224 bookmarksOrHistoryPicker(true, false);
Grace Kloba5942df02009-09-18 11:48:29 -07002225 return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002226 }
Grace Kloba5942df02009-09-18 11:48:29 -07002227 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002228 }
Grace Kloba5942df02009-09-18 11:48:29 -07002229 return super.onKeyDown(keyCode, event);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002230 }
2231
Grace Kloba5942df02009-09-18 11:48:29 -07002232 @Override
2233 public boolean onKeyUp(int keyCode, KeyEvent event) {
2234 switch(keyCode) {
2235 case KeyEvent.KEYCODE_MENU:
2236 mMenuIsDown = false;
2237 break;
Grace Kloba5942df02009-09-18 11:48:29 -07002238 case KeyEvent.KEYCODE_BACK:
2239 if (event.isTracking() && !event.isCanceled()) {
2240 if (mCustomView != null) {
2241 // if a custom view is showing, hide it
Grace Kloba22ac16e2009-10-07 18:00:23 -07002242 mTabControl.getCurrentWebView().getWebChromeClient()
2243 .onHideCustomView();
Grace Kloba5942df02009-09-18 11:48:29 -07002244 } else if (mActiveTabsPage != null) {
2245 // if tab page is showing, hide it
2246 removeActiveTabPage(true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002247 } else {
Grace Kloba5942df02009-09-18 11:48:29 -07002248 WebView subwindow = mTabControl.getCurrentSubWindow();
2249 if (subwindow != null) {
2250 if (subwindow.canGoBack()) {
2251 subwindow.goBack();
2252 } else {
2253 dismissSubWindow(mTabControl.getCurrentTab());
2254 }
2255 } else {
2256 goBackOnePageOrQuit();
2257 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002258 }
Grace Kloba5942df02009-09-18 11:48:29 -07002259 return true;
2260 }
2261 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002262 }
Grace Kloba5942df02009-09-18 11:48:29 -07002263 return super.onKeyUp(keyCode, event);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002264 }
2265
Leon Scroggins68579392009-09-15 15:31:54 -04002266 /* package */ void stopLoading() {
Ben Murdochb7cc8b42009-09-28 10:59:09 +01002267 mDidStopLoad = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002268 resetTitleAndRevertLockIcon();
2269 WebView w = getTopWindow();
2270 w.stopLoading();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002271 // FIXME: before refactor, it is using mWebViewClient. So I keep the
2272 // same logic here. But for subwindow case, should we call into the main
2273 // WebView's onPageFinished as we never call its onPageStarted and if
2274 // the page finishes itself, we don't call onPageFinished.
2275 mTabControl.getCurrentWebView().getWebViewClient().onPageFinished(w,
2276 w.getUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08002277
2278 cancelStopToast();
2279 mStopToast = Toast
2280 .makeText(this, R.string.stopping, Toast.LENGTH_SHORT);
2281 mStopToast.show();
2282 }
2283
Grace Kloba22ac16e2009-10-07 18:00:23 -07002284 boolean didUserStopLoading() {
2285 return mDidStopLoad;
2286 }
2287
The Android Open Source Project0c908882009-03-03 19:32:16 -08002288 private void cancelStopToast() {
2289 if (mStopToast != null) {
2290 mStopToast.cancel();
2291 mStopToast = null;
2292 }
2293 }
2294
Grace Kloba22ac16e2009-10-07 18:00:23 -07002295 // called by a UI or non-UI thread to post the message
2296 public void postMessage(int what, int arg1, int arg2, Object obj,
2297 long delayMillis) {
2298 mHandler.sendMessageDelayed(mHandler.obtainMessage(what, arg1, arg2,
2299 obj), delayMillis);
2300 }
2301
2302 // called by a UI or non-UI thread to remove the message
2303 void removeMessages(int what, Object object) {
2304 mHandler.removeMessages(what, object);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002305 }
2306
2307 // public message ids
2308 public final static int LOAD_URL = 1001;
2309 public final static int STOP_LOAD = 1002;
2310
2311 // Message Ids
2312 private static final int FOCUS_NODE_HREF = 102;
Grace Kloba92c18a52009-07-31 23:48:32 -07002313 private static final int RELEASE_WAKELOCK = 107;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002314
Grace Kloba22ac16e2009-10-07 18:00:23 -07002315 static final int UPDATE_BOOKMARK_THUMBNAIL = 108;
Ben Murdoch2694e232009-09-29 09:41:11 +01002316
Ben Murdocheecb4e62010-07-06 16:30:38 +01002317 private static final int TOUCH_ICON_DOWNLOADED = 109;
2318
Michael Kolb300b7f02010-08-25 13:47:24 -07002319 private static final int OPEN_BOOKMARKS = 201;
2320
The Android Open Source Project0c908882009-03-03 19:32:16 -08002321 // Private handler for handling javascript and saving passwords
2322 private Handler mHandler = new Handler() {
2323
Michael Kolbe0a36662010-06-29 10:37:12 -07002324 @Override
The Android Open Source Project0c908882009-03-03 19:32:16 -08002325 public void handleMessage(Message msg) {
2326 switch (msg.what) {
Michael Kolb300b7f02010-08-25 13:47:24 -07002327 case OPEN_BOOKMARKS:
2328 bookmarksOrHistoryPicker(false, false);
2329 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002330 case FOCUS_NODE_HREF:
Ben Murdoch2694e232009-09-29 09:41:11 +01002331 {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002332 String url = (String) msg.getData().get("url");
Ben Murdoch90d088c2009-11-17 18:14:04 +00002333 String title = (String) msg.getData().get("title");
The Android Open Source Project0c908882009-03-03 19:32:16 -08002334 if (url == null || url.length() == 0) {
2335 break;
2336 }
2337 HashMap focusNodeMap = (HashMap) msg.obj;
2338 WebView view = (WebView) focusNodeMap.get("webview");
2339 // Only apply the action if the top window did not change.
2340 if (getTopWindow() != view) {
2341 break;
2342 }
2343 switch (msg.arg1) {
2344 case R.id.open_context_menu_id:
2345 case R.id.view_image_context_menu_id:
Leon Scroggins92472e82010-02-17 16:32:28 -05002346 loadUrlFromContext(getTopWindow(), url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002347 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002348 case R.id.bookmark_context_menu_id:
2349 Intent intent = new Intent(BrowserActivity.this,
2350 AddBookmarkPage.class);
2351 intent.putExtra("url", url);
Ben Murdoch90d088c2009-11-17 18:14:04 +00002352 intent.putExtra("title", title);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002353 startActivity(intent);
2354 break;
2355 case R.id.share_link_context_menu_id:
Leon Scroggins3e204452010-05-10 11:06:03 -04002356 sharePage(BrowserActivity.this, title, url, null,
Leon Scroggins96afcb12009-12-10 12:35:56 -05002357 null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002358 break;
2359 case R.id.copy_link_context_menu_id:
2360 copy(url);
2361 break;
2362 case R.id.save_link_context_menu_id:
2363 case R.id.download_context_menu_id:
2364 onDownloadStartNoStream(url, null, null, null, -1);
2365 break;
2366 }
2367 break;
Ben Murdoch2694e232009-09-29 09:41:11 +01002368 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002369
2370 case LOAD_URL:
Leon Scroggins92472e82010-02-17 16:32:28 -05002371 loadUrlFromContext(getTopWindow(), (String) msg.obj);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002372 break;
2373
2374 case STOP_LOAD:
2375 stopLoading();
2376 break;
2377
The Android Open Source Project0c908882009-03-03 19:32:16 -08002378 case RELEASE_WAKELOCK:
2379 if (mWakeLock.isHeld()) {
2380 mWakeLock.release();
Grace Kloba5d0e02e2009-10-05 15:15:36 -07002381 // if we reach here, Browser should be still in the
2382 // background loading after WAKELOCK_TIMEOUT (5-min).
2383 // To avoid burning the battery, stop loading.
2384 mTabControl.stopAllLoading();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002385 }
2386 break;
Ben Murdoch2694e232009-09-29 09:41:11 +01002387
2388 case UPDATE_BOOKMARK_THUMBNAIL:
2389 WebView view = (WebView) msg.obj;
2390 if (view != null) {
2391 updateScreenshot(view);
2392 }
2393 break;
Ben Murdocheecb4e62010-07-06 16:30:38 +01002394
2395 case TOUCH_ICON_DOWNLOADED:
2396 Bundle b = msg.getData();
2397 showSaveToHomescreenDialog(b.getString("url"),
2398 b.getString("title"),
2399 (Bitmap) b.getParcelable("touchIcon"),
2400 (Bitmap) b.getParcelable("favicon"));
2401 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002402 }
2403 }
2404 };
2405
Leon Scroggins96afcb12009-12-10 12:35:56 -05002406 /**
2407 * Share a page, providing the title, url, favicon, and a screenshot. Uses
2408 * an {@link Intent} to launch the Activity chooser.
2409 * @param c Context used to launch a new Activity.
2410 * @param title Title of the page. Stored in the Intent with
Paul Westbrook03e6d392010-02-12 10:33:29 -08002411 * {@link Intent#EXTRA_SUBJECT}
Leon Scroggins96afcb12009-12-10 12:35:56 -05002412 * @param url URL of the page. Stored in the Intent with
2413 * {@link Intent#EXTRA_TEXT}
2414 * @param favicon Bitmap of the favicon for the page. Stored in the Intent
2415 * with {@link Browser#EXTRA_SHARE_FAVICON}
2416 * @param screenshot Bitmap of a screenshot of the page. Stored in the
2417 * Intent with {@link Browser#EXTRA_SHARE_SCREENSHOT}
2418 */
2419 public static final void sharePage(Context c, String title, String url,
2420 Bitmap favicon, Bitmap screenshot) {
2421 Intent send = new Intent(Intent.ACTION_SEND);
2422 send.setType("text/plain");
2423 send.putExtra(Intent.EXTRA_TEXT, url);
Paul Westbrook03e6d392010-02-12 10:33:29 -08002424 send.putExtra(Intent.EXTRA_SUBJECT, title);
Leon Scroggins96afcb12009-12-10 12:35:56 -05002425 send.putExtra(Browser.EXTRA_SHARE_FAVICON, favicon);
2426 send.putExtra(Browser.EXTRA_SHARE_SCREENSHOT, screenshot);
2427 try {
2428 c.startActivity(Intent.createChooser(send, c.getString(
2429 R.string.choosertitle_sharevia)));
2430 } catch(android.content.ActivityNotFoundException ex) {
2431 // if no app handles it, do nothing
2432 }
2433 }
2434
Leon Scroggins89c6d362009-07-15 16:54:37 -04002435 private void updateScreenshot(WebView view) {
2436 // If this is a bookmarked site, add a screenshot to the database.
2437 // FIXME: When should we update? Every time?
2438 // FIXME: Would like to make sure there is actually something to
2439 // draw, but the API for that (WebViewCore.pictureReady()) is not
2440 // currently accessible here.
Ben Murdochaac7aa62009-09-17 16:57:40 +01002441
Ben Murdoch87cc65d2010-06-29 20:34:10 +01002442 final Bitmap bm = createScreenshot(view, getDesiredThumbnailWidth(this),
2443 getDesiredThumbnailHeight(this));
Patrick Scottcb192b52010-04-14 14:38:55 -04002444 if (bm == null) {
2445 return;
Leon Scroggins89c6d362009-07-15 16:54:37 -04002446 }
Patrick Scottcb192b52010-04-14 14:38:55 -04002447
2448 final ContentResolver cr = getContentResolver();
2449 final String url = view.getUrl();
2450 final String originalUrl = view.getOriginalUrl();
2451
2452 new AsyncTask<Void, Void, Void>() {
2453 @Override
2454 protected Void doInBackground(Void... unused) {
2455 Cursor c = null;
2456 try {
Jeff Hamilton84029622010-08-05 14:29:28 -05002457 c = Bookmarks.queryBookmarksForUrl(
Jeff Hamilton8ce956c2010-08-17 11:13:53 -05002458 cr, originalUrl, url);
Patrick Scottcb192b52010-04-14 14:38:55 -04002459 if (c != null) {
2460 if (c.moveToFirst()) {
2461 ContentValues values = new ContentValues();
2462 final ByteArrayOutputStream os
2463 = new ByteArrayOutputStream();
2464 bm.compress(Bitmap.CompressFormat.PNG, 100, os);
Jeff Hamilton8ce956c2010-08-17 11:13:53 -05002465 values.put(BrowserContract.Bookmarks.THUMBNAIL,
Patrick Scottcb192b52010-04-14 14:38:55 -04002466 os.toByteArray());
2467 do {
2468 cr.update(ContentUris.withAppendedId(
Jeff Hamilton8ce956c2010-08-17 11:13:53 -05002469 BrowserContract.Bookmarks.CONTENT_URI, c.getLong(0)),
Patrick Scottcb192b52010-04-14 14:38:55 -04002470 values, null, null);
2471 } while (c.moveToNext());
2472 }
2473 }
2474 } catch (IllegalStateException e) {
2475 // Ignore
2476 } finally {
2477 if (c != null) c.close();
2478 }
2479 return null;
2480 }
2481 }.execute();
Leon Scroggins89c6d362009-07-15 16:54:37 -04002482 }
2483
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002484 /**
Leon Scrogginsf8551612009-09-24 16:06:02 -04002485 * Return the desired width for thumbnail screenshots, which are stored in
2486 * the database, and used on the bookmarks screen.
2487 * @param context Context for finding out the density of the screen.
Jeff Hamiltonf3026372010-08-19 00:12:27 -05002488 * @return desired width for thumbnail screenshot.
Leon Scrogginsf8551612009-09-24 16:06:02 -04002489 */
2490 /* package */ static int getDesiredThumbnailWidth(Context context) {
Jeff Hamiltonf3026372010-08-19 00:12:27 -05002491 return context.getResources().getDimensionPixelOffset(R.dimen.bookmarkThumbnailWidth);
Leon Scrogginsf8551612009-09-24 16:06:02 -04002492 }
2493
2494 /**
2495 * Return the desired height for thumbnail screenshots, which are stored in
2496 * the database, and used on the bookmarks screen.
2497 * @param context Context for finding out the density of the screen.
Jeff Hamiltonf3026372010-08-19 00:12:27 -05002498 * @return desired height for thumbnail screenshot.
Leon Scrogginsf8551612009-09-24 16:06:02 -04002499 */
2500 /* package */ static int getDesiredThumbnailHeight(Context context) {
Jeff Hamiltonf3026372010-08-19 00:12:27 -05002501 return context.getResources().getDimensionPixelOffset(R.dimen.bookmarkThumbnailHeight);
Leon Scrogginsf8551612009-09-24 16:06:02 -04002502 }
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002503
Ben Murdoch87cc65d2010-06-29 20:34:10 +01002504 private Bitmap createScreenshot(WebView view, int width, int height) {
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002505 Picture thumbnail = view.capturePicture();
Leon Scroggins45800572009-09-29 16:38:47 -04002506 if (thumbnail == null) {
2507 return null;
2508 }
Ben Murdoch87cc65d2010-06-29 20:34:10 +01002509 Bitmap bm = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002510 Canvas canvas = new Canvas(bm);
2511 // May need to tweak these values to determine what is the
2512 // best scale factor
Ben Murdoch2694e232009-09-29 09:41:11 +01002513 int thumbnailWidth = thumbnail.getWidth();
Ben Murdochae59c3f2009-10-20 18:30:28 +01002514 int thumbnailHeight = thumbnail.getHeight();
2515 float scaleFactorX = 1.0f;
2516 float scaleFactorY = 1.0f;
Ben Murdoch2694e232009-09-29 09:41:11 +01002517 if (thumbnailWidth > 0) {
Ben Murdoch87cc65d2010-06-29 20:34:10 +01002518 scaleFactorX = (float) width / (float)thumbnailWidth;
Ben Murdochae59c3f2009-10-20 18:30:28 +01002519 } else {
2520 return null;
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002521 }
Ben Murdochae59c3f2009-10-20 18:30:28 +01002522
2523 if (view.getWidth() > view.getHeight() &&
2524 thumbnailHeight < view.getHeight() && thumbnailHeight > 0) {
2525 // If the device is in landscape and the page is shorter
2526 // than the height of the view, stretch the thumbnail to fill the
2527 // space.
Ben Murdoch87cc65d2010-06-29 20:34:10 +01002528 scaleFactorY = (float) height / (float)thumbnailHeight;
Ben Murdochae59c3f2009-10-20 18:30:28 +01002529 } else {
2530 // In the portrait case, this looks nice.
2531 scaleFactorY = scaleFactorX;
2532 }
2533
2534 canvas.scale(scaleFactorX, scaleFactorY);
2535
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002536 thumbnail.draw(canvas);
2537 return bm;
2538 }
2539
The Android Open Source Project0c908882009-03-03 19:32:16 -08002540 // -------------------------------------------------------------------------
Grace Kloba22ac16e2009-10-07 18:00:23 -07002541 // Helper function for WebViewClient.
The Android Open Source Project0c908882009-03-03 19:32:16 -08002542 //-------------------------------------------------------------------------
2543
2544 // Use in overrideUrlLoading
2545 /* package */ final static String SCHEME_WTAI = "wtai://wp/";
2546 /* package */ final static String SCHEME_WTAI_MC = "wtai://wp/mc;";
2547 /* package */ final static String SCHEME_WTAI_SD = "wtai://wp/sd;";
2548 /* package */ final static String SCHEME_WTAI_AP = "wtai://wp/ap;";
2549
Leon Scroggins92472e82010-02-17 16:32:28 -05002550 // Keep this initial progress in sync with initialProgressValue (* 100)
2551 // in ProgressTracker.cpp
2552 private final static int INITIAL_PROGRESS = 10;
2553
Grace Kloba22ac16e2009-10-07 18:00:23 -07002554 void onPageStarted(WebView view, String url, Bitmap favicon) {
2555 // when BrowserActivity just starts, onPageStarted may be called before
2556 // onResume as it is triggered from onCreate. Call resumeWebViewTimers
2557 // to start the timer. As we won't switch tabs while an activity is in
2558 // pause state, we can ensure calling resume and pause in pair.
2559 if (mActivityInPause) resumeWebViewTimers();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002560
Grace Kloba22ac16e2009-10-07 18:00:23 -07002561 resetLockIcon(url);
2562 setUrlTitle(url, null);
2563 setFavicon(favicon);
Leon Scroggins8cf8f682009-11-04 11:13:50 -08002564 // Show some progress so that the user knows the page is beginning to
2565 // load
Leon Scroggins92472e82010-02-17 16:32:28 -05002566 onProgressChanged(view, INITIAL_PROGRESS);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002567 mDidStopLoad = false;
Grace Kloba22ac16e2009-10-07 18:00:23 -07002568 if (!mIsNetworkUp) createAndShowNetworkDialog();
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04002569 endActionMode();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002570 if (mSettings.isTracing()) {
2571 String host;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002572 try {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002573 WebAddress uri = new WebAddress(url);
2574 host = uri.mHost;
2575 } catch (android.net.ParseException ex) {
2576 host = "browser";
The Android Open Source Project0c908882009-03-03 19:32:16 -08002577 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002578 host = host.replace('.', '_');
2579 host += ".trace";
2580 mInTrace = true;
2581 Debug.startMethodTracing(host, 20 * 1024 * 1024);
2582 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002583
Grace Kloba22ac16e2009-10-07 18:00:23 -07002584 // Performance probe
2585 if (false) {
2586 mStart = SystemClock.uptimeMillis();
2587 mProcessStart = Process.getElapsedCpuTime();
2588 long[] sysCpu = new long[7];
2589 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2590 sysCpu, null)) {
2591 mUserStart = sysCpu[0] + sysCpu[1];
2592 mSystemStart = sysCpu[2];
2593 mIdleStart = sysCpu[3];
2594 mIrqStart = sysCpu[4] + sysCpu[5] + sysCpu[6];
2595 }
2596 mUiStart = SystemClock.currentThreadTimeMillis();
2597 }
2598 }
2599
2600 void onPageFinished(WebView view, String url) {
2601 // Reset the title and icon in case we stopped a provisional load.
2602 resetTitleAndIcon(view);
2603 // Update the lock icon image only once we are done loading
2604 updateLockIconToLatest();
2605 // pause the WebView timer and release the wake lock if it is finished
2606 // while BrowserActivity is in pause state.
2607 if (mActivityInPause && pauseWebViewTimers()) {
2608 if (mWakeLock.isHeld()) {
2609 mHandler.removeMessages(RELEASE_WAKELOCK);
2610 mWakeLock.release();
2611 }
2612 }
2613
2614 // Performance probe
2615 if (false) {
2616 long[] sysCpu = new long[7];
2617 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2618 sysCpu, null)) {
2619 String uiInfo = "UI thread used "
2620 + (SystemClock.currentThreadTimeMillis() - mUiStart)
2621 + " ms";
2622 if (LOGD_ENABLED) {
2623 Log.d(LOGTAG, uiInfo);
2624 }
2625 //The string that gets written to the log
2626 String performanceString = "It took total "
2627 + (SystemClock.uptimeMillis() - mStart)
2628 + " ms clock time to load the page."
2629 + "\nbrowser process used "
2630 + (Process.getElapsedCpuTime() - mProcessStart)
2631 + " ms, user processes used "
2632 + (sysCpu[0] + sysCpu[1] - mUserStart) * 10
2633 + " ms, kernel used "
2634 + (sysCpu[2] - mSystemStart) * 10
2635 + " ms, idle took " + (sysCpu[3] - mIdleStart) * 10
2636 + " ms and irq took "
2637 + (sysCpu[4] + sysCpu[5] + sysCpu[6] - mIrqStart)
2638 * 10 + " ms, " + uiInfo;
2639 if (LOGD_ENABLED) {
2640 Log.d(LOGTAG, performanceString + "\nWebpage: " + url);
2641 }
2642 if (url != null) {
2643 // strip the url to maintain consistency
2644 String newUrl = new String(url);
2645 if (newUrl.startsWith("http://www.")) {
2646 newUrl = newUrl.substring(11);
2647 } else if (newUrl.startsWith("http://")) {
2648 newUrl = newUrl.substring(7);
2649 } else if (newUrl.startsWith("https://www.")) {
2650 newUrl = newUrl.substring(12);
2651 } else if (newUrl.startsWith("https://")) {
2652 newUrl = newUrl.substring(8);
2653 }
2654 if (LOGD_ENABLED) {
2655 Log.d(LOGTAG, newUrl + " loaded");
2656 }
Grace Kloba5b078b52009-06-24 20:23:41 -07002657 }
2658 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002659 }
Grace Kloba5b078b52009-06-24 20:23:41 -07002660
Grace Kloba22ac16e2009-10-07 18:00:23 -07002661 if (mInTrace) {
2662 mInTrace = false;
2663 Debug.stopMethodTracing();
2664 }
2665 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002666
Grace Klobae7fe26b2010-06-28 16:23:33 -07002667 private void closeEmptyChildTab() {
2668 Tab current = mTabControl.getCurrentTab();
2669 if (current != null
2670 && current.getWebView().copyBackForwardList().getSize() == 0) {
2671 Tab parent = current.getParentTab();
2672 if (parent != null) {
2673 switchToTab(mTabControl.getTabIndex(parent));
2674 closeTab(current);
2675 }
2676 }
2677 }
2678
Grace Kloba22ac16e2009-10-07 18:00:23 -07002679 boolean shouldOverrideUrlLoading(WebView view, String url) {
2680 if (url.startsWith(SCHEME_WTAI)) {
2681 // wtai://wp/mc;number
2682 // number=string(phone-number)
2683 if (url.startsWith(SCHEME_WTAI_MC)) {
2684 Intent intent = new Intent(Intent.ACTION_VIEW,
2685 Uri.parse(WebView.SCHEME_TEL +
2686 url.substring(SCHEME_WTAI_MC.length())));
2687 startActivity(intent);
Grace Klobae7fe26b2010-06-28 16:23:33 -07002688 // before leaving BrowserActivity, close the empty child tab.
2689 // If a new tab is created through JavaScript open to load this
2690 // url, we would like to close it as we will load this url in a
2691 // different Activity.
2692 closeEmptyChildTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002693 return true;
2694 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002695 // wtai://wp/sd;dtmf
2696 // dtmf=string(dialstring)
2697 if (url.startsWith(SCHEME_WTAI_SD)) {
2698 // TODO: only send when there is active voice connection
2699 return false;
2700 }
2701 // wtai://wp/ap;number;name
2702 // number=string(phone-number)
2703 // name=string
2704 if (url.startsWith(SCHEME_WTAI_AP)) {
2705 // TODO
2706 return false;
2707 }
2708 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002709
Grace Kloba22ac16e2009-10-07 18:00:23 -07002710 // The "about:" schemes are internal to the browser; don't want these to
2711 // be dispatched to other apps.
2712 if (url.startsWith("about:")) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002713 return false;
2714 }
2715
Jeff Davidson43610292010-07-16 16:03:58 -07002716 // If this is a Google search, attempt to add an RLZ string (if one isn't already present).
2717 if (rlzProviderPresent()) {
2718 Uri siteUri = Uri.parse(url);
2719 if (needsRlzString(siteUri)) {
2720 String rlz = null;
2721 Cursor cur = null;
2722 try {
2723 cur = getContentResolver().query(getRlzUri(), null, null, null, null);
2724 if (cur != null && cur.moveToFirst() && !cur.isNull(0)) {
2725 url = siteUri.buildUpon()
2726 .appendQueryParameter("rlz", cur.getString(0))
2727 .build().toString();
2728 }
2729 } finally {
2730 if (cur != null) {
2731 cur.close();
2732 }
2733 }
2734 loadUrl(view, url);
2735 return true;
2736 }
2737 }
2738
Grace Kloba22ac16e2009-10-07 18:00:23 -07002739 Intent intent;
2740 // perform generic parsing of the URI to turn it into an Intent.
2741 try {
2742 intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME);
2743 } catch (URISyntaxException ex) {
2744 Log.w("Browser", "Bad URI " + url + ": " + ex.getMessage());
2745 return false;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002746 }
2747
Grace Kloba22ac16e2009-10-07 18:00:23 -07002748 // check whether the intent can be resolved. If not, we will see
2749 // whether we can download it from the Market.
2750 if (getPackageManager().resolveActivity(intent, 0) == null) {
2751 String packagename = intent.getPackage();
2752 if (packagename != null) {
2753 intent = new Intent(Intent.ACTION_VIEW, Uri
2754 .parse("market://search?q=pname:" + packagename));
2755 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2756 startActivity(intent);
Grace Klobae7fe26b2010-06-28 16:23:33 -07002757 // before leaving BrowserActivity, close the empty child tab.
2758 // If a new tab is created through JavaScript open to load this
2759 // url, we would like to close it as we will load this url in a
2760 // different Activity.
2761 closeEmptyChildTab();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002762 return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002763 } else {
2764 return false;
2765 }
2766 }
2767
Grace Kloba22ac16e2009-10-07 18:00:23 -07002768 // sanitize the Intent, ensuring web pages can not bypass browser
2769 // security (only access to BROWSABLE activities).
2770 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2771 intent.setComponent(null);
2772 try {
2773 if (startActivityIfNeeded(intent, -1)) {
Grace Klobae7fe26b2010-06-28 16:23:33 -07002774 // before leaving BrowserActivity, close the empty child tab.
2775 // If a new tab is created through JavaScript open to load this
2776 // url, we would like to close it as we will load this url in a
2777 // different Activity.
2778 closeEmptyChildTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002779 return true;
2780 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002781 } catch (ActivityNotFoundException ex) {
2782 // ignore the error. If no application can handle the URL,
2783 // eg about:blank, assume the browser can handle it.
2784 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002785
Grace Kloba22ac16e2009-10-07 18:00:23 -07002786 if (mMenuIsDown) {
Michael Kolb68792c82010-08-09 16:39:18 -07002787 openTab(url, false);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002788 closeOptionsMenu();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002789 return true;
2790 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002791 return false;
2792 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002793
Jeff Davidson43610292010-07-16 16:03:58 -07002794 // Determine whether the RLZ provider is present on the system.
2795 private boolean rlzProviderPresent() {
2796 if (mIsProviderPresent == null) {
2797 PackageManager pm = getPackageManager();
2798 mIsProviderPresent = pm.resolveContentProvider(BrowserSettings.RLZ_PROVIDER, 0) != null;
2799 }
2800 return mIsProviderPresent;
2801 }
2802
2803 // Retrieve the RLZ access point string and cache the URI used to retrieve RLZ values.
2804 private Uri getRlzUri() {
2805 if (mRlzUri == null) {
2806 String ap = getResources().getString(R.string.rlz_access_point);
2807 mRlzUri = Uri.withAppendedPath(BrowserSettings.RLZ_PROVIDER_URI, ap);
2808 }
2809 return mRlzUri;
2810 }
2811
2812 // Determine if this URI appears to be for a Google search and does not have an RLZ parameter.
2813 // Taken largely from Chrome source, src/chrome/browser/google_url_tracker.cc
2814 private static boolean needsRlzString(Uri uri) {
Bill Napierc50e71a2010-08-27 14:03:03 -07002815 String scheme = uri.getScheme();
2816 if (("http".equals(scheme) || "https".equals(scheme)) &&
2817 (uri.getQueryParameter("q") != null) && (uri.getQueryParameter("rlz") == null)) {
Jeff Davidson43610292010-07-16 16:03:58 -07002818 String host = uri.getHost();
2819 if (host == null) {
2820 return false;
2821 }
2822 String[] hostComponents = host.split("\\.");
2823
2824 if (hostComponents.length < 2) {
2825 return false;
2826 }
2827 int googleComponent = hostComponents.length - 2;
2828 String component = hostComponents[googleComponent];
2829 if (!"google".equals(component)) {
2830 if (hostComponents.length < 3 ||
2831 (!"co".equals(component) && !"com".equals(component))) {
2832 return false;
2833 }
2834 googleComponent = hostComponents.length - 3;
2835 if (!"google".equals(hostComponents[googleComponent])) {
2836 return false;
2837 }
2838 }
2839
2840 // Google corp network handling.
2841 if (googleComponent > 0 && "corp".equals(hostComponents[googleComponent - 1])) {
2842 return false;
2843 }
2844
2845 return true;
2846 }
2847 return false;
2848 }
2849
Grace Kloba22ac16e2009-10-07 18:00:23 -07002850 // -------------------------------------------------------------------------
2851 // Helper function for WebChromeClient
2852 // -------------------------------------------------------------------------
The Android Open Source Project0c908882009-03-03 19:32:16 -08002853
Grace Kloba22ac16e2009-10-07 18:00:23 -07002854 void onProgressChanged(WebView view, int newProgress) {
Michael Kolba2b2ba82010-08-04 17:54:03 -07002855
2856 // On the phone, the fake title bar will always cover up the
2857 // regular title bar (or the regular one is offscreen), so only the
2858 // fake title bar needs to change its progress
2859 mFakeTitleBar.setProgress(newProgress);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002860
Grace Kloba22ac16e2009-10-07 18:00:23 -07002861 if (newProgress == 100) {
2862 // onProgressChanged() may continue to be called after the main
2863 // frame has finished loading, as any remaining sub frames continue
2864 // to load. We'll only get called once though with newProgress as
2865 // 100 when everything is loaded. (onPageFinished is called once
2866 // when the main frame completes loading regardless of the state of
2867 // any sub frames so calls to onProgressChanges may continue after
2868 // onPageFinished has executed)
2869 if (mInLoad) {
2870 mInLoad = false;
Leon Scrogginsa27ff192009-09-14 12:58:04 -04002871 updateInLoadMenuItems();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002872 // If the options menu is open, leave the title bar
2873 if (!mOptionsMenuOpen || !mIconView) {
2874 hideFakeTitleBar();
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07002875 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002876 }
Leon Scrogginsaa37e7f2010-03-05 11:51:20 -05002877 } else {
2878 if (!mInLoad) {
2879 // onPageFinished may have already been called but a subframe is
2880 // still loading and updating the progress. Reset mInLoad and
2881 // update the menu items.
2882 mInLoad = true;
2883 updateInLoadMenuItems();
2884 }
2885 // When the page first begins to load, the Activity may still be
2886 // paused, in which case showFakeTitleBar will do nothing. Call
2887 // again as the page continues to load so that it will be shown.
2888 // (Calling it will the fake title bar is already showing will also
2889 // do nothing.
Grace Kloba22ac16e2009-10-07 18:00:23 -07002890 if (!mOptionsMenuOpen || mIconView) {
2891 // This page has begun to load, so show the title bar
2892 showFakeTitleBar();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002893 }
2894 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002895 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002896
Grace Kloba22ac16e2009-10-07 18:00:23 -07002897 void onShowCustomView(View view, WebChromeClient.CustomViewCallback callback) {
Derek Sollenberger8ff57db2009-12-08 15:39:55 -05002898 // if a view already exists then immediately terminate the new one
2899 if (mCustomView != null) {
2900 callback.onCustomViewHidden();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002901 return;
Derek Sollenberger8ff57db2009-12-08 15:39:55 -05002902 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002903
2904 // Add the custom view to its container.
2905 mCustomViewContainer.addView(view, COVER_SCREEN_GRAVITY_CENTER);
2906 mCustomView = view;
2907 mCustomViewCallback = callback;
2908 // Save the menu state and set it to empty while the custom
2909 // view is showing.
2910 mOldMenuState = mMenuState;
2911 mMenuState = EMPTY_MENU;
2912 // Hide the content view.
2913 mContentView.setVisibility(View.GONE);
2914 // Finally show the custom view container.
Andrei Popescu163ab742009-10-20 17:58:23 +01002915 setStatusBarVisibility(false);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002916 mCustomViewContainer.setVisibility(View.VISIBLE);
2917 mCustomViewContainer.bringToFront();
2918 }
2919
2920 void onHideCustomView() {
2921 if (mCustomView == null)
2922 return;
2923
2924 // Hide the custom view.
2925 mCustomView.setVisibility(View.GONE);
2926 // Remove the custom view from its container.
2927 mCustomViewContainer.removeView(mCustomView);
2928 mCustomView = null;
2929 // Reset the old menu state.
2930 mMenuState = mOldMenuState;
2931 mOldMenuState = EMPTY_MENU;
2932 mCustomViewContainer.setVisibility(View.GONE);
2933 mCustomViewCallback.onCustomViewHidden();
2934 // Show the content view.
Andrei Popescu163ab742009-10-20 17:58:23 +01002935 setStatusBarVisibility(true);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002936 mContentView.setVisibility(View.VISIBLE);
2937 }
2938
2939 Bitmap getDefaultVideoPoster() {
2940 if (mDefaultVideoPoster == null) {
2941 mDefaultVideoPoster = BitmapFactory.decodeResource(
2942 getResources(), R.drawable.default_video_poster);
Patrick Scott3918d442009-08-04 13:22:29 -04002943 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002944 return mDefaultVideoPoster;
2945 }
Patrick Scott3918d442009-08-04 13:22:29 -04002946
Grace Kloba22ac16e2009-10-07 18:00:23 -07002947 View getVideoLoadingProgressView() {
2948 if (mVideoProgressView == null) {
2949 LayoutInflater inflater = LayoutInflater.from(BrowserActivity.this);
2950 mVideoProgressView = inflater.inflate(
2951 R.layout.video_loading_progress, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002952 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002953 return mVideoProgressView;
2954 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002955
Leon Scroggins8d5fa432009-10-02 15:55:59 -04002956 /*
2957 * The Object used to inform the WebView of the file to upload.
2958 */
2959 private ValueCallback<Uri> mUploadMessage;
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002960 private String mCameraFilePath;
Leon Scroggins8d5fa432009-10-02 15:55:59 -04002961
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002962 void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
2963
2964 final String imageMimeType = "image/*";
Ben Murdoch6af492a2010-06-15 12:38:17 +01002965 final String videoMimeType = "video/*";
Ben Murdoch039bd472010-07-21 21:26:57 +01002966 final String audioMimeType = "audio/*";
Ben Murdochb50d7402010-07-16 12:42:22 +01002967 final String mediaSourceKey = "capture";
Ben Murdoch6af492a2010-06-15 12:38:17 +01002968 final String mediaSourceValueCamera = "camera";
Ben Murdochb50d7402010-07-16 12:42:22 +01002969 final String mediaSourceValueFileSystem = "filesystem";
Ben Murdoch6af492a2010-06-15 12:38:17 +01002970 final String mediaSourceValueCamcorder = "camcorder";
Ben Murdoch039bd472010-07-21 21:26:57 +01002971 final String mediaSourceValueMicrophone = "microphone";
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002972
Ben Murdoch039bd472010-07-21 21:26:57 +01002973 // media source can be 'filesystem' or 'camera' or 'camcorder' or 'microphone'.
Ben Murdoch6af492a2010-06-15 12:38:17 +01002974 String mediaSource = "";
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002975
Ben Murdoch6af492a2010-06-15 12:38:17 +01002976 // We add the camera intent if there was no accept type (or '*/*' or 'image/*').
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002977 boolean addCameraIntent = true;
Ben Murdoch6af492a2010-06-15 12:38:17 +01002978 // We add the camcorder intent if there was no accept type (or '*/*' or 'video/*').
2979 boolean addCamcorderIntent = true;
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002980
Ben Murdoch6af492a2010-06-15 12:38:17 +01002981 if (mUploadMessage != null) {
2982 // Already a file picker operation in progress.
2983 return;
2984 }
2985
Grace Kloba22ac16e2009-10-07 18:00:23 -07002986 mUploadMessage = uploadMsg;
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002987
2988 // Parse the accept type.
2989 String params[] = acceptType.split(";");
2990 String mimeType = params[0];
2991
2992 for (String p : params) {
2993 String[] keyValue = p.split("=");
2994 if (keyValue.length == 2) {
2995 // Process key=value parameters.
Ben Murdoch6af492a2010-06-15 12:38:17 +01002996 if (mediaSourceKey.equals(keyValue[0])) {
2997 mediaSource = keyValue[1];
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002998 }
2999 }
3000 }
3001
3002 // This intent will display the standard OPENABLE file picker.
Grace Kloba22ac16e2009-10-07 18:00:23 -07003003 Intent i = new Intent(Intent.ACTION_GET_CONTENT);
3004 i.addCategory(Intent.CATEGORY_OPENABLE);
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003005
3006 // Create an intent to add to the standard file picker that will
3007 // capture an image from the camera. We'll combine this intent with
3008 // the standard OPENABLE picker unless the web developer specifically
3009 // requested the camera or gallery be opened by passing a parameter
3010 // in the accept type.
3011 Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
3012 File externalDataDir = Environment.getExternalStoragePublicDirectory(
3013 Environment.DIRECTORY_DCIM);
3014 File cameraDataDir = new File(externalDataDir.getAbsolutePath() +
3015 File.separator + "browser-photos");
3016 cameraDataDir.mkdirs();
3017 mCameraFilePath = cameraDataDir.getAbsolutePath() + File.separator +
3018 System.currentTimeMillis() + ".jpg";
3019 cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(mCameraFilePath)));
3020
Ben Murdoch6af492a2010-06-15 12:38:17 +01003021 Intent camcorderIntent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
3022
Ben Murdoch039bd472010-07-21 21:26:57 +01003023 Intent soundRecIntent = new Intent(MediaStore.Audio.Media.RECORD_SOUND_ACTION);
3024
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003025 if (mimeType.equals(imageMimeType)) {
3026 i.setType(imageMimeType);
Ben Murdoch6af492a2010-06-15 12:38:17 +01003027 addCamcorderIntent = false;
3028 if (mediaSource.equals(mediaSourceValueCamera)) {
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003029 // Specified 'image/*' and requested the camera, so go ahead and launch the camera
3030 // directly.
3031 BrowserActivity.this.startActivityForResult(cameraIntent, FILE_SELECTED);
3032 return;
Ben Murdochb50d7402010-07-16 12:42:22 +01003033 } else if (mediaSource.equals(mediaSourceValueFileSystem)) {
3034 // Specified filesytem as the source, so don't want to consider the camera.
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003035 addCameraIntent = false;
3036 }
Ben Murdoch6af492a2010-06-15 12:38:17 +01003037 } else if (mimeType.equals(videoMimeType)) {
3038 i.setType(videoMimeType);
3039 addCameraIntent = false;
3040 // The camcorder saves it's own file and returns it to us in the intent, so
3041 // we don't need to generate one here.
3042 mCameraFilePath = null;
3043
3044 if (mediaSource.equals(mediaSourceValueCamcorder)) {
Ben Murdoch039bd472010-07-21 21:26:57 +01003045 // Specified 'video/*' and requested the camcorder, so go ahead and launch the
3046 // camcorder directly.
Ben Murdoch6af492a2010-06-15 12:38:17 +01003047 BrowserActivity.this.startActivityForResult(camcorderIntent, FILE_SELECTED);
3048 return;
Ben Murdochb50d7402010-07-16 12:42:22 +01003049 } else if (mediaSource.equals(mediaSourceValueFileSystem)) {
3050 // Specified filesystem as the source, so don't want to consider the camcorder.
Ben Murdoch6af492a2010-06-15 12:38:17 +01003051 addCamcorderIntent = false;
3052 }
Ben Murdoch039bd472010-07-21 21:26:57 +01003053 } else if (mimeType.equals(audioMimeType)) {
3054 i.setType(audioMimeType);
3055 addCameraIntent = false;
3056 addCamcorderIntent = false;
3057 if (mediaSource.equals(mediaSourceValueMicrophone)) {
3058 // Specified 'audio/*' and requested microphone, so go ahead and launch the sound
3059 // recorder.
3060 BrowserActivity.this.startActivityForResult(soundRecIntent, FILE_SELECTED);
3061 return;
3062 }
3063 // On a default system, there is no single option to open an audio "gallery". Both the
3064 // sound recorder and music browser respond to the OPENABLE/audio/* intent unlike the
3065 // image/* and video/* OPENABLE intents where the image / video gallery are the only
3066 // respondants (and so the user is not prompted by default).
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003067 } else {
3068 i.setType("*/*");
3069 }
3070
Ben Murdoch6af492a2010-06-15 12:38:17 +01003071 // Combine the chooser and the extra choices (like camera or camcorder)
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003072 Intent chooser = new Intent(Intent.ACTION_CHOOSER);
3073 chooser.putExtra(Intent.EXTRA_INTENT, i);
3074
Ben Murdoch6af492a2010-06-15 12:38:17 +01003075 Vector<Intent> extraInitialIntents = new Vector<Intent>(0);
3076
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003077 if (addCameraIntent) {
Ben Murdoch6af492a2010-06-15 12:38:17 +01003078 extraInitialIntents.add(cameraIntent);
3079 }
3080
3081 if (addCamcorderIntent) {
3082 extraInitialIntents.add(camcorderIntent);
3083 }
3084
3085 if (extraInitialIntents.size() > 0) {
3086 Intent[] extraIntents = new Intent[extraInitialIntents.size()];
3087 chooser.putExtra(Intent.EXTRA_INITIAL_INTENTS, extraInitialIntents.toArray(extraIntents));
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003088 }
3089
3090 chooser.putExtra(Intent.EXTRA_TITLE, getString(R.string.choose_upload));
3091 BrowserActivity.this.startActivityForResult(chooser, FILE_SELECTED);
Grace Kloba22ac16e2009-10-07 18:00:23 -07003092 }
3093
3094 // -------------------------------------------------------------------------
3095 // Implement functions for DownloadListener
3096 // -------------------------------------------------------------------------
3097
The Android Open Source Project0c908882009-03-03 19:32:16 -08003098 /**
3099 * Notify the host application a download should be done, or that
3100 * the data should be streamed if a streaming viewer is available.
3101 * @param url The full url to the content that should be downloaded
3102 * @param contentDisposition Content-disposition http header, if
3103 * present.
3104 * @param mimetype The mimetype of the content reported by the server
3105 * @param contentLength The file size reported by the server
3106 */
3107 public void onDownloadStart(String url, String userAgent,
3108 String contentDisposition, String mimetype, long contentLength) {
3109 // if we're dealing wih A/V content that's not explicitly marked
3110 // for download, check if it's streamable.
3111 if (contentDisposition == null
Patrick Scotte1fb9662009-08-31 14:31:52 -04003112 || !contentDisposition.regionMatches(
3113 true, 0, "attachment", 0, 10)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003114 // query the package manager to see if there's a registered handler
3115 // that matches.
3116 Intent intent = new Intent(Intent.ACTION_VIEW);
3117 intent.setDataAndType(Uri.parse(url), mimetype);
Patrick Scotte1fb9662009-08-31 14:31:52 -04003118 ResolveInfo info = getPackageManager().resolveActivity(intent,
3119 PackageManager.MATCH_DEFAULT_ONLY);
3120 if (info != null) {
3121 ComponentName myName = getComponentName();
3122 // If we resolved to ourselves, we don't want to attempt to
3123 // load the url only to try and download it again.
3124 if (!myName.getPackageName().equals(
3125 info.activityInfo.packageName)
3126 || !myName.getClassName().equals(
3127 info.activityInfo.name)) {
3128 // someone (other than us) knows how to handle this mime
3129 // type with this scheme, don't download.
3130 try {
3131 startActivity(intent);
3132 return;
3133 } catch (ActivityNotFoundException ex) {
3134 if (LOGD_ENABLED) {
3135 Log.d(LOGTAG, "activity not found for " + mimetype
3136 + " over " + Uri.parse(url).getScheme(),
3137 ex);
3138 }
3139 // Best behavior is to fall back to a download in this
3140 // case
The Android Open Source Project0c908882009-03-03 19:32:16 -08003141 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003142 }
3143 }
3144 }
3145 onDownloadStartNoStream(url, userAgent, contentDisposition, mimetype, contentLength);
3146 }
3147
Kristian Monsenfa52d172010-03-25 18:29:21 +00003148 // This is to work around the fact that java.net.URI throws Exceptions
3149 // instead of just encoding URL's properly
3150 // Helper method for onDownloadStartNoStream
3151 private static String encodePath(String path) {
3152 char[] chars = path.toCharArray();
3153
3154 boolean needed = false;
3155 for (char c : chars) {
3156 if (c == '[' || c == ']') {
3157 needed = true;
3158 break;
3159 }
3160 }
3161 if (needed == false) {
3162 return path;
3163 }
3164
3165 StringBuilder sb = new StringBuilder("");
3166 for (char c : chars) {
3167 if (c == '[' || c == ']') {
3168 sb.append('%');
3169 sb.append(Integer.toHexString(c));
3170 } else {
3171 sb.append(c);
3172 }
3173 }
3174
3175 return sb.toString();
3176 }
3177
The Android Open Source Project0c908882009-03-03 19:32:16 -08003178 /**
3179 * Notify the host application a download should be done, even if there
3180 * is a streaming viewer available for thise type.
3181 * @param url The full url to the content that should be downloaded
3182 * @param contentDisposition Content-disposition http header, if
3183 * present.
3184 * @param mimetype The mimetype of the content reported by the server
3185 * @param contentLength The file size reported by the server
3186 */
3187 /*package */ void onDownloadStartNoStream(String url, String userAgent,
3188 String contentDisposition, String mimetype, long contentLength) {
3189
3190 String filename = URLUtil.guessFileName(url,
3191 contentDisposition, mimetype);
3192
3193 // Check to see if we have an SDCard
3194 String status = Environment.getExternalStorageState();
3195 if (!status.equals(Environment.MEDIA_MOUNTED)) {
3196 int title;
3197 String msg;
3198
3199 // Check to see if the SDCard is busy, same as the music app
3200 if (status.equals(Environment.MEDIA_SHARED)) {
3201 msg = getString(R.string.download_sdcard_busy_dlg_msg);
3202 title = R.string.download_sdcard_busy_dlg_title;
3203 } else {
3204 msg = getString(R.string.download_no_sdcard_dlg_msg, filename);
3205 title = R.string.download_no_sdcard_dlg_title;
3206 }
3207
3208 new AlertDialog.Builder(this)
3209 .setTitle(title)
3210 .setIcon(android.R.drawable.ic_dialog_alert)
3211 .setMessage(msg)
3212 .setPositiveButton(R.string.ok, null)
3213 .show();
3214 return;
3215 }
3216
Kristian Monsenfa52d172010-03-25 18:29:21 +00003217 // java.net.URI is a lot stricter than KURL so we have to encode some
3218 // extra characters. Fix for b 2538060 and b 1634719
3219 WebAddress webAddress;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003220 try {
Kristian Monsenfa52d172010-03-25 18:29:21 +00003221 webAddress = new WebAddress(url);
3222 webAddress.mPath = encodePath(webAddress.mPath);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003223 } catch (Exception e) {
Kristian Monsenfa52d172010-03-25 18:29:21 +00003224 // This only happens for very bad urls, we want to chatch the
3225 // exception here
3226 Log.e(LOGTAG, "Exception trying to parse url:" + url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003227 return;
3228 }
3229
3230 // XXX: Have to use the old url since the cookies were stored using the
3231 // old percent-encoded url.
3232 String cookies = CookieManager.getInstance().getCookie(url);
3233
3234 ContentValues values = new ContentValues();
Kristian Monsenfa52d172010-03-25 18:29:21 +00003235 values.put(Downloads.Impl.COLUMN_URI, webAddress.toString());
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08003236 values.put(Downloads.Impl.COLUMN_COOKIE_DATA, cookies);
3237 values.put(Downloads.Impl.COLUMN_USER_AGENT, userAgent);
3238 values.put(Downloads.Impl.COLUMN_NOTIFICATION_PACKAGE,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003239 getPackageName());
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08003240 values.put(Downloads.Impl.COLUMN_NOTIFICATION_CLASS,
Leon Scrogginsa563d092010-04-19 16:53:49 -04003241 OpenDownloadReceiver.class.getCanonicalName());
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08003242 values.put(Downloads.Impl.COLUMN_VISIBILITY,
3243 Downloads.Impl.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
3244 values.put(Downloads.Impl.COLUMN_MIME_TYPE, mimetype);
3245 values.put(Downloads.Impl.COLUMN_FILE_NAME_HINT, filename);
Kristian Monsenfa52d172010-03-25 18:29:21 +00003246 values.put(Downloads.Impl.COLUMN_DESCRIPTION, webAddress.mHost);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003247 if (contentLength > 0) {
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08003248 values.put(Downloads.Impl.COLUMN_TOTAL_BYTES, contentLength);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003249 }
3250 if (mimetype == null) {
3251 // We must have long pressed on a link or image to download it. We
3252 // are not sure of the mimetype in this case, so do a head request
3253 new FetchUrlMimeType(this).execute(values);
3254 } else {
3255 final Uri contentUri =
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08003256 getContentResolver().insert(Downloads.Impl.CONTENT_URI, values);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003257 }
Leon Scroggins9191a7f2010-03-18 14:44:44 -04003258 Toast.makeText(this, R.string.download_pending, Toast.LENGTH_SHORT)
3259 .show();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003260 }
3261
Grace Kloba22ac16e2009-10-07 18:00:23 -07003262 // -------------------------------------------------------------------------
3263
The Android Open Source Project0c908882009-03-03 19:32:16 -08003264 /**
3265 * Resets the lock icon. This method is called when we start a new load and
3266 * know the url to be loaded.
3267 */
3268 private void resetLockIcon(String url) {
3269 // Save the lock-icon state (we revert to it if the load gets cancelled)
Grace Kloba22ac16e2009-10-07 18:00:23 -07003270 mTabControl.getCurrentTab().resetLockIcon(url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003271 updateLockIconImage(LOCK_ICON_UNSECURE);
3272 }
3273
The Android Open Source Project0c908882009-03-03 19:32:16 -08003274 /**
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04003275 * Update the lock icon to correspond to our latest state.
3276 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003277 private void updateLockIconToLatest() {
Leon Scroggins91f65fc2010-06-29 13:52:39 -04003278 Tab t = mTabControl.getCurrentTab();
3279 if (t != null) {
3280 updateLockIconImage(t.getLockIconType());
3281 }
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04003282 }
3283
3284 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08003285 * Updates the lock-icon image in the title-bar.
3286 */
3287 private void updateLockIconImage(int lockIconType) {
3288 Drawable d = null;
3289 if (lockIconType == LOCK_ICON_SECURE) {
3290 d = mSecLockIcon;
3291 } else if (lockIconType == LOCK_ICON_MIXED) {
3292 d = mMixLockIcon;
3293 }
Leon Scroggins68579392009-09-15 15:31:54 -04003294 mTitleBar.setLock(d);
Michael Kolba2b2ba82010-08-04 17:54:03 -07003295 mFakeTitleBar.setLock(d);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003296 }
3297
3298 /**
3299 * Displays a page-info dialog.
3300 * @param tab The tab to show info about
3301 * @param fromShowSSLCertificateOnError The flag that indicates whether
3302 * this dialog was opened from the SSL-certificate-on-error dialog or
3303 * not. This is important, since we need to know whether to return to
3304 * the parent dialog or simply dismiss.
3305 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003306 private void showPageInfo(final Tab tab,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003307 final boolean fromShowSSLCertificateOnError) {
3308 final LayoutInflater factory = LayoutInflater
3309 .from(this);
3310
3311 final View pageInfoView = factory.inflate(R.layout.page_info, null);
3312
3313 final WebView view = tab.getWebView();
3314
3315 String url = null;
3316 String title = null;
3317
3318 if (view == null) {
3319 url = tab.getUrl();
3320 title = tab.getTitle();
3321 } else if (view == mTabControl.getCurrentWebView()) {
3322 // Use the cached title and url if this is the current WebView
3323 url = mUrl;
3324 title = mTitle;
3325 } else {
3326 url = view.getUrl();
3327 title = view.getTitle();
3328 }
3329
3330 if (url == null) {
3331 url = "";
3332 }
3333 if (title == null) {
3334 title = "";
3335 }
3336
3337 ((TextView) pageInfoView.findViewById(R.id.address)).setText(url);
3338 ((TextView) pageInfoView.findViewById(R.id.title)).setText(title);
3339
3340 mPageInfoView = tab;
Leon Scrogginsc7b92f82010-01-11 18:17:31 -05003341 mPageInfoFromShowSSLCertificateOnError = fromShowSSLCertificateOnError;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003342
3343 AlertDialog.Builder alertDialogBuilder =
3344 new AlertDialog.Builder(this)
3345 .setTitle(R.string.page_info).setIcon(android.R.drawable.ic_dialog_info)
3346 .setView(pageInfoView)
3347 .setPositiveButton(
3348 R.string.ok,
3349 new DialogInterface.OnClickListener() {
3350 public void onClick(DialogInterface dialog,
3351 int whichButton) {
3352 mPageInfoDialog = null;
3353 mPageInfoView = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003354
3355 // if we came here from the SSL error dialog
3356 if (fromShowSSLCertificateOnError) {
3357 // go back to the SSL error dialog
3358 showSSLCertificateOnError(
3359 mSSLCertificateOnErrorView,
3360 mSSLCertificateOnErrorHandler,
3361 mSSLCertificateOnErrorError);
3362 }
3363 }
3364 })
3365 .setOnCancelListener(
3366 new DialogInterface.OnCancelListener() {
3367 public void onCancel(DialogInterface dialog) {
3368 mPageInfoDialog = null;
3369 mPageInfoView = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003370
3371 // if we came here from the SSL error dialog
3372 if (fromShowSSLCertificateOnError) {
3373 // go back to the SSL error dialog
3374 showSSLCertificateOnError(
3375 mSSLCertificateOnErrorView,
3376 mSSLCertificateOnErrorHandler,
3377 mSSLCertificateOnErrorError);
3378 }
3379 }
3380 });
3381
3382 // if we have a main top-level page SSL certificate set or a certificate
3383 // error
3384 if (fromShowSSLCertificateOnError ||
3385 (view != null && view.getCertificate() != null)) {
3386 // add a 'View Certificate' button
3387 alertDialogBuilder.setNeutralButton(
3388 R.string.view_certificate,
3389 new DialogInterface.OnClickListener() {
3390 public void onClick(DialogInterface dialog,
3391 int whichButton) {
3392 mPageInfoDialog = null;
3393 mPageInfoView = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003394
3395 // if we came here from the SSL error dialog
3396 if (fromShowSSLCertificateOnError) {
3397 // go back to the SSL error dialog
3398 showSSLCertificateOnError(
3399 mSSLCertificateOnErrorView,
3400 mSSLCertificateOnErrorHandler,
3401 mSSLCertificateOnErrorError);
3402 } else {
3403 // otherwise, display the top-most certificate from
3404 // the chain
3405 if (view.getCertificate() != null) {
3406 showSSLCertificate(tab);
3407 }
3408 }
3409 }
3410 });
3411 }
3412
3413 mPageInfoDialog = alertDialogBuilder.show();
3414 }
3415
3416 /**
3417 * Displays the main top-level page SSL certificate dialog
3418 * (accessible from the Page-Info dialog).
3419 * @param tab The tab to show certificate for.
3420 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003421 private void showSSLCertificate(final Tab tab) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003422 final View certificateView =
3423 inflateCertificateView(tab.getWebView().getCertificate());
3424 if (certificateView == null) {
3425 return;
3426 }
3427
3428 LayoutInflater factory = LayoutInflater.from(this);
3429
3430 final LinearLayout placeholder =
3431 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3432
3433 LinearLayout ll = (LinearLayout) factory.inflate(
3434 R.layout.ssl_success, placeholder);
3435 ((TextView)ll.findViewById(R.id.success))
3436 .setText(R.string.ssl_certificate_is_valid);
3437
3438 mSSLCertificateView = tab;
3439 mSSLCertificateDialog =
3440 new AlertDialog.Builder(this)
3441 .setTitle(R.string.ssl_certificate).setIcon(
3442 R.drawable.ic_dialog_browser_certificate_secure)
3443 .setView(certificateView)
3444 .setPositiveButton(R.string.ok,
3445 new DialogInterface.OnClickListener() {
3446 public void onClick(DialogInterface dialog,
3447 int whichButton) {
3448 mSSLCertificateDialog = null;
3449 mSSLCertificateView = null;
3450
3451 showPageInfo(tab, false);
3452 }
3453 })
3454 .setOnCancelListener(
3455 new DialogInterface.OnCancelListener() {
3456 public void onCancel(DialogInterface dialog) {
3457 mSSLCertificateDialog = null;
3458 mSSLCertificateView = null;
3459
3460 showPageInfo(tab, false);
3461 }
3462 })
3463 .show();
3464 }
3465
3466 /**
3467 * Displays the SSL error certificate dialog.
3468 * @param view The target web-view.
3469 * @param handler The SSL error handler responsible for cancelling the
3470 * connection that resulted in an SSL error or proceeding per user request.
3471 * @param error The SSL error object.
3472 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003473 void showSSLCertificateOnError(
The Android Open Source Project0c908882009-03-03 19:32:16 -08003474 final WebView view, final SslErrorHandler handler, final SslError error) {
3475
3476 final View certificateView =
3477 inflateCertificateView(error.getCertificate());
3478 if (certificateView == null) {
3479 return;
3480 }
3481
3482 LayoutInflater factory = LayoutInflater.from(this);
3483
3484 final LinearLayout placeholder =
3485 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3486
3487 if (error.hasError(SslError.SSL_UNTRUSTED)) {
3488 LinearLayout ll = (LinearLayout)factory
3489 .inflate(R.layout.ssl_warning, placeholder);
3490 ((TextView)ll.findViewById(R.id.warning))
3491 .setText(R.string.ssl_untrusted);
3492 }
3493
3494 if (error.hasError(SslError.SSL_IDMISMATCH)) {
3495 LinearLayout ll = (LinearLayout)factory
3496 .inflate(R.layout.ssl_warning, placeholder);
3497 ((TextView)ll.findViewById(R.id.warning))
3498 .setText(R.string.ssl_mismatch);
3499 }
3500
3501 if (error.hasError(SslError.SSL_EXPIRED)) {
3502 LinearLayout ll = (LinearLayout)factory
3503 .inflate(R.layout.ssl_warning, placeholder);
3504 ((TextView)ll.findViewById(R.id.warning))
3505 .setText(R.string.ssl_expired);
3506 }
3507
3508 if (error.hasError(SslError.SSL_NOTYETVALID)) {
3509 LinearLayout ll = (LinearLayout)factory
3510 .inflate(R.layout.ssl_warning, placeholder);
3511 ((TextView)ll.findViewById(R.id.warning))
3512 .setText(R.string.ssl_not_yet_valid);
3513 }
3514
3515 mSSLCertificateOnErrorHandler = handler;
3516 mSSLCertificateOnErrorView = view;
3517 mSSLCertificateOnErrorError = error;
3518 mSSLCertificateOnErrorDialog =
3519 new AlertDialog.Builder(this)
3520 .setTitle(R.string.ssl_certificate).setIcon(
3521 R.drawable.ic_dialog_browser_certificate_partially_secure)
3522 .setView(certificateView)
3523 .setPositiveButton(R.string.ok,
3524 new DialogInterface.OnClickListener() {
3525 public void onClick(DialogInterface dialog,
3526 int whichButton) {
3527 mSSLCertificateOnErrorDialog = null;
3528 mSSLCertificateOnErrorView = null;
3529 mSSLCertificateOnErrorHandler = null;
3530 mSSLCertificateOnErrorError = null;
3531
Grace Kloba22ac16e2009-10-07 18:00:23 -07003532 view.getWebViewClient().onReceivedSslError(
3533 view, handler, error);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003534 }
3535 })
3536 .setNeutralButton(R.string.page_info_view,
3537 new DialogInterface.OnClickListener() {
3538 public void onClick(DialogInterface dialog,
3539 int whichButton) {
3540 mSSLCertificateOnErrorDialog = null;
3541
3542 // do not clear the dialog state: we will
3543 // need to show the dialog again once the
3544 // user is done exploring the page-info details
3545
3546 showPageInfo(mTabControl.getTabFromView(view),
3547 true);
3548 }
3549 })
3550 .setOnCancelListener(
3551 new DialogInterface.OnCancelListener() {
3552 public void onCancel(DialogInterface dialog) {
3553 mSSLCertificateOnErrorDialog = null;
3554 mSSLCertificateOnErrorView = null;
3555 mSSLCertificateOnErrorHandler = null;
3556 mSSLCertificateOnErrorError = null;
3557
Grace Kloba22ac16e2009-10-07 18:00:23 -07003558 view.getWebViewClient().onReceivedSslError(
3559 view, handler, error);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003560 }
3561 })
3562 .show();
3563 }
3564
3565 /**
3566 * Inflates the SSL certificate view (helper method).
3567 * @param certificate The SSL certificate.
3568 * @return The resultant certificate view with issued-to, issued-by,
3569 * issued-on, expires-on, and possibly other fields set.
3570 * If the input certificate is null, returns null.
3571 */
3572 private View inflateCertificateView(SslCertificate certificate) {
3573 if (certificate == null) {
3574 return null;
3575 }
3576
3577 LayoutInflater factory = LayoutInflater.from(this);
3578
3579 View certificateView = factory.inflate(
3580 R.layout.ssl_certificate, null);
3581
3582 // issued to:
3583 SslCertificate.DName issuedTo = certificate.getIssuedTo();
3584 if (issuedTo != null) {
3585 ((TextView) certificateView.findViewById(R.id.to_common))
3586 .setText(issuedTo.getCName());
3587 ((TextView) certificateView.findViewById(R.id.to_org))
3588 .setText(issuedTo.getOName());
3589 ((TextView) certificateView.findViewById(R.id.to_org_unit))
3590 .setText(issuedTo.getUName());
3591 }
3592
3593 // issued by:
3594 SslCertificate.DName issuedBy = certificate.getIssuedBy();
3595 if (issuedBy != null) {
3596 ((TextView) certificateView.findViewById(R.id.by_common))
3597 .setText(issuedBy.getCName());
3598 ((TextView) certificateView.findViewById(R.id.by_org))
3599 .setText(issuedBy.getOName());
3600 ((TextView) certificateView.findViewById(R.id.by_org_unit))
3601 .setText(issuedBy.getUName());
3602 }
3603
3604 // issued on:
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003605 String issuedOn = formatCertificateDate(
3606 certificate.getValidNotBeforeDate());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003607 ((TextView) certificateView.findViewById(R.id.issued_on))
3608 .setText(issuedOn);
3609
3610 // expires on:
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003611 String expiresOn = formatCertificateDate(
3612 certificate.getValidNotAfterDate());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003613 ((TextView) certificateView.findViewById(R.id.expires_on))
3614 .setText(expiresOn);
3615
3616 return certificateView;
3617 }
3618
3619 /**
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003620 * Formats the certificate date to a properly localized date string.
The Android Open Source Project0c908882009-03-03 19:32:16 -08003621 * @return Properly localized version of the certificate date string and
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003622 * the "" if it fails to localize.
The Android Open Source Project0c908882009-03-03 19:32:16 -08003623 */
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003624 private String formatCertificateDate(Date certificateDate) {
3625 if (certificateDate == null) {
3626 return "";
The Android Open Source Project0c908882009-03-03 19:32:16 -08003627 }
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003628 String formattedDate = DateFormat.getDateFormat(this).format(certificateDate);
3629 if (formattedDate == null) {
3630 return "";
3631 }
3632 return formattedDate;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003633 }
3634
3635 /**
3636 * Displays an http-authentication dialog.
3637 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003638 void showHttpAuthentication(final HttpAuthHandler handler,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003639 final String host, final String realm, final String title,
3640 final String name, final String password, int focusId) {
3641 LayoutInflater factory = LayoutInflater.from(this);
3642 final View v = factory
3643 .inflate(R.layout.http_authentication, null);
3644 if (name != null) {
3645 ((EditText) v.findViewById(R.id.username_edit)).setText(name);
3646 }
3647 if (password != null) {
3648 ((EditText) v.findViewById(R.id.password_edit)).setText(password);
3649 }
3650
3651 String titleText = title;
3652 if (titleText == null) {
3653 titleText = getText(R.string.sign_in_to).toString().replace(
3654 "%s1", host).replace("%s2", realm);
3655 }
3656
3657 mHttpAuthHandler = handler;
3658 AlertDialog dialog = new AlertDialog.Builder(this)
3659 .setTitle(titleText)
3660 .setIcon(android.R.drawable.ic_dialog_alert)
3661 .setView(v)
3662 .setPositiveButton(R.string.action,
3663 new DialogInterface.OnClickListener() {
3664 public void onClick(DialogInterface dialog,
3665 int whichButton) {
3666 String nm = ((EditText) v
3667 .findViewById(R.id.username_edit))
3668 .getText().toString();
3669 String pw = ((EditText) v
3670 .findViewById(R.id.password_edit))
3671 .getText().toString();
3672 BrowserActivity.this.setHttpAuthUsernamePassword
3673 (host, realm, nm, pw);
3674 handler.proceed(nm, pw);
3675 mHttpAuthenticationDialog = null;
3676 mHttpAuthHandler = null;
3677 }})
3678 .setNegativeButton(R.string.cancel,
3679 new DialogInterface.OnClickListener() {
3680 public void onClick(DialogInterface dialog,
3681 int whichButton) {
3682 handler.cancel();
3683 BrowserActivity.this.resetTitleAndRevertLockIcon();
3684 mHttpAuthenticationDialog = null;
3685 mHttpAuthHandler = null;
3686 }})
3687 .setOnCancelListener(new DialogInterface.OnCancelListener() {
3688 public void onCancel(DialogInterface dialog) {
3689 handler.cancel();
3690 BrowserActivity.this.resetTitleAndRevertLockIcon();
3691 mHttpAuthenticationDialog = null;
3692 mHttpAuthHandler = null;
3693 }})
3694 .create();
3695 // Make the IME appear when the dialog is displayed if applicable.
3696 dialog.getWindow().setSoftInputMode(
3697 WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
3698 dialog.show();
3699 if (focusId != 0) {
3700 dialog.findViewById(focusId).requestFocus();
3701 } else {
3702 v.findViewById(R.id.username_edit).requestFocus();
3703 }
3704 mHttpAuthenticationDialog = dialog;
3705 }
3706
3707 public int getProgress() {
3708 WebView w = mTabControl.getCurrentWebView();
3709 if (w != null) {
3710 return w.getProgress();
3711 } else {
3712 return 100;
3713 }
3714 }
3715
3716 /**
3717 * Set HTTP authentication password.
3718 *
3719 * @param host The host for the password
3720 * @param realm The realm for the password
3721 * @param username The username for the password. If it is null, it means
3722 * password can't be saved.
3723 * @param password The password
3724 */
3725 public void setHttpAuthUsernamePassword(String host, String realm,
3726 String username,
3727 String password) {
Steve Block95a53b22010-03-25 17:24:58 +00003728 WebView w = getTopWindow();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003729 if (w != null) {
3730 w.setHttpAuthUsernamePassword(host, realm, username, password);
3731 }
3732 }
3733
3734 /**
3735 * connectivity manager says net has come or gone... inform the user
3736 * @param up true if net has come up, false if net has gone down
3737 */
3738 public void onNetworkToggle(boolean up) {
3739 if (up == mIsNetworkUp) {
3740 return;
3741 } else if (up) {
3742 mIsNetworkUp = true;
3743 if (mAlertDialog != null) {
3744 mAlertDialog.cancel();
3745 mAlertDialog = null;
3746 }
3747 } else {
3748 mIsNetworkUp = false;
Patrick Scotteb6ab2a2009-09-16 10:00:17 -04003749 if (mInLoad) {
3750 createAndShowNetworkDialog();
3751 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003752 }
3753 WebView w = mTabControl.getCurrentWebView();
3754 if (w != null) {
3755 w.setNetworkAvailable(up);
3756 }
3757 }
3758
Grace Kloba22ac16e2009-10-07 18:00:23 -07003759 boolean isNetworkUp() {
3760 return mIsNetworkUp;
3761 }
3762
Patrick Scotteb6ab2a2009-09-16 10:00:17 -04003763 // This method shows the network dialog alerting the user that the net is
3764 // down. It will only show the dialog if mAlertDialog is null.
3765 private void createAndShowNetworkDialog() {
3766 if (mAlertDialog == null) {
3767 mAlertDialog = new AlertDialog.Builder(this)
3768 .setTitle(R.string.loadSuspendedTitle)
3769 .setMessage(R.string.loadSuspended)
3770 .setPositiveButton(R.string.ok, null)
3771 .show();
3772 }
3773 }
3774
The Android Open Source Project0c908882009-03-03 19:32:16 -08003775 @Override
3776 protected void onActivityResult(int requestCode, int resultCode,
3777 Intent intent) {
Grace Klobabb394f32009-11-19 10:26:37 -08003778 if (getTopWindow() == null) return;
3779
The Android Open Source Project0c908882009-03-03 19:32:16 -08003780 switch (requestCode) {
3781 case COMBO_PAGE:
3782 if (resultCode == RESULT_OK && intent != null) {
3783 String data = intent.getAction();
3784 Bundle extras = intent.getExtras();
Michael Kolb300b7f02010-08-25 13:47:24 -07003785 if (extras != null &&
3786 extras.getBoolean(
3787 CombinedBookmarkHistoryActivity.EXTRA_OPEN_NEW_WINDOW,
3788 false)) {
Michael Kolb68792c82010-08-09 16:39:18 -07003789 openTab(data, false);
3790 } else if ((extras != null) &&
3791 extras.getBoolean(CombinedBookmarkHistoryActivity.NEWTAB_MODE)) {
3792 openTab(data, true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003793 } else {
Michael Kolb68792c82010-08-09 16:39:18 -07003794 final Tab currentTab = mTabControl.getCurrentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04003795 dismissSubWindow(currentTab);
3796 if (data != null && data.length() != 0) {
Leon Scroggins92472e82010-02-17 16:32:28 -05003797 loadUrl(getTopWindow(), data);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003798 }
3799 }
Michael Kolb3f65c382010-08-20 15:31:16 -07003800 } else if (resultCode == RESULT_CANCELED) {
3801 if (intent != null) {
3802 float evtx = intent.getFloatExtra(CombinedBookmarkHistoryActivity.EVT_X, -1);
3803 float evty = intent.getFloatExtra(CombinedBookmarkHistoryActivity.EVT_Y, -1);
3804 long now = System.currentTimeMillis();
3805 MotionEvent evt = MotionEvent.obtain(now, now,
3806 MotionEvent.ACTION_DOWN, evtx, evty, 0);
3807 dispatchTouchEvent(evt);
3808 MotionEvent up = MotionEvent.obtain(evt);
3809 up.setAction(MotionEvent.ACTION_UP);
3810 dispatchTouchEvent(up);
3811 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003812 }
Leon Scrogginsfde97462010-01-11 13:06:21 -05003813 // Deliberately fall through to PREFERENCES_PAGE, since the
3814 // same extra may be attached to the COMBO_PAGE
3815 case PREFERENCES_PAGE:
3816 if (resultCode == RESULT_OK && intent != null) {
3817 String action = intent.getStringExtra(Intent.EXTRA_TEXT);
3818 if (BrowserSettings.PREF_CLEAR_HISTORY.equals(action)) {
3819 mTabControl.removeParentChildRelationShips();
3820 }
3821 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003822 break;
Leon Scroggins8d5fa432009-10-02 15:55:59 -04003823 // Choose a file from the file picker.
3824 case FILE_SELECTED:
3825 if (null == mUploadMessage) break;
3826 Uri result = intent == null || resultCode != RESULT_OK ? null
3827 : intent.getData();
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003828
3829 // As we ask the camera to save the result of the user taking
3830 // a picture, the camera application does not return anything other
3831 // than RESULT_OK. So we need to check whether the file we expected
3832 // was written to disk in the in the case that we
3833 // did not get an intent returned but did get a RESULT_OK. If it was,
3834 // we assume that this result has came back from the camera.
3835 if (result == null && intent == null && resultCode == RESULT_OK) {
3836 File cameraFile = new File(mCameraFilePath);
3837 if (cameraFile.exists()) {
3838 result = Uri.fromFile(cameraFile);
Ben Murdoch07d34732010-05-27 18:34:46 +01003839 // Broadcast to the media scanner that we have a new photo
3840 // so it will be added into the gallery for the user.
3841 sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, result));
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003842 }
3843 }
Leon Scroggins8d5fa432009-10-02 15:55:59 -04003844 mUploadMessage.onReceiveValue(result);
3845 mUploadMessage = null;
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003846 mCameraFilePath = null;
Leon Scroggins8d5fa432009-10-02 15:55:59 -04003847 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003848 default:
3849 break;
3850 }
Leon Scroggins30444232009-09-04 18:36:20 -04003851 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003852 }
3853
3854 /*
3855 * This method is called as a result of the user selecting the options
Leon Scrogginsf08809b2010-01-21 09:27:46 -05003856 * menu to see the download window. It shows the download window on top of
3857 * the current window.
The Android Open Source Project0c908882009-03-03 19:32:16 -08003858 */
Leon Scrogginsf08809b2010-01-21 09:27:46 -05003859 private void viewDownloads(Uri downloadRecord) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003860 Intent intent = new Intent(this,
3861 BrowserDownloadPage.class);
3862 intent.setData(downloadRecord);
Grace Kloba22ac16e2009-10-07 18:00:23 -07003863 startActivityForResult(intent, BrowserActivity.DOWNLOAD_PAGE);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003864
3865 }
3866
Ben Murdocheecb4e62010-07-06 16:30:38 +01003867 /* package*/ void promptAddOrInstallBookmark() {
3868 final Tab current = mTabControl.getCurrentTab();
3869 Resources resources = getResources();
3870 CharSequence[] choices = {
3871 resources.getString(R.string.save_to_bookmarks),
3872 resources.getString(R.string.create_shortcut_bookmark)
3873 };
3874
3875 AlertDialog.Builder builder = new AlertDialog.Builder(this);
3876 builder.setTitle(R.string.add_new_bookmark);
3877 builder.setItems(choices, new DialogInterface.OnClickListener() {
3878 public void onClick(DialogInterface dialog, int item) {
3879 if (item == 0) {
3880 bookmarkCurrentPage();
3881 } else if (item == 1) {
3882 current.populatePickerData();
3883 String touchIconUrl = mTabControl.getCurrentWebView().getTouchIconUrl();
3884 if (touchIconUrl != null) {
3885 // Download the touch icon for this site then save it to the
3886 // homescreen.
3887 Bundle b = new Bundle();
3888 b.putString("url", current.getUrl());
3889 b.putString("title", current.getTitle());
3890 b.putParcelable("favicon", current.getFavicon());
3891 Message msg = mHandler.obtainMessage(TOUCH_ICON_DOWNLOADED);
3892 msg.setData(b);
Ben Murdochccb5de02010-07-19 18:38:17 +01003893 new DownloadTouchIcon(BrowserActivity.this, msg,
Ben Murdocheecb4e62010-07-06 16:30:38 +01003894 mTabControl.getCurrentWebView().getSettings()
3895 .getUserAgentString()).execute(touchIconUrl);
3896 } else {
3897 // add to homescreen, can do it immediately as there is no touch
3898 // icon.
3899 showSaveToHomescreenDialog(current.getUrl(), current.getTitle(),
3900 null, current.getFavicon());
3901 }
3902 }
3903 }
3904 });
3905 builder.create().show();
3906 }
3907
Leon Scroggins160a7e72009-08-14 18:28:01 -04003908 /**
3909 * Open the Go page.
3910 * @param startWithHistory If true, open starting on the history tab.
3911 * Otherwise, start with the bookmarks tab.
Leon Scroggins160a7e72009-08-14 18:28:01 -04003912 */
Michael Kolb68792c82010-08-09 16:39:18 -07003913 /* package */ void bookmarksOrHistoryPicker(boolean startWithHistory, boolean newTabMode) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003914 WebView current = mTabControl.getCurrentWebView();
3915 if (current == null) {
3916 return;
3917 }
3918 Intent intent = new Intent(this,
3919 CombinedBookmarkHistoryActivity.class);
3920 String title = current.getTitle();
3921 String url = current.getUrl();
Ben Murdoch87cc65d2010-06-29 20:34:10 +01003922 Bitmap thumbnail = createScreenshot(current, getDesiredThumbnailWidth(this),
3923 getDesiredThumbnailHeight(this));
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01003924
The Android Open Source Project0c908882009-03-03 19:32:16 -08003925 // Just in case the user opens bookmarks before a page finishes loading
3926 // so the current history item, and therefore the page, is null.
3927 if (null == url) {
3928 url = mLastEnteredUrl;
3929 // This can happen.
3930 if (null == url) {
3931 url = mSettings.getHomePage();
3932 }
3933 }
3934 // In case the web page has not yet received its associated title.
3935 if (title == null) {
3936 title = url;
3937 }
3938 intent.putExtra("title", title);
3939 intent.putExtra("url", url);
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01003940 intent.putExtra("thumbnail", thumbnail);
Leon Scroggins30444232009-09-04 18:36:20 -04003941 // Disable opening in a new window if we have maxed out the windows
Grace Kloba22ac16e2009-10-07 18:00:23 -07003942 intent.putExtra("disable_new_window", !mTabControl.canCreateNewTab());
Patrick Scott3918d442009-08-04 13:22:29 -04003943 intent.putExtra("touch_icon_url", current.getTouchIconUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003944 if (startWithHistory) {
Jeff Hamilton64144e42010-08-18 16:31:59 -05003945 intent.putExtra(CombinedBookmarkHistoryActivity.STARTING_FRAGMENT,
3946 CombinedBookmarkHistoryActivity.FRAGMENT_ID_HISTORY);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003947 }
Michael Kolb300b7f02010-08-25 13:47:24 -07003948 intent.putExtra(CombinedBookmarkHistoryActivity.NEWTAB_MODE, newTabMode);
Michael Kolb0998b0a2010-08-23 17:45:35 -07003949 int top = -1;
3950 int height = -1;
Michael Kolb3f65c382010-08-20 15:31:16 -07003951 if (mXLargeScreenSize) {
3952 showFakeTitleBar();
3953 int titleBarHeight = ((TitleBarXLarge)mFakeTitleBar).getHeightWithoutProgress();
Michael Kolb0998b0a2010-08-23 17:45:35 -07003954 top = mTabBar.getBottom() + titleBarHeight;
3955 height = getTopWindow().getHeight() - titleBarHeight;
Michael Kolb68792c82010-08-09 16:39:18 -07003956 }
Michael Kolb0998b0a2010-08-23 17:45:35 -07003957 intent.putExtra(CombinedBookmarkHistoryActivity.EXTRA_TOP, top);
3958 intent.putExtra(CombinedBookmarkHistoryActivity.EXTRA_HEIGHT, height);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003959 startActivityForResult(intent, COMBO_PAGE);
3960 }
3961
Ben Murdocheecb4e62010-07-06 16:30:38 +01003962 private void showSaveToHomescreenDialog(String url, String title, Bitmap touchIcon,
3963 Bitmap favicon) {
3964 Intent intent = new Intent(this, SaveToHomescreenDialog.class);
3965
3966 // Just in case the user tries to save before a page finishes loading
3967 // so the current history item, and therefore the page, is null.
3968 if (null == url) {
3969 url = mLastEnteredUrl;
3970 // This can happen.
3971 if (null == url) {
3972 url = mSettings.getHomePage();
3973 }
3974 }
3975
3976 // In case the web page has not yet received its associated title.
3977 if (title == null) {
3978 title = url;
3979 }
3980
3981 intent.putExtra("title", title);
3982 intent.putExtra("url", url);
3983 intent.putExtra("favicon", favicon);
3984 intent.putExtra("touchIcon", touchIcon);
3985 startActivity(intent);
3986 }
3987
3988
The Android Open Source Project0c908882009-03-03 19:32:16 -08003989 // Called when loading from context menu or LOAD_URL message
Leon Scroggins92472e82010-02-17 16:32:28 -05003990 private void loadUrlFromContext(WebView view, String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003991 // In case the user enters nothing.
3992 if (url != null && url.length() != 0 && view != null) {
3993 url = smartUrlFilter(url);
Grace Kloba22ac16e2009-10-07 18:00:23 -07003994 if (!view.getWebViewClient().shouldOverrideUrlLoading(view, url)) {
Leon Scroggins92472e82010-02-17 16:32:28 -05003995 loadUrl(view, url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003996 }
3997 }
3998 }
3999
Leon Scroggins92472e82010-02-17 16:32:28 -05004000 /**
4001 * Load the URL into the given WebView and update the title bar
4002 * to reflect the new load. Call this instead of WebView.loadUrl
4003 * directly.
4004 * @param view The WebView used to load url.
4005 * @param url The URL to load.
4006 */
4007 private void loadUrl(WebView view, String url) {
4008 updateTitleBarForNewLoad(view, url);
4009 view.loadUrl(url);
4010 }
4011
4012 /**
4013 * Load UrlData into a Tab and update the title bar to reflect the new
4014 * load. Call this instead of UrlData.loadIn directly.
4015 * @param t The Tab used to load.
4016 * @param data The UrlData being loaded.
4017 */
4018 private void loadUrlDataIn(Tab t, UrlData data) {
4019 updateTitleBarForNewLoad(t.getWebView(), data.mUrl);
4020 data.loadIn(t);
4021 }
4022
4023 /**
4024 * If the WebView is the top window, update the title bar to reflect
4025 * loading the new URL. i.e. set its text, clear the favicon (which
4026 * will be set once the page begins loading), and set the progress to
4027 * INITIAL_PROGRESS to show that the page has begun to load. Called
4028 * by loadUrl and loadUrlDataIn.
4029 * @param view The WebView that is starting a load.
4030 * @param url The URL that is being loaded.
4031 */
4032 private void updateTitleBarForNewLoad(WebView view, String url) {
4033 if (view == getTopWindow()) {
4034 setUrlTitle(url, null);
4035 setFavicon(null);
4036 onProgressChanged(view, INITIAL_PROGRESS);
4037 }
4038 }
4039
The Android Open Source Project0c908882009-03-03 19:32:16 -08004040 private String smartUrlFilter(Uri inUri) {
4041 if (inUri != null) {
4042 return smartUrlFilter(inUri.toString());
4043 }
4044 return null;
4045 }
4046
Feng Qianb34f87a2009-03-24 21:27:26 -07004047 protected static final Pattern ACCEPTED_URI_SCHEMA = Pattern.compile(
The Android Open Source Project0c908882009-03-03 19:32:16 -08004048 "(?i)" + // switch on case insensitive matching
4049 "(" + // begin group for schema
4050 "(?:http|https|file):\\/\\/" +
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004051 "|(?:inline|data|about|content|javascript):" +
The Android Open Source Project0c908882009-03-03 19:32:16 -08004052 ")" +
4053 "(.*)" );
4054
4055 /**
4056 * Attempts to determine whether user input is a URL or search
4057 * terms. Anything with a space is passed to search.
4058 *
4059 * Converts to lowercase any mistakenly uppercased schema (i.e.,
4060 * "Http://" converts to "http://"
4061 *
4062 * @return Original or modified URL
4063 *
4064 */
4065 String smartUrlFilter(String url) {
4066
4067 String inUrl = url.trim();
4068 boolean hasSpace = inUrl.indexOf(' ') != -1;
4069
4070 Matcher matcher = ACCEPTED_URI_SCHEMA.matcher(inUrl);
4071 if (matcher.matches()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08004072 // force scheme to lowercase
4073 String scheme = matcher.group(1);
4074 String lcScheme = scheme.toLowerCase();
4075 if (!lcScheme.equals(scheme)) {
Mitsuru Oshima123ecfb2009-05-18 19:11:14 -07004076 inUrl = lcScheme + matcher.group(2);
4077 }
4078 if (hasSpace) {
4079 inUrl = inUrl.replace(" ", "%20");
The Android Open Source Project0c908882009-03-03 19:32:16 -08004080 }
4081 return inUrl;
4082 }
4083 if (hasSpace) {
Satish Sampath565505b2009-05-29 15:37:27 +01004084 // FIXME: Is this the correct place to add to searches?
4085 // what if someone else calls this function?
4086 int shortcut = parseUrlShortcut(inUrl);
4087 if (shortcut != SHORTCUT_INVALID) {
4088 Browser.addSearchUrl(mResolver, inUrl);
4089 String query = inUrl.substring(2);
4090 switch (shortcut) {
4091 case SHORTCUT_GOOGLE_SEARCH:
Grace Kloba47fdfdb2009-06-30 11:15:34 -07004092 return URLUtil.composeSearchUrl(query, QuickSearch_G, QUERY_PLACE_HOLDER);
Satish Sampath565505b2009-05-29 15:37:27 +01004093 case SHORTCUT_WIKIPEDIA_SEARCH:
4094 return URLUtil.composeSearchUrl(query, QuickSearch_W, QUERY_PLACE_HOLDER);
4095 case SHORTCUT_DICTIONARY_SEARCH:
4096 return URLUtil.composeSearchUrl(query, QuickSearch_D, QUERY_PLACE_HOLDER);
4097 case SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH:
The Android Open Source Project0c908882009-03-03 19:32:16 -08004098 // FIXME: we need location in this case
Satish Sampath565505b2009-05-29 15:37:27 +01004099 return URLUtil.composeSearchUrl(query, QuickSearch_L, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004100 }
4101 }
4102 } else {
Dan Egnor5ee906c2009-11-18 12:11:49 -08004103 if (Patterns.WEB_URL.matcher(inUrl).matches()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08004104 return URLUtil.guessUrl(inUrl);
4105 }
4106 }
4107
4108 Browser.addSearchUrl(mResolver, inUrl);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07004109 return URLUtil.composeSearchUrl(inUrl, QuickSearch_G, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004110 }
4111
Ben Murdochbff2d602009-07-01 20:19:05 +01004112 /* package */ void setShouldShowErrorConsole(boolean flag) {
4113 if (flag == mShouldShowErrorConsole) {
4114 // Nothing to do.
4115 return;
4116 }
4117
4118 mShouldShowErrorConsole = flag;
4119
Grace Kloba22ac16e2009-10-07 18:00:23 -07004120 ErrorConsoleView errorConsole = mTabControl.getCurrentTab()
4121 .getErrorConsole(true);
Ben Murdochbff2d602009-07-01 20:19:05 +01004122
4123 if (flag) {
4124 // Setting the show state of the console will cause it's the layout to be inflated.
4125 if (errorConsole.numberOfErrors() > 0) {
4126 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
4127 } else {
4128 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
4129 }
4130
4131 // Now we can add it to the main view.
4132 mErrorConsoleContainer.addView(errorConsole,
Romain Guy15b8ec62010-01-08 15:06:43 -08004133 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
Ben Murdochbff2d602009-07-01 20:19:05 +01004134 ViewGroup.LayoutParams.WRAP_CONTENT));
4135 } else {
4136 mErrorConsoleContainer.removeView(errorConsole);
4137 }
4138
4139 }
4140
Grace Kloba22ac16e2009-10-07 18:00:23 -07004141 boolean shouldShowErrorConsole() {
4142 return mShouldShowErrorConsole;
4143 }
4144
Andrei Popescu163ab742009-10-20 17:58:23 +01004145 private void setStatusBarVisibility(boolean visible) {
4146 int flag = visible ? 0 : WindowManager.LayoutParams.FLAG_FULLSCREEN;
4147 getWindow().setFlags(flag, WindowManager.LayoutParams.FLAG_FULLSCREEN);
4148 }
4149
Andrei Popescu56199cc2010-01-12 22:39:16 +00004150
4151 private void sendNetworkType(String type, String subtype) {
4152 WebView w = mTabControl.getCurrentWebView();
4153 if (w != null) {
4154 w.setNetworkType(type, subtype);
4155 }
4156 }
4157
Grace Klobaeb6eef42009-09-15 17:56:32 -07004158 final static int LOCK_ICON_UNSECURE = 0;
4159 final static int LOCK_ICON_SECURE = 1;
4160 final static int LOCK_ICON_MIXED = 2;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004161
The Android Open Source Project0c908882009-03-03 19:32:16 -08004162 private BrowserSettings mSettings;
4163 private TabControl mTabControl;
4164 private ContentResolver mResolver;
4165 private FrameLayout mContentView;
Andrei Popescuadc008d2009-06-26 14:11:30 +01004166 private View mCustomView;
4167 private FrameLayout mCustomViewContainer;
Andrei Popescuc9b55562009-07-07 10:51:15 +01004168 private WebChromeClient.CustomViewCallback mCustomViewCallback;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004169
4170 // FIXME, temp address onPrepareMenu performance problem. When we move everything out of
4171 // view, we should rewrite this.
4172 private int mCurrentMenuState = 0;
4173 private int mMenuState = R.id.MAIN_MENU;
Andrei Popescuadc008d2009-06-26 14:11:30 +01004174 private int mOldMenuState = EMPTY_MENU;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004175 private static final int EMPTY_MENU = -1;
4176 private Menu mMenu;
4177
The Android Open Source Project0c908882009-03-03 19:32:16 -08004178 // Used to prevent chording to result in firing two shortcuts immediately
4179 // one after another. Fixes bug 1211714.
4180 boolean mCanChord;
4181
4182 private boolean mInLoad;
4183 private boolean mIsNetworkUp;
Ben Murdochb7cc8b42009-09-28 10:59:09 +01004184 private boolean mDidStopLoad;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004185
Cary Clark1f10cbf2010-03-22 11:45:23 -04004186 /* package */ boolean mActivityInPause = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004187
4188 private boolean mMenuIsDown;
4189
The Android Open Source Project0c908882009-03-03 19:32:16 -08004190 private static boolean mInTrace;
4191
4192 // Performance probe
4193 private static final int[] SYSTEM_CPU_FORMAT = new int[] {
4194 Process.PROC_SPACE_TERM | Process.PROC_COMBINE,
4195 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 1: user time
4196 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 2: nice time
4197 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 3: sys time
4198 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 4: idle time
4199 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 5: iowait time
4200 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 6: irq time
4201 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG // 7: softirq time
4202 };
4203
4204 private long mStart;
4205 private long mProcessStart;
4206 private long mUserStart;
4207 private long mSystemStart;
4208 private long mIdleStart;
4209 private long mIrqStart;
4210
4211 private long mUiStart;
4212
4213 private Drawable mMixLockIcon;
4214 private Drawable mSecLockIcon;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004215
4216 /* hold a ref so we can auto-cancel if necessary */
4217 private AlertDialog mAlertDialog;
4218
The Android Open Source Project0c908882009-03-03 19:32:16 -08004219 // The up-to-date URL and title (these can be different from those stored
4220 // in WebView, since it takes some time for the information in WebView to
4221 // get updated)
4222 private String mUrl;
4223 private String mTitle;
4224
4225 // As PageInfo has different style for landscape / portrait, we have
4226 // to re-open it when configuration changed
4227 private AlertDialog mPageInfoDialog;
Grace Kloba22ac16e2009-10-07 18:00:23 -07004228 private Tab mPageInfoView;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004229 // If the Page-Info dialog is launched from the SSL-certificate-on-error
4230 // dialog, we should not just dismiss it, but should get back to the
4231 // SSL-certificate-on-error dialog. This flag is used to store this state
Leon Scrogginsc7b92f82010-01-11 18:17:31 -05004232 private boolean mPageInfoFromShowSSLCertificateOnError;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004233
4234 // as SSLCertificateOnError has different style for landscape / portrait,
4235 // we have to re-open it when configuration changed
4236 private AlertDialog mSSLCertificateOnErrorDialog;
4237 private WebView mSSLCertificateOnErrorView;
4238 private SslErrorHandler mSSLCertificateOnErrorHandler;
4239 private SslError mSSLCertificateOnErrorError;
4240
4241 // as SSLCertificate has different style for landscape / portrait, we
4242 // have to re-open it when configuration changed
4243 private AlertDialog mSSLCertificateDialog;
Grace Kloba22ac16e2009-10-07 18:00:23 -07004244 private Tab mSSLCertificateView;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004245
4246 // as HttpAuthentication has different style for landscape / portrait, we
4247 // have to re-open it when configuration changed
4248 private AlertDialog mHttpAuthenticationDialog;
4249 private HttpAuthHandler mHttpAuthHandler;
4250
4251 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_PARAMS =
4252 new FrameLayout.LayoutParams(
Romain Guy15b8ec62010-01-08 15:06:43 -08004253 ViewGroup.LayoutParams.MATCH_PARENT,
4254 ViewGroup.LayoutParams.MATCH_PARENT);
Andrei Popescuadc008d2009-06-26 14:11:30 +01004255 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_GRAVITY_CENTER =
4256 new FrameLayout.LayoutParams(
Romain Guy15b8ec62010-01-08 15:06:43 -08004257 ViewGroup.LayoutParams.MATCH_PARENT,
4258 ViewGroup.LayoutParams.MATCH_PARENT,
Andrei Popescuadc008d2009-06-26 14:11:30 +01004259 Gravity.CENTER);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07004260 // Google search
4261 final static String QuickSearch_G = "http://www.google.com/m?q=%s";
The Android Open Source Project0c908882009-03-03 19:32:16 -08004262 // Wikipedia search
4263 final static String QuickSearch_W = "http://en.wikipedia.org/w/index.php?search=%s&go=Go";
4264 // Dictionary search
4265 final static String QuickSearch_D = "http://dictionary.reference.com/search?q=%s";
4266 // Google Mobile Local search
4267 final static String QuickSearch_L = "http://www.google.com/m/search?site=local&q=%s&near=mountain+view";
4268
4269 final static String QUERY_PLACE_HOLDER = "%s";
4270
4271 // "source" parameter for Google search through search key
4272 final static String GOOGLE_SEARCH_SOURCE_SEARCHKEY = "browser-key";
4273 // "source" parameter for Google search through goto menu
4274 final static String GOOGLE_SEARCH_SOURCE_GOTO = "browser-goto";
4275 // "source" parameter for Google search through simplily type
4276 final static String GOOGLE_SEARCH_SOURCE_TYPE = "browser-type";
4277 // "source" parameter for Google search suggested by the browser
4278 final static String GOOGLE_SEARCH_SOURCE_SUGGEST = "browser-suggest";
4279 // "source" parameter for Google search from unknown source
4280 final static String GOOGLE_SEARCH_SOURCE_UNKNOWN = "unknown";
4281
4282 private final static String LOGTAG = "browser";
4283
The Android Open Source Project0c908882009-03-03 19:32:16 -08004284 private String mLastEnteredUrl;
4285
4286 private PowerManager.WakeLock mWakeLock;
4287 private final static int WAKELOCK_TIMEOUT = 5 * 60 * 1000; // 5 minutes
4288
4289 private Toast mStopToast;
4290
Leon Scroggins571b3762010-05-26 10:25:01 -04004291 private TitleBarBase mTitleBar;
Michael Kolba2b2ba82010-08-04 17:54:03 -07004292 private TabBar mTabBar;
Leon Scroggins81db3662009-06-04 17:45:11 -04004293
Ben Murdochbff2d602009-07-01 20:19:05 +01004294 private LinearLayout mErrorConsoleContainer = null;
4295 private boolean mShouldShowErrorConsole = false;
4296
The Android Open Source Project0c908882009-03-03 19:32:16 -08004297 // As the ids are dynamically created, we can't guarantee that they will
4298 // be in sequence, so this static array maps ids to a window number.
4299 final static private int[] WINDOW_SHORTCUT_ID_ARRAY =
4300 { R.id.window_one_menu_id, R.id.window_two_menu_id, R.id.window_three_menu_id,
4301 R.id.window_four_menu_id, R.id.window_five_menu_id, R.id.window_six_menu_id,
4302 R.id.window_seven_menu_id, R.id.window_eight_menu_id };
4303
4304 // monitor platform changes
4305 private IntentFilter mNetworkStateChangedFilter;
4306 private BroadcastReceiver mNetworkStateIntentReceiver;
4307
Bjorn Bringerta7611812010-03-24 11:12:02 +00004308 private SystemAllowGeolocationOrigins mSystemAllowGeolocationOrigins;
4309
The Android Open Source Project0c908882009-03-03 19:32:16 -08004310 // activity requestCode
Nicolas Roard78a98e42009-05-11 13:34:17 +01004311 final static int COMBO_PAGE = 1;
4312 final static int DOWNLOAD_PAGE = 2;
4313 final static int PREFERENCES_PAGE = 3;
Leon Scroggins8d5fa432009-10-02 15:55:59 -04004314 final static int FILE_SELECTED = 4;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004315
Andrei Popescu540035d2009-09-18 18:59:20 +01004316 // the default <video> poster
4317 private Bitmap mDefaultVideoPoster;
4318 // the video progress view
4319 private View mVideoProgressView;
4320
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004321 /**
4322 * A UrlData class to abstract how the content will be set to WebView.
4323 * This base class uses loadUrl to show the content.
4324 */
Leon Scroggins6eac63e2010-03-15 18:19:14 -04004325 /* package */ static class UrlData {
Grace Kloba068e48b2010-01-26 18:11:27 -08004326 final String mUrl;
4327 final Map<String, String> mHeaders;
Leon Scroggins58d56c62010-01-28 15:12:40 -05004328 final Intent mVoiceIntent;
Grace Kloba60e095c2009-06-16 11:50:55 -07004329
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004330 UrlData(String url) {
4331 this.mUrl = url;
Grace Kloba068e48b2010-01-26 18:11:27 -08004332 this.mHeaders = null;
Leon Scroggins58d56c62010-01-28 15:12:40 -05004333 this.mVoiceIntent = null;
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004334 }
Grace Kloba60e095c2009-06-16 11:50:55 -07004335
Leon Scroggins58d56c62010-01-28 15:12:40 -05004336 UrlData(String url, Map<String, String> headers, Intent intent) {
Grace Kloba068e48b2010-01-26 18:11:27 -08004337 this.mUrl = url;
4338 this.mHeaders = headers;
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -05004339 if (RecognizerResultsIntent.ACTION_VOICE_SEARCH_RESULTS
4340 .equals(intent.getAction())) {
Leon Scroggins58d56c62010-01-28 15:12:40 -05004341 this.mVoiceIntent = intent;
4342 } else {
4343 this.mVoiceIntent = null;
4344 }
Grace Kloba60e095c2009-06-16 11:50:55 -07004345 }
4346
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004347 boolean isEmpty() {
Leon Scroggins58d56c62010-01-28 15:12:40 -05004348 return mVoiceIntent == null && (mUrl == null || mUrl.length() == 0);
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004349 }
4350
Leon Scroggins92472e82010-02-17 16:32:28 -05004351 /**
4352 * Load this UrlData into the given Tab. Use loadUrlDataIn to update
4353 * the title bar as well.
4354 */
Leon Scroggins58d56c62010-01-28 15:12:40 -05004355 public void loadIn(Tab t) {
4356 if (mVoiceIntent != null) {
4357 t.activateVoiceSearchMode(mVoiceIntent);
4358 } else {
4359 t.getWebView().loadUrl(mUrl, mHeaders);
4360 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004361 }
4362 };
4363
Leon Scroggins1f005d32009-08-10 17:36:42 -04004364 /* package */ static final UrlData EMPTY_URL_DATA = new UrlData(null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004365}