blob: fd06d90052afb205fd5aaf44e547f3a11a4eb588 [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)) {
616 url = intent.getData().toString();
617 } else if (Intent.ACTION_SEARCH.equals(action)
618 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
619 || Intent.ACTION_WEB_SEARCH.equals(action)) {
620 url = intent.getStringExtra(SearchManager.QUERY);
621 }
Bjorn Bringert04851702009-09-22 10:36:01 +0100622 return handleWebSearchRequest(url, intent.getBundleExtra(SearchManager.APP_DATA),
623 intent.getStringExtra(SearchManager.EXTRA_DATA_KEY));
Satish Sampath565505b2009-05-29 15:37:27 +0100624 }
625
626 /**
627 * Launches the default web search activity with the query parameters if the given url string
628 * was identified as plain search terms and not URL/shortcut.
629 * @return true if the request was handled and web search activity was launched, false if not.
630 */
Bjorn Bringert04851702009-09-22 10:36:01 +0100631 private boolean handleWebSearchRequest(String inUrl, Bundle appData, String extraData) {
Satish Sampath565505b2009-05-29 15:37:27 +0100632 if (inUrl == null) return false;
633
634 // In general, we shouldn't modify URL from Intent.
635 // But currently, we get the user-typed URL from search box as well.
636 String url = fixUrl(inUrl).trim();
637
638 // URLs and site specific search shortcuts are handled by the regular flow of control, so
639 // return early.
640 if (Regex.WEB_URL_PATTERN.matcher(url).matches()
Satish Sampathbc5b9f32009-06-04 18:21:40 +0100641 || ACCEPTED_URI_SCHEMA.matcher(url).matches()
Satish Sampath565505b2009-05-29 15:37:27 +0100642 || parseUrlShortcut(url) != SHORTCUT_INVALID) {
643 return false;
644 }
645
646 Browser.updateVisitedHistory(mResolver, url, false);
647 Browser.addSearchUrl(mResolver, url);
648
649 Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);
650 intent.addCategory(Intent.CATEGORY_DEFAULT);
651 intent.putExtra(SearchManager.QUERY, url);
Satish Sampath15e9f2d2009-06-23 22:29:49 +0100652 if (appData != null) {
653 intent.putExtra(SearchManager.APP_DATA, appData);
654 }
Bjorn Bringert04851702009-09-22 10:36:01 +0100655 if (extraData != null) {
656 intent.putExtra(SearchManager.EXTRA_DATA_KEY, extraData);
657 }
Grace Klobacc634032009-07-28 15:58:19 -0700658 intent.putExtra(Browser.EXTRA_APPLICATION_ID, getPackageName());
Satish Sampath565505b2009-05-29 15:37:27 +0100659 startActivity(intent);
660
661 return true;
662 }
663
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700664 private UrlData getUrlDataFromIntent(Intent intent) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800665 String url = null;
666 if (intent != null) {
667 final String action = intent.getAction();
668 if (Intent.ACTION_VIEW.equals(action)) {
669 url = smartUrlFilter(intent.getData());
670 if (url != null && url.startsWith("content:")) {
671 /* Append mimetype so webview knows how to display */
672 String mimeType = intent.resolveType(getContentResolver());
673 if (mimeType != null) {
674 url += "?" + mimeType;
675 }
676 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700677 if ("inline:".equals(url)) {
678 return new InlinedUrlData(
679 intent.getStringExtra(Browser.EXTRA_INLINE_CONTENT),
680 intent.getType(),
681 intent.getStringExtra(Browser.EXTRA_INLINE_ENCODING),
682 intent.getStringExtra(Browser.EXTRA_INLINE_FAILURL));
683 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800684 } else if (Intent.ACTION_SEARCH.equals(action)
685 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
686 || Intent.ACTION_WEB_SEARCH.equals(action)) {
687 url = intent.getStringExtra(SearchManager.QUERY);
688 if (url != null) {
689 mLastEnteredUrl = url;
690 // Don't add Urls, just search terms.
691 // Urls will get added when the page is loaded.
692 if (!Regex.WEB_URL_PATTERN.matcher(url).matches()) {
693 Browser.updateVisitedHistory(mResolver, url, false);
694 }
695 // In general, we shouldn't modify URL from Intent.
696 // But currently, we get the user-typed URL from search box as well.
697 url = fixUrl(url);
698 url = smartUrlFilter(url);
699 String searchSource = "&source=android-" + GOOGLE_SEARCH_SOURCE_SUGGEST + "&";
700 if (url.contains(searchSource)) {
701 String source = null;
702 final Bundle appData = intent.getBundleExtra(SearchManager.APP_DATA);
703 if (appData != null) {
704 source = appData.getString(SearchManager.SOURCE);
705 }
706 if (TextUtils.isEmpty(source)) {
707 source = GOOGLE_SEARCH_SOURCE_UNKNOWN;
708 }
709 url = url.replace(searchSource, "&source=android-"+source+"&");
710 }
711 }
712 }
713 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700714 return new UrlData(url);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800715 }
716
717 /* package */ static String fixUrl(String inUrl) {
Cary Clark652ff872009-09-10 13:34:44 -0400718 // FIXME: Converting the url to lower case
719 // duplicates functionality in smartUrlFilter().
720 // However, changing all current callers of fixUrl to
721 // call smartUrlFilter in addition may have unwanted
722 // consequences, and is deferred for now.
723 int colon = inUrl.indexOf(':');
724 boolean allLower = true;
725 for (int index = 0; index < colon; index++) {
726 char ch = inUrl.charAt(index);
727 if (!Character.isLetter(ch)) {
728 break;
729 }
730 allLower &= Character.isLowerCase(ch);
731 if (index == colon - 1 && !allLower) {
732 inUrl = inUrl.substring(0, colon).toLowerCase()
733 + inUrl.substring(colon);
734 }
735 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800736 if (inUrl.startsWith("http://") || inUrl.startsWith("https://"))
737 return inUrl;
738 if (inUrl.startsWith("http:") ||
739 inUrl.startsWith("https:")) {
740 if (inUrl.startsWith("http:/") || inUrl.startsWith("https:/")) {
741 inUrl = inUrl.replaceFirst("/", "//");
742 } else inUrl = inUrl.replaceFirst(":", "://");
743 }
744 return inUrl;
745 }
746
747 /**
748 * Looking for the pattern like this
749 *
750 * *
751 * * *
752 * *** * *******
753 * * *
754 * * *
755 * *
756 */
757 private final SensorListener mSensorListener = new SensorListener() {
758 private long mLastGestureTime;
759 private float[] mPrev = new float[3];
760 private float[] mPrevDiff = new float[3];
761 private float[] mDiff = new float[3];
762 private float[] mRevertDiff = new float[3];
763
764 public void onSensorChanged(int sensor, float[] values) {
765 boolean show = false;
766 float[] diff = new float[3];
767
768 for (int i = 0; i < 3; i++) {
769 diff[i] = values[i] - mPrev[i];
770 if (Math.abs(diff[i]) > 1) {
771 show = true;
772 }
773 if ((diff[i] > 1.0 && mDiff[i] < 0.2)
774 || (diff[i] < -1.0 && mDiff[i] > -0.2)) {
775 // start track when there is a big move, or revert
776 mRevertDiff[i] = mDiff[i];
777 mDiff[i] = 0;
778 } else if (diff[i] > -0.2 && diff[i] < 0.2) {
779 // reset when it is flat
780 mDiff[i] = mRevertDiff[i] = 0;
781 }
782 mDiff[i] += diff[i];
783 mPrevDiff[i] = diff[i];
784 mPrev[i] = values[i];
785 }
786
787 if (false) {
788 // only shows if we think the delta is big enough, in an attempt
789 // to detect "serious" moves left/right or up/down
790 Log.d("BrowserSensorHack", "sensorChanged " + sensor + " ("
791 + values[0] + ", " + values[1] + ", " + values[2] + ")"
792 + " diff(" + diff[0] + " " + diff[1] + " " + diff[2]
793 + ")");
794 Log.d("BrowserSensorHack", " mDiff(" + mDiff[0] + " "
795 + mDiff[1] + " " + mDiff[2] + ")" + " mRevertDiff("
796 + mRevertDiff[0] + " " + mRevertDiff[1] + " "
797 + mRevertDiff[2] + ")");
798 }
799
800 long now = android.os.SystemClock.uptimeMillis();
801 if (now - mLastGestureTime > 1000) {
802 mLastGestureTime = 0;
803
804 float y = mDiff[1];
805 float z = mDiff[2];
806 float ay = Math.abs(y);
807 float az = Math.abs(z);
808 float ry = mRevertDiff[1];
809 float rz = mRevertDiff[2];
810 float ary = Math.abs(ry);
811 float arz = Math.abs(rz);
812 boolean gestY = ay > 2.5f && ary > 1.0f && ay > ary;
813 boolean gestZ = az > 3.5f && arz > 1.0f && az > arz;
814
815 if ((gestY || gestZ) && !(gestY && gestZ)) {
816 WebView view = mTabControl.getCurrentWebView();
817
818 if (view != null) {
819 if (gestZ) {
820 if (z < 0) {
821 view.zoomOut();
822 } else {
823 view.zoomIn();
824 }
825 } else {
826 view.flingScroll(0, Math.round(y * 100));
827 }
828 }
829 mLastGestureTime = now;
830 }
831 }
832 }
833
834 public void onAccuracyChanged(int sensor, int accuracy) {
835 // TODO Auto-generated method stub
836
837 }
838 };
839
840 @Override protected void onResume() {
841 super.onResume();
Dave Bort31a6d1c2009-04-13 15:56:49 -0700842 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800843 Log.v(LOGTAG, "BrowserActivity.onResume: this=" + this);
844 }
845
846 if (!mActivityInPause) {
847 Log.e(LOGTAG, "BrowserActivity is already resumed.");
848 return;
849 }
850
Mike Reed7bfa63b2009-05-28 11:08:32 -0400851 mTabControl.resumeCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800852 mActivityInPause = false;
Mike Reed7bfa63b2009-05-28 11:08:32 -0400853 resumeWebViewTimers();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800854
855 if (mWakeLock.isHeld()) {
856 mHandler.removeMessages(RELEASE_WAKELOCK);
857 mWakeLock.release();
858 }
859
860 if (mCredsDlg != null) {
861 if (!mHandler.hasMessages(CANCEL_CREDS_REQUEST)) {
862 // In case credential request never comes back
863 mHandler.sendEmptyMessageDelayed(CANCEL_CREDS_REQUEST, 6000);
864 }
865 }
866
867 registerReceiver(mNetworkStateIntentReceiver,
868 mNetworkStateChangedFilter);
869 WebView.enablePlatformNotifications();
870
871 if (mSettings.doFlick()) {
872 if (mSensorManager == null) {
873 mSensorManager = (SensorManager) getSystemService(
874 Context.SENSOR_SERVICE);
875 }
876 mSensorManager.registerListener(mSensorListener,
877 SensorManager.SENSOR_ACCELEROMETER,
878 SensorManager.SENSOR_DELAY_FASTEST);
879 } else {
880 mSensorManager = null;
881 }
882 }
883
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400884 /**
885 * Since the actual title bar is embedded in the WebView, and removing it
886 * would change its appearance, create a temporary title bar to go at
887 * the top of the screen while the menu is open.
888 */
889 private TitleBar mFakeTitleBar;
890
891 /**
Leon Scrogginsd8fd2fc2009-09-16 11:12:09 -0400892 * Holder for the fake title bar. It will have a foreground shadow, as well
893 * as a white background, so the fake title bar looks like the real one.
894 */
895 private ViewGroup mFakeTitleBarHolder;
896
897 /**
898 * Layout parameters for the fake title bar within mFakeTitleBarHolder
899 */
900 private FrameLayout.LayoutParams mFakeTitleBarParams
901 = new FrameLayout.LayoutParams(
Leon Scrogginsc01e4a82009-09-16 14:41:00 -0400902 ViewGroup.LayoutParams.FILL_PARENT,
Leon Scrogginsd8fd2fc2009-09-16 11:12:09 -0400903 ViewGroup.LayoutParams.WRAP_CONTENT);
904 /**
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400905 * Keeps track of whether the options menu is open. This is important in
906 * determining whether to show or hide the title bar overlay.
907 */
908 private boolean mOptionsMenuOpen;
909
910 /**
911 * Only meaningful when mOptionsMenuOpen is true. This variable keeps track
912 * of whether the configuration has changed. The first onMenuOpened call
913 * after a configuration change is simply a reopening of the same menu
914 * (i.e. mIconView did not change).
915 */
916 private boolean mConfigChanged;
917
918 /**
919 * Whether or not the options menu is in its smaller, icon menu form. When
920 * true, we want the title bar overlay to be up. When false, we do not.
921 * Only meaningful if mOptionsMenuOpen is true.
922 */
923 private boolean mIconView;
924
Leon Scrogginsa81a7642009-08-31 17:05:41 -0400925 @Override
926 public boolean onMenuOpened(int featureId, Menu menu) {
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400927 if (Window.FEATURE_OPTIONS_PANEL == featureId) {
928 if (mOptionsMenuOpen) {
929 if (mConfigChanged) {
930 // We do not need to make any changes to the state of the
931 // title bar, since the only thing that happened was a
932 // change in orientation
933 mConfigChanged = false;
934 } else {
935 if (mIconView) {
936 // Switching the menu to expanded view, so hide the
937 // title bar.
938 hideFakeTitleBar();
939 mIconView = false;
940 } else {
941 // Switching the menu back to icon view, so show the
942 // title bar once again.
943 showFakeTitleBar();
944 mIconView = true;
945 }
946 }
947 } else {
948 // The options menu is closed, so open it, and show the title
949 showFakeTitleBar();
950 mOptionsMenuOpen = true;
951 mConfigChanged = false;
952 mIconView = true;
953 }
954 }
Leon Scrogginsa81a7642009-08-31 17:05:41 -0400955 return true;
956 }
957
Leon Scrogginsb94bf272009-09-25 15:22:08 -0400958 /**
959 * Special class used exclusively for the shadow drawn underneath the fake
960 * title bar. The shadow does not need to be drawn if the WebView
961 * underneath is scrolled to the top, because it will draw directly on top
962 * of the embedded shadow.
963 */
964 private static class Shadow extends View {
965 private WebView mWebView;
966
967 public Shadow(Context context, AttributeSet attrs) {
968 super(context, attrs);
969 }
970
971 public void setWebView(WebView view) {
972 mWebView = view;
973 }
974
975 @Override
976 public void draw(Canvas canvas) {
977 // In general onDraw is the method to override, but we care about
978 // whether or not the background gets drawn, which happens in draw()
979 if (mWebView == null || mWebView.getScrollY() > getHeight()) {
980 super.draw(canvas);
981 }
982 // Need to invalidate so that if the scroll position changes, we
983 // still draw as appropriate.
984 invalidate();
985 }
986 }
987
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400988 private void showFakeTitleBar() {
Patrick Scottf8de8ec2009-09-21 16:37:29 -0400989 final View decor = getWindow().peekDecorView();
Leon Scroggins4d7e4062009-09-15 15:49:45 -0400990 if (mFakeTitleBar == null && mActiveTabsPage == null
Patrick Scottf8de8ec2009-09-21 16:37:29 -0400991 && !mActivityInPause && decor != null
992 && decor.getWindowToken() != null) {
Leon Scrogginsf4bb18a2009-09-11 18:37:53 -0400993 final WebView webView = getTopWindow();
Leon Scroggins68579392009-09-15 15:31:54 -0400994 mFakeTitleBar = new TitleBar(this);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400995 mFakeTitleBar.setTitleAndUrl(null, webView.getUrl());
996 mFakeTitleBar.setProgress(webView.getProgress());
997 mFakeTitleBar.setFavicon(webView.getFavicon());
998 updateLockIconToLatest();
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400999
1000 WindowManager manager
1001 = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
1002
1003 // Add the title bar to the window manager so it can receive touches
1004 // while the menu is up
1005 WindowManager.LayoutParams params
1006 = new WindowManager.LayoutParams(
1007 ViewGroup.LayoutParams.FILL_PARENT,
1008 ViewGroup.LayoutParams.WRAP_CONTENT,
1009 WindowManager.LayoutParams.TYPE_APPLICATION_SUB_PANEL,
1010 WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
Leon Scroggins68549862009-09-21 16:02:01 -04001011 PixelFormat.TRANSLUCENT);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04001012 params.gravity = Gravity.TOP;
Leon Scrogginsa27ff192009-09-14 12:58:04 -04001013 WebView mainView = mTabControl.getCurrentWebView();
Leon Scroggins68549862009-09-21 16:02:01 -04001014 boolean atTop = mainView != null && mainView.getScrollY() == 0;
1015 params.windowAnimations = atTop ? 0
1016 : com.android.internal.R.style.Animation_DropDownDown;
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04001017 // XXX : Without providing an offset, the fake title bar will be
1018 // placed underneath the status bar. Use the global visible rect
1019 // of mBrowserFrameLayout to determine the bottom of the status bar
1020 Rect rectangle = new Rect();
1021 mBrowserFrameLayout.getGlobalVisibleRect(rectangle);
1022 params.y = rectangle.top;
Leon Scroggins68549862009-09-21 16:02:01 -04001023 // Add a holder for the title bar. It also holds a shadow to show
1024 // below the title bar.
Leon Scrogginsd8fd2fc2009-09-16 11:12:09 -04001025 if (mFakeTitleBarHolder == null) {
1026 mFakeTitleBarHolder = (ViewGroup) LayoutInflater.from(this)
1027 .inflate(R.layout.title_bar_bg, null);
1028 }
Leon Scrogginsb94bf272009-09-25 15:22:08 -04001029 Shadow shadow = (Shadow) mFakeTitleBarHolder.findViewById(
1030 R.id.shadow);
1031 shadow.setWebView(mainView);
Leon Scroggins68549862009-09-21 16:02:01 -04001032 mFakeTitleBarHolder.addView(mFakeTitleBar, 0, mFakeTitleBarParams);
Leon Scrogginsd8fd2fc2009-09-16 11:12:09 -04001033 manager.addView(mFakeTitleBarHolder, params);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04001034 }
1035 }
1036
1037 @Override
1038 public void onOptionsMenuClosed(Menu menu) {
1039 mOptionsMenuOpen = false;
Leon Scrogginsa27ff192009-09-14 12:58:04 -04001040 if (!mInLoad) {
1041 hideFakeTitleBar();
1042 } else if (!mIconView) {
1043 // The page is currently loading, and we are in expanded mode, so
1044 // we were not showing the menu. Show it once again. It will be
1045 // removed when the page finishes.
1046 showFakeTitleBar();
1047 }
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04001048 }
1049 private void hideFakeTitleBar() {
1050 if (mFakeTitleBar == null) return;
Leon Scroggins20329572009-09-23 17:42:41 -04001051 WindowManager.LayoutParams params = (WindowManager.LayoutParams)
1052 mFakeTitleBarHolder.getLayoutParams();
1053 WebView mainView = mTabControl.getCurrentWebView();
1054 // Although we decided whether or not to animate based on the current
1055 // scroll position, the scroll position may have changed since the
1056 // fake title bar was displayed. Make sure it has the appropriate
1057 // animation/lack thereof before removing.
1058 params.windowAnimations = mainView != null && mainView.getScrollY() == 0
1059 ? 0 : com.android.internal.R.style.Animation_DropDownDown;
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04001060 WindowManager manager
1061 = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
Leon Scroggins20329572009-09-23 17:42:41 -04001062 manager.updateViewLayout(mFakeTitleBarHolder, params);
Leon Scrogginsd8fd2fc2009-09-16 11:12:09 -04001063 mFakeTitleBarHolder.removeView(mFakeTitleBar);
1064 manager.removeView(mFakeTitleBarHolder);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04001065 mFakeTitleBar = null;
1066 }
1067
The Android Open Source Project0c908882009-03-03 19:32:16 -08001068 /**
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001069 * Special method for the fake title bar to call when displaying its context
1070 * menu, since it is in its own Window, and its parent does not show a
1071 * context menu.
1072 */
1073 /* package */ void showTitleBarContextMenu() {
1074 openContextMenu(mTitleBar);
1075 }
1076
1077 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08001078 * onSaveInstanceState(Bundle map)
1079 * onSaveInstanceState is called right before onStop(). The map contains
1080 * the saved state.
1081 */
1082 @Override protected void onSaveInstanceState(Bundle outState) {
Dave Bort31a6d1c2009-04-13 15:56:49 -07001083 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001084 Log.v(LOGTAG, "BrowserActivity.onSaveInstanceState: this=" + this);
1085 }
1086 // the default implementation requires each view to have an id. As the
1087 // browser handles the state itself and it doesn't use id for the views,
1088 // don't call the default implementation. Otherwise it will trigger the
1089 // warning like this, "couldn't save which view has focus because the
1090 // focused view XXX has no id".
1091
1092 // Save all the tabs
1093 mTabControl.saveState(outState);
1094 }
1095
1096 @Override protected void onPause() {
1097 super.onPause();
1098
1099 if (mActivityInPause) {
1100 Log.e(LOGTAG, "BrowserActivity is already paused.");
1101 return;
1102 }
1103
Mike Reed7bfa63b2009-05-28 11:08:32 -04001104 mTabControl.pauseCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001105 mActivityInPause = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -04001106 if (mTabControl.getCurrentIndex() >= 0 && !pauseWebViewTimers()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001107 mWakeLock.acquire();
1108 mHandler.sendMessageDelayed(mHandler
1109 .obtainMessage(RELEASE_WAKELOCK), WAKELOCK_TIMEOUT);
1110 }
1111
1112 // Clear the credentials toast if it is up
1113 if (mCredsDlg != null && mCredsDlg.isShowing()) {
1114 mCredsDlg.dismiss();
1115 }
1116 mCredsDlg = null;
1117
Leon Scrogginsa2ab6a72009-09-11 11:49:52 -04001118 // FIXME: This removes the active tabs page and resets the menu to
1119 // MAIN_MENU. A better solution might be to do this work in onNewIntent
1120 // but then we would need to save it in onSaveInstanceState and restore
1121 // it in onCreate/onRestoreInstanceState
1122 if (mActiveTabsPage != null) {
1123 removeActiveTabPage(true);
1124 }
1125
The Android Open Source Project0c908882009-03-03 19:32:16 -08001126 cancelStopToast();
1127
1128 // unregister network state listener
1129 unregisterReceiver(mNetworkStateIntentReceiver);
1130 WebView.disablePlatformNotifications();
1131
1132 if (mSensorManager != null) {
1133 mSensorManager.unregisterListener(mSensorListener);
1134 }
1135 }
1136
1137 @Override protected void onDestroy() {
Dave Bort31a6d1c2009-04-13 15:56:49 -07001138 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001139 Log.v(LOGTAG, "BrowserActivity.onDestroy: this=" + this);
1140 }
1141 super.onDestroy();
Grace Kloba0923d692009-09-23 21:37:25 -07001142
1143 if (mTabControl == null) return;
1144
The Android Open Source Project0c908882009-03-03 19:32:16 -08001145 // Remove the current tab and sub window
1146 TabControl.Tab t = mTabControl.getCurrentTab();
Patrick Scottfb5e77f2009-04-08 19:17:37 -07001147 if (t != null) {
1148 dismissSubWindow(t);
1149 removeTabFromContentView(t);
1150 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001151 // Destroy all the tabs
1152 mTabControl.destroy();
1153 WebIconDatabase.getInstance().close();
1154 if (mGlsConnection != null) {
1155 unbindService(mGlsConnection);
1156 mGlsConnection = null;
1157 }
1158
1159 //
1160 // stop MASF proxy service
1161 //
1162 //Intent proxyServiceIntent = new Intent();
1163 //proxyServiceIntent.setComponent
1164 // (new ComponentName(
1165 // "com.android.masfproxyservice",
1166 // "com.android.masfproxyservice.MasfProxyService"));
1167 //stopService(proxyServiceIntent);
Grace Klobab4da0ad2009-05-14 14:45:40 -07001168
1169 unregisterReceiver(mPackageInstallationReceiver);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001170 }
1171
1172 @Override
1173 public void onConfigurationChanged(Configuration newConfig) {
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04001174 mConfigChanged = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001175 super.onConfigurationChanged(newConfig);
1176
1177 if (mPageInfoDialog != null) {
1178 mPageInfoDialog.dismiss();
1179 showPageInfo(
1180 mPageInfoView,
1181 mPageInfoFromShowSSLCertificateOnError.booleanValue());
1182 }
1183 if (mSSLCertificateDialog != null) {
1184 mSSLCertificateDialog.dismiss();
1185 showSSLCertificate(
1186 mSSLCertificateView);
1187 }
1188 if (mSSLCertificateOnErrorDialog != null) {
1189 mSSLCertificateOnErrorDialog.dismiss();
1190 showSSLCertificateOnError(
1191 mSSLCertificateOnErrorView,
1192 mSSLCertificateOnErrorHandler,
1193 mSSLCertificateOnErrorError);
1194 }
1195 if (mHttpAuthenticationDialog != null) {
1196 String title = ((TextView) mHttpAuthenticationDialog
1197 .findViewById(com.android.internal.R.id.alertTitle)).getText()
1198 .toString();
1199 String name = ((TextView) mHttpAuthenticationDialog
1200 .findViewById(R.id.username_edit)).getText().toString();
1201 String password = ((TextView) mHttpAuthenticationDialog
1202 .findViewById(R.id.password_edit)).getText().toString();
1203 int focusId = mHttpAuthenticationDialog.getCurrentFocus()
1204 .getId();
1205 mHttpAuthenticationDialog.dismiss();
1206 showHttpAuthentication(mHttpAuthHandler, null, null, title,
1207 name, password, focusId);
1208 }
1209 if (mFindDialog != null && mFindDialog.isShowing()) {
1210 mFindDialog.onConfigurationChanged(newConfig);
1211 }
1212 }
1213
1214 @Override public void onLowMemory() {
1215 super.onLowMemory();
1216 mTabControl.freeMemory();
1217 }
1218
Mike Reed7bfa63b2009-05-28 11:08:32 -04001219 private boolean resumeWebViewTimers() {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001220 if ((!mActivityInPause && !mPageStarted) ||
1221 (mActivityInPause && mPageStarted)) {
1222 CookieSyncManager.getInstance().startSync();
1223 WebView w = mTabControl.getCurrentWebView();
1224 if (w != null) {
1225 w.resumeTimers();
1226 }
1227 return true;
1228 } else {
1229 return false;
1230 }
1231 }
1232
Mike Reed7bfa63b2009-05-28 11:08:32 -04001233 private boolean pauseWebViewTimers() {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001234 if (mActivityInPause && !mPageStarted) {
1235 CookieSyncManager.getInstance().stopSync();
1236 WebView w = mTabControl.getCurrentWebView();
1237 if (w != null) {
1238 w.pauseTimers();
1239 }
1240 return true;
1241 } else {
1242 return false;
1243 }
1244 }
1245
Leon Scroggins1f005d32009-08-10 17:36:42 -04001246 // FIXME: Do we want to call this when loading google for the first time?
The Android Open Source Project0c908882009-03-03 19:32:16 -08001247 /*
1248 * This function is called when we are launching for the first time. We
1249 * are waiting for the login credentials before loading Google home
1250 * pages. This way the user will be logged in straight away.
1251 */
1252 private void waitForCredentials() {
1253 // Show a toast
1254 mCredsDlg = new ProgressDialog(this);
1255 mCredsDlg.setIndeterminate(true);
1256 mCredsDlg.setMessage(getText(R.string.retrieving_creds_dlg_msg));
1257 // If the user cancels the operation, then cancel the Google
1258 // Credentials request.
1259 mCredsDlg.setCancelMessage(mHandler.obtainMessage(CANCEL_CREDS_REQUEST));
1260 mCredsDlg.show();
1261
1262 // We set a timeout for the retrieval of credentials in onResume()
1263 // as that is when we have freed up some CPU time to get
1264 // the login credentials.
1265 }
1266
1267 /*
1268 * If we have received the credentials or we have timed out and we are
1269 * showing the credentials dialog, then it is time to move on.
1270 */
1271 private void resumeAfterCredentials() {
1272 if (mCredsDlg == null) {
1273 return;
1274 }
1275
1276 // Clear the toast
1277 if (mCredsDlg.isShowing()) {
1278 mCredsDlg.dismiss();
1279 }
1280 mCredsDlg = null;
1281
1282 // Clear any pending timeout
1283 mHandler.removeMessages(CANCEL_CREDS_REQUEST);
1284
1285 // Load the page
1286 WebView w = mTabControl.getCurrentWebView();
1287 if (w != null) {
1288 w.loadUrl(mSettings.getHomePage());
1289 }
1290
1291 // Update the settings, need to do this last as it can take a moment
1292 // to persist the settings. In the mean time we could be loading
1293 // content.
1294 mSettings.setLoginInitialized(this);
1295 }
1296
1297 // Open the icon database and retain all the icons for visited sites.
1298 private void retainIconsOnStartup() {
1299 final WebIconDatabase db = WebIconDatabase.getInstance();
1300 db.open(getDir("icons", 0).getPath());
1301 try {
1302 Cursor c = Browser.getAllBookmarks(mResolver);
1303 if (!c.moveToFirst()) {
1304 c.deactivate();
1305 return;
1306 }
1307 int urlIndex = c.getColumnIndex(Browser.BookmarkColumns.URL);
1308 do {
1309 String url = c.getString(urlIndex);
1310 db.retainIconForPageUrl(url);
1311 } while (c.moveToNext());
1312 c.deactivate();
1313 } catch (IllegalStateException e) {
1314 Log.e(LOGTAG, "retainIconsOnStartup", e);
1315 }
1316 }
1317
1318 // Helper method for getting the top window.
1319 WebView getTopWindow() {
1320 return mTabControl.getCurrentTopWebView();
1321 }
1322
1323 @Override
1324 public boolean onCreateOptionsMenu(Menu menu) {
1325 super.onCreateOptionsMenu(menu);
1326
1327 MenuInflater inflater = getMenuInflater();
1328 inflater.inflate(R.menu.browser, menu);
1329 mMenu = menu;
1330 updateInLoadMenuItems();
1331 return true;
1332 }
1333
1334 /**
1335 * As the menu can be open when loading state changes
1336 * we must manually update the state of the stop/reload menu
1337 * item
1338 */
1339 private void updateInLoadMenuItems() {
1340 if (mMenu == null) {
1341 return;
1342 }
1343 MenuItem src = mInLoad ?
1344 mMenu.findItem(R.id.stop_menu_id):
1345 mMenu.findItem(R.id.reload_menu_id);
1346 MenuItem dest = mMenu.findItem(R.id.stop_reload_menu_id);
1347 dest.setIcon(src.getIcon());
1348 dest.setTitle(src.getTitle());
1349 }
1350
1351 @Override
1352 public boolean onContextItemSelected(MenuItem item) {
1353 // chording is not an issue with context menus, but we use the same
1354 // options selector, so set mCanChord to true so we can access them.
1355 mCanChord = true;
1356 int id = item.getItemId();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001357 switch (id) {
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001358 // For the context menu from the title bar
1359 case R.id.title_bar_share_page_url:
1360 case R.id.title_bar_copy_page_url:
1361 WebView mainView = mTabControl.getCurrentWebView();
1362 if (null == mainView) {
1363 return false;
1364 }
1365 if (id == R.id.title_bar_share_page_url) {
1366 Browser.sendString(this, mainView.getUrl());
1367 } else {
1368 copy(mainView.getUrl());
1369 }
1370 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001371 // -- Browser context menu
1372 case R.id.open_context_menu_id:
1373 case R.id.open_newtab_context_menu_id:
1374 case R.id.bookmark_context_menu_id:
1375 case R.id.save_link_context_menu_id:
1376 case R.id.share_link_context_menu_id:
1377 case R.id.copy_link_context_menu_id:
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001378 final WebView webView = getTopWindow();
1379 if (null == webView) {
1380 return false;
1381 }
1382 final HashMap hrefMap = new HashMap();
1383 hrefMap.put("webview", webView);
1384 final Message msg = mHandler.obtainMessage(
1385 FOCUS_NODE_HREF, id, 0, hrefMap);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001386 webView.requestFocusNodeHref(msg);
1387 break;
1388
1389 default:
1390 // For other context menus
1391 return onOptionsItemSelected(item);
1392 }
1393 mCanChord = false;
1394 return true;
1395 }
1396
1397 private Bundle createGoogleSearchSourceBundle(String source) {
1398 Bundle bundle = new Bundle();
1399 bundle.putString(SearchManager.SOURCE, source);
1400 return bundle;
1401 }
1402
1403 /**
The Android Open Source Project4e5f5872009-03-09 11:52:14 -07001404 * Overriding this to insert a local information bundle
The Android Open Source Project0c908882009-03-03 19:32:16 -08001405 */
1406 @Override
1407 public boolean onSearchRequested() {
Leon Scroggins68579392009-09-15 15:31:54 -04001408 if (mOptionsMenuOpen) closeOptionsMenu();
Leon Scroggins5bbe9802009-07-31 13:10:55 -04001409 String url = (getTopWindow() == null) ? null : getTopWindow().getUrl();
Grace Kloba83f47342009-07-20 10:44:31 -07001410 startSearch(mSettings.getHomePage().equals(url) ? null : url, true,
The Android Open Source Project4e5f5872009-03-09 11:52:14 -07001411 createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_SEARCHKEY), false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001412 return true;
1413 }
1414
1415 @Override
1416 public void startSearch(String initialQuery, boolean selectInitialQuery,
1417 Bundle appSearchData, boolean globalSearch) {
1418 if (appSearchData == null) {
1419 appSearchData = createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_TYPE);
1420 }
1421 super.startSearch(initialQuery, selectInitialQuery, appSearchData, globalSearch);
1422 }
1423
Leon Scroggins1f005d32009-08-10 17:36:42 -04001424 /**
1425 * Switch tabs. Called by the TitleBarSet when sliding the title bar
1426 * results in changing tabs.
Leon Scroggins160a7e72009-08-14 18:28:01 -04001427 * @param index Index of the tab to change to, as defined by
1428 * mTabControl.getTabIndex(Tab t).
1429 * @return boolean True if we successfully switched to a different tab. If
1430 * the indexth tab is null, or if that tab is the same as
1431 * the current one, return false.
Leon Scroggins1f005d32009-08-10 17:36:42 -04001432 */
Leon Scroggins160a7e72009-08-14 18:28:01 -04001433 /* package */ boolean switchToTab(int index) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001434 TabControl.Tab tab = mTabControl.getTab(index);
1435 TabControl.Tab currentTab = mTabControl.getCurrentTab();
1436 if (tab == null || tab == currentTab) {
Leon Scroggins160a7e72009-08-14 18:28:01 -04001437 return false;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001438 }
1439 if (currentTab != null) {
1440 // currentTab may be null if it was just removed. In that case,
1441 // we do not need to remove it
1442 removeTabFromContentView(currentTab);
1443 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001444 mTabControl.setCurrentTab(tab);
1445 attachTabToContentView(tab);
Grace Klobaeb6eef42009-09-15 17:56:32 -07001446 resetTitleIconAndProgress();
1447 updateLockIconToLatest();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001448 return true;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001449 }
1450
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001451 /* package */ TabControl.Tab openTabToHomePage() {
1452 return openTabAndShow(mSettings.getHomePage(), false, null);
1453 }
1454
Leon Scroggins1f005d32009-08-10 17:36:42 -04001455 /* package */ void closeCurrentWindow() {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001456 final TabControl.Tab current = mTabControl.getCurrentTab();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001457 if (mTabControl.getTabCount() == 1) {
Leon Scroggins30444232009-09-04 18:36:20 -04001458 // This is the last tab. Open a new one, with the home
1459 // page and close the current one.
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001460 TabControl.Tab newTab = openTabToHomePage();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001461 closeTab(current);
Leon Scroggins160a7e72009-08-14 18:28:01 -04001462 return;
1463 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001464 final TabControl.Tab parent = current.getParentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04001465 int indexToShow = -1;
1466 if (parent != null) {
1467 indexToShow = mTabControl.getTabIndex(parent);
1468 } else {
Leon Scroggins160a7e72009-08-14 18:28:01 -04001469 final int currentIndex = mTabControl.getCurrentIndex();
1470 // Try to move to the tab to the right
1471 indexToShow = currentIndex + 1;
1472 if (indexToShow > mTabControl.getTabCount() - 1) {
1473 // Try to move to the tab to the left
1474 indexToShow = currentIndex - 1;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001475 }
1476 }
Leon Scroggins160a7e72009-08-14 18:28:01 -04001477 if (switchToTab(indexToShow)) {
1478 // Close window
1479 closeTab(current);
1480 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001481 }
1482
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001483 private ActiveTabsPage mActiveTabsPage;
1484
1485 /**
1486 * Remove the active tabs page.
1487 * @param needToAttach If true, the active tabs page did not attach a tab
1488 * to the content view, so we need to do that here.
1489 */
1490 /* package */ void removeActiveTabPage(boolean needToAttach) {
1491 mContentView.removeView(mActiveTabsPage);
1492 mActiveTabsPage = null;
1493 mMenuState = R.id.MAIN_MENU;
1494 if (needToAttach) {
1495 attachTabToContentView(mTabControl.getCurrentTab());
1496 }
1497 getTopWindow().requestFocus();
1498 }
1499
The Android Open Source Project0c908882009-03-03 19:32:16 -08001500 @Override
1501 public boolean onOptionsItemSelected(MenuItem item) {
1502 if (!mCanChord) {
1503 // The user has already fired a shortcut with this hold down of the
1504 // menu key.
1505 return false;
1506 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001507 if (null == getTopWindow()) {
Leon Scroggins0d7ae0e2009-06-05 11:04:45 -04001508 return false;
1509 }
Grace Kloba6ee9c492009-07-13 10:04:34 -07001510 if (mMenuIsDown) {
1511 // The shortcut action consumes the MENU. Even if it is still down,
1512 // it won't trigger the next shortcut action. In the case of the
1513 // shortcut action triggering a new activity, like Bookmarks, we
1514 // won't get onKeyUp for MENU. So it is important to reset it here.
1515 mMenuIsDown = false;
1516 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001517 switch (item.getItemId()) {
1518 // -- Main menu
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001519 case R.id.new_tab_menu_id:
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001520 openTabToHomePage();
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001521 break;
1522
Leon Scroggins64b80f32009-08-07 12:03:34 -04001523 case R.id.goto_menu_id:
Leon Scroggins30444232009-09-04 18:36:20 -04001524 bookmarksOrHistoryPicker(false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001525 break;
1526
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001527 case R.id.active_tabs_menu_id:
1528 mActiveTabsPage = new ActiveTabsPage(this, mTabControl);
1529 removeTabFromContentView(mTabControl.getCurrentTab());
Leon Scroggins43de6162009-09-14 19:59:58 -04001530 hideFakeTitleBar();
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001531 mContentView.addView(mActiveTabsPage, COVER_SCREEN_PARAMS);
1532 mActiveTabsPage.requestFocus();
1533 mMenuState = EMPTY_MENU;
1534 break;
1535
Leon Scroggins1f005d32009-08-10 17:36:42 -04001536 case R.id.add_bookmark_menu_id:
1537 Intent i = new Intent(BrowserActivity.this,
1538 AddBookmarkPage.class);
1539 WebView w = getTopWindow();
1540 i.putExtra("url", w.getUrl());
1541 i.putExtra("title", w.getTitle());
Grace Kloba83cdb2c2009-09-16 00:48:57 -07001542 i.putExtra("touch_icon_url", w.getTouchIconUrl());
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01001543 i.putExtra("thumbnail", createScreenshot(w));
Leon Scroggins1f005d32009-08-10 17:36:42 -04001544 startActivity(i);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001545 break;
1546
1547 case R.id.stop_reload_menu_id:
1548 if (mInLoad) {
1549 stopLoading();
1550 } else {
1551 getTopWindow().reload();
1552 }
1553 break;
1554
1555 case R.id.back_menu_id:
1556 getTopWindow().goBack();
1557 break;
1558
1559 case R.id.forward_menu_id:
1560 getTopWindow().goForward();
1561 break;
1562
1563 case R.id.close_menu_id:
1564 // Close the subwindow if it exists.
1565 if (mTabControl.getCurrentSubWindow() != null) {
1566 dismissSubWindow(mTabControl.getCurrentTab());
1567 break;
1568 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001569 closeCurrentWindow();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001570 break;
1571
1572 case R.id.homepage_menu_id:
1573 TabControl.Tab current = mTabControl.getCurrentTab();
1574 if (current != null) {
1575 dismissSubWindow(current);
1576 current.getWebView().loadUrl(mSettings.getHomePage());
1577 }
1578 break;
1579
1580 case R.id.preferences_menu_id:
1581 Intent intent = new Intent(this,
1582 BrowserPreferencesPage.class);
1583 startActivityForResult(intent, PREFERENCES_PAGE);
1584 break;
1585
1586 case R.id.find_menu_id:
1587 if (null == mFindDialog) {
1588 mFindDialog = new FindDialog(this);
1589 }
1590 mFindDialog.setWebView(getTopWindow());
1591 mFindDialog.show();
1592 mMenuState = EMPTY_MENU;
1593 break;
1594
1595 case R.id.select_text_id:
1596 getTopWindow().emulateShiftHeld();
1597 break;
1598 case R.id.page_info_menu_id:
1599 showPageInfo(mTabControl.getCurrentTab(), false);
1600 break;
1601
1602 case R.id.classic_history_menu_id:
Leon Scroggins30444232009-09-04 18:36:20 -04001603 bookmarksOrHistoryPicker(true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001604 break;
1605
1606 case R.id.share_page_menu_id:
Andrei Popescu10fdba82009-09-24 13:25:47 +01001607 Browser.sendString(this, getTopWindow().getUrl(),
1608 getText(R.string.choosertitle_sharevia).toString());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001609 break;
1610
1611 case R.id.dump_nav_menu_id:
1612 getTopWindow().debugDump();
1613 break;
1614
1615 case R.id.zoom_in_menu_id:
1616 getTopWindow().zoomIn();
1617 break;
1618
1619 case R.id.zoom_out_menu_id:
1620 getTopWindow().zoomOut();
1621 break;
1622
1623 case R.id.view_downloads_menu_id:
1624 viewDownloads(null);
1625 break;
1626
The Android Open Source Project0c908882009-03-03 19:32:16 -08001627 case R.id.window_one_menu_id:
1628 case R.id.window_two_menu_id:
1629 case R.id.window_three_menu_id:
1630 case R.id.window_four_menu_id:
1631 case R.id.window_five_menu_id:
1632 case R.id.window_six_menu_id:
1633 case R.id.window_seven_menu_id:
1634 case R.id.window_eight_menu_id:
1635 {
1636 int menuid = item.getItemId();
1637 for (int id = 0; id < WINDOW_SHORTCUT_ID_ARRAY.length; id++) {
1638 if (WINDOW_SHORTCUT_ID_ARRAY[id] == menuid) {
1639 TabControl.Tab desiredTab = mTabControl.getTab(id);
1640 if (desiredTab != null &&
1641 desiredTab != mTabControl.getCurrentTab()) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001642 switchToTab(id);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001643 }
1644 break;
1645 }
1646 }
1647 }
1648 break;
1649
1650 default:
1651 if (!super.onOptionsItemSelected(item)) {
1652 return false;
1653 }
1654 // Otherwise fall through.
1655 }
1656 mCanChord = false;
1657 return true;
1658 }
1659
1660 public void closeFind() {
1661 mMenuState = R.id.MAIN_MENU;
1662 }
1663
1664 @Override public boolean onPrepareOptionsMenu(Menu menu)
1665 {
1666 // This happens when the user begins to hold down the menu key, so
1667 // allow them to chord to get a shortcut.
1668 mCanChord = true;
1669 // Note: setVisible will decide whether an item is visible; while
1670 // setEnabled() will decide whether an item is enabled, which also means
1671 // whether the matching shortcut key will function.
1672 super.onPrepareOptionsMenu(menu);
1673 switch (mMenuState) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001674 case EMPTY_MENU:
1675 if (mCurrentMenuState != mMenuState) {
1676 menu.setGroupVisible(R.id.MAIN_MENU, false);
1677 menu.setGroupEnabled(R.id.MAIN_MENU, false);
1678 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001679 }
1680 break;
1681 default:
1682 if (mCurrentMenuState != mMenuState) {
1683 menu.setGroupVisible(R.id.MAIN_MENU, true);
1684 menu.setGroupEnabled(R.id.MAIN_MENU, true);
1685 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001686 }
1687 final WebView w = getTopWindow();
1688 boolean canGoBack = false;
1689 boolean canGoForward = false;
1690 boolean isHome = false;
1691 if (w != null) {
1692 canGoBack = w.canGoBack();
1693 canGoForward = w.canGoForward();
1694 isHome = mSettings.getHomePage().equals(w.getUrl());
1695 }
1696 final MenuItem back = menu.findItem(R.id.back_menu_id);
1697 back.setEnabled(canGoBack);
1698
1699 final MenuItem home = menu.findItem(R.id.homepage_menu_id);
1700 home.setEnabled(!isHome);
1701
1702 menu.findItem(R.id.forward_menu_id)
1703 .setEnabled(canGoForward);
1704
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001705 menu.findItem(R.id.new_tab_menu_id).setEnabled(
1706 mTabControl.getTabCount() < TabControl.MAX_TABS);
1707
The Android Open Source Project0c908882009-03-03 19:32:16 -08001708 // decide whether to show the share link option
1709 PackageManager pm = getPackageManager();
1710 Intent send = new Intent(Intent.ACTION_SEND);
1711 send.setType("text/plain");
1712 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1713 menu.findItem(R.id.share_page_menu_id).setVisible(ri != null);
1714
The Android Open Source Project0c908882009-03-03 19:32:16 -08001715 boolean isNavDump = mSettings.isNavDump();
1716 final MenuItem nav = menu.findItem(R.id.dump_nav_menu_id);
1717 nav.setVisible(isNavDump);
1718 nav.setEnabled(isNavDump);
1719 break;
1720 }
1721 mCurrentMenuState = mMenuState;
1722 return true;
1723 }
1724
1725 @Override
1726 public void onCreateContextMenu(ContextMenu menu, View v,
1727 ContextMenuInfo menuInfo) {
1728 WebView webview = (WebView) v;
1729 WebView.HitTestResult result = webview.getHitTestResult();
1730 if (result == null) {
1731 return;
1732 }
1733
1734 int type = result.getType();
1735 if (type == WebView.HitTestResult.UNKNOWN_TYPE) {
1736 Log.w(LOGTAG,
1737 "We should not show context menu when nothing is touched");
1738 return;
1739 }
1740 if (type == WebView.HitTestResult.EDIT_TEXT_TYPE) {
1741 // let TextView handles context menu
1742 return;
1743 }
1744
1745 // Note, http://b/issue?id=1106666 is requesting that
1746 // an inflated menu can be used again. This is not available
1747 // yet, so inflate each time (yuk!)
1748 MenuInflater inflater = getMenuInflater();
1749 inflater.inflate(R.menu.browsercontext, menu);
1750
1751 // Show the correct menu group
1752 String extra = result.getExtra();
1753 menu.setGroupVisible(R.id.PHONE_MENU,
1754 type == WebView.HitTestResult.PHONE_TYPE);
1755 menu.setGroupVisible(R.id.EMAIL_MENU,
1756 type == WebView.HitTestResult.EMAIL_TYPE);
1757 menu.setGroupVisible(R.id.GEO_MENU,
1758 type == WebView.HitTestResult.GEO_TYPE);
1759 menu.setGroupVisible(R.id.IMAGE_MENU,
1760 type == WebView.HitTestResult.IMAGE_TYPE
1761 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1762 menu.setGroupVisible(R.id.ANCHOR_MENU,
1763 type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1764 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1765
1766 // Setup custom handling depending on the type
1767 switch (type) {
1768 case WebView.HitTestResult.PHONE_TYPE:
1769 menu.setHeaderTitle(Uri.decode(extra));
1770 menu.findItem(R.id.dial_context_menu_id).setIntent(
1771 new Intent(Intent.ACTION_VIEW, Uri
1772 .parse(WebView.SCHEME_TEL + extra)));
1773 Intent addIntent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
1774 addIntent.putExtra(Insert.PHONE, Uri.decode(extra));
Cary Clark5e335a32009-09-22 14:53:11 -04001775 addIntent.setType(ContactsContract.Contacts.CONTENT_ITEM_TYPE);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001776 menu.findItem(R.id.add_contact_context_menu_id).setIntent(
1777 addIntent);
1778 menu.findItem(R.id.copy_phone_context_menu_id).setOnMenuItemClickListener(
1779 new Copy(extra));
1780 break;
1781
1782 case WebView.HitTestResult.EMAIL_TYPE:
1783 menu.setHeaderTitle(extra);
1784 menu.findItem(R.id.email_context_menu_id).setIntent(
1785 new Intent(Intent.ACTION_VIEW, Uri
1786 .parse(WebView.SCHEME_MAILTO + extra)));
1787 menu.findItem(R.id.copy_mail_context_menu_id).setOnMenuItemClickListener(
1788 new Copy(extra));
1789 break;
1790
1791 case WebView.HitTestResult.GEO_TYPE:
1792 menu.setHeaderTitle(extra);
1793 menu.findItem(R.id.map_context_menu_id).setIntent(
1794 new Intent(Intent.ACTION_VIEW, Uri
1795 .parse(WebView.SCHEME_GEO
1796 + URLEncoder.encode(extra))));
1797 menu.findItem(R.id.copy_geo_context_menu_id).setOnMenuItemClickListener(
1798 new Copy(extra));
1799 break;
1800
1801 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1802 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
1803 TextView titleView = (TextView) LayoutInflater.from(this)
1804 .inflate(android.R.layout.browser_link_context_header,
1805 null);
1806 titleView.setText(extra);
1807 menu.setHeaderView(titleView);
1808 // decide whether to show the open link in new tab option
1809 menu.findItem(R.id.open_newtab_context_menu_id).setVisible(
1810 mTabControl.getTabCount() < TabControl.MAX_TABS);
1811 PackageManager pm = getPackageManager();
1812 Intent send = new Intent(Intent.ACTION_SEND);
1813 send.setType("text/plain");
1814 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1815 menu.findItem(R.id.share_link_context_menu_id).setVisible(ri != null);
1816 if (type == WebView.HitTestResult.SRC_ANCHOR_TYPE) {
1817 break;
1818 }
1819 // otherwise fall through to handle image part
1820 case WebView.HitTestResult.IMAGE_TYPE:
1821 if (type == WebView.HitTestResult.IMAGE_TYPE) {
1822 menu.setHeaderTitle(extra);
1823 }
1824 menu.findItem(R.id.view_image_context_menu_id).setIntent(
1825 new Intent(Intent.ACTION_VIEW, Uri.parse(extra)));
1826 menu.findItem(R.id.download_context_menu_id).
1827 setOnMenuItemClickListener(new Download(extra));
1828 break;
1829
1830 default:
1831 Log.w(LOGTAG, "We should not get here.");
1832 break;
1833 }
1834 }
1835
The Android Open Source Project0c908882009-03-03 19:32:16 -08001836 // Attach the given tab to the content view.
Grace Klobac928c302009-09-17 11:51:21 -07001837 // this should only be called for the current tab.
The Android Open Source Project0c908882009-03-03 19:32:16 -08001838 private void attachTabToContentView(TabControl.Tab t) {
Steve Block2bc69912009-07-30 14:45:13 +01001839 // Attach the container that contains the main WebView and any other UI
1840 // associated with the tab.
Patrick Scottd0119532009-09-17 08:00:31 -04001841 t.attachTabToContentView(mContentView);
Ben Murdochbff2d602009-07-01 20:19:05 +01001842
1843 if (mShouldShowErrorConsole) {
1844 ErrorConsoleView errorConsole = mTabControl.getCurrentErrorConsole(true);
1845 if (errorConsole.numberOfErrors() == 0) {
1846 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
1847 } else {
1848 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
1849 }
1850
1851 mErrorConsoleContainer.addView(errorConsole,
1852 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
1853 ViewGroup.LayoutParams.WRAP_CONTENT));
1854 }
1855
Grace Klobac928c302009-09-17 11:51:21 -07001856 setLockIconType(t.getLockIconType());
1857 setPrevLockType(t.getPrevLockIconType());
1858
1859 // this is to match the code in removeTabFromContentView()
1860 if (!mPageStarted && t.getTopWindow().getProgress() < 100) {
1861 mPageStarted = true;
Grace Klobaeb6eef42009-09-15 17:56:32 -07001862 }
1863
Leon Scroggins39ab28e2009-09-02 21:20:30 -04001864 WebView view = t.getWebView();
Leon Scroggins55a5bc22009-09-04 17:00:08 -04001865 view.setEmbeddedTitleBar(mTitleBar);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001866 // Request focus on the top window.
1867 t.getTopWindow().requestFocus();
1868 }
1869
1870 // Attach a sub window to the main WebView of the given tab.
1871 private void attachSubWindow(TabControl.Tab t) {
Patrick Scottd0119532009-09-17 08:00:31 -04001872 t.attachSubWindow(mContentView);
1873 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001874 }
1875
1876 // Remove the given tab from the content view.
1877 private void removeTabFromContentView(TabControl.Tab t) {
Steve Block2bc69912009-07-30 14:45:13 +01001878 // Remove the container that contains the main WebView.
Patrick Scottd0119532009-09-17 08:00:31 -04001879 t.removeTabFromContentView(mContentView);
Ben Murdochbff2d602009-07-01 20:19:05 +01001880
1881 if (mTabControl.getCurrentErrorConsole(false) != null) {
1882 mErrorConsoleContainer.removeView(mTabControl.getCurrentErrorConsole(false));
1883 }
1884
Leon Scroggins39ab28e2009-09-02 21:20:30 -04001885 WebView view = t.getWebView();
Leon Scrogginsbb85b902009-09-14 19:27:20 -04001886 if (view != null) {
1887 view.setEmbeddedTitleBar(null);
1888 }
Leon Scroggins39ab28e2009-09-02 21:20:30 -04001889
Grace Klobac928c302009-09-17 11:51:21 -07001890 // unlike attachTabToContentView(), removeTabFromContentView() can be
1891 // called for the non-current tab. Need to add the check.
Grace Klobaeb6eef42009-09-15 17:56:32 -07001892 if (t == mTabControl.getCurrentTab()) {
1893 t.setLockIconType(getLockIconType());
1894 t.setPrevLockIconType(getPrevLockType());
Grace Klobac928c302009-09-17 11:51:21 -07001895
1896 // this is not a perfect solution. But currently there is one
1897 // WebViewClient for all the WebView. if user switches from an
1898 // in-load window to an already loaded window, mPageStarted will not
1899 // be set to false. If user leaves the Browser, pauseWebViewTimers()
1900 // won't do anything and leaves the timer running even Browser is in
1901 // the background.
1902 if (mPageStarted) {
1903 mPageStarted = false;
1904 }
Grace Klobaeb6eef42009-09-15 17:56:32 -07001905 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001906 }
1907
1908 // Remove the sub window if it exists. Also called by TabControl when the
1909 // user clicks the 'X' to dismiss a sub window.
1910 /* package */ void dismissSubWindow(TabControl.Tab t) {
Patrick Scottd0119532009-09-17 08:00:31 -04001911 t.removeSubWindow(mContentView);
1912 // Tell the TabControl to dismiss the subwindow. This will destroy
1913 // the WebView.
1914 mTabControl.dismissSubWindow(t);
1915 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001916 }
1917
Leon Scroggins1f005d32009-08-10 17:36:42 -04001918 // A wrapper function of {@link #openTabAndShow(UrlData, boolean, String)}
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07001919 // that accepts url as string.
Leon Scroggins1f005d32009-08-10 17:36:42 -04001920 private TabControl.Tab openTabAndShow(String url, boolean closeOnExit,
1921 String appId) {
1922 return openTabAndShow(new UrlData(url), closeOnExit, appId);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001923 }
1924
1925 // This method does a ton of stuff. It will attempt to create a new tab
1926 // if we haven't reached MAX_TABS. Otherwise it uses the current tab. If
Leon Scroggins1f005d32009-08-10 17:36:42 -04001927 // url isn't null, it will load the given url.
1928 /* package */ TabControl.Tab openTabAndShow(UrlData urlData,
The Android Open Source Projectf59ec872009-03-13 13:04:24 -07001929 boolean closeOnExit, String appId) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001930 final boolean newTab = mTabControl.getTabCount() != TabControl.MAX_TABS;
1931 final TabControl.Tab currentTab = mTabControl.getCurrentTab();
1932 if (newTab) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001933 final TabControl.Tab tab = mTabControl.createNewTab(
1934 closeOnExit, appId, urlData.mUrl);
1935 WebView webview = tab.getWebView();
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001936 // If the last tab was removed from the active tabs page, currentTab
1937 // will be null.
1938 if (currentTab != null) {
1939 removeTabFromContentView(currentTab);
1940 }
Patrick Scott8bbd69f2009-08-14 13:35:53 -04001941 // We must set the new tab as the current tab to reflect the old
1942 // animation behavior.
1943 mTabControl.setCurrentTab(tab);
Grace Klobaeb6eef42009-09-15 17:56:32 -07001944 attachTabToContentView(tab);
Leon Scroggins160a7e72009-08-14 18:28:01 -04001945 if (!urlData.isEmpty()) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001946 urlData.loadIn(webview);
1947 }
1948 return tab;
1949 } else {
1950 // Get rid of the subwindow if it exists
1951 dismissSubWindow(currentTab);
1952 if (!urlData.isEmpty()) {
1953 // Load the given url.
1954 urlData.loadIn(currentTab.getWebView());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001955 }
1956 }
Grace Klobac9181842009-04-14 08:53:22 -07001957 return currentTab;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001958 }
1959
Grace Klobac9181842009-04-14 08:53:22 -07001960 private TabControl.Tab openTab(String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001961 if (mSettings.openInBackground()) {
The Android Open Source Projectf59ec872009-03-13 13:04:24 -07001962 TabControl.Tab t = mTabControl.createNewTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001963 if (t != null) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001964 WebView view = t.getWebView();
Leon Scroggins1f005d32009-08-10 17:36:42 -04001965 view.loadUrl(url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001966 }
Grace Klobac9181842009-04-14 08:53:22 -07001967 return t;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001968 } else {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001969 return openTabAndShow(url, false, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001970 }
1971 }
1972
1973 private class Copy implements OnMenuItemClickListener {
1974 private CharSequence mText;
1975
1976 public boolean onMenuItemClick(MenuItem item) {
1977 copy(mText);
1978 return true;
1979 }
1980
1981 public Copy(CharSequence toCopy) {
1982 mText = toCopy;
1983 }
1984 }
1985
1986 private class Download implements OnMenuItemClickListener {
1987 private String mText;
1988
1989 public boolean onMenuItemClick(MenuItem item) {
1990 onDownloadStartNoStream(mText, null, null, null, -1);
1991 return true;
1992 }
1993
1994 public Download(String toDownload) {
1995 mText = toDownload;
1996 }
1997 }
1998
1999 private void copy(CharSequence text) {
2000 try {
2001 IClipboard clip = IClipboard.Stub.asInterface(ServiceManager.getService("clipboard"));
2002 if (clip != null) {
2003 clip.setClipboardText(text);
2004 }
2005 } catch (android.os.RemoteException e) {
2006 Log.e(LOGTAG, "Copy failed", e);
2007 }
2008 }
2009
2010 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08002011 * Resets the browser title-view to whatever it must be
2012 * (for example, if we had a loading error)
2013 * When we have a new page, we call resetTitle, when we
2014 * have to reset the titlebar to whatever it used to be
2015 * (for example, if the user chose to stop loading), we
2016 * call resetTitleAndRevertLockIcon.
2017 */
2018 /* package */ void resetTitleAndRevertLockIcon() {
2019 revertLockIcon();
2020 resetTitleIconAndProgress();
2021 }
2022
2023 /**
2024 * Reset the title, favicon, and progress.
2025 */
2026 private void resetTitleIconAndProgress() {
2027 WebView current = mTabControl.getCurrentWebView();
2028 if (current == null) {
2029 return;
2030 }
2031 resetTitleAndIcon(current);
2032 int progress = current.getProgress();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002033 mWebChromeClient.onProgressChanged(current, progress);
2034 }
2035
2036 // Reset the title and the icon based on the given item.
2037 private void resetTitleAndIcon(WebView view) {
2038 WebHistoryItem item = view.copyBackForwardList().getCurrentItem();
2039 if (item != null) {
Leon Scroggins68579392009-09-15 15:31:54 -04002040 setUrlTitle(item.getUrl(), item.getTitle());
The Android Open Source Project0c908882009-03-03 19:32:16 -08002041 setFavicon(item.getFavicon());
2042 } else {
Leon Scroggins68579392009-09-15 15:31:54 -04002043 setUrlTitle(null, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002044 setFavicon(null);
2045 }
2046 }
2047
2048 /**
2049 * Sets a title composed of the URL and the title string.
2050 * @param url The URL of the site being loaded.
2051 * @param title The title of the site being loaded.
2052 */
Leon Scroggins68579392009-09-15 15:31:54 -04002053 private void setUrlTitle(String url, String title) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002054 mUrl = url;
2055 mTitle = title;
2056
Leon Scroggins68579392009-09-15 15:31:54 -04002057 mTitleBar.setTitleAndUrl(title, url);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04002058 if (mFakeTitleBar != null) {
2059 mFakeTitleBar.setTitleAndUrl(title, url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002060 }
2061 }
2062
2063 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08002064 * @param url The URL to build a title version of the URL from.
2065 * @return The title version of the URL or null if fails.
2066 * The title version of the URL can be either the URL hostname,
2067 * or the hostname with an "https://" prefix (for secure URLs),
2068 * or an empty string if, for example, the URL in question is a
2069 * file:// URL with no hostname.
2070 */
Leon Scroggins32e14a62009-06-11 10:26:34 -04002071 /* package */ static String buildTitleUrl(String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002072 String titleUrl = null;
2073
2074 if (url != null) {
2075 try {
2076 // parse the url string
2077 URL urlObj = new URL(url);
2078 if (urlObj != null) {
2079 titleUrl = "";
2080
2081 String protocol = urlObj.getProtocol();
2082 String host = urlObj.getHost();
2083
2084 if (host != null && 0 < host.length()) {
2085 titleUrl = host;
2086 if (protocol != null) {
2087 // if a secure site, add an "https://" prefix!
2088 if (protocol.equalsIgnoreCase("https")) {
2089 titleUrl = protocol + "://" + host;
2090 }
2091 }
2092 }
2093 }
2094 } catch (MalformedURLException e) {}
2095 }
2096
2097 return titleUrl;
2098 }
2099
2100 // Set the favicon in the title bar.
2101 private void setFavicon(Bitmap icon) {
Leon Scroggins68579392009-09-15 15:31:54 -04002102 mTitleBar.setFavicon(icon);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04002103 if (mFakeTitleBar != null) {
2104 mFakeTitleBar.setFavicon(icon);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002105 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002106 }
2107
2108 /**
2109 * Saves the current lock-icon state before resetting
2110 * the lock icon. If we have an error, we may need to
2111 * roll back to the previous state.
2112 */
2113 private void saveLockIcon() {
2114 mPrevLockType = mLockIconType;
2115 }
2116
2117 /**
2118 * Reverts the lock-icon state to the last saved state,
2119 * for example, if we had an error, and need to cancel
2120 * the load.
2121 */
2122 private void revertLockIcon() {
2123 mLockIconType = mPrevLockType;
2124
Dave Bort31a6d1c2009-04-13 15:56:49 -07002125 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002126 Log.v(LOGTAG, "BrowserActivity.revertLockIcon:" +
2127 " revert lock icon to " + mLockIconType);
2128 }
2129
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04002130 updateLockIconToLatest();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002131 }
2132
Leon Scroggins1f005d32009-08-10 17:36:42 -04002133 /**
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002134 * Close the tab, remove its associated title bar, and adjust mTabControl's
2135 * current tab to a valid value.
Leon Scroggins1f005d32009-08-10 17:36:42 -04002136 */
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002137 /* package */ void closeTab(TabControl.Tab t) {
2138 int currentIndex = mTabControl.getCurrentIndex();
2139 int removeIndex = mTabControl.getTabIndex(t);
Leon Scroggins1f005d32009-08-10 17:36:42 -04002140 mTabControl.removeTab(t);
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002141 if (currentIndex >= removeIndex && currentIndex != 0) {
2142 currentIndex--;
2143 }
2144 mTabControl.setCurrentTab(mTabControl.getTab(currentIndex));
Andrei Popescua5bf1de2009-09-23 16:39:23 +01002145 resetTitleIconAndProgress();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002146 }
2147
2148 private void goBackOnePageOrQuit() {
2149 TabControl.Tab current = mTabControl.getCurrentTab();
2150 if (current == null) {
2151 /*
2152 * Instead of finishing the activity, simply push this to the back
2153 * of the stack and let ActivityManager to choose the foreground
2154 * activity. As BrowserActivity is singleTask, it will be always the
2155 * root of the task. So we can use either true or false for
2156 * moveTaskToBack().
2157 */
2158 moveTaskToBack(true);
Grace Kloba00d85e72009-09-23 18:50:05 -07002159 return;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002160 }
2161 WebView w = current.getWebView();
2162 if (w.canGoBack()) {
2163 w.goBack();
2164 } else {
2165 // Check to see if we are closing a window that was created by
2166 // another window. If so, we switch back to that window.
2167 TabControl.Tab parent = current.getParentTab();
2168 if (parent != null) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04002169 switchToTab(mTabControl.getTabIndex(parent));
2170 // Now we close the other tab
2171 closeTab(current);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002172 } else {
2173 if (current.closeOnExit()) {
Grace Klobabb0af5c2009-09-01 00:56:09 -07002174 // force mPageStarted to be false as we are going to either
2175 // finish the activity or remove the tab. This will ensure
2176 // pauseWebView() taking action.
2177 mPageStarted = false;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002178 if (mTabControl.getTabCount() == 1) {
2179 finish();
2180 return;
2181 }
Mike Reed7bfa63b2009-05-28 11:08:32 -04002182 // call pauseWebViewTimers() now, we won't be able to call
2183 // it in onPause() as the WebView won't be valid.
Grace Klobaec1b5ad2009-08-18 08:42:32 -07002184 // Temporarily change mActivityInPause to be true as
2185 // pauseWebViewTimers() will do nothing if mActivityInPause
2186 // is false.
Grace Kloba918e1d72009-08-13 14:55:06 -07002187 boolean savedState = mActivityInPause;
2188 if (savedState) {
Grace Klobaec1b5ad2009-08-18 08:42:32 -07002189 Log.e(LOGTAG, "BrowserActivity is already paused "
2190 + "while handing goBackOnePageOrQuit.");
Grace Kloba918e1d72009-08-13 14:55:06 -07002191 }
2192 mActivityInPause = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -04002193 pauseWebViewTimers();
Grace Kloba918e1d72009-08-13 14:55:06 -07002194 mActivityInPause = savedState;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002195 removeTabFromContentView(current);
2196 mTabControl.removeTab(current);
2197 }
2198 /*
2199 * Instead of finishing the activity, simply push this to the back
2200 * of the stack and let ActivityManager to choose the foreground
2201 * activity. As BrowserActivity is singleTask, it will be always the
2202 * root of the task. So we can use either true or false for
2203 * moveTaskToBack().
2204 */
2205 moveTaskToBack(true);
2206 }
2207 }
2208 }
2209
Grace Kloba5942df02009-09-18 11:48:29 -07002210 @Override
2211 public boolean onKeyDown(int keyCode, KeyEvent event) {
2212 // The default key mode is DEFAULT_KEYS_SEARCH_LOCAL. As the MENU is
2213 // still down, we don't want to trigger the search. Pretend to consume
2214 // the key and do nothing.
2215 if (mMenuIsDown) return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002216
Grace Kloba5942df02009-09-18 11:48:29 -07002217 switch(keyCode) {
2218 case KeyEvent.KEYCODE_MENU:
2219 mMenuIsDown = true;
2220 break;
2221 case KeyEvent.KEYCODE_SPACE:
Grace Klobada0fe552009-09-22 18:17:24 -07002222 // WebView/WebTextView handle the keys in the KeyDown. As
2223 // the Activity's shortcut keys are only handled when WebView
2224 // doesn't, have to do it in onKeyDown instead of onKeyUp.
2225 if (event.isShiftPressed()) {
2226 getTopWindow().pageUp(false);
2227 } else {
2228 getTopWindow().pageDown(false);
2229 }
Grace Kloba5942df02009-09-18 11:48:29 -07002230 return true;
2231 case KeyEvent.KEYCODE_BACK:
2232 if (event.getRepeatCount() == 0) {
2233 event.startTracking();
2234 return true;
2235 } else if (mCustomView == null && mActiveTabsPage == null
2236 && event.isLongPress()) {
2237 bookmarksOrHistoryPicker(true);
2238 return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002239 }
Grace Kloba5942df02009-09-18 11:48:29 -07002240 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002241 }
Grace Kloba5942df02009-09-18 11:48:29 -07002242 return super.onKeyDown(keyCode, event);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002243 }
2244
Grace Kloba5942df02009-09-18 11:48:29 -07002245 @Override
2246 public boolean onKeyUp(int keyCode, KeyEvent event) {
2247 switch(keyCode) {
2248 case KeyEvent.KEYCODE_MENU:
2249 mMenuIsDown = false;
2250 break;
Grace Kloba5942df02009-09-18 11:48:29 -07002251 case KeyEvent.KEYCODE_BACK:
2252 if (event.isTracking() && !event.isCanceled()) {
2253 if (mCustomView != null) {
2254 // if a custom view is showing, hide it
2255 mWebChromeClient.onHideCustomView();
2256 } else if (mActiveTabsPage != null) {
2257 // if tab page is showing, hide it
2258 removeActiveTabPage(true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002259 } else {
Grace Kloba5942df02009-09-18 11:48:29 -07002260 WebView subwindow = mTabControl.getCurrentSubWindow();
2261 if (subwindow != null) {
2262 if (subwindow.canGoBack()) {
2263 subwindow.goBack();
2264 } else {
2265 dismissSubWindow(mTabControl.getCurrentTab());
2266 }
2267 } else {
2268 goBackOnePageOrQuit();
2269 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002270 }
Grace Kloba5942df02009-09-18 11:48:29 -07002271 return true;
2272 }
2273 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002274 }
Grace Kloba5942df02009-09-18 11:48:29 -07002275 return super.onKeyUp(keyCode, event);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002276 }
2277
Leon Scroggins68579392009-09-15 15:31:54 -04002278 /* package */ void stopLoading() {
Ben Murdochb7cc8b42009-09-28 10:59:09 +01002279 mDidStopLoad = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002280 resetTitleAndRevertLockIcon();
2281 WebView w = getTopWindow();
2282 w.stopLoading();
2283 mWebViewClient.onPageFinished(w, w.getUrl());
2284
2285 cancelStopToast();
2286 mStopToast = Toast
2287 .makeText(this, R.string.stopping, Toast.LENGTH_SHORT);
2288 mStopToast.show();
2289 }
2290
2291 private void cancelStopToast() {
2292 if (mStopToast != null) {
2293 mStopToast.cancel();
2294 mStopToast = null;
2295 }
2296 }
2297
2298 // called by a non-UI thread to post the message
2299 public void postMessage(int what, int arg1, int arg2, Object obj) {
2300 mHandler.sendMessage(mHandler.obtainMessage(what, arg1, arg2, obj));
2301 }
2302
2303 // public message ids
2304 public final static int LOAD_URL = 1001;
2305 public final static int STOP_LOAD = 1002;
2306
2307 // Message Ids
2308 private static final int FOCUS_NODE_HREF = 102;
2309 private static final int CANCEL_CREDS_REQUEST = 103;
Grace Kloba92c18a52009-07-31 23:48:32 -07002310 private static final int RELEASE_WAKELOCK = 107;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002311
2312 // Private handler for handling javascript and saving passwords
2313 private Handler mHandler = new Handler() {
2314
2315 public void handleMessage(Message msg) {
2316 switch (msg.what) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002317 case FOCUS_NODE_HREF:
2318 String url = (String) msg.getData().get("url");
2319 if (url == null || url.length() == 0) {
2320 break;
2321 }
2322 HashMap focusNodeMap = (HashMap) msg.obj;
2323 WebView view = (WebView) focusNodeMap.get("webview");
2324 // Only apply the action if the top window did not change.
2325 if (getTopWindow() != view) {
2326 break;
2327 }
2328 switch (msg.arg1) {
2329 case R.id.open_context_menu_id:
2330 case R.id.view_image_context_menu_id:
2331 loadURL(getTopWindow(), url);
2332 break;
2333 case R.id.open_newtab_context_menu_id:
Grace Klobac9181842009-04-14 08:53:22 -07002334 final TabControl.Tab parent = mTabControl
2335 .getCurrentTab();
2336 final TabControl.Tab newTab = openTab(url);
2337 if (newTab != parent) {
2338 parent.addChildTab(newTab);
2339 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002340 break;
2341 case R.id.bookmark_context_menu_id:
2342 Intent intent = new Intent(BrowserActivity.this,
2343 AddBookmarkPage.class);
2344 intent.putExtra("url", url);
2345 startActivity(intent);
2346 break;
2347 case R.id.share_link_context_menu_id:
Andrei Popescu10fdba82009-09-24 13:25:47 +01002348 Browser.sendString(BrowserActivity.this, url,
2349 getText(R.string.choosertitle_sharevia).toString());
The Android Open Source Project0c908882009-03-03 19:32:16 -08002350 break;
2351 case R.id.copy_link_context_menu_id:
2352 copy(url);
2353 break;
2354 case R.id.save_link_context_menu_id:
2355 case R.id.download_context_menu_id:
2356 onDownloadStartNoStream(url, null, null, null, -1);
2357 break;
2358 }
2359 break;
2360
2361 case LOAD_URL:
2362 loadURL(getTopWindow(), (String) msg.obj);
2363 break;
2364
2365 case STOP_LOAD:
2366 stopLoading();
2367 break;
2368
2369 case CANCEL_CREDS_REQUEST:
2370 resumeAfterCredentials();
2371 break;
2372
The Android Open Source Project0c908882009-03-03 19:32:16 -08002373 case RELEASE_WAKELOCK:
2374 if (mWakeLock.isHeld()) {
2375 mWakeLock.release();
2376 }
2377 break;
2378 }
2379 }
2380 };
2381
Leon Scroggins89c6d362009-07-15 16:54:37 -04002382 private void updateScreenshot(WebView view) {
2383 // If this is a bookmarked site, add a screenshot to the database.
2384 // FIXME: When should we update? Every time?
2385 // FIXME: Would like to make sure there is actually something to
2386 // draw, but the API for that (WebViewCore.pictureReady()) is not
2387 // currently accessible here.
Ben Murdochaac7aa62009-09-17 16:57:40 +01002388
Patrick Scott3918d442009-08-04 13:22:29 -04002389 ContentResolver cr = getContentResolver();
2390 final Cursor c = BrowserBookmarksAdapter.queryBookmarksForUrl(
Ben Murdochaac7aa62009-09-17 16:57:40 +01002391 cr, view.getOriginalUrl(), view.getUrl(), true);
Patrick Scott3918d442009-08-04 13:22:29 -04002392 if (c != null) {
Leon Scroggins89c6d362009-07-15 16:54:37 -04002393 boolean succeed = c.moveToFirst();
2394 ContentValues values = null;
2395 while (succeed) {
2396 if (values == null) {
2397 final ByteArrayOutputStream os
2398 = new ByteArrayOutputStream();
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002399 Bitmap bm = createScreenshot(view);
Leon Scroggins89c6d362009-07-15 16:54:37 -04002400 bm.compress(Bitmap.CompressFormat.PNG, 100, os);
2401 values = new ContentValues();
2402 values.put(Browser.BookmarkColumns.THUMBNAIL,
2403 os.toByteArray());
2404 }
2405 cr.update(ContentUris.withAppendedId(Browser.BOOKMARKS_URI,
2406 c.getInt(0)), values, null, null);
2407 succeed = c.moveToNext();
2408 }
2409 c.close();
2410 }
2411 }
2412
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002413 /**
Leon Scrogginsf8551612009-09-24 16:06:02 -04002414 * Values for the size of the thumbnail created when taking a screenshot.
2415 * Lazily initialized. Instead of using these directly, use
2416 * getDesiredThumbnailWidth() or getDesiredThumbnailHeight().
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002417 */
Leon Scrogginsf8551612009-09-24 16:06:02 -04002418 private static int THUMBNAIL_WIDTH = 0;
2419 private static int THUMBNAIL_HEIGHT = 0;
2420
2421 /**
2422 * Return the desired width for thumbnail screenshots, which are stored in
2423 * the database, and used on the bookmarks screen.
2424 * @param context Context for finding out the density of the screen.
2425 * @return int desired width for thumbnail screenshot.
2426 */
2427 /* package */ static int getDesiredThumbnailWidth(Context context) {
2428 if (THUMBNAIL_WIDTH == 0) {
2429 float density = context.getResources().getDisplayMetrics().density;
2430 THUMBNAIL_WIDTH = (int) (90 * density);
2431 THUMBNAIL_HEIGHT = (int) (80 * density);
2432 }
2433 return THUMBNAIL_WIDTH;
2434 }
2435
2436 /**
2437 * Return the desired height for thumbnail screenshots, which are stored in
2438 * the database, and used on the bookmarks screen.
2439 * @param context Context for finding out the density of the screen.
2440 * @return int desired height for thumbnail screenshot.
2441 */
2442 /* package */ static int getDesiredThumbnailHeight(Context context) {
2443 // To ensure that they are both initialized.
2444 getDesiredThumbnailWidth(context);
2445 return THUMBNAIL_HEIGHT;
2446 }
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002447
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002448 private Bitmap createScreenshot(WebView view) {
2449 Picture thumbnail = view.capturePicture();
Leon Scrogginsf8551612009-09-24 16:06:02 -04002450 Bitmap bm = Bitmap.createBitmap(getDesiredThumbnailWidth(this),
2451 getDesiredThumbnailHeight(this), Bitmap.Config.ARGB_4444);
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002452 Canvas canvas = new Canvas(bm);
2453 // May need to tweak these values to determine what is the
2454 // best scale factor
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002455 int contentWidth = view.getContentWidth();
2456 if (contentWidth > 0) {
Leon Scrogginsf8551612009-09-24 16:06:02 -04002457 float scaleFactor = (float) getDesiredThumbnailWidth(this)
2458 / (float) contentWidth;
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002459 canvas.scale(scaleFactor, scaleFactor);
2460 }
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002461 thumbnail.draw(canvas);
2462 return bm;
2463 }
2464
The Android Open Source Project0c908882009-03-03 19:32:16 -08002465 // -------------------------------------------------------------------------
2466 // WebViewClient implementation.
2467 //-------------------------------------------------------------------------
2468
2469 // Use in overrideUrlLoading
2470 /* package */ final static String SCHEME_WTAI = "wtai://wp/";
2471 /* package */ final static String SCHEME_WTAI_MC = "wtai://wp/mc;";
2472 /* package */ final static String SCHEME_WTAI_SD = "wtai://wp/sd;";
2473 /* package */ final static String SCHEME_WTAI_AP = "wtai://wp/ap;";
2474
2475 /* package */ WebViewClient getWebViewClient() {
2476 return mWebViewClient;
2477 }
2478
Patrick Scott3918d442009-08-04 13:22:29 -04002479 private void updateIcon(WebView view, Bitmap icon) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002480 if (icon != null) {
2481 BrowserBookmarksAdapter.updateBookmarkFavicon(mResolver,
Patrick Scott15525d42009-09-21 13:39:37 -04002482 view.getOriginalUrl(), view.getUrl(), icon);
2483 }
2484 setFavicon(icon);
2485 }
2486
2487 private void updateIcon(String url, Bitmap icon) {
2488 if (icon != null) {
2489 BrowserBookmarksAdapter.updateBookmarkFavicon(mResolver,
2490 null, url, icon);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002491 }
2492 setFavicon(icon);
2493 }
2494
2495 private final WebViewClient mWebViewClient = new WebViewClient() {
2496 @Override
2497 public void onPageStarted(WebView view, String url, Bitmap favicon) {
2498 resetLockIcon(url);
Leon Scroggins68579392009-09-15 15:31:54 -04002499 setUrlTitle(url, null);
Ben Murdochbff2d602009-07-01 20:19:05 +01002500
Patrick Scott59ce8302009-09-18 16:29:38 -04002501 // If we start a touch icon load and then load a new page, we don't
2502 // want to cancel the current touch icon loader. But, we do want to
2503 // create a new one when the touch icon url is known.
2504 if (mTouchIconLoader != null) {
2505 mTouchIconLoader.mActivity = null;
2506 mTouchIconLoader = null;
2507 }
2508
Ben Murdochbff2d602009-07-01 20:19:05 +01002509 ErrorConsoleView errorConsole = mTabControl.getCurrentErrorConsole(false);
2510 if (errorConsole != null) {
2511 errorConsole.clearErrorMessages();
2512 if (mShouldShowErrorConsole) {
2513 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
2514 }
2515 }
2516
The Android Open Source Project0c908882009-03-03 19:32:16 -08002517 // Call updateIcon instead of setFavicon so the bookmark
2518 // database can be updated.
Patrick Scott15525d42009-09-21 13:39:37 -04002519 updateIcon(url, favicon);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002520
Grace Kloba4d7880f2009-08-12 09:35:42 -07002521 if (mSettings.isTracing()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002522 String host;
2523 try {
2524 WebAddress uri = new WebAddress(url);
2525 host = uri.mHost;
2526 } catch (android.net.ParseException ex) {
Grace Kloba4d7880f2009-08-12 09:35:42 -07002527 host = "browser";
The Android Open Source Project0c908882009-03-03 19:32:16 -08002528 }
2529 host = host.replace('.', '_');
Grace Kloba4d7880f2009-08-12 09:35:42 -07002530 host += ".trace";
The Android Open Source Project0c908882009-03-03 19:32:16 -08002531 mInTrace = true;
Grace Kloba4d7880f2009-08-12 09:35:42 -07002532 Debug.startMethodTracing(host, 20 * 1024 * 1024);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002533 }
2534
2535 // Performance probe
2536 if (false) {
2537 mStart = SystemClock.uptimeMillis();
2538 mProcessStart = Process.getElapsedCpuTime();
2539 long[] sysCpu = new long[7];
2540 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2541 sysCpu, null)) {
2542 mUserStart = sysCpu[0] + sysCpu[1];
2543 mSystemStart = sysCpu[2];
2544 mIdleStart = sysCpu[3];
2545 mIrqStart = sysCpu[4] + sysCpu[5] + sysCpu[6];
2546 }
2547 mUiStart = SystemClock.currentThreadTimeMillis();
2548 }
2549
2550 if (!mPageStarted) {
2551 mPageStarted = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -04002552 // if onResume() has been called, resumeWebViewTimers() does
2553 // nothing.
2554 resumeWebViewTimers();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002555 }
2556
2557 // reset sync timer to avoid sync starts during loading a page
2558 CookieSyncManager.getInstance().resetSync();
2559
2560 mInLoad = true;
Ben Murdochb7cc8b42009-09-28 10:59:09 +01002561 mDidStopLoad = false;
Leon Scroggins184f5e32009-09-21 10:38:24 -04002562 showFakeTitleBar();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002563 updateInLoadMenuItems();
2564 if (!mIsNetworkUp) {
Patrick Scotteb6ab2a2009-09-16 10:00:17 -04002565 createAndShowNetworkDialog();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002566 if (view != null) {
2567 view.setNetworkAvailable(false);
2568 }
2569 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002570 }
2571
2572 @Override
2573 public void onPageFinished(WebView view, String url) {
2574 // Reset the title and icon in case we stopped a provisional
2575 // load.
2576 resetTitleAndIcon(view);
Ben Murdochb7cc8b42009-09-28 10:59:09 +01002577
2578 if (!mDidStopLoad) {
2579 // Only update the bookmark screenshot if the user did not
2580 // cancel the load early.
2581 updateScreenshot(view);
2582 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002583
2584 // Update the lock icon image only once we are done loading
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04002585 updateLockIconToLatest();
Leon Scrogginsb6b7f9e2009-06-18 12:05:28 -04002586
The Android Open Source Project0c908882009-03-03 19:32:16 -08002587 // Performance probe
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07002588 if (false) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002589 long[] sysCpu = new long[7];
2590 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2591 sysCpu, null)) {
2592 String uiInfo = "UI thread used "
2593 + (SystemClock.currentThreadTimeMillis() - mUiStart)
2594 + " ms";
Dave Bort31a6d1c2009-04-13 15:56:49 -07002595 if (LOGD_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002596 Log.d(LOGTAG, uiInfo);
2597 }
2598 //The string that gets written to the log
2599 String performanceString = "It took total "
2600 + (SystemClock.uptimeMillis() - mStart)
2601 + " ms clock time to load the page."
2602 + "\nbrowser process used "
2603 + (Process.getElapsedCpuTime() - mProcessStart)
2604 + " ms, user processes used "
2605 + (sysCpu[0] + sysCpu[1] - mUserStart) * 10
2606 + " ms, kernel used "
2607 + (sysCpu[2] - mSystemStart) * 10
2608 + " ms, idle took " + (sysCpu[3] - mIdleStart) * 10
2609 + " ms and irq took "
2610 + (sysCpu[4] + sysCpu[5] + sysCpu[6] - mIrqStart)
2611 * 10 + " ms, " + uiInfo;
Dave Bort31a6d1c2009-04-13 15:56:49 -07002612 if (LOGD_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002613 Log.d(LOGTAG, performanceString + "\nWebpage: " + url);
2614 }
2615 if (url != null) {
2616 // strip the url to maintain consistency
2617 String newUrl = new String(url);
2618 if (newUrl.startsWith("http://www.")) {
2619 newUrl = newUrl.substring(11);
2620 } else if (newUrl.startsWith("http://")) {
2621 newUrl = newUrl.substring(7);
2622 } else if (newUrl.startsWith("https://www.")) {
2623 newUrl = newUrl.substring(12);
2624 } else if (newUrl.startsWith("https://")) {
2625 newUrl = newUrl.substring(8);
2626 }
Dave Bort31a6d1c2009-04-13 15:56:49 -07002627 if (LOGD_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002628 Log.d(LOGTAG, newUrl + " loaded");
2629 }
2630 /*
2631 if (sWhiteList.contains(newUrl)) {
2632 // The string that gets pushed to the statistcs
2633 // service
2634 performanceString = performanceString
2635 + "\nWebpage: "
2636 + newUrl
2637 + "\nCarrier: "
2638 + android.os.SystemProperties
2639 .get("gsm.sim.operator.alpha");
2640 if (mWebView != null
2641 && mWebView.getContext() != null
2642 && mWebView.getContext().getSystemService(
2643 Context.CONNECTIVITY_SERVICE) != null) {
2644 ConnectivityManager cManager =
2645 (ConnectivityManager) mWebView
2646 .getContext().getSystemService(
2647 Context.CONNECTIVITY_SERVICE);
2648 NetworkInfo nInfo = cManager
2649 .getActiveNetworkInfo();
2650 if (nInfo != null) {
2651 performanceString = performanceString
2652 + "\nNetwork Type: "
2653 + nInfo.getType().toString();
2654 }
2655 }
2656 Checkin.logEvent(mResolver,
2657 Checkin.Events.Tag.WEBPAGE_LOAD,
2658 performanceString);
2659 Log.w(LOGTAG, "pushed to the statistics service");
2660 }
2661 */
2662 }
2663 }
2664 }
2665
2666 if (mInTrace) {
2667 mInTrace = false;
2668 Debug.stopMethodTracing();
2669 }
2670
2671 if (mPageStarted) {
2672 mPageStarted = false;
Mike Reed7bfa63b2009-05-28 11:08:32 -04002673 // pauseWebViewTimers() will do nothing and return false if
2674 // onPause() is not called yet.
2675 if (pauseWebViewTimers()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002676 if (mWakeLock.isHeld()) {
2677 mHandler.removeMessages(RELEASE_WAKELOCK);
2678 mWakeLock.release();
2679 }
2680 }
2681 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002682 }
2683
2684 // return true if want to hijack the url to let another app to handle it
2685 @Override
2686 public boolean shouldOverrideUrlLoading(WebView view, String url) {
2687 if (url.startsWith(SCHEME_WTAI)) {
2688 // wtai://wp/mc;number
2689 // number=string(phone-number)
2690 if (url.startsWith(SCHEME_WTAI_MC)) {
2691 Intent intent = new Intent(Intent.ACTION_VIEW,
2692 Uri.parse(WebView.SCHEME_TEL +
2693 url.substring(SCHEME_WTAI_MC.length())));
2694 startActivity(intent);
2695 return true;
2696 }
2697 // wtai://wp/sd;dtmf
2698 // dtmf=string(dialstring)
2699 if (url.startsWith(SCHEME_WTAI_SD)) {
2700 // TODO
2701 // only send when there is active voice connection
2702 return false;
2703 }
2704 // wtai://wp/ap;number;name
2705 // number=string(phone-number)
2706 // name=string
2707 if (url.startsWith(SCHEME_WTAI_AP)) {
2708 // TODO
2709 return false;
2710 }
2711 }
2712
Dianne Hackborn99189432009-06-17 18:06:18 -07002713 // The "about:" schemes are internal to the browser; don't
2714 // want these to be dispatched to other apps.
2715 if (url.startsWith("about:")) {
2716 return false;
2717 }
Ben Murdochbff2d602009-07-01 20:19:05 +01002718
Dianne Hackborn99189432009-06-17 18:06:18 -07002719 Intent intent;
Ben Murdochbff2d602009-07-01 20:19:05 +01002720
Dianne Hackborn99189432009-06-17 18:06:18 -07002721 // perform generic parsing of the URI to turn it into an Intent.
The Android Open Source Project0c908882009-03-03 19:32:16 -08002722 try {
Dianne Hackborn99189432009-06-17 18:06:18 -07002723 intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME);
2724 } catch (URISyntaxException ex) {
2725 Log.w("Browser", "Bad URI " + url + ": " + ex.getMessage());
The Android Open Source Project0c908882009-03-03 19:32:16 -08002726 return false;
2727 }
2728
Grace Kloba5b078b52009-06-24 20:23:41 -07002729 // check whether the intent can be resolved. If not, we will see
2730 // whether we can download it from the Market.
2731 if (getPackageManager().resolveActivity(intent, 0) == null) {
2732 String packagename = intent.getPackage();
2733 if (packagename != null) {
2734 intent = new Intent(Intent.ACTION_VIEW, Uri
2735 .parse("market://search?q=pname:" + packagename));
2736 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2737 startActivity(intent);
2738 return true;
2739 } else {
2740 return false;
2741 }
2742 }
2743
Dianne Hackborn99189432009-06-17 18:06:18 -07002744 // sanitize the Intent, ensuring web pages can not bypass browser
2745 // security (only access to BROWSABLE activities).
The Android Open Source Project0c908882009-03-03 19:32:16 -08002746 intent.addCategory(Intent.CATEGORY_BROWSABLE);
Dianne Hackborn99189432009-06-17 18:06:18 -07002747 intent.setComponent(null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002748 try {
2749 if (startActivityIfNeeded(intent, -1)) {
2750 return true;
2751 }
2752 } catch (ActivityNotFoundException ex) {
2753 // ignore the error. If no application can handle the URL,
2754 // eg about:blank, assume the browser can handle it.
2755 }
2756
2757 if (mMenuIsDown) {
2758 openTab(url);
2759 closeOptionsMenu();
2760 return true;
2761 }
2762
2763 return false;
2764 }
2765
2766 /**
2767 * Updates the lock icon. This method is called when we discover another
2768 * resource to be loaded for this page (for example, javascript). While
2769 * we update the icon type, we do not update the lock icon itself until
2770 * we are done loading, it is slightly more secure this way.
2771 */
2772 @Override
2773 public void onLoadResource(WebView view, String url) {
2774 if (url != null && url.length() > 0) {
2775 // It is only if the page claims to be secure
2776 // that we may have to update the lock:
2777 if (mLockIconType == LOCK_ICON_SECURE) {
2778 // If NOT a 'safe' url, change the lock to mixed content!
2779 if (!(URLUtil.isHttpsUrl(url) || URLUtil.isDataUrl(url) || URLUtil.isAboutUrl(url))) {
2780 mLockIconType = LOCK_ICON_MIXED;
Dave Bort31a6d1c2009-04-13 15:56:49 -07002781 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002782 Log.v(LOGTAG, "BrowserActivity.updateLockIcon:" +
2783 " updated lock icon to " + mLockIconType + " due to " + url);
2784 }
2785 }
2786 }
2787 }
2788 }
2789
2790 /**
2791 * Show the dialog, asking the user if they would like to continue after
2792 * an excessive number of HTTP redirects.
2793 */
2794 @Override
2795 public void onTooManyRedirects(WebView view, final Message cancelMsg,
2796 final Message continueMsg) {
2797 new AlertDialog.Builder(BrowserActivity.this)
2798 .setTitle(R.string.browserFrameRedirect)
2799 .setMessage(R.string.browserFrame307Post)
2800 .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
2801 public void onClick(DialogInterface dialog, int which) {
2802 continueMsg.sendToTarget();
2803 }})
2804 .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
2805 public void onClick(DialogInterface dialog, int which) {
2806 cancelMsg.sendToTarget();
2807 }})
2808 .setOnCancelListener(new OnCancelListener() {
2809 public void onCancel(DialogInterface dialog) {
2810 cancelMsg.sendToTarget();
2811 }})
2812 .show();
2813 }
2814
Patrick Scott37911c72009-03-24 18:02:58 -07002815 // Container class for the next error dialog that needs to be
2816 // displayed.
2817 class ErrorDialog {
2818 public final int mTitle;
2819 public final String mDescription;
2820 public final int mError;
2821 ErrorDialog(int title, String desc, int error) {
2822 mTitle = title;
2823 mDescription = desc;
2824 mError = error;
2825 }
2826 };
2827
2828 private void processNextError() {
2829 if (mQueuedErrors == null) {
2830 return;
2831 }
2832 // The first one is currently displayed so just remove it.
2833 mQueuedErrors.removeFirst();
2834 if (mQueuedErrors.size() == 0) {
2835 mQueuedErrors = null;
2836 return;
2837 }
2838 showError(mQueuedErrors.getFirst());
2839 }
2840
2841 private DialogInterface.OnDismissListener mDialogListener =
2842 new DialogInterface.OnDismissListener() {
2843 public void onDismiss(DialogInterface d) {
2844 processNextError();
2845 }
2846 };
2847 private LinkedList<ErrorDialog> mQueuedErrors;
2848
2849 private void queueError(int err, String desc) {
2850 if (mQueuedErrors == null) {
2851 mQueuedErrors = new LinkedList<ErrorDialog>();
2852 }
2853 for (ErrorDialog d : mQueuedErrors) {
2854 if (d.mError == err) {
2855 // Already saw a similar error, ignore the new one.
2856 return;
2857 }
2858 }
2859 ErrorDialog errDialog = new ErrorDialog(
Patrick Scott5d61a6c2009-08-25 13:52:46 -04002860 err == WebViewClient.ERROR_FILE_NOT_FOUND ?
Patrick Scott37911c72009-03-24 18:02:58 -07002861 R.string.browserFrameFileErrorLabel :
2862 R.string.browserFrameNetworkErrorLabel,
2863 desc, err);
2864 mQueuedErrors.addLast(errDialog);
2865
2866 // Show the dialog now if the queue was empty.
2867 if (mQueuedErrors.size() == 1) {
2868 showError(errDialog);
2869 }
2870 }
2871
2872 private void showError(ErrorDialog errDialog) {
2873 AlertDialog d = new AlertDialog.Builder(BrowserActivity.this)
2874 .setTitle(errDialog.mTitle)
2875 .setMessage(errDialog.mDescription)
2876 .setPositiveButton(R.string.ok, null)
2877 .create();
2878 d.setOnDismissListener(mDialogListener);
2879 d.show();
2880 }
2881
The Android Open Source Project0c908882009-03-03 19:32:16 -08002882 /**
2883 * Show a dialog informing the user of the network error reported by
2884 * WebCore.
2885 */
2886 @Override
2887 public void onReceivedError(WebView view, int errorCode,
2888 String description, String failingUrl) {
Patrick Scott5d61a6c2009-08-25 13:52:46 -04002889 if (errorCode != WebViewClient.ERROR_HOST_LOOKUP &&
2890 errorCode != WebViewClient.ERROR_CONNECT &&
2891 errorCode != WebViewClient.ERROR_BAD_URL &&
2892 errorCode != WebViewClient.ERROR_UNSUPPORTED_SCHEME &&
2893 errorCode != WebViewClient.ERROR_FILE) {
Patrick Scott37911c72009-03-24 18:02:58 -07002894 queueError(errorCode, description);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002895 }
Patrick Scott37911c72009-03-24 18:02:58 -07002896 Log.e(LOGTAG, "onReceivedError " + errorCode + " " + failingUrl
2897 + " " + description);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002898
Ben Murdochaac7aa62009-09-17 16:57:40 +01002899 mNeedExtraScreenShot = true;
2900
The Android Open Source Project0c908882009-03-03 19:32:16 -08002901 // We need to reset the title after an error.
2902 resetTitleAndRevertLockIcon();
2903 }
2904
2905 /**
2906 * Check with the user if it is ok to resend POST data as the page they
2907 * are trying to navigate to is the result of a POST.
2908 */
2909 @Override
2910 public void onFormResubmission(WebView view, final Message dontResend,
2911 final Message resend) {
2912 new AlertDialog.Builder(BrowserActivity.this)
2913 .setTitle(R.string.browserFrameFormResubmitLabel)
2914 .setMessage(R.string.browserFrameFormResubmitMessage)
2915 .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
2916 public void onClick(DialogInterface dialog, int which) {
2917 resend.sendToTarget();
2918 }})
2919 .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
2920 public void onClick(DialogInterface dialog, int which) {
2921 dontResend.sendToTarget();
2922 }})
2923 .setOnCancelListener(new OnCancelListener() {
2924 public void onCancel(DialogInterface dialog) {
2925 dontResend.sendToTarget();
2926 }})
2927 .show();
2928 }
2929
2930 /**
2931 * Insert the url into the visited history database.
2932 * @param url The url to be inserted.
2933 * @param isReload True if this url is being reloaded.
2934 * FIXME: Not sure what to do when reloading the page.
2935 */
2936 @Override
2937 public void doUpdateVisitedHistory(WebView view, String url,
2938 boolean isReload) {
2939 if (url.regionMatches(true, 0, "about:", 0, 6)) {
2940 return;
2941 }
Grace Kloba6b52a552009-09-03 16:29:56 -07002942 // remove "client" before updating it to the history so that it wont
2943 // show up in the auto-complete list.
2944 int index = url.indexOf("client=ms-");
2945 if (index > 0 && url.contains(".google.")) {
2946 int end = url.indexOf('&', index);
2947 if (end > 0) {
2948 url = url.substring(0, index-1).concat(url.substring(end));
2949 } else {
2950 url = url.substring(0, index-1);
2951 }
2952 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002953 Browser.updateVisitedHistory(mResolver, url, true);
2954 WebIconDatabase.getInstance().retainIconForPageUrl(url);
2955 }
2956
2957 /**
2958 * Displays SSL error(s) dialog to the user.
2959 */
2960 @Override
2961 public void onReceivedSslError(
2962 final WebView view, final SslErrorHandler handler, final SslError error) {
2963
2964 if (mSettings.showSecurityWarnings()) {
2965 final LayoutInflater factory =
2966 LayoutInflater.from(BrowserActivity.this);
2967 final View warningsView =
2968 factory.inflate(R.layout.ssl_warnings, null);
2969 final LinearLayout placeholder =
2970 (LinearLayout)warningsView.findViewById(R.id.placeholder);
2971
2972 if (error.hasError(SslError.SSL_UNTRUSTED)) {
2973 LinearLayout ll = (LinearLayout)factory
2974 .inflate(R.layout.ssl_warning, null);
2975 ((TextView)ll.findViewById(R.id.warning))
2976 .setText(R.string.ssl_untrusted);
2977 placeholder.addView(ll);
2978 }
2979
2980 if (error.hasError(SslError.SSL_IDMISMATCH)) {
2981 LinearLayout ll = (LinearLayout)factory
2982 .inflate(R.layout.ssl_warning, null);
2983 ((TextView)ll.findViewById(R.id.warning))
2984 .setText(R.string.ssl_mismatch);
2985 placeholder.addView(ll);
2986 }
2987
2988 if (error.hasError(SslError.SSL_EXPIRED)) {
2989 LinearLayout ll = (LinearLayout)factory
2990 .inflate(R.layout.ssl_warning, null);
2991 ((TextView)ll.findViewById(R.id.warning))
2992 .setText(R.string.ssl_expired);
2993 placeholder.addView(ll);
2994 }
2995
2996 if (error.hasError(SslError.SSL_NOTYETVALID)) {
2997 LinearLayout ll = (LinearLayout)factory
2998 .inflate(R.layout.ssl_warning, null);
2999 ((TextView)ll.findViewById(R.id.warning))
3000 .setText(R.string.ssl_not_yet_valid);
3001 placeholder.addView(ll);
3002 }
3003
3004 new AlertDialog.Builder(BrowserActivity.this)
3005 .setTitle(R.string.security_warning)
3006 .setIcon(android.R.drawable.ic_dialog_alert)
3007 .setView(warningsView)
3008 .setPositiveButton(R.string.ssl_continue,
3009 new DialogInterface.OnClickListener() {
3010 public void onClick(DialogInterface dialog, int whichButton) {
3011 handler.proceed();
3012 }
3013 })
3014 .setNeutralButton(R.string.view_certificate,
3015 new DialogInterface.OnClickListener() {
3016 public void onClick(DialogInterface dialog, int whichButton) {
3017 showSSLCertificateOnError(view, handler, error);
3018 }
3019 })
3020 .setNegativeButton(R.string.cancel,
3021 new DialogInterface.OnClickListener() {
3022 public void onClick(DialogInterface dialog, int whichButton) {
3023 handler.cancel();
3024 BrowserActivity.this.resetTitleAndRevertLockIcon();
3025 }
3026 })
3027 .setOnCancelListener(
3028 new DialogInterface.OnCancelListener() {
3029 public void onCancel(DialogInterface dialog) {
3030 handler.cancel();
3031 BrowserActivity.this.resetTitleAndRevertLockIcon();
3032 }
3033 })
3034 .show();
3035 } else {
3036 handler.proceed();
3037 }
3038 }
3039
3040 /**
3041 * Handles an HTTP authentication request.
3042 *
3043 * @param handler The authentication handler
3044 * @param host The host
3045 * @param realm The realm
3046 */
3047 @Override
3048 public void onReceivedHttpAuthRequest(WebView view,
3049 final HttpAuthHandler handler, final String host, final String realm) {
3050 String username = null;
3051 String password = null;
3052
3053 boolean reuseHttpAuthUsernamePassword =
3054 handler.useHttpAuthUsernamePassword();
3055
3056 if (reuseHttpAuthUsernamePassword &&
3057 (mTabControl.getCurrentWebView() != null)) {
3058 String[] credentials =
3059 mTabControl.getCurrentWebView()
3060 .getHttpAuthUsernamePassword(host, realm);
3061 if (credentials != null && credentials.length == 2) {
3062 username = credentials[0];
3063 password = credentials[1];
3064 }
3065 }
3066
3067 if (username != null && password != null) {
3068 handler.proceed(username, password);
3069 } else {
3070 showHttpAuthentication(handler, host, realm, null, null, null, 0);
3071 }
3072 }
3073
3074 @Override
3075 public boolean shouldOverrideKeyEvent(WebView view, KeyEvent event) {
3076 if (mMenuIsDown) {
3077 // only check shortcut key when MENU is held
3078 return getWindow().isShortcutKey(event.getKeyCode(), event);
3079 } else {
3080 return false;
3081 }
3082 }
3083
3084 @Override
3085 public void onUnhandledKeyEvent(WebView view, KeyEvent event) {
3086 if (view != mTabControl.getCurrentTopWebView()) {
3087 return;
3088 }
3089 if (event.isDown()) {
3090 BrowserActivity.this.onKeyDown(event.getKeyCode(), event);
3091 } else {
3092 BrowserActivity.this.onKeyUp(event.getKeyCode(), event);
3093 }
3094 }
3095 };
3096
3097 //--------------------------------------------------------------------------
3098 // WebChromeClient implementation
3099 //--------------------------------------------------------------------------
3100
3101 /* package */ WebChromeClient getWebChromeClient() {
3102 return mWebChromeClient;
3103 }
3104
3105 private final WebChromeClient mWebChromeClient = new WebChromeClient() {
3106 // Helper method to create a new tab or sub window.
3107 private void createWindow(final boolean dialog, final Message msg) {
3108 if (dialog) {
3109 mTabControl.createSubWindow();
3110 final TabControl.Tab t = mTabControl.getCurrentTab();
3111 attachSubWindow(t);
3112 WebView.WebViewTransport transport =
3113 (WebView.WebViewTransport) msg.obj;
3114 transport.setWebView(t.getSubWebView());
3115 msg.sendToTarget();
3116 } else {
3117 final TabControl.Tab parent = mTabControl.getCurrentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04003118 final TabControl.Tab newTab
3119 = openTabAndShow(EMPTY_URL_DATA, false, null);
Grace Klobac9181842009-04-14 08:53:22 -07003120 if (newTab != parent) {
3121 parent.addChildTab(newTab);
3122 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003123 WebView.WebViewTransport transport =
3124 (WebView.WebViewTransport) msg.obj;
3125 transport.setWebView(mTabControl.getCurrentWebView());
Leon Scroggins1f005d32009-08-10 17:36:42 -04003126 msg.sendToTarget();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003127 }
3128 }
3129
3130 @Override
3131 public boolean onCreateWindow(WebView view, final boolean dialog,
3132 final boolean userGesture, final Message resultMsg) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003133 // Short-circuit if we can't create any more tabs or sub windows.
3134 if (dialog && mTabControl.getCurrentSubWindow() != null) {
3135 new AlertDialog.Builder(BrowserActivity.this)
3136 .setTitle(R.string.too_many_subwindows_dialog_title)
3137 .setIcon(android.R.drawable.ic_dialog_alert)
3138 .setMessage(R.string.too_many_subwindows_dialog_message)
3139 .setPositiveButton(R.string.ok, null)
3140 .show();
3141 return false;
3142 } else if (mTabControl.getTabCount() >= TabControl.MAX_TABS) {
3143 new AlertDialog.Builder(BrowserActivity.this)
3144 .setTitle(R.string.too_many_windows_dialog_title)
3145 .setIcon(android.R.drawable.ic_dialog_alert)
3146 .setMessage(R.string.too_many_windows_dialog_message)
3147 .setPositiveButton(R.string.ok, null)
3148 .show();
3149 return false;
3150 }
3151
3152 // Short-circuit if this was a user gesture.
3153 if (userGesture) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003154 createWindow(dialog, resultMsg);
3155 return true;
3156 }
3157
3158 // Allow the popup and create the appropriate window.
3159 final AlertDialog.OnClickListener allowListener =
3160 new AlertDialog.OnClickListener() {
3161 public void onClick(DialogInterface d,
3162 int which) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003163 createWindow(dialog, resultMsg);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003164 }
3165 };
3166
3167 // Block the popup by returning a null WebView.
3168 final AlertDialog.OnClickListener blockListener =
3169 new AlertDialog.OnClickListener() {
3170 public void onClick(DialogInterface d, int which) {
3171 resultMsg.sendToTarget();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003172 }
3173 };
3174
3175 // Build a confirmation dialog to display to the user.
3176 final AlertDialog d =
3177 new AlertDialog.Builder(BrowserActivity.this)
3178 .setTitle(R.string.attention)
3179 .setIcon(android.R.drawable.ic_dialog_alert)
3180 .setMessage(R.string.popup_window_attempt)
3181 .setPositiveButton(R.string.allow, allowListener)
3182 .setNegativeButton(R.string.block, blockListener)
3183 .setCancelable(false)
3184 .create();
3185
3186 // Show the confirmation dialog.
3187 d.show();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003188 return true;
3189 }
3190
3191 @Override
3192 public void onCloseWindow(WebView window) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04003193 final TabControl.Tab current = mTabControl.getCurrentTab();
3194 final TabControl.Tab parent = current.getParentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003195 if (parent != null) {
3196 // JavaScript can only close popup window.
Leon Scroggins1f005d32009-08-10 17:36:42 -04003197 switchToTab(mTabControl.getTabIndex(parent));
3198 // Now we need to close the window
3199 closeTab(current);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003200 }
3201 }
3202
3203 @Override
3204 public void onProgressChanged(WebView view, int newProgress) {
Leon Scroggins68579392009-09-15 15:31:54 -04003205 mTitleBar.setProgress(newProgress);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04003206 if (mFakeTitleBar != null) {
3207 mFakeTitleBar.setProgress(newProgress);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003208 }
3209
3210 if (newProgress == 100) {
Ben Murdochaac7aa62009-09-17 16:57:40 +01003211 // onProgressChanged() may continue to be called after the main
3212 // frame has finished loading, as any remaining sub frames
3213 // continue to load. We'll only get called once though with
3214 // newProgress as 100 when everything is loaded.
3215 // (onPageFinished is called once when the main frame completes
3216 // loading regardless of the state of any sub frames so calls
3217 // to onProgressChanges may continue after onPageFinished has
3218 // executed)
3219
3220 // sync cookies and cache promptly here.
The Android Open Source Project0c908882009-03-03 19:32:16 -08003221 CookieSyncManager.getInstance().sync();
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07003222 if (mInLoad) {
3223 mInLoad = false;
3224 updateInLoadMenuItems();
Leon Scrogginsa27ff192009-09-14 12:58:04 -04003225 // If the options menu is open, leave the title bar
3226 if (!mOptionsMenuOpen || !mIconView) {
3227 hideFakeTitleBar();
3228 }
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07003229 }
Ben Murdochaac7aa62009-09-17 16:57:40 +01003230 if (mNeedExtraScreenShot) {
3231 // if there was an error loading this page, capture a new
3232 // screenshot to ensure that we get the correct thumbnail
3233 // as onPageFinished may have been called before the error
3234 // page was displayed.
3235 updateScreenshot(view);
3236 mNeedExtraScreenShot = false;
3237 }
Leon Scrogginsa27ff192009-09-14 12:58:04 -04003238 } else if (!mInLoad) {
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07003239 // onPageFinished may have already been called but a subframe
3240 // is still loading and updating the progress. Reset mInLoad
3241 // and update the menu items.
Leon Scrogginsa27ff192009-09-14 12:58:04 -04003242 mInLoad = true;
3243 updateInLoadMenuItems();
Leon Scroggins184f5e32009-09-21 10:38:24 -04003244 if (!mOptionsMenuOpen || mIconView) {
Leon Scrogginsa27ff192009-09-14 12:58:04 -04003245 // This page has begun to load, so show the title bar
3246 showFakeTitleBar();
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07003247 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003248 }
3249 }
3250
3251 @Override
3252 public void onReceivedTitle(WebView view, String title) {
Patrick Scott598c9cc2009-06-04 11:10:38 -04003253 String url = view.getUrl();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003254
3255 // here, if url is null, we want to reset the title
Leon Scroggins68579392009-09-15 15:31:54 -04003256 setUrlTitle(url, title);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003257
3258 if (url == null ||
3259 url.length() >= SQLiteDatabase.SQLITE_MAX_LIKE_PATTERN_LENGTH) {
3260 return;
3261 }
Leon Scrogginsfce182b2009-05-08 13:54:52 -04003262 // See if we can find the current url in our history database and
3263 // add the new title to it.
The Android Open Source Project0c908882009-03-03 19:32:16 -08003264 if (url.startsWith("http://www.")) {
3265 url = url.substring(11);
3266 } else if (url.startsWith("http://")) {
3267 url = url.substring(4);
3268 }
3269 try {
3270 url = "%" + url;
3271 String [] selArgs = new String[] { url };
3272
3273 String where = Browser.BookmarkColumns.URL + " LIKE ? AND "
3274 + Browser.BookmarkColumns.BOOKMARK + " = 0";
3275 Cursor c = mResolver.query(Browser.BOOKMARKS_URI,
3276 Browser.HISTORY_PROJECTION, where, selArgs, null);
3277 if (c.moveToFirst()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003278 // Current implementation of database only has one entry per
3279 // url.
Leon Scrogginsfce182b2009-05-08 13:54:52 -04003280 ContentValues map = new ContentValues();
3281 map.put(Browser.BookmarkColumns.TITLE, title);
3282 mResolver.update(Browser.BOOKMARKS_URI, map,
3283 "_id = " + c.getInt(0), null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003284 }
3285 c.close();
3286 } catch (IllegalStateException e) {
3287 Log.e(LOGTAG, "BrowserActivity onReceived title", e);
3288 } catch (SQLiteException ex) {
3289 Log.e(LOGTAG, "onReceivedTitle() caught SQLiteException: ", ex);
3290 }
3291 }
3292
3293 @Override
3294 public void onReceivedIcon(WebView view, Bitmap icon) {
Patrick Scott3918d442009-08-04 13:22:29 -04003295 updateIcon(view, icon);
3296 }
3297
3298 @Override
Patrick Scott59ce8302009-09-18 16:29:38 -04003299 public void onReceivedTouchIconUrl(WebView view, String url,
3300 boolean precomposed) {
Patrick Scott3918d442009-08-04 13:22:29 -04003301 final ContentResolver cr = getContentResolver();
3302 final Cursor c =
3303 BrowserBookmarksAdapter.queryBookmarksForUrl(cr,
Leon Scrogginsa5d669e2009-08-05 14:07:58 -04003304 view.getOriginalUrl(), view.getUrl(), true);
Patrick Scott3918d442009-08-04 13:22:29 -04003305 if (c != null) {
3306 if (c.getCount() > 0) {
Patrick Scott59ce8302009-09-18 16:29:38 -04003307 // Let precomposed icons take precedence over non-composed
3308 // icons.
3309 if (precomposed && mTouchIconLoader != null) {
3310 mTouchIconLoader.cancel(false);
3311 mTouchIconLoader = null;
3312 }
3313 // Have only one async task at a time.
3314 if (mTouchIconLoader == null) {
3315 mTouchIconLoader = new DownloadTouchIcon(
3316 BrowserActivity.this, cr, c, view);
3317 mTouchIconLoader.execute(url);
3318 }
Patrick Scott3918d442009-08-04 13:22:29 -04003319 } else {
3320 c.close();
3321 }
3322 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003323 }
Ben Murdoch092dd5d2009-04-22 12:34:12 +01003324
Andrei Popescuadc008d2009-06-26 14:11:30 +01003325 @Override
Andrei Popescuc9b55562009-07-07 10:51:15 +01003326 public void onShowCustomView(View view, WebChromeClient.CustomViewCallback callback) {
Andrei Popescuadc008d2009-06-26 14:11:30 +01003327 if (mCustomView != null)
3328 return;
3329
3330 // Add the custom view to its container.
3331 mCustomViewContainer.addView(view, COVER_SCREEN_GRAVITY_CENTER);
3332 mCustomView = view;
Andrei Popescuc9b55562009-07-07 10:51:15 +01003333 mCustomViewCallback = callback;
Andrei Popescuadc008d2009-06-26 14:11:30 +01003334 // Save the menu state and set it to empty while the custom
3335 // view is showing.
3336 mOldMenuState = mMenuState;
3337 mMenuState = EMPTY_MENU;
Andrei Popescuc9b55562009-07-07 10:51:15 +01003338 // Hide the content view.
3339 mContentView.setVisibility(View.GONE);
Andrei Popescuadc008d2009-06-26 14:11:30 +01003340 // Finally show the custom view container.
Andrei Popescuc9b55562009-07-07 10:51:15 +01003341 mCustomViewContainer.setVisibility(View.VISIBLE);
3342 mCustomViewContainer.bringToFront();
Andrei Popescuadc008d2009-06-26 14:11:30 +01003343 }
3344
3345 @Override
3346 public void onHideCustomView() {
3347 if (mCustomView == null)
3348 return;
3349
Andrei Popescuc9b55562009-07-07 10:51:15 +01003350 // Hide the custom view.
3351 mCustomView.setVisibility(View.GONE);
Andrei Popescuadc008d2009-06-26 14:11:30 +01003352 // Remove the custom view from its container.
3353 mCustomViewContainer.removeView(mCustomView);
3354 mCustomView = null;
3355 // Reset the old menu state.
3356 mMenuState = mOldMenuState;
3357 mOldMenuState = EMPTY_MENU;
3358 mCustomViewContainer.setVisibility(View.GONE);
Andrei Popescuc9b55562009-07-07 10:51:15 +01003359 mCustomViewCallback.onCustomViewHidden();
3360 // Show the content view.
3361 mContentView.setVisibility(View.VISIBLE);
Andrei Popescuadc008d2009-06-26 14:11:30 +01003362 }
3363
Ben Murdoch092dd5d2009-04-22 12:34:12 +01003364 /**
Andrei Popescu79e82b72009-07-27 12:01:59 +01003365 * The origin has exceeded its database quota.
Ben Murdoch092dd5d2009-04-22 12:34:12 +01003366 * @param url the URL that exceeded the quota
3367 * @param databaseIdentifier the identifier of the database on
3368 * which the transaction that caused the quota overflow was run
3369 * @param currentQuota the current quota for the origin.
Ben Murdoch25a15232009-08-25 19:38:07 +01003370 * @param estimatedSize the estimated size of the database.
Andrei Popescu79e82b72009-07-27 12:01:59 +01003371 * @param totalUsedQuota is the sum of all origins' quota.
Ben Murdoch092dd5d2009-04-22 12:34:12 +01003372 * @param quotaUpdater The callback to run when a decision to allow or
3373 * deny quota has been made. Don't forget to call this!
3374 */
3375 @Override
3376 public void onExceededDatabaseQuota(String url,
Ben Murdoch25a15232009-08-25 19:38:07 +01003377 String databaseIdentifier, long currentQuota, long estimatedSize,
3378 long totalUsedQuota, WebStorage.QuotaUpdater quotaUpdater) {
Andrei Popescu79e82b72009-07-27 12:01:59 +01003379 mSettings.getWebStorageSizeManager().onExceededDatabaseQuota(
Ben Murdoch25a15232009-08-25 19:38:07 +01003380 url, databaseIdentifier, currentQuota, estimatedSize,
3381 totalUsedQuota, quotaUpdater);
Andrei Popescu79e82b72009-07-27 12:01:59 +01003382 }
3383
3384 /**
3385 * The Application Cache has exceeded its max size.
3386 * @param spaceNeeded is the amount of disk space that would be needed
3387 * in order for the last appcache operation to succeed.
3388 * @param totalUsedQuota is the sum of all origins' quota.
3389 * @param quotaUpdater A callback to inform the WebCore thread that a new
3390 * app cache size is available. This callback must always be executed at
3391 * some point to ensure that the sleeping WebCore thread is woken up.
3392 */
3393 @Override
3394 public void onReachedMaxAppCacheSize(long spaceNeeded,
3395 long totalUsedQuota, WebStorage.QuotaUpdater quotaUpdater) {
3396 mSettings.getWebStorageSizeManager().onReachedMaxAppCacheSize(
3397 spaceNeeded, totalUsedQuota, quotaUpdater);
Ben Murdoch092dd5d2009-04-22 12:34:12 +01003398 }
Ben Murdoch7db26342009-06-03 18:21:19 +01003399
Steve Block2bc69912009-07-30 14:45:13 +01003400 /**
3401 * Instructs the browser to show a prompt to ask the user to set the
3402 * Geolocation permission state for the specified origin.
3403 * @param origin The origin for which Geolocation permissions are
3404 * requested.
3405 * @param callback The callback to call once the user has set the
3406 * Geolocation permission state.
3407 */
3408 @Override
3409 public void onGeolocationPermissionsShowPrompt(String origin,
3410 GeolocationPermissions.Callback callback) {
3411 mTabControl.getCurrentTab().getGeolocationPermissionsPrompt().show(
3412 origin, callback);
3413 }
3414
3415 /**
3416 * Instructs the browser to hide the Geolocation permissions prompt.
3417 */
3418 @Override
3419 public void onGeolocationPermissionsHidePrompt() {
3420 mTabControl.getCurrentTab().getGeolocationPermissionsPrompt().hide();
3421 }
3422
Ben Murdoch7db26342009-06-03 18:21:19 +01003423 /* Adds a JavaScript error message to the system log.
3424 * @param message The error message to report.
3425 * @param lineNumber The line number of the error.
3426 * @param sourceID The name of the source file that caused the error.
3427 */
3428 @Override
3429 public void addMessageToConsole(String message, int lineNumber, String sourceID) {
Ben Murdochbff2d602009-07-01 20:19:05 +01003430 ErrorConsoleView errorConsole = mTabControl.getCurrentErrorConsole(true);
3431 errorConsole.addErrorMessage(message, sourceID, lineNumber);
3432 if (mShouldShowErrorConsole &&
3433 errorConsole.getShowState() != ErrorConsoleView.SHOW_MAXIMIZED) {
3434 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
3435 }
3436 Log.w(LOGTAG, "Console: " + message + " " + sourceID + ":" + lineNumber);
Ben Murdoch7db26342009-06-03 18:21:19 +01003437 }
Andrei Popescu540035d2009-09-18 18:59:20 +01003438
3439 /**
3440 * Ask the browser for an icon to represent a <video> element.
3441 * This icon will be used if the Web page did not specify a poster attribute.
3442 *
3443 * @return Bitmap The icon or null if no such icon is available.
3444 * @hide pending API Council approval
3445 */
3446 @Override
3447 public Bitmap getDefaultVideoPoster() {
3448 if (mDefaultVideoPoster == null) {
3449 mDefaultVideoPoster = BitmapFactory.decodeResource(
3450 getResources(), R.drawable.default_video_poster);
3451 }
3452 return mDefaultVideoPoster;
3453 }
3454
3455 /**
3456 * Ask the host application for a custom progress view to show while
3457 * a <video> is loading.
3458 *
3459 * @return View The progress view.
3460 * @hide pending API Council approval
3461 */
3462 @Override
3463 public View getVideoLoadingProgressView() {
3464 if (mVideoProgressView == null) {
3465 LayoutInflater inflater = LayoutInflater.from(BrowserActivity.this);
3466 mVideoProgressView = inflater.inflate(R.layout.video_loading_progress, null);
3467 }
3468 return mVideoProgressView;
3469 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003470 };
3471
3472 /**
3473 * Notify the host application a download should be done, or that
3474 * the data should be streamed if a streaming viewer is available.
3475 * @param url The full url to the content that should be downloaded
3476 * @param contentDisposition Content-disposition http header, if
3477 * present.
3478 * @param mimetype The mimetype of the content reported by the server
3479 * @param contentLength The file size reported by the server
3480 */
3481 public void onDownloadStart(String url, String userAgent,
3482 String contentDisposition, String mimetype, long contentLength) {
3483 // if we're dealing wih A/V content that's not explicitly marked
3484 // for download, check if it's streamable.
3485 if (contentDisposition == null
Patrick Scotte1fb9662009-08-31 14:31:52 -04003486 || !contentDisposition.regionMatches(
3487 true, 0, "attachment", 0, 10)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003488 // query the package manager to see if there's a registered handler
3489 // that matches.
3490 Intent intent = new Intent(Intent.ACTION_VIEW);
3491 intent.setDataAndType(Uri.parse(url), mimetype);
Patrick Scotte1fb9662009-08-31 14:31:52 -04003492 ResolveInfo info = getPackageManager().resolveActivity(intent,
3493 PackageManager.MATCH_DEFAULT_ONLY);
3494 if (info != null) {
3495 ComponentName myName = getComponentName();
3496 // If we resolved to ourselves, we don't want to attempt to
3497 // load the url only to try and download it again.
3498 if (!myName.getPackageName().equals(
3499 info.activityInfo.packageName)
3500 || !myName.getClassName().equals(
3501 info.activityInfo.name)) {
3502 // someone (other than us) knows how to handle this mime
3503 // type with this scheme, don't download.
3504 try {
3505 startActivity(intent);
3506 return;
3507 } catch (ActivityNotFoundException ex) {
3508 if (LOGD_ENABLED) {
3509 Log.d(LOGTAG, "activity not found for " + mimetype
3510 + " over " + Uri.parse(url).getScheme(),
3511 ex);
3512 }
3513 // Best behavior is to fall back to a download in this
3514 // case
The Android Open Source Project0c908882009-03-03 19:32:16 -08003515 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003516 }
3517 }
3518 }
3519 onDownloadStartNoStream(url, userAgent, contentDisposition, mimetype, contentLength);
3520 }
3521
3522 /**
3523 * Notify the host application a download should be done, even if there
3524 * is a streaming viewer available for thise type.
3525 * @param url The full url to the content that should be downloaded
3526 * @param contentDisposition Content-disposition http header, if
3527 * present.
3528 * @param mimetype The mimetype of the content reported by the server
3529 * @param contentLength The file size reported by the server
3530 */
3531 /*package */ void onDownloadStartNoStream(String url, String userAgent,
3532 String contentDisposition, String mimetype, long contentLength) {
3533
3534 String filename = URLUtil.guessFileName(url,
3535 contentDisposition, mimetype);
3536
3537 // Check to see if we have an SDCard
3538 String status = Environment.getExternalStorageState();
3539 if (!status.equals(Environment.MEDIA_MOUNTED)) {
3540 int title;
3541 String msg;
3542
3543 // Check to see if the SDCard is busy, same as the music app
3544 if (status.equals(Environment.MEDIA_SHARED)) {
3545 msg = getString(R.string.download_sdcard_busy_dlg_msg);
3546 title = R.string.download_sdcard_busy_dlg_title;
3547 } else {
3548 msg = getString(R.string.download_no_sdcard_dlg_msg, filename);
3549 title = R.string.download_no_sdcard_dlg_title;
3550 }
3551
3552 new AlertDialog.Builder(this)
3553 .setTitle(title)
3554 .setIcon(android.R.drawable.ic_dialog_alert)
3555 .setMessage(msg)
3556 .setPositiveButton(R.string.ok, null)
3557 .show();
3558 return;
3559 }
3560
3561 // java.net.URI is a lot stricter than KURL so we have to undo
3562 // KURL's percent-encoding and redo the encoding using java.net.URI.
3563 URI uri = null;
3564 try {
3565 // Undo the percent-encoding that KURL may have done.
3566 String newUrl = new String(URLUtil.decode(url.getBytes()));
3567 // Parse the url into pieces
3568 WebAddress w = new WebAddress(newUrl);
3569 String frag = null;
3570 String query = null;
3571 String path = w.mPath;
3572 // Break the path into path, query, and fragment
3573 if (path.length() > 0) {
3574 // Strip the fragment
3575 int idx = path.lastIndexOf('#');
3576 if (idx != -1) {
3577 frag = path.substring(idx + 1);
3578 path = path.substring(0, idx);
3579 }
3580 idx = path.lastIndexOf('?');
3581 if (idx != -1) {
3582 query = path.substring(idx + 1);
3583 path = path.substring(0, idx);
3584 }
3585 }
3586 uri = new URI(w.mScheme, w.mAuthInfo, w.mHost, w.mPort, path,
3587 query, frag);
3588 } catch (Exception e) {
3589 Log.e(LOGTAG, "Could not parse url for download: " + url, e);
3590 return;
3591 }
3592
3593 // XXX: Have to use the old url since the cookies were stored using the
3594 // old percent-encoded url.
3595 String cookies = CookieManager.getInstance().getCookie(url);
3596
3597 ContentValues values = new ContentValues();
Jean-Baptiste Queru3dc09b22009-03-31 16:49:44 -07003598 values.put(Downloads.COLUMN_URI, uri.toString());
3599 values.put(Downloads.COLUMN_COOKIE_DATA, cookies);
3600 values.put(Downloads.COLUMN_USER_AGENT, userAgent);
3601 values.put(Downloads.COLUMN_NOTIFICATION_PACKAGE,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003602 getPackageName());
Jean-Baptiste Queru3dc09b22009-03-31 16:49:44 -07003603 values.put(Downloads.COLUMN_NOTIFICATION_CLASS,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003604 BrowserDownloadPage.class.getCanonicalName());
Jean-Baptiste Queru3dc09b22009-03-31 16:49:44 -07003605 values.put(Downloads.COLUMN_VISIBILITY, Downloads.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
3606 values.put(Downloads.COLUMN_MIME_TYPE, mimetype);
3607 values.put(Downloads.COLUMN_FILE_NAME_HINT, filename);
3608 values.put(Downloads.COLUMN_DESCRIPTION, uri.getHost());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003609 if (contentLength > 0) {
Jean-Baptiste Queru3dc09b22009-03-31 16:49:44 -07003610 values.put(Downloads.COLUMN_TOTAL_BYTES, contentLength);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003611 }
3612 if (mimetype == null) {
3613 // We must have long pressed on a link or image to download it. We
3614 // are not sure of the mimetype in this case, so do a head request
3615 new FetchUrlMimeType(this).execute(values);
3616 } else {
3617 final Uri contentUri =
3618 getContentResolver().insert(Downloads.CONTENT_URI, values);
3619 viewDownloads(contentUri);
3620 }
3621
3622 }
3623
3624 /**
3625 * Resets the lock icon. This method is called when we start a new load and
3626 * know the url to be loaded.
3627 */
3628 private void resetLockIcon(String url) {
3629 // Save the lock-icon state (we revert to it if the load gets cancelled)
3630 saveLockIcon();
3631
3632 mLockIconType = LOCK_ICON_UNSECURE;
3633 if (URLUtil.isHttpsUrl(url)) {
3634 mLockIconType = LOCK_ICON_SECURE;
Dave Bort31a6d1c2009-04-13 15:56:49 -07003635 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003636 Log.v(LOGTAG, "BrowserActivity.resetLockIcon:" +
3637 " reset lock icon to " + mLockIconType);
3638 }
3639 }
3640
3641 updateLockIconImage(LOCK_ICON_UNSECURE);
3642 }
3643
Grace Klobaeb6eef42009-09-15 17:56:32 -07003644 /* package */ void setLockIconType(int type) {
3645 mLockIconType = type;
3646 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003647
Grace Klobaeb6eef42009-09-15 17:56:32 -07003648 /* package */ int getLockIconType() {
3649 return mLockIconType;
3650 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003651
Grace Klobaeb6eef42009-09-15 17:56:32 -07003652 /* package */ void setPrevLockType(int type) {
3653 mPrevLockType = type;
3654 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003655
Grace Klobaeb6eef42009-09-15 17:56:32 -07003656 /* package */ int getPrevLockType() {
3657 return mPrevLockType;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003658 }
3659
3660 /**
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04003661 * Update the lock icon to correspond to our latest state.
3662 */
3663 /* package */ void updateLockIconToLatest() {
3664 updateLockIconImage(mLockIconType);
3665 }
3666
3667 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08003668 * Updates the lock-icon image in the title-bar.
3669 */
3670 private void updateLockIconImage(int lockIconType) {
3671 Drawable d = null;
3672 if (lockIconType == LOCK_ICON_SECURE) {
3673 d = mSecLockIcon;
3674 } else if (lockIconType == LOCK_ICON_MIXED) {
3675 d = mMixLockIcon;
3676 }
Leon Scroggins68579392009-09-15 15:31:54 -04003677 mTitleBar.setLock(d);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04003678 if (mFakeTitleBar != null) {
3679 mFakeTitleBar.setLock(d);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003680 }
3681 }
3682
3683 /**
3684 * Displays a page-info dialog.
3685 * @param tab The tab to show info about
3686 * @param fromShowSSLCertificateOnError The flag that indicates whether
3687 * this dialog was opened from the SSL-certificate-on-error dialog or
3688 * not. This is important, since we need to know whether to return to
3689 * the parent dialog or simply dismiss.
3690 */
3691 private void showPageInfo(final TabControl.Tab tab,
3692 final boolean fromShowSSLCertificateOnError) {
3693 final LayoutInflater factory = LayoutInflater
3694 .from(this);
3695
3696 final View pageInfoView = factory.inflate(R.layout.page_info, null);
3697
3698 final WebView view = tab.getWebView();
3699
3700 String url = null;
3701 String title = null;
3702
3703 if (view == null) {
3704 url = tab.getUrl();
3705 title = tab.getTitle();
3706 } else if (view == mTabControl.getCurrentWebView()) {
3707 // Use the cached title and url if this is the current WebView
3708 url = mUrl;
3709 title = mTitle;
3710 } else {
3711 url = view.getUrl();
3712 title = view.getTitle();
3713 }
3714
3715 if (url == null) {
3716 url = "";
3717 }
3718 if (title == null) {
3719 title = "";
3720 }
3721
3722 ((TextView) pageInfoView.findViewById(R.id.address)).setText(url);
3723 ((TextView) pageInfoView.findViewById(R.id.title)).setText(title);
3724
3725 mPageInfoView = tab;
3726 mPageInfoFromShowSSLCertificateOnError = new Boolean(fromShowSSLCertificateOnError);
3727
3728 AlertDialog.Builder alertDialogBuilder =
3729 new AlertDialog.Builder(this)
3730 .setTitle(R.string.page_info).setIcon(android.R.drawable.ic_dialog_info)
3731 .setView(pageInfoView)
3732 .setPositiveButton(
3733 R.string.ok,
3734 new DialogInterface.OnClickListener() {
3735 public void onClick(DialogInterface dialog,
3736 int whichButton) {
3737 mPageInfoDialog = null;
3738 mPageInfoView = null;
3739 mPageInfoFromShowSSLCertificateOnError = null;
3740
3741 // if we came here from the SSL error dialog
3742 if (fromShowSSLCertificateOnError) {
3743 // go back to the SSL error dialog
3744 showSSLCertificateOnError(
3745 mSSLCertificateOnErrorView,
3746 mSSLCertificateOnErrorHandler,
3747 mSSLCertificateOnErrorError);
3748 }
3749 }
3750 })
3751 .setOnCancelListener(
3752 new DialogInterface.OnCancelListener() {
3753 public void onCancel(DialogInterface dialog) {
3754 mPageInfoDialog = null;
3755 mPageInfoView = null;
3756 mPageInfoFromShowSSLCertificateOnError = null;
3757
3758 // if we came here from the SSL error dialog
3759 if (fromShowSSLCertificateOnError) {
3760 // go back to the SSL error dialog
3761 showSSLCertificateOnError(
3762 mSSLCertificateOnErrorView,
3763 mSSLCertificateOnErrorHandler,
3764 mSSLCertificateOnErrorError);
3765 }
3766 }
3767 });
3768
3769 // if we have a main top-level page SSL certificate set or a certificate
3770 // error
3771 if (fromShowSSLCertificateOnError ||
3772 (view != null && view.getCertificate() != null)) {
3773 // add a 'View Certificate' button
3774 alertDialogBuilder.setNeutralButton(
3775 R.string.view_certificate,
3776 new DialogInterface.OnClickListener() {
3777 public void onClick(DialogInterface dialog,
3778 int whichButton) {
3779 mPageInfoDialog = null;
3780 mPageInfoView = null;
3781 mPageInfoFromShowSSLCertificateOnError = null;
3782
3783 // if we came here from the SSL error dialog
3784 if (fromShowSSLCertificateOnError) {
3785 // go back to the SSL error dialog
3786 showSSLCertificateOnError(
3787 mSSLCertificateOnErrorView,
3788 mSSLCertificateOnErrorHandler,
3789 mSSLCertificateOnErrorError);
3790 } else {
3791 // otherwise, display the top-most certificate from
3792 // the chain
3793 if (view.getCertificate() != null) {
3794 showSSLCertificate(tab);
3795 }
3796 }
3797 }
3798 });
3799 }
3800
3801 mPageInfoDialog = alertDialogBuilder.show();
3802 }
3803
3804 /**
3805 * Displays the main top-level page SSL certificate dialog
3806 * (accessible from the Page-Info dialog).
3807 * @param tab The tab to show certificate for.
3808 */
3809 private void showSSLCertificate(final TabControl.Tab tab) {
3810 final View certificateView =
3811 inflateCertificateView(tab.getWebView().getCertificate());
3812 if (certificateView == null) {
3813 return;
3814 }
3815
3816 LayoutInflater factory = LayoutInflater.from(this);
3817
3818 final LinearLayout placeholder =
3819 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3820
3821 LinearLayout ll = (LinearLayout) factory.inflate(
3822 R.layout.ssl_success, placeholder);
3823 ((TextView)ll.findViewById(R.id.success))
3824 .setText(R.string.ssl_certificate_is_valid);
3825
3826 mSSLCertificateView = tab;
3827 mSSLCertificateDialog =
3828 new AlertDialog.Builder(this)
3829 .setTitle(R.string.ssl_certificate).setIcon(
3830 R.drawable.ic_dialog_browser_certificate_secure)
3831 .setView(certificateView)
3832 .setPositiveButton(R.string.ok,
3833 new DialogInterface.OnClickListener() {
3834 public void onClick(DialogInterface dialog,
3835 int whichButton) {
3836 mSSLCertificateDialog = null;
3837 mSSLCertificateView = null;
3838
3839 showPageInfo(tab, false);
3840 }
3841 })
3842 .setOnCancelListener(
3843 new DialogInterface.OnCancelListener() {
3844 public void onCancel(DialogInterface dialog) {
3845 mSSLCertificateDialog = null;
3846 mSSLCertificateView = null;
3847
3848 showPageInfo(tab, false);
3849 }
3850 })
3851 .show();
3852 }
3853
3854 /**
3855 * Displays the SSL error certificate dialog.
3856 * @param view The target web-view.
3857 * @param handler The SSL error handler responsible for cancelling the
3858 * connection that resulted in an SSL error or proceeding per user request.
3859 * @param error The SSL error object.
3860 */
3861 private void showSSLCertificateOnError(
3862 final WebView view, final SslErrorHandler handler, final SslError error) {
3863
3864 final View certificateView =
3865 inflateCertificateView(error.getCertificate());
3866 if (certificateView == null) {
3867 return;
3868 }
3869
3870 LayoutInflater factory = LayoutInflater.from(this);
3871
3872 final LinearLayout placeholder =
3873 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3874
3875 if (error.hasError(SslError.SSL_UNTRUSTED)) {
3876 LinearLayout ll = (LinearLayout)factory
3877 .inflate(R.layout.ssl_warning, placeholder);
3878 ((TextView)ll.findViewById(R.id.warning))
3879 .setText(R.string.ssl_untrusted);
3880 }
3881
3882 if (error.hasError(SslError.SSL_IDMISMATCH)) {
3883 LinearLayout ll = (LinearLayout)factory
3884 .inflate(R.layout.ssl_warning, placeholder);
3885 ((TextView)ll.findViewById(R.id.warning))
3886 .setText(R.string.ssl_mismatch);
3887 }
3888
3889 if (error.hasError(SslError.SSL_EXPIRED)) {
3890 LinearLayout ll = (LinearLayout)factory
3891 .inflate(R.layout.ssl_warning, placeholder);
3892 ((TextView)ll.findViewById(R.id.warning))
3893 .setText(R.string.ssl_expired);
3894 }
3895
3896 if (error.hasError(SslError.SSL_NOTYETVALID)) {
3897 LinearLayout ll = (LinearLayout)factory
3898 .inflate(R.layout.ssl_warning, placeholder);
3899 ((TextView)ll.findViewById(R.id.warning))
3900 .setText(R.string.ssl_not_yet_valid);
3901 }
3902
3903 mSSLCertificateOnErrorHandler = handler;
3904 mSSLCertificateOnErrorView = view;
3905 mSSLCertificateOnErrorError = error;
3906 mSSLCertificateOnErrorDialog =
3907 new AlertDialog.Builder(this)
3908 .setTitle(R.string.ssl_certificate).setIcon(
3909 R.drawable.ic_dialog_browser_certificate_partially_secure)
3910 .setView(certificateView)
3911 .setPositiveButton(R.string.ok,
3912 new DialogInterface.OnClickListener() {
3913 public void onClick(DialogInterface dialog,
3914 int whichButton) {
3915 mSSLCertificateOnErrorDialog = null;
3916 mSSLCertificateOnErrorView = null;
3917 mSSLCertificateOnErrorHandler = null;
3918 mSSLCertificateOnErrorError = null;
3919
3920 mWebViewClient.onReceivedSslError(
3921 view, handler, error);
3922 }
3923 })
3924 .setNeutralButton(R.string.page_info_view,
3925 new DialogInterface.OnClickListener() {
3926 public void onClick(DialogInterface dialog,
3927 int whichButton) {
3928 mSSLCertificateOnErrorDialog = null;
3929
3930 // do not clear the dialog state: we will
3931 // need to show the dialog again once the
3932 // user is done exploring the page-info details
3933
3934 showPageInfo(mTabControl.getTabFromView(view),
3935 true);
3936 }
3937 })
3938 .setOnCancelListener(
3939 new DialogInterface.OnCancelListener() {
3940 public void onCancel(DialogInterface dialog) {
3941 mSSLCertificateOnErrorDialog = null;
3942 mSSLCertificateOnErrorView = null;
3943 mSSLCertificateOnErrorHandler = null;
3944 mSSLCertificateOnErrorError = null;
3945
3946 mWebViewClient.onReceivedSslError(
3947 view, handler, error);
3948 }
3949 })
3950 .show();
3951 }
3952
3953 /**
3954 * Inflates the SSL certificate view (helper method).
3955 * @param certificate The SSL certificate.
3956 * @return The resultant certificate view with issued-to, issued-by,
3957 * issued-on, expires-on, and possibly other fields set.
3958 * If the input certificate is null, returns null.
3959 */
3960 private View inflateCertificateView(SslCertificate certificate) {
3961 if (certificate == null) {
3962 return null;
3963 }
3964
3965 LayoutInflater factory = LayoutInflater.from(this);
3966
3967 View certificateView = factory.inflate(
3968 R.layout.ssl_certificate, null);
3969
3970 // issued to:
3971 SslCertificate.DName issuedTo = certificate.getIssuedTo();
3972 if (issuedTo != null) {
3973 ((TextView) certificateView.findViewById(R.id.to_common))
3974 .setText(issuedTo.getCName());
3975 ((TextView) certificateView.findViewById(R.id.to_org))
3976 .setText(issuedTo.getOName());
3977 ((TextView) certificateView.findViewById(R.id.to_org_unit))
3978 .setText(issuedTo.getUName());
3979 }
3980
3981 // issued by:
3982 SslCertificate.DName issuedBy = certificate.getIssuedBy();
3983 if (issuedBy != null) {
3984 ((TextView) certificateView.findViewById(R.id.by_common))
3985 .setText(issuedBy.getCName());
3986 ((TextView) certificateView.findViewById(R.id.by_org))
3987 .setText(issuedBy.getOName());
3988 ((TextView) certificateView.findViewById(R.id.by_org_unit))
3989 .setText(issuedBy.getUName());
3990 }
3991
3992 // issued on:
3993 String issuedOn = reformatCertificateDate(
3994 certificate.getValidNotBefore());
3995 ((TextView) certificateView.findViewById(R.id.issued_on))
3996 .setText(issuedOn);
3997
3998 // expires on:
3999 String expiresOn = reformatCertificateDate(
4000 certificate.getValidNotAfter());
4001 ((TextView) certificateView.findViewById(R.id.expires_on))
4002 .setText(expiresOn);
4003
4004 return certificateView;
4005 }
4006
4007 /**
4008 * Re-formats the certificate date (Date.toString()) string to
4009 * a properly localized date string.
4010 * @return Properly localized version of the certificate date string and
4011 * the original certificate date string if fails to localize.
4012 * If the original string is null, returns an empty string "".
4013 */
4014 private String reformatCertificateDate(String certificateDate) {
4015 String reformattedDate = null;
4016
4017 if (certificateDate != null) {
4018 Date date = null;
4019 try {
4020 date = java.text.DateFormat.getInstance().parse(certificateDate);
4021 } catch (ParseException e) {
4022 date = null;
4023 }
4024
4025 if (date != null) {
4026 reformattedDate =
4027 DateFormat.getDateFormat(this).format(date);
4028 }
4029 }
4030
4031 return reformattedDate != null ? reformattedDate :
4032 (certificateDate != null ? certificateDate : "");
4033 }
4034
4035 /**
4036 * Displays an http-authentication dialog.
4037 */
4038 private void showHttpAuthentication(final HttpAuthHandler handler,
4039 final String host, final String realm, final String title,
4040 final String name, final String password, int focusId) {
4041 LayoutInflater factory = LayoutInflater.from(this);
4042 final View v = factory
4043 .inflate(R.layout.http_authentication, null);
4044 if (name != null) {
4045 ((EditText) v.findViewById(R.id.username_edit)).setText(name);
4046 }
4047 if (password != null) {
4048 ((EditText) v.findViewById(R.id.password_edit)).setText(password);
4049 }
4050
4051 String titleText = title;
4052 if (titleText == null) {
4053 titleText = getText(R.string.sign_in_to).toString().replace(
4054 "%s1", host).replace("%s2", realm);
4055 }
4056
4057 mHttpAuthHandler = handler;
4058 AlertDialog dialog = new AlertDialog.Builder(this)
4059 .setTitle(titleText)
4060 .setIcon(android.R.drawable.ic_dialog_alert)
4061 .setView(v)
4062 .setPositiveButton(R.string.action,
4063 new DialogInterface.OnClickListener() {
4064 public void onClick(DialogInterface dialog,
4065 int whichButton) {
4066 String nm = ((EditText) v
4067 .findViewById(R.id.username_edit))
4068 .getText().toString();
4069 String pw = ((EditText) v
4070 .findViewById(R.id.password_edit))
4071 .getText().toString();
4072 BrowserActivity.this.setHttpAuthUsernamePassword
4073 (host, realm, nm, pw);
4074 handler.proceed(nm, pw);
4075 mHttpAuthenticationDialog = null;
4076 mHttpAuthHandler = null;
4077 }})
4078 .setNegativeButton(R.string.cancel,
4079 new DialogInterface.OnClickListener() {
4080 public void onClick(DialogInterface dialog,
4081 int whichButton) {
4082 handler.cancel();
4083 BrowserActivity.this.resetTitleAndRevertLockIcon();
4084 mHttpAuthenticationDialog = null;
4085 mHttpAuthHandler = null;
4086 }})
4087 .setOnCancelListener(new DialogInterface.OnCancelListener() {
4088 public void onCancel(DialogInterface dialog) {
4089 handler.cancel();
4090 BrowserActivity.this.resetTitleAndRevertLockIcon();
4091 mHttpAuthenticationDialog = null;
4092 mHttpAuthHandler = null;
4093 }})
4094 .create();
4095 // Make the IME appear when the dialog is displayed if applicable.
4096 dialog.getWindow().setSoftInputMode(
4097 WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
4098 dialog.show();
4099 if (focusId != 0) {
4100 dialog.findViewById(focusId).requestFocus();
4101 } else {
4102 v.findViewById(R.id.username_edit).requestFocus();
4103 }
4104 mHttpAuthenticationDialog = dialog;
4105 }
4106
4107 public int getProgress() {
4108 WebView w = mTabControl.getCurrentWebView();
4109 if (w != null) {
4110 return w.getProgress();
4111 } else {
4112 return 100;
4113 }
4114 }
4115
4116 /**
4117 * Set HTTP authentication password.
4118 *
4119 * @param host The host for the password
4120 * @param realm The realm for the password
4121 * @param username The username for the password. If it is null, it means
4122 * password can't be saved.
4123 * @param password The password
4124 */
4125 public void setHttpAuthUsernamePassword(String host, String realm,
4126 String username,
4127 String password) {
4128 WebView w = mTabControl.getCurrentWebView();
4129 if (w != null) {
4130 w.setHttpAuthUsernamePassword(host, realm, username, password);
4131 }
4132 }
4133
4134 /**
4135 * connectivity manager says net has come or gone... inform the user
4136 * @param up true if net has come up, false if net has gone down
4137 */
4138 public void onNetworkToggle(boolean up) {
4139 if (up == mIsNetworkUp) {
4140 return;
4141 } else if (up) {
4142 mIsNetworkUp = true;
4143 if (mAlertDialog != null) {
4144 mAlertDialog.cancel();
4145 mAlertDialog = null;
4146 }
4147 } else {
4148 mIsNetworkUp = false;
Patrick Scotteb6ab2a2009-09-16 10:00:17 -04004149 if (mInLoad) {
4150 createAndShowNetworkDialog();
4151 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08004152 }
4153 WebView w = mTabControl.getCurrentWebView();
4154 if (w != null) {
4155 w.setNetworkAvailable(up);
4156 }
4157 }
4158
Patrick Scotteb6ab2a2009-09-16 10:00:17 -04004159 // This method shows the network dialog alerting the user that the net is
4160 // down. It will only show the dialog if mAlertDialog is null.
4161 private void createAndShowNetworkDialog() {
4162 if (mAlertDialog == null) {
4163 mAlertDialog = new AlertDialog.Builder(this)
4164 .setTitle(R.string.loadSuspendedTitle)
4165 .setMessage(R.string.loadSuspended)
4166 .setPositiveButton(R.string.ok, null)
4167 .show();
4168 }
4169 }
4170
The Android Open Source Project0c908882009-03-03 19:32:16 -08004171 @Override
4172 protected void onActivityResult(int requestCode, int resultCode,
4173 Intent intent) {
4174 switch (requestCode) {
4175 case COMBO_PAGE:
4176 if (resultCode == RESULT_OK && intent != null) {
4177 String data = intent.getAction();
4178 Bundle extras = intent.getExtras();
4179 if (extras != null && extras.getBoolean("new_window", false)) {
Leon Scroggins25d35472009-09-15 11:37:27 -04004180 openTab(data);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004181 } else {
4182 final TabControl.Tab currentTab =
4183 mTabControl.getCurrentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04004184 dismissSubWindow(currentTab);
4185 if (data != null && data.length() != 0) {
4186 getTopWindow().loadUrl(data);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004187 }
4188 }
4189 }
4190 break;
4191 default:
4192 break;
4193 }
Leon Scroggins30444232009-09-04 18:36:20 -04004194 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08004195 }
4196
4197 /*
4198 * This method is called as a result of the user selecting the options
4199 * menu to see the download window, or when a download changes state. It
4200 * shows the download window ontop of the current window.
4201 */
4202 /* package */ void viewDownloads(Uri downloadRecord) {
4203 Intent intent = new Intent(this,
4204 BrowserDownloadPage.class);
4205 intent.setData(downloadRecord);
4206 startActivityForResult(intent, this.DOWNLOAD_PAGE);
4207
4208 }
4209
Leon Scroggins160a7e72009-08-14 18:28:01 -04004210 /**
4211 * Open the Go page.
4212 * @param startWithHistory If true, open starting on the history tab.
4213 * Otherwise, start with the bookmarks tab.
Leon Scroggins160a7e72009-08-14 18:28:01 -04004214 */
Leon Scroggins30444232009-09-04 18:36:20 -04004215 /* package */ void bookmarksOrHistoryPicker(boolean startWithHistory) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08004216 WebView current = mTabControl.getCurrentWebView();
4217 if (current == null) {
4218 return;
4219 }
4220 Intent intent = new Intent(this,
4221 CombinedBookmarkHistoryActivity.class);
4222 String title = current.getTitle();
4223 String url = current.getUrl();
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01004224 Bitmap thumbnail = createScreenshot(current);
4225
The Android Open Source Project0c908882009-03-03 19:32:16 -08004226 // Just in case the user opens bookmarks before a page finishes loading
4227 // so the current history item, and therefore the page, is null.
4228 if (null == url) {
4229 url = mLastEnteredUrl;
4230 // This can happen.
4231 if (null == url) {
4232 url = mSettings.getHomePage();
4233 }
4234 }
4235 // In case the web page has not yet received its associated title.
4236 if (title == null) {
4237 title = url;
4238 }
4239 intent.putExtra("title", title);
4240 intent.putExtra("url", url);
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01004241 intent.putExtra("thumbnail", thumbnail);
Leon Scroggins30444232009-09-04 18:36:20 -04004242 // Disable opening in a new window if we have maxed out the windows
4243 intent.putExtra("disable_new_window", mTabControl.getTabCount()
4244 >= TabControl.MAX_TABS);
Patrick Scott3918d442009-08-04 13:22:29 -04004245 intent.putExtra("touch_icon_url", current.getTouchIconUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08004246 if (startWithHistory) {
4247 intent.putExtra(CombinedBookmarkHistoryActivity.STARTING_TAB,
4248 CombinedBookmarkHistoryActivity.HISTORY_TAB);
4249 }
4250 startActivityForResult(intent, COMBO_PAGE);
4251 }
4252
4253 // Called when loading from context menu or LOAD_URL message
4254 private void loadURL(WebView view, String url) {
4255 // In case the user enters nothing.
4256 if (url != null && url.length() != 0 && view != null) {
4257 url = smartUrlFilter(url);
4258 if (!mWebViewClient.shouldOverrideUrlLoading(view, url)) {
4259 view.loadUrl(url);
4260 }
4261 }
4262 }
4263
The Android Open Source Project0c908882009-03-03 19:32:16 -08004264 private String smartUrlFilter(Uri inUri) {
4265 if (inUri != null) {
4266 return smartUrlFilter(inUri.toString());
4267 }
4268 return null;
4269 }
4270
4271
4272 // get window count
4273
4274 int getWindowCount(){
4275 if(mTabControl != null){
4276 return mTabControl.getTabCount();
4277 }
4278 return 0;
4279 }
4280
Feng Qianb34f87a2009-03-24 21:27:26 -07004281 protected static final Pattern ACCEPTED_URI_SCHEMA = Pattern.compile(
The Android Open Source Project0c908882009-03-03 19:32:16 -08004282 "(?i)" + // switch on case insensitive matching
4283 "(" + // begin group for schema
4284 "(?:http|https|file):\\/\\/" +
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004285 "|(?:inline|data|about|content|javascript):" +
The Android Open Source Project0c908882009-03-03 19:32:16 -08004286 ")" +
4287 "(.*)" );
4288
4289 /**
4290 * Attempts to determine whether user input is a URL or search
4291 * terms. Anything with a space is passed to search.
4292 *
4293 * Converts to lowercase any mistakenly uppercased schema (i.e.,
4294 * "Http://" converts to "http://"
4295 *
4296 * @return Original or modified URL
4297 *
4298 */
4299 String smartUrlFilter(String url) {
4300
4301 String inUrl = url.trim();
4302 boolean hasSpace = inUrl.indexOf(' ') != -1;
4303
4304 Matcher matcher = ACCEPTED_URI_SCHEMA.matcher(inUrl);
4305 if (matcher.matches()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08004306 // force scheme to lowercase
4307 String scheme = matcher.group(1);
4308 String lcScheme = scheme.toLowerCase();
4309 if (!lcScheme.equals(scheme)) {
Mitsuru Oshima123ecfb2009-05-18 19:11:14 -07004310 inUrl = lcScheme + matcher.group(2);
4311 }
4312 if (hasSpace) {
4313 inUrl = inUrl.replace(" ", "%20");
The Android Open Source Project0c908882009-03-03 19:32:16 -08004314 }
4315 return inUrl;
4316 }
4317 if (hasSpace) {
Satish Sampath565505b2009-05-29 15:37:27 +01004318 // FIXME: Is this the correct place to add to searches?
4319 // what if someone else calls this function?
4320 int shortcut = parseUrlShortcut(inUrl);
4321 if (shortcut != SHORTCUT_INVALID) {
4322 Browser.addSearchUrl(mResolver, inUrl);
4323 String query = inUrl.substring(2);
4324 switch (shortcut) {
4325 case SHORTCUT_GOOGLE_SEARCH:
Grace Kloba47fdfdb2009-06-30 11:15:34 -07004326 return URLUtil.composeSearchUrl(query, QuickSearch_G, QUERY_PLACE_HOLDER);
Satish Sampath565505b2009-05-29 15:37:27 +01004327 case SHORTCUT_WIKIPEDIA_SEARCH:
4328 return URLUtil.composeSearchUrl(query, QuickSearch_W, QUERY_PLACE_HOLDER);
4329 case SHORTCUT_DICTIONARY_SEARCH:
4330 return URLUtil.composeSearchUrl(query, QuickSearch_D, QUERY_PLACE_HOLDER);
4331 case SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH:
The Android Open Source Project0c908882009-03-03 19:32:16 -08004332 // FIXME: we need location in this case
Satish Sampath565505b2009-05-29 15:37:27 +01004333 return URLUtil.composeSearchUrl(query, QuickSearch_L, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004334 }
4335 }
4336 } else {
4337 if (Regex.WEB_URL_PATTERN.matcher(inUrl).matches()) {
4338 return URLUtil.guessUrl(inUrl);
4339 }
4340 }
4341
4342 Browser.addSearchUrl(mResolver, inUrl);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07004343 return URLUtil.composeSearchUrl(inUrl, QuickSearch_G, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004344 }
4345
Ben Murdochbff2d602009-07-01 20:19:05 +01004346 /* package */ void setShouldShowErrorConsole(boolean flag) {
4347 if (flag == mShouldShowErrorConsole) {
4348 // Nothing to do.
4349 return;
4350 }
4351
4352 mShouldShowErrorConsole = flag;
4353
4354 ErrorConsoleView errorConsole = mTabControl.getCurrentErrorConsole(true);
4355
4356 if (flag) {
4357 // Setting the show state of the console will cause it's the layout to be inflated.
4358 if (errorConsole.numberOfErrors() > 0) {
4359 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
4360 } else {
4361 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
4362 }
4363
4364 // Now we can add it to the main view.
4365 mErrorConsoleContainer.addView(errorConsole,
4366 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
4367 ViewGroup.LayoutParams.WRAP_CONTENT));
4368 } else {
4369 mErrorConsoleContainer.removeView(errorConsole);
4370 }
4371
4372 }
4373
Grace Klobaeb6eef42009-09-15 17:56:32 -07004374 final static int LOCK_ICON_UNSECURE = 0;
4375 final static int LOCK_ICON_SECURE = 1;
4376 final static int LOCK_ICON_MIXED = 2;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004377
4378 private int mLockIconType = LOCK_ICON_UNSECURE;
4379 private int mPrevLockType = LOCK_ICON_UNSECURE;
4380
4381 private BrowserSettings mSettings;
4382 private TabControl mTabControl;
4383 private ContentResolver mResolver;
4384 private FrameLayout mContentView;
Andrei Popescuadc008d2009-06-26 14:11:30 +01004385 private View mCustomView;
4386 private FrameLayout mCustomViewContainer;
Andrei Popescuc9b55562009-07-07 10:51:15 +01004387 private WebChromeClient.CustomViewCallback mCustomViewCallback;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004388
4389 // FIXME, temp address onPrepareMenu performance problem. When we move everything out of
4390 // view, we should rewrite this.
4391 private int mCurrentMenuState = 0;
4392 private int mMenuState = R.id.MAIN_MENU;
Andrei Popescuadc008d2009-06-26 14:11:30 +01004393 private int mOldMenuState = EMPTY_MENU;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004394 private static final int EMPTY_MENU = -1;
4395 private Menu mMenu;
4396
4397 private FindDialog mFindDialog;
4398 // Used to prevent chording to result in firing two shortcuts immediately
4399 // one after another. Fixes bug 1211714.
4400 boolean mCanChord;
4401
4402 private boolean mInLoad;
4403 private boolean mIsNetworkUp;
Ben Murdochb7cc8b42009-09-28 10:59:09 +01004404 private boolean mDidStopLoad;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004405
4406 private boolean mPageStarted;
4407 private boolean mActivityInPause = true;
4408
Ben Murdochaac7aa62009-09-17 16:57:40 +01004409 // If the frame fails to load, we should snap a second screenshot
4410 // to ensure that we get the right thumbnail (i.e. of the error page).
4411 private boolean mNeedExtraScreenShot = false;
4412
The Android Open Source Project0c908882009-03-03 19:32:16 -08004413 private boolean mMenuIsDown;
4414
The Android Open Source Project0c908882009-03-03 19:32:16 -08004415 private static boolean mInTrace;
4416
4417 // Performance probe
4418 private static final int[] SYSTEM_CPU_FORMAT = new int[] {
4419 Process.PROC_SPACE_TERM | Process.PROC_COMBINE,
4420 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 1: user time
4421 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 2: nice time
4422 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 3: sys time
4423 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 4: idle time
4424 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 5: iowait time
4425 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 6: irq time
4426 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG // 7: softirq time
4427 };
4428
4429 private long mStart;
4430 private long mProcessStart;
4431 private long mUserStart;
4432 private long mSystemStart;
4433 private long mIdleStart;
4434 private long mIrqStart;
4435
4436 private long mUiStart;
4437
4438 private Drawable mMixLockIcon;
4439 private Drawable mSecLockIcon;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004440
4441 /* hold a ref so we can auto-cancel if necessary */
4442 private AlertDialog mAlertDialog;
4443
4444 // Wait for credentials before loading google.com
4445 private ProgressDialog mCredsDlg;
4446
4447 // The up-to-date URL and title (these can be different from those stored
4448 // in WebView, since it takes some time for the information in WebView to
4449 // get updated)
4450 private String mUrl;
4451 private String mTitle;
4452
4453 // As PageInfo has different style for landscape / portrait, we have
4454 // to re-open it when configuration changed
4455 private AlertDialog mPageInfoDialog;
4456 private TabControl.Tab mPageInfoView;
4457 // If the Page-Info dialog is launched from the SSL-certificate-on-error
4458 // dialog, we should not just dismiss it, but should get back to the
4459 // SSL-certificate-on-error dialog. This flag is used to store this state
4460 private Boolean mPageInfoFromShowSSLCertificateOnError;
4461
4462 // as SSLCertificateOnError has different style for landscape / portrait,
4463 // we have to re-open it when configuration changed
4464 private AlertDialog mSSLCertificateOnErrorDialog;
4465 private WebView mSSLCertificateOnErrorView;
4466 private SslErrorHandler mSSLCertificateOnErrorHandler;
4467 private SslError mSSLCertificateOnErrorError;
4468
4469 // as SSLCertificate has different style for landscape / portrait, we
4470 // have to re-open it when configuration changed
4471 private AlertDialog mSSLCertificateDialog;
4472 private TabControl.Tab mSSLCertificateView;
4473
4474 // as HttpAuthentication has different style for landscape / portrait, we
4475 // have to re-open it when configuration changed
4476 private AlertDialog mHttpAuthenticationDialog;
4477 private HttpAuthHandler mHttpAuthHandler;
4478
4479 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_PARAMS =
4480 new FrameLayout.LayoutParams(
4481 ViewGroup.LayoutParams.FILL_PARENT,
4482 ViewGroup.LayoutParams.FILL_PARENT);
Andrei Popescuadc008d2009-06-26 14:11:30 +01004483 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_GRAVITY_CENTER =
4484 new FrameLayout.LayoutParams(
4485 ViewGroup.LayoutParams.FILL_PARENT,
4486 ViewGroup.LayoutParams.FILL_PARENT,
4487 Gravity.CENTER);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07004488 // Google search
4489 final static String QuickSearch_G = "http://www.google.com/m?q=%s";
The Android Open Source Project0c908882009-03-03 19:32:16 -08004490 // Wikipedia search
4491 final static String QuickSearch_W = "http://en.wikipedia.org/w/index.php?search=%s&go=Go";
4492 // Dictionary search
4493 final static String QuickSearch_D = "http://dictionary.reference.com/search?q=%s";
4494 // Google Mobile Local search
4495 final static String QuickSearch_L = "http://www.google.com/m/search?site=local&q=%s&near=mountain+view";
4496
4497 final static String QUERY_PLACE_HOLDER = "%s";
4498
4499 // "source" parameter for Google search through search key
4500 final static String GOOGLE_SEARCH_SOURCE_SEARCHKEY = "browser-key";
4501 // "source" parameter for Google search through goto menu
4502 final static String GOOGLE_SEARCH_SOURCE_GOTO = "browser-goto";
4503 // "source" parameter for Google search through simplily type
4504 final static String GOOGLE_SEARCH_SOURCE_TYPE = "browser-type";
4505 // "source" parameter for Google search suggested by the browser
4506 final static String GOOGLE_SEARCH_SOURCE_SUGGEST = "browser-suggest";
4507 // "source" parameter for Google search from unknown source
4508 final static String GOOGLE_SEARCH_SOURCE_UNKNOWN = "unknown";
4509
4510 private final static String LOGTAG = "browser";
4511
The Android Open Source Project0c908882009-03-03 19:32:16 -08004512 private String mLastEnteredUrl;
4513
4514 private PowerManager.WakeLock mWakeLock;
4515 private final static int WAKELOCK_TIMEOUT = 5 * 60 * 1000; // 5 minutes
4516
4517 private Toast mStopToast;
4518
Leon Scroggins68579392009-09-15 15:31:54 -04004519 private TitleBar mTitleBar;
Leon Scroggins81db3662009-06-04 17:45:11 -04004520
Ben Murdochbff2d602009-07-01 20:19:05 +01004521 private LinearLayout mErrorConsoleContainer = null;
4522 private boolean mShouldShowErrorConsole = false;
4523
The Android Open Source Project0c908882009-03-03 19:32:16 -08004524 // As the ids are dynamically created, we can't guarantee that they will
4525 // be in sequence, so this static array maps ids to a window number.
4526 final static private int[] WINDOW_SHORTCUT_ID_ARRAY =
4527 { R.id.window_one_menu_id, R.id.window_two_menu_id, R.id.window_three_menu_id,
4528 R.id.window_four_menu_id, R.id.window_five_menu_id, R.id.window_six_menu_id,
4529 R.id.window_seven_menu_id, R.id.window_eight_menu_id };
4530
4531 // monitor platform changes
4532 private IntentFilter mNetworkStateChangedFilter;
4533 private BroadcastReceiver mNetworkStateIntentReceiver;
4534
Grace Klobab4da0ad2009-05-14 14:45:40 -07004535 private BroadcastReceiver mPackageInstallationReceiver;
4536
Patrick Scott59ce8302009-09-18 16:29:38 -04004537 // AsyncTask for downloading touch icons
4538 /* package */ DownloadTouchIcon mTouchIconLoader;
4539
The Android Open Source Project0c908882009-03-03 19:32:16 -08004540 // activity requestCode
Nicolas Roard78a98e42009-05-11 13:34:17 +01004541 final static int COMBO_PAGE = 1;
4542 final static int DOWNLOAD_PAGE = 2;
4543 final static int PREFERENCES_PAGE = 3;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004544
Andrei Popescu540035d2009-09-18 18:59:20 +01004545 // the default <video> poster
4546 private Bitmap mDefaultVideoPoster;
4547 // the video progress view
4548 private View mVideoProgressView;
4549
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004550 /**
4551 * A UrlData class to abstract how the content will be set to WebView.
4552 * This base class uses loadUrl to show the content.
4553 */
4554 private static class UrlData {
4555 String mUrl;
Grace Kloba60e095c2009-06-16 11:50:55 -07004556 byte[] mPostData;
4557
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004558 UrlData(String url) {
4559 this.mUrl = url;
4560 }
Grace Kloba60e095c2009-06-16 11:50:55 -07004561
4562 void setPostData(byte[] postData) {
4563 mPostData = postData;
4564 }
4565
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004566 boolean isEmpty() {
4567 return mUrl == null || mUrl.length() == 0;
4568 }
4569
Mitsuru Oshima7944b7d2009-06-16 16:34:51 -07004570 public void loadIn(WebView webView) {
Grace Kloba60e095c2009-06-16 11:50:55 -07004571 if (mPostData != null) {
4572 webView.postUrl(mUrl, mPostData);
4573 } else {
4574 webView.loadUrl(mUrl);
4575 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004576 }
4577 };
4578
4579 /**
4580 * A subclass of UrlData class that can display inlined content using
4581 * {@link WebView#loadDataWithBaseURL(String, String, String, String, String)}.
4582 */
4583 private static class InlinedUrlData extends UrlData {
4584 InlinedUrlData(String inlined, String mimeType, String encoding, String failUrl) {
4585 super(failUrl);
4586 mInlined = inlined;
4587 mMimeType = mimeType;
4588 mEncoding = encoding;
4589 }
4590 String mMimeType;
4591 String mInlined;
4592 String mEncoding;
Mitsuru Oshima7944b7d2009-06-16 16:34:51 -07004593 @Override
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004594 boolean isEmpty() {
Ben Murdochbff2d602009-07-01 20:19:05 +01004595 return mInlined == null || mInlined.length() == 0 || super.isEmpty();
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004596 }
4597
Mitsuru Oshima7944b7d2009-06-16 16:34:51 -07004598 @Override
4599 public void loadIn(WebView webView) {
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004600 webView.loadDataWithBaseURL(null, mInlined, mMimeType, mEncoding, mUrl);
4601 }
4602 }
4603
Leon Scroggins1f005d32009-08-10 17:36:42 -04004604 /* package */ static final UrlData EMPTY_URL_DATA = new UrlData(null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004605}