blob: b9f5f01d88312b5b96a1ed3f1259bb1323ce87be [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.ServiceManager;
63import android.os.SystemClock;
The Android Open Source Project0c908882009-03-03 19:32:16 -080064import android.provider.Browser;
Cary Clark5e335a32009-09-22 14:53:11 -040065import android.provider.ContactsContract;
The Android Open Source Project0c908882009-03-03 19:32:16 -080066import android.provider.Downloads;
67import android.provider.MediaStore;
Michael Kolbe0a36662010-06-29 10:37:12 -070068import android.provider.ContactsContract.Intents.Insert;
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -050069import android.speech.RecognizerResultsIntent;
The Android Open Source Project0c908882009-03-03 19:32:16 -080070import android.text.TextUtils;
71import android.text.format.DateFormat;
The Android Open Source Project0c908882009-03-03 19:32:16 -080072import android.util.Log;
Dianne Hackborn385effd2010-02-24 20:03:04 -080073import android.util.Patterns;
The Android Open Source Project0c908882009-03-03 19:32:16 -080074import android.view.ContextMenu;
75import android.view.Gravity;
76import android.view.KeyEvent;
77import android.view.LayoutInflater;
78import android.view.Menu;
79import android.view.MenuInflater;
80import android.view.MenuItem;
81import android.view.View;
82import android.view.ViewGroup;
83import android.view.Window;
84import android.view.WindowManager;
85import android.view.ContextMenu.ContextMenuInfo;
86import android.view.MenuItem.OnMenuItemClickListener;
Svetoslav Ganov2b345992010-05-06 06:13:54 -070087import android.view.accessibility.AccessibilityManager;
The Android Open Source Project0c908882009-03-03 19:32:16 -080088import android.webkit.CookieManager;
89import android.webkit.CookieSyncManager;
90import android.webkit.DownloadListener;
91import android.webkit.HttpAuthHandler;
Grace Klobab4da0ad2009-05-14 14:45:40 -070092import android.webkit.PluginManager;
The Android Open Source Project0c908882009-03-03 19:32:16 -080093import android.webkit.SslErrorHandler;
94import android.webkit.URLUtil;
Leon Clarkecb6cc862009-09-29 18:35:13 +010095import android.webkit.ValueCallback;
The Android Open Source Project0c908882009-03-03 19:32:16 -080096import android.webkit.WebChromeClient;
97import android.webkit.WebHistoryItem;
98import android.webkit.WebIconDatabase;
99import android.webkit.WebView;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800100import android.widget.EditText;
101import android.widget.FrameLayout;
102import android.widget.LinearLayout;
103import android.widget.TextView;
104import android.widget.Toast;
105
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);
219
220
Leon Scrogginsd746a942010-05-19 13:21:44 -0400221 if (mXLargeScreenSize) {
Michael Kolbfe251992010-07-08 15:41:55 -0700222 mTitleBar = new TitleBarXLarge(this, mTabControl);
Leon Scrogginsd746a942010-05-19 13:21:44 -0400223 LinearLayout layout = (LinearLayout) mBrowserFrameLayout.
224 findViewById(R.id.vertical_layout);
225 layout.addView(mTitleBar, 0, new LinearLayout.LayoutParams(
226 ViewGroup.LayoutParams.MATCH_PARENT,
227 ViewGroup.LayoutParams.WRAP_CONTENT));
228 } else {
Leon Scroggins571b3762010-05-26 10:25:01 -0400229 mTitleBar = new TitleBar(this);
Leon Scrogginsd746a942010-05-19 13:21:44 -0400230 // mTitleBar will be always be shown in the fully loaded mode on
231 // phone
232 mTitleBar.setProgress(100);
233 // Fake title bar is not needed in xlarge layout
234 mFakeTitleBar = new TitleBar(this);
235 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800236
The Android Open Source Project0c908882009-03-03 19:32:16 -0800237
238 // 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
Leon Scroggins58d56c62010-01-28 15:12:40 -0500397 /**
398 * Feed the previously stored results strings to the BrowserProvider so that
399 * the SearchDialog will show them instead of the standard searches.
400 * @param result String to show on the editable line of the SearchDialog.
401 */
402 /* package */ void showVoiceSearchResults(String result) {
403 ContentProviderClient client = mResolver.acquireContentProviderClient(
404 Browser.BOOKMARKS_URI);
405 ContentProvider prov = client.getLocalContentProvider();
406 BrowserProvider bp = (BrowserProvider) prov;
407 bp.setQueryResults(mTabControl.getCurrentTab().getVoiceSearchResults());
408 client.release();
409
Leon Scrogginsfbb3f152010-03-09 17:26:56 -0500410 Bundle bundle = createGoogleSearchSourceBundle(
411 GOOGLE_SEARCH_SOURCE_SEARCHKEY);
412 bundle.putBoolean(SearchManager.CONTEXT_IS_VOICE, true);
413 startSearch(result, false, bundle, false);
Leon Scroggins58d56c62010-01-28 15:12:40 -0500414 }
415
The Android Open Source Project0c908882009-03-03 19:32:16 -0800416 @Override
417 protected void onNewIntent(Intent intent) {
Grace Kloba22ac16e2009-10-07 18:00:23 -0700418 Tab current = mTabControl.getCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800419 // When a tab is closed on exit, the current tab index is set to -1.
420 // Reset before proceed as Browser requires the current tab to be set.
421 if (current == null) {
422 // Try to reset the tab in case the index was incorrect.
423 current = mTabControl.getTab(0);
424 if (current == null) {
425 // No tabs at all so just ignore this intent.
426 return;
427 }
428 mTabControl.setCurrentTab(current);
429 attachTabToContentView(current);
430 resetTitleAndIcon(current.getWebView());
431 }
432 final String action = intent.getAction();
433 final int flags = intent.getFlags();
434 if (Intent.ACTION_MAIN.equals(action) ||
435 (flags & Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY) != 0) {
436 // just resume the browser
437 return;
438 }
Leon Scrogginsb8a844d2010-03-18 15:06:15 -0400439 // In case the SearchDialog is open.
440 ((SearchManager) getSystemService(Context.SEARCH_SERVICE))
441 .stopSearch();
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -0500442 boolean activateVoiceSearch = RecognizerResultsIntent
443 .ACTION_VOICE_SEARCH_RESULTS.equals(action);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800444 if (Intent.ACTION_VIEW.equals(action)
445 || Intent.ACTION_SEARCH.equals(action)
446 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
Leon Scroggins58d56c62010-01-28 15:12:40 -0500447 || Intent.ACTION_WEB_SEARCH.equals(action)
448 || activateVoiceSearch) {
Leon Scroggins3b18ce32010-02-08 17:35:59 -0500449 if (current.isInVoiceSearchMode()) {
450 String title = current.getVoiceDisplayTitle();
451 if (title != null && title.equals(intent.getStringExtra(
452 SearchManager.QUERY))) {
453 // The user submitted the same search as the last voice
454 // search, so do nothing.
455 return;
456 }
Leon Scroggins1fe13a52010-02-09 15:31:26 -0500457 if (Intent.ACTION_SEARCH.equals(action)
458 && current.voiceSearchSourceIsGoogle()) {
459 Intent logIntent = new Intent(
460 LoggingEvents.ACTION_LOG_EVENT);
461 logIntent.putExtra(LoggingEvents.EXTRA_EVENT,
462 LoggingEvents.VoiceSearch.QUERY_UPDATED);
463 logIntent.putExtra(
464 LoggingEvents.VoiceSearch.EXTRA_QUERY_UPDATED_VALUE,
465 intent.getDataString());
466 sendBroadcast(logIntent);
467 // Note, onPageStarted will revert the voice title bar
468 // When http://b/issue?id=2379215 is fixed, we should update
469 // the title bar here.
470 }
Leon Scroggins3b18ce32010-02-08 17:35:59 -0500471 }
Satish Sampath565505b2009-05-29 15:37:27 +0100472 // If this was a search request (e.g. search query directly typed into the address bar),
473 // pass it on to the default web search provider.
474 if (handleWebSearchIntent(intent)) {
475 return;
476 }
477
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700478 UrlData urlData = getUrlDataFromIntent(intent);
479 if (urlData.isEmpty()) {
480 urlData = new UrlData(mSettings.getHomePage());
The Android Open Source Project0c908882009-03-03 19:32:16 -0800481 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700482
Grace Klobacc634032009-07-28 15:58:19 -0700483 final String appId = intent
484 .getStringExtra(Browser.EXTRA_APPLICATION_ID);
Leon Scroggins47208682010-04-07 17:59:48 -0400485 if ((Intent.ACTION_VIEW.equals(action)
486 // If a voice search has no appId, it means that it came
487 // from the browser. In that case, reuse the current tab.
488 || (activateVoiceSearch && appId != null))
Grace Klobacc634032009-07-28 15:58:19 -0700489 && !getPackageName().equals(appId)
490 && (flags & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0) {
Grace Kloba22ac16e2009-10-07 18:00:23 -0700491 Tab appTab = mTabControl.getTabFromId(appId);
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700492 if (appTab != null) {
493 Log.i(LOGTAG, "Reusing tab for " + appId);
494 // Dismiss the subwindow if applicable.
495 dismissSubWindow(appTab);
496 // Since we might kill the WebView, remove it from the
497 // content view first.
498 removeTabFromContentView(appTab);
499 // Recreate the main WebView after destroying the old one.
500 // If the WebView has the same original url and is on that
501 // page, it can be reused.
502 boolean needsLoad =
Leon Scroggins6eac63e2010-03-15 18:19:14 -0400503 mTabControl.recreateWebView(appTab, urlData);
Ben Murdochbff2d602009-07-01 20:19:05 +0100504
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700505 if (current != appTab) {
Leon Scroggins1f005d32009-08-10 17:36:42 -0400506 switchToTab(mTabControl.getTabIndex(appTab));
507 if (needsLoad) {
Patrick Scott9d53da02010-02-19 10:19:01 -0500508 loadUrlDataIn(appTab, urlData);
Leon Scroggins1f005d32009-08-10 17:36:42 -0400509 }
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700510 } else {
Leon Scroggins1f005d32009-08-10 17:36:42 -0400511 // If the tab was the current tab, we have to attach
512 // it to the view system again.
513 attachTabToContentView(appTab);
514 if (needsLoad) {
Patrick Scott9d53da02010-02-19 10:19:01 -0500515 loadUrlDataIn(appTab, urlData);
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700516 }
517 }
518 return;
Patrick Scottcd115892009-07-16 09:42:58 -0400519 } else {
520 // No matching application tab, try to find a regular tab
521 // with a matching url.
522 appTab = mTabControl.findUnusedTabWithUrl(urlData.mUrl);
Leon Scroggins25515f82009-08-19 15:31:58 -0400523 if (appTab != null) {
524 if (current != appTab) {
525 switchToTab(mTabControl.getTabIndex(appTab));
526 }
527 // Otherwise, we are already viewing the correct tab.
Patrick Scottcd115892009-07-16 09:42:58 -0400528 } else {
529 // if FLAG_ACTIVITY_BROUGHT_TO_FRONT flag is on, the url
530 // will be opened in a new tab unless we have reached
531 // MAX_TABS. Then the url will be opened in the current
532 // tab. If a new tab is created, it will have "true" for
533 // exit on close.
Leon Scroggins1f005d32009-08-10 17:36:42 -0400534 openTabAndShow(urlData, true, appId);
Patrick Scottcd115892009-07-16 09:42:58 -0400535 }
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700536 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800537 } else {
Grace Kloba638d3f42009-11-23 10:35:04 -0800538 if (!urlData.isEmpty()
539 && urlData.mUrl.startsWith("about:debug")) {
540 if ("about:debug.dom".equals(urlData.mUrl)) {
541 current.getWebView().dumpDomTree(false);
542 } else if ("about:debug.dom.file".equals(urlData.mUrl)) {
543 current.getWebView().dumpDomTree(true);
544 } else if ("about:debug.render".equals(urlData.mUrl)) {
545 current.getWebView().dumpRenderTree(false);
546 } else if ("about:debug.render.file".equals(urlData.mUrl)) {
547 current.getWebView().dumpRenderTree(true);
548 } else if ("about:debug.display".equals(urlData.mUrl)) {
549 current.getWebView().dumpDisplayTree();
Mike Reed9b78e1d2010-01-13 14:40:52 -0800550 } else if (urlData.mUrl.startsWith("about:debug.drag")) {
551 int index = urlData.mUrl.codePointAt(16) - '0';
552 if (index <= 0 || index > 9) {
553 current.getWebView().setDragTracker(null);
554 } else {
555 current.getWebView().setDragTracker(new MeshTracker(index));
556 }
Grace Kloba638d3f42009-11-23 10:35:04 -0800557 } else {
558 mSettings.toggleDebugSettings();
559 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800560 return;
561 }
Leon Scroggins1f005d32009-08-10 17:36:42 -0400562 // Get rid of the subwindow if it exists
563 dismissSubWindow(current);
Leon Scroggins8588d152010-04-15 11:01:53 -0400564 // If the current Tab is being used as an application tab,
565 // remove the association, since the new Intent means that it is
566 // no longer associated with that application.
567 current.setAppId(null);
Patrick Scott9d53da02010-02-19 10:19:01 -0500568 loadUrlDataIn(current, urlData);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800569 }
570 }
571 }
572
Satish Sampath565505b2009-05-29 15:37:27 +0100573 private int parseUrlShortcut(String url) {
574 if (url == null) return SHORTCUT_INVALID;
575
576 // FIXME: quick search, need to be customized by setting
577 if (url.length() > 2 && url.charAt(1) == ' ') {
578 switch (url.charAt(0)) {
579 case 'g': return SHORTCUT_GOOGLE_SEARCH;
580 case 'w': return SHORTCUT_WIKIPEDIA_SEARCH;
581 case 'd': return SHORTCUT_DICTIONARY_SEARCH;
582 case 'l': return SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH;
583 }
584 }
585 return SHORTCUT_INVALID;
586 }
587
588 /**
589 * Launches the default web search activity with the query parameters if the given intent's data
590 * are identified as plain search terms and not URLs/shortcuts.
591 * @return true if the intent was handled and web search activity was launched, false if not.
592 */
593 private boolean handleWebSearchIntent(Intent intent) {
594 if (intent == null) return false;
595
596 String url = null;
597 final String action = intent.getAction();
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -0500598 if (RecognizerResultsIntent.ACTION_VOICE_SEARCH_RESULTS.equals(
599 action)) {
Leon Scroggins58d56c62010-01-28 15:12:40 -0500600 return false;
601 }
Satish Sampath565505b2009-05-29 15:37:27 +0100602 if (Intent.ACTION_VIEW.equals(action)) {
Grace Kloba1e705052009-09-29 13:13:36 -0700603 Uri data = intent.getData();
604 if (data != null) url = data.toString();
Satish Sampath565505b2009-05-29 15:37:27 +0100605 } else if (Intent.ACTION_SEARCH.equals(action)
606 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
607 || Intent.ACTION_WEB_SEARCH.equals(action)) {
608 url = intent.getStringExtra(SearchManager.QUERY);
609 }
Bjorn Bringert04851702009-09-22 10:36:01 +0100610 return handleWebSearchRequest(url, intent.getBundleExtra(SearchManager.APP_DATA),
611 intent.getStringExtra(SearchManager.EXTRA_DATA_KEY));
Satish Sampath565505b2009-05-29 15:37:27 +0100612 }
613
614 /**
615 * Launches the default web search activity with the query parameters if the given url string
616 * was identified as plain search terms and not URL/shortcut.
617 * @return true if the request was handled and web search activity was launched, false if not.
618 */
Bjorn Bringert04851702009-09-22 10:36:01 +0100619 private boolean handleWebSearchRequest(String inUrl, Bundle appData, String extraData) {
Satish Sampath565505b2009-05-29 15:37:27 +0100620 if (inUrl == null) return false;
621
622 // In general, we shouldn't modify URL from Intent.
623 // But currently, we get the user-typed URL from search box as well.
624 String url = fixUrl(inUrl).trim();
625
626 // URLs and site specific search shortcuts are handled by the regular flow of control, so
627 // return early.
Dan Egnor5ee906c2009-11-18 12:11:49 -0800628 if (Patterns.WEB_URL.matcher(url).matches()
Satish Sampathbc5b9f32009-06-04 18:21:40 +0100629 || ACCEPTED_URI_SCHEMA.matcher(url).matches()
Satish Sampath565505b2009-05-29 15:37:27 +0100630 || parseUrlShortcut(url) != SHORTCUT_INVALID) {
631 return false;
632 }
633
Leon Scroggins8d06e362010-03-24 14:45:57 -0400634 final ContentResolver cr = mResolver;
635 final String newUrl = url;
Elliott Slaughterf0f03952010-07-14 18:10:36 -0700636 if (!mTabControl.getCurrentWebView().isPrivateBrowsingEnabled()) {
637 new AsyncTask<Void, Void, Void>() {
638 @Override
639 protected Void doInBackground(Void... unused) {
640 Browser.updateVisitedHistory(cr, newUrl, false);
641 Browser.addSearchUrl(cr, newUrl);
642 return null;
643 }
644 }.execute();
645 }
Satish Sampath565505b2009-05-29 15:37:27 +0100646
647 Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);
648 intent.addCategory(Intent.CATEGORY_DEFAULT);
649 intent.putExtra(SearchManager.QUERY, url);
Satish Sampath15e9f2d2009-06-23 22:29:49 +0100650 if (appData != null) {
651 intent.putExtra(SearchManager.APP_DATA, appData);
652 }
Bjorn Bringert04851702009-09-22 10:36:01 +0100653 if (extraData != null) {
654 intent.putExtra(SearchManager.EXTRA_DATA_KEY, extraData);
655 }
Grace Klobacc634032009-07-28 15:58:19 -0700656 intent.putExtra(Browser.EXTRA_APPLICATION_ID, getPackageName());
Satish Sampath565505b2009-05-29 15:37:27 +0100657 startActivity(intent);
658
659 return true;
660 }
661
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700662 private UrlData getUrlDataFromIntent(Intent intent) {
Leon Scroggins58d56c62010-01-28 15:12:40 -0500663 String url = "";
Grace Kloba068e48b2010-01-26 18:11:27 -0800664 Map<String, String> headers = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800665 if (intent != null) {
666 final String action = intent.getAction();
667 if (Intent.ACTION_VIEW.equals(action)) {
668 url = smartUrlFilter(intent.getData());
669 if (url != null && url.startsWith("content:")) {
670 /* Append mimetype so webview knows how to display */
671 String mimeType = intent.resolveType(getContentResolver());
672 if (mimeType != null) {
673 url += "?" + mimeType;
674 }
675 }
Grace Kloba068e48b2010-01-26 18:11:27 -0800676 if (url != null && url.startsWith("http")) {
Grace Kloba00f54c52010-01-27 14:53:51 -0800677 final Bundle pairs = intent
678 .getBundleExtra(Browser.EXTRA_HEADERS);
Grace Kloba2d508ed2010-01-28 11:39:15 -0800679 if (pairs != null && !pairs.isEmpty()) {
Grace Kloba00f54c52010-01-27 14:53:51 -0800680 Iterator<String> iter = pairs.keySet().iterator();
Grace Kloba068e48b2010-01-26 18:11:27 -0800681 headers = new HashMap<String, String>();
Grace Kloba00f54c52010-01-27 14:53:51 -0800682 while (iter.hasNext()) {
683 String key = iter.next();
684 headers.put(key, pairs.getString(key));
Grace Kloba068e48b2010-01-26 18:11:27 -0800685 }
686 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700687 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800688 } else if (Intent.ACTION_SEARCH.equals(action)
689 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
690 || Intent.ACTION_WEB_SEARCH.equals(action)) {
691 url = intent.getStringExtra(SearchManager.QUERY);
692 if (url != null) {
693 mLastEnteredUrl = url;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800694 // In general, we shouldn't modify URL from Intent.
695 // But currently, we get the user-typed URL from search box as well.
696 url = fixUrl(url);
697 url = smartUrlFilter(url);
Leon Scroggins8d06e362010-03-24 14:45:57 -0400698 final ContentResolver cr = mResolver;
699 final String newUrl = url;
700 new AsyncTask<Void, Void, Void>() {
Michael Kolbe0a36662010-06-29 10:37:12 -0700701 @Override
Leon Scroggins8d06e362010-03-24 14:45:57 -0400702 protected Void doInBackground(Void... unused) {
703 Browser.updateVisitedHistory(cr, newUrl, false);
704 return null;
705 }
706 }.execute();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800707 String searchSource = "&source=android-" + GOOGLE_SEARCH_SOURCE_SUGGEST + "&";
708 if (url.contains(searchSource)) {
709 String source = null;
710 final Bundle appData = intent.getBundleExtra(SearchManager.APP_DATA);
711 if (appData != null) {
Bjorn Bringert10d1cca2010-02-10 14:22:12 +0000712 source = appData.getString(Search.SOURCE);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800713 }
714 if (TextUtils.isEmpty(source)) {
715 source = GOOGLE_SEARCH_SOURCE_UNKNOWN;
716 }
717 url = url.replace(searchSource, "&source=android-"+source+"&");
718 }
719 }
720 }
721 }
Leon Scroggins58d56c62010-01-28 15:12:40 -0500722 return new UrlData(url, headers, intent);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800723 }
Leon Scroggins58d56c62010-01-28 15:12:40 -0500724 /* package */ void showVoiceTitleBar(String title) {
725 mTitleBar.setInVoiceMode(true);
Leon Scroggins58d56c62010-01-28 15:12:40 -0500726 mTitleBar.setDisplayTitle(title);
Leon Scrogginsd746a942010-05-19 13:21:44 -0400727
728 if (!mXLargeScreenSize) {
729 mFakeTitleBar.setInVoiceMode(true);
730 mFakeTitleBar.setDisplayTitle(title);
731 }
Leon Scroggins58d56c62010-01-28 15:12:40 -0500732 }
733 /* package */ void revertVoiceTitleBar() {
734 mTitleBar.setInVoiceMode(false);
Leon Scroggins003a5dd2010-03-10 12:13:14 -0500735 mTitleBar.setDisplayTitle(mUrl);
Leon Scrogginsd746a942010-05-19 13:21:44 -0400736
737 if (!mXLargeScreenSize) {
738 mFakeTitleBar.setInVoiceMode(false);
739 mFakeTitleBar.setDisplayTitle(mUrl);
740 }
Leon Scroggins58d56c62010-01-28 15:12:40 -0500741 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800742 /* package */ static String fixUrl(String inUrl) {
Cary Clark652ff872009-09-10 13:34:44 -0400743 // FIXME: Converting the url to lower case
744 // duplicates functionality in smartUrlFilter().
745 // However, changing all current callers of fixUrl to
746 // call smartUrlFilter in addition may have unwanted
747 // consequences, and is deferred for now.
748 int colon = inUrl.indexOf(':');
749 boolean allLower = true;
750 for (int index = 0; index < colon; index++) {
751 char ch = inUrl.charAt(index);
752 if (!Character.isLetter(ch)) {
753 break;
754 }
755 allLower &= Character.isLowerCase(ch);
756 if (index == colon - 1 && !allLower) {
757 inUrl = inUrl.substring(0, colon).toLowerCase()
758 + inUrl.substring(colon);
759 }
760 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800761 if (inUrl.startsWith("http://") || inUrl.startsWith("https://"))
762 return inUrl;
763 if (inUrl.startsWith("http:") ||
764 inUrl.startsWith("https:")) {
765 if (inUrl.startsWith("http:/") || inUrl.startsWith("https:/")) {
766 inUrl = inUrl.replaceFirst("/", "//");
767 } else inUrl = inUrl.replaceFirst(":", "://");
768 }
769 return inUrl;
770 }
771
Grace Kloba22ac16e2009-10-07 18:00:23 -0700772 @Override
773 protected void onResume() {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800774 super.onResume();
Dave Bort31a6d1c2009-04-13 15:56:49 -0700775 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800776 Log.v(LOGTAG, "BrowserActivity.onResume: this=" + this);
777 }
778
779 if (!mActivityInPause) {
780 Log.e(LOGTAG, "BrowserActivity is already resumed.");
781 return;
782 }
783
Mike Reed7bfa63b2009-05-28 11:08:32 -0400784 mTabControl.resumeCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800785 mActivityInPause = false;
Mike Reed7bfa63b2009-05-28 11:08:32 -0400786 resumeWebViewTimers();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800787
788 if (mWakeLock.isHeld()) {
789 mHandler.removeMessages(RELEASE_WAKELOCK);
790 mWakeLock.release();
791 }
792
The Android Open Source Project0c908882009-03-03 19:32:16 -0800793 registerReceiver(mNetworkStateIntentReceiver,
794 mNetworkStateChangedFilter);
795 WebView.enablePlatformNotifications();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800796 }
797
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400798 /**
799 * Since the actual title bar is embedded in the WebView, and removing it
Leon Scrogginsfe87bd32009-10-06 10:10:00 -0400800 * would change its appearance, use a different TitleBar to show overlayed
801 * at the top of the screen, when the menu is open or the page is loading.
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400802 */
803 private TitleBar mFakeTitleBar;
804
805 /**
806 * Keeps track of whether the options menu is open. This is important in
807 * determining whether to show or hide the title bar overlay.
808 */
809 private boolean mOptionsMenuOpen;
810
811 /**
812 * Only meaningful when mOptionsMenuOpen is true. This variable keeps track
813 * of whether the configuration has changed. The first onMenuOpened call
814 * after a configuration change is simply a reopening of the same menu
815 * (i.e. mIconView did not change).
816 */
817 private boolean mConfigChanged;
818
819 /**
820 * Whether or not the options menu is in its smaller, icon menu form. When
821 * true, we want the title bar overlay to be up. When false, we do not.
822 * Only meaningful if mOptionsMenuOpen is true.
823 */
824 private boolean mIconView;
825
Leon Scrogginsa81a7642009-08-31 17:05:41 -0400826 @Override
827 public boolean onMenuOpened(int featureId, Menu menu) {
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400828 if (Window.FEATURE_OPTIONS_PANEL == featureId) {
829 if (mOptionsMenuOpen) {
830 if (mConfigChanged) {
831 // We do not need to make any changes to the state of the
832 // title bar, since the only thing that happened was a
833 // change in orientation
834 mConfigChanged = false;
835 } else {
836 if (mIconView) {
837 // Switching the menu to expanded view, so hide the
838 // title bar.
839 hideFakeTitleBar();
840 mIconView = false;
841 } else {
842 // Switching the menu back to icon view, so show the
843 // title bar once again.
844 showFakeTitleBar();
845 mIconView = true;
846 }
847 }
848 } else {
849 // The options menu is closed, so open it, and show the title
850 showFakeTitleBar();
851 mOptionsMenuOpen = true;
852 mConfigChanged = false;
853 mIconView = true;
854 }
855 }
Leon Scrogginsa81a7642009-08-31 17:05:41 -0400856 return true;
857 }
858
Michael Kolbfe251992010-07-08 15:41:55 -0700859 private void rebuildTitleBar() {
860 if (mXLargeScreenSize) {
861 ((TitleBarXLarge) mTitleBar).rebuildLayout();
862 }
863 }
864
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400865 private void showFakeTitleBar() {
Leon Scrogginsd746a942010-05-19 13:21:44 -0400866 if (mXLargeScreenSize) return;
Leon Scrogginsfe87bd32009-10-06 10:10:00 -0400867 if (mFakeTitleBar.getParent() == null && mActiveTabsPage == null
Grace Kloba847c25b2010-03-30 16:00:26 -0700868 && !mActivityInPause) {
869 WebView mainView = mTabControl.getCurrentWebView();
870 // if there is no current WebView, don't show the faked title bar;
Grace Kloba65190702010-04-02 23:37:26 -0700871 if (mainView == null) {
Cary Clarka0464552009-09-29 13:00:45 -0400872 return;
873 }
Leon Scroggins79e36d92010-04-29 16:01:46 +0100874 // Do not need to check for null, since the current tab will have
875 // at least a main WebView, or we would have returned above.
Cary Clark01cfcdd2010-06-04 16:36:45 -0400876 if (dialogIsUp()) {
Leon Scroggins79e36d92010-04-29 16:01:46 +0100877 // Do not show the fake title bar, which would cover up the
Cary Clark01cfcdd2010-06-04 16:36:45 -0400878 // find or select dialog.
Leon Scroggins79e36d92010-04-29 16:01:46 +0100879 return;
880 }
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400881
882 WindowManager manager
883 = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
884
885 // Add the title bar to the window manager so it can receive touches
886 // while the menu is up
887 WindowManager.LayoutParams params
888 = new WindowManager.LayoutParams(
Romain Guy15b8ec62010-01-08 15:06:43 -0800889 ViewGroup.LayoutParams.MATCH_PARENT,
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400890 ViewGroup.LayoutParams.WRAP_CONTENT,
Grace Kloba847c25b2010-03-30 16:00:26 -0700891 WindowManager.LayoutParams.TYPE_APPLICATION,
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400892 WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
Leon Scroggins68549862009-09-21 16:02:01 -0400893 PixelFormat.TRANSLUCENT);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400894 params.gravity = Gravity.TOP;
Grace Kloba847c25b2010-03-30 16:00:26 -0700895 boolean atTop = mainView.getScrollY() == 0;
Leon Scroggins83932c72009-09-30 11:55:54 -0400896 params.windowAnimations = atTop ? 0 : R.style.TitleBar;
Grace Kloba13f9ace2010-03-18 21:44:14 -0700897 manager.addView(mFakeTitleBar, params);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400898 }
899 }
900
901 @Override
902 public void onOptionsMenuClosed(Menu menu) {
903 mOptionsMenuOpen = false;
Leon Scrogginsa27ff192009-09-14 12:58:04 -0400904 if (!mInLoad) {
905 hideFakeTitleBar();
906 } else if (!mIconView) {
907 // The page is currently loading, and we are in expanded mode, so
908 // we were not showing the menu. Show it once again. It will be
909 // removed when the page finishes.
910 showFakeTitleBar();
911 }
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400912 }
Grace Kloba22ac16e2009-10-07 18:00:23 -0700913
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400914 private void hideFakeTitleBar() {
Leon Scrogginsd746a942010-05-19 13:21:44 -0400915 if (mXLargeScreenSize || mFakeTitleBar.getParent() == null) return;
Leon Scroggins20329572009-09-23 17:42:41 -0400916 WindowManager.LayoutParams params = (WindowManager.LayoutParams)
Grace Kloba13f9ace2010-03-18 21:44:14 -0700917 mFakeTitleBar.getLayoutParams();
Leon Scroggins20329572009-09-23 17:42:41 -0400918 WebView mainView = mTabControl.getCurrentWebView();
919 // Although we decided whether or not to animate based on the current
920 // scroll position, the scroll position may have changed since the
921 // fake title bar was displayed. Make sure it has the appropriate
922 // animation/lack thereof before removing.
923 params.windowAnimations = mainView != null && mainView.getScrollY() == 0
Leon Scroggins83932c72009-09-30 11:55:54 -0400924 ? 0 : R.style.TitleBar;
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400925 WindowManager manager
926 = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
Grace Kloba13f9ace2010-03-18 21:44:14 -0700927 manager.updateViewLayout(mFakeTitleBar, params);
928 manager.removeView(mFakeTitleBar);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400929 }
930
The Android Open Source Project0c908882009-03-03 19:32:16 -0800931 /**
Leon Scrogginsc6fa1102009-09-21 10:40:01 -0400932 * Special method for the fake title bar to call when displaying its context
933 * menu, since it is in its own Window, and its parent does not show a
934 * context menu.
935 */
936 /* package */ void showTitleBarContextMenu() {
Cary Clark65f4a3c2009-09-28 17:05:06 -0400937 if (null == mTitleBar.getParent()) {
938 return;
939 }
Leon Scrogginsc6fa1102009-09-21 10:40:01 -0400940 openContextMenu(mTitleBar);
941 }
942
Leon Scrogginsb2b19f52009-10-09 16:10:00 -0400943 @Override
944 public void onContextMenuClosed(Menu menu) {
945 super.onContextMenuClosed(menu);
946 if (mInLoad) {
947 showFakeTitleBar();
948 }
949 }
950
Leon Scrogginsc6fa1102009-09-21 10:40:01 -0400951 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -0800952 * onSaveInstanceState(Bundle map)
953 * onSaveInstanceState is called right before onStop(). The map contains
954 * the saved state.
955 */
Grace Kloba22ac16e2009-10-07 18:00:23 -0700956 @Override
957 protected void onSaveInstanceState(Bundle outState) {
Dave Bort31a6d1c2009-04-13 15:56:49 -0700958 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800959 Log.v(LOGTAG, "BrowserActivity.onSaveInstanceState: this=" + this);
960 }
961 // the default implementation requires each view to have an id. As the
962 // browser handles the state itself and it doesn't use id for the views,
963 // don't call the default implementation. Otherwise it will trigger the
964 // warning like this, "couldn't save which view has focus because the
965 // focused view XXX has no id".
966
967 // Save all the tabs
968 mTabControl.saveState(outState);
969 }
970
Grace Kloba22ac16e2009-10-07 18:00:23 -0700971 @Override
972 protected void onPause() {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800973 super.onPause();
974
975 if (mActivityInPause) {
976 Log.e(LOGTAG, "BrowserActivity is already paused.");
977 return;
978 }
979
Mike Reed7bfa63b2009-05-28 11:08:32 -0400980 mTabControl.pauseCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800981 mActivityInPause = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -0400982 if (mTabControl.getCurrentIndex() >= 0 && !pauseWebViewTimers()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800983 mWakeLock.acquire();
984 mHandler.sendMessageDelayed(mHandler
985 .obtainMessage(RELEASE_WAKELOCK), WAKELOCK_TIMEOUT);
986 }
987
Leon Scrogginsa2ab6a72009-09-11 11:49:52 -0400988 // FIXME: This removes the active tabs page and resets the menu to
989 // MAIN_MENU. A better solution might be to do this work in onNewIntent
990 // but then we would need to save it in onSaveInstanceState and restore
991 // it in onCreate/onRestoreInstanceState
992 if (mActiveTabsPage != null) {
993 removeActiveTabPage(true);
994 }
995
The Android Open Source Project0c908882009-03-03 19:32:16 -0800996 cancelStopToast();
997
998 // unregister network state listener
999 unregisterReceiver(mNetworkStateIntentReceiver);
1000 WebView.disablePlatformNotifications();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001001 }
1002
Grace Kloba22ac16e2009-10-07 18:00:23 -07001003 @Override
1004 protected void onDestroy() {
Dave Bort31a6d1c2009-04-13 15:56:49 -07001005 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001006 Log.v(LOGTAG, "BrowserActivity.onDestroy: this=" + this);
1007 }
1008 super.onDestroy();
Grace Kloba0923d692009-09-23 21:37:25 -07001009
Leon Scroggins8d5fa432009-10-02 15:55:59 -04001010 if (mUploadMessage != null) {
1011 mUploadMessage.onReceiveValue(null);
1012 mUploadMessage = null;
1013 }
1014
Grace Kloba0923d692009-09-23 21:37:25 -07001015 if (mTabControl == null) return;
1016
Grace Kloba1fc98a32009-10-21 13:23:08 -07001017 // Remove the fake title bar if it is there
1018 hideFakeTitleBar();
1019
The Android Open Source Project0c908882009-03-03 19:32:16 -08001020 // Remove the current tab and sub window
Grace Kloba22ac16e2009-10-07 18:00:23 -07001021 Tab t = mTabControl.getCurrentTab();
Patrick Scottfb5e77f2009-04-08 19:17:37 -07001022 if (t != null) {
1023 dismissSubWindow(t);
1024 removeTabFromContentView(t);
1025 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001026 // Destroy all the tabs
1027 mTabControl.destroy();
1028 WebIconDatabase.getInstance().close();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001029
Grace Klobab4da0ad2009-05-14 14:45:40 -07001030 unregisterReceiver(mPackageInstallationReceiver);
Bjorn Bringerta7611812010-03-24 11:12:02 +00001031
1032 // Stop watching the default geolocation permissions
1033 mSystemAllowGeolocationOrigins.stop();
1034 mSystemAllowGeolocationOrigins = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001035 }
1036
1037 @Override
1038 public void onConfigurationChanged(Configuration newConfig) {
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04001039 mConfigChanged = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001040 super.onConfigurationChanged(newConfig);
1041
1042 if (mPageInfoDialog != null) {
1043 mPageInfoDialog.dismiss();
1044 showPageInfo(
1045 mPageInfoView,
Leon Scrogginsc7b92f82010-01-11 18:17:31 -05001046 mPageInfoFromShowSSLCertificateOnError);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001047 }
1048 if (mSSLCertificateDialog != null) {
1049 mSSLCertificateDialog.dismiss();
1050 showSSLCertificate(
1051 mSSLCertificateView);
1052 }
1053 if (mSSLCertificateOnErrorDialog != null) {
1054 mSSLCertificateOnErrorDialog.dismiss();
1055 showSSLCertificateOnError(
1056 mSSLCertificateOnErrorView,
1057 mSSLCertificateOnErrorHandler,
1058 mSSLCertificateOnErrorError);
1059 }
1060 if (mHttpAuthenticationDialog != null) {
1061 String title = ((TextView) mHttpAuthenticationDialog
1062 .findViewById(com.android.internal.R.id.alertTitle)).getText()
1063 .toString();
1064 String name = ((TextView) mHttpAuthenticationDialog
1065 .findViewById(R.id.username_edit)).getText().toString();
1066 String password = ((TextView) mHttpAuthenticationDialog
1067 .findViewById(R.id.password_edit)).getText().toString();
1068 int focusId = mHttpAuthenticationDialog.getCurrentFocus()
1069 .getId();
1070 mHttpAuthenticationDialog.dismiss();
1071 showHttpAuthentication(mHttpAuthHandler, null, null, title,
1072 name, password, focusId);
1073 }
Michael Kolbfe251992010-07-08 15:41:55 -07001074 rebuildTitleBar();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001075 }
1076
Grace Kloba22ac16e2009-10-07 18:00:23 -07001077 @Override
1078 public void onLowMemory() {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001079 super.onLowMemory();
1080 mTabControl.freeMemory();
1081 }
1082
Cary Clarkff4d92c2010-03-25 11:17:03 -04001083 private void resumeWebViewTimers() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001084 Tab tab = mTabControl.getCurrentTab();
Cary Clarkff4d92c2010-03-25 11:17:03 -04001085 if (tab == null) return; // monkey can trigger this
Grace Kloba22ac16e2009-10-07 18:00:23 -07001086 boolean inLoad = tab.inLoad();
1087 if ((!mActivityInPause && !inLoad) || (mActivityInPause && inLoad)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001088 CookieSyncManager.getInstance().startSync();
Grace Kloba22ac16e2009-10-07 18:00:23 -07001089 WebView w = tab.getWebView();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001090 if (w != null) {
1091 w.resumeTimers();
1092 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001093 }
1094 }
1095
Mike Reed7bfa63b2009-05-28 11:08:32 -04001096 private boolean pauseWebViewTimers() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001097 Tab tab = mTabControl.getCurrentTab();
1098 boolean inLoad = tab.inLoad();
1099 if (mActivityInPause && !inLoad) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001100 CookieSyncManager.getInstance().stopSync();
1101 WebView w = mTabControl.getCurrentWebView();
1102 if (w != null) {
1103 w.pauseTimers();
1104 }
1105 return true;
1106 } else {
1107 return false;
1108 }
1109 }
1110
The Android Open Source Project0c908882009-03-03 19:32:16 -08001111 // Open the icon database and retain all the icons for visited sites.
1112 private void retainIconsOnStartup() {
1113 final WebIconDatabase db = WebIconDatabase.getInstance();
1114 db.open(getDir("icons", 0).getPath());
Leon Scroggins2c0f6112010-03-12 18:09:39 -05001115 Cursor c = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001116 try {
Leon Scroggins2c0f6112010-03-12 18:09:39 -05001117 c = Browser.getAllBookmarks(mResolver);
1118 if (c.moveToFirst()) {
1119 int urlIndex = c.getColumnIndex(Browser.BookmarkColumns.URL);
1120 do {
1121 String url = c.getString(urlIndex);
1122 db.retainIconForPageUrl(url);
1123 } while (c.moveToNext());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001124 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001125 } catch (IllegalStateException e) {
1126 Log.e(LOGTAG, "retainIconsOnStartup", e);
Leon Scroggins2c0f6112010-03-12 18:09:39 -05001127 } finally {
1128 if (c!= null) c.close();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001129 }
1130 }
1131
1132 // Helper method for getting the top window.
1133 WebView getTopWindow() {
1134 return mTabControl.getCurrentTopWebView();
1135 }
1136
Grace Kloba22ac16e2009-10-07 18:00:23 -07001137 TabControl getTabControl() {
1138 return mTabControl;
1139 }
1140
The Android Open Source Project0c908882009-03-03 19:32:16 -08001141 @Override
1142 public boolean onCreateOptionsMenu(Menu menu) {
1143 super.onCreateOptionsMenu(menu);
1144
1145 MenuInflater inflater = getMenuInflater();
1146 inflater.inflate(R.menu.browser, menu);
1147 mMenu = menu;
1148 updateInLoadMenuItems();
1149 return true;
1150 }
1151
1152 /**
1153 * As the menu can be open when loading state changes
1154 * we must manually update the state of the stop/reload menu
1155 * item
1156 */
1157 private void updateInLoadMenuItems() {
1158 if (mMenu == null) {
1159 return;
1160 }
Michael Kolbe0a36662010-06-29 10:37:12 -07001161 MenuItem dest = mMenu.findItem(R.id.stop_reload_menu_id);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001162 MenuItem src = mInLoad ?
1163 mMenu.findItem(R.id.stop_menu_id):
Michael Kolbe0a36662010-06-29 10:37:12 -07001164 mMenu.findItem(R.id.reload_menu_id);
1165 if (src != null) {
1166 dest.setIcon(src.getIcon());
1167 dest.setTitle(src.getTitle());
1168 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001169 }
1170
1171 @Override
1172 public boolean onContextItemSelected(MenuItem item) {
1173 // chording is not an issue with context menus, but we use the same
1174 // options selector, so set mCanChord to true so we can access them.
1175 mCanChord = true;
1176 int id = item.getItemId();
Leon Scroggins96afcb12009-12-10 12:35:56 -05001177 boolean result = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001178 switch (id) {
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001179 // For the context menu from the title bar
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001180 case R.id.title_bar_copy_page_url:
Leon Scroggins96afcb12009-12-10 12:35:56 -05001181 Tab currentTab = mTabControl.getCurrentTab();
1182 if (null == currentTab) {
1183 result = false;
1184 break;
1185 }
1186 WebView mainView = currentTab.getWebView();
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001187 if (null == mainView) {
Leon Scroggins96afcb12009-12-10 12:35:56 -05001188 result = false;
1189 break;
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001190 }
Leon Scroggins96afcb12009-12-10 12:35:56 -05001191 copy(mainView.getUrl());
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001192 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001193 // -- Browser context menu
1194 case R.id.open_context_menu_id:
The Android Open Source Project0c908882009-03-03 19:32:16 -08001195 case R.id.bookmark_context_menu_id:
1196 case R.id.save_link_context_menu_id:
1197 case R.id.share_link_context_menu_id:
1198 case R.id.copy_link_context_menu_id:
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001199 final WebView webView = getTopWindow();
1200 if (null == webView) {
Leon Scroggins96afcb12009-12-10 12:35:56 -05001201 result = false;
1202 break;
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001203 }
1204 final HashMap hrefMap = new HashMap();
1205 hrefMap.put("webview", webView);
1206 final Message msg = mHandler.obtainMessage(
1207 FOCUS_NODE_HREF, id, 0, hrefMap);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001208 webView.requestFocusNodeHref(msg);
1209 break;
1210
1211 default:
1212 // For other context menus
Leon Scroggins96afcb12009-12-10 12:35:56 -05001213 result = onOptionsItemSelected(item);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001214 }
1215 mCanChord = false;
Leon Scroggins96afcb12009-12-10 12:35:56 -05001216 return result;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001217 }
1218
1219 private Bundle createGoogleSearchSourceBundle(String source) {
1220 Bundle bundle = new Bundle();
Bjorn Bringert10d1cca2010-02-10 14:22:12 +00001221 bundle.putString(Search.SOURCE, source);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001222 return bundle;
1223 }
1224
Leon Scroggins8ad29922010-02-16 12:33:55 -05001225 /* package */ void editUrl() {
Leon Scroggins68579392009-09-15 15:31:54 -04001226 if (mOptionsMenuOpen) closeOptionsMenu();
Leon Scroggins5bbe9802009-07-31 13:10:55 -04001227 String url = (getTopWindow() == null) ? null : getTopWindow().getUrl();
Grace Kloba83f47342009-07-20 10:44:31 -07001228 startSearch(mSettings.getHomePage().equals(url) ? null : url, true,
Leon Scroggins8ad29922010-02-16 12:33:55 -05001229 null, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001230 }
1231
Leon Scroggins8ad29922010-02-16 12:33:55 -05001232 /**
1233 * Overriding this to insert a local information bundle
1234 */
The Android Open Source Project0c908882009-03-03 19:32:16 -08001235 @Override
1236 public void startSearch(String initialQuery, boolean selectInitialQuery,
1237 Bundle appSearchData, boolean globalSearch) {
1238 if (appSearchData == null) {
1239 appSearchData = createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_TYPE);
1240 }
1241 super.startSearch(initialQuery, selectInitialQuery, appSearchData, globalSearch);
1242 }
1243
Leon Scroggins1f005d32009-08-10 17:36:42 -04001244 /**
1245 * Switch tabs. Called by the TitleBarSet when sliding the title bar
1246 * results in changing tabs.
Leon Scroggins160a7e72009-08-14 18:28:01 -04001247 * @param index Index of the tab to change to, as defined by
1248 * mTabControl.getTabIndex(Tab t).
1249 * @return boolean True if we successfully switched to a different tab. If
1250 * the indexth tab is null, or if that tab is the same as
1251 * the current one, return false.
Leon Scroggins1f005d32009-08-10 17:36:42 -04001252 */
Leon Scroggins160a7e72009-08-14 18:28:01 -04001253 /* package */ boolean switchToTab(int index) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001254 Tab tab = mTabControl.getTab(index);
1255 Tab currentTab = mTabControl.getCurrentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04001256 if (tab == null || tab == currentTab) {
Leon Scroggins160a7e72009-08-14 18:28:01 -04001257 return false;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001258 }
1259 if (currentTab != null) {
1260 // currentTab may be null if it was just removed. In that case,
1261 // we do not need to remove it
1262 removeTabFromContentView(currentTab);
1263 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001264 mTabControl.setCurrentTab(tab);
1265 attachTabToContentView(tab);
Grace Klobaeb6eef42009-09-15 17:56:32 -07001266 resetTitleIconAndProgress();
1267 updateLockIconToLatest();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001268 return true;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001269 }
1270
Grace Kloba22ac16e2009-10-07 18:00:23 -07001271 /* package */ Tab openTabToHomePage() {
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001272 return openTabAndShow(mSettings.getHomePage(), false, null);
1273 }
1274
Leon Scroggins1f005d32009-08-10 17:36:42 -04001275 /* package */ void closeCurrentWindow() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001276 final Tab current = mTabControl.getCurrentTab();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001277 if (mTabControl.getTabCount() == 1) {
Leon Scroggins30444232009-09-04 18:36:20 -04001278 // This is the last tab. Open a new one, with the home
1279 // page and close the current one.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001280 openTabToHomePage();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001281 closeTab(current);
Leon Scroggins160a7e72009-08-14 18:28:01 -04001282 return;
1283 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07001284 final Tab parent = current.getParentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04001285 int indexToShow = -1;
1286 if (parent != null) {
1287 indexToShow = mTabControl.getTabIndex(parent);
1288 } else {
Leon Scroggins160a7e72009-08-14 18:28:01 -04001289 final int currentIndex = mTabControl.getCurrentIndex();
1290 // Try to move to the tab to the right
1291 indexToShow = currentIndex + 1;
1292 if (indexToShow > mTabControl.getTabCount() - 1) {
1293 // Try to move to the tab to the left
1294 indexToShow = currentIndex - 1;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001295 }
1296 }
Leon Scroggins160a7e72009-08-14 18:28:01 -04001297 if (switchToTab(indexToShow)) {
1298 // Close window
1299 closeTab(current);
1300 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001301 }
1302
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001303 private ActiveTabsPage mActiveTabsPage;
1304
1305 /**
1306 * Remove the active tabs page.
1307 * @param needToAttach If true, the active tabs page did not attach a tab
1308 * to the content view, so we need to do that here.
1309 */
1310 /* package */ void removeActiveTabPage(boolean needToAttach) {
1311 mContentView.removeView(mActiveTabsPage);
Leon Scrogginsd746a942010-05-19 13:21:44 -04001312 mTitleBar.setVisibility(View.VISIBLE);
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001313 mActiveTabsPage = null;
1314 mMenuState = R.id.MAIN_MENU;
1315 if (needToAttach) {
1316 attachTabToContentView(mTabControl.getCurrentTab());
1317 }
1318 getTopWindow().requestFocus();
1319 }
1320
Cary Clark01cfcdd2010-06-04 16:36:45 -04001321 private WebView showDialog(WebDialog dialog) {
1322 // Need to do something special for Tablet
1323 Tab tab = mTabControl.getCurrentTab();
1324 if (tab.getSubWebView() == null) {
1325 // If the find or select is being performed on the main webview,
1326 // remove the embedded title bar.
1327 WebView mainView = tab.getWebView();
1328 if (mainView != null) {
1329 mainView.setEmbeddedTitleBar(null);
1330 }
1331 }
1332 hideFakeTitleBar();
1333 mMenuState = EMPTY_MENU;
1334 return tab.showDialog(dialog);
1335 }
1336
The Android Open Source Project0c908882009-03-03 19:32:16 -08001337 @Override
1338 public boolean onOptionsItemSelected(MenuItem item) {
1339 if (!mCanChord) {
1340 // The user has already fired a shortcut with this hold down of the
1341 // menu key.
1342 return false;
1343 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001344 if (null == getTopWindow()) {
Leon Scroggins0d7ae0e2009-06-05 11:04:45 -04001345 return false;
1346 }
Grace Kloba6ee9c492009-07-13 10:04:34 -07001347 if (mMenuIsDown) {
1348 // The shortcut action consumes the MENU. Even if it is still down,
1349 // it won't trigger the next shortcut action. In the case of the
1350 // shortcut action triggering a new activity, like Bookmarks, we
1351 // won't get onKeyUp for MENU. So it is important to reset it here.
1352 mMenuIsDown = false;
1353 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001354 switch (item.getItemId()) {
1355 // -- Main menu
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001356 case R.id.new_tab_menu_id:
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001357 openTabToHomePage();
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001358 break;
1359
Leon Scroggins64b80f32009-08-07 12:03:34 -04001360 case R.id.goto_menu_id:
Leon Scroggins8ad29922010-02-16 12:33:55 -05001361 editUrl();
Leon Scrogginsb3a5bed2009-09-28 11:21:56 -04001362 break;
1363
1364 case R.id.bookmarks_menu_id:
Leon Scroggins30444232009-09-04 18:36:20 -04001365 bookmarksOrHistoryPicker(false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001366 break;
1367
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001368 case R.id.active_tabs_menu_id:
1369 mActiveTabsPage = new ActiveTabsPage(this, mTabControl);
1370 removeTabFromContentView(mTabControl.getCurrentTab());
Leon Scrogginsd746a942010-05-19 13:21:44 -04001371 mTitleBar.setVisibility(View.GONE);
Leon Scroggins43de6162009-09-14 19:59:58 -04001372 hideFakeTitleBar();
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001373 mContentView.addView(mActiveTabsPage, COVER_SCREEN_PARAMS);
1374 mActiveTabsPage.requestFocus();
1375 mMenuState = EMPTY_MENU;
1376 break;
1377
Leon Scroggins1f005d32009-08-10 17:36:42 -04001378 case R.id.add_bookmark_menu_id:
Leon Scroggins571b3762010-05-26 10:25:01 -04001379 bookmarkCurrentPage();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001380 break;
1381
1382 case R.id.stop_reload_menu_id:
1383 if (mInLoad) {
1384 stopLoading();
1385 } else {
1386 getTopWindow().reload();
1387 }
1388 break;
1389
1390 case R.id.back_menu_id:
1391 getTopWindow().goBack();
1392 break;
1393
1394 case R.id.forward_menu_id:
1395 getTopWindow().goForward();
1396 break;
1397
1398 case R.id.close_menu_id:
1399 // Close the subwindow if it exists.
1400 if (mTabControl.getCurrentSubWindow() != null) {
1401 dismissSubWindow(mTabControl.getCurrentTab());
1402 break;
1403 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001404 closeCurrentWindow();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001405 break;
1406
1407 case R.id.homepage_menu_id:
Grace Kloba22ac16e2009-10-07 18:00:23 -07001408 Tab current = mTabControl.getCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001409 if (current != null) {
1410 dismissSubWindow(current);
Leon Scroggins92472e82010-02-17 16:32:28 -05001411 loadUrl(current.getWebView(), mSettings.getHomePage());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001412 }
1413 break;
1414
1415 case R.id.preferences_menu_id:
1416 Intent intent = new Intent(this,
1417 BrowserPreferencesPage.class);
Leon Scrogginsd5304942009-12-10 16:11:39 -05001418 intent.putExtra(BrowserPreferencesPage.CURRENT_PAGE,
1419 getTopWindow().getUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001420 startActivityForResult(intent, PREFERENCES_PAGE);
1421 break;
1422
1423 case R.id.find_menu_id:
Cary Clark01cfcdd2010-06-04 16:36:45 -04001424 showFindDialog();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001425 break;
1426
Elliott Slaughter0ced08c2010-06-30 11:40:42 -07001427 case R.id.save_webarchive_menu_id:
1428 if (LOGD_ENABLED) {
1429 Log.d(LOGTAG, "Save as Web Archive");
1430 }
1431 String directory = getExternalFilesDir(null).getAbsolutePath() + File.separator;
1432 getTopWindow().saveWebArchive(directory, true, new ValueCallback<String>() {
1433 @Override
1434 public void onReceiveValue(String value) {
1435 if (value != null) {
1436 Toast.makeText(BrowserActivity.this, R.string.webarchive_saved, Toast.LENGTH_SHORT).show();
1437 } else {
1438 Toast.makeText(BrowserActivity.this, R.string.webarchive_failed, Toast.LENGTH_SHORT).show();
1439 }
1440 }
1441 });
1442 break;
1443
The Android Open Source Project0c908882009-03-03 19:32:16 -08001444 case R.id.page_info_menu_id:
1445 showPageInfo(mTabControl.getCurrentTab(), false);
1446 break;
1447
1448 case R.id.classic_history_menu_id:
Leon Scroggins30444232009-09-04 18:36:20 -04001449 bookmarksOrHistoryPicker(true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001450 break;
1451
Leon Scroggins96afcb12009-12-10 12:35:56 -05001452 case R.id.title_bar_share_page_url:
The Android Open Source Project0c908882009-03-03 19:32:16 -08001453 case R.id.share_page_menu_id:
Leon Scroggins96afcb12009-12-10 12:35:56 -05001454 Tab currentTab = mTabControl.getCurrentTab();
1455 if (null == currentTab) {
1456 mCanChord = false;
1457 return false;
1458 }
1459 currentTab.populatePickerData();
1460 sharePage(this, currentTab.getTitle(),
1461 currentTab.getUrl(), currentTab.getFavicon(),
Ben Murdoch87cc65d2010-06-29 20:34:10 +01001462 createScreenshot(currentTab.getWebView(), getDesiredThumbnailWidth(this),
1463 getDesiredThumbnailHeight(this)));
The Android Open Source Project0c908882009-03-03 19:32:16 -08001464 break;
1465
1466 case R.id.dump_nav_menu_id:
1467 getTopWindow().debugDump();
1468 break;
1469
Andrei Popescu7a8b88b2010-02-02 00:30:38 +00001470 case R.id.dump_counters_menu_id:
1471 getTopWindow().dumpV8Counters();
1472 break;
1473
The Android Open Source Project0c908882009-03-03 19:32:16 -08001474 case R.id.zoom_in_menu_id:
1475 getTopWindow().zoomIn();
1476 break;
1477
1478 case R.id.zoom_out_menu_id:
1479 getTopWindow().zoomOut();
1480 break;
1481
1482 case R.id.view_downloads_menu_id:
1483 viewDownloads(null);
1484 break;
1485
The Android Open Source Project0c908882009-03-03 19:32:16 -08001486 case R.id.window_one_menu_id:
1487 case R.id.window_two_menu_id:
1488 case R.id.window_three_menu_id:
1489 case R.id.window_four_menu_id:
1490 case R.id.window_five_menu_id:
1491 case R.id.window_six_menu_id:
1492 case R.id.window_seven_menu_id:
1493 case R.id.window_eight_menu_id:
1494 {
1495 int menuid = item.getItemId();
1496 for (int id = 0; id < WINDOW_SHORTCUT_ID_ARRAY.length; id++) {
1497 if (WINDOW_SHORTCUT_ID_ARRAY[id] == menuid) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001498 Tab desiredTab = mTabControl.getTab(id);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001499 if (desiredTab != null &&
1500 desiredTab != mTabControl.getCurrentTab()) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001501 switchToTab(id);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001502 }
1503 break;
1504 }
1505 }
1506 }
1507 break;
1508
1509 default:
1510 if (!super.onOptionsItemSelected(item)) {
1511 return false;
1512 }
1513 // Otherwise fall through.
1514 }
1515 mCanChord = false;
1516 return true;
1517 }
1518
Leon Scroggins571b3762010-05-26 10:25:01 -04001519 /* package */ void bookmarkCurrentPage() {
1520 Intent i = new Intent(BrowserActivity.this,
1521 AddBookmarkPage.class);
1522 WebView w = getTopWindow();
1523 i.putExtra("url", w.getUrl());
1524 i.putExtra("title", w.getTitle());
1525 i.putExtra("touch_icon_url", w.getTouchIconUrl());
Ben Murdoch87cc65d2010-06-29 20:34:10 +01001526 i.putExtra("thumbnail", createScreenshot(w, getDesiredThumbnailWidth(this),
1527 getDesiredThumbnailHeight(this)));
Ben Murdocheecb4e62010-07-06 16:30:38 +01001528 i.putExtra("url_editable", false);
Leon Scroggins571b3762010-05-26 10:25:01 -04001529 startActivity(i);
1530 }
1531
Cary Clark01cfcdd2010-06-04 16:36:45 -04001532 private boolean dialogIsUp() {
1533 return null != mFindDialog && mFindDialog.isVisible() ||
1534 null != mSelectDialog && mSelectDialog.isVisible();
1535 }
1536
1537 private boolean closeDialog(WebDialog dialog) {
1538 if (null == dialog || !dialog.isVisible()) return false;
Leon Scroggins79e36d92010-04-29 16:01:46 +01001539 Tab currentTab = mTabControl.getCurrentTab();
Cary Clark01cfcdd2010-06-04 16:36:45 -04001540 currentTab.closeDialog(dialog);
1541 dialog.dismiss();
1542 return true;
1543 }
1544
1545 /*
1546 * Remove the find dialog or select dialog.
1547 */
1548 public void closeDialogs() {
1549 if (!(closeDialog(mFindDialog) || closeDialog(mSelectDialog))) return;
Leon Scrogginsd746a942010-05-19 13:21:44 -04001550 if (!mXLargeScreenSize) {
1551 // If the Find was being performed in the main WebView, replace the
1552 // embedded title bar.
Cary Clark01cfcdd2010-06-04 16:36:45 -04001553 Tab currentTab = mTabControl.getCurrentTab();
Leon Scrogginsd746a942010-05-19 13:21:44 -04001554 if (currentTab.getSubWebView() == null) {
1555 WebView mainView = currentTab.getWebView();
1556 if (mainView != null) {
1557 mainView.setEmbeddedTitleBar(mTitleBar);
1558 }
Leon Scroggins79e36d92010-04-29 16:01:46 +01001559 }
1560 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001561 mMenuState = R.id.MAIN_MENU;
Leon Scroggins79e36d92010-04-29 16:01:46 +01001562 if (mInLoad) {
1563 // The title bar was hidden, because otherwise it would cover up the
Cary Clark01cfcdd2010-06-04 16:36:45 -04001564 // find or select dialog. Now that the dialog has been removed,
1565 // show the fake title bar once again.
Leon Scroggins79e36d92010-04-29 16:01:46 +01001566 showFakeTitleBar();
1567 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001568 }
1569
Cary Clark01cfcdd2010-06-04 16:36:45 -04001570 public void showFindDialog() {
1571 if (null == mFindDialog) {
1572 mFindDialog = new FindDialog(this);
1573 }
1574 showDialog(mFindDialog).setFindIsUp(true);
1575 }
1576
1577 public void setFindDialogText(String text) {
1578 mFindDialog.setText(text);
1579 }
1580
1581 public void showSelectDialog() {
1582 if (null == mSelectDialog) {
1583 mSelectDialog = new SelectDialog(this);
1584 }
1585 showDialog(mSelectDialog).setUpSelect();
1586 mSelectDialog.hideSoftInput();
1587 }
1588
Grace Kloba22ac16e2009-10-07 18:00:23 -07001589 @Override
1590 public boolean onPrepareOptionsMenu(Menu menu) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001591 // This happens when the user begins to hold down the menu key, so
1592 // allow them to chord to get a shortcut.
1593 mCanChord = true;
1594 // Note: setVisible will decide whether an item is visible; while
1595 // setEnabled() will decide whether an item is enabled, which also means
1596 // whether the matching shortcut key will function.
1597 super.onPrepareOptionsMenu(menu);
1598 switch (mMenuState) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001599 case EMPTY_MENU:
1600 if (mCurrentMenuState != mMenuState) {
1601 menu.setGroupVisible(R.id.MAIN_MENU, false);
1602 menu.setGroupEnabled(R.id.MAIN_MENU, false);
1603 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001604 }
1605 break;
1606 default:
1607 if (mCurrentMenuState != mMenuState) {
1608 menu.setGroupVisible(R.id.MAIN_MENU, true);
1609 menu.setGroupEnabled(R.id.MAIN_MENU, true);
1610 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001611 }
1612 final WebView w = getTopWindow();
1613 boolean canGoBack = false;
1614 boolean canGoForward = false;
1615 boolean isHome = false;
1616 if (w != null) {
1617 canGoBack = w.canGoBack();
1618 canGoForward = w.canGoForward();
1619 isHome = mSettings.getHomePage().equals(w.getUrl());
1620 }
1621 final MenuItem back = menu.findItem(R.id.back_menu_id);
1622 back.setEnabled(canGoBack);
1623
1624 final MenuItem home = menu.findItem(R.id.homepage_menu_id);
1625 home.setEnabled(!isHome);
1626
Michael Kolbe0a36662010-06-29 10:37:12 -07001627 final MenuItem forward = menu.findItem(R.id.forward_menu_id);
1628 forward.setEnabled(canGoForward);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001629
Michael Kolbe0a36662010-06-29 10:37:12 -07001630 final MenuItem newtab = menu.findItem(R.id.new_tab_menu_id);
1631 newtab.setEnabled(mTabControl.canCreateNewTab());
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001632
The Android Open Source Project0c908882009-03-03 19:32:16 -08001633 // decide whether to show the share link option
1634 PackageManager pm = getPackageManager();
1635 Intent send = new Intent(Intent.ACTION_SEND);
1636 send.setType("text/plain");
1637 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1638 menu.findItem(R.id.share_page_menu_id).setVisible(ri != null);
1639
The Android Open Source Project0c908882009-03-03 19:32:16 -08001640 boolean isNavDump = mSettings.isNavDump();
1641 final MenuItem nav = menu.findItem(R.id.dump_nav_menu_id);
1642 nav.setVisible(isNavDump);
1643 nav.setEnabled(isNavDump);
Andrei Popescu7a8b88b2010-02-02 00:30:38 +00001644
1645 boolean showDebugSettings = mSettings.showDebugSettings();
1646 final MenuItem counter = menu.findItem(R.id.dump_counters_menu_id);
1647 counter.setVisible(showDebugSettings);
1648 counter.setEnabled(showDebugSettings);
1649
The Android Open Source Project0c908882009-03-03 19:32:16 -08001650 break;
1651 }
1652 mCurrentMenuState = mMenuState;
1653 return true;
1654 }
1655
1656 @Override
1657 public void onCreateContextMenu(ContextMenu menu, View v,
1658 ContextMenuInfo menuInfo) {
Leon Scroggins571b3762010-05-26 10:25:01 -04001659 if (v instanceof TitleBarBase) {
Leon Scroggins4e9f89b2010-02-22 16:54:14 -05001660 return;
1661 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001662 WebView webview = (WebView) v;
1663 WebView.HitTestResult result = webview.getHitTestResult();
1664 if (result == null) {
1665 return;
1666 }
1667
1668 int type = result.getType();
1669 if (type == WebView.HitTestResult.UNKNOWN_TYPE) {
1670 Log.w(LOGTAG,
1671 "We should not show context menu when nothing is touched");
1672 return;
1673 }
1674 if (type == WebView.HitTestResult.EDIT_TEXT_TYPE) {
1675 // let TextView handles context menu
1676 return;
1677 }
1678
1679 // Note, http://b/issue?id=1106666 is requesting that
1680 // an inflated menu can be used again. This is not available
1681 // yet, so inflate each time (yuk!)
1682 MenuInflater inflater = getMenuInflater();
1683 inflater.inflate(R.menu.browsercontext, menu);
1684
1685 // Show the correct menu group
Leon Scroggins III9e997c72010-05-26 13:25:16 -04001686 final String extra = result.getExtra();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001687 menu.setGroupVisible(R.id.PHONE_MENU,
1688 type == WebView.HitTestResult.PHONE_TYPE);
1689 menu.setGroupVisible(R.id.EMAIL_MENU,
1690 type == WebView.HitTestResult.EMAIL_TYPE);
1691 menu.setGroupVisible(R.id.GEO_MENU,
1692 type == WebView.HitTestResult.GEO_TYPE);
1693 menu.setGroupVisible(R.id.IMAGE_MENU,
1694 type == WebView.HitTestResult.IMAGE_TYPE
1695 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1696 menu.setGroupVisible(R.id.ANCHOR_MENU,
1697 type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1698 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1699
1700 // Setup custom handling depending on the type
1701 switch (type) {
1702 case WebView.HitTestResult.PHONE_TYPE:
1703 menu.setHeaderTitle(Uri.decode(extra));
1704 menu.findItem(R.id.dial_context_menu_id).setIntent(
1705 new Intent(Intent.ACTION_VIEW, Uri
1706 .parse(WebView.SCHEME_TEL + extra)));
1707 Intent addIntent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
1708 addIntent.putExtra(Insert.PHONE, Uri.decode(extra));
Cary Clark5e335a32009-09-22 14:53:11 -04001709 addIntent.setType(ContactsContract.Contacts.CONTENT_ITEM_TYPE);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001710 menu.findItem(R.id.add_contact_context_menu_id).setIntent(
1711 addIntent);
1712 menu.findItem(R.id.copy_phone_context_menu_id).setOnMenuItemClickListener(
1713 new Copy(extra));
1714 break;
1715
1716 case WebView.HitTestResult.EMAIL_TYPE:
1717 menu.setHeaderTitle(extra);
1718 menu.findItem(R.id.email_context_menu_id).setIntent(
1719 new Intent(Intent.ACTION_VIEW, Uri
1720 .parse(WebView.SCHEME_MAILTO + extra)));
1721 menu.findItem(R.id.copy_mail_context_menu_id).setOnMenuItemClickListener(
1722 new Copy(extra));
1723 break;
1724
1725 case WebView.HitTestResult.GEO_TYPE:
1726 menu.setHeaderTitle(extra);
1727 menu.findItem(R.id.map_context_menu_id).setIntent(
1728 new Intent(Intent.ACTION_VIEW, Uri
1729 .parse(WebView.SCHEME_GEO
1730 + URLEncoder.encode(extra))));
1731 menu.findItem(R.id.copy_geo_context_menu_id).setOnMenuItemClickListener(
1732 new Copy(extra));
1733 break;
1734
1735 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1736 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
1737 TextView titleView = (TextView) LayoutInflater.from(this)
1738 .inflate(android.R.layout.browser_link_context_header,
1739 null);
1740 titleView.setText(extra);
1741 menu.setHeaderView(titleView);
1742 // decide whether to show the open link in new tab option
Leon Scroggins III9e997c72010-05-26 13:25:16 -04001743 boolean showNewTab = mTabControl.canCreateNewTab();
1744 MenuItem newTabItem
1745 = menu.findItem(R.id.open_newtab_context_menu_id);
1746 newTabItem.setVisible(showNewTab);
1747 if (showNewTab) {
1748 newTabItem.setOnMenuItemClickListener(
1749 new MenuItem.OnMenuItemClickListener() {
1750 public boolean onMenuItemClick(MenuItem item) {
1751 final Tab parent = mTabControl.getCurrentTab();
1752 final Tab newTab = openTab(extra);
1753 if (newTab != parent) {
1754 parent.addChildTab(newTab);
1755 }
1756 return true;
1757 }
1758 });
1759 }
Ben Murdochde353622009-10-12 10:29:00 +01001760 menu.findItem(R.id.bookmark_context_menu_id).setVisible(
1761 Bookmarks.urlHasAcceptableScheme(extra));
The Android Open Source Project0c908882009-03-03 19:32:16 -08001762 PackageManager pm = getPackageManager();
1763 Intent send = new Intent(Intent.ACTION_SEND);
1764 send.setType("text/plain");
1765 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1766 menu.findItem(R.id.share_link_context_menu_id).setVisible(ri != null);
1767 if (type == WebView.HitTestResult.SRC_ANCHOR_TYPE) {
1768 break;
1769 }
1770 // otherwise fall through to handle image part
1771 case WebView.HitTestResult.IMAGE_TYPE:
1772 if (type == WebView.HitTestResult.IMAGE_TYPE) {
1773 menu.setHeaderTitle(extra);
1774 }
1775 menu.findItem(R.id.view_image_context_menu_id).setIntent(
1776 new Intent(Intent.ACTION_VIEW, Uri.parse(extra)));
1777 menu.findItem(R.id.download_context_menu_id).
1778 setOnMenuItemClickListener(new Download(extra));
Ben Murdoch4f75ba22009-10-27 11:48:28 +00001779 menu.findItem(R.id.set_wallpaper_context_menu_id).
1780 setOnMenuItemClickListener(new SetAsWallpaper(extra));
The Android Open Source Project0c908882009-03-03 19:32:16 -08001781 break;
1782
1783 default:
1784 Log.w(LOGTAG, "We should not get here.");
1785 break;
1786 }
Leon Scrogginsb2b19f52009-10-09 16:10:00 -04001787 hideFakeTitleBar();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001788 }
1789
The Android Open Source Project0c908882009-03-03 19:32:16 -08001790 // Attach the given tab to the content view.
Grace Klobac928c302009-09-17 11:51:21 -07001791 // this should only be called for the current tab.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001792 private void attachTabToContentView(Tab t) {
Steve Block2bc69912009-07-30 14:45:13 +01001793 // Attach the container that contains the main WebView and any other UI
1794 // associated with the tab.
Patrick Scottd0119532009-09-17 08:00:31 -04001795 t.attachTabToContentView(mContentView);
Ben Murdochbff2d602009-07-01 20:19:05 +01001796
1797 if (mShouldShowErrorConsole) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001798 ErrorConsoleView errorConsole = t.getErrorConsole(true);
Ben Murdochbff2d602009-07-01 20:19:05 +01001799 if (errorConsole.numberOfErrors() == 0) {
1800 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
1801 } else {
1802 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
1803 }
1804
1805 mErrorConsoleContainer.addView(errorConsole,
Romain Guy15b8ec62010-01-08 15:06:43 -08001806 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
Ben Murdochbff2d602009-07-01 20:19:05 +01001807 ViewGroup.LayoutParams.WRAP_CONTENT));
1808 }
1809
Leon Scrogginsd746a942010-05-19 13:21:44 -04001810 if (!mXLargeScreenSize){
1811 WebView view = t.getWebView();
1812 view.setEmbeddedTitleBar(mTitleBar);
1813 }
Leon Scroggins58d56c62010-01-28 15:12:40 -05001814 if (t.isInVoiceSearchMode()) {
1815 showVoiceTitleBar(t.getVoiceDisplayTitle());
1816 } else {
1817 revertVoiceTitleBar();
1818 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001819 // Request focus on the top window.
1820 t.getTopWindow().requestFocus();
1821 }
1822
1823 // Attach a sub window to the main WebView of the given tab.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001824 void attachSubWindow(Tab t) {
Patrick Scottd0119532009-09-17 08:00:31 -04001825 t.attachSubWindow(mContentView);
1826 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001827 }
1828
1829 // Remove the given tab from the content view.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001830 private void removeTabFromContentView(Tab t) {
Steve Block2bc69912009-07-30 14:45:13 +01001831 // Remove the container that contains the main WebView.
Patrick Scottd0119532009-09-17 08:00:31 -04001832 t.removeTabFromContentView(mContentView);
Ben Murdochbff2d602009-07-01 20:19:05 +01001833
Grace Kloba22ac16e2009-10-07 18:00:23 -07001834 ErrorConsoleView errorConsole = t.getErrorConsole(false);
1835 if (errorConsole != null) {
1836 mErrorConsoleContainer.removeView(errorConsole);
Ben Murdochbff2d602009-07-01 20:19:05 +01001837 }
1838
Leon Scrogginsd746a942010-05-19 13:21:44 -04001839 if (!mXLargeScreenSize) {
1840 WebView view = t.getWebView();
1841 if (view != null) {
1842 view.setEmbeddedTitleBar(null);
1843 }
Leon Scrogginsbb85b902009-09-14 19:27:20 -04001844 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001845 }
1846
1847 // Remove the sub window if it exists. Also called by TabControl when the
1848 // user clicks the 'X' to dismiss a sub window.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001849 /* package */ void dismissSubWindow(Tab t) {
Patrick Scottd0119532009-09-17 08:00:31 -04001850 t.removeSubWindow(mContentView);
Grace Kloba22ac16e2009-10-07 18:00:23 -07001851 // dismiss the subwindow. This will destroy the WebView.
1852 t.dismissSubWindow();
Patrick Scottd0119532009-09-17 08:00:31 -04001853 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001854 }
1855
Leon Scroggins1f005d32009-08-10 17:36:42 -04001856 // A wrapper function of {@link #openTabAndShow(UrlData, boolean, String)}
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07001857 // that accepts url as string.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001858 private Tab openTabAndShow(String url, boolean closeOnExit, String appId) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001859 return openTabAndShow(new UrlData(url), closeOnExit, appId);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001860 }
1861
1862 // This method does a ton of stuff. It will attempt to create a new tab
1863 // if we haven't reached MAX_TABS. Otherwise it uses the current tab. If
Leon Scroggins1f005d32009-08-10 17:36:42 -04001864 // url isn't null, it will load the given url.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001865 /* package */Tab openTabAndShow(UrlData urlData, boolean closeOnExit,
1866 String appId) {
1867 final Tab currentTab = mTabControl.getCurrentTab();
1868 if (mTabControl.canCreateNewTab()) {
1869 final Tab tab = mTabControl.createNewTab(closeOnExit, appId,
Elliott Slaughterf0f03952010-07-14 18:10:36 -07001870 urlData.mUrl, false);
Leon Scroggins1f005d32009-08-10 17:36:42 -04001871 WebView webview = tab.getWebView();
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001872 // If the last tab was removed from the active tabs page, currentTab
1873 // will be null.
1874 if (currentTab != null) {
1875 removeTabFromContentView(currentTab);
1876 }
Patrick Scott8bbd69f2009-08-14 13:35:53 -04001877 // We must set the new tab as the current tab to reflect the old
1878 // animation behavior.
1879 mTabControl.setCurrentTab(tab);
Grace Klobaeb6eef42009-09-15 17:56:32 -07001880 attachTabToContentView(tab);
Leon Scroggins160a7e72009-08-14 18:28:01 -04001881 if (!urlData.isEmpty()) {
Patrick Scott9d53da02010-02-19 10:19:01 -05001882 loadUrlDataIn(tab, urlData);
Leon Scroggins1f005d32009-08-10 17:36:42 -04001883 }
1884 return tab;
1885 } else {
1886 // Get rid of the subwindow if it exists
1887 dismissSubWindow(currentTab);
1888 if (!urlData.isEmpty()) {
1889 // Load the given url.
Patrick Scott9d53da02010-02-19 10:19:01 -05001890 loadUrlDataIn(currentTab, urlData);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001891 }
Leon Scroggins58d56c62010-01-28 15:12:40 -05001892 return currentTab;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001893 }
1894 }
1895
Grace Kloba22ac16e2009-10-07 18:00:23 -07001896 private Tab openTab(String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001897 if (mSettings.openInBackground()) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001898 Tab t = mTabControl.createNewTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001899 if (t != null) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001900 WebView view = t.getWebView();
Leon Scroggins92472e82010-02-17 16:32:28 -05001901 loadUrl(view, url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001902 }
Grace Klobac9181842009-04-14 08:53:22 -07001903 return t;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001904 } else {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001905 return openTabAndShow(url, false, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001906 }
1907 }
1908
Elliott Slaughterf0f03952010-07-14 18:10:36 -07001909 /* package */ Tab openIncognitoTab() {
1910 if (mTabControl.canCreateNewTab()) {
1911 Tab currentTab = mTabControl.getCurrentTab();
1912 Tab tab = mTabControl.createNewTab(false, null, null, true);
1913 if (currentTab != null) {
1914 removeTabFromContentView(currentTab);
1915 }
1916 mTabControl.setCurrentTab(tab);
1917 attachTabToContentView(tab);
1918 return tab;
1919 }
1920 return null;
1921 }
1922
The Android Open Source Project0c908882009-03-03 19:32:16 -08001923 private class Copy implements OnMenuItemClickListener {
1924 private CharSequence mText;
1925
1926 public boolean onMenuItemClick(MenuItem item) {
1927 copy(mText);
1928 return true;
1929 }
1930
1931 public Copy(CharSequence toCopy) {
1932 mText = toCopy;
1933 }
1934 }
1935
1936 private class Download implements OnMenuItemClickListener {
1937 private String mText;
1938
1939 public boolean onMenuItemClick(MenuItem item) {
1940 onDownloadStartNoStream(mText, null, null, null, -1);
1941 return true;
1942 }
1943
1944 public Download(String toDownload) {
1945 mText = toDownload;
1946 }
1947 }
1948
Ben Murdoch4f75ba22009-10-27 11:48:28 +00001949 private class SetAsWallpaper extends Thread implements
1950 OnMenuItemClickListener, DialogInterface.OnCancelListener {
1951 private URL mUrl;
1952 private ProgressDialog mWallpaperProgress;
1953 private boolean mCanceled = false;
1954
1955 public SetAsWallpaper(String url) {
1956 try {
1957 mUrl = new URL(url);
1958 } catch (MalformedURLException e) {
1959 mUrl = null;
1960 }
1961 }
1962
1963 public void onCancel(DialogInterface dialog) {
1964 mCanceled = true;
1965 }
1966
1967 public boolean onMenuItemClick(MenuItem item) {
1968 if (mUrl != null) {
1969 // The user may have tried to set a image with a large file size as their
1970 // background so it may take a few moments to perform the operation. Display
1971 // a progress spinner while it is working.
1972 mWallpaperProgress = new ProgressDialog(BrowserActivity.this);
1973 mWallpaperProgress.setIndeterminate(true);
1974 mWallpaperProgress.setMessage(getText(R.string.progress_dialog_setting_wallpaper));
1975 mWallpaperProgress.setCancelable(true);
1976 mWallpaperProgress.setOnCancelListener(this);
1977 mWallpaperProgress.show();
1978 start();
1979 }
1980 return true;
1981 }
1982
Michael Kolbe0a36662010-06-29 10:37:12 -07001983 @Override
Ben Murdoch4f75ba22009-10-27 11:48:28 +00001984 public void run() {
1985 Drawable oldWallpaper = BrowserActivity.this.getWallpaper();
1986 try {
1987 // TODO: This will cause the resource to be downloaded again, when we
1988 // should in most cases be able to grab it from the cache. To fix this
1989 // we should query WebCore to see if we can access a cached version and
1990 // instead open an input stream on that. This pattern could also be used
1991 // in the download manager where the same problem exists.
1992 InputStream inputstream = mUrl.openStream();
1993 if (inputstream != null) {
1994 setWallpaper(inputstream);
1995 }
1996 } catch (IOException e) {
1997 Log.e(LOGTAG, "Unable to set new wallpaper");
1998 // Act as though the user canceled the operation so we try to
1999 // restore the old wallpaper.
2000 mCanceled = true;
2001 }
2002
2003 if (mCanceled) {
2004 // Restore the old wallpaper if the user cancelled whilst we were setting
2005 // the new wallpaper.
2006 int width = oldWallpaper.getIntrinsicWidth();
2007 int height = oldWallpaper.getIntrinsicHeight();
2008 Bitmap bm = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
2009 Canvas canvas = new Canvas(bm);
2010 oldWallpaper.setBounds(0, 0, width, height);
2011 oldWallpaper.draw(canvas);
2012 try {
2013 setWallpaper(bm);
2014 } catch (IOException e) {
2015 Log.e(LOGTAG, "Unable to restore old wallpaper.");
2016 }
2017 mCanceled = false;
2018 }
2019
2020 if (mWallpaperProgress.isShowing()) {
2021 mWallpaperProgress.dismiss();
2022 }
2023 }
2024 }
2025
The Android Open Source Project0c908882009-03-03 19:32:16 -08002026 private void copy(CharSequence text) {
Dianne Hackborn80f32622010-08-05 14:17:53 -07002027 ClipboardManager cm = (ClipboardManager)getSystemService(Context.CLIPBOARD_SERVICE);
2028 cm.setText(text);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002029 }
2030
2031 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08002032 * Resets the browser title-view to whatever it must be
2033 * (for example, if we had a loading error)
2034 * When we have a new page, we call resetTitle, when we
2035 * have to reset the titlebar to whatever it used to be
2036 * (for example, if the user chose to stop loading), we
2037 * call resetTitleAndRevertLockIcon.
2038 */
2039 /* package */ void resetTitleAndRevertLockIcon() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002040 mTabControl.getCurrentTab().revertLockIcon();
2041 updateLockIconToLatest();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002042 resetTitleIconAndProgress();
2043 }
2044
2045 /**
2046 * Reset the title, favicon, and progress.
2047 */
2048 private void resetTitleIconAndProgress() {
2049 WebView current = mTabControl.getCurrentWebView();
2050 if (current == null) {
2051 return;
2052 }
2053 resetTitleAndIcon(current);
2054 int progress = current.getProgress();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002055 current.getWebChromeClient().onProgressChanged(current, progress);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002056 }
2057
2058 // Reset the title and the icon based on the given item.
2059 private void resetTitleAndIcon(WebView view) {
2060 WebHistoryItem item = view.copyBackForwardList().getCurrentItem();
2061 if (item != null) {
Leon Scroggins68579392009-09-15 15:31:54 -04002062 setUrlTitle(item.getUrl(), item.getTitle());
The Android Open Source Project0c908882009-03-03 19:32:16 -08002063 setFavicon(item.getFavicon());
2064 } else {
Leon Scroggins68579392009-09-15 15:31:54 -04002065 setUrlTitle(null, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002066 setFavicon(null);
2067 }
2068 }
2069
2070 /**
2071 * Sets a title composed of the URL and the title string.
2072 * @param url The URL of the site being loaded.
2073 * @param title The title of the site being loaded.
2074 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07002075 void setUrlTitle(String url, String title) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002076 mUrl = url;
2077 mTitle = title;
2078
Leon Scroggins58d56c62010-01-28 15:12:40 -05002079 // If we are in voice search mode, the title has already been set.
2080 if (mTabControl.getCurrentTab().isInVoiceSearchMode()) return;
2081 mTitleBar.setDisplayTitle(url);
Leon Scrogginsd746a942010-05-19 13:21:44 -04002082 if (!mXLargeScreenSize) {
2083 mFakeTitleBar.setDisplayTitle(url);
2084 }
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);
Leon Scrogginsd746a942010-05-19 13:21:44 -04002127 if (!mXLargeScreenSize) {
2128 mFakeTitleBar.setFavicon(icon);
2129 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002130 }
2131
2132 /**
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002133 * Close the tab, remove its associated title bar, and adjust mTabControl's
2134 * current tab to a valid value.
Leon Scroggins1f005d32009-08-10 17:36:42 -04002135 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07002136 /* package */ void closeTab(Tab t) {
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002137 int currentIndex = mTabControl.getCurrentIndex();
2138 int removeIndex = mTabControl.getTabIndex(t);
Leon Scroggins1f005d32009-08-10 17:36:42 -04002139 mTabControl.removeTab(t);
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002140 if (currentIndex >= removeIndex && currentIndex != 0) {
2141 currentIndex--;
2142 }
2143 mTabControl.setCurrentTab(mTabControl.getTab(currentIndex));
Andrei Popescua5bf1de2009-09-23 16:39:23 +01002144 resetTitleIconAndProgress();
Leon Scroggins654899b2010-06-25 16:25:23 -04002145 updateLockIconToLatest();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002146 }
2147
Leon Scrogginsdcc5eeb2010-02-23 17:26:37 -05002148 /* package */ void goBackOnePageOrQuit() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002149 Tab current = mTabControl.getCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002150 if (current == null) {
2151 /*
2152 * Instead of finishing the activity, simply push this to the back
2153 * of the stack and let ActivityManager to choose the foreground
2154 * activity. As BrowserActivity is singleTask, it will be always the
2155 * root of the task. So we can use either true or false for
2156 * moveTaskToBack().
2157 */
2158 moveTaskToBack(true);
Grace Kloba00d85e72009-09-23 18:50:05 -07002159 return;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002160 }
2161 WebView w = current.getWebView();
2162 if (w.canGoBack()) {
2163 w.goBack();
2164 } else {
2165 // Check to see if we are closing a window that was created by
2166 // another window. If so, we switch back to that window.
Grace Kloba22ac16e2009-10-07 18:00:23 -07002167 Tab parent = current.getParentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002168 if (parent != null) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04002169 switchToTab(mTabControl.getTabIndex(parent));
2170 // Now we close the other tab
2171 closeTab(current);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002172 } else {
2173 if (current.closeOnExit()) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002174 // force the tab's inLoad() to be false as we are going to
2175 // either finish the activity or remove the tab. This will
2176 // ensure pauseWebViewTimers() taking action.
2177 mTabControl.getCurrentTab().clearInLoad();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002178 if (mTabControl.getTabCount() == 1) {
2179 finish();
2180 return;
2181 }
Mike Reed7bfa63b2009-05-28 11:08:32 -04002182 // call pauseWebViewTimers() now, we won't be able to call
2183 // it in onPause() as the WebView won't be valid.
Grace Klobaec1b5ad2009-08-18 08:42:32 -07002184 // Temporarily change mActivityInPause to be true as
2185 // pauseWebViewTimers() will do nothing if mActivityInPause
2186 // is false.
Grace Kloba918e1d72009-08-13 14:55:06 -07002187 boolean savedState = mActivityInPause;
2188 if (savedState) {
Grace Klobaec1b5ad2009-08-18 08:42:32 -07002189 Log.e(LOGTAG, "BrowserActivity is already paused "
2190 + "while handing goBackOnePageOrQuit.");
Grace Kloba918e1d72009-08-13 14:55:06 -07002191 }
2192 mActivityInPause = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -04002193 pauseWebViewTimers();
Grace Kloba918e1d72009-08-13 14:55:06 -07002194 mActivityInPause = savedState;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002195 removeTabFromContentView(current);
2196 mTabControl.removeTab(current);
2197 }
2198 /*
2199 * Instead of finishing the activity, simply push this to the back
2200 * of the stack and let ActivityManager to choose the foreground
2201 * activity. As BrowserActivity is singleTask, it will be always the
2202 * root of the task. So we can use either true or false for
2203 * moveTaskToBack().
2204 */
2205 moveTaskToBack(true);
2206 }
2207 }
2208 }
2209
Grace Kloba22ac16e2009-10-07 18:00:23 -07002210 boolean isMenuDown() {
2211 return mMenuIsDown;
2212 }
2213
Grace Kloba5942df02009-09-18 11:48:29 -07002214 @Override
2215 public boolean onKeyDown(int keyCode, KeyEvent event) {
Leon Scrogginsf65b50d2009-12-08 10:44:28 -05002216 // Even if MENU is already held down, we need to call to super to open
2217 // the IME on long press.
2218 if (KeyEvent.KEYCODE_MENU == keyCode) {
2219 mMenuIsDown = true;
2220 return super.onKeyDown(keyCode, event);
2221 }
Grace Kloba5942df02009-09-18 11:48:29 -07002222 // The default key mode is DEFAULT_KEYS_SEARCH_LOCAL. As the MENU is
2223 // still down, we don't want to trigger the search. Pretend to consume
2224 // the key and do nothing.
2225 if (mMenuIsDown) return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002226
Grace Kloba5942df02009-09-18 11:48:29 -07002227 switch(keyCode) {
Grace Kloba5942df02009-09-18 11:48:29 -07002228 case KeyEvent.KEYCODE_SPACE:
Grace Klobada0fe552009-09-22 18:17:24 -07002229 // WebView/WebTextView handle the keys in the KeyDown. As
2230 // the Activity's shortcut keys are only handled when WebView
2231 // doesn't, have to do it in onKeyDown instead of onKeyUp.
2232 if (event.isShiftPressed()) {
2233 getTopWindow().pageUp(false);
2234 } else {
2235 getTopWindow().pageDown(false);
2236 }
Grace Kloba5942df02009-09-18 11:48:29 -07002237 return true;
2238 case KeyEvent.KEYCODE_BACK:
2239 if (event.getRepeatCount() == 0) {
2240 event.startTracking();
2241 return true;
2242 } else if (mCustomView == null && mActiveTabsPage == null
2243 && event.isLongPress()) {
2244 bookmarksOrHistoryPicker(true);
2245 return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002246 }
Grace Kloba5942df02009-09-18 11:48:29 -07002247 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002248 }
Grace Kloba5942df02009-09-18 11:48:29 -07002249 return super.onKeyDown(keyCode, event);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002250 }
2251
Grace Kloba5942df02009-09-18 11:48:29 -07002252 @Override
2253 public boolean onKeyUp(int keyCode, KeyEvent event) {
2254 switch(keyCode) {
2255 case KeyEvent.KEYCODE_MENU:
2256 mMenuIsDown = false;
2257 break;
Grace Kloba5942df02009-09-18 11:48:29 -07002258 case KeyEvent.KEYCODE_BACK:
2259 if (event.isTracking() && !event.isCanceled()) {
2260 if (mCustomView != null) {
2261 // if a custom view is showing, hide it
Grace Kloba22ac16e2009-10-07 18:00:23 -07002262 mTabControl.getCurrentWebView().getWebChromeClient()
2263 .onHideCustomView();
Grace Kloba5942df02009-09-18 11:48:29 -07002264 } else if (mActiveTabsPage != null) {
2265 // if tab page is showing, hide it
2266 removeActiveTabPage(true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002267 } else {
Grace Kloba5942df02009-09-18 11:48:29 -07002268 WebView subwindow = mTabControl.getCurrentSubWindow();
2269 if (subwindow != null) {
2270 if (subwindow.canGoBack()) {
2271 subwindow.goBack();
2272 } else {
2273 dismissSubWindow(mTabControl.getCurrentTab());
2274 }
2275 } else {
2276 goBackOnePageOrQuit();
2277 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002278 }
Grace Kloba5942df02009-09-18 11:48:29 -07002279 return true;
2280 }
2281 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002282 }
Grace Kloba5942df02009-09-18 11:48:29 -07002283 return super.onKeyUp(keyCode, event);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002284 }
2285
Leon Scroggins68579392009-09-15 15:31:54 -04002286 /* package */ void stopLoading() {
Ben Murdochb7cc8b42009-09-28 10:59:09 +01002287 mDidStopLoad = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002288 resetTitleAndRevertLockIcon();
2289 WebView w = getTopWindow();
2290 w.stopLoading();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002291 // FIXME: before refactor, it is using mWebViewClient. So I keep the
2292 // same logic here. But for subwindow case, should we call into the main
2293 // WebView's onPageFinished as we never call its onPageStarted and if
2294 // the page finishes itself, we don't call onPageFinished.
2295 mTabControl.getCurrentWebView().getWebViewClient().onPageFinished(w,
2296 w.getUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08002297
2298 cancelStopToast();
2299 mStopToast = Toast
2300 .makeText(this, R.string.stopping, Toast.LENGTH_SHORT);
2301 mStopToast.show();
2302 }
2303
Grace Kloba22ac16e2009-10-07 18:00:23 -07002304 boolean didUserStopLoading() {
2305 return mDidStopLoad;
2306 }
2307
The Android Open Source Project0c908882009-03-03 19:32:16 -08002308 private void cancelStopToast() {
2309 if (mStopToast != null) {
2310 mStopToast.cancel();
2311 mStopToast = null;
2312 }
2313 }
2314
Grace Kloba22ac16e2009-10-07 18:00:23 -07002315 // called by a UI or non-UI thread to post the message
2316 public void postMessage(int what, int arg1, int arg2, Object obj,
2317 long delayMillis) {
2318 mHandler.sendMessageDelayed(mHandler.obtainMessage(what, arg1, arg2,
2319 obj), delayMillis);
2320 }
2321
2322 // called by a UI or non-UI thread to remove the message
2323 void removeMessages(int what, Object object) {
2324 mHandler.removeMessages(what, object);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002325 }
2326
2327 // public message ids
2328 public final static int LOAD_URL = 1001;
2329 public final static int STOP_LOAD = 1002;
2330
2331 // Message Ids
2332 private static final int FOCUS_NODE_HREF = 102;
Grace Kloba92c18a52009-07-31 23:48:32 -07002333 private static final int RELEASE_WAKELOCK = 107;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002334
Grace Kloba22ac16e2009-10-07 18:00:23 -07002335 static final int UPDATE_BOOKMARK_THUMBNAIL = 108;
Ben Murdoch2694e232009-09-29 09:41:11 +01002336
Ben Murdocheecb4e62010-07-06 16:30:38 +01002337 private static final int TOUCH_ICON_DOWNLOADED = 109;
2338
The Android Open Source Project0c908882009-03-03 19:32:16 -08002339 // Private handler for handling javascript and saving passwords
2340 private Handler mHandler = new Handler() {
2341
Michael Kolbe0a36662010-06-29 10:37:12 -07002342 @Override
The Android Open Source Project0c908882009-03-03 19:32:16 -08002343 public void handleMessage(Message msg) {
2344 switch (msg.what) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002345 case FOCUS_NODE_HREF:
Ben Murdoch2694e232009-09-29 09:41:11 +01002346 {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002347 String url = (String) msg.getData().get("url");
Ben Murdoch90d088c2009-11-17 18:14:04 +00002348 String title = (String) msg.getData().get("title");
The Android Open Source Project0c908882009-03-03 19:32:16 -08002349 if (url == null || url.length() == 0) {
2350 break;
2351 }
2352 HashMap focusNodeMap = (HashMap) msg.obj;
2353 WebView view = (WebView) focusNodeMap.get("webview");
2354 // Only apply the action if the top window did not change.
2355 if (getTopWindow() != view) {
2356 break;
2357 }
2358 switch (msg.arg1) {
2359 case R.id.open_context_menu_id:
2360 case R.id.view_image_context_menu_id:
Leon Scroggins92472e82010-02-17 16:32:28 -05002361 loadUrlFromContext(getTopWindow(), url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002362 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002363 case R.id.bookmark_context_menu_id:
2364 Intent intent = new Intent(BrowserActivity.this,
2365 AddBookmarkPage.class);
2366 intent.putExtra("url", url);
Ben Murdoch90d088c2009-11-17 18:14:04 +00002367 intent.putExtra("title", title);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002368 startActivity(intent);
2369 break;
2370 case R.id.share_link_context_menu_id:
Leon Scroggins3e204452010-05-10 11:06:03 -04002371 sharePage(BrowserActivity.this, title, url, null,
Leon Scroggins96afcb12009-12-10 12:35:56 -05002372 null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002373 break;
2374 case R.id.copy_link_context_menu_id:
2375 copy(url);
2376 break;
2377 case R.id.save_link_context_menu_id:
2378 case R.id.download_context_menu_id:
2379 onDownloadStartNoStream(url, null, null, null, -1);
2380 break;
2381 }
2382 break;
Ben Murdoch2694e232009-09-29 09:41:11 +01002383 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002384
2385 case LOAD_URL:
Leon Scroggins92472e82010-02-17 16:32:28 -05002386 loadUrlFromContext(getTopWindow(), (String) msg.obj);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002387 break;
2388
2389 case STOP_LOAD:
2390 stopLoading();
2391 break;
2392
The Android Open Source Project0c908882009-03-03 19:32:16 -08002393 case RELEASE_WAKELOCK:
2394 if (mWakeLock.isHeld()) {
2395 mWakeLock.release();
Grace Kloba5d0e02e2009-10-05 15:15:36 -07002396 // if we reach here, Browser should be still in the
2397 // background loading after WAKELOCK_TIMEOUT (5-min).
2398 // To avoid burning the battery, stop loading.
2399 mTabControl.stopAllLoading();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002400 }
2401 break;
Ben Murdoch2694e232009-09-29 09:41:11 +01002402
2403 case UPDATE_BOOKMARK_THUMBNAIL:
2404 WebView view = (WebView) msg.obj;
2405 if (view != null) {
2406 updateScreenshot(view);
2407 }
2408 break;
Ben Murdocheecb4e62010-07-06 16:30:38 +01002409
2410 case TOUCH_ICON_DOWNLOADED:
2411 Bundle b = msg.getData();
2412 showSaveToHomescreenDialog(b.getString("url"),
2413 b.getString("title"),
2414 (Bitmap) b.getParcelable("touchIcon"),
2415 (Bitmap) b.getParcelable("favicon"));
2416 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002417 }
2418 }
2419 };
2420
Leon Scroggins96afcb12009-12-10 12:35:56 -05002421 /**
2422 * Share a page, providing the title, url, favicon, and a screenshot. Uses
2423 * an {@link Intent} to launch the Activity chooser.
2424 * @param c Context used to launch a new Activity.
2425 * @param title Title of the page. Stored in the Intent with
Paul Westbrook03e6d392010-02-12 10:33:29 -08002426 * {@link Intent#EXTRA_SUBJECT}
Leon Scroggins96afcb12009-12-10 12:35:56 -05002427 * @param url URL of the page. Stored in the Intent with
2428 * {@link Intent#EXTRA_TEXT}
2429 * @param favicon Bitmap of the favicon for the page. Stored in the Intent
2430 * with {@link Browser#EXTRA_SHARE_FAVICON}
2431 * @param screenshot Bitmap of a screenshot of the page. Stored in the
2432 * Intent with {@link Browser#EXTRA_SHARE_SCREENSHOT}
2433 */
2434 public static final void sharePage(Context c, String title, String url,
2435 Bitmap favicon, Bitmap screenshot) {
2436 Intent send = new Intent(Intent.ACTION_SEND);
2437 send.setType("text/plain");
2438 send.putExtra(Intent.EXTRA_TEXT, url);
Paul Westbrook03e6d392010-02-12 10:33:29 -08002439 send.putExtra(Intent.EXTRA_SUBJECT, title);
Leon Scroggins96afcb12009-12-10 12:35:56 -05002440 send.putExtra(Browser.EXTRA_SHARE_FAVICON, favicon);
2441 send.putExtra(Browser.EXTRA_SHARE_SCREENSHOT, screenshot);
2442 try {
2443 c.startActivity(Intent.createChooser(send, c.getString(
2444 R.string.choosertitle_sharevia)));
2445 } catch(android.content.ActivityNotFoundException ex) {
2446 // if no app handles it, do nothing
2447 }
2448 }
2449
Leon Scroggins89c6d362009-07-15 16:54:37 -04002450 private void updateScreenshot(WebView view) {
2451 // If this is a bookmarked site, add a screenshot to the database.
2452 // FIXME: When should we update? Every time?
2453 // FIXME: Would like to make sure there is actually something to
2454 // draw, but the API for that (WebViewCore.pictureReady()) is not
2455 // currently accessible here.
Ben Murdochaac7aa62009-09-17 16:57:40 +01002456
Ben Murdoch87cc65d2010-06-29 20:34:10 +01002457 final Bitmap bm = createScreenshot(view, getDesiredThumbnailWidth(this),
2458 getDesiredThumbnailHeight(this));
Patrick Scottcb192b52010-04-14 14:38:55 -04002459 if (bm == null) {
2460 return;
Leon Scroggins89c6d362009-07-15 16:54:37 -04002461 }
Patrick Scottcb192b52010-04-14 14:38:55 -04002462
2463 final ContentResolver cr = getContentResolver();
2464 final String url = view.getUrl();
2465 final String originalUrl = view.getOriginalUrl();
2466
2467 new AsyncTask<Void, Void, Void>() {
2468 @Override
2469 protected Void doInBackground(Void... unused) {
2470 Cursor c = null;
2471 try {
2472 c = BrowserBookmarksAdapter.queryBookmarksForUrl(
2473 cr, originalUrl, url, true);
2474 if (c != null) {
2475 if (c.moveToFirst()) {
2476 ContentValues values = new ContentValues();
2477 final ByteArrayOutputStream os
2478 = new ByteArrayOutputStream();
2479 bm.compress(Bitmap.CompressFormat.PNG, 100, os);
2480 values.put(Browser.BookmarkColumns.THUMBNAIL,
2481 os.toByteArray());
2482 do {
2483 cr.update(ContentUris.withAppendedId(
2484 Browser.BOOKMARKS_URI, c.getInt(0)),
2485 values, null, null);
2486 } while (c.moveToNext());
2487 }
2488 }
2489 } catch (IllegalStateException e) {
2490 // Ignore
2491 } finally {
2492 if (c != null) c.close();
2493 }
2494 return null;
2495 }
2496 }.execute();
Leon Scroggins89c6d362009-07-15 16:54:37 -04002497 }
2498
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002499 /**
Leon Scrogginsf8551612009-09-24 16:06:02 -04002500 * Values for the size of the thumbnail created when taking a screenshot.
2501 * Lazily initialized. Instead of using these directly, use
2502 * getDesiredThumbnailWidth() or getDesiredThumbnailHeight().
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002503 */
Leon Scrogginsf8551612009-09-24 16:06:02 -04002504 private static int THUMBNAIL_WIDTH = 0;
2505 private static int THUMBNAIL_HEIGHT = 0;
2506
2507 /**
2508 * Return the desired width for thumbnail screenshots, which are stored in
2509 * the database, and used on the bookmarks screen.
2510 * @param context Context for finding out the density of the screen.
2511 * @return int desired width for thumbnail screenshot.
2512 */
2513 /* package */ static int getDesiredThumbnailWidth(Context context) {
2514 if (THUMBNAIL_WIDTH == 0) {
2515 float density = context.getResources().getDisplayMetrics().density;
2516 THUMBNAIL_WIDTH = (int) (90 * density);
2517 THUMBNAIL_HEIGHT = (int) (80 * density);
2518 }
2519 return THUMBNAIL_WIDTH;
2520 }
2521
2522 /**
2523 * Return the desired height for thumbnail screenshots, which are stored in
2524 * the database, and used on the bookmarks screen.
2525 * @param context Context for finding out the density of the screen.
2526 * @return int desired height for thumbnail screenshot.
2527 */
2528 /* package */ static int getDesiredThumbnailHeight(Context context) {
2529 // To ensure that they are both initialized.
2530 getDesiredThumbnailWidth(context);
2531 return THUMBNAIL_HEIGHT;
2532 }
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002533
Ben Murdoch87cc65d2010-06-29 20:34:10 +01002534 private Bitmap createScreenshot(WebView view, int width, int height) {
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002535 Picture thumbnail = view.capturePicture();
Leon Scroggins45800572009-09-29 16:38:47 -04002536 if (thumbnail == null) {
2537 return null;
2538 }
Ben Murdoch87cc65d2010-06-29 20:34:10 +01002539 Bitmap bm = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002540 Canvas canvas = new Canvas(bm);
2541 // May need to tweak these values to determine what is the
2542 // best scale factor
Ben Murdoch2694e232009-09-29 09:41:11 +01002543 int thumbnailWidth = thumbnail.getWidth();
Ben Murdochae59c3f2009-10-20 18:30:28 +01002544 int thumbnailHeight = thumbnail.getHeight();
2545 float scaleFactorX = 1.0f;
2546 float scaleFactorY = 1.0f;
Ben Murdoch2694e232009-09-29 09:41:11 +01002547 if (thumbnailWidth > 0) {
Ben Murdoch87cc65d2010-06-29 20:34:10 +01002548 scaleFactorX = (float) width / (float)thumbnailWidth;
Ben Murdochae59c3f2009-10-20 18:30:28 +01002549 } else {
2550 return null;
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002551 }
Ben Murdochae59c3f2009-10-20 18:30:28 +01002552
2553 if (view.getWidth() > view.getHeight() &&
2554 thumbnailHeight < view.getHeight() && thumbnailHeight > 0) {
2555 // If the device is in landscape and the page is shorter
2556 // than the height of the view, stretch the thumbnail to fill the
2557 // space.
Ben Murdoch87cc65d2010-06-29 20:34:10 +01002558 scaleFactorY = (float) height / (float)thumbnailHeight;
Ben Murdochae59c3f2009-10-20 18:30:28 +01002559 } else {
2560 // In the portrait case, this looks nice.
2561 scaleFactorY = scaleFactorX;
2562 }
2563
2564 canvas.scale(scaleFactorX, scaleFactorY);
2565
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002566 thumbnail.draw(canvas);
2567 return bm;
2568 }
2569
The Android Open Source Project0c908882009-03-03 19:32:16 -08002570 // -------------------------------------------------------------------------
Grace Kloba22ac16e2009-10-07 18:00:23 -07002571 // Helper function for WebViewClient.
The Android Open Source Project0c908882009-03-03 19:32:16 -08002572 //-------------------------------------------------------------------------
2573
2574 // Use in overrideUrlLoading
2575 /* package */ final static String SCHEME_WTAI = "wtai://wp/";
2576 /* package */ final static String SCHEME_WTAI_MC = "wtai://wp/mc;";
2577 /* package */ final static String SCHEME_WTAI_SD = "wtai://wp/sd;";
2578 /* package */ final static String SCHEME_WTAI_AP = "wtai://wp/ap;";
2579
Leon Scroggins92472e82010-02-17 16:32:28 -05002580 // Keep this initial progress in sync with initialProgressValue (* 100)
2581 // in ProgressTracker.cpp
2582 private final static int INITIAL_PROGRESS = 10;
2583
Grace Kloba22ac16e2009-10-07 18:00:23 -07002584 void onPageStarted(WebView view, String url, Bitmap favicon) {
2585 // when BrowserActivity just starts, onPageStarted may be called before
2586 // onResume as it is triggered from onCreate. Call resumeWebViewTimers
2587 // to start the timer. As we won't switch tabs while an activity is in
2588 // pause state, we can ensure calling resume and pause in pair.
2589 if (mActivityInPause) resumeWebViewTimers();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002590
Grace Kloba22ac16e2009-10-07 18:00:23 -07002591 resetLockIcon(url);
2592 setUrlTitle(url, null);
2593 setFavicon(favicon);
Leon Scroggins8cf8f682009-11-04 11:13:50 -08002594 // Show some progress so that the user knows the page is beginning to
2595 // load
Leon Scroggins92472e82010-02-17 16:32:28 -05002596 onProgressChanged(view, INITIAL_PROGRESS);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002597 mDidStopLoad = false;
Grace Kloba22ac16e2009-10-07 18:00:23 -07002598 if (!mIsNetworkUp) createAndShowNetworkDialog();
Cary Clark01cfcdd2010-06-04 16:36:45 -04002599 closeDialogs();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002600 if (mSettings.isTracing()) {
2601 String host;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002602 try {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002603 WebAddress uri = new WebAddress(url);
2604 host = uri.mHost;
2605 } catch (android.net.ParseException ex) {
2606 host = "browser";
The Android Open Source Project0c908882009-03-03 19:32:16 -08002607 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002608 host = host.replace('.', '_');
2609 host += ".trace";
2610 mInTrace = true;
2611 Debug.startMethodTracing(host, 20 * 1024 * 1024);
2612 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002613
Grace Kloba22ac16e2009-10-07 18:00:23 -07002614 // Performance probe
2615 if (false) {
2616 mStart = SystemClock.uptimeMillis();
2617 mProcessStart = Process.getElapsedCpuTime();
2618 long[] sysCpu = new long[7];
2619 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2620 sysCpu, null)) {
2621 mUserStart = sysCpu[0] + sysCpu[1];
2622 mSystemStart = sysCpu[2];
2623 mIdleStart = sysCpu[3];
2624 mIrqStart = sysCpu[4] + sysCpu[5] + sysCpu[6];
2625 }
2626 mUiStart = SystemClock.currentThreadTimeMillis();
2627 }
2628 }
2629
2630 void onPageFinished(WebView view, String url) {
2631 // Reset the title and icon in case we stopped a provisional load.
2632 resetTitleAndIcon(view);
2633 // Update the lock icon image only once we are done loading
2634 updateLockIconToLatest();
2635 // pause the WebView timer and release the wake lock if it is finished
2636 // while BrowserActivity is in pause state.
2637 if (mActivityInPause && pauseWebViewTimers()) {
2638 if (mWakeLock.isHeld()) {
2639 mHandler.removeMessages(RELEASE_WAKELOCK);
2640 mWakeLock.release();
2641 }
2642 }
2643
2644 // Performance probe
2645 if (false) {
2646 long[] sysCpu = new long[7];
2647 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2648 sysCpu, null)) {
2649 String uiInfo = "UI thread used "
2650 + (SystemClock.currentThreadTimeMillis() - mUiStart)
2651 + " ms";
2652 if (LOGD_ENABLED) {
2653 Log.d(LOGTAG, uiInfo);
2654 }
2655 //The string that gets written to the log
2656 String performanceString = "It took total "
2657 + (SystemClock.uptimeMillis() - mStart)
2658 + " ms clock time to load the page."
2659 + "\nbrowser process used "
2660 + (Process.getElapsedCpuTime() - mProcessStart)
2661 + " ms, user processes used "
2662 + (sysCpu[0] + sysCpu[1] - mUserStart) * 10
2663 + " ms, kernel used "
2664 + (sysCpu[2] - mSystemStart) * 10
2665 + " ms, idle took " + (sysCpu[3] - mIdleStart) * 10
2666 + " ms and irq took "
2667 + (sysCpu[4] + sysCpu[5] + sysCpu[6] - mIrqStart)
2668 * 10 + " ms, " + uiInfo;
2669 if (LOGD_ENABLED) {
2670 Log.d(LOGTAG, performanceString + "\nWebpage: " + url);
2671 }
2672 if (url != null) {
2673 // strip the url to maintain consistency
2674 String newUrl = new String(url);
2675 if (newUrl.startsWith("http://www.")) {
2676 newUrl = newUrl.substring(11);
2677 } else if (newUrl.startsWith("http://")) {
2678 newUrl = newUrl.substring(7);
2679 } else if (newUrl.startsWith("https://www.")) {
2680 newUrl = newUrl.substring(12);
2681 } else if (newUrl.startsWith("https://")) {
2682 newUrl = newUrl.substring(8);
2683 }
2684 if (LOGD_ENABLED) {
2685 Log.d(LOGTAG, newUrl + " loaded");
2686 }
Grace Kloba5b078b52009-06-24 20:23:41 -07002687 }
2688 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002689 }
Grace Kloba5b078b52009-06-24 20:23:41 -07002690
Grace Kloba22ac16e2009-10-07 18:00:23 -07002691 if (mInTrace) {
2692 mInTrace = false;
2693 Debug.stopMethodTracing();
2694 }
2695 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002696
Grace Klobae7fe26b2010-06-28 16:23:33 -07002697 private void closeEmptyChildTab() {
2698 Tab current = mTabControl.getCurrentTab();
2699 if (current != null
2700 && current.getWebView().copyBackForwardList().getSize() == 0) {
2701 Tab parent = current.getParentTab();
2702 if (parent != null) {
2703 switchToTab(mTabControl.getTabIndex(parent));
2704 closeTab(current);
2705 }
2706 }
2707 }
2708
Grace Kloba22ac16e2009-10-07 18:00:23 -07002709 boolean shouldOverrideUrlLoading(WebView view, String url) {
2710 if (url.startsWith(SCHEME_WTAI)) {
2711 // wtai://wp/mc;number
2712 // number=string(phone-number)
2713 if (url.startsWith(SCHEME_WTAI_MC)) {
2714 Intent intent = new Intent(Intent.ACTION_VIEW,
2715 Uri.parse(WebView.SCHEME_TEL +
2716 url.substring(SCHEME_WTAI_MC.length())));
2717 startActivity(intent);
Grace Klobae7fe26b2010-06-28 16:23:33 -07002718 // before leaving BrowserActivity, close the empty child tab.
2719 // If a new tab is created through JavaScript open to load this
2720 // url, we would like to close it as we will load this url in a
2721 // different Activity.
2722 closeEmptyChildTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002723 return true;
2724 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002725 // wtai://wp/sd;dtmf
2726 // dtmf=string(dialstring)
2727 if (url.startsWith(SCHEME_WTAI_SD)) {
2728 // TODO: only send when there is active voice connection
2729 return false;
2730 }
2731 // wtai://wp/ap;number;name
2732 // number=string(phone-number)
2733 // name=string
2734 if (url.startsWith(SCHEME_WTAI_AP)) {
2735 // TODO
2736 return false;
2737 }
2738 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002739
Grace Kloba22ac16e2009-10-07 18:00:23 -07002740 // The "about:" schemes are internal to the browser; don't want these to
2741 // be dispatched to other apps.
2742 if (url.startsWith("about:")) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002743 return false;
2744 }
2745
Grace Kloba22ac16e2009-10-07 18:00:23 -07002746 Intent intent;
2747 // perform generic parsing of the URI to turn it into an Intent.
2748 try {
2749 intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME);
2750 } catch (URISyntaxException ex) {
2751 Log.w("Browser", "Bad URI " + url + ": " + ex.getMessage());
2752 return false;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002753 }
2754
Grace Kloba22ac16e2009-10-07 18:00:23 -07002755 // check whether the intent can be resolved. If not, we will see
2756 // whether we can download it from the Market.
2757 if (getPackageManager().resolveActivity(intent, 0) == null) {
2758 String packagename = intent.getPackage();
2759 if (packagename != null) {
2760 intent = new Intent(Intent.ACTION_VIEW, Uri
2761 .parse("market://search?q=pname:" + packagename));
2762 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2763 startActivity(intent);
Grace Klobae7fe26b2010-06-28 16:23:33 -07002764 // before leaving BrowserActivity, close the empty child tab.
2765 // If a new tab is created through JavaScript open to load this
2766 // url, we would like to close it as we will load this url in a
2767 // different Activity.
2768 closeEmptyChildTab();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002769 return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002770 } else {
2771 return false;
2772 }
2773 }
2774
Grace Kloba22ac16e2009-10-07 18:00:23 -07002775 // sanitize the Intent, ensuring web pages can not bypass browser
2776 // security (only access to BROWSABLE activities).
2777 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2778 intent.setComponent(null);
2779 try {
2780 if (startActivityIfNeeded(intent, -1)) {
Grace Klobae7fe26b2010-06-28 16:23:33 -07002781 // before leaving BrowserActivity, close the empty child tab.
2782 // If a new tab is created through JavaScript open to load this
2783 // url, we would like to close it as we will load this url in a
2784 // different Activity.
2785 closeEmptyChildTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002786 return true;
2787 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002788 } catch (ActivityNotFoundException ex) {
2789 // ignore the error. If no application can handle the URL,
2790 // eg about:blank, assume the browser can handle it.
2791 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002792
Grace Kloba22ac16e2009-10-07 18:00:23 -07002793 if (mMenuIsDown) {
2794 openTab(url);
2795 closeOptionsMenu();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002796 return true;
2797 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002798 return false;
2799 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002800
Grace Kloba22ac16e2009-10-07 18:00:23 -07002801 // -------------------------------------------------------------------------
2802 // Helper function for WebChromeClient
2803 // -------------------------------------------------------------------------
The Android Open Source Project0c908882009-03-03 19:32:16 -08002804
Grace Kloba22ac16e2009-10-07 18:00:23 -07002805 void onProgressChanged(WebView view, int newProgress) {
Leon Scrogginsd746a942010-05-19 13:21:44 -04002806 if (mXLargeScreenSize) {
2807 mTitleBar.setProgress(newProgress);
2808 } else {
2809 // On the phone, the fake title bar will always cover up the
2810 // regular title bar (or the regular one is offscreen), so only the
2811 // fake title bar needs to change its progress
2812 mFakeTitleBar.setProgress(newProgress);
2813 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002814
Grace Kloba22ac16e2009-10-07 18:00:23 -07002815 if (newProgress == 100) {
2816 // onProgressChanged() may continue to be called after the main
2817 // frame has finished loading, as any remaining sub frames continue
2818 // to load. We'll only get called once though with newProgress as
2819 // 100 when everything is loaded. (onPageFinished is called once
2820 // when the main frame completes loading regardless of the state of
2821 // any sub frames so calls to onProgressChanges may continue after
2822 // onPageFinished has executed)
2823 if (mInLoad) {
2824 mInLoad = false;
Leon Scrogginsa27ff192009-09-14 12:58:04 -04002825 updateInLoadMenuItems();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002826 // If the options menu is open, leave the title bar
2827 if (!mOptionsMenuOpen || !mIconView) {
2828 hideFakeTitleBar();
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07002829 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002830 }
Leon Scrogginsaa37e7f2010-03-05 11:51:20 -05002831 } else {
2832 if (!mInLoad) {
2833 // onPageFinished may have already been called but a subframe is
2834 // still loading and updating the progress. Reset mInLoad and
2835 // update the menu items.
2836 mInLoad = true;
2837 updateInLoadMenuItems();
2838 }
2839 // When the page first begins to load, the Activity may still be
2840 // paused, in which case showFakeTitleBar will do nothing. Call
2841 // again as the page continues to load so that it will be shown.
2842 // (Calling it will the fake title bar is already showing will also
2843 // do nothing.
Grace Kloba22ac16e2009-10-07 18:00:23 -07002844 if (!mOptionsMenuOpen || mIconView) {
2845 // This page has begun to load, so show the title bar
2846 showFakeTitleBar();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002847 }
2848 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002849 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002850
Grace Kloba22ac16e2009-10-07 18:00:23 -07002851 void onShowCustomView(View view, WebChromeClient.CustomViewCallback callback) {
Derek Sollenberger8ff57db2009-12-08 15:39:55 -05002852 // if a view already exists then immediately terminate the new one
2853 if (mCustomView != null) {
2854 callback.onCustomViewHidden();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002855 return;
Derek Sollenberger8ff57db2009-12-08 15:39:55 -05002856 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002857
2858 // Add the custom view to its container.
2859 mCustomViewContainer.addView(view, COVER_SCREEN_GRAVITY_CENTER);
2860 mCustomView = view;
2861 mCustomViewCallback = callback;
2862 // Save the menu state and set it to empty while the custom
2863 // view is showing.
2864 mOldMenuState = mMenuState;
2865 mMenuState = EMPTY_MENU;
2866 // Hide the content view.
2867 mContentView.setVisibility(View.GONE);
2868 // Finally show the custom view container.
Andrei Popescu163ab742009-10-20 17:58:23 +01002869 setStatusBarVisibility(false);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002870 mCustomViewContainer.setVisibility(View.VISIBLE);
2871 mCustomViewContainer.bringToFront();
2872 }
2873
2874 void onHideCustomView() {
2875 if (mCustomView == null)
2876 return;
2877
2878 // Hide the custom view.
2879 mCustomView.setVisibility(View.GONE);
2880 // Remove the custom view from its container.
2881 mCustomViewContainer.removeView(mCustomView);
2882 mCustomView = null;
2883 // Reset the old menu state.
2884 mMenuState = mOldMenuState;
2885 mOldMenuState = EMPTY_MENU;
2886 mCustomViewContainer.setVisibility(View.GONE);
2887 mCustomViewCallback.onCustomViewHidden();
2888 // Show the content view.
Andrei Popescu163ab742009-10-20 17:58:23 +01002889 setStatusBarVisibility(true);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002890 mContentView.setVisibility(View.VISIBLE);
2891 }
2892
2893 Bitmap getDefaultVideoPoster() {
2894 if (mDefaultVideoPoster == null) {
2895 mDefaultVideoPoster = BitmapFactory.decodeResource(
2896 getResources(), R.drawable.default_video_poster);
Patrick Scott3918d442009-08-04 13:22:29 -04002897 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002898 return mDefaultVideoPoster;
2899 }
Patrick Scott3918d442009-08-04 13:22:29 -04002900
Grace Kloba22ac16e2009-10-07 18:00:23 -07002901 View getVideoLoadingProgressView() {
2902 if (mVideoProgressView == null) {
2903 LayoutInflater inflater = LayoutInflater.from(BrowserActivity.this);
2904 mVideoProgressView = inflater.inflate(
2905 R.layout.video_loading_progress, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002906 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002907 return mVideoProgressView;
2908 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002909
Leon Scroggins8d5fa432009-10-02 15:55:59 -04002910 /*
2911 * The Object used to inform the WebView of the file to upload.
2912 */
2913 private ValueCallback<Uri> mUploadMessage;
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002914 private String mCameraFilePath;
Leon Scroggins8d5fa432009-10-02 15:55:59 -04002915
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002916 void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
2917
2918 final String imageMimeType = "image/*";
Ben Murdoch6af492a2010-06-15 12:38:17 +01002919 final String videoMimeType = "video/*";
Ben Murdoch039bd472010-07-21 21:26:57 +01002920 final String audioMimeType = "audio/*";
Ben Murdochb50d7402010-07-16 12:42:22 +01002921 final String mediaSourceKey = "capture";
Ben Murdoch6af492a2010-06-15 12:38:17 +01002922 final String mediaSourceValueCamera = "camera";
Ben Murdochb50d7402010-07-16 12:42:22 +01002923 final String mediaSourceValueFileSystem = "filesystem";
Ben Murdoch6af492a2010-06-15 12:38:17 +01002924 final String mediaSourceValueCamcorder = "camcorder";
Ben Murdoch039bd472010-07-21 21:26:57 +01002925 final String mediaSourceValueMicrophone = "microphone";
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002926
Ben Murdoch039bd472010-07-21 21:26:57 +01002927 // media source can be 'filesystem' or 'camera' or 'camcorder' or 'microphone'.
Ben Murdoch6af492a2010-06-15 12:38:17 +01002928 String mediaSource = "";
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002929
Ben Murdoch6af492a2010-06-15 12:38:17 +01002930 // We add the camera intent if there was no accept type (or '*/*' or 'image/*').
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002931 boolean addCameraIntent = true;
Ben Murdoch6af492a2010-06-15 12:38:17 +01002932 // We add the camcorder intent if there was no accept type (or '*/*' or 'video/*').
2933 boolean addCamcorderIntent = true;
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002934
Ben Murdoch6af492a2010-06-15 12:38:17 +01002935 if (mUploadMessage != null) {
2936 // Already a file picker operation in progress.
2937 return;
2938 }
2939
Grace Kloba22ac16e2009-10-07 18:00:23 -07002940 mUploadMessage = uploadMsg;
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002941
2942 // Parse the accept type.
2943 String params[] = acceptType.split(";");
2944 String mimeType = params[0];
2945
2946 for (String p : params) {
2947 String[] keyValue = p.split("=");
2948 if (keyValue.length == 2) {
2949 // Process key=value parameters.
Ben Murdoch6af492a2010-06-15 12:38:17 +01002950 if (mediaSourceKey.equals(keyValue[0])) {
2951 mediaSource = keyValue[1];
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002952 }
2953 }
2954 }
2955
2956 // This intent will display the standard OPENABLE file picker.
Grace Kloba22ac16e2009-10-07 18:00:23 -07002957 Intent i = new Intent(Intent.ACTION_GET_CONTENT);
2958 i.addCategory(Intent.CATEGORY_OPENABLE);
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002959
2960 // Create an intent to add to the standard file picker that will
2961 // capture an image from the camera. We'll combine this intent with
2962 // the standard OPENABLE picker unless the web developer specifically
2963 // requested the camera or gallery be opened by passing a parameter
2964 // in the accept type.
2965 Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
2966 File externalDataDir = Environment.getExternalStoragePublicDirectory(
2967 Environment.DIRECTORY_DCIM);
2968 File cameraDataDir = new File(externalDataDir.getAbsolutePath() +
2969 File.separator + "browser-photos");
2970 cameraDataDir.mkdirs();
2971 mCameraFilePath = cameraDataDir.getAbsolutePath() + File.separator +
2972 System.currentTimeMillis() + ".jpg";
2973 cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(mCameraFilePath)));
2974
Ben Murdoch6af492a2010-06-15 12:38:17 +01002975 Intent camcorderIntent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
2976
Ben Murdoch039bd472010-07-21 21:26:57 +01002977 Intent soundRecIntent = new Intent(MediaStore.Audio.Media.RECORD_SOUND_ACTION);
2978
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002979 if (mimeType.equals(imageMimeType)) {
2980 i.setType(imageMimeType);
Ben Murdoch6af492a2010-06-15 12:38:17 +01002981 addCamcorderIntent = false;
2982 if (mediaSource.equals(mediaSourceValueCamera)) {
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002983 // Specified 'image/*' and requested the camera, so go ahead and launch the camera
2984 // directly.
2985 BrowserActivity.this.startActivityForResult(cameraIntent, FILE_SELECTED);
2986 return;
Ben Murdochb50d7402010-07-16 12:42:22 +01002987 } else if (mediaSource.equals(mediaSourceValueFileSystem)) {
2988 // Specified filesytem as the source, so don't want to consider the camera.
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01002989 addCameraIntent = false;
2990 }
Ben Murdoch6af492a2010-06-15 12:38:17 +01002991 } else if (mimeType.equals(videoMimeType)) {
2992 i.setType(videoMimeType);
2993 addCameraIntent = false;
2994 // The camcorder saves it's own file and returns it to us in the intent, so
2995 // we don't need to generate one here.
2996 mCameraFilePath = null;
2997
2998 if (mediaSource.equals(mediaSourceValueCamcorder)) {
Ben Murdoch039bd472010-07-21 21:26:57 +01002999 // Specified 'video/*' and requested the camcorder, so go ahead and launch the
3000 // camcorder directly.
Ben Murdoch6af492a2010-06-15 12:38:17 +01003001 BrowserActivity.this.startActivityForResult(camcorderIntent, FILE_SELECTED);
3002 return;
Ben Murdochb50d7402010-07-16 12:42:22 +01003003 } else if (mediaSource.equals(mediaSourceValueFileSystem)) {
3004 // Specified filesystem as the source, so don't want to consider the camcorder.
Ben Murdoch6af492a2010-06-15 12:38:17 +01003005 addCamcorderIntent = false;
3006 }
Ben Murdoch039bd472010-07-21 21:26:57 +01003007 } else if (mimeType.equals(audioMimeType)) {
3008 i.setType(audioMimeType);
3009 addCameraIntent = false;
3010 addCamcorderIntent = false;
3011 if (mediaSource.equals(mediaSourceValueMicrophone)) {
3012 // Specified 'audio/*' and requested microphone, so go ahead and launch the sound
3013 // recorder.
3014 BrowserActivity.this.startActivityForResult(soundRecIntent, FILE_SELECTED);
3015 return;
3016 }
3017 // On a default system, there is no single option to open an audio "gallery". Both the
3018 // sound recorder and music browser respond to the OPENABLE/audio/* intent unlike the
3019 // image/* and video/* OPENABLE intents where the image / video gallery are the only
3020 // respondants (and so the user is not prompted by default).
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003021 } else {
3022 i.setType("*/*");
3023 }
3024
Ben Murdoch6af492a2010-06-15 12:38:17 +01003025 // Combine the chooser and the extra choices (like camera or camcorder)
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003026 Intent chooser = new Intent(Intent.ACTION_CHOOSER);
3027 chooser.putExtra(Intent.EXTRA_INTENT, i);
3028
Ben Murdoch6af492a2010-06-15 12:38:17 +01003029 Vector<Intent> extraInitialIntents = new Vector<Intent>(0);
3030
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003031 if (addCameraIntent) {
Ben Murdoch6af492a2010-06-15 12:38:17 +01003032 extraInitialIntents.add(cameraIntent);
3033 }
3034
3035 if (addCamcorderIntent) {
3036 extraInitialIntents.add(camcorderIntent);
3037 }
3038
3039 if (extraInitialIntents.size() > 0) {
3040 Intent[] extraIntents = new Intent[extraInitialIntents.size()];
3041 chooser.putExtra(Intent.EXTRA_INITIAL_INTENTS, extraInitialIntents.toArray(extraIntents));
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003042 }
3043
3044 chooser.putExtra(Intent.EXTRA_TITLE, getString(R.string.choose_upload));
3045 BrowserActivity.this.startActivityForResult(chooser, FILE_SELECTED);
Grace Kloba22ac16e2009-10-07 18:00:23 -07003046 }
3047
3048 // -------------------------------------------------------------------------
3049 // Implement functions for DownloadListener
3050 // -------------------------------------------------------------------------
3051
The Android Open Source Project0c908882009-03-03 19:32:16 -08003052 /**
3053 * Notify the host application a download should be done, or that
3054 * the data should be streamed if a streaming viewer is available.
3055 * @param url The full url to the content that should be downloaded
3056 * @param contentDisposition Content-disposition http header, if
3057 * present.
3058 * @param mimetype The mimetype of the content reported by the server
3059 * @param contentLength The file size reported by the server
3060 */
3061 public void onDownloadStart(String url, String userAgent,
3062 String contentDisposition, String mimetype, long contentLength) {
3063 // if we're dealing wih A/V content that's not explicitly marked
3064 // for download, check if it's streamable.
3065 if (contentDisposition == null
Patrick Scotte1fb9662009-08-31 14:31:52 -04003066 || !contentDisposition.regionMatches(
3067 true, 0, "attachment", 0, 10)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003068 // query the package manager to see if there's a registered handler
3069 // that matches.
3070 Intent intent = new Intent(Intent.ACTION_VIEW);
3071 intent.setDataAndType(Uri.parse(url), mimetype);
Patrick Scotte1fb9662009-08-31 14:31:52 -04003072 ResolveInfo info = getPackageManager().resolveActivity(intent,
3073 PackageManager.MATCH_DEFAULT_ONLY);
3074 if (info != null) {
3075 ComponentName myName = getComponentName();
3076 // If we resolved to ourselves, we don't want to attempt to
3077 // load the url only to try and download it again.
3078 if (!myName.getPackageName().equals(
3079 info.activityInfo.packageName)
3080 || !myName.getClassName().equals(
3081 info.activityInfo.name)) {
3082 // someone (other than us) knows how to handle this mime
3083 // type with this scheme, don't download.
3084 try {
3085 startActivity(intent);
3086 return;
3087 } catch (ActivityNotFoundException ex) {
3088 if (LOGD_ENABLED) {
3089 Log.d(LOGTAG, "activity not found for " + mimetype
3090 + " over " + Uri.parse(url).getScheme(),
3091 ex);
3092 }
3093 // Best behavior is to fall back to a download in this
3094 // case
The Android Open Source Project0c908882009-03-03 19:32:16 -08003095 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003096 }
3097 }
3098 }
3099 onDownloadStartNoStream(url, userAgent, contentDisposition, mimetype, contentLength);
3100 }
3101
Kristian Monsenfa52d172010-03-25 18:29:21 +00003102 // This is to work around the fact that java.net.URI throws Exceptions
3103 // instead of just encoding URL's properly
3104 // Helper method for onDownloadStartNoStream
3105 private static String encodePath(String path) {
3106 char[] chars = path.toCharArray();
3107
3108 boolean needed = false;
3109 for (char c : chars) {
3110 if (c == '[' || c == ']') {
3111 needed = true;
3112 break;
3113 }
3114 }
3115 if (needed == false) {
3116 return path;
3117 }
3118
3119 StringBuilder sb = new StringBuilder("");
3120 for (char c : chars) {
3121 if (c == '[' || c == ']') {
3122 sb.append('%');
3123 sb.append(Integer.toHexString(c));
3124 } else {
3125 sb.append(c);
3126 }
3127 }
3128
3129 return sb.toString();
3130 }
3131
The Android Open Source Project0c908882009-03-03 19:32:16 -08003132 /**
3133 * Notify the host application a download should be done, even if there
3134 * is a streaming viewer available for thise type.
3135 * @param url The full url to the content that should be downloaded
3136 * @param contentDisposition Content-disposition http header, if
3137 * present.
3138 * @param mimetype The mimetype of the content reported by the server
3139 * @param contentLength The file size reported by the server
3140 */
3141 /*package */ void onDownloadStartNoStream(String url, String userAgent,
3142 String contentDisposition, String mimetype, long contentLength) {
3143
3144 String filename = URLUtil.guessFileName(url,
3145 contentDisposition, mimetype);
3146
3147 // Check to see if we have an SDCard
3148 String status = Environment.getExternalStorageState();
3149 if (!status.equals(Environment.MEDIA_MOUNTED)) {
3150 int title;
3151 String msg;
3152
3153 // Check to see if the SDCard is busy, same as the music app
3154 if (status.equals(Environment.MEDIA_SHARED)) {
3155 msg = getString(R.string.download_sdcard_busy_dlg_msg);
3156 title = R.string.download_sdcard_busy_dlg_title;
3157 } else {
3158 msg = getString(R.string.download_no_sdcard_dlg_msg, filename);
3159 title = R.string.download_no_sdcard_dlg_title;
3160 }
3161
3162 new AlertDialog.Builder(this)
3163 .setTitle(title)
3164 .setIcon(android.R.drawable.ic_dialog_alert)
3165 .setMessage(msg)
3166 .setPositiveButton(R.string.ok, null)
3167 .show();
3168 return;
3169 }
3170
Kristian Monsenfa52d172010-03-25 18:29:21 +00003171 // java.net.URI is a lot stricter than KURL so we have to encode some
3172 // extra characters. Fix for b 2538060 and b 1634719
3173 WebAddress webAddress;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003174 try {
Kristian Monsenfa52d172010-03-25 18:29:21 +00003175 webAddress = new WebAddress(url);
3176 webAddress.mPath = encodePath(webAddress.mPath);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003177 } catch (Exception e) {
Kristian Monsenfa52d172010-03-25 18:29:21 +00003178 // This only happens for very bad urls, we want to chatch the
3179 // exception here
3180 Log.e(LOGTAG, "Exception trying to parse url:" + url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003181 return;
3182 }
3183
3184 // XXX: Have to use the old url since the cookies were stored using the
3185 // old percent-encoded url.
3186 String cookies = CookieManager.getInstance().getCookie(url);
3187
3188 ContentValues values = new ContentValues();
Kristian Monsenfa52d172010-03-25 18:29:21 +00003189 values.put(Downloads.Impl.COLUMN_URI, webAddress.toString());
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08003190 values.put(Downloads.Impl.COLUMN_COOKIE_DATA, cookies);
3191 values.put(Downloads.Impl.COLUMN_USER_AGENT, userAgent);
3192 values.put(Downloads.Impl.COLUMN_NOTIFICATION_PACKAGE,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003193 getPackageName());
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08003194 values.put(Downloads.Impl.COLUMN_NOTIFICATION_CLASS,
Leon Scrogginsa563d092010-04-19 16:53:49 -04003195 OpenDownloadReceiver.class.getCanonicalName());
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08003196 values.put(Downloads.Impl.COLUMN_VISIBILITY,
3197 Downloads.Impl.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
3198 values.put(Downloads.Impl.COLUMN_MIME_TYPE, mimetype);
3199 values.put(Downloads.Impl.COLUMN_FILE_NAME_HINT, filename);
Kristian Monsenfa52d172010-03-25 18:29:21 +00003200 values.put(Downloads.Impl.COLUMN_DESCRIPTION, webAddress.mHost);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003201 if (contentLength > 0) {
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08003202 values.put(Downloads.Impl.COLUMN_TOTAL_BYTES, contentLength);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003203 }
3204 if (mimetype == null) {
3205 // We must have long pressed on a link or image to download it. We
3206 // are not sure of the mimetype in this case, so do a head request
3207 new FetchUrlMimeType(this).execute(values);
3208 } else {
3209 final Uri contentUri =
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08003210 getContentResolver().insert(Downloads.Impl.CONTENT_URI, values);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003211 }
Leon Scroggins9191a7f2010-03-18 14:44:44 -04003212 Toast.makeText(this, R.string.download_pending, Toast.LENGTH_SHORT)
3213 .show();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003214 }
3215
Grace Kloba22ac16e2009-10-07 18:00:23 -07003216 // -------------------------------------------------------------------------
3217
The Android Open Source Project0c908882009-03-03 19:32:16 -08003218 /**
3219 * Resets the lock icon. This method is called when we start a new load and
3220 * know the url to be loaded.
3221 */
3222 private void resetLockIcon(String url) {
3223 // Save the lock-icon state (we revert to it if the load gets cancelled)
Grace Kloba22ac16e2009-10-07 18:00:23 -07003224 mTabControl.getCurrentTab().resetLockIcon(url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003225 updateLockIconImage(LOCK_ICON_UNSECURE);
3226 }
3227
The Android Open Source Project0c908882009-03-03 19:32:16 -08003228 /**
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04003229 * Update the lock icon to correspond to our latest state.
3230 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003231 private void updateLockIconToLatest() {
Leon Scroggins91f65fc2010-06-29 13:52:39 -04003232 Tab t = mTabControl.getCurrentTab();
3233 if (t != null) {
3234 updateLockIconImage(t.getLockIconType());
3235 }
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04003236 }
3237
3238 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08003239 * Updates the lock-icon image in the title-bar.
3240 */
3241 private void updateLockIconImage(int lockIconType) {
3242 Drawable d = null;
3243 if (lockIconType == LOCK_ICON_SECURE) {
3244 d = mSecLockIcon;
3245 } else if (lockIconType == LOCK_ICON_MIXED) {
3246 d = mMixLockIcon;
3247 }
Leon Scroggins68579392009-09-15 15:31:54 -04003248 mTitleBar.setLock(d);
Leon Scrogginsd746a942010-05-19 13:21:44 -04003249 if (!mXLargeScreenSize) {
3250 mFakeTitleBar.setLock(d);
3251 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003252 }
3253
3254 /**
3255 * Displays a page-info dialog.
3256 * @param tab The tab to show info about
3257 * @param fromShowSSLCertificateOnError The flag that indicates whether
3258 * this dialog was opened from the SSL-certificate-on-error dialog or
3259 * not. This is important, since we need to know whether to return to
3260 * the parent dialog or simply dismiss.
3261 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003262 private void showPageInfo(final Tab tab,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003263 final boolean fromShowSSLCertificateOnError) {
3264 final LayoutInflater factory = LayoutInflater
3265 .from(this);
3266
3267 final View pageInfoView = factory.inflate(R.layout.page_info, null);
3268
3269 final WebView view = tab.getWebView();
3270
3271 String url = null;
3272 String title = null;
3273
3274 if (view == null) {
3275 url = tab.getUrl();
3276 title = tab.getTitle();
3277 } else if (view == mTabControl.getCurrentWebView()) {
3278 // Use the cached title and url if this is the current WebView
3279 url = mUrl;
3280 title = mTitle;
3281 } else {
3282 url = view.getUrl();
3283 title = view.getTitle();
3284 }
3285
3286 if (url == null) {
3287 url = "";
3288 }
3289 if (title == null) {
3290 title = "";
3291 }
3292
3293 ((TextView) pageInfoView.findViewById(R.id.address)).setText(url);
3294 ((TextView) pageInfoView.findViewById(R.id.title)).setText(title);
3295
3296 mPageInfoView = tab;
Leon Scrogginsc7b92f82010-01-11 18:17:31 -05003297 mPageInfoFromShowSSLCertificateOnError = fromShowSSLCertificateOnError;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003298
3299 AlertDialog.Builder alertDialogBuilder =
3300 new AlertDialog.Builder(this)
3301 .setTitle(R.string.page_info).setIcon(android.R.drawable.ic_dialog_info)
3302 .setView(pageInfoView)
3303 .setPositiveButton(
3304 R.string.ok,
3305 new DialogInterface.OnClickListener() {
3306 public void onClick(DialogInterface dialog,
3307 int whichButton) {
3308 mPageInfoDialog = null;
3309 mPageInfoView = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003310
3311 // if we came here from the SSL error dialog
3312 if (fromShowSSLCertificateOnError) {
3313 // go back to the SSL error dialog
3314 showSSLCertificateOnError(
3315 mSSLCertificateOnErrorView,
3316 mSSLCertificateOnErrorHandler,
3317 mSSLCertificateOnErrorError);
3318 }
3319 }
3320 })
3321 .setOnCancelListener(
3322 new DialogInterface.OnCancelListener() {
3323 public void onCancel(DialogInterface dialog) {
3324 mPageInfoDialog = null;
3325 mPageInfoView = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003326
3327 // if we came here from the SSL error dialog
3328 if (fromShowSSLCertificateOnError) {
3329 // go back to the SSL error dialog
3330 showSSLCertificateOnError(
3331 mSSLCertificateOnErrorView,
3332 mSSLCertificateOnErrorHandler,
3333 mSSLCertificateOnErrorError);
3334 }
3335 }
3336 });
3337
3338 // if we have a main top-level page SSL certificate set or a certificate
3339 // error
3340 if (fromShowSSLCertificateOnError ||
3341 (view != null && view.getCertificate() != null)) {
3342 // add a 'View Certificate' button
3343 alertDialogBuilder.setNeutralButton(
3344 R.string.view_certificate,
3345 new DialogInterface.OnClickListener() {
3346 public void onClick(DialogInterface dialog,
3347 int whichButton) {
3348 mPageInfoDialog = null;
3349 mPageInfoView = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003350
3351 // if we came here from the SSL error dialog
3352 if (fromShowSSLCertificateOnError) {
3353 // go back to the SSL error dialog
3354 showSSLCertificateOnError(
3355 mSSLCertificateOnErrorView,
3356 mSSLCertificateOnErrorHandler,
3357 mSSLCertificateOnErrorError);
3358 } else {
3359 // otherwise, display the top-most certificate from
3360 // the chain
3361 if (view.getCertificate() != null) {
3362 showSSLCertificate(tab);
3363 }
3364 }
3365 }
3366 });
3367 }
3368
3369 mPageInfoDialog = alertDialogBuilder.show();
3370 }
3371
3372 /**
3373 * Displays the main top-level page SSL certificate dialog
3374 * (accessible from the Page-Info dialog).
3375 * @param tab The tab to show certificate for.
3376 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003377 private void showSSLCertificate(final Tab tab) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003378 final View certificateView =
3379 inflateCertificateView(tab.getWebView().getCertificate());
3380 if (certificateView == null) {
3381 return;
3382 }
3383
3384 LayoutInflater factory = LayoutInflater.from(this);
3385
3386 final LinearLayout placeholder =
3387 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3388
3389 LinearLayout ll = (LinearLayout) factory.inflate(
3390 R.layout.ssl_success, placeholder);
3391 ((TextView)ll.findViewById(R.id.success))
3392 .setText(R.string.ssl_certificate_is_valid);
3393
3394 mSSLCertificateView = tab;
3395 mSSLCertificateDialog =
3396 new AlertDialog.Builder(this)
3397 .setTitle(R.string.ssl_certificate).setIcon(
3398 R.drawable.ic_dialog_browser_certificate_secure)
3399 .setView(certificateView)
3400 .setPositiveButton(R.string.ok,
3401 new DialogInterface.OnClickListener() {
3402 public void onClick(DialogInterface dialog,
3403 int whichButton) {
3404 mSSLCertificateDialog = null;
3405 mSSLCertificateView = null;
3406
3407 showPageInfo(tab, false);
3408 }
3409 })
3410 .setOnCancelListener(
3411 new DialogInterface.OnCancelListener() {
3412 public void onCancel(DialogInterface dialog) {
3413 mSSLCertificateDialog = null;
3414 mSSLCertificateView = null;
3415
3416 showPageInfo(tab, false);
3417 }
3418 })
3419 .show();
3420 }
3421
3422 /**
3423 * Displays the SSL error certificate dialog.
3424 * @param view The target web-view.
3425 * @param handler The SSL error handler responsible for cancelling the
3426 * connection that resulted in an SSL error or proceeding per user request.
3427 * @param error The SSL error object.
3428 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003429 void showSSLCertificateOnError(
The Android Open Source Project0c908882009-03-03 19:32:16 -08003430 final WebView view, final SslErrorHandler handler, final SslError error) {
3431
3432 final View certificateView =
3433 inflateCertificateView(error.getCertificate());
3434 if (certificateView == null) {
3435 return;
3436 }
3437
3438 LayoutInflater factory = LayoutInflater.from(this);
3439
3440 final LinearLayout placeholder =
3441 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3442
3443 if (error.hasError(SslError.SSL_UNTRUSTED)) {
3444 LinearLayout ll = (LinearLayout)factory
3445 .inflate(R.layout.ssl_warning, placeholder);
3446 ((TextView)ll.findViewById(R.id.warning))
3447 .setText(R.string.ssl_untrusted);
3448 }
3449
3450 if (error.hasError(SslError.SSL_IDMISMATCH)) {
3451 LinearLayout ll = (LinearLayout)factory
3452 .inflate(R.layout.ssl_warning, placeholder);
3453 ((TextView)ll.findViewById(R.id.warning))
3454 .setText(R.string.ssl_mismatch);
3455 }
3456
3457 if (error.hasError(SslError.SSL_EXPIRED)) {
3458 LinearLayout ll = (LinearLayout)factory
3459 .inflate(R.layout.ssl_warning, placeholder);
3460 ((TextView)ll.findViewById(R.id.warning))
3461 .setText(R.string.ssl_expired);
3462 }
3463
3464 if (error.hasError(SslError.SSL_NOTYETVALID)) {
3465 LinearLayout ll = (LinearLayout)factory
3466 .inflate(R.layout.ssl_warning, placeholder);
3467 ((TextView)ll.findViewById(R.id.warning))
3468 .setText(R.string.ssl_not_yet_valid);
3469 }
3470
3471 mSSLCertificateOnErrorHandler = handler;
3472 mSSLCertificateOnErrorView = view;
3473 mSSLCertificateOnErrorError = error;
3474 mSSLCertificateOnErrorDialog =
3475 new AlertDialog.Builder(this)
3476 .setTitle(R.string.ssl_certificate).setIcon(
3477 R.drawable.ic_dialog_browser_certificate_partially_secure)
3478 .setView(certificateView)
3479 .setPositiveButton(R.string.ok,
3480 new DialogInterface.OnClickListener() {
3481 public void onClick(DialogInterface dialog,
3482 int whichButton) {
3483 mSSLCertificateOnErrorDialog = null;
3484 mSSLCertificateOnErrorView = null;
3485 mSSLCertificateOnErrorHandler = null;
3486 mSSLCertificateOnErrorError = null;
3487
Grace Kloba22ac16e2009-10-07 18:00:23 -07003488 view.getWebViewClient().onReceivedSslError(
3489 view, handler, error);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003490 }
3491 })
3492 .setNeutralButton(R.string.page_info_view,
3493 new DialogInterface.OnClickListener() {
3494 public void onClick(DialogInterface dialog,
3495 int whichButton) {
3496 mSSLCertificateOnErrorDialog = null;
3497
3498 // do not clear the dialog state: we will
3499 // need to show the dialog again once the
3500 // user is done exploring the page-info details
3501
3502 showPageInfo(mTabControl.getTabFromView(view),
3503 true);
3504 }
3505 })
3506 .setOnCancelListener(
3507 new DialogInterface.OnCancelListener() {
3508 public void onCancel(DialogInterface dialog) {
3509 mSSLCertificateOnErrorDialog = null;
3510 mSSLCertificateOnErrorView = null;
3511 mSSLCertificateOnErrorHandler = null;
3512 mSSLCertificateOnErrorError = null;
3513
Grace Kloba22ac16e2009-10-07 18:00:23 -07003514 view.getWebViewClient().onReceivedSslError(
3515 view, handler, error);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003516 }
3517 })
3518 .show();
3519 }
3520
3521 /**
3522 * Inflates the SSL certificate view (helper method).
3523 * @param certificate The SSL certificate.
3524 * @return The resultant certificate view with issued-to, issued-by,
3525 * issued-on, expires-on, and possibly other fields set.
3526 * If the input certificate is null, returns null.
3527 */
3528 private View inflateCertificateView(SslCertificate certificate) {
3529 if (certificate == null) {
3530 return null;
3531 }
3532
3533 LayoutInflater factory = LayoutInflater.from(this);
3534
3535 View certificateView = factory.inflate(
3536 R.layout.ssl_certificate, null);
3537
3538 // issued to:
3539 SslCertificate.DName issuedTo = certificate.getIssuedTo();
3540 if (issuedTo != null) {
3541 ((TextView) certificateView.findViewById(R.id.to_common))
3542 .setText(issuedTo.getCName());
3543 ((TextView) certificateView.findViewById(R.id.to_org))
3544 .setText(issuedTo.getOName());
3545 ((TextView) certificateView.findViewById(R.id.to_org_unit))
3546 .setText(issuedTo.getUName());
3547 }
3548
3549 // issued by:
3550 SslCertificate.DName issuedBy = certificate.getIssuedBy();
3551 if (issuedBy != null) {
3552 ((TextView) certificateView.findViewById(R.id.by_common))
3553 .setText(issuedBy.getCName());
3554 ((TextView) certificateView.findViewById(R.id.by_org))
3555 .setText(issuedBy.getOName());
3556 ((TextView) certificateView.findViewById(R.id.by_org_unit))
3557 .setText(issuedBy.getUName());
3558 }
3559
3560 // issued on:
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003561 String issuedOn = formatCertificateDate(
3562 certificate.getValidNotBeforeDate());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003563 ((TextView) certificateView.findViewById(R.id.issued_on))
3564 .setText(issuedOn);
3565
3566 // expires on:
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003567 String expiresOn = formatCertificateDate(
3568 certificate.getValidNotAfterDate());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003569 ((TextView) certificateView.findViewById(R.id.expires_on))
3570 .setText(expiresOn);
3571
3572 return certificateView;
3573 }
3574
3575 /**
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003576 * Formats the certificate date to a properly localized date string.
The Android Open Source Project0c908882009-03-03 19:32:16 -08003577 * @return Properly localized version of the certificate date string and
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003578 * the "" if it fails to localize.
The Android Open Source Project0c908882009-03-03 19:32:16 -08003579 */
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003580 private String formatCertificateDate(Date certificateDate) {
3581 if (certificateDate == null) {
3582 return "";
The Android Open Source Project0c908882009-03-03 19:32:16 -08003583 }
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003584 String formattedDate = DateFormat.getDateFormat(this).format(certificateDate);
3585 if (formattedDate == null) {
3586 return "";
3587 }
3588 return formattedDate;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003589 }
3590
3591 /**
3592 * Displays an http-authentication dialog.
3593 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003594 void showHttpAuthentication(final HttpAuthHandler handler,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003595 final String host, final String realm, final String title,
3596 final String name, final String password, int focusId) {
3597 LayoutInflater factory = LayoutInflater.from(this);
3598 final View v = factory
3599 .inflate(R.layout.http_authentication, null);
3600 if (name != null) {
3601 ((EditText) v.findViewById(R.id.username_edit)).setText(name);
3602 }
3603 if (password != null) {
3604 ((EditText) v.findViewById(R.id.password_edit)).setText(password);
3605 }
3606
3607 String titleText = title;
3608 if (titleText == null) {
3609 titleText = getText(R.string.sign_in_to).toString().replace(
3610 "%s1", host).replace("%s2", realm);
3611 }
3612
3613 mHttpAuthHandler = handler;
3614 AlertDialog dialog = new AlertDialog.Builder(this)
3615 .setTitle(titleText)
3616 .setIcon(android.R.drawable.ic_dialog_alert)
3617 .setView(v)
3618 .setPositiveButton(R.string.action,
3619 new DialogInterface.OnClickListener() {
3620 public void onClick(DialogInterface dialog,
3621 int whichButton) {
3622 String nm = ((EditText) v
3623 .findViewById(R.id.username_edit))
3624 .getText().toString();
3625 String pw = ((EditText) v
3626 .findViewById(R.id.password_edit))
3627 .getText().toString();
3628 BrowserActivity.this.setHttpAuthUsernamePassword
3629 (host, realm, nm, pw);
3630 handler.proceed(nm, pw);
3631 mHttpAuthenticationDialog = null;
3632 mHttpAuthHandler = null;
3633 }})
3634 .setNegativeButton(R.string.cancel,
3635 new DialogInterface.OnClickListener() {
3636 public void onClick(DialogInterface dialog,
3637 int whichButton) {
3638 handler.cancel();
3639 BrowserActivity.this.resetTitleAndRevertLockIcon();
3640 mHttpAuthenticationDialog = null;
3641 mHttpAuthHandler = null;
3642 }})
3643 .setOnCancelListener(new DialogInterface.OnCancelListener() {
3644 public void onCancel(DialogInterface dialog) {
3645 handler.cancel();
3646 BrowserActivity.this.resetTitleAndRevertLockIcon();
3647 mHttpAuthenticationDialog = null;
3648 mHttpAuthHandler = null;
3649 }})
3650 .create();
3651 // Make the IME appear when the dialog is displayed if applicable.
3652 dialog.getWindow().setSoftInputMode(
3653 WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
3654 dialog.show();
3655 if (focusId != 0) {
3656 dialog.findViewById(focusId).requestFocus();
3657 } else {
3658 v.findViewById(R.id.username_edit).requestFocus();
3659 }
3660 mHttpAuthenticationDialog = dialog;
3661 }
3662
3663 public int getProgress() {
3664 WebView w = mTabControl.getCurrentWebView();
3665 if (w != null) {
3666 return w.getProgress();
3667 } else {
3668 return 100;
3669 }
3670 }
3671
3672 /**
3673 * Set HTTP authentication password.
3674 *
3675 * @param host The host for the password
3676 * @param realm The realm for the password
3677 * @param username The username for the password. If it is null, it means
3678 * password can't be saved.
3679 * @param password The password
3680 */
3681 public void setHttpAuthUsernamePassword(String host, String realm,
3682 String username,
3683 String password) {
Steve Block95a53b22010-03-25 17:24:58 +00003684 WebView w = getTopWindow();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003685 if (w != null) {
3686 w.setHttpAuthUsernamePassword(host, realm, username, password);
3687 }
3688 }
3689
3690 /**
3691 * connectivity manager says net has come or gone... inform the user
3692 * @param up true if net has come up, false if net has gone down
3693 */
3694 public void onNetworkToggle(boolean up) {
3695 if (up == mIsNetworkUp) {
3696 return;
3697 } else if (up) {
3698 mIsNetworkUp = true;
3699 if (mAlertDialog != null) {
3700 mAlertDialog.cancel();
3701 mAlertDialog = null;
3702 }
3703 } else {
3704 mIsNetworkUp = false;
Patrick Scotteb6ab2a2009-09-16 10:00:17 -04003705 if (mInLoad) {
3706 createAndShowNetworkDialog();
3707 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003708 }
3709 WebView w = mTabControl.getCurrentWebView();
3710 if (w != null) {
3711 w.setNetworkAvailable(up);
3712 }
3713 }
3714
Grace Kloba22ac16e2009-10-07 18:00:23 -07003715 boolean isNetworkUp() {
3716 return mIsNetworkUp;
3717 }
3718
Patrick Scotteb6ab2a2009-09-16 10:00:17 -04003719 // This method shows the network dialog alerting the user that the net is
3720 // down. It will only show the dialog if mAlertDialog is null.
3721 private void createAndShowNetworkDialog() {
3722 if (mAlertDialog == null) {
3723 mAlertDialog = new AlertDialog.Builder(this)
3724 .setTitle(R.string.loadSuspendedTitle)
3725 .setMessage(R.string.loadSuspended)
3726 .setPositiveButton(R.string.ok, null)
3727 .show();
3728 }
3729 }
3730
The Android Open Source Project0c908882009-03-03 19:32:16 -08003731 @Override
3732 protected void onActivityResult(int requestCode, int resultCode,
3733 Intent intent) {
Grace Klobabb394f32009-11-19 10:26:37 -08003734 if (getTopWindow() == null) return;
3735
The Android Open Source Project0c908882009-03-03 19:32:16 -08003736 switch (requestCode) {
3737 case COMBO_PAGE:
3738 if (resultCode == RESULT_OK && intent != null) {
3739 String data = intent.getAction();
3740 Bundle extras = intent.getExtras();
3741 if (extras != null && extras.getBoolean("new_window", false)) {
Leon Scroggins25d35472009-09-15 11:37:27 -04003742 openTab(data);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003743 } else {
Grace Kloba22ac16e2009-10-07 18:00:23 -07003744 final Tab currentTab =
The Android Open Source Project0c908882009-03-03 19:32:16 -08003745 mTabControl.getCurrentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04003746 dismissSubWindow(currentTab);
3747 if (data != null && data.length() != 0) {
Leon Scroggins92472e82010-02-17 16:32:28 -05003748 loadUrl(getTopWindow(), data);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003749 }
3750 }
3751 }
Leon Scrogginsfde97462010-01-11 13:06:21 -05003752 // Deliberately fall through to PREFERENCES_PAGE, since the
3753 // same extra may be attached to the COMBO_PAGE
3754 case PREFERENCES_PAGE:
3755 if (resultCode == RESULT_OK && intent != null) {
3756 String action = intent.getStringExtra(Intent.EXTRA_TEXT);
3757 if (BrowserSettings.PREF_CLEAR_HISTORY.equals(action)) {
3758 mTabControl.removeParentChildRelationShips();
3759 }
3760 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003761 break;
Leon Scroggins8d5fa432009-10-02 15:55:59 -04003762 // Choose a file from the file picker.
3763 case FILE_SELECTED:
3764 if (null == mUploadMessage) break;
3765 Uri result = intent == null || resultCode != RESULT_OK ? null
3766 : intent.getData();
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003767
3768 // As we ask the camera to save the result of the user taking
3769 // a picture, the camera application does not return anything other
3770 // than RESULT_OK. So we need to check whether the file we expected
3771 // was written to disk in the in the case that we
3772 // did not get an intent returned but did get a RESULT_OK. If it was,
3773 // we assume that this result has came back from the camera.
3774 if (result == null && intent == null && resultCode == RESULT_OK) {
3775 File cameraFile = new File(mCameraFilePath);
3776 if (cameraFile.exists()) {
3777 result = Uri.fromFile(cameraFile);
Ben Murdoch07d34732010-05-27 18:34:46 +01003778 // Broadcast to the media scanner that we have a new photo
3779 // so it will be added into the gallery for the user.
3780 sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, result));
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003781 }
3782 }
Leon Scroggins8d5fa432009-10-02 15:55:59 -04003783 mUploadMessage.onReceiveValue(result);
3784 mUploadMessage = null;
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01003785 mCameraFilePath = null;
Leon Scroggins8d5fa432009-10-02 15:55:59 -04003786 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003787 default:
3788 break;
3789 }
Leon Scroggins30444232009-09-04 18:36:20 -04003790 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003791 }
3792
3793 /*
3794 * This method is called as a result of the user selecting the options
Leon Scrogginsf08809b2010-01-21 09:27:46 -05003795 * menu to see the download window. It shows the download window on top of
3796 * the current window.
The Android Open Source Project0c908882009-03-03 19:32:16 -08003797 */
Leon Scrogginsf08809b2010-01-21 09:27:46 -05003798 private void viewDownloads(Uri downloadRecord) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003799 Intent intent = new Intent(this,
3800 BrowserDownloadPage.class);
3801 intent.setData(downloadRecord);
Grace Kloba22ac16e2009-10-07 18:00:23 -07003802 startActivityForResult(intent, BrowserActivity.DOWNLOAD_PAGE);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003803
3804 }
3805
Ben Murdocheecb4e62010-07-06 16:30:38 +01003806 /* package*/ void promptAddOrInstallBookmark() {
3807 final Tab current = mTabControl.getCurrentTab();
3808 Resources resources = getResources();
3809 CharSequence[] choices = {
3810 resources.getString(R.string.save_to_bookmarks),
3811 resources.getString(R.string.create_shortcut_bookmark)
3812 };
3813
3814 AlertDialog.Builder builder = new AlertDialog.Builder(this);
3815 builder.setTitle(R.string.add_new_bookmark);
3816 builder.setItems(choices, new DialogInterface.OnClickListener() {
3817 public void onClick(DialogInterface dialog, int item) {
3818 if (item == 0) {
3819 bookmarkCurrentPage();
3820 } else if (item == 1) {
3821 current.populatePickerData();
3822 String touchIconUrl = mTabControl.getCurrentWebView().getTouchIconUrl();
3823 if (touchIconUrl != null) {
3824 // Download the touch icon for this site then save it to the
3825 // homescreen.
3826 Bundle b = new Bundle();
3827 b.putString("url", current.getUrl());
3828 b.putString("title", current.getTitle());
3829 b.putParcelable("favicon", current.getFavicon());
3830 Message msg = mHandler.obtainMessage(TOUCH_ICON_DOWNLOADED);
3831 msg.setData(b);
Ben Murdochccb5de02010-07-19 18:38:17 +01003832 new DownloadTouchIcon(BrowserActivity.this, msg,
Ben Murdocheecb4e62010-07-06 16:30:38 +01003833 mTabControl.getCurrentWebView().getSettings()
3834 .getUserAgentString()).execute(touchIconUrl);
3835 } else {
3836 // add to homescreen, can do it immediately as there is no touch
3837 // icon.
3838 showSaveToHomescreenDialog(current.getUrl(), current.getTitle(),
3839 null, current.getFavicon());
3840 }
3841 }
3842 }
3843 });
3844 builder.create().show();
3845 }
3846
Leon Scroggins160a7e72009-08-14 18:28:01 -04003847 /**
3848 * Open the Go page.
3849 * @param startWithHistory If true, open starting on the history tab.
3850 * Otherwise, start with the bookmarks tab.
Leon Scroggins160a7e72009-08-14 18:28:01 -04003851 */
Leon Scroggins30444232009-09-04 18:36:20 -04003852 /* package */ void bookmarksOrHistoryPicker(boolean startWithHistory) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003853 WebView current = mTabControl.getCurrentWebView();
3854 if (current == null) {
3855 return;
3856 }
3857 Intent intent = new Intent(this,
3858 CombinedBookmarkHistoryActivity.class);
3859 String title = current.getTitle();
3860 String url = current.getUrl();
Ben Murdoch87cc65d2010-06-29 20:34:10 +01003861 Bitmap thumbnail = createScreenshot(current, getDesiredThumbnailWidth(this),
3862 getDesiredThumbnailHeight(this));
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01003863
The Android Open Source Project0c908882009-03-03 19:32:16 -08003864 // Just in case the user opens bookmarks before a page finishes loading
3865 // so the current history item, and therefore the page, is null.
3866 if (null == url) {
3867 url = mLastEnteredUrl;
3868 // This can happen.
3869 if (null == url) {
3870 url = mSettings.getHomePage();
3871 }
3872 }
3873 // In case the web page has not yet received its associated title.
3874 if (title == null) {
3875 title = url;
3876 }
3877 intent.putExtra("title", title);
3878 intent.putExtra("url", url);
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01003879 intent.putExtra("thumbnail", thumbnail);
Leon Scroggins30444232009-09-04 18:36:20 -04003880 // Disable opening in a new window if we have maxed out the windows
Grace Kloba22ac16e2009-10-07 18:00:23 -07003881 intent.putExtra("disable_new_window", !mTabControl.canCreateNewTab());
Patrick Scott3918d442009-08-04 13:22:29 -04003882 intent.putExtra("touch_icon_url", current.getTouchIconUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003883 if (startWithHistory) {
3884 intent.putExtra(CombinedBookmarkHistoryActivity.STARTING_TAB,
3885 CombinedBookmarkHistoryActivity.HISTORY_TAB);
3886 }
3887 startActivityForResult(intent, COMBO_PAGE);
3888 }
3889
Ben Murdocheecb4e62010-07-06 16:30:38 +01003890 private void showSaveToHomescreenDialog(String url, String title, Bitmap touchIcon,
3891 Bitmap favicon) {
3892 Intent intent = new Intent(this, SaveToHomescreenDialog.class);
3893
3894 // Just in case the user tries to save before a page finishes loading
3895 // so the current history item, and therefore the page, is null.
3896 if (null == url) {
3897 url = mLastEnteredUrl;
3898 // This can happen.
3899 if (null == url) {
3900 url = mSettings.getHomePage();
3901 }
3902 }
3903
3904 // In case the web page has not yet received its associated title.
3905 if (title == null) {
3906 title = url;
3907 }
3908
3909 intent.putExtra("title", title);
3910 intent.putExtra("url", url);
3911 intent.putExtra("favicon", favicon);
3912 intent.putExtra("touchIcon", touchIcon);
3913 startActivity(intent);
3914 }
3915
3916
The Android Open Source Project0c908882009-03-03 19:32:16 -08003917 // Called when loading from context menu or LOAD_URL message
Leon Scroggins92472e82010-02-17 16:32:28 -05003918 private void loadUrlFromContext(WebView view, String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003919 // In case the user enters nothing.
3920 if (url != null && url.length() != 0 && view != null) {
3921 url = smartUrlFilter(url);
Grace Kloba22ac16e2009-10-07 18:00:23 -07003922 if (!view.getWebViewClient().shouldOverrideUrlLoading(view, url)) {
Leon Scroggins92472e82010-02-17 16:32:28 -05003923 loadUrl(view, url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003924 }
3925 }
3926 }
3927
Leon Scroggins92472e82010-02-17 16:32:28 -05003928 /**
3929 * Load the URL into the given WebView and update the title bar
3930 * to reflect the new load. Call this instead of WebView.loadUrl
3931 * directly.
3932 * @param view The WebView used to load url.
3933 * @param url The URL to load.
3934 */
3935 private void loadUrl(WebView view, String url) {
3936 updateTitleBarForNewLoad(view, url);
3937 view.loadUrl(url);
3938 }
3939
3940 /**
3941 * Load UrlData into a Tab and update the title bar to reflect the new
3942 * load. Call this instead of UrlData.loadIn directly.
3943 * @param t The Tab used to load.
3944 * @param data The UrlData being loaded.
3945 */
3946 private void loadUrlDataIn(Tab t, UrlData data) {
3947 updateTitleBarForNewLoad(t.getWebView(), data.mUrl);
3948 data.loadIn(t);
3949 }
3950
3951 /**
3952 * If the WebView is the top window, update the title bar to reflect
3953 * loading the new URL. i.e. set its text, clear the favicon (which
3954 * will be set once the page begins loading), and set the progress to
3955 * INITIAL_PROGRESS to show that the page has begun to load. Called
3956 * by loadUrl and loadUrlDataIn.
3957 * @param view The WebView that is starting a load.
3958 * @param url The URL that is being loaded.
3959 */
3960 private void updateTitleBarForNewLoad(WebView view, String url) {
3961 if (view == getTopWindow()) {
3962 setUrlTitle(url, null);
3963 setFavicon(null);
3964 onProgressChanged(view, INITIAL_PROGRESS);
3965 }
3966 }
3967
The Android Open Source Project0c908882009-03-03 19:32:16 -08003968 private String smartUrlFilter(Uri inUri) {
3969 if (inUri != null) {
3970 return smartUrlFilter(inUri.toString());
3971 }
3972 return null;
3973 }
3974
Feng Qianb34f87a2009-03-24 21:27:26 -07003975 protected static final Pattern ACCEPTED_URI_SCHEMA = Pattern.compile(
The Android Open Source Project0c908882009-03-03 19:32:16 -08003976 "(?i)" + // switch on case insensitive matching
3977 "(" + // begin group for schema
3978 "(?:http|https|file):\\/\\/" +
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003979 "|(?:inline|data|about|content|javascript):" +
The Android Open Source Project0c908882009-03-03 19:32:16 -08003980 ")" +
3981 "(.*)" );
3982
3983 /**
3984 * Attempts to determine whether user input is a URL or search
3985 * terms. Anything with a space is passed to search.
3986 *
3987 * Converts to lowercase any mistakenly uppercased schema (i.e.,
3988 * "Http://" converts to "http://"
3989 *
3990 * @return Original or modified URL
3991 *
3992 */
3993 String smartUrlFilter(String url) {
3994
3995 String inUrl = url.trim();
3996 boolean hasSpace = inUrl.indexOf(' ') != -1;
3997
3998 Matcher matcher = ACCEPTED_URI_SCHEMA.matcher(inUrl);
3999 if (matcher.matches()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08004000 // force scheme to lowercase
4001 String scheme = matcher.group(1);
4002 String lcScheme = scheme.toLowerCase();
4003 if (!lcScheme.equals(scheme)) {
Mitsuru Oshima123ecfb2009-05-18 19:11:14 -07004004 inUrl = lcScheme + matcher.group(2);
4005 }
4006 if (hasSpace) {
4007 inUrl = inUrl.replace(" ", "%20");
The Android Open Source Project0c908882009-03-03 19:32:16 -08004008 }
4009 return inUrl;
4010 }
4011 if (hasSpace) {
Satish Sampath565505b2009-05-29 15:37:27 +01004012 // FIXME: Is this the correct place to add to searches?
4013 // what if someone else calls this function?
4014 int shortcut = parseUrlShortcut(inUrl);
4015 if (shortcut != SHORTCUT_INVALID) {
4016 Browser.addSearchUrl(mResolver, inUrl);
4017 String query = inUrl.substring(2);
4018 switch (shortcut) {
4019 case SHORTCUT_GOOGLE_SEARCH:
Grace Kloba47fdfdb2009-06-30 11:15:34 -07004020 return URLUtil.composeSearchUrl(query, QuickSearch_G, QUERY_PLACE_HOLDER);
Satish Sampath565505b2009-05-29 15:37:27 +01004021 case SHORTCUT_WIKIPEDIA_SEARCH:
4022 return URLUtil.composeSearchUrl(query, QuickSearch_W, QUERY_PLACE_HOLDER);
4023 case SHORTCUT_DICTIONARY_SEARCH:
4024 return URLUtil.composeSearchUrl(query, QuickSearch_D, QUERY_PLACE_HOLDER);
4025 case SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH:
The Android Open Source Project0c908882009-03-03 19:32:16 -08004026 // FIXME: we need location in this case
Satish Sampath565505b2009-05-29 15:37:27 +01004027 return URLUtil.composeSearchUrl(query, QuickSearch_L, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004028 }
4029 }
4030 } else {
Dan Egnor5ee906c2009-11-18 12:11:49 -08004031 if (Patterns.WEB_URL.matcher(inUrl).matches()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08004032 return URLUtil.guessUrl(inUrl);
4033 }
4034 }
4035
4036 Browser.addSearchUrl(mResolver, inUrl);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07004037 return URLUtil.composeSearchUrl(inUrl, QuickSearch_G, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004038 }
4039
Ben Murdochbff2d602009-07-01 20:19:05 +01004040 /* package */ void setShouldShowErrorConsole(boolean flag) {
4041 if (flag == mShouldShowErrorConsole) {
4042 // Nothing to do.
4043 return;
4044 }
4045
4046 mShouldShowErrorConsole = flag;
4047
Grace Kloba22ac16e2009-10-07 18:00:23 -07004048 ErrorConsoleView errorConsole = mTabControl.getCurrentTab()
4049 .getErrorConsole(true);
Ben Murdochbff2d602009-07-01 20:19:05 +01004050
4051 if (flag) {
4052 // Setting the show state of the console will cause it's the layout to be inflated.
4053 if (errorConsole.numberOfErrors() > 0) {
4054 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
4055 } else {
4056 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
4057 }
4058
4059 // Now we can add it to the main view.
4060 mErrorConsoleContainer.addView(errorConsole,
Romain Guy15b8ec62010-01-08 15:06:43 -08004061 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
Ben Murdochbff2d602009-07-01 20:19:05 +01004062 ViewGroup.LayoutParams.WRAP_CONTENT));
4063 } else {
4064 mErrorConsoleContainer.removeView(errorConsole);
4065 }
4066
4067 }
4068
Grace Kloba22ac16e2009-10-07 18:00:23 -07004069 boolean shouldShowErrorConsole() {
4070 return mShouldShowErrorConsole;
4071 }
4072
Andrei Popescu163ab742009-10-20 17:58:23 +01004073 private void setStatusBarVisibility(boolean visible) {
4074 int flag = visible ? 0 : WindowManager.LayoutParams.FLAG_FULLSCREEN;
4075 getWindow().setFlags(flag, WindowManager.LayoutParams.FLAG_FULLSCREEN);
4076 }
4077
Andrei Popescu56199cc2010-01-12 22:39:16 +00004078
4079 private void sendNetworkType(String type, String subtype) {
4080 WebView w = mTabControl.getCurrentWebView();
4081 if (w != null) {
4082 w.setNetworkType(type, subtype);
4083 }
4084 }
4085
Andrei Popescu30995e72010-02-09 16:59:58 +00004086 private void packageChanged(String packageName, boolean wasAdded) {
4087 WebView w = mTabControl.getCurrentWebView();
4088 if (w == null) {
4089 return;
4090 }
4091
4092 if (wasAdded) {
4093 w.addPackageName(packageName);
4094 } else {
4095 w.removePackageName(packageName);
4096 }
4097 }
4098
4099 private void addPackageNames(Set<String> packageNames) {
4100 WebView w = mTabControl.getCurrentWebView();
4101 if (w == null) {
4102 return;
4103 }
4104
4105 w.addPackageNames(packageNames);
4106 }
4107
4108 private void getInstalledPackages() {
4109 AsyncTask<Void, Void, Set<String> > task =
4110 new AsyncTask<Void, Void, Set<String> >() {
Michael Kolbe0a36662010-06-29 10:37:12 -07004111 @Override
Andrei Popescu30995e72010-02-09 16:59:58 +00004112 protected Set<String> doInBackground(Void... unused) {
4113 Set<String> installedPackages = new HashSet<String>();
4114 PackageManager pm = BrowserActivity.this.getPackageManager();
4115 if (pm != null) {
4116 List<PackageInfo> packages = pm.getInstalledPackages(0);
4117 for (PackageInfo p : packages) {
4118 if (BrowserActivity.this.sGoogleApps.contains(p.packageName)) {
4119 installedPackages.add(p.packageName);
4120 }
4121 }
4122 }
4123
4124 return installedPackages;
4125 }
4126
4127 // Executes on the UI thread
Michael Kolbe0a36662010-06-29 10:37:12 -07004128 @Override
Andrei Popescu30995e72010-02-09 16:59:58 +00004129 protected void onPostExecute(Set<String> installedPackages) {
4130 addPackageNames(installedPackages);
4131 }
4132 };
4133 task.execute();
4134 }
4135
Grace Klobaeb6eef42009-09-15 17:56:32 -07004136 final static int LOCK_ICON_UNSECURE = 0;
4137 final static int LOCK_ICON_SECURE = 1;
4138 final static int LOCK_ICON_MIXED = 2;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004139
The Android Open Source Project0c908882009-03-03 19:32:16 -08004140 private BrowserSettings mSettings;
4141 private TabControl mTabControl;
4142 private ContentResolver mResolver;
4143 private FrameLayout mContentView;
Andrei Popescuadc008d2009-06-26 14:11:30 +01004144 private View mCustomView;
4145 private FrameLayout mCustomViewContainer;
Andrei Popescuc9b55562009-07-07 10:51:15 +01004146 private WebChromeClient.CustomViewCallback mCustomViewCallback;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004147
4148 // FIXME, temp address onPrepareMenu performance problem. When we move everything out of
4149 // view, we should rewrite this.
4150 private int mCurrentMenuState = 0;
4151 private int mMenuState = R.id.MAIN_MENU;
Andrei Popescuadc008d2009-06-26 14:11:30 +01004152 private int mOldMenuState = EMPTY_MENU;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004153 private static final int EMPTY_MENU = -1;
4154 private Menu mMenu;
4155
4156 private FindDialog mFindDialog;
Cary Clark01cfcdd2010-06-04 16:36:45 -04004157 private SelectDialog mSelectDialog;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004158 // Used to prevent chording to result in firing two shortcuts immediately
4159 // one after another. Fixes bug 1211714.
4160 boolean mCanChord;
4161
4162 private boolean mInLoad;
4163 private boolean mIsNetworkUp;
Ben Murdochb7cc8b42009-09-28 10:59:09 +01004164 private boolean mDidStopLoad;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004165
Cary Clark1f10cbf2010-03-22 11:45:23 -04004166 /* package */ boolean mActivityInPause = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004167
4168 private boolean mMenuIsDown;
4169
The Android Open Source Project0c908882009-03-03 19:32:16 -08004170 private static boolean mInTrace;
4171
4172 // Performance probe
4173 private static final int[] SYSTEM_CPU_FORMAT = new int[] {
4174 Process.PROC_SPACE_TERM | Process.PROC_COMBINE,
4175 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 1: user time
4176 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 2: nice time
4177 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 3: sys time
4178 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 4: idle time
4179 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 5: iowait time
4180 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 6: irq time
4181 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG // 7: softirq time
4182 };
4183
4184 private long mStart;
4185 private long mProcessStart;
4186 private long mUserStart;
4187 private long mSystemStart;
4188 private long mIdleStart;
4189 private long mIrqStart;
4190
4191 private long mUiStart;
4192
4193 private Drawable mMixLockIcon;
4194 private Drawable mSecLockIcon;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004195
4196 /* hold a ref so we can auto-cancel if necessary */
4197 private AlertDialog mAlertDialog;
4198
The Android Open Source Project0c908882009-03-03 19:32:16 -08004199 // The up-to-date URL and title (these can be different from those stored
4200 // in WebView, since it takes some time for the information in WebView to
4201 // get updated)
4202 private String mUrl;
4203 private String mTitle;
4204
4205 // As PageInfo has different style for landscape / portrait, we have
4206 // to re-open it when configuration changed
4207 private AlertDialog mPageInfoDialog;
Grace Kloba22ac16e2009-10-07 18:00:23 -07004208 private Tab mPageInfoView;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004209 // If the Page-Info dialog is launched from the SSL-certificate-on-error
4210 // dialog, we should not just dismiss it, but should get back to the
4211 // SSL-certificate-on-error dialog. This flag is used to store this state
Leon Scrogginsc7b92f82010-01-11 18:17:31 -05004212 private boolean mPageInfoFromShowSSLCertificateOnError;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004213
4214 // as SSLCertificateOnError has different style for landscape / portrait,
4215 // we have to re-open it when configuration changed
4216 private AlertDialog mSSLCertificateOnErrorDialog;
4217 private WebView mSSLCertificateOnErrorView;
4218 private SslErrorHandler mSSLCertificateOnErrorHandler;
4219 private SslError mSSLCertificateOnErrorError;
4220
4221 // as SSLCertificate has different style for landscape / portrait, we
4222 // have to re-open it when configuration changed
4223 private AlertDialog mSSLCertificateDialog;
Grace Kloba22ac16e2009-10-07 18:00:23 -07004224 private Tab mSSLCertificateView;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004225
4226 // as HttpAuthentication has different style for landscape / portrait, we
4227 // have to re-open it when configuration changed
4228 private AlertDialog mHttpAuthenticationDialog;
4229 private HttpAuthHandler mHttpAuthHandler;
4230
4231 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_PARAMS =
4232 new FrameLayout.LayoutParams(
Romain Guy15b8ec62010-01-08 15:06:43 -08004233 ViewGroup.LayoutParams.MATCH_PARENT,
4234 ViewGroup.LayoutParams.MATCH_PARENT);
Andrei Popescuadc008d2009-06-26 14:11:30 +01004235 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_GRAVITY_CENTER =
4236 new FrameLayout.LayoutParams(
Romain Guy15b8ec62010-01-08 15:06:43 -08004237 ViewGroup.LayoutParams.MATCH_PARENT,
4238 ViewGroup.LayoutParams.MATCH_PARENT,
Andrei Popescuadc008d2009-06-26 14:11:30 +01004239 Gravity.CENTER);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07004240 // Google search
4241 final static String QuickSearch_G = "http://www.google.com/m?q=%s";
The Android Open Source Project0c908882009-03-03 19:32:16 -08004242 // Wikipedia search
4243 final static String QuickSearch_W = "http://en.wikipedia.org/w/index.php?search=%s&go=Go";
4244 // Dictionary search
4245 final static String QuickSearch_D = "http://dictionary.reference.com/search?q=%s";
4246 // Google Mobile Local search
4247 final static String QuickSearch_L = "http://www.google.com/m/search?site=local&q=%s&near=mountain+view";
4248
4249 final static String QUERY_PLACE_HOLDER = "%s";
4250
4251 // "source" parameter for Google search through search key
4252 final static String GOOGLE_SEARCH_SOURCE_SEARCHKEY = "browser-key";
4253 // "source" parameter for Google search through goto menu
4254 final static String GOOGLE_SEARCH_SOURCE_GOTO = "browser-goto";
4255 // "source" parameter for Google search through simplily type
4256 final static String GOOGLE_SEARCH_SOURCE_TYPE = "browser-type";
4257 // "source" parameter for Google search suggested by the browser
4258 final static String GOOGLE_SEARCH_SOURCE_SUGGEST = "browser-suggest";
4259 // "source" parameter for Google search from unknown source
4260 final static String GOOGLE_SEARCH_SOURCE_UNKNOWN = "unknown";
4261
4262 private final static String LOGTAG = "browser";
4263
The Android Open Source Project0c908882009-03-03 19:32:16 -08004264 private String mLastEnteredUrl;
4265
4266 private PowerManager.WakeLock mWakeLock;
4267 private final static int WAKELOCK_TIMEOUT = 5 * 60 * 1000; // 5 minutes
4268
4269 private Toast mStopToast;
4270
Leon Scroggins571b3762010-05-26 10:25:01 -04004271 private TitleBarBase mTitleBar;
Leon Scroggins81db3662009-06-04 17:45:11 -04004272
Ben Murdochbff2d602009-07-01 20:19:05 +01004273 private LinearLayout mErrorConsoleContainer = null;
4274 private boolean mShouldShowErrorConsole = false;
4275
The Android Open Source Project0c908882009-03-03 19:32:16 -08004276 // As the ids are dynamically created, we can't guarantee that they will
4277 // be in sequence, so this static array maps ids to a window number.
4278 final static private int[] WINDOW_SHORTCUT_ID_ARRAY =
4279 { R.id.window_one_menu_id, R.id.window_two_menu_id, R.id.window_three_menu_id,
4280 R.id.window_four_menu_id, R.id.window_five_menu_id, R.id.window_six_menu_id,
4281 R.id.window_seven_menu_id, R.id.window_eight_menu_id };
4282
4283 // monitor platform changes
4284 private IntentFilter mNetworkStateChangedFilter;
4285 private BroadcastReceiver mNetworkStateIntentReceiver;
4286
Grace Klobab4da0ad2009-05-14 14:45:40 -07004287 private BroadcastReceiver mPackageInstallationReceiver;
4288
Bjorn Bringerta7611812010-03-24 11:12:02 +00004289 private SystemAllowGeolocationOrigins mSystemAllowGeolocationOrigins;
4290
The Android Open Source Project0c908882009-03-03 19:32:16 -08004291 // activity requestCode
Nicolas Roard78a98e42009-05-11 13:34:17 +01004292 final static int COMBO_PAGE = 1;
4293 final static int DOWNLOAD_PAGE = 2;
4294 final static int PREFERENCES_PAGE = 3;
Leon Scroggins8d5fa432009-10-02 15:55:59 -04004295 final static int FILE_SELECTED = 4;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004296
Andrei Popescu540035d2009-09-18 18:59:20 +01004297 // the default <video> poster
4298 private Bitmap mDefaultVideoPoster;
4299 // the video progress view
4300 private View mVideoProgressView;
4301
Andrei Popescu30995e72010-02-09 16:59:58 +00004302 // The Google packages we monitor for the navigator.isApplicationInstalled()
4303 // API. Add as needed.
4304 private static Set<String> sGoogleApps;
4305 static {
4306 sGoogleApps = new HashSet<String>();
4307 sGoogleApps.add("com.google.android.youtube");
4308 }
4309
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004310 /**
4311 * A UrlData class to abstract how the content will be set to WebView.
4312 * This base class uses loadUrl to show the content.
4313 */
Leon Scroggins6eac63e2010-03-15 18:19:14 -04004314 /* package */ static class UrlData {
Grace Kloba068e48b2010-01-26 18:11:27 -08004315 final String mUrl;
4316 final Map<String, String> mHeaders;
Leon Scroggins58d56c62010-01-28 15:12:40 -05004317 final Intent mVoiceIntent;
Grace Kloba60e095c2009-06-16 11:50:55 -07004318
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004319 UrlData(String url) {
4320 this.mUrl = url;
Grace Kloba068e48b2010-01-26 18:11:27 -08004321 this.mHeaders = null;
Leon Scroggins58d56c62010-01-28 15:12:40 -05004322 this.mVoiceIntent = null;
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004323 }
Grace Kloba60e095c2009-06-16 11:50:55 -07004324
Leon Scroggins58d56c62010-01-28 15:12:40 -05004325 UrlData(String url, Map<String, String> headers, Intent intent) {
Grace Kloba068e48b2010-01-26 18:11:27 -08004326 this.mUrl = url;
4327 this.mHeaders = headers;
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -05004328 if (RecognizerResultsIntent.ACTION_VOICE_SEARCH_RESULTS
4329 .equals(intent.getAction())) {
Leon Scroggins58d56c62010-01-28 15:12:40 -05004330 this.mVoiceIntent = intent;
4331 } else {
4332 this.mVoiceIntent = null;
4333 }
Grace Kloba60e095c2009-06-16 11:50:55 -07004334 }
4335
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004336 boolean isEmpty() {
Leon Scroggins58d56c62010-01-28 15:12:40 -05004337 return mVoiceIntent == null && (mUrl == null || mUrl.length() == 0);
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004338 }
4339
Leon Scroggins92472e82010-02-17 16:32:28 -05004340 /**
4341 * Load this UrlData into the given Tab. Use loadUrlDataIn to update
4342 * the title bar as well.
4343 */
Leon Scroggins58d56c62010-01-28 15:12:40 -05004344 public void loadIn(Tab t) {
4345 if (mVoiceIntent != null) {
4346 t.activateVoiceSearchMode(mVoiceIntent);
4347 } else {
4348 t.getWebView().loadUrl(mUrl, mHeaders);
4349 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004350 }
4351 };
4352
Leon Scroggins1f005d32009-08-10 17:36:42 -04004353 /* package */ static final UrlData EMPTY_URL_DATA = new UrlData(null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004354}