blob: 1e7361bfc9a94a37a03ec5416d9d1ac989f1b98d [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
19import com.google.android.googleapps.IGoogleLoginService;
20import com.google.android.googlelogin.GoogleLoginServiceConstants;
21
22import android.app.Activity;
The Android Open Source Project0c908882009-03-03 19:32:16 -080023import android.app.AlertDialog;
24import android.app.ProgressDialog;
25import android.app.SearchManager;
26import android.content.ActivityNotFoundException;
27import android.content.BroadcastReceiver;
28import android.content.ComponentName;
29import android.content.ContentResolver;
Leon Scrogginsb6b7f9e2009-06-18 12:05:28 -040030import android.content.ContentUris;
The Android Open Source Project0c908882009-03-03 19:32:16 -080031import android.content.ContentValues;
32import android.content.Context;
33import android.content.DialogInterface;
34import android.content.Intent;
35import android.content.IntentFilter;
36import android.content.ServiceConnection;
37import android.content.DialogInterface.OnCancelListener;
Grace Klobab4da0ad2009-05-14 14:45:40 -070038import android.content.pm.PackageInfo;
The Android Open Source Project0c908882009-03-03 19:32:16 -080039import android.content.pm.PackageManager;
40import android.content.pm.ResolveInfo;
41import android.content.res.AssetManager;
42import android.content.res.Configuration;
43import android.content.res.Resources;
44import android.database.Cursor;
45import android.database.sqlite.SQLiteDatabase;
46import android.database.sqlite.SQLiteException;
47import android.graphics.Bitmap;
Andrei Popescu540035d2009-09-18 18:59:20 +010048import android.graphics.BitmapFactory;
The Android Open Source Project0c908882009-03-03 19:32:16 -080049import android.graphics.Canvas;
The Android Open Source Project0c908882009-03-03 19:32:16 -080050import android.graphics.DrawFilter;
51import android.graphics.Paint;
52import android.graphics.PaintFlagsDrawFilter;
53import android.graphics.Picture;
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -040054import android.graphics.PixelFormat;
55import android.graphics.Rect;
The Android Open Source Project0c908882009-03-03 19:32:16 -080056import android.graphics.drawable.Drawable;
The Android Open Source Project0c908882009-03-03 19:32:16 -080057import android.hardware.SensorListener;
58import android.hardware.SensorManager;
59import android.net.ConnectivityManager;
Patrick Scotteb6ab2a2009-09-16 10:00:17 -040060import android.net.NetworkInfo;
The Android Open Source Project0c908882009-03-03 19:32:16 -080061import android.net.Uri;
62import android.net.WebAddress;
63import android.net.http.EventHandler;
64import android.net.http.SslCertificate;
65import android.net.http.SslError;
66import android.os.AsyncTask;
67import android.os.Bundle;
68import android.os.Debug;
69import android.os.Environment;
70import android.os.Handler;
71import android.os.IBinder;
72import android.os.Message;
73import android.os.PowerManager;
74import android.os.Process;
75import android.os.RemoteException;
76import android.os.ServiceManager;
77import android.os.SystemClock;
The Android Open Source Project0c908882009-03-03 19:32:16 -080078import android.provider.Browser;
Cary Clark5e335a32009-09-22 14:53:11 -040079import android.provider.ContactsContract;
80import android.provider.ContactsContract.Intents.Insert;
The Android Open Source Project0c908882009-03-03 19:32:16 -080081import android.provider.Downloads;
82import android.provider.MediaStore;
The Android Open Source Project0c908882009-03-03 19:32:16 -080083import android.text.IClipboard;
84import android.text.TextUtils;
85import android.text.format.DateFormat;
86import android.text.util.Regex;
Leon Scrogginsb94bf272009-09-25 15:22:08 -040087import android.util.AttributeSet;
The Android Open Source Project0c908882009-03-03 19:32:16 -080088import android.util.Log;
89import android.view.ContextMenu;
90import android.view.Gravity;
91import android.view.KeyEvent;
92import android.view.LayoutInflater;
93import android.view.Menu;
94import android.view.MenuInflater;
95import android.view.MenuItem;
96import android.view.View;
97import android.view.ViewGroup;
98import android.view.Window;
99import android.view.WindowManager;
100import android.view.ContextMenu.ContextMenuInfo;
101import android.view.MenuItem.OnMenuItemClickListener;
102import android.view.animation.AlphaAnimation;
103import android.view.animation.Animation;
104import android.view.animation.AnimationSet;
105import android.view.animation.DecelerateInterpolator;
106import android.view.animation.ScaleAnimation;
107import android.view.animation.TranslateAnimation;
108import android.webkit.CookieManager;
109import android.webkit.CookieSyncManager;
110import android.webkit.DownloadListener;
Steve Block2bc69912009-07-30 14:45:13 +0100111import android.webkit.GeolocationPermissions;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800112import android.webkit.HttpAuthHandler;
Grace Klobab4da0ad2009-05-14 14:45:40 -0700113import android.webkit.PluginManager;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800114import android.webkit.SslErrorHandler;
115import android.webkit.URLUtil;
Leon Clarkecb6cc862009-09-29 18:35:13 +0100116import android.webkit.ValueCallback;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800117import android.webkit.WebChromeClient;
Andrei Popescuc9b55562009-07-07 10:51:15 +0100118import android.webkit.WebChromeClient.CustomViewCallback;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800119import android.webkit.WebHistoryItem;
120import android.webkit.WebIconDatabase;
Ben Murdoch092dd5d2009-04-22 12:34:12 +0100121import android.webkit.WebStorage;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800122import android.webkit.WebView;
123import android.webkit.WebViewClient;
124import android.widget.EditText;
125import android.widget.FrameLayout;
126import android.widget.LinearLayout;
127import android.widget.TextView;
128import android.widget.Toast;
129
130import java.io.BufferedOutputStream;
Leon Scrogginsb6b7f9e2009-06-18 12:05:28 -0400131import java.io.ByteArrayOutputStream;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800132import java.io.File;
133import java.io.FileInputStream;
134import java.io.FileOutputStream;
135import java.io.IOException;
136import java.io.InputStream;
137import java.net.MalformedURLException;
138import java.net.URI;
Dianne Hackborn99189432009-06-17 18:06:18 -0700139import java.net.URISyntaxException;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800140import java.net.URL;
141import java.net.URLEncoder;
142import java.text.ParseException;
143import java.util.Date;
144import java.util.Enumeration;
145import java.util.HashMap;
Patrick Scott37911c72009-03-24 18:02:58 -0700146import java.util.LinkedList;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800147import java.util.Vector;
148import java.util.regex.Matcher;
149import java.util.regex.Pattern;
150import java.util.zip.ZipEntry;
151import java.util.zip.ZipFile;
152
153public class BrowserActivity extends Activity
Grace Kloba5942df02009-09-18 11:48:29 -0700154 implements View.OnCreateContextMenuListener,
The Android Open Source Project0c908882009-03-03 19:32:16 -0800155 DownloadListener {
156
Dave Bort31a6d1c2009-04-13 15:56:49 -0700157 /* Define some aliases to make these debugging flags easier to refer to.
158 * This file imports android.provider.Browser, so we can't just refer to "Browser.DEBUG".
159 */
160 private final static boolean DEBUG = com.android.browser.Browser.DEBUG;
161 private final static boolean LOGV_ENABLED = com.android.browser.Browser.LOGV_ENABLED;
162 private final static boolean LOGD_ENABLED = com.android.browser.Browser.LOGD_ENABLED;
163
The Android Open Source Project0c908882009-03-03 19:32:16 -0800164 private IGoogleLoginService mGls = null;
165 private ServiceConnection mGlsConnection = null;
166
167 private SensorManager mSensorManager = null;
168
Satish Sampath565505b2009-05-29 15:37:27 +0100169 // These are single-character shortcuts for searching popular sources.
170 private static final int SHORTCUT_INVALID = 0;
171 private static final int SHORTCUT_GOOGLE_SEARCH = 1;
172 private static final int SHORTCUT_WIKIPEDIA_SEARCH = 2;
173 private static final int SHORTCUT_DICTIONARY_SEARCH = 3;
174 private static final int SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH = 4;
175
The Android Open Source Project0c908882009-03-03 19:32:16 -0800176 /* Whitelisted webpages
177 private static HashSet<String> sWhiteList;
178
179 static {
180 sWhiteList = new HashSet<String>();
181 sWhiteList.add("cnn.com/");
182 sWhiteList.add("espn.go.com/");
183 sWhiteList.add("nytimes.com/");
184 sWhiteList.add("engadget.com/");
185 sWhiteList.add("yahoo.com/");
186 sWhiteList.add("msn.com/");
187 sWhiteList.add("amazon.com/");
188 sWhiteList.add("consumerist.com/");
189 sWhiteList.add("google.com/m/news");
190 }
191 */
192
193 private void setupHomePage() {
194 final Runnable getAccount = new Runnable() {
195 public void run() {
196 // Lower priority
197 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
198 // get the default home page
199 String homepage = mSettings.getHomePage();
200
201 try {
202 if (mGls == null) return;
203
Grace Klobaf2c5c1b2009-05-26 10:48:31 -0700204 if (!homepage.startsWith("http://www.google.")) return;
205 if (homepage.indexOf('?') == -1) return;
206
The Android Open Source Project0c908882009-03-03 19:32:16 -0800207 String hostedUser = mGls.getAccount(GoogleLoginServiceConstants.PREFER_HOSTED);
208 String googleUser = mGls.getAccount(GoogleLoginServiceConstants.REQUIRE_GOOGLE);
209
210 // three cases:
211 //
212 // hostedUser == googleUser
213 // The device has only a google account
214 //
215 // hostedUser != googleUser
216 // The device has a hosted account and a google account
217 //
218 // hostedUser != null, googleUser == null
219 // The device has only a hosted account (so far)
220
221 // developers might have no accounts at all
222 if (hostedUser == null) return;
223
224 if (googleUser == null || !hostedUser.equals(googleUser)) {
225 String domain = hostedUser.substring(hostedUser.lastIndexOf('@')+1);
Grace Klobaf2c5c1b2009-05-26 10:48:31 -0700226 homepage = homepage.replace("?", "/a/" + domain + "?");
The Android Open Source Project0c908882009-03-03 19:32:16 -0800227 }
228 } catch (RemoteException ignore) {
229 // Login service died; carry on
230 } catch (RuntimeException ignore) {
231 // Login service died; carry on
232 } finally {
233 finish(homepage);
234 }
235 }
236
237 private void finish(final String homepage) {
238 mHandler.post(new Runnable() {
239 public void run() {
240 mSettings.setHomePage(BrowserActivity.this, homepage);
241 resumeAfterCredentials();
242
243 // as this is running in a separate thread,
244 // BrowserActivity's onDestroy() may have been called,
245 // which also calls unbindService().
246 if (mGlsConnection != null) {
247 // we no longer need to keep GLS open
248 unbindService(mGlsConnection);
249 mGlsConnection = null;
250 }
251 } });
252 } };
253
254 final boolean[] done = { false };
255
256 // Open a connection to the Google Login Service. The first
257 // time the connection is established, set up the homepage depending on
258 // the account in a background thread.
259 mGlsConnection = new ServiceConnection() {
260 public void onServiceConnected(ComponentName className, IBinder service) {
261 mGls = IGoogleLoginService.Stub.asInterface(service);
262 if (done[0] == false) {
263 done[0] = true;
264 Thread account = new Thread(getAccount);
265 account.setName("GLSAccount");
266 account.start();
267 }
268 }
269 public void onServiceDisconnected(ComponentName className) {
270 mGls = null;
271 }
272 };
273
274 bindService(GoogleLoginServiceConstants.SERVICE_INTENT,
275 mGlsConnection, Context.BIND_AUTO_CREATE);
276 }
277
Cary Clarka9771242009-08-11 16:42:26 -0400278 private static class ClearThumbnails extends AsyncTask<File, Void, Void> {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800279 @Override
280 public Void doInBackground(File... files) {
281 if (files != null) {
282 for (File f : files) {
Cary Clarkd6be1752009-08-12 12:56:42 -0400283 if (!f.delete()) {
284 Log.e(LOGTAG, f.getPath() + " was not deleted");
285 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800286 }
287 }
288 return null;
289 }
290 }
291
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400292 /**
293 * This layout holds everything you see below the status bar, including the
294 * error console, the custom view container, and the webviews.
295 */
296 private FrameLayout mBrowserFrameLayout;
Leon Scroggins81db3662009-06-04 17:45:11 -0400297
The Android Open Source Project0c908882009-03-03 19:32:16 -0800298 @Override public void onCreate(Bundle icicle) {
Dave Bort31a6d1c2009-04-13 15:56:49 -0700299 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800300 Log.v(LOGTAG, this + " onStart");
301 }
302 super.onCreate(icicle);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800303 // test the browser in OpenGL
304 // requestWindowFeature(Window.FEATURE_OPENGL);
305
306 setDefaultKeyMode(DEFAULT_KEYS_SEARCH_LOCAL);
307
308 mResolver = getContentResolver();
309
Grace Kloba0923d692009-09-23 21:37:25 -0700310 // If this was a web search request, pass it on to the default web
311 // search provider and finish this activity.
312 if (handleWebSearchIntent(getIntent())) {
313 finish();
314 return;
315 }
316
The Android Open Source Project0c908882009-03-03 19:32:16 -0800317 //
318 // start MASF proxy service
319 //
320 //Intent proxyServiceIntent = new Intent();
321 //proxyServiceIntent.setComponent
322 // (new ComponentName(
323 // "com.android.masfproxyservice",
324 // "com.android.masfproxyservice.MasfProxyService"));
325 //startService(proxyServiceIntent, null);
326
327 mSecLockIcon = Resources.getSystem().getDrawable(
328 android.R.drawable.ic_secure);
329 mMixLockIcon = Resources.getSystem().getDrawable(
330 android.R.drawable.ic_partial_secure);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800331
Leon Scroggins81db3662009-06-04 17:45:11 -0400332 FrameLayout frameLayout = (FrameLayout) getWindow().getDecorView()
333 .findViewById(com.android.internal.R.id.content);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400334 mBrowserFrameLayout = (FrameLayout) LayoutInflater.from(this)
335 .inflate(R.layout.custom_screen, null);
336 mContentView = (FrameLayout) mBrowserFrameLayout.findViewById(
337 R.id.main_content);
338 mErrorConsoleContainer = (LinearLayout) mBrowserFrameLayout
339 .findViewById(R.id.error_console);
340 mCustomViewContainer = (FrameLayout) mBrowserFrameLayout
341 .findViewById(R.id.fullscreen_custom_content);
342 frameLayout.addView(mBrowserFrameLayout, COVER_SCREEN_PARAMS);
Leon Scroggins68579392009-09-15 15:31:54 -0400343 mTitleBar = new TitleBar(this);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800344
345 // Create the tab control and our initial tab
346 mTabControl = new TabControl(this);
347
348 // Open the icon database and retain all the bookmark urls for favicons
349 retainIconsOnStartup();
350
351 // Keep a settings instance handy.
352 mSettings = BrowserSettings.getInstance();
353 mSettings.setTabControl(mTabControl);
354 mSettings.loadFromDb(this);
355
356 PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
357 mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Browser");
358
Grace Klobaa34f6862009-07-31 16:28:17 -0700359 /* enables registration for changes in network status from
360 http stack */
361 mNetworkStateChangedFilter = new IntentFilter();
362 mNetworkStateChangedFilter.addAction(
363 ConnectivityManager.CONNECTIVITY_ACTION);
364 mNetworkStateIntentReceiver = new BroadcastReceiver() {
365 @Override
366 public void onReceive(Context context, Intent intent) {
367 if (intent.getAction().equals(
368 ConnectivityManager.CONNECTIVITY_ACTION)) {
Patrick Scotteb6ab2a2009-09-16 10:00:17 -0400369 NetworkInfo info =
370 (NetworkInfo) intent.getParcelableExtra(
371 ConnectivityManager.EXTRA_NETWORK_INFO);
372 onNetworkToggle(
373 (info != null) ? info.isConnected() : false);
Grace Klobaa34f6862009-07-31 16:28:17 -0700374 }
375 }
376 };
377
Grace Kloba615c6c92009-08-03 10:22:44 -0700378 IntentFilter filter = new IntentFilter(Intent.ACTION_PACKAGE_ADDED);
379 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
380 filter.addDataScheme("package");
381 mPackageInstallationReceiver = new BroadcastReceiver() {
382 @Override
383 public void onReceive(Context context, Intent intent) {
384 final String action = intent.getAction();
385 final String packageName = intent.getData()
386 .getSchemeSpecificPart();
387 final boolean replacing = intent.getBooleanExtra(
388 Intent.EXTRA_REPLACING, false);
389 if (Intent.ACTION_PACKAGE_REMOVED.equals(action) && replacing) {
390 // if it is replacing, refreshPlugins() when adding
391 return;
392 }
393 PackageManager pm = BrowserActivity.this.getPackageManager();
394 PackageInfo pkgInfo = null;
395 try {
396 pkgInfo = pm.getPackageInfo(packageName,
397 PackageManager.GET_PERMISSIONS);
398 } catch (PackageManager.NameNotFoundException e) {
399 return;
400 }
401 if (pkgInfo != null) {
402 String permissions[] = pkgInfo.requestedPermissions;
403 if (permissions == null) {
404 return;
405 }
406 boolean permissionOk = false;
407 for (String permit : permissions) {
408 if (PluginManager.PLUGIN_PERMISSION.equals(permit)) {
409 permissionOk = true;
410 break;
411 }
412 }
413 if (permissionOk) {
414 PluginManager.getInstance(BrowserActivity.this)
415 .refreshPlugins(
416 Intent.ACTION_PACKAGE_ADDED
417 .equals(action));
418 }
419 }
420 }
421 };
422 registerReceiver(mPackageInstallationReceiver, filter);
423
The Android Open Source Project0c908882009-03-03 19:32:16 -0800424 if (!mTabControl.restoreState(icicle)) {
425 // clear up the thumbnail directory if we can't restore the state as
426 // none of the files in the directory are referenced any more.
427 new ClearThumbnails().execute(
428 mTabControl.getThumbnailDir().listFiles());
Grace Klobaaab3f092009-07-30 12:29:51 -0700429 // there is no quit on Android. But if we can't restore the state,
430 // we can treat it as a new Browser, remove the old session cookies.
431 CookieManager.getInstance().removeSessionCookie();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800432 final Intent intent = getIntent();
433 final Bundle extra = intent.getExtras();
434 // Create an initial tab.
435 // If the intent is ACTION_VIEW and data is not null, the Browser is
436 // invoked to view the content by another application. In this case,
437 // the tab will be close when exit.
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700438 UrlData urlData = getUrlDataFromIntent(intent);
439
The Android Open Source Project0c908882009-03-03 19:32:16 -0800440 final TabControl.Tab t = mTabControl.createNewTab(
441 Intent.ACTION_VIEW.equals(intent.getAction()) &&
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700442 intent.getData() != null,
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700443 intent.getStringExtra(Browser.EXTRA_APPLICATION_ID), urlData.mUrl);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800444 mTabControl.setCurrentTab(t);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800445 attachTabToContentView(t);
446 WebView webView = t.getWebView();
447 if (extra != null) {
448 int scale = extra.getInt(Browser.INITIAL_ZOOM_LEVEL, 0);
449 if (scale > 0 && scale <= 1000) {
450 webView.setInitialScale(scale);
451 }
452 }
453 // If we are not restoring from an icicle, then there is a high
454 // likely hood this is the first run. So, check to see if the
455 // homepage needs to be configured and copy any plugins from our
456 // asset directory to the data partition.
457 if ((extra == null || !extra.getBoolean("testing"))
458 && !mSettings.isLoginInitialized()) {
459 setupHomePage();
460 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800461
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700462 if (urlData.isEmpty()) {
Leon Scroggins30444232009-09-04 18:36:20 -0400463 if (mSettings.isLoginInitialized()) {
464 webView.loadUrl(mSettings.getHomePage());
465 } else {
466 waitForCredentials();
467 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800468 } else {
Grace Kloba81678d92009-06-30 07:09:56 -0700469 if (extra != null) {
470 urlData.setPostData(extra
471 .getByteArray(Browser.EXTRA_POST_DATA));
472 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700473 urlData.loadIn(webView);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800474 }
475 } else {
476 // TabControl.restoreState() will create a new tab even if
Leon Scroggins1f005d32009-08-10 17:36:42 -0400477 // restoring the state fails.
The Android Open Source Project0c908882009-03-03 19:32:16 -0800478 attachTabToContentView(mTabControl.getCurrentTab());
479 }
Grace Kloba615c6c92009-08-03 10:22:44 -0700480
Feng Qianb3c02da2009-06-29 15:58:08 -0700481 // Read JavaScript flags if it exists.
482 String jsFlags = mSettings.getJsFlags();
483 if (jsFlags.trim().length() != 0) {
484 mTabControl.getCurrentWebView().setJsFlags(jsFlags);
485 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800486 }
487
488 @Override
489 protected void onNewIntent(Intent intent) {
490 TabControl.Tab current = mTabControl.getCurrentTab();
491 // When a tab is closed on exit, the current tab index is set to -1.
492 // Reset before proceed as Browser requires the current tab to be set.
493 if (current == null) {
494 // Try to reset the tab in case the index was incorrect.
495 current = mTabControl.getTab(0);
496 if (current == null) {
497 // No tabs at all so just ignore this intent.
498 return;
499 }
500 mTabControl.setCurrentTab(current);
501 attachTabToContentView(current);
502 resetTitleAndIcon(current.getWebView());
503 }
504 final String action = intent.getAction();
505 final int flags = intent.getFlags();
506 if (Intent.ACTION_MAIN.equals(action) ||
507 (flags & Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY) != 0) {
508 // just resume the browser
509 return;
510 }
511 if (Intent.ACTION_VIEW.equals(action)
512 || Intent.ACTION_SEARCH.equals(action)
513 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
514 || Intent.ACTION_WEB_SEARCH.equals(action)) {
Satish Sampath565505b2009-05-29 15:37:27 +0100515 // If this was a search request (e.g. search query directly typed into the address bar),
516 // pass it on to the default web search provider.
517 if (handleWebSearchIntent(intent)) {
518 return;
519 }
520
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700521 UrlData urlData = getUrlDataFromIntent(intent);
522 if (urlData.isEmpty()) {
523 urlData = new UrlData(mSettings.getHomePage());
The Android Open Source Project0c908882009-03-03 19:32:16 -0800524 }
Grace Kloba81678d92009-06-30 07:09:56 -0700525 urlData.setPostData(intent
526 .getByteArrayExtra(Browser.EXTRA_POST_DATA));
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700527
Grace Klobacc634032009-07-28 15:58:19 -0700528 final String appId = intent
529 .getStringExtra(Browser.EXTRA_APPLICATION_ID);
530 if (Intent.ACTION_VIEW.equals(action)
531 && !getPackageName().equals(appId)
532 && (flags & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0) {
Patrick Scottcd115892009-07-16 09:42:58 -0400533 TabControl.Tab appTab = mTabControl.getTabFromId(appId);
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700534 if (appTab != null) {
535 Log.i(LOGTAG, "Reusing tab for " + appId);
536 // Dismiss the subwindow if applicable.
537 dismissSubWindow(appTab);
538 // Since we might kill the WebView, remove it from the
539 // content view first.
540 removeTabFromContentView(appTab);
541 // Recreate the main WebView after destroying the old one.
542 // If the WebView has the same original url and is on that
543 // page, it can be reused.
544 boolean needsLoad =
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700545 mTabControl.recreateWebView(appTab, urlData.mUrl);
Ben Murdochbff2d602009-07-01 20:19:05 +0100546
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700547 if (current != appTab) {
Leon Scroggins1f005d32009-08-10 17:36:42 -0400548 switchToTab(mTabControl.getTabIndex(appTab));
549 if (needsLoad) {
550 urlData.loadIn(appTab.getWebView());
551 }
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700552 } else {
Leon Scroggins1f005d32009-08-10 17:36:42 -0400553 // If the tab was the current tab, we have to attach
554 // it to the view system again.
555 attachTabToContentView(appTab);
556 if (needsLoad) {
557 urlData.loadIn(appTab.getWebView());
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700558 }
559 }
560 return;
Patrick Scottcd115892009-07-16 09:42:58 -0400561 } else {
562 // No matching application tab, try to find a regular tab
563 // with a matching url.
564 appTab = mTabControl.findUnusedTabWithUrl(urlData.mUrl);
Leon Scroggins25515f82009-08-19 15:31:58 -0400565 if (appTab != null) {
566 if (current != appTab) {
567 switchToTab(mTabControl.getTabIndex(appTab));
568 }
569 // Otherwise, we are already viewing the correct tab.
Patrick Scottcd115892009-07-16 09:42:58 -0400570 } else {
571 // if FLAG_ACTIVITY_BROUGHT_TO_FRONT flag is on, the url
572 // will be opened in a new tab unless we have reached
573 // MAX_TABS. Then the url will be opened in the current
574 // tab. If a new tab is created, it will have "true" for
575 // exit on close.
Leon Scroggins1f005d32009-08-10 17:36:42 -0400576 openTabAndShow(urlData, true, appId);
Patrick Scottcd115892009-07-16 09:42:58 -0400577 }
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700578 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800579 } else {
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700580 if ("about:debug".equals(urlData.mUrl)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800581 mSettings.toggleDebugSettings();
582 return;
583 }
Leon Scroggins1f005d32009-08-10 17:36:42 -0400584 // Get rid of the subwindow if it exists
585 dismissSubWindow(current);
586 urlData.loadIn(current.getWebView());
The Android Open Source Project0c908882009-03-03 19:32:16 -0800587 }
588 }
589 }
590
Satish Sampath565505b2009-05-29 15:37:27 +0100591 private int parseUrlShortcut(String url) {
592 if (url == null) return SHORTCUT_INVALID;
593
594 // FIXME: quick search, need to be customized by setting
595 if (url.length() > 2 && url.charAt(1) == ' ') {
596 switch (url.charAt(0)) {
597 case 'g': return SHORTCUT_GOOGLE_SEARCH;
598 case 'w': return SHORTCUT_WIKIPEDIA_SEARCH;
599 case 'd': return SHORTCUT_DICTIONARY_SEARCH;
600 case 'l': return SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH;
601 }
602 }
603 return SHORTCUT_INVALID;
604 }
605
606 /**
607 * Launches the default web search activity with the query parameters if the given intent's data
608 * are identified as plain search terms and not URLs/shortcuts.
609 * @return true if the intent was handled and web search activity was launched, false if not.
610 */
611 private boolean handleWebSearchIntent(Intent intent) {
612 if (intent == null) return false;
613
614 String url = null;
615 final String action = intent.getAction();
616 if (Intent.ACTION_VIEW.equals(action)) {
Grace Kloba1e705052009-09-29 13:13:36 -0700617 Uri data = intent.getData();
618 if (data != null) url = data.toString();
Satish Sampath565505b2009-05-29 15:37:27 +0100619 } else if (Intent.ACTION_SEARCH.equals(action)
620 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
621 || Intent.ACTION_WEB_SEARCH.equals(action)) {
622 url = intent.getStringExtra(SearchManager.QUERY);
623 }
Bjorn Bringert04851702009-09-22 10:36:01 +0100624 return handleWebSearchRequest(url, intent.getBundleExtra(SearchManager.APP_DATA),
625 intent.getStringExtra(SearchManager.EXTRA_DATA_KEY));
Satish Sampath565505b2009-05-29 15:37:27 +0100626 }
627
628 /**
629 * Launches the default web search activity with the query parameters if the given url string
630 * was identified as plain search terms and not URL/shortcut.
631 * @return true if the request was handled and web search activity was launched, false if not.
632 */
Bjorn Bringert04851702009-09-22 10:36:01 +0100633 private boolean handleWebSearchRequest(String inUrl, Bundle appData, String extraData) {
Satish Sampath565505b2009-05-29 15:37:27 +0100634 if (inUrl == null) return false;
635
636 // In general, we shouldn't modify URL from Intent.
637 // But currently, we get the user-typed URL from search box as well.
638 String url = fixUrl(inUrl).trim();
639
640 // URLs and site specific search shortcuts are handled by the regular flow of control, so
641 // return early.
642 if (Regex.WEB_URL_PATTERN.matcher(url).matches()
Satish Sampathbc5b9f32009-06-04 18:21:40 +0100643 || ACCEPTED_URI_SCHEMA.matcher(url).matches()
Satish Sampath565505b2009-05-29 15:37:27 +0100644 || parseUrlShortcut(url) != SHORTCUT_INVALID) {
645 return false;
646 }
647
648 Browser.updateVisitedHistory(mResolver, url, false);
649 Browser.addSearchUrl(mResolver, url);
650
651 Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);
652 intent.addCategory(Intent.CATEGORY_DEFAULT);
653 intent.putExtra(SearchManager.QUERY, url);
Satish Sampath15e9f2d2009-06-23 22:29:49 +0100654 if (appData != null) {
655 intent.putExtra(SearchManager.APP_DATA, appData);
656 }
Bjorn Bringert04851702009-09-22 10:36:01 +0100657 if (extraData != null) {
658 intent.putExtra(SearchManager.EXTRA_DATA_KEY, extraData);
659 }
Grace Klobacc634032009-07-28 15:58:19 -0700660 intent.putExtra(Browser.EXTRA_APPLICATION_ID, getPackageName());
Satish Sampath565505b2009-05-29 15:37:27 +0100661 startActivity(intent);
662
663 return true;
664 }
665
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700666 private UrlData getUrlDataFromIntent(Intent intent) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800667 String url = null;
668 if (intent != null) {
669 final String action = intent.getAction();
670 if (Intent.ACTION_VIEW.equals(action)) {
671 url = smartUrlFilter(intent.getData());
672 if (url != null && url.startsWith("content:")) {
673 /* Append mimetype so webview knows how to display */
674 String mimeType = intent.resolveType(getContentResolver());
675 if (mimeType != null) {
676 url += "?" + mimeType;
677 }
678 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700679 if ("inline:".equals(url)) {
680 return new InlinedUrlData(
681 intent.getStringExtra(Browser.EXTRA_INLINE_CONTENT),
682 intent.getType(),
683 intent.getStringExtra(Browser.EXTRA_INLINE_ENCODING),
684 intent.getStringExtra(Browser.EXTRA_INLINE_FAILURL));
685 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800686 } else if (Intent.ACTION_SEARCH.equals(action)
687 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
688 || Intent.ACTION_WEB_SEARCH.equals(action)) {
689 url = intent.getStringExtra(SearchManager.QUERY);
690 if (url != null) {
691 mLastEnteredUrl = url;
692 // Don't add Urls, just search terms.
693 // Urls will get added when the page is loaded.
694 if (!Regex.WEB_URL_PATTERN.matcher(url).matches()) {
695 Browser.updateVisitedHistory(mResolver, url, false);
696 }
697 // In general, we shouldn't modify URL from Intent.
698 // But currently, we get the user-typed URL from search box as well.
699 url = fixUrl(url);
700 url = smartUrlFilter(url);
701 String searchSource = "&source=android-" + GOOGLE_SEARCH_SOURCE_SUGGEST + "&";
702 if (url.contains(searchSource)) {
703 String source = null;
704 final Bundle appData = intent.getBundleExtra(SearchManager.APP_DATA);
705 if (appData != null) {
706 source = appData.getString(SearchManager.SOURCE);
707 }
708 if (TextUtils.isEmpty(source)) {
709 source = GOOGLE_SEARCH_SOURCE_UNKNOWN;
710 }
711 url = url.replace(searchSource, "&source=android-"+source+"&");
712 }
713 }
714 }
715 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700716 return new UrlData(url);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800717 }
718
719 /* package */ static String fixUrl(String inUrl) {
Cary Clark652ff872009-09-10 13:34:44 -0400720 // FIXME: Converting the url to lower case
721 // duplicates functionality in smartUrlFilter().
722 // However, changing all current callers of fixUrl to
723 // call smartUrlFilter in addition may have unwanted
724 // consequences, and is deferred for now.
725 int colon = inUrl.indexOf(':');
726 boolean allLower = true;
727 for (int index = 0; index < colon; index++) {
728 char ch = inUrl.charAt(index);
729 if (!Character.isLetter(ch)) {
730 break;
731 }
732 allLower &= Character.isLowerCase(ch);
733 if (index == colon - 1 && !allLower) {
734 inUrl = inUrl.substring(0, colon).toLowerCase()
735 + inUrl.substring(colon);
736 }
737 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800738 if (inUrl.startsWith("http://") || inUrl.startsWith("https://"))
739 return inUrl;
740 if (inUrl.startsWith("http:") ||
741 inUrl.startsWith("https:")) {
742 if (inUrl.startsWith("http:/") || inUrl.startsWith("https:/")) {
743 inUrl = inUrl.replaceFirst("/", "//");
744 } else inUrl = inUrl.replaceFirst(":", "://");
745 }
746 return inUrl;
747 }
748
749 /**
750 * Looking for the pattern like this
751 *
752 * *
753 * * *
754 * *** * *******
755 * * *
756 * * *
757 * *
758 */
759 private final SensorListener mSensorListener = new SensorListener() {
760 private long mLastGestureTime;
761 private float[] mPrev = new float[3];
762 private float[] mPrevDiff = new float[3];
763 private float[] mDiff = new float[3];
764 private float[] mRevertDiff = new float[3];
765
766 public void onSensorChanged(int sensor, float[] values) {
767 boolean show = false;
768 float[] diff = new float[3];
769
770 for (int i = 0; i < 3; i++) {
771 diff[i] = values[i] - mPrev[i];
772 if (Math.abs(diff[i]) > 1) {
773 show = true;
774 }
775 if ((diff[i] > 1.0 && mDiff[i] < 0.2)
776 || (diff[i] < -1.0 && mDiff[i] > -0.2)) {
777 // start track when there is a big move, or revert
778 mRevertDiff[i] = mDiff[i];
779 mDiff[i] = 0;
780 } else if (diff[i] > -0.2 && diff[i] < 0.2) {
781 // reset when it is flat
782 mDiff[i] = mRevertDiff[i] = 0;
783 }
784 mDiff[i] += diff[i];
785 mPrevDiff[i] = diff[i];
786 mPrev[i] = values[i];
787 }
788
789 if (false) {
790 // only shows if we think the delta is big enough, in an attempt
791 // to detect "serious" moves left/right or up/down
792 Log.d("BrowserSensorHack", "sensorChanged " + sensor + " ("
793 + values[0] + ", " + values[1] + ", " + values[2] + ")"
794 + " diff(" + diff[0] + " " + diff[1] + " " + diff[2]
795 + ")");
796 Log.d("BrowserSensorHack", " mDiff(" + mDiff[0] + " "
797 + mDiff[1] + " " + mDiff[2] + ")" + " mRevertDiff("
798 + mRevertDiff[0] + " " + mRevertDiff[1] + " "
799 + mRevertDiff[2] + ")");
800 }
801
802 long now = android.os.SystemClock.uptimeMillis();
803 if (now - mLastGestureTime > 1000) {
804 mLastGestureTime = 0;
805
806 float y = mDiff[1];
807 float z = mDiff[2];
808 float ay = Math.abs(y);
809 float az = Math.abs(z);
810 float ry = mRevertDiff[1];
811 float rz = mRevertDiff[2];
812 float ary = Math.abs(ry);
813 float arz = Math.abs(rz);
814 boolean gestY = ay > 2.5f && ary > 1.0f && ay > ary;
815 boolean gestZ = az > 3.5f && arz > 1.0f && az > arz;
816
817 if ((gestY || gestZ) && !(gestY && gestZ)) {
818 WebView view = mTabControl.getCurrentWebView();
819
820 if (view != null) {
821 if (gestZ) {
822 if (z < 0) {
823 view.zoomOut();
824 } else {
825 view.zoomIn();
826 }
827 } else {
828 view.flingScroll(0, Math.round(y * 100));
829 }
830 }
831 mLastGestureTime = now;
832 }
833 }
834 }
835
836 public void onAccuracyChanged(int sensor, int accuracy) {
837 // TODO Auto-generated method stub
838
839 }
840 };
841
842 @Override protected void onResume() {
843 super.onResume();
Dave Bort31a6d1c2009-04-13 15:56:49 -0700844 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800845 Log.v(LOGTAG, "BrowserActivity.onResume: this=" + this);
846 }
847
848 if (!mActivityInPause) {
849 Log.e(LOGTAG, "BrowserActivity is already resumed.");
850 return;
851 }
852
Mike Reed7bfa63b2009-05-28 11:08:32 -0400853 mTabControl.resumeCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800854 mActivityInPause = false;
Mike Reed7bfa63b2009-05-28 11:08:32 -0400855 resumeWebViewTimers();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800856
857 if (mWakeLock.isHeld()) {
858 mHandler.removeMessages(RELEASE_WAKELOCK);
859 mWakeLock.release();
860 }
861
862 if (mCredsDlg != null) {
863 if (!mHandler.hasMessages(CANCEL_CREDS_REQUEST)) {
864 // In case credential request never comes back
865 mHandler.sendEmptyMessageDelayed(CANCEL_CREDS_REQUEST, 6000);
866 }
867 }
868
869 registerReceiver(mNetworkStateIntentReceiver,
870 mNetworkStateChangedFilter);
871 WebView.enablePlatformNotifications();
872
873 if (mSettings.doFlick()) {
874 if (mSensorManager == null) {
875 mSensorManager = (SensorManager) getSystemService(
876 Context.SENSOR_SERVICE);
877 }
878 mSensorManager.registerListener(mSensorListener,
879 SensorManager.SENSOR_ACCELEROMETER,
880 SensorManager.SENSOR_DELAY_FASTEST);
881 } else {
882 mSensorManager = null;
883 }
884 }
885
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400886 /**
887 * Since the actual title bar is embedded in the WebView, and removing it
888 * would change its appearance, create a temporary title bar to go at
889 * the top of the screen while the menu is open.
890 */
891 private TitleBar mFakeTitleBar;
892
893 /**
Leon Scrogginsd8fd2fc2009-09-16 11:12:09 -0400894 * Holder for the fake title bar. It will have a foreground shadow, as well
895 * as a white background, so the fake title bar looks like the real one.
896 */
897 private ViewGroup mFakeTitleBarHolder;
898
899 /**
900 * Layout parameters for the fake title bar within mFakeTitleBarHolder
901 */
902 private FrameLayout.LayoutParams mFakeTitleBarParams
903 = new FrameLayout.LayoutParams(
Leon Scrogginsc01e4a82009-09-16 14:41:00 -0400904 ViewGroup.LayoutParams.FILL_PARENT,
Leon Scrogginsd8fd2fc2009-09-16 11:12:09 -0400905 ViewGroup.LayoutParams.WRAP_CONTENT);
906 /**
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400907 * Keeps track of whether the options menu is open. This is important in
908 * determining whether to show or hide the title bar overlay.
909 */
910 private boolean mOptionsMenuOpen;
911
912 /**
913 * Only meaningful when mOptionsMenuOpen is true. This variable keeps track
914 * of whether the configuration has changed. The first onMenuOpened call
915 * after a configuration change is simply a reopening of the same menu
916 * (i.e. mIconView did not change).
917 */
918 private boolean mConfigChanged;
919
920 /**
921 * Whether or not the options menu is in its smaller, icon menu form. When
922 * true, we want the title bar overlay to be up. When false, we do not.
923 * Only meaningful if mOptionsMenuOpen is true.
924 */
925 private boolean mIconView;
926
Leon Scrogginsa81a7642009-08-31 17:05:41 -0400927 @Override
928 public boolean onMenuOpened(int featureId, Menu menu) {
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400929 if (Window.FEATURE_OPTIONS_PANEL == featureId) {
930 if (mOptionsMenuOpen) {
931 if (mConfigChanged) {
932 // We do not need to make any changes to the state of the
933 // title bar, since the only thing that happened was a
934 // change in orientation
935 mConfigChanged = false;
936 } else {
937 if (mIconView) {
938 // Switching the menu to expanded view, so hide the
939 // title bar.
940 hideFakeTitleBar();
941 mIconView = false;
942 } else {
943 // Switching the menu back to icon view, so show the
944 // title bar once again.
945 showFakeTitleBar();
946 mIconView = true;
947 }
948 }
949 } else {
950 // The options menu is closed, so open it, and show the title
951 showFakeTitleBar();
952 mOptionsMenuOpen = true;
953 mConfigChanged = false;
954 mIconView = true;
955 }
956 }
Leon Scrogginsa81a7642009-08-31 17:05:41 -0400957 return true;
958 }
959
Leon Scrogginsb94bf272009-09-25 15:22:08 -0400960 /**
961 * Special class used exclusively for the shadow drawn underneath the fake
962 * title bar. The shadow does not need to be drawn if the WebView
963 * underneath is scrolled to the top, because it will draw directly on top
964 * of the embedded shadow.
965 */
966 private static class Shadow extends View {
967 private WebView mWebView;
968
969 public Shadow(Context context, AttributeSet attrs) {
970 super(context, attrs);
971 }
972
973 public void setWebView(WebView view) {
974 mWebView = view;
975 }
976
977 @Override
978 public void draw(Canvas canvas) {
979 // In general onDraw is the method to override, but we care about
980 // whether or not the background gets drawn, which happens in draw()
981 if (mWebView == null || mWebView.getScrollY() > getHeight()) {
982 super.draw(canvas);
983 }
984 // Need to invalidate so that if the scroll position changes, we
985 // still draw as appropriate.
986 invalidate();
987 }
988 }
989
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400990 private void showFakeTitleBar() {
Patrick Scottf8de8ec2009-09-21 16:37:29 -0400991 final View decor = getWindow().peekDecorView();
Leon Scroggins4d7e4062009-09-15 15:49:45 -0400992 if (mFakeTitleBar == null && mActiveTabsPage == null
Patrick Scottf8de8ec2009-09-21 16:37:29 -0400993 && !mActivityInPause && decor != null
994 && decor.getWindowToken() != null) {
Cary Clarka0464552009-09-29 13:00:45 -0400995 Rect visRect = new Rect();
996 if (!mBrowserFrameLayout.getGlobalVisibleRect(visRect)) {
997 if (LOGD_ENABLED) {
998 Log.d(LOGTAG, "showFakeTitleBar visRect failed");
999 }
1000 return;
1001 }
Leon Scrogginsf4bb18a2009-09-11 18:37:53 -04001002 final WebView webView = getTopWindow();
Leon Scroggins68579392009-09-15 15:31:54 -04001003 mFakeTitleBar = new TitleBar(this);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04001004 mFakeTitleBar.setTitleAndUrl(null, webView.getUrl());
1005 mFakeTitleBar.setProgress(webView.getProgress());
1006 mFakeTitleBar.setFavicon(webView.getFavicon());
1007 updateLockIconToLatest();
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04001008
1009 WindowManager manager
1010 = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
1011
1012 // Add the title bar to the window manager so it can receive touches
1013 // while the menu is up
1014 WindowManager.LayoutParams params
1015 = new WindowManager.LayoutParams(
1016 ViewGroup.LayoutParams.FILL_PARENT,
1017 ViewGroup.LayoutParams.WRAP_CONTENT,
1018 WindowManager.LayoutParams.TYPE_APPLICATION_SUB_PANEL,
1019 WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
Leon Scroggins68549862009-09-21 16:02:01 -04001020 PixelFormat.TRANSLUCENT);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04001021 params.gravity = Gravity.TOP;
Leon Scrogginsa27ff192009-09-14 12:58:04 -04001022 WebView mainView = mTabControl.getCurrentWebView();
Leon Scroggins68549862009-09-21 16:02:01 -04001023 boolean atTop = mainView != null && mainView.getScrollY() == 0;
Leon Scroggins83932c72009-09-30 11:55:54 -04001024 params.windowAnimations = atTop ? 0 : R.style.TitleBar;
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04001025 // XXX : Without providing an offset, the fake title bar will be
1026 // placed underneath the status bar. Use the global visible rect
1027 // of mBrowserFrameLayout to determine the bottom of the status bar
Cary Clarka0464552009-09-29 13:00:45 -04001028 params.y = visRect.top;
Leon Scroggins68549862009-09-21 16:02:01 -04001029 // Add a holder for the title bar. It also holds a shadow to show
1030 // below the title bar.
Leon Scrogginsd8fd2fc2009-09-16 11:12:09 -04001031 if (mFakeTitleBarHolder == null) {
1032 mFakeTitleBarHolder = (ViewGroup) LayoutInflater.from(this)
1033 .inflate(R.layout.title_bar_bg, null);
1034 }
Leon Scrogginsb94bf272009-09-25 15:22:08 -04001035 Shadow shadow = (Shadow) mFakeTitleBarHolder.findViewById(
1036 R.id.shadow);
1037 shadow.setWebView(mainView);
Leon Scroggins68549862009-09-21 16:02:01 -04001038 mFakeTitleBarHolder.addView(mFakeTitleBar, 0, mFakeTitleBarParams);
Leon Scrogginsd8fd2fc2009-09-16 11:12:09 -04001039 manager.addView(mFakeTitleBarHolder, params);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04001040 }
1041 }
1042
1043 @Override
1044 public void onOptionsMenuClosed(Menu menu) {
1045 mOptionsMenuOpen = false;
Leon Scrogginsa27ff192009-09-14 12:58:04 -04001046 if (!mInLoad) {
1047 hideFakeTitleBar();
1048 } else if (!mIconView) {
1049 // The page is currently loading, and we are in expanded mode, so
1050 // we were not showing the menu. Show it once again. It will be
1051 // removed when the page finishes.
1052 showFakeTitleBar();
1053 }
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04001054 }
1055 private void hideFakeTitleBar() {
1056 if (mFakeTitleBar == null) return;
Leon Scroggins20329572009-09-23 17:42:41 -04001057 WindowManager.LayoutParams params = (WindowManager.LayoutParams)
1058 mFakeTitleBarHolder.getLayoutParams();
1059 WebView mainView = mTabControl.getCurrentWebView();
1060 // Although we decided whether or not to animate based on the current
1061 // scroll position, the scroll position may have changed since the
1062 // fake title bar was displayed. Make sure it has the appropriate
1063 // animation/lack thereof before removing.
1064 params.windowAnimations = mainView != null && mainView.getScrollY() == 0
Leon Scroggins83932c72009-09-30 11:55:54 -04001065 ? 0 : R.style.TitleBar;
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04001066 WindowManager manager
1067 = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
Leon Scroggins20329572009-09-23 17:42:41 -04001068 manager.updateViewLayout(mFakeTitleBarHolder, params);
Leon Scrogginsd8fd2fc2009-09-16 11:12:09 -04001069 mFakeTitleBarHolder.removeView(mFakeTitleBar);
1070 manager.removeView(mFakeTitleBarHolder);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04001071 mFakeTitleBar = null;
1072 }
1073
The Android Open Source Project0c908882009-03-03 19:32:16 -08001074 /**
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001075 * Special method for the fake title bar to call when displaying its context
1076 * menu, since it is in its own Window, and its parent does not show a
1077 * context menu.
1078 */
1079 /* package */ void showTitleBarContextMenu() {
Cary Clark65f4a3c2009-09-28 17:05:06 -04001080 if (null == mTitleBar.getParent()) {
1081 return;
1082 }
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001083 openContextMenu(mTitleBar);
1084 }
1085
1086 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08001087 * onSaveInstanceState(Bundle map)
1088 * onSaveInstanceState is called right before onStop(). The map contains
1089 * the saved state.
1090 */
1091 @Override protected void onSaveInstanceState(Bundle outState) {
Dave Bort31a6d1c2009-04-13 15:56:49 -07001092 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001093 Log.v(LOGTAG, "BrowserActivity.onSaveInstanceState: this=" + this);
1094 }
1095 // the default implementation requires each view to have an id. As the
1096 // browser handles the state itself and it doesn't use id for the views,
1097 // don't call the default implementation. Otherwise it will trigger the
1098 // warning like this, "couldn't save which view has focus because the
1099 // focused view XXX has no id".
1100
1101 // Save all the tabs
1102 mTabControl.saveState(outState);
1103 }
1104
1105 @Override protected void onPause() {
1106 super.onPause();
1107
1108 if (mActivityInPause) {
1109 Log.e(LOGTAG, "BrowserActivity is already paused.");
1110 return;
1111 }
1112
Mike Reed7bfa63b2009-05-28 11:08:32 -04001113 mTabControl.pauseCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001114 mActivityInPause = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -04001115 if (mTabControl.getCurrentIndex() >= 0 && !pauseWebViewTimers()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001116 mWakeLock.acquire();
1117 mHandler.sendMessageDelayed(mHandler
1118 .obtainMessage(RELEASE_WAKELOCK), WAKELOCK_TIMEOUT);
1119 }
1120
1121 // Clear the credentials toast if it is up
1122 if (mCredsDlg != null && mCredsDlg.isShowing()) {
1123 mCredsDlg.dismiss();
1124 }
1125 mCredsDlg = null;
1126
Leon Scrogginsa2ab6a72009-09-11 11:49:52 -04001127 // FIXME: This removes the active tabs page and resets the menu to
1128 // MAIN_MENU. A better solution might be to do this work in onNewIntent
1129 // but then we would need to save it in onSaveInstanceState and restore
1130 // it in onCreate/onRestoreInstanceState
1131 if (mActiveTabsPage != null) {
1132 removeActiveTabPage(true);
1133 }
1134
The Android Open Source Project0c908882009-03-03 19:32:16 -08001135 cancelStopToast();
1136
1137 // unregister network state listener
1138 unregisterReceiver(mNetworkStateIntentReceiver);
1139 WebView.disablePlatformNotifications();
1140
1141 if (mSensorManager != null) {
1142 mSensorManager.unregisterListener(mSensorListener);
1143 }
1144 }
1145
1146 @Override protected void onDestroy() {
Dave Bort31a6d1c2009-04-13 15:56:49 -07001147 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001148 Log.v(LOGTAG, "BrowserActivity.onDestroy: this=" + this);
1149 }
1150 super.onDestroy();
Grace Kloba0923d692009-09-23 21:37:25 -07001151
1152 if (mTabControl == null) return;
1153
The Android Open Source Project0c908882009-03-03 19:32:16 -08001154 // Remove the current tab and sub window
1155 TabControl.Tab t = mTabControl.getCurrentTab();
Patrick Scottfb5e77f2009-04-08 19:17:37 -07001156 if (t != null) {
1157 dismissSubWindow(t);
1158 removeTabFromContentView(t);
1159 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001160 // Destroy all the tabs
1161 mTabControl.destroy();
1162 WebIconDatabase.getInstance().close();
1163 if (mGlsConnection != null) {
1164 unbindService(mGlsConnection);
1165 mGlsConnection = null;
1166 }
1167
1168 //
1169 // stop MASF proxy service
1170 //
1171 //Intent proxyServiceIntent = new Intent();
1172 //proxyServiceIntent.setComponent
1173 // (new ComponentName(
1174 // "com.android.masfproxyservice",
1175 // "com.android.masfproxyservice.MasfProxyService"));
1176 //stopService(proxyServiceIntent);
Grace Klobab4da0ad2009-05-14 14:45:40 -07001177
1178 unregisterReceiver(mPackageInstallationReceiver);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001179 }
1180
1181 @Override
1182 public void onConfigurationChanged(Configuration newConfig) {
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04001183 mConfigChanged = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001184 super.onConfigurationChanged(newConfig);
1185
1186 if (mPageInfoDialog != null) {
1187 mPageInfoDialog.dismiss();
1188 showPageInfo(
1189 mPageInfoView,
1190 mPageInfoFromShowSSLCertificateOnError.booleanValue());
1191 }
1192 if (mSSLCertificateDialog != null) {
1193 mSSLCertificateDialog.dismiss();
1194 showSSLCertificate(
1195 mSSLCertificateView);
1196 }
1197 if (mSSLCertificateOnErrorDialog != null) {
1198 mSSLCertificateOnErrorDialog.dismiss();
1199 showSSLCertificateOnError(
1200 mSSLCertificateOnErrorView,
1201 mSSLCertificateOnErrorHandler,
1202 mSSLCertificateOnErrorError);
1203 }
1204 if (mHttpAuthenticationDialog != null) {
1205 String title = ((TextView) mHttpAuthenticationDialog
1206 .findViewById(com.android.internal.R.id.alertTitle)).getText()
1207 .toString();
1208 String name = ((TextView) mHttpAuthenticationDialog
1209 .findViewById(R.id.username_edit)).getText().toString();
1210 String password = ((TextView) mHttpAuthenticationDialog
1211 .findViewById(R.id.password_edit)).getText().toString();
1212 int focusId = mHttpAuthenticationDialog.getCurrentFocus()
1213 .getId();
1214 mHttpAuthenticationDialog.dismiss();
1215 showHttpAuthentication(mHttpAuthHandler, null, null, title,
1216 name, password, focusId);
1217 }
1218 if (mFindDialog != null && mFindDialog.isShowing()) {
1219 mFindDialog.onConfigurationChanged(newConfig);
1220 }
1221 }
1222
1223 @Override public void onLowMemory() {
1224 super.onLowMemory();
1225 mTabControl.freeMemory();
1226 }
1227
Mike Reed7bfa63b2009-05-28 11:08:32 -04001228 private boolean resumeWebViewTimers() {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001229 if ((!mActivityInPause && !mPageStarted) ||
1230 (mActivityInPause && mPageStarted)) {
1231 CookieSyncManager.getInstance().startSync();
1232 WebView w = mTabControl.getCurrentWebView();
1233 if (w != null) {
1234 w.resumeTimers();
1235 }
1236 return true;
1237 } else {
1238 return false;
1239 }
1240 }
1241
Mike Reed7bfa63b2009-05-28 11:08:32 -04001242 private boolean pauseWebViewTimers() {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001243 if (mActivityInPause && !mPageStarted) {
1244 CookieSyncManager.getInstance().stopSync();
1245 WebView w = mTabControl.getCurrentWebView();
1246 if (w != null) {
1247 w.pauseTimers();
1248 }
1249 return true;
1250 } else {
1251 return false;
1252 }
1253 }
1254
Leon Scroggins1f005d32009-08-10 17:36:42 -04001255 // FIXME: Do we want to call this when loading google for the first time?
The Android Open Source Project0c908882009-03-03 19:32:16 -08001256 /*
1257 * This function is called when we are launching for the first time. We
1258 * are waiting for the login credentials before loading Google home
1259 * pages. This way the user will be logged in straight away.
1260 */
1261 private void waitForCredentials() {
1262 // Show a toast
1263 mCredsDlg = new ProgressDialog(this);
1264 mCredsDlg.setIndeterminate(true);
1265 mCredsDlg.setMessage(getText(R.string.retrieving_creds_dlg_msg));
1266 // If the user cancels the operation, then cancel the Google
1267 // Credentials request.
1268 mCredsDlg.setCancelMessage(mHandler.obtainMessage(CANCEL_CREDS_REQUEST));
1269 mCredsDlg.show();
1270
1271 // We set a timeout for the retrieval of credentials in onResume()
1272 // as that is when we have freed up some CPU time to get
1273 // the login credentials.
1274 }
1275
1276 /*
1277 * If we have received the credentials or we have timed out and we are
1278 * showing the credentials dialog, then it is time to move on.
1279 */
1280 private void resumeAfterCredentials() {
1281 if (mCredsDlg == null) {
1282 return;
1283 }
1284
1285 // Clear the toast
1286 if (mCredsDlg.isShowing()) {
1287 mCredsDlg.dismiss();
1288 }
1289 mCredsDlg = null;
1290
1291 // Clear any pending timeout
1292 mHandler.removeMessages(CANCEL_CREDS_REQUEST);
1293
1294 // Load the page
1295 WebView w = mTabControl.getCurrentWebView();
1296 if (w != null) {
1297 w.loadUrl(mSettings.getHomePage());
1298 }
1299
1300 // Update the settings, need to do this last as it can take a moment
1301 // to persist the settings. In the mean time we could be loading
1302 // content.
1303 mSettings.setLoginInitialized(this);
1304 }
1305
1306 // Open the icon database and retain all the icons for visited sites.
1307 private void retainIconsOnStartup() {
1308 final WebIconDatabase db = WebIconDatabase.getInstance();
1309 db.open(getDir("icons", 0).getPath());
1310 try {
1311 Cursor c = Browser.getAllBookmarks(mResolver);
1312 if (!c.moveToFirst()) {
1313 c.deactivate();
1314 return;
1315 }
1316 int urlIndex = c.getColumnIndex(Browser.BookmarkColumns.URL);
1317 do {
1318 String url = c.getString(urlIndex);
1319 db.retainIconForPageUrl(url);
1320 } while (c.moveToNext());
1321 c.deactivate();
1322 } catch (IllegalStateException e) {
1323 Log.e(LOGTAG, "retainIconsOnStartup", e);
1324 }
1325 }
1326
1327 // Helper method for getting the top window.
1328 WebView getTopWindow() {
1329 return mTabControl.getCurrentTopWebView();
1330 }
1331
1332 @Override
1333 public boolean onCreateOptionsMenu(Menu menu) {
1334 super.onCreateOptionsMenu(menu);
1335
1336 MenuInflater inflater = getMenuInflater();
1337 inflater.inflate(R.menu.browser, menu);
1338 mMenu = menu;
1339 updateInLoadMenuItems();
1340 return true;
1341 }
1342
1343 /**
1344 * As the menu can be open when loading state changes
1345 * we must manually update the state of the stop/reload menu
1346 * item
1347 */
1348 private void updateInLoadMenuItems() {
1349 if (mMenu == null) {
1350 return;
1351 }
1352 MenuItem src = mInLoad ?
1353 mMenu.findItem(R.id.stop_menu_id):
1354 mMenu.findItem(R.id.reload_menu_id);
1355 MenuItem dest = mMenu.findItem(R.id.stop_reload_menu_id);
1356 dest.setIcon(src.getIcon());
1357 dest.setTitle(src.getTitle());
1358 }
1359
1360 @Override
1361 public boolean onContextItemSelected(MenuItem item) {
1362 // chording is not an issue with context menus, but we use the same
1363 // options selector, so set mCanChord to true so we can access them.
1364 mCanChord = true;
1365 int id = item.getItemId();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001366 switch (id) {
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001367 // For the context menu from the title bar
1368 case R.id.title_bar_share_page_url:
1369 case R.id.title_bar_copy_page_url:
1370 WebView mainView = mTabControl.getCurrentWebView();
1371 if (null == mainView) {
1372 return false;
1373 }
1374 if (id == R.id.title_bar_share_page_url) {
1375 Browser.sendString(this, mainView.getUrl());
1376 } else {
1377 copy(mainView.getUrl());
1378 }
1379 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001380 // -- Browser context menu
1381 case R.id.open_context_menu_id:
1382 case R.id.open_newtab_context_menu_id:
1383 case R.id.bookmark_context_menu_id:
1384 case R.id.save_link_context_menu_id:
1385 case R.id.share_link_context_menu_id:
1386 case R.id.copy_link_context_menu_id:
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001387 final WebView webView = getTopWindow();
1388 if (null == webView) {
1389 return false;
1390 }
1391 final HashMap hrefMap = new HashMap();
1392 hrefMap.put("webview", webView);
1393 final Message msg = mHandler.obtainMessage(
1394 FOCUS_NODE_HREF, id, 0, hrefMap);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001395 webView.requestFocusNodeHref(msg);
1396 break;
1397
1398 default:
1399 // For other context menus
1400 return onOptionsItemSelected(item);
1401 }
1402 mCanChord = false;
1403 return true;
1404 }
1405
1406 private Bundle createGoogleSearchSourceBundle(String source) {
1407 Bundle bundle = new Bundle();
1408 bundle.putString(SearchManager.SOURCE, source);
1409 return bundle;
1410 }
1411
1412 /**
The Android Open Source Project4e5f5872009-03-09 11:52:14 -07001413 * Overriding this to insert a local information bundle
The Android Open Source Project0c908882009-03-03 19:32:16 -08001414 */
1415 @Override
1416 public boolean onSearchRequested() {
Leon Scroggins68579392009-09-15 15:31:54 -04001417 if (mOptionsMenuOpen) closeOptionsMenu();
Leon Scroggins5bbe9802009-07-31 13:10:55 -04001418 String url = (getTopWindow() == null) ? null : getTopWindow().getUrl();
Grace Kloba83f47342009-07-20 10:44:31 -07001419 startSearch(mSettings.getHomePage().equals(url) ? null : url, true,
The Android Open Source Project4e5f5872009-03-09 11:52:14 -07001420 createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_SEARCHKEY), false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001421 return true;
1422 }
1423
1424 @Override
1425 public void startSearch(String initialQuery, boolean selectInitialQuery,
1426 Bundle appSearchData, boolean globalSearch) {
1427 if (appSearchData == null) {
1428 appSearchData = createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_TYPE);
1429 }
1430 super.startSearch(initialQuery, selectInitialQuery, appSearchData, globalSearch);
1431 }
1432
Leon Scroggins1f005d32009-08-10 17:36:42 -04001433 /**
1434 * Switch tabs. Called by the TitleBarSet when sliding the title bar
1435 * results in changing tabs.
Leon Scroggins160a7e72009-08-14 18:28:01 -04001436 * @param index Index of the tab to change to, as defined by
1437 * mTabControl.getTabIndex(Tab t).
1438 * @return boolean True if we successfully switched to a different tab. If
1439 * the indexth tab is null, or if that tab is the same as
1440 * the current one, return false.
Leon Scroggins1f005d32009-08-10 17:36:42 -04001441 */
Leon Scroggins160a7e72009-08-14 18:28:01 -04001442 /* package */ boolean switchToTab(int index) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001443 TabControl.Tab tab = mTabControl.getTab(index);
1444 TabControl.Tab currentTab = mTabControl.getCurrentTab();
1445 if (tab == null || tab == currentTab) {
Leon Scroggins160a7e72009-08-14 18:28:01 -04001446 return false;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001447 }
1448 if (currentTab != null) {
1449 // currentTab may be null if it was just removed. In that case,
1450 // we do not need to remove it
1451 removeTabFromContentView(currentTab);
1452 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001453 mTabControl.setCurrentTab(tab);
1454 attachTabToContentView(tab);
Grace Klobaeb6eef42009-09-15 17:56:32 -07001455 resetTitleIconAndProgress();
1456 updateLockIconToLatest();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001457 return true;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001458 }
1459
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001460 /* package */ TabControl.Tab openTabToHomePage() {
1461 return openTabAndShow(mSettings.getHomePage(), false, null);
1462 }
1463
Leon Scroggins1f005d32009-08-10 17:36:42 -04001464 /* package */ void closeCurrentWindow() {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001465 final TabControl.Tab current = mTabControl.getCurrentTab();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001466 if (mTabControl.getTabCount() == 1) {
Leon Scroggins30444232009-09-04 18:36:20 -04001467 // This is the last tab. Open a new one, with the home
1468 // page and close the current one.
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001469 TabControl.Tab newTab = openTabToHomePage();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001470 closeTab(current);
Leon Scroggins160a7e72009-08-14 18:28:01 -04001471 return;
1472 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001473 final TabControl.Tab parent = current.getParentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04001474 int indexToShow = -1;
1475 if (parent != null) {
1476 indexToShow = mTabControl.getTabIndex(parent);
1477 } else {
Leon Scroggins160a7e72009-08-14 18:28:01 -04001478 final int currentIndex = mTabControl.getCurrentIndex();
1479 // Try to move to the tab to the right
1480 indexToShow = currentIndex + 1;
1481 if (indexToShow > mTabControl.getTabCount() - 1) {
1482 // Try to move to the tab to the left
1483 indexToShow = currentIndex - 1;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001484 }
1485 }
Leon Scroggins160a7e72009-08-14 18:28:01 -04001486 if (switchToTab(indexToShow)) {
1487 // Close window
1488 closeTab(current);
1489 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001490 }
1491
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001492 private ActiveTabsPage mActiveTabsPage;
1493
1494 /**
1495 * Remove the active tabs page.
1496 * @param needToAttach If true, the active tabs page did not attach a tab
1497 * to the content view, so we need to do that here.
1498 */
1499 /* package */ void removeActiveTabPage(boolean needToAttach) {
1500 mContentView.removeView(mActiveTabsPage);
1501 mActiveTabsPage = null;
1502 mMenuState = R.id.MAIN_MENU;
1503 if (needToAttach) {
1504 attachTabToContentView(mTabControl.getCurrentTab());
1505 }
1506 getTopWindow().requestFocus();
1507 }
1508
The Android Open Source Project0c908882009-03-03 19:32:16 -08001509 @Override
1510 public boolean onOptionsItemSelected(MenuItem item) {
1511 if (!mCanChord) {
1512 // The user has already fired a shortcut with this hold down of the
1513 // menu key.
1514 return false;
1515 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001516 if (null == getTopWindow()) {
Leon Scroggins0d7ae0e2009-06-05 11:04:45 -04001517 return false;
1518 }
Grace Kloba6ee9c492009-07-13 10:04:34 -07001519 if (mMenuIsDown) {
1520 // The shortcut action consumes the MENU. Even if it is still down,
1521 // it won't trigger the next shortcut action. In the case of the
1522 // shortcut action triggering a new activity, like Bookmarks, we
1523 // won't get onKeyUp for MENU. So it is important to reset it here.
1524 mMenuIsDown = false;
1525 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001526 switch (item.getItemId()) {
1527 // -- Main menu
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001528 case R.id.new_tab_menu_id:
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001529 openTabToHomePage();
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001530 break;
1531
Leon Scroggins64b80f32009-08-07 12:03:34 -04001532 case R.id.goto_menu_id:
Leon Scrogginsb3a5bed2009-09-28 11:21:56 -04001533 onSearchRequested();
1534 break;
1535
1536 case R.id.bookmarks_menu_id:
Leon Scroggins30444232009-09-04 18:36:20 -04001537 bookmarksOrHistoryPicker(false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001538 break;
1539
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001540 case R.id.active_tabs_menu_id:
1541 mActiveTabsPage = new ActiveTabsPage(this, mTabControl);
1542 removeTabFromContentView(mTabControl.getCurrentTab());
Leon Scroggins43de6162009-09-14 19:59:58 -04001543 hideFakeTitleBar();
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001544 mContentView.addView(mActiveTabsPage, COVER_SCREEN_PARAMS);
1545 mActiveTabsPage.requestFocus();
1546 mMenuState = EMPTY_MENU;
1547 break;
1548
Leon Scroggins1f005d32009-08-10 17:36:42 -04001549 case R.id.add_bookmark_menu_id:
1550 Intent i = new Intent(BrowserActivity.this,
1551 AddBookmarkPage.class);
1552 WebView w = getTopWindow();
1553 i.putExtra("url", w.getUrl());
1554 i.putExtra("title", w.getTitle());
Grace Kloba83cdb2c2009-09-16 00:48:57 -07001555 i.putExtra("touch_icon_url", w.getTouchIconUrl());
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01001556 i.putExtra("thumbnail", createScreenshot(w));
Leon Scroggins1f005d32009-08-10 17:36:42 -04001557 startActivity(i);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001558 break;
1559
1560 case R.id.stop_reload_menu_id:
1561 if (mInLoad) {
1562 stopLoading();
1563 } else {
1564 getTopWindow().reload();
1565 }
1566 break;
1567
1568 case R.id.back_menu_id:
1569 getTopWindow().goBack();
1570 break;
1571
1572 case R.id.forward_menu_id:
1573 getTopWindow().goForward();
1574 break;
1575
1576 case R.id.close_menu_id:
1577 // Close the subwindow if it exists.
1578 if (mTabControl.getCurrentSubWindow() != null) {
1579 dismissSubWindow(mTabControl.getCurrentTab());
1580 break;
1581 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001582 closeCurrentWindow();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001583 break;
1584
1585 case R.id.homepage_menu_id:
1586 TabControl.Tab current = mTabControl.getCurrentTab();
1587 if (current != null) {
1588 dismissSubWindow(current);
1589 current.getWebView().loadUrl(mSettings.getHomePage());
1590 }
1591 break;
1592
1593 case R.id.preferences_menu_id:
1594 Intent intent = new Intent(this,
1595 BrowserPreferencesPage.class);
1596 startActivityForResult(intent, PREFERENCES_PAGE);
1597 break;
1598
1599 case R.id.find_menu_id:
1600 if (null == mFindDialog) {
1601 mFindDialog = new FindDialog(this);
1602 }
1603 mFindDialog.setWebView(getTopWindow());
1604 mFindDialog.show();
1605 mMenuState = EMPTY_MENU;
1606 break;
1607
1608 case R.id.select_text_id:
1609 getTopWindow().emulateShiftHeld();
1610 break;
1611 case R.id.page_info_menu_id:
1612 showPageInfo(mTabControl.getCurrentTab(), false);
1613 break;
1614
1615 case R.id.classic_history_menu_id:
Leon Scroggins30444232009-09-04 18:36:20 -04001616 bookmarksOrHistoryPicker(true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001617 break;
1618
1619 case R.id.share_page_menu_id:
Andrei Popescu10fdba82009-09-24 13:25:47 +01001620 Browser.sendString(this, getTopWindow().getUrl(),
1621 getText(R.string.choosertitle_sharevia).toString());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001622 break;
1623
1624 case R.id.dump_nav_menu_id:
1625 getTopWindow().debugDump();
1626 break;
1627
1628 case R.id.zoom_in_menu_id:
1629 getTopWindow().zoomIn();
1630 break;
1631
1632 case R.id.zoom_out_menu_id:
1633 getTopWindow().zoomOut();
1634 break;
1635
1636 case R.id.view_downloads_menu_id:
1637 viewDownloads(null);
1638 break;
1639
The Android Open Source Project0c908882009-03-03 19:32:16 -08001640 case R.id.window_one_menu_id:
1641 case R.id.window_two_menu_id:
1642 case R.id.window_three_menu_id:
1643 case R.id.window_four_menu_id:
1644 case R.id.window_five_menu_id:
1645 case R.id.window_six_menu_id:
1646 case R.id.window_seven_menu_id:
1647 case R.id.window_eight_menu_id:
1648 {
1649 int menuid = item.getItemId();
1650 for (int id = 0; id < WINDOW_SHORTCUT_ID_ARRAY.length; id++) {
1651 if (WINDOW_SHORTCUT_ID_ARRAY[id] == menuid) {
1652 TabControl.Tab desiredTab = mTabControl.getTab(id);
1653 if (desiredTab != null &&
1654 desiredTab != mTabControl.getCurrentTab()) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001655 switchToTab(id);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001656 }
1657 break;
1658 }
1659 }
1660 }
1661 break;
1662
1663 default:
1664 if (!super.onOptionsItemSelected(item)) {
1665 return false;
1666 }
1667 // Otherwise fall through.
1668 }
1669 mCanChord = false;
1670 return true;
1671 }
1672
1673 public void closeFind() {
1674 mMenuState = R.id.MAIN_MENU;
1675 }
1676
1677 @Override public boolean onPrepareOptionsMenu(Menu menu)
1678 {
1679 // This happens when the user begins to hold down the menu key, so
1680 // allow them to chord to get a shortcut.
1681 mCanChord = true;
1682 // Note: setVisible will decide whether an item is visible; while
1683 // setEnabled() will decide whether an item is enabled, which also means
1684 // whether the matching shortcut key will function.
1685 super.onPrepareOptionsMenu(menu);
1686 switch (mMenuState) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001687 case EMPTY_MENU:
1688 if (mCurrentMenuState != mMenuState) {
1689 menu.setGroupVisible(R.id.MAIN_MENU, false);
1690 menu.setGroupEnabled(R.id.MAIN_MENU, false);
1691 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001692 }
1693 break;
1694 default:
1695 if (mCurrentMenuState != mMenuState) {
1696 menu.setGroupVisible(R.id.MAIN_MENU, true);
1697 menu.setGroupEnabled(R.id.MAIN_MENU, true);
1698 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001699 }
1700 final WebView w = getTopWindow();
1701 boolean canGoBack = false;
1702 boolean canGoForward = false;
1703 boolean isHome = false;
1704 if (w != null) {
1705 canGoBack = w.canGoBack();
1706 canGoForward = w.canGoForward();
1707 isHome = mSettings.getHomePage().equals(w.getUrl());
1708 }
1709 final MenuItem back = menu.findItem(R.id.back_menu_id);
1710 back.setEnabled(canGoBack);
1711
1712 final MenuItem home = menu.findItem(R.id.homepage_menu_id);
1713 home.setEnabled(!isHome);
1714
1715 menu.findItem(R.id.forward_menu_id)
1716 .setEnabled(canGoForward);
1717
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001718 menu.findItem(R.id.new_tab_menu_id).setEnabled(
1719 mTabControl.getTabCount() < TabControl.MAX_TABS);
1720
The Android Open Source Project0c908882009-03-03 19:32:16 -08001721 // decide whether to show the share link option
1722 PackageManager pm = getPackageManager();
1723 Intent send = new Intent(Intent.ACTION_SEND);
1724 send.setType("text/plain");
1725 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1726 menu.findItem(R.id.share_page_menu_id).setVisible(ri != null);
1727
The Android Open Source Project0c908882009-03-03 19:32:16 -08001728 boolean isNavDump = mSettings.isNavDump();
1729 final MenuItem nav = menu.findItem(R.id.dump_nav_menu_id);
1730 nav.setVisible(isNavDump);
1731 nav.setEnabled(isNavDump);
1732 break;
1733 }
1734 mCurrentMenuState = mMenuState;
1735 return true;
1736 }
1737
1738 @Override
1739 public void onCreateContextMenu(ContextMenu menu, View v,
1740 ContextMenuInfo menuInfo) {
1741 WebView webview = (WebView) v;
1742 WebView.HitTestResult result = webview.getHitTestResult();
1743 if (result == null) {
1744 return;
1745 }
1746
1747 int type = result.getType();
1748 if (type == WebView.HitTestResult.UNKNOWN_TYPE) {
1749 Log.w(LOGTAG,
1750 "We should not show context menu when nothing is touched");
1751 return;
1752 }
1753 if (type == WebView.HitTestResult.EDIT_TEXT_TYPE) {
1754 // let TextView handles context menu
1755 return;
1756 }
1757
1758 // Note, http://b/issue?id=1106666 is requesting that
1759 // an inflated menu can be used again. This is not available
1760 // yet, so inflate each time (yuk!)
1761 MenuInflater inflater = getMenuInflater();
1762 inflater.inflate(R.menu.browsercontext, menu);
1763
1764 // Show the correct menu group
1765 String extra = result.getExtra();
1766 menu.setGroupVisible(R.id.PHONE_MENU,
1767 type == WebView.HitTestResult.PHONE_TYPE);
1768 menu.setGroupVisible(R.id.EMAIL_MENU,
1769 type == WebView.HitTestResult.EMAIL_TYPE);
1770 menu.setGroupVisible(R.id.GEO_MENU,
1771 type == WebView.HitTestResult.GEO_TYPE);
1772 menu.setGroupVisible(R.id.IMAGE_MENU,
1773 type == WebView.HitTestResult.IMAGE_TYPE
1774 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1775 menu.setGroupVisible(R.id.ANCHOR_MENU,
1776 type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1777 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1778
1779 // Setup custom handling depending on the type
1780 switch (type) {
1781 case WebView.HitTestResult.PHONE_TYPE:
1782 menu.setHeaderTitle(Uri.decode(extra));
1783 menu.findItem(R.id.dial_context_menu_id).setIntent(
1784 new Intent(Intent.ACTION_VIEW, Uri
1785 .parse(WebView.SCHEME_TEL + extra)));
1786 Intent addIntent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
1787 addIntent.putExtra(Insert.PHONE, Uri.decode(extra));
Cary Clark5e335a32009-09-22 14:53:11 -04001788 addIntent.setType(ContactsContract.Contacts.CONTENT_ITEM_TYPE);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001789 menu.findItem(R.id.add_contact_context_menu_id).setIntent(
1790 addIntent);
1791 menu.findItem(R.id.copy_phone_context_menu_id).setOnMenuItemClickListener(
1792 new Copy(extra));
1793 break;
1794
1795 case WebView.HitTestResult.EMAIL_TYPE:
1796 menu.setHeaderTitle(extra);
1797 menu.findItem(R.id.email_context_menu_id).setIntent(
1798 new Intent(Intent.ACTION_VIEW, Uri
1799 .parse(WebView.SCHEME_MAILTO + extra)));
1800 menu.findItem(R.id.copy_mail_context_menu_id).setOnMenuItemClickListener(
1801 new Copy(extra));
1802 break;
1803
1804 case WebView.HitTestResult.GEO_TYPE:
1805 menu.setHeaderTitle(extra);
1806 menu.findItem(R.id.map_context_menu_id).setIntent(
1807 new Intent(Intent.ACTION_VIEW, Uri
1808 .parse(WebView.SCHEME_GEO
1809 + URLEncoder.encode(extra))));
1810 menu.findItem(R.id.copy_geo_context_menu_id).setOnMenuItemClickListener(
1811 new Copy(extra));
1812 break;
1813
1814 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1815 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
1816 TextView titleView = (TextView) LayoutInflater.from(this)
1817 .inflate(android.R.layout.browser_link_context_header,
1818 null);
1819 titleView.setText(extra);
1820 menu.setHeaderView(titleView);
1821 // decide whether to show the open link in new tab option
1822 menu.findItem(R.id.open_newtab_context_menu_id).setVisible(
1823 mTabControl.getTabCount() < TabControl.MAX_TABS);
1824 PackageManager pm = getPackageManager();
1825 Intent send = new Intent(Intent.ACTION_SEND);
1826 send.setType("text/plain");
1827 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1828 menu.findItem(R.id.share_link_context_menu_id).setVisible(ri != null);
1829 if (type == WebView.HitTestResult.SRC_ANCHOR_TYPE) {
1830 break;
1831 }
1832 // otherwise fall through to handle image part
1833 case WebView.HitTestResult.IMAGE_TYPE:
1834 if (type == WebView.HitTestResult.IMAGE_TYPE) {
1835 menu.setHeaderTitle(extra);
1836 }
1837 menu.findItem(R.id.view_image_context_menu_id).setIntent(
1838 new Intent(Intent.ACTION_VIEW, Uri.parse(extra)));
1839 menu.findItem(R.id.download_context_menu_id).
1840 setOnMenuItemClickListener(new Download(extra));
1841 break;
1842
1843 default:
1844 Log.w(LOGTAG, "We should not get here.");
1845 break;
1846 }
1847 }
1848
The Android Open Source Project0c908882009-03-03 19:32:16 -08001849 // Attach the given tab to the content view.
Grace Klobac928c302009-09-17 11:51:21 -07001850 // this should only be called for the current tab.
The Android Open Source Project0c908882009-03-03 19:32:16 -08001851 private void attachTabToContentView(TabControl.Tab t) {
Steve Block2bc69912009-07-30 14:45:13 +01001852 // Attach the container that contains the main WebView and any other UI
1853 // associated with the tab.
Patrick Scottd0119532009-09-17 08:00:31 -04001854 t.attachTabToContentView(mContentView);
Ben Murdochbff2d602009-07-01 20:19:05 +01001855
1856 if (mShouldShowErrorConsole) {
1857 ErrorConsoleView errorConsole = mTabControl.getCurrentErrorConsole(true);
1858 if (errorConsole.numberOfErrors() == 0) {
1859 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
1860 } else {
1861 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
1862 }
1863
1864 mErrorConsoleContainer.addView(errorConsole,
1865 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
1866 ViewGroup.LayoutParams.WRAP_CONTENT));
1867 }
1868
Grace Klobac928c302009-09-17 11:51:21 -07001869 setLockIconType(t.getLockIconType());
1870 setPrevLockType(t.getPrevLockIconType());
1871
1872 // this is to match the code in removeTabFromContentView()
1873 if (!mPageStarted && t.getTopWindow().getProgress() < 100) {
1874 mPageStarted = true;
Grace Klobaeb6eef42009-09-15 17:56:32 -07001875 }
1876
Leon Scroggins39ab28e2009-09-02 21:20:30 -04001877 WebView view = t.getWebView();
Leon Scroggins55a5bc22009-09-04 17:00:08 -04001878 view.setEmbeddedTitleBar(mTitleBar);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001879 // Request focus on the top window.
1880 t.getTopWindow().requestFocus();
1881 }
1882
1883 // Attach a sub window to the main WebView of the given tab.
1884 private void attachSubWindow(TabControl.Tab t) {
Patrick Scottd0119532009-09-17 08:00:31 -04001885 t.attachSubWindow(mContentView);
1886 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001887 }
1888
1889 // Remove the given tab from the content view.
1890 private void removeTabFromContentView(TabControl.Tab t) {
Steve Block2bc69912009-07-30 14:45:13 +01001891 // Remove the container that contains the main WebView.
Patrick Scottd0119532009-09-17 08:00:31 -04001892 t.removeTabFromContentView(mContentView);
Ben Murdochbff2d602009-07-01 20:19:05 +01001893
1894 if (mTabControl.getCurrentErrorConsole(false) != null) {
1895 mErrorConsoleContainer.removeView(mTabControl.getCurrentErrorConsole(false));
1896 }
1897
Leon Scroggins39ab28e2009-09-02 21:20:30 -04001898 WebView view = t.getWebView();
Leon Scrogginsbb85b902009-09-14 19:27:20 -04001899 if (view != null) {
1900 view.setEmbeddedTitleBar(null);
1901 }
Leon Scroggins39ab28e2009-09-02 21:20:30 -04001902
Grace Klobac928c302009-09-17 11:51:21 -07001903 // unlike attachTabToContentView(), removeTabFromContentView() can be
1904 // called for the non-current tab. Need to add the check.
Grace Klobaeb6eef42009-09-15 17:56:32 -07001905 if (t == mTabControl.getCurrentTab()) {
1906 t.setLockIconType(getLockIconType());
1907 t.setPrevLockIconType(getPrevLockType());
Grace Klobac928c302009-09-17 11:51:21 -07001908
1909 // this is not a perfect solution. But currently there is one
1910 // WebViewClient for all the WebView. if user switches from an
1911 // in-load window to an already loaded window, mPageStarted will not
1912 // be set to false. If user leaves the Browser, pauseWebViewTimers()
1913 // won't do anything and leaves the timer running even Browser is in
1914 // the background.
1915 if (mPageStarted) {
1916 mPageStarted = false;
1917 }
Grace Klobaeb6eef42009-09-15 17:56:32 -07001918 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001919 }
1920
1921 // Remove the sub window if it exists. Also called by TabControl when the
1922 // user clicks the 'X' to dismiss a sub window.
1923 /* package */ void dismissSubWindow(TabControl.Tab t) {
Patrick Scottd0119532009-09-17 08:00:31 -04001924 t.removeSubWindow(mContentView);
1925 // Tell the TabControl to dismiss the subwindow. This will destroy
1926 // the WebView.
1927 mTabControl.dismissSubWindow(t);
1928 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001929 }
1930
Leon Scroggins1f005d32009-08-10 17:36:42 -04001931 // A wrapper function of {@link #openTabAndShow(UrlData, boolean, String)}
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07001932 // that accepts url as string.
Leon Scroggins1f005d32009-08-10 17:36:42 -04001933 private TabControl.Tab openTabAndShow(String url, boolean closeOnExit,
1934 String appId) {
1935 return openTabAndShow(new UrlData(url), closeOnExit, appId);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001936 }
1937
1938 // This method does a ton of stuff. It will attempt to create a new tab
1939 // if we haven't reached MAX_TABS. Otherwise it uses the current tab. If
Leon Scroggins1f005d32009-08-10 17:36:42 -04001940 // url isn't null, it will load the given url.
1941 /* package */ TabControl.Tab openTabAndShow(UrlData urlData,
The Android Open Source Projectf59ec872009-03-13 13:04:24 -07001942 boolean closeOnExit, String appId) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001943 final boolean newTab = mTabControl.getTabCount() != TabControl.MAX_TABS;
1944 final TabControl.Tab currentTab = mTabControl.getCurrentTab();
1945 if (newTab) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001946 final TabControl.Tab tab = mTabControl.createNewTab(
1947 closeOnExit, appId, urlData.mUrl);
1948 WebView webview = tab.getWebView();
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001949 // If the last tab was removed from the active tabs page, currentTab
1950 // will be null.
1951 if (currentTab != null) {
1952 removeTabFromContentView(currentTab);
1953 }
Patrick Scott8bbd69f2009-08-14 13:35:53 -04001954 // We must set the new tab as the current tab to reflect the old
1955 // animation behavior.
1956 mTabControl.setCurrentTab(tab);
Grace Klobaeb6eef42009-09-15 17:56:32 -07001957 attachTabToContentView(tab);
Leon Scroggins160a7e72009-08-14 18:28:01 -04001958 if (!urlData.isEmpty()) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001959 urlData.loadIn(webview);
1960 }
1961 return tab;
1962 } else {
1963 // Get rid of the subwindow if it exists
1964 dismissSubWindow(currentTab);
1965 if (!urlData.isEmpty()) {
1966 // Load the given url.
1967 urlData.loadIn(currentTab.getWebView());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001968 }
1969 }
Grace Klobac9181842009-04-14 08:53:22 -07001970 return currentTab;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001971 }
1972
Grace Klobac9181842009-04-14 08:53:22 -07001973 private TabControl.Tab openTab(String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001974 if (mSettings.openInBackground()) {
The Android Open Source Projectf59ec872009-03-13 13:04:24 -07001975 TabControl.Tab t = mTabControl.createNewTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001976 if (t != null) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001977 WebView view = t.getWebView();
Leon Scroggins1f005d32009-08-10 17:36:42 -04001978 view.loadUrl(url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001979 }
Grace Klobac9181842009-04-14 08:53:22 -07001980 return t;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001981 } else {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001982 return openTabAndShow(url, false, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001983 }
1984 }
1985
1986 private class Copy implements OnMenuItemClickListener {
1987 private CharSequence mText;
1988
1989 public boolean onMenuItemClick(MenuItem item) {
1990 copy(mText);
1991 return true;
1992 }
1993
1994 public Copy(CharSequence toCopy) {
1995 mText = toCopy;
1996 }
1997 }
1998
1999 private class Download implements OnMenuItemClickListener {
2000 private String mText;
2001
2002 public boolean onMenuItemClick(MenuItem item) {
2003 onDownloadStartNoStream(mText, null, null, null, -1);
2004 return true;
2005 }
2006
2007 public Download(String toDownload) {
2008 mText = toDownload;
2009 }
2010 }
2011
2012 private void copy(CharSequence text) {
2013 try {
2014 IClipboard clip = IClipboard.Stub.asInterface(ServiceManager.getService("clipboard"));
2015 if (clip != null) {
2016 clip.setClipboardText(text);
2017 }
2018 } catch (android.os.RemoteException e) {
2019 Log.e(LOGTAG, "Copy failed", e);
2020 }
2021 }
2022
2023 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08002024 * Resets the browser title-view to whatever it must be
2025 * (for example, if we had a loading error)
2026 * When we have a new page, we call resetTitle, when we
2027 * have to reset the titlebar to whatever it used to be
2028 * (for example, if the user chose to stop loading), we
2029 * call resetTitleAndRevertLockIcon.
2030 */
2031 /* package */ void resetTitleAndRevertLockIcon() {
2032 revertLockIcon();
2033 resetTitleIconAndProgress();
2034 }
2035
2036 /**
2037 * Reset the title, favicon, and progress.
2038 */
2039 private void resetTitleIconAndProgress() {
2040 WebView current = mTabControl.getCurrentWebView();
2041 if (current == null) {
2042 return;
2043 }
2044 resetTitleAndIcon(current);
2045 int progress = current.getProgress();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002046 mWebChromeClient.onProgressChanged(current, progress);
2047 }
2048
2049 // Reset the title and the icon based on the given item.
2050 private void resetTitleAndIcon(WebView view) {
2051 WebHistoryItem item = view.copyBackForwardList().getCurrentItem();
2052 if (item != null) {
Leon Scroggins68579392009-09-15 15:31:54 -04002053 setUrlTitle(item.getUrl(), item.getTitle());
The Android Open Source Project0c908882009-03-03 19:32:16 -08002054 setFavicon(item.getFavicon());
2055 } else {
Leon Scroggins68579392009-09-15 15:31:54 -04002056 setUrlTitle(null, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002057 setFavicon(null);
2058 }
2059 }
2060
2061 /**
2062 * Sets a title composed of the URL and the title string.
2063 * @param url The URL of the site being loaded.
2064 * @param title The title of the site being loaded.
2065 */
Leon Scroggins68579392009-09-15 15:31:54 -04002066 private void setUrlTitle(String url, String title) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002067 mUrl = url;
2068 mTitle = title;
2069
Leon Scroggins68579392009-09-15 15:31:54 -04002070 mTitleBar.setTitleAndUrl(title, url);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04002071 if (mFakeTitleBar != null) {
2072 mFakeTitleBar.setTitleAndUrl(title, url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002073 }
2074 }
2075
2076 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08002077 * @param url The URL to build a title version of the URL from.
2078 * @return The title version of the URL or null if fails.
2079 * The title version of the URL can be either the URL hostname,
2080 * or the hostname with an "https://" prefix (for secure URLs),
2081 * or an empty string if, for example, the URL in question is a
2082 * file:// URL with no hostname.
2083 */
Leon Scroggins32e14a62009-06-11 10:26:34 -04002084 /* package */ static String buildTitleUrl(String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002085 String titleUrl = null;
2086
2087 if (url != null) {
2088 try {
2089 // parse the url string
2090 URL urlObj = new URL(url);
2091 if (urlObj != null) {
2092 titleUrl = "";
2093
2094 String protocol = urlObj.getProtocol();
2095 String host = urlObj.getHost();
2096
2097 if (host != null && 0 < host.length()) {
2098 titleUrl = host;
2099 if (protocol != null) {
2100 // if a secure site, add an "https://" prefix!
2101 if (protocol.equalsIgnoreCase("https")) {
2102 titleUrl = protocol + "://" + host;
2103 }
2104 }
2105 }
2106 }
2107 } catch (MalformedURLException e) {}
2108 }
2109
2110 return titleUrl;
2111 }
2112
2113 // Set the favicon in the title bar.
2114 private void setFavicon(Bitmap icon) {
Leon Scroggins68579392009-09-15 15:31:54 -04002115 mTitleBar.setFavicon(icon);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04002116 if (mFakeTitleBar != null) {
2117 mFakeTitleBar.setFavicon(icon);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002118 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002119 }
2120
2121 /**
2122 * Saves the current lock-icon state before resetting
2123 * the lock icon. If we have an error, we may need to
2124 * roll back to the previous state.
2125 */
2126 private void saveLockIcon() {
2127 mPrevLockType = mLockIconType;
2128 }
2129
2130 /**
2131 * Reverts the lock-icon state to the last saved state,
2132 * for example, if we had an error, and need to cancel
2133 * the load.
2134 */
2135 private void revertLockIcon() {
2136 mLockIconType = mPrevLockType;
2137
Dave Bort31a6d1c2009-04-13 15:56:49 -07002138 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002139 Log.v(LOGTAG, "BrowserActivity.revertLockIcon:" +
2140 " revert lock icon to " + mLockIconType);
2141 }
2142
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04002143 updateLockIconToLatest();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002144 }
2145
Leon Scroggins1f005d32009-08-10 17:36:42 -04002146 /**
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002147 * Close the tab, remove its associated title bar, and adjust mTabControl's
2148 * current tab to a valid value.
Leon Scroggins1f005d32009-08-10 17:36:42 -04002149 */
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002150 /* package */ void closeTab(TabControl.Tab t) {
2151 int currentIndex = mTabControl.getCurrentIndex();
2152 int removeIndex = mTabControl.getTabIndex(t);
Leon Scroggins1f005d32009-08-10 17:36:42 -04002153 mTabControl.removeTab(t);
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002154 if (currentIndex >= removeIndex && currentIndex != 0) {
2155 currentIndex--;
2156 }
2157 mTabControl.setCurrentTab(mTabControl.getTab(currentIndex));
Andrei Popescua5bf1de2009-09-23 16:39:23 +01002158 resetTitleIconAndProgress();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002159 }
2160
2161 private void goBackOnePageOrQuit() {
2162 TabControl.Tab current = mTabControl.getCurrentTab();
2163 if (current == null) {
2164 /*
2165 * Instead of finishing the activity, simply push this to the back
2166 * of the stack and let ActivityManager to choose the foreground
2167 * activity. As BrowserActivity is singleTask, it will be always the
2168 * root of the task. So we can use either true or false for
2169 * moveTaskToBack().
2170 */
2171 moveTaskToBack(true);
Grace Kloba00d85e72009-09-23 18:50:05 -07002172 return;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002173 }
2174 WebView w = current.getWebView();
2175 if (w.canGoBack()) {
2176 w.goBack();
2177 } else {
2178 // Check to see if we are closing a window that was created by
2179 // another window. If so, we switch back to that window.
2180 TabControl.Tab parent = current.getParentTab();
2181 if (parent != null) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04002182 switchToTab(mTabControl.getTabIndex(parent));
2183 // Now we close the other tab
2184 closeTab(current);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002185 } else {
2186 if (current.closeOnExit()) {
Grace Klobabb0af5c2009-09-01 00:56:09 -07002187 // force mPageStarted to be false as we are going to either
2188 // finish the activity or remove the tab. This will ensure
2189 // pauseWebView() taking action.
2190 mPageStarted = false;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002191 if (mTabControl.getTabCount() == 1) {
2192 finish();
2193 return;
2194 }
Mike Reed7bfa63b2009-05-28 11:08:32 -04002195 // call pauseWebViewTimers() now, we won't be able to call
2196 // it in onPause() as the WebView won't be valid.
Grace Klobaec1b5ad2009-08-18 08:42:32 -07002197 // Temporarily change mActivityInPause to be true as
2198 // pauseWebViewTimers() will do nothing if mActivityInPause
2199 // is false.
Grace Kloba918e1d72009-08-13 14:55:06 -07002200 boolean savedState = mActivityInPause;
2201 if (savedState) {
Grace Klobaec1b5ad2009-08-18 08:42:32 -07002202 Log.e(LOGTAG, "BrowserActivity is already paused "
2203 + "while handing goBackOnePageOrQuit.");
Grace Kloba918e1d72009-08-13 14:55:06 -07002204 }
2205 mActivityInPause = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -04002206 pauseWebViewTimers();
Grace Kloba918e1d72009-08-13 14:55:06 -07002207 mActivityInPause = savedState;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002208 removeTabFromContentView(current);
2209 mTabControl.removeTab(current);
2210 }
2211 /*
2212 * Instead of finishing the activity, simply push this to the back
2213 * of the stack and let ActivityManager to choose the foreground
2214 * activity. As BrowserActivity is singleTask, it will be always the
2215 * root of the task. So we can use either true or false for
2216 * moveTaskToBack().
2217 */
2218 moveTaskToBack(true);
2219 }
2220 }
2221 }
2222
Grace Kloba5942df02009-09-18 11:48:29 -07002223 @Override
2224 public boolean onKeyDown(int keyCode, KeyEvent event) {
2225 // The default key mode is DEFAULT_KEYS_SEARCH_LOCAL. As the MENU is
2226 // still down, we don't want to trigger the search. Pretend to consume
2227 // the key and do nothing.
2228 if (mMenuIsDown) return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002229
Grace Kloba5942df02009-09-18 11:48:29 -07002230 switch(keyCode) {
2231 case KeyEvent.KEYCODE_MENU:
2232 mMenuIsDown = true;
2233 break;
2234 case KeyEvent.KEYCODE_SPACE:
Grace Klobada0fe552009-09-22 18:17:24 -07002235 // WebView/WebTextView handle the keys in the KeyDown. As
2236 // the Activity's shortcut keys are only handled when WebView
2237 // doesn't, have to do it in onKeyDown instead of onKeyUp.
2238 if (event.isShiftPressed()) {
2239 getTopWindow().pageUp(false);
2240 } else {
2241 getTopWindow().pageDown(false);
2242 }
Grace Kloba5942df02009-09-18 11:48:29 -07002243 return true;
2244 case KeyEvent.KEYCODE_BACK:
2245 if (event.getRepeatCount() == 0) {
2246 event.startTracking();
2247 return true;
2248 } else if (mCustomView == null && mActiveTabsPage == null
2249 && event.isLongPress()) {
2250 bookmarksOrHistoryPicker(true);
2251 return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002252 }
Grace Kloba5942df02009-09-18 11:48:29 -07002253 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002254 }
Grace Kloba5942df02009-09-18 11:48:29 -07002255 return super.onKeyDown(keyCode, event);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002256 }
2257
Grace Kloba5942df02009-09-18 11:48:29 -07002258 @Override
2259 public boolean onKeyUp(int keyCode, KeyEvent event) {
2260 switch(keyCode) {
2261 case KeyEvent.KEYCODE_MENU:
2262 mMenuIsDown = false;
2263 break;
Grace Kloba5942df02009-09-18 11:48:29 -07002264 case KeyEvent.KEYCODE_BACK:
2265 if (event.isTracking() && !event.isCanceled()) {
2266 if (mCustomView != null) {
2267 // if a custom view is showing, hide it
2268 mWebChromeClient.onHideCustomView();
2269 } else if (mActiveTabsPage != null) {
2270 // if tab page is showing, hide it
2271 removeActiveTabPage(true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002272 } else {
Grace Kloba5942df02009-09-18 11:48:29 -07002273 WebView subwindow = mTabControl.getCurrentSubWindow();
2274 if (subwindow != null) {
2275 if (subwindow.canGoBack()) {
2276 subwindow.goBack();
2277 } else {
2278 dismissSubWindow(mTabControl.getCurrentTab());
2279 }
2280 } else {
2281 goBackOnePageOrQuit();
2282 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002283 }
Grace Kloba5942df02009-09-18 11:48:29 -07002284 return true;
2285 }
2286 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002287 }
Grace Kloba5942df02009-09-18 11:48:29 -07002288 return super.onKeyUp(keyCode, event);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002289 }
2290
Leon Scroggins68579392009-09-15 15:31:54 -04002291 /* package */ void stopLoading() {
Ben Murdochb7cc8b42009-09-28 10:59:09 +01002292 mDidStopLoad = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002293 resetTitleAndRevertLockIcon();
2294 WebView w = getTopWindow();
2295 w.stopLoading();
2296 mWebViewClient.onPageFinished(w, w.getUrl());
2297
2298 cancelStopToast();
2299 mStopToast = Toast
2300 .makeText(this, R.string.stopping, Toast.LENGTH_SHORT);
2301 mStopToast.show();
2302 }
2303
2304 private void cancelStopToast() {
2305 if (mStopToast != null) {
2306 mStopToast.cancel();
2307 mStopToast = null;
2308 }
2309 }
2310
2311 // called by a non-UI thread to post the message
2312 public void postMessage(int what, int arg1, int arg2, Object obj) {
2313 mHandler.sendMessage(mHandler.obtainMessage(what, arg1, arg2, obj));
2314 }
2315
2316 // public message ids
2317 public final static int LOAD_URL = 1001;
2318 public final static int STOP_LOAD = 1002;
2319
2320 // Message Ids
2321 private static final int FOCUS_NODE_HREF = 102;
2322 private static final int CANCEL_CREDS_REQUEST = 103;
Grace Kloba92c18a52009-07-31 23:48:32 -07002323 private static final int RELEASE_WAKELOCK = 107;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002324
Ben Murdoch2694e232009-09-29 09:41:11 +01002325 private static final int UPDATE_BOOKMARK_THUMBNAIL = 108;
2326
The Android Open Source Project0c908882009-03-03 19:32:16 -08002327 // Private handler for handling javascript and saving passwords
2328 private Handler mHandler = new Handler() {
2329
2330 public void handleMessage(Message msg) {
2331 switch (msg.what) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002332 case FOCUS_NODE_HREF:
Ben Murdoch2694e232009-09-29 09:41:11 +01002333 {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002334 String url = (String) msg.getData().get("url");
2335 if (url == null || url.length() == 0) {
2336 break;
2337 }
2338 HashMap focusNodeMap = (HashMap) msg.obj;
2339 WebView view = (WebView) focusNodeMap.get("webview");
2340 // Only apply the action if the top window did not change.
2341 if (getTopWindow() != view) {
2342 break;
2343 }
2344 switch (msg.arg1) {
2345 case R.id.open_context_menu_id:
2346 case R.id.view_image_context_menu_id:
2347 loadURL(getTopWindow(), url);
2348 break;
2349 case R.id.open_newtab_context_menu_id:
Grace Klobac9181842009-04-14 08:53:22 -07002350 final TabControl.Tab parent = mTabControl
2351 .getCurrentTab();
2352 final TabControl.Tab newTab = openTab(url);
2353 if (newTab != parent) {
2354 parent.addChildTab(newTab);
2355 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002356 break;
2357 case R.id.bookmark_context_menu_id:
2358 Intent intent = new Intent(BrowserActivity.this,
2359 AddBookmarkPage.class);
2360 intent.putExtra("url", url);
2361 startActivity(intent);
2362 break;
2363 case R.id.share_link_context_menu_id:
Andrei Popescu10fdba82009-09-24 13:25:47 +01002364 Browser.sendString(BrowserActivity.this, url,
2365 getText(R.string.choosertitle_sharevia).toString());
The Android Open Source Project0c908882009-03-03 19:32:16 -08002366 break;
2367 case R.id.copy_link_context_menu_id:
2368 copy(url);
2369 break;
2370 case R.id.save_link_context_menu_id:
2371 case R.id.download_context_menu_id:
2372 onDownloadStartNoStream(url, null, null, null, -1);
2373 break;
2374 }
2375 break;
Ben Murdoch2694e232009-09-29 09:41:11 +01002376 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002377
2378 case LOAD_URL:
2379 loadURL(getTopWindow(), (String) msg.obj);
2380 break;
2381
2382 case STOP_LOAD:
2383 stopLoading();
2384 break;
2385
2386 case CANCEL_CREDS_REQUEST:
2387 resumeAfterCredentials();
2388 break;
2389
The Android Open Source Project0c908882009-03-03 19:32:16 -08002390 case RELEASE_WAKELOCK:
2391 if (mWakeLock.isHeld()) {
2392 mWakeLock.release();
2393 }
2394 break;
Ben Murdoch2694e232009-09-29 09:41:11 +01002395
2396 case UPDATE_BOOKMARK_THUMBNAIL:
2397 WebView view = (WebView) msg.obj;
2398 if (view != null) {
2399 updateScreenshot(view);
2400 }
2401 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002402 }
2403 }
2404 };
2405
Leon Scroggins89c6d362009-07-15 16:54:37 -04002406 private void updateScreenshot(WebView view) {
2407 // If this is a bookmarked site, add a screenshot to the database.
2408 // FIXME: When should we update? Every time?
2409 // FIXME: Would like to make sure there is actually something to
2410 // draw, but the API for that (WebViewCore.pictureReady()) is not
2411 // currently accessible here.
Ben Murdochaac7aa62009-09-17 16:57:40 +01002412
Patrick Scott3918d442009-08-04 13:22:29 -04002413 ContentResolver cr = getContentResolver();
2414 final Cursor c = BrowserBookmarksAdapter.queryBookmarksForUrl(
Ben Murdochaac7aa62009-09-17 16:57:40 +01002415 cr, view.getOriginalUrl(), view.getUrl(), true);
Patrick Scott3918d442009-08-04 13:22:29 -04002416 if (c != null) {
Leon Scroggins89c6d362009-07-15 16:54:37 -04002417 boolean succeed = c.moveToFirst();
2418 ContentValues values = null;
2419 while (succeed) {
2420 if (values == null) {
2421 final ByteArrayOutputStream os
2422 = new ByteArrayOutputStream();
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002423 Bitmap bm = createScreenshot(view);
Leon Scroggins45800572009-09-29 16:38:47 -04002424 if (bm == null) {
2425 c.close();
2426 return;
2427 }
Leon Scroggins89c6d362009-07-15 16:54:37 -04002428 bm.compress(Bitmap.CompressFormat.PNG, 100, os);
2429 values = new ContentValues();
2430 values.put(Browser.BookmarkColumns.THUMBNAIL,
2431 os.toByteArray());
2432 }
2433 cr.update(ContentUris.withAppendedId(Browser.BOOKMARKS_URI,
2434 c.getInt(0)), values, null, null);
2435 succeed = c.moveToNext();
2436 }
2437 c.close();
2438 }
2439 }
2440
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002441 /**
Leon Scrogginsf8551612009-09-24 16:06:02 -04002442 * Values for the size of the thumbnail created when taking a screenshot.
2443 * Lazily initialized. Instead of using these directly, use
2444 * getDesiredThumbnailWidth() or getDesiredThumbnailHeight().
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002445 */
Leon Scrogginsf8551612009-09-24 16:06:02 -04002446 private static int THUMBNAIL_WIDTH = 0;
2447 private static int THUMBNAIL_HEIGHT = 0;
2448
2449 /**
2450 * Return the desired width for thumbnail screenshots, which are stored in
2451 * the database, and used on the bookmarks screen.
2452 * @param context Context for finding out the density of the screen.
2453 * @return int desired width for thumbnail screenshot.
2454 */
2455 /* package */ static int getDesiredThumbnailWidth(Context context) {
2456 if (THUMBNAIL_WIDTH == 0) {
2457 float density = context.getResources().getDisplayMetrics().density;
2458 THUMBNAIL_WIDTH = (int) (90 * density);
2459 THUMBNAIL_HEIGHT = (int) (80 * density);
2460 }
2461 return THUMBNAIL_WIDTH;
2462 }
2463
2464 /**
2465 * Return the desired height for thumbnail screenshots, which are stored in
2466 * the database, and used on the bookmarks screen.
2467 * @param context Context for finding out the density of the screen.
2468 * @return int desired height for thumbnail screenshot.
2469 */
2470 /* package */ static int getDesiredThumbnailHeight(Context context) {
2471 // To ensure that they are both initialized.
2472 getDesiredThumbnailWidth(context);
2473 return THUMBNAIL_HEIGHT;
2474 }
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002475
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002476 private Bitmap createScreenshot(WebView view) {
2477 Picture thumbnail = view.capturePicture();
Leon Scroggins45800572009-09-29 16:38:47 -04002478 if (thumbnail == null) {
2479 return null;
2480 }
Leon Scrogginsf8551612009-09-24 16:06:02 -04002481 Bitmap bm = Bitmap.createBitmap(getDesiredThumbnailWidth(this),
2482 getDesiredThumbnailHeight(this), Bitmap.Config.ARGB_4444);
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002483 Canvas canvas = new Canvas(bm);
2484 // May need to tweak these values to determine what is the
2485 // best scale factor
Ben Murdoch2694e232009-09-29 09:41:11 +01002486 int thumbnailWidth = thumbnail.getWidth();
2487 if (thumbnailWidth > 0) {
2488 float scaleFactor = (float) getDesiredThumbnailWidth(this) /
2489 (float)thumbnailWidth;
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002490 canvas.scale(scaleFactor, scaleFactor);
2491 }
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002492 thumbnail.draw(canvas);
2493 return bm;
2494 }
2495
The Android Open Source Project0c908882009-03-03 19:32:16 -08002496 // -------------------------------------------------------------------------
2497 // WebViewClient implementation.
2498 //-------------------------------------------------------------------------
2499
2500 // Use in overrideUrlLoading
2501 /* package */ final static String SCHEME_WTAI = "wtai://wp/";
2502 /* package */ final static String SCHEME_WTAI_MC = "wtai://wp/mc;";
2503 /* package */ final static String SCHEME_WTAI_SD = "wtai://wp/sd;";
2504 /* package */ final static String SCHEME_WTAI_AP = "wtai://wp/ap;";
2505
2506 /* package */ WebViewClient getWebViewClient() {
2507 return mWebViewClient;
2508 }
2509
Patrick Scott3918d442009-08-04 13:22:29 -04002510 private void updateIcon(WebView view, Bitmap icon) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002511 if (icon != null) {
2512 BrowserBookmarksAdapter.updateBookmarkFavicon(mResolver,
Patrick Scott15525d42009-09-21 13:39:37 -04002513 view.getOriginalUrl(), view.getUrl(), icon);
2514 }
2515 setFavicon(icon);
2516 }
2517
2518 private void updateIcon(String url, Bitmap icon) {
2519 if (icon != null) {
2520 BrowserBookmarksAdapter.updateBookmarkFavicon(mResolver,
2521 null, url, icon);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002522 }
2523 setFavicon(icon);
2524 }
2525
2526 private final WebViewClient mWebViewClient = new WebViewClient() {
2527 @Override
2528 public void onPageStarted(WebView view, String url, Bitmap favicon) {
2529 resetLockIcon(url);
Leon Scroggins68579392009-09-15 15:31:54 -04002530 setUrlTitle(url, null);
Ben Murdochbff2d602009-07-01 20:19:05 +01002531
Ben Murdoch2694e232009-09-29 09:41:11 +01002532 // We've started to load a new page. If there was a pending message
2533 // to save a screenshot then we will now take the new page and
2534 // save an incorrect screenshot. Therefore, remove any pending
2535 // thumbnail messages from the queue.
2536 mHandler.removeMessages(UPDATE_BOOKMARK_THUMBNAIL);
2537
Patrick Scott59ce8302009-09-18 16:29:38 -04002538 // If we start a touch icon load and then load a new page, we don't
2539 // want to cancel the current touch icon loader. But, we do want to
2540 // create a new one when the touch icon url is known.
2541 if (mTouchIconLoader != null) {
2542 mTouchIconLoader.mActivity = null;
2543 mTouchIconLoader = null;
2544 }
2545
Ben Murdochbff2d602009-07-01 20:19:05 +01002546 ErrorConsoleView errorConsole = mTabControl.getCurrentErrorConsole(false);
2547 if (errorConsole != null) {
2548 errorConsole.clearErrorMessages();
2549 if (mShouldShowErrorConsole) {
2550 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
2551 }
2552 }
2553
The Android Open Source Project0c908882009-03-03 19:32:16 -08002554 // Call updateIcon instead of setFavicon so the bookmark
2555 // database can be updated.
Patrick Scott15525d42009-09-21 13:39:37 -04002556 updateIcon(url, favicon);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002557
Grace Kloba4d7880f2009-08-12 09:35:42 -07002558 if (mSettings.isTracing()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002559 String host;
2560 try {
2561 WebAddress uri = new WebAddress(url);
2562 host = uri.mHost;
2563 } catch (android.net.ParseException ex) {
Grace Kloba4d7880f2009-08-12 09:35:42 -07002564 host = "browser";
The Android Open Source Project0c908882009-03-03 19:32:16 -08002565 }
2566 host = host.replace('.', '_');
Grace Kloba4d7880f2009-08-12 09:35:42 -07002567 host += ".trace";
The Android Open Source Project0c908882009-03-03 19:32:16 -08002568 mInTrace = true;
Grace Kloba4d7880f2009-08-12 09:35:42 -07002569 Debug.startMethodTracing(host, 20 * 1024 * 1024);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002570 }
2571
2572 // Performance probe
2573 if (false) {
2574 mStart = SystemClock.uptimeMillis();
2575 mProcessStart = Process.getElapsedCpuTime();
2576 long[] sysCpu = new long[7];
2577 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2578 sysCpu, null)) {
2579 mUserStart = sysCpu[0] + sysCpu[1];
2580 mSystemStart = sysCpu[2];
2581 mIdleStart = sysCpu[3];
2582 mIrqStart = sysCpu[4] + sysCpu[5] + sysCpu[6];
2583 }
2584 mUiStart = SystemClock.currentThreadTimeMillis();
2585 }
2586
2587 if (!mPageStarted) {
2588 mPageStarted = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -04002589 // if onResume() has been called, resumeWebViewTimers() does
2590 // nothing.
2591 resumeWebViewTimers();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002592 }
2593
2594 // reset sync timer to avoid sync starts during loading a page
2595 CookieSyncManager.getInstance().resetSync();
2596
2597 mInLoad = true;
Ben Murdochb7cc8b42009-09-28 10:59:09 +01002598 mDidStopLoad = false;
Leon Scroggins184f5e32009-09-21 10:38:24 -04002599 showFakeTitleBar();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002600 updateInLoadMenuItems();
2601 if (!mIsNetworkUp) {
Patrick Scotteb6ab2a2009-09-16 10:00:17 -04002602 createAndShowNetworkDialog();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002603 if (view != null) {
2604 view.setNetworkAvailable(false);
2605 }
2606 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002607 }
2608
2609 @Override
2610 public void onPageFinished(WebView view, String url) {
2611 // Reset the title and icon in case we stopped a provisional
2612 // load.
2613 resetTitleAndIcon(view);
Ben Murdochb7cc8b42009-09-28 10:59:09 +01002614
2615 if (!mDidStopLoad) {
2616 // Only update the bookmark screenshot if the user did not
2617 // cancel the load early.
Ben Murdoch2694e232009-09-29 09:41:11 +01002618 Message updateScreenshot = Message.obtain(mHandler, UPDATE_BOOKMARK_THUMBNAIL, view);
2619 mHandler.sendMessageDelayed(updateScreenshot, 500);
Ben Murdochb7cc8b42009-09-28 10:59:09 +01002620 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002621
2622 // Update the lock icon image only once we are done loading
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04002623 updateLockIconToLatest();
Leon Scrogginsb6b7f9e2009-06-18 12:05:28 -04002624
The Android Open Source Project0c908882009-03-03 19:32:16 -08002625 // Performance probe
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07002626 if (false) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002627 long[] sysCpu = new long[7];
2628 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2629 sysCpu, null)) {
2630 String uiInfo = "UI thread used "
2631 + (SystemClock.currentThreadTimeMillis() - mUiStart)
2632 + " ms";
Dave Bort31a6d1c2009-04-13 15:56:49 -07002633 if (LOGD_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002634 Log.d(LOGTAG, uiInfo);
2635 }
2636 //The string that gets written to the log
2637 String performanceString = "It took total "
2638 + (SystemClock.uptimeMillis() - mStart)
2639 + " ms clock time to load the page."
2640 + "\nbrowser process used "
2641 + (Process.getElapsedCpuTime() - mProcessStart)
2642 + " ms, user processes used "
2643 + (sysCpu[0] + sysCpu[1] - mUserStart) * 10
2644 + " ms, kernel used "
2645 + (sysCpu[2] - mSystemStart) * 10
2646 + " ms, idle took " + (sysCpu[3] - mIdleStart) * 10
2647 + " ms and irq took "
2648 + (sysCpu[4] + sysCpu[5] + sysCpu[6] - mIrqStart)
2649 * 10 + " ms, " + uiInfo;
Dave Bort31a6d1c2009-04-13 15:56:49 -07002650 if (LOGD_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002651 Log.d(LOGTAG, performanceString + "\nWebpage: " + url);
2652 }
2653 if (url != null) {
2654 // strip the url to maintain consistency
2655 String newUrl = new String(url);
2656 if (newUrl.startsWith("http://www.")) {
2657 newUrl = newUrl.substring(11);
2658 } else if (newUrl.startsWith("http://")) {
2659 newUrl = newUrl.substring(7);
2660 } else if (newUrl.startsWith("https://www.")) {
2661 newUrl = newUrl.substring(12);
2662 } else if (newUrl.startsWith("https://")) {
2663 newUrl = newUrl.substring(8);
2664 }
Dave Bort31a6d1c2009-04-13 15:56:49 -07002665 if (LOGD_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002666 Log.d(LOGTAG, newUrl + " loaded");
2667 }
2668 /*
2669 if (sWhiteList.contains(newUrl)) {
2670 // The string that gets pushed to the statistcs
2671 // service
2672 performanceString = performanceString
2673 + "\nWebpage: "
2674 + newUrl
2675 + "\nCarrier: "
2676 + android.os.SystemProperties
2677 .get("gsm.sim.operator.alpha");
2678 if (mWebView != null
2679 && mWebView.getContext() != null
2680 && mWebView.getContext().getSystemService(
2681 Context.CONNECTIVITY_SERVICE) != null) {
2682 ConnectivityManager cManager =
2683 (ConnectivityManager) mWebView
2684 .getContext().getSystemService(
2685 Context.CONNECTIVITY_SERVICE);
2686 NetworkInfo nInfo = cManager
2687 .getActiveNetworkInfo();
2688 if (nInfo != null) {
2689 performanceString = performanceString
2690 + "\nNetwork Type: "
2691 + nInfo.getType().toString();
2692 }
2693 }
2694 Checkin.logEvent(mResolver,
2695 Checkin.Events.Tag.WEBPAGE_LOAD,
2696 performanceString);
2697 Log.w(LOGTAG, "pushed to the statistics service");
2698 }
2699 */
2700 }
2701 }
2702 }
2703
2704 if (mInTrace) {
2705 mInTrace = false;
2706 Debug.stopMethodTracing();
2707 }
2708
2709 if (mPageStarted) {
2710 mPageStarted = false;
Mike Reed7bfa63b2009-05-28 11:08:32 -04002711 // pauseWebViewTimers() will do nothing and return false if
2712 // onPause() is not called yet.
2713 if (pauseWebViewTimers()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002714 if (mWakeLock.isHeld()) {
2715 mHandler.removeMessages(RELEASE_WAKELOCK);
2716 mWakeLock.release();
2717 }
2718 }
2719 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002720 }
2721
2722 // return true if want to hijack the url to let another app to handle it
2723 @Override
2724 public boolean shouldOverrideUrlLoading(WebView view, String url) {
2725 if (url.startsWith(SCHEME_WTAI)) {
2726 // wtai://wp/mc;number
2727 // number=string(phone-number)
2728 if (url.startsWith(SCHEME_WTAI_MC)) {
2729 Intent intent = new Intent(Intent.ACTION_VIEW,
2730 Uri.parse(WebView.SCHEME_TEL +
2731 url.substring(SCHEME_WTAI_MC.length())));
2732 startActivity(intent);
2733 return true;
2734 }
2735 // wtai://wp/sd;dtmf
2736 // dtmf=string(dialstring)
2737 if (url.startsWith(SCHEME_WTAI_SD)) {
2738 // TODO
2739 // only send when there is active voice connection
2740 return false;
2741 }
2742 // wtai://wp/ap;number;name
2743 // number=string(phone-number)
2744 // name=string
2745 if (url.startsWith(SCHEME_WTAI_AP)) {
2746 // TODO
2747 return false;
2748 }
2749 }
2750
Dianne Hackborn99189432009-06-17 18:06:18 -07002751 // The "about:" schemes are internal to the browser; don't
2752 // want these to be dispatched to other apps.
2753 if (url.startsWith("about:")) {
2754 return false;
2755 }
Ben Murdochbff2d602009-07-01 20:19:05 +01002756
Dianne Hackborn99189432009-06-17 18:06:18 -07002757 Intent intent;
Ben Murdochbff2d602009-07-01 20:19:05 +01002758
Dianne Hackborn99189432009-06-17 18:06:18 -07002759 // perform generic parsing of the URI to turn it into an Intent.
The Android Open Source Project0c908882009-03-03 19:32:16 -08002760 try {
Dianne Hackborn99189432009-06-17 18:06:18 -07002761 intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME);
2762 } catch (URISyntaxException ex) {
2763 Log.w("Browser", "Bad URI " + url + ": " + ex.getMessage());
The Android Open Source Project0c908882009-03-03 19:32:16 -08002764 return false;
2765 }
2766
Grace Kloba5b078b52009-06-24 20:23:41 -07002767 // check whether the intent can be resolved. If not, we will see
2768 // whether we can download it from the Market.
2769 if (getPackageManager().resolveActivity(intent, 0) == null) {
2770 String packagename = intent.getPackage();
2771 if (packagename != null) {
2772 intent = new Intent(Intent.ACTION_VIEW, Uri
2773 .parse("market://search?q=pname:" + packagename));
2774 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2775 startActivity(intent);
2776 return true;
2777 } else {
2778 return false;
2779 }
2780 }
2781
Dianne Hackborn99189432009-06-17 18:06:18 -07002782 // sanitize the Intent, ensuring web pages can not bypass browser
2783 // security (only access to BROWSABLE activities).
The Android Open Source Project0c908882009-03-03 19:32:16 -08002784 intent.addCategory(Intent.CATEGORY_BROWSABLE);
Dianne Hackborn99189432009-06-17 18:06:18 -07002785 intent.setComponent(null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002786 try {
2787 if (startActivityIfNeeded(intent, -1)) {
2788 return true;
2789 }
2790 } catch (ActivityNotFoundException ex) {
2791 // ignore the error. If no application can handle the URL,
2792 // eg about:blank, assume the browser can handle it.
2793 }
2794
2795 if (mMenuIsDown) {
2796 openTab(url);
2797 closeOptionsMenu();
2798 return true;
2799 }
2800
2801 return false;
2802 }
2803
2804 /**
2805 * Updates the lock icon. This method is called when we discover another
2806 * resource to be loaded for this page (for example, javascript). While
2807 * we update the icon type, we do not update the lock icon itself until
2808 * we are done loading, it is slightly more secure this way.
2809 */
2810 @Override
2811 public void onLoadResource(WebView view, String url) {
2812 if (url != null && url.length() > 0) {
2813 // It is only if the page claims to be secure
2814 // that we may have to update the lock:
2815 if (mLockIconType == LOCK_ICON_SECURE) {
2816 // If NOT a 'safe' url, change the lock to mixed content!
2817 if (!(URLUtil.isHttpsUrl(url) || URLUtil.isDataUrl(url) || URLUtil.isAboutUrl(url))) {
2818 mLockIconType = LOCK_ICON_MIXED;
Dave Bort31a6d1c2009-04-13 15:56:49 -07002819 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002820 Log.v(LOGTAG, "BrowserActivity.updateLockIcon:" +
2821 " updated lock icon to " + mLockIconType + " due to " + url);
2822 }
2823 }
2824 }
2825 }
2826 }
2827
2828 /**
2829 * Show the dialog, asking the user if they would like to continue after
2830 * an excessive number of HTTP redirects.
2831 */
2832 @Override
2833 public void onTooManyRedirects(WebView view, final Message cancelMsg,
2834 final Message continueMsg) {
2835 new AlertDialog.Builder(BrowserActivity.this)
2836 .setTitle(R.string.browserFrameRedirect)
2837 .setMessage(R.string.browserFrame307Post)
2838 .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
2839 public void onClick(DialogInterface dialog, int which) {
2840 continueMsg.sendToTarget();
2841 }})
2842 .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
2843 public void onClick(DialogInterface dialog, int which) {
2844 cancelMsg.sendToTarget();
2845 }})
2846 .setOnCancelListener(new OnCancelListener() {
2847 public void onCancel(DialogInterface dialog) {
2848 cancelMsg.sendToTarget();
2849 }})
2850 .show();
2851 }
2852
Patrick Scott37911c72009-03-24 18:02:58 -07002853 // Container class for the next error dialog that needs to be
2854 // displayed.
2855 class ErrorDialog {
2856 public final int mTitle;
2857 public final String mDescription;
2858 public final int mError;
2859 ErrorDialog(int title, String desc, int error) {
2860 mTitle = title;
2861 mDescription = desc;
2862 mError = error;
2863 }
2864 };
2865
2866 private void processNextError() {
2867 if (mQueuedErrors == null) {
2868 return;
2869 }
2870 // The first one is currently displayed so just remove it.
2871 mQueuedErrors.removeFirst();
2872 if (mQueuedErrors.size() == 0) {
2873 mQueuedErrors = null;
2874 return;
2875 }
2876 showError(mQueuedErrors.getFirst());
2877 }
2878
2879 private DialogInterface.OnDismissListener mDialogListener =
2880 new DialogInterface.OnDismissListener() {
2881 public void onDismiss(DialogInterface d) {
2882 processNextError();
2883 }
2884 };
2885 private LinkedList<ErrorDialog> mQueuedErrors;
2886
2887 private void queueError(int err, String desc) {
2888 if (mQueuedErrors == null) {
2889 mQueuedErrors = new LinkedList<ErrorDialog>();
2890 }
2891 for (ErrorDialog d : mQueuedErrors) {
2892 if (d.mError == err) {
2893 // Already saw a similar error, ignore the new one.
2894 return;
2895 }
2896 }
2897 ErrorDialog errDialog = new ErrorDialog(
Patrick Scott5d61a6c2009-08-25 13:52:46 -04002898 err == WebViewClient.ERROR_FILE_NOT_FOUND ?
Patrick Scott37911c72009-03-24 18:02:58 -07002899 R.string.browserFrameFileErrorLabel :
2900 R.string.browserFrameNetworkErrorLabel,
2901 desc, err);
2902 mQueuedErrors.addLast(errDialog);
2903
2904 // Show the dialog now if the queue was empty.
2905 if (mQueuedErrors.size() == 1) {
2906 showError(errDialog);
2907 }
2908 }
2909
2910 private void showError(ErrorDialog errDialog) {
2911 AlertDialog d = new AlertDialog.Builder(BrowserActivity.this)
2912 .setTitle(errDialog.mTitle)
2913 .setMessage(errDialog.mDescription)
2914 .setPositiveButton(R.string.ok, null)
2915 .create();
2916 d.setOnDismissListener(mDialogListener);
2917 d.show();
2918 }
2919
The Android Open Source Project0c908882009-03-03 19:32:16 -08002920 /**
2921 * Show a dialog informing the user of the network error reported by
2922 * WebCore.
2923 */
2924 @Override
2925 public void onReceivedError(WebView view, int errorCode,
2926 String description, String failingUrl) {
Patrick Scott5d61a6c2009-08-25 13:52:46 -04002927 if (errorCode != WebViewClient.ERROR_HOST_LOOKUP &&
2928 errorCode != WebViewClient.ERROR_CONNECT &&
2929 errorCode != WebViewClient.ERROR_BAD_URL &&
2930 errorCode != WebViewClient.ERROR_UNSUPPORTED_SCHEME &&
2931 errorCode != WebViewClient.ERROR_FILE) {
Patrick Scott37911c72009-03-24 18:02:58 -07002932 queueError(errorCode, description);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002933 }
Patrick Scott37911c72009-03-24 18:02:58 -07002934 Log.e(LOGTAG, "onReceivedError " + errorCode + " " + failingUrl
2935 + " " + description);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002936
2937 // We need to reset the title after an error.
2938 resetTitleAndRevertLockIcon();
2939 }
2940
2941 /**
2942 * Check with the user if it is ok to resend POST data as the page they
2943 * are trying to navigate to is the result of a POST.
2944 */
2945 @Override
2946 public void onFormResubmission(WebView view, final Message dontResend,
2947 final Message resend) {
2948 new AlertDialog.Builder(BrowserActivity.this)
2949 .setTitle(R.string.browserFrameFormResubmitLabel)
2950 .setMessage(R.string.browserFrameFormResubmitMessage)
2951 .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
2952 public void onClick(DialogInterface dialog, int which) {
2953 resend.sendToTarget();
2954 }})
2955 .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
2956 public void onClick(DialogInterface dialog, int which) {
2957 dontResend.sendToTarget();
2958 }})
2959 .setOnCancelListener(new OnCancelListener() {
2960 public void onCancel(DialogInterface dialog) {
2961 dontResend.sendToTarget();
2962 }})
2963 .show();
2964 }
2965
2966 /**
2967 * Insert the url into the visited history database.
2968 * @param url The url to be inserted.
2969 * @param isReload True if this url is being reloaded.
2970 * FIXME: Not sure what to do when reloading the page.
2971 */
2972 @Override
2973 public void doUpdateVisitedHistory(WebView view, String url,
2974 boolean isReload) {
2975 if (url.regionMatches(true, 0, "about:", 0, 6)) {
2976 return;
2977 }
Grace Kloba6b52a552009-09-03 16:29:56 -07002978 // remove "client" before updating it to the history so that it wont
2979 // show up in the auto-complete list.
2980 int index = url.indexOf("client=ms-");
2981 if (index > 0 && url.contains(".google.")) {
2982 int end = url.indexOf('&', index);
2983 if (end > 0) {
2984 url = url.substring(0, index-1).concat(url.substring(end));
2985 } else {
2986 url = url.substring(0, index-1);
2987 }
2988 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002989 Browser.updateVisitedHistory(mResolver, url, true);
2990 WebIconDatabase.getInstance().retainIconForPageUrl(url);
2991 }
2992
2993 /**
2994 * Displays SSL error(s) dialog to the user.
2995 */
2996 @Override
2997 public void onReceivedSslError(
2998 final WebView view, final SslErrorHandler handler, final SslError error) {
2999
3000 if (mSettings.showSecurityWarnings()) {
3001 final LayoutInflater factory =
3002 LayoutInflater.from(BrowserActivity.this);
3003 final View warningsView =
3004 factory.inflate(R.layout.ssl_warnings, null);
3005 final LinearLayout placeholder =
3006 (LinearLayout)warningsView.findViewById(R.id.placeholder);
3007
3008 if (error.hasError(SslError.SSL_UNTRUSTED)) {
3009 LinearLayout ll = (LinearLayout)factory
3010 .inflate(R.layout.ssl_warning, null);
3011 ((TextView)ll.findViewById(R.id.warning))
3012 .setText(R.string.ssl_untrusted);
3013 placeholder.addView(ll);
3014 }
3015
3016 if (error.hasError(SslError.SSL_IDMISMATCH)) {
3017 LinearLayout ll = (LinearLayout)factory
3018 .inflate(R.layout.ssl_warning, null);
3019 ((TextView)ll.findViewById(R.id.warning))
3020 .setText(R.string.ssl_mismatch);
3021 placeholder.addView(ll);
3022 }
3023
3024 if (error.hasError(SslError.SSL_EXPIRED)) {
3025 LinearLayout ll = (LinearLayout)factory
3026 .inflate(R.layout.ssl_warning, null);
3027 ((TextView)ll.findViewById(R.id.warning))
3028 .setText(R.string.ssl_expired);
3029 placeholder.addView(ll);
3030 }
3031
3032 if (error.hasError(SslError.SSL_NOTYETVALID)) {
3033 LinearLayout ll = (LinearLayout)factory
3034 .inflate(R.layout.ssl_warning, null);
3035 ((TextView)ll.findViewById(R.id.warning))
3036 .setText(R.string.ssl_not_yet_valid);
3037 placeholder.addView(ll);
3038 }
3039
3040 new AlertDialog.Builder(BrowserActivity.this)
3041 .setTitle(R.string.security_warning)
3042 .setIcon(android.R.drawable.ic_dialog_alert)
3043 .setView(warningsView)
3044 .setPositiveButton(R.string.ssl_continue,
3045 new DialogInterface.OnClickListener() {
3046 public void onClick(DialogInterface dialog, int whichButton) {
3047 handler.proceed();
3048 }
3049 })
3050 .setNeutralButton(R.string.view_certificate,
3051 new DialogInterface.OnClickListener() {
3052 public void onClick(DialogInterface dialog, int whichButton) {
3053 showSSLCertificateOnError(view, handler, error);
3054 }
3055 })
3056 .setNegativeButton(R.string.cancel,
3057 new DialogInterface.OnClickListener() {
3058 public void onClick(DialogInterface dialog, int whichButton) {
3059 handler.cancel();
3060 BrowserActivity.this.resetTitleAndRevertLockIcon();
3061 }
3062 })
3063 .setOnCancelListener(
3064 new DialogInterface.OnCancelListener() {
3065 public void onCancel(DialogInterface dialog) {
3066 handler.cancel();
3067 BrowserActivity.this.resetTitleAndRevertLockIcon();
3068 }
3069 })
3070 .show();
3071 } else {
3072 handler.proceed();
3073 }
3074 }
3075
3076 /**
3077 * Handles an HTTP authentication request.
3078 *
3079 * @param handler The authentication handler
3080 * @param host The host
3081 * @param realm The realm
3082 */
3083 @Override
3084 public void onReceivedHttpAuthRequest(WebView view,
3085 final HttpAuthHandler handler, final String host, final String realm) {
3086 String username = null;
3087 String password = null;
3088
3089 boolean reuseHttpAuthUsernamePassword =
3090 handler.useHttpAuthUsernamePassword();
3091
3092 if (reuseHttpAuthUsernamePassword &&
3093 (mTabControl.getCurrentWebView() != null)) {
3094 String[] credentials =
3095 mTabControl.getCurrentWebView()
3096 .getHttpAuthUsernamePassword(host, realm);
3097 if (credentials != null && credentials.length == 2) {
3098 username = credentials[0];
3099 password = credentials[1];
3100 }
3101 }
3102
3103 if (username != null && password != null) {
3104 handler.proceed(username, password);
3105 } else {
3106 showHttpAuthentication(handler, host, realm, null, null, null, 0);
3107 }
3108 }
3109
3110 @Override
3111 public boolean shouldOverrideKeyEvent(WebView view, KeyEvent event) {
3112 if (mMenuIsDown) {
3113 // only check shortcut key when MENU is held
3114 return getWindow().isShortcutKey(event.getKeyCode(), event);
3115 } else {
3116 return false;
3117 }
3118 }
3119
3120 @Override
3121 public void onUnhandledKeyEvent(WebView view, KeyEvent event) {
3122 if (view != mTabControl.getCurrentTopWebView()) {
3123 return;
3124 }
3125 if (event.isDown()) {
3126 BrowserActivity.this.onKeyDown(event.getKeyCode(), event);
3127 } else {
3128 BrowserActivity.this.onKeyUp(event.getKeyCode(), event);
3129 }
3130 }
3131 };
3132
3133 //--------------------------------------------------------------------------
3134 // WebChromeClient implementation
3135 //--------------------------------------------------------------------------
3136
3137 /* package */ WebChromeClient getWebChromeClient() {
3138 return mWebChromeClient;
3139 }
3140
3141 private final WebChromeClient mWebChromeClient = new WebChromeClient() {
3142 // Helper method to create a new tab or sub window.
3143 private void createWindow(final boolean dialog, final Message msg) {
3144 if (dialog) {
3145 mTabControl.createSubWindow();
3146 final TabControl.Tab t = mTabControl.getCurrentTab();
3147 attachSubWindow(t);
3148 WebView.WebViewTransport transport =
3149 (WebView.WebViewTransport) msg.obj;
3150 transport.setWebView(t.getSubWebView());
3151 msg.sendToTarget();
3152 } else {
3153 final TabControl.Tab parent = mTabControl.getCurrentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04003154 final TabControl.Tab newTab
3155 = openTabAndShow(EMPTY_URL_DATA, false, null);
Grace Klobac9181842009-04-14 08:53:22 -07003156 if (newTab != parent) {
3157 parent.addChildTab(newTab);
3158 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003159 WebView.WebViewTransport transport =
3160 (WebView.WebViewTransport) msg.obj;
3161 transport.setWebView(mTabControl.getCurrentWebView());
Leon Scroggins1f005d32009-08-10 17:36:42 -04003162 msg.sendToTarget();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003163 }
3164 }
3165
3166 @Override
3167 public boolean onCreateWindow(WebView view, final boolean dialog,
3168 final boolean userGesture, final Message resultMsg) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003169 // Short-circuit if we can't create any more tabs or sub windows.
3170 if (dialog && mTabControl.getCurrentSubWindow() != null) {
3171 new AlertDialog.Builder(BrowserActivity.this)
3172 .setTitle(R.string.too_many_subwindows_dialog_title)
3173 .setIcon(android.R.drawable.ic_dialog_alert)
3174 .setMessage(R.string.too_many_subwindows_dialog_message)
3175 .setPositiveButton(R.string.ok, null)
3176 .show();
3177 return false;
3178 } else if (mTabControl.getTabCount() >= TabControl.MAX_TABS) {
3179 new AlertDialog.Builder(BrowserActivity.this)
3180 .setTitle(R.string.too_many_windows_dialog_title)
3181 .setIcon(android.R.drawable.ic_dialog_alert)
3182 .setMessage(R.string.too_many_windows_dialog_message)
3183 .setPositiveButton(R.string.ok, null)
3184 .show();
3185 return false;
3186 }
3187
3188 // Short-circuit if this was a user gesture.
3189 if (userGesture) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003190 createWindow(dialog, resultMsg);
3191 return true;
3192 }
3193
3194 // Allow the popup and create the appropriate window.
3195 final AlertDialog.OnClickListener allowListener =
3196 new AlertDialog.OnClickListener() {
3197 public void onClick(DialogInterface d,
3198 int which) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003199 createWindow(dialog, resultMsg);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003200 }
3201 };
3202
3203 // Block the popup by returning a null WebView.
3204 final AlertDialog.OnClickListener blockListener =
3205 new AlertDialog.OnClickListener() {
3206 public void onClick(DialogInterface d, int which) {
3207 resultMsg.sendToTarget();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003208 }
3209 };
3210
3211 // Build a confirmation dialog to display to the user.
3212 final AlertDialog d =
3213 new AlertDialog.Builder(BrowserActivity.this)
3214 .setTitle(R.string.attention)
3215 .setIcon(android.R.drawable.ic_dialog_alert)
3216 .setMessage(R.string.popup_window_attempt)
3217 .setPositiveButton(R.string.allow, allowListener)
3218 .setNegativeButton(R.string.block, blockListener)
3219 .setCancelable(false)
3220 .create();
3221
3222 // Show the confirmation dialog.
3223 d.show();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003224 return true;
3225 }
3226
3227 @Override
3228 public void onCloseWindow(WebView window) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04003229 final TabControl.Tab current = mTabControl.getCurrentTab();
3230 final TabControl.Tab parent = current.getParentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003231 if (parent != null) {
3232 // JavaScript can only close popup window.
Leon Scroggins1f005d32009-08-10 17:36:42 -04003233 switchToTab(mTabControl.getTabIndex(parent));
3234 // Now we need to close the window
3235 closeTab(current);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003236 }
3237 }
3238
3239 @Override
3240 public void onProgressChanged(WebView view, int newProgress) {
Leon Scroggins68579392009-09-15 15:31:54 -04003241 mTitleBar.setProgress(newProgress);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04003242 if (mFakeTitleBar != null) {
3243 mFakeTitleBar.setProgress(newProgress);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003244 }
3245
3246 if (newProgress == 100) {
Ben Murdochaac7aa62009-09-17 16:57:40 +01003247 // onProgressChanged() may continue to be called after the main
3248 // frame has finished loading, as any remaining sub frames
3249 // continue to load. We'll only get called once though with
3250 // newProgress as 100 when everything is loaded.
3251 // (onPageFinished is called once when the main frame completes
3252 // loading regardless of the state of any sub frames so calls
3253 // to onProgressChanges may continue after onPageFinished has
3254 // executed)
3255
3256 // sync cookies and cache promptly here.
The Android Open Source Project0c908882009-03-03 19:32:16 -08003257 CookieSyncManager.getInstance().sync();
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07003258 if (mInLoad) {
3259 mInLoad = false;
3260 updateInLoadMenuItems();
Leon Scrogginsa27ff192009-09-14 12:58:04 -04003261 // If the options menu is open, leave the title bar
3262 if (!mOptionsMenuOpen || !mIconView) {
3263 hideFakeTitleBar();
3264 }
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07003265 }
Leon Scrogginsa27ff192009-09-14 12:58:04 -04003266 } else if (!mInLoad) {
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07003267 // onPageFinished may have already been called but a subframe
3268 // is still loading and updating the progress. Reset mInLoad
3269 // and update the menu items.
Leon Scrogginsa27ff192009-09-14 12:58:04 -04003270 mInLoad = true;
3271 updateInLoadMenuItems();
Leon Scroggins184f5e32009-09-21 10:38:24 -04003272 if (!mOptionsMenuOpen || mIconView) {
Leon Scrogginsa27ff192009-09-14 12:58:04 -04003273 // This page has begun to load, so show the title bar
3274 showFakeTitleBar();
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07003275 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003276 }
3277 }
3278
3279 @Override
3280 public void onReceivedTitle(WebView view, String title) {
Patrick Scott598c9cc2009-06-04 11:10:38 -04003281 String url = view.getUrl();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003282
3283 // here, if url is null, we want to reset the title
Leon Scroggins68579392009-09-15 15:31:54 -04003284 setUrlTitle(url, title);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003285
3286 if (url == null ||
3287 url.length() >= SQLiteDatabase.SQLITE_MAX_LIKE_PATTERN_LENGTH) {
3288 return;
3289 }
Leon Scrogginsfce182b2009-05-08 13:54:52 -04003290 // See if we can find the current url in our history database and
3291 // add the new title to it.
The Android Open Source Project0c908882009-03-03 19:32:16 -08003292 if (url.startsWith("http://www.")) {
3293 url = url.substring(11);
3294 } else if (url.startsWith("http://")) {
3295 url = url.substring(4);
3296 }
3297 try {
3298 url = "%" + url;
3299 String [] selArgs = new String[] { url };
3300
3301 String where = Browser.BookmarkColumns.URL + " LIKE ? AND "
3302 + Browser.BookmarkColumns.BOOKMARK + " = 0";
3303 Cursor c = mResolver.query(Browser.BOOKMARKS_URI,
3304 Browser.HISTORY_PROJECTION, where, selArgs, null);
3305 if (c.moveToFirst()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003306 // Current implementation of database only has one entry per
3307 // url.
Leon Scrogginsfce182b2009-05-08 13:54:52 -04003308 ContentValues map = new ContentValues();
3309 map.put(Browser.BookmarkColumns.TITLE, title);
3310 mResolver.update(Browser.BOOKMARKS_URI, map,
3311 "_id = " + c.getInt(0), null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003312 }
3313 c.close();
3314 } catch (IllegalStateException e) {
3315 Log.e(LOGTAG, "BrowserActivity onReceived title", e);
3316 } catch (SQLiteException ex) {
3317 Log.e(LOGTAG, "onReceivedTitle() caught SQLiteException: ", ex);
3318 }
3319 }
3320
3321 @Override
3322 public void onReceivedIcon(WebView view, Bitmap icon) {
Patrick Scott3918d442009-08-04 13:22:29 -04003323 updateIcon(view, icon);
3324 }
3325
3326 @Override
Patrick Scott59ce8302009-09-18 16:29:38 -04003327 public void onReceivedTouchIconUrl(WebView view, String url,
3328 boolean precomposed) {
Patrick Scott3918d442009-08-04 13:22:29 -04003329 final ContentResolver cr = getContentResolver();
3330 final Cursor c =
3331 BrowserBookmarksAdapter.queryBookmarksForUrl(cr,
Leon Scrogginsa5d669e2009-08-05 14:07:58 -04003332 view.getOriginalUrl(), view.getUrl(), true);
Patrick Scott3918d442009-08-04 13:22:29 -04003333 if (c != null) {
3334 if (c.getCount() > 0) {
Patrick Scott59ce8302009-09-18 16:29:38 -04003335 // Let precomposed icons take precedence over non-composed
3336 // icons.
3337 if (precomposed && mTouchIconLoader != null) {
3338 mTouchIconLoader.cancel(false);
3339 mTouchIconLoader = null;
3340 }
3341 // Have only one async task at a time.
3342 if (mTouchIconLoader == null) {
3343 mTouchIconLoader = new DownloadTouchIcon(
3344 BrowserActivity.this, cr, c, view);
3345 mTouchIconLoader.execute(url);
3346 }
Patrick Scott3918d442009-08-04 13:22:29 -04003347 } else {
3348 c.close();
3349 }
3350 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003351 }
Ben Murdoch092dd5d2009-04-22 12:34:12 +01003352
Andrei Popescuadc008d2009-06-26 14:11:30 +01003353 @Override
Andrei Popescuc9b55562009-07-07 10:51:15 +01003354 public void onShowCustomView(View view, WebChromeClient.CustomViewCallback callback) {
Andrei Popescuadc008d2009-06-26 14:11:30 +01003355 if (mCustomView != null)
3356 return;
3357
3358 // Add the custom view to its container.
3359 mCustomViewContainer.addView(view, COVER_SCREEN_GRAVITY_CENTER);
3360 mCustomView = view;
Andrei Popescuc9b55562009-07-07 10:51:15 +01003361 mCustomViewCallback = callback;
Andrei Popescuadc008d2009-06-26 14:11:30 +01003362 // Save the menu state and set it to empty while the custom
3363 // view is showing.
3364 mOldMenuState = mMenuState;
3365 mMenuState = EMPTY_MENU;
Andrei Popescuc9b55562009-07-07 10:51:15 +01003366 // Hide the content view.
3367 mContentView.setVisibility(View.GONE);
Andrei Popescuadc008d2009-06-26 14:11:30 +01003368 // Finally show the custom view container.
Andrei Popescuc9b55562009-07-07 10:51:15 +01003369 mCustomViewContainer.setVisibility(View.VISIBLE);
3370 mCustomViewContainer.bringToFront();
Andrei Popescuadc008d2009-06-26 14:11:30 +01003371 }
3372
3373 @Override
3374 public void onHideCustomView() {
3375 if (mCustomView == null)
3376 return;
3377
Andrei Popescuc9b55562009-07-07 10:51:15 +01003378 // Hide the custom view.
3379 mCustomView.setVisibility(View.GONE);
Andrei Popescuadc008d2009-06-26 14:11:30 +01003380 // Remove the custom view from its container.
3381 mCustomViewContainer.removeView(mCustomView);
3382 mCustomView = null;
3383 // Reset the old menu state.
3384 mMenuState = mOldMenuState;
3385 mOldMenuState = EMPTY_MENU;
3386 mCustomViewContainer.setVisibility(View.GONE);
Andrei Popescuc9b55562009-07-07 10:51:15 +01003387 mCustomViewCallback.onCustomViewHidden();
3388 // Show the content view.
3389 mContentView.setVisibility(View.VISIBLE);
Andrei Popescuadc008d2009-06-26 14:11:30 +01003390 }
3391
Ben Murdoch092dd5d2009-04-22 12:34:12 +01003392 /**
Andrei Popescu79e82b72009-07-27 12:01:59 +01003393 * The origin has exceeded its database quota.
Ben Murdoch092dd5d2009-04-22 12:34:12 +01003394 * @param url the URL that exceeded the quota
3395 * @param databaseIdentifier the identifier of the database on
3396 * which the transaction that caused the quota overflow was run
3397 * @param currentQuota the current quota for the origin.
Ben Murdoch25a15232009-08-25 19:38:07 +01003398 * @param estimatedSize the estimated size of the database.
Andrei Popescu79e82b72009-07-27 12:01:59 +01003399 * @param totalUsedQuota is the sum of all origins' quota.
Ben Murdoch092dd5d2009-04-22 12:34:12 +01003400 * @param quotaUpdater The callback to run when a decision to allow or
3401 * deny quota has been made. Don't forget to call this!
3402 */
3403 @Override
3404 public void onExceededDatabaseQuota(String url,
Ben Murdoch25a15232009-08-25 19:38:07 +01003405 String databaseIdentifier, long currentQuota, long estimatedSize,
3406 long totalUsedQuota, WebStorage.QuotaUpdater quotaUpdater) {
Andrei Popescu79e82b72009-07-27 12:01:59 +01003407 mSettings.getWebStorageSizeManager().onExceededDatabaseQuota(
Ben Murdoch25a15232009-08-25 19:38:07 +01003408 url, databaseIdentifier, currentQuota, estimatedSize,
3409 totalUsedQuota, quotaUpdater);
Andrei Popescu79e82b72009-07-27 12:01:59 +01003410 }
3411
3412 /**
3413 * The Application Cache has exceeded its max size.
3414 * @param spaceNeeded is the amount of disk space that would be needed
3415 * in order for the last appcache operation to succeed.
3416 * @param totalUsedQuota is the sum of all origins' quota.
3417 * @param quotaUpdater A callback to inform the WebCore thread that a new
3418 * app cache size is available. This callback must always be executed at
3419 * some point to ensure that the sleeping WebCore thread is woken up.
3420 */
3421 @Override
3422 public void onReachedMaxAppCacheSize(long spaceNeeded,
3423 long totalUsedQuota, WebStorage.QuotaUpdater quotaUpdater) {
3424 mSettings.getWebStorageSizeManager().onReachedMaxAppCacheSize(
3425 spaceNeeded, totalUsedQuota, quotaUpdater);
Ben Murdoch092dd5d2009-04-22 12:34:12 +01003426 }
Ben Murdoch7db26342009-06-03 18:21:19 +01003427
Steve Block2bc69912009-07-30 14:45:13 +01003428 /**
3429 * Instructs the browser to show a prompt to ask the user to set the
3430 * Geolocation permission state for the specified origin.
3431 * @param origin The origin for which Geolocation permissions are
3432 * requested.
3433 * @param callback The callback to call once the user has set the
3434 * Geolocation permission state.
3435 */
3436 @Override
3437 public void onGeolocationPermissionsShowPrompt(String origin,
3438 GeolocationPermissions.Callback callback) {
3439 mTabControl.getCurrentTab().getGeolocationPermissionsPrompt().show(
3440 origin, callback);
3441 }
3442
3443 /**
3444 * Instructs the browser to hide the Geolocation permissions prompt.
3445 */
3446 @Override
3447 public void onGeolocationPermissionsHidePrompt() {
3448 mTabControl.getCurrentTab().getGeolocationPermissionsPrompt().hide();
3449 }
3450
Ben Murdoch7db26342009-06-03 18:21:19 +01003451 /* Adds a JavaScript error message to the system log.
3452 * @param message The error message to report.
3453 * @param lineNumber The line number of the error.
3454 * @param sourceID The name of the source file that caused the error.
3455 */
3456 @Override
3457 public void addMessageToConsole(String message, int lineNumber, String sourceID) {
Ben Murdochbff2d602009-07-01 20:19:05 +01003458 ErrorConsoleView errorConsole = mTabControl.getCurrentErrorConsole(true);
3459 errorConsole.addErrorMessage(message, sourceID, lineNumber);
3460 if (mShouldShowErrorConsole &&
3461 errorConsole.getShowState() != ErrorConsoleView.SHOW_MAXIMIZED) {
3462 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
3463 }
3464 Log.w(LOGTAG, "Console: " + message + " " + sourceID + ":" + lineNumber);
Ben Murdoch7db26342009-06-03 18:21:19 +01003465 }
Andrei Popescu540035d2009-09-18 18:59:20 +01003466
3467 /**
3468 * Ask the browser for an icon to represent a <video> element.
3469 * This icon will be used if the Web page did not specify a poster attribute.
3470 *
3471 * @return Bitmap The icon or null if no such icon is available.
3472 * @hide pending API Council approval
3473 */
3474 @Override
3475 public Bitmap getDefaultVideoPoster() {
3476 if (mDefaultVideoPoster == null) {
3477 mDefaultVideoPoster = BitmapFactory.decodeResource(
3478 getResources(), R.drawable.default_video_poster);
3479 }
3480 return mDefaultVideoPoster;
3481 }
3482
3483 /**
3484 * Ask the host application for a custom progress view to show while
3485 * a <video> is loading.
3486 *
3487 * @return View The progress view.
3488 * @hide pending API Council approval
3489 */
3490 @Override
3491 public View getVideoLoadingProgressView() {
3492 if (mVideoProgressView == null) {
3493 LayoutInflater inflater = LayoutInflater.from(BrowserActivity.this);
3494 mVideoProgressView = inflater.inflate(R.layout.video_loading_progress, null);
3495 }
3496 return mVideoProgressView;
3497 }
Leon Clarkecb6cc862009-09-29 18:35:13 +01003498
3499 /**
3500 * Deliver a list of already-visited URLs
3501 * @hide pending API Council approval
3502 */
3503 @Override
3504 public void getVisitedHistory(final ValueCallback<String[]> callback) {
3505 AsyncTask<Void, Void, String[]> task = new AsyncTask<Void, Void, String[]>() {
3506 public String[] doInBackground(Void... unused) {
3507 return Browser.getVisitedHistory(getContentResolver());
3508 }
3509
3510 public void onPostExecute(String[] result) {
3511 callback.onReceiveValue(result);
3512
3513 };
3514 };
3515 task.execute();
3516 };
The Android Open Source Project0c908882009-03-03 19:32:16 -08003517 };
3518
3519 /**
3520 * Notify the host application a download should be done, or that
3521 * the data should be streamed if a streaming viewer is available.
3522 * @param url The full url to the content that should be downloaded
3523 * @param contentDisposition Content-disposition http header, if
3524 * present.
3525 * @param mimetype The mimetype of the content reported by the server
3526 * @param contentLength The file size reported by the server
3527 */
3528 public void onDownloadStart(String url, String userAgent,
3529 String contentDisposition, String mimetype, long contentLength) {
3530 // if we're dealing wih A/V content that's not explicitly marked
3531 // for download, check if it's streamable.
3532 if (contentDisposition == null
Patrick Scotte1fb9662009-08-31 14:31:52 -04003533 || !contentDisposition.regionMatches(
3534 true, 0, "attachment", 0, 10)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003535 // query the package manager to see if there's a registered handler
3536 // that matches.
3537 Intent intent = new Intent(Intent.ACTION_VIEW);
3538 intent.setDataAndType(Uri.parse(url), mimetype);
Patrick Scotte1fb9662009-08-31 14:31:52 -04003539 ResolveInfo info = getPackageManager().resolveActivity(intent,
3540 PackageManager.MATCH_DEFAULT_ONLY);
3541 if (info != null) {
3542 ComponentName myName = getComponentName();
3543 // If we resolved to ourselves, we don't want to attempt to
3544 // load the url only to try and download it again.
3545 if (!myName.getPackageName().equals(
3546 info.activityInfo.packageName)
3547 || !myName.getClassName().equals(
3548 info.activityInfo.name)) {
3549 // someone (other than us) knows how to handle this mime
3550 // type with this scheme, don't download.
3551 try {
3552 startActivity(intent);
3553 return;
3554 } catch (ActivityNotFoundException ex) {
3555 if (LOGD_ENABLED) {
3556 Log.d(LOGTAG, "activity not found for " + mimetype
3557 + " over " + Uri.parse(url).getScheme(),
3558 ex);
3559 }
3560 // Best behavior is to fall back to a download in this
3561 // case
The Android Open Source Project0c908882009-03-03 19:32:16 -08003562 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003563 }
3564 }
3565 }
3566 onDownloadStartNoStream(url, userAgent, contentDisposition, mimetype, contentLength);
3567 }
3568
3569 /**
3570 * Notify the host application a download should be done, even if there
3571 * is a streaming viewer available for thise type.
3572 * @param url The full url to the content that should be downloaded
3573 * @param contentDisposition Content-disposition http header, if
3574 * present.
3575 * @param mimetype The mimetype of the content reported by the server
3576 * @param contentLength The file size reported by the server
3577 */
3578 /*package */ void onDownloadStartNoStream(String url, String userAgent,
3579 String contentDisposition, String mimetype, long contentLength) {
3580
3581 String filename = URLUtil.guessFileName(url,
3582 contentDisposition, mimetype);
3583
3584 // Check to see if we have an SDCard
3585 String status = Environment.getExternalStorageState();
3586 if (!status.equals(Environment.MEDIA_MOUNTED)) {
3587 int title;
3588 String msg;
3589
3590 // Check to see if the SDCard is busy, same as the music app
3591 if (status.equals(Environment.MEDIA_SHARED)) {
3592 msg = getString(R.string.download_sdcard_busy_dlg_msg);
3593 title = R.string.download_sdcard_busy_dlg_title;
3594 } else {
3595 msg = getString(R.string.download_no_sdcard_dlg_msg, filename);
3596 title = R.string.download_no_sdcard_dlg_title;
3597 }
3598
3599 new AlertDialog.Builder(this)
3600 .setTitle(title)
3601 .setIcon(android.R.drawable.ic_dialog_alert)
3602 .setMessage(msg)
3603 .setPositiveButton(R.string.ok, null)
3604 .show();
3605 return;
3606 }
3607
3608 // java.net.URI is a lot stricter than KURL so we have to undo
3609 // KURL's percent-encoding and redo the encoding using java.net.URI.
3610 URI uri = null;
3611 try {
3612 // Undo the percent-encoding that KURL may have done.
3613 String newUrl = new String(URLUtil.decode(url.getBytes()));
3614 // Parse the url into pieces
3615 WebAddress w = new WebAddress(newUrl);
3616 String frag = null;
3617 String query = null;
3618 String path = w.mPath;
3619 // Break the path into path, query, and fragment
3620 if (path.length() > 0) {
3621 // Strip the fragment
3622 int idx = path.lastIndexOf('#');
3623 if (idx != -1) {
3624 frag = path.substring(idx + 1);
3625 path = path.substring(0, idx);
3626 }
3627 idx = path.lastIndexOf('?');
3628 if (idx != -1) {
3629 query = path.substring(idx + 1);
3630 path = path.substring(0, idx);
3631 }
3632 }
3633 uri = new URI(w.mScheme, w.mAuthInfo, w.mHost, w.mPort, path,
3634 query, frag);
3635 } catch (Exception e) {
3636 Log.e(LOGTAG, "Could not parse url for download: " + url, e);
3637 return;
3638 }
3639
3640 // XXX: Have to use the old url since the cookies were stored using the
3641 // old percent-encoded url.
3642 String cookies = CookieManager.getInstance().getCookie(url);
3643
3644 ContentValues values = new ContentValues();
Jean-Baptiste Queru3dc09b22009-03-31 16:49:44 -07003645 values.put(Downloads.COLUMN_URI, uri.toString());
3646 values.put(Downloads.COLUMN_COOKIE_DATA, cookies);
3647 values.put(Downloads.COLUMN_USER_AGENT, userAgent);
3648 values.put(Downloads.COLUMN_NOTIFICATION_PACKAGE,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003649 getPackageName());
Jean-Baptiste Queru3dc09b22009-03-31 16:49:44 -07003650 values.put(Downloads.COLUMN_NOTIFICATION_CLASS,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003651 BrowserDownloadPage.class.getCanonicalName());
Jean-Baptiste Queru3dc09b22009-03-31 16:49:44 -07003652 values.put(Downloads.COLUMN_VISIBILITY, Downloads.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
3653 values.put(Downloads.COLUMN_MIME_TYPE, mimetype);
3654 values.put(Downloads.COLUMN_FILE_NAME_HINT, filename);
3655 values.put(Downloads.COLUMN_DESCRIPTION, uri.getHost());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003656 if (contentLength > 0) {
Jean-Baptiste Queru3dc09b22009-03-31 16:49:44 -07003657 values.put(Downloads.COLUMN_TOTAL_BYTES, contentLength);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003658 }
3659 if (mimetype == null) {
3660 // We must have long pressed on a link or image to download it. We
3661 // are not sure of the mimetype in this case, so do a head request
3662 new FetchUrlMimeType(this).execute(values);
3663 } else {
3664 final Uri contentUri =
3665 getContentResolver().insert(Downloads.CONTENT_URI, values);
3666 viewDownloads(contentUri);
3667 }
3668
3669 }
3670
3671 /**
3672 * Resets the lock icon. This method is called when we start a new load and
3673 * know the url to be loaded.
3674 */
3675 private void resetLockIcon(String url) {
3676 // Save the lock-icon state (we revert to it if the load gets cancelled)
3677 saveLockIcon();
3678
3679 mLockIconType = LOCK_ICON_UNSECURE;
3680 if (URLUtil.isHttpsUrl(url)) {
3681 mLockIconType = LOCK_ICON_SECURE;
Dave Bort31a6d1c2009-04-13 15:56:49 -07003682 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003683 Log.v(LOGTAG, "BrowserActivity.resetLockIcon:" +
3684 " reset lock icon to " + mLockIconType);
3685 }
3686 }
3687
3688 updateLockIconImage(LOCK_ICON_UNSECURE);
3689 }
3690
Grace Klobaeb6eef42009-09-15 17:56:32 -07003691 /* package */ void setLockIconType(int type) {
3692 mLockIconType = type;
3693 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003694
Grace Klobaeb6eef42009-09-15 17:56:32 -07003695 /* package */ int getLockIconType() {
3696 return mLockIconType;
3697 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003698
Grace Klobaeb6eef42009-09-15 17:56:32 -07003699 /* package */ void setPrevLockType(int type) {
3700 mPrevLockType = type;
3701 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003702
Grace Klobaeb6eef42009-09-15 17:56:32 -07003703 /* package */ int getPrevLockType() {
3704 return mPrevLockType;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003705 }
3706
3707 /**
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04003708 * Update the lock icon to correspond to our latest state.
3709 */
3710 /* package */ void updateLockIconToLatest() {
3711 updateLockIconImage(mLockIconType);
3712 }
3713
3714 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08003715 * Updates the lock-icon image in the title-bar.
3716 */
3717 private void updateLockIconImage(int lockIconType) {
3718 Drawable d = null;
3719 if (lockIconType == LOCK_ICON_SECURE) {
3720 d = mSecLockIcon;
3721 } else if (lockIconType == LOCK_ICON_MIXED) {
3722 d = mMixLockIcon;
3723 }
Leon Scroggins68579392009-09-15 15:31:54 -04003724 mTitleBar.setLock(d);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04003725 if (mFakeTitleBar != null) {
3726 mFakeTitleBar.setLock(d);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003727 }
3728 }
3729
3730 /**
3731 * Displays a page-info dialog.
3732 * @param tab The tab to show info about
3733 * @param fromShowSSLCertificateOnError The flag that indicates whether
3734 * this dialog was opened from the SSL-certificate-on-error dialog or
3735 * not. This is important, since we need to know whether to return to
3736 * the parent dialog or simply dismiss.
3737 */
3738 private void showPageInfo(final TabControl.Tab tab,
3739 final boolean fromShowSSLCertificateOnError) {
3740 final LayoutInflater factory = LayoutInflater
3741 .from(this);
3742
3743 final View pageInfoView = factory.inflate(R.layout.page_info, null);
3744
3745 final WebView view = tab.getWebView();
3746
3747 String url = null;
3748 String title = null;
3749
3750 if (view == null) {
3751 url = tab.getUrl();
3752 title = tab.getTitle();
3753 } else if (view == mTabControl.getCurrentWebView()) {
3754 // Use the cached title and url if this is the current WebView
3755 url = mUrl;
3756 title = mTitle;
3757 } else {
3758 url = view.getUrl();
3759 title = view.getTitle();
3760 }
3761
3762 if (url == null) {
3763 url = "";
3764 }
3765 if (title == null) {
3766 title = "";
3767 }
3768
3769 ((TextView) pageInfoView.findViewById(R.id.address)).setText(url);
3770 ((TextView) pageInfoView.findViewById(R.id.title)).setText(title);
3771
3772 mPageInfoView = tab;
3773 mPageInfoFromShowSSLCertificateOnError = new Boolean(fromShowSSLCertificateOnError);
3774
3775 AlertDialog.Builder alertDialogBuilder =
3776 new AlertDialog.Builder(this)
3777 .setTitle(R.string.page_info).setIcon(android.R.drawable.ic_dialog_info)
3778 .setView(pageInfoView)
3779 .setPositiveButton(
3780 R.string.ok,
3781 new DialogInterface.OnClickListener() {
3782 public void onClick(DialogInterface dialog,
3783 int whichButton) {
3784 mPageInfoDialog = null;
3785 mPageInfoView = null;
3786 mPageInfoFromShowSSLCertificateOnError = null;
3787
3788 // if we came here from the SSL error dialog
3789 if (fromShowSSLCertificateOnError) {
3790 // go back to the SSL error dialog
3791 showSSLCertificateOnError(
3792 mSSLCertificateOnErrorView,
3793 mSSLCertificateOnErrorHandler,
3794 mSSLCertificateOnErrorError);
3795 }
3796 }
3797 })
3798 .setOnCancelListener(
3799 new DialogInterface.OnCancelListener() {
3800 public void onCancel(DialogInterface dialog) {
3801 mPageInfoDialog = null;
3802 mPageInfoView = null;
3803 mPageInfoFromShowSSLCertificateOnError = null;
3804
3805 // if we came here from the SSL error dialog
3806 if (fromShowSSLCertificateOnError) {
3807 // go back to the SSL error dialog
3808 showSSLCertificateOnError(
3809 mSSLCertificateOnErrorView,
3810 mSSLCertificateOnErrorHandler,
3811 mSSLCertificateOnErrorError);
3812 }
3813 }
3814 });
3815
3816 // if we have a main top-level page SSL certificate set or a certificate
3817 // error
3818 if (fromShowSSLCertificateOnError ||
3819 (view != null && view.getCertificate() != null)) {
3820 // add a 'View Certificate' button
3821 alertDialogBuilder.setNeutralButton(
3822 R.string.view_certificate,
3823 new DialogInterface.OnClickListener() {
3824 public void onClick(DialogInterface dialog,
3825 int whichButton) {
3826 mPageInfoDialog = null;
3827 mPageInfoView = null;
3828 mPageInfoFromShowSSLCertificateOnError = null;
3829
3830 // if we came here from the SSL error dialog
3831 if (fromShowSSLCertificateOnError) {
3832 // go back to the SSL error dialog
3833 showSSLCertificateOnError(
3834 mSSLCertificateOnErrorView,
3835 mSSLCertificateOnErrorHandler,
3836 mSSLCertificateOnErrorError);
3837 } else {
3838 // otherwise, display the top-most certificate from
3839 // the chain
3840 if (view.getCertificate() != null) {
3841 showSSLCertificate(tab);
3842 }
3843 }
3844 }
3845 });
3846 }
3847
3848 mPageInfoDialog = alertDialogBuilder.show();
3849 }
3850
3851 /**
3852 * Displays the main top-level page SSL certificate dialog
3853 * (accessible from the Page-Info dialog).
3854 * @param tab The tab to show certificate for.
3855 */
3856 private void showSSLCertificate(final TabControl.Tab tab) {
3857 final View certificateView =
3858 inflateCertificateView(tab.getWebView().getCertificate());
3859 if (certificateView == null) {
3860 return;
3861 }
3862
3863 LayoutInflater factory = LayoutInflater.from(this);
3864
3865 final LinearLayout placeholder =
3866 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3867
3868 LinearLayout ll = (LinearLayout) factory.inflate(
3869 R.layout.ssl_success, placeholder);
3870 ((TextView)ll.findViewById(R.id.success))
3871 .setText(R.string.ssl_certificate_is_valid);
3872
3873 mSSLCertificateView = tab;
3874 mSSLCertificateDialog =
3875 new AlertDialog.Builder(this)
3876 .setTitle(R.string.ssl_certificate).setIcon(
3877 R.drawable.ic_dialog_browser_certificate_secure)
3878 .setView(certificateView)
3879 .setPositiveButton(R.string.ok,
3880 new DialogInterface.OnClickListener() {
3881 public void onClick(DialogInterface dialog,
3882 int whichButton) {
3883 mSSLCertificateDialog = null;
3884 mSSLCertificateView = null;
3885
3886 showPageInfo(tab, false);
3887 }
3888 })
3889 .setOnCancelListener(
3890 new DialogInterface.OnCancelListener() {
3891 public void onCancel(DialogInterface dialog) {
3892 mSSLCertificateDialog = null;
3893 mSSLCertificateView = null;
3894
3895 showPageInfo(tab, false);
3896 }
3897 })
3898 .show();
3899 }
3900
3901 /**
3902 * Displays the SSL error certificate dialog.
3903 * @param view The target web-view.
3904 * @param handler The SSL error handler responsible for cancelling the
3905 * connection that resulted in an SSL error or proceeding per user request.
3906 * @param error The SSL error object.
3907 */
3908 private void showSSLCertificateOnError(
3909 final WebView view, final SslErrorHandler handler, final SslError error) {
3910
3911 final View certificateView =
3912 inflateCertificateView(error.getCertificate());
3913 if (certificateView == null) {
3914 return;
3915 }
3916
3917 LayoutInflater factory = LayoutInflater.from(this);
3918
3919 final LinearLayout placeholder =
3920 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3921
3922 if (error.hasError(SslError.SSL_UNTRUSTED)) {
3923 LinearLayout ll = (LinearLayout)factory
3924 .inflate(R.layout.ssl_warning, placeholder);
3925 ((TextView)ll.findViewById(R.id.warning))
3926 .setText(R.string.ssl_untrusted);
3927 }
3928
3929 if (error.hasError(SslError.SSL_IDMISMATCH)) {
3930 LinearLayout ll = (LinearLayout)factory
3931 .inflate(R.layout.ssl_warning, placeholder);
3932 ((TextView)ll.findViewById(R.id.warning))
3933 .setText(R.string.ssl_mismatch);
3934 }
3935
3936 if (error.hasError(SslError.SSL_EXPIRED)) {
3937 LinearLayout ll = (LinearLayout)factory
3938 .inflate(R.layout.ssl_warning, placeholder);
3939 ((TextView)ll.findViewById(R.id.warning))
3940 .setText(R.string.ssl_expired);
3941 }
3942
3943 if (error.hasError(SslError.SSL_NOTYETVALID)) {
3944 LinearLayout ll = (LinearLayout)factory
3945 .inflate(R.layout.ssl_warning, placeholder);
3946 ((TextView)ll.findViewById(R.id.warning))
3947 .setText(R.string.ssl_not_yet_valid);
3948 }
3949
3950 mSSLCertificateOnErrorHandler = handler;
3951 mSSLCertificateOnErrorView = view;
3952 mSSLCertificateOnErrorError = error;
3953 mSSLCertificateOnErrorDialog =
3954 new AlertDialog.Builder(this)
3955 .setTitle(R.string.ssl_certificate).setIcon(
3956 R.drawable.ic_dialog_browser_certificate_partially_secure)
3957 .setView(certificateView)
3958 .setPositiveButton(R.string.ok,
3959 new DialogInterface.OnClickListener() {
3960 public void onClick(DialogInterface dialog,
3961 int whichButton) {
3962 mSSLCertificateOnErrorDialog = null;
3963 mSSLCertificateOnErrorView = null;
3964 mSSLCertificateOnErrorHandler = null;
3965 mSSLCertificateOnErrorError = null;
3966
3967 mWebViewClient.onReceivedSslError(
3968 view, handler, error);
3969 }
3970 })
3971 .setNeutralButton(R.string.page_info_view,
3972 new DialogInterface.OnClickListener() {
3973 public void onClick(DialogInterface dialog,
3974 int whichButton) {
3975 mSSLCertificateOnErrorDialog = null;
3976
3977 // do not clear the dialog state: we will
3978 // need to show the dialog again once the
3979 // user is done exploring the page-info details
3980
3981 showPageInfo(mTabControl.getTabFromView(view),
3982 true);
3983 }
3984 })
3985 .setOnCancelListener(
3986 new DialogInterface.OnCancelListener() {
3987 public void onCancel(DialogInterface dialog) {
3988 mSSLCertificateOnErrorDialog = null;
3989 mSSLCertificateOnErrorView = null;
3990 mSSLCertificateOnErrorHandler = null;
3991 mSSLCertificateOnErrorError = null;
3992
3993 mWebViewClient.onReceivedSslError(
3994 view, handler, error);
3995 }
3996 })
3997 .show();
3998 }
3999
4000 /**
4001 * Inflates the SSL certificate view (helper method).
4002 * @param certificate The SSL certificate.
4003 * @return The resultant certificate view with issued-to, issued-by,
4004 * issued-on, expires-on, and possibly other fields set.
4005 * If the input certificate is null, returns null.
4006 */
4007 private View inflateCertificateView(SslCertificate certificate) {
4008 if (certificate == null) {
4009 return null;
4010 }
4011
4012 LayoutInflater factory = LayoutInflater.from(this);
4013
4014 View certificateView = factory.inflate(
4015 R.layout.ssl_certificate, null);
4016
4017 // issued to:
4018 SslCertificate.DName issuedTo = certificate.getIssuedTo();
4019 if (issuedTo != null) {
4020 ((TextView) certificateView.findViewById(R.id.to_common))
4021 .setText(issuedTo.getCName());
4022 ((TextView) certificateView.findViewById(R.id.to_org))
4023 .setText(issuedTo.getOName());
4024 ((TextView) certificateView.findViewById(R.id.to_org_unit))
4025 .setText(issuedTo.getUName());
4026 }
4027
4028 // issued by:
4029 SslCertificate.DName issuedBy = certificate.getIssuedBy();
4030 if (issuedBy != null) {
4031 ((TextView) certificateView.findViewById(R.id.by_common))
4032 .setText(issuedBy.getCName());
4033 ((TextView) certificateView.findViewById(R.id.by_org))
4034 .setText(issuedBy.getOName());
4035 ((TextView) certificateView.findViewById(R.id.by_org_unit))
4036 .setText(issuedBy.getUName());
4037 }
4038
4039 // issued on:
4040 String issuedOn = reformatCertificateDate(
4041 certificate.getValidNotBefore());
4042 ((TextView) certificateView.findViewById(R.id.issued_on))
4043 .setText(issuedOn);
4044
4045 // expires on:
4046 String expiresOn = reformatCertificateDate(
4047 certificate.getValidNotAfter());
4048 ((TextView) certificateView.findViewById(R.id.expires_on))
4049 .setText(expiresOn);
4050
4051 return certificateView;
4052 }
4053
4054 /**
4055 * Re-formats the certificate date (Date.toString()) string to
4056 * a properly localized date string.
4057 * @return Properly localized version of the certificate date string and
4058 * the original certificate date string if fails to localize.
4059 * If the original string is null, returns an empty string "".
4060 */
4061 private String reformatCertificateDate(String certificateDate) {
4062 String reformattedDate = null;
4063
4064 if (certificateDate != null) {
4065 Date date = null;
4066 try {
4067 date = java.text.DateFormat.getInstance().parse(certificateDate);
4068 } catch (ParseException e) {
4069 date = null;
4070 }
4071
4072 if (date != null) {
4073 reformattedDate =
4074 DateFormat.getDateFormat(this).format(date);
4075 }
4076 }
4077
4078 return reformattedDate != null ? reformattedDate :
4079 (certificateDate != null ? certificateDate : "");
4080 }
4081
4082 /**
4083 * Displays an http-authentication dialog.
4084 */
4085 private void showHttpAuthentication(final HttpAuthHandler handler,
4086 final String host, final String realm, final String title,
4087 final String name, final String password, int focusId) {
4088 LayoutInflater factory = LayoutInflater.from(this);
4089 final View v = factory
4090 .inflate(R.layout.http_authentication, null);
4091 if (name != null) {
4092 ((EditText) v.findViewById(R.id.username_edit)).setText(name);
4093 }
4094 if (password != null) {
4095 ((EditText) v.findViewById(R.id.password_edit)).setText(password);
4096 }
4097
4098 String titleText = title;
4099 if (titleText == null) {
4100 titleText = getText(R.string.sign_in_to).toString().replace(
4101 "%s1", host).replace("%s2", realm);
4102 }
4103
4104 mHttpAuthHandler = handler;
4105 AlertDialog dialog = new AlertDialog.Builder(this)
4106 .setTitle(titleText)
4107 .setIcon(android.R.drawable.ic_dialog_alert)
4108 .setView(v)
4109 .setPositiveButton(R.string.action,
4110 new DialogInterface.OnClickListener() {
4111 public void onClick(DialogInterface dialog,
4112 int whichButton) {
4113 String nm = ((EditText) v
4114 .findViewById(R.id.username_edit))
4115 .getText().toString();
4116 String pw = ((EditText) v
4117 .findViewById(R.id.password_edit))
4118 .getText().toString();
4119 BrowserActivity.this.setHttpAuthUsernamePassword
4120 (host, realm, nm, pw);
4121 handler.proceed(nm, pw);
4122 mHttpAuthenticationDialog = null;
4123 mHttpAuthHandler = null;
4124 }})
4125 .setNegativeButton(R.string.cancel,
4126 new DialogInterface.OnClickListener() {
4127 public void onClick(DialogInterface dialog,
4128 int whichButton) {
4129 handler.cancel();
4130 BrowserActivity.this.resetTitleAndRevertLockIcon();
4131 mHttpAuthenticationDialog = null;
4132 mHttpAuthHandler = null;
4133 }})
4134 .setOnCancelListener(new DialogInterface.OnCancelListener() {
4135 public void onCancel(DialogInterface dialog) {
4136 handler.cancel();
4137 BrowserActivity.this.resetTitleAndRevertLockIcon();
4138 mHttpAuthenticationDialog = null;
4139 mHttpAuthHandler = null;
4140 }})
4141 .create();
4142 // Make the IME appear when the dialog is displayed if applicable.
4143 dialog.getWindow().setSoftInputMode(
4144 WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
4145 dialog.show();
4146 if (focusId != 0) {
4147 dialog.findViewById(focusId).requestFocus();
4148 } else {
4149 v.findViewById(R.id.username_edit).requestFocus();
4150 }
4151 mHttpAuthenticationDialog = dialog;
4152 }
4153
4154 public int getProgress() {
4155 WebView w = mTabControl.getCurrentWebView();
4156 if (w != null) {
4157 return w.getProgress();
4158 } else {
4159 return 100;
4160 }
4161 }
4162
4163 /**
4164 * Set HTTP authentication password.
4165 *
4166 * @param host The host for the password
4167 * @param realm The realm for the password
4168 * @param username The username for the password. If it is null, it means
4169 * password can't be saved.
4170 * @param password The password
4171 */
4172 public void setHttpAuthUsernamePassword(String host, String realm,
4173 String username,
4174 String password) {
4175 WebView w = mTabControl.getCurrentWebView();
4176 if (w != null) {
4177 w.setHttpAuthUsernamePassword(host, realm, username, password);
4178 }
4179 }
4180
4181 /**
4182 * connectivity manager says net has come or gone... inform the user
4183 * @param up true if net has come up, false if net has gone down
4184 */
4185 public void onNetworkToggle(boolean up) {
4186 if (up == mIsNetworkUp) {
4187 return;
4188 } else if (up) {
4189 mIsNetworkUp = true;
4190 if (mAlertDialog != null) {
4191 mAlertDialog.cancel();
4192 mAlertDialog = null;
4193 }
4194 } else {
4195 mIsNetworkUp = false;
Patrick Scotteb6ab2a2009-09-16 10:00:17 -04004196 if (mInLoad) {
4197 createAndShowNetworkDialog();
4198 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08004199 }
4200 WebView w = mTabControl.getCurrentWebView();
4201 if (w != null) {
4202 w.setNetworkAvailable(up);
4203 }
4204 }
4205
Patrick Scotteb6ab2a2009-09-16 10:00:17 -04004206 // This method shows the network dialog alerting the user that the net is
4207 // down. It will only show the dialog if mAlertDialog is null.
4208 private void createAndShowNetworkDialog() {
4209 if (mAlertDialog == null) {
4210 mAlertDialog = new AlertDialog.Builder(this)
4211 .setTitle(R.string.loadSuspendedTitle)
4212 .setMessage(R.string.loadSuspended)
4213 .setPositiveButton(R.string.ok, null)
4214 .show();
4215 }
4216 }
4217
The Android Open Source Project0c908882009-03-03 19:32:16 -08004218 @Override
4219 protected void onActivityResult(int requestCode, int resultCode,
4220 Intent intent) {
4221 switch (requestCode) {
4222 case COMBO_PAGE:
4223 if (resultCode == RESULT_OK && intent != null) {
4224 String data = intent.getAction();
4225 Bundle extras = intent.getExtras();
4226 if (extras != null && extras.getBoolean("new_window", false)) {
Leon Scroggins25d35472009-09-15 11:37:27 -04004227 openTab(data);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004228 } else {
4229 final TabControl.Tab currentTab =
4230 mTabControl.getCurrentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04004231 dismissSubWindow(currentTab);
4232 if (data != null && data.length() != 0) {
4233 getTopWindow().loadUrl(data);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004234 }
4235 }
4236 }
4237 break;
4238 default:
4239 break;
4240 }
Leon Scroggins30444232009-09-04 18:36:20 -04004241 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08004242 }
4243
4244 /*
4245 * This method is called as a result of the user selecting the options
4246 * menu to see the download window, or when a download changes state. It
4247 * shows the download window ontop of the current window.
4248 */
4249 /* package */ void viewDownloads(Uri downloadRecord) {
4250 Intent intent = new Intent(this,
4251 BrowserDownloadPage.class);
4252 intent.setData(downloadRecord);
4253 startActivityForResult(intent, this.DOWNLOAD_PAGE);
4254
4255 }
4256
Leon Scroggins160a7e72009-08-14 18:28:01 -04004257 /**
4258 * Open the Go page.
4259 * @param startWithHistory If true, open starting on the history tab.
4260 * Otherwise, start with the bookmarks tab.
Leon Scroggins160a7e72009-08-14 18:28:01 -04004261 */
Leon Scroggins30444232009-09-04 18:36:20 -04004262 /* package */ void bookmarksOrHistoryPicker(boolean startWithHistory) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08004263 WebView current = mTabControl.getCurrentWebView();
4264 if (current == null) {
4265 return;
4266 }
4267 Intent intent = new Intent(this,
4268 CombinedBookmarkHistoryActivity.class);
4269 String title = current.getTitle();
4270 String url = current.getUrl();
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01004271 Bitmap thumbnail = createScreenshot(current);
4272
The Android Open Source Project0c908882009-03-03 19:32:16 -08004273 // Just in case the user opens bookmarks before a page finishes loading
4274 // so the current history item, and therefore the page, is null.
4275 if (null == url) {
4276 url = mLastEnteredUrl;
4277 // This can happen.
4278 if (null == url) {
4279 url = mSettings.getHomePage();
4280 }
4281 }
4282 // In case the web page has not yet received its associated title.
4283 if (title == null) {
4284 title = url;
4285 }
4286 intent.putExtra("title", title);
4287 intent.putExtra("url", url);
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01004288 intent.putExtra("thumbnail", thumbnail);
Leon Scroggins30444232009-09-04 18:36:20 -04004289 // Disable opening in a new window if we have maxed out the windows
4290 intent.putExtra("disable_new_window", mTabControl.getTabCount()
4291 >= TabControl.MAX_TABS);
Patrick Scott3918d442009-08-04 13:22:29 -04004292 intent.putExtra("touch_icon_url", current.getTouchIconUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08004293 if (startWithHistory) {
4294 intent.putExtra(CombinedBookmarkHistoryActivity.STARTING_TAB,
4295 CombinedBookmarkHistoryActivity.HISTORY_TAB);
4296 }
4297 startActivityForResult(intent, COMBO_PAGE);
4298 }
4299
4300 // Called when loading from context menu or LOAD_URL message
4301 private void loadURL(WebView view, String url) {
4302 // In case the user enters nothing.
4303 if (url != null && url.length() != 0 && view != null) {
4304 url = smartUrlFilter(url);
4305 if (!mWebViewClient.shouldOverrideUrlLoading(view, url)) {
4306 view.loadUrl(url);
4307 }
4308 }
4309 }
4310
The Android Open Source Project0c908882009-03-03 19:32:16 -08004311 private String smartUrlFilter(Uri inUri) {
4312 if (inUri != null) {
4313 return smartUrlFilter(inUri.toString());
4314 }
4315 return null;
4316 }
4317
4318
4319 // get window count
4320
4321 int getWindowCount(){
4322 if(mTabControl != null){
4323 return mTabControl.getTabCount();
4324 }
4325 return 0;
4326 }
4327
Feng Qianb34f87a2009-03-24 21:27:26 -07004328 protected static final Pattern ACCEPTED_URI_SCHEMA = Pattern.compile(
The Android Open Source Project0c908882009-03-03 19:32:16 -08004329 "(?i)" + // switch on case insensitive matching
4330 "(" + // begin group for schema
4331 "(?:http|https|file):\\/\\/" +
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004332 "|(?:inline|data|about|content|javascript):" +
The Android Open Source Project0c908882009-03-03 19:32:16 -08004333 ")" +
4334 "(.*)" );
4335
4336 /**
4337 * Attempts to determine whether user input is a URL or search
4338 * terms. Anything with a space is passed to search.
4339 *
4340 * Converts to lowercase any mistakenly uppercased schema (i.e.,
4341 * "Http://" converts to "http://"
4342 *
4343 * @return Original or modified URL
4344 *
4345 */
4346 String smartUrlFilter(String url) {
4347
4348 String inUrl = url.trim();
4349 boolean hasSpace = inUrl.indexOf(' ') != -1;
4350
4351 Matcher matcher = ACCEPTED_URI_SCHEMA.matcher(inUrl);
4352 if (matcher.matches()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08004353 // force scheme to lowercase
4354 String scheme = matcher.group(1);
4355 String lcScheme = scheme.toLowerCase();
4356 if (!lcScheme.equals(scheme)) {
Mitsuru Oshima123ecfb2009-05-18 19:11:14 -07004357 inUrl = lcScheme + matcher.group(2);
4358 }
4359 if (hasSpace) {
4360 inUrl = inUrl.replace(" ", "%20");
The Android Open Source Project0c908882009-03-03 19:32:16 -08004361 }
4362 return inUrl;
4363 }
4364 if (hasSpace) {
Satish Sampath565505b2009-05-29 15:37:27 +01004365 // FIXME: Is this the correct place to add to searches?
4366 // what if someone else calls this function?
4367 int shortcut = parseUrlShortcut(inUrl);
4368 if (shortcut != SHORTCUT_INVALID) {
4369 Browser.addSearchUrl(mResolver, inUrl);
4370 String query = inUrl.substring(2);
4371 switch (shortcut) {
4372 case SHORTCUT_GOOGLE_SEARCH:
Grace Kloba47fdfdb2009-06-30 11:15:34 -07004373 return URLUtil.composeSearchUrl(query, QuickSearch_G, QUERY_PLACE_HOLDER);
Satish Sampath565505b2009-05-29 15:37:27 +01004374 case SHORTCUT_WIKIPEDIA_SEARCH:
4375 return URLUtil.composeSearchUrl(query, QuickSearch_W, QUERY_PLACE_HOLDER);
4376 case SHORTCUT_DICTIONARY_SEARCH:
4377 return URLUtil.composeSearchUrl(query, QuickSearch_D, QUERY_PLACE_HOLDER);
4378 case SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH:
The Android Open Source Project0c908882009-03-03 19:32:16 -08004379 // FIXME: we need location in this case
Satish Sampath565505b2009-05-29 15:37:27 +01004380 return URLUtil.composeSearchUrl(query, QuickSearch_L, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004381 }
4382 }
4383 } else {
4384 if (Regex.WEB_URL_PATTERN.matcher(inUrl).matches()) {
4385 return URLUtil.guessUrl(inUrl);
4386 }
4387 }
4388
4389 Browser.addSearchUrl(mResolver, inUrl);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07004390 return URLUtil.composeSearchUrl(inUrl, QuickSearch_G, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004391 }
4392
Ben Murdochbff2d602009-07-01 20:19:05 +01004393 /* package */ void setShouldShowErrorConsole(boolean flag) {
4394 if (flag == mShouldShowErrorConsole) {
4395 // Nothing to do.
4396 return;
4397 }
4398
4399 mShouldShowErrorConsole = flag;
4400
4401 ErrorConsoleView errorConsole = mTabControl.getCurrentErrorConsole(true);
4402
4403 if (flag) {
4404 // Setting the show state of the console will cause it's the layout to be inflated.
4405 if (errorConsole.numberOfErrors() > 0) {
4406 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
4407 } else {
4408 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
4409 }
4410
4411 // Now we can add it to the main view.
4412 mErrorConsoleContainer.addView(errorConsole,
4413 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
4414 ViewGroup.LayoutParams.WRAP_CONTENT));
4415 } else {
4416 mErrorConsoleContainer.removeView(errorConsole);
4417 }
4418
4419 }
4420
Grace Klobaeb6eef42009-09-15 17:56:32 -07004421 final static int LOCK_ICON_UNSECURE = 0;
4422 final static int LOCK_ICON_SECURE = 1;
4423 final static int LOCK_ICON_MIXED = 2;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004424
4425 private int mLockIconType = LOCK_ICON_UNSECURE;
4426 private int mPrevLockType = LOCK_ICON_UNSECURE;
4427
4428 private BrowserSettings mSettings;
4429 private TabControl mTabControl;
4430 private ContentResolver mResolver;
4431 private FrameLayout mContentView;
Andrei Popescuadc008d2009-06-26 14:11:30 +01004432 private View mCustomView;
4433 private FrameLayout mCustomViewContainer;
Andrei Popescuc9b55562009-07-07 10:51:15 +01004434 private WebChromeClient.CustomViewCallback mCustomViewCallback;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004435
4436 // FIXME, temp address onPrepareMenu performance problem. When we move everything out of
4437 // view, we should rewrite this.
4438 private int mCurrentMenuState = 0;
4439 private int mMenuState = R.id.MAIN_MENU;
Andrei Popescuadc008d2009-06-26 14:11:30 +01004440 private int mOldMenuState = EMPTY_MENU;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004441 private static final int EMPTY_MENU = -1;
4442 private Menu mMenu;
4443
4444 private FindDialog mFindDialog;
4445 // Used to prevent chording to result in firing two shortcuts immediately
4446 // one after another. Fixes bug 1211714.
4447 boolean mCanChord;
4448
4449 private boolean mInLoad;
4450 private boolean mIsNetworkUp;
Ben Murdochb7cc8b42009-09-28 10:59:09 +01004451 private boolean mDidStopLoad;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004452
4453 private boolean mPageStarted;
4454 private boolean mActivityInPause = true;
4455
4456 private boolean mMenuIsDown;
4457
The Android Open Source Project0c908882009-03-03 19:32:16 -08004458 private static boolean mInTrace;
4459
4460 // Performance probe
4461 private static final int[] SYSTEM_CPU_FORMAT = new int[] {
4462 Process.PROC_SPACE_TERM | Process.PROC_COMBINE,
4463 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 1: user time
4464 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 2: nice time
4465 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 3: sys time
4466 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 4: idle time
4467 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 5: iowait time
4468 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 6: irq time
4469 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG // 7: softirq time
4470 };
4471
4472 private long mStart;
4473 private long mProcessStart;
4474 private long mUserStart;
4475 private long mSystemStart;
4476 private long mIdleStart;
4477 private long mIrqStart;
4478
4479 private long mUiStart;
4480
4481 private Drawable mMixLockIcon;
4482 private Drawable mSecLockIcon;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004483
4484 /* hold a ref so we can auto-cancel if necessary */
4485 private AlertDialog mAlertDialog;
4486
4487 // Wait for credentials before loading google.com
4488 private ProgressDialog mCredsDlg;
4489
4490 // The up-to-date URL and title (these can be different from those stored
4491 // in WebView, since it takes some time for the information in WebView to
4492 // get updated)
4493 private String mUrl;
4494 private String mTitle;
4495
4496 // As PageInfo has different style for landscape / portrait, we have
4497 // to re-open it when configuration changed
4498 private AlertDialog mPageInfoDialog;
4499 private TabControl.Tab mPageInfoView;
4500 // If the Page-Info dialog is launched from the SSL-certificate-on-error
4501 // dialog, we should not just dismiss it, but should get back to the
4502 // SSL-certificate-on-error dialog. This flag is used to store this state
4503 private Boolean mPageInfoFromShowSSLCertificateOnError;
4504
4505 // as SSLCertificateOnError has different style for landscape / portrait,
4506 // we have to re-open it when configuration changed
4507 private AlertDialog mSSLCertificateOnErrorDialog;
4508 private WebView mSSLCertificateOnErrorView;
4509 private SslErrorHandler mSSLCertificateOnErrorHandler;
4510 private SslError mSSLCertificateOnErrorError;
4511
4512 // as SSLCertificate has different style for landscape / portrait, we
4513 // have to re-open it when configuration changed
4514 private AlertDialog mSSLCertificateDialog;
4515 private TabControl.Tab mSSLCertificateView;
4516
4517 // as HttpAuthentication has different style for landscape / portrait, we
4518 // have to re-open it when configuration changed
4519 private AlertDialog mHttpAuthenticationDialog;
4520 private HttpAuthHandler mHttpAuthHandler;
4521
4522 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_PARAMS =
4523 new FrameLayout.LayoutParams(
4524 ViewGroup.LayoutParams.FILL_PARENT,
4525 ViewGroup.LayoutParams.FILL_PARENT);
Andrei Popescuadc008d2009-06-26 14:11:30 +01004526 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_GRAVITY_CENTER =
4527 new FrameLayout.LayoutParams(
4528 ViewGroup.LayoutParams.FILL_PARENT,
4529 ViewGroup.LayoutParams.FILL_PARENT,
4530 Gravity.CENTER);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07004531 // Google search
4532 final static String QuickSearch_G = "http://www.google.com/m?q=%s";
The Android Open Source Project0c908882009-03-03 19:32:16 -08004533 // Wikipedia search
4534 final static String QuickSearch_W = "http://en.wikipedia.org/w/index.php?search=%s&go=Go";
4535 // Dictionary search
4536 final static String QuickSearch_D = "http://dictionary.reference.com/search?q=%s";
4537 // Google Mobile Local search
4538 final static String QuickSearch_L = "http://www.google.com/m/search?site=local&q=%s&near=mountain+view";
4539
4540 final static String QUERY_PLACE_HOLDER = "%s";
4541
4542 // "source" parameter for Google search through search key
4543 final static String GOOGLE_SEARCH_SOURCE_SEARCHKEY = "browser-key";
4544 // "source" parameter for Google search through goto menu
4545 final static String GOOGLE_SEARCH_SOURCE_GOTO = "browser-goto";
4546 // "source" parameter for Google search through simplily type
4547 final static String GOOGLE_SEARCH_SOURCE_TYPE = "browser-type";
4548 // "source" parameter for Google search suggested by the browser
4549 final static String GOOGLE_SEARCH_SOURCE_SUGGEST = "browser-suggest";
4550 // "source" parameter for Google search from unknown source
4551 final static String GOOGLE_SEARCH_SOURCE_UNKNOWN = "unknown";
4552
4553 private final static String LOGTAG = "browser";
4554
The Android Open Source Project0c908882009-03-03 19:32:16 -08004555 private String mLastEnteredUrl;
4556
4557 private PowerManager.WakeLock mWakeLock;
4558 private final static int WAKELOCK_TIMEOUT = 5 * 60 * 1000; // 5 minutes
4559
4560 private Toast mStopToast;
4561
Leon Scroggins68579392009-09-15 15:31:54 -04004562 private TitleBar mTitleBar;
Leon Scroggins81db3662009-06-04 17:45:11 -04004563
Ben Murdochbff2d602009-07-01 20:19:05 +01004564 private LinearLayout mErrorConsoleContainer = null;
4565 private boolean mShouldShowErrorConsole = false;
4566
The Android Open Source Project0c908882009-03-03 19:32:16 -08004567 // As the ids are dynamically created, we can't guarantee that they will
4568 // be in sequence, so this static array maps ids to a window number.
4569 final static private int[] WINDOW_SHORTCUT_ID_ARRAY =
4570 { R.id.window_one_menu_id, R.id.window_two_menu_id, R.id.window_three_menu_id,
4571 R.id.window_four_menu_id, R.id.window_five_menu_id, R.id.window_six_menu_id,
4572 R.id.window_seven_menu_id, R.id.window_eight_menu_id };
4573
4574 // monitor platform changes
4575 private IntentFilter mNetworkStateChangedFilter;
4576 private BroadcastReceiver mNetworkStateIntentReceiver;
4577
Grace Klobab4da0ad2009-05-14 14:45:40 -07004578 private BroadcastReceiver mPackageInstallationReceiver;
4579
Patrick Scott59ce8302009-09-18 16:29:38 -04004580 // AsyncTask for downloading touch icons
4581 /* package */ DownloadTouchIcon mTouchIconLoader;
4582
The Android Open Source Project0c908882009-03-03 19:32:16 -08004583 // activity requestCode
Nicolas Roard78a98e42009-05-11 13:34:17 +01004584 final static int COMBO_PAGE = 1;
4585 final static int DOWNLOAD_PAGE = 2;
4586 final static int PREFERENCES_PAGE = 3;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004587
Andrei Popescu540035d2009-09-18 18:59:20 +01004588 // the default <video> poster
4589 private Bitmap mDefaultVideoPoster;
4590 // the video progress view
4591 private View mVideoProgressView;
4592
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004593 /**
4594 * A UrlData class to abstract how the content will be set to WebView.
4595 * This base class uses loadUrl to show the content.
4596 */
4597 private static class UrlData {
4598 String mUrl;
Grace Kloba60e095c2009-06-16 11:50:55 -07004599 byte[] mPostData;
4600
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004601 UrlData(String url) {
4602 this.mUrl = url;
4603 }
Grace Kloba60e095c2009-06-16 11:50:55 -07004604
4605 void setPostData(byte[] postData) {
4606 mPostData = postData;
4607 }
4608
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004609 boolean isEmpty() {
4610 return mUrl == null || mUrl.length() == 0;
4611 }
4612
Mitsuru Oshima7944b7d2009-06-16 16:34:51 -07004613 public void loadIn(WebView webView) {
Grace Kloba60e095c2009-06-16 11:50:55 -07004614 if (mPostData != null) {
4615 webView.postUrl(mUrl, mPostData);
4616 } else {
4617 webView.loadUrl(mUrl);
4618 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004619 }
4620 };
4621
4622 /**
4623 * A subclass of UrlData class that can display inlined content using
4624 * {@link WebView#loadDataWithBaseURL(String, String, String, String, String)}.
4625 */
4626 private static class InlinedUrlData extends UrlData {
4627 InlinedUrlData(String inlined, String mimeType, String encoding, String failUrl) {
4628 super(failUrl);
4629 mInlined = inlined;
4630 mMimeType = mimeType;
4631 mEncoding = encoding;
4632 }
4633 String mMimeType;
4634 String mInlined;
4635 String mEncoding;
Mitsuru Oshima7944b7d2009-06-16 16:34:51 -07004636 @Override
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004637 boolean isEmpty() {
Ben Murdochbff2d602009-07-01 20:19:05 +01004638 return mInlined == null || mInlined.length() == 0 || super.isEmpty();
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004639 }
4640
Mitsuru Oshima7944b7d2009-06-16 16:34:51 -07004641 @Override
4642 public void loadIn(WebView webView) {
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004643 webView.loadDataWithBaseURL(null, mInlined, mMimeType, mEncoding, mUrl);
4644 }
4645 }
4646
Leon Scroggins1f005d32009-08-10 17:36:42 -04004647 /* package */ static final UrlData EMPTY_URL_DATA = new UrlData(null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004648}