blob: 1f969afaf086d99b0d9a7fcc75e0f44791bf13ad [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 Scott3918d442009-08-04 13:22:29 -04002317 ContentResolver cr = getContentResolver();
2318 final Cursor c = BrowserBookmarksAdapter.queryBookmarksForUrl(
Ben Murdochaac7aa62009-09-17 16:57:40 +01002319 cr, view.getOriginalUrl(), view.getUrl(), true);
Patrick Scott3918d442009-08-04 13:22:29 -04002320 if (c != null) {
Leon Scroggins89c6d362009-07-15 16:54:37 -04002321 boolean succeed = c.moveToFirst();
2322 ContentValues values = null;
2323 while (succeed) {
2324 if (values == null) {
2325 final ByteArrayOutputStream os
2326 = new ByteArrayOutputStream();
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002327 Bitmap bm = createScreenshot(view);
Leon Scroggins45800572009-09-29 16:38:47 -04002328 if (bm == null) {
2329 c.close();
2330 return;
2331 }
Leon Scroggins89c6d362009-07-15 16:54:37 -04002332 bm.compress(Bitmap.CompressFormat.PNG, 100, os);
2333 values = new ContentValues();
2334 values.put(Browser.BookmarkColumns.THUMBNAIL,
2335 os.toByteArray());
2336 }
2337 cr.update(ContentUris.withAppendedId(Browser.BOOKMARKS_URI,
2338 c.getInt(0)), values, null, null);
2339 succeed = c.moveToNext();
2340 }
2341 c.close();
2342 }
2343 }
2344
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002345 /**
Leon Scrogginsf8551612009-09-24 16:06:02 -04002346 * Values for the size of the thumbnail created when taking a screenshot.
2347 * Lazily initialized. Instead of using these directly, use
2348 * getDesiredThumbnailWidth() or getDesiredThumbnailHeight().
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002349 */
Leon Scrogginsf8551612009-09-24 16:06:02 -04002350 private static int THUMBNAIL_WIDTH = 0;
2351 private static int THUMBNAIL_HEIGHT = 0;
2352
2353 /**
2354 * Return the desired width for thumbnail screenshots, which are stored in
2355 * the database, and used on the bookmarks screen.
2356 * @param context Context for finding out the density of the screen.
2357 * @return int desired width for thumbnail screenshot.
2358 */
2359 /* package */ static int getDesiredThumbnailWidth(Context context) {
2360 if (THUMBNAIL_WIDTH == 0) {
2361 float density = context.getResources().getDisplayMetrics().density;
2362 THUMBNAIL_WIDTH = (int) (90 * density);
2363 THUMBNAIL_HEIGHT = (int) (80 * density);
2364 }
2365 return THUMBNAIL_WIDTH;
2366 }
2367
2368 /**
2369 * Return the desired height for thumbnail screenshots, which are stored in
2370 * the database, and used on the bookmarks screen.
2371 * @param context Context for finding out the density of the screen.
2372 * @return int desired height for thumbnail screenshot.
2373 */
2374 /* package */ static int getDesiredThumbnailHeight(Context context) {
2375 // To ensure that they are both initialized.
2376 getDesiredThumbnailWidth(context);
2377 return THUMBNAIL_HEIGHT;
2378 }
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002379
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002380 private Bitmap createScreenshot(WebView view) {
2381 Picture thumbnail = view.capturePicture();
Leon Scroggins45800572009-09-29 16:38:47 -04002382 if (thumbnail == null) {
2383 return null;
2384 }
Leon Scrogginsf8551612009-09-24 16:06:02 -04002385 Bitmap bm = Bitmap.createBitmap(getDesiredThumbnailWidth(this),
Cary Clarkab168ba2010-04-08 09:11:28 -04002386 getDesiredThumbnailHeight(this), Bitmap.Config.RGB_565);
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002387 Canvas canvas = new Canvas(bm);
2388 // May need to tweak these values to determine what is the
2389 // best scale factor
Ben Murdoch2694e232009-09-29 09:41:11 +01002390 int thumbnailWidth = thumbnail.getWidth();
Ben Murdochae59c3f2009-10-20 18:30:28 +01002391 int thumbnailHeight = thumbnail.getHeight();
2392 float scaleFactorX = 1.0f;
2393 float scaleFactorY = 1.0f;
Ben Murdoch2694e232009-09-29 09:41:11 +01002394 if (thumbnailWidth > 0) {
Ben Murdochae59c3f2009-10-20 18:30:28 +01002395 scaleFactorX = (float) getDesiredThumbnailWidth(this) /
Ben Murdoch2694e232009-09-29 09:41:11 +01002396 (float)thumbnailWidth;
Ben Murdochae59c3f2009-10-20 18:30:28 +01002397 } else {
2398 return null;
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002399 }
Ben Murdochae59c3f2009-10-20 18:30:28 +01002400
2401 if (view.getWidth() > view.getHeight() &&
2402 thumbnailHeight < view.getHeight() && thumbnailHeight > 0) {
2403 // If the device is in landscape and the page is shorter
2404 // than the height of the view, stretch the thumbnail to fill the
2405 // space.
2406 scaleFactorY = (float) getDesiredThumbnailHeight(this) /
2407 (float)thumbnailHeight;
2408 } else {
2409 // In the portrait case, this looks nice.
2410 scaleFactorY = scaleFactorX;
2411 }
2412
2413 canvas.scale(scaleFactorX, scaleFactorY);
2414
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002415 thumbnail.draw(canvas);
2416 return bm;
2417 }
2418
The Android Open Source Project0c908882009-03-03 19:32:16 -08002419 // -------------------------------------------------------------------------
Grace Kloba22ac16e2009-10-07 18:00:23 -07002420 // Helper function for WebViewClient.
The Android Open Source Project0c908882009-03-03 19:32:16 -08002421 //-------------------------------------------------------------------------
2422
2423 // Use in overrideUrlLoading
2424 /* package */ final static String SCHEME_WTAI = "wtai://wp/";
2425 /* package */ final static String SCHEME_WTAI_MC = "wtai://wp/mc;";
2426 /* package */ final static String SCHEME_WTAI_SD = "wtai://wp/sd;";
2427 /* package */ final static String SCHEME_WTAI_AP = "wtai://wp/ap;";
2428
Leon Scroggins92472e82010-02-17 16:32:28 -05002429 // Keep this initial progress in sync with initialProgressValue (* 100)
2430 // in ProgressTracker.cpp
2431 private final static int INITIAL_PROGRESS = 10;
2432
Grace Kloba22ac16e2009-10-07 18:00:23 -07002433 void onPageStarted(WebView view, String url, Bitmap favicon) {
2434 // when BrowserActivity just starts, onPageStarted may be called before
2435 // onResume as it is triggered from onCreate. Call resumeWebViewTimers
2436 // to start the timer. As we won't switch tabs while an activity is in
2437 // pause state, we can ensure calling resume and pause in pair.
2438 if (mActivityInPause) resumeWebViewTimers();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002439
Grace Kloba22ac16e2009-10-07 18:00:23 -07002440 resetLockIcon(url);
2441 setUrlTitle(url, null);
2442 setFavicon(favicon);
Leon Scroggins8cf8f682009-11-04 11:13:50 -08002443 // Show some progress so that the user knows the page is beginning to
2444 // load
Leon Scroggins92472e82010-02-17 16:32:28 -05002445 onProgressChanged(view, INITIAL_PROGRESS);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002446 mDidStopLoad = false;
Grace Kloba22ac16e2009-10-07 18:00:23 -07002447 if (!mIsNetworkUp) createAndShowNetworkDialog();
Patrick Scott15525d42009-09-21 13:39:37 -04002448
Grace Kloba22ac16e2009-10-07 18:00:23 -07002449 if (mSettings.isTracing()) {
2450 String host;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002451 try {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002452 WebAddress uri = new WebAddress(url);
2453 host = uri.mHost;
2454 } catch (android.net.ParseException ex) {
2455 host = "browser";
The Android Open Source Project0c908882009-03-03 19:32:16 -08002456 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002457 host = host.replace('.', '_');
2458 host += ".trace";
2459 mInTrace = true;
2460 Debug.startMethodTracing(host, 20 * 1024 * 1024);
2461 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002462
Grace Kloba22ac16e2009-10-07 18:00:23 -07002463 // Performance probe
2464 if (false) {
2465 mStart = SystemClock.uptimeMillis();
2466 mProcessStart = Process.getElapsedCpuTime();
2467 long[] sysCpu = new long[7];
2468 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2469 sysCpu, null)) {
2470 mUserStart = sysCpu[0] + sysCpu[1];
2471 mSystemStart = sysCpu[2];
2472 mIdleStart = sysCpu[3];
2473 mIrqStart = sysCpu[4] + sysCpu[5] + sysCpu[6];
2474 }
2475 mUiStart = SystemClock.currentThreadTimeMillis();
2476 }
2477 }
2478
2479 void onPageFinished(WebView view, String url) {
2480 // Reset the title and icon in case we stopped a provisional load.
2481 resetTitleAndIcon(view);
2482 // Update the lock icon image only once we are done loading
2483 updateLockIconToLatest();
2484 // pause the WebView timer and release the wake lock if it is finished
2485 // while BrowserActivity is in pause state.
2486 if (mActivityInPause && pauseWebViewTimers()) {
2487 if (mWakeLock.isHeld()) {
2488 mHandler.removeMessages(RELEASE_WAKELOCK);
2489 mWakeLock.release();
2490 }
2491 }
2492
2493 // Performance probe
2494 if (false) {
2495 long[] sysCpu = new long[7];
2496 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2497 sysCpu, null)) {
2498 String uiInfo = "UI thread used "
2499 + (SystemClock.currentThreadTimeMillis() - mUiStart)
2500 + " ms";
2501 if (LOGD_ENABLED) {
2502 Log.d(LOGTAG, uiInfo);
2503 }
2504 //The string that gets written to the log
2505 String performanceString = "It took total "
2506 + (SystemClock.uptimeMillis() - mStart)
2507 + " ms clock time to load the page."
2508 + "\nbrowser process used "
2509 + (Process.getElapsedCpuTime() - mProcessStart)
2510 + " ms, user processes used "
2511 + (sysCpu[0] + sysCpu[1] - mUserStart) * 10
2512 + " ms, kernel used "
2513 + (sysCpu[2] - mSystemStart) * 10
2514 + " ms, idle took " + (sysCpu[3] - mIdleStart) * 10
2515 + " ms and irq took "
2516 + (sysCpu[4] + sysCpu[5] + sysCpu[6] - mIrqStart)
2517 * 10 + " ms, " + uiInfo;
2518 if (LOGD_ENABLED) {
2519 Log.d(LOGTAG, performanceString + "\nWebpage: " + url);
2520 }
2521 if (url != null) {
2522 // strip the url to maintain consistency
2523 String newUrl = new String(url);
2524 if (newUrl.startsWith("http://www.")) {
2525 newUrl = newUrl.substring(11);
2526 } else if (newUrl.startsWith("http://")) {
2527 newUrl = newUrl.substring(7);
2528 } else if (newUrl.startsWith("https://www.")) {
2529 newUrl = newUrl.substring(12);
2530 } else if (newUrl.startsWith("https://")) {
2531 newUrl = newUrl.substring(8);
2532 }
2533 if (LOGD_ENABLED) {
2534 Log.d(LOGTAG, newUrl + " loaded");
2535 }
Grace Kloba5b078b52009-06-24 20:23:41 -07002536 }
2537 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002538 }
Grace Kloba5b078b52009-06-24 20:23:41 -07002539
Grace Kloba22ac16e2009-10-07 18:00:23 -07002540 if (mInTrace) {
2541 mInTrace = false;
2542 Debug.stopMethodTracing();
2543 }
2544 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002545
Grace Kloba22ac16e2009-10-07 18:00:23 -07002546 boolean shouldOverrideUrlLoading(WebView view, String url) {
2547 if (url.startsWith(SCHEME_WTAI)) {
2548 // wtai://wp/mc;number
2549 // number=string(phone-number)
2550 if (url.startsWith(SCHEME_WTAI_MC)) {
2551 Intent intent = new Intent(Intent.ACTION_VIEW,
2552 Uri.parse(WebView.SCHEME_TEL +
2553 url.substring(SCHEME_WTAI_MC.length())));
2554 startActivity(intent);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002555 return true;
2556 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002557 // wtai://wp/sd;dtmf
2558 // dtmf=string(dialstring)
2559 if (url.startsWith(SCHEME_WTAI_SD)) {
2560 // TODO: only send when there is active voice connection
2561 return false;
2562 }
2563 // wtai://wp/ap;number;name
2564 // number=string(phone-number)
2565 // name=string
2566 if (url.startsWith(SCHEME_WTAI_AP)) {
2567 // TODO
2568 return false;
2569 }
2570 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002571
Grace Kloba22ac16e2009-10-07 18:00:23 -07002572 // The "about:" schemes are internal to the browser; don't want these to
2573 // be dispatched to other apps.
2574 if (url.startsWith("about:")) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002575 return false;
2576 }
2577
Grace Kloba22ac16e2009-10-07 18:00:23 -07002578 Intent intent;
2579 // perform generic parsing of the URI to turn it into an Intent.
2580 try {
2581 intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME);
2582 } catch (URISyntaxException ex) {
2583 Log.w("Browser", "Bad URI " + url + ": " + ex.getMessage());
2584 return false;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002585 }
2586
Grace Kloba22ac16e2009-10-07 18:00:23 -07002587 // check whether the intent can be resolved. If not, we will see
2588 // whether we can download it from the Market.
2589 if (getPackageManager().resolveActivity(intent, 0) == null) {
2590 String packagename = intent.getPackage();
2591 if (packagename != null) {
2592 intent = new Intent(Intent.ACTION_VIEW, Uri
2593 .parse("market://search?q=pname:" + packagename));
2594 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2595 startActivity(intent);
2596 return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002597 } else {
2598 return false;
2599 }
2600 }
2601
Grace Kloba22ac16e2009-10-07 18:00:23 -07002602 // sanitize the Intent, ensuring web pages can not bypass browser
2603 // security (only access to BROWSABLE activities).
2604 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2605 intent.setComponent(null);
2606 try {
2607 if (startActivityIfNeeded(intent, -1)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002608 return true;
2609 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002610 } catch (ActivityNotFoundException ex) {
2611 // ignore the error. If no application can handle the URL,
2612 // eg about:blank, assume the browser can handle it.
2613 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002614
Grace Kloba22ac16e2009-10-07 18:00:23 -07002615 if (mMenuIsDown) {
2616 openTab(url);
2617 closeOptionsMenu();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002618 return true;
2619 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002620 return false;
2621 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002622
Grace Kloba22ac16e2009-10-07 18:00:23 -07002623 // -------------------------------------------------------------------------
2624 // Helper function for WebChromeClient
2625 // -------------------------------------------------------------------------
The Android Open Source Project0c908882009-03-03 19:32:16 -08002626
Grace Kloba22ac16e2009-10-07 18:00:23 -07002627 void onProgressChanged(WebView view, int newProgress) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002628 mFakeTitleBar.setProgress(newProgress);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002629
Grace Kloba22ac16e2009-10-07 18:00:23 -07002630 if (newProgress == 100) {
2631 // onProgressChanged() may continue to be called after the main
2632 // frame has finished loading, as any remaining sub frames continue
2633 // to load. We'll only get called once though with newProgress as
2634 // 100 when everything is loaded. (onPageFinished is called once
2635 // when the main frame completes loading regardless of the state of
2636 // any sub frames so calls to onProgressChanges may continue after
2637 // onPageFinished has executed)
2638 if (mInLoad) {
2639 mInLoad = false;
Leon Scrogginsa27ff192009-09-14 12:58:04 -04002640 updateInLoadMenuItems();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002641 // If the options menu is open, leave the title bar
2642 if (!mOptionsMenuOpen || !mIconView) {
2643 hideFakeTitleBar();
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07002644 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002645 }
Leon Scrogginsaa37e7f2010-03-05 11:51:20 -05002646 } else {
2647 if (!mInLoad) {
2648 // onPageFinished may have already been called but a subframe is
2649 // still loading and updating the progress. Reset mInLoad and
2650 // update the menu items.
2651 mInLoad = true;
2652 updateInLoadMenuItems();
2653 }
2654 // When the page first begins to load, the Activity may still be
2655 // paused, in which case showFakeTitleBar will do nothing. Call
2656 // again as the page continues to load so that it will be shown.
2657 // (Calling it will the fake title bar is already showing will also
2658 // do nothing.
Grace Kloba22ac16e2009-10-07 18:00:23 -07002659 if (!mOptionsMenuOpen || mIconView) {
2660 // This page has begun to load, so show the title bar
2661 showFakeTitleBar();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002662 }
2663 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002664 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002665
Grace Kloba22ac16e2009-10-07 18:00:23 -07002666 void onShowCustomView(View view, WebChromeClient.CustomViewCallback callback) {
Derek Sollenberger8ff57db2009-12-08 15:39:55 -05002667 // if a view already exists then immediately terminate the new one
2668 if (mCustomView != null) {
2669 callback.onCustomViewHidden();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002670 return;
Derek Sollenberger8ff57db2009-12-08 15:39:55 -05002671 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002672
2673 // Add the custom view to its container.
2674 mCustomViewContainer.addView(view, COVER_SCREEN_GRAVITY_CENTER);
2675 mCustomView = view;
2676 mCustomViewCallback = callback;
2677 // Save the menu state and set it to empty while the custom
2678 // view is showing.
2679 mOldMenuState = mMenuState;
2680 mMenuState = EMPTY_MENU;
2681 // Hide the content view.
2682 mContentView.setVisibility(View.GONE);
2683 // Finally show the custom view container.
Andrei Popescu163ab742009-10-20 17:58:23 +01002684 setStatusBarVisibility(false);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002685 mCustomViewContainer.setVisibility(View.VISIBLE);
2686 mCustomViewContainer.bringToFront();
2687 }
2688
2689 void onHideCustomView() {
2690 if (mCustomView == null)
2691 return;
2692
2693 // Hide the custom view.
2694 mCustomView.setVisibility(View.GONE);
2695 // Remove the custom view from its container.
2696 mCustomViewContainer.removeView(mCustomView);
2697 mCustomView = null;
2698 // Reset the old menu state.
2699 mMenuState = mOldMenuState;
2700 mOldMenuState = EMPTY_MENU;
2701 mCustomViewContainer.setVisibility(View.GONE);
2702 mCustomViewCallback.onCustomViewHidden();
2703 // Show the content view.
Andrei Popescu163ab742009-10-20 17:58:23 +01002704 setStatusBarVisibility(true);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002705 mContentView.setVisibility(View.VISIBLE);
2706 }
2707
2708 Bitmap getDefaultVideoPoster() {
2709 if (mDefaultVideoPoster == null) {
2710 mDefaultVideoPoster = BitmapFactory.decodeResource(
2711 getResources(), R.drawable.default_video_poster);
Patrick Scott3918d442009-08-04 13:22:29 -04002712 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002713 return mDefaultVideoPoster;
2714 }
Patrick Scott3918d442009-08-04 13:22:29 -04002715
Grace Kloba22ac16e2009-10-07 18:00:23 -07002716 View getVideoLoadingProgressView() {
2717 if (mVideoProgressView == null) {
2718 LayoutInflater inflater = LayoutInflater.from(BrowserActivity.this);
2719 mVideoProgressView = inflater.inflate(
2720 R.layout.video_loading_progress, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002721 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002722 return mVideoProgressView;
2723 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002724
Leon Scroggins8d5fa432009-10-02 15:55:59 -04002725 /*
2726 * The Object used to inform the WebView of the file to upload.
2727 */
2728 private ValueCallback<Uri> mUploadMessage;
2729
Grace Kloba22ac16e2009-10-07 18:00:23 -07002730 void openFileChooser(ValueCallback<Uri> uploadMsg) {
2731 if (mUploadMessage != null) return;
2732 mUploadMessage = uploadMsg;
2733 Intent i = new Intent(Intent.ACTION_GET_CONTENT);
2734 i.addCategory(Intent.CATEGORY_OPENABLE);
2735 i.setType("*/*");
2736 BrowserActivity.this.startActivityForResult(Intent.createChooser(i,
2737 getString(R.string.choose_upload)), FILE_SELECTED);
2738 }
2739
2740 // -------------------------------------------------------------------------
2741 // Implement functions for DownloadListener
2742 // -------------------------------------------------------------------------
2743
The Android Open Source Project0c908882009-03-03 19:32:16 -08002744 /**
2745 * Notify the host application a download should be done, or that
2746 * the data should be streamed if a streaming viewer is available.
2747 * @param url The full url to the content that should be downloaded
2748 * @param contentDisposition Content-disposition http header, if
2749 * present.
2750 * @param mimetype The mimetype of the content reported by the server
2751 * @param contentLength The file size reported by the server
2752 */
2753 public void onDownloadStart(String url, String userAgent,
2754 String contentDisposition, String mimetype, long contentLength) {
2755 // if we're dealing wih A/V content that's not explicitly marked
2756 // for download, check if it's streamable.
2757 if (contentDisposition == null
Patrick Scotte1fb9662009-08-31 14:31:52 -04002758 || !contentDisposition.regionMatches(
2759 true, 0, "attachment", 0, 10)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002760 // query the package manager to see if there's a registered handler
2761 // that matches.
2762 Intent intent = new Intent(Intent.ACTION_VIEW);
2763 intent.setDataAndType(Uri.parse(url), mimetype);
Patrick Scotte1fb9662009-08-31 14:31:52 -04002764 ResolveInfo info = getPackageManager().resolveActivity(intent,
2765 PackageManager.MATCH_DEFAULT_ONLY);
2766 if (info != null) {
2767 ComponentName myName = getComponentName();
2768 // If we resolved to ourselves, we don't want to attempt to
2769 // load the url only to try and download it again.
2770 if (!myName.getPackageName().equals(
2771 info.activityInfo.packageName)
2772 || !myName.getClassName().equals(
2773 info.activityInfo.name)) {
2774 // someone (other than us) knows how to handle this mime
2775 // type with this scheme, don't download.
2776 try {
2777 startActivity(intent);
2778 return;
2779 } catch (ActivityNotFoundException ex) {
2780 if (LOGD_ENABLED) {
2781 Log.d(LOGTAG, "activity not found for " + mimetype
2782 + " over " + Uri.parse(url).getScheme(),
2783 ex);
2784 }
2785 // Best behavior is to fall back to a download in this
2786 // case
The Android Open Source Project0c908882009-03-03 19:32:16 -08002787 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002788 }
2789 }
2790 }
2791 onDownloadStartNoStream(url, userAgent, contentDisposition, mimetype, contentLength);
2792 }
2793
Kristian Monsenfa52d172010-03-25 18:29:21 +00002794 // This is to work around the fact that java.net.URI throws Exceptions
2795 // instead of just encoding URL's properly
2796 // Helper method for onDownloadStartNoStream
2797 private static String encodePath(String path) {
2798 char[] chars = path.toCharArray();
2799
2800 boolean needed = false;
2801 for (char c : chars) {
2802 if (c == '[' || c == ']') {
2803 needed = true;
2804 break;
2805 }
2806 }
2807 if (needed == false) {
2808 return path;
2809 }
2810
2811 StringBuilder sb = new StringBuilder("");
2812 for (char c : chars) {
2813 if (c == '[' || c == ']') {
2814 sb.append('%');
2815 sb.append(Integer.toHexString(c));
2816 } else {
2817 sb.append(c);
2818 }
2819 }
2820
2821 return sb.toString();
2822 }
2823
The Android Open Source Project0c908882009-03-03 19:32:16 -08002824 /**
2825 * Notify the host application a download should be done, even if there
2826 * is a streaming viewer available for thise type.
2827 * @param url The full url to the content that should be downloaded
2828 * @param contentDisposition Content-disposition http header, if
2829 * present.
2830 * @param mimetype The mimetype of the content reported by the server
2831 * @param contentLength The file size reported by the server
2832 */
2833 /*package */ void onDownloadStartNoStream(String url, String userAgent,
2834 String contentDisposition, String mimetype, long contentLength) {
2835
2836 String filename = URLUtil.guessFileName(url,
2837 contentDisposition, mimetype);
2838
2839 // Check to see if we have an SDCard
2840 String status = Environment.getExternalStorageState();
2841 if (!status.equals(Environment.MEDIA_MOUNTED)) {
2842 int title;
2843 String msg;
2844
2845 // Check to see if the SDCard is busy, same as the music app
2846 if (status.equals(Environment.MEDIA_SHARED)) {
2847 msg = getString(R.string.download_sdcard_busy_dlg_msg);
2848 title = R.string.download_sdcard_busy_dlg_title;
2849 } else {
2850 msg = getString(R.string.download_no_sdcard_dlg_msg, filename);
2851 title = R.string.download_no_sdcard_dlg_title;
2852 }
2853
2854 new AlertDialog.Builder(this)
2855 .setTitle(title)
2856 .setIcon(android.R.drawable.ic_dialog_alert)
2857 .setMessage(msg)
2858 .setPositiveButton(R.string.ok, null)
2859 .show();
2860 return;
2861 }
2862
Kristian Monsenfa52d172010-03-25 18:29:21 +00002863 // java.net.URI is a lot stricter than KURL so we have to encode some
2864 // extra characters. Fix for b 2538060 and b 1634719
2865 WebAddress webAddress;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002866 try {
Kristian Monsenfa52d172010-03-25 18:29:21 +00002867 webAddress = new WebAddress(url);
2868 webAddress.mPath = encodePath(webAddress.mPath);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002869 } catch (Exception e) {
Kristian Monsenfa52d172010-03-25 18:29:21 +00002870 // This only happens for very bad urls, we want to chatch the
2871 // exception here
2872 Log.e(LOGTAG, "Exception trying to parse url:" + url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002873 return;
2874 }
2875
2876 // XXX: Have to use the old url since the cookies were stored using the
2877 // old percent-encoded url.
2878 String cookies = CookieManager.getInstance().getCookie(url);
2879
2880 ContentValues values = new ContentValues();
Kristian Monsenfa52d172010-03-25 18:29:21 +00002881 values.put(Downloads.Impl.COLUMN_URI, webAddress.toString());
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08002882 values.put(Downloads.Impl.COLUMN_COOKIE_DATA, cookies);
2883 values.put(Downloads.Impl.COLUMN_USER_AGENT, userAgent);
2884 values.put(Downloads.Impl.COLUMN_NOTIFICATION_PACKAGE,
The Android Open Source Project0c908882009-03-03 19:32:16 -08002885 getPackageName());
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08002886 values.put(Downloads.Impl.COLUMN_NOTIFICATION_CLASS,
The Android Open Source Project0c908882009-03-03 19:32:16 -08002887 BrowserDownloadPage.class.getCanonicalName());
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08002888 values.put(Downloads.Impl.COLUMN_VISIBILITY,
2889 Downloads.Impl.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
2890 values.put(Downloads.Impl.COLUMN_MIME_TYPE, mimetype);
2891 values.put(Downloads.Impl.COLUMN_FILE_NAME_HINT, filename);
Kristian Monsenfa52d172010-03-25 18:29:21 +00002892 values.put(Downloads.Impl.COLUMN_DESCRIPTION, webAddress.mHost);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002893 if (contentLength > 0) {
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08002894 values.put(Downloads.Impl.COLUMN_TOTAL_BYTES, contentLength);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002895 }
2896 if (mimetype == null) {
2897 // We must have long pressed on a link or image to download it. We
2898 // are not sure of the mimetype in this case, so do a head request
2899 new FetchUrlMimeType(this).execute(values);
2900 } else {
2901 final Uri contentUri =
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08002902 getContentResolver().insert(Downloads.Impl.CONTENT_URI, values);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002903 }
Leon Scroggins9191a7f2010-03-18 14:44:44 -04002904 Toast.makeText(this, R.string.download_pending, Toast.LENGTH_SHORT)
2905 .show();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002906 }
2907
Grace Kloba22ac16e2009-10-07 18:00:23 -07002908 // -------------------------------------------------------------------------
2909
The Android Open Source Project0c908882009-03-03 19:32:16 -08002910 /**
2911 * Resets the lock icon. This method is called when we start a new load and
2912 * know the url to be loaded.
2913 */
2914 private void resetLockIcon(String url) {
2915 // Save the lock-icon state (we revert to it if the load gets cancelled)
Grace Kloba22ac16e2009-10-07 18:00:23 -07002916 mTabControl.getCurrentTab().resetLockIcon(url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002917 updateLockIconImage(LOCK_ICON_UNSECURE);
2918 }
2919
The Android Open Source Project0c908882009-03-03 19:32:16 -08002920 /**
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04002921 * Update the lock icon to correspond to our latest state.
2922 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07002923 private void updateLockIconToLatest() {
2924 updateLockIconImage(mTabControl.getCurrentTab().getLockIconType());
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04002925 }
2926
2927 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08002928 * Updates the lock-icon image in the title-bar.
2929 */
2930 private void updateLockIconImage(int lockIconType) {
2931 Drawable d = null;
2932 if (lockIconType == LOCK_ICON_SECURE) {
2933 d = mSecLockIcon;
2934 } else if (lockIconType == LOCK_ICON_MIXED) {
2935 d = mMixLockIcon;
2936 }
Leon Scroggins68579392009-09-15 15:31:54 -04002937 mTitleBar.setLock(d);
Leon Scrogginsfe87bd32009-10-06 10:10:00 -04002938 mFakeTitleBar.setLock(d);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002939 }
2940
2941 /**
2942 * Displays a page-info dialog.
2943 * @param tab The tab to show info about
2944 * @param fromShowSSLCertificateOnError The flag that indicates whether
2945 * this dialog was opened from the SSL-certificate-on-error dialog or
2946 * not. This is important, since we need to know whether to return to
2947 * the parent dialog or simply dismiss.
2948 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07002949 private void showPageInfo(final Tab tab,
The Android Open Source Project0c908882009-03-03 19:32:16 -08002950 final boolean fromShowSSLCertificateOnError) {
2951 final LayoutInflater factory = LayoutInflater
2952 .from(this);
2953
2954 final View pageInfoView = factory.inflate(R.layout.page_info, null);
2955
2956 final WebView view = tab.getWebView();
2957
2958 String url = null;
2959 String title = null;
2960
2961 if (view == null) {
2962 url = tab.getUrl();
2963 title = tab.getTitle();
2964 } else if (view == mTabControl.getCurrentWebView()) {
2965 // Use the cached title and url if this is the current WebView
2966 url = mUrl;
2967 title = mTitle;
2968 } else {
2969 url = view.getUrl();
2970 title = view.getTitle();
2971 }
2972
2973 if (url == null) {
2974 url = "";
2975 }
2976 if (title == null) {
2977 title = "";
2978 }
2979
2980 ((TextView) pageInfoView.findViewById(R.id.address)).setText(url);
2981 ((TextView) pageInfoView.findViewById(R.id.title)).setText(title);
2982
2983 mPageInfoView = tab;
Leon Scrogginsc7b92f82010-01-11 18:17:31 -05002984 mPageInfoFromShowSSLCertificateOnError = fromShowSSLCertificateOnError;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002985
2986 AlertDialog.Builder alertDialogBuilder =
2987 new AlertDialog.Builder(this)
2988 .setTitle(R.string.page_info).setIcon(android.R.drawable.ic_dialog_info)
2989 .setView(pageInfoView)
2990 .setPositiveButton(
2991 R.string.ok,
2992 new DialogInterface.OnClickListener() {
2993 public void onClick(DialogInterface dialog,
2994 int whichButton) {
2995 mPageInfoDialog = null;
2996 mPageInfoView = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002997
2998 // if we came here from the SSL error dialog
2999 if (fromShowSSLCertificateOnError) {
3000 // go back to the SSL error dialog
3001 showSSLCertificateOnError(
3002 mSSLCertificateOnErrorView,
3003 mSSLCertificateOnErrorHandler,
3004 mSSLCertificateOnErrorError);
3005 }
3006 }
3007 })
3008 .setOnCancelListener(
3009 new DialogInterface.OnCancelListener() {
3010 public void onCancel(DialogInterface dialog) {
3011 mPageInfoDialog = null;
3012 mPageInfoView = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003013
3014 // if we came here from the SSL error dialog
3015 if (fromShowSSLCertificateOnError) {
3016 // go back to the SSL error dialog
3017 showSSLCertificateOnError(
3018 mSSLCertificateOnErrorView,
3019 mSSLCertificateOnErrorHandler,
3020 mSSLCertificateOnErrorError);
3021 }
3022 }
3023 });
3024
3025 // if we have a main top-level page SSL certificate set or a certificate
3026 // error
3027 if (fromShowSSLCertificateOnError ||
3028 (view != null && view.getCertificate() != null)) {
3029 // add a 'View Certificate' button
3030 alertDialogBuilder.setNeutralButton(
3031 R.string.view_certificate,
3032 new DialogInterface.OnClickListener() {
3033 public void onClick(DialogInterface dialog,
3034 int whichButton) {
3035 mPageInfoDialog = null;
3036 mPageInfoView = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003037
3038 // if we came here from the SSL error dialog
3039 if (fromShowSSLCertificateOnError) {
3040 // go back to the SSL error dialog
3041 showSSLCertificateOnError(
3042 mSSLCertificateOnErrorView,
3043 mSSLCertificateOnErrorHandler,
3044 mSSLCertificateOnErrorError);
3045 } else {
3046 // otherwise, display the top-most certificate from
3047 // the chain
3048 if (view.getCertificate() != null) {
3049 showSSLCertificate(tab);
3050 }
3051 }
3052 }
3053 });
3054 }
3055
3056 mPageInfoDialog = alertDialogBuilder.show();
3057 }
3058
3059 /**
3060 * Displays the main top-level page SSL certificate dialog
3061 * (accessible from the Page-Info dialog).
3062 * @param tab The tab to show certificate for.
3063 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003064 private void showSSLCertificate(final Tab tab) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003065 final View certificateView =
3066 inflateCertificateView(tab.getWebView().getCertificate());
3067 if (certificateView == null) {
3068 return;
3069 }
3070
3071 LayoutInflater factory = LayoutInflater.from(this);
3072
3073 final LinearLayout placeholder =
3074 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3075
3076 LinearLayout ll = (LinearLayout) factory.inflate(
3077 R.layout.ssl_success, placeholder);
3078 ((TextView)ll.findViewById(R.id.success))
3079 .setText(R.string.ssl_certificate_is_valid);
3080
3081 mSSLCertificateView = tab;
3082 mSSLCertificateDialog =
3083 new AlertDialog.Builder(this)
3084 .setTitle(R.string.ssl_certificate).setIcon(
3085 R.drawable.ic_dialog_browser_certificate_secure)
3086 .setView(certificateView)
3087 .setPositiveButton(R.string.ok,
3088 new DialogInterface.OnClickListener() {
3089 public void onClick(DialogInterface dialog,
3090 int whichButton) {
3091 mSSLCertificateDialog = null;
3092 mSSLCertificateView = null;
3093
3094 showPageInfo(tab, false);
3095 }
3096 })
3097 .setOnCancelListener(
3098 new DialogInterface.OnCancelListener() {
3099 public void onCancel(DialogInterface dialog) {
3100 mSSLCertificateDialog = null;
3101 mSSLCertificateView = null;
3102
3103 showPageInfo(tab, false);
3104 }
3105 })
3106 .show();
3107 }
3108
3109 /**
3110 * Displays the SSL error certificate dialog.
3111 * @param view The target web-view.
3112 * @param handler The SSL error handler responsible for cancelling the
3113 * connection that resulted in an SSL error or proceeding per user request.
3114 * @param error The SSL error object.
3115 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003116 void showSSLCertificateOnError(
The Android Open Source Project0c908882009-03-03 19:32:16 -08003117 final WebView view, final SslErrorHandler handler, final SslError error) {
3118
3119 final View certificateView =
3120 inflateCertificateView(error.getCertificate());
3121 if (certificateView == null) {
3122 return;
3123 }
3124
3125 LayoutInflater factory = LayoutInflater.from(this);
3126
3127 final LinearLayout placeholder =
3128 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3129
3130 if (error.hasError(SslError.SSL_UNTRUSTED)) {
3131 LinearLayout ll = (LinearLayout)factory
3132 .inflate(R.layout.ssl_warning, placeholder);
3133 ((TextView)ll.findViewById(R.id.warning))
3134 .setText(R.string.ssl_untrusted);
3135 }
3136
3137 if (error.hasError(SslError.SSL_IDMISMATCH)) {
3138 LinearLayout ll = (LinearLayout)factory
3139 .inflate(R.layout.ssl_warning, placeholder);
3140 ((TextView)ll.findViewById(R.id.warning))
3141 .setText(R.string.ssl_mismatch);
3142 }
3143
3144 if (error.hasError(SslError.SSL_EXPIRED)) {
3145 LinearLayout ll = (LinearLayout)factory
3146 .inflate(R.layout.ssl_warning, placeholder);
3147 ((TextView)ll.findViewById(R.id.warning))
3148 .setText(R.string.ssl_expired);
3149 }
3150
3151 if (error.hasError(SslError.SSL_NOTYETVALID)) {
3152 LinearLayout ll = (LinearLayout)factory
3153 .inflate(R.layout.ssl_warning, placeholder);
3154 ((TextView)ll.findViewById(R.id.warning))
3155 .setText(R.string.ssl_not_yet_valid);
3156 }
3157
3158 mSSLCertificateOnErrorHandler = handler;
3159 mSSLCertificateOnErrorView = view;
3160 mSSLCertificateOnErrorError = error;
3161 mSSLCertificateOnErrorDialog =
3162 new AlertDialog.Builder(this)
3163 .setTitle(R.string.ssl_certificate).setIcon(
3164 R.drawable.ic_dialog_browser_certificate_partially_secure)
3165 .setView(certificateView)
3166 .setPositiveButton(R.string.ok,
3167 new DialogInterface.OnClickListener() {
3168 public void onClick(DialogInterface dialog,
3169 int whichButton) {
3170 mSSLCertificateOnErrorDialog = null;
3171 mSSLCertificateOnErrorView = null;
3172 mSSLCertificateOnErrorHandler = null;
3173 mSSLCertificateOnErrorError = null;
3174
Grace Kloba22ac16e2009-10-07 18:00:23 -07003175 view.getWebViewClient().onReceivedSslError(
3176 view, handler, error);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003177 }
3178 })
3179 .setNeutralButton(R.string.page_info_view,
3180 new DialogInterface.OnClickListener() {
3181 public void onClick(DialogInterface dialog,
3182 int whichButton) {
3183 mSSLCertificateOnErrorDialog = null;
3184
3185 // do not clear the dialog state: we will
3186 // need to show the dialog again once the
3187 // user is done exploring the page-info details
3188
3189 showPageInfo(mTabControl.getTabFromView(view),
3190 true);
3191 }
3192 })
3193 .setOnCancelListener(
3194 new DialogInterface.OnCancelListener() {
3195 public void onCancel(DialogInterface dialog) {
3196 mSSLCertificateOnErrorDialog = null;
3197 mSSLCertificateOnErrorView = null;
3198 mSSLCertificateOnErrorHandler = null;
3199 mSSLCertificateOnErrorError = null;
3200
Grace Kloba22ac16e2009-10-07 18:00:23 -07003201 view.getWebViewClient().onReceivedSslError(
3202 view, handler, error);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003203 }
3204 })
3205 .show();
3206 }
3207
3208 /**
3209 * Inflates the SSL certificate view (helper method).
3210 * @param certificate The SSL certificate.
3211 * @return The resultant certificate view with issued-to, issued-by,
3212 * issued-on, expires-on, and possibly other fields set.
3213 * If the input certificate is null, returns null.
3214 */
3215 private View inflateCertificateView(SslCertificate certificate) {
3216 if (certificate == null) {
3217 return null;
3218 }
3219
3220 LayoutInflater factory = LayoutInflater.from(this);
3221
3222 View certificateView = factory.inflate(
3223 R.layout.ssl_certificate, null);
3224
3225 // issued to:
3226 SslCertificate.DName issuedTo = certificate.getIssuedTo();
3227 if (issuedTo != null) {
3228 ((TextView) certificateView.findViewById(R.id.to_common))
3229 .setText(issuedTo.getCName());
3230 ((TextView) certificateView.findViewById(R.id.to_org))
3231 .setText(issuedTo.getOName());
3232 ((TextView) certificateView.findViewById(R.id.to_org_unit))
3233 .setText(issuedTo.getUName());
3234 }
3235
3236 // issued by:
3237 SslCertificate.DName issuedBy = certificate.getIssuedBy();
3238 if (issuedBy != null) {
3239 ((TextView) certificateView.findViewById(R.id.by_common))
3240 .setText(issuedBy.getCName());
3241 ((TextView) certificateView.findViewById(R.id.by_org))
3242 .setText(issuedBy.getOName());
3243 ((TextView) certificateView.findViewById(R.id.by_org_unit))
3244 .setText(issuedBy.getUName());
3245 }
3246
3247 // issued on:
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003248 String issuedOn = formatCertificateDate(
3249 certificate.getValidNotBeforeDate());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003250 ((TextView) certificateView.findViewById(R.id.issued_on))
3251 .setText(issuedOn);
3252
3253 // expires on:
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003254 String expiresOn = formatCertificateDate(
3255 certificate.getValidNotAfterDate());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003256 ((TextView) certificateView.findViewById(R.id.expires_on))
3257 .setText(expiresOn);
3258
3259 return certificateView;
3260 }
3261
3262 /**
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003263 * Formats the certificate date to a properly localized date string.
The Android Open Source Project0c908882009-03-03 19:32:16 -08003264 * @return Properly localized version of the certificate date string and
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003265 * the "" if it fails to localize.
The Android Open Source Project0c908882009-03-03 19:32:16 -08003266 */
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003267 private String formatCertificateDate(Date certificateDate) {
3268 if (certificateDate == null) {
3269 return "";
The Android Open Source Project0c908882009-03-03 19:32:16 -08003270 }
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003271 String formattedDate = DateFormat.getDateFormat(this).format(certificateDate);
3272 if (formattedDate == null) {
3273 return "";
3274 }
3275 return formattedDate;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003276 }
3277
3278 /**
3279 * Displays an http-authentication dialog.
3280 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003281 void showHttpAuthentication(final HttpAuthHandler handler,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003282 final String host, final String realm, final String title,
3283 final String name, final String password, int focusId) {
3284 LayoutInflater factory = LayoutInflater.from(this);
3285 final View v = factory
3286 .inflate(R.layout.http_authentication, null);
3287 if (name != null) {
3288 ((EditText) v.findViewById(R.id.username_edit)).setText(name);
3289 }
3290 if (password != null) {
3291 ((EditText) v.findViewById(R.id.password_edit)).setText(password);
3292 }
3293
3294 String titleText = title;
3295 if (titleText == null) {
3296 titleText = getText(R.string.sign_in_to).toString().replace(
3297 "%s1", host).replace("%s2", realm);
3298 }
3299
3300 mHttpAuthHandler = handler;
3301 AlertDialog dialog = new AlertDialog.Builder(this)
3302 .setTitle(titleText)
3303 .setIcon(android.R.drawable.ic_dialog_alert)
3304 .setView(v)
3305 .setPositiveButton(R.string.action,
3306 new DialogInterface.OnClickListener() {
3307 public void onClick(DialogInterface dialog,
3308 int whichButton) {
3309 String nm = ((EditText) v
3310 .findViewById(R.id.username_edit))
3311 .getText().toString();
3312 String pw = ((EditText) v
3313 .findViewById(R.id.password_edit))
3314 .getText().toString();
3315 BrowserActivity.this.setHttpAuthUsernamePassword
3316 (host, realm, nm, pw);
3317 handler.proceed(nm, pw);
3318 mHttpAuthenticationDialog = null;
3319 mHttpAuthHandler = null;
3320 }})
3321 .setNegativeButton(R.string.cancel,
3322 new DialogInterface.OnClickListener() {
3323 public void onClick(DialogInterface dialog,
3324 int whichButton) {
3325 handler.cancel();
3326 BrowserActivity.this.resetTitleAndRevertLockIcon();
3327 mHttpAuthenticationDialog = null;
3328 mHttpAuthHandler = null;
3329 }})
3330 .setOnCancelListener(new DialogInterface.OnCancelListener() {
3331 public void onCancel(DialogInterface dialog) {
3332 handler.cancel();
3333 BrowserActivity.this.resetTitleAndRevertLockIcon();
3334 mHttpAuthenticationDialog = null;
3335 mHttpAuthHandler = null;
3336 }})
3337 .create();
3338 // Make the IME appear when the dialog is displayed if applicable.
3339 dialog.getWindow().setSoftInputMode(
3340 WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
3341 dialog.show();
3342 if (focusId != 0) {
3343 dialog.findViewById(focusId).requestFocus();
3344 } else {
3345 v.findViewById(R.id.username_edit).requestFocus();
3346 }
3347 mHttpAuthenticationDialog = dialog;
3348 }
3349
3350 public int getProgress() {
3351 WebView w = mTabControl.getCurrentWebView();
3352 if (w != null) {
3353 return w.getProgress();
3354 } else {
3355 return 100;
3356 }
3357 }
3358
3359 /**
3360 * Set HTTP authentication password.
3361 *
3362 * @param host The host for the password
3363 * @param realm The realm for the password
3364 * @param username The username for the password. If it is null, it means
3365 * password can't be saved.
3366 * @param password The password
3367 */
3368 public void setHttpAuthUsernamePassword(String host, String realm,
3369 String username,
3370 String password) {
Steve Block95a53b22010-03-25 17:24:58 +00003371 WebView w = getTopWindow();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003372 if (w != null) {
3373 w.setHttpAuthUsernamePassword(host, realm, username, password);
3374 }
3375 }
3376
3377 /**
3378 * connectivity manager says net has come or gone... inform the user
3379 * @param up true if net has come up, false if net has gone down
3380 */
3381 public void onNetworkToggle(boolean up) {
3382 if (up == mIsNetworkUp) {
3383 return;
3384 } else if (up) {
3385 mIsNetworkUp = true;
3386 if (mAlertDialog != null) {
3387 mAlertDialog.cancel();
3388 mAlertDialog = null;
3389 }
3390 } else {
3391 mIsNetworkUp = false;
Patrick Scotteb6ab2a2009-09-16 10:00:17 -04003392 if (mInLoad) {
3393 createAndShowNetworkDialog();
3394 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003395 }
3396 WebView w = mTabControl.getCurrentWebView();
3397 if (w != null) {
3398 w.setNetworkAvailable(up);
3399 }
3400 }
3401
Grace Kloba22ac16e2009-10-07 18:00:23 -07003402 boolean isNetworkUp() {
3403 return mIsNetworkUp;
3404 }
3405
Patrick Scotteb6ab2a2009-09-16 10:00:17 -04003406 // This method shows the network dialog alerting the user that the net is
3407 // down. It will only show the dialog if mAlertDialog is null.
3408 private void createAndShowNetworkDialog() {
3409 if (mAlertDialog == null) {
3410 mAlertDialog = new AlertDialog.Builder(this)
3411 .setTitle(R.string.loadSuspendedTitle)
3412 .setMessage(R.string.loadSuspended)
3413 .setPositiveButton(R.string.ok, null)
3414 .show();
3415 }
3416 }
3417
The Android Open Source Project0c908882009-03-03 19:32:16 -08003418 @Override
3419 protected void onActivityResult(int requestCode, int resultCode,
3420 Intent intent) {
Grace Klobabb394f32009-11-19 10:26:37 -08003421 if (getTopWindow() == null) return;
3422
The Android Open Source Project0c908882009-03-03 19:32:16 -08003423 switch (requestCode) {
3424 case COMBO_PAGE:
3425 if (resultCode == RESULT_OK && intent != null) {
3426 String data = intent.getAction();
3427 Bundle extras = intent.getExtras();
3428 if (extras != null && extras.getBoolean("new_window", false)) {
Leon Scroggins25d35472009-09-15 11:37:27 -04003429 openTab(data);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003430 } else {
Grace Kloba22ac16e2009-10-07 18:00:23 -07003431 final Tab currentTab =
The Android Open Source Project0c908882009-03-03 19:32:16 -08003432 mTabControl.getCurrentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04003433 dismissSubWindow(currentTab);
3434 if (data != null && data.length() != 0) {
Leon Scroggins92472e82010-02-17 16:32:28 -05003435 loadUrl(getTopWindow(), data);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003436 }
3437 }
3438 }
Leon Scrogginsfde97462010-01-11 13:06:21 -05003439 // Deliberately fall through to PREFERENCES_PAGE, since the
3440 // same extra may be attached to the COMBO_PAGE
3441 case PREFERENCES_PAGE:
3442 if (resultCode == RESULT_OK && intent != null) {
3443 String action = intent.getStringExtra(Intent.EXTRA_TEXT);
3444 if (BrowserSettings.PREF_CLEAR_HISTORY.equals(action)) {
3445 mTabControl.removeParentChildRelationShips();
3446 }
3447 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003448 break;
Leon Scroggins8d5fa432009-10-02 15:55:59 -04003449 // Choose a file from the file picker.
3450 case FILE_SELECTED:
3451 if (null == mUploadMessage) break;
3452 Uri result = intent == null || resultCode != RESULT_OK ? null
3453 : intent.getData();
3454 mUploadMessage.onReceiveValue(result);
3455 mUploadMessage = null;
3456 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003457 default:
3458 break;
3459 }
Leon Scroggins30444232009-09-04 18:36:20 -04003460 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003461 }
3462
3463 /*
3464 * This method is called as a result of the user selecting the options
Leon Scrogginsf08809b2010-01-21 09:27:46 -05003465 * menu to see the download window. It shows the download window on top of
3466 * the current window.
The Android Open Source Project0c908882009-03-03 19:32:16 -08003467 */
Leon Scrogginsf08809b2010-01-21 09:27:46 -05003468 private void viewDownloads(Uri downloadRecord) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003469 Intent intent = new Intent(this,
3470 BrowserDownloadPage.class);
3471 intent.setData(downloadRecord);
Grace Kloba22ac16e2009-10-07 18:00:23 -07003472 startActivityForResult(intent, BrowserActivity.DOWNLOAD_PAGE);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003473
3474 }
3475
Leon Scroggins160a7e72009-08-14 18:28:01 -04003476 /**
3477 * Open the Go page.
3478 * @param startWithHistory If true, open starting on the history tab.
3479 * Otherwise, start with the bookmarks tab.
Leon Scroggins160a7e72009-08-14 18:28:01 -04003480 */
Leon Scroggins30444232009-09-04 18:36:20 -04003481 /* package */ void bookmarksOrHistoryPicker(boolean startWithHistory) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003482 WebView current = mTabControl.getCurrentWebView();
3483 if (current == null) {
3484 return;
3485 }
3486 Intent intent = new Intent(this,
3487 CombinedBookmarkHistoryActivity.class);
3488 String title = current.getTitle();
3489 String url = current.getUrl();
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01003490 Bitmap thumbnail = createScreenshot(current);
3491
The Android Open Source Project0c908882009-03-03 19:32:16 -08003492 // Just in case the user opens bookmarks before a page finishes loading
3493 // so the current history item, and therefore the page, is null.
3494 if (null == url) {
3495 url = mLastEnteredUrl;
3496 // This can happen.
3497 if (null == url) {
3498 url = mSettings.getHomePage();
3499 }
3500 }
3501 // In case the web page has not yet received its associated title.
3502 if (title == null) {
3503 title = url;
3504 }
3505 intent.putExtra("title", title);
3506 intent.putExtra("url", url);
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01003507 intent.putExtra("thumbnail", thumbnail);
Leon Scroggins30444232009-09-04 18:36:20 -04003508 // Disable opening in a new window if we have maxed out the windows
Grace Kloba22ac16e2009-10-07 18:00:23 -07003509 intent.putExtra("disable_new_window", !mTabControl.canCreateNewTab());
Patrick Scott3918d442009-08-04 13:22:29 -04003510 intent.putExtra("touch_icon_url", current.getTouchIconUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003511 if (startWithHistory) {
3512 intent.putExtra(CombinedBookmarkHistoryActivity.STARTING_TAB,
3513 CombinedBookmarkHistoryActivity.HISTORY_TAB);
3514 }
3515 startActivityForResult(intent, COMBO_PAGE);
3516 }
3517
3518 // Called when loading from context menu or LOAD_URL message
Leon Scroggins92472e82010-02-17 16:32:28 -05003519 private void loadUrlFromContext(WebView view, String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003520 // In case the user enters nothing.
3521 if (url != null && url.length() != 0 && view != null) {
3522 url = smartUrlFilter(url);
Grace Kloba22ac16e2009-10-07 18:00:23 -07003523 if (!view.getWebViewClient().shouldOverrideUrlLoading(view, url)) {
Leon Scroggins92472e82010-02-17 16:32:28 -05003524 loadUrl(view, url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003525 }
3526 }
3527 }
3528
Leon Scroggins92472e82010-02-17 16:32:28 -05003529 /**
3530 * Load the URL into the given WebView and update the title bar
3531 * to reflect the new load. Call this instead of WebView.loadUrl
3532 * directly.
3533 * @param view The WebView used to load url.
3534 * @param url The URL to load.
3535 */
3536 private void loadUrl(WebView view, String url) {
3537 updateTitleBarForNewLoad(view, url);
3538 view.loadUrl(url);
3539 }
3540
3541 /**
3542 * Load UrlData into a Tab and update the title bar to reflect the new
3543 * load. Call this instead of UrlData.loadIn directly.
3544 * @param t The Tab used to load.
3545 * @param data The UrlData being loaded.
3546 */
3547 private void loadUrlDataIn(Tab t, UrlData data) {
3548 updateTitleBarForNewLoad(t.getWebView(), data.mUrl);
3549 data.loadIn(t);
3550 }
3551
3552 /**
3553 * If the WebView is the top window, update the title bar to reflect
3554 * loading the new URL. i.e. set its text, clear the favicon (which
3555 * will be set once the page begins loading), and set the progress to
3556 * INITIAL_PROGRESS to show that the page has begun to load. Called
3557 * by loadUrl and loadUrlDataIn.
3558 * @param view The WebView that is starting a load.
3559 * @param url The URL that is being loaded.
3560 */
3561 private void updateTitleBarForNewLoad(WebView view, String url) {
3562 if (view == getTopWindow()) {
3563 setUrlTitle(url, null);
3564 setFavicon(null);
3565 onProgressChanged(view, INITIAL_PROGRESS);
3566 }
3567 }
3568
The Android Open Source Project0c908882009-03-03 19:32:16 -08003569 private String smartUrlFilter(Uri inUri) {
3570 if (inUri != null) {
3571 return smartUrlFilter(inUri.toString());
3572 }
3573 return null;
3574 }
3575
Feng Qianb34f87a2009-03-24 21:27:26 -07003576 protected static final Pattern ACCEPTED_URI_SCHEMA = Pattern.compile(
The Android Open Source Project0c908882009-03-03 19:32:16 -08003577 "(?i)" + // switch on case insensitive matching
3578 "(" + // begin group for schema
3579 "(?:http|https|file):\\/\\/" +
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003580 "|(?:inline|data|about|content|javascript):" +
The Android Open Source Project0c908882009-03-03 19:32:16 -08003581 ")" +
3582 "(.*)" );
3583
3584 /**
3585 * Attempts to determine whether user input is a URL or search
3586 * terms. Anything with a space is passed to search.
3587 *
3588 * Converts to lowercase any mistakenly uppercased schema (i.e.,
3589 * "Http://" converts to "http://"
3590 *
3591 * @return Original or modified URL
3592 *
3593 */
3594 String smartUrlFilter(String url) {
3595
3596 String inUrl = url.trim();
3597 boolean hasSpace = inUrl.indexOf(' ') != -1;
3598
3599 Matcher matcher = ACCEPTED_URI_SCHEMA.matcher(inUrl);
3600 if (matcher.matches()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003601 // force scheme to lowercase
3602 String scheme = matcher.group(1);
3603 String lcScheme = scheme.toLowerCase();
3604 if (!lcScheme.equals(scheme)) {
Mitsuru Oshima123ecfb2009-05-18 19:11:14 -07003605 inUrl = lcScheme + matcher.group(2);
3606 }
3607 if (hasSpace) {
3608 inUrl = inUrl.replace(" ", "%20");
The Android Open Source Project0c908882009-03-03 19:32:16 -08003609 }
3610 return inUrl;
3611 }
3612 if (hasSpace) {
Satish Sampath565505b2009-05-29 15:37:27 +01003613 // FIXME: Is this the correct place to add to searches?
3614 // what if someone else calls this function?
3615 int shortcut = parseUrlShortcut(inUrl);
3616 if (shortcut != SHORTCUT_INVALID) {
3617 Browser.addSearchUrl(mResolver, inUrl);
3618 String query = inUrl.substring(2);
3619 switch (shortcut) {
3620 case SHORTCUT_GOOGLE_SEARCH:
Grace Kloba47fdfdb2009-06-30 11:15:34 -07003621 return URLUtil.composeSearchUrl(query, QuickSearch_G, QUERY_PLACE_HOLDER);
Satish Sampath565505b2009-05-29 15:37:27 +01003622 case SHORTCUT_WIKIPEDIA_SEARCH:
3623 return URLUtil.composeSearchUrl(query, QuickSearch_W, QUERY_PLACE_HOLDER);
3624 case SHORTCUT_DICTIONARY_SEARCH:
3625 return URLUtil.composeSearchUrl(query, QuickSearch_D, QUERY_PLACE_HOLDER);
3626 case SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH:
The Android Open Source Project0c908882009-03-03 19:32:16 -08003627 // FIXME: we need location in this case
Satish Sampath565505b2009-05-29 15:37:27 +01003628 return URLUtil.composeSearchUrl(query, QuickSearch_L, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003629 }
3630 }
3631 } else {
Dan Egnor5ee906c2009-11-18 12:11:49 -08003632 if (Patterns.WEB_URL.matcher(inUrl).matches()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003633 return URLUtil.guessUrl(inUrl);
3634 }
3635 }
3636
3637 Browser.addSearchUrl(mResolver, inUrl);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07003638 return URLUtil.composeSearchUrl(inUrl, QuickSearch_G, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003639 }
3640
Ben Murdochbff2d602009-07-01 20:19:05 +01003641 /* package */ void setShouldShowErrorConsole(boolean flag) {
3642 if (flag == mShouldShowErrorConsole) {
3643 // Nothing to do.
3644 return;
3645 }
3646
3647 mShouldShowErrorConsole = flag;
3648
Grace Kloba22ac16e2009-10-07 18:00:23 -07003649 ErrorConsoleView errorConsole = mTabControl.getCurrentTab()
3650 .getErrorConsole(true);
Ben Murdochbff2d602009-07-01 20:19:05 +01003651
3652 if (flag) {
3653 // Setting the show state of the console will cause it's the layout to be inflated.
3654 if (errorConsole.numberOfErrors() > 0) {
3655 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
3656 } else {
3657 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
3658 }
3659
3660 // Now we can add it to the main view.
3661 mErrorConsoleContainer.addView(errorConsole,
Romain Guy15b8ec62010-01-08 15:06:43 -08003662 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
Ben Murdochbff2d602009-07-01 20:19:05 +01003663 ViewGroup.LayoutParams.WRAP_CONTENT));
3664 } else {
3665 mErrorConsoleContainer.removeView(errorConsole);
3666 }
3667
3668 }
3669
Grace Kloba22ac16e2009-10-07 18:00:23 -07003670 boolean shouldShowErrorConsole() {
3671 return mShouldShowErrorConsole;
3672 }
3673
Andrei Popescu163ab742009-10-20 17:58:23 +01003674 private void setStatusBarVisibility(boolean visible) {
3675 int flag = visible ? 0 : WindowManager.LayoutParams.FLAG_FULLSCREEN;
3676 getWindow().setFlags(flag, WindowManager.LayoutParams.FLAG_FULLSCREEN);
3677 }
3678
Andrei Popescu56199cc2010-01-12 22:39:16 +00003679
3680 private void sendNetworkType(String type, String subtype) {
3681 WebView w = mTabControl.getCurrentWebView();
3682 if (w != null) {
3683 w.setNetworkType(type, subtype);
3684 }
3685 }
3686
Andrei Popescu30995e72010-02-09 16:59:58 +00003687 private void packageChanged(String packageName, boolean wasAdded) {
3688 WebView w = mTabControl.getCurrentWebView();
3689 if (w == null) {
3690 return;
3691 }
3692
3693 if (wasAdded) {
3694 w.addPackageName(packageName);
3695 } else {
3696 w.removePackageName(packageName);
3697 }
3698 }
3699
3700 private void addPackageNames(Set<String> packageNames) {
3701 WebView w = mTabControl.getCurrentWebView();
3702 if (w == null) {
3703 return;
3704 }
3705
3706 w.addPackageNames(packageNames);
3707 }
3708
3709 private void getInstalledPackages() {
3710 AsyncTask<Void, Void, Set<String> > task =
3711 new AsyncTask<Void, Void, Set<String> >() {
3712 protected Set<String> doInBackground(Void... unused) {
3713 Set<String> installedPackages = new HashSet<String>();
3714 PackageManager pm = BrowserActivity.this.getPackageManager();
3715 if (pm != null) {
3716 List<PackageInfo> packages = pm.getInstalledPackages(0);
3717 for (PackageInfo p : packages) {
3718 if (BrowserActivity.this.sGoogleApps.contains(p.packageName)) {
3719 installedPackages.add(p.packageName);
3720 }
3721 }
3722 }
3723
3724 return installedPackages;
3725 }
3726
3727 // Executes on the UI thread
3728 protected void onPostExecute(Set<String> installedPackages) {
3729 addPackageNames(installedPackages);
3730 }
3731 };
3732 task.execute();
3733 }
3734
Grace Klobaeb6eef42009-09-15 17:56:32 -07003735 final static int LOCK_ICON_UNSECURE = 0;
3736 final static int LOCK_ICON_SECURE = 1;
3737 final static int LOCK_ICON_MIXED = 2;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003738
The Android Open Source Project0c908882009-03-03 19:32:16 -08003739 private BrowserSettings mSettings;
3740 private TabControl mTabControl;
3741 private ContentResolver mResolver;
3742 private FrameLayout mContentView;
Andrei Popescuadc008d2009-06-26 14:11:30 +01003743 private View mCustomView;
3744 private FrameLayout mCustomViewContainer;
Andrei Popescuc9b55562009-07-07 10:51:15 +01003745 private WebChromeClient.CustomViewCallback mCustomViewCallback;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003746
3747 // FIXME, temp address onPrepareMenu performance problem. When we move everything out of
3748 // view, we should rewrite this.
3749 private int mCurrentMenuState = 0;
3750 private int mMenuState = R.id.MAIN_MENU;
Andrei Popescuadc008d2009-06-26 14:11:30 +01003751 private int mOldMenuState = EMPTY_MENU;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003752 private static final int EMPTY_MENU = -1;
3753 private Menu mMenu;
3754
3755 private FindDialog mFindDialog;
3756 // Used to prevent chording to result in firing two shortcuts immediately
3757 // one after another. Fixes bug 1211714.
3758 boolean mCanChord;
3759
3760 private boolean mInLoad;
3761 private boolean mIsNetworkUp;
Ben Murdochb7cc8b42009-09-28 10:59:09 +01003762 private boolean mDidStopLoad;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003763
Cary Clark1f10cbf2010-03-22 11:45:23 -04003764 /* package */ boolean mActivityInPause = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003765
3766 private boolean mMenuIsDown;
3767
The Android Open Source Project0c908882009-03-03 19:32:16 -08003768 private static boolean mInTrace;
3769
3770 // Performance probe
3771 private static final int[] SYSTEM_CPU_FORMAT = new int[] {
3772 Process.PROC_SPACE_TERM | Process.PROC_COMBINE,
3773 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 1: user time
3774 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 2: nice time
3775 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 3: sys time
3776 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 4: idle time
3777 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 5: iowait time
3778 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 6: irq time
3779 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG // 7: softirq time
3780 };
3781
3782 private long mStart;
3783 private long mProcessStart;
3784 private long mUserStart;
3785 private long mSystemStart;
3786 private long mIdleStart;
3787 private long mIrqStart;
3788
3789 private long mUiStart;
3790
3791 private Drawable mMixLockIcon;
3792 private Drawable mSecLockIcon;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003793
3794 /* hold a ref so we can auto-cancel if necessary */
3795 private AlertDialog mAlertDialog;
3796
The Android Open Source Project0c908882009-03-03 19:32:16 -08003797 // The up-to-date URL and title (these can be different from those stored
3798 // in WebView, since it takes some time for the information in WebView to
3799 // get updated)
3800 private String mUrl;
3801 private String mTitle;
3802
3803 // As PageInfo has different style for landscape / portrait, we have
3804 // to re-open it when configuration changed
3805 private AlertDialog mPageInfoDialog;
Grace Kloba22ac16e2009-10-07 18:00:23 -07003806 private Tab mPageInfoView;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003807 // If the Page-Info dialog is launched from the SSL-certificate-on-error
3808 // dialog, we should not just dismiss it, but should get back to the
3809 // SSL-certificate-on-error dialog. This flag is used to store this state
Leon Scrogginsc7b92f82010-01-11 18:17:31 -05003810 private boolean mPageInfoFromShowSSLCertificateOnError;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003811
3812 // as SSLCertificateOnError has different style for landscape / portrait,
3813 // we have to re-open it when configuration changed
3814 private AlertDialog mSSLCertificateOnErrorDialog;
3815 private WebView mSSLCertificateOnErrorView;
3816 private SslErrorHandler mSSLCertificateOnErrorHandler;
3817 private SslError mSSLCertificateOnErrorError;
3818
3819 // as SSLCertificate has different style for landscape / portrait, we
3820 // have to re-open it when configuration changed
3821 private AlertDialog mSSLCertificateDialog;
Grace Kloba22ac16e2009-10-07 18:00:23 -07003822 private Tab mSSLCertificateView;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003823
3824 // as HttpAuthentication has different style for landscape / portrait, we
3825 // have to re-open it when configuration changed
3826 private AlertDialog mHttpAuthenticationDialog;
3827 private HttpAuthHandler mHttpAuthHandler;
3828
3829 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_PARAMS =
3830 new FrameLayout.LayoutParams(
Romain Guy15b8ec62010-01-08 15:06:43 -08003831 ViewGroup.LayoutParams.MATCH_PARENT,
3832 ViewGroup.LayoutParams.MATCH_PARENT);
Andrei Popescuadc008d2009-06-26 14:11:30 +01003833 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_GRAVITY_CENTER =
3834 new FrameLayout.LayoutParams(
Romain Guy15b8ec62010-01-08 15:06:43 -08003835 ViewGroup.LayoutParams.MATCH_PARENT,
3836 ViewGroup.LayoutParams.MATCH_PARENT,
Andrei Popescuadc008d2009-06-26 14:11:30 +01003837 Gravity.CENTER);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07003838 // Google search
3839 final static String QuickSearch_G = "http://www.google.com/m?q=%s";
The Android Open Source Project0c908882009-03-03 19:32:16 -08003840 // Wikipedia search
3841 final static String QuickSearch_W = "http://en.wikipedia.org/w/index.php?search=%s&go=Go";
3842 // Dictionary search
3843 final static String QuickSearch_D = "http://dictionary.reference.com/search?q=%s";
3844 // Google Mobile Local search
3845 final static String QuickSearch_L = "http://www.google.com/m/search?site=local&q=%s&near=mountain+view";
3846
3847 final static String QUERY_PLACE_HOLDER = "%s";
3848
3849 // "source" parameter for Google search through search key
3850 final static String GOOGLE_SEARCH_SOURCE_SEARCHKEY = "browser-key";
3851 // "source" parameter for Google search through goto menu
3852 final static String GOOGLE_SEARCH_SOURCE_GOTO = "browser-goto";
3853 // "source" parameter for Google search through simplily type
3854 final static String GOOGLE_SEARCH_SOURCE_TYPE = "browser-type";
3855 // "source" parameter for Google search suggested by the browser
3856 final static String GOOGLE_SEARCH_SOURCE_SUGGEST = "browser-suggest";
3857 // "source" parameter for Google search from unknown source
3858 final static String GOOGLE_SEARCH_SOURCE_UNKNOWN = "unknown";
3859
3860 private final static String LOGTAG = "browser";
3861
The Android Open Source Project0c908882009-03-03 19:32:16 -08003862 private String mLastEnteredUrl;
3863
3864 private PowerManager.WakeLock mWakeLock;
3865 private final static int WAKELOCK_TIMEOUT = 5 * 60 * 1000; // 5 minutes
3866
3867 private Toast mStopToast;
3868
Leon Scroggins68579392009-09-15 15:31:54 -04003869 private TitleBar mTitleBar;
Leon Scroggins81db3662009-06-04 17:45:11 -04003870
Ben Murdochbff2d602009-07-01 20:19:05 +01003871 private LinearLayout mErrorConsoleContainer = null;
3872 private boolean mShouldShowErrorConsole = false;
3873
The Android Open Source Project0c908882009-03-03 19:32:16 -08003874 // As the ids are dynamically created, we can't guarantee that they will
3875 // be in sequence, so this static array maps ids to a window number.
3876 final static private int[] WINDOW_SHORTCUT_ID_ARRAY =
3877 { R.id.window_one_menu_id, R.id.window_two_menu_id, R.id.window_three_menu_id,
3878 R.id.window_four_menu_id, R.id.window_five_menu_id, R.id.window_six_menu_id,
3879 R.id.window_seven_menu_id, R.id.window_eight_menu_id };
3880
3881 // monitor platform changes
3882 private IntentFilter mNetworkStateChangedFilter;
3883 private BroadcastReceiver mNetworkStateIntentReceiver;
3884
Grace Klobab4da0ad2009-05-14 14:45:40 -07003885 private BroadcastReceiver mPackageInstallationReceiver;
3886
Bjorn Bringerta7611812010-03-24 11:12:02 +00003887 private SystemAllowGeolocationOrigins mSystemAllowGeolocationOrigins;
3888
The Android Open Source Project0c908882009-03-03 19:32:16 -08003889 // activity requestCode
Nicolas Roard78a98e42009-05-11 13:34:17 +01003890 final static int COMBO_PAGE = 1;
3891 final static int DOWNLOAD_PAGE = 2;
3892 final static int PREFERENCES_PAGE = 3;
Leon Scroggins8d5fa432009-10-02 15:55:59 -04003893 final static int FILE_SELECTED = 4;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003894
Andrei Popescu540035d2009-09-18 18:59:20 +01003895 // the default <video> poster
3896 private Bitmap mDefaultVideoPoster;
3897 // the video progress view
3898 private View mVideoProgressView;
3899
Andrei Popescu30995e72010-02-09 16:59:58 +00003900 // The Google packages we monitor for the navigator.isApplicationInstalled()
3901 // API. Add as needed.
3902 private static Set<String> sGoogleApps;
3903 static {
3904 sGoogleApps = new HashSet<String>();
3905 sGoogleApps.add("com.google.android.youtube");
3906 }
3907
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003908 /**
3909 * A UrlData class to abstract how the content will be set to WebView.
3910 * This base class uses loadUrl to show the content.
3911 */
Leon Scroggins6eac63e2010-03-15 18:19:14 -04003912 /* package */ static class UrlData {
Grace Kloba068e48b2010-01-26 18:11:27 -08003913 final String mUrl;
3914 final Map<String, String> mHeaders;
Leon Scroggins58d56c62010-01-28 15:12:40 -05003915 final Intent mVoiceIntent;
Grace Kloba60e095c2009-06-16 11:50:55 -07003916
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003917 UrlData(String url) {
3918 this.mUrl = url;
Grace Kloba068e48b2010-01-26 18:11:27 -08003919 this.mHeaders = null;
Leon Scroggins58d56c62010-01-28 15:12:40 -05003920 this.mVoiceIntent = null;
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003921 }
Grace Kloba60e095c2009-06-16 11:50:55 -07003922
Leon Scroggins58d56c62010-01-28 15:12:40 -05003923 UrlData(String url, Map<String, String> headers, Intent intent) {
Grace Kloba068e48b2010-01-26 18:11:27 -08003924 this.mUrl = url;
3925 this.mHeaders = headers;
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -05003926 if (RecognizerResultsIntent.ACTION_VOICE_SEARCH_RESULTS
3927 .equals(intent.getAction())) {
Leon Scroggins58d56c62010-01-28 15:12:40 -05003928 this.mVoiceIntent = intent;
3929 } else {
3930 this.mVoiceIntent = null;
3931 }
Grace Kloba60e095c2009-06-16 11:50:55 -07003932 }
3933
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003934 boolean isEmpty() {
Leon Scroggins58d56c62010-01-28 15:12:40 -05003935 return mVoiceIntent == null && (mUrl == null || mUrl.length() == 0);
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003936 }
3937
Leon Scroggins92472e82010-02-17 16:32:28 -05003938 /**
3939 * Load this UrlData into the given Tab. Use loadUrlDataIn to update
3940 * the title bar as well.
3941 */
Leon Scroggins58d56c62010-01-28 15:12:40 -05003942 public void loadIn(Tab t) {
3943 if (mVoiceIntent != null) {
3944 t.activateVoiceSearchMode(mVoiceIntent);
3945 } else {
3946 t.getWebView().loadUrl(mUrl, mHeaders);
3947 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003948 }
3949 };
3950
Leon Scroggins1f005d32009-08-10 17:36:42 -04003951 /* package */ static final UrlData EMPTY_URL_DATA = new UrlData(null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003952}