WebView.java revision 959046c3aa38a99acc3f582232710ebc543d938a
1/* 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 android.webkit; 18 19import android.app.AlertDialog; 20import android.content.Context; 21import android.content.DialogInterface; 22import android.content.Intent; 23import android.content.DialogInterface.OnCancelListener; 24import android.database.DataSetObserver; 25import android.graphics.Bitmap; 26import android.graphics.Canvas; 27import android.graphics.Color; 28import android.graphics.Paint; 29import android.graphics.Path; 30import android.graphics.Picture; 31import android.graphics.Point; 32import android.graphics.Rect; 33import android.graphics.Region; 34import android.net.http.SslCertificate; 35import android.net.Uri; 36import android.os.Bundle; 37import android.os.Handler; 38import android.os.Message; 39import android.os.ServiceManager; 40import android.os.SystemClock; 41import android.provider.Checkin; 42import android.text.IClipboard; 43import android.text.Selection; 44import android.text.Spannable; 45import android.util.AttributeSet; 46import android.util.EventLog; 47import android.util.Log; 48import android.view.Gravity; 49import android.view.KeyEvent; 50import android.view.LayoutInflater; 51import android.view.MotionEvent; 52import android.view.SoundEffectConstants; 53import android.view.VelocityTracker; 54import android.view.View; 55import android.view.ViewConfiguration; 56import android.view.ViewGroup; 57import android.view.ViewParent; 58import android.view.ViewTreeObserver; 59import android.view.animation.AlphaAnimation; 60import android.view.inputmethod.InputMethodManager; 61import android.webkit.WebTextView.AutoCompleteAdapter; 62import android.webkit.WebViewCore.EventHub; 63import android.widget.AbsoluteLayout; 64import android.widget.Adapter; 65import android.widget.AdapterView; 66import android.widget.ArrayAdapter; 67import android.widget.FrameLayout; 68import android.widget.ImageView; 69import android.widget.ListView; 70import android.widget.Scroller; 71import android.widget.Toast; 72import android.widget.ZoomButtonsController; 73import android.widget.ZoomControls; 74import android.widget.AdapterView.OnItemClickListener; 75 76import java.io.File; 77import java.io.FileInputStream; 78import java.io.FileNotFoundException; 79import java.io.FileOutputStream; 80import java.io.IOException; 81import java.net.URLDecoder; 82import java.util.ArrayList; 83import java.util.List; 84 85/** 86 * <p>A View that displays web pages. This class is the basis upon which you 87 * can roll your own web browser or simply display some online content within your Activity. 88 * It uses the WebKit rendering engine to display 89 * web pages and includes methods to navigate forward and backward 90 * through a history, zoom in and out, perform text searches and more.</p> 91 * <p>To enable the built-in zoom, set 92 * {@link #getSettings() WebSettings}.{@link WebSettings#setBuiltInZoomControls(boolean)} 93 * (introduced in API version 3). 94 * <p>Note that, in order for your Activity to access the Internet and load web pages 95 * in a WebView, you must add the <var>INTERNET</var> permissions to your 96 * Android Manifest file:</p> 97 * <pre><uses-permission android:name="android.permission.INTERNET" /></pre> 98 * 99 * <p>This must be a child of the <code><manifest></code> element.</p> 100 * 101 * <h3>Basic usage</h3> 102 * 103 * <p>By default, a WebView provides no browser-like widgets, does not 104 * enable JavaScript and errors will be ignored. If your goal is only 105 * to display some HTML as a part of your UI, this is probably fine; 106 * the user won't need to interact with the web page beyond reading 107 * it, and the web page won't need to interact with the user. If you 108 * actually want a fully blown web browser, then you probably want to 109 * invoke the Browser application with your URL rather than show it 110 * with a WebView. See {@link android.content.Intent} for more information.</p> 111 * 112 * <pre class="prettyprint"> 113 * WebView webview = new WebView(this); 114 * setContentView(webview); 115 * 116 * // Simplest usage: note that an exception will NOT be thrown 117 * // if there is an error loading this page (see below). 118 * webview.loadUrl("http://slashdot.org/"); 119 * 120 * // Of course you can also load from any string: 121 * String summary = "<html><body>You scored <b>192</b> points.</body></html>"; 122 * webview.loadData(summary, "text/html", "utf-8"); 123 * // ... although note that there are restrictions on what this HTML can do. 124 * // See the JavaDocs for loadData and loadDataWithBaseUrl for more info. 125 * </pre> 126 * 127 * <p>A WebView has several customization points where you can add your 128 * own behavior. These are:</p> 129 * 130 * <ul> 131 * <li>Creating and setting a {@link android.webkit.WebChromeClient} subclass. 132 * This class is called when something that might impact a 133 * browser UI happens, for instance, progress updates and 134 * JavaScript alerts are sent here. 135 * </li> 136 * <li>Creating and setting a {@link android.webkit.WebViewClient} subclass. 137 * It will be called when things happen that impact the 138 * rendering of the content, eg, errors or form submissions. You 139 * can also intercept URL loading here.</li> 140 * <li>Via the {@link android.webkit.WebSettings} class, which contains 141 * miscellaneous configuration. </li> 142 * <li>With the {@link android.webkit.WebView#addJavascriptInterface} method. 143 * This lets you bind Java objects into the WebView so they can be 144 * controlled from the web pages JavaScript.</li> 145 * </ul> 146 * 147 * <p>Here's a more complicated example, showing error handling, 148 * settings, and progress notification:</p> 149 * 150 * <pre class="prettyprint"> 151 * // Let's display the progress in the activity title bar, like the 152 * // browser app does. 153 * getWindow().requestFeature(Window.FEATURE_PROGRESS); 154 * 155 * webview.getSettings().setJavaScriptEnabled(true); 156 * 157 * final Activity activity = this; 158 * webview.setWebChromeClient(new WebChromeClient() { 159 * public void onProgressChanged(WebView view, int progress) { 160 * // Activities and WebViews measure progress with different scales. 161 * // The progress meter will automatically disappear when we reach 100% 162 * activity.setProgress(progress * 1000); 163 * } 164 * }); 165 * webview.setWebViewClient(new WebViewClient() { 166 * public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) { 167 * Toast.makeText(activity, "Oh no! " + description, Toast.LENGTH_SHORT).show(); 168 * } 169 * }); 170 * 171 * webview.loadUrl("http://slashdot.org/"); 172 * </pre> 173 * 174 * <h3>Cookie and window management</h3> 175 * 176 * <p>For obvious security reasons, your application has its own 177 * cache, cookie store etc - it does not share the Browser 178 * applications data. Cookies are managed on a separate thread, so 179 * operations like index building don't block the UI 180 * thread. Follow the instructions in {@link android.webkit.CookieSyncManager} 181 * if you want to use cookies in your application. 182 * </p> 183 * 184 * <p>By default, requests by the HTML to open new windows are 185 * ignored. This is true whether they be opened by JavaScript or by 186 * the target attribute on a link. You can customize your 187 * WebChromeClient to provide your own behaviour for opening multiple windows, 188 * and render them in whatever manner you want.</p> 189 * 190 * <p>Standard behavior for an Activity is to be destroyed and 191 * recreated when the devices orientation is changed. This will cause 192 * the WebView to reload the current page. If you don't want that, you 193 * can set your Activity to handle the orientation and keyboardHidden 194 * changes, and then just leave the WebView alone. It'll automatically 195 * re-orient itself as appropriate.</p> 196 */ 197public class WebView extends AbsoluteLayout 198 implements ViewTreeObserver.OnGlobalFocusChangeListener, 199 ViewGroup.OnHierarchyChangeListener { 200 201 // if AUTO_REDRAW_HACK is true, then the CALL key will toggle redrawing 202 // the screen all-the-time. Good for profiling our drawing code 203 static private final boolean AUTO_REDRAW_HACK = false; 204 // true means redraw the screen all-the-time. Only with AUTO_REDRAW_HACK 205 private boolean mAutoRedraw; 206 207 static final String LOGTAG = "webview"; 208 209 static class ScaleLimitData { 210 int mMinScale; 211 int mMaxScale; 212 } 213 214 private static class ExtendedZoomControls extends FrameLayout { 215 public ExtendedZoomControls(Context context, AttributeSet attrs) { 216 super(context, attrs); 217 LayoutInflater inflater = (LayoutInflater) 218 context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 219 inflater.inflate(com.android.internal.R.layout.zoom_magnify, this, true); 220 mPlusMinusZoomControls = (ZoomControls) findViewById( 221 com.android.internal.R.id.zoomControls); 222 mZoomMagnify = (ImageView) findViewById(com.android.internal.R.id.zoomMagnify); 223 } 224 225 public void show(boolean showZoom, boolean canZoomOut) { 226 mPlusMinusZoomControls.setVisibility( 227 showZoom ? View.VISIBLE : View.GONE); 228 mZoomMagnify.setVisibility(canZoomOut ? View.VISIBLE : View.GONE); 229 fade(View.VISIBLE, 0.0f, 1.0f); 230 } 231 232 public void hide() { 233 fade(View.GONE, 1.0f, 0.0f); 234 } 235 236 private void fade(int visibility, float startAlpha, float endAlpha) { 237 AlphaAnimation anim = new AlphaAnimation(startAlpha, endAlpha); 238 anim.setDuration(500); 239 startAnimation(anim); 240 setVisibility(visibility); 241 } 242 243 public void setIsZoomMagnifyEnabled(boolean isEnabled) { 244 mZoomMagnify.setEnabled(isEnabled); 245 } 246 247 public boolean hasFocus() { 248 return mPlusMinusZoomControls.hasFocus() || mZoomMagnify.hasFocus(); 249 } 250 251 public void setOnZoomInClickListener(OnClickListener listener) { 252 mPlusMinusZoomControls.setOnZoomInClickListener(listener); 253 } 254 255 public void setOnZoomOutClickListener(OnClickListener listener) { 256 mPlusMinusZoomControls.setOnZoomOutClickListener(listener); 257 } 258 259 public void setOnZoomMagnifyClickListener(OnClickListener listener) { 260 mZoomMagnify.setOnClickListener(listener); 261 } 262 263 ZoomControls mPlusMinusZoomControls; 264 ImageView mZoomMagnify; 265 } 266 267 /** 268 * Transportation object for returning WebView across thread boundaries. 269 */ 270 public class WebViewTransport { 271 private WebView mWebview; 272 273 /** 274 * Set the WebView to the transportation object. 275 * @param webview The WebView to transport. 276 */ 277 public synchronized void setWebView(WebView webview) { 278 mWebview = webview; 279 } 280 281 /** 282 * Return the WebView object. 283 * @return WebView The transported WebView object. 284 */ 285 public synchronized WebView getWebView() { 286 return mWebview; 287 } 288 } 289 290 // A final CallbackProxy shared by WebViewCore and BrowserFrame. 291 private final CallbackProxy mCallbackProxy; 292 293 private final WebViewDatabase mDatabase; 294 295 // SSL certificate for the main top-level page (if secure) 296 private SslCertificate mCertificate; 297 298 // Native WebView pointer that is 0 until the native object has been 299 // created. 300 private int mNativeClass; 301 // This would be final but it needs to be set to null when the WebView is 302 // destroyed. 303 private WebViewCore mWebViewCore; 304 // Handler for dispatching UI messages. 305 /* package */ final Handler mPrivateHandler = new PrivateHandler(); 306 private WebTextView mWebTextView; 307 // Used to ignore changes to webkit text that arrives to the UI side after 308 // more key events. 309 private int mTextGeneration; 310 311 // The list of loaded plugins. 312 private static PluginList sPluginList; 313 314 /** 315 * Position of the last touch event. 316 */ 317 private float mLastTouchX; 318 private float mLastTouchY; 319 320 /** 321 * Time of the last touch event. 322 */ 323 private long mLastTouchTime; 324 325 /** 326 * Time of the last time sending touch event to WebViewCore 327 */ 328 private long mLastSentTouchTime; 329 330 /** 331 * The minimum elapsed time before sending another ACTION_MOVE event to 332 * WebViewCore 333 */ 334 private static final int TOUCH_SENT_INTERVAL = 100; 335 336 /** 337 * Helper class to get velocity for fling 338 */ 339 VelocityTracker mVelocityTracker; 340 341 /** 342 * Touch mode 343 */ 344 private int mTouchMode = TOUCH_DONE_MODE; 345 private static final int TOUCH_INIT_MODE = 1; 346 private static final int TOUCH_DRAG_START_MODE = 2; 347 private static final int TOUCH_DRAG_MODE = 3; 348 private static final int TOUCH_SHORTPRESS_START_MODE = 4; 349 private static final int TOUCH_SHORTPRESS_MODE = 5; 350 private static final int TOUCH_DOUBLECLICK_MODE = 6; 351 private static final int TOUCH_DONE_MODE = 7; 352 private static final int TOUCH_SELECT_MODE = 8; 353 // touch mode values specific to scale+scroll 354 private static final int FIRST_SCROLL_ZOOM = 9; 355 private static final int SCROLL_ZOOM_ANIMATION_IN = 9; 356 private static final int SCROLL_ZOOM_ANIMATION_OUT = 10; 357 private static final int SCROLL_ZOOM_OUT = 11; 358 private static final int LAST_SCROLL_ZOOM = 11; 359 // end of touch mode values specific to scale+scroll 360 361 // Whether to forward the touch events to WebCore 362 private boolean mForwardTouchEvents = false; 363 364 // Whether to prevent drag during touch. The initial value depends on 365 // mForwardTouchEvents. If WebCore wants touch events, we assume it will 366 // take control of touch events unless it says no for touch down event. 367 private boolean mPreventDrag; 368 369 // Whether or not to draw the cursor ring. 370 private boolean mDrawCursorRing = true; 371 372 // true if onPause has been called (and not onResume) 373 private boolean mIsPaused; 374 375 /** 376 * Customizable constant 377 */ 378 // pre-computed square of ViewConfiguration.getScaledTouchSlop() 379 private int mTouchSlopSquare; 380 // pre-computed density adjusted navigation slop 381 private int mNavSlop; 382 // This should be ViewConfiguration.getTapTimeout() 383 // But system time out is 100ms, which is too short for the browser. 384 // In the browser, if it switches out of tap too soon, jump tap won't work. 385 private static final int TAP_TIMEOUT = 200; 386 // This should be ViewConfiguration.getLongPressTimeout() 387 // But system time out is 500ms, which is too short for the browser. 388 // With a short timeout, it's difficult to treat trigger a short press. 389 private static final int LONG_PRESS_TIMEOUT = 1000; 390 // needed to avoid flinging after a pause of no movement 391 private static final int MIN_FLING_TIME = 250; 392 // The time that the Zoom Controls are visible before fading away 393 private static final long ZOOM_CONTROLS_TIMEOUT = 394 ViewConfiguration.getZoomControlsTimeout(); 395 // The amount of content to overlap between two screens when going through 396 // pages with the space bar, in pixels. 397 private static final int PAGE_SCROLL_OVERLAP = 24; 398 399 /** 400 * These prevent calling requestLayout if either dimension is fixed. This 401 * depends on the layout parameters and the measure specs. 402 */ 403 boolean mWidthCanMeasure; 404 boolean mHeightCanMeasure; 405 406 // Remember the last dimensions we sent to the native side so we can avoid 407 // sending the same dimensions more than once. 408 int mLastWidthSent; 409 int mLastHeightSent; 410 411 private int mContentWidth; // cache of value from WebViewCore 412 private int mContentHeight; // cache of value from WebViewCore 413 414 // Need to have the separate control for horizontal and vertical scrollbar 415 // style than the View's single scrollbar style 416 private boolean mOverlayHorizontalScrollbar = true; 417 private boolean mOverlayVerticalScrollbar = false; 418 419 // our standard speed. this way small distances will be traversed in less 420 // time than large distances, but we cap the duration, so that very large 421 // distances won't take too long to get there. 422 private static final int STD_SPEED = 480; // pixels per second 423 // time for the longest scroll animation 424 private static final int MAX_DURATION = 750; // milliseconds 425 private Scroller mScroller; 426 427 private boolean mWrapContent; 428 429 /** 430 * Private message ids 431 */ 432 private static final int REMEMBER_PASSWORD = 1; 433 private static final int NEVER_REMEMBER_PASSWORD = 2; 434 private static final int SWITCH_TO_SHORTPRESS = 3; 435 private static final int SWITCH_TO_LONGPRESS = 4; 436 private static final int REQUEST_FORM_DATA = 6; 437 private static final int SWITCH_TO_CLICK = 7; 438 private static final int RESUME_WEBCORE_UPDATE = 8; 439 440 //! arg1=x, arg2=y 441 static final int SCROLL_TO_MSG_ID = 10; 442 static final int SCROLL_BY_MSG_ID = 11; 443 //! arg1=x, arg2=y 444 static final int SPAWN_SCROLL_TO_MSG_ID = 12; 445 //! arg1=x, arg2=y 446 static final int SYNC_SCROLL_TO_MSG_ID = 13; 447 static final int NEW_PICTURE_MSG_ID = 14; 448 static final int UPDATE_TEXT_ENTRY_MSG_ID = 15; 449 static final int WEBCORE_INITIALIZED_MSG_ID = 16; 450 static final int UPDATE_TEXTFIELD_TEXT_MSG_ID = 17; 451 static final int DID_FIRST_LAYOUT_MSG_ID = 18; 452 453 static final int UPDATE_CLIPBOARD = 22; 454 static final int LONG_PRESS_CENTER = 23; 455 static final int PREVENT_TOUCH_ID = 24; 456 static final int WEBCORE_NEED_TOUCH_EVENTS = 25; 457 // obj=Rect in doc coordinates 458 static final int INVAL_RECT_MSG_ID = 26; 459 460 static final String[] HandlerDebugString = { 461 "REMEMBER_PASSWORD", // = 1; 462 "NEVER_REMEMBER_PASSWORD", // = 2; 463 "SWITCH_TO_SHORTPRESS", // = 3; 464 "SWITCH_TO_LONGPRESS", // = 4; 465 "5", 466 "REQUEST_FORM_DATA", // = 6; 467 "SWITCH_TO_CLICK", // = 7; 468 "RESUME_WEBCORE_UPDATE", // = 8; 469 "9", 470 "SCROLL_TO_MSG_ID", // = 10; 471 "SCROLL_BY_MSG_ID", // = 11; 472 "SPAWN_SCROLL_TO_MSG_ID", // = 12; 473 "SYNC_SCROLL_TO_MSG_ID", // = 13; 474 "NEW_PICTURE_MSG_ID", // = 14; 475 "UPDATE_TEXT_ENTRY_MSG_ID", // = 15; 476 "WEBCORE_INITIALIZED_MSG_ID", // = 16; 477 "UPDATE_TEXTFIELD_TEXT_MSG_ID", // = 17; 478 "DID_FIRST_LAYOUT_MSG_ID", // = 18; 479 "19", 480 "20", 481 "21", // = 21; 482 "UPDATE_CLIPBOARD", // = 22; 483 "LONG_PRESS_CENTER", // = 23; 484 "PREVENT_TOUCH_ID", // = 24; 485 "WEBCORE_NEED_TOUCH_EVENTS", // = 25; 486 "INVAL_RECT_MSG_ID" // = 26; 487 }; 488 489 // width which view is considered to be fully zoomed out 490 static final int ZOOM_OUT_WIDTH = 1008; 491 492 // default scale limit. Depending on the display density 493 private static float DEFAULT_MAX_ZOOM_SCALE; 494 private static float DEFAULT_MIN_ZOOM_SCALE; 495 // scale limit, which can be set through viewport meta tag in the web page 496 private float mMaxZoomScale; 497 private float mMinZoomScale; 498 private boolean mMinZoomScaleFixed = false; 499 500 // initial scale in percent. 0 means using default. 501 private int mInitialScale = 0; 502 503 // default scale. Depending on the display density. 504 static int DEFAULT_SCALE_PERCENT; 505 private float mDefaultScale; 506 507 // set to true temporarily while the zoom control is being dragged 508 private boolean mPreviewZoomOnly = false; 509 510 // computed scale and inverse, from mZoomWidth. 511 private float mActualScale; 512 private float mInvActualScale; 513 // if this is non-zero, it is used on drawing rather than mActualScale 514 private float mZoomScale; 515 private float mInvInitialZoomScale; 516 private float mInvFinalZoomScale; 517 private long mZoomStart; 518 private static final int ZOOM_ANIMATION_LENGTH = 500; 519 520 private boolean mUserScroll = false; 521 522 private int mSnapScrollMode = SNAP_NONE; 523 private static final int SNAP_NONE = 1; 524 private static final int SNAP_X = 2; 525 private static final int SNAP_Y = 3; 526 private static final int SNAP_X_LOCK = 4; 527 private static final int SNAP_Y_LOCK = 5; 528 private boolean mSnapPositive; 529 530 // Used to match key downs and key ups 531 private boolean mGotKeyDown; 532 533 /* package */ static boolean mLogEvent = true; 534 private static final int EVENT_LOG_ZOOM_LEVEL_CHANGE = 70101; 535 private static final int EVENT_LOG_DOUBLE_TAP_DURATION = 70102; 536 537 // for event log 538 private long mLastTouchUpTime = 0; 539 540 /** 541 * URI scheme for telephone number 542 */ 543 public static final String SCHEME_TEL = "tel:"; 544 /** 545 * URI scheme for email address 546 */ 547 public static final String SCHEME_MAILTO = "mailto:"; 548 /** 549 * URI scheme for map address 550 */ 551 public static final String SCHEME_GEO = "geo:0,0?q="; 552 553 private int mBackgroundColor = Color.WHITE; 554 555 // Used to notify listeners of a new picture. 556 private PictureListener mPictureListener; 557 /** 558 * Interface to listen for new pictures as they change. 559 */ 560 public interface PictureListener { 561 /** 562 * Notify the listener that the picture has changed. 563 * @param view The WebView that owns the picture. 564 * @param picture The new picture. 565 */ 566 public void onNewPicture(WebView view, Picture picture); 567 } 568 569 // FIXME: Want to make this public, but need to change the API file. 570 public /*static*/ class HitTestResult { 571 /** 572 * Default HitTestResult, where the target is unknown 573 */ 574 public static final int UNKNOWN_TYPE = 0; 575 /** 576 * HitTestResult for hitting a HTML::a tag 577 */ 578 public static final int ANCHOR_TYPE = 1; 579 /** 580 * HitTestResult for hitting a phone number 581 */ 582 public static final int PHONE_TYPE = 2; 583 /** 584 * HitTestResult for hitting a map address 585 */ 586 public static final int GEO_TYPE = 3; 587 /** 588 * HitTestResult for hitting an email address 589 */ 590 public static final int EMAIL_TYPE = 4; 591 /** 592 * HitTestResult for hitting an HTML::img tag 593 */ 594 public static final int IMAGE_TYPE = 5; 595 /** 596 * HitTestResult for hitting a HTML::a tag which contains HTML::img 597 */ 598 public static final int IMAGE_ANCHOR_TYPE = 6; 599 /** 600 * HitTestResult for hitting a HTML::a tag with src=http 601 */ 602 public static final int SRC_ANCHOR_TYPE = 7; 603 /** 604 * HitTestResult for hitting a HTML::a tag with src=http + HTML::img 605 */ 606 public static final int SRC_IMAGE_ANCHOR_TYPE = 8; 607 /** 608 * HitTestResult for hitting an edit text area 609 */ 610 public static final int EDIT_TEXT_TYPE = 9; 611 612 private int mType; 613 private String mExtra; 614 615 HitTestResult() { 616 mType = UNKNOWN_TYPE; 617 } 618 619 private void setType(int type) { 620 mType = type; 621 } 622 623 private void setExtra(String extra) { 624 mExtra = extra; 625 } 626 627 public int getType() { 628 return mType; 629 } 630 631 public String getExtra() { 632 return mExtra; 633 } 634 } 635 636 // The View containing the zoom controls 637 private ExtendedZoomControls mZoomControls; 638 private Runnable mZoomControlRunnable; 639 640 private ZoomButtonsController mZoomButtonsController; 641 642 // These keep track of the center point of the zoom. They are used to 643 // determine the point around which we should zoom. 644 private float mZoomCenterX; 645 private float mZoomCenterY; 646 647 private ZoomButtonsController.OnZoomListener mZoomListener = 648 new ZoomButtonsController.OnZoomListener() { 649 650 public void onVisibilityChanged(boolean visible) { 651 if (visible) { 652 switchOutDrawHistory(); 653 updateZoomButtonsEnabled(); 654 } 655 } 656 657 public void onZoom(boolean zoomIn) { 658 if (zoomIn) { 659 zoomIn(); 660 } else { 661 zoomOut(); 662 } 663 664 updateZoomButtonsEnabled(); 665 } 666 }; 667 668 /** 669 * Construct a new WebView with a Context object. 670 * @param context A Context object used to access application assets. 671 */ 672 public WebView(Context context) { 673 this(context, null); 674 } 675 676 /** 677 * Construct a new WebView with layout parameters. 678 * @param context A Context object used to access application assets. 679 * @param attrs An AttributeSet passed to our parent. 680 */ 681 public WebView(Context context, AttributeSet attrs) { 682 this(context, attrs, com.android.internal.R.attr.webViewStyle); 683 } 684 685 /** 686 * Construct a new WebView with layout parameters and a default style. 687 * @param context A Context object used to access application assets. 688 * @param attrs An AttributeSet passed to our parent. 689 * @param defStyle The default style resource ID. 690 */ 691 public WebView(Context context, AttributeSet attrs, int defStyle) { 692 super(context, attrs, defStyle); 693 init(); 694 695 mCallbackProxy = new CallbackProxy(context, this); 696 mWebViewCore = new WebViewCore(context, this, mCallbackProxy); 697 mDatabase = WebViewDatabase.getInstance(context); 698 mScroller = new Scroller(context); 699 700 mZoomButtonsController = new ZoomButtonsController(this); 701 mZoomButtonsController.setOnZoomListener(mZoomListener); 702 // ZoomButtonsController positions the buttons at the bottom, but in 703 // the middle. Change their layout parameters so they appear on the 704 // right. 705 View controls = mZoomButtonsController.getZoomControls(); 706 ViewGroup.LayoutParams params = controls.getLayoutParams(); 707 if (params instanceof FrameLayout.LayoutParams) { 708 FrameLayout.LayoutParams frameParams = (FrameLayout.LayoutParams) 709 params; 710 frameParams.gravity = Gravity.RIGHT; 711 } 712 } 713 714 private void updateZoomButtonsEnabled() { 715 boolean canZoomIn = mActualScale < mMaxZoomScale; 716 boolean canZoomOut = mActualScale > mMinZoomScale; 717 if (!canZoomIn && !canZoomOut) { 718 // Hide the zoom in and out buttons, as well as the fit to page 719 // button, if the page cannot zoom 720 mZoomButtonsController.getZoomControls().setVisibility(View.GONE); 721 } else { 722 // Bring back the hidden zoom controls. 723 mZoomButtonsController.getZoomControls() 724 .setVisibility(View.VISIBLE); 725 // Set each one individually, as a page may be able to zoom in 726 // or out. 727 mZoomButtonsController.setZoomInEnabled(canZoomIn); 728 mZoomButtonsController.setZoomOutEnabled(canZoomOut); 729 } 730 } 731 732 private void init() { 733 setWillNotDraw(false); 734 setFocusable(true); 735 setFocusableInTouchMode(true); 736 setClickable(true); 737 setLongClickable(true); 738 739 final int slop = ViewConfiguration.get(getContext()).getScaledTouchSlop(); 740 mTouchSlopSquare = slop * slop; 741 mMinLockSnapReverseDistance = slop; 742 final float density = getContext().getResources().getDisplayMetrics().density; 743 // use one line height, 16 based on our current default font, for how 744 // far we allow a touch be away from the edge of a link 745 mNavSlop = (int) (16 * density); 746 // density adjusted scale factors 747 DEFAULT_SCALE_PERCENT = (int) (100 * density); 748 mDefaultScale = density; 749 mActualScale = density; 750 mInvActualScale = 1 / density; 751 DEFAULT_MAX_ZOOM_SCALE = 4.0f * density; 752 DEFAULT_MIN_ZOOM_SCALE = 0.25f * density; 753 mMaxZoomScale = DEFAULT_MAX_ZOOM_SCALE; 754 mMinZoomScale = DEFAULT_MIN_ZOOM_SCALE; 755 } 756 757 /* package */void updateDefaultZoomDensity(int zoomDensity) { 758 final float density = getContext().getResources().getDisplayMetrics().density 759 * 100 / zoomDensity; 760 if (Math.abs(density - mDefaultScale) > 0.01) { 761 float scaleFactor = density / mDefaultScale; 762 // adjust the limits 763 mNavSlop = (int) (16 * density); 764 DEFAULT_SCALE_PERCENT = (int) (100 * density); 765 DEFAULT_MAX_ZOOM_SCALE = 4.0f * density; 766 DEFAULT_MIN_ZOOM_SCALE = 0.25f * density; 767 mDefaultScale = density; 768 mMaxZoomScale *= scaleFactor; 769 mMinZoomScale *= scaleFactor; 770 setNewZoomScale(mActualScale * scaleFactor, false); 771 } 772 } 773 774 /* package */ boolean onSavePassword(String schemePlusHost, String username, 775 String password, final Message resumeMsg) { 776 boolean rVal = false; 777 if (resumeMsg == null) { 778 // null resumeMsg implies saving password silently 779 mDatabase.setUsernamePassword(schemePlusHost, username, password); 780 } else { 781 final Message remember = mPrivateHandler.obtainMessage( 782 REMEMBER_PASSWORD); 783 remember.getData().putString("host", schemePlusHost); 784 remember.getData().putString("username", username); 785 remember.getData().putString("password", password); 786 remember.obj = resumeMsg; 787 788 final Message neverRemember = mPrivateHandler.obtainMessage( 789 NEVER_REMEMBER_PASSWORD); 790 neverRemember.getData().putString("host", schemePlusHost); 791 neverRemember.getData().putString("username", username); 792 neverRemember.getData().putString("password", password); 793 neverRemember.obj = resumeMsg; 794 795 new AlertDialog.Builder(getContext()) 796 .setTitle(com.android.internal.R.string.save_password_label) 797 .setMessage(com.android.internal.R.string.save_password_message) 798 .setPositiveButton(com.android.internal.R.string.save_password_notnow, 799 new DialogInterface.OnClickListener() { 800 public void onClick(DialogInterface dialog, int which) { 801 resumeMsg.sendToTarget(); 802 } 803 }) 804 .setNeutralButton(com.android.internal.R.string.save_password_remember, 805 new DialogInterface.OnClickListener() { 806 public void onClick(DialogInterface dialog, int which) { 807 remember.sendToTarget(); 808 } 809 }) 810 .setNegativeButton(com.android.internal.R.string.save_password_never, 811 new DialogInterface.OnClickListener() { 812 public void onClick(DialogInterface dialog, int which) { 813 neverRemember.sendToTarget(); 814 } 815 }) 816 .setOnCancelListener(new OnCancelListener() { 817 public void onCancel(DialogInterface dialog) { 818 resumeMsg.sendToTarget(); 819 } 820 }).show(); 821 // Return true so that WebViewCore will pause while the dialog is 822 // up. 823 rVal = true; 824 } 825 return rVal; 826 } 827 828 @Override 829 public void setScrollBarStyle(int style) { 830 if (style == View.SCROLLBARS_INSIDE_INSET 831 || style == View.SCROLLBARS_OUTSIDE_INSET) { 832 mOverlayHorizontalScrollbar = mOverlayVerticalScrollbar = false; 833 } else { 834 mOverlayHorizontalScrollbar = mOverlayVerticalScrollbar = true; 835 } 836 super.setScrollBarStyle(style); 837 } 838 839 /** 840 * Specify whether the horizontal scrollbar has overlay style. 841 * @param overlay TRUE if horizontal scrollbar should have overlay style. 842 */ 843 public void setHorizontalScrollbarOverlay(boolean overlay) { 844 mOverlayHorizontalScrollbar = overlay; 845 } 846 847 /** 848 * Specify whether the vertical scrollbar has overlay style. 849 * @param overlay TRUE if vertical scrollbar should have overlay style. 850 */ 851 public void setVerticalScrollbarOverlay(boolean overlay) { 852 mOverlayVerticalScrollbar = overlay; 853 } 854 855 /** 856 * Return whether horizontal scrollbar has overlay style 857 * @return TRUE if horizontal scrollbar has overlay style. 858 */ 859 public boolean overlayHorizontalScrollbar() { 860 return mOverlayHorizontalScrollbar; 861 } 862 863 /** 864 * Return whether vertical scrollbar has overlay style 865 * @return TRUE if vertical scrollbar has overlay style. 866 */ 867 public boolean overlayVerticalScrollbar() { 868 return mOverlayVerticalScrollbar; 869 } 870 871 /* 872 * Return the width of the view where the content of WebView should render 873 * to. 874 */ 875 private int getViewWidth() { 876 if (!isVerticalScrollBarEnabled() || mOverlayVerticalScrollbar) { 877 return getWidth(); 878 } else { 879 return getWidth() - getVerticalScrollbarWidth(); 880 } 881 } 882 883 /* 884 * Return the height of the view where the content of WebView should render 885 * to. 886 */ 887 private int getViewHeight() { 888 if (!isHorizontalScrollBarEnabled() || mOverlayHorizontalScrollbar) { 889 return getHeight(); 890 } else { 891 return getHeight() - getHorizontalScrollbarHeight(); 892 } 893 } 894 895 /** 896 * @return The SSL certificate for the main top-level page or null if 897 * there is no certificate (the site is not secure). 898 */ 899 public SslCertificate getCertificate() { 900 return mCertificate; 901 } 902 903 /** 904 * Sets the SSL certificate for the main top-level page. 905 */ 906 public void setCertificate(SslCertificate certificate) { 907 // here, the certificate can be null (if the site is not secure) 908 mCertificate = certificate; 909 } 910 911 //------------------------------------------------------------------------- 912 // Methods called by activity 913 //------------------------------------------------------------------------- 914 915 /** 916 * Save the username and password for a particular host in the WebView's 917 * internal database. 918 * @param host The host that required the credentials. 919 * @param username The username for the given host. 920 * @param password The password for the given host. 921 */ 922 public void savePassword(String host, String username, String password) { 923 mDatabase.setUsernamePassword(host, username, password); 924 } 925 926 /** 927 * Set the HTTP authentication credentials for a given host and realm. 928 * 929 * @param host The host for the credentials. 930 * @param realm The realm for the credentials. 931 * @param username The username for the password. If it is null, it means 932 * password can't be saved. 933 * @param password The password 934 */ 935 public void setHttpAuthUsernamePassword(String host, String realm, 936 String username, String password) { 937 mDatabase.setHttpAuthUsernamePassword(host, realm, username, password); 938 } 939 940 /** 941 * Retrieve the HTTP authentication username and password for a given 942 * host & realm pair 943 * 944 * @param host The host for which the credentials apply. 945 * @param realm The realm for which the credentials apply. 946 * @return String[] if found, String[0] is username, which can be null and 947 * String[1] is password. Return null if it can't find anything. 948 */ 949 public String[] getHttpAuthUsernamePassword(String host, String realm) { 950 return mDatabase.getHttpAuthUsernamePassword(host, realm); 951 } 952 953 /** 954 * Destroy the internal state of the WebView. This method should be called 955 * after the WebView has been removed from the view system. No other 956 * methods may be called on a WebView after destroy. 957 */ 958 public void destroy() { 959 clearTextEntry(); 960 if (mWebViewCore != null) { 961 // Set the handlers to null before destroying WebViewCore so no 962 // more messages will be posted. 963 mCallbackProxy.setWebViewClient(null); 964 mCallbackProxy.setWebChromeClient(null); 965 // Tell WebViewCore to destroy itself 966 WebViewCore webViewCore = mWebViewCore; 967 mWebViewCore = null; // prevent using partial webViewCore 968 webViewCore.destroy(); 969 // Remove any pending messages that might not be serviced yet. 970 mPrivateHandler.removeCallbacksAndMessages(null); 971 mCallbackProxy.removeCallbacksAndMessages(null); 972 // Wake up the WebCore thread just in case it is waiting for a 973 // javascript dialog. 974 synchronized (mCallbackProxy) { 975 mCallbackProxy.notify(); 976 } 977 } 978 if (mNativeClass != 0) { 979 nativeDestroy(); 980 mNativeClass = 0; 981 } 982 } 983 984 /** 985 * Enables platform notifications of data state and proxy changes. 986 */ 987 public static void enablePlatformNotifications() { 988 Network.enablePlatformNotifications(); 989 } 990 991 /** 992 * If platform notifications are enabled, this should be called 993 * from the Activity's onPause() or onStop(). 994 */ 995 public static void disablePlatformNotifications() { 996 Network.disablePlatformNotifications(); 997 } 998 999 /** 1000 * Inform WebView of the network state. This is used to set 1001 * the javascript property window.navigator.isOnline and 1002 * generates the online/offline event as specified in HTML5, sec. 5.7.7 1003 * @param networkUp boolean indicating if network is available 1004 */ 1005 public void setNetworkAvailable(boolean networkUp) { 1006 mWebViewCore.sendMessage(EventHub.SET_NETWORK_STATE, 1007 networkUp ? 1 : 0, 0); 1008 } 1009 1010 /** 1011 * Save the state of this WebView used in 1012 * {@link android.app.Activity#onSaveInstanceState}. Please note that this 1013 * method no longer stores the display data for this WebView. The previous 1014 * behavior could potentially leak files if {@link #restoreState} was never 1015 * called. See {@link #savePicture} and {@link #restorePicture} for saving 1016 * and restoring the display data. 1017 * @param outState The Bundle to store the WebView state. 1018 * @return The same copy of the back/forward list used to save the state. If 1019 * saveState fails, the returned list will be null. 1020 * @see #savePicture 1021 * @see #restorePicture 1022 */ 1023 public WebBackForwardList saveState(Bundle outState) { 1024 if (outState == null) { 1025 return null; 1026 } 1027 // We grab a copy of the back/forward list because a client of WebView 1028 // may have invalidated the history list by calling clearHistory. 1029 WebBackForwardList list = copyBackForwardList(); 1030 final int currentIndex = list.getCurrentIndex(); 1031 final int size = list.getSize(); 1032 // We should fail saving the state if the list is empty or the index is 1033 // not in a valid range. 1034 if (currentIndex < 0 || currentIndex >= size || size == 0) { 1035 return null; 1036 } 1037 outState.putInt("index", currentIndex); 1038 // FIXME: This should just be a byte[][] instead of ArrayList but 1039 // Parcel.java does not have the code to handle multi-dimensional 1040 // arrays. 1041 ArrayList<byte[]> history = new ArrayList<byte[]>(size); 1042 for (int i = 0; i < size; i++) { 1043 WebHistoryItem item = list.getItemAtIndex(i); 1044 byte[] data = item.getFlattenedData(); 1045 if (data == null) { 1046 // It would be very odd to not have any data for a given history 1047 // item. And we will fail to rebuild the history list without 1048 // flattened data. 1049 return null; 1050 } 1051 history.add(data); 1052 } 1053 outState.putSerializable("history", history); 1054 if (mCertificate != null) { 1055 outState.putBundle("certificate", 1056 SslCertificate.saveState(mCertificate)); 1057 } 1058 return list; 1059 } 1060 1061 /** 1062 * Save the current display data to the Bundle given. Used in conjunction 1063 * with {@link #saveState}. 1064 * @param b A Bundle to store the display data. 1065 * @param dest The file to store the serialized picture data. Will be 1066 * overwritten with this WebView's picture data. 1067 * @return True if the picture was successfully saved. 1068 */ 1069 public boolean savePicture(Bundle b, File dest) { 1070 if (dest == null || b == null) { 1071 return false; 1072 } 1073 final Picture p = capturePicture(); 1074 try { 1075 final FileOutputStream out = new FileOutputStream(dest); 1076 p.writeToStream(out); 1077 out.close(); 1078 } catch (FileNotFoundException e){ 1079 e.printStackTrace(); 1080 } catch (IOException e) { 1081 e.printStackTrace(); 1082 } catch (RuntimeException e) { 1083 e.printStackTrace(); 1084 } 1085 if (dest.length() > 0) { 1086 b.putInt("scrollX", mScrollX); 1087 b.putInt("scrollY", mScrollY); 1088 b.putFloat("scale", mActualScale); 1089 return true; 1090 } 1091 return false; 1092 } 1093 1094 /** 1095 * Restore the display data that was save in {@link #savePicture}. Used in 1096 * conjunction with {@link #restoreState}. 1097 * @param b A Bundle containing the saved display data. 1098 * @param src The file where the picture data was stored. 1099 * @return True if the picture was successfully restored. 1100 */ 1101 public boolean restorePicture(Bundle b, File src) { 1102 if (src == null || b == null) { 1103 return false; 1104 } 1105 if (src.exists()) { 1106 Picture p = null; 1107 try { 1108 final FileInputStream in = new FileInputStream(src); 1109 p = Picture.createFromStream(in); 1110 in.close(); 1111 } catch (FileNotFoundException e){ 1112 e.printStackTrace(); 1113 } catch (RuntimeException e) { 1114 e.printStackTrace(); 1115 } catch (IOException e) { 1116 e.printStackTrace(); 1117 } 1118 if (p != null) { 1119 int sx = b.getInt("scrollX", 0); 1120 int sy = b.getInt("scrollY", 0); 1121 float scale = b.getFloat("scale", 1.0f); 1122 mDrawHistory = true; 1123 mHistoryPicture = p; 1124 mScrollX = sx; 1125 mScrollY = sy; 1126 mHistoryWidth = Math.round(p.getWidth() * scale); 1127 mHistoryHeight = Math.round(p.getHeight() * scale); 1128 // as getWidth() / getHeight() of the view are not 1129 // available yet, set up mActualScale, so that when 1130 // onSizeChanged() is called, the rest will be set 1131 // correctly 1132 mActualScale = scale; 1133 invalidate(); 1134 return true; 1135 } 1136 } 1137 return false; 1138 } 1139 1140 /** 1141 * Restore the state of this WebView from the given map used in 1142 * {@link android.app.Activity#onRestoreInstanceState}. This method should 1143 * be called to restore the state of the WebView before using the object. If 1144 * it is called after the WebView has had a chance to build state (load 1145 * pages, create a back/forward list, etc.) there may be undesirable 1146 * side-effects. Please note that this method no longer restores the 1147 * display data for this WebView. See {@link #savePicture} and {@link 1148 * #restorePicture} for saving and restoring the display data. 1149 * @param inState The incoming Bundle of state. 1150 * @return The restored back/forward list or null if restoreState failed. 1151 * @see #savePicture 1152 * @see #restorePicture 1153 */ 1154 public WebBackForwardList restoreState(Bundle inState) { 1155 WebBackForwardList returnList = null; 1156 if (inState == null) { 1157 return returnList; 1158 } 1159 if (inState.containsKey("index") && inState.containsKey("history")) { 1160 mCertificate = SslCertificate.restoreState( 1161 inState.getBundle("certificate")); 1162 1163 final WebBackForwardList list = mCallbackProxy.getBackForwardList(); 1164 final int index = inState.getInt("index"); 1165 // We can't use a clone of the list because we need to modify the 1166 // shared copy, so synchronize instead to prevent concurrent 1167 // modifications. 1168 synchronized (list) { 1169 final List<byte[]> history = 1170 (List<byte[]>) inState.getSerializable("history"); 1171 final int size = history.size(); 1172 // Check the index bounds so we don't crash in native code while 1173 // restoring the history index. 1174 if (index < 0 || index >= size) { 1175 return null; 1176 } 1177 for (int i = 0; i < size; i++) { 1178 byte[] data = history.remove(0); 1179 if (data == null) { 1180 // If we somehow have null data, we cannot reconstruct 1181 // the item and thus our history list cannot be rebuilt. 1182 return null; 1183 } 1184 WebHistoryItem item = new WebHistoryItem(data); 1185 list.addHistoryItem(item); 1186 } 1187 // Grab the most recent copy to return to the caller. 1188 returnList = copyBackForwardList(); 1189 // Update the copy to have the correct index. 1190 returnList.setCurrentIndex(index); 1191 } 1192 // Remove all pending messages because we are restoring previous 1193 // state. 1194 mWebViewCore.removeMessages(); 1195 // Send a restore state message. 1196 mWebViewCore.sendMessage(EventHub.RESTORE_STATE, index); 1197 } 1198 return returnList; 1199 } 1200 1201 /** 1202 * Load the given url. 1203 * @param url The url of the resource to load. 1204 */ 1205 public void loadUrl(String url) { 1206 switchOutDrawHistory(); 1207 mWebViewCore.sendMessage(EventHub.LOAD_URL, url); 1208 clearTextEntry(); 1209 } 1210 1211 /** 1212 * Load the url with postData using "POST" method into the WebView. If url 1213 * is not a network url, it will be loaded with {link 1214 * {@link #loadUrl(String)} instead. 1215 * 1216 * @param url The url of the resource to load. 1217 * @param postData The data will be passed to "POST" request. 1218 * 1219 * @hide pending API solidification 1220 */ 1221 public void postUrl(String url, byte[] postData) { 1222 if (URLUtil.isNetworkUrl(url)) { 1223 switchOutDrawHistory(); 1224 WebViewCore.PostUrlData arg = new WebViewCore.PostUrlData(); 1225 arg.mUrl = url; 1226 arg.mPostData = postData; 1227 mWebViewCore.sendMessage(EventHub.POST_URL, arg); 1228 clearTextEntry(); 1229 } else { 1230 loadUrl(url); 1231 } 1232 } 1233 1234 /** 1235 * Load the given data into the WebView. This will load the data into 1236 * WebView using the data: scheme. Content loaded through this mechanism 1237 * does not have the ability to load content from the network. 1238 * @param data A String of data in the given encoding. 1239 * @param mimeType The MIMEType of the data. i.e. text/html, image/jpeg 1240 * @param encoding The encoding of the data. i.e. utf-8, base64 1241 */ 1242 public void loadData(String data, String mimeType, String encoding) { 1243 loadUrl("data:" + mimeType + ";" + encoding + "," + data); 1244 } 1245 1246 /** 1247 * Load the given data into the WebView, use the provided URL as the base 1248 * URL for the content. The base URL is the URL that represents the page 1249 * that is loaded through this interface. As such, it is used for the 1250 * history entry and to resolve any relative URLs. The failUrl is used if 1251 * browser fails to load the data provided. If it is empty or null, and the 1252 * load fails, then no history entry is created. 1253 * <p> 1254 * Note for post 1.0. Due to the change in the WebKit, the access to asset 1255 * files through "file:///android_asset/" for the sub resources is more 1256 * restricted. If you provide null or empty string as baseUrl, you won't be 1257 * able to access asset files. If the baseUrl is anything other than 1258 * http(s)/ftp(s)/about/javascript as scheme, you can access asset files for 1259 * sub resources. 1260 * 1261 * @param baseUrl Url to resolve relative paths with, if null defaults to 1262 * "about:blank" 1263 * @param data A String of data in the given encoding. 1264 * @param mimeType The MIMEType of the data. i.e. text/html. If null, 1265 * defaults to "text/html" 1266 * @param encoding The encoding of the data. i.e. utf-8, us-ascii 1267 * @param failUrl URL to use if the content fails to load or null. 1268 */ 1269 public void loadDataWithBaseURL(String baseUrl, String data, 1270 String mimeType, String encoding, String failUrl) { 1271 1272 if (baseUrl != null && baseUrl.toLowerCase().startsWith("data:")) { 1273 loadData(data, mimeType, encoding); 1274 return; 1275 } 1276 switchOutDrawHistory(); 1277 WebViewCore.BaseUrlData arg = new WebViewCore.BaseUrlData(); 1278 arg.mBaseUrl = baseUrl; 1279 arg.mData = data; 1280 arg.mMimeType = mimeType; 1281 arg.mEncoding = encoding; 1282 arg.mFailUrl = failUrl; 1283 mWebViewCore.sendMessage(EventHub.LOAD_DATA, arg); 1284 clearTextEntry(); 1285 } 1286 1287 /** 1288 * Stop the current load. 1289 */ 1290 public void stopLoading() { 1291 // TODO: should we clear all the messages in the queue before sending 1292 // STOP_LOADING? 1293 switchOutDrawHistory(); 1294 mWebViewCore.sendMessage(EventHub.STOP_LOADING); 1295 } 1296 1297 /** 1298 * Reload the current url. 1299 */ 1300 public void reload() { 1301 switchOutDrawHistory(); 1302 mWebViewCore.sendMessage(EventHub.RELOAD); 1303 } 1304 1305 /** 1306 * Return true if this WebView has a back history item. 1307 * @return True iff this WebView has a back history item. 1308 */ 1309 public boolean canGoBack() { 1310 WebBackForwardList l = mCallbackProxy.getBackForwardList(); 1311 synchronized (l) { 1312 if (l.getClearPending()) { 1313 return false; 1314 } else { 1315 return l.getCurrentIndex() > 0; 1316 } 1317 } 1318 } 1319 1320 /** 1321 * Go back in the history of this WebView. 1322 */ 1323 public void goBack() { 1324 goBackOrForward(-1); 1325 } 1326 1327 /** 1328 * Return true if this WebView has a forward history item. 1329 * @return True iff this Webview has a forward history item. 1330 */ 1331 public boolean canGoForward() { 1332 WebBackForwardList l = mCallbackProxy.getBackForwardList(); 1333 synchronized (l) { 1334 if (l.getClearPending()) { 1335 return false; 1336 } else { 1337 return l.getCurrentIndex() < l.getSize() - 1; 1338 } 1339 } 1340 } 1341 1342 /** 1343 * Go forward in the history of this WebView. 1344 */ 1345 public void goForward() { 1346 goBackOrForward(1); 1347 } 1348 1349 /** 1350 * Return true if the page can go back or forward the given 1351 * number of steps. 1352 * @param steps The negative or positive number of steps to move the 1353 * history. 1354 */ 1355 public boolean canGoBackOrForward(int steps) { 1356 WebBackForwardList l = mCallbackProxy.getBackForwardList(); 1357 synchronized (l) { 1358 if (l.getClearPending()) { 1359 return false; 1360 } else { 1361 int newIndex = l.getCurrentIndex() + steps; 1362 return newIndex >= 0 && newIndex < l.getSize(); 1363 } 1364 } 1365 } 1366 1367 /** 1368 * Go to the history item that is the number of steps away from 1369 * the current item. Steps is negative if backward and positive 1370 * if forward. 1371 * @param steps The number of steps to take back or forward in the back 1372 * forward list. 1373 */ 1374 public void goBackOrForward(int steps) { 1375 goBackOrForward(steps, false); 1376 } 1377 1378 private void goBackOrForward(int steps, boolean ignoreSnapshot) { 1379 // every time we go back or forward, we want to reset the 1380 // WebView certificate: 1381 // if the new site is secure, we will reload it and get a 1382 // new certificate set; 1383 // if the new site is not secure, the certificate must be 1384 // null, and that will be the case 1385 mCertificate = null; 1386 if (steps != 0) { 1387 clearTextEntry(); 1388 mWebViewCore.sendMessage(EventHub.GO_BACK_FORWARD, steps, 1389 ignoreSnapshot ? 1 : 0); 1390 } 1391 } 1392 1393 private boolean extendScroll(int y) { 1394 int finalY = mScroller.getFinalY(); 1395 int newY = pinLocY(finalY + y); 1396 if (newY == finalY) return false; 1397 mScroller.setFinalY(newY); 1398 mScroller.extendDuration(computeDuration(0, y)); 1399 return true; 1400 } 1401 1402 /** 1403 * Scroll the contents of the view up by half the view size 1404 * @param top true to jump to the top of the page 1405 * @return true if the page was scrolled 1406 */ 1407 public boolean pageUp(boolean top) { 1408 if (mNativeClass == 0) { 1409 return false; 1410 } 1411 nativeClearCursor(); // start next trackball movement from page edge 1412 if (top) { 1413 // go to the top of the document 1414 return pinScrollTo(mScrollX, 0, true, 0); 1415 } 1416 // Page up 1417 int h = getHeight(); 1418 int y; 1419 if (h > 2 * PAGE_SCROLL_OVERLAP) { 1420 y = -h + PAGE_SCROLL_OVERLAP; 1421 } else { 1422 y = -h / 2; 1423 } 1424 mUserScroll = true; 1425 return mScroller.isFinished() ? pinScrollBy(0, y, true, 0) 1426 : extendScroll(y); 1427 } 1428 1429 /** 1430 * Scroll the contents of the view down by half the page size 1431 * @param bottom true to jump to bottom of page 1432 * @return true if the page was scrolled 1433 */ 1434 public boolean pageDown(boolean bottom) { 1435 if (mNativeClass == 0) { 1436 return false; 1437 } 1438 nativeClearCursor(); // start next trackball movement from page edge 1439 if (bottom) { 1440 return pinScrollTo(mScrollX, mContentHeight, true, 0); 1441 } 1442 // Page down. 1443 int h = getHeight(); 1444 int y; 1445 if (h > 2 * PAGE_SCROLL_OVERLAP) { 1446 y = h - PAGE_SCROLL_OVERLAP; 1447 } else { 1448 y = h / 2; 1449 } 1450 mUserScroll = true; 1451 return mScroller.isFinished() ? pinScrollBy(0, y, true, 0) 1452 : extendScroll(y); 1453 } 1454 1455 /** 1456 * Clear the view so that onDraw() will draw nothing but white background, 1457 * and onMeasure() will return 0 if MeasureSpec is not MeasureSpec.EXACTLY 1458 */ 1459 public void clearView() { 1460 mContentWidth = 0; 1461 mContentHeight = 0; 1462 mWebViewCore.sendMessage(EventHub.CLEAR_CONTENT); 1463 } 1464 1465 /** 1466 * Return a new picture that captures the current display of the webview. 1467 * This is a copy of the display, and will be unaffected if the webview 1468 * later loads a different URL. 1469 * 1470 * @return a picture containing the current contents of the view. Note this 1471 * picture is of the entire document, and is not restricted to the 1472 * bounds of the view. 1473 */ 1474 public Picture capturePicture() { 1475 if (null == mWebViewCore) return null; // check for out of memory tab 1476 return mWebViewCore.copyContentPicture(); 1477 } 1478 1479 /** 1480 * Return true if the browser is displaying a TextView for text input. 1481 */ 1482 private boolean inEditingMode() { 1483 return mWebTextView != null && mWebTextView.getParent() != null 1484 && mWebTextView.hasFocus(); 1485 } 1486 1487 private void clearTextEntry() { 1488 if (inEditingMode()) { 1489 mWebTextView.remove(); 1490 } 1491 } 1492 1493 /** 1494 * Return the current scale of the WebView 1495 * @return The current scale. 1496 */ 1497 public float getScale() { 1498 return mActualScale; 1499 } 1500 1501 /** 1502 * Set the initial scale for the WebView. 0 means default. If 1503 * {@link WebSettings#getUseWideViewPort()} is true, it zooms out all the 1504 * way. Otherwise it starts with 100%. If initial scale is greater than 0, 1505 * WebView starts will this value as initial scale. 1506 * 1507 * @param scaleInPercent The initial scale in percent. 1508 */ 1509 public void setInitialScale(int scaleInPercent) { 1510 mInitialScale = scaleInPercent; 1511 } 1512 1513 /** 1514 * Invoke the graphical zoom picker widget for this WebView. This will 1515 * result in the zoom widget appearing on the screen to control the zoom 1516 * level of this WebView. 1517 */ 1518 public void invokeZoomPicker() { 1519 if (!getSettings().supportZoom()) { 1520 Log.w(LOGTAG, "This WebView doesn't support zoom."); 1521 return; 1522 } 1523 clearTextEntry(); 1524 if (getSettings().getBuiltInZoomControls()) { 1525 mZoomButtonsController.setVisible(true); 1526 } else { 1527 mPrivateHandler.removeCallbacks(mZoomControlRunnable); 1528 mPrivateHandler.postDelayed(mZoomControlRunnable, 1529 ZOOM_CONTROLS_TIMEOUT); 1530 } 1531 } 1532 1533 /** 1534 * Return a HitTestResult based on the current cursor node. If a HTML::a tag 1535 * is found and the anchor has a non-javascript url, the HitTestResult type 1536 * is set to SRC_ANCHOR_TYPE and the url is set in the "extra" field. If the 1537 * anchor does not have a url or if it is a javascript url, the type will 1538 * be UNKNOWN_TYPE and the url has to be retrieved through 1539 * {@link #requestFocusNodeHref} asynchronously. If a HTML::img tag is 1540 * found, the HitTestResult type is set to IMAGE_TYPE and the url is set in 1541 * the "extra" field. A type of 1542 * SRC_IMAGE_ANCHOR_TYPE indicates an anchor with a url that has an image as 1543 * a child node. If a phone number is found, the HitTestResult type is set 1544 * to PHONE_TYPE and the phone number is set in the "extra" field of 1545 * HitTestResult. If a map address is found, the HitTestResult type is set 1546 * to GEO_TYPE and the address is set in the "extra" field of HitTestResult. 1547 * If an email address is found, the HitTestResult type is set to EMAIL_TYPE 1548 * and the email is set in the "extra" field of HitTestResult. Otherwise, 1549 * HitTestResult type is set to UNKNOWN_TYPE. 1550 */ 1551 public HitTestResult getHitTestResult() { 1552 if (mNativeClass == 0) { 1553 return null; 1554 } 1555 1556 HitTestResult result = new HitTestResult(); 1557 if (nativeHasCursorNode()) { 1558 if (nativeCursorIsTextInput()) { 1559 result.setType(HitTestResult.EDIT_TEXT_TYPE); 1560 } else { 1561 String text = nativeCursorText(); 1562 if (text != null) { 1563 if (text.startsWith(SCHEME_TEL)) { 1564 result.setType(HitTestResult.PHONE_TYPE); 1565 result.setExtra(text.substring(SCHEME_TEL.length())); 1566 } else if (text.startsWith(SCHEME_MAILTO)) { 1567 result.setType(HitTestResult.EMAIL_TYPE); 1568 result.setExtra(text.substring(SCHEME_MAILTO.length())); 1569 } else if (text.startsWith(SCHEME_GEO)) { 1570 result.setType(HitTestResult.GEO_TYPE); 1571 result.setExtra(URLDecoder.decode(text 1572 .substring(SCHEME_GEO.length()))); 1573 } else if (nativeCursorIsAnchor()) { 1574 result.setType(HitTestResult.SRC_ANCHOR_TYPE); 1575 result.setExtra(text); 1576 } 1577 } 1578 } 1579 } 1580 int type = result.getType(); 1581 if (type == HitTestResult.UNKNOWN_TYPE 1582 || type == HitTestResult.SRC_ANCHOR_TYPE) { 1583 // Now check to see if it is an image. 1584 int contentX = viewToContent((int) mLastTouchX + mScrollX); 1585 int contentY = viewToContent((int) mLastTouchY + mScrollY); 1586 String text = nativeImageURI(contentX, contentY); 1587 if (text != null) { 1588 result.setType(type == HitTestResult.UNKNOWN_TYPE ? 1589 HitTestResult.IMAGE_TYPE : 1590 HitTestResult.SRC_IMAGE_ANCHOR_TYPE); 1591 result.setExtra(text); 1592 } 1593 } 1594 return result; 1595 } 1596 1597 /** 1598 * Request the href of an anchor element due to getFocusNodePath returning 1599 * "href." If hrefMsg is null, this method returns immediately and does not 1600 * dispatch hrefMsg to its target. 1601 * 1602 * @param hrefMsg This message will be dispatched with the result of the 1603 * request as the data member with "url" as key. The result can 1604 * be null. 1605 */ 1606 // FIXME: API change required to change the name of this function. We now 1607 // look at the cursor node, and not the focus node. Also, what is 1608 // getFocusNodePath? 1609 public void requestFocusNodeHref(Message hrefMsg) { 1610 if (hrefMsg == null || mNativeClass == 0) { 1611 return; 1612 } 1613 if (nativeCursorIsAnchor()) { 1614 mWebViewCore.sendMessage(EventHub.REQUEST_CURSOR_HREF, 1615 nativeCursorFramePointer(), nativeCursorNodePointer(), 1616 hrefMsg); 1617 } 1618 } 1619 1620 /** 1621 * Request the url of the image last touched by the user. msg will be sent 1622 * to its target with a String representing the url as its object. 1623 * 1624 * @param msg This message will be dispatched with the result of the request 1625 * as the data member with "url" as key. The result can be null. 1626 */ 1627 public void requestImageRef(Message msg) { 1628 int contentX = viewToContent((int) mLastTouchX + mScrollX); 1629 int contentY = viewToContent((int) mLastTouchY + mScrollY); 1630 String ref = nativeImageURI(contentX, contentY); 1631 Bundle data = msg.getData(); 1632 data.putString("url", ref); 1633 msg.setData(data); 1634 msg.sendToTarget(); 1635 } 1636 1637 private static int pinLoc(int x, int viewMax, int docMax) { 1638// Log.d(LOGTAG, "-- pinLoc " + x + " " + viewMax + " " + docMax); 1639 if (docMax < viewMax) { // the doc has room on the sides for "blank" 1640 // pin the short document to the top/left of the screen 1641 x = 0; 1642// Log.d(LOGTAG, "--- center " + x); 1643 } else if (x < 0) { 1644 x = 0; 1645// Log.d(LOGTAG, "--- zero"); 1646 } else if (x + viewMax > docMax) { 1647 x = docMax - viewMax; 1648// Log.d(LOGTAG, "--- pin " + x); 1649 } 1650 return x; 1651 } 1652 1653 // Expects x in view coordinates 1654 private int pinLocX(int x) { 1655 return pinLoc(x, getViewWidth(), computeHorizontalScrollRange()); 1656 } 1657 1658 // Expects y in view coordinates 1659 private int pinLocY(int y) { 1660 return pinLoc(y, getViewHeight(), computeVerticalScrollRange()); 1661 } 1662 1663 /*package*/ int viewToContent(int x) { 1664 return Math.round(x * mInvActualScale); 1665 } 1666 1667 private int contentToView(int x) { 1668 return Math.round(x * mActualScale); 1669 } 1670 1671 // Called by JNI to invalidate the View, given rectangle coordinates in 1672 // content space 1673 private void viewInvalidate(int l, int t, int r, int b) { 1674 invalidate(contentToView(l), contentToView(t), contentToView(r), 1675 contentToView(b)); 1676 } 1677 1678 // Called by JNI to invalidate the View after a delay, given rectangle 1679 // coordinates in content space 1680 private void viewInvalidateDelayed(long delay, int l, int t, int r, int b) { 1681 postInvalidateDelayed(delay, contentToView(l), contentToView(t), 1682 contentToView(r), contentToView(b)); 1683 } 1684 1685 private Rect contentToView(Rect x) { 1686 return new Rect(contentToView(x.left), contentToView(x.top) 1687 , contentToView(x.right), contentToView(x.bottom)); 1688 } 1689 1690 /* call from webcoreview.draw(), so we're still executing in the UI thread 1691 */ 1692 private void recordNewContentSize(int w, int h, boolean updateLayout) { 1693 1694 // premature data from webkit, ignore 1695 if ((w | h) == 0) { 1696 return; 1697 } 1698 1699 // don't abort a scroll animation if we didn't change anything 1700 if (mContentWidth != w || mContentHeight != h) { 1701 // record new dimensions 1702 mContentWidth = w; 1703 mContentHeight = h; 1704 // If history Picture is drawn, don't update scroll. They will be 1705 // updated when we get out of that mode. 1706 if (!mDrawHistory) { 1707 // repin our scroll, taking into account the new content size 1708 int oldX = mScrollX; 1709 int oldY = mScrollY; 1710 mScrollX = pinLocX(mScrollX); 1711 mScrollY = pinLocY(mScrollY); 1712 // android.util.Log.d("skia", "recordNewContentSize - 1713 // abortAnimation"); 1714 mScroller.abortAnimation(); // just in case 1715 if (oldX != mScrollX || oldY != mScrollY) { 1716 sendOurVisibleRect(); 1717 } 1718 } 1719 } 1720 contentSizeChanged(updateLayout); 1721 } 1722 1723 private void setNewZoomScale(float scale, boolean force) { 1724 if (scale < mMinZoomScale) { 1725 scale = mMinZoomScale; 1726 } else if (scale > mMaxZoomScale) { 1727 scale = mMaxZoomScale; 1728 } 1729 if (scale != mActualScale || force) { 1730 if (mDrawHistory) { 1731 // If history Picture is drawn, don't update scroll. They will 1732 // be updated when we get out of that mode. 1733 if (scale != mActualScale && !mPreviewZoomOnly) { 1734 mCallbackProxy.onScaleChanged(mActualScale, scale); 1735 } 1736 mActualScale = scale; 1737 mInvActualScale = 1 / scale; 1738 if (!mPreviewZoomOnly) { 1739 sendViewSizeZoom(); 1740 } 1741 } else { 1742 // update our scroll so we don't appear to jump 1743 // i.e. keep the center of the doc in the center of the view 1744 1745 int oldX = mScrollX; 1746 int oldY = mScrollY; 1747 float ratio = scale * mInvActualScale; // old inverse 1748 float sx = ratio * oldX + (ratio - 1) * mZoomCenterX; 1749 float sy = ratio * oldY + (ratio - 1) * mZoomCenterY; 1750 1751 // now update our new scale and inverse 1752 if (scale != mActualScale && !mPreviewZoomOnly) { 1753 mCallbackProxy.onScaleChanged(mActualScale, scale); 1754 } 1755 mActualScale = scale; 1756 mInvActualScale = 1 / scale; 1757 1758 // as we don't have animation for scaling, don't do animation 1759 // for scrolling, as it causes weird intermediate state 1760 // pinScrollTo(Math.round(sx), Math.round(sy)); 1761 mScrollX = pinLocX(Math.round(sx)); 1762 mScrollY = pinLocY(Math.round(sy)); 1763 1764 if (!mPreviewZoomOnly) { 1765 sendViewSizeZoom(); 1766 sendOurVisibleRect(); 1767 } 1768 } 1769 } 1770 } 1771 1772 // Used to avoid sending many visible rect messages. 1773 private Rect mLastVisibleRectSent; 1774 private Rect mLastGlobalRect; 1775 1776 private Rect sendOurVisibleRect() { 1777 Rect rect = new Rect(); 1778 calcOurContentVisibleRect(rect); 1779 // Rect.equals() checks for null input. 1780 if (!rect.equals(mLastVisibleRectSent)) { 1781 Point pos = new Point(rect.left, rect.top); 1782 mWebViewCore.sendMessage(EventHub.SET_SCROLL_OFFSET, 1783 nativeMoveGeneration(), 0, pos); 1784 mLastVisibleRectSent = rect; 1785 } 1786 Rect globalRect = new Rect(); 1787 if (getGlobalVisibleRect(globalRect) 1788 && !globalRect.equals(mLastGlobalRect)) { 1789 if (DebugFlags.WEB_VIEW) { 1790 Log.v(LOGTAG, "sendOurVisibleRect=(" + globalRect.left + "," 1791 + globalRect.top + ",r=" + globalRect.right + ",b=" 1792 + globalRect.bottom); 1793 } 1794 // TODO: the global offset is only used by windowRect() 1795 // in ChromeClientAndroid ; other clients such as touch 1796 // and mouse events could return view + screen relative points. 1797 mWebViewCore.sendMessage(EventHub.SET_GLOBAL_BOUNDS, globalRect); 1798 mLastGlobalRect = globalRect; 1799 } 1800 return rect; 1801 } 1802 1803 // Sets r to be the visible rectangle of our webview in view coordinates 1804 private void calcOurVisibleRect(Rect r) { 1805 Point p = new Point(); 1806 getGlobalVisibleRect(r, p); 1807 r.offset(-p.x, -p.y); 1808 if (mFindIsUp) { 1809 r.bottom -= FIND_HEIGHT; 1810 } 1811 } 1812 1813 // Sets r to be our visible rectangle in content coordinates 1814 private void calcOurContentVisibleRect(Rect r) { 1815 calcOurVisibleRect(r); 1816 r.left = viewToContent(r.left); 1817 r.top = viewToContent(r.top); 1818 r.right = viewToContent(r.right); 1819 r.bottom = viewToContent(r.bottom); 1820 } 1821 1822 /** 1823 * Compute unzoomed width and height, and if they differ from the last 1824 * values we sent, send them to webkit (to be used has new viewport) 1825 * 1826 * @return true if new values were sent 1827 */ 1828 private boolean sendViewSizeZoom() { 1829 int newWidth = Math.round(getViewWidth() * mInvActualScale); 1830 int newHeight = Math.round(getViewHeight() * mInvActualScale); 1831 /* 1832 * Because the native side may have already done a layout before the 1833 * View system was able to measure us, we have to send a height of 0 to 1834 * remove excess whitespace when we grow our width. This will trigger a 1835 * layout and a change in content size. This content size change will 1836 * mean that contentSizeChanged will either call this method directly or 1837 * indirectly from onSizeChanged. 1838 */ 1839 if (newWidth > mLastWidthSent && mWrapContent) { 1840 newHeight = 0; 1841 } 1842 // Avoid sending another message if the dimensions have not changed. 1843 if (newWidth != mLastWidthSent || newHeight != mLastHeightSent) { 1844 mWebViewCore.sendMessage(EventHub.VIEW_SIZE_CHANGED, 1845 newWidth, newHeight, new Float(mActualScale)); 1846 mLastWidthSent = newWidth; 1847 mLastHeightSent = newHeight; 1848 return true; 1849 } 1850 return false; 1851 } 1852 1853 @Override 1854 protected int computeHorizontalScrollRange() { 1855 if (mDrawHistory) { 1856 return mHistoryWidth; 1857 } else { 1858 return contentToView(mContentWidth); 1859 } 1860 } 1861 1862 // Make sure this stays in sync with the actual height of the FindDialog. 1863 private static final int FIND_HEIGHT = 79; 1864 1865 @Override 1866 protected int computeVerticalScrollRange() { 1867 if (mDrawHistory) { 1868 return mHistoryHeight; 1869 } else { 1870 int height = contentToView(mContentHeight); 1871 if (mFindIsUp) { 1872 height += FIND_HEIGHT; 1873 } 1874 return height; 1875 } 1876 } 1877 1878 /** 1879 * Get the url for the current page. This is not always the same as the url 1880 * passed to WebViewClient.onPageStarted because although the load for 1881 * that url has begun, the current page may not have changed. 1882 * @return The url for the current page. 1883 */ 1884 public String getUrl() { 1885 WebHistoryItem h = mCallbackProxy.getBackForwardList().getCurrentItem(); 1886 return h != null ? h.getUrl() : null; 1887 } 1888 1889 /** 1890 * Get the original url for the current page. This is not always the same 1891 * as the url passed to WebViewClient.onPageStarted because although the 1892 * load for that url has begun, the current page may not have changed. 1893 * Also, there may have been redirects resulting in a different url to that 1894 * originally requested. 1895 * @return The url that was originally requested for the current page. 1896 */ 1897 public String getOriginalUrl() { 1898 WebHistoryItem h = mCallbackProxy.getBackForwardList().getCurrentItem(); 1899 return h != null ? h.getOriginalUrl() : null; 1900 } 1901 1902 /** 1903 * Get the title for the current page. This is the title of the current page 1904 * until WebViewClient.onReceivedTitle is called. 1905 * @return The title for the current page. 1906 */ 1907 public String getTitle() { 1908 WebHistoryItem h = mCallbackProxy.getBackForwardList().getCurrentItem(); 1909 return h != null ? h.getTitle() : null; 1910 } 1911 1912 /** 1913 * Get the favicon for the current page. This is the favicon of the current 1914 * page until WebViewClient.onReceivedIcon is called. 1915 * @return The favicon for the current page. 1916 */ 1917 public Bitmap getFavicon() { 1918 WebHistoryItem h = mCallbackProxy.getBackForwardList().getCurrentItem(); 1919 return h != null ? h.getFavicon() : null; 1920 } 1921 1922 /** 1923 * Get the progress for the current page. 1924 * @return The progress for the current page between 0 and 100. 1925 */ 1926 public int getProgress() { 1927 return mCallbackProxy.getProgress(); 1928 } 1929 1930 /** 1931 * @return the height of the HTML content. 1932 */ 1933 public int getContentHeight() { 1934 return mContentHeight; 1935 } 1936 1937 /** 1938 * Pause all layout, parsing, and javascript timers for all webviews. This 1939 * is a global requests, not restricted to just this webview. This can be 1940 * useful if the application has been paused. 1941 */ 1942 public void pauseTimers() { 1943 mWebViewCore.sendMessage(EventHub.PAUSE_TIMERS); 1944 } 1945 1946 /** 1947 * Resume all layout, parsing, and javascript timers for all webviews. 1948 * This will resume dispatching all timers. 1949 */ 1950 public void resumeTimers() { 1951 mWebViewCore.sendMessage(EventHub.RESUME_TIMERS); 1952 } 1953 1954 /** 1955 * Call this to pause any extra processing associated with this view and 1956 * its associated DOM/plugins/javascript/etc. For example, if the view is 1957 * taken offscreen, this could be called to reduce unnecessary CPU and/or 1958 * network traffic. When the view is again "active", call onResume(). 1959 * 1960 * Note that this differs from pauseTimers(), which affects all views/DOMs 1961 * @hide 1962 */ 1963 public void onPause() { 1964 if (!mIsPaused) { 1965 mIsPaused = true; 1966 mWebViewCore.sendMessage(EventHub.ON_PAUSE); 1967 } 1968 } 1969 1970 /** 1971 * Call this to balanace a previous call to onPause() 1972 * @hide 1973 */ 1974 public void onResume() { 1975 if (mIsPaused) { 1976 mIsPaused = false; 1977 mWebViewCore.sendMessage(EventHub.ON_RESUME); 1978 } 1979 } 1980 1981 /** 1982 * Returns true if the view is paused, meaning onPause() was called. Calling 1983 * onResume() sets the paused state back to false. 1984 * @hide 1985 */ 1986 public boolean isPaused() { 1987 return mIsPaused; 1988 } 1989 1990 /** 1991 * Call this to inform the view that memory is low so that it can 1992 * free any available memory. 1993 * @hide 1994 */ 1995 public void freeMemory() { 1996 mWebViewCore.sendMessage(EventHub.FREE_MEMORY); 1997 } 1998 1999 /** 2000 * Clear the resource cache. Note that the cache is per-application, so 2001 * this will clear the cache for all WebViews used. 2002 * 2003 * @param includeDiskFiles If false, only the RAM cache is cleared. 2004 */ 2005 public void clearCache(boolean includeDiskFiles) { 2006 // Note: this really needs to be a static method as it clears cache for all 2007 // WebView. But we need mWebViewCore to send message to WebCore thread, so 2008 // we can't make this static. 2009 mWebViewCore.sendMessage(EventHub.CLEAR_CACHE, 2010 includeDiskFiles ? 1 : 0, 0); 2011 } 2012 2013 /** 2014 * Make sure that clearing the form data removes the adapter from the 2015 * currently focused textfield if there is one. 2016 */ 2017 public void clearFormData() { 2018 if (inEditingMode()) { 2019 AutoCompleteAdapter adapter = null; 2020 mWebTextView.setAdapterCustom(adapter); 2021 } 2022 } 2023 2024 /** 2025 * Tell the WebView to clear its internal back/forward list. 2026 */ 2027 public void clearHistory() { 2028 mCallbackProxy.getBackForwardList().setClearPending(); 2029 mWebViewCore.sendMessage(EventHub.CLEAR_HISTORY); 2030 } 2031 2032 /** 2033 * Clear the SSL preferences table stored in response to proceeding with SSL 2034 * certificate errors. 2035 */ 2036 public void clearSslPreferences() { 2037 mWebViewCore.sendMessage(EventHub.CLEAR_SSL_PREF_TABLE); 2038 } 2039 2040 /** 2041 * Return the WebBackForwardList for this WebView. This contains the 2042 * back/forward list for use in querying each item in the history stack. 2043 * This is a copy of the private WebBackForwardList so it contains only a 2044 * snapshot of the current state. Multiple calls to this method may return 2045 * different objects. The object returned from this method will not be 2046 * updated to reflect any new state. 2047 */ 2048 public WebBackForwardList copyBackForwardList() { 2049 return mCallbackProxy.getBackForwardList().clone(); 2050 } 2051 2052 /* 2053 * Highlight and scroll to the next occurance of String in findAll. 2054 * Wraps the page infinitely, and scrolls. Must be called after 2055 * calling findAll. 2056 * 2057 * @param forward Direction to search. 2058 */ 2059 public void findNext(boolean forward) { 2060 nativeFindNext(forward); 2061 } 2062 2063 /* 2064 * Find all instances of find on the page and highlight them. 2065 * @param find String to find. 2066 * @return int The number of occurances of the String "find" 2067 * that were found. 2068 */ 2069 public int findAll(String find) { 2070 mFindIsUp = true; 2071 int result = nativeFindAll(find.toLowerCase(), find.toUpperCase()); 2072 invalidate(); 2073 return result; 2074 } 2075 2076 // Used to know whether the find dialog is open. Affects whether 2077 // or not we draw the highlights for matches. 2078 private boolean mFindIsUp; 2079 2080 /** 2081 * Return the first substring consisting of the address of a physical 2082 * location. Currently, only addresses in the United States are detected, 2083 * and consist of: 2084 * - a house number 2085 * - a street name 2086 * - a street type (Road, Circle, etc), either spelled out or abbreviated 2087 * - a city name 2088 * - a state or territory, either spelled out or two-letter abbr. 2089 * - an optional 5 digit or 9 digit zip code. 2090 * 2091 * All names must be correctly capitalized, and the zip code, if present, 2092 * must be valid for the state. The street type must be a standard USPS 2093 * spelling or abbreviation. The state or territory must also be spelled 2094 * or abbreviated using USPS standards. The house number may not exceed 2095 * five digits. 2096 * @param addr The string to search for addresses. 2097 * 2098 * @return the address, or if no address is found, return null. 2099 */ 2100 public static String findAddress(String addr) { 2101 return findAddress(addr, false); 2102 } 2103 2104 /** 2105 * @hide 2106 * Return the first substring consisting of the address of a physical 2107 * location. Currently, only addresses in the United States are detected, 2108 * and consist of: 2109 * - a house number 2110 * - a street name 2111 * - a street type (Road, Circle, etc), either spelled out or abbreviated 2112 * - a city name 2113 * - a state or territory, either spelled out or two-letter abbr. 2114 * - an optional 5 digit or 9 digit zip code. 2115 * 2116 * Names are optionally capitalized, and the zip code, if present, 2117 * must be valid for the state. The street type must be a standard USPS 2118 * spelling or abbreviation. The state or territory must also be spelled 2119 * or abbreviated using USPS standards. The house number may not exceed 2120 * five digits. 2121 * @param addr The string to search for addresses. 2122 * @param caseInsensitive addr Set to true to make search ignore case. 2123 * 2124 * @return the address, or if no address is found, return null. 2125 */ 2126 public static String findAddress(String addr, boolean caseInsensitive) { 2127 return WebViewCore.nativeFindAddress(addr, caseInsensitive); 2128 } 2129 2130 /* 2131 * Clear the highlighting surrounding text matches created by findAll. 2132 */ 2133 public void clearMatches() { 2134 mFindIsUp = false; 2135 nativeSetFindIsDown(); 2136 // Now that the dialog has been removed, ensure that we scroll to a 2137 // location that is not beyond the end of the page. 2138 pinScrollTo(mScrollX, mScrollY, false, 0); 2139 invalidate(); 2140 } 2141 2142 /** 2143 * Query the document to see if it contains any image references. The 2144 * message object will be dispatched with arg1 being set to 1 if images 2145 * were found and 0 if the document does not reference any images. 2146 * @param response The message that will be dispatched with the result. 2147 */ 2148 public void documentHasImages(Message response) { 2149 if (response == null) { 2150 return; 2151 } 2152 mWebViewCore.sendMessage(EventHub.DOC_HAS_IMAGES, response); 2153 } 2154 2155 @Override 2156 public void computeScroll() { 2157 if (mScroller.computeScrollOffset()) { 2158 int oldX = mScrollX; 2159 int oldY = mScrollY; 2160 mScrollX = mScroller.getCurrX(); 2161 mScrollY = mScroller.getCurrY(); 2162 postInvalidate(); // So we draw again 2163 if (oldX != mScrollX || oldY != mScrollY) { 2164 // as onScrollChanged() is not called, sendOurVisibleRect() 2165 // needs to be call explicitly 2166 sendOurVisibleRect(); 2167 } 2168 } else { 2169 super.computeScroll(); 2170 } 2171 } 2172 2173 private static int computeDuration(int dx, int dy) { 2174 int distance = Math.max(Math.abs(dx), Math.abs(dy)); 2175 int duration = distance * 1000 / STD_SPEED; 2176 return Math.min(duration, MAX_DURATION); 2177 } 2178 2179 // helper to pin the scrollBy parameters (already in view coordinates) 2180 // returns true if the scroll was changed 2181 private boolean pinScrollBy(int dx, int dy, boolean animate, int animationDuration) { 2182 return pinScrollTo(mScrollX + dx, mScrollY + dy, animate, animationDuration); 2183 } 2184 2185 // helper to pin the scrollTo parameters (already in view coordinates) 2186 // returns true if the scroll was changed 2187 private boolean pinScrollTo(int x, int y, boolean animate, int animationDuration) { 2188 x = pinLocX(x); 2189 y = pinLocY(y); 2190 int dx = x - mScrollX; 2191 int dy = y - mScrollY; 2192 2193 if ((dx | dy) == 0) { 2194 return false; 2195 } 2196 2197 if (true && animate) { 2198 // Log.d(LOGTAG, "startScroll: " + dx + " " + dy); 2199 2200 mScroller.startScroll(mScrollX, mScrollY, dx, dy, 2201 animationDuration > 0 ? animationDuration : computeDuration(dx, dy)); 2202 invalidate(); 2203 } else { 2204 mScroller.abortAnimation(); // just in case 2205 scrollTo(x, y); 2206 } 2207 return true; 2208 } 2209 2210 // Scale from content to view coordinates, and pin. 2211 // Also called by jni webview.cpp 2212 private void setContentScrollBy(int cx, int cy, boolean animate) { 2213 if (mDrawHistory) { 2214 // disallow WebView to change the scroll position as History Picture 2215 // is used in the view system. 2216 // TODO: as we switchOutDrawHistory when trackball or navigation 2217 // keys are hit, this should be safe. Right? 2218 return; 2219 } 2220 cx = contentToView(cx); 2221 cy = contentToView(cy); 2222 if (mHeightCanMeasure) { 2223 // move our visible rect according to scroll request 2224 if (cy != 0) { 2225 Rect tempRect = new Rect(); 2226 calcOurVisibleRect(tempRect); 2227 tempRect.offset(cx, cy); 2228 requestRectangleOnScreen(tempRect); 2229 } 2230 // FIXME: We scroll horizontally no matter what because currently 2231 // ScrollView and ListView will not scroll horizontally. 2232 // FIXME: Why do we only scroll horizontally if there is no 2233 // vertical scroll? 2234// Log.d(LOGTAG, "setContentScrollBy cy=" + cy); 2235 if (cy == 0 && cx != 0) { 2236 pinScrollBy(cx, 0, animate, 0); 2237 } 2238 } else { 2239 pinScrollBy(cx, cy, animate, 0); 2240 } 2241 } 2242 2243 // scale from content to view coordinates, and pin 2244 // return true if pin caused the final x/y different than the request cx/cy; 2245 // return false if the view scroll to the exact position as it is requested. 2246 private boolean setContentScrollTo(int cx, int cy) { 2247 if (mDrawHistory) { 2248 // disallow WebView to change the scroll position as History Picture 2249 // is used in the view system. 2250 // One known case where this is called is that WebCore tries to 2251 // restore the scroll position. As history Picture already uses the 2252 // saved scroll position, it is ok to skip this. 2253 return false; 2254 } 2255 int vx = contentToView(cx); 2256 int vy = contentToView(cy); 2257// Log.d(LOGTAG, "content scrollTo [" + cx + " " + cy + "] view=[" + 2258// vx + " " + vy + "]"); 2259 pinScrollTo(vx, vy, false, 0); 2260 if (mScrollX != vx || mScrollY != vy) { 2261 return true; 2262 } else { 2263 return false; 2264 } 2265 } 2266 2267 // scale from content to view coordinates, and pin 2268 private void spawnContentScrollTo(int cx, int cy) { 2269 if (mDrawHistory) { 2270 // disallow WebView to change the scroll position as History Picture 2271 // is used in the view system. 2272 return; 2273 } 2274 int vx = contentToView(cx); 2275 int vy = contentToView(cy); 2276 pinScrollTo(vx, vy, true, 0); 2277 } 2278 2279 /** 2280 * These are from webkit, and are in content coordinate system (unzoomed) 2281 */ 2282 private void contentSizeChanged(boolean updateLayout) { 2283 // suppress 0,0 since we usually see real dimensions soon after 2284 // this avoids drawing the prev content in a funny place. If we find a 2285 // way to consolidate these notifications, this check may become 2286 // obsolete 2287 if ((mContentWidth | mContentHeight) == 0) { 2288 return; 2289 } 2290 2291 if (mHeightCanMeasure) { 2292 if (getMeasuredHeight() != contentToView(mContentHeight) 2293 && updateLayout) { 2294 requestLayout(); 2295 } 2296 } else if (mWidthCanMeasure) { 2297 if (getMeasuredWidth() != contentToView(mContentWidth) 2298 && updateLayout) { 2299 requestLayout(); 2300 } 2301 } else { 2302 // If we don't request a layout, try to send our view size to the 2303 // native side to ensure that WebCore has the correct dimensions. 2304 sendViewSizeZoom(); 2305 } 2306 } 2307 2308 /** 2309 * Set the WebViewClient that will receive various notifications and 2310 * requests. This will replace the current handler. 2311 * @param client An implementation of WebViewClient. 2312 */ 2313 public void setWebViewClient(WebViewClient client) { 2314 mCallbackProxy.setWebViewClient(client); 2315 } 2316 2317 /** 2318 * Register the interface to be used when content can not be handled by 2319 * the rendering engine, and should be downloaded instead. This will replace 2320 * the current handler. 2321 * @param listener An implementation of DownloadListener. 2322 */ 2323 public void setDownloadListener(DownloadListener listener) { 2324 mCallbackProxy.setDownloadListener(listener); 2325 } 2326 2327 /** 2328 * Set the chrome handler. This is an implementation of WebChromeClient for 2329 * use in handling Javascript dialogs, favicons, titles, and the progress. 2330 * This will replace the current handler. 2331 * @param client An implementation of WebChromeClient. 2332 */ 2333 public void setWebChromeClient(WebChromeClient client) { 2334 mCallbackProxy.setWebChromeClient(client); 2335 } 2336 2337 /** 2338 * Set the Picture listener. This is an interface used to receive 2339 * notifications of a new Picture. 2340 * @param listener An implementation of WebView.PictureListener. 2341 */ 2342 public void setPictureListener(PictureListener listener) { 2343 mPictureListener = listener; 2344 } 2345 2346 /** 2347 * {@hide} 2348 */ 2349 /* FIXME: Debug only! Remove for SDK! */ 2350 public void externalRepresentation(Message callback) { 2351 mWebViewCore.sendMessage(EventHub.REQUEST_EXT_REPRESENTATION, callback); 2352 } 2353 2354 /** 2355 * {@hide} 2356 */ 2357 /* FIXME: Debug only! Remove for SDK! */ 2358 public void documentAsText(Message callback) { 2359 mWebViewCore.sendMessage(EventHub.REQUEST_DOC_AS_TEXT, callback); 2360 } 2361 2362 /** 2363 * Use this function to bind an object to Javascript so that the 2364 * methods can be accessed from Javascript. 2365 * <p><strong>IMPORTANT:</strong> 2366 * <ul> 2367 * <li> Using addJavascriptInterface() allows JavaScript to control your 2368 * application. This can be a very useful feature or a dangerous security 2369 * issue. When the HTML in the WebView is untrustworthy (for example, part 2370 * or all of the HTML is provided by some person or process), then an 2371 * attacker could inject HTML that will execute your code and possibly any 2372 * code of the attacker's choosing.<br> 2373 * Do not use addJavascriptInterface() unless all of the HTML in this 2374 * WebView was written by you.</li> 2375 * <li> The Java object that is bound runs in another thread and not in 2376 * the thread that it was constructed in.</li> 2377 * </ul></p> 2378 * @param obj The class instance to bind to Javascript 2379 * @param interfaceName The name to used to expose the class in Javascript 2380 */ 2381 public void addJavascriptInterface(Object obj, String interfaceName) { 2382 WebViewCore.JSInterfaceData arg = new WebViewCore.JSInterfaceData(); 2383 arg.mObject = obj; 2384 arg.mInterfaceName = interfaceName; 2385 mWebViewCore.sendMessage(EventHub.ADD_JS_INTERFACE, arg); 2386 } 2387 2388 /** 2389 * Return the WebSettings object used to control the settings for this 2390 * WebView. 2391 * @return A WebSettings object that can be used to control this WebView's 2392 * settings. 2393 */ 2394 public WebSettings getSettings() { 2395 return mWebViewCore.getSettings(); 2396 } 2397 2398 /** 2399 * Return the list of currently loaded plugins. 2400 * @return The list of currently loaded plugins. 2401 */ 2402 public static synchronized PluginList getPluginList() { 2403 if (sPluginList == null) { 2404 sPluginList = new PluginList(); 2405 } 2406 return sPluginList; 2407 } 2408 2409 /** 2410 * TODO: need to add @Deprecated 2411 */ 2412 public void refreshPlugins(boolean reloadOpenPages) { 2413 PluginManager.getInstance(mContext).refreshPlugins(reloadOpenPages); 2414 } 2415 2416 //------------------------------------------------------------------------- 2417 // Override View methods 2418 //------------------------------------------------------------------------- 2419 2420 @Override 2421 protected void finalize() throws Throwable { 2422 destroy(); 2423 } 2424 2425 @Override 2426 protected void onDraw(Canvas canvas) { 2427 // if mNativeClass is 0, the WebView has been destroyed. Do nothing. 2428 if (mNativeClass == 0) { 2429 return; 2430 } 2431 if (mWebViewCore.mEndScaleZoom) { 2432 mWebViewCore.mEndScaleZoom = false; 2433 if (mTouchMode >= FIRST_SCROLL_ZOOM 2434 && mTouchMode <= LAST_SCROLL_ZOOM) { 2435 setHorizontalScrollBarEnabled(true); 2436 setVerticalScrollBarEnabled(true); 2437 mTouchMode = TOUCH_DONE_MODE; 2438 } 2439 } 2440 int sc = canvas.save(); 2441 if (mTouchMode >= FIRST_SCROLL_ZOOM && mTouchMode <= LAST_SCROLL_ZOOM) { 2442 scrollZoomDraw(canvas); 2443 } else { 2444 // Update the buttons in the picture, so when we draw the picture 2445 // to the screen, they are in the correct state. 2446 // Tell the native side if user is a) touching the screen, 2447 // b) pressing the trackball down, or c) pressing the enter key 2448 // If the cursor is on a button, we need to draw it in the pressed 2449 // state. 2450 // If mNativeClass is 0, we should not reach here, so we do not 2451 // need to check it again. 2452 nativeRecordButtons(hasFocus() && hasWindowFocus(), 2453 mTouchMode == TOUCH_SHORTPRESS_START_MODE 2454 || mTrackballDown || mGotCenterDown, false); 2455 drawCoreAndCursorRing(canvas, mBackgroundColor, mDrawCursorRing); 2456 } 2457 canvas.restoreToCount(sc); 2458 2459 if (AUTO_REDRAW_HACK && mAutoRedraw) { 2460 invalidate(); 2461 } 2462 } 2463 2464 @Override 2465 public void setLayoutParams(ViewGroup.LayoutParams params) { 2466 if (params.height == LayoutParams.WRAP_CONTENT) { 2467 mWrapContent = true; 2468 } 2469 super.setLayoutParams(params); 2470 } 2471 2472 @Override 2473 public boolean performLongClick() { 2474 if (inEditingMode()) { 2475 return mWebTextView.performLongClick(); 2476 } else { 2477 return super.performLongClick(); 2478 } 2479 } 2480 2481 private void drawCoreAndCursorRing(Canvas canvas, int color, 2482 boolean drawCursorRing) { 2483 if (mDrawHistory) { 2484 canvas.scale(mActualScale, mActualScale); 2485 canvas.drawPicture(mHistoryPicture); 2486 return; 2487 } 2488 2489 boolean animateZoom = mZoomScale != 0; 2490 boolean animateScroll = !mScroller.isFinished() 2491 || mVelocityTracker != null; 2492 if (animateZoom) { 2493 float zoomScale; 2494 int interval = (int) (SystemClock.uptimeMillis() - mZoomStart); 2495 if (interval < ZOOM_ANIMATION_LENGTH) { 2496 float ratio = (float) interval / ZOOM_ANIMATION_LENGTH; 2497 zoomScale = 1.0f / (mInvInitialZoomScale 2498 + (mInvFinalZoomScale - mInvInitialZoomScale) * ratio); 2499 invalidate(); 2500 } else { 2501 zoomScale = mZoomScale; 2502 // set mZoomScale to be 0 as we have done animation 2503 mZoomScale = 0; 2504 } 2505 float scale = (mActualScale - zoomScale) * mInvActualScale; 2506 float tx = scale * (mZoomCenterX + mScrollX); 2507 float ty = scale * (mZoomCenterY + mScrollY); 2508 2509 // this block pins the translate to "legal" bounds. This makes the 2510 // animation a bit non-obvious, but it means we won't pop when the 2511 // "real" zoom takes effect 2512 if (true) { 2513 // canvas.translate(mScrollX, mScrollY); 2514 tx -= mScrollX; 2515 ty -= mScrollY; 2516 tx = -pinLoc(-Math.round(tx), getViewWidth(), Math 2517 .round(mContentWidth * zoomScale)); 2518 ty = -pinLoc(-Math.round(ty), getViewHeight(), Math 2519 .round(mContentHeight * zoomScale)); 2520 tx += mScrollX; 2521 ty += mScrollY; 2522 } 2523 canvas.translate(tx, ty); 2524 canvas.scale(zoomScale, zoomScale); 2525 } else { 2526 canvas.scale(mActualScale, mActualScale); 2527 } 2528 2529 mWebViewCore.drawContentPicture(canvas, color, animateZoom, 2530 animateScroll); 2531 2532 if (mNativeClass == 0) return; 2533 if (mShiftIsPressed) { 2534 if (mTouchSelection) { 2535 nativeDrawSelectionRegion(canvas); 2536 } else { 2537 nativeDrawSelection(canvas, mSelectX, mSelectY, 2538 mExtendSelection); 2539 } 2540 } else if (drawCursorRing) { 2541 if (mTouchMode == TOUCH_SHORTPRESS_START_MODE) { 2542 mTouchMode = TOUCH_SHORTPRESS_MODE; 2543 HitTestResult hitTest = getHitTestResult(); 2544 if (hitTest != null && 2545 hitTest.mType != HitTestResult.UNKNOWN_TYPE) { 2546 mPrivateHandler.sendMessageDelayed(mPrivateHandler 2547 .obtainMessage(SWITCH_TO_LONGPRESS), 2548 LONG_PRESS_TIMEOUT); 2549 } 2550 } 2551 nativeDrawCursorRing(canvas); 2552 } 2553 // When the FindDialog is up, only draw the matches if we are not in 2554 // the process of scrolling them into view. 2555 if (mFindIsUp && !animateScroll) { 2556 nativeDrawMatches(canvas); 2557 } 2558 } 2559 2560 private float scrollZoomGridScale(float invScale) { 2561 float griddedInvScale = (int) (invScale * SCROLL_ZOOM_GRID) 2562 / (float) SCROLL_ZOOM_GRID; 2563 return 1.0f / griddedInvScale; 2564 } 2565 2566 private float scrollZoomX(float scale) { 2567 int width = getViewWidth(); 2568 float maxScrollZoomX = mContentWidth * scale - width; 2569 int maxX = mContentWidth - width; 2570 return -(maxScrollZoomX > 0 ? mZoomScrollX * maxScrollZoomX / maxX 2571 : maxScrollZoomX / 2); 2572 } 2573 2574 private float scrollZoomY(float scale) { 2575 int height = getViewHeight(); 2576 float maxScrollZoomY = mContentHeight * scale - height; 2577 int maxY = mContentHeight - height; 2578 return -(maxScrollZoomY > 0 ? mZoomScrollY * maxScrollZoomY / maxY 2579 : maxScrollZoomY / 2); 2580 } 2581 2582 private void drawMagnifyFrame(Canvas canvas, Rect frame, Paint paint) { 2583 final float ADORNMENT_LEN = 16.0f; 2584 float width = frame.width(); 2585 float height = frame.height(); 2586 Path path = new Path(); 2587 path.moveTo(-ADORNMENT_LEN, -ADORNMENT_LEN); 2588 path.lineTo(0, 0); 2589 path.lineTo(width, 0); 2590 path.lineTo(width + ADORNMENT_LEN, -ADORNMENT_LEN); 2591 path.moveTo(-ADORNMENT_LEN, height + ADORNMENT_LEN); 2592 path.lineTo(0, height); 2593 path.lineTo(width, height); 2594 path.lineTo(width + ADORNMENT_LEN, height + ADORNMENT_LEN); 2595 path.moveTo(0, 0); 2596 path.lineTo(0, height); 2597 path.moveTo(width, 0); 2598 path.lineTo(width, height); 2599 path.offset(frame.left, frame.top); 2600 canvas.drawPath(path, paint); 2601 } 2602 2603 // Returns frame surrounding magified portion of screen while 2604 // scroll-zoom is enabled. The frame is also used to center the 2605 // zoom-in zoom-out points at the start and end of the animation. 2606 private Rect scrollZoomFrame(int width, int height, float halfScale) { 2607 Rect scrollFrame = new Rect(); 2608 scrollFrame.set(mZoomScrollX, mZoomScrollY, 2609 mZoomScrollX + width, mZoomScrollY + height); 2610 if (mContentWidth * mZoomScrollLimit < width) { 2611 float scale = zoomFrameScaleX(width, halfScale, 1.0f); 2612 float offsetX = (width * scale - width) * 0.5f; 2613 scrollFrame.left -= offsetX; 2614 scrollFrame.right += offsetX; 2615 } 2616 if (mContentHeight * mZoomScrollLimit < height) { 2617 float scale = zoomFrameScaleY(height, halfScale, 1.0f); 2618 float offsetY = (height * scale - height) * 0.5f; 2619 scrollFrame.top -= offsetY; 2620 scrollFrame.bottom += offsetY; 2621 } 2622 return scrollFrame; 2623 } 2624 2625 private float zoomFrameScaleX(int width, float halfScale, float noScale) { 2626 // mContentWidth > width > mContentWidth * mZoomScrollLimit 2627 if (mContentWidth <= width) { 2628 return halfScale; 2629 } 2630 float part = (width - mContentWidth * mZoomScrollLimit) 2631 / (width * (1 - mZoomScrollLimit)); 2632 return halfScale * part + noScale * (1.0f - part); 2633 } 2634 2635 private float zoomFrameScaleY(int height, float halfScale, float noScale) { 2636 if (mContentHeight <= height) { 2637 return halfScale; 2638 } 2639 float part = (height - mContentHeight * mZoomScrollLimit) 2640 / (height * (1 - mZoomScrollLimit)); 2641 return halfScale * part + noScale * (1.0f - part); 2642 } 2643 2644 private float scrollZoomMagScale(float invScale) { 2645 return (invScale * 2 + mInvActualScale) / 3; 2646 } 2647 2648 private void scrollZoomDraw(Canvas canvas) { 2649 float invScale = mZoomScrollInvLimit; 2650 int elapsed = 0; 2651 if (mTouchMode != SCROLL_ZOOM_OUT) { 2652 elapsed = (int) Math.min(System.currentTimeMillis() 2653 - mZoomScrollStart, SCROLL_ZOOM_DURATION); 2654 float transitionScale = (mZoomScrollInvLimit - mInvActualScale) 2655 * elapsed / SCROLL_ZOOM_DURATION; 2656 if (mTouchMode == SCROLL_ZOOM_ANIMATION_OUT) { 2657 invScale = mInvActualScale + transitionScale; 2658 } else { /* if (mTouchMode == SCROLL_ZOOM_ANIMATION_IN) */ 2659 invScale = mZoomScrollInvLimit - transitionScale; 2660 } 2661 } 2662 float scale = scrollZoomGridScale(invScale); 2663 invScale = 1.0f / scale; 2664 int width = getViewWidth(); 2665 int height = getViewHeight(); 2666 float halfScale = scrollZoomMagScale(invScale); 2667 Rect scrollFrame = scrollZoomFrame(width, height, halfScale); 2668 if (elapsed == SCROLL_ZOOM_DURATION) { 2669 if (mTouchMode == SCROLL_ZOOM_ANIMATION_IN) { 2670 setHorizontalScrollBarEnabled(true); 2671 setVerticalScrollBarEnabled(true); 2672 rebuildWebTextView(); 2673 scrollTo((int) (scrollFrame.centerX() * mActualScale) 2674 - (width >> 1), (int) (scrollFrame.centerY() 2675 * mActualScale) - (height >> 1)); 2676 mTouchMode = TOUCH_DONE_MODE; 2677 } else { 2678 mTouchMode = SCROLL_ZOOM_OUT; 2679 } 2680 } 2681 float newX = scrollZoomX(scale); 2682 float newY = scrollZoomY(scale); 2683 if (DebugFlags.WEB_VIEW) { 2684 Log.v(LOGTAG, "scrollZoomDraw scale=" + scale + " + (" + newX 2685 + ", " + newY + ") mZoomScroll=(" + mZoomScrollX + ", " 2686 + mZoomScrollY + ")" + " invScale=" + invScale + " scale=" 2687 + scale); 2688 } 2689 canvas.translate(newX, newY); 2690 canvas.scale(scale, scale); 2691 boolean animating = mTouchMode != SCROLL_ZOOM_OUT; 2692 if (mDrawHistory) { 2693 int sc = canvas.save(Canvas.CLIP_SAVE_FLAG); 2694 Rect clip = new Rect(0, 0, mHistoryPicture.getWidth(), 2695 mHistoryPicture.getHeight()); 2696 canvas.clipRect(clip, Region.Op.DIFFERENCE); 2697 canvas.drawColor(mBackgroundColor); 2698 canvas.restoreToCount(sc); 2699 canvas.drawPicture(mHistoryPicture); 2700 } else { 2701 mWebViewCore.drawContentPicture(canvas, mBackgroundColor, 2702 animating, true); 2703 } 2704 if (mTouchMode == TOUCH_DONE_MODE) { 2705 return; 2706 } 2707 Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG); 2708 paint.setStyle(Paint.Style.STROKE); 2709 paint.setStrokeWidth(30.0f); 2710 paint.setARGB(0x50, 0, 0, 0); 2711 int maxX = mContentWidth - width; 2712 int maxY = mContentHeight - height; 2713 if (true) { // experiment: draw hint to place finger off magnify area 2714 drawMagnifyFrame(canvas, scrollFrame, paint); 2715 } else { 2716 canvas.drawRect(scrollFrame, paint); 2717 } 2718 int sc = canvas.save(); 2719 canvas.clipRect(scrollFrame); 2720 float halfX = (float) mZoomScrollX / maxX; 2721 if (mContentWidth * mZoomScrollLimit < width) { 2722 halfX = zoomFrameScaleX(width, 0.5f, halfX); 2723 } 2724 float halfY = (float) mZoomScrollY / maxY; 2725 if (mContentHeight * mZoomScrollLimit < height) { 2726 halfY = zoomFrameScaleY(height, 0.5f, halfY); 2727 } 2728 canvas.scale(halfScale, halfScale, mZoomScrollX + width * halfX 2729 , mZoomScrollY + height * halfY); 2730 if (DebugFlags.WEB_VIEW) { 2731 Log.v(LOGTAG, "scrollZoomDraw halfScale=" + halfScale + " w/h=(" 2732 + width + ", " + height + ") half=(" + halfX + ", " 2733 + halfY + ")"); 2734 } 2735 if (mDrawHistory) { 2736 canvas.drawPicture(mHistoryPicture); 2737 } else { 2738 mWebViewCore.drawContentPicture(canvas, mBackgroundColor, 2739 animating, false); 2740 } 2741 canvas.restoreToCount(sc); 2742 if (mTouchMode != SCROLL_ZOOM_OUT) { 2743 invalidate(); 2744 } 2745 } 2746 2747 private void zoomScrollTap(float x, float y) { 2748 float scale = scrollZoomGridScale(mZoomScrollInvLimit); 2749 float left = scrollZoomX(scale); 2750 float top = scrollZoomY(scale); 2751 int width = getViewWidth(); 2752 int height = getViewHeight(); 2753 x -= width * scale / 2; 2754 y -= height * scale / 2; 2755 mZoomScrollX = Math.min(mContentWidth - width 2756 , Math.max(0, (int) ((x - left) / scale))); 2757 mZoomScrollY = Math.min(mContentHeight - height 2758 , Math.max(0, (int) ((y - top) / scale))); 2759 if (DebugFlags.WEB_VIEW) { 2760 Log.v(LOGTAG, "zoomScrollTap scale=" + scale + " + (" + left 2761 + ", " + top + ") mZoomScroll=(" + mZoomScrollX + ", " 2762 + mZoomScrollY + ")" + " x=" + x + " y=" + y); 2763 } 2764 } 2765 2766 /** 2767 * @hide 2768 */ 2769 public boolean canZoomScrollOut() { 2770 if (mContentWidth == 0 || mContentHeight == 0) { 2771 return false; 2772 } 2773 int width = getViewWidth(); 2774 int height = getViewHeight(); 2775 float x = (float) width / (float) mContentWidth; 2776 float y = (float) height / (float) mContentHeight; 2777 mZoomScrollLimit = Math.max(DEFAULT_MIN_ZOOM_SCALE, Math.min(x, y)); 2778 mZoomScrollInvLimit = 1.0f / mZoomScrollLimit; 2779 if (DebugFlags.WEB_VIEW) { 2780 Log.v(LOGTAG, "canZoomScrollOut" 2781 + " mInvActualScale=" + mInvActualScale 2782 + " mZoomScrollLimit=" + mZoomScrollLimit 2783 + " mZoomScrollInvLimit=" + mZoomScrollInvLimit 2784 + " mContentWidth=" + mContentWidth 2785 + " mContentHeight=" + mContentHeight 2786 ); 2787 } 2788 // don't zoom out unless magnify area is at least half as wide 2789 // or tall as content 2790 float limit = mZoomScrollLimit * 2; 2791 return mContentWidth >= width * limit 2792 || mContentHeight >= height * limit; 2793 } 2794 2795 private void startZoomScrollOut() { 2796 setHorizontalScrollBarEnabled(false); 2797 setVerticalScrollBarEnabled(false); 2798 if (getSettings().getBuiltInZoomControls()) { 2799 if (mZoomButtonsController.isVisible()) { 2800 mZoomButtonsController.setVisible(false); 2801 } 2802 } else { 2803 if (mZoomControlRunnable != null) { 2804 mPrivateHandler.removeCallbacks(mZoomControlRunnable); 2805 } 2806 if (mZoomControls != null) { 2807 mZoomControls.hide(); 2808 } 2809 } 2810 int width = getViewWidth(); 2811 int height = getViewHeight(); 2812 int halfW = width >> 1; 2813 mLastTouchX = halfW; 2814 int halfH = height >> 1; 2815 mLastTouchY = halfH; 2816 mScroller.abortAnimation(); 2817 mZoomScrollStart = System.currentTimeMillis(); 2818 Rect zoomFrame = scrollZoomFrame(width, height 2819 , scrollZoomMagScale(mZoomScrollInvLimit)); 2820 mZoomScrollX = Math.max(0, (int) ((mScrollX + halfW) * mInvActualScale) 2821 - (zoomFrame.width() >> 1)); 2822 mZoomScrollY = Math.max(0, (int) ((mScrollY + halfH) * mInvActualScale) 2823 - (zoomFrame.height() >> 1)); 2824 scrollTo(0, 0); // triggers inval, starts animation 2825 clearTextEntry(); 2826 if (DebugFlags.WEB_VIEW) { 2827 Log.v(LOGTAG, "startZoomScrollOut mZoomScroll=(" 2828 + mZoomScrollX + ", " + mZoomScrollY +")"); 2829 } 2830 } 2831 2832 /** 2833 * @hide 2834 */ 2835 public void zoomScrollOut() { 2836 if (canZoomScrollOut() == false) { 2837 mTouchMode = TOUCH_DONE_MODE; 2838 return; 2839 } 2840 startZoomScrollOut(); 2841 mTouchMode = SCROLL_ZOOM_ANIMATION_OUT; 2842 invalidate(); 2843 } 2844 2845 private void moveZoomScrollWindow(float x, float y) { 2846 if (Math.abs(x - mLastZoomScrollRawX) < 1.5f 2847 && Math.abs(y - mLastZoomScrollRawY) < 1.5f) { 2848 return; 2849 } 2850 mLastZoomScrollRawX = x; 2851 mLastZoomScrollRawY = y; 2852 int oldX = mZoomScrollX; 2853 int oldY = mZoomScrollY; 2854 int width = getViewWidth(); 2855 int height = getViewHeight(); 2856 int maxZoomX = mContentWidth - width; 2857 if (maxZoomX > 0) { 2858 int maxScreenX = width - (int) Math.ceil(width 2859 * mZoomScrollLimit) - SCROLL_ZOOM_FINGER_BUFFER; 2860 if (DebugFlags.WEB_VIEW) { 2861 Log.v(LOGTAG, "moveZoomScrollWindow-X" 2862 + " maxScreenX=" + maxScreenX + " width=" + width 2863 + " mZoomScrollLimit=" + mZoomScrollLimit + " x=" + x); 2864 } 2865 x += maxScreenX * mLastScrollX / maxZoomX - mLastTouchX; 2866 x *= Math.max(maxZoomX / maxScreenX, mZoomScrollInvLimit); 2867 mZoomScrollX = Math.max(0, Math.min(maxZoomX, (int) x)); 2868 } 2869 int maxZoomY = mContentHeight - height; 2870 if (maxZoomY > 0) { 2871 int maxScreenY = height - (int) Math.ceil(height 2872 * mZoomScrollLimit) - SCROLL_ZOOM_FINGER_BUFFER; 2873 if (DebugFlags.WEB_VIEW) { 2874 Log.v(LOGTAG, "moveZoomScrollWindow-Y" 2875 + " maxScreenY=" + maxScreenY + " height=" + height 2876 + " mZoomScrollLimit=" + mZoomScrollLimit + " y=" + y); 2877 } 2878 y += maxScreenY * mLastScrollY / maxZoomY - mLastTouchY; 2879 y *= Math.max(maxZoomY / maxScreenY, mZoomScrollInvLimit); 2880 mZoomScrollY = Math.max(0, Math.min(maxZoomY, (int) y)); 2881 } 2882 if (oldX != mZoomScrollX || oldY != mZoomScrollY) { 2883 invalidate(); 2884 } 2885 if (DebugFlags.WEB_VIEW) { 2886 Log.v(LOGTAG, "moveZoomScrollWindow" 2887 + " scrollTo=(" + mZoomScrollX + ", " + mZoomScrollY + ")" 2888 + " mLastTouch=(" + mLastTouchX + ", " + mLastTouchY + ")" 2889 + " maxZoom=(" + maxZoomX + ", " + maxZoomY + ")" 2890 + " last=("+mLastScrollX+", "+mLastScrollY+")" 2891 + " x=" + x + " y=" + y); 2892 } 2893 } 2894 2895 private void setZoomScrollIn() { 2896 mZoomScrollStart = System.currentTimeMillis(); 2897 } 2898 2899 private float mZoomScrollLimit; 2900 private float mZoomScrollInvLimit; 2901 private int mLastScrollX; 2902 private int mLastScrollY; 2903 private long mZoomScrollStart; 2904 private int mZoomScrollX; 2905 private int mZoomScrollY; 2906 private float mLastZoomScrollRawX = -1000.0f; 2907 private float mLastZoomScrollRawY = -1000.0f; 2908 // The zoomed scale varies from 1.0 to DEFAULT_MIN_ZOOM_SCALE == 0.25. 2909 // The zoom animation duration SCROLL_ZOOM_DURATION == 0.5. 2910 // Two pressures compete for gridding; a high frame rate (e.g. 20 fps) 2911 // and minimizing font cache allocations (fewer frames is better). 2912 // A SCROLL_ZOOM_GRID of 6 permits about 20 zoom levels over 0.5 seconds: 2913 // the inverse of: 1.0, 1.16, 1.33, 1.5, 1.67, 1.84, 2.0, etc. to 4.0 2914 private static final int SCROLL_ZOOM_GRID = 6; 2915 private static final int SCROLL_ZOOM_DURATION = 500; 2916 // Make it easier to get to the bottom of a document by reserving a 32 2917 // pixel buffer, for when the starting drag is a bit below the bottom of 2918 // the magnify frame. 2919 private static final int SCROLL_ZOOM_FINGER_BUFFER = 32; 2920 2921 // draw history 2922 private boolean mDrawHistory = false; 2923 private Picture mHistoryPicture = null; 2924 private int mHistoryWidth = 0; 2925 private int mHistoryHeight = 0; 2926 2927 // Only check the flag, can be called from WebCore thread 2928 boolean drawHistory() { 2929 return mDrawHistory; 2930 } 2931 2932 // Should only be called in UI thread 2933 void switchOutDrawHistory() { 2934 if (null == mWebViewCore) return; // CallbackProxy may trigger this 2935 if (mDrawHistory && mWebViewCore.pictureReady()) { 2936 mDrawHistory = false; 2937 invalidate(); 2938 int oldScrollX = mScrollX; 2939 int oldScrollY = mScrollY; 2940 mScrollX = pinLocX(mScrollX); 2941 mScrollY = pinLocY(mScrollY); 2942 if (oldScrollX != mScrollX || oldScrollY != mScrollY) { 2943 mUserScroll = false; 2944 mWebViewCore.sendMessage(EventHub.SYNC_SCROLL, oldScrollX, 2945 oldScrollY); 2946 } 2947 sendOurVisibleRect(); 2948 } 2949 } 2950 2951 WebViewCore.CursorData cursorData() { 2952 WebViewCore.CursorData result = new WebViewCore.CursorData(); 2953 result.mMoveGeneration = nativeMoveGeneration(); 2954 result.mFrame = nativeCursorFramePointer(); 2955 Point position = nativeCursorPosition(); 2956 result.mX = position.x; 2957 result.mY = position.y; 2958 return result; 2959 } 2960 2961 /** 2962 * Delete text from start to end in the focused textfield. If there is no 2963 * focus, or if start == end, silently fail. If start and end are out of 2964 * order, swap them. 2965 * @param start Beginning of selection to delete. 2966 * @param end End of selection to delete. 2967 */ 2968 /* package */ void deleteSelection(int start, int end) { 2969 mTextGeneration++; 2970 mWebViewCore.sendMessage(EventHub.DELETE_SELECTION, start, end); 2971 } 2972 2973 /** 2974 * Set the selection to (start, end) in the focused textfield. If start and 2975 * end are out of order, swap them. 2976 * @param start Beginning of selection. 2977 * @param end End of selection. 2978 */ 2979 /* package */ void setSelection(int start, int end) { 2980 mWebViewCore.sendMessage(EventHub.SET_SELECTION, start, end); 2981 } 2982 2983 // Called by JNI when a touch event puts a textfield into focus. 2984 private void displaySoftKeyboard() { 2985 InputMethodManager imm = (InputMethodManager) 2986 getContext().getSystemService(Context.INPUT_METHOD_SERVICE); 2987 imm.showSoftInput(mWebTextView, 0); 2988 mWebTextView.enableScrollOnScreen(true); 2989 // Now we need to fake a touch event to place the cursor where the 2990 // user touched. 2991 AbsoluteLayout.LayoutParams lp = (AbsoluteLayout.LayoutParams) 2992 mWebTextView.getLayoutParams(); 2993 if (lp != null) { 2994 // Take the last touch and adjust for the location of the 2995 // WebTextView. 2996 float x = mLastTouchX + (float) (mScrollX - lp.x); 2997 float y = mLastTouchY + (float) (mScrollY - lp.y); 2998 mWebTextView.fakeTouchEvent(x, y); 2999 } 3000 } 3001 3002 /* 3003 * This method checks the current focus and cursor and potentially rebuilds 3004 * mWebTextView to have the appropriate properties, such as password, 3005 * multiline, and what text it contains. It also removes it if necessary. 3006 */ 3007 private void rebuildWebTextView() { 3008 // If the WebView does not have focus, do nothing until it gains focus. 3009 if (!hasFocus() && (null == mWebTextView || !mWebTextView.hasFocus()) 3010 || (mTouchMode >= FIRST_SCROLL_ZOOM 3011 && mTouchMode <= LAST_SCROLL_ZOOM)) { 3012 return; 3013 } 3014 boolean alreadyThere = inEditingMode(); 3015 // inEditingMode can only return true if mWebTextView is non-null, 3016 // so we can safely call remove() if (alreadyThere) 3017 if (0 == mNativeClass || !nativeFocusCandidateIsTextInput()) { 3018 if (alreadyThere) { 3019 mWebTextView.remove(); 3020 } 3021 return; 3022 } 3023 // At this point, we know we have found an input field, so go ahead 3024 // and create the WebTextView if necessary. 3025 if (mWebTextView == null) { 3026 mWebTextView = new WebTextView(mContext, WebView.this); 3027 // Initialize our generation number. 3028 mTextGeneration = 0; 3029 } 3030 mWebTextView.setTextSize(contentToView(nativeFocusCandidateTextSize())); 3031 Rect visibleRect = new Rect(); 3032 calcOurContentVisibleRect(visibleRect); 3033 // Note that sendOurVisibleRect calls viewToContent, so the coordinates 3034 // should be in content coordinates. 3035 Rect bounds = nativeFocusCandidateNodeBounds(); 3036 if (!Rect.intersects(bounds, visibleRect)) { 3037 // Node is not on screen, so do not bother. 3038 return; 3039 } 3040 String text = nativeFocusCandidateText(); 3041 int nodePointer = nativeFocusCandidatePointer(); 3042 if (alreadyThere && mWebTextView.isSameTextField(nodePointer)) { 3043 // It is possible that we have the same textfield, but it has moved, 3044 // i.e. In the case of opening/closing the screen. 3045 // In that case, we need to set the dimensions, but not the other 3046 // aspects. 3047 // We also need to restore the selection, which gets wrecked by 3048 // calling setTextEntryRect. 3049 Spannable spannable = (Spannable) mWebTextView.getText(); 3050 int start = Selection.getSelectionStart(spannable); 3051 int end = Selection.getSelectionEnd(spannable); 3052 // If the text has been changed by webkit, update it. However, if 3053 // there has been more UI text input, ignore it. We will receive 3054 // another update when that text is recognized. 3055 if (text != null && !text.equals(spannable.toString()) 3056 && nativeTextGeneration() == mTextGeneration) { 3057 mWebTextView.setTextAndKeepSelection(text); 3058 } else { 3059 Selection.setSelection(spannable, start, end); 3060 } 3061 } else { 3062 Rect vBox = contentToView(bounds); 3063 mWebTextView.setRect(vBox.left, vBox.top, vBox.width(), 3064 vBox.height()); 3065 mWebTextView.setGravity(nativeFocusCandidateIsRtlText() ? 3066 Gravity.RIGHT : Gravity.NO_GRAVITY); 3067 // this needs to be called before update adapter thread starts to 3068 // ensure the mWebTextView has the same node pointer 3069 mWebTextView.setNodePointer(nodePointer); 3070 int maxLength = -1; 3071 boolean isTextField = nativeFocusCandidateIsTextField(); 3072 if (isTextField) { 3073 maxLength = nativeFocusCandidateMaxLength(); 3074 String name = nativeFocusCandidateName(); 3075 if (mWebViewCore.getSettings().getSaveFormData() 3076 && name != null) { 3077 Message update = mPrivateHandler.obtainMessage( 3078 REQUEST_FORM_DATA, nodePointer); 3079 RequestFormData updater = new RequestFormData(name, 3080 getUrl(), update); 3081 Thread t = new Thread(updater); 3082 t.start(); 3083 } 3084 } 3085 mWebTextView.setMaxLength(maxLength); 3086 AutoCompleteAdapter adapter = null; 3087 mWebTextView.setAdapterCustom(adapter); 3088 mWebTextView.setSingleLine(isTextField); 3089 mWebTextView.setInPassword(nativeFocusCandidateIsPassword()); 3090 if (null == text) { 3091 mWebTextView.setText("", 0, 0); 3092 } else { 3093 // Change to true to enable the old style behavior, where 3094 // entering a textfield/textarea always set the selection to the 3095 // whole field. This was desirable for the case where the user 3096 // intends to scroll past the field using the trackball. 3097 // However, it causes a problem when replying to emails - the 3098 // user expects the cursor to be at the beginning of the 3099 // textarea. Testing out a new behavior, where textfields set 3100 // selection at the end, and textareas at the beginning. 3101 if (false) { 3102 mWebTextView.setText(text, 0, text.length()); 3103 } else if (isTextField) { 3104 int length = text.length(); 3105 mWebTextView.setText(text, length, length); 3106 } else { 3107 mWebTextView.setText(text, 0, 0); 3108 } 3109 } 3110 mWebTextView.requestFocus(); 3111 } 3112 } 3113 3114 /* 3115 * This class requests an Adapter for the WebTextView which shows past 3116 * entries stored in the database. It is a Runnable so that it can be done 3117 * in its own thread, without slowing down the UI. 3118 */ 3119 private class RequestFormData implements Runnable { 3120 private String mName; 3121 private String mUrl; 3122 private Message mUpdateMessage; 3123 3124 public RequestFormData(String name, String url, Message msg) { 3125 mName = name; 3126 mUrl = url; 3127 mUpdateMessage = msg; 3128 } 3129 3130 public void run() { 3131 ArrayList<String> pastEntries = mDatabase.getFormData(mUrl, mName); 3132 if (pastEntries.size() > 0) { 3133 AutoCompleteAdapter adapter = new 3134 AutoCompleteAdapter(mContext, pastEntries); 3135 mUpdateMessage.obj = adapter; 3136 mUpdateMessage.sendToTarget(); 3137 } 3138 } 3139 } 3140 3141 // This is used to determine long press with the center key. Does not 3142 // affect long press with the trackball/touch. 3143 private boolean mGotCenterDown = false; 3144 3145 @Override 3146 public boolean onKeyDown(int keyCode, KeyEvent event) { 3147 if (DebugFlags.WEB_VIEW) { 3148 Log.v(LOGTAG, "keyDown at " + System.currentTimeMillis() 3149 + ", " + event); 3150 } 3151 3152 if (mNativeClass == 0) { 3153 return false; 3154 } 3155 3156 // do this hack up front, so it always works, regardless of touch-mode 3157 if (AUTO_REDRAW_HACK && (keyCode == KeyEvent.KEYCODE_CALL)) { 3158 mAutoRedraw = !mAutoRedraw; 3159 if (mAutoRedraw) { 3160 invalidate(); 3161 } 3162 return true; 3163 } 3164 3165 // Bubble up the key event if 3166 // 1. it is a system key; or 3167 // 2. the host application wants to handle it; or 3168 // 3. webview is in scroll-zoom state; 3169 if (event.isSystem() 3170 || mCallbackProxy.uiOverrideKeyEvent(event) 3171 || (mTouchMode >= FIRST_SCROLL_ZOOM && mTouchMode <= LAST_SCROLL_ZOOM)) { 3172 return false; 3173 } 3174 3175 if (mShiftIsPressed == false && nativeCursorWantsKeyEvents() == false 3176 && (keyCode == KeyEvent.KEYCODE_SHIFT_LEFT 3177 || keyCode == KeyEvent.KEYCODE_SHIFT_RIGHT)) { 3178 mExtendSelection = false; 3179 mShiftIsPressed = true; 3180 if (nativeHasCursorNode()) { 3181 Rect rect = nativeCursorNodeBounds(); 3182 mSelectX = contentToView(rect.left); 3183 mSelectY = contentToView(rect.top); 3184 } else { 3185 mSelectX = mScrollX + (int) mLastTouchX; 3186 mSelectY = mScrollY + (int) mLastTouchY; 3187 } 3188 nativeHideCursor(); 3189 } 3190 3191 if (keyCode >= KeyEvent.KEYCODE_DPAD_UP 3192 && keyCode <= KeyEvent.KEYCODE_DPAD_RIGHT) { 3193 // always handle the navigation keys in the UI thread 3194 switchOutDrawHistory(); 3195 if (navHandledKey(keyCode, 1, false, event.getEventTime())) { 3196 playSoundEffect(keyCodeToSoundsEffect(keyCode)); 3197 return true; 3198 } 3199 // Bubble up the key event as WebView doesn't handle it 3200 return false; 3201 } 3202 3203 if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER) { 3204 switchOutDrawHistory(); 3205 if (event.getRepeatCount() == 0) { 3206 mGotCenterDown = true; 3207 mPrivateHandler.sendMessageDelayed(mPrivateHandler 3208 .obtainMessage(LONG_PRESS_CENTER), LONG_PRESS_TIMEOUT); 3209 // Already checked mNativeClass, so we do not need to check it 3210 // again. 3211 nativeRecordButtons(hasFocus() && hasWindowFocus(), true, true); 3212 return true; 3213 } 3214 // Bubble up the key event as WebView doesn't handle it 3215 return false; 3216 } 3217 3218 if (keyCode != KeyEvent.KEYCODE_SHIFT_LEFT 3219 && keyCode != KeyEvent.KEYCODE_SHIFT_RIGHT) { 3220 // turn off copy select if a shift-key combo is pressed 3221 mExtendSelection = mShiftIsPressed = false; 3222 if (mTouchMode == TOUCH_SELECT_MODE) { 3223 mTouchMode = TOUCH_INIT_MODE; 3224 } 3225 } 3226 3227 if (getSettings().getNavDump()) { 3228 switch (keyCode) { 3229 case KeyEvent.KEYCODE_4: 3230 // "/data/data/com.android.browser/displayTree.txt" 3231 nativeDumpDisplayTree(getUrl()); 3232 break; 3233 case KeyEvent.KEYCODE_5: 3234 case KeyEvent.KEYCODE_6: 3235 // 5: dump the dom tree to the file 3236 // "/data/data/com.android.browser/domTree.txt" 3237 // 6: dump the dom tree to the adb log 3238 mWebViewCore.sendMessage(EventHub.DUMP_DOMTREE, 3239 (keyCode == KeyEvent.KEYCODE_5) ? 1 : 0, 0); 3240 break; 3241 case KeyEvent.KEYCODE_7: 3242 case KeyEvent.KEYCODE_8: 3243 // 7: dump the render tree to the file 3244 // "/data/data/com.android.browser/renderTree.txt" 3245 // 8: dump the render tree to the adb log 3246 mWebViewCore.sendMessage(EventHub.DUMP_RENDERTREE, 3247 (keyCode == KeyEvent.KEYCODE_7) ? 1 : 0, 0); 3248 break; 3249 case KeyEvent.KEYCODE_9: 3250 nativeInstrumentReport(); 3251 return true; 3252 } 3253 } 3254 3255 if (nativeCursorWantsKeyEvents() && !nativeCursorMatchesFocus()) { 3256 // This message will put the node in focus, for the DOM's notion 3257 // of focus 3258 mWebViewCore.sendMessage(EventHub.CLICK); 3259 if (nativeCursorIsTextInput()) { 3260 // This will bring up the WebTextView and put it in focus, for 3261 // our view system's notion of focus 3262 rebuildWebTextView(); 3263 // Now we need to pass the event to it 3264 return mWebTextView.onKeyDown(keyCode, event); 3265 } 3266 } 3267 3268 // TODO: should we pass all the keys to DOM or check the meta tag 3269 if (nativeCursorWantsKeyEvents() || true) { 3270 // pass the key to DOM 3271 mWebViewCore.sendMessage(EventHub.KEY_DOWN, event); 3272 // return true as DOM handles the key 3273 return true; 3274 } 3275 3276 // Bubble up the key event as WebView doesn't handle it 3277 return false; 3278 } 3279 3280 @Override 3281 public boolean onKeyUp(int keyCode, KeyEvent event) { 3282 if (DebugFlags.WEB_VIEW) { 3283 Log.v(LOGTAG, "keyUp at " + System.currentTimeMillis() 3284 + ", " + event); 3285 } 3286 3287 if (mNativeClass == 0) { 3288 return false; 3289 } 3290 3291 // special CALL handling when cursor node's href is "tel:XXX" 3292 if (keyCode == KeyEvent.KEYCODE_CALL && nativeHasCursorNode()) { 3293 String text = nativeCursorText(); 3294 if (!nativeCursorIsTextInput() && text != null 3295 && text.startsWith(SCHEME_TEL)) { 3296 Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse(text)); 3297 getContext().startActivity(intent); 3298 return true; 3299 } 3300 } 3301 3302 // Bubble up the key event if 3303 // 1. it is a system key; or 3304 // 2. the host application wants to handle it; 3305 if (event.isSystem() || mCallbackProxy.uiOverrideKeyEvent(event)) { 3306 return false; 3307 } 3308 3309 // special handling in scroll_zoom state 3310 if (mTouchMode >= FIRST_SCROLL_ZOOM && mTouchMode <= LAST_SCROLL_ZOOM) { 3311 if (KeyEvent.KEYCODE_DPAD_CENTER == keyCode 3312 && mTouchMode != SCROLL_ZOOM_ANIMATION_IN) { 3313 setZoomScrollIn(); 3314 mTouchMode = SCROLL_ZOOM_ANIMATION_IN; 3315 invalidate(); 3316 return true; 3317 } 3318 return false; 3319 } 3320 3321 if (keyCode == KeyEvent.KEYCODE_SHIFT_LEFT 3322 || keyCode == KeyEvent.KEYCODE_SHIFT_RIGHT) { 3323 if (commitCopy()) { 3324 return true; 3325 } 3326 } 3327 3328 if (keyCode >= KeyEvent.KEYCODE_DPAD_UP 3329 && keyCode <= KeyEvent.KEYCODE_DPAD_RIGHT) { 3330 // always handle the navigation keys in the UI thread 3331 // Bubble up the key event as WebView doesn't handle it 3332 return false; 3333 } 3334 3335 if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER) { 3336 // remove the long press message first 3337 mPrivateHandler.removeMessages(LONG_PRESS_CENTER); 3338 mGotCenterDown = false; 3339 3340 if (mShiftIsPressed) { 3341 return false; 3342 } 3343 if (getSettings().supportZoom() 3344 && mTouchMode == TOUCH_DOUBLECLICK_MODE) { 3345 zoomScrollOut(); 3346 } else { 3347 mPrivateHandler.sendMessageDelayed(mPrivateHandler 3348 .obtainMessage(SWITCH_TO_CLICK), TAP_TIMEOUT); 3349 if (DebugFlags.WEB_VIEW) { 3350 Log.v(LOGTAG, "TOUCH_DOUBLECLICK_MODE"); 3351 } 3352 mTouchMode = TOUCH_DOUBLECLICK_MODE; 3353 } 3354 return true; 3355 } 3356 3357 // TODO: should we pass all the keys to DOM or check the meta tag 3358 if (nativeCursorWantsKeyEvents() || true) { 3359 // pass the key to DOM 3360 mWebViewCore.sendMessage(EventHub.KEY_UP, event); 3361 // return true as DOM handles the key 3362 return true; 3363 } 3364 3365 // Bubble up the key event as WebView doesn't handle it 3366 return false; 3367 } 3368 3369 /** 3370 * @hide 3371 */ 3372 public void emulateShiftHeld() { 3373 mExtendSelection = false; 3374 mShiftIsPressed = true; 3375 nativeHideCursor(); 3376 } 3377 3378 private boolean commitCopy() { 3379 boolean copiedSomething = false; 3380 if (mExtendSelection) { 3381 // copy region so core operates on copy without touching orig. 3382 Region selection = new Region(nativeGetSelection()); 3383 if (selection.isEmpty() == false) { 3384 Toast.makeText(mContext 3385 , com.android.internal.R.string.text_copied 3386 , Toast.LENGTH_SHORT).show(); 3387 mWebViewCore.sendMessage(EventHub.GET_SELECTION, selection); 3388 copiedSomething = true; 3389 } 3390 mExtendSelection = false; 3391 } 3392 mShiftIsPressed = false; 3393 if (mTouchMode == TOUCH_SELECT_MODE) { 3394 mTouchMode = TOUCH_INIT_MODE; 3395 } 3396 return copiedSomething; 3397 } 3398 3399 // Set this as a hierarchy change listener so we can know when this view 3400 // is removed and still have access to our parent. 3401 @Override 3402 protected void onAttachedToWindow() { 3403 super.onAttachedToWindow(); 3404 ViewParent parent = getParent(); 3405 if (parent instanceof ViewGroup) { 3406 ViewGroup p = (ViewGroup) parent; 3407 p.setOnHierarchyChangeListener(this); 3408 } 3409 } 3410 3411 @Override 3412 protected void onDetachedFromWindow() { 3413 super.onDetachedFromWindow(); 3414 ViewParent parent = getParent(); 3415 if (parent instanceof ViewGroup) { 3416 ViewGroup p = (ViewGroup) parent; 3417 p.setOnHierarchyChangeListener(null); 3418 } 3419 3420 // Clean up the zoom controller 3421 mZoomButtonsController.setVisible(false); 3422 } 3423 3424 // Implementation for OnHierarchyChangeListener 3425 public void onChildViewAdded(View parent, View child) {} 3426 3427 public void onChildViewRemoved(View p, View child) { 3428 if (child == this) { 3429 if (inEditingMode()) { 3430 clearTextEntry(); 3431 } 3432 } 3433 } 3434 3435 /** 3436 * @deprecated WebView should not have implemented 3437 * ViewTreeObserver.OnGlobalFocusChangeListener. This method 3438 * does nothing now. 3439 */ 3440 @Deprecated 3441 public void onGlobalFocusChanged(View oldFocus, View newFocus) { 3442 } 3443 3444 // To avoid drawing the cursor ring, and remove the TextView when our window 3445 // loses focus. 3446 @Override 3447 public void onWindowFocusChanged(boolean hasWindowFocus) { 3448 if (hasWindowFocus) { 3449 if (hasFocus()) { 3450 // If our window regained focus, and we have focus, then begin 3451 // drawing the cursor ring 3452 mDrawCursorRing = true; 3453 if (mNativeClass != 0) { 3454 nativeRecordButtons(true, false, true); 3455 } 3456 } else { 3457 // If our window gained focus, but we do not have it, do not 3458 // draw the cursor ring. 3459 mDrawCursorRing = false; 3460 // We do not call nativeRecordButtons here because we assume 3461 // that when we lost focus, or window focus, it got called with 3462 // false for the first parameter 3463 } 3464 } else { 3465 if (getSettings().getBuiltInZoomControls() && !mZoomButtonsController.isVisible()) { 3466 /* 3467 * The zoom controls come in their own window, so our window 3468 * loses focus. Our policy is to not draw the cursor ring if 3469 * our window is not focused, but this is an exception since 3470 * the user can still navigate the web page with the zoom 3471 * controls showing. 3472 */ 3473 // If our window has lost focus, stop drawing the cursor ring 3474 mDrawCursorRing = false; 3475 } 3476 mGotKeyDown = false; 3477 mShiftIsPressed = false; 3478 if (mNativeClass != 0) { 3479 nativeRecordButtons(false, false, true); 3480 } 3481 setFocusControllerInactive(); 3482 } 3483 invalidate(); 3484 super.onWindowFocusChanged(hasWindowFocus); 3485 } 3486 3487 /* 3488 * Pass a message to WebCore Thread, telling the WebCore::Page's 3489 * FocusController to be "inactive" so that it will 3490 * not draw the blinking cursor. It gets set to "active" to draw the cursor 3491 * in WebViewCore.cpp, when the WebCore thread receives key events/clicks. 3492 */ 3493 private void setFocusControllerInactive() { 3494 // Do not need to also check whether mWebViewCore is null, because 3495 // mNativeClass is only set if mWebViewCore is non null 3496 if (mNativeClass == 0) return; 3497 mWebViewCore.sendMessage(EventHub.SET_INACTIVE); 3498 } 3499 3500 @Override 3501 protected void onFocusChanged(boolean focused, int direction, 3502 Rect previouslyFocusedRect) { 3503 if (DebugFlags.WEB_VIEW) { 3504 Log.v(LOGTAG, "MT focusChanged " + focused + ", " + direction); 3505 } 3506 if (focused) { 3507 // When we regain focus, if we have window focus, resume drawing 3508 // the cursor ring 3509 if (hasWindowFocus()) { 3510 mDrawCursorRing = true; 3511 if (mNativeClass != 0) { 3512 nativeRecordButtons(true, false, true); 3513 } 3514 //} else { 3515 // The WebView has gained focus while we do not have 3516 // windowfocus. When our window lost focus, we should have 3517 // called nativeRecordButtons(false...) 3518 } 3519 } else { 3520 // When we lost focus, unless focus went to the TextView (which is 3521 // true if we are in editing mode), stop drawing the cursor ring. 3522 if (!inEditingMode()) { 3523 mDrawCursorRing = false; 3524 if (mNativeClass != 0) { 3525 nativeRecordButtons(false, false, true); 3526 } 3527 setFocusControllerInactive(); 3528 } 3529 mGotKeyDown = false; 3530 } 3531 3532 super.onFocusChanged(focused, direction, previouslyFocusedRect); 3533 } 3534 3535 @Override 3536 protected void onSizeChanged(int w, int h, int ow, int oh) { 3537 super.onSizeChanged(w, h, ow, oh); 3538 // Center zooming to the center of the screen. 3539 mZoomCenterX = getViewWidth() * .5f; 3540 mZoomCenterY = getViewHeight() * .5f; 3541 3542 // update mMinZoomScale if the minimum zoom scale is not fixed 3543 if (!mMinZoomScaleFixed) { 3544 mMinZoomScale = (float) getViewWidth() 3545 / Math.max(ZOOM_OUT_WIDTH, mContentWidth); 3546 } 3547 3548 // we always force, in case our height changed, in which case we still 3549 // want to send the notification over to webkit 3550 setNewZoomScale(mActualScale, true); 3551 } 3552 3553 @Override 3554 protected void onScrollChanged(int l, int t, int oldl, int oldt) { 3555 super.onScrollChanged(l, t, oldl, oldt); 3556 sendOurVisibleRect(); 3557 } 3558 3559 3560 @Override 3561 public boolean dispatchKeyEvent(KeyEvent event) { 3562 boolean dispatch = true; 3563 3564 if (!inEditingMode()) { 3565 if (event.getAction() == KeyEvent.ACTION_DOWN) { 3566 mGotKeyDown = true; 3567 } else { 3568 if (!mGotKeyDown) { 3569 /* 3570 * We got a key up for which we were not the recipient of 3571 * the original key down. Don't give it to the view. 3572 */ 3573 dispatch = false; 3574 } 3575 mGotKeyDown = false; 3576 } 3577 } 3578 3579 if (dispatch) { 3580 return super.dispatchKeyEvent(event); 3581 } else { 3582 // We didn't dispatch, so let something else handle the key 3583 return false; 3584 } 3585 } 3586 3587 // Here are the snap align logic: 3588 // 1. If it starts nearly horizontally or vertically, snap align; 3589 // 2. If there is a dramitic direction change, let it go; 3590 // 3. If there is a same direction back and forth, lock it. 3591 3592 // adjustable parameters 3593 private int mMinLockSnapReverseDistance; 3594 private static final float MAX_SLOPE_FOR_DIAG = 1.5f; 3595 private static final int MIN_BREAK_SNAP_CROSS_DISTANCE = 80; 3596 3597 @Override 3598 public boolean onTouchEvent(MotionEvent ev) { 3599 if (mNativeClass == 0 || !isClickable() || !isLongClickable()) { 3600 return false; 3601 } 3602 3603 if (DebugFlags.WEB_VIEW) { 3604 Log.v(LOGTAG, ev + " at " + ev.getEventTime() + " mTouchMode=" 3605 + mTouchMode); 3606 } 3607 3608 int action = ev.getAction(); 3609 float x = ev.getX(); 3610 float y = ev.getY(); 3611 long eventTime = ev.getEventTime(); 3612 3613 // Due to the touch screen edge effect, a touch closer to the edge 3614 // always snapped to the edge. As getViewWidth() can be different from 3615 // getWidth() due to the scrollbar, adjusting the point to match 3616 // getViewWidth(). Same applied to the height. 3617 if (x > getViewWidth() - 1) { 3618 x = getViewWidth() - 1; 3619 } 3620 if (y > getViewHeight() - 1) { 3621 y = getViewHeight() - 1; 3622 } 3623 3624 // pass the touch events from UI thread to WebCore thread 3625 if (mForwardTouchEvents && mTouchMode != SCROLL_ZOOM_OUT 3626 && mTouchMode != SCROLL_ZOOM_ANIMATION_IN 3627 && mTouchMode != SCROLL_ZOOM_ANIMATION_OUT 3628 && (action != MotionEvent.ACTION_MOVE || 3629 eventTime - mLastSentTouchTime > TOUCH_SENT_INTERVAL)) { 3630 WebViewCore.TouchEventData ted = new WebViewCore.TouchEventData(); 3631 ted.mAction = action; 3632 ted.mX = viewToContent((int) x + mScrollX); 3633 ted.mY = viewToContent((int) y + mScrollY); 3634 mWebViewCore.sendMessage(EventHub.TOUCH_EVENT, ted); 3635 mLastSentTouchTime = eventTime; 3636 } 3637 3638 int deltaX = (int) (mLastTouchX - x); 3639 int deltaY = (int) (mLastTouchY - y); 3640 3641 switch (action) { 3642 case MotionEvent.ACTION_DOWN: { 3643 if (mTouchMode == SCROLL_ZOOM_ANIMATION_IN 3644 || mTouchMode == SCROLL_ZOOM_ANIMATION_OUT) { 3645 // no interaction while animation is in progress 3646 break; 3647 } else if (mTouchMode == SCROLL_ZOOM_OUT) { 3648 mLastScrollX = mZoomScrollX; 3649 mLastScrollY = mZoomScrollY; 3650 // If two taps are close, ignore the first tap 3651 } else if (!mScroller.isFinished()) { 3652 mScroller.abortAnimation(); 3653 mTouchMode = TOUCH_DRAG_START_MODE; 3654 mPrivateHandler.removeMessages(RESUME_WEBCORE_UPDATE); 3655 } else if (mShiftIsPressed) { 3656 mSelectX = mScrollX + (int) x; 3657 mSelectY = mScrollY + (int) y; 3658 mTouchMode = TOUCH_SELECT_MODE; 3659 if (DebugFlags.WEB_VIEW) { 3660 Log.v(LOGTAG, "select=" + mSelectX + "," + mSelectY); 3661 } 3662 nativeMoveSelection(viewToContent(mSelectX) 3663 , viewToContent(mSelectY), false); 3664 mTouchSelection = mExtendSelection = true; 3665 } else { 3666 mTouchMode = TOUCH_INIT_MODE; 3667 mPreventDrag = mForwardTouchEvents; 3668 if (mLogEvent && eventTime - mLastTouchUpTime < 1000) { 3669 EventLog.writeEvent(EVENT_LOG_DOUBLE_TAP_DURATION, 3670 (eventTime - mLastTouchUpTime), eventTime); 3671 } 3672 } 3673 // Trigger the link 3674 if (mTouchMode == TOUCH_INIT_MODE) { 3675 mPrivateHandler.sendMessageDelayed(mPrivateHandler 3676 .obtainMessage(SWITCH_TO_SHORTPRESS), TAP_TIMEOUT); 3677 } 3678 // Remember where the motion event started 3679 mLastTouchX = x; 3680 mLastTouchY = y; 3681 mLastTouchTime = eventTime; 3682 mVelocityTracker = VelocityTracker.obtain(); 3683 mSnapScrollMode = SNAP_NONE; 3684 break; 3685 } 3686 case MotionEvent.ACTION_MOVE: { 3687 if (mTouchMode == TOUCH_DONE_MODE 3688 || mTouchMode == SCROLL_ZOOM_ANIMATION_IN 3689 || mTouchMode == SCROLL_ZOOM_ANIMATION_OUT) { 3690 // no dragging during scroll zoom animation 3691 break; 3692 } 3693 if (mTouchMode == SCROLL_ZOOM_OUT) { 3694 // while fully zoomed out, move the virtual window 3695 moveZoomScrollWindow(x, y); 3696 break; 3697 } 3698 mVelocityTracker.addMovement(ev); 3699 3700 if (mTouchMode != TOUCH_DRAG_MODE) { 3701 if (mTouchMode == TOUCH_SELECT_MODE) { 3702 mSelectX = mScrollX + (int) x; 3703 mSelectY = mScrollY + (int) y; 3704 if (DebugFlags.WEB_VIEW) { 3705 Log.v(LOGTAG, "xtend=" + mSelectX + "," + mSelectY); 3706 } 3707 nativeMoveSelection(viewToContent(mSelectX) 3708 , viewToContent(mSelectY), true); 3709 invalidate(); 3710 break; 3711 } 3712 if (mPreventDrag || (deltaX * deltaX + deltaY * deltaY) 3713 < mTouchSlopSquare) { 3714 break; 3715 } 3716 3717 if (mTouchMode == TOUCH_SHORTPRESS_MODE 3718 || mTouchMode == TOUCH_SHORTPRESS_START_MODE) { 3719 mPrivateHandler.removeMessages(SWITCH_TO_LONGPRESS); 3720 } else if (mTouchMode == TOUCH_INIT_MODE) { 3721 mPrivateHandler.removeMessages(SWITCH_TO_SHORTPRESS); 3722 } 3723 3724 // if it starts nearly horizontal or vertical, enforce it 3725 int ax = Math.abs(deltaX); 3726 int ay = Math.abs(deltaY); 3727 if (ax > MAX_SLOPE_FOR_DIAG * ay) { 3728 mSnapScrollMode = SNAP_X; 3729 mSnapPositive = deltaX > 0; 3730 } else if (ay > MAX_SLOPE_FOR_DIAG * ax) { 3731 mSnapScrollMode = SNAP_Y; 3732 mSnapPositive = deltaY > 0; 3733 } 3734 3735 mTouchMode = TOUCH_DRAG_MODE; 3736 WebViewCore.pauseUpdate(mWebViewCore); 3737 nativeHideCursor(); 3738 // remove the zoom anchor if there is any 3739 if (mZoomScale != 0) { 3740 mWebViewCore 3741 .sendMessage(EventHub.SET_SNAP_ANCHOR, 0, 0); 3742 } 3743 WebSettings settings = getSettings(); 3744 if (settings.supportZoom() 3745 && settings.getBuiltInZoomControls() 3746 && !mZoomButtonsController.isVisible() 3747 && (canZoomScrollOut() || 3748 mMinZoomScale < mMaxZoomScale)) { 3749 mZoomButtonsController.setVisible(true); 3750 } 3751 } 3752 3753 // do pan 3754 int newScrollX = pinLocX(mScrollX + deltaX); 3755 deltaX = newScrollX - mScrollX; 3756 int newScrollY = pinLocY(mScrollY + deltaY); 3757 deltaY = newScrollY - mScrollY; 3758 boolean done = false; 3759 if (deltaX == 0 && deltaY == 0) { 3760 done = true; 3761 } else { 3762 if (mSnapScrollMode == SNAP_X || mSnapScrollMode == SNAP_Y) { 3763 int ax = Math.abs(deltaX); 3764 int ay = Math.abs(deltaY); 3765 if (mSnapScrollMode == SNAP_X) { 3766 // radical change means getting out of snap mode 3767 if (ay > MAX_SLOPE_FOR_DIAG * ax 3768 && ay > MIN_BREAK_SNAP_CROSS_DISTANCE) { 3769 mSnapScrollMode = SNAP_NONE; 3770 } 3771 // reverse direction means lock in the snap mode 3772 if ((ax > MAX_SLOPE_FOR_DIAG * ay) && 3773 ((mSnapPositive && 3774 deltaX < -mMinLockSnapReverseDistance) 3775 || (!mSnapPositive && 3776 deltaX > mMinLockSnapReverseDistance))) { 3777 mSnapScrollMode = SNAP_X_LOCK; 3778 } 3779 } else { 3780 // radical change means getting out of snap mode 3781 if ((ax > MAX_SLOPE_FOR_DIAG * ay) 3782 && ax > MIN_BREAK_SNAP_CROSS_DISTANCE) { 3783 mSnapScrollMode = SNAP_NONE; 3784 } 3785 // reverse direction means lock in the snap mode 3786 if ((ay > MAX_SLOPE_FOR_DIAG * ax) && 3787 ((mSnapPositive && 3788 deltaY < -mMinLockSnapReverseDistance) 3789 || (!mSnapPositive && 3790 deltaY > mMinLockSnapReverseDistance))) { 3791 mSnapScrollMode = SNAP_Y_LOCK; 3792 } 3793 } 3794 } 3795 3796 if (mSnapScrollMode == SNAP_X 3797 || mSnapScrollMode == SNAP_X_LOCK) { 3798 scrollBy(deltaX, 0); 3799 mLastTouchX = x; 3800 } else if (mSnapScrollMode == SNAP_Y 3801 || mSnapScrollMode == SNAP_Y_LOCK) { 3802 scrollBy(0, deltaY); 3803 mLastTouchY = y; 3804 } else { 3805 scrollBy(deltaX, deltaY); 3806 mLastTouchX = x; 3807 mLastTouchY = y; 3808 } 3809 mLastTouchTime = eventTime; 3810 mUserScroll = true; 3811 } 3812 3813 if (!getSettings().getBuiltInZoomControls()) { 3814 boolean showPlusMinus = mMinZoomScale < mMaxZoomScale; 3815 boolean showMagnify = canZoomScrollOut(); 3816 if (mZoomControls != null && (showPlusMinus || showMagnify)) { 3817 if (mZoomControls.getVisibility() == View.VISIBLE) { 3818 mPrivateHandler.removeCallbacks(mZoomControlRunnable); 3819 } else { 3820 mZoomControls.show(showPlusMinus, showMagnify); 3821 } 3822 mPrivateHandler.postDelayed(mZoomControlRunnable, 3823 ZOOM_CONTROLS_TIMEOUT); 3824 } 3825 } 3826 3827 if (done) { 3828 // return false to indicate that we can't pan out of the 3829 // view space 3830 return false; 3831 } 3832 break; 3833 } 3834 case MotionEvent.ACTION_UP: { 3835 mLastTouchUpTime = eventTime; 3836 switch (mTouchMode) { 3837 case TOUCH_INIT_MODE: // tap 3838 case TOUCH_SHORTPRESS_START_MODE: 3839 case TOUCH_SHORTPRESS_MODE: 3840 mPrivateHandler.removeMessages(SWITCH_TO_SHORTPRESS); 3841 mPrivateHandler.removeMessages(SWITCH_TO_LONGPRESS); 3842 mTouchMode = TOUCH_DONE_MODE; 3843 doShortPress(); 3844 break; 3845 case TOUCH_SELECT_MODE: 3846 commitCopy(); 3847 mTouchSelection = false; 3848 break; 3849 case SCROLL_ZOOM_ANIMATION_IN: 3850 case SCROLL_ZOOM_ANIMATION_OUT: 3851 // no action during scroll animation 3852 break; 3853 case SCROLL_ZOOM_OUT: 3854 if (DebugFlags.WEB_VIEW) { 3855 Log.v(LOGTAG, "ACTION_UP SCROLL_ZOOM_OUT" 3856 + " eventTime - mLastTouchTime=" 3857 + (eventTime - mLastTouchTime)); 3858 } 3859 // for now, always zoom back when the drag completes 3860 if (true || eventTime - mLastTouchTime < TAP_TIMEOUT) { 3861 // but if we tap, zoom in where we tap 3862 if (eventTime - mLastTouchTime < TAP_TIMEOUT) { 3863 zoomScrollTap(x, y); 3864 } 3865 // start zooming in back to the original view 3866 setZoomScrollIn(); 3867 mTouchMode = SCROLL_ZOOM_ANIMATION_IN; 3868 invalidate(); 3869 } 3870 break; 3871 case TOUCH_DRAG_MODE: 3872 // if the user waits a while w/o moving before the 3873 // up, we don't want to do a fling 3874 if (eventTime - mLastTouchTime <= MIN_FLING_TIME) { 3875 mVelocityTracker.addMovement(ev); 3876 doFling(); 3877 break; 3878 } 3879 WebViewCore.resumeUpdate(mWebViewCore); 3880 break; 3881 case TOUCH_DRAG_START_MODE: 3882 case TOUCH_DONE_MODE: 3883 // do nothing 3884 break; 3885 } 3886 // we also use mVelocityTracker == null to tell us that we are 3887 // not "moving around", so we can take the slower/prettier 3888 // mode in the drawing code 3889 if (mVelocityTracker != null) { 3890 mVelocityTracker.recycle(); 3891 mVelocityTracker = null; 3892 } 3893 break; 3894 } 3895 case MotionEvent.ACTION_CANCEL: { 3896 // we also use mVelocityTracker == null to tell us that we are 3897 // not "moving around", so we can take the slower/prettier 3898 // mode in the drawing code 3899 if (mVelocityTracker != null) { 3900 mVelocityTracker.recycle(); 3901 mVelocityTracker = null; 3902 } 3903 if (mTouchMode == SCROLL_ZOOM_OUT || 3904 mTouchMode == SCROLL_ZOOM_ANIMATION_IN) { 3905 scrollTo(mZoomScrollX, mZoomScrollY); 3906 } else if (mTouchMode == TOUCH_DRAG_MODE) { 3907 WebViewCore.resumeUpdate(mWebViewCore); 3908 } 3909 mPrivateHandler.removeMessages(SWITCH_TO_SHORTPRESS); 3910 mPrivateHandler.removeMessages(SWITCH_TO_LONGPRESS); 3911 mTouchMode = TOUCH_DONE_MODE; 3912 nativeHideCursor(); 3913 break; 3914 } 3915 } 3916 return true; 3917 } 3918 3919 private long mTrackballFirstTime = 0; 3920 private long mTrackballLastTime = 0; 3921 private float mTrackballRemainsX = 0.0f; 3922 private float mTrackballRemainsY = 0.0f; 3923 private int mTrackballXMove = 0; 3924 private int mTrackballYMove = 0; 3925 private boolean mExtendSelection = false; 3926 private boolean mTouchSelection = false; 3927 private static final int TRACKBALL_KEY_TIMEOUT = 1000; 3928 private static final int TRACKBALL_TIMEOUT = 200; 3929 private static final int TRACKBALL_WAIT = 100; 3930 private static final int TRACKBALL_SCALE = 400; 3931 private static final int TRACKBALL_SCROLL_COUNT = 5; 3932 private static final int TRACKBALL_MOVE_COUNT = 10; 3933 private static final int TRACKBALL_MULTIPLIER = 3; 3934 private static final int SELECT_CURSOR_OFFSET = 16; 3935 private int mSelectX = 0; 3936 private int mSelectY = 0; 3937 private boolean mShiftIsPressed = false; 3938 private boolean mTrackballDown = false; 3939 private long mTrackballUpTime = 0; 3940 private long mLastCursorTime = 0; 3941 private Rect mLastCursorBounds; 3942 3943 // Set by default; BrowserActivity clears to interpret trackball data 3944 // directly for movement. Currently, the framework only passes 3945 // arrow key events, not trackball events, from one child to the next 3946 private boolean mMapTrackballToArrowKeys = true; 3947 3948 public void setMapTrackballToArrowKeys(boolean setMap) { 3949 mMapTrackballToArrowKeys = setMap; 3950 } 3951 3952 void resetTrackballTime() { 3953 mTrackballLastTime = 0; 3954 } 3955 3956 @Override 3957 public boolean onTrackballEvent(MotionEvent ev) { 3958 long time = ev.getEventTime(); 3959 if ((ev.getMetaState() & KeyEvent.META_ALT_ON) != 0) { 3960 if (ev.getY() > 0) pageDown(true); 3961 if (ev.getY() < 0) pageUp(true); 3962 return true; 3963 } 3964 if (ev.getAction() == MotionEvent.ACTION_DOWN) { 3965 mPrivateHandler.removeMessages(SWITCH_TO_CLICK); 3966 mTrackballDown = true; 3967 if (mNativeClass != 0) { 3968 nativeRecordButtons(hasFocus() && hasWindowFocus(), true, true); 3969 } 3970 if (time - mLastCursorTime <= TRACKBALL_TIMEOUT 3971 && !mLastCursorBounds.equals(nativeGetCursorRingBounds())) { 3972 nativeSelectBestAt(mLastCursorBounds); 3973 } 3974 if (DebugFlags.WEB_VIEW) { 3975 Log.v(LOGTAG, "onTrackballEvent down ev=" + ev 3976 + " time=" + time 3977 + " mLastCursorTime=" + mLastCursorTime); 3978 } 3979 if (isInTouchMode()) requestFocusFromTouch(); 3980 return false; // let common code in onKeyDown at it 3981 } 3982 if (ev.getAction() == MotionEvent.ACTION_UP) { 3983 // LONG_PRESS_CENTER is set in common onKeyDown 3984 mPrivateHandler.removeMessages(LONG_PRESS_CENTER); 3985 mTrackballDown = false; 3986 mTrackballUpTime = time; 3987 if (mShiftIsPressed) { 3988 if (mExtendSelection) { 3989 commitCopy(); 3990 } else { 3991 mExtendSelection = true; 3992 } 3993 } 3994 if (DebugFlags.WEB_VIEW) { 3995 Log.v(LOGTAG, "onTrackballEvent up ev=" + ev 3996 + " time=" + time 3997 ); 3998 } 3999 return false; // let common code in onKeyUp at it 4000 } 4001 if (mMapTrackballToArrowKeys && mShiftIsPressed == false) { 4002 if (DebugFlags.WEB_VIEW) Log.v(LOGTAG, "onTrackballEvent gmail quit"); 4003 return false; 4004 } 4005 // no move if we're still waiting on SWITCH_TO_CLICK timeout 4006 if (mTouchMode == TOUCH_DOUBLECLICK_MODE) { 4007 if (DebugFlags.WEB_VIEW) Log.v(LOGTAG, "onTrackballEvent 2 click quit"); 4008 return true; 4009 } 4010 if (mTrackballDown) { 4011 if (DebugFlags.WEB_VIEW) Log.v(LOGTAG, "onTrackballEvent down quit"); 4012 return true; // discard move if trackball is down 4013 } 4014 if (time - mTrackballUpTime < TRACKBALL_TIMEOUT) { 4015 if (DebugFlags.WEB_VIEW) Log.v(LOGTAG, "onTrackballEvent up timeout quit"); 4016 return true; 4017 } 4018 // TODO: alternatively we can do panning as touch does 4019 switchOutDrawHistory(); 4020 if (time - mTrackballLastTime > TRACKBALL_TIMEOUT) { 4021 if (DebugFlags.WEB_VIEW) { 4022 Log.v(LOGTAG, "onTrackballEvent time=" 4023 + time + " last=" + mTrackballLastTime); 4024 } 4025 mTrackballFirstTime = time; 4026 mTrackballXMove = mTrackballYMove = 0; 4027 } 4028 mTrackballLastTime = time; 4029 if (DebugFlags.WEB_VIEW) { 4030 Log.v(LOGTAG, "onTrackballEvent ev=" + ev + " time=" + time); 4031 } 4032 mTrackballRemainsX += ev.getX(); 4033 mTrackballRemainsY += ev.getY(); 4034 doTrackball(time); 4035 return true; 4036 } 4037 4038 void moveSelection(float xRate, float yRate) { 4039 if (mNativeClass == 0) 4040 return; 4041 int width = getViewWidth(); 4042 int height = getViewHeight(); 4043 mSelectX += scaleTrackballX(xRate, width); 4044 mSelectY += scaleTrackballY(yRate, height); 4045 int maxX = width + mScrollX; 4046 int maxY = height + mScrollY; 4047 mSelectX = Math.min(maxX, Math.max(mScrollX - SELECT_CURSOR_OFFSET 4048 , mSelectX)); 4049 mSelectY = Math.min(maxY, Math.max(mScrollY - SELECT_CURSOR_OFFSET 4050 , mSelectY)); 4051 if (DebugFlags.WEB_VIEW) { 4052 Log.v(LOGTAG, "moveSelection" 4053 + " mSelectX=" + mSelectX 4054 + " mSelectY=" + mSelectY 4055 + " mScrollX=" + mScrollX 4056 + " mScrollY=" + mScrollY 4057 + " xRate=" + xRate 4058 + " yRate=" + yRate 4059 ); 4060 } 4061 nativeMoveSelection(viewToContent(mSelectX) 4062 , viewToContent(mSelectY), mExtendSelection); 4063 int scrollX = mSelectX < mScrollX ? -SELECT_CURSOR_OFFSET 4064 : mSelectX > maxX - SELECT_CURSOR_OFFSET ? SELECT_CURSOR_OFFSET 4065 : 0; 4066 int scrollY = mSelectY < mScrollY ? -SELECT_CURSOR_OFFSET 4067 : mSelectY > maxY - SELECT_CURSOR_OFFSET ? SELECT_CURSOR_OFFSET 4068 : 0; 4069 pinScrollBy(scrollX, scrollY, true, 0); 4070 Rect select = new Rect(mSelectX, mSelectY, mSelectX + 1, mSelectY + 1); 4071 requestRectangleOnScreen(select); 4072 invalidate(); 4073 } 4074 4075 private int scaleTrackballX(float xRate, int width) { 4076 int xMove = (int) (xRate / TRACKBALL_SCALE * width); 4077 int nextXMove = xMove; 4078 if (xMove > 0) { 4079 if (xMove > mTrackballXMove) { 4080 xMove -= mTrackballXMove; 4081 } 4082 } else if (xMove < mTrackballXMove) { 4083 xMove -= mTrackballXMove; 4084 } 4085 mTrackballXMove = nextXMove; 4086 return xMove; 4087 } 4088 4089 private int scaleTrackballY(float yRate, int height) { 4090 int yMove = (int) (yRate / TRACKBALL_SCALE * height); 4091 int nextYMove = yMove; 4092 if (yMove > 0) { 4093 if (yMove > mTrackballYMove) { 4094 yMove -= mTrackballYMove; 4095 } 4096 } else if (yMove < mTrackballYMove) { 4097 yMove -= mTrackballYMove; 4098 } 4099 mTrackballYMove = nextYMove; 4100 return yMove; 4101 } 4102 4103 private int keyCodeToSoundsEffect(int keyCode) { 4104 switch(keyCode) { 4105 case KeyEvent.KEYCODE_DPAD_UP: 4106 return SoundEffectConstants.NAVIGATION_UP; 4107 case KeyEvent.KEYCODE_DPAD_RIGHT: 4108 return SoundEffectConstants.NAVIGATION_RIGHT; 4109 case KeyEvent.KEYCODE_DPAD_DOWN: 4110 return SoundEffectConstants.NAVIGATION_DOWN; 4111 case KeyEvent.KEYCODE_DPAD_LEFT: 4112 return SoundEffectConstants.NAVIGATION_LEFT; 4113 } 4114 throw new IllegalArgumentException("keyCode must be one of " + 4115 "{KEYCODE_DPAD_UP, KEYCODE_DPAD_RIGHT, KEYCODE_DPAD_DOWN, " + 4116 "KEYCODE_DPAD_LEFT}."); 4117 } 4118 4119 private void doTrackball(long time) { 4120 int elapsed = (int) (mTrackballLastTime - mTrackballFirstTime); 4121 if (elapsed == 0) { 4122 elapsed = TRACKBALL_TIMEOUT; 4123 } 4124 float xRate = mTrackballRemainsX * 1000 / elapsed; 4125 float yRate = mTrackballRemainsY * 1000 / elapsed; 4126 if (mShiftIsPressed) { 4127 moveSelection(xRate, yRate); 4128 mTrackballRemainsX = mTrackballRemainsY = 0; 4129 return; 4130 } 4131 float ax = Math.abs(xRate); 4132 float ay = Math.abs(yRate); 4133 float maxA = Math.max(ax, ay); 4134 if (DebugFlags.WEB_VIEW) { 4135 Log.v(LOGTAG, "doTrackball elapsed=" + elapsed 4136 + " xRate=" + xRate 4137 + " yRate=" + yRate 4138 + " mTrackballRemainsX=" + mTrackballRemainsX 4139 + " mTrackballRemainsY=" + mTrackballRemainsY); 4140 } 4141 int width = mContentWidth - getViewWidth(); 4142 int height = mContentHeight - getViewHeight(); 4143 if (width < 0) width = 0; 4144 if (height < 0) height = 0; 4145 if (mTouchMode == SCROLL_ZOOM_OUT) { 4146 int oldX = mZoomScrollX; 4147 int oldY = mZoomScrollY; 4148 int maxWH = Math.max(width, height); 4149 mZoomScrollX += scaleTrackballX(xRate, maxWH); 4150 mZoomScrollY += scaleTrackballY(yRate, maxWH); 4151 if (DebugFlags.WEB_VIEW) { 4152 Log.v(LOGTAG, "doTrackball SCROLL_ZOOM_OUT" 4153 + " mZoomScrollX=" + mZoomScrollX 4154 + " mZoomScrollY=" + mZoomScrollY); 4155 } 4156 mZoomScrollX = Math.min(width, Math.max(0, mZoomScrollX)); 4157 mZoomScrollY = Math.min(height, Math.max(0, mZoomScrollY)); 4158 if (oldX != mZoomScrollX || oldY != mZoomScrollY) { 4159 invalidate(); 4160 } 4161 mTrackballRemainsX = mTrackballRemainsY = 0; 4162 return; 4163 } 4164 ax = Math.abs(mTrackballRemainsX * TRACKBALL_MULTIPLIER); 4165 ay = Math.abs(mTrackballRemainsY * TRACKBALL_MULTIPLIER); 4166 maxA = Math.max(ax, ay); 4167 int count = Math.max(0, (int) maxA); 4168 int oldScrollX = mScrollX; 4169 int oldScrollY = mScrollY; 4170 if (count > 0) { 4171 int selectKeyCode = ax < ay ? mTrackballRemainsY < 0 ? 4172 KeyEvent.KEYCODE_DPAD_UP : KeyEvent.KEYCODE_DPAD_DOWN : 4173 mTrackballRemainsX < 0 ? KeyEvent.KEYCODE_DPAD_LEFT : 4174 KeyEvent.KEYCODE_DPAD_RIGHT; 4175 count = Math.min(count, TRACKBALL_MOVE_COUNT); 4176 if (DebugFlags.WEB_VIEW) { 4177 Log.v(LOGTAG, "doTrackball keyCode=" + selectKeyCode 4178 + " count=" + count 4179 + " mTrackballRemainsX=" + mTrackballRemainsX 4180 + " mTrackballRemainsY=" + mTrackballRemainsY); 4181 } 4182 if (navHandledKey(selectKeyCode, count, false, time)) { 4183 playSoundEffect(keyCodeToSoundsEffect(selectKeyCode)); 4184 } 4185 mTrackballRemainsX = mTrackballRemainsY = 0; 4186 } 4187 if (count >= TRACKBALL_SCROLL_COUNT) { 4188 int xMove = scaleTrackballX(xRate, width); 4189 int yMove = scaleTrackballY(yRate, height); 4190 if (DebugFlags.WEB_VIEW) { 4191 Log.v(LOGTAG, "doTrackball pinScrollBy" 4192 + " count=" + count 4193 + " xMove=" + xMove + " yMove=" + yMove 4194 + " mScrollX-oldScrollX=" + (mScrollX-oldScrollX) 4195 + " mScrollY-oldScrollY=" + (mScrollY-oldScrollY) 4196 ); 4197 } 4198 if (Math.abs(mScrollX - oldScrollX) > Math.abs(xMove)) { 4199 xMove = 0; 4200 } 4201 if (Math.abs(mScrollY - oldScrollY) > Math.abs(yMove)) { 4202 yMove = 0; 4203 } 4204 if (xMove != 0 || yMove != 0) { 4205 pinScrollBy(xMove, yMove, true, 0); 4206 } 4207 mUserScroll = true; 4208 } 4209 } 4210 4211 public void flingScroll(int vx, int vy) { 4212 int maxX = Math.max(computeHorizontalScrollRange() - getViewWidth(), 0); 4213 int maxY = Math.max(computeVerticalScrollRange() - getViewHeight(), 0); 4214 4215 mScroller.fling(mScrollX, mScrollY, vx, vy, 0, maxX, 0, maxY); 4216 invalidate(); 4217 } 4218 4219 private void doFling() { 4220 if (mVelocityTracker == null) { 4221 return; 4222 } 4223 int maxX = Math.max(computeHorizontalScrollRange() - getViewWidth(), 0); 4224 int maxY = Math.max(computeVerticalScrollRange() - getViewHeight(), 0); 4225 4226 mVelocityTracker.computeCurrentVelocity(1000); 4227 int vx = (int) mVelocityTracker.getXVelocity(); 4228 int vy = (int) mVelocityTracker.getYVelocity(); 4229 4230 if (mSnapScrollMode != SNAP_NONE) { 4231 if (mSnapScrollMode == SNAP_X || mSnapScrollMode == SNAP_X_LOCK) { 4232 vy = 0; 4233 } else { 4234 vx = 0; 4235 } 4236 } 4237 4238 if (true /* EMG release: make our fling more like Maps' */) { 4239 // maps cuts their velocity in half 4240 vx = vx * 3 / 4; 4241 vy = vy * 3 / 4; 4242 } 4243 4244 mScroller.fling(mScrollX, mScrollY, -vx, -vy, 0, maxX, 0, maxY); 4245 // TODO: duration is calculated based on velocity, if the range is 4246 // small, the animation will stop before duration is up. We may 4247 // want to calculate how long the animation is going to run to precisely 4248 // resume the webcore update. 4249 final int time = mScroller.getDuration(); 4250 mPrivateHandler.sendEmptyMessageDelayed(RESUME_WEBCORE_UPDATE, time); 4251 invalidate(); 4252 } 4253 4254 private boolean zoomWithPreview(float scale) { 4255 float oldScale = mActualScale; 4256 4257 // snap to DEFAULT_SCALE if it is close 4258 if (scale > (mDefaultScale - 0.05) && scale < (mDefaultScale + 0.05)) { 4259 scale = mDefaultScale; 4260 } 4261 4262 setNewZoomScale(scale, false); 4263 4264 if (oldScale != mActualScale) { 4265 // use mZoomPickerScale to see zoom preview first 4266 mZoomStart = SystemClock.uptimeMillis(); 4267 mInvInitialZoomScale = 1.0f / oldScale; 4268 mInvFinalZoomScale = 1.0f / mActualScale; 4269 mZoomScale = mActualScale; 4270 invalidate(); 4271 return true; 4272 } else { 4273 return false; 4274 } 4275 } 4276 4277 /** 4278 * Returns a view containing zoom controls i.e. +/- buttons. The caller is 4279 * in charge of installing this view to the view hierarchy. This view will 4280 * become visible when the user starts scrolling via touch and fade away if 4281 * the user does not interact with it. 4282 * <p/> 4283 * API version 3 introduces a built-in zoom mechanism that is shown 4284 * automatically by the MapView. This is the preferred approach for 4285 * showing the zoom UI. 4286 * 4287 * @deprecated The built-in zoom mechanism is preferred, see 4288 * {@link WebSettings#setBuiltInZoomControls(boolean)}. 4289 */ 4290 @Deprecated 4291 public View getZoomControls() { 4292 if (!getSettings().supportZoom()) { 4293 Log.w(LOGTAG, "This WebView doesn't support zoom."); 4294 return null; 4295 } 4296 if (mZoomControls == null) { 4297 mZoomControls = createZoomControls(); 4298 4299 /* 4300 * need to be set to VISIBLE first so that getMeasuredHeight() in 4301 * {@link #onSizeChanged()} can return the measured value for proper 4302 * layout. 4303 */ 4304 mZoomControls.setVisibility(View.VISIBLE); 4305 mZoomControlRunnable = new Runnable() { 4306 public void run() { 4307 4308 /* Don't dismiss the controls if the user has 4309 * focus on them. Wait and check again later. 4310 */ 4311 if (!mZoomControls.hasFocus()) { 4312 mZoomControls.hide(); 4313 } else { 4314 mPrivateHandler.removeCallbacks(mZoomControlRunnable); 4315 mPrivateHandler.postDelayed(mZoomControlRunnable, 4316 ZOOM_CONTROLS_TIMEOUT); 4317 } 4318 } 4319 }; 4320 } 4321 return mZoomControls; 4322 } 4323 4324 private ExtendedZoomControls createZoomControls() { 4325 ExtendedZoomControls zoomControls = new ExtendedZoomControls(mContext 4326 , null); 4327 zoomControls.setOnZoomInClickListener(new OnClickListener() { 4328 public void onClick(View v) { 4329 // reset time out 4330 mPrivateHandler.removeCallbacks(mZoomControlRunnable); 4331 mPrivateHandler.postDelayed(mZoomControlRunnable, 4332 ZOOM_CONTROLS_TIMEOUT); 4333 zoomIn(); 4334 } 4335 }); 4336 zoomControls.setOnZoomOutClickListener(new OnClickListener() { 4337 public void onClick(View v) { 4338 // reset time out 4339 mPrivateHandler.removeCallbacks(mZoomControlRunnable); 4340 mPrivateHandler.postDelayed(mZoomControlRunnable, 4341 ZOOM_CONTROLS_TIMEOUT); 4342 zoomOut(); 4343 } 4344 }); 4345 zoomControls.setOnZoomMagnifyClickListener(new OnClickListener() { 4346 public void onClick(View v) { 4347 mPrivateHandler.removeCallbacks(mZoomControlRunnable); 4348 mPrivateHandler.postDelayed(mZoomControlRunnable, 4349 ZOOM_CONTROLS_TIMEOUT); 4350 zoomScrollOut(); 4351 } 4352 }); 4353 return zoomControls; 4354 } 4355 4356 /** 4357 * Gets the {@link ZoomButtonsController} which can be used to add 4358 * additional buttons to the zoom controls window. 4359 * 4360 * @return The instance of {@link ZoomButtonsController} used by this class, 4361 * or null if it is unavailable. 4362 * @hide 4363 */ 4364 public ZoomButtonsController getZoomButtonsController() { 4365 return mZoomButtonsController; 4366 } 4367 4368 /** 4369 * Perform zoom in in the webview 4370 * @return TRUE if zoom in succeeds. FALSE if no zoom changes. 4371 */ 4372 public boolean zoomIn() { 4373 // TODO: alternatively we can disallow this during draw history mode 4374 switchOutDrawHistory(); 4375 return zoomWithPreview(mActualScale * 1.25f); 4376 } 4377 4378 /** 4379 * Perform zoom out in the webview 4380 * @return TRUE if zoom out succeeds. FALSE if no zoom changes. 4381 */ 4382 public boolean zoomOut() { 4383 // TODO: alternatively we can disallow this during draw history mode 4384 switchOutDrawHistory(); 4385 return zoomWithPreview(mActualScale * 0.8f); 4386 } 4387 4388 private void updateSelection() { 4389 if (mNativeClass == 0) { 4390 return; 4391 } 4392 // mLastTouchX and mLastTouchY are the point in the current viewport 4393 int contentX = viewToContent((int) mLastTouchX + mScrollX); 4394 int contentY = viewToContent((int) mLastTouchY + mScrollY); 4395 Rect rect = new Rect(contentX - mNavSlop, contentY - mNavSlop, 4396 contentX + mNavSlop, contentY + mNavSlop); 4397 nativeSelectBestAt(rect); 4398 } 4399 4400 /*package*/ void shortPressOnTextField() { 4401 if (inEditingMode()) { 4402 View v = mWebTextView; 4403 int x = viewToContent((v.getLeft() + v.getRight()) >> 1); 4404 int y = viewToContent((v.getTop() + v.getBottom()) >> 1); 4405 nativeMotionUp(x, y, mNavSlop); 4406 } 4407 } 4408 4409 private void doShortPress() { 4410 if (mNativeClass == 0) { 4411 return; 4412 } 4413 switchOutDrawHistory(); 4414 // mLastTouchX and mLastTouchY are the point in the current viewport 4415 int contentX = viewToContent((int) mLastTouchX + mScrollX); 4416 int contentY = viewToContent((int) mLastTouchY + mScrollY); 4417 if (nativeMotionUp(contentX, contentY, mNavSlop)) { 4418 if (mLogEvent) { 4419 Checkin.updateStats(mContext.getContentResolver(), 4420 Checkin.Stats.Tag.BROWSER_SNAP_CENTER, 1, 0.0); 4421 } 4422 } 4423 if (nativeHasCursorNode() && !nativeCursorIsTextInput()) { 4424 playSoundEffect(SoundEffectConstants.CLICK); 4425 } 4426 } 4427 4428 // Called by JNI to handle a touch on a node representing an email address, 4429 // address, or phone number 4430 private void overrideLoading(String url) { 4431 mCallbackProxy.uiOverrideUrlLoading(url); 4432 } 4433 4434 @Override 4435 public boolean requestFocus(int direction, Rect previouslyFocusedRect) { 4436 boolean result = false; 4437 if (inEditingMode()) { 4438 result = mWebTextView.requestFocus(direction, 4439 previouslyFocusedRect); 4440 } else { 4441 result = super.requestFocus(direction, previouslyFocusedRect); 4442 if (mWebViewCore.getSettings().getNeedInitialFocus()) { 4443 // For cases such as GMail, where we gain focus from a direction, 4444 // we want to move to the first available link. 4445 // FIXME: If there are no visible links, we may not want to 4446 int fakeKeyDirection = 0; 4447 switch(direction) { 4448 case View.FOCUS_UP: 4449 fakeKeyDirection = KeyEvent.KEYCODE_DPAD_UP; 4450 break; 4451 case View.FOCUS_DOWN: 4452 fakeKeyDirection = KeyEvent.KEYCODE_DPAD_DOWN; 4453 break; 4454 case View.FOCUS_LEFT: 4455 fakeKeyDirection = KeyEvent.KEYCODE_DPAD_LEFT; 4456 break; 4457 case View.FOCUS_RIGHT: 4458 fakeKeyDirection = KeyEvent.KEYCODE_DPAD_RIGHT; 4459 break; 4460 default: 4461 return result; 4462 } 4463 if (mNativeClass != 0 && !nativeHasCursorNode()) { 4464 navHandledKey(fakeKeyDirection, 1, true, 0); 4465 } 4466 } 4467 } 4468 return result; 4469 } 4470 4471 @Override 4472 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 4473 super.onMeasure(widthMeasureSpec, heightMeasureSpec); 4474 4475 int heightMode = MeasureSpec.getMode(heightMeasureSpec); 4476 int heightSize = MeasureSpec.getSize(heightMeasureSpec); 4477 int widthMode = MeasureSpec.getMode(widthMeasureSpec); 4478 int widthSize = MeasureSpec.getSize(widthMeasureSpec); 4479 4480 int measuredHeight = heightSize; 4481 int measuredWidth = widthSize; 4482 4483 // Grab the content size from WebViewCore. 4484 int contentHeight = mContentHeight; 4485 int contentWidth = mContentWidth; 4486 4487// Log.d(LOGTAG, "------- measure " + heightMode); 4488 4489 if (heightMode != MeasureSpec.EXACTLY) { 4490 mHeightCanMeasure = true; 4491 measuredHeight = contentHeight; 4492 if (heightMode == MeasureSpec.AT_MOST) { 4493 // If we are larger than the AT_MOST height, then our height can 4494 // no longer be measured and we should scroll internally. 4495 if (measuredHeight > heightSize) { 4496 measuredHeight = heightSize; 4497 mHeightCanMeasure = false; 4498 } 4499 } 4500 } else { 4501 mHeightCanMeasure = false; 4502 } 4503 if (mNativeClass != 0) { 4504 nativeSetHeightCanMeasure(mHeightCanMeasure); 4505 } 4506 // For the width, always use the given size unless unspecified. 4507 if (widthMode == MeasureSpec.UNSPECIFIED) { 4508 mWidthCanMeasure = true; 4509 measuredWidth = contentWidth; 4510 } else { 4511 mWidthCanMeasure = false; 4512 } 4513 4514 synchronized (this) { 4515 setMeasuredDimension(measuredWidth, measuredHeight); 4516 } 4517 } 4518 4519 @Override 4520 public boolean requestChildRectangleOnScreen(View child, 4521 Rect rect, 4522 boolean immediate) { 4523 rect.offset(child.getLeft() - child.getScrollX(), 4524 child.getTop() - child.getScrollY()); 4525 4526 int height = getHeight() - getHorizontalScrollbarHeight(); 4527 int screenTop = mScrollY; 4528 int screenBottom = screenTop + height; 4529 4530 int scrollYDelta = 0; 4531 4532 if (rect.bottom > screenBottom) { 4533 int oneThirdOfScreenHeight = height / 3; 4534 if (rect.height() > 2 * oneThirdOfScreenHeight) { 4535 // If the rectangle is too tall to fit in the bottom two thirds 4536 // of the screen, place it at the top. 4537 scrollYDelta = rect.top - screenTop; 4538 } else { 4539 // If the rectangle will still fit on screen, we want its 4540 // top to be in the top third of the screen. 4541 scrollYDelta = rect.top - (screenTop + oneThirdOfScreenHeight); 4542 } 4543 } else if (rect.top < screenTop) { 4544 scrollYDelta = rect.top - screenTop; 4545 } 4546 4547 int width = getWidth() - getVerticalScrollbarWidth(); 4548 int screenLeft = mScrollX; 4549 int screenRight = screenLeft + width; 4550 4551 int scrollXDelta = 0; 4552 4553 if (rect.right > screenRight && rect.left > screenLeft) { 4554 if (rect.width() > width) { 4555 scrollXDelta += (rect.left - screenLeft); 4556 } else { 4557 scrollXDelta += (rect.right - screenRight); 4558 } 4559 } else if (rect.left < screenLeft) { 4560 scrollXDelta -= (screenLeft - rect.left); 4561 } 4562 4563 if ((scrollYDelta | scrollXDelta) != 0) { 4564 return pinScrollBy(scrollXDelta, scrollYDelta, !immediate, 0); 4565 } 4566 4567 return false; 4568 } 4569 4570 /* package */ void replaceTextfieldText(int oldStart, int oldEnd, 4571 String replace, int newStart, int newEnd) { 4572 WebViewCore.ReplaceTextData arg = new WebViewCore.ReplaceTextData(); 4573 arg.mReplace = replace; 4574 arg.mNewStart = newStart; 4575 arg.mNewEnd = newEnd; 4576 mTextGeneration++; 4577 mWebViewCore.sendMessage(EventHub.REPLACE_TEXT, oldStart, oldEnd, arg); 4578 } 4579 4580 /* package */ void passToJavaScript(String currentText, KeyEvent event) { 4581 if (nativeCursorWantsKeyEvents() && !nativeCursorMatchesFocus()) { 4582 mWebViewCore.sendMessage(EventHub.CLICK); 4583 } 4584 WebViewCore.JSKeyData arg = new WebViewCore.JSKeyData(); 4585 arg.mEvent = event; 4586 arg.mCurrentText = currentText; 4587 // Increase our text generation number, and pass it to webcore thread 4588 mTextGeneration++; 4589 mWebViewCore.sendMessage(EventHub.PASS_TO_JS, mTextGeneration, 0, arg); 4590 // WebKit's document state is not saved until about to leave the page. 4591 // To make sure the host application, like Browser, has the up to date 4592 // document state when it goes to background, we force to save the 4593 // document state. 4594 mWebViewCore.removeMessages(EventHub.SAVE_DOCUMENT_STATE); 4595 mWebViewCore.sendMessageDelayed(EventHub.SAVE_DOCUMENT_STATE, 4596 cursorData(), 1000); 4597 } 4598 4599 /* package */ WebViewCore getWebViewCore() { 4600 return mWebViewCore; 4601 } 4602 4603 //------------------------------------------------------------------------- 4604 // Methods can be called from a separate thread, like WebViewCore 4605 // If it needs to call the View system, it has to send message. 4606 //------------------------------------------------------------------------- 4607 4608 /** 4609 * General handler to receive message coming from webkit thread 4610 */ 4611 class PrivateHandler extends Handler { 4612 @Override 4613 public void handleMessage(Message msg) { 4614 if (DebugFlags.WEB_VIEW) { 4615 Log.v(LOGTAG, msg.what < REMEMBER_PASSWORD || msg.what 4616 > INVAL_RECT_MSG_ID ? Integer.toString(msg.what) 4617 : HandlerDebugString[msg.what - REMEMBER_PASSWORD]); 4618 } 4619 switch (msg.what) { 4620 case REMEMBER_PASSWORD: { 4621 mDatabase.setUsernamePassword( 4622 msg.getData().getString("host"), 4623 msg.getData().getString("username"), 4624 msg.getData().getString("password")); 4625 ((Message) msg.obj).sendToTarget(); 4626 break; 4627 } 4628 case NEVER_REMEMBER_PASSWORD: { 4629 mDatabase.setUsernamePassword( 4630 msg.getData().getString("host"), null, null); 4631 ((Message) msg.obj).sendToTarget(); 4632 break; 4633 } 4634 case SWITCH_TO_SHORTPRESS: { 4635 if (mTouchMode == TOUCH_INIT_MODE) { 4636 mTouchMode = TOUCH_SHORTPRESS_START_MODE; 4637 updateSelection(); 4638 } 4639 break; 4640 } 4641 case SWITCH_TO_LONGPRESS: { 4642 if (!mPreventDrag) { 4643 mTouchMode = TOUCH_DONE_MODE; 4644 performLongClick(); 4645 rebuildWebTextView(); 4646 } 4647 break; 4648 } 4649 case SWITCH_TO_CLICK: 4650 // The user clicked with the trackball, and did not click a 4651 // second time, so perform the action of a trackball single 4652 // click 4653 mTouchMode = TOUCH_DONE_MODE; 4654 Rect visibleRect = sendOurVisibleRect(); 4655 // Note that sendOurVisibleRect calls viewToContent, so the 4656 // coordinates should be in content coordinates. 4657 if (!nativeCursorIntersects(visibleRect)) { 4658 break; 4659 } 4660 nativeSetFollowedLink(true); 4661 mWebViewCore.sendMessage(EventHub.SET_MOVE_MOUSE, 4662 cursorData()); 4663 playSoundEffect(SoundEffectConstants.CLICK); 4664 boolean isTextInput = nativeCursorIsTextInput(); 4665 if (isTextInput || !mCallbackProxy.uiOverrideUrlLoading( 4666 nativeCursorText())) { 4667 mWebViewCore.sendMessage(EventHub.CLICK); 4668 } 4669 if (isTextInput) { 4670 rebuildWebTextView(); 4671 } 4672 break; 4673 case SCROLL_BY_MSG_ID: 4674 setContentScrollBy(msg.arg1, msg.arg2, (Boolean) msg.obj); 4675 break; 4676 case SYNC_SCROLL_TO_MSG_ID: 4677 if (mUserScroll) { 4678 // if user has scrolled explicitly, don't sync the 4679 // scroll position any more 4680 mUserScroll = false; 4681 break; 4682 } 4683 // fall through 4684 case SCROLL_TO_MSG_ID: 4685 if (setContentScrollTo(msg.arg1, msg.arg2)) { 4686 // if we can't scroll to the exact position due to pin, 4687 // send a message to WebCore to re-scroll when we get a 4688 // new picture 4689 mUserScroll = false; 4690 mWebViewCore.sendMessage(EventHub.SYNC_SCROLL, 4691 msg.arg1, msg.arg2); 4692 } 4693 break; 4694 case SPAWN_SCROLL_TO_MSG_ID: 4695 spawnContentScrollTo(msg.arg1, msg.arg2); 4696 break; 4697 case NEW_PICTURE_MSG_ID: 4698 // called for new content 4699 final WebViewCore.DrawData draw = 4700 (WebViewCore.DrawData) msg.obj; 4701 final Point viewSize = draw.mViewPoint; 4702 if (mZoomScale > 0) { 4703 // use the same logic in sendViewSizeZoom() to make sure 4704 // the mZoomScale has matched the viewSize so that we 4705 // can clear mZoomScale 4706 if (Math.round(getViewWidth() / mZoomScale) == viewSize.x) { 4707 mZoomScale = 0; 4708 mWebViewCore.sendMessage(EventHub.SET_SNAP_ANCHOR, 4709 0, 0); 4710 } 4711 } 4712 if (!mMinZoomScaleFixed) { 4713 mMinZoomScale = (float) getViewWidth() 4714 / Math.max(ZOOM_OUT_WIDTH, draw.mWidthHeight.x); 4715 } 4716 // We update the layout (i.e. request a layout from the 4717 // view system) if the last view size that we sent to 4718 // WebCore matches the view size of the picture we just 4719 // received in the fixed dimension. 4720 final boolean updateLayout = viewSize.x == mLastWidthSent 4721 && viewSize.y == mLastHeightSent; 4722 recordNewContentSize(draw.mWidthHeight.x, 4723 draw.mWidthHeight.y, updateLayout); 4724 if (DebugFlags.WEB_VIEW) { 4725 Rect b = draw.mInvalRegion.getBounds(); 4726 Log.v(LOGTAG, "NEW_PICTURE_MSG_ID {" + 4727 b.left+","+b.top+","+b.right+","+b.bottom+"}"); 4728 } 4729 invalidate(contentToView(draw.mInvalRegion.getBounds())); 4730 if (mPictureListener != null) { 4731 mPictureListener.onNewPicture(WebView.this, capturePicture()); 4732 } 4733 break; 4734 case WEBCORE_INITIALIZED_MSG_ID: 4735 // nativeCreate sets mNativeClass to a non-zero value 4736 nativeCreate(msg.arg1); 4737 break; 4738 case UPDATE_TEXTFIELD_TEXT_MSG_ID: 4739 // Make sure that the textfield is currently focused 4740 // and representing the same node as the pointer. 4741 if (inEditingMode() && 4742 mWebTextView.isSameTextField(msg.arg1)) { 4743 if (msg.getData().getBoolean("password")) { 4744 Spannable text = (Spannable) mWebTextView.getText(); 4745 int start = Selection.getSelectionStart(text); 4746 int end = Selection.getSelectionEnd(text); 4747 mWebTextView.setInPassword(true); 4748 // Restore the selection, which may have been 4749 // ruined by setInPassword. 4750 Spannable pword = 4751 (Spannable) mWebTextView.getText(); 4752 Selection.setSelection(pword, start, end); 4753 // If the text entry has created more events, ignore 4754 // this one. 4755 } else if (msg.arg2 == mTextGeneration) { 4756 mWebTextView.setTextAndKeepSelection( 4757 (String) msg.obj); 4758 } 4759 } 4760 break; 4761 case DID_FIRST_LAYOUT_MSG_ID: 4762 if (mNativeClass == 0) { 4763 break; 4764 } 4765 ScaleLimitData scaleLimit = (ScaleLimitData) msg.obj; 4766 int minScale = scaleLimit.mMinScale; 4767 if (minScale == 0) { 4768 mMinZoomScale = DEFAULT_MIN_ZOOM_SCALE; 4769 mMinZoomScaleFixed = false; 4770 } else { 4771 mMinZoomScale = (float) (minScale / 100.0); 4772 mMinZoomScaleFixed = true; 4773 } 4774 int maxScale = scaleLimit.mMaxScale; 4775 if (maxScale == 0) { 4776 mMaxZoomScale = DEFAULT_MAX_ZOOM_SCALE; 4777 } else { 4778 mMaxZoomScale = (float) (maxScale / 100.0); 4779 } 4780 // If history Picture is drawn, don't update zoomWidth 4781 if (mDrawHistory) { 4782 break; 4783 } 4784 int width = getViewWidth(); 4785 if (width == 0) { 4786 break; 4787 } 4788 int initialScale = msg.arg1; 4789 int viewportWidth = msg.arg2; 4790 // start a new page with DEFAULT_SCALE zoom scale. 4791 float scale = mDefaultScale; 4792 if (mInitialScale > 0) { 4793 scale = mInitialScale / 100.0f; 4794 } else { 4795 if (initialScale < 0) break; 4796 if (mWebViewCore.getSettings().getUseWideViewPort()) { 4797 // force viewSizeChanged by setting mLastWidthSent 4798 // to 0 4799 mLastWidthSent = 0; 4800 } 4801 if (initialScale == 0) { 4802 // if viewportWidth is defined and it is smaller 4803 // than the view width, zoom in to fill the view 4804 if (viewportWidth > 0 && viewportWidth < width) { 4805 scale = (float) width / viewportWidth; 4806 } 4807 } else { 4808 scale = initialScale / 100.0f; 4809 } 4810 } 4811 setNewZoomScale(scale, false); 4812 break; 4813 case UPDATE_TEXT_ENTRY_MSG_ID: 4814 // this is sent after finishing resize in WebViewCore. Make 4815 // sure the text edit box is still on the screen. 4816 if (inEditingMode() && nativeCursorIsTextInput()) { 4817 mWebTextView.bringIntoView(); 4818 } 4819 rebuildWebTextView(); 4820 break; 4821 case INVAL_RECT_MSG_ID: { 4822 Rect r = (Rect)msg.obj; 4823 if (r == null) { 4824 invalidate(); 4825 } else { 4826 // we need to scale r from content into view coords, 4827 // which viewInvalidate() does for us 4828 viewInvalidate(r.left, r.top, r.right, r.bottom); 4829 } 4830 break; 4831 } 4832 case REQUEST_FORM_DATA: 4833 AutoCompleteAdapter adapter = (AutoCompleteAdapter) msg.obj; 4834 if (mWebTextView.isSameTextField(msg.arg1)) { 4835 mWebTextView.setAdapterCustom(adapter); 4836 } 4837 break; 4838 case UPDATE_CLIPBOARD: 4839 String str = (String) msg.obj; 4840 if (DebugFlags.WEB_VIEW) { 4841 Log.v(LOGTAG, "UPDATE_CLIPBOARD " + str); 4842 } 4843 try { 4844 IClipboard clip = IClipboard.Stub.asInterface( 4845 ServiceManager.getService("clipboard")); 4846 clip.setClipboardText(str); 4847 } catch (android.os.RemoteException e) { 4848 Log.e(LOGTAG, "Clipboard failed", e); 4849 } 4850 break; 4851 case RESUME_WEBCORE_UPDATE: 4852 WebViewCore.resumeUpdate(mWebViewCore); 4853 break; 4854 4855 case LONG_PRESS_CENTER: 4856 // as this is shared by keydown and trackballdown, reset all 4857 // the states 4858 mGotCenterDown = false; 4859 mTrackballDown = false; 4860 // LONG_PRESS_CENTER is sent as a delayed message. If we 4861 // switch to windows overview, the WebView will be 4862 // temporarily removed from the view system. In that case, 4863 // do nothing. 4864 if (getParent() != null) { 4865 performLongClick(); 4866 } 4867 break; 4868 4869 case WEBCORE_NEED_TOUCH_EVENTS: 4870 mForwardTouchEvents = (msg.arg1 != 0); 4871 break; 4872 4873 case PREVENT_TOUCH_ID: 4874 if (msg.arg1 == MotionEvent.ACTION_DOWN) { 4875 mPreventDrag = msg.arg2 == 1; 4876 if (mPreventDrag) { 4877 mTouchMode = TOUCH_DONE_MODE; 4878 } 4879 } 4880 break; 4881 4882 default: 4883 super.handleMessage(msg); 4884 break; 4885 } 4886 } 4887 } 4888 4889 // Class used to use a dropdown for a <select> element 4890 private class InvokeListBox implements Runnable { 4891 // Whether the listbox allows multiple selection. 4892 private boolean mMultiple; 4893 // Passed in to a list with multiple selection to tell 4894 // which items are selected. 4895 private int[] mSelectedArray; 4896 // Passed in to a list with single selection to tell 4897 // where the initial selection is. 4898 private int mSelection; 4899 4900 private Container[] mContainers; 4901 4902 // Need these to provide stable ids to my ArrayAdapter, 4903 // which normally does not have stable ids. (Bug 1250098) 4904 private class Container extends Object { 4905 String mString; 4906 boolean mEnabled; 4907 int mId; 4908 4909 public String toString() { 4910 return mString; 4911 } 4912 } 4913 4914 /** 4915 * Subclass ArrayAdapter so we can disable OptionGroupLabels, 4916 * and allow filtering. 4917 */ 4918 private class MyArrayListAdapter extends ArrayAdapter<Container> { 4919 public MyArrayListAdapter(Context context, Container[] objects, boolean multiple) { 4920 super(context, 4921 multiple ? com.android.internal.R.layout.select_dialog_multichoice : 4922 com.android.internal.R.layout.select_dialog_singlechoice, 4923 objects); 4924 } 4925 4926 @Override 4927 public boolean hasStableIds() { 4928 // AdapterView's onChanged method uses this to determine whether 4929 // to restore the old state. Return false so that the old (out 4930 // of date) state does not replace the new, valid state. 4931 return false; 4932 } 4933 4934 private Container item(int position) { 4935 if (position < 0 || position >= getCount()) { 4936 return null; 4937 } 4938 return (Container) getItem(position); 4939 } 4940 4941 @Override 4942 public long getItemId(int position) { 4943 Container item = item(position); 4944 if (item == null) { 4945 return -1; 4946 } 4947 return item.mId; 4948 } 4949 4950 @Override 4951 public boolean areAllItemsEnabled() { 4952 return false; 4953 } 4954 4955 @Override 4956 public boolean isEnabled(int position) { 4957 Container item = item(position); 4958 if (item == null) { 4959 return false; 4960 } 4961 return item.mEnabled; 4962 } 4963 } 4964 4965 private InvokeListBox(String[] array, 4966 boolean[] enabled, int[] selected) { 4967 mMultiple = true; 4968 mSelectedArray = selected; 4969 4970 int length = array.length; 4971 mContainers = new Container[length]; 4972 for (int i = 0; i < length; i++) { 4973 mContainers[i] = new Container(); 4974 mContainers[i].mString = array[i]; 4975 mContainers[i].mEnabled = enabled[i]; 4976 mContainers[i].mId = i; 4977 } 4978 } 4979 4980 private InvokeListBox(String[] array, boolean[] enabled, int 4981 selection) { 4982 mSelection = selection; 4983 mMultiple = false; 4984 4985 int length = array.length; 4986 mContainers = new Container[length]; 4987 for (int i = 0; i < length; i++) { 4988 mContainers[i] = new Container(); 4989 mContainers[i].mString = array[i]; 4990 mContainers[i].mEnabled = enabled[i]; 4991 mContainers[i].mId = i; 4992 } 4993 } 4994 4995 /* 4996 * Whenever the data set changes due to filtering, this class ensures 4997 * that the checked item remains checked. 4998 */ 4999 private class SingleDataSetObserver extends DataSetObserver { 5000 private long mCheckedId; 5001 private ListView mListView; 5002 private Adapter mAdapter; 5003 5004 /* 5005 * Create a new observer. 5006 * @param id The ID of the item to keep checked. 5007 * @param l ListView for getting and clearing the checked states 5008 * @param a Adapter for getting the IDs 5009 */ 5010 public SingleDataSetObserver(long id, ListView l, Adapter a) { 5011 mCheckedId = id; 5012 mListView = l; 5013 mAdapter = a; 5014 } 5015 5016 public void onChanged() { 5017 // The filter may have changed which item is checked. Find the 5018 // item that the ListView thinks is checked. 5019 int position = mListView.getCheckedItemPosition(); 5020 long id = mAdapter.getItemId(position); 5021 if (mCheckedId != id) { 5022 // Clear the ListView's idea of the checked item, since 5023 // it is incorrect 5024 mListView.clearChoices(); 5025 // Search for mCheckedId. If it is in the filtered list, 5026 // mark it as checked 5027 int count = mAdapter.getCount(); 5028 for (int i = 0; i < count; i++) { 5029 if (mAdapter.getItemId(i) == mCheckedId) { 5030 mListView.setItemChecked(i, true); 5031 break; 5032 } 5033 } 5034 } 5035 } 5036 5037 public void onInvalidate() {} 5038 } 5039 5040 public void run() { 5041 final ListView listView = (ListView) LayoutInflater.from(mContext) 5042 .inflate(com.android.internal.R.layout.select_dialog, null); 5043 final MyArrayListAdapter adapter = new 5044 MyArrayListAdapter(mContext, mContainers, mMultiple); 5045 AlertDialog.Builder b = new AlertDialog.Builder(mContext) 5046 .setView(listView).setCancelable(true) 5047 .setInverseBackgroundForced(true); 5048 5049 if (mMultiple) { 5050 b.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { 5051 public void onClick(DialogInterface dialog, int which) { 5052 mWebViewCore.sendMessage( 5053 EventHub.LISTBOX_CHOICES, 5054 adapter.getCount(), 0, 5055 listView.getCheckedItemPositions()); 5056 }}); 5057 b.setNegativeButton(android.R.string.cancel, 5058 new DialogInterface.OnClickListener() { 5059 public void onClick(DialogInterface dialog, int which) { 5060 mWebViewCore.sendMessage( 5061 EventHub.SINGLE_LISTBOX_CHOICE, -2, 0); 5062 }}); 5063 } 5064 final AlertDialog dialog = b.create(); 5065 listView.setAdapter(adapter); 5066 listView.setFocusableInTouchMode(true); 5067 // There is a bug (1250103) where the checks in a ListView with 5068 // multiple items selected are associated with the positions, not 5069 // the ids, so the items do not properly retain their checks when 5070 // filtered. Do not allow filtering on multiple lists until 5071 // that bug is fixed. 5072 5073 listView.setTextFilterEnabled(!mMultiple); 5074 if (mMultiple) { 5075 listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE); 5076 int length = mSelectedArray.length; 5077 for (int i = 0; i < length; i++) { 5078 listView.setItemChecked(mSelectedArray[i], true); 5079 } 5080 } else { 5081 listView.setOnItemClickListener(new OnItemClickListener() { 5082 public void onItemClick(AdapterView parent, View v, 5083 int position, long id) { 5084 mWebViewCore.sendMessage( 5085 EventHub.SINGLE_LISTBOX_CHOICE, (int)id, 0); 5086 dialog.dismiss(); 5087 } 5088 }); 5089 if (mSelection != -1) { 5090 listView.setSelection(mSelection); 5091 listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE); 5092 listView.setItemChecked(mSelection, true); 5093 DataSetObserver observer = new SingleDataSetObserver( 5094 adapter.getItemId(mSelection), listView, adapter); 5095 adapter.registerDataSetObserver(observer); 5096 } 5097 } 5098 dialog.setOnCancelListener(new DialogInterface.OnCancelListener() { 5099 public void onCancel(DialogInterface dialog) { 5100 mWebViewCore.sendMessage( 5101 EventHub.SINGLE_LISTBOX_CHOICE, -2, 0); 5102 } 5103 }); 5104 dialog.show(); 5105 } 5106 } 5107 5108 /* 5109 * Request a dropdown menu for a listbox with multiple selection. 5110 * 5111 * @param array Labels for the listbox. 5112 * @param enabledArray Which positions are enabled. 5113 * @param selectedArray Which positions are initally selected. 5114 */ 5115 void requestListBox(String[] array, boolean[]enabledArray, int[] 5116 selectedArray) { 5117 mPrivateHandler.post( 5118 new InvokeListBox(array, enabledArray, selectedArray)); 5119 } 5120 5121 /* 5122 * Request a dropdown menu for a listbox with single selection or a single 5123 * <select> element. 5124 * 5125 * @param array Labels for the listbox. 5126 * @param enabledArray Which positions are enabled. 5127 * @param selection Which position is initally selected. 5128 */ 5129 void requestListBox(String[] array, boolean[]enabledArray, int selection) { 5130 mPrivateHandler.post( 5131 new InvokeListBox(array, enabledArray, selection)); 5132 } 5133 5134 // called by JNI 5135 private void sendMoveMouse(int frame, int node, int x, int y) { 5136 mWebViewCore.sendMessage(EventHub.SET_MOVE_MOUSE, 5137 new WebViewCore.CursorData(frame, node, x, y)); 5138 } 5139 5140 // called by JNI 5141 private void sendMoveMouseIfLatest(boolean setFocusControllerInactive) { 5142 if (setFocusControllerInactive) { 5143 setFocusControllerInactive(); 5144 } 5145 mWebViewCore.sendMessage(EventHub.SET_MOVE_MOUSE_IF_LATEST, cursorData()); 5146 } 5147 5148 // called by JNI 5149 private void sendMotionUp(int touchGeneration, 5150 int frame, int node, int x, int y, int size) { 5151 WebViewCore.TouchUpData touchUpData = new WebViewCore.TouchUpData(); 5152 touchUpData.mMoveGeneration = touchGeneration; 5153 touchUpData.mSize = size; 5154 touchUpData.mFrame = frame; 5155 touchUpData.mNode = node; 5156 touchUpData.mX = x; 5157 touchUpData.mY = y; 5158 mWebViewCore.sendMessage(EventHub.TOUCH_UP, touchUpData); 5159 } 5160 5161 5162 private int getScaledMaxXScroll() { 5163 int width; 5164 if (mHeightCanMeasure == false) { 5165 width = getViewWidth() / 4; 5166 } else { 5167 Rect visRect = new Rect(); 5168 calcOurVisibleRect(visRect); 5169 width = visRect.width() / 2; 5170 } 5171 // FIXME the divisor should be retrieved from somewhere 5172 return viewToContent(width); 5173 } 5174 5175 private int getScaledMaxYScroll() { 5176 int height; 5177 if (mHeightCanMeasure == false) { 5178 height = getViewHeight() / 4; 5179 } else { 5180 Rect visRect = new Rect(); 5181 calcOurVisibleRect(visRect); 5182 height = visRect.height() / 2; 5183 } 5184 // FIXME the divisor should be retrieved from somewhere 5185 // the closest thing today is hard-coded into ScrollView.java 5186 // (from ScrollView.java, line 363) int maxJump = height/2; 5187 return viewToContent(height); 5188 } 5189 5190 /** 5191 * Called by JNI to invalidate view 5192 */ 5193 private void viewInvalidate() { 5194 invalidate(); 5195 } 5196 5197 // return true if the key was handled 5198 private boolean navHandledKey(int keyCode, int count, boolean noScroll 5199 , long time) { 5200 if (mNativeClass == 0) { 5201 return false; 5202 } 5203 mLastCursorTime = time; 5204 mLastCursorBounds = nativeGetCursorRingBounds(); 5205 boolean keyHandled 5206 = nativeMoveCursor(keyCode, count, noScroll) == false; 5207 if (DebugFlags.WEB_VIEW) { 5208 Log.v(LOGTAG, "navHandledKey mLastCursorBounds=" + mLastCursorBounds 5209 + " mLastCursorTime=" + mLastCursorTime 5210 + " handled=" + keyHandled); 5211 } 5212 if (keyHandled == false || mHeightCanMeasure == false) { 5213 return keyHandled; 5214 } 5215 Rect contentCursorRingBounds = nativeGetCursorRingBounds(); 5216 if (contentCursorRingBounds.isEmpty()) return keyHandled; 5217 Rect viewCursorRingBounds = contentToView(contentCursorRingBounds); 5218 Rect visRect = new Rect(); 5219 calcOurVisibleRect(visRect); 5220 Rect outset = new Rect(visRect); 5221 int maxXScroll = visRect.width() / 2; 5222 int maxYScroll = visRect.height() / 2; 5223 outset.inset(-maxXScroll, -maxYScroll); 5224 if (Rect.intersects(outset, viewCursorRingBounds) == false) { 5225 return keyHandled; 5226 } 5227 // FIXME: Necessary because ScrollView/ListView do not scroll left/right 5228 int maxH = Math.min(viewCursorRingBounds.right - visRect.right, 5229 maxXScroll); 5230 if (maxH > 0) { 5231 pinScrollBy(maxH, 0, true, 0); 5232 } else { 5233 maxH = Math.max(viewCursorRingBounds.left - visRect.left, 5234 -maxXScroll); 5235 if (maxH < 0) { 5236 pinScrollBy(maxH, 0, true, 0); 5237 } 5238 } 5239 if (mLastCursorBounds.isEmpty()) return keyHandled; 5240 if (mLastCursorBounds.equals(contentCursorRingBounds)) { 5241 return keyHandled; 5242 } 5243 if (DebugFlags.WEB_VIEW) { 5244 Log.v(LOGTAG, "navHandledKey contentCursorRingBounds=" 5245 + contentCursorRingBounds); 5246 } 5247 requestRectangleOnScreen(viewCursorRingBounds); 5248 mUserScroll = true; 5249 return keyHandled; 5250 } 5251 5252 /** 5253 * Set the background color. It's white by default. Pass 5254 * zero to make the view transparent. 5255 * @param color the ARGB color described by Color.java 5256 */ 5257 public void setBackgroundColor(int color) { 5258 mBackgroundColor = color; 5259 mWebViewCore.sendMessage(EventHub.SET_BACKGROUND_COLOR, color); 5260 } 5261 5262 public void debugDump() { 5263 nativeDebugDump(); 5264 mWebViewCore.sendMessage(EventHub.DUMP_NAVTREE); 5265 } 5266 5267 /** 5268 * Update our cache with updatedText. 5269 * @param updatedText The new text to put in our cache. 5270 */ 5271 /* package */ void updateCachedTextfield(String updatedText) { 5272 // Also place our generation number so that when we look at the cache 5273 // we recognize that it is up to date. 5274 nativeUpdateCachedTextfield(updatedText, mTextGeneration); 5275 } 5276 5277 private native void nativeClearCursor(); 5278 private native void nativeCreate(int ptr); 5279 private native int nativeCursorFramePointer(); 5280 private native Rect nativeCursorNodeBounds(); 5281 /* package */ native int nativeCursorNodePointer(); 5282 /* package */ native boolean nativeCursorMatchesFocus(); 5283 private native boolean nativeCursorIntersects(Rect visibleRect); 5284 private native boolean nativeCursorIsAnchor(); 5285 private native boolean nativeCursorIsTextInput(); 5286 private native Point nativeCursorPosition(); 5287 private native String nativeCursorText(); 5288 /** 5289 * Returns true if the native cursor node says it wants to handle key events 5290 * (ala plugins). This can only be called if mNativeClass is non-zero! 5291 */ 5292 private native boolean nativeCursorWantsKeyEvents(); 5293 private native void nativeDebugDump(); 5294 private native void nativeDestroy(); 5295 private native void nativeDrawCursorRing(Canvas content); 5296 private native void nativeDrawMatches(Canvas canvas); 5297 private native void nativeDrawSelection(Canvas content 5298 , int x, int y, boolean extendSelection); 5299 private native void nativeDrawSelectionRegion(Canvas content); 5300 private native void nativeDumpDisplayTree(String urlOrNull); 5301 private native int nativeFindAll(String findLower, String findUpper); 5302 private native void nativeFindNext(boolean forward); 5303 private native boolean nativeFocusCandidateIsPassword(); 5304 private native boolean nativeFocusCandidateIsRtlText(); 5305 private native boolean nativeFocusCandidateIsTextField(); 5306 private native boolean nativeFocusCandidateIsTextInput(); 5307 private native int nativeFocusCandidateMaxLength(); 5308 private native String nativeFocusCandidateName(); 5309 private native Rect nativeFocusCandidateNodeBounds(); 5310 /* package */ native int nativeFocusCandidatePointer(); 5311 private native String nativeFocusCandidateText(); 5312 private native int nativeFocusCandidateTextSize(); 5313 private native Rect nativeGetCursorRingBounds(); 5314 private native Region nativeGetSelection(); 5315 private native boolean nativeHasCursorNode(); 5316 private native boolean nativeHasFocusNode(); 5317 private native void nativeHideCursor(); 5318 private native String nativeImageURI(int x, int y); 5319 private native void nativeInstrumentReport(); 5320 // return true if the page has been scrolled 5321 private native boolean nativeMotionUp(int x, int y, int slop); 5322 // returns false if it handled the key 5323 private native boolean nativeMoveCursor(int keyCode, int count, 5324 boolean noScroll); 5325 private native int nativeMoveGeneration(); 5326 private native void nativeMoveSelection(int x, int y, 5327 boolean extendSelection); 5328 // Like many other of our native methods, you must make sure that 5329 // mNativeClass is not null before calling this method. 5330 private native void nativeRecordButtons(boolean focused, 5331 boolean pressed, boolean invalidate); 5332 private native void nativeSelectBestAt(Rect rect); 5333 private native void nativeSetFindIsDown(); 5334 private native void nativeSetFollowedLink(boolean followed); 5335 private native void nativeSetHeightCanMeasure(boolean measure); 5336 private native int nativeTextGeneration(); 5337 // Never call this version except by updateCachedTextfield(String) - 5338 // we always want to pass in our generation number. 5339 private native void nativeUpdateCachedTextfield(String updatedText, 5340 int generation); 5341 5342} 5343