blob: 864d68867864a4768a857e3d723d46ebc323306f [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;
25import android.content.ComponentName;
Leon Scroggins58d56c62010-01-28 15:12:40 -050026import android.content.ContentProvider;
27import android.content.ContentProviderClient;
The Android Open Source Project0c908882009-03-03 19:32:16 -080028import android.content.ContentResolver;
Leon Scrogginsb6b7f9e2009-06-18 12:05:28 -040029import android.content.ContentUris;
The Android Open Source Project0c908882009-03-03 19:32:16 -080030import android.content.ContentValues;
31import android.content.Context;
32import android.content.DialogInterface;
33import android.content.Intent;
34import android.content.IntentFilter;
Grace Klobab4da0ad2009-05-14 14:45:40 -070035import android.content.pm.PackageInfo;
The Android Open Source Project0c908882009-03-03 19:32:16 -080036import android.content.pm.PackageManager;
37import android.content.pm.ResolveInfo;
The Android Open Source Project0c908882009-03-03 19:32:16 -080038import android.content.res.Configuration;
39import android.content.res.Resources;
40import android.database.Cursor;
Leon Scroggins96afcb12009-12-10 12:35:56 -050041import android.database.DatabaseUtils;
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;
47import android.graphics.Rect;
The Android Open Source Project0c908882009-03-03 19:32:16 -080048import android.graphics.drawable.Drawable;
The Android Open Source Project0c908882009-03-03 19:32:16 -080049import android.net.ConnectivityManager;
Andrei Popescu56199cc2010-01-12 22:39:16 +000050import android.net.NetworkInfo;
The Android Open Source Project0c908882009-03-03 19:32:16 -080051import android.net.Uri;
52import android.net.WebAddress;
The Android Open Source Project0c908882009-03-03 19:32:16 -080053import android.net.http.SslCertificate;
54import android.net.http.SslError;
55import android.os.AsyncTask;
56import android.os.Bundle;
57import android.os.Debug;
58import android.os.Environment;
59import android.os.Handler;
The Android Open Source Project0c908882009-03-03 19:32:16 -080060import android.os.Message;
61import android.os.PowerManager;
62import android.os.Process;
The Android Open Source Project0c908882009-03-03 19:32:16 -080063import android.os.ServiceManager;
64import android.os.SystemClock;
The Android Open Source Project0c908882009-03-03 19:32:16 -080065import android.provider.Browser;
Cary Clark5e335a32009-09-22 14:53:11 -040066import android.provider.ContactsContract;
67import android.provider.ContactsContract.Intents.Insert;
The Android Open Source Project0c908882009-03-03 19:32:16 -080068import android.provider.Downloads;
69import android.provider.MediaStore;
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -050070import android.speech.RecognizerResultsIntent;
The Android Open Source Project0c908882009-03-03 19:32:16 -080071import android.text.IClipboard;
72import android.text.TextUtils;
73import android.text.format.DateFormat;
Leon Scrogginsb94bf272009-09-25 15:22:08 -040074import android.util.AttributeSet;
The Android Open Source Project0c908882009-03-03 19:32:16 -080075import android.util.Log;
76import android.view.ContextMenu;
77import android.view.Gravity;
78import android.view.KeyEvent;
79import android.view.LayoutInflater;
80import android.view.Menu;
81import android.view.MenuInflater;
82import android.view.MenuItem;
83import android.view.View;
84import android.view.ViewGroup;
85import android.view.Window;
86import android.view.WindowManager;
87import android.view.ContextMenu.ContextMenuInfo;
88import android.view.MenuItem.OnMenuItemClickListener;
The Android Open Source Project0c908882009-03-03 19:32:16 -080089import android.webkit.CookieManager;
90import android.webkit.CookieSyncManager;
91import android.webkit.DownloadListener;
92import android.webkit.HttpAuthHandler;
Grace Klobab4da0ad2009-05-14 14:45:40 -070093import android.webkit.PluginManager;
The Android Open Source Project0c908882009-03-03 19:32:16 -080094import android.webkit.SslErrorHandler;
95import android.webkit.URLUtil;
Leon Clarkecb6cc862009-09-29 18:35:13 +010096import android.webkit.ValueCallback;
The Android Open Source Project0c908882009-03-03 19:32:16 -080097import android.webkit.WebChromeClient;
98import android.webkit.WebHistoryItem;
99import android.webkit.WebIconDatabase;
100import android.webkit.WebView;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800101import android.widget.EditText;
102import android.widget.FrameLayout;
103import android.widget.LinearLayout;
104import android.widget.TextView;
105import android.widget.Toast;
Fred Quintana752b6562009-12-18 10:18:26 -0800106import android.accounts.Account;
107import android.accounts.AccountManager;
108import android.accounts.AccountManagerFuture;
109import android.accounts.AuthenticatorException;
110import android.accounts.OperationCanceledException;
111import android.accounts.AccountManagerCallback;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800112
Dan Egnor5ee906c2009-11-18 12:11:49 -0800113import com.android.common.Patterns;
Leon Scroggins1fe13a52010-02-09 15:31:26 -0500114import com.android.common.speech.LoggingEvents;
Dan Egnor5ee906c2009-11-18 12:11:49 -0800115
Doug Zongker716d4f52010-01-21 14:35:23 -0800116import com.google.android.gsf.GoogleLoginServiceConstants;
Dan Egnor5ee906c2009-11-18 12:11:49 -0800117
Leon Scrogginsb6b7f9e2009-06-18 12:05:28 -0400118import java.io.ByteArrayOutputStream;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800119import java.io.File;
Ben Murdoch4f75ba22009-10-27 11:48:28 +0000120import java.io.IOException;
121import java.io.InputStream;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800122import java.net.MalformedURLException;
123import java.net.URI;
Dianne Hackborn99189432009-06-17 18:06:18 -0700124import java.net.URISyntaxException;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800125import java.net.URL;
126import java.net.URLEncoder;
127import java.text.ParseException;
128import java.util.Date;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800129import java.util.HashMap;
Grace Kloba00f54c52010-01-27 14:53:51 -0800130import java.util.Iterator;
Grace Kloba068e48b2010-01-26 18:11:27 -0800131import java.util.Map;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800132import java.util.regex.Matcher;
133import java.util.regex.Pattern;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800134
135public class BrowserActivity extends Activity
Fred Quintana752b6562009-12-18 10:18:26 -0800136 implements View.OnCreateContextMenuListener, DownloadListener,
137 AccountManagerCallback<Account[]> {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800138
Dave Bort31a6d1c2009-04-13 15:56:49 -0700139 /* Define some aliases to make these debugging flags easier to refer to.
140 * This file imports android.provider.Browser, so we can't just refer to "Browser.DEBUG".
141 */
142 private final static boolean DEBUG = com.android.browser.Browser.DEBUG;
143 private final static boolean LOGV_ENABLED = com.android.browser.Browser.LOGV_ENABLED;
144 private final static boolean LOGD_ENABLED = com.android.browser.Browser.LOGD_ENABLED;
145
Satish Sampath565505b2009-05-29 15:37:27 +0100146 // These are single-character shortcuts for searching popular sources.
147 private static final int SHORTCUT_INVALID = 0;
148 private static final int SHORTCUT_GOOGLE_SEARCH = 1;
149 private static final int SHORTCUT_WIKIPEDIA_SEARCH = 2;
150 private static final int SHORTCUT_DICTIONARY_SEARCH = 3;
151 private static final int SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH = 4;
152
Fred Quintana752b6562009-12-18 10:18:26 -0800153 private Account[] mAccountsGoogle;
154 private Account[] mAccountsPreferHosted;
155
156 private void startReadOfGoogleAccounts() {
157 mAccountsGoogle = null;
158 mAccountsPreferHosted = null;
159
160 AccountManager.get(this).getAccountsByTypeAndFeatures(
161 GoogleLoginServiceConstants.ACCOUNT_TYPE,
162 new String[]{GoogleLoginServiceConstants.FEATURE_LEGACY_HOSTED_OR_GOOGLE},
163 this, null);
164 }
165
166 /** This implements AccountManagerCallback<Account[]> */
167 public void run(AccountManagerFuture<Account[]> accountManagerFuture) {
168 try {
169 if (mAccountsGoogle == null) {
170 mAccountsGoogle = accountManagerFuture.getResult();
171
172 AccountManager.get(this).getAccountsByTypeAndFeatures(
173 GoogleLoginServiceConstants.ACCOUNT_TYPE,
174 new String[]{GoogleLoginServiceConstants.FEATURE_LEGACY_GOOGLE},
175 this, null);
176 } else {
177 mAccountsPreferHosted = accountManagerFuture.getResult();
178 setupHomePage();
179 }
180 } catch (OperationCanceledException e) {
181 setupHomePage();
182 } catch (IOException e) {
183 setupHomePage();
184 } catch (AuthenticatorException e) {
185 setupHomePage();
186 }
187 }
188
The Android Open Source Project0c908882009-03-03 19:32:16 -0800189 private void setupHomePage() {
Fred Quintana752b6562009-12-18 10:18:26 -0800190 // get the default home page
191 String homepage = mSettings.getHomePage();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800192
Fred Quintana752b6562009-12-18 10:18:26 -0800193 if (mAccountsPreferHosted != null && mAccountsGoogle != null) {
194 // three cases:
195 //
196 // hostedUser == googleUser
197 // The device has only a google account
198 //
199 // hostedUser != googleUser
200 // The device has a hosted account and a google account
201 //
202 // hostedUser != null, googleUser == null
203 // The device has only a hosted account (so far)
204 String hostedUser = mAccountsPreferHosted.length == 0
205 ? null
206 : mAccountsPreferHosted[0].name;
207 String googleUser = mAccountsGoogle.length == 0 ? null : mAccountsGoogle[0].name;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800208
Fred Quintana752b6562009-12-18 10:18:26 -0800209 // developers might have no accounts at all
210 if (hostedUser == null) return;
Grace Klobaf2c5c1b2009-05-26 10:48:31 -0700211
Fred Quintana752b6562009-12-18 10:18:26 -0800212 if (googleUser == null || !hostedUser.equals(googleUser)) {
213 String domain = hostedUser.substring(hostedUser.lastIndexOf('@')+1);
214 homepage = homepage.replace("?", "/a/" + domain + "?");
The Android Open Source Project0c908882009-03-03 19:32:16 -0800215 }
Fred Quintana752b6562009-12-18 10:18:26 -0800216 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800217
Fred Quintana752b6562009-12-18 10:18:26 -0800218 mSettings.setHomePage(BrowserActivity.this, homepage);
219 resumeAfterCredentials();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800220 }
221
Cary Clarka9771242009-08-11 16:42:26 -0400222 private static class ClearThumbnails extends AsyncTask<File, Void, Void> {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800223 @Override
224 public Void doInBackground(File... files) {
225 if (files != null) {
226 for (File f : files) {
Cary Clarkd6be1752009-08-12 12:56:42 -0400227 if (!f.delete()) {
228 Log.e(LOGTAG, f.getPath() + " was not deleted");
229 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800230 }
231 }
232 return null;
233 }
234 }
235
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400236 /**
237 * This layout holds everything you see below the status bar, including the
238 * error console, the custom view container, and the webviews.
239 */
240 private FrameLayout mBrowserFrameLayout;
Leon Scroggins81db3662009-06-04 17:45:11 -0400241
Grace Kloba22ac16e2009-10-07 18:00:23 -0700242 @Override
243 public void onCreate(Bundle icicle) {
Dave Bort31a6d1c2009-04-13 15:56:49 -0700244 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800245 Log.v(LOGTAG, this + " onStart");
246 }
247 super.onCreate(icicle);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800248 // test the browser in OpenGL
249 // requestWindowFeature(Window.FEATURE_OPENGL);
250
Mike Reedd334bf52010-01-26 15:21:44 -0500251 // enable this to test the browser in 32bit
252 if (false) {
253 getWindow().setFormat(PixelFormat.RGBX_8888);
254 BitmapFactory.setDefaultConfig(Bitmap.Config.ARGB_8888);
255 }
256
The Android Open Source Project0c908882009-03-03 19:32:16 -0800257 setDefaultKeyMode(DEFAULT_KEYS_SEARCH_LOCAL);
258
259 mResolver = getContentResolver();
260
Grace Kloba0923d692009-09-23 21:37:25 -0700261 // If this was a web search request, pass it on to the default web
262 // search provider and finish this activity.
263 if (handleWebSearchIntent(getIntent())) {
264 finish();
265 return;
266 }
267
The Android Open Source Project0c908882009-03-03 19:32:16 -0800268 mSecLockIcon = Resources.getSystem().getDrawable(
269 android.R.drawable.ic_secure);
270 mMixLockIcon = Resources.getSystem().getDrawable(
271 android.R.drawable.ic_partial_secure);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800272
Leon Scroggins81db3662009-06-04 17:45:11 -0400273 FrameLayout frameLayout = (FrameLayout) getWindow().getDecorView()
274 .findViewById(com.android.internal.R.id.content);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400275 mBrowserFrameLayout = (FrameLayout) LayoutInflater.from(this)
276 .inflate(R.layout.custom_screen, null);
277 mContentView = (FrameLayout) mBrowserFrameLayout.findViewById(
278 R.id.main_content);
279 mErrorConsoleContainer = (LinearLayout) mBrowserFrameLayout
280 .findViewById(R.id.error_console);
281 mCustomViewContainer = (FrameLayout) mBrowserFrameLayout
282 .findViewById(R.id.fullscreen_custom_content);
283 frameLayout.addView(mBrowserFrameLayout, COVER_SCREEN_PARAMS);
Leon Scroggins68579392009-09-15 15:31:54 -0400284 mTitleBar = new TitleBar(this);
Leon Scrogginsfe87bd32009-10-06 10:10:00 -0400285 mFakeTitleBar = new TitleBar(this);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800286
287 // Create the tab control and our initial tab
288 mTabControl = new TabControl(this);
289
290 // Open the icon database and retain all the bookmark urls for favicons
291 retainIconsOnStartup();
292
293 // Keep a settings instance handy.
294 mSettings = BrowserSettings.getInstance();
295 mSettings.setTabControl(mTabControl);
296 mSettings.loadFromDb(this);
297
298 PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
299 mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Browser");
300
Grace Klobaa34f6862009-07-31 16:28:17 -0700301 /* enables registration for changes in network status from
302 http stack */
303 mNetworkStateChangedFilter = new IntentFilter();
304 mNetworkStateChangedFilter.addAction(
305 ConnectivityManager.CONNECTIVITY_ACTION);
306 mNetworkStateIntentReceiver = new BroadcastReceiver() {
307 @Override
308 public void onReceive(Context context, Intent intent) {
309 if (intent.getAction().equals(
310 ConnectivityManager.CONNECTIVITY_ACTION)) {
Robert Greenwalt7d899d62009-10-23 10:33:48 -0700311 boolean noConnectivity = intent.getBooleanExtra(
312 ConnectivityManager.EXTRA_NO_CONNECTIVITY, false);
Andrei Popescu56199cc2010-01-12 22:39:16 +0000313 if (!noConnectivity) {
314 NetworkInfo info = intent.getParcelableExtra(
315 ConnectivityManager.EXTRA_NETWORK_INFO);
316 String typeName = info.getTypeName();
317 String subtypeName = info.getSubtypeName();
318 sendNetworkType(typeName.toLowerCase(),
319 (subtypeName != null ? subtypeName.toLowerCase() : ""));
320 }
Robert Greenwalt7d899d62009-10-23 10:33:48 -0700321 onNetworkToggle(!noConnectivity);
Grace Klobaa34f6862009-07-31 16:28:17 -0700322 }
323 }
324 };
325
Grace Kloba615c6c92009-08-03 10:22:44 -0700326 IntentFilter filter = new IntentFilter(Intent.ACTION_PACKAGE_ADDED);
327 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
328 filter.addDataScheme("package");
329 mPackageInstallationReceiver = new BroadcastReceiver() {
330 @Override
331 public void onReceive(Context context, Intent intent) {
332 final String action = intent.getAction();
333 final String packageName = intent.getData()
334 .getSchemeSpecificPart();
335 final boolean replacing = intent.getBooleanExtra(
336 Intent.EXTRA_REPLACING, false);
337 if (Intent.ACTION_PACKAGE_REMOVED.equals(action) && replacing) {
338 // if it is replacing, refreshPlugins() when adding
339 return;
340 }
341 PackageManager pm = BrowserActivity.this.getPackageManager();
342 PackageInfo pkgInfo = null;
343 try {
344 pkgInfo = pm.getPackageInfo(packageName,
345 PackageManager.GET_PERMISSIONS);
346 } catch (PackageManager.NameNotFoundException e) {
347 return;
348 }
349 if (pkgInfo != null) {
350 String permissions[] = pkgInfo.requestedPermissions;
351 if (permissions == null) {
352 return;
353 }
354 boolean permissionOk = false;
355 for (String permit : permissions) {
356 if (PluginManager.PLUGIN_PERMISSION.equals(permit)) {
357 permissionOk = true;
358 break;
359 }
360 }
361 if (permissionOk) {
362 PluginManager.getInstance(BrowserActivity.this)
363 .refreshPlugins(
364 Intent.ACTION_PACKAGE_ADDED
365 .equals(action));
366 }
367 }
368 }
369 };
370 registerReceiver(mPackageInstallationReceiver, filter);
371
The Android Open Source Project0c908882009-03-03 19:32:16 -0800372 if (!mTabControl.restoreState(icicle)) {
373 // clear up the thumbnail directory if we can't restore the state as
374 // none of the files in the directory are referenced any more.
375 new ClearThumbnails().execute(
376 mTabControl.getThumbnailDir().listFiles());
Grace Klobaaab3f092009-07-30 12:29:51 -0700377 // there is no quit on Android. But if we can't restore the state,
378 // we can treat it as a new Browser, remove the old session cookies.
379 CookieManager.getInstance().removeSessionCookie();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800380 final Intent intent = getIntent();
381 final Bundle extra = intent.getExtras();
382 // Create an initial tab.
383 // If the intent is ACTION_VIEW and data is not null, the Browser is
384 // invoked to view the content by another application. In this case,
385 // the tab will be close when exit.
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700386 UrlData urlData = getUrlDataFromIntent(intent);
387
Leon Scroggins58d56c62010-01-28 15:12:40 -0500388 String action = intent.getAction();
Grace Kloba22ac16e2009-10-07 18:00:23 -0700389 final Tab t = mTabControl.createNewTab(
Leon Scroggins58d56c62010-01-28 15:12:40 -0500390 (Intent.ACTION_VIEW.equals(action) &&
391 intent.getData() != null)
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -0500392 || RecognizerResultsIntent.ACTION_VOICE_SEARCH_RESULTS
393 .equals(action),
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700394 intent.getStringExtra(Browser.EXTRA_APPLICATION_ID), urlData.mUrl);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800395 mTabControl.setCurrentTab(t);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800396 attachTabToContentView(t);
397 WebView webView = t.getWebView();
398 if (extra != null) {
399 int scale = extra.getInt(Browser.INITIAL_ZOOM_LEVEL, 0);
400 if (scale > 0 && scale <= 1000) {
401 webView.setInitialScale(scale);
402 }
403 }
404 // If we are not restoring from an icicle, then there is a high
405 // likely hood this is the first run. So, check to see if the
406 // homepage needs to be configured and copy any plugins from our
407 // asset directory to the data partition.
408 if ((extra == null || !extra.getBoolean("testing"))
409 && !mSettings.isLoginInitialized()) {
Fred Quintana752b6562009-12-18 10:18:26 -0800410 startReadOfGoogleAccounts();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800411 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800412
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700413 if (urlData.isEmpty()) {
Leon Scroggins30444232009-09-04 18:36:20 -0400414 if (mSettings.isLoginInitialized()) {
415 webView.loadUrl(mSettings.getHomePage());
416 } else {
417 waitForCredentials();
418 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800419 } else {
Leon Scroggins58d56c62010-01-28 15:12:40 -0500420 urlData.loadIn(t);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800421 }
422 } else {
423 // TabControl.restoreState() will create a new tab even if
Leon Scroggins1f005d32009-08-10 17:36:42 -0400424 // restoring the state fails.
The Android Open Source Project0c908882009-03-03 19:32:16 -0800425 attachTabToContentView(mTabControl.getCurrentTab());
426 }
Grace Kloba615c6c92009-08-03 10:22:44 -0700427
Feng Qianb3c02da2009-06-29 15:58:08 -0700428 // Read JavaScript flags if it exists.
429 String jsFlags = mSettings.getJsFlags();
430 if (jsFlags.trim().length() != 0) {
431 mTabControl.getCurrentWebView().setJsFlags(jsFlags);
432 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800433 }
434
Leon Scroggins58d56c62010-01-28 15:12:40 -0500435 /**
436 * Feed the previously stored results strings to the BrowserProvider so that
437 * the SearchDialog will show them instead of the standard searches.
438 * @param result String to show on the editable line of the SearchDialog.
439 */
440 /* package */ void showVoiceSearchResults(String result) {
441 ContentProviderClient client = mResolver.acquireContentProviderClient(
442 Browser.BOOKMARKS_URI);
443 ContentProvider prov = client.getLocalContentProvider();
444 BrowserProvider bp = (BrowserProvider) prov;
445 bp.setQueryResults(mTabControl.getCurrentTab().getVoiceSearchResults());
446 client.release();
447
448 startSearch(result, false,
449 createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_SEARCHKEY),
450 false);
451 }
452
The Android Open Source Project0c908882009-03-03 19:32:16 -0800453 @Override
454 protected void onNewIntent(Intent intent) {
Grace Kloba22ac16e2009-10-07 18:00:23 -0700455 Tab current = mTabControl.getCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800456 // When a tab is closed on exit, the current tab index is set to -1.
457 // Reset before proceed as Browser requires the current tab to be set.
458 if (current == null) {
459 // Try to reset the tab in case the index was incorrect.
460 current = mTabControl.getTab(0);
461 if (current == null) {
462 // No tabs at all so just ignore this intent.
463 return;
464 }
465 mTabControl.setCurrentTab(current);
466 attachTabToContentView(current);
467 resetTitleAndIcon(current.getWebView());
468 }
469 final String action = intent.getAction();
470 final int flags = intent.getFlags();
471 if (Intent.ACTION_MAIN.equals(action) ||
472 (flags & Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY) != 0) {
473 // just resume the browser
474 return;
475 }
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -0500476 boolean activateVoiceSearch = RecognizerResultsIntent
477 .ACTION_VOICE_SEARCH_RESULTS.equals(action);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800478 if (Intent.ACTION_VIEW.equals(action)
479 || Intent.ACTION_SEARCH.equals(action)
480 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
Leon Scroggins58d56c62010-01-28 15:12:40 -0500481 || Intent.ACTION_WEB_SEARCH.equals(action)
482 || activateVoiceSearch) {
Leon Scroggins3b18ce32010-02-08 17:35:59 -0500483 if (current.isInVoiceSearchMode()) {
484 String title = current.getVoiceDisplayTitle();
485 if (title != null && title.equals(intent.getStringExtra(
486 SearchManager.QUERY))) {
487 // The user submitted the same search as the last voice
488 // search, so do nothing.
489 return;
490 }
Leon Scroggins1fe13a52010-02-09 15:31:26 -0500491 if (Intent.ACTION_SEARCH.equals(action)
492 && current.voiceSearchSourceIsGoogle()) {
493 Intent logIntent = new Intent(
494 LoggingEvents.ACTION_LOG_EVENT);
495 logIntent.putExtra(LoggingEvents.EXTRA_EVENT,
496 LoggingEvents.VoiceSearch.QUERY_UPDATED);
497 logIntent.putExtra(
498 LoggingEvents.VoiceSearch.EXTRA_QUERY_UPDATED_VALUE,
499 intent.getDataString());
500 sendBroadcast(logIntent);
501 // Note, onPageStarted will revert the voice title bar
502 // When http://b/issue?id=2379215 is fixed, we should update
503 // the title bar here.
504 }
Leon Scroggins3b18ce32010-02-08 17:35:59 -0500505 }
Satish Sampath565505b2009-05-29 15:37:27 +0100506 // If this was a search request (e.g. search query directly typed into the address bar),
507 // pass it on to the default web search provider.
508 if (handleWebSearchIntent(intent)) {
509 return;
510 }
511
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700512 UrlData urlData = getUrlDataFromIntent(intent);
513 if (urlData.isEmpty()) {
514 urlData = new UrlData(mSettings.getHomePage());
The Android Open Source Project0c908882009-03-03 19:32:16 -0800515 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700516
Grace Klobacc634032009-07-28 15:58:19 -0700517 final String appId = intent
518 .getStringExtra(Browser.EXTRA_APPLICATION_ID);
Leon Scroggins58d56c62010-01-28 15:12:40 -0500519 if ((Intent.ACTION_VIEW.equals(action) || activateVoiceSearch)
Grace Klobacc634032009-07-28 15:58:19 -0700520 && !getPackageName().equals(appId)
521 && (flags & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0) {
Grace Kloba22ac16e2009-10-07 18:00:23 -0700522 Tab appTab = mTabControl.getTabFromId(appId);
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700523 if (appTab != null) {
524 Log.i(LOGTAG, "Reusing tab for " + appId);
525 // Dismiss the subwindow if applicable.
526 dismissSubWindow(appTab);
527 // Since we might kill the WebView, remove it from the
528 // content view first.
529 removeTabFromContentView(appTab);
530 // Recreate the main WebView after destroying the old one.
531 // If the WebView has the same original url and is on that
532 // page, it can be reused.
533 boolean needsLoad =
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700534 mTabControl.recreateWebView(appTab, urlData.mUrl);
Ben Murdochbff2d602009-07-01 20:19:05 +0100535
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700536 if (current != appTab) {
Leon Scroggins1f005d32009-08-10 17:36:42 -0400537 switchToTab(mTabControl.getTabIndex(appTab));
538 if (needsLoad) {
Leon Scroggins58d56c62010-01-28 15:12:40 -0500539 urlData.loadIn(appTab);
Leon Scroggins1f005d32009-08-10 17:36:42 -0400540 }
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700541 } else {
Leon Scroggins1f005d32009-08-10 17:36:42 -0400542 // If the tab was the current tab, we have to attach
543 // it to the view system again.
544 attachTabToContentView(appTab);
545 if (needsLoad) {
Leon Scroggins58d56c62010-01-28 15:12:40 -0500546 urlData.loadIn(appTab);
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700547 }
548 }
549 return;
Patrick Scottcd115892009-07-16 09:42:58 -0400550 } else {
551 // No matching application tab, try to find a regular tab
552 // with a matching url.
553 appTab = mTabControl.findUnusedTabWithUrl(urlData.mUrl);
Leon Scroggins25515f82009-08-19 15:31:58 -0400554 if (appTab != null) {
555 if (current != appTab) {
556 switchToTab(mTabControl.getTabIndex(appTab));
557 }
558 // Otherwise, we are already viewing the correct tab.
Patrick Scottcd115892009-07-16 09:42:58 -0400559 } else {
560 // if FLAG_ACTIVITY_BROUGHT_TO_FRONT flag is on, the url
561 // will be opened in a new tab unless we have reached
562 // MAX_TABS. Then the url will be opened in the current
563 // tab. If a new tab is created, it will have "true" for
564 // exit on close.
Leon Scroggins1f005d32009-08-10 17:36:42 -0400565 openTabAndShow(urlData, true, appId);
Patrick Scottcd115892009-07-16 09:42:58 -0400566 }
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700567 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800568 } else {
Grace Kloba638d3f42009-11-23 10:35:04 -0800569 if (!urlData.isEmpty()
570 && urlData.mUrl.startsWith("about:debug")) {
571 if ("about:debug.dom".equals(urlData.mUrl)) {
572 current.getWebView().dumpDomTree(false);
573 } else if ("about:debug.dom.file".equals(urlData.mUrl)) {
574 current.getWebView().dumpDomTree(true);
575 } else if ("about:debug.render".equals(urlData.mUrl)) {
576 current.getWebView().dumpRenderTree(false);
577 } else if ("about:debug.render.file".equals(urlData.mUrl)) {
578 current.getWebView().dumpRenderTree(true);
579 } else if ("about:debug.display".equals(urlData.mUrl)) {
580 current.getWebView().dumpDisplayTree();
Mike Reed9b78e1d2010-01-13 14:40:52 -0800581 } else if (urlData.mUrl.startsWith("about:debug.drag")) {
582 int index = urlData.mUrl.codePointAt(16) - '0';
583 if (index <= 0 || index > 9) {
584 current.getWebView().setDragTracker(null);
585 } else {
586 current.getWebView().setDragTracker(new MeshTracker(index));
587 }
Grace Kloba638d3f42009-11-23 10:35:04 -0800588 } else {
589 mSettings.toggleDebugSettings();
590 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800591 return;
592 }
Leon Scroggins1f005d32009-08-10 17:36:42 -0400593 // Get rid of the subwindow if it exists
594 dismissSubWindow(current);
Leon Scroggins58d56c62010-01-28 15:12:40 -0500595 urlData.loadIn(current);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800596 }
597 }
598 }
599
Satish Sampath565505b2009-05-29 15:37:27 +0100600 private int parseUrlShortcut(String url) {
601 if (url == null) return SHORTCUT_INVALID;
602
603 // FIXME: quick search, need to be customized by setting
604 if (url.length() > 2 && url.charAt(1) == ' ') {
605 switch (url.charAt(0)) {
606 case 'g': return SHORTCUT_GOOGLE_SEARCH;
607 case 'w': return SHORTCUT_WIKIPEDIA_SEARCH;
608 case 'd': return SHORTCUT_DICTIONARY_SEARCH;
609 case 'l': return SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH;
610 }
611 }
612 return SHORTCUT_INVALID;
613 }
614
615 /**
616 * Launches the default web search activity with the query parameters if the given intent's data
617 * are identified as plain search terms and not URLs/shortcuts.
618 * @return true if the intent was handled and web search activity was launched, false if not.
619 */
620 private boolean handleWebSearchIntent(Intent intent) {
621 if (intent == null) return false;
622
623 String url = null;
624 final String action = intent.getAction();
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -0500625 if (RecognizerResultsIntent.ACTION_VOICE_SEARCH_RESULTS.equals(
626 action)) {
Leon Scroggins58d56c62010-01-28 15:12:40 -0500627 return false;
628 }
Satish Sampath565505b2009-05-29 15:37:27 +0100629 if (Intent.ACTION_VIEW.equals(action)) {
Grace Kloba1e705052009-09-29 13:13:36 -0700630 Uri data = intent.getData();
631 if (data != null) url = data.toString();
Satish Sampath565505b2009-05-29 15:37:27 +0100632 } else if (Intent.ACTION_SEARCH.equals(action)
633 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
634 || Intent.ACTION_WEB_SEARCH.equals(action)) {
635 url = intent.getStringExtra(SearchManager.QUERY);
636 }
Bjorn Bringert04851702009-09-22 10:36:01 +0100637 return handleWebSearchRequest(url, intent.getBundleExtra(SearchManager.APP_DATA),
638 intent.getStringExtra(SearchManager.EXTRA_DATA_KEY));
Satish Sampath565505b2009-05-29 15:37:27 +0100639 }
640
641 /**
642 * Launches the default web search activity with the query parameters if the given url string
643 * was identified as plain search terms and not URL/shortcut.
644 * @return true if the request was handled and web search activity was launched, false if not.
645 */
Bjorn Bringert04851702009-09-22 10:36:01 +0100646 private boolean handleWebSearchRequest(String inUrl, Bundle appData, String extraData) {
Satish Sampath565505b2009-05-29 15:37:27 +0100647 if (inUrl == null) return false;
648
649 // In general, we shouldn't modify URL from Intent.
650 // But currently, we get the user-typed URL from search box as well.
651 String url = fixUrl(inUrl).trim();
652
653 // URLs and site specific search shortcuts are handled by the regular flow of control, so
654 // return early.
Dan Egnor5ee906c2009-11-18 12:11:49 -0800655 if (Patterns.WEB_URL.matcher(url).matches()
Satish Sampathbc5b9f32009-06-04 18:21:40 +0100656 || ACCEPTED_URI_SCHEMA.matcher(url).matches()
Satish Sampath565505b2009-05-29 15:37:27 +0100657 || parseUrlShortcut(url) != SHORTCUT_INVALID) {
658 return false;
659 }
660
661 Browser.updateVisitedHistory(mResolver, url, false);
662 Browser.addSearchUrl(mResolver, url);
663
664 Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);
665 intent.addCategory(Intent.CATEGORY_DEFAULT);
666 intent.putExtra(SearchManager.QUERY, url);
Satish Sampath15e9f2d2009-06-23 22:29:49 +0100667 if (appData != null) {
668 intent.putExtra(SearchManager.APP_DATA, appData);
669 }
Bjorn Bringert04851702009-09-22 10:36:01 +0100670 if (extraData != null) {
671 intent.putExtra(SearchManager.EXTRA_DATA_KEY, extraData);
672 }
Grace Klobacc634032009-07-28 15:58:19 -0700673 intent.putExtra(Browser.EXTRA_APPLICATION_ID, getPackageName());
Satish Sampath565505b2009-05-29 15:37:27 +0100674 startActivity(intent);
675
676 return true;
677 }
678
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700679 private UrlData getUrlDataFromIntent(Intent intent) {
Leon Scroggins58d56c62010-01-28 15:12:40 -0500680 String url = "";
Grace Kloba068e48b2010-01-26 18:11:27 -0800681 Map<String, String> headers = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800682 if (intent != null) {
683 final String action = intent.getAction();
684 if (Intent.ACTION_VIEW.equals(action)) {
685 url = smartUrlFilter(intent.getData());
686 if (url != null && url.startsWith("content:")) {
687 /* Append mimetype so webview knows how to display */
688 String mimeType = intent.resolveType(getContentResolver());
689 if (mimeType != null) {
690 url += "?" + mimeType;
691 }
692 }
Grace Kloba068e48b2010-01-26 18:11:27 -0800693 if (url != null && url.startsWith("http")) {
Grace Kloba00f54c52010-01-27 14:53:51 -0800694 final Bundle pairs = intent
695 .getBundleExtra(Browser.EXTRA_HEADERS);
Grace Kloba2d508ed2010-01-28 11:39:15 -0800696 if (pairs != null && !pairs.isEmpty()) {
Grace Kloba00f54c52010-01-27 14:53:51 -0800697 Iterator<String> iter = pairs.keySet().iterator();
Grace Kloba068e48b2010-01-26 18:11:27 -0800698 headers = new HashMap<String, String>();
Grace Kloba00f54c52010-01-27 14:53:51 -0800699 while (iter.hasNext()) {
700 String key = iter.next();
701 headers.put(key, pairs.getString(key));
Grace Kloba068e48b2010-01-26 18:11:27 -0800702 }
703 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700704 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800705 } else if (Intent.ACTION_SEARCH.equals(action)
706 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
707 || Intent.ACTION_WEB_SEARCH.equals(action)) {
708 url = intent.getStringExtra(SearchManager.QUERY);
709 if (url != null) {
710 mLastEnteredUrl = url;
Leon Scrogginsb4464432009-11-25 12:37:50 -0500711 Browser.updateVisitedHistory(mResolver, url, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800712 // In general, we shouldn't modify URL from Intent.
713 // But currently, we get the user-typed URL from search box as well.
714 url = fixUrl(url);
715 url = smartUrlFilter(url);
716 String searchSource = "&source=android-" + GOOGLE_SEARCH_SOURCE_SUGGEST + "&";
717 if (url.contains(searchSource)) {
718 String source = null;
719 final Bundle appData = intent.getBundleExtra(SearchManager.APP_DATA);
720 if (appData != null) {
721 source = appData.getString(SearchManager.SOURCE);
722 }
723 if (TextUtils.isEmpty(source)) {
724 source = GOOGLE_SEARCH_SOURCE_UNKNOWN;
725 }
726 url = url.replace(searchSource, "&source=android-"+source+"&");
727 }
728 }
729 }
730 }
Leon Scroggins58d56c62010-01-28 15:12:40 -0500731 return new UrlData(url, headers, intent);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800732 }
Leon Scroggins58d56c62010-01-28 15:12:40 -0500733 /* package */ void showVoiceTitleBar(String title) {
734 mTitleBar.setInVoiceMode(true);
735 mFakeTitleBar.setInVoiceMode(true);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800736
Leon Scroggins58d56c62010-01-28 15:12:40 -0500737 mTitleBar.setDisplayTitle(title);
738 mFakeTitleBar.setDisplayTitle(title);
739 }
740 /* package */ void revertVoiceTitleBar() {
741 mTitleBar.setInVoiceMode(false);
742 mFakeTitleBar.setInVoiceMode(false);
743
744 mTitleBar.setDisplayTitle(mTitle);
745 mFakeTitleBar.setDisplayTitle(mTitle);
746 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800747 /* package */ static String fixUrl(String inUrl) {
Cary Clark652ff872009-09-10 13:34:44 -0400748 // FIXME: Converting the url to lower case
749 // duplicates functionality in smartUrlFilter().
750 // However, changing all current callers of fixUrl to
751 // call smartUrlFilter in addition may have unwanted
752 // consequences, and is deferred for now.
753 int colon = inUrl.indexOf(':');
754 boolean allLower = true;
755 for (int index = 0; index < colon; index++) {
756 char ch = inUrl.charAt(index);
757 if (!Character.isLetter(ch)) {
758 break;
759 }
760 allLower &= Character.isLowerCase(ch);
761 if (index == colon - 1 && !allLower) {
762 inUrl = inUrl.substring(0, colon).toLowerCase()
763 + inUrl.substring(colon);
764 }
765 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800766 if (inUrl.startsWith("http://") || inUrl.startsWith("https://"))
767 return inUrl;
768 if (inUrl.startsWith("http:") ||
769 inUrl.startsWith("https:")) {
770 if (inUrl.startsWith("http:/") || inUrl.startsWith("https:/")) {
771 inUrl = inUrl.replaceFirst("/", "//");
772 } else inUrl = inUrl.replaceFirst(":", "://");
773 }
774 return inUrl;
775 }
776
Grace Kloba22ac16e2009-10-07 18:00:23 -0700777 @Override
778 protected void onResume() {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800779 super.onResume();
Dave Bort31a6d1c2009-04-13 15:56:49 -0700780 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800781 Log.v(LOGTAG, "BrowserActivity.onResume: this=" + this);
782 }
783
784 if (!mActivityInPause) {
785 Log.e(LOGTAG, "BrowserActivity is already resumed.");
786 return;
787 }
788
Mike Reed7bfa63b2009-05-28 11:08:32 -0400789 mTabControl.resumeCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800790 mActivityInPause = false;
Mike Reed7bfa63b2009-05-28 11:08:32 -0400791 resumeWebViewTimers();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800792
793 if (mWakeLock.isHeld()) {
794 mHandler.removeMessages(RELEASE_WAKELOCK);
795 mWakeLock.release();
796 }
797
798 if (mCredsDlg != null) {
799 if (!mHandler.hasMessages(CANCEL_CREDS_REQUEST)) {
800 // In case credential request never comes back
801 mHandler.sendEmptyMessageDelayed(CANCEL_CREDS_REQUEST, 6000);
802 }
803 }
804
805 registerReceiver(mNetworkStateIntentReceiver,
806 mNetworkStateChangedFilter);
807 WebView.enablePlatformNotifications();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800808 }
809
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400810 /**
811 * Since the actual title bar is embedded in the WebView, and removing it
Leon Scrogginsfe87bd32009-10-06 10:10:00 -0400812 * would change its appearance, use a different TitleBar to show overlayed
813 * at the top of the screen, when the menu is open or the page is loading.
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400814 */
815 private TitleBar mFakeTitleBar;
816
817 /**
Leon Scrogginsd8fd2fc2009-09-16 11:12:09 -0400818 * Holder for the fake title bar. It will have a foreground shadow, as well
819 * as a white background, so the fake title bar looks like the real one.
820 */
821 private ViewGroup mFakeTitleBarHolder;
822
823 /**
824 * Layout parameters for the fake title bar within mFakeTitleBarHolder
825 */
826 private FrameLayout.LayoutParams mFakeTitleBarParams
827 = new FrameLayout.LayoutParams(
Romain Guy15b8ec62010-01-08 15:06:43 -0800828 ViewGroup.LayoutParams.MATCH_PARENT,
Leon Scrogginsd8fd2fc2009-09-16 11:12:09 -0400829 ViewGroup.LayoutParams.WRAP_CONTENT);
830 /**
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400831 * Keeps track of whether the options menu is open. This is important in
832 * determining whether to show or hide the title bar overlay.
833 */
834 private boolean mOptionsMenuOpen;
835
836 /**
837 * Only meaningful when mOptionsMenuOpen is true. This variable keeps track
838 * of whether the configuration has changed. The first onMenuOpened call
839 * after a configuration change is simply a reopening of the same menu
840 * (i.e. mIconView did not change).
841 */
842 private boolean mConfigChanged;
843
844 /**
845 * Whether or not the options menu is in its smaller, icon menu form. When
846 * true, we want the title bar overlay to be up. When false, we do not.
847 * Only meaningful if mOptionsMenuOpen is true.
848 */
849 private boolean mIconView;
850
Leon Scrogginsa81a7642009-08-31 17:05:41 -0400851 @Override
852 public boolean onMenuOpened(int featureId, Menu menu) {
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400853 if (Window.FEATURE_OPTIONS_PANEL == featureId) {
854 if (mOptionsMenuOpen) {
855 if (mConfigChanged) {
856 // We do not need to make any changes to the state of the
857 // title bar, since the only thing that happened was a
858 // change in orientation
859 mConfigChanged = false;
860 } else {
861 if (mIconView) {
862 // Switching the menu to expanded view, so hide the
863 // title bar.
864 hideFakeTitleBar();
865 mIconView = false;
866 } else {
867 // Switching the menu back to icon view, so show the
868 // title bar once again.
869 showFakeTitleBar();
870 mIconView = true;
871 }
872 }
873 } else {
874 // The options menu is closed, so open it, and show the title
875 showFakeTitleBar();
876 mOptionsMenuOpen = true;
877 mConfigChanged = false;
878 mIconView = true;
879 }
880 }
Leon Scrogginsa81a7642009-08-31 17:05:41 -0400881 return true;
882 }
883
Leon Scrogginsb94bf272009-09-25 15:22:08 -0400884 /**
885 * Special class used exclusively for the shadow drawn underneath the fake
886 * title bar. The shadow does not need to be drawn if the WebView
887 * underneath is scrolled to the top, because it will draw directly on top
888 * of the embedded shadow.
889 */
890 private static class Shadow extends View {
891 private WebView mWebView;
892
893 public Shadow(Context context, AttributeSet attrs) {
894 super(context, attrs);
895 }
896
897 public void setWebView(WebView view) {
898 mWebView = view;
899 }
900
901 @Override
902 public void draw(Canvas canvas) {
903 // In general onDraw is the method to override, but we care about
904 // whether or not the background gets drawn, which happens in draw()
905 if (mWebView == null || mWebView.getScrollY() > getHeight()) {
906 super.draw(canvas);
907 }
908 // Need to invalidate so that if the scroll position changes, we
909 // still draw as appropriate.
910 invalidate();
911 }
912 }
913
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400914 private void showFakeTitleBar() {
Patrick Scottf8de8ec2009-09-21 16:37:29 -0400915 final View decor = getWindow().peekDecorView();
Leon Scrogginsfe87bd32009-10-06 10:10:00 -0400916 if (mFakeTitleBar.getParent() == null && mActiveTabsPage == null
Patrick Scottf8de8ec2009-09-21 16:37:29 -0400917 && !mActivityInPause && decor != null
918 && decor.getWindowToken() != null) {
Cary Clarka0464552009-09-29 13:00:45 -0400919 Rect visRect = new Rect();
920 if (!mBrowserFrameLayout.getGlobalVisibleRect(visRect)) {
921 if (LOGD_ENABLED) {
922 Log.d(LOGTAG, "showFakeTitleBar visRect failed");
923 }
924 return;
925 }
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400926
927 WindowManager manager
928 = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
929
930 // Add the title bar to the window manager so it can receive touches
931 // while the menu is up
932 WindowManager.LayoutParams params
933 = new WindowManager.LayoutParams(
Romain Guy15b8ec62010-01-08 15:06:43 -0800934 ViewGroup.LayoutParams.MATCH_PARENT,
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400935 ViewGroup.LayoutParams.WRAP_CONTENT,
936 WindowManager.LayoutParams.TYPE_APPLICATION_SUB_PANEL,
937 WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
Leon Scroggins68549862009-09-21 16:02:01 -0400938 PixelFormat.TRANSLUCENT);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400939 params.gravity = Gravity.TOP;
Leon Scrogginsa27ff192009-09-14 12:58:04 -0400940 WebView mainView = mTabControl.getCurrentWebView();
Leon Scroggins68549862009-09-21 16:02:01 -0400941 boolean atTop = mainView != null && mainView.getScrollY() == 0;
Leon Scroggins83932c72009-09-30 11:55:54 -0400942 params.windowAnimations = atTop ? 0 : R.style.TitleBar;
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400943 // XXX : Without providing an offset, the fake title bar will be
944 // placed underneath the status bar. Use the global visible rect
945 // of mBrowserFrameLayout to determine the bottom of the status bar
Cary Clarka0464552009-09-29 13:00:45 -0400946 params.y = visRect.top;
Leon Scroggins68549862009-09-21 16:02:01 -0400947 // Add a holder for the title bar. It also holds a shadow to show
948 // below the title bar.
Leon Scrogginsd8fd2fc2009-09-16 11:12:09 -0400949 if (mFakeTitleBarHolder == null) {
950 mFakeTitleBarHolder = (ViewGroup) LayoutInflater.from(this)
951 .inflate(R.layout.title_bar_bg, null);
952 }
Leon Scrogginsb94bf272009-09-25 15:22:08 -0400953 Shadow shadow = (Shadow) mFakeTitleBarHolder.findViewById(
954 R.id.shadow);
955 shadow.setWebView(mainView);
Leon Scroggins68549862009-09-21 16:02:01 -0400956 mFakeTitleBarHolder.addView(mFakeTitleBar, 0, mFakeTitleBarParams);
Leon Scrogginsd8fd2fc2009-09-16 11:12:09 -0400957 manager.addView(mFakeTitleBarHolder, params);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400958 }
959 }
960
961 @Override
962 public void onOptionsMenuClosed(Menu menu) {
963 mOptionsMenuOpen = false;
Leon Scrogginsa27ff192009-09-14 12:58:04 -0400964 if (!mInLoad) {
965 hideFakeTitleBar();
966 } else if (!mIconView) {
967 // The page is currently loading, and we are in expanded mode, so
968 // we were not showing the menu. Show it once again. It will be
969 // removed when the page finishes.
970 showFakeTitleBar();
971 }
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400972 }
Grace Kloba22ac16e2009-10-07 18:00:23 -0700973
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400974 private void hideFakeTitleBar() {
Leon Scrogginsfe87bd32009-10-06 10:10:00 -0400975 if (mFakeTitleBar.getParent() == null) return;
Leon Scroggins20329572009-09-23 17:42:41 -0400976 WindowManager.LayoutParams params = (WindowManager.LayoutParams)
977 mFakeTitleBarHolder.getLayoutParams();
978 WebView mainView = mTabControl.getCurrentWebView();
979 // Although we decided whether or not to animate based on the current
980 // scroll position, the scroll position may have changed since the
981 // fake title bar was displayed. Make sure it has the appropriate
982 // animation/lack thereof before removing.
983 params.windowAnimations = mainView != null && mainView.getScrollY() == 0
Leon Scroggins83932c72009-09-30 11:55:54 -0400984 ? 0 : R.style.TitleBar;
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400985 WindowManager manager
986 = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
Leon Scroggins20329572009-09-23 17:42:41 -0400987 manager.updateViewLayout(mFakeTitleBarHolder, params);
Leon Scrogginsd8fd2fc2009-09-16 11:12:09 -0400988 mFakeTitleBarHolder.removeView(mFakeTitleBar);
989 manager.removeView(mFakeTitleBarHolder);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400990 }
991
The Android Open Source Project0c908882009-03-03 19:32:16 -0800992 /**
Leon Scrogginsc6fa1102009-09-21 10:40:01 -0400993 * Special method for the fake title bar to call when displaying its context
994 * menu, since it is in its own Window, and its parent does not show a
995 * context menu.
996 */
997 /* package */ void showTitleBarContextMenu() {
Cary Clark65f4a3c2009-09-28 17:05:06 -0400998 if (null == mTitleBar.getParent()) {
999 return;
1000 }
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001001 openContextMenu(mTitleBar);
1002 }
1003
Leon Scrogginsb2b19f52009-10-09 16:10:00 -04001004 @Override
1005 public void onContextMenuClosed(Menu menu) {
1006 super.onContextMenuClosed(menu);
1007 if (mInLoad) {
1008 showFakeTitleBar();
1009 }
1010 }
1011
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001012 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08001013 * onSaveInstanceState(Bundle map)
1014 * onSaveInstanceState is called right before onStop(). The map contains
1015 * the saved state.
1016 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07001017 @Override
1018 protected void onSaveInstanceState(Bundle outState) {
Dave Bort31a6d1c2009-04-13 15:56:49 -07001019 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001020 Log.v(LOGTAG, "BrowserActivity.onSaveInstanceState: this=" + this);
1021 }
1022 // the default implementation requires each view to have an id. As the
1023 // browser handles the state itself and it doesn't use id for the views,
1024 // don't call the default implementation. Otherwise it will trigger the
1025 // warning like this, "couldn't save which view has focus because the
1026 // focused view XXX has no id".
1027
1028 // Save all the tabs
1029 mTabControl.saveState(outState);
1030 }
1031
Grace Kloba22ac16e2009-10-07 18:00:23 -07001032 @Override
1033 protected void onPause() {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001034 super.onPause();
1035
1036 if (mActivityInPause) {
1037 Log.e(LOGTAG, "BrowserActivity is already paused.");
1038 return;
1039 }
1040
Mike Reed7bfa63b2009-05-28 11:08:32 -04001041 mTabControl.pauseCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001042 mActivityInPause = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -04001043 if (mTabControl.getCurrentIndex() >= 0 && !pauseWebViewTimers()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001044 mWakeLock.acquire();
1045 mHandler.sendMessageDelayed(mHandler
1046 .obtainMessage(RELEASE_WAKELOCK), WAKELOCK_TIMEOUT);
1047 }
1048
1049 // Clear the credentials toast if it is up
1050 if (mCredsDlg != null && mCredsDlg.isShowing()) {
1051 mCredsDlg.dismiss();
1052 }
1053 mCredsDlg = null;
1054
Leon Scrogginsa2ab6a72009-09-11 11:49:52 -04001055 // FIXME: This removes the active tabs page and resets the menu to
1056 // MAIN_MENU. A better solution might be to do this work in onNewIntent
1057 // but then we would need to save it in onSaveInstanceState and restore
1058 // it in onCreate/onRestoreInstanceState
1059 if (mActiveTabsPage != null) {
1060 removeActiveTabPage(true);
1061 }
1062
The Android Open Source Project0c908882009-03-03 19:32:16 -08001063 cancelStopToast();
1064
1065 // unregister network state listener
1066 unregisterReceiver(mNetworkStateIntentReceiver);
1067 WebView.disablePlatformNotifications();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001068 }
1069
Grace Kloba22ac16e2009-10-07 18:00:23 -07001070 @Override
1071 protected void onDestroy() {
Dave Bort31a6d1c2009-04-13 15:56:49 -07001072 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001073 Log.v(LOGTAG, "BrowserActivity.onDestroy: this=" + this);
1074 }
1075 super.onDestroy();
Grace Kloba0923d692009-09-23 21:37:25 -07001076
Leon Scroggins8d5fa432009-10-02 15:55:59 -04001077 if (mUploadMessage != null) {
1078 mUploadMessage.onReceiveValue(null);
1079 mUploadMessage = null;
1080 }
1081
Grace Kloba0923d692009-09-23 21:37:25 -07001082 if (mTabControl == null) return;
1083
Grace Kloba1fc98a32009-10-21 13:23:08 -07001084 // Remove the fake title bar if it is there
1085 hideFakeTitleBar();
1086
The Android Open Source Project0c908882009-03-03 19:32:16 -08001087 // Remove the current tab and sub window
Grace Kloba22ac16e2009-10-07 18:00:23 -07001088 Tab t = mTabControl.getCurrentTab();
Patrick Scottfb5e77f2009-04-08 19:17:37 -07001089 if (t != null) {
1090 dismissSubWindow(t);
1091 removeTabFromContentView(t);
1092 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001093 // Destroy all the tabs
1094 mTabControl.destroy();
1095 WebIconDatabase.getInstance().close();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001096
Grace Klobab4da0ad2009-05-14 14:45:40 -07001097 unregisterReceiver(mPackageInstallationReceiver);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001098 }
1099
1100 @Override
1101 public void onConfigurationChanged(Configuration newConfig) {
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04001102 mConfigChanged = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001103 super.onConfigurationChanged(newConfig);
1104
1105 if (mPageInfoDialog != null) {
1106 mPageInfoDialog.dismiss();
1107 showPageInfo(
1108 mPageInfoView,
Leon Scrogginsc7b92f82010-01-11 18:17:31 -05001109 mPageInfoFromShowSSLCertificateOnError);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001110 }
1111 if (mSSLCertificateDialog != null) {
1112 mSSLCertificateDialog.dismiss();
1113 showSSLCertificate(
1114 mSSLCertificateView);
1115 }
1116 if (mSSLCertificateOnErrorDialog != null) {
1117 mSSLCertificateOnErrorDialog.dismiss();
1118 showSSLCertificateOnError(
1119 mSSLCertificateOnErrorView,
1120 mSSLCertificateOnErrorHandler,
1121 mSSLCertificateOnErrorError);
1122 }
1123 if (mHttpAuthenticationDialog != null) {
1124 String title = ((TextView) mHttpAuthenticationDialog
1125 .findViewById(com.android.internal.R.id.alertTitle)).getText()
1126 .toString();
1127 String name = ((TextView) mHttpAuthenticationDialog
1128 .findViewById(R.id.username_edit)).getText().toString();
1129 String password = ((TextView) mHttpAuthenticationDialog
1130 .findViewById(R.id.password_edit)).getText().toString();
1131 int focusId = mHttpAuthenticationDialog.getCurrentFocus()
1132 .getId();
1133 mHttpAuthenticationDialog.dismiss();
1134 showHttpAuthentication(mHttpAuthHandler, null, null, title,
1135 name, password, focusId);
1136 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001137 }
1138
Grace Kloba22ac16e2009-10-07 18:00:23 -07001139 @Override
1140 public void onLowMemory() {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001141 super.onLowMemory();
1142 mTabControl.freeMemory();
1143 }
1144
Mike Reed7bfa63b2009-05-28 11:08:32 -04001145 private boolean resumeWebViewTimers() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001146 Tab tab = mTabControl.getCurrentTab();
1147 boolean inLoad = tab.inLoad();
1148 if ((!mActivityInPause && !inLoad) || (mActivityInPause && inLoad)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001149 CookieSyncManager.getInstance().startSync();
Grace Kloba22ac16e2009-10-07 18:00:23 -07001150 WebView w = tab.getWebView();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001151 if (w != null) {
1152 w.resumeTimers();
1153 }
1154 return true;
1155 } else {
1156 return false;
1157 }
1158 }
1159
Mike Reed7bfa63b2009-05-28 11:08:32 -04001160 private boolean pauseWebViewTimers() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001161 Tab tab = mTabControl.getCurrentTab();
1162 boolean inLoad = tab.inLoad();
1163 if (mActivityInPause && !inLoad) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001164 CookieSyncManager.getInstance().stopSync();
1165 WebView w = mTabControl.getCurrentWebView();
1166 if (w != null) {
1167 w.pauseTimers();
1168 }
1169 return true;
1170 } else {
1171 return false;
1172 }
1173 }
1174
Leon Scroggins1f005d32009-08-10 17:36:42 -04001175 // FIXME: Do we want to call this when loading google for the first time?
The Android Open Source Project0c908882009-03-03 19:32:16 -08001176 /*
1177 * This function is called when we are launching for the first time. We
1178 * are waiting for the login credentials before loading Google home
1179 * pages. This way the user will be logged in straight away.
1180 */
1181 private void waitForCredentials() {
1182 // Show a toast
1183 mCredsDlg = new ProgressDialog(this);
1184 mCredsDlg.setIndeterminate(true);
1185 mCredsDlg.setMessage(getText(R.string.retrieving_creds_dlg_msg));
1186 // If the user cancels the operation, then cancel the Google
1187 // Credentials request.
1188 mCredsDlg.setCancelMessage(mHandler.obtainMessage(CANCEL_CREDS_REQUEST));
1189 mCredsDlg.show();
1190
1191 // We set a timeout for the retrieval of credentials in onResume()
1192 // as that is when we have freed up some CPU time to get
1193 // the login credentials.
1194 }
1195
1196 /*
1197 * If we have received the credentials or we have timed out and we are
1198 * showing the credentials dialog, then it is time to move on.
1199 */
1200 private void resumeAfterCredentials() {
1201 if (mCredsDlg == null) {
1202 return;
1203 }
1204
1205 // Clear the toast
1206 if (mCredsDlg.isShowing()) {
1207 mCredsDlg.dismiss();
1208 }
1209 mCredsDlg = null;
1210
1211 // Clear any pending timeout
1212 mHandler.removeMessages(CANCEL_CREDS_REQUEST);
1213
1214 // Load the page
1215 WebView w = mTabControl.getCurrentWebView();
1216 if (w != null) {
1217 w.loadUrl(mSettings.getHomePage());
1218 }
1219
1220 // Update the settings, need to do this last as it can take a moment
1221 // to persist the settings. In the mean time we could be loading
1222 // content.
1223 mSettings.setLoginInitialized(this);
1224 }
1225
1226 // Open the icon database and retain all the icons for visited sites.
1227 private void retainIconsOnStartup() {
1228 final WebIconDatabase db = WebIconDatabase.getInstance();
1229 db.open(getDir("icons", 0).getPath());
1230 try {
1231 Cursor c = Browser.getAllBookmarks(mResolver);
1232 if (!c.moveToFirst()) {
1233 c.deactivate();
1234 return;
1235 }
1236 int urlIndex = c.getColumnIndex(Browser.BookmarkColumns.URL);
1237 do {
1238 String url = c.getString(urlIndex);
1239 db.retainIconForPageUrl(url);
1240 } while (c.moveToNext());
1241 c.deactivate();
1242 } catch (IllegalStateException e) {
1243 Log.e(LOGTAG, "retainIconsOnStartup", e);
1244 }
1245 }
1246
1247 // Helper method for getting the top window.
1248 WebView getTopWindow() {
1249 return mTabControl.getCurrentTopWebView();
1250 }
1251
Grace Kloba22ac16e2009-10-07 18:00:23 -07001252 TabControl getTabControl() {
1253 return mTabControl;
1254 }
1255
The Android Open Source Project0c908882009-03-03 19:32:16 -08001256 @Override
1257 public boolean onCreateOptionsMenu(Menu menu) {
1258 super.onCreateOptionsMenu(menu);
1259
1260 MenuInflater inflater = getMenuInflater();
1261 inflater.inflate(R.menu.browser, menu);
1262 mMenu = menu;
1263 updateInLoadMenuItems();
1264 return true;
1265 }
1266
1267 /**
1268 * As the menu can be open when loading state changes
1269 * we must manually update the state of the stop/reload menu
1270 * item
1271 */
1272 private void updateInLoadMenuItems() {
1273 if (mMenu == null) {
1274 return;
1275 }
1276 MenuItem src = mInLoad ?
1277 mMenu.findItem(R.id.stop_menu_id):
1278 mMenu.findItem(R.id.reload_menu_id);
1279 MenuItem dest = mMenu.findItem(R.id.stop_reload_menu_id);
1280 dest.setIcon(src.getIcon());
1281 dest.setTitle(src.getTitle());
1282 }
1283
1284 @Override
1285 public boolean onContextItemSelected(MenuItem item) {
1286 // chording is not an issue with context menus, but we use the same
1287 // options selector, so set mCanChord to true so we can access them.
1288 mCanChord = true;
1289 int id = item.getItemId();
Leon Scroggins96afcb12009-12-10 12:35:56 -05001290 boolean result = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001291 switch (id) {
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001292 // For the context menu from the title bar
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001293 case R.id.title_bar_copy_page_url:
Leon Scroggins96afcb12009-12-10 12:35:56 -05001294 Tab currentTab = mTabControl.getCurrentTab();
1295 if (null == currentTab) {
1296 result = false;
1297 break;
1298 }
1299 WebView mainView = currentTab.getWebView();
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001300 if (null == mainView) {
Leon Scroggins96afcb12009-12-10 12:35:56 -05001301 result = false;
1302 break;
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001303 }
Leon Scroggins96afcb12009-12-10 12:35:56 -05001304 copy(mainView.getUrl());
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001305 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001306 // -- Browser context menu
1307 case R.id.open_context_menu_id:
1308 case R.id.open_newtab_context_menu_id:
1309 case R.id.bookmark_context_menu_id:
1310 case R.id.save_link_context_menu_id:
1311 case R.id.share_link_context_menu_id:
1312 case R.id.copy_link_context_menu_id:
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001313 final WebView webView = getTopWindow();
1314 if (null == webView) {
Leon Scroggins96afcb12009-12-10 12:35:56 -05001315 result = false;
1316 break;
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001317 }
1318 final HashMap hrefMap = new HashMap();
1319 hrefMap.put("webview", webView);
1320 final Message msg = mHandler.obtainMessage(
1321 FOCUS_NODE_HREF, id, 0, hrefMap);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001322 webView.requestFocusNodeHref(msg);
1323 break;
1324
1325 default:
1326 // For other context menus
Leon Scroggins96afcb12009-12-10 12:35:56 -05001327 result = onOptionsItemSelected(item);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001328 }
1329 mCanChord = false;
Leon Scroggins96afcb12009-12-10 12:35:56 -05001330 return result;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001331 }
1332
1333 private Bundle createGoogleSearchSourceBundle(String source) {
1334 Bundle bundle = new Bundle();
1335 bundle.putString(SearchManager.SOURCE, source);
1336 return bundle;
1337 }
1338
1339 /**
The Android Open Source Project4e5f5872009-03-09 11:52:14 -07001340 * Overriding this to insert a local information bundle
The Android Open Source Project0c908882009-03-03 19:32:16 -08001341 */
1342 @Override
1343 public boolean onSearchRequested() {
Leon Scroggins68579392009-09-15 15:31:54 -04001344 if (mOptionsMenuOpen) closeOptionsMenu();
Leon Scroggins5bbe9802009-07-31 13:10:55 -04001345 String url = (getTopWindow() == null) ? null : getTopWindow().getUrl();
Grace Kloba83f47342009-07-20 10:44:31 -07001346 startSearch(mSettings.getHomePage().equals(url) ? null : url, true,
The Android Open Source Project4e5f5872009-03-09 11:52:14 -07001347 createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_SEARCHKEY), false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001348 return true;
1349 }
1350
1351 @Override
1352 public void startSearch(String initialQuery, boolean selectInitialQuery,
1353 Bundle appSearchData, boolean globalSearch) {
1354 if (appSearchData == null) {
1355 appSearchData = createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_TYPE);
1356 }
1357 super.startSearch(initialQuery, selectInitialQuery, appSearchData, globalSearch);
1358 }
1359
Leon Scroggins1f005d32009-08-10 17:36:42 -04001360 /**
1361 * Switch tabs. Called by the TitleBarSet when sliding the title bar
1362 * results in changing tabs.
Leon Scroggins160a7e72009-08-14 18:28:01 -04001363 * @param index Index of the tab to change to, as defined by
1364 * mTabControl.getTabIndex(Tab t).
1365 * @return boolean True if we successfully switched to a different tab. If
1366 * the indexth tab is null, or if that tab is the same as
1367 * the current one, return false.
Leon Scroggins1f005d32009-08-10 17:36:42 -04001368 */
Leon Scroggins160a7e72009-08-14 18:28:01 -04001369 /* package */ boolean switchToTab(int index) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001370 Tab tab = mTabControl.getTab(index);
1371 Tab currentTab = mTabControl.getCurrentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04001372 if (tab == null || tab == currentTab) {
Leon Scroggins160a7e72009-08-14 18:28:01 -04001373 return false;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001374 }
1375 if (currentTab != null) {
1376 // currentTab may be null if it was just removed. In that case,
1377 // we do not need to remove it
1378 removeTabFromContentView(currentTab);
1379 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001380 mTabControl.setCurrentTab(tab);
1381 attachTabToContentView(tab);
Grace Klobaeb6eef42009-09-15 17:56:32 -07001382 resetTitleIconAndProgress();
1383 updateLockIconToLatest();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001384 return true;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001385 }
1386
Grace Kloba22ac16e2009-10-07 18:00:23 -07001387 /* package */ Tab openTabToHomePage() {
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001388 return openTabAndShow(mSettings.getHomePage(), false, null);
1389 }
1390
Leon Scroggins1f005d32009-08-10 17:36:42 -04001391 /* package */ void closeCurrentWindow() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001392 final Tab current = mTabControl.getCurrentTab();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001393 if (mTabControl.getTabCount() == 1) {
Leon Scroggins30444232009-09-04 18:36:20 -04001394 // This is the last tab. Open a new one, with the home
1395 // page and close the current one.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001396 openTabToHomePage();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001397 closeTab(current);
Leon Scroggins160a7e72009-08-14 18:28:01 -04001398 return;
1399 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07001400 final Tab parent = current.getParentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04001401 int indexToShow = -1;
1402 if (parent != null) {
1403 indexToShow = mTabControl.getTabIndex(parent);
1404 } else {
Leon Scroggins160a7e72009-08-14 18:28:01 -04001405 final int currentIndex = mTabControl.getCurrentIndex();
1406 // Try to move to the tab to the right
1407 indexToShow = currentIndex + 1;
1408 if (indexToShow > mTabControl.getTabCount() - 1) {
1409 // Try to move to the tab to the left
1410 indexToShow = currentIndex - 1;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001411 }
1412 }
Leon Scroggins160a7e72009-08-14 18:28:01 -04001413 if (switchToTab(indexToShow)) {
1414 // Close window
1415 closeTab(current);
1416 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001417 }
1418
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001419 private ActiveTabsPage mActiveTabsPage;
1420
1421 /**
1422 * Remove the active tabs page.
1423 * @param needToAttach If true, the active tabs page did not attach a tab
1424 * to the content view, so we need to do that here.
1425 */
1426 /* package */ void removeActiveTabPage(boolean needToAttach) {
1427 mContentView.removeView(mActiveTabsPage);
1428 mActiveTabsPage = null;
1429 mMenuState = R.id.MAIN_MENU;
1430 if (needToAttach) {
1431 attachTabToContentView(mTabControl.getCurrentTab());
1432 }
1433 getTopWindow().requestFocus();
1434 }
1435
The Android Open Source Project0c908882009-03-03 19:32:16 -08001436 @Override
1437 public boolean onOptionsItemSelected(MenuItem item) {
1438 if (!mCanChord) {
1439 // The user has already fired a shortcut with this hold down of the
1440 // menu key.
1441 return false;
1442 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001443 if (null == getTopWindow()) {
Leon Scroggins0d7ae0e2009-06-05 11:04:45 -04001444 return false;
1445 }
Grace Kloba6ee9c492009-07-13 10:04:34 -07001446 if (mMenuIsDown) {
1447 // The shortcut action consumes the MENU. Even if it is still down,
1448 // it won't trigger the next shortcut action. In the case of the
1449 // shortcut action triggering a new activity, like Bookmarks, we
1450 // won't get onKeyUp for MENU. So it is important to reset it here.
1451 mMenuIsDown = false;
1452 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001453 switch (item.getItemId()) {
1454 // -- Main menu
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001455 case R.id.new_tab_menu_id:
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001456 openTabToHomePage();
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001457 break;
1458
Leon Scroggins64b80f32009-08-07 12:03:34 -04001459 case R.id.goto_menu_id:
Leon Scrogginsb3a5bed2009-09-28 11:21:56 -04001460 onSearchRequested();
1461 break;
1462
1463 case R.id.bookmarks_menu_id:
Leon Scroggins30444232009-09-04 18:36:20 -04001464 bookmarksOrHistoryPicker(false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001465 break;
1466
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001467 case R.id.active_tabs_menu_id:
1468 mActiveTabsPage = new ActiveTabsPage(this, mTabControl);
1469 removeTabFromContentView(mTabControl.getCurrentTab());
Leon Scroggins43de6162009-09-14 19:59:58 -04001470 hideFakeTitleBar();
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001471 mContentView.addView(mActiveTabsPage, COVER_SCREEN_PARAMS);
1472 mActiveTabsPage.requestFocus();
1473 mMenuState = EMPTY_MENU;
1474 break;
1475
Leon Scroggins1f005d32009-08-10 17:36:42 -04001476 case R.id.add_bookmark_menu_id:
1477 Intent i = new Intent(BrowserActivity.this,
1478 AddBookmarkPage.class);
1479 WebView w = getTopWindow();
1480 i.putExtra("url", w.getUrl());
1481 i.putExtra("title", w.getTitle());
Grace Kloba83cdb2c2009-09-16 00:48:57 -07001482 i.putExtra("touch_icon_url", w.getTouchIconUrl());
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01001483 i.putExtra("thumbnail", createScreenshot(w));
Leon Scroggins1f005d32009-08-10 17:36:42 -04001484 startActivity(i);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001485 break;
1486
1487 case R.id.stop_reload_menu_id:
1488 if (mInLoad) {
1489 stopLoading();
1490 } else {
1491 getTopWindow().reload();
1492 }
1493 break;
1494
1495 case R.id.back_menu_id:
1496 getTopWindow().goBack();
1497 break;
1498
1499 case R.id.forward_menu_id:
1500 getTopWindow().goForward();
1501 break;
1502
1503 case R.id.close_menu_id:
1504 // Close the subwindow if it exists.
1505 if (mTabControl.getCurrentSubWindow() != null) {
1506 dismissSubWindow(mTabControl.getCurrentTab());
1507 break;
1508 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001509 closeCurrentWindow();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001510 break;
1511
1512 case R.id.homepage_menu_id:
Grace Kloba22ac16e2009-10-07 18:00:23 -07001513 Tab current = mTabControl.getCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001514 if (current != null) {
1515 dismissSubWindow(current);
1516 current.getWebView().loadUrl(mSettings.getHomePage());
1517 }
1518 break;
1519
1520 case R.id.preferences_menu_id:
1521 Intent intent = new Intent(this,
1522 BrowserPreferencesPage.class);
Leon Scrogginsd5304942009-12-10 16:11:39 -05001523 intent.putExtra(BrowserPreferencesPage.CURRENT_PAGE,
1524 getTopWindow().getUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001525 startActivityForResult(intent, PREFERENCES_PAGE);
1526 break;
1527
1528 case R.id.find_menu_id:
1529 if (null == mFindDialog) {
1530 mFindDialog = new FindDialog(this);
1531 }
1532 mFindDialog.setWebView(getTopWindow());
1533 mFindDialog.show();
1534 mMenuState = EMPTY_MENU;
1535 break;
1536
1537 case R.id.select_text_id:
1538 getTopWindow().emulateShiftHeld();
1539 break;
1540 case R.id.page_info_menu_id:
1541 showPageInfo(mTabControl.getCurrentTab(), false);
1542 break;
1543
1544 case R.id.classic_history_menu_id:
Leon Scroggins30444232009-09-04 18:36:20 -04001545 bookmarksOrHistoryPicker(true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001546 break;
1547
Leon Scroggins96afcb12009-12-10 12:35:56 -05001548 case R.id.title_bar_share_page_url:
The Android Open Source Project0c908882009-03-03 19:32:16 -08001549 case R.id.share_page_menu_id:
Leon Scroggins96afcb12009-12-10 12:35:56 -05001550 Tab currentTab = mTabControl.getCurrentTab();
1551 if (null == currentTab) {
1552 mCanChord = false;
1553 return false;
1554 }
1555 currentTab.populatePickerData();
1556 sharePage(this, currentTab.getTitle(),
1557 currentTab.getUrl(), currentTab.getFavicon(),
1558 createScreenshot(currentTab.getWebView()));
The Android Open Source Project0c908882009-03-03 19:32:16 -08001559 break;
1560
1561 case R.id.dump_nav_menu_id:
1562 getTopWindow().debugDump();
1563 break;
1564
Andrei Popescu7a8b88b2010-02-02 00:30:38 +00001565 case R.id.dump_counters_menu_id:
1566 getTopWindow().dumpV8Counters();
1567 break;
1568
The Android Open Source Project0c908882009-03-03 19:32:16 -08001569 case R.id.zoom_in_menu_id:
1570 getTopWindow().zoomIn();
1571 break;
1572
1573 case R.id.zoom_out_menu_id:
1574 getTopWindow().zoomOut();
1575 break;
1576
1577 case R.id.view_downloads_menu_id:
1578 viewDownloads(null);
1579 break;
1580
The Android Open Source Project0c908882009-03-03 19:32:16 -08001581 case R.id.window_one_menu_id:
1582 case R.id.window_two_menu_id:
1583 case R.id.window_three_menu_id:
1584 case R.id.window_four_menu_id:
1585 case R.id.window_five_menu_id:
1586 case R.id.window_six_menu_id:
1587 case R.id.window_seven_menu_id:
1588 case R.id.window_eight_menu_id:
1589 {
1590 int menuid = item.getItemId();
1591 for (int id = 0; id < WINDOW_SHORTCUT_ID_ARRAY.length; id++) {
1592 if (WINDOW_SHORTCUT_ID_ARRAY[id] == menuid) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001593 Tab desiredTab = mTabControl.getTab(id);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001594 if (desiredTab != null &&
1595 desiredTab != mTabControl.getCurrentTab()) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001596 switchToTab(id);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001597 }
1598 break;
1599 }
1600 }
1601 }
1602 break;
1603
1604 default:
1605 if (!super.onOptionsItemSelected(item)) {
1606 return false;
1607 }
1608 // Otherwise fall through.
1609 }
1610 mCanChord = false;
1611 return true;
1612 }
1613
1614 public void closeFind() {
1615 mMenuState = R.id.MAIN_MENU;
1616 }
1617
Grace Kloba22ac16e2009-10-07 18:00:23 -07001618 @Override
1619 public boolean onPrepareOptionsMenu(Menu menu) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001620 // This happens when the user begins to hold down the menu key, so
1621 // allow them to chord to get a shortcut.
1622 mCanChord = true;
1623 // Note: setVisible will decide whether an item is visible; while
1624 // setEnabled() will decide whether an item is enabled, which also means
1625 // whether the matching shortcut key will function.
1626 super.onPrepareOptionsMenu(menu);
1627 switch (mMenuState) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001628 case EMPTY_MENU:
1629 if (mCurrentMenuState != mMenuState) {
1630 menu.setGroupVisible(R.id.MAIN_MENU, false);
1631 menu.setGroupEnabled(R.id.MAIN_MENU, false);
1632 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001633 }
1634 break;
1635 default:
1636 if (mCurrentMenuState != mMenuState) {
1637 menu.setGroupVisible(R.id.MAIN_MENU, true);
1638 menu.setGroupEnabled(R.id.MAIN_MENU, true);
1639 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001640 }
1641 final WebView w = getTopWindow();
1642 boolean canGoBack = false;
1643 boolean canGoForward = false;
1644 boolean isHome = false;
1645 if (w != null) {
1646 canGoBack = w.canGoBack();
1647 canGoForward = w.canGoForward();
1648 isHome = mSettings.getHomePage().equals(w.getUrl());
1649 }
1650 final MenuItem back = menu.findItem(R.id.back_menu_id);
1651 back.setEnabled(canGoBack);
1652
1653 final MenuItem home = menu.findItem(R.id.homepage_menu_id);
1654 home.setEnabled(!isHome);
1655
1656 menu.findItem(R.id.forward_menu_id)
1657 .setEnabled(canGoForward);
1658
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001659 menu.findItem(R.id.new_tab_menu_id).setEnabled(
Grace Kloba22ac16e2009-10-07 18:00:23 -07001660 mTabControl.canCreateNewTab());
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001661
The Android Open Source Project0c908882009-03-03 19:32:16 -08001662 // decide whether to show the share link option
1663 PackageManager pm = getPackageManager();
1664 Intent send = new Intent(Intent.ACTION_SEND);
1665 send.setType("text/plain");
1666 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1667 menu.findItem(R.id.share_page_menu_id).setVisible(ri != null);
1668
The Android Open Source Project0c908882009-03-03 19:32:16 -08001669 boolean isNavDump = mSettings.isNavDump();
1670 final MenuItem nav = menu.findItem(R.id.dump_nav_menu_id);
1671 nav.setVisible(isNavDump);
1672 nav.setEnabled(isNavDump);
Andrei Popescu7a8b88b2010-02-02 00:30:38 +00001673
1674 boolean showDebugSettings = mSettings.showDebugSettings();
1675 final MenuItem counter = menu.findItem(R.id.dump_counters_menu_id);
1676 counter.setVisible(showDebugSettings);
1677 counter.setEnabled(showDebugSettings);
1678
The Android Open Source Project0c908882009-03-03 19:32:16 -08001679 break;
1680 }
1681 mCurrentMenuState = mMenuState;
1682 return true;
1683 }
1684
1685 @Override
1686 public void onCreateContextMenu(ContextMenu menu, View v,
1687 ContextMenuInfo menuInfo) {
1688 WebView webview = (WebView) v;
1689 WebView.HitTestResult result = webview.getHitTestResult();
1690 if (result == null) {
1691 return;
1692 }
1693
1694 int type = result.getType();
1695 if (type == WebView.HitTestResult.UNKNOWN_TYPE) {
1696 Log.w(LOGTAG,
1697 "We should not show context menu when nothing is touched");
1698 return;
1699 }
1700 if (type == WebView.HitTestResult.EDIT_TEXT_TYPE) {
1701 // let TextView handles context menu
1702 return;
1703 }
1704
1705 // Note, http://b/issue?id=1106666 is requesting that
1706 // an inflated menu can be used again. This is not available
1707 // yet, so inflate each time (yuk!)
1708 MenuInflater inflater = getMenuInflater();
1709 inflater.inflate(R.menu.browsercontext, menu);
1710
1711 // Show the correct menu group
1712 String extra = result.getExtra();
1713 menu.setGroupVisible(R.id.PHONE_MENU,
1714 type == WebView.HitTestResult.PHONE_TYPE);
1715 menu.setGroupVisible(R.id.EMAIL_MENU,
1716 type == WebView.HitTestResult.EMAIL_TYPE);
1717 menu.setGroupVisible(R.id.GEO_MENU,
1718 type == WebView.HitTestResult.GEO_TYPE);
1719 menu.setGroupVisible(R.id.IMAGE_MENU,
1720 type == WebView.HitTestResult.IMAGE_TYPE
1721 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1722 menu.setGroupVisible(R.id.ANCHOR_MENU,
1723 type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1724 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1725
1726 // Setup custom handling depending on the type
1727 switch (type) {
1728 case WebView.HitTestResult.PHONE_TYPE:
1729 menu.setHeaderTitle(Uri.decode(extra));
1730 menu.findItem(R.id.dial_context_menu_id).setIntent(
1731 new Intent(Intent.ACTION_VIEW, Uri
1732 .parse(WebView.SCHEME_TEL + extra)));
1733 Intent addIntent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
1734 addIntent.putExtra(Insert.PHONE, Uri.decode(extra));
Cary Clark5e335a32009-09-22 14:53:11 -04001735 addIntent.setType(ContactsContract.Contacts.CONTENT_ITEM_TYPE);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001736 menu.findItem(R.id.add_contact_context_menu_id).setIntent(
1737 addIntent);
1738 menu.findItem(R.id.copy_phone_context_menu_id).setOnMenuItemClickListener(
1739 new Copy(extra));
1740 break;
1741
1742 case WebView.HitTestResult.EMAIL_TYPE:
1743 menu.setHeaderTitle(extra);
1744 menu.findItem(R.id.email_context_menu_id).setIntent(
1745 new Intent(Intent.ACTION_VIEW, Uri
1746 .parse(WebView.SCHEME_MAILTO + extra)));
1747 menu.findItem(R.id.copy_mail_context_menu_id).setOnMenuItemClickListener(
1748 new Copy(extra));
1749 break;
1750
1751 case WebView.HitTestResult.GEO_TYPE:
1752 menu.setHeaderTitle(extra);
1753 menu.findItem(R.id.map_context_menu_id).setIntent(
1754 new Intent(Intent.ACTION_VIEW, Uri
1755 .parse(WebView.SCHEME_GEO
1756 + URLEncoder.encode(extra))));
1757 menu.findItem(R.id.copy_geo_context_menu_id).setOnMenuItemClickListener(
1758 new Copy(extra));
1759 break;
1760
1761 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1762 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
1763 TextView titleView = (TextView) LayoutInflater.from(this)
1764 .inflate(android.R.layout.browser_link_context_header,
1765 null);
1766 titleView.setText(extra);
1767 menu.setHeaderView(titleView);
1768 // decide whether to show the open link in new tab option
1769 menu.findItem(R.id.open_newtab_context_menu_id).setVisible(
Grace Kloba22ac16e2009-10-07 18:00:23 -07001770 mTabControl.canCreateNewTab());
Ben Murdochde353622009-10-12 10:29:00 +01001771 menu.findItem(R.id.bookmark_context_menu_id).setVisible(
1772 Bookmarks.urlHasAcceptableScheme(extra));
The Android Open Source Project0c908882009-03-03 19:32:16 -08001773 PackageManager pm = getPackageManager();
1774 Intent send = new Intent(Intent.ACTION_SEND);
1775 send.setType("text/plain");
1776 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1777 menu.findItem(R.id.share_link_context_menu_id).setVisible(ri != null);
1778 if (type == WebView.HitTestResult.SRC_ANCHOR_TYPE) {
1779 break;
1780 }
1781 // otherwise fall through to handle image part
1782 case WebView.HitTestResult.IMAGE_TYPE:
1783 if (type == WebView.HitTestResult.IMAGE_TYPE) {
1784 menu.setHeaderTitle(extra);
1785 }
1786 menu.findItem(R.id.view_image_context_menu_id).setIntent(
1787 new Intent(Intent.ACTION_VIEW, Uri.parse(extra)));
1788 menu.findItem(R.id.download_context_menu_id).
1789 setOnMenuItemClickListener(new Download(extra));
Ben Murdoch4f75ba22009-10-27 11:48:28 +00001790 menu.findItem(R.id.set_wallpaper_context_menu_id).
1791 setOnMenuItemClickListener(new SetAsWallpaper(extra));
The Android Open Source Project0c908882009-03-03 19:32:16 -08001792 break;
1793
1794 default:
1795 Log.w(LOGTAG, "We should not get here.");
1796 break;
1797 }
Leon Scrogginsb2b19f52009-10-09 16:10:00 -04001798 hideFakeTitleBar();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001799 }
1800
The Android Open Source Project0c908882009-03-03 19:32:16 -08001801 // Attach the given tab to the content view.
Grace Klobac928c302009-09-17 11:51:21 -07001802 // this should only be called for the current tab.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001803 private void attachTabToContentView(Tab t) {
Steve Block2bc69912009-07-30 14:45:13 +01001804 // Attach the container that contains the main WebView and any other UI
1805 // associated with the tab.
Patrick Scottd0119532009-09-17 08:00:31 -04001806 t.attachTabToContentView(mContentView);
Ben Murdochbff2d602009-07-01 20:19:05 +01001807
1808 if (mShouldShowErrorConsole) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001809 ErrorConsoleView errorConsole = t.getErrorConsole(true);
Ben Murdochbff2d602009-07-01 20:19:05 +01001810 if (errorConsole.numberOfErrors() == 0) {
1811 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
1812 } else {
1813 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
1814 }
1815
1816 mErrorConsoleContainer.addView(errorConsole,
Romain Guy15b8ec62010-01-08 15:06:43 -08001817 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
Ben Murdochbff2d602009-07-01 20:19:05 +01001818 ViewGroup.LayoutParams.WRAP_CONTENT));
1819 }
1820
Leon Scroggins39ab28e2009-09-02 21:20:30 -04001821 WebView view = t.getWebView();
Leon Scroggins55a5bc22009-09-04 17:00:08 -04001822 view.setEmbeddedTitleBar(mTitleBar);
Leon Scroggins58d56c62010-01-28 15:12:40 -05001823 if (t.isInVoiceSearchMode()) {
1824 showVoiceTitleBar(t.getVoiceDisplayTitle());
1825 } else {
1826 revertVoiceTitleBar();
1827 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001828 // Request focus on the top window.
1829 t.getTopWindow().requestFocus();
1830 }
1831
1832 // Attach a sub window to the main WebView of the given tab.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001833 void attachSubWindow(Tab t) {
Patrick Scottd0119532009-09-17 08:00:31 -04001834 t.attachSubWindow(mContentView);
1835 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001836 }
1837
1838 // Remove the given tab from the content view.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001839 private void removeTabFromContentView(Tab t) {
Steve Block2bc69912009-07-30 14:45:13 +01001840 // Remove the container that contains the main WebView.
Patrick Scottd0119532009-09-17 08:00:31 -04001841 t.removeTabFromContentView(mContentView);
Ben Murdochbff2d602009-07-01 20:19:05 +01001842
Grace Kloba22ac16e2009-10-07 18:00:23 -07001843 ErrorConsoleView errorConsole = t.getErrorConsole(false);
1844 if (errorConsole != null) {
1845 mErrorConsoleContainer.removeView(errorConsole);
Ben Murdochbff2d602009-07-01 20:19:05 +01001846 }
1847
Leon Scroggins39ab28e2009-09-02 21:20:30 -04001848 WebView view = t.getWebView();
Leon Scrogginsbb85b902009-09-14 19:27:20 -04001849 if (view != null) {
1850 view.setEmbeddedTitleBar(null);
1851 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001852 }
1853
1854 // Remove the sub window if it exists. Also called by TabControl when the
1855 // user clicks the 'X' to dismiss a sub window.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001856 /* package */ void dismissSubWindow(Tab t) {
Patrick Scottd0119532009-09-17 08:00:31 -04001857 t.removeSubWindow(mContentView);
Grace Kloba22ac16e2009-10-07 18:00:23 -07001858 // dismiss the subwindow. This will destroy the WebView.
1859 t.dismissSubWindow();
Patrick Scottd0119532009-09-17 08:00:31 -04001860 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001861 }
1862
Leon Scroggins1f005d32009-08-10 17:36:42 -04001863 // A wrapper function of {@link #openTabAndShow(UrlData, boolean, String)}
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07001864 // that accepts url as string.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001865 private Tab openTabAndShow(String url, boolean closeOnExit, String appId) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001866 return openTabAndShow(new UrlData(url), closeOnExit, appId);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001867 }
1868
1869 // This method does a ton of stuff. It will attempt to create a new tab
1870 // if we haven't reached MAX_TABS. Otherwise it uses the current tab. If
Leon Scroggins1f005d32009-08-10 17:36:42 -04001871 // url isn't null, it will load the given url.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001872 /* package */Tab openTabAndShow(UrlData urlData, boolean closeOnExit,
1873 String appId) {
1874 final Tab currentTab = mTabControl.getCurrentTab();
1875 if (mTabControl.canCreateNewTab()) {
1876 final Tab tab = mTabControl.createNewTab(closeOnExit, appId,
1877 urlData.mUrl);
Leon Scroggins1f005d32009-08-10 17:36:42 -04001878 WebView webview = tab.getWebView();
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001879 // If the last tab was removed from the active tabs page, currentTab
1880 // will be null.
1881 if (currentTab != null) {
1882 removeTabFromContentView(currentTab);
1883 }
Patrick Scott8bbd69f2009-08-14 13:35:53 -04001884 // We must set the new tab as the current tab to reflect the old
1885 // animation behavior.
1886 mTabControl.setCurrentTab(tab);
Grace Klobaeb6eef42009-09-15 17:56:32 -07001887 attachTabToContentView(tab);
Leon Scroggins160a7e72009-08-14 18:28:01 -04001888 if (!urlData.isEmpty()) {
Leon Scroggins58d56c62010-01-28 15:12:40 -05001889 urlData.loadIn(tab);
Leon Scroggins1f005d32009-08-10 17:36:42 -04001890 }
1891 return tab;
1892 } else {
1893 // Get rid of the subwindow if it exists
1894 dismissSubWindow(currentTab);
1895 if (!urlData.isEmpty()) {
1896 // Load the given url.
Leon Scroggins58d56c62010-01-28 15:12:40 -05001897 urlData.loadIn(currentTab);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001898 }
Leon Scroggins58d56c62010-01-28 15:12:40 -05001899 return currentTab;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001900 }
1901 }
1902
Grace Kloba22ac16e2009-10-07 18:00:23 -07001903 private Tab openTab(String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001904 if (mSettings.openInBackground()) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001905 Tab t = mTabControl.createNewTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001906 if (t != null) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001907 WebView view = t.getWebView();
Leon Scroggins1f005d32009-08-10 17:36:42 -04001908 view.loadUrl(url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001909 }
Grace Klobac9181842009-04-14 08:53:22 -07001910 return t;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001911 } else {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001912 return openTabAndShow(url, false, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001913 }
1914 }
1915
1916 private class Copy implements OnMenuItemClickListener {
1917 private CharSequence mText;
1918
1919 public boolean onMenuItemClick(MenuItem item) {
1920 copy(mText);
1921 return true;
1922 }
1923
1924 public Copy(CharSequence toCopy) {
1925 mText = toCopy;
1926 }
1927 }
1928
1929 private class Download implements OnMenuItemClickListener {
1930 private String mText;
1931
1932 public boolean onMenuItemClick(MenuItem item) {
1933 onDownloadStartNoStream(mText, null, null, null, -1);
1934 return true;
1935 }
1936
1937 public Download(String toDownload) {
1938 mText = toDownload;
1939 }
1940 }
1941
Ben Murdoch4f75ba22009-10-27 11:48:28 +00001942 private class SetAsWallpaper extends Thread implements
1943 OnMenuItemClickListener, DialogInterface.OnCancelListener {
1944 private URL mUrl;
1945 private ProgressDialog mWallpaperProgress;
1946 private boolean mCanceled = false;
1947
1948 public SetAsWallpaper(String url) {
1949 try {
1950 mUrl = new URL(url);
1951 } catch (MalformedURLException e) {
1952 mUrl = null;
1953 }
1954 }
1955
1956 public void onCancel(DialogInterface dialog) {
1957 mCanceled = true;
1958 }
1959
1960 public boolean onMenuItemClick(MenuItem item) {
1961 if (mUrl != null) {
1962 // The user may have tried to set a image with a large file size as their
1963 // background so it may take a few moments to perform the operation. Display
1964 // a progress spinner while it is working.
1965 mWallpaperProgress = new ProgressDialog(BrowserActivity.this);
1966 mWallpaperProgress.setIndeterminate(true);
1967 mWallpaperProgress.setMessage(getText(R.string.progress_dialog_setting_wallpaper));
1968 mWallpaperProgress.setCancelable(true);
1969 mWallpaperProgress.setOnCancelListener(this);
1970 mWallpaperProgress.show();
1971 start();
1972 }
1973 return true;
1974 }
1975
1976 public void run() {
1977 Drawable oldWallpaper = BrowserActivity.this.getWallpaper();
1978 try {
1979 // TODO: This will cause the resource to be downloaded again, when we
1980 // should in most cases be able to grab it from the cache. To fix this
1981 // we should query WebCore to see if we can access a cached version and
1982 // instead open an input stream on that. This pattern could also be used
1983 // in the download manager where the same problem exists.
1984 InputStream inputstream = mUrl.openStream();
1985 if (inputstream != null) {
1986 setWallpaper(inputstream);
1987 }
1988 } catch (IOException e) {
1989 Log.e(LOGTAG, "Unable to set new wallpaper");
1990 // Act as though the user canceled the operation so we try to
1991 // restore the old wallpaper.
1992 mCanceled = true;
1993 }
1994
1995 if (mCanceled) {
1996 // Restore the old wallpaper if the user cancelled whilst we were setting
1997 // the new wallpaper.
1998 int width = oldWallpaper.getIntrinsicWidth();
1999 int height = oldWallpaper.getIntrinsicHeight();
2000 Bitmap bm = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
2001 Canvas canvas = new Canvas(bm);
2002 oldWallpaper.setBounds(0, 0, width, height);
2003 oldWallpaper.draw(canvas);
2004 try {
2005 setWallpaper(bm);
2006 } catch (IOException e) {
2007 Log.e(LOGTAG, "Unable to restore old wallpaper.");
2008 }
2009 mCanceled = false;
2010 }
2011
2012 if (mWallpaperProgress.isShowing()) {
2013 mWallpaperProgress.dismiss();
2014 }
2015 }
2016 }
2017
The Android Open Source Project0c908882009-03-03 19:32:16 -08002018 private void copy(CharSequence text) {
2019 try {
2020 IClipboard clip = IClipboard.Stub.asInterface(ServiceManager.getService("clipboard"));
2021 if (clip != null) {
2022 clip.setClipboardText(text);
2023 }
2024 } catch (android.os.RemoteException e) {
2025 Log.e(LOGTAG, "Copy failed", e);
2026 }
2027 }
2028
2029 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08002030 * Resets the browser title-view to whatever it must be
2031 * (for example, if we had a loading error)
2032 * When we have a new page, we call resetTitle, when we
2033 * have to reset the titlebar to whatever it used to be
2034 * (for example, if the user chose to stop loading), we
2035 * call resetTitleAndRevertLockIcon.
2036 */
2037 /* package */ void resetTitleAndRevertLockIcon() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002038 mTabControl.getCurrentTab().revertLockIcon();
2039 updateLockIconToLatest();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002040 resetTitleIconAndProgress();
2041 }
2042
2043 /**
2044 * Reset the title, favicon, and progress.
2045 */
2046 private void resetTitleIconAndProgress() {
2047 WebView current = mTabControl.getCurrentWebView();
2048 if (current == null) {
2049 return;
2050 }
2051 resetTitleAndIcon(current);
2052 int progress = current.getProgress();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002053 current.getWebChromeClient().onProgressChanged(current, progress);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002054 }
2055
2056 // Reset the title and the icon based on the given item.
2057 private void resetTitleAndIcon(WebView view) {
2058 WebHistoryItem item = view.copyBackForwardList().getCurrentItem();
2059 if (item != null) {
Leon Scroggins68579392009-09-15 15:31:54 -04002060 setUrlTitle(item.getUrl(), item.getTitle());
The Android Open Source Project0c908882009-03-03 19:32:16 -08002061 setFavicon(item.getFavicon());
2062 } else {
Leon Scroggins68579392009-09-15 15:31:54 -04002063 setUrlTitle(null, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002064 setFavicon(null);
2065 }
2066 }
2067
2068 /**
2069 * Sets a title composed of the URL and the title string.
2070 * @param url The URL of the site being loaded.
2071 * @param title The title of the site being loaded.
2072 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07002073 void setUrlTitle(String url, String title) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002074 mUrl = url;
2075 mTitle = title;
2076
Leon Scroggins58d56c62010-01-28 15:12:40 -05002077 // If we are in voice search mode, the title has already been set.
2078 if (mTabControl.getCurrentTab().isInVoiceSearchMode()) return;
2079 mTitleBar.setDisplayTitle(url);
2080 mFakeTitleBar.setDisplayTitle(url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002081 }
2082
2083 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08002084 * @param url The URL to build a title version of the URL from.
2085 * @return The title version of the URL or null if fails.
2086 * The title version of the URL can be either the URL hostname,
2087 * or the hostname with an "https://" prefix (for secure URLs),
2088 * or an empty string if, for example, the URL in question is a
2089 * file:// URL with no hostname.
2090 */
Leon Scroggins32e14a62009-06-11 10:26:34 -04002091 /* package */ static String buildTitleUrl(String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002092 String titleUrl = null;
2093
2094 if (url != null) {
2095 try {
2096 // parse the url string
2097 URL urlObj = new URL(url);
2098 if (urlObj != null) {
2099 titleUrl = "";
2100
2101 String protocol = urlObj.getProtocol();
2102 String host = urlObj.getHost();
2103
2104 if (host != null && 0 < host.length()) {
2105 titleUrl = host;
2106 if (protocol != null) {
2107 // if a secure site, add an "https://" prefix!
2108 if (protocol.equalsIgnoreCase("https")) {
2109 titleUrl = protocol + "://" + host;
2110 }
2111 }
2112 }
2113 }
2114 } catch (MalformedURLException e) {}
2115 }
2116
2117 return titleUrl;
2118 }
2119
2120 // Set the favicon in the title bar.
Grace Kloba22ac16e2009-10-07 18:00:23 -07002121 void setFavicon(Bitmap icon) {
Leon Scroggins68579392009-09-15 15:31:54 -04002122 mTitleBar.setFavicon(icon);
Leon Scrogginsfe87bd32009-10-06 10:10:00 -04002123 mFakeTitleBar.setFavicon(icon);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002124 }
2125
2126 /**
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002127 * Close the tab, remove its associated title bar, and adjust mTabControl's
2128 * current tab to a valid value.
Leon Scroggins1f005d32009-08-10 17:36:42 -04002129 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07002130 /* package */ void closeTab(Tab t) {
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002131 int currentIndex = mTabControl.getCurrentIndex();
2132 int removeIndex = mTabControl.getTabIndex(t);
Leon Scroggins1f005d32009-08-10 17:36:42 -04002133 mTabControl.removeTab(t);
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002134 if (currentIndex >= removeIndex && currentIndex != 0) {
2135 currentIndex--;
2136 }
2137 mTabControl.setCurrentTab(mTabControl.getTab(currentIndex));
Andrei Popescua5bf1de2009-09-23 16:39:23 +01002138 resetTitleIconAndProgress();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002139 }
2140
2141 private void goBackOnePageOrQuit() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002142 Tab current = mTabControl.getCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002143 if (current == null) {
2144 /*
2145 * Instead of finishing the activity, simply push this to the back
2146 * of the stack and let ActivityManager to choose the foreground
2147 * activity. As BrowserActivity is singleTask, it will be always the
2148 * root of the task. So we can use either true or false for
2149 * moveTaskToBack().
2150 */
2151 moveTaskToBack(true);
Grace Kloba00d85e72009-09-23 18:50:05 -07002152 return;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002153 }
2154 WebView w = current.getWebView();
2155 if (w.canGoBack()) {
2156 w.goBack();
2157 } else {
2158 // Check to see if we are closing a window that was created by
2159 // another window. If so, we switch back to that window.
Grace Kloba22ac16e2009-10-07 18:00:23 -07002160 Tab parent = current.getParentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002161 if (parent != null) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04002162 switchToTab(mTabControl.getTabIndex(parent));
2163 // Now we close the other tab
2164 closeTab(current);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002165 } else {
2166 if (current.closeOnExit()) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002167 // force the tab's inLoad() to be false as we are going to
2168 // either finish the activity or remove the tab. This will
2169 // ensure pauseWebViewTimers() taking action.
2170 mTabControl.getCurrentTab().clearInLoad();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002171 if (mTabControl.getTabCount() == 1) {
2172 finish();
2173 return;
2174 }
Mike Reed7bfa63b2009-05-28 11:08:32 -04002175 // call pauseWebViewTimers() now, we won't be able to call
2176 // it in onPause() as the WebView won't be valid.
Grace Klobaec1b5ad2009-08-18 08:42:32 -07002177 // Temporarily change mActivityInPause to be true as
2178 // pauseWebViewTimers() will do nothing if mActivityInPause
2179 // is false.
Grace Kloba918e1d72009-08-13 14:55:06 -07002180 boolean savedState = mActivityInPause;
2181 if (savedState) {
Grace Klobaec1b5ad2009-08-18 08:42:32 -07002182 Log.e(LOGTAG, "BrowserActivity is already paused "
2183 + "while handing goBackOnePageOrQuit.");
Grace Kloba918e1d72009-08-13 14:55:06 -07002184 }
2185 mActivityInPause = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -04002186 pauseWebViewTimers();
Grace Kloba918e1d72009-08-13 14:55:06 -07002187 mActivityInPause = savedState;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002188 removeTabFromContentView(current);
2189 mTabControl.removeTab(current);
2190 }
2191 /*
2192 * Instead of finishing the activity, simply push this to the back
2193 * of the stack and let ActivityManager to choose the foreground
2194 * activity. As BrowserActivity is singleTask, it will be always the
2195 * root of the task. So we can use either true or false for
2196 * moveTaskToBack().
2197 */
2198 moveTaskToBack(true);
2199 }
2200 }
2201 }
2202
Grace Kloba22ac16e2009-10-07 18:00:23 -07002203 boolean isMenuDown() {
2204 return mMenuIsDown;
2205 }
2206
Grace Kloba5942df02009-09-18 11:48:29 -07002207 @Override
2208 public boolean onKeyDown(int keyCode, KeyEvent event) {
Leon Scrogginsf65b50d2009-12-08 10:44:28 -05002209 // Even if MENU is already held down, we need to call to super to open
2210 // the IME on long press.
2211 if (KeyEvent.KEYCODE_MENU == keyCode) {
2212 mMenuIsDown = true;
2213 return super.onKeyDown(keyCode, event);
2214 }
Grace Kloba5942df02009-09-18 11:48:29 -07002215 // The default key mode is DEFAULT_KEYS_SEARCH_LOCAL. As the MENU is
2216 // still down, we don't want to trigger the search. Pretend to consume
2217 // the key and do nothing.
2218 if (mMenuIsDown) return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002219
Grace Kloba5942df02009-09-18 11:48:29 -07002220 switch(keyCode) {
Grace Kloba5942df02009-09-18 11:48:29 -07002221 case KeyEvent.KEYCODE_SPACE:
Grace Klobada0fe552009-09-22 18:17:24 -07002222 // WebView/WebTextView handle the keys in the KeyDown. As
2223 // the Activity's shortcut keys are only handled when WebView
2224 // doesn't, have to do it in onKeyDown instead of onKeyUp.
2225 if (event.isShiftPressed()) {
2226 getTopWindow().pageUp(false);
2227 } else {
2228 getTopWindow().pageDown(false);
2229 }
Grace Kloba5942df02009-09-18 11:48:29 -07002230 return true;
2231 case KeyEvent.KEYCODE_BACK:
2232 if (event.getRepeatCount() == 0) {
2233 event.startTracking();
2234 return true;
2235 } else if (mCustomView == null && mActiveTabsPage == null
2236 && event.isLongPress()) {
2237 bookmarksOrHistoryPicker(true);
2238 return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002239 }
Grace Kloba5942df02009-09-18 11:48:29 -07002240 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002241 }
Grace Kloba5942df02009-09-18 11:48:29 -07002242 return super.onKeyDown(keyCode, event);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002243 }
2244
Grace Kloba5942df02009-09-18 11:48:29 -07002245 @Override
2246 public boolean onKeyUp(int keyCode, KeyEvent event) {
2247 switch(keyCode) {
2248 case KeyEvent.KEYCODE_MENU:
2249 mMenuIsDown = false;
2250 break;
Grace Kloba5942df02009-09-18 11:48:29 -07002251 case KeyEvent.KEYCODE_BACK:
2252 if (event.isTracking() && !event.isCanceled()) {
2253 if (mCustomView != null) {
2254 // if a custom view is showing, hide it
Grace Kloba22ac16e2009-10-07 18:00:23 -07002255 mTabControl.getCurrentWebView().getWebChromeClient()
2256 .onHideCustomView();
Grace Kloba5942df02009-09-18 11:48:29 -07002257 } else if (mActiveTabsPage != null) {
2258 // if tab page is showing, hide it
2259 removeActiveTabPage(true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002260 } else {
Grace Kloba5942df02009-09-18 11:48:29 -07002261 WebView subwindow = mTabControl.getCurrentSubWindow();
2262 if (subwindow != null) {
2263 if (subwindow.canGoBack()) {
2264 subwindow.goBack();
2265 } else {
2266 dismissSubWindow(mTabControl.getCurrentTab());
2267 }
2268 } else {
2269 goBackOnePageOrQuit();
2270 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002271 }
Grace Kloba5942df02009-09-18 11:48:29 -07002272 return true;
2273 }
2274 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002275 }
Grace Kloba5942df02009-09-18 11:48:29 -07002276 return super.onKeyUp(keyCode, event);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002277 }
2278
Leon Scroggins68579392009-09-15 15:31:54 -04002279 /* package */ void stopLoading() {
Ben Murdochb7cc8b42009-09-28 10:59:09 +01002280 mDidStopLoad = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002281 resetTitleAndRevertLockIcon();
2282 WebView w = getTopWindow();
2283 w.stopLoading();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002284 // FIXME: before refactor, it is using mWebViewClient. So I keep the
2285 // same logic here. But for subwindow case, should we call into the main
2286 // WebView's onPageFinished as we never call its onPageStarted and if
2287 // the page finishes itself, we don't call onPageFinished.
2288 mTabControl.getCurrentWebView().getWebViewClient().onPageFinished(w,
2289 w.getUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08002290
2291 cancelStopToast();
2292 mStopToast = Toast
2293 .makeText(this, R.string.stopping, Toast.LENGTH_SHORT);
2294 mStopToast.show();
2295 }
2296
Grace Kloba22ac16e2009-10-07 18:00:23 -07002297 boolean didUserStopLoading() {
2298 return mDidStopLoad;
2299 }
2300
The Android Open Source Project0c908882009-03-03 19:32:16 -08002301 private void cancelStopToast() {
2302 if (mStopToast != null) {
2303 mStopToast.cancel();
2304 mStopToast = null;
2305 }
2306 }
2307
Grace Kloba22ac16e2009-10-07 18:00:23 -07002308 // called by a UI or non-UI thread to post the message
2309 public void postMessage(int what, int arg1, int arg2, Object obj,
2310 long delayMillis) {
2311 mHandler.sendMessageDelayed(mHandler.obtainMessage(what, arg1, arg2,
2312 obj), delayMillis);
2313 }
2314
2315 // called by a UI or non-UI thread to remove the message
2316 void removeMessages(int what, Object object) {
2317 mHandler.removeMessages(what, object);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002318 }
2319
2320 // public message ids
2321 public final static int LOAD_URL = 1001;
2322 public final static int STOP_LOAD = 1002;
2323
2324 // Message Ids
2325 private static final int FOCUS_NODE_HREF = 102;
2326 private static final int CANCEL_CREDS_REQUEST = 103;
Grace Kloba92c18a52009-07-31 23:48:32 -07002327 private static final int RELEASE_WAKELOCK = 107;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002328
Grace Kloba22ac16e2009-10-07 18:00:23 -07002329 static final int UPDATE_BOOKMARK_THUMBNAIL = 108;
Ben Murdoch2694e232009-09-29 09:41:11 +01002330
The Android Open Source Project0c908882009-03-03 19:32:16 -08002331 // Private handler for handling javascript and saving passwords
2332 private Handler mHandler = new Handler() {
2333
2334 public void handleMessage(Message msg) {
2335 switch (msg.what) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002336 case FOCUS_NODE_HREF:
Ben Murdoch2694e232009-09-29 09:41:11 +01002337 {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002338 String url = (String) msg.getData().get("url");
Ben Murdoch90d088c2009-11-17 18:14:04 +00002339 String title = (String) msg.getData().get("title");
The Android Open Source Project0c908882009-03-03 19:32:16 -08002340 if (url == null || url.length() == 0) {
2341 break;
2342 }
2343 HashMap focusNodeMap = (HashMap) msg.obj;
2344 WebView view = (WebView) focusNodeMap.get("webview");
2345 // Only apply the action if the top window did not change.
2346 if (getTopWindow() != view) {
2347 break;
2348 }
2349 switch (msg.arg1) {
2350 case R.id.open_context_menu_id:
2351 case R.id.view_image_context_menu_id:
2352 loadURL(getTopWindow(), url);
2353 break;
2354 case R.id.open_newtab_context_menu_id:
Grace Kloba22ac16e2009-10-07 18:00:23 -07002355 final Tab parent = mTabControl.getCurrentTab();
2356 final Tab newTab = openTab(url);
Grace Klobac9181842009-04-14 08:53:22 -07002357 if (newTab != parent) {
2358 parent.addChildTab(newTab);
2359 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002360 break;
2361 case R.id.bookmark_context_menu_id:
2362 Intent intent = new Intent(BrowserActivity.this,
2363 AddBookmarkPage.class);
2364 intent.putExtra("url", url);
Ben Murdoch90d088c2009-11-17 18:14:04 +00002365 intent.putExtra("title", title);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002366 startActivity(intent);
2367 break;
2368 case R.id.share_link_context_menu_id:
Leon Scroggins96afcb12009-12-10 12:35:56 -05002369 // See if this site has been visited before
2370 StringBuilder sb = new StringBuilder(
2371 Browser.BookmarkColumns.URL + " = ");
2372 DatabaseUtils.appendEscapedSQLString(sb, url);
2373 Cursor c = mResolver.query(Browser.BOOKMARKS_URI,
2374 Browser.HISTORY_PROJECTION,
2375 sb.toString(),
2376 null,
2377 null);
2378 if (c.moveToFirst()) {
2379 // The site has been visited before, so grab the
2380 // info from the database.
2381 Bitmap favicon = null;
2382 Bitmap thumbnail = null;
2383 String linkTitle = c.getString(Browser.
2384 HISTORY_PROJECTION_TITLE_INDEX);
2385 byte[] data = c.getBlob(Browser.
2386 HISTORY_PROJECTION_FAVICON_INDEX);
2387 if (data != null) {
2388 favicon = BitmapFactory.decodeByteArray(
2389 data, 0, data.length);
2390 }
2391 data = c.getBlob(Browser.
2392 HISTORY_PROJECTION_THUMBNAIL_INDEX);
2393 if (data != null) {
2394 thumbnail = BitmapFactory.decodeByteArray(
2395 data, 0, data.length);
2396 }
2397 sharePage(BrowserActivity.this,
2398 linkTitle, url, favicon, thumbnail);
2399 } else {
2400 Browser.sendString(BrowserActivity.this, url,
2401 getString(
2402 R.string.choosertitle_sharevia));
2403 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002404 break;
2405 case R.id.copy_link_context_menu_id:
2406 copy(url);
2407 break;
2408 case R.id.save_link_context_menu_id:
2409 case R.id.download_context_menu_id:
2410 onDownloadStartNoStream(url, null, null, null, -1);
2411 break;
2412 }
2413 break;
Ben Murdoch2694e232009-09-29 09:41:11 +01002414 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002415
2416 case LOAD_URL:
2417 loadURL(getTopWindow(), (String) msg.obj);
2418 break;
2419
2420 case STOP_LOAD:
2421 stopLoading();
2422 break;
2423
2424 case CANCEL_CREDS_REQUEST:
2425 resumeAfterCredentials();
2426 break;
2427
The Android Open Source Project0c908882009-03-03 19:32:16 -08002428 case RELEASE_WAKELOCK:
2429 if (mWakeLock.isHeld()) {
2430 mWakeLock.release();
Grace Kloba5d0e02e2009-10-05 15:15:36 -07002431 // if we reach here, Browser should be still in the
2432 // background loading after WAKELOCK_TIMEOUT (5-min).
2433 // To avoid burning the battery, stop loading.
2434 mTabControl.stopAllLoading();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002435 }
2436 break;
Ben Murdoch2694e232009-09-29 09:41:11 +01002437
2438 case UPDATE_BOOKMARK_THUMBNAIL:
2439 WebView view = (WebView) msg.obj;
2440 if (view != null) {
2441 updateScreenshot(view);
2442 }
2443 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002444 }
2445 }
2446 };
2447
Leon Scroggins96afcb12009-12-10 12:35:56 -05002448 /**
2449 * Share a page, providing the title, url, favicon, and a screenshot. Uses
2450 * an {@link Intent} to launch the Activity chooser.
2451 * @param c Context used to launch a new Activity.
2452 * @param title Title of the page. Stored in the Intent with
2453 * {@link Browser#EXTRA_SHARE_TITLE}
2454 * @param url URL of the page. Stored in the Intent with
2455 * {@link Intent#EXTRA_TEXT}
2456 * @param favicon Bitmap of the favicon for the page. Stored in the Intent
2457 * with {@link Browser#EXTRA_SHARE_FAVICON}
2458 * @param screenshot Bitmap of a screenshot of the page. Stored in the
2459 * Intent with {@link Browser#EXTRA_SHARE_SCREENSHOT}
2460 */
2461 public static final void sharePage(Context c, String title, String url,
2462 Bitmap favicon, Bitmap screenshot) {
2463 Intent send = new Intent(Intent.ACTION_SEND);
2464 send.setType("text/plain");
2465 send.putExtra(Intent.EXTRA_TEXT, url);
2466 send.putExtra(Browser.EXTRA_SHARE_TITLE, title);
2467 send.putExtra(Browser.EXTRA_SHARE_FAVICON, favicon);
2468 send.putExtra(Browser.EXTRA_SHARE_SCREENSHOT, screenshot);
2469 try {
2470 c.startActivity(Intent.createChooser(send, c.getString(
2471 R.string.choosertitle_sharevia)));
2472 } catch(android.content.ActivityNotFoundException ex) {
2473 // if no app handles it, do nothing
2474 }
2475 }
2476
Leon Scroggins89c6d362009-07-15 16:54:37 -04002477 private void updateScreenshot(WebView view) {
2478 // If this is a bookmarked site, add a screenshot to the database.
2479 // FIXME: When should we update? Every time?
2480 // FIXME: Would like to make sure there is actually something to
2481 // draw, but the API for that (WebViewCore.pictureReady()) is not
2482 // currently accessible here.
Ben Murdochaac7aa62009-09-17 16:57:40 +01002483
Patrick Scott3918d442009-08-04 13:22:29 -04002484 ContentResolver cr = getContentResolver();
2485 final Cursor c = BrowserBookmarksAdapter.queryBookmarksForUrl(
Ben Murdochaac7aa62009-09-17 16:57:40 +01002486 cr, view.getOriginalUrl(), view.getUrl(), true);
Patrick Scott3918d442009-08-04 13:22:29 -04002487 if (c != null) {
Leon Scroggins89c6d362009-07-15 16:54:37 -04002488 boolean succeed = c.moveToFirst();
2489 ContentValues values = null;
2490 while (succeed) {
2491 if (values == null) {
2492 final ByteArrayOutputStream os
2493 = new ByteArrayOutputStream();
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002494 Bitmap bm = createScreenshot(view);
Leon Scroggins45800572009-09-29 16:38:47 -04002495 if (bm == null) {
2496 c.close();
2497 return;
2498 }
Leon Scroggins89c6d362009-07-15 16:54:37 -04002499 bm.compress(Bitmap.CompressFormat.PNG, 100, os);
2500 values = new ContentValues();
2501 values.put(Browser.BookmarkColumns.THUMBNAIL,
2502 os.toByteArray());
2503 }
2504 cr.update(ContentUris.withAppendedId(Browser.BOOKMARKS_URI,
2505 c.getInt(0)), values, null, null);
2506 succeed = c.moveToNext();
2507 }
2508 c.close();
2509 }
2510 }
2511
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002512 /**
Leon Scrogginsf8551612009-09-24 16:06:02 -04002513 * Values for the size of the thumbnail created when taking a screenshot.
2514 * Lazily initialized. Instead of using these directly, use
2515 * getDesiredThumbnailWidth() or getDesiredThumbnailHeight().
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002516 */
Leon Scrogginsf8551612009-09-24 16:06:02 -04002517 private static int THUMBNAIL_WIDTH = 0;
2518 private static int THUMBNAIL_HEIGHT = 0;
2519
2520 /**
2521 * Return the desired width for thumbnail screenshots, which are stored in
2522 * the database, and used on the bookmarks screen.
2523 * @param context Context for finding out the density of the screen.
2524 * @return int desired width for thumbnail screenshot.
2525 */
2526 /* package */ static int getDesiredThumbnailWidth(Context context) {
2527 if (THUMBNAIL_WIDTH == 0) {
2528 float density = context.getResources().getDisplayMetrics().density;
2529 THUMBNAIL_WIDTH = (int) (90 * density);
2530 THUMBNAIL_HEIGHT = (int) (80 * density);
2531 }
2532 return THUMBNAIL_WIDTH;
2533 }
2534
2535 /**
2536 * Return the desired height for thumbnail screenshots, which are stored in
2537 * the database, and used on the bookmarks screen.
2538 * @param context Context for finding out the density of the screen.
2539 * @return int desired height for thumbnail screenshot.
2540 */
2541 /* package */ static int getDesiredThumbnailHeight(Context context) {
2542 // To ensure that they are both initialized.
2543 getDesiredThumbnailWidth(context);
2544 return THUMBNAIL_HEIGHT;
2545 }
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002546
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002547 private Bitmap createScreenshot(WebView view) {
2548 Picture thumbnail = view.capturePicture();
Leon Scroggins45800572009-09-29 16:38:47 -04002549 if (thumbnail == null) {
2550 return null;
2551 }
Leon Scrogginsf8551612009-09-24 16:06:02 -04002552 Bitmap bm = Bitmap.createBitmap(getDesiredThumbnailWidth(this),
2553 getDesiredThumbnailHeight(this), Bitmap.Config.ARGB_4444);
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002554 Canvas canvas = new Canvas(bm);
2555 // May need to tweak these values to determine what is the
2556 // best scale factor
Ben Murdoch2694e232009-09-29 09:41:11 +01002557 int thumbnailWidth = thumbnail.getWidth();
Ben Murdochae59c3f2009-10-20 18:30:28 +01002558 int thumbnailHeight = thumbnail.getHeight();
2559 float scaleFactorX = 1.0f;
2560 float scaleFactorY = 1.0f;
Ben Murdoch2694e232009-09-29 09:41:11 +01002561 if (thumbnailWidth > 0) {
Ben Murdochae59c3f2009-10-20 18:30:28 +01002562 scaleFactorX = (float) getDesiredThumbnailWidth(this) /
Ben Murdoch2694e232009-09-29 09:41:11 +01002563 (float)thumbnailWidth;
Ben Murdochae59c3f2009-10-20 18:30:28 +01002564 } else {
2565 return null;
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002566 }
Ben Murdochae59c3f2009-10-20 18:30:28 +01002567
2568 if (view.getWidth() > view.getHeight() &&
2569 thumbnailHeight < view.getHeight() && thumbnailHeight > 0) {
2570 // If the device is in landscape and the page is shorter
2571 // than the height of the view, stretch the thumbnail to fill the
2572 // space.
2573 scaleFactorY = (float) getDesiredThumbnailHeight(this) /
2574 (float)thumbnailHeight;
2575 } else {
2576 // In the portrait case, this looks nice.
2577 scaleFactorY = scaleFactorX;
2578 }
2579
2580 canvas.scale(scaleFactorX, scaleFactorY);
2581
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002582 thumbnail.draw(canvas);
2583 return bm;
2584 }
2585
The Android Open Source Project0c908882009-03-03 19:32:16 -08002586 // -------------------------------------------------------------------------
Grace Kloba22ac16e2009-10-07 18:00:23 -07002587 // Helper function for WebViewClient.
The Android Open Source Project0c908882009-03-03 19:32:16 -08002588 //-------------------------------------------------------------------------
2589
2590 // Use in overrideUrlLoading
2591 /* package */ final static String SCHEME_WTAI = "wtai://wp/";
2592 /* package */ final static String SCHEME_WTAI_MC = "wtai://wp/mc;";
2593 /* package */ final static String SCHEME_WTAI_SD = "wtai://wp/sd;";
2594 /* package */ final static String SCHEME_WTAI_AP = "wtai://wp/ap;";
2595
Grace Kloba22ac16e2009-10-07 18:00:23 -07002596 void onPageStarted(WebView view, String url, Bitmap favicon) {
2597 // when BrowserActivity just starts, onPageStarted may be called before
2598 // onResume as it is triggered from onCreate. Call resumeWebViewTimers
2599 // to start the timer. As we won't switch tabs while an activity is in
2600 // pause state, we can ensure calling resume and pause in pair.
2601 if (mActivityInPause) resumeWebViewTimers();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002602
Grace Kloba22ac16e2009-10-07 18:00:23 -07002603 resetLockIcon(url);
2604 setUrlTitle(url, null);
2605 setFavicon(favicon);
Leon Scroggins8cf8f682009-11-04 11:13:50 -08002606 // Keep this initial progress in sync with initialProgressValue (* 100)
2607 // in ProgressTracker.cpp
2608 // Show some progress so that the user knows the page is beginning to
2609 // load
2610 onProgressChanged(view, 10);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002611 mDidStopLoad = false;
Grace Kloba22ac16e2009-10-07 18:00:23 -07002612 if (!mIsNetworkUp) createAndShowNetworkDialog();
Patrick Scott15525d42009-09-21 13:39:37 -04002613
Grace Kloba22ac16e2009-10-07 18:00:23 -07002614 if (mSettings.isTracing()) {
2615 String host;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002616 try {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002617 WebAddress uri = new WebAddress(url);
2618 host = uri.mHost;
2619 } catch (android.net.ParseException ex) {
2620 host = "browser";
The Android Open Source Project0c908882009-03-03 19:32:16 -08002621 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002622 host = host.replace('.', '_');
2623 host += ".trace";
2624 mInTrace = true;
2625 Debug.startMethodTracing(host, 20 * 1024 * 1024);
2626 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002627
Grace Kloba22ac16e2009-10-07 18:00:23 -07002628 // Performance probe
2629 if (false) {
2630 mStart = SystemClock.uptimeMillis();
2631 mProcessStart = Process.getElapsedCpuTime();
2632 long[] sysCpu = new long[7];
2633 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2634 sysCpu, null)) {
2635 mUserStart = sysCpu[0] + sysCpu[1];
2636 mSystemStart = sysCpu[2];
2637 mIdleStart = sysCpu[3];
2638 mIrqStart = sysCpu[4] + sysCpu[5] + sysCpu[6];
2639 }
2640 mUiStart = SystemClock.currentThreadTimeMillis();
2641 }
2642 }
2643
2644 void onPageFinished(WebView view, String url) {
2645 // Reset the title and icon in case we stopped a provisional load.
2646 resetTitleAndIcon(view);
2647 // Update the lock icon image only once we are done loading
2648 updateLockIconToLatest();
2649 // pause the WebView timer and release the wake lock if it is finished
2650 // while BrowserActivity is in pause state.
2651 if (mActivityInPause && pauseWebViewTimers()) {
2652 if (mWakeLock.isHeld()) {
2653 mHandler.removeMessages(RELEASE_WAKELOCK);
2654 mWakeLock.release();
2655 }
2656 }
2657
2658 // Performance probe
2659 if (false) {
2660 long[] sysCpu = new long[7];
2661 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2662 sysCpu, null)) {
2663 String uiInfo = "UI thread used "
2664 + (SystemClock.currentThreadTimeMillis() - mUiStart)
2665 + " ms";
2666 if (LOGD_ENABLED) {
2667 Log.d(LOGTAG, uiInfo);
2668 }
2669 //The string that gets written to the log
2670 String performanceString = "It took total "
2671 + (SystemClock.uptimeMillis() - mStart)
2672 + " ms clock time to load the page."
2673 + "\nbrowser process used "
2674 + (Process.getElapsedCpuTime() - mProcessStart)
2675 + " ms, user processes used "
2676 + (sysCpu[0] + sysCpu[1] - mUserStart) * 10
2677 + " ms, kernel used "
2678 + (sysCpu[2] - mSystemStart) * 10
2679 + " ms, idle took " + (sysCpu[3] - mIdleStart) * 10
2680 + " ms and irq took "
2681 + (sysCpu[4] + sysCpu[5] + sysCpu[6] - mIrqStart)
2682 * 10 + " ms, " + uiInfo;
2683 if (LOGD_ENABLED) {
2684 Log.d(LOGTAG, performanceString + "\nWebpage: " + url);
2685 }
2686 if (url != null) {
2687 // strip the url to maintain consistency
2688 String newUrl = new String(url);
2689 if (newUrl.startsWith("http://www.")) {
2690 newUrl = newUrl.substring(11);
2691 } else if (newUrl.startsWith("http://")) {
2692 newUrl = newUrl.substring(7);
2693 } else if (newUrl.startsWith("https://www.")) {
2694 newUrl = newUrl.substring(12);
2695 } else if (newUrl.startsWith("https://")) {
2696 newUrl = newUrl.substring(8);
2697 }
2698 if (LOGD_ENABLED) {
2699 Log.d(LOGTAG, newUrl + " loaded");
2700 }
Grace Kloba5b078b52009-06-24 20:23:41 -07002701 }
2702 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002703 }
Grace Kloba5b078b52009-06-24 20:23:41 -07002704
Grace Kloba22ac16e2009-10-07 18:00:23 -07002705 if (mInTrace) {
2706 mInTrace = false;
2707 Debug.stopMethodTracing();
2708 }
2709 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002710
Grace Kloba22ac16e2009-10-07 18:00:23 -07002711 boolean shouldOverrideUrlLoading(WebView view, String url) {
2712 if (url.startsWith(SCHEME_WTAI)) {
2713 // wtai://wp/mc;number
2714 // number=string(phone-number)
2715 if (url.startsWith(SCHEME_WTAI_MC)) {
2716 Intent intent = new Intent(Intent.ACTION_VIEW,
2717 Uri.parse(WebView.SCHEME_TEL +
2718 url.substring(SCHEME_WTAI_MC.length())));
2719 startActivity(intent);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002720 return true;
2721 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002722 // wtai://wp/sd;dtmf
2723 // dtmf=string(dialstring)
2724 if (url.startsWith(SCHEME_WTAI_SD)) {
2725 // TODO: only send when there is active voice connection
2726 return false;
2727 }
2728 // wtai://wp/ap;number;name
2729 // number=string(phone-number)
2730 // name=string
2731 if (url.startsWith(SCHEME_WTAI_AP)) {
2732 // TODO
2733 return false;
2734 }
2735 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002736
Grace Kloba22ac16e2009-10-07 18:00:23 -07002737 // The "about:" schemes are internal to the browser; don't want these to
2738 // be dispatched to other apps.
2739 if (url.startsWith("about:")) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002740 return false;
2741 }
2742
Grace Kloba22ac16e2009-10-07 18:00:23 -07002743 Intent intent;
2744 // perform generic parsing of the URI to turn it into an Intent.
2745 try {
2746 intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME);
2747 } catch (URISyntaxException ex) {
2748 Log.w("Browser", "Bad URI " + url + ": " + ex.getMessage());
2749 return false;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002750 }
2751
Grace Kloba22ac16e2009-10-07 18:00:23 -07002752 // check whether the intent can be resolved. If not, we will see
2753 // whether we can download it from the Market.
2754 if (getPackageManager().resolveActivity(intent, 0) == null) {
2755 String packagename = intent.getPackage();
2756 if (packagename != null) {
2757 intent = new Intent(Intent.ACTION_VIEW, Uri
2758 .parse("market://search?q=pname:" + packagename));
2759 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2760 startActivity(intent);
2761 return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002762 } else {
2763 return false;
2764 }
2765 }
2766
Grace Kloba22ac16e2009-10-07 18:00:23 -07002767 // sanitize the Intent, ensuring web pages can not bypass browser
2768 // security (only access to BROWSABLE activities).
2769 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2770 intent.setComponent(null);
2771 try {
2772 if (startActivityIfNeeded(intent, -1)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002773 return true;
2774 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002775 } catch (ActivityNotFoundException ex) {
2776 // ignore the error. If no application can handle the URL,
2777 // eg about:blank, assume the browser can handle it.
2778 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002779
Grace Kloba22ac16e2009-10-07 18:00:23 -07002780 if (mMenuIsDown) {
2781 openTab(url);
2782 closeOptionsMenu();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002783 return true;
2784 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002785 return false;
2786 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002787
Grace Kloba22ac16e2009-10-07 18:00:23 -07002788 // -------------------------------------------------------------------------
2789 // Helper function for WebChromeClient
2790 // -------------------------------------------------------------------------
The Android Open Source Project0c908882009-03-03 19:32:16 -08002791
Grace Kloba22ac16e2009-10-07 18:00:23 -07002792 void onProgressChanged(WebView view, int newProgress) {
2793 mTitleBar.setProgress(newProgress);
2794 mFakeTitleBar.setProgress(newProgress);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002795
Grace Kloba22ac16e2009-10-07 18:00:23 -07002796 if (newProgress == 100) {
2797 // onProgressChanged() may continue to be called after the main
2798 // frame has finished loading, as any remaining sub frames continue
2799 // to load. We'll only get called once though with newProgress as
2800 // 100 when everything is loaded. (onPageFinished is called once
2801 // when the main frame completes loading regardless of the state of
2802 // any sub frames so calls to onProgressChanges may continue after
2803 // onPageFinished has executed)
2804 if (mInLoad) {
2805 mInLoad = false;
Leon Scrogginsa27ff192009-09-14 12:58:04 -04002806 updateInLoadMenuItems();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002807 // If the options menu is open, leave the title bar
2808 if (!mOptionsMenuOpen || !mIconView) {
2809 hideFakeTitleBar();
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07002810 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002811 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002812 } else if (!mInLoad) {
2813 // onPageFinished may have already been called but a subframe is
2814 // still loading and updating the progress. Reset mInLoad and update
2815 // the menu items.
2816 mInLoad = true;
2817 updateInLoadMenuItems();
2818 if (!mOptionsMenuOpen || mIconView) {
2819 // This page has begun to load, so show the title bar
2820 showFakeTitleBar();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002821 }
2822 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002823 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002824
Grace Kloba22ac16e2009-10-07 18:00:23 -07002825 void onShowCustomView(View view, WebChromeClient.CustomViewCallback callback) {
Derek Sollenberger8ff57db2009-12-08 15:39:55 -05002826 // if a view already exists then immediately terminate the new one
2827 if (mCustomView != null) {
2828 callback.onCustomViewHidden();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002829 return;
Derek Sollenberger8ff57db2009-12-08 15:39:55 -05002830 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002831
2832 // Add the custom view to its container.
2833 mCustomViewContainer.addView(view, COVER_SCREEN_GRAVITY_CENTER);
2834 mCustomView = view;
2835 mCustomViewCallback = callback;
2836 // Save the menu state and set it to empty while the custom
2837 // view is showing.
2838 mOldMenuState = mMenuState;
2839 mMenuState = EMPTY_MENU;
2840 // Hide the content view.
2841 mContentView.setVisibility(View.GONE);
2842 // Finally show the custom view container.
Andrei Popescu163ab742009-10-20 17:58:23 +01002843 setStatusBarVisibility(false);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002844 mCustomViewContainer.setVisibility(View.VISIBLE);
2845 mCustomViewContainer.bringToFront();
2846 }
2847
2848 void onHideCustomView() {
2849 if (mCustomView == null)
2850 return;
2851
2852 // Hide the custom view.
2853 mCustomView.setVisibility(View.GONE);
2854 // Remove the custom view from its container.
2855 mCustomViewContainer.removeView(mCustomView);
2856 mCustomView = null;
2857 // Reset the old menu state.
2858 mMenuState = mOldMenuState;
2859 mOldMenuState = EMPTY_MENU;
2860 mCustomViewContainer.setVisibility(View.GONE);
2861 mCustomViewCallback.onCustomViewHidden();
2862 // Show the content view.
Andrei Popescu163ab742009-10-20 17:58:23 +01002863 setStatusBarVisibility(true);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002864 mContentView.setVisibility(View.VISIBLE);
2865 }
2866
2867 Bitmap getDefaultVideoPoster() {
2868 if (mDefaultVideoPoster == null) {
2869 mDefaultVideoPoster = BitmapFactory.decodeResource(
2870 getResources(), R.drawable.default_video_poster);
Patrick Scott3918d442009-08-04 13:22:29 -04002871 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002872 return mDefaultVideoPoster;
2873 }
Patrick Scott3918d442009-08-04 13:22:29 -04002874
Grace Kloba22ac16e2009-10-07 18:00:23 -07002875 View getVideoLoadingProgressView() {
2876 if (mVideoProgressView == null) {
2877 LayoutInflater inflater = LayoutInflater.from(BrowserActivity.this);
2878 mVideoProgressView = inflater.inflate(
2879 R.layout.video_loading_progress, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002880 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002881 return mVideoProgressView;
2882 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002883
Leon Scroggins8d5fa432009-10-02 15:55:59 -04002884 /*
2885 * The Object used to inform the WebView of the file to upload.
2886 */
2887 private ValueCallback<Uri> mUploadMessage;
2888
Grace Kloba22ac16e2009-10-07 18:00:23 -07002889 void openFileChooser(ValueCallback<Uri> uploadMsg) {
2890 if (mUploadMessage != null) return;
2891 mUploadMessage = uploadMsg;
2892 Intent i = new Intent(Intent.ACTION_GET_CONTENT);
2893 i.addCategory(Intent.CATEGORY_OPENABLE);
2894 i.setType("*/*");
2895 BrowserActivity.this.startActivityForResult(Intent.createChooser(i,
2896 getString(R.string.choose_upload)), FILE_SELECTED);
2897 }
2898
2899 // -------------------------------------------------------------------------
2900 // Implement functions for DownloadListener
2901 // -------------------------------------------------------------------------
2902
The Android Open Source Project0c908882009-03-03 19:32:16 -08002903 /**
2904 * Notify the host application a download should be done, or that
2905 * the data should be streamed if a streaming viewer is available.
2906 * @param url The full url to the content that should be downloaded
2907 * @param contentDisposition Content-disposition http header, if
2908 * present.
2909 * @param mimetype The mimetype of the content reported by the server
2910 * @param contentLength The file size reported by the server
2911 */
2912 public void onDownloadStart(String url, String userAgent,
2913 String contentDisposition, String mimetype, long contentLength) {
2914 // if we're dealing wih A/V content that's not explicitly marked
2915 // for download, check if it's streamable.
2916 if (contentDisposition == null
Patrick Scotte1fb9662009-08-31 14:31:52 -04002917 || !contentDisposition.regionMatches(
2918 true, 0, "attachment", 0, 10)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002919 // query the package manager to see if there's a registered handler
2920 // that matches.
2921 Intent intent = new Intent(Intent.ACTION_VIEW);
2922 intent.setDataAndType(Uri.parse(url), mimetype);
Patrick Scotte1fb9662009-08-31 14:31:52 -04002923 ResolveInfo info = getPackageManager().resolveActivity(intent,
2924 PackageManager.MATCH_DEFAULT_ONLY);
2925 if (info != null) {
2926 ComponentName myName = getComponentName();
2927 // If we resolved to ourselves, we don't want to attempt to
2928 // load the url only to try and download it again.
2929 if (!myName.getPackageName().equals(
2930 info.activityInfo.packageName)
2931 || !myName.getClassName().equals(
2932 info.activityInfo.name)) {
2933 // someone (other than us) knows how to handle this mime
2934 // type with this scheme, don't download.
2935 try {
2936 startActivity(intent);
2937 return;
2938 } catch (ActivityNotFoundException ex) {
2939 if (LOGD_ENABLED) {
2940 Log.d(LOGTAG, "activity not found for " + mimetype
2941 + " over " + Uri.parse(url).getScheme(),
2942 ex);
2943 }
2944 // Best behavior is to fall back to a download in this
2945 // case
The Android Open Source Project0c908882009-03-03 19:32:16 -08002946 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002947 }
2948 }
2949 }
2950 onDownloadStartNoStream(url, userAgent, contentDisposition, mimetype, contentLength);
2951 }
2952
2953 /**
2954 * Notify the host application a download should be done, even if there
2955 * is a streaming viewer available for thise type.
2956 * @param url The full url to the content that should be downloaded
2957 * @param contentDisposition Content-disposition http header, if
2958 * present.
2959 * @param mimetype The mimetype of the content reported by the server
2960 * @param contentLength The file size reported by the server
2961 */
2962 /*package */ void onDownloadStartNoStream(String url, String userAgent,
2963 String contentDisposition, String mimetype, long contentLength) {
2964
2965 String filename = URLUtil.guessFileName(url,
2966 contentDisposition, mimetype);
2967
2968 // Check to see if we have an SDCard
2969 String status = Environment.getExternalStorageState();
2970 if (!status.equals(Environment.MEDIA_MOUNTED)) {
2971 int title;
2972 String msg;
2973
2974 // Check to see if the SDCard is busy, same as the music app
2975 if (status.equals(Environment.MEDIA_SHARED)) {
2976 msg = getString(R.string.download_sdcard_busy_dlg_msg);
2977 title = R.string.download_sdcard_busy_dlg_title;
2978 } else {
2979 msg = getString(R.string.download_no_sdcard_dlg_msg, filename);
2980 title = R.string.download_no_sdcard_dlg_title;
2981 }
2982
2983 new AlertDialog.Builder(this)
2984 .setTitle(title)
2985 .setIcon(android.R.drawable.ic_dialog_alert)
2986 .setMessage(msg)
2987 .setPositiveButton(R.string.ok, null)
2988 .show();
2989 return;
2990 }
2991
2992 // java.net.URI is a lot stricter than KURL so we have to undo
2993 // KURL's percent-encoding and redo the encoding using java.net.URI.
2994 URI uri = null;
2995 try {
2996 // Undo the percent-encoding that KURL may have done.
2997 String newUrl = new String(URLUtil.decode(url.getBytes()));
2998 // Parse the url into pieces
2999 WebAddress w = new WebAddress(newUrl);
3000 String frag = null;
3001 String query = null;
3002 String path = w.mPath;
3003 // Break the path into path, query, and fragment
3004 if (path.length() > 0) {
3005 // Strip the fragment
3006 int idx = path.lastIndexOf('#');
3007 if (idx != -1) {
3008 frag = path.substring(idx + 1);
3009 path = path.substring(0, idx);
3010 }
3011 idx = path.lastIndexOf('?');
3012 if (idx != -1) {
3013 query = path.substring(idx + 1);
3014 path = path.substring(0, idx);
3015 }
3016 }
3017 uri = new URI(w.mScheme, w.mAuthInfo, w.mHost, w.mPort, path,
3018 query, frag);
3019 } catch (Exception e) {
3020 Log.e(LOGTAG, "Could not parse url for download: " + url, e);
3021 return;
3022 }
3023
3024 // XXX: Have to use the old url since the cookies were stored using the
3025 // old percent-encoded url.
3026 String cookies = CookieManager.getInstance().getCookie(url);
3027
3028 ContentValues values = new ContentValues();
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08003029 values.put(Downloads.Impl.COLUMN_URI, uri.toString());
3030 values.put(Downloads.Impl.COLUMN_COOKIE_DATA, cookies);
3031 values.put(Downloads.Impl.COLUMN_USER_AGENT, userAgent);
3032 values.put(Downloads.Impl.COLUMN_NOTIFICATION_PACKAGE,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003033 getPackageName());
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08003034 values.put(Downloads.Impl.COLUMN_NOTIFICATION_CLASS,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003035 BrowserDownloadPage.class.getCanonicalName());
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08003036 values.put(Downloads.Impl.COLUMN_VISIBILITY,
3037 Downloads.Impl.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
3038 values.put(Downloads.Impl.COLUMN_MIME_TYPE, mimetype);
3039 values.put(Downloads.Impl.COLUMN_FILE_NAME_HINT, filename);
3040 values.put(Downloads.Impl.COLUMN_DESCRIPTION, uri.getHost());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003041 if (contentLength > 0) {
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08003042 values.put(Downloads.Impl.COLUMN_TOTAL_BYTES, contentLength);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003043 }
3044 if (mimetype == null) {
3045 // We must have long pressed on a link or image to download it. We
3046 // are not sure of the mimetype in this case, so do a head request
3047 new FetchUrlMimeType(this).execute(values);
3048 } else {
3049 final Uri contentUri =
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08003050 getContentResolver().insert(Downloads.Impl.CONTENT_URI, values);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003051 }
3052
3053 }
3054
Grace Kloba22ac16e2009-10-07 18:00:23 -07003055 // -------------------------------------------------------------------------
3056
The Android Open Source Project0c908882009-03-03 19:32:16 -08003057 /**
3058 * Resets the lock icon. This method is called when we start a new load and
3059 * know the url to be loaded.
3060 */
3061 private void resetLockIcon(String url) {
3062 // Save the lock-icon state (we revert to it if the load gets cancelled)
Grace Kloba22ac16e2009-10-07 18:00:23 -07003063 mTabControl.getCurrentTab().resetLockIcon(url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003064 updateLockIconImage(LOCK_ICON_UNSECURE);
3065 }
3066
The Android Open Source Project0c908882009-03-03 19:32:16 -08003067 /**
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04003068 * Update the lock icon to correspond to our latest state.
3069 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003070 private void updateLockIconToLatest() {
3071 updateLockIconImage(mTabControl.getCurrentTab().getLockIconType());
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04003072 }
3073
3074 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08003075 * Updates the lock-icon image in the title-bar.
3076 */
3077 private void updateLockIconImage(int lockIconType) {
3078 Drawable d = null;
3079 if (lockIconType == LOCK_ICON_SECURE) {
3080 d = mSecLockIcon;
3081 } else if (lockIconType == LOCK_ICON_MIXED) {
3082 d = mMixLockIcon;
3083 }
Leon Scroggins68579392009-09-15 15:31:54 -04003084 mTitleBar.setLock(d);
Leon Scrogginsfe87bd32009-10-06 10:10:00 -04003085 mFakeTitleBar.setLock(d);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003086 }
3087
3088 /**
3089 * Displays a page-info dialog.
3090 * @param tab The tab to show info about
3091 * @param fromShowSSLCertificateOnError The flag that indicates whether
3092 * this dialog was opened from the SSL-certificate-on-error dialog or
3093 * not. This is important, since we need to know whether to return to
3094 * the parent dialog or simply dismiss.
3095 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003096 private void showPageInfo(final Tab tab,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003097 final boolean fromShowSSLCertificateOnError) {
3098 final LayoutInflater factory = LayoutInflater
3099 .from(this);
3100
3101 final View pageInfoView = factory.inflate(R.layout.page_info, null);
3102
3103 final WebView view = tab.getWebView();
3104
3105 String url = null;
3106 String title = null;
3107
3108 if (view == null) {
3109 url = tab.getUrl();
3110 title = tab.getTitle();
3111 } else if (view == mTabControl.getCurrentWebView()) {
3112 // Use the cached title and url if this is the current WebView
3113 url = mUrl;
3114 title = mTitle;
3115 } else {
3116 url = view.getUrl();
3117 title = view.getTitle();
3118 }
3119
3120 if (url == null) {
3121 url = "";
3122 }
3123 if (title == null) {
3124 title = "";
3125 }
3126
3127 ((TextView) pageInfoView.findViewById(R.id.address)).setText(url);
3128 ((TextView) pageInfoView.findViewById(R.id.title)).setText(title);
3129
3130 mPageInfoView = tab;
Leon Scrogginsc7b92f82010-01-11 18:17:31 -05003131 mPageInfoFromShowSSLCertificateOnError = fromShowSSLCertificateOnError;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003132
3133 AlertDialog.Builder alertDialogBuilder =
3134 new AlertDialog.Builder(this)
3135 .setTitle(R.string.page_info).setIcon(android.R.drawable.ic_dialog_info)
3136 .setView(pageInfoView)
3137 .setPositiveButton(
3138 R.string.ok,
3139 new DialogInterface.OnClickListener() {
3140 public void onClick(DialogInterface dialog,
3141 int whichButton) {
3142 mPageInfoDialog = null;
3143 mPageInfoView = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003144
3145 // if we came here from the SSL error dialog
3146 if (fromShowSSLCertificateOnError) {
3147 // go back to the SSL error dialog
3148 showSSLCertificateOnError(
3149 mSSLCertificateOnErrorView,
3150 mSSLCertificateOnErrorHandler,
3151 mSSLCertificateOnErrorError);
3152 }
3153 }
3154 })
3155 .setOnCancelListener(
3156 new DialogInterface.OnCancelListener() {
3157 public void onCancel(DialogInterface dialog) {
3158 mPageInfoDialog = null;
3159 mPageInfoView = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003160
3161 // if we came here from the SSL error dialog
3162 if (fromShowSSLCertificateOnError) {
3163 // go back to the SSL error dialog
3164 showSSLCertificateOnError(
3165 mSSLCertificateOnErrorView,
3166 mSSLCertificateOnErrorHandler,
3167 mSSLCertificateOnErrorError);
3168 }
3169 }
3170 });
3171
3172 // if we have a main top-level page SSL certificate set or a certificate
3173 // error
3174 if (fromShowSSLCertificateOnError ||
3175 (view != null && view.getCertificate() != null)) {
3176 // add a 'View Certificate' button
3177 alertDialogBuilder.setNeutralButton(
3178 R.string.view_certificate,
3179 new DialogInterface.OnClickListener() {
3180 public void onClick(DialogInterface dialog,
3181 int whichButton) {
3182 mPageInfoDialog = null;
3183 mPageInfoView = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003184
3185 // if we came here from the SSL error dialog
3186 if (fromShowSSLCertificateOnError) {
3187 // go back to the SSL error dialog
3188 showSSLCertificateOnError(
3189 mSSLCertificateOnErrorView,
3190 mSSLCertificateOnErrorHandler,
3191 mSSLCertificateOnErrorError);
3192 } else {
3193 // otherwise, display the top-most certificate from
3194 // the chain
3195 if (view.getCertificate() != null) {
3196 showSSLCertificate(tab);
3197 }
3198 }
3199 }
3200 });
3201 }
3202
3203 mPageInfoDialog = alertDialogBuilder.show();
3204 }
3205
3206 /**
3207 * Displays the main top-level page SSL certificate dialog
3208 * (accessible from the Page-Info dialog).
3209 * @param tab The tab to show certificate for.
3210 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003211 private void showSSLCertificate(final Tab tab) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003212 final View certificateView =
3213 inflateCertificateView(tab.getWebView().getCertificate());
3214 if (certificateView == null) {
3215 return;
3216 }
3217
3218 LayoutInflater factory = LayoutInflater.from(this);
3219
3220 final LinearLayout placeholder =
3221 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3222
3223 LinearLayout ll = (LinearLayout) factory.inflate(
3224 R.layout.ssl_success, placeholder);
3225 ((TextView)ll.findViewById(R.id.success))
3226 .setText(R.string.ssl_certificate_is_valid);
3227
3228 mSSLCertificateView = tab;
3229 mSSLCertificateDialog =
3230 new AlertDialog.Builder(this)
3231 .setTitle(R.string.ssl_certificate).setIcon(
3232 R.drawable.ic_dialog_browser_certificate_secure)
3233 .setView(certificateView)
3234 .setPositiveButton(R.string.ok,
3235 new DialogInterface.OnClickListener() {
3236 public void onClick(DialogInterface dialog,
3237 int whichButton) {
3238 mSSLCertificateDialog = null;
3239 mSSLCertificateView = null;
3240
3241 showPageInfo(tab, false);
3242 }
3243 })
3244 .setOnCancelListener(
3245 new DialogInterface.OnCancelListener() {
3246 public void onCancel(DialogInterface dialog) {
3247 mSSLCertificateDialog = null;
3248 mSSLCertificateView = null;
3249
3250 showPageInfo(tab, false);
3251 }
3252 })
3253 .show();
3254 }
3255
3256 /**
3257 * Displays the SSL error certificate dialog.
3258 * @param view The target web-view.
3259 * @param handler The SSL error handler responsible for cancelling the
3260 * connection that resulted in an SSL error or proceeding per user request.
3261 * @param error The SSL error object.
3262 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003263 void showSSLCertificateOnError(
The Android Open Source Project0c908882009-03-03 19:32:16 -08003264 final WebView view, final SslErrorHandler handler, final SslError error) {
3265
3266 final View certificateView =
3267 inflateCertificateView(error.getCertificate());
3268 if (certificateView == null) {
3269 return;
3270 }
3271
3272 LayoutInflater factory = LayoutInflater.from(this);
3273
3274 final LinearLayout placeholder =
3275 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3276
3277 if (error.hasError(SslError.SSL_UNTRUSTED)) {
3278 LinearLayout ll = (LinearLayout)factory
3279 .inflate(R.layout.ssl_warning, placeholder);
3280 ((TextView)ll.findViewById(R.id.warning))
3281 .setText(R.string.ssl_untrusted);
3282 }
3283
3284 if (error.hasError(SslError.SSL_IDMISMATCH)) {
3285 LinearLayout ll = (LinearLayout)factory
3286 .inflate(R.layout.ssl_warning, placeholder);
3287 ((TextView)ll.findViewById(R.id.warning))
3288 .setText(R.string.ssl_mismatch);
3289 }
3290
3291 if (error.hasError(SslError.SSL_EXPIRED)) {
3292 LinearLayout ll = (LinearLayout)factory
3293 .inflate(R.layout.ssl_warning, placeholder);
3294 ((TextView)ll.findViewById(R.id.warning))
3295 .setText(R.string.ssl_expired);
3296 }
3297
3298 if (error.hasError(SslError.SSL_NOTYETVALID)) {
3299 LinearLayout ll = (LinearLayout)factory
3300 .inflate(R.layout.ssl_warning, placeholder);
3301 ((TextView)ll.findViewById(R.id.warning))
3302 .setText(R.string.ssl_not_yet_valid);
3303 }
3304
3305 mSSLCertificateOnErrorHandler = handler;
3306 mSSLCertificateOnErrorView = view;
3307 mSSLCertificateOnErrorError = error;
3308 mSSLCertificateOnErrorDialog =
3309 new AlertDialog.Builder(this)
3310 .setTitle(R.string.ssl_certificate).setIcon(
3311 R.drawable.ic_dialog_browser_certificate_partially_secure)
3312 .setView(certificateView)
3313 .setPositiveButton(R.string.ok,
3314 new DialogInterface.OnClickListener() {
3315 public void onClick(DialogInterface dialog,
3316 int whichButton) {
3317 mSSLCertificateOnErrorDialog = null;
3318 mSSLCertificateOnErrorView = null;
3319 mSSLCertificateOnErrorHandler = null;
3320 mSSLCertificateOnErrorError = null;
3321
Grace Kloba22ac16e2009-10-07 18:00:23 -07003322 view.getWebViewClient().onReceivedSslError(
3323 view, handler, error);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003324 }
3325 })
3326 .setNeutralButton(R.string.page_info_view,
3327 new DialogInterface.OnClickListener() {
3328 public void onClick(DialogInterface dialog,
3329 int whichButton) {
3330 mSSLCertificateOnErrorDialog = null;
3331
3332 // do not clear the dialog state: we will
3333 // need to show the dialog again once the
3334 // user is done exploring the page-info details
3335
3336 showPageInfo(mTabControl.getTabFromView(view),
3337 true);
3338 }
3339 })
3340 .setOnCancelListener(
3341 new DialogInterface.OnCancelListener() {
3342 public void onCancel(DialogInterface dialog) {
3343 mSSLCertificateOnErrorDialog = null;
3344 mSSLCertificateOnErrorView = null;
3345 mSSLCertificateOnErrorHandler = null;
3346 mSSLCertificateOnErrorError = null;
3347
Grace Kloba22ac16e2009-10-07 18:00:23 -07003348 view.getWebViewClient().onReceivedSslError(
3349 view, handler, error);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003350 }
3351 })
3352 .show();
3353 }
3354
3355 /**
3356 * Inflates the SSL certificate view (helper method).
3357 * @param certificate The SSL certificate.
3358 * @return The resultant certificate view with issued-to, issued-by,
3359 * issued-on, expires-on, and possibly other fields set.
3360 * If the input certificate is null, returns null.
3361 */
3362 private View inflateCertificateView(SslCertificate certificate) {
3363 if (certificate == null) {
3364 return null;
3365 }
3366
3367 LayoutInflater factory = LayoutInflater.from(this);
3368
3369 View certificateView = factory.inflate(
3370 R.layout.ssl_certificate, null);
3371
3372 // issued to:
3373 SslCertificate.DName issuedTo = certificate.getIssuedTo();
3374 if (issuedTo != null) {
3375 ((TextView) certificateView.findViewById(R.id.to_common))
3376 .setText(issuedTo.getCName());
3377 ((TextView) certificateView.findViewById(R.id.to_org))
3378 .setText(issuedTo.getOName());
3379 ((TextView) certificateView.findViewById(R.id.to_org_unit))
3380 .setText(issuedTo.getUName());
3381 }
3382
3383 // issued by:
3384 SslCertificate.DName issuedBy = certificate.getIssuedBy();
3385 if (issuedBy != null) {
3386 ((TextView) certificateView.findViewById(R.id.by_common))
3387 .setText(issuedBy.getCName());
3388 ((TextView) certificateView.findViewById(R.id.by_org))
3389 .setText(issuedBy.getOName());
3390 ((TextView) certificateView.findViewById(R.id.by_org_unit))
3391 .setText(issuedBy.getUName());
3392 }
3393
3394 // issued on:
3395 String issuedOn = reformatCertificateDate(
3396 certificate.getValidNotBefore());
3397 ((TextView) certificateView.findViewById(R.id.issued_on))
3398 .setText(issuedOn);
3399
3400 // expires on:
3401 String expiresOn = reformatCertificateDate(
3402 certificate.getValidNotAfter());
3403 ((TextView) certificateView.findViewById(R.id.expires_on))
3404 .setText(expiresOn);
3405
3406 return certificateView;
3407 }
3408
3409 /**
3410 * Re-formats the certificate date (Date.toString()) string to
3411 * a properly localized date string.
3412 * @return Properly localized version of the certificate date string and
3413 * the original certificate date string if fails to localize.
3414 * If the original string is null, returns an empty string "".
3415 */
3416 private String reformatCertificateDate(String certificateDate) {
3417 String reformattedDate = null;
3418
3419 if (certificateDate != null) {
3420 Date date = null;
3421 try {
3422 date = java.text.DateFormat.getInstance().parse(certificateDate);
3423 } catch (ParseException e) {
3424 date = null;
3425 }
3426
3427 if (date != null) {
3428 reformattedDate =
3429 DateFormat.getDateFormat(this).format(date);
3430 }
3431 }
3432
3433 return reformattedDate != null ? reformattedDate :
3434 (certificateDate != null ? certificateDate : "");
3435 }
3436
3437 /**
3438 * Displays an http-authentication dialog.
3439 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003440 void showHttpAuthentication(final HttpAuthHandler handler,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003441 final String host, final String realm, final String title,
3442 final String name, final String password, int focusId) {
3443 LayoutInflater factory = LayoutInflater.from(this);
3444 final View v = factory
3445 .inflate(R.layout.http_authentication, null);
3446 if (name != null) {
3447 ((EditText) v.findViewById(R.id.username_edit)).setText(name);
3448 }
3449 if (password != null) {
3450 ((EditText) v.findViewById(R.id.password_edit)).setText(password);
3451 }
3452
3453 String titleText = title;
3454 if (titleText == null) {
3455 titleText = getText(R.string.sign_in_to).toString().replace(
3456 "%s1", host).replace("%s2", realm);
3457 }
3458
3459 mHttpAuthHandler = handler;
3460 AlertDialog dialog = new AlertDialog.Builder(this)
3461 .setTitle(titleText)
3462 .setIcon(android.R.drawable.ic_dialog_alert)
3463 .setView(v)
3464 .setPositiveButton(R.string.action,
3465 new DialogInterface.OnClickListener() {
3466 public void onClick(DialogInterface dialog,
3467 int whichButton) {
3468 String nm = ((EditText) v
3469 .findViewById(R.id.username_edit))
3470 .getText().toString();
3471 String pw = ((EditText) v
3472 .findViewById(R.id.password_edit))
3473 .getText().toString();
3474 BrowserActivity.this.setHttpAuthUsernamePassword
3475 (host, realm, nm, pw);
3476 handler.proceed(nm, pw);
3477 mHttpAuthenticationDialog = null;
3478 mHttpAuthHandler = null;
3479 }})
3480 .setNegativeButton(R.string.cancel,
3481 new DialogInterface.OnClickListener() {
3482 public void onClick(DialogInterface dialog,
3483 int whichButton) {
3484 handler.cancel();
3485 BrowserActivity.this.resetTitleAndRevertLockIcon();
3486 mHttpAuthenticationDialog = null;
3487 mHttpAuthHandler = null;
3488 }})
3489 .setOnCancelListener(new DialogInterface.OnCancelListener() {
3490 public void onCancel(DialogInterface dialog) {
3491 handler.cancel();
3492 BrowserActivity.this.resetTitleAndRevertLockIcon();
3493 mHttpAuthenticationDialog = null;
3494 mHttpAuthHandler = null;
3495 }})
3496 .create();
3497 // Make the IME appear when the dialog is displayed if applicable.
3498 dialog.getWindow().setSoftInputMode(
3499 WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
3500 dialog.show();
3501 if (focusId != 0) {
3502 dialog.findViewById(focusId).requestFocus();
3503 } else {
3504 v.findViewById(R.id.username_edit).requestFocus();
3505 }
3506 mHttpAuthenticationDialog = dialog;
3507 }
3508
3509 public int getProgress() {
3510 WebView w = mTabControl.getCurrentWebView();
3511 if (w != null) {
3512 return w.getProgress();
3513 } else {
3514 return 100;
3515 }
3516 }
3517
3518 /**
3519 * Set HTTP authentication password.
3520 *
3521 * @param host The host for the password
3522 * @param realm The realm for the password
3523 * @param username The username for the password. If it is null, it means
3524 * password can't be saved.
3525 * @param password The password
3526 */
3527 public void setHttpAuthUsernamePassword(String host, String realm,
3528 String username,
3529 String password) {
3530 WebView w = mTabControl.getCurrentWebView();
3531 if (w != null) {
3532 w.setHttpAuthUsernamePassword(host, realm, username, password);
3533 }
3534 }
3535
3536 /**
3537 * connectivity manager says net has come or gone... inform the user
3538 * @param up true if net has come up, false if net has gone down
3539 */
3540 public void onNetworkToggle(boolean up) {
3541 if (up == mIsNetworkUp) {
3542 return;
3543 } else if (up) {
3544 mIsNetworkUp = true;
3545 if (mAlertDialog != null) {
3546 mAlertDialog.cancel();
3547 mAlertDialog = null;
3548 }
3549 } else {
3550 mIsNetworkUp = false;
Patrick Scotteb6ab2a2009-09-16 10:00:17 -04003551 if (mInLoad) {
3552 createAndShowNetworkDialog();
3553 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003554 }
3555 WebView w = mTabControl.getCurrentWebView();
3556 if (w != null) {
3557 w.setNetworkAvailable(up);
3558 }
3559 }
3560
Grace Kloba22ac16e2009-10-07 18:00:23 -07003561 boolean isNetworkUp() {
3562 return mIsNetworkUp;
3563 }
3564
Patrick Scotteb6ab2a2009-09-16 10:00:17 -04003565 // This method shows the network dialog alerting the user that the net is
3566 // down. It will only show the dialog if mAlertDialog is null.
3567 private void createAndShowNetworkDialog() {
3568 if (mAlertDialog == null) {
3569 mAlertDialog = new AlertDialog.Builder(this)
3570 .setTitle(R.string.loadSuspendedTitle)
3571 .setMessage(R.string.loadSuspended)
3572 .setPositiveButton(R.string.ok, null)
3573 .show();
3574 }
3575 }
3576
The Android Open Source Project0c908882009-03-03 19:32:16 -08003577 @Override
3578 protected void onActivityResult(int requestCode, int resultCode,
3579 Intent intent) {
Grace Klobabb394f32009-11-19 10:26:37 -08003580 if (getTopWindow() == null) return;
3581
The Android Open Source Project0c908882009-03-03 19:32:16 -08003582 switch (requestCode) {
3583 case COMBO_PAGE:
3584 if (resultCode == RESULT_OK && intent != null) {
3585 String data = intent.getAction();
3586 Bundle extras = intent.getExtras();
3587 if (extras != null && extras.getBoolean("new_window", false)) {
Leon Scroggins25d35472009-09-15 11:37:27 -04003588 openTab(data);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003589 } else {
Grace Kloba22ac16e2009-10-07 18:00:23 -07003590 final Tab currentTab =
The Android Open Source Project0c908882009-03-03 19:32:16 -08003591 mTabControl.getCurrentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04003592 dismissSubWindow(currentTab);
3593 if (data != null && data.length() != 0) {
3594 getTopWindow().loadUrl(data);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003595 }
3596 }
3597 }
Leon Scrogginsfde97462010-01-11 13:06:21 -05003598 // Deliberately fall through to PREFERENCES_PAGE, since the
3599 // same extra may be attached to the COMBO_PAGE
3600 case PREFERENCES_PAGE:
3601 if (resultCode == RESULT_OK && intent != null) {
3602 String action = intent.getStringExtra(Intent.EXTRA_TEXT);
3603 if (BrowserSettings.PREF_CLEAR_HISTORY.equals(action)) {
3604 mTabControl.removeParentChildRelationShips();
3605 }
3606 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003607 break;
Leon Scroggins8d5fa432009-10-02 15:55:59 -04003608 // Choose a file from the file picker.
3609 case FILE_SELECTED:
3610 if (null == mUploadMessage) break;
3611 Uri result = intent == null || resultCode != RESULT_OK ? null
3612 : intent.getData();
3613 mUploadMessage.onReceiveValue(result);
3614 mUploadMessage = null;
3615 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003616 default:
3617 break;
3618 }
Leon Scroggins30444232009-09-04 18:36:20 -04003619 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003620 }
3621
3622 /*
3623 * This method is called as a result of the user selecting the options
Leon Scrogginsf08809b2010-01-21 09:27:46 -05003624 * menu to see the download window. It shows the download window on top of
3625 * the current window.
The Android Open Source Project0c908882009-03-03 19:32:16 -08003626 */
Leon Scrogginsf08809b2010-01-21 09:27:46 -05003627 private void viewDownloads(Uri downloadRecord) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003628 Intent intent = new Intent(this,
3629 BrowserDownloadPage.class);
3630 intent.setData(downloadRecord);
Grace Kloba22ac16e2009-10-07 18:00:23 -07003631 startActivityForResult(intent, BrowserActivity.DOWNLOAD_PAGE);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003632
3633 }
3634
Leon Scroggins160a7e72009-08-14 18:28:01 -04003635 /**
3636 * Open the Go page.
3637 * @param startWithHistory If true, open starting on the history tab.
3638 * Otherwise, start with the bookmarks tab.
Leon Scroggins160a7e72009-08-14 18:28:01 -04003639 */
Leon Scroggins30444232009-09-04 18:36:20 -04003640 /* package */ void bookmarksOrHistoryPicker(boolean startWithHistory) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003641 WebView current = mTabControl.getCurrentWebView();
3642 if (current == null) {
3643 return;
3644 }
3645 Intent intent = new Intent(this,
3646 CombinedBookmarkHistoryActivity.class);
3647 String title = current.getTitle();
3648 String url = current.getUrl();
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01003649 Bitmap thumbnail = createScreenshot(current);
3650
The Android Open Source Project0c908882009-03-03 19:32:16 -08003651 // Just in case the user opens bookmarks before a page finishes loading
3652 // so the current history item, and therefore the page, is null.
3653 if (null == url) {
3654 url = mLastEnteredUrl;
3655 // This can happen.
3656 if (null == url) {
3657 url = mSettings.getHomePage();
3658 }
3659 }
3660 // In case the web page has not yet received its associated title.
3661 if (title == null) {
3662 title = url;
3663 }
3664 intent.putExtra("title", title);
3665 intent.putExtra("url", url);
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01003666 intent.putExtra("thumbnail", thumbnail);
Leon Scroggins30444232009-09-04 18:36:20 -04003667 // Disable opening in a new window if we have maxed out the windows
Grace Kloba22ac16e2009-10-07 18:00:23 -07003668 intent.putExtra("disable_new_window", !mTabControl.canCreateNewTab());
Patrick Scott3918d442009-08-04 13:22:29 -04003669 intent.putExtra("touch_icon_url", current.getTouchIconUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003670 if (startWithHistory) {
3671 intent.putExtra(CombinedBookmarkHistoryActivity.STARTING_TAB,
3672 CombinedBookmarkHistoryActivity.HISTORY_TAB);
3673 }
3674 startActivityForResult(intent, COMBO_PAGE);
3675 }
3676
3677 // Called when loading from context menu or LOAD_URL message
3678 private void loadURL(WebView view, String url) {
3679 // In case the user enters nothing.
3680 if (url != null && url.length() != 0 && view != null) {
3681 url = smartUrlFilter(url);
Grace Kloba22ac16e2009-10-07 18:00:23 -07003682 if (!view.getWebViewClient().shouldOverrideUrlLoading(view, url)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003683 view.loadUrl(url);
3684 }
3685 }
3686 }
3687
The Android Open Source Project0c908882009-03-03 19:32:16 -08003688 private String smartUrlFilter(Uri inUri) {
3689 if (inUri != null) {
3690 return smartUrlFilter(inUri.toString());
3691 }
3692 return null;
3693 }
3694
Feng Qianb34f87a2009-03-24 21:27:26 -07003695 protected static final Pattern ACCEPTED_URI_SCHEMA = Pattern.compile(
The Android Open Source Project0c908882009-03-03 19:32:16 -08003696 "(?i)" + // switch on case insensitive matching
3697 "(" + // begin group for schema
3698 "(?:http|https|file):\\/\\/" +
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003699 "|(?:inline|data|about|content|javascript):" +
The Android Open Source Project0c908882009-03-03 19:32:16 -08003700 ")" +
3701 "(.*)" );
3702
3703 /**
3704 * Attempts to determine whether user input is a URL or search
3705 * terms. Anything with a space is passed to search.
3706 *
3707 * Converts to lowercase any mistakenly uppercased schema (i.e.,
3708 * "Http://" converts to "http://"
3709 *
3710 * @return Original or modified URL
3711 *
3712 */
3713 String smartUrlFilter(String url) {
3714
3715 String inUrl = url.trim();
3716 boolean hasSpace = inUrl.indexOf(' ') != -1;
3717
3718 Matcher matcher = ACCEPTED_URI_SCHEMA.matcher(inUrl);
3719 if (matcher.matches()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003720 // force scheme to lowercase
3721 String scheme = matcher.group(1);
3722 String lcScheme = scheme.toLowerCase();
3723 if (!lcScheme.equals(scheme)) {
Mitsuru Oshima123ecfb2009-05-18 19:11:14 -07003724 inUrl = lcScheme + matcher.group(2);
3725 }
3726 if (hasSpace) {
3727 inUrl = inUrl.replace(" ", "%20");
The Android Open Source Project0c908882009-03-03 19:32:16 -08003728 }
3729 return inUrl;
3730 }
3731 if (hasSpace) {
Satish Sampath565505b2009-05-29 15:37:27 +01003732 // FIXME: Is this the correct place to add to searches?
3733 // what if someone else calls this function?
3734 int shortcut = parseUrlShortcut(inUrl);
3735 if (shortcut != SHORTCUT_INVALID) {
3736 Browser.addSearchUrl(mResolver, inUrl);
3737 String query = inUrl.substring(2);
3738 switch (shortcut) {
3739 case SHORTCUT_GOOGLE_SEARCH:
Grace Kloba47fdfdb2009-06-30 11:15:34 -07003740 return URLUtil.composeSearchUrl(query, QuickSearch_G, QUERY_PLACE_HOLDER);
Satish Sampath565505b2009-05-29 15:37:27 +01003741 case SHORTCUT_WIKIPEDIA_SEARCH:
3742 return URLUtil.composeSearchUrl(query, QuickSearch_W, QUERY_PLACE_HOLDER);
3743 case SHORTCUT_DICTIONARY_SEARCH:
3744 return URLUtil.composeSearchUrl(query, QuickSearch_D, QUERY_PLACE_HOLDER);
3745 case SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH:
The Android Open Source Project0c908882009-03-03 19:32:16 -08003746 // FIXME: we need location in this case
Satish Sampath565505b2009-05-29 15:37:27 +01003747 return URLUtil.composeSearchUrl(query, QuickSearch_L, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003748 }
3749 }
3750 } else {
Dan Egnor5ee906c2009-11-18 12:11:49 -08003751 if (Patterns.WEB_URL.matcher(inUrl).matches()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003752 return URLUtil.guessUrl(inUrl);
3753 }
3754 }
3755
3756 Browser.addSearchUrl(mResolver, inUrl);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07003757 return URLUtil.composeSearchUrl(inUrl, QuickSearch_G, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003758 }
3759
Ben Murdochbff2d602009-07-01 20:19:05 +01003760 /* package */ void setShouldShowErrorConsole(boolean flag) {
3761 if (flag == mShouldShowErrorConsole) {
3762 // Nothing to do.
3763 return;
3764 }
3765
3766 mShouldShowErrorConsole = flag;
3767
Grace Kloba22ac16e2009-10-07 18:00:23 -07003768 ErrorConsoleView errorConsole = mTabControl.getCurrentTab()
3769 .getErrorConsole(true);
Ben Murdochbff2d602009-07-01 20:19:05 +01003770
3771 if (flag) {
3772 // Setting the show state of the console will cause it's the layout to be inflated.
3773 if (errorConsole.numberOfErrors() > 0) {
3774 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
3775 } else {
3776 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
3777 }
3778
3779 // Now we can add it to the main view.
3780 mErrorConsoleContainer.addView(errorConsole,
Romain Guy15b8ec62010-01-08 15:06:43 -08003781 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
Ben Murdochbff2d602009-07-01 20:19:05 +01003782 ViewGroup.LayoutParams.WRAP_CONTENT));
3783 } else {
3784 mErrorConsoleContainer.removeView(errorConsole);
3785 }
3786
3787 }
3788
Grace Kloba22ac16e2009-10-07 18:00:23 -07003789 boolean shouldShowErrorConsole() {
3790 return mShouldShowErrorConsole;
3791 }
3792
Andrei Popescu163ab742009-10-20 17:58:23 +01003793 private void setStatusBarVisibility(boolean visible) {
3794 int flag = visible ? 0 : WindowManager.LayoutParams.FLAG_FULLSCREEN;
3795 getWindow().setFlags(flag, WindowManager.LayoutParams.FLAG_FULLSCREEN);
3796 }
3797
Andrei Popescu56199cc2010-01-12 22:39:16 +00003798
3799 private void sendNetworkType(String type, String subtype) {
3800 WebView w = mTabControl.getCurrentWebView();
3801 if (w != null) {
3802 w.setNetworkType(type, subtype);
3803 }
3804 }
3805
Grace Klobaeb6eef42009-09-15 17:56:32 -07003806 final static int LOCK_ICON_UNSECURE = 0;
3807 final static int LOCK_ICON_SECURE = 1;
3808 final static int LOCK_ICON_MIXED = 2;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003809
The Android Open Source Project0c908882009-03-03 19:32:16 -08003810 private BrowserSettings mSettings;
3811 private TabControl mTabControl;
3812 private ContentResolver mResolver;
3813 private FrameLayout mContentView;
Andrei Popescuadc008d2009-06-26 14:11:30 +01003814 private View mCustomView;
3815 private FrameLayout mCustomViewContainer;
Andrei Popescuc9b55562009-07-07 10:51:15 +01003816 private WebChromeClient.CustomViewCallback mCustomViewCallback;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003817
3818 // FIXME, temp address onPrepareMenu performance problem. When we move everything out of
3819 // view, we should rewrite this.
3820 private int mCurrentMenuState = 0;
3821 private int mMenuState = R.id.MAIN_MENU;
Andrei Popescuadc008d2009-06-26 14:11:30 +01003822 private int mOldMenuState = EMPTY_MENU;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003823 private static final int EMPTY_MENU = -1;
3824 private Menu mMenu;
3825
3826 private FindDialog mFindDialog;
3827 // Used to prevent chording to result in firing two shortcuts immediately
3828 // one after another. Fixes bug 1211714.
3829 boolean mCanChord;
3830
3831 private boolean mInLoad;
3832 private boolean mIsNetworkUp;
Ben Murdochb7cc8b42009-09-28 10:59:09 +01003833 private boolean mDidStopLoad;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003834
The Android Open Source Project0c908882009-03-03 19:32:16 -08003835 private boolean mActivityInPause = true;
3836
3837 private boolean mMenuIsDown;
3838
The Android Open Source Project0c908882009-03-03 19:32:16 -08003839 private static boolean mInTrace;
3840
3841 // Performance probe
3842 private static final int[] SYSTEM_CPU_FORMAT = new int[] {
3843 Process.PROC_SPACE_TERM | Process.PROC_COMBINE,
3844 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 1: user time
3845 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 2: nice time
3846 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 3: sys time
3847 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 4: idle time
3848 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 5: iowait time
3849 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 6: irq time
3850 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG // 7: softirq time
3851 };
3852
3853 private long mStart;
3854 private long mProcessStart;
3855 private long mUserStart;
3856 private long mSystemStart;
3857 private long mIdleStart;
3858 private long mIrqStart;
3859
3860 private long mUiStart;
3861
3862 private Drawable mMixLockIcon;
3863 private Drawable mSecLockIcon;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003864
3865 /* hold a ref so we can auto-cancel if necessary */
3866 private AlertDialog mAlertDialog;
3867
3868 // Wait for credentials before loading google.com
3869 private ProgressDialog mCredsDlg;
3870
3871 // The up-to-date URL and title (these can be different from those stored
3872 // in WebView, since it takes some time for the information in WebView to
3873 // get updated)
3874 private String mUrl;
3875 private String mTitle;
3876
3877 // As PageInfo has different style for landscape / portrait, we have
3878 // to re-open it when configuration changed
3879 private AlertDialog mPageInfoDialog;
Grace Kloba22ac16e2009-10-07 18:00:23 -07003880 private Tab mPageInfoView;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003881 // If the Page-Info dialog is launched from the SSL-certificate-on-error
3882 // dialog, we should not just dismiss it, but should get back to the
3883 // SSL-certificate-on-error dialog. This flag is used to store this state
Leon Scrogginsc7b92f82010-01-11 18:17:31 -05003884 private boolean mPageInfoFromShowSSLCertificateOnError;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003885
3886 // as SSLCertificateOnError has different style for landscape / portrait,
3887 // we have to re-open it when configuration changed
3888 private AlertDialog mSSLCertificateOnErrorDialog;
3889 private WebView mSSLCertificateOnErrorView;
3890 private SslErrorHandler mSSLCertificateOnErrorHandler;
3891 private SslError mSSLCertificateOnErrorError;
3892
3893 // as SSLCertificate has different style for landscape / portrait, we
3894 // have to re-open it when configuration changed
3895 private AlertDialog mSSLCertificateDialog;
Grace Kloba22ac16e2009-10-07 18:00:23 -07003896 private Tab mSSLCertificateView;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003897
3898 // as HttpAuthentication has different style for landscape / portrait, we
3899 // have to re-open it when configuration changed
3900 private AlertDialog mHttpAuthenticationDialog;
3901 private HttpAuthHandler mHttpAuthHandler;
3902
3903 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_PARAMS =
3904 new FrameLayout.LayoutParams(
Romain Guy15b8ec62010-01-08 15:06:43 -08003905 ViewGroup.LayoutParams.MATCH_PARENT,
3906 ViewGroup.LayoutParams.MATCH_PARENT);
Andrei Popescuadc008d2009-06-26 14:11:30 +01003907 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_GRAVITY_CENTER =
3908 new FrameLayout.LayoutParams(
Romain Guy15b8ec62010-01-08 15:06:43 -08003909 ViewGroup.LayoutParams.MATCH_PARENT,
3910 ViewGroup.LayoutParams.MATCH_PARENT,
Andrei Popescuadc008d2009-06-26 14:11:30 +01003911 Gravity.CENTER);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07003912 // Google search
3913 final static String QuickSearch_G = "http://www.google.com/m?q=%s";
The Android Open Source Project0c908882009-03-03 19:32:16 -08003914 // Wikipedia search
3915 final static String QuickSearch_W = "http://en.wikipedia.org/w/index.php?search=%s&go=Go";
3916 // Dictionary search
3917 final static String QuickSearch_D = "http://dictionary.reference.com/search?q=%s";
3918 // Google Mobile Local search
3919 final static String QuickSearch_L = "http://www.google.com/m/search?site=local&q=%s&near=mountain+view";
3920
3921 final static String QUERY_PLACE_HOLDER = "%s";
3922
3923 // "source" parameter for Google search through search key
3924 final static String GOOGLE_SEARCH_SOURCE_SEARCHKEY = "browser-key";
3925 // "source" parameter for Google search through goto menu
3926 final static String GOOGLE_SEARCH_SOURCE_GOTO = "browser-goto";
3927 // "source" parameter for Google search through simplily type
3928 final static String GOOGLE_SEARCH_SOURCE_TYPE = "browser-type";
3929 // "source" parameter for Google search suggested by the browser
3930 final static String GOOGLE_SEARCH_SOURCE_SUGGEST = "browser-suggest";
3931 // "source" parameter for Google search from unknown source
3932 final static String GOOGLE_SEARCH_SOURCE_UNKNOWN = "unknown";
3933
3934 private final static String LOGTAG = "browser";
3935
The Android Open Source Project0c908882009-03-03 19:32:16 -08003936 private String mLastEnteredUrl;
3937
3938 private PowerManager.WakeLock mWakeLock;
3939 private final static int WAKELOCK_TIMEOUT = 5 * 60 * 1000; // 5 minutes
3940
3941 private Toast mStopToast;
3942
Leon Scroggins68579392009-09-15 15:31:54 -04003943 private TitleBar mTitleBar;
Leon Scroggins81db3662009-06-04 17:45:11 -04003944
Ben Murdochbff2d602009-07-01 20:19:05 +01003945 private LinearLayout mErrorConsoleContainer = null;
3946 private boolean mShouldShowErrorConsole = false;
3947
The Android Open Source Project0c908882009-03-03 19:32:16 -08003948 // As the ids are dynamically created, we can't guarantee that they will
3949 // be in sequence, so this static array maps ids to a window number.
3950 final static private int[] WINDOW_SHORTCUT_ID_ARRAY =
3951 { R.id.window_one_menu_id, R.id.window_two_menu_id, R.id.window_three_menu_id,
3952 R.id.window_four_menu_id, R.id.window_five_menu_id, R.id.window_six_menu_id,
3953 R.id.window_seven_menu_id, R.id.window_eight_menu_id };
3954
3955 // monitor platform changes
3956 private IntentFilter mNetworkStateChangedFilter;
3957 private BroadcastReceiver mNetworkStateIntentReceiver;
3958
Grace Klobab4da0ad2009-05-14 14:45:40 -07003959 private BroadcastReceiver mPackageInstallationReceiver;
3960
The Android Open Source Project0c908882009-03-03 19:32:16 -08003961 // activity requestCode
Nicolas Roard78a98e42009-05-11 13:34:17 +01003962 final static int COMBO_PAGE = 1;
3963 final static int DOWNLOAD_PAGE = 2;
3964 final static int PREFERENCES_PAGE = 3;
Leon Scroggins8d5fa432009-10-02 15:55:59 -04003965 final static int FILE_SELECTED = 4;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003966
Andrei Popescu540035d2009-09-18 18:59:20 +01003967 // the default <video> poster
3968 private Bitmap mDefaultVideoPoster;
3969 // the video progress view
3970 private View mVideoProgressView;
3971
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003972 /**
3973 * A UrlData class to abstract how the content will be set to WebView.
3974 * This base class uses loadUrl to show the content.
3975 */
3976 private static class UrlData {
Grace Kloba068e48b2010-01-26 18:11:27 -08003977 final String mUrl;
3978 final Map<String, String> mHeaders;
Leon Scroggins58d56c62010-01-28 15:12:40 -05003979 final Intent mVoiceIntent;
Grace Kloba60e095c2009-06-16 11:50:55 -07003980
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003981 UrlData(String url) {
3982 this.mUrl = url;
Grace Kloba068e48b2010-01-26 18:11:27 -08003983 this.mHeaders = null;
Leon Scroggins58d56c62010-01-28 15:12:40 -05003984 this.mVoiceIntent = null;
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003985 }
Grace Kloba60e095c2009-06-16 11:50:55 -07003986
Leon Scroggins58d56c62010-01-28 15:12:40 -05003987 UrlData(String url, Map<String, String> headers, Intent intent) {
Grace Kloba068e48b2010-01-26 18:11:27 -08003988 this.mUrl = url;
3989 this.mHeaders = headers;
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -05003990 if (RecognizerResultsIntent.ACTION_VOICE_SEARCH_RESULTS
3991 .equals(intent.getAction())) {
Leon Scroggins58d56c62010-01-28 15:12:40 -05003992 this.mVoiceIntent = intent;
3993 } else {
3994 this.mVoiceIntent = null;
3995 }
Grace Kloba60e095c2009-06-16 11:50:55 -07003996 }
3997
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003998 boolean isEmpty() {
Leon Scroggins58d56c62010-01-28 15:12:40 -05003999 return mVoiceIntent == null && (mUrl == null || mUrl.length() == 0);
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004000 }
4001
Leon Scroggins58d56c62010-01-28 15:12:40 -05004002 public void loadIn(Tab t) {
4003 if (mVoiceIntent != null) {
4004 t.activateVoiceSearchMode(mVoiceIntent);
4005 } else {
4006 t.getWebView().loadUrl(mUrl, mHeaders);
4007 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004008 }
4009 };
4010
Leon Scroggins1f005d32009-08-10 17:36:42 -04004011 /* package */ static final UrlData EMPTY_URL_DATA = new UrlData(null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004012}