blob: 1954dadad60919ea8d1c505e85f270f11ae85c0e [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;
1024 params.windowAnimations = atTop ? 0
1025 : com.android.internal.R.style.Animation_DropDownDown;
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04001026 // XXX : Without providing an offset, the fake title bar will be
1027 // placed underneath the status bar. Use the global visible rect
1028 // of mBrowserFrameLayout to determine the bottom of the status bar
Cary Clarka0464552009-09-29 13:00:45 -04001029 params.y = visRect.top;
Leon Scroggins68549862009-09-21 16:02:01 -04001030 // Add a holder for the title bar. It also holds a shadow to show
1031 // below the title bar.
Leon Scrogginsd8fd2fc2009-09-16 11:12:09 -04001032 if (mFakeTitleBarHolder == null) {
1033 mFakeTitleBarHolder = (ViewGroup) LayoutInflater.from(this)
1034 .inflate(R.layout.title_bar_bg, null);
1035 }
Leon Scrogginsb94bf272009-09-25 15:22:08 -04001036 Shadow shadow = (Shadow) mFakeTitleBarHolder.findViewById(
1037 R.id.shadow);
1038 shadow.setWebView(mainView);
Leon Scroggins68549862009-09-21 16:02:01 -04001039 mFakeTitleBarHolder.addView(mFakeTitleBar, 0, mFakeTitleBarParams);
Leon Scrogginsd8fd2fc2009-09-16 11:12:09 -04001040 manager.addView(mFakeTitleBarHolder, params);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04001041 }
1042 }
1043
1044 @Override
1045 public void onOptionsMenuClosed(Menu menu) {
1046 mOptionsMenuOpen = false;
Leon Scrogginsa27ff192009-09-14 12:58:04 -04001047 if (!mInLoad) {
1048 hideFakeTitleBar();
1049 } else if (!mIconView) {
1050 // The page is currently loading, and we are in expanded mode, so
1051 // we were not showing the menu. Show it once again. It will be
1052 // removed when the page finishes.
1053 showFakeTitleBar();
1054 }
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04001055 }
1056 private void hideFakeTitleBar() {
1057 if (mFakeTitleBar == null) return;
Leon Scroggins20329572009-09-23 17:42:41 -04001058 WindowManager.LayoutParams params = (WindowManager.LayoutParams)
1059 mFakeTitleBarHolder.getLayoutParams();
1060 WebView mainView = mTabControl.getCurrentWebView();
1061 // Although we decided whether or not to animate based on the current
1062 // scroll position, the scroll position may have changed since the
1063 // fake title bar was displayed. Make sure it has the appropriate
1064 // animation/lack thereof before removing.
1065 params.windowAnimations = mainView != null && mainView.getScrollY() == 0
1066 ? 0 : com.android.internal.R.style.Animation_DropDownDown;
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04001067 WindowManager manager
1068 = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
Leon Scroggins20329572009-09-23 17:42:41 -04001069 manager.updateViewLayout(mFakeTitleBarHolder, params);
Leon Scrogginsd8fd2fc2009-09-16 11:12:09 -04001070 mFakeTitleBarHolder.removeView(mFakeTitleBar);
1071 manager.removeView(mFakeTitleBarHolder);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04001072 mFakeTitleBar = null;
1073 }
1074
The Android Open Source Project0c908882009-03-03 19:32:16 -08001075 /**
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001076 * Special method for the fake title bar to call when displaying its context
1077 * menu, since it is in its own Window, and its parent does not show a
1078 * context menu.
1079 */
1080 /* package */ void showTitleBarContextMenu() {
Cary Clark65f4a3c2009-09-28 17:05:06 -04001081 if (null == mTitleBar.getParent()) {
1082 return;
1083 }
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001084 openContextMenu(mTitleBar);
1085 }
1086
1087 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08001088 * onSaveInstanceState(Bundle map)
1089 * onSaveInstanceState is called right before onStop(). The map contains
1090 * the saved state.
1091 */
1092 @Override protected void onSaveInstanceState(Bundle outState) {
Dave Bort31a6d1c2009-04-13 15:56:49 -07001093 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001094 Log.v(LOGTAG, "BrowserActivity.onSaveInstanceState: this=" + this);
1095 }
1096 // the default implementation requires each view to have an id. As the
1097 // browser handles the state itself and it doesn't use id for the views,
1098 // don't call the default implementation. Otherwise it will trigger the
1099 // warning like this, "couldn't save which view has focus because the
1100 // focused view XXX has no id".
1101
1102 // Save all the tabs
1103 mTabControl.saveState(outState);
1104 }
1105
1106 @Override protected void onPause() {
1107 super.onPause();
1108
1109 if (mActivityInPause) {
1110 Log.e(LOGTAG, "BrowserActivity is already paused.");
1111 return;
1112 }
1113
Mike Reed7bfa63b2009-05-28 11:08:32 -04001114 mTabControl.pauseCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001115 mActivityInPause = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -04001116 if (mTabControl.getCurrentIndex() >= 0 && !pauseWebViewTimers()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001117 mWakeLock.acquire();
1118 mHandler.sendMessageDelayed(mHandler
1119 .obtainMessage(RELEASE_WAKELOCK), WAKELOCK_TIMEOUT);
1120 }
1121
1122 // Clear the credentials toast if it is up
1123 if (mCredsDlg != null && mCredsDlg.isShowing()) {
1124 mCredsDlg.dismiss();
1125 }
1126 mCredsDlg = null;
1127
Leon Scrogginsa2ab6a72009-09-11 11:49:52 -04001128 // FIXME: This removes the active tabs page and resets the menu to
1129 // MAIN_MENU. A better solution might be to do this work in onNewIntent
1130 // but then we would need to save it in onSaveInstanceState and restore
1131 // it in onCreate/onRestoreInstanceState
1132 if (mActiveTabsPage != null) {
1133 removeActiveTabPage(true);
1134 }
1135
The Android Open Source Project0c908882009-03-03 19:32:16 -08001136 cancelStopToast();
1137
1138 // unregister network state listener
1139 unregisterReceiver(mNetworkStateIntentReceiver);
1140 WebView.disablePlatformNotifications();
1141
1142 if (mSensorManager != null) {
1143 mSensorManager.unregisterListener(mSensorListener);
1144 }
1145 }
1146
1147 @Override protected void onDestroy() {
Dave Bort31a6d1c2009-04-13 15:56:49 -07001148 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001149 Log.v(LOGTAG, "BrowserActivity.onDestroy: this=" + this);
1150 }
1151 super.onDestroy();
Grace Kloba0923d692009-09-23 21:37:25 -07001152
1153 if (mTabControl == null) return;
1154
The Android Open Source Project0c908882009-03-03 19:32:16 -08001155 // Remove the current tab and sub window
1156 TabControl.Tab t = mTabControl.getCurrentTab();
Patrick Scottfb5e77f2009-04-08 19:17:37 -07001157 if (t != null) {
1158 dismissSubWindow(t);
1159 removeTabFromContentView(t);
1160 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001161 // Destroy all the tabs
1162 mTabControl.destroy();
1163 WebIconDatabase.getInstance().close();
1164 if (mGlsConnection != null) {
1165 unbindService(mGlsConnection);
1166 mGlsConnection = null;
1167 }
1168
1169 //
1170 // stop MASF proxy service
1171 //
1172 //Intent proxyServiceIntent = new Intent();
1173 //proxyServiceIntent.setComponent
1174 // (new ComponentName(
1175 // "com.android.masfproxyservice",
1176 // "com.android.masfproxyservice.MasfProxyService"));
1177 //stopService(proxyServiceIntent);
Grace Klobab4da0ad2009-05-14 14:45:40 -07001178
1179 unregisterReceiver(mPackageInstallationReceiver);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001180 }
1181
1182 @Override
1183 public void onConfigurationChanged(Configuration newConfig) {
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04001184 mConfigChanged = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001185 super.onConfigurationChanged(newConfig);
1186
1187 if (mPageInfoDialog != null) {
1188 mPageInfoDialog.dismiss();
1189 showPageInfo(
1190 mPageInfoView,
1191 mPageInfoFromShowSSLCertificateOnError.booleanValue());
1192 }
1193 if (mSSLCertificateDialog != null) {
1194 mSSLCertificateDialog.dismiss();
1195 showSSLCertificate(
1196 mSSLCertificateView);
1197 }
1198 if (mSSLCertificateOnErrorDialog != null) {
1199 mSSLCertificateOnErrorDialog.dismiss();
1200 showSSLCertificateOnError(
1201 mSSLCertificateOnErrorView,
1202 mSSLCertificateOnErrorHandler,
1203 mSSLCertificateOnErrorError);
1204 }
1205 if (mHttpAuthenticationDialog != null) {
1206 String title = ((TextView) mHttpAuthenticationDialog
1207 .findViewById(com.android.internal.R.id.alertTitle)).getText()
1208 .toString();
1209 String name = ((TextView) mHttpAuthenticationDialog
1210 .findViewById(R.id.username_edit)).getText().toString();
1211 String password = ((TextView) mHttpAuthenticationDialog
1212 .findViewById(R.id.password_edit)).getText().toString();
1213 int focusId = mHttpAuthenticationDialog.getCurrentFocus()
1214 .getId();
1215 mHttpAuthenticationDialog.dismiss();
1216 showHttpAuthentication(mHttpAuthHandler, null, null, title,
1217 name, password, focusId);
1218 }
1219 if (mFindDialog != null && mFindDialog.isShowing()) {
1220 mFindDialog.onConfigurationChanged(newConfig);
1221 }
1222 }
1223
1224 @Override public void onLowMemory() {
1225 super.onLowMemory();
1226 mTabControl.freeMemory();
1227 }
1228
Mike Reed7bfa63b2009-05-28 11:08:32 -04001229 private boolean resumeWebViewTimers() {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001230 if ((!mActivityInPause && !mPageStarted) ||
1231 (mActivityInPause && mPageStarted)) {
1232 CookieSyncManager.getInstance().startSync();
1233 WebView w = mTabControl.getCurrentWebView();
1234 if (w != null) {
1235 w.resumeTimers();
1236 }
1237 return true;
1238 } else {
1239 return false;
1240 }
1241 }
1242
Mike Reed7bfa63b2009-05-28 11:08:32 -04001243 private boolean pauseWebViewTimers() {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001244 if (mActivityInPause && !mPageStarted) {
1245 CookieSyncManager.getInstance().stopSync();
1246 WebView w = mTabControl.getCurrentWebView();
1247 if (w != null) {
1248 w.pauseTimers();
1249 }
1250 return true;
1251 } else {
1252 return false;
1253 }
1254 }
1255
Leon Scroggins1f005d32009-08-10 17:36:42 -04001256 // FIXME: Do we want to call this when loading google for the first time?
The Android Open Source Project0c908882009-03-03 19:32:16 -08001257 /*
1258 * This function is called when we are launching for the first time. We
1259 * are waiting for the login credentials before loading Google home
1260 * pages. This way the user will be logged in straight away.
1261 */
1262 private void waitForCredentials() {
1263 // Show a toast
1264 mCredsDlg = new ProgressDialog(this);
1265 mCredsDlg.setIndeterminate(true);
1266 mCredsDlg.setMessage(getText(R.string.retrieving_creds_dlg_msg));
1267 // If the user cancels the operation, then cancel the Google
1268 // Credentials request.
1269 mCredsDlg.setCancelMessage(mHandler.obtainMessage(CANCEL_CREDS_REQUEST));
1270 mCredsDlg.show();
1271
1272 // We set a timeout for the retrieval of credentials in onResume()
1273 // as that is when we have freed up some CPU time to get
1274 // the login credentials.
1275 }
1276
1277 /*
1278 * If we have received the credentials or we have timed out and we are
1279 * showing the credentials dialog, then it is time to move on.
1280 */
1281 private void resumeAfterCredentials() {
1282 if (mCredsDlg == null) {
1283 return;
1284 }
1285
1286 // Clear the toast
1287 if (mCredsDlg.isShowing()) {
1288 mCredsDlg.dismiss();
1289 }
1290 mCredsDlg = null;
1291
1292 // Clear any pending timeout
1293 mHandler.removeMessages(CANCEL_CREDS_REQUEST);
1294
1295 // Load the page
1296 WebView w = mTabControl.getCurrentWebView();
1297 if (w != null) {
1298 w.loadUrl(mSettings.getHomePage());
1299 }
1300
1301 // Update the settings, need to do this last as it can take a moment
1302 // to persist the settings. In the mean time we could be loading
1303 // content.
1304 mSettings.setLoginInitialized(this);
1305 }
1306
1307 // Open the icon database and retain all the icons for visited sites.
1308 private void retainIconsOnStartup() {
1309 final WebIconDatabase db = WebIconDatabase.getInstance();
1310 db.open(getDir("icons", 0).getPath());
1311 try {
1312 Cursor c = Browser.getAllBookmarks(mResolver);
1313 if (!c.moveToFirst()) {
1314 c.deactivate();
1315 return;
1316 }
1317 int urlIndex = c.getColumnIndex(Browser.BookmarkColumns.URL);
1318 do {
1319 String url = c.getString(urlIndex);
1320 db.retainIconForPageUrl(url);
1321 } while (c.moveToNext());
1322 c.deactivate();
1323 } catch (IllegalStateException e) {
1324 Log.e(LOGTAG, "retainIconsOnStartup", e);
1325 }
1326 }
1327
1328 // Helper method for getting the top window.
1329 WebView getTopWindow() {
1330 return mTabControl.getCurrentTopWebView();
1331 }
1332
1333 @Override
1334 public boolean onCreateOptionsMenu(Menu menu) {
1335 super.onCreateOptionsMenu(menu);
1336
1337 MenuInflater inflater = getMenuInflater();
1338 inflater.inflate(R.menu.browser, menu);
1339 mMenu = menu;
1340 updateInLoadMenuItems();
1341 return true;
1342 }
1343
1344 /**
1345 * As the menu can be open when loading state changes
1346 * we must manually update the state of the stop/reload menu
1347 * item
1348 */
1349 private void updateInLoadMenuItems() {
1350 if (mMenu == null) {
1351 return;
1352 }
1353 MenuItem src = mInLoad ?
1354 mMenu.findItem(R.id.stop_menu_id):
1355 mMenu.findItem(R.id.reload_menu_id);
1356 MenuItem dest = mMenu.findItem(R.id.stop_reload_menu_id);
1357 dest.setIcon(src.getIcon());
1358 dest.setTitle(src.getTitle());
1359 }
1360
1361 @Override
1362 public boolean onContextItemSelected(MenuItem item) {
1363 // chording is not an issue with context menus, but we use the same
1364 // options selector, so set mCanChord to true so we can access them.
1365 mCanChord = true;
1366 int id = item.getItemId();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001367 switch (id) {
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001368 // For the context menu from the title bar
1369 case R.id.title_bar_share_page_url:
1370 case R.id.title_bar_copy_page_url:
1371 WebView mainView = mTabControl.getCurrentWebView();
1372 if (null == mainView) {
1373 return false;
1374 }
1375 if (id == R.id.title_bar_share_page_url) {
1376 Browser.sendString(this, mainView.getUrl());
1377 } else {
1378 copy(mainView.getUrl());
1379 }
1380 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001381 // -- Browser context menu
1382 case R.id.open_context_menu_id:
1383 case R.id.open_newtab_context_menu_id:
1384 case R.id.bookmark_context_menu_id:
1385 case R.id.save_link_context_menu_id:
1386 case R.id.share_link_context_menu_id:
1387 case R.id.copy_link_context_menu_id:
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001388 final WebView webView = getTopWindow();
1389 if (null == webView) {
1390 return false;
1391 }
1392 final HashMap hrefMap = new HashMap();
1393 hrefMap.put("webview", webView);
1394 final Message msg = mHandler.obtainMessage(
1395 FOCUS_NODE_HREF, id, 0, hrefMap);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001396 webView.requestFocusNodeHref(msg);
1397 break;
1398
1399 default:
1400 // For other context menus
1401 return onOptionsItemSelected(item);
1402 }
1403 mCanChord = false;
1404 return true;
1405 }
1406
1407 private Bundle createGoogleSearchSourceBundle(String source) {
1408 Bundle bundle = new Bundle();
1409 bundle.putString(SearchManager.SOURCE, source);
1410 return bundle;
1411 }
1412
1413 /**
The Android Open Source Project4e5f5872009-03-09 11:52:14 -07001414 * Overriding this to insert a local information bundle
The Android Open Source Project0c908882009-03-03 19:32:16 -08001415 */
1416 @Override
1417 public boolean onSearchRequested() {
Leon Scroggins68579392009-09-15 15:31:54 -04001418 if (mOptionsMenuOpen) closeOptionsMenu();
Leon Scroggins5bbe9802009-07-31 13:10:55 -04001419 String url = (getTopWindow() == null) ? null : getTopWindow().getUrl();
Grace Kloba83f47342009-07-20 10:44:31 -07001420 startSearch(mSettings.getHomePage().equals(url) ? null : url, true,
The Android Open Source Project4e5f5872009-03-09 11:52:14 -07001421 createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_SEARCHKEY), false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001422 return true;
1423 }
1424
1425 @Override
1426 public void startSearch(String initialQuery, boolean selectInitialQuery,
1427 Bundle appSearchData, boolean globalSearch) {
1428 if (appSearchData == null) {
1429 appSearchData = createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_TYPE);
1430 }
1431 super.startSearch(initialQuery, selectInitialQuery, appSearchData, globalSearch);
1432 }
1433
Leon Scroggins1f005d32009-08-10 17:36:42 -04001434 /**
1435 * Switch tabs. Called by the TitleBarSet when sliding the title bar
1436 * results in changing tabs.
Leon Scroggins160a7e72009-08-14 18:28:01 -04001437 * @param index Index of the tab to change to, as defined by
1438 * mTabControl.getTabIndex(Tab t).
1439 * @return boolean True if we successfully switched to a different tab. If
1440 * the indexth tab is null, or if that tab is the same as
1441 * the current one, return false.
Leon Scroggins1f005d32009-08-10 17:36:42 -04001442 */
Leon Scroggins160a7e72009-08-14 18:28:01 -04001443 /* package */ boolean switchToTab(int index) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001444 TabControl.Tab tab = mTabControl.getTab(index);
1445 TabControl.Tab currentTab = mTabControl.getCurrentTab();
1446 if (tab == null || tab == currentTab) {
Leon Scroggins160a7e72009-08-14 18:28:01 -04001447 return false;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001448 }
1449 if (currentTab != null) {
1450 // currentTab may be null if it was just removed. In that case,
1451 // we do not need to remove it
1452 removeTabFromContentView(currentTab);
1453 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001454 mTabControl.setCurrentTab(tab);
1455 attachTabToContentView(tab);
Grace Klobaeb6eef42009-09-15 17:56:32 -07001456 resetTitleIconAndProgress();
1457 updateLockIconToLatest();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001458 return true;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001459 }
1460
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001461 /* package */ TabControl.Tab openTabToHomePage() {
1462 return openTabAndShow(mSettings.getHomePage(), false, null);
1463 }
1464
Leon Scroggins1f005d32009-08-10 17:36:42 -04001465 /* package */ void closeCurrentWindow() {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001466 final TabControl.Tab current = mTabControl.getCurrentTab();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001467 if (mTabControl.getTabCount() == 1) {
Leon Scroggins30444232009-09-04 18:36:20 -04001468 // This is the last tab. Open a new one, with the home
1469 // page and close the current one.
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001470 TabControl.Tab newTab = openTabToHomePage();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001471 closeTab(current);
Leon Scroggins160a7e72009-08-14 18:28:01 -04001472 return;
1473 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001474 final TabControl.Tab parent = current.getParentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04001475 int indexToShow = -1;
1476 if (parent != null) {
1477 indexToShow = mTabControl.getTabIndex(parent);
1478 } else {
Leon Scroggins160a7e72009-08-14 18:28:01 -04001479 final int currentIndex = mTabControl.getCurrentIndex();
1480 // Try to move to the tab to the right
1481 indexToShow = currentIndex + 1;
1482 if (indexToShow > mTabControl.getTabCount() - 1) {
1483 // Try to move to the tab to the left
1484 indexToShow = currentIndex - 1;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001485 }
1486 }
Leon Scroggins160a7e72009-08-14 18:28:01 -04001487 if (switchToTab(indexToShow)) {
1488 // Close window
1489 closeTab(current);
1490 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001491 }
1492
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001493 private ActiveTabsPage mActiveTabsPage;
1494
1495 /**
1496 * Remove the active tabs page.
1497 * @param needToAttach If true, the active tabs page did not attach a tab
1498 * to the content view, so we need to do that here.
1499 */
1500 /* package */ void removeActiveTabPage(boolean needToAttach) {
1501 mContentView.removeView(mActiveTabsPage);
1502 mActiveTabsPage = null;
1503 mMenuState = R.id.MAIN_MENU;
1504 if (needToAttach) {
1505 attachTabToContentView(mTabControl.getCurrentTab());
1506 }
1507 getTopWindow().requestFocus();
1508 }
1509
The Android Open Source Project0c908882009-03-03 19:32:16 -08001510 @Override
1511 public boolean onOptionsItemSelected(MenuItem item) {
1512 if (!mCanChord) {
1513 // The user has already fired a shortcut with this hold down of the
1514 // menu key.
1515 return false;
1516 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001517 if (null == getTopWindow()) {
Leon Scroggins0d7ae0e2009-06-05 11:04:45 -04001518 return false;
1519 }
Grace Kloba6ee9c492009-07-13 10:04:34 -07001520 if (mMenuIsDown) {
1521 // The shortcut action consumes the MENU. Even if it is still down,
1522 // it won't trigger the next shortcut action. In the case of the
1523 // shortcut action triggering a new activity, like Bookmarks, we
1524 // won't get onKeyUp for MENU. So it is important to reset it here.
1525 mMenuIsDown = false;
1526 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001527 switch (item.getItemId()) {
1528 // -- Main menu
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001529 case R.id.new_tab_menu_id:
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001530 openTabToHomePage();
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001531 break;
1532
Leon Scroggins64b80f32009-08-07 12:03:34 -04001533 case R.id.goto_menu_id:
Leon Scrogginsb3a5bed2009-09-28 11:21:56 -04001534 onSearchRequested();
1535 break;
1536
1537 case R.id.bookmarks_menu_id:
Leon Scroggins30444232009-09-04 18:36:20 -04001538 bookmarksOrHistoryPicker(false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001539 break;
1540
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001541 case R.id.active_tabs_menu_id:
1542 mActiveTabsPage = new ActiveTabsPage(this, mTabControl);
1543 removeTabFromContentView(mTabControl.getCurrentTab());
Leon Scroggins43de6162009-09-14 19:59:58 -04001544 hideFakeTitleBar();
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001545 mContentView.addView(mActiveTabsPage, COVER_SCREEN_PARAMS);
1546 mActiveTabsPage.requestFocus();
1547 mMenuState = EMPTY_MENU;
1548 break;
1549
Leon Scroggins1f005d32009-08-10 17:36:42 -04001550 case R.id.add_bookmark_menu_id:
1551 Intent i = new Intent(BrowserActivity.this,
1552 AddBookmarkPage.class);
1553 WebView w = getTopWindow();
1554 i.putExtra("url", w.getUrl());
1555 i.putExtra("title", w.getTitle());
Grace Kloba83cdb2c2009-09-16 00:48:57 -07001556 i.putExtra("touch_icon_url", w.getTouchIconUrl());
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01001557 i.putExtra("thumbnail", createScreenshot(w));
Leon Scroggins1f005d32009-08-10 17:36:42 -04001558 startActivity(i);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001559 break;
1560
1561 case R.id.stop_reload_menu_id:
1562 if (mInLoad) {
1563 stopLoading();
1564 } else {
1565 getTopWindow().reload();
1566 }
1567 break;
1568
1569 case R.id.back_menu_id:
1570 getTopWindow().goBack();
1571 break;
1572
1573 case R.id.forward_menu_id:
1574 getTopWindow().goForward();
1575 break;
1576
1577 case R.id.close_menu_id:
1578 // Close the subwindow if it exists.
1579 if (mTabControl.getCurrentSubWindow() != null) {
1580 dismissSubWindow(mTabControl.getCurrentTab());
1581 break;
1582 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001583 closeCurrentWindow();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001584 break;
1585
1586 case R.id.homepage_menu_id:
1587 TabControl.Tab current = mTabControl.getCurrentTab();
1588 if (current != null) {
1589 dismissSubWindow(current);
1590 current.getWebView().loadUrl(mSettings.getHomePage());
1591 }
1592 break;
1593
1594 case R.id.preferences_menu_id:
1595 Intent intent = new Intent(this,
1596 BrowserPreferencesPage.class);
1597 startActivityForResult(intent, PREFERENCES_PAGE);
1598 break;
1599
1600 case R.id.find_menu_id:
1601 if (null == mFindDialog) {
1602 mFindDialog = new FindDialog(this);
1603 }
1604 mFindDialog.setWebView(getTopWindow());
1605 mFindDialog.show();
1606 mMenuState = EMPTY_MENU;
1607 break;
1608
1609 case R.id.select_text_id:
1610 getTopWindow().emulateShiftHeld();
1611 break;
1612 case R.id.page_info_menu_id:
1613 showPageInfo(mTabControl.getCurrentTab(), false);
1614 break;
1615
1616 case R.id.classic_history_menu_id:
Leon Scroggins30444232009-09-04 18:36:20 -04001617 bookmarksOrHistoryPicker(true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001618 break;
1619
1620 case R.id.share_page_menu_id:
Andrei Popescu10fdba82009-09-24 13:25:47 +01001621 Browser.sendString(this, getTopWindow().getUrl(),
1622 getText(R.string.choosertitle_sharevia).toString());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001623 break;
1624
1625 case R.id.dump_nav_menu_id:
1626 getTopWindow().debugDump();
1627 break;
1628
1629 case R.id.zoom_in_menu_id:
1630 getTopWindow().zoomIn();
1631 break;
1632
1633 case R.id.zoom_out_menu_id:
1634 getTopWindow().zoomOut();
1635 break;
1636
1637 case R.id.view_downloads_menu_id:
1638 viewDownloads(null);
1639 break;
1640
The Android Open Source Project0c908882009-03-03 19:32:16 -08001641 case R.id.window_one_menu_id:
1642 case R.id.window_two_menu_id:
1643 case R.id.window_three_menu_id:
1644 case R.id.window_four_menu_id:
1645 case R.id.window_five_menu_id:
1646 case R.id.window_six_menu_id:
1647 case R.id.window_seven_menu_id:
1648 case R.id.window_eight_menu_id:
1649 {
1650 int menuid = item.getItemId();
1651 for (int id = 0; id < WINDOW_SHORTCUT_ID_ARRAY.length; id++) {
1652 if (WINDOW_SHORTCUT_ID_ARRAY[id] == menuid) {
1653 TabControl.Tab desiredTab = mTabControl.getTab(id);
1654 if (desiredTab != null &&
1655 desiredTab != mTabControl.getCurrentTab()) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001656 switchToTab(id);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001657 }
1658 break;
1659 }
1660 }
1661 }
1662 break;
1663
1664 default:
1665 if (!super.onOptionsItemSelected(item)) {
1666 return false;
1667 }
1668 // Otherwise fall through.
1669 }
1670 mCanChord = false;
1671 return true;
1672 }
1673
1674 public void closeFind() {
1675 mMenuState = R.id.MAIN_MENU;
1676 }
1677
1678 @Override public boolean onPrepareOptionsMenu(Menu menu)
1679 {
1680 // This happens when the user begins to hold down the menu key, so
1681 // allow them to chord to get a shortcut.
1682 mCanChord = true;
1683 // Note: setVisible will decide whether an item is visible; while
1684 // setEnabled() will decide whether an item is enabled, which also means
1685 // whether the matching shortcut key will function.
1686 super.onPrepareOptionsMenu(menu);
1687 switch (mMenuState) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001688 case EMPTY_MENU:
1689 if (mCurrentMenuState != mMenuState) {
1690 menu.setGroupVisible(R.id.MAIN_MENU, false);
1691 menu.setGroupEnabled(R.id.MAIN_MENU, false);
1692 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001693 }
1694 break;
1695 default:
1696 if (mCurrentMenuState != mMenuState) {
1697 menu.setGroupVisible(R.id.MAIN_MENU, true);
1698 menu.setGroupEnabled(R.id.MAIN_MENU, true);
1699 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001700 }
1701 final WebView w = getTopWindow();
1702 boolean canGoBack = false;
1703 boolean canGoForward = false;
1704 boolean isHome = false;
1705 if (w != null) {
1706 canGoBack = w.canGoBack();
1707 canGoForward = w.canGoForward();
1708 isHome = mSettings.getHomePage().equals(w.getUrl());
1709 }
1710 final MenuItem back = menu.findItem(R.id.back_menu_id);
1711 back.setEnabled(canGoBack);
1712
1713 final MenuItem home = menu.findItem(R.id.homepage_menu_id);
1714 home.setEnabled(!isHome);
1715
1716 menu.findItem(R.id.forward_menu_id)
1717 .setEnabled(canGoForward);
1718
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001719 menu.findItem(R.id.new_tab_menu_id).setEnabled(
1720 mTabControl.getTabCount() < TabControl.MAX_TABS);
1721
The Android Open Source Project0c908882009-03-03 19:32:16 -08001722 // decide whether to show the share link option
1723 PackageManager pm = getPackageManager();
1724 Intent send = new Intent(Intent.ACTION_SEND);
1725 send.setType("text/plain");
1726 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1727 menu.findItem(R.id.share_page_menu_id).setVisible(ri != null);
1728
The Android Open Source Project0c908882009-03-03 19:32:16 -08001729 boolean isNavDump = mSettings.isNavDump();
1730 final MenuItem nav = menu.findItem(R.id.dump_nav_menu_id);
1731 nav.setVisible(isNavDump);
1732 nav.setEnabled(isNavDump);
1733 break;
1734 }
1735 mCurrentMenuState = mMenuState;
1736 return true;
1737 }
1738
1739 @Override
1740 public void onCreateContextMenu(ContextMenu menu, View v,
1741 ContextMenuInfo menuInfo) {
1742 WebView webview = (WebView) v;
1743 WebView.HitTestResult result = webview.getHitTestResult();
1744 if (result == null) {
1745 return;
1746 }
1747
1748 int type = result.getType();
1749 if (type == WebView.HitTestResult.UNKNOWN_TYPE) {
1750 Log.w(LOGTAG,
1751 "We should not show context menu when nothing is touched");
1752 return;
1753 }
1754 if (type == WebView.HitTestResult.EDIT_TEXT_TYPE) {
1755 // let TextView handles context menu
1756 return;
1757 }
1758
1759 // Note, http://b/issue?id=1106666 is requesting that
1760 // an inflated menu can be used again. This is not available
1761 // yet, so inflate each time (yuk!)
1762 MenuInflater inflater = getMenuInflater();
1763 inflater.inflate(R.menu.browsercontext, menu);
1764
1765 // Show the correct menu group
1766 String extra = result.getExtra();
1767 menu.setGroupVisible(R.id.PHONE_MENU,
1768 type == WebView.HitTestResult.PHONE_TYPE);
1769 menu.setGroupVisible(R.id.EMAIL_MENU,
1770 type == WebView.HitTestResult.EMAIL_TYPE);
1771 menu.setGroupVisible(R.id.GEO_MENU,
1772 type == WebView.HitTestResult.GEO_TYPE);
1773 menu.setGroupVisible(R.id.IMAGE_MENU,
1774 type == WebView.HitTestResult.IMAGE_TYPE
1775 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1776 menu.setGroupVisible(R.id.ANCHOR_MENU,
1777 type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1778 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1779
1780 // Setup custom handling depending on the type
1781 switch (type) {
1782 case WebView.HitTestResult.PHONE_TYPE:
1783 menu.setHeaderTitle(Uri.decode(extra));
1784 menu.findItem(R.id.dial_context_menu_id).setIntent(
1785 new Intent(Intent.ACTION_VIEW, Uri
1786 .parse(WebView.SCHEME_TEL + extra)));
1787 Intent addIntent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
1788 addIntent.putExtra(Insert.PHONE, Uri.decode(extra));
Cary Clark5e335a32009-09-22 14:53:11 -04001789 addIntent.setType(ContactsContract.Contacts.CONTENT_ITEM_TYPE);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001790 menu.findItem(R.id.add_contact_context_menu_id).setIntent(
1791 addIntent);
1792 menu.findItem(R.id.copy_phone_context_menu_id).setOnMenuItemClickListener(
1793 new Copy(extra));
1794 break;
1795
1796 case WebView.HitTestResult.EMAIL_TYPE:
1797 menu.setHeaderTitle(extra);
1798 menu.findItem(R.id.email_context_menu_id).setIntent(
1799 new Intent(Intent.ACTION_VIEW, Uri
1800 .parse(WebView.SCHEME_MAILTO + extra)));
1801 menu.findItem(R.id.copy_mail_context_menu_id).setOnMenuItemClickListener(
1802 new Copy(extra));
1803 break;
1804
1805 case WebView.HitTestResult.GEO_TYPE:
1806 menu.setHeaderTitle(extra);
1807 menu.findItem(R.id.map_context_menu_id).setIntent(
1808 new Intent(Intent.ACTION_VIEW, Uri
1809 .parse(WebView.SCHEME_GEO
1810 + URLEncoder.encode(extra))));
1811 menu.findItem(R.id.copy_geo_context_menu_id).setOnMenuItemClickListener(
1812 new Copy(extra));
1813 break;
1814
1815 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1816 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
1817 TextView titleView = (TextView) LayoutInflater.from(this)
1818 .inflate(android.R.layout.browser_link_context_header,
1819 null);
1820 titleView.setText(extra);
1821 menu.setHeaderView(titleView);
1822 // decide whether to show the open link in new tab option
1823 menu.findItem(R.id.open_newtab_context_menu_id).setVisible(
1824 mTabControl.getTabCount() < TabControl.MAX_TABS);
1825 PackageManager pm = getPackageManager();
1826 Intent send = new Intent(Intent.ACTION_SEND);
1827 send.setType("text/plain");
1828 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1829 menu.findItem(R.id.share_link_context_menu_id).setVisible(ri != null);
1830 if (type == WebView.HitTestResult.SRC_ANCHOR_TYPE) {
1831 break;
1832 }
1833 // otherwise fall through to handle image part
1834 case WebView.HitTestResult.IMAGE_TYPE:
1835 if (type == WebView.HitTestResult.IMAGE_TYPE) {
1836 menu.setHeaderTitle(extra);
1837 }
1838 menu.findItem(R.id.view_image_context_menu_id).setIntent(
1839 new Intent(Intent.ACTION_VIEW, Uri.parse(extra)));
1840 menu.findItem(R.id.download_context_menu_id).
1841 setOnMenuItemClickListener(new Download(extra));
1842 break;
1843
1844 default:
1845 Log.w(LOGTAG, "We should not get here.");
1846 break;
1847 }
1848 }
1849
The Android Open Source Project0c908882009-03-03 19:32:16 -08001850 // Attach the given tab to the content view.
Grace Klobac928c302009-09-17 11:51:21 -07001851 // this should only be called for the current tab.
The Android Open Source Project0c908882009-03-03 19:32:16 -08001852 private void attachTabToContentView(TabControl.Tab t) {
Steve Block2bc69912009-07-30 14:45:13 +01001853 // Attach the container that contains the main WebView and any other UI
1854 // associated with the tab.
Patrick Scottd0119532009-09-17 08:00:31 -04001855 t.attachTabToContentView(mContentView);
Ben Murdochbff2d602009-07-01 20:19:05 +01001856
1857 if (mShouldShowErrorConsole) {
1858 ErrorConsoleView errorConsole = mTabControl.getCurrentErrorConsole(true);
1859 if (errorConsole.numberOfErrors() == 0) {
1860 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
1861 } else {
1862 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
1863 }
1864
1865 mErrorConsoleContainer.addView(errorConsole,
1866 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
1867 ViewGroup.LayoutParams.WRAP_CONTENT));
1868 }
1869
Grace Klobac928c302009-09-17 11:51:21 -07001870 setLockIconType(t.getLockIconType());
1871 setPrevLockType(t.getPrevLockIconType());
1872
1873 // this is to match the code in removeTabFromContentView()
1874 if (!mPageStarted && t.getTopWindow().getProgress() < 100) {
1875 mPageStarted = true;
Grace Klobaeb6eef42009-09-15 17:56:32 -07001876 }
1877
Leon Scroggins39ab28e2009-09-02 21:20:30 -04001878 WebView view = t.getWebView();
Leon Scroggins55a5bc22009-09-04 17:00:08 -04001879 view.setEmbeddedTitleBar(mTitleBar);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001880 // Request focus on the top window.
1881 t.getTopWindow().requestFocus();
1882 }
1883
1884 // Attach a sub window to the main WebView of the given tab.
1885 private void attachSubWindow(TabControl.Tab t) {
Patrick Scottd0119532009-09-17 08:00:31 -04001886 t.attachSubWindow(mContentView);
1887 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001888 }
1889
1890 // Remove the given tab from the content view.
1891 private void removeTabFromContentView(TabControl.Tab t) {
Steve Block2bc69912009-07-30 14:45:13 +01001892 // Remove the container that contains the main WebView.
Patrick Scottd0119532009-09-17 08:00:31 -04001893 t.removeTabFromContentView(mContentView);
Ben Murdochbff2d602009-07-01 20:19:05 +01001894
1895 if (mTabControl.getCurrentErrorConsole(false) != null) {
1896 mErrorConsoleContainer.removeView(mTabControl.getCurrentErrorConsole(false));
1897 }
1898
Leon Scroggins39ab28e2009-09-02 21:20:30 -04001899 WebView view = t.getWebView();
Leon Scrogginsbb85b902009-09-14 19:27:20 -04001900 if (view != null) {
1901 view.setEmbeddedTitleBar(null);
1902 }
Leon Scroggins39ab28e2009-09-02 21:20:30 -04001903
Grace Klobac928c302009-09-17 11:51:21 -07001904 // unlike attachTabToContentView(), removeTabFromContentView() can be
1905 // called for the non-current tab. Need to add the check.
Grace Klobaeb6eef42009-09-15 17:56:32 -07001906 if (t == mTabControl.getCurrentTab()) {
1907 t.setLockIconType(getLockIconType());
1908 t.setPrevLockIconType(getPrevLockType());
Grace Klobac928c302009-09-17 11:51:21 -07001909
1910 // this is not a perfect solution. But currently there is one
1911 // WebViewClient for all the WebView. if user switches from an
1912 // in-load window to an already loaded window, mPageStarted will not
1913 // be set to false. If user leaves the Browser, pauseWebViewTimers()
1914 // won't do anything and leaves the timer running even Browser is in
1915 // the background.
1916 if (mPageStarted) {
1917 mPageStarted = false;
1918 }
Grace Klobaeb6eef42009-09-15 17:56:32 -07001919 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001920 }
1921
1922 // Remove the sub window if it exists. Also called by TabControl when the
1923 // user clicks the 'X' to dismiss a sub window.
1924 /* package */ void dismissSubWindow(TabControl.Tab t) {
Patrick Scottd0119532009-09-17 08:00:31 -04001925 t.removeSubWindow(mContentView);
1926 // Tell the TabControl to dismiss the subwindow. This will destroy
1927 // the WebView.
1928 mTabControl.dismissSubWindow(t);
1929 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001930 }
1931
Leon Scroggins1f005d32009-08-10 17:36:42 -04001932 // A wrapper function of {@link #openTabAndShow(UrlData, boolean, String)}
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07001933 // that accepts url as string.
Leon Scroggins1f005d32009-08-10 17:36:42 -04001934 private TabControl.Tab openTabAndShow(String url, boolean closeOnExit,
1935 String appId) {
1936 return openTabAndShow(new UrlData(url), closeOnExit, appId);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001937 }
1938
1939 // This method does a ton of stuff. It will attempt to create a new tab
1940 // if we haven't reached MAX_TABS. Otherwise it uses the current tab. If
Leon Scroggins1f005d32009-08-10 17:36:42 -04001941 // url isn't null, it will load the given url.
1942 /* package */ TabControl.Tab openTabAndShow(UrlData urlData,
The Android Open Source Projectf59ec872009-03-13 13:04:24 -07001943 boolean closeOnExit, String appId) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001944 final boolean newTab = mTabControl.getTabCount() != TabControl.MAX_TABS;
1945 final TabControl.Tab currentTab = mTabControl.getCurrentTab();
1946 if (newTab) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001947 final TabControl.Tab tab = mTabControl.createNewTab(
1948 closeOnExit, appId, urlData.mUrl);
1949 WebView webview = tab.getWebView();
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001950 // If the last tab was removed from the active tabs page, currentTab
1951 // will be null.
1952 if (currentTab != null) {
1953 removeTabFromContentView(currentTab);
1954 }
Patrick Scott8bbd69f2009-08-14 13:35:53 -04001955 // We must set the new tab as the current tab to reflect the old
1956 // animation behavior.
1957 mTabControl.setCurrentTab(tab);
Grace Klobaeb6eef42009-09-15 17:56:32 -07001958 attachTabToContentView(tab);
Leon Scroggins160a7e72009-08-14 18:28:01 -04001959 if (!urlData.isEmpty()) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001960 urlData.loadIn(webview);
1961 }
1962 return tab;
1963 } else {
1964 // Get rid of the subwindow if it exists
1965 dismissSubWindow(currentTab);
1966 if (!urlData.isEmpty()) {
1967 // Load the given url.
1968 urlData.loadIn(currentTab.getWebView());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001969 }
1970 }
Grace Klobac9181842009-04-14 08:53:22 -07001971 return currentTab;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001972 }
1973
Grace Klobac9181842009-04-14 08:53:22 -07001974 private TabControl.Tab openTab(String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001975 if (mSettings.openInBackground()) {
The Android Open Source Projectf59ec872009-03-13 13:04:24 -07001976 TabControl.Tab t = mTabControl.createNewTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001977 if (t != null) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001978 WebView view = t.getWebView();
Leon Scroggins1f005d32009-08-10 17:36:42 -04001979 view.loadUrl(url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001980 }
Grace Klobac9181842009-04-14 08:53:22 -07001981 return t;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001982 } else {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001983 return openTabAndShow(url, false, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001984 }
1985 }
1986
1987 private class Copy implements OnMenuItemClickListener {
1988 private CharSequence mText;
1989
1990 public boolean onMenuItemClick(MenuItem item) {
1991 copy(mText);
1992 return true;
1993 }
1994
1995 public Copy(CharSequence toCopy) {
1996 mText = toCopy;
1997 }
1998 }
1999
2000 private class Download implements OnMenuItemClickListener {
2001 private String mText;
2002
2003 public boolean onMenuItemClick(MenuItem item) {
2004 onDownloadStartNoStream(mText, null, null, null, -1);
2005 return true;
2006 }
2007
2008 public Download(String toDownload) {
2009 mText = toDownload;
2010 }
2011 }
2012
2013 private void copy(CharSequence text) {
2014 try {
2015 IClipboard clip = IClipboard.Stub.asInterface(ServiceManager.getService("clipboard"));
2016 if (clip != null) {
2017 clip.setClipboardText(text);
2018 }
2019 } catch (android.os.RemoteException e) {
2020 Log.e(LOGTAG, "Copy failed", e);
2021 }
2022 }
2023
2024 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08002025 * Resets the browser title-view to whatever it must be
2026 * (for example, if we had a loading error)
2027 * When we have a new page, we call resetTitle, when we
2028 * have to reset the titlebar to whatever it used to be
2029 * (for example, if the user chose to stop loading), we
2030 * call resetTitleAndRevertLockIcon.
2031 */
2032 /* package */ void resetTitleAndRevertLockIcon() {
2033 revertLockIcon();
2034 resetTitleIconAndProgress();
2035 }
2036
2037 /**
2038 * Reset the title, favicon, and progress.
2039 */
2040 private void resetTitleIconAndProgress() {
2041 WebView current = mTabControl.getCurrentWebView();
2042 if (current == null) {
2043 return;
2044 }
2045 resetTitleAndIcon(current);
2046 int progress = current.getProgress();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002047 mWebChromeClient.onProgressChanged(current, progress);
2048 }
2049
2050 // Reset the title and the icon based on the given item.
2051 private void resetTitleAndIcon(WebView view) {
2052 WebHistoryItem item = view.copyBackForwardList().getCurrentItem();
2053 if (item != null) {
Leon Scroggins68579392009-09-15 15:31:54 -04002054 setUrlTitle(item.getUrl(), item.getTitle());
The Android Open Source Project0c908882009-03-03 19:32:16 -08002055 setFavicon(item.getFavicon());
2056 } else {
Leon Scroggins68579392009-09-15 15:31:54 -04002057 setUrlTitle(null, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002058 setFavicon(null);
2059 }
2060 }
2061
2062 /**
2063 * Sets a title composed of the URL and the title string.
2064 * @param url The URL of the site being loaded.
2065 * @param title The title of the site being loaded.
2066 */
Leon Scroggins68579392009-09-15 15:31:54 -04002067 private void setUrlTitle(String url, String title) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002068 mUrl = url;
2069 mTitle = title;
2070
Leon Scroggins68579392009-09-15 15:31:54 -04002071 mTitleBar.setTitleAndUrl(title, url);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04002072 if (mFakeTitleBar != null) {
2073 mFakeTitleBar.setTitleAndUrl(title, url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002074 }
2075 }
2076
2077 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08002078 * @param url The URL to build a title version of the URL from.
2079 * @return The title version of the URL or null if fails.
2080 * The title version of the URL can be either the URL hostname,
2081 * or the hostname with an "https://" prefix (for secure URLs),
2082 * or an empty string if, for example, the URL in question is a
2083 * file:// URL with no hostname.
2084 */
Leon Scroggins32e14a62009-06-11 10:26:34 -04002085 /* package */ static String buildTitleUrl(String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002086 String titleUrl = null;
2087
2088 if (url != null) {
2089 try {
2090 // parse the url string
2091 URL urlObj = new URL(url);
2092 if (urlObj != null) {
2093 titleUrl = "";
2094
2095 String protocol = urlObj.getProtocol();
2096 String host = urlObj.getHost();
2097
2098 if (host != null && 0 < host.length()) {
2099 titleUrl = host;
2100 if (protocol != null) {
2101 // if a secure site, add an "https://" prefix!
2102 if (protocol.equalsIgnoreCase("https")) {
2103 titleUrl = protocol + "://" + host;
2104 }
2105 }
2106 }
2107 }
2108 } catch (MalformedURLException e) {}
2109 }
2110
2111 return titleUrl;
2112 }
2113
2114 // Set the favicon in the title bar.
2115 private void setFavicon(Bitmap icon) {
Leon Scroggins68579392009-09-15 15:31:54 -04002116 mTitleBar.setFavicon(icon);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04002117 if (mFakeTitleBar != null) {
2118 mFakeTitleBar.setFavicon(icon);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002119 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002120 }
2121
2122 /**
2123 * Saves the current lock-icon state before resetting
2124 * the lock icon. If we have an error, we may need to
2125 * roll back to the previous state.
2126 */
2127 private void saveLockIcon() {
2128 mPrevLockType = mLockIconType;
2129 }
2130
2131 /**
2132 * Reverts the lock-icon state to the last saved state,
2133 * for example, if we had an error, and need to cancel
2134 * the load.
2135 */
2136 private void revertLockIcon() {
2137 mLockIconType = mPrevLockType;
2138
Dave Bort31a6d1c2009-04-13 15:56:49 -07002139 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002140 Log.v(LOGTAG, "BrowserActivity.revertLockIcon:" +
2141 " revert lock icon to " + mLockIconType);
2142 }
2143
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04002144 updateLockIconToLatest();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002145 }
2146
Leon Scroggins1f005d32009-08-10 17:36:42 -04002147 /**
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002148 * Close the tab, remove its associated title bar, and adjust mTabControl's
2149 * current tab to a valid value.
Leon Scroggins1f005d32009-08-10 17:36:42 -04002150 */
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002151 /* package */ void closeTab(TabControl.Tab t) {
2152 int currentIndex = mTabControl.getCurrentIndex();
2153 int removeIndex = mTabControl.getTabIndex(t);
Leon Scroggins1f005d32009-08-10 17:36:42 -04002154 mTabControl.removeTab(t);
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002155 if (currentIndex >= removeIndex && currentIndex != 0) {
2156 currentIndex--;
2157 }
2158 mTabControl.setCurrentTab(mTabControl.getTab(currentIndex));
Andrei Popescua5bf1de2009-09-23 16:39:23 +01002159 resetTitleIconAndProgress();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002160 }
2161
2162 private void goBackOnePageOrQuit() {
2163 TabControl.Tab current = mTabControl.getCurrentTab();
2164 if (current == null) {
2165 /*
2166 * Instead of finishing the activity, simply push this to the back
2167 * of the stack and let ActivityManager to choose the foreground
2168 * activity. As BrowserActivity is singleTask, it will be always the
2169 * root of the task. So we can use either true or false for
2170 * moveTaskToBack().
2171 */
2172 moveTaskToBack(true);
Grace Kloba00d85e72009-09-23 18:50:05 -07002173 return;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002174 }
2175 WebView w = current.getWebView();
2176 if (w.canGoBack()) {
2177 w.goBack();
2178 } else {
2179 // Check to see if we are closing a window that was created by
2180 // another window. If so, we switch back to that window.
2181 TabControl.Tab parent = current.getParentTab();
2182 if (parent != null) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04002183 switchToTab(mTabControl.getTabIndex(parent));
2184 // Now we close the other tab
2185 closeTab(current);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002186 } else {
2187 if (current.closeOnExit()) {
Grace Klobabb0af5c2009-09-01 00:56:09 -07002188 // force mPageStarted to be false as we are going to either
2189 // finish the activity or remove the tab. This will ensure
2190 // pauseWebView() taking action.
2191 mPageStarted = false;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002192 if (mTabControl.getTabCount() == 1) {
2193 finish();
2194 return;
2195 }
Mike Reed7bfa63b2009-05-28 11:08:32 -04002196 // call pauseWebViewTimers() now, we won't be able to call
2197 // it in onPause() as the WebView won't be valid.
Grace Klobaec1b5ad2009-08-18 08:42:32 -07002198 // Temporarily change mActivityInPause to be true as
2199 // pauseWebViewTimers() will do nothing if mActivityInPause
2200 // is false.
Grace Kloba918e1d72009-08-13 14:55:06 -07002201 boolean savedState = mActivityInPause;
2202 if (savedState) {
Grace Klobaec1b5ad2009-08-18 08:42:32 -07002203 Log.e(LOGTAG, "BrowserActivity is already paused "
2204 + "while handing goBackOnePageOrQuit.");
Grace Kloba918e1d72009-08-13 14:55:06 -07002205 }
2206 mActivityInPause = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -04002207 pauseWebViewTimers();
Grace Kloba918e1d72009-08-13 14:55:06 -07002208 mActivityInPause = savedState;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002209 removeTabFromContentView(current);
2210 mTabControl.removeTab(current);
2211 }
2212 /*
2213 * Instead of finishing the activity, simply push this to the back
2214 * of the stack and let ActivityManager to choose the foreground
2215 * activity. As BrowserActivity is singleTask, it will be always the
2216 * root of the task. So we can use either true or false for
2217 * moveTaskToBack().
2218 */
2219 moveTaskToBack(true);
2220 }
2221 }
2222 }
2223
Grace Kloba5942df02009-09-18 11:48:29 -07002224 @Override
2225 public boolean onKeyDown(int keyCode, KeyEvent event) {
2226 // The default key mode is DEFAULT_KEYS_SEARCH_LOCAL. As the MENU is
2227 // still down, we don't want to trigger the search. Pretend to consume
2228 // the key and do nothing.
2229 if (mMenuIsDown) return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002230
Grace Kloba5942df02009-09-18 11:48:29 -07002231 switch(keyCode) {
2232 case KeyEvent.KEYCODE_MENU:
2233 mMenuIsDown = true;
2234 break;
2235 case KeyEvent.KEYCODE_SPACE:
Grace Klobada0fe552009-09-22 18:17:24 -07002236 // WebView/WebTextView handle the keys in the KeyDown. As
2237 // the Activity's shortcut keys are only handled when WebView
2238 // doesn't, have to do it in onKeyDown instead of onKeyUp.
2239 if (event.isShiftPressed()) {
2240 getTopWindow().pageUp(false);
2241 } else {
2242 getTopWindow().pageDown(false);
2243 }
Grace Kloba5942df02009-09-18 11:48:29 -07002244 return true;
2245 case KeyEvent.KEYCODE_BACK:
2246 if (event.getRepeatCount() == 0) {
2247 event.startTracking();
2248 return true;
2249 } else if (mCustomView == null && mActiveTabsPage == null
2250 && event.isLongPress()) {
2251 bookmarksOrHistoryPicker(true);
2252 return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002253 }
Grace Kloba5942df02009-09-18 11:48:29 -07002254 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002255 }
Grace Kloba5942df02009-09-18 11:48:29 -07002256 return super.onKeyDown(keyCode, event);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002257 }
2258
Grace Kloba5942df02009-09-18 11:48:29 -07002259 @Override
2260 public boolean onKeyUp(int keyCode, KeyEvent event) {
2261 switch(keyCode) {
2262 case KeyEvent.KEYCODE_MENU:
2263 mMenuIsDown = false;
2264 break;
Grace Kloba5942df02009-09-18 11:48:29 -07002265 case KeyEvent.KEYCODE_BACK:
2266 if (event.isTracking() && !event.isCanceled()) {
2267 if (mCustomView != null) {
2268 // if a custom view is showing, hide it
2269 mWebChromeClient.onHideCustomView();
2270 } else if (mActiveTabsPage != null) {
2271 // if tab page is showing, hide it
2272 removeActiveTabPage(true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002273 } else {
Grace Kloba5942df02009-09-18 11:48:29 -07002274 WebView subwindow = mTabControl.getCurrentSubWindow();
2275 if (subwindow != null) {
2276 if (subwindow.canGoBack()) {
2277 subwindow.goBack();
2278 } else {
2279 dismissSubWindow(mTabControl.getCurrentTab());
2280 }
2281 } else {
2282 goBackOnePageOrQuit();
2283 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002284 }
Grace Kloba5942df02009-09-18 11:48:29 -07002285 return true;
2286 }
2287 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002288 }
Grace Kloba5942df02009-09-18 11:48:29 -07002289 return super.onKeyUp(keyCode, event);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002290 }
2291
Leon Scroggins68579392009-09-15 15:31:54 -04002292 /* package */ void stopLoading() {
Ben Murdochb7cc8b42009-09-28 10:59:09 +01002293 mDidStopLoad = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002294 resetTitleAndRevertLockIcon();
2295 WebView w = getTopWindow();
2296 w.stopLoading();
2297 mWebViewClient.onPageFinished(w, w.getUrl());
2298
2299 cancelStopToast();
2300 mStopToast = Toast
2301 .makeText(this, R.string.stopping, Toast.LENGTH_SHORT);
2302 mStopToast.show();
2303 }
2304
2305 private void cancelStopToast() {
2306 if (mStopToast != null) {
2307 mStopToast.cancel();
2308 mStopToast = null;
2309 }
2310 }
2311
2312 // called by a non-UI thread to post the message
2313 public void postMessage(int what, int arg1, int arg2, Object obj) {
2314 mHandler.sendMessage(mHandler.obtainMessage(what, arg1, arg2, obj));
2315 }
2316
2317 // public message ids
2318 public final static int LOAD_URL = 1001;
2319 public final static int STOP_LOAD = 1002;
2320
2321 // Message Ids
2322 private static final int FOCUS_NODE_HREF = 102;
2323 private static final int CANCEL_CREDS_REQUEST = 103;
Grace Kloba92c18a52009-07-31 23:48:32 -07002324 private static final int RELEASE_WAKELOCK = 107;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002325
Ben Murdoch2694e232009-09-29 09:41:11 +01002326 private static final int UPDATE_BOOKMARK_THUMBNAIL = 108;
2327
The Android Open Source Project0c908882009-03-03 19:32:16 -08002328 // Private handler for handling javascript and saving passwords
2329 private Handler mHandler = new Handler() {
2330
2331 public void handleMessage(Message msg) {
2332 switch (msg.what) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002333 case FOCUS_NODE_HREF:
Ben Murdoch2694e232009-09-29 09:41:11 +01002334 {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002335 String url = (String) msg.getData().get("url");
2336 if (url == null || url.length() == 0) {
2337 break;
2338 }
2339 HashMap focusNodeMap = (HashMap) msg.obj;
2340 WebView view = (WebView) focusNodeMap.get("webview");
2341 // Only apply the action if the top window did not change.
2342 if (getTopWindow() != view) {
2343 break;
2344 }
2345 switch (msg.arg1) {
2346 case R.id.open_context_menu_id:
2347 case R.id.view_image_context_menu_id:
2348 loadURL(getTopWindow(), url);
2349 break;
2350 case R.id.open_newtab_context_menu_id:
Grace Klobac9181842009-04-14 08:53:22 -07002351 final TabControl.Tab parent = mTabControl
2352 .getCurrentTab();
2353 final TabControl.Tab newTab = openTab(url);
2354 if (newTab != parent) {
2355 parent.addChildTab(newTab);
2356 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002357 break;
2358 case R.id.bookmark_context_menu_id:
2359 Intent intent = new Intent(BrowserActivity.this,
2360 AddBookmarkPage.class);
2361 intent.putExtra("url", url);
2362 startActivity(intent);
2363 break;
2364 case R.id.share_link_context_menu_id:
Andrei Popescu10fdba82009-09-24 13:25:47 +01002365 Browser.sendString(BrowserActivity.this, url,
2366 getText(R.string.choosertitle_sharevia).toString());
The Android Open Source Project0c908882009-03-03 19:32:16 -08002367 break;
2368 case R.id.copy_link_context_menu_id:
2369 copy(url);
2370 break;
2371 case R.id.save_link_context_menu_id:
2372 case R.id.download_context_menu_id:
2373 onDownloadStartNoStream(url, null, null, null, -1);
2374 break;
2375 }
2376 break;
Ben Murdoch2694e232009-09-29 09:41:11 +01002377 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002378
2379 case LOAD_URL:
2380 loadURL(getTopWindow(), (String) msg.obj);
2381 break;
2382
2383 case STOP_LOAD:
2384 stopLoading();
2385 break;
2386
2387 case CANCEL_CREDS_REQUEST:
2388 resumeAfterCredentials();
2389 break;
2390
The Android Open Source Project0c908882009-03-03 19:32:16 -08002391 case RELEASE_WAKELOCK:
2392 if (mWakeLock.isHeld()) {
2393 mWakeLock.release();
2394 }
2395 break;
Ben Murdoch2694e232009-09-29 09:41:11 +01002396
2397 case UPDATE_BOOKMARK_THUMBNAIL:
2398 WebView view = (WebView) msg.obj;
2399 if (view != null) {
2400 updateScreenshot(view);
2401 }
2402 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002403 }
2404 }
2405 };
2406
Leon Scroggins89c6d362009-07-15 16:54:37 -04002407 private void updateScreenshot(WebView view) {
2408 // If this is a bookmarked site, add a screenshot to the database.
2409 // FIXME: When should we update? Every time?
2410 // FIXME: Would like to make sure there is actually something to
2411 // draw, but the API for that (WebViewCore.pictureReady()) is not
2412 // currently accessible here.
Ben Murdochaac7aa62009-09-17 16:57:40 +01002413
Patrick Scott3918d442009-08-04 13:22:29 -04002414 ContentResolver cr = getContentResolver();
2415 final Cursor c = BrowserBookmarksAdapter.queryBookmarksForUrl(
Ben Murdochaac7aa62009-09-17 16:57:40 +01002416 cr, view.getOriginalUrl(), view.getUrl(), true);
Patrick Scott3918d442009-08-04 13:22:29 -04002417 if (c != null) {
Leon Scroggins89c6d362009-07-15 16:54:37 -04002418 boolean succeed = c.moveToFirst();
2419 ContentValues values = null;
2420 while (succeed) {
2421 if (values == null) {
2422 final ByteArrayOutputStream os
2423 = new ByteArrayOutputStream();
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002424 Bitmap bm = createScreenshot(view);
Leon Scroggins45800572009-09-29 16:38:47 -04002425 if (bm == null) {
2426 c.close();
2427 return;
2428 }
Leon Scroggins89c6d362009-07-15 16:54:37 -04002429 bm.compress(Bitmap.CompressFormat.PNG, 100, os);
2430 values = new ContentValues();
2431 values.put(Browser.BookmarkColumns.THUMBNAIL,
2432 os.toByteArray());
2433 }
2434 cr.update(ContentUris.withAppendedId(Browser.BOOKMARKS_URI,
2435 c.getInt(0)), values, null, null);
2436 succeed = c.moveToNext();
2437 }
2438 c.close();
2439 }
2440 }
2441
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002442 /**
Leon Scrogginsf8551612009-09-24 16:06:02 -04002443 * Values for the size of the thumbnail created when taking a screenshot.
2444 * Lazily initialized. Instead of using these directly, use
2445 * getDesiredThumbnailWidth() or getDesiredThumbnailHeight().
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002446 */
Leon Scrogginsf8551612009-09-24 16:06:02 -04002447 private static int THUMBNAIL_WIDTH = 0;
2448 private static int THUMBNAIL_HEIGHT = 0;
2449
2450 /**
2451 * Return the desired width for thumbnail screenshots, which are stored in
2452 * the database, and used on the bookmarks screen.
2453 * @param context Context for finding out the density of the screen.
2454 * @return int desired width for thumbnail screenshot.
2455 */
2456 /* package */ static int getDesiredThumbnailWidth(Context context) {
2457 if (THUMBNAIL_WIDTH == 0) {
2458 float density = context.getResources().getDisplayMetrics().density;
2459 THUMBNAIL_WIDTH = (int) (90 * density);
2460 THUMBNAIL_HEIGHT = (int) (80 * density);
2461 }
2462 return THUMBNAIL_WIDTH;
2463 }
2464
2465 /**
2466 * Return the desired height for thumbnail screenshots, which are stored in
2467 * the database, and used on the bookmarks screen.
2468 * @param context Context for finding out the density of the screen.
2469 * @return int desired height for thumbnail screenshot.
2470 */
2471 /* package */ static int getDesiredThumbnailHeight(Context context) {
2472 // To ensure that they are both initialized.
2473 getDesiredThumbnailWidth(context);
2474 return THUMBNAIL_HEIGHT;
2475 }
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002476
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002477 private Bitmap createScreenshot(WebView view) {
2478 Picture thumbnail = view.capturePicture();
Leon Scroggins45800572009-09-29 16:38:47 -04002479 if (thumbnail == null) {
2480 return null;
2481 }
Leon Scrogginsf8551612009-09-24 16:06:02 -04002482 Bitmap bm = Bitmap.createBitmap(getDesiredThumbnailWidth(this),
2483 getDesiredThumbnailHeight(this), Bitmap.Config.ARGB_4444);
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002484 Canvas canvas = new Canvas(bm);
2485 // May need to tweak these values to determine what is the
2486 // best scale factor
Ben Murdoch2694e232009-09-29 09:41:11 +01002487 int thumbnailWidth = thumbnail.getWidth();
2488 if (thumbnailWidth > 0) {
2489 float scaleFactor = (float) getDesiredThumbnailWidth(this) /
2490 (float)thumbnailWidth;
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002491 canvas.scale(scaleFactor, scaleFactor);
2492 }
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002493 thumbnail.draw(canvas);
2494 return bm;
2495 }
2496
The Android Open Source Project0c908882009-03-03 19:32:16 -08002497 // -------------------------------------------------------------------------
2498 // WebViewClient implementation.
2499 //-------------------------------------------------------------------------
2500
2501 // Use in overrideUrlLoading
2502 /* package */ final static String SCHEME_WTAI = "wtai://wp/";
2503 /* package */ final static String SCHEME_WTAI_MC = "wtai://wp/mc;";
2504 /* package */ final static String SCHEME_WTAI_SD = "wtai://wp/sd;";
2505 /* package */ final static String SCHEME_WTAI_AP = "wtai://wp/ap;";
2506
2507 /* package */ WebViewClient getWebViewClient() {
2508 return mWebViewClient;
2509 }
2510
Patrick Scott3918d442009-08-04 13:22:29 -04002511 private void updateIcon(WebView view, Bitmap icon) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002512 if (icon != null) {
2513 BrowserBookmarksAdapter.updateBookmarkFavicon(mResolver,
Patrick Scott15525d42009-09-21 13:39:37 -04002514 view.getOriginalUrl(), view.getUrl(), icon);
2515 }
2516 setFavicon(icon);
2517 }
2518
2519 private void updateIcon(String url, Bitmap icon) {
2520 if (icon != null) {
2521 BrowserBookmarksAdapter.updateBookmarkFavicon(mResolver,
2522 null, url, icon);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002523 }
2524 setFavicon(icon);
2525 }
2526
2527 private final WebViewClient mWebViewClient = new WebViewClient() {
2528 @Override
2529 public void onPageStarted(WebView view, String url, Bitmap favicon) {
2530 resetLockIcon(url);
Leon Scroggins68579392009-09-15 15:31:54 -04002531 setUrlTitle(url, null);
Ben Murdochbff2d602009-07-01 20:19:05 +01002532
Ben Murdoch2694e232009-09-29 09:41:11 +01002533 // We've started to load a new page. If there was a pending message
2534 // to save a screenshot then we will now take the new page and
2535 // save an incorrect screenshot. Therefore, remove any pending
2536 // thumbnail messages from the queue.
2537 mHandler.removeMessages(UPDATE_BOOKMARK_THUMBNAIL);
2538
Patrick Scott59ce8302009-09-18 16:29:38 -04002539 // If we start a touch icon load and then load a new page, we don't
2540 // want to cancel the current touch icon loader. But, we do want to
2541 // create a new one when the touch icon url is known.
2542 if (mTouchIconLoader != null) {
2543 mTouchIconLoader.mActivity = null;
2544 mTouchIconLoader = null;
2545 }
2546
Ben Murdochbff2d602009-07-01 20:19:05 +01002547 ErrorConsoleView errorConsole = mTabControl.getCurrentErrorConsole(false);
2548 if (errorConsole != null) {
2549 errorConsole.clearErrorMessages();
2550 if (mShouldShowErrorConsole) {
2551 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
2552 }
2553 }
2554
The Android Open Source Project0c908882009-03-03 19:32:16 -08002555 // Call updateIcon instead of setFavicon so the bookmark
2556 // database can be updated.
Patrick Scott15525d42009-09-21 13:39:37 -04002557 updateIcon(url, favicon);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002558
Grace Kloba4d7880f2009-08-12 09:35:42 -07002559 if (mSettings.isTracing()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002560 String host;
2561 try {
2562 WebAddress uri = new WebAddress(url);
2563 host = uri.mHost;
2564 } catch (android.net.ParseException ex) {
Grace Kloba4d7880f2009-08-12 09:35:42 -07002565 host = "browser";
The Android Open Source Project0c908882009-03-03 19:32:16 -08002566 }
2567 host = host.replace('.', '_');
Grace Kloba4d7880f2009-08-12 09:35:42 -07002568 host += ".trace";
The Android Open Source Project0c908882009-03-03 19:32:16 -08002569 mInTrace = true;
Grace Kloba4d7880f2009-08-12 09:35:42 -07002570 Debug.startMethodTracing(host, 20 * 1024 * 1024);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002571 }
2572
2573 // Performance probe
2574 if (false) {
2575 mStart = SystemClock.uptimeMillis();
2576 mProcessStart = Process.getElapsedCpuTime();
2577 long[] sysCpu = new long[7];
2578 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2579 sysCpu, null)) {
2580 mUserStart = sysCpu[0] + sysCpu[1];
2581 mSystemStart = sysCpu[2];
2582 mIdleStart = sysCpu[3];
2583 mIrqStart = sysCpu[4] + sysCpu[5] + sysCpu[6];
2584 }
2585 mUiStart = SystemClock.currentThreadTimeMillis();
2586 }
2587
2588 if (!mPageStarted) {
2589 mPageStarted = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -04002590 // if onResume() has been called, resumeWebViewTimers() does
2591 // nothing.
2592 resumeWebViewTimers();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002593 }
2594
2595 // reset sync timer to avoid sync starts during loading a page
2596 CookieSyncManager.getInstance().resetSync();
2597
2598 mInLoad = true;
Ben Murdochb7cc8b42009-09-28 10:59:09 +01002599 mDidStopLoad = false;
Leon Scroggins184f5e32009-09-21 10:38:24 -04002600 showFakeTitleBar();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002601 updateInLoadMenuItems();
2602 if (!mIsNetworkUp) {
Patrick Scotteb6ab2a2009-09-16 10:00:17 -04002603 createAndShowNetworkDialog();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002604 if (view != null) {
2605 view.setNetworkAvailable(false);
2606 }
2607 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002608 }
2609
2610 @Override
2611 public void onPageFinished(WebView view, String url) {
2612 // Reset the title and icon in case we stopped a provisional
2613 // load.
2614 resetTitleAndIcon(view);
Ben Murdochb7cc8b42009-09-28 10:59:09 +01002615
2616 if (!mDidStopLoad) {
2617 // Only update the bookmark screenshot if the user did not
2618 // cancel the load early.
Ben Murdoch2694e232009-09-29 09:41:11 +01002619 Message updateScreenshot = Message.obtain(mHandler, UPDATE_BOOKMARK_THUMBNAIL, view);
2620 mHandler.sendMessageDelayed(updateScreenshot, 500);
Ben Murdochb7cc8b42009-09-28 10:59:09 +01002621 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002622
2623 // Update the lock icon image only once we are done loading
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04002624 updateLockIconToLatest();
Leon Scrogginsb6b7f9e2009-06-18 12:05:28 -04002625
The Android Open Source Project0c908882009-03-03 19:32:16 -08002626 // Performance probe
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07002627 if (false) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002628 long[] sysCpu = new long[7];
2629 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2630 sysCpu, null)) {
2631 String uiInfo = "UI thread used "
2632 + (SystemClock.currentThreadTimeMillis() - mUiStart)
2633 + " ms";
Dave Bort31a6d1c2009-04-13 15:56:49 -07002634 if (LOGD_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002635 Log.d(LOGTAG, uiInfo);
2636 }
2637 //The string that gets written to the log
2638 String performanceString = "It took total "
2639 + (SystemClock.uptimeMillis() - mStart)
2640 + " ms clock time to load the page."
2641 + "\nbrowser process used "
2642 + (Process.getElapsedCpuTime() - mProcessStart)
2643 + " ms, user processes used "
2644 + (sysCpu[0] + sysCpu[1] - mUserStart) * 10
2645 + " ms, kernel used "
2646 + (sysCpu[2] - mSystemStart) * 10
2647 + " ms, idle took " + (sysCpu[3] - mIdleStart) * 10
2648 + " ms and irq took "
2649 + (sysCpu[4] + sysCpu[5] + sysCpu[6] - mIrqStart)
2650 * 10 + " ms, " + uiInfo;
Dave Bort31a6d1c2009-04-13 15:56:49 -07002651 if (LOGD_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002652 Log.d(LOGTAG, performanceString + "\nWebpage: " + url);
2653 }
2654 if (url != null) {
2655 // strip the url to maintain consistency
2656 String newUrl = new String(url);
2657 if (newUrl.startsWith("http://www.")) {
2658 newUrl = newUrl.substring(11);
2659 } else if (newUrl.startsWith("http://")) {
2660 newUrl = newUrl.substring(7);
2661 } else if (newUrl.startsWith("https://www.")) {
2662 newUrl = newUrl.substring(12);
2663 } else if (newUrl.startsWith("https://")) {
2664 newUrl = newUrl.substring(8);
2665 }
Dave Bort31a6d1c2009-04-13 15:56:49 -07002666 if (LOGD_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002667 Log.d(LOGTAG, newUrl + " loaded");
2668 }
2669 /*
2670 if (sWhiteList.contains(newUrl)) {
2671 // The string that gets pushed to the statistcs
2672 // service
2673 performanceString = performanceString
2674 + "\nWebpage: "
2675 + newUrl
2676 + "\nCarrier: "
2677 + android.os.SystemProperties
2678 .get("gsm.sim.operator.alpha");
2679 if (mWebView != null
2680 && mWebView.getContext() != null
2681 && mWebView.getContext().getSystemService(
2682 Context.CONNECTIVITY_SERVICE) != null) {
2683 ConnectivityManager cManager =
2684 (ConnectivityManager) mWebView
2685 .getContext().getSystemService(
2686 Context.CONNECTIVITY_SERVICE);
2687 NetworkInfo nInfo = cManager
2688 .getActiveNetworkInfo();
2689 if (nInfo != null) {
2690 performanceString = performanceString
2691 + "\nNetwork Type: "
2692 + nInfo.getType().toString();
2693 }
2694 }
2695 Checkin.logEvent(mResolver,
2696 Checkin.Events.Tag.WEBPAGE_LOAD,
2697 performanceString);
2698 Log.w(LOGTAG, "pushed to the statistics service");
2699 }
2700 */
2701 }
2702 }
2703 }
2704
2705 if (mInTrace) {
2706 mInTrace = false;
2707 Debug.stopMethodTracing();
2708 }
2709
2710 if (mPageStarted) {
2711 mPageStarted = false;
Mike Reed7bfa63b2009-05-28 11:08:32 -04002712 // pauseWebViewTimers() will do nothing and return false if
2713 // onPause() is not called yet.
2714 if (pauseWebViewTimers()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002715 if (mWakeLock.isHeld()) {
2716 mHandler.removeMessages(RELEASE_WAKELOCK);
2717 mWakeLock.release();
2718 }
2719 }
2720 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002721 }
2722
2723 // return true if want to hijack the url to let another app to handle it
2724 @Override
2725 public boolean shouldOverrideUrlLoading(WebView view, String url) {
2726 if (url.startsWith(SCHEME_WTAI)) {
2727 // wtai://wp/mc;number
2728 // number=string(phone-number)
2729 if (url.startsWith(SCHEME_WTAI_MC)) {
2730 Intent intent = new Intent(Intent.ACTION_VIEW,
2731 Uri.parse(WebView.SCHEME_TEL +
2732 url.substring(SCHEME_WTAI_MC.length())));
2733 startActivity(intent);
2734 return true;
2735 }
2736 // wtai://wp/sd;dtmf
2737 // dtmf=string(dialstring)
2738 if (url.startsWith(SCHEME_WTAI_SD)) {
2739 // TODO
2740 // only send when there is active voice connection
2741 return false;
2742 }
2743 // wtai://wp/ap;number;name
2744 // number=string(phone-number)
2745 // name=string
2746 if (url.startsWith(SCHEME_WTAI_AP)) {
2747 // TODO
2748 return false;
2749 }
2750 }
2751
Dianne Hackborn99189432009-06-17 18:06:18 -07002752 // The "about:" schemes are internal to the browser; don't
2753 // want these to be dispatched to other apps.
2754 if (url.startsWith("about:")) {
2755 return false;
2756 }
Ben Murdochbff2d602009-07-01 20:19:05 +01002757
Dianne Hackborn99189432009-06-17 18:06:18 -07002758 Intent intent;
Ben Murdochbff2d602009-07-01 20:19:05 +01002759
Dianne Hackborn99189432009-06-17 18:06:18 -07002760 // perform generic parsing of the URI to turn it into an Intent.
The Android Open Source Project0c908882009-03-03 19:32:16 -08002761 try {
Dianne Hackborn99189432009-06-17 18:06:18 -07002762 intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME);
2763 } catch (URISyntaxException ex) {
2764 Log.w("Browser", "Bad URI " + url + ": " + ex.getMessage());
The Android Open Source Project0c908882009-03-03 19:32:16 -08002765 return false;
2766 }
2767
Grace Kloba5b078b52009-06-24 20:23:41 -07002768 // check whether the intent can be resolved. If not, we will see
2769 // whether we can download it from the Market.
2770 if (getPackageManager().resolveActivity(intent, 0) == null) {
2771 String packagename = intent.getPackage();
2772 if (packagename != null) {
2773 intent = new Intent(Intent.ACTION_VIEW, Uri
2774 .parse("market://search?q=pname:" + packagename));
2775 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2776 startActivity(intent);
2777 return true;
2778 } else {
2779 return false;
2780 }
2781 }
2782
Dianne Hackborn99189432009-06-17 18:06:18 -07002783 // sanitize the Intent, ensuring web pages can not bypass browser
2784 // security (only access to BROWSABLE activities).
The Android Open Source Project0c908882009-03-03 19:32:16 -08002785 intent.addCategory(Intent.CATEGORY_BROWSABLE);
Dianne Hackborn99189432009-06-17 18:06:18 -07002786 intent.setComponent(null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002787 try {
2788 if (startActivityIfNeeded(intent, -1)) {
2789 return true;
2790 }
2791 } catch (ActivityNotFoundException ex) {
2792 // ignore the error. If no application can handle the URL,
2793 // eg about:blank, assume the browser can handle it.
2794 }
2795
2796 if (mMenuIsDown) {
2797 openTab(url);
2798 closeOptionsMenu();
2799 return true;
2800 }
2801
2802 return false;
2803 }
2804
2805 /**
2806 * Updates the lock icon. This method is called when we discover another
2807 * resource to be loaded for this page (for example, javascript). While
2808 * we update the icon type, we do not update the lock icon itself until
2809 * we are done loading, it is slightly more secure this way.
2810 */
2811 @Override
2812 public void onLoadResource(WebView view, String url) {
2813 if (url != null && url.length() > 0) {
2814 // It is only if the page claims to be secure
2815 // that we may have to update the lock:
2816 if (mLockIconType == LOCK_ICON_SECURE) {
2817 // If NOT a 'safe' url, change the lock to mixed content!
2818 if (!(URLUtil.isHttpsUrl(url) || URLUtil.isDataUrl(url) || URLUtil.isAboutUrl(url))) {
2819 mLockIconType = LOCK_ICON_MIXED;
Dave Bort31a6d1c2009-04-13 15:56:49 -07002820 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002821 Log.v(LOGTAG, "BrowserActivity.updateLockIcon:" +
2822 " updated lock icon to " + mLockIconType + " due to " + url);
2823 }
2824 }
2825 }
2826 }
2827 }
2828
2829 /**
2830 * Show the dialog, asking the user if they would like to continue after
2831 * an excessive number of HTTP redirects.
2832 */
2833 @Override
2834 public void onTooManyRedirects(WebView view, final Message cancelMsg,
2835 final Message continueMsg) {
2836 new AlertDialog.Builder(BrowserActivity.this)
2837 .setTitle(R.string.browserFrameRedirect)
2838 .setMessage(R.string.browserFrame307Post)
2839 .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
2840 public void onClick(DialogInterface dialog, int which) {
2841 continueMsg.sendToTarget();
2842 }})
2843 .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
2844 public void onClick(DialogInterface dialog, int which) {
2845 cancelMsg.sendToTarget();
2846 }})
2847 .setOnCancelListener(new OnCancelListener() {
2848 public void onCancel(DialogInterface dialog) {
2849 cancelMsg.sendToTarget();
2850 }})
2851 .show();
2852 }
2853
Patrick Scott37911c72009-03-24 18:02:58 -07002854 // Container class for the next error dialog that needs to be
2855 // displayed.
2856 class ErrorDialog {
2857 public final int mTitle;
2858 public final String mDescription;
2859 public final int mError;
2860 ErrorDialog(int title, String desc, int error) {
2861 mTitle = title;
2862 mDescription = desc;
2863 mError = error;
2864 }
2865 };
2866
2867 private void processNextError() {
2868 if (mQueuedErrors == null) {
2869 return;
2870 }
2871 // The first one is currently displayed so just remove it.
2872 mQueuedErrors.removeFirst();
2873 if (mQueuedErrors.size() == 0) {
2874 mQueuedErrors = null;
2875 return;
2876 }
2877 showError(mQueuedErrors.getFirst());
2878 }
2879
2880 private DialogInterface.OnDismissListener mDialogListener =
2881 new DialogInterface.OnDismissListener() {
2882 public void onDismiss(DialogInterface d) {
2883 processNextError();
2884 }
2885 };
2886 private LinkedList<ErrorDialog> mQueuedErrors;
2887
2888 private void queueError(int err, String desc) {
2889 if (mQueuedErrors == null) {
2890 mQueuedErrors = new LinkedList<ErrorDialog>();
2891 }
2892 for (ErrorDialog d : mQueuedErrors) {
2893 if (d.mError == err) {
2894 // Already saw a similar error, ignore the new one.
2895 return;
2896 }
2897 }
2898 ErrorDialog errDialog = new ErrorDialog(
Patrick Scott5d61a6c2009-08-25 13:52:46 -04002899 err == WebViewClient.ERROR_FILE_NOT_FOUND ?
Patrick Scott37911c72009-03-24 18:02:58 -07002900 R.string.browserFrameFileErrorLabel :
2901 R.string.browserFrameNetworkErrorLabel,
2902 desc, err);
2903 mQueuedErrors.addLast(errDialog);
2904
2905 // Show the dialog now if the queue was empty.
2906 if (mQueuedErrors.size() == 1) {
2907 showError(errDialog);
2908 }
2909 }
2910
2911 private void showError(ErrorDialog errDialog) {
2912 AlertDialog d = new AlertDialog.Builder(BrowserActivity.this)
2913 .setTitle(errDialog.mTitle)
2914 .setMessage(errDialog.mDescription)
2915 .setPositiveButton(R.string.ok, null)
2916 .create();
2917 d.setOnDismissListener(mDialogListener);
2918 d.show();
2919 }
2920
The Android Open Source Project0c908882009-03-03 19:32:16 -08002921 /**
2922 * Show a dialog informing the user of the network error reported by
2923 * WebCore.
2924 */
2925 @Override
2926 public void onReceivedError(WebView view, int errorCode,
2927 String description, String failingUrl) {
Patrick Scott5d61a6c2009-08-25 13:52:46 -04002928 if (errorCode != WebViewClient.ERROR_HOST_LOOKUP &&
2929 errorCode != WebViewClient.ERROR_CONNECT &&
2930 errorCode != WebViewClient.ERROR_BAD_URL &&
2931 errorCode != WebViewClient.ERROR_UNSUPPORTED_SCHEME &&
2932 errorCode != WebViewClient.ERROR_FILE) {
Patrick Scott37911c72009-03-24 18:02:58 -07002933 queueError(errorCode, description);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002934 }
Patrick Scott37911c72009-03-24 18:02:58 -07002935 Log.e(LOGTAG, "onReceivedError " + errorCode + " " + failingUrl
2936 + " " + description);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002937
2938 // We need to reset the title after an error.
2939 resetTitleAndRevertLockIcon();
2940 }
2941
2942 /**
2943 * Check with the user if it is ok to resend POST data as the page they
2944 * are trying to navigate to is the result of a POST.
2945 */
2946 @Override
2947 public void onFormResubmission(WebView view, final Message dontResend,
2948 final Message resend) {
2949 new AlertDialog.Builder(BrowserActivity.this)
2950 .setTitle(R.string.browserFrameFormResubmitLabel)
2951 .setMessage(R.string.browserFrameFormResubmitMessage)
2952 .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
2953 public void onClick(DialogInterface dialog, int which) {
2954 resend.sendToTarget();
2955 }})
2956 .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
2957 public void onClick(DialogInterface dialog, int which) {
2958 dontResend.sendToTarget();
2959 }})
2960 .setOnCancelListener(new OnCancelListener() {
2961 public void onCancel(DialogInterface dialog) {
2962 dontResend.sendToTarget();
2963 }})
2964 .show();
2965 }
2966
2967 /**
2968 * Insert the url into the visited history database.
2969 * @param url The url to be inserted.
2970 * @param isReload True if this url is being reloaded.
2971 * FIXME: Not sure what to do when reloading the page.
2972 */
2973 @Override
2974 public void doUpdateVisitedHistory(WebView view, String url,
2975 boolean isReload) {
2976 if (url.regionMatches(true, 0, "about:", 0, 6)) {
2977 return;
2978 }
Grace Kloba6b52a552009-09-03 16:29:56 -07002979 // remove "client" before updating it to the history so that it wont
2980 // show up in the auto-complete list.
2981 int index = url.indexOf("client=ms-");
2982 if (index > 0 && url.contains(".google.")) {
2983 int end = url.indexOf('&', index);
2984 if (end > 0) {
2985 url = url.substring(0, index-1).concat(url.substring(end));
2986 } else {
2987 url = url.substring(0, index-1);
2988 }
2989 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002990 Browser.updateVisitedHistory(mResolver, url, true);
2991 WebIconDatabase.getInstance().retainIconForPageUrl(url);
2992 }
2993
2994 /**
2995 * Displays SSL error(s) dialog to the user.
2996 */
2997 @Override
2998 public void onReceivedSslError(
2999 final WebView view, final SslErrorHandler handler, final SslError error) {
3000
3001 if (mSettings.showSecurityWarnings()) {
3002 final LayoutInflater factory =
3003 LayoutInflater.from(BrowserActivity.this);
3004 final View warningsView =
3005 factory.inflate(R.layout.ssl_warnings, null);
3006 final LinearLayout placeholder =
3007 (LinearLayout)warningsView.findViewById(R.id.placeholder);
3008
3009 if (error.hasError(SslError.SSL_UNTRUSTED)) {
3010 LinearLayout ll = (LinearLayout)factory
3011 .inflate(R.layout.ssl_warning, null);
3012 ((TextView)ll.findViewById(R.id.warning))
3013 .setText(R.string.ssl_untrusted);
3014 placeholder.addView(ll);
3015 }
3016
3017 if (error.hasError(SslError.SSL_IDMISMATCH)) {
3018 LinearLayout ll = (LinearLayout)factory
3019 .inflate(R.layout.ssl_warning, null);
3020 ((TextView)ll.findViewById(R.id.warning))
3021 .setText(R.string.ssl_mismatch);
3022 placeholder.addView(ll);
3023 }
3024
3025 if (error.hasError(SslError.SSL_EXPIRED)) {
3026 LinearLayout ll = (LinearLayout)factory
3027 .inflate(R.layout.ssl_warning, null);
3028 ((TextView)ll.findViewById(R.id.warning))
3029 .setText(R.string.ssl_expired);
3030 placeholder.addView(ll);
3031 }
3032
3033 if (error.hasError(SslError.SSL_NOTYETVALID)) {
3034 LinearLayout ll = (LinearLayout)factory
3035 .inflate(R.layout.ssl_warning, null);
3036 ((TextView)ll.findViewById(R.id.warning))
3037 .setText(R.string.ssl_not_yet_valid);
3038 placeholder.addView(ll);
3039 }
3040
3041 new AlertDialog.Builder(BrowserActivity.this)
3042 .setTitle(R.string.security_warning)
3043 .setIcon(android.R.drawable.ic_dialog_alert)
3044 .setView(warningsView)
3045 .setPositiveButton(R.string.ssl_continue,
3046 new DialogInterface.OnClickListener() {
3047 public void onClick(DialogInterface dialog, int whichButton) {
3048 handler.proceed();
3049 }
3050 })
3051 .setNeutralButton(R.string.view_certificate,
3052 new DialogInterface.OnClickListener() {
3053 public void onClick(DialogInterface dialog, int whichButton) {
3054 showSSLCertificateOnError(view, handler, error);
3055 }
3056 })
3057 .setNegativeButton(R.string.cancel,
3058 new DialogInterface.OnClickListener() {
3059 public void onClick(DialogInterface dialog, int whichButton) {
3060 handler.cancel();
3061 BrowserActivity.this.resetTitleAndRevertLockIcon();
3062 }
3063 })
3064 .setOnCancelListener(
3065 new DialogInterface.OnCancelListener() {
3066 public void onCancel(DialogInterface dialog) {
3067 handler.cancel();
3068 BrowserActivity.this.resetTitleAndRevertLockIcon();
3069 }
3070 })
3071 .show();
3072 } else {
3073 handler.proceed();
3074 }
3075 }
3076
3077 /**
3078 * Handles an HTTP authentication request.
3079 *
3080 * @param handler The authentication handler
3081 * @param host The host
3082 * @param realm The realm
3083 */
3084 @Override
3085 public void onReceivedHttpAuthRequest(WebView view,
3086 final HttpAuthHandler handler, final String host, final String realm) {
3087 String username = null;
3088 String password = null;
3089
3090 boolean reuseHttpAuthUsernamePassword =
3091 handler.useHttpAuthUsernamePassword();
3092
3093 if (reuseHttpAuthUsernamePassword &&
3094 (mTabControl.getCurrentWebView() != null)) {
3095 String[] credentials =
3096 mTabControl.getCurrentWebView()
3097 .getHttpAuthUsernamePassword(host, realm);
3098 if (credentials != null && credentials.length == 2) {
3099 username = credentials[0];
3100 password = credentials[1];
3101 }
3102 }
3103
3104 if (username != null && password != null) {
3105 handler.proceed(username, password);
3106 } else {
3107 showHttpAuthentication(handler, host, realm, null, null, null, 0);
3108 }
3109 }
3110
3111 @Override
3112 public boolean shouldOverrideKeyEvent(WebView view, KeyEvent event) {
3113 if (mMenuIsDown) {
3114 // only check shortcut key when MENU is held
3115 return getWindow().isShortcutKey(event.getKeyCode(), event);
3116 } else {
3117 return false;
3118 }
3119 }
3120
3121 @Override
3122 public void onUnhandledKeyEvent(WebView view, KeyEvent event) {
3123 if (view != mTabControl.getCurrentTopWebView()) {
3124 return;
3125 }
3126 if (event.isDown()) {
3127 BrowserActivity.this.onKeyDown(event.getKeyCode(), event);
3128 } else {
3129 BrowserActivity.this.onKeyUp(event.getKeyCode(), event);
3130 }
3131 }
3132 };
3133
3134 //--------------------------------------------------------------------------
3135 // WebChromeClient implementation
3136 //--------------------------------------------------------------------------
3137
3138 /* package */ WebChromeClient getWebChromeClient() {
3139 return mWebChromeClient;
3140 }
3141
3142 private final WebChromeClient mWebChromeClient = new WebChromeClient() {
3143 // Helper method to create a new tab or sub window.
3144 private void createWindow(final boolean dialog, final Message msg) {
3145 if (dialog) {
3146 mTabControl.createSubWindow();
3147 final TabControl.Tab t = mTabControl.getCurrentTab();
3148 attachSubWindow(t);
3149 WebView.WebViewTransport transport =
3150 (WebView.WebViewTransport) msg.obj;
3151 transport.setWebView(t.getSubWebView());
3152 msg.sendToTarget();
3153 } else {
3154 final TabControl.Tab parent = mTabControl.getCurrentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04003155 final TabControl.Tab newTab
3156 = openTabAndShow(EMPTY_URL_DATA, false, null);
Grace Klobac9181842009-04-14 08:53:22 -07003157 if (newTab != parent) {
3158 parent.addChildTab(newTab);
3159 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003160 WebView.WebViewTransport transport =
3161 (WebView.WebViewTransport) msg.obj;
3162 transport.setWebView(mTabControl.getCurrentWebView());
Leon Scroggins1f005d32009-08-10 17:36:42 -04003163 msg.sendToTarget();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003164 }
3165 }
3166
3167 @Override
3168 public boolean onCreateWindow(WebView view, final boolean dialog,
3169 final boolean userGesture, final Message resultMsg) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003170 // Short-circuit if we can't create any more tabs or sub windows.
3171 if (dialog && mTabControl.getCurrentSubWindow() != null) {
3172 new AlertDialog.Builder(BrowserActivity.this)
3173 .setTitle(R.string.too_many_subwindows_dialog_title)
3174 .setIcon(android.R.drawable.ic_dialog_alert)
3175 .setMessage(R.string.too_many_subwindows_dialog_message)
3176 .setPositiveButton(R.string.ok, null)
3177 .show();
3178 return false;
3179 } else if (mTabControl.getTabCount() >= TabControl.MAX_TABS) {
3180 new AlertDialog.Builder(BrowserActivity.this)
3181 .setTitle(R.string.too_many_windows_dialog_title)
3182 .setIcon(android.R.drawable.ic_dialog_alert)
3183 .setMessage(R.string.too_many_windows_dialog_message)
3184 .setPositiveButton(R.string.ok, null)
3185 .show();
3186 return false;
3187 }
3188
3189 // Short-circuit if this was a user gesture.
3190 if (userGesture) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003191 createWindow(dialog, resultMsg);
3192 return true;
3193 }
3194
3195 // Allow the popup and create the appropriate window.
3196 final AlertDialog.OnClickListener allowListener =
3197 new AlertDialog.OnClickListener() {
3198 public void onClick(DialogInterface d,
3199 int which) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003200 createWindow(dialog, resultMsg);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003201 }
3202 };
3203
3204 // Block the popup by returning a null WebView.
3205 final AlertDialog.OnClickListener blockListener =
3206 new AlertDialog.OnClickListener() {
3207 public void onClick(DialogInterface d, int which) {
3208 resultMsg.sendToTarget();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003209 }
3210 };
3211
3212 // Build a confirmation dialog to display to the user.
3213 final AlertDialog d =
3214 new AlertDialog.Builder(BrowserActivity.this)
3215 .setTitle(R.string.attention)
3216 .setIcon(android.R.drawable.ic_dialog_alert)
3217 .setMessage(R.string.popup_window_attempt)
3218 .setPositiveButton(R.string.allow, allowListener)
3219 .setNegativeButton(R.string.block, blockListener)
3220 .setCancelable(false)
3221 .create();
3222
3223 // Show the confirmation dialog.
3224 d.show();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003225 return true;
3226 }
3227
3228 @Override
3229 public void onCloseWindow(WebView window) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04003230 final TabControl.Tab current = mTabControl.getCurrentTab();
3231 final TabControl.Tab parent = current.getParentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003232 if (parent != null) {
3233 // JavaScript can only close popup window.
Leon Scroggins1f005d32009-08-10 17:36:42 -04003234 switchToTab(mTabControl.getTabIndex(parent));
3235 // Now we need to close the window
3236 closeTab(current);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003237 }
3238 }
3239
3240 @Override
3241 public void onProgressChanged(WebView view, int newProgress) {
Leon Scroggins68579392009-09-15 15:31:54 -04003242 mTitleBar.setProgress(newProgress);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04003243 if (mFakeTitleBar != null) {
3244 mFakeTitleBar.setProgress(newProgress);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003245 }
3246
3247 if (newProgress == 100) {
Ben Murdochaac7aa62009-09-17 16:57:40 +01003248 // onProgressChanged() may continue to be called after the main
3249 // frame has finished loading, as any remaining sub frames
3250 // continue to load. We'll only get called once though with
3251 // newProgress as 100 when everything is loaded.
3252 // (onPageFinished is called once when the main frame completes
3253 // loading regardless of the state of any sub frames so calls
3254 // to onProgressChanges may continue after onPageFinished has
3255 // executed)
3256
3257 // sync cookies and cache promptly here.
The Android Open Source Project0c908882009-03-03 19:32:16 -08003258 CookieSyncManager.getInstance().sync();
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07003259 if (mInLoad) {
3260 mInLoad = false;
3261 updateInLoadMenuItems();
Leon Scrogginsa27ff192009-09-14 12:58:04 -04003262 // If the options menu is open, leave the title bar
3263 if (!mOptionsMenuOpen || !mIconView) {
3264 hideFakeTitleBar();
3265 }
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07003266 }
Leon Scrogginsa27ff192009-09-14 12:58:04 -04003267 } else if (!mInLoad) {
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07003268 // onPageFinished may have already been called but a subframe
3269 // is still loading and updating the progress. Reset mInLoad
3270 // and update the menu items.
Leon Scrogginsa27ff192009-09-14 12:58:04 -04003271 mInLoad = true;
3272 updateInLoadMenuItems();
Leon Scroggins184f5e32009-09-21 10:38:24 -04003273 if (!mOptionsMenuOpen || mIconView) {
Leon Scrogginsa27ff192009-09-14 12:58:04 -04003274 // This page has begun to load, so show the title bar
3275 showFakeTitleBar();
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07003276 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003277 }
3278 }
3279
3280 @Override
3281 public void onReceivedTitle(WebView view, String title) {
Patrick Scott598c9cc2009-06-04 11:10:38 -04003282 String url = view.getUrl();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003283
3284 // here, if url is null, we want to reset the title
Leon Scroggins68579392009-09-15 15:31:54 -04003285 setUrlTitle(url, title);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003286
3287 if (url == null ||
3288 url.length() >= SQLiteDatabase.SQLITE_MAX_LIKE_PATTERN_LENGTH) {
3289 return;
3290 }
Leon Scrogginsfce182b2009-05-08 13:54:52 -04003291 // See if we can find the current url in our history database and
3292 // add the new title to it.
The Android Open Source Project0c908882009-03-03 19:32:16 -08003293 if (url.startsWith("http://www.")) {
3294 url = url.substring(11);
3295 } else if (url.startsWith("http://")) {
3296 url = url.substring(4);
3297 }
3298 try {
3299 url = "%" + url;
3300 String [] selArgs = new String[] { url };
3301
3302 String where = Browser.BookmarkColumns.URL + " LIKE ? AND "
3303 + Browser.BookmarkColumns.BOOKMARK + " = 0";
3304 Cursor c = mResolver.query(Browser.BOOKMARKS_URI,
3305 Browser.HISTORY_PROJECTION, where, selArgs, null);
3306 if (c.moveToFirst()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003307 // Current implementation of database only has one entry per
3308 // url.
Leon Scrogginsfce182b2009-05-08 13:54:52 -04003309 ContentValues map = new ContentValues();
3310 map.put(Browser.BookmarkColumns.TITLE, title);
3311 mResolver.update(Browser.BOOKMARKS_URI, map,
3312 "_id = " + c.getInt(0), null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003313 }
3314 c.close();
3315 } catch (IllegalStateException e) {
3316 Log.e(LOGTAG, "BrowserActivity onReceived title", e);
3317 } catch (SQLiteException ex) {
3318 Log.e(LOGTAG, "onReceivedTitle() caught SQLiteException: ", ex);
3319 }
3320 }
3321
3322 @Override
3323 public void onReceivedIcon(WebView view, Bitmap icon) {
Patrick Scott3918d442009-08-04 13:22:29 -04003324 updateIcon(view, icon);
3325 }
3326
3327 @Override
Patrick Scott59ce8302009-09-18 16:29:38 -04003328 public void onReceivedTouchIconUrl(WebView view, String url,
3329 boolean precomposed) {
Patrick Scott3918d442009-08-04 13:22:29 -04003330 final ContentResolver cr = getContentResolver();
3331 final Cursor c =
3332 BrowserBookmarksAdapter.queryBookmarksForUrl(cr,
Leon Scrogginsa5d669e2009-08-05 14:07:58 -04003333 view.getOriginalUrl(), view.getUrl(), true);
Patrick Scott3918d442009-08-04 13:22:29 -04003334 if (c != null) {
3335 if (c.getCount() > 0) {
Patrick Scott59ce8302009-09-18 16:29:38 -04003336 // Let precomposed icons take precedence over non-composed
3337 // icons.
3338 if (precomposed && mTouchIconLoader != null) {
3339 mTouchIconLoader.cancel(false);
3340 mTouchIconLoader = null;
3341 }
3342 // Have only one async task at a time.
3343 if (mTouchIconLoader == null) {
3344 mTouchIconLoader = new DownloadTouchIcon(
3345 BrowserActivity.this, cr, c, view);
3346 mTouchIconLoader.execute(url);
3347 }
Patrick Scott3918d442009-08-04 13:22:29 -04003348 } else {
3349 c.close();
3350 }
3351 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003352 }
Ben Murdoch092dd5d2009-04-22 12:34:12 +01003353
Andrei Popescuadc008d2009-06-26 14:11:30 +01003354 @Override
Andrei Popescuc9b55562009-07-07 10:51:15 +01003355 public void onShowCustomView(View view, WebChromeClient.CustomViewCallback callback) {
Andrei Popescuadc008d2009-06-26 14:11:30 +01003356 if (mCustomView != null)
3357 return;
3358
3359 // Add the custom view to its container.
3360 mCustomViewContainer.addView(view, COVER_SCREEN_GRAVITY_CENTER);
3361 mCustomView = view;
Andrei Popescuc9b55562009-07-07 10:51:15 +01003362 mCustomViewCallback = callback;
Andrei Popescuadc008d2009-06-26 14:11:30 +01003363 // Save the menu state and set it to empty while the custom
3364 // view is showing.
3365 mOldMenuState = mMenuState;
3366 mMenuState = EMPTY_MENU;
Andrei Popescuc9b55562009-07-07 10:51:15 +01003367 // Hide the content view.
3368 mContentView.setVisibility(View.GONE);
Andrei Popescuadc008d2009-06-26 14:11:30 +01003369 // Finally show the custom view container.
Andrei Popescuc9b55562009-07-07 10:51:15 +01003370 mCustomViewContainer.setVisibility(View.VISIBLE);
3371 mCustomViewContainer.bringToFront();
Andrei Popescuadc008d2009-06-26 14:11:30 +01003372 }
3373
3374 @Override
3375 public void onHideCustomView() {
3376 if (mCustomView == null)
3377 return;
3378
Andrei Popescuc9b55562009-07-07 10:51:15 +01003379 // Hide the custom view.
3380 mCustomView.setVisibility(View.GONE);
Andrei Popescuadc008d2009-06-26 14:11:30 +01003381 // Remove the custom view from its container.
3382 mCustomViewContainer.removeView(mCustomView);
3383 mCustomView = null;
3384 // Reset the old menu state.
3385 mMenuState = mOldMenuState;
3386 mOldMenuState = EMPTY_MENU;
3387 mCustomViewContainer.setVisibility(View.GONE);
Andrei Popescuc9b55562009-07-07 10:51:15 +01003388 mCustomViewCallback.onCustomViewHidden();
3389 // Show the content view.
3390 mContentView.setVisibility(View.VISIBLE);
Andrei Popescuadc008d2009-06-26 14:11:30 +01003391 }
3392
Ben Murdoch092dd5d2009-04-22 12:34:12 +01003393 /**
Andrei Popescu79e82b72009-07-27 12:01:59 +01003394 * The origin has exceeded its database quota.
Ben Murdoch092dd5d2009-04-22 12:34:12 +01003395 * @param url the URL that exceeded the quota
3396 * @param databaseIdentifier the identifier of the database on
3397 * which the transaction that caused the quota overflow was run
3398 * @param currentQuota the current quota for the origin.
Ben Murdoch25a15232009-08-25 19:38:07 +01003399 * @param estimatedSize the estimated size of the database.
Andrei Popescu79e82b72009-07-27 12:01:59 +01003400 * @param totalUsedQuota is the sum of all origins' quota.
Ben Murdoch092dd5d2009-04-22 12:34:12 +01003401 * @param quotaUpdater The callback to run when a decision to allow or
3402 * deny quota has been made. Don't forget to call this!
3403 */
3404 @Override
3405 public void onExceededDatabaseQuota(String url,
Ben Murdoch25a15232009-08-25 19:38:07 +01003406 String databaseIdentifier, long currentQuota, long estimatedSize,
3407 long totalUsedQuota, WebStorage.QuotaUpdater quotaUpdater) {
Andrei Popescu79e82b72009-07-27 12:01:59 +01003408 mSettings.getWebStorageSizeManager().onExceededDatabaseQuota(
Ben Murdoch25a15232009-08-25 19:38:07 +01003409 url, databaseIdentifier, currentQuota, estimatedSize,
3410 totalUsedQuota, quotaUpdater);
Andrei Popescu79e82b72009-07-27 12:01:59 +01003411 }
3412
3413 /**
3414 * The Application Cache has exceeded its max size.
3415 * @param spaceNeeded is the amount of disk space that would be needed
3416 * in order for the last appcache operation to succeed.
3417 * @param totalUsedQuota is the sum of all origins' quota.
3418 * @param quotaUpdater A callback to inform the WebCore thread that a new
3419 * app cache size is available. This callback must always be executed at
3420 * some point to ensure that the sleeping WebCore thread is woken up.
3421 */
3422 @Override
3423 public void onReachedMaxAppCacheSize(long spaceNeeded,
3424 long totalUsedQuota, WebStorage.QuotaUpdater quotaUpdater) {
3425 mSettings.getWebStorageSizeManager().onReachedMaxAppCacheSize(
3426 spaceNeeded, totalUsedQuota, quotaUpdater);
Ben Murdoch092dd5d2009-04-22 12:34:12 +01003427 }
Ben Murdoch7db26342009-06-03 18:21:19 +01003428
Steve Block2bc69912009-07-30 14:45:13 +01003429 /**
3430 * Instructs the browser to show a prompt to ask the user to set the
3431 * Geolocation permission state for the specified origin.
3432 * @param origin The origin for which Geolocation permissions are
3433 * requested.
3434 * @param callback The callback to call once the user has set the
3435 * Geolocation permission state.
3436 */
3437 @Override
3438 public void onGeolocationPermissionsShowPrompt(String origin,
3439 GeolocationPermissions.Callback callback) {
3440 mTabControl.getCurrentTab().getGeolocationPermissionsPrompt().show(
3441 origin, callback);
3442 }
3443
3444 /**
3445 * Instructs the browser to hide the Geolocation permissions prompt.
3446 */
3447 @Override
3448 public void onGeolocationPermissionsHidePrompt() {
3449 mTabControl.getCurrentTab().getGeolocationPermissionsPrompt().hide();
3450 }
3451
Ben Murdoch7db26342009-06-03 18:21:19 +01003452 /* Adds a JavaScript error message to the system log.
3453 * @param message The error message to report.
3454 * @param lineNumber The line number of the error.
3455 * @param sourceID The name of the source file that caused the error.
3456 */
3457 @Override
3458 public void addMessageToConsole(String message, int lineNumber, String sourceID) {
Ben Murdochbff2d602009-07-01 20:19:05 +01003459 ErrorConsoleView errorConsole = mTabControl.getCurrentErrorConsole(true);
3460 errorConsole.addErrorMessage(message, sourceID, lineNumber);
3461 if (mShouldShowErrorConsole &&
3462 errorConsole.getShowState() != ErrorConsoleView.SHOW_MAXIMIZED) {
3463 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
3464 }
3465 Log.w(LOGTAG, "Console: " + message + " " + sourceID + ":" + lineNumber);
Ben Murdoch7db26342009-06-03 18:21:19 +01003466 }
Andrei Popescu540035d2009-09-18 18:59:20 +01003467
3468 /**
3469 * Ask the browser for an icon to represent a <video> element.
3470 * This icon will be used if the Web page did not specify a poster attribute.
3471 *
3472 * @return Bitmap The icon or null if no such icon is available.
3473 * @hide pending API Council approval
3474 */
3475 @Override
3476 public Bitmap getDefaultVideoPoster() {
3477 if (mDefaultVideoPoster == null) {
3478 mDefaultVideoPoster = BitmapFactory.decodeResource(
3479 getResources(), R.drawable.default_video_poster);
3480 }
3481 return mDefaultVideoPoster;
3482 }
3483
3484 /**
3485 * Ask the host application for a custom progress view to show while
3486 * a <video> is loading.
3487 *
3488 * @return View The progress view.
3489 * @hide pending API Council approval
3490 */
3491 @Override
3492 public View getVideoLoadingProgressView() {
3493 if (mVideoProgressView == null) {
3494 LayoutInflater inflater = LayoutInflater.from(BrowserActivity.this);
3495 mVideoProgressView = inflater.inflate(R.layout.video_loading_progress, null);
3496 }
3497 return mVideoProgressView;
3498 }
Leon Clarkecb6cc862009-09-29 18:35:13 +01003499
3500 /**
3501 * Deliver a list of already-visited URLs
3502 * @hide pending API Council approval
3503 */
3504 @Override
3505 public void getVisitedHistory(final ValueCallback<String[]> callback) {
3506 AsyncTask<Void, Void, String[]> task = new AsyncTask<Void, Void, String[]>() {
3507 public String[] doInBackground(Void... unused) {
3508 return Browser.getVisitedHistory(getContentResolver());
3509 }
3510
3511 public void onPostExecute(String[] result) {
3512 callback.onReceiveValue(result);
3513
3514 };
3515 };
3516 task.execute();
3517 };
The Android Open Source Project0c908882009-03-03 19:32:16 -08003518 };
3519
3520 /**
3521 * Notify the host application a download should be done, or that
3522 * the data should be streamed if a streaming viewer is available.
3523 * @param url The full url to the content that should be downloaded
3524 * @param contentDisposition Content-disposition http header, if
3525 * present.
3526 * @param mimetype The mimetype of the content reported by the server
3527 * @param contentLength The file size reported by the server
3528 */
3529 public void onDownloadStart(String url, String userAgent,
3530 String contentDisposition, String mimetype, long contentLength) {
3531 // if we're dealing wih A/V content that's not explicitly marked
3532 // for download, check if it's streamable.
3533 if (contentDisposition == null
Patrick Scotte1fb9662009-08-31 14:31:52 -04003534 || !contentDisposition.regionMatches(
3535 true, 0, "attachment", 0, 10)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003536 // query the package manager to see if there's a registered handler
3537 // that matches.
3538 Intent intent = new Intent(Intent.ACTION_VIEW);
3539 intent.setDataAndType(Uri.parse(url), mimetype);
Patrick Scotte1fb9662009-08-31 14:31:52 -04003540 ResolveInfo info = getPackageManager().resolveActivity(intent,
3541 PackageManager.MATCH_DEFAULT_ONLY);
3542 if (info != null) {
3543 ComponentName myName = getComponentName();
3544 // If we resolved to ourselves, we don't want to attempt to
3545 // load the url only to try and download it again.
3546 if (!myName.getPackageName().equals(
3547 info.activityInfo.packageName)
3548 || !myName.getClassName().equals(
3549 info.activityInfo.name)) {
3550 // someone (other than us) knows how to handle this mime
3551 // type with this scheme, don't download.
3552 try {
3553 startActivity(intent);
3554 return;
3555 } catch (ActivityNotFoundException ex) {
3556 if (LOGD_ENABLED) {
3557 Log.d(LOGTAG, "activity not found for " + mimetype
3558 + " over " + Uri.parse(url).getScheme(),
3559 ex);
3560 }
3561 // Best behavior is to fall back to a download in this
3562 // case
The Android Open Source Project0c908882009-03-03 19:32:16 -08003563 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003564 }
3565 }
3566 }
3567 onDownloadStartNoStream(url, userAgent, contentDisposition, mimetype, contentLength);
3568 }
3569
3570 /**
3571 * Notify the host application a download should be done, even if there
3572 * is a streaming viewer available for thise type.
3573 * @param url The full url to the content that should be downloaded
3574 * @param contentDisposition Content-disposition http header, if
3575 * present.
3576 * @param mimetype The mimetype of the content reported by the server
3577 * @param contentLength The file size reported by the server
3578 */
3579 /*package */ void onDownloadStartNoStream(String url, String userAgent,
3580 String contentDisposition, String mimetype, long contentLength) {
3581
3582 String filename = URLUtil.guessFileName(url,
3583 contentDisposition, mimetype);
3584
3585 // Check to see if we have an SDCard
3586 String status = Environment.getExternalStorageState();
3587 if (!status.equals(Environment.MEDIA_MOUNTED)) {
3588 int title;
3589 String msg;
3590
3591 // Check to see if the SDCard is busy, same as the music app
3592 if (status.equals(Environment.MEDIA_SHARED)) {
3593 msg = getString(R.string.download_sdcard_busy_dlg_msg);
3594 title = R.string.download_sdcard_busy_dlg_title;
3595 } else {
3596 msg = getString(R.string.download_no_sdcard_dlg_msg, filename);
3597 title = R.string.download_no_sdcard_dlg_title;
3598 }
3599
3600 new AlertDialog.Builder(this)
3601 .setTitle(title)
3602 .setIcon(android.R.drawable.ic_dialog_alert)
3603 .setMessage(msg)
3604 .setPositiveButton(R.string.ok, null)
3605 .show();
3606 return;
3607 }
3608
3609 // java.net.URI is a lot stricter than KURL so we have to undo
3610 // KURL's percent-encoding and redo the encoding using java.net.URI.
3611 URI uri = null;
3612 try {
3613 // Undo the percent-encoding that KURL may have done.
3614 String newUrl = new String(URLUtil.decode(url.getBytes()));
3615 // Parse the url into pieces
3616 WebAddress w = new WebAddress(newUrl);
3617 String frag = null;
3618 String query = null;
3619 String path = w.mPath;
3620 // Break the path into path, query, and fragment
3621 if (path.length() > 0) {
3622 // Strip the fragment
3623 int idx = path.lastIndexOf('#');
3624 if (idx != -1) {
3625 frag = path.substring(idx + 1);
3626 path = path.substring(0, idx);
3627 }
3628 idx = path.lastIndexOf('?');
3629 if (idx != -1) {
3630 query = path.substring(idx + 1);
3631 path = path.substring(0, idx);
3632 }
3633 }
3634 uri = new URI(w.mScheme, w.mAuthInfo, w.mHost, w.mPort, path,
3635 query, frag);
3636 } catch (Exception e) {
3637 Log.e(LOGTAG, "Could not parse url for download: " + url, e);
3638 return;
3639 }
3640
3641 // XXX: Have to use the old url since the cookies were stored using the
3642 // old percent-encoded url.
3643 String cookies = CookieManager.getInstance().getCookie(url);
3644
3645 ContentValues values = new ContentValues();
Jean-Baptiste Queru3dc09b22009-03-31 16:49:44 -07003646 values.put(Downloads.COLUMN_URI, uri.toString());
3647 values.put(Downloads.COLUMN_COOKIE_DATA, cookies);
3648 values.put(Downloads.COLUMN_USER_AGENT, userAgent);
3649 values.put(Downloads.COLUMN_NOTIFICATION_PACKAGE,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003650 getPackageName());
Jean-Baptiste Queru3dc09b22009-03-31 16:49:44 -07003651 values.put(Downloads.COLUMN_NOTIFICATION_CLASS,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003652 BrowserDownloadPage.class.getCanonicalName());
Jean-Baptiste Queru3dc09b22009-03-31 16:49:44 -07003653 values.put(Downloads.COLUMN_VISIBILITY, Downloads.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
3654 values.put(Downloads.COLUMN_MIME_TYPE, mimetype);
3655 values.put(Downloads.COLUMN_FILE_NAME_HINT, filename);
3656 values.put(Downloads.COLUMN_DESCRIPTION, uri.getHost());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003657 if (contentLength > 0) {
Jean-Baptiste Queru3dc09b22009-03-31 16:49:44 -07003658 values.put(Downloads.COLUMN_TOTAL_BYTES, contentLength);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003659 }
3660 if (mimetype == null) {
3661 // We must have long pressed on a link or image to download it. We
3662 // are not sure of the mimetype in this case, so do a head request
3663 new FetchUrlMimeType(this).execute(values);
3664 } else {
3665 final Uri contentUri =
3666 getContentResolver().insert(Downloads.CONTENT_URI, values);
3667 viewDownloads(contentUri);
3668 }
3669
3670 }
3671
3672 /**
3673 * Resets the lock icon. This method is called when we start a new load and
3674 * know the url to be loaded.
3675 */
3676 private void resetLockIcon(String url) {
3677 // Save the lock-icon state (we revert to it if the load gets cancelled)
3678 saveLockIcon();
3679
3680 mLockIconType = LOCK_ICON_UNSECURE;
3681 if (URLUtil.isHttpsUrl(url)) {
3682 mLockIconType = LOCK_ICON_SECURE;
Dave Bort31a6d1c2009-04-13 15:56:49 -07003683 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003684 Log.v(LOGTAG, "BrowserActivity.resetLockIcon:" +
3685 " reset lock icon to " + mLockIconType);
3686 }
3687 }
3688
3689 updateLockIconImage(LOCK_ICON_UNSECURE);
3690 }
3691
Grace Klobaeb6eef42009-09-15 17:56:32 -07003692 /* package */ void setLockIconType(int type) {
3693 mLockIconType = type;
3694 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003695
Grace Klobaeb6eef42009-09-15 17:56:32 -07003696 /* package */ int getLockIconType() {
3697 return mLockIconType;
3698 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003699
Grace Klobaeb6eef42009-09-15 17:56:32 -07003700 /* package */ void setPrevLockType(int type) {
3701 mPrevLockType = type;
3702 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003703
Grace Klobaeb6eef42009-09-15 17:56:32 -07003704 /* package */ int getPrevLockType() {
3705 return mPrevLockType;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003706 }
3707
3708 /**
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04003709 * Update the lock icon to correspond to our latest state.
3710 */
3711 /* package */ void updateLockIconToLatest() {
3712 updateLockIconImage(mLockIconType);
3713 }
3714
3715 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08003716 * Updates the lock-icon image in the title-bar.
3717 */
3718 private void updateLockIconImage(int lockIconType) {
3719 Drawable d = null;
3720 if (lockIconType == LOCK_ICON_SECURE) {
3721 d = mSecLockIcon;
3722 } else if (lockIconType == LOCK_ICON_MIXED) {
3723 d = mMixLockIcon;
3724 }
Leon Scroggins68579392009-09-15 15:31:54 -04003725 mTitleBar.setLock(d);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04003726 if (mFakeTitleBar != null) {
3727 mFakeTitleBar.setLock(d);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003728 }
3729 }
3730
3731 /**
3732 * Displays a page-info dialog.
3733 * @param tab The tab to show info about
3734 * @param fromShowSSLCertificateOnError The flag that indicates whether
3735 * this dialog was opened from the SSL-certificate-on-error dialog or
3736 * not. This is important, since we need to know whether to return to
3737 * the parent dialog or simply dismiss.
3738 */
3739 private void showPageInfo(final TabControl.Tab tab,
3740 final boolean fromShowSSLCertificateOnError) {
3741 final LayoutInflater factory = LayoutInflater
3742 .from(this);
3743
3744 final View pageInfoView = factory.inflate(R.layout.page_info, null);
3745
3746 final WebView view = tab.getWebView();
3747
3748 String url = null;
3749 String title = null;
3750
3751 if (view == null) {
3752 url = tab.getUrl();
3753 title = tab.getTitle();
3754 } else if (view == mTabControl.getCurrentWebView()) {
3755 // Use the cached title and url if this is the current WebView
3756 url = mUrl;
3757 title = mTitle;
3758 } else {
3759 url = view.getUrl();
3760 title = view.getTitle();
3761 }
3762
3763 if (url == null) {
3764 url = "";
3765 }
3766 if (title == null) {
3767 title = "";
3768 }
3769
3770 ((TextView) pageInfoView.findViewById(R.id.address)).setText(url);
3771 ((TextView) pageInfoView.findViewById(R.id.title)).setText(title);
3772
3773 mPageInfoView = tab;
3774 mPageInfoFromShowSSLCertificateOnError = new Boolean(fromShowSSLCertificateOnError);
3775
3776 AlertDialog.Builder alertDialogBuilder =
3777 new AlertDialog.Builder(this)
3778 .setTitle(R.string.page_info).setIcon(android.R.drawable.ic_dialog_info)
3779 .setView(pageInfoView)
3780 .setPositiveButton(
3781 R.string.ok,
3782 new DialogInterface.OnClickListener() {
3783 public void onClick(DialogInterface dialog,
3784 int whichButton) {
3785 mPageInfoDialog = null;
3786 mPageInfoView = null;
3787 mPageInfoFromShowSSLCertificateOnError = null;
3788
3789 // if we came here from the SSL error dialog
3790 if (fromShowSSLCertificateOnError) {
3791 // go back to the SSL error dialog
3792 showSSLCertificateOnError(
3793 mSSLCertificateOnErrorView,
3794 mSSLCertificateOnErrorHandler,
3795 mSSLCertificateOnErrorError);
3796 }
3797 }
3798 })
3799 .setOnCancelListener(
3800 new DialogInterface.OnCancelListener() {
3801 public void onCancel(DialogInterface dialog) {
3802 mPageInfoDialog = null;
3803 mPageInfoView = null;
3804 mPageInfoFromShowSSLCertificateOnError = null;
3805
3806 // if we came here from the SSL error dialog
3807 if (fromShowSSLCertificateOnError) {
3808 // go back to the SSL error dialog
3809 showSSLCertificateOnError(
3810 mSSLCertificateOnErrorView,
3811 mSSLCertificateOnErrorHandler,
3812 mSSLCertificateOnErrorError);
3813 }
3814 }
3815 });
3816
3817 // if we have a main top-level page SSL certificate set or a certificate
3818 // error
3819 if (fromShowSSLCertificateOnError ||
3820 (view != null && view.getCertificate() != null)) {
3821 // add a 'View Certificate' button
3822 alertDialogBuilder.setNeutralButton(
3823 R.string.view_certificate,
3824 new DialogInterface.OnClickListener() {
3825 public void onClick(DialogInterface dialog,
3826 int whichButton) {
3827 mPageInfoDialog = null;
3828 mPageInfoView = null;
3829 mPageInfoFromShowSSLCertificateOnError = null;
3830
3831 // if we came here from the SSL error dialog
3832 if (fromShowSSLCertificateOnError) {
3833 // go back to the SSL error dialog
3834 showSSLCertificateOnError(
3835 mSSLCertificateOnErrorView,
3836 mSSLCertificateOnErrorHandler,
3837 mSSLCertificateOnErrorError);
3838 } else {
3839 // otherwise, display the top-most certificate from
3840 // the chain
3841 if (view.getCertificate() != null) {
3842 showSSLCertificate(tab);
3843 }
3844 }
3845 }
3846 });
3847 }
3848
3849 mPageInfoDialog = alertDialogBuilder.show();
3850 }
3851
3852 /**
3853 * Displays the main top-level page SSL certificate dialog
3854 * (accessible from the Page-Info dialog).
3855 * @param tab The tab to show certificate for.
3856 */
3857 private void showSSLCertificate(final TabControl.Tab tab) {
3858 final View certificateView =
3859 inflateCertificateView(tab.getWebView().getCertificate());
3860 if (certificateView == null) {
3861 return;
3862 }
3863
3864 LayoutInflater factory = LayoutInflater.from(this);
3865
3866 final LinearLayout placeholder =
3867 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3868
3869 LinearLayout ll = (LinearLayout) factory.inflate(
3870 R.layout.ssl_success, placeholder);
3871 ((TextView)ll.findViewById(R.id.success))
3872 .setText(R.string.ssl_certificate_is_valid);
3873
3874 mSSLCertificateView = tab;
3875 mSSLCertificateDialog =
3876 new AlertDialog.Builder(this)
3877 .setTitle(R.string.ssl_certificate).setIcon(
3878 R.drawable.ic_dialog_browser_certificate_secure)
3879 .setView(certificateView)
3880 .setPositiveButton(R.string.ok,
3881 new DialogInterface.OnClickListener() {
3882 public void onClick(DialogInterface dialog,
3883 int whichButton) {
3884 mSSLCertificateDialog = null;
3885 mSSLCertificateView = null;
3886
3887 showPageInfo(tab, false);
3888 }
3889 })
3890 .setOnCancelListener(
3891 new DialogInterface.OnCancelListener() {
3892 public void onCancel(DialogInterface dialog) {
3893 mSSLCertificateDialog = null;
3894 mSSLCertificateView = null;
3895
3896 showPageInfo(tab, false);
3897 }
3898 })
3899 .show();
3900 }
3901
3902 /**
3903 * Displays the SSL error certificate dialog.
3904 * @param view The target web-view.
3905 * @param handler The SSL error handler responsible for cancelling the
3906 * connection that resulted in an SSL error or proceeding per user request.
3907 * @param error The SSL error object.
3908 */
3909 private void showSSLCertificateOnError(
3910 final WebView view, final SslErrorHandler handler, final SslError error) {
3911
3912 final View certificateView =
3913 inflateCertificateView(error.getCertificate());
3914 if (certificateView == null) {
3915 return;
3916 }
3917
3918 LayoutInflater factory = LayoutInflater.from(this);
3919
3920 final LinearLayout placeholder =
3921 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3922
3923 if (error.hasError(SslError.SSL_UNTRUSTED)) {
3924 LinearLayout ll = (LinearLayout)factory
3925 .inflate(R.layout.ssl_warning, placeholder);
3926 ((TextView)ll.findViewById(R.id.warning))
3927 .setText(R.string.ssl_untrusted);
3928 }
3929
3930 if (error.hasError(SslError.SSL_IDMISMATCH)) {
3931 LinearLayout ll = (LinearLayout)factory
3932 .inflate(R.layout.ssl_warning, placeholder);
3933 ((TextView)ll.findViewById(R.id.warning))
3934 .setText(R.string.ssl_mismatch);
3935 }
3936
3937 if (error.hasError(SslError.SSL_EXPIRED)) {
3938 LinearLayout ll = (LinearLayout)factory
3939 .inflate(R.layout.ssl_warning, placeholder);
3940 ((TextView)ll.findViewById(R.id.warning))
3941 .setText(R.string.ssl_expired);
3942 }
3943
3944 if (error.hasError(SslError.SSL_NOTYETVALID)) {
3945 LinearLayout ll = (LinearLayout)factory
3946 .inflate(R.layout.ssl_warning, placeholder);
3947 ((TextView)ll.findViewById(R.id.warning))
3948 .setText(R.string.ssl_not_yet_valid);
3949 }
3950
3951 mSSLCertificateOnErrorHandler = handler;
3952 mSSLCertificateOnErrorView = view;
3953 mSSLCertificateOnErrorError = error;
3954 mSSLCertificateOnErrorDialog =
3955 new AlertDialog.Builder(this)
3956 .setTitle(R.string.ssl_certificate).setIcon(
3957 R.drawable.ic_dialog_browser_certificate_partially_secure)
3958 .setView(certificateView)
3959 .setPositiveButton(R.string.ok,
3960 new DialogInterface.OnClickListener() {
3961 public void onClick(DialogInterface dialog,
3962 int whichButton) {
3963 mSSLCertificateOnErrorDialog = null;
3964 mSSLCertificateOnErrorView = null;
3965 mSSLCertificateOnErrorHandler = null;
3966 mSSLCertificateOnErrorError = null;
3967
3968 mWebViewClient.onReceivedSslError(
3969 view, handler, error);
3970 }
3971 })
3972 .setNeutralButton(R.string.page_info_view,
3973 new DialogInterface.OnClickListener() {
3974 public void onClick(DialogInterface dialog,
3975 int whichButton) {
3976 mSSLCertificateOnErrorDialog = null;
3977
3978 // do not clear the dialog state: we will
3979 // need to show the dialog again once the
3980 // user is done exploring the page-info details
3981
3982 showPageInfo(mTabControl.getTabFromView(view),
3983 true);
3984 }
3985 })
3986 .setOnCancelListener(
3987 new DialogInterface.OnCancelListener() {
3988 public void onCancel(DialogInterface dialog) {
3989 mSSLCertificateOnErrorDialog = null;
3990 mSSLCertificateOnErrorView = null;
3991 mSSLCertificateOnErrorHandler = null;
3992 mSSLCertificateOnErrorError = null;
3993
3994 mWebViewClient.onReceivedSslError(
3995 view, handler, error);
3996 }
3997 })
3998 .show();
3999 }
4000
4001 /**
4002 * Inflates the SSL certificate view (helper method).
4003 * @param certificate The SSL certificate.
4004 * @return The resultant certificate view with issued-to, issued-by,
4005 * issued-on, expires-on, and possibly other fields set.
4006 * If the input certificate is null, returns null.
4007 */
4008 private View inflateCertificateView(SslCertificate certificate) {
4009 if (certificate == null) {
4010 return null;
4011 }
4012
4013 LayoutInflater factory = LayoutInflater.from(this);
4014
4015 View certificateView = factory.inflate(
4016 R.layout.ssl_certificate, null);
4017
4018 // issued to:
4019 SslCertificate.DName issuedTo = certificate.getIssuedTo();
4020 if (issuedTo != null) {
4021 ((TextView) certificateView.findViewById(R.id.to_common))
4022 .setText(issuedTo.getCName());
4023 ((TextView) certificateView.findViewById(R.id.to_org))
4024 .setText(issuedTo.getOName());
4025 ((TextView) certificateView.findViewById(R.id.to_org_unit))
4026 .setText(issuedTo.getUName());
4027 }
4028
4029 // issued by:
4030 SslCertificate.DName issuedBy = certificate.getIssuedBy();
4031 if (issuedBy != null) {
4032 ((TextView) certificateView.findViewById(R.id.by_common))
4033 .setText(issuedBy.getCName());
4034 ((TextView) certificateView.findViewById(R.id.by_org))
4035 .setText(issuedBy.getOName());
4036 ((TextView) certificateView.findViewById(R.id.by_org_unit))
4037 .setText(issuedBy.getUName());
4038 }
4039
4040 // issued on:
4041 String issuedOn = reformatCertificateDate(
4042 certificate.getValidNotBefore());
4043 ((TextView) certificateView.findViewById(R.id.issued_on))
4044 .setText(issuedOn);
4045
4046 // expires on:
4047 String expiresOn = reformatCertificateDate(
4048 certificate.getValidNotAfter());
4049 ((TextView) certificateView.findViewById(R.id.expires_on))
4050 .setText(expiresOn);
4051
4052 return certificateView;
4053 }
4054
4055 /**
4056 * Re-formats the certificate date (Date.toString()) string to
4057 * a properly localized date string.
4058 * @return Properly localized version of the certificate date string and
4059 * the original certificate date string if fails to localize.
4060 * If the original string is null, returns an empty string "".
4061 */
4062 private String reformatCertificateDate(String certificateDate) {
4063 String reformattedDate = null;
4064
4065 if (certificateDate != null) {
4066 Date date = null;
4067 try {
4068 date = java.text.DateFormat.getInstance().parse(certificateDate);
4069 } catch (ParseException e) {
4070 date = null;
4071 }
4072
4073 if (date != null) {
4074 reformattedDate =
4075 DateFormat.getDateFormat(this).format(date);
4076 }
4077 }
4078
4079 return reformattedDate != null ? reformattedDate :
4080 (certificateDate != null ? certificateDate : "");
4081 }
4082
4083 /**
4084 * Displays an http-authentication dialog.
4085 */
4086 private void showHttpAuthentication(final HttpAuthHandler handler,
4087 final String host, final String realm, final String title,
4088 final String name, final String password, int focusId) {
4089 LayoutInflater factory = LayoutInflater.from(this);
4090 final View v = factory
4091 .inflate(R.layout.http_authentication, null);
4092 if (name != null) {
4093 ((EditText) v.findViewById(R.id.username_edit)).setText(name);
4094 }
4095 if (password != null) {
4096 ((EditText) v.findViewById(R.id.password_edit)).setText(password);
4097 }
4098
4099 String titleText = title;
4100 if (titleText == null) {
4101 titleText = getText(R.string.sign_in_to).toString().replace(
4102 "%s1", host).replace("%s2", realm);
4103 }
4104
4105 mHttpAuthHandler = handler;
4106 AlertDialog dialog = new AlertDialog.Builder(this)
4107 .setTitle(titleText)
4108 .setIcon(android.R.drawable.ic_dialog_alert)
4109 .setView(v)
4110 .setPositiveButton(R.string.action,
4111 new DialogInterface.OnClickListener() {
4112 public void onClick(DialogInterface dialog,
4113 int whichButton) {
4114 String nm = ((EditText) v
4115 .findViewById(R.id.username_edit))
4116 .getText().toString();
4117 String pw = ((EditText) v
4118 .findViewById(R.id.password_edit))
4119 .getText().toString();
4120 BrowserActivity.this.setHttpAuthUsernamePassword
4121 (host, realm, nm, pw);
4122 handler.proceed(nm, pw);
4123 mHttpAuthenticationDialog = null;
4124 mHttpAuthHandler = null;
4125 }})
4126 .setNegativeButton(R.string.cancel,
4127 new DialogInterface.OnClickListener() {
4128 public void onClick(DialogInterface dialog,
4129 int whichButton) {
4130 handler.cancel();
4131 BrowserActivity.this.resetTitleAndRevertLockIcon();
4132 mHttpAuthenticationDialog = null;
4133 mHttpAuthHandler = null;
4134 }})
4135 .setOnCancelListener(new DialogInterface.OnCancelListener() {
4136 public void onCancel(DialogInterface dialog) {
4137 handler.cancel();
4138 BrowserActivity.this.resetTitleAndRevertLockIcon();
4139 mHttpAuthenticationDialog = null;
4140 mHttpAuthHandler = null;
4141 }})
4142 .create();
4143 // Make the IME appear when the dialog is displayed if applicable.
4144 dialog.getWindow().setSoftInputMode(
4145 WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
4146 dialog.show();
4147 if (focusId != 0) {
4148 dialog.findViewById(focusId).requestFocus();
4149 } else {
4150 v.findViewById(R.id.username_edit).requestFocus();
4151 }
4152 mHttpAuthenticationDialog = dialog;
4153 }
4154
4155 public int getProgress() {
4156 WebView w = mTabControl.getCurrentWebView();
4157 if (w != null) {
4158 return w.getProgress();
4159 } else {
4160 return 100;
4161 }
4162 }
4163
4164 /**
4165 * Set HTTP authentication password.
4166 *
4167 * @param host The host for the password
4168 * @param realm The realm for the password
4169 * @param username The username for the password. If it is null, it means
4170 * password can't be saved.
4171 * @param password The password
4172 */
4173 public void setHttpAuthUsernamePassword(String host, String realm,
4174 String username,
4175 String password) {
4176 WebView w = mTabControl.getCurrentWebView();
4177 if (w != null) {
4178 w.setHttpAuthUsernamePassword(host, realm, username, password);
4179 }
4180 }
4181
4182 /**
4183 * connectivity manager says net has come or gone... inform the user
4184 * @param up true if net has come up, false if net has gone down
4185 */
4186 public void onNetworkToggle(boolean up) {
4187 if (up == mIsNetworkUp) {
4188 return;
4189 } else if (up) {
4190 mIsNetworkUp = true;
4191 if (mAlertDialog != null) {
4192 mAlertDialog.cancel();
4193 mAlertDialog = null;
4194 }
4195 } else {
4196 mIsNetworkUp = false;
Patrick Scotteb6ab2a2009-09-16 10:00:17 -04004197 if (mInLoad) {
4198 createAndShowNetworkDialog();
4199 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08004200 }
4201 WebView w = mTabControl.getCurrentWebView();
4202 if (w != null) {
4203 w.setNetworkAvailable(up);
4204 }
4205 }
4206
Patrick Scotteb6ab2a2009-09-16 10:00:17 -04004207 // This method shows the network dialog alerting the user that the net is
4208 // down. It will only show the dialog if mAlertDialog is null.
4209 private void createAndShowNetworkDialog() {
4210 if (mAlertDialog == null) {
4211 mAlertDialog = new AlertDialog.Builder(this)
4212 .setTitle(R.string.loadSuspendedTitle)
4213 .setMessage(R.string.loadSuspended)
4214 .setPositiveButton(R.string.ok, null)
4215 .show();
4216 }
4217 }
4218
The Android Open Source Project0c908882009-03-03 19:32:16 -08004219 @Override
4220 protected void onActivityResult(int requestCode, int resultCode,
4221 Intent intent) {
4222 switch (requestCode) {
4223 case COMBO_PAGE:
4224 if (resultCode == RESULT_OK && intent != null) {
4225 String data = intent.getAction();
4226 Bundle extras = intent.getExtras();
4227 if (extras != null && extras.getBoolean("new_window", false)) {
Leon Scroggins25d35472009-09-15 11:37:27 -04004228 openTab(data);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004229 } else {
4230 final TabControl.Tab currentTab =
4231 mTabControl.getCurrentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04004232 dismissSubWindow(currentTab);
4233 if (data != null && data.length() != 0) {
4234 getTopWindow().loadUrl(data);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004235 }
4236 }
4237 }
4238 break;
4239 default:
4240 break;
4241 }
Leon Scroggins30444232009-09-04 18:36:20 -04004242 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08004243 }
4244
4245 /*
4246 * This method is called as a result of the user selecting the options
4247 * menu to see the download window, or when a download changes state. It
4248 * shows the download window ontop of the current window.
4249 */
4250 /* package */ void viewDownloads(Uri downloadRecord) {
4251 Intent intent = new Intent(this,
4252 BrowserDownloadPage.class);
4253 intent.setData(downloadRecord);
4254 startActivityForResult(intent, this.DOWNLOAD_PAGE);
4255
4256 }
4257
Leon Scroggins160a7e72009-08-14 18:28:01 -04004258 /**
4259 * Open the Go page.
4260 * @param startWithHistory If true, open starting on the history tab.
4261 * Otherwise, start with the bookmarks tab.
Leon Scroggins160a7e72009-08-14 18:28:01 -04004262 */
Leon Scroggins30444232009-09-04 18:36:20 -04004263 /* package */ void bookmarksOrHistoryPicker(boolean startWithHistory) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08004264 WebView current = mTabControl.getCurrentWebView();
4265 if (current == null) {
4266 return;
4267 }
4268 Intent intent = new Intent(this,
4269 CombinedBookmarkHistoryActivity.class);
4270 String title = current.getTitle();
4271 String url = current.getUrl();
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01004272 Bitmap thumbnail = createScreenshot(current);
4273
The Android Open Source Project0c908882009-03-03 19:32:16 -08004274 // Just in case the user opens bookmarks before a page finishes loading
4275 // so the current history item, and therefore the page, is null.
4276 if (null == url) {
4277 url = mLastEnteredUrl;
4278 // This can happen.
4279 if (null == url) {
4280 url = mSettings.getHomePage();
4281 }
4282 }
4283 // In case the web page has not yet received its associated title.
4284 if (title == null) {
4285 title = url;
4286 }
4287 intent.putExtra("title", title);
4288 intent.putExtra("url", url);
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01004289 intent.putExtra("thumbnail", thumbnail);
Leon Scroggins30444232009-09-04 18:36:20 -04004290 // Disable opening in a new window if we have maxed out the windows
4291 intent.putExtra("disable_new_window", mTabControl.getTabCount()
4292 >= TabControl.MAX_TABS);
Patrick Scott3918d442009-08-04 13:22:29 -04004293 intent.putExtra("touch_icon_url", current.getTouchIconUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08004294 if (startWithHistory) {
4295 intent.putExtra(CombinedBookmarkHistoryActivity.STARTING_TAB,
4296 CombinedBookmarkHistoryActivity.HISTORY_TAB);
4297 }
4298 startActivityForResult(intent, COMBO_PAGE);
4299 }
4300
4301 // Called when loading from context menu or LOAD_URL message
4302 private void loadURL(WebView view, String url) {
4303 // In case the user enters nothing.
4304 if (url != null && url.length() != 0 && view != null) {
4305 url = smartUrlFilter(url);
4306 if (!mWebViewClient.shouldOverrideUrlLoading(view, url)) {
4307 view.loadUrl(url);
4308 }
4309 }
4310 }
4311
The Android Open Source Project0c908882009-03-03 19:32:16 -08004312 private String smartUrlFilter(Uri inUri) {
4313 if (inUri != null) {
4314 return smartUrlFilter(inUri.toString());
4315 }
4316 return null;
4317 }
4318
4319
4320 // get window count
4321
4322 int getWindowCount(){
4323 if(mTabControl != null){
4324 return mTabControl.getTabCount();
4325 }
4326 return 0;
4327 }
4328
Feng Qianb34f87a2009-03-24 21:27:26 -07004329 protected static final Pattern ACCEPTED_URI_SCHEMA = Pattern.compile(
The Android Open Source Project0c908882009-03-03 19:32:16 -08004330 "(?i)" + // switch on case insensitive matching
4331 "(" + // begin group for schema
4332 "(?:http|https|file):\\/\\/" +
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004333 "|(?:inline|data|about|content|javascript):" +
The Android Open Source Project0c908882009-03-03 19:32:16 -08004334 ")" +
4335 "(.*)" );
4336
4337 /**
4338 * Attempts to determine whether user input is a URL or search
4339 * terms. Anything with a space is passed to search.
4340 *
4341 * Converts to lowercase any mistakenly uppercased schema (i.e.,
4342 * "Http://" converts to "http://"
4343 *
4344 * @return Original or modified URL
4345 *
4346 */
4347 String smartUrlFilter(String url) {
4348
4349 String inUrl = url.trim();
4350 boolean hasSpace = inUrl.indexOf(' ') != -1;
4351
4352 Matcher matcher = ACCEPTED_URI_SCHEMA.matcher(inUrl);
4353 if (matcher.matches()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08004354 // force scheme to lowercase
4355 String scheme = matcher.group(1);
4356 String lcScheme = scheme.toLowerCase();
4357 if (!lcScheme.equals(scheme)) {
Mitsuru Oshima123ecfb2009-05-18 19:11:14 -07004358 inUrl = lcScheme + matcher.group(2);
4359 }
4360 if (hasSpace) {
4361 inUrl = inUrl.replace(" ", "%20");
The Android Open Source Project0c908882009-03-03 19:32:16 -08004362 }
4363 return inUrl;
4364 }
4365 if (hasSpace) {
Satish Sampath565505b2009-05-29 15:37:27 +01004366 // FIXME: Is this the correct place to add to searches?
4367 // what if someone else calls this function?
4368 int shortcut = parseUrlShortcut(inUrl);
4369 if (shortcut != SHORTCUT_INVALID) {
4370 Browser.addSearchUrl(mResolver, inUrl);
4371 String query = inUrl.substring(2);
4372 switch (shortcut) {
4373 case SHORTCUT_GOOGLE_SEARCH:
Grace Kloba47fdfdb2009-06-30 11:15:34 -07004374 return URLUtil.composeSearchUrl(query, QuickSearch_G, QUERY_PLACE_HOLDER);
Satish Sampath565505b2009-05-29 15:37:27 +01004375 case SHORTCUT_WIKIPEDIA_SEARCH:
4376 return URLUtil.composeSearchUrl(query, QuickSearch_W, QUERY_PLACE_HOLDER);
4377 case SHORTCUT_DICTIONARY_SEARCH:
4378 return URLUtil.composeSearchUrl(query, QuickSearch_D, QUERY_PLACE_HOLDER);
4379 case SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH:
The Android Open Source Project0c908882009-03-03 19:32:16 -08004380 // FIXME: we need location in this case
Satish Sampath565505b2009-05-29 15:37:27 +01004381 return URLUtil.composeSearchUrl(query, QuickSearch_L, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004382 }
4383 }
4384 } else {
4385 if (Regex.WEB_URL_PATTERN.matcher(inUrl).matches()) {
4386 return URLUtil.guessUrl(inUrl);
4387 }
4388 }
4389
4390 Browser.addSearchUrl(mResolver, inUrl);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07004391 return URLUtil.composeSearchUrl(inUrl, QuickSearch_G, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004392 }
4393
Ben Murdochbff2d602009-07-01 20:19:05 +01004394 /* package */ void setShouldShowErrorConsole(boolean flag) {
4395 if (flag == mShouldShowErrorConsole) {
4396 // Nothing to do.
4397 return;
4398 }
4399
4400 mShouldShowErrorConsole = flag;
4401
4402 ErrorConsoleView errorConsole = mTabControl.getCurrentErrorConsole(true);
4403
4404 if (flag) {
4405 // Setting the show state of the console will cause it's the layout to be inflated.
4406 if (errorConsole.numberOfErrors() > 0) {
4407 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
4408 } else {
4409 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
4410 }
4411
4412 // Now we can add it to the main view.
4413 mErrorConsoleContainer.addView(errorConsole,
4414 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
4415 ViewGroup.LayoutParams.WRAP_CONTENT));
4416 } else {
4417 mErrorConsoleContainer.removeView(errorConsole);
4418 }
4419
4420 }
4421
Grace Klobaeb6eef42009-09-15 17:56:32 -07004422 final static int LOCK_ICON_UNSECURE = 0;
4423 final static int LOCK_ICON_SECURE = 1;
4424 final static int LOCK_ICON_MIXED = 2;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004425
4426 private int mLockIconType = LOCK_ICON_UNSECURE;
4427 private int mPrevLockType = LOCK_ICON_UNSECURE;
4428
4429 private BrowserSettings mSettings;
4430 private TabControl mTabControl;
4431 private ContentResolver mResolver;
4432 private FrameLayout mContentView;
Andrei Popescuadc008d2009-06-26 14:11:30 +01004433 private View mCustomView;
4434 private FrameLayout mCustomViewContainer;
Andrei Popescuc9b55562009-07-07 10:51:15 +01004435 private WebChromeClient.CustomViewCallback mCustomViewCallback;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004436
4437 // FIXME, temp address onPrepareMenu performance problem. When we move everything out of
4438 // view, we should rewrite this.
4439 private int mCurrentMenuState = 0;
4440 private int mMenuState = R.id.MAIN_MENU;
Andrei Popescuadc008d2009-06-26 14:11:30 +01004441 private int mOldMenuState = EMPTY_MENU;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004442 private static final int EMPTY_MENU = -1;
4443 private Menu mMenu;
4444
4445 private FindDialog mFindDialog;
4446 // Used to prevent chording to result in firing two shortcuts immediately
4447 // one after another. Fixes bug 1211714.
4448 boolean mCanChord;
4449
4450 private boolean mInLoad;
4451 private boolean mIsNetworkUp;
Ben Murdochb7cc8b42009-09-28 10:59:09 +01004452 private boolean mDidStopLoad;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004453
4454 private boolean mPageStarted;
4455 private boolean mActivityInPause = true;
4456
4457 private boolean mMenuIsDown;
4458
The Android Open Source Project0c908882009-03-03 19:32:16 -08004459 private static boolean mInTrace;
4460
4461 // Performance probe
4462 private static final int[] SYSTEM_CPU_FORMAT = new int[] {
4463 Process.PROC_SPACE_TERM | Process.PROC_COMBINE,
4464 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 1: user time
4465 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 2: nice time
4466 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 3: sys time
4467 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 4: idle time
4468 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 5: iowait time
4469 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 6: irq time
4470 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG // 7: softirq time
4471 };
4472
4473 private long mStart;
4474 private long mProcessStart;
4475 private long mUserStart;
4476 private long mSystemStart;
4477 private long mIdleStart;
4478 private long mIrqStart;
4479
4480 private long mUiStart;
4481
4482 private Drawable mMixLockIcon;
4483 private Drawable mSecLockIcon;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004484
4485 /* hold a ref so we can auto-cancel if necessary */
4486 private AlertDialog mAlertDialog;
4487
4488 // Wait for credentials before loading google.com
4489 private ProgressDialog mCredsDlg;
4490
4491 // The up-to-date URL and title (these can be different from those stored
4492 // in WebView, since it takes some time for the information in WebView to
4493 // get updated)
4494 private String mUrl;
4495 private String mTitle;
4496
4497 // As PageInfo has different style for landscape / portrait, we have
4498 // to re-open it when configuration changed
4499 private AlertDialog mPageInfoDialog;
4500 private TabControl.Tab mPageInfoView;
4501 // If the Page-Info dialog is launched from the SSL-certificate-on-error
4502 // dialog, we should not just dismiss it, but should get back to the
4503 // SSL-certificate-on-error dialog. This flag is used to store this state
4504 private Boolean mPageInfoFromShowSSLCertificateOnError;
4505
4506 // as SSLCertificateOnError has different style for landscape / portrait,
4507 // we have to re-open it when configuration changed
4508 private AlertDialog mSSLCertificateOnErrorDialog;
4509 private WebView mSSLCertificateOnErrorView;
4510 private SslErrorHandler mSSLCertificateOnErrorHandler;
4511 private SslError mSSLCertificateOnErrorError;
4512
4513 // as SSLCertificate has different style for landscape / portrait, we
4514 // have to re-open it when configuration changed
4515 private AlertDialog mSSLCertificateDialog;
4516 private TabControl.Tab mSSLCertificateView;
4517
4518 // as HttpAuthentication has different style for landscape / portrait, we
4519 // have to re-open it when configuration changed
4520 private AlertDialog mHttpAuthenticationDialog;
4521 private HttpAuthHandler mHttpAuthHandler;
4522
4523 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_PARAMS =
4524 new FrameLayout.LayoutParams(
4525 ViewGroup.LayoutParams.FILL_PARENT,
4526 ViewGroup.LayoutParams.FILL_PARENT);
Andrei Popescuadc008d2009-06-26 14:11:30 +01004527 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_GRAVITY_CENTER =
4528 new FrameLayout.LayoutParams(
4529 ViewGroup.LayoutParams.FILL_PARENT,
4530 ViewGroup.LayoutParams.FILL_PARENT,
4531 Gravity.CENTER);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07004532 // Google search
4533 final static String QuickSearch_G = "http://www.google.com/m?q=%s";
The Android Open Source Project0c908882009-03-03 19:32:16 -08004534 // Wikipedia search
4535 final static String QuickSearch_W = "http://en.wikipedia.org/w/index.php?search=%s&go=Go";
4536 // Dictionary search
4537 final static String QuickSearch_D = "http://dictionary.reference.com/search?q=%s";
4538 // Google Mobile Local search
4539 final static String QuickSearch_L = "http://www.google.com/m/search?site=local&q=%s&near=mountain+view";
4540
4541 final static String QUERY_PLACE_HOLDER = "%s";
4542
4543 // "source" parameter for Google search through search key
4544 final static String GOOGLE_SEARCH_SOURCE_SEARCHKEY = "browser-key";
4545 // "source" parameter for Google search through goto menu
4546 final static String GOOGLE_SEARCH_SOURCE_GOTO = "browser-goto";
4547 // "source" parameter for Google search through simplily type
4548 final static String GOOGLE_SEARCH_SOURCE_TYPE = "browser-type";
4549 // "source" parameter for Google search suggested by the browser
4550 final static String GOOGLE_SEARCH_SOURCE_SUGGEST = "browser-suggest";
4551 // "source" parameter for Google search from unknown source
4552 final static String GOOGLE_SEARCH_SOURCE_UNKNOWN = "unknown";
4553
4554 private final static String LOGTAG = "browser";
4555
The Android Open Source Project0c908882009-03-03 19:32:16 -08004556 private String mLastEnteredUrl;
4557
4558 private PowerManager.WakeLock mWakeLock;
4559 private final static int WAKELOCK_TIMEOUT = 5 * 60 * 1000; // 5 minutes
4560
4561 private Toast mStopToast;
4562
Leon Scroggins68579392009-09-15 15:31:54 -04004563 private TitleBar mTitleBar;
Leon Scroggins81db3662009-06-04 17:45:11 -04004564
Ben Murdochbff2d602009-07-01 20:19:05 +01004565 private LinearLayout mErrorConsoleContainer = null;
4566 private boolean mShouldShowErrorConsole = false;
4567
The Android Open Source Project0c908882009-03-03 19:32:16 -08004568 // As the ids are dynamically created, we can't guarantee that they will
4569 // be in sequence, so this static array maps ids to a window number.
4570 final static private int[] WINDOW_SHORTCUT_ID_ARRAY =
4571 { R.id.window_one_menu_id, R.id.window_two_menu_id, R.id.window_three_menu_id,
4572 R.id.window_four_menu_id, R.id.window_five_menu_id, R.id.window_six_menu_id,
4573 R.id.window_seven_menu_id, R.id.window_eight_menu_id };
4574
4575 // monitor platform changes
4576 private IntentFilter mNetworkStateChangedFilter;
4577 private BroadcastReceiver mNetworkStateIntentReceiver;
4578
Grace Klobab4da0ad2009-05-14 14:45:40 -07004579 private BroadcastReceiver mPackageInstallationReceiver;
4580
Patrick Scott59ce8302009-09-18 16:29:38 -04004581 // AsyncTask for downloading touch icons
4582 /* package */ DownloadTouchIcon mTouchIconLoader;
4583
The Android Open Source Project0c908882009-03-03 19:32:16 -08004584 // activity requestCode
Nicolas Roard78a98e42009-05-11 13:34:17 +01004585 final static int COMBO_PAGE = 1;
4586 final static int DOWNLOAD_PAGE = 2;
4587 final static int PREFERENCES_PAGE = 3;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004588
Andrei Popescu540035d2009-09-18 18:59:20 +01004589 // the default <video> poster
4590 private Bitmap mDefaultVideoPoster;
4591 // the video progress view
4592 private View mVideoProgressView;
4593
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004594 /**
4595 * A UrlData class to abstract how the content will be set to WebView.
4596 * This base class uses loadUrl to show the content.
4597 */
4598 private static class UrlData {
4599 String mUrl;
Grace Kloba60e095c2009-06-16 11:50:55 -07004600 byte[] mPostData;
4601
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004602 UrlData(String url) {
4603 this.mUrl = url;
4604 }
Grace Kloba60e095c2009-06-16 11:50:55 -07004605
4606 void setPostData(byte[] postData) {
4607 mPostData = postData;
4608 }
4609
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004610 boolean isEmpty() {
4611 return mUrl == null || mUrl.length() == 0;
4612 }
4613
Mitsuru Oshima7944b7d2009-06-16 16:34:51 -07004614 public void loadIn(WebView webView) {
Grace Kloba60e095c2009-06-16 11:50:55 -07004615 if (mPostData != null) {
4616 webView.postUrl(mUrl, mPostData);
4617 } else {
4618 webView.loadUrl(mUrl);
4619 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004620 }
4621 };
4622
4623 /**
4624 * A subclass of UrlData class that can display inlined content using
4625 * {@link WebView#loadDataWithBaseURL(String, String, String, String, String)}.
4626 */
4627 private static class InlinedUrlData extends UrlData {
4628 InlinedUrlData(String inlined, String mimeType, String encoding, String failUrl) {
4629 super(failUrl);
4630 mInlined = inlined;
4631 mMimeType = mimeType;
4632 mEncoding = encoding;
4633 }
4634 String mMimeType;
4635 String mInlined;
4636 String mEncoding;
Mitsuru Oshima7944b7d2009-06-16 16:34:51 -07004637 @Override
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004638 boolean isEmpty() {
Ben Murdochbff2d602009-07-01 20:19:05 +01004639 return mInlined == null || mInlined.length() == 0 || super.isEmpty();
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004640 }
4641
Mitsuru Oshima7944b7d2009-06-16 16:34:51 -07004642 @Override
4643 public void loadIn(WebView webView) {
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004644 webView.loadDataWithBaseURL(null, mInlined, mMimeType, mEncoding, mUrl);
4645 }
4646 }
4647
Leon Scroggins1f005d32009-08-10 17:36:42 -04004648 /* package */ static final UrlData EMPTY_URL_DATA = new UrlData(null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004649}