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