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