blob: 52a31258b515075e4b0276b60a182e753b714308 [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;
Bjorn Bringert10d1cca2010-02-10 14:22:12 +0000114import com.android.common.Search;
Leon Scroggins1fe13a52010-02-09 15:31:26 -0500115import com.android.common.speech.LoggingEvents;
Dan Egnor5ee906c2009-11-18 12:11:49 -0800116
Doug Zongker716d4f52010-01-21 14:35:23 -0800117import com.google.android.gsf.GoogleLoginServiceConstants;
Dan Egnor5ee906c2009-11-18 12:11:49 -0800118
Leon Scrogginsb6b7f9e2009-06-18 12:05:28 -0400119import java.io.ByteArrayOutputStream;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800120import java.io.File;
Ben Murdoch4f75ba22009-10-27 11:48:28 +0000121import java.io.IOException;
122import java.io.InputStream;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800123import java.net.MalformedURLException;
124import java.net.URI;
Dianne Hackborn99189432009-06-17 18:06:18 -0700125import java.net.URISyntaxException;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800126import java.net.URL;
127import java.net.URLEncoder;
128import java.text.ParseException;
129import java.util.Date;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800130import java.util.HashMap;
Andrei Popescu30995e72010-02-09 16:59:58 +0000131import java.util.HashSet;
Grace Kloba00f54c52010-01-27 14:53:51 -0800132import java.util.Iterator;
Andrei Popescu30995e72010-02-09 16:59:58 +0000133import java.util.List;
Grace Kloba068e48b2010-01-26 18:11:27 -0800134import java.util.Map;
Andrei Popescu30995e72010-02-09 16:59:58 +0000135import java.util.Set;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800136import java.util.regex.Matcher;
137import java.util.regex.Pattern;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800138
139public class BrowserActivity extends Activity
Fred Quintana752b6562009-12-18 10:18:26 -0800140 implements View.OnCreateContextMenuListener, DownloadListener,
141 AccountManagerCallback<Account[]> {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800142
Dave Bort31a6d1c2009-04-13 15:56:49 -0700143 /* Define some aliases to make these debugging flags easier to refer to.
144 * This file imports android.provider.Browser, so we can't just refer to "Browser.DEBUG".
145 */
146 private final static boolean DEBUG = com.android.browser.Browser.DEBUG;
147 private final static boolean LOGV_ENABLED = com.android.browser.Browser.LOGV_ENABLED;
148 private final static boolean LOGD_ENABLED = com.android.browser.Browser.LOGD_ENABLED;
149
Satish Sampath565505b2009-05-29 15:37:27 +0100150 // These are single-character shortcuts for searching popular sources.
151 private static final int SHORTCUT_INVALID = 0;
152 private static final int SHORTCUT_GOOGLE_SEARCH = 1;
153 private static final int SHORTCUT_WIKIPEDIA_SEARCH = 2;
154 private static final int SHORTCUT_DICTIONARY_SEARCH = 3;
155 private static final int SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH = 4;
156
Fred Quintana752b6562009-12-18 10:18:26 -0800157 private Account[] mAccountsGoogle;
158 private Account[] mAccountsPreferHosted;
159
160 private void startReadOfGoogleAccounts() {
161 mAccountsGoogle = null;
162 mAccountsPreferHosted = null;
163
164 AccountManager.get(this).getAccountsByTypeAndFeatures(
165 GoogleLoginServiceConstants.ACCOUNT_TYPE,
166 new String[]{GoogleLoginServiceConstants.FEATURE_LEGACY_HOSTED_OR_GOOGLE},
167 this, null);
168 }
169
170 /** This implements AccountManagerCallback<Account[]> */
171 public void run(AccountManagerFuture<Account[]> accountManagerFuture) {
172 try {
173 if (mAccountsGoogle == null) {
174 mAccountsGoogle = accountManagerFuture.getResult();
175
176 AccountManager.get(this).getAccountsByTypeAndFeatures(
177 GoogleLoginServiceConstants.ACCOUNT_TYPE,
178 new String[]{GoogleLoginServiceConstants.FEATURE_LEGACY_GOOGLE},
179 this, null);
180 } else {
181 mAccountsPreferHosted = accountManagerFuture.getResult();
182 setupHomePage();
183 }
184 } catch (OperationCanceledException e) {
185 setupHomePage();
186 } catch (IOException e) {
187 setupHomePage();
188 } catch (AuthenticatorException e) {
189 setupHomePage();
190 }
191 }
192
The Android Open Source Project0c908882009-03-03 19:32:16 -0800193 private void setupHomePage() {
Fred Quintana752b6562009-12-18 10:18:26 -0800194 // get the default home page
195 String homepage = mSettings.getHomePage();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800196
Fred Quintana752b6562009-12-18 10:18:26 -0800197 if (mAccountsPreferHosted != null && mAccountsGoogle != null) {
198 // three cases:
199 //
200 // hostedUser == googleUser
201 // The device has only a google account
202 //
203 // hostedUser != googleUser
204 // The device has a hosted account and a google account
205 //
206 // hostedUser != null, googleUser == null
207 // The device has only a hosted account (so far)
208 String hostedUser = mAccountsPreferHosted.length == 0
209 ? null
210 : mAccountsPreferHosted[0].name;
211 String googleUser = mAccountsGoogle.length == 0 ? null : mAccountsGoogle[0].name;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800212
Fred Quintana752b6562009-12-18 10:18:26 -0800213 // developers might have no accounts at all
214 if (hostedUser == null) return;
Grace Klobaf2c5c1b2009-05-26 10:48:31 -0700215
Fred Quintana752b6562009-12-18 10:18:26 -0800216 if (googleUser == null || !hostedUser.equals(googleUser)) {
217 String domain = hostedUser.substring(hostedUser.lastIndexOf('@')+1);
218 homepage = homepage.replace("?", "/a/" + domain + "?");
The Android Open Source Project0c908882009-03-03 19:32:16 -0800219 }
Fred Quintana752b6562009-12-18 10:18:26 -0800220 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800221
Fred Quintana752b6562009-12-18 10:18:26 -0800222 mSettings.setHomePage(BrowserActivity.this, homepage);
223 resumeAfterCredentials();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800224 }
225
Cary Clarka9771242009-08-11 16:42:26 -0400226 private static class ClearThumbnails extends AsyncTask<File, Void, Void> {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800227 @Override
228 public Void doInBackground(File... files) {
229 if (files != null) {
230 for (File f : files) {
Cary Clarkd6be1752009-08-12 12:56:42 -0400231 if (!f.delete()) {
232 Log.e(LOGTAG, f.getPath() + " was not deleted");
233 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800234 }
235 }
236 return null;
237 }
238 }
239
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400240 /**
241 * This layout holds everything you see below the status bar, including the
242 * error console, the custom view container, and the webviews.
243 */
244 private FrameLayout mBrowserFrameLayout;
Leon Scroggins81db3662009-06-04 17:45:11 -0400245
Grace Kloba22ac16e2009-10-07 18:00:23 -0700246 @Override
247 public void onCreate(Bundle icicle) {
Dave Bort31a6d1c2009-04-13 15:56:49 -0700248 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800249 Log.v(LOGTAG, this + " onStart");
250 }
251 super.onCreate(icicle);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800252 // test the browser in OpenGL
253 // requestWindowFeature(Window.FEATURE_OPENGL);
254
Mike Reedd334bf52010-01-26 15:21:44 -0500255 // enable this to test the browser in 32bit
256 if (false) {
257 getWindow().setFormat(PixelFormat.RGBX_8888);
258 BitmapFactory.setDefaultConfig(Bitmap.Config.ARGB_8888);
259 }
260
The Android Open Source Project0c908882009-03-03 19:32:16 -0800261 setDefaultKeyMode(DEFAULT_KEYS_SEARCH_LOCAL);
262
263 mResolver = getContentResolver();
264
Grace Kloba0923d692009-09-23 21:37:25 -0700265 // If this was a web search request, pass it on to the default web
266 // search provider and finish this activity.
267 if (handleWebSearchIntent(getIntent())) {
268 finish();
269 return;
270 }
271
The Android Open Source Project0c908882009-03-03 19:32:16 -0800272 mSecLockIcon = Resources.getSystem().getDrawable(
273 android.R.drawable.ic_secure);
274 mMixLockIcon = Resources.getSystem().getDrawable(
275 android.R.drawable.ic_partial_secure);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800276
Leon Scroggins81db3662009-06-04 17:45:11 -0400277 FrameLayout frameLayout = (FrameLayout) getWindow().getDecorView()
278 .findViewById(com.android.internal.R.id.content);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400279 mBrowserFrameLayout = (FrameLayout) LayoutInflater.from(this)
280 .inflate(R.layout.custom_screen, null);
281 mContentView = (FrameLayout) mBrowserFrameLayout.findViewById(
282 R.id.main_content);
283 mErrorConsoleContainer = (LinearLayout) mBrowserFrameLayout
284 .findViewById(R.id.error_console);
285 mCustomViewContainer = (FrameLayout) mBrowserFrameLayout
286 .findViewById(R.id.fullscreen_custom_content);
287 frameLayout.addView(mBrowserFrameLayout, COVER_SCREEN_PARAMS);
Leon Scroggins68579392009-09-15 15:31:54 -0400288 mTitleBar = new TitleBar(this);
Leon Scrogginsfe87bd32009-10-06 10:10:00 -0400289 mFakeTitleBar = new TitleBar(this);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800290
291 // Create the tab control and our initial tab
292 mTabControl = new TabControl(this);
293
294 // Open the icon database and retain all the bookmark urls for favicons
295 retainIconsOnStartup();
296
297 // Keep a settings instance handy.
298 mSettings = BrowserSettings.getInstance();
299 mSettings.setTabControl(mTabControl);
300 mSettings.loadFromDb(this);
301
302 PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
303 mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Browser");
304
Grace Klobaa34f6862009-07-31 16:28:17 -0700305 /* enables registration for changes in network status from
306 http stack */
307 mNetworkStateChangedFilter = new IntentFilter();
308 mNetworkStateChangedFilter.addAction(
309 ConnectivityManager.CONNECTIVITY_ACTION);
310 mNetworkStateIntentReceiver = new BroadcastReceiver() {
311 @Override
312 public void onReceive(Context context, Intent intent) {
313 if (intent.getAction().equals(
314 ConnectivityManager.CONNECTIVITY_ACTION)) {
Andrei Popescue4c98462010-02-19 15:44:13 +0000315
316 NetworkInfo info = intent.getParcelableExtra(
317 ConnectivityManager.EXTRA_NETWORK_INFO);
318 String typeName = info.getTypeName();
319 String subtypeName = info.getSubtypeName();
320 sendNetworkType(typeName.toLowerCase(),
321 (subtypeName != null ? subtypeName.toLowerCase() : ""));
322
323 onNetworkToggle(info.isAvailable());
Grace Klobaa34f6862009-07-31 16:28:17 -0700324 }
325 }
326 };
327
Grace Kloba615c6c92009-08-03 10:22:44 -0700328 IntentFilter filter = new IntentFilter(Intent.ACTION_PACKAGE_ADDED);
329 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
330 filter.addDataScheme("package");
331 mPackageInstallationReceiver = new BroadcastReceiver() {
332 @Override
333 public void onReceive(Context context, Intent intent) {
334 final String action = intent.getAction();
335 final String packageName = intent.getData()
336 .getSchemeSpecificPart();
337 final boolean replacing = intent.getBooleanExtra(
338 Intent.EXTRA_REPLACING, false);
339 if (Intent.ACTION_PACKAGE_REMOVED.equals(action) && replacing) {
340 // if it is replacing, refreshPlugins() when adding
341 return;
342 }
Andrei Popescu30995e72010-02-09 16:59:58 +0000343
344 if (sGoogleApps.contains(packageName)) {
345 BrowserActivity.this.packageChanged(packageName,
346 Intent.ACTION_PACKAGE_ADDED.equals(action));
347 }
348
Grace Kloba615c6c92009-08-03 10:22:44 -0700349 PackageManager pm = BrowserActivity.this.getPackageManager();
350 PackageInfo pkgInfo = null;
351 try {
352 pkgInfo = pm.getPackageInfo(packageName,
353 PackageManager.GET_PERMISSIONS);
354 } catch (PackageManager.NameNotFoundException e) {
355 return;
356 }
357 if (pkgInfo != null) {
358 String permissions[] = pkgInfo.requestedPermissions;
359 if (permissions == null) {
360 return;
361 }
362 boolean permissionOk = false;
363 for (String permit : permissions) {
364 if (PluginManager.PLUGIN_PERMISSION.equals(permit)) {
365 permissionOk = true;
366 break;
367 }
368 }
369 if (permissionOk) {
370 PluginManager.getInstance(BrowserActivity.this)
371 .refreshPlugins(
372 Intent.ACTION_PACKAGE_ADDED
373 .equals(action));
374 }
375 }
376 }
377 };
378 registerReceiver(mPackageInstallationReceiver, filter);
379
The Android Open Source Project0c908882009-03-03 19:32:16 -0800380 if (!mTabControl.restoreState(icicle)) {
381 // clear up the thumbnail directory if we can't restore the state as
382 // none of the files in the directory are referenced any more.
383 new ClearThumbnails().execute(
384 mTabControl.getThumbnailDir().listFiles());
Grace Klobaaab3f092009-07-30 12:29:51 -0700385 // there is no quit on Android. But if we can't restore the state,
386 // we can treat it as a new Browser, remove the old session cookies.
387 CookieManager.getInstance().removeSessionCookie();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800388 final Intent intent = getIntent();
389 final Bundle extra = intent.getExtras();
390 // Create an initial tab.
391 // If the intent is ACTION_VIEW and data is not null, the Browser is
392 // invoked to view the content by another application. In this case,
393 // the tab will be close when exit.
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700394 UrlData urlData = getUrlDataFromIntent(intent);
395
Leon Scroggins58d56c62010-01-28 15:12:40 -0500396 String action = intent.getAction();
Grace Kloba22ac16e2009-10-07 18:00:23 -0700397 final Tab t = mTabControl.createNewTab(
Leon Scroggins58d56c62010-01-28 15:12:40 -0500398 (Intent.ACTION_VIEW.equals(action) &&
399 intent.getData() != null)
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -0500400 || RecognizerResultsIntent.ACTION_VOICE_SEARCH_RESULTS
401 .equals(action),
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700402 intent.getStringExtra(Browser.EXTRA_APPLICATION_ID), urlData.mUrl);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800403 mTabControl.setCurrentTab(t);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800404 attachTabToContentView(t);
405 WebView webView = t.getWebView();
406 if (extra != null) {
407 int scale = extra.getInt(Browser.INITIAL_ZOOM_LEVEL, 0);
408 if (scale > 0 && scale <= 1000) {
409 webView.setInitialScale(scale);
410 }
411 }
412 // If we are not restoring from an icicle, then there is a high
413 // likely hood this is the first run. So, check to see if the
414 // homepage needs to be configured and copy any plugins from our
415 // asset directory to the data partition.
416 if ((extra == null || !extra.getBoolean("testing"))
417 && !mSettings.isLoginInitialized()) {
Fred Quintana752b6562009-12-18 10:18:26 -0800418 startReadOfGoogleAccounts();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800419 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800420
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700421 if (urlData.isEmpty()) {
Leon Scroggins30444232009-09-04 18:36:20 -0400422 if (mSettings.isLoginInitialized()) {
Leon Scroggins92472e82010-02-17 16:32:28 -0500423 loadUrl(webView, mSettings.getHomePage());
Leon Scroggins30444232009-09-04 18:36:20 -0400424 } else {
425 waitForCredentials();
426 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800427 } else {
Patrick Scott9d53da02010-02-19 10:19:01 -0500428 loadUrlDataIn(t, urlData);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800429 }
430 } else {
431 // TabControl.restoreState() will create a new tab even if
Leon Scroggins1f005d32009-08-10 17:36:42 -0400432 // restoring the state fails.
The Android Open Source Project0c908882009-03-03 19:32:16 -0800433 attachTabToContentView(mTabControl.getCurrentTab());
434 }
Grace Kloba615c6c92009-08-03 10:22:44 -0700435
Feng Qianb3c02da2009-06-29 15:58:08 -0700436 // Read JavaScript flags if it exists.
437 String jsFlags = mSettings.getJsFlags();
438 if (jsFlags.trim().length() != 0) {
439 mTabControl.getCurrentWebView().setJsFlags(jsFlags);
440 }
Andrei Popescu30995e72010-02-09 16:59:58 +0000441 // Work out which packages are installed on the system.
442 getInstalledPackages();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800443 }
444
Leon Scroggins58d56c62010-01-28 15:12:40 -0500445 /**
446 * Feed the previously stored results strings to the BrowserProvider so that
447 * the SearchDialog will show them instead of the standard searches.
448 * @param result String to show on the editable line of the SearchDialog.
449 */
450 /* package */ void showVoiceSearchResults(String result) {
451 ContentProviderClient client = mResolver.acquireContentProviderClient(
452 Browser.BOOKMARKS_URI);
453 ContentProvider prov = client.getLocalContentProvider();
454 BrowserProvider bp = (BrowserProvider) prov;
455 bp.setQueryResults(mTabControl.getCurrentTab().getVoiceSearchResults());
456 client.release();
457
458 startSearch(result, false,
459 createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_SEARCHKEY),
460 false);
461 }
462
The Android Open Source Project0c908882009-03-03 19:32:16 -0800463 @Override
464 protected void onNewIntent(Intent intent) {
Grace Kloba22ac16e2009-10-07 18:00:23 -0700465 Tab current = mTabControl.getCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800466 // When a tab is closed on exit, the current tab index is set to -1.
467 // Reset before proceed as Browser requires the current tab to be set.
468 if (current == null) {
469 // Try to reset the tab in case the index was incorrect.
470 current = mTabControl.getTab(0);
471 if (current == null) {
472 // No tabs at all so just ignore this intent.
473 return;
474 }
475 mTabControl.setCurrentTab(current);
476 attachTabToContentView(current);
477 resetTitleAndIcon(current.getWebView());
478 }
479 final String action = intent.getAction();
480 final int flags = intent.getFlags();
481 if (Intent.ACTION_MAIN.equals(action) ||
482 (flags & Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY) != 0) {
483 // just resume the browser
484 return;
485 }
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -0500486 boolean activateVoiceSearch = RecognizerResultsIntent
487 .ACTION_VOICE_SEARCH_RESULTS.equals(action);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800488 if (Intent.ACTION_VIEW.equals(action)
489 || Intent.ACTION_SEARCH.equals(action)
490 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
Leon Scroggins58d56c62010-01-28 15:12:40 -0500491 || Intent.ACTION_WEB_SEARCH.equals(action)
492 || activateVoiceSearch) {
Leon Scroggins3b18ce32010-02-08 17:35:59 -0500493 if (current.isInVoiceSearchMode()) {
494 String title = current.getVoiceDisplayTitle();
495 if (title != null && title.equals(intent.getStringExtra(
496 SearchManager.QUERY))) {
497 // The user submitted the same search as the last voice
498 // search, so do nothing.
499 return;
500 }
Leon Scroggins1fe13a52010-02-09 15:31:26 -0500501 if (Intent.ACTION_SEARCH.equals(action)
502 && current.voiceSearchSourceIsGoogle()) {
503 Intent logIntent = new Intent(
504 LoggingEvents.ACTION_LOG_EVENT);
505 logIntent.putExtra(LoggingEvents.EXTRA_EVENT,
506 LoggingEvents.VoiceSearch.QUERY_UPDATED);
507 logIntent.putExtra(
508 LoggingEvents.VoiceSearch.EXTRA_QUERY_UPDATED_VALUE,
509 intent.getDataString());
510 sendBroadcast(logIntent);
511 // Note, onPageStarted will revert the voice title bar
512 // When http://b/issue?id=2379215 is fixed, we should update
513 // the title bar here.
514 }
Leon Scroggins3b18ce32010-02-08 17:35:59 -0500515 }
Satish Sampath565505b2009-05-29 15:37:27 +0100516 // If this was a search request (e.g. search query directly typed into the address bar),
517 // pass it on to the default web search provider.
518 if (handleWebSearchIntent(intent)) {
519 return;
520 }
521
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700522 UrlData urlData = getUrlDataFromIntent(intent);
523 if (urlData.isEmpty()) {
524 urlData = new UrlData(mSettings.getHomePage());
The Android Open Source Project0c908882009-03-03 19:32:16 -0800525 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700526
Grace Klobacc634032009-07-28 15:58:19 -0700527 final String appId = intent
528 .getStringExtra(Browser.EXTRA_APPLICATION_ID);
Leon Scroggins58d56c62010-01-28 15:12:40 -0500529 if ((Intent.ACTION_VIEW.equals(action) || activateVoiceSearch)
Grace Klobacc634032009-07-28 15:58:19 -0700530 && !getPackageName().equals(appId)
531 && (flags & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0) {
Grace Kloba22ac16e2009-10-07 18:00:23 -0700532 Tab appTab = mTabControl.getTabFromId(appId);
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700533 if (appTab != null) {
534 Log.i(LOGTAG, "Reusing tab for " + appId);
535 // Dismiss the subwindow if applicable.
536 dismissSubWindow(appTab);
537 // Since we might kill the WebView, remove it from the
538 // content view first.
539 removeTabFromContentView(appTab);
540 // Recreate the main WebView after destroying the old one.
541 // If the WebView has the same original url and is on that
542 // page, it can be reused.
543 boolean needsLoad =
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700544 mTabControl.recreateWebView(appTab, urlData.mUrl);
Ben Murdochbff2d602009-07-01 20:19:05 +0100545
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700546 if (current != appTab) {
Leon Scroggins1f005d32009-08-10 17:36:42 -0400547 switchToTab(mTabControl.getTabIndex(appTab));
548 if (needsLoad) {
Patrick Scott9d53da02010-02-19 10:19:01 -0500549 loadUrlDataIn(appTab, urlData);
Leon Scroggins1f005d32009-08-10 17:36:42 -0400550 }
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700551 } else {
Leon Scroggins1f005d32009-08-10 17:36:42 -0400552 // If the tab was the current tab, we have to attach
553 // it to the view system again.
554 attachTabToContentView(appTab);
555 if (needsLoad) {
Patrick Scott9d53da02010-02-19 10:19:01 -0500556 loadUrlDataIn(appTab, urlData);
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700557 }
558 }
559 return;
Patrick Scottcd115892009-07-16 09:42:58 -0400560 } else {
561 // No matching application tab, try to find a regular tab
562 // with a matching url.
563 appTab = mTabControl.findUnusedTabWithUrl(urlData.mUrl);
Leon Scroggins25515f82009-08-19 15:31:58 -0400564 if (appTab != null) {
565 if (current != appTab) {
566 switchToTab(mTabControl.getTabIndex(appTab));
567 }
568 // Otherwise, we are already viewing the correct tab.
Patrick Scottcd115892009-07-16 09:42:58 -0400569 } else {
570 // if FLAG_ACTIVITY_BROUGHT_TO_FRONT flag is on, the url
571 // will be opened in a new tab unless we have reached
572 // MAX_TABS. Then the url will be opened in the current
573 // tab. If a new tab is created, it will have "true" for
574 // exit on close.
Leon Scroggins1f005d32009-08-10 17:36:42 -0400575 openTabAndShow(urlData, true, appId);
Patrick Scottcd115892009-07-16 09:42:58 -0400576 }
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700577 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800578 } else {
Grace Kloba638d3f42009-11-23 10:35:04 -0800579 if (!urlData.isEmpty()
580 && urlData.mUrl.startsWith("about:debug")) {
581 if ("about:debug.dom".equals(urlData.mUrl)) {
582 current.getWebView().dumpDomTree(false);
583 } else if ("about:debug.dom.file".equals(urlData.mUrl)) {
584 current.getWebView().dumpDomTree(true);
585 } else if ("about:debug.render".equals(urlData.mUrl)) {
586 current.getWebView().dumpRenderTree(false);
587 } else if ("about:debug.render.file".equals(urlData.mUrl)) {
588 current.getWebView().dumpRenderTree(true);
589 } else if ("about:debug.display".equals(urlData.mUrl)) {
590 current.getWebView().dumpDisplayTree();
Mike Reed9b78e1d2010-01-13 14:40:52 -0800591 } else if (urlData.mUrl.startsWith("about:debug.drag")) {
592 int index = urlData.mUrl.codePointAt(16) - '0';
593 if (index <= 0 || index > 9) {
594 current.getWebView().setDragTracker(null);
595 } else {
596 current.getWebView().setDragTracker(new MeshTracker(index));
597 }
Grace Kloba638d3f42009-11-23 10:35:04 -0800598 } else {
599 mSettings.toggleDebugSettings();
600 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800601 return;
602 }
Leon Scroggins1f005d32009-08-10 17:36:42 -0400603 // Get rid of the subwindow if it exists
604 dismissSubWindow(current);
Patrick Scott9d53da02010-02-19 10:19:01 -0500605 loadUrlDataIn(current, urlData);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800606 }
607 }
608 }
609
Satish Sampath565505b2009-05-29 15:37:27 +0100610 private int parseUrlShortcut(String url) {
611 if (url == null) return SHORTCUT_INVALID;
612
613 // FIXME: quick search, need to be customized by setting
614 if (url.length() > 2 && url.charAt(1) == ' ') {
615 switch (url.charAt(0)) {
616 case 'g': return SHORTCUT_GOOGLE_SEARCH;
617 case 'w': return SHORTCUT_WIKIPEDIA_SEARCH;
618 case 'd': return SHORTCUT_DICTIONARY_SEARCH;
619 case 'l': return SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH;
620 }
621 }
622 return SHORTCUT_INVALID;
623 }
624
625 /**
626 * Launches the default web search activity with the query parameters if the given intent's data
627 * are identified as plain search terms and not URLs/shortcuts.
628 * @return true if the intent was handled and web search activity was launched, false if not.
629 */
630 private boolean handleWebSearchIntent(Intent intent) {
631 if (intent == null) return false;
632
633 String url = null;
634 final String action = intent.getAction();
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -0500635 if (RecognizerResultsIntent.ACTION_VOICE_SEARCH_RESULTS.equals(
636 action)) {
Leon Scroggins58d56c62010-01-28 15:12:40 -0500637 return false;
638 }
Satish Sampath565505b2009-05-29 15:37:27 +0100639 if (Intent.ACTION_VIEW.equals(action)) {
Grace Kloba1e705052009-09-29 13:13:36 -0700640 Uri data = intent.getData();
641 if (data != null) url = data.toString();
Satish Sampath565505b2009-05-29 15:37:27 +0100642 } else if (Intent.ACTION_SEARCH.equals(action)
643 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
644 || Intent.ACTION_WEB_SEARCH.equals(action)) {
645 url = intent.getStringExtra(SearchManager.QUERY);
646 }
Bjorn Bringert04851702009-09-22 10:36:01 +0100647 return handleWebSearchRequest(url, intent.getBundleExtra(SearchManager.APP_DATA),
648 intent.getStringExtra(SearchManager.EXTRA_DATA_KEY));
Satish Sampath565505b2009-05-29 15:37:27 +0100649 }
650
651 /**
652 * Launches the default web search activity with the query parameters if the given url string
653 * was identified as plain search terms and not URL/shortcut.
654 * @return true if the request was handled and web search activity was launched, false if not.
655 */
Bjorn Bringert04851702009-09-22 10:36:01 +0100656 private boolean handleWebSearchRequest(String inUrl, Bundle appData, String extraData) {
Satish Sampath565505b2009-05-29 15:37:27 +0100657 if (inUrl == null) return false;
658
659 // In general, we shouldn't modify URL from Intent.
660 // But currently, we get the user-typed URL from search box as well.
661 String url = fixUrl(inUrl).trim();
662
663 // URLs and site specific search shortcuts are handled by the regular flow of control, so
664 // return early.
Dan Egnor5ee906c2009-11-18 12:11:49 -0800665 if (Patterns.WEB_URL.matcher(url).matches()
Satish Sampathbc5b9f32009-06-04 18:21:40 +0100666 || ACCEPTED_URI_SCHEMA.matcher(url).matches()
Satish Sampath565505b2009-05-29 15:37:27 +0100667 || parseUrlShortcut(url) != SHORTCUT_INVALID) {
668 return false;
669 }
670
671 Browser.updateVisitedHistory(mResolver, url, false);
672 Browser.addSearchUrl(mResolver, url);
673
674 Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);
675 intent.addCategory(Intent.CATEGORY_DEFAULT);
676 intent.putExtra(SearchManager.QUERY, url);
Satish Sampath15e9f2d2009-06-23 22:29:49 +0100677 if (appData != null) {
678 intent.putExtra(SearchManager.APP_DATA, appData);
679 }
Bjorn Bringert04851702009-09-22 10:36:01 +0100680 if (extraData != null) {
681 intent.putExtra(SearchManager.EXTRA_DATA_KEY, extraData);
682 }
Grace Klobacc634032009-07-28 15:58:19 -0700683 intent.putExtra(Browser.EXTRA_APPLICATION_ID, getPackageName());
Satish Sampath565505b2009-05-29 15:37:27 +0100684 startActivity(intent);
685
686 return true;
687 }
688
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700689 private UrlData getUrlDataFromIntent(Intent intent) {
Leon Scroggins58d56c62010-01-28 15:12:40 -0500690 String url = "";
Grace Kloba068e48b2010-01-26 18:11:27 -0800691 Map<String, String> headers = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800692 if (intent != null) {
693 final String action = intent.getAction();
694 if (Intent.ACTION_VIEW.equals(action)) {
695 url = smartUrlFilter(intent.getData());
696 if (url != null && url.startsWith("content:")) {
697 /* Append mimetype so webview knows how to display */
698 String mimeType = intent.resolveType(getContentResolver());
699 if (mimeType != null) {
700 url += "?" + mimeType;
701 }
702 }
Grace Kloba068e48b2010-01-26 18:11:27 -0800703 if (url != null && url.startsWith("http")) {
Grace Kloba00f54c52010-01-27 14:53:51 -0800704 final Bundle pairs = intent
705 .getBundleExtra(Browser.EXTRA_HEADERS);
Grace Kloba2d508ed2010-01-28 11:39:15 -0800706 if (pairs != null && !pairs.isEmpty()) {
Grace Kloba00f54c52010-01-27 14:53:51 -0800707 Iterator<String> iter = pairs.keySet().iterator();
Grace Kloba068e48b2010-01-26 18:11:27 -0800708 headers = new HashMap<String, String>();
Grace Kloba00f54c52010-01-27 14:53:51 -0800709 while (iter.hasNext()) {
710 String key = iter.next();
711 headers.put(key, pairs.getString(key));
Grace Kloba068e48b2010-01-26 18:11:27 -0800712 }
713 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700714 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800715 } else if (Intent.ACTION_SEARCH.equals(action)
716 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
717 || Intent.ACTION_WEB_SEARCH.equals(action)) {
718 url = intent.getStringExtra(SearchManager.QUERY);
719 if (url != null) {
720 mLastEnteredUrl = url;
Leon Scrogginsb4464432009-11-25 12:37:50 -0500721 Browser.updateVisitedHistory(mResolver, url, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800722 // In general, we shouldn't modify URL from Intent.
723 // But currently, we get the user-typed URL from search box as well.
724 url = fixUrl(url);
725 url = smartUrlFilter(url);
726 String searchSource = "&source=android-" + GOOGLE_SEARCH_SOURCE_SUGGEST + "&";
727 if (url.contains(searchSource)) {
728 String source = null;
729 final Bundle appData = intent.getBundleExtra(SearchManager.APP_DATA);
730 if (appData != null) {
Bjorn Bringert10d1cca2010-02-10 14:22:12 +0000731 source = appData.getString(Search.SOURCE);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800732 }
733 if (TextUtils.isEmpty(source)) {
734 source = GOOGLE_SEARCH_SOURCE_UNKNOWN;
735 }
736 url = url.replace(searchSource, "&source=android-"+source+"&");
737 }
738 }
739 }
740 }
Leon Scroggins58d56c62010-01-28 15:12:40 -0500741 return new UrlData(url, headers, intent);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800742 }
Leon Scroggins58d56c62010-01-28 15:12:40 -0500743 /* package */ void showVoiceTitleBar(String title) {
744 mTitleBar.setInVoiceMode(true);
745 mFakeTitleBar.setInVoiceMode(true);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800746
Leon Scroggins58d56c62010-01-28 15:12:40 -0500747 mTitleBar.setDisplayTitle(title);
748 mFakeTitleBar.setDisplayTitle(title);
749 }
750 /* package */ void revertVoiceTitleBar() {
751 mTitleBar.setInVoiceMode(false);
752 mFakeTitleBar.setInVoiceMode(false);
753
754 mTitleBar.setDisplayTitle(mTitle);
755 mFakeTitleBar.setDisplayTitle(mTitle);
756 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800757 /* package */ static String fixUrl(String inUrl) {
Cary Clark652ff872009-09-10 13:34:44 -0400758 // FIXME: Converting the url to lower case
759 // duplicates functionality in smartUrlFilter().
760 // However, changing all current callers of fixUrl to
761 // call smartUrlFilter in addition may have unwanted
762 // consequences, and is deferred for now.
763 int colon = inUrl.indexOf(':');
764 boolean allLower = true;
765 for (int index = 0; index < colon; index++) {
766 char ch = inUrl.charAt(index);
767 if (!Character.isLetter(ch)) {
768 break;
769 }
770 allLower &= Character.isLowerCase(ch);
771 if (index == colon - 1 && !allLower) {
772 inUrl = inUrl.substring(0, colon).toLowerCase()
773 + inUrl.substring(colon);
774 }
775 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800776 if (inUrl.startsWith("http://") || inUrl.startsWith("https://"))
777 return inUrl;
778 if (inUrl.startsWith("http:") ||
779 inUrl.startsWith("https:")) {
780 if (inUrl.startsWith("http:/") || inUrl.startsWith("https:/")) {
781 inUrl = inUrl.replaceFirst("/", "//");
782 } else inUrl = inUrl.replaceFirst(":", "://");
783 }
784 return inUrl;
785 }
786
Grace Kloba22ac16e2009-10-07 18:00:23 -0700787 @Override
788 protected void onResume() {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800789 super.onResume();
Dave Bort31a6d1c2009-04-13 15:56:49 -0700790 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800791 Log.v(LOGTAG, "BrowserActivity.onResume: this=" + this);
792 }
793
794 if (!mActivityInPause) {
795 Log.e(LOGTAG, "BrowserActivity is already resumed.");
796 return;
797 }
798
Mike Reed7bfa63b2009-05-28 11:08:32 -0400799 mTabControl.resumeCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800800 mActivityInPause = false;
Mike Reed7bfa63b2009-05-28 11:08:32 -0400801 resumeWebViewTimers();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800802
803 if (mWakeLock.isHeld()) {
804 mHandler.removeMessages(RELEASE_WAKELOCK);
805 mWakeLock.release();
806 }
807
808 if (mCredsDlg != null) {
809 if (!mHandler.hasMessages(CANCEL_CREDS_REQUEST)) {
810 // In case credential request never comes back
811 mHandler.sendEmptyMessageDelayed(CANCEL_CREDS_REQUEST, 6000);
812 }
813 }
814
815 registerReceiver(mNetworkStateIntentReceiver,
816 mNetworkStateChangedFilter);
817 WebView.enablePlatformNotifications();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800818 }
819
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400820 /**
821 * Since the actual title bar is embedded in the WebView, and removing it
Leon Scrogginsfe87bd32009-10-06 10:10:00 -0400822 * would change its appearance, use a different TitleBar to show overlayed
823 * at the top of the screen, when the menu is open or the page is loading.
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400824 */
825 private TitleBar mFakeTitleBar;
826
827 /**
Leon Scrogginsd8fd2fc2009-09-16 11:12:09 -0400828 * Holder for the fake title bar. It will have a foreground shadow, as well
829 * as a white background, so the fake title bar looks like the real one.
830 */
831 private ViewGroup mFakeTitleBarHolder;
832
833 /**
834 * Layout parameters for the fake title bar within mFakeTitleBarHolder
835 */
836 private FrameLayout.LayoutParams mFakeTitleBarParams
837 = new FrameLayout.LayoutParams(
Romain Guy15b8ec62010-01-08 15:06:43 -0800838 ViewGroup.LayoutParams.MATCH_PARENT,
Leon Scrogginsd8fd2fc2009-09-16 11:12:09 -0400839 ViewGroup.LayoutParams.WRAP_CONTENT);
840 /**
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400841 * Keeps track of whether the options menu is open. This is important in
842 * determining whether to show or hide the title bar overlay.
843 */
844 private boolean mOptionsMenuOpen;
845
846 /**
847 * Only meaningful when mOptionsMenuOpen is true. This variable keeps track
848 * of whether the configuration has changed. The first onMenuOpened call
849 * after a configuration change is simply a reopening of the same menu
850 * (i.e. mIconView did not change).
851 */
852 private boolean mConfigChanged;
853
854 /**
855 * Whether or not the options menu is in its smaller, icon menu form. When
856 * true, we want the title bar overlay to be up. When false, we do not.
857 * Only meaningful if mOptionsMenuOpen is true.
858 */
859 private boolean mIconView;
860
Leon Scrogginsa81a7642009-08-31 17:05:41 -0400861 @Override
862 public boolean onMenuOpened(int featureId, Menu menu) {
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400863 if (Window.FEATURE_OPTIONS_PANEL == featureId) {
864 if (mOptionsMenuOpen) {
865 if (mConfigChanged) {
866 // We do not need to make any changes to the state of the
867 // title bar, since the only thing that happened was a
868 // change in orientation
869 mConfigChanged = false;
870 } else {
871 if (mIconView) {
872 // Switching the menu to expanded view, so hide the
873 // title bar.
874 hideFakeTitleBar();
875 mIconView = false;
876 } else {
877 // Switching the menu back to icon view, so show the
878 // title bar once again.
879 showFakeTitleBar();
880 mIconView = true;
881 }
882 }
883 } else {
884 // The options menu is closed, so open it, and show the title
885 showFakeTitleBar();
886 mOptionsMenuOpen = true;
887 mConfigChanged = false;
888 mIconView = true;
889 }
890 }
Leon Scrogginsa81a7642009-08-31 17:05:41 -0400891 return true;
892 }
893
Leon Scrogginsb94bf272009-09-25 15:22:08 -0400894 /**
895 * Special class used exclusively for the shadow drawn underneath the fake
896 * title bar. The shadow does not need to be drawn if the WebView
897 * underneath is scrolled to the top, because it will draw directly on top
898 * of the embedded shadow.
899 */
900 private static class Shadow extends View {
901 private WebView mWebView;
902
903 public Shadow(Context context, AttributeSet attrs) {
904 super(context, attrs);
905 }
906
907 public void setWebView(WebView view) {
908 mWebView = view;
909 }
910
911 @Override
912 public void draw(Canvas canvas) {
913 // In general onDraw is the method to override, but we care about
914 // whether or not the background gets drawn, which happens in draw()
915 if (mWebView == null || mWebView.getScrollY() > getHeight()) {
916 super.draw(canvas);
917 }
918 // Need to invalidate so that if the scroll position changes, we
919 // still draw as appropriate.
920 invalidate();
921 }
922 }
923
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400924 private void showFakeTitleBar() {
Patrick Scottf8de8ec2009-09-21 16:37:29 -0400925 final View decor = getWindow().peekDecorView();
Leon Scrogginsfe87bd32009-10-06 10:10:00 -0400926 if (mFakeTitleBar.getParent() == null && mActiveTabsPage == null
Patrick Scottf8de8ec2009-09-21 16:37:29 -0400927 && !mActivityInPause && decor != null
928 && decor.getWindowToken() != null) {
Cary Clarka0464552009-09-29 13:00:45 -0400929 Rect visRect = new Rect();
930 if (!mBrowserFrameLayout.getGlobalVisibleRect(visRect)) {
931 if (LOGD_ENABLED) {
932 Log.d(LOGTAG, "showFakeTitleBar visRect failed");
933 }
934 return;
935 }
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400936
937 WindowManager manager
938 = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
939
940 // Add the title bar to the window manager so it can receive touches
941 // while the menu is up
942 WindowManager.LayoutParams params
943 = new WindowManager.LayoutParams(
Romain Guy15b8ec62010-01-08 15:06:43 -0800944 ViewGroup.LayoutParams.MATCH_PARENT,
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400945 ViewGroup.LayoutParams.WRAP_CONTENT,
946 WindowManager.LayoutParams.TYPE_APPLICATION_SUB_PANEL,
947 WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
Leon Scroggins68549862009-09-21 16:02:01 -0400948 PixelFormat.TRANSLUCENT);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400949 params.gravity = Gravity.TOP;
Leon Scrogginsa27ff192009-09-14 12:58:04 -0400950 WebView mainView = mTabControl.getCurrentWebView();
Leon Scroggins68549862009-09-21 16:02:01 -0400951 boolean atTop = mainView != null && mainView.getScrollY() == 0;
Leon Scroggins83932c72009-09-30 11:55:54 -0400952 params.windowAnimations = atTop ? 0 : R.style.TitleBar;
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400953 // XXX : Without providing an offset, the fake title bar will be
954 // placed underneath the status bar. Use the global visible rect
955 // of mBrowserFrameLayout to determine the bottom of the status bar
Cary Clarka0464552009-09-29 13:00:45 -0400956 params.y = visRect.top;
Leon Scroggins68549862009-09-21 16:02:01 -0400957 // Add a holder for the title bar. It also holds a shadow to show
958 // below the title bar.
Leon Scrogginsd8fd2fc2009-09-16 11:12:09 -0400959 if (mFakeTitleBarHolder == null) {
960 mFakeTitleBarHolder = (ViewGroup) LayoutInflater.from(this)
961 .inflate(R.layout.title_bar_bg, null);
962 }
Leon Scrogginsb94bf272009-09-25 15:22:08 -0400963 Shadow shadow = (Shadow) mFakeTitleBarHolder.findViewById(
964 R.id.shadow);
965 shadow.setWebView(mainView);
Leon Scroggins68549862009-09-21 16:02:01 -0400966 mFakeTitleBarHolder.addView(mFakeTitleBar, 0, mFakeTitleBarParams);
Leon Scrogginsd8fd2fc2009-09-16 11:12:09 -0400967 manager.addView(mFakeTitleBarHolder, params);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400968 }
969 }
970
971 @Override
972 public void onOptionsMenuClosed(Menu menu) {
973 mOptionsMenuOpen = false;
Leon Scrogginsa27ff192009-09-14 12:58:04 -0400974 if (!mInLoad) {
975 hideFakeTitleBar();
976 } else if (!mIconView) {
977 // The page is currently loading, and we are in expanded mode, so
978 // we were not showing the menu. Show it once again. It will be
979 // removed when the page finishes.
980 showFakeTitleBar();
981 }
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400982 }
Grace Kloba22ac16e2009-10-07 18:00:23 -0700983
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400984 private void hideFakeTitleBar() {
Leon Scrogginsfe87bd32009-10-06 10:10:00 -0400985 if (mFakeTitleBar.getParent() == null) return;
Leon Scroggins20329572009-09-23 17:42:41 -0400986 WindowManager.LayoutParams params = (WindowManager.LayoutParams)
987 mFakeTitleBarHolder.getLayoutParams();
988 WebView mainView = mTabControl.getCurrentWebView();
989 // Although we decided whether or not to animate based on the current
990 // scroll position, the scroll position may have changed since the
991 // fake title bar was displayed. Make sure it has the appropriate
992 // animation/lack thereof before removing.
993 params.windowAnimations = mainView != null && mainView.getScrollY() == 0
Leon Scroggins83932c72009-09-30 11:55:54 -0400994 ? 0 : R.style.TitleBar;
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400995 WindowManager manager
996 = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
Leon Scroggins20329572009-09-23 17:42:41 -0400997 manager.updateViewLayout(mFakeTitleBarHolder, params);
Leon Scrogginsd8fd2fc2009-09-16 11:12:09 -0400998 mFakeTitleBarHolder.removeView(mFakeTitleBar);
999 manager.removeView(mFakeTitleBarHolder);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04001000 }
1001
The Android Open Source Project0c908882009-03-03 19:32:16 -08001002 /**
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001003 * Special method for the fake title bar to call when displaying its context
1004 * menu, since it is in its own Window, and its parent does not show a
1005 * context menu.
1006 */
1007 /* package */ void showTitleBarContextMenu() {
Cary Clark65f4a3c2009-09-28 17:05:06 -04001008 if (null == mTitleBar.getParent()) {
1009 return;
1010 }
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001011 openContextMenu(mTitleBar);
1012 }
1013
Leon Scrogginsb2b19f52009-10-09 16:10:00 -04001014 @Override
1015 public void onContextMenuClosed(Menu menu) {
1016 super.onContextMenuClosed(menu);
1017 if (mInLoad) {
1018 showFakeTitleBar();
1019 }
1020 }
1021
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001022 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08001023 * onSaveInstanceState(Bundle map)
1024 * onSaveInstanceState is called right before onStop(). The map contains
1025 * the saved state.
1026 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07001027 @Override
1028 protected void onSaveInstanceState(Bundle outState) {
Dave Bort31a6d1c2009-04-13 15:56:49 -07001029 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001030 Log.v(LOGTAG, "BrowserActivity.onSaveInstanceState: this=" + this);
1031 }
1032 // the default implementation requires each view to have an id. As the
1033 // browser handles the state itself and it doesn't use id for the views,
1034 // don't call the default implementation. Otherwise it will trigger the
1035 // warning like this, "couldn't save which view has focus because the
1036 // focused view XXX has no id".
1037
1038 // Save all the tabs
1039 mTabControl.saveState(outState);
1040 }
1041
Grace Kloba22ac16e2009-10-07 18:00:23 -07001042 @Override
1043 protected void onPause() {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001044 super.onPause();
1045
1046 if (mActivityInPause) {
1047 Log.e(LOGTAG, "BrowserActivity is already paused.");
1048 return;
1049 }
1050
Mike Reed7bfa63b2009-05-28 11:08:32 -04001051 mTabControl.pauseCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001052 mActivityInPause = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -04001053 if (mTabControl.getCurrentIndex() >= 0 && !pauseWebViewTimers()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001054 mWakeLock.acquire();
1055 mHandler.sendMessageDelayed(mHandler
1056 .obtainMessage(RELEASE_WAKELOCK), WAKELOCK_TIMEOUT);
1057 }
1058
1059 // Clear the credentials toast if it is up
1060 if (mCredsDlg != null && mCredsDlg.isShowing()) {
1061 mCredsDlg.dismiss();
1062 }
1063 mCredsDlg = null;
1064
Leon Scrogginsa2ab6a72009-09-11 11:49:52 -04001065 // FIXME: This removes the active tabs page and resets the menu to
1066 // MAIN_MENU. A better solution might be to do this work in onNewIntent
1067 // but then we would need to save it in onSaveInstanceState and restore
1068 // it in onCreate/onRestoreInstanceState
1069 if (mActiveTabsPage != null) {
1070 removeActiveTabPage(true);
1071 }
1072
The Android Open Source Project0c908882009-03-03 19:32:16 -08001073 cancelStopToast();
1074
1075 // unregister network state listener
1076 unregisterReceiver(mNetworkStateIntentReceiver);
1077 WebView.disablePlatformNotifications();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001078 }
1079
Grace Kloba22ac16e2009-10-07 18:00:23 -07001080 @Override
1081 protected void onDestroy() {
Dave Bort31a6d1c2009-04-13 15:56:49 -07001082 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001083 Log.v(LOGTAG, "BrowserActivity.onDestroy: this=" + this);
1084 }
1085 super.onDestroy();
Grace Kloba0923d692009-09-23 21:37:25 -07001086
Leon Scroggins8d5fa432009-10-02 15:55:59 -04001087 if (mUploadMessage != null) {
1088 mUploadMessage.onReceiveValue(null);
1089 mUploadMessage = null;
1090 }
1091
Grace Kloba0923d692009-09-23 21:37:25 -07001092 if (mTabControl == null) return;
1093
Grace Kloba1fc98a32009-10-21 13:23:08 -07001094 // Remove the fake title bar if it is there
1095 hideFakeTitleBar();
1096
The Android Open Source Project0c908882009-03-03 19:32:16 -08001097 // Remove the current tab and sub window
Grace Kloba22ac16e2009-10-07 18:00:23 -07001098 Tab t = mTabControl.getCurrentTab();
Patrick Scottfb5e77f2009-04-08 19:17:37 -07001099 if (t != null) {
1100 dismissSubWindow(t);
1101 removeTabFromContentView(t);
1102 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001103 // Destroy all the tabs
1104 mTabControl.destroy();
1105 WebIconDatabase.getInstance().close();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001106
Grace Klobab4da0ad2009-05-14 14:45:40 -07001107 unregisterReceiver(mPackageInstallationReceiver);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001108 }
1109
1110 @Override
1111 public void onConfigurationChanged(Configuration newConfig) {
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04001112 mConfigChanged = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001113 super.onConfigurationChanged(newConfig);
1114
1115 if (mPageInfoDialog != null) {
1116 mPageInfoDialog.dismiss();
1117 showPageInfo(
1118 mPageInfoView,
Leon Scrogginsc7b92f82010-01-11 18:17:31 -05001119 mPageInfoFromShowSSLCertificateOnError);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001120 }
1121 if (mSSLCertificateDialog != null) {
1122 mSSLCertificateDialog.dismiss();
1123 showSSLCertificate(
1124 mSSLCertificateView);
1125 }
1126 if (mSSLCertificateOnErrorDialog != null) {
1127 mSSLCertificateOnErrorDialog.dismiss();
1128 showSSLCertificateOnError(
1129 mSSLCertificateOnErrorView,
1130 mSSLCertificateOnErrorHandler,
1131 mSSLCertificateOnErrorError);
1132 }
1133 if (mHttpAuthenticationDialog != null) {
1134 String title = ((TextView) mHttpAuthenticationDialog
1135 .findViewById(com.android.internal.R.id.alertTitle)).getText()
1136 .toString();
1137 String name = ((TextView) mHttpAuthenticationDialog
1138 .findViewById(R.id.username_edit)).getText().toString();
1139 String password = ((TextView) mHttpAuthenticationDialog
1140 .findViewById(R.id.password_edit)).getText().toString();
1141 int focusId = mHttpAuthenticationDialog.getCurrentFocus()
1142 .getId();
1143 mHttpAuthenticationDialog.dismiss();
1144 showHttpAuthentication(mHttpAuthHandler, null, null, title,
1145 name, password, focusId);
1146 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001147 }
1148
Grace Kloba22ac16e2009-10-07 18:00:23 -07001149 @Override
1150 public void onLowMemory() {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001151 super.onLowMemory();
1152 mTabControl.freeMemory();
1153 }
1154
Mike Reed7bfa63b2009-05-28 11:08:32 -04001155 private boolean resumeWebViewTimers() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001156 Tab tab = mTabControl.getCurrentTab();
1157 boolean inLoad = tab.inLoad();
1158 if ((!mActivityInPause && !inLoad) || (mActivityInPause && inLoad)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001159 CookieSyncManager.getInstance().startSync();
Grace Kloba22ac16e2009-10-07 18:00:23 -07001160 WebView w = tab.getWebView();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001161 if (w != null) {
1162 w.resumeTimers();
1163 }
1164 return true;
1165 } else {
1166 return false;
1167 }
1168 }
1169
Mike Reed7bfa63b2009-05-28 11:08:32 -04001170 private boolean pauseWebViewTimers() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001171 Tab tab = mTabControl.getCurrentTab();
1172 boolean inLoad = tab.inLoad();
1173 if (mActivityInPause && !inLoad) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001174 CookieSyncManager.getInstance().stopSync();
1175 WebView w = mTabControl.getCurrentWebView();
1176 if (w != null) {
1177 w.pauseTimers();
1178 }
1179 return true;
1180 } else {
1181 return false;
1182 }
1183 }
1184
Leon Scroggins1f005d32009-08-10 17:36:42 -04001185 // FIXME: Do we want to call this when loading google for the first time?
The Android Open Source Project0c908882009-03-03 19:32:16 -08001186 /*
1187 * This function is called when we are launching for the first time. We
1188 * are waiting for the login credentials before loading Google home
1189 * pages. This way the user will be logged in straight away.
1190 */
1191 private void waitForCredentials() {
1192 // Show a toast
1193 mCredsDlg = new ProgressDialog(this);
1194 mCredsDlg.setIndeterminate(true);
1195 mCredsDlg.setMessage(getText(R.string.retrieving_creds_dlg_msg));
1196 // If the user cancels the operation, then cancel the Google
1197 // Credentials request.
1198 mCredsDlg.setCancelMessage(mHandler.obtainMessage(CANCEL_CREDS_REQUEST));
1199 mCredsDlg.show();
1200
1201 // We set a timeout for the retrieval of credentials in onResume()
1202 // as that is when we have freed up some CPU time to get
1203 // the login credentials.
1204 }
1205
1206 /*
1207 * If we have received the credentials or we have timed out and we are
1208 * showing the credentials dialog, then it is time to move on.
1209 */
1210 private void resumeAfterCredentials() {
1211 if (mCredsDlg == null) {
1212 return;
1213 }
1214
1215 // Clear the toast
1216 if (mCredsDlg.isShowing()) {
1217 mCredsDlg.dismiss();
1218 }
1219 mCredsDlg = null;
1220
1221 // Clear any pending timeout
1222 mHandler.removeMessages(CANCEL_CREDS_REQUEST);
1223
1224 // Load the page
1225 WebView w = mTabControl.getCurrentWebView();
1226 if (w != null) {
Leon Scroggins92472e82010-02-17 16:32:28 -05001227 loadUrl(w, mSettings.getHomePage());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001228 }
1229
1230 // Update the settings, need to do this last as it can take a moment
1231 // to persist the settings. In the mean time we could be loading
1232 // content.
1233 mSettings.setLoginInitialized(this);
1234 }
1235
1236 // Open the icon database and retain all the icons for visited sites.
1237 private void retainIconsOnStartup() {
1238 final WebIconDatabase db = WebIconDatabase.getInstance();
1239 db.open(getDir("icons", 0).getPath());
1240 try {
1241 Cursor c = Browser.getAllBookmarks(mResolver);
1242 if (!c.moveToFirst()) {
1243 c.deactivate();
1244 return;
1245 }
1246 int urlIndex = c.getColumnIndex(Browser.BookmarkColumns.URL);
1247 do {
1248 String url = c.getString(urlIndex);
1249 db.retainIconForPageUrl(url);
1250 } while (c.moveToNext());
1251 c.deactivate();
1252 } catch (IllegalStateException e) {
1253 Log.e(LOGTAG, "retainIconsOnStartup", e);
1254 }
1255 }
1256
1257 // Helper method for getting the top window.
1258 WebView getTopWindow() {
1259 return mTabControl.getCurrentTopWebView();
1260 }
1261
Grace Kloba22ac16e2009-10-07 18:00:23 -07001262 TabControl getTabControl() {
1263 return mTabControl;
1264 }
1265
The Android Open Source Project0c908882009-03-03 19:32:16 -08001266 @Override
1267 public boolean onCreateOptionsMenu(Menu menu) {
1268 super.onCreateOptionsMenu(menu);
1269
1270 MenuInflater inflater = getMenuInflater();
1271 inflater.inflate(R.menu.browser, menu);
1272 mMenu = menu;
1273 updateInLoadMenuItems();
1274 return true;
1275 }
1276
1277 /**
1278 * As the menu can be open when loading state changes
1279 * we must manually update the state of the stop/reload menu
1280 * item
1281 */
1282 private void updateInLoadMenuItems() {
1283 if (mMenu == null) {
1284 return;
1285 }
1286 MenuItem src = mInLoad ?
1287 mMenu.findItem(R.id.stop_menu_id):
1288 mMenu.findItem(R.id.reload_menu_id);
1289 MenuItem dest = mMenu.findItem(R.id.stop_reload_menu_id);
1290 dest.setIcon(src.getIcon());
1291 dest.setTitle(src.getTitle());
1292 }
1293
1294 @Override
1295 public boolean onContextItemSelected(MenuItem item) {
1296 // chording is not an issue with context menus, but we use the same
1297 // options selector, so set mCanChord to true so we can access them.
1298 mCanChord = true;
1299 int id = item.getItemId();
Leon Scroggins96afcb12009-12-10 12:35:56 -05001300 boolean result = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001301 switch (id) {
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001302 // For the context menu from the title bar
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001303 case R.id.title_bar_copy_page_url:
Leon Scroggins96afcb12009-12-10 12:35:56 -05001304 Tab currentTab = mTabControl.getCurrentTab();
1305 if (null == currentTab) {
1306 result = false;
1307 break;
1308 }
1309 WebView mainView = currentTab.getWebView();
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001310 if (null == mainView) {
Leon Scroggins96afcb12009-12-10 12:35:56 -05001311 result = false;
1312 break;
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001313 }
Leon Scroggins96afcb12009-12-10 12:35:56 -05001314 copy(mainView.getUrl());
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001315 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001316 // -- Browser context menu
1317 case R.id.open_context_menu_id:
1318 case R.id.open_newtab_context_menu_id:
1319 case R.id.bookmark_context_menu_id:
1320 case R.id.save_link_context_menu_id:
1321 case R.id.share_link_context_menu_id:
1322 case R.id.copy_link_context_menu_id:
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001323 final WebView webView = getTopWindow();
1324 if (null == webView) {
Leon Scroggins96afcb12009-12-10 12:35:56 -05001325 result = false;
1326 break;
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001327 }
1328 final HashMap hrefMap = new HashMap();
1329 hrefMap.put("webview", webView);
1330 final Message msg = mHandler.obtainMessage(
1331 FOCUS_NODE_HREF, id, 0, hrefMap);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001332 webView.requestFocusNodeHref(msg);
1333 break;
1334
1335 default:
1336 // For other context menus
Leon Scroggins96afcb12009-12-10 12:35:56 -05001337 result = onOptionsItemSelected(item);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001338 }
1339 mCanChord = false;
Leon Scroggins96afcb12009-12-10 12:35:56 -05001340 return result;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001341 }
1342
1343 private Bundle createGoogleSearchSourceBundle(String source) {
1344 Bundle bundle = new Bundle();
Bjorn Bringert10d1cca2010-02-10 14:22:12 +00001345 bundle.putString(Search.SOURCE, source);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001346 return bundle;
1347 }
1348
Leon Scroggins8ad29922010-02-16 12:33:55 -05001349 /* package */ void editUrl() {
Leon Scroggins68579392009-09-15 15:31:54 -04001350 if (mOptionsMenuOpen) closeOptionsMenu();
Leon Scroggins5bbe9802009-07-31 13:10:55 -04001351 String url = (getTopWindow() == null) ? null : getTopWindow().getUrl();
Grace Kloba83f47342009-07-20 10:44:31 -07001352 startSearch(mSettings.getHomePage().equals(url) ? null : url, true,
Leon Scroggins8ad29922010-02-16 12:33:55 -05001353 null, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001354 }
1355
Leon Scroggins8ad29922010-02-16 12:33:55 -05001356 /**
1357 * Overriding this to insert a local information bundle
1358 */
The Android Open Source Project0c908882009-03-03 19:32:16 -08001359 @Override
1360 public void startSearch(String initialQuery, boolean selectInitialQuery,
1361 Bundle appSearchData, boolean globalSearch) {
1362 if (appSearchData == null) {
1363 appSearchData = createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_TYPE);
1364 }
1365 super.startSearch(initialQuery, selectInitialQuery, appSearchData, globalSearch);
1366 }
1367
Leon Scroggins1f005d32009-08-10 17:36:42 -04001368 /**
1369 * Switch tabs. Called by the TitleBarSet when sliding the title bar
1370 * results in changing tabs.
Leon Scroggins160a7e72009-08-14 18:28:01 -04001371 * @param index Index of the tab to change to, as defined by
1372 * mTabControl.getTabIndex(Tab t).
1373 * @return boolean True if we successfully switched to a different tab. If
1374 * the indexth tab is null, or if that tab is the same as
1375 * the current one, return false.
Leon Scroggins1f005d32009-08-10 17:36:42 -04001376 */
Leon Scroggins160a7e72009-08-14 18:28:01 -04001377 /* package */ boolean switchToTab(int index) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001378 Tab tab = mTabControl.getTab(index);
1379 Tab currentTab = mTabControl.getCurrentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04001380 if (tab == null || tab == currentTab) {
Leon Scroggins160a7e72009-08-14 18:28:01 -04001381 return false;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001382 }
1383 if (currentTab != null) {
1384 // currentTab may be null if it was just removed. In that case,
1385 // we do not need to remove it
1386 removeTabFromContentView(currentTab);
1387 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001388 mTabControl.setCurrentTab(tab);
1389 attachTabToContentView(tab);
Grace Klobaeb6eef42009-09-15 17:56:32 -07001390 resetTitleIconAndProgress();
1391 updateLockIconToLatest();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001392 return true;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001393 }
1394
Grace Kloba22ac16e2009-10-07 18:00:23 -07001395 /* package */ Tab openTabToHomePage() {
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001396 return openTabAndShow(mSettings.getHomePage(), false, null);
1397 }
1398
Leon Scroggins1f005d32009-08-10 17:36:42 -04001399 /* package */ void closeCurrentWindow() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001400 final Tab current = mTabControl.getCurrentTab();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001401 if (mTabControl.getTabCount() == 1) {
Leon Scroggins30444232009-09-04 18:36:20 -04001402 // This is the last tab. Open a new one, with the home
1403 // page and close the current one.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001404 openTabToHomePage();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001405 closeTab(current);
Leon Scroggins160a7e72009-08-14 18:28:01 -04001406 return;
1407 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07001408 final Tab parent = current.getParentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04001409 int indexToShow = -1;
1410 if (parent != null) {
1411 indexToShow = mTabControl.getTabIndex(parent);
1412 } else {
Leon Scroggins160a7e72009-08-14 18:28:01 -04001413 final int currentIndex = mTabControl.getCurrentIndex();
1414 // Try to move to the tab to the right
1415 indexToShow = currentIndex + 1;
1416 if (indexToShow > mTabControl.getTabCount() - 1) {
1417 // Try to move to the tab to the left
1418 indexToShow = currentIndex - 1;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001419 }
1420 }
Leon Scroggins160a7e72009-08-14 18:28:01 -04001421 if (switchToTab(indexToShow)) {
1422 // Close window
1423 closeTab(current);
1424 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001425 }
1426
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001427 private ActiveTabsPage mActiveTabsPage;
1428
1429 /**
1430 * Remove the active tabs page.
1431 * @param needToAttach If true, the active tabs page did not attach a tab
1432 * to the content view, so we need to do that here.
1433 */
1434 /* package */ void removeActiveTabPage(boolean needToAttach) {
1435 mContentView.removeView(mActiveTabsPage);
1436 mActiveTabsPage = null;
1437 mMenuState = R.id.MAIN_MENU;
1438 if (needToAttach) {
1439 attachTabToContentView(mTabControl.getCurrentTab());
1440 }
1441 getTopWindow().requestFocus();
1442 }
1443
The Android Open Source Project0c908882009-03-03 19:32:16 -08001444 @Override
1445 public boolean onOptionsItemSelected(MenuItem item) {
1446 if (!mCanChord) {
1447 // The user has already fired a shortcut with this hold down of the
1448 // menu key.
1449 return false;
1450 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001451 if (null == getTopWindow()) {
Leon Scroggins0d7ae0e2009-06-05 11:04:45 -04001452 return false;
1453 }
Grace Kloba6ee9c492009-07-13 10:04:34 -07001454 if (mMenuIsDown) {
1455 // The shortcut action consumes the MENU. Even if it is still down,
1456 // it won't trigger the next shortcut action. In the case of the
1457 // shortcut action triggering a new activity, like Bookmarks, we
1458 // won't get onKeyUp for MENU. So it is important to reset it here.
1459 mMenuIsDown = false;
1460 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001461 switch (item.getItemId()) {
1462 // -- Main menu
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001463 case R.id.new_tab_menu_id:
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001464 openTabToHomePage();
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001465 break;
1466
Leon Scroggins64b80f32009-08-07 12:03:34 -04001467 case R.id.goto_menu_id:
Leon Scroggins8ad29922010-02-16 12:33:55 -05001468 editUrl();
Leon Scrogginsb3a5bed2009-09-28 11:21:56 -04001469 break;
1470
1471 case R.id.bookmarks_menu_id:
Leon Scroggins30444232009-09-04 18:36:20 -04001472 bookmarksOrHistoryPicker(false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001473 break;
1474
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001475 case R.id.active_tabs_menu_id:
1476 mActiveTabsPage = new ActiveTabsPage(this, mTabControl);
1477 removeTabFromContentView(mTabControl.getCurrentTab());
Leon Scroggins43de6162009-09-14 19:59:58 -04001478 hideFakeTitleBar();
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001479 mContentView.addView(mActiveTabsPage, COVER_SCREEN_PARAMS);
1480 mActiveTabsPage.requestFocus();
1481 mMenuState = EMPTY_MENU;
1482 break;
1483
Leon Scroggins1f005d32009-08-10 17:36:42 -04001484 case R.id.add_bookmark_menu_id:
1485 Intent i = new Intent(BrowserActivity.this,
1486 AddBookmarkPage.class);
1487 WebView w = getTopWindow();
1488 i.putExtra("url", w.getUrl());
1489 i.putExtra("title", w.getTitle());
Grace Kloba83cdb2c2009-09-16 00:48:57 -07001490 i.putExtra("touch_icon_url", w.getTouchIconUrl());
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01001491 i.putExtra("thumbnail", createScreenshot(w));
Leon Scroggins1f005d32009-08-10 17:36:42 -04001492 startActivity(i);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001493 break;
1494
1495 case R.id.stop_reload_menu_id:
1496 if (mInLoad) {
1497 stopLoading();
1498 } else {
1499 getTopWindow().reload();
1500 }
1501 break;
1502
1503 case R.id.back_menu_id:
1504 getTopWindow().goBack();
1505 break;
1506
1507 case R.id.forward_menu_id:
1508 getTopWindow().goForward();
1509 break;
1510
1511 case R.id.close_menu_id:
1512 // Close the subwindow if it exists.
1513 if (mTabControl.getCurrentSubWindow() != null) {
1514 dismissSubWindow(mTabControl.getCurrentTab());
1515 break;
1516 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001517 closeCurrentWindow();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001518 break;
1519
1520 case R.id.homepage_menu_id:
Grace Kloba22ac16e2009-10-07 18:00:23 -07001521 Tab current = mTabControl.getCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001522 if (current != null) {
1523 dismissSubWindow(current);
Leon Scroggins92472e82010-02-17 16:32:28 -05001524 loadUrl(current.getWebView(), mSettings.getHomePage());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001525 }
1526 break;
1527
1528 case R.id.preferences_menu_id:
1529 Intent intent = new Intent(this,
1530 BrowserPreferencesPage.class);
Leon Scrogginsd5304942009-12-10 16:11:39 -05001531 intent.putExtra(BrowserPreferencesPage.CURRENT_PAGE,
1532 getTopWindow().getUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001533 startActivityForResult(intent, PREFERENCES_PAGE);
1534 break;
1535
1536 case R.id.find_menu_id:
1537 if (null == mFindDialog) {
1538 mFindDialog = new FindDialog(this);
1539 }
1540 mFindDialog.setWebView(getTopWindow());
1541 mFindDialog.show();
1542 mMenuState = EMPTY_MENU;
1543 break;
1544
1545 case R.id.select_text_id:
1546 getTopWindow().emulateShiftHeld();
1547 break;
1548 case R.id.page_info_menu_id:
1549 showPageInfo(mTabControl.getCurrentTab(), false);
1550 break;
1551
1552 case R.id.classic_history_menu_id:
Leon Scroggins30444232009-09-04 18:36:20 -04001553 bookmarksOrHistoryPicker(true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001554 break;
1555
Leon Scroggins96afcb12009-12-10 12:35:56 -05001556 case R.id.title_bar_share_page_url:
The Android Open Source Project0c908882009-03-03 19:32:16 -08001557 case R.id.share_page_menu_id:
Leon Scroggins96afcb12009-12-10 12:35:56 -05001558 Tab currentTab = mTabControl.getCurrentTab();
1559 if (null == currentTab) {
1560 mCanChord = false;
1561 return false;
1562 }
1563 currentTab.populatePickerData();
1564 sharePage(this, currentTab.getTitle(),
1565 currentTab.getUrl(), currentTab.getFavicon(),
1566 createScreenshot(currentTab.getWebView()));
The Android Open Source Project0c908882009-03-03 19:32:16 -08001567 break;
1568
1569 case R.id.dump_nav_menu_id:
1570 getTopWindow().debugDump();
1571 break;
1572
Andrei Popescu7a8b88b2010-02-02 00:30:38 +00001573 case R.id.dump_counters_menu_id:
1574 getTopWindow().dumpV8Counters();
1575 break;
1576
The Android Open Source Project0c908882009-03-03 19:32:16 -08001577 case R.id.zoom_in_menu_id:
1578 getTopWindow().zoomIn();
1579 break;
1580
1581 case R.id.zoom_out_menu_id:
1582 getTopWindow().zoomOut();
1583 break;
1584
1585 case R.id.view_downloads_menu_id:
1586 viewDownloads(null);
1587 break;
1588
The Android Open Source Project0c908882009-03-03 19:32:16 -08001589 case R.id.window_one_menu_id:
1590 case R.id.window_two_menu_id:
1591 case R.id.window_three_menu_id:
1592 case R.id.window_four_menu_id:
1593 case R.id.window_five_menu_id:
1594 case R.id.window_six_menu_id:
1595 case R.id.window_seven_menu_id:
1596 case R.id.window_eight_menu_id:
1597 {
1598 int menuid = item.getItemId();
1599 for (int id = 0; id < WINDOW_SHORTCUT_ID_ARRAY.length; id++) {
1600 if (WINDOW_SHORTCUT_ID_ARRAY[id] == menuid) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001601 Tab desiredTab = mTabControl.getTab(id);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001602 if (desiredTab != null &&
1603 desiredTab != mTabControl.getCurrentTab()) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001604 switchToTab(id);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001605 }
1606 break;
1607 }
1608 }
1609 }
1610 break;
1611
1612 default:
1613 if (!super.onOptionsItemSelected(item)) {
1614 return false;
1615 }
1616 // Otherwise fall through.
1617 }
1618 mCanChord = false;
1619 return true;
1620 }
1621
1622 public void closeFind() {
1623 mMenuState = R.id.MAIN_MENU;
1624 }
1625
Grace Kloba22ac16e2009-10-07 18:00:23 -07001626 @Override
1627 public boolean onPrepareOptionsMenu(Menu menu) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001628 // This happens when the user begins to hold down the menu key, so
1629 // allow them to chord to get a shortcut.
1630 mCanChord = true;
1631 // Note: setVisible will decide whether an item is visible; while
1632 // setEnabled() will decide whether an item is enabled, which also means
1633 // whether the matching shortcut key will function.
1634 super.onPrepareOptionsMenu(menu);
1635 switch (mMenuState) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001636 case EMPTY_MENU:
1637 if (mCurrentMenuState != mMenuState) {
1638 menu.setGroupVisible(R.id.MAIN_MENU, false);
1639 menu.setGroupEnabled(R.id.MAIN_MENU, false);
1640 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001641 }
1642 break;
1643 default:
1644 if (mCurrentMenuState != mMenuState) {
1645 menu.setGroupVisible(R.id.MAIN_MENU, true);
1646 menu.setGroupEnabled(R.id.MAIN_MENU, true);
1647 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001648 }
1649 final WebView w = getTopWindow();
1650 boolean canGoBack = false;
1651 boolean canGoForward = false;
1652 boolean isHome = false;
1653 if (w != null) {
1654 canGoBack = w.canGoBack();
1655 canGoForward = w.canGoForward();
1656 isHome = mSettings.getHomePage().equals(w.getUrl());
1657 }
1658 final MenuItem back = menu.findItem(R.id.back_menu_id);
1659 back.setEnabled(canGoBack);
1660
1661 final MenuItem home = menu.findItem(R.id.homepage_menu_id);
1662 home.setEnabled(!isHome);
1663
1664 menu.findItem(R.id.forward_menu_id)
1665 .setEnabled(canGoForward);
1666
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001667 menu.findItem(R.id.new_tab_menu_id).setEnabled(
Grace Kloba22ac16e2009-10-07 18:00:23 -07001668 mTabControl.canCreateNewTab());
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001669
The Android Open Source Project0c908882009-03-03 19:32:16 -08001670 // decide whether to show the share link option
1671 PackageManager pm = getPackageManager();
1672 Intent send = new Intent(Intent.ACTION_SEND);
1673 send.setType("text/plain");
1674 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1675 menu.findItem(R.id.share_page_menu_id).setVisible(ri != null);
1676
The Android Open Source Project0c908882009-03-03 19:32:16 -08001677 boolean isNavDump = mSettings.isNavDump();
1678 final MenuItem nav = menu.findItem(R.id.dump_nav_menu_id);
1679 nav.setVisible(isNavDump);
1680 nav.setEnabled(isNavDump);
Andrei Popescu7a8b88b2010-02-02 00:30:38 +00001681
1682 boolean showDebugSettings = mSettings.showDebugSettings();
1683 final MenuItem counter = menu.findItem(R.id.dump_counters_menu_id);
1684 counter.setVisible(showDebugSettings);
1685 counter.setEnabled(showDebugSettings);
1686
The Android Open Source Project0c908882009-03-03 19:32:16 -08001687 break;
1688 }
1689 mCurrentMenuState = mMenuState;
1690 return true;
1691 }
1692
1693 @Override
1694 public void onCreateContextMenu(ContextMenu menu, View v,
1695 ContextMenuInfo menuInfo) {
1696 WebView webview = (WebView) v;
1697 WebView.HitTestResult result = webview.getHitTestResult();
1698 if (result == null) {
1699 return;
1700 }
1701
1702 int type = result.getType();
1703 if (type == WebView.HitTestResult.UNKNOWN_TYPE) {
1704 Log.w(LOGTAG,
1705 "We should not show context menu when nothing is touched");
1706 return;
1707 }
1708 if (type == WebView.HitTestResult.EDIT_TEXT_TYPE) {
1709 // let TextView handles context menu
1710 return;
1711 }
1712
1713 // Note, http://b/issue?id=1106666 is requesting that
1714 // an inflated menu can be used again. This is not available
1715 // yet, so inflate each time (yuk!)
1716 MenuInflater inflater = getMenuInflater();
1717 inflater.inflate(R.menu.browsercontext, menu);
1718
1719 // Show the correct menu group
1720 String extra = result.getExtra();
1721 menu.setGroupVisible(R.id.PHONE_MENU,
1722 type == WebView.HitTestResult.PHONE_TYPE);
1723 menu.setGroupVisible(R.id.EMAIL_MENU,
1724 type == WebView.HitTestResult.EMAIL_TYPE);
1725 menu.setGroupVisible(R.id.GEO_MENU,
1726 type == WebView.HitTestResult.GEO_TYPE);
1727 menu.setGroupVisible(R.id.IMAGE_MENU,
1728 type == WebView.HitTestResult.IMAGE_TYPE
1729 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1730 menu.setGroupVisible(R.id.ANCHOR_MENU,
1731 type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1732 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1733
1734 // Setup custom handling depending on the type
1735 switch (type) {
1736 case WebView.HitTestResult.PHONE_TYPE:
1737 menu.setHeaderTitle(Uri.decode(extra));
1738 menu.findItem(R.id.dial_context_menu_id).setIntent(
1739 new Intent(Intent.ACTION_VIEW, Uri
1740 .parse(WebView.SCHEME_TEL + extra)));
1741 Intent addIntent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
1742 addIntent.putExtra(Insert.PHONE, Uri.decode(extra));
Cary Clark5e335a32009-09-22 14:53:11 -04001743 addIntent.setType(ContactsContract.Contacts.CONTENT_ITEM_TYPE);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001744 menu.findItem(R.id.add_contact_context_menu_id).setIntent(
1745 addIntent);
1746 menu.findItem(R.id.copy_phone_context_menu_id).setOnMenuItemClickListener(
1747 new Copy(extra));
1748 break;
1749
1750 case WebView.HitTestResult.EMAIL_TYPE:
1751 menu.setHeaderTitle(extra);
1752 menu.findItem(R.id.email_context_menu_id).setIntent(
1753 new Intent(Intent.ACTION_VIEW, Uri
1754 .parse(WebView.SCHEME_MAILTO + extra)));
1755 menu.findItem(R.id.copy_mail_context_menu_id).setOnMenuItemClickListener(
1756 new Copy(extra));
1757 break;
1758
1759 case WebView.HitTestResult.GEO_TYPE:
1760 menu.setHeaderTitle(extra);
1761 menu.findItem(R.id.map_context_menu_id).setIntent(
1762 new Intent(Intent.ACTION_VIEW, Uri
1763 .parse(WebView.SCHEME_GEO
1764 + URLEncoder.encode(extra))));
1765 menu.findItem(R.id.copy_geo_context_menu_id).setOnMenuItemClickListener(
1766 new Copy(extra));
1767 break;
1768
1769 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1770 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
1771 TextView titleView = (TextView) LayoutInflater.from(this)
1772 .inflate(android.R.layout.browser_link_context_header,
1773 null);
1774 titleView.setText(extra);
1775 menu.setHeaderView(titleView);
1776 // decide whether to show the open link in new tab option
1777 menu.findItem(R.id.open_newtab_context_menu_id).setVisible(
Grace Kloba22ac16e2009-10-07 18:00:23 -07001778 mTabControl.canCreateNewTab());
Ben Murdochde353622009-10-12 10:29:00 +01001779 menu.findItem(R.id.bookmark_context_menu_id).setVisible(
1780 Bookmarks.urlHasAcceptableScheme(extra));
The Android Open Source Project0c908882009-03-03 19:32:16 -08001781 PackageManager pm = getPackageManager();
1782 Intent send = new Intent(Intent.ACTION_SEND);
1783 send.setType("text/plain");
1784 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1785 menu.findItem(R.id.share_link_context_menu_id).setVisible(ri != null);
1786 if (type == WebView.HitTestResult.SRC_ANCHOR_TYPE) {
1787 break;
1788 }
1789 // otherwise fall through to handle image part
1790 case WebView.HitTestResult.IMAGE_TYPE:
1791 if (type == WebView.HitTestResult.IMAGE_TYPE) {
1792 menu.setHeaderTitle(extra);
1793 }
1794 menu.findItem(R.id.view_image_context_menu_id).setIntent(
1795 new Intent(Intent.ACTION_VIEW, Uri.parse(extra)));
1796 menu.findItem(R.id.download_context_menu_id).
1797 setOnMenuItemClickListener(new Download(extra));
Ben Murdoch4f75ba22009-10-27 11:48:28 +00001798 menu.findItem(R.id.set_wallpaper_context_menu_id).
1799 setOnMenuItemClickListener(new SetAsWallpaper(extra));
The Android Open Source Project0c908882009-03-03 19:32:16 -08001800 break;
1801
1802 default:
1803 Log.w(LOGTAG, "We should not get here.");
1804 break;
1805 }
Leon Scrogginsb2b19f52009-10-09 16:10:00 -04001806 hideFakeTitleBar();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001807 }
1808
The Android Open Source Project0c908882009-03-03 19:32:16 -08001809 // Attach the given tab to the content view.
Grace Klobac928c302009-09-17 11:51:21 -07001810 // this should only be called for the current tab.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001811 private void attachTabToContentView(Tab t) {
Steve Block2bc69912009-07-30 14:45:13 +01001812 // Attach the container that contains the main WebView and any other UI
1813 // associated with the tab.
Patrick Scottd0119532009-09-17 08:00:31 -04001814 t.attachTabToContentView(mContentView);
Ben Murdochbff2d602009-07-01 20:19:05 +01001815
1816 if (mShouldShowErrorConsole) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001817 ErrorConsoleView errorConsole = t.getErrorConsole(true);
Ben Murdochbff2d602009-07-01 20:19:05 +01001818 if (errorConsole.numberOfErrors() == 0) {
1819 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
1820 } else {
1821 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
1822 }
1823
1824 mErrorConsoleContainer.addView(errorConsole,
Romain Guy15b8ec62010-01-08 15:06:43 -08001825 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
Ben Murdochbff2d602009-07-01 20:19:05 +01001826 ViewGroup.LayoutParams.WRAP_CONTENT));
1827 }
1828
Leon Scroggins39ab28e2009-09-02 21:20:30 -04001829 WebView view = t.getWebView();
Leon Scroggins55a5bc22009-09-04 17:00:08 -04001830 view.setEmbeddedTitleBar(mTitleBar);
Leon Scroggins58d56c62010-01-28 15:12:40 -05001831 if (t.isInVoiceSearchMode()) {
1832 showVoiceTitleBar(t.getVoiceDisplayTitle());
1833 } else {
1834 revertVoiceTitleBar();
1835 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001836 // Request focus on the top window.
1837 t.getTopWindow().requestFocus();
1838 }
1839
1840 // Attach a sub window to the main WebView of the given tab.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001841 void attachSubWindow(Tab t) {
Patrick Scottd0119532009-09-17 08:00:31 -04001842 t.attachSubWindow(mContentView);
1843 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001844 }
1845
1846 // Remove the given tab from the content view.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001847 private void removeTabFromContentView(Tab t) {
Steve Block2bc69912009-07-30 14:45:13 +01001848 // Remove the container that contains the main WebView.
Patrick Scottd0119532009-09-17 08:00:31 -04001849 t.removeTabFromContentView(mContentView);
Ben Murdochbff2d602009-07-01 20:19:05 +01001850
Grace Kloba22ac16e2009-10-07 18:00:23 -07001851 ErrorConsoleView errorConsole = t.getErrorConsole(false);
1852 if (errorConsole != null) {
1853 mErrorConsoleContainer.removeView(errorConsole);
Ben Murdochbff2d602009-07-01 20:19:05 +01001854 }
1855
Leon Scroggins39ab28e2009-09-02 21:20:30 -04001856 WebView view = t.getWebView();
Leon Scrogginsbb85b902009-09-14 19:27:20 -04001857 if (view != null) {
1858 view.setEmbeddedTitleBar(null);
1859 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001860 }
1861
1862 // Remove the sub window if it exists. Also called by TabControl when the
1863 // user clicks the 'X' to dismiss a sub window.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001864 /* package */ void dismissSubWindow(Tab t) {
Patrick Scottd0119532009-09-17 08:00:31 -04001865 t.removeSubWindow(mContentView);
Grace Kloba22ac16e2009-10-07 18:00:23 -07001866 // dismiss the subwindow. This will destroy the WebView.
1867 t.dismissSubWindow();
Patrick Scottd0119532009-09-17 08:00:31 -04001868 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001869 }
1870
Leon Scroggins1f005d32009-08-10 17:36:42 -04001871 // A wrapper function of {@link #openTabAndShow(UrlData, boolean, String)}
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07001872 // that accepts url as string.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001873 private Tab openTabAndShow(String url, boolean closeOnExit, String appId) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001874 return openTabAndShow(new UrlData(url), closeOnExit, appId);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001875 }
1876
1877 // This method does a ton of stuff. It will attempt to create a new tab
1878 // if we haven't reached MAX_TABS. Otherwise it uses the current tab. If
Leon Scroggins1f005d32009-08-10 17:36:42 -04001879 // url isn't null, it will load the given url.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001880 /* package */Tab openTabAndShow(UrlData urlData, boolean closeOnExit,
1881 String appId) {
1882 final Tab currentTab = mTabControl.getCurrentTab();
1883 if (mTabControl.canCreateNewTab()) {
1884 final Tab tab = mTabControl.createNewTab(closeOnExit, appId,
1885 urlData.mUrl);
Leon Scroggins1f005d32009-08-10 17:36:42 -04001886 WebView webview = tab.getWebView();
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001887 // If the last tab was removed from the active tabs page, currentTab
1888 // will be null.
1889 if (currentTab != null) {
1890 removeTabFromContentView(currentTab);
1891 }
Patrick Scott8bbd69f2009-08-14 13:35:53 -04001892 // We must set the new tab as the current tab to reflect the old
1893 // animation behavior.
1894 mTabControl.setCurrentTab(tab);
Grace Klobaeb6eef42009-09-15 17:56:32 -07001895 attachTabToContentView(tab);
Leon Scroggins160a7e72009-08-14 18:28:01 -04001896 if (!urlData.isEmpty()) {
Patrick Scott9d53da02010-02-19 10:19:01 -05001897 loadUrlDataIn(tab, urlData);
Leon Scroggins1f005d32009-08-10 17:36:42 -04001898 }
1899 return tab;
1900 } else {
1901 // Get rid of the subwindow if it exists
1902 dismissSubWindow(currentTab);
1903 if (!urlData.isEmpty()) {
1904 // Load the given url.
Patrick Scott9d53da02010-02-19 10:19:01 -05001905 loadUrlDataIn(currentTab, urlData);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001906 }
Leon Scroggins58d56c62010-01-28 15:12:40 -05001907 return currentTab;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001908 }
1909 }
1910
Grace Kloba22ac16e2009-10-07 18:00:23 -07001911 private Tab openTab(String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001912 if (mSettings.openInBackground()) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001913 Tab t = mTabControl.createNewTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001914 if (t != null) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001915 WebView view = t.getWebView();
Leon Scroggins92472e82010-02-17 16:32:28 -05001916 loadUrl(view, url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001917 }
Grace Klobac9181842009-04-14 08:53:22 -07001918 return t;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001919 } else {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001920 return openTabAndShow(url, false, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001921 }
1922 }
1923
1924 private class Copy implements OnMenuItemClickListener {
1925 private CharSequence mText;
1926
1927 public boolean onMenuItemClick(MenuItem item) {
1928 copy(mText);
1929 return true;
1930 }
1931
1932 public Copy(CharSequence toCopy) {
1933 mText = toCopy;
1934 }
1935 }
1936
1937 private class Download implements OnMenuItemClickListener {
1938 private String mText;
1939
1940 public boolean onMenuItemClick(MenuItem item) {
1941 onDownloadStartNoStream(mText, null, null, null, -1);
1942 return true;
1943 }
1944
1945 public Download(String toDownload) {
1946 mText = toDownload;
1947 }
1948 }
1949
Ben Murdoch4f75ba22009-10-27 11:48:28 +00001950 private class SetAsWallpaper extends Thread implements
1951 OnMenuItemClickListener, DialogInterface.OnCancelListener {
1952 private URL mUrl;
1953 private ProgressDialog mWallpaperProgress;
1954 private boolean mCanceled = false;
1955
1956 public SetAsWallpaper(String url) {
1957 try {
1958 mUrl = new URL(url);
1959 } catch (MalformedURLException e) {
1960 mUrl = null;
1961 }
1962 }
1963
1964 public void onCancel(DialogInterface dialog) {
1965 mCanceled = true;
1966 }
1967
1968 public boolean onMenuItemClick(MenuItem item) {
1969 if (mUrl != null) {
1970 // The user may have tried to set a image with a large file size as their
1971 // background so it may take a few moments to perform the operation. Display
1972 // a progress spinner while it is working.
1973 mWallpaperProgress = new ProgressDialog(BrowserActivity.this);
1974 mWallpaperProgress.setIndeterminate(true);
1975 mWallpaperProgress.setMessage(getText(R.string.progress_dialog_setting_wallpaper));
1976 mWallpaperProgress.setCancelable(true);
1977 mWallpaperProgress.setOnCancelListener(this);
1978 mWallpaperProgress.show();
1979 start();
1980 }
1981 return true;
1982 }
1983
1984 public void run() {
1985 Drawable oldWallpaper = BrowserActivity.this.getWallpaper();
1986 try {
1987 // TODO: This will cause the resource to be downloaded again, when we
1988 // should in most cases be able to grab it from the cache. To fix this
1989 // we should query WebCore to see if we can access a cached version and
1990 // instead open an input stream on that. This pattern could also be used
1991 // in the download manager where the same problem exists.
1992 InputStream inputstream = mUrl.openStream();
1993 if (inputstream != null) {
1994 setWallpaper(inputstream);
1995 }
1996 } catch (IOException e) {
1997 Log.e(LOGTAG, "Unable to set new wallpaper");
1998 // Act as though the user canceled the operation so we try to
1999 // restore the old wallpaper.
2000 mCanceled = true;
2001 }
2002
2003 if (mCanceled) {
2004 // Restore the old wallpaper if the user cancelled whilst we were setting
2005 // the new wallpaper.
2006 int width = oldWallpaper.getIntrinsicWidth();
2007 int height = oldWallpaper.getIntrinsicHeight();
2008 Bitmap bm = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
2009 Canvas canvas = new Canvas(bm);
2010 oldWallpaper.setBounds(0, 0, width, height);
2011 oldWallpaper.draw(canvas);
2012 try {
2013 setWallpaper(bm);
2014 } catch (IOException e) {
2015 Log.e(LOGTAG, "Unable to restore old wallpaper.");
2016 }
2017 mCanceled = false;
2018 }
2019
2020 if (mWallpaperProgress.isShowing()) {
2021 mWallpaperProgress.dismiss();
2022 }
2023 }
2024 }
2025
The Android Open Source Project0c908882009-03-03 19:32:16 -08002026 private void copy(CharSequence text) {
2027 try {
2028 IClipboard clip = IClipboard.Stub.asInterface(ServiceManager.getService("clipboard"));
2029 if (clip != null) {
2030 clip.setClipboardText(text);
2031 }
2032 } catch (android.os.RemoteException e) {
2033 Log.e(LOGTAG, "Copy failed", e);
2034 }
2035 }
2036
2037 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08002038 * Resets the browser title-view to whatever it must be
2039 * (for example, if we had a loading error)
2040 * When we have a new page, we call resetTitle, when we
2041 * have to reset the titlebar to whatever it used to be
2042 * (for example, if the user chose to stop loading), we
2043 * call resetTitleAndRevertLockIcon.
2044 */
2045 /* package */ void resetTitleAndRevertLockIcon() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002046 mTabControl.getCurrentTab().revertLockIcon();
2047 updateLockIconToLatest();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002048 resetTitleIconAndProgress();
2049 }
2050
2051 /**
2052 * Reset the title, favicon, and progress.
2053 */
2054 private void resetTitleIconAndProgress() {
2055 WebView current = mTabControl.getCurrentWebView();
2056 if (current == null) {
2057 return;
2058 }
2059 resetTitleAndIcon(current);
2060 int progress = current.getProgress();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002061 current.getWebChromeClient().onProgressChanged(current, progress);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002062 }
2063
2064 // Reset the title and the icon based on the given item.
2065 private void resetTitleAndIcon(WebView view) {
2066 WebHistoryItem item = view.copyBackForwardList().getCurrentItem();
2067 if (item != null) {
Leon Scroggins68579392009-09-15 15:31:54 -04002068 setUrlTitle(item.getUrl(), item.getTitle());
The Android Open Source Project0c908882009-03-03 19:32:16 -08002069 setFavicon(item.getFavicon());
2070 } else {
Leon Scroggins68579392009-09-15 15:31:54 -04002071 setUrlTitle(null, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002072 setFavicon(null);
2073 }
2074 }
2075
2076 /**
2077 * Sets a title composed of the URL and the title string.
2078 * @param url The URL of the site being loaded.
2079 * @param title The title of the site being loaded.
2080 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07002081 void setUrlTitle(String url, String title) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002082 mUrl = url;
2083 mTitle = title;
2084
Leon Scroggins58d56c62010-01-28 15:12:40 -05002085 // If we are in voice search mode, the title has already been set.
2086 if (mTabControl.getCurrentTab().isInVoiceSearchMode()) return;
2087 mTitleBar.setDisplayTitle(url);
2088 mFakeTitleBar.setDisplayTitle(url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002089 }
2090
2091 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08002092 * @param url The URL to build a title version of the URL from.
2093 * @return The title version of the URL or null if fails.
2094 * The title version of the URL can be either the URL hostname,
2095 * or the hostname with an "https://" prefix (for secure URLs),
2096 * or an empty string if, for example, the URL in question is a
2097 * file:// URL with no hostname.
2098 */
Leon Scroggins32e14a62009-06-11 10:26:34 -04002099 /* package */ static String buildTitleUrl(String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002100 String titleUrl = null;
2101
2102 if (url != null) {
2103 try {
2104 // parse the url string
2105 URL urlObj = new URL(url);
2106 if (urlObj != null) {
2107 titleUrl = "";
2108
2109 String protocol = urlObj.getProtocol();
2110 String host = urlObj.getHost();
2111
2112 if (host != null && 0 < host.length()) {
2113 titleUrl = host;
2114 if (protocol != null) {
2115 // if a secure site, add an "https://" prefix!
2116 if (protocol.equalsIgnoreCase("https")) {
2117 titleUrl = protocol + "://" + host;
2118 }
2119 }
2120 }
2121 }
2122 } catch (MalformedURLException e) {}
2123 }
2124
2125 return titleUrl;
2126 }
2127
2128 // Set the favicon in the title bar.
Grace Kloba22ac16e2009-10-07 18:00:23 -07002129 void setFavicon(Bitmap icon) {
Leon Scroggins68579392009-09-15 15:31:54 -04002130 mTitleBar.setFavicon(icon);
Leon Scrogginsfe87bd32009-10-06 10:10:00 -04002131 mFakeTitleBar.setFavicon(icon);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002132 }
2133
2134 /**
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002135 * Close the tab, remove its associated title bar, and adjust mTabControl's
2136 * current tab to a valid value.
Leon Scroggins1f005d32009-08-10 17:36:42 -04002137 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07002138 /* package */ void closeTab(Tab t) {
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002139 int currentIndex = mTabControl.getCurrentIndex();
2140 int removeIndex = mTabControl.getTabIndex(t);
Leon Scroggins1f005d32009-08-10 17:36:42 -04002141 mTabControl.removeTab(t);
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002142 if (currentIndex >= removeIndex && currentIndex != 0) {
2143 currentIndex--;
2144 }
2145 mTabControl.setCurrentTab(mTabControl.getTab(currentIndex));
Andrei Popescua5bf1de2009-09-23 16:39:23 +01002146 resetTitleIconAndProgress();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002147 }
2148
2149 private void goBackOnePageOrQuit() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002150 Tab current = mTabControl.getCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002151 if (current == null) {
2152 /*
2153 * Instead of finishing the activity, simply push this to the back
2154 * of the stack and let ActivityManager to choose the foreground
2155 * activity. As BrowserActivity is singleTask, it will be always the
2156 * root of the task. So we can use either true or false for
2157 * moveTaskToBack().
2158 */
2159 moveTaskToBack(true);
Grace Kloba00d85e72009-09-23 18:50:05 -07002160 return;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002161 }
2162 WebView w = current.getWebView();
2163 if (w.canGoBack()) {
2164 w.goBack();
2165 } else {
2166 // Check to see if we are closing a window that was created by
2167 // another window. If so, we switch back to that window.
Grace Kloba22ac16e2009-10-07 18:00:23 -07002168 Tab parent = current.getParentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002169 if (parent != null) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04002170 switchToTab(mTabControl.getTabIndex(parent));
2171 // Now we close the other tab
2172 closeTab(current);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002173 } else {
2174 if (current.closeOnExit()) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002175 // force the tab's inLoad() to be false as we are going to
2176 // either finish the activity or remove the tab. This will
2177 // ensure pauseWebViewTimers() taking action.
2178 mTabControl.getCurrentTab().clearInLoad();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002179 if (mTabControl.getTabCount() == 1) {
2180 finish();
2181 return;
2182 }
Mike Reed7bfa63b2009-05-28 11:08:32 -04002183 // call pauseWebViewTimers() now, we won't be able to call
2184 // it in onPause() as the WebView won't be valid.
Grace Klobaec1b5ad2009-08-18 08:42:32 -07002185 // Temporarily change mActivityInPause to be true as
2186 // pauseWebViewTimers() will do nothing if mActivityInPause
2187 // is false.
Grace Kloba918e1d72009-08-13 14:55:06 -07002188 boolean savedState = mActivityInPause;
2189 if (savedState) {
Grace Klobaec1b5ad2009-08-18 08:42:32 -07002190 Log.e(LOGTAG, "BrowserActivity is already paused "
2191 + "while handing goBackOnePageOrQuit.");
Grace Kloba918e1d72009-08-13 14:55:06 -07002192 }
2193 mActivityInPause = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -04002194 pauseWebViewTimers();
Grace Kloba918e1d72009-08-13 14:55:06 -07002195 mActivityInPause = savedState;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002196 removeTabFromContentView(current);
2197 mTabControl.removeTab(current);
2198 }
2199 /*
2200 * Instead of finishing the activity, simply push this to the back
2201 * of the stack and let ActivityManager to choose the foreground
2202 * activity. As BrowserActivity is singleTask, it will be always the
2203 * root of the task. So we can use either true or false for
2204 * moveTaskToBack().
2205 */
2206 moveTaskToBack(true);
2207 }
2208 }
2209 }
2210
Grace Kloba22ac16e2009-10-07 18:00:23 -07002211 boolean isMenuDown() {
2212 return mMenuIsDown;
2213 }
2214
Grace Kloba5942df02009-09-18 11:48:29 -07002215 @Override
2216 public boolean onKeyDown(int keyCode, KeyEvent event) {
Leon Scrogginsf65b50d2009-12-08 10:44:28 -05002217 // Even if MENU is already held down, we need to call to super to open
2218 // the IME on long press.
2219 if (KeyEvent.KEYCODE_MENU == keyCode) {
2220 mMenuIsDown = true;
2221 return super.onKeyDown(keyCode, event);
2222 }
Grace Kloba5942df02009-09-18 11:48:29 -07002223 // The default key mode is DEFAULT_KEYS_SEARCH_LOCAL. As the MENU is
2224 // still down, we don't want to trigger the search. Pretend to consume
2225 // the key and do nothing.
2226 if (mMenuIsDown) return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002227
Grace Kloba5942df02009-09-18 11:48:29 -07002228 switch(keyCode) {
Grace Kloba5942df02009-09-18 11:48:29 -07002229 case KeyEvent.KEYCODE_SPACE:
Grace Klobada0fe552009-09-22 18:17:24 -07002230 // WebView/WebTextView handle the keys in the KeyDown. As
2231 // the Activity's shortcut keys are only handled when WebView
2232 // doesn't, have to do it in onKeyDown instead of onKeyUp.
2233 if (event.isShiftPressed()) {
2234 getTopWindow().pageUp(false);
2235 } else {
2236 getTopWindow().pageDown(false);
2237 }
Grace Kloba5942df02009-09-18 11:48:29 -07002238 return true;
2239 case KeyEvent.KEYCODE_BACK:
2240 if (event.getRepeatCount() == 0) {
2241 event.startTracking();
2242 return true;
2243 } else if (mCustomView == null && mActiveTabsPage == null
2244 && event.isLongPress()) {
2245 bookmarksOrHistoryPicker(true);
2246 return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002247 }
Grace Kloba5942df02009-09-18 11:48:29 -07002248 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002249 }
Grace Kloba5942df02009-09-18 11:48:29 -07002250 return super.onKeyDown(keyCode, event);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002251 }
2252
Grace Kloba5942df02009-09-18 11:48:29 -07002253 @Override
2254 public boolean onKeyUp(int keyCode, KeyEvent event) {
2255 switch(keyCode) {
2256 case KeyEvent.KEYCODE_MENU:
2257 mMenuIsDown = false;
2258 break;
Grace Kloba5942df02009-09-18 11:48:29 -07002259 case KeyEvent.KEYCODE_BACK:
2260 if (event.isTracking() && !event.isCanceled()) {
2261 if (mCustomView != null) {
2262 // if a custom view is showing, hide it
Grace Kloba22ac16e2009-10-07 18:00:23 -07002263 mTabControl.getCurrentWebView().getWebChromeClient()
2264 .onHideCustomView();
Grace Kloba5942df02009-09-18 11:48:29 -07002265 } else if (mActiveTabsPage != null) {
2266 // if tab page is showing, hide it
2267 removeActiveTabPage(true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002268 } else {
Grace Kloba5942df02009-09-18 11:48:29 -07002269 WebView subwindow = mTabControl.getCurrentSubWindow();
2270 if (subwindow != null) {
2271 if (subwindow.canGoBack()) {
2272 subwindow.goBack();
2273 } else {
2274 dismissSubWindow(mTabControl.getCurrentTab());
2275 }
2276 } else {
2277 goBackOnePageOrQuit();
2278 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002279 }
Grace Kloba5942df02009-09-18 11:48:29 -07002280 return true;
2281 }
2282 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002283 }
Grace Kloba5942df02009-09-18 11:48:29 -07002284 return super.onKeyUp(keyCode, event);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002285 }
2286
Leon Scroggins68579392009-09-15 15:31:54 -04002287 /* package */ void stopLoading() {
Ben Murdochb7cc8b42009-09-28 10:59:09 +01002288 mDidStopLoad = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002289 resetTitleAndRevertLockIcon();
2290 WebView w = getTopWindow();
2291 w.stopLoading();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002292 // FIXME: before refactor, it is using mWebViewClient. So I keep the
2293 // same logic here. But for subwindow case, should we call into the main
2294 // WebView's onPageFinished as we never call its onPageStarted and if
2295 // the page finishes itself, we don't call onPageFinished.
2296 mTabControl.getCurrentWebView().getWebViewClient().onPageFinished(w,
2297 w.getUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08002298
2299 cancelStopToast();
2300 mStopToast = Toast
2301 .makeText(this, R.string.stopping, Toast.LENGTH_SHORT);
2302 mStopToast.show();
2303 }
2304
Grace Kloba22ac16e2009-10-07 18:00:23 -07002305 boolean didUserStopLoading() {
2306 return mDidStopLoad;
2307 }
2308
The Android Open Source Project0c908882009-03-03 19:32:16 -08002309 private void cancelStopToast() {
2310 if (mStopToast != null) {
2311 mStopToast.cancel();
2312 mStopToast = null;
2313 }
2314 }
2315
Grace Kloba22ac16e2009-10-07 18:00:23 -07002316 // called by a UI or non-UI thread to post the message
2317 public void postMessage(int what, int arg1, int arg2, Object obj,
2318 long delayMillis) {
2319 mHandler.sendMessageDelayed(mHandler.obtainMessage(what, arg1, arg2,
2320 obj), delayMillis);
2321 }
2322
2323 // called by a UI or non-UI thread to remove the message
2324 void removeMessages(int what, Object object) {
2325 mHandler.removeMessages(what, object);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002326 }
2327
2328 // public message ids
2329 public final static int LOAD_URL = 1001;
2330 public final static int STOP_LOAD = 1002;
2331
2332 // Message Ids
2333 private static final int FOCUS_NODE_HREF = 102;
2334 private static final int CANCEL_CREDS_REQUEST = 103;
Grace Kloba92c18a52009-07-31 23:48:32 -07002335 private static final int RELEASE_WAKELOCK = 107;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002336
Grace Kloba22ac16e2009-10-07 18:00:23 -07002337 static final int UPDATE_BOOKMARK_THUMBNAIL = 108;
Ben Murdoch2694e232009-09-29 09:41:11 +01002338
The Android Open Source Project0c908882009-03-03 19:32:16 -08002339 // Private handler for handling javascript and saving passwords
2340 private Handler mHandler = new Handler() {
2341
2342 public void handleMessage(Message msg) {
2343 switch (msg.what) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002344 case FOCUS_NODE_HREF:
Ben Murdoch2694e232009-09-29 09:41:11 +01002345 {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002346 String url = (String) msg.getData().get("url");
Ben Murdoch90d088c2009-11-17 18:14:04 +00002347 String title = (String) msg.getData().get("title");
The Android Open Source Project0c908882009-03-03 19:32:16 -08002348 if (url == null || url.length() == 0) {
2349 break;
2350 }
2351 HashMap focusNodeMap = (HashMap) msg.obj;
2352 WebView view = (WebView) focusNodeMap.get("webview");
2353 // Only apply the action if the top window did not change.
2354 if (getTopWindow() != view) {
2355 break;
2356 }
2357 switch (msg.arg1) {
2358 case R.id.open_context_menu_id:
2359 case R.id.view_image_context_menu_id:
Leon Scroggins92472e82010-02-17 16:32:28 -05002360 loadUrlFromContext(getTopWindow(), url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002361 break;
2362 case R.id.open_newtab_context_menu_id:
Grace Kloba22ac16e2009-10-07 18:00:23 -07002363 final Tab parent = mTabControl.getCurrentTab();
2364 final Tab newTab = openTab(url);
Grace Klobac9181842009-04-14 08:53:22 -07002365 if (newTab != parent) {
2366 parent.addChildTab(newTab);
2367 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002368 break;
2369 case R.id.bookmark_context_menu_id:
2370 Intent intent = new Intent(BrowserActivity.this,
2371 AddBookmarkPage.class);
2372 intent.putExtra("url", url);
Ben Murdoch90d088c2009-11-17 18:14:04 +00002373 intent.putExtra("title", title);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002374 startActivity(intent);
2375 break;
2376 case R.id.share_link_context_menu_id:
Leon Scroggins96afcb12009-12-10 12:35:56 -05002377 // See if this site has been visited before
2378 StringBuilder sb = new StringBuilder(
2379 Browser.BookmarkColumns.URL + " = ");
2380 DatabaseUtils.appendEscapedSQLString(sb, url);
2381 Cursor c = mResolver.query(Browser.BOOKMARKS_URI,
2382 Browser.HISTORY_PROJECTION,
2383 sb.toString(),
2384 null,
2385 null);
2386 if (c.moveToFirst()) {
2387 // The site has been visited before, so grab the
2388 // info from the database.
2389 Bitmap favicon = null;
2390 Bitmap thumbnail = null;
2391 String linkTitle = c.getString(Browser.
2392 HISTORY_PROJECTION_TITLE_INDEX);
2393 byte[] data = c.getBlob(Browser.
2394 HISTORY_PROJECTION_FAVICON_INDEX);
2395 if (data != null) {
2396 favicon = BitmapFactory.decodeByteArray(
2397 data, 0, data.length);
2398 }
2399 data = c.getBlob(Browser.
2400 HISTORY_PROJECTION_THUMBNAIL_INDEX);
2401 if (data != null) {
2402 thumbnail = BitmapFactory.decodeByteArray(
2403 data, 0, data.length);
2404 }
2405 sharePage(BrowserActivity.this,
2406 linkTitle, url, favicon, thumbnail);
2407 } else {
2408 Browser.sendString(BrowserActivity.this, url,
2409 getString(
2410 R.string.choosertitle_sharevia));
2411 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002412 break;
2413 case R.id.copy_link_context_menu_id:
2414 copy(url);
2415 break;
2416 case R.id.save_link_context_menu_id:
2417 case R.id.download_context_menu_id:
2418 onDownloadStartNoStream(url, null, null, null, -1);
2419 break;
2420 }
2421 break;
Ben Murdoch2694e232009-09-29 09:41:11 +01002422 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002423
2424 case LOAD_URL:
Leon Scroggins92472e82010-02-17 16:32:28 -05002425 loadUrlFromContext(getTopWindow(), (String) msg.obj);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002426 break;
2427
2428 case STOP_LOAD:
2429 stopLoading();
2430 break;
2431
2432 case CANCEL_CREDS_REQUEST:
2433 resumeAfterCredentials();
2434 break;
2435
The Android Open Source Project0c908882009-03-03 19:32:16 -08002436 case RELEASE_WAKELOCK:
2437 if (mWakeLock.isHeld()) {
2438 mWakeLock.release();
Grace Kloba5d0e02e2009-10-05 15:15:36 -07002439 // if we reach here, Browser should be still in the
2440 // background loading after WAKELOCK_TIMEOUT (5-min).
2441 // To avoid burning the battery, stop loading.
2442 mTabControl.stopAllLoading();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002443 }
2444 break;
Ben Murdoch2694e232009-09-29 09:41:11 +01002445
2446 case UPDATE_BOOKMARK_THUMBNAIL:
2447 WebView view = (WebView) msg.obj;
2448 if (view != null) {
2449 updateScreenshot(view);
2450 }
2451 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002452 }
2453 }
2454 };
2455
Leon Scroggins96afcb12009-12-10 12:35:56 -05002456 /**
2457 * Share a page, providing the title, url, favicon, and a screenshot. Uses
2458 * an {@link Intent} to launch the Activity chooser.
2459 * @param c Context used to launch a new Activity.
2460 * @param title Title of the page. Stored in the Intent with
2461 * {@link Browser#EXTRA_SHARE_TITLE}
2462 * @param url URL of the page. Stored in the Intent with
2463 * {@link Intent#EXTRA_TEXT}
2464 * @param favicon Bitmap of the favicon for the page. Stored in the Intent
2465 * with {@link Browser#EXTRA_SHARE_FAVICON}
2466 * @param screenshot Bitmap of a screenshot of the page. Stored in the
2467 * Intent with {@link Browser#EXTRA_SHARE_SCREENSHOT}
2468 */
2469 public static final void sharePage(Context c, String title, String url,
2470 Bitmap favicon, Bitmap screenshot) {
2471 Intent send = new Intent(Intent.ACTION_SEND);
2472 send.setType("text/plain");
2473 send.putExtra(Intent.EXTRA_TEXT, url);
2474 send.putExtra(Browser.EXTRA_SHARE_TITLE, title);
2475 send.putExtra(Browser.EXTRA_SHARE_FAVICON, favicon);
2476 send.putExtra(Browser.EXTRA_SHARE_SCREENSHOT, screenshot);
2477 try {
2478 c.startActivity(Intent.createChooser(send, c.getString(
2479 R.string.choosertitle_sharevia)));
2480 } catch(android.content.ActivityNotFoundException ex) {
2481 // if no app handles it, do nothing
2482 }
2483 }
2484
Leon Scroggins89c6d362009-07-15 16:54:37 -04002485 private void updateScreenshot(WebView view) {
2486 // If this is a bookmarked site, add a screenshot to the database.
2487 // FIXME: When should we update? Every time?
2488 // FIXME: Would like to make sure there is actually something to
2489 // draw, but the API for that (WebViewCore.pictureReady()) is not
2490 // currently accessible here.
Ben Murdochaac7aa62009-09-17 16:57:40 +01002491
Patrick Scott3918d442009-08-04 13:22:29 -04002492 ContentResolver cr = getContentResolver();
2493 final Cursor c = BrowserBookmarksAdapter.queryBookmarksForUrl(
Ben Murdochaac7aa62009-09-17 16:57:40 +01002494 cr, view.getOriginalUrl(), view.getUrl(), true);
Patrick Scott3918d442009-08-04 13:22:29 -04002495 if (c != null) {
Leon Scroggins89c6d362009-07-15 16:54:37 -04002496 boolean succeed = c.moveToFirst();
2497 ContentValues values = null;
2498 while (succeed) {
2499 if (values == null) {
2500 final ByteArrayOutputStream os
2501 = new ByteArrayOutputStream();
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002502 Bitmap bm = createScreenshot(view);
Leon Scroggins45800572009-09-29 16:38:47 -04002503 if (bm == null) {
2504 c.close();
2505 return;
2506 }
Leon Scroggins89c6d362009-07-15 16:54:37 -04002507 bm.compress(Bitmap.CompressFormat.PNG, 100, os);
2508 values = new ContentValues();
2509 values.put(Browser.BookmarkColumns.THUMBNAIL,
2510 os.toByteArray());
2511 }
2512 cr.update(ContentUris.withAppendedId(Browser.BOOKMARKS_URI,
2513 c.getInt(0)), values, null, null);
2514 succeed = c.moveToNext();
2515 }
2516 c.close();
2517 }
2518 }
2519
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002520 /**
Leon Scrogginsf8551612009-09-24 16:06:02 -04002521 * Values for the size of the thumbnail created when taking a screenshot.
2522 * Lazily initialized. Instead of using these directly, use
2523 * getDesiredThumbnailWidth() or getDesiredThumbnailHeight().
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002524 */
Leon Scrogginsf8551612009-09-24 16:06:02 -04002525 private static int THUMBNAIL_WIDTH = 0;
2526 private static int THUMBNAIL_HEIGHT = 0;
2527
2528 /**
2529 * Return the desired width for thumbnail screenshots, which are stored in
2530 * the database, and used on the bookmarks screen.
2531 * @param context Context for finding out the density of the screen.
2532 * @return int desired width for thumbnail screenshot.
2533 */
2534 /* package */ static int getDesiredThumbnailWidth(Context context) {
2535 if (THUMBNAIL_WIDTH == 0) {
2536 float density = context.getResources().getDisplayMetrics().density;
2537 THUMBNAIL_WIDTH = (int) (90 * density);
2538 THUMBNAIL_HEIGHT = (int) (80 * density);
2539 }
2540 return THUMBNAIL_WIDTH;
2541 }
2542
2543 /**
2544 * Return the desired height for thumbnail screenshots, which are stored in
2545 * the database, and used on the bookmarks screen.
2546 * @param context Context for finding out the density of the screen.
2547 * @return int desired height for thumbnail screenshot.
2548 */
2549 /* package */ static int getDesiredThumbnailHeight(Context context) {
2550 // To ensure that they are both initialized.
2551 getDesiredThumbnailWidth(context);
2552 return THUMBNAIL_HEIGHT;
2553 }
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002554
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002555 private Bitmap createScreenshot(WebView view) {
2556 Picture thumbnail = view.capturePicture();
Leon Scroggins45800572009-09-29 16:38:47 -04002557 if (thumbnail == null) {
2558 return null;
2559 }
Leon Scrogginsf8551612009-09-24 16:06:02 -04002560 Bitmap bm = Bitmap.createBitmap(getDesiredThumbnailWidth(this),
2561 getDesiredThumbnailHeight(this), Bitmap.Config.ARGB_4444);
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002562 Canvas canvas = new Canvas(bm);
2563 // May need to tweak these values to determine what is the
2564 // best scale factor
Ben Murdoch2694e232009-09-29 09:41:11 +01002565 int thumbnailWidth = thumbnail.getWidth();
Ben Murdochae59c3f2009-10-20 18:30:28 +01002566 int thumbnailHeight = thumbnail.getHeight();
2567 float scaleFactorX = 1.0f;
2568 float scaleFactorY = 1.0f;
Ben Murdoch2694e232009-09-29 09:41:11 +01002569 if (thumbnailWidth > 0) {
Ben Murdochae59c3f2009-10-20 18:30:28 +01002570 scaleFactorX = (float) getDesiredThumbnailWidth(this) /
Ben Murdoch2694e232009-09-29 09:41:11 +01002571 (float)thumbnailWidth;
Ben Murdochae59c3f2009-10-20 18:30:28 +01002572 } else {
2573 return null;
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002574 }
Ben Murdochae59c3f2009-10-20 18:30:28 +01002575
2576 if (view.getWidth() > view.getHeight() &&
2577 thumbnailHeight < view.getHeight() && thumbnailHeight > 0) {
2578 // If the device is in landscape and the page is shorter
2579 // than the height of the view, stretch the thumbnail to fill the
2580 // space.
2581 scaleFactorY = (float) getDesiredThumbnailHeight(this) /
2582 (float)thumbnailHeight;
2583 } else {
2584 // In the portrait case, this looks nice.
2585 scaleFactorY = scaleFactorX;
2586 }
2587
2588 canvas.scale(scaleFactorX, scaleFactorY);
2589
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002590 thumbnail.draw(canvas);
2591 return bm;
2592 }
2593
The Android Open Source Project0c908882009-03-03 19:32:16 -08002594 // -------------------------------------------------------------------------
Grace Kloba22ac16e2009-10-07 18:00:23 -07002595 // Helper function for WebViewClient.
The Android Open Source Project0c908882009-03-03 19:32:16 -08002596 //-------------------------------------------------------------------------
2597
2598 // Use in overrideUrlLoading
2599 /* package */ final static String SCHEME_WTAI = "wtai://wp/";
2600 /* package */ final static String SCHEME_WTAI_MC = "wtai://wp/mc;";
2601 /* package */ final static String SCHEME_WTAI_SD = "wtai://wp/sd;";
2602 /* package */ final static String SCHEME_WTAI_AP = "wtai://wp/ap;";
2603
Leon Scroggins92472e82010-02-17 16:32:28 -05002604 // Keep this initial progress in sync with initialProgressValue (* 100)
2605 // in ProgressTracker.cpp
2606 private final static int INITIAL_PROGRESS = 10;
2607
Grace Kloba22ac16e2009-10-07 18:00:23 -07002608 void onPageStarted(WebView view, String url, Bitmap favicon) {
2609 // when BrowserActivity just starts, onPageStarted may be called before
2610 // onResume as it is triggered from onCreate. Call resumeWebViewTimers
2611 // to start the timer. As we won't switch tabs while an activity is in
2612 // pause state, we can ensure calling resume and pause in pair.
2613 if (mActivityInPause) resumeWebViewTimers();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002614
Grace Kloba22ac16e2009-10-07 18:00:23 -07002615 resetLockIcon(url);
2616 setUrlTitle(url, null);
2617 setFavicon(favicon);
Leon Scroggins8cf8f682009-11-04 11:13:50 -08002618 // Show some progress so that the user knows the page is beginning to
2619 // load
Leon Scroggins92472e82010-02-17 16:32:28 -05002620 onProgressChanged(view, INITIAL_PROGRESS);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002621 mDidStopLoad = false;
Grace Kloba22ac16e2009-10-07 18:00:23 -07002622 if (!mIsNetworkUp) createAndShowNetworkDialog();
Patrick Scott15525d42009-09-21 13:39:37 -04002623
Grace Kloba22ac16e2009-10-07 18:00:23 -07002624 if (mSettings.isTracing()) {
2625 String host;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002626 try {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002627 WebAddress uri = new WebAddress(url);
2628 host = uri.mHost;
2629 } catch (android.net.ParseException ex) {
2630 host = "browser";
The Android Open Source Project0c908882009-03-03 19:32:16 -08002631 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002632 host = host.replace('.', '_');
2633 host += ".trace";
2634 mInTrace = true;
2635 Debug.startMethodTracing(host, 20 * 1024 * 1024);
2636 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002637
Grace Kloba22ac16e2009-10-07 18:00:23 -07002638 // Performance probe
2639 if (false) {
2640 mStart = SystemClock.uptimeMillis();
2641 mProcessStart = Process.getElapsedCpuTime();
2642 long[] sysCpu = new long[7];
2643 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2644 sysCpu, null)) {
2645 mUserStart = sysCpu[0] + sysCpu[1];
2646 mSystemStart = sysCpu[2];
2647 mIdleStart = sysCpu[3];
2648 mIrqStart = sysCpu[4] + sysCpu[5] + sysCpu[6];
2649 }
2650 mUiStart = SystemClock.currentThreadTimeMillis();
2651 }
2652 }
2653
2654 void onPageFinished(WebView view, String url) {
2655 // Reset the title and icon in case we stopped a provisional load.
2656 resetTitleAndIcon(view);
2657 // Update the lock icon image only once we are done loading
2658 updateLockIconToLatest();
2659 // pause the WebView timer and release the wake lock if it is finished
2660 // while BrowserActivity is in pause state.
2661 if (mActivityInPause && pauseWebViewTimers()) {
2662 if (mWakeLock.isHeld()) {
2663 mHandler.removeMessages(RELEASE_WAKELOCK);
2664 mWakeLock.release();
2665 }
2666 }
2667
2668 // Performance probe
2669 if (false) {
2670 long[] sysCpu = new long[7];
2671 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2672 sysCpu, null)) {
2673 String uiInfo = "UI thread used "
2674 + (SystemClock.currentThreadTimeMillis() - mUiStart)
2675 + " ms";
2676 if (LOGD_ENABLED) {
2677 Log.d(LOGTAG, uiInfo);
2678 }
2679 //The string that gets written to the log
2680 String performanceString = "It took total "
2681 + (SystemClock.uptimeMillis() - mStart)
2682 + " ms clock time to load the page."
2683 + "\nbrowser process used "
2684 + (Process.getElapsedCpuTime() - mProcessStart)
2685 + " ms, user processes used "
2686 + (sysCpu[0] + sysCpu[1] - mUserStart) * 10
2687 + " ms, kernel used "
2688 + (sysCpu[2] - mSystemStart) * 10
2689 + " ms, idle took " + (sysCpu[3] - mIdleStart) * 10
2690 + " ms and irq took "
2691 + (sysCpu[4] + sysCpu[5] + sysCpu[6] - mIrqStart)
2692 * 10 + " ms, " + uiInfo;
2693 if (LOGD_ENABLED) {
2694 Log.d(LOGTAG, performanceString + "\nWebpage: " + url);
2695 }
2696 if (url != null) {
2697 // strip the url to maintain consistency
2698 String newUrl = new String(url);
2699 if (newUrl.startsWith("http://www.")) {
2700 newUrl = newUrl.substring(11);
2701 } else if (newUrl.startsWith("http://")) {
2702 newUrl = newUrl.substring(7);
2703 } else if (newUrl.startsWith("https://www.")) {
2704 newUrl = newUrl.substring(12);
2705 } else if (newUrl.startsWith("https://")) {
2706 newUrl = newUrl.substring(8);
2707 }
2708 if (LOGD_ENABLED) {
2709 Log.d(LOGTAG, newUrl + " loaded");
2710 }
Grace Kloba5b078b52009-06-24 20:23:41 -07002711 }
2712 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002713 }
Grace Kloba5b078b52009-06-24 20:23:41 -07002714
Grace Kloba22ac16e2009-10-07 18:00:23 -07002715 if (mInTrace) {
2716 mInTrace = false;
2717 Debug.stopMethodTracing();
2718 }
2719 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002720
Grace Kloba22ac16e2009-10-07 18:00:23 -07002721 boolean shouldOverrideUrlLoading(WebView view, String url) {
2722 if (url.startsWith(SCHEME_WTAI)) {
2723 // wtai://wp/mc;number
2724 // number=string(phone-number)
2725 if (url.startsWith(SCHEME_WTAI_MC)) {
2726 Intent intent = new Intent(Intent.ACTION_VIEW,
2727 Uri.parse(WebView.SCHEME_TEL +
2728 url.substring(SCHEME_WTAI_MC.length())));
2729 startActivity(intent);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002730 return true;
2731 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002732 // wtai://wp/sd;dtmf
2733 // dtmf=string(dialstring)
2734 if (url.startsWith(SCHEME_WTAI_SD)) {
2735 // TODO: only send when there is active voice connection
2736 return false;
2737 }
2738 // wtai://wp/ap;number;name
2739 // number=string(phone-number)
2740 // name=string
2741 if (url.startsWith(SCHEME_WTAI_AP)) {
2742 // TODO
2743 return false;
2744 }
2745 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002746
Grace Kloba22ac16e2009-10-07 18:00:23 -07002747 // The "about:" schemes are internal to the browser; don't want these to
2748 // be dispatched to other apps.
2749 if (url.startsWith("about:")) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002750 return false;
2751 }
2752
Grace Kloba22ac16e2009-10-07 18:00:23 -07002753 Intent intent;
2754 // perform generic parsing of the URI to turn it into an Intent.
2755 try {
2756 intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME);
2757 } catch (URISyntaxException ex) {
2758 Log.w("Browser", "Bad URI " + url + ": " + ex.getMessage());
2759 return false;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002760 }
2761
Grace Kloba22ac16e2009-10-07 18:00:23 -07002762 // check whether the intent can be resolved. If not, we will see
2763 // whether we can download it from the Market.
2764 if (getPackageManager().resolveActivity(intent, 0) == null) {
2765 String packagename = intent.getPackage();
2766 if (packagename != null) {
2767 intent = new Intent(Intent.ACTION_VIEW, Uri
2768 .parse("market://search?q=pname:" + packagename));
2769 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2770 startActivity(intent);
2771 return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002772 } else {
2773 return false;
2774 }
2775 }
2776
Grace Kloba22ac16e2009-10-07 18:00:23 -07002777 // sanitize the Intent, ensuring web pages can not bypass browser
2778 // security (only access to BROWSABLE activities).
2779 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2780 intent.setComponent(null);
2781 try {
2782 if (startActivityIfNeeded(intent, -1)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002783 return true;
2784 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002785 } catch (ActivityNotFoundException ex) {
2786 // ignore the error. If no application can handle the URL,
2787 // eg about:blank, assume the browser can handle it.
2788 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002789
Grace Kloba22ac16e2009-10-07 18:00:23 -07002790 if (mMenuIsDown) {
2791 openTab(url);
2792 closeOptionsMenu();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002793 return true;
2794 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002795 return false;
2796 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002797
Grace Kloba22ac16e2009-10-07 18:00:23 -07002798 // -------------------------------------------------------------------------
2799 // Helper function for WebChromeClient
2800 // -------------------------------------------------------------------------
The Android Open Source Project0c908882009-03-03 19:32:16 -08002801
Grace Kloba22ac16e2009-10-07 18:00:23 -07002802 void onProgressChanged(WebView view, int newProgress) {
2803 mTitleBar.setProgress(newProgress);
2804 mFakeTitleBar.setProgress(newProgress);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002805
Grace Kloba22ac16e2009-10-07 18:00:23 -07002806 if (newProgress == 100) {
2807 // onProgressChanged() may continue to be called after the main
2808 // frame has finished loading, as any remaining sub frames continue
2809 // to load. We'll only get called once though with newProgress as
2810 // 100 when everything is loaded. (onPageFinished is called once
2811 // when the main frame completes loading regardless of the state of
2812 // any sub frames so calls to onProgressChanges may continue after
2813 // onPageFinished has executed)
2814 if (mInLoad) {
2815 mInLoad = false;
Leon Scrogginsa27ff192009-09-14 12:58:04 -04002816 updateInLoadMenuItems();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002817 // If the options menu is open, leave the title bar
2818 if (!mOptionsMenuOpen || !mIconView) {
2819 hideFakeTitleBar();
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07002820 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002821 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002822 } else if (!mInLoad) {
2823 // onPageFinished may have already been called but a subframe is
2824 // still loading and updating the progress. Reset mInLoad and update
2825 // the menu items.
2826 mInLoad = true;
2827 updateInLoadMenuItems();
2828 if (!mOptionsMenuOpen || mIconView) {
2829 // This page has begun to load, so show the title bar
2830 showFakeTitleBar();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002831 }
2832 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002833 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002834
Grace Kloba22ac16e2009-10-07 18:00:23 -07002835 void onShowCustomView(View view, WebChromeClient.CustomViewCallback callback) {
Derek Sollenberger8ff57db2009-12-08 15:39:55 -05002836 // if a view already exists then immediately terminate the new one
2837 if (mCustomView != null) {
2838 callback.onCustomViewHidden();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002839 return;
Derek Sollenberger8ff57db2009-12-08 15:39:55 -05002840 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002841
2842 // Add the custom view to its container.
2843 mCustomViewContainer.addView(view, COVER_SCREEN_GRAVITY_CENTER);
2844 mCustomView = view;
2845 mCustomViewCallback = callback;
2846 // Save the menu state and set it to empty while the custom
2847 // view is showing.
2848 mOldMenuState = mMenuState;
2849 mMenuState = EMPTY_MENU;
2850 // Hide the content view.
2851 mContentView.setVisibility(View.GONE);
2852 // Finally show the custom view container.
Andrei Popescu163ab742009-10-20 17:58:23 +01002853 setStatusBarVisibility(false);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002854 mCustomViewContainer.setVisibility(View.VISIBLE);
2855 mCustomViewContainer.bringToFront();
2856 }
2857
2858 void onHideCustomView() {
2859 if (mCustomView == null)
2860 return;
2861
2862 // Hide the custom view.
2863 mCustomView.setVisibility(View.GONE);
2864 // Remove the custom view from its container.
2865 mCustomViewContainer.removeView(mCustomView);
2866 mCustomView = null;
2867 // Reset the old menu state.
2868 mMenuState = mOldMenuState;
2869 mOldMenuState = EMPTY_MENU;
2870 mCustomViewContainer.setVisibility(View.GONE);
2871 mCustomViewCallback.onCustomViewHidden();
2872 // Show the content view.
Andrei Popescu163ab742009-10-20 17:58:23 +01002873 setStatusBarVisibility(true);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002874 mContentView.setVisibility(View.VISIBLE);
2875 }
2876
2877 Bitmap getDefaultVideoPoster() {
2878 if (mDefaultVideoPoster == null) {
2879 mDefaultVideoPoster = BitmapFactory.decodeResource(
2880 getResources(), R.drawable.default_video_poster);
Patrick Scott3918d442009-08-04 13:22:29 -04002881 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002882 return mDefaultVideoPoster;
2883 }
Patrick Scott3918d442009-08-04 13:22:29 -04002884
Grace Kloba22ac16e2009-10-07 18:00:23 -07002885 View getVideoLoadingProgressView() {
2886 if (mVideoProgressView == null) {
2887 LayoutInflater inflater = LayoutInflater.from(BrowserActivity.this);
2888 mVideoProgressView = inflater.inflate(
2889 R.layout.video_loading_progress, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002890 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002891 return mVideoProgressView;
2892 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002893
Leon Scroggins8d5fa432009-10-02 15:55:59 -04002894 /*
2895 * The Object used to inform the WebView of the file to upload.
2896 */
2897 private ValueCallback<Uri> mUploadMessage;
2898
Grace Kloba22ac16e2009-10-07 18:00:23 -07002899 void openFileChooser(ValueCallback<Uri> uploadMsg) {
2900 if (mUploadMessage != null) return;
2901 mUploadMessage = uploadMsg;
2902 Intent i = new Intent(Intent.ACTION_GET_CONTENT);
2903 i.addCategory(Intent.CATEGORY_OPENABLE);
2904 i.setType("*/*");
2905 BrowserActivity.this.startActivityForResult(Intent.createChooser(i,
2906 getString(R.string.choose_upload)), FILE_SELECTED);
2907 }
2908
2909 // -------------------------------------------------------------------------
2910 // Implement functions for DownloadListener
2911 // -------------------------------------------------------------------------
2912
The Android Open Source Project0c908882009-03-03 19:32:16 -08002913 /**
2914 * Notify the host application a download should be done, or that
2915 * the data should be streamed if a streaming viewer is available.
2916 * @param url The full url to the content that should be downloaded
2917 * @param contentDisposition Content-disposition http header, if
2918 * present.
2919 * @param mimetype The mimetype of the content reported by the server
2920 * @param contentLength The file size reported by the server
2921 */
2922 public void onDownloadStart(String url, String userAgent,
2923 String contentDisposition, String mimetype, long contentLength) {
2924 // if we're dealing wih A/V content that's not explicitly marked
2925 // for download, check if it's streamable.
2926 if (contentDisposition == null
Patrick Scotte1fb9662009-08-31 14:31:52 -04002927 || !contentDisposition.regionMatches(
2928 true, 0, "attachment", 0, 10)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002929 // query the package manager to see if there's a registered handler
2930 // that matches.
2931 Intent intent = new Intent(Intent.ACTION_VIEW);
2932 intent.setDataAndType(Uri.parse(url), mimetype);
Patrick Scotte1fb9662009-08-31 14:31:52 -04002933 ResolveInfo info = getPackageManager().resolveActivity(intent,
2934 PackageManager.MATCH_DEFAULT_ONLY);
2935 if (info != null) {
2936 ComponentName myName = getComponentName();
2937 // If we resolved to ourselves, we don't want to attempt to
2938 // load the url only to try and download it again.
2939 if (!myName.getPackageName().equals(
2940 info.activityInfo.packageName)
2941 || !myName.getClassName().equals(
2942 info.activityInfo.name)) {
2943 // someone (other than us) knows how to handle this mime
2944 // type with this scheme, don't download.
2945 try {
2946 startActivity(intent);
2947 return;
2948 } catch (ActivityNotFoundException ex) {
2949 if (LOGD_ENABLED) {
2950 Log.d(LOGTAG, "activity not found for " + mimetype
2951 + " over " + Uri.parse(url).getScheme(),
2952 ex);
2953 }
2954 // Best behavior is to fall back to a download in this
2955 // case
The Android Open Source Project0c908882009-03-03 19:32:16 -08002956 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002957 }
2958 }
2959 }
2960 onDownloadStartNoStream(url, userAgent, contentDisposition, mimetype, contentLength);
2961 }
2962
2963 /**
2964 * Notify the host application a download should be done, even if there
2965 * is a streaming viewer available for thise type.
2966 * @param url The full url to the content that should be downloaded
2967 * @param contentDisposition Content-disposition http header, if
2968 * present.
2969 * @param mimetype The mimetype of the content reported by the server
2970 * @param contentLength The file size reported by the server
2971 */
2972 /*package */ void onDownloadStartNoStream(String url, String userAgent,
2973 String contentDisposition, String mimetype, long contentLength) {
2974
2975 String filename = URLUtil.guessFileName(url,
2976 contentDisposition, mimetype);
2977
2978 // Check to see if we have an SDCard
2979 String status = Environment.getExternalStorageState();
2980 if (!status.equals(Environment.MEDIA_MOUNTED)) {
2981 int title;
2982 String msg;
2983
2984 // Check to see if the SDCard is busy, same as the music app
2985 if (status.equals(Environment.MEDIA_SHARED)) {
2986 msg = getString(R.string.download_sdcard_busy_dlg_msg);
2987 title = R.string.download_sdcard_busy_dlg_title;
2988 } else {
2989 msg = getString(R.string.download_no_sdcard_dlg_msg, filename);
2990 title = R.string.download_no_sdcard_dlg_title;
2991 }
2992
2993 new AlertDialog.Builder(this)
2994 .setTitle(title)
2995 .setIcon(android.R.drawable.ic_dialog_alert)
2996 .setMessage(msg)
2997 .setPositiveButton(R.string.ok, null)
2998 .show();
2999 return;
3000 }
3001
3002 // java.net.URI is a lot stricter than KURL so we have to undo
3003 // KURL's percent-encoding and redo the encoding using java.net.URI.
3004 URI uri = null;
3005 try {
3006 // Undo the percent-encoding that KURL may have done.
3007 String newUrl = new String(URLUtil.decode(url.getBytes()));
3008 // Parse the url into pieces
3009 WebAddress w = new WebAddress(newUrl);
3010 String frag = null;
3011 String query = null;
3012 String path = w.mPath;
3013 // Break the path into path, query, and fragment
3014 if (path.length() > 0) {
3015 // Strip the fragment
3016 int idx = path.lastIndexOf('#');
3017 if (idx != -1) {
3018 frag = path.substring(idx + 1);
3019 path = path.substring(0, idx);
3020 }
3021 idx = path.lastIndexOf('?');
3022 if (idx != -1) {
3023 query = path.substring(idx + 1);
3024 path = path.substring(0, idx);
3025 }
3026 }
3027 uri = new URI(w.mScheme, w.mAuthInfo, w.mHost, w.mPort, path,
3028 query, frag);
3029 } catch (Exception e) {
3030 Log.e(LOGTAG, "Could not parse url for download: " + url, e);
3031 return;
3032 }
3033
3034 // XXX: Have to use the old url since the cookies were stored using the
3035 // old percent-encoded url.
3036 String cookies = CookieManager.getInstance().getCookie(url);
3037
3038 ContentValues values = new ContentValues();
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08003039 values.put(Downloads.Impl.COLUMN_URI, uri.toString());
3040 values.put(Downloads.Impl.COLUMN_COOKIE_DATA, cookies);
3041 values.put(Downloads.Impl.COLUMN_USER_AGENT, userAgent);
3042 values.put(Downloads.Impl.COLUMN_NOTIFICATION_PACKAGE,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003043 getPackageName());
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08003044 values.put(Downloads.Impl.COLUMN_NOTIFICATION_CLASS,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003045 BrowserDownloadPage.class.getCanonicalName());
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08003046 values.put(Downloads.Impl.COLUMN_VISIBILITY,
3047 Downloads.Impl.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
3048 values.put(Downloads.Impl.COLUMN_MIME_TYPE, mimetype);
3049 values.put(Downloads.Impl.COLUMN_FILE_NAME_HINT, filename);
3050 values.put(Downloads.Impl.COLUMN_DESCRIPTION, uri.getHost());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003051 if (contentLength > 0) {
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08003052 values.put(Downloads.Impl.COLUMN_TOTAL_BYTES, contentLength);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003053 }
3054 if (mimetype == null) {
3055 // We must have long pressed on a link or image to download it. We
3056 // are not sure of the mimetype in this case, so do a head request
3057 new FetchUrlMimeType(this).execute(values);
3058 } else {
3059 final Uri contentUri =
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08003060 getContentResolver().insert(Downloads.Impl.CONTENT_URI, values);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003061 }
3062
3063 }
3064
Grace Kloba22ac16e2009-10-07 18:00:23 -07003065 // -------------------------------------------------------------------------
3066
The Android Open Source Project0c908882009-03-03 19:32:16 -08003067 /**
3068 * Resets the lock icon. This method is called when we start a new load and
3069 * know the url to be loaded.
3070 */
3071 private void resetLockIcon(String url) {
3072 // Save the lock-icon state (we revert to it if the load gets cancelled)
Grace Kloba22ac16e2009-10-07 18:00:23 -07003073 mTabControl.getCurrentTab().resetLockIcon(url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003074 updateLockIconImage(LOCK_ICON_UNSECURE);
3075 }
3076
The Android Open Source Project0c908882009-03-03 19:32:16 -08003077 /**
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04003078 * Update the lock icon to correspond to our latest state.
3079 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003080 private void updateLockIconToLatest() {
3081 updateLockIconImage(mTabControl.getCurrentTab().getLockIconType());
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04003082 }
3083
3084 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08003085 * Updates the lock-icon image in the title-bar.
3086 */
3087 private void updateLockIconImage(int lockIconType) {
3088 Drawable d = null;
3089 if (lockIconType == LOCK_ICON_SECURE) {
3090 d = mSecLockIcon;
3091 } else if (lockIconType == LOCK_ICON_MIXED) {
3092 d = mMixLockIcon;
3093 }
Leon Scroggins68579392009-09-15 15:31:54 -04003094 mTitleBar.setLock(d);
Leon Scrogginsfe87bd32009-10-06 10:10:00 -04003095 mFakeTitleBar.setLock(d);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003096 }
3097
3098 /**
3099 * Displays a page-info dialog.
3100 * @param tab The tab to show info about
3101 * @param fromShowSSLCertificateOnError The flag that indicates whether
3102 * this dialog was opened from the SSL-certificate-on-error dialog or
3103 * not. This is important, since we need to know whether to return to
3104 * the parent dialog or simply dismiss.
3105 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003106 private void showPageInfo(final Tab tab,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003107 final boolean fromShowSSLCertificateOnError) {
3108 final LayoutInflater factory = LayoutInflater
3109 .from(this);
3110
3111 final View pageInfoView = factory.inflate(R.layout.page_info, null);
3112
3113 final WebView view = tab.getWebView();
3114
3115 String url = null;
3116 String title = null;
3117
3118 if (view == null) {
3119 url = tab.getUrl();
3120 title = tab.getTitle();
3121 } else if (view == mTabControl.getCurrentWebView()) {
3122 // Use the cached title and url if this is the current WebView
3123 url = mUrl;
3124 title = mTitle;
3125 } else {
3126 url = view.getUrl();
3127 title = view.getTitle();
3128 }
3129
3130 if (url == null) {
3131 url = "";
3132 }
3133 if (title == null) {
3134 title = "";
3135 }
3136
3137 ((TextView) pageInfoView.findViewById(R.id.address)).setText(url);
3138 ((TextView) pageInfoView.findViewById(R.id.title)).setText(title);
3139
3140 mPageInfoView = tab;
Leon Scrogginsc7b92f82010-01-11 18:17:31 -05003141 mPageInfoFromShowSSLCertificateOnError = fromShowSSLCertificateOnError;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003142
3143 AlertDialog.Builder alertDialogBuilder =
3144 new AlertDialog.Builder(this)
3145 .setTitle(R.string.page_info).setIcon(android.R.drawable.ic_dialog_info)
3146 .setView(pageInfoView)
3147 .setPositiveButton(
3148 R.string.ok,
3149 new DialogInterface.OnClickListener() {
3150 public void onClick(DialogInterface dialog,
3151 int whichButton) {
3152 mPageInfoDialog = null;
3153 mPageInfoView = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003154
3155 // if we came here from the SSL error dialog
3156 if (fromShowSSLCertificateOnError) {
3157 // go back to the SSL error dialog
3158 showSSLCertificateOnError(
3159 mSSLCertificateOnErrorView,
3160 mSSLCertificateOnErrorHandler,
3161 mSSLCertificateOnErrorError);
3162 }
3163 }
3164 })
3165 .setOnCancelListener(
3166 new DialogInterface.OnCancelListener() {
3167 public void onCancel(DialogInterface dialog) {
3168 mPageInfoDialog = null;
3169 mPageInfoView = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003170
3171 // if we came here from the SSL error dialog
3172 if (fromShowSSLCertificateOnError) {
3173 // go back to the SSL error dialog
3174 showSSLCertificateOnError(
3175 mSSLCertificateOnErrorView,
3176 mSSLCertificateOnErrorHandler,
3177 mSSLCertificateOnErrorError);
3178 }
3179 }
3180 });
3181
3182 // if we have a main top-level page SSL certificate set or a certificate
3183 // error
3184 if (fromShowSSLCertificateOnError ||
3185 (view != null && view.getCertificate() != null)) {
3186 // add a 'View Certificate' button
3187 alertDialogBuilder.setNeutralButton(
3188 R.string.view_certificate,
3189 new DialogInterface.OnClickListener() {
3190 public void onClick(DialogInterface dialog,
3191 int whichButton) {
3192 mPageInfoDialog = null;
3193 mPageInfoView = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003194
3195 // if we came here from the SSL error dialog
3196 if (fromShowSSLCertificateOnError) {
3197 // go back to the SSL error dialog
3198 showSSLCertificateOnError(
3199 mSSLCertificateOnErrorView,
3200 mSSLCertificateOnErrorHandler,
3201 mSSLCertificateOnErrorError);
3202 } else {
3203 // otherwise, display the top-most certificate from
3204 // the chain
3205 if (view.getCertificate() != null) {
3206 showSSLCertificate(tab);
3207 }
3208 }
3209 }
3210 });
3211 }
3212
3213 mPageInfoDialog = alertDialogBuilder.show();
3214 }
3215
3216 /**
3217 * Displays the main top-level page SSL certificate dialog
3218 * (accessible from the Page-Info dialog).
3219 * @param tab The tab to show certificate for.
3220 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003221 private void showSSLCertificate(final Tab tab) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003222 final View certificateView =
3223 inflateCertificateView(tab.getWebView().getCertificate());
3224 if (certificateView == null) {
3225 return;
3226 }
3227
3228 LayoutInflater factory = LayoutInflater.from(this);
3229
3230 final LinearLayout placeholder =
3231 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3232
3233 LinearLayout ll = (LinearLayout) factory.inflate(
3234 R.layout.ssl_success, placeholder);
3235 ((TextView)ll.findViewById(R.id.success))
3236 .setText(R.string.ssl_certificate_is_valid);
3237
3238 mSSLCertificateView = tab;
3239 mSSLCertificateDialog =
3240 new AlertDialog.Builder(this)
3241 .setTitle(R.string.ssl_certificate).setIcon(
3242 R.drawable.ic_dialog_browser_certificate_secure)
3243 .setView(certificateView)
3244 .setPositiveButton(R.string.ok,
3245 new DialogInterface.OnClickListener() {
3246 public void onClick(DialogInterface dialog,
3247 int whichButton) {
3248 mSSLCertificateDialog = null;
3249 mSSLCertificateView = null;
3250
3251 showPageInfo(tab, false);
3252 }
3253 })
3254 .setOnCancelListener(
3255 new DialogInterface.OnCancelListener() {
3256 public void onCancel(DialogInterface dialog) {
3257 mSSLCertificateDialog = null;
3258 mSSLCertificateView = null;
3259
3260 showPageInfo(tab, false);
3261 }
3262 })
3263 .show();
3264 }
3265
3266 /**
3267 * Displays the SSL error certificate dialog.
3268 * @param view The target web-view.
3269 * @param handler The SSL error handler responsible for cancelling the
3270 * connection that resulted in an SSL error or proceeding per user request.
3271 * @param error The SSL error object.
3272 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003273 void showSSLCertificateOnError(
The Android Open Source Project0c908882009-03-03 19:32:16 -08003274 final WebView view, final SslErrorHandler handler, final SslError error) {
3275
3276 final View certificateView =
3277 inflateCertificateView(error.getCertificate());
3278 if (certificateView == null) {
3279 return;
3280 }
3281
3282 LayoutInflater factory = LayoutInflater.from(this);
3283
3284 final LinearLayout placeholder =
3285 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3286
3287 if (error.hasError(SslError.SSL_UNTRUSTED)) {
3288 LinearLayout ll = (LinearLayout)factory
3289 .inflate(R.layout.ssl_warning, placeholder);
3290 ((TextView)ll.findViewById(R.id.warning))
3291 .setText(R.string.ssl_untrusted);
3292 }
3293
3294 if (error.hasError(SslError.SSL_IDMISMATCH)) {
3295 LinearLayout ll = (LinearLayout)factory
3296 .inflate(R.layout.ssl_warning, placeholder);
3297 ((TextView)ll.findViewById(R.id.warning))
3298 .setText(R.string.ssl_mismatch);
3299 }
3300
3301 if (error.hasError(SslError.SSL_EXPIRED)) {
3302 LinearLayout ll = (LinearLayout)factory
3303 .inflate(R.layout.ssl_warning, placeholder);
3304 ((TextView)ll.findViewById(R.id.warning))
3305 .setText(R.string.ssl_expired);
3306 }
3307
3308 if (error.hasError(SslError.SSL_NOTYETVALID)) {
3309 LinearLayout ll = (LinearLayout)factory
3310 .inflate(R.layout.ssl_warning, placeholder);
3311 ((TextView)ll.findViewById(R.id.warning))
3312 .setText(R.string.ssl_not_yet_valid);
3313 }
3314
3315 mSSLCertificateOnErrorHandler = handler;
3316 mSSLCertificateOnErrorView = view;
3317 mSSLCertificateOnErrorError = error;
3318 mSSLCertificateOnErrorDialog =
3319 new AlertDialog.Builder(this)
3320 .setTitle(R.string.ssl_certificate).setIcon(
3321 R.drawable.ic_dialog_browser_certificate_partially_secure)
3322 .setView(certificateView)
3323 .setPositiveButton(R.string.ok,
3324 new DialogInterface.OnClickListener() {
3325 public void onClick(DialogInterface dialog,
3326 int whichButton) {
3327 mSSLCertificateOnErrorDialog = null;
3328 mSSLCertificateOnErrorView = null;
3329 mSSLCertificateOnErrorHandler = null;
3330 mSSLCertificateOnErrorError = null;
3331
Grace Kloba22ac16e2009-10-07 18:00:23 -07003332 view.getWebViewClient().onReceivedSslError(
3333 view, handler, error);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003334 }
3335 })
3336 .setNeutralButton(R.string.page_info_view,
3337 new DialogInterface.OnClickListener() {
3338 public void onClick(DialogInterface dialog,
3339 int whichButton) {
3340 mSSLCertificateOnErrorDialog = null;
3341
3342 // do not clear the dialog state: we will
3343 // need to show the dialog again once the
3344 // user is done exploring the page-info details
3345
3346 showPageInfo(mTabControl.getTabFromView(view),
3347 true);
3348 }
3349 })
3350 .setOnCancelListener(
3351 new DialogInterface.OnCancelListener() {
3352 public void onCancel(DialogInterface dialog) {
3353 mSSLCertificateOnErrorDialog = null;
3354 mSSLCertificateOnErrorView = null;
3355 mSSLCertificateOnErrorHandler = null;
3356 mSSLCertificateOnErrorError = null;
3357
Grace Kloba22ac16e2009-10-07 18:00:23 -07003358 view.getWebViewClient().onReceivedSslError(
3359 view, handler, error);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003360 }
3361 })
3362 .show();
3363 }
3364
3365 /**
3366 * Inflates the SSL certificate view (helper method).
3367 * @param certificate The SSL certificate.
3368 * @return The resultant certificate view with issued-to, issued-by,
3369 * issued-on, expires-on, and possibly other fields set.
3370 * If the input certificate is null, returns null.
3371 */
3372 private View inflateCertificateView(SslCertificate certificate) {
3373 if (certificate == null) {
3374 return null;
3375 }
3376
3377 LayoutInflater factory = LayoutInflater.from(this);
3378
3379 View certificateView = factory.inflate(
3380 R.layout.ssl_certificate, null);
3381
3382 // issued to:
3383 SslCertificate.DName issuedTo = certificate.getIssuedTo();
3384 if (issuedTo != null) {
3385 ((TextView) certificateView.findViewById(R.id.to_common))
3386 .setText(issuedTo.getCName());
3387 ((TextView) certificateView.findViewById(R.id.to_org))
3388 .setText(issuedTo.getOName());
3389 ((TextView) certificateView.findViewById(R.id.to_org_unit))
3390 .setText(issuedTo.getUName());
3391 }
3392
3393 // issued by:
3394 SslCertificate.DName issuedBy = certificate.getIssuedBy();
3395 if (issuedBy != null) {
3396 ((TextView) certificateView.findViewById(R.id.by_common))
3397 .setText(issuedBy.getCName());
3398 ((TextView) certificateView.findViewById(R.id.by_org))
3399 .setText(issuedBy.getOName());
3400 ((TextView) certificateView.findViewById(R.id.by_org_unit))
3401 .setText(issuedBy.getUName());
3402 }
3403
3404 // issued on:
3405 String issuedOn = reformatCertificateDate(
3406 certificate.getValidNotBefore());
3407 ((TextView) certificateView.findViewById(R.id.issued_on))
3408 .setText(issuedOn);
3409
3410 // expires on:
3411 String expiresOn = reformatCertificateDate(
3412 certificate.getValidNotAfter());
3413 ((TextView) certificateView.findViewById(R.id.expires_on))
3414 .setText(expiresOn);
3415
3416 return certificateView;
3417 }
3418
3419 /**
3420 * Re-formats the certificate date (Date.toString()) string to
3421 * a properly localized date string.
3422 * @return Properly localized version of the certificate date string and
3423 * the original certificate date string if fails to localize.
3424 * If the original string is null, returns an empty string "".
3425 */
3426 private String reformatCertificateDate(String certificateDate) {
3427 String reformattedDate = null;
3428
3429 if (certificateDate != null) {
3430 Date date = null;
3431 try {
3432 date = java.text.DateFormat.getInstance().parse(certificateDate);
3433 } catch (ParseException e) {
3434 date = null;
3435 }
3436
3437 if (date != null) {
3438 reformattedDate =
3439 DateFormat.getDateFormat(this).format(date);
3440 }
3441 }
3442
3443 return reformattedDate != null ? reformattedDate :
3444 (certificateDate != null ? certificateDate : "");
3445 }
3446
3447 /**
3448 * Displays an http-authentication dialog.
3449 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003450 void showHttpAuthentication(final HttpAuthHandler handler,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003451 final String host, final String realm, final String title,
3452 final String name, final String password, int focusId) {
3453 LayoutInflater factory = LayoutInflater.from(this);
3454 final View v = factory
3455 .inflate(R.layout.http_authentication, null);
3456 if (name != null) {
3457 ((EditText) v.findViewById(R.id.username_edit)).setText(name);
3458 }
3459 if (password != null) {
3460 ((EditText) v.findViewById(R.id.password_edit)).setText(password);
3461 }
3462
3463 String titleText = title;
3464 if (titleText == null) {
3465 titleText = getText(R.string.sign_in_to).toString().replace(
3466 "%s1", host).replace("%s2", realm);
3467 }
3468
3469 mHttpAuthHandler = handler;
3470 AlertDialog dialog = new AlertDialog.Builder(this)
3471 .setTitle(titleText)
3472 .setIcon(android.R.drawable.ic_dialog_alert)
3473 .setView(v)
3474 .setPositiveButton(R.string.action,
3475 new DialogInterface.OnClickListener() {
3476 public void onClick(DialogInterface dialog,
3477 int whichButton) {
3478 String nm = ((EditText) v
3479 .findViewById(R.id.username_edit))
3480 .getText().toString();
3481 String pw = ((EditText) v
3482 .findViewById(R.id.password_edit))
3483 .getText().toString();
3484 BrowserActivity.this.setHttpAuthUsernamePassword
3485 (host, realm, nm, pw);
3486 handler.proceed(nm, pw);
3487 mHttpAuthenticationDialog = null;
3488 mHttpAuthHandler = null;
3489 }})
3490 .setNegativeButton(R.string.cancel,
3491 new DialogInterface.OnClickListener() {
3492 public void onClick(DialogInterface dialog,
3493 int whichButton) {
3494 handler.cancel();
3495 BrowserActivity.this.resetTitleAndRevertLockIcon();
3496 mHttpAuthenticationDialog = null;
3497 mHttpAuthHandler = null;
3498 }})
3499 .setOnCancelListener(new DialogInterface.OnCancelListener() {
3500 public void onCancel(DialogInterface dialog) {
3501 handler.cancel();
3502 BrowserActivity.this.resetTitleAndRevertLockIcon();
3503 mHttpAuthenticationDialog = null;
3504 mHttpAuthHandler = null;
3505 }})
3506 .create();
3507 // Make the IME appear when the dialog is displayed if applicable.
3508 dialog.getWindow().setSoftInputMode(
3509 WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
3510 dialog.show();
3511 if (focusId != 0) {
3512 dialog.findViewById(focusId).requestFocus();
3513 } else {
3514 v.findViewById(R.id.username_edit).requestFocus();
3515 }
3516 mHttpAuthenticationDialog = dialog;
3517 }
3518
3519 public int getProgress() {
3520 WebView w = mTabControl.getCurrentWebView();
3521 if (w != null) {
3522 return w.getProgress();
3523 } else {
3524 return 100;
3525 }
3526 }
3527
3528 /**
3529 * Set HTTP authentication password.
3530 *
3531 * @param host The host for the password
3532 * @param realm The realm for the password
3533 * @param username The username for the password. If it is null, it means
3534 * password can't be saved.
3535 * @param password The password
3536 */
3537 public void setHttpAuthUsernamePassword(String host, String realm,
3538 String username,
3539 String password) {
3540 WebView w = mTabControl.getCurrentWebView();
3541 if (w != null) {
3542 w.setHttpAuthUsernamePassword(host, realm, username, password);
3543 }
3544 }
3545
3546 /**
3547 * connectivity manager says net has come or gone... inform the user
3548 * @param up true if net has come up, false if net has gone down
3549 */
3550 public void onNetworkToggle(boolean up) {
3551 if (up == mIsNetworkUp) {
3552 return;
3553 } else if (up) {
3554 mIsNetworkUp = true;
3555 if (mAlertDialog != null) {
3556 mAlertDialog.cancel();
3557 mAlertDialog = null;
3558 }
3559 } else {
3560 mIsNetworkUp = false;
Patrick Scotteb6ab2a2009-09-16 10:00:17 -04003561 if (mInLoad) {
3562 createAndShowNetworkDialog();
3563 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003564 }
3565 WebView w = mTabControl.getCurrentWebView();
3566 if (w != null) {
3567 w.setNetworkAvailable(up);
3568 }
3569 }
3570
Grace Kloba22ac16e2009-10-07 18:00:23 -07003571 boolean isNetworkUp() {
3572 return mIsNetworkUp;
3573 }
3574
Patrick Scotteb6ab2a2009-09-16 10:00:17 -04003575 // This method shows the network dialog alerting the user that the net is
3576 // down. It will only show the dialog if mAlertDialog is null.
3577 private void createAndShowNetworkDialog() {
3578 if (mAlertDialog == null) {
3579 mAlertDialog = new AlertDialog.Builder(this)
3580 .setTitle(R.string.loadSuspendedTitle)
3581 .setMessage(R.string.loadSuspended)
3582 .setPositiveButton(R.string.ok, null)
3583 .show();
3584 }
3585 }
3586
The Android Open Source Project0c908882009-03-03 19:32:16 -08003587 @Override
3588 protected void onActivityResult(int requestCode, int resultCode,
3589 Intent intent) {
Grace Klobabb394f32009-11-19 10:26:37 -08003590 if (getTopWindow() == null) return;
3591
The Android Open Source Project0c908882009-03-03 19:32:16 -08003592 switch (requestCode) {
3593 case COMBO_PAGE:
3594 if (resultCode == RESULT_OK && intent != null) {
3595 String data = intent.getAction();
3596 Bundle extras = intent.getExtras();
3597 if (extras != null && extras.getBoolean("new_window", false)) {
Leon Scroggins25d35472009-09-15 11:37:27 -04003598 openTab(data);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003599 } else {
Grace Kloba22ac16e2009-10-07 18:00:23 -07003600 final Tab currentTab =
The Android Open Source Project0c908882009-03-03 19:32:16 -08003601 mTabControl.getCurrentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04003602 dismissSubWindow(currentTab);
3603 if (data != null && data.length() != 0) {
Leon Scroggins92472e82010-02-17 16:32:28 -05003604 loadUrl(getTopWindow(), data);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003605 }
3606 }
3607 }
Leon Scrogginsfde97462010-01-11 13:06:21 -05003608 // Deliberately fall through to PREFERENCES_PAGE, since the
3609 // same extra may be attached to the COMBO_PAGE
3610 case PREFERENCES_PAGE:
3611 if (resultCode == RESULT_OK && intent != null) {
3612 String action = intent.getStringExtra(Intent.EXTRA_TEXT);
3613 if (BrowserSettings.PREF_CLEAR_HISTORY.equals(action)) {
3614 mTabControl.removeParentChildRelationShips();
3615 }
3616 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003617 break;
Leon Scroggins8d5fa432009-10-02 15:55:59 -04003618 // Choose a file from the file picker.
3619 case FILE_SELECTED:
3620 if (null == mUploadMessage) break;
3621 Uri result = intent == null || resultCode != RESULT_OK ? null
3622 : intent.getData();
3623 mUploadMessage.onReceiveValue(result);
3624 mUploadMessage = null;
3625 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003626 default:
3627 break;
3628 }
Leon Scroggins30444232009-09-04 18:36:20 -04003629 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003630 }
3631
3632 /*
3633 * This method is called as a result of the user selecting the options
Leon Scrogginsf08809b2010-01-21 09:27:46 -05003634 * menu to see the download window. It shows the download window on top of
3635 * the current window.
The Android Open Source Project0c908882009-03-03 19:32:16 -08003636 */
Leon Scrogginsf08809b2010-01-21 09:27:46 -05003637 private void viewDownloads(Uri downloadRecord) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003638 Intent intent = new Intent(this,
3639 BrowserDownloadPage.class);
3640 intent.setData(downloadRecord);
Grace Kloba22ac16e2009-10-07 18:00:23 -07003641 startActivityForResult(intent, BrowserActivity.DOWNLOAD_PAGE);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003642
3643 }
3644
Leon Scroggins160a7e72009-08-14 18:28:01 -04003645 /**
3646 * Open the Go page.
3647 * @param startWithHistory If true, open starting on the history tab.
3648 * Otherwise, start with the bookmarks tab.
Leon Scroggins160a7e72009-08-14 18:28:01 -04003649 */
Leon Scroggins30444232009-09-04 18:36:20 -04003650 /* package */ void bookmarksOrHistoryPicker(boolean startWithHistory) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003651 WebView current = mTabControl.getCurrentWebView();
3652 if (current == null) {
3653 return;
3654 }
3655 Intent intent = new Intent(this,
3656 CombinedBookmarkHistoryActivity.class);
3657 String title = current.getTitle();
3658 String url = current.getUrl();
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01003659 Bitmap thumbnail = createScreenshot(current);
3660
The Android Open Source Project0c908882009-03-03 19:32:16 -08003661 // Just in case the user opens bookmarks before a page finishes loading
3662 // so the current history item, and therefore the page, is null.
3663 if (null == url) {
3664 url = mLastEnteredUrl;
3665 // This can happen.
3666 if (null == url) {
3667 url = mSettings.getHomePage();
3668 }
3669 }
3670 // In case the web page has not yet received its associated title.
3671 if (title == null) {
3672 title = url;
3673 }
3674 intent.putExtra("title", title);
3675 intent.putExtra("url", url);
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01003676 intent.putExtra("thumbnail", thumbnail);
Leon Scroggins30444232009-09-04 18:36:20 -04003677 // Disable opening in a new window if we have maxed out the windows
Grace Kloba22ac16e2009-10-07 18:00:23 -07003678 intent.putExtra("disable_new_window", !mTabControl.canCreateNewTab());
Patrick Scott3918d442009-08-04 13:22:29 -04003679 intent.putExtra("touch_icon_url", current.getTouchIconUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003680 if (startWithHistory) {
3681 intent.putExtra(CombinedBookmarkHistoryActivity.STARTING_TAB,
3682 CombinedBookmarkHistoryActivity.HISTORY_TAB);
3683 }
3684 startActivityForResult(intent, COMBO_PAGE);
3685 }
3686
3687 // Called when loading from context menu or LOAD_URL message
Leon Scroggins92472e82010-02-17 16:32:28 -05003688 private void loadUrlFromContext(WebView view, String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003689 // In case the user enters nothing.
3690 if (url != null && url.length() != 0 && view != null) {
3691 url = smartUrlFilter(url);
Grace Kloba22ac16e2009-10-07 18:00:23 -07003692 if (!view.getWebViewClient().shouldOverrideUrlLoading(view, url)) {
Leon Scroggins92472e82010-02-17 16:32:28 -05003693 loadUrl(view, url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003694 }
3695 }
3696 }
3697
Leon Scroggins92472e82010-02-17 16:32:28 -05003698 /**
3699 * Load the URL into the given WebView and update the title bar
3700 * to reflect the new load. Call this instead of WebView.loadUrl
3701 * directly.
3702 * @param view The WebView used to load url.
3703 * @param url The URL to load.
3704 */
3705 private void loadUrl(WebView view, String url) {
3706 updateTitleBarForNewLoad(view, url);
3707 view.loadUrl(url);
3708 }
3709
3710 /**
3711 * Load UrlData into a Tab and update the title bar to reflect the new
3712 * load. Call this instead of UrlData.loadIn directly.
3713 * @param t The Tab used to load.
3714 * @param data The UrlData being loaded.
3715 */
3716 private void loadUrlDataIn(Tab t, UrlData data) {
3717 updateTitleBarForNewLoad(t.getWebView(), data.mUrl);
3718 data.loadIn(t);
3719 }
3720
3721 /**
3722 * If the WebView is the top window, update the title bar to reflect
3723 * loading the new URL. i.e. set its text, clear the favicon (which
3724 * will be set once the page begins loading), and set the progress to
3725 * INITIAL_PROGRESS to show that the page has begun to load. Called
3726 * by loadUrl and loadUrlDataIn.
3727 * @param view The WebView that is starting a load.
3728 * @param url The URL that is being loaded.
3729 */
3730 private void updateTitleBarForNewLoad(WebView view, String url) {
3731 if (view == getTopWindow()) {
3732 setUrlTitle(url, null);
3733 setFavicon(null);
3734 onProgressChanged(view, INITIAL_PROGRESS);
3735 }
3736 }
3737
The Android Open Source Project0c908882009-03-03 19:32:16 -08003738 private String smartUrlFilter(Uri inUri) {
3739 if (inUri != null) {
3740 return smartUrlFilter(inUri.toString());
3741 }
3742 return null;
3743 }
3744
Feng Qianb34f87a2009-03-24 21:27:26 -07003745 protected static final Pattern ACCEPTED_URI_SCHEMA = Pattern.compile(
The Android Open Source Project0c908882009-03-03 19:32:16 -08003746 "(?i)" + // switch on case insensitive matching
3747 "(" + // begin group for schema
3748 "(?:http|https|file):\\/\\/" +
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003749 "|(?:inline|data|about|content|javascript):" +
The Android Open Source Project0c908882009-03-03 19:32:16 -08003750 ")" +
3751 "(.*)" );
3752
3753 /**
3754 * Attempts to determine whether user input is a URL or search
3755 * terms. Anything with a space is passed to search.
3756 *
3757 * Converts to lowercase any mistakenly uppercased schema (i.e.,
3758 * "Http://" converts to "http://"
3759 *
3760 * @return Original or modified URL
3761 *
3762 */
3763 String smartUrlFilter(String url) {
3764
3765 String inUrl = url.trim();
3766 boolean hasSpace = inUrl.indexOf(' ') != -1;
3767
3768 Matcher matcher = ACCEPTED_URI_SCHEMA.matcher(inUrl);
3769 if (matcher.matches()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003770 // force scheme to lowercase
3771 String scheme = matcher.group(1);
3772 String lcScheme = scheme.toLowerCase();
3773 if (!lcScheme.equals(scheme)) {
Mitsuru Oshima123ecfb2009-05-18 19:11:14 -07003774 inUrl = lcScheme + matcher.group(2);
3775 }
3776 if (hasSpace) {
3777 inUrl = inUrl.replace(" ", "%20");
The Android Open Source Project0c908882009-03-03 19:32:16 -08003778 }
3779 return inUrl;
3780 }
3781 if (hasSpace) {
Satish Sampath565505b2009-05-29 15:37:27 +01003782 // FIXME: Is this the correct place to add to searches?
3783 // what if someone else calls this function?
3784 int shortcut = parseUrlShortcut(inUrl);
3785 if (shortcut != SHORTCUT_INVALID) {
3786 Browser.addSearchUrl(mResolver, inUrl);
3787 String query = inUrl.substring(2);
3788 switch (shortcut) {
3789 case SHORTCUT_GOOGLE_SEARCH:
Grace Kloba47fdfdb2009-06-30 11:15:34 -07003790 return URLUtil.composeSearchUrl(query, QuickSearch_G, QUERY_PLACE_HOLDER);
Satish Sampath565505b2009-05-29 15:37:27 +01003791 case SHORTCUT_WIKIPEDIA_SEARCH:
3792 return URLUtil.composeSearchUrl(query, QuickSearch_W, QUERY_PLACE_HOLDER);
3793 case SHORTCUT_DICTIONARY_SEARCH:
3794 return URLUtil.composeSearchUrl(query, QuickSearch_D, QUERY_PLACE_HOLDER);
3795 case SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH:
The Android Open Source Project0c908882009-03-03 19:32:16 -08003796 // FIXME: we need location in this case
Satish Sampath565505b2009-05-29 15:37:27 +01003797 return URLUtil.composeSearchUrl(query, QuickSearch_L, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003798 }
3799 }
3800 } else {
Dan Egnor5ee906c2009-11-18 12:11:49 -08003801 if (Patterns.WEB_URL.matcher(inUrl).matches()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003802 return URLUtil.guessUrl(inUrl);
3803 }
3804 }
3805
3806 Browser.addSearchUrl(mResolver, inUrl);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07003807 return URLUtil.composeSearchUrl(inUrl, QuickSearch_G, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003808 }
3809
Ben Murdochbff2d602009-07-01 20:19:05 +01003810 /* package */ void setShouldShowErrorConsole(boolean flag) {
3811 if (flag == mShouldShowErrorConsole) {
3812 // Nothing to do.
3813 return;
3814 }
3815
3816 mShouldShowErrorConsole = flag;
3817
Grace Kloba22ac16e2009-10-07 18:00:23 -07003818 ErrorConsoleView errorConsole = mTabControl.getCurrentTab()
3819 .getErrorConsole(true);
Ben Murdochbff2d602009-07-01 20:19:05 +01003820
3821 if (flag) {
3822 // Setting the show state of the console will cause it's the layout to be inflated.
3823 if (errorConsole.numberOfErrors() > 0) {
3824 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
3825 } else {
3826 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
3827 }
3828
3829 // Now we can add it to the main view.
3830 mErrorConsoleContainer.addView(errorConsole,
Romain Guy15b8ec62010-01-08 15:06:43 -08003831 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
Ben Murdochbff2d602009-07-01 20:19:05 +01003832 ViewGroup.LayoutParams.WRAP_CONTENT));
3833 } else {
3834 mErrorConsoleContainer.removeView(errorConsole);
3835 }
3836
3837 }
3838
Grace Kloba22ac16e2009-10-07 18:00:23 -07003839 boolean shouldShowErrorConsole() {
3840 return mShouldShowErrorConsole;
3841 }
3842
Andrei Popescu163ab742009-10-20 17:58:23 +01003843 private void setStatusBarVisibility(boolean visible) {
3844 int flag = visible ? 0 : WindowManager.LayoutParams.FLAG_FULLSCREEN;
3845 getWindow().setFlags(flag, WindowManager.LayoutParams.FLAG_FULLSCREEN);
3846 }
3847
Andrei Popescu56199cc2010-01-12 22:39:16 +00003848
3849 private void sendNetworkType(String type, String subtype) {
3850 WebView w = mTabControl.getCurrentWebView();
3851 if (w != null) {
3852 w.setNetworkType(type, subtype);
3853 }
3854 }
3855
Andrei Popescu30995e72010-02-09 16:59:58 +00003856 private void packageChanged(String packageName, boolean wasAdded) {
3857 WebView w = mTabControl.getCurrentWebView();
3858 if (w == null) {
3859 return;
3860 }
3861
3862 if (wasAdded) {
3863 w.addPackageName(packageName);
3864 } else {
3865 w.removePackageName(packageName);
3866 }
3867 }
3868
3869 private void addPackageNames(Set<String> packageNames) {
3870 WebView w = mTabControl.getCurrentWebView();
3871 if (w == null) {
3872 return;
3873 }
3874
3875 w.addPackageNames(packageNames);
3876 }
3877
3878 private void getInstalledPackages() {
3879 AsyncTask<Void, Void, Set<String> > task =
3880 new AsyncTask<Void, Void, Set<String> >() {
3881 protected Set<String> doInBackground(Void... unused) {
3882 Set<String> installedPackages = new HashSet<String>();
3883 PackageManager pm = BrowserActivity.this.getPackageManager();
3884 if (pm != null) {
3885 List<PackageInfo> packages = pm.getInstalledPackages(0);
3886 for (PackageInfo p : packages) {
3887 if (BrowserActivity.this.sGoogleApps.contains(p.packageName)) {
3888 installedPackages.add(p.packageName);
3889 }
3890 }
3891 }
3892
3893 return installedPackages;
3894 }
3895
3896 // Executes on the UI thread
3897 protected void onPostExecute(Set<String> installedPackages) {
3898 addPackageNames(installedPackages);
3899 }
3900 };
3901 task.execute();
3902 }
3903
Grace Klobaeb6eef42009-09-15 17:56:32 -07003904 final static int LOCK_ICON_UNSECURE = 0;
3905 final static int LOCK_ICON_SECURE = 1;
3906 final static int LOCK_ICON_MIXED = 2;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003907
The Android Open Source Project0c908882009-03-03 19:32:16 -08003908 private BrowserSettings mSettings;
3909 private TabControl mTabControl;
3910 private ContentResolver mResolver;
3911 private FrameLayout mContentView;
Andrei Popescuadc008d2009-06-26 14:11:30 +01003912 private View mCustomView;
3913 private FrameLayout mCustomViewContainer;
Andrei Popescuc9b55562009-07-07 10:51:15 +01003914 private WebChromeClient.CustomViewCallback mCustomViewCallback;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003915
3916 // FIXME, temp address onPrepareMenu performance problem. When we move everything out of
3917 // view, we should rewrite this.
3918 private int mCurrentMenuState = 0;
3919 private int mMenuState = R.id.MAIN_MENU;
Andrei Popescuadc008d2009-06-26 14:11:30 +01003920 private int mOldMenuState = EMPTY_MENU;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003921 private static final int EMPTY_MENU = -1;
3922 private Menu mMenu;
3923
3924 private FindDialog mFindDialog;
3925 // Used to prevent chording to result in firing two shortcuts immediately
3926 // one after another. Fixes bug 1211714.
3927 boolean mCanChord;
3928
3929 private boolean mInLoad;
3930 private boolean mIsNetworkUp;
Ben Murdochb7cc8b42009-09-28 10:59:09 +01003931 private boolean mDidStopLoad;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003932
The Android Open Source Project0c908882009-03-03 19:32:16 -08003933 private boolean mActivityInPause = true;
3934
3935 private boolean mMenuIsDown;
3936
The Android Open Source Project0c908882009-03-03 19:32:16 -08003937 private static boolean mInTrace;
3938
3939 // Performance probe
3940 private static final int[] SYSTEM_CPU_FORMAT = new int[] {
3941 Process.PROC_SPACE_TERM | Process.PROC_COMBINE,
3942 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 1: user time
3943 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 2: nice time
3944 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 3: sys time
3945 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 4: idle time
3946 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 5: iowait time
3947 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 6: irq time
3948 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG // 7: softirq time
3949 };
3950
3951 private long mStart;
3952 private long mProcessStart;
3953 private long mUserStart;
3954 private long mSystemStart;
3955 private long mIdleStart;
3956 private long mIrqStart;
3957
3958 private long mUiStart;
3959
3960 private Drawable mMixLockIcon;
3961 private Drawable mSecLockIcon;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003962
3963 /* hold a ref so we can auto-cancel if necessary */
3964 private AlertDialog mAlertDialog;
3965
3966 // Wait for credentials before loading google.com
3967 private ProgressDialog mCredsDlg;
3968
3969 // The up-to-date URL and title (these can be different from those stored
3970 // in WebView, since it takes some time for the information in WebView to
3971 // get updated)
3972 private String mUrl;
3973 private String mTitle;
3974
3975 // As PageInfo has different style for landscape / portrait, we have
3976 // to re-open it when configuration changed
3977 private AlertDialog mPageInfoDialog;
Grace Kloba22ac16e2009-10-07 18:00:23 -07003978 private Tab mPageInfoView;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003979 // If the Page-Info dialog is launched from the SSL-certificate-on-error
3980 // dialog, we should not just dismiss it, but should get back to the
3981 // SSL-certificate-on-error dialog. This flag is used to store this state
Leon Scrogginsc7b92f82010-01-11 18:17:31 -05003982 private boolean mPageInfoFromShowSSLCertificateOnError;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003983
3984 // as SSLCertificateOnError has different style for landscape / portrait,
3985 // we have to re-open it when configuration changed
3986 private AlertDialog mSSLCertificateOnErrorDialog;
3987 private WebView mSSLCertificateOnErrorView;
3988 private SslErrorHandler mSSLCertificateOnErrorHandler;
3989 private SslError mSSLCertificateOnErrorError;
3990
3991 // as SSLCertificate has different style for landscape / portrait, we
3992 // have to re-open it when configuration changed
3993 private AlertDialog mSSLCertificateDialog;
Grace Kloba22ac16e2009-10-07 18:00:23 -07003994 private Tab mSSLCertificateView;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003995
3996 // as HttpAuthentication has different style for landscape / portrait, we
3997 // have to re-open it when configuration changed
3998 private AlertDialog mHttpAuthenticationDialog;
3999 private HttpAuthHandler mHttpAuthHandler;
4000
4001 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_PARAMS =
4002 new FrameLayout.LayoutParams(
Romain Guy15b8ec62010-01-08 15:06:43 -08004003 ViewGroup.LayoutParams.MATCH_PARENT,
4004 ViewGroup.LayoutParams.MATCH_PARENT);
Andrei Popescuadc008d2009-06-26 14:11:30 +01004005 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_GRAVITY_CENTER =
4006 new FrameLayout.LayoutParams(
Romain Guy15b8ec62010-01-08 15:06:43 -08004007 ViewGroup.LayoutParams.MATCH_PARENT,
4008 ViewGroup.LayoutParams.MATCH_PARENT,
Andrei Popescuadc008d2009-06-26 14:11:30 +01004009 Gravity.CENTER);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07004010 // Google search
4011 final static String QuickSearch_G = "http://www.google.com/m?q=%s";
The Android Open Source Project0c908882009-03-03 19:32:16 -08004012 // Wikipedia search
4013 final static String QuickSearch_W = "http://en.wikipedia.org/w/index.php?search=%s&go=Go";
4014 // Dictionary search
4015 final static String QuickSearch_D = "http://dictionary.reference.com/search?q=%s";
4016 // Google Mobile Local search
4017 final static String QuickSearch_L = "http://www.google.com/m/search?site=local&q=%s&near=mountain+view";
4018
4019 final static String QUERY_PLACE_HOLDER = "%s";
4020
4021 // "source" parameter for Google search through search key
4022 final static String GOOGLE_SEARCH_SOURCE_SEARCHKEY = "browser-key";
4023 // "source" parameter for Google search through goto menu
4024 final static String GOOGLE_SEARCH_SOURCE_GOTO = "browser-goto";
4025 // "source" parameter for Google search through simplily type
4026 final static String GOOGLE_SEARCH_SOURCE_TYPE = "browser-type";
4027 // "source" parameter for Google search suggested by the browser
4028 final static String GOOGLE_SEARCH_SOURCE_SUGGEST = "browser-suggest";
4029 // "source" parameter for Google search from unknown source
4030 final static String GOOGLE_SEARCH_SOURCE_UNKNOWN = "unknown";
4031
4032 private final static String LOGTAG = "browser";
4033
The Android Open Source Project0c908882009-03-03 19:32:16 -08004034 private String mLastEnteredUrl;
4035
4036 private PowerManager.WakeLock mWakeLock;
4037 private final static int WAKELOCK_TIMEOUT = 5 * 60 * 1000; // 5 minutes
4038
4039 private Toast mStopToast;
4040
Leon Scroggins68579392009-09-15 15:31:54 -04004041 private TitleBar mTitleBar;
Leon Scroggins81db3662009-06-04 17:45:11 -04004042
Ben Murdochbff2d602009-07-01 20:19:05 +01004043 private LinearLayout mErrorConsoleContainer = null;
4044 private boolean mShouldShowErrorConsole = false;
4045
The Android Open Source Project0c908882009-03-03 19:32:16 -08004046 // As the ids are dynamically created, we can't guarantee that they will
4047 // be in sequence, so this static array maps ids to a window number.
4048 final static private int[] WINDOW_SHORTCUT_ID_ARRAY =
4049 { R.id.window_one_menu_id, R.id.window_two_menu_id, R.id.window_three_menu_id,
4050 R.id.window_four_menu_id, R.id.window_five_menu_id, R.id.window_six_menu_id,
4051 R.id.window_seven_menu_id, R.id.window_eight_menu_id };
4052
4053 // monitor platform changes
4054 private IntentFilter mNetworkStateChangedFilter;
4055 private BroadcastReceiver mNetworkStateIntentReceiver;
4056
Grace Klobab4da0ad2009-05-14 14:45:40 -07004057 private BroadcastReceiver mPackageInstallationReceiver;
4058
The Android Open Source Project0c908882009-03-03 19:32:16 -08004059 // activity requestCode
Nicolas Roard78a98e42009-05-11 13:34:17 +01004060 final static int COMBO_PAGE = 1;
4061 final static int DOWNLOAD_PAGE = 2;
4062 final static int PREFERENCES_PAGE = 3;
Leon Scroggins8d5fa432009-10-02 15:55:59 -04004063 final static int FILE_SELECTED = 4;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004064
Andrei Popescu540035d2009-09-18 18:59:20 +01004065 // the default <video> poster
4066 private Bitmap mDefaultVideoPoster;
4067 // the video progress view
4068 private View mVideoProgressView;
4069
Andrei Popescu30995e72010-02-09 16:59:58 +00004070 // The Google packages we monitor for the navigator.isApplicationInstalled()
4071 // API. Add as needed.
4072 private static Set<String> sGoogleApps;
4073 static {
4074 sGoogleApps = new HashSet<String>();
4075 sGoogleApps.add("com.google.android.youtube");
4076 }
4077
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004078 /**
4079 * A UrlData class to abstract how the content will be set to WebView.
4080 * This base class uses loadUrl to show the content.
4081 */
4082 private static class UrlData {
Grace Kloba068e48b2010-01-26 18:11:27 -08004083 final String mUrl;
4084 final Map<String, String> mHeaders;
Leon Scroggins58d56c62010-01-28 15:12:40 -05004085 final Intent mVoiceIntent;
Grace Kloba60e095c2009-06-16 11:50:55 -07004086
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004087 UrlData(String url) {
4088 this.mUrl = url;
Grace Kloba068e48b2010-01-26 18:11:27 -08004089 this.mHeaders = null;
Leon Scroggins58d56c62010-01-28 15:12:40 -05004090 this.mVoiceIntent = null;
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004091 }
Grace Kloba60e095c2009-06-16 11:50:55 -07004092
Leon Scroggins58d56c62010-01-28 15:12:40 -05004093 UrlData(String url, Map<String, String> headers, Intent intent) {
Grace Kloba068e48b2010-01-26 18:11:27 -08004094 this.mUrl = url;
4095 this.mHeaders = headers;
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -05004096 if (RecognizerResultsIntent.ACTION_VOICE_SEARCH_RESULTS
4097 .equals(intent.getAction())) {
Leon Scroggins58d56c62010-01-28 15:12:40 -05004098 this.mVoiceIntent = intent;
4099 } else {
4100 this.mVoiceIntent = null;
4101 }
Grace Kloba60e095c2009-06-16 11:50:55 -07004102 }
4103
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004104 boolean isEmpty() {
Leon Scroggins58d56c62010-01-28 15:12:40 -05004105 return mVoiceIntent == null && (mUrl == null || mUrl.length() == 0);
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004106 }
4107
Leon Scroggins92472e82010-02-17 16:32:28 -05004108 /**
4109 * Load this UrlData into the given Tab. Use loadUrlDataIn to update
4110 * the title bar as well.
4111 */
Leon Scroggins58d56c62010-01-28 15:12:40 -05004112 public void loadIn(Tab t) {
4113 if (mVoiceIntent != null) {
4114 t.activateVoiceSearchMode(mVoiceIntent);
4115 } else {
4116 t.getWebView().loadUrl(mUrl, mHeaders);
4117 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004118 }
4119 };
4120
Leon Scroggins1f005d32009-08-10 17:36:42 -04004121 /* package */ static final UrlData EMPTY_URL_DATA = new UrlData(null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004122}