blob: 1263f3fd566ba7170e67e41e9da3f3614a098685 [file] [log] [blame]
The Android Open Source Project0c908882009-03-03 19:32:16 -08001/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.browser;
18
Michael Kolb3f65c382010-08-20 15:31:16 -070019import com.android.browser.ScrollWebView.ScrollListener;
Bjorn Bringertd69f51d2010-09-13 14:06:41 +010020import com.android.browser.search.SearchEngine;
Michael Kolb3f65c382010-08-20 15:31:16 -070021import com.android.common.Search;
22import com.android.common.speech.LoggingEvents;
23
Michael Kolbed217742010-08-10 17:52:34 -070024import android.app.ActionBar;
The Android Open Source Project0c908882009-03-03 19:32:16 -080025import android.app.Activity;
The Android Open Source Project0c908882009-03-03 19:32:16 -080026import android.app.AlertDialog;
Michael Kolbc7485ae2010-09-03 10:10:58 -070027import android.app.Dialog;
Steve Howard5a862fc2010-09-28 12:52:06 -070028import android.app.DownloadManager;
The Android Open Source Project0c908882009-03-03 19:32:16 -080029import android.app.ProgressDialog;
30import android.app.SearchManager;
31import android.content.ActivityNotFoundException;
32import android.content.BroadcastReceiver;
Dianne Hackborn80f32622010-08-05 14:17:53 -070033import android.content.ClipboardManager;
The Android Open Source Project0c908882009-03-03 19:32:16 -080034import android.content.ComponentName;
Leon Scroggins58d56c62010-01-28 15:12:40 -050035import android.content.ContentProvider;
36import android.content.ContentProviderClient;
The Android Open Source Project0c908882009-03-03 19:32:16 -080037import android.content.ContentResolver;
Leon Scrogginsb6b7f9e2009-06-18 12:05:28 -040038import android.content.ContentUris;
The Android Open Source Project0c908882009-03-03 19:32:16 -080039import android.content.ContentValues;
40import android.content.Context;
41import android.content.DialogInterface;
42import android.content.Intent;
43import android.content.IntentFilter;
The Android Open Source Project0c908882009-03-03 19:32:16 -080044import android.content.pm.PackageManager;
45import android.content.pm.ResolveInfo;
The Android Open Source Project0c908882009-03-03 19:32:16 -080046import android.content.res.Configuration;
47import android.content.res.Resources;
48import android.database.Cursor;
The Android Open Source Project0c908882009-03-03 19:32:16 -080049import android.graphics.Bitmap;
Andrei Popescu540035d2009-09-18 18:59:20 +010050import android.graphics.BitmapFactory;
The Android Open Source Project0c908882009-03-03 19:32:16 -080051import android.graphics.Canvas;
The Android Open Source Project0c908882009-03-03 19:32:16 -080052import android.graphics.Picture;
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -040053import android.graphics.PixelFormat;
The Android Open Source Project0c908882009-03-03 19:32:16 -080054import android.graphics.drawable.Drawable;
The Android Open Source Project0c908882009-03-03 19:32:16 -080055import android.net.ConnectivityManager;
Andrei Popescu56199cc2010-01-12 22:39:16 +000056import android.net.NetworkInfo;
The Android Open Source Project0c908882009-03-03 19:32:16 -080057import android.net.Uri;
58import android.net.WebAddress;
The Android Open Source Project0c908882009-03-03 19:32:16 -080059import android.net.http.SslCertificate;
60import android.net.http.SslError;
61import android.os.AsyncTask;
62import android.os.Bundle;
63import android.os.Debug;
64import android.os.Environment;
65import android.os.Handler;
The Android Open Source Project0c908882009-03-03 19:32:16 -080066import android.os.Message;
67import android.os.PowerManager;
68import android.os.Process;
The Android Open Source Project0c908882009-03-03 19:32:16 -080069import android.os.SystemClock;
The Android Open Source Project0c908882009-03-03 19:32:16 -080070import android.provider.Browser;
Jeff Hamilton8ce956c2010-08-17 11:13:53 -050071import android.provider.BrowserContract;
Cary Clark5e335a32009-09-22 14:53:11 -040072import android.provider.ContactsContract;
Jeff Hamilton1a805652010-09-07 12:36:30 -070073import android.provider.BrowserContract.Images;
Michael Kolba2b2ba82010-08-04 17:54:03 -070074import android.provider.ContactsContract.Intents.Insert;
The Android Open Source Project0c908882009-03-03 19:32:16 -080075import android.provider.Downloads;
76import android.provider.MediaStore;
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -050077import android.speech.RecognizerResultsIntent;
The Android Open Source Project0c908882009-03-03 19:32:16 -080078import android.text.TextUtils;
79import android.text.format.DateFormat;
The Android Open Source Project0c908882009-03-03 19:32:16 -080080import android.util.Log;
Dianne Hackborn385effd2010-02-24 20:03:04 -080081import android.util.Patterns;
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -040082import android.view.ActionMode;
The Android Open Source Project0c908882009-03-03 19:32:16 -080083import android.view.ContextMenu;
Michael Kolba2b2ba82010-08-04 17:54:03 -070084import android.view.ContextMenu.ContextMenuInfo;
The Android Open Source Project0c908882009-03-03 19:32:16 -080085import android.view.Gravity;
86import android.view.KeyEvent;
87import android.view.LayoutInflater;
88import android.view.Menu;
89import android.view.MenuInflater;
90import android.view.MenuItem;
Michael Kolba2b2ba82010-08-04 17:54:03 -070091import android.view.MenuItem.OnMenuItemClickListener;
Michael Kolb3f65c382010-08-20 15:31:16 -070092import android.view.MotionEvent;
The Android Open Source Project0c908882009-03-03 19:32:16 -080093import android.view.View;
94import android.view.ViewGroup;
95import android.view.Window;
96import android.view.WindowManager;
Svetoslav Ganov2b345992010-05-06 06:13:54 -070097import android.view.accessibility.AccessibilityManager;
The Android Open Source Project0c908882009-03-03 19:32:16 -080098import android.webkit.CookieManager;
99import android.webkit.CookieSyncManager;
100import android.webkit.DownloadListener;
101import android.webkit.HttpAuthHandler;
102import android.webkit.SslErrorHandler;
103import android.webkit.URLUtil;
Leon Clarkecb6cc862009-09-29 18:35:13 +0100104import android.webkit.ValueCallback;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800105import android.webkit.WebChromeClient;
106import android.webkit.WebHistoryItem;
107import android.webkit.WebIconDatabase;
108import android.webkit.WebView;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800109import android.widget.EditText;
110import android.widget.FrameLayout;
111import android.widget.LinearLayout;
Michael Kolbc7485ae2010-09-03 10:10:58 -0700112import android.widget.PopupMenu;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800113import android.widget.TextView;
114import android.widget.Toast;
115
Leon Scrogginsb6b7f9e2009-06-18 12:05:28 -0400116import java.io.ByteArrayOutputStream;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800117import java.io.File;
Ben Murdoch4f75ba22009-10-27 11:48:28 +0000118import java.io.IOException;
119import java.io.InputStream;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800120import java.net.MalformedURLException;
Dianne Hackborn99189432009-06-17 18:06:18 -0700121import java.net.URISyntaxException;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800122import java.net.URL;
123import java.net.URLEncoder;
Elliott Slaughter3d6df162010-08-25 13:17:44 -0700124import java.util.Calendar;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800125import java.util.Date;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800126import java.util.HashMap;
Grace Kloba00f54c52010-01-27 14:53:51 -0800127import java.util.Iterator;
Grace Kloba068e48b2010-01-26 18:11:27 -0800128import java.util.Map;
Michael Kolbfe251992010-07-08 15:41:55 -0700129import java.util.Vector;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800130import java.util.regex.Matcher;
131import java.util.regex.Pattern;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800132
133public class BrowserActivity extends Activity
Michael Kolbc7485ae2010-09-03 10:10:58 -0700134 implements View.OnCreateContextMenuListener, DownloadListener,
135 PopupMenu.OnMenuItemClickListener {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800136
Dave Bort31a6d1c2009-04-13 15:56:49 -0700137 /* Define some aliases to make these debugging flags easier to refer to.
138 * This file imports android.provider.Browser, so we can't just refer to "Browser.DEBUG".
139 */
140 private final static boolean DEBUG = com.android.browser.Browser.DEBUG;
141 private final static boolean LOGV_ENABLED = com.android.browser.Browser.LOGV_ENABLED;
142 private final static boolean LOGD_ENABLED = com.android.browser.Browser.LOGD_ENABLED;
143
Satish Sampath565505b2009-05-29 15:37:27 +0100144 // These are single-character shortcuts for searching popular sources.
145 private static final int SHORTCUT_INVALID = 0;
146 private static final int SHORTCUT_GOOGLE_SEARCH = 1;
147 private static final int SHORTCUT_WIKIPEDIA_SEARCH = 2;
148 private static final int SHORTCUT_DICTIONARY_SEARCH = 3;
149 private static final int SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH = 4;
150
Cary Clarka9771242009-08-11 16:42:26 -0400151 private static class ClearThumbnails extends AsyncTask<File, Void, Void> {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800152 @Override
153 public Void doInBackground(File... files) {
154 if (files != null) {
155 for (File f : files) {
Cary Clarkd6be1752009-08-12 12:56:42 -0400156 if (!f.delete()) {
157 Log.e(LOGTAG, f.getPath() + " was not deleted");
158 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800159 }
160 }
161 return null;
162 }
163 }
164
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400165 /**
166 * This layout holds everything you see below the status bar, including the
167 * error console, the custom view container, and the webviews.
168 */
169 private FrameLayout mBrowserFrameLayout;
Leon Scroggins81db3662009-06-04 17:45:11 -0400170
Leon Scrogginsd746a942010-05-19 13:21:44 -0400171 private boolean mXLargeScreenSize;
172
Jeff Davidson43610292010-07-16 16:03:58 -0700173 private Boolean mIsProviderPresent = null;
174 private Uri mRlzUri = null;
175
Grace Kloba22ac16e2009-10-07 18:00:23 -0700176 @Override
177 public void onCreate(Bundle icicle) {
Dave Bort31a6d1c2009-04-13 15:56:49 -0700178 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800179 Log.v(LOGTAG, this + " onStart");
180 }
181 super.onCreate(icicle);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800182 // test the browser in OpenGL
183 // requestWindowFeature(Window.FEATURE_OPENGL);
184
Mike Reedd334bf52010-01-26 15:21:44 -0500185 // enable this to test the browser in 32bit
186 if (false) {
187 getWindow().setFormat(PixelFormat.RGBX_8888);
188 BitmapFactory.setDefaultConfig(Bitmap.Config.ARGB_8888);
189 }
190
Svetoslav Ganov2b345992010-05-06 06:13:54 -0700191 if (AccessibilityManager.getInstance(this).isEnabled()) {
192 setDefaultKeyMode(DEFAULT_KEYS_DISABLE);
193 } else {
194 setDefaultKeyMode(DEFAULT_KEYS_SEARCH_LOCAL);
195 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800196
197 mResolver = getContentResolver();
198
Leon Scroggins IIIcc14c8c2010-09-27 12:45:34 -0400199 // Keep a settings instance handy.
200 mSettings = BrowserSettings.getInstance();
201
Grace Kloba0923d692009-09-23 21:37:25 -0700202 // If this was a web search request, pass it on to the default web
203 // search provider and finish this activity.
204 if (handleWebSearchIntent(getIntent())) {
205 finish();
206 return;
207 }
208
The Android Open Source Project0c908882009-03-03 19:32:16 -0800209 mSecLockIcon = Resources.getSystem().getDrawable(
210 android.R.drawable.ic_secure);
211 mMixLockIcon = Resources.getSystem().getDrawable(
212 android.R.drawable.ic_partial_secure);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800213
Michael Kolbed217742010-08-10 17:52:34 -0700214 // Create the tab control and our initial tab
215 mTabControl = new TabControl(this);
216
217 mXLargeScreenSize = (getResources().getConfiguration().screenLayout
218 & Configuration.SCREENLAYOUT_SIZE_MASK)
219 == Configuration.SCREENLAYOUT_SIZE_XLARGE;
220
Leon Scroggins81db3662009-06-04 17:45:11 -0400221 FrameLayout frameLayout = (FrameLayout) getWindow().getDecorView()
222 .findViewById(com.android.internal.R.id.content);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400223 mBrowserFrameLayout = (FrameLayout) LayoutInflater.from(this)
224 .inflate(R.layout.custom_screen, null);
225 mContentView = (FrameLayout) mBrowserFrameLayout.findViewById(
226 R.id.main_content);
227 mErrorConsoleContainer = (LinearLayout) mBrowserFrameLayout
228 .findViewById(R.id.error_console);
229 mCustomViewContainer = (FrameLayout) mBrowserFrameLayout
230 .findViewById(R.id.fullscreen_custom_content);
231 frameLayout.addView(mBrowserFrameLayout, COVER_SCREEN_PARAMS);
Michael Kolbe0a36662010-06-29 10:37:12 -0700232
Leon Scrogginsd746a942010-05-19 13:21:44 -0400233 if (mXLargeScreenSize) {
Michael Kolba2b2ba82010-08-04 17:54:03 -0700234 mTitleBar = new TitleBarXLarge(this);
235 mTitleBar.setProgress(100);
236 mFakeTitleBar = new TitleBarXLarge(this);
Michael Kolbed217742010-08-10 17:52:34 -0700237 ActionBar actionBar = getActionBar();
Michael Kolba2b2ba82010-08-04 17:54:03 -0700238 mTabBar = new TabBar(this, mTabControl, (TitleBarXLarge) mFakeTitleBar);
Michael Kolbed217742010-08-10 17:52:34 -0700239 actionBar.setCustomNavigationMode(mTabBar);
Michael Kolb68775752010-08-19 12:42:01 -0700240 // disable built in zoom controls
241 mTabControl.setDisplayZoomControls(false);
Leon Scrogginsd746a942010-05-19 13:21:44 -0400242 } else {
Leon Scroggins571b3762010-05-26 10:25:01 -0400243 mTitleBar = new TitleBar(this);
Leon Scrogginsd746a942010-05-19 13:21:44 -0400244 // mTitleBar will be always be shown in the fully loaded mode on
245 // phone
246 mTitleBar.setProgress(100);
Leon Scrogginsd746a942010-05-19 13:21:44 -0400247 mFakeTitleBar = new TitleBar(this);
248 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800249
The Android Open Source Project0c908882009-03-03 19:32:16 -0800250 // Open the icon database and retain all the bookmark urls for favicons
251 retainIconsOnStartup();
252
The Android Open Source Project0c908882009-03-03 19:32:16 -0800253 mSettings.setTabControl(mTabControl);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800254
255 PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
256 mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Browser");
257
Patrick Scott6adacc92010-03-05 08:24:51 -0500258 // Find out if the network is currently up.
259 ConnectivityManager cm = (ConnectivityManager) getSystemService(
260 Context.CONNECTIVITY_SERVICE);
261 NetworkInfo info = cm.getActiveNetworkInfo();
262 if (info != null) {
263 mIsNetworkUp = info.isAvailable();
264 }
265
Grace Klobaa34f6862009-07-31 16:28:17 -0700266 /* enables registration for changes in network status from
267 http stack */
268 mNetworkStateChangedFilter = new IntentFilter();
269 mNetworkStateChangedFilter.addAction(
270 ConnectivityManager.CONNECTIVITY_ACTION);
271 mNetworkStateIntentReceiver = new BroadcastReceiver() {
272 @Override
273 public void onReceive(Context context, Intent intent) {
274 if (intent.getAction().equals(
275 ConnectivityManager.CONNECTIVITY_ACTION)) {
Andrei Popescue4c98462010-02-19 15:44:13 +0000276
277 NetworkInfo info = intent.getParcelableExtra(
278 ConnectivityManager.EXTRA_NETWORK_INFO);
279 String typeName = info.getTypeName();
280 String subtypeName = info.getSubtypeName();
281 sendNetworkType(typeName.toLowerCase(),
282 (subtypeName != null ? subtypeName.toLowerCase() : ""));
283
284 onNetworkToggle(info.isAvailable());
Grace Klobaa34f6862009-07-31 16:28:17 -0700285 }
286 }
287 };
288
Elliott Slaughter3d6df162010-08-25 13:17:44 -0700289 // Unless the last browser usage was within 24 hours, destroy any
290 // remaining incognito tabs.
291
292 Calendar lastActiveDate = icicle != null ? (Calendar) icicle.getSerializable("lastActiveDate") : null;
293 Calendar today = Calendar.getInstance();
294 Calendar yesterday = Calendar.getInstance();
295 yesterday.add(Calendar.DATE, -1);
296
297 boolean dontRestoreIncognitoTabs = lastActiveDate == null
298 || lastActiveDate.before(yesterday)
299 || lastActiveDate.after(today);
300
301 if (!mTabControl.restoreState(icicle, dontRestoreIncognitoTabs)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800302 // clear up the thumbnail directory if we can't restore the state as
303 // none of the files in the directory are referenced any more.
304 new ClearThumbnails().execute(
305 mTabControl.getThumbnailDir().listFiles());
Grace Klobaaab3f092009-07-30 12:29:51 -0700306 // there is no quit on Android. But if we can't restore the state,
307 // we can treat it as a new Browser, remove the old session cookies.
308 CookieManager.getInstance().removeSessionCookie();
Elliott Slaughter3d6df162010-08-25 13:17:44 -0700309 // remove any incognito files
310 WebView.cleanupPrivateBrowsingFiles(this);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800311 final Intent intent = getIntent();
312 final Bundle extra = intent.getExtras();
313 // Create an initial tab.
314 // If the intent is ACTION_VIEW and data is not null, the Browser is
315 // invoked to view the content by another application. In this case,
316 // the tab will be close when exit.
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700317 UrlData urlData = getUrlDataFromIntent(intent);
318
Leon Scroggins58d56c62010-01-28 15:12:40 -0500319 String action = intent.getAction();
Grace Kloba22ac16e2009-10-07 18:00:23 -0700320 final Tab t = mTabControl.createNewTab(
Leon Scroggins58d56c62010-01-28 15:12:40 -0500321 (Intent.ACTION_VIEW.equals(action) &&
322 intent.getData() != null)
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -0500323 || RecognizerResultsIntent.ACTION_VOICE_SEARCH_RESULTS
324 .equals(action),
Elliott Slaughterf0f03952010-07-14 18:10:36 -0700325 intent.getStringExtra(Browser.EXTRA_APPLICATION_ID),
326 urlData.mUrl, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800327 mTabControl.setCurrentTab(t);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800328 attachTabToContentView(t);
329 WebView webView = t.getWebView();
330 if (extra != null) {
331 int scale = extra.getInt(Browser.INITIAL_ZOOM_LEVEL, 0);
332 if (scale > 0 && scale <= 1000) {
333 webView.setInitialScale(scale);
334 }
335 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800336
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700337 if (urlData.isEmpty()) {
Shimeng (Simon) Wang98d5fce2010-03-16 13:23:39 -0700338 loadUrl(webView, mSettings.getHomePage());
The Android Open Source Project0c908882009-03-03 19:32:16 -0800339 } else {
Patrick Scott9d53da02010-02-19 10:19:01 -0500340 loadUrlDataIn(t, urlData);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800341 }
342 } else {
Elliott Slaughter3d6df162010-08-25 13:17:44 -0700343 if (dontRestoreIncognitoTabs) {
344 WebView.cleanupPrivateBrowsingFiles(this);
345 }
346
The Android Open Source Project0c908882009-03-03 19:32:16 -0800347 // TabControl.restoreState() will create a new tab even if
Leon Scroggins1f005d32009-08-10 17:36:42 -0400348 // restoring the state fails.
The Android Open Source Project0c908882009-03-03 19:32:16 -0800349 attachTabToContentView(mTabControl.getCurrentTab());
350 }
Grace Kloba615c6c92009-08-03 10:22:44 -0700351
Cary Clarkb4b83182010-07-01 12:36:56 -0400352 // Delete old thumbnails to save space
353 File dir = mTabControl.getThumbnailDir();
354 if (dir.exists()) {
355 for (String child : dir.list()) {
356 File f = new File(dir, child);
357 f.delete();
358 }
359 }
360
Feng Qianb3c02da2009-06-29 15:58:08 -0700361 // Read JavaScript flags if it exists.
362 String jsFlags = mSettings.getJsFlags();
363 if (jsFlags.trim().length() != 0) {
364 mTabControl.getCurrentWebView().setJsFlags(jsFlags);
365 }
Bjorn Bringerta7611812010-03-24 11:12:02 +0000366
367 // Start watching the default geolocation permissions
368 mSystemAllowGeolocationOrigins
369 = new SystemAllowGeolocationOrigins(getApplicationContext());
370 mSystemAllowGeolocationOrigins.start();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800371 }
372
Michael Kolba2b2ba82010-08-04 17:54:03 -0700373 ScrollListener getScrollListener() {
374 return mTabBar;
375 }
376
Leon Scroggins58d56c62010-01-28 15:12:40 -0500377 /**
378 * Feed the previously stored results strings to the BrowserProvider so that
379 * the SearchDialog will show them instead of the standard searches.
380 * @param result String to show on the editable line of the SearchDialog.
381 */
382 /* package */ void showVoiceSearchResults(String result) {
383 ContentProviderClient client = mResolver.acquireContentProviderClient(
384 Browser.BOOKMARKS_URI);
385 ContentProvider prov = client.getLocalContentProvider();
386 BrowserProvider bp = (BrowserProvider) prov;
387 bp.setQueryResults(mTabControl.getCurrentTab().getVoiceSearchResults());
388 client.release();
389
Leon Scrogginsfbb3f152010-03-09 17:26:56 -0500390 Bundle bundle = createGoogleSearchSourceBundle(
391 GOOGLE_SEARCH_SOURCE_SEARCHKEY);
392 bundle.putBoolean(SearchManager.CONTEXT_IS_VOICE, true);
393 startSearch(result, false, bundle, false);
Leon Scroggins58d56c62010-01-28 15:12:40 -0500394 }
395
The Android Open Source Project0c908882009-03-03 19:32:16 -0800396 @Override
397 protected void onNewIntent(Intent intent) {
Grace Kloba22ac16e2009-10-07 18:00:23 -0700398 Tab current = mTabControl.getCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800399 // When a tab is closed on exit, the current tab index is set to -1.
400 // Reset before proceed as Browser requires the current tab to be set.
401 if (current == null) {
402 // Try to reset the tab in case the index was incorrect.
403 current = mTabControl.getTab(0);
404 if (current == null) {
405 // No tabs at all so just ignore this intent.
406 return;
407 }
408 mTabControl.setCurrentTab(current);
409 attachTabToContentView(current);
410 resetTitleAndIcon(current.getWebView());
411 }
412 final String action = intent.getAction();
413 final int flags = intent.getFlags();
414 if (Intent.ACTION_MAIN.equals(action) ||
415 (flags & Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY) != 0) {
416 // just resume the browser
417 return;
418 }
Leon Scrogginsb8a844d2010-03-18 15:06:15 -0400419 // In case the SearchDialog is open.
420 ((SearchManager) getSystemService(Context.SEARCH_SERVICE))
421 .stopSearch();
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -0500422 boolean activateVoiceSearch = RecognizerResultsIntent
423 .ACTION_VOICE_SEARCH_RESULTS.equals(action);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800424 if (Intent.ACTION_VIEW.equals(action)
425 || Intent.ACTION_SEARCH.equals(action)
426 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
Leon Scroggins58d56c62010-01-28 15:12:40 -0500427 || Intent.ACTION_WEB_SEARCH.equals(action)
428 || activateVoiceSearch) {
Leon Scroggins3b18ce32010-02-08 17:35:59 -0500429 if (current.isInVoiceSearchMode()) {
430 String title = current.getVoiceDisplayTitle();
431 if (title != null && title.equals(intent.getStringExtra(
432 SearchManager.QUERY))) {
433 // The user submitted the same search as the last voice
434 // search, so do nothing.
435 return;
436 }
Leon Scroggins1fe13a52010-02-09 15:31:26 -0500437 if (Intent.ACTION_SEARCH.equals(action)
438 && current.voiceSearchSourceIsGoogle()) {
439 Intent logIntent = new Intent(
440 LoggingEvents.ACTION_LOG_EVENT);
441 logIntent.putExtra(LoggingEvents.EXTRA_EVENT,
442 LoggingEvents.VoiceSearch.QUERY_UPDATED);
443 logIntent.putExtra(
444 LoggingEvents.VoiceSearch.EXTRA_QUERY_UPDATED_VALUE,
445 intent.getDataString());
446 sendBroadcast(logIntent);
447 // Note, onPageStarted will revert the voice title bar
448 // When http://b/issue?id=2379215 is fixed, we should update
449 // the title bar here.
450 }
Leon Scroggins3b18ce32010-02-08 17:35:59 -0500451 }
Satish Sampath565505b2009-05-29 15:37:27 +0100452 // If this was a search request (e.g. search query directly typed into the address bar),
453 // pass it on to the default web search provider.
454 if (handleWebSearchIntent(intent)) {
455 return;
456 }
457
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700458 UrlData urlData = getUrlDataFromIntent(intent);
459 if (urlData.isEmpty()) {
460 urlData = new UrlData(mSettings.getHomePage());
The Android Open Source Project0c908882009-03-03 19:32:16 -0800461 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700462
Grace Klobacc634032009-07-28 15:58:19 -0700463 final String appId = intent
464 .getStringExtra(Browser.EXTRA_APPLICATION_ID);
Leon Scroggins47208682010-04-07 17:59:48 -0400465 if ((Intent.ACTION_VIEW.equals(action)
466 // If a voice search has no appId, it means that it came
467 // from the browser. In that case, reuse the current tab.
468 || (activateVoiceSearch && appId != null))
Grace Klobacc634032009-07-28 15:58:19 -0700469 && !getPackageName().equals(appId)
470 && (flags & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0) {
Grace Kloba22ac16e2009-10-07 18:00:23 -0700471 Tab appTab = mTabControl.getTabFromId(appId);
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700472 if (appTab != null) {
473 Log.i(LOGTAG, "Reusing tab for " + appId);
474 // Dismiss the subwindow if applicable.
475 dismissSubWindow(appTab);
476 // Since we might kill the WebView, remove it from the
477 // content view first.
478 removeTabFromContentView(appTab);
479 // Recreate the main WebView after destroying the old one.
480 // If the WebView has the same original url and is on that
481 // page, it can be reused.
482 boolean needsLoad =
Leon Scroggins6eac63e2010-03-15 18:19:14 -0400483 mTabControl.recreateWebView(appTab, urlData);
Ben Murdochbff2d602009-07-01 20:19:05 +0100484
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700485 if (current != appTab) {
Leon Scroggins1f005d32009-08-10 17:36:42 -0400486 switchToTab(mTabControl.getTabIndex(appTab));
487 if (needsLoad) {
Patrick Scott9d53da02010-02-19 10:19:01 -0500488 loadUrlDataIn(appTab, urlData);
Leon Scroggins1f005d32009-08-10 17:36:42 -0400489 }
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700490 } else {
Leon Scroggins1f005d32009-08-10 17:36:42 -0400491 // If the tab was the current tab, we have to attach
492 // it to the view system again.
493 attachTabToContentView(appTab);
494 if (needsLoad) {
Patrick Scott9d53da02010-02-19 10:19:01 -0500495 loadUrlDataIn(appTab, urlData);
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700496 }
497 }
498 return;
Patrick Scottcd115892009-07-16 09:42:58 -0400499 } else {
500 // No matching application tab, try to find a regular tab
501 // with a matching url.
502 appTab = mTabControl.findUnusedTabWithUrl(urlData.mUrl);
Leon Scroggins25515f82009-08-19 15:31:58 -0400503 if (appTab != null) {
504 if (current != appTab) {
505 switchToTab(mTabControl.getTabIndex(appTab));
506 }
507 // Otherwise, we are already viewing the correct tab.
Patrick Scottcd115892009-07-16 09:42:58 -0400508 } else {
509 // if FLAG_ACTIVITY_BROUGHT_TO_FRONT flag is on, the url
510 // will be opened in a new tab unless we have reached
511 // MAX_TABS. Then the url will be opened in the current
512 // tab. If a new tab is created, it will have "true" for
513 // exit on close.
Leon Scroggins1f005d32009-08-10 17:36:42 -0400514 openTabAndShow(urlData, true, appId);
Patrick Scottcd115892009-07-16 09:42:58 -0400515 }
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700516 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800517 } else {
Grace Kloba638d3f42009-11-23 10:35:04 -0800518 if (!urlData.isEmpty()
519 && urlData.mUrl.startsWith("about:debug")) {
520 if ("about:debug.dom".equals(urlData.mUrl)) {
521 current.getWebView().dumpDomTree(false);
522 } else if ("about:debug.dom.file".equals(urlData.mUrl)) {
523 current.getWebView().dumpDomTree(true);
524 } else if ("about:debug.render".equals(urlData.mUrl)) {
525 current.getWebView().dumpRenderTree(false);
526 } else if ("about:debug.render.file".equals(urlData.mUrl)) {
527 current.getWebView().dumpRenderTree(true);
528 } else if ("about:debug.display".equals(urlData.mUrl)) {
529 current.getWebView().dumpDisplayTree();
Mike Reed9b78e1d2010-01-13 14:40:52 -0800530 } else if (urlData.mUrl.startsWith("about:debug.drag")) {
531 int index = urlData.mUrl.codePointAt(16) - '0';
532 if (index <= 0 || index > 9) {
533 current.getWebView().setDragTracker(null);
534 } else {
535 current.getWebView().setDragTracker(new MeshTracker(index));
536 }
Grace Kloba638d3f42009-11-23 10:35:04 -0800537 } else {
538 mSettings.toggleDebugSettings();
539 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800540 return;
541 }
Leon Scroggins1f005d32009-08-10 17:36:42 -0400542 // Get rid of the subwindow if it exists
543 dismissSubWindow(current);
Leon Scroggins8588d152010-04-15 11:01:53 -0400544 // If the current Tab is being used as an application tab,
545 // remove the association, since the new Intent means that it is
546 // no longer associated with that application.
547 current.setAppId(null);
Patrick Scott9d53da02010-02-19 10:19:01 -0500548 loadUrlDataIn(current, urlData);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800549 }
550 }
551 }
552
Satish Sampath565505b2009-05-29 15:37:27 +0100553 private int parseUrlShortcut(String url) {
554 if (url == null) return SHORTCUT_INVALID;
555
556 // FIXME: quick search, need to be customized by setting
557 if (url.length() > 2 && url.charAt(1) == ' ') {
558 switch (url.charAt(0)) {
559 case 'g': return SHORTCUT_GOOGLE_SEARCH;
560 case 'w': return SHORTCUT_WIKIPEDIA_SEARCH;
561 case 'd': return SHORTCUT_DICTIONARY_SEARCH;
562 case 'l': return SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH;
563 }
564 }
565 return SHORTCUT_INVALID;
566 }
567
568 /**
569 * Launches the default web search activity with the query parameters if the given intent's data
570 * are identified as plain search terms and not URLs/shortcuts.
571 * @return true if the intent was handled and web search activity was launched, false if not.
572 */
573 private boolean handleWebSearchIntent(Intent intent) {
574 if (intent == null) return false;
575
576 String url = null;
577 final String action = intent.getAction();
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -0500578 if (RecognizerResultsIntent.ACTION_VOICE_SEARCH_RESULTS.equals(
579 action)) {
Leon Scroggins58d56c62010-01-28 15:12:40 -0500580 return false;
581 }
Satish Sampath565505b2009-05-29 15:37:27 +0100582 if (Intent.ACTION_VIEW.equals(action)) {
Grace Kloba1e705052009-09-29 13:13:36 -0700583 Uri data = intent.getData();
584 if (data != null) url = data.toString();
Satish Sampath565505b2009-05-29 15:37:27 +0100585 } else if (Intent.ACTION_SEARCH.equals(action)
586 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
587 || Intent.ACTION_WEB_SEARCH.equals(action)) {
588 url = intent.getStringExtra(SearchManager.QUERY);
589 }
Bjorn Bringert04851702009-09-22 10:36:01 +0100590 return handleWebSearchRequest(url, intent.getBundleExtra(SearchManager.APP_DATA),
591 intent.getStringExtra(SearchManager.EXTRA_DATA_KEY));
Satish Sampath565505b2009-05-29 15:37:27 +0100592 }
593
594 /**
595 * Launches the default web search activity with the query parameters if the given url string
596 * was identified as plain search terms and not URL/shortcut.
597 * @return true if the request was handled and web search activity was launched, false if not.
598 */
Bjorn Bringert04851702009-09-22 10:36:01 +0100599 private boolean handleWebSearchRequest(String inUrl, Bundle appData, String extraData) {
Satish Sampath565505b2009-05-29 15:37:27 +0100600 if (inUrl == null) return false;
601
602 // In general, we shouldn't modify URL from Intent.
603 // But currently, we get the user-typed URL from search box as well.
604 String url = fixUrl(inUrl).trim();
605
606 // URLs and site specific search shortcuts are handled by the regular flow of control, so
607 // return early.
Dan Egnor5ee906c2009-11-18 12:11:49 -0800608 if (Patterns.WEB_URL.matcher(url).matches()
Satish Sampathbc5b9f32009-06-04 18:21:40 +0100609 || ACCEPTED_URI_SCHEMA.matcher(url).matches()
Satish Sampath565505b2009-05-29 15:37:27 +0100610 || parseUrlShortcut(url) != SHORTCUT_INVALID) {
611 return false;
612 }
613
Leon Scroggins8d06e362010-03-24 14:45:57 -0400614 final ContentResolver cr = mResolver;
615 final String newUrl = url;
Elliott Slaughter627d96f2010-08-18 16:35:30 -0700616 if (mTabControl == null || !mTabControl.getCurrentWebView().isPrivateBrowsingEnabled()) {
Elliott Slaughterf0f03952010-07-14 18:10:36 -0700617 new AsyncTask<Void, Void, Void>() {
618 @Override
619 protected Void doInBackground(Void... unused) {
620 Browser.updateVisitedHistory(cr, newUrl, false);
621 Browser.addSearchUrl(cr, newUrl);
622 return null;
623 }
624 }.execute();
625 }
Satish Sampath565505b2009-05-29 15:37:27 +0100626
Bjorn Bringertd69f51d2010-09-13 14:06:41 +0100627 SearchEngine searchEngine = mSettings.getSearchEngine();
628 if (searchEngine == null) return false;
629 searchEngine.startSearch(this, url, appData, extraData);
Satish Sampath565505b2009-05-29 15:37:27 +0100630
631 return true;
632 }
633
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700634 private UrlData getUrlDataFromIntent(Intent intent) {
Leon Scroggins58d56c62010-01-28 15:12:40 -0500635 String url = "";
Grace Kloba068e48b2010-01-26 18:11:27 -0800636 Map<String, String> headers = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800637 if (intent != null) {
638 final String action = intent.getAction();
639 if (Intent.ACTION_VIEW.equals(action)) {
640 url = smartUrlFilter(intent.getData());
641 if (url != null && url.startsWith("content:")) {
642 /* Append mimetype so webview knows how to display */
643 String mimeType = intent.resolveType(getContentResolver());
644 if (mimeType != null) {
645 url += "?" + mimeType;
646 }
647 }
Grace Kloba068e48b2010-01-26 18:11:27 -0800648 if (url != null && url.startsWith("http")) {
Grace Kloba00f54c52010-01-27 14:53:51 -0800649 final Bundle pairs = intent
650 .getBundleExtra(Browser.EXTRA_HEADERS);
Grace Kloba2d508ed2010-01-28 11:39:15 -0800651 if (pairs != null && !pairs.isEmpty()) {
Grace Kloba00f54c52010-01-27 14:53:51 -0800652 Iterator<String> iter = pairs.keySet().iterator();
Grace Kloba068e48b2010-01-26 18:11:27 -0800653 headers = new HashMap<String, String>();
Grace Kloba00f54c52010-01-27 14:53:51 -0800654 while (iter.hasNext()) {
655 String key = iter.next();
656 headers.put(key, pairs.getString(key));
Grace Kloba068e48b2010-01-26 18:11:27 -0800657 }
658 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700659 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800660 } else if (Intent.ACTION_SEARCH.equals(action)
661 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
662 || Intent.ACTION_WEB_SEARCH.equals(action)) {
663 url = intent.getStringExtra(SearchManager.QUERY);
664 if (url != null) {
665 mLastEnteredUrl = url;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800666 // In general, we shouldn't modify URL from Intent.
667 // But currently, we get the user-typed URL from search box as well.
668 url = fixUrl(url);
669 url = smartUrlFilter(url);
Leon Scroggins8d06e362010-03-24 14:45:57 -0400670 final ContentResolver cr = mResolver;
671 final String newUrl = url;
Elliott Slaughter8389e992010-08-20 15:44:08 -0700672 if (mTabControl == null
673 || mTabControl.getCurrentWebView() == null
674 || !mTabControl.getCurrentWebView().isPrivateBrowsingEnabled()) {
675 new AsyncTask<Void, Void, Void>() {
676 @Override
677 protected Void doInBackground(Void... unused) {
678 Browser.updateVisitedHistory(cr, newUrl, false);
679 return null;
680 }
681 }.execute();
682 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800683 String searchSource = "&source=android-" + GOOGLE_SEARCH_SOURCE_SUGGEST + "&";
684 if (url.contains(searchSource)) {
685 String source = null;
686 final Bundle appData = intent.getBundleExtra(SearchManager.APP_DATA);
687 if (appData != null) {
Bjorn Bringert10d1cca2010-02-10 14:22:12 +0000688 source = appData.getString(Search.SOURCE);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800689 }
690 if (TextUtils.isEmpty(source)) {
691 source = GOOGLE_SEARCH_SOURCE_UNKNOWN;
692 }
693 url = url.replace(searchSource, "&source=android-"+source+"&");
694 }
695 }
696 }
697 }
Leon Scroggins58d56c62010-01-28 15:12:40 -0500698 return new UrlData(url, headers, intent);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800699 }
Leon Scroggins58d56c62010-01-28 15:12:40 -0500700 /* package */ void showVoiceTitleBar(String title) {
701 mTitleBar.setInVoiceMode(true);
Leon Scroggins58d56c62010-01-28 15:12:40 -0500702 mTitleBar.setDisplayTitle(title);
Michael Kolba2b2ba82010-08-04 17:54:03 -0700703 mFakeTitleBar.setInVoiceMode(true);
704 mFakeTitleBar.setDisplayTitle(title);
Leon Scroggins58d56c62010-01-28 15:12:40 -0500705 }
706 /* package */ void revertVoiceTitleBar() {
707 mTitleBar.setInVoiceMode(false);
Leon Scroggins003a5dd2010-03-10 12:13:14 -0500708 mTitleBar.setDisplayTitle(mUrl);
Michael Kolba2b2ba82010-08-04 17:54:03 -0700709 mFakeTitleBar.setInVoiceMode(false);
710 mFakeTitleBar.setDisplayTitle(mUrl);
Leon Scroggins58d56c62010-01-28 15:12:40 -0500711 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800712 /* package */ static String fixUrl(String inUrl) {
Cary Clark652ff872009-09-10 13:34:44 -0400713 // FIXME: Converting the url to lower case
714 // duplicates functionality in smartUrlFilter().
715 // However, changing all current callers of fixUrl to
716 // call smartUrlFilter in addition may have unwanted
717 // consequences, and is deferred for now.
718 int colon = inUrl.indexOf(':');
719 boolean allLower = true;
720 for (int index = 0; index < colon; index++) {
721 char ch = inUrl.charAt(index);
722 if (!Character.isLetter(ch)) {
723 break;
724 }
725 allLower &= Character.isLowerCase(ch);
726 if (index == colon - 1 && !allLower) {
727 inUrl = inUrl.substring(0, colon).toLowerCase()
728 + inUrl.substring(colon);
729 }
730 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800731 if (inUrl.startsWith("http://") || inUrl.startsWith("https://"))
732 return inUrl;
733 if (inUrl.startsWith("http:") ||
734 inUrl.startsWith("https:")) {
735 if (inUrl.startsWith("http:/") || inUrl.startsWith("https:/")) {
736 inUrl = inUrl.replaceFirst("/", "//");
737 } else inUrl = inUrl.replaceFirst(":", "://");
738 }
739 return inUrl;
740 }
741
Grace Kloba22ac16e2009-10-07 18:00:23 -0700742 @Override
743 protected void onResume() {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800744 super.onResume();
Dave Bort31a6d1c2009-04-13 15:56:49 -0700745 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800746 Log.v(LOGTAG, "BrowserActivity.onResume: this=" + this);
747 }
748
749 if (!mActivityInPause) {
750 Log.e(LOGTAG, "BrowserActivity is already resumed.");
751 return;
752 }
753
Mike Reed7bfa63b2009-05-28 11:08:32 -0400754 mTabControl.resumeCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800755 mActivityInPause = false;
Mike Reed7bfa63b2009-05-28 11:08:32 -0400756 resumeWebViewTimers();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800757
758 if (mWakeLock.isHeld()) {
759 mHandler.removeMessages(RELEASE_WAKELOCK);
760 mWakeLock.release();
761 }
762
The Android Open Source Project0c908882009-03-03 19:32:16 -0800763 registerReceiver(mNetworkStateIntentReceiver,
764 mNetworkStateChangedFilter);
765 WebView.enablePlatformNotifications();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800766 }
767
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400768 /**
769 * Since the actual title bar is embedded in the WebView, and removing it
Leon Scrogginsfe87bd32009-10-06 10:10:00 -0400770 * would change its appearance, use a different TitleBar to show overlayed
771 * at the top of the screen, when the menu is open or the page is loading.
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400772 */
Michael Kolba2b2ba82010-08-04 17:54:03 -0700773 private TitleBarBase mFakeTitleBar;
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400774
775 /**
776 * Keeps track of whether the options menu is open. This is important in
777 * determining whether to show or hide the title bar overlay.
778 */
779 private boolean mOptionsMenuOpen;
780
781 /**
782 * Only meaningful when mOptionsMenuOpen is true. This variable keeps track
783 * of whether the configuration has changed. The first onMenuOpened call
784 * after a configuration change is simply a reopening of the same menu
785 * (i.e. mIconView did not change).
786 */
787 private boolean mConfigChanged;
788
789 /**
790 * Whether or not the options menu is in its smaller, icon menu form. When
791 * true, we want the title bar overlay to be up. When false, we do not.
792 * Only meaningful if mOptionsMenuOpen is true.
793 */
794 private boolean mIconView;
795
Leon Scrogginsa81a7642009-08-31 17:05:41 -0400796 @Override
797 public boolean onMenuOpened(int featureId, Menu menu) {
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400798 if (Window.FEATURE_OPTIONS_PANEL == featureId) {
799 if (mOptionsMenuOpen) {
800 if (mConfigChanged) {
801 // We do not need to make any changes to the state of the
802 // title bar, since the only thing that happened was a
803 // change in orientation
804 mConfigChanged = false;
805 } else {
806 if (mIconView) {
807 // Switching the menu to expanded view, so hide the
808 // title bar.
809 hideFakeTitleBar();
810 mIconView = false;
811 } else {
812 // Switching the menu back to icon view, so show the
813 // title bar once again.
814 showFakeTitleBar();
815 mIconView = true;
816 }
817 }
818 } else {
819 // The options menu is closed, so open it, and show the title
820 showFakeTitleBar();
821 mOptionsMenuOpen = true;
822 mConfigChanged = false;
823 mIconView = true;
824 }
825 }
Leon Scrogginsa81a7642009-08-31 17:05:41 -0400826 return true;
827 }
828
Michael Kolba2b2ba82010-08-04 17:54:03 -0700829 void showFakeTitleBar() {
830 if (!isFakeTitleBarShowing() && mActiveTabsPage == null && !mActivityInPause) {
Grace Kloba847c25b2010-03-30 16:00:26 -0700831 WebView mainView = mTabControl.getCurrentWebView();
832 // if there is no current WebView, don't show the faked title bar;
Grace Kloba65190702010-04-02 23:37:26 -0700833 if (mainView == null) {
Cary Clarka0464552009-09-29 13:00:45 -0400834 return;
835 }
Leon Scroggins79e36d92010-04-29 16:01:46 +0100836 // Do not need to check for null, since the current tab will have
837 // at least a main WebView, or we would have returned above.
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -0400838 if (isInCustomActionMode()) {
839 // Do not show the fake title bar, while a custom ActionMode
840 // (i.e. find or select) is showing.
Leon Scroggins79e36d92010-04-29 16:01:46 +0100841 return;
842 }
Michael Kolba2b2ba82010-08-04 17:54:03 -0700843 if (mXLargeScreenSize) {
844 mContentView.addView(mFakeTitleBar);
845 mTabBar.onShowTitleBar();
846 } else {
847 WindowManager manager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400848
Michael Kolba2b2ba82010-08-04 17:54:03 -0700849 // Add the title bar to the window manager so it can receive
850 // touches
851 // while the menu is up
852 WindowManager.LayoutParams params =
853 new WindowManager.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
854 ViewGroup.LayoutParams.WRAP_CONTENT,
855 WindowManager.LayoutParams.TYPE_APPLICATION,
856 WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
857 PixelFormat.TRANSLUCENT);
858 params.gravity = Gravity.TOP;
859 boolean atTop = mainView.getScrollY() == 0;
860 params.windowAnimations = atTop ? 0 : R.style.TitleBar;
861 manager.addView(mFakeTitleBar, params);
862 }
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400863 }
864 }
865
866 @Override
867 public void onOptionsMenuClosed(Menu menu) {
868 mOptionsMenuOpen = false;
Leon Scrogginsa27ff192009-09-14 12:58:04 -0400869 if (!mInLoad) {
870 hideFakeTitleBar();
871 } else if (!mIconView) {
872 // The page is currently loading, and we are in expanded mode, so
873 // we were not showing the menu. Show it once again. It will be
874 // removed when the page finishes.
875 showFakeTitleBar();
876 }
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400877 }
Grace Kloba22ac16e2009-10-07 18:00:23 -0700878
Michael Kolba2b2ba82010-08-04 17:54:03 -0700879 void stopScrolling() {
880 ((ScrollWebView) mTabControl.getCurrentWebView()).stopScroll();
881 }
882
883 void hideFakeTitleBar() {
884 if (!isFakeTitleBarShowing()) return;
885 if (mXLargeScreenSize) {
886 mContentView.removeView(mFakeTitleBar);
887 mTabBar.onHideTitleBar();
888 } else {
889 WindowManager.LayoutParams params =
890 (WindowManager.LayoutParams) mFakeTitleBar.getLayoutParams();
891 WebView mainView = mTabControl.getCurrentWebView();
892 // Although we decided whether or not to animate based on the
893 // current
894 // scroll position, the scroll position may have changed since the
895 // fake title bar was displayed. Make sure it has the appropriate
896 // animation/lack thereof before removing.
897 params.windowAnimations =
898 mainView != null && mainView.getScrollY() == 0 ? 0 : R.style.TitleBar;
899 WindowManager manager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
900 manager.updateViewLayout(mFakeTitleBar, params);
901 manager.removeView(mFakeTitleBar);
902 }
903 }
904
905 boolean isFakeTitleBarShowing() {
906 return (mFakeTitleBar.getParent() != null);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400907 }
908
The Android Open Source Project0c908882009-03-03 19:32:16 -0800909 /**
Leon Scrogginsc6fa1102009-09-21 10:40:01 -0400910 * Special method for the fake title bar to call when displaying its context
911 * menu, since it is in its own Window, and its parent does not show a
912 * context menu.
913 */
914 /* package */ void showTitleBarContextMenu() {
Cary Clark65f4a3c2009-09-28 17:05:06 -0400915 if (null == mTitleBar.getParent()) {
916 return;
917 }
Leon Scrogginsc6fa1102009-09-21 10:40:01 -0400918 openContextMenu(mTitleBar);
919 }
920
Leon Scrogginsb2b19f52009-10-09 16:10:00 -0400921 @Override
922 public void onContextMenuClosed(Menu menu) {
923 super.onContextMenuClosed(menu);
924 if (mInLoad) {
925 showFakeTitleBar();
926 }
927 }
928
Leon Scrogginsc6fa1102009-09-21 10:40:01 -0400929 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -0800930 * onSaveInstanceState(Bundle map)
931 * onSaveInstanceState is called right before onStop(). The map contains
932 * the saved state.
933 */
Grace Kloba22ac16e2009-10-07 18:00:23 -0700934 @Override
935 protected void onSaveInstanceState(Bundle outState) {
Dave Bort31a6d1c2009-04-13 15:56:49 -0700936 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800937 Log.v(LOGTAG, "BrowserActivity.onSaveInstanceState: this=" + this);
938 }
939 // the default implementation requires each view to have an id. As the
940 // browser handles the state itself and it doesn't use id for the views,
941 // don't call the default implementation. Otherwise it will trigger the
942 // warning like this, "couldn't save which view has focus because the
943 // focused view XXX has no id".
944
945 // Save all the tabs
946 mTabControl.saveState(outState);
Elliott Slaughter3d6df162010-08-25 13:17:44 -0700947
948 // Save time so that we know how old incognito tabs (if any) are.
949 outState.putSerializable("lastActiveDate", Calendar.getInstance());
The Android Open Source Project0c908882009-03-03 19:32:16 -0800950 }
951
Grace Kloba22ac16e2009-10-07 18:00:23 -0700952 @Override
953 protected void onPause() {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800954 super.onPause();
955
956 if (mActivityInPause) {
957 Log.e(LOGTAG, "BrowserActivity is already paused.");
958 return;
959 }
960
Mike Reed7bfa63b2009-05-28 11:08:32 -0400961 mTabControl.pauseCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800962 mActivityInPause = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -0400963 if (mTabControl.getCurrentIndex() >= 0 && !pauseWebViewTimers()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800964 mWakeLock.acquire();
965 mHandler.sendMessageDelayed(mHandler
966 .obtainMessage(RELEASE_WAKELOCK), WAKELOCK_TIMEOUT);
967 }
968
Leon Scrogginsa2ab6a72009-09-11 11:49:52 -0400969 // FIXME: This removes the active tabs page and resets the menu to
970 // MAIN_MENU. A better solution might be to do this work in onNewIntent
971 // but then we would need to save it in onSaveInstanceState and restore
972 // it in onCreate/onRestoreInstanceState
973 if (mActiveTabsPage != null) {
974 removeActiveTabPage(true);
975 }
976
The Android Open Source Project0c908882009-03-03 19:32:16 -0800977 cancelStopToast();
978
979 // unregister network state listener
980 unregisterReceiver(mNetworkStateIntentReceiver);
981 WebView.disablePlatformNotifications();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800982 }
983
Grace Kloba22ac16e2009-10-07 18:00:23 -0700984 @Override
985 protected void onDestroy() {
Dave Bort31a6d1c2009-04-13 15:56:49 -0700986 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800987 Log.v(LOGTAG, "BrowserActivity.onDestroy: this=" + this);
988 }
989 super.onDestroy();
Grace Kloba0923d692009-09-23 21:37:25 -0700990
Leon Scroggins8d5fa432009-10-02 15:55:59 -0400991 if (mUploadMessage != null) {
992 mUploadMessage.onReceiveValue(null);
993 mUploadMessage = null;
994 }
995
Grace Kloba0923d692009-09-23 21:37:25 -0700996 if (mTabControl == null) return;
997
Grace Kloba1fc98a32009-10-21 13:23:08 -0700998 // Remove the fake title bar if it is there
999 hideFakeTitleBar();
1000
The Android Open Source Project0c908882009-03-03 19:32:16 -08001001 // Remove the current tab and sub window
Grace Kloba22ac16e2009-10-07 18:00:23 -07001002 Tab t = mTabControl.getCurrentTab();
Patrick Scottfb5e77f2009-04-08 19:17:37 -07001003 if (t != null) {
1004 dismissSubWindow(t);
1005 removeTabFromContentView(t);
1006 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001007 // Destroy all the tabs
1008 mTabControl.destroy();
1009 WebIconDatabase.getInstance().close();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001010
Bjorn Bringerta7611812010-03-24 11:12:02 +00001011 // Stop watching the default geolocation permissions
1012 mSystemAllowGeolocationOrigins.stop();
1013 mSystemAllowGeolocationOrigins = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001014 }
1015
1016 @Override
1017 public void onConfigurationChanged(Configuration newConfig) {
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04001018 mConfigChanged = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001019 super.onConfigurationChanged(newConfig);
1020
1021 if (mPageInfoDialog != null) {
1022 mPageInfoDialog.dismiss();
1023 showPageInfo(
1024 mPageInfoView,
Leon Scrogginsc7b92f82010-01-11 18:17:31 -05001025 mPageInfoFromShowSSLCertificateOnError);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001026 }
1027 if (mSSLCertificateDialog != null) {
1028 mSSLCertificateDialog.dismiss();
1029 showSSLCertificate(
1030 mSSLCertificateView);
1031 }
1032 if (mSSLCertificateOnErrorDialog != null) {
1033 mSSLCertificateOnErrorDialog.dismiss();
1034 showSSLCertificateOnError(
1035 mSSLCertificateOnErrorView,
1036 mSSLCertificateOnErrorHandler,
1037 mSSLCertificateOnErrorError);
1038 }
1039 if (mHttpAuthenticationDialog != null) {
1040 String title = ((TextView) mHttpAuthenticationDialog
1041 .findViewById(com.android.internal.R.id.alertTitle)).getText()
1042 .toString();
1043 String name = ((TextView) mHttpAuthenticationDialog
1044 .findViewById(R.id.username_edit)).getText().toString();
1045 String password = ((TextView) mHttpAuthenticationDialog
1046 .findViewById(R.id.password_edit)).getText().toString();
1047 int focusId = mHttpAuthenticationDialog.getCurrentFocus()
1048 .getId();
1049 mHttpAuthenticationDialog.dismiss();
1050 showHttpAuthentication(mHttpAuthHandler, null, null, title,
1051 name, password, focusId);
1052 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001053 }
1054
Grace Kloba22ac16e2009-10-07 18:00:23 -07001055 @Override
1056 public void onLowMemory() {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001057 super.onLowMemory();
1058 mTabControl.freeMemory();
1059 }
1060
Cary Clarkff4d92c2010-03-25 11:17:03 -04001061 private void resumeWebViewTimers() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001062 Tab tab = mTabControl.getCurrentTab();
Cary Clarkff4d92c2010-03-25 11:17:03 -04001063 if (tab == null) return; // monkey can trigger this
Grace Kloba22ac16e2009-10-07 18:00:23 -07001064 boolean inLoad = tab.inLoad();
1065 if ((!mActivityInPause && !inLoad) || (mActivityInPause && inLoad)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001066 CookieSyncManager.getInstance().startSync();
Grace Kloba22ac16e2009-10-07 18:00:23 -07001067 WebView w = tab.getWebView();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001068 if (w != null) {
1069 w.resumeTimers();
1070 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001071 }
1072 }
1073
Mike Reed7bfa63b2009-05-28 11:08:32 -04001074 private boolean pauseWebViewTimers() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001075 Tab tab = mTabControl.getCurrentTab();
1076 boolean inLoad = tab.inLoad();
1077 if (mActivityInPause && !inLoad) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001078 CookieSyncManager.getInstance().stopSync();
1079 WebView w = mTabControl.getCurrentWebView();
1080 if (w != null) {
1081 w.pauseTimers();
1082 }
1083 return true;
1084 } else {
1085 return false;
1086 }
1087 }
1088
The Android Open Source Project0c908882009-03-03 19:32:16 -08001089 // Open the icon database and retain all the icons for visited sites.
1090 private void retainIconsOnStartup() {
1091 final WebIconDatabase db = WebIconDatabase.getInstance();
1092 db.open(getDir("icons", 0).getPath());
Leon Scroggins2c0f6112010-03-12 18:09:39 -05001093 Cursor c = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001094 try {
Leon Scroggins2c0f6112010-03-12 18:09:39 -05001095 c = Browser.getAllBookmarks(mResolver);
1096 if (c.moveToFirst()) {
1097 int urlIndex = c.getColumnIndex(Browser.BookmarkColumns.URL);
1098 do {
1099 String url = c.getString(urlIndex);
1100 db.retainIconForPageUrl(url);
1101 } while (c.moveToNext());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001102 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001103 } catch (IllegalStateException e) {
1104 Log.e(LOGTAG, "retainIconsOnStartup", e);
Leon Scroggins2c0f6112010-03-12 18:09:39 -05001105 } finally {
1106 if (c!= null) c.close();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001107 }
1108 }
1109
1110 // Helper method for getting the top window.
1111 WebView getTopWindow() {
1112 return mTabControl.getCurrentTopWebView();
1113 }
1114
Grace Kloba22ac16e2009-10-07 18:00:23 -07001115 TabControl getTabControl() {
1116 return mTabControl;
1117 }
1118
The Android Open Source Project0c908882009-03-03 19:32:16 -08001119 @Override
1120 public boolean onCreateOptionsMenu(Menu menu) {
1121 super.onCreateOptionsMenu(menu);
1122
1123 MenuInflater inflater = getMenuInflater();
1124 inflater.inflate(R.menu.browser, menu);
1125 mMenu = menu;
1126 updateInLoadMenuItems();
1127 return true;
1128 }
1129
1130 /**
1131 * As the menu can be open when loading state changes
1132 * we must manually update the state of the stop/reload menu
1133 * item
1134 */
1135 private void updateInLoadMenuItems() {
1136 if (mMenu == null) {
1137 return;
1138 }
Michael Kolbe0a36662010-06-29 10:37:12 -07001139 MenuItem dest = mMenu.findItem(R.id.stop_reload_menu_id);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001140 MenuItem src = mInLoad ?
1141 mMenu.findItem(R.id.stop_menu_id):
Michael Kolbe0a36662010-06-29 10:37:12 -07001142 mMenu.findItem(R.id.reload_menu_id);
1143 if (src != null) {
1144 dest.setIcon(src.getIcon());
1145 dest.setTitle(src.getTitle());
1146 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001147 }
1148
1149 @Override
1150 public boolean onContextItemSelected(MenuItem item) {
1151 // chording is not an issue with context menus, but we use the same
1152 // options selector, so set mCanChord to true so we can access them.
1153 mCanChord = true;
1154 int id = item.getItemId();
Leon Scroggins96afcb12009-12-10 12:35:56 -05001155 boolean result = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001156 switch (id) {
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001157 // For the context menu from the title bar
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001158 case R.id.title_bar_copy_page_url:
Leon Scroggins96afcb12009-12-10 12:35:56 -05001159 Tab currentTab = mTabControl.getCurrentTab();
1160 if (null == currentTab) {
1161 result = false;
1162 break;
1163 }
1164 WebView mainView = currentTab.getWebView();
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001165 if (null == mainView) {
Leon Scroggins96afcb12009-12-10 12:35:56 -05001166 result = false;
1167 break;
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001168 }
Leon Scroggins96afcb12009-12-10 12:35:56 -05001169 copy(mainView.getUrl());
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001170 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001171 // -- Browser context menu
1172 case R.id.open_context_menu_id:
The Android Open Source Project0c908882009-03-03 19:32:16 -08001173 case R.id.bookmark_context_menu_id:
1174 case R.id.save_link_context_menu_id:
1175 case R.id.share_link_context_menu_id:
1176 case R.id.copy_link_context_menu_id:
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001177 final WebView webView = getTopWindow();
1178 if (null == webView) {
Leon Scroggins96afcb12009-12-10 12:35:56 -05001179 result = false;
1180 break;
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001181 }
1182 final HashMap hrefMap = new HashMap();
1183 hrefMap.put("webview", webView);
1184 final Message msg = mHandler.obtainMessage(
1185 FOCUS_NODE_HREF, id, 0, hrefMap);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001186 webView.requestFocusNodeHref(msg);
1187 break;
1188
1189 default:
1190 // For other context menus
Leon Scroggins96afcb12009-12-10 12:35:56 -05001191 result = onOptionsItemSelected(item);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001192 }
1193 mCanChord = false;
Leon Scroggins96afcb12009-12-10 12:35:56 -05001194 return result;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001195 }
1196
1197 private Bundle createGoogleSearchSourceBundle(String source) {
1198 Bundle bundle = new Bundle();
Bjorn Bringert10d1cca2010-02-10 14:22:12 +00001199 bundle.putString(Search.SOURCE, source);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001200 return bundle;
1201 }
1202
Leon Scroggins8ad29922010-02-16 12:33:55 -05001203 /* package */ void editUrl() {
Leon Scroggins68579392009-09-15 15:31:54 -04001204 if (mOptionsMenuOpen) closeOptionsMenu();
Leon Scroggins5bbe9802009-07-31 13:10:55 -04001205 String url = (getTopWindow() == null) ? null : getTopWindow().getUrl();
Grace Kloba83f47342009-07-20 10:44:31 -07001206 startSearch(mSettings.getHomePage().equals(url) ? null : url, true,
Leon Scroggins8ad29922010-02-16 12:33:55 -05001207 null, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001208 }
1209
Leon Scroggins8ad29922010-02-16 12:33:55 -05001210 /**
1211 * Overriding this to insert a local information bundle
1212 */
The Android Open Source Project0c908882009-03-03 19:32:16 -08001213 @Override
1214 public void startSearch(String initialQuery, boolean selectInitialQuery,
1215 Bundle appSearchData, boolean globalSearch) {
1216 if (appSearchData == null) {
1217 appSearchData = createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_TYPE);
1218 }
Leon Scroggins III430057d2010-09-14 10:57:37 -04001219
1220 SearchEngine searchEngine = mSettings.getSearchEngine();
1221 if (searchEngine != null && !searchEngine.supportsVoiceSearch()) {
1222 appSearchData.putBoolean(SearchManager.DISABLE_VOICE_SEARCH, true);
1223 }
1224
The Android Open Source Project0c908882009-03-03 19:32:16 -08001225 super.startSearch(initialQuery, selectInitialQuery, appSearchData, globalSearch);
1226 }
1227
Leon Scroggins1f005d32009-08-10 17:36:42 -04001228 /**
1229 * Switch tabs. Called by the TitleBarSet when sliding the title bar
1230 * results in changing tabs.
Leon Scroggins160a7e72009-08-14 18:28:01 -04001231 * @param index Index of the tab to change to, as defined by
1232 * mTabControl.getTabIndex(Tab t).
1233 * @return boolean True if we successfully switched to a different tab. If
1234 * the indexth tab is null, or if that tab is the same as
1235 * the current one, return false.
Leon Scroggins1f005d32009-08-10 17:36:42 -04001236 */
Leon Scroggins160a7e72009-08-14 18:28:01 -04001237 /* package */ boolean switchToTab(int index) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001238 Tab tab = mTabControl.getTab(index);
1239 Tab currentTab = mTabControl.getCurrentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04001240 if (tab == null || tab == currentTab) {
Leon Scroggins160a7e72009-08-14 18:28:01 -04001241 return false;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001242 }
1243 if (currentTab != null) {
1244 // currentTab may be null if it was just removed. In that case,
1245 // we do not need to remove it
1246 removeTabFromContentView(currentTab);
1247 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001248 mTabControl.setCurrentTab(tab);
1249 attachTabToContentView(tab);
Grace Klobaeb6eef42009-09-15 17:56:32 -07001250 resetTitleIconAndProgress();
1251 updateLockIconToLatest();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001252 return true;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001253 }
1254
Grace Kloba22ac16e2009-10-07 18:00:23 -07001255 /* package */ Tab openTabToHomePage() {
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001256 return openTabAndShow(mSettings.getHomePage(), false, null);
1257 }
1258
Leon Scroggins1f005d32009-08-10 17:36:42 -04001259 /* package */ void closeCurrentWindow() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001260 final Tab current = mTabControl.getCurrentTab();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001261 if (mTabControl.getTabCount() == 1) {
Leon Scroggins30444232009-09-04 18:36:20 -04001262 // This is the last tab. Open a new one, with the home
1263 // page and close the current one.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001264 openTabToHomePage();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001265 closeTab(current);
Leon Scroggins160a7e72009-08-14 18:28:01 -04001266 return;
1267 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07001268 final Tab parent = current.getParentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04001269 int indexToShow = -1;
1270 if (parent != null) {
1271 indexToShow = mTabControl.getTabIndex(parent);
1272 } else {
Leon Scroggins160a7e72009-08-14 18:28:01 -04001273 final int currentIndex = mTabControl.getCurrentIndex();
1274 // Try to move to the tab to the right
1275 indexToShow = currentIndex + 1;
1276 if (indexToShow > mTabControl.getTabCount() - 1) {
1277 // Try to move to the tab to the left
1278 indexToShow = currentIndex - 1;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001279 }
1280 }
Leon Scroggins160a7e72009-08-14 18:28:01 -04001281 if (switchToTab(indexToShow)) {
1282 // Close window
1283 closeTab(current);
1284 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001285 }
1286
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001287 private ActiveTabsPage mActiveTabsPage;
1288
1289 /**
1290 * Remove the active tabs page.
1291 * @param needToAttach If true, the active tabs page did not attach a tab
1292 * to the content view, so we need to do that here.
1293 */
1294 /* package */ void removeActiveTabPage(boolean needToAttach) {
1295 mContentView.removeView(mActiveTabsPage);
Leon Scrogginsd746a942010-05-19 13:21:44 -04001296 mTitleBar.setVisibility(View.VISIBLE);
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001297 mActiveTabsPage = null;
1298 mMenuState = R.id.MAIN_MENU;
1299 if (needToAttach) {
1300 attachTabToContentView(mTabControl.getCurrentTab());
1301 }
1302 getTopWindow().requestFocus();
1303 }
1304
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04001305 @Override
1306 public ActionMode onStartActionMode(ActionMode.Callback callback) {
Leon Scroggins4fc12cb2010-08-24 14:24:05 -04001307 mActionMode = super.onStartActionMode(callback);
1308 hideFakeTitleBar();
1309 // Would like to change the MENU, but onEndActionMode may not be called
1310 return mActionMode;
Cary Clark01cfcdd2010-06-04 16:36:45 -04001311 }
1312
The Android Open Source Project0c908882009-03-03 19:32:16 -08001313 @Override
1314 public boolean onOptionsItemSelected(MenuItem item) {
Michael Kolbed217742010-08-10 17:52:34 -07001315 // check the action bar button before mCanChord check, as the prepare call
1316 // doesn't come for action bar buttons
1317 if (item.getItemId() == R.id.newtab) {
Michael Kolb300b7f02010-08-25 13:47:24 -07001318 openTabToHomePage();
Michael Kolbed217742010-08-10 17:52:34 -07001319 return true;
1320 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001321 if (!mCanChord) {
1322 // The user has already fired a shortcut with this hold down of the
1323 // menu key.
1324 return false;
1325 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001326 if (null == getTopWindow()) {
Leon Scroggins0d7ae0e2009-06-05 11:04:45 -04001327 return false;
1328 }
Grace Kloba6ee9c492009-07-13 10:04:34 -07001329 if (mMenuIsDown) {
1330 // The shortcut action consumes the MENU. Even if it is still down,
1331 // it won't trigger the next shortcut action. In the case of the
1332 // shortcut action triggering a new activity, like Bookmarks, we
1333 // won't get onKeyUp for MENU. So it is important to reset it here.
1334 mMenuIsDown = false;
1335 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001336 switch (item.getItemId()) {
1337 // -- Main menu
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001338 case R.id.new_tab_menu_id:
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001339 openTabToHomePage();
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001340 break;
1341
Michael Kolbae62fd42010-08-18 16:33:28 -07001342 case R.id.incognito_menu_id:
1343 openIncognitoTab();
1344 break;
1345
Leon Scroggins64b80f32009-08-07 12:03:34 -04001346 case R.id.goto_menu_id:
Leon Scroggins8ad29922010-02-16 12:33:55 -05001347 editUrl();
Leon Scrogginsb3a5bed2009-09-28 11:21:56 -04001348 break;
1349
1350 case R.id.bookmarks_menu_id:
Michael Kolb68792c82010-08-09 16:39:18 -07001351 bookmarksOrHistoryPicker(false, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001352 break;
1353
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001354 case R.id.active_tabs_menu_id:
1355 mActiveTabsPage = new ActiveTabsPage(this, mTabControl);
1356 removeTabFromContentView(mTabControl.getCurrentTab());
Leon Scrogginsd746a942010-05-19 13:21:44 -04001357 mTitleBar.setVisibility(View.GONE);
Leon Scroggins43de6162009-09-14 19:59:58 -04001358 hideFakeTitleBar();
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001359 mContentView.addView(mActiveTabsPage, COVER_SCREEN_PARAMS);
1360 mActiveTabsPage.requestFocus();
1361 mMenuState = EMPTY_MENU;
1362 break;
1363
Leon Scroggins1f005d32009-08-10 17:36:42 -04001364 case R.id.add_bookmark_menu_id:
Leon Scroggins571b3762010-05-26 10:25:01 -04001365 bookmarkCurrentPage();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001366 break;
1367
1368 case R.id.stop_reload_menu_id:
1369 if (mInLoad) {
1370 stopLoading();
1371 } else {
1372 getTopWindow().reload();
1373 }
1374 break;
1375
1376 case R.id.back_menu_id:
1377 getTopWindow().goBack();
1378 break;
1379
1380 case R.id.forward_menu_id:
1381 getTopWindow().goForward();
1382 break;
1383
1384 case R.id.close_menu_id:
1385 // Close the subwindow if it exists.
1386 if (mTabControl.getCurrentSubWindow() != null) {
1387 dismissSubWindow(mTabControl.getCurrentTab());
1388 break;
1389 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001390 closeCurrentWindow();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001391 break;
1392
1393 case R.id.homepage_menu_id:
Grace Kloba22ac16e2009-10-07 18:00:23 -07001394 Tab current = mTabControl.getCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001395 if (current != null) {
1396 dismissSubWindow(current);
Leon Scroggins92472e82010-02-17 16:32:28 -05001397 loadUrl(current.getWebView(), mSettings.getHomePage());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001398 }
1399 break;
1400
1401 case R.id.preferences_menu_id:
1402 Intent intent = new Intent(this,
1403 BrowserPreferencesPage.class);
Leon Scrogginsd5304942009-12-10 16:11:39 -05001404 intent.putExtra(BrowserPreferencesPage.CURRENT_PAGE,
1405 getTopWindow().getUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001406 startActivityForResult(intent, PREFERENCES_PAGE);
1407 break;
1408
1409 case R.id.find_menu_id:
Leon Scroggins4fc12cb2010-08-24 14:24:05 -04001410 getTopWindow().showFindDialog(null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001411 break;
1412
Elliott Slaughter0ced08c2010-06-30 11:40:42 -07001413 case R.id.save_webarchive_menu_id:
1414 if (LOGD_ENABLED) {
1415 Log.d(LOGTAG, "Save as Web Archive");
1416 }
Elliott Slaughteraba242c2010-09-01 16:21:07 -07001417 String state = Environment.getExternalStorageState();
1418 if (Environment.MEDIA_MOUNTED.equals(state)) {
1419 String directory = Environment.getExternalStoragePublicDirectory(
1420 Environment.DIRECTORY_DOWNLOADS).getAbsolutePath() + File.separator;
Shimeng (Simon) Wang447c8462010-09-15 18:16:55 -07001421 File dir = new File(directory);
1422 if (!dir.exists() && !dir.mkdirs()) {
1423 Log.e(LOGTAG, "Save as Web Archive: mkdirs for " + directory + " failed!");
1424 Toast.makeText(BrowserActivity.this, R.string.webarchive_failed,
1425 Toast.LENGTH_SHORT).show();
1426 break;
1427 }
Elliott Slaughteraba242c2010-09-01 16:21:07 -07001428 getTopWindow().saveWebArchive(directory, true, new ValueCallback<String>() {
1429 @Override
1430 public void onReceiveValue(String value) {
1431 if (value != null) {
1432 Toast.makeText(BrowserActivity.this, R.string.webarchive_saved,
1433 Toast.LENGTH_SHORT).show();
1434 } else {
1435 Toast.makeText(BrowserActivity.this, R.string.webarchive_failed,
1436 Toast.LENGTH_SHORT).show();
1437 }
Elliott Slaughter0ced08c2010-06-30 11:40:42 -07001438 }
Elliott Slaughteraba242c2010-09-01 16:21:07 -07001439 });
1440 } else {
1441 Toast.makeText(BrowserActivity.this, R.string.webarchive_failed,
1442 Toast.LENGTH_SHORT).show();
1443 }
Elliott Slaughter0ced08c2010-06-30 11:40:42 -07001444 break;
1445
The Android Open Source Project0c908882009-03-03 19:32:16 -08001446 case R.id.page_info_menu_id:
1447 showPageInfo(mTabControl.getCurrentTab(), false);
1448 break;
1449
1450 case R.id.classic_history_menu_id:
Michael Kolb68792c82010-08-09 16:39:18 -07001451 bookmarksOrHistoryPicker(true, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001452 break;
1453
Leon Scroggins96afcb12009-12-10 12:35:56 -05001454 case R.id.title_bar_share_page_url:
The Android Open Source Project0c908882009-03-03 19:32:16 -08001455 case R.id.share_page_menu_id:
Leon Scroggins96afcb12009-12-10 12:35:56 -05001456 Tab currentTab = mTabControl.getCurrentTab();
1457 if (null == currentTab) {
1458 mCanChord = false;
1459 return false;
1460 }
1461 currentTab.populatePickerData();
1462 sharePage(this, currentTab.getTitle(),
1463 currentTab.getUrl(), currentTab.getFavicon(),
Ben Murdoch87cc65d2010-06-29 20:34:10 +01001464 createScreenshot(currentTab.getWebView(), getDesiredThumbnailWidth(this),
1465 getDesiredThumbnailHeight(this)));
The Android Open Source Project0c908882009-03-03 19:32:16 -08001466 break;
1467
1468 case R.id.dump_nav_menu_id:
1469 getTopWindow().debugDump();
1470 break;
1471
Andrei Popescu7a8b88b2010-02-02 00:30:38 +00001472 case R.id.dump_counters_menu_id:
1473 getTopWindow().dumpV8Counters();
1474 break;
1475
The Android Open Source Project0c908882009-03-03 19:32:16 -08001476 case R.id.zoom_in_menu_id:
1477 getTopWindow().zoomIn();
1478 break;
1479
1480 case R.id.zoom_out_menu_id:
1481 getTopWindow().zoomOut();
1482 break;
1483
1484 case R.id.view_downloads_menu_id:
Leon Scroggins IIIa682a3c2010-09-27 12:32:40 -04001485 viewDownloads();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001486 break;
1487
The Android Open Source Project0c908882009-03-03 19:32:16 -08001488 case R.id.window_one_menu_id:
1489 case R.id.window_two_menu_id:
1490 case R.id.window_three_menu_id:
1491 case R.id.window_four_menu_id:
1492 case R.id.window_five_menu_id:
1493 case R.id.window_six_menu_id:
1494 case R.id.window_seven_menu_id:
1495 case R.id.window_eight_menu_id:
1496 {
1497 int menuid = item.getItemId();
1498 for (int id = 0; id < WINDOW_SHORTCUT_ID_ARRAY.length; id++) {
1499 if (WINDOW_SHORTCUT_ID_ARRAY[id] == menuid) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001500 Tab desiredTab = mTabControl.getTab(id);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001501 if (desiredTab != null &&
1502 desiredTab != mTabControl.getCurrentTab()) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001503 switchToTab(id);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001504 }
1505 break;
1506 }
1507 }
1508 }
1509 break;
1510
1511 default:
1512 if (!super.onOptionsItemSelected(item)) {
1513 return false;
1514 }
1515 // Otherwise fall through.
1516 }
1517 mCanChord = false;
1518 return true;
1519 }
1520
Leon Scroggins571b3762010-05-26 10:25:01 -04001521 /* package */ void bookmarkCurrentPage() {
1522 Intent i = new Intent(BrowserActivity.this,
1523 AddBookmarkPage.class);
1524 WebView w = getTopWindow();
1525 i.putExtra("url", w.getUrl());
1526 i.putExtra("title", w.getTitle());
1527 i.putExtra("touch_icon_url", w.getTouchIconUrl());
Ben Murdoch87cc65d2010-06-29 20:34:10 +01001528 i.putExtra("thumbnail", createScreenshot(w, getDesiredThumbnailWidth(this),
1529 getDesiredThumbnailHeight(this)));
Leon Scroggins III76a0e9c2010-10-05 16:10:01 -04001530 // Put the dialog at the upper right of the screen, covering the
1531 // star on the title bar.
1532 i.putExtra("gravity", Gravity.RIGHT | Gravity.TOP);
Leon Scroggins571b3762010-05-26 10:25:01 -04001533 startActivity(i);
1534 }
1535
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04001536 /*
1537 * True if a custom ActionMode (i.e. find or select) is in use.
1538 */
1539 private boolean isInCustomActionMode() {
1540 return mActionMode != null;
Cary Clark01cfcdd2010-06-04 16:36:45 -04001541 }
1542
1543 /*
Leon Scroggins4fc12cb2010-08-24 14:24:05 -04001544 * End the current ActionMode.
Cary Clark01cfcdd2010-06-04 16:36:45 -04001545 */
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04001546 void endActionMode() {
1547 if (mActionMode != null) {
Leon Scroggins4fc12cb2010-08-24 14:24:05 -04001548 ActionMode mode = mActionMode;
1549 onEndActionMode();
1550 mode.finish();
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04001551 }
1552 }
1553
1554 /*
1555 * Called by find and select when they are finished. Replace title bars
1556 * as necessary.
1557 */
1558 public void onEndActionMode() {
1559 if (!isInCustomActionMode()) return;
Leon Scroggins79e36d92010-04-29 16:01:46 +01001560 if (mInLoad) {
1561 // The title bar was hidden, because otherwise it would cover up the
Michael Kolba2b2ba82010-08-04 17:54:03 -07001562 // find or select dialog. Now that the dialog has been removed,
Cary Clark01cfcdd2010-06-04 16:36:45 -04001563 // show the fake title bar once again.
Leon Scroggins79e36d92010-04-29 16:01:46 +01001564 showFakeTitleBar();
1565 }
Leon Scroggins4fc12cb2010-08-24 14:24:05 -04001566 // Would like to return the menu state to normal, but this does not
1567 // necessarily get called.
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04001568 mActionMode = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001569 }
1570
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04001571 // For select and find, we keep track of the ActionMode so that
1572 // finish() can be called as desired.
1573 private ActionMode mActionMode;
1574
Grace Kloba22ac16e2009-10-07 18:00:23 -07001575 @Override
1576 public boolean onPrepareOptionsMenu(Menu menu) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001577 // This happens when the user begins to hold down the menu key, so
1578 // allow them to chord to get a shortcut.
1579 mCanChord = true;
1580 // Note: setVisible will decide whether an item is visible; while
1581 // setEnabled() will decide whether an item is enabled, which also means
1582 // whether the matching shortcut key will function.
1583 super.onPrepareOptionsMenu(menu);
1584 switch (mMenuState) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001585 case EMPTY_MENU:
1586 if (mCurrentMenuState != mMenuState) {
1587 menu.setGroupVisible(R.id.MAIN_MENU, false);
1588 menu.setGroupEnabled(R.id.MAIN_MENU, false);
1589 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001590 }
1591 break;
1592 default:
1593 if (mCurrentMenuState != mMenuState) {
1594 menu.setGroupVisible(R.id.MAIN_MENU, true);
1595 menu.setGroupEnabled(R.id.MAIN_MENU, true);
1596 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001597 }
1598 final WebView w = getTopWindow();
1599 boolean canGoBack = false;
1600 boolean canGoForward = false;
1601 boolean isHome = false;
1602 if (w != null) {
1603 canGoBack = w.canGoBack();
1604 canGoForward = w.canGoForward();
1605 isHome = mSettings.getHomePage().equals(w.getUrl());
1606 }
1607 final MenuItem back = menu.findItem(R.id.back_menu_id);
1608 back.setEnabled(canGoBack);
1609
1610 final MenuItem home = menu.findItem(R.id.homepage_menu_id);
1611 home.setEnabled(!isHome);
1612
Michael Kolbe0a36662010-06-29 10:37:12 -07001613 final MenuItem forward = menu.findItem(R.id.forward_menu_id);
1614 forward.setEnabled(canGoForward);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001615
Michael Kolbed217742010-08-10 17:52:34 -07001616 if (!mXLargeScreenSize) {
1617 final MenuItem newtab = menu.findItem(R.id.new_tab_menu_id);
1618 newtab.setEnabled(mTabControl.canCreateNewTab());
1619 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001620 // decide whether to show the share link option
1621 PackageManager pm = getPackageManager();
1622 Intent send = new Intent(Intent.ACTION_SEND);
1623 send.setType("text/plain");
1624 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1625 menu.findItem(R.id.share_page_menu_id).setVisible(ri != null);
1626
The Android Open Source Project0c908882009-03-03 19:32:16 -08001627 boolean isNavDump = mSettings.isNavDump();
1628 final MenuItem nav = menu.findItem(R.id.dump_nav_menu_id);
1629 nav.setVisible(isNavDump);
1630 nav.setEnabled(isNavDump);
Andrei Popescu7a8b88b2010-02-02 00:30:38 +00001631
1632 boolean showDebugSettings = mSettings.showDebugSettings();
1633 final MenuItem counter = menu.findItem(R.id.dump_counters_menu_id);
1634 counter.setVisible(showDebugSettings);
1635 counter.setEnabled(showDebugSettings);
1636
The Android Open Source Project0c908882009-03-03 19:32:16 -08001637 break;
1638 }
1639 mCurrentMenuState = mMenuState;
1640 return true;
1641 }
1642
1643 @Override
1644 public void onCreateContextMenu(ContextMenu menu, View v,
1645 ContextMenuInfo menuInfo) {
Leon Scroggins571b3762010-05-26 10:25:01 -04001646 if (v instanceof TitleBarBase) {
Leon Scroggins4e9f89b2010-02-22 16:54:14 -05001647 return;
1648 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001649 WebView webview = (WebView) v;
1650 WebView.HitTestResult result = webview.getHitTestResult();
1651 if (result == null) {
1652 return;
1653 }
1654
1655 int type = result.getType();
1656 if (type == WebView.HitTestResult.UNKNOWN_TYPE) {
1657 Log.w(LOGTAG,
1658 "We should not show context menu when nothing is touched");
1659 return;
1660 }
1661 if (type == WebView.HitTestResult.EDIT_TEXT_TYPE) {
1662 // let TextView handles context menu
1663 return;
1664 }
1665
1666 // Note, http://b/issue?id=1106666 is requesting that
1667 // an inflated menu can be used again. This is not available
1668 // yet, so inflate each time (yuk!)
1669 MenuInflater inflater = getMenuInflater();
1670 inflater.inflate(R.menu.browsercontext, menu);
1671
1672 // Show the correct menu group
Leon Scroggins III9e997c72010-05-26 13:25:16 -04001673 final String extra = result.getExtra();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001674 menu.setGroupVisible(R.id.PHONE_MENU,
1675 type == WebView.HitTestResult.PHONE_TYPE);
1676 menu.setGroupVisible(R.id.EMAIL_MENU,
1677 type == WebView.HitTestResult.EMAIL_TYPE);
1678 menu.setGroupVisible(R.id.GEO_MENU,
1679 type == WebView.HitTestResult.GEO_TYPE);
1680 menu.setGroupVisible(R.id.IMAGE_MENU,
1681 type == WebView.HitTestResult.IMAGE_TYPE
1682 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1683 menu.setGroupVisible(R.id.ANCHOR_MENU,
1684 type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1685 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1686
1687 // Setup custom handling depending on the type
1688 switch (type) {
1689 case WebView.HitTestResult.PHONE_TYPE:
1690 menu.setHeaderTitle(Uri.decode(extra));
1691 menu.findItem(R.id.dial_context_menu_id).setIntent(
1692 new Intent(Intent.ACTION_VIEW, Uri
1693 .parse(WebView.SCHEME_TEL + extra)));
1694 Intent addIntent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
1695 addIntent.putExtra(Insert.PHONE, Uri.decode(extra));
Cary Clark5e335a32009-09-22 14:53:11 -04001696 addIntent.setType(ContactsContract.Contacts.CONTENT_ITEM_TYPE);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001697 menu.findItem(R.id.add_contact_context_menu_id).setIntent(
1698 addIntent);
1699 menu.findItem(R.id.copy_phone_context_menu_id).setOnMenuItemClickListener(
1700 new Copy(extra));
1701 break;
1702
1703 case WebView.HitTestResult.EMAIL_TYPE:
1704 menu.setHeaderTitle(extra);
1705 menu.findItem(R.id.email_context_menu_id).setIntent(
1706 new Intent(Intent.ACTION_VIEW, Uri
1707 .parse(WebView.SCHEME_MAILTO + extra)));
1708 menu.findItem(R.id.copy_mail_context_menu_id).setOnMenuItemClickListener(
1709 new Copy(extra));
1710 break;
1711
1712 case WebView.HitTestResult.GEO_TYPE:
1713 menu.setHeaderTitle(extra);
1714 menu.findItem(R.id.map_context_menu_id).setIntent(
1715 new Intent(Intent.ACTION_VIEW, Uri
1716 .parse(WebView.SCHEME_GEO
1717 + URLEncoder.encode(extra))));
1718 menu.findItem(R.id.copy_geo_context_menu_id).setOnMenuItemClickListener(
1719 new Copy(extra));
1720 break;
1721
1722 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1723 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
1724 TextView titleView = (TextView) LayoutInflater.from(this)
1725 .inflate(android.R.layout.browser_link_context_header,
1726 null);
1727 titleView.setText(extra);
1728 menu.setHeaderView(titleView);
1729 // decide whether to show the open link in new tab option
Leon Scroggins III9e997c72010-05-26 13:25:16 -04001730 boolean showNewTab = mTabControl.canCreateNewTab();
1731 MenuItem newTabItem
1732 = menu.findItem(R.id.open_newtab_context_menu_id);
1733 newTabItem.setVisible(showNewTab);
1734 if (showNewTab) {
1735 newTabItem.setOnMenuItemClickListener(
1736 new MenuItem.OnMenuItemClickListener() {
1737 public boolean onMenuItemClick(MenuItem item) {
1738 final Tab parent = mTabControl.getCurrentTab();
Michael Kolb68792c82010-08-09 16:39:18 -07001739 final Tab newTab = openTab(extra, false);
Leon Scroggins III9e997c72010-05-26 13:25:16 -04001740 if (newTab != parent) {
1741 parent.addChildTab(newTab);
1742 }
1743 return true;
1744 }
1745 });
1746 }
Ben Murdochde353622009-10-12 10:29:00 +01001747 menu.findItem(R.id.bookmark_context_menu_id).setVisible(
1748 Bookmarks.urlHasAcceptableScheme(extra));
The Android Open Source Project0c908882009-03-03 19:32:16 -08001749 PackageManager pm = getPackageManager();
1750 Intent send = new Intent(Intent.ACTION_SEND);
1751 send.setType("text/plain");
1752 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1753 menu.findItem(R.id.share_link_context_menu_id).setVisible(ri != null);
1754 if (type == WebView.HitTestResult.SRC_ANCHOR_TYPE) {
1755 break;
1756 }
1757 // otherwise fall through to handle image part
1758 case WebView.HitTestResult.IMAGE_TYPE:
1759 if (type == WebView.HitTestResult.IMAGE_TYPE) {
1760 menu.setHeaderTitle(extra);
1761 }
1762 menu.findItem(R.id.view_image_context_menu_id).setIntent(
1763 new Intent(Intent.ACTION_VIEW, Uri.parse(extra)));
1764 menu.findItem(R.id.download_context_menu_id).
1765 setOnMenuItemClickListener(new Download(extra));
Ben Murdoch4f75ba22009-10-27 11:48:28 +00001766 menu.findItem(R.id.set_wallpaper_context_menu_id).
1767 setOnMenuItemClickListener(new SetAsWallpaper(extra));
The Android Open Source Project0c908882009-03-03 19:32:16 -08001768 break;
1769
1770 default:
1771 Log.w(LOGTAG, "We should not get here.");
1772 break;
1773 }
Leon Scrogginsb2b19f52009-10-09 16:10:00 -04001774 hideFakeTitleBar();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001775 }
1776
The Android Open Source Project0c908882009-03-03 19:32:16 -08001777 // Attach the given tab to the content view.
Grace Klobac928c302009-09-17 11:51:21 -07001778 // this should only be called for the current tab.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001779 private void attachTabToContentView(Tab t) {
Steve Block2bc69912009-07-30 14:45:13 +01001780 // Attach the container that contains the main WebView and any other UI
1781 // associated with the tab.
Patrick Scottd0119532009-09-17 08:00:31 -04001782 t.attachTabToContentView(mContentView);
Ben Murdochbff2d602009-07-01 20:19:05 +01001783
1784 if (mShouldShowErrorConsole) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001785 ErrorConsoleView errorConsole = t.getErrorConsole(true);
Ben Murdochbff2d602009-07-01 20:19:05 +01001786 if (errorConsole.numberOfErrors() == 0) {
1787 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
1788 } else {
1789 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
1790 }
1791
1792 mErrorConsoleContainer.addView(errorConsole,
Romain Guy15b8ec62010-01-08 15:06:43 -08001793 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
Ben Murdochbff2d602009-07-01 20:19:05 +01001794 ViewGroup.LayoutParams.WRAP_CONTENT));
1795 }
1796
Michael Kolba2b2ba82010-08-04 17:54:03 -07001797 WebView view = t.getWebView();
1798 view.setEmbeddedTitleBar(mTitleBar);
Leon Scroggins58d56c62010-01-28 15:12:40 -05001799 if (t.isInVoiceSearchMode()) {
1800 showVoiceTitleBar(t.getVoiceDisplayTitle());
1801 } else {
1802 revertVoiceTitleBar();
1803 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001804 // Request focus on the top window.
1805 t.getTopWindow().requestFocus();
Michael Kolba2b2ba82010-08-04 17:54:03 -07001806 if (mTabControl.getTabChangeListener() != null) {
1807 mTabControl.getTabChangeListener().onCurrentTab(t);
1808 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001809 }
1810
1811 // Attach a sub window to the main WebView of the given tab.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001812 void attachSubWindow(Tab t) {
Patrick Scottd0119532009-09-17 08:00:31 -04001813 t.attachSubWindow(mContentView);
1814 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001815 }
1816
1817 // Remove the given tab from the content view.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001818 private void removeTabFromContentView(Tab t) {
Steve Block2bc69912009-07-30 14:45:13 +01001819 // Remove the container that contains the main WebView.
Patrick Scottd0119532009-09-17 08:00:31 -04001820 t.removeTabFromContentView(mContentView);
Ben Murdochbff2d602009-07-01 20:19:05 +01001821
Grace Kloba22ac16e2009-10-07 18:00:23 -07001822 ErrorConsoleView errorConsole = t.getErrorConsole(false);
1823 if (errorConsole != null) {
1824 mErrorConsoleContainer.removeView(errorConsole);
Ben Murdochbff2d602009-07-01 20:19:05 +01001825 }
1826
Michael Kolba2b2ba82010-08-04 17:54:03 -07001827 WebView view = t.getWebView();
1828 if (view != null) {
1829 view.setEmbeddedTitleBar(null);
Leon Scrogginsbb85b902009-09-14 19:27:20 -04001830 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001831 }
1832
1833 // Remove the sub window if it exists. Also called by TabControl when the
1834 // user clicks the 'X' to dismiss a sub window.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001835 /* package */ void dismissSubWindow(Tab t) {
Patrick Scottd0119532009-09-17 08:00:31 -04001836 t.removeSubWindow(mContentView);
Grace Kloba22ac16e2009-10-07 18:00:23 -07001837 // dismiss the subwindow. This will destroy the WebView.
1838 t.dismissSubWindow();
Patrick Scottd0119532009-09-17 08:00:31 -04001839 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001840 }
1841
Leon Scroggins1f005d32009-08-10 17:36:42 -04001842 // A wrapper function of {@link #openTabAndShow(UrlData, boolean, String)}
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07001843 // that accepts url as string.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001844 private Tab openTabAndShow(String url, boolean closeOnExit, String appId) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001845 return openTabAndShow(new UrlData(url), closeOnExit, appId);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001846 }
1847
1848 // This method does a ton of stuff. It will attempt to create a new tab
1849 // if we haven't reached MAX_TABS. Otherwise it uses the current tab. If
Leon Scroggins1f005d32009-08-10 17:36:42 -04001850 // url isn't null, it will load the given url.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001851 /* package */Tab openTabAndShow(UrlData urlData, boolean closeOnExit,
1852 String appId) {
1853 final Tab currentTab = mTabControl.getCurrentTab();
1854 if (mTabControl.canCreateNewTab()) {
1855 final Tab tab = mTabControl.createNewTab(closeOnExit, appId,
Elliott Slaughterf0f03952010-07-14 18:10:36 -07001856 urlData.mUrl, false);
Leon Scroggins1f005d32009-08-10 17:36:42 -04001857 WebView webview = tab.getWebView();
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001858 // If the last tab was removed from the active tabs page, currentTab
1859 // will be null.
1860 if (currentTab != null) {
1861 removeTabFromContentView(currentTab);
1862 }
Patrick Scott8bbd69f2009-08-14 13:35:53 -04001863 // We must set the new tab as the current tab to reflect the old
1864 // animation behavior.
1865 mTabControl.setCurrentTab(tab);
Grace Klobaeb6eef42009-09-15 17:56:32 -07001866 attachTabToContentView(tab);
Leon Scroggins160a7e72009-08-14 18:28:01 -04001867 if (!urlData.isEmpty()) {
Patrick Scott9d53da02010-02-19 10:19:01 -05001868 loadUrlDataIn(tab, urlData);
Leon Scroggins1f005d32009-08-10 17:36:42 -04001869 }
1870 return tab;
1871 } else {
1872 // Get rid of the subwindow if it exists
1873 dismissSubWindow(currentTab);
1874 if (!urlData.isEmpty()) {
1875 // Load the given url.
Patrick Scott9d53da02010-02-19 10:19:01 -05001876 loadUrlDataIn(currentTab, urlData);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001877 }
Leon Scroggins58d56c62010-01-28 15:12:40 -05001878 return currentTab;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001879 }
1880 }
1881
Michael Kolb68792c82010-08-09 16:39:18 -07001882 private Tab openTab(String url, boolean forceForeground) {
1883 if (mSettings.openInBackground() && !forceForeground) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001884 Tab t = mTabControl.createNewTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001885 if (t != null) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001886 WebView view = t.getWebView();
Leon Scroggins92472e82010-02-17 16:32:28 -05001887 loadUrl(view, url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001888 }
Grace Klobac9181842009-04-14 08:53:22 -07001889 return t;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001890 } else {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001891 return openTabAndShow(url, false, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001892 }
1893 }
1894
Elliott Slaughterf0f03952010-07-14 18:10:36 -07001895 /* package */ Tab openIncognitoTab() {
1896 if (mTabControl.canCreateNewTab()) {
1897 Tab currentTab = mTabControl.getCurrentTab();
1898 Tab tab = mTabControl.createNewTab(false, null, null, true);
1899 if (currentTab != null) {
1900 removeTabFromContentView(currentTab);
1901 }
1902 mTabControl.setCurrentTab(tab);
1903 attachTabToContentView(tab);
1904 return tab;
1905 }
1906 return null;
1907 }
1908
The Android Open Source Project0c908882009-03-03 19:32:16 -08001909 private class Copy implements OnMenuItemClickListener {
1910 private CharSequence mText;
1911
1912 public boolean onMenuItemClick(MenuItem item) {
1913 copy(mText);
1914 return true;
1915 }
1916
1917 public Copy(CharSequence toCopy) {
1918 mText = toCopy;
1919 }
1920 }
1921
1922 private class Download implements OnMenuItemClickListener {
1923 private String mText;
1924
1925 public boolean onMenuItemClick(MenuItem item) {
1926 onDownloadStartNoStream(mText, null, null, null, -1);
1927 return true;
1928 }
1929
1930 public Download(String toDownload) {
1931 mText = toDownload;
1932 }
1933 }
1934
Ben Murdoch4f75ba22009-10-27 11:48:28 +00001935 private class SetAsWallpaper extends Thread implements
1936 OnMenuItemClickListener, DialogInterface.OnCancelListener {
1937 private URL mUrl;
1938 private ProgressDialog mWallpaperProgress;
1939 private boolean mCanceled = false;
1940
1941 public SetAsWallpaper(String url) {
1942 try {
1943 mUrl = new URL(url);
1944 } catch (MalformedURLException e) {
1945 mUrl = null;
1946 }
1947 }
1948
1949 public void onCancel(DialogInterface dialog) {
1950 mCanceled = true;
1951 }
1952
1953 public boolean onMenuItemClick(MenuItem item) {
1954 if (mUrl != null) {
1955 // The user may have tried to set a image with a large file size as their
1956 // background so it may take a few moments to perform the operation. Display
1957 // a progress spinner while it is working.
1958 mWallpaperProgress = new ProgressDialog(BrowserActivity.this);
1959 mWallpaperProgress.setIndeterminate(true);
1960 mWallpaperProgress.setMessage(getText(R.string.progress_dialog_setting_wallpaper));
1961 mWallpaperProgress.setCancelable(true);
1962 mWallpaperProgress.setOnCancelListener(this);
1963 mWallpaperProgress.show();
1964 start();
1965 }
1966 return true;
1967 }
1968
Michael Kolbe0a36662010-06-29 10:37:12 -07001969 @Override
Ben Murdoch4f75ba22009-10-27 11:48:28 +00001970 public void run() {
1971 Drawable oldWallpaper = BrowserActivity.this.getWallpaper();
1972 try {
1973 // TODO: This will cause the resource to be downloaded again, when we
1974 // should in most cases be able to grab it from the cache. To fix this
1975 // we should query WebCore to see if we can access a cached version and
1976 // instead open an input stream on that. This pattern could also be used
1977 // in the download manager where the same problem exists.
1978 InputStream inputstream = mUrl.openStream();
1979 if (inputstream != null) {
1980 setWallpaper(inputstream);
1981 }
1982 } catch (IOException e) {
1983 Log.e(LOGTAG, "Unable to set new wallpaper");
1984 // Act as though the user canceled the operation so we try to
1985 // restore the old wallpaper.
1986 mCanceled = true;
1987 }
1988
1989 if (mCanceled) {
1990 // Restore the old wallpaper if the user cancelled whilst we were setting
1991 // the new wallpaper.
1992 int width = oldWallpaper.getIntrinsicWidth();
1993 int height = oldWallpaper.getIntrinsicHeight();
1994 Bitmap bm = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
1995 Canvas canvas = new Canvas(bm);
1996 oldWallpaper.setBounds(0, 0, width, height);
1997 oldWallpaper.draw(canvas);
1998 try {
1999 setWallpaper(bm);
2000 } catch (IOException e) {
2001 Log.e(LOGTAG, "Unable to restore old wallpaper.");
2002 }
2003 mCanceled = false;
2004 }
2005
2006 if (mWallpaperProgress.isShowing()) {
2007 mWallpaperProgress.dismiss();
2008 }
2009 }
2010 }
2011
The Android Open Source Project0c908882009-03-03 19:32:16 -08002012 private void copy(CharSequence text) {
Dianne Hackborn80f32622010-08-05 14:17:53 -07002013 ClipboardManager cm = (ClipboardManager)getSystemService(Context.CLIPBOARD_SERVICE);
2014 cm.setText(text);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002015 }
2016
2017 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08002018 * Resets the browser title-view to whatever it must be
2019 * (for example, if we had a loading error)
2020 * When we have a new page, we call resetTitle, when we
2021 * have to reset the titlebar to whatever it used to be
2022 * (for example, if the user chose to stop loading), we
2023 * call resetTitleAndRevertLockIcon.
2024 */
2025 /* package */ void resetTitleAndRevertLockIcon() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002026 mTabControl.getCurrentTab().revertLockIcon();
2027 updateLockIconToLatest();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002028 resetTitleIconAndProgress();
2029 }
2030
2031 /**
2032 * Reset the title, favicon, and progress.
2033 */
2034 private void resetTitleIconAndProgress() {
2035 WebView current = mTabControl.getCurrentWebView();
2036 if (current == null) {
2037 return;
2038 }
2039 resetTitleAndIcon(current);
2040 int progress = current.getProgress();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002041 current.getWebChromeClient().onProgressChanged(current, progress);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002042 }
2043
2044 // Reset the title and the icon based on the given item.
2045 private void resetTitleAndIcon(WebView view) {
2046 WebHistoryItem item = view.copyBackForwardList().getCurrentItem();
2047 if (item != null) {
Leon Scroggins68579392009-09-15 15:31:54 -04002048 setUrlTitle(item.getUrl(), item.getTitle());
The Android Open Source Project0c908882009-03-03 19:32:16 -08002049 setFavicon(item.getFavicon());
2050 } else {
Leon Scroggins68579392009-09-15 15:31:54 -04002051 setUrlTitle(null, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002052 setFavicon(null);
2053 }
2054 }
2055
2056 /**
2057 * Sets a title composed of the URL and the title string.
2058 * @param url The URL of the site being loaded.
2059 * @param title The title of the site being loaded.
2060 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07002061 void setUrlTitle(String url, String title) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002062 mUrl = url;
2063 mTitle = title;
2064
Leon Scroggins58d56c62010-01-28 15:12:40 -05002065 // If we are in voice search mode, the title has already been set.
2066 if (mTabControl.getCurrentTab().isInVoiceSearchMode()) return;
2067 mTitleBar.setDisplayTitle(url);
Michael Kolba2b2ba82010-08-04 17:54:03 -07002068 mFakeTitleBar.setDisplayTitle(url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002069 }
2070
2071 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08002072 * @param url The URL to build a title version of the URL from.
2073 * @return The title version of the URL or null if fails.
2074 * The title version of the URL can be either the URL hostname,
2075 * or the hostname with an "https://" prefix (for secure URLs),
2076 * or an empty string if, for example, the URL in question is a
2077 * file:// URL with no hostname.
2078 */
Leon Scroggins32e14a62009-06-11 10:26:34 -04002079 /* package */ static String buildTitleUrl(String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002080 String titleUrl = null;
2081
2082 if (url != null) {
2083 try {
2084 // parse the url string
2085 URL urlObj = new URL(url);
2086 if (urlObj != null) {
2087 titleUrl = "";
2088
2089 String protocol = urlObj.getProtocol();
2090 String host = urlObj.getHost();
2091
2092 if (host != null && 0 < host.length()) {
2093 titleUrl = host;
2094 if (protocol != null) {
2095 // if a secure site, add an "https://" prefix!
2096 if (protocol.equalsIgnoreCase("https")) {
2097 titleUrl = protocol + "://" + host;
2098 }
2099 }
2100 }
2101 }
2102 } catch (MalformedURLException e) {}
2103 }
2104
2105 return titleUrl;
2106 }
2107
2108 // Set the favicon in the title bar.
Grace Kloba22ac16e2009-10-07 18:00:23 -07002109 void setFavicon(Bitmap icon) {
Leon Scroggins68579392009-09-15 15:31:54 -04002110 mTitleBar.setFavicon(icon);
Michael Kolba2b2ba82010-08-04 17:54:03 -07002111 mFakeTitleBar.setFavicon(icon);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002112 }
2113
2114 /**
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002115 * Close the tab, remove its associated title bar, and adjust mTabControl's
2116 * current tab to a valid value.
Leon Scroggins1f005d32009-08-10 17:36:42 -04002117 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07002118 /* package */ void closeTab(Tab t) {
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002119 int currentIndex = mTabControl.getCurrentIndex();
2120 int removeIndex = mTabControl.getTabIndex(t);
Leon Scroggins1f005d32009-08-10 17:36:42 -04002121 mTabControl.removeTab(t);
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002122 if (currentIndex >= removeIndex && currentIndex != 0) {
2123 currentIndex--;
2124 }
2125 mTabControl.setCurrentTab(mTabControl.getTab(currentIndex));
Andrei Popescua5bf1de2009-09-23 16:39:23 +01002126 resetTitleIconAndProgress();
Leon Scroggins654899b2010-06-25 16:25:23 -04002127 updateLockIconToLatest();
Elliott Slaughtere440a882010-08-20 13:54:45 -07002128
2129 if (!mTabControl.hasAnyOpenIncognitoTabs()) {
2130 WebView.cleanupPrivateBrowsingFiles(this);
2131 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002132 }
2133
Leon Scrogginsdcc5eeb2010-02-23 17:26:37 -05002134 /* package */ void goBackOnePageOrQuit() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002135 Tab current = mTabControl.getCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002136 if (current == null) {
2137 /*
2138 * Instead of finishing the activity, simply push this to the back
2139 * of the stack and let ActivityManager to choose the foreground
2140 * activity. As BrowserActivity is singleTask, it will be always the
2141 * root of the task. So we can use either true or false for
2142 * moveTaskToBack().
2143 */
2144 moveTaskToBack(true);
Grace Kloba00d85e72009-09-23 18:50:05 -07002145 return;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002146 }
2147 WebView w = current.getWebView();
2148 if (w.canGoBack()) {
2149 w.goBack();
2150 } else {
2151 // Check to see if we are closing a window that was created by
2152 // another window. If so, we switch back to that window.
Grace Kloba22ac16e2009-10-07 18:00:23 -07002153 Tab parent = current.getParentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002154 if (parent != null) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04002155 switchToTab(mTabControl.getTabIndex(parent));
2156 // Now we close the other tab
2157 closeTab(current);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002158 } else {
2159 if (current.closeOnExit()) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002160 // force the tab's inLoad() to be false as we are going to
2161 // either finish the activity or remove the tab. This will
2162 // ensure pauseWebViewTimers() taking action.
2163 mTabControl.getCurrentTab().clearInLoad();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002164 if (mTabControl.getTabCount() == 1) {
2165 finish();
2166 return;
2167 }
Mike Reed7bfa63b2009-05-28 11:08:32 -04002168 // call pauseWebViewTimers() now, we won't be able to call
2169 // it in onPause() as the WebView won't be valid.
Grace Klobaec1b5ad2009-08-18 08:42:32 -07002170 // Temporarily change mActivityInPause to be true as
2171 // pauseWebViewTimers() will do nothing if mActivityInPause
2172 // is false.
Grace Kloba918e1d72009-08-13 14:55:06 -07002173 boolean savedState = mActivityInPause;
2174 if (savedState) {
Grace Klobaec1b5ad2009-08-18 08:42:32 -07002175 Log.e(LOGTAG, "BrowserActivity is already paused "
2176 + "while handing goBackOnePageOrQuit.");
Grace Kloba918e1d72009-08-13 14:55:06 -07002177 }
2178 mActivityInPause = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -04002179 pauseWebViewTimers();
Grace Kloba918e1d72009-08-13 14:55:06 -07002180 mActivityInPause = savedState;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002181 removeTabFromContentView(current);
2182 mTabControl.removeTab(current);
2183 }
2184 /*
2185 * Instead of finishing the activity, simply push this to the back
2186 * of the stack and let ActivityManager to choose the foreground
2187 * activity. As BrowserActivity is singleTask, it will be always the
2188 * root of the task. So we can use either true or false for
2189 * moveTaskToBack().
2190 */
2191 moveTaskToBack(true);
2192 }
2193 }
2194 }
2195
Grace Kloba22ac16e2009-10-07 18:00:23 -07002196 boolean isMenuDown() {
2197 return mMenuIsDown;
2198 }
2199
Grace Kloba5942df02009-09-18 11:48:29 -07002200 @Override
2201 public boolean onKeyDown(int keyCode, KeyEvent event) {
Leon Scrogginsf65b50d2009-12-08 10:44:28 -05002202 // Even if MENU is already held down, we need to call to super to open
2203 // the IME on long press.
2204 if (KeyEvent.KEYCODE_MENU == keyCode) {
2205 mMenuIsDown = true;
2206 return super.onKeyDown(keyCode, event);
2207 }
Grace Kloba5942df02009-09-18 11:48:29 -07002208 // The default key mode is DEFAULT_KEYS_SEARCH_LOCAL. As the MENU is
2209 // still down, we don't want to trigger the search. Pretend to consume
2210 // the key and do nothing.
2211 if (mMenuIsDown) return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002212
Grace Kloba5942df02009-09-18 11:48:29 -07002213 switch(keyCode) {
Grace Kloba5942df02009-09-18 11:48:29 -07002214 case KeyEvent.KEYCODE_SPACE:
Grace Klobada0fe552009-09-22 18:17:24 -07002215 // WebView/WebTextView handle the keys in the KeyDown. As
2216 // the Activity's shortcut keys are only handled when WebView
2217 // doesn't, have to do it in onKeyDown instead of onKeyUp.
2218 if (event.isShiftPressed()) {
2219 getTopWindow().pageUp(false);
2220 } else {
2221 getTopWindow().pageDown(false);
2222 }
Grace Kloba5942df02009-09-18 11:48:29 -07002223 return true;
2224 case KeyEvent.KEYCODE_BACK:
2225 if (event.getRepeatCount() == 0) {
2226 event.startTracking();
2227 return true;
2228 } else if (mCustomView == null && mActiveTabsPage == null
2229 && event.isLongPress()) {
Michael Kolb68792c82010-08-09 16:39:18 -07002230 bookmarksOrHistoryPicker(true, false);
Grace Kloba5942df02009-09-18 11:48:29 -07002231 return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002232 }
Grace Kloba5942df02009-09-18 11:48:29 -07002233 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002234 }
Grace Kloba5942df02009-09-18 11:48:29 -07002235 return super.onKeyDown(keyCode, event);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002236 }
2237
Grace Kloba5942df02009-09-18 11:48:29 -07002238 @Override
2239 public boolean onKeyUp(int keyCode, KeyEvent event) {
2240 switch(keyCode) {
2241 case KeyEvent.KEYCODE_MENU:
2242 mMenuIsDown = false;
2243 break;
Grace Kloba5942df02009-09-18 11:48:29 -07002244 case KeyEvent.KEYCODE_BACK:
2245 if (event.isTracking() && !event.isCanceled()) {
2246 if (mCustomView != null) {
2247 // if a custom view is showing, hide it
Grace Kloba22ac16e2009-10-07 18:00:23 -07002248 mTabControl.getCurrentWebView().getWebChromeClient()
2249 .onHideCustomView();
Grace Kloba5942df02009-09-18 11:48:29 -07002250 } else if (mActiveTabsPage != null) {
2251 // if tab page is showing, hide it
2252 removeActiveTabPage(true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002253 } else {
Grace Kloba5942df02009-09-18 11:48:29 -07002254 WebView subwindow = mTabControl.getCurrentSubWindow();
2255 if (subwindow != null) {
2256 if (subwindow.canGoBack()) {
2257 subwindow.goBack();
2258 } else {
2259 dismissSubWindow(mTabControl.getCurrentTab());
2260 }
2261 } else {
2262 goBackOnePageOrQuit();
2263 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002264 }
Grace Kloba5942df02009-09-18 11:48:29 -07002265 return true;
2266 }
2267 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002268 }
Grace Kloba5942df02009-09-18 11:48:29 -07002269 return super.onKeyUp(keyCode, event);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002270 }
2271
Leon Scroggins68579392009-09-15 15:31:54 -04002272 /* package */ void stopLoading() {
Ben Murdochb7cc8b42009-09-28 10:59:09 +01002273 mDidStopLoad = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002274 resetTitleAndRevertLockIcon();
2275 WebView w = getTopWindow();
2276 w.stopLoading();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002277 // FIXME: before refactor, it is using mWebViewClient. So I keep the
2278 // same logic here. But for subwindow case, should we call into the main
2279 // WebView's onPageFinished as we never call its onPageStarted and if
2280 // the page finishes itself, we don't call onPageFinished.
2281 mTabControl.getCurrentWebView().getWebViewClient().onPageFinished(w,
2282 w.getUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08002283
2284 cancelStopToast();
2285 mStopToast = Toast
2286 .makeText(this, R.string.stopping, Toast.LENGTH_SHORT);
2287 mStopToast.show();
2288 }
2289
Grace Kloba22ac16e2009-10-07 18:00:23 -07002290 boolean didUserStopLoading() {
2291 return mDidStopLoad;
2292 }
2293
The Android Open Source Project0c908882009-03-03 19:32:16 -08002294 private void cancelStopToast() {
2295 if (mStopToast != null) {
2296 mStopToast.cancel();
2297 mStopToast = null;
2298 }
2299 }
2300
Grace Kloba22ac16e2009-10-07 18:00:23 -07002301 // called by a UI or non-UI thread to post the message
2302 public void postMessage(int what, int arg1, int arg2, Object obj,
2303 long delayMillis) {
2304 mHandler.sendMessageDelayed(mHandler.obtainMessage(what, arg1, arg2,
2305 obj), delayMillis);
2306 }
2307
2308 // called by a UI or non-UI thread to remove the message
2309 void removeMessages(int what, Object object) {
2310 mHandler.removeMessages(what, object);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002311 }
2312
2313 // public message ids
2314 public final static int LOAD_URL = 1001;
2315 public final static int STOP_LOAD = 1002;
2316
2317 // Message Ids
2318 private static final int FOCUS_NODE_HREF = 102;
Grace Kloba92c18a52009-07-31 23:48:32 -07002319 private static final int RELEASE_WAKELOCK = 107;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002320
Grace Kloba22ac16e2009-10-07 18:00:23 -07002321 static final int UPDATE_BOOKMARK_THUMBNAIL = 108;
Ben Murdoch2694e232009-09-29 09:41:11 +01002322
Ben Murdocheecb4e62010-07-06 16:30:38 +01002323 private static final int TOUCH_ICON_DOWNLOADED = 109;
2324
Michael Kolb300b7f02010-08-25 13:47:24 -07002325 private static final int OPEN_BOOKMARKS = 201;
2326
The Android Open Source Project0c908882009-03-03 19:32:16 -08002327 // Private handler for handling javascript and saving passwords
2328 private Handler mHandler = new Handler() {
2329
Michael Kolbe0a36662010-06-29 10:37:12 -07002330 @Override
The Android Open Source Project0c908882009-03-03 19:32:16 -08002331 public void handleMessage(Message msg) {
2332 switch (msg.what) {
Michael Kolb300b7f02010-08-25 13:47:24 -07002333 case OPEN_BOOKMARKS:
2334 bookmarksOrHistoryPicker(false, false);
2335 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002336 case FOCUS_NODE_HREF:
Ben Murdoch2694e232009-09-29 09:41:11 +01002337 {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002338 String url = (String) msg.getData().get("url");
Ben Murdoch90d088c2009-11-17 18:14:04 +00002339 String title = (String) msg.getData().get("title");
The Android Open Source Project0c908882009-03-03 19:32:16 -08002340 if (url == null || url.length() == 0) {
2341 break;
2342 }
2343 HashMap focusNodeMap = (HashMap) msg.obj;
2344 WebView view = (WebView) focusNodeMap.get("webview");
2345 // Only apply the action if the top window did not change.
2346 if (getTopWindow() != view) {
2347 break;
2348 }
2349 switch (msg.arg1) {
2350 case R.id.open_context_menu_id:
2351 case R.id.view_image_context_menu_id:
Leon Scroggins92472e82010-02-17 16:32:28 -05002352 loadUrlFromContext(getTopWindow(), url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002353 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002354 case R.id.bookmark_context_menu_id:
2355 Intent intent = new Intent(BrowserActivity.this,
2356 AddBookmarkPage.class);
2357 intent.putExtra("url", url);
Ben Murdoch90d088c2009-11-17 18:14:04 +00002358 intent.putExtra("title", title);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002359 startActivity(intent);
2360 break;
2361 case R.id.share_link_context_menu_id:
Leon Scroggins3e204452010-05-10 11:06:03 -04002362 sharePage(BrowserActivity.this, title, url, null,
Leon Scroggins96afcb12009-12-10 12:35:56 -05002363 null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002364 break;
2365 case R.id.copy_link_context_menu_id:
2366 copy(url);
2367 break;
2368 case R.id.save_link_context_menu_id:
2369 case R.id.download_context_menu_id:
2370 onDownloadStartNoStream(url, null, null, null, -1);
2371 break;
2372 }
2373 break;
Ben Murdoch2694e232009-09-29 09:41:11 +01002374 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002375
2376 case LOAD_URL:
Leon Scroggins92472e82010-02-17 16:32:28 -05002377 loadUrlFromContext(getTopWindow(), (String) msg.obj);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002378 break;
2379
2380 case STOP_LOAD:
2381 stopLoading();
2382 break;
2383
The Android Open Source Project0c908882009-03-03 19:32:16 -08002384 case RELEASE_WAKELOCK:
2385 if (mWakeLock.isHeld()) {
2386 mWakeLock.release();
Grace Kloba5d0e02e2009-10-05 15:15:36 -07002387 // if we reach here, Browser should be still in the
2388 // background loading after WAKELOCK_TIMEOUT (5-min).
2389 // To avoid burning the battery, stop loading.
2390 mTabControl.stopAllLoading();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002391 }
2392 break;
Ben Murdoch2694e232009-09-29 09:41:11 +01002393
2394 case UPDATE_BOOKMARK_THUMBNAIL:
2395 WebView view = (WebView) msg.obj;
2396 if (view != null) {
2397 updateScreenshot(view);
2398 }
2399 break;
Ben Murdocheecb4e62010-07-06 16:30:38 +01002400
2401 case TOUCH_ICON_DOWNLOADED:
2402 Bundle b = msg.getData();
2403 showSaveToHomescreenDialog(b.getString("url"),
2404 b.getString("title"),
2405 (Bitmap) b.getParcelable("touchIcon"),
2406 (Bitmap) b.getParcelable("favicon"));
2407 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002408 }
2409 }
2410 };
2411
Leon Scroggins96afcb12009-12-10 12:35:56 -05002412 /**
2413 * Share a page, providing the title, url, favicon, and a screenshot. Uses
2414 * an {@link Intent} to launch the Activity chooser.
2415 * @param c Context used to launch a new Activity.
2416 * @param title Title of the page. Stored in the Intent with
Paul Westbrook03e6d392010-02-12 10:33:29 -08002417 * {@link Intent#EXTRA_SUBJECT}
Leon Scroggins96afcb12009-12-10 12:35:56 -05002418 * @param url URL of the page. Stored in the Intent with
2419 * {@link Intent#EXTRA_TEXT}
2420 * @param favicon Bitmap of the favicon for the page. Stored in the Intent
2421 * with {@link Browser#EXTRA_SHARE_FAVICON}
2422 * @param screenshot Bitmap of a screenshot of the page. Stored in the
2423 * Intent with {@link Browser#EXTRA_SHARE_SCREENSHOT}
2424 */
2425 public static final void sharePage(Context c, String title, String url,
2426 Bitmap favicon, Bitmap screenshot) {
2427 Intent send = new Intent(Intent.ACTION_SEND);
2428 send.setType("text/plain");
2429 send.putExtra(Intent.EXTRA_TEXT, url);
Paul Westbrook03e6d392010-02-12 10:33:29 -08002430 send.putExtra(Intent.EXTRA_SUBJECT, title);
Leon Scroggins96afcb12009-12-10 12:35:56 -05002431 send.putExtra(Browser.EXTRA_SHARE_FAVICON, favicon);
2432 send.putExtra(Browser.EXTRA_SHARE_SCREENSHOT, screenshot);
2433 try {
2434 c.startActivity(Intent.createChooser(send, c.getString(
2435 R.string.choosertitle_sharevia)));
2436 } catch(android.content.ActivityNotFoundException ex) {
2437 // if no app handles it, do nothing
2438 }
2439 }
2440
Leon Scroggins89c6d362009-07-15 16:54:37 -04002441 private void updateScreenshot(WebView view) {
2442 // If this is a bookmarked site, add a screenshot to the database.
2443 // FIXME: When should we update? Every time?
2444 // FIXME: Would like to make sure there is actually something to
2445 // draw, but the API for that (WebViewCore.pictureReady()) is not
2446 // currently accessible here.
Ben Murdochaac7aa62009-09-17 16:57:40 +01002447
Ben Murdoch87cc65d2010-06-29 20:34:10 +01002448 final Bitmap bm = createScreenshot(view, getDesiredThumbnailWidth(this),
2449 getDesiredThumbnailHeight(this));
Patrick Scottcb192b52010-04-14 14:38:55 -04002450 if (bm == null) {
2451 return;
Leon Scroggins89c6d362009-07-15 16:54:37 -04002452 }
Patrick Scottcb192b52010-04-14 14:38:55 -04002453
2454 final ContentResolver cr = getContentResolver();
2455 final String url = view.getUrl();
2456 final String originalUrl = view.getOriginalUrl();
2457
2458 new AsyncTask<Void, Void, Void>() {
2459 @Override
2460 protected Void doInBackground(Void... unused) {
Jeff Hamilton1a805652010-09-07 12:36:30 -07002461 Cursor cursor = null;
Patrick Scottcb192b52010-04-14 14:38:55 -04002462 try {
Jeff Hamilton1a805652010-09-07 12:36:30 -07002463 cursor = Bookmarks.queryCombinedForUrl(cr, originalUrl, url);
2464 if (cursor != null && cursor.moveToFirst()) {
2465 final ByteArrayOutputStream os = new ByteArrayOutputStream();
2466 bm.compress(Bitmap.CompressFormat.PNG, 100, os);
2467
2468 ContentValues values = new ContentValues();
2469 values.put(Images.THUMBNAIL, os.toByteArray());
2470 values.put(Images.URL, cursor.getString(0));
2471
2472 do {
2473 cr.update(Images.CONTENT_URI, values, null, null);
2474 } while (cursor.moveToNext());
Patrick Scottcb192b52010-04-14 14:38:55 -04002475 }
2476 } catch (IllegalStateException e) {
2477 // Ignore
2478 } finally {
Jeff Hamilton1a805652010-09-07 12:36:30 -07002479 if (cursor != null) cursor.close();
Patrick Scottcb192b52010-04-14 14:38:55 -04002480 }
2481 return null;
2482 }
2483 }.execute();
Leon Scroggins89c6d362009-07-15 16:54:37 -04002484 }
2485
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002486 /**
Leon Scrogginsf8551612009-09-24 16:06:02 -04002487 * Return the desired width for thumbnail screenshots, which are stored in
2488 * the database, and used on the bookmarks screen.
2489 * @param context Context for finding out the density of the screen.
Jeff Hamiltonf3026372010-08-19 00:12:27 -05002490 * @return desired width for thumbnail screenshot.
Leon Scrogginsf8551612009-09-24 16:06:02 -04002491 */
2492 /* package */ static int getDesiredThumbnailWidth(Context context) {
Jeff Hamiltonf3026372010-08-19 00:12:27 -05002493 return context.getResources().getDimensionPixelOffset(R.dimen.bookmarkThumbnailWidth);
Leon Scrogginsf8551612009-09-24 16:06:02 -04002494 }
2495
2496 /**
2497 * Return the desired height for thumbnail screenshots, which are stored in
2498 * the database, and used on the bookmarks screen.
2499 * @param context Context for finding out the density of the screen.
Jeff Hamiltonf3026372010-08-19 00:12:27 -05002500 * @return desired height for thumbnail screenshot.
Leon Scrogginsf8551612009-09-24 16:06:02 -04002501 */
2502 /* package */ static int getDesiredThumbnailHeight(Context context) {
Jeff Hamiltonf3026372010-08-19 00:12:27 -05002503 return context.getResources().getDimensionPixelOffset(R.dimen.bookmarkThumbnailHeight);
Leon Scrogginsf8551612009-09-24 16:06:02 -04002504 }
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002505
Ben Murdoch87cc65d2010-06-29 20:34:10 +01002506 private Bitmap createScreenshot(WebView view, int width, int height) {
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002507 Picture thumbnail = view.capturePicture();
Leon Scroggins45800572009-09-29 16:38:47 -04002508 if (thumbnail == null) {
2509 return null;
2510 }
Ben Murdoch87cc65d2010-06-29 20:34:10 +01002511 Bitmap bm = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002512 Canvas canvas = new Canvas(bm);
2513 // May need to tweak these values to determine what is the
2514 // best scale factor
Ben Murdoch2694e232009-09-29 09:41:11 +01002515 int thumbnailWidth = thumbnail.getWidth();
Ben Murdochae59c3f2009-10-20 18:30:28 +01002516 int thumbnailHeight = thumbnail.getHeight();
2517 float scaleFactorX = 1.0f;
2518 float scaleFactorY = 1.0f;
Ben Murdoch2694e232009-09-29 09:41:11 +01002519 if (thumbnailWidth > 0) {
Ben Murdoch87cc65d2010-06-29 20:34:10 +01002520 scaleFactorX = (float) width / (float)thumbnailWidth;
Ben Murdochae59c3f2009-10-20 18:30:28 +01002521 } else {
2522 return null;
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002523 }
Ben Murdochae59c3f2009-10-20 18:30:28 +01002524
2525 if (view.getWidth() > view.getHeight() &&
2526 thumbnailHeight < view.getHeight() && thumbnailHeight > 0) {
2527 // If the device is in landscape and the page is shorter
2528 // than the height of the view, stretch the thumbnail to fill the
2529 // space.
Ben Murdoch87cc65d2010-06-29 20:34:10 +01002530 scaleFactorY = (float) height / (float)thumbnailHeight;
Ben Murdochae59c3f2009-10-20 18:30:28 +01002531 } else {
2532 // In the portrait case, this looks nice.
2533 scaleFactorY = scaleFactorX;
2534 }
2535
2536 canvas.scale(scaleFactorX, scaleFactorY);
2537
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002538 thumbnail.draw(canvas);
2539 return bm;
2540 }
2541
The Android Open Source Project0c908882009-03-03 19:32:16 -08002542 // -------------------------------------------------------------------------
Grace Kloba22ac16e2009-10-07 18:00:23 -07002543 // Helper function for WebViewClient.
The Android Open Source Project0c908882009-03-03 19:32:16 -08002544 //-------------------------------------------------------------------------
2545
2546 // Use in overrideUrlLoading
2547 /* package */ final static String SCHEME_WTAI = "wtai://wp/";
2548 /* package */ final static String SCHEME_WTAI_MC = "wtai://wp/mc;";
2549 /* package */ final static String SCHEME_WTAI_SD = "wtai://wp/sd;";
2550 /* package */ final static String SCHEME_WTAI_AP = "wtai://wp/ap;";
2551
Leon Scroggins92472e82010-02-17 16:32:28 -05002552 // Keep this initial progress in sync with initialProgressValue (* 100)
2553 // in ProgressTracker.cpp
2554 private final static int INITIAL_PROGRESS = 10;
2555
Grace Kloba22ac16e2009-10-07 18:00:23 -07002556 void onPageStarted(WebView view, String url, Bitmap favicon) {
2557 // when BrowserActivity just starts, onPageStarted may be called before
2558 // onResume as it is triggered from onCreate. Call resumeWebViewTimers
2559 // to start the timer. As we won't switch tabs while an activity is in
2560 // pause state, we can ensure calling resume and pause in pair.
2561 if (mActivityInPause) resumeWebViewTimers();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002562
Grace Kloba22ac16e2009-10-07 18:00:23 -07002563 resetLockIcon(url);
2564 setUrlTitle(url, null);
2565 setFavicon(favicon);
Leon Scroggins8cf8f682009-11-04 11:13:50 -08002566 // Show some progress so that the user knows the page is beginning to
2567 // load
Leon Scroggins92472e82010-02-17 16:32:28 -05002568 onProgressChanged(view, INITIAL_PROGRESS);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002569 mDidStopLoad = false;
Grace Kloba22ac16e2009-10-07 18:00:23 -07002570 if (!mIsNetworkUp) createAndShowNetworkDialog();
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04002571 endActionMode();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002572 if (mSettings.isTracing()) {
2573 String host;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002574 try {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002575 WebAddress uri = new WebAddress(url);
2576 host = uri.mHost;
2577 } catch (android.net.ParseException ex) {
2578 host = "browser";
The Android Open Source Project0c908882009-03-03 19:32:16 -08002579 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002580 host = host.replace('.', '_');
2581 host += ".trace";
2582 mInTrace = true;
2583 Debug.startMethodTracing(host, 20 * 1024 * 1024);
2584 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002585
Grace Kloba22ac16e2009-10-07 18:00:23 -07002586 // Performance probe
2587 if (false) {
2588 mStart = SystemClock.uptimeMillis();
2589 mProcessStart = Process.getElapsedCpuTime();
2590 long[] sysCpu = new long[7];
2591 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2592 sysCpu, null)) {
2593 mUserStart = sysCpu[0] + sysCpu[1];
2594 mSystemStart = sysCpu[2];
2595 mIdleStart = sysCpu[3];
2596 mIrqStart = sysCpu[4] + sysCpu[5] + sysCpu[6];
2597 }
2598 mUiStart = SystemClock.currentThreadTimeMillis();
2599 }
2600 }
2601
2602 void onPageFinished(WebView view, String url) {
2603 // Reset the title and icon in case we stopped a provisional load.
2604 resetTitleAndIcon(view);
2605 // Update the lock icon image only once we are done loading
2606 updateLockIconToLatest();
2607 // pause the WebView timer and release the wake lock if it is finished
2608 // while BrowserActivity is in pause state.
2609 if (mActivityInPause && pauseWebViewTimers()) {
2610 if (mWakeLock.isHeld()) {
2611 mHandler.removeMessages(RELEASE_WAKELOCK);
2612 mWakeLock.release();
2613 }
2614 }
2615
2616 // Performance probe
2617 if (false) {
2618 long[] sysCpu = new long[7];
2619 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2620 sysCpu, null)) {
2621 String uiInfo = "UI thread used "
2622 + (SystemClock.currentThreadTimeMillis() - mUiStart)
2623 + " ms";
2624 if (LOGD_ENABLED) {
2625 Log.d(LOGTAG, uiInfo);
2626 }
2627 //The string that gets written to the log
2628 String performanceString = "It took total "
2629 + (SystemClock.uptimeMillis() - mStart)
2630 + " ms clock time to load the page."
2631 + "\nbrowser process used "
2632 + (Process.getElapsedCpuTime() - mProcessStart)
2633 + " ms, user processes used "
2634 + (sysCpu[0] + sysCpu[1] - mUserStart) * 10
2635 + " ms, kernel used "
2636 + (sysCpu[2] - mSystemStart) * 10
2637 + " ms, idle took " + (sysCpu[3] - mIdleStart) * 10
2638 + " ms and irq took "
2639 + (sysCpu[4] + sysCpu[5] + sysCpu[6] - mIrqStart)
2640 * 10 + " ms, " + uiInfo;
2641 if (LOGD_ENABLED) {
2642 Log.d(LOGTAG, performanceString + "\nWebpage: " + url);
2643 }
2644 if (url != null) {
2645 // strip the url to maintain consistency
2646 String newUrl = new String(url);
2647 if (newUrl.startsWith("http://www.")) {
2648 newUrl = newUrl.substring(11);
2649 } else if (newUrl.startsWith("http://")) {
2650 newUrl = newUrl.substring(7);
2651 } else if (newUrl.startsWith("https://www.")) {
2652 newUrl = newUrl.substring(12);
2653 } else if (newUrl.startsWith("https://")) {
2654 newUrl = newUrl.substring(8);
2655 }
2656 if (LOGD_ENABLED) {
2657 Log.d(LOGTAG, newUrl + " loaded");
2658 }
Grace Kloba5b078b52009-06-24 20:23:41 -07002659 }
2660 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002661 }
Grace Kloba5b078b52009-06-24 20:23:41 -07002662
Grace Kloba22ac16e2009-10-07 18:00:23 -07002663 if (mInTrace) {
2664 mInTrace = false;
2665 Debug.stopMethodTracing();
2666 }
2667 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002668
Grace Klobae7fe26b2010-06-28 16:23:33 -07002669 private void closeEmptyChildTab() {
2670 Tab current = mTabControl.getCurrentTab();
2671 if (current != null
2672 && current.getWebView().copyBackForwardList().getSize() == 0) {
2673 Tab parent = current.getParentTab();
2674 if (parent != null) {
2675 switchToTab(mTabControl.getTabIndex(parent));
2676 closeTab(current);
2677 }
2678 }
2679 }
2680
Grace Kloba22ac16e2009-10-07 18:00:23 -07002681 boolean shouldOverrideUrlLoading(WebView view, String url) {
Jeff Hamilton47654f42010-09-07 09:57:51 -05002682 if (view.isPrivateBrowsingEnabled()) {
2683 // Don't allow urls to leave the browser app when in private browsing mode
2684 loadUrl(view, url);
2685 return true;
2686 }
2687
Grace Kloba22ac16e2009-10-07 18:00:23 -07002688 if (url.startsWith(SCHEME_WTAI)) {
2689 // wtai://wp/mc;number
2690 // number=string(phone-number)
2691 if (url.startsWith(SCHEME_WTAI_MC)) {
2692 Intent intent = new Intent(Intent.ACTION_VIEW,
2693 Uri.parse(WebView.SCHEME_TEL +
2694 url.substring(SCHEME_WTAI_MC.length())));
2695 startActivity(intent);
Grace Klobae7fe26b2010-06-28 16:23:33 -07002696 // before leaving BrowserActivity, close the empty child tab.
2697 // If a new tab is created through JavaScript open to load this
2698 // url, we would like to close it as we will load this url in a
2699 // different Activity.
2700 closeEmptyChildTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002701 return true;
2702 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002703 // wtai://wp/sd;dtmf
2704 // dtmf=string(dialstring)
2705 if (url.startsWith(SCHEME_WTAI_SD)) {
2706 // TODO: only send when there is active voice connection
2707 return false;
2708 }
2709 // wtai://wp/ap;number;name
2710 // number=string(phone-number)
2711 // name=string
2712 if (url.startsWith(SCHEME_WTAI_AP)) {
2713 // TODO
2714 return false;
2715 }
2716 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002717
Grace Kloba22ac16e2009-10-07 18:00:23 -07002718 // The "about:" schemes are internal to the browser; don't want these to
2719 // be dispatched to other apps.
2720 if (url.startsWith("about:")) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002721 return false;
2722 }
2723
Jeff Davidson43610292010-07-16 16:03:58 -07002724 // If this is a Google search, attempt to add an RLZ string (if one isn't already present).
2725 if (rlzProviderPresent()) {
2726 Uri siteUri = Uri.parse(url);
2727 if (needsRlzString(siteUri)) {
2728 String rlz = null;
2729 Cursor cur = null;
2730 try {
2731 cur = getContentResolver().query(getRlzUri(), null, null, null, null);
2732 if (cur != null && cur.moveToFirst() && !cur.isNull(0)) {
2733 url = siteUri.buildUpon()
2734 .appendQueryParameter("rlz", cur.getString(0))
2735 .build().toString();
2736 }
2737 } finally {
2738 if (cur != null) {
2739 cur.close();
2740 }
2741 }
2742 loadUrl(view, url);
2743 return true;
2744 }
2745 }
2746
Grace Kloba22ac16e2009-10-07 18:00:23 -07002747 Intent intent;
2748 // perform generic parsing of the URI to turn it into an Intent.
2749 try {
2750 intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME);
2751 } catch (URISyntaxException ex) {
2752 Log.w("Browser", "Bad URI " + url + ": " + ex.getMessage());
2753 return false;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002754 }
2755
Grace Kloba22ac16e2009-10-07 18:00:23 -07002756 // check whether the intent can be resolved. If not, we will see
2757 // whether we can download it from the Market.
2758 if (getPackageManager().resolveActivity(intent, 0) == null) {
2759 String packagename = intent.getPackage();
2760 if (packagename != null) {
2761 intent = new Intent(Intent.ACTION_VIEW, Uri
2762 .parse("market://search?q=pname:" + packagename));
2763 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2764 startActivity(intent);
Grace Klobae7fe26b2010-06-28 16:23:33 -07002765 // before leaving BrowserActivity, close the empty child tab.
2766 // If a new tab is created through JavaScript open to load this
2767 // url, we would like to close it as we will load this url in a
2768 // different Activity.
2769 closeEmptyChildTab();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002770 return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002771 } else {
2772 return false;
2773 }
2774 }
2775
Grace Kloba22ac16e2009-10-07 18:00:23 -07002776 // sanitize the Intent, ensuring web pages can not bypass browser
2777 // security (only access to BROWSABLE activities).
2778 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2779 intent.setComponent(null);
2780 try {
2781 if (startActivityIfNeeded(intent, -1)) {
Grace Klobae7fe26b2010-06-28 16:23:33 -07002782 // before leaving BrowserActivity, close the empty child tab.
2783 // If a new tab is created through JavaScript open to load this
2784 // url, we would like to close it as we will load this url in a
2785 // different Activity.
2786 closeEmptyChildTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002787 return true;
2788 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002789 } catch (ActivityNotFoundException ex) {
2790 // ignore the error. If no application can handle the URL,
2791 // eg about:blank, assume the browser can handle it.
2792 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002793
Grace Kloba22ac16e2009-10-07 18:00:23 -07002794 if (mMenuIsDown) {
Michael Kolb68792c82010-08-09 16:39:18 -07002795 openTab(url, false);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002796 closeOptionsMenu();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002797 return true;
2798 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002799 return false;
2800 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002801
Jeff Davidson43610292010-07-16 16:03:58 -07002802 // Determine whether the RLZ provider is present on the system.
2803 private boolean rlzProviderPresent() {
2804 if (mIsProviderPresent == null) {
2805 PackageManager pm = getPackageManager();
2806 mIsProviderPresent = pm.resolveContentProvider(BrowserSettings.RLZ_PROVIDER, 0) != null;
2807 }
2808 return mIsProviderPresent;
2809 }
2810
2811 // Retrieve the RLZ access point string and cache the URI used to retrieve RLZ values.
2812 private Uri getRlzUri() {
2813 if (mRlzUri == null) {
2814 String ap = getResources().getString(R.string.rlz_access_point);
2815 mRlzUri = Uri.withAppendedPath(BrowserSettings.RLZ_PROVIDER_URI, ap);
2816 }
2817 return mRlzUri;
2818 }
2819
2820 // Determine if this URI appears to be for a Google search and does not have an RLZ parameter.
2821 // Taken largely from Chrome source, src/chrome/browser/google_url_tracker.cc
2822 private static boolean needsRlzString(Uri uri) {
Bill Napierc50e71a2010-08-27 14:03:03 -07002823 String scheme = uri.getScheme();
2824 if (("http".equals(scheme) || "https".equals(scheme)) &&
2825 (uri.getQueryParameter("q") != null) && (uri.getQueryParameter("rlz") == null)) {
Jeff Davidson43610292010-07-16 16:03:58 -07002826 String host = uri.getHost();
2827 if (host == null) {
2828 return false;
2829 }
2830 String[] hostComponents = host.split("\\.");
2831
2832 if (hostComponents.length < 2) {
2833 return false;
2834 }
2835 int googleComponent = hostComponents.length - 2;
2836 String component = hostComponents[googleComponent];
2837 if (!"google".equals(component)) {
2838 if (hostComponents.length < 3 ||
2839 (!"co".equals(component) && !"com".equals(component))) {
2840 return false;
2841 }
2842 googleComponent = hostComponents.length - 3;
2843 if (!"google".equals(hostComponents[googleComponent])) {
2844 return false;
2845 }
2846 }
2847
2848 // Google corp network handling.
2849 if (googleComponent > 0 && "corp".equals(hostComponents[googleComponent - 1])) {
2850 return false;
2851 }
2852
2853 return true;
2854 }
2855 return false;
2856 }
2857
Grace Kloba22ac16e2009-10-07 18:00:23 -07002858 // -------------------------------------------------------------------------
2859 // Helper function for WebChromeClient
2860 // -------------------------------------------------------------------------
The Android Open Source Project0c908882009-03-03 19:32:16 -08002861
Grace Kloba22ac16e2009-10-07 18:00:23 -07002862 void onProgressChanged(WebView view, int newProgress) {
Michael Kolba2b2ba82010-08-04 17:54:03 -07002863
2864 // On the phone, the fake title bar will always cover up the
2865 // regular title bar (or the regular one is offscreen), so only the
2866 // fake title bar needs to change its progress
2867 mFakeTitleBar.setProgress(newProgress);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002868
Grace Kloba22ac16e2009-10-07 18:00:23 -07002869 if (newProgress == 100) {
2870 // onProgressChanged() may continue to be called after the main
2871 // frame has finished loading, as any remaining sub frames continue
2872 // to load. We'll only get called once though with newProgress as
2873 // 100 when everything is loaded. (onPageFinished is called once
2874 // when the main frame completes loading regardless of the state of
2875 // any sub frames so calls to onProgressChanges may continue after
2876 // onPageFinished has executed)
2877 if (mInLoad) {
2878 mInLoad = false;
Leon Scrogginsa27ff192009-09-14 12:58:04 -04002879 updateInLoadMenuItems();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002880 // If the options menu is open, leave the title bar
2881 if (!mOptionsMenuOpen || !mIconView) {
2882 hideFakeTitleBar();
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07002883 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002884 }
Leon Scrogginsaa37e7f2010-03-05 11:51:20 -05002885 } else {
2886 if (!mInLoad) {
2887 // onPageFinished may have already been called but a subframe is
2888 // still loading and updating the progress. Reset mInLoad and
2889 // update the menu items.
2890 mInLoad = true;
2891 updateInLoadMenuItems();
2892 }
2893 // When the page first begins to load, the Activity may still be
2894 // paused, in which case showFakeTitleBar will do nothing. Call
2895 // again as the page continues to load so that it will be shown.
2896 // (Calling it will the fake title bar is already showing will also
2897 // do nothing.
Grace Kloba22ac16e2009-10-07 18:00:23 -07002898 if (!mOptionsMenuOpen || mIconView) {
2899 // This page has begun to load, so show the title bar
2900 showFakeTitleBar();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002901 }
2902 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002903 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002904
Grace Kloba22ac16e2009-10-07 18:00:23 -07002905 void onShowCustomView(View view, WebChromeClient.CustomViewCallback callback) {
Derek Sollenberger8ff57db2009-12-08 15:39:55 -05002906 // if a view already exists then immediately terminate the new one
2907 if (mCustomView != null) {
2908 callback.onCustomViewHidden();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002909 return;
Derek Sollenberger8ff57db2009-12-08 15:39:55 -05002910 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002911
2912 // Add the custom view to its container.
2913 mCustomViewContainer.addView(view, COVER_SCREEN_GRAVITY_CENTER);
2914 mCustomView = view;
2915 mCustomViewCallback = callback;
2916 // Save the menu state and set it to empty while the custom
2917 // view is showing.
2918 mOldMenuState = mMenuState;
2919 mMenuState = EMPTY_MENU;
2920 // Hide the content view.
2921 mContentView.setVisibility(View.GONE);
2922 // Finally show the custom view container.
Andrei Popescu163ab742009-10-20 17:58:23 +01002923 setStatusBarVisibility(false);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002924 mCustomViewContainer.setVisibility(View.VISIBLE);
2925 mCustomViewContainer.bringToFront();
2926 }
2927
2928 void onHideCustomView() {
2929 if (mCustomView == null)
2930 return;
2931
2932 // Hide the custom view.
2933 mCustomView.setVisibility(View.GONE);
2934 // Remove the custom view from its container.
2935 mCustomViewContainer.removeView(mCustomView);
2936 mCustomView = null;
2937 // Reset the old menu state.
2938 mMenuState = mOldMenuState;
2939 mOldMenuState = EMPTY_MENU;
2940 mCustomViewContainer.setVisibility(View.GONE);
2941 mCustomViewCallback.onCustomViewHidden();
2942 // Show the content view.
Andrei Popescu163ab742009-10-20 17:58:23 +01002943 setStatusBarVisibility(true);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002944 mContentView.setVisibility(View.VISIBLE);
2945 }
2946
2947 Bitmap getDefaultVideoPoster() {
2948 if (mDefaultVideoPoster == null) {
2949 mDefaultVideoPoster = BitmapFactory.decodeResource(
2950 getResources(), R.drawable.default_video_poster);
Patrick Scott3918d442009-08-04 13:22:29 -04002951 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002952 return mDefaultVideoPoster;
2953 }
Patrick Scott3918d442009-08-04 13:22:29 -04002954
Grace Kloba22ac16e2009-10-07 18:00:23 -07002955 View getVideoLoadingProgressView() {
2956 if (mVideoProgressView == null) {
2957 LayoutInflater inflater = LayoutInflater.from(BrowserActivity.this);
2958 mVideoProgressView = inflater.inflate(
2959 R.layout.video_loading_progress, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002960 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002961 return mVideoProgressView;
2962 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002963
Leon Scroggins8d5fa432009-10-02 15:55:59 -04002964 /*
2965 * The Object used to inform the WebView of the file to upload.
2966 */
2967 private ValueCallback<Uri> mUploadMessage;
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002968 private String mCameraFilePath;
Leon Scroggins8d5fa432009-10-02 15:55:59 -04002969
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002970 void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
2971
2972 final String imageMimeType = "image/*";
Ben Murdoch6af492a2010-06-15 12:38:17 +01002973 final String videoMimeType = "video/*";
Ben Murdoch039bd472010-07-21 21:26:57 +01002974 final String audioMimeType = "audio/*";
Ben Murdochb50d7402010-07-16 12:42:22 +01002975 final String mediaSourceKey = "capture";
Ben Murdoch6af492a2010-06-15 12:38:17 +01002976 final String mediaSourceValueCamera = "camera";
Ben Murdochb50d7402010-07-16 12:42:22 +01002977 final String mediaSourceValueFileSystem = "filesystem";
Ben Murdoch6af492a2010-06-15 12:38:17 +01002978 final String mediaSourceValueCamcorder = "camcorder";
Ben Murdoch039bd472010-07-21 21:26:57 +01002979 final String mediaSourceValueMicrophone = "microphone";
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002980
Ben Murdoch039bd472010-07-21 21:26:57 +01002981 // media source can be 'filesystem' or 'camera' or 'camcorder' or 'microphone'.
Ben Murdoch6af492a2010-06-15 12:38:17 +01002982 String mediaSource = "";
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002983
Ben Murdoch6af492a2010-06-15 12:38:17 +01002984 // We add the camera intent if there was no accept type (or '*/*' or 'image/*').
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002985 boolean addCameraIntent = true;
Ben Murdoch6af492a2010-06-15 12:38:17 +01002986 // We add the camcorder intent if there was no accept type (or '*/*' or 'video/*').
2987 boolean addCamcorderIntent = true;
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002988
Ben Murdoch6af492a2010-06-15 12:38:17 +01002989 if (mUploadMessage != null) {
2990 // Already a file picker operation in progress.
2991 return;
2992 }
2993
Grace Kloba22ac16e2009-10-07 18:00:23 -07002994 mUploadMessage = uploadMsg;
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002995
2996 // Parse the accept type.
2997 String params[] = acceptType.split(";");
2998 String mimeType = params[0];
2999
3000 for (String p : params) {
3001 String[] keyValue = p.split("=");
3002 if (keyValue.length == 2) {
3003 // Process key=value parameters.
Ben Murdoch6af492a2010-06-15 12:38:17 +01003004 if (mediaSourceKey.equals(keyValue[0])) {
3005 mediaSource = keyValue[1];
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003006 }
3007 }
3008 }
3009
3010 // This intent will display the standard OPENABLE file picker.
Grace Kloba22ac16e2009-10-07 18:00:23 -07003011 Intent i = new Intent(Intent.ACTION_GET_CONTENT);
3012 i.addCategory(Intent.CATEGORY_OPENABLE);
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003013
3014 // Create an intent to add to the standard file picker that will
3015 // capture an image from the camera. We'll combine this intent with
3016 // the standard OPENABLE picker unless the web developer specifically
3017 // requested the camera or gallery be opened by passing a parameter
3018 // in the accept type.
3019 Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
3020 File externalDataDir = Environment.getExternalStoragePublicDirectory(
3021 Environment.DIRECTORY_DCIM);
3022 File cameraDataDir = new File(externalDataDir.getAbsolutePath() +
3023 File.separator + "browser-photos");
3024 cameraDataDir.mkdirs();
3025 mCameraFilePath = cameraDataDir.getAbsolutePath() + File.separator +
3026 System.currentTimeMillis() + ".jpg";
3027 cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(mCameraFilePath)));
3028
Ben Murdoch6af492a2010-06-15 12:38:17 +01003029 Intent camcorderIntent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
3030
Ben Murdoch039bd472010-07-21 21:26:57 +01003031 Intent soundRecIntent = new Intent(MediaStore.Audio.Media.RECORD_SOUND_ACTION);
3032
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003033 if (mimeType.equals(imageMimeType)) {
3034 i.setType(imageMimeType);
Ben Murdoch6af492a2010-06-15 12:38:17 +01003035 addCamcorderIntent = false;
3036 if (mediaSource.equals(mediaSourceValueCamera)) {
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003037 // Specified 'image/*' and requested the camera, so go ahead and launch the camera
3038 // directly.
3039 BrowserActivity.this.startActivityForResult(cameraIntent, FILE_SELECTED);
3040 return;
Ben Murdochb50d7402010-07-16 12:42:22 +01003041 } else if (mediaSource.equals(mediaSourceValueFileSystem)) {
3042 // Specified filesytem as the source, so don't want to consider the camera.
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003043 addCameraIntent = false;
3044 }
Ben Murdoch6af492a2010-06-15 12:38:17 +01003045 } else if (mimeType.equals(videoMimeType)) {
3046 i.setType(videoMimeType);
3047 addCameraIntent = false;
3048 // The camcorder saves it's own file and returns it to us in the intent, so
3049 // we don't need to generate one here.
3050 mCameraFilePath = null;
3051
3052 if (mediaSource.equals(mediaSourceValueCamcorder)) {
Ben Murdoch039bd472010-07-21 21:26:57 +01003053 // Specified 'video/*' and requested the camcorder, so go ahead and launch the
3054 // camcorder directly.
Ben Murdoch6af492a2010-06-15 12:38:17 +01003055 BrowserActivity.this.startActivityForResult(camcorderIntent, FILE_SELECTED);
3056 return;
Ben Murdochb50d7402010-07-16 12:42:22 +01003057 } else if (mediaSource.equals(mediaSourceValueFileSystem)) {
3058 // Specified filesystem as the source, so don't want to consider the camcorder.
Ben Murdoch6af492a2010-06-15 12:38:17 +01003059 addCamcorderIntent = false;
3060 }
Ben Murdoch039bd472010-07-21 21:26:57 +01003061 } else if (mimeType.equals(audioMimeType)) {
3062 i.setType(audioMimeType);
3063 addCameraIntent = false;
3064 addCamcorderIntent = false;
3065 if (mediaSource.equals(mediaSourceValueMicrophone)) {
3066 // Specified 'audio/*' and requested microphone, so go ahead and launch the sound
3067 // recorder.
3068 BrowserActivity.this.startActivityForResult(soundRecIntent, FILE_SELECTED);
3069 return;
3070 }
3071 // On a default system, there is no single option to open an audio "gallery". Both the
3072 // sound recorder and music browser respond to the OPENABLE/audio/* intent unlike the
3073 // image/* and video/* OPENABLE intents where the image / video gallery are the only
3074 // respondants (and so the user is not prompted by default).
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003075 } else {
3076 i.setType("*/*");
3077 }
3078
Ben Murdoch6af492a2010-06-15 12:38:17 +01003079 // Combine the chooser and the extra choices (like camera or camcorder)
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003080 Intent chooser = new Intent(Intent.ACTION_CHOOSER);
3081 chooser.putExtra(Intent.EXTRA_INTENT, i);
3082
Ben Murdoch6af492a2010-06-15 12:38:17 +01003083 Vector<Intent> extraInitialIntents = new Vector<Intent>(0);
3084
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003085 if (addCameraIntent) {
Ben Murdoch6af492a2010-06-15 12:38:17 +01003086 extraInitialIntents.add(cameraIntent);
3087 }
3088
3089 if (addCamcorderIntent) {
3090 extraInitialIntents.add(camcorderIntent);
3091 }
3092
3093 if (extraInitialIntents.size() > 0) {
3094 Intent[] extraIntents = new Intent[extraInitialIntents.size()];
3095 chooser.putExtra(Intent.EXTRA_INITIAL_INTENTS, extraInitialIntents.toArray(extraIntents));
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003096 }
3097
3098 chooser.putExtra(Intent.EXTRA_TITLE, getString(R.string.choose_upload));
3099 BrowserActivity.this.startActivityForResult(chooser, FILE_SELECTED);
Grace Kloba22ac16e2009-10-07 18:00:23 -07003100 }
3101
3102 // -------------------------------------------------------------------------
3103 // Implement functions for DownloadListener
3104 // -------------------------------------------------------------------------
3105
The Android Open Source Project0c908882009-03-03 19:32:16 -08003106 /**
3107 * Notify the host application a download should be done, or that
3108 * the data should be streamed if a streaming viewer is available.
3109 * @param url The full url to the content that should be downloaded
3110 * @param contentDisposition Content-disposition http header, if
3111 * present.
3112 * @param mimetype The mimetype of the content reported by the server
3113 * @param contentLength The file size reported by the server
3114 */
3115 public void onDownloadStart(String url, String userAgent,
3116 String contentDisposition, String mimetype, long contentLength) {
3117 // if we're dealing wih A/V content that's not explicitly marked
3118 // for download, check if it's streamable.
3119 if (contentDisposition == null
Patrick Scotte1fb9662009-08-31 14:31:52 -04003120 || !contentDisposition.regionMatches(
3121 true, 0, "attachment", 0, 10)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003122 // query the package manager to see if there's a registered handler
3123 // that matches.
3124 Intent intent = new Intent(Intent.ACTION_VIEW);
3125 intent.setDataAndType(Uri.parse(url), mimetype);
Patrick Scotte1fb9662009-08-31 14:31:52 -04003126 ResolveInfo info = getPackageManager().resolveActivity(intent,
3127 PackageManager.MATCH_DEFAULT_ONLY);
3128 if (info != null) {
3129 ComponentName myName = getComponentName();
3130 // If we resolved to ourselves, we don't want to attempt to
3131 // load the url only to try and download it again.
3132 if (!myName.getPackageName().equals(
3133 info.activityInfo.packageName)
3134 || !myName.getClassName().equals(
3135 info.activityInfo.name)) {
3136 // someone (other than us) knows how to handle this mime
3137 // type with this scheme, don't download.
3138 try {
3139 startActivity(intent);
3140 return;
3141 } catch (ActivityNotFoundException ex) {
3142 if (LOGD_ENABLED) {
3143 Log.d(LOGTAG, "activity not found for " + mimetype
3144 + " over " + Uri.parse(url).getScheme(),
3145 ex);
3146 }
3147 // Best behavior is to fall back to a download in this
3148 // case
The Android Open Source Project0c908882009-03-03 19:32:16 -08003149 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003150 }
3151 }
3152 }
3153 onDownloadStartNoStream(url, userAgent, contentDisposition, mimetype, contentLength);
3154 }
3155
Kristian Monsenfa52d172010-03-25 18:29:21 +00003156 // This is to work around the fact that java.net.URI throws Exceptions
3157 // instead of just encoding URL's properly
3158 // Helper method for onDownloadStartNoStream
3159 private static String encodePath(String path) {
3160 char[] chars = path.toCharArray();
3161
3162 boolean needed = false;
3163 for (char c : chars) {
3164 if (c == '[' || c == ']') {
3165 needed = true;
3166 break;
3167 }
3168 }
3169 if (needed == false) {
3170 return path;
3171 }
3172
3173 StringBuilder sb = new StringBuilder("");
3174 for (char c : chars) {
3175 if (c == '[' || c == ']') {
3176 sb.append('%');
3177 sb.append(Integer.toHexString(c));
3178 } else {
3179 sb.append(c);
3180 }
3181 }
3182
3183 return sb.toString();
3184 }
3185
The Android Open Source Project0c908882009-03-03 19:32:16 -08003186 /**
3187 * Notify the host application a download should be done, even if there
3188 * is a streaming viewer available for thise type.
3189 * @param url The full url to the content that should be downloaded
3190 * @param contentDisposition Content-disposition http header, if
3191 * present.
3192 * @param mimetype The mimetype of the content reported by the server
3193 * @param contentLength The file size reported by the server
3194 */
3195 /*package */ void onDownloadStartNoStream(String url, String userAgent,
3196 String contentDisposition, String mimetype, long contentLength) {
3197
3198 String filename = URLUtil.guessFileName(url,
3199 contentDisposition, mimetype);
3200
3201 // Check to see if we have an SDCard
3202 String status = Environment.getExternalStorageState();
3203 if (!status.equals(Environment.MEDIA_MOUNTED)) {
3204 int title;
3205 String msg;
3206
3207 // Check to see if the SDCard is busy, same as the music app
3208 if (status.equals(Environment.MEDIA_SHARED)) {
3209 msg = getString(R.string.download_sdcard_busy_dlg_msg);
3210 title = R.string.download_sdcard_busy_dlg_title;
3211 } else {
3212 msg = getString(R.string.download_no_sdcard_dlg_msg, filename);
3213 title = R.string.download_no_sdcard_dlg_title;
3214 }
3215
3216 new AlertDialog.Builder(this)
3217 .setTitle(title)
3218 .setIcon(android.R.drawable.ic_dialog_alert)
3219 .setMessage(msg)
3220 .setPositiveButton(R.string.ok, null)
3221 .show();
3222 return;
3223 }
3224
Kristian Monsenfa52d172010-03-25 18:29:21 +00003225 // java.net.URI is a lot stricter than KURL so we have to encode some
3226 // extra characters. Fix for b 2538060 and b 1634719
3227 WebAddress webAddress;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003228 try {
Kristian Monsenfa52d172010-03-25 18:29:21 +00003229 webAddress = new WebAddress(url);
3230 webAddress.mPath = encodePath(webAddress.mPath);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003231 } catch (Exception e) {
Kristian Monsenfa52d172010-03-25 18:29:21 +00003232 // This only happens for very bad urls, we want to chatch the
3233 // exception here
3234 Log.e(LOGTAG, "Exception trying to parse url:" + url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003235 return;
3236 }
3237
3238 // XXX: Have to use the old url since the cookies were stored using the
3239 // old percent-encoded url.
3240 String cookies = CookieManager.getInstance().getCookie(url);
3241
3242 ContentValues values = new ContentValues();
Kristian Monsenfa52d172010-03-25 18:29:21 +00003243 values.put(Downloads.Impl.COLUMN_URI, webAddress.toString());
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08003244 values.put(Downloads.Impl.COLUMN_COOKIE_DATA, cookies);
3245 values.put(Downloads.Impl.COLUMN_USER_AGENT, userAgent);
3246 values.put(Downloads.Impl.COLUMN_NOTIFICATION_PACKAGE,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003247 getPackageName());
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08003248 values.put(Downloads.Impl.COLUMN_NOTIFICATION_CLASS,
Leon Scrogginsa563d092010-04-19 16:53:49 -04003249 OpenDownloadReceiver.class.getCanonicalName());
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08003250 values.put(Downloads.Impl.COLUMN_VISIBILITY,
3251 Downloads.Impl.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
3252 values.put(Downloads.Impl.COLUMN_MIME_TYPE, mimetype);
3253 values.put(Downloads.Impl.COLUMN_FILE_NAME_HINT, filename);
Kristian Monsenfa52d172010-03-25 18:29:21 +00003254 values.put(Downloads.Impl.COLUMN_DESCRIPTION, webAddress.mHost);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003255 if (contentLength > 0) {
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08003256 values.put(Downloads.Impl.COLUMN_TOTAL_BYTES, contentLength);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003257 }
3258 if (mimetype == null) {
3259 // We must have long pressed on a link or image to download it. We
3260 // are not sure of the mimetype in this case, so do a head request
3261 new FetchUrlMimeType(this).execute(values);
3262 } else {
3263 final Uri contentUri =
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08003264 getContentResolver().insert(Downloads.Impl.CONTENT_URI, values);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003265 }
Leon Scroggins9191a7f2010-03-18 14:44:44 -04003266 Toast.makeText(this, R.string.download_pending, Toast.LENGTH_SHORT)
3267 .show();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003268 }
3269
Grace Kloba22ac16e2009-10-07 18:00:23 -07003270 // -------------------------------------------------------------------------
3271
The Android Open Source Project0c908882009-03-03 19:32:16 -08003272 /**
3273 * Resets the lock icon. This method is called when we start a new load and
3274 * know the url to be loaded.
3275 */
3276 private void resetLockIcon(String url) {
3277 // Save the lock-icon state (we revert to it if the load gets cancelled)
Grace Kloba22ac16e2009-10-07 18:00:23 -07003278 mTabControl.getCurrentTab().resetLockIcon(url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003279 updateLockIconImage(LOCK_ICON_UNSECURE);
3280 }
3281
The Android Open Source Project0c908882009-03-03 19:32:16 -08003282 /**
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04003283 * Update the lock icon to correspond to our latest state.
3284 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003285 private void updateLockIconToLatest() {
Leon Scroggins91f65fc2010-06-29 13:52:39 -04003286 Tab t = mTabControl.getCurrentTab();
3287 if (t != null) {
3288 updateLockIconImage(t.getLockIconType());
3289 }
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04003290 }
3291
3292 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08003293 * Updates the lock-icon image in the title-bar.
3294 */
3295 private void updateLockIconImage(int lockIconType) {
3296 Drawable d = null;
3297 if (lockIconType == LOCK_ICON_SECURE) {
3298 d = mSecLockIcon;
3299 } else if (lockIconType == LOCK_ICON_MIXED) {
3300 d = mMixLockIcon;
3301 }
Leon Scroggins68579392009-09-15 15:31:54 -04003302 mTitleBar.setLock(d);
Michael Kolba2b2ba82010-08-04 17:54:03 -07003303 mFakeTitleBar.setLock(d);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003304 }
3305
3306 /**
3307 * Displays a page-info dialog.
3308 * @param tab The tab to show info about
3309 * @param fromShowSSLCertificateOnError The flag that indicates whether
3310 * this dialog was opened from the SSL-certificate-on-error dialog or
3311 * not. This is important, since we need to know whether to return to
3312 * the parent dialog or simply dismiss.
3313 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003314 private void showPageInfo(final Tab tab,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003315 final boolean fromShowSSLCertificateOnError) {
3316 final LayoutInflater factory = LayoutInflater
3317 .from(this);
3318
3319 final View pageInfoView = factory.inflate(R.layout.page_info, null);
3320
3321 final WebView view = tab.getWebView();
3322
3323 String url = null;
3324 String title = null;
3325
3326 if (view == null) {
3327 url = tab.getUrl();
3328 title = tab.getTitle();
3329 } else if (view == mTabControl.getCurrentWebView()) {
3330 // Use the cached title and url if this is the current WebView
3331 url = mUrl;
3332 title = mTitle;
3333 } else {
3334 url = view.getUrl();
3335 title = view.getTitle();
3336 }
3337
3338 if (url == null) {
3339 url = "";
3340 }
3341 if (title == null) {
3342 title = "";
3343 }
3344
3345 ((TextView) pageInfoView.findViewById(R.id.address)).setText(url);
3346 ((TextView) pageInfoView.findViewById(R.id.title)).setText(title);
3347
3348 mPageInfoView = tab;
Leon Scrogginsc7b92f82010-01-11 18:17:31 -05003349 mPageInfoFromShowSSLCertificateOnError = fromShowSSLCertificateOnError;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003350
3351 AlertDialog.Builder alertDialogBuilder =
3352 new AlertDialog.Builder(this)
3353 .setTitle(R.string.page_info).setIcon(android.R.drawable.ic_dialog_info)
3354 .setView(pageInfoView)
3355 .setPositiveButton(
3356 R.string.ok,
3357 new DialogInterface.OnClickListener() {
3358 public void onClick(DialogInterface dialog,
3359 int whichButton) {
3360 mPageInfoDialog = null;
3361 mPageInfoView = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003362
3363 // if we came here from the SSL error dialog
3364 if (fromShowSSLCertificateOnError) {
3365 // go back to the SSL error dialog
3366 showSSLCertificateOnError(
3367 mSSLCertificateOnErrorView,
3368 mSSLCertificateOnErrorHandler,
3369 mSSLCertificateOnErrorError);
3370 }
3371 }
3372 })
3373 .setOnCancelListener(
3374 new DialogInterface.OnCancelListener() {
3375 public void onCancel(DialogInterface dialog) {
3376 mPageInfoDialog = null;
3377 mPageInfoView = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003378
3379 // if we came here from the SSL error dialog
3380 if (fromShowSSLCertificateOnError) {
3381 // go back to the SSL error dialog
3382 showSSLCertificateOnError(
3383 mSSLCertificateOnErrorView,
3384 mSSLCertificateOnErrorHandler,
3385 mSSLCertificateOnErrorError);
3386 }
3387 }
3388 });
3389
3390 // if we have a main top-level page SSL certificate set or a certificate
3391 // error
3392 if (fromShowSSLCertificateOnError ||
3393 (view != null && view.getCertificate() != null)) {
3394 // add a 'View Certificate' button
3395 alertDialogBuilder.setNeutralButton(
3396 R.string.view_certificate,
3397 new DialogInterface.OnClickListener() {
3398 public void onClick(DialogInterface dialog,
3399 int whichButton) {
3400 mPageInfoDialog = null;
3401 mPageInfoView = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003402
3403 // if we came here from the SSL error dialog
3404 if (fromShowSSLCertificateOnError) {
3405 // go back to the SSL error dialog
3406 showSSLCertificateOnError(
3407 mSSLCertificateOnErrorView,
3408 mSSLCertificateOnErrorHandler,
3409 mSSLCertificateOnErrorError);
3410 } else {
3411 // otherwise, display the top-most certificate from
3412 // the chain
3413 if (view.getCertificate() != null) {
3414 showSSLCertificate(tab);
3415 }
3416 }
3417 }
3418 });
3419 }
3420
3421 mPageInfoDialog = alertDialogBuilder.show();
3422 }
3423
3424 /**
3425 * Displays the main top-level page SSL certificate dialog
3426 * (accessible from the Page-Info dialog).
3427 * @param tab The tab to show certificate for.
3428 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003429 private void showSSLCertificate(final Tab tab) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003430 final View certificateView =
3431 inflateCertificateView(tab.getWebView().getCertificate());
3432 if (certificateView == null) {
3433 return;
3434 }
3435
3436 LayoutInflater factory = LayoutInflater.from(this);
3437
3438 final LinearLayout placeholder =
3439 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3440
3441 LinearLayout ll = (LinearLayout) factory.inflate(
3442 R.layout.ssl_success, placeholder);
3443 ((TextView)ll.findViewById(R.id.success))
3444 .setText(R.string.ssl_certificate_is_valid);
3445
3446 mSSLCertificateView = tab;
3447 mSSLCertificateDialog =
3448 new AlertDialog.Builder(this)
3449 .setTitle(R.string.ssl_certificate).setIcon(
3450 R.drawable.ic_dialog_browser_certificate_secure)
3451 .setView(certificateView)
3452 .setPositiveButton(R.string.ok,
3453 new DialogInterface.OnClickListener() {
3454 public void onClick(DialogInterface dialog,
3455 int whichButton) {
3456 mSSLCertificateDialog = null;
3457 mSSLCertificateView = null;
3458
3459 showPageInfo(tab, false);
3460 }
3461 })
3462 .setOnCancelListener(
3463 new DialogInterface.OnCancelListener() {
3464 public void onCancel(DialogInterface dialog) {
3465 mSSLCertificateDialog = null;
3466 mSSLCertificateView = null;
3467
3468 showPageInfo(tab, false);
3469 }
3470 })
3471 .show();
3472 }
3473
3474 /**
3475 * Displays the SSL error certificate dialog.
3476 * @param view The target web-view.
3477 * @param handler The SSL error handler responsible for cancelling the
3478 * connection that resulted in an SSL error or proceeding per user request.
3479 * @param error The SSL error object.
3480 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003481 void showSSLCertificateOnError(
The Android Open Source Project0c908882009-03-03 19:32:16 -08003482 final WebView view, final SslErrorHandler handler, final SslError error) {
3483
3484 final View certificateView =
3485 inflateCertificateView(error.getCertificate());
3486 if (certificateView == null) {
3487 return;
3488 }
3489
3490 LayoutInflater factory = LayoutInflater.from(this);
3491
3492 final LinearLayout placeholder =
3493 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3494
3495 if (error.hasError(SslError.SSL_UNTRUSTED)) {
3496 LinearLayout ll = (LinearLayout)factory
3497 .inflate(R.layout.ssl_warning, placeholder);
3498 ((TextView)ll.findViewById(R.id.warning))
3499 .setText(R.string.ssl_untrusted);
3500 }
3501
3502 if (error.hasError(SslError.SSL_IDMISMATCH)) {
3503 LinearLayout ll = (LinearLayout)factory
3504 .inflate(R.layout.ssl_warning, placeholder);
3505 ((TextView)ll.findViewById(R.id.warning))
3506 .setText(R.string.ssl_mismatch);
3507 }
3508
3509 if (error.hasError(SslError.SSL_EXPIRED)) {
3510 LinearLayout ll = (LinearLayout)factory
3511 .inflate(R.layout.ssl_warning, placeholder);
3512 ((TextView)ll.findViewById(R.id.warning))
3513 .setText(R.string.ssl_expired);
3514 }
3515
3516 if (error.hasError(SslError.SSL_NOTYETVALID)) {
3517 LinearLayout ll = (LinearLayout)factory
3518 .inflate(R.layout.ssl_warning, placeholder);
3519 ((TextView)ll.findViewById(R.id.warning))
3520 .setText(R.string.ssl_not_yet_valid);
3521 }
3522
3523 mSSLCertificateOnErrorHandler = handler;
3524 mSSLCertificateOnErrorView = view;
3525 mSSLCertificateOnErrorError = error;
3526 mSSLCertificateOnErrorDialog =
3527 new AlertDialog.Builder(this)
3528 .setTitle(R.string.ssl_certificate).setIcon(
3529 R.drawable.ic_dialog_browser_certificate_partially_secure)
3530 .setView(certificateView)
3531 .setPositiveButton(R.string.ok,
3532 new DialogInterface.OnClickListener() {
3533 public void onClick(DialogInterface dialog,
3534 int whichButton) {
3535 mSSLCertificateOnErrorDialog = null;
3536 mSSLCertificateOnErrorView = null;
3537 mSSLCertificateOnErrorHandler = null;
3538 mSSLCertificateOnErrorError = null;
3539
Grace Kloba22ac16e2009-10-07 18:00:23 -07003540 view.getWebViewClient().onReceivedSslError(
3541 view, handler, error);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003542 }
3543 })
3544 .setNeutralButton(R.string.page_info_view,
3545 new DialogInterface.OnClickListener() {
3546 public void onClick(DialogInterface dialog,
3547 int whichButton) {
3548 mSSLCertificateOnErrorDialog = null;
3549
3550 // do not clear the dialog state: we will
3551 // need to show the dialog again once the
3552 // user is done exploring the page-info details
3553
3554 showPageInfo(mTabControl.getTabFromView(view),
3555 true);
3556 }
3557 })
3558 .setOnCancelListener(
3559 new DialogInterface.OnCancelListener() {
3560 public void onCancel(DialogInterface dialog) {
3561 mSSLCertificateOnErrorDialog = null;
3562 mSSLCertificateOnErrorView = null;
3563 mSSLCertificateOnErrorHandler = null;
3564 mSSLCertificateOnErrorError = null;
3565
Grace Kloba22ac16e2009-10-07 18:00:23 -07003566 view.getWebViewClient().onReceivedSslError(
3567 view, handler, error);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003568 }
3569 })
3570 .show();
3571 }
3572
3573 /**
3574 * Inflates the SSL certificate view (helper method).
3575 * @param certificate The SSL certificate.
3576 * @return The resultant certificate view with issued-to, issued-by,
3577 * issued-on, expires-on, and possibly other fields set.
3578 * If the input certificate is null, returns null.
3579 */
3580 private View inflateCertificateView(SslCertificate certificate) {
3581 if (certificate == null) {
3582 return null;
3583 }
3584
3585 LayoutInflater factory = LayoutInflater.from(this);
3586
3587 View certificateView = factory.inflate(
3588 R.layout.ssl_certificate, null);
3589
3590 // issued to:
3591 SslCertificate.DName issuedTo = certificate.getIssuedTo();
3592 if (issuedTo != null) {
3593 ((TextView) certificateView.findViewById(R.id.to_common))
3594 .setText(issuedTo.getCName());
3595 ((TextView) certificateView.findViewById(R.id.to_org))
3596 .setText(issuedTo.getOName());
3597 ((TextView) certificateView.findViewById(R.id.to_org_unit))
3598 .setText(issuedTo.getUName());
3599 }
3600
3601 // issued by:
3602 SslCertificate.DName issuedBy = certificate.getIssuedBy();
3603 if (issuedBy != null) {
3604 ((TextView) certificateView.findViewById(R.id.by_common))
3605 .setText(issuedBy.getCName());
3606 ((TextView) certificateView.findViewById(R.id.by_org))
3607 .setText(issuedBy.getOName());
3608 ((TextView) certificateView.findViewById(R.id.by_org_unit))
3609 .setText(issuedBy.getUName());
3610 }
3611
3612 // issued on:
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003613 String issuedOn = formatCertificateDate(
3614 certificate.getValidNotBeforeDate());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003615 ((TextView) certificateView.findViewById(R.id.issued_on))
3616 .setText(issuedOn);
3617
3618 // expires on:
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003619 String expiresOn = formatCertificateDate(
3620 certificate.getValidNotAfterDate());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003621 ((TextView) certificateView.findViewById(R.id.expires_on))
3622 .setText(expiresOn);
3623
3624 return certificateView;
3625 }
3626
3627 /**
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003628 * Formats the certificate date to a properly localized date string.
The Android Open Source Project0c908882009-03-03 19:32:16 -08003629 * @return Properly localized version of the certificate date string and
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003630 * the "" if it fails to localize.
The Android Open Source Project0c908882009-03-03 19:32:16 -08003631 */
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003632 private String formatCertificateDate(Date certificateDate) {
3633 if (certificateDate == null) {
3634 return "";
The Android Open Source Project0c908882009-03-03 19:32:16 -08003635 }
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003636 String formattedDate = DateFormat.getDateFormat(this).format(certificateDate);
3637 if (formattedDate == null) {
3638 return "";
3639 }
3640 return formattedDate;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003641 }
3642
3643 /**
3644 * Displays an http-authentication dialog.
3645 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003646 void showHttpAuthentication(final HttpAuthHandler handler,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003647 final String host, final String realm, final String title,
3648 final String name, final String password, int focusId) {
3649 LayoutInflater factory = LayoutInflater.from(this);
3650 final View v = factory
3651 .inflate(R.layout.http_authentication, null);
3652 if (name != null) {
3653 ((EditText) v.findViewById(R.id.username_edit)).setText(name);
3654 }
3655 if (password != null) {
3656 ((EditText) v.findViewById(R.id.password_edit)).setText(password);
3657 }
3658
3659 String titleText = title;
3660 if (titleText == null) {
3661 titleText = getText(R.string.sign_in_to).toString().replace(
3662 "%s1", host).replace("%s2", realm);
3663 }
3664
3665 mHttpAuthHandler = handler;
3666 AlertDialog dialog = new AlertDialog.Builder(this)
3667 .setTitle(titleText)
3668 .setIcon(android.R.drawable.ic_dialog_alert)
3669 .setView(v)
3670 .setPositiveButton(R.string.action,
3671 new DialogInterface.OnClickListener() {
3672 public void onClick(DialogInterface dialog,
3673 int whichButton) {
3674 String nm = ((EditText) v
3675 .findViewById(R.id.username_edit))
3676 .getText().toString();
3677 String pw = ((EditText) v
3678 .findViewById(R.id.password_edit))
3679 .getText().toString();
3680 BrowserActivity.this.setHttpAuthUsernamePassword
3681 (host, realm, nm, pw);
3682 handler.proceed(nm, pw);
3683 mHttpAuthenticationDialog = null;
3684 mHttpAuthHandler = null;
3685 }})
3686 .setNegativeButton(R.string.cancel,
3687 new DialogInterface.OnClickListener() {
3688 public void onClick(DialogInterface dialog,
3689 int whichButton) {
3690 handler.cancel();
3691 BrowserActivity.this.resetTitleAndRevertLockIcon();
3692 mHttpAuthenticationDialog = null;
3693 mHttpAuthHandler = null;
3694 }})
3695 .setOnCancelListener(new DialogInterface.OnCancelListener() {
3696 public void onCancel(DialogInterface dialog) {
3697 handler.cancel();
3698 BrowserActivity.this.resetTitleAndRevertLockIcon();
3699 mHttpAuthenticationDialog = null;
3700 mHttpAuthHandler = null;
3701 }})
3702 .create();
3703 // Make the IME appear when the dialog is displayed if applicable.
3704 dialog.getWindow().setSoftInputMode(
3705 WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
3706 dialog.show();
3707 if (focusId != 0) {
3708 dialog.findViewById(focusId).requestFocus();
3709 } else {
3710 v.findViewById(R.id.username_edit).requestFocus();
3711 }
3712 mHttpAuthenticationDialog = dialog;
3713 }
3714
3715 public int getProgress() {
3716 WebView w = mTabControl.getCurrentWebView();
3717 if (w != null) {
3718 return w.getProgress();
3719 } else {
3720 return 100;
3721 }
3722 }
3723
3724 /**
3725 * Set HTTP authentication password.
3726 *
3727 * @param host The host for the password
3728 * @param realm The realm for the password
3729 * @param username The username for the password. If it is null, it means
3730 * password can't be saved.
3731 * @param password The password
3732 */
3733 public void setHttpAuthUsernamePassword(String host, String realm,
3734 String username,
3735 String password) {
Steve Block95a53b22010-03-25 17:24:58 +00003736 WebView w = getTopWindow();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003737 if (w != null) {
3738 w.setHttpAuthUsernamePassword(host, realm, username, password);
3739 }
3740 }
3741
3742 /**
3743 * connectivity manager says net has come or gone... inform the user
3744 * @param up true if net has come up, false if net has gone down
3745 */
3746 public void onNetworkToggle(boolean up) {
3747 if (up == mIsNetworkUp) {
3748 return;
3749 } else if (up) {
3750 mIsNetworkUp = true;
3751 if (mAlertDialog != null) {
3752 mAlertDialog.cancel();
3753 mAlertDialog = null;
3754 }
3755 } else {
3756 mIsNetworkUp = false;
Patrick Scotteb6ab2a2009-09-16 10:00:17 -04003757 if (mInLoad) {
3758 createAndShowNetworkDialog();
3759 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003760 }
3761 WebView w = mTabControl.getCurrentWebView();
3762 if (w != null) {
3763 w.setNetworkAvailable(up);
3764 }
3765 }
3766
Grace Kloba22ac16e2009-10-07 18:00:23 -07003767 boolean isNetworkUp() {
3768 return mIsNetworkUp;
3769 }
3770
Patrick Scotteb6ab2a2009-09-16 10:00:17 -04003771 // This method shows the network dialog alerting the user that the net is
3772 // down. It will only show the dialog if mAlertDialog is null.
3773 private void createAndShowNetworkDialog() {
3774 if (mAlertDialog == null) {
3775 mAlertDialog = new AlertDialog.Builder(this)
3776 .setTitle(R.string.loadSuspendedTitle)
3777 .setMessage(R.string.loadSuspended)
3778 .setPositiveButton(R.string.ok, null)
3779 .show();
3780 }
3781 }
3782
The Android Open Source Project0c908882009-03-03 19:32:16 -08003783 @Override
3784 protected void onActivityResult(int requestCode, int resultCode,
3785 Intent intent) {
Grace Klobabb394f32009-11-19 10:26:37 -08003786 if (getTopWindow() == null) return;
3787
The Android Open Source Project0c908882009-03-03 19:32:16 -08003788 switch (requestCode) {
3789 case COMBO_PAGE:
3790 if (resultCode == RESULT_OK && intent != null) {
3791 String data = intent.getAction();
3792 Bundle extras = intent.getExtras();
Michael Kolb300b7f02010-08-25 13:47:24 -07003793 if (extras != null &&
3794 extras.getBoolean(
3795 CombinedBookmarkHistoryActivity.EXTRA_OPEN_NEW_WINDOW,
3796 false)) {
Michael Kolb68792c82010-08-09 16:39:18 -07003797 openTab(data, false);
3798 } else if ((extras != null) &&
3799 extras.getBoolean(CombinedBookmarkHistoryActivity.NEWTAB_MODE)) {
3800 openTab(data, true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003801 } else {
Michael Kolb68792c82010-08-09 16:39:18 -07003802 final Tab currentTab = mTabControl.getCurrentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04003803 dismissSubWindow(currentTab);
3804 if (data != null && data.length() != 0) {
Leon Scroggins92472e82010-02-17 16:32:28 -05003805 loadUrl(getTopWindow(), data);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003806 }
3807 }
Michael Kolb3f65c382010-08-20 15:31:16 -07003808 } else if (resultCode == RESULT_CANCELED) {
3809 if (intent != null) {
3810 float evtx = intent.getFloatExtra(CombinedBookmarkHistoryActivity.EVT_X, -1);
3811 float evty = intent.getFloatExtra(CombinedBookmarkHistoryActivity.EVT_Y, -1);
3812 long now = System.currentTimeMillis();
3813 MotionEvent evt = MotionEvent.obtain(now, now,
3814 MotionEvent.ACTION_DOWN, evtx, evty, 0);
3815 dispatchTouchEvent(evt);
3816 MotionEvent up = MotionEvent.obtain(evt);
3817 up.setAction(MotionEvent.ACTION_UP);
3818 dispatchTouchEvent(up);
3819 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003820 }
Leon Scrogginsfde97462010-01-11 13:06:21 -05003821 // Deliberately fall through to PREFERENCES_PAGE, since the
3822 // same extra may be attached to the COMBO_PAGE
3823 case PREFERENCES_PAGE:
3824 if (resultCode == RESULT_OK && intent != null) {
3825 String action = intent.getStringExtra(Intent.EXTRA_TEXT);
3826 if (BrowserSettings.PREF_CLEAR_HISTORY.equals(action)) {
3827 mTabControl.removeParentChildRelationShips();
3828 }
3829 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003830 break;
Leon Scroggins8d5fa432009-10-02 15:55:59 -04003831 // Choose a file from the file picker.
3832 case FILE_SELECTED:
3833 if (null == mUploadMessage) break;
3834 Uri result = intent == null || resultCode != RESULT_OK ? null
3835 : intent.getData();
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003836
3837 // As we ask the camera to save the result of the user taking
3838 // a picture, the camera application does not return anything other
3839 // than RESULT_OK. So we need to check whether the file we expected
3840 // was written to disk in the in the case that we
3841 // did not get an intent returned but did get a RESULT_OK. If it was,
3842 // we assume that this result has came back from the camera.
3843 if (result == null && intent == null && resultCode == RESULT_OK) {
3844 File cameraFile = new File(mCameraFilePath);
3845 if (cameraFile.exists()) {
3846 result = Uri.fromFile(cameraFile);
Ben Murdoch07d34732010-05-27 18:34:46 +01003847 // Broadcast to the media scanner that we have a new photo
3848 // so it will be added into the gallery for the user.
3849 sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, result));
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003850 }
3851 }
Leon Scroggins8d5fa432009-10-02 15:55:59 -04003852 mUploadMessage.onReceiveValue(result);
3853 mUploadMessage = null;
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003854 mCameraFilePath = null;
Leon Scroggins8d5fa432009-10-02 15:55:59 -04003855 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003856 default:
3857 break;
3858 }
Leon Scroggins30444232009-09-04 18:36:20 -04003859 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003860 }
3861
3862 /*
3863 * This method is called as a result of the user selecting the options
Leon Scrogginsf08809b2010-01-21 09:27:46 -05003864 * menu to see the download window. It shows the download window on top of
3865 * the current window.
The Android Open Source Project0c908882009-03-03 19:32:16 -08003866 */
Leon Scroggins IIIa682a3c2010-09-27 12:32:40 -04003867 private void viewDownloads() {
3868 Intent intent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
3869 startActivity(intent);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003870 }
3871
Michael Kolbc7485ae2010-09-03 10:10:58 -07003872 /* package */ void promptAddOrInstallBookmark(View anchor) {
3873 PopupMenu popup = new PopupMenu(this, anchor);
3874 popup.getMenuInflater().inflate(R.menu.bookmark_shortcut, popup.getMenu());
3875 popup.setOnMenuItemClickListener(this);
3876 popup.show();
3877 }
Michael Kolbebba8b42010-09-30 12:57:59 -07003878
Michael Kolbc7485ae2010-09-03 10:10:58 -07003879 /**
3880 * popup menu item click listener
3881 * @param item
3882 */
3883 public boolean onMenuItemClick(MenuItem item) {
3884 switch(item.getItemId()) {
3885 case R.id.add_bookmark_menu_id:
3886 bookmarkCurrentPage();
3887 return true;
3888 case R.id.shortcut_to_home_menu_id:
3889 Tab current = mTabControl.getCurrentTab();
3890 current.populatePickerData();
3891 String touchIconUrl = mTabControl.getCurrentWebView().getTouchIconUrl();
3892 if (touchIconUrl != null) {
3893 // Download the touch icon for this site then save
3894 // it to the
3895 // homescreen.
3896 Bundle b = new Bundle();
3897 b.putString("url", current.getUrl());
3898 b.putString("title", current.getTitle());
3899 b.putParcelable("favicon", current.getFavicon());
3900 Message msg = mHandler.obtainMessage(TOUCH_ICON_DOWNLOADED);
3901 msg.setData(b);
3902 new DownloadTouchIcon(BrowserActivity.this, msg,
3903 mTabControl.getCurrentWebView().getSettings().getUserAgentString())
3904 .execute(touchIconUrl);
3905 } else {
3906 // add to homescreen, can do it immediately as there
3907 // is no touch
3908 // icon.
3909 showSaveToHomescreenDialog(
3910 current.getUrl(), current.getTitle(), null, current.getFavicon());
3911 }
3912 return true;
3913 default:
3914 return false;
3915 }
3916 }
Michael Kolbebba8b42010-09-30 12:57:59 -07003917
Michael Kolbc7485ae2010-09-03 10:10:58 -07003918 /* package */Dialog makeAddOrInstallDialog() {
Ben Murdocheecb4e62010-07-06 16:30:38 +01003919 final Tab current = mTabControl.getCurrentTab();
3920 Resources resources = getResources();
Michael Kolbc7485ae2010-09-03 10:10:58 -07003921 CharSequence[] choices =
3922 {resources.getString(R.string.save_to_bookmarks),
3923 resources.getString(R.string.create_shortcut_bookmark)};
Ben Murdocheecb4e62010-07-06 16:30:38 +01003924
3925 AlertDialog.Builder builder = new AlertDialog.Builder(this);
3926 builder.setTitle(R.string.add_new_bookmark);
3927 builder.setItems(choices, new DialogInterface.OnClickListener() {
Michael Kolbc7485ae2010-09-03 10:10:58 -07003928 public void onClick(DialogInterface dialog, int item) {
3929 if (item == 0) {
3930 bookmarkCurrentPage();
3931 } else if (item == 1) {
3932 }
3933 }
Ben Murdocheecb4e62010-07-06 16:30:38 +01003934 });
Michael Kolbc7485ae2010-09-03 10:10:58 -07003935 return builder.create();
Ben Murdocheecb4e62010-07-06 16:30:38 +01003936 }
3937
Leon Scroggins160a7e72009-08-14 18:28:01 -04003938 /**
3939 * Open the Go page.
3940 * @param startWithHistory If true, open starting on the history tab.
3941 * Otherwise, start with the bookmarks tab.
Leon Scroggins160a7e72009-08-14 18:28:01 -04003942 */
Michael Kolb68792c82010-08-09 16:39:18 -07003943 /* package */ void bookmarksOrHistoryPicker(boolean startWithHistory, boolean newTabMode) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003944 WebView current = mTabControl.getCurrentWebView();
3945 if (current == null) {
3946 return;
3947 }
3948 Intent intent = new Intent(this,
3949 CombinedBookmarkHistoryActivity.class);
3950 String title = current.getTitle();
3951 String url = current.getUrl();
Ben Murdoch87cc65d2010-06-29 20:34:10 +01003952 Bitmap thumbnail = createScreenshot(current, getDesiredThumbnailWidth(this),
3953 getDesiredThumbnailHeight(this));
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01003954
The Android Open Source Project0c908882009-03-03 19:32:16 -08003955 // Just in case the user opens bookmarks before a page finishes loading
3956 // so the current history item, and therefore the page, is null.
3957 if (null == url) {
3958 url = mLastEnteredUrl;
3959 // This can happen.
3960 if (null == url) {
3961 url = mSettings.getHomePage();
3962 }
3963 }
3964 // In case the web page has not yet received its associated title.
3965 if (title == null) {
3966 title = url;
3967 }
3968 intent.putExtra("title", title);
3969 intent.putExtra("url", url);
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01003970 intent.putExtra("thumbnail", thumbnail);
Leon Scroggins30444232009-09-04 18:36:20 -04003971 // Disable opening in a new window if we have maxed out the windows
Grace Kloba22ac16e2009-10-07 18:00:23 -07003972 intent.putExtra("disable_new_window", !mTabControl.canCreateNewTab());
Patrick Scott3918d442009-08-04 13:22:29 -04003973 intent.putExtra("touch_icon_url", current.getTouchIconUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003974 if (startWithHistory) {
Jeff Hamilton64144e42010-08-18 16:31:59 -05003975 intent.putExtra(CombinedBookmarkHistoryActivity.STARTING_FRAGMENT,
3976 CombinedBookmarkHistoryActivity.FRAGMENT_ID_HISTORY);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003977 }
Michael Kolb300b7f02010-08-25 13:47:24 -07003978 intent.putExtra(CombinedBookmarkHistoryActivity.NEWTAB_MODE, newTabMode);
Michael Kolb0998b0a2010-08-23 17:45:35 -07003979 int top = -1;
3980 int height = -1;
Michael Kolb3f65c382010-08-20 15:31:16 -07003981 if (mXLargeScreenSize) {
3982 showFakeTitleBar();
3983 int titleBarHeight = ((TitleBarXLarge)mFakeTitleBar).getHeightWithoutProgress();
Michael Kolb0998b0a2010-08-23 17:45:35 -07003984 top = mTabBar.getBottom() + titleBarHeight;
3985 height = getTopWindow().getHeight() - titleBarHeight;
Michael Kolb68792c82010-08-09 16:39:18 -07003986 }
Michael Kolb0998b0a2010-08-23 17:45:35 -07003987 intent.putExtra(CombinedBookmarkHistoryActivity.EXTRA_TOP, top);
3988 intent.putExtra(CombinedBookmarkHistoryActivity.EXTRA_HEIGHT, height);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003989 startActivityForResult(intent, COMBO_PAGE);
3990 }
3991
Ben Murdocheecb4e62010-07-06 16:30:38 +01003992 private void showSaveToHomescreenDialog(String url, String title, Bitmap touchIcon,
3993 Bitmap favicon) {
3994 Intent intent = new Intent(this, SaveToHomescreenDialog.class);
3995
3996 // Just in case the user tries to save before a page finishes loading
3997 // so the current history item, and therefore the page, is null.
3998 if (null == url) {
3999 url = mLastEnteredUrl;
4000 // This can happen.
4001 if (null == url) {
4002 url = mSettings.getHomePage();
4003 }
4004 }
4005
4006 // In case the web page has not yet received its associated title.
4007 if (title == null) {
4008 title = url;
4009 }
4010
4011 intent.putExtra("title", title);
4012 intent.putExtra("url", url);
4013 intent.putExtra("favicon", favicon);
4014 intent.putExtra("touchIcon", touchIcon);
4015 startActivity(intent);
4016 }
4017
4018
The Android Open Source Project0c908882009-03-03 19:32:16 -08004019 // Called when loading from context menu or LOAD_URL message
Leon Scroggins92472e82010-02-17 16:32:28 -05004020 private void loadUrlFromContext(WebView view, String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08004021 // In case the user enters nothing.
4022 if (url != null && url.length() != 0 && view != null) {
4023 url = smartUrlFilter(url);
Grace Kloba22ac16e2009-10-07 18:00:23 -07004024 if (!view.getWebViewClient().shouldOverrideUrlLoading(view, url)) {
Leon Scroggins92472e82010-02-17 16:32:28 -05004025 loadUrl(view, url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004026 }
4027 }
4028 }
4029
Leon Scroggins92472e82010-02-17 16:32:28 -05004030 /**
4031 * Load the URL into the given WebView and update the title bar
4032 * to reflect the new load. Call this instead of WebView.loadUrl
4033 * directly.
4034 * @param view The WebView used to load url.
4035 * @param url The URL to load.
4036 */
4037 private void loadUrl(WebView view, String url) {
4038 updateTitleBarForNewLoad(view, url);
4039 view.loadUrl(url);
4040 }
4041
4042 /**
4043 * Load UrlData into a Tab and update the title bar to reflect the new
4044 * load. Call this instead of UrlData.loadIn directly.
4045 * @param t The Tab used to load.
4046 * @param data The UrlData being loaded.
4047 */
4048 private void loadUrlDataIn(Tab t, UrlData data) {
4049 updateTitleBarForNewLoad(t.getWebView(), data.mUrl);
4050 data.loadIn(t);
4051 }
4052
4053 /**
4054 * If the WebView is the top window, update the title bar to reflect
4055 * loading the new URL. i.e. set its text, clear the favicon (which
4056 * will be set once the page begins loading), and set the progress to
4057 * INITIAL_PROGRESS to show that the page has begun to load. Called
4058 * by loadUrl and loadUrlDataIn.
4059 * @param view The WebView that is starting a load.
4060 * @param url The URL that is being loaded.
4061 */
4062 private void updateTitleBarForNewLoad(WebView view, String url) {
4063 if (view == getTopWindow()) {
4064 setUrlTitle(url, null);
4065 setFavicon(null);
4066 onProgressChanged(view, INITIAL_PROGRESS);
4067 }
4068 }
4069
The Android Open Source Project0c908882009-03-03 19:32:16 -08004070 private String smartUrlFilter(Uri inUri) {
4071 if (inUri != null) {
4072 return smartUrlFilter(inUri.toString());
4073 }
4074 return null;
4075 }
4076
Feng Qianb34f87a2009-03-24 21:27:26 -07004077 protected static final Pattern ACCEPTED_URI_SCHEMA = Pattern.compile(
The Android Open Source Project0c908882009-03-03 19:32:16 -08004078 "(?i)" + // switch on case insensitive matching
4079 "(" + // begin group for schema
4080 "(?:http|https|file):\\/\\/" +
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004081 "|(?:inline|data|about|content|javascript):" +
The Android Open Source Project0c908882009-03-03 19:32:16 -08004082 ")" +
4083 "(.*)" );
4084
4085 /**
4086 * Attempts to determine whether user input is a URL or search
4087 * terms. Anything with a space is passed to search.
4088 *
4089 * Converts to lowercase any mistakenly uppercased schema (i.e.,
4090 * "Http://" converts to "http://"
4091 *
4092 * @return Original or modified URL
4093 *
4094 */
4095 String smartUrlFilter(String url) {
4096
4097 String inUrl = url.trim();
4098 boolean hasSpace = inUrl.indexOf(' ') != -1;
4099
4100 Matcher matcher = ACCEPTED_URI_SCHEMA.matcher(inUrl);
4101 if (matcher.matches()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08004102 // force scheme to lowercase
4103 String scheme = matcher.group(1);
4104 String lcScheme = scheme.toLowerCase();
4105 if (!lcScheme.equals(scheme)) {
Mitsuru Oshima123ecfb2009-05-18 19:11:14 -07004106 inUrl = lcScheme + matcher.group(2);
4107 }
4108 if (hasSpace) {
4109 inUrl = inUrl.replace(" ", "%20");
The Android Open Source Project0c908882009-03-03 19:32:16 -08004110 }
4111 return inUrl;
4112 }
4113 if (hasSpace) {
Satish Sampath565505b2009-05-29 15:37:27 +01004114 // FIXME: Is this the correct place to add to searches?
4115 // what if someone else calls this function?
4116 int shortcut = parseUrlShortcut(inUrl);
4117 if (shortcut != SHORTCUT_INVALID) {
4118 Browser.addSearchUrl(mResolver, inUrl);
4119 String query = inUrl.substring(2);
4120 switch (shortcut) {
4121 case SHORTCUT_GOOGLE_SEARCH:
Grace Kloba47fdfdb2009-06-30 11:15:34 -07004122 return URLUtil.composeSearchUrl(query, QuickSearch_G, QUERY_PLACE_HOLDER);
Satish Sampath565505b2009-05-29 15:37:27 +01004123 case SHORTCUT_WIKIPEDIA_SEARCH:
4124 return URLUtil.composeSearchUrl(query, QuickSearch_W, QUERY_PLACE_HOLDER);
4125 case SHORTCUT_DICTIONARY_SEARCH:
4126 return URLUtil.composeSearchUrl(query, QuickSearch_D, QUERY_PLACE_HOLDER);
4127 case SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH:
The Android Open Source Project0c908882009-03-03 19:32:16 -08004128 // FIXME: we need location in this case
Satish Sampath565505b2009-05-29 15:37:27 +01004129 return URLUtil.composeSearchUrl(query, QuickSearch_L, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004130 }
4131 }
4132 } else {
Dan Egnor5ee906c2009-11-18 12:11:49 -08004133 if (Patterns.WEB_URL.matcher(inUrl).matches()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08004134 return URLUtil.guessUrl(inUrl);
4135 }
4136 }
4137
4138 Browser.addSearchUrl(mResolver, inUrl);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07004139 return URLUtil.composeSearchUrl(inUrl, QuickSearch_G, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004140 }
4141
Ben Murdochbff2d602009-07-01 20:19:05 +01004142 /* package */ void setShouldShowErrorConsole(boolean flag) {
4143 if (flag == mShouldShowErrorConsole) {
4144 // Nothing to do.
4145 return;
4146 }
Leon Scroggins IIIa9e35b62010-09-16 15:30:15 -04004147 Tab t = mTabControl.getCurrentTab();
4148 if (t == null) {
4149 // There is no current tab so we cannot toggle the error console
4150 return;
4151 }
Ben Murdochbff2d602009-07-01 20:19:05 +01004152
4153 mShouldShowErrorConsole = flag;
4154
Leon Scroggins IIIa9e35b62010-09-16 15:30:15 -04004155 ErrorConsoleView errorConsole = t.getErrorConsole(true);
Ben Murdochbff2d602009-07-01 20:19:05 +01004156
4157 if (flag) {
4158 // Setting the show state of the console will cause it's the layout to be inflated.
4159 if (errorConsole.numberOfErrors() > 0) {
4160 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
4161 } else {
4162 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
4163 }
4164
4165 // Now we can add it to the main view.
4166 mErrorConsoleContainer.addView(errorConsole,
Romain Guy15b8ec62010-01-08 15:06:43 -08004167 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
Ben Murdochbff2d602009-07-01 20:19:05 +01004168 ViewGroup.LayoutParams.WRAP_CONTENT));
4169 } else {
4170 mErrorConsoleContainer.removeView(errorConsole);
4171 }
4172
4173 }
4174
Grace Kloba22ac16e2009-10-07 18:00:23 -07004175 boolean shouldShowErrorConsole() {
4176 return mShouldShowErrorConsole;
4177 }
4178
Andrei Popescu163ab742009-10-20 17:58:23 +01004179 private void setStatusBarVisibility(boolean visible) {
4180 int flag = visible ? 0 : WindowManager.LayoutParams.FLAG_FULLSCREEN;
4181 getWindow().setFlags(flag, WindowManager.LayoutParams.FLAG_FULLSCREEN);
4182 }
4183
Andrei Popescu56199cc2010-01-12 22:39:16 +00004184
4185 private void sendNetworkType(String type, String subtype) {
4186 WebView w = mTabControl.getCurrentWebView();
4187 if (w != null) {
4188 w.setNetworkType(type, subtype);
4189 }
4190 }
4191
Grace Klobaeb6eef42009-09-15 17:56:32 -07004192 final static int LOCK_ICON_UNSECURE = 0;
4193 final static int LOCK_ICON_SECURE = 1;
4194 final static int LOCK_ICON_MIXED = 2;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004195
The Android Open Source Project0c908882009-03-03 19:32:16 -08004196 private BrowserSettings mSettings;
4197 private TabControl mTabControl;
4198 private ContentResolver mResolver;
4199 private FrameLayout mContentView;
Andrei Popescuadc008d2009-06-26 14:11:30 +01004200 private View mCustomView;
4201 private FrameLayout mCustomViewContainer;
Andrei Popescuc9b55562009-07-07 10:51:15 +01004202 private WebChromeClient.CustomViewCallback mCustomViewCallback;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004203
4204 // FIXME, temp address onPrepareMenu performance problem. When we move everything out of
4205 // view, we should rewrite this.
4206 private int mCurrentMenuState = 0;
4207 private int mMenuState = R.id.MAIN_MENU;
Andrei Popescuadc008d2009-06-26 14:11:30 +01004208 private int mOldMenuState = EMPTY_MENU;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004209 private static final int EMPTY_MENU = -1;
4210 private Menu mMenu;
4211
The Android Open Source Project0c908882009-03-03 19:32:16 -08004212 // Used to prevent chording to result in firing two shortcuts immediately
4213 // one after another. Fixes bug 1211714.
4214 boolean mCanChord;
4215
4216 private boolean mInLoad;
4217 private boolean mIsNetworkUp;
Ben Murdochb7cc8b42009-09-28 10:59:09 +01004218 private boolean mDidStopLoad;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004219
Cary Clark1f10cbf2010-03-22 11:45:23 -04004220 /* package */ boolean mActivityInPause = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004221
4222 private boolean mMenuIsDown;
4223
The Android Open Source Project0c908882009-03-03 19:32:16 -08004224 private static boolean mInTrace;
4225
4226 // Performance probe
4227 private static final int[] SYSTEM_CPU_FORMAT = new int[] {
4228 Process.PROC_SPACE_TERM | Process.PROC_COMBINE,
4229 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 1: user time
4230 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 2: nice time
4231 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 3: sys time
4232 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 4: idle time
4233 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 5: iowait time
4234 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 6: irq time
4235 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG // 7: softirq time
4236 };
4237
4238 private long mStart;
4239 private long mProcessStart;
4240 private long mUserStart;
4241 private long mSystemStart;
4242 private long mIdleStart;
4243 private long mIrqStart;
4244
4245 private long mUiStart;
4246
4247 private Drawable mMixLockIcon;
4248 private Drawable mSecLockIcon;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004249
4250 /* hold a ref so we can auto-cancel if necessary */
4251 private AlertDialog mAlertDialog;
4252
The Android Open Source Project0c908882009-03-03 19:32:16 -08004253 // The up-to-date URL and title (these can be different from those stored
4254 // in WebView, since it takes some time for the information in WebView to
4255 // get updated)
4256 private String mUrl;
4257 private String mTitle;
4258
4259 // As PageInfo has different style for landscape / portrait, we have
4260 // to re-open it when configuration changed
4261 private AlertDialog mPageInfoDialog;
Grace Kloba22ac16e2009-10-07 18:00:23 -07004262 private Tab mPageInfoView;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004263 // If the Page-Info dialog is launched from the SSL-certificate-on-error
4264 // dialog, we should not just dismiss it, but should get back to the
4265 // SSL-certificate-on-error dialog. This flag is used to store this state
Leon Scrogginsc7b92f82010-01-11 18:17:31 -05004266 private boolean mPageInfoFromShowSSLCertificateOnError;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004267
4268 // as SSLCertificateOnError has different style for landscape / portrait,
4269 // we have to re-open it when configuration changed
4270 private AlertDialog mSSLCertificateOnErrorDialog;
4271 private WebView mSSLCertificateOnErrorView;
4272 private SslErrorHandler mSSLCertificateOnErrorHandler;
4273 private SslError mSSLCertificateOnErrorError;
4274
4275 // as SSLCertificate has different style for landscape / portrait, we
4276 // have to re-open it when configuration changed
4277 private AlertDialog mSSLCertificateDialog;
Grace Kloba22ac16e2009-10-07 18:00:23 -07004278 private Tab mSSLCertificateView;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004279
4280 // as HttpAuthentication has different style for landscape / portrait, we
4281 // have to re-open it when configuration changed
4282 private AlertDialog mHttpAuthenticationDialog;
4283 private HttpAuthHandler mHttpAuthHandler;
4284
4285 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_PARAMS =
4286 new FrameLayout.LayoutParams(
Romain Guy15b8ec62010-01-08 15:06:43 -08004287 ViewGroup.LayoutParams.MATCH_PARENT,
4288 ViewGroup.LayoutParams.MATCH_PARENT);
Andrei Popescuadc008d2009-06-26 14:11:30 +01004289 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_GRAVITY_CENTER =
4290 new FrameLayout.LayoutParams(
Romain Guy15b8ec62010-01-08 15:06:43 -08004291 ViewGroup.LayoutParams.MATCH_PARENT,
4292 ViewGroup.LayoutParams.MATCH_PARENT,
Andrei Popescuadc008d2009-06-26 14:11:30 +01004293 Gravity.CENTER);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07004294 // Google search
4295 final static String QuickSearch_G = "http://www.google.com/m?q=%s";
The Android Open Source Project0c908882009-03-03 19:32:16 -08004296 // Wikipedia search
4297 final static String QuickSearch_W = "http://en.wikipedia.org/w/index.php?search=%s&go=Go";
4298 // Dictionary search
4299 final static String QuickSearch_D = "http://dictionary.reference.com/search?q=%s";
4300 // Google Mobile Local search
4301 final static String QuickSearch_L = "http://www.google.com/m/search?site=local&q=%s&near=mountain+view";
4302
4303 final static String QUERY_PLACE_HOLDER = "%s";
4304
4305 // "source" parameter for Google search through search key
4306 final static String GOOGLE_SEARCH_SOURCE_SEARCHKEY = "browser-key";
4307 // "source" parameter for Google search through goto menu
4308 final static String GOOGLE_SEARCH_SOURCE_GOTO = "browser-goto";
4309 // "source" parameter for Google search through simplily type
4310 final static String GOOGLE_SEARCH_SOURCE_TYPE = "browser-type";
4311 // "source" parameter for Google search suggested by the browser
4312 final static String GOOGLE_SEARCH_SOURCE_SUGGEST = "browser-suggest";
4313 // "source" parameter for Google search from unknown source
4314 final static String GOOGLE_SEARCH_SOURCE_UNKNOWN = "unknown";
4315
4316 private final static String LOGTAG = "browser";
4317
The Android Open Source Project0c908882009-03-03 19:32:16 -08004318 private String mLastEnteredUrl;
4319
4320 private PowerManager.WakeLock mWakeLock;
4321 private final static int WAKELOCK_TIMEOUT = 5 * 60 * 1000; // 5 minutes
4322
4323 private Toast mStopToast;
4324
Leon Scroggins571b3762010-05-26 10:25:01 -04004325 private TitleBarBase mTitleBar;
Michael Kolba2b2ba82010-08-04 17:54:03 -07004326 private TabBar mTabBar;
Leon Scroggins81db3662009-06-04 17:45:11 -04004327
Ben Murdochbff2d602009-07-01 20:19:05 +01004328 private LinearLayout mErrorConsoleContainer = null;
4329 private boolean mShouldShowErrorConsole = false;
4330
The Android Open Source Project0c908882009-03-03 19:32:16 -08004331 // As the ids are dynamically created, we can't guarantee that they will
4332 // be in sequence, so this static array maps ids to a window number.
4333 final static private int[] WINDOW_SHORTCUT_ID_ARRAY =
4334 { R.id.window_one_menu_id, R.id.window_two_menu_id, R.id.window_three_menu_id,
4335 R.id.window_four_menu_id, R.id.window_five_menu_id, R.id.window_six_menu_id,
4336 R.id.window_seven_menu_id, R.id.window_eight_menu_id };
4337
4338 // monitor platform changes
4339 private IntentFilter mNetworkStateChangedFilter;
4340 private BroadcastReceiver mNetworkStateIntentReceiver;
4341
Bjorn Bringerta7611812010-03-24 11:12:02 +00004342 private SystemAllowGeolocationOrigins mSystemAllowGeolocationOrigins;
4343
The Android Open Source Project0c908882009-03-03 19:32:16 -08004344 // activity requestCode
Nicolas Roard78a98e42009-05-11 13:34:17 +01004345 final static int COMBO_PAGE = 1;
Nicolas Roard78a98e42009-05-11 13:34:17 +01004346 final static int PREFERENCES_PAGE = 3;
Leon Scroggins8d5fa432009-10-02 15:55:59 -04004347 final static int FILE_SELECTED = 4;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004348
Andrei Popescu540035d2009-09-18 18:59:20 +01004349 // the default <video> poster
4350 private Bitmap mDefaultVideoPoster;
4351 // the video progress view
4352 private View mVideoProgressView;
4353
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004354 /**
4355 * A UrlData class to abstract how the content will be set to WebView.
4356 * This base class uses loadUrl to show the content.
4357 */
Leon Scroggins6eac63e2010-03-15 18:19:14 -04004358 /* package */ static class UrlData {
Grace Kloba068e48b2010-01-26 18:11:27 -08004359 final String mUrl;
4360 final Map<String, String> mHeaders;
Leon Scroggins58d56c62010-01-28 15:12:40 -05004361 final Intent mVoiceIntent;
Grace Kloba60e095c2009-06-16 11:50:55 -07004362
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004363 UrlData(String url) {
4364 this.mUrl = url;
Grace Kloba068e48b2010-01-26 18:11:27 -08004365 this.mHeaders = null;
Leon Scroggins58d56c62010-01-28 15:12:40 -05004366 this.mVoiceIntent = null;
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004367 }
Grace Kloba60e095c2009-06-16 11:50:55 -07004368
Leon Scroggins58d56c62010-01-28 15:12:40 -05004369 UrlData(String url, Map<String, String> headers, Intent intent) {
Grace Kloba068e48b2010-01-26 18:11:27 -08004370 this.mUrl = url;
4371 this.mHeaders = headers;
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -05004372 if (RecognizerResultsIntent.ACTION_VOICE_SEARCH_RESULTS
4373 .equals(intent.getAction())) {
Leon Scroggins58d56c62010-01-28 15:12:40 -05004374 this.mVoiceIntent = intent;
4375 } else {
4376 this.mVoiceIntent = null;
4377 }
Grace Kloba60e095c2009-06-16 11:50:55 -07004378 }
4379
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004380 boolean isEmpty() {
Leon Scroggins58d56c62010-01-28 15:12:40 -05004381 return mVoiceIntent == null && (mUrl == null || mUrl.length() == 0);
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004382 }
4383
Leon Scroggins92472e82010-02-17 16:32:28 -05004384 /**
4385 * Load this UrlData into the given Tab. Use loadUrlDataIn to update
4386 * the title bar as well.
4387 */
Leon Scroggins58d56c62010-01-28 15:12:40 -05004388 public void loadIn(Tab t) {
4389 if (mVoiceIntent != null) {
4390 t.activateVoiceSearchMode(mVoiceIntent);
4391 } else {
4392 t.getWebView().loadUrl(mUrl, mHeaders);
4393 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004394 }
4395 };
4396
Leon Scroggins1f005d32009-08-10 17:36:42 -04004397 /* package */ static final UrlData EMPTY_URL_DATA = new UrlData(null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004398}