blob: 40ada94b11a7153035a44320ae737e57f68af30d [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
The Android Open Source Project0c908882009-03-03 19:32:16 -080019import android.app.Activity;
The Android Open Source Project0c908882009-03-03 19:32:16 -080020import android.app.AlertDialog;
21import android.app.ProgressDialog;
22import android.app.SearchManager;
23import android.content.ActivityNotFoundException;
24import android.content.BroadcastReceiver;
Dianne Hackborn80f32622010-08-05 14:17:53 -070025import android.content.ClipboardManager;
The Android Open Source Project0c908882009-03-03 19:32:16 -080026import android.content.ComponentName;
Leon Scroggins58d56c62010-01-28 15:12:40 -050027import android.content.ContentProvider;
28import android.content.ContentProviderClient;
The Android Open Source Project0c908882009-03-03 19:32:16 -080029import android.content.ContentResolver;
Leon Scrogginsb6b7f9e2009-06-18 12:05:28 -040030import android.content.ContentUris;
The Android Open Source Project0c908882009-03-03 19:32:16 -080031import android.content.ContentValues;
32import android.content.Context;
33import android.content.DialogInterface;
34import android.content.Intent;
35import android.content.IntentFilter;
Grace Klobab4da0ad2009-05-14 14:45:40 -070036import android.content.pm.PackageInfo;
The Android Open Source Project0c908882009-03-03 19:32:16 -080037import android.content.pm.PackageManager;
38import android.content.pm.ResolveInfo;
The Android Open Source Project0c908882009-03-03 19:32:16 -080039import android.content.res.Configuration;
40import android.content.res.Resources;
41import android.database.Cursor;
The Android Open Source Project0c908882009-03-03 19:32:16 -080042import android.graphics.Bitmap;
Andrei Popescu540035d2009-09-18 18:59:20 +010043import android.graphics.BitmapFactory;
The Android Open Source Project0c908882009-03-03 19:32:16 -080044import android.graphics.Canvas;
The Android Open Source Project0c908882009-03-03 19:32:16 -080045import android.graphics.Picture;
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -040046import android.graphics.PixelFormat;
The Android Open Source Project0c908882009-03-03 19:32:16 -080047import android.graphics.drawable.Drawable;
The Android Open Source Project0c908882009-03-03 19:32:16 -080048import android.net.ConnectivityManager;
Andrei Popescu56199cc2010-01-12 22:39:16 +000049import android.net.NetworkInfo;
The Android Open Source Project0c908882009-03-03 19:32:16 -080050import android.net.Uri;
51import android.net.WebAddress;
The Android Open Source Project0c908882009-03-03 19:32:16 -080052import android.net.http.SslCertificate;
53import android.net.http.SslError;
54import android.os.AsyncTask;
55import android.os.Bundle;
56import android.os.Debug;
57import android.os.Environment;
58import android.os.Handler;
The Android Open Source Project0c908882009-03-03 19:32:16 -080059import android.os.Message;
60import android.os.PowerManager;
61import android.os.Process;
The Android Open Source Project0c908882009-03-03 19:32:16 -080062import android.os.SystemClock;
The Android Open Source Project0c908882009-03-03 19:32:16 -080063import android.provider.Browser;
Cary Clark5e335a32009-09-22 14:53:11 -040064import android.provider.ContactsContract;
Michael Kolba2b2ba82010-08-04 17:54:03 -070065import android.provider.ContactsContract.Intents.Insert;
The Android Open Source Project0c908882009-03-03 19:32:16 -080066import android.provider.Downloads;
67import android.provider.MediaStore;
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -050068import android.speech.RecognizerResultsIntent;
The Android Open Source Project0c908882009-03-03 19:32:16 -080069import android.text.TextUtils;
70import android.text.format.DateFormat;
The Android Open Source Project0c908882009-03-03 19:32:16 -080071import android.util.Log;
Dianne Hackborn385effd2010-02-24 20:03:04 -080072import android.util.Patterns;
The Android Open Source Project0c908882009-03-03 19:32:16 -080073import android.view.ContextMenu;
Michael Kolba2b2ba82010-08-04 17:54:03 -070074import android.view.ContextMenu.ContextMenuInfo;
The Android Open Source Project0c908882009-03-03 19:32:16 -080075import android.view.Gravity;
76import android.view.KeyEvent;
77import android.view.LayoutInflater;
78import android.view.Menu;
79import android.view.MenuInflater;
80import android.view.MenuItem;
Michael Kolba2b2ba82010-08-04 17:54:03 -070081import android.view.MenuItem.OnMenuItemClickListener;
The Android Open Source Project0c908882009-03-03 19:32:16 -080082import android.view.View;
83import android.view.ViewGroup;
84import android.view.Window;
85import android.view.WindowManager;
Svetoslav Ganov2b345992010-05-06 06:13:54 -070086import android.view.accessibility.AccessibilityManager;
The Android Open Source Project0c908882009-03-03 19:32:16 -080087import android.webkit.CookieManager;
88import android.webkit.CookieSyncManager;
89import android.webkit.DownloadListener;
90import android.webkit.HttpAuthHandler;
Grace Klobab4da0ad2009-05-14 14:45:40 -070091import android.webkit.PluginManager;
The Android Open Source Project0c908882009-03-03 19:32:16 -080092import android.webkit.SslErrorHandler;
93import android.webkit.URLUtil;
Leon Clarkecb6cc862009-09-29 18:35:13 +010094import android.webkit.ValueCallback;
The Android Open Source Project0c908882009-03-03 19:32:16 -080095import android.webkit.WebChromeClient;
96import android.webkit.WebHistoryItem;
97import android.webkit.WebIconDatabase;
98import android.webkit.WebView;
The Android Open Source Project0c908882009-03-03 19:32:16 -080099import android.widget.EditText;
100import android.widget.FrameLayout;
101import android.widget.LinearLayout;
102import android.widget.TextView;
103import android.widget.Toast;
104
Michael Kolba2b2ba82010-08-04 17:54:03 -0700105import com.android.browser.ScrollWebView.ScrollListener;
Bjorn Bringert10d1cca2010-02-10 14:22:12 +0000106import com.android.common.Search;
Leon Scroggins1fe13a52010-02-09 15:31:26 -0500107import com.android.common.speech.LoggingEvents;
Dan Egnor5ee906c2009-11-18 12:11:49 -0800108
Leon Scrogginsb6b7f9e2009-06-18 12:05:28 -0400109import java.io.ByteArrayOutputStream;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800110import java.io.File;
Ben Murdoch4f75ba22009-10-27 11:48:28 +0000111import java.io.IOException;
112import java.io.InputStream;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800113import java.net.MalformedURLException;
Dianne Hackborn99189432009-06-17 18:06:18 -0700114import java.net.URISyntaxException;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800115import java.net.URL;
116import java.net.URLEncoder;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800117import java.util.Date;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800118import java.util.HashMap;
Andrei Popescu30995e72010-02-09 16:59:58 +0000119import java.util.HashSet;
Grace Kloba00f54c52010-01-27 14:53:51 -0800120import java.util.Iterator;
Andrei Popescu30995e72010-02-09 16:59:58 +0000121import java.util.List;
Grace Kloba068e48b2010-01-26 18:11:27 -0800122import java.util.Map;
Andrei Popescu30995e72010-02-09 16:59:58 +0000123import java.util.Set;
Michael Kolbfe251992010-07-08 15:41:55 -0700124import java.util.Vector;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800125import java.util.regex.Matcher;
126import java.util.regex.Pattern;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800127
128public class BrowserActivity extends Activity
Shimeng (Simon) Wang98d5fce2010-03-16 13:23:39 -0700129 implements View.OnCreateContextMenuListener, DownloadListener {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800130
Dave Bort31a6d1c2009-04-13 15:56:49 -0700131 /* Define some aliases to make these debugging flags easier to refer to.
132 * This file imports android.provider.Browser, so we can't just refer to "Browser.DEBUG".
133 */
134 private final static boolean DEBUG = com.android.browser.Browser.DEBUG;
135 private final static boolean LOGV_ENABLED = com.android.browser.Browser.LOGV_ENABLED;
136 private final static boolean LOGD_ENABLED = com.android.browser.Browser.LOGD_ENABLED;
137
Satish Sampath565505b2009-05-29 15:37:27 +0100138 // These are single-character shortcuts for searching popular sources.
139 private static final int SHORTCUT_INVALID = 0;
140 private static final int SHORTCUT_GOOGLE_SEARCH = 1;
141 private static final int SHORTCUT_WIKIPEDIA_SEARCH = 2;
142 private static final int SHORTCUT_DICTIONARY_SEARCH = 3;
143 private static final int SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH = 4;
144
Cary Clarka9771242009-08-11 16:42:26 -0400145 private static class ClearThumbnails extends AsyncTask<File, Void, Void> {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800146 @Override
147 public Void doInBackground(File... files) {
148 if (files != null) {
149 for (File f : files) {
Cary Clarkd6be1752009-08-12 12:56:42 -0400150 if (!f.delete()) {
151 Log.e(LOGTAG, f.getPath() + " was not deleted");
152 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800153 }
154 }
155 return null;
156 }
157 }
158
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400159 /**
160 * This layout holds everything you see below the status bar, including the
161 * error console, the custom view container, and the webviews.
162 */
163 private FrameLayout mBrowserFrameLayout;
Leon Scroggins81db3662009-06-04 17:45:11 -0400164
Leon Scrogginsd746a942010-05-19 13:21:44 -0400165 private boolean mXLargeScreenSize;
166
Grace Kloba22ac16e2009-10-07 18:00:23 -0700167 @Override
168 public void onCreate(Bundle icicle) {
Dave Bort31a6d1c2009-04-13 15:56:49 -0700169 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800170 Log.v(LOGTAG, this + " onStart");
171 }
172 super.onCreate(icicle);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800173 // test the browser in OpenGL
174 // requestWindowFeature(Window.FEATURE_OPENGL);
175
Mike Reedd334bf52010-01-26 15:21:44 -0500176 // enable this to test the browser in 32bit
177 if (false) {
178 getWindow().setFormat(PixelFormat.RGBX_8888);
179 BitmapFactory.setDefaultConfig(Bitmap.Config.ARGB_8888);
180 }
181
Svetoslav Ganov2b345992010-05-06 06:13:54 -0700182 if (AccessibilityManager.getInstance(this).isEnabled()) {
183 setDefaultKeyMode(DEFAULT_KEYS_DISABLE);
184 } else {
185 setDefaultKeyMode(DEFAULT_KEYS_SEARCH_LOCAL);
186 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800187
188 mResolver = getContentResolver();
189
Grace Kloba0923d692009-09-23 21:37:25 -0700190 // If this was a web search request, pass it on to the default web
191 // search provider and finish this activity.
192 if (handleWebSearchIntent(getIntent())) {
193 finish();
194 return;
195 }
196
The Android Open Source Project0c908882009-03-03 19:32:16 -0800197 mSecLockIcon = Resources.getSystem().getDrawable(
198 android.R.drawable.ic_secure);
199 mMixLockIcon = Resources.getSystem().getDrawable(
200 android.R.drawable.ic_partial_secure);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800201
Leon Scroggins81db3662009-06-04 17:45:11 -0400202 FrameLayout frameLayout = (FrameLayout) getWindow().getDecorView()
203 .findViewById(com.android.internal.R.id.content);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400204 mBrowserFrameLayout = (FrameLayout) LayoutInflater.from(this)
205 .inflate(R.layout.custom_screen, null);
206 mContentView = (FrameLayout) mBrowserFrameLayout.findViewById(
207 R.id.main_content);
208 mErrorConsoleContainer = (LinearLayout) mBrowserFrameLayout
209 .findViewById(R.id.error_console);
210 mCustomViewContainer = (FrameLayout) mBrowserFrameLayout
211 .findViewById(R.id.fullscreen_custom_content);
212 frameLayout.addView(mBrowserFrameLayout, COVER_SCREEN_PARAMS);
Leon Scrogginsd746a942010-05-19 13:21:44 -0400213 mXLargeScreenSize = (getResources().getConfiguration().screenLayout
214 & Configuration.SCREENLAYOUT_SIZE_MASK)
215 == Configuration.SCREENLAYOUT_SIZE_XLARGE;
Michael Kolbe0a36662010-06-29 10:37:12 -0700216
Michael Kolbfe251992010-07-08 15:41:55 -0700217 // Create the tab control and our initial tab
218 mTabControl = new TabControl(this);
Leon Scrogginsd746a942010-05-19 13:21:44 -0400219 if (mXLargeScreenSize) {
Michael Kolba2b2ba82010-08-04 17:54:03 -0700220 mTitleBar = new TitleBarXLarge(this);
221 mTitleBar.setProgress(100);
222 mFakeTitleBar = new TitleBarXLarge(this);
223 mTabBar = new TabBar(this, mTabControl, (TitleBarXLarge) mFakeTitleBar);
Leon Scrogginsd746a942010-05-19 13:21:44 -0400224 LinearLayout layout = (LinearLayout) mBrowserFrameLayout.
225 findViewById(R.id.vertical_layout);
Michael Kolba2b2ba82010-08-04 17:54:03 -0700226 layout.addView(mTabBar, 0, new LinearLayout.LayoutParams(
Leon Scrogginsd746a942010-05-19 13:21:44 -0400227 ViewGroup.LayoutParams.MATCH_PARENT,
228 ViewGroup.LayoutParams.WRAP_CONTENT));
229 } else {
Leon Scroggins571b3762010-05-26 10:25:01 -0400230 mTitleBar = new TitleBar(this);
Leon Scrogginsd746a942010-05-19 13:21:44 -0400231 // mTitleBar will be always be shown in the fully loaded mode on
232 // phone
233 mTitleBar.setProgress(100);
234 // Fake title bar is not needed in xlarge layout
235 mFakeTitleBar = new TitleBar(this);
236 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800237
The Android Open Source Project0c908882009-03-03 19:32:16 -0800238 // Open the icon database and retain all the bookmark urls for favicons
239 retainIconsOnStartup();
240
241 // Keep a settings instance handy.
242 mSettings = BrowserSettings.getInstance();
243 mSettings.setTabControl(mTabControl);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800244
245 PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
246 mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Browser");
247
Patrick Scott6adacc92010-03-05 08:24:51 -0500248 // Find out if the network is currently up.
249 ConnectivityManager cm = (ConnectivityManager) getSystemService(
250 Context.CONNECTIVITY_SERVICE);
251 NetworkInfo info = cm.getActiveNetworkInfo();
252 if (info != null) {
253 mIsNetworkUp = info.isAvailable();
254 }
255
Grace Klobaa34f6862009-07-31 16:28:17 -0700256 /* enables registration for changes in network status from
257 http stack */
258 mNetworkStateChangedFilter = new IntentFilter();
259 mNetworkStateChangedFilter.addAction(
260 ConnectivityManager.CONNECTIVITY_ACTION);
261 mNetworkStateIntentReceiver = new BroadcastReceiver() {
262 @Override
263 public void onReceive(Context context, Intent intent) {
264 if (intent.getAction().equals(
265 ConnectivityManager.CONNECTIVITY_ACTION)) {
Andrei Popescue4c98462010-02-19 15:44:13 +0000266
267 NetworkInfo info = intent.getParcelableExtra(
268 ConnectivityManager.EXTRA_NETWORK_INFO);
269 String typeName = info.getTypeName();
270 String subtypeName = info.getSubtypeName();
271 sendNetworkType(typeName.toLowerCase(),
272 (subtypeName != null ? subtypeName.toLowerCase() : ""));
273
274 onNetworkToggle(info.isAvailable());
Grace Klobaa34f6862009-07-31 16:28:17 -0700275 }
276 }
277 };
278
Grace Kloba615c6c92009-08-03 10:22:44 -0700279 IntentFilter filter = new IntentFilter(Intent.ACTION_PACKAGE_ADDED);
280 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
281 filter.addDataScheme("package");
282 mPackageInstallationReceiver = new BroadcastReceiver() {
283 @Override
284 public void onReceive(Context context, Intent intent) {
285 final String action = intent.getAction();
286 final String packageName = intent.getData()
287 .getSchemeSpecificPart();
288 final boolean replacing = intent.getBooleanExtra(
289 Intent.EXTRA_REPLACING, false);
290 if (Intent.ACTION_PACKAGE_REMOVED.equals(action) && replacing) {
291 // if it is replacing, refreshPlugins() when adding
292 return;
293 }
Andrei Popescu30995e72010-02-09 16:59:58 +0000294
295 if (sGoogleApps.contains(packageName)) {
296 BrowserActivity.this.packageChanged(packageName,
297 Intent.ACTION_PACKAGE_ADDED.equals(action));
298 }
299
Grace Kloba615c6c92009-08-03 10:22:44 -0700300 PackageManager pm = BrowserActivity.this.getPackageManager();
301 PackageInfo pkgInfo = null;
302 try {
303 pkgInfo = pm.getPackageInfo(packageName,
304 PackageManager.GET_PERMISSIONS);
305 } catch (PackageManager.NameNotFoundException e) {
306 return;
307 }
308 if (pkgInfo != null) {
309 String permissions[] = pkgInfo.requestedPermissions;
310 if (permissions == null) {
311 return;
312 }
313 boolean permissionOk = false;
314 for (String permit : permissions) {
315 if (PluginManager.PLUGIN_PERMISSION.equals(permit)) {
316 permissionOk = true;
317 break;
318 }
319 }
320 if (permissionOk) {
321 PluginManager.getInstance(BrowserActivity.this)
Grace Klobae56a0f22010-05-26 17:31:02 -0700322 .refreshPlugins(true);
Grace Kloba615c6c92009-08-03 10:22:44 -0700323 }
324 }
325 }
326 };
327 registerReceiver(mPackageInstallationReceiver, filter);
328
The Android Open Source Project0c908882009-03-03 19:32:16 -0800329 if (!mTabControl.restoreState(icicle)) {
330 // clear up the thumbnail directory if we can't restore the state as
331 // none of the files in the directory are referenced any more.
332 new ClearThumbnails().execute(
333 mTabControl.getThumbnailDir().listFiles());
Grace Klobaaab3f092009-07-30 12:29:51 -0700334 // there is no quit on Android. But if we can't restore the state,
335 // we can treat it as a new Browser, remove the old session cookies.
336 CookieManager.getInstance().removeSessionCookie();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800337 final Intent intent = getIntent();
338 final Bundle extra = intent.getExtras();
339 // Create an initial tab.
340 // If the intent is ACTION_VIEW and data is not null, the Browser is
341 // invoked to view the content by another application. In this case,
342 // the tab will be close when exit.
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700343 UrlData urlData = getUrlDataFromIntent(intent);
344
Leon Scroggins58d56c62010-01-28 15:12:40 -0500345 String action = intent.getAction();
Grace Kloba22ac16e2009-10-07 18:00:23 -0700346 final Tab t = mTabControl.createNewTab(
Leon Scroggins58d56c62010-01-28 15:12:40 -0500347 (Intent.ACTION_VIEW.equals(action) &&
348 intent.getData() != null)
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -0500349 || RecognizerResultsIntent.ACTION_VOICE_SEARCH_RESULTS
350 .equals(action),
Elliott Slaughterf0f03952010-07-14 18:10:36 -0700351 intent.getStringExtra(Browser.EXTRA_APPLICATION_ID),
352 urlData.mUrl, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800353 mTabControl.setCurrentTab(t);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800354 attachTabToContentView(t);
355 WebView webView = t.getWebView();
356 if (extra != null) {
357 int scale = extra.getInt(Browser.INITIAL_ZOOM_LEVEL, 0);
358 if (scale > 0 && scale <= 1000) {
359 webView.setInitialScale(scale);
360 }
361 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800362
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700363 if (urlData.isEmpty()) {
Shimeng (Simon) Wang98d5fce2010-03-16 13:23:39 -0700364 loadUrl(webView, mSettings.getHomePage());
The Android Open Source Project0c908882009-03-03 19:32:16 -0800365 } else {
Patrick Scott9d53da02010-02-19 10:19:01 -0500366 loadUrlDataIn(t, urlData);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800367 }
368 } else {
369 // TabControl.restoreState() will create a new tab even if
Leon Scroggins1f005d32009-08-10 17:36:42 -0400370 // restoring the state fails.
The Android Open Source Project0c908882009-03-03 19:32:16 -0800371 attachTabToContentView(mTabControl.getCurrentTab());
372 }
Grace Kloba615c6c92009-08-03 10:22:44 -0700373
Cary Clarkb4b83182010-07-01 12:36:56 -0400374 // Delete old thumbnails to save space
375 File dir = mTabControl.getThumbnailDir();
376 if (dir.exists()) {
377 for (String child : dir.list()) {
378 File f = new File(dir, child);
379 f.delete();
380 }
381 }
382
Feng Qianb3c02da2009-06-29 15:58:08 -0700383 // Read JavaScript flags if it exists.
384 String jsFlags = mSettings.getJsFlags();
385 if (jsFlags.trim().length() != 0) {
386 mTabControl.getCurrentWebView().setJsFlags(jsFlags);
387 }
Andrei Popescu30995e72010-02-09 16:59:58 +0000388 // Work out which packages are installed on the system.
389 getInstalledPackages();
Bjorn Bringerta7611812010-03-24 11:12:02 +0000390
391 // Start watching the default geolocation permissions
392 mSystemAllowGeolocationOrigins
393 = new SystemAllowGeolocationOrigins(getApplicationContext());
394 mSystemAllowGeolocationOrigins.start();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800395 }
396
Michael Kolba2b2ba82010-08-04 17:54:03 -0700397 ScrollListener getScrollListener() {
398 return mTabBar;
399 }
400
Leon Scroggins58d56c62010-01-28 15:12:40 -0500401 /**
402 * Feed the previously stored results strings to the BrowserProvider so that
403 * the SearchDialog will show them instead of the standard searches.
404 * @param result String to show on the editable line of the SearchDialog.
405 */
406 /* package */ void showVoiceSearchResults(String result) {
407 ContentProviderClient client = mResolver.acquireContentProviderClient(
408 Browser.BOOKMARKS_URI);
409 ContentProvider prov = client.getLocalContentProvider();
410 BrowserProvider bp = (BrowserProvider) prov;
411 bp.setQueryResults(mTabControl.getCurrentTab().getVoiceSearchResults());
412 client.release();
413
Leon Scrogginsfbb3f152010-03-09 17:26:56 -0500414 Bundle bundle = createGoogleSearchSourceBundle(
415 GOOGLE_SEARCH_SOURCE_SEARCHKEY);
416 bundle.putBoolean(SearchManager.CONTEXT_IS_VOICE, true);
417 startSearch(result, false, bundle, false);
Leon Scroggins58d56c62010-01-28 15:12:40 -0500418 }
419
The Android Open Source Project0c908882009-03-03 19:32:16 -0800420 @Override
421 protected void onNewIntent(Intent intent) {
Grace Kloba22ac16e2009-10-07 18:00:23 -0700422 Tab current = mTabControl.getCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800423 // When a tab is closed on exit, the current tab index is set to -1.
424 // Reset before proceed as Browser requires the current tab to be set.
425 if (current == null) {
426 // Try to reset the tab in case the index was incorrect.
427 current = mTabControl.getTab(0);
428 if (current == null) {
429 // No tabs at all so just ignore this intent.
430 return;
431 }
432 mTabControl.setCurrentTab(current);
433 attachTabToContentView(current);
434 resetTitleAndIcon(current.getWebView());
435 }
436 final String action = intent.getAction();
437 final int flags = intent.getFlags();
438 if (Intent.ACTION_MAIN.equals(action) ||
439 (flags & Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY) != 0) {
440 // just resume the browser
441 return;
442 }
Leon Scrogginsb8a844d2010-03-18 15:06:15 -0400443 // In case the SearchDialog is open.
444 ((SearchManager) getSystemService(Context.SEARCH_SERVICE))
445 .stopSearch();
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -0500446 boolean activateVoiceSearch = RecognizerResultsIntent
447 .ACTION_VOICE_SEARCH_RESULTS.equals(action);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800448 if (Intent.ACTION_VIEW.equals(action)
449 || Intent.ACTION_SEARCH.equals(action)
450 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
Leon Scroggins58d56c62010-01-28 15:12:40 -0500451 || Intent.ACTION_WEB_SEARCH.equals(action)
452 || activateVoiceSearch) {
Leon Scroggins3b18ce32010-02-08 17:35:59 -0500453 if (current.isInVoiceSearchMode()) {
454 String title = current.getVoiceDisplayTitle();
455 if (title != null && title.equals(intent.getStringExtra(
456 SearchManager.QUERY))) {
457 // The user submitted the same search as the last voice
458 // search, so do nothing.
459 return;
460 }
Leon Scroggins1fe13a52010-02-09 15:31:26 -0500461 if (Intent.ACTION_SEARCH.equals(action)
462 && current.voiceSearchSourceIsGoogle()) {
463 Intent logIntent = new Intent(
464 LoggingEvents.ACTION_LOG_EVENT);
465 logIntent.putExtra(LoggingEvents.EXTRA_EVENT,
466 LoggingEvents.VoiceSearch.QUERY_UPDATED);
467 logIntent.putExtra(
468 LoggingEvents.VoiceSearch.EXTRA_QUERY_UPDATED_VALUE,
469 intent.getDataString());
470 sendBroadcast(logIntent);
471 // Note, onPageStarted will revert the voice title bar
472 // When http://b/issue?id=2379215 is fixed, we should update
473 // the title bar here.
474 }
Leon Scroggins3b18ce32010-02-08 17:35:59 -0500475 }
Satish Sampath565505b2009-05-29 15:37:27 +0100476 // If this was a search request (e.g. search query directly typed into the address bar),
477 // pass it on to the default web search provider.
478 if (handleWebSearchIntent(intent)) {
479 return;
480 }
481
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700482 UrlData urlData = getUrlDataFromIntent(intent);
483 if (urlData.isEmpty()) {
484 urlData = new UrlData(mSettings.getHomePage());
The Android Open Source Project0c908882009-03-03 19:32:16 -0800485 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700486
Grace Klobacc634032009-07-28 15:58:19 -0700487 final String appId = intent
488 .getStringExtra(Browser.EXTRA_APPLICATION_ID);
Leon Scroggins47208682010-04-07 17:59:48 -0400489 if ((Intent.ACTION_VIEW.equals(action)
490 // If a voice search has no appId, it means that it came
491 // from the browser. In that case, reuse the current tab.
492 || (activateVoiceSearch && appId != null))
Grace Klobacc634032009-07-28 15:58:19 -0700493 && !getPackageName().equals(appId)
494 && (flags & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0) {
Grace Kloba22ac16e2009-10-07 18:00:23 -0700495 Tab appTab = mTabControl.getTabFromId(appId);
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700496 if (appTab != null) {
497 Log.i(LOGTAG, "Reusing tab for " + appId);
498 // Dismiss the subwindow if applicable.
499 dismissSubWindow(appTab);
500 // Since we might kill the WebView, remove it from the
501 // content view first.
502 removeTabFromContentView(appTab);
503 // Recreate the main WebView after destroying the old one.
504 // If the WebView has the same original url and is on that
505 // page, it can be reused.
506 boolean needsLoad =
Leon Scroggins6eac63e2010-03-15 18:19:14 -0400507 mTabControl.recreateWebView(appTab, urlData);
Ben Murdochbff2d602009-07-01 20:19:05 +0100508
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700509 if (current != appTab) {
Leon Scroggins1f005d32009-08-10 17:36:42 -0400510 switchToTab(mTabControl.getTabIndex(appTab));
511 if (needsLoad) {
Patrick Scott9d53da02010-02-19 10:19:01 -0500512 loadUrlDataIn(appTab, urlData);
Leon Scroggins1f005d32009-08-10 17:36:42 -0400513 }
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700514 } else {
Leon Scroggins1f005d32009-08-10 17:36:42 -0400515 // If the tab was the current tab, we have to attach
516 // it to the view system again.
517 attachTabToContentView(appTab);
518 if (needsLoad) {
Patrick Scott9d53da02010-02-19 10:19:01 -0500519 loadUrlDataIn(appTab, urlData);
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700520 }
521 }
522 return;
Patrick Scottcd115892009-07-16 09:42:58 -0400523 } else {
524 // No matching application tab, try to find a regular tab
525 // with a matching url.
526 appTab = mTabControl.findUnusedTabWithUrl(urlData.mUrl);
Leon Scroggins25515f82009-08-19 15:31:58 -0400527 if (appTab != null) {
528 if (current != appTab) {
529 switchToTab(mTabControl.getTabIndex(appTab));
530 }
531 // Otherwise, we are already viewing the correct tab.
Patrick Scottcd115892009-07-16 09:42:58 -0400532 } else {
533 // if FLAG_ACTIVITY_BROUGHT_TO_FRONT flag is on, the url
534 // will be opened in a new tab unless we have reached
535 // MAX_TABS. Then the url will be opened in the current
536 // tab. If a new tab is created, it will have "true" for
537 // exit on close.
Leon Scroggins1f005d32009-08-10 17:36:42 -0400538 openTabAndShow(urlData, true, appId);
Patrick Scottcd115892009-07-16 09:42:58 -0400539 }
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700540 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800541 } else {
Grace Kloba638d3f42009-11-23 10:35:04 -0800542 if (!urlData.isEmpty()
543 && urlData.mUrl.startsWith("about:debug")) {
544 if ("about:debug.dom".equals(urlData.mUrl)) {
545 current.getWebView().dumpDomTree(false);
546 } else if ("about:debug.dom.file".equals(urlData.mUrl)) {
547 current.getWebView().dumpDomTree(true);
548 } else if ("about:debug.render".equals(urlData.mUrl)) {
549 current.getWebView().dumpRenderTree(false);
550 } else if ("about:debug.render.file".equals(urlData.mUrl)) {
551 current.getWebView().dumpRenderTree(true);
552 } else if ("about:debug.display".equals(urlData.mUrl)) {
553 current.getWebView().dumpDisplayTree();
Mike Reed9b78e1d2010-01-13 14:40:52 -0800554 } else if (urlData.mUrl.startsWith("about:debug.drag")) {
555 int index = urlData.mUrl.codePointAt(16) - '0';
556 if (index <= 0 || index > 9) {
557 current.getWebView().setDragTracker(null);
558 } else {
559 current.getWebView().setDragTracker(new MeshTracker(index));
560 }
Grace Kloba638d3f42009-11-23 10:35:04 -0800561 } else {
562 mSettings.toggleDebugSettings();
563 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800564 return;
565 }
Leon Scroggins1f005d32009-08-10 17:36:42 -0400566 // Get rid of the subwindow if it exists
567 dismissSubWindow(current);
Leon Scroggins8588d152010-04-15 11:01:53 -0400568 // If the current Tab is being used as an application tab,
569 // remove the association, since the new Intent means that it is
570 // no longer associated with that application.
571 current.setAppId(null);
Patrick Scott9d53da02010-02-19 10:19:01 -0500572 loadUrlDataIn(current, urlData);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800573 }
574 }
575 }
576
Satish Sampath565505b2009-05-29 15:37:27 +0100577 private int parseUrlShortcut(String url) {
578 if (url == null) return SHORTCUT_INVALID;
579
580 // FIXME: quick search, need to be customized by setting
581 if (url.length() > 2 && url.charAt(1) == ' ') {
582 switch (url.charAt(0)) {
583 case 'g': return SHORTCUT_GOOGLE_SEARCH;
584 case 'w': return SHORTCUT_WIKIPEDIA_SEARCH;
585 case 'd': return SHORTCUT_DICTIONARY_SEARCH;
586 case 'l': return SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH;
587 }
588 }
589 return SHORTCUT_INVALID;
590 }
591
592 /**
593 * Launches the default web search activity with the query parameters if the given intent's data
594 * are identified as plain search terms and not URLs/shortcuts.
595 * @return true if the intent was handled and web search activity was launched, false if not.
596 */
597 private boolean handleWebSearchIntent(Intent intent) {
598 if (intent == null) return false;
599
600 String url = null;
601 final String action = intent.getAction();
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -0500602 if (RecognizerResultsIntent.ACTION_VOICE_SEARCH_RESULTS.equals(
603 action)) {
Leon Scroggins58d56c62010-01-28 15:12:40 -0500604 return false;
605 }
Satish Sampath565505b2009-05-29 15:37:27 +0100606 if (Intent.ACTION_VIEW.equals(action)) {
Grace Kloba1e705052009-09-29 13:13:36 -0700607 Uri data = intent.getData();
608 if (data != null) url = data.toString();
Satish Sampath565505b2009-05-29 15:37:27 +0100609 } else if (Intent.ACTION_SEARCH.equals(action)
610 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
611 || Intent.ACTION_WEB_SEARCH.equals(action)) {
612 url = intent.getStringExtra(SearchManager.QUERY);
613 }
Bjorn Bringert04851702009-09-22 10:36:01 +0100614 return handleWebSearchRequest(url, intent.getBundleExtra(SearchManager.APP_DATA),
615 intent.getStringExtra(SearchManager.EXTRA_DATA_KEY));
Satish Sampath565505b2009-05-29 15:37:27 +0100616 }
617
618 /**
619 * Launches the default web search activity with the query parameters if the given url string
620 * was identified as plain search terms and not URL/shortcut.
621 * @return true if the request was handled and web search activity was launched, false if not.
622 */
Bjorn Bringert04851702009-09-22 10:36:01 +0100623 private boolean handleWebSearchRequest(String inUrl, Bundle appData, String extraData) {
Satish Sampath565505b2009-05-29 15:37:27 +0100624 if (inUrl == null) return false;
625
626 // In general, we shouldn't modify URL from Intent.
627 // But currently, we get the user-typed URL from search box as well.
628 String url = fixUrl(inUrl).trim();
629
630 // URLs and site specific search shortcuts are handled by the regular flow of control, so
631 // return early.
Dan Egnor5ee906c2009-11-18 12:11:49 -0800632 if (Patterns.WEB_URL.matcher(url).matches()
Satish Sampathbc5b9f32009-06-04 18:21:40 +0100633 || ACCEPTED_URI_SCHEMA.matcher(url).matches()
Satish Sampath565505b2009-05-29 15:37:27 +0100634 || parseUrlShortcut(url) != SHORTCUT_INVALID) {
635 return false;
636 }
637
Leon Scroggins8d06e362010-03-24 14:45:57 -0400638 final ContentResolver cr = mResolver;
639 final String newUrl = url;
Elliott Slaughterf0f03952010-07-14 18:10:36 -0700640 if (!mTabControl.getCurrentWebView().isPrivateBrowsingEnabled()) {
641 new AsyncTask<Void, Void, Void>() {
642 @Override
643 protected Void doInBackground(Void... unused) {
644 Browser.updateVisitedHistory(cr, newUrl, false);
645 Browser.addSearchUrl(cr, newUrl);
646 return null;
647 }
648 }.execute();
649 }
Satish Sampath565505b2009-05-29 15:37:27 +0100650
651 Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);
652 intent.addCategory(Intent.CATEGORY_DEFAULT);
653 intent.putExtra(SearchManager.QUERY, url);
Satish Sampath15e9f2d2009-06-23 22:29:49 +0100654 if (appData != null) {
655 intent.putExtra(SearchManager.APP_DATA, appData);
656 }
Bjorn Bringert04851702009-09-22 10:36:01 +0100657 if (extraData != null) {
658 intent.putExtra(SearchManager.EXTRA_DATA_KEY, extraData);
659 }
Grace Klobacc634032009-07-28 15:58:19 -0700660 intent.putExtra(Browser.EXTRA_APPLICATION_ID, getPackageName());
Satish Sampath565505b2009-05-29 15:37:27 +0100661 startActivity(intent);
662
663 return true;
664 }
665
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700666 private UrlData getUrlDataFromIntent(Intent intent) {
Leon Scroggins58d56c62010-01-28 15:12:40 -0500667 String url = "";
Grace Kloba068e48b2010-01-26 18:11:27 -0800668 Map<String, String> headers = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800669 if (intent != null) {
670 final String action = intent.getAction();
671 if (Intent.ACTION_VIEW.equals(action)) {
672 url = smartUrlFilter(intent.getData());
673 if (url != null && url.startsWith("content:")) {
674 /* Append mimetype so webview knows how to display */
675 String mimeType = intent.resolveType(getContentResolver());
676 if (mimeType != null) {
677 url += "?" + mimeType;
678 }
679 }
Grace Kloba068e48b2010-01-26 18:11:27 -0800680 if (url != null && url.startsWith("http")) {
Grace Kloba00f54c52010-01-27 14:53:51 -0800681 final Bundle pairs = intent
682 .getBundleExtra(Browser.EXTRA_HEADERS);
Grace Kloba2d508ed2010-01-28 11:39:15 -0800683 if (pairs != null && !pairs.isEmpty()) {
Grace Kloba00f54c52010-01-27 14:53:51 -0800684 Iterator<String> iter = pairs.keySet().iterator();
Grace Kloba068e48b2010-01-26 18:11:27 -0800685 headers = new HashMap<String, String>();
Grace Kloba00f54c52010-01-27 14:53:51 -0800686 while (iter.hasNext()) {
687 String key = iter.next();
688 headers.put(key, pairs.getString(key));
Grace Kloba068e48b2010-01-26 18:11:27 -0800689 }
690 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700691 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800692 } else if (Intent.ACTION_SEARCH.equals(action)
693 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
694 || Intent.ACTION_WEB_SEARCH.equals(action)) {
695 url = intent.getStringExtra(SearchManager.QUERY);
696 if (url != null) {
697 mLastEnteredUrl = url;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800698 // In general, we shouldn't modify URL from Intent.
699 // But currently, we get the user-typed URL from search box as well.
700 url = fixUrl(url);
701 url = smartUrlFilter(url);
Leon Scroggins8d06e362010-03-24 14:45:57 -0400702 final ContentResolver cr = mResolver;
703 final String newUrl = url;
704 new AsyncTask<Void, Void, Void>() {
Michael Kolbe0a36662010-06-29 10:37:12 -0700705 @Override
Leon Scroggins8d06e362010-03-24 14:45:57 -0400706 protected Void doInBackground(Void... unused) {
707 Browser.updateVisitedHistory(cr, newUrl, false);
708 return null;
709 }
710 }.execute();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800711 String searchSource = "&source=android-" + GOOGLE_SEARCH_SOURCE_SUGGEST + "&";
712 if (url.contains(searchSource)) {
713 String source = null;
714 final Bundle appData = intent.getBundleExtra(SearchManager.APP_DATA);
715 if (appData != null) {
Bjorn Bringert10d1cca2010-02-10 14:22:12 +0000716 source = appData.getString(Search.SOURCE);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800717 }
718 if (TextUtils.isEmpty(source)) {
719 source = GOOGLE_SEARCH_SOURCE_UNKNOWN;
720 }
721 url = url.replace(searchSource, "&source=android-"+source+"&");
722 }
723 }
724 }
725 }
Leon Scroggins58d56c62010-01-28 15:12:40 -0500726 return new UrlData(url, headers, intent);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800727 }
Leon Scroggins58d56c62010-01-28 15:12:40 -0500728 /* package */ void showVoiceTitleBar(String title) {
729 mTitleBar.setInVoiceMode(true);
Leon Scroggins58d56c62010-01-28 15:12:40 -0500730 mTitleBar.setDisplayTitle(title);
Michael Kolba2b2ba82010-08-04 17:54:03 -0700731 mFakeTitleBar.setInVoiceMode(true);
732 mFakeTitleBar.setDisplayTitle(title);
Leon Scroggins58d56c62010-01-28 15:12:40 -0500733 }
734 /* package */ void revertVoiceTitleBar() {
735 mTitleBar.setInVoiceMode(false);
Leon Scroggins003a5dd2010-03-10 12:13:14 -0500736 mTitleBar.setDisplayTitle(mUrl);
Michael Kolba2b2ba82010-08-04 17:54:03 -0700737 mFakeTitleBar.setInVoiceMode(false);
738 mFakeTitleBar.setDisplayTitle(mUrl);
Leon Scroggins58d56c62010-01-28 15:12:40 -0500739 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800740 /* package */ static String fixUrl(String inUrl) {
Cary Clark652ff872009-09-10 13:34:44 -0400741 // FIXME: Converting the url to lower case
742 // duplicates functionality in smartUrlFilter().
743 // However, changing all current callers of fixUrl to
744 // call smartUrlFilter in addition may have unwanted
745 // consequences, and is deferred for now.
746 int colon = inUrl.indexOf(':');
747 boolean allLower = true;
748 for (int index = 0; index < colon; index++) {
749 char ch = inUrl.charAt(index);
750 if (!Character.isLetter(ch)) {
751 break;
752 }
753 allLower &= Character.isLowerCase(ch);
754 if (index == colon - 1 && !allLower) {
755 inUrl = inUrl.substring(0, colon).toLowerCase()
756 + inUrl.substring(colon);
757 }
758 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800759 if (inUrl.startsWith("http://") || inUrl.startsWith("https://"))
760 return inUrl;
761 if (inUrl.startsWith("http:") ||
762 inUrl.startsWith("https:")) {
763 if (inUrl.startsWith("http:/") || inUrl.startsWith("https:/")) {
764 inUrl = inUrl.replaceFirst("/", "//");
765 } else inUrl = inUrl.replaceFirst(":", "://");
766 }
767 return inUrl;
768 }
769
Grace Kloba22ac16e2009-10-07 18:00:23 -0700770 @Override
771 protected void onResume() {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800772 super.onResume();
Dave Bort31a6d1c2009-04-13 15:56:49 -0700773 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800774 Log.v(LOGTAG, "BrowserActivity.onResume: this=" + this);
775 }
776
777 if (!mActivityInPause) {
778 Log.e(LOGTAG, "BrowserActivity is already resumed.");
779 return;
780 }
781
Mike Reed7bfa63b2009-05-28 11:08:32 -0400782 mTabControl.resumeCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800783 mActivityInPause = false;
Mike Reed7bfa63b2009-05-28 11:08:32 -0400784 resumeWebViewTimers();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800785
786 if (mWakeLock.isHeld()) {
787 mHandler.removeMessages(RELEASE_WAKELOCK);
788 mWakeLock.release();
789 }
790
The Android Open Source Project0c908882009-03-03 19:32:16 -0800791 registerReceiver(mNetworkStateIntentReceiver,
792 mNetworkStateChangedFilter);
793 WebView.enablePlatformNotifications();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800794 }
795
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400796 /**
797 * Since the actual title bar is embedded in the WebView, and removing it
Leon Scrogginsfe87bd32009-10-06 10:10:00 -0400798 * would change its appearance, use a different TitleBar to show overlayed
799 * at the top of the screen, when the menu is open or the page is loading.
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400800 */
Michael Kolba2b2ba82010-08-04 17:54:03 -0700801 private TitleBarBase mFakeTitleBar;
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400802
803 /**
804 * Keeps track of whether the options menu is open. This is important in
805 * determining whether to show or hide the title bar overlay.
806 */
807 private boolean mOptionsMenuOpen;
808
809 /**
810 * Only meaningful when mOptionsMenuOpen is true. This variable keeps track
811 * of whether the configuration has changed. The first onMenuOpened call
812 * after a configuration change is simply a reopening of the same menu
813 * (i.e. mIconView did not change).
814 */
815 private boolean mConfigChanged;
816
817 /**
818 * Whether or not the options menu is in its smaller, icon menu form. When
819 * true, we want the title bar overlay to be up. When false, we do not.
820 * Only meaningful if mOptionsMenuOpen is true.
821 */
822 private boolean mIconView;
823
Leon Scrogginsa81a7642009-08-31 17:05:41 -0400824 @Override
825 public boolean onMenuOpened(int featureId, Menu menu) {
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400826 if (Window.FEATURE_OPTIONS_PANEL == featureId) {
827 if (mOptionsMenuOpen) {
828 if (mConfigChanged) {
829 // We do not need to make any changes to the state of the
830 // title bar, since the only thing that happened was a
831 // change in orientation
832 mConfigChanged = false;
833 } else {
834 if (mIconView) {
835 // Switching the menu to expanded view, so hide the
836 // title bar.
837 hideFakeTitleBar();
838 mIconView = false;
839 } else {
840 // Switching the menu back to icon view, so show the
841 // title bar once again.
842 showFakeTitleBar();
843 mIconView = true;
844 }
845 }
846 } else {
847 // The options menu is closed, so open it, and show the title
848 showFakeTitleBar();
849 mOptionsMenuOpen = true;
850 mConfigChanged = false;
851 mIconView = true;
852 }
853 }
Leon Scrogginsa81a7642009-08-31 17:05:41 -0400854 return true;
855 }
856
Michael Kolba2b2ba82010-08-04 17:54:03 -0700857 void showFakeTitleBar() {
858 if (!isFakeTitleBarShowing() && mActiveTabsPage == null && !mActivityInPause) {
Grace Kloba847c25b2010-03-30 16:00:26 -0700859 WebView mainView = mTabControl.getCurrentWebView();
860 // if there is no current WebView, don't show the faked title bar;
Grace Kloba65190702010-04-02 23:37:26 -0700861 if (mainView == null) {
Cary Clarka0464552009-09-29 13:00:45 -0400862 return;
863 }
Leon Scroggins79e36d92010-04-29 16:01:46 +0100864 // Do not need to check for null, since the current tab will have
865 // at least a main WebView, or we would have returned above.
Cary Clark01cfcdd2010-06-04 16:36:45 -0400866 if (dialogIsUp()) {
Leon Scroggins79e36d92010-04-29 16:01:46 +0100867 // Do not show the fake title bar, which would cover up the
Cary Clark01cfcdd2010-06-04 16:36:45 -0400868 // find or select dialog.
Leon Scroggins79e36d92010-04-29 16:01:46 +0100869 return;
870 }
Michael Kolba2b2ba82010-08-04 17:54:03 -0700871 if (mXLargeScreenSize) {
872 mContentView.addView(mFakeTitleBar);
873 mTabBar.onShowTitleBar();
874 } else {
875 WindowManager manager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400876
Michael Kolba2b2ba82010-08-04 17:54:03 -0700877 // Add the title bar to the window manager so it can receive
878 // touches
879 // while the menu is up
880 WindowManager.LayoutParams params =
881 new WindowManager.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
882 ViewGroup.LayoutParams.WRAP_CONTENT,
883 WindowManager.LayoutParams.TYPE_APPLICATION,
884 WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
885 PixelFormat.TRANSLUCENT);
886 params.gravity = Gravity.TOP;
887 boolean atTop = mainView.getScrollY() == 0;
888 params.windowAnimations = atTop ? 0 : R.style.TitleBar;
889 manager.addView(mFakeTitleBar, params);
890 }
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400891 }
892 }
893
894 @Override
895 public void onOptionsMenuClosed(Menu menu) {
896 mOptionsMenuOpen = false;
Leon Scrogginsa27ff192009-09-14 12:58:04 -0400897 if (!mInLoad) {
898 hideFakeTitleBar();
899 } else if (!mIconView) {
900 // The page is currently loading, and we are in expanded mode, so
901 // we were not showing the menu. Show it once again. It will be
902 // removed when the page finishes.
903 showFakeTitleBar();
904 }
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400905 }
Grace Kloba22ac16e2009-10-07 18:00:23 -0700906
Michael Kolba2b2ba82010-08-04 17:54:03 -0700907 void stopScrolling() {
908 ((ScrollWebView) mTabControl.getCurrentWebView()).stopScroll();
909 }
910
911 void hideFakeTitleBar() {
912 if (!isFakeTitleBarShowing()) return;
913 if (mXLargeScreenSize) {
914 mContentView.removeView(mFakeTitleBar);
915 mTabBar.onHideTitleBar();
916 } else {
917 WindowManager.LayoutParams params =
918 (WindowManager.LayoutParams) mFakeTitleBar.getLayoutParams();
919 WebView mainView = mTabControl.getCurrentWebView();
920 // Although we decided whether or not to animate based on the
921 // current
922 // scroll position, the scroll position may have changed since the
923 // fake title bar was displayed. Make sure it has the appropriate
924 // animation/lack thereof before removing.
925 params.windowAnimations =
926 mainView != null && mainView.getScrollY() == 0 ? 0 : R.style.TitleBar;
927 WindowManager manager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
928 manager.updateViewLayout(mFakeTitleBar, params);
929 manager.removeView(mFakeTitleBar);
930 }
931 }
932
933 boolean isFakeTitleBarShowing() {
934 return (mFakeTitleBar.getParent() != null);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400935 }
936
The Android Open Source Project0c908882009-03-03 19:32:16 -0800937 /**
Leon Scrogginsc6fa1102009-09-21 10:40:01 -0400938 * Special method for the fake title bar to call when displaying its context
939 * menu, since it is in its own Window, and its parent does not show a
940 * context menu.
941 */
942 /* package */ void showTitleBarContextMenu() {
Cary Clark65f4a3c2009-09-28 17:05:06 -0400943 if (null == mTitleBar.getParent()) {
944 return;
945 }
Leon Scrogginsc6fa1102009-09-21 10:40:01 -0400946 openContextMenu(mTitleBar);
947 }
948
Leon Scrogginsb2b19f52009-10-09 16:10:00 -0400949 @Override
950 public void onContextMenuClosed(Menu menu) {
951 super.onContextMenuClosed(menu);
952 if (mInLoad) {
953 showFakeTitleBar();
954 }
955 }
956
Leon Scrogginsc6fa1102009-09-21 10:40:01 -0400957 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -0800958 * onSaveInstanceState(Bundle map)
959 * onSaveInstanceState is called right before onStop(). The map contains
960 * the saved state.
961 */
Grace Kloba22ac16e2009-10-07 18:00:23 -0700962 @Override
963 protected void onSaveInstanceState(Bundle outState) {
Dave Bort31a6d1c2009-04-13 15:56:49 -0700964 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800965 Log.v(LOGTAG, "BrowserActivity.onSaveInstanceState: this=" + this);
966 }
967 // the default implementation requires each view to have an id. As the
968 // browser handles the state itself and it doesn't use id for the views,
969 // don't call the default implementation. Otherwise it will trigger the
970 // warning like this, "couldn't save which view has focus because the
971 // focused view XXX has no id".
972
973 // Save all the tabs
974 mTabControl.saveState(outState);
975 }
976
Grace Kloba22ac16e2009-10-07 18:00:23 -0700977 @Override
978 protected void onPause() {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800979 super.onPause();
980
981 if (mActivityInPause) {
982 Log.e(LOGTAG, "BrowserActivity is already paused.");
983 return;
984 }
985
Mike Reed7bfa63b2009-05-28 11:08:32 -0400986 mTabControl.pauseCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800987 mActivityInPause = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -0400988 if (mTabControl.getCurrentIndex() >= 0 && !pauseWebViewTimers()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800989 mWakeLock.acquire();
990 mHandler.sendMessageDelayed(mHandler
991 .obtainMessage(RELEASE_WAKELOCK), WAKELOCK_TIMEOUT);
992 }
993
Leon Scrogginsa2ab6a72009-09-11 11:49:52 -0400994 // FIXME: This removes the active tabs page and resets the menu to
995 // MAIN_MENU. A better solution might be to do this work in onNewIntent
996 // but then we would need to save it in onSaveInstanceState and restore
997 // it in onCreate/onRestoreInstanceState
998 if (mActiveTabsPage != null) {
999 removeActiveTabPage(true);
1000 }
1001
The Android Open Source Project0c908882009-03-03 19:32:16 -08001002 cancelStopToast();
1003
1004 // unregister network state listener
1005 unregisterReceiver(mNetworkStateIntentReceiver);
1006 WebView.disablePlatformNotifications();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001007 }
1008
Grace Kloba22ac16e2009-10-07 18:00:23 -07001009 @Override
1010 protected void onDestroy() {
Dave Bort31a6d1c2009-04-13 15:56:49 -07001011 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001012 Log.v(LOGTAG, "BrowserActivity.onDestroy: this=" + this);
1013 }
1014 super.onDestroy();
Grace Kloba0923d692009-09-23 21:37:25 -07001015
Leon Scroggins8d5fa432009-10-02 15:55:59 -04001016 if (mUploadMessage != null) {
1017 mUploadMessage.onReceiveValue(null);
1018 mUploadMessage = null;
1019 }
1020
Grace Kloba0923d692009-09-23 21:37:25 -07001021 if (mTabControl == null) return;
1022
Grace Kloba1fc98a32009-10-21 13:23:08 -07001023 // Remove the fake title bar if it is there
1024 hideFakeTitleBar();
1025
The Android Open Source Project0c908882009-03-03 19:32:16 -08001026 // Remove the current tab and sub window
Grace Kloba22ac16e2009-10-07 18:00:23 -07001027 Tab t = mTabControl.getCurrentTab();
Patrick Scottfb5e77f2009-04-08 19:17:37 -07001028 if (t != null) {
1029 dismissSubWindow(t);
1030 removeTabFromContentView(t);
1031 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001032 // Destroy all the tabs
1033 mTabControl.destroy();
1034 WebIconDatabase.getInstance().close();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001035
Grace Klobab4da0ad2009-05-14 14:45:40 -07001036 unregisterReceiver(mPackageInstallationReceiver);
Bjorn Bringerta7611812010-03-24 11:12:02 +00001037
1038 // Stop watching the default geolocation permissions
1039 mSystemAllowGeolocationOrigins.stop();
1040 mSystemAllowGeolocationOrigins = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001041 }
1042
1043 @Override
1044 public void onConfigurationChanged(Configuration newConfig) {
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04001045 mConfigChanged = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001046 super.onConfigurationChanged(newConfig);
1047
1048 if (mPageInfoDialog != null) {
1049 mPageInfoDialog.dismiss();
1050 showPageInfo(
1051 mPageInfoView,
Leon Scrogginsc7b92f82010-01-11 18:17:31 -05001052 mPageInfoFromShowSSLCertificateOnError);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001053 }
1054 if (mSSLCertificateDialog != null) {
1055 mSSLCertificateDialog.dismiss();
1056 showSSLCertificate(
1057 mSSLCertificateView);
1058 }
1059 if (mSSLCertificateOnErrorDialog != null) {
1060 mSSLCertificateOnErrorDialog.dismiss();
1061 showSSLCertificateOnError(
1062 mSSLCertificateOnErrorView,
1063 mSSLCertificateOnErrorHandler,
1064 mSSLCertificateOnErrorError);
1065 }
1066 if (mHttpAuthenticationDialog != null) {
1067 String title = ((TextView) mHttpAuthenticationDialog
1068 .findViewById(com.android.internal.R.id.alertTitle)).getText()
1069 .toString();
1070 String name = ((TextView) mHttpAuthenticationDialog
1071 .findViewById(R.id.username_edit)).getText().toString();
1072 String password = ((TextView) mHttpAuthenticationDialog
1073 .findViewById(R.id.password_edit)).getText().toString();
1074 int focusId = mHttpAuthenticationDialog.getCurrentFocus()
1075 .getId();
1076 mHttpAuthenticationDialog.dismiss();
1077 showHttpAuthentication(mHttpAuthHandler, null, null, title,
1078 name, password, focusId);
1079 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001080 }
1081
Grace Kloba22ac16e2009-10-07 18:00:23 -07001082 @Override
1083 public void onLowMemory() {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001084 super.onLowMemory();
1085 mTabControl.freeMemory();
1086 }
1087
Cary Clarkff4d92c2010-03-25 11:17:03 -04001088 private void resumeWebViewTimers() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001089 Tab tab = mTabControl.getCurrentTab();
Cary Clarkff4d92c2010-03-25 11:17:03 -04001090 if (tab == null) return; // monkey can trigger this
Grace Kloba22ac16e2009-10-07 18:00:23 -07001091 boolean inLoad = tab.inLoad();
1092 if ((!mActivityInPause && !inLoad) || (mActivityInPause && inLoad)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001093 CookieSyncManager.getInstance().startSync();
Grace Kloba22ac16e2009-10-07 18:00:23 -07001094 WebView w = tab.getWebView();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001095 if (w != null) {
1096 w.resumeTimers();
1097 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001098 }
1099 }
1100
Mike Reed7bfa63b2009-05-28 11:08:32 -04001101 private boolean pauseWebViewTimers() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001102 Tab tab = mTabControl.getCurrentTab();
1103 boolean inLoad = tab.inLoad();
1104 if (mActivityInPause && !inLoad) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001105 CookieSyncManager.getInstance().stopSync();
1106 WebView w = mTabControl.getCurrentWebView();
1107 if (w != null) {
1108 w.pauseTimers();
1109 }
1110 return true;
1111 } else {
1112 return false;
1113 }
1114 }
1115
The Android Open Source Project0c908882009-03-03 19:32:16 -08001116 // Open the icon database and retain all the icons for visited sites.
1117 private void retainIconsOnStartup() {
1118 final WebIconDatabase db = WebIconDatabase.getInstance();
1119 db.open(getDir("icons", 0).getPath());
Leon Scroggins2c0f6112010-03-12 18:09:39 -05001120 Cursor c = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001121 try {
Leon Scroggins2c0f6112010-03-12 18:09:39 -05001122 c = Browser.getAllBookmarks(mResolver);
1123 if (c.moveToFirst()) {
1124 int urlIndex = c.getColumnIndex(Browser.BookmarkColumns.URL);
1125 do {
1126 String url = c.getString(urlIndex);
1127 db.retainIconForPageUrl(url);
1128 } while (c.moveToNext());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001129 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001130 } catch (IllegalStateException e) {
1131 Log.e(LOGTAG, "retainIconsOnStartup", e);
Leon Scroggins2c0f6112010-03-12 18:09:39 -05001132 } finally {
1133 if (c!= null) c.close();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001134 }
1135 }
1136
1137 // Helper method for getting the top window.
1138 WebView getTopWindow() {
1139 return mTabControl.getCurrentTopWebView();
1140 }
1141
Grace Kloba22ac16e2009-10-07 18:00:23 -07001142 TabControl getTabControl() {
1143 return mTabControl;
1144 }
1145
The Android Open Source Project0c908882009-03-03 19:32:16 -08001146 @Override
1147 public boolean onCreateOptionsMenu(Menu menu) {
1148 super.onCreateOptionsMenu(menu);
1149
1150 MenuInflater inflater = getMenuInflater();
1151 inflater.inflate(R.menu.browser, menu);
1152 mMenu = menu;
1153 updateInLoadMenuItems();
1154 return true;
1155 }
1156
1157 /**
1158 * As the menu can be open when loading state changes
1159 * we must manually update the state of the stop/reload menu
1160 * item
1161 */
1162 private void updateInLoadMenuItems() {
1163 if (mMenu == null) {
1164 return;
1165 }
Michael Kolbe0a36662010-06-29 10:37:12 -07001166 MenuItem dest = mMenu.findItem(R.id.stop_reload_menu_id);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001167 MenuItem src = mInLoad ?
1168 mMenu.findItem(R.id.stop_menu_id):
Michael Kolbe0a36662010-06-29 10:37:12 -07001169 mMenu.findItem(R.id.reload_menu_id);
1170 if (src != null) {
1171 dest.setIcon(src.getIcon());
1172 dest.setTitle(src.getTitle());
1173 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001174 }
1175
1176 @Override
1177 public boolean onContextItemSelected(MenuItem item) {
1178 // chording is not an issue with context menus, but we use the same
1179 // options selector, so set mCanChord to true so we can access them.
1180 mCanChord = true;
1181 int id = item.getItemId();
Leon Scroggins96afcb12009-12-10 12:35:56 -05001182 boolean result = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001183 switch (id) {
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001184 // For the context menu from the title bar
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001185 case R.id.title_bar_copy_page_url:
Leon Scroggins96afcb12009-12-10 12:35:56 -05001186 Tab currentTab = mTabControl.getCurrentTab();
1187 if (null == currentTab) {
1188 result = false;
1189 break;
1190 }
1191 WebView mainView = currentTab.getWebView();
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001192 if (null == mainView) {
Leon Scroggins96afcb12009-12-10 12:35:56 -05001193 result = false;
1194 break;
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001195 }
Leon Scroggins96afcb12009-12-10 12:35:56 -05001196 copy(mainView.getUrl());
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001197 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001198 // -- Browser context menu
1199 case R.id.open_context_menu_id:
The Android Open Source Project0c908882009-03-03 19:32:16 -08001200 case R.id.bookmark_context_menu_id:
1201 case R.id.save_link_context_menu_id:
1202 case R.id.share_link_context_menu_id:
1203 case R.id.copy_link_context_menu_id:
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001204 final WebView webView = getTopWindow();
1205 if (null == webView) {
Leon Scroggins96afcb12009-12-10 12:35:56 -05001206 result = false;
1207 break;
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001208 }
1209 final HashMap hrefMap = new HashMap();
1210 hrefMap.put("webview", webView);
1211 final Message msg = mHandler.obtainMessage(
1212 FOCUS_NODE_HREF, id, 0, hrefMap);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001213 webView.requestFocusNodeHref(msg);
1214 break;
1215
1216 default:
1217 // For other context menus
Leon Scroggins96afcb12009-12-10 12:35:56 -05001218 result = onOptionsItemSelected(item);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001219 }
1220 mCanChord = false;
Leon Scroggins96afcb12009-12-10 12:35:56 -05001221 return result;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001222 }
1223
1224 private Bundle createGoogleSearchSourceBundle(String source) {
1225 Bundle bundle = new Bundle();
Bjorn Bringert10d1cca2010-02-10 14:22:12 +00001226 bundle.putString(Search.SOURCE, source);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001227 return bundle;
1228 }
1229
Leon Scroggins8ad29922010-02-16 12:33:55 -05001230 /* package */ void editUrl() {
Leon Scroggins68579392009-09-15 15:31:54 -04001231 if (mOptionsMenuOpen) closeOptionsMenu();
Leon Scroggins5bbe9802009-07-31 13:10:55 -04001232 String url = (getTopWindow() == null) ? null : getTopWindow().getUrl();
Grace Kloba83f47342009-07-20 10:44:31 -07001233 startSearch(mSettings.getHomePage().equals(url) ? null : url, true,
Leon Scroggins8ad29922010-02-16 12:33:55 -05001234 null, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001235 }
1236
Leon Scroggins8ad29922010-02-16 12:33:55 -05001237 /**
1238 * Overriding this to insert a local information bundle
1239 */
The Android Open Source Project0c908882009-03-03 19:32:16 -08001240 @Override
1241 public void startSearch(String initialQuery, boolean selectInitialQuery,
1242 Bundle appSearchData, boolean globalSearch) {
1243 if (appSearchData == null) {
1244 appSearchData = createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_TYPE);
1245 }
1246 super.startSearch(initialQuery, selectInitialQuery, appSearchData, globalSearch);
1247 }
1248
Leon Scroggins1f005d32009-08-10 17:36:42 -04001249 /**
1250 * Switch tabs. Called by the TitleBarSet when sliding the title bar
1251 * results in changing tabs.
Leon Scroggins160a7e72009-08-14 18:28:01 -04001252 * @param index Index of the tab to change to, as defined by
1253 * mTabControl.getTabIndex(Tab t).
1254 * @return boolean True if we successfully switched to a different tab. If
1255 * the indexth tab is null, or if that tab is the same as
1256 * the current one, return false.
Leon Scroggins1f005d32009-08-10 17:36:42 -04001257 */
Leon Scroggins160a7e72009-08-14 18:28:01 -04001258 /* package */ boolean switchToTab(int index) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001259 Tab tab = mTabControl.getTab(index);
1260 Tab currentTab = mTabControl.getCurrentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04001261 if (tab == null || tab == currentTab) {
Leon Scroggins160a7e72009-08-14 18:28:01 -04001262 return false;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001263 }
1264 if (currentTab != null) {
1265 // currentTab may be null if it was just removed. In that case,
1266 // we do not need to remove it
1267 removeTabFromContentView(currentTab);
1268 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001269 mTabControl.setCurrentTab(tab);
1270 attachTabToContentView(tab);
Grace Klobaeb6eef42009-09-15 17:56:32 -07001271 resetTitleIconAndProgress();
1272 updateLockIconToLatest();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001273 return true;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001274 }
1275
Grace Kloba22ac16e2009-10-07 18:00:23 -07001276 /* package */ Tab openTabToHomePage() {
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001277 return openTabAndShow(mSettings.getHomePage(), false, null);
1278 }
1279
Leon Scroggins1f005d32009-08-10 17:36:42 -04001280 /* package */ void closeCurrentWindow() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001281 final Tab current = mTabControl.getCurrentTab();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001282 if (mTabControl.getTabCount() == 1) {
Leon Scroggins30444232009-09-04 18:36:20 -04001283 // This is the last tab. Open a new one, with the home
1284 // page and close the current one.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001285 openTabToHomePage();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001286 closeTab(current);
Leon Scroggins160a7e72009-08-14 18:28:01 -04001287 return;
1288 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07001289 final Tab parent = current.getParentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04001290 int indexToShow = -1;
1291 if (parent != null) {
1292 indexToShow = mTabControl.getTabIndex(parent);
1293 } else {
Leon Scroggins160a7e72009-08-14 18:28:01 -04001294 final int currentIndex = mTabControl.getCurrentIndex();
1295 // Try to move to the tab to the right
1296 indexToShow = currentIndex + 1;
1297 if (indexToShow > mTabControl.getTabCount() - 1) {
1298 // Try to move to the tab to the left
1299 indexToShow = currentIndex - 1;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001300 }
1301 }
Leon Scroggins160a7e72009-08-14 18:28:01 -04001302 if (switchToTab(indexToShow)) {
1303 // Close window
1304 closeTab(current);
1305 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001306 }
1307
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001308 private ActiveTabsPage mActiveTabsPage;
1309
1310 /**
1311 * Remove the active tabs page.
1312 * @param needToAttach If true, the active tabs page did not attach a tab
1313 * to the content view, so we need to do that here.
1314 */
1315 /* package */ void removeActiveTabPage(boolean needToAttach) {
1316 mContentView.removeView(mActiveTabsPage);
Leon Scrogginsd746a942010-05-19 13:21:44 -04001317 mTitleBar.setVisibility(View.VISIBLE);
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001318 mActiveTabsPage = null;
1319 mMenuState = R.id.MAIN_MENU;
1320 if (needToAttach) {
1321 attachTabToContentView(mTabControl.getCurrentTab());
1322 }
1323 getTopWindow().requestFocus();
1324 }
1325
Cary Clark01cfcdd2010-06-04 16:36:45 -04001326 private WebView showDialog(WebDialog dialog) {
1327 // Need to do something special for Tablet
1328 Tab tab = mTabControl.getCurrentTab();
1329 if (tab.getSubWebView() == null) {
1330 // If the find or select is being performed on the main webview,
1331 // remove the embedded title bar.
1332 WebView mainView = tab.getWebView();
1333 if (mainView != null) {
1334 mainView.setEmbeddedTitleBar(null);
1335 }
1336 }
1337 hideFakeTitleBar();
1338 mMenuState = EMPTY_MENU;
1339 return tab.showDialog(dialog);
1340 }
1341
The Android Open Source Project0c908882009-03-03 19:32:16 -08001342 @Override
1343 public boolean onOptionsItemSelected(MenuItem item) {
1344 if (!mCanChord) {
1345 // The user has already fired a shortcut with this hold down of the
1346 // menu key.
1347 return false;
1348 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001349 if (null == getTopWindow()) {
Leon Scroggins0d7ae0e2009-06-05 11:04:45 -04001350 return false;
1351 }
Grace Kloba6ee9c492009-07-13 10:04:34 -07001352 if (mMenuIsDown) {
1353 // The shortcut action consumes the MENU. Even if it is still down,
1354 // it won't trigger the next shortcut action. In the case of the
1355 // shortcut action triggering a new activity, like Bookmarks, we
1356 // won't get onKeyUp for MENU. So it is important to reset it here.
1357 mMenuIsDown = false;
1358 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001359 switch (item.getItemId()) {
1360 // -- Main menu
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001361 case R.id.new_tab_menu_id:
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001362 openTabToHomePage();
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001363 break;
1364
Leon Scroggins64b80f32009-08-07 12:03:34 -04001365 case R.id.goto_menu_id:
Leon Scroggins8ad29922010-02-16 12:33:55 -05001366 editUrl();
Leon Scrogginsb3a5bed2009-09-28 11:21:56 -04001367 break;
1368
1369 case R.id.bookmarks_menu_id:
Leon Scroggins30444232009-09-04 18:36:20 -04001370 bookmarksOrHistoryPicker(false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001371 break;
1372
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001373 case R.id.active_tabs_menu_id:
1374 mActiveTabsPage = new ActiveTabsPage(this, mTabControl);
1375 removeTabFromContentView(mTabControl.getCurrentTab());
Leon Scrogginsd746a942010-05-19 13:21:44 -04001376 mTitleBar.setVisibility(View.GONE);
Leon Scroggins43de6162009-09-14 19:59:58 -04001377 hideFakeTitleBar();
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001378 mContentView.addView(mActiveTabsPage, COVER_SCREEN_PARAMS);
1379 mActiveTabsPage.requestFocus();
1380 mMenuState = EMPTY_MENU;
1381 break;
1382
Leon Scroggins1f005d32009-08-10 17:36:42 -04001383 case R.id.add_bookmark_menu_id:
Leon Scroggins571b3762010-05-26 10:25:01 -04001384 bookmarkCurrentPage();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001385 break;
1386
1387 case R.id.stop_reload_menu_id:
1388 if (mInLoad) {
1389 stopLoading();
1390 } else {
1391 getTopWindow().reload();
1392 }
1393 break;
1394
1395 case R.id.back_menu_id:
1396 getTopWindow().goBack();
1397 break;
1398
1399 case R.id.forward_menu_id:
1400 getTopWindow().goForward();
1401 break;
1402
1403 case R.id.close_menu_id:
1404 // Close the subwindow if it exists.
1405 if (mTabControl.getCurrentSubWindow() != null) {
1406 dismissSubWindow(mTabControl.getCurrentTab());
1407 break;
1408 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001409 closeCurrentWindow();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001410 break;
1411
1412 case R.id.homepage_menu_id:
Grace Kloba22ac16e2009-10-07 18:00:23 -07001413 Tab current = mTabControl.getCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001414 if (current != null) {
1415 dismissSubWindow(current);
Leon Scroggins92472e82010-02-17 16:32:28 -05001416 loadUrl(current.getWebView(), mSettings.getHomePage());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001417 }
1418 break;
1419
1420 case R.id.preferences_menu_id:
1421 Intent intent = new Intent(this,
1422 BrowserPreferencesPage.class);
Leon Scrogginsd5304942009-12-10 16:11:39 -05001423 intent.putExtra(BrowserPreferencesPage.CURRENT_PAGE,
1424 getTopWindow().getUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001425 startActivityForResult(intent, PREFERENCES_PAGE);
1426 break;
1427
1428 case R.id.find_menu_id:
Cary Clark01cfcdd2010-06-04 16:36:45 -04001429 showFindDialog();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001430 break;
1431
Elliott Slaughter0ced08c2010-06-30 11:40:42 -07001432 case R.id.save_webarchive_menu_id:
1433 if (LOGD_ENABLED) {
1434 Log.d(LOGTAG, "Save as Web Archive");
1435 }
1436 String directory = getExternalFilesDir(null).getAbsolutePath() + File.separator;
1437 getTopWindow().saveWebArchive(directory, true, new ValueCallback<String>() {
1438 @Override
1439 public void onReceiveValue(String value) {
1440 if (value != null) {
1441 Toast.makeText(BrowserActivity.this, R.string.webarchive_saved, Toast.LENGTH_SHORT).show();
1442 } else {
1443 Toast.makeText(BrowserActivity.this, R.string.webarchive_failed, Toast.LENGTH_SHORT).show();
1444 }
1445 }
1446 });
1447 break;
1448
The Android Open Source Project0c908882009-03-03 19:32:16 -08001449 case R.id.page_info_menu_id:
1450 showPageInfo(mTabControl.getCurrentTab(), false);
1451 break;
1452
1453 case R.id.classic_history_menu_id:
Leon Scroggins30444232009-09-04 18:36:20 -04001454 bookmarksOrHistoryPicker(true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001455 break;
1456
Leon Scroggins96afcb12009-12-10 12:35:56 -05001457 case R.id.title_bar_share_page_url:
The Android Open Source Project0c908882009-03-03 19:32:16 -08001458 case R.id.share_page_menu_id:
Leon Scroggins96afcb12009-12-10 12:35:56 -05001459 Tab currentTab = mTabControl.getCurrentTab();
1460 if (null == currentTab) {
1461 mCanChord = false;
1462 return false;
1463 }
1464 currentTab.populatePickerData();
1465 sharePage(this, currentTab.getTitle(),
1466 currentTab.getUrl(), currentTab.getFavicon(),
Ben Murdoch87cc65d2010-06-29 20:34:10 +01001467 createScreenshot(currentTab.getWebView(), getDesiredThumbnailWidth(this),
1468 getDesiredThumbnailHeight(this)));
The Android Open Source Project0c908882009-03-03 19:32:16 -08001469 break;
1470
1471 case R.id.dump_nav_menu_id:
1472 getTopWindow().debugDump();
1473 break;
1474
Andrei Popescu7a8b88b2010-02-02 00:30:38 +00001475 case R.id.dump_counters_menu_id:
1476 getTopWindow().dumpV8Counters();
1477 break;
1478
The Android Open Source Project0c908882009-03-03 19:32:16 -08001479 case R.id.zoom_in_menu_id:
1480 getTopWindow().zoomIn();
1481 break;
1482
1483 case R.id.zoom_out_menu_id:
1484 getTopWindow().zoomOut();
1485 break;
1486
1487 case R.id.view_downloads_menu_id:
1488 viewDownloads(null);
1489 break;
1490
The Android Open Source Project0c908882009-03-03 19:32:16 -08001491 case R.id.window_one_menu_id:
1492 case R.id.window_two_menu_id:
1493 case R.id.window_three_menu_id:
1494 case R.id.window_four_menu_id:
1495 case R.id.window_five_menu_id:
1496 case R.id.window_six_menu_id:
1497 case R.id.window_seven_menu_id:
1498 case R.id.window_eight_menu_id:
1499 {
1500 int menuid = item.getItemId();
1501 for (int id = 0; id < WINDOW_SHORTCUT_ID_ARRAY.length; id++) {
1502 if (WINDOW_SHORTCUT_ID_ARRAY[id] == menuid) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001503 Tab desiredTab = mTabControl.getTab(id);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001504 if (desiredTab != null &&
1505 desiredTab != mTabControl.getCurrentTab()) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001506 switchToTab(id);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001507 }
1508 break;
1509 }
1510 }
1511 }
1512 break;
1513
1514 default:
1515 if (!super.onOptionsItemSelected(item)) {
1516 return false;
1517 }
1518 // Otherwise fall through.
1519 }
1520 mCanChord = false;
1521 return true;
1522 }
1523
Leon Scroggins571b3762010-05-26 10:25:01 -04001524 /* package */ void bookmarkCurrentPage() {
1525 Intent i = new Intent(BrowserActivity.this,
1526 AddBookmarkPage.class);
1527 WebView w = getTopWindow();
1528 i.putExtra("url", w.getUrl());
1529 i.putExtra("title", w.getTitle());
1530 i.putExtra("touch_icon_url", w.getTouchIconUrl());
Ben Murdoch87cc65d2010-06-29 20:34:10 +01001531 i.putExtra("thumbnail", createScreenshot(w, getDesiredThumbnailWidth(this),
1532 getDesiredThumbnailHeight(this)));
Ben Murdocheecb4e62010-07-06 16:30:38 +01001533 i.putExtra("url_editable", false);
Leon Scroggins571b3762010-05-26 10:25:01 -04001534 startActivity(i);
1535 }
1536
Cary Clark01cfcdd2010-06-04 16:36:45 -04001537 private boolean dialogIsUp() {
1538 return null != mFindDialog && mFindDialog.isVisible() ||
1539 null != mSelectDialog && mSelectDialog.isVisible();
1540 }
1541
1542 private boolean closeDialog(WebDialog dialog) {
1543 if (null == dialog || !dialog.isVisible()) return false;
Leon Scroggins79e36d92010-04-29 16:01:46 +01001544 Tab currentTab = mTabControl.getCurrentTab();
Cary Clark01cfcdd2010-06-04 16:36:45 -04001545 currentTab.closeDialog(dialog);
1546 dialog.dismiss();
1547 return true;
1548 }
1549
1550 /*
1551 * Remove the find dialog or select dialog.
1552 */
1553 public void closeDialogs() {
1554 if (!(closeDialog(mFindDialog) || closeDialog(mSelectDialog))) return;
Michael Kolba2b2ba82010-08-04 17:54:03 -07001555 // If the Find was being performed in the main WebView, replace the
1556 // embedded title bar.
1557 Tab currentTab = mTabControl.getCurrentTab();
1558 if (currentTab.getSubWebView() == null) {
1559 WebView mainView = currentTab.getWebView();
1560 if (mainView != null) {
1561 mainView.setEmbeddedTitleBar(mTitleBar);
Leon Scroggins79e36d92010-04-29 16:01:46 +01001562 }
1563 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001564 mMenuState = R.id.MAIN_MENU;
Leon Scroggins79e36d92010-04-29 16:01:46 +01001565 if (mInLoad) {
1566 // The title bar was hidden, because otherwise it would cover up the
Michael Kolba2b2ba82010-08-04 17:54:03 -07001567 // find or select dialog. Now that the dialog has been removed,
Cary Clark01cfcdd2010-06-04 16:36:45 -04001568 // show the fake title bar once again.
Leon Scroggins79e36d92010-04-29 16:01:46 +01001569 showFakeTitleBar();
1570 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001571 }
1572
Cary Clark01cfcdd2010-06-04 16:36:45 -04001573 public void showFindDialog() {
1574 if (null == mFindDialog) {
1575 mFindDialog = new FindDialog(this);
1576 }
1577 showDialog(mFindDialog).setFindIsUp(true);
1578 }
1579
1580 public void setFindDialogText(String text) {
1581 mFindDialog.setText(text);
1582 }
1583
1584 public void showSelectDialog() {
1585 if (null == mSelectDialog) {
1586 mSelectDialog = new SelectDialog(this);
1587 }
1588 showDialog(mSelectDialog).setUpSelect();
1589 mSelectDialog.hideSoftInput();
1590 }
1591
Grace Kloba22ac16e2009-10-07 18:00:23 -07001592 @Override
1593 public boolean onPrepareOptionsMenu(Menu menu) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001594 // This happens when the user begins to hold down the menu key, so
1595 // allow them to chord to get a shortcut.
1596 mCanChord = true;
1597 // Note: setVisible will decide whether an item is visible; while
1598 // setEnabled() will decide whether an item is enabled, which also means
1599 // whether the matching shortcut key will function.
1600 super.onPrepareOptionsMenu(menu);
1601 switch (mMenuState) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001602 case EMPTY_MENU:
1603 if (mCurrentMenuState != mMenuState) {
1604 menu.setGroupVisible(R.id.MAIN_MENU, false);
1605 menu.setGroupEnabled(R.id.MAIN_MENU, false);
1606 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001607 }
1608 break;
1609 default:
1610 if (mCurrentMenuState != mMenuState) {
1611 menu.setGroupVisible(R.id.MAIN_MENU, true);
1612 menu.setGroupEnabled(R.id.MAIN_MENU, true);
1613 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001614 }
1615 final WebView w = getTopWindow();
1616 boolean canGoBack = false;
1617 boolean canGoForward = false;
1618 boolean isHome = false;
1619 if (w != null) {
1620 canGoBack = w.canGoBack();
1621 canGoForward = w.canGoForward();
1622 isHome = mSettings.getHomePage().equals(w.getUrl());
1623 }
1624 final MenuItem back = menu.findItem(R.id.back_menu_id);
1625 back.setEnabled(canGoBack);
1626
1627 final MenuItem home = menu.findItem(R.id.homepage_menu_id);
1628 home.setEnabled(!isHome);
1629
Michael Kolbe0a36662010-06-29 10:37:12 -07001630 final MenuItem forward = menu.findItem(R.id.forward_menu_id);
1631 forward.setEnabled(canGoForward);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001632
Michael Kolbe0a36662010-06-29 10:37:12 -07001633 final MenuItem newtab = menu.findItem(R.id.new_tab_menu_id);
1634 newtab.setEnabled(mTabControl.canCreateNewTab());
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001635
The Android Open Source Project0c908882009-03-03 19:32:16 -08001636 // decide whether to show the share link option
1637 PackageManager pm = getPackageManager();
1638 Intent send = new Intent(Intent.ACTION_SEND);
1639 send.setType("text/plain");
1640 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1641 menu.findItem(R.id.share_page_menu_id).setVisible(ri != null);
1642
The Android Open Source Project0c908882009-03-03 19:32:16 -08001643 boolean isNavDump = mSettings.isNavDump();
1644 final MenuItem nav = menu.findItem(R.id.dump_nav_menu_id);
1645 nav.setVisible(isNavDump);
1646 nav.setEnabled(isNavDump);
Andrei Popescu7a8b88b2010-02-02 00:30:38 +00001647
1648 boolean showDebugSettings = mSettings.showDebugSettings();
1649 final MenuItem counter = menu.findItem(R.id.dump_counters_menu_id);
1650 counter.setVisible(showDebugSettings);
1651 counter.setEnabled(showDebugSettings);
1652
The Android Open Source Project0c908882009-03-03 19:32:16 -08001653 break;
1654 }
1655 mCurrentMenuState = mMenuState;
1656 return true;
1657 }
1658
1659 @Override
1660 public void onCreateContextMenu(ContextMenu menu, View v,
1661 ContextMenuInfo menuInfo) {
Leon Scroggins571b3762010-05-26 10:25:01 -04001662 if (v instanceof TitleBarBase) {
Leon Scroggins4e9f89b2010-02-22 16:54:14 -05001663 return;
1664 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001665 WebView webview = (WebView) v;
1666 WebView.HitTestResult result = webview.getHitTestResult();
1667 if (result == null) {
1668 return;
1669 }
1670
1671 int type = result.getType();
1672 if (type == WebView.HitTestResult.UNKNOWN_TYPE) {
1673 Log.w(LOGTAG,
1674 "We should not show context menu when nothing is touched");
1675 return;
1676 }
1677 if (type == WebView.HitTestResult.EDIT_TEXT_TYPE) {
1678 // let TextView handles context menu
1679 return;
1680 }
1681
1682 // Note, http://b/issue?id=1106666 is requesting that
1683 // an inflated menu can be used again. This is not available
1684 // yet, so inflate each time (yuk!)
1685 MenuInflater inflater = getMenuInflater();
1686 inflater.inflate(R.menu.browsercontext, menu);
1687
1688 // Show the correct menu group
Leon Scroggins III9e997c72010-05-26 13:25:16 -04001689 final String extra = result.getExtra();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001690 menu.setGroupVisible(R.id.PHONE_MENU,
1691 type == WebView.HitTestResult.PHONE_TYPE);
1692 menu.setGroupVisible(R.id.EMAIL_MENU,
1693 type == WebView.HitTestResult.EMAIL_TYPE);
1694 menu.setGroupVisible(R.id.GEO_MENU,
1695 type == WebView.HitTestResult.GEO_TYPE);
1696 menu.setGroupVisible(R.id.IMAGE_MENU,
1697 type == WebView.HitTestResult.IMAGE_TYPE
1698 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1699 menu.setGroupVisible(R.id.ANCHOR_MENU,
1700 type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1701 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1702
1703 // Setup custom handling depending on the type
1704 switch (type) {
1705 case WebView.HitTestResult.PHONE_TYPE:
1706 menu.setHeaderTitle(Uri.decode(extra));
1707 menu.findItem(R.id.dial_context_menu_id).setIntent(
1708 new Intent(Intent.ACTION_VIEW, Uri
1709 .parse(WebView.SCHEME_TEL + extra)));
1710 Intent addIntent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
1711 addIntent.putExtra(Insert.PHONE, Uri.decode(extra));
Cary Clark5e335a32009-09-22 14:53:11 -04001712 addIntent.setType(ContactsContract.Contacts.CONTENT_ITEM_TYPE);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001713 menu.findItem(R.id.add_contact_context_menu_id).setIntent(
1714 addIntent);
1715 menu.findItem(R.id.copy_phone_context_menu_id).setOnMenuItemClickListener(
1716 new Copy(extra));
1717 break;
1718
1719 case WebView.HitTestResult.EMAIL_TYPE:
1720 menu.setHeaderTitle(extra);
1721 menu.findItem(R.id.email_context_menu_id).setIntent(
1722 new Intent(Intent.ACTION_VIEW, Uri
1723 .parse(WebView.SCHEME_MAILTO + extra)));
1724 menu.findItem(R.id.copy_mail_context_menu_id).setOnMenuItemClickListener(
1725 new Copy(extra));
1726 break;
1727
1728 case WebView.HitTestResult.GEO_TYPE:
1729 menu.setHeaderTitle(extra);
1730 menu.findItem(R.id.map_context_menu_id).setIntent(
1731 new Intent(Intent.ACTION_VIEW, Uri
1732 .parse(WebView.SCHEME_GEO
1733 + URLEncoder.encode(extra))));
1734 menu.findItem(R.id.copy_geo_context_menu_id).setOnMenuItemClickListener(
1735 new Copy(extra));
1736 break;
1737
1738 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1739 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
1740 TextView titleView = (TextView) LayoutInflater.from(this)
1741 .inflate(android.R.layout.browser_link_context_header,
1742 null);
1743 titleView.setText(extra);
1744 menu.setHeaderView(titleView);
1745 // decide whether to show the open link in new tab option
Leon Scroggins III9e997c72010-05-26 13:25:16 -04001746 boolean showNewTab = mTabControl.canCreateNewTab();
1747 MenuItem newTabItem
1748 = menu.findItem(R.id.open_newtab_context_menu_id);
1749 newTabItem.setVisible(showNewTab);
1750 if (showNewTab) {
1751 newTabItem.setOnMenuItemClickListener(
1752 new MenuItem.OnMenuItemClickListener() {
1753 public boolean onMenuItemClick(MenuItem item) {
1754 final Tab parent = mTabControl.getCurrentTab();
1755 final Tab newTab = openTab(extra);
1756 if (newTab != parent) {
1757 parent.addChildTab(newTab);
1758 }
1759 return true;
1760 }
1761 });
1762 }
Ben Murdochde353622009-10-12 10:29:00 +01001763 menu.findItem(R.id.bookmark_context_menu_id).setVisible(
1764 Bookmarks.urlHasAcceptableScheme(extra));
The Android Open Source Project0c908882009-03-03 19:32:16 -08001765 PackageManager pm = getPackageManager();
1766 Intent send = new Intent(Intent.ACTION_SEND);
1767 send.setType("text/plain");
1768 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1769 menu.findItem(R.id.share_link_context_menu_id).setVisible(ri != null);
1770 if (type == WebView.HitTestResult.SRC_ANCHOR_TYPE) {
1771 break;
1772 }
1773 // otherwise fall through to handle image part
1774 case WebView.HitTestResult.IMAGE_TYPE:
1775 if (type == WebView.HitTestResult.IMAGE_TYPE) {
1776 menu.setHeaderTitle(extra);
1777 }
1778 menu.findItem(R.id.view_image_context_menu_id).setIntent(
1779 new Intent(Intent.ACTION_VIEW, Uri.parse(extra)));
1780 menu.findItem(R.id.download_context_menu_id).
1781 setOnMenuItemClickListener(new Download(extra));
Ben Murdoch4f75ba22009-10-27 11:48:28 +00001782 menu.findItem(R.id.set_wallpaper_context_menu_id).
1783 setOnMenuItemClickListener(new SetAsWallpaper(extra));
The Android Open Source Project0c908882009-03-03 19:32:16 -08001784 break;
1785
1786 default:
1787 Log.w(LOGTAG, "We should not get here.");
1788 break;
1789 }
Leon Scrogginsb2b19f52009-10-09 16:10:00 -04001790 hideFakeTitleBar();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001791 }
1792
The Android Open Source Project0c908882009-03-03 19:32:16 -08001793 // Attach the given tab to the content view.
Grace Klobac928c302009-09-17 11:51:21 -07001794 // this should only be called for the current tab.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001795 private void attachTabToContentView(Tab t) {
Steve Block2bc69912009-07-30 14:45:13 +01001796 // Attach the container that contains the main WebView and any other UI
1797 // associated with the tab.
Patrick Scottd0119532009-09-17 08:00:31 -04001798 t.attachTabToContentView(mContentView);
Ben Murdochbff2d602009-07-01 20:19:05 +01001799
1800 if (mShouldShowErrorConsole) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001801 ErrorConsoleView errorConsole = t.getErrorConsole(true);
Ben Murdochbff2d602009-07-01 20:19:05 +01001802 if (errorConsole.numberOfErrors() == 0) {
1803 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
1804 } else {
1805 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
1806 }
1807
1808 mErrorConsoleContainer.addView(errorConsole,
Romain Guy15b8ec62010-01-08 15:06:43 -08001809 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
Ben Murdochbff2d602009-07-01 20:19:05 +01001810 ViewGroup.LayoutParams.WRAP_CONTENT));
1811 }
1812
Michael Kolba2b2ba82010-08-04 17:54:03 -07001813 WebView view = t.getWebView();
1814 view.setEmbeddedTitleBar(mTitleBar);
Leon Scroggins58d56c62010-01-28 15:12:40 -05001815 if (t.isInVoiceSearchMode()) {
1816 showVoiceTitleBar(t.getVoiceDisplayTitle());
1817 } else {
1818 revertVoiceTitleBar();
1819 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001820 // Request focus on the top window.
1821 t.getTopWindow().requestFocus();
Michael Kolba2b2ba82010-08-04 17:54:03 -07001822 if (mTabControl.getTabChangeListener() != null) {
1823 mTabControl.getTabChangeListener().onCurrentTab(t);
1824 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001825 }
1826
1827 // Attach a sub window to the main WebView of the given tab.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001828 void attachSubWindow(Tab t) {
Patrick Scottd0119532009-09-17 08:00:31 -04001829 t.attachSubWindow(mContentView);
1830 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001831 }
1832
1833 // Remove the given tab from the content view.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001834 private void removeTabFromContentView(Tab t) {
Steve Block2bc69912009-07-30 14:45:13 +01001835 // Remove the container that contains the main WebView.
Patrick Scottd0119532009-09-17 08:00:31 -04001836 t.removeTabFromContentView(mContentView);
Ben Murdochbff2d602009-07-01 20:19:05 +01001837
Grace Kloba22ac16e2009-10-07 18:00:23 -07001838 ErrorConsoleView errorConsole = t.getErrorConsole(false);
1839 if (errorConsole != null) {
1840 mErrorConsoleContainer.removeView(errorConsole);
Ben Murdochbff2d602009-07-01 20:19:05 +01001841 }
1842
Michael Kolba2b2ba82010-08-04 17:54:03 -07001843 WebView view = t.getWebView();
1844 if (view != null) {
1845 view.setEmbeddedTitleBar(null);
Leon Scrogginsbb85b902009-09-14 19:27:20 -04001846 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001847 }
1848
1849 // Remove the sub window if it exists. Also called by TabControl when the
1850 // user clicks the 'X' to dismiss a sub window.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001851 /* package */ void dismissSubWindow(Tab t) {
Patrick Scottd0119532009-09-17 08:00:31 -04001852 t.removeSubWindow(mContentView);
Grace Kloba22ac16e2009-10-07 18:00:23 -07001853 // dismiss the subwindow. This will destroy the WebView.
1854 t.dismissSubWindow();
Patrick Scottd0119532009-09-17 08:00:31 -04001855 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001856 }
1857
Leon Scroggins1f005d32009-08-10 17:36:42 -04001858 // A wrapper function of {@link #openTabAndShow(UrlData, boolean, String)}
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07001859 // that accepts url as string.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001860 private Tab openTabAndShow(String url, boolean closeOnExit, String appId) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001861 return openTabAndShow(new UrlData(url), closeOnExit, appId);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001862 }
1863
1864 // This method does a ton of stuff. It will attempt to create a new tab
1865 // if we haven't reached MAX_TABS. Otherwise it uses the current tab. If
Leon Scroggins1f005d32009-08-10 17:36:42 -04001866 // url isn't null, it will load the given url.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001867 /* package */Tab openTabAndShow(UrlData urlData, boolean closeOnExit,
1868 String appId) {
1869 final Tab currentTab = mTabControl.getCurrentTab();
1870 if (mTabControl.canCreateNewTab()) {
1871 final Tab tab = mTabControl.createNewTab(closeOnExit, appId,
Elliott Slaughterf0f03952010-07-14 18:10:36 -07001872 urlData.mUrl, false);
Leon Scroggins1f005d32009-08-10 17:36:42 -04001873 WebView webview = tab.getWebView();
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001874 // If the last tab was removed from the active tabs page, currentTab
1875 // will be null.
1876 if (currentTab != null) {
1877 removeTabFromContentView(currentTab);
1878 }
Patrick Scott8bbd69f2009-08-14 13:35:53 -04001879 // We must set the new tab as the current tab to reflect the old
1880 // animation behavior.
1881 mTabControl.setCurrentTab(tab);
Grace Klobaeb6eef42009-09-15 17:56:32 -07001882 attachTabToContentView(tab);
Leon Scroggins160a7e72009-08-14 18:28:01 -04001883 if (!urlData.isEmpty()) {
Patrick Scott9d53da02010-02-19 10:19:01 -05001884 loadUrlDataIn(tab, urlData);
Leon Scroggins1f005d32009-08-10 17:36:42 -04001885 }
1886 return tab;
1887 } else {
1888 // Get rid of the subwindow if it exists
1889 dismissSubWindow(currentTab);
1890 if (!urlData.isEmpty()) {
1891 // Load the given url.
Patrick Scott9d53da02010-02-19 10:19:01 -05001892 loadUrlDataIn(currentTab, urlData);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001893 }
Leon Scroggins58d56c62010-01-28 15:12:40 -05001894 return currentTab;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001895 }
1896 }
1897
Grace Kloba22ac16e2009-10-07 18:00:23 -07001898 private Tab openTab(String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001899 if (mSettings.openInBackground()) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001900 Tab t = mTabControl.createNewTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001901 if (t != null) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001902 WebView view = t.getWebView();
Leon Scroggins92472e82010-02-17 16:32:28 -05001903 loadUrl(view, url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001904 }
Grace Klobac9181842009-04-14 08:53:22 -07001905 return t;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001906 } else {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001907 return openTabAndShow(url, false, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001908 }
1909 }
1910
Elliott Slaughterf0f03952010-07-14 18:10:36 -07001911 /* package */ Tab openIncognitoTab() {
1912 if (mTabControl.canCreateNewTab()) {
1913 Tab currentTab = mTabControl.getCurrentTab();
1914 Tab tab = mTabControl.createNewTab(false, null, null, true);
1915 if (currentTab != null) {
1916 removeTabFromContentView(currentTab);
1917 }
1918 mTabControl.setCurrentTab(tab);
1919 attachTabToContentView(tab);
1920 return tab;
1921 }
1922 return null;
1923 }
1924
The Android Open Source Project0c908882009-03-03 19:32:16 -08001925 private class Copy implements OnMenuItemClickListener {
1926 private CharSequence mText;
1927
1928 public boolean onMenuItemClick(MenuItem item) {
1929 copy(mText);
1930 return true;
1931 }
1932
1933 public Copy(CharSequence toCopy) {
1934 mText = toCopy;
1935 }
1936 }
1937
1938 private class Download implements OnMenuItemClickListener {
1939 private String mText;
1940
1941 public boolean onMenuItemClick(MenuItem item) {
1942 onDownloadStartNoStream(mText, null, null, null, -1);
1943 return true;
1944 }
1945
1946 public Download(String toDownload) {
1947 mText = toDownload;
1948 }
1949 }
1950
Ben Murdoch4f75ba22009-10-27 11:48:28 +00001951 private class SetAsWallpaper extends Thread implements
1952 OnMenuItemClickListener, DialogInterface.OnCancelListener {
1953 private URL mUrl;
1954 private ProgressDialog mWallpaperProgress;
1955 private boolean mCanceled = false;
1956
1957 public SetAsWallpaper(String url) {
1958 try {
1959 mUrl = new URL(url);
1960 } catch (MalformedURLException e) {
1961 mUrl = null;
1962 }
1963 }
1964
1965 public void onCancel(DialogInterface dialog) {
1966 mCanceled = true;
1967 }
1968
1969 public boolean onMenuItemClick(MenuItem item) {
1970 if (mUrl != null) {
1971 // The user may have tried to set a image with a large file size as their
1972 // background so it may take a few moments to perform the operation. Display
1973 // a progress spinner while it is working.
1974 mWallpaperProgress = new ProgressDialog(BrowserActivity.this);
1975 mWallpaperProgress.setIndeterminate(true);
1976 mWallpaperProgress.setMessage(getText(R.string.progress_dialog_setting_wallpaper));
1977 mWallpaperProgress.setCancelable(true);
1978 mWallpaperProgress.setOnCancelListener(this);
1979 mWallpaperProgress.show();
1980 start();
1981 }
1982 return true;
1983 }
1984
Michael Kolbe0a36662010-06-29 10:37:12 -07001985 @Override
Ben Murdoch4f75ba22009-10-27 11:48:28 +00001986 public void run() {
1987 Drawable oldWallpaper = BrowserActivity.this.getWallpaper();
1988 try {
1989 // TODO: This will cause the resource to be downloaded again, when we
1990 // should in most cases be able to grab it from the cache. To fix this
1991 // we should query WebCore to see if we can access a cached version and
1992 // instead open an input stream on that. This pattern could also be used
1993 // in the download manager where the same problem exists.
1994 InputStream inputstream = mUrl.openStream();
1995 if (inputstream != null) {
1996 setWallpaper(inputstream);
1997 }
1998 } catch (IOException e) {
1999 Log.e(LOGTAG, "Unable to set new wallpaper");
2000 // Act as though the user canceled the operation so we try to
2001 // restore the old wallpaper.
2002 mCanceled = true;
2003 }
2004
2005 if (mCanceled) {
2006 // Restore the old wallpaper if the user cancelled whilst we were setting
2007 // the new wallpaper.
2008 int width = oldWallpaper.getIntrinsicWidth();
2009 int height = oldWallpaper.getIntrinsicHeight();
2010 Bitmap bm = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
2011 Canvas canvas = new Canvas(bm);
2012 oldWallpaper.setBounds(0, 0, width, height);
2013 oldWallpaper.draw(canvas);
2014 try {
2015 setWallpaper(bm);
2016 } catch (IOException e) {
2017 Log.e(LOGTAG, "Unable to restore old wallpaper.");
2018 }
2019 mCanceled = false;
2020 }
2021
2022 if (mWallpaperProgress.isShowing()) {
2023 mWallpaperProgress.dismiss();
2024 }
2025 }
2026 }
2027
The Android Open Source Project0c908882009-03-03 19:32:16 -08002028 private void copy(CharSequence text) {
Dianne Hackborn80f32622010-08-05 14:17:53 -07002029 ClipboardManager cm = (ClipboardManager)getSystemService(Context.CLIPBOARD_SERVICE);
2030 cm.setText(text);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002031 }
2032
2033 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08002034 * Resets the browser title-view to whatever it must be
2035 * (for example, if we had a loading error)
2036 * When we have a new page, we call resetTitle, when we
2037 * have to reset the titlebar to whatever it used to be
2038 * (for example, if the user chose to stop loading), we
2039 * call resetTitleAndRevertLockIcon.
2040 */
2041 /* package */ void resetTitleAndRevertLockIcon() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002042 mTabControl.getCurrentTab().revertLockIcon();
2043 updateLockIconToLatest();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002044 resetTitleIconAndProgress();
2045 }
2046
2047 /**
2048 * Reset the title, favicon, and progress.
2049 */
2050 private void resetTitleIconAndProgress() {
2051 WebView current = mTabControl.getCurrentWebView();
2052 if (current == null) {
2053 return;
2054 }
2055 resetTitleAndIcon(current);
2056 int progress = current.getProgress();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002057 current.getWebChromeClient().onProgressChanged(current, progress);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002058 }
2059
2060 // Reset the title and the icon based on the given item.
2061 private void resetTitleAndIcon(WebView view) {
2062 WebHistoryItem item = view.copyBackForwardList().getCurrentItem();
2063 if (item != null) {
Leon Scroggins68579392009-09-15 15:31:54 -04002064 setUrlTitle(item.getUrl(), item.getTitle());
The Android Open Source Project0c908882009-03-03 19:32:16 -08002065 setFavicon(item.getFavicon());
2066 } else {
Leon Scroggins68579392009-09-15 15:31:54 -04002067 setUrlTitle(null, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002068 setFavicon(null);
2069 }
2070 }
2071
2072 /**
2073 * Sets a title composed of the URL and the title string.
2074 * @param url The URL of the site being loaded.
2075 * @param title The title of the site being loaded.
2076 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07002077 void setUrlTitle(String url, String title) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002078 mUrl = url;
2079 mTitle = title;
2080
Leon Scroggins58d56c62010-01-28 15:12:40 -05002081 // If we are in voice search mode, the title has already been set.
2082 if (mTabControl.getCurrentTab().isInVoiceSearchMode()) return;
2083 mTitleBar.setDisplayTitle(url);
Michael Kolba2b2ba82010-08-04 17:54:03 -07002084 mFakeTitleBar.setDisplayTitle(url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002085 }
2086
2087 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08002088 * @param url The URL to build a title version of the URL from.
2089 * @return The title version of the URL or null if fails.
2090 * The title version of the URL can be either the URL hostname,
2091 * or the hostname with an "https://" prefix (for secure URLs),
2092 * or an empty string if, for example, the URL in question is a
2093 * file:// URL with no hostname.
2094 */
Leon Scroggins32e14a62009-06-11 10:26:34 -04002095 /* package */ static String buildTitleUrl(String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002096 String titleUrl = null;
2097
2098 if (url != null) {
2099 try {
2100 // parse the url string
2101 URL urlObj = new URL(url);
2102 if (urlObj != null) {
2103 titleUrl = "";
2104
2105 String protocol = urlObj.getProtocol();
2106 String host = urlObj.getHost();
2107
2108 if (host != null && 0 < host.length()) {
2109 titleUrl = host;
2110 if (protocol != null) {
2111 // if a secure site, add an "https://" prefix!
2112 if (protocol.equalsIgnoreCase("https")) {
2113 titleUrl = protocol + "://" + host;
2114 }
2115 }
2116 }
2117 }
2118 } catch (MalformedURLException e) {}
2119 }
2120
2121 return titleUrl;
2122 }
2123
2124 // Set the favicon in the title bar.
Grace Kloba22ac16e2009-10-07 18:00:23 -07002125 void setFavicon(Bitmap icon) {
Leon Scroggins68579392009-09-15 15:31:54 -04002126 mTitleBar.setFavicon(icon);
Michael Kolba2b2ba82010-08-04 17:54:03 -07002127 mFakeTitleBar.setFavicon(icon);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002128 }
2129
2130 /**
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002131 * Close the tab, remove its associated title bar, and adjust mTabControl's
2132 * current tab to a valid value.
Leon Scroggins1f005d32009-08-10 17:36:42 -04002133 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07002134 /* package */ void closeTab(Tab t) {
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002135 int currentIndex = mTabControl.getCurrentIndex();
2136 int removeIndex = mTabControl.getTabIndex(t);
Leon Scroggins1f005d32009-08-10 17:36:42 -04002137 mTabControl.removeTab(t);
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002138 if (currentIndex >= removeIndex && currentIndex != 0) {
2139 currentIndex--;
2140 }
2141 mTabControl.setCurrentTab(mTabControl.getTab(currentIndex));
Andrei Popescua5bf1de2009-09-23 16:39:23 +01002142 resetTitleIconAndProgress();
Leon Scroggins654899b2010-06-25 16:25:23 -04002143 updateLockIconToLatest();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002144 }
2145
Leon Scrogginsdcc5eeb2010-02-23 17:26:37 -05002146 /* package */ void goBackOnePageOrQuit() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002147 Tab current = mTabControl.getCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002148 if (current == null) {
2149 /*
2150 * Instead of finishing the activity, simply push this to the back
2151 * of the stack and let ActivityManager to choose the foreground
2152 * activity. As BrowserActivity is singleTask, it will be always the
2153 * root of the task. So we can use either true or false for
2154 * moveTaskToBack().
2155 */
2156 moveTaskToBack(true);
Grace Kloba00d85e72009-09-23 18:50:05 -07002157 return;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002158 }
2159 WebView w = current.getWebView();
2160 if (w.canGoBack()) {
2161 w.goBack();
2162 } else {
2163 // Check to see if we are closing a window that was created by
2164 // another window. If so, we switch back to that window.
Grace Kloba22ac16e2009-10-07 18:00:23 -07002165 Tab parent = current.getParentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002166 if (parent != null) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04002167 switchToTab(mTabControl.getTabIndex(parent));
2168 // Now we close the other tab
2169 closeTab(current);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002170 } else {
2171 if (current.closeOnExit()) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002172 // force the tab's inLoad() to be false as we are going to
2173 // either finish the activity or remove the tab. This will
2174 // ensure pauseWebViewTimers() taking action.
2175 mTabControl.getCurrentTab().clearInLoad();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002176 if (mTabControl.getTabCount() == 1) {
2177 finish();
2178 return;
2179 }
Mike Reed7bfa63b2009-05-28 11:08:32 -04002180 // call pauseWebViewTimers() now, we won't be able to call
2181 // it in onPause() as the WebView won't be valid.
Grace Klobaec1b5ad2009-08-18 08:42:32 -07002182 // Temporarily change mActivityInPause to be true as
2183 // pauseWebViewTimers() will do nothing if mActivityInPause
2184 // is false.
Grace Kloba918e1d72009-08-13 14:55:06 -07002185 boolean savedState = mActivityInPause;
2186 if (savedState) {
Grace Klobaec1b5ad2009-08-18 08:42:32 -07002187 Log.e(LOGTAG, "BrowserActivity is already paused "
2188 + "while handing goBackOnePageOrQuit.");
Grace Kloba918e1d72009-08-13 14:55:06 -07002189 }
2190 mActivityInPause = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -04002191 pauseWebViewTimers();
Grace Kloba918e1d72009-08-13 14:55:06 -07002192 mActivityInPause = savedState;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002193 removeTabFromContentView(current);
2194 mTabControl.removeTab(current);
2195 }
2196 /*
2197 * Instead of finishing the activity, simply push this to the back
2198 * of the stack and let ActivityManager to choose the foreground
2199 * activity. As BrowserActivity is singleTask, it will be always the
2200 * root of the task. So we can use either true or false for
2201 * moveTaskToBack().
2202 */
2203 moveTaskToBack(true);
2204 }
2205 }
2206 }
2207
Grace Kloba22ac16e2009-10-07 18:00:23 -07002208 boolean isMenuDown() {
2209 return mMenuIsDown;
2210 }
2211
Grace Kloba5942df02009-09-18 11:48:29 -07002212 @Override
2213 public boolean onKeyDown(int keyCode, KeyEvent event) {
Leon Scrogginsf65b50d2009-12-08 10:44:28 -05002214 // Even if MENU is already held down, we need to call to super to open
2215 // the IME on long press.
2216 if (KeyEvent.KEYCODE_MENU == keyCode) {
2217 mMenuIsDown = true;
2218 return super.onKeyDown(keyCode, event);
2219 }
Grace Kloba5942df02009-09-18 11:48:29 -07002220 // The default key mode is DEFAULT_KEYS_SEARCH_LOCAL. As the MENU is
2221 // still down, we don't want to trigger the search. Pretend to consume
2222 // the key and do nothing.
2223 if (mMenuIsDown) return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002224
Grace Kloba5942df02009-09-18 11:48:29 -07002225 switch(keyCode) {
Grace Kloba5942df02009-09-18 11:48:29 -07002226 case KeyEvent.KEYCODE_SPACE:
Grace Klobada0fe552009-09-22 18:17:24 -07002227 // WebView/WebTextView handle the keys in the KeyDown. As
2228 // the Activity's shortcut keys are only handled when WebView
2229 // doesn't, have to do it in onKeyDown instead of onKeyUp.
2230 if (event.isShiftPressed()) {
2231 getTopWindow().pageUp(false);
2232 } else {
2233 getTopWindow().pageDown(false);
2234 }
Grace Kloba5942df02009-09-18 11:48:29 -07002235 return true;
2236 case KeyEvent.KEYCODE_BACK:
2237 if (event.getRepeatCount() == 0) {
2238 event.startTracking();
2239 return true;
2240 } else if (mCustomView == null && mActiveTabsPage == null
2241 && event.isLongPress()) {
2242 bookmarksOrHistoryPicker(true);
2243 return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002244 }
Grace Kloba5942df02009-09-18 11:48:29 -07002245 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002246 }
Grace Kloba5942df02009-09-18 11:48:29 -07002247 return super.onKeyDown(keyCode, event);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002248 }
2249
Grace Kloba5942df02009-09-18 11:48:29 -07002250 @Override
2251 public boolean onKeyUp(int keyCode, KeyEvent event) {
2252 switch(keyCode) {
2253 case KeyEvent.KEYCODE_MENU:
2254 mMenuIsDown = false;
2255 break;
Grace Kloba5942df02009-09-18 11:48:29 -07002256 case KeyEvent.KEYCODE_BACK:
2257 if (event.isTracking() && !event.isCanceled()) {
2258 if (mCustomView != null) {
2259 // if a custom view is showing, hide it
Grace Kloba22ac16e2009-10-07 18:00:23 -07002260 mTabControl.getCurrentWebView().getWebChromeClient()
2261 .onHideCustomView();
Grace Kloba5942df02009-09-18 11:48:29 -07002262 } else if (mActiveTabsPage != null) {
2263 // if tab page is showing, hide it
2264 removeActiveTabPage(true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002265 } else {
Grace Kloba5942df02009-09-18 11:48:29 -07002266 WebView subwindow = mTabControl.getCurrentSubWindow();
2267 if (subwindow != null) {
2268 if (subwindow.canGoBack()) {
2269 subwindow.goBack();
2270 } else {
2271 dismissSubWindow(mTabControl.getCurrentTab());
2272 }
2273 } else {
2274 goBackOnePageOrQuit();
2275 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002276 }
Grace Kloba5942df02009-09-18 11:48:29 -07002277 return true;
2278 }
2279 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002280 }
Grace Kloba5942df02009-09-18 11:48:29 -07002281 return super.onKeyUp(keyCode, event);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002282 }
2283
Leon Scroggins68579392009-09-15 15:31:54 -04002284 /* package */ void stopLoading() {
Ben Murdochb7cc8b42009-09-28 10:59:09 +01002285 mDidStopLoad = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002286 resetTitleAndRevertLockIcon();
2287 WebView w = getTopWindow();
2288 w.stopLoading();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002289 // FIXME: before refactor, it is using mWebViewClient. So I keep the
2290 // same logic here. But for subwindow case, should we call into the main
2291 // WebView's onPageFinished as we never call its onPageStarted and if
2292 // the page finishes itself, we don't call onPageFinished.
2293 mTabControl.getCurrentWebView().getWebViewClient().onPageFinished(w,
2294 w.getUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08002295
2296 cancelStopToast();
2297 mStopToast = Toast
2298 .makeText(this, R.string.stopping, Toast.LENGTH_SHORT);
2299 mStopToast.show();
2300 }
2301
Grace Kloba22ac16e2009-10-07 18:00:23 -07002302 boolean didUserStopLoading() {
2303 return mDidStopLoad;
2304 }
2305
The Android Open Source Project0c908882009-03-03 19:32:16 -08002306 private void cancelStopToast() {
2307 if (mStopToast != null) {
2308 mStopToast.cancel();
2309 mStopToast = null;
2310 }
2311 }
2312
Grace Kloba22ac16e2009-10-07 18:00:23 -07002313 // called by a UI or non-UI thread to post the message
2314 public void postMessage(int what, int arg1, int arg2, Object obj,
2315 long delayMillis) {
2316 mHandler.sendMessageDelayed(mHandler.obtainMessage(what, arg1, arg2,
2317 obj), delayMillis);
2318 }
2319
2320 // called by a UI or non-UI thread to remove the message
2321 void removeMessages(int what, Object object) {
2322 mHandler.removeMessages(what, object);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002323 }
2324
2325 // public message ids
2326 public final static int LOAD_URL = 1001;
2327 public final static int STOP_LOAD = 1002;
2328
2329 // Message Ids
2330 private static final int FOCUS_NODE_HREF = 102;
Grace Kloba92c18a52009-07-31 23:48:32 -07002331 private static final int RELEASE_WAKELOCK = 107;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002332
Grace Kloba22ac16e2009-10-07 18:00:23 -07002333 static final int UPDATE_BOOKMARK_THUMBNAIL = 108;
Ben Murdoch2694e232009-09-29 09:41:11 +01002334
Ben Murdocheecb4e62010-07-06 16:30:38 +01002335 private static final int TOUCH_ICON_DOWNLOADED = 109;
2336
The Android Open Source Project0c908882009-03-03 19:32:16 -08002337 // Private handler for handling javascript and saving passwords
2338 private Handler mHandler = new Handler() {
2339
Michael Kolbe0a36662010-06-29 10:37:12 -07002340 @Override
The Android Open Source Project0c908882009-03-03 19:32:16 -08002341 public void handleMessage(Message msg) {
2342 switch (msg.what) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002343 case FOCUS_NODE_HREF:
Ben Murdoch2694e232009-09-29 09:41:11 +01002344 {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002345 String url = (String) msg.getData().get("url");
Ben Murdoch90d088c2009-11-17 18:14:04 +00002346 String title = (String) msg.getData().get("title");
The Android Open Source Project0c908882009-03-03 19:32:16 -08002347 if (url == null || url.length() == 0) {
2348 break;
2349 }
2350 HashMap focusNodeMap = (HashMap) msg.obj;
2351 WebView view = (WebView) focusNodeMap.get("webview");
2352 // Only apply the action if the top window did not change.
2353 if (getTopWindow() != view) {
2354 break;
2355 }
2356 switch (msg.arg1) {
2357 case R.id.open_context_menu_id:
2358 case R.id.view_image_context_menu_id:
Leon Scroggins92472e82010-02-17 16:32:28 -05002359 loadUrlFromContext(getTopWindow(), url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002360 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002361 case R.id.bookmark_context_menu_id:
2362 Intent intent = new Intent(BrowserActivity.this,
2363 AddBookmarkPage.class);
2364 intent.putExtra("url", url);
Ben Murdoch90d088c2009-11-17 18:14:04 +00002365 intent.putExtra("title", title);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002366 startActivity(intent);
2367 break;
2368 case R.id.share_link_context_menu_id:
Leon Scroggins3e204452010-05-10 11:06:03 -04002369 sharePage(BrowserActivity.this, title, url, null,
Leon Scroggins96afcb12009-12-10 12:35:56 -05002370 null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002371 break;
2372 case R.id.copy_link_context_menu_id:
2373 copy(url);
2374 break;
2375 case R.id.save_link_context_menu_id:
2376 case R.id.download_context_menu_id:
2377 onDownloadStartNoStream(url, null, null, null, -1);
2378 break;
2379 }
2380 break;
Ben Murdoch2694e232009-09-29 09:41:11 +01002381 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002382
2383 case LOAD_URL:
Leon Scroggins92472e82010-02-17 16:32:28 -05002384 loadUrlFromContext(getTopWindow(), (String) msg.obj);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002385 break;
2386
2387 case STOP_LOAD:
2388 stopLoading();
2389 break;
2390
The Android Open Source Project0c908882009-03-03 19:32:16 -08002391 case RELEASE_WAKELOCK:
2392 if (mWakeLock.isHeld()) {
2393 mWakeLock.release();
Grace Kloba5d0e02e2009-10-05 15:15:36 -07002394 // if we reach here, Browser should be still in the
2395 // background loading after WAKELOCK_TIMEOUT (5-min).
2396 // To avoid burning the battery, stop loading.
2397 mTabControl.stopAllLoading();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002398 }
2399 break;
Ben Murdoch2694e232009-09-29 09:41:11 +01002400
2401 case UPDATE_BOOKMARK_THUMBNAIL:
2402 WebView view = (WebView) msg.obj;
2403 if (view != null) {
2404 updateScreenshot(view);
2405 }
2406 break;
Ben Murdocheecb4e62010-07-06 16:30:38 +01002407
2408 case TOUCH_ICON_DOWNLOADED:
2409 Bundle b = msg.getData();
2410 showSaveToHomescreenDialog(b.getString("url"),
2411 b.getString("title"),
2412 (Bitmap) b.getParcelable("touchIcon"),
2413 (Bitmap) b.getParcelable("favicon"));
2414 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002415 }
2416 }
2417 };
2418
Leon Scroggins96afcb12009-12-10 12:35:56 -05002419 /**
2420 * Share a page, providing the title, url, favicon, and a screenshot. Uses
2421 * an {@link Intent} to launch the Activity chooser.
2422 * @param c Context used to launch a new Activity.
2423 * @param title Title of the page. Stored in the Intent with
Paul Westbrook03e6d392010-02-12 10:33:29 -08002424 * {@link Intent#EXTRA_SUBJECT}
Leon Scroggins96afcb12009-12-10 12:35:56 -05002425 * @param url URL of the page. Stored in the Intent with
2426 * {@link Intent#EXTRA_TEXT}
2427 * @param favicon Bitmap of the favicon for the page. Stored in the Intent
2428 * with {@link Browser#EXTRA_SHARE_FAVICON}
2429 * @param screenshot Bitmap of a screenshot of the page. Stored in the
2430 * Intent with {@link Browser#EXTRA_SHARE_SCREENSHOT}
2431 */
2432 public static final void sharePage(Context c, String title, String url,
2433 Bitmap favicon, Bitmap screenshot) {
2434 Intent send = new Intent(Intent.ACTION_SEND);
2435 send.setType("text/plain");
2436 send.putExtra(Intent.EXTRA_TEXT, url);
Paul Westbrook03e6d392010-02-12 10:33:29 -08002437 send.putExtra(Intent.EXTRA_SUBJECT, title);
Leon Scroggins96afcb12009-12-10 12:35:56 -05002438 send.putExtra(Browser.EXTRA_SHARE_FAVICON, favicon);
2439 send.putExtra(Browser.EXTRA_SHARE_SCREENSHOT, screenshot);
2440 try {
2441 c.startActivity(Intent.createChooser(send, c.getString(
2442 R.string.choosertitle_sharevia)));
2443 } catch(android.content.ActivityNotFoundException ex) {
2444 // if no app handles it, do nothing
2445 }
2446 }
2447
Leon Scroggins89c6d362009-07-15 16:54:37 -04002448 private void updateScreenshot(WebView view) {
2449 // If this is a bookmarked site, add a screenshot to the database.
2450 // FIXME: When should we update? Every time?
2451 // FIXME: Would like to make sure there is actually something to
2452 // draw, but the API for that (WebViewCore.pictureReady()) is not
2453 // currently accessible here.
Ben Murdochaac7aa62009-09-17 16:57:40 +01002454
Ben Murdoch87cc65d2010-06-29 20:34:10 +01002455 final Bitmap bm = createScreenshot(view, getDesiredThumbnailWidth(this),
2456 getDesiredThumbnailHeight(this));
Patrick Scottcb192b52010-04-14 14:38:55 -04002457 if (bm == null) {
2458 return;
Leon Scroggins89c6d362009-07-15 16:54:37 -04002459 }
Patrick Scottcb192b52010-04-14 14:38:55 -04002460
2461 final ContentResolver cr = getContentResolver();
2462 final String url = view.getUrl();
2463 final String originalUrl = view.getOriginalUrl();
2464
2465 new AsyncTask<Void, Void, Void>() {
2466 @Override
2467 protected Void doInBackground(Void... unused) {
2468 Cursor c = null;
2469 try {
2470 c = BrowserBookmarksAdapter.queryBookmarksForUrl(
2471 cr, originalUrl, url, true);
2472 if (c != null) {
2473 if (c.moveToFirst()) {
2474 ContentValues values = new ContentValues();
2475 final ByteArrayOutputStream os
2476 = new ByteArrayOutputStream();
2477 bm.compress(Bitmap.CompressFormat.PNG, 100, os);
2478 values.put(Browser.BookmarkColumns.THUMBNAIL,
2479 os.toByteArray());
2480 do {
2481 cr.update(ContentUris.withAppendedId(
2482 Browser.BOOKMARKS_URI, c.getInt(0)),
2483 values, null, null);
2484 } while (c.moveToNext());
2485 }
2486 }
2487 } catch (IllegalStateException e) {
2488 // Ignore
2489 } finally {
2490 if (c != null) c.close();
2491 }
2492 return null;
2493 }
2494 }.execute();
Leon Scroggins89c6d362009-07-15 16:54:37 -04002495 }
2496
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002497 /**
Leon Scrogginsf8551612009-09-24 16:06:02 -04002498 * Values for the size of the thumbnail created when taking a screenshot.
2499 * Lazily initialized. Instead of using these directly, use
2500 * getDesiredThumbnailWidth() or getDesiredThumbnailHeight().
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002501 */
Leon Scrogginsf8551612009-09-24 16:06:02 -04002502 private static int THUMBNAIL_WIDTH = 0;
2503 private static int THUMBNAIL_HEIGHT = 0;
2504
2505 /**
2506 * Return the desired width for thumbnail screenshots, which are stored in
2507 * the database, and used on the bookmarks screen.
2508 * @param context Context for finding out the density of the screen.
2509 * @return int desired width for thumbnail screenshot.
2510 */
2511 /* package */ static int getDesiredThumbnailWidth(Context context) {
2512 if (THUMBNAIL_WIDTH == 0) {
2513 float density = context.getResources().getDisplayMetrics().density;
2514 THUMBNAIL_WIDTH = (int) (90 * density);
2515 THUMBNAIL_HEIGHT = (int) (80 * density);
2516 }
2517 return THUMBNAIL_WIDTH;
2518 }
2519
2520 /**
2521 * Return the desired height for thumbnail screenshots, which are stored in
2522 * the database, and used on the bookmarks screen.
2523 * @param context Context for finding out the density of the screen.
2524 * @return int desired height for thumbnail screenshot.
2525 */
2526 /* package */ static int getDesiredThumbnailHeight(Context context) {
2527 // To ensure that they are both initialized.
2528 getDesiredThumbnailWidth(context);
2529 return THUMBNAIL_HEIGHT;
2530 }
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002531
Ben Murdoch87cc65d2010-06-29 20:34:10 +01002532 private Bitmap createScreenshot(WebView view, int width, int height) {
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002533 Picture thumbnail = view.capturePicture();
Leon Scroggins45800572009-09-29 16:38:47 -04002534 if (thumbnail == null) {
2535 return null;
2536 }
Ben Murdoch87cc65d2010-06-29 20:34:10 +01002537 Bitmap bm = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002538 Canvas canvas = new Canvas(bm);
2539 // May need to tweak these values to determine what is the
2540 // best scale factor
Ben Murdoch2694e232009-09-29 09:41:11 +01002541 int thumbnailWidth = thumbnail.getWidth();
Ben Murdochae59c3f2009-10-20 18:30:28 +01002542 int thumbnailHeight = thumbnail.getHeight();
2543 float scaleFactorX = 1.0f;
2544 float scaleFactorY = 1.0f;
Ben Murdoch2694e232009-09-29 09:41:11 +01002545 if (thumbnailWidth > 0) {
Ben Murdoch87cc65d2010-06-29 20:34:10 +01002546 scaleFactorX = (float) width / (float)thumbnailWidth;
Ben Murdochae59c3f2009-10-20 18:30:28 +01002547 } else {
2548 return null;
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002549 }
Ben Murdochae59c3f2009-10-20 18:30:28 +01002550
2551 if (view.getWidth() > view.getHeight() &&
2552 thumbnailHeight < view.getHeight() && thumbnailHeight > 0) {
2553 // If the device is in landscape and the page is shorter
2554 // than the height of the view, stretch the thumbnail to fill the
2555 // space.
Ben Murdoch87cc65d2010-06-29 20:34:10 +01002556 scaleFactorY = (float) height / (float)thumbnailHeight;
Ben Murdochae59c3f2009-10-20 18:30:28 +01002557 } else {
2558 // In the portrait case, this looks nice.
2559 scaleFactorY = scaleFactorX;
2560 }
2561
2562 canvas.scale(scaleFactorX, scaleFactorY);
2563
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002564 thumbnail.draw(canvas);
2565 return bm;
2566 }
2567
The Android Open Source Project0c908882009-03-03 19:32:16 -08002568 // -------------------------------------------------------------------------
Grace Kloba22ac16e2009-10-07 18:00:23 -07002569 // Helper function for WebViewClient.
The Android Open Source Project0c908882009-03-03 19:32:16 -08002570 //-------------------------------------------------------------------------
2571
2572 // Use in overrideUrlLoading
2573 /* package */ final static String SCHEME_WTAI = "wtai://wp/";
2574 /* package */ final static String SCHEME_WTAI_MC = "wtai://wp/mc;";
2575 /* package */ final static String SCHEME_WTAI_SD = "wtai://wp/sd;";
2576 /* package */ final static String SCHEME_WTAI_AP = "wtai://wp/ap;";
2577
Leon Scroggins92472e82010-02-17 16:32:28 -05002578 // Keep this initial progress in sync with initialProgressValue (* 100)
2579 // in ProgressTracker.cpp
2580 private final static int INITIAL_PROGRESS = 10;
2581
Grace Kloba22ac16e2009-10-07 18:00:23 -07002582 void onPageStarted(WebView view, String url, Bitmap favicon) {
2583 // when BrowserActivity just starts, onPageStarted may be called before
2584 // onResume as it is triggered from onCreate. Call resumeWebViewTimers
2585 // to start the timer. As we won't switch tabs while an activity is in
2586 // pause state, we can ensure calling resume and pause in pair.
2587 if (mActivityInPause) resumeWebViewTimers();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002588
Grace Kloba22ac16e2009-10-07 18:00:23 -07002589 resetLockIcon(url);
2590 setUrlTitle(url, null);
2591 setFavicon(favicon);
Leon Scroggins8cf8f682009-11-04 11:13:50 -08002592 // Show some progress so that the user knows the page is beginning to
2593 // load
Leon Scroggins92472e82010-02-17 16:32:28 -05002594 onProgressChanged(view, INITIAL_PROGRESS);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002595 mDidStopLoad = false;
Grace Kloba22ac16e2009-10-07 18:00:23 -07002596 if (!mIsNetworkUp) createAndShowNetworkDialog();
Cary Clark01cfcdd2010-06-04 16:36:45 -04002597 closeDialogs();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002598 if (mSettings.isTracing()) {
2599 String host;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002600 try {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002601 WebAddress uri = new WebAddress(url);
2602 host = uri.mHost;
2603 } catch (android.net.ParseException ex) {
2604 host = "browser";
The Android Open Source Project0c908882009-03-03 19:32:16 -08002605 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002606 host = host.replace('.', '_');
2607 host += ".trace";
2608 mInTrace = true;
2609 Debug.startMethodTracing(host, 20 * 1024 * 1024);
2610 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002611
Grace Kloba22ac16e2009-10-07 18:00:23 -07002612 // Performance probe
2613 if (false) {
2614 mStart = SystemClock.uptimeMillis();
2615 mProcessStart = Process.getElapsedCpuTime();
2616 long[] sysCpu = new long[7];
2617 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2618 sysCpu, null)) {
2619 mUserStart = sysCpu[0] + sysCpu[1];
2620 mSystemStart = sysCpu[2];
2621 mIdleStart = sysCpu[3];
2622 mIrqStart = sysCpu[4] + sysCpu[5] + sysCpu[6];
2623 }
2624 mUiStart = SystemClock.currentThreadTimeMillis();
2625 }
2626 }
2627
2628 void onPageFinished(WebView view, String url) {
2629 // Reset the title and icon in case we stopped a provisional load.
2630 resetTitleAndIcon(view);
2631 // Update the lock icon image only once we are done loading
2632 updateLockIconToLatest();
2633 // pause the WebView timer and release the wake lock if it is finished
2634 // while BrowserActivity is in pause state.
2635 if (mActivityInPause && pauseWebViewTimers()) {
2636 if (mWakeLock.isHeld()) {
2637 mHandler.removeMessages(RELEASE_WAKELOCK);
2638 mWakeLock.release();
2639 }
2640 }
2641
2642 // Performance probe
2643 if (false) {
2644 long[] sysCpu = new long[7];
2645 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2646 sysCpu, null)) {
2647 String uiInfo = "UI thread used "
2648 + (SystemClock.currentThreadTimeMillis() - mUiStart)
2649 + " ms";
2650 if (LOGD_ENABLED) {
2651 Log.d(LOGTAG, uiInfo);
2652 }
2653 //The string that gets written to the log
2654 String performanceString = "It took total "
2655 + (SystemClock.uptimeMillis() - mStart)
2656 + " ms clock time to load the page."
2657 + "\nbrowser process used "
2658 + (Process.getElapsedCpuTime() - mProcessStart)
2659 + " ms, user processes used "
2660 + (sysCpu[0] + sysCpu[1] - mUserStart) * 10
2661 + " ms, kernel used "
2662 + (sysCpu[2] - mSystemStart) * 10
2663 + " ms, idle took " + (sysCpu[3] - mIdleStart) * 10
2664 + " ms and irq took "
2665 + (sysCpu[4] + sysCpu[5] + sysCpu[6] - mIrqStart)
2666 * 10 + " ms, " + uiInfo;
2667 if (LOGD_ENABLED) {
2668 Log.d(LOGTAG, performanceString + "\nWebpage: " + url);
2669 }
2670 if (url != null) {
2671 // strip the url to maintain consistency
2672 String newUrl = new String(url);
2673 if (newUrl.startsWith("http://www.")) {
2674 newUrl = newUrl.substring(11);
2675 } else if (newUrl.startsWith("http://")) {
2676 newUrl = newUrl.substring(7);
2677 } else if (newUrl.startsWith("https://www.")) {
2678 newUrl = newUrl.substring(12);
2679 } else if (newUrl.startsWith("https://")) {
2680 newUrl = newUrl.substring(8);
2681 }
2682 if (LOGD_ENABLED) {
2683 Log.d(LOGTAG, newUrl + " loaded");
2684 }
Grace Kloba5b078b52009-06-24 20:23:41 -07002685 }
2686 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002687 }
Grace Kloba5b078b52009-06-24 20:23:41 -07002688
Grace Kloba22ac16e2009-10-07 18:00:23 -07002689 if (mInTrace) {
2690 mInTrace = false;
2691 Debug.stopMethodTracing();
2692 }
2693 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002694
Grace Klobae7fe26b2010-06-28 16:23:33 -07002695 private void closeEmptyChildTab() {
2696 Tab current = mTabControl.getCurrentTab();
2697 if (current != null
2698 && current.getWebView().copyBackForwardList().getSize() == 0) {
2699 Tab parent = current.getParentTab();
2700 if (parent != null) {
2701 switchToTab(mTabControl.getTabIndex(parent));
2702 closeTab(current);
2703 }
2704 }
2705 }
2706
Grace Kloba22ac16e2009-10-07 18:00:23 -07002707 boolean shouldOverrideUrlLoading(WebView view, String url) {
2708 if (url.startsWith(SCHEME_WTAI)) {
2709 // wtai://wp/mc;number
2710 // number=string(phone-number)
2711 if (url.startsWith(SCHEME_WTAI_MC)) {
2712 Intent intent = new Intent(Intent.ACTION_VIEW,
2713 Uri.parse(WebView.SCHEME_TEL +
2714 url.substring(SCHEME_WTAI_MC.length())));
2715 startActivity(intent);
Grace Klobae7fe26b2010-06-28 16:23:33 -07002716 // before leaving BrowserActivity, close the empty child tab.
2717 // If a new tab is created through JavaScript open to load this
2718 // url, we would like to close it as we will load this url in a
2719 // different Activity.
2720 closeEmptyChildTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002721 return true;
2722 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002723 // wtai://wp/sd;dtmf
2724 // dtmf=string(dialstring)
2725 if (url.startsWith(SCHEME_WTAI_SD)) {
2726 // TODO: only send when there is active voice connection
2727 return false;
2728 }
2729 // wtai://wp/ap;number;name
2730 // number=string(phone-number)
2731 // name=string
2732 if (url.startsWith(SCHEME_WTAI_AP)) {
2733 // TODO
2734 return false;
2735 }
2736 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002737
Grace Kloba22ac16e2009-10-07 18:00:23 -07002738 // The "about:" schemes are internal to the browser; don't want these to
2739 // be dispatched to other apps.
2740 if (url.startsWith("about:")) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002741 return false;
2742 }
2743
Grace Kloba22ac16e2009-10-07 18:00:23 -07002744 Intent intent;
2745 // perform generic parsing of the URI to turn it into an Intent.
2746 try {
2747 intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME);
2748 } catch (URISyntaxException ex) {
2749 Log.w("Browser", "Bad URI " + url + ": " + ex.getMessage());
2750 return false;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002751 }
2752
Grace Kloba22ac16e2009-10-07 18:00:23 -07002753 // check whether the intent can be resolved. If not, we will see
2754 // whether we can download it from the Market.
2755 if (getPackageManager().resolveActivity(intent, 0) == null) {
2756 String packagename = intent.getPackage();
2757 if (packagename != null) {
2758 intent = new Intent(Intent.ACTION_VIEW, Uri
2759 .parse("market://search?q=pname:" + packagename));
2760 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2761 startActivity(intent);
Grace Klobae7fe26b2010-06-28 16:23:33 -07002762 // before leaving BrowserActivity, close the empty child tab.
2763 // If a new tab is created through JavaScript open to load this
2764 // url, we would like to close it as we will load this url in a
2765 // different Activity.
2766 closeEmptyChildTab();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002767 return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002768 } else {
2769 return false;
2770 }
2771 }
2772
Grace Kloba22ac16e2009-10-07 18:00:23 -07002773 // sanitize the Intent, ensuring web pages can not bypass browser
2774 // security (only access to BROWSABLE activities).
2775 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2776 intent.setComponent(null);
2777 try {
2778 if (startActivityIfNeeded(intent, -1)) {
Grace Klobae7fe26b2010-06-28 16:23:33 -07002779 // before leaving BrowserActivity, close the empty child tab.
2780 // If a new tab is created through JavaScript open to load this
2781 // url, we would like to close it as we will load this url in a
2782 // different Activity.
2783 closeEmptyChildTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002784 return true;
2785 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002786 } catch (ActivityNotFoundException ex) {
2787 // ignore the error. If no application can handle the URL,
2788 // eg about:blank, assume the browser can handle it.
2789 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002790
Grace Kloba22ac16e2009-10-07 18:00:23 -07002791 if (mMenuIsDown) {
2792 openTab(url);
2793 closeOptionsMenu();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002794 return true;
2795 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002796 return false;
2797 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002798
Grace Kloba22ac16e2009-10-07 18:00:23 -07002799 // -------------------------------------------------------------------------
2800 // Helper function for WebChromeClient
2801 // -------------------------------------------------------------------------
The Android Open Source Project0c908882009-03-03 19:32:16 -08002802
Grace Kloba22ac16e2009-10-07 18:00:23 -07002803 void onProgressChanged(WebView view, int newProgress) {
Michael Kolba2b2ba82010-08-04 17:54:03 -07002804
2805 // On the phone, the fake title bar will always cover up the
2806 // regular title bar (or the regular one is offscreen), so only the
2807 // fake title bar needs to change its progress
2808 mFakeTitleBar.setProgress(newProgress);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002809
Grace Kloba22ac16e2009-10-07 18:00:23 -07002810 if (newProgress == 100) {
2811 // onProgressChanged() may continue to be called after the main
2812 // frame has finished loading, as any remaining sub frames continue
2813 // to load. We'll only get called once though with newProgress as
2814 // 100 when everything is loaded. (onPageFinished is called once
2815 // when the main frame completes loading regardless of the state of
2816 // any sub frames so calls to onProgressChanges may continue after
2817 // onPageFinished has executed)
2818 if (mInLoad) {
2819 mInLoad = false;
Leon Scrogginsa27ff192009-09-14 12:58:04 -04002820 updateInLoadMenuItems();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002821 // If the options menu is open, leave the title bar
2822 if (!mOptionsMenuOpen || !mIconView) {
2823 hideFakeTitleBar();
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07002824 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002825 }
Leon Scrogginsaa37e7f2010-03-05 11:51:20 -05002826 } else {
2827 if (!mInLoad) {
2828 // onPageFinished may have already been called but a subframe is
2829 // still loading and updating the progress. Reset mInLoad and
2830 // update the menu items.
2831 mInLoad = true;
2832 updateInLoadMenuItems();
2833 }
2834 // When the page first begins to load, the Activity may still be
2835 // paused, in which case showFakeTitleBar will do nothing. Call
2836 // again as the page continues to load so that it will be shown.
2837 // (Calling it will the fake title bar is already showing will also
2838 // do nothing.
Grace Kloba22ac16e2009-10-07 18:00:23 -07002839 if (!mOptionsMenuOpen || mIconView) {
2840 // This page has begun to load, so show the title bar
2841 showFakeTitleBar();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002842 }
2843 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002844 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002845
Grace Kloba22ac16e2009-10-07 18:00:23 -07002846 void onShowCustomView(View view, WebChromeClient.CustomViewCallback callback) {
Derek Sollenberger8ff57db2009-12-08 15:39:55 -05002847 // if a view already exists then immediately terminate the new one
2848 if (mCustomView != null) {
2849 callback.onCustomViewHidden();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002850 return;
Derek Sollenberger8ff57db2009-12-08 15:39:55 -05002851 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002852
2853 // Add the custom view to its container.
2854 mCustomViewContainer.addView(view, COVER_SCREEN_GRAVITY_CENTER);
2855 mCustomView = view;
2856 mCustomViewCallback = callback;
2857 // Save the menu state and set it to empty while the custom
2858 // view is showing.
2859 mOldMenuState = mMenuState;
2860 mMenuState = EMPTY_MENU;
2861 // Hide the content view.
2862 mContentView.setVisibility(View.GONE);
2863 // Finally show the custom view container.
Andrei Popescu163ab742009-10-20 17:58:23 +01002864 setStatusBarVisibility(false);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002865 mCustomViewContainer.setVisibility(View.VISIBLE);
2866 mCustomViewContainer.bringToFront();
2867 }
2868
2869 void onHideCustomView() {
2870 if (mCustomView == null)
2871 return;
2872
2873 // Hide the custom view.
2874 mCustomView.setVisibility(View.GONE);
2875 // Remove the custom view from its container.
2876 mCustomViewContainer.removeView(mCustomView);
2877 mCustomView = null;
2878 // Reset the old menu state.
2879 mMenuState = mOldMenuState;
2880 mOldMenuState = EMPTY_MENU;
2881 mCustomViewContainer.setVisibility(View.GONE);
2882 mCustomViewCallback.onCustomViewHidden();
2883 // Show the content view.
Andrei Popescu163ab742009-10-20 17:58:23 +01002884 setStatusBarVisibility(true);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002885 mContentView.setVisibility(View.VISIBLE);
2886 }
2887
2888 Bitmap getDefaultVideoPoster() {
2889 if (mDefaultVideoPoster == null) {
2890 mDefaultVideoPoster = BitmapFactory.decodeResource(
2891 getResources(), R.drawable.default_video_poster);
Patrick Scott3918d442009-08-04 13:22:29 -04002892 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002893 return mDefaultVideoPoster;
2894 }
Patrick Scott3918d442009-08-04 13:22:29 -04002895
Grace Kloba22ac16e2009-10-07 18:00:23 -07002896 View getVideoLoadingProgressView() {
2897 if (mVideoProgressView == null) {
2898 LayoutInflater inflater = LayoutInflater.from(BrowserActivity.this);
2899 mVideoProgressView = inflater.inflate(
2900 R.layout.video_loading_progress, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002901 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002902 return mVideoProgressView;
2903 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002904
Leon Scroggins8d5fa432009-10-02 15:55:59 -04002905 /*
2906 * The Object used to inform the WebView of the file to upload.
2907 */
2908 private ValueCallback<Uri> mUploadMessage;
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002909 private String mCameraFilePath;
Leon Scroggins8d5fa432009-10-02 15:55:59 -04002910
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002911 void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
2912
2913 final String imageMimeType = "image/*";
Ben Murdoch6af492a2010-06-15 12:38:17 +01002914 final String videoMimeType = "video/*";
Ben Murdoch039bd472010-07-21 21:26:57 +01002915 final String audioMimeType = "audio/*";
Ben Murdochb50d7402010-07-16 12:42:22 +01002916 final String mediaSourceKey = "capture";
Ben Murdoch6af492a2010-06-15 12:38:17 +01002917 final String mediaSourceValueCamera = "camera";
Ben Murdochb50d7402010-07-16 12:42:22 +01002918 final String mediaSourceValueFileSystem = "filesystem";
Ben Murdoch6af492a2010-06-15 12:38:17 +01002919 final String mediaSourceValueCamcorder = "camcorder";
Ben Murdoch039bd472010-07-21 21:26:57 +01002920 final String mediaSourceValueMicrophone = "microphone";
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002921
Ben Murdoch039bd472010-07-21 21:26:57 +01002922 // media source can be 'filesystem' or 'camera' or 'camcorder' or 'microphone'.
Ben Murdoch6af492a2010-06-15 12:38:17 +01002923 String mediaSource = "";
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002924
Ben Murdoch6af492a2010-06-15 12:38:17 +01002925 // We add the camera intent if there was no accept type (or '*/*' or 'image/*').
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002926 boolean addCameraIntent = true;
Ben Murdoch6af492a2010-06-15 12:38:17 +01002927 // We add the camcorder intent if there was no accept type (or '*/*' or 'video/*').
2928 boolean addCamcorderIntent = true;
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002929
Ben Murdoch6af492a2010-06-15 12:38:17 +01002930 if (mUploadMessage != null) {
2931 // Already a file picker operation in progress.
2932 return;
2933 }
2934
Grace Kloba22ac16e2009-10-07 18:00:23 -07002935 mUploadMessage = uploadMsg;
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002936
2937 // Parse the accept type.
2938 String params[] = acceptType.split(";");
2939 String mimeType = params[0];
2940
2941 for (String p : params) {
2942 String[] keyValue = p.split("=");
2943 if (keyValue.length == 2) {
2944 // Process key=value parameters.
Ben Murdoch6af492a2010-06-15 12:38:17 +01002945 if (mediaSourceKey.equals(keyValue[0])) {
2946 mediaSource = keyValue[1];
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002947 }
2948 }
2949 }
2950
2951 // This intent will display the standard OPENABLE file picker.
Grace Kloba22ac16e2009-10-07 18:00:23 -07002952 Intent i = new Intent(Intent.ACTION_GET_CONTENT);
2953 i.addCategory(Intent.CATEGORY_OPENABLE);
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002954
2955 // Create an intent to add to the standard file picker that will
2956 // capture an image from the camera. We'll combine this intent with
2957 // the standard OPENABLE picker unless the web developer specifically
2958 // requested the camera or gallery be opened by passing a parameter
2959 // in the accept type.
2960 Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
2961 File externalDataDir = Environment.getExternalStoragePublicDirectory(
2962 Environment.DIRECTORY_DCIM);
2963 File cameraDataDir = new File(externalDataDir.getAbsolutePath() +
2964 File.separator + "browser-photos");
2965 cameraDataDir.mkdirs();
2966 mCameraFilePath = cameraDataDir.getAbsolutePath() + File.separator +
2967 System.currentTimeMillis() + ".jpg";
2968 cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(mCameraFilePath)));
2969
Ben Murdoch6af492a2010-06-15 12:38:17 +01002970 Intent camcorderIntent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
2971
Ben Murdoch039bd472010-07-21 21:26:57 +01002972 Intent soundRecIntent = new Intent(MediaStore.Audio.Media.RECORD_SOUND_ACTION);
2973
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002974 if (mimeType.equals(imageMimeType)) {
2975 i.setType(imageMimeType);
Ben Murdoch6af492a2010-06-15 12:38:17 +01002976 addCamcorderIntent = false;
2977 if (mediaSource.equals(mediaSourceValueCamera)) {
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002978 // Specified 'image/*' and requested the camera, so go ahead and launch the camera
2979 // directly.
2980 BrowserActivity.this.startActivityForResult(cameraIntent, FILE_SELECTED);
2981 return;
Ben Murdochb50d7402010-07-16 12:42:22 +01002982 } else if (mediaSource.equals(mediaSourceValueFileSystem)) {
2983 // Specified filesytem as the source, so don't want to consider the camera.
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002984 addCameraIntent = false;
2985 }
Ben Murdoch6af492a2010-06-15 12:38:17 +01002986 } else if (mimeType.equals(videoMimeType)) {
2987 i.setType(videoMimeType);
2988 addCameraIntent = false;
2989 // The camcorder saves it's own file and returns it to us in the intent, so
2990 // we don't need to generate one here.
2991 mCameraFilePath = null;
2992
2993 if (mediaSource.equals(mediaSourceValueCamcorder)) {
Ben Murdoch039bd472010-07-21 21:26:57 +01002994 // Specified 'video/*' and requested the camcorder, so go ahead and launch the
2995 // camcorder directly.
Ben Murdoch6af492a2010-06-15 12:38:17 +01002996 BrowserActivity.this.startActivityForResult(camcorderIntent, FILE_SELECTED);
2997 return;
Ben Murdochb50d7402010-07-16 12:42:22 +01002998 } else if (mediaSource.equals(mediaSourceValueFileSystem)) {
2999 // Specified filesystem as the source, so don't want to consider the camcorder.
Ben Murdoch6af492a2010-06-15 12:38:17 +01003000 addCamcorderIntent = false;
3001 }
Ben Murdoch039bd472010-07-21 21:26:57 +01003002 } else if (mimeType.equals(audioMimeType)) {
3003 i.setType(audioMimeType);
3004 addCameraIntent = false;
3005 addCamcorderIntent = false;
3006 if (mediaSource.equals(mediaSourceValueMicrophone)) {
3007 // Specified 'audio/*' and requested microphone, so go ahead and launch the sound
3008 // recorder.
3009 BrowserActivity.this.startActivityForResult(soundRecIntent, FILE_SELECTED);
3010 return;
3011 }
3012 // On a default system, there is no single option to open an audio "gallery". Both the
3013 // sound recorder and music browser respond to the OPENABLE/audio/* intent unlike the
3014 // image/* and video/* OPENABLE intents where the image / video gallery are the only
3015 // respondants (and so the user is not prompted by default).
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003016 } else {
3017 i.setType("*/*");
3018 }
3019
Ben Murdoch6af492a2010-06-15 12:38:17 +01003020 // Combine the chooser and the extra choices (like camera or camcorder)
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003021 Intent chooser = new Intent(Intent.ACTION_CHOOSER);
3022 chooser.putExtra(Intent.EXTRA_INTENT, i);
3023
Ben Murdoch6af492a2010-06-15 12:38:17 +01003024 Vector<Intent> extraInitialIntents = new Vector<Intent>(0);
3025
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003026 if (addCameraIntent) {
Ben Murdoch6af492a2010-06-15 12:38:17 +01003027 extraInitialIntents.add(cameraIntent);
3028 }
3029
3030 if (addCamcorderIntent) {
3031 extraInitialIntents.add(camcorderIntent);
3032 }
3033
3034 if (extraInitialIntents.size() > 0) {
3035 Intent[] extraIntents = new Intent[extraInitialIntents.size()];
3036 chooser.putExtra(Intent.EXTRA_INITIAL_INTENTS, extraInitialIntents.toArray(extraIntents));
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003037 }
3038
3039 chooser.putExtra(Intent.EXTRA_TITLE, getString(R.string.choose_upload));
3040 BrowserActivity.this.startActivityForResult(chooser, FILE_SELECTED);
Grace Kloba22ac16e2009-10-07 18:00:23 -07003041 }
3042
3043 // -------------------------------------------------------------------------
3044 // Implement functions for DownloadListener
3045 // -------------------------------------------------------------------------
3046
The Android Open Source Project0c908882009-03-03 19:32:16 -08003047 /**
3048 * Notify the host application a download should be done, or that
3049 * the data should be streamed if a streaming viewer is available.
3050 * @param url The full url to the content that should be downloaded
3051 * @param contentDisposition Content-disposition http header, if
3052 * present.
3053 * @param mimetype The mimetype of the content reported by the server
3054 * @param contentLength The file size reported by the server
3055 */
3056 public void onDownloadStart(String url, String userAgent,
3057 String contentDisposition, String mimetype, long contentLength) {
3058 // if we're dealing wih A/V content that's not explicitly marked
3059 // for download, check if it's streamable.
3060 if (contentDisposition == null
Patrick Scotte1fb9662009-08-31 14:31:52 -04003061 || !contentDisposition.regionMatches(
3062 true, 0, "attachment", 0, 10)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003063 // query the package manager to see if there's a registered handler
3064 // that matches.
3065 Intent intent = new Intent(Intent.ACTION_VIEW);
3066 intent.setDataAndType(Uri.parse(url), mimetype);
Patrick Scotte1fb9662009-08-31 14:31:52 -04003067 ResolveInfo info = getPackageManager().resolveActivity(intent,
3068 PackageManager.MATCH_DEFAULT_ONLY);
3069 if (info != null) {
3070 ComponentName myName = getComponentName();
3071 // If we resolved to ourselves, we don't want to attempt to
3072 // load the url only to try and download it again.
3073 if (!myName.getPackageName().equals(
3074 info.activityInfo.packageName)
3075 || !myName.getClassName().equals(
3076 info.activityInfo.name)) {
3077 // someone (other than us) knows how to handle this mime
3078 // type with this scheme, don't download.
3079 try {
3080 startActivity(intent);
3081 return;
3082 } catch (ActivityNotFoundException ex) {
3083 if (LOGD_ENABLED) {
3084 Log.d(LOGTAG, "activity not found for " + mimetype
3085 + " over " + Uri.parse(url).getScheme(),
3086 ex);
3087 }
3088 // Best behavior is to fall back to a download in this
3089 // case
The Android Open Source Project0c908882009-03-03 19:32:16 -08003090 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003091 }
3092 }
3093 }
3094 onDownloadStartNoStream(url, userAgent, contentDisposition, mimetype, contentLength);
3095 }
3096
Kristian Monsenfa52d172010-03-25 18:29:21 +00003097 // This is to work around the fact that java.net.URI throws Exceptions
3098 // instead of just encoding URL's properly
3099 // Helper method for onDownloadStartNoStream
3100 private static String encodePath(String path) {
3101 char[] chars = path.toCharArray();
3102
3103 boolean needed = false;
3104 for (char c : chars) {
3105 if (c == '[' || c == ']') {
3106 needed = true;
3107 break;
3108 }
3109 }
3110 if (needed == false) {
3111 return path;
3112 }
3113
3114 StringBuilder sb = new StringBuilder("");
3115 for (char c : chars) {
3116 if (c == '[' || c == ']') {
3117 sb.append('%');
3118 sb.append(Integer.toHexString(c));
3119 } else {
3120 sb.append(c);
3121 }
3122 }
3123
3124 return sb.toString();
3125 }
3126
The Android Open Source Project0c908882009-03-03 19:32:16 -08003127 /**
3128 * Notify the host application a download should be done, even if there
3129 * is a streaming viewer available for thise type.
3130 * @param url The full url to the content that should be downloaded
3131 * @param contentDisposition Content-disposition http header, if
3132 * present.
3133 * @param mimetype The mimetype of the content reported by the server
3134 * @param contentLength The file size reported by the server
3135 */
3136 /*package */ void onDownloadStartNoStream(String url, String userAgent,
3137 String contentDisposition, String mimetype, long contentLength) {
3138
3139 String filename = URLUtil.guessFileName(url,
3140 contentDisposition, mimetype);
3141
3142 // Check to see if we have an SDCard
3143 String status = Environment.getExternalStorageState();
3144 if (!status.equals(Environment.MEDIA_MOUNTED)) {
3145 int title;
3146 String msg;
3147
3148 // Check to see if the SDCard is busy, same as the music app
3149 if (status.equals(Environment.MEDIA_SHARED)) {
3150 msg = getString(R.string.download_sdcard_busy_dlg_msg);
3151 title = R.string.download_sdcard_busy_dlg_title;
3152 } else {
3153 msg = getString(R.string.download_no_sdcard_dlg_msg, filename);
3154 title = R.string.download_no_sdcard_dlg_title;
3155 }
3156
3157 new AlertDialog.Builder(this)
3158 .setTitle(title)
3159 .setIcon(android.R.drawable.ic_dialog_alert)
3160 .setMessage(msg)
3161 .setPositiveButton(R.string.ok, null)
3162 .show();
3163 return;
3164 }
3165
Kristian Monsenfa52d172010-03-25 18:29:21 +00003166 // java.net.URI is a lot stricter than KURL so we have to encode some
3167 // extra characters. Fix for b 2538060 and b 1634719
3168 WebAddress webAddress;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003169 try {
Kristian Monsenfa52d172010-03-25 18:29:21 +00003170 webAddress = new WebAddress(url);
3171 webAddress.mPath = encodePath(webAddress.mPath);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003172 } catch (Exception e) {
Kristian Monsenfa52d172010-03-25 18:29:21 +00003173 // This only happens for very bad urls, we want to chatch the
3174 // exception here
3175 Log.e(LOGTAG, "Exception trying to parse url:" + url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003176 return;
3177 }
3178
3179 // XXX: Have to use the old url since the cookies were stored using the
3180 // old percent-encoded url.
3181 String cookies = CookieManager.getInstance().getCookie(url);
3182
3183 ContentValues values = new ContentValues();
Kristian Monsenfa52d172010-03-25 18:29:21 +00003184 values.put(Downloads.Impl.COLUMN_URI, webAddress.toString());
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08003185 values.put(Downloads.Impl.COLUMN_COOKIE_DATA, cookies);
3186 values.put(Downloads.Impl.COLUMN_USER_AGENT, userAgent);
3187 values.put(Downloads.Impl.COLUMN_NOTIFICATION_PACKAGE,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003188 getPackageName());
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08003189 values.put(Downloads.Impl.COLUMN_NOTIFICATION_CLASS,
Leon Scrogginsa563d092010-04-19 16:53:49 -04003190 OpenDownloadReceiver.class.getCanonicalName());
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08003191 values.put(Downloads.Impl.COLUMN_VISIBILITY,
3192 Downloads.Impl.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
3193 values.put(Downloads.Impl.COLUMN_MIME_TYPE, mimetype);
3194 values.put(Downloads.Impl.COLUMN_FILE_NAME_HINT, filename);
Kristian Monsenfa52d172010-03-25 18:29:21 +00003195 values.put(Downloads.Impl.COLUMN_DESCRIPTION, webAddress.mHost);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003196 if (contentLength > 0) {
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08003197 values.put(Downloads.Impl.COLUMN_TOTAL_BYTES, contentLength);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003198 }
3199 if (mimetype == null) {
3200 // We must have long pressed on a link or image to download it. We
3201 // are not sure of the mimetype in this case, so do a head request
3202 new FetchUrlMimeType(this).execute(values);
3203 } else {
3204 final Uri contentUri =
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08003205 getContentResolver().insert(Downloads.Impl.CONTENT_URI, values);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003206 }
Leon Scroggins9191a7f2010-03-18 14:44:44 -04003207 Toast.makeText(this, R.string.download_pending, Toast.LENGTH_SHORT)
3208 .show();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003209 }
3210
Grace Kloba22ac16e2009-10-07 18:00:23 -07003211 // -------------------------------------------------------------------------
3212
The Android Open Source Project0c908882009-03-03 19:32:16 -08003213 /**
3214 * Resets the lock icon. This method is called when we start a new load and
3215 * know the url to be loaded.
3216 */
3217 private void resetLockIcon(String url) {
3218 // Save the lock-icon state (we revert to it if the load gets cancelled)
Grace Kloba22ac16e2009-10-07 18:00:23 -07003219 mTabControl.getCurrentTab().resetLockIcon(url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003220 updateLockIconImage(LOCK_ICON_UNSECURE);
3221 }
3222
The Android Open Source Project0c908882009-03-03 19:32:16 -08003223 /**
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04003224 * Update the lock icon to correspond to our latest state.
3225 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003226 private void updateLockIconToLatest() {
Leon Scroggins91f65fc2010-06-29 13:52:39 -04003227 Tab t = mTabControl.getCurrentTab();
3228 if (t != null) {
3229 updateLockIconImage(t.getLockIconType());
3230 }
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04003231 }
3232
3233 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08003234 * Updates the lock-icon image in the title-bar.
3235 */
3236 private void updateLockIconImage(int lockIconType) {
3237 Drawable d = null;
3238 if (lockIconType == LOCK_ICON_SECURE) {
3239 d = mSecLockIcon;
3240 } else if (lockIconType == LOCK_ICON_MIXED) {
3241 d = mMixLockIcon;
3242 }
Leon Scroggins68579392009-09-15 15:31:54 -04003243 mTitleBar.setLock(d);
Michael Kolba2b2ba82010-08-04 17:54:03 -07003244 mFakeTitleBar.setLock(d);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003245 }
3246
3247 /**
3248 * Displays a page-info dialog.
3249 * @param tab The tab to show info about
3250 * @param fromShowSSLCertificateOnError The flag that indicates whether
3251 * this dialog was opened from the SSL-certificate-on-error dialog or
3252 * not. This is important, since we need to know whether to return to
3253 * the parent dialog or simply dismiss.
3254 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003255 private void showPageInfo(final Tab tab,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003256 final boolean fromShowSSLCertificateOnError) {
3257 final LayoutInflater factory = LayoutInflater
3258 .from(this);
3259
3260 final View pageInfoView = factory.inflate(R.layout.page_info, null);
3261
3262 final WebView view = tab.getWebView();
3263
3264 String url = null;
3265 String title = null;
3266
3267 if (view == null) {
3268 url = tab.getUrl();
3269 title = tab.getTitle();
3270 } else if (view == mTabControl.getCurrentWebView()) {
3271 // Use the cached title and url if this is the current WebView
3272 url = mUrl;
3273 title = mTitle;
3274 } else {
3275 url = view.getUrl();
3276 title = view.getTitle();
3277 }
3278
3279 if (url == null) {
3280 url = "";
3281 }
3282 if (title == null) {
3283 title = "";
3284 }
3285
3286 ((TextView) pageInfoView.findViewById(R.id.address)).setText(url);
3287 ((TextView) pageInfoView.findViewById(R.id.title)).setText(title);
3288
3289 mPageInfoView = tab;
Leon Scrogginsc7b92f82010-01-11 18:17:31 -05003290 mPageInfoFromShowSSLCertificateOnError = fromShowSSLCertificateOnError;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003291
3292 AlertDialog.Builder alertDialogBuilder =
3293 new AlertDialog.Builder(this)
3294 .setTitle(R.string.page_info).setIcon(android.R.drawable.ic_dialog_info)
3295 .setView(pageInfoView)
3296 .setPositiveButton(
3297 R.string.ok,
3298 new DialogInterface.OnClickListener() {
3299 public void onClick(DialogInterface dialog,
3300 int whichButton) {
3301 mPageInfoDialog = null;
3302 mPageInfoView = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003303
3304 // if we came here from the SSL error dialog
3305 if (fromShowSSLCertificateOnError) {
3306 // go back to the SSL error dialog
3307 showSSLCertificateOnError(
3308 mSSLCertificateOnErrorView,
3309 mSSLCertificateOnErrorHandler,
3310 mSSLCertificateOnErrorError);
3311 }
3312 }
3313 })
3314 .setOnCancelListener(
3315 new DialogInterface.OnCancelListener() {
3316 public void onCancel(DialogInterface dialog) {
3317 mPageInfoDialog = null;
3318 mPageInfoView = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003319
3320 // if we came here from the SSL error dialog
3321 if (fromShowSSLCertificateOnError) {
3322 // go back to the SSL error dialog
3323 showSSLCertificateOnError(
3324 mSSLCertificateOnErrorView,
3325 mSSLCertificateOnErrorHandler,
3326 mSSLCertificateOnErrorError);
3327 }
3328 }
3329 });
3330
3331 // if we have a main top-level page SSL certificate set or a certificate
3332 // error
3333 if (fromShowSSLCertificateOnError ||
3334 (view != null && view.getCertificate() != null)) {
3335 // add a 'View Certificate' button
3336 alertDialogBuilder.setNeutralButton(
3337 R.string.view_certificate,
3338 new DialogInterface.OnClickListener() {
3339 public void onClick(DialogInterface dialog,
3340 int whichButton) {
3341 mPageInfoDialog = null;
3342 mPageInfoView = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003343
3344 // if we came here from the SSL error dialog
3345 if (fromShowSSLCertificateOnError) {
3346 // go back to the SSL error dialog
3347 showSSLCertificateOnError(
3348 mSSLCertificateOnErrorView,
3349 mSSLCertificateOnErrorHandler,
3350 mSSLCertificateOnErrorError);
3351 } else {
3352 // otherwise, display the top-most certificate from
3353 // the chain
3354 if (view.getCertificate() != null) {
3355 showSSLCertificate(tab);
3356 }
3357 }
3358 }
3359 });
3360 }
3361
3362 mPageInfoDialog = alertDialogBuilder.show();
3363 }
3364
3365 /**
3366 * Displays the main top-level page SSL certificate dialog
3367 * (accessible from the Page-Info dialog).
3368 * @param tab The tab to show certificate for.
3369 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003370 private void showSSLCertificate(final Tab tab) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003371 final View certificateView =
3372 inflateCertificateView(tab.getWebView().getCertificate());
3373 if (certificateView == null) {
3374 return;
3375 }
3376
3377 LayoutInflater factory = LayoutInflater.from(this);
3378
3379 final LinearLayout placeholder =
3380 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3381
3382 LinearLayout ll = (LinearLayout) factory.inflate(
3383 R.layout.ssl_success, placeholder);
3384 ((TextView)ll.findViewById(R.id.success))
3385 .setText(R.string.ssl_certificate_is_valid);
3386
3387 mSSLCertificateView = tab;
3388 mSSLCertificateDialog =
3389 new AlertDialog.Builder(this)
3390 .setTitle(R.string.ssl_certificate).setIcon(
3391 R.drawable.ic_dialog_browser_certificate_secure)
3392 .setView(certificateView)
3393 .setPositiveButton(R.string.ok,
3394 new DialogInterface.OnClickListener() {
3395 public void onClick(DialogInterface dialog,
3396 int whichButton) {
3397 mSSLCertificateDialog = null;
3398 mSSLCertificateView = null;
3399
3400 showPageInfo(tab, false);
3401 }
3402 })
3403 .setOnCancelListener(
3404 new DialogInterface.OnCancelListener() {
3405 public void onCancel(DialogInterface dialog) {
3406 mSSLCertificateDialog = null;
3407 mSSLCertificateView = null;
3408
3409 showPageInfo(tab, false);
3410 }
3411 })
3412 .show();
3413 }
3414
3415 /**
3416 * Displays the SSL error certificate dialog.
3417 * @param view The target web-view.
3418 * @param handler The SSL error handler responsible for cancelling the
3419 * connection that resulted in an SSL error or proceeding per user request.
3420 * @param error The SSL error object.
3421 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003422 void showSSLCertificateOnError(
The Android Open Source Project0c908882009-03-03 19:32:16 -08003423 final WebView view, final SslErrorHandler handler, final SslError error) {
3424
3425 final View certificateView =
3426 inflateCertificateView(error.getCertificate());
3427 if (certificateView == null) {
3428 return;
3429 }
3430
3431 LayoutInflater factory = LayoutInflater.from(this);
3432
3433 final LinearLayout placeholder =
3434 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3435
3436 if (error.hasError(SslError.SSL_UNTRUSTED)) {
3437 LinearLayout ll = (LinearLayout)factory
3438 .inflate(R.layout.ssl_warning, placeholder);
3439 ((TextView)ll.findViewById(R.id.warning))
3440 .setText(R.string.ssl_untrusted);
3441 }
3442
3443 if (error.hasError(SslError.SSL_IDMISMATCH)) {
3444 LinearLayout ll = (LinearLayout)factory
3445 .inflate(R.layout.ssl_warning, placeholder);
3446 ((TextView)ll.findViewById(R.id.warning))
3447 .setText(R.string.ssl_mismatch);
3448 }
3449
3450 if (error.hasError(SslError.SSL_EXPIRED)) {
3451 LinearLayout ll = (LinearLayout)factory
3452 .inflate(R.layout.ssl_warning, placeholder);
3453 ((TextView)ll.findViewById(R.id.warning))
3454 .setText(R.string.ssl_expired);
3455 }
3456
3457 if (error.hasError(SslError.SSL_NOTYETVALID)) {
3458 LinearLayout ll = (LinearLayout)factory
3459 .inflate(R.layout.ssl_warning, placeholder);
3460 ((TextView)ll.findViewById(R.id.warning))
3461 .setText(R.string.ssl_not_yet_valid);
3462 }
3463
3464 mSSLCertificateOnErrorHandler = handler;
3465 mSSLCertificateOnErrorView = view;
3466 mSSLCertificateOnErrorError = error;
3467 mSSLCertificateOnErrorDialog =
3468 new AlertDialog.Builder(this)
3469 .setTitle(R.string.ssl_certificate).setIcon(
3470 R.drawable.ic_dialog_browser_certificate_partially_secure)
3471 .setView(certificateView)
3472 .setPositiveButton(R.string.ok,
3473 new DialogInterface.OnClickListener() {
3474 public void onClick(DialogInterface dialog,
3475 int whichButton) {
3476 mSSLCertificateOnErrorDialog = null;
3477 mSSLCertificateOnErrorView = null;
3478 mSSLCertificateOnErrorHandler = null;
3479 mSSLCertificateOnErrorError = null;
3480
Grace Kloba22ac16e2009-10-07 18:00:23 -07003481 view.getWebViewClient().onReceivedSslError(
3482 view, handler, error);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003483 }
3484 })
3485 .setNeutralButton(R.string.page_info_view,
3486 new DialogInterface.OnClickListener() {
3487 public void onClick(DialogInterface dialog,
3488 int whichButton) {
3489 mSSLCertificateOnErrorDialog = null;
3490
3491 // do not clear the dialog state: we will
3492 // need to show the dialog again once the
3493 // user is done exploring the page-info details
3494
3495 showPageInfo(mTabControl.getTabFromView(view),
3496 true);
3497 }
3498 })
3499 .setOnCancelListener(
3500 new DialogInterface.OnCancelListener() {
3501 public void onCancel(DialogInterface dialog) {
3502 mSSLCertificateOnErrorDialog = null;
3503 mSSLCertificateOnErrorView = null;
3504 mSSLCertificateOnErrorHandler = null;
3505 mSSLCertificateOnErrorError = null;
3506
Grace Kloba22ac16e2009-10-07 18:00:23 -07003507 view.getWebViewClient().onReceivedSslError(
3508 view, handler, error);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003509 }
3510 })
3511 .show();
3512 }
3513
3514 /**
3515 * Inflates the SSL certificate view (helper method).
3516 * @param certificate The SSL certificate.
3517 * @return The resultant certificate view with issued-to, issued-by,
3518 * issued-on, expires-on, and possibly other fields set.
3519 * If the input certificate is null, returns null.
3520 */
3521 private View inflateCertificateView(SslCertificate certificate) {
3522 if (certificate == null) {
3523 return null;
3524 }
3525
3526 LayoutInflater factory = LayoutInflater.from(this);
3527
3528 View certificateView = factory.inflate(
3529 R.layout.ssl_certificate, null);
3530
3531 // issued to:
3532 SslCertificate.DName issuedTo = certificate.getIssuedTo();
3533 if (issuedTo != null) {
3534 ((TextView) certificateView.findViewById(R.id.to_common))
3535 .setText(issuedTo.getCName());
3536 ((TextView) certificateView.findViewById(R.id.to_org))
3537 .setText(issuedTo.getOName());
3538 ((TextView) certificateView.findViewById(R.id.to_org_unit))
3539 .setText(issuedTo.getUName());
3540 }
3541
3542 // issued by:
3543 SslCertificate.DName issuedBy = certificate.getIssuedBy();
3544 if (issuedBy != null) {
3545 ((TextView) certificateView.findViewById(R.id.by_common))
3546 .setText(issuedBy.getCName());
3547 ((TextView) certificateView.findViewById(R.id.by_org))
3548 .setText(issuedBy.getOName());
3549 ((TextView) certificateView.findViewById(R.id.by_org_unit))
3550 .setText(issuedBy.getUName());
3551 }
3552
3553 // issued on:
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003554 String issuedOn = formatCertificateDate(
3555 certificate.getValidNotBeforeDate());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003556 ((TextView) certificateView.findViewById(R.id.issued_on))
3557 .setText(issuedOn);
3558
3559 // expires on:
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003560 String expiresOn = formatCertificateDate(
3561 certificate.getValidNotAfterDate());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003562 ((TextView) certificateView.findViewById(R.id.expires_on))
3563 .setText(expiresOn);
3564
3565 return certificateView;
3566 }
3567
3568 /**
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003569 * Formats the certificate date to a properly localized date string.
The Android Open Source Project0c908882009-03-03 19:32:16 -08003570 * @return Properly localized version of the certificate date string and
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003571 * the "" if it fails to localize.
The Android Open Source Project0c908882009-03-03 19:32:16 -08003572 */
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003573 private String formatCertificateDate(Date certificateDate) {
3574 if (certificateDate == null) {
3575 return "";
The Android Open Source Project0c908882009-03-03 19:32:16 -08003576 }
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003577 String formattedDate = DateFormat.getDateFormat(this).format(certificateDate);
3578 if (formattedDate == null) {
3579 return "";
3580 }
3581 return formattedDate;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003582 }
3583
3584 /**
3585 * Displays an http-authentication dialog.
3586 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003587 void showHttpAuthentication(final HttpAuthHandler handler,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003588 final String host, final String realm, final String title,
3589 final String name, final String password, int focusId) {
3590 LayoutInflater factory = LayoutInflater.from(this);
3591 final View v = factory
3592 .inflate(R.layout.http_authentication, null);
3593 if (name != null) {
3594 ((EditText) v.findViewById(R.id.username_edit)).setText(name);
3595 }
3596 if (password != null) {
3597 ((EditText) v.findViewById(R.id.password_edit)).setText(password);
3598 }
3599
3600 String titleText = title;
3601 if (titleText == null) {
3602 titleText = getText(R.string.sign_in_to).toString().replace(
3603 "%s1", host).replace("%s2", realm);
3604 }
3605
3606 mHttpAuthHandler = handler;
3607 AlertDialog dialog = new AlertDialog.Builder(this)
3608 .setTitle(titleText)
3609 .setIcon(android.R.drawable.ic_dialog_alert)
3610 .setView(v)
3611 .setPositiveButton(R.string.action,
3612 new DialogInterface.OnClickListener() {
3613 public void onClick(DialogInterface dialog,
3614 int whichButton) {
3615 String nm = ((EditText) v
3616 .findViewById(R.id.username_edit))
3617 .getText().toString();
3618 String pw = ((EditText) v
3619 .findViewById(R.id.password_edit))
3620 .getText().toString();
3621 BrowserActivity.this.setHttpAuthUsernamePassword
3622 (host, realm, nm, pw);
3623 handler.proceed(nm, pw);
3624 mHttpAuthenticationDialog = null;
3625 mHttpAuthHandler = null;
3626 }})
3627 .setNegativeButton(R.string.cancel,
3628 new DialogInterface.OnClickListener() {
3629 public void onClick(DialogInterface dialog,
3630 int whichButton) {
3631 handler.cancel();
3632 BrowserActivity.this.resetTitleAndRevertLockIcon();
3633 mHttpAuthenticationDialog = null;
3634 mHttpAuthHandler = null;
3635 }})
3636 .setOnCancelListener(new DialogInterface.OnCancelListener() {
3637 public void onCancel(DialogInterface dialog) {
3638 handler.cancel();
3639 BrowserActivity.this.resetTitleAndRevertLockIcon();
3640 mHttpAuthenticationDialog = null;
3641 mHttpAuthHandler = null;
3642 }})
3643 .create();
3644 // Make the IME appear when the dialog is displayed if applicable.
3645 dialog.getWindow().setSoftInputMode(
3646 WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
3647 dialog.show();
3648 if (focusId != 0) {
3649 dialog.findViewById(focusId).requestFocus();
3650 } else {
3651 v.findViewById(R.id.username_edit).requestFocus();
3652 }
3653 mHttpAuthenticationDialog = dialog;
3654 }
3655
3656 public int getProgress() {
3657 WebView w = mTabControl.getCurrentWebView();
3658 if (w != null) {
3659 return w.getProgress();
3660 } else {
3661 return 100;
3662 }
3663 }
3664
3665 /**
3666 * Set HTTP authentication password.
3667 *
3668 * @param host The host for the password
3669 * @param realm The realm for the password
3670 * @param username The username for the password. If it is null, it means
3671 * password can't be saved.
3672 * @param password The password
3673 */
3674 public void setHttpAuthUsernamePassword(String host, String realm,
3675 String username,
3676 String password) {
Steve Block95a53b22010-03-25 17:24:58 +00003677 WebView w = getTopWindow();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003678 if (w != null) {
3679 w.setHttpAuthUsernamePassword(host, realm, username, password);
3680 }
3681 }
3682
3683 /**
3684 * connectivity manager says net has come or gone... inform the user
3685 * @param up true if net has come up, false if net has gone down
3686 */
3687 public void onNetworkToggle(boolean up) {
3688 if (up == mIsNetworkUp) {
3689 return;
3690 } else if (up) {
3691 mIsNetworkUp = true;
3692 if (mAlertDialog != null) {
3693 mAlertDialog.cancel();
3694 mAlertDialog = null;
3695 }
3696 } else {
3697 mIsNetworkUp = false;
Patrick Scotteb6ab2a2009-09-16 10:00:17 -04003698 if (mInLoad) {
3699 createAndShowNetworkDialog();
3700 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003701 }
3702 WebView w = mTabControl.getCurrentWebView();
3703 if (w != null) {
3704 w.setNetworkAvailable(up);
3705 }
3706 }
3707
Grace Kloba22ac16e2009-10-07 18:00:23 -07003708 boolean isNetworkUp() {
3709 return mIsNetworkUp;
3710 }
3711
Patrick Scotteb6ab2a2009-09-16 10:00:17 -04003712 // This method shows the network dialog alerting the user that the net is
3713 // down. It will only show the dialog if mAlertDialog is null.
3714 private void createAndShowNetworkDialog() {
3715 if (mAlertDialog == null) {
3716 mAlertDialog = new AlertDialog.Builder(this)
3717 .setTitle(R.string.loadSuspendedTitle)
3718 .setMessage(R.string.loadSuspended)
3719 .setPositiveButton(R.string.ok, null)
3720 .show();
3721 }
3722 }
3723
The Android Open Source Project0c908882009-03-03 19:32:16 -08003724 @Override
3725 protected void onActivityResult(int requestCode, int resultCode,
3726 Intent intent) {
Grace Klobabb394f32009-11-19 10:26:37 -08003727 if (getTopWindow() == null) return;
3728
The Android Open Source Project0c908882009-03-03 19:32:16 -08003729 switch (requestCode) {
3730 case COMBO_PAGE:
3731 if (resultCode == RESULT_OK && intent != null) {
3732 String data = intent.getAction();
3733 Bundle extras = intent.getExtras();
3734 if (extras != null && extras.getBoolean("new_window", false)) {
Leon Scroggins25d35472009-09-15 11:37:27 -04003735 openTab(data);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003736 } else {
Grace Kloba22ac16e2009-10-07 18:00:23 -07003737 final Tab currentTab =
The Android Open Source Project0c908882009-03-03 19:32:16 -08003738 mTabControl.getCurrentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04003739 dismissSubWindow(currentTab);
3740 if (data != null && data.length() != 0) {
Leon Scroggins92472e82010-02-17 16:32:28 -05003741 loadUrl(getTopWindow(), data);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003742 }
3743 }
3744 }
Leon Scrogginsfde97462010-01-11 13:06:21 -05003745 // Deliberately fall through to PREFERENCES_PAGE, since the
3746 // same extra may be attached to the COMBO_PAGE
3747 case PREFERENCES_PAGE:
3748 if (resultCode == RESULT_OK && intent != null) {
3749 String action = intent.getStringExtra(Intent.EXTRA_TEXT);
3750 if (BrowserSettings.PREF_CLEAR_HISTORY.equals(action)) {
3751 mTabControl.removeParentChildRelationShips();
3752 }
3753 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003754 break;
Leon Scroggins8d5fa432009-10-02 15:55:59 -04003755 // Choose a file from the file picker.
3756 case FILE_SELECTED:
3757 if (null == mUploadMessage) break;
3758 Uri result = intent == null || resultCode != RESULT_OK ? null
3759 : intent.getData();
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003760
3761 // As we ask the camera to save the result of the user taking
3762 // a picture, the camera application does not return anything other
3763 // than RESULT_OK. So we need to check whether the file we expected
3764 // was written to disk in the in the case that we
3765 // did not get an intent returned but did get a RESULT_OK. If it was,
3766 // we assume that this result has came back from the camera.
3767 if (result == null && intent == null && resultCode == RESULT_OK) {
3768 File cameraFile = new File(mCameraFilePath);
3769 if (cameraFile.exists()) {
3770 result = Uri.fromFile(cameraFile);
Ben Murdoch07d34732010-05-27 18:34:46 +01003771 // Broadcast to the media scanner that we have a new photo
3772 // so it will be added into the gallery for the user.
3773 sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, result));
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003774 }
3775 }
Leon Scroggins8d5fa432009-10-02 15:55:59 -04003776 mUploadMessage.onReceiveValue(result);
3777 mUploadMessage = null;
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003778 mCameraFilePath = null;
Leon Scroggins8d5fa432009-10-02 15:55:59 -04003779 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003780 default:
3781 break;
3782 }
Leon Scroggins30444232009-09-04 18:36:20 -04003783 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003784 }
3785
3786 /*
3787 * This method is called as a result of the user selecting the options
Leon Scrogginsf08809b2010-01-21 09:27:46 -05003788 * menu to see the download window. It shows the download window on top of
3789 * the current window.
The Android Open Source Project0c908882009-03-03 19:32:16 -08003790 */
Leon Scrogginsf08809b2010-01-21 09:27:46 -05003791 private void viewDownloads(Uri downloadRecord) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003792 Intent intent = new Intent(this,
3793 BrowserDownloadPage.class);
3794 intent.setData(downloadRecord);
Grace Kloba22ac16e2009-10-07 18:00:23 -07003795 startActivityForResult(intent, BrowserActivity.DOWNLOAD_PAGE);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003796
3797 }
3798
Ben Murdocheecb4e62010-07-06 16:30:38 +01003799 /* package*/ void promptAddOrInstallBookmark() {
3800 final Tab current = mTabControl.getCurrentTab();
3801 Resources resources = getResources();
3802 CharSequence[] choices = {
3803 resources.getString(R.string.save_to_bookmarks),
3804 resources.getString(R.string.create_shortcut_bookmark)
3805 };
3806
3807 AlertDialog.Builder builder = new AlertDialog.Builder(this);
3808 builder.setTitle(R.string.add_new_bookmark);
3809 builder.setItems(choices, new DialogInterface.OnClickListener() {
3810 public void onClick(DialogInterface dialog, int item) {
3811 if (item == 0) {
3812 bookmarkCurrentPage();
3813 } else if (item == 1) {
3814 current.populatePickerData();
3815 String touchIconUrl = mTabControl.getCurrentWebView().getTouchIconUrl();
3816 if (touchIconUrl != null) {
3817 // Download the touch icon for this site then save it to the
3818 // homescreen.
3819 Bundle b = new Bundle();
3820 b.putString("url", current.getUrl());
3821 b.putString("title", current.getTitle());
3822 b.putParcelable("favicon", current.getFavicon());
3823 Message msg = mHandler.obtainMessage(TOUCH_ICON_DOWNLOADED);
3824 msg.setData(b);
Ben Murdochccb5de02010-07-19 18:38:17 +01003825 new DownloadTouchIcon(BrowserActivity.this, msg,
Ben Murdocheecb4e62010-07-06 16:30:38 +01003826 mTabControl.getCurrentWebView().getSettings()
3827 .getUserAgentString()).execute(touchIconUrl);
3828 } else {
3829 // add to homescreen, can do it immediately as there is no touch
3830 // icon.
3831 showSaveToHomescreenDialog(current.getUrl(), current.getTitle(),
3832 null, current.getFavicon());
3833 }
3834 }
3835 }
3836 });
3837 builder.create().show();
3838 }
3839
Leon Scroggins160a7e72009-08-14 18:28:01 -04003840 /**
3841 * Open the Go page.
3842 * @param startWithHistory If true, open starting on the history tab.
3843 * Otherwise, start with the bookmarks tab.
Leon Scroggins160a7e72009-08-14 18:28:01 -04003844 */
Leon Scroggins30444232009-09-04 18:36:20 -04003845 /* package */ void bookmarksOrHistoryPicker(boolean startWithHistory) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003846 WebView current = mTabControl.getCurrentWebView();
3847 if (current == null) {
3848 return;
3849 }
3850 Intent intent = new Intent(this,
3851 CombinedBookmarkHistoryActivity.class);
3852 String title = current.getTitle();
3853 String url = current.getUrl();
Ben Murdoch87cc65d2010-06-29 20:34:10 +01003854 Bitmap thumbnail = createScreenshot(current, getDesiredThumbnailWidth(this),
3855 getDesiredThumbnailHeight(this));
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01003856
The Android Open Source Project0c908882009-03-03 19:32:16 -08003857 // Just in case the user opens bookmarks before a page finishes loading
3858 // so the current history item, and therefore the page, is null.
3859 if (null == url) {
3860 url = mLastEnteredUrl;
3861 // This can happen.
3862 if (null == url) {
3863 url = mSettings.getHomePage();
3864 }
3865 }
3866 // In case the web page has not yet received its associated title.
3867 if (title == null) {
3868 title = url;
3869 }
3870 intent.putExtra("title", title);
3871 intent.putExtra("url", url);
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01003872 intent.putExtra("thumbnail", thumbnail);
Leon Scroggins30444232009-09-04 18:36:20 -04003873 // Disable opening in a new window if we have maxed out the windows
Grace Kloba22ac16e2009-10-07 18:00:23 -07003874 intent.putExtra("disable_new_window", !mTabControl.canCreateNewTab());
Patrick Scott3918d442009-08-04 13:22:29 -04003875 intent.putExtra("touch_icon_url", current.getTouchIconUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003876 if (startWithHistory) {
3877 intent.putExtra(CombinedBookmarkHistoryActivity.STARTING_TAB,
3878 CombinedBookmarkHistoryActivity.HISTORY_TAB);
3879 }
3880 startActivityForResult(intent, COMBO_PAGE);
3881 }
3882
Ben Murdocheecb4e62010-07-06 16:30:38 +01003883 private void showSaveToHomescreenDialog(String url, String title, Bitmap touchIcon,
3884 Bitmap favicon) {
3885 Intent intent = new Intent(this, SaveToHomescreenDialog.class);
3886
3887 // Just in case the user tries to save before a page finishes loading
3888 // so the current history item, and therefore the page, is null.
3889 if (null == url) {
3890 url = mLastEnteredUrl;
3891 // This can happen.
3892 if (null == url) {
3893 url = mSettings.getHomePage();
3894 }
3895 }
3896
3897 // In case the web page has not yet received its associated title.
3898 if (title == null) {
3899 title = url;
3900 }
3901
3902 intent.putExtra("title", title);
3903 intent.putExtra("url", url);
3904 intent.putExtra("favicon", favicon);
3905 intent.putExtra("touchIcon", touchIcon);
3906 startActivity(intent);
3907 }
3908
3909
The Android Open Source Project0c908882009-03-03 19:32:16 -08003910 // Called when loading from context menu or LOAD_URL message
Leon Scroggins92472e82010-02-17 16:32:28 -05003911 private void loadUrlFromContext(WebView view, String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003912 // In case the user enters nothing.
3913 if (url != null && url.length() != 0 && view != null) {
3914 url = smartUrlFilter(url);
Grace Kloba22ac16e2009-10-07 18:00:23 -07003915 if (!view.getWebViewClient().shouldOverrideUrlLoading(view, url)) {
Leon Scroggins92472e82010-02-17 16:32:28 -05003916 loadUrl(view, url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003917 }
3918 }
3919 }
3920
Leon Scroggins92472e82010-02-17 16:32:28 -05003921 /**
3922 * Load the URL into the given WebView and update the title bar
3923 * to reflect the new load. Call this instead of WebView.loadUrl
3924 * directly.
3925 * @param view The WebView used to load url.
3926 * @param url The URL to load.
3927 */
3928 private void loadUrl(WebView view, String url) {
3929 updateTitleBarForNewLoad(view, url);
3930 view.loadUrl(url);
3931 }
3932
3933 /**
3934 * Load UrlData into a Tab and update the title bar to reflect the new
3935 * load. Call this instead of UrlData.loadIn directly.
3936 * @param t The Tab used to load.
3937 * @param data The UrlData being loaded.
3938 */
3939 private void loadUrlDataIn(Tab t, UrlData data) {
3940 updateTitleBarForNewLoad(t.getWebView(), data.mUrl);
3941 data.loadIn(t);
3942 }
3943
3944 /**
3945 * If the WebView is the top window, update the title bar to reflect
3946 * loading the new URL. i.e. set its text, clear the favicon (which
3947 * will be set once the page begins loading), and set the progress to
3948 * INITIAL_PROGRESS to show that the page has begun to load. Called
3949 * by loadUrl and loadUrlDataIn.
3950 * @param view The WebView that is starting a load.
3951 * @param url The URL that is being loaded.
3952 */
3953 private void updateTitleBarForNewLoad(WebView view, String url) {
3954 if (view == getTopWindow()) {
3955 setUrlTitle(url, null);
3956 setFavicon(null);
3957 onProgressChanged(view, INITIAL_PROGRESS);
3958 }
3959 }
3960
The Android Open Source Project0c908882009-03-03 19:32:16 -08003961 private String smartUrlFilter(Uri inUri) {
3962 if (inUri != null) {
3963 return smartUrlFilter(inUri.toString());
3964 }
3965 return null;
3966 }
3967
Feng Qianb34f87a2009-03-24 21:27:26 -07003968 protected static final Pattern ACCEPTED_URI_SCHEMA = Pattern.compile(
The Android Open Source Project0c908882009-03-03 19:32:16 -08003969 "(?i)" + // switch on case insensitive matching
3970 "(" + // begin group for schema
3971 "(?:http|https|file):\\/\\/" +
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003972 "|(?:inline|data|about|content|javascript):" +
The Android Open Source Project0c908882009-03-03 19:32:16 -08003973 ")" +
3974 "(.*)" );
3975
3976 /**
3977 * Attempts to determine whether user input is a URL or search
3978 * terms. Anything with a space is passed to search.
3979 *
3980 * Converts to lowercase any mistakenly uppercased schema (i.e.,
3981 * "Http://" converts to "http://"
3982 *
3983 * @return Original or modified URL
3984 *
3985 */
3986 String smartUrlFilter(String url) {
3987
3988 String inUrl = url.trim();
3989 boolean hasSpace = inUrl.indexOf(' ') != -1;
3990
3991 Matcher matcher = ACCEPTED_URI_SCHEMA.matcher(inUrl);
3992 if (matcher.matches()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003993 // force scheme to lowercase
3994 String scheme = matcher.group(1);
3995 String lcScheme = scheme.toLowerCase();
3996 if (!lcScheme.equals(scheme)) {
Mitsuru Oshima123ecfb2009-05-18 19:11:14 -07003997 inUrl = lcScheme + matcher.group(2);
3998 }
3999 if (hasSpace) {
4000 inUrl = inUrl.replace(" ", "%20");
The Android Open Source Project0c908882009-03-03 19:32:16 -08004001 }
4002 return inUrl;
4003 }
4004 if (hasSpace) {
Satish Sampath565505b2009-05-29 15:37:27 +01004005 // FIXME: Is this the correct place to add to searches?
4006 // what if someone else calls this function?
4007 int shortcut = parseUrlShortcut(inUrl);
4008 if (shortcut != SHORTCUT_INVALID) {
4009 Browser.addSearchUrl(mResolver, inUrl);
4010 String query = inUrl.substring(2);
4011 switch (shortcut) {
4012 case SHORTCUT_GOOGLE_SEARCH:
Grace Kloba47fdfdb2009-06-30 11:15:34 -07004013 return URLUtil.composeSearchUrl(query, QuickSearch_G, QUERY_PLACE_HOLDER);
Satish Sampath565505b2009-05-29 15:37:27 +01004014 case SHORTCUT_WIKIPEDIA_SEARCH:
4015 return URLUtil.composeSearchUrl(query, QuickSearch_W, QUERY_PLACE_HOLDER);
4016 case SHORTCUT_DICTIONARY_SEARCH:
4017 return URLUtil.composeSearchUrl(query, QuickSearch_D, QUERY_PLACE_HOLDER);
4018 case SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH:
The Android Open Source Project0c908882009-03-03 19:32:16 -08004019 // FIXME: we need location in this case
Satish Sampath565505b2009-05-29 15:37:27 +01004020 return URLUtil.composeSearchUrl(query, QuickSearch_L, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004021 }
4022 }
4023 } else {
Dan Egnor5ee906c2009-11-18 12:11:49 -08004024 if (Patterns.WEB_URL.matcher(inUrl).matches()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08004025 return URLUtil.guessUrl(inUrl);
4026 }
4027 }
4028
4029 Browser.addSearchUrl(mResolver, inUrl);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07004030 return URLUtil.composeSearchUrl(inUrl, QuickSearch_G, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004031 }
4032
Ben Murdochbff2d602009-07-01 20:19:05 +01004033 /* package */ void setShouldShowErrorConsole(boolean flag) {
4034 if (flag == mShouldShowErrorConsole) {
4035 // Nothing to do.
4036 return;
4037 }
4038
4039 mShouldShowErrorConsole = flag;
4040
Grace Kloba22ac16e2009-10-07 18:00:23 -07004041 ErrorConsoleView errorConsole = mTabControl.getCurrentTab()
4042 .getErrorConsole(true);
Ben Murdochbff2d602009-07-01 20:19:05 +01004043
4044 if (flag) {
4045 // Setting the show state of the console will cause it's the layout to be inflated.
4046 if (errorConsole.numberOfErrors() > 0) {
4047 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
4048 } else {
4049 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
4050 }
4051
4052 // Now we can add it to the main view.
4053 mErrorConsoleContainer.addView(errorConsole,
Romain Guy15b8ec62010-01-08 15:06:43 -08004054 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
Ben Murdochbff2d602009-07-01 20:19:05 +01004055 ViewGroup.LayoutParams.WRAP_CONTENT));
4056 } else {
4057 mErrorConsoleContainer.removeView(errorConsole);
4058 }
4059
4060 }
4061
Grace Kloba22ac16e2009-10-07 18:00:23 -07004062 boolean shouldShowErrorConsole() {
4063 return mShouldShowErrorConsole;
4064 }
4065
Andrei Popescu163ab742009-10-20 17:58:23 +01004066 private void setStatusBarVisibility(boolean visible) {
4067 int flag = visible ? 0 : WindowManager.LayoutParams.FLAG_FULLSCREEN;
4068 getWindow().setFlags(flag, WindowManager.LayoutParams.FLAG_FULLSCREEN);
4069 }
4070
Andrei Popescu56199cc2010-01-12 22:39:16 +00004071
4072 private void sendNetworkType(String type, String subtype) {
4073 WebView w = mTabControl.getCurrentWebView();
4074 if (w != null) {
4075 w.setNetworkType(type, subtype);
4076 }
4077 }
4078
Andrei Popescu30995e72010-02-09 16:59:58 +00004079 private void packageChanged(String packageName, boolean wasAdded) {
4080 WebView w = mTabControl.getCurrentWebView();
4081 if (w == null) {
4082 return;
4083 }
4084
4085 if (wasAdded) {
4086 w.addPackageName(packageName);
4087 } else {
4088 w.removePackageName(packageName);
4089 }
4090 }
4091
4092 private void addPackageNames(Set<String> packageNames) {
4093 WebView w = mTabControl.getCurrentWebView();
4094 if (w == null) {
4095 return;
4096 }
4097
4098 w.addPackageNames(packageNames);
4099 }
4100
4101 private void getInstalledPackages() {
4102 AsyncTask<Void, Void, Set<String> > task =
4103 new AsyncTask<Void, Void, Set<String> >() {
Michael Kolbe0a36662010-06-29 10:37:12 -07004104 @Override
Andrei Popescu30995e72010-02-09 16:59:58 +00004105 protected Set<String> doInBackground(Void... unused) {
4106 Set<String> installedPackages = new HashSet<String>();
4107 PackageManager pm = BrowserActivity.this.getPackageManager();
4108 if (pm != null) {
4109 List<PackageInfo> packages = pm.getInstalledPackages(0);
4110 for (PackageInfo p : packages) {
4111 if (BrowserActivity.this.sGoogleApps.contains(p.packageName)) {
4112 installedPackages.add(p.packageName);
4113 }
4114 }
4115 }
4116
4117 return installedPackages;
4118 }
4119
4120 // Executes on the UI thread
Michael Kolbe0a36662010-06-29 10:37:12 -07004121 @Override
Andrei Popescu30995e72010-02-09 16:59:58 +00004122 protected void onPostExecute(Set<String> installedPackages) {
4123 addPackageNames(installedPackages);
4124 }
4125 };
4126 task.execute();
4127 }
4128
Grace Klobaeb6eef42009-09-15 17:56:32 -07004129 final static int LOCK_ICON_UNSECURE = 0;
4130 final static int LOCK_ICON_SECURE = 1;
4131 final static int LOCK_ICON_MIXED = 2;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004132
The Android Open Source Project0c908882009-03-03 19:32:16 -08004133 private BrowserSettings mSettings;
4134 private TabControl mTabControl;
4135 private ContentResolver mResolver;
4136 private FrameLayout mContentView;
Andrei Popescuadc008d2009-06-26 14:11:30 +01004137 private View mCustomView;
4138 private FrameLayout mCustomViewContainer;
Andrei Popescuc9b55562009-07-07 10:51:15 +01004139 private WebChromeClient.CustomViewCallback mCustomViewCallback;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004140
4141 // FIXME, temp address onPrepareMenu performance problem. When we move everything out of
4142 // view, we should rewrite this.
4143 private int mCurrentMenuState = 0;
4144 private int mMenuState = R.id.MAIN_MENU;
Andrei Popescuadc008d2009-06-26 14:11:30 +01004145 private int mOldMenuState = EMPTY_MENU;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004146 private static final int EMPTY_MENU = -1;
4147 private Menu mMenu;
4148
4149 private FindDialog mFindDialog;
Cary Clark01cfcdd2010-06-04 16:36:45 -04004150 private SelectDialog mSelectDialog;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004151 // Used to prevent chording to result in firing two shortcuts immediately
4152 // one after another. Fixes bug 1211714.
4153 boolean mCanChord;
4154
4155 private boolean mInLoad;
4156 private boolean mIsNetworkUp;
Ben Murdochb7cc8b42009-09-28 10:59:09 +01004157 private boolean mDidStopLoad;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004158
Cary Clark1f10cbf2010-03-22 11:45:23 -04004159 /* package */ boolean mActivityInPause = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004160
4161 private boolean mMenuIsDown;
4162
The Android Open Source Project0c908882009-03-03 19:32:16 -08004163 private static boolean mInTrace;
4164
4165 // Performance probe
4166 private static final int[] SYSTEM_CPU_FORMAT = new int[] {
4167 Process.PROC_SPACE_TERM | Process.PROC_COMBINE,
4168 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 1: user time
4169 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 2: nice time
4170 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 3: sys time
4171 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 4: idle time
4172 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 5: iowait time
4173 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 6: irq time
4174 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG // 7: softirq time
4175 };
4176
4177 private long mStart;
4178 private long mProcessStart;
4179 private long mUserStart;
4180 private long mSystemStart;
4181 private long mIdleStart;
4182 private long mIrqStart;
4183
4184 private long mUiStart;
4185
4186 private Drawable mMixLockIcon;
4187 private Drawable mSecLockIcon;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004188
4189 /* hold a ref so we can auto-cancel if necessary */
4190 private AlertDialog mAlertDialog;
4191
The Android Open Source Project0c908882009-03-03 19:32:16 -08004192 // The up-to-date URL and title (these can be different from those stored
4193 // in WebView, since it takes some time for the information in WebView to
4194 // get updated)
4195 private String mUrl;
4196 private String mTitle;
4197
4198 // As PageInfo has different style for landscape / portrait, we have
4199 // to re-open it when configuration changed
4200 private AlertDialog mPageInfoDialog;
Grace Kloba22ac16e2009-10-07 18:00:23 -07004201 private Tab mPageInfoView;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004202 // If the Page-Info dialog is launched from the SSL-certificate-on-error
4203 // dialog, we should not just dismiss it, but should get back to the
4204 // SSL-certificate-on-error dialog. This flag is used to store this state
Leon Scrogginsc7b92f82010-01-11 18:17:31 -05004205 private boolean mPageInfoFromShowSSLCertificateOnError;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004206
4207 // as SSLCertificateOnError has different style for landscape / portrait,
4208 // we have to re-open it when configuration changed
4209 private AlertDialog mSSLCertificateOnErrorDialog;
4210 private WebView mSSLCertificateOnErrorView;
4211 private SslErrorHandler mSSLCertificateOnErrorHandler;
4212 private SslError mSSLCertificateOnErrorError;
4213
4214 // as SSLCertificate has different style for landscape / portrait, we
4215 // have to re-open it when configuration changed
4216 private AlertDialog mSSLCertificateDialog;
Grace Kloba22ac16e2009-10-07 18:00:23 -07004217 private Tab mSSLCertificateView;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004218
4219 // as HttpAuthentication has different style for landscape / portrait, we
4220 // have to re-open it when configuration changed
4221 private AlertDialog mHttpAuthenticationDialog;
4222 private HttpAuthHandler mHttpAuthHandler;
4223
4224 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_PARAMS =
4225 new FrameLayout.LayoutParams(
Romain Guy15b8ec62010-01-08 15:06:43 -08004226 ViewGroup.LayoutParams.MATCH_PARENT,
4227 ViewGroup.LayoutParams.MATCH_PARENT);
Andrei Popescuadc008d2009-06-26 14:11:30 +01004228 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_GRAVITY_CENTER =
4229 new FrameLayout.LayoutParams(
Romain Guy15b8ec62010-01-08 15:06:43 -08004230 ViewGroup.LayoutParams.MATCH_PARENT,
4231 ViewGroup.LayoutParams.MATCH_PARENT,
Andrei Popescuadc008d2009-06-26 14:11:30 +01004232 Gravity.CENTER);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07004233 // Google search
4234 final static String QuickSearch_G = "http://www.google.com/m?q=%s";
The Android Open Source Project0c908882009-03-03 19:32:16 -08004235 // Wikipedia search
4236 final static String QuickSearch_W = "http://en.wikipedia.org/w/index.php?search=%s&go=Go";
4237 // Dictionary search
4238 final static String QuickSearch_D = "http://dictionary.reference.com/search?q=%s";
4239 // Google Mobile Local search
4240 final static String QuickSearch_L = "http://www.google.com/m/search?site=local&q=%s&near=mountain+view";
4241
4242 final static String QUERY_PLACE_HOLDER = "%s";
4243
4244 // "source" parameter for Google search through search key
4245 final static String GOOGLE_SEARCH_SOURCE_SEARCHKEY = "browser-key";
4246 // "source" parameter for Google search through goto menu
4247 final static String GOOGLE_SEARCH_SOURCE_GOTO = "browser-goto";
4248 // "source" parameter for Google search through simplily type
4249 final static String GOOGLE_SEARCH_SOURCE_TYPE = "browser-type";
4250 // "source" parameter for Google search suggested by the browser
4251 final static String GOOGLE_SEARCH_SOURCE_SUGGEST = "browser-suggest";
4252 // "source" parameter for Google search from unknown source
4253 final static String GOOGLE_SEARCH_SOURCE_UNKNOWN = "unknown";
4254
4255 private final static String LOGTAG = "browser";
4256
The Android Open Source Project0c908882009-03-03 19:32:16 -08004257 private String mLastEnteredUrl;
4258
4259 private PowerManager.WakeLock mWakeLock;
4260 private final static int WAKELOCK_TIMEOUT = 5 * 60 * 1000; // 5 minutes
4261
4262 private Toast mStopToast;
4263
Leon Scroggins571b3762010-05-26 10:25:01 -04004264 private TitleBarBase mTitleBar;
Michael Kolba2b2ba82010-08-04 17:54:03 -07004265 private TabBar mTabBar;
Leon Scroggins81db3662009-06-04 17:45:11 -04004266
Ben Murdochbff2d602009-07-01 20:19:05 +01004267 private LinearLayout mErrorConsoleContainer = null;
4268 private boolean mShouldShowErrorConsole = false;
4269
The Android Open Source Project0c908882009-03-03 19:32:16 -08004270 // As the ids are dynamically created, we can't guarantee that they will
4271 // be in sequence, so this static array maps ids to a window number.
4272 final static private int[] WINDOW_SHORTCUT_ID_ARRAY =
4273 { R.id.window_one_menu_id, R.id.window_two_menu_id, R.id.window_three_menu_id,
4274 R.id.window_four_menu_id, R.id.window_five_menu_id, R.id.window_six_menu_id,
4275 R.id.window_seven_menu_id, R.id.window_eight_menu_id };
4276
4277 // monitor platform changes
4278 private IntentFilter mNetworkStateChangedFilter;
4279 private BroadcastReceiver mNetworkStateIntentReceiver;
4280
Grace Klobab4da0ad2009-05-14 14:45:40 -07004281 private BroadcastReceiver mPackageInstallationReceiver;
4282
Bjorn Bringerta7611812010-03-24 11:12:02 +00004283 private SystemAllowGeolocationOrigins mSystemAllowGeolocationOrigins;
4284
The Android Open Source Project0c908882009-03-03 19:32:16 -08004285 // activity requestCode
Nicolas Roard78a98e42009-05-11 13:34:17 +01004286 final static int COMBO_PAGE = 1;
4287 final static int DOWNLOAD_PAGE = 2;
4288 final static int PREFERENCES_PAGE = 3;
Leon Scroggins8d5fa432009-10-02 15:55:59 -04004289 final static int FILE_SELECTED = 4;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004290
Andrei Popescu540035d2009-09-18 18:59:20 +01004291 // the default <video> poster
4292 private Bitmap mDefaultVideoPoster;
4293 // the video progress view
4294 private View mVideoProgressView;
4295
Andrei Popescu30995e72010-02-09 16:59:58 +00004296 // The Google packages we monitor for the navigator.isApplicationInstalled()
4297 // API. Add as needed.
4298 private static Set<String> sGoogleApps;
4299 static {
4300 sGoogleApps = new HashSet<String>();
4301 sGoogleApps.add("com.google.android.youtube");
4302 }
4303
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004304 /**
4305 * A UrlData class to abstract how the content will be set to WebView.
4306 * This base class uses loadUrl to show the content.
4307 */
Leon Scroggins6eac63e2010-03-15 18:19:14 -04004308 /* package */ static class UrlData {
Grace Kloba068e48b2010-01-26 18:11:27 -08004309 final String mUrl;
4310 final Map<String, String> mHeaders;
Leon Scroggins58d56c62010-01-28 15:12:40 -05004311 final Intent mVoiceIntent;
Grace Kloba60e095c2009-06-16 11:50:55 -07004312
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004313 UrlData(String url) {
4314 this.mUrl = url;
Grace Kloba068e48b2010-01-26 18:11:27 -08004315 this.mHeaders = null;
Leon Scroggins58d56c62010-01-28 15:12:40 -05004316 this.mVoiceIntent = null;
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004317 }
Grace Kloba60e095c2009-06-16 11:50:55 -07004318
Leon Scroggins58d56c62010-01-28 15:12:40 -05004319 UrlData(String url, Map<String, String> headers, Intent intent) {
Grace Kloba068e48b2010-01-26 18:11:27 -08004320 this.mUrl = url;
4321 this.mHeaders = headers;
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -05004322 if (RecognizerResultsIntent.ACTION_VOICE_SEARCH_RESULTS
4323 .equals(intent.getAction())) {
Leon Scroggins58d56c62010-01-28 15:12:40 -05004324 this.mVoiceIntent = intent;
4325 } else {
4326 this.mVoiceIntent = null;
4327 }
Grace Kloba60e095c2009-06-16 11:50:55 -07004328 }
4329
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004330 boolean isEmpty() {
Leon Scroggins58d56c62010-01-28 15:12:40 -05004331 return mVoiceIntent == null && (mUrl == null || mUrl.length() == 0);
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004332 }
4333
Leon Scroggins92472e82010-02-17 16:32:28 -05004334 /**
4335 * Load this UrlData into the given Tab. Use loadUrlDataIn to update
4336 * the title bar as well.
4337 */
Leon Scroggins58d56c62010-01-28 15:12:40 -05004338 public void loadIn(Tab t) {
4339 if (mVoiceIntent != null) {
4340 t.activateVoiceSearchMode(mVoiceIntent);
4341 } else {
4342 t.getWebView().loadUrl(mUrl, mHeaders);
4343 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004344 }
4345 };
4346
Leon Scroggins1f005d32009-08-10 17:36:42 -04004347 /* package */ static final UrlData EMPTY_URL_DATA = new UrlData(null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004348}