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