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