blob: f9558b919fed6ba4d42f5a5cd884bf0d58fb36b4 [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);
Patrick Scott9d53da02010-02-19 10:19:01 -0500542 loadUrlDataIn(current, urlData);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800543 }
544 }
545 }
546
Satish Sampath565505b2009-05-29 15:37:27 +0100547 private int parseUrlShortcut(String url) {
548 if (url == null) return SHORTCUT_INVALID;
549
550 // FIXME: quick search, need to be customized by setting
551 if (url.length() > 2 && url.charAt(1) == ' ') {
552 switch (url.charAt(0)) {
553 case 'g': return SHORTCUT_GOOGLE_SEARCH;
554 case 'w': return SHORTCUT_WIKIPEDIA_SEARCH;
555 case 'd': return SHORTCUT_DICTIONARY_SEARCH;
556 case 'l': return SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH;
557 }
558 }
559 return SHORTCUT_INVALID;
560 }
561
562 /**
563 * Launches the default web search activity with the query parameters if the given intent's data
564 * are identified as plain search terms and not URLs/shortcuts.
565 * @return true if the intent was handled and web search activity was launched, false if not.
566 */
567 private boolean handleWebSearchIntent(Intent intent) {
568 if (intent == null) return false;
569
570 String url = null;
571 final String action = intent.getAction();
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -0500572 if (RecognizerResultsIntent.ACTION_VOICE_SEARCH_RESULTS.equals(
573 action)) {
Leon Scroggins58d56c62010-01-28 15:12:40 -0500574 return false;
575 }
Satish Sampath565505b2009-05-29 15:37:27 +0100576 if (Intent.ACTION_VIEW.equals(action)) {
Grace Kloba1e705052009-09-29 13:13:36 -0700577 Uri data = intent.getData();
578 if (data != null) url = data.toString();
Satish Sampath565505b2009-05-29 15:37:27 +0100579 } else if (Intent.ACTION_SEARCH.equals(action)
580 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
581 || Intent.ACTION_WEB_SEARCH.equals(action)) {
582 url = intent.getStringExtra(SearchManager.QUERY);
583 }
Bjorn Bringert04851702009-09-22 10:36:01 +0100584 return handleWebSearchRequest(url, intent.getBundleExtra(SearchManager.APP_DATA),
585 intent.getStringExtra(SearchManager.EXTRA_DATA_KEY));
Satish Sampath565505b2009-05-29 15:37:27 +0100586 }
587
588 /**
589 * Launches the default web search activity with the query parameters if the given url string
590 * was identified as plain search terms and not URL/shortcut.
591 * @return true if the request was handled and web search activity was launched, false if not.
592 */
Bjorn Bringert04851702009-09-22 10:36:01 +0100593 private boolean handleWebSearchRequest(String inUrl, Bundle appData, String extraData) {
Satish Sampath565505b2009-05-29 15:37:27 +0100594 if (inUrl == null) return false;
595
596 // In general, we shouldn't modify URL from Intent.
597 // But currently, we get the user-typed URL from search box as well.
598 String url = fixUrl(inUrl).trim();
599
600 // URLs and site specific search shortcuts are handled by the regular flow of control, so
601 // return early.
Dan Egnor5ee906c2009-11-18 12:11:49 -0800602 if (Patterns.WEB_URL.matcher(url).matches()
Satish Sampathbc5b9f32009-06-04 18:21:40 +0100603 || ACCEPTED_URI_SCHEMA.matcher(url).matches()
Satish Sampath565505b2009-05-29 15:37:27 +0100604 || parseUrlShortcut(url) != SHORTCUT_INVALID) {
605 return false;
606 }
607
Leon Scroggins8d06e362010-03-24 14:45:57 -0400608 final ContentResolver cr = mResolver;
609 final String newUrl = url;
610 new AsyncTask<Void, Void, Void>() {
611 protected Void doInBackground(Void... unused) {
612 Browser.updateVisitedHistory(cr, newUrl, false);
613 Browser.addSearchUrl(cr, newUrl);
614 return null;
615 }
616 }.execute();
Satish Sampath565505b2009-05-29 15:37:27 +0100617
618 Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);
619 intent.addCategory(Intent.CATEGORY_DEFAULT);
620 intent.putExtra(SearchManager.QUERY, url);
Satish Sampath15e9f2d2009-06-23 22:29:49 +0100621 if (appData != null) {
622 intent.putExtra(SearchManager.APP_DATA, appData);
623 }
Bjorn Bringert04851702009-09-22 10:36:01 +0100624 if (extraData != null) {
625 intent.putExtra(SearchManager.EXTRA_DATA_KEY, extraData);
626 }
Grace Klobacc634032009-07-28 15:58:19 -0700627 intent.putExtra(Browser.EXTRA_APPLICATION_ID, getPackageName());
Satish Sampath565505b2009-05-29 15:37:27 +0100628 startActivity(intent);
629
630 return true;
631 }
632
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700633 private UrlData getUrlDataFromIntent(Intent intent) {
Leon Scroggins58d56c62010-01-28 15:12:40 -0500634 String url = "";
Grace Kloba068e48b2010-01-26 18:11:27 -0800635 Map<String, String> headers = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800636 if (intent != null) {
637 final String action = intent.getAction();
638 if (Intent.ACTION_VIEW.equals(action)) {
639 url = smartUrlFilter(intent.getData());
640 if (url != null && url.startsWith("content:")) {
641 /* Append mimetype so webview knows how to display */
642 String mimeType = intent.resolveType(getContentResolver());
643 if (mimeType != null) {
644 url += "?" + mimeType;
645 }
646 }
Grace Kloba068e48b2010-01-26 18:11:27 -0800647 if (url != null && url.startsWith("http")) {
Grace Kloba00f54c52010-01-27 14:53:51 -0800648 final Bundle pairs = intent
649 .getBundleExtra(Browser.EXTRA_HEADERS);
Grace Kloba2d508ed2010-01-28 11:39:15 -0800650 if (pairs != null && !pairs.isEmpty()) {
Grace Kloba00f54c52010-01-27 14:53:51 -0800651 Iterator<String> iter = pairs.keySet().iterator();
Grace Kloba068e48b2010-01-26 18:11:27 -0800652 headers = new HashMap<String, String>();
Grace Kloba00f54c52010-01-27 14:53:51 -0800653 while (iter.hasNext()) {
654 String key = iter.next();
655 headers.put(key, pairs.getString(key));
Grace Kloba068e48b2010-01-26 18:11:27 -0800656 }
657 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700658 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800659 } else if (Intent.ACTION_SEARCH.equals(action)
660 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
661 || Intent.ACTION_WEB_SEARCH.equals(action)) {
662 url = intent.getStringExtra(SearchManager.QUERY);
663 if (url != null) {
664 mLastEnteredUrl = url;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800665 // In general, we shouldn't modify URL from Intent.
666 // But currently, we get the user-typed URL from search box as well.
667 url = fixUrl(url);
668 url = smartUrlFilter(url);
Leon Scroggins8d06e362010-03-24 14:45:57 -0400669 final ContentResolver cr = mResolver;
670 final String newUrl = url;
671 new AsyncTask<Void, Void, Void>() {
672 protected Void doInBackground(Void... unused) {
673 Browser.updateVisitedHistory(cr, newUrl, false);
674 return null;
675 }
676 }.execute();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800677 String searchSource = "&source=android-" + GOOGLE_SEARCH_SOURCE_SUGGEST + "&";
678 if (url.contains(searchSource)) {
679 String source = null;
680 final Bundle appData = intent.getBundleExtra(SearchManager.APP_DATA);
681 if (appData != null) {
Bjorn Bringert10d1cca2010-02-10 14:22:12 +0000682 source = appData.getString(Search.SOURCE);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800683 }
684 if (TextUtils.isEmpty(source)) {
685 source = GOOGLE_SEARCH_SOURCE_UNKNOWN;
686 }
687 url = url.replace(searchSource, "&source=android-"+source+"&");
688 }
689 }
690 }
691 }
Leon Scroggins58d56c62010-01-28 15:12:40 -0500692 return new UrlData(url, headers, intent);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800693 }
Leon Scroggins58d56c62010-01-28 15:12:40 -0500694 /* package */ void showVoiceTitleBar(String title) {
695 mTitleBar.setInVoiceMode(true);
696 mFakeTitleBar.setInVoiceMode(true);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800697
Leon Scroggins58d56c62010-01-28 15:12:40 -0500698 mTitleBar.setDisplayTitle(title);
699 mFakeTitleBar.setDisplayTitle(title);
700 }
701 /* package */ void revertVoiceTitleBar() {
702 mTitleBar.setInVoiceMode(false);
703 mFakeTitleBar.setInVoiceMode(false);
704
Leon Scroggins003a5dd2010-03-10 12:13:14 -0500705 mTitleBar.setDisplayTitle(mUrl);
706 mFakeTitleBar.setDisplayTitle(mUrl);
Leon Scroggins58d56c62010-01-28 15:12:40 -0500707 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800708 /* package */ static String fixUrl(String inUrl) {
Cary Clark652ff872009-09-10 13:34:44 -0400709 // FIXME: Converting the url to lower case
710 // duplicates functionality in smartUrlFilter().
711 // However, changing all current callers of fixUrl to
712 // call smartUrlFilter in addition may have unwanted
713 // consequences, and is deferred for now.
714 int colon = inUrl.indexOf(':');
715 boolean allLower = true;
716 for (int index = 0; index < colon; index++) {
717 char ch = inUrl.charAt(index);
718 if (!Character.isLetter(ch)) {
719 break;
720 }
721 allLower &= Character.isLowerCase(ch);
722 if (index == colon - 1 && !allLower) {
723 inUrl = inUrl.substring(0, colon).toLowerCase()
724 + inUrl.substring(colon);
725 }
726 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800727 if (inUrl.startsWith("http://") || inUrl.startsWith("https://"))
728 return inUrl;
729 if (inUrl.startsWith("http:") ||
730 inUrl.startsWith("https:")) {
731 if (inUrl.startsWith("http:/") || inUrl.startsWith("https:/")) {
732 inUrl = inUrl.replaceFirst("/", "//");
733 } else inUrl = inUrl.replaceFirst(":", "://");
734 }
735 return inUrl;
736 }
737
Grace Kloba22ac16e2009-10-07 18:00:23 -0700738 @Override
739 protected void onResume() {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800740 super.onResume();
Dave Bort31a6d1c2009-04-13 15:56:49 -0700741 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800742 Log.v(LOGTAG, "BrowserActivity.onResume: this=" + this);
743 }
744
745 if (!mActivityInPause) {
746 Log.e(LOGTAG, "BrowserActivity is already resumed.");
747 return;
748 }
749
Mike Reed7bfa63b2009-05-28 11:08:32 -0400750 mTabControl.resumeCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800751 mActivityInPause = false;
Mike Reed7bfa63b2009-05-28 11:08:32 -0400752 resumeWebViewTimers();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800753
754 if (mWakeLock.isHeld()) {
755 mHandler.removeMessages(RELEASE_WAKELOCK);
756 mWakeLock.release();
757 }
758
The Android Open Source Project0c908882009-03-03 19:32:16 -0800759 registerReceiver(mNetworkStateIntentReceiver,
760 mNetworkStateChangedFilter);
761 WebView.enablePlatformNotifications();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800762 }
763
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400764 /**
765 * Since the actual title bar is embedded in the WebView, and removing it
Leon Scrogginsfe87bd32009-10-06 10:10:00 -0400766 * would change its appearance, use a different TitleBar to show overlayed
767 * at the top of the screen, when the menu is open or the page is loading.
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400768 */
769 private TitleBar mFakeTitleBar;
770
771 /**
772 * Keeps track of whether the options menu is open. This is important in
773 * determining whether to show or hide the title bar overlay.
774 */
775 private boolean mOptionsMenuOpen;
776
777 /**
778 * Only meaningful when mOptionsMenuOpen is true. This variable keeps track
779 * of whether the configuration has changed. The first onMenuOpened call
780 * after a configuration change is simply a reopening of the same menu
781 * (i.e. mIconView did not change).
782 */
783 private boolean mConfigChanged;
784
785 /**
786 * Whether or not the options menu is in its smaller, icon menu form. When
787 * true, we want the title bar overlay to be up. When false, we do not.
788 * Only meaningful if mOptionsMenuOpen is true.
789 */
790 private boolean mIconView;
791
Leon Scrogginsa81a7642009-08-31 17:05:41 -0400792 @Override
793 public boolean onMenuOpened(int featureId, Menu menu) {
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400794 if (Window.FEATURE_OPTIONS_PANEL == featureId) {
795 if (mOptionsMenuOpen) {
796 if (mConfigChanged) {
797 // We do not need to make any changes to the state of the
798 // title bar, since the only thing that happened was a
799 // change in orientation
800 mConfigChanged = false;
801 } else {
802 if (mIconView) {
803 // Switching the menu to expanded view, so hide the
804 // title bar.
805 hideFakeTitleBar();
806 mIconView = false;
807 } else {
808 // Switching the menu back to icon view, so show the
809 // title bar once again.
810 showFakeTitleBar();
811 mIconView = true;
812 }
813 }
814 } else {
815 // The options menu is closed, so open it, and show the title
816 showFakeTitleBar();
817 mOptionsMenuOpen = true;
818 mConfigChanged = false;
819 mIconView = true;
820 }
821 }
Leon Scrogginsa81a7642009-08-31 17:05:41 -0400822 return true;
823 }
824
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400825 private void showFakeTitleBar() {
Leon Scrogginsfe87bd32009-10-06 10:10:00 -0400826 if (mFakeTitleBar.getParent() == null && mActiveTabsPage == null
Grace Kloba847c25b2010-03-30 16:00:26 -0700827 && !mActivityInPause) {
828 WebView mainView = mTabControl.getCurrentWebView();
829 // if there is no current WebView, don't show the faked title bar;
Grace Kloba65190702010-04-02 23:37:26 -0700830 if (mainView == null) {
Cary Clarka0464552009-09-29 13:00:45 -0400831 return;
832 }
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400833
834 WindowManager manager
835 = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
836
837 // Add the title bar to the window manager so it can receive touches
838 // while the menu is up
839 WindowManager.LayoutParams params
840 = new WindowManager.LayoutParams(
Romain Guy15b8ec62010-01-08 15:06:43 -0800841 ViewGroup.LayoutParams.MATCH_PARENT,
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400842 ViewGroup.LayoutParams.WRAP_CONTENT,
Grace Kloba847c25b2010-03-30 16:00:26 -0700843 WindowManager.LayoutParams.TYPE_APPLICATION,
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400844 WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
Leon Scroggins68549862009-09-21 16:02:01 -0400845 PixelFormat.TRANSLUCENT);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400846 params.gravity = Gravity.TOP;
Grace Kloba847c25b2010-03-30 16:00:26 -0700847 boolean atTop = mainView.getScrollY() == 0;
Leon Scroggins83932c72009-09-30 11:55:54 -0400848 params.windowAnimations = atTop ? 0 : R.style.TitleBar;
Grace Kloba13f9ace2010-03-18 21:44:14 -0700849 manager.addView(mFakeTitleBar, params);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400850 }
851 }
852
853 @Override
854 public void onOptionsMenuClosed(Menu menu) {
855 mOptionsMenuOpen = false;
Leon Scrogginsa27ff192009-09-14 12:58:04 -0400856 if (!mInLoad) {
857 hideFakeTitleBar();
858 } else if (!mIconView) {
859 // The page is currently loading, and we are in expanded mode, so
860 // we were not showing the menu. Show it once again. It will be
861 // removed when the page finishes.
862 showFakeTitleBar();
863 }
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400864 }
Grace Kloba22ac16e2009-10-07 18:00:23 -0700865
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400866 private void hideFakeTitleBar() {
Leon Scrogginsfe87bd32009-10-06 10:10:00 -0400867 if (mFakeTitleBar.getParent() == null) return;
Leon Scroggins20329572009-09-23 17:42:41 -0400868 WindowManager.LayoutParams params = (WindowManager.LayoutParams)
Grace Kloba13f9ace2010-03-18 21:44:14 -0700869 mFakeTitleBar.getLayoutParams();
Leon Scroggins20329572009-09-23 17:42:41 -0400870 WebView mainView = mTabControl.getCurrentWebView();
871 // Although we decided whether or not to animate based on the current
872 // scroll position, the scroll position may have changed since the
873 // fake title bar was displayed. Make sure it has the appropriate
874 // animation/lack thereof before removing.
875 params.windowAnimations = mainView != null && mainView.getScrollY() == 0
Leon Scroggins83932c72009-09-30 11:55:54 -0400876 ? 0 : R.style.TitleBar;
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400877 WindowManager manager
878 = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
Grace Kloba13f9ace2010-03-18 21:44:14 -0700879 manager.updateViewLayout(mFakeTitleBar, params);
880 manager.removeView(mFakeTitleBar);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400881 }
882
The Android Open Source Project0c908882009-03-03 19:32:16 -0800883 /**
Leon Scrogginsc6fa1102009-09-21 10:40:01 -0400884 * Special method for the fake title bar to call when displaying its context
885 * menu, since it is in its own Window, and its parent does not show a
886 * context menu.
887 */
888 /* package */ void showTitleBarContextMenu() {
Cary Clark65f4a3c2009-09-28 17:05:06 -0400889 if (null == mTitleBar.getParent()) {
890 return;
891 }
Leon Scrogginsc6fa1102009-09-21 10:40:01 -0400892 openContextMenu(mTitleBar);
893 }
894
Leon Scrogginsb2b19f52009-10-09 16:10:00 -0400895 @Override
896 public void onContextMenuClosed(Menu menu) {
897 super.onContextMenuClosed(menu);
898 if (mInLoad) {
899 showFakeTitleBar();
900 }
901 }
902
Leon Scrogginsc6fa1102009-09-21 10:40:01 -0400903 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -0800904 * onSaveInstanceState(Bundle map)
905 * onSaveInstanceState is called right before onStop(). The map contains
906 * the saved state.
907 */
Grace Kloba22ac16e2009-10-07 18:00:23 -0700908 @Override
909 protected void onSaveInstanceState(Bundle outState) {
Dave Bort31a6d1c2009-04-13 15:56:49 -0700910 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800911 Log.v(LOGTAG, "BrowserActivity.onSaveInstanceState: this=" + this);
912 }
913 // the default implementation requires each view to have an id. As the
914 // browser handles the state itself and it doesn't use id for the views,
915 // don't call the default implementation. Otherwise it will trigger the
916 // warning like this, "couldn't save which view has focus because the
917 // focused view XXX has no id".
918
919 // Save all the tabs
920 mTabControl.saveState(outState);
921 }
922
Grace Kloba22ac16e2009-10-07 18:00:23 -0700923 @Override
924 protected void onPause() {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800925 super.onPause();
926
927 if (mActivityInPause) {
928 Log.e(LOGTAG, "BrowserActivity is already paused.");
929 return;
930 }
931
Mike Reed7bfa63b2009-05-28 11:08:32 -0400932 mTabControl.pauseCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800933 mActivityInPause = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -0400934 if (mTabControl.getCurrentIndex() >= 0 && !pauseWebViewTimers()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800935 mWakeLock.acquire();
936 mHandler.sendMessageDelayed(mHandler
937 .obtainMessage(RELEASE_WAKELOCK), WAKELOCK_TIMEOUT);
938 }
939
Leon Scrogginsa2ab6a72009-09-11 11:49:52 -0400940 // FIXME: This removes the active tabs page and resets the menu to
941 // MAIN_MENU. A better solution might be to do this work in onNewIntent
942 // but then we would need to save it in onSaveInstanceState and restore
943 // it in onCreate/onRestoreInstanceState
944 if (mActiveTabsPage != null) {
945 removeActiveTabPage(true);
946 }
947
The Android Open Source Project0c908882009-03-03 19:32:16 -0800948 cancelStopToast();
949
950 // unregister network state listener
951 unregisterReceiver(mNetworkStateIntentReceiver);
952 WebView.disablePlatformNotifications();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800953 }
954
Grace Kloba22ac16e2009-10-07 18:00:23 -0700955 @Override
956 protected void onDestroy() {
Dave Bort31a6d1c2009-04-13 15:56:49 -0700957 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800958 Log.v(LOGTAG, "BrowserActivity.onDestroy: this=" + this);
959 }
960 super.onDestroy();
Grace Kloba0923d692009-09-23 21:37:25 -0700961
Leon Scroggins8d5fa432009-10-02 15:55:59 -0400962 if (mUploadMessage != null) {
963 mUploadMessage.onReceiveValue(null);
964 mUploadMessage = null;
965 }
966
Grace Kloba0923d692009-09-23 21:37:25 -0700967 if (mTabControl == null) return;
968
Grace Kloba1fc98a32009-10-21 13:23:08 -0700969 // Remove the fake title bar if it is there
970 hideFakeTitleBar();
971
The Android Open Source Project0c908882009-03-03 19:32:16 -0800972 // Remove the current tab and sub window
Grace Kloba22ac16e2009-10-07 18:00:23 -0700973 Tab t = mTabControl.getCurrentTab();
Patrick Scottfb5e77f2009-04-08 19:17:37 -0700974 if (t != null) {
975 dismissSubWindow(t);
976 removeTabFromContentView(t);
977 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800978 // Destroy all the tabs
979 mTabControl.destroy();
980 WebIconDatabase.getInstance().close();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800981
Grace Klobab4da0ad2009-05-14 14:45:40 -0700982 unregisterReceiver(mPackageInstallationReceiver);
Bjorn Bringerta7611812010-03-24 11:12:02 +0000983
984 // Stop watching the default geolocation permissions
985 mSystemAllowGeolocationOrigins.stop();
986 mSystemAllowGeolocationOrigins = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800987 }
988
989 @Override
990 public void onConfigurationChanged(Configuration newConfig) {
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400991 mConfigChanged = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800992 super.onConfigurationChanged(newConfig);
993
994 if (mPageInfoDialog != null) {
995 mPageInfoDialog.dismiss();
996 showPageInfo(
997 mPageInfoView,
Leon Scrogginsc7b92f82010-01-11 18:17:31 -0500998 mPageInfoFromShowSSLCertificateOnError);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800999 }
1000 if (mSSLCertificateDialog != null) {
1001 mSSLCertificateDialog.dismiss();
1002 showSSLCertificate(
1003 mSSLCertificateView);
1004 }
1005 if (mSSLCertificateOnErrorDialog != null) {
1006 mSSLCertificateOnErrorDialog.dismiss();
1007 showSSLCertificateOnError(
1008 mSSLCertificateOnErrorView,
1009 mSSLCertificateOnErrorHandler,
1010 mSSLCertificateOnErrorError);
1011 }
1012 if (mHttpAuthenticationDialog != null) {
1013 String title = ((TextView) mHttpAuthenticationDialog
1014 .findViewById(com.android.internal.R.id.alertTitle)).getText()
1015 .toString();
1016 String name = ((TextView) mHttpAuthenticationDialog
1017 .findViewById(R.id.username_edit)).getText().toString();
1018 String password = ((TextView) mHttpAuthenticationDialog
1019 .findViewById(R.id.password_edit)).getText().toString();
1020 int focusId = mHttpAuthenticationDialog.getCurrentFocus()
1021 .getId();
1022 mHttpAuthenticationDialog.dismiss();
1023 showHttpAuthentication(mHttpAuthHandler, null, null, title,
1024 name, password, focusId);
1025 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001026 }
1027
Grace Kloba22ac16e2009-10-07 18:00:23 -07001028 @Override
1029 public void onLowMemory() {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001030 super.onLowMemory();
1031 mTabControl.freeMemory();
1032 }
1033
Cary Clarkff4d92c2010-03-25 11:17:03 -04001034 private void resumeWebViewTimers() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001035 Tab tab = mTabControl.getCurrentTab();
Cary Clarkff4d92c2010-03-25 11:17:03 -04001036 if (tab == null) return; // monkey can trigger this
Grace Kloba22ac16e2009-10-07 18:00:23 -07001037 boolean inLoad = tab.inLoad();
1038 if ((!mActivityInPause && !inLoad) || (mActivityInPause && inLoad)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001039 CookieSyncManager.getInstance().startSync();
Grace Kloba22ac16e2009-10-07 18:00:23 -07001040 WebView w = tab.getWebView();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001041 if (w != null) {
1042 w.resumeTimers();
1043 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001044 }
1045 }
1046
Mike Reed7bfa63b2009-05-28 11:08:32 -04001047 private boolean pauseWebViewTimers() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001048 Tab tab = mTabControl.getCurrentTab();
1049 boolean inLoad = tab.inLoad();
1050 if (mActivityInPause && !inLoad) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001051 CookieSyncManager.getInstance().stopSync();
1052 WebView w = mTabControl.getCurrentWebView();
1053 if (w != null) {
1054 w.pauseTimers();
1055 }
1056 return true;
1057 } else {
1058 return false;
1059 }
1060 }
1061
The Android Open Source Project0c908882009-03-03 19:32:16 -08001062 // Open the icon database and retain all the icons for visited sites.
1063 private void retainIconsOnStartup() {
1064 final WebIconDatabase db = WebIconDatabase.getInstance();
1065 db.open(getDir("icons", 0).getPath());
Leon Scroggins2c0f6112010-03-12 18:09:39 -05001066 Cursor c = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001067 try {
Leon Scroggins2c0f6112010-03-12 18:09:39 -05001068 c = Browser.getAllBookmarks(mResolver);
1069 if (c.moveToFirst()) {
1070 int urlIndex = c.getColumnIndex(Browser.BookmarkColumns.URL);
1071 do {
1072 String url = c.getString(urlIndex);
1073 db.retainIconForPageUrl(url);
1074 } while (c.moveToNext());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001075 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001076 } catch (IllegalStateException e) {
1077 Log.e(LOGTAG, "retainIconsOnStartup", e);
Leon Scroggins2c0f6112010-03-12 18:09:39 -05001078 } finally {
1079 if (c!= null) c.close();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001080 }
1081 }
1082
1083 // Helper method for getting the top window.
1084 WebView getTopWindow() {
1085 return mTabControl.getCurrentTopWebView();
1086 }
1087
Grace Kloba22ac16e2009-10-07 18:00:23 -07001088 TabControl getTabControl() {
1089 return mTabControl;
1090 }
1091
The Android Open Source Project0c908882009-03-03 19:32:16 -08001092 @Override
1093 public boolean onCreateOptionsMenu(Menu menu) {
1094 super.onCreateOptionsMenu(menu);
1095
1096 MenuInflater inflater = getMenuInflater();
1097 inflater.inflate(R.menu.browser, menu);
1098 mMenu = menu;
1099 updateInLoadMenuItems();
1100 return true;
1101 }
1102
1103 /**
1104 * As the menu can be open when loading state changes
1105 * we must manually update the state of the stop/reload menu
1106 * item
1107 */
1108 private void updateInLoadMenuItems() {
1109 if (mMenu == null) {
1110 return;
1111 }
1112 MenuItem src = mInLoad ?
1113 mMenu.findItem(R.id.stop_menu_id):
1114 mMenu.findItem(R.id.reload_menu_id);
1115 MenuItem dest = mMenu.findItem(R.id.stop_reload_menu_id);
1116 dest.setIcon(src.getIcon());
1117 dest.setTitle(src.getTitle());
1118 }
1119
1120 @Override
1121 public boolean onContextItemSelected(MenuItem item) {
1122 // chording is not an issue with context menus, but we use the same
1123 // options selector, so set mCanChord to true so we can access them.
1124 mCanChord = true;
1125 int id = item.getItemId();
Leon Scroggins96afcb12009-12-10 12:35:56 -05001126 boolean result = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001127 switch (id) {
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001128 // For the context menu from the title bar
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001129 case R.id.title_bar_copy_page_url:
Leon Scroggins96afcb12009-12-10 12:35:56 -05001130 Tab currentTab = mTabControl.getCurrentTab();
1131 if (null == currentTab) {
1132 result = false;
1133 break;
1134 }
1135 WebView mainView = currentTab.getWebView();
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001136 if (null == mainView) {
Leon Scroggins96afcb12009-12-10 12:35:56 -05001137 result = false;
1138 break;
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001139 }
Leon Scroggins96afcb12009-12-10 12:35:56 -05001140 copy(mainView.getUrl());
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001141 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001142 // -- Browser context menu
1143 case R.id.open_context_menu_id:
1144 case R.id.open_newtab_context_menu_id:
1145 case R.id.bookmark_context_menu_id:
1146 case R.id.save_link_context_menu_id:
1147 case R.id.share_link_context_menu_id:
1148 case R.id.copy_link_context_menu_id:
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001149 final WebView webView = getTopWindow();
1150 if (null == webView) {
Leon Scroggins96afcb12009-12-10 12:35:56 -05001151 result = false;
1152 break;
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001153 }
1154 final HashMap hrefMap = new HashMap();
1155 hrefMap.put("webview", webView);
1156 final Message msg = mHandler.obtainMessage(
1157 FOCUS_NODE_HREF, id, 0, hrefMap);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001158 webView.requestFocusNodeHref(msg);
1159 break;
1160
1161 default:
1162 // For other context menus
Leon Scroggins96afcb12009-12-10 12:35:56 -05001163 result = onOptionsItemSelected(item);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001164 }
1165 mCanChord = false;
Leon Scroggins96afcb12009-12-10 12:35:56 -05001166 return result;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001167 }
1168
1169 private Bundle createGoogleSearchSourceBundle(String source) {
1170 Bundle bundle = new Bundle();
Bjorn Bringert10d1cca2010-02-10 14:22:12 +00001171 bundle.putString(Search.SOURCE, source);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001172 return bundle;
1173 }
1174
Leon Scroggins8ad29922010-02-16 12:33:55 -05001175 /* package */ void editUrl() {
Leon Scroggins68579392009-09-15 15:31:54 -04001176 if (mOptionsMenuOpen) closeOptionsMenu();
Leon Scroggins5bbe9802009-07-31 13:10:55 -04001177 String url = (getTopWindow() == null) ? null : getTopWindow().getUrl();
Grace Kloba83f47342009-07-20 10:44:31 -07001178 startSearch(mSettings.getHomePage().equals(url) ? null : url, true,
Leon Scroggins8ad29922010-02-16 12:33:55 -05001179 null, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001180 }
1181
Leon Scroggins8ad29922010-02-16 12:33:55 -05001182 /**
1183 * Overriding this to insert a local information bundle
1184 */
The Android Open Source Project0c908882009-03-03 19:32:16 -08001185 @Override
1186 public void startSearch(String initialQuery, boolean selectInitialQuery,
1187 Bundle appSearchData, boolean globalSearch) {
1188 if (appSearchData == null) {
1189 appSearchData = createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_TYPE);
1190 }
1191 super.startSearch(initialQuery, selectInitialQuery, appSearchData, globalSearch);
1192 }
1193
Leon Scroggins1f005d32009-08-10 17:36:42 -04001194 /**
1195 * Switch tabs. Called by the TitleBarSet when sliding the title bar
1196 * results in changing tabs.
Leon Scroggins160a7e72009-08-14 18:28:01 -04001197 * @param index Index of the tab to change to, as defined by
1198 * mTabControl.getTabIndex(Tab t).
1199 * @return boolean True if we successfully switched to a different tab. If
1200 * the indexth tab is null, or if that tab is the same as
1201 * the current one, return false.
Leon Scroggins1f005d32009-08-10 17:36:42 -04001202 */
Leon Scroggins160a7e72009-08-14 18:28:01 -04001203 /* package */ boolean switchToTab(int index) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001204 Tab tab = mTabControl.getTab(index);
1205 Tab currentTab = mTabControl.getCurrentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04001206 if (tab == null || tab == currentTab) {
Leon Scroggins160a7e72009-08-14 18:28:01 -04001207 return false;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001208 }
1209 if (currentTab != null) {
1210 // currentTab may be null if it was just removed. In that case,
1211 // we do not need to remove it
1212 removeTabFromContentView(currentTab);
1213 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001214 mTabControl.setCurrentTab(tab);
1215 attachTabToContentView(tab);
Grace Klobaeb6eef42009-09-15 17:56:32 -07001216 resetTitleIconAndProgress();
1217 updateLockIconToLatest();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001218 return true;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001219 }
1220
Grace Kloba22ac16e2009-10-07 18:00:23 -07001221 /* package */ Tab openTabToHomePage() {
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001222 return openTabAndShow(mSettings.getHomePage(), false, null);
1223 }
1224
Leon Scroggins1f005d32009-08-10 17:36:42 -04001225 /* package */ void closeCurrentWindow() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001226 final Tab current = mTabControl.getCurrentTab();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001227 if (mTabControl.getTabCount() == 1) {
Leon Scroggins30444232009-09-04 18:36:20 -04001228 // This is the last tab. Open a new one, with the home
1229 // page and close the current one.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001230 openTabToHomePage();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001231 closeTab(current);
Leon Scroggins160a7e72009-08-14 18:28:01 -04001232 return;
1233 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07001234 final Tab parent = current.getParentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04001235 int indexToShow = -1;
1236 if (parent != null) {
1237 indexToShow = mTabControl.getTabIndex(parent);
1238 } else {
Leon Scroggins160a7e72009-08-14 18:28:01 -04001239 final int currentIndex = mTabControl.getCurrentIndex();
1240 // Try to move to the tab to the right
1241 indexToShow = currentIndex + 1;
1242 if (indexToShow > mTabControl.getTabCount() - 1) {
1243 // Try to move to the tab to the left
1244 indexToShow = currentIndex - 1;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001245 }
1246 }
Leon Scroggins160a7e72009-08-14 18:28:01 -04001247 if (switchToTab(indexToShow)) {
1248 // Close window
1249 closeTab(current);
1250 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001251 }
1252
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001253 private ActiveTabsPage mActiveTabsPage;
1254
1255 /**
1256 * Remove the active tabs page.
1257 * @param needToAttach If true, the active tabs page did not attach a tab
1258 * to the content view, so we need to do that here.
1259 */
1260 /* package */ void removeActiveTabPage(boolean needToAttach) {
1261 mContentView.removeView(mActiveTabsPage);
1262 mActiveTabsPage = null;
1263 mMenuState = R.id.MAIN_MENU;
1264 if (needToAttach) {
1265 attachTabToContentView(mTabControl.getCurrentTab());
1266 }
1267 getTopWindow().requestFocus();
1268 }
1269
The Android Open Source Project0c908882009-03-03 19:32:16 -08001270 @Override
1271 public boolean onOptionsItemSelected(MenuItem item) {
1272 if (!mCanChord) {
1273 // The user has already fired a shortcut with this hold down of the
1274 // menu key.
1275 return false;
1276 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001277 if (null == getTopWindow()) {
Leon Scroggins0d7ae0e2009-06-05 11:04:45 -04001278 return false;
1279 }
Grace Kloba6ee9c492009-07-13 10:04:34 -07001280 if (mMenuIsDown) {
1281 // The shortcut action consumes the MENU. Even if it is still down,
1282 // it won't trigger the next shortcut action. In the case of the
1283 // shortcut action triggering a new activity, like Bookmarks, we
1284 // won't get onKeyUp for MENU. So it is important to reset it here.
1285 mMenuIsDown = false;
1286 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001287 switch (item.getItemId()) {
1288 // -- Main menu
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001289 case R.id.new_tab_menu_id:
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001290 openTabToHomePage();
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001291 break;
1292
Leon Scroggins64b80f32009-08-07 12:03:34 -04001293 case R.id.goto_menu_id:
Leon Scroggins8ad29922010-02-16 12:33:55 -05001294 editUrl();
Leon Scrogginsb3a5bed2009-09-28 11:21:56 -04001295 break;
1296
1297 case R.id.bookmarks_menu_id:
Leon Scroggins30444232009-09-04 18:36:20 -04001298 bookmarksOrHistoryPicker(false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001299 break;
1300
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001301 case R.id.active_tabs_menu_id:
1302 mActiveTabsPage = new ActiveTabsPage(this, mTabControl);
1303 removeTabFromContentView(mTabControl.getCurrentTab());
Leon Scroggins43de6162009-09-14 19:59:58 -04001304 hideFakeTitleBar();
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001305 mContentView.addView(mActiveTabsPage, COVER_SCREEN_PARAMS);
1306 mActiveTabsPage.requestFocus();
1307 mMenuState = EMPTY_MENU;
1308 break;
1309
Leon Scroggins1f005d32009-08-10 17:36:42 -04001310 case R.id.add_bookmark_menu_id:
1311 Intent i = new Intent(BrowserActivity.this,
1312 AddBookmarkPage.class);
1313 WebView w = getTopWindow();
1314 i.putExtra("url", w.getUrl());
1315 i.putExtra("title", w.getTitle());
Grace Kloba83cdb2c2009-09-16 00:48:57 -07001316 i.putExtra("touch_icon_url", w.getTouchIconUrl());
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01001317 i.putExtra("thumbnail", createScreenshot(w));
Leon Scroggins1f005d32009-08-10 17:36:42 -04001318 startActivity(i);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001319 break;
1320
1321 case R.id.stop_reload_menu_id:
1322 if (mInLoad) {
1323 stopLoading();
1324 } else {
1325 getTopWindow().reload();
1326 }
1327 break;
1328
1329 case R.id.back_menu_id:
1330 getTopWindow().goBack();
1331 break;
1332
1333 case R.id.forward_menu_id:
1334 getTopWindow().goForward();
1335 break;
1336
1337 case R.id.close_menu_id:
1338 // Close the subwindow if it exists.
1339 if (mTabControl.getCurrentSubWindow() != null) {
1340 dismissSubWindow(mTabControl.getCurrentTab());
1341 break;
1342 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001343 closeCurrentWindow();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001344 break;
1345
1346 case R.id.homepage_menu_id:
Grace Kloba22ac16e2009-10-07 18:00:23 -07001347 Tab current = mTabControl.getCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001348 if (current != null) {
1349 dismissSubWindow(current);
Leon Scroggins92472e82010-02-17 16:32:28 -05001350 loadUrl(current.getWebView(), mSettings.getHomePage());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001351 }
1352 break;
1353
1354 case R.id.preferences_menu_id:
1355 Intent intent = new Intent(this,
1356 BrowserPreferencesPage.class);
Leon Scrogginsd5304942009-12-10 16:11:39 -05001357 intent.putExtra(BrowserPreferencesPage.CURRENT_PAGE,
1358 getTopWindow().getUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001359 startActivityForResult(intent, PREFERENCES_PAGE);
1360 break;
1361
1362 case R.id.find_menu_id:
1363 if (null == mFindDialog) {
1364 mFindDialog = new FindDialog(this);
1365 }
1366 mFindDialog.setWebView(getTopWindow());
1367 mFindDialog.show();
Cary Clark7d3ac792010-03-03 10:11:44 -05001368 getTopWindow().setFindIsUp(true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001369 mMenuState = EMPTY_MENU;
1370 break;
1371
1372 case R.id.select_text_id:
1373 getTopWindow().emulateShiftHeld();
1374 break;
1375 case R.id.page_info_menu_id:
1376 showPageInfo(mTabControl.getCurrentTab(), false);
1377 break;
1378
1379 case R.id.classic_history_menu_id:
Leon Scroggins30444232009-09-04 18:36:20 -04001380 bookmarksOrHistoryPicker(true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001381 break;
1382
Leon Scroggins96afcb12009-12-10 12:35:56 -05001383 case R.id.title_bar_share_page_url:
The Android Open Source Project0c908882009-03-03 19:32:16 -08001384 case R.id.share_page_menu_id:
Leon Scroggins96afcb12009-12-10 12:35:56 -05001385 Tab currentTab = mTabControl.getCurrentTab();
1386 if (null == currentTab) {
1387 mCanChord = false;
1388 return false;
1389 }
1390 currentTab.populatePickerData();
1391 sharePage(this, currentTab.getTitle(),
1392 currentTab.getUrl(), currentTab.getFavicon(),
1393 createScreenshot(currentTab.getWebView()));
The Android Open Source Project0c908882009-03-03 19:32:16 -08001394 break;
1395
1396 case R.id.dump_nav_menu_id:
1397 getTopWindow().debugDump();
1398 break;
1399
Andrei Popescu7a8b88b2010-02-02 00:30:38 +00001400 case R.id.dump_counters_menu_id:
1401 getTopWindow().dumpV8Counters();
1402 break;
1403
The Android Open Source Project0c908882009-03-03 19:32:16 -08001404 case R.id.zoom_in_menu_id:
1405 getTopWindow().zoomIn();
1406 break;
1407
1408 case R.id.zoom_out_menu_id:
1409 getTopWindow().zoomOut();
1410 break;
1411
1412 case R.id.view_downloads_menu_id:
1413 viewDownloads(null);
1414 break;
1415
The Android Open Source Project0c908882009-03-03 19:32:16 -08001416 case R.id.window_one_menu_id:
1417 case R.id.window_two_menu_id:
1418 case R.id.window_three_menu_id:
1419 case R.id.window_four_menu_id:
1420 case R.id.window_five_menu_id:
1421 case R.id.window_six_menu_id:
1422 case R.id.window_seven_menu_id:
1423 case R.id.window_eight_menu_id:
1424 {
1425 int menuid = item.getItemId();
1426 for (int id = 0; id < WINDOW_SHORTCUT_ID_ARRAY.length; id++) {
1427 if (WINDOW_SHORTCUT_ID_ARRAY[id] == menuid) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001428 Tab desiredTab = mTabControl.getTab(id);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001429 if (desiredTab != null &&
1430 desiredTab != mTabControl.getCurrentTab()) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001431 switchToTab(id);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001432 }
1433 break;
1434 }
1435 }
1436 }
1437 break;
1438
1439 default:
1440 if (!super.onOptionsItemSelected(item)) {
1441 return false;
1442 }
1443 // Otherwise fall through.
1444 }
1445 mCanChord = false;
1446 return true;
1447 }
1448
1449 public void closeFind() {
1450 mMenuState = R.id.MAIN_MENU;
1451 }
1452
Grace Kloba22ac16e2009-10-07 18:00:23 -07001453 @Override
1454 public boolean onPrepareOptionsMenu(Menu menu) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001455 // This happens when the user begins to hold down the menu key, so
1456 // allow them to chord to get a shortcut.
1457 mCanChord = true;
1458 // Note: setVisible will decide whether an item is visible; while
1459 // setEnabled() will decide whether an item is enabled, which also means
1460 // whether the matching shortcut key will function.
1461 super.onPrepareOptionsMenu(menu);
1462 switch (mMenuState) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001463 case EMPTY_MENU:
1464 if (mCurrentMenuState != mMenuState) {
1465 menu.setGroupVisible(R.id.MAIN_MENU, false);
1466 menu.setGroupEnabled(R.id.MAIN_MENU, false);
1467 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001468 }
1469 break;
1470 default:
1471 if (mCurrentMenuState != mMenuState) {
1472 menu.setGroupVisible(R.id.MAIN_MENU, true);
1473 menu.setGroupEnabled(R.id.MAIN_MENU, true);
1474 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001475 }
1476 final WebView w = getTopWindow();
1477 boolean canGoBack = false;
1478 boolean canGoForward = false;
1479 boolean isHome = false;
1480 if (w != null) {
1481 canGoBack = w.canGoBack();
1482 canGoForward = w.canGoForward();
1483 isHome = mSettings.getHomePage().equals(w.getUrl());
1484 }
1485 final MenuItem back = menu.findItem(R.id.back_menu_id);
1486 back.setEnabled(canGoBack);
1487
1488 final MenuItem home = menu.findItem(R.id.homepage_menu_id);
1489 home.setEnabled(!isHome);
1490
1491 menu.findItem(R.id.forward_menu_id)
1492 .setEnabled(canGoForward);
1493
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001494 menu.findItem(R.id.new_tab_menu_id).setEnabled(
Grace Kloba22ac16e2009-10-07 18:00:23 -07001495 mTabControl.canCreateNewTab());
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001496
The Android Open Source Project0c908882009-03-03 19:32:16 -08001497 // decide whether to show the share link option
1498 PackageManager pm = getPackageManager();
1499 Intent send = new Intent(Intent.ACTION_SEND);
1500 send.setType("text/plain");
1501 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1502 menu.findItem(R.id.share_page_menu_id).setVisible(ri != null);
1503
The Android Open Source Project0c908882009-03-03 19:32:16 -08001504 boolean isNavDump = mSettings.isNavDump();
1505 final MenuItem nav = menu.findItem(R.id.dump_nav_menu_id);
1506 nav.setVisible(isNavDump);
1507 nav.setEnabled(isNavDump);
Andrei Popescu7a8b88b2010-02-02 00:30:38 +00001508
1509 boolean showDebugSettings = mSettings.showDebugSettings();
1510 final MenuItem counter = menu.findItem(R.id.dump_counters_menu_id);
1511 counter.setVisible(showDebugSettings);
1512 counter.setEnabled(showDebugSettings);
1513
The Android Open Source Project0c908882009-03-03 19:32:16 -08001514 break;
1515 }
1516 mCurrentMenuState = mMenuState;
1517 return true;
1518 }
1519
1520 @Override
1521 public void onCreateContextMenu(ContextMenu menu, View v,
1522 ContextMenuInfo menuInfo) {
Leon Scroggins4e9f89b2010-02-22 16:54:14 -05001523 if (v instanceof TitleBar) {
1524 return;
1525 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001526 WebView webview = (WebView) v;
1527 WebView.HitTestResult result = webview.getHitTestResult();
1528 if (result == null) {
1529 return;
1530 }
1531
1532 int type = result.getType();
1533 if (type == WebView.HitTestResult.UNKNOWN_TYPE) {
1534 Log.w(LOGTAG,
1535 "We should not show context menu when nothing is touched");
1536 return;
1537 }
1538 if (type == WebView.HitTestResult.EDIT_TEXT_TYPE) {
1539 // let TextView handles context menu
1540 return;
1541 }
1542
1543 // Note, http://b/issue?id=1106666 is requesting that
1544 // an inflated menu can be used again. This is not available
1545 // yet, so inflate each time (yuk!)
1546 MenuInflater inflater = getMenuInflater();
1547 inflater.inflate(R.menu.browsercontext, menu);
1548
1549 // Show the correct menu group
1550 String extra = result.getExtra();
1551 menu.setGroupVisible(R.id.PHONE_MENU,
1552 type == WebView.HitTestResult.PHONE_TYPE);
1553 menu.setGroupVisible(R.id.EMAIL_MENU,
1554 type == WebView.HitTestResult.EMAIL_TYPE);
1555 menu.setGroupVisible(R.id.GEO_MENU,
1556 type == WebView.HitTestResult.GEO_TYPE);
1557 menu.setGroupVisible(R.id.IMAGE_MENU,
1558 type == WebView.HitTestResult.IMAGE_TYPE
1559 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1560 menu.setGroupVisible(R.id.ANCHOR_MENU,
1561 type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1562 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1563
1564 // Setup custom handling depending on the type
1565 switch (type) {
1566 case WebView.HitTestResult.PHONE_TYPE:
1567 menu.setHeaderTitle(Uri.decode(extra));
1568 menu.findItem(R.id.dial_context_menu_id).setIntent(
1569 new Intent(Intent.ACTION_VIEW, Uri
1570 .parse(WebView.SCHEME_TEL + extra)));
1571 Intent addIntent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
1572 addIntent.putExtra(Insert.PHONE, Uri.decode(extra));
Cary Clark5e335a32009-09-22 14:53:11 -04001573 addIntent.setType(ContactsContract.Contacts.CONTENT_ITEM_TYPE);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001574 menu.findItem(R.id.add_contact_context_menu_id).setIntent(
1575 addIntent);
1576 menu.findItem(R.id.copy_phone_context_menu_id).setOnMenuItemClickListener(
1577 new Copy(extra));
1578 break;
1579
1580 case WebView.HitTestResult.EMAIL_TYPE:
1581 menu.setHeaderTitle(extra);
1582 menu.findItem(R.id.email_context_menu_id).setIntent(
1583 new Intent(Intent.ACTION_VIEW, Uri
1584 .parse(WebView.SCHEME_MAILTO + extra)));
1585 menu.findItem(R.id.copy_mail_context_menu_id).setOnMenuItemClickListener(
1586 new Copy(extra));
1587 break;
1588
1589 case WebView.HitTestResult.GEO_TYPE:
1590 menu.setHeaderTitle(extra);
1591 menu.findItem(R.id.map_context_menu_id).setIntent(
1592 new Intent(Intent.ACTION_VIEW, Uri
1593 .parse(WebView.SCHEME_GEO
1594 + URLEncoder.encode(extra))));
1595 menu.findItem(R.id.copy_geo_context_menu_id).setOnMenuItemClickListener(
1596 new Copy(extra));
1597 break;
1598
1599 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1600 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
1601 TextView titleView = (TextView) LayoutInflater.from(this)
1602 .inflate(android.R.layout.browser_link_context_header,
1603 null);
1604 titleView.setText(extra);
1605 menu.setHeaderView(titleView);
1606 // decide whether to show the open link in new tab option
1607 menu.findItem(R.id.open_newtab_context_menu_id).setVisible(
Grace Kloba22ac16e2009-10-07 18:00:23 -07001608 mTabControl.canCreateNewTab());
Ben Murdochde353622009-10-12 10:29:00 +01001609 menu.findItem(R.id.bookmark_context_menu_id).setVisible(
1610 Bookmarks.urlHasAcceptableScheme(extra));
The Android Open Source Project0c908882009-03-03 19:32:16 -08001611 PackageManager pm = getPackageManager();
1612 Intent send = new Intent(Intent.ACTION_SEND);
1613 send.setType("text/plain");
1614 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1615 menu.findItem(R.id.share_link_context_menu_id).setVisible(ri != null);
1616 if (type == WebView.HitTestResult.SRC_ANCHOR_TYPE) {
1617 break;
1618 }
1619 // otherwise fall through to handle image part
1620 case WebView.HitTestResult.IMAGE_TYPE:
1621 if (type == WebView.HitTestResult.IMAGE_TYPE) {
1622 menu.setHeaderTitle(extra);
1623 }
1624 menu.findItem(R.id.view_image_context_menu_id).setIntent(
1625 new Intent(Intent.ACTION_VIEW, Uri.parse(extra)));
1626 menu.findItem(R.id.download_context_menu_id).
1627 setOnMenuItemClickListener(new Download(extra));
Ben Murdoch4f75ba22009-10-27 11:48:28 +00001628 menu.findItem(R.id.set_wallpaper_context_menu_id).
1629 setOnMenuItemClickListener(new SetAsWallpaper(extra));
The Android Open Source Project0c908882009-03-03 19:32:16 -08001630 break;
1631
1632 default:
1633 Log.w(LOGTAG, "We should not get here.");
1634 break;
1635 }
Leon Scrogginsb2b19f52009-10-09 16:10:00 -04001636 hideFakeTitleBar();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001637 }
1638
The Android Open Source Project0c908882009-03-03 19:32:16 -08001639 // Attach the given tab to the content view.
Grace Klobac928c302009-09-17 11:51:21 -07001640 // this should only be called for the current tab.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001641 private void attachTabToContentView(Tab t) {
Steve Block2bc69912009-07-30 14:45:13 +01001642 // Attach the container that contains the main WebView and any other UI
1643 // associated with the tab.
Patrick Scottd0119532009-09-17 08:00:31 -04001644 t.attachTabToContentView(mContentView);
Ben Murdochbff2d602009-07-01 20:19:05 +01001645
1646 if (mShouldShowErrorConsole) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001647 ErrorConsoleView errorConsole = t.getErrorConsole(true);
Ben Murdochbff2d602009-07-01 20:19:05 +01001648 if (errorConsole.numberOfErrors() == 0) {
1649 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
1650 } else {
1651 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
1652 }
1653
1654 mErrorConsoleContainer.addView(errorConsole,
Romain Guy15b8ec62010-01-08 15:06:43 -08001655 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
Ben Murdochbff2d602009-07-01 20:19:05 +01001656 ViewGroup.LayoutParams.WRAP_CONTENT));
1657 }
1658
Leon Scroggins39ab28e2009-09-02 21:20:30 -04001659 WebView view = t.getWebView();
Leon Scroggins55a5bc22009-09-04 17:00:08 -04001660 view.setEmbeddedTitleBar(mTitleBar);
Leon Scroggins58d56c62010-01-28 15:12:40 -05001661 if (t.isInVoiceSearchMode()) {
1662 showVoiceTitleBar(t.getVoiceDisplayTitle());
1663 } else {
1664 revertVoiceTitleBar();
1665 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001666 // Request focus on the top window.
1667 t.getTopWindow().requestFocus();
1668 }
1669
1670 // Attach a sub window to the main WebView of the given tab.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001671 void attachSubWindow(Tab t) {
Patrick Scottd0119532009-09-17 08:00:31 -04001672 t.attachSubWindow(mContentView);
1673 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001674 }
1675
1676 // Remove the given tab from the content view.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001677 private void removeTabFromContentView(Tab t) {
Steve Block2bc69912009-07-30 14:45:13 +01001678 // Remove the container that contains the main WebView.
Patrick Scottd0119532009-09-17 08:00:31 -04001679 t.removeTabFromContentView(mContentView);
Ben Murdochbff2d602009-07-01 20:19:05 +01001680
Grace Kloba22ac16e2009-10-07 18:00:23 -07001681 ErrorConsoleView errorConsole = t.getErrorConsole(false);
1682 if (errorConsole != null) {
1683 mErrorConsoleContainer.removeView(errorConsole);
Ben Murdochbff2d602009-07-01 20:19:05 +01001684 }
1685
Leon Scroggins39ab28e2009-09-02 21:20:30 -04001686 WebView view = t.getWebView();
Leon Scrogginsbb85b902009-09-14 19:27:20 -04001687 if (view != null) {
1688 view.setEmbeddedTitleBar(null);
1689 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001690 }
1691
1692 // Remove the sub window if it exists. Also called by TabControl when the
1693 // user clicks the 'X' to dismiss a sub window.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001694 /* package */ void dismissSubWindow(Tab t) {
Patrick Scottd0119532009-09-17 08:00:31 -04001695 t.removeSubWindow(mContentView);
Grace Kloba22ac16e2009-10-07 18:00:23 -07001696 // dismiss the subwindow. This will destroy the WebView.
1697 t.dismissSubWindow();
Patrick Scottd0119532009-09-17 08:00:31 -04001698 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001699 }
1700
Leon Scroggins1f005d32009-08-10 17:36:42 -04001701 // A wrapper function of {@link #openTabAndShow(UrlData, boolean, String)}
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07001702 // that accepts url as string.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001703 private Tab openTabAndShow(String url, boolean closeOnExit, String appId) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001704 return openTabAndShow(new UrlData(url), closeOnExit, appId);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001705 }
1706
1707 // This method does a ton of stuff. It will attempt to create a new tab
1708 // if we haven't reached MAX_TABS. Otherwise it uses the current tab. If
Leon Scroggins1f005d32009-08-10 17:36:42 -04001709 // url isn't null, it will load the given url.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001710 /* package */Tab openTabAndShow(UrlData urlData, boolean closeOnExit,
1711 String appId) {
1712 final Tab currentTab = mTabControl.getCurrentTab();
1713 if (mTabControl.canCreateNewTab()) {
1714 final Tab tab = mTabControl.createNewTab(closeOnExit, appId,
1715 urlData.mUrl);
Leon Scroggins1f005d32009-08-10 17:36:42 -04001716 WebView webview = tab.getWebView();
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001717 // If the last tab was removed from the active tabs page, currentTab
1718 // will be null.
1719 if (currentTab != null) {
1720 removeTabFromContentView(currentTab);
1721 }
Patrick Scott8bbd69f2009-08-14 13:35:53 -04001722 // We must set the new tab as the current tab to reflect the old
1723 // animation behavior.
1724 mTabControl.setCurrentTab(tab);
Grace Klobaeb6eef42009-09-15 17:56:32 -07001725 attachTabToContentView(tab);
Leon Scroggins160a7e72009-08-14 18:28:01 -04001726 if (!urlData.isEmpty()) {
Patrick Scott9d53da02010-02-19 10:19:01 -05001727 loadUrlDataIn(tab, urlData);
Leon Scroggins1f005d32009-08-10 17:36:42 -04001728 }
1729 return tab;
1730 } else {
1731 // Get rid of the subwindow if it exists
1732 dismissSubWindow(currentTab);
1733 if (!urlData.isEmpty()) {
1734 // Load the given url.
Patrick Scott9d53da02010-02-19 10:19:01 -05001735 loadUrlDataIn(currentTab, urlData);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001736 }
Leon Scroggins58d56c62010-01-28 15:12:40 -05001737 return currentTab;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001738 }
1739 }
1740
Grace Kloba22ac16e2009-10-07 18:00:23 -07001741 private Tab openTab(String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001742 if (mSettings.openInBackground()) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001743 Tab t = mTabControl.createNewTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001744 if (t != null) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001745 WebView view = t.getWebView();
Leon Scroggins92472e82010-02-17 16:32:28 -05001746 loadUrl(view, url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001747 }
Grace Klobac9181842009-04-14 08:53:22 -07001748 return t;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001749 } else {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001750 return openTabAndShow(url, false, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001751 }
1752 }
1753
1754 private class Copy implements OnMenuItemClickListener {
1755 private CharSequence mText;
1756
1757 public boolean onMenuItemClick(MenuItem item) {
1758 copy(mText);
1759 return true;
1760 }
1761
1762 public Copy(CharSequence toCopy) {
1763 mText = toCopy;
1764 }
1765 }
1766
1767 private class Download implements OnMenuItemClickListener {
1768 private String mText;
1769
1770 public boolean onMenuItemClick(MenuItem item) {
1771 onDownloadStartNoStream(mText, null, null, null, -1);
1772 return true;
1773 }
1774
1775 public Download(String toDownload) {
1776 mText = toDownload;
1777 }
1778 }
1779
Ben Murdoch4f75ba22009-10-27 11:48:28 +00001780 private class SetAsWallpaper extends Thread implements
1781 OnMenuItemClickListener, DialogInterface.OnCancelListener {
1782 private URL mUrl;
1783 private ProgressDialog mWallpaperProgress;
1784 private boolean mCanceled = false;
1785
1786 public SetAsWallpaper(String url) {
1787 try {
1788 mUrl = new URL(url);
1789 } catch (MalformedURLException e) {
1790 mUrl = null;
1791 }
1792 }
1793
1794 public void onCancel(DialogInterface dialog) {
1795 mCanceled = true;
1796 }
1797
1798 public boolean onMenuItemClick(MenuItem item) {
1799 if (mUrl != null) {
1800 // The user may have tried to set a image with a large file size as their
1801 // background so it may take a few moments to perform the operation. Display
1802 // a progress spinner while it is working.
1803 mWallpaperProgress = new ProgressDialog(BrowserActivity.this);
1804 mWallpaperProgress.setIndeterminate(true);
1805 mWallpaperProgress.setMessage(getText(R.string.progress_dialog_setting_wallpaper));
1806 mWallpaperProgress.setCancelable(true);
1807 mWallpaperProgress.setOnCancelListener(this);
1808 mWallpaperProgress.show();
1809 start();
1810 }
1811 return true;
1812 }
1813
1814 public void run() {
1815 Drawable oldWallpaper = BrowserActivity.this.getWallpaper();
1816 try {
1817 // TODO: This will cause the resource to be downloaded again, when we
1818 // should in most cases be able to grab it from the cache. To fix this
1819 // we should query WebCore to see if we can access a cached version and
1820 // instead open an input stream on that. This pattern could also be used
1821 // in the download manager where the same problem exists.
1822 InputStream inputstream = mUrl.openStream();
1823 if (inputstream != null) {
1824 setWallpaper(inputstream);
1825 }
1826 } catch (IOException e) {
1827 Log.e(LOGTAG, "Unable to set new wallpaper");
1828 // Act as though the user canceled the operation so we try to
1829 // restore the old wallpaper.
1830 mCanceled = true;
1831 }
1832
1833 if (mCanceled) {
1834 // Restore the old wallpaper if the user cancelled whilst we were setting
1835 // the new wallpaper.
1836 int width = oldWallpaper.getIntrinsicWidth();
1837 int height = oldWallpaper.getIntrinsicHeight();
1838 Bitmap bm = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
1839 Canvas canvas = new Canvas(bm);
1840 oldWallpaper.setBounds(0, 0, width, height);
1841 oldWallpaper.draw(canvas);
1842 try {
1843 setWallpaper(bm);
1844 } catch (IOException e) {
1845 Log.e(LOGTAG, "Unable to restore old wallpaper.");
1846 }
1847 mCanceled = false;
1848 }
1849
1850 if (mWallpaperProgress.isShowing()) {
1851 mWallpaperProgress.dismiss();
1852 }
1853 }
1854 }
1855
The Android Open Source Project0c908882009-03-03 19:32:16 -08001856 private void copy(CharSequence text) {
1857 try {
1858 IClipboard clip = IClipboard.Stub.asInterface(ServiceManager.getService("clipboard"));
1859 if (clip != null) {
1860 clip.setClipboardText(text);
1861 }
1862 } catch (android.os.RemoteException e) {
1863 Log.e(LOGTAG, "Copy failed", e);
1864 }
1865 }
1866
1867 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08001868 * Resets the browser title-view to whatever it must be
1869 * (for example, if we had a loading error)
1870 * When we have a new page, we call resetTitle, when we
1871 * have to reset the titlebar to whatever it used to be
1872 * (for example, if the user chose to stop loading), we
1873 * call resetTitleAndRevertLockIcon.
1874 */
1875 /* package */ void resetTitleAndRevertLockIcon() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001876 mTabControl.getCurrentTab().revertLockIcon();
1877 updateLockIconToLatest();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001878 resetTitleIconAndProgress();
1879 }
1880
1881 /**
1882 * Reset the title, favicon, and progress.
1883 */
1884 private void resetTitleIconAndProgress() {
1885 WebView current = mTabControl.getCurrentWebView();
1886 if (current == null) {
1887 return;
1888 }
1889 resetTitleAndIcon(current);
1890 int progress = current.getProgress();
Grace Kloba22ac16e2009-10-07 18:00:23 -07001891 current.getWebChromeClient().onProgressChanged(current, progress);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001892 }
1893
1894 // Reset the title and the icon based on the given item.
1895 private void resetTitleAndIcon(WebView view) {
1896 WebHistoryItem item = view.copyBackForwardList().getCurrentItem();
1897 if (item != null) {
Leon Scroggins68579392009-09-15 15:31:54 -04001898 setUrlTitle(item.getUrl(), item.getTitle());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001899 setFavicon(item.getFavicon());
1900 } else {
Leon Scroggins68579392009-09-15 15:31:54 -04001901 setUrlTitle(null, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001902 setFavicon(null);
1903 }
1904 }
1905
1906 /**
1907 * Sets a title composed of the URL and the title string.
1908 * @param url The URL of the site being loaded.
1909 * @param title The title of the site being loaded.
1910 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07001911 void setUrlTitle(String url, String title) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001912 mUrl = url;
1913 mTitle = title;
1914
Leon Scroggins58d56c62010-01-28 15:12:40 -05001915 // If we are in voice search mode, the title has already been set.
1916 if (mTabControl.getCurrentTab().isInVoiceSearchMode()) return;
1917 mTitleBar.setDisplayTitle(url);
1918 mFakeTitleBar.setDisplayTitle(url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001919 }
1920
1921 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08001922 * @param url The URL to build a title version of the URL from.
1923 * @return The title version of the URL or null if fails.
1924 * The title version of the URL can be either the URL hostname,
1925 * or the hostname with an "https://" prefix (for secure URLs),
1926 * or an empty string if, for example, the URL in question is a
1927 * file:// URL with no hostname.
1928 */
Leon Scroggins32e14a62009-06-11 10:26:34 -04001929 /* package */ static String buildTitleUrl(String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001930 String titleUrl = null;
1931
1932 if (url != null) {
1933 try {
1934 // parse the url string
1935 URL urlObj = new URL(url);
1936 if (urlObj != null) {
1937 titleUrl = "";
1938
1939 String protocol = urlObj.getProtocol();
1940 String host = urlObj.getHost();
1941
1942 if (host != null && 0 < host.length()) {
1943 titleUrl = host;
1944 if (protocol != null) {
1945 // if a secure site, add an "https://" prefix!
1946 if (protocol.equalsIgnoreCase("https")) {
1947 titleUrl = protocol + "://" + host;
1948 }
1949 }
1950 }
1951 }
1952 } catch (MalformedURLException e) {}
1953 }
1954
1955 return titleUrl;
1956 }
1957
1958 // Set the favicon in the title bar.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001959 void setFavicon(Bitmap icon) {
Leon Scroggins68579392009-09-15 15:31:54 -04001960 mTitleBar.setFavicon(icon);
Leon Scrogginsfe87bd32009-10-06 10:10:00 -04001961 mFakeTitleBar.setFavicon(icon);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001962 }
1963
1964 /**
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001965 * Close the tab, remove its associated title bar, and adjust mTabControl's
1966 * current tab to a valid value.
Leon Scroggins1f005d32009-08-10 17:36:42 -04001967 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07001968 /* package */ void closeTab(Tab t) {
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001969 int currentIndex = mTabControl.getCurrentIndex();
1970 int removeIndex = mTabControl.getTabIndex(t);
Leon Scroggins1f005d32009-08-10 17:36:42 -04001971 mTabControl.removeTab(t);
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001972 if (currentIndex >= removeIndex && currentIndex != 0) {
1973 currentIndex--;
1974 }
1975 mTabControl.setCurrentTab(mTabControl.getTab(currentIndex));
Andrei Popescua5bf1de2009-09-23 16:39:23 +01001976 resetTitleIconAndProgress();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001977 }
1978
Leon Scrogginsdcc5eeb2010-02-23 17:26:37 -05001979 /* package */ void goBackOnePageOrQuit() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001980 Tab current = mTabControl.getCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001981 if (current == null) {
1982 /*
1983 * Instead of finishing the activity, simply push this to the back
1984 * of the stack and let ActivityManager to choose the foreground
1985 * activity. As BrowserActivity is singleTask, it will be always the
1986 * root of the task. So we can use either true or false for
1987 * moveTaskToBack().
1988 */
1989 moveTaskToBack(true);
Grace Kloba00d85e72009-09-23 18:50:05 -07001990 return;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001991 }
1992 WebView w = current.getWebView();
1993 if (w.canGoBack()) {
1994 w.goBack();
1995 } else {
1996 // Check to see if we are closing a window that was created by
1997 // another window. If so, we switch back to that window.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001998 Tab parent = current.getParentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001999 if (parent != null) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04002000 switchToTab(mTabControl.getTabIndex(parent));
2001 // Now we close the other tab
2002 closeTab(current);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002003 } else {
2004 if (current.closeOnExit()) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002005 // force the tab's inLoad() to be false as we are going to
2006 // either finish the activity or remove the tab. This will
2007 // ensure pauseWebViewTimers() taking action.
2008 mTabControl.getCurrentTab().clearInLoad();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002009 if (mTabControl.getTabCount() == 1) {
2010 finish();
2011 return;
2012 }
Mike Reed7bfa63b2009-05-28 11:08:32 -04002013 // call pauseWebViewTimers() now, we won't be able to call
2014 // it in onPause() as the WebView won't be valid.
Grace Klobaec1b5ad2009-08-18 08:42:32 -07002015 // Temporarily change mActivityInPause to be true as
2016 // pauseWebViewTimers() will do nothing if mActivityInPause
2017 // is false.
Grace Kloba918e1d72009-08-13 14:55:06 -07002018 boolean savedState = mActivityInPause;
2019 if (savedState) {
Grace Klobaec1b5ad2009-08-18 08:42:32 -07002020 Log.e(LOGTAG, "BrowserActivity is already paused "
2021 + "while handing goBackOnePageOrQuit.");
Grace Kloba918e1d72009-08-13 14:55:06 -07002022 }
2023 mActivityInPause = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -04002024 pauseWebViewTimers();
Grace Kloba918e1d72009-08-13 14:55:06 -07002025 mActivityInPause = savedState;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002026 removeTabFromContentView(current);
2027 mTabControl.removeTab(current);
2028 }
2029 /*
2030 * Instead of finishing the activity, simply push this to the back
2031 * of the stack and let ActivityManager to choose the foreground
2032 * activity. As BrowserActivity is singleTask, it will be always the
2033 * root of the task. So we can use either true or false for
2034 * moveTaskToBack().
2035 */
2036 moveTaskToBack(true);
2037 }
2038 }
2039 }
2040
Grace Kloba22ac16e2009-10-07 18:00:23 -07002041 boolean isMenuDown() {
2042 return mMenuIsDown;
2043 }
2044
Grace Kloba5942df02009-09-18 11:48:29 -07002045 @Override
2046 public boolean onKeyDown(int keyCode, KeyEvent event) {
Leon Scrogginsf65b50d2009-12-08 10:44:28 -05002047 // Even if MENU is already held down, we need to call to super to open
2048 // the IME on long press.
2049 if (KeyEvent.KEYCODE_MENU == keyCode) {
2050 mMenuIsDown = true;
2051 return super.onKeyDown(keyCode, event);
2052 }
Grace Kloba5942df02009-09-18 11:48:29 -07002053 // The default key mode is DEFAULT_KEYS_SEARCH_LOCAL. As the MENU is
2054 // still down, we don't want to trigger the search. Pretend to consume
2055 // the key and do nothing.
2056 if (mMenuIsDown) return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002057
Grace Kloba5942df02009-09-18 11:48:29 -07002058 switch(keyCode) {
Grace Kloba5942df02009-09-18 11:48:29 -07002059 case KeyEvent.KEYCODE_SPACE:
Grace Klobada0fe552009-09-22 18:17:24 -07002060 // WebView/WebTextView handle the keys in the KeyDown. As
2061 // the Activity's shortcut keys are only handled when WebView
2062 // doesn't, have to do it in onKeyDown instead of onKeyUp.
2063 if (event.isShiftPressed()) {
2064 getTopWindow().pageUp(false);
2065 } else {
2066 getTopWindow().pageDown(false);
2067 }
Grace Kloba5942df02009-09-18 11:48:29 -07002068 return true;
2069 case KeyEvent.KEYCODE_BACK:
2070 if (event.getRepeatCount() == 0) {
2071 event.startTracking();
2072 return true;
2073 } else if (mCustomView == null && mActiveTabsPage == null
2074 && event.isLongPress()) {
2075 bookmarksOrHistoryPicker(true);
2076 return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002077 }
Grace Kloba5942df02009-09-18 11:48:29 -07002078 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002079 }
Grace Kloba5942df02009-09-18 11:48:29 -07002080 return super.onKeyDown(keyCode, event);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002081 }
2082
Grace Kloba5942df02009-09-18 11:48:29 -07002083 @Override
2084 public boolean onKeyUp(int keyCode, KeyEvent event) {
2085 switch(keyCode) {
2086 case KeyEvent.KEYCODE_MENU:
2087 mMenuIsDown = false;
2088 break;
Grace Kloba5942df02009-09-18 11:48:29 -07002089 case KeyEvent.KEYCODE_BACK:
2090 if (event.isTracking() && !event.isCanceled()) {
2091 if (mCustomView != null) {
2092 // if a custom view is showing, hide it
Grace Kloba22ac16e2009-10-07 18:00:23 -07002093 mTabControl.getCurrentWebView().getWebChromeClient()
2094 .onHideCustomView();
Grace Kloba5942df02009-09-18 11:48:29 -07002095 } else if (mActiveTabsPage != null) {
2096 // if tab page is showing, hide it
2097 removeActiveTabPage(true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002098 } else {
Grace Kloba5942df02009-09-18 11:48:29 -07002099 WebView subwindow = mTabControl.getCurrentSubWindow();
2100 if (subwindow != null) {
2101 if (subwindow.canGoBack()) {
2102 subwindow.goBack();
2103 } else {
2104 dismissSubWindow(mTabControl.getCurrentTab());
2105 }
2106 } else {
2107 goBackOnePageOrQuit();
2108 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002109 }
Grace Kloba5942df02009-09-18 11:48:29 -07002110 return true;
2111 }
2112 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002113 }
Grace Kloba5942df02009-09-18 11:48:29 -07002114 return super.onKeyUp(keyCode, event);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002115 }
2116
Leon Scroggins68579392009-09-15 15:31:54 -04002117 /* package */ void stopLoading() {
Ben Murdochb7cc8b42009-09-28 10:59:09 +01002118 mDidStopLoad = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002119 resetTitleAndRevertLockIcon();
2120 WebView w = getTopWindow();
2121 w.stopLoading();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002122 // FIXME: before refactor, it is using mWebViewClient. So I keep the
2123 // same logic here. But for subwindow case, should we call into the main
2124 // WebView's onPageFinished as we never call its onPageStarted and if
2125 // the page finishes itself, we don't call onPageFinished.
2126 mTabControl.getCurrentWebView().getWebViewClient().onPageFinished(w,
2127 w.getUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08002128
2129 cancelStopToast();
2130 mStopToast = Toast
2131 .makeText(this, R.string.stopping, Toast.LENGTH_SHORT);
2132 mStopToast.show();
2133 }
2134
Grace Kloba22ac16e2009-10-07 18:00:23 -07002135 boolean didUserStopLoading() {
2136 return mDidStopLoad;
2137 }
2138
The Android Open Source Project0c908882009-03-03 19:32:16 -08002139 private void cancelStopToast() {
2140 if (mStopToast != null) {
2141 mStopToast.cancel();
2142 mStopToast = null;
2143 }
2144 }
2145
Grace Kloba22ac16e2009-10-07 18:00:23 -07002146 // called by a UI or non-UI thread to post the message
2147 public void postMessage(int what, int arg1, int arg2, Object obj,
2148 long delayMillis) {
2149 mHandler.sendMessageDelayed(mHandler.obtainMessage(what, arg1, arg2,
2150 obj), delayMillis);
2151 }
2152
2153 // called by a UI or non-UI thread to remove the message
2154 void removeMessages(int what, Object object) {
2155 mHandler.removeMessages(what, object);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002156 }
2157
2158 // public message ids
2159 public final static int LOAD_URL = 1001;
2160 public final static int STOP_LOAD = 1002;
2161
2162 // Message Ids
2163 private static final int FOCUS_NODE_HREF = 102;
Grace Kloba92c18a52009-07-31 23:48:32 -07002164 private static final int RELEASE_WAKELOCK = 107;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002165
Grace Kloba22ac16e2009-10-07 18:00:23 -07002166 static final int UPDATE_BOOKMARK_THUMBNAIL = 108;
Ben Murdoch2694e232009-09-29 09:41:11 +01002167
The Android Open Source Project0c908882009-03-03 19:32:16 -08002168 // Private handler for handling javascript and saving passwords
2169 private Handler mHandler = new Handler() {
2170
2171 public void handleMessage(Message msg) {
2172 switch (msg.what) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002173 case FOCUS_NODE_HREF:
Ben Murdoch2694e232009-09-29 09:41:11 +01002174 {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002175 String url = (String) msg.getData().get("url");
Ben Murdoch90d088c2009-11-17 18:14:04 +00002176 String title = (String) msg.getData().get("title");
The Android Open Source Project0c908882009-03-03 19:32:16 -08002177 if (url == null || url.length() == 0) {
2178 break;
2179 }
2180 HashMap focusNodeMap = (HashMap) msg.obj;
2181 WebView view = (WebView) focusNodeMap.get("webview");
2182 // Only apply the action if the top window did not change.
2183 if (getTopWindow() != view) {
2184 break;
2185 }
2186 switch (msg.arg1) {
2187 case R.id.open_context_menu_id:
2188 case R.id.view_image_context_menu_id:
Leon Scroggins92472e82010-02-17 16:32:28 -05002189 loadUrlFromContext(getTopWindow(), url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002190 break;
2191 case R.id.open_newtab_context_menu_id:
Grace Kloba22ac16e2009-10-07 18:00:23 -07002192 final Tab parent = mTabControl.getCurrentTab();
2193 final Tab newTab = openTab(url);
Grace Klobac9181842009-04-14 08:53:22 -07002194 if (newTab != parent) {
2195 parent.addChildTab(newTab);
2196 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002197 break;
2198 case R.id.bookmark_context_menu_id:
2199 Intent intent = new Intent(BrowserActivity.this,
2200 AddBookmarkPage.class);
2201 intent.putExtra("url", url);
Ben Murdoch90d088c2009-11-17 18:14:04 +00002202 intent.putExtra("title", title);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002203 startActivity(intent);
2204 break;
2205 case R.id.share_link_context_menu_id:
Leon Scroggins96afcb12009-12-10 12:35:56 -05002206 // See if this site has been visited before
2207 StringBuilder sb = new StringBuilder(
2208 Browser.BookmarkColumns.URL + " = ");
2209 DatabaseUtils.appendEscapedSQLString(sb, url);
2210 Cursor c = mResolver.query(Browser.BOOKMARKS_URI,
2211 Browser.HISTORY_PROJECTION,
2212 sb.toString(),
2213 null,
2214 null);
2215 if (c.moveToFirst()) {
2216 // The site has been visited before, so grab the
2217 // info from the database.
2218 Bitmap favicon = null;
2219 Bitmap thumbnail = null;
2220 String linkTitle = c.getString(Browser.
2221 HISTORY_PROJECTION_TITLE_INDEX);
2222 byte[] data = c.getBlob(Browser.
2223 HISTORY_PROJECTION_FAVICON_INDEX);
2224 if (data != null) {
2225 favicon = BitmapFactory.decodeByteArray(
2226 data, 0, data.length);
2227 }
2228 data = c.getBlob(Browser.
2229 HISTORY_PROJECTION_THUMBNAIL_INDEX);
2230 if (data != null) {
2231 thumbnail = BitmapFactory.decodeByteArray(
2232 data, 0, data.length);
2233 }
2234 sharePage(BrowserActivity.this,
2235 linkTitle, url, favicon, thumbnail);
2236 } else {
2237 Browser.sendString(BrowserActivity.this, url,
2238 getString(
2239 R.string.choosertitle_sharevia));
2240 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002241 break;
2242 case R.id.copy_link_context_menu_id:
2243 copy(url);
2244 break;
2245 case R.id.save_link_context_menu_id:
2246 case R.id.download_context_menu_id:
2247 onDownloadStartNoStream(url, null, null, null, -1);
2248 break;
2249 }
2250 break;
Ben Murdoch2694e232009-09-29 09:41:11 +01002251 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002252
2253 case LOAD_URL:
Leon Scroggins92472e82010-02-17 16:32:28 -05002254 loadUrlFromContext(getTopWindow(), (String) msg.obj);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002255 break;
2256
2257 case STOP_LOAD:
2258 stopLoading();
2259 break;
2260
The Android Open Source Project0c908882009-03-03 19:32:16 -08002261 case RELEASE_WAKELOCK:
2262 if (mWakeLock.isHeld()) {
2263 mWakeLock.release();
Grace Kloba5d0e02e2009-10-05 15:15:36 -07002264 // if we reach here, Browser should be still in the
2265 // background loading after WAKELOCK_TIMEOUT (5-min).
2266 // To avoid burning the battery, stop loading.
2267 mTabControl.stopAllLoading();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002268 }
2269 break;
Ben Murdoch2694e232009-09-29 09:41:11 +01002270
2271 case UPDATE_BOOKMARK_THUMBNAIL:
2272 WebView view = (WebView) msg.obj;
2273 if (view != null) {
2274 updateScreenshot(view);
2275 }
2276 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002277 }
2278 }
2279 };
2280
Leon Scroggins96afcb12009-12-10 12:35:56 -05002281 /**
2282 * Share a page, providing the title, url, favicon, and a screenshot. Uses
2283 * an {@link Intent} to launch the Activity chooser.
2284 * @param c Context used to launch a new Activity.
2285 * @param title Title of the page. Stored in the Intent with
Paul Westbrook03e6d392010-02-12 10:33:29 -08002286 * {@link Intent#EXTRA_SUBJECT}
Leon Scroggins96afcb12009-12-10 12:35:56 -05002287 * @param url URL of the page. Stored in the Intent with
2288 * {@link Intent#EXTRA_TEXT}
2289 * @param favicon Bitmap of the favicon for the page. Stored in the Intent
2290 * with {@link Browser#EXTRA_SHARE_FAVICON}
2291 * @param screenshot Bitmap of a screenshot of the page. Stored in the
2292 * Intent with {@link Browser#EXTRA_SHARE_SCREENSHOT}
2293 */
2294 public static final void sharePage(Context c, String title, String url,
2295 Bitmap favicon, Bitmap screenshot) {
2296 Intent send = new Intent(Intent.ACTION_SEND);
2297 send.setType("text/plain");
2298 send.putExtra(Intent.EXTRA_TEXT, url);
Paul Westbrook03e6d392010-02-12 10:33:29 -08002299 send.putExtra(Intent.EXTRA_SUBJECT, title);
Leon Scroggins96afcb12009-12-10 12:35:56 -05002300 send.putExtra(Browser.EXTRA_SHARE_FAVICON, favicon);
2301 send.putExtra(Browser.EXTRA_SHARE_SCREENSHOT, screenshot);
2302 try {
2303 c.startActivity(Intent.createChooser(send, c.getString(
2304 R.string.choosertitle_sharevia)));
2305 } catch(android.content.ActivityNotFoundException ex) {
2306 // if no app handles it, do nothing
2307 }
2308 }
2309
Leon Scroggins89c6d362009-07-15 16:54:37 -04002310 private void updateScreenshot(WebView view) {
2311 // If this is a bookmarked site, add a screenshot to the database.
2312 // FIXME: When should we update? Every time?
2313 // FIXME: Would like to make sure there is actually something to
2314 // draw, but the API for that (WebViewCore.pictureReady()) is not
2315 // currently accessible here.
Ben Murdochaac7aa62009-09-17 16:57:40 +01002316
Patrick Scottcb192b52010-04-14 14:38:55 -04002317 final Bitmap bm = createScreenshot(view);
2318 if (bm == null) {
2319 return;
Leon Scroggins89c6d362009-07-15 16:54:37 -04002320 }
Patrick Scottcb192b52010-04-14 14:38:55 -04002321
2322 final ContentResolver cr = getContentResolver();
2323 final String url = view.getUrl();
2324 final String originalUrl = view.getOriginalUrl();
2325
2326 new AsyncTask<Void, Void, Void>() {
2327 @Override
2328 protected Void doInBackground(Void... unused) {
2329 Cursor c = null;
2330 try {
2331 c = BrowserBookmarksAdapter.queryBookmarksForUrl(
2332 cr, originalUrl, url, true);
2333 if (c != null) {
2334 if (c.moveToFirst()) {
2335 ContentValues values = new ContentValues();
2336 final ByteArrayOutputStream os
2337 = new ByteArrayOutputStream();
2338 bm.compress(Bitmap.CompressFormat.PNG, 100, os);
2339 values.put(Browser.BookmarkColumns.THUMBNAIL,
2340 os.toByteArray());
2341 do {
2342 cr.update(ContentUris.withAppendedId(
2343 Browser.BOOKMARKS_URI, c.getInt(0)),
2344 values, null, null);
2345 } while (c.moveToNext());
2346 }
2347 }
2348 } catch (IllegalStateException e) {
2349 // Ignore
2350 } finally {
2351 if (c != null) c.close();
2352 }
2353 return null;
2354 }
2355 }.execute();
Leon Scroggins89c6d362009-07-15 16:54:37 -04002356 }
2357
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002358 /**
Leon Scrogginsf8551612009-09-24 16:06:02 -04002359 * Values for the size of the thumbnail created when taking a screenshot.
2360 * Lazily initialized. Instead of using these directly, use
2361 * getDesiredThumbnailWidth() or getDesiredThumbnailHeight().
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002362 */
Leon Scrogginsf8551612009-09-24 16:06:02 -04002363 private static int THUMBNAIL_WIDTH = 0;
2364 private static int THUMBNAIL_HEIGHT = 0;
2365
2366 /**
2367 * Return the desired width for thumbnail screenshots, which are stored in
2368 * the database, and used on the bookmarks screen.
2369 * @param context Context for finding out the density of the screen.
2370 * @return int desired width for thumbnail screenshot.
2371 */
2372 /* package */ static int getDesiredThumbnailWidth(Context context) {
2373 if (THUMBNAIL_WIDTH == 0) {
2374 float density = context.getResources().getDisplayMetrics().density;
2375 THUMBNAIL_WIDTH = (int) (90 * density);
2376 THUMBNAIL_HEIGHT = (int) (80 * density);
2377 }
2378 return THUMBNAIL_WIDTH;
2379 }
2380
2381 /**
2382 * Return the desired height for thumbnail screenshots, which are stored in
2383 * the database, and used on the bookmarks screen.
2384 * @param context Context for finding out the density of the screen.
2385 * @return int desired height for thumbnail screenshot.
2386 */
2387 /* package */ static int getDesiredThumbnailHeight(Context context) {
2388 // To ensure that they are both initialized.
2389 getDesiredThumbnailWidth(context);
2390 return THUMBNAIL_HEIGHT;
2391 }
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002392
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002393 private Bitmap createScreenshot(WebView view) {
2394 Picture thumbnail = view.capturePicture();
Leon Scroggins45800572009-09-29 16:38:47 -04002395 if (thumbnail == null) {
2396 return null;
2397 }
Leon Scrogginsf8551612009-09-24 16:06:02 -04002398 Bitmap bm = Bitmap.createBitmap(getDesiredThumbnailWidth(this),
Cary Clarkab168ba2010-04-08 09:11:28 -04002399 getDesiredThumbnailHeight(this), Bitmap.Config.RGB_565);
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002400 Canvas canvas = new Canvas(bm);
2401 // May need to tweak these values to determine what is the
2402 // best scale factor
Ben Murdoch2694e232009-09-29 09:41:11 +01002403 int thumbnailWidth = thumbnail.getWidth();
Ben Murdochae59c3f2009-10-20 18:30:28 +01002404 int thumbnailHeight = thumbnail.getHeight();
2405 float scaleFactorX = 1.0f;
2406 float scaleFactorY = 1.0f;
Ben Murdoch2694e232009-09-29 09:41:11 +01002407 if (thumbnailWidth > 0) {
Ben Murdochae59c3f2009-10-20 18:30:28 +01002408 scaleFactorX = (float) getDesiredThumbnailWidth(this) /
Ben Murdoch2694e232009-09-29 09:41:11 +01002409 (float)thumbnailWidth;
Ben Murdochae59c3f2009-10-20 18:30:28 +01002410 } else {
2411 return null;
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002412 }
Ben Murdochae59c3f2009-10-20 18:30:28 +01002413
2414 if (view.getWidth() > view.getHeight() &&
2415 thumbnailHeight < view.getHeight() && thumbnailHeight > 0) {
2416 // If the device is in landscape and the page is shorter
2417 // than the height of the view, stretch the thumbnail to fill the
2418 // space.
2419 scaleFactorY = (float) getDesiredThumbnailHeight(this) /
2420 (float)thumbnailHeight;
2421 } else {
2422 // In the portrait case, this looks nice.
2423 scaleFactorY = scaleFactorX;
2424 }
2425
2426 canvas.scale(scaleFactorX, scaleFactorY);
2427
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002428 thumbnail.draw(canvas);
2429 return bm;
2430 }
2431
The Android Open Source Project0c908882009-03-03 19:32:16 -08002432 // -------------------------------------------------------------------------
Grace Kloba22ac16e2009-10-07 18:00:23 -07002433 // Helper function for WebViewClient.
The Android Open Source Project0c908882009-03-03 19:32:16 -08002434 //-------------------------------------------------------------------------
2435
2436 // Use in overrideUrlLoading
2437 /* package */ final static String SCHEME_WTAI = "wtai://wp/";
2438 /* package */ final static String SCHEME_WTAI_MC = "wtai://wp/mc;";
2439 /* package */ final static String SCHEME_WTAI_SD = "wtai://wp/sd;";
2440 /* package */ final static String SCHEME_WTAI_AP = "wtai://wp/ap;";
2441
Leon Scroggins92472e82010-02-17 16:32:28 -05002442 // Keep this initial progress in sync with initialProgressValue (* 100)
2443 // in ProgressTracker.cpp
2444 private final static int INITIAL_PROGRESS = 10;
2445
Grace Kloba22ac16e2009-10-07 18:00:23 -07002446 void onPageStarted(WebView view, String url, Bitmap favicon) {
2447 // when BrowserActivity just starts, onPageStarted may be called before
2448 // onResume as it is triggered from onCreate. Call resumeWebViewTimers
2449 // to start the timer. As we won't switch tabs while an activity is in
2450 // pause state, we can ensure calling resume and pause in pair.
2451 if (mActivityInPause) resumeWebViewTimers();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002452
Grace Kloba22ac16e2009-10-07 18:00:23 -07002453 resetLockIcon(url);
2454 setUrlTitle(url, null);
2455 setFavicon(favicon);
Leon Scroggins8cf8f682009-11-04 11:13:50 -08002456 // Show some progress so that the user knows the page is beginning to
2457 // load
Leon Scroggins92472e82010-02-17 16:32:28 -05002458 onProgressChanged(view, INITIAL_PROGRESS);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002459 mDidStopLoad = false;
Grace Kloba22ac16e2009-10-07 18:00:23 -07002460 if (!mIsNetworkUp) createAndShowNetworkDialog();
Patrick Scott15525d42009-09-21 13:39:37 -04002461
Grace Kloba22ac16e2009-10-07 18:00:23 -07002462 if (mSettings.isTracing()) {
2463 String host;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002464 try {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002465 WebAddress uri = new WebAddress(url);
2466 host = uri.mHost;
2467 } catch (android.net.ParseException ex) {
2468 host = "browser";
The Android Open Source Project0c908882009-03-03 19:32:16 -08002469 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002470 host = host.replace('.', '_');
2471 host += ".trace";
2472 mInTrace = true;
2473 Debug.startMethodTracing(host, 20 * 1024 * 1024);
2474 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002475
Grace Kloba22ac16e2009-10-07 18:00:23 -07002476 // Performance probe
2477 if (false) {
2478 mStart = SystemClock.uptimeMillis();
2479 mProcessStart = Process.getElapsedCpuTime();
2480 long[] sysCpu = new long[7];
2481 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2482 sysCpu, null)) {
2483 mUserStart = sysCpu[0] + sysCpu[1];
2484 mSystemStart = sysCpu[2];
2485 mIdleStart = sysCpu[3];
2486 mIrqStart = sysCpu[4] + sysCpu[5] + sysCpu[6];
2487 }
2488 mUiStart = SystemClock.currentThreadTimeMillis();
2489 }
2490 }
2491
2492 void onPageFinished(WebView view, String url) {
2493 // Reset the title and icon in case we stopped a provisional load.
2494 resetTitleAndIcon(view);
2495 // Update the lock icon image only once we are done loading
2496 updateLockIconToLatest();
2497 // pause the WebView timer and release the wake lock if it is finished
2498 // while BrowserActivity is in pause state.
2499 if (mActivityInPause && pauseWebViewTimers()) {
2500 if (mWakeLock.isHeld()) {
2501 mHandler.removeMessages(RELEASE_WAKELOCK);
2502 mWakeLock.release();
2503 }
2504 }
2505
2506 // Performance probe
2507 if (false) {
2508 long[] sysCpu = new long[7];
2509 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2510 sysCpu, null)) {
2511 String uiInfo = "UI thread used "
2512 + (SystemClock.currentThreadTimeMillis() - mUiStart)
2513 + " ms";
2514 if (LOGD_ENABLED) {
2515 Log.d(LOGTAG, uiInfo);
2516 }
2517 //The string that gets written to the log
2518 String performanceString = "It took total "
2519 + (SystemClock.uptimeMillis() - mStart)
2520 + " ms clock time to load the page."
2521 + "\nbrowser process used "
2522 + (Process.getElapsedCpuTime() - mProcessStart)
2523 + " ms, user processes used "
2524 + (sysCpu[0] + sysCpu[1] - mUserStart) * 10
2525 + " ms, kernel used "
2526 + (sysCpu[2] - mSystemStart) * 10
2527 + " ms, idle took " + (sysCpu[3] - mIdleStart) * 10
2528 + " ms and irq took "
2529 + (sysCpu[4] + sysCpu[5] + sysCpu[6] - mIrqStart)
2530 * 10 + " ms, " + uiInfo;
2531 if (LOGD_ENABLED) {
2532 Log.d(LOGTAG, performanceString + "\nWebpage: " + url);
2533 }
2534 if (url != null) {
2535 // strip the url to maintain consistency
2536 String newUrl = new String(url);
2537 if (newUrl.startsWith("http://www.")) {
2538 newUrl = newUrl.substring(11);
2539 } else if (newUrl.startsWith("http://")) {
2540 newUrl = newUrl.substring(7);
2541 } else if (newUrl.startsWith("https://www.")) {
2542 newUrl = newUrl.substring(12);
2543 } else if (newUrl.startsWith("https://")) {
2544 newUrl = newUrl.substring(8);
2545 }
2546 if (LOGD_ENABLED) {
2547 Log.d(LOGTAG, newUrl + " loaded");
2548 }
Grace Kloba5b078b52009-06-24 20:23:41 -07002549 }
2550 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002551 }
Grace Kloba5b078b52009-06-24 20:23:41 -07002552
Grace Kloba22ac16e2009-10-07 18:00:23 -07002553 if (mInTrace) {
2554 mInTrace = false;
2555 Debug.stopMethodTracing();
2556 }
2557 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002558
Grace Kloba22ac16e2009-10-07 18:00:23 -07002559 boolean shouldOverrideUrlLoading(WebView view, String url) {
2560 if (url.startsWith(SCHEME_WTAI)) {
2561 // wtai://wp/mc;number
2562 // number=string(phone-number)
2563 if (url.startsWith(SCHEME_WTAI_MC)) {
2564 Intent intent = new Intent(Intent.ACTION_VIEW,
2565 Uri.parse(WebView.SCHEME_TEL +
2566 url.substring(SCHEME_WTAI_MC.length())));
2567 startActivity(intent);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002568 return true;
2569 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002570 // wtai://wp/sd;dtmf
2571 // dtmf=string(dialstring)
2572 if (url.startsWith(SCHEME_WTAI_SD)) {
2573 // TODO: only send when there is active voice connection
2574 return false;
2575 }
2576 // wtai://wp/ap;number;name
2577 // number=string(phone-number)
2578 // name=string
2579 if (url.startsWith(SCHEME_WTAI_AP)) {
2580 // TODO
2581 return false;
2582 }
2583 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002584
Grace Kloba22ac16e2009-10-07 18:00:23 -07002585 // The "about:" schemes are internal to the browser; don't want these to
2586 // be dispatched to other apps.
2587 if (url.startsWith("about:")) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002588 return false;
2589 }
2590
Grace Kloba22ac16e2009-10-07 18:00:23 -07002591 Intent intent;
2592 // perform generic parsing of the URI to turn it into an Intent.
2593 try {
2594 intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME);
2595 } catch (URISyntaxException ex) {
2596 Log.w("Browser", "Bad URI " + url + ": " + ex.getMessage());
2597 return false;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002598 }
2599
Grace Kloba22ac16e2009-10-07 18:00:23 -07002600 // check whether the intent can be resolved. If not, we will see
2601 // whether we can download it from the Market.
2602 if (getPackageManager().resolveActivity(intent, 0) == null) {
2603 String packagename = intent.getPackage();
2604 if (packagename != null) {
2605 intent = new Intent(Intent.ACTION_VIEW, Uri
2606 .parse("market://search?q=pname:" + packagename));
2607 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2608 startActivity(intent);
2609 return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002610 } else {
2611 return false;
2612 }
2613 }
2614
Grace Kloba22ac16e2009-10-07 18:00:23 -07002615 // sanitize the Intent, ensuring web pages can not bypass browser
2616 // security (only access to BROWSABLE activities).
2617 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2618 intent.setComponent(null);
2619 try {
2620 if (startActivityIfNeeded(intent, -1)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002621 return true;
2622 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002623 } catch (ActivityNotFoundException ex) {
2624 // ignore the error. If no application can handle the URL,
2625 // eg about:blank, assume the browser can handle it.
2626 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002627
Grace Kloba22ac16e2009-10-07 18:00:23 -07002628 if (mMenuIsDown) {
2629 openTab(url);
2630 closeOptionsMenu();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002631 return true;
2632 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002633 return false;
2634 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002635
Grace Kloba22ac16e2009-10-07 18:00:23 -07002636 // -------------------------------------------------------------------------
2637 // Helper function for WebChromeClient
2638 // -------------------------------------------------------------------------
The Android Open Source Project0c908882009-03-03 19:32:16 -08002639
Grace Kloba22ac16e2009-10-07 18:00:23 -07002640 void onProgressChanged(WebView view, int newProgress) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002641 mFakeTitleBar.setProgress(newProgress);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002642
Grace Kloba22ac16e2009-10-07 18:00:23 -07002643 if (newProgress == 100) {
2644 // onProgressChanged() may continue to be called after the main
2645 // frame has finished loading, as any remaining sub frames continue
2646 // to load. We'll only get called once though with newProgress as
2647 // 100 when everything is loaded. (onPageFinished is called once
2648 // when the main frame completes loading regardless of the state of
2649 // any sub frames so calls to onProgressChanges may continue after
2650 // onPageFinished has executed)
2651 if (mInLoad) {
2652 mInLoad = false;
Leon Scrogginsa27ff192009-09-14 12:58:04 -04002653 updateInLoadMenuItems();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002654 // If the options menu is open, leave the title bar
2655 if (!mOptionsMenuOpen || !mIconView) {
2656 hideFakeTitleBar();
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07002657 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002658 }
Leon Scrogginsaa37e7f2010-03-05 11:51:20 -05002659 } else {
2660 if (!mInLoad) {
2661 // onPageFinished may have already been called but a subframe is
2662 // still loading and updating the progress. Reset mInLoad and
2663 // update the menu items.
2664 mInLoad = true;
2665 updateInLoadMenuItems();
2666 }
2667 // When the page first begins to load, the Activity may still be
2668 // paused, in which case showFakeTitleBar will do nothing. Call
2669 // again as the page continues to load so that it will be shown.
2670 // (Calling it will the fake title bar is already showing will also
2671 // do nothing.
Grace Kloba22ac16e2009-10-07 18:00:23 -07002672 if (!mOptionsMenuOpen || mIconView) {
2673 // This page has begun to load, so show the title bar
2674 showFakeTitleBar();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002675 }
2676 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002677 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002678
Grace Kloba22ac16e2009-10-07 18:00:23 -07002679 void onShowCustomView(View view, WebChromeClient.CustomViewCallback callback) {
Derek Sollenberger8ff57db2009-12-08 15:39:55 -05002680 // if a view already exists then immediately terminate the new one
2681 if (mCustomView != null) {
2682 callback.onCustomViewHidden();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002683 return;
Derek Sollenberger8ff57db2009-12-08 15:39:55 -05002684 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002685
2686 // Add the custom view to its container.
2687 mCustomViewContainer.addView(view, COVER_SCREEN_GRAVITY_CENTER);
2688 mCustomView = view;
2689 mCustomViewCallback = callback;
2690 // Save the menu state and set it to empty while the custom
2691 // view is showing.
2692 mOldMenuState = mMenuState;
2693 mMenuState = EMPTY_MENU;
2694 // Hide the content view.
2695 mContentView.setVisibility(View.GONE);
2696 // Finally show the custom view container.
Andrei Popescu163ab742009-10-20 17:58:23 +01002697 setStatusBarVisibility(false);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002698 mCustomViewContainer.setVisibility(View.VISIBLE);
2699 mCustomViewContainer.bringToFront();
2700 }
2701
2702 void onHideCustomView() {
2703 if (mCustomView == null)
2704 return;
2705
2706 // Hide the custom view.
2707 mCustomView.setVisibility(View.GONE);
2708 // Remove the custom view from its container.
2709 mCustomViewContainer.removeView(mCustomView);
2710 mCustomView = null;
2711 // Reset the old menu state.
2712 mMenuState = mOldMenuState;
2713 mOldMenuState = EMPTY_MENU;
2714 mCustomViewContainer.setVisibility(View.GONE);
2715 mCustomViewCallback.onCustomViewHidden();
2716 // Show the content view.
Andrei Popescu163ab742009-10-20 17:58:23 +01002717 setStatusBarVisibility(true);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002718 mContentView.setVisibility(View.VISIBLE);
2719 }
2720
2721 Bitmap getDefaultVideoPoster() {
2722 if (mDefaultVideoPoster == null) {
2723 mDefaultVideoPoster = BitmapFactory.decodeResource(
2724 getResources(), R.drawable.default_video_poster);
Patrick Scott3918d442009-08-04 13:22:29 -04002725 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002726 return mDefaultVideoPoster;
2727 }
Patrick Scott3918d442009-08-04 13:22:29 -04002728
Grace Kloba22ac16e2009-10-07 18:00:23 -07002729 View getVideoLoadingProgressView() {
2730 if (mVideoProgressView == null) {
2731 LayoutInflater inflater = LayoutInflater.from(BrowserActivity.this);
2732 mVideoProgressView = inflater.inflate(
2733 R.layout.video_loading_progress, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002734 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002735 return mVideoProgressView;
2736 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002737
Leon Scroggins8d5fa432009-10-02 15:55:59 -04002738 /*
2739 * The Object used to inform the WebView of the file to upload.
2740 */
2741 private ValueCallback<Uri> mUploadMessage;
2742
Grace Kloba22ac16e2009-10-07 18:00:23 -07002743 void openFileChooser(ValueCallback<Uri> uploadMsg) {
2744 if (mUploadMessage != null) return;
2745 mUploadMessage = uploadMsg;
2746 Intent i = new Intent(Intent.ACTION_GET_CONTENT);
2747 i.addCategory(Intent.CATEGORY_OPENABLE);
2748 i.setType("*/*");
2749 BrowserActivity.this.startActivityForResult(Intent.createChooser(i,
2750 getString(R.string.choose_upload)), FILE_SELECTED);
2751 }
2752
2753 // -------------------------------------------------------------------------
2754 // Implement functions for DownloadListener
2755 // -------------------------------------------------------------------------
2756
The Android Open Source Project0c908882009-03-03 19:32:16 -08002757 /**
2758 * Notify the host application a download should be done, or that
2759 * the data should be streamed if a streaming viewer is available.
2760 * @param url The full url to the content that should be downloaded
2761 * @param contentDisposition Content-disposition http header, if
2762 * present.
2763 * @param mimetype The mimetype of the content reported by the server
2764 * @param contentLength The file size reported by the server
2765 */
2766 public void onDownloadStart(String url, String userAgent,
2767 String contentDisposition, String mimetype, long contentLength) {
2768 // if we're dealing wih A/V content that's not explicitly marked
2769 // for download, check if it's streamable.
2770 if (contentDisposition == null
Patrick Scotte1fb9662009-08-31 14:31:52 -04002771 || !contentDisposition.regionMatches(
2772 true, 0, "attachment", 0, 10)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002773 // query the package manager to see if there's a registered handler
2774 // that matches.
2775 Intent intent = new Intent(Intent.ACTION_VIEW);
2776 intent.setDataAndType(Uri.parse(url), mimetype);
Patrick Scotte1fb9662009-08-31 14:31:52 -04002777 ResolveInfo info = getPackageManager().resolveActivity(intent,
2778 PackageManager.MATCH_DEFAULT_ONLY);
2779 if (info != null) {
2780 ComponentName myName = getComponentName();
2781 // If we resolved to ourselves, we don't want to attempt to
2782 // load the url only to try and download it again.
2783 if (!myName.getPackageName().equals(
2784 info.activityInfo.packageName)
2785 || !myName.getClassName().equals(
2786 info.activityInfo.name)) {
2787 // someone (other than us) knows how to handle this mime
2788 // type with this scheme, don't download.
2789 try {
2790 startActivity(intent);
2791 return;
2792 } catch (ActivityNotFoundException ex) {
2793 if (LOGD_ENABLED) {
2794 Log.d(LOGTAG, "activity not found for " + mimetype
2795 + " over " + Uri.parse(url).getScheme(),
2796 ex);
2797 }
2798 // Best behavior is to fall back to a download in this
2799 // case
The Android Open Source Project0c908882009-03-03 19:32:16 -08002800 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002801 }
2802 }
2803 }
2804 onDownloadStartNoStream(url, userAgent, contentDisposition, mimetype, contentLength);
2805 }
2806
Kristian Monsenfa52d172010-03-25 18:29:21 +00002807 // This is to work around the fact that java.net.URI throws Exceptions
2808 // instead of just encoding URL's properly
2809 // Helper method for onDownloadStartNoStream
2810 private static String encodePath(String path) {
2811 char[] chars = path.toCharArray();
2812
2813 boolean needed = false;
2814 for (char c : chars) {
2815 if (c == '[' || c == ']') {
2816 needed = true;
2817 break;
2818 }
2819 }
2820 if (needed == false) {
2821 return path;
2822 }
2823
2824 StringBuilder sb = new StringBuilder("");
2825 for (char c : chars) {
2826 if (c == '[' || c == ']') {
2827 sb.append('%');
2828 sb.append(Integer.toHexString(c));
2829 } else {
2830 sb.append(c);
2831 }
2832 }
2833
2834 return sb.toString();
2835 }
2836
The Android Open Source Project0c908882009-03-03 19:32:16 -08002837 /**
2838 * Notify the host application a download should be done, even if there
2839 * is a streaming viewer available for thise type.
2840 * @param url The full url to the content that should be downloaded
2841 * @param contentDisposition Content-disposition http header, if
2842 * present.
2843 * @param mimetype The mimetype of the content reported by the server
2844 * @param contentLength The file size reported by the server
2845 */
2846 /*package */ void onDownloadStartNoStream(String url, String userAgent,
2847 String contentDisposition, String mimetype, long contentLength) {
2848
2849 String filename = URLUtil.guessFileName(url,
2850 contentDisposition, mimetype);
2851
2852 // Check to see if we have an SDCard
2853 String status = Environment.getExternalStorageState();
2854 if (!status.equals(Environment.MEDIA_MOUNTED)) {
2855 int title;
2856 String msg;
2857
2858 // Check to see if the SDCard is busy, same as the music app
2859 if (status.equals(Environment.MEDIA_SHARED)) {
2860 msg = getString(R.string.download_sdcard_busy_dlg_msg);
2861 title = R.string.download_sdcard_busy_dlg_title;
2862 } else {
2863 msg = getString(R.string.download_no_sdcard_dlg_msg, filename);
2864 title = R.string.download_no_sdcard_dlg_title;
2865 }
2866
2867 new AlertDialog.Builder(this)
2868 .setTitle(title)
2869 .setIcon(android.R.drawable.ic_dialog_alert)
2870 .setMessage(msg)
2871 .setPositiveButton(R.string.ok, null)
2872 .show();
2873 return;
2874 }
2875
Kristian Monsenfa52d172010-03-25 18:29:21 +00002876 // java.net.URI is a lot stricter than KURL so we have to encode some
2877 // extra characters. Fix for b 2538060 and b 1634719
2878 WebAddress webAddress;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002879 try {
Kristian Monsenfa52d172010-03-25 18:29:21 +00002880 webAddress = new WebAddress(url);
2881 webAddress.mPath = encodePath(webAddress.mPath);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002882 } catch (Exception e) {
Kristian Monsenfa52d172010-03-25 18:29:21 +00002883 // This only happens for very bad urls, we want to chatch the
2884 // exception here
2885 Log.e(LOGTAG, "Exception trying to parse url:" + url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002886 return;
2887 }
2888
2889 // XXX: Have to use the old url since the cookies were stored using the
2890 // old percent-encoded url.
2891 String cookies = CookieManager.getInstance().getCookie(url);
2892
2893 ContentValues values = new ContentValues();
Kristian Monsenfa52d172010-03-25 18:29:21 +00002894 values.put(Downloads.Impl.COLUMN_URI, webAddress.toString());
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08002895 values.put(Downloads.Impl.COLUMN_COOKIE_DATA, cookies);
2896 values.put(Downloads.Impl.COLUMN_USER_AGENT, userAgent);
2897 values.put(Downloads.Impl.COLUMN_NOTIFICATION_PACKAGE,
The Android Open Source Project0c908882009-03-03 19:32:16 -08002898 getPackageName());
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08002899 values.put(Downloads.Impl.COLUMN_NOTIFICATION_CLASS,
The Android Open Source Project0c908882009-03-03 19:32:16 -08002900 BrowserDownloadPage.class.getCanonicalName());
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08002901 values.put(Downloads.Impl.COLUMN_VISIBILITY,
2902 Downloads.Impl.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
2903 values.put(Downloads.Impl.COLUMN_MIME_TYPE, mimetype);
2904 values.put(Downloads.Impl.COLUMN_FILE_NAME_HINT, filename);
Kristian Monsenfa52d172010-03-25 18:29:21 +00002905 values.put(Downloads.Impl.COLUMN_DESCRIPTION, webAddress.mHost);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002906 if (contentLength > 0) {
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08002907 values.put(Downloads.Impl.COLUMN_TOTAL_BYTES, contentLength);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002908 }
2909 if (mimetype == null) {
2910 // We must have long pressed on a link or image to download it. We
2911 // are not sure of the mimetype in this case, so do a head request
2912 new FetchUrlMimeType(this).execute(values);
2913 } else {
2914 final Uri contentUri =
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08002915 getContentResolver().insert(Downloads.Impl.CONTENT_URI, values);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002916 }
Leon Scroggins9191a7f2010-03-18 14:44:44 -04002917 Toast.makeText(this, R.string.download_pending, Toast.LENGTH_SHORT)
2918 .show();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002919 }
2920
Grace Kloba22ac16e2009-10-07 18:00:23 -07002921 // -------------------------------------------------------------------------
2922
The Android Open Source Project0c908882009-03-03 19:32:16 -08002923 /**
2924 * Resets the lock icon. This method is called when we start a new load and
2925 * know the url to be loaded.
2926 */
2927 private void resetLockIcon(String url) {
2928 // Save the lock-icon state (we revert to it if the load gets cancelled)
Grace Kloba22ac16e2009-10-07 18:00:23 -07002929 mTabControl.getCurrentTab().resetLockIcon(url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002930 updateLockIconImage(LOCK_ICON_UNSECURE);
2931 }
2932
The Android Open Source Project0c908882009-03-03 19:32:16 -08002933 /**
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04002934 * Update the lock icon to correspond to our latest state.
2935 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07002936 private void updateLockIconToLatest() {
2937 updateLockIconImage(mTabControl.getCurrentTab().getLockIconType());
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04002938 }
2939
2940 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08002941 * Updates the lock-icon image in the title-bar.
2942 */
2943 private void updateLockIconImage(int lockIconType) {
2944 Drawable d = null;
2945 if (lockIconType == LOCK_ICON_SECURE) {
2946 d = mSecLockIcon;
2947 } else if (lockIconType == LOCK_ICON_MIXED) {
2948 d = mMixLockIcon;
2949 }
Leon Scroggins68579392009-09-15 15:31:54 -04002950 mTitleBar.setLock(d);
Leon Scrogginsfe87bd32009-10-06 10:10:00 -04002951 mFakeTitleBar.setLock(d);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002952 }
2953
2954 /**
2955 * Displays a page-info dialog.
2956 * @param tab The tab to show info about
2957 * @param fromShowSSLCertificateOnError The flag that indicates whether
2958 * this dialog was opened from the SSL-certificate-on-error dialog or
2959 * not. This is important, since we need to know whether to return to
2960 * the parent dialog or simply dismiss.
2961 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07002962 private void showPageInfo(final Tab tab,
The Android Open Source Project0c908882009-03-03 19:32:16 -08002963 final boolean fromShowSSLCertificateOnError) {
2964 final LayoutInflater factory = LayoutInflater
2965 .from(this);
2966
2967 final View pageInfoView = factory.inflate(R.layout.page_info, null);
2968
2969 final WebView view = tab.getWebView();
2970
2971 String url = null;
2972 String title = null;
2973
2974 if (view == null) {
2975 url = tab.getUrl();
2976 title = tab.getTitle();
2977 } else if (view == mTabControl.getCurrentWebView()) {
2978 // Use the cached title and url if this is the current WebView
2979 url = mUrl;
2980 title = mTitle;
2981 } else {
2982 url = view.getUrl();
2983 title = view.getTitle();
2984 }
2985
2986 if (url == null) {
2987 url = "";
2988 }
2989 if (title == null) {
2990 title = "";
2991 }
2992
2993 ((TextView) pageInfoView.findViewById(R.id.address)).setText(url);
2994 ((TextView) pageInfoView.findViewById(R.id.title)).setText(title);
2995
2996 mPageInfoView = tab;
Leon Scrogginsc7b92f82010-01-11 18:17:31 -05002997 mPageInfoFromShowSSLCertificateOnError = fromShowSSLCertificateOnError;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002998
2999 AlertDialog.Builder alertDialogBuilder =
3000 new AlertDialog.Builder(this)
3001 .setTitle(R.string.page_info).setIcon(android.R.drawable.ic_dialog_info)
3002 .setView(pageInfoView)
3003 .setPositiveButton(
3004 R.string.ok,
3005 new DialogInterface.OnClickListener() {
3006 public void onClick(DialogInterface dialog,
3007 int whichButton) {
3008 mPageInfoDialog = null;
3009 mPageInfoView = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003010
3011 // if we came here from the SSL error dialog
3012 if (fromShowSSLCertificateOnError) {
3013 // go back to the SSL error dialog
3014 showSSLCertificateOnError(
3015 mSSLCertificateOnErrorView,
3016 mSSLCertificateOnErrorHandler,
3017 mSSLCertificateOnErrorError);
3018 }
3019 }
3020 })
3021 .setOnCancelListener(
3022 new DialogInterface.OnCancelListener() {
3023 public void onCancel(DialogInterface dialog) {
3024 mPageInfoDialog = null;
3025 mPageInfoView = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003026
3027 // if we came here from the SSL error dialog
3028 if (fromShowSSLCertificateOnError) {
3029 // go back to the SSL error dialog
3030 showSSLCertificateOnError(
3031 mSSLCertificateOnErrorView,
3032 mSSLCertificateOnErrorHandler,
3033 mSSLCertificateOnErrorError);
3034 }
3035 }
3036 });
3037
3038 // if we have a main top-level page SSL certificate set or a certificate
3039 // error
3040 if (fromShowSSLCertificateOnError ||
3041 (view != null && view.getCertificate() != null)) {
3042 // add a 'View Certificate' button
3043 alertDialogBuilder.setNeutralButton(
3044 R.string.view_certificate,
3045 new DialogInterface.OnClickListener() {
3046 public void onClick(DialogInterface dialog,
3047 int whichButton) {
3048 mPageInfoDialog = null;
3049 mPageInfoView = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003050
3051 // if we came here from the SSL error dialog
3052 if (fromShowSSLCertificateOnError) {
3053 // go back to the SSL error dialog
3054 showSSLCertificateOnError(
3055 mSSLCertificateOnErrorView,
3056 mSSLCertificateOnErrorHandler,
3057 mSSLCertificateOnErrorError);
3058 } else {
3059 // otherwise, display the top-most certificate from
3060 // the chain
3061 if (view.getCertificate() != null) {
3062 showSSLCertificate(tab);
3063 }
3064 }
3065 }
3066 });
3067 }
3068
3069 mPageInfoDialog = alertDialogBuilder.show();
3070 }
3071
3072 /**
3073 * Displays the main top-level page SSL certificate dialog
3074 * (accessible from the Page-Info dialog).
3075 * @param tab The tab to show certificate for.
3076 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003077 private void showSSLCertificate(final Tab tab) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003078 final View certificateView =
3079 inflateCertificateView(tab.getWebView().getCertificate());
3080 if (certificateView == null) {
3081 return;
3082 }
3083
3084 LayoutInflater factory = LayoutInflater.from(this);
3085
3086 final LinearLayout placeholder =
3087 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3088
3089 LinearLayout ll = (LinearLayout) factory.inflate(
3090 R.layout.ssl_success, placeholder);
3091 ((TextView)ll.findViewById(R.id.success))
3092 .setText(R.string.ssl_certificate_is_valid);
3093
3094 mSSLCertificateView = tab;
3095 mSSLCertificateDialog =
3096 new AlertDialog.Builder(this)
3097 .setTitle(R.string.ssl_certificate).setIcon(
3098 R.drawable.ic_dialog_browser_certificate_secure)
3099 .setView(certificateView)
3100 .setPositiveButton(R.string.ok,
3101 new DialogInterface.OnClickListener() {
3102 public void onClick(DialogInterface dialog,
3103 int whichButton) {
3104 mSSLCertificateDialog = null;
3105 mSSLCertificateView = null;
3106
3107 showPageInfo(tab, false);
3108 }
3109 })
3110 .setOnCancelListener(
3111 new DialogInterface.OnCancelListener() {
3112 public void onCancel(DialogInterface dialog) {
3113 mSSLCertificateDialog = null;
3114 mSSLCertificateView = null;
3115
3116 showPageInfo(tab, false);
3117 }
3118 })
3119 .show();
3120 }
3121
3122 /**
3123 * Displays the SSL error certificate dialog.
3124 * @param view The target web-view.
3125 * @param handler The SSL error handler responsible for cancelling the
3126 * connection that resulted in an SSL error or proceeding per user request.
3127 * @param error The SSL error object.
3128 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003129 void showSSLCertificateOnError(
The Android Open Source Project0c908882009-03-03 19:32:16 -08003130 final WebView view, final SslErrorHandler handler, final SslError error) {
3131
3132 final View certificateView =
3133 inflateCertificateView(error.getCertificate());
3134 if (certificateView == null) {
3135 return;
3136 }
3137
3138 LayoutInflater factory = LayoutInflater.from(this);
3139
3140 final LinearLayout placeholder =
3141 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3142
3143 if (error.hasError(SslError.SSL_UNTRUSTED)) {
3144 LinearLayout ll = (LinearLayout)factory
3145 .inflate(R.layout.ssl_warning, placeholder);
3146 ((TextView)ll.findViewById(R.id.warning))
3147 .setText(R.string.ssl_untrusted);
3148 }
3149
3150 if (error.hasError(SslError.SSL_IDMISMATCH)) {
3151 LinearLayout ll = (LinearLayout)factory
3152 .inflate(R.layout.ssl_warning, placeholder);
3153 ((TextView)ll.findViewById(R.id.warning))
3154 .setText(R.string.ssl_mismatch);
3155 }
3156
3157 if (error.hasError(SslError.SSL_EXPIRED)) {
3158 LinearLayout ll = (LinearLayout)factory
3159 .inflate(R.layout.ssl_warning, placeholder);
3160 ((TextView)ll.findViewById(R.id.warning))
3161 .setText(R.string.ssl_expired);
3162 }
3163
3164 if (error.hasError(SslError.SSL_NOTYETVALID)) {
3165 LinearLayout ll = (LinearLayout)factory
3166 .inflate(R.layout.ssl_warning, placeholder);
3167 ((TextView)ll.findViewById(R.id.warning))
3168 .setText(R.string.ssl_not_yet_valid);
3169 }
3170
3171 mSSLCertificateOnErrorHandler = handler;
3172 mSSLCertificateOnErrorView = view;
3173 mSSLCertificateOnErrorError = error;
3174 mSSLCertificateOnErrorDialog =
3175 new AlertDialog.Builder(this)
3176 .setTitle(R.string.ssl_certificate).setIcon(
3177 R.drawable.ic_dialog_browser_certificate_partially_secure)
3178 .setView(certificateView)
3179 .setPositiveButton(R.string.ok,
3180 new DialogInterface.OnClickListener() {
3181 public void onClick(DialogInterface dialog,
3182 int whichButton) {
3183 mSSLCertificateOnErrorDialog = null;
3184 mSSLCertificateOnErrorView = null;
3185 mSSLCertificateOnErrorHandler = null;
3186 mSSLCertificateOnErrorError = null;
3187
Grace Kloba22ac16e2009-10-07 18:00:23 -07003188 view.getWebViewClient().onReceivedSslError(
3189 view, handler, error);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003190 }
3191 })
3192 .setNeutralButton(R.string.page_info_view,
3193 new DialogInterface.OnClickListener() {
3194 public void onClick(DialogInterface dialog,
3195 int whichButton) {
3196 mSSLCertificateOnErrorDialog = null;
3197
3198 // do not clear the dialog state: we will
3199 // need to show the dialog again once the
3200 // user is done exploring the page-info details
3201
3202 showPageInfo(mTabControl.getTabFromView(view),
3203 true);
3204 }
3205 })
3206 .setOnCancelListener(
3207 new DialogInterface.OnCancelListener() {
3208 public void onCancel(DialogInterface dialog) {
3209 mSSLCertificateOnErrorDialog = null;
3210 mSSLCertificateOnErrorView = null;
3211 mSSLCertificateOnErrorHandler = null;
3212 mSSLCertificateOnErrorError = null;
3213
Grace Kloba22ac16e2009-10-07 18:00:23 -07003214 view.getWebViewClient().onReceivedSslError(
3215 view, handler, error);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003216 }
3217 })
3218 .show();
3219 }
3220
3221 /**
3222 * Inflates the SSL certificate view (helper method).
3223 * @param certificate The SSL certificate.
3224 * @return The resultant certificate view with issued-to, issued-by,
3225 * issued-on, expires-on, and possibly other fields set.
3226 * If the input certificate is null, returns null.
3227 */
3228 private View inflateCertificateView(SslCertificate certificate) {
3229 if (certificate == null) {
3230 return null;
3231 }
3232
3233 LayoutInflater factory = LayoutInflater.from(this);
3234
3235 View certificateView = factory.inflate(
3236 R.layout.ssl_certificate, null);
3237
3238 // issued to:
3239 SslCertificate.DName issuedTo = certificate.getIssuedTo();
3240 if (issuedTo != null) {
3241 ((TextView) certificateView.findViewById(R.id.to_common))
3242 .setText(issuedTo.getCName());
3243 ((TextView) certificateView.findViewById(R.id.to_org))
3244 .setText(issuedTo.getOName());
3245 ((TextView) certificateView.findViewById(R.id.to_org_unit))
3246 .setText(issuedTo.getUName());
3247 }
3248
3249 // issued by:
3250 SslCertificate.DName issuedBy = certificate.getIssuedBy();
3251 if (issuedBy != null) {
3252 ((TextView) certificateView.findViewById(R.id.by_common))
3253 .setText(issuedBy.getCName());
3254 ((TextView) certificateView.findViewById(R.id.by_org))
3255 .setText(issuedBy.getOName());
3256 ((TextView) certificateView.findViewById(R.id.by_org_unit))
3257 .setText(issuedBy.getUName());
3258 }
3259
3260 // issued on:
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003261 String issuedOn = formatCertificateDate(
3262 certificate.getValidNotBeforeDate());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003263 ((TextView) certificateView.findViewById(R.id.issued_on))
3264 .setText(issuedOn);
3265
3266 // expires on:
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003267 String expiresOn = formatCertificateDate(
3268 certificate.getValidNotAfterDate());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003269 ((TextView) certificateView.findViewById(R.id.expires_on))
3270 .setText(expiresOn);
3271
3272 return certificateView;
3273 }
3274
3275 /**
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003276 * Formats the certificate date to a properly localized date string.
The Android Open Source Project0c908882009-03-03 19:32:16 -08003277 * @return Properly localized version of the certificate date string and
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003278 * the "" if it fails to localize.
The Android Open Source Project0c908882009-03-03 19:32:16 -08003279 */
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003280 private String formatCertificateDate(Date certificateDate) {
3281 if (certificateDate == null) {
3282 return "";
The Android Open Source Project0c908882009-03-03 19:32:16 -08003283 }
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003284 String formattedDate = DateFormat.getDateFormat(this).format(certificateDate);
3285 if (formattedDate == null) {
3286 return "";
3287 }
3288 return formattedDate;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003289 }
3290
3291 /**
3292 * Displays an http-authentication dialog.
3293 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003294 void showHttpAuthentication(final HttpAuthHandler handler,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003295 final String host, final String realm, final String title,
3296 final String name, final String password, int focusId) {
3297 LayoutInflater factory = LayoutInflater.from(this);
3298 final View v = factory
3299 .inflate(R.layout.http_authentication, null);
3300 if (name != null) {
3301 ((EditText) v.findViewById(R.id.username_edit)).setText(name);
3302 }
3303 if (password != null) {
3304 ((EditText) v.findViewById(R.id.password_edit)).setText(password);
3305 }
3306
3307 String titleText = title;
3308 if (titleText == null) {
3309 titleText = getText(R.string.sign_in_to).toString().replace(
3310 "%s1", host).replace("%s2", realm);
3311 }
3312
3313 mHttpAuthHandler = handler;
3314 AlertDialog dialog = new AlertDialog.Builder(this)
3315 .setTitle(titleText)
3316 .setIcon(android.R.drawable.ic_dialog_alert)
3317 .setView(v)
3318 .setPositiveButton(R.string.action,
3319 new DialogInterface.OnClickListener() {
3320 public void onClick(DialogInterface dialog,
3321 int whichButton) {
3322 String nm = ((EditText) v
3323 .findViewById(R.id.username_edit))
3324 .getText().toString();
3325 String pw = ((EditText) v
3326 .findViewById(R.id.password_edit))
3327 .getText().toString();
3328 BrowserActivity.this.setHttpAuthUsernamePassword
3329 (host, realm, nm, pw);
3330 handler.proceed(nm, pw);
3331 mHttpAuthenticationDialog = null;
3332 mHttpAuthHandler = null;
3333 }})
3334 .setNegativeButton(R.string.cancel,
3335 new DialogInterface.OnClickListener() {
3336 public void onClick(DialogInterface dialog,
3337 int whichButton) {
3338 handler.cancel();
3339 BrowserActivity.this.resetTitleAndRevertLockIcon();
3340 mHttpAuthenticationDialog = null;
3341 mHttpAuthHandler = null;
3342 }})
3343 .setOnCancelListener(new DialogInterface.OnCancelListener() {
3344 public void onCancel(DialogInterface dialog) {
3345 handler.cancel();
3346 BrowserActivity.this.resetTitleAndRevertLockIcon();
3347 mHttpAuthenticationDialog = null;
3348 mHttpAuthHandler = null;
3349 }})
3350 .create();
3351 // Make the IME appear when the dialog is displayed if applicable.
3352 dialog.getWindow().setSoftInputMode(
3353 WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
3354 dialog.show();
3355 if (focusId != 0) {
3356 dialog.findViewById(focusId).requestFocus();
3357 } else {
3358 v.findViewById(R.id.username_edit).requestFocus();
3359 }
3360 mHttpAuthenticationDialog = dialog;
3361 }
3362
3363 public int getProgress() {
3364 WebView w = mTabControl.getCurrentWebView();
3365 if (w != null) {
3366 return w.getProgress();
3367 } else {
3368 return 100;
3369 }
3370 }
3371
3372 /**
3373 * Set HTTP authentication password.
3374 *
3375 * @param host The host for the password
3376 * @param realm The realm for the password
3377 * @param username The username for the password. If it is null, it means
3378 * password can't be saved.
3379 * @param password The password
3380 */
3381 public void setHttpAuthUsernamePassword(String host, String realm,
3382 String username,
3383 String password) {
Steve Block95a53b22010-03-25 17:24:58 +00003384 WebView w = getTopWindow();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003385 if (w != null) {
3386 w.setHttpAuthUsernamePassword(host, realm, username, password);
3387 }
3388 }
3389
3390 /**
3391 * connectivity manager says net has come or gone... inform the user
3392 * @param up true if net has come up, false if net has gone down
3393 */
3394 public void onNetworkToggle(boolean up) {
3395 if (up == mIsNetworkUp) {
3396 return;
3397 } else if (up) {
3398 mIsNetworkUp = true;
3399 if (mAlertDialog != null) {
3400 mAlertDialog.cancel();
3401 mAlertDialog = null;
3402 }
3403 } else {
3404 mIsNetworkUp = false;
Patrick Scotteb6ab2a2009-09-16 10:00:17 -04003405 if (mInLoad) {
3406 createAndShowNetworkDialog();
3407 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003408 }
3409 WebView w = mTabControl.getCurrentWebView();
3410 if (w != null) {
3411 w.setNetworkAvailable(up);
3412 }
3413 }
3414
Grace Kloba22ac16e2009-10-07 18:00:23 -07003415 boolean isNetworkUp() {
3416 return mIsNetworkUp;
3417 }
3418
Patrick Scotteb6ab2a2009-09-16 10:00:17 -04003419 // This method shows the network dialog alerting the user that the net is
3420 // down. It will only show the dialog if mAlertDialog is null.
3421 private void createAndShowNetworkDialog() {
3422 if (mAlertDialog == null) {
3423 mAlertDialog = new AlertDialog.Builder(this)
3424 .setTitle(R.string.loadSuspendedTitle)
3425 .setMessage(R.string.loadSuspended)
3426 .setPositiveButton(R.string.ok, null)
3427 .show();
3428 }
3429 }
3430
The Android Open Source Project0c908882009-03-03 19:32:16 -08003431 @Override
3432 protected void onActivityResult(int requestCode, int resultCode,
3433 Intent intent) {
Grace Klobabb394f32009-11-19 10:26:37 -08003434 if (getTopWindow() == null) return;
3435
The Android Open Source Project0c908882009-03-03 19:32:16 -08003436 switch (requestCode) {
3437 case COMBO_PAGE:
3438 if (resultCode == RESULT_OK && intent != null) {
3439 String data = intent.getAction();
3440 Bundle extras = intent.getExtras();
3441 if (extras != null && extras.getBoolean("new_window", false)) {
Leon Scroggins25d35472009-09-15 11:37:27 -04003442 openTab(data);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003443 } else {
Grace Kloba22ac16e2009-10-07 18:00:23 -07003444 final Tab currentTab =
The Android Open Source Project0c908882009-03-03 19:32:16 -08003445 mTabControl.getCurrentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04003446 dismissSubWindow(currentTab);
3447 if (data != null && data.length() != 0) {
Leon Scroggins92472e82010-02-17 16:32:28 -05003448 loadUrl(getTopWindow(), data);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003449 }
3450 }
3451 }
Leon Scrogginsfde97462010-01-11 13:06:21 -05003452 // Deliberately fall through to PREFERENCES_PAGE, since the
3453 // same extra may be attached to the COMBO_PAGE
3454 case PREFERENCES_PAGE:
3455 if (resultCode == RESULT_OK && intent != null) {
3456 String action = intent.getStringExtra(Intent.EXTRA_TEXT);
3457 if (BrowserSettings.PREF_CLEAR_HISTORY.equals(action)) {
3458 mTabControl.removeParentChildRelationShips();
3459 }
3460 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003461 break;
Leon Scroggins8d5fa432009-10-02 15:55:59 -04003462 // Choose a file from the file picker.
3463 case FILE_SELECTED:
3464 if (null == mUploadMessage) break;
3465 Uri result = intent == null || resultCode != RESULT_OK ? null
3466 : intent.getData();
3467 mUploadMessage.onReceiveValue(result);
3468 mUploadMessage = null;
3469 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003470 default:
3471 break;
3472 }
Leon Scroggins30444232009-09-04 18:36:20 -04003473 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003474 }
3475
3476 /*
3477 * This method is called as a result of the user selecting the options
Leon Scrogginsf08809b2010-01-21 09:27:46 -05003478 * menu to see the download window. It shows the download window on top of
3479 * the current window.
The Android Open Source Project0c908882009-03-03 19:32:16 -08003480 */
Leon Scrogginsf08809b2010-01-21 09:27:46 -05003481 private void viewDownloads(Uri downloadRecord) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003482 Intent intent = new Intent(this,
3483 BrowserDownloadPage.class);
3484 intent.setData(downloadRecord);
Grace Kloba22ac16e2009-10-07 18:00:23 -07003485 startActivityForResult(intent, BrowserActivity.DOWNLOAD_PAGE);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003486
3487 }
3488
Leon Scroggins160a7e72009-08-14 18:28:01 -04003489 /**
3490 * Open the Go page.
3491 * @param startWithHistory If true, open starting on the history tab.
3492 * Otherwise, start with the bookmarks tab.
Leon Scroggins160a7e72009-08-14 18:28:01 -04003493 */
Leon Scroggins30444232009-09-04 18:36:20 -04003494 /* package */ void bookmarksOrHistoryPicker(boolean startWithHistory) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003495 WebView current = mTabControl.getCurrentWebView();
3496 if (current == null) {
3497 return;
3498 }
3499 Intent intent = new Intent(this,
3500 CombinedBookmarkHistoryActivity.class);
3501 String title = current.getTitle();
3502 String url = current.getUrl();
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01003503 Bitmap thumbnail = createScreenshot(current);
3504
The Android Open Source Project0c908882009-03-03 19:32:16 -08003505 // Just in case the user opens bookmarks before a page finishes loading
3506 // so the current history item, and therefore the page, is null.
3507 if (null == url) {
3508 url = mLastEnteredUrl;
3509 // This can happen.
3510 if (null == url) {
3511 url = mSettings.getHomePage();
3512 }
3513 }
3514 // In case the web page has not yet received its associated title.
3515 if (title == null) {
3516 title = url;
3517 }
3518 intent.putExtra("title", title);
3519 intent.putExtra("url", url);
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01003520 intent.putExtra("thumbnail", thumbnail);
Leon Scroggins30444232009-09-04 18:36:20 -04003521 // Disable opening in a new window if we have maxed out the windows
Grace Kloba22ac16e2009-10-07 18:00:23 -07003522 intent.putExtra("disable_new_window", !mTabControl.canCreateNewTab());
Patrick Scott3918d442009-08-04 13:22:29 -04003523 intent.putExtra("touch_icon_url", current.getTouchIconUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003524 if (startWithHistory) {
3525 intent.putExtra(CombinedBookmarkHistoryActivity.STARTING_TAB,
3526 CombinedBookmarkHistoryActivity.HISTORY_TAB);
3527 }
3528 startActivityForResult(intent, COMBO_PAGE);
3529 }
3530
3531 // Called when loading from context menu or LOAD_URL message
Leon Scroggins92472e82010-02-17 16:32:28 -05003532 private void loadUrlFromContext(WebView view, String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003533 // In case the user enters nothing.
3534 if (url != null && url.length() != 0 && view != null) {
3535 url = smartUrlFilter(url);
Grace Kloba22ac16e2009-10-07 18:00:23 -07003536 if (!view.getWebViewClient().shouldOverrideUrlLoading(view, url)) {
Leon Scroggins92472e82010-02-17 16:32:28 -05003537 loadUrl(view, url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003538 }
3539 }
3540 }
3541
Leon Scroggins92472e82010-02-17 16:32:28 -05003542 /**
3543 * Load the URL into the given WebView and update the title bar
3544 * to reflect the new load. Call this instead of WebView.loadUrl
3545 * directly.
3546 * @param view The WebView used to load url.
3547 * @param url The URL to load.
3548 */
3549 private void loadUrl(WebView view, String url) {
3550 updateTitleBarForNewLoad(view, url);
3551 view.loadUrl(url);
3552 }
3553
3554 /**
3555 * Load UrlData into a Tab and update the title bar to reflect the new
3556 * load. Call this instead of UrlData.loadIn directly.
3557 * @param t The Tab used to load.
3558 * @param data The UrlData being loaded.
3559 */
3560 private void loadUrlDataIn(Tab t, UrlData data) {
3561 updateTitleBarForNewLoad(t.getWebView(), data.mUrl);
3562 data.loadIn(t);
3563 }
3564
3565 /**
3566 * If the WebView is the top window, update the title bar to reflect
3567 * loading the new URL. i.e. set its text, clear the favicon (which
3568 * will be set once the page begins loading), and set the progress to
3569 * INITIAL_PROGRESS to show that the page has begun to load. Called
3570 * by loadUrl and loadUrlDataIn.
3571 * @param view The WebView that is starting a load.
3572 * @param url The URL that is being loaded.
3573 */
3574 private void updateTitleBarForNewLoad(WebView view, String url) {
3575 if (view == getTopWindow()) {
3576 setUrlTitle(url, null);
3577 setFavicon(null);
3578 onProgressChanged(view, INITIAL_PROGRESS);
3579 }
3580 }
3581
The Android Open Source Project0c908882009-03-03 19:32:16 -08003582 private String smartUrlFilter(Uri inUri) {
3583 if (inUri != null) {
3584 return smartUrlFilter(inUri.toString());
3585 }
3586 return null;
3587 }
3588
Feng Qianb34f87a2009-03-24 21:27:26 -07003589 protected static final Pattern ACCEPTED_URI_SCHEMA = Pattern.compile(
The Android Open Source Project0c908882009-03-03 19:32:16 -08003590 "(?i)" + // switch on case insensitive matching
3591 "(" + // begin group for schema
3592 "(?:http|https|file):\\/\\/" +
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003593 "|(?:inline|data|about|content|javascript):" +
The Android Open Source Project0c908882009-03-03 19:32:16 -08003594 ")" +
3595 "(.*)" );
3596
3597 /**
3598 * Attempts to determine whether user input is a URL or search
3599 * terms. Anything with a space is passed to search.
3600 *
3601 * Converts to lowercase any mistakenly uppercased schema (i.e.,
3602 * "Http://" converts to "http://"
3603 *
3604 * @return Original or modified URL
3605 *
3606 */
3607 String smartUrlFilter(String url) {
3608
3609 String inUrl = url.trim();
3610 boolean hasSpace = inUrl.indexOf(' ') != -1;
3611
3612 Matcher matcher = ACCEPTED_URI_SCHEMA.matcher(inUrl);
3613 if (matcher.matches()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003614 // force scheme to lowercase
3615 String scheme = matcher.group(1);
3616 String lcScheme = scheme.toLowerCase();
3617 if (!lcScheme.equals(scheme)) {
Mitsuru Oshima123ecfb2009-05-18 19:11:14 -07003618 inUrl = lcScheme + matcher.group(2);
3619 }
3620 if (hasSpace) {
3621 inUrl = inUrl.replace(" ", "%20");
The Android Open Source Project0c908882009-03-03 19:32:16 -08003622 }
3623 return inUrl;
3624 }
3625 if (hasSpace) {
Satish Sampath565505b2009-05-29 15:37:27 +01003626 // FIXME: Is this the correct place to add to searches?
3627 // what if someone else calls this function?
3628 int shortcut = parseUrlShortcut(inUrl);
3629 if (shortcut != SHORTCUT_INVALID) {
3630 Browser.addSearchUrl(mResolver, inUrl);
3631 String query = inUrl.substring(2);
3632 switch (shortcut) {
3633 case SHORTCUT_GOOGLE_SEARCH:
Grace Kloba47fdfdb2009-06-30 11:15:34 -07003634 return URLUtil.composeSearchUrl(query, QuickSearch_G, QUERY_PLACE_HOLDER);
Satish Sampath565505b2009-05-29 15:37:27 +01003635 case SHORTCUT_WIKIPEDIA_SEARCH:
3636 return URLUtil.composeSearchUrl(query, QuickSearch_W, QUERY_PLACE_HOLDER);
3637 case SHORTCUT_DICTIONARY_SEARCH:
3638 return URLUtil.composeSearchUrl(query, QuickSearch_D, QUERY_PLACE_HOLDER);
3639 case SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH:
The Android Open Source Project0c908882009-03-03 19:32:16 -08003640 // FIXME: we need location in this case
Satish Sampath565505b2009-05-29 15:37:27 +01003641 return URLUtil.composeSearchUrl(query, QuickSearch_L, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003642 }
3643 }
3644 } else {
Dan Egnor5ee906c2009-11-18 12:11:49 -08003645 if (Patterns.WEB_URL.matcher(inUrl).matches()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003646 return URLUtil.guessUrl(inUrl);
3647 }
3648 }
3649
3650 Browser.addSearchUrl(mResolver, inUrl);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07003651 return URLUtil.composeSearchUrl(inUrl, QuickSearch_G, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003652 }
3653
Ben Murdochbff2d602009-07-01 20:19:05 +01003654 /* package */ void setShouldShowErrorConsole(boolean flag) {
3655 if (flag == mShouldShowErrorConsole) {
3656 // Nothing to do.
3657 return;
3658 }
3659
3660 mShouldShowErrorConsole = flag;
3661
Grace Kloba22ac16e2009-10-07 18:00:23 -07003662 ErrorConsoleView errorConsole = mTabControl.getCurrentTab()
3663 .getErrorConsole(true);
Ben Murdochbff2d602009-07-01 20:19:05 +01003664
3665 if (flag) {
3666 // Setting the show state of the console will cause it's the layout to be inflated.
3667 if (errorConsole.numberOfErrors() > 0) {
3668 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
3669 } else {
3670 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
3671 }
3672
3673 // Now we can add it to the main view.
3674 mErrorConsoleContainer.addView(errorConsole,
Romain Guy15b8ec62010-01-08 15:06:43 -08003675 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
Ben Murdochbff2d602009-07-01 20:19:05 +01003676 ViewGroup.LayoutParams.WRAP_CONTENT));
3677 } else {
3678 mErrorConsoleContainer.removeView(errorConsole);
3679 }
3680
3681 }
3682
Grace Kloba22ac16e2009-10-07 18:00:23 -07003683 boolean shouldShowErrorConsole() {
3684 return mShouldShowErrorConsole;
3685 }
3686
Andrei Popescu163ab742009-10-20 17:58:23 +01003687 private void setStatusBarVisibility(boolean visible) {
3688 int flag = visible ? 0 : WindowManager.LayoutParams.FLAG_FULLSCREEN;
3689 getWindow().setFlags(flag, WindowManager.LayoutParams.FLAG_FULLSCREEN);
3690 }
3691
Andrei Popescu56199cc2010-01-12 22:39:16 +00003692
3693 private void sendNetworkType(String type, String subtype) {
3694 WebView w = mTabControl.getCurrentWebView();
3695 if (w != null) {
3696 w.setNetworkType(type, subtype);
3697 }
3698 }
3699
Andrei Popescu30995e72010-02-09 16:59:58 +00003700 private void packageChanged(String packageName, boolean wasAdded) {
3701 WebView w = mTabControl.getCurrentWebView();
3702 if (w == null) {
3703 return;
3704 }
3705
3706 if (wasAdded) {
3707 w.addPackageName(packageName);
3708 } else {
3709 w.removePackageName(packageName);
3710 }
3711 }
3712
3713 private void addPackageNames(Set<String> packageNames) {
3714 WebView w = mTabControl.getCurrentWebView();
3715 if (w == null) {
3716 return;
3717 }
3718
3719 w.addPackageNames(packageNames);
3720 }
3721
3722 private void getInstalledPackages() {
3723 AsyncTask<Void, Void, Set<String> > task =
3724 new AsyncTask<Void, Void, Set<String> >() {
3725 protected Set<String> doInBackground(Void... unused) {
3726 Set<String> installedPackages = new HashSet<String>();
3727 PackageManager pm = BrowserActivity.this.getPackageManager();
3728 if (pm != null) {
3729 List<PackageInfo> packages = pm.getInstalledPackages(0);
3730 for (PackageInfo p : packages) {
3731 if (BrowserActivity.this.sGoogleApps.contains(p.packageName)) {
3732 installedPackages.add(p.packageName);
3733 }
3734 }
3735 }
3736
3737 return installedPackages;
3738 }
3739
3740 // Executes on the UI thread
3741 protected void onPostExecute(Set<String> installedPackages) {
3742 addPackageNames(installedPackages);
3743 }
3744 };
3745 task.execute();
3746 }
3747
Grace Klobaeb6eef42009-09-15 17:56:32 -07003748 final static int LOCK_ICON_UNSECURE = 0;
3749 final static int LOCK_ICON_SECURE = 1;
3750 final static int LOCK_ICON_MIXED = 2;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003751
The Android Open Source Project0c908882009-03-03 19:32:16 -08003752 private BrowserSettings mSettings;
3753 private TabControl mTabControl;
3754 private ContentResolver mResolver;
3755 private FrameLayout mContentView;
Andrei Popescuadc008d2009-06-26 14:11:30 +01003756 private View mCustomView;
3757 private FrameLayout mCustomViewContainer;
Andrei Popescuc9b55562009-07-07 10:51:15 +01003758 private WebChromeClient.CustomViewCallback mCustomViewCallback;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003759
3760 // FIXME, temp address onPrepareMenu performance problem. When we move everything out of
3761 // view, we should rewrite this.
3762 private int mCurrentMenuState = 0;
3763 private int mMenuState = R.id.MAIN_MENU;
Andrei Popescuadc008d2009-06-26 14:11:30 +01003764 private int mOldMenuState = EMPTY_MENU;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003765 private static final int EMPTY_MENU = -1;
3766 private Menu mMenu;
3767
3768 private FindDialog mFindDialog;
3769 // Used to prevent chording to result in firing two shortcuts immediately
3770 // one after another. Fixes bug 1211714.
3771 boolean mCanChord;
3772
3773 private boolean mInLoad;
3774 private boolean mIsNetworkUp;
Ben Murdochb7cc8b42009-09-28 10:59:09 +01003775 private boolean mDidStopLoad;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003776
Cary Clark1f10cbf2010-03-22 11:45:23 -04003777 /* package */ boolean mActivityInPause = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003778
3779 private boolean mMenuIsDown;
3780
The Android Open Source Project0c908882009-03-03 19:32:16 -08003781 private static boolean mInTrace;
3782
3783 // Performance probe
3784 private static final int[] SYSTEM_CPU_FORMAT = new int[] {
3785 Process.PROC_SPACE_TERM | Process.PROC_COMBINE,
3786 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 1: user time
3787 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 2: nice time
3788 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 3: sys time
3789 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 4: idle time
3790 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 5: iowait time
3791 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 6: irq time
3792 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG // 7: softirq time
3793 };
3794
3795 private long mStart;
3796 private long mProcessStart;
3797 private long mUserStart;
3798 private long mSystemStart;
3799 private long mIdleStart;
3800 private long mIrqStart;
3801
3802 private long mUiStart;
3803
3804 private Drawable mMixLockIcon;
3805 private Drawable mSecLockIcon;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003806
3807 /* hold a ref so we can auto-cancel if necessary */
3808 private AlertDialog mAlertDialog;
3809
The Android Open Source Project0c908882009-03-03 19:32:16 -08003810 // The up-to-date URL and title (these can be different from those stored
3811 // in WebView, since it takes some time for the information in WebView to
3812 // get updated)
3813 private String mUrl;
3814 private String mTitle;
3815
3816 // As PageInfo has different style for landscape / portrait, we have
3817 // to re-open it when configuration changed
3818 private AlertDialog mPageInfoDialog;
Grace Kloba22ac16e2009-10-07 18:00:23 -07003819 private Tab mPageInfoView;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003820 // If the Page-Info dialog is launched from the SSL-certificate-on-error
3821 // dialog, we should not just dismiss it, but should get back to the
3822 // SSL-certificate-on-error dialog. This flag is used to store this state
Leon Scrogginsc7b92f82010-01-11 18:17:31 -05003823 private boolean mPageInfoFromShowSSLCertificateOnError;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003824
3825 // as SSLCertificateOnError has different style for landscape / portrait,
3826 // we have to re-open it when configuration changed
3827 private AlertDialog mSSLCertificateOnErrorDialog;
3828 private WebView mSSLCertificateOnErrorView;
3829 private SslErrorHandler mSSLCertificateOnErrorHandler;
3830 private SslError mSSLCertificateOnErrorError;
3831
3832 // as SSLCertificate has different style for landscape / portrait, we
3833 // have to re-open it when configuration changed
3834 private AlertDialog mSSLCertificateDialog;
Grace Kloba22ac16e2009-10-07 18:00:23 -07003835 private Tab mSSLCertificateView;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003836
3837 // as HttpAuthentication has different style for landscape / portrait, we
3838 // have to re-open it when configuration changed
3839 private AlertDialog mHttpAuthenticationDialog;
3840 private HttpAuthHandler mHttpAuthHandler;
3841
3842 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_PARAMS =
3843 new FrameLayout.LayoutParams(
Romain Guy15b8ec62010-01-08 15:06:43 -08003844 ViewGroup.LayoutParams.MATCH_PARENT,
3845 ViewGroup.LayoutParams.MATCH_PARENT);
Andrei Popescuadc008d2009-06-26 14:11:30 +01003846 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_GRAVITY_CENTER =
3847 new FrameLayout.LayoutParams(
Romain Guy15b8ec62010-01-08 15:06:43 -08003848 ViewGroup.LayoutParams.MATCH_PARENT,
3849 ViewGroup.LayoutParams.MATCH_PARENT,
Andrei Popescuadc008d2009-06-26 14:11:30 +01003850 Gravity.CENTER);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07003851 // Google search
3852 final static String QuickSearch_G = "http://www.google.com/m?q=%s";
The Android Open Source Project0c908882009-03-03 19:32:16 -08003853 // Wikipedia search
3854 final static String QuickSearch_W = "http://en.wikipedia.org/w/index.php?search=%s&go=Go";
3855 // Dictionary search
3856 final static String QuickSearch_D = "http://dictionary.reference.com/search?q=%s";
3857 // Google Mobile Local search
3858 final static String QuickSearch_L = "http://www.google.com/m/search?site=local&q=%s&near=mountain+view";
3859
3860 final static String QUERY_PLACE_HOLDER = "%s";
3861
3862 // "source" parameter for Google search through search key
3863 final static String GOOGLE_SEARCH_SOURCE_SEARCHKEY = "browser-key";
3864 // "source" parameter for Google search through goto menu
3865 final static String GOOGLE_SEARCH_SOURCE_GOTO = "browser-goto";
3866 // "source" parameter for Google search through simplily type
3867 final static String GOOGLE_SEARCH_SOURCE_TYPE = "browser-type";
3868 // "source" parameter for Google search suggested by the browser
3869 final static String GOOGLE_SEARCH_SOURCE_SUGGEST = "browser-suggest";
3870 // "source" parameter for Google search from unknown source
3871 final static String GOOGLE_SEARCH_SOURCE_UNKNOWN = "unknown";
3872
3873 private final static String LOGTAG = "browser";
3874
The Android Open Source Project0c908882009-03-03 19:32:16 -08003875 private String mLastEnteredUrl;
3876
3877 private PowerManager.WakeLock mWakeLock;
3878 private final static int WAKELOCK_TIMEOUT = 5 * 60 * 1000; // 5 minutes
3879
3880 private Toast mStopToast;
3881
Leon Scroggins68579392009-09-15 15:31:54 -04003882 private TitleBar mTitleBar;
Leon Scroggins81db3662009-06-04 17:45:11 -04003883
Ben Murdochbff2d602009-07-01 20:19:05 +01003884 private LinearLayout mErrorConsoleContainer = null;
3885 private boolean mShouldShowErrorConsole = false;
3886
The Android Open Source Project0c908882009-03-03 19:32:16 -08003887 // As the ids are dynamically created, we can't guarantee that they will
3888 // be in sequence, so this static array maps ids to a window number.
3889 final static private int[] WINDOW_SHORTCUT_ID_ARRAY =
3890 { R.id.window_one_menu_id, R.id.window_two_menu_id, R.id.window_three_menu_id,
3891 R.id.window_four_menu_id, R.id.window_five_menu_id, R.id.window_six_menu_id,
3892 R.id.window_seven_menu_id, R.id.window_eight_menu_id };
3893
3894 // monitor platform changes
3895 private IntentFilter mNetworkStateChangedFilter;
3896 private BroadcastReceiver mNetworkStateIntentReceiver;
3897
Grace Klobab4da0ad2009-05-14 14:45:40 -07003898 private BroadcastReceiver mPackageInstallationReceiver;
3899
Bjorn Bringerta7611812010-03-24 11:12:02 +00003900 private SystemAllowGeolocationOrigins mSystemAllowGeolocationOrigins;
3901
The Android Open Source Project0c908882009-03-03 19:32:16 -08003902 // activity requestCode
Nicolas Roard78a98e42009-05-11 13:34:17 +01003903 final static int COMBO_PAGE = 1;
3904 final static int DOWNLOAD_PAGE = 2;
3905 final static int PREFERENCES_PAGE = 3;
Leon Scroggins8d5fa432009-10-02 15:55:59 -04003906 final static int FILE_SELECTED = 4;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003907
Andrei Popescu540035d2009-09-18 18:59:20 +01003908 // the default <video> poster
3909 private Bitmap mDefaultVideoPoster;
3910 // the video progress view
3911 private View mVideoProgressView;
3912
Andrei Popescu30995e72010-02-09 16:59:58 +00003913 // The Google packages we monitor for the navigator.isApplicationInstalled()
3914 // API. Add as needed.
3915 private static Set<String> sGoogleApps;
3916 static {
3917 sGoogleApps = new HashSet<String>();
3918 sGoogleApps.add("com.google.android.youtube");
3919 }
3920
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003921 /**
3922 * A UrlData class to abstract how the content will be set to WebView.
3923 * This base class uses loadUrl to show the content.
3924 */
Leon Scroggins6eac63e2010-03-15 18:19:14 -04003925 /* package */ static class UrlData {
Grace Kloba068e48b2010-01-26 18:11:27 -08003926 final String mUrl;
3927 final Map<String, String> mHeaders;
Leon Scroggins58d56c62010-01-28 15:12:40 -05003928 final Intent mVoiceIntent;
Grace Kloba60e095c2009-06-16 11:50:55 -07003929
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003930 UrlData(String url) {
3931 this.mUrl = url;
Grace Kloba068e48b2010-01-26 18:11:27 -08003932 this.mHeaders = null;
Leon Scroggins58d56c62010-01-28 15:12:40 -05003933 this.mVoiceIntent = null;
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003934 }
Grace Kloba60e095c2009-06-16 11:50:55 -07003935
Leon Scroggins58d56c62010-01-28 15:12:40 -05003936 UrlData(String url, Map<String, String> headers, Intent intent) {
Grace Kloba068e48b2010-01-26 18:11:27 -08003937 this.mUrl = url;
3938 this.mHeaders = headers;
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -05003939 if (RecognizerResultsIntent.ACTION_VOICE_SEARCH_RESULTS
3940 .equals(intent.getAction())) {
Leon Scroggins58d56c62010-01-28 15:12:40 -05003941 this.mVoiceIntent = intent;
3942 } else {
3943 this.mVoiceIntent = null;
3944 }
Grace Kloba60e095c2009-06-16 11:50:55 -07003945 }
3946
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003947 boolean isEmpty() {
Leon Scroggins58d56c62010-01-28 15:12:40 -05003948 return mVoiceIntent == null && (mUrl == null || mUrl.length() == 0);
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003949 }
3950
Leon Scroggins92472e82010-02-17 16:32:28 -05003951 /**
3952 * Load this UrlData into the given Tab. Use loadUrlDataIn to update
3953 * the title bar as well.
3954 */
Leon Scroggins58d56c62010-01-28 15:12:40 -05003955 public void loadIn(Tab t) {
3956 if (mVoiceIntent != null) {
3957 t.activateVoiceSearchMode(mVoiceIntent);
3958 } else {
3959 t.getWebView().loadUrl(mUrl, mHeaders);
3960 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003961 }
3962 };
3963
Leon Scroggins1f005d32009-08-10 17:36:42 -04003964 /* package */ static final UrlData EMPTY_URL_DATA = new UrlData(null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003965}