blob: cbf78d6ef7f0ec34b3dc709169bc22ef14746d4c [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();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800368 }
369
Leon Scroggins58d56c62010-01-28 15:12:40 -0500370 /**
371 * Feed the previously stored results strings to the BrowserProvider so that
372 * the SearchDialog will show them instead of the standard searches.
373 * @param result String to show on the editable line of the SearchDialog.
374 */
375 /* package */ void showVoiceSearchResults(String result) {
376 ContentProviderClient client = mResolver.acquireContentProviderClient(
377 Browser.BOOKMARKS_URI);
378 ContentProvider prov = client.getLocalContentProvider();
379 BrowserProvider bp = (BrowserProvider) prov;
380 bp.setQueryResults(mTabControl.getCurrentTab().getVoiceSearchResults());
381 client.release();
382
Leon Scrogginsfbb3f152010-03-09 17:26:56 -0500383 Bundle bundle = createGoogleSearchSourceBundle(
384 GOOGLE_SEARCH_SOURCE_SEARCHKEY);
385 bundle.putBoolean(SearchManager.CONTEXT_IS_VOICE, true);
386 startSearch(result, false, bundle, false);
Leon Scroggins58d56c62010-01-28 15:12:40 -0500387 }
388
The Android Open Source Project0c908882009-03-03 19:32:16 -0800389 @Override
390 protected void onNewIntent(Intent intent) {
Grace Kloba22ac16e2009-10-07 18:00:23 -0700391 Tab current = mTabControl.getCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800392 // When a tab is closed on exit, the current tab index is set to -1.
393 // Reset before proceed as Browser requires the current tab to be set.
394 if (current == null) {
395 // Try to reset the tab in case the index was incorrect.
396 current = mTabControl.getTab(0);
397 if (current == null) {
398 // No tabs at all so just ignore this intent.
399 return;
400 }
401 mTabControl.setCurrentTab(current);
402 attachTabToContentView(current);
403 resetTitleAndIcon(current.getWebView());
404 }
405 final String action = intent.getAction();
406 final int flags = intent.getFlags();
407 if (Intent.ACTION_MAIN.equals(action) ||
408 (flags & Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY) != 0) {
409 // just resume the browser
410 return;
411 }
Leon Scrogginsb8a844d2010-03-18 15:06:15 -0400412 // In case the SearchDialog is open.
413 ((SearchManager) getSystemService(Context.SEARCH_SERVICE))
414 .stopSearch();
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -0500415 boolean activateVoiceSearch = RecognizerResultsIntent
416 .ACTION_VOICE_SEARCH_RESULTS.equals(action);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800417 if (Intent.ACTION_VIEW.equals(action)
418 || Intent.ACTION_SEARCH.equals(action)
419 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
Leon Scroggins58d56c62010-01-28 15:12:40 -0500420 || Intent.ACTION_WEB_SEARCH.equals(action)
421 || activateVoiceSearch) {
Leon Scroggins3b18ce32010-02-08 17:35:59 -0500422 if (current.isInVoiceSearchMode()) {
423 String title = current.getVoiceDisplayTitle();
424 if (title != null && title.equals(intent.getStringExtra(
425 SearchManager.QUERY))) {
426 // The user submitted the same search as the last voice
427 // search, so do nothing.
428 return;
429 }
Leon Scroggins1fe13a52010-02-09 15:31:26 -0500430 if (Intent.ACTION_SEARCH.equals(action)
431 && current.voiceSearchSourceIsGoogle()) {
432 Intent logIntent = new Intent(
433 LoggingEvents.ACTION_LOG_EVENT);
434 logIntent.putExtra(LoggingEvents.EXTRA_EVENT,
435 LoggingEvents.VoiceSearch.QUERY_UPDATED);
436 logIntent.putExtra(
437 LoggingEvents.VoiceSearch.EXTRA_QUERY_UPDATED_VALUE,
438 intent.getDataString());
439 sendBroadcast(logIntent);
440 // Note, onPageStarted will revert the voice title bar
441 // When http://b/issue?id=2379215 is fixed, we should update
442 // the title bar here.
443 }
Leon Scroggins3b18ce32010-02-08 17:35:59 -0500444 }
Satish Sampath565505b2009-05-29 15:37:27 +0100445 // If this was a search request (e.g. search query directly typed into the address bar),
446 // pass it on to the default web search provider.
447 if (handleWebSearchIntent(intent)) {
448 return;
449 }
450
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700451 UrlData urlData = getUrlDataFromIntent(intent);
452 if (urlData.isEmpty()) {
453 urlData = new UrlData(mSettings.getHomePage());
The Android Open Source Project0c908882009-03-03 19:32:16 -0800454 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700455
Grace Klobacc634032009-07-28 15:58:19 -0700456 final String appId = intent
457 .getStringExtra(Browser.EXTRA_APPLICATION_ID);
Leon Scroggins58d56c62010-01-28 15:12:40 -0500458 if ((Intent.ACTION_VIEW.equals(action) || activateVoiceSearch)
Grace Klobacc634032009-07-28 15:58:19 -0700459 && !getPackageName().equals(appId)
460 && (flags & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0) {
Grace Kloba22ac16e2009-10-07 18:00:23 -0700461 Tab appTab = mTabControl.getTabFromId(appId);
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700462 if (appTab != null) {
463 Log.i(LOGTAG, "Reusing tab for " + appId);
464 // Dismiss the subwindow if applicable.
465 dismissSubWindow(appTab);
466 // Since we might kill the WebView, remove it from the
467 // content view first.
468 removeTabFromContentView(appTab);
469 // Recreate the main WebView after destroying the old one.
470 // If the WebView has the same original url and is on that
471 // page, it can be reused.
472 boolean needsLoad =
Leon Scroggins6eac63e2010-03-15 18:19:14 -0400473 mTabControl.recreateWebView(appTab, urlData);
Ben Murdochbff2d602009-07-01 20:19:05 +0100474
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700475 if (current != appTab) {
Leon Scroggins1f005d32009-08-10 17:36:42 -0400476 switchToTab(mTabControl.getTabIndex(appTab));
477 if (needsLoad) {
Patrick Scott9d53da02010-02-19 10:19:01 -0500478 loadUrlDataIn(appTab, urlData);
Leon Scroggins1f005d32009-08-10 17:36:42 -0400479 }
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700480 } else {
Leon Scroggins1f005d32009-08-10 17:36:42 -0400481 // If the tab was the current tab, we have to attach
482 // it to the view system again.
483 attachTabToContentView(appTab);
484 if (needsLoad) {
Patrick Scott9d53da02010-02-19 10:19:01 -0500485 loadUrlDataIn(appTab, urlData);
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700486 }
487 }
488 return;
Patrick Scottcd115892009-07-16 09:42:58 -0400489 } else {
490 // No matching application tab, try to find a regular tab
491 // with a matching url.
492 appTab = mTabControl.findUnusedTabWithUrl(urlData.mUrl);
Leon Scroggins25515f82009-08-19 15:31:58 -0400493 if (appTab != null) {
494 if (current != appTab) {
495 switchToTab(mTabControl.getTabIndex(appTab));
496 }
497 // Otherwise, we are already viewing the correct tab.
Patrick Scottcd115892009-07-16 09:42:58 -0400498 } else {
499 // if FLAG_ACTIVITY_BROUGHT_TO_FRONT flag is on, the url
500 // will be opened in a new tab unless we have reached
501 // MAX_TABS. Then the url will be opened in the current
502 // tab. If a new tab is created, it will have "true" for
503 // exit on close.
Leon Scroggins1f005d32009-08-10 17:36:42 -0400504 openTabAndShow(urlData, true, appId);
Patrick Scottcd115892009-07-16 09:42:58 -0400505 }
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700506 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800507 } else {
Grace Kloba638d3f42009-11-23 10:35:04 -0800508 if (!urlData.isEmpty()
509 && urlData.mUrl.startsWith("about:debug")) {
510 if ("about:debug.dom".equals(urlData.mUrl)) {
511 current.getWebView().dumpDomTree(false);
512 } else if ("about:debug.dom.file".equals(urlData.mUrl)) {
513 current.getWebView().dumpDomTree(true);
514 } else if ("about:debug.render".equals(urlData.mUrl)) {
515 current.getWebView().dumpRenderTree(false);
516 } else if ("about:debug.render.file".equals(urlData.mUrl)) {
517 current.getWebView().dumpRenderTree(true);
518 } else if ("about:debug.display".equals(urlData.mUrl)) {
519 current.getWebView().dumpDisplayTree();
Mike Reed9b78e1d2010-01-13 14:40:52 -0800520 } else if (urlData.mUrl.startsWith("about:debug.drag")) {
521 int index = urlData.mUrl.codePointAt(16) - '0';
522 if (index <= 0 || index > 9) {
523 current.getWebView().setDragTracker(null);
524 } else {
525 current.getWebView().setDragTracker(new MeshTracker(index));
526 }
Grace Kloba638d3f42009-11-23 10:35:04 -0800527 } else {
528 mSettings.toggleDebugSettings();
529 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800530 return;
531 }
Leon Scroggins1f005d32009-08-10 17:36:42 -0400532 // Get rid of the subwindow if it exists
533 dismissSubWindow(current);
Patrick Scott9d53da02010-02-19 10:19:01 -0500534 loadUrlDataIn(current, urlData);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800535 }
536 }
537 }
538
Satish Sampath565505b2009-05-29 15:37:27 +0100539 private int parseUrlShortcut(String url) {
540 if (url == null) return SHORTCUT_INVALID;
541
542 // FIXME: quick search, need to be customized by setting
543 if (url.length() > 2 && url.charAt(1) == ' ') {
544 switch (url.charAt(0)) {
545 case 'g': return SHORTCUT_GOOGLE_SEARCH;
546 case 'w': return SHORTCUT_WIKIPEDIA_SEARCH;
547 case 'd': return SHORTCUT_DICTIONARY_SEARCH;
548 case 'l': return SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH;
549 }
550 }
551 return SHORTCUT_INVALID;
552 }
553
554 /**
555 * Launches the default web search activity with the query parameters if the given intent's data
556 * are identified as plain search terms and not URLs/shortcuts.
557 * @return true if the intent was handled and web search activity was launched, false if not.
558 */
559 private boolean handleWebSearchIntent(Intent intent) {
560 if (intent == null) return false;
561
562 String url = null;
563 final String action = intent.getAction();
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -0500564 if (RecognizerResultsIntent.ACTION_VOICE_SEARCH_RESULTS.equals(
565 action)) {
Leon Scroggins58d56c62010-01-28 15:12:40 -0500566 return false;
567 }
Satish Sampath565505b2009-05-29 15:37:27 +0100568 if (Intent.ACTION_VIEW.equals(action)) {
Grace Kloba1e705052009-09-29 13:13:36 -0700569 Uri data = intent.getData();
570 if (data != null) url = data.toString();
Satish Sampath565505b2009-05-29 15:37:27 +0100571 } else if (Intent.ACTION_SEARCH.equals(action)
572 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
573 || Intent.ACTION_WEB_SEARCH.equals(action)) {
574 url = intent.getStringExtra(SearchManager.QUERY);
575 }
Bjorn Bringert04851702009-09-22 10:36:01 +0100576 return handleWebSearchRequest(url, intent.getBundleExtra(SearchManager.APP_DATA),
577 intent.getStringExtra(SearchManager.EXTRA_DATA_KEY));
Satish Sampath565505b2009-05-29 15:37:27 +0100578 }
579
580 /**
581 * Launches the default web search activity with the query parameters if the given url string
582 * was identified as plain search terms and not URL/shortcut.
583 * @return true if the request was handled and web search activity was launched, false if not.
584 */
Bjorn Bringert04851702009-09-22 10:36:01 +0100585 private boolean handleWebSearchRequest(String inUrl, Bundle appData, String extraData) {
Satish Sampath565505b2009-05-29 15:37:27 +0100586 if (inUrl == null) return false;
587
588 // In general, we shouldn't modify URL from Intent.
589 // But currently, we get the user-typed URL from search box as well.
590 String url = fixUrl(inUrl).trim();
591
592 // URLs and site specific search shortcuts are handled by the regular flow of control, so
593 // return early.
Dan Egnor5ee906c2009-11-18 12:11:49 -0800594 if (Patterns.WEB_URL.matcher(url).matches()
Satish Sampathbc5b9f32009-06-04 18:21:40 +0100595 || ACCEPTED_URI_SCHEMA.matcher(url).matches()
Satish Sampath565505b2009-05-29 15:37:27 +0100596 || parseUrlShortcut(url) != SHORTCUT_INVALID) {
597 return false;
598 }
599
600 Browser.updateVisitedHistory(mResolver, url, false);
601 Browser.addSearchUrl(mResolver, url);
602
603 Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);
604 intent.addCategory(Intent.CATEGORY_DEFAULT);
605 intent.putExtra(SearchManager.QUERY, url);
Satish Sampath15e9f2d2009-06-23 22:29:49 +0100606 if (appData != null) {
607 intent.putExtra(SearchManager.APP_DATA, appData);
608 }
Bjorn Bringert04851702009-09-22 10:36:01 +0100609 if (extraData != null) {
610 intent.putExtra(SearchManager.EXTRA_DATA_KEY, extraData);
611 }
Grace Klobacc634032009-07-28 15:58:19 -0700612 intent.putExtra(Browser.EXTRA_APPLICATION_ID, getPackageName());
Satish Sampath565505b2009-05-29 15:37:27 +0100613 startActivity(intent);
614
615 return true;
616 }
617
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700618 private UrlData getUrlDataFromIntent(Intent intent) {
Leon Scroggins58d56c62010-01-28 15:12:40 -0500619 String url = "";
Grace Kloba068e48b2010-01-26 18:11:27 -0800620 Map<String, String> headers = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800621 if (intent != null) {
622 final String action = intent.getAction();
623 if (Intent.ACTION_VIEW.equals(action)) {
624 url = smartUrlFilter(intent.getData());
625 if (url != null && url.startsWith("content:")) {
626 /* Append mimetype so webview knows how to display */
627 String mimeType = intent.resolveType(getContentResolver());
628 if (mimeType != null) {
629 url += "?" + mimeType;
630 }
631 }
Grace Kloba068e48b2010-01-26 18:11:27 -0800632 if (url != null && url.startsWith("http")) {
Grace Kloba00f54c52010-01-27 14:53:51 -0800633 final Bundle pairs = intent
634 .getBundleExtra(Browser.EXTRA_HEADERS);
Grace Kloba2d508ed2010-01-28 11:39:15 -0800635 if (pairs != null && !pairs.isEmpty()) {
Grace Kloba00f54c52010-01-27 14:53:51 -0800636 Iterator<String> iter = pairs.keySet().iterator();
Grace Kloba068e48b2010-01-26 18:11:27 -0800637 headers = new HashMap<String, String>();
Grace Kloba00f54c52010-01-27 14:53:51 -0800638 while (iter.hasNext()) {
639 String key = iter.next();
640 headers.put(key, pairs.getString(key));
Grace Kloba068e48b2010-01-26 18:11:27 -0800641 }
642 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700643 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800644 } else if (Intent.ACTION_SEARCH.equals(action)
645 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
646 || Intent.ACTION_WEB_SEARCH.equals(action)) {
647 url = intent.getStringExtra(SearchManager.QUERY);
648 if (url != null) {
649 mLastEnteredUrl = url;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800650 // In general, we shouldn't modify URL from Intent.
651 // But currently, we get the user-typed URL from search box as well.
652 url = fixUrl(url);
653 url = smartUrlFilter(url);
Leon Scrogginsda3e0302010-03-02 16:01:49 -0500654 Browser.updateVisitedHistory(mResolver, url, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800655 String searchSource = "&source=android-" + GOOGLE_SEARCH_SOURCE_SUGGEST + "&";
656 if (url.contains(searchSource)) {
657 String source = null;
658 final Bundle appData = intent.getBundleExtra(SearchManager.APP_DATA);
659 if (appData != null) {
Bjorn Bringert10d1cca2010-02-10 14:22:12 +0000660 source = appData.getString(Search.SOURCE);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800661 }
662 if (TextUtils.isEmpty(source)) {
663 source = GOOGLE_SEARCH_SOURCE_UNKNOWN;
664 }
665 url = url.replace(searchSource, "&source=android-"+source+"&");
666 }
667 }
668 }
669 }
Leon Scroggins58d56c62010-01-28 15:12:40 -0500670 return new UrlData(url, headers, intent);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800671 }
Leon Scroggins58d56c62010-01-28 15:12:40 -0500672 /* package */ void showVoiceTitleBar(String title) {
673 mTitleBar.setInVoiceMode(true);
674 mFakeTitleBar.setInVoiceMode(true);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800675
Leon Scroggins58d56c62010-01-28 15:12:40 -0500676 mTitleBar.setDisplayTitle(title);
677 mFakeTitleBar.setDisplayTitle(title);
678 }
679 /* package */ void revertVoiceTitleBar() {
680 mTitleBar.setInVoiceMode(false);
681 mFakeTitleBar.setInVoiceMode(false);
682
Leon Scroggins003a5dd2010-03-10 12:13:14 -0500683 mTitleBar.setDisplayTitle(mUrl);
684 mFakeTitleBar.setDisplayTitle(mUrl);
Leon Scroggins58d56c62010-01-28 15:12:40 -0500685 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800686 /* package */ static String fixUrl(String inUrl) {
Cary Clark652ff872009-09-10 13:34:44 -0400687 // FIXME: Converting the url to lower case
688 // duplicates functionality in smartUrlFilter().
689 // However, changing all current callers of fixUrl to
690 // call smartUrlFilter in addition may have unwanted
691 // consequences, and is deferred for now.
692 int colon = inUrl.indexOf(':');
693 boolean allLower = true;
694 for (int index = 0; index < colon; index++) {
695 char ch = inUrl.charAt(index);
696 if (!Character.isLetter(ch)) {
697 break;
698 }
699 allLower &= Character.isLowerCase(ch);
700 if (index == colon - 1 && !allLower) {
701 inUrl = inUrl.substring(0, colon).toLowerCase()
702 + inUrl.substring(colon);
703 }
704 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800705 if (inUrl.startsWith("http://") || inUrl.startsWith("https://"))
706 return inUrl;
707 if (inUrl.startsWith("http:") ||
708 inUrl.startsWith("https:")) {
709 if (inUrl.startsWith("http:/") || inUrl.startsWith("https:/")) {
710 inUrl = inUrl.replaceFirst("/", "//");
711 } else inUrl = inUrl.replaceFirst(":", "://");
712 }
713 return inUrl;
714 }
715
Grace Kloba22ac16e2009-10-07 18:00:23 -0700716 @Override
717 protected void onResume() {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800718 super.onResume();
Dave Bort31a6d1c2009-04-13 15:56:49 -0700719 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800720 Log.v(LOGTAG, "BrowserActivity.onResume: this=" + this);
721 }
722
723 if (!mActivityInPause) {
724 Log.e(LOGTAG, "BrowserActivity is already resumed.");
725 return;
726 }
727
Mike Reed7bfa63b2009-05-28 11:08:32 -0400728 mTabControl.resumeCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800729 mActivityInPause = false;
Mike Reed7bfa63b2009-05-28 11:08:32 -0400730 resumeWebViewTimers();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800731
732 if (mWakeLock.isHeld()) {
733 mHandler.removeMessages(RELEASE_WAKELOCK);
734 mWakeLock.release();
735 }
736
The Android Open Source Project0c908882009-03-03 19:32:16 -0800737 registerReceiver(mNetworkStateIntentReceiver,
738 mNetworkStateChangedFilter);
739 WebView.enablePlatformNotifications();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800740 }
741
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400742 /**
743 * Since the actual title bar is embedded in the WebView, and removing it
Leon Scrogginsfe87bd32009-10-06 10:10:00 -0400744 * would change its appearance, use a different TitleBar to show overlayed
745 * at the top of the screen, when the menu is open or the page is loading.
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400746 */
747 private TitleBar mFakeTitleBar;
748
749 /**
Leon Scrogginsd8fd2fc2009-09-16 11:12:09 -0400750 * Holder for the fake title bar. It will have a foreground shadow, as well
751 * as a white background, so the fake title bar looks like the real one.
752 */
753 private ViewGroup mFakeTitleBarHolder;
754
755 /**
756 * Layout parameters for the fake title bar within mFakeTitleBarHolder
757 */
758 private FrameLayout.LayoutParams mFakeTitleBarParams
759 = new FrameLayout.LayoutParams(
Romain Guy15b8ec62010-01-08 15:06:43 -0800760 ViewGroup.LayoutParams.MATCH_PARENT,
Leon Scrogginsd8fd2fc2009-09-16 11:12:09 -0400761 ViewGroup.LayoutParams.WRAP_CONTENT);
762 /**
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400763 * Keeps track of whether the options menu is open. This is important in
764 * determining whether to show or hide the title bar overlay.
765 */
766 private boolean mOptionsMenuOpen;
767
768 /**
769 * Only meaningful when mOptionsMenuOpen is true. This variable keeps track
770 * of whether the configuration has changed. The first onMenuOpened call
771 * after a configuration change is simply a reopening of the same menu
772 * (i.e. mIconView did not change).
773 */
774 private boolean mConfigChanged;
775
776 /**
777 * Whether or not the options menu is in its smaller, icon menu form. When
778 * true, we want the title bar overlay to be up. When false, we do not.
779 * Only meaningful if mOptionsMenuOpen is true.
780 */
781 private boolean mIconView;
782
Leon Scrogginsa81a7642009-08-31 17:05:41 -0400783 @Override
784 public boolean onMenuOpened(int featureId, Menu menu) {
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400785 if (Window.FEATURE_OPTIONS_PANEL == featureId) {
786 if (mOptionsMenuOpen) {
787 if (mConfigChanged) {
788 // We do not need to make any changes to the state of the
789 // title bar, since the only thing that happened was a
790 // change in orientation
791 mConfigChanged = false;
792 } else {
793 if (mIconView) {
794 // Switching the menu to expanded view, so hide the
795 // title bar.
796 hideFakeTitleBar();
797 mIconView = false;
798 } else {
799 // Switching the menu back to icon view, so show the
800 // title bar once again.
801 showFakeTitleBar();
802 mIconView = true;
803 }
804 }
805 } else {
806 // The options menu is closed, so open it, and show the title
807 showFakeTitleBar();
808 mOptionsMenuOpen = true;
809 mConfigChanged = false;
810 mIconView = true;
811 }
812 }
Leon Scrogginsa81a7642009-08-31 17:05:41 -0400813 return true;
814 }
815
Leon Scrogginsb94bf272009-09-25 15:22:08 -0400816 /**
817 * Special class used exclusively for the shadow drawn underneath the fake
818 * title bar. The shadow does not need to be drawn if the WebView
819 * underneath is scrolled to the top, because it will draw directly on top
820 * of the embedded shadow.
821 */
822 private static class Shadow extends View {
823 private WebView mWebView;
824
825 public Shadow(Context context, AttributeSet attrs) {
826 super(context, attrs);
827 }
828
829 public void setWebView(WebView view) {
830 mWebView = view;
831 }
832
833 @Override
834 public void draw(Canvas canvas) {
835 // In general onDraw is the method to override, but we care about
836 // whether or not the background gets drawn, which happens in draw()
837 if (mWebView == null || mWebView.getScrollY() > getHeight()) {
838 super.draw(canvas);
839 }
Leon Scrogginsb94bf272009-09-25 15:22:08 -0400840 }
841 }
842
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400843 private void showFakeTitleBar() {
Patrick Scottf8de8ec2009-09-21 16:37:29 -0400844 final View decor = getWindow().peekDecorView();
Leon Scrogginsfe87bd32009-10-06 10:10:00 -0400845 if (mFakeTitleBar.getParent() == null && mActiveTabsPage == null
Patrick Scottf8de8ec2009-09-21 16:37:29 -0400846 && !mActivityInPause && decor != null
847 && decor.getWindowToken() != null) {
Cary Clarka0464552009-09-29 13:00:45 -0400848 Rect visRect = new Rect();
849 if (!mBrowserFrameLayout.getGlobalVisibleRect(visRect)) {
850 if (LOGD_ENABLED) {
851 Log.d(LOGTAG, "showFakeTitleBar visRect failed");
852 }
853 return;
854 }
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400855
856 WindowManager manager
857 = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
858
859 // Add the title bar to the window manager so it can receive touches
860 // while the menu is up
861 WindowManager.LayoutParams params
862 = new WindowManager.LayoutParams(
Romain Guy15b8ec62010-01-08 15:06:43 -0800863 ViewGroup.LayoutParams.MATCH_PARENT,
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400864 ViewGroup.LayoutParams.WRAP_CONTENT,
865 WindowManager.LayoutParams.TYPE_APPLICATION_SUB_PANEL,
866 WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
Leon Scroggins68549862009-09-21 16:02:01 -0400867 PixelFormat.TRANSLUCENT);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400868 params.gravity = Gravity.TOP;
Leon Scrogginsa27ff192009-09-14 12:58:04 -0400869 WebView mainView = mTabControl.getCurrentWebView();
Leon Scroggins68549862009-09-21 16:02:01 -0400870 boolean atTop = mainView != null && mainView.getScrollY() == 0;
Leon Scroggins83932c72009-09-30 11:55:54 -0400871 params.windowAnimations = atTop ? 0 : R.style.TitleBar;
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400872 // XXX : Without providing an offset, the fake title bar will be
873 // placed underneath the status bar. Use the global visible rect
874 // of mBrowserFrameLayout to determine the bottom of the status bar
Cary Clarka0464552009-09-29 13:00:45 -0400875 params.y = visRect.top;
Leon Scroggins68549862009-09-21 16:02:01 -0400876 // Add a holder for the title bar. It also holds a shadow to show
877 // below the title bar.
Leon Scrogginsd8fd2fc2009-09-16 11:12:09 -0400878 if (mFakeTitleBarHolder == null) {
879 mFakeTitleBarHolder = (ViewGroup) LayoutInflater.from(this)
880 .inflate(R.layout.title_bar_bg, null);
881 }
Leon Scrogginsb94bf272009-09-25 15:22:08 -0400882 Shadow shadow = (Shadow) mFakeTitleBarHolder.findViewById(
883 R.id.shadow);
884 shadow.setWebView(mainView);
Leon Scroggins68549862009-09-21 16:02:01 -0400885 mFakeTitleBarHolder.addView(mFakeTitleBar, 0, mFakeTitleBarParams);
Leon Scrogginsd8fd2fc2009-09-16 11:12:09 -0400886 manager.addView(mFakeTitleBarHolder, params);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400887 }
888 }
889
890 @Override
891 public void onOptionsMenuClosed(Menu menu) {
892 mOptionsMenuOpen = false;
Leon Scrogginsa27ff192009-09-14 12:58:04 -0400893 if (!mInLoad) {
894 hideFakeTitleBar();
895 } else if (!mIconView) {
896 // The page is currently loading, and we are in expanded mode, so
897 // we were not showing the menu. Show it once again. It will be
898 // removed when the page finishes.
899 showFakeTitleBar();
900 }
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400901 }
Grace Kloba22ac16e2009-10-07 18:00:23 -0700902
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400903 private void hideFakeTitleBar() {
Leon Scrogginsfe87bd32009-10-06 10:10:00 -0400904 if (mFakeTitleBar.getParent() == null) return;
Leon Scroggins20329572009-09-23 17:42:41 -0400905 WindowManager.LayoutParams params = (WindowManager.LayoutParams)
906 mFakeTitleBarHolder.getLayoutParams();
907 WebView mainView = mTabControl.getCurrentWebView();
908 // Although we decided whether or not to animate based on the current
909 // scroll position, the scroll position may have changed since the
910 // fake title bar was displayed. Make sure it has the appropriate
911 // animation/lack thereof before removing.
912 params.windowAnimations = mainView != null && mainView.getScrollY() == 0
Leon Scroggins83932c72009-09-30 11:55:54 -0400913 ? 0 : R.style.TitleBar;
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400914 WindowManager manager
915 = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
Leon Scroggins20329572009-09-23 17:42:41 -0400916 manager.updateViewLayout(mFakeTitleBarHolder, params);
Leon Scrogginsd8fd2fc2009-09-16 11:12:09 -0400917 mFakeTitleBarHolder.removeView(mFakeTitleBar);
918 manager.removeView(mFakeTitleBarHolder);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400919 }
920
The Android Open Source Project0c908882009-03-03 19:32:16 -0800921 /**
Leon Scrogginsc6fa1102009-09-21 10:40:01 -0400922 * Special method for the fake title bar to call when displaying its context
923 * menu, since it is in its own Window, and its parent does not show a
924 * context menu.
925 */
926 /* package */ void showTitleBarContextMenu() {
Cary Clark65f4a3c2009-09-28 17:05:06 -0400927 if (null == mTitleBar.getParent()) {
928 return;
929 }
Leon Scrogginsc6fa1102009-09-21 10:40:01 -0400930 openContextMenu(mTitleBar);
931 }
932
Leon Scrogginsb2b19f52009-10-09 16:10:00 -0400933 @Override
934 public void onContextMenuClosed(Menu menu) {
935 super.onContextMenuClosed(menu);
936 if (mInLoad) {
937 showFakeTitleBar();
938 }
939 }
940
Leon Scrogginsc6fa1102009-09-21 10:40:01 -0400941 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -0800942 * onSaveInstanceState(Bundle map)
943 * onSaveInstanceState is called right before onStop(). The map contains
944 * the saved state.
945 */
Grace Kloba22ac16e2009-10-07 18:00:23 -0700946 @Override
947 protected void onSaveInstanceState(Bundle outState) {
Dave Bort31a6d1c2009-04-13 15:56:49 -0700948 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800949 Log.v(LOGTAG, "BrowserActivity.onSaveInstanceState: this=" + this);
950 }
951 // the default implementation requires each view to have an id. As the
952 // browser handles the state itself and it doesn't use id for the views,
953 // don't call the default implementation. Otherwise it will trigger the
954 // warning like this, "couldn't save which view has focus because the
955 // focused view XXX has no id".
956
957 // Save all the tabs
958 mTabControl.saveState(outState);
959 }
960
Grace Kloba22ac16e2009-10-07 18:00:23 -0700961 @Override
962 protected void onPause() {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800963 super.onPause();
964
965 if (mActivityInPause) {
966 Log.e(LOGTAG, "BrowserActivity is already paused.");
967 return;
968 }
969
Mike Reed7bfa63b2009-05-28 11:08:32 -0400970 mTabControl.pauseCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800971 mActivityInPause = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -0400972 if (mTabControl.getCurrentIndex() >= 0 && !pauseWebViewTimers()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800973 mWakeLock.acquire();
974 mHandler.sendMessageDelayed(mHandler
975 .obtainMessage(RELEASE_WAKELOCK), WAKELOCK_TIMEOUT);
976 }
977
Leon Scrogginsa2ab6a72009-09-11 11:49:52 -0400978 // FIXME: This removes the active tabs page and resets the menu to
979 // MAIN_MENU. A better solution might be to do this work in onNewIntent
980 // but then we would need to save it in onSaveInstanceState and restore
981 // it in onCreate/onRestoreInstanceState
982 if (mActiveTabsPage != null) {
983 removeActiveTabPage(true);
984 }
985
The Android Open Source Project0c908882009-03-03 19:32:16 -0800986 cancelStopToast();
987
988 // unregister network state listener
989 unregisterReceiver(mNetworkStateIntentReceiver);
990 WebView.disablePlatformNotifications();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800991 }
992
Grace Kloba22ac16e2009-10-07 18:00:23 -0700993 @Override
994 protected void onDestroy() {
Dave Bort31a6d1c2009-04-13 15:56:49 -0700995 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800996 Log.v(LOGTAG, "BrowserActivity.onDestroy: this=" + this);
997 }
998 super.onDestroy();
Grace Kloba0923d692009-09-23 21:37:25 -0700999
Leon Scroggins8d5fa432009-10-02 15:55:59 -04001000 if (mUploadMessage != null) {
1001 mUploadMessage.onReceiveValue(null);
1002 mUploadMessage = null;
1003 }
1004
Grace Kloba0923d692009-09-23 21:37:25 -07001005 if (mTabControl == null) return;
1006
Grace Kloba1fc98a32009-10-21 13:23:08 -07001007 // Remove the fake title bar if it is there
1008 hideFakeTitleBar();
1009
The Android Open Source Project0c908882009-03-03 19:32:16 -08001010 // Remove the current tab and sub window
Grace Kloba22ac16e2009-10-07 18:00:23 -07001011 Tab t = mTabControl.getCurrentTab();
Patrick Scottfb5e77f2009-04-08 19:17:37 -07001012 if (t != null) {
1013 dismissSubWindow(t);
1014 removeTabFromContentView(t);
1015 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001016 // Destroy all the tabs
1017 mTabControl.destroy();
1018 WebIconDatabase.getInstance().close();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001019
Grace Klobab4da0ad2009-05-14 14:45:40 -07001020 unregisterReceiver(mPackageInstallationReceiver);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001021 }
1022
1023 @Override
1024 public void onConfigurationChanged(Configuration newConfig) {
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04001025 mConfigChanged = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001026 super.onConfigurationChanged(newConfig);
1027
1028 if (mPageInfoDialog != null) {
1029 mPageInfoDialog.dismiss();
1030 showPageInfo(
1031 mPageInfoView,
Leon Scrogginsc7b92f82010-01-11 18:17:31 -05001032 mPageInfoFromShowSSLCertificateOnError);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001033 }
1034 if (mSSLCertificateDialog != null) {
1035 mSSLCertificateDialog.dismiss();
1036 showSSLCertificate(
1037 mSSLCertificateView);
1038 }
1039 if (mSSLCertificateOnErrorDialog != null) {
1040 mSSLCertificateOnErrorDialog.dismiss();
1041 showSSLCertificateOnError(
1042 mSSLCertificateOnErrorView,
1043 mSSLCertificateOnErrorHandler,
1044 mSSLCertificateOnErrorError);
1045 }
1046 if (mHttpAuthenticationDialog != null) {
1047 String title = ((TextView) mHttpAuthenticationDialog
1048 .findViewById(com.android.internal.R.id.alertTitle)).getText()
1049 .toString();
1050 String name = ((TextView) mHttpAuthenticationDialog
1051 .findViewById(R.id.username_edit)).getText().toString();
1052 String password = ((TextView) mHttpAuthenticationDialog
1053 .findViewById(R.id.password_edit)).getText().toString();
1054 int focusId = mHttpAuthenticationDialog.getCurrentFocus()
1055 .getId();
1056 mHttpAuthenticationDialog.dismiss();
1057 showHttpAuthentication(mHttpAuthHandler, null, null, title,
1058 name, password, focusId);
1059 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001060 }
1061
Grace Kloba22ac16e2009-10-07 18:00:23 -07001062 @Override
1063 public void onLowMemory() {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001064 super.onLowMemory();
1065 mTabControl.freeMemory();
1066 }
1067
Mike Reed7bfa63b2009-05-28 11:08:32 -04001068 private boolean resumeWebViewTimers() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001069 Tab tab = mTabControl.getCurrentTab();
1070 boolean inLoad = tab.inLoad();
1071 if ((!mActivityInPause && !inLoad) || (mActivityInPause && inLoad)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001072 CookieSyncManager.getInstance().startSync();
Grace Kloba22ac16e2009-10-07 18:00:23 -07001073 WebView w = tab.getWebView();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001074 if (w != null) {
1075 w.resumeTimers();
1076 }
1077 return true;
1078 } else {
1079 return false;
1080 }
1081 }
1082
Mike Reed7bfa63b2009-05-28 11:08:32 -04001083 private boolean pauseWebViewTimers() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001084 Tab tab = mTabControl.getCurrentTab();
1085 boolean inLoad = tab.inLoad();
1086 if (mActivityInPause && !inLoad) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001087 CookieSyncManager.getInstance().stopSync();
1088 WebView w = mTabControl.getCurrentWebView();
1089 if (w != null) {
1090 w.pauseTimers();
1091 }
1092 return true;
1093 } else {
1094 return false;
1095 }
1096 }
1097
The Android Open Source Project0c908882009-03-03 19:32:16 -08001098 // Open the icon database and retain all the icons for visited sites.
1099 private void retainIconsOnStartup() {
1100 final WebIconDatabase db = WebIconDatabase.getInstance();
1101 db.open(getDir("icons", 0).getPath());
Leon Scroggins2c0f6112010-03-12 18:09:39 -05001102 Cursor c = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001103 try {
Leon Scroggins2c0f6112010-03-12 18:09:39 -05001104 c = Browser.getAllBookmarks(mResolver);
1105 if (c.moveToFirst()) {
1106 int urlIndex = c.getColumnIndex(Browser.BookmarkColumns.URL);
1107 do {
1108 String url = c.getString(urlIndex);
1109 db.retainIconForPageUrl(url);
1110 } while (c.moveToNext());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001111 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001112 } catch (IllegalStateException e) {
1113 Log.e(LOGTAG, "retainIconsOnStartup", e);
Leon Scroggins2c0f6112010-03-12 18:09:39 -05001114 } finally {
1115 if (c!= null) c.close();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001116 }
1117 }
1118
1119 // Helper method for getting the top window.
1120 WebView getTopWindow() {
1121 return mTabControl.getCurrentTopWebView();
1122 }
1123
Grace Kloba22ac16e2009-10-07 18:00:23 -07001124 TabControl getTabControl() {
1125 return mTabControl;
1126 }
1127
The Android Open Source Project0c908882009-03-03 19:32:16 -08001128 @Override
1129 public boolean onCreateOptionsMenu(Menu menu) {
1130 super.onCreateOptionsMenu(menu);
1131
1132 MenuInflater inflater = getMenuInflater();
1133 inflater.inflate(R.menu.browser, menu);
1134 mMenu = menu;
1135 updateInLoadMenuItems();
1136 return true;
1137 }
1138
1139 /**
1140 * As the menu can be open when loading state changes
1141 * we must manually update the state of the stop/reload menu
1142 * item
1143 */
1144 private void updateInLoadMenuItems() {
1145 if (mMenu == null) {
1146 return;
1147 }
1148 MenuItem src = mInLoad ?
1149 mMenu.findItem(R.id.stop_menu_id):
1150 mMenu.findItem(R.id.reload_menu_id);
1151 MenuItem dest = mMenu.findItem(R.id.stop_reload_menu_id);
1152 dest.setIcon(src.getIcon());
1153 dest.setTitle(src.getTitle());
1154 }
1155
1156 @Override
1157 public boolean onContextItemSelected(MenuItem item) {
1158 // chording is not an issue with context menus, but we use the same
1159 // options selector, so set mCanChord to true so we can access them.
1160 mCanChord = true;
1161 int id = item.getItemId();
Leon Scroggins96afcb12009-12-10 12:35:56 -05001162 boolean result = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001163 switch (id) {
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001164 // For the context menu from the title bar
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001165 case R.id.title_bar_copy_page_url:
Leon Scroggins96afcb12009-12-10 12:35:56 -05001166 Tab currentTab = mTabControl.getCurrentTab();
1167 if (null == currentTab) {
1168 result = false;
1169 break;
1170 }
1171 WebView mainView = currentTab.getWebView();
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001172 if (null == mainView) {
Leon Scroggins96afcb12009-12-10 12:35:56 -05001173 result = false;
1174 break;
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001175 }
Leon Scroggins96afcb12009-12-10 12:35:56 -05001176 copy(mainView.getUrl());
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001177 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001178 // -- Browser context menu
1179 case R.id.open_context_menu_id:
1180 case R.id.open_newtab_context_menu_id:
1181 case R.id.bookmark_context_menu_id:
1182 case R.id.save_link_context_menu_id:
1183 case R.id.share_link_context_menu_id:
1184 case R.id.copy_link_context_menu_id:
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001185 final WebView webView = getTopWindow();
1186 if (null == webView) {
Leon Scroggins96afcb12009-12-10 12:35:56 -05001187 result = false;
1188 break;
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001189 }
1190 final HashMap hrefMap = new HashMap();
1191 hrefMap.put("webview", webView);
1192 final Message msg = mHandler.obtainMessage(
1193 FOCUS_NODE_HREF, id, 0, hrefMap);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001194 webView.requestFocusNodeHref(msg);
1195 break;
1196
1197 default:
1198 // For other context menus
Leon Scroggins96afcb12009-12-10 12:35:56 -05001199 result = onOptionsItemSelected(item);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001200 }
1201 mCanChord = false;
Leon Scroggins96afcb12009-12-10 12:35:56 -05001202 return result;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001203 }
1204
1205 private Bundle createGoogleSearchSourceBundle(String source) {
1206 Bundle bundle = new Bundle();
Bjorn Bringert10d1cca2010-02-10 14:22:12 +00001207 bundle.putString(Search.SOURCE, source);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001208 return bundle;
1209 }
1210
Leon Scroggins8ad29922010-02-16 12:33:55 -05001211 /* package */ void editUrl() {
Leon Scroggins68579392009-09-15 15:31:54 -04001212 if (mOptionsMenuOpen) closeOptionsMenu();
Leon Scroggins5bbe9802009-07-31 13:10:55 -04001213 String url = (getTopWindow() == null) ? null : getTopWindow().getUrl();
Grace Kloba83f47342009-07-20 10:44:31 -07001214 startSearch(mSettings.getHomePage().equals(url) ? null : url, true,
Leon Scroggins8ad29922010-02-16 12:33:55 -05001215 null, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001216 }
1217
Leon Scroggins8ad29922010-02-16 12:33:55 -05001218 /**
1219 * Overriding this to insert a local information bundle
1220 */
The Android Open Source Project0c908882009-03-03 19:32:16 -08001221 @Override
1222 public void startSearch(String initialQuery, boolean selectInitialQuery,
1223 Bundle appSearchData, boolean globalSearch) {
1224 if (appSearchData == null) {
1225 appSearchData = createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_TYPE);
1226 }
1227 super.startSearch(initialQuery, selectInitialQuery, appSearchData, globalSearch);
1228 }
1229
Leon Scroggins1f005d32009-08-10 17:36:42 -04001230 /**
1231 * Switch tabs. Called by the TitleBarSet when sliding the title bar
1232 * results in changing tabs.
Leon Scroggins160a7e72009-08-14 18:28:01 -04001233 * @param index Index of the tab to change to, as defined by
1234 * mTabControl.getTabIndex(Tab t).
1235 * @return boolean True if we successfully switched to a different tab. If
1236 * the indexth tab is null, or if that tab is the same as
1237 * the current one, return false.
Leon Scroggins1f005d32009-08-10 17:36:42 -04001238 */
Leon Scroggins160a7e72009-08-14 18:28:01 -04001239 /* package */ boolean switchToTab(int index) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001240 Tab tab = mTabControl.getTab(index);
1241 Tab currentTab = mTabControl.getCurrentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04001242 if (tab == null || tab == currentTab) {
Leon Scroggins160a7e72009-08-14 18:28:01 -04001243 return false;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001244 }
1245 if (currentTab != null) {
1246 // currentTab may be null if it was just removed. In that case,
1247 // we do not need to remove it
1248 removeTabFromContentView(currentTab);
1249 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001250 mTabControl.setCurrentTab(tab);
1251 attachTabToContentView(tab);
Grace Klobaeb6eef42009-09-15 17:56:32 -07001252 resetTitleIconAndProgress();
1253 updateLockIconToLatest();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001254 return true;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001255 }
1256
Grace Kloba22ac16e2009-10-07 18:00:23 -07001257 /* package */ Tab openTabToHomePage() {
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001258 return openTabAndShow(mSettings.getHomePage(), false, null);
1259 }
1260
Leon Scroggins1f005d32009-08-10 17:36:42 -04001261 /* package */ void closeCurrentWindow() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001262 final Tab current = mTabControl.getCurrentTab();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001263 if (mTabControl.getTabCount() == 1) {
Leon Scroggins30444232009-09-04 18:36:20 -04001264 // This is the last tab. Open a new one, with the home
1265 // page and close the current one.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001266 openTabToHomePage();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001267 closeTab(current);
Leon Scroggins160a7e72009-08-14 18:28:01 -04001268 return;
1269 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07001270 final Tab parent = current.getParentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04001271 int indexToShow = -1;
1272 if (parent != null) {
1273 indexToShow = mTabControl.getTabIndex(parent);
1274 } else {
Leon Scroggins160a7e72009-08-14 18:28:01 -04001275 final int currentIndex = mTabControl.getCurrentIndex();
1276 // Try to move to the tab to the right
1277 indexToShow = currentIndex + 1;
1278 if (indexToShow > mTabControl.getTabCount() - 1) {
1279 // Try to move to the tab to the left
1280 indexToShow = currentIndex - 1;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001281 }
1282 }
Leon Scroggins160a7e72009-08-14 18:28:01 -04001283 if (switchToTab(indexToShow)) {
1284 // Close window
1285 closeTab(current);
1286 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001287 }
1288
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001289 private ActiveTabsPage mActiveTabsPage;
1290
1291 /**
1292 * Remove the active tabs page.
1293 * @param needToAttach If true, the active tabs page did not attach a tab
1294 * to the content view, so we need to do that here.
1295 */
1296 /* package */ void removeActiveTabPage(boolean needToAttach) {
1297 mContentView.removeView(mActiveTabsPage);
1298 mActiveTabsPage = null;
1299 mMenuState = R.id.MAIN_MENU;
1300 if (needToAttach) {
1301 attachTabToContentView(mTabControl.getCurrentTab());
1302 }
1303 getTopWindow().requestFocus();
1304 }
1305
The Android Open Source Project0c908882009-03-03 19:32:16 -08001306 @Override
1307 public boolean onOptionsItemSelected(MenuItem item) {
1308 if (!mCanChord) {
1309 // The user has already fired a shortcut with this hold down of the
1310 // menu key.
1311 return false;
1312 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001313 if (null == getTopWindow()) {
Leon Scroggins0d7ae0e2009-06-05 11:04:45 -04001314 return false;
1315 }
Grace Kloba6ee9c492009-07-13 10:04:34 -07001316 if (mMenuIsDown) {
1317 // The shortcut action consumes the MENU. Even if it is still down,
1318 // it won't trigger the next shortcut action. In the case of the
1319 // shortcut action triggering a new activity, like Bookmarks, we
1320 // won't get onKeyUp for MENU. So it is important to reset it here.
1321 mMenuIsDown = false;
1322 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001323 switch (item.getItemId()) {
1324 // -- Main menu
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001325 case R.id.new_tab_menu_id:
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001326 openTabToHomePage();
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001327 break;
1328
Leon Scroggins64b80f32009-08-07 12:03:34 -04001329 case R.id.goto_menu_id:
Leon Scroggins8ad29922010-02-16 12:33:55 -05001330 editUrl();
Leon Scrogginsb3a5bed2009-09-28 11:21:56 -04001331 break;
1332
1333 case R.id.bookmarks_menu_id:
Leon Scroggins30444232009-09-04 18:36:20 -04001334 bookmarksOrHistoryPicker(false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001335 break;
1336
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001337 case R.id.active_tabs_menu_id:
1338 mActiveTabsPage = new ActiveTabsPage(this, mTabControl);
1339 removeTabFromContentView(mTabControl.getCurrentTab());
Leon Scroggins43de6162009-09-14 19:59:58 -04001340 hideFakeTitleBar();
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001341 mContentView.addView(mActiveTabsPage, COVER_SCREEN_PARAMS);
1342 mActiveTabsPage.requestFocus();
1343 mMenuState = EMPTY_MENU;
1344 break;
1345
Leon Scroggins1f005d32009-08-10 17:36:42 -04001346 case R.id.add_bookmark_menu_id:
1347 Intent i = new Intent(BrowserActivity.this,
1348 AddBookmarkPage.class);
1349 WebView w = getTopWindow();
1350 i.putExtra("url", w.getUrl());
1351 i.putExtra("title", w.getTitle());
Grace Kloba83cdb2c2009-09-16 00:48:57 -07001352 i.putExtra("touch_icon_url", w.getTouchIconUrl());
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01001353 i.putExtra("thumbnail", createScreenshot(w));
Leon Scroggins1f005d32009-08-10 17:36:42 -04001354 startActivity(i);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001355 break;
1356
1357 case R.id.stop_reload_menu_id:
1358 if (mInLoad) {
1359 stopLoading();
1360 } else {
1361 getTopWindow().reload();
1362 }
1363 break;
1364
1365 case R.id.back_menu_id:
1366 getTopWindow().goBack();
1367 break;
1368
1369 case R.id.forward_menu_id:
1370 getTopWindow().goForward();
1371 break;
1372
1373 case R.id.close_menu_id:
1374 // Close the subwindow if it exists.
1375 if (mTabControl.getCurrentSubWindow() != null) {
1376 dismissSubWindow(mTabControl.getCurrentTab());
1377 break;
1378 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001379 closeCurrentWindow();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001380 break;
1381
1382 case R.id.homepage_menu_id:
Grace Kloba22ac16e2009-10-07 18:00:23 -07001383 Tab current = mTabControl.getCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001384 if (current != null) {
1385 dismissSubWindow(current);
Leon Scroggins92472e82010-02-17 16:32:28 -05001386 loadUrl(current.getWebView(), mSettings.getHomePage());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001387 }
1388 break;
1389
1390 case R.id.preferences_menu_id:
1391 Intent intent = new Intent(this,
1392 BrowserPreferencesPage.class);
Leon Scrogginsd5304942009-12-10 16:11:39 -05001393 intent.putExtra(BrowserPreferencesPage.CURRENT_PAGE,
1394 getTopWindow().getUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001395 startActivityForResult(intent, PREFERENCES_PAGE);
1396 break;
1397
1398 case R.id.find_menu_id:
1399 if (null == mFindDialog) {
1400 mFindDialog = new FindDialog(this);
1401 }
1402 mFindDialog.setWebView(getTopWindow());
1403 mFindDialog.show();
Cary Clark7d3ac792010-03-03 10:11:44 -05001404 getTopWindow().setFindIsUp(true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001405 mMenuState = EMPTY_MENU;
1406 break;
1407
1408 case R.id.select_text_id:
1409 getTopWindow().emulateShiftHeld();
1410 break;
1411 case R.id.page_info_menu_id:
1412 showPageInfo(mTabControl.getCurrentTab(), false);
1413 break;
1414
1415 case R.id.classic_history_menu_id:
Leon Scroggins30444232009-09-04 18:36:20 -04001416 bookmarksOrHistoryPicker(true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001417 break;
1418
Leon Scroggins96afcb12009-12-10 12:35:56 -05001419 case R.id.title_bar_share_page_url:
The Android Open Source Project0c908882009-03-03 19:32:16 -08001420 case R.id.share_page_menu_id:
Leon Scroggins96afcb12009-12-10 12:35:56 -05001421 Tab currentTab = mTabControl.getCurrentTab();
1422 if (null == currentTab) {
1423 mCanChord = false;
1424 return false;
1425 }
1426 currentTab.populatePickerData();
1427 sharePage(this, currentTab.getTitle(),
1428 currentTab.getUrl(), currentTab.getFavicon(),
1429 createScreenshot(currentTab.getWebView()));
The Android Open Source Project0c908882009-03-03 19:32:16 -08001430 break;
1431
1432 case R.id.dump_nav_menu_id:
1433 getTopWindow().debugDump();
1434 break;
1435
Andrei Popescu7a8b88b2010-02-02 00:30:38 +00001436 case R.id.dump_counters_menu_id:
1437 getTopWindow().dumpV8Counters();
1438 break;
1439
The Android Open Source Project0c908882009-03-03 19:32:16 -08001440 case R.id.zoom_in_menu_id:
1441 getTopWindow().zoomIn();
1442 break;
1443
1444 case R.id.zoom_out_menu_id:
1445 getTopWindow().zoomOut();
1446 break;
1447
1448 case R.id.view_downloads_menu_id:
1449 viewDownloads(null);
1450 break;
1451
The Android Open Source Project0c908882009-03-03 19:32:16 -08001452 case R.id.window_one_menu_id:
1453 case R.id.window_two_menu_id:
1454 case R.id.window_three_menu_id:
1455 case R.id.window_four_menu_id:
1456 case R.id.window_five_menu_id:
1457 case R.id.window_six_menu_id:
1458 case R.id.window_seven_menu_id:
1459 case R.id.window_eight_menu_id:
1460 {
1461 int menuid = item.getItemId();
1462 for (int id = 0; id < WINDOW_SHORTCUT_ID_ARRAY.length; id++) {
1463 if (WINDOW_SHORTCUT_ID_ARRAY[id] == menuid) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001464 Tab desiredTab = mTabControl.getTab(id);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001465 if (desiredTab != null &&
1466 desiredTab != mTabControl.getCurrentTab()) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001467 switchToTab(id);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001468 }
1469 break;
1470 }
1471 }
1472 }
1473 break;
1474
1475 default:
1476 if (!super.onOptionsItemSelected(item)) {
1477 return false;
1478 }
1479 // Otherwise fall through.
1480 }
1481 mCanChord = false;
1482 return true;
1483 }
1484
1485 public void closeFind() {
1486 mMenuState = R.id.MAIN_MENU;
1487 }
1488
Grace Kloba22ac16e2009-10-07 18:00:23 -07001489 @Override
1490 public boolean onPrepareOptionsMenu(Menu menu) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001491 // This happens when the user begins to hold down the menu key, so
1492 // allow them to chord to get a shortcut.
1493 mCanChord = true;
1494 // Note: setVisible will decide whether an item is visible; while
1495 // setEnabled() will decide whether an item is enabled, which also means
1496 // whether the matching shortcut key will function.
1497 super.onPrepareOptionsMenu(menu);
1498 switch (mMenuState) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001499 case EMPTY_MENU:
1500 if (mCurrentMenuState != mMenuState) {
1501 menu.setGroupVisible(R.id.MAIN_MENU, false);
1502 menu.setGroupEnabled(R.id.MAIN_MENU, false);
1503 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001504 }
1505 break;
1506 default:
1507 if (mCurrentMenuState != mMenuState) {
1508 menu.setGroupVisible(R.id.MAIN_MENU, true);
1509 menu.setGroupEnabled(R.id.MAIN_MENU, true);
1510 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001511 }
1512 final WebView w = getTopWindow();
1513 boolean canGoBack = false;
1514 boolean canGoForward = false;
1515 boolean isHome = false;
1516 if (w != null) {
1517 canGoBack = w.canGoBack();
1518 canGoForward = w.canGoForward();
1519 isHome = mSettings.getHomePage().equals(w.getUrl());
1520 }
1521 final MenuItem back = menu.findItem(R.id.back_menu_id);
1522 back.setEnabled(canGoBack);
1523
1524 final MenuItem home = menu.findItem(R.id.homepage_menu_id);
1525 home.setEnabled(!isHome);
1526
1527 menu.findItem(R.id.forward_menu_id)
1528 .setEnabled(canGoForward);
1529
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001530 menu.findItem(R.id.new_tab_menu_id).setEnabled(
Grace Kloba22ac16e2009-10-07 18:00:23 -07001531 mTabControl.canCreateNewTab());
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001532
The Android Open Source Project0c908882009-03-03 19:32:16 -08001533 // decide whether to show the share link option
1534 PackageManager pm = getPackageManager();
1535 Intent send = new Intent(Intent.ACTION_SEND);
1536 send.setType("text/plain");
1537 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1538 menu.findItem(R.id.share_page_menu_id).setVisible(ri != null);
1539
The Android Open Source Project0c908882009-03-03 19:32:16 -08001540 boolean isNavDump = mSettings.isNavDump();
1541 final MenuItem nav = menu.findItem(R.id.dump_nav_menu_id);
1542 nav.setVisible(isNavDump);
1543 nav.setEnabled(isNavDump);
Andrei Popescu7a8b88b2010-02-02 00:30:38 +00001544
1545 boolean showDebugSettings = mSettings.showDebugSettings();
1546 final MenuItem counter = menu.findItem(R.id.dump_counters_menu_id);
1547 counter.setVisible(showDebugSettings);
1548 counter.setEnabled(showDebugSettings);
1549
The Android Open Source Project0c908882009-03-03 19:32:16 -08001550 break;
1551 }
1552 mCurrentMenuState = mMenuState;
1553 return true;
1554 }
1555
1556 @Override
1557 public void onCreateContextMenu(ContextMenu menu, View v,
1558 ContextMenuInfo menuInfo) {
Leon Scroggins4e9f89b2010-02-22 16:54:14 -05001559 if (v instanceof TitleBar) {
1560 return;
1561 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001562 WebView webview = (WebView) v;
1563 WebView.HitTestResult result = webview.getHitTestResult();
1564 if (result == null) {
1565 return;
1566 }
1567
1568 int type = result.getType();
1569 if (type == WebView.HitTestResult.UNKNOWN_TYPE) {
1570 Log.w(LOGTAG,
1571 "We should not show context menu when nothing is touched");
1572 return;
1573 }
1574 if (type == WebView.HitTestResult.EDIT_TEXT_TYPE) {
1575 // let TextView handles context menu
1576 return;
1577 }
1578
1579 // Note, http://b/issue?id=1106666 is requesting that
1580 // an inflated menu can be used again. This is not available
1581 // yet, so inflate each time (yuk!)
1582 MenuInflater inflater = getMenuInflater();
1583 inflater.inflate(R.menu.browsercontext, menu);
1584
1585 // Show the correct menu group
1586 String extra = result.getExtra();
1587 menu.setGroupVisible(R.id.PHONE_MENU,
1588 type == WebView.HitTestResult.PHONE_TYPE);
1589 menu.setGroupVisible(R.id.EMAIL_MENU,
1590 type == WebView.HitTestResult.EMAIL_TYPE);
1591 menu.setGroupVisible(R.id.GEO_MENU,
1592 type == WebView.HitTestResult.GEO_TYPE);
1593 menu.setGroupVisible(R.id.IMAGE_MENU,
1594 type == WebView.HitTestResult.IMAGE_TYPE
1595 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1596 menu.setGroupVisible(R.id.ANCHOR_MENU,
1597 type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1598 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1599
1600 // Setup custom handling depending on the type
1601 switch (type) {
1602 case WebView.HitTestResult.PHONE_TYPE:
1603 menu.setHeaderTitle(Uri.decode(extra));
1604 menu.findItem(R.id.dial_context_menu_id).setIntent(
1605 new Intent(Intent.ACTION_VIEW, Uri
1606 .parse(WebView.SCHEME_TEL + extra)));
1607 Intent addIntent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
1608 addIntent.putExtra(Insert.PHONE, Uri.decode(extra));
Cary Clark5e335a32009-09-22 14:53:11 -04001609 addIntent.setType(ContactsContract.Contacts.CONTENT_ITEM_TYPE);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001610 menu.findItem(R.id.add_contact_context_menu_id).setIntent(
1611 addIntent);
1612 menu.findItem(R.id.copy_phone_context_menu_id).setOnMenuItemClickListener(
1613 new Copy(extra));
1614 break;
1615
1616 case WebView.HitTestResult.EMAIL_TYPE:
1617 menu.setHeaderTitle(extra);
1618 menu.findItem(R.id.email_context_menu_id).setIntent(
1619 new Intent(Intent.ACTION_VIEW, Uri
1620 .parse(WebView.SCHEME_MAILTO + extra)));
1621 menu.findItem(R.id.copy_mail_context_menu_id).setOnMenuItemClickListener(
1622 new Copy(extra));
1623 break;
1624
1625 case WebView.HitTestResult.GEO_TYPE:
1626 menu.setHeaderTitle(extra);
1627 menu.findItem(R.id.map_context_menu_id).setIntent(
1628 new Intent(Intent.ACTION_VIEW, Uri
1629 .parse(WebView.SCHEME_GEO
1630 + URLEncoder.encode(extra))));
1631 menu.findItem(R.id.copy_geo_context_menu_id).setOnMenuItemClickListener(
1632 new Copy(extra));
1633 break;
1634
1635 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1636 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
1637 TextView titleView = (TextView) LayoutInflater.from(this)
1638 .inflate(android.R.layout.browser_link_context_header,
1639 null);
1640 titleView.setText(extra);
1641 menu.setHeaderView(titleView);
1642 // decide whether to show the open link in new tab option
1643 menu.findItem(R.id.open_newtab_context_menu_id).setVisible(
Grace Kloba22ac16e2009-10-07 18:00:23 -07001644 mTabControl.canCreateNewTab());
Ben Murdochde353622009-10-12 10:29:00 +01001645 menu.findItem(R.id.bookmark_context_menu_id).setVisible(
1646 Bookmarks.urlHasAcceptableScheme(extra));
The Android Open Source Project0c908882009-03-03 19:32:16 -08001647 PackageManager pm = getPackageManager();
1648 Intent send = new Intent(Intent.ACTION_SEND);
1649 send.setType("text/plain");
1650 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1651 menu.findItem(R.id.share_link_context_menu_id).setVisible(ri != null);
1652 if (type == WebView.HitTestResult.SRC_ANCHOR_TYPE) {
1653 break;
1654 }
1655 // otherwise fall through to handle image part
1656 case WebView.HitTestResult.IMAGE_TYPE:
1657 if (type == WebView.HitTestResult.IMAGE_TYPE) {
1658 menu.setHeaderTitle(extra);
1659 }
1660 menu.findItem(R.id.view_image_context_menu_id).setIntent(
1661 new Intent(Intent.ACTION_VIEW, Uri.parse(extra)));
1662 menu.findItem(R.id.download_context_menu_id).
1663 setOnMenuItemClickListener(new Download(extra));
Ben Murdoch4f75ba22009-10-27 11:48:28 +00001664 menu.findItem(R.id.set_wallpaper_context_menu_id).
1665 setOnMenuItemClickListener(new SetAsWallpaper(extra));
The Android Open Source Project0c908882009-03-03 19:32:16 -08001666 break;
1667
1668 default:
1669 Log.w(LOGTAG, "We should not get here.");
1670 break;
1671 }
Leon Scrogginsb2b19f52009-10-09 16:10:00 -04001672 hideFakeTitleBar();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001673 }
1674
The Android Open Source Project0c908882009-03-03 19:32:16 -08001675 // Attach the given tab to the content view.
Grace Klobac928c302009-09-17 11:51:21 -07001676 // this should only be called for the current tab.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001677 private void attachTabToContentView(Tab t) {
Steve Block2bc69912009-07-30 14:45:13 +01001678 // Attach the container that contains the main WebView and any other UI
1679 // associated with the tab.
Patrick Scottd0119532009-09-17 08:00:31 -04001680 t.attachTabToContentView(mContentView);
Ben Murdochbff2d602009-07-01 20:19:05 +01001681
1682 if (mShouldShowErrorConsole) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001683 ErrorConsoleView errorConsole = t.getErrorConsole(true);
Ben Murdochbff2d602009-07-01 20:19:05 +01001684 if (errorConsole.numberOfErrors() == 0) {
1685 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
1686 } else {
1687 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
1688 }
1689
1690 mErrorConsoleContainer.addView(errorConsole,
Romain Guy15b8ec62010-01-08 15:06:43 -08001691 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
Ben Murdochbff2d602009-07-01 20:19:05 +01001692 ViewGroup.LayoutParams.WRAP_CONTENT));
1693 }
1694
Leon Scroggins39ab28e2009-09-02 21:20:30 -04001695 WebView view = t.getWebView();
Leon Scroggins55a5bc22009-09-04 17:00:08 -04001696 view.setEmbeddedTitleBar(mTitleBar);
Leon Scroggins58d56c62010-01-28 15:12:40 -05001697 if (t.isInVoiceSearchMode()) {
1698 showVoiceTitleBar(t.getVoiceDisplayTitle());
1699 } else {
1700 revertVoiceTitleBar();
1701 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001702 // Request focus on the top window.
1703 t.getTopWindow().requestFocus();
1704 }
1705
1706 // Attach a sub window to the main WebView of the given tab.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001707 void attachSubWindow(Tab t) {
Patrick Scottd0119532009-09-17 08:00:31 -04001708 t.attachSubWindow(mContentView);
1709 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001710 }
1711
1712 // Remove the given tab from the content view.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001713 private void removeTabFromContentView(Tab t) {
Steve Block2bc69912009-07-30 14:45:13 +01001714 // Remove the container that contains the main WebView.
Patrick Scottd0119532009-09-17 08:00:31 -04001715 t.removeTabFromContentView(mContentView);
Ben Murdochbff2d602009-07-01 20:19:05 +01001716
Grace Kloba22ac16e2009-10-07 18:00:23 -07001717 ErrorConsoleView errorConsole = t.getErrorConsole(false);
1718 if (errorConsole != null) {
1719 mErrorConsoleContainer.removeView(errorConsole);
Ben Murdochbff2d602009-07-01 20:19:05 +01001720 }
1721
Leon Scroggins39ab28e2009-09-02 21:20:30 -04001722 WebView view = t.getWebView();
Leon Scrogginsbb85b902009-09-14 19:27:20 -04001723 if (view != null) {
1724 view.setEmbeddedTitleBar(null);
1725 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001726 }
1727
1728 // Remove the sub window if it exists. Also called by TabControl when the
1729 // user clicks the 'X' to dismiss a sub window.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001730 /* package */ void dismissSubWindow(Tab t) {
Patrick Scottd0119532009-09-17 08:00:31 -04001731 t.removeSubWindow(mContentView);
Grace Kloba22ac16e2009-10-07 18:00:23 -07001732 // dismiss the subwindow. This will destroy the WebView.
1733 t.dismissSubWindow();
Patrick Scottd0119532009-09-17 08:00:31 -04001734 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001735 }
1736
Leon Scroggins1f005d32009-08-10 17:36:42 -04001737 // A wrapper function of {@link #openTabAndShow(UrlData, boolean, String)}
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07001738 // that accepts url as string.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001739 private Tab openTabAndShow(String url, boolean closeOnExit, String appId) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001740 return openTabAndShow(new UrlData(url), closeOnExit, appId);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001741 }
1742
1743 // This method does a ton of stuff. It will attempt to create a new tab
1744 // if we haven't reached MAX_TABS. Otherwise it uses the current tab. If
Leon Scroggins1f005d32009-08-10 17:36:42 -04001745 // url isn't null, it will load the given url.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001746 /* package */Tab openTabAndShow(UrlData urlData, boolean closeOnExit,
1747 String appId) {
1748 final Tab currentTab = mTabControl.getCurrentTab();
1749 if (mTabControl.canCreateNewTab()) {
1750 final Tab tab = mTabControl.createNewTab(closeOnExit, appId,
1751 urlData.mUrl);
Leon Scroggins1f005d32009-08-10 17:36:42 -04001752 WebView webview = tab.getWebView();
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001753 // If the last tab was removed from the active tabs page, currentTab
1754 // will be null.
1755 if (currentTab != null) {
1756 removeTabFromContentView(currentTab);
1757 }
Patrick Scott8bbd69f2009-08-14 13:35:53 -04001758 // We must set the new tab as the current tab to reflect the old
1759 // animation behavior.
1760 mTabControl.setCurrentTab(tab);
Grace Klobaeb6eef42009-09-15 17:56:32 -07001761 attachTabToContentView(tab);
Leon Scroggins160a7e72009-08-14 18:28:01 -04001762 if (!urlData.isEmpty()) {
Patrick Scott9d53da02010-02-19 10:19:01 -05001763 loadUrlDataIn(tab, urlData);
Leon Scroggins1f005d32009-08-10 17:36:42 -04001764 }
1765 return tab;
1766 } else {
1767 // Get rid of the subwindow if it exists
1768 dismissSubWindow(currentTab);
1769 if (!urlData.isEmpty()) {
1770 // Load the given url.
Patrick Scott9d53da02010-02-19 10:19:01 -05001771 loadUrlDataIn(currentTab, urlData);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001772 }
Leon Scroggins58d56c62010-01-28 15:12:40 -05001773 return currentTab;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001774 }
1775 }
1776
Grace Kloba22ac16e2009-10-07 18:00:23 -07001777 private Tab openTab(String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001778 if (mSettings.openInBackground()) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001779 Tab t = mTabControl.createNewTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001780 if (t != null) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001781 WebView view = t.getWebView();
Leon Scroggins92472e82010-02-17 16:32:28 -05001782 loadUrl(view, url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001783 }
Grace Klobac9181842009-04-14 08:53:22 -07001784 return t;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001785 } else {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001786 return openTabAndShow(url, false, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001787 }
1788 }
1789
1790 private class Copy implements OnMenuItemClickListener {
1791 private CharSequence mText;
1792
1793 public boolean onMenuItemClick(MenuItem item) {
1794 copy(mText);
1795 return true;
1796 }
1797
1798 public Copy(CharSequence toCopy) {
1799 mText = toCopy;
1800 }
1801 }
1802
1803 private class Download implements OnMenuItemClickListener {
1804 private String mText;
1805
1806 public boolean onMenuItemClick(MenuItem item) {
1807 onDownloadStartNoStream(mText, null, null, null, -1);
1808 return true;
1809 }
1810
1811 public Download(String toDownload) {
1812 mText = toDownload;
1813 }
1814 }
1815
Ben Murdoch4f75ba22009-10-27 11:48:28 +00001816 private class SetAsWallpaper extends Thread implements
1817 OnMenuItemClickListener, DialogInterface.OnCancelListener {
1818 private URL mUrl;
1819 private ProgressDialog mWallpaperProgress;
1820 private boolean mCanceled = false;
1821
1822 public SetAsWallpaper(String url) {
1823 try {
1824 mUrl = new URL(url);
1825 } catch (MalformedURLException e) {
1826 mUrl = null;
1827 }
1828 }
1829
1830 public void onCancel(DialogInterface dialog) {
1831 mCanceled = true;
1832 }
1833
1834 public boolean onMenuItemClick(MenuItem item) {
1835 if (mUrl != null) {
1836 // The user may have tried to set a image with a large file size as their
1837 // background so it may take a few moments to perform the operation. Display
1838 // a progress spinner while it is working.
1839 mWallpaperProgress = new ProgressDialog(BrowserActivity.this);
1840 mWallpaperProgress.setIndeterminate(true);
1841 mWallpaperProgress.setMessage(getText(R.string.progress_dialog_setting_wallpaper));
1842 mWallpaperProgress.setCancelable(true);
1843 mWallpaperProgress.setOnCancelListener(this);
1844 mWallpaperProgress.show();
1845 start();
1846 }
1847 return true;
1848 }
1849
1850 public void run() {
1851 Drawable oldWallpaper = BrowserActivity.this.getWallpaper();
1852 try {
1853 // TODO: This will cause the resource to be downloaded again, when we
1854 // should in most cases be able to grab it from the cache. To fix this
1855 // we should query WebCore to see if we can access a cached version and
1856 // instead open an input stream on that. This pattern could also be used
1857 // in the download manager where the same problem exists.
1858 InputStream inputstream = mUrl.openStream();
1859 if (inputstream != null) {
1860 setWallpaper(inputstream);
1861 }
1862 } catch (IOException e) {
1863 Log.e(LOGTAG, "Unable to set new wallpaper");
1864 // Act as though the user canceled the operation so we try to
1865 // restore the old wallpaper.
1866 mCanceled = true;
1867 }
1868
1869 if (mCanceled) {
1870 // Restore the old wallpaper if the user cancelled whilst we were setting
1871 // the new wallpaper.
1872 int width = oldWallpaper.getIntrinsicWidth();
1873 int height = oldWallpaper.getIntrinsicHeight();
1874 Bitmap bm = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
1875 Canvas canvas = new Canvas(bm);
1876 oldWallpaper.setBounds(0, 0, width, height);
1877 oldWallpaper.draw(canvas);
1878 try {
1879 setWallpaper(bm);
1880 } catch (IOException e) {
1881 Log.e(LOGTAG, "Unable to restore old wallpaper.");
1882 }
1883 mCanceled = false;
1884 }
1885
1886 if (mWallpaperProgress.isShowing()) {
1887 mWallpaperProgress.dismiss();
1888 }
1889 }
1890 }
1891
The Android Open Source Project0c908882009-03-03 19:32:16 -08001892 private void copy(CharSequence text) {
1893 try {
1894 IClipboard clip = IClipboard.Stub.asInterface(ServiceManager.getService("clipboard"));
1895 if (clip != null) {
1896 clip.setClipboardText(text);
1897 }
1898 } catch (android.os.RemoteException e) {
1899 Log.e(LOGTAG, "Copy failed", e);
1900 }
1901 }
1902
1903 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08001904 * Resets the browser title-view to whatever it must be
1905 * (for example, if we had a loading error)
1906 * When we have a new page, we call resetTitle, when we
1907 * have to reset the titlebar to whatever it used to be
1908 * (for example, if the user chose to stop loading), we
1909 * call resetTitleAndRevertLockIcon.
1910 */
1911 /* package */ void resetTitleAndRevertLockIcon() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001912 mTabControl.getCurrentTab().revertLockIcon();
1913 updateLockIconToLatest();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001914 resetTitleIconAndProgress();
1915 }
1916
1917 /**
1918 * Reset the title, favicon, and progress.
1919 */
1920 private void resetTitleIconAndProgress() {
1921 WebView current = mTabControl.getCurrentWebView();
1922 if (current == null) {
1923 return;
1924 }
1925 resetTitleAndIcon(current);
1926 int progress = current.getProgress();
Grace Kloba22ac16e2009-10-07 18:00:23 -07001927 current.getWebChromeClient().onProgressChanged(current, progress);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001928 }
1929
1930 // Reset the title and the icon based on the given item.
1931 private void resetTitleAndIcon(WebView view) {
1932 WebHistoryItem item = view.copyBackForwardList().getCurrentItem();
1933 if (item != null) {
Leon Scroggins68579392009-09-15 15:31:54 -04001934 setUrlTitle(item.getUrl(), item.getTitle());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001935 setFavicon(item.getFavicon());
1936 } else {
Leon Scroggins68579392009-09-15 15:31:54 -04001937 setUrlTitle(null, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001938 setFavicon(null);
1939 }
1940 }
1941
1942 /**
1943 * Sets a title composed of the URL and the title string.
1944 * @param url The URL of the site being loaded.
1945 * @param title The title of the site being loaded.
1946 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07001947 void setUrlTitle(String url, String title) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001948 mUrl = url;
1949 mTitle = title;
1950
Leon Scroggins58d56c62010-01-28 15:12:40 -05001951 // If we are in voice search mode, the title has already been set.
1952 if (mTabControl.getCurrentTab().isInVoiceSearchMode()) return;
1953 mTitleBar.setDisplayTitle(url);
1954 mFakeTitleBar.setDisplayTitle(url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001955 }
1956
1957 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08001958 * @param url The URL to build a title version of the URL from.
1959 * @return The title version of the URL or null if fails.
1960 * The title version of the URL can be either the URL hostname,
1961 * or the hostname with an "https://" prefix (for secure URLs),
1962 * or an empty string if, for example, the URL in question is a
1963 * file:// URL with no hostname.
1964 */
Leon Scroggins32e14a62009-06-11 10:26:34 -04001965 /* package */ static String buildTitleUrl(String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001966 String titleUrl = null;
1967
1968 if (url != null) {
1969 try {
1970 // parse the url string
1971 URL urlObj = new URL(url);
1972 if (urlObj != null) {
1973 titleUrl = "";
1974
1975 String protocol = urlObj.getProtocol();
1976 String host = urlObj.getHost();
1977
1978 if (host != null && 0 < host.length()) {
1979 titleUrl = host;
1980 if (protocol != null) {
1981 // if a secure site, add an "https://" prefix!
1982 if (protocol.equalsIgnoreCase("https")) {
1983 titleUrl = protocol + "://" + host;
1984 }
1985 }
1986 }
1987 }
1988 } catch (MalformedURLException e) {}
1989 }
1990
1991 return titleUrl;
1992 }
1993
1994 // Set the favicon in the title bar.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001995 void setFavicon(Bitmap icon) {
Leon Scroggins68579392009-09-15 15:31:54 -04001996 mTitleBar.setFavicon(icon);
Leon Scrogginsfe87bd32009-10-06 10:10:00 -04001997 mFakeTitleBar.setFavicon(icon);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001998 }
1999
2000 /**
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002001 * Close the tab, remove its associated title bar, and adjust mTabControl's
2002 * current tab to a valid value.
Leon Scroggins1f005d32009-08-10 17:36:42 -04002003 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07002004 /* package */ void closeTab(Tab t) {
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002005 int currentIndex = mTabControl.getCurrentIndex();
2006 int removeIndex = mTabControl.getTabIndex(t);
Leon Scroggins1f005d32009-08-10 17:36:42 -04002007 mTabControl.removeTab(t);
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002008 if (currentIndex >= removeIndex && currentIndex != 0) {
2009 currentIndex--;
2010 }
2011 mTabControl.setCurrentTab(mTabControl.getTab(currentIndex));
Andrei Popescua5bf1de2009-09-23 16:39:23 +01002012 resetTitleIconAndProgress();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002013 }
2014
Leon Scrogginsdcc5eeb2010-02-23 17:26:37 -05002015 /* package */ void goBackOnePageOrQuit() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002016 Tab current = mTabControl.getCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002017 if (current == null) {
2018 /*
2019 * Instead of finishing the activity, simply push this to the back
2020 * of the stack and let ActivityManager to choose the foreground
2021 * activity. As BrowserActivity is singleTask, it will be always the
2022 * root of the task. So we can use either true or false for
2023 * moveTaskToBack().
2024 */
2025 moveTaskToBack(true);
Grace Kloba00d85e72009-09-23 18:50:05 -07002026 return;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002027 }
2028 WebView w = current.getWebView();
2029 if (w.canGoBack()) {
2030 w.goBack();
2031 } else {
2032 // Check to see if we are closing a window that was created by
2033 // another window. If so, we switch back to that window.
Grace Kloba22ac16e2009-10-07 18:00:23 -07002034 Tab parent = current.getParentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002035 if (parent != null) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04002036 switchToTab(mTabControl.getTabIndex(parent));
2037 // Now we close the other tab
2038 closeTab(current);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002039 } else {
2040 if (current.closeOnExit()) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002041 // force the tab's inLoad() to be false as we are going to
2042 // either finish the activity or remove the tab. This will
2043 // ensure pauseWebViewTimers() taking action.
2044 mTabControl.getCurrentTab().clearInLoad();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002045 if (mTabControl.getTabCount() == 1) {
2046 finish();
2047 return;
2048 }
Mike Reed7bfa63b2009-05-28 11:08:32 -04002049 // call pauseWebViewTimers() now, we won't be able to call
2050 // it in onPause() as the WebView won't be valid.
Grace Klobaec1b5ad2009-08-18 08:42:32 -07002051 // Temporarily change mActivityInPause to be true as
2052 // pauseWebViewTimers() will do nothing if mActivityInPause
2053 // is false.
Grace Kloba918e1d72009-08-13 14:55:06 -07002054 boolean savedState = mActivityInPause;
2055 if (savedState) {
Grace Klobaec1b5ad2009-08-18 08:42:32 -07002056 Log.e(LOGTAG, "BrowserActivity is already paused "
2057 + "while handing goBackOnePageOrQuit.");
Grace Kloba918e1d72009-08-13 14:55:06 -07002058 }
2059 mActivityInPause = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -04002060 pauseWebViewTimers();
Grace Kloba918e1d72009-08-13 14:55:06 -07002061 mActivityInPause = savedState;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002062 removeTabFromContentView(current);
2063 mTabControl.removeTab(current);
2064 }
2065 /*
2066 * Instead of finishing the activity, simply push this to the back
2067 * of the stack and let ActivityManager to choose the foreground
2068 * activity. As BrowserActivity is singleTask, it will be always the
2069 * root of the task. So we can use either true or false for
2070 * moveTaskToBack().
2071 */
2072 moveTaskToBack(true);
2073 }
2074 }
2075 }
2076
Grace Kloba22ac16e2009-10-07 18:00:23 -07002077 boolean isMenuDown() {
2078 return mMenuIsDown;
2079 }
2080
Grace Kloba5942df02009-09-18 11:48:29 -07002081 @Override
2082 public boolean onKeyDown(int keyCode, KeyEvent event) {
Leon Scrogginsf65b50d2009-12-08 10:44:28 -05002083 // Even if MENU is already held down, we need to call to super to open
2084 // the IME on long press.
2085 if (KeyEvent.KEYCODE_MENU == keyCode) {
2086 mMenuIsDown = true;
2087 return super.onKeyDown(keyCode, event);
2088 }
Grace Kloba5942df02009-09-18 11:48:29 -07002089 // The default key mode is DEFAULT_KEYS_SEARCH_LOCAL. As the MENU is
2090 // still down, we don't want to trigger the search. Pretend to consume
2091 // the key and do nothing.
2092 if (mMenuIsDown) return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002093
Grace Kloba5942df02009-09-18 11:48:29 -07002094 switch(keyCode) {
Grace Kloba5942df02009-09-18 11:48:29 -07002095 case KeyEvent.KEYCODE_SPACE:
Grace Klobada0fe552009-09-22 18:17:24 -07002096 // WebView/WebTextView handle the keys in the KeyDown. As
2097 // the Activity's shortcut keys are only handled when WebView
2098 // doesn't, have to do it in onKeyDown instead of onKeyUp.
2099 if (event.isShiftPressed()) {
2100 getTopWindow().pageUp(false);
2101 } else {
2102 getTopWindow().pageDown(false);
2103 }
Grace Kloba5942df02009-09-18 11:48:29 -07002104 return true;
2105 case KeyEvent.KEYCODE_BACK:
2106 if (event.getRepeatCount() == 0) {
2107 event.startTracking();
2108 return true;
2109 } else if (mCustomView == null && mActiveTabsPage == null
2110 && event.isLongPress()) {
2111 bookmarksOrHistoryPicker(true);
2112 return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002113 }
Grace Kloba5942df02009-09-18 11:48:29 -07002114 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002115 }
Grace Kloba5942df02009-09-18 11:48:29 -07002116 return super.onKeyDown(keyCode, event);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002117 }
2118
Grace Kloba5942df02009-09-18 11:48:29 -07002119 @Override
2120 public boolean onKeyUp(int keyCode, KeyEvent event) {
2121 switch(keyCode) {
2122 case KeyEvent.KEYCODE_MENU:
2123 mMenuIsDown = false;
2124 break;
Grace Kloba5942df02009-09-18 11:48:29 -07002125 case KeyEvent.KEYCODE_BACK:
2126 if (event.isTracking() && !event.isCanceled()) {
2127 if (mCustomView != null) {
2128 // if a custom view is showing, hide it
Grace Kloba22ac16e2009-10-07 18:00:23 -07002129 mTabControl.getCurrentWebView().getWebChromeClient()
2130 .onHideCustomView();
Grace Kloba5942df02009-09-18 11:48:29 -07002131 } else if (mActiveTabsPage != null) {
2132 // if tab page is showing, hide it
2133 removeActiveTabPage(true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002134 } else {
Grace Kloba5942df02009-09-18 11:48:29 -07002135 WebView subwindow = mTabControl.getCurrentSubWindow();
2136 if (subwindow != null) {
2137 if (subwindow.canGoBack()) {
2138 subwindow.goBack();
2139 } else {
2140 dismissSubWindow(mTabControl.getCurrentTab());
2141 }
2142 } else {
2143 goBackOnePageOrQuit();
2144 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002145 }
Grace Kloba5942df02009-09-18 11:48:29 -07002146 return true;
2147 }
2148 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002149 }
Grace Kloba5942df02009-09-18 11:48:29 -07002150 return super.onKeyUp(keyCode, event);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002151 }
2152
Leon Scroggins68579392009-09-15 15:31:54 -04002153 /* package */ void stopLoading() {
Ben Murdochb7cc8b42009-09-28 10:59:09 +01002154 mDidStopLoad = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002155 resetTitleAndRevertLockIcon();
2156 WebView w = getTopWindow();
2157 w.stopLoading();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002158 // FIXME: before refactor, it is using mWebViewClient. So I keep the
2159 // same logic here. But for subwindow case, should we call into the main
2160 // WebView's onPageFinished as we never call its onPageStarted and if
2161 // the page finishes itself, we don't call onPageFinished.
2162 mTabControl.getCurrentWebView().getWebViewClient().onPageFinished(w,
2163 w.getUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08002164
2165 cancelStopToast();
2166 mStopToast = Toast
2167 .makeText(this, R.string.stopping, Toast.LENGTH_SHORT);
2168 mStopToast.show();
2169 }
2170
Grace Kloba22ac16e2009-10-07 18:00:23 -07002171 boolean didUserStopLoading() {
2172 return mDidStopLoad;
2173 }
2174
The Android Open Source Project0c908882009-03-03 19:32:16 -08002175 private void cancelStopToast() {
2176 if (mStopToast != null) {
2177 mStopToast.cancel();
2178 mStopToast = null;
2179 }
2180 }
2181
Grace Kloba22ac16e2009-10-07 18:00:23 -07002182 // called by a UI or non-UI thread to post the message
2183 public void postMessage(int what, int arg1, int arg2, Object obj,
2184 long delayMillis) {
2185 mHandler.sendMessageDelayed(mHandler.obtainMessage(what, arg1, arg2,
2186 obj), delayMillis);
2187 }
2188
2189 // called by a UI or non-UI thread to remove the message
2190 void removeMessages(int what, Object object) {
2191 mHandler.removeMessages(what, object);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002192 }
2193
2194 // public message ids
2195 public final static int LOAD_URL = 1001;
2196 public final static int STOP_LOAD = 1002;
2197
2198 // Message Ids
2199 private static final int FOCUS_NODE_HREF = 102;
Grace Kloba92c18a52009-07-31 23:48:32 -07002200 private static final int RELEASE_WAKELOCK = 107;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002201
Grace Kloba22ac16e2009-10-07 18:00:23 -07002202 static final int UPDATE_BOOKMARK_THUMBNAIL = 108;
Ben Murdoch2694e232009-09-29 09:41:11 +01002203
The Android Open Source Project0c908882009-03-03 19:32:16 -08002204 // Private handler for handling javascript and saving passwords
2205 private Handler mHandler = new Handler() {
2206
2207 public void handleMessage(Message msg) {
2208 switch (msg.what) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002209 case FOCUS_NODE_HREF:
Ben Murdoch2694e232009-09-29 09:41:11 +01002210 {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002211 String url = (String) msg.getData().get("url");
Ben Murdoch90d088c2009-11-17 18:14:04 +00002212 String title = (String) msg.getData().get("title");
The Android Open Source Project0c908882009-03-03 19:32:16 -08002213 if (url == null || url.length() == 0) {
2214 break;
2215 }
2216 HashMap focusNodeMap = (HashMap) msg.obj;
2217 WebView view = (WebView) focusNodeMap.get("webview");
2218 // Only apply the action if the top window did not change.
2219 if (getTopWindow() != view) {
2220 break;
2221 }
2222 switch (msg.arg1) {
2223 case R.id.open_context_menu_id:
2224 case R.id.view_image_context_menu_id:
Leon Scroggins92472e82010-02-17 16:32:28 -05002225 loadUrlFromContext(getTopWindow(), url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002226 break;
2227 case R.id.open_newtab_context_menu_id:
Grace Kloba22ac16e2009-10-07 18:00:23 -07002228 final Tab parent = mTabControl.getCurrentTab();
2229 final Tab newTab = openTab(url);
Grace Klobac9181842009-04-14 08:53:22 -07002230 if (newTab != parent) {
2231 parent.addChildTab(newTab);
2232 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002233 break;
2234 case R.id.bookmark_context_menu_id:
2235 Intent intent = new Intent(BrowserActivity.this,
2236 AddBookmarkPage.class);
2237 intent.putExtra("url", url);
Ben Murdoch90d088c2009-11-17 18:14:04 +00002238 intent.putExtra("title", title);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002239 startActivity(intent);
2240 break;
2241 case R.id.share_link_context_menu_id:
Leon Scroggins96afcb12009-12-10 12:35:56 -05002242 // See if this site has been visited before
2243 StringBuilder sb = new StringBuilder(
2244 Browser.BookmarkColumns.URL + " = ");
2245 DatabaseUtils.appendEscapedSQLString(sb, url);
2246 Cursor c = mResolver.query(Browser.BOOKMARKS_URI,
2247 Browser.HISTORY_PROJECTION,
2248 sb.toString(),
2249 null,
2250 null);
2251 if (c.moveToFirst()) {
2252 // The site has been visited before, so grab the
2253 // info from the database.
2254 Bitmap favicon = null;
2255 Bitmap thumbnail = null;
2256 String linkTitle = c.getString(Browser.
2257 HISTORY_PROJECTION_TITLE_INDEX);
2258 byte[] data = c.getBlob(Browser.
2259 HISTORY_PROJECTION_FAVICON_INDEX);
2260 if (data != null) {
2261 favicon = BitmapFactory.decodeByteArray(
2262 data, 0, data.length);
2263 }
2264 data = c.getBlob(Browser.
2265 HISTORY_PROJECTION_THUMBNAIL_INDEX);
2266 if (data != null) {
2267 thumbnail = BitmapFactory.decodeByteArray(
2268 data, 0, data.length);
2269 }
2270 sharePage(BrowserActivity.this,
2271 linkTitle, url, favicon, thumbnail);
2272 } else {
2273 Browser.sendString(BrowserActivity.this, url,
2274 getString(
2275 R.string.choosertitle_sharevia));
2276 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002277 break;
2278 case R.id.copy_link_context_menu_id:
2279 copy(url);
2280 break;
2281 case R.id.save_link_context_menu_id:
2282 case R.id.download_context_menu_id:
2283 onDownloadStartNoStream(url, null, null, null, -1);
2284 break;
2285 }
2286 break;
Ben Murdoch2694e232009-09-29 09:41:11 +01002287 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002288
2289 case LOAD_URL:
Leon Scroggins92472e82010-02-17 16:32:28 -05002290 loadUrlFromContext(getTopWindow(), (String) msg.obj);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002291 break;
2292
2293 case STOP_LOAD:
2294 stopLoading();
2295 break;
2296
The Android Open Source Project0c908882009-03-03 19:32:16 -08002297 case RELEASE_WAKELOCK:
2298 if (mWakeLock.isHeld()) {
2299 mWakeLock.release();
Grace Kloba5d0e02e2009-10-05 15:15:36 -07002300 // if we reach here, Browser should be still in the
2301 // background loading after WAKELOCK_TIMEOUT (5-min).
2302 // To avoid burning the battery, stop loading.
2303 mTabControl.stopAllLoading();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002304 }
2305 break;
Ben Murdoch2694e232009-09-29 09:41:11 +01002306
2307 case UPDATE_BOOKMARK_THUMBNAIL:
2308 WebView view = (WebView) msg.obj;
2309 if (view != null) {
2310 updateScreenshot(view);
2311 }
2312 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002313 }
2314 }
2315 };
2316
Leon Scroggins96afcb12009-12-10 12:35:56 -05002317 /**
2318 * Share a page, providing the title, url, favicon, and a screenshot. Uses
2319 * an {@link Intent} to launch the Activity chooser.
2320 * @param c Context used to launch a new Activity.
2321 * @param title Title of the page. Stored in the Intent with
Paul Westbrook03e6d392010-02-12 10:33:29 -08002322 * {@link Intent#EXTRA_SUBJECT}
Leon Scroggins96afcb12009-12-10 12:35:56 -05002323 * @param url URL of the page. Stored in the Intent with
2324 * {@link Intent#EXTRA_TEXT}
2325 * @param favicon Bitmap of the favicon for the page. Stored in the Intent
2326 * with {@link Browser#EXTRA_SHARE_FAVICON}
2327 * @param screenshot Bitmap of a screenshot of the page. Stored in the
2328 * Intent with {@link Browser#EXTRA_SHARE_SCREENSHOT}
2329 */
2330 public static final void sharePage(Context c, String title, String url,
2331 Bitmap favicon, Bitmap screenshot) {
2332 Intent send = new Intent(Intent.ACTION_SEND);
2333 send.setType("text/plain");
2334 send.putExtra(Intent.EXTRA_TEXT, url);
Paul Westbrook03e6d392010-02-12 10:33:29 -08002335 send.putExtra(Intent.EXTRA_SUBJECT, title);
Leon Scroggins96afcb12009-12-10 12:35:56 -05002336 send.putExtra(Browser.EXTRA_SHARE_FAVICON, favicon);
2337 send.putExtra(Browser.EXTRA_SHARE_SCREENSHOT, screenshot);
2338 try {
2339 c.startActivity(Intent.createChooser(send, c.getString(
2340 R.string.choosertitle_sharevia)));
2341 } catch(android.content.ActivityNotFoundException ex) {
2342 // if no app handles it, do nothing
2343 }
2344 }
2345
Leon Scroggins89c6d362009-07-15 16:54:37 -04002346 private void updateScreenshot(WebView view) {
2347 // If this is a bookmarked site, add a screenshot to the database.
2348 // FIXME: When should we update? Every time?
2349 // FIXME: Would like to make sure there is actually something to
2350 // draw, but the API for that (WebViewCore.pictureReady()) is not
2351 // currently accessible here.
Ben Murdochaac7aa62009-09-17 16:57:40 +01002352
Patrick Scott3918d442009-08-04 13:22:29 -04002353 ContentResolver cr = getContentResolver();
2354 final Cursor c = BrowserBookmarksAdapter.queryBookmarksForUrl(
Ben Murdochaac7aa62009-09-17 16:57:40 +01002355 cr, view.getOriginalUrl(), view.getUrl(), true);
Patrick Scott3918d442009-08-04 13:22:29 -04002356 if (c != null) {
Leon Scroggins89c6d362009-07-15 16:54:37 -04002357 boolean succeed = c.moveToFirst();
2358 ContentValues values = null;
2359 while (succeed) {
2360 if (values == null) {
2361 final ByteArrayOutputStream os
2362 = new ByteArrayOutputStream();
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002363 Bitmap bm = createScreenshot(view);
Leon Scroggins45800572009-09-29 16:38:47 -04002364 if (bm == null) {
2365 c.close();
2366 return;
2367 }
Leon Scroggins89c6d362009-07-15 16:54:37 -04002368 bm.compress(Bitmap.CompressFormat.PNG, 100, os);
2369 values = new ContentValues();
2370 values.put(Browser.BookmarkColumns.THUMBNAIL,
2371 os.toByteArray());
2372 }
2373 cr.update(ContentUris.withAppendedId(Browser.BOOKMARKS_URI,
2374 c.getInt(0)), values, null, null);
2375 succeed = c.moveToNext();
2376 }
2377 c.close();
2378 }
2379 }
2380
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002381 /**
Leon Scrogginsf8551612009-09-24 16:06:02 -04002382 * Values for the size of the thumbnail created when taking a screenshot.
2383 * Lazily initialized. Instead of using these directly, use
2384 * getDesiredThumbnailWidth() or getDesiredThumbnailHeight().
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002385 */
Leon Scrogginsf8551612009-09-24 16:06:02 -04002386 private static int THUMBNAIL_WIDTH = 0;
2387 private static int THUMBNAIL_HEIGHT = 0;
2388
2389 /**
2390 * Return the desired width for thumbnail screenshots, which are stored in
2391 * the database, and used on the bookmarks screen.
2392 * @param context Context for finding out the density of the screen.
2393 * @return int desired width for thumbnail screenshot.
2394 */
2395 /* package */ static int getDesiredThumbnailWidth(Context context) {
2396 if (THUMBNAIL_WIDTH == 0) {
2397 float density = context.getResources().getDisplayMetrics().density;
2398 THUMBNAIL_WIDTH = (int) (90 * density);
2399 THUMBNAIL_HEIGHT = (int) (80 * density);
2400 }
2401 return THUMBNAIL_WIDTH;
2402 }
2403
2404 /**
2405 * Return the desired height for thumbnail screenshots, which are stored in
2406 * the database, and used on the bookmarks screen.
2407 * @param context Context for finding out the density of the screen.
2408 * @return int desired height for thumbnail screenshot.
2409 */
2410 /* package */ static int getDesiredThumbnailHeight(Context context) {
2411 // To ensure that they are both initialized.
2412 getDesiredThumbnailWidth(context);
2413 return THUMBNAIL_HEIGHT;
2414 }
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002415
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002416 private Bitmap createScreenshot(WebView view) {
2417 Picture thumbnail = view.capturePicture();
Leon Scroggins45800572009-09-29 16:38:47 -04002418 if (thumbnail == null) {
2419 return null;
2420 }
Leon Scrogginsf8551612009-09-24 16:06:02 -04002421 Bitmap bm = Bitmap.createBitmap(getDesiredThumbnailWidth(this),
2422 getDesiredThumbnailHeight(this), Bitmap.Config.ARGB_4444);
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002423 Canvas canvas = new Canvas(bm);
2424 // May need to tweak these values to determine what is the
2425 // best scale factor
Ben Murdoch2694e232009-09-29 09:41:11 +01002426 int thumbnailWidth = thumbnail.getWidth();
Ben Murdochae59c3f2009-10-20 18:30:28 +01002427 int thumbnailHeight = thumbnail.getHeight();
2428 float scaleFactorX = 1.0f;
2429 float scaleFactorY = 1.0f;
Ben Murdoch2694e232009-09-29 09:41:11 +01002430 if (thumbnailWidth > 0) {
Ben Murdochae59c3f2009-10-20 18:30:28 +01002431 scaleFactorX = (float) getDesiredThumbnailWidth(this) /
Ben Murdoch2694e232009-09-29 09:41:11 +01002432 (float)thumbnailWidth;
Ben Murdochae59c3f2009-10-20 18:30:28 +01002433 } else {
2434 return null;
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002435 }
Ben Murdochae59c3f2009-10-20 18:30:28 +01002436
2437 if (view.getWidth() > view.getHeight() &&
2438 thumbnailHeight < view.getHeight() && thumbnailHeight > 0) {
2439 // If the device is in landscape and the page is shorter
2440 // than the height of the view, stretch the thumbnail to fill the
2441 // space.
2442 scaleFactorY = (float) getDesiredThumbnailHeight(this) /
2443 (float)thumbnailHeight;
2444 } else {
2445 // In the portrait case, this looks nice.
2446 scaleFactorY = scaleFactorX;
2447 }
2448
2449 canvas.scale(scaleFactorX, scaleFactorY);
2450
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002451 thumbnail.draw(canvas);
2452 return bm;
2453 }
2454
The Android Open Source Project0c908882009-03-03 19:32:16 -08002455 // -------------------------------------------------------------------------
Grace Kloba22ac16e2009-10-07 18:00:23 -07002456 // Helper function for WebViewClient.
The Android Open Source Project0c908882009-03-03 19:32:16 -08002457 //-------------------------------------------------------------------------
2458
2459 // Use in overrideUrlLoading
2460 /* package */ final static String SCHEME_WTAI = "wtai://wp/";
2461 /* package */ final static String SCHEME_WTAI_MC = "wtai://wp/mc;";
2462 /* package */ final static String SCHEME_WTAI_SD = "wtai://wp/sd;";
2463 /* package */ final static String SCHEME_WTAI_AP = "wtai://wp/ap;";
2464
Leon Scroggins92472e82010-02-17 16:32:28 -05002465 // Keep this initial progress in sync with initialProgressValue (* 100)
2466 // in ProgressTracker.cpp
2467 private final static int INITIAL_PROGRESS = 10;
2468
Grace Kloba22ac16e2009-10-07 18:00:23 -07002469 void onPageStarted(WebView view, String url, Bitmap favicon) {
2470 // when BrowserActivity just starts, onPageStarted may be called before
2471 // onResume as it is triggered from onCreate. Call resumeWebViewTimers
2472 // to start the timer. As we won't switch tabs while an activity is in
2473 // pause state, we can ensure calling resume and pause in pair.
2474 if (mActivityInPause) resumeWebViewTimers();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002475
Grace Kloba22ac16e2009-10-07 18:00:23 -07002476 resetLockIcon(url);
2477 setUrlTitle(url, null);
2478 setFavicon(favicon);
Leon Scroggins8cf8f682009-11-04 11:13:50 -08002479 // Show some progress so that the user knows the page is beginning to
2480 // load
Leon Scroggins92472e82010-02-17 16:32:28 -05002481 onProgressChanged(view, INITIAL_PROGRESS);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002482 mDidStopLoad = false;
Grace Kloba22ac16e2009-10-07 18:00:23 -07002483 if (!mIsNetworkUp) createAndShowNetworkDialog();
Patrick Scott15525d42009-09-21 13:39:37 -04002484
Grace Kloba22ac16e2009-10-07 18:00:23 -07002485 if (mSettings.isTracing()) {
2486 String host;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002487 try {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002488 WebAddress uri = new WebAddress(url);
2489 host = uri.mHost;
2490 } catch (android.net.ParseException ex) {
2491 host = "browser";
The Android Open Source Project0c908882009-03-03 19:32:16 -08002492 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002493 host = host.replace('.', '_');
2494 host += ".trace";
2495 mInTrace = true;
2496 Debug.startMethodTracing(host, 20 * 1024 * 1024);
2497 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002498
Grace Kloba22ac16e2009-10-07 18:00:23 -07002499 // Performance probe
2500 if (false) {
2501 mStart = SystemClock.uptimeMillis();
2502 mProcessStart = Process.getElapsedCpuTime();
2503 long[] sysCpu = new long[7];
2504 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2505 sysCpu, null)) {
2506 mUserStart = sysCpu[0] + sysCpu[1];
2507 mSystemStart = sysCpu[2];
2508 mIdleStart = sysCpu[3];
2509 mIrqStart = sysCpu[4] + sysCpu[5] + sysCpu[6];
2510 }
2511 mUiStart = SystemClock.currentThreadTimeMillis();
2512 }
2513 }
2514
2515 void onPageFinished(WebView view, String url) {
2516 // Reset the title and icon in case we stopped a provisional load.
2517 resetTitleAndIcon(view);
2518 // Update the lock icon image only once we are done loading
2519 updateLockIconToLatest();
2520 // pause the WebView timer and release the wake lock if it is finished
2521 // while BrowserActivity is in pause state.
2522 if (mActivityInPause && pauseWebViewTimers()) {
2523 if (mWakeLock.isHeld()) {
2524 mHandler.removeMessages(RELEASE_WAKELOCK);
2525 mWakeLock.release();
2526 }
2527 }
2528
2529 // Performance probe
2530 if (false) {
2531 long[] sysCpu = new long[7];
2532 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2533 sysCpu, null)) {
2534 String uiInfo = "UI thread used "
2535 + (SystemClock.currentThreadTimeMillis() - mUiStart)
2536 + " ms";
2537 if (LOGD_ENABLED) {
2538 Log.d(LOGTAG, uiInfo);
2539 }
2540 //The string that gets written to the log
2541 String performanceString = "It took total "
2542 + (SystemClock.uptimeMillis() - mStart)
2543 + " ms clock time to load the page."
2544 + "\nbrowser process used "
2545 + (Process.getElapsedCpuTime() - mProcessStart)
2546 + " ms, user processes used "
2547 + (sysCpu[0] + sysCpu[1] - mUserStart) * 10
2548 + " ms, kernel used "
2549 + (sysCpu[2] - mSystemStart) * 10
2550 + " ms, idle took " + (sysCpu[3] - mIdleStart) * 10
2551 + " ms and irq took "
2552 + (sysCpu[4] + sysCpu[5] + sysCpu[6] - mIrqStart)
2553 * 10 + " ms, " + uiInfo;
2554 if (LOGD_ENABLED) {
2555 Log.d(LOGTAG, performanceString + "\nWebpage: " + url);
2556 }
2557 if (url != null) {
2558 // strip the url to maintain consistency
2559 String newUrl = new String(url);
2560 if (newUrl.startsWith("http://www.")) {
2561 newUrl = newUrl.substring(11);
2562 } else if (newUrl.startsWith("http://")) {
2563 newUrl = newUrl.substring(7);
2564 } else if (newUrl.startsWith("https://www.")) {
2565 newUrl = newUrl.substring(12);
2566 } else if (newUrl.startsWith("https://")) {
2567 newUrl = newUrl.substring(8);
2568 }
2569 if (LOGD_ENABLED) {
2570 Log.d(LOGTAG, newUrl + " loaded");
2571 }
Grace Kloba5b078b52009-06-24 20:23:41 -07002572 }
2573 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002574 }
Grace Kloba5b078b52009-06-24 20:23:41 -07002575
Grace Kloba22ac16e2009-10-07 18:00:23 -07002576 if (mInTrace) {
2577 mInTrace = false;
2578 Debug.stopMethodTracing();
2579 }
2580 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002581
Grace Kloba22ac16e2009-10-07 18:00:23 -07002582 boolean shouldOverrideUrlLoading(WebView view, String url) {
2583 if (url.startsWith(SCHEME_WTAI)) {
2584 // wtai://wp/mc;number
2585 // number=string(phone-number)
2586 if (url.startsWith(SCHEME_WTAI_MC)) {
2587 Intent intent = new Intent(Intent.ACTION_VIEW,
2588 Uri.parse(WebView.SCHEME_TEL +
2589 url.substring(SCHEME_WTAI_MC.length())));
2590 startActivity(intent);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002591 return true;
2592 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002593 // wtai://wp/sd;dtmf
2594 // dtmf=string(dialstring)
2595 if (url.startsWith(SCHEME_WTAI_SD)) {
2596 // TODO: only send when there is active voice connection
2597 return false;
2598 }
2599 // wtai://wp/ap;number;name
2600 // number=string(phone-number)
2601 // name=string
2602 if (url.startsWith(SCHEME_WTAI_AP)) {
2603 // TODO
2604 return false;
2605 }
2606 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002607
Grace Kloba22ac16e2009-10-07 18:00:23 -07002608 // The "about:" schemes are internal to the browser; don't want these to
2609 // be dispatched to other apps.
2610 if (url.startsWith("about:")) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002611 return false;
2612 }
2613
Grace Kloba22ac16e2009-10-07 18:00:23 -07002614 Intent intent;
2615 // perform generic parsing of the URI to turn it into an Intent.
2616 try {
2617 intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME);
2618 } catch (URISyntaxException ex) {
2619 Log.w("Browser", "Bad URI " + url + ": " + ex.getMessage());
2620 return false;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002621 }
2622
Grace Kloba22ac16e2009-10-07 18:00:23 -07002623 // check whether the intent can be resolved. If not, we will see
2624 // whether we can download it from the Market.
2625 if (getPackageManager().resolveActivity(intent, 0) == null) {
2626 String packagename = intent.getPackage();
2627 if (packagename != null) {
2628 intent = new Intent(Intent.ACTION_VIEW, Uri
2629 .parse("market://search?q=pname:" + packagename));
2630 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2631 startActivity(intent);
2632 return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002633 } else {
2634 return false;
2635 }
2636 }
2637
Grace Kloba22ac16e2009-10-07 18:00:23 -07002638 // sanitize the Intent, ensuring web pages can not bypass browser
2639 // security (only access to BROWSABLE activities).
2640 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2641 intent.setComponent(null);
2642 try {
2643 if (startActivityIfNeeded(intent, -1)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002644 return true;
2645 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002646 } catch (ActivityNotFoundException ex) {
2647 // ignore the error. If no application can handle the URL,
2648 // eg about:blank, assume the browser can handle it.
2649 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002650
Grace Kloba22ac16e2009-10-07 18:00:23 -07002651 if (mMenuIsDown) {
2652 openTab(url);
2653 closeOptionsMenu();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002654 return true;
2655 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002656 return false;
2657 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002658
Grace Kloba22ac16e2009-10-07 18:00:23 -07002659 // -------------------------------------------------------------------------
2660 // Helper function for WebChromeClient
2661 // -------------------------------------------------------------------------
The Android Open Source Project0c908882009-03-03 19:32:16 -08002662
Grace Kloba22ac16e2009-10-07 18:00:23 -07002663 void onProgressChanged(WebView view, int newProgress) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002664 mFakeTitleBar.setProgress(newProgress);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002665
Grace Kloba22ac16e2009-10-07 18:00:23 -07002666 if (newProgress == 100) {
2667 // onProgressChanged() may continue to be called after the main
2668 // frame has finished loading, as any remaining sub frames continue
2669 // to load. We'll only get called once though with newProgress as
2670 // 100 when everything is loaded. (onPageFinished is called once
2671 // when the main frame completes loading regardless of the state of
2672 // any sub frames so calls to onProgressChanges may continue after
2673 // onPageFinished has executed)
2674 if (mInLoad) {
2675 mInLoad = false;
Leon Scrogginsa27ff192009-09-14 12:58:04 -04002676 updateInLoadMenuItems();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002677 // If the options menu is open, leave the title bar
2678 if (!mOptionsMenuOpen || !mIconView) {
2679 hideFakeTitleBar();
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07002680 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002681 }
Leon Scrogginsaa37e7f2010-03-05 11:51:20 -05002682 } else {
2683 if (!mInLoad) {
2684 // onPageFinished may have already been called but a subframe is
2685 // still loading and updating the progress. Reset mInLoad and
2686 // update the menu items.
2687 mInLoad = true;
2688 updateInLoadMenuItems();
2689 }
2690 // When the page first begins to load, the Activity may still be
2691 // paused, in which case showFakeTitleBar will do nothing. Call
2692 // again as the page continues to load so that it will be shown.
2693 // (Calling it will the fake title bar is already showing will also
2694 // do nothing.
Grace Kloba22ac16e2009-10-07 18:00:23 -07002695 if (!mOptionsMenuOpen || mIconView) {
2696 // This page has begun to load, so show the title bar
2697 showFakeTitleBar();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002698 }
2699 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002700 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002701
Grace Kloba22ac16e2009-10-07 18:00:23 -07002702 void onShowCustomView(View view, WebChromeClient.CustomViewCallback callback) {
Derek Sollenberger8ff57db2009-12-08 15:39:55 -05002703 // if a view already exists then immediately terminate the new one
2704 if (mCustomView != null) {
2705 callback.onCustomViewHidden();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002706 return;
Derek Sollenberger8ff57db2009-12-08 15:39:55 -05002707 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002708
2709 // Add the custom view to its container.
2710 mCustomViewContainer.addView(view, COVER_SCREEN_GRAVITY_CENTER);
2711 mCustomView = view;
2712 mCustomViewCallback = callback;
2713 // Save the menu state and set it to empty while the custom
2714 // view is showing.
2715 mOldMenuState = mMenuState;
2716 mMenuState = EMPTY_MENU;
2717 // Hide the content view.
2718 mContentView.setVisibility(View.GONE);
2719 // Finally show the custom view container.
Andrei Popescu163ab742009-10-20 17:58:23 +01002720 setStatusBarVisibility(false);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002721 mCustomViewContainer.setVisibility(View.VISIBLE);
2722 mCustomViewContainer.bringToFront();
2723 }
2724
2725 void onHideCustomView() {
2726 if (mCustomView == null)
2727 return;
2728
2729 // Hide the custom view.
2730 mCustomView.setVisibility(View.GONE);
2731 // Remove the custom view from its container.
2732 mCustomViewContainer.removeView(mCustomView);
2733 mCustomView = null;
2734 // Reset the old menu state.
2735 mMenuState = mOldMenuState;
2736 mOldMenuState = EMPTY_MENU;
2737 mCustomViewContainer.setVisibility(View.GONE);
2738 mCustomViewCallback.onCustomViewHidden();
2739 // Show the content view.
Andrei Popescu163ab742009-10-20 17:58:23 +01002740 setStatusBarVisibility(true);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002741 mContentView.setVisibility(View.VISIBLE);
2742 }
2743
2744 Bitmap getDefaultVideoPoster() {
2745 if (mDefaultVideoPoster == null) {
2746 mDefaultVideoPoster = BitmapFactory.decodeResource(
2747 getResources(), R.drawable.default_video_poster);
Patrick Scott3918d442009-08-04 13:22:29 -04002748 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002749 return mDefaultVideoPoster;
2750 }
Patrick Scott3918d442009-08-04 13:22:29 -04002751
Grace Kloba22ac16e2009-10-07 18:00:23 -07002752 View getVideoLoadingProgressView() {
2753 if (mVideoProgressView == null) {
2754 LayoutInflater inflater = LayoutInflater.from(BrowserActivity.this);
2755 mVideoProgressView = inflater.inflate(
2756 R.layout.video_loading_progress, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002757 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002758 return mVideoProgressView;
2759 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002760
Leon Scroggins8d5fa432009-10-02 15:55:59 -04002761 /*
2762 * The Object used to inform the WebView of the file to upload.
2763 */
2764 private ValueCallback<Uri> mUploadMessage;
2765
Grace Kloba22ac16e2009-10-07 18:00:23 -07002766 void openFileChooser(ValueCallback<Uri> uploadMsg) {
2767 if (mUploadMessage != null) return;
2768 mUploadMessage = uploadMsg;
2769 Intent i = new Intent(Intent.ACTION_GET_CONTENT);
2770 i.addCategory(Intent.CATEGORY_OPENABLE);
2771 i.setType("*/*");
2772 BrowserActivity.this.startActivityForResult(Intent.createChooser(i,
2773 getString(R.string.choose_upload)), FILE_SELECTED);
2774 }
2775
2776 // -------------------------------------------------------------------------
2777 // Implement functions for DownloadListener
2778 // -------------------------------------------------------------------------
2779
The Android Open Source Project0c908882009-03-03 19:32:16 -08002780 /**
2781 * Notify the host application a download should be done, or that
2782 * the data should be streamed if a streaming viewer is available.
2783 * @param url The full url to the content that should be downloaded
2784 * @param contentDisposition Content-disposition http header, if
2785 * present.
2786 * @param mimetype The mimetype of the content reported by the server
2787 * @param contentLength The file size reported by the server
2788 */
2789 public void onDownloadStart(String url, String userAgent,
2790 String contentDisposition, String mimetype, long contentLength) {
2791 // if we're dealing wih A/V content that's not explicitly marked
2792 // for download, check if it's streamable.
2793 if (contentDisposition == null
Patrick Scotte1fb9662009-08-31 14:31:52 -04002794 || !contentDisposition.regionMatches(
2795 true, 0, "attachment", 0, 10)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002796 // query the package manager to see if there's a registered handler
2797 // that matches.
2798 Intent intent = new Intent(Intent.ACTION_VIEW);
2799 intent.setDataAndType(Uri.parse(url), mimetype);
Patrick Scotte1fb9662009-08-31 14:31:52 -04002800 ResolveInfo info = getPackageManager().resolveActivity(intent,
2801 PackageManager.MATCH_DEFAULT_ONLY);
2802 if (info != null) {
2803 ComponentName myName = getComponentName();
2804 // If we resolved to ourselves, we don't want to attempt to
2805 // load the url only to try and download it again.
2806 if (!myName.getPackageName().equals(
2807 info.activityInfo.packageName)
2808 || !myName.getClassName().equals(
2809 info.activityInfo.name)) {
2810 // someone (other than us) knows how to handle this mime
2811 // type with this scheme, don't download.
2812 try {
2813 startActivity(intent);
2814 return;
2815 } catch (ActivityNotFoundException ex) {
2816 if (LOGD_ENABLED) {
2817 Log.d(LOGTAG, "activity not found for " + mimetype
2818 + " over " + Uri.parse(url).getScheme(),
2819 ex);
2820 }
2821 // Best behavior is to fall back to a download in this
2822 // case
The Android Open Source Project0c908882009-03-03 19:32:16 -08002823 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002824 }
2825 }
2826 }
2827 onDownloadStartNoStream(url, userAgent, contentDisposition, mimetype, contentLength);
2828 }
2829
2830 /**
2831 * Notify the host application a download should be done, even if there
2832 * is a streaming viewer available for thise type.
2833 * @param url The full url to the content that should be downloaded
2834 * @param contentDisposition Content-disposition http header, if
2835 * present.
2836 * @param mimetype The mimetype of the content reported by the server
2837 * @param contentLength The file size reported by the server
2838 */
2839 /*package */ void onDownloadStartNoStream(String url, String userAgent,
2840 String contentDisposition, String mimetype, long contentLength) {
2841
2842 String filename = URLUtil.guessFileName(url,
2843 contentDisposition, mimetype);
2844
2845 // Check to see if we have an SDCard
2846 String status = Environment.getExternalStorageState();
2847 if (!status.equals(Environment.MEDIA_MOUNTED)) {
2848 int title;
2849 String msg;
2850
2851 // Check to see if the SDCard is busy, same as the music app
2852 if (status.equals(Environment.MEDIA_SHARED)) {
2853 msg = getString(R.string.download_sdcard_busy_dlg_msg);
2854 title = R.string.download_sdcard_busy_dlg_title;
2855 } else {
2856 msg = getString(R.string.download_no_sdcard_dlg_msg, filename);
2857 title = R.string.download_no_sdcard_dlg_title;
2858 }
2859
2860 new AlertDialog.Builder(this)
2861 .setTitle(title)
2862 .setIcon(android.R.drawable.ic_dialog_alert)
2863 .setMessage(msg)
2864 .setPositiveButton(R.string.ok, null)
2865 .show();
2866 return;
2867 }
2868
2869 // java.net.URI is a lot stricter than KURL so we have to undo
2870 // KURL's percent-encoding and redo the encoding using java.net.URI.
2871 URI uri = null;
2872 try {
2873 // Undo the percent-encoding that KURL may have done.
2874 String newUrl = new String(URLUtil.decode(url.getBytes()));
2875 // Parse the url into pieces
2876 WebAddress w = new WebAddress(newUrl);
2877 String frag = null;
2878 String query = null;
2879 String path = w.mPath;
2880 // Break the path into path, query, and fragment
2881 if (path.length() > 0) {
2882 // Strip the fragment
2883 int idx = path.lastIndexOf('#');
2884 if (idx != -1) {
2885 frag = path.substring(idx + 1);
2886 path = path.substring(0, idx);
2887 }
2888 idx = path.lastIndexOf('?');
2889 if (idx != -1) {
2890 query = path.substring(idx + 1);
2891 path = path.substring(0, idx);
2892 }
2893 }
2894 uri = new URI(w.mScheme, w.mAuthInfo, w.mHost, w.mPort, path,
2895 query, frag);
2896 } catch (Exception e) {
2897 Log.e(LOGTAG, "Could not parse url for download: " + url, e);
2898 return;
2899 }
2900
2901 // XXX: Have to use the old url since the cookies were stored using the
2902 // old percent-encoded url.
2903 String cookies = CookieManager.getInstance().getCookie(url);
2904
2905 ContentValues values = new ContentValues();
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08002906 values.put(Downloads.Impl.COLUMN_URI, uri.toString());
2907 values.put(Downloads.Impl.COLUMN_COOKIE_DATA, cookies);
2908 values.put(Downloads.Impl.COLUMN_USER_AGENT, userAgent);
2909 values.put(Downloads.Impl.COLUMN_NOTIFICATION_PACKAGE,
The Android Open Source Project0c908882009-03-03 19:32:16 -08002910 getPackageName());
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08002911 values.put(Downloads.Impl.COLUMN_NOTIFICATION_CLASS,
The Android Open Source Project0c908882009-03-03 19:32:16 -08002912 BrowserDownloadPage.class.getCanonicalName());
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08002913 values.put(Downloads.Impl.COLUMN_VISIBILITY,
2914 Downloads.Impl.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
2915 values.put(Downloads.Impl.COLUMN_MIME_TYPE, mimetype);
2916 values.put(Downloads.Impl.COLUMN_FILE_NAME_HINT, filename);
2917 values.put(Downloads.Impl.COLUMN_DESCRIPTION, uri.getHost());
The Android Open Source Project0c908882009-03-03 19:32:16 -08002918 if (contentLength > 0) {
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08002919 values.put(Downloads.Impl.COLUMN_TOTAL_BYTES, contentLength);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002920 }
2921 if (mimetype == null) {
2922 // We must have long pressed on a link or image to download it. We
2923 // are not sure of the mimetype in this case, so do a head request
2924 new FetchUrlMimeType(this).execute(values);
2925 } else {
2926 final Uri contentUri =
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08002927 getContentResolver().insert(Downloads.Impl.CONTENT_URI, values);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002928 }
Leon Scroggins9191a7f2010-03-18 14:44:44 -04002929 Toast.makeText(this, R.string.download_pending, Toast.LENGTH_SHORT)
2930 .show();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002931 }
2932
Grace Kloba22ac16e2009-10-07 18:00:23 -07002933 // -------------------------------------------------------------------------
2934
The Android Open Source Project0c908882009-03-03 19:32:16 -08002935 /**
2936 * Resets the lock icon. This method is called when we start a new load and
2937 * know the url to be loaded.
2938 */
2939 private void resetLockIcon(String url) {
2940 // Save the lock-icon state (we revert to it if the load gets cancelled)
Grace Kloba22ac16e2009-10-07 18:00:23 -07002941 mTabControl.getCurrentTab().resetLockIcon(url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002942 updateLockIconImage(LOCK_ICON_UNSECURE);
2943 }
2944
The Android Open Source Project0c908882009-03-03 19:32:16 -08002945 /**
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04002946 * Update the lock icon to correspond to our latest state.
2947 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07002948 private void updateLockIconToLatest() {
2949 updateLockIconImage(mTabControl.getCurrentTab().getLockIconType());
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04002950 }
2951
2952 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08002953 * Updates the lock-icon image in the title-bar.
2954 */
2955 private void updateLockIconImage(int lockIconType) {
2956 Drawable d = null;
2957 if (lockIconType == LOCK_ICON_SECURE) {
2958 d = mSecLockIcon;
2959 } else if (lockIconType == LOCK_ICON_MIXED) {
2960 d = mMixLockIcon;
2961 }
Leon Scroggins68579392009-09-15 15:31:54 -04002962 mTitleBar.setLock(d);
Leon Scrogginsfe87bd32009-10-06 10:10:00 -04002963 mFakeTitleBar.setLock(d);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002964 }
2965
2966 /**
2967 * Displays a page-info dialog.
2968 * @param tab The tab to show info about
2969 * @param fromShowSSLCertificateOnError The flag that indicates whether
2970 * this dialog was opened from the SSL-certificate-on-error dialog or
2971 * not. This is important, since we need to know whether to return to
2972 * the parent dialog or simply dismiss.
2973 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07002974 private void showPageInfo(final Tab tab,
The Android Open Source Project0c908882009-03-03 19:32:16 -08002975 final boolean fromShowSSLCertificateOnError) {
2976 final LayoutInflater factory = LayoutInflater
2977 .from(this);
2978
2979 final View pageInfoView = factory.inflate(R.layout.page_info, null);
2980
2981 final WebView view = tab.getWebView();
2982
2983 String url = null;
2984 String title = null;
2985
2986 if (view == null) {
2987 url = tab.getUrl();
2988 title = tab.getTitle();
2989 } else if (view == mTabControl.getCurrentWebView()) {
2990 // Use the cached title and url if this is the current WebView
2991 url = mUrl;
2992 title = mTitle;
2993 } else {
2994 url = view.getUrl();
2995 title = view.getTitle();
2996 }
2997
2998 if (url == null) {
2999 url = "";
3000 }
3001 if (title == null) {
3002 title = "";
3003 }
3004
3005 ((TextView) pageInfoView.findViewById(R.id.address)).setText(url);
3006 ((TextView) pageInfoView.findViewById(R.id.title)).setText(title);
3007
3008 mPageInfoView = tab;
Leon Scrogginsc7b92f82010-01-11 18:17:31 -05003009 mPageInfoFromShowSSLCertificateOnError = fromShowSSLCertificateOnError;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003010
3011 AlertDialog.Builder alertDialogBuilder =
3012 new AlertDialog.Builder(this)
3013 .setTitle(R.string.page_info).setIcon(android.R.drawable.ic_dialog_info)
3014 .setView(pageInfoView)
3015 .setPositiveButton(
3016 R.string.ok,
3017 new DialogInterface.OnClickListener() {
3018 public void onClick(DialogInterface dialog,
3019 int whichButton) {
3020 mPageInfoDialog = null;
3021 mPageInfoView = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003022
3023 // if we came here from the SSL error dialog
3024 if (fromShowSSLCertificateOnError) {
3025 // go back to the SSL error dialog
3026 showSSLCertificateOnError(
3027 mSSLCertificateOnErrorView,
3028 mSSLCertificateOnErrorHandler,
3029 mSSLCertificateOnErrorError);
3030 }
3031 }
3032 })
3033 .setOnCancelListener(
3034 new DialogInterface.OnCancelListener() {
3035 public void onCancel(DialogInterface dialog) {
3036 mPageInfoDialog = null;
3037 mPageInfoView = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003038
3039 // if we came here from the SSL error dialog
3040 if (fromShowSSLCertificateOnError) {
3041 // go back to the SSL error dialog
3042 showSSLCertificateOnError(
3043 mSSLCertificateOnErrorView,
3044 mSSLCertificateOnErrorHandler,
3045 mSSLCertificateOnErrorError);
3046 }
3047 }
3048 });
3049
3050 // if we have a main top-level page SSL certificate set or a certificate
3051 // error
3052 if (fromShowSSLCertificateOnError ||
3053 (view != null && view.getCertificate() != null)) {
3054 // add a 'View Certificate' button
3055 alertDialogBuilder.setNeutralButton(
3056 R.string.view_certificate,
3057 new DialogInterface.OnClickListener() {
3058 public void onClick(DialogInterface dialog,
3059 int whichButton) {
3060 mPageInfoDialog = null;
3061 mPageInfoView = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003062
3063 // if we came here from the SSL error dialog
3064 if (fromShowSSLCertificateOnError) {
3065 // go back to the SSL error dialog
3066 showSSLCertificateOnError(
3067 mSSLCertificateOnErrorView,
3068 mSSLCertificateOnErrorHandler,
3069 mSSLCertificateOnErrorError);
3070 } else {
3071 // otherwise, display the top-most certificate from
3072 // the chain
3073 if (view.getCertificate() != null) {
3074 showSSLCertificate(tab);
3075 }
3076 }
3077 }
3078 });
3079 }
3080
3081 mPageInfoDialog = alertDialogBuilder.show();
3082 }
3083
3084 /**
3085 * Displays the main top-level page SSL certificate dialog
3086 * (accessible from the Page-Info dialog).
3087 * @param tab The tab to show certificate for.
3088 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003089 private void showSSLCertificate(final Tab tab) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003090 final View certificateView =
3091 inflateCertificateView(tab.getWebView().getCertificate());
3092 if (certificateView == null) {
3093 return;
3094 }
3095
3096 LayoutInflater factory = LayoutInflater.from(this);
3097
3098 final LinearLayout placeholder =
3099 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3100
3101 LinearLayout ll = (LinearLayout) factory.inflate(
3102 R.layout.ssl_success, placeholder);
3103 ((TextView)ll.findViewById(R.id.success))
3104 .setText(R.string.ssl_certificate_is_valid);
3105
3106 mSSLCertificateView = tab;
3107 mSSLCertificateDialog =
3108 new AlertDialog.Builder(this)
3109 .setTitle(R.string.ssl_certificate).setIcon(
3110 R.drawable.ic_dialog_browser_certificate_secure)
3111 .setView(certificateView)
3112 .setPositiveButton(R.string.ok,
3113 new DialogInterface.OnClickListener() {
3114 public void onClick(DialogInterface dialog,
3115 int whichButton) {
3116 mSSLCertificateDialog = null;
3117 mSSLCertificateView = null;
3118
3119 showPageInfo(tab, false);
3120 }
3121 })
3122 .setOnCancelListener(
3123 new DialogInterface.OnCancelListener() {
3124 public void onCancel(DialogInterface dialog) {
3125 mSSLCertificateDialog = null;
3126 mSSLCertificateView = null;
3127
3128 showPageInfo(tab, false);
3129 }
3130 })
3131 .show();
3132 }
3133
3134 /**
3135 * Displays the SSL error certificate dialog.
3136 * @param view The target web-view.
3137 * @param handler The SSL error handler responsible for cancelling the
3138 * connection that resulted in an SSL error or proceeding per user request.
3139 * @param error The SSL error object.
3140 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003141 void showSSLCertificateOnError(
The Android Open Source Project0c908882009-03-03 19:32:16 -08003142 final WebView view, final SslErrorHandler handler, final SslError error) {
3143
3144 final View certificateView =
3145 inflateCertificateView(error.getCertificate());
3146 if (certificateView == null) {
3147 return;
3148 }
3149
3150 LayoutInflater factory = LayoutInflater.from(this);
3151
3152 final LinearLayout placeholder =
3153 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3154
3155 if (error.hasError(SslError.SSL_UNTRUSTED)) {
3156 LinearLayout ll = (LinearLayout)factory
3157 .inflate(R.layout.ssl_warning, placeholder);
3158 ((TextView)ll.findViewById(R.id.warning))
3159 .setText(R.string.ssl_untrusted);
3160 }
3161
3162 if (error.hasError(SslError.SSL_IDMISMATCH)) {
3163 LinearLayout ll = (LinearLayout)factory
3164 .inflate(R.layout.ssl_warning, placeholder);
3165 ((TextView)ll.findViewById(R.id.warning))
3166 .setText(R.string.ssl_mismatch);
3167 }
3168
3169 if (error.hasError(SslError.SSL_EXPIRED)) {
3170 LinearLayout ll = (LinearLayout)factory
3171 .inflate(R.layout.ssl_warning, placeholder);
3172 ((TextView)ll.findViewById(R.id.warning))
3173 .setText(R.string.ssl_expired);
3174 }
3175
3176 if (error.hasError(SslError.SSL_NOTYETVALID)) {
3177 LinearLayout ll = (LinearLayout)factory
3178 .inflate(R.layout.ssl_warning, placeholder);
3179 ((TextView)ll.findViewById(R.id.warning))
3180 .setText(R.string.ssl_not_yet_valid);
3181 }
3182
3183 mSSLCertificateOnErrorHandler = handler;
3184 mSSLCertificateOnErrorView = view;
3185 mSSLCertificateOnErrorError = error;
3186 mSSLCertificateOnErrorDialog =
3187 new AlertDialog.Builder(this)
3188 .setTitle(R.string.ssl_certificate).setIcon(
3189 R.drawable.ic_dialog_browser_certificate_partially_secure)
3190 .setView(certificateView)
3191 .setPositiveButton(R.string.ok,
3192 new DialogInterface.OnClickListener() {
3193 public void onClick(DialogInterface dialog,
3194 int whichButton) {
3195 mSSLCertificateOnErrorDialog = null;
3196 mSSLCertificateOnErrorView = null;
3197 mSSLCertificateOnErrorHandler = null;
3198 mSSLCertificateOnErrorError = null;
3199
Grace Kloba22ac16e2009-10-07 18:00:23 -07003200 view.getWebViewClient().onReceivedSslError(
3201 view, handler, error);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003202 }
3203 })
3204 .setNeutralButton(R.string.page_info_view,
3205 new DialogInterface.OnClickListener() {
3206 public void onClick(DialogInterface dialog,
3207 int whichButton) {
3208 mSSLCertificateOnErrorDialog = null;
3209
3210 // do not clear the dialog state: we will
3211 // need to show the dialog again once the
3212 // user is done exploring the page-info details
3213
3214 showPageInfo(mTabControl.getTabFromView(view),
3215 true);
3216 }
3217 })
3218 .setOnCancelListener(
3219 new DialogInterface.OnCancelListener() {
3220 public void onCancel(DialogInterface dialog) {
3221 mSSLCertificateOnErrorDialog = null;
3222 mSSLCertificateOnErrorView = null;
3223 mSSLCertificateOnErrorHandler = null;
3224 mSSLCertificateOnErrorError = null;
3225
Grace Kloba22ac16e2009-10-07 18:00:23 -07003226 view.getWebViewClient().onReceivedSslError(
3227 view, handler, error);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003228 }
3229 })
3230 .show();
3231 }
3232
3233 /**
3234 * Inflates the SSL certificate view (helper method).
3235 * @param certificate The SSL certificate.
3236 * @return The resultant certificate view with issued-to, issued-by,
3237 * issued-on, expires-on, and possibly other fields set.
3238 * If the input certificate is null, returns null.
3239 */
3240 private View inflateCertificateView(SslCertificate certificate) {
3241 if (certificate == null) {
3242 return null;
3243 }
3244
3245 LayoutInflater factory = LayoutInflater.from(this);
3246
3247 View certificateView = factory.inflate(
3248 R.layout.ssl_certificate, null);
3249
3250 // issued to:
3251 SslCertificate.DName issuedTo = certificate.getIssuedTo();
3252 if (issuedTo != null) {
3253 ((TextView) certificateView.findViewById(R.id.to_common))
3254 .setText(issuedTo.getCName());
3255 ((TextView) certificateView.findViewById(R.id.to_org))
3256 .setText(issuedTo.getOName());
3257 ((TextView) certificateView.findViewById(R.id.to_org_unit))
3258 .setText(issuedTo.getUName());
3259 }
3260
3261 // issued by:
3262 SslCertificate.DName issuedBy = certificate.getIssuedBy();
3263 if (issuedBy != null) {
3264 ((TextView) certificateView.findViewById(R.id.by_common))
3265 .setText(issuedBy.getCName());
3266 ((TextView) certificateView.findViewById(R.id.by_org))
3267 .setText(issuedBy.getOName());
3268 ((TextView) certificateView.findViewById(R.id.by_org_unit))
3269 .setText(issuedBy.getUName());
3270 }
3271
3272 // issued on:
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003273 String issuedOn = formatCertificateDate(
3274 certificate.getValidNotBeforeDate());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003275 ((TextView) certificateView.findViewById(R.id.issued_on))
3276 .setText(issuedOn);
3277
3278 // expires on:
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003279 String expiresOn = formatCertificateDate(
3280 certificate.getValidNotAfterDate());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003281 ((TextView) certificateView.findViewById(R.id.expires_on))
3282 .setText(expiresOn);
3283
3284 return certificateView;
3285 }
3286
3287 /**
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003288 * Formats the certificate date to a properly localized date string.
The Android Open Source Project0c908882009-03-03 19:32:16 -08003289 * @return Properly localized version of the certificate date string and
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003290 * the "" if it fails to localize.
The Android Open Source Project0c908882009-03-03 19:32:16 -08003291 */
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003292 private String formatCertificateDate(Date certificateDate) {
3293 if (certificateDate == null) {
3294 return "";
The Android Open Source Project0c908882009-03-03 19:32:16 -08003295 }
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003296 String formattedDate = DateFormat.getDateFormat(this).format(certificateDate);
3297 if (formattedDate == null) {
3298 return "";
3299 }
3300 return formattedDate;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003301 }
3302
3303 /**
3304 * Displays an http-authentication dialog.
3305 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003306 void showHttpAuthentication(final HttpAuthHandler handler,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003307 final String host, final String realm, final String title,
3308 final String name, final String password, int focusId) {
3309 LayoutInflater factory = LayoutInflater.from(this);
3310 final View v = factory
3311 .inflate(R.layout.http_authentication, null);
3312 if (name != null) {
3313 ((EditText) v.findViewById(R.id.username_edit)).setText(name);
3314 }
3315 if (password != null) {
3316 ((EditText) v.findViewById(R.id.password_edit)).setText(password);
3317 }
3318
3319 String titleText = title;
3320 if (titleText == null) {
3321 titleText = getText(R.string.sign_in_to).toString().replace(
3322 "%s1", host).replace("%s2", realm);
3323 }
3324
3325 mHttpAuthHandler = handler;
3326 AlertDialog dialog = new AlertDialog.Builder(this)
3327 .setTitle(titleText)
3328 .setIcon(android.R.drawable.ic_dialog_alert)
3329 .setView(v)
3330 .setPositiveButton(R.string.action,
3331 new DialogInterface.OnClickListener() {
3332 public void onClick(DialogInterface dialog,
3333 int whichButton) {
3334 String nm = ((EditText) v
3335 .findViewById(R.id.username_edit))
3336 .getText().toString();
3337 String pw = ((EditText) v
3338 .findViewById(R.id.password_edit))
3339 .getText().toString();
3340 BrowserActivity.this.setHttpAuthUsernamePassword
3341 (host, realm, nm, pw);
3342 handler.proceed(nm, pw);
3343 mHttpAuthenticationDialog = null;
3344 mHttpAuthHandler = null;
3345 }})
3346 .setNegativeButton(R.string.cancel,
3347 new DialogInterface.OnClickListener() {
3348 public void onClick(DialogInterface dialog,
3349 int whichButton) {
3350 handler.cancel();
3351 BrowserActivity.this.resetTitleAndRevertLockIcon();
3352 mHttpAuthenticationDialog = null;
3353 mHttpAuthHandler = null;
3354 }})
3355 .setOnCancelListener(new DialogInterface.OnCancelListener() {
3356 public void onCancel(DialogInterface dialog) {
3357 handler.cancel();
3358 BrowserActivity.this.resetTitleAndRevertLockIcon();
3359 mHttpAuthenticationDialog = null;
3360 mHttpAuthHandler = null;
3361 }})
3362 .create();
3363 // Make the IME appear when the dialog is displayed if applicable.
3364 dialog.getWindow().setSoftInputMode(
3365 WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
3366 dialog.show();
3367 if (focusId != 0) {
3368 dialog.findViewById(focusId).requestFocus();
3369 } else {
3370 v.findViewById(R.id.username_edit).requestFocus();
3371 }
3372 mHttpAuthenticationDialog = dialog;
3373 }
3374
3375 public int getProgress() {
3376 WebView w = mTabControl.getCurrentWebView();
3377 if (w != null) {
3378 return w.getProgress();
3379 } else {
3380 return 100;
3381 }
3382 }
3383
3384 /**
3385 * Set HTTP authentication password.
3386 *
3387 * @param host The host for the password
3388 * @param realm The realm for the password
3389 * @param username The username for the password. If it is null, it means
3390 * password can't be saved.
3391 * @param password The password
3392 */
3393 public void setHttpAuthUsernamePassword(String host, String realm,
3394 String username,
3395 String password) {
3396 WebView w = mTabControl.getCurrentWebView();
3397 if (w != null) {
3398 w.setHttpAuthUsernamePassword(host, realm, username, password);
3399 }
3400 }
3401
3402 /**
3403 * connectivity manager says net has come or gone... inform the user
3404 * @param up true if net has come up, false if net has gone down
3405 */
3406 public void onNetworkToggle(boolean up) {
3407 if (up == mIsNetworkUp) {
3408 return;
3409 } else if (up) {
3410 mIsNetworkUp = true;
3411 if (mAlertDialog != null) {
3412 mAlertDialog.cancel();
3413 mAlertDialog = null;
3414 }
3415 } else {
3416 mIsNetworkUp = false;
Patrick Scotteb6ab2a2009-09-16 10:00:17 -04003417 if (mInLoad) {
3418 createAndShowNetworkDialog();
3419 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003420 }
3421 WebView w = mTabControl.getCurrentWebView();
3422 if (w != null) {
3423 w.setNetworkAvailable(up);
3424 }
3425 }
3426
Grace Kloba22ac16e2009-10-07 18:00:23 -07003427 boolean isNetworkUp() {
3428 return mIsNetworkUp;
3429 }
3430
Patrick Scotteb6ab2a2009-09-16 10:00:17 -04003431 // This method shows the network dialog alerting the user that the net is
3432 // down. It will only show the dialog if mAlertDialog is null.
3433 private void createAndShowNetworkDialog() {
3434 if (mAlertDialog == null) {
3435 mAlertDialog = new AlertDialog.Builder(this)
3436 .setTitle(R.string.loadSuspendedTitle)
3437 .setMessage(R.string.loadSuspended)
3438 .setPositiveButton(R.string.ok, null)
3439 .show();
3440 }
3441 }
3442
The Android Open Source Project0c908882009-03-03 19:32:16 -08003443 @Override
3444 protected void onActivityResult(int requestCode, int resultCode,
3445 Intent intent) {
Grace Klobabb394f32009-11-19 10:26:37 -08003446 if (getTopWindow() == null) return;
3447
The Android Open Source Project0c908882009-03-03 19:32:16 -08003448 switch (requestCode) {
3449 case COMBO_PAGE:
3450 if (resultCode == RESULT_OK && intent != null) {
3451 String data = intent.getAction();
3452 Bundle extras = intent.getExtras();
3453 if (extras != null && extras.getBoolean("new_window", false)) {
Leon Scroggins25d35472009-09-15 11:37:27 -04003454 openTab(data);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003455 } else {
Grace Kloba22ac16e2009-10-07 18:00:23 -07003456 final Tab currentTab =
The Android Open Source Project0c908882009-03-03 19:32:16 -08003457 mTabControl.getCurrentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04003458 dismissSubWindow(currentTab);
3459 if (data != null && data.length() != 0) {
Leon Scroggins92472e82010-02-17 16:32:28 -05003460 loadUrl(getTopWindow(), data);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003461 }
3462 }
3463 }
Leon Scrogginsfde97462010-01-11 13:06:21 -05003464 // Deliberately fall through to PREFERENCES_PAGE, since the
3465 // same extra may be attached to the COMBO_PAGE
3466 case PREFERENCES_PAGE:
3467 if (resultCode == RESULT_OK && intent != null) {
3468 String action = intent.getStringExtra(Intent.EXTRA_TEXT);
3469 if (BrowserSettings.PREF_CLEAR_HISTORY.equals(action)) {
3470 mTabControl.removeParentChildRelationShips();
3471 }
3472 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003473 break;
Leon Scroggins8d5fa432009-10-02 15:55:59 -04003474 // Choose a file from the file picker.
3475 case FILE_SELECTED:
3476 if (null == mUploadMessage) break;
3477 Uri result = intent == null || resultCode != RESULT_OK ? null
3478 : intent.getData();
3479 mUploadMessage.onReceiveValue(result);
3480 mUploadMessage = null;
3481 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003482 default:
3483 break;
3484 }
Leon Scroggins30444232009-09-04 18:36:20 -04003485 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003486 }
3487
3488 /*
3489 * This method is called as a result of the user selecting the options
Leon Scrogginsf08809b2010-01-21 09:27:46 -05003490 * menu to see the download window. It shows the download window on top of
3491 * the current window.
The Android Open Source Project0c908882009-03-03 19:32:16 -08003492 */
Leon Scrogginsf08809b2010-01-21 09:27:46 -05003493 private void viewDownloads(Uri downloadRecord) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003494 Intent intent = new Intent(this,
3495 BrowserDownloadPage.class);
3496 intent.setData(downloadRecord);
Grace Kloba22ac16e2009-10-07 18:00:23 -07003497 startActivityForResult(intent, BrowserActivity.DOWNLOAD_PAGE);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003498
3499 }
3500
Leon Scroggins160a7e72009-08-14 18:28:01 -04003501 /**
3502 * Open the Go page.
3503 * @param startWithHistory If true, open starting on the history tab.
3504 * Otherwise, start with the bookmarks tab.
Leon Scroggins160a7e72009-08-14 18:28:01 -04003505 */
Leon Scroggins30444232009-09-04 18:36:20 -04003506 /* package */ void bookmarksOrHistoryPicker(boolean startWithHistory) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003507 WebView current = mTabControl.getCurrentWebView();
3508 if (current == null) {
3509 return;
3510 }
3511 Intent intent = new Intent(this,
3512 CombinedBookmarkHistoryActivity.class);
3513 String title = current.getTitle();
3514 String url = current.getUrl();
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01003515 Bitmap thumbnail = createScreenshot(current);
3516
The Android Open Source Project0c908882009-03-03 19:32:16 -08003517 // Just in case the user opens bookmarks before a page finishes loading
3518 // so the current history item, and therefore the page, is null.
3519 if (null == url) {
3520 url = mLastEnteredUrl;
3521 // This can happen.
3522 if (null == url) {
3523 url = mSettings.getHomePage();
3524 }
3525 }
3526 // In case the web page has not yet received its associated title.
3527 if (title == null) {
3528 title = url;
3529 }
3530 intent.putExtra("title", title);
3531 intent.putExtra("url", url);
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01003532 intent.putExtra("thumbnail", thumbnail);
Leon Scroggins30444232009-09-04 18:36:20 -04003533 // Disable opening in a new window if we have maxed out the windows
Grace Kloba22ac16e2009-10-07 18:00:23 -07003534 intent.putExtra("disable_new_window", !mTabControl.canCreateNewTab());
Patrick Scott3918d442009-08-04 13:22:29 -04003535 intent.putExtra("touch_icon_url", current.getTouchIconUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003536 if (startWithHistory) {
3537 intent.putExtra(CombinedBookmarkHistoryActivity.STARTING_TAB,
3538 CombinedBookmarkHistoryActivity.HISTORY_TAB);
3539 }
3540 startActivityForResult(intent, COMBO_PAGE);
3541 }
3542
3543 // Called when loading from context menu or LOAD_URL message
Leon Scroggins92472e82010-02-17 16:32:28 -05003544 private void loadUrlFromContext(WebView view, String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003545 // In case the user enters nothing.
3546 if (url != null && url.length() != 0 && view != null) {
3547 url = smartUrlFilter(url);
Grace Kloba22ac16e2009-10-07 18:00:23 -07003548 if (!view.getWebViewClient().shouldOverrideUrlLoading(view, url)) {
Leon Scroggins92472e82010-02-17 16:32:28 -05003549 loadUrl(view, url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003550 }
3551 }
3552 }
3553
Leon Scroggins92472e82010-02-17 16:32:28 -05003554 /**
3555 * Load the URL into the given WebView and update the title bar
3556 * to reflect the new load. Call this instead of WebView.loadUrl
3557 * directly.
3558 * @param view The WebView used to load url.
3559 * @param url The URL to load.
3560 */
3561 private void loadUrl(WebView view, String url) {
3562 updateTitleBarForNewLoad(view, url);
3563 view.loadUrl(url);
3564 }
3565
3566 /**
3567 * Load UrlData into a Tab and update the title bar to reflect the new
3568 * load. Call this instead of UrlData.loadIn directly.
3569 * @param t The Tab used to load.
3570 * @param data The UrlData being loaded.
3571 */
3572 private void loadUrlDataIn(Tab t, UrlData data) {
3573 updateTitleBarForNewLoad(t.getWebView(), data.mUrl);
3574 data.loadIn(t);
3575 }
3576
3577 /**
3578 * If the WebView is the top window, update the title bar to reflect
3579 * loading the new URL. i.e. set its text, clear the favicon (which
3580 * will be set once the page begins loading), and set the progress to
3581 * INITIAL_PROGRESS to show that the page has begun to load. Called
3582 * by loadUrl and loadUrlDataIn.
3583 * @param view The WebView that is starting a load.
3584 * @param url The URL that is being loaded.
3585 */
3586 private void updateTitleBarForNewLoad(WebView view, String url) {
3587 if (view == getTopWindow()) {
3588 setUrlTitle(url, null);
3589 setFavicon(null);
3590 onProgressChanged(view, INITIAL_PROGRESS);
3591 }
3592 }
3593
The Android Open Source Project0c908882009-03-03 19:32:16 -08003594 private String smartUrlFilter(Uri inUri) {
3595 if (inUri != null) {
3596 return smartUrlFilter(inUri.toString());
3597 }
3598 return null;
3599 }
3600
Feng Qianb34f87a2009-03-24 21:27:26 -07003601 protected static final Pattern ACCEPTED_URI_SCHEMA = Pattern.compile(
The Android Open Source Project0c908882009-03-03 19:32:16 -08003602 "(?i)" + // switch on case insensitive matching
3603 "(" + // begin group for schema
3604 "(?:http|https|file):\\/\\/" +
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003605 "|(?:inline|data|about|content|javascript):" +
The Android Open Source Project0c908882009-03-03 19:32:16 -08003606 ")" +
3607 "(.*)" );
3608
3609 /**
3610 * Attempts to determine whether user input is a URL or search
3611 * terms. Anything with a space is passed to search.
3612 *
3613 * Converts to lowercase any mistakenly uppercased schema (i.e.,
3614 * "Http://" converts to "http://"
3615 *
3616 * @return Original or modified URL
3617 *
3618 */
3619 String smartUrlFilter(String url) {
3620
3621 String inUrl = url.trim();
3622 boolean hasSpace = inUrl.indexOf(' ') != -1;
3623
3624 Matcher matcher = ACCEPTED_URI_SCHEMA.matcher(inUrl);
3625 if (matcher.matches()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003626 // force scheme to lowercase
3627 String scheme = matcher.group(1);
3628 String lcScheme = scheme.toLowerCase();
3629 if (!lcScheme.equals(scheme)) {
Mitsuru Oshima123ecfb2009-05-18 19:11:14 -07003630 inUrl = lcScheme + matcher.group(2);
3631 }
3632 if (hasSpace) {
3633 inUrl = inUrl.replace(" ", "%20");
The Android Open Source Project0c908882009-03-03 19:32:16 -08003634 }
3635 return inUrl;
3636 }
3637 if (hasSpace) {
Satish Sampath565505b2009-05-29 15:37:27 +01003638 // FIXME: Is this the correct place to add to searches?
3639 // what if someone else calls this function?
3640 int shortcut = parseUrlShortcut(inUrl);
3641 if (shortcut != SHORTCUT_INVALID) {
3642 Browser.addSearchUrl(mResolver, inUrl);
3643 String query = inUrl.substring(2);
3644 switch (shortcut) {
3645 case SHORTCUT_GOOGLE_SEARCH:
Grace Kloba47fdfdb2009-06-30 11:15:34 -07003646 return URLUtil.composeSearchUrl(query, QuickSearch_G, QUERY_PLACE_HOLDER);
Satish Sampath565505b2009-05-29 15:37:27 +01003647 case SHORTCUT_WIKIPEDIA_SEARCH:
3648 return URLUtil.composeSearchUrl(query, QuickSearch_W, QUERY_PLACE_HOLDER);
3649 case SHORTCUT_DICTIONARY_SEARCH:
3650 return URLUtil.composeSearchUrl(query, QuickSearch_D, QUERY_PLACE_HOLDER);
3651 case SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH:
The Android Open Source Project0c908882009-03-03 19:32:16 -08003652 // FIXME: we need location in this case
Satish Sampath565505b2009-05-29 15:37:27 +01003653 return URLUtil.composeSearchUrl(query, QuickSearch_L, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003654 }
3655 }
3656 } else {
Dan Egnor5ee906c2009-11-18 12:11:49 -08003657 if (Patterns.WEB_URL.matcher(inUrl).matches()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003658 return URLUtil.guessUrl(inUrl);
3659 }
3660 }
3661
3662 Browser.addSearchUrl(mResolver, inUrl);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07003663 return URLUtil.composeSearchUrl(inUrl, QuickSearch_G, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003664 }
3665
Ben Murdochbff2d602009-07-01 20:19:05 +01003666 /* package */ void setShouldShowErrorConsole(boolean flag) {
3667 if (flag == mShouldShowErrorConsole) {
3668 // Nothing to do.
3669 return;
3670 }
3671
3672 mShouldShowErrorConsole = flag;
3673
Grace Kloba22ac16e2009-10-07 18:00:23 -07003674 ErrorConsoleView errorConsole = mTabControl.getCurrentTab()
3675 .getErrorConsole(true);
Ben Murdochbff2d602009-07-01 20:19:05 +01003676
3677 if (flag) {
3678 // Setting the show state of the console will cause it's the layout to be inflated.
3679 if (errorConsole.numberOfErrors() > 0) {
3680 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
3681 } else {
3682 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
3683 }
3684
3685 // Now we can add it to the main view.
3686 mErrorConsoleContainer.addView(errorConsole,
Romain Guy15b8ec62010-01-08 15:06:43 -08003687 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
Ben Murdochbff2d602009-07-01 20:19:05 +01003688 ViewGroup.LayoutParams.WRAP_CONTENT));
3689 } else {
3690 mErrorConsoleContainer.removeView(errorConsole);
3691 }
3692
3693 }
3694
Grace Kloba22ac16e2009-10-07 18:00:23 -07003695 boolean shouldShowErrorConsole() {
3696 return mShouldShowErrorConsole;
3697 }
3698
Andrei Popescu163ab742009-10-20 17:58:23 +01003699 private void setStatusBarVisibility(boolean visible) {
3700 int flag = visible ? 0 : WindowManager.LayoutParams.FLAG_FULLSCREEN;
3701 getWindow().setFlags(flag, WindowManager.LayoutParams.FLAG_FULLSCREEN);
3702 }
3703
Andrei Popescu56199cc2010-01-12 22:39:16 +00003704
3705 private void sendNetworkType(String type, String subtype) {
3706 WebView w = mTabControl.getCurrentWebView();
3707 if (w != null) {
3708 w.setNetworkType(type, subtype);
3709 }
3710 }
3711
Andrei Popescu30995e72010-02-09 16:59:58 +00003712 private void packageChanged(String packageName, boolean wasAdded) {
3713 WebView w = mTabControl.getCurrentWebView();
3714 if (w == null) {
3715 return;
3716 }
3717
3718 if (wasAdded) {
3719 w.addPackageName(packageName);
3720 } else {
3721 w.removePackageName(packageName);
3722 }
3723 }
3724
3725 private void addPackageNames(Set<String> packageNames) {
3726 WebView w = mTabControl.getCurrentWebView();
3727 if (w == null) {
3728 return;
3729 }
3730
3731 w.addPackageNames(packageNames);
3732 }
3733
3734 private void getInstalledPackages() {
3735 AsyncTask<Void, Void, Set<String> > task =
3736 new AsyncTask<Void, Void, Set<String> >() {
3737 protected Set<String> doInBackground(Void... unused) {
3738 Set<String> installedPackages = new HashSet<String>();
3739 PackageManager pm = BrowserActivity.this.getPackageManager();
3740 if (pm != null) {
3741 List<PackageInfo> packages = pm.getInstalledPackages(0);
3742 for (PackageInfo p : packages) {
3743 if (BrowserActivity.this.sGoogleApps.contains(p.packageName)) {
3744 installedPackages.add(p.packageName);
3745 }
3746 }
3747 }
3748
3749 return installedPackages;
3750 }
3751
3752 // Executes on the UI thread
3753 protected void onPostExecute(Set<String> installedPackages) {
3754 addPackageNames(installedPackages);
3755 }
3756 };
3757 task.execute();
3758 }
3759
Grace Klobaeb6eef42009-09-15 17:56:32 -07003760 final static int LOCK_ICON_UNSECURE = 0;
3761 final static int LOCK_ICON_SECURE = 1;
3762 final static int LOCK_ICON_MIXED = 2;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003763
The Android Open Source Project0c908882009-03-03 19:32:16 -08003764 private BrowserSettings mSettings;
3765 private TabControl mTabControl;
3766 private ContentResolver mResolver;
3767 private FrameLayout mContentView;
Andrei Popescuadc008d2009-06-26 14:11:30 +01003768 private View mCustomView;
3769 private FrameLayout mCustomViewContainer;
Andrei Popescuc9b55562009-07-07 10:51:15 +01003770 private WebChromeClient.CustomViewCallback mCustomViewCallback;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003771
3772 // FIXME, temp address onPrepareMenu performance problem. When we move everything out of
3773 // view, we should rewrite this.
3774 private int mCurrentMenuState = 0;
3775 private int mMenuState = R.id.MAIN_MENU;
Andrei Popescuadc008d2009-06-26 14:11:30 +01003776 private int mOldMenuState = EMPTY_MENU;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003777 private static final int EMPTY_MENU = -1;
3778 private Menu mMenu;
3779
3780 private FindDialog mFindDialog;
3781 // Used to prevent chording to result in firing two shortcuts immediately
3782 // one after another. Fixes bug 1211714.
3783 boolean mCanChord;
3784
3785 private boolean mInLoad;
3786 private boolean mIsNetworkUp;
Ben Murdochb7cc8b42009-09-28 10:59:09 +01003787 private boolean mDidStopLoad;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003788
The Android Open Source Project0c908882009-03-03 19:32:16 -08003789 private boolean mActivityInPause = true;
3790
3791 private boolean mMenuIsDown;
3792
The Android Open Source Project0c908882009-03-03 19:32:16 -08003793 private static boolean mInTrace;
3794
3795 // Performance probe
3796 private static final int[] SYSTEM_CPU_FORMAT = new int[] {
3797 Process.PROC_SPACE_TERM | Process.PROC_COMBINE,
3798 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 1: user time
3799 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 2: nice time
3800 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 3: sys time
3801 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 4: idle time
3802 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 5: iowait time
3803 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 6: irq time
3804 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG // 7: softirq time
3805 };
3806
3807 private long mStart;
3808 private long mProcessStart;
3809 private long mUserStart;
3810 private long mSystemStart;
3811 private long mIdleStart;
3812 private long mIrqStart;
3813
3814 private long mUiStart;
3815
3816 private Drawable mMixLockIcon;
3817 private Drawable mSecLockIcon;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003818
3819 /* hold a ref so we can auto-cancel if necessary */
3820 private AlertDialog mAlertDialog;
3821
The Android Open Source Project0c908882009-03-03 19:32:16 -08003822 // The up-to-date URL and title (these can be different from those stored
3823 // in WebView, since it takes some time for the information in WebView to
3824 // get updated)
3825 private String mUrl;
3826 private String mTitle;
3827
3828 // As PageInfo has different style for landscape / portrait, we have
3829 // to re-open it when configuration changed
3830 private AlertDialog mPageInfoDialog;
Grace Kloba22ac16e2009-10-07 18:00:23 -07003831 private Tab mPageInfoView;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003832 // If the Page-Info dialog is launched from the SSL-certificate-on-error
3833 // dialog, we should not just dismiss it, but should get back to the
3834 // SSL-certificate-on-error dialog. This flag is used to store this state
Leon Scrogginsc7b92f82010-01-11 18:17:31 -05003835 private boolean mPageInfoFromShowSSLCertificateOnError;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003836
3837 // as SSLCertificateOnError has different style for landscape / portrait,
3838 // we have to re-open it when configuration changed
3839 private AlertDialog mSSLCertificateOnErrorDialog;
3840 private WebView mSSLCertificateOnErrorView;
3841 private SslErrorHandler mSSLCertificateOnErrorHandler;
3842 private SslError mSSLCertificateOnErrorError;
3843
3844 // as SSLCertificate has different style for landscape / portrait, we
3845 // have to re-open it when configuration changed
3846 private AlertDialog mSSLCertificateDialog;
Grace Kloba22ac16e2009-10-07 18:00:23 -07003847 private Tab mSSLCertificateView;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003848
3849 // as HttpAuthentication has different style for landscape / portrait, we
3850 // have to re-open it when configuration changed
3851 private AlertDialog mHttpAuthenticationDialog;
3852 private HttpAuthHandler mHttpAuthHandler;
3853
3854 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_PARAMS =
3855 new FrameLayout.LayoutParams(
Romain Guy15b8ec62010-01-08 15:06:43 -08003856 ViewGroup.LayoutParams.MATCH_PARENT,
3857 ViewGroup.LayoutParams.MATCH_PARENT);
Andrei Popescuadc008d2009-06-26 14:11:30 +01003858 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_GRAVITY_CENTER =
3859 new FrameLayout.LayoutParams(
Romain Guy15b8ec62010-01-08 15:06:43 -08003860 ViewGroup.LayoutParams.MATCH_PARENT,
3861 ViewGroup.LayoutParams.MATCH_PARENT,
Andrei Popescuadc008d2009-06-26 14:11:30 +01003862 Gravity.CENTER);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07003863 // Google search
3864 final static String QuickSearch_G = "http://www.google.com/m?q=%s";
The Android Open Source Project0c908882009-03-03 19:32:16 -08003865 // Wikipedia search
3866 final static String QuickSearch_W = "http://en.wikipedia.org/w/index.php?search=%s&go=Go";
3867 // Dictionary search
3868 final static String QuickSearch_D = "http://dictionary.reference.com/search?q=%s";
3869 // Google Mobile Local search
3870 final static String QuickSearch_L = "http://www.google.com/m/search?site=local&q=%s&near=mountain+view";
3871
3872 final static String QUERY_PLACE_HOLDER = "%s";
3873
3874 // "source" parameter for Google search through search key
3875 final static String GOOGLE_SEARCH_SOURCE_SEARCHKEY = "browser-key";
3876 // "source" parameter for Google search through goto menu
3877 final static String GOOGLE_SEARCH_SOURCE_GOTO = "browser-goto";
3878 // "source" parameter for Google search through simplily type
3879 final static String GOOGLE_SEARCH_SOURCE_TYPE = "browser-type";
3880 // "source" parameter for Google search suggested by the browser
3881 final static String GOOGLE_SEARCH_SOURCE_SUGGEST = "browser-suggest";
3882 // "source" parameter for Google search from unknown source
3883 final static String GOOGLE_SEARCH_SOURCE_UNKNOWN = "unknown";
3884
3885 private final static String LOGTAG = "browser";
3886
The Android Open Source Project0c908882009-03-03 19:32:16 -08003887 private String mLastEnteredUrl;
3888
3889 private PowerManager.WakeLock mWakeLock;
3890 private final static int WAKELOCK_TIMEOUT = 5 * 60 * 1000; // 5 minutes
3891
3892 private Toast mStopToast;
3893
Leon Scroggins68579392009-09-15 15:31:54 -04003894 private TitleBar mTitleBar;
Leon Scroggins81db3662009-06-04 17:45:11 -04003895
Ben Murdochbff2d602009-07-01 20:19:05 +01003896 private LinearLayout mErrorConsoleContainer = null;
3897 private boolean mShouldShowErrorConsole = false;
3898
The Android Open Source Project0c908882009-03-03 19:32:16 -08003899 // As the ids are dynamically created, we can't guarantee that they will
3900 // be in sequence, so this static array maps ids to a window number.
3901 final static private int[] WINDOW_SHORTCUT_ID_ARRAY =
3902 { R.id.window_one_menu_id, R.id.window_two_menu_id, R.id.window_three_menu_id,
3903 R.id.window_four_menu_id, R.id.window_five_menu_id, R.id.window_six_menu_id,
3904 R.id.window_seven_menu_id, R.id.window_eight_menu_id };
3905
3906 // monitor platform changes
3907 private IntentFilter mNetworkStateChangedFilter;
3908 private BroadcastReceiver mNetworkStateIntentReceiver;
3909
Grace Klobab4da0ad2009-05-14 14:45:40 -07003910 private BroadcastReceiver mPackageInstallationReceiver;
3911
The Android Open Source Project0c908882009-03-03 19:32:16 -08003912 // activity requestCode
Nicolas Roard78a98e42009-05-11 13:34:17 +01003913 final static int COMBO_PAGE = 1;
3914 final static int DOWNLOAD_PAGE = 2;
3915 final static int PREFERENCES_PAGE = 3;
Leon Scroggins8d5fa432009-10-02 15:55:59 -04003916 final static int FILE_SELECTED = 4;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003917
Andrei Popescu540035d2009-09-18 18:59:20 +01003918 // the default <video> poster
3919 private Bitmap mDefaultVideoPoster;
3920 // the video progress view
3921 private View mVideoProgressView;
3922
Andrei Popescu30995e72010-02-09 16:59:58 +00003923 // The Google packages we monitor for the navigator.isApplicationInstalled()
3924 // API. Add as needed.
3925 private static Set<String> sGoogleApps;
3926 static {
3927 sGoogleApps = new HashSet<String>();
3928 sGoogleApps.add("com.google.android.youtube");
3929 }
3930
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003931 /**
3932 * A UrlData class to abstract how the content will be set to WebView.
3933 * This base class uses loadUrl to show the content.
3934 */
Leon Scroggins6eac63e2010-03-15 18:19:14 -04003935 /* package */ static class UrlData {
Grace Kloba068e48b2010-01-26 18:11:27 -08003936 final String mUrl;
3937 final Map<String, String> mHeaders;
Leon Scroggins58d56c62010-01-28 15:12:40 -05003938 final Intent mVoiceIntent;
Grace Kloba60e095c2009-06-16 11:50:55 -07003939
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003940 UrlData(String url) {
3941 this.mUrl = url;
Grace Kloba068e48b2010-01-26 18:11:27 -08003942 this.mHeaders = null;
Leon Scroggins58d56c62010-01-28 15:12:40 -05003943 this.mVoiceIntent = null;
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003944 }
Grace Kloba60e095c2009-06-16 11:50:55 -07003945
Leon Scroggins58d56c62010-01-28 15:12:40 -05003946 UrlData(String url, Map<String, String> headers, Intent intent) {
Grace Kloba068e48b2010-01-26 18:11:27 -08003947 this.mUrl = url;
3948 this.mHeaders = headers;
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -05003949 if (RecognizerResultsIntent.ACTION_VOICE_SEARCH_RESULTS
3950 .equals(intent.getAction())) {
Leon Scroggins58d56c62010-01-28 15:12:40 -05003951 this.mVoiceIntent = intent;
3952 } else {
3953 this.mVoiceIntent = null;
3954 }
Grace Kloba60e095c2009-06-16 11:50:55 -07003955 }
3956
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003957 boolean isEmpty() {
Leon Scroggins58d56c62010-01-28 15:12:40 -05003958 return mVoiceIntent == null && (mUrl == null || mUrl.length() == 0);
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003959 }
3960
Leon Scroggins92472e82010-02-17 16:32:28 -05003961 /**
3962 * Load this UrlData into the given Tab. Use loadUrlDataIn to update
3963 * the title bar as well.
3964 */
Leon Scroggins58d56c62010-01-28 15:12:40 -05003965 public void loadIn(Tab t) {
3966 if (mVoiceIntent != null) {
3967 t.activateVoiceSearchMode(mVoiceIntent);
3968 } else {
3969 t.getWebView().loadUrl(mUrl, mHeaders);
3970 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003971 }
3972 };
3973
Leon Scroggins1f005d32009-08-10 17:36:42 -04003974 /* package */ static final UrlData EMPTY_URL_DATA = new UrlData(null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003975}