blob: 8969296235e899b0e794b8a4c99efaba2fb2f755 [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;
Dianne Hackborn385effd2010-02-24 20:03:04 -080076import android.util.Patterns;
The Android Open Source Project0c908882009-03-03 19:32:16 -080077import android.view.ContextMenu;
78import android.view.Gravity;
79import android.view.KeyEvent;
80import android.view.LayoutInflater;
81import android.view.Menu;
82import android.view.MenuInflater;
83import android.view.MenuItem;
84import android.view.View;
85import android.view.ViewGroup;
86import android.view.Window;
87import android.view.WindowManager;
88import android.view.ContextMenu.ContextMenuInfo;
89import android.view.MenuItem.OnMenuItemClickListener;
The Android Open Source Project0c908882009-03-03 19:32:16 -080090import android.webkit.CookieManager;
91import android.webkit.CookieSyncManager;
92import android.webkit.DownloadListener;
93import android.webkit.HttpAuthHandler;
Grace Klobab4da0ad2009-05-14 14:45:40 -070094import android.webkit.PluginManager;
The Android Open Source Project0c908882009-03-03 19:32:16 -080095import android.webkit.SslErrorHandler;
96import android.webkit.URLUtil;
Leon Clarkecb6cc862009-09-29 18:35:13 +010097import android.webkit.ValueCallback;
The Android Open Source Project0c908882009-03-03 19:32:16 -080098import android.webkit.WebChromeClient;
99import android.webkit.WebHistoryItem;
100import android.webkit.WebIconDatabase;
101import android.webkit.WebView;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800102import android.widget.EditText;
103import android.widget.FrameLayout;
104import android.widget.LinearLayout;
105import android.widget.TextView;
106import android.widget.Toast;
Fred Quintana752b6562009-12-18 10:18:26 -0800107import android.accounts.Account;
108import android.accounts.AccountManager;
109import android.accounts.AccountManagerFuture;
110import android.accounts.AuthenticatorException;
111import android.accounts.OperationCanceledException;
112import android.accounts.AccountManagerCallback;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800113
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
Leon Scrogginsb6b7f9e2009-06-18 12:05:28 -0400117import java.io.ByteArrayOutputStream;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800118import java.io.File;
Ben Murdoch4f75ba22009-10-27 11:48:28 +0000119import java.io.IOException;
120import java.io.InputStream;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800121import java.net.MalformedURLException;
122import java.net.URI;
Dianne Hackborn99189432009-06-17 18:06:18 -0700123import java.net.URISyntaxException;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800124import java.net.URL;
125import java.net.URLEncoder;
126import java.text.ParseException;
127import java.util.Date;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800128import java.util.HashMap;
Andrei Popescu30995e72010-02-09 16:59:58 +0000129import java.util.HashSet;
Grace Kloba00f54c52010-01-27 14:53:51 -0800130import java.util.Iterator;
Andrei Popescu30995e72010-02-09 16:59:58 +0000131import java.util.List;
Grace Kloba068e48b2010-01-26 18:11:27 -0800132import java.util.Map;
Andrei Popescu30995e72010-02-09 16:59:58 +0000133import java.util.Set;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800134import java.util.regex.Matcher;
135import java.util.regex.Pattern;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800136
137public class BrowserActivity extends Activity
Shimeng (Simon) Wang98d5fce2010-03-16 13:23:39 -0700138 implements View.OnCreateContextMenuListener, DownloadListener {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800139
Dave Bort31a6d1c2009-04-13 15:56:49 -0700140 /* Define some aliases to make these debugging flags easier to refer to.
141 * This file imports android.provider.Browser, so we can't just refer to "Browser.DEBUG".
142 */
143 private final static boolean DEBUG = com.android.browser.Browser.DEBUG;
144 private final static boolean LOGV_ENABLED = com.android.browser.Browser.LOGV_ENABLED;
145 private final static boolean LOGD_ENABLED = com.android.browser.Browser.LOGD_ENABLED;
146
Satish Sampath565505b2009-05-29 15:37:27 +0100147 // These are single-character shortcuts for searching popular sources.
148 private static final int SHORTCUT_INVALID = 0;
149 private static final int SHORTCUT_GOOGLE_SEARCH = 1;
150 private static final int SHORTCUT_WIKIPEDIA_SEARCH = 2;
151 private static final int SHORTCUT_DICTIONARY_SEARCH = 3;
152 private static final int SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH = 4;
153
Cary Clarka9771242009-08-11 16:42:26 -0400154 private static class ClearThumbnails extends AsyncTask<File, Void, Void> {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800155 @Override
156 public Void doInBackground(File... files) {
157 if (files != null) {
158 for (File f : files) {
Cary Clarkd6be1752009-08-12 12:56:42 -0400159 if (!f.delete()) {
160 Log.e(LOGTAG, f.getPath() + " was not deleted");
161 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800162 }
163 }
164 return null;
165 }
166 }
167
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400168 /**
169 * This layout holds everything you see below the status bar, including the
170 * error console, the custom view container, and the webviews.
171 */
172 private FrameLayout mBrowserFrameLayout;
Leon Scroggins81db3662009-06-04 17:45:11 -0400173
Grace Kloba22ac16e2009-10-07 18:00:23 -0700174 @Override
175 public void onCreate(Bundle icicle) {
Dave Bort31a6d1c2009-04-13 15:56:49 -0700176 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800177 Log.v(LOGTAG, this + " onStart");
178 }
179 super.onCreate(icicle);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800180 // test the browser in OpenGL
181 // requestWindowFeature(Window.FEATURE_OPENGL);
182
Mike Reedd334bf52010-01-26 15:21:44 -0500183 // enable this to test the browser in 32bit
184 if (false) {
185 getWindow().setFormat(PixelFormat.RGBX_8888);
186 BitmapFactory.setDefaultConfig(Bitmap.Config.ARGB_8888);
187 }
188
The Android Open Source Project0c908882009-03-03 19:32:16 -0800189 setDefaultKeyMode(DEFAULT_KEYS_SEARCH_LOCAL);
190
191 mResolver = getContentResolver();
192
Grace Kloba0923d692009-09-23 21:37:25 -0700193 // If this was a web search request, pass it on to the default web
194 // search provider and finish this activity.
195 if (handleWebSearchIntent(getIntent())) {
196 finish();
197 return;
198 }
199
The Android Open Source Project0c908882009-03-03 19:32:16 -0800200 mSecLockIcon = Resources.getSystem().getDrawable(
201 android.R.drawable.ic_secure);
202 mMixLockIcon = Resources.getSystem().getDrawable(
203 android.R.drawable.ic_partial_secure);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800204
Leon Scroggins81db3662009-06-04 17:45:11 -0400205 FrameLayout frameLayout = (FrameLayout) getWindow().getDecorView()
206 .findViewById(com.android.internal.R.id.content);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400207 mBrowserFrameLayout = (FrameLayout) LayoutInflater.from(this)
208 .inflate(R.layout.custom_screen, null);
209 mContentView = (FrameLayout) mBrowserFrameLayout.findViewById(
210 R.id.main_content);
211 mErrorConsoleContainer = (LinearLayout) mBrowserFrameLayout
212 .findViewById(R.id.error_console);
213 mCustomViewContainer = (FrameLayout) mBrowserFrameLayout
214 .findViewById(R.id.fullscreen_custom_content);
215 frameLayout.addView(mBrowserFrameLayout, COVER_SCREEN_PARAMS);
Leon Scroggins68579392009-09-15 15:31:54 -0400216 mTitleBar = new TitleBar(this);
Grace Kloba1542f742010-03-17 21:11:15 -0700217 // mTitleBar will be always shown in the fully loaded mode
218 mTitleBar.setProgress(100);
Leon Scrogginsfe87bd32009-10-06 10:10:00 -0400219 mFakeTitleBar = new TitleBar(this);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800220
221 // Create the tab control and our initial tab
222 mTabControl = new TabControl(this);
223
224 // Open the icon database and retain all the bookmark urls for favicons
225 retainIconsOnStartup();
226
227 // Keep a settings instance handy.
228 mSettings = BrowserSettings.getInstance();
229 mSettings.setTabControl(mTabControl);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800230
231 PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
232 mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Browser");
233
Patrick Scott6adacc92010-03-05 08:24:51 -0500234 // Find out if the network is currently up.
235 ConnectivityManager cm = (ConnectivityManager) getSystemService(
236 Context.CONNECTIVITY_SERVICE);
237 NetworkInfo info = cm.getActiveNetworkInfo();
238 if (info != null) {
239 mIsNetworkUp = info.isAvailable();
240 }
241
Grace Klobaa34f6862009-07-31 16:28:17 -0700242 /* enables registration for changes in network status from
243 http stack */
244 mNetworkStateChangedFilter = new IntentFilter();
245 mNetworkStateChangedFilter.addAction(
246 ConnectivityManager.CONNECTIVITY_ACTION);
247 mNetworkStateIntentReceiver = new BroadcastReceiver() {
248 @Override
249 public void onReceive(Context context, Intent intent) {
250 if (intent.getAction().equals(
251 ConnectivityManager.CONNECTIVITY_ACTION)) {
Andrei Popescue4c98462010-02-19 15:44:13 +0000252
253 NetworkInfo info = intent.getParcelableExtra(
254 ConnectivityManager.EXTRA_NETWORK_INFO);
255 String typeName = info.getTypeName();
256 String subtypeName = info.getSubtypeName();
257 sendNetworkType(typeName.toLowerCase(),
258 (subtypeName != null ? subtypeName.toLowerCase() : ""));
259
260 onNetworkToggle(info.isAvailable());
Grace Klobaa34f6862009-07-31 16:28:17 -0700261 }
262 }
263 };
264
Grace Kloba615c6c92009-08-03 10:22:44 -0700265 IntentFilter filter = new IntentFilter(Intent.ACTION_PACKAGE_ADDED);
266 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
267 filter.addDataScheme("package");
268 mPackageInstallationReceiver = new BroadcastReceiver() {
269 @Override
270 public void onReceive(Context context, Intent intent) {
271 final String action = intent.getAction();
272 final String packageName = intent.getData()
273 .getSchemeSpecificPart();
274 final boolean replacing = intent.getBooleanExtra(
275 Intent.EXTRA_REPLACING, false);
276 if (Intent.ACTION_PACKAGE_REMOVED.equals(action) && replacing) {
277 // if it is replacing, refreshPlugins() when adding
278 return;
279 }
Andrei Popescu30995e72010-02-09 16:59:58 +0000280
281 if (sGoogleApps.contains(packageName)) {
282 BrowserActivity.this.packageChanged(packageName,
283 Intent.ACTION_PACKAGE_ADDED.equals(action));
284 }
285
Grace Kloba615c6c92009-08-03 10:22:44 -0700286 PackageManager pm = BrowserActivity.this.getPackageManager();
287 PackageInfo pkgInfo = null;
288 try {
289 pkgInfo = pm.getPackageInfo(packageName,
290 PackageManager.GET_PERMISSIONS);
291 } catch (PackageManager.NameNotFoundException e) {
292 return;
293 }
294 if (pkgInfo != null) {
295 String permissions[] = pkgInfo.requestedPermissions;
296 if (permissions == null) {
297 return;
298 }
299 boolean permissionOk = false;
300 for (String permit : permissions) {
301 if (PluginManager.PLUGIN_PERMISSION.equals(permit)) {
302 permissionOk = true;
303 break;
304 }
305 }
306 if (permissionOk) {
307 PluginManager.getInstance(BrowserActivity.this)
308 .refreshPlugins(
309 Intent.ACTION_PACKAGE_ADDED
310 .equals(action));
311 }
312 }
313 }
314 };
315 registerReceiver(mPackageInstallationReceiver, filter);
316
The Android Open Source Project0c908882009-03-03 19:32:16 -0800317 if (!mTabControl.restoreState(icicle)) {
318 // clear up the thumbnail directory if we can't restore the state as
319 // none of the files in the directory are referenced any more.
320 new ClearThumbnails().execute(
321 mTabControl.getThumbnailDir().listFiles());
Grace Klobaaab3f092009-07-30 12:29:51 -0700322 // there is no quit on Android. But if we can't restore the state,
323 // we can treat it as a new Browser, remove the old session cookies.
324 CookieManager.getInstance().removeSessionCookie();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800325 final Intent intent = getIntent();
326 final Bundle extra = intent.getExtras();
327 // Create an initial tab.
328 // If the intent is ACTION_VIEW and data is not null, the Browser is
329 // invoked to view the content by another application. In this case,
330 // the tab will be close when exit.
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700331 UrlData urlData = getUrlDataFromIntent(intent);
332
Leon Scroggins58d56c62010-01-28 15:12:40 -0500333 String action = intent.getAction();
Grace Kloba22ac16e2009-10-07 18:00:23 -0700334 final Tab t = mTabControl.createNewTab(
Leon Scroggins58d56c62010-01-28 15:12:40 -0500335 (Intent.ACTION_VIEW.equals(action) &&
336 intent.getData() != null)
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -0500337 || RecognizerResultsIntent.ACTION_VOICE_SEARCH_RESULTS
338 .equals(action),
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700339 intent.getStringExtra(Browser.EXTRA_APPLICATION_ID), urlData.mUrl);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800340 mTabControl.setCurrentTab(t);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800341 attachTabToContentView(t);
342 WebView webView = t.getWebView();
343 if (extra != null) {
344 int scale = extra.getInt(Browser.INITIAL_ZOOM_LEVEL, 0);
345 if (scale > 0 && scale <= 1000) {
346 webView.setInitialScale(scale);
347 }
348 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800349
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700350 if (urlData.isEmpty()) {
Shimeng (Simon) Wang98d5fce2010-03-16 13:23:39 -0700351 loadUrl(webView, mSettings.getHomePage());
The Android Open Source Project0c908882009-03-03 19:32:16 -0800352 } else {
Patrick Scott9d53da02010-02-19 10:19:01 -0500353 loadUrlDataIn(t, urlData);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800354 }
355 } else {
356 // TabControl.restoreState() will create a new tab even if
Leon Scroggins1f005d32009-08-10 17:36:42 -0400357 // restoring the state fails.
The Android Open Source Project0c908882009-03-03 19:32:16 -0800358 attachTabToContentView(mTabControl.getCurrentTab());
359 }
Grace Kloba615c6c92009-08-03 10:22:44 -0700360
Feng Qianb3c02da2009-06-29 15:58:08 -0700361 // Read JavaScript flags if it exists.
362 String jsFlags = mSettings.getJsFlags();
363 if (jsFlags.trim().length() != 0) {
364 mTabControl.getCurrentWebView().setJsFlags(jsFlags);
365 }
Andrei Popescu30995e72010-02-09 16:59:58 +0000366 // Work out which packages are installed on the system.
367 getInstalledPackages();
Bjorn Bringerta7611812010-03-24 11:12:02 +0000368
369 // Start watching the default geolocation permissions
370 mSystemAllowGeolocationOrigins
371 = new SystemAllowGeolocationOrigins(getApplicationContext());
372 mSystemAllowGeolocationOrigins.start();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800373 }
374
Leon Scroggins58d56c62010-01-28 15:12:40 -0500375 /**
376 * Feed the previously stored results strings to the BrowserProvider so that
377 * the SearchDialog will show them instead of the standard searches.
378 * @param result String to show on the editable line of the SearchDialog.
379 */
380 /* package */ void showVoiceSearchResults(String result) {
381 ContentProviderClient client = mResolver.acquireContentProviderClient(
382 Browser.BOOKMARKS_URI);
383 ContentProvider prov = client.getLocalContentProvider();
384 BrowserProvider bp = (BrowserProvider) prov;
385 bp.setQueryResults(mTabControl.getCurrentTab().getVoiceSearchResults());
386 client.release();
387
Leon Scrogginsfbb3f152010-03-09 17:26:56 -0500388 Bundle bundle = createGoogleSearchSourceBundle(
389 GOOGLE_SEARCH_SOURCE_SEARCHKEY);
390 bundle.putBoolean(SearchManager.CONTEXT_IS_VOICE, true);
391 startSearch(result, false, bundle, false);
Leon Scroggins58d56c62010-01-28 15:12:40 -0500392 }
393
The Android Open Source Project0c908882009-03-03 19:32:16 -0800394 @Override
395 protected void onNewIntent(Intent intent) {
Grace Kloba22ac16e2009-10-07 18:00:23 -0700396 Tab current = mTabControl.getCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800397 // When a tab is closed on exit, the current tab index is set to -1.
398 // Reset before proceed as Browser requires the current tab to be set.
399 if (current == null) {
400 // Try to reset the tab in case the index was incorrect.
401 current = mTabControl.getTab(0);
402 if (current == null) {
403 // No tabs at all so just ignore this intent.
404 return;
405 }
406 mTabControl.setCurrentTab(current);
407 attachTabToContentView(current);
408 resetTitleAndIcon(current.getWebView());
409 }
410 final String action = intent.getAction();
411 final int flags = intent.getFlags();
412 if (Intent.ACTION_MAIN.equals(action) ||
413 (flags & Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY) != 0) {
414 // just resume the browser
415 return;
416 }
Leon Scrogginsb8a844d2010-03-18 15:06:15 -0400417 // In case the SearchDialog is open.
418 ((SearchManager) getSystemService(Context.SEARCH_SERVICE))
419 .stopSearch();
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -0500420 boolean activateVoiceSearch = RecognizerResultsIntent
421 .ACTION_VOICE_SEARCH_RESULTS.equals(action);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800422 if (Intent.ACTION_VIEW.equals(action)
423 || Intent.ACTION_SEARCH.equals(action)
424 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
Leon Scroggins58d56c62010-01-28 15:12:40 -0500425 || Intent.ACTION_WEB_SEARCH.equals(action)
426 || activateVoiceSearch) {
Leon Scroggins3b18ce32010-02-08 17:35:59 -0500427 if (current.isInVoiceSearchMode()) {
428 String title = current.getVoiceDisplayTitle();
429 if (title != null && title.equals(intent.getStringExtra(
430 SearchManager.QUERY))) {
431 // The user submitted the same search as the last voice
432 // search, so do nothing.
433 return;
434 }
Leon Scroggins1fe13a52010-02-09 15:31:26 -0500435 if (Intent.ACTION_SEARCH.equals(action)
436 && current.voiceSearchSourceIsGoogle()) {
437 Intent logIntent = new Intent(
438 LoggingEvents.ACTION_LOG_EVENT);
439 logIntent.putExtra(LoggingEvents.EXTRA_EVENT,
440 LoggingEvents.VoiceSearch.QUERY_UPDATED);
441 logIntent.putExtra(
442 LoggingEvents.VoiceSearch.EXTRA_QUERY_UPDATED_VALUE,
443 intent.getDataString());
444 sendBroadcast(logIntent);
445 // Note, onPageStarted will revert the voice title bar
446 // When http://b/issue?id=2379215 is fixed, we should update
447 // the title bar here.
448 }
Leon Scroggins3b18ce32010-02-08 17:35:59 -0500449 }
Satish Sampath565505b2009-05-29 15:37:27 +0100450 // If this was a search request (e.g. search query directly typed into the address bar),
451 // pass it on to the default web search provider.
452 if (handleWebSearchIntent(intent)) {
453 return;
454 }
455
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700456 UrlData urlData = getUrlDataFromIntent(intent);
457 if (urlData.isEmpty()) {
458 urlData = new UrlData(mSettings.getHomePage());
The Android Open Source Project0c908882009-03-03 19:32:16 -0800459 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700460
Grace Klobacc634032009-07-28 15:58:19 -0700461 final String appId = intent
462 .getStringExtra(Browser.EXTRA_APPLICATION_ID);
Leon Scroggins47208682010-04-07 17:59:48 -0400463 if ((Intent.ACTION_VIEW.equals(action)
464 // If a voice search has no appId, it means that it came
465 // from the browser. In that case, reuse the current tab.
466 || (activateVoiceSearch && appId != null))
Grace Klobacc634032009-07-28 15:58:19 -0700467 && !getPackageName().equals(appId)
468 && (flags & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0) {
Grace Kloba22ac16e2009-10-07 18:00:23 -0700469 Tab appTab = mTabControl.getTabFromId(appId);
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700470 if (appTab != null) {
471 Log.i(LOGTAG, "Reusing tab for " + appId);
472 // Dismiss the subwindow if applicable.
473 dismissSubWindow(appTab);
474 // Since we might kill the WebView, remove it from the
475 // content view first.
476 removeTabFromContentView(appTab);
477 // Recreate the main WebView after destroying the old one.
478 // If the WebView has the same original url and is on that
479 // page, it can be reused.
480 boolean needsLoad =
Leon Scroggins6eac63e2010-03-15 18:19:14 -0400481 mTabControl.recreateWebView(appTab, urlData);
Ben Murdochbff2d602009-07-01 20:19:05 +0100482
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700483 if (current != appTab) {
Leon Scroggins1f005d32009-08-10 17:36:42 -0400484 switchToTab(mTabControl.getTabIndex(appTab));
485 if (needsLoad) {
Patrick Scott9d53da02010-02-19 10:19:01 -0500486 loadUrlDataIn(appTab, urlData);
Leon Scroggins1f005d32009-08-10 17:36:42 -0400487 }
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700488 } else {
Leon Scroggins1f005d32009-08-10 17:36:42 -0400489 // If the tab was the current tab, we have to attach
490 // it to the view system again.
491 attachTabToContentView(appTab);
492 if (needsLoad) {
Patrick Scott9d53da02010-02-19 10:19:01 -0500493 loadUrlDataIn(appTab, urlData);
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700494 }
495 }
496 return;
Patrick Scottcd115892009-07-16 09:42:58 -0400497 } else {
498 // No matching application tab, try to find a regular tab
499 // with a matching url.
500 appTab = mTabControl.findUnusedTabWithUrl(urlData.mUrl);
Leon Scroggins25515f82009-08-19 15:31:58 -0400501 if (appTab != null) {
502 if (current != appTab) {
503 switchToTab(mTabControl.getTabIndex(appTab));
504 }
505 // Otherwise, we are already viewing the correct tab.
Patrick Scottcd115892009-07-16 09:42:58 -0400506 } else {
507 // if FLAG_ACTIVITY_BROUGHT_TO_FRONT flag is on, the url
508 // will be opened in a new tab unless we have reached
509 // MAX_TABS. Then the url will be opened in the current
510 // tab. If a new tab is created, it will have "true" for
511 // exit on close.
Leon Scroggins1f005d32009-08-10 17:36:42 -0400512 openTabAndShow(urlData, true, appId);
Patrick Scottcd115892009-07-16 09:42:58 -0400513 }
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700514 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800515 } else {
Grace Kloba638d3f42009-11-23 10:35:04 -0800516 if (!urlData.isEmpty()
517 && urlData.mUrl.startsWith("about:debug")) {
518 if ("about:debug.dom".equals(urlData.mUrl)) {
519 current.getWebView().dumpDomTree(false);
520 } else if ("about:debug.dom.file".equals(urlData.mUrl)) {
521 current.getWebView().dumpDomTree(true);
522 } else if ("about:debug.render".equals(urlData.mUrl)) {
523 current.getWebView().dumpRenderTree(false);
524 } else if ("about:debug.render.file".equals(urlData.mUrl)) {
525 current.getWebView().dumpRenderTree(true);
526 } else if ("about:debug.display".equals(urlData.mUrl)) {
527 current.getWebView().dumpDisplayTree();
Mike Reed9b78e1d2010-01-13 14:40:52 -0800528 } else if (urlData.mUrl.startsWith("about:debug.drag")) {
529 int index = urlData.mUrl.codePointAt(16) - '0';
530 if (index <= 0 || index > 9) {
531 current.getWebView().setDragTracker(null);
532 } else {
533 current.getWebView().setDragTracker(new MeshTracker(index));
534 }
Grace Kloba638d3f42009-11-23 10:35:04 -0800535 } else {
536 mSettings.toggleDebugSettings();
537 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800538 return;
539 }
Leon Scroggins1f005d32009-08-10 17:36:42 -0400540 // Get rid of the subwindow if it exists
541 dismissSubWindow(current);
Leon Scroggins8588d152010-04-15 11:01:53 -0400542 // If the current Tab is being used as an application tab,
543 // remove the association, since the new Intent means that it is
544 // no longer associated with that application.
545 current.setAppId(null);
Patrick Scott9d53da02010-02-19 10:19:01 -0500546 loadUrlDataIn(current, urlData);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800547 }
548 }
549 }
550
Satish Sampath565505b2009-05-29 15:37:27 +0100551 private int parseUrlShortcut(String url) {
552 if (url == null) return SHORTCUT_INVALID;
553
554 // FIXME: quick search, need to be customized by setting
555 if (url.length() > 2 && url.charAt(1) == ' ') {
556 switch (url.charAt(0)) {
557 case 'g': return SHORTCUT_GOOGLE_SEARCH;
558 case 'w': return SHORTCUT_WIKIPEDIA_SEARCH;
559 case 'd': return SHORTCUT_DICTIONARY_SEARCH;
560 case 'l': return SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH;
561 }
562 }
563 return SHORTCUT_INVALID;
564 }
565
566 /**
567 * Launches the default web search activity with the query parameters if the given intent's data
568 * are identified as plain search terms and not URLs/shortcuts.
569 * @return true if the intent was handled and web search activity was launched, false if not.
570 */
571 private boolean handleWebSearchIntent(Intent intent) {
572 if (intent == null) return false;
573
574 String url = null;
575 final String action = intent.getAction();
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -0500576 if (RecognizerResultsIntent.ACTION_VOICE_SEARCH_RESULTS.equals(
577 action)) {
Leon Scroggins58d56c62010-01-28 15:12:40 -0500578 return false;
579 }
Satish Sampath565505b2009-05-29 15:37:27 +0100580 if (Intent.ACTION_VIEW.equals(action)) {
Grace Kloba1e705052009-09-29 13:13:36 -0700581 Uri data = intent.getData();
582 if (data != null) url = data.toString();
Satish Sampath565505b2009-05-29 15:37:27 +0100583 } else if (Intent.ACTION_SEARCH.equals(action)
584 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
585 || Intent.ACTION_WEB_SEARCH.equals(action)) {
586 url = intent.getStringExtra(SearchManager.QUERY);
587 }
Bjorn Bringert04851702009-09-22 10:36:01 +0100588 return handleWebSearchRequest(url, intent.getBundleExtra(SearchManager.APP_DATA),
589 intent.getStringExtra(SearchManager.EXTRA_DATA_KEY));
Satish Sampath565505b2009-05-29 15:37:27 +0100590 }
591
592 /**
593 * Launches the default web search activity with the query parameters if the given url string
594 * was identified as plain search terms and not URL/shortcut.
595 * @return true if the request was handled and web search activity was launched, false if not.
596 */
Bjorn Bringert04851702009-09-22 10:36:01 +0100597 private boolean handleWebSearchRequest(String inUrl, Bundle appData, String extraData) {
Satish Sampath565505b2009-05-29 15:37:27 +0100598 if (inUrl == null) return false;
599
600 // In general, we shouldn't modify URL from Intent.
601 // But currently, we get the user-typed URL from search box as well.
602 String url = fixUrl(inUrl).trim();
603
604 // URLs and site specific search shortcuts are handled by the regular flow of control, so
605 // return early.
Dan Egnor5ee906c2009-11-18 12:11:49 -0800606 if (Patterns.WEB_URL.matcher(url).matches()
Satish Sampathbc5b9f32009-06-04 18:21:40 +0100607 || ACCEPTED_URI_SCHEMA.matcher(url).matches()
Satish Sampath565505b2009-05-29 15:37:27 +0100608 || parseUrlShortcut(url) != SHORTCUT_INVALID) {
609 return false;
610 }
611
Leon Scroggins8d06e362010-03-24 14:45:57 -0400612 final ContentResolver cr = mResolver;
613 final String newUrl = url;
614 new AsyncTask<Void, Void, Void>() {
615 protected Void doInBackground(Void... unused) {
616 Browser.updateVisitedHistory(cr, newUrl, false);
617 Browser.addSearchUrl(cr, newUrl);
618 return null;
619 }
620 }.execute();
Satish Sampath565505b2009-05-29 15:37:27 +0100621
622 Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);
623 intent.addCategory(Intent.CATEGORY_DEFAULT);
624 intent.putExtra(SearchManager.QUERY, url);
Satish Sampath15e9f2d2009-06-23 22:29:49 +0100625 if (appData != null) {
626 intent.putExtra(SearchManager.APP_DATA, appData);
627 }
Bjorn Bringert04851702009-09-22 10:36:01 +0100628 if (extraData != null) {
629 intent.putExtra(SearchManager.EXTRA_DATA_KEY, extraData);
630 }
Grace Klobacc634032009-07-28 15:58:19 -0700631 intent.putExtra(Browser.EXTRA_APPLICATION_ID, getPackageName());
Mattias Falk552751e2010-08-23 12:03:57 +0200632
633 // can't be sure there is an activity for the Intent
634 try {
635 startActivity(intent);
636 } catch (ActivityNotFoundException ex) {
637 return false;
638 }
Satish Sampath565505b2009-05-29 15:37:27 +0100639
640 return true;
641 }
642
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700643 private UrlData getUrlDataFromIntent(Intent intent) {
Leon Scroggins58d56c62010-01-28 15:12:40 -0500644 String url = "";
Grace Kloba068e48b2010-01-26 18:11:27 -0800645 Map<String, String> headers = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800646 if (intent != null) {
647 final String action = intent.getAction();
648 if (Intent.ACTION_VIEW.equals(action)) {
649 url = smartUrlFilter(intent.getData());
650 if (url != null && url.startsWith("content:")) {
651 /* Append mimetype so webview knows how to display */
652 String mimeType = intent.resolveType(getContentResolver());
653 if (mimeType != null) {
654 url += "?" + mimeType;
655 }
656 }
Grace Kloba068e48b2010-01-26 18:11:27 -0800657 if (url != null && url.startsWith("http")) {
Grace Kloba00f54c52010-01-27 14:53:51 -0800658 final Bundle pairs = intent
659 .getBundleExtra(Browser.EXTRA_HEADERS);
Grace Kloba2d508ed2010-01-28 11:39:15 -0800660 if (pairs != null && !pairs.isEmpty()) {
Grace Kloba00f54c52010-01-27 14:53:51 -0800661 Iterator<String> iter = pairs.keySet().iterator();
Grace Kloba068e48b2010-01-26 18:11:27 -0800662 headers = new HashMap<String, String>();
Grace Kloba00f54c52010-01-27 14:53:51 -0800663 while (iter.hasNext()) {
664 String key = iter.next();
665 headers.put(key, pairs.getString(key));
Grace Kloba068e48b2010-01-26 18:11:27 -0800666 }
667 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700668 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800669 } else if (Intent.ACTION_SEARCH.equals(action)
670 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
671 || Intent.ACTION_WEB_SEARCH.equals(action)) {
672 url = intent.getStringExtra(SearchManager.QUERY);
673 if (url != null) {
674 mLastEnteredUrl = url;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800675 // In general, we shouldn't modify URL from Intent.
676 // But currently, we get the user-typed URL from search box as well.
677 url = fixUrl(url);
678 url = smartUrlFilter(url);
Leon Scroggins8d06e362010-03-24 14:45:57 -0400679 final ContentResolver cr = mResolver;
680 final String newUrl = url;
681 new AsyncTask<Void, Void, Void>() {
682 protected Void doInBackground(Void... unused) {
683 Browser.updateVisitedHistory(cr, newUrl, false);
684 return null;
685 }
686 }.execute();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800687 String searchSource = "&source=android-" + GOOGLE_SEARCH_SOURCE_SUGGEST + "&";
688 if (url.contains(searchSource)) {
689 String source = null;
690 final Bundle appData = intent.getBundleExtra(SearchManager.APP_DATA);
691 if (appData != null) {
Bjorn Bringert10d1cca2010-02-10 14:22:12 +0000692 source = appData.getString(Search.SOURCE);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800693 }
694 if (TextUtils.isEmpty(source)) {
695 source = GOOGLE_SEARCH_SOURCE_UNKNOWN;
696 }
697 url = url.replace(searchSource, "&source=android-"+source+"&");
698 }
699 }
700 }
701 }
Leon Scroggins58d56c62010-01-28 15:12:40 -0500702 return new UrlData(url, headers, intent);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800703 }
Leon Scroggins58d56c62010-01-28 15:12:40 -0500704 /* package */ void showVoiceTitleBar(String title) {
705 mTitleBar.setInVoiceMode(true);
706 mFakeTitleBar.setInVoiceMode(true);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800707
Leon Scroggins58d56c62010-01-28 15:12:40 -0500708 mTitleBar.setDisplayTitle(title);
709 mFakeTitleBar.setDisplayTitle(title);
710 }
711 /* package */ void revertVoiceTitleBar() {
712 mTitleBar.setInVoiceMode(false);
713 mFakeTitleBar.setInVoiceMode(false);
714
Leon Scroggins003a5dd2010-03-10 12:13:14 -0500715 mTitleBar.setDisplayTitle(mUrl);
716 mFakeTitleBar.setDisplayTitle(mUrl);
Leon Scroggins58d56c62010-01-28 15:12:40 -0500717 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800718 /* package */ static String fixUrl(String inUrl) {
Cary Clark652ff872009-09-10 13:34:44 -0400719 // FIXME: Converting the url to lower case
720 // duplicates functionality in smartUrlFilter().
721 // However, changing all current callers of fixUrl to
722 // call smartUrlFilter in addition may have unwanted
723 // consequences, and is deferred for now.
724 int colon = inUrl.indexOf(':');
725 boolean allLower = true;
726 for (int index = 0; index < colon; index++) {
727 char ch = inUrl.charAt(index);
728 if (!Character.isLetter(ch)) {
729 break;
730 }
731 allLower &= Character.isLowerCase(ch);
732 if (index == colon - 1 && !allLower) {
733 inUrl = inUrl.substring(0, colon).toLowerCase()
734 + inUrl.substring(colon);
735 }
736 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800737 if (inUrl.startsWith("http://") || inUrl.startsWith("https://"))
738 return inUrl;
739 if (inUrl.startsWith("http:") ||
740 inUrl.startsWith("https:")) {
741 if (inUrl.startsWith("http:/") || inUrl.startsWith("https:/")) {
742 inUrl = inUrl.replaceFirst("/", "//");
743 } else inUrl = inUrl.replaceFirst(":", "://");
744 }
745 return inUrl;
746 }
747
Grace Kloba22ac16e2009-10-07 18:00:23 -0700748 @Override
749 protected void onResume() {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800750 super.onResume();
Dave Bort31a6d1c2009-04-13 15:56:49 -0700751 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800752 Log.v(LOGTAG, "BrowserActivity.onResume: this=" + this);
753 }
754
755 if (!mActivityInPause) {
756 Log.e(LOGTAG, "BrowserActivity is already resumed.");
757 return;
758 }
759
Mike Reed7bfa63b2009-05-28 11:08:32 -0400760 mTabControl.resumeCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800761 mActivityInPause = false;
Mike Reed7bfa63b2009-05-28 11:08:32 -0400762 resumeWebViewTimers();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800763
764 if (mWakeLock.isHeld()) {
765 mHandler.removeMessages(RELEASE_WAKELOCK);
766 mWakeLock.release();
767 }
768
The Android Open Source Project0c908882009-03-03 19:32:16 -0800769 registerReceiver(mNetworkStateIntentReceiver,
770 mNetworkStateChangedFilter);
771 WebView.enablePlatformNotifications();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800772 }
773
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400774 /**
775 * Since the actual title bar is embedded in the WebView, and removing it
Leon Scrogginsfe87bd32009-10-06 10:10:00 -0400776 * would change its appearance, use a different TitleBar to show overlayed
777 * at the top of the screen, when the menu is open or the page is loading.
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400778 */
779 private TitleBar mFakeTitleBar;
780
781 /**
782 * Keeps track of whether the options menu is open. This is important in
783 * determining whether to show or hide the title bar overlay.
784 */
785 private boolean mOptionsMenuOpen;
786
787 /**
788 * Only meaningful when mOptionsMenuOpen is true. This variable keeps track
789 * of whether the configuration has changed. The first onMenuOpened call
790 * after a configuration change is simply a reopening of the same menu
791 * (i.e. mIconView did not change).
792 */
793 private boolean mConfigChanged;
794
795 /**
796 * Whether or not the options menu is in its smaller, icon menu form. When
797 * true, we want the title bar overlay to be up. When false, we do not.
798 * Only meaningful if mOptionsMenuOpen is true.
799 */
800 private boolean mIconView;
801
Leon Scrogginsa81a7642009-08-31 17:05:41 -0400802 @Override
803 public boolean onMenuOpened(int featureId, Menu menu) {
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400804 if (Window.FEATURE_OPTIONS_PANEL == featureId) {
805 if (mOptionsMenuOpen) {
806 if (mConfigChanged) {
807 // We do not need to make any changes to the state of the
808 // title bar, since the only thing that happened was a
809 // change in orientation
810 mConfigChanged = false;
811 } else {
812 if (mIconView) {
813 // Switching the menu to expanded view, so hide the
814 // title bar.
815 hideFakeTitleBar();
816 mIconView = false;
817 } else {
818 // Switching the menu back to icon view, so show the
819 // title bar once again.
820 showFakeTitleBar();
821 mIconView = true;
822 }
823 }
824 } else {
825 // The options menu is closed, so open it, and show the title
826 showFakeTitleBar();
827 mOptionsMenuOpen = true;
828 mConfigChanged = false;
829 mIconView = true;
830 }
831 }
Leon Scrogginsa81a7642009-08-31 17:05:41 -0400832 return true;
833 }
834
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400835 private void showFakeTitleBar() {
Leon Scrogginsfe87bd32009-10-06 10:10:00 -0400836 if (mFakeTitleBar.getParent() == null && mActiveTabsPage == null
Grace Kloba847c25b2010-03-30 16:00:26 -0700837 && !mActivityInPause) {
838 WebView mainView = mTabControl.getCurrentWebView();
839 // if there is no current WebView, don't show the faked title bar;
Grace Kloba65190702010-04-02 23:37:26 -0700840 if (mainView == null) {
Cary Clarka0464552009-09-29 13:00:45 -0400841 return;
842 }
Cary Clark2c326e62010-08-19 18:40:57 -0400843 // Do not need to check for null, since the current tab will have
844 // at least a main WebView, or we would have returned above.
845 if (dialogIsUp()) {
846 // Do not show the fake title bar, which would cover up the
847 // find or select dialog.
848 return;
849 }
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400850
851 WindowManager manager
852 = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
853
854 // Add the title bar to the window manager so it can receive touches
855 // while the menu is up
856 WindowManager.LayoutParams params
857 = new WindowManager.LayoutParams(
Romain Guy15b8ec62010-01-08 15:06:43 -0800858 ViewGroup.LayoutParams.MATCH_PARENT,
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400859 ViewGroup.LayoutParams.WRAP_CONTENT,
Grace Kloba847c25b2010-03-30 16:00:26 -0700860 WindowManager.LayoutParams.TYPE_APPLICATION,
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400861 WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
Leon Scroggins68549862009-09-21 16:02:01 -0400862 PixelFormat.TRANSLUCENT);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400863 params.gravity = Gravity.TOP;
Grace Kloba847c25b2010-03-30 16:00:26 -0700864 boolean atTop = mainView.getScrollY() == 0;
Leon Scroggins83932c72009-09-30 11:55:54 -0400865 params.windowAnimations = atTop ? 0 : R.style.TitleBar;
Grace Kloba13f9ace2010-03-18 21:44:14 -0700866 manager.addView(mFakeTitleBar, params);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400867 }
868 }
869
870 @Override
871 public void onOptionsMenuClosed(Menu menu) {
872 mOptionsMenuOpen = false;
Leon Scrogginsa27ff192009-09-14 12:58:04 -0400873 if (!mInLoad) {
874 hideFakeTitleBar();
875 } else if (!mIconView) {
876 // The page is currently loading, and we are in expanded mode, so
877 // we were not showing the menu. Show it once again. It will be
878 // removed when the page finishes.
879 showFakeTitleBar();
880 }
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400881 }
Grace Kloba22ac16e2009-10-07 18:00:23 -0700882
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400883 private void hideFakeTitleBar() {
Leon Scrogginsfe87bd32009-10-06 10:10:00 -0400884 if (mFakeTitleBar.getParent() == null) return;
Leon Scroggins20329572009-09-23 17:42:41 -0400885 WindowManager.LayoutParams params = (WindowManager.LayoutParams)
Grace Kloba13f9ace2010-03-18 21:44:14 -0700886 mFakeTitleBar.getLayoutParams();
Leon Scroggins20329572009-09-23 17:42:41 -0400887 WebView mainView = mTabControl.getCurrentWebView();
888 // Although we decided whether or not to animate based on the current
889 // scroll position, the scroll position may have changed since the
890 // fake title bar was displayed. Make sure it has the appropriate
891 // animation/lack thereof before removing.
892 params.windowAnimations = mainView != null && mainView.getScrollY() == 0
Leon Scroggins83932c72009-09-30 11:55:54 -0400893 ? 0 : R.style.TitleBar;
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400894 WindowManager manager
895 = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
Grace Kloba13f9ace2010-03-18 21:44:14 -0700896 manager.updateViewLayout(mFakeTitleBar, params);
897 manager.removeView(mFakeTitleBar);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400898 }
899
The Android Open Source Project0c908882009-03-03 19:32:16 -0800900 /**
Leon Scrogginsc6fa1102009-09-21 10:40:01 -0400901 * Special method for the fake title bar to call when displaying its context
902 * menu, since it is in its own Window, and its parent does not show a
903 * context menu.
904 */
905 /* package */ void showTitleBarContextMenu() {
Cary Clark65f4a3c2009-09-28 17:05:06 -0400906 if (null == mTitleBar.getParent()) {
907 return;
908 }
Leon Scrogginsc6fa1102009-09-21 10:40:01 -0400909 openContextMenu(mTitleBar);
910 }
911
Leon Scrogginsb2b19f52009-10-09 16:10:00 -0400912 @Override
913 public void onContextMenuClosed(Menu menu) {
914 super.onContextMenuClosed(menu);
915 if (mInLoad) {
916 showFakeTitleBar();
917 }
918 }
919
Leon Scrogginsc6fa1102009-09-21 10:40:01 -0400920 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -0800921 * onSaveInstanceState(Bundle map)
922 * onSaveInstanceState is called right before onStop(). The map contains
923 * the saved state.
924 */
Grace Kloba22ac16e2009-10-07 18:00:23 -0700925 @Override
926 protected void onSaveInstanceState(Bundle outState) {
Dave Bort31a6d1c2009-04-13 15:56:49 -0700927 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800928 Log.v(LOGTAG, "BrowserActivity.onSaveInstanceState: this=" + this);
929 }
930 // the default implementation requires each view to have an id. As the
931 // browser handles the state itself and it doesn't use id for the views,
932 // don't call the default implementation. Otherwise it will trigger the
933 // warning like this, "couldn't save which view has focus because the
934 // focused view XXX has no id".
935
936 // Save all the tabs
937 mTabControl.saveState(outState);
938 }
939
Grace Kloba22ac16e2009-10-07 18:00:23 -0700940 @Override
941 protected void onPause() {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800942 super.onPause();
943
944 if (mActivityInPause) {
945 Log.e(LOGTAG, "BrowserActivity is already paused.");
946 return;
947 }
948
Mike Reed7bfa63b2009-05-28 11:08:32 -0400949 mTabControl.pauseCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800950 mActivityInPause = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -0400951 if (mTabControl.getCurrentIndex() >= 0 && !pauseWebViewTimers()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800952 mWakeLock.acquire();
953 mHandler.sendMessageDelayed(mHandler
954 .obtainMessage(RELEASE_WAKELOCK), WAKELOCK_TIMEOUT);
955 }
956
Leon Scrogginsa2ab6a72009-09-11 11:49:52 -0400957 // FIXME: This removes the active tabs page and resets the menu to
958 // MAIN_MENU. A better solution might be to do this work in onNewIntent
959 // but then we would need to save it in onSaveInstanceState and restore
960 // it in onCreate/onRestoreInstanceState
961 if (mActiveTabsPage != null) {
962 removeActiveTabPage(true);
963 }
964
The Android Open Source Project0c908882009-03-03 19:32:16 -0800965 cancelStopToast();
966
967 // unregister network state listener
968 unregisterReceiver(mNetworkStateIntentReceiver);
969 WebView.disablePlatformNotifications();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800970 }
971
Grace Kloba22ac16e2009-10-07 18:00:23 -0700972 @Override
973 protected void onDestroy() {
Dave Bort31a6d1c2009-04-13 15:56:49 -0700974 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800975 Log.v(LOGTAG, "BrowserActivity.onDestroy: this=" + this);
976 }
977 super.onDestroy();
Grace Kloba0923d692009-09-23 21:37:25 -0700978
Leon Scroggins8d5fa432009-10-02 15:55:59 -0400979 if (mUploadMessage != null) {
980 mUploadMessage.onReceiveValue(null);
981 mUploadMessage = null;
982 }
983
Grace Kloba0923d692009-09-23 21:37:25 -0700984 if (mTabControl == null) return;
985
Grace Kloba1fc98a32009-10-21 13:23:08 -0700986 // Remove the fake title bar if it is there
987 hideFakeTitleBar();
988
The Android Open Source Project0c908882009-03-03 19:32:16 -0800989 // Remove the current tab and sub window
Grace Kloba22ac16e2009-10-07 18:00:23 -0700990 Tab t = mTabControl.getCurrentTab();
Patrick Scottfb5e77f2009-04-08 19:17:37 -0700991 if (t != null) {
992 dismissSubWindow(t);
993 removeTabFromContentView(t);
994 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800995 // Destroy all the tabs
996 mTabControl.destroy();
997 WebIconDatabase.getInstance().close();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800998
Grace Klobab4da0ad2009-05-14 14:45:40 -0700999 unregisterReceiver(mPackageInstallationReceiver);
Bjorn Bringerta7611812010-03-24 11:12:02 +00001000
1001 // Stop watching the default geolocation permissions
1002 mSystemAllowGeolocationOrigins.stop();
1003 mSystemAllowGeolocationOrigins = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001004 }
1005
1006 @Override
1007 public void onConfigurationChanged(Configuration newConfig) {
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04001008 mConfigChanged = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001009 super.onConfigurationChanged(newConfig);
1010
1011 if (mPageInfoDialog != null) {
1012 mPageInfoDialog.dismiss();
1013 showPageInfo(
1014 mPageInfoView,
Leon Scrogginsc7b92f82010-01-11 18:17:31 -05001015 mPageInfoFromShowSSLCertificateOnError);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001016 }
1017 if (mSSLCertificateDialog != null) {
1018 mSSLCertificateDialog.dismiss();
1019 showSSLCertificate(
1020 mSSLCertificateView);
1021 }
1022 if (mSSLCertificateOnErrorDialog != null) {
1023 mSSLCertificateOnErrorDialog.dismiss();
1024 showSSLCertificateOnError(
1025 mSSLCertificateOnErrorView,
1026 mSSLCertificateOnErrorHandler,
1027 mSSLCertificateOnErrorError);
1028 }
1029 if (mHttpAuthenticationDialog != null) {
1030 String title = ((TextView) mHttpAuthenticationDialog
1031 .findViewById(com.android.internal.R.id.alertTitle)).getText()
1032 .toString();
1033 String name = ((TextView) mHttpAuthenticationDialog
1034 .findViewById(R.id.username_edit)).getText().toString();
1035 String password = ((TextView) mHttpAuthenticationDialog
1036 .findViewById(R.id.password_edit)).getText().toString();
1037 int focusId = mHttpAuthenticationDialog.getCurrentFocus()
1038 .getId();
1039 mHttpAuthenticationDialog.dismiss();
1040 showHttpAuthentication(mHttpAuthHandler, null, null, title,
1041 name, password, focusId);
1042 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001043 }
1044
Grace Kloba22ac16e2009-10-07 18:00:23 -07001045 @Override
1046 public void onLowMemory() {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001047 super.onLowMemory();
1048 mTabControl.freeMemory();
1049 }
1050
Cary Clarkff4d92c2010-03-25 11:17:03 -04001051 private void resumeWebViewTimers() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001052 Tab tab = mTabControl.getCurrentTab();
Cary Clarkff4d92c2010-03-25 11:17:03 -04001053 if (tab == null) return; // monkey can trigger this
Grace Kloba22ac16e2009-10-07 18:00:23 -07001054 boolean inLoad = tab.inLoad();
1055 if ((!mActivityInPause && !inLoad) || (mActivityInPause && inLoad)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001056 CookieSyncManager.getInstance().startSync();
Grace Kloba22ac16e2009-10-07 18:00:23 -07001057 WebView w = tab.getWebView();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001058 if (w != null) {
1059 w.resumeTimers();
1060 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001061 }
1062 }
1063
Mike Reed7bfa63b2009-05-28 11:08:32 -04001064 private boolean pauseWebViewTimers() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001065 Tab tab = mTabControl.getCurrentTab();
1066 boolean inLoad = tab.inLoad();
1067 if (mActivityInPause && !inLoad) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001068 CookieSyncManager.getInstance().stopSync();
1069 WebView w = mTabControl.getCurrentWebView();
1070 if (w != null) {
1071 w.pauseTimers();
1072 }
1073 return true;
1074 } else {
1075 return false;
1076 }
1077 }
1078
The Android Open Source Project0c908882009-03-03 19:32:16 -08001079 // Open the icon database and retain all the icons for visited sites.
1080 private void retainIconsOnStartup() {
1081 final WebIconDatabase db = WebIconDatabase.getInstance();
1082 db.open(getDir("icons", 0).getPath());
Leon Scroggins2c0f6112010-03-12 18:09:39 -05001083 Cursor c = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001084 try {
Leon Scroggins2c0f6112010-03-12 18:09:39 -05001085 c = Browser.getAllBookmarks(mResolver);
1086 if (c.moveToFirst()) {
1087 int urlIndex = c.getColumnIndex(Browser.BookmarkColumns.URL);
1088 do {
1089 String url = c.getString(urlIndex);
1090 db.retainIconForPageUrl(url);
1091 } while (c.moveToNext());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001092 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001093 } catch (IllegalStateException e) {
1094 Log.e(LOGTAG, "retainIconsOnStartup", e);
Leon Scroggins2c0f6112010-03-12 18:09:39 -05001095 } finally {
1096 if (c!= null) c.close();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001097 }
1098 }
1099
1100 // Helper method for getting the top window.
1101 WebView getTopWindow() {
1102 return mTabControl.getCurrentTopWebView();
1103 }
1104
Grace Kloba22ac16e2009-10-07 18:00:23 -07001105 TabControl getTabControl() {
1106 return mTabControl;
1107 }
1108
The Android Open Source Project0c908882009-03-03 19:32:16 -08001109 @Override
1110 public boolean onCreateOptionsMenu(Menu menu) {
1111 super.onCreateOptionsMenu(menu);
1112
1113 MenuInflater inflater = getMenuInflater();
1114 inflater.inflate(R.menu.browser, menu);
1115 mMenu = menu;
1116 updateInLoadMenuItems();
1117 return true;
1118 }
1119
1120 /**
1121 * As the menu can be open when loading state changes
1122 * we must manually update the state of the stop/reload menu
1123 * item
1124 */
1125 private void updateInLoadMenuItems() {
1126 if (mMenu == null) {
1127 return;
1128 }
1129 MenuItem src = mInLoad ?
1130 mMenu.findItem(R.id.stop_menu_id):
1131 mMenu.findItem(R.id.reload_menu_id);
1132 MenuItem dest = mMenu.findItem(R.id.stop_reload_menu_id);
1133 dest.setIcon(src.getIcon());
1134 dest.setTitle(src.getTitle());
1135 }
1136
1137 @Override
1138 public boolean onContextItemSelected(MenuItem item) {
1139 // chording is not an issue with context menus, but we use the same
1140 // options selector, so set mCanChord to true so we can access them.
1141 mCanChord = true;
1142 int id = item.getItemId();
Leon Scroggins96afcb12009-12-10 12:35:56 -05001143 boolean result = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001144 switch (id) {
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001145 // For the context menu from the title bar
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001146 case R.id.title_bar_copy_page_url:
Leon Scroggins96afcb12009-12-10 12:35:56 -05001147 Tab currentTab = mTabControl.getCurrentTab();
1148 if (null == currentTab) {
1149 result = false;
1150 break;
1151 }
1152 WebView mainView = currentTab.getWebView();
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001153 if (null == mainView) {
Leon Scroggins96afcb12009-12-10 12:35:56 -05001154 result = false;
1155 break;
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001156 }
Leon Scroggins96afcb12009-12-10 12:35:56 -05001157 copy(mainView.getUrl());
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001158 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001159 // -- Browser context menu
1160 case R.id.open_context_menu_id:
1161 case R.id.open_newtab_context_menu_id:
1162 case R.id.bookmark_context_menu_id:
1163 case R.id.save_link_context_menu_id:
1164 case R.id.share_link_context_menu_id:
1165 case R.id.copy_link_context_menu_id:
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001166 final WebView webView = getTopWindow();
1167 if (null == webView) {
Leon Scroggins96afcb12009-12-10 12:35:56 -05001168 result = false;
1169 break;
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001170 }
1171 final HashMap hrefMap = new HashMap();
1172 hrefMap.put("webview", webView);
1173 final Message msg = mHandler.obtainMessage(
1174 FOCUS_NODE_HREF, id, 0, hrefMap);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001175 webView.requestFocusNodeHref(msg);
1176 break;
1177
1178 default:
1179 // For other context menus
Leon Scroggins96afcb12009-12-10 12:35:56 -05001180 result = onOptionsItemSelected(item);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001181 }
1182 mCanChord = false;
Leon Scroggins96afcb12009-12-10 12:35:56 -05001183 return result;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001184 }
1185
1186 private Bundle createGoogleSearchSourceBundle(String source) {
1187 Bundle bundle = new Bundle();
Bjorn Bringert10d1cca2010-02-10 14:22:12 +00001188 bundle.putString(Search.SOURCE, source);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001189 return bundle;
1190 }
1191
Leon Scroggins8ad29922010-02-16 12:33:55 -05001192 /* package */ void editUrl() {
Leon Scroggins68579392009-09-15 15:31:54 -04001193 if (mOptionsMenuOpen) closeOptionsMenu();
Leon Scroggins5bbe9802009-07-31 13:10:55 -04001194 String url = (getTopWindow() == null) ? null : getTopWindow().getUrl();
Grace Kloba83f47342009-07-20 10:44:31 -07001195 startSearch(mSettings.getHomePage().equals(url) ? null : url, true,
Leon Scroggins8ad29922010-02-16 12:33:55 -05001196 null, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001197 }
1198
Leon Scroggins8ad29922010-02-16 12:33:55 -05001199 /**
1200 * Overriding this to insert a local information bundle
1201 */
The Android Open Source Project0c908882009-03-03 19:32:16 -08001202 @Override
1203 public void startSearch(String initialQuery, boolean selectInitialQuery,
1204 Bundle appSearchData, boolean globalSearch) {
1205 if (appSearchData == null) {
1206 appSearchData = createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_TYPE);
1207 }
1208 super.startSearch(initialQuery, selectInitialQuery, appSearchData, globalSearch);
1209 }
1210
Leon Scroggins1f005d32009-08-10 17:36:42 -04001211 /**
1212 * Switch tabs. Called by the TitleBarSet when sliding the title bar
1213 * results in changing tabs.
Leon Scroggins160a7e72009-08-14 18:28:01 -04001214 * @param index Index of the tab to change to, as defined by
1215 * mTabControl.getTabIndex(Tab t).
1216 * @return boolean True if we successfully switched to a different tab. If
1217 * the indexth tab is null, or if that tab is the same as
1218 * the current one, return false.
Leon Scroggins1f005d32009-08-10 17:36:42 -04001219 */
Leon Scroggins160a7e72009-08-14 18:28:01 -04001220 /* package */ boolean switchToTab(int index) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001221 Tab tab = mTabControl.getTab(index);
1222 Tab currentTab = mTabControl.getCurrentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04001223 if (tab == null || tab == currentTab) {
Leon Scroggins160a7e72009-08-14 18:28:01 -04001224 return false;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001225 }
1226 if (currentTab != null) {
1227 // currentTab may be null if it was just removed. In that case,
1228 // we do not need to remove it
1229 removeTabFromContentView(currentTab);
1230 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001231 mTabControl.setCurrentTab(tab);
1232 attachTabToContentView(tab);
Grace Klobaeb6eef42009-09-15 17:56:32 -07001233 resetTitleIconAndProgress();
1234 updateLockIconToLatest();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001235 return true;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001236 }
1237
Grace Kloba22ac16e2009-10-07 18:00:23 -07001238 /* package */ Tab openTabToHomePage() {
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001239 return openTabAndShow(mSettings.getHomePage(), false, null);
1240 }
1241
Leon Scroggins1f005d32009-08-10 17:36:42 -04001242 /* package */ void closeCurrentWindow() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001243 final Tab current = mTabControl.getCurrentTab();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001244 if (mTabControl.getTabCount() == 1) {
Leon Scroggins30444232009-09-04 18:36:20 -04001245 // This is the last tab. Open a new one, with the home
1246 // page and close the current one.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001247 openTabToHomePage();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001248 closeTab(current);
Leon Scroggins160a7e72009-08-14 18:28:01 -04001249 return;
1250 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07001251 final Tab parent = current.getParentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04001252 int indexToShow = -1;
1253 if (parent != null) {
1254 indexToShow = mTabControl.getTabIndex(parent);
1255 } else {
Leon Scroggins160a7e72009-08-14 18:28:01 -04001256 final int currentIndex = mTabControl.getCurrentIndex();
1257 // Try to move to the tab to the right
1258 indexToShow = currentIndex + 1;
1259 if (indexToShow > mTabControl.getTabCount() - 1) {
1260 // Try to move to the tab to the left
1261 indexToShow = currentIndex - 1;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001262 }
1263 }
Leon Scroggins160a7e72009-08-14 18:28:01 -04001264 if (switchToTab(indexToShow)) {
1265 // Close window
1266 closeTab(current);
1267 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001268 }
1269
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001270 private ActiveTabsPage mActiveTabsPage;
1271
1272 /**
1273 * Remove the active tabs page.
1274 * @param needToAttach If true, the active tabs page did not attach a tab
1275 * to the content view, so we need to do that here.
1276 */
1277 /* package */ void removeActiveTabPage(boolean needToAttach) {
1278 mContentView.removeView(mActiveTabsPage);
1279 mActiveTabsPage = null;
1280 mMenuState = R.id.MAIN_MENU;
1281 if (needToAttach) {
1282 attachTabToContentView(mTabControl.getCurrentTab());
1283 }
1284 getTopWindow().requestFocus();
1285 }
1286
Cary Clark2c326e62010-08-19 18:40:57 -04001287 private WebView showDialog(WebDialog dialog) {
1288 // Need to do something special for Tablet
1289 Tab tab = mTabControl.getCurrentTab();
1290 if (tab.getSubWebView() == null) {
1291 // If the find or select is being performed on the main webview,
1292 // remove the embedded title bar.
1293 WebView mainView = tab.getWebView();
1294 if (mainView != null) {
1295 mainView.setEmbeddedTitleBar(null);
1296 }
1297 }
1298 hideFakeTitleBar();
1299 mMenuState = EMPTY_MENU;
1300 return tab.showDialog(dialog);
1301 }
1302
The Android Open Source Project0c908882009-03-03 19:32:16 -08001303 @Override
1304 public boolean onOptionsItemSelected(MenuItem item) {
1305 if (!mCanChord) {
1306 // The user has already fired a shortcut with this hold down of the
1307 // menu key.
1308 return false;
1309 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001310 if (null == getTopWindow()) {
Leon Scroggins0d7ae0e2009-06-05 11:04:45 -04001311 return false;
1312 }
Grace Kloba6ee9c492009-07-13 10:04:34 -07001313 if (mMenuIsDown) {
1314 // The shortcut action consumes the MENU. Even if it is still down,
1315 // it won't trigger the next shortcut action. In the case of the
1316 // shortcut action triggering a new activity, like Bookmarks, we
1317 // won't get onKeyUp for MENU. So it is important to reset it here.
1318 mMenuIsDown = false;
1319 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001320 switch (item.getItemId()) {
1321 // -- Main menu
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001322 case R.id.new_tab_menu_id:
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001323 openTabToHomePage();
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001324 break;
1325
Leon Scroggins64b80f32009-08-07 12:03:34 -04001326 case R.id.goto_menu_id:
Leon Scroggins8ad29922010-02-16 12:33:55 -05001327 editUrl();
Leon Scrogginsb3a5bed2009-09-28 11:21:56 -04001328 break;
1329
1330 case R.id.bookmarks_menu_id:
Leon Scroggins30444232009-09-04 18:36:20 -04001331 bookmarksOrHistoryPicker(false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001332 break;
1333
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001334 case R.id.active_tabs_menu_id:
1335 mActiveTabsPage = new ActiveTabsPage(this, mTabControl);
1336 removeTabFromContentView(mTabControl.getCurrentTab());
Leon Scroggins43de6162009-09-14 19:59:58 -04001337 hideFakeTitleBar();
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001338 mContentView.addView(mActiveTabsPage, COVER_SCREEN_PARAMS);
1339 mActiveTabsPage.requestFocus();
1340 mMenuState = EMPTY_MENU;
1341 break;
1342
Leon Scroggins1f005d32009-08-10 17:36:42 -04001343 case R.id.add_bookmark_menu_id:
1344 Intent i = new Intent(BrowserActivity.this,
1345 AddBookmarkPage.class);
1346 WebView w = getTopWindow();
1347 i.putExtra("url", w.getUrl());
1348 i.putExtra("title", w.getTitle());
Grace Kloba83cdb2c2009-09-16 00:48:57 -07001349 i.putExtra("touch_icon_url", w.getTouchIconUrl());
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01001350 i.putExtra("thumbnail", createScreenshot(w));
Leon Scroggins1f005d32009-08-10 17:36:42 -04001351 startActivity(i);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001352 break;
1353
1354 case R.id.stop_reload_menu_id:
1355 if (mInLoad) {
1356 stopLoading();
1357 } else {
1358 getTopWindow().reload();
1359 }
1360 break;
1361
1362 case R.id.back_menu_id:
1363 getTopWindow().goBack();
1364 break;
1365
1366 case R.id.forward_menu_id:
1367 getTopWindow().goForward();
1368 break;
1369
1370 case R.id.close_menu_id:
1371 // Close the subwindow if it exists.
1372 if (mTabControl.getCurrentSubWindow() != null) {
1373 dismissSubWindow(mTabControl.getCurrentTab());
1374 break;
1375 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001376 closeCurrentWindow();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001377 break;
1378
1379 case R.id.homepage_menu_id:
Grace Kloba22ac16e2009-10-07 18:00:23 -07001380 Tab current = mTabControl.getCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001381 if (current != null) {
1382 dismissSubWindow(current);
Leon Scroggins92472e82010-02-17 16:32:28 -05001383 loadUrl(current.getWebView(), mSettings.getHomePage());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001384 }
1385 break;
1386
1387 case R.id.preferences_menu_id:
1388 Intent intent = new Intent(this,
1389 BrowserPreferencesPage.class);
Leon Scrogginsd5304942009-12-10 16:11:39 -05001390 intent.putExtra(BrowserPreferencesPage.CURRENT_PAGE,
1391 getTopWindow().getUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001392 startActivityForResult(intent, PREFERENCES_PAGE);
1393 break;
1394
1395 case R.id.find_menu_id:
Cary Clark2c326e62010-08-19 18:40:57 -04001396 showFindDialog();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001397 break;
1398
1399 case R.id.select_text_id:
Cary Clark2c326e62010-08-19 18:40:57 -04001400 showSelectDialog();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001401 break;
Cary Clark2c326e62010-08-19 18:40:57 -04001402
The Android Open Source Project0c908882009-03-03 19:32:16 -08001403 case R.id.page_info_menu_id:
1404 showPageInfo(mTabControl.getCurrentTab(), false);
1405 break;
1406
1407 case R.id.classic_history_menu_id:
Leon Scroggins30444232009-09-04 18:36:20 -04001408 bookmarksOrHistoryPicker(true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001409 break;
1410
Leon Scroggins96afcb12009-12-10 12:35:56 -05001411 case R.id.title_bar_share_page_url:
The Android Open Source Project0c908882009-03-03 19:32:16 -08001412 case R.id.share_page_menu_id:
Leon Scroggins96afcb12009-12-10 12:35:56 -05001413 Tab currentTab = mTabControl.getCurrentTab();
1414 if (null == currentTab) {
1415 mCanChord = false;
1416 return false;
1417 }
1418 currentTab.populatePickerData();
1419 sharePage(this, currentTab.getTitle(),
1420 currentTab.getUrl(), currentTab.getFavicon(),
1421 createScreenshot(currentTab.getWebView()));
The Android Open Source Project0c908882009-03-03 19:32:16 -08001422 break;
1423
1424 case R.id.dump_nav_menu_id:
1425 getTopWindow().debugDump();
1426 break;
1427
Andrei Popescu7a8b88b2010-02-02 00:30:38 +00001428 case R.id.dump_counters_menu_id:
1429 getTopWindow().dumpV8Counters();
1430 break;
1431
The Android Open Source Project0c908882009-03-03 19:32:16 -08001432 case R.id.zoom_in_menu_id:
1433 getTopWindow().zoomIn();
1434 break;
1435
1436 case R.id.zoom_out_menu_id:
1437 getTopWindow().zoomOut();
1438 break;
1439
1440 case R.id.view_downloads_menu_id:
1441 viewDownloads(null);
1442 break;
1443
The Android Open Source Project0c908882009-03-03 19:32:16 -08001444 case R.id.window_one_menu_id:
1445 case R.id.window_two_menu_id:
1446 case R.id.window_three_menu_id:
1447 case R.id.window_four_menu_id:
1448 case R.id.window_five_menu_id:
1449 case R.id.window_six_menu_id:
1450 case R.id.window_seven_menu_id:
1451 case R.id.window_eight_menu_id:
1452 {
1453 int menuid = item.getItemId();
1454 for (int id = 0; id < WINDOW_SHORTCUT_ID_ARRAY.length; id++) {
1455 if (WINDOW_SHORTCUT_ID_ARRAY[id] == menuid) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001456 Tab desiredTab = mTabControl.getTab(id);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001457 if (desiredTab != null &&
1458 desiredTab != mTabControl.getCurrentTab()) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001459 switchToTab(id);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001460 }
1461 break;
1462 }
1463 }
1464 }
1465 break;
1466
1467 default:
1468 if (!super.onOptionsItemSelected(item)) {
1469 return false;
1470 }
1471 // Otherwise fall through.
1472 }
1473 mCanChord = false;
1474 return true;
1475 }
1476
Cary Clark2c326e62010-08-19 18:40:57 -04001477 private boolean dialogIsUp() {
1478 return null != mFindDialog && mFindDialog.isVisible() ||
1479 null != mSelectDialog && mSelectDialog.isVisible();
1480 }
1481
1482 private boolean closeDialog(WebDialog dialog) {
1483 if (null == dialog || !dialog.isVisible()) return false;
1484 Tab currentTab = mTabControl.getCurrentTab();
1485 currentTab.closeDialog(dialog);
1486 dialog.dismiss();
1487 return true;
1488 }
1489
1490 /*
1491 * Remove the find dialog or select dialog.
1492 */
1493 public void closeDialogs() {
1494 if (!(closeDialog(mFindDialog) || closeDialog(mSelectDialog))) return;
1495 // If the Find was being performed in the main WebView, replace the
1496 // embedded title bar.
1497 Tab currentTab = mTabControl.getCurrentTab();
1498 if (currentTab.getSubWebView() == null) {
1499 WebView mainView = currentTab.getWebView();
1500 if (mainView != null) {
1501 mainView.setEmbeddedTitleBar(mTitleBar);
1502 }
1503 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001504 mMenuState = R.id.MAIN_MENU;
Cary Clark2c326e62010-08-19 18:40:57 -04001505 if (mInLoad) {
1506 // The title bar was hidden, because otherwise it would cover up the
1507 // find or select dialog. Now that the dialog has been removed,
1508 // show the fake title bar once again.
1509 showFakeTitleBar();
1510 }
1511 }
1512
1513 public void showFindDialog() {
1514 if (null == mFindDialog) {
1515 mFindDialog = new FindDialog(this);
1516 }
1517 showDialog(mFindDialog).setFindIsUp(true);
1518 }
1519
1520 public void setFindDialogText(String text) {
1521 mFindDialog.setText(text);
1522 }
1523
1524 public void showSelectDialog() {
1525 if (null == mSelectDialog) {
1526 mSelectDialog = new SelectDialog(this);
1527 }
1528 showDialog(mSelectDialog).setUpSelect();
1529 mSelectDialog.hideSoftInput();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001530 }
1531
Grace Kloba22ac16e2009-10-07 18:00:23 -07001532 @Override
1533 public boolean onPrepareOptionsMenu(Menu menu) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001534 // This happens when the user begins to hold down the menu key, so
1535 // allow them to chord to get a shortcut.
1536 mCanChord = true;
1537 // Note: setVisible will decide whether an item is visible; while
1538 // setEnabled() will decide whether an item is enabled, which also means
1539 // whether the matching shortcut key will function.
1540 super.onPrepareOptionsMenu(menu);
1541 switch (mMenuState) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001542 case EMPTY_MENU:
1543 if (mCurrentMenuState != mMenuState) {
1544 menu.setGroupVisible(R.id.MAIN_MENU, false);
1545 menu.setGroupEnabled(R.id.MAIN_MENU, false);
1546 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001547 }
1548 break;
1549 default:
1550 if (mCurrentMenuState != mMenuState) {
1551 menu.setGroupVisible(R.id.MAIN_MENU, true);
1552 menu.setGroupEnabled(R.id.MAIN_MENU, true);
1553 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001554 }
1555 final WebView w = getTopWindow();
1556 boolean canGoBack = false;
1557 boolean canGoForward = false;
1558 boolean isHome = false;
1559 if (w != null) {
1560 canGoBack = w.canGoBack();
1561 canGoForward = w.canGoForward();
1562 isHome = mSettings.getHomePage().equals(w.getUrl());
1563 }
1564 final MenuItem back = menu.findItem(R.id.back_menu_id);
1565 back.setEnabled(canGoBack);
1566
1567 final MenuItem home = menu.findItem(R.id.homepage_menu_id);
1568 home.setEnabled(!isHome);
1569
1570 menu.findItem(R.id.forward_menu_id)
1571 .setEnabled(canGoForward);
1572
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001573 menu.findItem(R.id.new_tab_menu_id).setEnabled(
Grace Kloba22ac16e2009-10-07 18:00:23 -07001574 mTabControl.canCreateNewTab());
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001575
The Android Open Source Project0c908882009-03-03 19:32:16 -08001576 // decide whether to show the share link option
1577 PackageManager pm = getPackageManager();
1578 Intent send = new Intent(Intent.ACTION_SEND);
1579 send.setType("text/plain");
1580 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1581 menu.findItem(R.id.share_page_menu_id).setVisible(ri != null);
1582
The Android Open Source Project0c908882009-03-03 19:32:16 -08001583 boolean isNavDump = mSettings.isNavDump();
1584 final MenuItem nav = menu.findItem(R.id.dump_nav_menu_id);
1585 nav.setVisible(isNavDump);
1586 nav.setEnabled(isNavDump);
Andrei Popescu7a8b88b2010-02-02 00:30:38 +00001587
1588 boolean showDebugSettings = mSettings.showDebugSettings();
1589 final MenuItem counter = menu.findItem(R.id.dump_counters_menu_id);
1590 counter.setVisible(showDebugSettings);
1591 counter.setEnabled(showDebugSettings);
1592
The Android Open Source Project0c908882009-03-03 19:32:16 -08001593 break;
1594 }
1595 mCurrentMenuState = mMenuState;
1596 return true;
1597 }
1598
1599 @Override
1600 public void onCreateContextMenu(ContextMenu menu, View v,
1601 ContextMenuInfo menuInfo) {
Leon Scroggins4e9f89b2010-02-22 16:54:14 -05001602 if (v instanceof TitleBar) {
1603 return;
1604 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001605 WebView webview = (WebView) v;
1606 WebView.HitTestResult result = webview.getHitTestResult();
1607 if (result == null) {
1608 return;
1609 }
1610
1611 int type = result.getType();
1612 if (type == WebView.HitTestResult.UNKNOWN_TYPE) {
1613 Log.w(LOGTAG,
1614 "We should not show context menu when nothing is touched");
1615 return;
1616 }
1617 if (type == WebView.HitTestResult.EDIT_TEXT_TYPE) {
1618 // let TextView handles context menu
1619 return;
1620 }
1621
1622 // Note, http://b/issue?id=1106666 is requesting that
1623 // an inflated menu can be used again. This is not available
1624 // yet, so inflate each time (yuk!)
1625 MenuInflater inflater = getMenuInflater();
1626 inflater.inflate(R.menu.browsercontext, menu);
1627
1628 // Show the correct menu group
1629 String extra = result.getExtra();
1630 menu.setGroupVisible(R.id.PHONE_MENU,
1631 type == WebView.HitTestResult.PHONE_TYPE);
1632 menu.setGroupVisible(R.id.EMAIL_MENU,
1633 type == WebView.HitTestResult.EMAIL_TYPE);
1634 menu.setGroupVisible(R.id.GEO_MENU,
1635 type == WebView.HitTestResult.GEO_TYPE);
1636 menu.setGroupVisible(R.id.IMAGE_MENU,
1637 type == WebView.HitTestResult.IMAGE_TYPE
1638 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1639 menu.setGroupVisible(R.id.ANCHOR_MENU,
1640 type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1641 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1642
1643 // Setup custom handling depending on the type
1644 switch (type) {
1645 case WebView.HitTestResult.PHONE_TYPE:
1646 menu.setHeaderTitle(Uri.decode(extra));
1647 menu.findItem(R.id.dial_context_menu_id).setIntent(
1648 new Intent(Intent.ACTION_VIEW, Uri
1649 .parse(WebView.SCHEME_TEL + extra)));
1650 Intent addIntent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
1651 addIntent.putExtra(Insert.PHONE, Uri.decode(extra));
Cary Clark5e335a32009-09-22 14:53:11 -04001652 addIntent.setType(ContactsContract.Contacts.CONTENT_ITEM_TYPE);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001653 menu.findItem(R.id.add_contact_context_menu_id).setIntent(
1654 addIntent);
1655 menu.findItem(R.id.copy_phone_context_menu_id).setOnMenuItemClickListener(
1656 new Copy(extra));
1657 break;
1658
1659 case WebView.HitTestResult.EMAIL_TYPE:
1660 menu.setHeaderTitle(extra);
1661 menu.findItem(R.id.email_context_menu_id).setIntent(
1662 new Intent(Intent.ACTION_VIEW, Uri
1663 .parse(WebView.SCHEME_MAILTO + extra)));
1664 menu.findItem(R.id.copy_mail_context_menu_id).setOnMenuItemClickListener(
1665 new Copy(extra));
1666 break;
1667
1668 case WebView.HitTestResult.GEO_TYPE:
1669 menu.setHeaderTitle(extra);
1670 menu.findItem(R.id.map_context_menu_id).setIntent(
1671 new Intent(Intent.ACTION_VIEW, Uri
1672 .parse(WebView.SCHEME_GEO
1673 + URLEncoder.encode(extra))));
1674 menu.findItem(R.id.copy_geo_context_menu_id).setOnMenuItemClickListener(
1675 new Copy(extra));
1676 break;
1677
1678 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1679 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
1680 TextView titleView = (TextView) LayoutInflater.from(this)
1681 .inflate(android.R.layout.browser_link_context_header,
1682 null);
1683 titleView.setText(extra);
1684 menu.setHeaderView(titleView);
1685 // decide whether to show the open link in new tab option
1686 menu.findItem(R.id.open_newtab_context_menu_id).setVisible(
Grace Kloba22ac16e2009-10-07 18:00:23 -07001687 mTabControl.canCreateNewTab());
Ben Murdochde353622009-10-12 10:29:00 +01001688 menu.findItem(R.id.bookmark_context_menu_id).setVisible(
1689 Bookmarks.urlHasAcceptableScheme(extra));
The Android Open Source Project0c908882009-03-03 19:32:16 -08001690 PackageManager pm = getPackageManager();
1691 Intent send = new Intent(Intent.ACTION_SEND);
1692 send.setType("text/plain");
1693 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1694 menu.findItem(R.id.share_link_context_menu_id).setVisible(ri != null);
1695 if (type == WebView.HitTestResult.SRC_ANCHOR_TYPE) {
1696 break;
1697 }
1698 // otherwise fall through to handle image part
1699 case WebView.HitTestResult.IMAGE_TYPE:
1700 if (type == WebView.HitTestResult.IMAGE_TYPE) {
1701 menu.setHeaderTitle(extra);
1702 }
1703 menu.findItem(R.id.view_image_context_menu_id).setIntent(
1704 new Intent(Intent.ACTION_VIEW, Uri.parse(extra)));
1705 menu.findItem(R.id.download_context_menu_id).
1706 setOnMenuItemClickListener(new Download(extra));
Ben Murdoch4f75ba22009-10-27 11:48:28 +00001707 menu.findItem(R.id.set_wallpaper_context_menu_id).
1708 setOnMenuItemClickListener(new SetAsWallpaper(extra));
The Android Open Source Project0c908882009-03-03 19:32:16 -08001709 break;
1710
1711 default:
1712 Log.w(LOGTAG, "We should not get here.");
1713 break;
1714 }
Leon Scrogginsb2b19f52009-10-09 16:10:00 -04001715 hideFakeTitleBar();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001716 }
1717
The Android Open Source Project0c908882009-03-03 19:32:16 -08001718 // Attach the given tab to the content view.
Grace Klobac928c302009-09-17 11:51:21 -07001719 // this should only be called for the current tab.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001720 private void attachTabToContentView(Tab t) {
Steve Block2bc69912009-07-30 14:45:13 +01001721 // Attach the container that contains the main WebView and any other UI
1722 // associated with the tab.
Patrick Scottd0119532009-09-17 08:00:31 -04001723 t.attachTabToContentView(mContentView);
Ben Murdochbff2d602009-07-01 20:19:05 +01001724
1725 if (mShouldShowErrorConsole) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001726 ErrorConsoleView errorConsole = t.getErrorConsole(true);
Ben Murdochbff2d602009-07-01 20:19:05 +01001727 if (errorConsole.numberOfErrors() == 0) {
1728 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
1729 } else {
1730 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
1731 }
1732
1733 mErrorConsoleContainer.addView(errorConsole,
Romain Guy15b8ec62010-01-08 15:06:43 -08001734 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
Ben Murdochbff2d602009-07-01 20:19:05 +01001735 ViewGroup.LayoutParams.WRAP_CONTENT));
1736 }
1737
Leon Scroggins39ab28e2009-09-02 21:20:30 -04001738 WebView view = t.getWebView();
Leon Scroggins55a5bc22009-09-04 17:00:08 -04001739 view.setEmbeddedTitleBar(mTitleBar);
Leon Scroggins58d56c62010-01-28 15:12:40 -05001740 if (t.isInVoiceSearchMode()) {
1741 showVoiceTitleBar(t.getVoiceDisplayTitle());
1742 } else {
1743 revertVoiceTitleBar();
1744 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001745 // Request focus on the top window.
1746 t.getTopWindow().requestFocus();
1747 }
1748
1749 // Attach a sub window to the main WebView of the given tab.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001750 void attachSubWindow(Tab t) {
Patrick Scottd0119532009-09-17 08:00:31 -04001751 t.attachSubWindow(mContentView);
1752 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001753 }
1754
1755 // Remove the given tab from the content view.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001756 private void removeTabFromContentView(Tab t) {
Steve Block2bc69912009-07-30 14:45:13 +01001757 // Remove the container that contains the main WebView.
Patrick Scottd0119532009-09-17 08:00:31 -04001758 t.removeTabFromContentView(mContentView);
Ben Murdochbff2d602009-07-01 20:19:05 +01001759
Grace Kloba22ac16e2009-10-07 18:00:23 -07001760 ErrorConsoleView errorConsole = t.getErrorConsole(false);
1761 if (errorConsole != null) {
1762 mErrorConsoleContainer.removeView(errorConsole);
Ben Murdochbff2d602009-07-01 20:19:05 +01001763 }
1764
Leon Scroggins39ab28e2009-09-02 21:20:30 -04001765 WebView view = t.getWebView();
Leon Scrogginsbb85b902009-09-14 19:27:20 -04001766 if (view != null) {
1767 view.setEmbeddedTitleBar(null);
1768 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001769 }
1770
1771 // Remove the sub window if it exists. Also called by TabControl when the
1772 // user clicks the 'X' to dismiss a sub window.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001773 /* package */ void dismissSubWindow(Tab t) {
Patrick Scottd0119532009-09-17 08:00:31 -04001774 t.removeSubWindow(mContentView);
Grace Kloba22ac16e2009-10-07 18:00:23 -07001775 // dismiss the subwindow. This will destroy the WebView.
1776 t.dismissSubWindow();
Patrick Scottd0119532009-09-17 08:00:31 -04001777 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001778 }
1779
Leon Scroggins1f005d32009-08-10 17:36:42 -04001780 // A wrapper function of {@link #openTabAndShow(UrlData, boolean, String)}
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07001781 // that accepts url as string.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001782 private Tab openTabAndShow(String url, boolean closeOnExit, String appId) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001783 return openTabAndShow(new UrlData(url), closeOnExit, appId);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001784 }
1785
1786 // This method does a ton of stuff. It will attempt to create a new tab
1787 // if we haven't reached MAX_TABS. Otherwise it uses the current tab. If
Leon Scroggins1f005d32009-08-10 17:36:42 -04001788 // url isn't null, it will load the given url.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001789 /* package */Tab openTabAndShow(UrlData urlData, boolean closeOnExit,
1790 String appId) {
1791 final Tab currentTab = mTabControl.getCurrentTab();
1792 if (mTabControl.canCreateNewTab()) {
1793 final Tab tab = mTabControl.createNewTab(closeOnExit, appId,
1794 urlData.mUrl);
Leon Scroggins1f005d32009-08-10 17:36:42 -04001795 WebView webview = tab.getWebView();
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001796 // If the last tab was removed from the active tabs page, currentTab
1797 // will be null.
1798 if (currentTab != null) {
1799 removeTabFromContentView(currentTab);
1800 }
Patrick Scott8bbd69f2009-08-14 13:35:53 -04001801 // We must set the new tab as the current tab to reflect the old
1802 // animation behavior.
1803 mTabControl.setCurrentTab(tab);
Grace Klobaeb6eef42009-09-15 17:56:32 -07001804 attachTabToContentView(tab);
Leon Scroggins160a7e72009-08-14 18:28:01 -04001805 if (!urlData.isEmpty()) {
Patrick Scott9d53da02010-02-19 10:19:01 -05001806 loadUrlDataIn(tab, urlData);
Leon Scroggins1f005d32009-08-10 17:36:42 -04001807 }
1808 return tab;
1809 } else {
1810 // Get rid of the subwindow if it exists
1811 dismissSubWindow(currentTab);
1812 if (!urlData.isEmpty()) {
1813 // Load the given url.
Patrick Scott9d53da02010-02-19 10:19:01 -05001814 loadUrlDataIn(currentTab, urlData);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001815 }
Leon Scroggins58d56c62010-01-28 15:12:40 -05001816 return currentTab;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001817 }
1818 }
1819
Grace Kloba22ac16e2009-10-07 18:00:23 -07001820 private Tab openTab(String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001821 if (mSettings.openInBackground()) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001822 Tab t = mTabControl.createNewTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001823 if (t != null) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001824 WebView view = t.getWebView();
Leon Scroggins92472e82010-02-17 16:32:28 -05001825 loadUrl(view, url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001826 }
Grace Klobac9181842009-04-14 08:53:22 -07001827 return t;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001828 } else {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001829 return openTabAndShow(url, false, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001830 }
1831 }
1832
1833 private class Copy implements OnMenuItemClickListener {
1834 private CharSequence mText;
1835
1836 public boolean onMenuItemClick(MenuItem item) {
1837 copy(mText);
1838 return true;
1839 }
1840
1841 public Copy(CharSequence toCopy) {
1842 mText = toCopy;
1843 }
1844 }
1845
1846 private class Download implements OnMenuItemClickListener {
1847 private String mText;
1848
1849 public boolean onMenuItemClick(MenuItem item) {
1850 onDownloadStartNoStream(mText, null, null, null, -1);
1851 return true;
1852 }
1853
1854 public Download(String toDownload) {
1855 mText = toDownload;
1856 }
1857 }
1858
Ben Murdoch4f75ba22009-10-27 11:48:28 +00001859 private class SetAsWallpaper extends Thread implements
1860 OnMenuItemClickListener, DialogInterface.OnCancelListener {
1861 private URL mUrl;
1862 private ProgressDialog mWallpaperProgress;
1863 private boolean mCanceled = false;
1864
1865 public SetAsWallpaper(String url) {
1866 try {
1867 mUrl = new URL(url);
1868 } catch (MalformedURLException e) {
1869 mUrl = null;
1870 }
1871 }
1872
1873 public void onCancel(DialogInterface dialog) {
1874 mCanceled = true;
1875 }
1876
1877 public boolean onMenuItemClick(MenuItem item) {
1878 if (mUrl != null) {
1879 // The user may have tried to set a image with a large file size as their
1880 // background so it may take a few moments to perform the operation. Display
1881 // a progress spinner while it is working.
1882 mWallpaperProgress = new ProgressDialog(BrowserActivity.this);
1883 mWallpaperProgress.setIndeterminate(true);
1884 mWallpaperProgress.setMessage(getText(R.string.progress_dialog_setting_wallpaper));
1885 mWallpaperProgress.setCancelable(true);
1886 mWallpaperProgress.setOnCancelListener(this);
1887 mWallpaperProgress.show();
1888 start();
1889 }
1890 return true;
1891 }
1892
1893 public void run() {
1894 Drawable oldWallpaper = BrowserActivity.this.getWallpaper();
1895 try {
1896 // TODO: This will cause the resource to be downloaded again, when we
1897 // should in most cases be able to grab it from the cache. To fix this
1898 // we should query WebCore to see if we can access a cached version and
1899 // instead open an input stream on that. This pattern could also be used
1900 // in the download manager where the same problem exists.
1901 InputStream inputstream = mUrl.openStream();
1902 if (inputstream != null) {
1903 setWallpaper(inputstream);
1904 }
1905 } catch (IOException e) {
1906 Log.e(LOGTAG, "Unable to set new wallpaper");
1907 // Act as though the user canceled the operation so we try to
1908 // restore the old wallpaper.
1909 mCanceled = true;
1910 }
1911
1912 if (mCanceled) {
1913 // Restore the old wallpaper if the user cancelled whilst we were setting
1914 // the new wallpaper.
1915 int width = oldWallpaper.getIntrinsicWidth();
1916 int height = oldWallpaper.getIntrinsicHeight();
1917 Bitmap bm = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
1918 Canvas canvas = new Canvas(bm);
1919 oldWallpaper.setBounds(0, 0, width, height);
1920 oldWallpaper.draw(canvas);
1921 try {
1922 setWallpaper(bm);
1923 } catch (IOException e) {
1924 Log.e(LOGTAG, "Unable to restore old wallpaper.");
1925 }
1926 mCanceled = false;
1927 }
1928
1929 if (mWallpaperProgress.isShowing()) {
1930 mWallpaperProgress.dismiss();
1931 }
1932 }
1933 }
1934
The Android Open Source Project0c908882009-03-03 19:32:16 -08001935 private void copy(CharSequence text) {
1936 try {
1937 IClipboard clip = IClipboard.Stub.asInterface(ServiceManager.getService("clipboard"));
1938 if (clip != null) {
1939 clip.setClipboardText(text);
1940 }
1941 } catch (android.os.RemoteException e) {
1942 Log.e(LOGTAG, "Copy failed", e);
1943 }
1944 }
1945
1946 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08001947 * Resets the browser title-view to whatever it must be
1948 * (for example, if we had a loading error)
1949 * When we have a new page, we call resetTitle, when we
1950 * have to reset the titlebar to whatever it used to be
1951 * (for example, if the user chose to stop loading), we
1952 * call resetTitleAndRevertLockIcon.
1953 */
1954 /* package */ void resetTitleAndRevertLockIcon() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001955 mTabControl.getCurrentTab().revertLockIcon();
1956 updateLockIconToLatest();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001957 resetTitleIconAndProgress();
1958 }
1959
1960 /**
1961 * Reset the title, favicon, and progress.
1962 */
1963 private void resetTitleIconAndProgress() {
1964 WebView current = mTabControl.getCurrentWebView();
1965 if (current == null) {
1966 return;
1967 }
1968 resetTitleAndIcon(current);
1969 int progress = current.getProgress();
Grace Kloba22ac16e2009-10-07 18:00:23 -07001970 current.getWebChromeClient().onProgressChanged(current, progress);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001971 }
1972
1973 // Reset the title and the icon based on the given item.
1974 private void resetTitleAndIcon(WebView view) {
1975 WebHistoryItem item = view.copyBackForwardList().getCurrentItem();
1976 if (item != null) {
Leon Scroggins68579392009-09-15 15:31:54 -04001977 setUrlTitle(item.getUrl(), item.getTitle());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001978 setFavicon(item.getFavicon());
1979 } else {
Leon Scroggins68579392009-09-15 15:31:54 -04001980 setUrlTitle(null, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001981 setFavicon(null);
1982 }
1983 }
1984
1985 /**
1986 * Sets a title composed of the URL and the title string.
1987 * @param url The URL of the site being loaded.
1988 * @param title The title of the site being loaded.
1989 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07001990 void setUrlTitle(String url, String title) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001991 mUrl = url;
1992 mTitle = title;
1993
Leon Scroggins58d56c62010-01-28 15:12:40 -05001994 // If we are in voice search mode, the title has already been set.
1995 if (mTabControl.getCurrentTab().isInVoiceSearchMode()) return;
1996 mTitleBar.setDisplayTitle(url);
1997 mFakeTitleBar.setDisplayTitle(url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001998 }
1999
2000 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08002001 * @param url The URL to build a title version of the URL from.
2002 * @return The title version of the URL or null if fails.
2003 * The title version of the URL can be either the URL hostname,
2004 * or the hostname with an "https://" prefix (for secure URLs),
2005 * or an empty string if, for example, the URL in question is a
2006 * file:// URL with no hostname.
2007 */
Leon Scroggins32e14a62009-06-11 10:26:34 -04002008 /* package */ static String buildTitleUrl(String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002009 String titleUrl = null;
2010
2011 if (url != null) {
2012 try {
2013 // parse the url string
2014 URL urlObj = new URL(url);
2015 if (urlObj != null) {
2016 titleUrl = "";
2017
2018 String protocol = urlObj.getProtocol();
2019 String host = urlObj.getHost();
2020
2021 if (host != null && 0 < host.length()) {
2022 titleUrl = host;
2023 if (protocol != null) {
2024 // if a secure site, add an "https://" prefix!
2025 if (protocol.equalsIgnoreCase("https")) {
2026 titleUrl = protocol + "://" + host;
2027 }
2028 }
2029 }
2030 }
2031 } catch (MalformedURLException e) {}
2032 }
2033
2034 return titleUrl;
2035 }
2036
2037 // Set the favicon in the title bar.
Grace Kloba22ac16e2009-10-07 18:00:23 -07002038 void setFavicon(Bitmap icon) {
Leon Scroggins68579392009-09-15 15:31:54 -04002039 mTitleBar.setFavicon(icon);
Leon Scrogginsfe87bd32009-10-06 10:10:00 -04002040 mFakeTitleBar.setFavicon(icon);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002041 }
2042
2043 /**
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002044 * Close the tab, remove its associated title bar, and adjust mTabControl's
2045 * current tab to a valid value.
Leon Scroggins1f005d32009-08-10 17:36:42 -04002046 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07002047 /* package */ void closeTab(Tab t) {
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002048 int currentIndex = mTabControl.getCurrentIndex();
2049 int removeIndex = mTabControl.getTabIndex(t);
Leon Scroggins1f005d32009-08-10 17:36:42 -04002050 mTabControl.removeTab(t);
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002051 if (currentIndex >= removeIndex && currentIndex != 0) {
2052 currentIndex--;
2053 }
2054 mTabControl.setCurrentTab(mTabControl.getTab(currentIndex));
Andrei Popescua5bf1de2009-09-23 16:39:23 +01002055 resetTitleIconAndProgress();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002056 }
2057
Leon Scrogginsdcc5eeb2010-02-23 17:26:37 -05002058 /* package */ void goBackOnePageOrQuit() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002059 Tab current = mTabControl.getCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002060 if (current == null) {
2061 /*
2062 * Instead of finishing the activity, simply push this to the back
2063 * of the stack and let ActivityManager to choose the foreground
2064 * activity. As BrowserActivity is singleTask, it will be always the
2065 * root of the task. So we can use either true or false for
2066 * moveTaskToBack().
2067 */
2068 moveTaskToBack(true);
Grace Kloba00d85e72009-09-23 18:50:05 -07002069 return;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002070 }
2071 WebView w = current.getWebView();
2072 if (w.canGoBack()) {
2073 w.goBack();
2074 } else {
2075 // Check to see if we are closing a window that was created by
2076 // another window. If so, we switch back to that window.
Grace Kloba22ac16e2009-10-07 18:00:23 -07002077 Tab parent = current.getParentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002078 if (parent != null) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04002079 switchToTab(mTabControl.getTabIndex(parent));
2080 // Now we close the other tab
2081 closeTab(current);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002082 } else {
2083 if (current.closeOnExit()) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002084 // force the tab's inLoad() to be false as we are going to
2085 // either finish the activity or remove the tab. This will
2086 // ensure pauseWebViewTimers() taking action.
2087 mTabControl.getCurrentTab().clearInLoad();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002088 if (mTabControl.getTabCount() == 1) {
2089 finish();
2090 return;
2091 }
Mike Reed7bfa63b2009-05-28 11:08:32 -04002092 // call pauseWebViewTimers() now, we won't be able to call
2093 // it in onPause() as the WebView won't be valid.
Grace Klobaec1b5ad2009-08-18 08:42:32 -07002094 // Temporarily change mActivityInPause to be true as
2095 // pauseWebViewTimers() will do nothing if mActivityInPause
2096 // is false.
Grace Kloba918e1d72009-08-13 14:55:06 -07002097 boolean savedState = mActivityInPause;
2098 if (savedState) {
Grace Klobaec1b5ad2009-08-18 08:42:32 -07002099 Log.e(LOGTAG, "BrowserActivity is already paused "
2100 + "while handing goBackOnePageOrQuit.");
Grace Kloba918e1d72009-08-13 14:55:06 -07002101 }
2102 mActivityInPause = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -04002103 pauseWebViewTimers();
Grace Kloba918e1d72009-08-13 14:55:06 -07002104 mActivityInPause = savedState;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002105 removeTabFromContentView(current);
2106 mTabControl.removeTab(current);
2107 }
2108 /*
2109 * Instead of finishing the activity, simply push this to the back
2110 * of the stack and let ActivityManager to choose the foreground
2111 * activity. As BrowserActivity is singleTask, it will be always the
2112 * root of the task. So we can use either true or false for
2113 * moveTaskToBack().
2114 */
2115 moveTaskToBack(true);
2116 }
2117 }
2118 }
2119
Grace Kloba22ac16e2009-10-07 18:00:23 -07002120 boolean isMenuDown() {
2121 return mMenuIsDown;
2122 }
2123
Grace Kloba5942df02009-09-18 11:48:29 -07002124 @Override
2125 public boolean onKeyDown(int keyCode, KeyEvent event) {
Leon Scrogginsf65b50d2009-12-08 10:44:28 -05002126 // Even if MENU is already held down, we need to call to super to open
2127 // the IME on long press.
2128 if (KeyEvent.KEYCODE_MENU == keyCode) {
2129 mMenuIsDown = true;
2130 return super.onKeyDown(keyCode, event);
2131 }
Grace Kloba5942df02009-09-18 11:48:29 -07002132 // The default key mode is DEFAULT_KEYS_SEARCH_LOCAL. As the MENU is
2133 // still down, we don't want to trigger the search. Pretend to consume
2134 // the key and do nothing.
2135 if (mMenuIsDown) return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002136
Grace Kloba5942df02009-09-18 11:48:29 -07002137 switch(keyCode) {
Grace Kloba5942df02009-09-18 11:48:29 -07002138 case KeyEvent.KEYCODE_SPACE:
Grace Klobada0fe552009-09-22 18:17:24 -07002139 // WebView/WebTextView handle the keys in the KeyDown. As
2140 // the Activity's shortcut keys are only handled when WebView
2141 // doesn't, have to do it in onKeyDown instead of onKeyUp.
2142 if (event.isShiftPressed()) {
2143 getTopWindow().pageUp(false);
2144 } else {
2145 getTopWindow().pageDown(false);
2146 }
Grace Kloba5942df02009-09-18 11:48:29 -07002147 return true;
2148 case KeyEvent.KEYCODE_BACK:
2149 if (event.getRepeatCount() == 0) {
2150 event.startTracking();
2151 return true;
2152 } else if (mCustomView == null && mActiveTabsPage == null
2153 && event.isLongPress()) {
2154 bookmarksOrHistoryPicker(true);
2155 return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002156 }
Grace Kloba5942df02009-09-18 11:48:29 -07002157 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002158 }
Grace Kloba5942df02009-09-18 11:48:29 -07002159 return super.onKeyDown(keyCode, event);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002160 }
2161
Grace Kloba5942df02009-09-18 11:48:29 -07002162 @Override
2163 public boolean onKeyUp(int keyCode, KeyEvent event) {
2164 switch(keyCode) {
2165 case KeyEvent.KEYCODE_MENU:
2166 mMenuIsDown = false;
2167 break;
Grace Kloba5942df02009-09-18 11:48:29 -07002168 case KeyEvent.KEYCODE_BACK:
2169 if (event.isTracking() && !event.isCanceled()) {
2170 if (mCustomView != null) {
2171 // if a custom view is showing, hide it
Grace Kloba22ac16e2009-10-07 18:00:23 -07002172 mTabControl.getCurrentWebView().getWebChromeClient()
2173 .onHideCustomView();
Grace Kloba5942df02009-09-18 11:48:29 -07002174 } else if (mActiveTabsPage != null) {
2175 // if tab page is showing, hide it
2176 removeActiveTabPage(true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002177 } else {
Grace Kloba5942df02009-09-18 11:48:29 -07002178 WebView subwindow = mTabControl.getCurrentSubWindow();
2179 if (subwindow != null) {
2180 if (subwindow.canGoBack()) {
2181 subwindow.goBack();
2182 } else {
2183 dismissSubWindow(mTabControl.getCurrentTab());
2184 }
2185 } else {
2186 goBackOnePageOrQuit();
2187 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002188 }
Grace Kloba5942df02009-09-18 11:48:29 -07002189 return true;
2190 }
2191 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002192 }
Grace Kloba5942df02009-09-18 11:48:29 -07002193 return super.onKeyUp(keyCode, event);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002194 }
2195
Leon Scroggins68579392009-09-15 15:31:54 -04002196 /* package */ void stopLoading() {
Ben Murdochb7cc8b42009-09-28 10:59:09 +01002197 mDidStopLoad = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002198 resetTitleAndRevertLockIcon();
2199 WebView w = getTopWindow();
2200 w.stopLoading();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002201 // FIXME: before refactor, it is using mWebViewClient. So I keep the
2202 // same logic here. But for subwindow case, should we call into the main
2203 // WebView's onPageFinished as we never call its onPageStarted and if
2204 // the page finishes itself, we don't call onPageFinished.
2205 mTabControl.getCurrentWebView().getWebViewClient().onPageFinished(w,
2206 w.getUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08002207
2208 cancelStopToast();
2209 mStopToast = Toast
2210 .makeText(this, R.string.stopping, Toast.LENGTH_SHORT);
2211 mStopToast.show();
2212 }
2213
Grace Kloba22ac16e2009-10-07 18:00:23 -07002214 boolean didUserStopLoading() {
2215 return mDidStopLoad;
2216 }
2217
The Android Open Source Project0c908882009-03-03 19:32:16 -08002218 private void cancelStopToast() {
2219 if (mStopToast != null) {
2220 mStopToast.cancel();
2221 mStopToast = null;
2222 }
2223 }
2224
Grace Kloba22ac16e2009-10-07 18:00:23 -07002225 // called by a UI or non-UI thread to post the message
2226 public void postMessage(int what, int arg1, int arg2, Object obj,
2227 long delayMillis) {
2228 mHandler.sendMessageDelayed(mHandler.obtainMessage(what, arg1, arg2,
2229 obj), delayMillis);
2230 }
2231
2232 // called by a UI or non-UI thread to remove the message
2233 void removeMessages(int what, Object object) {
2234 mHandler.removeMessages(what, object);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002235 }
2236
2237 // public message ids
2238 public final static int LOAD_URL = 1001;
2239 public final static int STOP_LOAD = 1002;
2240
2241 // Message Ids
2242 private static final int FOCUS_NODE_HREF = 102;
Grace Kloba92c18a52009-07-31 23:48:32 -07002243 private static final int RELEASE_WAKELOCK = 107;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002244
Grace Kloba22ac16e2009-10-07 18:00:23 -07002245 static final int UPDATE_BOOKMARK_THUMBNAIL = 108;
Ben Murdoch2694e232009-09-29 09:41:11 +01002246
The Android Open Source Project0c908882009-03-03 19:32:16 -08002247 // Private handler for handling javascript and saving passwords
2248 private Handler mHandler = new Handler() {
2249
2250 public void handleMessage(Message msg) {
2251 switch (msg.what) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002252 case FOCUS_NODE_HREF:
Ben Murdoch2694e232009-09-29 09:41:11 +01002253 {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002254 String url = (String) msg.getData().get("url");
Ben Murdoch90d088c2009-11-17 18:14:04 +00002255 String title = (String) msg.getData().get("title");
The Android Open Source Project0c908882009-03-03 19:32:16 -08002256 if (url == null || url.length() == 0) {
2257 break;
2258 }
2259 HashMap focusNodeMap = (HashMap) msg.obj;
2260 WebView view = (WebView) focusNodeMap.get("webview");
2261 // Only apply the action if the top window did not change.
2262 if (getTopWindow() != view) {
2263 break;
2264 }
2265 switch (msg.arg1) {
2266 case R.id.open_context_menu_id:
2267 case R.id.view_image_context_menu_id:
Leon Scroggins92472e82010-02-17 16:32:28 -05002268 loadUrlFromContext(getTopWindow(), url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002269 break;
2270 case R.id.open_newtab_context_menu_id:
Grace Kloba22ac16e2009-10-07 18:00:23 -07002271 final Tab parent = mTabControl.getCurrentTab();
2272 final Tab newTab = openTab(url);
Grace Klobac9181842009-04-14 08:53:22 -07002273 if (newTab != parent) {
2274 parent.addChildTab(newTab);
2275 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002276 break;
2277 case R.id.bookmark_context_menu_id:
2278 Intent intent = new Intent(BrowserActivity.this,
2279 AddBookmarkPage.class);
2280 intent.putExtra("url", url);
Ben Murdoch90d088c2009-11-17 18:14:04 +00002281 intent.putExtra("title", title);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002282 startActivity(intent);
2283 break;
2284 case R.id.share_link_context_menu_id:
Leon Scroggins96afcb12009-12-10 12:35:56 -05002285 // See if this site has been visited before
2286 StringBuilder sb = new StringBuilder(
2287 Browser.BookmarkColumns.URL + " = ");
2288 DatabaseUtils.appendEscapedSQLString(sb, url);
2289 Cursor c = mResolver.query(Browser.BOOKMARKS_URI,
2290 Browser.HISTORY_PROJECTION,
2291 sb.toString(),
2292 null,
2293 null);
2294 if (c.moveToFirst()) {
2295 // The site has been visited before, so grab the
2296 // info from the database.
2297 Bitmap favicon = null;
2298 Bitmap thumbnail = null;
2299 String linkTitle = c.getString(Browser.
2300 HISTORY_PROJECTION_TITLE_INDEX);
2301 byte[] data = c.getBlob(Browser.
2302 HISTORY_PROJECTION_FAVICON_INDEX);
2303 if (data != null) {
2304 favicon = BitmapFactory.decodeByteArray(
2305 data, 0, data.length);
2306 }
2307 data = c.getBlob(Browser.
2308 HISTORY_PROJECTION_THUMBNAIL_INDEX);
2309 if (data != null) {
2310 thumbnail = BitmapFactory.decodeByteArray(
2311 data, 0, data.length);
2312 }
2313 sharePage(BrowserActivity.this,
2314 linkTitle, url, favicon, thumbnail);
2315 } else {
2316 Browser.sendString(BrowserActivity.this, url,
2317 getString(
2318 R.string.choosertitle_sharevia));
2319 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002320 break;
2321 case R.id.copy_link_context_menu_id:
2322 copy(url);
2323 break;
2324 case R.id.save_link_context_menu_id:
2325 case R.id.download_context_menu_id:
2326 onDownloadStartNoStream(url, null, null, null, -1);
2327 break;
2328 }
2329 break;
Ben Murdoch2694e232009-09-29 09:41:11 +01002330 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002331
2332 case LOAD_URL:
Leon Scroggins92472e82010-02-17 16:32:28 -05002333 loadUrlFromContext(getTopWindow(), (String) msg.obj);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002334 break;
2335
2336 case STOP_LOAD:
2337 stopLoading();
2338 break;
2339
The Android Open Source Project0c908882009-03-03 19:32:16 -08002340 case RELEASE_WAKELOCK:
2341 if (mWakeLock.isHeld()) {
2342 mWakeLock.release();
Grace Kloba5d0e02e2009-10-05 15:15:36 -07002343 // if we reach here, Browser should be still in the
2344 // background loading after WAKELOCK_TIMEOUT (5-min).
2345 // To avoid burning the battery, stop loading.
2346 mTabControl.stopAllLoading();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002347 }
2348 break;
Ben Murdoch2694e232009-09-29 09:41:11 +01002349
2350 case UPDATE_BOOKMARK_THUMBNAIL:
2351 WebView view = (WebView) msg.obj;
2352 if (view != null) {
2353 updateScreenshot(view);
2354 }
2355 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002356 }
2357 }
2358 };
2359
Leon Scroggins96afcb12009-12-10 12:35:56 -05002360 /**
2361 * Share a page, providing the title, url, favicon, and a screenshot. Uses
2362 * an {@link Intent} to launch the Activity chooser.
2363 * @param c Context used to launch a new Activity.
2364 * @param title Title of the page. Stored in the Intent with
Paul Westbrook03e6d392010-02-12 10:33:29 -08002365 * {@link Intent#EXTRA_SUBJECT}
Leon Scroggins96afcb12009-12-10 12:35:56 -05002366 * @param url URL of the page. Stored in the Intent with
2367 * {@link Intent#EXTRA_TEXT}
2368 * @param favicon Bitmap of the favicon for the page. Stored in the Intent
2369 * with {@link Browser#EXTRA_SHARE_FAVICON}
2370 * @param screenshot Bitmap of a screenshot of the page. Stored in the
2371 * Intent with {@link Browser#EXTRA_SHARE_SCREENSHOT}
2372 */
2373 public static final void sharePage(Context c, String title, String url,
2374 Bitmap favicon, Bitmap screenshot) {
2375 Intent send = new Intent(Intent.ACTION_SEND);
2376 send.setType("text/plain");
2377 send.putExtra(Intent.EXTRA_TEXT, url);
Paul Westbrook03e6d392010-02-12 10:33:29 -08002378 send.putExtra(Intent.EXTRA_SUBJECT, title);
Leon Scroggins96afcb12009-12-10 12:35:56 -05002379 send.putExtra(Browser.EXTRA_SHARE_FAVICON, favicon);
2380 send.putExtra(Browser.EXTRA_SHARE_SCREENSHOT, screenshot);
2381 try {
2382 c.startActivity(Intent.createChooser(send, c.getString(
2383 R.string.choosertitle_sharevia)));
2384 } catch(android.content.ActivityNotFoundException ex) {
2385 // if no app handles it, do nothing
2386 }
2387 }
2388
Leon Scroggins89c6d362009-07-15 16:54:37 -04002389 private void updateScreenshot(WebView view) {
2390 // If this is a bookmarked site, add a screenshot to the database.
2391 // FIXME: When should we update? Every time?
2392 // FIXME: Would like to make sure there is actually something to
2393 // draw, but the API for that (WebViewCore.pictureReady()) is not
2394 // currently accessible here.
Ben Murdochaac7aa62009-09-17 16:57:40 +01002395
Patrick Scottcb192b52010-04-14 14:38:55 -04002396 final Bitmap bm = createScreenshot(view);
2397 if (bm == null) {
2398 return;
Leon Scroggins89c6d362009-07-15 16:54:37 -04002399 }
Patrick Scottcb192b52010-04-14 14:38:55 -04002400
2401 final ContentResolver cr = getContentResolver();
2402 final String url = view.getUrl();
2403 final String originalUrl = view.getOriginalUrl();
2404
2405 new AsyncTask<Void, Void, Void>() {
2406 @Override
2407 protected Void doInBackground(Void... unused) {
2408 Cursor c = null;
2409 try {
2410 c = BrowserBookmarksAdapter.queryBookmarksForUrl(
2411 cr, originalUrl, url, true);
2412 if (c != null) {
2413 if (c.moveToFirst()) {
2414 ContentValues values = new ContentValues();
2415 final ByteArrayOutputStream os
2416 = new ByteArrayOutputStream();
2417 bm.compress(Bitmap.CompressFormat.PNG, 100, os);
2418 values.put(Browser.BookmarkColumns.THUMBNAIL,
2419 os.toByteArray());
2420 do {
2421 cr.update(ContentUris.withAppendedId(
2422 Browser.BOOKMARKS_URI, c.getInt(0)),
2423 values, null, null);
2424 } while (c.moveToNext());
2425 }
2426 }
2427 } catch (IllegalStateException e) {
2428 // Ignore
2429 } finally {
2430 if (c != null) c.close();
2431 }
2432 return null;
2433 }
2434 }.execute();
Leon Scroggins89c6d362009-07-15 16:54:37 -04002435 }
2436
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002437 /**
Leon Scrogginsf8551612009-09-24 16:06:02 -04002438 * Values for the size of the thumbnail created when taking a screenshot.
2439 * Lazily initialized. Instead of using these directly, use
2440 * getDesiredThumbnailWidth() or getDesiredThumbnailHeight().
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002441 */
Leon Scrogginsf8551612009-09-24 16:06:02 -04002442 private static int THUMBNAIL_WIDTH = 0;
2443 private static int THUMBNAIL_HEIGHT = 0;
2444
2445 /**
2446 * Return the desired width for thumbnail screenshots, which are stored in
2447 * the database, and used on the bookmarks screen.
2448 * @param context Context for finding out the density of the screen.
2449 * @return int desired width for thumbnail screenshot.
2450 */
2451 /* package */ static int getDesiredThumbnailWidth(Context context) {
2452 if (THUMBNAIL_WIDTH == 0) {
2453 float density = context.getResources().getDisplayMetrics().density;
2454 THUMBNAIL_WIDTH = (int) (90 * density);
2455 THUMBNAIL_HEIGHT = (int) (80 * density);
2456 }
2457 return THUMBNAIL_WIDTH;
2458 }
2459
2460 /**
2461 * Return the desired height for thumbnail screenshots, which are stored in
2462 * the database, and used on the bookmarks screen.
2463 * @param context Context for finding out the density of the screen.
2464 * @return int desired height for thumbnail screenshot.
2465 */
2466 /* package */ static int getDesiredThumbnailHeight(Context context) {
2467 // To ensure that they are both initialized.
2468 getDesiredThumbnailWidth(context);
2469 return THUMBNAIL_HEIGHT;
2470 }
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002471
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002472 private Bitmap createScreenshot(WebView view) {
2473 Picture thumbnail = view.capturePicture();
Leon Scroggins45800572009-09-29 16:38:47 -04002474 if (thumbnail == null) {
2475 return null;
2476 }
Leon Scrogginsf8551612009-09-24 16:06:02 -04002477 Bitmap bm = Bitmap.createBitmap(getDesiredThumbnailWidth(this),
Cary Clarkab168ba2010-04-08 09:11:28 -04002478 getDesiredThumbnailHeight(this), Bitmap.Config.RGB_565);
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002479 Canvas canvas = new Canvas(bm);
2480 // May need to tweak these values to determine what is the
2481 // best scale factor
Ben Murdoch2694e232009-09-29 09:41:11 +01002482 int thumbnailWidth = thumbnail.getWidth();
Ben Murdochae59c3f2009-10-20 18:30:28 +01002483 int thumbnailHeight = thumbnail.getHeight();
2484 float scaleFactorX = 1.0f;
2485 float scaleFactorY = 1.0f;
Ben Murdoch2694e232009-09-29 09:41:11 +01002486 if (thumbnailWidth > 0) {
Ben Murdochae59c3f2009-10-20 18:30:28 +01002487 scaleFactorX = (float) getDesiredThumbnailWidth(this) /
Ben Murdoch2694e232009-09-29 09:41:11 +01002488 (float)thumbnailWidth;
Ben Murdochae59c3f2009-10-20 18:30:28 +01002489 } else {
2490 return null;
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002491 }
Ben Murdochae59c3f2009-10-20 18:30:28 +01002492
2493 if (view.getWidth() > view.getHeight() &&
2494 thumbnailHeight < view.getHeight() && thumbnailHeight > 0) {
2495 // If the device is in landscape and the page is shorter
2496 // than the height of the view, stretch the thumbnail to fill the
2497 // space.
2498 scaleFactorY = (float) getDesiredThumbnailHeight(this) /
2499 (float)thumbnailHeight;
2500 } else {
2501 // In the portrait case, this looks nice.
2502 scaleFactorY = scaleFactorX;
2503 }
2504
2505 canvas.scale(scaleFactorX, scaleFactorY);
2506
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002507 thumbnail.draw(canvas);
2508 return bm;
2509 }
2510
The Android Open Source Project0c908882009-03-03 19:32:16 -08002511 // -------------------------------------------------------------------------
Grace Kloba22ac16e2009-10-07 18:00:23 -07002512 // Helper function for WebViewClient.
The Android Open Source Project0c908882009-03-03 19:32:16 -08002513 //-------------------------------------------------------------------------
2514
2515 // Use in overrideUrlLoading
2516 /* package */ final static String SCHEME_WTAI = "wtai://wp/";
2517 /* package */ final static String SCHEME_WTAI_MC = "wtai://wp/mc;";
2518 /* package */ final static String SCHEME_WTAI_SD = "wtai://wp/sd;";
2519 /* package */ final static String SCHEME_WTAI_AP = "wtai://wp/ap;";
2520
Leon Scroggins92472e82010-02-17 16:32:28 -05002521 // Keep this initial progress in sync with initialProgressValue (* 100)
2522 // in ProgressTracker.cpp
2523 private final static int INITIAL_PROGRESS = 10;
2524
Grace Kloba22ac16e2009-10-07 18:00:23 -07002525 void onPageStarted(WebView view, String url, Bitmap favicon) {
2526 // when BrowserActivity just starts, onPageStarted may be called before
2527 // onResume as it is triggered from onCreate. Call resumeWebViewTimers
2528 // to start the timer. As we won't switch tabs while an activity is in
2529 // pause state, we can ensure calling resume and pause in pair.
2530 if (mActivityInPause) resumeWebViewTimers();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002531
Grace Kloba22ac16e2009-10-07 18:00:23 -07002532 resetLockIcon(url);
2533 setUrlTitle(url, null);
2534 setFavicon(favicon);
Leon Scroggins8cf8f682009-11-04 11:13:50 -08002535 // Show some progress so that the user knows the page is beginning to
2536 // load
Leon Scroggins92472e82010-02-17 16:32:28 -05002537 onProgressChanged(view, INITIAL_PROGRESS);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002538 mDidStopLoad = false;
Grace Kloba22ac16e2009-10-07 18:00:23 -07002539 if (!mIsNetworkUp) createAndShowNetworkDialog();
Cary Clark2c326e62010-08-19 18:40:57 -04002540 closeDialogs();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002541 if (mSettings.isTracing()) {
2542 String host;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002543 try {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002544 WebAddress uri = new WebAddress(url);
2545 host = uri.mHost;
2546 } catch (android.net.ParseException ex) {
2547 host = "browser";
The Android Open Source Project0c908882009-03-03 19:32:16 -08002548 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002549 host = host.replace('.', '_');
2550 host += ".trace";
2551 mInTrace = true;
2552 Debug.startMethodTracing(host, 20 * 1024 * 1024);
2553 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002554
Grace Kloba22ac16e2009-10-07 18:00:23 -07002555 // Performance probe
2556 if (false) {
2557 mStart = SystemClock.uptimeMillis();
2558 mProcessStart = Process.getElapsedCpuTime();
2559 long[] sysCpu = new long[7];
2560 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2561 sysCpu, null)) {
2562 mUserStart = sysCpu[0] + sysCpu[1];
2563 mSystemStart = sysCpu[2];
2564 mIdleStart = sysCpu[3];
2565 mIrqStart = sysCpu[4] + sysCpu[5] + sysCpu[6];
2566 }
2567 mUiStart = SystemClock.currentThreadTimeMillis();
2568 }
2569 }
2570
2571 void onPageFinished(WebView view, String url) {
2572 // Reset the title and icon in case we stopped a provisional load.
2573 resetTitleAndIcon(view);
2574 // Update the lock icon image only once we are done loading
2575 updateLockIconToLatest();
2576 // pause the WebView timer and release the wake lock if it is finished
2577 // while BrowserActivity is in pause state.
2578 if (mActivityInPause && pauseWebViewTimers()) {
2579 if (mWakeLock.isHeld()) {
2580 mHandler.removeMessages(RELEASE_WAKELOCK);
2581 mWakeLock.release();
2582 }
2583 }
2584
2585 // Performance probe
2586 if (false) {
2587 long[] sysCpu = new long[7];
2588 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2589 sysCpu, null)) {
2590 String uiInfo = "UI thread used "
2591 + (SystemClock.currentThreadTimeMillis() - mUiStart)
2592 + " ms";
2593 if (LOGD_ENABLED) {
2594 Log.d(LOGTAG, uiInfo);
2595 }
2596 //The string that gets written to the log
2597 String performanceString = "It took total "
2598 + (SystemClock.uptimeMillis() - mStart)
2599 + " ms clock time to load the page."
2600 + "\nbrowser process used "
2601 + (Process.getElapsedCpuTime() - mProcessStart)
2602 + " ms, user processes used "
2603 + (sysCpu[0] + sysCpu[1] - mUserStart) * 10
2604 + " ms, kernel used "
2605 + (sysCpu[2] - mSystemStart) * 10
2606 + " ms, idle took " + (sysCpu[3] - mIdleStart) * 10
2607 + " ms and irq took "
2608 + (sysCpu[4] + sysCpu[5] + sysCpu[6] - mIrqStart)
2609 * 10 + " ms, " + uiInfo;
2610 if (LOGD_ENABLED) {
2611 Log.d(LOGTAG, performanceString + "\nWebpage: " + url);
2612 }
2613 if (url != null) {
2614 // strip the url to maintain consistency
2615 String newUrl = new String(url);
2616 if (newUrl.startsWith("http://www.")) {
2617 newUrl = newUrl.substring(11);
2618 } else if (newUrl.startsWith("http://")) {
2619 newUrl = newUrl.substring(7);
2620 } else if (newUrl.startsWith("https://www.")) {
2621 newUrl = newUrl.substring(12);
2622 } else if (newUrl.startsWith("https://")) {
2623 newUrl = newUrl.substring(8);
2624 }
2625 if (LOGD_ENABLED) {
2626 Log.d(LOGTAG, newUrl + " loaded");
2627 }
Grace Kloba5b078b52009-06-24 20:23:41 -07002628 }
2629 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002630 }
Grace Kloba5b078b52009-06-24 20:23:41 -07002631
Grace Kloba22ac16e2009-10-07 18:00:23 -07002632 if (mInTrace) {
2633 mInTrace = false;
2634 Debug.stopMethodTracing();
2635 }
2636 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002637
Grace Kloba22ac16e2009-10-07 18:00:23 -07002638 boolean shouldOverrideUrlLoading(WebView view, String url) {
2639 if (url.startsWith(SCHEME_WTAI)) {
2640 // wtai://wp/mc;number
2641 // number=string(phone-number)
2642 if (url.startsWith(SCHEME_WTAI_MC)) {
2643 Intent intent = new Intent(Intent.ACTION_VIEW,
2644 Uri.parse(WebView.SCHEME_TEL +
2645 url.substring(SCHEME_WTAI_MC.length())));
2646 startActivity(intent);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002647 return true;
2648 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002649 // wtai://wp/sd;dtmf
2650 // dtmf=string(dialstring)
2651 if (url.startsWith(SCHEME_WTAI_SD)) {
2652 // TODO: only send when there is active voice connection
2653 return false;
2654 }
2655 // wtai://wp/ap;number;name
2656 // number=string(phone-number)
2657 // name=string
2658 if (url.startsWith(SCHEME_WTAI_AP)) {
2659 // TODO
2660 return false;
2661 }
2662 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002663
Grace Kloba22ac16e2009-10-07 18:00:23 -07002664 // The "about:" schemes are internal to the browser; don't want these to
2665 // be dispatched to other apps.
2666 if (url.startsWith("about:")) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002667 return false;
2668 }
2669
Grace Kloba22ac16e2009-10-07 18:00:23 -07002670 Intent intent;
2671 // perform generic parsing of the URI to turn it into an Intent.
2672 try {
2673 intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME);
2674 } catch (URISyntaxException ex) {
2675 Log.w("Browser", "Bad URI " + url + ": " + ex.getMessage());
2676 return false;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002677 }
2678
Grace Kloba22ac16e2009-10-07 18:00:23 -07002679 // check whether the intent can be resolved. If not, we will see
2680 // whether we can download it from the Market.
2681 if (getPackageManager().resolveActivity(intent, 0) == null) {
2682 String packagename = intent.getPackage();
2683 if (packagename != null) {
2684 intent = new Intent(Intent.ACTION_VIEW, Uri
2685 .parse("market://search?q=pname:" + packagename));
2686 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2687 startActivity(intent);
2688 return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002689 } else {
2690 return false;
2691 }
2692 }
2693
Grace Kloba22ac16e2009-10-07 18:00:23 -07002694 // sanitize the Intent, ensuring web pages can not bypass browser
2695 // security (only access to BROWSABLE activities).
2696 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2697 intent.setComponent(null);
2698 try {
2699 if (startActivityIfNeeded(intent, -1)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002700 return true;
2701 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002702 } catch (ActivityNotFoundException ex) {
2703 // ignore the error. If no application can handle the URL,
2704 // eg about:blank, assume the browser can handle it.
2705 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002706
Grace Kloba22ac16e2009-10-07 18:00:23 -07002707 if (mMenuIsDown) {
2708 openTab(url);
2709 closeOptionsMenu();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002710 return true;
2711 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002712 return false;
2713 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002714
Grace Kloba22ac16e2009-10-07 18:00:23 -07002715 // -------------------------------------------------------------------------
2716 // Helper function for WebChromeClient
2717 // -------------------------------------------------------------------------
The Android Open Source Project0c908882009-03-03 19:32:16 -08002718
Grace Kloba22ac16e2009-10-07 18:00:23 -07002719 void onProgressChanged(WebView view, int newProgress) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002720 mFakeTitleBar.setProgress(newProgress);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002721
Grace Kloba22ac16e2009-10-07 18:00:23 -07002722 if (newProgress == 100) {
2723 // onProgressChanged() may continue to be called after the main
2724 // frame has finished loading, as any remaining sub frames continue
2725 // to load. We'll only get called once though with newProgress as
2726 // 100 when everything is loaded. (onPageFinished is called once
2727 // when the main frame completes loading regardless of the state of
2728 // any sub frames so calls to onProgressChanges may continue after
2729 // onPageFinished has executed)
2730 if (mInLoad) {
2731 mInLoad = false;
Leon Scrogginsa27ff192009-09-14 12:58:04 -04002732 updateInLoadMenuItems();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002733 // If the options menu is open, leave the title bar
2734 if (!mOptionsMenuOpen || !mIconView) {
2735 hideFakeTitleBar();
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07002736 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002737 }
Leon Scrogginsaa37e7f2010-03-05 11:51:20 -05002738 } else {
2739 if (!mInLoad) {
2740 // onPageFinished may have already been called but a subframe is
2741 // still loading and updating the progress. Reset mInLoad and
2742 // update the menu items.
2743 mInLoad = true;
2744 updateInLoadMenuItems();
2745 }
2746 // When the page first begins to load, the Activity may still be
2747 // paused, in which case showFakeTitleBar will do nothing. Call
2748 // again as the page continues to load so that it will be shown.
2749 // (Calling it will the fake title bar is already showing will also
2750 // do nothing.
Grace Kloba22ac16e2009-10-07 18:00:23 -07002751 if (!mOptionsMenuOpen || mIconView) {
2752 // This page has begun to load, so show the title bar
2753 showFakeTitleBar();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002754 }
2755 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002756 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002757
Grace Kloba22ac16e2009-10-07 18:00:23 -07002758 void onShowCustomView(View view, WebChromeClient.CustomViewCallback callback) {
Derek Sollenberger8ff57db2009-12-08 15:39:55 -05002759 // if a view already exists then immediately terminate the new one
2760 if (mCustomView != null) {
2761 callback.onCustomViewHidden();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002762 return;
Derek Sollenberger8ff57db2009-12-08 15:39:55 -05002763 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002764
2765 // Add the custom view to its container.
2766 mCustomViewContainer.addView(view, COVER_SCREEN_GRAVITY_CENTER);
2767 mCustomView = view;
2768 mCustomViewCallback = callback;
2769 // Save the menu state and set it to empty while the custom
2770 // view is showing.
2771 mOldMenuState = mMenuState;
2772 mMenuState = EMPTY_MENU;
2773 // Hide the content view.
2774 mContentView.setVisibility(View.GONE);
2775 // Finally show the custom view container.
Andrei Popescu163ab742009-10-20 17:58:23 +01002776 setStatusBarVisibility(false);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002777 mCustomViewContainer.setVisibility(View.VISIBLE);
2778 mCustomViewContainer.bringToFront();
2779 }
2780
2781 void onHideCustomView() {
2782 if (mCustomView == null)
2783 return;
2784
2785 // Hide the custom view.
2786 mCustomView.setVisibility(View.GONE);
2787 // Remove the custom view from its container.
2788 mCustomViewContainer.removeView(mCustomView);
2789 mCustomView = null;
2790 // Reset the old menu state.
2791 mMenuState = mOldMenuState;
2792 mOldMenuState = EMPTY_MENU;
2793 mCustomViewContainer.setVisibility(View.GONE);
2794 mCustomViewCallback.onCustomViewHidden();
2795 // Show the content view.
Andrei Popescu163ab742009-10-20 17:58:23 +01002796 setStatusBarVisibility(true);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002797 mContentView.setVisibility(View.VISIBLE);
2798 }
2799
2800 Bitmap getDefaultVideoPoster() {
2801 if (mDefaultVideoPoster == null) {
2802 mDefaultVideoPoster = BitmapFactory.decodeResource(
2803 getResources(), R.drawable.default_video_poster);
Patrick Scott3918d442009-08-04 13:22:29 -04002804 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002805 return mDefaultVideoPoster;
2806 }
Patrick Scott3918d442009-08-04 13:22:29 -04002807
Grace Kloba22ac16e2009-10-07 18:00:23 -07002808 View getVideoLoadingProgressView() {
2809 if (mVideoProgressView == null) {
2810 LayoutInflater inflater = LayoutInflater.from(BrowserActivity.this);
2811 mVideoProgressView = inflater.inflate(
2812 R.layout.video_loading_progress, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002813 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002814 return mVideoProgressView;
2815 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002816
Leon Scroggins8d5fa432009-10-02 15:55:59 -04002817 /*
2818 * The Object used to inform the WebView of the file to upload.
2819 */
2820 private ValueCallback<Uri> mUploadMessage;
2821
Grace Kloba22ac16e2009-10-07 18:00:23 -07002822 void openFileChooser(ValueCallback<Uri> uploadMsg) {
2823 if (mUploadMessage != null) return;
2824 mUploadMessage = uploadMsg;
2825 Intent i = new Intent(Intent.ACTION_GET_CONTENT);
2826 i.addCategory(Intent.CATEGORY_OPENABLE);
2827 i.setType("*/*");
2828 BrowserActivity.this.startActivityForResult(Intent.createChooser(i,
2829 getString(R.string.choose_upload)), FILE_SELECTED);
2830 }
2831
2832 // -------------------------------------------------------------------------
2833 // Implement functions for DownloadListener
2834 // -------------------------------------------------------------------------
2835
The Android Open Source Project0c908882009-03-03 19:32:16 -08002836 /**
2837 * Notify the host application a download should be done, or that
2838 * the data should be streamed if a streaming viewer is available.
2839 * @param url The full url to the content that should be downloaded
2840 * @param contentDisposition Content-disposition http header, if
2841 * present.
2842 * @param mimetype The mimetype of the content reported by the server
2843 * @param contentLength The file size reported by the server
2844 */
2845 public void onDownloadStart(String url, String userAgent,
2846 String contentDisposition, String mimetype, long contentLength) {
2847 // if we're dealing wih A/V content that's not explicitly marked
2848 // for download, check if it's streamable.
2849 if (contentDisposition == null
Patrick Scotte1fb9662009-08-31 14:31:52 -04002850 || !contentDisposition.regionMatches(
2851 true, 0, "attachment", 0, 10)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002852 // query the package manager to see if there's a registered handler
2853 // that matches.
2854 Intent intent = new Intent(Intent.ACTION_VIEW);
2855 intent.setDataAndType(Uri.parse(url), mimetype);
Patrick Scotte1fb9662009-08-31 14:31:52 -04002856 ResolveInfo info = getPackageManager().resolveActivity(intent,
2857 PackageManager.MATCH_DEFAULT_ONLY);
2858 if (info != null) {
2859 ComponentName myName = getComponentName();
2860 // If we resolved to ourselves, we don't want to attempt to
2861 // load the url only to try and download it again.
2862 if (!myName.getPackageName().equals(
2863 info.activityInfo.packageName)
2864 || !myName.getClassName().equals(
2865 info.activityInfo.name)) {
2866 // someone (other than us) knows how to handle this mime
2867 // type with this scheme, don't download.
2868 try {
2869 startActivity(intent);
2870 return;
2871 } catch (ActivityNotFoundException ex) {
2872 if (LOGD_ENABLED) {
2873 Log.d(LOGTAG, "activity not found for " + mimetype
2874 + " over " + Uri.parse(url).getScheme(),
2875 ex);
2876 }
2877 // Best behavior is to fall back to a download in this
2878 // case
The Android Open Source Project0c908882009-03-03 19:32:16 -08002879 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002880 }
2881 }
2882 }
2883 onDownloadStartNoStream(url, userAgent, contentDisposition, mimetype, contentLength);
2884 }
2885
Kristian Monsenfa52d172010-03-25 18:29:21 +00002886 // This is to work around the fact that java.net.URI throws Exceptions
2887 // instead of just encoding URL's properly
2888 // Helper method for onDownloadStartNoStream
2889 private static String encodePath(String path) {
2890 char[] chars = path.toCharArray();
2891
2892 boolean needed = false;
2893 for (char c : chars) {
2894 if (c == '[' || c == ']') {
2895 needed = true;
2896 break;
2897 }
2898 }
2899 if (needed == false) {
2900 return path;
2901 }
2902
2903 StringBuilder sb = new StringBuilder("");
2904 for (char c : chars) {
2905 if (c == '[' || c == ']') {
2906 sb.append('%');
2907 sb.append(Integer.toHexString(c));
2908 } else {
2909 sb.append(c);
2910 }
2911 }
2912
2913 return sb.toString();
2914 }
2915
The Android Open Source Project0c908882009-03-03 19:32:16 -08002916 /**
2917 * Notify the host application a download should be done, even if there
2918 * is a streaming viewer available for thise type.
2919 * @param url The full url to the content that should be downloaded
2920 * @param contentDisposition Content-disposition http header, if
2921 * present.
2922 * @param mimetype The mimetype of the content reported by the server
2923 * @param contentLength The file size reported by the server
2924 */
2925 /*package */ void onDownloadStartNoStream(String url, String userAgent,
2926 String contentDisposition, String mimetype, long contentLength) {
2927
2928 String filename = URLUtil.guessFileName(url,
2929 contentDisposition, mimetype);
2930
2931 // Check to see if we have an SDCard
2932 String status = Environment.getExternalStorageState();
2933 if (!status.equals(Environment.MEDIA_MOUNTED)) {
2934 int title;
2935 String msg;
2936
2937 // Check to see if the SDCard is busy, same as the music app
2938 if (status.equals(Environment.MEDIA_SHARED)) {
2939 msg = getString(R.string.download_sdcard_busy_dlg_msg);
2940 title = R.string.download_sdcard_busy_dlg_title;
2941 } else {
2942 msg = getString(R.string.download_no_sdcard_dlg_msg, filename);
2943 title = R.string.download_no_sdcard_dlg_title;
2944 }
2945
2946 new AlertDialog.Builder(this)
2947 .setTitle(title)
2948 .setIcon(android.R.drawable.ic_dialog_alert)
2949 .setMessage(msg)
2950 .setPositiveButton(R.string.ok, null)
2951 .show();
2952 return;
2953 }
2954
Kristian Monsenfa52d172010-03-25 18:29:21 +00002955 // java.net.URI is a lot stricter than KURL so we have to encode some
2956 // extra characters. Fix for b 2538060 and b 1634719
2957 WebAddress webAddress;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002958 try {
Kristian Monsenfa52d172010-03-25 18:29:21 +00002959 webAddress = new WebAddress(url);
2960 webAddress.mPath = encodePath(webAddress.mPath);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002961 } catch (Exception e) {
Kristian Monsenfa52d172010-03-25 18:29:21 +00002962 // This only happens for very bad urls, we want to chatch the
2963 // exception here
2964 Log.e(LOGTAG, "Exception trying to parse url:" + url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002965 return;
2966 }
2967
2968 // XXX: Have to use the old url since the cookies were stored using the
2969 // old percent-encoded url.
2970 String cookies = CookieManager.getInstance().getCookie(url);
2971
2972 ContentValues values = new ContentValues();
Kristian Monsenfa52d172010-03-25 18:29:21 +00002973 values.put(Downloads.Impl.COLUMN_URI, webAddress.toString());
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08002974 values.put(Downloads.Impl.COLUMN_COOKIE_DATA, cookies);
2975 values.put(Downloads.Impl.COLUMN_USER_AGENT, userAgent);
2976 values.put(Downloads.Impl.COLUMN_NOTIFICATION_PACKAGE,
The Android Open Source Project0c908882009-03-03 19:32:16 -08002977 getPackageName());
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08002978 values.put(Downloads.Impl.COLUMN_NOTIFICATION_CLASS,
Leon Scrogginsa563d092010-04-19 16:53:49 -04002979 OpenDownloadReceiver.class.getCanonicalName());
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08002980 values.put(Downloads.Impl.COLUMN_VISIBILITY,
2981 Downloads.Impl.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
2982 values.put(Downloads.Impl.COLUMN_MIME_TYPE, mimetype);
2983 values.put(Downloads.Impl.COLUMN_FILE_NAME_HINT, filename);
Kristian Monsenfa52d172010-03-25 18:29:21 +00002984 values.put(Downloads.Impl.COLUMN_DESCRIPTION, webAddress.mHost);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002985 if (contentLength > 0) {
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08002986 values.put(Downloads.Impl.COLUMN_TOTAL_BYTES, contentLength);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002987 }
2988 if (mimetype == null) {
2989 // We must have long pressed on a link or image to download it. We
2990 // are not sure of the mimetype in this case, so do a head request
2991 new FetchUrlMimeType(this).execute(values);
2992 } else {
2993 final Uri contentUri =
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08002994 getContentResolver().insert(Downloads.Impl.CONTENT_URI, values);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002995 }
Leon Scroggins9191a7f2010-03-18 14:44:44 -04002996 Toast.makeText(this, R.string.download_pending, Toast.LENGTH_SHORT)
2997 .show();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002998 }
2999
Grace Kloba22ac16e2009-10-07 18:00:23 -07003000 // -------------------------------------------------------------------------
3001
The Android Open Source Project0c908882009-03-03 19:32:16 -08003002 /**
3003 * Resets the lock icon. This method is called when we start a new load and
3004 * know the url to be loaded.
3005 */
3006 private void resetLockIcon(String url) {
3007 // Save the lock-icon state (we revert to it if the load gets cancelled)
Grace Kloba22ac16e2009-10-07 18:00:23 -07003008 mTabControl.getCurrentTab().resetLockIcon(url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003009 updateLockIconImage(LOCK_ICON_UNSECURE);
3010 }
3011
The Android Open Source Project0c908882009-03-03 19:32:16 -08003012 /**
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04003013 * Update the lock icon to correspond to our latest state.
3014 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003015 private void updateLockIconToLatest() {
3016 updateLockIconImage(mTabControl.getCurrentTab().getLockIconType());
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04003017 }
3018
3019 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08003020 * Updates the lock-icon image in the title-bar.
3021 */
3022 private void updateLockIconImage(int lockIconType) {
3023 Drawable d = null;
3024 if (lockIconType == LOCK_ICON_SECURE) {
3025 d = mSecLockIcon;
3026 } else if (lockIconType == LOCK_ICON_MIXED) {
3027 d = mMixLockIcon;
3028 }
Leon Scroggins68579392009-09-15 15:31:54 -04003029 mTitleBar.setLock(d);
Leon Scrogginsfe87bd32009-10-06 10:10:00 -04003030 mFakeTitleBar.setLock(d);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003031 }
3032
3033 /**
3034 * Displays a page-info dialog.
3035 * @param tab The tab to show info about
3036 * @param fromShowSSLCertificateOnError The flag that indicates whether
3037 * this dialog was opened from the SSL-certificate-on-error dialog or
3038 * not. This is important, since we need to know whether to return to
3039 * the parent dialog or simply dismiss.
3040 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003041 private void showPageInfo(final Tab tab,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003042 final boolean fromShowSSLCertificateOnError) {
3043 final LayoutInflater factory = LayoutInflater
3044 .from(this);
3045
3046 final View pageInfoView = factory.inflate(R.layout.page_info, null);
3047
3048 final WebView view = tab.getWebView();
3049
3050 String url = null;
3051 String title = null;
3052
3053 if (view == null) {
3054 url = tab.getUrl();
3055 title = tab.getTitle();
3056 } else if (view == mTabControl.getCurrentWebView()) {
3057 // Use the cached title and url if this is the current WebView
3058 url = mUrl;
3059 title = mTitle;
3060 } else {
3061 url = view.getUrl();
3062 title = view.getTitle();
3063 }
3064
3065 if (url == null) {
3066 url = "";
3067 }
3068 if (title == null) {
3069 title = "";
3070 }
3071
3072 ((TextView) pageInfoView.findViewById(R.id.address)).setText(url);
3073 ((TextView) pageInfoView.findViewById(R.id.title)).setText(title);
3074
3075 mPageInfoView = tab;
Leon Scrogginsc7b92f82010-01-11 18:17:31 -05003076 mPageInfoFromShowSSLCertificateOnError = fromShowSSLCertificateOnError;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003077
3078 AlertDialog.Builder alertDialogBuilder =
3079 new AlertDialog.Builder(this)
3080 .setTitle(R.string.page_info).setIcon(android.R.drawable.ic_dialog_info)
3081 .setView(pageInfoView)
3082 .setPositiveButton(
3083 R.string.ok,
3084 new DialogInterface.OnClickListener() {
3085 public void onClick(DialogInterface dialog,
3086 int whichButton) {
3087 mPageInfoDialog = null;
3088 mPageInfoView = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003089
3090 // if we came here from the SSL error dialog
3091 if (fromShowSSLCertificateOnError) {
3092 // go back to the SSL error dialog
3093 showSSLCertificateOnError(
3094 mSSLCertificateOnErrorView,
3095 mSSLCertificateOnErrorHandler,
3096 mSSLCertificateOnErrorError);
3097 }
3098 }
3099 })
3100 .setOnCancelListener(
3101 new DialogInterface.OnCancelListener() {
3102 public void onCancel(DialogInterface dialog) {
3103 mPageInfoDialog = null;
3104 mPageInfoView = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003105
3106 // if we came here from the SSL error dialog
3107 if (fromShowSSLCertificateOnError) {
3108 // go back to the SSL error dialog
3109 showSSLCertificateOnError(
3110 mSSLCertificateOnErrorView,
3111 mSSLCertificateOnErrorHandler,
3112 mSSLCertificateOnErrorError);
3113 }
3114 }
3115 });
3116
3117 // if we have a main top-level page SSL certificate set or a certificate
3118 // error
3119 if (fromShowSSLCertificateOnError ||
3120 (view != null && view.getCertificate() != null)) {
3121 // add a 'View Certificate' button
3122 alertDialogBuilder.setNeutralButton(
3123 R.string.view_certificate,
3124 new DialogInterface.OnClickListener() {
3125 public void onClick(DialogInterface dialog,
3126 int whichButton) {
3127 mPageInfoDialog = null;
3128 mPageInfoView = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003129
3130 // if we came here from the SSL error dialog
3131 if (fromShowSSLCertificateOnError) {
3132 // go back to the SSL error dialog
3133 showSSLCertificateOnError(
3134 mSSLCertificateOnErrorView,
3135 mSSLCertificateOnErrorHandler,
3136 mSSLCertificateOnErrorError);
3137 } else {
3138 // otherwise, display the top-most certificate from
3139 // the chain
3140 if (view.getCertificate() != null) {
3141 showSSLCertificate(tab);
3142 }
3143 }
3144 }
3145 });
3146 }
3147
3148 mPageInfoDialog = alertDialogBuilder.show();
3149 }
3150
3151 /**
3152 * Displays the main top-level page SSL certificate dialog
3153 * (accessible from the Page-Info dialog).
3154 * @param tab The tab to show certificate for.
3155 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003156 private void showSSLCertificate(final Tab tab) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003157 final View certificateView =
3158 inflateCertificateView(tab.getWebView().getCertificate());
3159 if (certificateView == null) {
3160 return;
3161 }
3162
3163 LayoutInflater factory = LayoutInflater.from(this);
3164
3165 final LinearLayout placeholder =
3166 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3167
3168 LinearLayout ll = (LinearLayout) factory.inflate(
3169 R.layout.ssl_success, placeholder);
3170 ((TextView)ll.findViewById(R.id.success))
3171 .setText(R.string.ssl_certificate_is_valid);
3172
3173 mSSLCertificateView = tab;
3174 mSSLCertificateDialog =
3175 new AlertDialog.Builder(this)
3176 .setTitle(R.string.ssl_certificate).setIcon(
3177 R.drawable.ic_dialog_browser_certificate_secure)
3178 .setView(certificateView)
3179 .setPositiveButton(R.string.ok,
3180 new DialogInterface.OnClickListener() {
3181 public void onClick(DialogInterface dialog,
3182 int whichButton) {
3183 mSSLCertificateDialog = null;
3184 mSSLCertificateView = null;
3185
3186 showPageInfo(tab, false);
3187 }
3188 })
3189 .setOnCancelListener(
3190 new DialogInterface.OnCancelListener() {
3191 public void onCancel(DialogInterface dialog) {
3192 mSSLCertificateDialog = null;
3193 mSSLCertificateView = null;
3194
3195 showPageInfo(tab, false);
3196 }
3197 })
3198 .show();
3199 }
3200
3201 /**
3202 * Displays the SSL error certificate dialog.
3203 * @param view The target web-view.
3204 * @param handler The SSL error handler responsible for cancelling the
3205 * connection that resulted in an SSL error or proceeding per user request.
3206 * @param error The SSL error object.
3207 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003208 void showSSLCertificateOnError(
The Android Open Source Project0c908882009-03-03 19:32:16 -08003209 final WebView view, final SslErrorHandler handler, final SslError error) {
3210
3211 final View certificateView =
3212 inflateCertificateView(error.getCertificate());
3213 if (certificateView == null) {
3214 return;
3215 }
3216
3217 LayoutInflater factory = LayoutInflater.from(this);
3218
3219 final LinearLayout placeholder =
3220 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3221
3222 if (error.hasError(SslError.SSL_UNTRUSTED)) {
3223 LinearLayout ll = (LinearLayout)factory
3224 .inflate(R.layout.ssl_warning, placeholder);
3225 ((TextView)ll.findViewById(R.id.warning))
3226 .setText(R.string.ssl_untrusted);
3227 }
3228
3229 if (error.hasError(SslError.SSL_IDMISMATCH)) {
3230 LinearLayout ll = (LinearLayout)factory
3231 .inflate(R.layout.ssl_warning, placeholder);
3232 ((TextView)ll.findViewById(R.id.warning))
3233 .setText(R.string.ssl_mismatch);
3234 }
3235
3236 if (error.hasError(SslError.SSL_EXPIRED)) {
3237 LinearLayout ll = (LinearLayout)factory
3238 .inflate(R.layout.ssl_warning, placeholder);
3239 ((TextView)ll.findViewById(R.id.warning))
3240 .setText(R.string.ssl_expired);
3241 }
3242
3243 if (error.hasError(SslError.SSL_NOTYETVALID)) {
3244 LinearLayout ll = (LinearLayout)factory
3245 .inflate(R.layout.ssl_warning, placeholder);
3246 ((TextView)ll.findViewById(R.id.warning))
3247 .setText(R.string.ssl_not_yet_valid);
3248 }
3249
3250 mSSLCertificateOnErrorHandler = handler;
3251 mSSLCertificateOnErrorView = view;
3252 mSSLCertificateOnErrorError = error;
3253 mSSLCertificateOnErrorDialog =
3254 new AlertDialog.Builder(this)
3255 .setTitle(R.string.ssl_certificate).setIcon(
3256 R.drawable.ic_dialog_browser_certificate_partially_secure)
3257 .setView(certificateView)
3258 .setPositiveButton(R.string.ok,
3259 new DialogInterface.OnClickListener() {
3260 public void onClick(DialogInterface dialog,
3261 int whichButton) {
3262 mSSLCertificateOnErrorDialog = null;
3263 mSSLCertificateOnErrorView = null;
3264 mSSLCertificateOnErrorHandler = null;
3265 mSSLCertificateOnErrorError = null;
3266
Grace Kloba22ac16e2009-10-07 18:00:23 -07003267 view.getWebViewClient().onReceivedSslError(
3268 view, handler, error);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003269 }
3270 })
3271 .setNeutralButton(R.string.page_info_view,
3272 new DialogInterface.OnClickListener() {
3273 public void onClick(DialogInterface dialog,
3274 int whichButton) {
3275 mSSLCertificateOnErrorDialog = null;
3276
3277 // do not clear the dialog state: we will
3278 // need to show the dialog again once the
3279 // user is done exploring the page-info details
3280
3281 showPageInfo(mTabControl.getTabFromView(view),
3282 true);
3283 }
3284 })
3285 .setOnCancelListener(
3286 new DialogInterface.OnCancelListener() {
3287 public void onCancel(DialogInterface dialog) {
3288 mSSLCertificateOnErrorDialog = null;
3289 mSSLCertificateOnErrorView = null;
3290 mSSLCertificateOnErrorHandler = null;
3291 mSSLCertificateOnErrorError = null;
3292
Grace Kloba22ac16e2009-10-07 18:00:23 -07003293 view.getWebViewClient().onReceivedSslError(
3294 view, handler, error);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003295 }
3296 })
3297 .show();
3298 }
3299
3300 /**
3301 * Inflates the SSL certificate view (helper method).
3302 * @param certificate The SSL certificate.
3303 * @return The resultant certificate view with issued-to, issued-by,
3304 * issued-on, expires-on, and possibly other fields set.
3305 * If the input certificate is null, returns null.
3306 */
3307 private View inflateCertificateView(SslCertificate certificate) {
3308 if (certificate == null) {
3309 return null;
3310 }
3311
3312 LayoutInflater factory = LayoutInflater.from(this);
3313
3314 View certificateView = factory.inflate(
3315 R.layout.ssl_certificate, null);
3316
3317 // issued to:
3318 SslCertificate.DName issuedTo = certificate.getIssuedTo();
3319 if (issuedTo != null) {
3320 ((TextView) certificateView.findViewById(R.id.to_common))
3321 .setText(issuedTo.getCName());
3322 ((TextView) certificateView.findViewById(R.id.to_org))
3323 .setText(issuedTo.getOName());
3324 ((TextView) certificateView.findViewById(R.id.to_org_unit))
3325 .setText(issuedTo.getUName());
3326 }
3327
3328 // issued by:
3329 SslCertificate.DName issuedBy = certificate.getIssuedBy();
3330 if (issuedBy != null) {
3331 ((TextView) certificateView.findViewById(R.id.by_common))
3332 .setText(issuedBy.getCName());
3333 ((TextView) certificateView.findViewById(R.id.by_org))
3334 .setText(issuedBy.getOName());
3335 ((TextView) certificateView.findViewById(R.id.by_org_unit))
3336 .setText(issuedBy.getUName());
3337 }
3338
3339 // issued on:
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003340 String issuedOn = formatCertificateDate(
3341 certificate.getValidNotBeforeDate());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003342 ((TextView) certificateView.findViewById(R.id.issued_on))
3343 .setText(issuedOn);
3344
3345 // expires on:
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003346 String expiresOn = formatCertificateDate(
3347 certificate.getValidNotAfterDate());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003348 ((TextView) certificateView.findViewById(R.id.expires_on))
3349 .setText(expiresOn);
3350
3351 return certificateView;
3352 }
3353
3354 /**
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003355 * Formats the certificate date to a properly localized date string.
The Android Open Source Project0c908882009-03-03 19:32:16 -08003356 * @return Properly localized version of the certificate date string and
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003357 * the "" if it fails to localize.
The Android Open Source Project0c908882009-03-03 19:32:16 -08003358 */
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003359 private String formatCertificateDate(Date certificateDate) {
3360 if (certificateDate == null) {
3361 return "";
The Android Open Source Project0c908882009-03-03 19:32:16 -08003362 }
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003363 String formattedDate = DateFormat.getDateFormat(this).format(certificateDate);
3364 if (formattedDate == null) {
3365 return "";
3366 }
3367 return formattedDate;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003368 }
3369
3370 /**
3371 * Displays an http-authentication dialog.
3372 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003373 void showHttpAuthentication(final HttpAuthHandler handler,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003374 final String host, final String realm, final String title,
3375 final String name, final String password, int focusId) {
3376 LayoutInflater factory = LayoutInflater.from(this);
3377 final View v = factory
3378 .inflate(R.layout.http_authentication, null);
3379 if (name != null) {
3380 ((EditText) v.findViewById(R.id.username_edit)).setText(name);
3381 }
3382 if (password != null) {
3383 ((EditText) v.findViewById(R.id.password_edit)).setText(password);
3384 }
3385
3386 String titleText = title;
3387 if (titleText == null) {
3388 titleText = getText(R.string.sign_in_to).toString().replace(
3389 "%s1", host).replace("%s2", realm);
3390 }
3391
3392 mHttpAuthHandler = handler;
3393 AlertDialog dialog = new AlertDialog.Builder(this)
3394 .setTitle(titleText)
3395 .setIcon(android.R.drawable.ic_dialog_alert)
3396 .setView(v)
3397 .setPositiveButton(R.string.action,
3398 new DialogInterface.OnClickListener() {
3399 public void onClick(DialogInterface dialog,
3400 int whichButton) {
3401 String nm = ((EditText) v
3402 .findViewById(R.id.username_edit))
3403 .getText().toString();
3404 String pw = ((EditText) v
3405 .findViewById(R.id.password_edit))
3406 .getText().toString();
3407 BrowserActivity.this.setHttpAuthUsernamePassword
3408 (host, realm, nm, pw);
3409 handler.proceed(nm, pw);
3410 mHttpAuthenticationDialog = null;
3411 mHttpAuthHandler = null;
3412 }})
3413 .setNegativeButton(R.string.cancel,
3414 new DialogInterface.OnClickListener() {
3415 public void onClick(DialogInterface dialog,
3416 int whichButton) {
3417 handler.cancel();
3418 BrowserActivity.this.resetTitleAndRevertLockIcon();
3419 mHttpAuthenticationDialog = null;
3420 mHttpAuthHandler = null;
3421 }})
3422 .setOnCancelListener(new DialogInterface.OnCancelListener() {
3423 public void onCancel(DialogInterface dialog) {
3424 handler.cancel();
3425 BrowserActivity.this.resetTitleAndRevertLockIcon();
3426 mHttpAuthenticationDialog = null;
3427 mHttpAuthHandler = null;
3428 }})
3429 .create();
3430 // Make the IME appear when the dialog is displayed if applicable.
3431 dialog.getWindow().setSoftInputMode(
3432 WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
3433 dialog.show();
3434 if (focusId != 0) {
3435 dialog.findViewById(focusId).requestFocus();
3436 } else {
3437 v.findViewById(R.id.username_edit).requestFocus();
3438 }
3439 mHttpAuthenticationDialog = dialog;
3440 }
3441
3442 public int getProgress() {
3443 WebView w = mTabControl.getCurrentWebView();
3444 if (w != null) {
3445 return w.getProgress();
3446 } else {
3447 return 100;
3448 }
3449 }
3450
3451 /**
3452 * Set HTTP authentication password.
3453 *
3454 * @param host The host for the password
3455 * @param realm The realm for the password
3456 * @param username The username for the password. If it is null, it means
3457 * password can't be saved.
3458 * @param password The password
3459 */
3460 public void setHttpAuthUsernamePassword(String host, String realm,
3461 String username,
3462 String password) {
Steve Block95a53b22010-03-25 17:24:58 +00003463 WebView w = getTopWindow();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003464 if (w != null) {
3465 w.setHttpAuthUsernamePassword(host, realm, username, password);
3466 }
3467 }
3468
3469 /**
3470 * connectivity manager says net has come or gone... inform the user
3471 * @param up true if net has come up, false if net has gone down
3472 */
3473 public void onNetworkToggle(boolean up) {
3474 if (up == mIsNetworkUp) {
3475 return;
3476 } else if (up) {
3477 mIsNetworkUp = true;
3478 if (mAlertDialog != null) {
3479 mAlertDialog.cancel();
3480 mAlertDialog = null;
3481 }
3482 } else {
3483 mIsNetworkUp = false;
Patrick Scotteb6ab2a2009-09-16 10:00:17 -04003484 if (mInLoad) {
3485 createAndShowNetworkDialog();
3486 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003487 }
3488 WebView w = mTabControl.getCurrentWebView();
3489 if (w != null) {
3490 w.setNetworkAvailable(up);
3491 }
3492 }
3493
Grace Kloba22ac16e2009-10-07 18:00:23 -07003494 boolean isNetworkUp() {
3495 return mIsNetworkUp;
3496 }
3497
Patrick Scotteb6ab2a2009-09-16 10:00:17 -04003498 // This method shows the network dialog alerting the user that the net is
3499 // down. It will only show the dialog if mAlertDialog is null.
3500 private void createAndShowNetworkDialog() {
3501 if (mAlertDialog == null) {
3502 mAlertDialog = new AlertDialog.Builder(this)
3503 .setTitle(R.string.loadSuspendedTitle)
3504 .setMessage(R.string.loadSuspended)
3505 .setPositiveButton(R.string.ok, null)
3506 .show();
3507 }
3508 }
3509
The Android Open Source Project0c908882009-03-03 19:32:16 -08003510 @Override
3511 protected void onActivityResult(int requestCode, int resultCode,
3512 Intent intent) {
Grace Klobabb394f32009-11-19 10:26:37 -08003513 if (getTopWindow() == null) return;
3514
The Android Open Source Project0c908882009-03-03 19:32:16 -08003515 switch (requestCode) {
3516 case COMBO_PAGE:
3517 if (resultCode == RESULT_OK && intent != null) {
3518 String data = intent.getAction();
3519 Bundle extras = intent.getExtras();
3520 if (extras != null && extras.getBoolean("new_window", false)) {
Leon Scroggins25d35472009-09-15 11:37:27 -04003521 openTab(data);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003522 } else {
Grace Kloba22ac16e2009-10-07 18:00:23 -07003523 final Tab currentTab =
The Android Open Source Project0c908882009-03-03 19:32:16 -08003524 mTabControl.getCurrentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04003525 dismissSubWindow(currentTab);
3526 if (data != null && data.length() != 0) {
Leon Scroggins92472e82010-02-17 16:32:28 -05003527 loadUrl(getTopWindow(), data);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003528 }
3529 }
3530 }
Leon Scrogginsfde97462010-01-11 13:06:21 -05003531 // Deliberately fall through to PREFERENCES_PAGE, since the
3532 // same extra may be attached to the COMBO_PAGE
3533 case PREFERENCES_PAGE:
3534 if (resultCode == RESULT_OK && intent != null) {
3535 String action = intent.getStringExtra(Intent.EXTRA_TEXT);
3536 if (BrowserSettings.PREF_CLEAR_HISTORY.equals(action)) {
3537 mTabControl.removeParentChildRelationShips();
3538 }
3539 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003540 break;
Leon Scroggins8d5fa432009-10-02 15:55:59 -04003541 // Choose a file from the file picker.
3542 case FILE_SELECTED:
3543 if (null == mUploadMessage) break;
3544 Uri result = intent == null || resultCode != RESULT_OK ? null
3545 : intent.getData();
3546 mUploadMessage.onReceiveValue(result);
3547 mUploadMessage = null;
3548 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003549 default:
3550 break;
3551 }
Leon Scroggins30444232009-09-04 18:36:20 -04003552 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003553 }
3554
3555 /*
3556 * This method is called as a result of the user selecting the options
Leon Scrogginsf08809b2010-01-21 09:27:46 -05003557 * menu to see the download window. It shows the download window on top of
3558 * the current window.
The Android Open Source Project0c908882009-03-03 19:32:16 -08003559 */
Leon Scrogginsf08809b2010-01-21 09:27:46 -05003560 private void viewDownloads(Uri downloadRecord) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003561 Intent intent = new Intent(this,
3562 BrowserDownloadPage.class);
3563 intent.setData(downloadRecord);
Grace Kloba22ac16e2009-10-07 18:00:23 -07003564 startActivityForResult(intent, BrowserActivity.DOWNLOAD_PAGE);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003565
3566 }
3567
Leon Scroggins160a7e72009-08-14 18:28:01 -04003568 /**
3569 * Open the Go page.
3570 * @param startWithHistory If true, open starting on the history tab.
3571 * Otherwise, start with the bookmarks tab.
Leon Scroggins160a7e72009-08-14 18:28:01 -04003572 */
Leon Scroggins30444232009-09-04 18:36:20 -04003573 /* package */ void bookmarksOrHistoryPicker(boolean startWithHistory) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003574 WebView current = mTabControl.getCurrentWebView();
3575 if (current == null) {
3576 return;
3577 }
3578 Intent intent = new Intent(this,
3579 CombinedBookmarkHistoryActivity.class);
3580 String title = current.getTitle();
3581 String url = current.getUrl();
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01003582 Bitmap thumbnail = createScreenshot(current);
3583
The Android Open Source Project0c908882009-03-03 19:32:16 -08003584 // Just in case the user opens bookmarks before a page finishes loading
3585 // so the current history item, and therefore the page, is null.
3586 if (null == url) {
3587 url = mLastEnteredUrl;
3588 // This can happen.
3589 if (null == url) {
3590 url = mSettings.getHomePage();
3591 }
3592 }
3593 // In case the web page has not yet received its associated title.
3594 if (title == null) {
3595 title = url;
3596 }
3597 intent.putExtra("title", title);
3598 intent.putExtra("url", url);
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01003599 intent.putExtra("thumbnail", thumbnail);
Leon Scroggins30444232009-09-04 18:36:20 -04003600 // Disable opening in a new window if we have maxed out the windows
Grace Kloba22ac16e2009-10-07 18:00:23 -07003601 intent.putExtra("disable_new_window", !mTabControl.canCreateNewTab());
Patrick Scott3918d442009-08-04 13:22:29 -04003602 intent.putExtra("touch_icon_url", current.getTouchIconUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003603 if (startWithHistory) {
3604 intent.putExtra(CombinedBookmarkHistoryActivity.STARTING_TAB,
3605 CombinedBookmarkHistoryActivity.HISTORY_TAB);
3606 }
3607 startActivityForResult(intent, COMBO_PAGE);
3608 }
3609
3610 // Called when loading from context menu or LOAD_URL message
Leon Scroggins92472e82010-02-17 16:32:28 -05003611 private void loadUrlFromContext(WebView view, String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003612 // In case the user enters nothing.
3613 if (url != null && url.length() != 0 && view != null) {
3614 url = smartUrlFilter(url);
Grace Kloba22ac16e2009-10-07 18:00:23 -07003615 if (!view.getWebViewClient().shouldOverrideUrlLoading(view, url)) {
Leon Scroggins92472e82010-02-17 16:32:28 -05003616 loadUrl(view, url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003617 }
3618 }
3619 }
3620
Leon Scroggins92472e82010-02-17 16:32:28 -05003621 /**
3622 * Load the URL into the given WebView and update the title bar
3623 * to reflect the new load. Call this instead of WebView.loadUrl
3624 * directly.
3625 * @param view The WebView used to load url.
3626 * @param url The URL to load.
3627 */
3628 private void loadUrl(WebView view, String url) {
3629 updateTitleBarForNewLoad(view, url);
3630 view.loadUrl(url);
3631 }
3632
3633 /**
3634 * Load UrlData into a Tab and update the title bar to reflect the new
3635 * load. Call this instead of UrlData.loadIn directly.
3636 * @param t The Tab used to load.
3637 * @param data The UrlData being loaded.
3638 */
3639 private void loadUrlDataIn(Tab t, UrlData data) {
3640 updateTitleBarForNewLoad(t.getWebView(), data.mUrl);
3641 data.loadIn(t);
3642 }
3643
3644 /**
3645 * If the WebView is the top window, update the title bar to reflect
3646 * loading the new URL. i.e. set its text, clear the favicon (which
3647 * will be set once the page begins loading), and set the progress to
3648 * INITIAL_PROGRESS to show that the page has begun to load. Called
3649 * by loadUrl and loadUrlDataIn.
3650 * @param view The WebView that is starting a load.
3651 * @param url The URL that is being loaded.
3652 */
3653 private void updateTitleBarForNewLoad(WebView view, String url) {
3654 if (view == getTopWindow()) {
3655 setUrlTitle(url, null);
3656 setFavicon(null);
3657 onProgressChanged(view, INITIAL_PROGRESS);
3658 }
3659 }
3660
The Android Open Source Project0c908882009-03-03 19:32:16 -08003661 private String smartUrlFilter(Uri inUri) {
3662 if (inUri != null) {
3663 return smartUrlFilter(inUri.toString());
3664 }
3665 return null;
3666 }
3667
Feng Qianb34f87a2009-03-24 21:27:26 -07003668 protected static final Pattern ACCEPTED_URI_SCHEMA = Pattern.compile(
The Android Open Source Project0c908882009-03-03 19:32:16 -08003669 "(?i)" + // switch on case insensitive matching
3670 "(" + // begin group for schema
3671 "(?:http|https|file):\\/\\/" +
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003672 "|(?:inline|data|about|content|javascript):" +
The Android Open Source Project0c908882009-03-03 19:32:16 -08003673 ")" +
3674 "(.*)" );
3675
3676 /**
3677 * Attempts to determine whether user input is a URL or search
3678 * terms. Anything with a space is passed to search.
3679 *
3680 * Converts to lowercase any mistakenly uppercased schema (i.e.,
3681 * "Http://" converts to "http://"
3682 *
3683 * @return Original or modified URL
3684 *
3685 */
3686 String smartUrlFilter(String url) {
3687
3688 String inUrl = url.trim();
3689 boolean hasSpace = inUrl.indexOf(' ') != -1;
3690
3691 Matcher matcher = ACCEPTED_URI_SCHEMA.matcher(inUrl);
3692 if (matcher.matches()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003693 // force scheme to lowercase
3694 String scheme = matcher.group(1);
3695 String lcScheme = scheme.toLowerCase();
3696 if (!lcScheme.equals(scheme)) {
Mitsuru Oshima123ecfb2009-05-18 19:11:14 -07003697 inUrl = lcScheme + matcher.group(2);
3698 }
3699 if (hasSpace) {
3700 inUrl = inUrl.replace(" ", "%20");
The Android Open Source Project0c908882009-03-03 19:32:16 -08003701 }
3702 return inUrl;
3703 }
3704 if (hasSpace) {
Satish Sampath565505b2009-05-29 15:37:27 +01003705 // FIXME: Is this the correct place to add to searches?
3706 // what if someone else calls this function?
3707 int shortcut = parseUrlShortcut(inUrl);
3708 if (shortcut != SHORTCUT_INVALID) {
3709 Browser.addSearchUrl(mResolver, inUrl);
3710 String query = inUrl.substring(2);
3711 switch (shortcut) {
3712 case SHORTCUT_GOOGLE_SEARCH:
Grace Kloba47fdfdb2009-06-30 11:15:34 -07003713 return URLUtil.composeSearchUrl(query, QuickSearch_G, QUERY_PLACE_HOLDER);
Satish Sampath565505b2009-05-29 15:37:27 +01003714 case SHORTCUT_WIKIPEDIA_SEARCH:
3715 return URLUtil.composeSearchUrl(query, QuickSearch_W, QUERY_PLACE_HOLDER);
3716 case SHORTCUT_DICTIONARY_SEARCH:
3717 return URLUtil.composeSearchUrl(query, QuickSearch_D, QUERY_PLACE_HOLDER);
3718 case SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH:
The Android Open Source Project0c908882009-03-03 19:32:16 -08003719 // FIXME: we need location in this case
Satish Sampath565505b2009-05-29 15:37:27 +01003720 return URLUtil.composeSearchUrl(query, QuickSearch_L, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003721 }
3722 }
3723 } else {
Dan Egnor5ee906c2009-11-18 12:11:49 -08003724 if (Patterns.WEB_URL.matcher(inUrl).matches()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003725 return URLUtil.guessUrl(inUrl);
3726 }
3727 }
3728
3729 Browser.addSearchUrl(mResolver, inUrl);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07003730 return URLUtil.composeSearchUrl(inUrl, QuickSearch_G, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003731 }
3732
Ben Murdochbff2d602009-07-01 20:19:05 +01003733 /* package */ void setShouldShowErrorConsole(boolean flag) {
3734 if (flag == mShouldShowErrorConsole) {
3735 // Nothing to do.
3736 return;
3737 }
3738
3739 mShouldShowErrorConsole = flag;
3740
Grace Kloba22ac16e2009-10-07 18:00:23 -07003741 ErrorConsoleView errorConsole = mTabControl.getCurrentTab()
3742 .getErrorConsole(true);
Ben Murdochbff2d602009-07-01 20:19:05 +01003743
3744 if (flag) {
3745 // Setting the show state of the console will cause it's the layout to be inflated.
3746 if (errorConsole.numberOfErrors() > 0) {
3747 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
3748 } else {
3749 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
3750 }
3751
3752 // Now we can add it to the main view.
3753 mErrorConsoleContainer.addView(errorConsole,
Romain Guy15b8ec62010-01-08 15:06:43 -08003754 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
Ben Murdochbff2d602009-07-01 20:19:05 +01003755 ViewGroup.LayoutParams.WRAP_CONTENT));
3756 } else {
3757 mErrorConsoleContainer.removeView(errorConsole);
3758 }
3759
3760 }
3761
Grace Kloba22ac16e2009-10-07 18:00:23 -07003762 boolean shouldShowErrorConsole() {
3763 return mShouldShowErrorConsole;
3764 }
3765
Andrei Popescu163ab742009-10-20 17:58:23 +01003766 private void setStatusBarVisibility(boolean visible) {
3767 int flag = visible ? 0 : WindowManager.LayoutParams.FLAG_FULLSCREEN;
3768 getWindow().setFlags(flag, WindowManager.LayoutParams.FLAG_FULLSCREEN);
3769 }
3770
Andrei Popescu56199cc2010-01-12 22:39:16 +00003771
3772 private void sendNetworkType(String type, String subtype) {
3773 WebView w = mTabControl.getCurrentWebView();
3774 if (w != null) {
3775 w.setNetworkType(type, subtype);
3776 }
3777 }
3778
Andrei Popescu30995e72010-02-09 16:59:58 +00003779 private void packageChanged(String packageName, boolean wasAdded) {
3780 WebView w = mTabControl.getCurrentWebView();
3781 if (w == null) {
3782 return;
3783 }
3784
3785 if (wasAdded) {
3786 w.addPackageName(packageName);
3787 } else {
3788 w.removePackageName(packageName);
3789 }
3790 }
3791
3792 private void addPackageNames(Set<String> packageNames) {
3793 WebView w = mTabControl.getCurrentWebView();
3794 if (w == null) {
3795 return;
3796 }
3797
3798 w.addPackageNames(packageNames);
3799 }
3800
3801 private void getInstalledPackages() {
3802 AsyncTask<Void, Void, Set<String> > task =
3803 new AsyncTask<Void, Void, Set<String> >() {
3804 protected Set<String> doInBackground(Void... unused) {
3805 Set<String> installedPackages = new HashSet<String>();
3806 PackageManager pm = BrowserActivity.this.getPackageManager();
3807 if (pm != null) {
3808 List<PackageInfo> packages = pm.getInstalledPackages(0);
3809 for (PackageInfo p : packages) {
3810 if (BrowserActivity.this.sGoogleApps.contains(p.packageName)) {
3811 installedPackages.add(p.packageName);
3812 }
3813 }
3814 }
3815
3816 return installedPackages;
3817 }
3818
3819 // Executes on the UI thread
3820 protected void onPostExecute(Set<String> installedPackages) {
3821 addPackageNames(installedPackages);
3822 }
3823 };
3824 task.execute();
3825 }
3826
Grace Klobaeb6eef42009-09-15 17:56:32 -07003827 final static int LOCK_ICON_UNSECURE = 0;
3828 final static int LOCK_ICON_SECURE = 1;
3829 final static int LOCK_ICON_MIXED = 2;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003830
The Android Open Source Project0c908882009-03-03 19:32:16 -08003831 private BrowserSettings mSettings;
3832 private TabControl mTabControl;
3833 private ContentResolver mResolver;
3834 private FrameLayout mContentView;
Andrei Popescuadc008d2009-06-26 14:11:30 +01003835 private View mCustomView;
3836 private FrameLayout mCustomViewContainer;
Andrei Popescuc9b55562009-07-07 10:51:15 +01003837 private WebChromeClient.CustomViewCallback mCustomViewCallback;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003838
3839 // FIXME, temp address onPrepareMenu performance problem. When we move everything out of
3840 // view, we should rewrite this.
3841 private int mCurrentMenuState = 0;
3842 private int mMenuState = R.id.MAIN_MENU;
Andrei Popescuadc008d2009-06-26 14:11:30 +01003843 private int mOldMenuState = EMPTY_MENU;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003844 private static final int EMPTY_MENU = -1;
3845 private Menu mMenu;
3846
3847 private FindDialog mFindDialog;
Cary Clark2c326e62010-08-19 18:40:57 -04003848 private SelectDialog mSelectDialog;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003849 // Used to prevent chording to result in firing two shortcuts immediately
3850 // one after another. Fixes bug 1211714.
3851 boolean mCanChord;
3852
3853 private boolean mInLoad;
3854 private boolean mIsNetworkUp;
Ben Murdochb7cc8b42009-09-28 10:59:09 +01003855 private boolean mDidStopLoad;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003856
Cary Clark1f10cbf2010-03-22 11:45:23 -04003857 /* package */ boolean mActivityInPause = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003858
3859 private boolean mMenuIsDown;
3860
The Android Open Source Project0c908882009-03-03 19:32:16 -08003861 private static boolean mInTrace;
3862
3863 // Performance probe
3864 private static final int[] SYSTEM_CPU_FORMAT = new int[] {
3865 Process.PROC_SPACE_TERM | Process.PROC_COMBINE,
3866 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 1: user time
3867 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 2: nice time
3868 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 3: sys time
3869 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 4: idle time
3870 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 5: iowait time
3871 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 6: irq time
3872 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG // 7: softirq time
3873 };
3874
3875 private long mStart;
3876 private long mProcessStart;
3877 private long mUserStart;
3878 private long mSystemStart;
3879 private long mIdleStart;
3880 private long mIrqStart;
3881
3882 private long mUiStart;
3883
3884 private Drawable mMixLockIcon;
3885 private Drawable mSecLockIcon;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003886
3887 /* hold a ref so we can auto-cancel if necessary */
3888 private AlertDialog mAlertDialog;
3889
The Android Open Source Project0c908882009-03-03 19:32:16 -08003890 // The up-to-date URL and title (these can be different from those stored
3891 // in WebView, since it takes some time for the information in WebView to
3892 // get updated)
3893 private String mUrl;
3894 private String mTitle;
3895
3896 // As PageInfo has different style for landscape / portrait, we have
3897 // to re-open it when configuration changed
3898 private AlertDialog mPageInfoDialog;
Grace Kloba22ac16e2009-10-07 18:00:23 -07003899 private Tab mPageInfoView;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003900 // If the Page-Info dialog is launched from the SSL-certificate-on-error
3901 // dialog, we should not just dismiss it, but should get back to the
3902 // SSL-certificate-on-error dialog. This flag is used to store this state
Leon Scrogginsc7b92f82010-01-11 18:17:31 -05003903 private boolean mPageInfoFromShowSSLCertificateOnError;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003904
3905 // as SSLCertificateOnError has different style for landscape / portrait,
3906 // we have to re-open it when configuration changed
3907 private AlertDialog mSSLCertificateOnErrorDialog;
3908 private WebView mSSLCertificateOnErrorView;
3909 private SslErrorHandler mSSLCertificateOnErrorHandler;
3910 private SslError mSSLCertificateOnErrorError;
3911
3912 // as SSLCertificate has different style for landscape / portrait, we
3913 // have to re-open it when configuration changed
3914 private AlertDialog mSSLCertificateDialog;
Grace Kloba22ac16e2009-10-07 18:00:23 -07003915 private Tab mSSLCertificateView;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003916
3917 // as HttpAuthentication has different style for landscape / portrait, we
3918 // have to re-open it when configuration changed
3919 private AlertDialog mHttpAuthenticationDialog;
3920 private HttpAuthHandler mHttpAuthHandler;
3921
3922 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_PARAMS =
3923 new FrameLayout.LayoutParams(
Romain Guy15b8ec62010-01-08 15:06:43 -08003924 ViewGroup.LayoutParams.MATCH_PARENT,
3925 ViewGroup.LayoutParams.MATCH_PARENT);
Andrei Popescuadc008d2009-06-26 14:11:30 +01003926 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_GRAVITY_CENTER =
3927 new FrameLayout.LayoutParams(
Romain Guy15b8ec62010-01-08 15:06:43 -08003928 ViewGroup.LayoutParams.MATCH_PARENT,
3929 ViewGroup.LayoutParams.MATCH_PARENT,
Andrei Popescuadc008d2009-06-26 14:11:30 +01003930 Gravity.CENTER);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07003931 // Google search
3932 final static String QuickSearch_G = "http://www.google.com/m?q=%s";
The Android Open Source Project0c908882009-03-03 19:32:16 -08003933 // Wikipedia search
3934 final static String QuickSearch_W = "http://en.wikipedia.org/w/index.php?search=%s&go=Go";
3935 // Dictionary search
3936 final static String QuickSearch_D = "http://dictionary.reference.com/search?q=%s";
3937 // Google Mobile Local search
3938 final static String QuickSearch_L = "http://www.google.com/m/search?site=local&q=%s&near=mountain+view";
3939
3940 final static String QUERY_PLACE_HOLDER = "%s";
3941
3942 // "source" parameter for Google search through search key
3943 final static String GOOGLE_SEARCH_SOURCE_SEARCHKEY = "browser-key";
3944 // "source" parameter for Google search through goto menu
3945 final static String GOOGLE_SEARCH_SOURCE_GOTO = "browser-goto";
3946 // "source" parameter for Google search through simplily type
3947 final static String GOOGLE_SEARCH_SOURCE_TYPE = "browser-type";
3948 // "source" parameter for Google search suggested by the browser
3949 final static String GOOGLE_SEARCH_SOURCE_SUGGEST = "browser-suggest";
3950 // "source" parameter for Google search from unknown source
3951 final static String GOOGLE_SEARCH_SOURCE_UNKNOWN = "unknown";
3952
3953 private final static String LOGTAG = "browser";
3954
The Android Open Source Project0c908882009-03-03 19:32:16 -08003955 private String mLastEnteredUrl;
3956
3957 private PowerManager.WakeLock mWakeLock;
3958 private final static int WAKELOCK_TIMEOUT = 5 * 60 * 1000; // 5 minutes
3959
3960 private Toast mStopToast;
3961
Leon Scroggins68579392009-09-15 15:31:54 -04003962 private TitleBar mTitleBar;
Leon Scroggins81db3662009-06-04 17:45:11 -04003963
Ben Murdochbff2d602009-07-01 20:19:05 +01003964 private LinearLayout mErrorConsoleContainer = null;
3965 private boolean mShouldShowErrorConsole = false;
3966
The Android Open Source Project0c908882009-03-03 19:32:16 -08003967 // As the ids are dynamically created, we can't guarantee that they will
3968 // be in sequence, so this static array maps ids to a window number.
3969 final static private int[] WINDOW_SHORTCUT_ID_ARRAY =
3970 { R.id.window_one_menu_id, R.id.window_two_menu_id, R.id.window_three_menu_id,
3971 R.id.window_four_menu_id, R.id.window_five_menu_id, R.id.window_six_menu_id,
3972 R.id.window_seven_menu_id, R.id.window_eight_menu_id };
3973
3974 // monitor platform changes
3975 private IntentFilter mNetworkStateChangedFilter;
3976 private BroadcastReceiver mNetworkStateIntentReceiver;
3977
Grace Klobab4da0ad2009-05-14 14:45:40 -07003978 private BroadcastReceiver mPackageInstallationReceiver;
3979
Bjorn Bringerta7611812010-03-24 11:12:02 +00003980 private SystemAllowGeolocationOrigins mSystemAllowGeolocationOrigins;
3981
The Android Open Source Project0c908882009-03-03 19:32:16 -08003982 // activity requestCode
Nicolas Roard78a98e42009-05-11 13:34:17 +01003983 final static int COMBO_PAGE = 1;
3984 final static int DOWNLOAD_PAGE = 2;
3985 final static int PREFERENCES_PAGE = 3;
Leon Scroggins8d5fa432009-10-02 15:55:59 -04003986 final static int FILE_SELECTED = 4;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003987
Andrei Popescu540035d2009-09-18 18:59:20 +01003988 // the default <video> poster
3989 private Bitmap mDefaultVideoPoster;
3990 // the video progress view
3991 private View mVideoProgressView;
3992
Andrei Popescu30995e72010-02-09 16:59:58 +00003993 // The Google packages we monitor for the navigator.isApplicationInstalled()
3994 // API. Add as needed.
3995 private static Set<String> sGoogleApps;
3996 static {
3997 sGoogleApps = new HashSet<String>();
3998 sGoogleApps.add("com.google.android.youtube");
3999 }
4000
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004001 /**
4002 * A UrlData class to abstract how the content will be set to WebView.
4003 * This base class uses loadUrl to show the content.
4004 */
Leon Scroggins6eac63e2010-03-15 18:19:14 -04004005 /* package */ static class UrlData {
Grace Kloba068e48b2010-01-26 18:11:27 -08004006 final String mUrl;
4007 final Map<String, String> mHeaders;
Leon Scroggins58d56c62010-01-28 15:12:40 -05004008 final Intent mVoiceIntent;
Grace Kloba60e095c2009-06-16 11:50:55 -07004009
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004010 UrlData(String url) {
4011 this.mUrl = url;
Grace Kloba068e48b2010-01-26 18:11:27 -08004012 this.mHeaders = null;
Leon Scroggins58d56c62010-01-28 15:12:40 -05004013 this.mVoiceIntent = null;
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004014 }
Grace Kloba60e095c2009-06-16 11:50:55 -07004015
Leon Scroggins58d56c62010-01-28 15:12:40 -05004016 UrlData(String url, Map<String, String> headers, Intent intent) {
Grace Kloba068e48b2010-01-26 18:11:27 -08004017 this.mUrl = url;
4018 this.mHeaders = headers;
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -05004019 if (RecognizerResultsIntent.ACTION_VOICE_SEARCH_RESULTS
4020 .equals(intent.getAction())) {
Leon Scroggins58d56c62010-01-28 15:12:40 -05004021 this.mVoiceIntent = intent;
4022 } else {
4023 this.mVoiceIntent = null;
4024 }
Grace Kloba60e095c2009-06-16 11:50:55 -07004025 }
4026
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004027 boolean isEmpty() {
Leon Scroggins58d56c62010-01-28 15:12:40 -05004028 return mVoiceIntent == null && (mUrl == null || mUrl.length() == 0);
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004029 }
4030
Leon Scroggins92472e82010-02-17 16:32:28 -05004031 /**
4032 * Load this UrlData into the given Tab. Use loadUrlDataIn to update
4033 * the title bar as well.
4034 */
Leon Scroggins58d56c62010-01-28 15:12:40 -05004035 public void loadIn(Tab t) {
4036 if (mVoiceIntent != null) {
4037 t.activateVoiceSearchMode(mVoiceIntent);
4038 } else {
4039 t.getWebView().loadUrl(mUrl, mHeaders);
4040 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004041 }
4042 };
4043
Leon Scroggins1f005d32009-08-10 17:36:42 -04004044 /* package */ static final UrlData EMPTY_URL_DATA = new UrlData(null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004045}