WebView.java revision 2d3ef37ae6ce91c759e57dda7f16d148fdeee35a
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.annotation.Widget; 20import android.app.AlertDialog; 21import android.content.BroadcastReceiver; 22import android.content.ClipboardManager; 23import android.content.Context; 24import android.content.DialogInterface; 25import android.content.DialogInterface.OnCancelListener; 26import android.content.Intent; 27import android.content.IntentFilter; 28import android.content.pm.PackageInfo; 29import android.content.pm.PackageManager; 30import android.content.res.Configuration; 31import android.database.DataSetObserver; 32import android.graphics.Bitmap; 33import android.graphics.BitmapFactory; 34import android.graphics.BitmapShader; 35import android.graphics.Canvas; 36import android.graphics.Color; 37import android.graphics.CornerPathEffect; 38import android.graphics.DrawFilter; 39import android.graphics.Paint; 40import android.graphics.PaintFlagsDrawFilter; 41import android.graphics.Picture; 42import android.graphics.Point; 43import android.graphics.Rect; 44import android.graphics.RectF; 45import android.graphics.Region; 46import android.graphics.Shader; 47import android.graphics.drawable.Drawable; 48import android.net.Proxy; 49import android.net.ProxyProperties; 50import android.net.Uri; 51import android.net.http.SslCertificate; 52import android.os.AsyncTask; 53import android.os.Bundle; 54import android.os.Handler; 55import android.os.Message; 56import android.provider.Settings; 57import android.speech.tts.TextToSpeech; 58import android.text.Selection; 59import android.text.Spannable; 60import android.util.AttributeSet; 61import android.util.EventLog; 62import android.util.Log; 63import android.view.Gravity; 64import android.view.HardwareCanvas; 65import android.view.InputDevice; 66import android.view.KeyCharacterMap; 67import android.view.KeyEvent; 68import android.view.LayoutInflater; 69import android.view.MotionEvent; 70import android.view.ScaleGestureDetector; 71import android.view.SoundEffectConstants; 72import android.view.VelocityTracker; 73import android.view.View; 74import android.view.ViewConfiguration; 75import android.view.ViewGroup; 76import android.view.ViewParent; 77import android.view.ViewTreeObserver; 78import android.view.accessibility.AccessibilityManager; 79import android.view.inputmethod.EditorInfo; 80import android.view.inputmethod.InputConnection; 81import android.view.inputmethod.InputMethodManager; 82import android.webkit.WebTextView.AutoCompleteAdapter; 83import android.webkit.WebViewCore.EventHub; 84import android.webkit.WebViewCore.TouchEventData; 85import android.webkit.WebViewCore.TouchHighlightData; 86import android.widget.AbsoluteLayout; 87import android.widget.Adapter; 88import android.widget.AdapterView; 89import android.widget.AdapterView.OnItemClickListener; 90import android.widget.ArrayAdapter; 91import android.widget.CheckedTextView; 92import android.widget.LinearLayout; 93import android.widget.ListView; 94import android.widget.OverScroller; 95import android.widget.Toast; 96 97import java.io.File; 98import java.io.FileInputStream; 99import java.io.FileNotFoundException; 100import java.io.FileOutputStream; 101import java.net.URLDecoder; 102import java.util.ArrayList; 103import java.util.HashMap; 104import java.util.HashSet; 105import java.util.List; 106import java.util.Map; 107import java.util.Set; 108import java.util.Vector; 109import java.util.regex.Matcher; 110import java.util.regex.Pattern; 111 112import junit.framework.Assert; 113 114/** 115 * <p>A View that displays web pages. This class is the basis upon which you 116 * can roll your own web browser or simply display some online content within your Activity. 117 * It uses the WebKit rendering engine to display 118 * web pages and includes methods to navigate forward and backward 119 * through a history, zoom in and out, perform text searches and more.</p> 120 * <p>To enable the built-in zoom, set 121 * {@link #getSettings() WebSettings}.{@link WebSettings#setBuiltInZoomControls(boolean)} 122 * (introduced in API version 3). 123 * <p>Note that, in order for your Activity to access the Internet and load web pages 124 * in a WebView, you must add the {@code INTERNET} permissions to your 125 * Android Manifest file:</p> 126 * <pre><uses-permission android:name="android.permission.INTERNET" /></pre> 127 * 128 * <p>This must be a child of the <a 129 * href="{@docRoot}guide/topics/manifest/manifest-element.html">{@code <manifest>}</a> 130 * element.</p> 131 * 132 * <p>See the <a href="{@docRoot}resources/tutorials/views/hello-webview.html">Web View 133 * tutorial</a>.</p> 134 * 135 * <h3>Basic usage</h3> 136 * 137 * <p>By default, a WebView provides no browser-like widgets, does not 138 * enable JavaScript and web page errors are ignored. If your goal is only 139 * to display some HTML as a part of your UI, this is probably fine; 140 * the user won't need to interact with the web page beyond reading 141 * it, and the web page won't need to interact with the user. If you 142 * actually want a full-blown web browser, then you probably want to 143 * invoke the Browser application with a URL Intent rather than show it 144 * with a WebView. For example: 145 * <pre> 146 * Uri uri = Uri.parse("http://www.example.com"); 147 * Intent intent = new Intent(Intent.ACTION_VIEW, uri); 148 * startActivity(intent); 149 * </pre> 150 * <p>See {@link android.content.Intent} for more information.</p> 151 * 152 * <p>To provide a WebView in your own Activity, include a {@code <WebView>} in your layout, 153 * or set the entire Activity window as a WebView during {@link 154 * android.app.Activity#onCreate(Bundle) onCreate()}:</p> 155 * <pre class="prettyprint"> 156 * WebView webview = new WebView(this); 157 * setContentView(webview); 158 * </pre> 159 * 160 * <p>Then load the desired web page:</p> 161 * <pre> 162 * // Simplest usage: note that an exception will NOT be thrown 163 * // if there is an error loading this page (see below). 164 * webview.loadUrl("http://slashdot.org/"); 165 * 166 * // OR, you can also load from an HTML string: 167 * String summary = "<html><body>You scored <b>192</b> points.</body></html>"; 168 * webview.loadData(summary, "text/html", "utf-8"); 169 * // ... although note that there are restrictions on what this HTML can do. 170 * // See the JavaDocs for {@link #loadData(String,String,String) loadData()} and {@link 171 * #loadDataWithBaseURL(String,String,String,String,String) loadDataWithBaseURL()} for more info. 172 * </pre> 173 * 174 * <p>A WebView has several customization points where you can add your 175 * own behavior. These are:</p> 176 * 177 * <ul> 178 * <li>Creating and setting a {@link android.webkit.WebChromeClient} subclass. 179 * This class is called when something that might impact a 180 * browser UI happens, for instance, progress updates and 181 * JavaScript alerts are sent here (see <a 182 * href="{@docRoot}guide/developing/debug-tasks.html#DebuggingWebPages">Debugging Tasks</a>). 183 * </li> 184 * <li>Creating and setting a {@link android.webkit.WebViewClient} subclass. 185 * It will be called when things happen that impact the 186 * rendering of the content, eg, errors or form submissions. You 187 * can also intercept URL loading here (via {@link 188 * android.webkit.WebViewClient#shouldOverrideUrlLoading(WebView,String) 189 * shouldOverrideUrlLoading()}).</li> 190 * <li>Modifying the {@link android.webkit.WebSettings}, such as 191 * enabling JavaScript with {@link android.webkit.WebSettings#setJavaScriptEnabled(boolean) 192 * setJavaScriptEnabled()}. </li> 193 * <li>Adding JavaScript-to-Java interfaces with the {@link 194 * android.webkit.WebView#addJavascriptInterface} method. 195 * This lets you bind Java objects into the WebView so they can be 196 * controlled from the web pages JavaScript.</li> 197 * </ul> 198 * 199 * <p>Here's a more complicated example, showing error handling, 200 * settings, and progress notification:</p> 201 * 202 * <pre class="prettyprint"> 203 * // Let's display the progress in the activity title bar, like the 204 * // browser app does. 205 * getWindow().requestFeature(Window.FEATURE_PROGRESS); 206 * 207 * webview.getSettings().setJavaScriptEnabled(true); 208 * 209 * final Activity activity = this; 210 * webview.setWebChromeClient(new WebChromeClient() { 211 * public void onProgressChanged(WebView view, int progress) { 212 * // Activities and WebViews measure progress with different scales. 213 * // The progress meter will automatically disappear when we reach 100% 214 * activity.setProgress(progress * 1000); 215 * } 216 * }); 217 * webview.setWebViewClient(new WebViewClient() { 218 * public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) { 219 * Toast.makeText(activity, "Oh no! " + description, Toast.LENGTH_SHORT).show(); 220 * } 221 * }); 222 * 223 * webview.loadUrl("http://slashdot.org/"); 224 * </pre> 225 * 226 * <h3>Cookie and window management</h3> 227 * 228 * <p>For obvious security reasons, your application has its own 229 * cache, cookie store etc.—it does not share the Browser 230 * application's data. Cookies are managed on a separate thread, so 231 * operations like index building don't block the UI 232 * thread. Follow the instructions in {@link android.webkit.CookieSyncManager} 233 * if you want to use cookies in your application. 234 * </p> 235 * 236 * <p>By default, requests by the HTML to open new windows are 237 * ignored. This is true whether they be opened by JavaScript or by 238 * the target attribute on a link. You can customize your 239 * {@link WebChromeClient} to provide your own behaviour for opening multiple windows, 240 * and render them in whatever manner you want.</p> 241 * 242 * <p>The standard behavior for an Activity is to be destroyed and 243 * recreated when the device orientation or any other configuration changes. This will cause 244 * the WebView to reload the current page. If you don't want that, you 245 * can set your Activity to handle the {@code orientation} and {@code keyboardHidden} 246 * changes, and then just leave the WebView alone. It'll automatically 247 * re-orient itself as appropriate. Read <a 248 * href="{@docRoot}guide/topics/resources/runtime-changes.html">Handling Runtime Changes</a> for 249 * more information about how to handle configuration changes during runtime.</p> 250 * 251 * 252 * <h3>Building web pages to support different screen densities</h3> 253 * 254 * <p>The screen density of a device is based on the screen resolution. A screen with low density 255 * has fewer available pixels per inch, where a screen with high density 256 * has more — sometimes significantly more — pixels per inch. The density of a 257 * screen is important because, other things being equal, a UI element (such as a button) whose 258 * height and width are defined in terms of screen pixels will appear larger on the lower density 259 * screen and smaller on the higher density screen. 260 * For simplicity, Android collapses all actual screen densities into three generalized densities: 261 * high, medium, and low.</p> 262 * <p>By default, WebView scales a web page so that it is drawn at a size that matches the default 263 * appearance on a medium density screen. So, it applies 1.5x scaling on a high density screen 264 * (because its pixels are smaller) and 0.75x scaling on a low density screen (because its pixels 265 * are bigger). 266 * Starting with API Level 5 (Android 2.0), WebView supports DOM, CSS, and meta tag features to help 267 * you (as a web developer) target screens with different screen densities.</p> 268 * <p>Here's a summary of the features you can use to handle different screen densities:</p> 269 * <ul> 270 * <li>The {@code window.devicePixelRatio} DOM property. The value of this property specifies the 271 * default scaling factor used for the current device. For example, if the value of {@code 272 * window.devicePixelRatio} is "1.0", then the device is considered a medium density (mdpi) device 273 * and default scaling is not applied to the web page; if the value is "1.5", then the device is 274 * considered a high density device (hdpi) and the page content is scaled 1.5x; if the 275 * value is "0.75", then the device is considered a low density device (ldpi) and the content is 276 * scaled 0.75x. However, if you specify the {@code "target-densitydpi"} meta property 277 * (discussed below), then you can stop this default scaling behavior.</li> 278 * <li>The {@code -webkit-device-pixel-ratio} CSS media query. Use this to specify the screen 279 * densities for which this style sheet is to be used. The corresponding value should be either 280 * "0.75", "1", or "1.5", to indicate that the styles are for devices with low density, medium 281 * density, or high density screens, respectively. For example: 282 * <pre> 283 * <link rel="stylesheet" media="screen and (-webkit-device-pixel-ratio:1.5)" href="hdpi.css" /></pre> 284 * <p>The {@code hdpi.css} stylesheet is only used for devices with a screen pixel ration of 1.5, 285 * which is the high density pixel ratio.</p> 286 * </li> 287 * <li>The {@code target-densitydpi} property for the {@code viewport} meta tag. You can use 288 * this to specify the target density for which the web page is designed, using the following 289 * values: 290 * <ul> 291 * <li>{@code device-dpi} - Use the device's native dpi as the target dpi. Default scaling never 292 * occurs.</li> 293 * <li>{@code high-dpi} - Use hdpi as the target dpi. Medium and low density screens scale down 294 * as appropriate.</li> 295 * <li>{@code medium-dpi} - Use mdpi as the target dpi. High density screens scale up and 296 * low density screens scale down. This is also the default behavior.</li> 297 * <li>{@code low-dpi} - Use ldpi as the target dpi. Medium and high density screens scale up 298 * as appropriate.</li> 299 * <li><em>{@code <value>}</em> - Specify a dpi value to use as the target dpi (accepted 300 * values are 70-400).</li> 301 * </ul> 302 * <p>Here's an example meta tag to specify the target density:</p> 303 * <pre><meta name="viewport" content="target-densitydpi=device-dpi" /></pre></li> 304 * </ul> 305 * <p>If you want to modify your web page for different densities, by using the {@code 306 * -webkit-device-pixel-ratio} CSS media query and/or the {@code 307 * window.devicePixelRatio} DOM property, then you should set the {@code target-densitydpi} meta 308 * property to {@code device-dpi}. This stops Android from performing scaling in your web page and 309 * allows you to make the necessary adjustments for each density via CSS and JavaScript.</p> 310 * 311 * 312 */ 313@Widget 314public class WebView extends AbsoluteLayout 315 implements ViewTreeObserver.OnGlobalFocusChangeListener, 316 ViewGroup.OnHierarchyChangeListener { 317 318 private class InnerGlobalLayoutListener implements ViewTreeObserver.OnGlobalLayoutListener { 319 public void onGlobalLayout() { 320 if (isShown()) { 321 setGLRectViewport(); 322 } 323 } 324 } 325 326 private class InnerScrollChangedListener implements ViewTreeObserver.OnScrollChangedListener { 327 public void onScrollChanged() { 328 if (isShown()) { 329 setGLRectViewport(); 330 } 331 } 332 } 333 334 // The listener to capture global layout change event. 335 private InnerGlobalLayoutListener mGlobalLayoutListener = null; 336 337 // The listener to capture scroll event. 338 private InnerScrollChangedListener mScrollChangedListener = null; 339 340 // if AUTO_REDRAW_HACK is true, then the CALL key will toggle redrawing 341 // the screen all-the-time. Good for profiling our drawing code 342 static private final boolean AUTO_REDRAW_HACK = false; 343 // true means redraw the screen all-the-time. Only with AUTO_REDRAW_HACK 344 private boolean mAutoRedraw; 345 346 // Reference to the AlertDialog displayed by InvokeListBox. 347 // It's used to dismiss the dialog in destroy if not done before. 348 private AlertDialog mListBoxDialog = null; 349 350 static final String LOGTAG = "webview"; 351 352 private ZoomManager mZoomManager; 353 354 private final Rect mGLRectViewport = new Rect(); 355 private final Rect mViewRectViewport = new Rect(); 356 private boolean mGLViewportEmpty = false; 357 358 /** 359 * Transportation object for returning WebView across thread boundaries. 360 */ 361 public class WebViewTransport { 362 private WebView mWebview; 363 364 /** 365 * Set the WebView to the transportation object. 366 * @param webview The WebView to transport. 367 */ 368 public synchronized void setWebView(WebView webview) { 369 mWebview = webview; 370 } 371 372 /** 373 * Return the WebView object. 374 * @return WebView The transported WebView object. 375 */ 376 public synchronized WebView getWebView() { 377 return mWebview; 378 } 379 } 380 381 // A final CallbackProxy shared by WebViewCore and BrowserFrame. 382 private final CallbackProxy mCallbackProxy; 383 384 private final WebViewDatabase mDatabase; 385 386 // SSL certificate for the main top-level page (if secure) 387 private SslCertificate mCertificate; 388 389 // Native WebView pointer that is 0 until the native object has been 390 // created. 391 private int mNativeClass; 392 // This would be final but it needs to be set to null when the WebView is 393 // destroyed. 394 private WebViewCore mWebViewCore; 395 // Handler for dispatching UI messages. 396 /* package */ final Handler mPrivateHandler = new PrivateHandler(); 397 private WebTextView mWebTextView; 398 // Used to ignore changes to webkit text that arrives to the UI side after 399 // more key events. 400 private int mTextGeneration; 401 402 /* package */ void incrementTextGeneration() { mTextGeneration++; } 403 404 // Used by WebViewCore to create child views. 405 /* package */ final ViewManager mViewManager; 406 407 // Used to display in full screen mode 408 PluginFullScreenHolder mFullScreenHolder; 409 410 /** 411 * Position of the last touch event in pixels. 412 * Use integer to prevent loss of dragging delta calculation accuracy; 413 * which was done in float and converted to integer, and resulted in gradual 414 * and compounding touch position and view dragging mismatch. 415 */ 416 private int mLastTouchX; 417 private int mLastTouchY; 418 419 /** 420 * Time of the last touch event. 421 */ 422 private long mLastTouchTime; 423 424 /** 425 * Time of the last time sending touch event to WebViewCore 426 */ 427 private long mLastSentTouchTime; 428 429 /** 430 * The minimum elapsed time before sending another ACTION_MOVE event to 431 * WebViewCore. This really should be tuned for each type of the devices. 432 * For example in Google Map api test case, it takes Dream device at least 433 * 150ms to do a full cycle in the WebViewCore by processing a touch event, 434 * triggering the layout and drawing the picture. While the same process 435 * takes 60+ms on the current high speed device. If we make 436 * TOUCH_SENT_INTERVAL too small, there will be multiple touch events sent 437 * to WebViewCore queue and the real layout and draw events will be pushed 438 * to further, which slows down the refresh rate. Choose 50 to favor the 439 * current high speed devices. For Dream like devices, 100 is a better 440 * choice. Maybe make this in the buildspec later. 441 * (Update 12/14/2010: changed to 0 since current device should be able to 442 * handle the raw events and Map team voted to have the raw events too. 443 */ 444 private static final int TOUCH_SENT_INTERVAL = 0; 445 private int mCurrentTouchInterval = TOUCH_SENT_INTERVAL; 446 447 /** 448 * Helper class to get velocity for fling 449 */ 450 VelocityTracker mVelocityTracker; 451 private int mMaximumFling; 452 private float mLastVelocity; 453 private float mLastVelX; 454 private float mLastVelY; 455 456 // The id of the native layer being scrolled. 457 private int mScrollingLayer; 458 private Rect mScrollingLayerRect = new Rect(); 459 460 // only trigger accelerated fling if the new velocity is at least 461 // MINIMUM_VELOCITY_RATIO_FOR_ACCELERATION times of the previous velocity 462 private static final float MINIMUM_VELOCITY_RATIO_FOR_ACCELERATION = 0.2f; 463 464 /** 465 * Touch mode 466 */ 467 private int mTouchMode = TOUCH_DONE_MODE; 468 private static final int TOUCH_INIT_MODE = 1; 469 private static final int TOUCH_DRAG_START_MODE = 2; 470 private static final int TOUCH_DRAG_MODE = 3; 471 private static final int TOUCH_SHORTPRESS_START_MODE = 4; 472 private static final int TOUCH_SHORTPRESS_MODE = 5; 473 private static final int TOUCH_DOUBLE_TAP_MODE = 6; 474 private static final int TOUCH_DONE_MODE = 7; 475 private static final int TOUCH_PINCH_DRAG = 8; 476 private static final int TOUCH_DRAG_LAYER_MODE = 9; 477 478 // Whether to forward the touch events to WebCore 479 // Can only be set by WebKit via JNI. 480 private boolean mForwardTouchEvents = false; 481 482 // Whether to prevent default during touch. The initial value depends on 483 // mForwardTouchEvents. If WebCore wants all the touch events, it says yes 484 // for touch down. Otherwise UI will wait for the answer of the first 485 // confirmed move before taking over the control. 486 private static final int PREVENT_DEFAULT_NO = 0; 487 private static final int PREVENT_DEFAULT_MAYBE_YES = 1; 488 private static final int PREVENT_DEFAULT_NO_FROM_TOUCH_DOWN = 2; 489 private static final int PREVENT_DEFAULT_YES = 3; 490 private static final int PREVENT_DEFAULT_IGNORE = 4; 491 private int mPreventDefault = PREVENT_DEFAULT_IGNORE; 492 493 // true when the touch movement exceeds the slop 494 private boolean mConfirmMove; 495 496 // if true, touch events will be first processed by WebCore, if prevent 497 // default is not set, the UI will continue handle them. 498 private boolean mDeferTouchProcess; 499 500 // Currently, multi-touch events are sent to WebKit first then back to 501 // WebView while single-touch events are handled in WebView first. 502 // So there is a chance that a single-touch move event is handled in WebView 503 // before multi-touch events are finished. 504 // if mIsHandlingMultiTouch is true, which means multi-touch event handling 505 // is not finished, then any single-touch move event will be skipped. 506 // FIXME: send single-touch events to WebKit first then back to WebView. 507 private boolean mIsHandlingMultiTouch = false; 508 509 // to avoid interfering with the current touch events, track them 510 // separately. Currently no snapping or fling in the deferred process mode 511 private int mDeferTouchMode = TOUCH_DONE_MODE; 512 private float mLastDeferTouchX; 513 private float mLastDeferTouchY; 514 515 // To keep track of whether the current drag was initiated by a WebTextView, 516 // so that we know not to hide the cursor 517 boolean mDragFromTextInput; 518 519 // Whether or not to draw the cursor ring. 520 private boolean mDrawCursorRing = true; 521 522 // true if onPause has been called (and not onResume) 523 private boolean mIsPaused; 524 525 private HitTestResult mInitialHitTestResult; 526 527 /** 528 * Customizable constant 529 */ 530 // pre-computed square of ViewConfiguration.getScaledTouchSlop() 531 private int mTouchSlopSquare; 532 // pre-computed square of ViewConfiguration.getScaledDoubleTapSlop() 533 private int mDoubleTapSlopSquare; 534 // pre-computed density adjusted navigation slop 535 private int mNavSlop; 536 // This should be ViewConfiguration.getTapTimeout() 537 // But system time out is 100ms, which is too short for the browser. 538 // In the browser, if it switches out of tap too soon, jump tap won't work. 539 private static final int TAP_TIMEOUT = 200; 540 // This should be ViewConfiguration.getLongPressTimeout() 541 // But system time out is 500ms, which is too short for the browser. 542 // With a short timeout, it's difficult to treat trigger a short press. 543 private static final int LONG_PRESS_TIMEOUT = 1000; 544 // needed to avoid flinging after a pause of no movement 545 private static final int MIN_FLING_TIME = 250; 546 // draw unfiltered after drag is held without movement 547 private static final int MOTIONLESS_TIME = 100; 548 // The amount of content to overlap between two screens when going through 549 // pages with the space bar, in pixels. 550 private static final int PAGE_SCROLL_OVERLAP = 24; 551 552 /** 553 * These prevent calling requestLayout if either dimension is fixed. This 554 * depends on the layout parameters and the measure specs. 555 */ 556 boolean mWidthCanMeasure; 557 boolean mHeightCanMeasure; 558 559 // Remember the last dimensions we sent to the native side so we can avoid 560 // sending the same dimensions more than once. 561 int mLastWidthSent; 562 int mLastHeightSent; 563 // Since view height sent to webkit could be fixed to avoid relayout, this 564 // value records the last sent actual view height. 565 int mLastActualHeightSent; 566 567 private int mContentWidth; // cache of value from WebViewCore 568 private int mContentHeight; // cache of value from WebViewCore 569 570 // Need to have the separate control for horizontal and vertical scrollbar 571 // style than the View's single scrollbar style 572 private boolean mOverlayHorizontalScrollbar = true; 573 private boolean mOverlayVerticalScrollbar = false; 574 575 // our standard speed. this way small distances will be traversed in less 576 // time than large distances, but we cap the duration, so that very large 577 // distances won't take too long to get there. 578 private static final int STD_SPEED = 480; // pixels per second 579 // time for the longest scroll animation 580 private static final int MAX_DURATION = 750; // milliseconds 581 private static final int SLIDE_TITLE_DURATION = 500; // milliseconds 582 583 // Used by OverScrollGlow 584 OverScroller mScroller; 585 586 private boolean mInOverScrollMode = false; 587 private static Paint mOverScrollBackground; 588 private static Paint mOverScrollBorder; 589 590 private boolean mWrapContent; 591 private static final int MOTIONLESS_FALSE = 0; 592 private static final int MOTIONLESS_PENDING = 1; 593 private static final int MOTIONLESS_TRUE = 2; 594 private static final int MOTIONLESS_IGNORE = 3; 595 private int mHeldMotionless; 596 597 // An instance for injecting accessibility in WebViews with disabled 598 // JavaScript or ones for which no accessibility script exists 599 private AccessibilityInjector mAccessibilityInjector; 600 601 // flag indicating if accessibility script is injected so we 602 // know to handle Shift and arrows natively first 603 private boolean mAccessibilityScriptInjected; 604 605 // the color used to highlight the touch rectangles 606 private static final int mHightlightColor = 0x33000000; 607 // the round corner for the highlight path 608 private static final float TOUCH_HIGHLIGHT_ARC = 5.0f; 609 // the region indicating where the user touched on the screen 610 private Region mTouchHighlightRegion = new Region(); 611 // the paint for the touch highlight 612 private Paint mTouchHightlightPaint; 613 // debug only 614 private static final boolean DEBUG_TOUCH_HIGHLIGHT = true; 615 private static final int TOUCH_HIGHLIGHT_ELAPSE_TIME = 2000; 616 private Paint mTouchCrossHairColor; 617 private int mTouchHighlightX; 618 private int mTouchHighlightY; 619 620 /* 621 * Private message ids 622 */ 623 private static final int REMEMBER_PASSWORD = 1; 624 private static final int NEVER_REMEMBER_PASSWORD = 2; 625 private static final int SWITCH_TO_SHORTPRESS = 3; 626 private static final int SWITCH_TO_LONGPRESS = 4; 627 private static final int RELEASE_SINGLE_TAP = 5; 628 private static final int REQUEST_FORM_DATA = 6; 629 private static final int RESUME_WEBCORE_PRIORITY = 7; 630 private static final int DRAG_HELD_MOTIONLESS = 8; 631 private static final int AWAKEN_SCROLL_BARS = 9; 632 private static final int PREVENT_DEFAULT_TIMEOUT = 10; 633 private static final int SCROLL_SELECT_TEXT = 11; 634 635 636 private static final int FIRST_PRIVATE_MSG_ID = REMEMBER_PASSWORD; 637 private static final int LAST_PRIVATE_MSG_ID = SCROLL_SELECT_TEXT; 638 639 /* 640 * Package message ids 641 */ 642 static final int SCROLL_TO_MSG_ID = 101; 643 static final int NEW_PICTURE_MSG_ID = 105; 644 static final int UPDATE_TEXT_ENTRY_MSG_ID = 106; 645 static final int WEBCORE_INITIALIZED_MSG_ID = 107; 646 static final int UPDATE_TEXTFIELD_TEXT_MSG_ID = 108; 647 static final int UPDATE_ZOOM_RANGE = 109; 648 static final int UNHANDLED_NAV_KEY = 110; 649 static final int CLEAR_TEXT_ENTRY = 111; 650 static final int UPDATE_TEXT_SELECTION_MSG_ID = 112; 651 static final int SHOW_RECT_MSG_ID = 113; 652 static final int LONG_PRESS_CENTER = 114; 653 static final int PREVENT_TOUCH_ID = 115; 654 static final int WEBCORE_NEED_TOUCH_EVENTS = 116; 655 // obj=Rect in doc coordinates 656 static final int INVAL_RECT_MSG_ID = 117; 657 static final int REQUEST_KEYBOARD = 118; 658 static final int DO_MOTION_UP = 119; 659 static final int SHOW_FULLSCREEN = 120; 660 static final int HIDE_FULLSCREEN = 121; 661 static final int DOM_FOCUS_CHANGED = 122; 662 static final int REPLACE_BASE_CONTENT = 123; 663 static final int FORM_DID_BLUR = 124; 664 static final int RETURN_LABEL = 125; 665 static final int FIND_AGAIN = 126; 666 static final int CENTER_FIT_RECT = 127; 667 static final int REQUEST_KEYBOARD_WITH_SELECTION_MSG_ID = 128; 668 static final int SET_SCROLLBAR_MODES = 129; 669 static final int SELECTION_STRING_CHANGED = 130; 670 static final int SET_TOUCH_HIGHLIGHT_RECTS = 131; 671 static final int SAVE_WEBARCHIVE_FINISHED = 132; 672 673 static final int SET_AUTOFILLABLE = 133; 674 static final int AUTOFILL_COMPLETE = 134; 675 676 static final int SELECT_AT = 135; 677 static final int SCREEN_ON = 136; 678 679 private static final int FIRST_PACKAGE_MSG_ID = SCROLL_TO_MSG_ID; 680 private static final int LAST_PACKAGE_MSG_ID = SET_TOUCH_HIGHLIGHT_RECTS; 681 682 static final String[] HandlerPrivateDebugString = { 683 "REMEMBER_PASSWORD", // = 1; 684 "NEVER_REMEMBER_PASSWORD", // = 2; 685 "SWITCH_TO_SHORTPRESS", // = 3; 686 "SWITCH_TO_LONGPRESS", // = 4; 687 "RELEASE_SINGLE_TAP", // = 5; 688 "REQUEST_FORM_DATA", // = 6; 689 "RESUME_WEBCORE_PRIORITY", // = 7; 690 "DRAG_HELD_MOTIONLESS", // = 8; 691 "AWAKEN_SCROLL_BARS", // = 9; 692 "PREVENT_DEFAULT_TIMEOUT", // = 10; 693 "SCROLL_SELECT_TEXT" // = 11; 694 }; 695 696 static final String[] HandlerPackageDebugString = { 697 "SCROLL_TO_MSG_ID", // = 101; 698 "102", // = 102; 699 "103", // = 103; 700 "104", // = 104; 701 "NEW_PICTURE_MSG_ID", // = 105; 702 "UPDATE_TEXT_ENTRY_MSG_ID", // = 106; 703 "WEBCORE_INITIALIZED_MSG_ID", // = 107; 704 "UPDATE_TEXTFIELD_TEXT_MSG_ID", // = 108; 705 "UPDATE_ZOOM_RANGE", // = 109; 706 "UNHANDLED_NAV_KEY", // = 110; 707 "CLEAR_TEXT_ENTRY", // = 111; 708 "UPDATE_TEXT_SELECTION_MSG_ID", // = 112; 709 "SHOW_RECT_MSG_ID", // = 113; 710 "LONG_PRESS_CENTER", // = 114; 711 "PREVENT_TOUCH_ID", // = 115; 712 "WEBCORE_NEED_TOUCH_EVENTS", // = 116; 713 "INVAL_RECT_MSG_ID", // = 117; 714 "REQUEST_KEYBOARD", // = 118; 715 "DO_MOTION_UP", // = 119; 716 "SHOW_FULLSCREEN", // = 120; 717 "HIDE_FULLSCREEN", // = 121; 718 "DOM_FOCUS_CHANGED", // = 122; 719 "REPLACE_BASE_CONTENT", // = 123; 720 "FORM_DID_BLUR", // = 124; 721 "RETURN_LABEL", // = 125; 722 "FIND_AGAIN", // = 126; 723 "CENTER_FIT_RECT", // = 127; 724 "REQUEST_KEYBOARD_WITH_SELECTION_MSG_ID", // = 128; 725 "SET_SCROLLBAR_MODES", // = 129; 726 "SELECTION_STRING_CHANGED", // = 130; 727 "SET_TOUCH_HIGHLIGHT_RECTS", // = 131; 728 "SAVE_WEBARCHIVE_FINISHED", // = 132; 729 "SET_AUTOFILLABLE", // = 133; 730 "AUTOFILL_COMPLETE", // = 134; 731 "SELECT_AT", // = 135; 732 "SCREEN_ON" // = 136; 733 }; 734 735 // If the site doesn't use the viewport meta tag to specify the viewport, 736 // use DEFAULT_VIEWPORT_WIDTH as the default viewport width 737 static final int DEFAULT_VIEWPORT_WIDTH = 980; 738 739 // normally we try to fit the content to the minimum preferred width 740 // calculated by the Webkit. To avoid the bad behavior when some site's 741 // minimum preferred width keeps growing when changing the viewport width or 742 // the minimum preferred width is huge, an upper limit is needed. 743 static int sMaxViewportWidth = DEFAULT_VIEWPORT_WIDTH; 744 745 // initial scale in percent. 0 means using default. 746 private int mInitialScaleInPercent = 0; 747 748 // Whether or not a scroll event should be sent to webkit. This is only set 749 // to false when restoring the scroll position. 750 private boolean mSendScrollEvent = true; 751 752 private int mSnapScrollMode = SNAP_NONE; 753 private static final int SNAP_NONE = 0; 754 private static final int SNAP_LOCK = 1; // not a separate state 755 private static final int SNAP_X = 2; // may be combined with SNAP_LOCK 756 private static final int SNAP_Y = 4; // may be combined with SNAP_LOCK 757 private boolean mSnapPositive; 758 759 // keep these in sync with their counterparts in WebView.cpp 760 private static final int DRAW_EXTRAS_NONE = 0; 761 private static final int DRAW_EXTRAS_FIND = 1; 762 private static final int DRAW_EXTRAS_SELECTION = 2; 763 private static final int DRAW_EXTRAS_CURSOR_RING = 3; 764 765 // keep this in sync with WebCore:ScrollbarMode in WebKit 766 private static final int SCROLLBAR_AUTO = 0; 767 private static final int SCROLLBAR_ALWAYSOFF = 1; 768 // as we auto fade scrollbar, this is ignored. 769 private static final int SCROLLBAR_ALWAYSON = 2; 770 private int mHorizontalScrollBarMode = SCROLLBAR_AUTO; 771 private int mVerticalScrollBarMode = SCROLLBAR_AUTO; 772 773 // constants for determining script injection strategy 774 private static final int ACCESSIBILITY_SCRIPT_INJECTION_UNDEFINED = -1; 775 private static final int ACCESSIBILITY_SCRIPT_INJECTION_OPTED_OUT = 0; 776 private static final int ACCESSIBILITY_SCRIPT_INJECTION_PROVIDED = 1; 777 778 // the alias via which accessibility JavaScript interface is exposed 779 private static final String ALIAS_ACCESSIBILITY_JS_INTERFACE = "accessibility"; 780 781 // JavaScript to inject the script chooser which will 782 // pick the right script for the current URL 783 private static final String ACCESSIBILITY_SCRIPT_CHOOSER_JAVASCRIPT = 784 "javascript:(function() {" + 785 " var chooser = document.createElement('script');" + 786 " chooser.type = 'text/javascript';" + 787 " chooser.src = 'https://ssl.gstatic.com/accessibility/javascript/android/AndroidScriptChooser.user.js';" + 788 " document.getElementsByTagName('head')[0].appendChild(chooser);" + 789 " })();"; 790 791 // Regular expression that matches the "axs" URL parameter. 792 // The value of 0 means the accessibility script is opted out 793 // The value of 1 means the accessibility script is already injected 794 private static final String PATTERN_MATCH_AXS_URL_PARAMETER = "(\\?axs=(0|1))|(&axs=(0|1))"; 795 796 // TextToSpeech instance exposed to JavaScript to the injected screenreader. 797 private TextToSpeech mTextToSpeech; 798 799 // variable to cache the above pattern in case accessibility is enabled. 800 private Pattern mMatchAxsUrlParameterPattern; 801 802 /** 803 * Max distance to overscroll by in pixels. 804 * This how far content can be pulled beyond its normal bounds by the user. 805 */ 806 private int mOverscrollDistance; 807 808 /** 809 * Max distance to overfling by in pixels. 810 * This is how far flinged content can move beyond the end of its normal bounds. 811 */ 812 private int mOverflingDistance; 813 814 private OverScrollGlow mOverScrollGlow; 815 816 // Used to match key downs and key ups 817 private Vector<Integer> mKeysPressed; 818 819 /* package */ static boolean mLogEvent = true; 820 821 // for event log 822 private long mLastTouchUpTime = 0; 823 824 private WebViewCore.AutoFillData mAutoFillData; 825 826 /** 827 * URI scheme for telephone number 828 */ 829 public static final String SCHEME_TEL = "tel:"; 830 /** 831 * URI scheme for email address 832 */ 833 public static final String SCHEME_MAILTO = "mailto:"; 834 /** 835 * URI scheme for map address 836 */ 837 public static final String SCHEME_GEO = "geo:0,0?q="; 838 839 private int mBackgroundColor = Color.WHITE; 840 841 private static final long SELECT_SCROLL_INTERVAL = 1000 / 60; // 60 / second 842 private int mAutoScrollX = 0; 843 private int mAutoScrollY = 0; 844 private int mMinAutoScrollX = 0; 845 private int mMaxAutoScrollX = 0; 846 private int mMinAutoScrollY = 0; 847 private int mMaxAutoScrollY = 0; 848 private Rect mScrollingLayerBounds = new Rect(); 849 private boolean mSentAutoScrollMessage = false; 850 851 // used for serializing asynchronously handled touch events. 852 private final TouchEventQueue mTouchEventQueue = new TouchEventQueue(); 853 854 // Used to notify listeners of a new picture. 855 private PictureListener mPictureListener; 856 /** 857 * Interface to listen for new pictures as they change. 858 * @deprecated This interface is now obsolete. 859 */ 860 @Deprecated 861 public interface PictureListener { 862 /** 863 * Notify the listener that the picture has changed. 864 * @param view The WebView that owns the picture. 865 * @param picture The new picture. 866 * @deprecated This method is now obsolete. 867 */ 868 @Deprecated 869 public void onNewPicture(WebView view, Picture picture); 870 } 871 872 // FIXME: Want to make this public, but need to change the API file. 873 public /*static*/ class HitTestResult { 874 /** 875 * Default HitTestResult, where the target is unknown 876 */ 877 public static final int UNKNOWN_TYPE = 0; 878 /** 879 * HitTestResult for hitting a HTML::a tag 880 */ 881 public static final int ANCHOR_TYPE = 1; 882 /** 883 * HitTestResult for hitting a phone number 884 */ 885 public static final int PHONE_TYPE = 2; 886 /** 887 * HitTestResult for hitting a map address 888 */ 889 public static final int GEO_TYPE = 3; 890 /** 891 * HitTestResult for hitting an email address 892 */ 893 public static final int EMAIL_TYPE = 4; 894 /** 895 * HitTestResult for hitting an HTML::img tag 896 */ 897 public static final int IMAGE_TYPE = 5; 898 /** 899 * HitTestResult for hitting a HTML::a tag which contains HTML::img 900 */ 901 public static final int IMAGE_ANCHOR_TYPE = 6; 902 /** 903 * HitTestResult for hitting a HTML::a tag with src=http 904 */ 905 public static final int SRC_ANCHOR_TYPE = 7; 906 /** 907 * HitTestResult for hitting a HTML::a tag with src=http + HTML::img 908 */ 909 public static final int SRC_IMAGE_ANCHOR_TYPE = 8; 910 /** 911 * HitTestResult for hitting an edit text area 912 */ 913 public static final int EDIT_TEXT_TYPE = 9; 914 915 private int mType; 916 private String mExtra; 917 918 HitTestResult() { 919 mType = UNKNOWN_TYPE; 920 } 921 922 private void setType(int type) { 923 mType = type; 924 } 925 926 private void setExtra(String extra) { 927 mExtra = extra; 928 } 929 930 public int getType() { 931 return mType; 932 } 933 934 public String getExtra() { 935 return mExtra; 936 } 937 } 938 939 /** 940 * Construct a new WebView with a Context object. 941 * @param context A Context object used to access application assets. 942 */ 943 public WebView(Context context) { 944 this(context, null); 945 } 946 947 /** 948 * Construct a new WebView with layout parameters. 949 * @param context A Context object used to access application assets. 950 * @param attrs An AttributeSet passed to our parent. 951 */ 952 public WebView(Context context, AttributeSet attrs) { 953 this(context, attrs, com.android.internal.R.attr.webViewStyle); 954 } 955 956 /** 957 * Construct a new WebView with layout parameters and a default style. 958 * @param context A Context object used to access application assets. 959 * @param attrs An AttributeSet passed to our parent. 960 * @param defStyle The default style resource ID. 961 */ 962 public WebView(Context context, AttributeSet attrs, int defStyle) { 963 this(context, attrs, defStyle, false); 964 } 965 966 /** 967 * Construct a new WebView with layout parameters and a default style. 968 * @param context A Context object used to access application assets. 969 * @param attrs An AttributeSet passed to our parent. 970 * @param defStyle The default style resource ID. 971 */ 972 public WebView(Context context, AttributeSet attrs, int defStyle, 973 boolean privateBrowsing) { 974 this(context, attrs, defStyle, null, privateBrowsing); 975 } 976 977 /** 978 * Construct a new WebView with layout parameters, a default style and a set 979 * of custom Javscript interfaces to be added to the WebView at initialization 980 * time. This guarantees that these interfaces will be available when the JS 981 * context is initialized. 982 * @param context A Context object used to access application assets. 983 * @param attrs An AttributeSet passed to our parent. 984 * @param defStyle The default style resource ID. 985 * @param javaScriptInterfaces is a Map of interface names, as keys, and 986 * object implementing those interfaces, as values. 987 * @hide pending API council approval. 988 */ 989 protected WebView(Context context, AttributeSet attrs, int defStyle, 990 Map<String, Object> javaScriptInterfaces, boolean privateBrowsing) { 991 super(context, attrs, defStyle); 992 993 // Used by the chrome stack to find application paths 994 JniUtil.setContext(context); 995 996 mCallbackProxy = new CallbackProxy(context, this); 997 mViewManager = new ViewManager(this); 998 L10nUtils.setApplicationContext(context.getApplicationContext()); 999 mWebViewCore = new WebViewCore(context, this, mCallbackProxy, javaScriptInterfaces); 1000 mDatabase = WebViewDatabase.getInstance(context); 1001 mScroller = new OverScroller(context, null, 0, 0, false); //TODO Use OverScroller's flywheel 1002 mZoomManager = new ZoomManager(this, mCallbackProxy); 1003 1004 /* The init method must follow the creation of certain member variables, 1005 * such as the mZoomManager. 1006 */ 1007 init(); 1008 setupPackageListener(context); 1009 setupProxyListener(context); 1010 updateMultiTouchSupport(context); 1011 1012 if (privateBrowsing) { 1013 startPrivateBrowsing(); 1014 } 1015 1016 mAutoFillData = new WebViewCore.AutoFillData(); 1017 } 1018 1019 private static class ProxyReceiver extends BroadcastReceiver { 1020 @Override 1021 public void onReceive(Context context, Intent intent) { 1022 if (intent.getAction().equals(Proxy.PROXY_CHANGE_ACTION)) { 1023 handleProxyBroadcast(intent); 1024 } 1025 } 1026 } 1027 1028 /* 1029 * A variable to track if there is a receiver added for PROXY_CHANGE_ACTION 1030 */ 1031 private static boolean sProxyReceiverAdded; 1032 1033 private static synchronized void setupProxyListener(Context context) { 1034 if (sProxyReceiverAdded) { 1035 return; 1036 } 1037 IntentFilter filter = new IntentFilter(); 1038 filter.addAction(Proxy.PROXY_CHANGE_ACTION); 1039 Intent currentProxy = context.getApplicationContext().registerReceiver( 1040 new ProxyReceiver(), filter); 1041 sProxyReceiverAdded = true; 1042 if (currentProxy != null) { 1043 handleProxyBroadcast(currentProxy); 1044 } 1045 } 1046 1047 private static void handleProxyBroadcast(Intent intent) { 1048 ProxyProperties proxyProperties = (ProxyProperties)intent.getExtra(Proxy.EXTRA_PROXY_INFO); 1049 if (proxyProperties == null || proxyProperties.getHost() == null) { 1050 WebViewCore.sendStaticMessage(EventHub.PROXY_CHANGED, ""); 1051 return; 1052 } 1053 1054 String host = proxyProperties.getHost(); 1055 int port = proxyProperties.getPort(); 1056 if (port != 0) 1057 host += ":" + port; 1058 1059 // TODO: Handle exclusion list 1060 // The plan is to make an AndroidProxyResolver, and handle the blacklist 1061 // there 1062 String exclusionList = proxyProperties.getExclusionList(); 1063 WebViewCore.sendStaticMessage(EventHub.PROXY_CHANGED, host); 1064 } 1065 1066 /* 1067 * A variable to track if there is a receiver added for ACTION_PACKAGE_ADDED 1068 * or ACTION_PACKAGE_REMOVED. 1069 */ 1070 private static boolean sPackageInstallationReceiverAdded = false; 1071 1072 /* 1073 * A set of Google packages we monitor for the 1074 * navigator.isApplicationInstalled() API. Add additional packages as 1075 * needed. 1076 */ 1077 private static Set<String> sGoogleApps; 1078 static { 1079 sGoogleApps = new HashSet<String>(); 1080 sGoogleApps.add("com.google.android.youtube"); 1081 } 1082 1083 private static class PackageListener extends BroadcastReceiver { 1084 @Override 1085 public void onReceive(Context context, Intent intent) { 1086 final String action = intent.getAction(); 1087 final String packageName = intent.getData().getSchemeSpecificPart(); 1088 final boolean replacing = intent.getBooleanExtra(Intent.EXTRA_REPLACING, false); 1089 if (Intent.ACTION_PACKAGE_REMOVED.equals(action) && replacing) { 1090 // if it is replacing, refreshPlugins() when adding 1091 return; 1092 } 1093 1094 if (sGoogleApps.contains(packageName)) { 1095 if (Intent.ACTION_PACKAGE_ADDED.equals(action)) { 1096 WebViewCore.sendStaticMessage(EventHub.ADD_PACKAGE_NAME, packageName); 1097 } else { 1098 WebViewCore.sendStaticMessage(EventHub.REMOVE_PACKAGE_NAME, packageName); 1099 } 1100 } 1101 1102 PluginManager pm = PluginManager.getInstance(context); 1103 if (pm.containsPluginPermissionAndSignatures(packageName)) { 1104 pm.refreshPlugins(Intent.ACTION_PACKAGE_ADDED.equals(action)); 1105 } 1106 } 1107 } 1108 1109 private void setupPackageListener(Context context) { 1110 1111 /* 1112 * we must synchronize the instance check and the creation of the 1113 * receiver to ensure that only ONE receiver exists for all WebView 1114 * instances. 1115 */ 1116 synchronized (WebView.class) { 1117 1118 // if the receiver already exists then we do not need to register it 1119 // again 1120 if (sPackageInstallationReceiverAdded) { 1121 return; 1122 } 1123 1124 IntentFilter filter = new IntentFilter(Intent.ACTION_PACKAGE_ADDED); 1125 filter.addAction(Intent.ACTION_PACKAGE_REMOVED); 1126 filter.addDataScheme("package"); 1127 BroadcastReceiver packageListener = new PackageListener(); 1128 context.getApplicationContext().registerReceiver(packageListener, filter); 1129 sPackageInstallationReceiverAdded = true; 1130 } 1131 1132 // check if any of the monitored apps are already installed 1133 AsyncTask<Void, Void, Set<String>> task = new AsyncTask<Void, Void, Set<String>>() { 1134 1135 @Override 1136 protected Set<String> doInBackground(Void... unused) { 1137 Set<String> installedPackages = new HashSet<String>(); 1138 PackageManager pm = mContext.getPackageManager(); 1139 List<PackageInfo> packages = pm.getInstalledPackages(0); 1140 for (PackageInfo p : packages) { 1141 if (sGoogleApps.contains(p.packageName)) { 1142 installedPackages.add(p.packageName); 1143 } 1144 } 1145 return installedPackages; 1146 } 1147 1148 // Executes on the UI thread 1149 @Override 1150 protected void onPostExecute(Set<String> installedPackages) { 1151 if (mWebViewCore != null) { 1152 mWebViewCore.sendMessage(EventHub.ADD_PACKAGE_NAMES, installedPackages); 1153 } 1154 } 1155 }; 1156 task.execute(); 1157 } 1158 1159 void updateMultiTouchSupport(Context context) { 1160 mZoomManager.updateMultiTouchSupport(context); 1161 } 1162 1163 private void init() { 1164 setWillNotDraw(false); 1165 setFocusable(true); 1166 setFocusableInTouchMode(true); 1167 setClickable(true); 1168 setLongClickable(true); 1169 1170 final ViewConfiguration configuration = ViewConfiguration.get(getContext()); 1171 int slop = configuration.getScaledTouchSlop(); 1172 mTouchSlopSquare = slop * slop; 1173 mMinLockSnapReverseDistance = slop; 1174 slop = configuration.getScaledDoubleTapSlop(); 1175 mDoubleTapSlopSquare = slop * slop; 1176 final float density = getContext().getResources().getDisplayMetrics().density; 1177 // use one line height, 16 based on our current default font, for how 1178 // far we allow a touch be away from the edge of a link 1179 mNavSlop = (int) (16 * density); 1180 mZoomManager.init(density); 1181 mMaximumFling = configuration.getScaledMaximumFlingVelocity(); 1182 1183 // Compute the inverse of the density squared. 1184 DRAG_LAYER_INVERSE_DENSITY_SQUARED = 1 / (density * density); 1185 1186 mOverscrollDistance = configuration.getScaledOverscrollDistance(); 1187 mOverflingDistance = configuration.getScaledOverflingDistance(); 1188 1189 setScrollBarStyle(super.getScrollBarStyle()); 1190 // Initially use a size of two, since the user is likely to only hold 1191 // down two keys at a time (shift + another key) 1192 mKeysPressed = new Vector<Integer>(2); 1193 } 1194 1195 /** 1196 * Adds accessibility APIs to JavaScript. 1197 * 1198 * Note: This method is responsible to performing the necessary 1199 * check if the accessibility APIs should be exposed. 1200 */ 1201 private void addAccessibilityApisToJavaScript() { 1202 if (AccessibilityManager.getInstance(mContext).isEnabled() 1203 && getSettings().getJavaScriptEnabled()) { 1204 // exposing the TTS for now ... 1205 mTextToSpeech = new TextToSpeech(getContext(), null); 1206 addJavascriptInterface(mTextToSpeech, ALIAS_ACCESSIBILITY_JS_INTERFACE); 1207 } 1208 } 1209 1210 /** 1211 * Removes accessibility APIs from JavaScript. 1212 */ 1213 private void removeAccessibilityApisFromJavaScript() { 1214 // exposing the TTS for now ... 1215 if (mTextToSpeech != null) { 1216 removeJavascriptInterface(ALIAS_ACCESSIBILITY_JS_INTERFACE); 1217 mTextToSpeech.shutdown(); 1218 mTextToSpeech = null; 1219 } 1220 } 1221 1222 @Override 1223 public void setOverScrollMode(int mode) { 1224 super.setOverScrollMode(mode); 1225 if (mode != OVER_SCROLL_NEVER) { 1226 if (mOverScrollGlow == null) { 1227 mOverScrollGlow = new OverScrollGlow(this); 1228 } 1229 } else { 1230 mOverScrollGlow = null; 1231 } 1232 } 1233 1234 /* package */void updateDefaultZoomDensity(int zoomDensity) { 1235 final float density = mContext.getResources().getDisplayMetrics().density 1236 * 100 / zoomDensity; 1237 mNavSlop = (int) (16 * density); 1238 mZoomManager.updateDefaultZoomDensity(density); 1239 } 1240 1241 /* package */ boolean onSavePassword(String schemePlusHost, String username, 1242 String password, final Message resumeMsg) { 1243 boolean rVal = false; 1244 if (resumeMsg == null) { 1245 // null resumeMsg implies saving password silently 1246 mDatabase.setUsernamePassword(schemePlusHost, username, password); 1247 } else { 1248 final Message remember = mPrivateHandler.obtainMessage( 1249 REMEMBER_PASSWORD); 1250 remember.getData().putString("host", schemePlusHost); 1251 remember.getData().putString("username", username); 1252 remember.getData().putString("password", password); 1253 remember.obj = resumeMsg; 1254 1255 final Message neverRemember = mPrivateHandler.obtainMessage( 1256 NEVER_REMEMBER_PASSWORD); 1257 neverRemember.getData().putString("host", schemePlusHost); 1258 neverRemember.getData().putString("username", username); 1259 neverRemember.getData().putString("password", password); 1260 neverRemember.obj = resumeMsg; 1261 1262 new AlertDialog.Builder(getContext()) 1263 .setTitle(com.android.internal.R.string.save_password_label) 1264 .setMessage(com.android.internal.R.string.save_password_message) 1265 .setPositiveButton(com.android.internal.R.string.save_password_notnow, 1266 new DialogInterface.OnClickListener() { 1267 public void onClick(DialogInterface dialog, int which) { 1268 resumeMsg.sendToTarget(); 1269 } 1270 }) 1271 .setNeutralButton(com.android.internal.R.string.save_password_remember, 1272 new DialogInterface.OnClickListener() { 1273 public void onClick(DialogInterface dialog, int which) { 1274 remember.sendToTarget(); 1275 } 1276 }) 1277 .setNegativeButton(com.android.internal.R.string.save_password_never, 1278 new DialogInterface.OnClickListener() { 1279 public void onClick(DialogInterface dialog, int which) { 1280 neverRemember.sendToTarget(); 1281 } 1282 }) 1283 .setOnCancelListener(new OnCancelListener() { 1284 public void onCancel(DialogInterface dialog) { 1285 resumeMsg.sendToTarget(); 1286 } 1287 }).show(); 1288 // Return true so that WebViewCore will pause while the dialog is 1289 // up. 1290 rVal = true; 1291 } 1292 return rVal; 1293 } 1294 1295 @Override 1296 public void setScrollBarStyle(int style) { 1297 if (style == View.SCROLLBARS_INSIDE_INSET 1298 || style == View.SCROLLBARS_OUTSIDE_INSET) { 1299 mOverlayHorizontalScrollbar = mOverlayVerticalScrollbar = false; 1300 } else { 1301 mOverlayHorizontalScrollbar = mOverlayVerticalScrollbar = true; 1302 } 1303 super.setScrollBarStyle(style); 1304 } 1305 1306 /** 1307 * Specify whether the horizontal scrollbar has overlay style. 1308 * @param overlay TRUE if horizontal scrollbar should have overlay style. 1309 */ 1310 public void setHorizontalScrollbarOverlay(boolean overlay) { 1311 mOverlayHorizontalScrollbar = overlay; 1312 } 1313 1314 /** 1315 * Specify whether the vertical scrollbar has overlay style. 1316 * @param overlay TRUE if vertical scrollbar should have overlay style. 1317 */ 1318 public void setVerticalScrollbarOverlay(boolean overlay) { 1319 mOverlayVerticalScrollbar = overlay; 1320 } 1321 1322 /** 1323 * Return whether horizontal scrollbar has overlay style 1324 * @return TRUE if horizontal scrollbar has overlay style. 1325 */ 1326 public boolean overlayHorizontalScrollbar() { 1327 return mOverlayHorizontalScrollbar; 1328 } 1329 1330 /** 1331 * Return whether vertical scrollbar has overlay style 1332 * @return TRUE if vertical scrollbar has overlay style. 1333 */ 1334 public boolean overlayVerticalScrollbar() { 1335 return mOverlayVerticalScrollbar; 1336 } 1337 1338 /* 1339 * Return the width of the view where the content of WebView should render 1340 * to. 1341 * Note: this can be called from WebCoreThread. 1342 */ 1343 /* package */ int getViewWidth() { 1344 if (!isVerticalScrollBarEnabled() || mOverlayVerticalScrollbar) { 1345 return getWidth(); 1346 } else { 1347 return Math.max(0, getWidth() - getVerticalScrollbarWidth()); 1348 } 1349 } 1350 1351 /** 1352 * returns the height of the titlebarview (if any). Does not care about 1353 * scrolling 1354 * @hide 1355 */ 1356 protected int getTitleHeight() { 1357 return mTitleBar != null ? mTitleBar.getHeight() : 0; 1358 } 1359 1360 /* 1361 * Return the amount of the titlebarview (if any) that is visible 1362 * 1363 * @hide 1364 */ 1365 public int getVisibleTitleHeight() { 1366 // need to restrict mScrollY due to over scroll 1367 return Math.max(getTitleHeight() - Math.max(0, mScrollY), 0); 1368 } 1369 1370 /* 1371 * Return the height of the view where the content of WebView should render 1372 * to. Note that this excludes mTitleBar, if there is one. 1373 * Note: this can be called from WebCoreThread. 1374 */ 1375 /* package */ int getViewHeight() { 1376 return getViewHeightWithTitle() - getVisibleTitleHeight(); 1377 } 1378 1379 private int getViewHeightWithTitle() { 1380 int height = getHeight(); 1381 if (isHorizontalScrollBarEnabled() && !mOverlayHorizontalScrollbar) { 1382 height -= getHorizontalScrollbarHeight(); 1383 } 1384 return height; 1385 } 1386 1387 /** 1388 * @return The SSL certificate for the main top-level page or null if 1389 * there is no certificate (the site is not secure). 1390 */ 1391 public SslCertificate getCertificate() { 1392 return mCertificate; 1393 } 1394 1395 /** 1396 * Sets the SSL certificate for the main top-level page. 1397 */ 1398 public void setCertificate(SslCertificate certificate) { 1399 if (DebugFlags.WEB_VIEW) { 1400 Log.v(LOGTAG, "setCertificate=" + certificate); 1401 } 1402 // here, the certificate can be null (if the site is not secure) 1403 mCertificate = certificate; 1404 } 1405 1406 //------------------------------------------------------------------------- 1407 // Methods called by activity 1408 //------------------------------------------------------------------------- 1409 1410 /** 1411 * Save the username and password for a particular host in the WebView's 1412 * internal database. 1413 * @param host The host that required the credentials. 1414 * @param username The username for the given host. 1415 * @param password The password for the given host. 1416 */ 1417 public void savePassword(String host, String username, String password) { 1418 mDatabase.setUsernamePassword(host, username, password); 1419 } 1420 1421 /** 1422 * Set the HTTP authentication credentials for a given host and realm. 1423 * 1424 * @param host The host for the credentials. 1425 * @param realm The realm for the credentials. 1426 * @param username The username for the password. If it is null, it means 1427 * password can't be saved. 1428 * @param password The password 1429 */ 1430 public void setHttpAuthUsernamePassword(String host, String realm, 1431 String username, String password) { 1432 mDatabase.setHttpAuthUsernamePassword(host, realm, username, password); 1433 } 1434 1435 /** 1436 * Retrieve the HTTP authentication username and password for a given 1437 * host & realm pair 1438 * 1439 * @param host The host for which the credentials apply. 1440 * @param realm The realm for which the credentials apply. 1441 * @return String[] if found, String[0] is username, which can be null and 1442 * String[1] is password. Return null if it can't find anything. 1443 */ 1444 public String[] getHttpAuthUsernamePassword(String host, String realm) { 1445 return mDatabase.getHttpAuthUsernamePassword(host, realm); 1446 } 1447 1448 /** 1449 * Remove Find or Select ActionModes, if active. 1450 */ 1451 private void clearActionModes() { 1452 if (mSelectCallback != null) { 1453 mSelectCallback.finish(); 1454 } 1455 if (mFindCallback != null) { 1456 mFindCallback.finish(); 1457 } 1458 } 1459 1460 /** 1461 * Called to clear state when moving from one page to another, or changing 1462 * in some other way that makes elements associated with the current page 1463 * (such as WebTextView or ActionModes) no longer relevant. 1464 */ 1465 private void clearHelpers() { 1466 clearTextEntry(); 1467 clearActionModes(); 1468 dismissFullScreenMode(); 1469 } 1470 1471 /** 1472 * Destroy the internal state of the WebView. This method should be called 1473 * after the WebView has been removed from the view system. No other 1474 * methods may be called on a WebView after destroy. 1475 */ 1476 public void destroy() { 1477 clearHelpers(); 1478 if (mListBoxDialog != null) { 1479 mListBoxDialog.dismiss(); 1480 mListBoxDialog = null; 1481 } 1482 if (mNativeClass != 0) nativeStopGL(); 1483 if (mWebViewCore != null) { 1484 // Set the handlers to null before destroying WebViewCore so no 1485 // more messages will be posted. 1486 mCallbackProxy.setWebViewClient(null); 1487 mCallbackProxy.setWebChromeClient(null); 1488 // Tell WebViewCore to destroy itself 1489 synchronized (this) { 1490 WebViewCore webViewCore = mWebViewCore; 1491 mWebViewCore = null; // prevent using partial webViewCore 1492 webViewCore.destroy(); 1493 } 1494 // Remove any pending messages that might not be serviced yet. 1495 mPrivateHandler.removeCallbacksAndMessages(null); 1496 mCallbackProxy.removeCallbacksAndMessages(null); 1497 // Wake up the WebCore thread just in case it is waiting for a 1498 // JavaScript dialog. 1499 synchronized (mCallbackProxy) { 1500 mCallbackProxy.notify(); 1501 } 1502 } 1503 if (mNativeClass != 0) { 1504 nativeDestroy(); 1505 mNativeClass = 0; 1506 } 1507 } 1508 1509 /** 1510 * Enables platform notifications of data state and proxy changes. 1511 * @deprecated Obsolete - platform notifications are always enabled. 1512 */ 1513 @Deprecated 1514 public static void enablePlatformNotifications() { 1515 Network.enablePlatformNotifications(); 1516 } 1517 1518 /** 1519 * If platform notifications are enabled, this should be called 1520 * from the Activity's onPause() or onStop(). 1521 * @deprecated Obsolete - platform notifications are always enabled. 1522 */ 1523 @Deprecated 1524 public static void disablePlatformNotifications() { 1525 Network.disablePlatformNotifications(); 1526 } 1527 1528 /** 1529 * Sets JavaScript engine flags. 1530 * 1531 * @param flags JS engine flags in a String 1532 * 1533 * @hide pending API solidification 1534 */ 1535 public void setJsFlags(String flags) { 1536 mWebViewCore.sendMessage(EventHub.SET_JS_FLAGS, flags); 1537 } 1538 1539 /** 1540 * Inform WebView of the network state. This is used to set 1541 * the JavaScript property window.navigator.isOnline and 1542 * generates the online/offline event as specified in HTML5, sec. 5.7.7 1543 * @param networkUp boolean indicating if network is available 1544 */ 1545 public void setNetworkAvailable(boolean networkUp) { 1546 mWebViewCore.sendMessage(EventHub.SET_NETWORK_STATE, 1547 networkUp ? 1 : 0, 0); 1548 } 1549 1550 /** 1551 * Inform WebView about the current network type. 1552 * {@hide} 1553 */ 1554 public void setNetworkType(String type, String subtype) { 1555 Map<String, String> map = new HashMap<String, String>(); 1556 map.put("type", type); 1557 map.put("subtype", subtype); 1558 mWebViewCore.sendMessage(EventHub.SET_NETWORK_TYPE, map); 1559 } 1560 /** 1561 * Save the state of this WebView used in 1562 * {@link android.app.Activity#onSaveInstanceState}. Please note that this 1563 * method no longer stores the display data for this WebView. The previous 1564 * behavior could potentially leak files if {@link #restoreState} was never 1565 * called. See {@link #savePicture} and {@link #restorePicture} for saving 1566 * and restoring the display data. 1567 * @param outState The Bundle to store the WebView state. 1568 * @return The same copy of the back/forward list used to save the state. If 1569 * saveState fails, the returned list will be null. 1570 * @see #savePicture 1571 * @see #restorePicture 1572 */ 1573 public WebBackForwardList saveState(Bundle outState) { 1574 if (outState == null) { 1575 return null; 1576 } 1577 // We grab a copy of the back/forward list because a client of WebView 1578 // may have invalidated the history list by calling clearHistory. 1579 WebBackForwardList list = copyBackForwardList(); 1580 final int currentIndex = list.getCurrentIndex(); 1581 final int size = list.getSize(); 1582 // We should fail saving the state if the list is empty or the index is 1583 // not in a valid range. 1584 if (currentIndex < 0 || currentIndex >= size || size == 0) { 1585 return null; 1586 } 1587 outState.putInt("index", currentIndex); 1588 // FIXME: This should just be a byte[][] instead of ArrayList but 1589 // Parcel.java does not have the code to handle multi-dimensional 1590 // arrays. 1591 ArrayList<byte[]> history = new ArrayList<byte[]>(size); 1592 for (int i = 0; i < size; i++) { 1593 WebHistoryItem item = list.getItemAtIndex(i); 1594 if (null == item) { 1595 // FIXME: this shouldn't happen 1596 // need to determine how item got set to null 1597 Log.w(LOGTAG, "saveState: Unexpected null history item."); 1598 return null; 1599 } 1600 byte[] data = item.getFlattenedData(); 1601 if (data == null) { 1602 // It would be very odd to not have any data for a given history 1603 // item. And we will fail to rebuild the history list without 1604 // flattened data. 1605 return null; 1606 } 1607 history.add(data); 1608 } 1609 outState.putSerializable("history", history); 1610 if (mCertificate != null) { 1611 outState.putBundle("certificate", 1612 SslCertificate.saveState(mCertificate)); 1613 } 1614 outState.putBoolean("privateBrowsingEnabled", isPrivateBrowsingEnabled()); 1615 mZoomManager.saveZoomState(outState); 1616 return list; 1617 } 1618 1619 /** 1620 * Save the current display data to the Bundle given. Used in conjunction 1621 * with {@link #saveState}. 1622 * @param b A Bundle to store the display data. 1623 * @param dest The file to store the serialized picture data. Will be 1624 * overwritten with this WebView's picture data. 1625 * @return True if the picture was successfully saved. 1626 * @deprecated This method is now obsolete. 1627 */ 1628 @Deprecated 1629 public boolean savePicture(Bundle b, final File dest) { 1630 if (dest == null || b == null) { 1631 return false; 1632 } 1633 final Picture p = capturePicture(); 1634 // Use a temporary file while writing to ensure the destination file 1635 // contains valid data. 1636 final File temp = new File(dest.getPath() + ".writing"); 1637 new Thread(new Runnable() { 1638 public void run() { 1639 FileOutputStream out = null; 1640 try { 1641 out = new FileOutputStream(temp); 1642 p.writeToStream(out); 1643 // Writing the picture succeeded, rename the temporary file 1644 // to the destination. 1645 temp.renameTo(dest); 1646 } catch (Exception e) { 1647 // too late to do anything about it. 1648 } finally { 1649 if (out != null) { 1650 try { 1651 out.close(); 1652 } catch (Exception e) { 1653 // Can't do anything about that 1654 } 1655 } 1656 temp.delete(); 1657 } 1658 } 1659 }).start(); 1660 // now update the bundle 1661 b.putInt("scrollX", mScrollX); 1662 b.putInt("scrollY", mScrollY); 1663 mZoomManager.saveZoomState(b); 1664 return true; 1665 } 1666 1667 private void restoreHistoryPictureFields(Picture p, Bundle b) { 1668 int sx = b.getInt("scrollX", 0); 1669 int sy = b.getInt("scrollY", 0); 1670 1671 mDrawHistory = true; 1672 mHistoryPicture = p; 1673 mScrollX = sx; 1674 mScrollY = sy; 1675 mZoomManager.restoreZoomState(b); 1676 final float scale = mZoomManager.getScale(); 1677 mHistoryWidth = Math.round(p.getWidth() * scale); 1678 mHistoryHeight = Math.round(p.getHeight() * scale); 1679 1680 invalidate(); 1681 } 1682 1683 /** 1684 * Restore the display data that was save in {@link #savePicture}. Used in 1685 * conjunction with {@link #restoreState}. 1686 * @param b A Bundle containing the saved display data. 1687 * @param src The file where the picture data was stored. 1688 * @return True if the picture was successfully restored. 1689 * @deprecated This method is now obsolete. 1690 */ 1691 @Deprecated 1692 public boolean restorePicture(Bundle b, File src) { 1693 if (src == null || b == null) { 1694 return false; 1695 } 1696 if (!src.exists()) { 1697 return false; 1698 } 1699 try { 1700 final FileInputStream in = new FileInputStream(src); 1701 final Bundle copy = new Bundle(b); 1702 new Thread(new Runnable() { 1703 public void run() { 1704 try { 1705 final Picture p = Picture.createFromStream(in); 1706 if (p != null) { 1707 // Post a runnable on the main thread to update the 1708 // history picture fields. 1709 mPrivateHandler.post(new Runnable() { 1710 public void run() { 1711 restoreHistoryPictureFields(p, copy); 1712 } 1713 }); 1714 } 1715 } finally { 1716 try { 1717 in.close(); 1718 } catch (Exception e) { 1719 // Nothing we can do now. 1720 } 1721 } 1722 } 1723 }).start(); 1724 } catch (FileNotFoundException e){ 1725 e.printStackTrace(); 1726 } 1727 return true; 1728 } 1729 1730 /** 1731 * Restore the state of this WebView from the given map used in 1732 * {@link android.app.Activity#onRestoreInstanceState}. This method should 1733 * be called to restore the state of the WebView before using the object. If 1734 * it is called after the WebView has had a chance to build state (load 1735 * pages, create a back/forward list, etc.) there may be undesirable 1736 * side-effects. Please note that this method no longer restores the 1737 * display data for this WebView. See {@link #savePicture} and {@link 1738 * #restorePicture} for saving and restoring the display data. 1739 * @param inState The incoming Bundle of state. 1740 * @return The restored back/forward list or null if restoreState failed. 1741 * @see #savePicture 1742 * @see #restorePicture 1743 */ 1744 public WebBackForwardList restoreState(Bundle inState) { 1745 WebBackForwardList returnList = null; 1746 if (inState == null) { 1747 return returnList; 1748 } 1749 if (inState.containsKey("index") && inState.containsKey("history")) { 1750 mCertificate = SslCertificate.restoreState( 1751 inState.getBundle("certificate")); 1752 1753 final WebBackForwardList list = mCallbackProxy.getBackForwardList(); 1754 final int index = inState.getInt("index"); 1755 // We can't use a clone of the list because we need to modify the 1756 // shared copy, so synchronize instead to prevent concurrent 1757 // modifications. 1758 synchronized (list) { 1759 final List<byte[]> history = 1760 (List<byte[]>) inState.getSerializable("history"); 1761 final int size = history.size(); 1762 // Check the index bounds so we don't crash in native code while 1763 // restoring the history index. 1764 if (index < 0 || index >= size) { 1765 return null; 1766 } 1767 for (int i = 0; i < size; i++) { 1768 byte[] data = history.remove(0); 1769 if (data == null) { 1770 // If we somehow have null data, we cannot reconstruct 1771 // the item and thus our history list cannot be rebuilt. 1772 return null; 1773 } 1774 WebHistoryItem item = new WebHistoryItem(data); 1775 list.addHistoryItem(item); 1776 } 1777 // Grab the most recent copy to return to the caller. 1778 returnList = copyBackForwardList(); 1779 // Update the copy to have the correct index. 1780 returnList.setCurrentIndex(index); 1781 } 1782 // Restore private browsing setting. 1783 if (inState.getBoolean("privateBrowsingEnabled")) { 1784 getSettings().setPrivateBrowsingEnabled(true); 1785 } 1786 mZoomManager.restoreZoomState(inState); 1787 // Remove all pending messages because we are restoring previous 1788 // state. 1789 mWebViewCore.removeMessages(); 1790 // Send a restore state message. 1791 mWebViewCore.sendMessage(EventHub.RESTORE_STATE, index); 1792 } 1793 return returnList; 1794 } 1795 1796 /** 1797 * Load the given url with the extra headers. 1798 * @param url The url of the resource to load. 1799 * @param extraHeaders The extra headers sent with this url. This should not 1800 * include the common headers like "user-agent". If it does, it 1801 * will be replaced by the intrinsic value of the WebView. 1802 */ 1803 public void loadUrl(String url, Map<String, String> extraHeaders) { 1804 switchOutDrawHistory(); 1805 WebViewCore.GetUrlData arg = new WebViewCore.GetUrlData(); 1806 arg.mUrl = url; 1807 arg.mExtraHeaders = extraHeaders; 1808 mWebViewCore.sendMessage(EventHub.LOAD_URL, arg); 1809 clearHelpers(); 1810 } 1811 1812 /** 1813 * Load the given url. 1814 * @param url The url of the resource to load. 1815 */ 1816 public void loadUrl(String url) { 1817 if (url == null) { 1818 return; 1819 } 1820 loadUrl(url, null); 1821 } 1822 1823 /** 1824 * Load the url with postData using "POST" method into the WebView. If url 1825 * is not a network url, it will be loaded with {link 1826 * {@link #loadUrl(String)} instead. 1827 * 1828 * @param url The url of the resource to load. 1829 * @param postData The data will be passed to "POST" request. 1830 */ 1831 public void postUrl(String url, byte[] postData) { 1832 if (URLUtil.isNetworkUrl(url)) { 1833 switchOutDrawHistory(); 1834 WebViewCore.PostUrlData arg = new WebViewCore.PostUrlData(); 1835 arg.mUrl = url; 1836 arg.mPostData = postData; 1837 mWebViewCore.sendMessage(EventHub.POST_URL, arg); 1838 clearHelpers(); 1839 } else { 1840 loadUrl(url); 1841 } 1842 } 1843 1844 /** 1845 * Load the given data into the WebView. This will load the data into 1846 * WebView using the data: scheme. Content loaded through this mechanism 1847 * does not have the ability to load content from the network. 1848 * @param data A String of data in the given encoding. The date must 1849 * be URI-escaped -- '#', '%', '\', '?' should be replaced by %23, %25, 1850 * %27, %3f respectively. 1851 * @param mimeType The MIMEType of the data. i.e. text/html, image/jpeg 1852 * @param encoding The encoding of the data. i.e. utf-8, base64 1853 */ 1854 public void loadData(String data, String mimeType, String encoding) { 1855 loadUrl("data:" + mimeType + ";" + encoding + "," + data); 1856 } 1857 1858 /** 1859 * Load the given data into the WebView, use the provided URL as the base 1860 * URL for the content. The base URL is the URL that represents the page 1861 * that is loaded through this interface. As such, it is used to resolve any 1862 * relative URLs. The historyUrl is used for the history entry. 1863 * <p> 1864 * Note for post 1.0. Due to the change in the WebKit, the access to asset 1865 * files through "file:///android_asset/" for the sub resources is more 1866 * restricted. If you provide null or empty string as baseUrl, you won't be 1867 * able to access asset files. If the baseUrl is anything other than 1868 * http(s)/ftp(s)/about/javascript as scheme, you can access asset files for 1869 * sub resources. 1870 * 1871 * @param baseUrl Url to resolve relative paths with, if null defaults to 1872 * "about:blank" 1873 * @param data A String of data in the given encoding. 1874 * @param mimeType The MIMEType of the data. i.e. text/html. If null, 1875 * defaults to "text/html" 1876 * @param encoding The encoding of the data. i.e. utf-8, us-ascii 1877 * @param historyUrl URL to use as the history entry. Can be null. 1878 */ 1879 public void loadDataWithBaseURL(String baseUrl, String data, 1880 String mimeType, String encoding, String historyUrl) { 1881 1882 if (baseUrl != null && baseUrl.toLowerCase().startsWith("data:")) { 1883 loadData(data, mimeType, encoding); 1884 return; 1885 } 1886 switchOutDrawHistory(); 1887 WebViewCore.BaseUrlData arg = new WebViewCore.BaseUrlData(); 1888 arg.mBaseUrl = baseUrl; 1889 arg.mData = data; 1890 arg.mMimeType = mimeType; 1891 arg.mEncoding = encoding; 1892 arg.mHistoryUrl = historyUrl; 1893 mWebViewCore.sendMessage(EventHub.LOAD_DATA, arg); 1894 clearHelpers(); 1895 } 1896 1897 /** 1898 * Saves the current view as a web archive. 1899 * 1900 * @param filename The filename where the archive should be placed. 1901 */ 1902 public void saveWebArchive(String filename) { 1903 saveWebArchive(filename, false, null); 1904 } 1905 1906 /* package */ static class SaveWebArchiveMessage { 1907 SaveWebArchiveMessage (String basename, boolean autoname, ValueCallback<String> callback) { 1908 mBasename = basename; 1909 mAutoname = autoname; 1910 mCallback = callback; 1911 } 1912 1913 /* package */ final String mBasename; 1914 /* package */ final boolean mAutoname; 1915 /* package */ final ValueCallback<String> mCallback; 1916 /* package */ String mResultFile; 1917 } 1918 1919 /** 1920 * Saves the current view as a web archive. 1921 * 1922 * @param basename The filename where the archive should be placed. 1923 * @param autoname If false, takes basename to be a file. If true, basename 1924 * is assumed to be a directory in which a filename will be 1925 * chosen according to the url of the current page. 1926 * @param callback Called after the web archive has been saved. The 1927 * parameter for onReceiveValue will either be the filename 1928 * under which the file was saved, or null if saving the 1929 * file failed. 1930 */ 1931 public void saveWebArchive(String basename, boolean autoname, ValueCallback<String> callback) { 1932 mWebViewCore.sendMessage(EventHub.SAVE_WEBARCHIVE, 1933 new SaveWebArchiveMessage(basename, autoname, callback)); 1934 } 1935 1936 /** 1937 * Stop the current load. 1938 */ 1939 public void stopLoading() { 1940 // TODO: should we clear all the messages in the queue before sending 1941 // STOP_LOADING? 1942 switchOutDrawHistory(); 1943 mWebViewCore.sendMessage(EventHub.STOP_LOADING); 1944 } 1945 1946 /** 1947 * Reload the current url. 1948 */ 1949 public void reload() { 1950 clearHelpers(); 1951 switchOutDrawHistory(); 1952 mWebViewCore.sendMessage(EventHub.RELOAD); 1953 } 1954 1955 /** 1956 * Return true if this WebView has a back history item. 1957 * @return True iff this WebView has a back history item. 1958 */ 1959 public boolean canGoBack() { 1960 WebBackForwardList l = mCallbackProxy.getBackForwardList(); 1961 synchronized (l) { 1962 if (l.getClearPending()) { 1963 return false; 1964 } else { 1965 return l.getCurrentIndex() > 0; 1966 } 1967 } 1968 } 1969 1970 /** 1971 * Go back in the history of this WebView. 1972 */ 1973 public void goBack() { 1974 goBackOrForward(-1); 1975 } 1976 1977 /** 1978 * Return true if this WebView has a forward history item. 1979 * @return True iff this Webview has a forward history item. 1980 */ 1981 public boolean canGoForward() { 1982 WebBackForwardList l = mCallbackProxy.getBackForwardList(); 1983 synchronized (l) { 1984 if (l.getClearPending()) { 1985 return false; 1986 } else { 1987 return l.getCurrentIndex() < l.getSize() - 1; 1988 } 1989 } 1990 } 1991 1992 /** 1993 * Go forward in the history of this WebView. 1994 */ 1995 public void goForward() { 1996 goBackOrForward(1); 1997 } 1998 1999 /** 2000 * Return true if the page can go back or forward the given 2001 * number of steps. 2002 * @param steps The negative or positive number of steps to move the 2003 * history. 2004 */ 2005 public boolean canGoBackOrForward(int steps) { 2006 WebBackForwardList l = mCallbackProxy.getBackForwardList(); 2007 synchronized (l) { 2008 if (l.getClearPending()) { 2009 return false; 2010 } else { 2011 int newIndex = l.getCurrentIndex() + steps; 2012 return newIndex >= 0 && newIndex < l.getSize(); 2013 } 2014 } 2015 } 2016 2017 /** 2018 * Go to the history item that is the number of steps away from 2019 * the current item. Steps is negative if backward and positive 2020 * if forward. 2021 * @param steps The number of steps to take back or forward in the back 2022 * forward list. 2023 */ 2024 public void goBackOrForward(int steps) { 2025 goBackOrForward(steps, false); 2026 } 2027 2028 private void goBackOrForward(int steps, boolean ignoreSnapshot) { 2029 if (steps != 0) { 2030 clearHelpers(); 2031 mWebViewCore.sendMessage(EventHub.GO_BACK_FORWARD, steps, 2032 ignoreSnapshot ? 1 : 0); 2033 } 2034 } 2035 2036 /** 2037 * Returns true if private browsing is enabled in this WebView. 2038 */ 2039 public boolean isPrivateBrowsingEnabled() { 2040 return getSettings().isPrivateBrowsingEnabled(); 2041 } 2042 2043 private void startPrivateBrowsing() { 2044 getSettings().setPrivateBrowsingEnabled(true); 2045 } 2046 2047 private boolean extendScroll(int y) { 2048 int finalY = mScroller.getFinalY(); 2049 int newY = pinLocY(finalY + y); 2050 if (newY == finalY) return false; 2051 mScroller.setFinalY(newY); 2052 mScroller.extendDuration(computeDuration(0, y)); 2053 return true; 2054 } 2055 2056 /** 2057 * Scroll the contents of the view up by half the view size 2058 * @param top true to jump to the top of the page 2059 * @return true if the page was scrolled 2060 */ 2061 public boolean pageUp(boolean top) { 2062 if (mNativeClass == 0) { 2063 return false; 2064 } 2065 nativeClearCursor(); // start next trackball movement from page edge 2066 if (top) { 2067 // go to the top of the document 2068 return pinScrollTo(mScrollX, 0, true, 0); 2069 } 2070 // Page up 2071 int h = getHeight(); 2072 int y; 2073 if (h > 2 * PAGE_SCROLL_OVERLAP) { 2074 y = -h + PAGE_SCROLL_OVERLAP; 2075 } else { 2076 y = -h / 2; 2077 } 2078 return mScroller.isFinished() ? pinScrollBy(0, y, true, 0) 2079 : extendScroll(y); 2080 } 2081 2082 /** 2083 * Scroll the contents of the view down by half the page size 2084 * @param bottom true to jump to bottom of page 2085 * @return true if the page was scrolled 2086 */ 2087 public boolean pageDown(boolean bottom) { 2088 if (mNativeClass == 0) { 2089 return false; 2090 } 2091 nativeClearCursor(); // start next trackball movement from page edge 2092 if (bottom) { 2093 return pinScrollTo(mScrollX, computeRealVerticalScrollRange(), true, 0); 2094 } 2095 // Page down. 2096 int h = getHeight(); 2097 int y; 2098 if (h > 2 * PAGE_SCROLL_OVERLAP) { 2099 y = h - PAGE_SCROLL_OVERLAP; 2100 } else { 2101 y = h / 2; 2102 } 2103 return mScroller.isFinished() ? pinScrollBy(0, y, true, 0) 2104 : extendScroll(y); 2105 } 2106 2107 /** 2108 * Clear the view so that onDraw() will draw nothing but white background, 2109 * and onMeasure() will return 0 if MeasureSpec is not MeasureSpec.EXACTLY 2110 */ 2111 public void clearView() { 2112 mContentWidth = 0; 2113 mContentHeight = 0; 2114 setBaseLayer(0, null, false); 2115 mWebViewCore.sendMessage(EventHub.CLEAR_CONTENT); 2116 } 2117 2118 /** 2119 * Return a new picture that captures the current display of the webview. 2120 * This is a copy of the display, and will be unaffected if the webview 2121 * later loads a different URL. 2122 * 2123 * @return a picture containing the current contents of the view. Note this 2124 * picture is of the entire document, and is not restricted to the 2125 * bounds of the view. 2126 */ 2127 public Picture capturePicture() { 2128 if (mNativeClass == 0) return null; 2129 Picture result = new Picture(); 2130 nativeCopyBaseContentToPicture(result); 2131 return result; 2132 } 2133 2134 /** 2135 * Return true if the browser is displaying a TextView for text input. 2136 */ 2137 private boolean inEditingMode() { 2138 return mWebTextView != null && mWebTextView.getParent() != null; 2139 } 2140 2141 /** 2142 * Remove the WebTextView. 2143 */ 2144 private void clearTextEntry() { 2145 if (inEditingMode()) { 2146 mWebTextView.remove(); 2147 } else { 2148 // The keyboard may be open with the WebView as the served view 2149 hideSoftKeyboard(); 2150 } 2151 } 2152 2153 /** 2154 * Return the current scale of the WebView 2155 * @return The current scale. 2156 */ 2157 public float getScale() { 2158 return mZoomManager.getScale(); 2159 } 2160 2161 /** 2162 * Set the initial scale for the WebView. 0 means default. If 2163 * {@link WebSettings#getUseWideViewPort()} is true, it zooms out all the 2164 * way. Otherwise it starts with 100%. If initial scale is greater than 0, 2165 * WebView starts will this value as initial scale. 2166 * 2167 * @param scaleInPercent The initial scale in percent. 2168 */ 2169 public void setInitialScale(int scaleInPercent) { 2170 mZoomManager.setInitialScaleInPercent(scaleInPercent); 2171 } 2172 2173 /** 2174 * Invoke the graphical zoom picker widget for this WebView. This will 2175 * result in the zoom widget appearing on the screen to control the zoom 2176 * level of this WebView. 2177 */ 2178 public void invokeZoomPicker() { 2179 if (!getSettings().supportZoom()) { 2180 Log.w(LOGTAG, "This WebView doesn't support zoom."); 2181 return; 2182 } 2183 clearHelpers(); 2184 mZoomManager.invokeZoomPicker(); 2185 } 2186 2187 /** 2188 * Return a HitTestResult based on the current cursor node. If a HTML::a tag 2189 * is found and the anchor has a non-JavaScript url, the HitTestResult type 2190 * is set to SRC_ANCHOR_TYPE and the url is set in the "extra" field. If the 2191 * anchor does not have a url or if it is a JavaScript url, the type will 2192 * be UNKNOWN_TYPE and the url has to be retrieved through 2193 * {@link #requestFocusNodeHref} asynchronously. If a HTML::img tag is 2194 * found, the HitTestResult type is set to IMAGE_TYPE and the url is set in 2195 * the "extra" field. A type of 2196 * SRC_IMAGE_ANCHOR_TYPE indicates an anchor with a url that has an image as 2197 * a child node. If a phone number is found, the HitTestResult type is set 2198 * to PHONE_TYPE and the phone number is set in the "extra" field of 2199 * HitTestResult. If a map address is found, the HitTestResult type is set 2200 * to GEO_TYPE and the address is set in the "extra" field of HitTestResult. 2201 * If an email address is found, the HitTestResult type is set to EMAIL_TYPE 2202 * and the email is set in the "extra" field of HitTestResult. Otherwise, 2203 * HitTestResult type is set to UNKNOWN_TYPE. 2204 */ 2205 public HitTestResult getHitTestResult() { 2206 return hitTestResult(mInitialHitTestResult); 2207 } 2208 2209 private HitTestResult hitTestResult(HitTestResult fallback) { 2210 if (mNativeClass == 0) { 2211 return null; 2212 } 2213 2214 HitTestResult result = new HitTestResult(); 2215 if (nativeHasCursorNode()) { 2216 if (nativeCursorIsTextInput()) { 2217 result.setType(HitTestResult.EDIT_TEXT_TYPE); 2218 } else { 2219 String text = nativeCursorText(); 2220 if (text != null) { 2221 if (text.startsWith(SCHEME_TEL)) { 2222 result.setType(HitTestResult.PHONE_TYPE); 2223 result.setExtra(text.substring(SCHEME_TEL.length())); 2224 } else if (text.startsWith(SCHEME_MAILTO)) { 2225 result.setType(HitTestResult.EMAIL_TYPE); 2226 result.setExtra(text.substring(SCHEME_MAILTO.length())); 2227 } else if (text.startsWith(SCHEME_GEO)) { 2228 result.setType(HitTestResult.GEO_TYPE); 2229 result.setExtra(URLDecoder.decode(text 2230 .substring(SCHEME_GEO.length()))); 2231 } else if (nativeCursorIsAnchor()) { 2232 result.setType(HitTestResult.SRC_ANCHOR_TYPE); 2233 result.setExtra(text); 2234 } 2235 } 2236 } 2237 } else if (fallback != null) { 2238 /* If webkit causes a rebuild while the long press is in progress, 2239 * the cursor node may be reset, even if it is still around. This 2240 * uses the cursor node saved when the touch began. Since the 2241 * nativeImageURI below only changes the result if it is successful, 2242 * this uses the data beneath the touch if available or the original 2243 * tap data otherwise. 2244 */ 2245 Log.v(LOGTAG, "hitTestResult use fallback"); 2246 result = fallback; 2247 } 2248 int type = result.getType(); 2249 if (type == HitTestResult.UNKNOWN_TYPE 2250 || type == HitTestResult.SRC_ANCHOR_TYPE) { 2251 // Now check to see if it is an image. 2252 int contentX = viewToContentX(mLastTouchX + mScrollX); 2253 int contentY = viewToContentY(mLastTouchY + mScrollY); 2254 String text = nativeImageURI(contentX, contentY); 2255 if (text != null) { 2256 result.setType(type == HitTestResult.UNKNOWN_TYPE ? 2257 HitTestResult.IMAGE_TYPE : 2258 HitTestResult.SRC_IMAGE_ANCHOR_TYPE); 2259 result.setExtra(text); 2260 } 2261 } 2262 return result; 2263 } 2264 2265 // Called by JNI when the DOM has changed the focus. Clear the focus so 2266 // that new keys will go to the newly focused field 2267 private void domChangedFocus() { 2268 if (inEditingMode()) { 2269 mPrivateHandler.obtainMessage(DOM_FOCUS_CHANGED).sendToTarget(); 2270 } 2271 } 2272 /** 2273 * Request the anchor or image element URL at the last tapped point. 2274 * If hrefMsg is null, this method returns immediately and does not 2275 * dispatch hrefMsg to its target. If the tapped point hits an image, 2276 * an anchor, or an image in an anchor, the message associates 2277 * strings in named keys in its data. The value paired with the key 2278 * may be an empty string. 2279 * 2280 * @param hrefMsg This message will be dispatched with the result of the 2281 * request. The message data contains three keys: 2282 * - "url" returns the anchor's href attribute. 2283 * - "title" returns the anchor's text. 2284 * - "src" returns the image's src attribute. 2285 */ 2286 public void requestFocusNodeHref(Message hrefMsg) { 2287 if (hrefMsg == null) { 2288 return; 2289 } 2290 int contentX = viewToContentX(mLastTouchX + mScrollX); 2291 int contentY = viewToContentY(mLastTouchY + mScrollY); 2292 if (nativeHasCursorNode()) { 2293 Rect cursorBounds = nativeGetCursorRingBounds(); 2294 if (!cursorBounds.contains(contentX, contentY)) { 2295 int slop = viewToContentDimension(mNavSlop); 2296 cursorBounds.inset(-slop, -slop); 2297 if (cursorBounds.contains(contentX, contentY)) { 2298 contentX = (int) cursorBounds.centerX(); 2299 contentY = (int) cursorBounds.centerY(); 2300 } 2301 } 2302 } 2303 mWebViewCore.sendMessage(EventHub.REQUEST_CURSOR_HREF, 2304 contentX, contentY, hrefMsg); 2305 } 2306 2307 /** 2308 * Request the url of the image last touched by the user. msg will be sent 2309 * to its target with a String representing the url as its object. 2310 * 2311 * @param msg This message will be dispatched with the result of the request 2312 * as the data member with "url" as key. The result can be null. 2313 */ 2314 public void requestImageRef(Message msg) { 2315 if (0 == mNativeClass) return; // client isn't initialized 2316 int contentX = viewToContentX(mLastTouchX + mScrollX); 2317 int contentY = viewToContentY(mLastTouchY + mScrollY); 2318 String ref = nativeImageURI(contentX, contentY); 2319 Bundle data = msg.getData(); 2320 data.putString("url", ref); 2321 msg.setData(data); 2322 msg.sendToTarget(); 2323 } 2324 2325 static int pinLoc(int x, int viewMax, int docMax) { 2326// Log.d(LOGTAG, "-- pinLoc " + x + " " + viewMax + " " + docMax); 2327 if (docMax < viewMax) { // the doc has room on the sides for "blank" 2328 // pin the short document to the top/left of the screen 2329 x = 0; 2330// Log.d(LOGTAG, "--- center " + x); 2331 } else if (x < 0) { 2332 x = 0; 2333// Log.d(LOGTAG, "--- zero"); 2334 } else if (x + viewMax > docMax) { 2335 x = docMax - viewMax; 2336// Log.d(LOGTAG, "--- pin " + x); 2337 } 2338 return x; 2339 } 2340 2341 // Expects x in view coordinates 2342 int pinLocX(int x) { 2343 if (mInOverScrollMode) return x; 2344 return pinLoc(x, getViewWidth(), computeRealHorizontalScrollRange()); 2345 } 2346 2347 // Expects y in view coordinates 2348 int pinLocY(int y) { 2349 if (mInOverScrollMode) return y; 2350 return pinLoc(y, getViewHeightWithTitle(), 2351 computeRealVerticalScrollRange() + getTitleHeight()); 2352 } 2353 2354 /** 2355 * A title bar which is embedded in this WebView, and scrolls along with it 2356 * vertically, but not horizontally. 2357 */ 2358 private View mTitleBar; 2359 2360 /** 2361 * the title bar rendering gravity 2362 */ 2363 private int mTitleGravity; 2364 2365 /** 2366 * Add or remove a title bar to be embedded into the WebView, and scroll 2367 * along with it vertically, while remaining in view horizontally. Pass 2368 * null to remove the title bar from the WebView, and return to drawing 2369 * the WebView normally without translating to account for the title bar. 2370 * @hide 2371 */ 2372 public void setEmbeddedTitleBar(View v) { 2373 if (mTitleBar == v) return; 2374 if (mTitleBar != null) { 2375 removeView(mTitleBar); 2376 } 2377 if (null != v) { 2378 addView(v, new AbsoluteLayout.LayoutParams( 2379 ViewGroup.LayoutParams.MATCH_PARENT, 2380 ViewGroup.LayoutParams.WRAP_CONTENT, 0, 0)); 2381 } 2382 mTitleBar = v; 2383 } 2384 2385 /** 2386 * Set where to render the embedded title bar 2387 * NO_GRAVITY at the top of the page 2388 * TOP at the top of the screen 2389 * @hide 2390 */ 2391 public void setTitleBarGravity(int gravity) { 2392 mTitleGravity = gravity; 2393 } 2394 2395 /** 2396 * Given a distance in view space, convert it to content space. Note: this 2397 * does not reflect translation, just scaling, so this should not be called 2398 * with coordinates, but should be called for dimensions like width or 2399 * height. 2400 */ 2401 private int viewToContentDimension(int d) { 2402 return Math.round(d * mZoomManager.getInvScale()); 2403 } 2404 2405 /** 2406 * Given an x coordinate in view space, convert it to content space. Also 2407 * may be used for absolute heights (such as for the WebTextView's 2408 * textSize, which is unaffected by the height of the title bar). 2409 */ 2410 /*package*/ int viewToContentX(int x) { 2411 return viewToContentDimension(x); 2412 } 2413 2414 /** 2415 * Given a y coordinate in view space, convert it to content space. 2416 * Takes into account the height of the title bar if there is one 2417 * embedded into the WebView. 2418 */ 2419 /*package*/ int viewToContentY(int y) { 2420 return viewToContentDimension(y - getTitleHeight()); 2421 } 2422 2423 /** 2424 * Given a x coordinate in view space, convert it to content space. 2425 * Returns the result as a float. 2426 */ 2427 private float viewToContentXf(int x) { 2428 return x * mZoomManager.getInvScale(); 2429 } 2430 2431 /** 2432 * Given a y coordinate in view space, convert it to content space. 2433 * Takes into account the height of the title bar if there is one 2434 * embedded into the WebView. Returns the result as a float. 2435 */ 2436 private float viewToContentYf(int y) { 2437 return (y - getTitleHeight()) * mZoomManager.getInvScale(); 2438 } 2439 2440 /** 2441 * Given a distance in content space, convert it to view space. Note: this 2442 * does not reflect translation, just scaling, so this should not be called 2443 * with coordinates, but should be called for dimensions like width or 2444 * height. 2445 */ 2446 /*package*/ int contentToViewDimension(int d) { 2447 return Math.round(d * mZoomManager.getScale()); 2448 } 2449 2450 /** 2451 * Given an x coordinate in content space, convert it to view 2452 * space. 2453 */ 2454 /*package*/ int contentToViewX(int x) { 2455 return contentToViewDimension(x); 2456 } 2457 2458 /** 2459 * Given a y coordinate in content space, convert it to view 2460 * space. Takes into account the height of the title bar. 2461 */ 2462 /*package*/ int contentToViewY(int y) { 2463 return contentToViewDimension(y) + getTitleHeight(); 2464 } 2465 2466 private Rect contentToViewRect(Rect x) { 2467 return new Rect(contentToViewX(x.left), contentToViewY(x.top), 2468 contentToViewX(x.right), contentToViewY(x.bottom)); 2469 } 2470 2471 /* To invalidate a rectangle in content coordinates, we need to transform 2472 the rect into view coordinates, so we can then call invalidate(...). 2473 2474 Normally, we would just call contentToView[XY](...), which eventually 2475 calls Math.round(coordinate * mActualScale). However, for invalidates, 2476 we need to account for the slop that occurs with antialiasing. To 2477 address that, we are a little more liberal in the size of the rect that 2478 we invalidate. 2479 2480 This liberal calculation calls floor() for the top/left, and ceil() for 2481 the bottom/right coordinates. This catches the possible extra pixels of 2482 antialiasing that we might have missed with just round(). 2483 */ 2484 2485 // Called by JNI to invalidate the View, given rectangle coordinates in 2486 // content space 2487 private void viewInvalidate(int l, int t, int r, int b) { 2488 final float scale = mZoomManager.getScale(); 2489 final int dy = getTitleHeight(); 2490 invalidate((int)Math.floor(l * scale), 2491 (int)Math.floor(t * scale) + dy, 2492 (int)Math.ceil(r * scale), 2493 (int)Math.ceil(b * scale) + dy); 2494 } 2495 2496 // Called by JNI to invalidate the View after a delay, given rectangle 2497 // coordinates in content space 2498 private void viewInvalidateDelayed(long delay, int l, int t, int r, int b) { 2499 final float scale = mZoomManager.getScale(); 2500 final int dy = getTitleHeight(); 2501 postInvalidateDelayed(delay, 2502 (int)Math.floor(l * scale), 2503 (int)Math.floor(t * scale) + dy, 2504 (int)Math.ceil(r * scale), 2505 (int)Math.ceil(b * scale) + dy); 2506 } 2507 2508 private void invalidateContentRect(Rect r) { 2509 viewInvalidate(r.left, r.top, r.right, r.bottom); 2510 } 2511 2512 // stop the scroll animation, and don't let a subsequent fling add 2513 // to the existing velocity 2514 private void abortAnimation() { 2515 mScroller.abortAnimation(); 2516 mLastVelocity = 0; 2517 } 2518 2519 /* call from webcoreview.draw(), so we're still executing in the UI thread 2520 */ 2521 private void recordNewContentSize(int w, int h, boolean updateLayout) { 2522 2523 // premature data from webkit, ignore 2524 if ((w | h) == 0) { 2525 return; 2526 } 2527 2528 // don't abort a scroll animation if we didn't change anything 2529 if (mContentWidth != w || mContentHeight != h) { 2530 // record new dimensions 2531 mContentWidth = w; 2532 mContentHeight = h; 2533 // If history Picture is drawn, don't update scroll. They will be 2534 // updated when we get out of that mode. 2535 if (!mDrawHistory) { 2536 // repin our scroll, taking into account the new content size 2537 updateScrollCoordinates(pinLocX(mScrollX), pinLocY(mScrollY)); 2538 if (!mScroller.isFinished()) { 2539 // We are in the middle of a scroll. Repin the final scroll 2540 // position. 2541 mScroller.setFinalX(pinLocX(mScroller.getFinalX())); 2542 mScroller.setFinalY(pinLocY(mScroller.getFinalY())); 2543 } 2544 } 2545 } 2546 contentSizeChanged(updateLayout); 2547 } 2548 2549 // Used to avoid sending many visible rect messages. 2550 private Rect mLastVisibleRectSent; 2551 private Rect mLastGlobalRect; 2552 2553 Rect sendOurVisibleRect() { 2554 if (mZoomManager.isPreventingWebkitUpdates()) return mLastVisibleRectSent; 2555 Rect rect = new Rect(); 2556 calcOurContentVisibleRect(rect); 2557 // Rect.equals() checks for null input. 2558 if (!rect.equals(mLastVisibleRectSent)) { 2559 Point pos = new Point(rect.left, rect.top); 2560 mWebViewCore.removeMessages(EventHub.SET_SCROLL_OFFSET); 2561 mWebViewCore.sendMessage(EventHub.SET_SCROLL_OFFSET, 2562 nativeMoveGeneration(), mSendScrollEvent ? 1 : 0, pos); 2563 mLastVisibleRectSent = rect; 2564 mPrivateHandler.removeMessages(SWITCH_TO_LONGPRESS); 2565 } 2566 Rect globalRect = new Rect(); 2567 if (getGlobalVisibleRect(globalRect) 2568 && !globalRect.equals(mLastGlobalRect)) { 2569 if (DebugFlags.WEB_VIEW) { 2570 Log.v(LOGTAG, "sendOurVisibleRect=(" + globalRect.left + "," 2571 + globalRect.top + ",r=" + globalRect.right + ",b=" 2572 + globalRect.bottom); 2573 } 2574 // TODO: the global offset is only used by windowRect() 2575 // in ChromeClientAndroid ; other clients such as touch 2576 // and mouse events could return view + screen relative points. 2577 mWebViewCore.sendMessage(EventHub.SET_GLOBAL_BOUNDS, globalRect); 2578 mLastGlobalRect = globalRect; 2579 } 2580 return rect; 2581 } 2582 2583 // Sets r to be the visible rectangle of our webview in view coordinates 2584 private void calcOurVisibleRect(Rect r) { 2585 Point p = new Point(); 2586 getGlobalVisibleRect(r, p); 2587 r.offset(-p.x, -p.y); 2588 } 2589 2590 // Sets r to be our visible rectangle in content coordinates 2591 private void calcOurContentVisibleRect(Rect r) { 2592 calcOurVisibleRect(r); 2593 r.left = viewToContentX(r.left); 2594 // viewToContentY will remove the total height of the title bar. Add 2595 // the visible height back in to account for the fact that if the title 2596 // bar is partially visible, the part of the visible rect which is 2597 // displaying our content is displaced by that amount. 2598 r.top = viewToContentY(r.top + getVisibleTitleHeight()); 2599 r.right = viewToContentX(r.right); 2600 r.bottom = viewToContentY(r.bottom); 2601 } 2602 2603 // Sets r to be our visible rectangle in content coordinates. We use this 2604 // method on the native side to compute the position of the fixed layers. 2605 // Uses floating coordinates (necessary to correctly place elements when 2606 // the scale factor is not 1) 2607 private void calcOurContentVisibleRectF(RectF r) { 2608 Rect ri = new Rect(0,0,0,0); 2609 calcOurVisibleRect(ri); 2610 r.left = viewToContentXf(ri.left); 2611 // viewToContentY will remove the total height of the title bar. Add 2612 // the visible height back in to account for the fact that if the title 2613 // bar is partially visible, the part of the visible rect which is 2614 // displaying our content is displaced by that amount. 2615 r.top = viewToContentYf(ri.top + getVisibleTitleHeight()); 2616 r.right = viewToContentXf(ri.right); 2617 r.bottom = viewToContentYf(ri.bottom); 2618 } 2619 2620 static class ViewSizeData { 2621 int mWidth; 2622 int mHeight; 2623 float mHeightWidthRatio; 2624 int mActualViewHeight; 2625 int mTextWrapWidth; 2626 int mAnchorX; 2627 int mAnchorY; 2628 float mScale; 2629 boolean mIgnoreHeight; 2630 } 2631 2632 /** 2633 * Compute unzoomed width and height, and if they differ from the last 2634 * values we sent, send them to webkit (to be used as new viewport) 2635 * 2636 * @param force ensures that the message is sent to webkit even if the width 2637 * or height has not changed since the last message 2638 * 2639 * @return true if new values were sent 2640 */ 2641 boolean sendViewSizeZoom(boolean force) { 2642 if (mZoomManager.isPreventingWebkitUpdates()) return false; 2643 2644 int viewWidth = getViewWidth(); 2645 int newWidth = Math.round(viewWidth * mZoomManager.getInvScale()); 2646 // This height could be fixed and be different from actual visible height. 2647 int viewHeight = getViewHeightWithTitle() - getTitleHeight(); 2648 int newHeight = Math.round(viewHeight * mZoomManager.getInvScale()); 2649 // Make the ratio more accurate than (newHeight / newWidth), since the 2650 // latter both are calculated and rounded. 2651 float heightWidthRatio = (float) viewHeight / viewWidth; 2652 /* 2653 * Because the native side may have already done a layout before the 2654 * View system was able to measure us, we have to send a height of 0 to 2655 * remove excess whitespace when we grow our width. This will trigger a 2656 * layout and a change in content size. This content size change will 2657 * mean that contentSizeChanged will either call this method directly or 2658 * indirectly from onSizeChanged. 2659 */ 2660 if (newWidth > mLastWidthSent && mWrapContent) { 2661 newHeight = 0; 2662 heightWidthRatio = 0; 2663 } 2664 // Actual visible content height. 2665 int actualViewHeight = Math.round(getViewHeight() * mZoomManager.getInvScale()); 2666 // Avoid sending another message if the dimensions have not changed. 2667 if (newWidth != mLastWidthSent || newHeight != mLastHeightSent || force || 2668 actualViewHeight != mLastActualHeightSent) { 2669 ViewSizeData data = new ViewSizeData(); 2670 data.mWidth = newWidth; 2671 data.mHeight = newHeight; 2672 data.mHeightWidthRatio = heightWidthRatio; 2673 data.mActualViewHeight = actualViewHeight; 2674 data.mTextWrapWidth = Math.round(viewWidth / mZoomManager.getTextWrapScale()); 2675 data.mScale = mZoomManager.getScale(); 2676 data.mIgnoreHeight = mZoomManager.isFixedLengthAnimationInProgress() 2677 && !mHeightCanMeasure; 2678 data.mAnchorX = mZoomManager.getDocumentAnchorX(); 2679 data.mAnchorY = mZoomManager.getDocumentAnchorY(); 2680 mWebViewCore.sendMessage(EventHub.VIEW_SIZE_CHANGED, data); 2681 mLastWidthSent = newWidth; 2682 mLastHeightSent = newHeight; 2683 mLastActualHeightSent = actualViewHeight; 2684 mZoomManager.clearDocumentAnchor(); 2685 return true; 2686 } 2687 return false; 2688 } 2689 2690 private int computeRealHorizontalScrollRange() { 2691 if (mDrawHistory) { 2692 return mHistoryWidth; 2693 } else { 2694 // to avoid rounding error caused unnecessary scrollbar, use floor 2695 return (int) Math.floor(mContentWidth * mZoomManager.getScale()); 2696 } 2697 } 2698 2699 @Override 2700 protected int computeHorizontalScrollRange() { 2701 int range = computeRealHorizontalScrollRange(); 2702 2703 // Adjust reported range if overscrolled to compress the scroll bars 2704 final int scrollX = mScrollX; 2705 final int overscrollRight = computeMaxScrollX(); 2706 if (scrollX < 0) { 2707 range -= scrollX; 2708 } else if (scrollX > overscrollRight) { 2709 range += scrollX - overscrollRight; 2710 } 2711 2712 return range; 2713 } 2714 2715 @Override 2716 protected int computeHorizontalScrollOffset() { 2717 return Math.max(mScrollX, 0); 2718 } 2719 2720 private int computeRealVerticalScrollRange() { 2721 if (mDrawHistory) { 2722 return mHistoryHeight; 2723 } else { 2724 // to avoid rounding error caused unnecessary scrollbar, use floor 2725 return (int) Math.floor(mContentHeight * mZoomManager.getScale()); 2726 } 2727 } 2728 2729 @Override 2730 protected int computeVerticalScrollRange() { 2731 int range = computeRealVerticalScrollRange(); 2732 2733 // Adjust reported range if overscrolled to compress the scroll bars 2734 final int scrollY = mScrollY; 2735 final int overscrollBottom = computeMaxScrollY(); 2736 if (scrollY < 0) { 2737 range -= scrollY; 2738 } else if (scrollY > overscrollBottom) { 2739 range += scrollY - overscrollBottom; 2740 } 2741 2742 return range; 2743 } 2744 2745 @Override 2746 protected int computeVerticalScrollOffset() { 2747 return Math.max(mScrollY - getTitleHeight(), 0); 2748 } 2749 2750 @Override 2751 protected int computeVerticalScrollExtent() { 2752 return getViewHeight(); 2753 } 2754 2755 /** @hide */ 2756 @Override 2757 protected void onDrawVerticalScrollBar(Canvas canvas, 2758 Drawable scrollBar, 2759 int l, int t, int r, int b) { 2760 if (mScrollY < 0) { 2761 t -= mScrollY; 2762 } 2763 scrollBar.setBounds(l, t + getVisibleTitleHeight(), r, b); 2764 scrollBar.draw(canvas); 2765 } 2766 2767 @Override 2768 protected void onOverScrolled(int scrollX, int scrollY, boolean clampedX, 2769 boolean clampedY) { 2770 // Special-case layer scrolling so that we do not trigger normal scroll 2771 // updating. 2772 if (mTouchMode == TOUCH_DRAG_LAYER_MODE) { 2773 nativeScrollLayer(mScrollingLayer, scrollX, scrollY); 2774 mScrollingLayerRect.left = scrollX; 2775 mScrollingLayerRect.top = scrollY; 2776 invalidate(); 2777 return; 2778 } 2779 mInOverScrollMode = false; 2780 int maxX = computeMaxScrollX(); 2781 int maxY = computeMaxScrollY(); 2782 if (maxX == 0) { 2783 // do not over scroll x if the page just fits the screen 2784 scrollX = pinLocX(scrollX); 2785 } else if (scrollX < 0 || scrollX > maxX) { 2786 mInOverScrollMode = true; 2787 } 2788 if (scrollY < 0 || scrollY > maxY) { 2789 mInOverScrollMode = true; 2790 } 2791 2792 int oldX = mScrollX; 2793 int oldY = mScrollY; 2794 2795 super.scrollTo(scrollX, scrollY); 2796 2797 if (mOverScrollGlow != null) { 2798 mOverScrollGlow.pullGlow(mScrollX, mScrollY, oldX, oldY, maxX, maxY); 2799 } 2800 } 2801 2802 /** 2803 * Get the url for the current page. This is not always the same as the url 2804 * passed to WebViewClient.onPageStarted because although the load for 2805 * that url has begun, the current page may not have changed. 2806 * @return The url for the current page. 2807 */ 2808 public String getUrl() { 2809 WebHistoryItem h = mCallbackProxy.getBackForwardList().getCurrentItem(); 2810 return h != null ? h.getUrl() : null; 2811 } 2812 2813 /** 2814 * Get the original url for the current page. This is not always the same 2815 * as the url passed to WebViewClient.onPageStarted because although the 2816 * load for that url has begun, the current page may not have changed. 2817 * Also, there may have been redirects resulting in a different url to that 2818 * originally requested. 2819 * @return The url that was originally requested for the current page. 2820 */ 2821 public String getOriginalUrl() { 2822 WebHistoryItem h = mCallbackProxy.getBackForwardList().getCurrentItem(); 2823 return h != null ? h.getOriginalUrl() : null; 2824 } 2825 2826 /** 2827 * Get the title for the current page. This is the title of the current page 2828 * until WebViewClient.onReceivedTitle is called. 2829 * @return The title for the current page. 2830 */ 2831 public String getTitle() { 2832 WebHistoryItem h = mCallbackProxy.getBackForwardList().getCurrentItem(); 2833 return h != null ? h.getTitle() : null; 2834 } 2835 2836 /** 2837 * Get the favicon for the current page. This is the favicon of the current 2838 * page until WebViewClient.onReceivedIcon is called. 2839 * @return The favicon for the current page. 2840 */ 2841 public Bitmap getFavicon() { 2842 WebHistoryItem h = mCallbackProxy.getBackForwardList().getCurrentItem(); 2843 return h != null ? h.getFavicon() : null; 2844 } 2845 2846 /** 2847 * Get the touch icon url for the apple-touch-icon <link> element, or 2848 * a URL on this site's server pointing to the standard location of a 2849 * touch icon. 2850 * @hide 2851 */ 2852 public String getTouchIconUrl() { 2853 WebHistoryItem h = mCallbackProxy.getBackForwardList().getCurrentItem(); 2854 return h != null ? h.getTouchIconUrl() : null; 2855 } 2856 2857 /** 2858 * Get the progress for the current page. 2859 * @return The progress for the current page between 0 and 100. 2860 */ 2861 public int getProgress() { 2862 return mCallbackProxy.getProgress(); 2863 } 2864 2865 /** 2866 * @return the height of the HTML content. 2867 */ 2868 public int getContentHeight() { 2869 return mContentHeight; 2870 } 2871 2872 /** 2873 * @return the width of the HTML content. 2874 * @hide 2875 */ 2876 public int getContentWidth() { 2877 return mContentWidth; 2878 } 2879 2880 /** 2881 * Pause all layout, parsing, and JavaScript timers for all webviews. This 2882 * is a global requests, not restricted to just this webview. This can be 2883 * useful if the application has been paused. 2884 */ 2885 public void pauseTimers() { 2886 mWebViewCore.sendMessage(EventHub.PAUSE_TIMERS); 2887 } 2888 2889 /** 2890 * Resume all layout, parsing, and JavaScript timers for all webviews. 2891 * This will resume dispatching all timers. 2892 */ 2893 public void resumeTimers() { 2894 mWebViewCore.sendMessage(EventHub.RESUME_TIMERS); 2895 } 2896 2897 /** 2898 * Call this to pause any extra processing associated with this WebView and 2899 * its associated DOM, plugins, JavaScript etc. For example, if the WebView 2900 * is taken offscreen, this could be called to reduce unnecessary CPU or 2901 * network traffic. When the WebView is again "active", call onResume(). 2902 * 2903 * Note that this differs from pauseTimers(), which affects all WebViews. 2904 */ 2905 public void onPause() { 2906 if (!mIsPaused) { 2907 mIsPaused = true; 2908 mWebViewCore.sendMessage(EventHub.ON_PAUSE); 2909 } 2910 } 2911 2912 /** 2913 * Call this to resume a WebView after a previous call to onPause(). 2914 */ 2915 public void onResume() { 2916 if (mIsPaused) { 2917 mIsPaused = false; 2918 mWebViewCore.sendMessage(EventHub.ON_RESUME); 2919 } 2920 } 2921 2922 /** 2923 * Returns true if the view is paused, meaning onPause() was called. Calling 2924 * onResume() sets the paused state back to false. 2925 * @hide 2926 */ 2927 public boolean isPaused() { 2928 return mIsPaused; 2929 } 2930 2931 /** 2932 * Call this to inform the view that memory is low so that it can 2933 * free any available memory. 2934 */ 2935 public void freeMemory() { 2936 mWebViewCore.sendMessage(EventHub.FREE_MEMORY); 2937 } 2938 2939 /** 2940 * Clear the resource cache. Note that the cache is per-application, so 2941 * this will clear the cache for all WebViews used. 2942 * 2943 * @param includeDiskFiles If false, only the RAM cache is cleared. 2944 */ 2945 public void clearCache(boolean includeDiskFiles) { 2946 // Note: this really needs to be a static method as it clears cache for all 2947 // WebView. But we need mWebViewCore to send message to WebCore thread, so 2948 // we can't make this static. 2949 mWebViewCore.sendMessage(EventHub.CLEAR_CACHE, 2950 includeDiskFiles ? 1 : 0, 0); 2951 } 2952 2953 /** 2954 * Make sure that clearing the form data removes the adapter from the 2955 * currently focused textfield if there is one. 2956 */ 2957 public void clearFormData() { 2958 if (inEditingMode()) { 2959 AutoCompleteAdapter adapter = null; 2960 mWebTextView.setAdapterCustom(adapter); 2961 } 2962 } 2963 2964 /** 2965 * Tell the WebView to clear its internal back/forward list. 2966 */ 2967 public void clearHistory() { 2968 mCallbackProxy.getBackForwardList().setClearPending(); 2969 mWebViewCore.sendMessage(EventHub.CLEAR_HISTORY); 2970 } 2971 2972 /** 2973 * Clear the SSL preferences table stored in response to proceeding with SSL 2974 * certificate errors. 2975 */ 2976 public void clearSslPreferences() { 2977 mWebViewCore.sendMessage(EventHub.CLEAR_SSL_PREF_TABLE); 2978 } 2979 2980 /** 2981 * Return the WebBackForwardList for this WebView. This contains the 2982 * back/forward list for use in querying each item in the history stack. 2983 * This is a copy of the private WebBackForwardList so it contains only a 2984 * snapshot of the current state. Multiple calls to this method may return 2985 * different objects. The object returned from this method will not be 2986 * updated to reflect any new state. 2987 */ 2988 public WebBackForwardList copyBackForwardList() { 2989 return mCallbackProxy.getBackForwardList().clone(); 2990 } 2991 2992 /* 2993 * Highlight and scroll to the next occurance of String in findAll. 2994 * Wraps the page infinitely, and scrolls. Must be called after 2995 * calling findAll. 2996 * 2997 * @param forward Direction to search. 2998 */ 2999 public void findNext(boolean forward) { 3000 if (0 == mNativeClass) return; // client isn't initialized 3001 nativeFindNext(forward); 3002 } 3003 3004 /* 3005 * Find all instances of find on the page and highlight them. 3006 * @param find String to find. 3007 * @return int The number of occurances of the String "find" 3008 * that were found. 3009 */ 3010 public int findAll(String find) { 3011 if (0 == mNativeClass) return 0; // client isn't initialized 3012 int result = find != null ? nativeFindAll(find.toLowerCase(), 3013 find.toUpperCase(), find.equalsIgnoreCase(mLastFind)) : 0; 3014 invalidate(); 3015 mLastFind = find; 3016 return result; 3017 } 3018 3019 /** 3020 * Start an ActionMode for finding text in this WebView. Only works if this 3021 * WebView is attached to the view system. 3022 * @param text If non-null, will be the initial text to search for. 3023 * Otherwise, the last String searched for in this WebView will 3024 * be used to start. 3025 * @param showIme If true, show the IME, assuming the user will begin typing. 3026 * If false and text is non-null, perform a find all. 3027 * @return boolean True if the find dialog is shown, false otherwise. 3028 */ 3029 public boolean showFindDialog(String text, boolean showIme) { 3030 FindActionModeCallback callback = new FindActionModeCallback(mContext); 3031 if (getParent() == null || startActionMode(callback) == null) { 3032 // Could not start the action mode, so end Find on page 3033 return false; 3034 } 3035 mFindCallback = callback; 3036 setFindIsUp(true); 3037 mFindCallback.setWebView(this); 3038 if (showIme) { 3039 mFindCallback.showSoftInput(); 3040 } else if (text != null) { 3041 mFindCallback.setText(text); 3042 mFindCallback.findAll(); 3043 return true; 3044 } 3045 if (text == null) { 3046 text = mLastFind; 3047 } 3048 if (text != null) { 3049 mFindCallback.setText(text); 3050 } 3051 return true; 3052 } 3053 3054 /** 3055 * Keep track of the find callback so that we can remove its titlebar if 3056 * necessary. 3057 */ 3058 private FindActionModeCallback mFindCallback; 3059 3060 /** 3061 * Toggle whether the find dialog is showing, for both native and Java. 3062 */ 3063 private void setFindIsUp(boolean isUp) { 3064 mFindIsUp = isUp; 3065 if (0 == mNativeClass) return; // client isn't initialized 3066 nativeSetFindIsUp(isUp); 3067 } 3068 3069 /** 3070 * Return the index of the currently highlighted match. 3071 */ 3072 int findIndex() { 3073 if (0 == mNativeClass) return -1; 3074 return nativeFindIndex(); 3075 } 3076 3077 // Used to know whether the find dialog is open. Affects whether 3078 // or not we draw the highlights for matches. 3079 private boolean mFindIsUp; 3080 3081 // Keep track of the last string sent, so we can search again when find is 3082 // reopened. 3083 private String mLastFind; 3084 3085 /** 3086 * Return the first substring consisting of the address of a physical 3087 * location. Currently, only addresses in the United States are detected, 3088 * and consist of: 3089 * - a house number 3090 * - a street name 3091 * - a street type (Road, Circle, etc), either spelled out or abbreviated 3092 * - a city name 3093 * - a state or territory, either spelled out or two-letter abbr. 3094 * - an optional 5 digit or 9 digit zip code. 3095 * 3096 * All names must be correctly capitalized, and the zip code, if present, 3097 * must be valid for the state. The street type must be a standard USPS 3098 * spelling or abbreviation. The state or territory must also be spelled 3099 * or abbreviated using USPS standards. The house number may not exceed 3100 * five digits. 3101 * @param addr The string to search for addresses. 3102 * 3103 * @return the address, or if no address is found, return null. 3104 */ 3105 public static String findAddress(String addr) { 3106 return findAddress(addr, false); 3107 } 3108 3109 /** 3110 * @hide 3111 * Return the first substring consisting of the address of a physical 3112 * location. Currently, only addresses in the United States are detected, 3113 * and consist of: 3114 * - a house number 3115 * - a street name 3116 * - a street type (Road, Circle, etc), either spelled out or abbreviated 3117 * - a city name 3118 * - a state or territory, either spelled out or two-letter abbr. 3119 * - an optional 5 digit or 9 digit zip code. 3120 * 3121 * Names are optionally capitalized, and the zip code, if present, 3122 * must be valid for the state. The street type must be a standard USPS 3123 * spelling or abbreviation. The state or territory must also be spelled 3124 * or abbreviated using USPS standards. The house number may not exceed 3125 * five digits. 3126 * @param addr The string to search for addresses. 3127 * @param caseInsensitive addr Set to true to make search ignore case. 3128 * 3129 * @return the address, or if no address is found, return null. 3130 */ 3131 public static String findAddress(String addr, boolean caseInsensitive) { 3132 return WebViewCore.nativeFindAddress(addr, caseInsensitive); 3133 } 3134 3135 /* 3136 * Clear the highlighting surrounding text matches created by findAll. 3137 */ 3138 public void clearMatches() { 3139 if (mNativeClass == 0) 3140 return; 3141 nativeSetFindIsEmpty(); 3142 invalidate(); 3143 } 3144 3145 /** 3146 * Called when the find ActionMode ends. 3147 */ 3148 void notifyFindDialogDismissed() { 3149 mFindCallback = null; 3150 if (mWebViewCore == null) { 3151 return; 3152 } 3153 clearMatches(); 3154 setFindIsUp(false); 3155 // Now that the dialog has been removed, ensure that we scroll to a 3156 // location that is not beyond the end of the page. 3157 pinScrollTo(mScrollX, mScrollY, false, 0); 3158 invalidate(); 3159 } 3160 3161 /** 3162 * Query the document to see if it contains any image references. The 3163 * message object will be dispatched with arg1 being set to 1 if images 3164 * were found and 0 if the document does not reference any images. 3165 * @param response The message that will be dispatched with the result. 3166 */ 3167 public void documentHasImages(Message response) { 3168 if (response == null) { 3169 return; 3170 } 3171 mWebViewCore.sendMessage(EventHub.DOC_HAS_IMAGES, response); 3172 } 3173 3174 /** 3175 * Request the scroller to abort any ongoing animation 3176 * 3177 * @hide 3178 */ 3179 public void stopScroll() { 3180 mScroller.forceFinished(true); 3181 mLastVelocity = 0; 3182 } 3183 3184 @Override 3185 public void computeScroll() { 3186 if (mScroller.computeScrollOffset()) { 3187 int oldX = mScrollX; 3188 int oldY = mScrollY; 3189 int x = mScroller.getCurrX(); 3190 int y = mScroller.getCurrY(); 3191 invalidate(); // So we draw again 3192 3193 if (!mScroller.isFinished()) { 3194 int rangeX = computeMaxScrollX(); 3195 int rangeY = computeMaxScrollY(); 3196 int overflingDistance = mOverflingDistance; 3197 3198 // Use the layer's scroll data if needed. 3199 if (mTouchMode == TOUCH_DRAG_LAYER_MODE) { 3200 oldX = mScrollingLayerRect.left; 3201 oldY = mScrollingLayerRect.top; 3202 rangeX = mScrollingLayerRect.right; 3203 rangeY = mScrollingLayerRect.bottom; 3204 // No overscrolling for layers. 3205 overflingDistance = 0; 3206 } 3207 3208 overScrollBy(x - oldX, y - oldY, oldX, oldY, 3209 rangeX, rangeY, 3210 overflingDistance, overflingDistance, false); 3211 3212 if (mOverScrollGlow != null) { 3213 mOverScrollGlow.absorbGlow(x, y, oldX, oldY, rangeX, rangeY); 3214 } 3215 } else { 3216 if (mTouchMode != TOUCH_DRAG_LAYER_MODE) { 3217 mScrollX = x; 3218 mScrollY = y; 3219 } else { 3220 // Update the layer position instead of WebView. 3221 nativeScrollLayer(mScrollingLayer, x, y); 3222 mScrollingLayerRect.left = x; 3223 mScrollingLayerRect.top = y; 3224 } 3225 abortAnimation(); 3226 mPrivateHandler.removeMessages(RESUME_WEBCORE_PRIORITY); 3227 WebViewCore.resumePriority(); 3228 if (!mSelectingText) { 3229 WebViewCore.resumeUpdatePicture(mWebViewCore); 3230 } 3231 if (oldX != mScrollX || oldY != mScrollY) { 3232 sendOurVisibleRect(); 3233 } 3234 } 3235 } else { 3236 super.computeScroll(); 3237 } 3238 } 3239 3240 private static int computeDuration(int dx, int dy) { 3241 int distance = Math.max(Math.abs(dx), Math.abs(dy)); 3242 int duration = distance * 1000 / STD_SPEED; 3243 return Math.min(duration, MAX_DURATION); 3244 } 3245 3246 // helper to pin the scrollBy parameters (already in view coordinates) 3247 // returns true if the scroll was changed 3248 private boolean pinScrollBy(int dx, int dy, boolean animate, int animationDuration) { 3249 return pinScrollTo(mScrollX + dx, mScrollY + dy, animate, animationDuration); 3250 } 3251 // helper to pin the scrollTo parameters (already in view coordinates) 3252 // returns true if the scroll was changed 3253 private boolean pinScrollTo(int x, int y, boolean animate, int animationDuration) { 3254 x = pinLocX(x); 3255 y = pinLocY(y); 3256 int dx = x - mScrollX; 3257 int dy = y - mScrollY; 3258 3259 if ((dx | dy) == 0) { 3260 return false; 3261 } 3262 abortAnimation(); 3263 if (animate) { 3264 // Log.d(LOGTAG, "startScroll: " + dx + " " + dy); 3265 mScroller.startScroll(mScrollX, mScrollY, dx, dy, 3266 animationDuration > 0 ? animationDuration : computeDuration(dx, dy)); 3267 awakenScrollBars(mScroller.getDuration()); 3268 invalidate(); 3269 } else { 3270 scrollTo(x, y); 3271 } 3272 return true; 3273 } 3274 3275 // Scale from content to view coordinates, and pin. 3276 // Also called by jni webview.cpp 3277 private boolean setContentScrollBy(int cx, int cy, boolean animate) { 3278 if (mDrawHistory) { 3279 // disallow WebView to change the scroll position as History Picture 3280 // is used in the view system. 3281 // TODO: as we switchOutDrawHistory when trackball or navigation 3282 // keys are hit, this should be safe. Right? 3283 return false; 3284 } 3285 cx = contentToViewDimension(cx); 3286 cy = contentToViewDimension(cy); 3287 if (mHeightCanMeasure) { 3288 // move our visible rect according to scroll request 3289 if (cy != 0) { 3290 Rect tempRect = new Rect(); 3291 calcOurVisibleRect(tempRect); 3292 tempRect.offset(cx, cy); 3293 requestRectangleOnScreen(tempRect); 3294 } 3295 // FIXME: We scroll horizontally no matter what because currently 3296 // ScrollView and ListView will not scroll horizontally. 3297 // FIXME: Why do we only scroll horizontally if there is no 3298 // vertical scroll? 3299// Log.d(LOGTAG, "setContentScrollBy cy=" + cy); 3300 return cy == 0 && cx != 0 && pinScrollBy(cx, 0, animate, 0); 3301 } else { 3302 return pinScrollBy(cx, cy, animate, 0); 3303 } 3304 } 3305 3306 /** 3307 * Called by CallbackProxy when the page starts loading. 3308 * @param url The URL of the page which has started loading. 3309 */ 3310 /* package */ void onPageStarted(String url) { 3311 // every time we start a new page, we want to reset the 3312 // WebView certificate: if the new site is secure, we 3313 // will reload it and get a new certificate set; 3314 // if the new site is not secure, the certificate must be 3315 // null, and that will be the case 3316 setCertificate(null); 3317 3318 // reset the flag since we set to true in if need after 3319 // loading is see onPageFinished(Url) 3320 mAccessibilityScriptInjected = false; 3321 } 3322 3323 /** 3324 * Called by CallbackProxy when the page finishes loading. 3325 * @param url The URL of the page which has finished loading. 3326 */ 3327 /* package */ void onPageFinished(String url) { 3328 if (mPageThatNeedsToSlideTitleBarOffScreen != null) { 3329 // If the user is now on a different page, or has scrolled the page 3330 // past the point where the title bar is offscreen, ignore the 3331 // scroll request. 3332 if (mPageThatNeedsToSlideTitleBarOffScreen.equals(url) 3333 && mScrollX == 0 && mScrollY == 0) { 3334 pinScrollTo(0, mYDistanceToSlideTitleOffScreen, true, 3335 SLIDE_TITLE_DURATION); 3336 } 3337 mPageThatNeedsToSlideTitleBarOffScreen = null; 3338 } 3339 mZoomManager.onPageFinished(url); 3340 injectAccessibilityForUrl(url); 3341 } 3342 3343 /** 3344 * This method injects accessibility in the loaded document if accessibility 3345 * is enabled. If JavaScript is enabled we try to inject a URL specific script. 3346 * If no URL specific script is found or JavaScript is disabled we fallback to 3347 * the default {@link AccessibilityInjector} implementation. 3348 * </p> 3349 * If the URL has the "axs" paramter set to 1 it has already done the 3350 * script injection so we do nothing. If the parameter is set to 0 3351 * the URL opts out accessibility script injection so we fall back to 3352 * the default {@link AccessibilityInjector}. 3353 * </p> 3354 * Note: If the user has not opted-in the accessibility script injection no scripts 3355 * are injected rather the default {@link AccessibilityInjector} implementation 3356 * is used. 3357 * 3358 * @param url The URL loaded by this {@link WebView}. 3359 */ 3360 private void injectAccessibilityForUrl(String url) { 3361 if (mWebViewCore == null) { 3362 return; 3363 } 3364 AccessibilityManager accessibilityManager = AccessibilityManager.getInstance(mContext); 3365 3366 if (!accessibilityManager.isEnabled()) { 3367 // it is possible that accessibility was turned off between reloads 3368 ensureAccessibilityScriptInjectorInstance(false); 3369 return; 3370 } 3371 3372 if (!getSettings().getJavaScriptEnabled()) { 3373 // no JS so we fallback to the basic buil-in support 3374 ensureAccessibilityScriptInjectorInstance(true); 3375 return; 3376 } 3377 3378 // check the URL "axs" parameter to choose appropriate action 3379 int axsParameterValue = getAxsUrlParameterValue(url); 3380 if (axsParameterValue == ACCESSIBILITY_SCRIPT_INJECTION_UNDEFINED) { 3381 boolean onDeviceScriptInjectionEnabled = (Settings.Secure.getInt(mContext 3382 .getContentResolver(), Settings.Secure.ACCESSIBILITY_SCRIPT_INJECTION, 0) == 1); 3383 if (onDeviceScriptInjectionEnabled) { 3384 ensureAccessibilityScriptInjectorInstance(false); 3385 // neither script injected nor script injection opted out => we inject 3386 loadUrl(ACCESSIBILITY_SCRIPT_CHOOSER_JAVASCRIPT); 3387 // TODO: Set this flag after successfull script injection. Maybe upon injection 3388 // the chooser should update the meta tag and we check it to declare success 3389 mAccessibilityScriptInjected = true; 3390 } else { 3391 // injection disabled so we fallback to the basic built-in support 3392 ensureAccessibilityScriptInjectorInstance(true); 3393 } 3394 } else if (axsParameterValue == ACCESSIBILITY_SCRIPT_INJECTION_OPTED_OUT) { 3395 // injection opted out so we fallback to the basic buil-in support 3396 ensureAccessibilityScriptInjectorInstance(true); 3397 } else if (axsParameterValue == ACCESSIBILITY_SCRIPT_INJECTION_PROVIDED) { 3398 ensureAccessibilityScriptInjectorInstance(false); 3399 // the URL provides accessibility but we still need to add our generic script 3400 loadUrl(ACCESSIBILITY_SCRIPT_CHOOSER_JAVASCRIPT); 3401 } else { 3402 Log.e(LOGTAG, "Unknown URL value for the \"axs\" URL parameter: " + axsParameterValue); 3403 } 3404 } 3405 3406 /** 3407 * Ensures the instance of the {@link AccessibilityInjector} to be present ot not. 3408 * 3409 * @param present True to ensure an insance, false to ensure no instance. 3410 */ 3411 private void ensureAccessibilityScriptInjectorInstance(boolean present) { 3412 if (present) { 3413 if (mAccessibilityInjector == null) { 3414 mAccessibilityInjector = new AccessibilityInjector(this); 3415 } 3416 } else { 3417 mAccessibilityInjector = null; 3418 } 3419 } 3420 3421 /** 3422 * Gets the "axs" URL parameter value. 3423 * 3424 * @param url A url to fetch the paramter from. 3425 * @return The parameter value if such, -1 otherwise. 3426 */ 3427 private int getAxsUrlParameterValue(String url) { 3428 if (mMatchAxsUrlParameterPattern == null) { 3429 mMatchAxsUrlParameterPattern = Pattern.compile(PATTERN_MATCH_AXS_URL_PARAMETER); 3430 } 3431 Matcher matcher = mMatchAxsUrlParameterPattern.matcher(url); 3432 if (matcher.find()) { 3433 String keyValuePair = url.substring(matcher.start(), matcher.end()); 3434 return Integer.parseInt(keyValuePair.split("=")[1]); 3435 } 3436 return -1; 3437 } 3438 3439 /** 3440 * The URL of a page that sent a message to scroll the title bar off screen. 3441 * 3442 * Many mobile sites tell the page to scroll to (0,1) in order to scroll the 3443 * title bar off the screen. Sometimes, the scroll position is set before 3444 * the page finishes loading. Rather than scrolling while the page is still 3445 * loading, keep track of the URL and new scroll position so we can perform 3446 * the scroll once the page finishes loading. 3447 */ 3448 private String mPageThatNeedsToSlideTitleBarOffScreen; 3449 3450 /** 3451 * The destination Y scroll position to be used when the page finishes 3452 * loading. See mPageThatNeedsToSlideTitleBarOffScreen. 3453 */ 3454 private int mYDistanceToSlideTitleOffScreen; 3455 3456 // scale from content to view coordinates, and pin 3457 // return true if pin caused the final x/y different than the request cx/cy, 3458 // and a future scroll may reach the request cx/cy after our size has 3459 // changed 3460 // return false if the view scroll to the exact position as it is requested, 3461 // where negative numbers are taken to mean 0 3462 private boolean setContentScrollTo(int cx, int cy) { 3463 if (mDrawHistory) { 3464 // disallow WebView to change the scroll position as History Picture 3465 // is used in the view system. 3466 // One known case where this is called is that WebCore tries to 3467 // restore the scroll position. As history Picture already uses the 3468 // saved scroll position, it is ok to skip this. 3469 return false; 3470 } 3471 int vx; 3472 int vy; 3473 if ((cx | cy) == 0) { 3474 // If the page is being scrolled to (0,0), do not add in the title 3475 // bar's height, and simply scroll to (0,0). (The only other work 3476 // in contentToView_ is to multiply, so this would not change 0.) 3477 vx = 0; 3478 vy = 0; 3479 } else { 3480 vx = contentToViewX(cx); 3481 vy = contentToViewY(cy); 3482 } 3483// Log.d(LOGTAG, "content scrollTo [" + cx + " " + cy + "] view=[" + 3484// vx + " " + vy + "]"); 3485 // Some mobile sites attempt to scroll the title bar off the page by 3486 // scrolling to (0,1). If we are at the top left corner of the 3487 // page, assume this is an attempt to scroll off the title bar, and 3488 // animate the title bar off screen slowly enough that the user can see 3489 // it. 3490 if (cx == 0 && cy == 1 && mScrollX == 0 && mScrollY == 0 3491 && mTitleBar != null) { 3492 // FIXME: 100 should be defined somewhere as our max progress. 3493 if (getProgress() < 100) { 3494 // Wait to scroll the title bar off screen until the page has 3495 // finished loading. Keep track of the URL and the destination 3496 // Y position 3497 mPageThatNeedsToSlideTitleBarOffScreen = getUrl(); 3498 mYDistanceToSlideTitleOffScreen = vy; 3499 } else { 3500 pinScrollTo(vx, vy, true, SLIDE_TITLE_DURATION); 3501 } 3502 // Since we are animating, we have not yet reached the desired 3503 // scroll position. Do not return true to request another attempt 3504 return false; 3505 } 3506 pinScrollTo(vx, vy, false, 0); 3507 // If the request was to scroll to a negative coordinate, treat it as if 3508 // it was a request to scroll to 0 3509 if ((mScrollX != vx && cx >= 0) || (mScrollY != vy && cy >= 0)) { 3510 return true; 3511 } else { 3512 return false; 3513 } 3514 } 3515 3516 // scale from content to view coordinates, and pin 3517 private void spawnContentScrollTo(int cx, int cy) { 3518 if (mDrawHistory) { 3519 // disallow WebView to change the scroll position as History Picture 3520 // is used in the view system. 3521 return; 3522 } 3523 int vx = contentToViewX(cx); 3524 int vy = contentToViewY(cy); 3525 pinScrollTo(vx, vy, true, 0); 3526 } 3527 3528 /** 3529 * These are from webkit, and are in content coordinate system (unzoomed) 3530 */ 3531 private void contentSizeChanged(boolean updateLayout) { 3532 // suppress 0,0 since we usually see real dimensions soon after 3533 // this avoids drawing the prev content in a funny place. If we find a 3534 // way to consolidate these notifications, this check may become 3535 // obsolete 3536 if ((mContentWidth | mContentHeight) == 0) { 3537 return; 3538 } 3539 3540 if (mHeightCanMeasure) { 3541 if (getMeasuredHeight() != contentToViewDimension(mContentHeight) 3542 || updateLayout) { 3543 requestLayout(); 3544 } 3545 } else if (mWidthCanMeasure) { 3546 if (getMeasuredWidth() != contentToViewDimension(mContentWidth) 3547 || updateLayout) { 3548 requestLayout(); 3549 } 3550 } else { 3551 // If we don't request a layout, try to send our view size to the 3552 // native side to ensure that WebCore has the correct dimensions. 3553 sendViewSizeZoom(false); 3554 } 3555 } 3556 3557 /** 3558 * Set the WebViewClient that will receive various notifications and 3559 * requests. This will replace the current handler. 3560 * @param client An implementation of WebViewClient. 3561 */ 3562 public void setWebViewClient(WebViewClient client) { 3563 mCallbackProxy.setWebViewClient(client); 3564 } 3565 3566 /** 3567 * Gets the WebViewClient 3568 * @return the current WebViewClient instance. 3569 * 3570 *@hide pending API council approval. 3571 */ 3572 public WebViewClient getWebViewClient() { 3573 return mCallbackProxy.getWebViewClient(); 3574 } 3575 3576 /** 3577 * Register the interface to be used when content can not be handled by 3578 * the rendering engine, and should be downloaded instead. This will replace 3579 * the current handler. 3580 * @param listener An implementation of DownloadListener. 3581 */ 3582 public void setDownloadListener(DownloadListener listener) { 3583 mCallbackProxy.setDownloadListener(listener); 3584 } 3585 3586 /** 3587 * Set the chrome handler. This is an implementation of WebChromeClient for 3588 * use in handling JavaScript dialogs, favicons, titles, and the progress. 3589 * This will replace the current handler. 3590 * @param client An implementation of WebChromeClient. 3591 */ 3592 public void setWebChromeClient(WebChromeClient client) { 3593 mCallbackProxy.setWebChromeClient(client); 3594 } 3595 3596 /** 3597 * Gets the chrome handler. 3598 * @return the current WebChromeClient instance. 3599 * 3600 * @hide API council approval. 3601 */ 3602 public WebChromeClient getWebChromeClient() { 3603 return mCallbackProxy.getWebChromeClient(); 3604 } 3605 3606 /** 3607 * Set the back/forward list client. This is an implementation of 3608 * WebBackForwardListClient for handling new items and changes in the 3609 * history index. 3610 * @param client An implementation of WebBackForwardListClient. 3611 * {@hide} 3612 */ 3613 public void setWebBackForwardListClient(WebBackForwardListClient client) { 3614 mCallbackProxy.setWebBackForwardListClient(client); 3615 } 3616 3617 /** 3618 * Gets the WebBackForwardListClient. 3619 * {@hide} 3620 */ 3621 public WebBackForwardListClient getWebBackForwardListClient() { 3622 return mCallbackProxy.getWebBackForwardListClient(); 3623 } 3624 3625 /** 3626 * Set the Picture listener. This is an interface used to receive 3627 * notifications of a new Picture. 3628 * @param listener An implementation of WebView.PictureListener. 3629 * @deprecated This method is now obsolete. 3630 */ 3631 @Deprecated 3632 public void setPictureListener(PictureListener listener) { 3633 mPictureListener = listener; 3634 } 3635 3636 /** 3637 * {@hide} 3638 */ 3639 /* FIXME: Debug only! Remove for SDK! */ 3640 public void externalRepresentation(Message callback) { 3641 mWebViewCore.sendMessage(EventHub.REQUEST_EXT_REPRESENTATION, callback); 3642 } 3643 3644 /** 3645 * {@hide} 3646 */ 3647 /* FIXME: Debug only! Remove for SDK! */ 3648 public void documentAsText(Message callback) { 3649 mWebViewCore.sendMessage(EventHub.REQUEST_DOC_AS_TEXT, callback); 3650 } 3651 3652 /** 3653 * Use this function to bind an object to JavaScript so that the 3654 * methods can be accessed from JavaScript. 3655 * <p><strong>IMPORTANT:</strong> 3656 * <ul> 3657 * <li> Using addJavascriptInterface() allows JavaScript to control your 3658 * application. This can be a very useful feature or a dangerous security 3659 * issue. When the HTML in the WebView is untrustworthy (for example, part 3660 * or all of the HTML is provided by some person or process), then an 3661 * attacker could inject HTML that will execute your code and possibly any 3662 * code of the attacker's choosing.<br> 3663 * Do not use addJavascriptInterface() unless all of the HTML in this 3664 * WebView was written by you.</li> 3665 * <li> The Java object that is bound runs in another thread and not in 3666 * the thread that it was constructed in.</li> 3667 * </ul></p> 3668 * @param obj The class instance to bind to JavaScript, null instances are 3669 * ignored. 3670 * @param interfaceName The name to used to expose the instance in 3671 * JavaScript. 3672 */ 3673 public void addJavascriptInterface(Object obj, String interfaceName) { 3674 if (obj == null) { 3675 return; 3676 } 3677 WebViewCore.JSInterfaceData arg = new WebViewCore.JSInterfaceData(); 3678 arg.mObject = obj; 3679 arg.mInterfaceName = interfaceName; 3680 mWebViewCore.sendMessage(EventHub.ADD_JS_INTERFACE, arg); 3681 } 3682 3683 /** 3684 * Removes a previously added JavaScript interface with the given name. 3685 * @param interfaceName The name of the interface to remove. 3686 */ 3687 public void removeJavascriptInterface(String interfaceName) { 3688 if (mWebViewCore != null) { 3689 WebViewCore.JSInterfaceData arg = new WebViewCore.JSInterfaceData(); 3690 arg.mInterfaceName = interfaceName; 3691 mWebViewCore.sendMessage(EventHub.REMOVE_JS_INTERFACE, arg); 3692 } 3693 } 3694 3695 /** 3696 * Return the WebSettings object used to control the settings for this 3697 * WebView. 3698 * @return A WebSettings object that can be used to control this WebView's 3699 * settings. 3700 */ 3701 public WebSettings getSettings() { 3702 return (mWebViewCore != null) ? mWebViewCore.getSettings() : null; 3703 } 3704 3705 /** 3706 * Return the list of currently loaded plugins. 3707 * @return The list of currently loaded plugins. 3708 * 3709 * @hide 3710 * @deprecated This was used for Gears, which has been deprecated. 3711 */ 3712 @Deprecated 3713 public static synchronized PluginList getPluginList() { 3714 return new PluginList(); 3715 } 3716 3717 /** 3718 * @hide 3719 * @deprecated This was used for Gears, which has been deprecated. 3720 */ 3721 @Deprecated 3722 public void refreshPlugins(boolean reloadOpenPages) { } 3723 3724 //------------------------------------------------------------------------- 3725 // Override View methods 3726 //------------------------------------------------------------------------- 3727 3728 @Override 3729 protected void finalize() throws Throwable { 3730 try { 3731 destroy(); 3732 } finally { 3733 super.finalize(); 3734 } 3735 } 3736 3737 @Override 3738 protected boolean drawChild(Canvas canvas, View child, long drawingTime) { 3739 if (child == mTitleBar) { 3740 // When drawing the title bar, move it horizontally to always show 3741 // at the top of the WebView. 3742 mTitleBar.offsetLeftAndRight(mScrollX - mTitleBar.getLeft()); 3743 int newTop = 0; 3744 if (mTitleGravity == Gravity.NO_GRAVITY) { 3745 newTop = Math.min(0, mScrollY); 3746 } else if (mTitleGravity == Gravity.TOP) { 3747 newTop = mScrollY; 3748 } 3749 mTitleBar.setBottom(newTop + mTitleBar.getHeight()); 3750 mTitleBar.setTop(newTop); 3751 } 3752 return super.drawChild(canvas, child, drawingTime); 3753 } 3754 3755 private void drawContent(Canvas canvas) { 3756 // Update the buttons in the picture, so when we draw the picture 3757 // to the screen, they are in the correct state. 3758 // Tell the native side if user is a) touching the screen, 3759 // b) pressing the trackball down, or c) pressing the enter key 3760 // If the cursor is on a button, we need to draw it in the pressed 3761 // state. 3762 // If mNativeClass is 0, we should not reach here, so we do not 3763 // need to check it again. 3764 nativeRecordButtons(hasFocus() && hasWindowFocus(), 3765 mTouchMode == TOUCH_SHORTPRESS_START_MODE 3766 || mTrackballDown || mGotCenterDown, false); 3767 drawCoreAndCursorRing(canvas, mBackgroundColor, mDrawCursorRing); 3768 } 3769 3770 /** 3771 * Draw the background when beyond bounds 3772 * @param canvas Canvas to draw into 3773 */ 3774 private void drawOverScrollBackground(Canvas canvas) { 3775 if (mOverScrollBackground == null) { 3776 mOverScrollBackground = new Paint(); 3777 Bitmap bm = BitmapFactory.decodeResource( 3778 mContext.getResources(), 3779 com.android.internal.R.drawable.status_bar_background); 3780 mOverScrollBackground.setShader(new BitmapShader(bm, 3781 Shader.TileMode.REPEAT, Shader.TileMode.REPEAT)); 3782 mOverScrollBorder = new Paint(); 3783 mOverScrollBorder.setStyle(Paint.Style.STROKE); 3784 mOverScrollBorder.setStrokeWidth(0); 3785 mOverScrollBorder.setColor(0xffbbbbbb); 3786 } 3787 3788 int top = 0; 3789 int right = computeRealHorizontalScrollRange(); 3790 int bottom = top + computeRealVerticalScrollRange(); 3791 // first draw the background and anchor to the top of the view 3792 canvas.save(); 3793 canvas.translate(mScrollX, mScrollY); 3794 canvas.clipRect(-mScrollX, top - mScrollY, right - mScrollX, bottom 3795 - mScrollY, Region.Op.DIFFERENCE); 3796 canvas.drawPaint(mOverScrollBackground); 3797 canvas.restore(); 3798 // then draw the border 3799 canvas.drawRect(-1, top - 1, right, bottom, mOverScrollBorder); 3800 // next clip the region for the content 3801 canvas.clipRect(0, top, right, bottom); 3802 } 3803 3804 @Override 3805 protected void onDraw(Canvas canvas) { 3806 // if mNativeClass is 0, the WebView has been destroyed. Do nothing. 3807 if (mNativeClass == 0) { 3808 return; 3809 } 3810 3811 // if both mContentWidth and mContentHeight are 0, it means there is no 3812 // valid Picture passed to WebView yet. This can happen when WebView 3813 // just starts. Draw the background and return. 3814 if ((mContentWidth | mContentHeight) == 0 && mHistoryPicture == null) { 3815 canvas.drawColor(mBackgroundColor); 3816 return; 3817 } 3818 3819 if (canvas.isHardwareAccelerated()) { 3820 mZoomManager.setHardwareAccelerated(); 3821 } 3822 3823 int saveCount = canvas.save(); 3824 if (mInOverScrollMode && !getSettings() 3825 .getUseWebViewBackgroundForOverscrollBackground()) { 3826 drawOverScrollBackground(canvas); 3827 } 3828 if (mTitleBar != null) { 3829 canvas.translate(0, getTitleHeight()); 3830 } 3831 drawContent(canvas); 3832 canvas.restoreToCount(saveCount); 3833 3834 if (AUTO_REDRAW_HACK && mAutoRedraw) { 3835 invalidate(); 3836 } 3837 if (inEditingMode()) { 3838 mWebTextView.onDrawSubstitute(); 3839 } 3840 mWebViewCore.signalRepaintDone(); 3841 3842 if (mOverScrollGlow != null && mOverScrollGlow.drawEdgeGlows(canvas)) { 3843 invalidate(); 3844 } 3845 3846 // paint the highlight in the end 3847 if (!mTouchHighlightRegion.isEmpty()) { 3848 if (mTouchHightlightPaint == null) { 3849 mTouchHightlightPaint = new Paint(); 3850 mTouchHightlightPaint.setColor(mHightlightColor); 3851 mTouchHightlightPaint.setAntiAlias(true); 3852 mTouchHightlightPaint.setPathEffect(new CornerPathEffect( 3853 TOUCH_HIGHLIGHT_ARC)); 3854 } 3855 canvas.drawPath(mTouchHighlightRegion.getBoundaryPath(), 3856 mTouchHightlightPaint); 3857 } 3858 if (DEBUG_TOUCH_HIGHLIGHT) { 3859 if (getSettings().getNavDump()) { 3860 if ((mTouchHighlightX | mTouchHighlightY) != 0) { 3861 if (mTouchCrossHairColor == null) { 3862 mTouchCrossHairColor = new Paint(); 3863 mTouchCrossHairColor.setColor(Color.RED); 3864 } 3865 canvas.drawLine(mTouchHighlightX - mNavSlop, 3866 mTouchHighlightY - mNavSlop, mTouchHighlightX 3867 + mNavSlop + 1, mTouchHighlightY + mNavSlop 3868 + 1, mTouchCrossHairColor); 3869 canvas.drawLine(mTouchHighlightX + mNavSlop + 1, 3870 mTouchHighlightY - mNavSlop, mTouchHighlightX 3871 - mNavSlop, 3872 mTouchHighlightY + mNavSlop + 1, 3873 mTouchCrossHairColor); 3874 } 3875 } 3876 } 3877 } 3878 3879 private void removeTouchHighlight(boolean removePendingMessage) { 3880 if (removePendingMessage) { 3881 mWebViewCore.removeMessages(EventHub.GET_TOUCH_HIGHLIGHT_RECTS); 3882 } 3883 mWebViewCore.sendMessage(EventHub.REMOVE_TOUCH_HIGHLIGHT_RECTS); 3884 } 3885 3886 @Override 3887 public void setLayoutParams(ViewGroup.LayoutParams params) { 3888 if (params.height == LayoutParams.WRAP_CONTENT) { 3889 mWrapContent = true; 3890 } 3891 super.setLayoutParams(params); 3892 } 3893 3894 @Override 3895 public boolean performLongClick() { 3896 // performLongClick() is the result of a delayed message. If we switch 3897 // to windows overview, the WebView will be temporarily removed from the 3898 // view system. In that case, do nothing. 3899 if (getParent() == null) return false; 3900 3901 // A multi-finger gesture can look like a long press; make sure we don't take 3902 // long press actions if we're scaling. 3903 final ScaleGestureDetector detector = mZoomManager.getMultiTouchGestureDetector(); 3904 if (detector != null && detector.isInProgress()) { 3905 return false; 3906 } 3907 3908 if (mNativeClass != 0 && nativeCursorIsTextInput()) { 3909 // Send the click so that the textfield is in focus 3910 centerKeyPressOnTextField(); 3911 rebuildWebTextView(); 3912 } else { 3913 clearTextEntry(); 3914 } 3915 if (inEditingMode()) { 3916 // Since we just called rebuildWebTextView, the layout is not set 3917 // properly. Update it so it can correctly find the word to select. 3918 mWebTextView.ensureLayout(); 3919 // Provide a touch down event to WebTextView, which will allow it 3920 // to store the location to use in performLongClick. 3921 AbsoluteLayout.LayoutParams params 3922 = (AbsoluteLayout.LayoutParams) mWebTextView.getLayoutParams(); 3923 MotionEvent fake = MotionEvent.obtain(mLastTouchTime, 3924 mLastTouchTime, MotionEvent.ACTION_DOWN, 3925 mLastTouchX - params.x + mScrollX, 3926 mLastTouchY - params.y + mScrollY, 0); 3927 mWebTextView.dispatchTouchEvent(fake); 3928 return mWebTextView.performLongClick(); 3929 } 3930 if (mSelectingText) return false; // long click does nothing on selection 3931 /* if long click brings up a context menu, the super function 3932 * returns true and we're done. Otherwise, nothing happened when 3933 * the user clicked. */ 3934 if (super.performLongClick()) { 3935 return true; 3936 } 3937 /* In the case where the application hasn't already handled the long 3938 * click action, look for a word under the click. If one is found, 3939 * animate the text selection into view. 3940 * FIXME: no animation code yet */ 3941 return selectText(); 3942 } 3943 3944 /** 3945 * Select the word at the last click point. 3946 * 3947 * @hide pending API council approval 3948 */ 3949 public boolean selectText() { 3950 int x = viewToContentX(mLastTouchX + mScrollX); 3951 int y = viewToContentY(mLastTouchY + mScrollY); 3952 return selectText(x, y); 3953 } 3954 3955 /** 3956 * Select the word at the indicated content coordinates. 3957 */ 3958 boolean selectText(int x, int y) { 3959 if (!setUpSelect(true, x, y)) { 3960 return false; 3961 } 3962 nativeSetExtendSelection(); 3963 mDrawSelectionPointer = false; 3964 mSelectionStarted = true; 3965 mTouchMode = TOUCH_DRAG_MODE; 3966 return true; 3967 } 3968 3969 private int mOrientation = Configuration.ORIENTATION_UNDEFINED; 3970 3971 @Override 3972 protected void onConfigurationChanged(Configuration newConfig) { 3973 if (mSelectingText && mOrientation != newConfig.orientation) { 3974 selectionDone(); 3975 } 3976 mOrientation = newConfig.orientation; 3977 } 3978 3979 /** 3980 * Keep track of the Callback so we can end its ActionMode or remove its 3981 * titlebar. 3982 */ 3983 private SelectActionModeCallback mSelectCallback; 3984 3985 // These values are possible options for didUpdateWebTextViewDimensions. 3986 private static final int FULLY_ON_SCREEN = 0; 3987 private static final int INTERSECTS_SCREEN = 1; 3988 private static final int ANYWHERE = 2; 3989 3990 /** 3991 * Check to see if the focused textfield/textarea is still on screen. If it 3992 * is, update the the dimensions and location of WebTextView. Otherwise, 3993 * remove the WebTextView. Should be called when the zoom level changes. 3994 * @param intersection How to determine whether the textfield/textarea is 3995 * still on screen. 3996 * @return boolean True if the textfield/textarea is still on screen and the 3997 * dimensions/location of WebTextView have been updated. 3998 */ 3999 private boolean didUpdateWebTextViewDimensions(int intersection) { 4000 Rect contentBounds = nativeFocusCandidateNodeBounds(); 4001 Rect vBox = contentToViewRect(contentBounds); 4002 Rect visibleRect = new Rect(); 4003 calcOurVisibleRect(visibleRect); 4004 // If the textfield is on screen, place the WebTextView in 4005 // its new place, accounting for our new scroll/zoom values, 4006 // and adjust its textsize. 4007 boolean onScreen; 4008 switch (intersection) { 4009 case FULLY_ON_SCREEN: 4010 onScreen = visibleRect.contains(vBox); 4011 break; 4012 case INTERSECTS_SCREEN: 4013 onScreen = Rect.intersects(visibleRect, vBox); 4014 break; 4015 case ANYWHERE: 4016 onScreen = true; 4017 break; 4018 default: 4019 throw new AssertionError( 4020 "invalid parameter passed to didUpdateWebTextViewDimensions"); 4021 } 4022 if (onScreen) { 4023 mWebTextView.setRect(vBox.left, vBox.top, vBox.width(), 4024 vBox.height()); 4025 mWebTextView.updateTextSize(); 4026 updateWebTextViewPadding(); 4027 return true; 4028 } else { 4029 // The textfield is now off screen. The user probably 4030 // was not zooming to see the textfield better. Remove 4031 // the WebTextView. If the user types a key, and the 4032 // textfield is still in focus, we will reconstruct 4033 // the WebTextView and scroll it back on screen. 4034 mWebTextView.remove(); 4035 return false; 4036 } 4037 } 4038 4039 void setBaseLayer(int layer, Region invalRegion, boolean showVisualIndicator) { 4040 if (mNativeClass == 0) 4041 return; 4042 nativeSetBaseLayer(layer, invalRegion, showVisualIndicator); 4043 } 4044 4045 private void onZoomAnimationStart() { 4046 // If it is in password mode, turn it off so it does not draw misplaced. 4047 if (inEditingMode() && nativeFocusCandidateIsPassword()) { 4048 mWebTextView.setInPassword(false); 4049 } 4050 } 4051 4052 private void onZoomAnimationEnd() { 4053 // adjust the edit text view if needed 4054 if (inEditingMode() && didUpdateWebTextViewDimensions(FULLY_ON_SCREEN) 4055 && nativeFocusCandidateIsPassword()) { 4056 // If it is a password field, start drawing the WebTextView once 4057 // again. 4058 mWebTextView.setInPassword(true); 4059 } 4060 } 4061 4062 void onFixedLengthZoomAnimationStart() { 4063 WebViewCore.pauseUpdatePicture(getWebViewCore()); 4064 onZoomAnimationStart(); 4065 } 4066 4067 void onFixedLengthZoomAnimationEnd() { 4068 if (!mSelectingText) { 4069 WebViewCore.resumeUpdatePicture(mWebViewCore); 4070 } 4071 onZoomAnimationEnd(); 4072 } 4073 4074 private static final int ZOOM_BITS = Paint.FILTER_BITMAP_FLAG | 4075 Paint.DITHER_FLAG | 4076 Paint.SUBPIXEL_TEXT_FLAG; 4077 private static final int SCROLL_BITS = Paint.FILTER_BITMAP_FLAG | 4078 Paint.DITHER_FLAG; 4079 4080 private final DrawFilter mZoomFilter = 4081 new PaintFlagsDrawFilter(ZOOM_BITS, Paint.LINEAR_TEXT_FLAG); 4082 // If we need to trade better quality for speed, set mScrollFilter to null 4083 private final DrawFilter mScrollFilter = 4084 new PaintFlagsDrawFilter(SCROLL_BITS, 0); 4085 4086 private void drawCoreAndCursorRing(Canvas canvas, int color, 4087 boolean drawCursorRing) { 4088 if (mDrawHistory) { 4089 canvas.scale(mZoomManager.getScale(), mZoomManager.getScale()); 4090 canvas.drawPicture(mHistoryPicture); 4091 return; 4092 } 4093 if (mNativeClass == 0) return; 4094 4095 boolean animateZoom = mZoomManager.isFixedLengthAnimationInProgress(); 4096 boolean animateScroll = ((!mScroller.isFinished() 4097 || mVelocityTracker != null) 4098 && (mTouchMode != TOUCH_DRAG_MODE || 4099 mHeldMotionless != MOTIONLESS_TRUE)) 4100 || mDeferTouchMode == TOUCH_DRAG_MODE; 4101 if (mTouchMode == TOUCH_DRAG_MODE) { 4102 if (mHeldMotionless == MOTIONLESS_PENDING) { 4103 mPrivateHandler.removeMessages(DRAG_HELD_MOTIONLESS); 4104 mPrivateHandler.removeMessages(AWAKEN_SCROLL_BARS); 4105 mHeldMotionless = MOTIONLESS_FALSE; 4106 } 4107 if (mHeldMotionless == MOTIONLESS_FALSE) { 4108 mPrivateHandler.sendMessageDelayed(mPrivateHandler 4109 .obtainMessage(DRAG_HELD_MOTIONLESS), MOTIONLESS_TIME); 4110 mHeldMotionless = MOTIONLESS_PENDING; 4111 } 4112 } 4113 if (animateZoom) { 4114 mZoomManager.animateZoom(canvas); 4115 } else if (!canvas.isHardwareAccelerated()) { 4116 canvas.scale(mZoomManager.getScale(), mZoomManager.getScale()); 4117 } 4118 4119 boolean UIAnimationsRunning = false; 4120 // Currently for each draw we compute the animation values; 4121 // We may in the future decide to do that independently. 4122 if (mNativeClass != 0 && nativeEvaluateLayersAnimations()) { 4123 UIAnimationsRunning = true; 4124 // If we have unfinished (or unstarted) animations, 4125 // we ask for a repaint. 4126 invalidate(); 4127 } 4128 4129 // decide which adornments to draw 4130 int extras = DRAW_EXTRAS_NONE; 4131 if (mFindIsUp) { 4132 extras = DRAW_EXTRAS_FIND; 4133 } else if (mSelectingText) { 4134 extras = DRAW_EXTRAS_SELECTION; 4135 nativeSetSelectionPointer(mDrawSelectionPointer, 4136 mZoomManager.getInvScale(), 4137 mSelectX, mSelectY - getTitleHeight()); 4138 } else if (drawCursorRing) { 4139 extras = DRAW_EXTRAS_CURSOR_RING; 4140 } 4141 if (DebugFlags.WEB_VIEW) { 4142 Log.v(LOGTAG, "mFindIsUp=" + mFindIsUp 4143 + " mSelectingText=" + mSelectingText 4144 + " nativePageShouldHandleShiftAndArrows()=" 4145 + nativePageShouldHandleShiftAndArrows() 4146 + " animateZoom=" + animateZoom 4147 + " extras=" + extras); 4148 } 4149 4150 if (canvas.isHardwareAccelerated()) { 4151 int functor = nativeGetDrawGLFunction(mGLViewportEmpty ? null : mGLRectViewport, 4152 mGLViewportEmpty ? null : mViewRectViewport, getScale(), extras); 4153 ((HardwareCanvas) canvas).callDrawGLFunction(functor); 4154 } else { 4155 DrawFilter df = null; 4156 if (mZoomManager.isZoomAnimating() || UIAnimationsRunning) { 4157 df = mZoomFilter; 4158 } else if (animateScroll) { 4159 df = mScrollFilter; 4160 } 4161 canvas.setDrawFilter(df); 4162 // XXX: Revisit splitting content. Right now it causes a 4163 // synchronization problem with layers. 4164 int content = nativeDraw(canvas, color, extras, false); 4165 canvas.setDrawFilter(null); 4166 if (content != 0) { 4167 mWebViewCore.sendMessage(EventHub.SPLIT_PICTURE_SET, content, 0); 4168 } 4169 } 4170 4171 if (extras == DRAW_EXTRAS_CURSOR_RING) { 4172 if (mTouchMode == TOUCH_SHORTPRESS_START_MODE) { 4173 mTouchMode = TOUCH_SHORTPRESS_MODE; 4174 } 4175 } 4176 if (mFocusSizeChanged) { 4177 mFocusSizeChanged = false; 4178 // If we are zooming, this will get handled above, when the zoom 4179 // finishes. We also do not need to do this unless the WebTextView 4180 // is showing. 4181 if (!animateZoom && inEditingMode()) { 4182 didUpdateWebTextViewDimensions(ANYWHERE); 4183 } 4184 } 4185 } 4186 4187 // draw history 4188 private boolean mDrawHistory = false; 4189 private Picture mHistoryPicture = null; 4190 private int mHistoryWidth = 0; 4191 private int mHistoryHeight = 0; 4192 4193 // Only check the flag, can be called from WebCore thread 4194 boolean drawHistory() { 4195 return mDrawHistory; 4196 } 4197 4198 int getHistoryPictureWidth() { 4199 return (mHistoryPicture != null) ? mHistoryPicture.getWidth() : 0; 4200 } 4201 4202 // Should only be called in UI thread 4203 void switchOutDrawHistory() { 4204 if (null == mWebViewCore) return; // CallbackProxy may trigger this 4205 if (mDrawHistory && (getProgress() == 100 || nativeHasContent())) { 4206 mDrawHistory = false; 4207 mHistoryPicture = null; 4208 invalidate(); 4209 int oldScrollX = mScrollX; 4210 int oldScrollY = mScrollY; 4211 mScrollX = pinLocX(mScrollX); 4212 mScrollY = pinLocY(mScrollY); 4213 if (oldScrollX != mScrollX || oldScrollY != mScrollY) { 4214 onScrollChanged(mScrollX, mScrollY, oldScrollX, oldScrollY); 4215 } else { 4216 sendOurVisibleRect(); 4217 } 4218 } 4219 } 4220 4221 WebViewCore.CursorData cursorData() { 4222 WebViewCore.CursorData result = new WebViewCore.CursorData(); 4223 result.mMoveGeneration = nativeMoveGeneration(); 4224 result.mFrame = nativeCursorFramePointer(); 4225 Point position = nativeCursorPosition(); 4226 result.mX = position.x; 4227 result.mY = position.y; 4228 return result; 4229 } 4230 4231 /** 4232 * Delete text from start to end in the focused textfield. If there is no 4233 * focus, or if start == end, silently fail. If start and end are out of 4234 * order, swap them. 4235 * @param start Beginning of selection to delete. 4236 * @param end End of selection to delete. 4237 */ 4238 /* package */ void deleteSelection(int start, int end) { 4239 mTextGeneration++; 4240 WebViewCore.TextSelectionData data 4241 = new WebViewCore.TextSelectionData(start, end); 4242 mWebViewCore.sendMessage(EventHub.DELETE_SELECTION, mTextGeneration, 0, 4243 data); 4244 } 4245 4246 /** 4247 * Set the selection to (start, end) in the focused textfield. If start and 4248 * end are out of order, swap them. 4249 * @param start Beginning of selection. 4250 * @param end End of selection. 4251 */ 4252 /* package */ void setSelection(int start, int end) { 4253 if (mWebViewCore != null) { 4254 mWebViewCore.sendMessage(EventHub.SET_SELECTION, start, end); 4255 } 4256 } 4257 4258 @Override 4259 public InputConnection onCreateInputConnection(EditorInfo outAttrs) { 4260 InputConnection connection = super.onCreateInputConnection(outAttrs); 4261 outAttrs.imeOptions |= EditorInfo.IME_FLAG_NO_FULLSCREEN; 4262 return connection; 4263 } 4264 4265 /** 4266 * Called in response to a message from webkit telling us that the soft 4267 * keyboard should be launched. 4268 */ 4269 private void displaySoftKeyboard(boolean isTextView) { 4270 InputMethodManager imm = (InputMethodManager) 4271 getContext().getSystemService(Context.INPUT_METHOD_SERVICE); 4272 4273 // bring it back to the default level scale so that user can enter text 4274 boolean zoom = mZoomManager.getScale() < mZoomManager.getDefaultScale(); 4275 if (zoom) { 4276 mZoomManager.setZoomCenter(mLastTouchX, mLastTouchY); 4277 mZoomManager.setZoomScale(mZoomManager.getDefaultScale(), false); 4278 } 4279 if (isTextView) { 4280 rebuildWebTextView(); 4281 if (inEditingMode()) { 4282 imm.showSoftInput(mWebTextView, 0); 4283 if (zoom) { 4284 didUpdateWebTextViewDimensions(INTERSECTS_SCREEN); 4285 } 4286 return; 4287 } 4288 } 4289 // Used by plugins and contentEditable. 4290 // Also used if the navigation cache is out of date, and 4291 // does not recognize that a textfield is in focus. In that 4292 // case, use WebView as the targeted view. 4293 // see http://b/issue?id=2457459 4294 imm.showSoftInput(this, 0); 4295 } 4296 4297 // Called by WebKit to instruct the UI to hide the keyboard 4298 private void hideSoftKeyboard() { 4299 InputMethodManager imm = InputMethodManager.peekInstance(); 4300 if (imm != null && (imm.isActive(this) 4301 || (inEditingMode() && imm.isActive(mWebTextView)))) { 4302 imm.hideSoftInputFromWindow(this.getWindowToken(), 0); 4303 } 4304 } 4305 4306 /* 4307 * This method checks the current focus and cursor and potentially rebuilds 4308 * mWebTextView to have the appropriate properties, such as password, 4309 * multiline, and what text it contains. It also removes it if necessary. 4310 */ 4311 /* package */ void rebuildWebTextView() { 4312 // If the WebView does not have focus, do nothing until it gains focus. 4313 if (!hasFocus() && (null == mWebTextView || !mWebTextView.hasFocus())) { 4314 return; 4315 } 4316 boolean alreadyThere = inEditingMode(); 4317 // inEditingMode can only return true if mWebTextView is non-null, 4318 // so we can safely call remove() if (alreadyThere) 4319 if (0 == mNativeClass || !nativeFocusCandidateIsTextInput()) { 4320 if (alreadyThere) { 4321 mWebTextView.remove(); 4322 } 4323 return; 4324 } 4325 // At this point, we know we have found an input field, so go ahead 4326 // and create the WebTextView if necessary. 4327 if (mWebTextView == null) { 4328 mWebTextView = new WebTextView(mContext, WebView.this, mAutoFillData.getQueryId()); 4329 // Initialize our generation number. 4330 mTextGeneration = 0; 4331 } 4332 mWebTextView.updateTextSize(); 4333 Rect visibleRect = new Rect(); 4334 calcOurContentVisibleRect(visibleRect); 4335 // Note that sendOurVisibleRect calls viewToContent, so the coordinates 4336 // should be in content coordinates. 4337 Rect bounds = nativeFocusCandidateNodeBounds(); 4338 Rect vBox = contentToViewRect(bounds); 4339 mWebTextView.setRect(vBox.left, vBox.top, vBox.width(), vBox.height()); 4340 if (!Rect.intersects(bounds, visibleRect)) { 4341 revealSelection(); 4342 } 4343 String text = nativeFocusCandidateText(); 4344 int nodePointer = nativeFocusCandidatePointer(); 4345 if (alreadyThere && mWebTextView.isSameTextField(nodePointer)) { 4346 // It is possible that we have the same textfield, but it has moved, 4347 // i.e. In the case of opening/closing the screen. 4348 // In that case, we need to set the dimensions, but not the other 4349 // aspects. 4350 // If the text has been changed by webkit, update it. However, if 4351 // there has been more UI text input, ignore it. We will receive 4352 // another update when that text is recognized. 4353 if (text != null && !text.equals(mWebTextView.getText().toString()) 4354 && nativeTextGeneration() == mTextGeneration) { 4355 mWebTextView.setTextAndKeepSelection(text); 4356 } 4357 } else { 4358 mWebTextView.setGravity(nativeFocusCandidateIsRtlText() ? 4359 Gravity.RIGHT : Gravity.NO_GRAVITY); 4360 // This needs to be called before setType, which may call 4361 // requestFormData, and it needs to have the correct nodePointer. 4362 mWebTextView.setNodePointer(nodePointer); 4363 mWebTextView.setType(nativeFocusCandidateType()); 4364 updateWebTextViewPadding(); 4365 if (null == text) { 4366 if (DebugFlags.WEB_VIEW) { 4367 Log.v(LOGTAG, "rebuildWebTextView null == text"); 4368 } 4369 text = ""; 4370 } 4371 mWebTextView.setTextAndKeepSelection(text); 4372 InputMethodManager imm = InputMethodManager.peekInstance(); 4373 if (imm != null && imm.isActive(mWebTextView)) { 4374 imm.restartInput(mWebTextView); 4375 } 4376 } 4377 if (isFocused()) { 4378 mWebTextView.requestFocus(); 4379 } 4380 } 4381 4382 /** 4383 * Update the padding of mWebTextView based on the native textfield/textarea 4384 */ 4385 void updateWebTextViewPadding() { 4386 Rect paddingRect = nativeFocusCandidatePaddingRect(); 4387 if (paddingRect != null) { 4388 // Use contentToViewDimension since these are the dimensions of 4389 // the padding. 4390 mWebTextView.setPadding( 4391 contentToViewDimension(paddingRect.left), 4392 contentToViewDimension(paddingRect.top), 4393 contentToViewDimension(paddingRect.right), 4394 contentToViewDimension(paddingRect.bottom)); 4395 } 4396 } 4397 4398 /** 4399 * Tell webkit to put the cursor on screen. 4400 */ 4401 /* package */ void revealSelection() { 4402 if (mWebViewCore != null) { 4403 mWebViewCore.sendMessage(EventHub.REVEAL_SELECTION); 4404 } 4405 } 4406 4407 /** 4408 * Called by WebTextView to find saved form data associated with the 4409 * textfield 4410 * @param name Name of the textfield. 4411 * @param nodePointer Pointer to the node of the textfield, so it can be 4412 * compared to the currently focused textfield when the data is 4413 * retrieved. 4414 * @param autoFillable true if WebKit has determined this field is part of 4415 * a form that can be auto filled. 4416 * @param autoComplete true if the attribute "autocomplete" is set to true 4417 * on the textfield. 4418 */ 4419 /* package */ void requestFormData(String name, int nodePointer, 4420 boolean autoFillable, boolean autoComplete) { 4421 if (mWebViewCore.getSettings().getSaveFormData()) { 4422 Message update = mPrivateHandler.obtainMessage(REQUEST_FORM_DATA); 4423 update.arg1 = nodePointer; 4424 RequestFormData updater = new RequestFormData(name, getUrl(), 4425 update, autoFillable, autoComplete); 4426 Thread t = new Thread(updater); 4427 t.start(); 4428 } 4429 } 4430 4431 /** 4432 * Pass a message to find out the <label> associated with the <input> 4433 * identified by nodePointer 4434 * @param framePointer Pointer to the frame containing the <input> node 4435 * @param nodePointer Pointer to the node for which a <label> is desired. 4436 */ 4437 /* package */ void requestLabel(int framePointer, int nodePointer) { 4438 mWebViewCore.sendMessage(EventHub.REQUEST_LABEL, framePointer, 4439 nodePointer); 4440 } 4441 4442 /* 4443 * This class requests an Adapter for the WebTextView which shows past 4444 * entries stored in the database. It is a Runnable so that it can be done 4445 * in its own thread, without slowing down the UI. 4446 */ 4447 private class RequestFormData implements Runnable { 4448 private String mName; 4449 private String mUrl; 4450 private Message mUpdateMessage; 4451 private boolean mAutoFillable; 4452 private boolean mAutoComplete; 4453 4454 public RequestFormData(String name, String url, Message msg, 4455 boolean autoFillable, boolean autoComplete) { 4456 mName = name; 4457 mUrl = url; 4458 mUpdateMessage = msg; 4459 mAutoFillable = autoFillable; 4460 mAutoComplete = autoComplete; 4461 } 4462 4463 public void run() { 4464 ArrayList<String> pastEntries = new ArrayList<String>(); 4465 4466 if (mAutoFillable) { 4467 // Note that code inside the adapter click handler in WebTextView depends 4468 // on the AutoFill item being at the top of the drop down list. If you change 4469 // the order, make sure to do it there too! 4470 WebSettings settings = getSettings(); 4471 if (settings != null && settings.getAutoFillProfile() != null) { 4472 pastEntries.add(getResources().getText( 4473 com.android.internal.R.string.autofill_this_form).toString() + 4474 " " + 4475 mAutoFillData.getPreviewString()); 4476 mWebTextView.setAutoFillProfileIsSet(true); 4477 } else { 4478 // There is no autofill profile set up yet, so add an option that 4479 // will invite the user to set their profile up. 4480 pastEntries.add(getResources().getText( 4481 com.android.internal.R.string.setup_autofill).toString()); 4482 mWebTextView.setAutoFillProfileIsSet(false); 4483 } 4484 } 4485 4486 if (mAutoComplete) { 4487 pastEntries.addAll(mDatabase.getFormData(mUrl, mName)); 4488 } 4489 4490 if (pastEntries.size() > 0) { 4491 AutoCompleteAdapter adapter = new 4492 AutoCompleteAdapter(mContext, pastEntries); 4493 mUpdateMessage.obj = adapter; 4494 mUpdateMessage.sendToTarget(); 4495 } 4496 } 4497 } 4498 4499 /** 4500 * Dump the display tree to "/sdcard/displayTree.txt" 4501 * 4502 * @hide debug only 4503 */ 4504 public void dumpDisplayTree() { 4505 nativeDumpDisplayTree(getUrl()); 4506 } 4507 4508 /** 4509 * Dump the dom tree to adb shell if "toFile" is False, otherwise dump it to 4510 * "/sdcard/domTree.txt" 4511 * 4512 * @hide debug only 4513 */ 4514 public void dumpDomTree(boolean toFile) { 4515 mWebViewCore.sendMessage(EventHub.DUMP_DOMTREE, toFile ? 1 : 0, 0); 4516 } 4517 4518 /** 4519 * Dump the render tree to adb shell if "toFile" is False, otherwise dump it 4520 * to "/sdcard/renderTree.txt" 4521 * 4522 * @hide debug only 4523 */ 4524 public void dumpRenderTree(boolean toFile) { 4525 mWebViewCore.sendMessage(EventHub.DUMP_RENDERTREE, toFile ? 1 : 0, 0); 4526 } 4527 4528 /** 4529 * Called by DRT on UI thread, need to proxy to WebCore thread. 4530 * 4531 * @hide debug only 4532 */ 4533 public void useMockDeviceOrientation() { 4534 mWebViewCore.sendMessage(EventHub.USE_MOCK_DEVICE_ORIENTATION); 4535 } 4536 4537 /** 4538 * Called by DRT on WebCore thread. 4539 * 4540 * @hide debug only 4541 */ 4542 public void setMockDeviceOrientation(boolean canProvideAlpha, double alpha, 4543 boolean canProvideBeta, double beta, boolean canProvideGamma, double gamma) { 4544 mWebViewCore.setMockDeviceOrientation(canProvideAlpha, alpha, canProvideBeta, beta, 4545 canProvideGamma, gamma); 4546 } 4547 4548 /** 4549 * Dump the V8 counters to standard output. 4550 * Note that you need a build with V8 and WEBCORE_INSTRUMENTATION set to 4551 * true. Otherwise, this will do nothing. 4552 * 4553 * @hide debug only 4554 */ 4555 public void dumpV8Counters() { 4556 mWebViewCore.sendMessage(EventHub.DUMP_V8COUNTERS); 4557 } 4558 4559 // This is used to determine long press with the center key. Does not 4560 // affect long press with the trackball/touch. 4561 private boolean mGotCenterDown = false; 4562 4563 @Override 4564 public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) { 4565 // send complex characters to webkit for use by JS and plugins 4566 if (keyCode == KeyEvent.KEYCODE_UNKNOWN && event.getCharacters() != null) { 4567 // pass the key to DOM 4568 mWebViewCore.sendMessage(EventHub.KEY_DOWN, event); 4569 mWebViewCore.sendMessage(EventHub.KEY_UP, event); 4570 // return true as DOM handles the key 4571 return true; 4572 } 4573 return false; 4574 } 4575 4576 private boolean isEnterActionKey(int keyCode) { 4577 return keyCode == KeyEvent.KEYCODE_DPAD_CENTER 4578 || keyCode == KeyEvent.KEYCODE_ENTER 4579 || keyCode == KeyEvent.KEYCODE_NUMPAD_ENTER; 4580 } 4581 4582 @Override 4583 public boolean onKeyDown(int keyCode, KeyEvent event) { 4584 if (DebugFlags.WEB_VIEW) { 4585 Log.v(LOGTAG, "keyDown at " + System.currentTimeMillis() 4586 + "keyCode=" + keyCode 4587 + ", " + event + ", unicode=" + event.getUnicodeChar()); 4588 } 4589 4590 // don't implement accelerator keys here; defer to host application 4591 if (event.isCtrlPressed()) { 4592 return false; 4593 } 4594 4595 if (mNativeClass == 0) { 4596 return false; 4597 } 4598 4599 // do this hack up front, so it always works, regardless of touch-mode 4600 if (AUTO_REDRAW_HACK && (keyCode == KeyEvent.KEYCODE_CALL)) { 4601 mAutoRedraw = !mAutoRedraw; 4602 if (mAutoRedraw) { 4603 invalidate(); 4604 } 4605 return true; 4606 } 4607 4608 // Bubble up the key event if 4609 // 1. it is a system key; or 4610 // 2. the host application wants to handle it; 4611 if (event.isSystem() 4612 || mCallbackProxy.uiOverrideKeyEvent(event)) { 4613 return false; 4614 } 4615 4616 // accessibility support 4617 if (accessibilityScriptInjected()) { 4618 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 4619 // if an accessibility script is injected we delegate to it the key handling. 4620 // this script is a screen reader which is a fully fledged solution for blind 4621 // users to navigate in and interact with web pages. 4622 mWebViewCore.sendMessage(EventHub.KEY_DOWN, event); 4623 return true; 4624 } else { 4625 // Clean up if accessibility was disabled after loading the current URL. 4626 mAccessibilityScriptInjected = false; 4627 } 4628 } else if (mAccessibilityInjector != null) { 4629 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 4630 if (mAccessibilityInjector.onKeyEvent(event)) { 4631 // if an accessibility injector is present (no JavaScript enabled or the site 4632 // opts out injecting our JavaScript screen reader) we let it decide whether 4633 // to act on and consume the event. 4634 return true; 4635 } 4636 } else { 4637 // Clean up if accessibility was disabled after loading the current URL. 4638 mAccessibilityInjector = null; 4639 } 4640 } 4641 4642 if (keyCode == KeyEvent.KEYCODE_PAGE_UP) { 4643 if (event.hasNoModifiers()) { 4644 pageUp(false); 4645 return true; 4646 } else if (event.hasModifiers(KeyEvent.META_ALT_ON)) { 4647 pageUp(true); 4648 return true; 4649 } 4650 } 4651 4652 if (keyCode == KeyEvent.KEYCODE_PAGE_DOWN) { 4653 if (event.hasNoModifiers()) { 4654 pageDown(false); 4655 return true; 4656 } else if (event.hasModifiers(KeyEvent.META_ALT_ON)) { 4657 pageDown(true); 4658 return true; 4659 } 4660 } 4661 4662 if (keyCode == KeyEvent.KEYCODE_MOVE_HOME && event.hasNoModifiers()) { 4663 pageUp(true); 4664 return true; 4665 } 4666 4667 if (keyCode == KeyEvent.KEYCODE_MOVE_END && event.hasNoModifiers()) { 4668 pageDown(true); 4669 return true; 4670 } 4671 4672 if (keyCode >= KeyEvent.KEYCODE_DPAD_UP 4673 && keyCode <= KeyEvent.KEYCODE_DPAD_RIGHT) { 4674 switchOutDrawHistory(); 4675 if (nativePageShouldHandleShiftAndArrows()) { 4676 letPageHandleNavKey(keyCode, event.getEventTime(), true, event.getMetaState()); 4677 return true; 4678 } 4679 if (event.hasModifiers(KeyEvent.META_ALT_ON)) { 4680 switch (keyCode) { 4681 case KeyEvent.KEYCODE_DPAD_UP: 4682 pageUp(true); 4683 return true; 4684 case KeyEvent.KEYCODE_DPAD_DOWN: 4685 pageDown(true); 4686 return true; 4687 case KeyEvent.KEYCODE_DPAD_LEFT: 4688 nativeClearCursor(); // start next trackball movement from page edge 4689 return pinScrollTo(0, mScrollY, true, 0); 4690 case KeyEvent.KEYCODE_DPAD_RIGHT: 4691 nativeClearCursor(); // start next trackball movement from page edge 4692 return pinScrollTo(mContentWidth, mScrollY, true, 0); 4693 } 4694 } 4695 if (mSelectingText) { 4696 int xRate = keyCode == KeyEvent.KEYCODE_DPAD_LEFT 4697 ? -1 : keyCode == KeyEvent.KEYCODE_DPAD_RIGHT ? 1 : 0; 4698 int yRate = keyCode == KeyEvent.KEYCODE_DPAD_UP ? 4699 -1 : keyCode == KeyEvent.KEYCODE_DPAD_DOWN ? 1 : 0; 4700 int multiplier = event.getRepeatCount() + 1; 4701 moveSelection(xRate * multiplier, yRate * multiplier); 4702 return true; 4703 } 4704 if (navHandledKey(keyCode, 1, false, event.getEventTime())) { 4705 playSoundEffect(keyCodeToSoundsEffect(keyCode)); 4706 return true; 4707 } 4708 // Bubble up the key event as WebView doesn't handle it 4709 return false; 4710 } 4711 4712 if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER) { 4713 switchOutDrawHistory(); 4714 boolean wantsKeyEvents = nativeCursorNodePointer() == 0 4715 || nativeCursorWantsKeyEvents(); 4716 if (event.getRepeatCount() == 0) { 4717 if (mSelectingText) { 4718 return true; // discard press if copy in progress 4719 } 4720 mGotCenterDown = true; 4721 mPrivateHandler.sendMessageDelayed(mPrivateHandler 4722 .obtainMessage(LONG_PRESS_CENTER), LONG_PRESS_TIMEOUT); 4723 // Already checked mNativeClass, so we do not need to check it 4724 // again. 4725 nativeRecordButtons(hasFocus() && hasWindowFocus(), true, true); 4726 if (!wantsKeyEvents) return true; 4727 } 4728 // Bubble up the key event as WebView doesn't handle it 4729 if (!wantsKeyEvents) return false; 4730 } 4731 4732 if (getSettings().getNavDump()) { 4733 switch (keyCode) { 4734 case KeyEvent.KEYCODE_4: 4735 dumpDisplayTree(); 4736 break; 4737 case KeyEvent.KEYCODE_5: 4738 case KeyEvent.KEYCODE_6: 4739 dumpDomTree(keyCode == KeyEvent.KEYCODE_5); 4740 break; 4741 case KeyEvent.KEYCODE_7: 4742 case KeyEvent.KEYCODE_8: 4743 dumpRenderTree(keyCode == KeyEvent.KEYCODE_7); 4744 break; 4745 case KeyEvent.KEYCODE_9: 4746 nativeInstrumentReport(); 4747 return true; 4748 } 4749 } 4750 4751 if (nativeCursorIsTextInput()) { 4752 // This message will put the node in focus, for the DOM's notion 4753 // of focus. 4754 mWebViewCore.sendMessage(EventHub.FAKE_CLICK, nativeCursorFramePointer(), 4755 nativeCursorNodePointer()); 4756 // This will bring up the WebTextView and put it in focus, for 4757 // our view system's notion of focus 4758 rebuildWebTextView(); 4759 // Now we need to pass the event to it 4760 if (inEditingMode()) { 4761 mWebTextView.setDefaultSelection(); 4762 return mWebTextView.dispatchKeyEvent(event); 4763 } 4764 } else if (nativeHasFocusNode()) { 4765 // In this case, the cursor is not on a text input, but the focus 4766 // might be. Check it, and if so, hand over to the WebTextView. 4767 rebuildWebTextView(); 4768 if (inEditingMode()) { 4769 mWebTextView.setDefaultSelection(); 4770 return mWebTextView.dispatchKeyEvent(event); 4771 } 4772 } 4773 4774 // TODO: should we pass all the keys to DOM or check the meta tag 4775 if (nativeCursorWantsKeyEvents() || true) { 4776 // pass the key to DOM 4777 mWebViewCore.sendMessage(EventHub.KEY_DOWN, event); 4778 // return true as DOM handles the key 4779 return true; 4780 } 4781 4782 // Bubble up the key event as WebView doesn't handle it 4783 return false; 4784 } 4785 4786 @Override 4787 public boolean onKeyUp(int keyCode, KeyEvent event) { 4788 if (DebugFlags.WEB_VIEW) { 4789 Log.v(LOGTAG, "keyUp at " + System.currentTimeMillis() 4790 + ", " + event + ", unicode=" + event.getUnicodeChar()); 4791 } 4792 4793 if (mNativeClass == 0) { 4794 return false; 4795 } 4796 4797 // special CALL handling when cursor node's href is "tel:XXX" 4798 if (keyCode == KeyEvent.KEYCODE_CALL && nativeHasCursorNode()) { 4799 String text = nativeCursorText(); 4800 if (!nativeCursorIsTextInput() && text != null 4801 && text.startsWith(SCHEME_TEL)) { 4802 Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse(text)); 4803 getContext().startActivity(intent); 4804 return true; 4805 } 4806 } 4807 4808 // Bubble up the key event if 4809 // 1. it is a system key; or 4810 // 2. the host application wants to handle it; 4811 if (event.isSystem() 4812 || mCallbackProxy.uiOverrideKeyEvent(event)) { 4813 return false; 4814 } 4815 4816 // accessibility support 4817 if (accessibilityScriptInjected()) { 4818 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 4819 // if an accessibility script is injected we delegate to it the key handling. 4820 // this script is a screen reader which is a fully fledged solution for blind 4821 // users to navigate in and interact with web pages. 4822 mWebViewCore.sendMessage(EventHub.KEY_UP, event); 4823 return true; 4824 } else { 4825 // Clean up if accessibility was disabled after loading the current URL. 4826 mAccessibilityScriptInjected = false; 4827 } 4828 } else if (mAccessibilityInjector != null) { 4829 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 4830 if (mAccessibilityInjector.onKeyEvent(event)) { 4831 // if an accessibility injector is present (no JavaScript enabled or the site 4832 // opts out injecting our JavaScript screen reader) we let it decide whether to 4833 // act on and consume the event. 4834 return true; 4835 } 4836 } else { 4837 // Clean up if accessibility was disabled after loading the current URL. 4838 mAccessibilityInjector = null; 4839 } 4840 } 4841 4842 if (keyCode >= KeyEvent.KEYCODE_DPAD_UP 4843 && keyCode <= KeyEvent.KEYCODE_DPAD_RIGHT) { 4844 if (nativePageShouldHandleShiftAndArrows()) { 4845 letPageHandleNavKey(keyCode, event.getEventTime(), false, event.getMetaState()); 4846 return true; 4847 } 4848 // always handle the navigation keys in the UI thread 4849 // Bubble up the key event as WebView doesn't handle it 4850 return false; 4851 } 4852 4853 if (isEnterActionKey(keyCode)) { 4854 // remove the long press message first 4855 mPrivateHandler.removeMessages(LONG_PRESS_CENTER); 4856 mGotCenterDown = false; 4857 4858 if (mSelectingText) { 4859 if (mExtendSelection) { 4860 copySelection(); 4861 selectionDone(); 4862 } else { 4863 mExtendSelection = true; 4864 nativeSetExtendSelection(); 4865 invalidate(); // draw the i-beam instead of the arrow 4866 } 4867 return true; // discard press if copy in progress 4868 } 4869 4870 // perform the single click 4871 Rect visibleRect = sendOurVisibleRect(); 4872 // Note that sendOurVisibleRect calls viewToContent, so the 4873 // coordinates should be in content coordinates. 4874 if (!nativeCursorIntersects(visibleRect)) { 4875 return false; 4876 } 4877 WebViewCore.CursorData data = cursorData(); 4878 mWebViewCore.sendMessage(EventHub.SET_MOVE_MOUSE, data); 4879 playSoundEffect(SoundEffectConstants.CLICK); 4880 if (nativeCursorIsTextInput()) { 4881 rebuildWebTextView(); 4882 centerKeyPressOnTextField(); 4883 if (inEditingMode()) { 4884 mWebTextView.setDefaultSelection(); 4885 } 4886 return true; 4887 } 4888 clearTextEntry(); 4889 nativeShowCursorTimed(); 4890 if (mCallbackProxy.uiOverrideUrlLoading(nativeCursorText())) { 4891 return true; 4892 } 4893 if (nativeCursorNodePointer() != 0 && !nativeCursorWantsKeyEvents()) { 4894 mWebViewCore.sendMessage(EventHub.CLICK, data.mFrame, 4895 nativeCursorNodePointer()); 4896 return true; 4897 } 4898 } 4899 4900 // TODO: should we pass all the keys to DOM or check the meta tag 4901 if (nativeCursorWantsKeyEvents() || true) { 4902 // pass the key to DOM 4903 mWebViewCore.sendMessage(EventHub.KEY_UP, event); 4904 // return true as DOM handles the key 4905 return true; 4906 } 4907 4908 // Bubble up the key event as WebView doesn't handle it 4909 return false; 4910 } 4911 4912 /* 4913 * Enter selecting text mode, and see if CAB should be shown. 4914 * Returns true if the WebView is now in 4915 * selecting text mode (including if it was already in that mode, and this 4916 * method did nothing). 4917 */ 4918 private boolean setUpSelect(boolean selectWord, int x, int y) { 4919 if (0 == mNativeClass) return false; // client isn't initialized 4920 if (inFullScreenMode()) return false; 4921 if (mSelectingText) return true; 4922 nativeResetSelection(); 4923 if (selectWord && !nativeWordSelection(x, y)) { 4924 selectionDone(); 4925 return false; 4926 } 4927 mSelectCallback = new SelectActionModeCallback(); 4928 mSelectCallback.setWebView(this); 4929 if (startActionMode(mSelectCallback) == null) { 4930 // There is no ActionMode, so do not allow the user to modify a 4931 // selection. 4932 selectionDone(); 4933 return false; 4934 } 4935 mExtendSelection = false; 4936 mSelectingText = mDrawSelectionPointer = true; 4937 // don't let the picture change during text selection 4938 WebViewCore.pauseUpdatePicture(mWebViewCore); 4939 if (nativeHasCursorNode()) { 4940 Rect rect = nativeCursorNodeBounds(); 4941 mSelectX = contentToViewX(rect.left); 4942 mSelectY = contentToViewY(rect.top); 4943 } else if (mLastTouchY > getVisibleTitleHeight()) { 4944 mSelectX = mScrollX + mLastTouchX; 4945 mSelectY = mScrollY + mLastTouchY; 4946 } else { 4947 mSelectX = mScrollX + getViewWidth() / 2; 4948 mSelectY = mScrollY + getViewHeightWithTitle() / 2; 4949 } 4950 nativeHideCursor(); 4951 mMinAutoScrollX = 0; 4952 mMaxAutoScrollX = getViewWidth(); 4953 mMinAutoScrollY = 0; 4954 mMaxAutoScrollY = getViewHeightWithTitle(); 4955 mScrollingLayer = nativeScrollableLayer(viewToContentX(mSelectX), 4956 viewToContentY(mSelectY), mScrollingLayerRect, 4957 mScrollingLayerBounds); 4958 if (mScrollingLayer != 0) { 4959 if (mScrollingLayerRect.left != mScrollingLayerRect.right) { 4960 mMinAutoScrollX = Math.max(mMinAutoScrollX, 4961 contentToViewX(mScrollingLayerBounds.left)); 4962 mMaxAutoScrollX = Math.min(mMaxAutoScrollX, 4963 contentToViewX(mScrollingLayerBounds.right)); 4964 } 4965 if (mScrollingLayerRect.top != mScrollingLayerRect.bottom) { 4966 mMinAutoScrollY = Math.max(mMinAutoScrollY, 4967 contentToViewY(mScrollingLayerBounds.top)); 4968 mMaxAutoScrollY = Math.min(mMaxAutoScrollY, 4969 contentToViewY(mScrollingLayerBounds.bottom)); 4970 } 4971 } 4972 mMinAutoScrollX += SELECT_SCROLL; 4973 mMaxAutoScrollX -= SELECT_SCROLL; 4974 mMinAutoScrollY += SELECT_SCROLL; 4975 mMaxAutoScrollY -= SELECT_SCROLL; 4976 return true; 4977 } 4978 4979 /** 4980 * Use this method to put the WebView into text selection mode. 4981 * Do not rely on this functionality; it will be deprecated in the future. 4982 * @deprecated This method is now obsolete. 4983 */ 4984 @Deprecated 4985 public void emulateShiftHeld() { 4986 setUpSelect(false, 0, 0); 4987 } 4988 4989 /** 4990 * Select all of the text in this WebView. 4991 * 4992 * @hide pending API council approval. 4993 */ 4994 public void selectAll() { 4995 if (0 == mNativeClass) return; // client isn't initialized 4996 if (inFullScreenMode()) return; 4997 if (!mSelectingText) { 4998 // retrieve a point somewhere within the text 4999 Point select = nativeSelectableText(); 5000 if (!selectText(select.x, select.y)) return; 5001 } 5002 nativeSelectAll(); 5003 mDrawSelectionPointer = false; 5004 mExtendSelection = true; 5005 invalidate(); 5006 } 5007 5008 /** 5009 * Called when the selection has been removed. 5010 */ 5011 void selectionDone() { 5012 if (mSelectingText) { 5013 mSelectingText = false; 5014 // finish is idempotent, so this is fine even if selectionDone was 5015 // called by mSelectCallback.onDestroyActionMode 5016 mSelectCallback.finish(); 5017 mSelectCallback = null; 5018 WebViewCore.resumePriority(); 5019 WebViewCore.resumeUpdatePicture(mWebViewCore); 5020 invalidate(); // redraw without selection 5021 mAutoScrollX = 0; 5022 mAutoScrollY = 0; 5023 mSentAutoScrollMessage = false; 5024 } 5025 } 5026 5027 /** 5028 * Copy the selection to the clipboard 5029 * 5030 * @hide pending API council approval. 5031 */ 5032 public boolean copySelection() { 5033 boolean copiedSomething = false; 5034 String selection = getSelection(); 5035 if (selection != null && selection != "") { 5036 if (DebugFlags.WEB_VIEW) { 5037 Log.v(LOGTAG, "copySelection \"" + selection + "\""); 5038 } 5039 Toast.makeText(mContext 5040 , com.android.internal.R.string.text_copied 5041 , Toast.LENGTH_SHORT).show(); 5042 copiedSomething = true; 5043 ClipboardManager cm = (ClipboardManager)getContext() 5044 .getSystemService(Context.CLIPBOARD_SERVICE); 5045 cm.setText(selection); 5046 } 5047 invalidate(); // remove selection region and pointer 5048 return copiedSomething; 5049 } 5050 5051 /** 5052 * @hide pending API Council approval. 5053 */ 5054 public SearchBox getSearchBox() { 5055 if ((mWebViewCore == null) || (mWebViewCore.getBrowserFrame() == null)) { 5056 return null; 5057 } 5058 return mWebViewCore.getBrowserFrame().getSearchBox(); 5059 } 5060 5061 /** 5062 * Returns the currently highlighted text as a string. 5063 */ 5064 String getSelection() { 5065 if (mNativeClass == 0) return ""; 5066 return nativeGetSelection(); 5067 } 5068 5069 @Override 5070 protected void onAttachedToWindow() { 5071 super.onAttachedToWindow(); 5072 if (hasWindowFocus()) setActive(true); 5073 final ViewTreeObserver treeObserver = getViewTreeObserver(); 5074 if (mGlobalLayoutListener == null) { 5075 mGlobalLayoutListener = new InnerGlobalLayoutListener(); 5076 treeObserver.addOnGlobalLayoutListener(mGlobalLayoutListener); 5077 } 5078 if (mScrollChangedListener == null) { 5079 mScrollChangedListener = new InnerScrollChangedListener(); 5080 treeObserver.addOnScrollChangedListener(mScrollChangedListener); 5081 } 5082 5083 addAccessibilityApisToJavaScript(); 5084 5085 mTouchEventQueue.reset(); 5086 } 5087 5088 @Override 5089 protected void onDetachedFromWindow() { 5090 clearHelpers(); 5091 mZoomManager.dismissZoomPicker(); 5092 if (hasWindowFocus()) setActive(false); 5093 5094 final ViewTreeObserver treeObserver = getViewTreeObserver(); 5095 if (mGlobalLayoutListener != null) { 5096 treeObserver.removeGlobalOnLayoutListener(mGlobalLayoutListener); 5097 mGlobalLayoutListener = null; 5098 } 5099 if (mScrollChangedListener != null) { 5100 treeObserver.removeOnScrollChangedListener(mScrollChangedListener); 5101 mScrollChangedListener = null; 5102 } 5103 5104 removeAccessibilityApisFromJavaScript(); 5105 5106 super.onDetachedFromWindow(); 5107 } 5108 5109 @Override 5110 protected void onVisibilityChanged(View changedView, int visibility) { 5111 super.onVisibilityChanged(changedView, visibility); 5112 // The zoomManager may be null if the webview is created from XML that 5113 // specifies the view's visibility param as not visible (see http://b/2794841) 5114 if (visibility != View.VISIBLE && mZoomManager != null) { 5115 mZoomManager.dismissZoomPicker(); 5116 } 5117 } 5118 5119 /** 5120 * @deprecated WebView no longer needs to implement 5121 * ViewGroup.OnHierarchyChangeListener. This method does nothing now. 5122 */ 5123 @Deprecated 5124 public void onChildViewAdded(View parent, View child) {} 5125 5126 /** 5127 * @deprecated WebView no longer needs to implement 5128 * ViewGroup.OnHierarchyChangeListener. This method does nothing now. 5129 */ 5130 @Deprecated 5131 public void onChildViewRemoved(View p, View child) {} 5132 5133 /** 5134 * @deprecated WebView should not have implemented 5135 * ViewTreeObserver.OnGlobalFocusChangeListener. This method does nothing now. 5136 */ 5137 @Deprecated 5138 public void onGlobalFocusChanged(View oldFocus, View newFocus) { 5139 } 5140 5141 void setActive(boolean active) { 5142 if (active) { 5143 if (hasFocus()) { 5144 // If our window regained focus, and we have focus, then begin 5145 // drawing the cursor ring 5146 mDrawCursorRing = true; 5147 setFocusControllerActive(true); 5148 if (mNativeClass != 0) { 5149 nativeRecordButtons(true, false, true); 5150 } 5151 } else { 5152 if (!inEditingMode()) { 5153 // If our window gained focus, but we do not have it, do not 5154 // draw the cursor ring. 5155 mDrawCursorRing = false; 5156 setFocusControllerActive(false); 5157 } 5158 // We do not call nativeRecordButtons here because we assume 5159 // that when we lost focus, or window focus, it got called with 5160 // false for the first parameter 5161 } 5162 } else { 5163 if (!mZoomManager.isZoomPickerVisible()) { 5164 /* 5165 * The external zoom controls come in their own window, so our 5166 * window loses focus. Our policy is to not draw the cursor ring 5167 * if our window is not focused, but this is an exception since 5168 * the user can still navigate the web page with the zoom 5169 * controls showing. 5170 */ 5171 mDrawCursorRing = false; 5172 } 5173 mKeysPressed.clear(); 5174 mPrivateHandler.removeMessages(SWITCH_TO_LONGPRESS); 5175 mTouchMode = TOUCH_DONE_MODE; 5176 if (mNativeClass != 0) { 5177 nativeRecordButtons(false, false, true); 5178 } 5179 setFocusControllerActive(false); 5180 } 5181 invalidate(); 5182 } 5183 5184 // To avoid drawing the cursor ring, and remove the TextView when our window 5185 // loses focus. 5186 @Override 5187 public void onWindowFocusChanged(boolean hasWindowFocus) { 5188 setActive(hasWindowFocus); 5189 if (hasWindowFocus) { 5190 JWebCoreJavaBridge.setActiveWebView(this); 5191 } else { 5192 JWebCoreJavaBridge.removeActiveWebView(this); 5193 } 5194 super.onWindowFocusChanged(hasWindowFocus); 5195 } 5196 5197 /* 5198 * Pass a message to WebCore Thread, telling the WebCore::Page's 5199 * FocusController to be "inactive" so that it will 5200 * not draw the blinking cursor. It gets set to "active" to draw the cursor 5201 * in WebViewCore.cpp, when the WebCore thread receives key events/clicks. 5202 */ 5203 /* package */ void setFocusControllerActive(boolean active) { 5204 if (mWebViewCore == null) return; 5205 mWebViewCore.sendMessage(EventHub.SET_ACTIVE, active ? 1 : 0, 0); 5206 // Need to send this message after the document regains focus. 5207 if (active && mListBoxMessage != null) { 5208 mWebViewCore.sendMessage(mListBoxMessage); 5209 mListBoxMessage = null; 5210 } 5211 } 5212 5213 @Override 5214 protected void onFocusChanged(boolean focused, int direction, 5215 Rect previouslyFocusedRect) { 5216 if (DebugFlags.WEB_VIEW) { 5217 Log.v(LOGTAG, "MT focusChanged " + focused + ", " + direction); 5218 } 5219 if (focused) { 5220 // When we regain focus, if we have window focus, resume drawing 5221 // the cursor ring 5222 if (hasWindowFocus()) { 5223 mDrawCursorRing = true; 5224 if (mNativeClass != 0) { 5225 nativeRecordButtons(true, false, true); 5226 } 5227 setFocusControllerActive(true); 5228 //} else { 5229 // The WebView has gained focus while we do not have 5230 // windowfocus. When our window lost focus, we should have 5231 // called nativeRecordButtons(false...) 5232 } 5233 } else { 5234 // When we lost focus, unless focus went to the TextView (which is 5235 // true if we are in editing mode), stop drawing the cursor ring. 5236 if (!inEditingMode()) { 5237 mDrawCursorRing = false; 5238 if (mNativeClass != 0) { 5239 nativeRecordButtons(false, false, true); 5240 } 5241 setFocusControllerActive(false); 5242 } 5243 mKeysPressed.clear(); 5244 } 5245 5246 super.onFocusChanged(focused, direction, previouslyFocusedRect); 5247 } 5248 5249 void setGLRectViewport() { 5250 // Use the getGlobalVisibleRect() to get the intersection among the parents 5251 // visible == false means we're clipped - send a null rect down to indicate that 5252 // we should not draw 5253 boolean visible = getGlobalVisibleRect(mGLRectViewport); 5254 if (visible) { 5255 // Then need to invert the Y axis, just for GL 5256 View rootView = getRootView(); 5257 int rootViewHeight = rootView.getHeight(); 5258 mViewRectViewport.set(mGLRectViewport); 5259 int savedWebViewBottom = mGLRectViewport.bottom; 5260 mGLRectViewport.bottom = rootViewHeight - mGLRectViewport.top - getVisibleTitleHeight(); 5261 mGLRectViewport.top = rootViewHeight - savedWebViewBottom; 5262 mGLViewportEmpty = false; 5263 } else { 5264 mGLViewportEmpty = true; 5265 } 5266 nativeUpdateDrawGLFunction(mGLViewportEmpty ? null : mGLRectViewport, 5267 mGLViewportEmpty ? null : mViewRectViewport); 5268 } 5269 5270 /** 5271 * @hide 5272 */ 5273 @Override 5274 protected boolean setFrame(int left, int top, int right, int bottom) { 5275 boolean changed = super.setFrame(left, top, right, bottom); 5276 if (!changed && mHeightCanMeasure) { 5277 // When mHeightCanMeasure is true, we will set mLastHeightSent to 0 5278 // in WebViewCore after we get the first layout. We do call 5279 // requestLayout() when we get contentSizeChanged(). But the View 5280 // system won't call onSizeChanged if the dimension is not changed. 5281 // In this case, we need to call sendViewSizeZoom() explicitly to 5282 // notify the WebKit about the new dimensions. 5283 sendViewSizeZoom(false); 5284 } 5285 setGLRectViewport(); 5286 return changed; 5287 } 5288 5289 @Override 5290 protected void onSizeChanged(int w, int h, int ow, int oh) { 5291 super.onSizeChanged(w, h, ow, oh); 5292 5293 // adjust the max viewport width depending on the view dimensions. This 5294 // is to ensure the scaling is not going insane. So do not shrink it if 5295 // the view size is temporarily smaller, e.g. when soft keyboard is up. 5296 int newMaxViewportWidth = (int) (Math.max(w, h) / mZoomManager.getDefaultMinZoomScale()); 5297 if (newMaxViewportWidth > sMaxViewportWidth) { 5298 sMaxViewportWidth = newMaxViewportWidth; 5299 } 5300 5301 mZoomManager.onSizeChanged(w, h, ow, oh); 5302 } 5303 5304 @Override 5305 protected void onScrollChanged(int l, int t, int oldl, int oldt) { 5306 super.onScrollChanged(l, t, oldl, oldt); 5307 if (!mInOverScrollMode) { 5308 sendOurVisibleRect(); 5309 // update WebKit if visible title bar height changed. The logic is same 5310 // as getVisibleTitleHeight. 5311 int titleHeight = getTitleHeight(); 5312 if (Math.max(titleHeight - t, 0) != Math.max(titleHeight - oldt, 0)) { 5313 sendViewSizeZoom(false); 5314 } 5315 } 5316 } 5317 5318 @Override 5319 public boolean dispatchKeyEvent(KeyEvent event) { 5320 switch (event.getAction()) { 5321 case KeyEvent.ACTION_DOWN: 5322 mKeysPressed.add(Integer.valueOf(event.getKeyCode())); 5323 break; 5324 case KeyEvent.ACTION_MULTIPLE: 5325 // Always accept the action. 5326 break; 5327 case KeyEvent.ACTION_UP: 5328 int location = mKeysPressed.indexOf(Integer.valueOf(event.getKeyCode())); 5329 if (location == -1) { 5330 // We did not receive the key down for this key, so do not 5331 // handle the key up. 5332 return false; 5333 } else { 5334 // We did receive the key down. Handle the key up, and 5335 // remove it from our pressed keys. 5336 mKeysPressed.remove(location); 5337 } 5338 break; 5339 default: 5340 // Accept the action. This should not happen, unless a new 5341 // action is added to KeyEvent. 5342 break; 5343 } 5344 if (inEditingMode() && mWebTextView.isFocused()) { 5345 // Ensure that the WebTextView gets the event, even if it does 5346 // not currently have a bounds. 5347 return mWebTextView.dispatchKeyEvent(event); 5348 } else { 5349 return super.dispatchKeyEvent(event); 5350 } 5351 } 5352 5353 // Here are the snap align logic: 5354 // 1. If it starts nearly horizontally or vertically, snap align; 5355 // 2. If there is a dramitic direction change, let it go; 5356 // 3. If there is a same direction back and forth, lock it. 5357 5358 // adjustable parameters 5359 private int mMinLockSnapReverseDistance; 5360 private static final float MAX_SLOPE_FOR_DIAG = 1.5f; 5361 private static final int MIN_BREAK_SNAP_CROSS_DISTANCE = 80; 5362 5363 private boolean hitFocusedPlugin(int contentX, int contentY) { 5364 if (DebugFlags.WEB_VIEW) { 5365 Log.v(LOGTAG, "nativeFocusIsPlugin()=" + nativeFocusIsPlugin()); 5366 Rect r = nativeFocusNodeBounds(); 5367 Log.v(LOGTAG, "nativeFocusNodeBounds()=(" + r.left + ", " + r.top 5368 + ", " + r.right + ", " + r.bottom + ")"); 5369 } 5370 return nativeFocusIsPlugin() 5371 && nativeFocusNodeBounds().contains(contentX, contentY); 5372 } 5373 5374 private boolean shouldForwardTouchEvent() { 5375 return mFullScreenHolder != null || (mForwardTouchEvents 5376 && !mSelectingText 5377 && mPreventDefault != PREVENT_DEFAULT_IGNORE); 5378 } 5379 5380 private boolean inFullScreenMode() { 5381 return mFullScreenHolder != null; 5382 } 5383 5384 private void dismissFullScreenMode() { 5385 if (inFullScreenMode()) { 5386 mFullScreenHolder.dismiss(); 5387 mFullScreenHolder = null; 5388 } 5389 } 5390 5391 void onPinchToZoomAnimationStart() { 5392 // cancel the single touch handling 5393 cancelTouch(); 5394 onZoomAnimationStart(); 5395 } 5396 5397 void onPinchToZoomAnimationEnd(ScaleGestureDetector detector) { 5398 onZoomAnimationEnd(); 5399 // start a drag, TOUCH_PINCH_DRAG, can't use TOUCH_INIT_MODE as 5400 // it may trigger the unwanted click, can't use TOUCH_DRAG_MODE 5401 // as it may trigger the unwanted fling. 5402 mTouchMode = TOUCH_PINCH_DRAG; 5403 mConfirmMove = true; 5404 startTouch(detector.getFocusX(), detector.getFocusY(), mLastTouchTime); 5405 } 5406 5407 // See if there is a layer at x, y and switch to TOUCH_DRAG_LAYER_MODE if a 5408 // layer is found. 5409 private void startScrollingLayer(float x, float y) { 5410 int contentX = viewToContentX((int) x + mScrollX); 5411 int contentY = viewToContentY((int) y + mScrollY); 5412 mScrollingLayer = nativeScrollableLayer(contentX, contentY, 5413 mScrollingLayerRect, mScrollingLayerBounds); 5414 if (mScrollingLayer != 0) { 5415 mTouchMode = TOUCH_DRAG_LAYER_MODE; 5416 } 5417 } 5418 5419 // 1/(density * density) used to compute the distance between points. 5420 // Computed in init(). 5421 private float DRAG_LAYER_INVERSE_DENSITY_SQUARED; 5422 5423 // The distance between two points reported in onTouchEvent scaled by the 5424 // density of the screen. 5425 private static final int DRAG_LAYER_FINGER_DISTANCE = 20000; 5426 5427 @Override 5428 public boolean onTouchEvent(MotionEvent ev) { 5429 if (mNativeClass == 0 || (!isClickable() && !isLongClickable())) { 5430 return false; 5431 } 5432 5433 if (DebugFlags.WEB_VIEW) { 5434 Log.v(LOGTAG, ev + " at " + ev.getEventTime() 5435 + " mTouchMode=" + mTouchMode 5436 + " numPointers=" + ev.getPointerCount()); 5437 } 5438 5439 // If WebKit wasn't interested in this multitouch gesture, enqueue 5440 // the event for handling directly rather than making the round trip 5441 // to WebKit and back. 5442 if (ev.getPointerCount() > 1 && mPreventDefault != PREVENT_DEFAULT_NO) { 5443 passMultiTouchToWebKit(ev, mTouchEventQueue.nextTouchSequence()); 5444 } else { 5445 mTouchEventQueue.enqueueTouchEvent(ev); 5446 } 5447 5448 // Since all events are handled asynchronously, we always want the gesture stream. 5449 return true; 5450 } 5451 5452 /* 5453 * Common code for single touch and multi-touch. 5454 * (x, y) denotes current focus point, which is the touch point for single touch 5455 * and the middle point for multi-touch. 5456 */ 5457 private boolean handleTouchEventCommon(MotionEvent ev, int action, int x, int y) { 5458 long eventTime = ev.getEventTime(); 5459 5460 5461 // Due to the touch screen edge effect, a touch closer to the edge 5462 // always snapped to the edge. As getViewWidth() can be different from 5463 // getWidth() due to the scrollbar, adjusting the point to match 5464 // getViewWidth(). Same applied to the height. 5465 x = Math.min(x, getViewWidth() - 1); 5466 y = Math.min(y, getViewHeightWithTitle() - 1); 5467 5468 int deltaX = mLastTouchX - x; 5469 int deltaY = mLastTouchY - y; 5470 int contentX = viewToContentX(x + mScrollX); 5471 int contentY = viewToContentY(y + mScrollY); 5472 5473 switch (action) { 5474 case MotionEvent.ACTION_DOWN: { 5475 mPreventDefault = PREVENT_DEFAULT_NO; 5476 mConfirmMove = false; 5477 mIsHandlingMultiTouch = false; 5478 mInitialHitTestResult = null; 5479 if (!mScroller.isFinished()) { 5480 // stop the current scroll animation, but if this is 5481 // the start of a fling, allow it to add to the current 5482 // fling's velocity 5483 mScroller.abortAnimation(); 5484 mTouchMode = TOUCH_DRAG_START_MODE; 5485 mConfirmMove = true; 5486 mPrivateHandler.removeMessages(RESUME_WEBCORE_PRIORITY); 5487 } else if (mPrivateHandler.hasMessages(RELEASE_SINGLE_TAP)) { 5488 mPrivateHandler.removeMessages(RELEASE_SINGLE_TAP); 5489 if (getSettings().supportTouchOnly()) { 5490 removeTouchHighlight(true); 5491 } 5492 if (deltaX * deltaX + deltaY * deltaY < mDoubleTapSlopSquare) { 5493 mTouchMode = TOUCH_DOUBLE_TAP_MODE; 5494 } else { 5495 // commit the short press action for the previous tap 5496 doShortPress(); 5497 mTouchMode = TOUCH_INIT_MODE; 5498 mDeferTouchProcess = (!inFullScreenMode() 5499 && mForwardTouchEvents) ? hitFocusedPlugin( 5500 contentX, contentY) : false; 5501 } 5502 } else { // the normal case 5503 mTouchMode = TOUCH_INIT_MODE; 5504 mDeferTouchProcess = (!inFullScreenMode() 5505 && mForwardTouchEvents) ? hitFocusedPlugin( 5506 contentX, contentY) : false; 5507 mWebViewCore.sendMessage( 5508 EventHub.UPDATE_FRAME_CACHE_IF_LOADING); 5509 if (getSettings().supportTouchOnly()) { 5510 TouchHighlightData data = new TouchHighlightData(); 5511 data.mX = contentX; 5512 data.mY = contentY; 5513 data.mSlop = viewToContentDimension(mNavSlop); 5514 mWebViewCore.sendMessageDelayed( 5515 EventHub.GET_TOUCH_HIGHLIGHT_RECTS, data, 5516 ViewConfiguration.getTapTimeout()); 5517 if (DEBUG_TOUCH_HIGHLIGHT) { 5518 if (getSettings().getNavDump()) { 5519 mTouchHighlightX = (int) x + mScrollX; 5520 mTouchHighlightY = (int) y + mScrollY; 5521 mPrivateHandler.postDelayed(new Runnable() { 5522 public void run() { 5523 mTouchHighlightX = mTouchHighlightY = 0; 5524 invalidate(); 5525 } 5526 }, TOUCH_HIGHLIGHT_ELAPSE_TIME); 5527 } 5528 } 5529 } 5530 if (mLogEvent && eventTime - mLastTouchUpTime < 1000) { 5531 EventLog.writeEvent(EventLogTags.BROWSER_DOUBLE_TAP_DURATION, 5532 (eventTime - mLastTouchUpTime), eventTime); 5533 } 5534 if (mSelectingText) { 5535 mDrawSelectionPointer = false; 5536 mSelectionStarted = nativeStartSelection(contentX, contentY); 5537 if (DebugFlags.WEB_VIEW) { 5538 Log.v(LOGTAG, "select=" + contentX + "," + contentY); 5539 } 5540 invalidate(); 5541 } 5542 } 5543 // Trigger the link 5544 if (!mSelectingText && (mTouchMode == TOUCH_INIT_MODE 5545 || mTouchMode == TOUCH_DOUBLE_TAP_MODE)) { 5546 mPrivateHandler.sendEmptyMessageDelayed( 5547 SWITCH_TO_SHORTPRESS, TAP_TIMEOUT); 5548 mPrivateHandler.sendEmptyMessageDelayed( 5549 SWITCH_TO_LONGPRESS, LONG_PRESS_TIMEOUT); 5550 if (inFullScreenMode() || mDeferTouchProcess) { 5551 mPreventDefault = PREVENT_DEFAULT_YES; 5552 } else if (mForwardTouchEvents) { 5553 mPreventDefault = PREVENT_DEFAULT_MAYBE_YES; 5554 } else { 5555 mPreventDefault = PREVENT_DEFAULT_NO; 5556 } 5557 // pass the touch events from UI thread to WebCore thread 5558 if (shouldForwardTouchEvent()) { 5559 TouchEventData ted = new TouchEventData(); 5560 ted.mAction = action; 5561 ted.mIds = new int[1]; 5562 ted.mIds[0] = ev.getPointerId(0); 5563 ted.mPoints = new Point[1]; 5564 ted.mPoints[0] = new Point(contentX, contentY); 5565 ted.mMetaState = ev.getMetaState(); 5566 ted.mReprocess = mDeferTouchProcess; 5567 ted.mNativeLayer = nativeScrollableLayer( 5568 contentX, contentY, ted.mNativeLayerRect, null); 5569 ted.mSequence = mTouchEventQueue.nextTouchSequence(); 5570 mWebViewCore.sendMessage(EventHub.TOUCH_EVENT, ted); 5571 if (mDeferTouchProcess) { 5572 // still needs to set them for compute deltaX/Y 5573 mLastTouchX = x; 5574 mLastTouchY = y; 5575 break; 5576 } 5577 if (!inFullScreenMode()) { 5578 mPrivateHandler.removeMessages(PREVENT_DEFAULT_TIMEOUT); 5579 mPrivateHandler.sendMessageDelayed(mPrivateHandler 5580 .obtainMessage(PREVENT_DEFAULT_TIMEOUT, 5581 action, 0), TAP_TIMEOUT); 5582 } 5583 } 5584 } 5585 startTouch(x, y, eventTime); 5586 break; 5587 } 5588 case MotionEvent.ACTION_MOVE: { 5589 boolean firstMove = false; 5590 if (!mConfirmMove && (deltaX * deltaX + deltaY * deltaY) 5591 >= mTouchSlopSquare) { 5592 mPrivateHandler.removeMessages(SWITCH_TO_SHORTPRESS); 5593 mPrivateHandler.removeMessages(SWITCH_TO_LONGPRESS); 5594 mConfirmMove = true; 5595 firstMove = true; 5596 if (mTouchMode == TOUCH_DOUBLE_TAP_MODE) { 5597 mTouchMode = TOUCH_INIT_MODE; 5598 } 5599 if (getSettings().supportTouchOnly()) { 5600 removeTouchHighlight(true); 5601 } 5602 } 5603 // pass the touch events from UI thread to WebCore thread 5604 if (shouldForwardTouchEvent() && mConfirmMove && (firstMove 5605 || eventTime - mLastSentTouchTime > mCurrentTouchInterval)) { 5606 TouchEventData ted = new TouchEventData(); 5607 ted.mAction = action; 5608 ted.mIds = new int[1]; 5609 ted.mIds[0] = ev.getPointerId(0); 5610 ted.mPoints = new Point[1]; 5611 ted.mPoints[0] = new Point(contentX, contentY); 5612 ted.mMetaState = ev.getMetaState(); 5613 ted.mReprocess = mDeferTouchProcess; 5614 ted.mNativeLayer = mScrollingLayer; 5615 ted.mNativeLayerRect.set(mScrollingLayerRect); 5616 ted.mSequence = mTouchEventQueue.nextTouchSequence(); 5617 mWebViewCore.sendMessage(EventHub.TOUCH_EVENT, ted); 5618 mLastSentTouchTime = eventTime; 5619 if (mDeferTouchProcess) { 5620 break; 5621 } 5622 if (firstMove && !inFullScreenMode()) { 5623 mPrivateHandler.sendMessageDelayed(mPrivateHandler 5624 .obtainMessage(PREVENT_DEFAULT_TIMEOUT, 5625 action, 0), TAP_TIMEOUT); 5626 } 5627 } 5628 if (mTouchMode == TOUCH_DONE_MODE 5629 || mPreventDefault == PREVENT_DEFAULT_YES) { 5630 // no dragging during scroll zoom animation, or when prevent 5631 // default is yes 5632 break; 5633 } 5634 if (mVelocityTracker == null) { 5635 Log.e(LOGTAG, "Got null mVelocityTracker when " 5636 + "mPreventDefault = " + mPreventDefault 5637 + " mDeferTouchProcess = " + mDeferTouchProcess 5638 + " mTouchMode = " + mTouchMode); 5639 } else { 5640 mVelocityTracker.addMovement(ev); 5641 } 5642 if (mSelectingText && mSelectionStarted) { 5643 if (DebugFlags.WEB_VIEW) { 5644 Log.v(LOGTAG, "extend=" + contentX + "," + contentY); 5645 } 5646 ViewParent parent = getParent(); 5647 if (parent != null) { 5648 parent.requestDisallowInterceptTouchEvent(true); 5649 } 5650 mAutoScrollX = x <= mMinAutoScrollX ? -SELECT_SCROLL 5651 : x >= mMaxAutoScrollX ? SELECT_SCROLL : 0; 5652 mAutoScrollY = y <= mMinAutoScrollY ? -SELECT_SCROLL 5653 : y >= mMaxAutoScrollY ? SELECT_SCROLL : 0; 5654 if ((mAutoScrollX != 0 || mAutoScrollY != 0) 5655 && !mSentAutoScrollMessage) { 5656 mSentAutoScrollMessage = true; 5657 mPrivateHandler.sendEmptyMessageDelayed( 5658 SCROLL_SELECT_TEXT, SELECT_SCROLL_INTERVAL); 5659 } 5660 if (deltaX != 0 || deltaY != 0) { 5661 nativeExtendSelection(contentX, contentY); 5662 invalidate(); 5663 } 5664 break; 5665 } 5666 5667 if (mTouchMode != TOUCH_DRAG_MODE && 5668 mTouchMode != TOUCH_DRAG_LAYER_MODE) { 5669 5670 if (!mConfirmMove) { 5671 break; 5672 } 5673 5674 if (mPreventDefault == PREVENT_DEFAULT_MAYBE_YES 5675 || mPreventDefault == PREVENT_DEFAULT_NO_FROM_TOUCH_DOWN) { 5676 // track mLastTouchTime as we may need to do fling at 5677 // ACTION_UP 5678 mLastTouchTime = eventTime; 5679 break; 5680 } 5681 5682 // Only lock dragging to one axis if we don't have a scale in progress. 5683 // Scaling implies free-roaming movement. Note this is only ever a question 5684 // if mZoomManager.supportsPanDuringZoom() is true. 5685 final ScaleGestureDetector detector = 5686 mZoomManager.getMultiTouchGestureDetector(); 5687 if (detector == null || !detector.isInProgress()) { 5688 // if it starts nearly horizontal or vertical, enforce it 5689 int ax = Math.abs(deltaX); 5690 int ay = Math.abs(deltaY); 5691 if (ax > MAX_SLOPE_FOR_DIAG * ay) { 5692 mSnapScrollMode = SNAP_X; 5693 mSnapPositive = deltaX > 0; 5694 } else if (ay > MAX_SLOPE_FOR_DIAG * ax) { 5695 mSnapScrollMode = SNAP_Y; 5696 mSnapPositive = deltaY > 0; 5697 } 5698 } 5699 5700 mTouchMode = TOUCH_DRAG_MODE; 5701 mLastTouchX = x; 5702 mLastTouchY = y; 5703 deltaX = 0; 5704 deltaY = 0; 5705 5706 startScrollingLayer(x, y); 5707 startDrag(); 5708 } 5709 5710 // do pan 5711 boolean done = false; 5712 boolean keepScrollBarsVisible = false; 5713 if (deltaX == 0 && deltaY == 0) { 5714 keepScrollBarsVisible = done = true; 5715 } else { 5716 if (mSnapScrollMode == SNAP_X || mSnapScrollMode == SNAP_Y) { 5717 int ax = Math.abs(deltaX); 5718 int ay = Math.abs(deltaY); 5719 if (mSnapScrollMode == SNAP_X) { 5720 // radical change means getting out of snap mode 5721 if (ay > MAX_SLOPE_FOR_DIAG * ax 5722 && ay > MIN_BREAK_SNAP_CROSS_DISTANCE) { 5723 mSnapScrollMode = SNAP_NONE; 5724 } 5725 // reverse direction means lock in the snap mode 5726 if (ax > MAX_SLOPE_FOR_DIAG * ay && 5727 (mSnapPositive 5728 ? deltaX < -mMinLockSnapReverseDistance 5729 : deltaX > mMinLockSnapReverseDistance)) { 5730 mSnapScrollMode |= SNAP_LOCK; 5731 } 5732 } else { 5733 // radical change means getting out of snap mode 5734 if (ax > MAX_SLOPE_FOR_DIAG * ay 5735 && ax > MIN_BREAK_SNAP_CROSS_DISTANCE) { 5736 mSnapScrollMode = SNAP_NONE; 5737 } 5738 // reverse direction means lock in the snap mode 5739 if (ay > MAX_SLOPE_FOR_DIAG * ax && 5740 (mSnapPositive 5741 ? deltaY < -mMinLockSnapReverseDistance 5742 : deltaY > mMinLockSnapReverseDistance)) { 5743 mSnapScrollMode |= SNAP_LOCK; 5744 } 5745 } 5746 } 5747 if (mSnapScrollMode != SNAP_NONE) { 5748 if ((mSnapScrollMode & SNAP_X) == SNAP_X) { 5749 deltaY = 0; 5750 } else { 5751 deltaX = 0; 5752 } 5753 } 5754 if ((deltaX | deltaY) != 0) { 5755 if (deltaX != 0) { 5756 mLastTouchX = x; 5757 } 5758 if (deltaY != 0) { 5759 mLastTouchY = y; 5760 } 5761 mHeldMotionless = MOTIONLESS_FALSE; 5762 } 5763 mLastTouchTime = eventTime; 5764 } 5765 5766 doDrag(deltaX, deltaY); 5767 5768 // Turn off scrollbars when dragging a layer. 5769 if (keepScrollBarsVisible && 5770 mTouchMode != TOUCH_DRAG_LAYER_MODE) { 5771 if (mHeldMotionless != MOTIONLESS_TRUE) { 5772 mHeldMotionless = MOTIONLESS_TRUE; 5773 invalidate(); 5774 } 5775 // keep the scrollbar on the screen even there is no scroll 5776 awakenScrollBars(ViewConfiguration.getScrollDefaultDelay(), 5777 false); 5778 // return false to indicate that we can't pan out of the 5779 // view space 5780 return !done; 5781 } 5782 break; 5783 } 5784 case MotionEvent.ACTION_UP: { 5785 if (!isFocused()) requestFocus(); 5786 // pass the touch events from UI thread to WebCore thread 5787 if (shouldForwardTouchEvent()) { 5788 TouchEventData ted = new TouchEventData(); 5789 ted.mIds = new int[1]; 5790 ted.mIds[0] = ev.getPointerId(0); 5791 ted.mAction = action; 5792 ted.mPoints = new Point[1]; 5793 ted.mPoints[0] = new Point(contentX, contentY); 5794 ted.mMetaState = ev.getMetaState(); 5795 ted.mReprocess = mDeferTouchProcess; 5796 ted.mNativeLayer = mScrollingLayer; 5797 ted.mNativeLayerRect.set(mScrollingLayerRect); 5798 ted.mSequence = mTouchEventQueue.nextTouchSequence(); 5799 mWebViewCore.sendMessage(EventHub.TOUCH_EVENT, ted); 5800 } 5801 mLastTouchUpTime = eventTime; 5802 if (mSentAutoScrollMessage) { 5803 mAutoScrollX = mAutoScrollY = 0; 5804 } 5805 switch (mTouchMode) { 5806 case TOUCH_DOUBLE_TAP_MODE: // double tap 5807 mPrivateHandler.removeMessages(SWITCH_TO_SHORTPRESS); 5808 mPrivateHandler.removeMessages(SWITCH_TO_LONGPRESS); 5809 if (inFullScreenMode() || mDeferTouchProcess) { 5810 TouchEventData ted = new TouchEventData(); 5811 ted.mIds = new int[1]; 5812 ted.mIds[0] = ev.getPointerId(0); 5813 ted.mAction = WebViewCore.ACTION_DOUBLETAP; 5814 ted.mPoints = new Point[1]; 5815 ted.mPoints[0] = new Point(contentX, contentY); 5816 ted.mMetaState = ev.getMetaState(); 5817 ted.mReprocess = mDeferTouchProcess; 5818 ted.mNativeLayer = nativeScrollableLayer( 5819 contentX, contentY, 5820 ted.mNativeLayerRect, null); 5821 ted.mSequence = mTouchEventQueue.nextTouchSequence(); 5822 mWebViewCore.sendMessage(EventHub.TOUCH_EVENT, ted); 5823 } else if (mPreventDefault != PREVENT_DEFAULT_YES){ 5824 mZoomManager.handleDoubleTap(mLastTouchX, mLastTouchY); 5825 mTouchMode = TOUCH_DONE_MODE; 5826 } 5827 break; 5828 case TOUCH_INIT_MODE: // tap 5829 case TOUCH_SHORTPRESS_START_MODE: 5830 case TOUCH_SHORTPRESS_MODE: 5831 mPrivateHandler.removeMessages(SWITCH_TO_SHORTPRESS); 5832 mPrivateHandler.removeMessages(SWITCH_TO_LONGPRESS); 5833 if (mConfirmMove) { 5834 Log.w(LOGTAG, "Miss a drag as we are waiting for" + 5835 " WebCore's response for touch down."); 5836 if (mPreventDefault != PREVENT_DEFAULT_YES 5837 && (computeMaxScrollX() > 0 5838 || computeMaxScrollY() > 0)) { 5839 // If the user has performed a very quick touch 5840 // sequence it is possible that we may get here 5841 // before WebCore has had a chance to process the events. 5842 // In this case, any call to preventDefault in the 5843 // JS touch handler will not have been executed yet. 5844 // Hence we will see both the UI (now) and WebCore 5845 // (when context switches) handling the event, 5846 // regardless of whether the web developer actually 5847 // doeses preventDefault in their touch handler. This 5848 // is the nature of our asynchronous touch model. 5849 5850 // we will not rewrite drag code here, but we 5851 // will try fling if it applies. 5852 WebViewCore.reducePriority(); 5853 // to get better performance, pause updating the 5854 // picture 5855 WebViewCore.pauseUpdatePicture(mWebViewCore); 5856 // fall through to TOUCH_DRAG_MODE 5857 } else { 5858 // WebKit may consume the touch event and modify 5859 // DOM. drawContentPicture() will be called with 5860 // animateSroll as true for better performance. 5861 // Force redraw in high-quality. 5862 invalidate(); 5863 break; 5864 } 5865 } else { 5866 if (mSelectingText) { 5867 // tapping on selection or controls does nothing 5868 if (!nativeHitSelection(contentX, contentY)) { 5869 selectionDone(); 5870 } 5871 break; 5872 } 5873 // only trigger double tap if the WebView is 5874 // scalable 5875 if (mTouchMode == TOUCH_INIT_MODE 5876 && (canZoomIn() || canZoomOut())) { 5877 mPrivateHandler.sendEmptyMessageDelayed( 5878 RELEASE_SINGLE_TAP, ViewConfiguration 5879 .getDoubleTapTimeout()); 5880 } else { 5881 doShortPress(); 5882 } 5883 break; 5884 } 5885 case TOUCH_DRAG_MODE: 5886 case TOUCH_DRAG_LAYER_MODE: 5887 mPrivateHandler.removeMessages(DRAG_HELD_MOTIONLESS); 5888 mPrivateHandler.removeMessages(AWAKEN_SCROLL_BARS); 5889 // if the user waits a while w/o moving before the 5890 // up, we don't want to do a fling 5891 if (eventTime - mLastTouchTime <= MIN_FLING_TIME) { 5892 if (mVelocityTracker == null) { 5893 Log.e(LOGTAG, "Got null mVelocityTracker when " 5894 + "mPreventDefault = " 5895 + mPreventDefault 5896 + " mDeferTouchProcess = " 5897 + mDeferTouchProcess); 5898 } else { 5899 mVelocityTracker.addMovement(ev); 5900 } 5901 // set to MOTIONLESS_IGNORE so that it won't keep 5902 // removing and sending message in 5903 // drawCoreAndCursorRing() 5904 mHeldMotionless = MOTIONLESS_IGNORE; 5905 doFling(); 5906 break; 5907 } else { 5908 if (mScroller.springBack(mScrollX, mScrollY, 0, 5909 computeMaxScrollX(), 0, 5910 computeMaxScrollY())) { 5911 invalidate(); 5912 } 5913 } 5914 // redraw in high-quality, as we're done dragging 5915 mHeldMotionless = MOTIONLESS_TRUE; 5916 invalidate(); 5917 // fall through 5918 case TOUCH_DRAG_START_MODE: 5919 // TOUCH_DRAG_START_MODE should not happen for the real 5920 // device as we almost certain will get a MOVE. But this 5921 // is possible on emulator. 5922 mLastVelocity = 0; 5923 WebViewCore.resumePriority(); 5924 if (!mSelectingText) { 5925 WebViewCore.resumeUpdatePicture(mWebViewCore); 5926 } 5927 break; 5928 } 5929 stopTouch(); 5930 break; 5931 } 5932 case MotionEvent.ACTION_CANCEL: { 5933 if (mTouchMode == TOUCH_DRAG_MODE) { 5934 mScroller.springBack(mScrollX, mScrollY, 0, 5935 computeMaxScrollX(), 0, computeMaxScrollY()); 5936 invalidate(); 5937 } 5938 cancelWebCoreTouchEvent(contentX, contentY, false); 5939 cancelTouch(); 5940 break; 5941 } 5942 } 5943 return true; 5944 } 5945 5946 private void passMultiTouchToWebKit(MotionEvent ev, long sequence) { 5947 TouchEventData ted = new TouchEventData(); 5948 ted.mAction = ev.getActionMasked(); 5949 final int count = ev.getPointerCount(); 5950 ted.mIds = new int[count]; 5951 ted.mPoints = new Point[count]; 5952 for (int c = 0; c < count; c++) { 5953 ted.mIds[c] = ev.getPointerId(c); 5954 int x = viewToContentX((int) ev.getX(c) + mScrollX); 5955 int y = viewToContentY((int) ev.getY(c) + mScrollY); 5956 ted.mPoints[c] = new Point(x, y); 5957 } 5958 if (ted.mAction == MotionEvent.ACTION_POINTER_DOWN 5959 || ted.mAction == MotionEvent.ACTION_POINTER_UP) { 5960 ted.mActionIndex = ev.getActionIndex(); 5961 } 5962 ted.mMetaState = ev.getMetaState(); 5963 ted.mReprocess = true; 5964 ted.mMotionEvent = MotionEvent.obtain(ev); 5965 ted.mSequence = sequence; 5966 mWebViewCore.sendMessage(EventHub.TOUCH_EVENT, ted); 5967 cancelLongPress(); 5968 mPrivateHandler.removeMessages(SWITCH_TO_LONGPRESS); 5969 mPreventDefault = PREVENT_DEFAULT_IGNORE; 5970 } 5971 5972 private void handleMultiTouchInWebView(MotionEvent ev) { 5973 if (DebugFlags.WEB_VIEW) { 5974 Log.v(LOGTAG, "multi-touch: " + ev + " at " + ev.getEventTime() 5975 + " mTouchMode=" + mTouchMode 5976 + " numPointers=" + ev.getPointerCount() 5977 + " scrolloffset=(" + mScrollX + "," + mScrollY + ")"); 5978 } 5979 5980 final ScaleGestureDetector detector = 5981 mZoomManager.getMultiTouchGestureDetector(); 5982 5983 // A few apps use WebView but don't instantiate gesture detector. 5984 // We don't need to support multi touch for them. 5985 if (detector == null) return; 5986 5987 float x = ev.getX(); 5988 float y = ev.getY(); 5989 5990 detector.onTouchEvent(ev); 5991 5992 if (detector.isInProgress()) { 5993 if (DebugFlags.WEB_VIEW) { 5994 Log.v(LOGTAG, "detector is in progress"); 5995 } 5996 mLastTouchTime = ev.getEventTime(); 5997 x = detector.getFocusX(); 5998 y = detector.getFocusY(); 5999 6000 cancelLongPress(); 6001 mPrivateHandler.removeMessages(SWITCH_TO_LONGPRESS); 6002 if (!mZoomManager.supportsPanDuringZoom()) { 6003 return; 6004 } 6005 mTouchMode = TOUCH_DRAG_MODE; 6006 if (mVelocityTracker == null) { 6007 mVelocityTracker = VelocityTracker.obtain(); 6008 } 6009 } 6010 6011 int action = ev.getActionMasked(); 6012 if (action == MotionEvent.ACTION_POINTER_DOWN) { 6013 cancelTouch(); 6014 action = MotionEvent.ACTION_DOWN; 6015 } else if (action == MotionEvent.ACTION_POINTER_UP && ev.getPointerCount() == 2) { 6016 // set mLastTouchX/Y to the remaining point 6017 mLastTouchX = Math.round(x); 6018 mLastTouchY = Math.round(y); 6019 mIsHandlingMultiTouch = false; 6020 } else if (action == MotionEvent.ACTION_MOVE) { 6021 // negative x or y indicate it is on the edge, skip it. 6022 if (x < 0 || y < 0) { 6023 return; 6024 } 6025 } 6026 6027 handleTouchEventCommon(ev, action, Math.round(x), Math.round(y)); 6028 } 6029 6030 private void cancelWebCoreTouchEvent(int x, int y, boolean removeEvents) { 6031 if (shouldForwardTouchEvent()) { 6032 if (removeEvents) { 6033 mWebViewCore.removeMessages(EventHub.TOUCH_EVENT); 6034 } 6035 TouchEventData ted = new TouchEventData(); 6036 ted.mIds = new int[1]; 6037 ted.mIds[0] = 0; 6038 ted.mPoints = new Point[1]; 6039 ted.mPoints[0] = new Point(x, y); 6040 ted.mAction = MotionEvent.ACTION_CANCEL; 6041 ted.mNativeLayer = nativeScrollableLayer( 6042 x, y, ted.mNativeLayerRect, null); 6043 ted.mSequence = mTouchEventQueue.nextTouchSequence(); 6044 mWebViewCore.sendMessage(EventHub.TOUCH_EVENT, ted); 6045 mPreventDefault = PREVENT_DEFAULT_IGNORE; 6046 } 6047 } 6048 6049 private void startTouch(float x, float y, long eventTime) { 6050 // Remember where the motion event started 6051 mLastTouchX = Math.round(x); 6052 mLastTouchY = Math.round(y); 6053 mLastTouchTime = eventTime; 6054 mVelocityTracker = VelocityTracker.obtain(); 6055 mSnapScrollMode = SNAP_NONE; 6056 } 6057 6058 private void startDrag() { 6059 WebViewCore.reducePriority(); 6060 // to get better performance, pause updating the picture 6061 WebViewCore.pauseUpdatePicture(mWebViewCore); 6062 if (!mDragFromTextInput) { 6063 nativeHideCursor(); 6064 } 6065 6066 if (mHorizontalScrollBarMode != SCROLLBAR_ALWAYSOFF 6067 || mVerticalScrollBarMode != SCROLLBAR_ALWAYSOFF) { 6068 mZoomManager.invokeZoomPicker(); 6069 } 6070 } 6071 6072 private void doDrag(int deltaX, int deltaY) { 6073 if ((deltaX | deltaY) != 0) { 6074 int oldX = mScrollX; 6075 int oldY = mScrollY; 6076 int rangeX = computeMaxScrollX(); 6077 int rangeY = computeMaxScrollY(); 6078 int overscrollDistance = mOverscrollDistance; 6079 6080 // Check for the original scrolling layer in case we change 6081 // directions. mTouchMode might be TOUCH_DRAG_MODE if we have 6082 // reached the edge of a layer but mScrollingLayer will be non-zero 6083 // if we initiated the drag on a layer. 6084 if (mScrollingLayer != 0) { 6085 final int contentX = viewToContentDimension(deltaX); 6086 final int contentY = viewToContentDimension(deltaY); 6087 6088 // Check the scrolling bounds to see if we will actually do any 6089 // scrolling. The rectangle is in document coordinates. 6090 final int maxX = mScrollingLayerRect.right; 6091 final int maxY = mScrollingLayerRect.bottom; 6092 final int resultX = Math.max(0, 6093 Math.min(mScrollingLayerRect.left + contentX, maxX)); 6094 final int resultY = Math.max(0, 6095 Math.min(mScrollingLayerRect.top + contentY, maxY)); 6096 6097 if (resultX != mScrollingLayerRect.left || 6098 resultY != mScrollingLayerRect.top) { 6099 // In case we switched to dragging the page. 6100 mTouchMode = TOUCH_DRAG_LAYER_MODE; 6101 deltaX = contentX; 6102 deltaY = contentY; 6103 oldX = mScrollingLayerRect.left; 6104 oldY = mScrollingLayerRect.top; 6105 rangeX = maxX; 6106 rangeY = maxY; 6107 } else { 6108 // Scroll the main page if we are not going to scroll the 6109 // layer. This does not reset mScrollingLayer in case the 6110 // user changes directions and the layer can scroll the 6111 // other way. 6112 mTouchMode = TOUCH_DRAG_MODE; 6113 } 6114 } 6115 6116 if (mOverScrollGlow != null) { 6117 mOverScrollGlow.setOverScrollDeltas(deltaX, deltaY); 6118 } 6119 6120 overScrollBy(deltaX, deltaY, oldX, oldY, 6121 rangeX, rangeY, 6122 mOverscrollDistance, mOverscrollDistance, true); 6123 if (mOverScrollGlow != null && mOverScrollGlow.isAnimating()) { 6124 invalidate(); 6125 } 6126 } 6127 mZoomManager.keepZoomPickerVisible(); 6128 } 6129 6130 private void stopTouch() { 6131 // we also use mVelocityTracker == null to tell us that we are 6132 // not "moving around", so we can take the slower/prettier 6133 // mode in the drawing code 6134 if (mVelocityTracker != null) { 6135 mVelocityTracker.recycle(); 6136 mVelocityTracker = null; 6137 } 6138 6139 // Release any pulled glows 6140 if (mOverScrollGlow != null) { 6141 mOverScrollGlow.releaseAll(); 6142 } 6143 } 6144 6145 private void cancelTouch() { 6146 // we also use mVelocityTracker == null to tell us that we are 6147 // not "moving around", so we can take the slower/prettier 6148 // mode in the drawing code 6149 if (mVelocityTracker != null) { 6150 mVelocityTracker.recycle(); 6151 mVelocityTracker = null; 6152 } 6153 6154 if ((mTouchMode == TOUCH_DRAG_MODE 6155 || mTouchMode == TOUCH_DRAG_LAYER_MODE) && !mSelectingText) { 6156 WebViewCore.resumePriority(); 6157 WebViewCore.resumeUpdatePicture(mWebViewCore); 6158 } 6159 mPrivateHandler.removeMessages(SWITCH_TO_SHORTPRESS); 6160 mPrivateHandler.removeMessages(SWITCH_TO_LONGPRESS); 6161 mPrivateHandler.removeMessages(DRAG_HELD_MOTIONLESS); 6162 mPrivateHandler.removeMessages(AWAKEN_SCROLL_BARS); 6163 if (getSettings().supportTouchOnly()) { 6164 removeTouchHighlight(true); 6165 } 6166 mHeldMotionless = MOTIONLESS_TRUE; 6167 mTouchMode = TOUCH_DONE_MODE; 6168 nativeHideCursor(); 6169 } 6170 6171 @Override 6172 public boolean onGenericMotionEvent(MotionEvent event) { 6173 if ((event.getSource() & InputDevice.SOURCE_CLASS_POINTER) != 0) { 6174 switch (event.getAction()) { 6175 case MotionEvent.ACTION_SCROLL: { 6176 final float vscroll; 6177 final float hscroll; 6178 if ((event.getMetaState() & KeyEvent.META_SHIFT_ON) != 0) { 6179 vscroll = 0; 6180 hscroll = event.getAxisValue(MotionEvent.AXIS_VSCROLL); 6181 } else { 6182 vscroll = -event.getAxisValue(MotionEvent.AXIS_VSCROLL); 6183 hscroll = event.getAxisValue(MotionEvent.AXIS_HSCROLL); 6184 } 6185 if (hscroll != 0 || vscroll != 0) { 6186 final int vdelta = (int) (vscroll * getVerticalScrollFactor()); 6187 final int hdelta = (int) (hscroll * getHorizontalScrollFactor()); 6188 if (pinScrollBy(hdelta, vdelta, true, 0)) { 6189 return true; 6190 } 6191 } 6192 } 6193 } 6194 } 6195 return super.onGenericMotionEvent(event); 6196 } 6197 6198 private long mTrackballFirstTime = 0; 6199 private long mTrackballLastTime = 0; 6200 private float mTrackballRemainsX = 0.0f; 6201 private float mTrackballRemainsY = 0.0f; 6202 private int mTrackballXMove = 0; 6203 private int mTrackballYMove = 0; 6204 private boolean mSelectingText = false; 6205 private boolean mSelectionStarted = false; 6206 private boolean mExtendSelection = false; 6207 private boolean mDrawSelectionPointer = false; 6208 private static final int TRACKBALL_KEY_TIMEOUT = 1000; 6209 private static final int TRACKBALL_TIMEOUT = 200; 6210 private static final int TRACKBALL_WAIT = 100; 6211 private static final int TRACKBALL_SCALE = 400; 6212 private static final int TRACKBALL_SCROLL_COUNT = 5; 6213 private static final int TRACKBALL_MOVE_COUNT = 10; 6214 private static final int TRACKBALL_MULTIPLIER = 3; 6215 private static final int SELECT_CURSOR_OFFSET = 16; 6216 private static final int SELECT_SCROLL = 5; 6217 private int mSelectX = 0; 6218 private int mSelectY = 0; 6219 private boolean mFocusSizeChanged = false; 6220 private boolean mTrackballDown = false; 6221 private long mTrackballUpTime = 0; 6222 private long mLastCursorTime = 0; 6223 private Rect mLastCursorBounds; 6224 6225 // Set by default; BrowserActivity clears to interpret trackball data 6226 // directly for movement. Currently, the framework only passes 6227 // arrow key events, not trackball events, from one child to the next 6228 private boolean mMapTrackballToArrowKeys = true; 6229 6230 public void setMapTrackballToArrowKeys(boolean setMap) { 6231 mMapTrackballToArrowKeys = setMap; 6232 } 6233 6234 void resetTrackballTime() { 6235 mTrackballLastTime = 0; 6236 } 6237 6238 @Override 6239 public boolean onTrackballEvent(MotionEvent ev) { 6240 long time = ev.getEventTime(); 6241 if ((ev.getMetaState() & KeyEvent.META_ALT_ON) != 0) { 6242 if (ev.getY() > 0) pageDown(true); 6243 if (ev.getY() < 0) pageUp(true); 6244 return true; 6245 } 6246 if (ev.getAction() == MotionEvent.ACTION_DOWN) { 6247 if (mSelectingText) { 6248 return true; // discard press if copy in progress 6249 } 6250 mTrackballDown = true; 6251 if (mNativeClass == 0) { 6252 return false; 6253 } 6254 nativeRecordButtons(hasFocus() && hasWindowFocus(), true, true); 6255 if (time - mLastCursorTime <= TRACKBALL_TIMEOUT 6256 && !mLastCursorBounds.equals(nativeGetCursorRingBounds())) { 6257 nativeSelectBestAt(mLastCursorBounds); 6258 } 6259 if (DebugFlags.WEB_VIEW) { 6260 Log.v(LOGTAG, "onTrackballEvent down ev=" + ev 6261 + " time=" + time 6262 + " mLastCursorTime=" + mLastCursorTime); 6263 } 6264 if (isInTouchMode()) requestFocusFromTouch(); 6265 return false; // let common code in onKeyDown at it 6266 } 6267 if (ev.getAction() == MotionEvent.ACTION_UP) { 6268 // LONG_PRESS_CENTER is set in common onKeyDown 6269 mPrivateHandler.removeMessages(LONG_PRESS_CENTER); 6270 mTrackballDown = false; 6271 mTrackballUpTime = time; 6272 if (mSelectingText) { 6273 if (mExtendSelection) { 6274 copySelection(); 6275 selectionDone(); 6276 } else { 6277 mExtendSelection = true; 6278 nativeSetExtendSelection(); 6279 invalidate(); // draw the i-beam instead of the arrow 6280 } 6281 return true; // discard press if copy in progress 6282 } 6283 if (DebugFlags.WEB_VIEW) { 6284 Log.v(LOGTAG, "onTrackballEvent up ev=" + ev 6285 + " time=" + time 6286 ); 6287 } 6288 return false; // let common code in onKeyUp at it 6289 } 6290 if ((mMapTrackballToArrowKeys && (ev.getMetaState() & KeyEvent.META_SHIFT_ON) == 0) || 6291 AccessibilityManager.getInstance(mContext).isEnabled()) { 6292 if (DebugFlags.WEB_VIEW) Log.v(LOGTAG, "onTrackballEvent gmail quit"); 6293 return false; 6294 } 6295 if (mTrackballDown) { 6296 if (DebugFlags.WEB_VIEW) Log.v(LOGTAG, "onTrackballEvent down quit"); 6297 return true; // discard move if trackball is down 6298 } 6299 if (time - mTrackballUpTime < TRACKBALL_TIMEOUT) { 6300 if (DebugFlags.WEB_VIEW) Log.v(LOGTAG, "onTrackballEvent up timeout quit"); 6301 return true; 6302 } 6303 // TODO: alternatively we can do panning as touch does 6304 switchOutDrawHistory(); 6305 if (time - mTrackballLastTime > TRACKBALL_TIMEOUT) { 6306 if (DebugFlags.WEB_VIEW) { 6307 Log.v(LOGTAG, "onTrackballEvent time=" 6308 + time + " last=" + mTrackballLastTime); 6309 } 6310 mTrackballFirstTime = time; 6311 mTrackballXMove = mTrackballYMove = 0; 6312 } 6313 mTrackballLastTime = time; 6314 if (DebugFlags.WEB_VIEW) { 6315 Log.v(LOGTAG, "onTrackballEvent ev=" + ev + " time=" + time); 6316 } 6317 mTrackballRemainsX += ev.getX(); 6318 mTrackballRemainsY += ev.getY(); 6319 doTrackball(time, ev.getMetaState()); 6320 return true; 6321 } 6322 6323 void moveSelection(float xRate, float yRate) { 6324 if (mNativeClass == 0) 6325 return; 6326 int width = getViewWidth(); 6327 int height = getViewHeight(); 6328 mSelectX += xRate; 6329 mSelectY += yRate; 6330 int maxX = width + mScrollX; 6331 int maxY = height + mScrollY; 6332 mSelectX = Math.min(maxX, Math.max(mScrollX - SELECT_CURSOR_OFFSET 6333 , mSelectX)); 6334 mSelectY = Math.min(maxY, Math.max(mScrollY - SELECT_CURSOR_OFFSET 6335 , mSelectY)); 6336 if (DebugFlags.WEB_VIEW) { 6337 Log.v(LOGTAG, "moveSelection" 6338 + " mSelectX=" + mSelectX 6339 + " mSelectY=" + mSelectY 6340 + " mScrollX=" + mScrollX 6341 + " mScrollY=" + mScrollY 6342 + " xRate=" + xRate 6343 + " yRate=" + yRate 6344 ); 6345 } 6346 nativeMoveSelection(viewToContentX(mSelectX), viewToContentY(mSelectY)); 6347 int scrollX = mSelectX < mScrollX ? -SELECT_CURSOR_OFFSET 6348 : mSelectX > maxX - SELECT_CURSOR_OFFSET ? SELECT_CURSOR_OFFSET 6349 : 0; 6350 int scrollY = mSelectY < mScrollY ? -SELECT_CURSOR_OFFSET 6351 : mSelectY > maxY - SELECT_CURSOR_OFFSET ? SELECT_CURSOR_OFFSET 6352 : 0; 6353 pinScrollBy(scrollX, scrollY, true, 0); 6354 Rect select = new Rect(mSelectX, mSelectY, mSelectX + 1, mSelectY + 1); 6355 requestRectangleOnScreen(select); 6356 invalidate(); 6357 } 6358 6359 private int scaleTrackballX(float xRate, int width) { 6360 int xMove = (int) (xRate / TRACKBALL_SCALE * width); 6361 int nextXMove = xMove; 6362 if (xMove > 0) { 6363 if (xMove > mTrackballXMove) { 6364 xMove -= mTrackballXMove; 6365 } 6366 } else if (xMove < mTrackballXMove) { 6367 xMove -= mTrackballXMove; 6368 } 6369 mTrackballXMove = nextXMove; 6370 return xMove; 6371 } 6372 6373 private int scaleTrackballY(float yRate, int height) { 6374 int yMove = (int) (yRate / TRACKBALL_SCALE * height); 6375 int nextYMove = yMove; 6376 if (yMove > 0) { 6377 if (yMove > mTrackballYMove) { 6378 yMove -= mTrackballYMove; 6379 } 6380 } else if (yMove < mTrackballYMove) { 6381 yMove -= mTrackballYMove; 6382 } 6383 mTrackballYMove = nextYMove; 6384 return yMove; 6385 } 6386 6387 private int keyCodeToSoundsEffect(int keyCode) { 6388 switch(keyCode) { 6389 case KeyEvent.KEYCODE_DPAD_UP: 6390 return SoundEffectConstants.NAVIGATION_UP; 6391 case KeyEvent.KEYCODE_DPAD_RIGHT: 6392 return SoundEffectConstants.NAVIGATION_RIGHT; 6393 case KeyEvent.KEYCODE_DPAD_DOWN: 6394 return SoundEffectConstants.NAVIGATION_DOWN; 6395 case KeyEvent.KEYCODE_DPAD_LEFT: 6396 return SoundEffectConstants.NAVIGATION_LEFT; 6397 } 6398 throw new IllegalArgumentException("keyCode must be one of " + 6399 "{KEYCODE_DPAD_UP, KEYCODE_DPAD_RIGHT, KEYCODE_DPAD_DOWN, " + 6400 "KEYCODE_DPAD_LEFT}."); 6401 } 6402 6403 private void doTrackball(long time, int metaState) { 6404 int elapsed = (int) (mTrackballLastTime - mTrackballFirstTime); 6405 if (elapsed == 0) { 6406 elapsed = TRACKBALL_TIMEOUT; 6407 } 6408 float xRate = mTrackballRemainsX * 1000 / elapsed; 6409 float yRate = mTrackballRemainsY * 1000 / elapsed; 6410 int viewWidth = getViewWidth(); 6411 int viewHeight = getViewHeight(); 6412 if (mSelectingText) { 6413 if (!mDrawSelectionPointer) { 6414 // The last selection was made by touch, disabling drawing the 6415 // selection pointer. Allow the trackball to adjust the 6416 // position of the touch control. 6417 mSelectX = contentToViewX(nativeSelectionX()); 6418 mSelectY = contentToViewY(nativeSelectionY()); 6419 mDrawSelectionPointer = mExtendSelection = true; 6420 nativeSetExtendSelection(); 6421 } 6422 moveSelection(scaleTrackballX(xRate, viewWidth), 6423 scaleTrackballY(yRate, viewHeight)); 6424 mTrackballRemainsX = mTrackballRemainsY = 0; 6425 return; 6426 } 6427 float ax = Math.abs(xRate); 6428 float ay = Math.abs(yRate); 6429 float maxA = Math.max(ax, ay); 6430 if (DebugFlags.WEB_VIEW) { 6431 Log.v(LOGTAG, "doTrackball elapsed=" + elapsed 6432 + " xRate=" + xRate 6433 + " yRate=" + yRate 6434 + " mTrackballRemainsX=" + mTrackballRemainsX 6435 + " mTrackballRemainsY=" + mTrackballRemainsY); 6436 } 6437 int width = mContentWidth - viewWidth; 6438 int height = mContentHeight - viewHeight; 6439 if (width < 0) width = 0; 6440 if (height < 0) height = 0; 6441 ax = Math.abs(mTrackballRemainsX * TRACKBALL_MULTIPLIER); 6442 ay = Math.abs(mTrackballRemainsY * TRACKBALL_MULTIPLIER); 6443 maxA = Math.max(ax, ay); 6444 int count = Math.max(0, (int) maxA); 6445 int oldScrollX = mScrollX; 6446 int oldScrollY = mScrollY; 6447 if (count > 0) { 6448 int selectKeyCode = ax < ay ? mTrackballRemainsY < 0 ? 6449 KeyEvent.KEYCODE_DPAD_UP : KeyEvent.KEYCODE_DPAD_DOWN : 6450 mTrackballRemainsX < 0 ? KeyEvent.KEYCODE_DPAD_LEFT : 6451 KeyEvent.KEYCODE_DPAD_RIGHT; 6452 count = Math.min(count, TRACKBALL_MOVE_COUNT); 6453 if (DebugFlags.WEB_VIEW) { 6454 Log.v(LOGTAG, "doTrackball keyCode=" + selectKeyCode 6455 + " count=" + count 6456 + " mTrackballRemainsX=" + mTrackballRemainsX 6457 + " mTrackballRemainsY=" + mTrackballRemainsY); 6458 } 6459 if (mNativeClass != 0 && nativePageShouldHandleShiftAndArrows()) { 6460 for (int i = 0; i < count; i++) { 6461 letPageHandleNavKey(selectKeyCode, time, true, metaState); 6462 } 6463 letPageHandleNavKey(selectKeyCode, time, false, metaState); 6464 } else if (navHandledKey(selectKeyCode, count, false, time)) { 6465 playSoundEffect(keyCodeToSoundsEffect(selectKeyCode)); 6466 } 6467 mTrackballRemainsX = mTrackballRemainsY = 0; 6468 } 6469 if (count >= TRACKBALL_SCROLL_COUNT) { 6470 int xMove = scaleTrackballX(xRate, width); 6471 int yMove = scaleTrackballY(yRate, height); 6472 if (DebugFlags.WEB_VIEW) { 6473 Log.v(LOGTAG, "doTrackball pinScrollBy" 6474 + " count=" + count 6475 + " xMove=" + xMove + " yMove=" + yMove 6476 + " mScrollX-oldScrollX=" + (mScrollX-oldScrollX) 6477 + " mScrollY-oldScrollY=" + (mScrollY-oldScrollY) 6478 ); 6479 } 6480 if (Math.abs(mScrollX - oldScrollX) > Math.abs(xMove)) { 6481 xMove = 0; 6482 } 6483 if (Math.abs(mScrollY - oldScrollY) > Math.abs(yMove)) { 6484 yMove = 0; 6485 } 6486 if (xMove != 0 || yMove != 0) { 6487 pinScrollBy(xMove, yMove, true, 0); 6488 } 6489 } 6490 } 6491 6492 /** 6493 * Compute the maximum horizontal scroll position. Used by {@link OverScrollGlow}. 6494 * @return Maximum horizontal scroll position within real content 6495 */ 6496 int computeMaxScrollX() { 6497 return Math.max(computeRealHorizontalScrollRange() - getViewWidth(), 0); 6498 } 6499 6500 /** 6501 * Compute the maximum vertical scroll position. Used by {@link OverScrollGlow}. 6502 * @return Maximum vertical scroll position within real content 6503 */ 6504 int computeMaxScrollY() { 6505 return Math.max(computeRealVerticalScrollRange() + getTitleHeight() 6506 - getViewHeightWithTitle(), 0); 6507 } 6508 6509 boolean updateScrollCoordinates(int x, int y) { 6510 int oldX = mScrollX; 6511 int oldY = mScrollY; 6512 mScrollX = x; 6513 mScrollY = y; 6514 if (oldX != mScrollX || oldY != mScrollY) { 6515 onScrollChanged(mScrollX, mScrollY, oldX, oldY); 6516 return true; 6517 } else { 6518 return false; 6519 } 6520 } 6521 6522 public void flingScroll(int vx, int vy) { 6523 mScroller.fling(mScrollX, mScrollY, vx, vy, 0, computeMaxScrollX(), 0, 6524 computeMaxScrollY(), mOverflingDistance, mOverflingDistance); 6525 invalidate(); 6526 } 6527 6528 private void doFling() { 6529 if (mVelocityTracker == null) { 6530 return; 6531 } 6532 int maxX = computeMaxScrollX(); 6533 int maxY = computeMaxScrollY(); 6534 6535 mVelocityTracker.computeCurrentVelocity(1000, mMaximumFling); 6536 int vx = (int) mVelocityTracker.getXVelocity(); 6537 int vy = (int) mVelocityTracker.getYVelocity(); 6538 6539 int scrollX = mScrollX; 6540 int scrollY = mScrollY; 6541 int overscrollDistance = mOverscrollDistance; 6542 int overflingDistance = mOverflingDistance; 6543 6544 // Use the layer's scroll data if applicable. 6545 if (mTouchMode == TOUCH_DRAG_LAYER_MODE) { 6546 scrollX = mScrollingLayerRect.left; 6547 scrollY = mScrollingLayerRect.top; 6548 maxX = mScrollingLayerRect.right; 6549 maxY = mScrollingLayerRect.bottom; 6550 // No overscrolling for layers. 6551 overscrollDistance = overflingDistance = 0; 6552 } 6553 6554 if (mSnapScrollMode != SNAP_NONE) { 6555 if ((mSnapScrollMode & SNAP_X) == SNAP_X) { 6556 vy = 0; 6557 } else { 6558 vx = 0; 6559 } 6560 } 6561 if (true /* EMG release: make our fling more like Maps' */) { 6562 // maps cuts their velocity in half 6563 vx = vx * 3 / 4; 6564 vy = vy * 3 / 4; 6565 } 6566 if ((maxX == 0 && vy == 0) || (maxY == 0 && vx == 0)) { 6567 WebViewCore.resumePriority(); 6568 if (!mSelectingText) { 6569 WebViewCore.resumeUpdatePicture(mWebViewCore); 6570 } 6571 if (mScroller.springBack(scrollX, scrollY, 0, maxX, 0, maxY)) { 6572 invalidate(); 6573 } 6574 return; 6575 } 6576 float currentVelocity = mScroller.getCurrVelocity(); 6577 float velocity = (float) Math.hypot(vx, vy); 6578 if (mLastVelocity > 0 && currentVelocity > 0 && velocity 6579 > mLastVelocity * MINIMUM_VELOCITY_RATIO_FOR_ACCELERATION) { 6580 float deltaR = (float) (Math.abs(Math.atan2(mLastVelY, mLastVelX) 6581 - Math.atan2(vy, vx))); 6582 final float circle = (float) (Math.PI) * 2.0f; 6583 if (deltaR > circle * 0.9f || deltaR < circle * 0.1f) { 6584 vx += currentVelocity * mLastVelX / mLastVelocity; 6585 vy += currentVelocity * mLastVelY / mLastVelocity; 6586 velocity = (float) Math.hypot(vx, vy); 6587 if (DebugFlags.WEB_VIEW) { 6588 Log.v(LOGTAG, "doFling vx= " + vx + " vy=" + vy); 6589 } 6590 } else if (DebugFlags.WEB_VIEW) { 6591 Log.v(LOGTAG, "doFling missed " + deltaR / circle); 6592 } 6593 } else if (DebugFlags.WEB_VIEW) { 6594 Log.v(LOGTAG, "doFling start last=" + mLastVelocity 6595 + " current=" + currentVelocity 6596 + " vx=" + vx + " vy=" + vy 6597 + " maxX=" + maxX + " maxY=" + maxY 6598 + " scrollX=" + scrollX + " scrollY=" + scrollY 6599 + " layer=" + mScrollingLayer); 6600 } 6601 6602 // Allow sloppy flings without overscrolling at the edges. 6603 if ((scrollX == 0 || scrollX == maxX) && Math.abs(vx) < Math.abs(vy)) { 6604 vx = 0; 6605 } 6606 if ((scrollY == 0 || scrollY == maxY) && Math.abs(vy) < Math.abs(vx)) { 6607 vy = 0; 6608 } 6609 6610 if (overscrollDistance < overflingDistance) { 6611 if ((vx > 0 && scrollX == -overscrollDistance) || 6612 (vx < 0 && scrollX == maxX + overscrollDistance)) { 6613 vx = 0; 6614 } 6615 if ((vy > 0 && scrollY == -overscrollDistance) || 6616 (vy < 0 && scrollY == maxY + overscrollDistance)) { 6617 vy = 0; 6618 } 6619 } 6620 6621 mLastVelX = vx; 6622 mLastVelY = vy; 6623 mLastVelocity = velocity; 6624 6625 // no horizontal overscroll if the content just fits 6626 mScroller.fling(scrollX, scrollY, -vx, -vy, 0, maxX, 0, maxY, 6627 maxX == 0 ? 0 : overflingDistance, overflingDistance); 6628 // Duration is calculated based on velocity. With range boundaries and overscroll 6629 // we may not know how long the final animation will take. (Hence the deprecation 6630 // warning on the call below.) It's not a big deal for scroll bars but if webcore 6631 // resumes during this effect we will take a performance hit. See computeScroll; 6632 // we resume webcore there when the animation is finished. 6633 final int time = mScroller.getDuration(); 6634 6635 // Suppress scrollbars for layer scrolling. 6636 if (mTouchMode != TOUCH_DRAG_LAYER_MODE) { 6637 awakenScrollBars(time); 6638 } 6639 6640 invalidate(); 6641 } 6642 6643 /** 6644 * Returns a view containing zoom controls i.e. +/- buttons. The caller is 6645 * in charge of installing this view to the view hierarchy. This view will 6646 * become visible when the user starts scrolling via touch and fade away if 6647 * the user does not interact with it. 6648 * <p/> 6649 * API version 3 introduces a built-in zoom mechanism that is shown 6650 * automatically by the MapView. This is the preferred approach for 6651 * showing the zoom UI. 6652 * 6653 * @deprecated The built-in zoom mechanism is preferred, see 6654 * {@link WebSettings#setBuiltInZoomControls(boolean)}. 6655 */ 6656 @Deprecated 6657 public View getZoomControls() { 6658 if (!getSettings().supportZoom()) { 6659 Log.w(LOGTAG, "This WebView doesn't support zoom."); 6660 return null; 6661 } 6662 return mZoomManager.getExternalZoomPicker(); 6663 } 6664 6665 void dismissZoomControl() { 6666 mZoomManager.dismissZoomPicker(); 6667 } 6668 6669 float getDefaultZoomScale() { 6670 return mZoomManager.getDefaultScale(); 6671 } 6672 6673 /** 6674 * @return TRUE if the WebView can be zoomed in. 6675 */ 6676 public boolean canZoomIn() { 6677 return mZoomManager.canZoomIn(); 6678 } 6679 6680 /** 6681 * @return TRUE if the WebView can be zoomed out. 6682 */ 6683 public boolean canZoomOut() { 6684 return mZoomManager.canZoomOut(); 6685 } 6686 6687 /** 6688 * Perform zoom in in the webview 6689 * @return TRUE if zoom in succeeds. FALSE if no zoom changes. 6690 */ 6691 public boolean zoomIn() { 6692 return mZoomManager.zoomIn(); 6693 } 6694 6695 /** 6696 * Perform zoom out in the webview 6697 * @return TRUE if zoom out succeeds. FALSE if no zoom changes. 6698 */ 6699 public boolean zoomOut() { 6700 return mZoomManager.zoomOut(); 6701 } 6702 6703 private void updateSelection() { 6704 if (mNativeClass == 0) { 6705 return; 6706 } 6707 // mLastTouchX and mLastTouchY are the point in the current viewport 6708 int contentX = viewToContentX(mLastTouchX + mScrollX); 6709 int contentY = viewToContentY(mLastTouchY + mScrollY); 6710 int slop = viewToContentDimension(mNavSlop); 6711 Rect rect = new Rect(contentX - slop, contentY - slop, 6712 contentX + slop, contentY + slop); 6713 nativeSelectBestAt(rect); 6714 mInitialHitTestResult = hitTestResult(null); 6715 } 6716 6717 /** 6718 * Scroll the focused text field to match the WebTextView 6719 * @param xPercent New x position of the WebTextView from 0 to 1. 6720 */ 6721 /*package*/ void scrollFocusedTextInputX(float xPercent) { 6722 if (!inEditingMode() || mWebViewCore == null) { 6723 return; 6724 } 6725 mWebViewCore.sendMessage(EventHub.SCROLL_TEXT_INPUT, 0, 6726 new Float(xPercent)); 6727 } 6728 6729 /** 6730 * Scroll the focused textarea vertically to match the WebTextView 6731 * @param y New y position of the WebTextView in view coordinates 6732 */ 6733 /* package */ void scrollFocusedTextInputY(int y) { 6734 if (!inEditingMode() || mWebViewCore == null) { 6735 return; 6736 } 6737 mWebViewCore.sendMessage(EventHub.SCROLL_TEXT_INPUT, 0, viewToContentDimension(y)); 6738 } 6739 6740 /** 6741 * Set our starting point and time for a drag from the WebTextView. 6742 */ 6743 /*package*/ void initiateTextFieldDrag(float x, float y, long eventTime) { 6744 if (!inEditingMode()) { 6745 return; 6746 } 6747 mLastTouchX = Math.round(x + mWebTextView.getLeft() - mScrollX); 6748 mLastTouchY = Math.round(y + mWebTextView.getTop() - mScrollY); 6749 mLastTouchTime = eventTime; 6750 if (!mScroller.isFinished()) { 6751 abortAnimation(); 6752 mPrivateHandler.removeMessages(RESUME_WEBCORE_PRIORITY); 6753 } 6754 mSnapScrollMode = SNAP_NONE; 6755 mVelocityTracker = VelocityTracker.obtain(); 6756 mTouchMode = TOUCH_DRAG_START_MODE; 6757 } 6758 6759 /** 6760 * Given a motion event from the WebTextView, set its location to our 6761 * coordinates, and handle the event. 6762 */ 6763 /*package*/ boolean textFieldDrag(MotionEvent event) { 6764 if (!inEditingMode()) { 6765 return false; 6766 } 6767 mDragFromTextInput = true; 6768 event.offsetLocation((float) (mWebTextView.getLeft() - mScrollX), 6769 (float) (mWebTextView.getTop() - mScrollY)); 6770 boolean result = onTouchEvent(event); 6771 mDragFromTextInput = false; 6772 return result; 6773 } 6774 6775 /** 6776 * Due a touch up from a WebTextView. This will be handled by webkit to 6777 * change the selection. 6778 * @param event MotionEvent in the WebTextView's coordinates. 6779 */ 6780 /*package*/ void touchUpOnTextField(MotionEvent event) { 6781 if (!inEditingMode()) { 6782 return; 6783 } 6784 int x = viewToContentX((int) event.getX() + mWebTextView.getLeft()); 6785 int y = viewToContentY((int) event.getY() + mWebTextView.getTop()); 6786 int slop = viewToContentDimension(mNavSlop); 6787 nativeMotionUp(x, y, slop); 6788 } 6789 6790 /** 6791 * Called when pressing the center key or trackball on a textfield. 6792 */ 6793 /*package*/ void centerKeyPressOnTextField() { 6794 mWebViewCore.sendMessage(EventHub.CLICK, nativeCursorFramePointer(), 6795 nativeCursorNodePointer()); 6796 } 6797 6798 private void doShortPress() { 6799 if (mNativeClass == 0) { 6800 return; 6801 } 6802 if (mPreventDefault == PREVENT_DEFAULT_YES) { 6803 return; 6804 } 6805 mTouchMode = TOUCH_DONE_MODE; 6806 switchOutDrawHistory(); 6807 // mLastTouchX and mLastTouchY are the point in the current viewport 6808 int contentX = viewToContentX(mLastTouchX + mScrollX); 6809 int contentY = viewToContentY(mLastTouchY + mScrollY); 6810 int slop = viewToContentDimension(mNavSlop); 6811 if (getSettings().supportTouchOnly()) { 6812 removeTouchHighlight(false); 6813 WebViewCore.TouchUpData touchUpData = new WebViewCore.TouchUpData(); 6814 // use "0" as generation id to inform WebKit to use the same x/y as 6815 // it used when processing GET_TOUCH_HIGHLIGHT_RECTS 6816 touchUpData.mMoveGeneration = 0; 6817 mWebViewCore.sendMessage(EventHub.TOUCH_UP, touchUpData); 6818 } else if (nativePointInNavCache(contentX, contentY, slop)) { 6819 WebViewCore.MotionUpData motionUpData = new WebViewCore 6820 .MotionUpData(); 6821 motionUpData.mFrame = nativeCacheHitFramePointer(); 6822 motionUpData.mNode = nativeCacheHitNodePointer(); 6823 motionUpData.mBounds = nativeCacheHitNodeBounds(); 6824 motionUpData.mX = contentX; 6825 motionUpData.mY = contentY; 6826 mWebViewCore.sendMessageAtFrontOfQueue(EventHub.VALID_NODE_BOUNDS, 6827 motionUpData); 6828 } else { 6829 doMotionUp(contentX, contentY); 6830 } 6831 } 6832 6833 private void doMotionUp(int contentX, int contentY) { 6834 int slop = viewToContentDimension(mNavSlop); 6835 if (nativeMotionUp(contentX, contentY, slop) && mLogEvent) { 6836 EventLog.writeEvent(EventLogTags.BROWSER_SNAP_CENTER); 6837 } 6838 if (nativeHasCursorNode() && !nativeCursorIsTextInput()) { 6839 playSoundEffect(SoundEffectConstants.CLICK); 6840 } 6841 } 6842 6843 /** 6844 * Returns plugin bounds if x/y in content coordinates corresponds to a 6845 * plugin. Otherwise a NULL rectangle is returned. 6846 */ 6847 Rect getPluginBounds(int x, int y) { 6848 int slop = viewToContentDimension(mNavSlop); 6849 if (nativePointInNavCache(x, y, slop) && nativeCacheHitIsPlugin()) { 6850 return nativeCacheHitNodeBounds(); 6851 } else { 6852 return null; 6853 } 6854 } 6855 6856 /* 6857 * Return true if the rect (e.g. plugin) is fully visible and maximized 6858 * inside the WebView. 6859 */ 6860 boolean isRectFitOnScreen(Rect rect) { 6861 final int rectWidth = rect.width(); 6862 final int rectHeight = rect.height(); 6863 final int viewWidth = getViewWidth(); 6864 final int viewHeight = getViewHeightWithTitle(); 6865 float scale = Math.min((float) viewWidth / rectWidth, (float) viewHeight / rectHeight); 6866 scale = mZoomManager.computeScaleWithLimits(scale); 6867 return !mZoomManager.willScaleTriggerZoom(scale) 6868 && contentToViewX(rect.left) >= mScrollX 6869 && contentToViewX(rect.right) <= mScrollX + viewWidth 6870 && contentToViewY(rect.top) >= mScrollY 6871 && contentToViewY(rect.bottom) <= mScrollY + viewHeight; 6872 } 6873 6874 /* 6875 * Maximize and center the rectangle, specified in the document coordinate 6876 * space, inside the WebView. If the zoom doesn't need to be changed, do an 6877 * animated scroll to center it. If the zoom needs to be changed, find the 6878 * zoom center and do a smooth zoom transition. The rect is in document 6879 * coordinates 6880 */ 6881 void centerFitRect(Rect rect) { 6882 final int rectWidth = rect.width(); 6883 final int rectHeight = rect.height(); 6884 final int viewWidth = getViewWidth(); 6885 final int viewHeight = getViewHeightWithTitle(); 6886 float scale = Math.min((float) viewWidth / rectWidth, (float) viewHeight 6887 / rectHeight); 6888 scale = mZoomManager.computeScaleWithLimits(scale); 6889 if (!mZoomManager.willScaleTriggerZoom(scale)) { 6890 pinScrollTo(contentToViewX(rect.left + rectWidth / 2) - viewWidth / 2, 6891 contentToViewY(rect.top + rectHeight / 2) - viewHeight / 2, 6892 true, 0); 6893 } else { 6894 float actualScale = mZoomManager.getScale(); 6895 float oldScreenX = rect.left * actualScale - mScrollX; 6896 float rectViewX = rect.left * scale; 6897 float rectViewWidth = rectWidth * scale; 6898 float newMaxWidth = mContentWidth * scale; 6899 float newScreenX = (viewWidth - rectViewWidth) / 2; 6900 // pin the newX to the WebView 6901 if (newScreenX > rectViewX) { 6902 newScreenX = rectViewX; 6903 } else if (newScreenX > (newMaxWidth - rectViewX - rectViewWidth)) { 6904 newScreenX = viewWidth - (newMaxWidth - rectViewX); 6905 } 6906 float zoomCenterX = (oldScreenX * scale - newScreenX * actualScale) 6907 / (scale - actualScale); 6908 float oldScreenY = rect.top * actualScale + getTitleHeight() 6909 - mScrollY; 6910 float rectViewY = rect.top * scale + getTitleHeight(); 6911 float rectViewHeight = rectHeight * scale; 6912 float newMaxHeight = mContentHeight * scale + getTitleHeight(); 6913 float newScreenY = (viewHeight - rectViewHeight) / 2; 6914 // pin the newY to the WebView 6915 if (newScreenY > rectViewY) { 6916 newScreenY = rectViewY; 6917 } else if (newScreenY > (newMaxHeight - rectViewY - rectViewHeight)) { 6918 newScreenY = viewHeight - (newMaxHeight - rectViewY); 6919 } 6920 float zoomCenterY = (oldScreenY * scale - newScreenY * actualScale) 6921 / (scale - actualScale); 6922 mZoomManager.setZoomCenter(zoomCenterX, zoomCenterY); 6923 mZoomManager.startZoomAnimation(scale, false); 6924 } 6925 } 6926 6927 // Called by JNI to handle a touch on a node representing an email address, 6928 // address, or phone number 6929 private void overrideLoading(String url) { 6930 mCallbackProxy.uiOverrideUrlLoading(url); 6931 } 6932 6933 @Override 6934 public boolean requestFocus(int direction, Rect previouslyFocusedRect) { 6935 // FIXME: If a subwindow is showing find, and the user touches the 6936 // background window, it can steal focus. 6937 if (mFindIsUp) return false; 6938 boolean result = false; 6939 if (inEditingMode()) { 6940 result = mWebTextView.requestFocus(direction, 6941 previouslyFocusedRect); 6942 } else { 6943 result = super.requestFocus(direction, previouslyFocusedRect); 6944 if (mWebViewCore.getSettings().getNeedInitialFocus() && !isInTouchMode()) { 6945 // For cases such as GMail, where we gain focus from a direction, 6946 // we want to move to the first available link. 6947 // FIXME: If there are no visible links, we may not want to 6948 int fakeKeyDirection = 0; 6949 switch(direction) { 6950 case View.FOCUS_UP: 6951 fakeKeyDirection = KeyEvent.KEYCODE_DPAD_UP; 6952 break; 6953 case View.FOCUS_DOWN: 6954 fakeKeyDirection = KeyEvent.KEYCODE_DPAD_DOWN; 6955 break; 6956 case View.FOCUS_LEFT: 6957 fakeKeyDirection = KeyEvent.KEYCODE_DPAD_LEFT; 6958 break; 6959 case View.FOCUS_RIGHT: 6960 fakeKeyDirection = KeyEvent.KEYCODE_DPAD_RIGHT; 6961 break; 6962 default: 6963 return result; 6964 } 6965 if (mNativeClass != 0 && !nativeHasCursorNode()) { 6966 navHandledKey(fakeKeyDirection, 1, true, 0); 6967 } 6968 } 6969 } 6970 return result; 6971 } 6972 6973 @Override 6974 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 6975 super.onMeasure(widthMeasureSpec, heightMeasureSpec); 6976 6977 int heightMode = MeasureSpec.getMode(heightMeasureSpec); 6978 int heightSize = MeasureSpec.getSize(heightMeasureSpec); 6979 int widthMode = MeasureSpec.getMode(widthMeasureSpec); 6980 int widthSize = MeasureSpec.getSize(widthMeasureSpec); 6981 6982 int measuredHeight = heightSize; 6983 int measuredWidth = widthSize; 6984 6985 // Grab the content size from WebViewCore. 6986 int contentHeight = contentToViewDimension(mContentHeight); 6987 int contentWidth = contentToViewDimension(mContentWidth); 6988 6989// Log.d(LOGTAG, "------- measure " + heightMode); 6990 6991 if (heightMode != MeasureSpec.EXACTLY) { 6992 mHeightCanMeasure = true; 6993 measuredHeight = contentHeight; 6994 if (heightMode == MeasureSpec.AT_MOST) { 6995 // If we are larger than the AT_MOST height, then our height can 6996 // no longer be measured and we should scroll internally. 6997 if (measuredHeight > heightSize) { 6998 measuredHeight = heightSize; 6999 mHeightCanMeasure = false; 7000 } else if (measuredHeight < heightSize) { 7001 measuredHeight |= MEASURED_STATE_TOO_SMALL; 7002 } 7003 } 7004 } else { 7005 mHeightCanMeasure = false; 7006 } 7007 if (mNativeClass != 0) { 7008 nativeSetHeightCanMeasure(mHeightCanMeasure); 7009 } 7010 // For the width, always use the given size unless unspecified. 7011 if (widthMode == MeasureSpec.UNSPECIFIED) { 7012 mWidthCanMeasure = true; 7013 measuredWidth = contentWidth; 7014 } else { 7015 if (measuredWidth < contentWidth) { 7016 measuredWidth |= MEASURED_STATE_TOO_SMALL; 7017 } 7018 mWidthCanMeasure = false; 7019 } 7020 7021 synchronized (this) { 7022 setMeasuredDimension(measuredWidth, measuredHeight); 7023 } 7024 } 7025 7026 @Override 7027 public boolean requestChildRectangleOnScreen(View child, 7028 Rect rect, 7029 boolean immediate) { 7030 if (mNativeClass == 0) { 7031 return false; 7032 } 7033 // don't scroll while in zoom animation. When it is done, we will adjust 7034 // the necessary components (e.g., WebTextView if it is in editing mode) 7035 if (mZoomManager.isFixedLengthAnimationInProgress()) { 7036 return false; 7037 } 7038 7039 rect.offset(child.getLeft() - child.getScrollX(), 7040 child.getTop() - child.getScrollY()); 7041 7042 Rect content = new Rect(viewToContentX(mScrollX), 7043 viewToContentY(mScrollY), 7044 viewToContentX(mScrollX + getWidth() 7045 - getVerticalScrollbarWidth()), 7046 viewToContentY(mScrollY + getViewHeightWithTitle())); 7047 content = nativeSubtractLayers(content); 7048 int screenTop = contentToViewY(content.top); 7049 int screenBottom = contentToViewY(content.bottom); 7050 int height = screenBottom - screenTop; 7051 int scrollYDelta = 0; 7052 7053 if (rect.bottom > screenBottom) { 7054 int oneThirdOfScreenHeight = height / 3; 7055 if (rect.height() > 2 * oneThirdOfScreenHeight) { 7056 // If the rectangle is too tall to fit in the bottom two thirds 7057 // of the screen, place it at the top. 7058 scrollYDelta = rect.top - screenTop; 7059 } else { 7060 // If the rectangle will still fit on screen, we want its 7061 // top to be in the top third of the screen. 7062 scrollYDelta = rect.top - (screenTop + oneThirdOfScreenHeight); 7063 } 7064 } else if (rect.top < screenTop) { 7065 scrollYDelta = rect.top - screenTop; 7066 } 7067 7068 int screenLeft = contentToViewX(content.left); 7069 int screenRight = contentToViewX(content.right); 7070 int width = screenRight - screenLeft; 7071 int scrollXDelta = 0; 7072 7073 if (rect.right > screenRight && rect.left > screenLeft) { 7074 if (rect.width() > width) { 7075 scrollXDelta += (rect.left - screenLeft); 7076 } else { 7077 scrollXDelta += (rect.right - screenRight); 7078 } 7079 } else if (rect.left < screenLeft) { 7080 scrollXDelta -= (screenLeft - rect.left); 7081 } 7082 7083 if ((scrollYDelta | scrollXDelta) != 0) { 7084 return pinScrollBy(scrollXDelta, scrollYDelta, !immediate, 0); 7085 } 7086 7087 return false; 7088 } 7089 7090 /* package */ void replaceTextfieldText(int oldStart, int oldEnd, 7091 String replace, int newStart, int newEnd) { 7092 WebViewCore.ReplaceTextData arg = new WebViewCore.ReplaceTextData(); 7093 arg.mReplace = replace; 7094 arg.mNewStart = newStart; 7095 arg.mNewEnd = newEnd; 7096 mTextGeneration++; 7097 arg.mTextGeneration = mTextGeneration; 7098 mWebViewCore.sendMessage(EventHub.REPLACE_TEXT, oldStart, oldEnd, arg); 7099 } 7100 7101 /* package */ void passToJavaScript(String currentText, KeyEvent event) { 7102 WebViewCore.JSKeyData arg = new WebViewCore.JSKeyData(); 7103 arg.mEvent = event; 7104 arg.mCurrentText = currentText; 7105 // Increase our text generation number, and pass it to webcore thread 7106 mTextGeneration++; 7107 mWebViewCore.sendMessage(EventHub.PASS_TO_JS, mTextGeneration, 0, arg); 7108 // WebKit's document state is not saved until about to leave the page. 7109 // To make sure the host application, like Browser, has the up to date 7110 // document state when it goes to background, we force to save the 7111 // document state. 7112 mWebViewCore.removeMessages(EventHub.SAVE_DOCUMENT_STATE); 7113 mWebViewCore.sendMessageDelayed(EventHub.SAVE_DOCUMENT_STATE, 7114 cursorData(), 1000); 7115 } 7116 7117 /* package */ synchronized WebViewCore getWebViewCore() { 7118 return mWebViewCore; 7119 } 7120 7121 /** 7122 * Used only by TouchEventQueue to store pending touch events. 7123 */ 7124 private static class QueuedTouch { 7125 long mSequence; 7126 MotionEvent mEvent; // Optional 7127 TouchEventData mTed; // Optional 7128 7129 QueuedTouch mNext; 7130 7131 public QueuedTouch set(TouchEventData ted) { 7132 mSequence = ted.mSequence; 7133 mTed = ted; 7134 mEvent = null; 7135 mNext = null; 7136 return this; 7137 } 7138 7139 public QueuedTouch set(MotionEvent ev, long sequence) { 7140 mEvent = MotionEvent.obtain(ev); 7141 mSequence = sequence; 7142 mTed = null; 7143 mNext = null; 7144 return this; 7145 } 7146 7147 public QueuedTouch add(QueuedTouch other) { 7148 if (other.mSequence < mSequence) { 7149 other.mNext = this; 7150 return other; 7151 } 7152 7153 QueuedTouch insertAt = this; 7154 while (insertAt.mNext != null && insertAt.mNext.mSequence < other.mSequence) { 7155 insertAt = insertAt.mNext; 7156 } 7157 other.mNext = insertAt.mNext; 7158 insertAt.mNext = other; 7159 return this; 7160 } 7161 } 7162 7163 /** 7164 * WebView handles touch events asynchronously since some events must be passed to WebKit 7165 * for potentially slower processing. TouchEventQueue serializes touch events regardless 7166 * of which path they take to ensure that no events are ever processed out of order 7167 * by WebView. 7168 */ 7169 private class TouchEventQueue { 7170 private long mNextTouchSequence = Long.MIN_VALUE + 1; 7171 private long mLastHandledTouchSequence = Long.MIN_VALUE; 7172 private QueuedTouch mTouchEventQueue; 7173 private QueuedTouch mQueuedTouchRecycleBin; 7174 private int mQueuedTouchRecycleCount; 7175 private static final int MAX_RECYCLED_QUEUED_TOUCH = 15; 7176 7177 private QueuedTouch obtainQueuedTouch() { 7178 if (mQueuedTouchRecycleBin != null) { 7179 QueuedTouch result = mQueuedTouchRecycleBin; 7180 mQueuedTouchRecycleBin = result.mNext; 7181 mQueuedTouchRecycleCount--; 7182 return result; 7183 } 7184 return new QueuedTouch(); 7185 } 7186 7187 private void recycleQueuedTouch(QueuedTouch qd) { 7188 if (mQueuedTouchRecycleCount < MAX_RECYCLED_QUEUED_TOUCH) { 7189 qd.mNext = mQueuedTouchRecycleBin; 7190 mQueuedTouchRecycleBin = qd; 7191 mQueuedTouchRecycleCount++; 7192 } 7193 } 7194 7195 /** 7196 * Reset the touch event queue. This will dump any pending events 7197 * and reset the sequence numbering. 7198 */ 7199 public void reset() { 7200 mNextTouchSequence = Long.MIN_VALUE + 1; 7201 mLastHandledTouchSequence = Long.MIN_VALUE; 7202 while (mTouchEventQueue != null) { 7203 QueuedTouch recycleMe = mTouchEventQueue; 7204 mTouchEventQueue = mTouchEventQueue.mNext; 7205 recycleQueuedTouch(recycleMe); 7206 } 7207 } 7208 7209 /** 7210 * Return the next valid sequence number for tagging incoming touch events. 7211 * @return The next touch event sequence number 7212 */ 7213 public long nextTouchSequence() { 7214 return mNextTouchSequence++; 7215 } 7216 7217 /** 7218 * Enqueue a touch event in the form of TouchEventData. 7219 * The sequence number will be read from the mSequence field of the argument. 7220 * 7221 * If the touch event's sequence number is the next in line to be processed, it will 7222 * be handled before this method returns. Any subsequent events that have already 7223 * been queued will also be processed in their proper order. 7224 * 7225 * @param ted Touch data to be processed in order. 7226 */ 7227 public void enqueueTouchEvent(TouchEventData ted) { 7228 if (mLastHandledTouchSequence + 1 == ted.mSequence) { 7229 handleQueuedTouchEventData(ted); 7230 7231 mLastHandledTouchSequence++; 7232 7233 // Do we have any more? Run them if so. 7234 QueuedTouch qd = mTouchEventQueue; 7235 while (qd != null && qd.mSequence == mLastHandledTouchSequence + 1) { 7236 handleQueuedTouch(qd); 7237 QueuedTouch recycleMe = qd; 7238 qd = qd.mNext; 7239 recycleQueuedTouch(recycleMe); 7240 mLastHandledTouchSequence++; 7241 } 7242 mTouchEventQueue = qd; 7243 } else { 7244 QueuedTouch qd = obtainQueuedTouch().set(ted); 7245 mTouchEventQueue = mTouchEventQueue == null ? qd : mTouchEventQueue.add(qd); 7246 } 7247 } 7248 7249 /** 7250 * Enqueue a touch event in the form of a MotionEvent from the framework. 7251 * 7252 * If the touch event's sequence number is the next in line to be processed, it will 7253 * be handled before this method returns. Any subsequent events that have already 7254 * been queued will also be processed in their proper order. 7255 * 7256 * @param ev MotionEvent to be processed in order 7257 */ 7258 public void enqueueTouchEvent(MotionEvent ev) { 7259 final long sequence = nextTouchSequence(); 7260 if (mLastHandledTouchSequence + 1 == sequence) { 7261 handleQueuedMotionEvent(ev); 7262 7263 mLastHandledTouchSequence++; 7264 7265 // Do we have any more? Run them if so. 7266 QueuedTouch qd = mTouchEventQueue; 7267 while (qd != null && qd.mSequence == mLastHandledTouchSequence + 1) { 7268 handleQueuedTouch(qd); 7269 QueuedTouch recycleMe = qd; 7270 qd = qd.mNext; 7271 recycleQueuedTouch(recycleMe); 7272 mLastHandledTouchSequence++; 7273 } 7274 mTouchEventQueue = qd; 7275 } else { 7276 QueuedTouch qd = obtainQueuedTouch().set(ev, sequence); 7277 mTouchEventQueue = mTouchEventQueue == null ? qd : mTouchEventQueue.add(qd); 7278 } 7279 } 7280 7281 private void handleQueuedTouch(QueuedTouch qt) { 7282 if (qt.mTed != null) { 7283 handleQueuedTouchEventData(qt.mTed); 7284 } else { 7285 handleQueuedMotionEvent(qt.mEvent); 7286 qt.mEvent.recycle(); 7287 } 7288 } 7289 7290 private void handleQueuedMotionEvent(MotionEvent ev) { 7291 int action = ev.getActionMasked(); 7292 if (ev.getPointerCount() > 1) { // Multi-touch 7293 mIsHandlingMultiTouch = true; 7294 7295 handleMultiTouchInWebView(ev); 7296 } else { 7297 final ScaleGestureDetector detector = mZoomManager.getMultiTouchGestureDetector(); 7298 if (detector != null) { 7299 // ScaleGestureDetector needs a consistent event stream to operate properly. 7300 // It won't take any action with fewer than two pointers, but it needs to 7301 // update internal bookkeeping state. 7302 detector.onTouchEvent(ev); 7303 } 7304 7305 handleTouchEventCommon(ev, action, Math.round(ev.getX()), Math.round(ev.getY())); 7306 } 7307 } 7308 7309 private void handleQueuedTouchEventData(TouchEventData ted) { 7310 if (!ted.mReprocess) { 7311 if (ted.mAction == MotionEvent.ACTION_DOWN 7312 && mPreventDefault == PREVENT_DEFAULT_MAYBE_YES) { 7313 // if prevent default is called from WebCore, UI 7314 // will not handle the rest of the touch events any 7315 // more. 7316 mPreventDefault = ted.mNativeResult ? PREVENT_DEFAULT_YES 7317 : PREVENT_DEFAULT_NO_FROM_TOUCH_DOWN; 7318 } else if (ted.mAction == MotionEvent.ACTION_MOVE 7319 && mPreventDefault == PREVENT_DEFAULT_NO_FROM_TOUCH_DOWN) { 7320 // the return for the first ACTION_MOVE will decide 7321 // whether UI will handle touch or not. Currently no 7322 // support for alternating prevent default 7323 mPreventDefault = ted.mNativeResult ? PREVENT_DEFAULT_YES 7324 : PREVENT_DEFAULT_NO; 7325 } 7326 if (mPreventDefault == PREVENT_DEFAULT_YES) { 7327 mTouchHighlightRegion.setEmpty(); 7328 } 7329 } else { 7330 if (ted.mPoints.length > 1) { // multi-touch 7331 if (ted.mAction == MotionEvent.ACTION_POINTER_UP && 7332 ted.mMotionEvent.getPointerCount() == 2) { 7333 mIsHandlingMultiTouch = false; 7334 } 7335 if (!ted.mNativeResult) { 7336 mPreventDefault = PREVENT_DEFAULT_NO; 7337 handleMultiTouchInWebView(ted.mMotionEvent); 7338 } else { 7339 mPreventDefault = PREVENT_DEFAULT_YES; 7340 } 7341 return; 7342 } 7343 7344 // prevent default is not called in WebCore, so the 7345 // message needs to be reprocessed in UI 7346 if (!ted.mNativeResult) { 7347 // Following is for single touch. 7348 switch (ted.mAction) { 7349 case MotionEvent.ACTION_DOWN: 7350 mLastDeferTouchX = contentToViewX(ted.mPoints[0].x) 7351 - mScrollX; 7352 mLastDeferTouchY = contentToViewY(ted.mPoints[0].y) 7353 - mScrollY; 7354 mDeferTouchMode = TOUCH_INIT_MODE; 7355 break; 7356 case MotionEvent.ACTION_MOVE: { 7357 // no snapping in defer process 7358 int x = contentToViewX(ted.mPoints[0].x) - mScrollX; 7359 int y = contentToViewY(ted.mPoints[0].y) - mScrollY; 7360 if (mDeferTouchMode != TOUCH_DRAG_MODE) { 7361 mDeferTouchMode = TOUCH_DRAG_MODE; 7362 mLastDeferTouchX = x; 7363 mLastDeferTouchY = y; 7364 startScrollingLayer(x, y); 7365 startDrag(); 7366 } 7367 int deltaX = pinLocX((int) (mScrollX 7368 + mLastDeferTouchX - x)) 7369 - mScrollX; 7370 int deltaY = pinLocY((int) (mScrollY 7371 + mLastDeferTouchY - y)) 7372 - mScrollY; 7373 doDrag(deltaX, deltaY); 7374 if (deltaX != 0) mLastDeferTouchX = x; 7375 if (deltaY != 0) mLastDeferTouchY = y; 7376 break; 7377 } 7378 case MotionEvent.ACTION_UP: 7379 case MotionEvent.ACTION_CANCEL: 7380 if (mDeferTouchMode == TOUCH_DRAG_MODE) { 7381 // no fling in defer process 7382 mScroller.springBack(mScrollX, mScrollY, 0, 7383 computeMaxScrollX(), 0, 7384 computeMaxScrollY()); 7385 invalidate(); 7386 WebViewCore.resumePriority(); 7387 WebViewCore.resumeUpdatePicture(mWebViewCore); 7388 } 7389 mDeferTouchMode = TOUCH_DONE_MODE; 7390 break; 7391 case WebViewCore.ACTION_DOUBLETAP: 7392 // doDoubleTap() needs mLastTouchX/Y as anchor 7393 mLastTouchX = contentToViewX(ted.mPoints[0].x) - mScrollX; 7394 mLastTouchY = contentToViewY(ted.mPoints[0].y) - mScrollY; 7395 mZoomManager.handleDoubleTap(mLastTouchX, mLastTouchY); 7396 mDeferTouchMode = TOUCH_DONE_MODE; 7397 break; 7398 case WebViewCore.ACTION_LONGPRESS: 7399 HitTestResult hitTest = getHitTestResult(); 7400 if (hitTest != null && hitTest.mType 7401 != HitTestResult.UNKNOWN_TYPE) { 7402 performLongClick(); 7403 } 7404 mDeferTouchMode = TOUCH_DONE_MODE; 7405 break; 7406 } 7407 } 7408 } 7409 } 7410 } 7411 7412 //------------------------------------------------------------------------- 7413 // Methods can be called from a separate thread, like WebViewCore 7414 // If it needs to call the View system, it has to send message. 7415 //------------------------------------------------------------------------- 7416 7417 /** 7418 * General handler to receive message coming from webkit thread 7419 */ 7420 class PrivateHandler extends Handler { 7421 @Override 7422 public void handleMessage(Message msg) { 7423 // exclude INVAL_RECT_MSG_ID since it is frequently output 7424 if (DebugFlags.WEB_VIEW && msg.what != INVAL_RECT_MSG_ID) { 7425 if (msg.what >= FIRST_PRIVATE_MSG_ID 7426 && msg.what <= LAST_PRIVATE_MSG_ID) { 7427 Log.v(LOGTAG, HandlerPrivateDebugString[msg.what 7428 - FIRST_PRIVATE_MSG_ID]); 7429 } else if (msg.what >= FIRST_PACKAGE_MSG_ID 7430 && msg.what <= LAST_PACKAGE_MSG_ID) { 7431 Log.v(LOGTAG, HandlerPackageDebugString[msg.what 7432 - FIRST_PACKAGE_MSG_ID]); 7433 } else { 7434 Log.v(LOGTAG, Integer.toString(msg.what)); 7435 } 7436 } 7437 if (mWebViewCore == null) { 7438 // after WebView's destroy() is called, skip handling messages. 7439 return; 7440 } 7441 switch (msg.what) { 7442 case REMEMBER_PASSWORD: { 7443 mDatabase.setUsernamePassword( 7444 msg.getData().getString("host"), 7445 msg.getData().getString("username"), 7446 msg.getData().getString("password")); 7447 ((Message) msg.obj).sendToTarget(); 7448 break; 7449 } 7450 case NEVER_REMEMBER_PASSWORD: { 7451 mDatabase.setUsernamePassword( 7452 msg.getData().getString("host"), null, null); 7453 ((Message) msg.obj).sendToTarget(); 7454 break; 7455 } 7456 case PREVENT_DEFAULT_TIMEOUT: { 7457 // if timeout happens, cancel it so that it won't block UI 7458 // to continue handling touch events 7459 if ((msg.arg1 == MotionEvent.ACTION_DOWN 7460 && mPreventDefault == PREVENT_DEFAULT_MAYBE_YES) 7461 || (msg.arg1 == MotionEvent.ACTION_MOVE 7462 && mPreventDefault == PREVENT_DEFAULT_NO_FROM_TOUCH_DOWN)) { 7463 cancelWebCoreTouchEvent( 7464 viewToContentX(mLastTouchX + mScrollX), 7465 viewToContentY(mLastTouchY + mScrollY), 7466 true); 7467 } 7468 break; 7469 } 7470 case SCROLL_SELECT_TEXT: { 7471 if (mAutoScrollX == 0 && mAutoScrollY == 0) { 7472 mSentAutoScrollMessage = false; 7473 break; 7474 } 7475 if (mScrollingLayer == 0) { 7476 pinScrollBy(mAutoScrollX, mAutoScrollY, true, 0); 7477 } else { 7478 mScrollingLayerRect.left += mAutoScrollX; 7479 mScrollingLayerRect.top += mAutoScrollY; 7480 nativeScrollLayer(mScrollingLayer, 7481 mScrollingLayerRect.left, 7482 mScrollingLayerRect.top); 7483 invalidate(); 7484 } 7485 sendEmptyMessageDelayed( 7486 SCROLL_SELECT_TEXT, SELECT_SCROLL_INTERVAL); 7487 break; 7488 } 7489 case SWITCH_TO_SHORTPRESS: { 7490 mInitialHitTestResult = null; // set by updateSelection() 7491 if (mTouchMode == TOUCH_INIT_MODE) { 7492 if (!getSettings().supportTouchOnly() 7493 && mPreventDefault != PREVENT_DEFAULT_YES) { 7494 mTouchMode = TOUCH_SHORTPRESS_START_MODE; 7495 updateSelection(); 7496 } else { 7497 // set to TOUCH_SHORTPRESS_MODE so that it won't 7498 // trigger double tap any more 7499 mTouchMode = TOUCH_SHORTPRESS_MODE; 7500 } 7501 } else if (mTouchMode == TOUCH_DOUBLE_TAP_MODE) { 7502 mTouchMode = TOUCH_DONE_MODE; 7503 } 7504 break; 7505 } 7506 case SWITCH_TO_LONGPRESS: { 7507 if (getSettings().supportTouchOnly()) { 7508 removeTouchHighlight(false); 7509 } 7510 if (inFullScreenMode() || mDeferTouchProcess) { 7511 TouchEventData ted = new TouchEventData(); 7512 ted.mAction = WebViewCore.ACTION_LONGPRESS; 7513 ted.mIds = new int[1]; 7514 ted.mIds[0] = 0; 7515 ted.mPoints = new Point[1]; 7516 ted.mPoints[0] = new Point(viewToContentX(mLastTouchX + mScrollX), 7517 viewToContentY(mLastTouchY + mScrollY)); 7518 // metaState for long press is tricky. Should it be the 7519 // state when the press started or when the press was 7520 // released? Or some intermediary key state? For 7521 // simplicity for now, we don't set it. 7522 ted.mMetaState = 0; 7523 ted.mReprocess = mDeferTouchProcess; 7524 ted.mNativeLayer = nativeScrollableLayer( 7525 ted.mPoints[0].x, ted.mPoints[0].y, 7526 ted.mNativeLayerRect, null); 7527 ted.mSequence = mTouchEventQueue.nextTouchSequence(); 7528 mWebViewCore.sendMessage(EventHub.TOUCH_EVENT, ted); 7529 } else if (mPreventDefault != PREVENT_DEFAULT_YES) { 7530 mTouchMode = TOUCH_DONE_MODE; 7531 performLongClick(); 7532 } 7533 break; 7534 } 7535 case RELEASE_SINGLE_TAP: { 7536 doShortPress(); 7537 break; 7538 } 7539 case SCROLL_TO_MSG_ID: { 7540 // arg1 = animate, arg2 = onlyIfImeIsShowing 7541 // obj = Point(x, y) 7542 if (msg.arg2 == 1) { 7543 // This scroll is intended to bring the textfield into 7544 // view, but is only necessary if the IME is showing 7545 InputMethodManager imm = InputMethodManager.peekInstance(); 7546 if (imm == null || !imm.isAcceptingText() 7547 || (!imm.isActive(WebView.this) && (!inEditingMode() 7548 || !imm.isActive(mWebTextView)))) { 7549 break; 7550 } 7551 } 7552 final Point p = (Point) msg.obj; 7553 if (msg.arg1 == 1) { 7554 spawnContentScrollTo(p.x, p.y); 7555 } else { 7556 setContentScrollTo(p.x, p.y); 7557 } 7558 break; 7559 } 7560 case UPDATE_ZOOM_RANGE: { 7561 WebViewCore.ViewState viewState = (WebViewCore.ViewState) msg.obj; 7562 // mScrollX contains the new minPrefWidth 7563 mZoomManager.updateZoomRange(viewState, getViewWidth(), viewState.mScrollX); 7564 break; 7565 } 7566 case REPLACE_BASE_CONTENT: { 7567 nativeReplaceBaseContent(msg.arg1); 7568 break; 7569 } 7570 case NEW_PICTURE_MSG_ID: { 7571 // called for new content 7572 final WebViewCore.DrawData draw = (WebViewCore.DrawData) msg.obj; 7573 setBaseLayer(draw.mBaseLayer, draw.mInvalRegion, 7574 getSettings().getShowVisualIndicator()); 7575 final Point viewSize = draw.mViewSize; 7576 WebViewCore.ViewState viewState = draw.mViewState; 7577 boolean isPictureAfterFirstLayout = viewState != null; 7578 if (isPictureAfterFirstLayout) { 7579 // Reset the last sent data here since dealing with new page. 7580 mLastWidthSent = 0; 7581 mZoomManager.onFirstLayout(draw); 7582 if (!mDrawHistory) { 7583 // Do not send the scroll event for this particular 7584 // scroll message. Note that a scroll event may 7585 // still be fired if the user scrolls before the 7586 // message can be handled. 7587 mSendScrollEvent = false; 7588 setContentScrollTo(viewState.mScrollX, viewState.mScrollY); 7589 mSendScrollEvent = true; 7590 7591 // As we are on a new page, remove the WebTextView. This 7592 // is necessary for page loads driven by webkit, and in 7593 // particular when the user was on a password field, so 7594 // the WebTextView was visible. 7595 clearTextEntry(); 7596 } 7597 } 7598 7599 // We update the layout (i.e. request a layout from the 7600 // view system) if the last view size that we sent to 7601 // WebCore matches the view size of the picture we just 7602 // received in the fixed dimension. 7603 final boolean updateLayout = viewSize.x == mLastWidthSent 7604 && viewSize.y == mLastHeightSent; 7605 // Don't send scroll event for picture coming from webkit, 7606 // since the new picture may cause a scroll event to override 7607 // the saved history scroll position. 7608 mSendScrollEvent = false; 7609 recordNewContentSize(draw.mContentSize.x, 7610 draw.mContentSize.y, updateLayout); 7611 mSendScrollEvent = true; 7612 if (DebugFlags.WEB_VIEW) { 7613 Rect b = draw.mInvalRegion.getBounds(); 7614 Log.v(LOGTAG, "NEW_PICTURE_MSG_ID {" + 7615 b.left+","+b.top+","+b.right+","+b.bottom+"}"); 7616 } 7617 invalidateContentRect(draw.mInvalRegion.getBounds()); 7618 7619 if (mPictureListener != null) { 7620 mPictureListener.onNewPicture(WebView.this, capturePicture()); 7621 } 7622 7623 // update the zoom information based on the new picture 7624 mZoomManager.onNewPicture(draw); 7625 7626 if (draw.mFocusSizeChanged && inEditingMode()) { 7627 mFocusSizeChanged = true; 7628 } 7629 if (isPictureAfterFirstLayout) { 7630 mViewManager.postReadyToDrawAll(); 7631 } 7632 break; 7633 } 7634 case WEBCORE_INITIALIZED_MSG_ID: 7635 // nativeCreate sets mNativeClass to a non-zero value 7636 nativeCreate(msg.arg1); 7637 break; 7638 case UPDATE_TEXTFIELD_TEXT_MSG_ID: 7639 // Make sure that the textfield is currently focused 7640 // and representing the same node as the pointer. 7641 if (inEditingMode() && 7642 mWebTextView.isSameTextField(msg.arg1)) { 7643 if (msg.getData().getBoolean("password")) { 7644 Spannable text = (Spannable) mWebTextView.getText(); 7645 int start = Selection.getSelectionStart(text); 7646 int end = Selection.getSelectionEnd(text); 7647 mWebTextView.setInPassword(true); 7648 // Restore the selection, which may have been 7649 // ruined by setInPassword. 7650 Spannable pword = 7651 (Spannable) mWebTextView.getText(); 7652 Selection.setSelection(pword, start, end); 7653 // If the text entry has created more events, ignore 7654 // this one. 7655 } else if (msg.arg2 == mTextGeneration) { 7656 String text = (String) msg.obj; 7657 if (null == text) { 7658 text = ""; 7659 } 7660 mWebTextView.setTextAndKeepSelection(text); 7661 } 7662 } 7663 break; 7664 case REQUEST_KEYBOARD_WITH_SELECTION_MSG_ID: 7665 displaySoftKeyboard(true); 7666 // fall through to UPDATE_TEXT_SELECTION_MSG_ID 7667 case UPDATE_TEXT_SELECTION_MSG_ID: 7668 updateTextSelectionFromMessage(msg.arg1, msg.arg2, 7669 (WebViewCore.TextSelectionData) msg.obj); 7670 break; 7671 case FORM_DID_BLUR: 7672 if (inEditingMode() 7673 && mWebTextView.isSameTextField(msg.arg1)) { 7674 hideSoftKeyboard(); 7675 } 7676 break; 7677 case RETURN_LABEL: 7678 if (inEditingMode() 7679 && mWebTextView.isSameTextField(msg.arg1)) { 7680 mWebTextView.setHint((String) msg.obj); 7681 InputMethodManager imm 7682 = InputMethodManager.peekInstance(); 7683 // The hint is propagated to the IME in 7684 // onCreateInputConnection. If the IME is already 7685 // active, restart it so that its hint text is updated. 7686 if (imm != null && imm.isActive(mWebTextView)) { 7687 imm.restartInput(mWebTextView); 7688 } 7689 } 7690 break; 7691 case UNHANDLED_NAV_KEY: 7692 navHandledKey(msg.arg1, 1, false, 0); 7693 break; 7694 case UPDATE_TEXT_ENTRY_MSG_ID: 7695 // this is sent after finishing resize in WebViewCore. Make 7696 // sure the text edit box is still on the screen. 7697 if (inEditingMode() && nativeCursorIsTextInput()) { 7698 rebuildWebTextView(); 7699 } 7700 break; 7701 case CLEAR_TEXT_ENTRY: 7702 clearTextEntry(); 7703 break; 7704 case INVAL_RECT_MSG_ID: { 7705 Rect r = (Rect)msg.obj; 7706 if (r == null) { 7707 invalidate(); 7708 } else { 7709 // we need to scale r from content into view coords, 7710 // which viewInvalidate() does for us 7711 viewInvalidate(r.left, r.top, r.right, r.bottom); 7712 } 7713 break; 7714 } 7715 case REQUEST_FORM_DATA: 7716 AutoCompleteAdapter adapter = (AutoCompleteAdapter) msg.obj; 7717 if (mWebTextView.isSameTextField(msg.arg1)) { 7718 mWebTextView.setAdapterCustom(adapter); 7719 } 7720 break; 7721 case RESUME_WEBCORE_PRIORITY: 7722 WebViewCore.resumePriority(); 7723 WebViewCore.resumeUpdatePicture(mWebViewCore); 7724 break; 7725 7726 case LONG_PRESS_CENTER: 7727 // as this is shared by keydown and trackballdown, reset all 7728 // the states 7729 mGotCenterDown = false; 7730 mTrackballDown = false; 7731 performLongClick(); 7732 break; 7733 7734 case WEBCORE_NEED_TOUCH_EVENTS: 7735 mForwardTouchEvents = (msg.arg1 != 0); 7736 break; 7737 7738 case PREVENT_TOUCH_ID: 7739 if (inFullScreenMode()) { 7740 break; 7741 } 7742 TouchEventData ted = (TouchEventData) msg.obj; 7743 7744 // WebCore is responding to us; remove pending timeout. 7745 // It will be re-posted when needed. 7746 removeMessages(PREVENT_DEFAULT_TIMEOUT); 7747 7748 mTouchEventQueue.enqueueTouchEvent(ted); 7749 break; 7750 7751 case REQUEST_KEYBOARD: 7752 if (msg.arg1 == 0) { 7753 hideSoftKeyboard(); 7754 } else { 7755 displaySoftKeyboard(false); 7756 } 7757 break; 7758 7759 case FIND_AGAIN: 7760 // Ignore if find has been dismissed. 7761 if (mFindIsUp && mFindCallback != null) { 7762 mFindCallback.findAll(); 7763 } 7764 break; 7765 7766 case DRAG_HELD_MOTIONLESS: 7767 mHeldMotionless = MOTIONLESS_TRUE; 7768 invalidate(); 7769 // fall through to keep scrollbars awake 7770 7771 case AWAKEN_SCROLL_BARS: 7772 if (mTouchMode == TOUCH_DRAG_MODE 7773 && mHeldMotionless == MOTIONLESS_TRUE) { 7774 awakenScrollBars(ViewConfiguration 7775 .getScrollDefaultDelay(), false); 7776 mPrivateHandler.sendMessageDelayed(mPrivateHandler 7777 .obtainMessage(AWAKEN_SCROLL_BARS), 7778 ViewConfiguration.getScrollDefaultDelay()); 7779 } 7780 break; 7781 7782 case DO_MOTION_UP: 7783 doMotionUp(msg.arg1, msg.arg2); 7784 break; 7785 7786 case SCREEN_ON: 7787 setKeepScreenOn(msg.arg1 == 1); 7788 break; 7789 7790 case SHOW_FULLSCREEN: { 7791 View view = (View) msg.obj; 7792 int npp = msg.arg1; 7793 7794 if (inFullScreenMode()) { 7795 Log.w(LOGTAG, "Should not have another full screen."); 7796 dismissFullScreenMode(); 7797 } 7798 mFullScreenHolder = new PluginFullScreenHolder(WebView.this, npp); 7799 mFullScreenHolder.setContentView(view); 7800 mFullScreenHolder.setCancelable(false); 7801 mFullScreenHolder.setCanceledOnTouchOutside(false); 7802 mFullScreenHolder.show(); 7803 7804 break; 7805 } 7806 case HIDE_FULLSCREEN: 7807 dismissFullScreenMode(); 7808 break; 7809 7810 case DOM_FOCUS_CHANGED: 7811 if (inEditingMode()) { 7812 nativeClearCursor(); 7813 rebuildWebTextView(); 7814 } 7815 break; 7816 7817 case SHOW_RECT_MSG_ID: { 7818 WebViewCore.ShowRectData data = (WebViewCore.ShowRectData) msg.obj; 7819 int x = mScrollX; 7820 int left = contentToViewX(data.mLeft); 7821 int width = contentToViewDimension(data.mWidth); 7822 int maxWidth = contentToViewDimension(data.mContentWidth); 7823 int viewWidth = getViewWidth(); 7824 if (width < viewWidth) { 7825 // center align 7826 x += left + width / 2 - mScrollX - viewWidth / 2; 7827 } else { 7828 x += (int) (left + data.mXPercentInDoc * width 7829 - mScrollX - data.mXPercentInView * viewWidth); 7830 } 7831 if (DebugFlags.WEB_VIEW) { 7832 Log.v(LOGTAG, "showRectMsg=(left=" + left + ",width=" + 7833 width + ",maxWidth=" + maxWidth + 7834 ",viewWidth=" + viewWidth + ",x=" 7835 + x + ",xPercentInDoc=" + data.mXPercentInDoc + 7836 ",xPercentInView=" + data.mXPercentInView+ ")"); 7837 } 7838 // use the passing content width to cap x as the current 7839 // mContentWidth may not be updated yet 7840 x = Math.max(0, 7841 (Math.min(maxWidth, x + viewWidth)) - viewWidth); 7842 int top = contentToViewY(data.mTop); 7843 int height = contentToViewDimension(data.mHeight); 7844 int maxHeight = contentToViewDimension(data.mContentHeight); 7845 int viewHeight = getViewHeight(); 7846 int y = (int) (top + data.mYPercentInDoc * height - 7847 data.mYPercentInView * viewHeight); 7848 if (DebugFlags.WEB_VIEW) { 7849 Log.v(LOGTAG, "showRectMsg=(top=" + top + ",height=" + 7850 height + ",maxHeight=" + maxHeight + 7851 ",viewHeight=" + viewHeight + ",y=" 7852 + y + ",yPercentInDoc=" + data.mYPercentInDoc + 7853 ",yPercentInView=" + data.mYPercentInView+ ")"); 7854 } 7855 // use the passing content height to cap y as the current 7856 // mContentHeight may not be updated yet 7857 y = Math.max(0, 7858 (Math.min(maxHeight, y + viewHeight) - viewHeight)); 7859 // We need to take into account the visible title height 7860 // when scrolling since y is an absolute view position. 7861 y = Math.max(0, y - getVisibleTitleHeight()); 7862 scrollTo(x, y); 7863 } 7864 break; 7865 7866 case CENTER_FIT_RECT: 7867 centerFitRect((Rect)msg.obj); 7868 break; 7869 7870 case SET_SCROLLBAR_MODES: 7871 mHorizontalScrollBarMode = msg.arg1; 7872 mVerticalScrollBarMode = msg.arg2; 7873 break; 7874 7875 case SELECTION_STRING_CHANGED: 7876 if (mAccessibilityInjector != null) { 7877 String selectionString = (String) msg.obj; 7878 mAccessibilityInjector.onSelectionStringChange(selectionString); 7879 } 7880 break; 7881 7882 case SET_TOUCH_HIGHLIGHT_RECTS: 7883 invalidate(mTouchHighlightRegion.getBounds()); 7884 mTouchHighlightRegion.setEmpty(); 7885 if (msg.obj != null) { 7886 ArrayList<Rect> rects = (ArrayList<Rect>) msg.obj; 7887 for (Rect rect : rects) { 7888 Rect viewRect = contentToViewRect(rect); 7889 // some sites, like stories in nytimes.com, set 7890 // mouse event handler in the top div. It is not 7891 // user friendly to highlight the div if it covers 7892 // more than half of the screen. 7893 if (viewRect.width() < getWidth() >> 1 7894 || viewRect.height() < getHeight() >> 1) { 7895 mTouchHighlightRegion.union(viewRect); 7896 invalidate(viewRect); 7897 } else { 7898 Log.w(LOGTAG, "Skip the huge selection rect:" 7899 + viewRect); 7900 } 7901 } 7902 } 7903 break; 7904 7905 case SAVE_WEBARCHIVE_FINISHED: 7906 SaveWebArchiveMessage saveMessage = (SaveWebArchiveMessage)msg.obj; 7907 if (saveMessage.mCallback != null) { 7908 saveMessage.mCallback.onReceiveValue(saveMessage.mResultFile); 7909 } 7910 break; 7911 7912 case SET_AUTOFILLABLE: 7913 mAutoFillData = (WebViewCore.AutoFillData) msg.obj; 7914 if (mWebTextView != null) { 7915 mWebTextView.setAutoFillable(mAutoFillData.getQueryId()); 7916 rebuildWebTextView(); 7917 } 7918 break; 7919 7920 case AUTOFILL_COMPLETE: 7921 if (mWebTextView != null) { 7922 // Clear the WebTextView adapter when AutoFill finishes 7923 // so that the drop down gets cleared. 7924 mWebTextView.setAdapterCustom(null); 7925 } 7926 break; 7927 7928 case SELECT_AT: 7929 nativeSelectAt(msg.arg1, msg.arg2); 7930 break; 7931 7932 default: 7933 super.handleMessage(msg); 7934 break; 7935 } 7936 } 7937 } 7938 7939 /** 7940 * Used when receiving messages for REQUEST_KEYBOARD_WITH_SELECTION_MSG_ID 7941 * and UPDATE_TEXT_SELECTION_MSG_ID. Update the selection of WebTextView. 7942 */ 7943 private void updateTextSelectionFromMessage(int nodePointer, 7944 int textGeneration, WebViewCore.TextSelectionData data) { 7945 if (inEditingMode() 7946 && mWebTextView.isSameTextField(nodePointer) 7947 && textGeneration == mTextGeneration) { 7948 mWebTextView.setSelectionFromWebKit(data.mStart, data.mEnd); 7949 } 7950 } 7951 7952 // Class used to use a dropdown for a <select> element 7953 private class InvokeListBox implements Runnable { 7954 // Whether the listbox allows multiple selection. 7955 private boolean mMultiple; 7956 // Passed in to a list with multiple selection to tell 7957 // which items are selected. 7958 private int[] mSelectedArray; 7959 // Passed in to a list with single selection to tell 7960 // where the initial selection is. 7961 private int mSelection; 7962 7963 private Container[] mContainers; 7964 7965 // Need these to provide stable ids to my ArrayAdapter, 7966 // which normally does not have stable ids. (Bug 1250098) 7967 private class Container extends Object { 7968 /** 7969 * Possible values for mEnabled. Keep in sync with OptionStatus in 7970 * WebViewCore.cpp 7971 */ 7972 final static int OPTGROUP = -1; 7973 final static int OPTION_DISABLED = 0; 7974 final static int OPTION_ENABLED = 1; 7975 7976 String mString; 7977 int mEnabled; 7978 int mId; 7979 7980 @Override 7981 public String toString() { 7982 return mString; 7983 } 7984 } 7985 7986 /** 7987 * Subclass ArrayAdapter so we can disable OptionGroupLabels, 7988 * and allow filtering. 7989 */ 7990 private class MyArrayListAdapter extends ArrayAdapter<Container> { 7991 public MyArrayListAdapter() { 7992 super(mContext, 7993 mMultiple ? com.android.internal.R.layout.select_dialog_multichoice : 7994 com.android.internal.R.layout.webview_select_singlechoice, 7995 mContainers); 7996 } 7997 7998 @Override 7999 public View getView(int position, View convertView, 8000 ViewGroup parent) { 8001 // Always pass in null so that we will get a new CheckedTextView 8002 // Otherwise, an item which was previously used as an <optgroup> 8003 // element (i.e. has no check), could get used as an <option> 8004 // element, which needs a checkbox/radio, but it would not have 8005 // one. 8006 convertView = super.getView(position, null, parent); 8007 Container c = item(position); 8008 if (c != null && Container.OPTION_ENABLED != c.mEnabled) { 8009 // ListView does not draw dividers between disabled and 8010 // enabled elements. Use a LinearLayout to provide dividers 8011 LinearLayout layout = new LinearLayout(mContext); 8012 layout.setOrientation(LinearLayout.VERTICAL); 8013 if (position > 0) { 8014 View dividerTop = new View(mContext); 8015 dividerTop.setBackgroundResource( 8016 android.R.drawable.divider_horizontal_bright); 8017 layout.addView(dividerTop); 8018 } 8019 8020 if (Container.OPTGROUP == c.mEnabled) { 8021 // Currently select_dialog_multichoice uses CheckedTextViews. 8022 // If that changes, the class cast will no longer be valid. 8023 if (mMultiple) { 8024 Assert.assertTrue(convertView instanceof CheckedTextView); 8025 ((CheckedTextView) convertView).setCheckMarkDrawable(null); 8026 } 8027 } else { 8028 // c.mEnabled == Container.OPTION_DISABLED 8029 // Draw the disabled element in a disabled state. 8030 convertView.setEnabled(false); 8031 } 8032 8033 layout.addView(convertView); 8034 if (position < getCount() - 1) { 8035 View dividerBottom = new View(mContext); 8036 dividerBottom.setBackgroundResource( 8037 android.R.drawable.divider_horizontal_bright); 8038 layout.addView(dividerBottom); 8039 } 8040 return layout; 8041 } 8042 return convertView; 8043 } 8044 8045 @Override 8046 public boolean hasStableIds() { 8047 // AdapterView's onChanged method uses this to determine whether 8048 // to restore the old state. Return false so that the old (out 8049 // of date) state does not replace the new, valid state. 8050 return false; 8051 } 8052 8053 private Container item(int position) { 8054 if (position < 0 || position >= getCount()) { 8055 return null; 8056 } 8057 return (Container) getItem(position); 8058 } 8059 8060 @Override 8061 public long getItemId(int position) { 8062 Container item = item(position); 8063 if (item == null) { 8064 return -1; 8065 } 8066 return item.mId; 8067 } 8068 8069 @Override 8070 public boolean areAllItemsEnabled() { 8071 return false; 8072 } 8073 8074 @Override 8075 public boolean isEnabled(int position) { 8076 Container item = item(position); 8077 if (item == null) { 8078 return false; 8079 } 8080 return Container.OPTION_ENABLED == item.mEnabled; 8081 } 8082 } 8083 8084 private InvokeListBox(String[] array, int[] enabled, int[] selected) { 8085 mMultiple = true; 8086 mSelectedArray = selected; 8087 8088 int length = array.length; 8089 mContainers = new Container[length]; 8090 for (int i = 0; i < length; i++) { 8091 mContainers[i] = new Container(); 8092 mContainers[i].mString = array[i]; 8093 mContainers[i].mEnabled = enabled[i]; 8094 mContainers[i].mId = i; 8095 } 8096 } 8097 8098 private InvokeListBox(String[] array, int[] enabled, int selection) { 8099 mSelection = selection; 8100 mMultiple = false; 8101 8102 int length = array.length; 8103 mContainers = new Container[length]; 8104 for (int i = 0; i < length; i++) { 8105 mContainers[i] = new Container(); 8106 mContainers[i].mString = array[i]; 8107 mContainers[i].mEnabled = enabled[i]; 8108 mContainers[i].mId = i; 8109 } 8110 } 8111 8112 /* 8113 * Whenever the data set changes due to filtering, this class ensures 8114 * that the checked item remains checked. 8115 */ 8116 private class SingleDataSetObserver extends DataSetObserver { 8117 private long mCheckedId; 8118 private ListView mListView; 8119 private Adapter mAdapter; 8120 8121 /* 8122 * Create a new observer. 8123 * @param id The ID of the item to keep checked. 8124 * @param l ListView for getting and clearing the checked states 8125 * @param a Adapter for getting the IDs 8126 */ 8127 public SingleDataSetObserver(long id, ListView l, Adapter a) { 8128 mCheckedId = id; 8129 mListView = l; 8130 mAdapter = a; 8131 } 8132 8133 @Override 8134 public void onChanged() { 8135 // The filter may have changed which item is checked. Find the 8136 // item that the ListView thinks is checked. 8137 int position = mListView.getCheckedItemPosition(); 8138 long id = mAdapter.getItemId(position); 8139 if (mCheckedId != id) { 8140 // Clear the ListView's idea of the checked item, since 8141 // it is incorrect 8142 mListView.clearChoices(); 8143 // Search for mCheckedId. If it is in the filtered list, 8144 // mark it as checked 8145 int count = mAdapter.getCount(); 8146 for (int i = 0; i < count; i++) { 8147 if (mAdapter.getItemId(i) == mCheckedId) { 8148 mListView.setItemChecked(i, true); 8149 break; 8150 } 8151 } 8152 } 8153 } 8154 } 8155 8156 public void run() { 8157 final ListView listView = (ListView) LayoutInflater.from(mContext) 8158 .inflate(com.android.internal.R.layout.select_dialog, null); 8159 final MyArrayListAdapter adapter = new MyArrayListAdapter(); 8160 AlertDialog.Builder b = new AlertDialog.Builder(mContext) 8161 .setView(listView).setCancelable(true) 8162 .setInverseBackgroundForced(true); 8163 8164 if (mMultiple) { 8165 b.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { 8166 public void onClick(DialogInterface dialog, int which) { 8167 mWebViewCore.sendMessage( 8168 EventHub.LISTBOX_CHOICES, 8169 adapter.getCount(), 0, 8170 listView.getCheckedItemPositions()); 8171 }}); 8172 b.setNegativeButton(android.R.string.cancel, 8173 new DialogInterface.OnClickListener() { 8174 public void onClick(DialogInterface dialog, int which) { 8175 mWebViewCore.sendMessage( 8176 EventHub.SINGLE_LISTBOX_CHOICE, -2, 0); 8177 }}); 8178 } 8179 mListBoxDialog = b.create(); 8180 listView.setAdapter(adapter); 8181 listView.setFocusableInTouchMode(true); 8182 // There is a bug (1250103) where the checks in a ListView with 8183 // multiple items selected are associated with the positions, not 8184 // the ids, so the items do not properly retain their checks when 8185 // filtered. Do not allow filtering on multiple lists until 8186 // that bug is fixed. 8187 8188 listView.setTextFilterEnabled(!mMultiple); 8189 if (mMultiple) { 8190 listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE); 8191 int length = mSelectedArray.length; 8192 for (int i = 0; i < length; i++) { 8193 listView.setItemChecked(mSelectedArray[i], true); 8194 } 8195 } else { 8196 listView.setOnItemClickListener(new OnItemClickListener() { 8197 public void onItemClick(AdapterView<?> parent, View v, 8198 int position, long id) { 8199 // Rather than sending the message right away, send it 8200 // after the page regains focus. 8201 mListBoxMessage = Message.obtain(null, 8202 EventHub.SINGLE_LISTBOX_CHOICE, (int) id, 0); 8203 mListBoxDialog.dismiss(); 8204 mListBoxDialog = null; 8205 } 8206 }); 8207 if (mSelection != -1) { 8208 listView.setSelection(mSelection); 8209 listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE); 8210 listView.setItemChecked(mSelection, true); 8211 DataSetObserver observer = new SingleDataSetObserver( 8212 adapter.getItemId(mSelection), listView, adapter); 8213 adapter.registerDataSetObserver(observer); 8214 } 8215 } 8216 mListBoxDialog.setOnCancelListener(new DialogInterface.OnCancelListener() { 8217 public void onCancel(DialogInterface dialog) { 8218 mWebViewCore.sendMessage( 8219 EventHub.SINGLE_LISTBOX_CHOICE, -2, 0); 8220 mListBoxDialog = null; 8221 } 8222 }); 8223 mListBoxDialog.show(); 8224 } 8225 } 8226 8227 private Message mListBoxMessage; 8228 8229 /* 8230 * Request a dropdown menu for a listbox with multiple selection. 8231 * 8232 * @param array Labels for the listbox. 8233 * @param enabledArray State for each element in the list. See static 8234 * integers in Container class. 8235 * @param selectedArray Which positions are initally selected. 8236 */ 8237 void requestListBox(String[] array, int[] enabledArray, int[] 8238 selectedArray) { 8239 mPrivateHandler.post( 8240 new InvokeListBox(array, enabledArray, selectedArray)); 8241 } 8242 8243 /* 8244 * Request a dropdown menu for a listbox with single selection or a single 8245 * <select> element. 8246 * 8247 * @param array Labels for the listbox. 8248 * @param enabledArray State for each element in the list. See static 8249 * integers in Container class. 8250 * @param selection Which position is initally selected. 8251 */ 8252 void requestListBox(String[] array, int[] enabledArray, int selection) { 8253 mPrivateHandler.post( 8254 new InvokeListBox(array, enabledArray, selection)); 8255 } 8256 8257 // called by JNI 8258 private void sendMoveFocus(int frame, int node) { 8259 mWebViewCore.sendMessage(EventHub.SET_MOVE_FOCUS, 8260 new WebViewCore.CursorData(frame, node, 0, 0)); 8261 } 8262 8263 // called by JNI 8264 private void sendMoveMouse(int frame, int node, int x, int y) { 8265 mWebViewCore.sendMessage(EventHub.SET_MOVE_MOUSE, 8266 new WebViewCore.CursorData(frame, node, x, y)); 8267 } 8268 8269 /* 8270 * Send a mouse move event to the webcore thread. 8271 * 8272 * @param removeFocus Pass true to remove the WebTextView, if present. 8273 * @param stopPaintingCaret Stop drawing the blinking caret if true. 8274 * called by JNI 8275 */ 8276 @SuppressWarnings("unused") 8277 private void sendMoveMouseIfLatest(boolean removeFocus, boolean stopPaintingCaret) { 8278 if (removeFocus) { 8279 clearTextEntry(); 8280 } 8281 mWebViewCore.sendMessage(EventHub.SET_MOVE_MOUSE_IF_LATEST, 8282 stopPaintingCaret ? 1 : 0, 0, 8283 cursorData()); 8284 } 8285 8286 /** 8287 * Called by JNI to send a message to the webcore thread that the user 8288 * touched the webpage. 8289 * @param touchGeneration Generation number of the touch, to ignore touches 8290 * after a new one has been generated. 8291 * @param frame Pointer to the frame holding the node that was touched. 8292 * @param node Pointer to the node touched. 8293 * @param x x-position of the touch. 8294 * @param y y-position of the touch. 8295 */ 8296 private void sendMotionUp(int touchGeneration, 8297 int frame, int node, int x, int y) { 8298 WebViewCore.TouchUpData touchUpData = new WebViewCore.TouchUpData(); 8299 touchUpData.mMoveGeneration = touchGeneration; 8300 touchUpData.mFrame = frame; 8301 touchUpData.mNode = node; 8302 touchUpData.mX = x; 8303 touchUpData.mY = y; 8304 touchUpData.mNativeLayer = nativeScrollableLayer( 8305 x, y, touchUpData.mNativeLayerRect, null); 8306 mWebViewCore.sendMessage(EventHub.TOUCH_UP, touchUpData); 8307 } 8308 8309 8310 private int getScaledMaxXScroll() { 8311 int width; 8312 if (mHeightCanMeasure == false) { 8313 width = getViewWidth() / 4; 8314 } else { 8315 Rect visRect = new Rect(); 8316 calcOurVisibleRect(visRect); 8317 width = visRect.width() / 2; 8318 } 8319 // FIXME the divisor should be retrieved from somewhere 8320 return viewToContentX(width); 8321 } 8322 8323 private int getScaledMaxYScroll() { 8324 int height; 8325 if (mHeightCanMeasure == false) { 8326 height = getViewHeight() / 4; 8327 } else { 8328 Rect visRect = new Rect(); 8329 calcOurVisibleRect(visRect); 8330 height = visRect.height() / 2; 8331 } 8332 // FIXME the divisor should be retrieved from somewhere 8333 // the closest thing today is hard-coded into ScrollView.java 8334 // (from ScrollView.java, line 363) int maxJump = height/2; 8335 return Math.round(height * mZoomManager.getInvScale()); 8336 } 8337 8338 /** 8339 * Called by JNI to invalidate view 8340 */ 8341 private void viewInvalidate() { 8342 invalidate(); 8343 } 8344 8345 /** 8346 * Pass the key directly to the page. This assumes that 8347 * nativePageShouldHandleShiftAndArrows() returned true. 8348 */ 8349 private void letPageHandleNavKey(int keyCode, long time, boolean down, int metaState) { 8350 int keyEventAction; 8351 int eventHubAction; 8352 if (down) { 8353 keyEventAction = KeyEvent.ACTION_DOWN; 8354 eventHubAction = EventHub.KEY_DOWN; 8355 playSoundEffect(keyCodeToSoundsEffect(keyCode)); 8356 } else { 8357 keyEventAction = KeyEvent.ACTION_UP; 8358 eventHubAction = EventHub.KEY_UP; 8359 } 8360 8361 KeyEvent event = new KeyEvent(time, time, keyEventAction, keyCode, 8362 1, (metaState & KeyEvent.META_SHIFT_ON) 8363 | (metaState & KeyEvent.META_ALT_ON) 8364 | (metaState & KeyEvent.META_SYM_ON) 8365 , KeyCharacterMap.VIRTUAL_KEYBOARD, 0, 0); 8366 mWebViewCore.sendMessage(eventHubAction, event); 8367 } 8368 8369 // return true if the key was handled 8370 private boolean navHandledKey(int keyCode, int count, boolean noScroll, 8371 long time) { 8372 if (mNativeClass == 0) { 8373 return false; 8374 } 8375 mInitialHitTestResult = null; 8376 mLastCursorTime = time; 8377 mLastCursorBounds = nativeGetCursorRingBounds(); 8378 boolean keyHandled 8379 = nativeMoveCursor(keyCode, count, noScroll) == false; 8380 if (DebugFlags.WEB_VIEW) { 8381 Log.v(LOGTAG, "navHandledKey mLastCursorBounds=" + mLastCursorBounds 8382 + " mLastCursorTime=" + mLastCursorTime 8383 + " handled=" + keyHandled); 8384 } 8385 if (keyHandled == false) { 8386 return keyHandled; 8387 } 8388 Rect contentCursorRingBounds = nativeGetCursorRingBounds(); 8389 if (contentCursorRingBounds.isEmpty()) return keyHandled; 8390 Rect viewCursorRingBounds = contentToViewRect(contentCursorRingBounds); 8391 // set last touch so that context menu related functions will work 8392 mLastTouchX = (viewCursorRingBounds.left + viewCursorRingBounds.right) / 2; 8393 mLastTouchY = (viewCursorRingBounds.top + viewCursorRingBounds.bottom) / 2; 8394 if (mHeightCanMeasure == false) { 8395 return keyHandled; 8396 } 8397 Rect visRect = new Rect(); 8398 calcOurVisibleRect(visRect); 8399 Rect outset = new Rect(visRect); 8400 int maxXScroll = visRect.width() / 2; 8401 int maxYScroll = visRect.height() / 2; 8402 outset.inset(-maxXScroll, -maxYScroll); 8403 if (Rect.intersects(outset, viewCursorRingBounds) == false) { 8404 return keyHandled; 8405 } 8406 // FIXME: Necessary because ScrollView/ListView do not scroll left/right 8407 int maxH = Math.min(viewCursorRingBounds.right - visRect.right, 8408 maxXScroll); 8409 if (maxH > 0) { 8410 pinScrollBy(maxH, 0, true, 0); 8411 } else { 8412 maxH = Math.max(viewCursorRingBounds.left - visRect.left, 8413 -maxXScroll); 8414 if (maxH < 0) { 8415 pinScrollBy(maxH, 0, true, 0); 8416 } 8417 } 8418 if (mLastCursorBounds.isEmpty()) return keyHandled; 8419 if (mLastCursorBounds.equals(contentCursorRingBounds)) { 8420 return keyHandled; 8421 } 8422 if (DebugFlags.WEB_VIEW) { 8423 Log.v(LOGTAG, "navHandledKey contentCursorRingBounds=" 8424 + contentCursorRingBounds); 8425 } 8426 requestRectangleOnScreen(viewCursorRingBounds); 8427 return keyHandled; 8428 } 8429 8430 /** 8431 * @return Whether accessibility script has been injected. 8432 */ 8433 private boolean accessibilityScriptInjected() { 8434 // TODO: Maybe the injected script should announce its presence in 8435 // the page meta-tag so the nativePageShouldHandleShiftAndArrows 8436 // will check that as one of the conditions it looks for 8437 return mAccessibilityScriptInjected; 8438 } 8439 8440 /** 8441 * Set the background color. It's white by default. Pass 8442 * zero to make the view transparent. 8443 * @param color the ARGB color described by Color.java 8444 */ 8445 @Override 8446 public void setBackgroundColor(int color) { 8447 mBackgroundColor = color; 8448 mWebViewCore.sendMessage(EventHub.SET_BACKGROUND_COLOR, color); 8449 } 8450 8451 /** 8452 * @deprecated This method is now obsolete. 8453 */ 8454 @Deprecated 8455 public void debugDump() { 8456 nativeDebugDump(); 8457 mWebViewCore.sendMessage(EventHub.DUMP_NAVTREE); 8458 } 8459 8460 /** 8461 * Draw the HTML page into the specified canvas. This call ignores any 8462 * view-specific zoom, scroll offset, or other changes. It does not draw 8463 * any view-specific chrome, such as progress or URL bars. 8464 * 8465 * @hide only needs to be accessible to Browser and testing 8466 */ 8467 public void drawPage(Canvas canvas) { 8468 nativeDraw(canvas, 0, 0, false); 8469 } 8470 8471 /** 8472 * Enable expanded tiles bound for smoother scrolling. 8473 * 8474 * @hide only used by the Browser 8475 */ 8476 public void setExpandedTileBounds(boolean enabled) { 8477 nativeSetExpandedTileBounds(enabled); 8478 } 8479 8480 /** 8481 * Set the time to wait between passing touches to WebCore. See also the 8482 * TOUCH_SENT_INTERVAL member for further discussion. 8483 * 8484 * @hide This is only used by the DRT test application. 8485 */ 8486 public void setTouchInterval(int interval) { 8487 mCurrentTouchInterval = interval; 8488 } 8489 8490 /** 8491 * Update our cache with updatedText. 8492 * @param updatedText The new text to put in our cache. 8493 */ 8494 /* package */ void updateCachedTextfield(String updatedText) { 8495 // Also place our generation number so that when we look at the cache 8496 // we recognize that it is up to date. 8497 nativeUpdateCachedTextfield(updatedText, mTextGeneration); 8498 } 8499 8500 /*package*/ void autoFillForm(int autoFillQueryId) { 8501 mWebViewCore.sendMessage(EventHub.AUTOFILL_FORM, autoFillQueryId, /* unused */0); 8502 } 8503 8504 /* package */ ViewManager getViewManager() { 8505 return mViewManager; 8506 } 8507 8508 private native int nativeCacheHitFramePointer(); 8509 private native boolean nativeCacheHitIsPlugin(); 8510 private native Rect nativeCacheHitNodeBounds(); 8511 private native int nativeCacheHitNodePointer(); 8512 /* package */ native void nativeClearCursor(); 8513 private native void nativeCreate(int ptr); 8514 private native int nativeCursorFramePointer(); 8515 private native Rect nativeCursorNodeBounds(); 8516 private native int nativeCursorNodePointer(); 8517 private native boolean nativeCursorIntersects(Rect visibleRect); 8518 private native boolean nativeCursorIsAnchor(); 8519 private native boolean nativeCursorIsTextInput(); 8520 private native Point nativeCursorPosition(); 8521 private native String nativeCursorText(); 8522 /** 8523 * Returns true if the native cursor node says it wants to handle key events 8524 * (ala plugins). This can only be called if mNativeClass is non-zero! 8525 */ 8526 private native boolean nativeCursorWantsKeyEvents(); 8527 private native void nativeDebugDump(); 8528 private native void nativeDestroy(); 8529 8530 /** 8531 * Draw the picture set with a background color and extra. If 8532 * "splitIfNeeded" is true and the return value is not 0, the return value 8533 * MUST be passed to WebViewCore with SPLIT_PICTURE_SET message so that the 8534 * native allocation can be freed. 8535 */ 8536 private native int nativeDraw(Canvas canvas, int color, int extra, 8537 boolean splitIfNeeded); 8538 private native void nativeDumpDisplayTree(String urlOrNull); 8539 private native boolean nativeEvaluateLayersAnimations(); 8540 private native int nativeGetDrawGLFunction(Rect rect, Rect viewRect, 8541 float scale, int extras); 8542 private native void nativeUpdateDrawGLFunction(Rect rect, Rect viewRect); 8543 private native boolean nativeDrawGL(Rect rect, float scale, int extras); 8544 private native void nativeExtendSelection(int x, int y); 8545 private native int nativeFindAll(String findLower, String findUpper, 8546 boolean sameAsLastSearch); 8547 private native void nativeFindNext(boolean forward); 8548 /* package */ native int nativeFocusCandidateFramePointer(); 8549 /* package */ native boolean nativeFocusCandidateHasNextTextfield(); 8550 /* package */ native boolean nativeFocusCandidateIsPassword(); 8551 private native boolean nativeFocusCandidateIsRtlText(); 8552 private native boolean nativeFocusCandidateIsTextInput(); 8553 /* package */ native int nativeFocusCandidateMaxLength(); 8554 /* package */ native boolean nativeFocusCandidateIsAutoComplete(); 8555 /* package */ native String nativeFocusCandidateName(); 8556 private native Rect nativeFocusCandidateNodeBounds(); 8557 /** 8558 * @return A Rect with left, top, right, bottom set to the corresponding 8559 * padding values in the focus candidate, if it is a textfield/textarea with 8560 * a style. Otherwise return null. This is not actually a rectangle; Rect 8561 * is being used to pass four integers. 8562 */ 8563 private native Rect nativeFocusCandidatePaddingRect(); 8564 /* package */ native int nativeFocusCandidatePointer(); 8565 private native String nativeFocusCandidateText(); 8566 /* package */ native float nativeFocusCandidateTextSize(); 8567 /* package */ native int nativeFocusCandidateLineHeight(); 8568 /** 8569 * Returns an integer corresponding to WebView.cpp::type. 8570 * See WebTextView.setType() 8571 */ 8572 private native int nativeFocusCandidateType(); 8573 private native boolean nativeFocusIsPlugin(); 8574 private native Rect nativeFocusNodeBounds(); 8575 /* package */ native int nativeFocusNodePointer(); 8576 private native Rect nativeGetCursorRingBounds(); 8577 private native String nativeGetSelection(); 8578 private native boolean nativeHasCursorNode(); 8579 private native boolean nativeHasFocusNode(); 8580 private native void nativeHideCursor(); 8581 private native boolean nativeHitSelection(int x, int y); 8582 private native String nativeImageURI(int x, int y); 8583 private native void nativeInstrumentReport(); 8584 private native Rect nativeLayerBounds(int layer); 8585 /* package */ native boolean nativeMoveCursorToNextTextInput(); 8586 // return true if the page has been scrolled 8587 private native boolean nativeMotionUp(int x, int y, int slop); 8588 // returns false if it handled the key 8589 private native boolean nativeMoveCursor(int keyCode, int count, 8590 boolean noScroll); 8591 private native int nativeMoveGeneration(); 8592 private native void nativeMoveSelection(int x, int y); 8593 /** 8594 * @return true if the page should get the shift and arrow keys, rather 8595 * than select text/navigation. 8596 * 8597 * If the focus is a plugin, or if the focus and cursor match and are 8598 * a contentEditable element, then the page should handle these keys. 8599 */ 8600 private native boolean nativePageShouldHandleShiftAndArrows(); 8601 private native boolean nativePointInNavCache(int x, int y, int slop); 8602 // Like many other of our native methods, you must make sure that 8603 // mNativeClass is not null before calling this method. 8604 private native void nativeRecordButtons(boolean focused, 8605 boolean pressed, boolean invalidate); 8606 private native void nativeResetSelection(); 8607 private native Point nativeSelectableText(); 8608 private native void nativeSelectAll(); 8609 private native void nativeSelectBestAt(Rect rect); 8610 private native void nativeSelectAt(int x, int y); 8611 private native int nativeSelectionX(); 8612 private native int nativeSelectionY(); 8613 private native int nativeFindIndex(); 8614 private native void nativeSetExtendSelection(); 8615 private native void nativeSetFindIsEmpty(); 8616 private native void nativeSetFindIsUp(boolean isUp); 8617 private native void nativeSetHeightCanMeasure(boolean measure); 8618 private native void nativeSetBaseLayer(int layer, Region invalRegion, 8619 boolean showVisualIndicator); 8620 private native void nativeShowCursorTimed(); 8621 private native void nativeReplaceBaseContent(int content); 8622 private native void nativeCopyBaseContentToPicture(Picture pict); 8623 private native boolean nativeHasContent(); 8624 private native void nativeSetSelectionPointer(boolean set, 8625 float scale, int x, int y); 8626 private native boolean nativeStartSelection(int x, int y); 8627 private native void nativeStopGL(); 8628 private native Rect nativeSubtractLayers(Rect content); 8629 private native int nativeTextGeneration(); 8630 // Never call this version except by updateCachedTextfield(String) - 8631 // we always want to pass in our generation number. 8632 private native void nativeUpdateCachedTextfield(String updatedText, 8633 int generation); 8634 private native boolean nativeWordSelection(int x, int y); 8635 // return NO_LEFTEDGE means failure. 8636 static final int NO_LEFTEDGE = -1; 8637 native int nativeGetBlockLeftEdge(int x, int y, float scale); 8638 8639 private native void nativeSetExpandedTileBounds(boolean enabled); 8640 8641 // Returns a pointer to the scrollable LayerAndroid at the given point. 8642 private native int nativeScrollableLayer(int x, int y, Rect scrollRect, 8643 Rect scrollBounds); 8644 /** 8645 * Scroll the specified layer. 8646 * @param layer Id of the layer to scroll, as determined by nativeScrollableLayer. 8647 * @param newX Destination x position to which to scroll. 8648 * @param newY Destination y position to which to scroll. 8649 * @return True if the layer is successfully scrolled. 8650 */ 8651 private native boolean nativeScrollLayer(int layer, int newX, int newY); 8652} 8653