WebView.java revision e00e8a78374cdcf01a25bd6327d2b94944b2bc3f
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 destroyImpl(); 4025 } finally { 4026 super.finalize(); 4027 } 4028 } 4029 4030 @Override 4031 protected boolean drawChild(Canvas canvas, View child, long drawingTime) { 4032 if (child == mTitleBar) { 4033 // When drawing the title bar, move it horizontally to always show 4034 // at the top of the WebView. 4035 mTitleBar.offsetLeftAndRight(mScrollX - mTitleBar.getLeft()); 4036 int newTop = 0; 4037 if (mTitleGravity == Gravity.NO_GRAVITY) { 4038 newTop = Math.min(0, mScrollY); 4039 } else if (mTitleGravity == Gravity.TOP) { 4040 newTop = mScrollY; 4041 } 4042 mTitleBar.setBottom(newTop + mTitleBar.getHeight()); 4043 mTitleBar.setTop(newTop); 4044 } 4045 return super.drawChild(canvas, child, drawingTime); 4046 } 4047 4048 private void drawContent(Canvas canvas, boolean drawRings) { 4049 // Update the buttons in the picture, so when we draw the picture 4050 // to the screen, they are in the correct state. 4051 // Tell the native side if user is a) touching the screen, 4052 // b) pressing the trackball down, or c) pressing the enter key 4053 // If the cursor is on a button, we need to draw it in the pressed 4054 // state. 4055 // If mNativeClass is 0, we should not reach here, so we do not 4056 // need to check it again. 4057 nativeRecordButtons(hasFocus() && hasWindowFocus(), 4058 (mTouchMode == TOUCH_SHORTPRESS_START_MODE && !USE_WEBKIT_RINGS) 4059 || mTrackballDown || mGotCenterDown, false); 4060 drawCoreAndCursorRing(canvas, mBackgroundColor, 4061 mDrawCursorRing && drawRings); 4062 } 4063 4064 /** 4065 * Draw the background when beyond bounds 4066 * @param canvas Canvas to draw into 4067 */ 4068 private void drawOverScrollBackground(Canvas canvas) { 4069 if (mOverScrollBackground == null) { 4070 mOverScrollBackground = new Paint(); 4071 Bitmap bm = BitmapFactory.decodeResource( 4072 mContext.getResources(), 4073 com.android.internal.R.drawable.status_bar_background); 4074 mOverScrollBackground.setShader(new BitmapShader(bm, 4075 Shader.TileMode.REPEAT, Shader.TileMode.REPEAT)); 4076 mOverScrollBorder = new Paint(); 4077 mOverScrollBorder.setStyle(Paint.Style.STROKE); 4078 mOverScrollBorder.setStrokeWidth(0); 4079 mOverScrollBorder.setColor(0xffbbbbbb); 4080 } 4081 4082 int top = 0; 4083 int right = computeRealHorizontalScrollRange(); 4084 int bottom = top + computeRealVerticalScrollRange(); 4085 // first draw the background and anchor to the top of the view 4086 canvas.save(); 4087 canvas.translate(mScrollX, mScrollY); 4088 canvas.clipRect(-mScrollX, top - mScrollY, right - mScrollX, bottom 4089 - mScrollY, Region.Op.DIFFERENCE); 4090 canvas.drawPaint(mOverScrollBackground); 4091 canvas.restore(); 4092 // then draw the border 4093 canvas.drawRect(-1, top - 1, right, bottom, mOverScrollBorder); 4094 // next clip the region for the content 4095 canvas.clipRect(0, top, right, bottom); 4096 } 4097 4098 @Override 4099 protected void onDraw(Canvas canvas) { 4100 // if mNativeClass is 0, the WebView is either destroyed or not 4101 // initialized. In either case, just draw the background color and return 4102 if (mNativeClass == 0) { 4103 canvas.drawColor(mBackgroundColor); 4104 return; 4105 } 4106 4107 // if both mContentWidth and mContentHeight are 0, it means there is no 4108 // valid Picture passed to WebView yet. This can happen when WebView 4109 // just starts. Draw the background and return. 4110 if ((mContentWidth | mContentHeight) == 0 && mHistoryPicture == null) { 4111 canvas.drawColor(mBackgroundColor); 4112 return; 4113 } 4114 4115 if (canvas.isHardwareAccelerated()) { 4116 mZoomManager.setHardwareAccelerated(); 4117 } 4118 4119 int saveCount = canvas.save(); 4120 if (mInOverScrollMode && !getSettings() 4121 .getUseWebViewBackgroundForOverscrollBackground()) { 4122 drawOverScrollBackground(canvas); 4123 } 4124 if (mTitleBar != null) { 4125 canvas.translate(0, getTitleHeight()); 4126 } 4127 boolean drawJavaRings = !mTouchHighlightRegion.isEmpty() 4128 && (mTouchMode == TOUCH_INIT_MODE 4129 || mTouchMode == TOUCH_SHORTPRESS_START_MODE 4130 || mTouchMode == TOUCH_SHORTPRESS_MODE 4131 || mTouchMode == TOUCH_DONE_MODE); 4132 boolean drawNativeRings = !drawJavaRings; 4133 if (USE_WEBKIT_RINGS) { 4134 drawNativeRings = !drawJavaRings && !isInTouchMode(); 4135 } 4136 drawContent(canvas, drawNativeRings); 4137 canvas.restoreToCount(saveCount); 4138 4139 if (AUTO_REDRAW_HACK && mAutoRedraw) { 4140 invalidate(); 4141 } 4142 mWebViewCore.signalRepaintDone(); 4143 4144 if (mOverScrollGlow != null && mOverScrollGlow.drawEdgeGlows(canvas)) { 4145 invalidate(); 4146 } 4147 4148 // paint the highlight in the end 4149 if (drawJavaRings) { 4150 long delay = System.currentTimeMillis() - mTouchHighlightRequested; 4151 if (delay < ViewConfiguration.getTapTimeout()) { 4152 Rect r = mTouchHighlightRegion.getBounds(); 4153 postInvalidateDelayed(delay, r.left, r.top, r.right, r.bottom); 4154 } else { 4155 if (mTouchHightlightPaint == null) { 4156 mTouchHightlightPaint = new Paint(); 4157 mTouchHightlightPaint.setColor(HIGHLIGHT_COLOR); 4158 } 4159 RegionIterator iter = new RegionIterator(mTouchHighlightRegion); 4160 Rect r = new Rect(); 4161 while (iter.next(r)) { 4162 canvas.drawRect(r, mTouchHightlightPaint); 4163 } 4164 } 4165 } 4166 if (DEBUG_TOUCH_HIGHLIGHT) { 4167 if (getSettings().getNavDump()) { 4168 if ((mTouchHighlightX | mTouchHighlightY) != 0) { 4169 if (mTouchCrossHairColor == null) { 4170 mTouchCrossHairColor = new Paint(); 4171 mTouchCrossHairColor.setColor(Color.RED); 4172 } 4173 canvas.drawLine(mTouchHighlightX - mNavSlop, 4174 mTouchHighlightY - mNavSlop, mTouchHighlightX 4175 + mNavSlop + 1, mTouchHighlightY + mNavSlop 4176 + 1, mTouchCrossHairColor); 4177 canvas.drawLine(mTouchHighlightX + mNavSlop + 1, 4178 mTouchHighlightY - mNavSlop, mTouchHighlightX 4179 - mNavSlop, 4180 mTouchHighlightY + mNavSlop + 1, 4181 mTouchCrossHairColor); 4182 } 4183 } 4184 } 4185 } 4186 4187 private void removeTouchHighlight() { 4188 mWebViewCore.removeMessages(EventHub.GET_TOUCH_HIGHLIGHT_RECTS); 4189 mPrivateHandler.removeMessages(SET_TOUCH_HIGHLIGHT_RECTS); 4190 setTouchHighlightRects(null); 4191 } 4192 4193 @Override 4194 public void setLayoutParams(ViewGroup.LayoutParams params) { 4195 if (params.height == LayoutParams.WRAP_CONTENT) { 4196 mWrapContent = true; 4197 } 4198 super.setLayoutParams(params); 4199 } 4200 4201 @Override 4202 public boolean performLongClick() { 4203 // performLongClick() is the result of a delayed message. If we switch 4204 // to windows overview, the WebView will be temporarily removed from the 4205 // view system. In that case, do nothing. 4206 if (getParent() == null) return false; 4207 4208 // A multi-finger gesture can look like a long press; make sure we don't take 4209 // long press actions if we're scaling. 4210 final ScaleGestureDetector detector = mZoomManager.getMultiTouchGestureDetector(); 4211 if (detector != null && detector.isInProgress()) { 4212 return false; 4213 } 4214 4215 if (mNativeClass != 0 && nativeCursorIsTextInput()) { 4216 // Send the click so that the textfield is in focus 4217 centerKeyPressOnTextField(); 4218 rebuildWebTextView(); 4219 } else { 4220 clearTextEntry(); 4221 } 4222 if (inEditingMode()) { 4223 // Since we just called rebuildWebTextView, the layout is not set 4224 // properly. Update it so it can correctly find the word to select. 4225 mWebTextView.ensureLayout(); 4226 // Provide a touch down event to WebTextView, which will allow it 4227 // to store the location to use in performLongClick. 4228 AbsoluteLayout.LayoutParams params 4229 = (AbsoluteLayout.LayoutParams) mWebTextView.getLayoutParams(); 4230 MotionEvent fake = MotionEvent.obtain(mLastTouchTime, 4231 mLastTouchTime, MotionEvent.ACTION_DOWN, 4232 mLastTouchX - params.x + mScrollX, 4233 mLastTouchY - params.y + mScrollY, 0); 4234 mWebTextView.dispatchTouchEvent(fake); 4235 return mWebTextView.performLongClick(); 4236 } 4237 if (mSelectingText) return false; // long click does nothing on selection 4238 /* if long click brings up a context menu, the super function 4239 * returns true and we're done. Otherwise, nothing happened when 4240 * the user clicked. */ 4241 if (super.performLongClick()) { 4242 return true; 4243 } 4244 /* In the case where the application hasn't already handled the long 4245 * click action, look for a word under the click. If one is found, 4246 * animate the text selection into view. 4247 * FIXME: no animation code yet */ 4248 return selectText(); 4249 } 4250 4251 /** 4252 * Select the word at the last click point. 4253 * 4254 * @hide pending API council approval 4255 */ 4256 public boolean selectText() { 4257 int x = viewToContentX(mLastTouchX + mScrollX); 4258 int y = viewToContentY(mLastTouchY + mScrollY); 4259 return selectText(x, y); 4260 } 4261 4262 /** 4263 * Select the word at the indicated content coordinates. 4264 */ 4265 boolean selectText(int x, int y) { 4266 if (!setUpSelect(true, x, y)) { 4267 return false; 4268 } 4269 nativeSetExtendSelection(); 4270 mDrawSelectionPointer = false; 4271 mSelectionStarted = true; 4272 mTouchMode = TOUCH_DRAG_MODE; 4273 return true; 4274 } 4275 4276 private int mOrientation = Configuration.ORIENTATION_UNDEFINED; 4277 4278 @Override 4279 protected void onConfigurationChanged(Configuration newConfig) { 4280 if (mSelectingText && mOrientation != newConfig.orientation) { 4281 selectionDone(); 4282 } 4283 mOrientation = newConfig.orientation; 4284 } 4285 4286 /** 4287 * Keep track of the Callback so we can end its ActionMode or remove its 4288 * titlebar. 4289 */ 4290 private SelectActionModeCallback mSelectCallback; 4291 4292 // These values are possible options for didUpdateWebTextViewDimensions. 4293 private static final int FULLY_ON_SCREEN = 0; 4294 private static final int INTERSECTS_SCREEN = 1; 4295 private static final int ANYWHERE = 2; 4296 4297 /** 4298 * Check to see if the focused textfield/textarea is still on screen. If it 4299 * is, update the the dimensions and location of WebTextView. Otherwise, 4300 * remove the WebTextView. Should be called when the zoom level changes. 4301 * @param intersection How to determine whether the textfield/textarea is 4302 * still on screen. 4303 * @return boolean True if the textfield/textarea is still on screen and the 4304 * dimensions/location of WebTextView have been updated. 4305 */ 4306 private boolean didUpdateWebTextViewDimensions(int intersection) { 4307 Rect contentBounds = nativeFocusCandidateNodeBounds(); 4308 Rect vBox = contentToViewRect(contentBounds); 4309 Rect visibleRect = new Rect(); 4310 calcOurVisibleRect(visibleRect); 4311 // If the textfield is on screen, place the WebTextView in 4312 // its new place, accounting for our new scroll/zoom values, 4313 // and adjust its textsize. 4314 boolean onScreen; 4315 switch (intersection) { 4316 case FULLY_ON_SCREEN: 4317 onScreen = visibleRect.contains(vBox); 4318 break; 4319 case INTERSECTS_SCREEN: 4320 onScreen = Rect.intersects(visibleRect, vBox); 4321 break; 4322 case ANYWHERE: 4323 onScreen = true; 4324 break; 4325 default: 4326 throw new AssertionError( 4327 "invalid parameter passed to didUpdateWebTextViewDimensions"); 4328 } 4329 if (onScreen) { 4330 mWebTextView.setRect(vBox.left, vBox.top, vBox.width(), 4331 vBox.height()); 4332 mWebTextView.updateTextSize(); 4333 updateWebTextViewPadding(); 4334 return true; 4335 } else { 4336 // The textfield is now off screen. The user probably 4337 // was not zooming to see the textfield better. Remove 4338 // the WebTextView. If the user types a key, and the 4339 // textfield is still in focus, we will reconstruct 4340 // the WebTextView and scroll it back on screen. 4341 mWebTextView.remove(); 4342 return false; 4343 } 4344 } 4345 4346 void setBaseLayer(int layer, Region invalRegion, boolean showVisualIndicator, 4347 boolean isPictureAfterFirstLayout, boolean registerPageSwapCallback) { 4348 if (mNativeClass == 0) 4349 return; 4350 nativeSetBaseLayer(layer, invalRegion, showVisualIndicator, 4351 isPictureAfterFirstLayout, registerPageSwapCallback); 4352 if (mHTML5VideoViewProxy != null) { 4353 mHTML5VideoViewProxy.setBaseLayer(layer); 4354 } 4355 } 4356 4357 int getBaseLayer() { 4358 if (mNativeClass == 0) { 4359 return 0; 4360 } 4361 return nativeGetBaseLayer(); 4362 } 4363 4364 private void onZoomAnimationStart() { 4365 // If it is in password mode, turn it off so it does not draw misplaced. 4366 if (inEditingMode()) { 4367 mWebTextView.setVisibility(INVISIBLE); 4368 } 4369 } 4370 4371 private void onZoomAnimationEnd() { 4372 // adjust the edit text view if needed 4373 if (inEditingMode() 4374 && didUpdateWebTextViewDimensions(FULLY_ON_SCREEN)) { 4375 // If it is a password field, start drawing the WebTextView once 4376 // again. 4377 mWebTextView.setVisibility(VISIBLE); 4378 } 4379 } 4380 4381 void onFixedLengthZoomAnimationStart() { 4382 WebViewCore.pauseUpdatePicture(getWebViewCore()); 4383 onZoomAnimationStart(); 4384 } 4385 4386 void onFixedLengthZoomAnimationEnd() { 4387 if (!mBlockWebkitViewMessages && !mSelectingText) { 4388 WebViewCore.resumeUpdatePicture(mWebViewCore); 4389 } 4390 onZoomAnimationEnd(); 4391 } 4392 4393 private static final int ZOOM_BITS = Paint.FILTER_BITMAP_FLAG | 4394 Paint.DITHER_FLAG | 4395 Paint.SUBPIXEL_TEXT_FLAG; 4396 private static final int SCROLL_BITS = Paint.FILTER_BITMAP_FLAG | 4397 Paint.DITHER_FLAG; 4398 4399 private final DrawFilter mZoomFilter = 4400 new PaintFlagsDrawFilter(ZOOM_BITS, Paint.LINEAR_TEXT_FLAG); 4401 // If we need to trade better quality for speed, set mScrollFilter to null 4402 private final DrawFilter mScrollFilter = 4403 new PaintFlagsDrawFilter(SCROLL_BITS, 0); 4404 4405 private void drawCoreAndCursorRing(Canvas canvas, int color, 4406 boolean drawCursorRing) { 4407 if (mDrawHistory) { 4408 canvas.scale(mZoomManager.getScale(), mZoomManager.getScale()); 4409 canvas.drawPicture(mHistoryPicture); 4410 return; 4411 } 4412 if (mNativeClass == 0) return; 4413 4414 boolean animateZoom = mZoomManager.isFixedLengthAnimationInProgress(); 4415 boolean animateScroll = ((!mScroller.isFinished() 4416 || mVelocityTracker != null) 4417 && (mTouchMode != TOUCH_DRAG_MODE || 4418 mHeldMotionless != MOTIONLESS_TRUE)) 4419 || mDeferTouchMode == TOUCH_DRAG_MODE; 4420 if (mTouchMode == TOUCH_DRAG_MODE) { 4421 if (mHeldMotionless == MOTIONLESS_PENDING) { 4422 mPrivateHandler.removeMessages(DRAG_HELD_MOTIONLESS); 4423 mPrivateHandler.removeMessages(AWAKEN_SCROLL_BARS); 4424 mHeldMotionless = MOTIONLESS_FALSE; 4425 } 4426 if (mHeldMotionless == MOTIONLESS_FALSE) { 4427 mPrivateHandler.sendMessageDelayed(mPrivateHandler 4428 .obtainMessage(DRAG_HELD_MOTIONLESS), MOTIONLESS_TIME); 4429 mHeldMotionless = MOTIONLESS_PENDING; 4430 } 4431 } 4432 if (animateZoom) { 4433 mZoomManager.animateZoom(canvas); 4434 } else if (!canvas.isHardwareAccelerated()) { 4435 canvas.scale(mZoomManager.getScale(), mZoomManager.getScale()); 4436 } 4437 4438 boolean UIAnimationsRunning = false; 4439 // Currently for each draw we compute the animation values; 4440 // We may in the future decide to do that independently. 4441 if (mNativeClass != 0 && nativeEvaluateLayersAnimations()) { 4442 UIAnimationsRunning = true; 4443 // If we have unfinished (or unstarted) animations, 4444 // we ask for a repaint. We only need to do this in software 4445 // rendering (with hardware rendering we already have a different 4446 // method of requesting a repaint) 4447 if (!canvas.isHardwareAccelerated()) 4448 invalidate(); 4449 } 4450 4451 // decide which adornments to draw 4452 int extras = DRAW_EXTRAS_NONE; 4453 if (mFindIsUp) { 4454 extras = DRAW_EXTRAS_FIND; 4455 } else if (mSelectingText && !USE_JAVA_TEXT_SELECTION) { 4456 extras = DRAW_EXTRAS_SELECTION; 4457 nativeSetSelectionPointer(mDrawSelectionPointer, 4458 mZoomManager.getInvScale(), 4459 mSelectX, mSelectY - getTitleHeight()); 4460 } else if (drawCursorRing) { 4461 extras = DRAW_EXTRAS_CURSOR_RING; 4462 } 4463 if (DebugFlags.WEB_VIEW) { 4464 Log.v(LOGTAG, "mFindIsUp=" + mFindIsUp 4465 + " mSelectingText=" + mSelectingText 4466 + " nativePageShouldHandleShiftAndArrows()=" 4467 + nativePageShouldHandleShiftAndArrows() 4468 + " animateZoom=" + animateZoom 4469 + " extras=" + extras); 4470 } 4471 4472 if (canvas.isHardwareAccelerated()) { 4473 int functor = nativeGetDrawGLFunction(mGLViewportEmpty ? null : mGLRectViewport, 4474 mGLViewportEmpty ? null : mViewRectViewport, getScale(), extras); 4475 ((HardwareCanvas) canvas).callDrawGLFunction(functor); 4476 4477 if (mHardwareAccelSkia != getSettings().getHardwareAccelSkiaEnabled()) { 4478 mHardwareAccelSkia = getSettings().getHardwareAccelSkiaEnabled(); 4479 nativeUseHardwareAccelSkia(mHardwareAccelSkia); 4480 } 4481 4482 if (mSelectingText && USE_JAVA_TEXT_SELECTION) { 4483 drawTextSelectionHandles(canvas); 4484 } 4485 4486 } else { 4487 DrawFilter df = null; 4488 if (mZoomManager.isZoomAnimating() || UIAnimationsRunning) { 4489 df = mZoomFilter; 4490 } else if (animateScroll) { 4491 df = mScrollFilter; 4492 } 4493 canvas.setDrawFilter(df); 4494 // XXX: Revisit splitting content. Right now it causes a 4495 // synchronization problem with layers. 4496 int content = nativeDraw(canvas, color, extras, false); 4497 canvas.setDrawFilter(null); 4498 if (!mBlockWebkitViewMessages && content != 0) { 4499 mWebViewCore.sendMessage(EventHub.SPLIT_PICTURE_SET, content, 0); 4500 } 4501 } 4502 4503 if (extras == DRAW_EXTRAS_CURSOR_RING) { 4504 if (mTouchMode == TOUCH_SHORTPRESS_START_MODE) { 4505 mTouchMode = TOUCH_SHORTPRESS_MODE; 4506 } 4507 } 4508 if (mFocusSizeChanged) { 4509 mFocusSizeChanged = false; 4510 // If we are zooming, this will get handled above, when the zoom 4511 // finishes. We also do not need to do this unless the WebTextView 4512 // is showing. With hardware acceleration, the pageSwapCallback() 4513 // updates the WebTextView position in sync with page swapping 4514 if (!canvas.isHardwareAccelerated() && !animateZoom && inEditingMode()) { 4515 didUpdateWebTextViewDimensions(ANYWHERE); 4516 } 4517 } 4518 } 4519 4520 private void drawTextSelectionHandles(Canvas canvas) { 4521 if (mTextSelectionPaint == null) { 4522 mTextSelectionPaint = new Paint(); 4523 mTextSelectionPaint.setColor(HIGHLIGHT_COLOR); 4524 } 4525 mTextSelectionRegion.setEmpty(); 4526 nativeGetTextSelectionRegion(mTextSelectionRegion); 4527 Rect r = new Rect(); 4528 RegionIterator iter = new RegionIterator(mTextSelectionRegion); 4529 int start_x = -1; 4530 int start_y = -1; 4531 int end_x = -1; 4532 int end_y = -1; 4533 while (iter.next(r)) { 4534 r = new Rect( 4535 contentToViewDimension(r.left), 4536 contentToViewDimension(r.top), 4537 contentToViewDimension(r.right), 4538 contentToViewDimension(r.bottom)); 4539 // Regions are in order. First one is where selection starts, 4540 // last one is where it ends 4541 if (start_x < 0 || start_y < 0) { 4542 start_x = r.left; 4543 start_y = r.bottom; 4544 } 4545 end_x = r.right; 4546 end_y = r.bottom; 4547 canvas.drawRect(r, mTextSelectionPaint); 4548 } 4549 if (mSelectHandleLeft == null) { 4550 mSelectHandleLeft = mContext.getResources().getDrawable( 4551 com.android.internal.R.drawable.text_select_handle_left); 4552 } 4553 // Magic formula copied from TextView 4554 start_x -= (mSelectHandleLeft.getIntrinsicWidth() * 3) / 4; 4555 mSelectHandleLeft.setBounds(start_x, start_y, 4556 start_x + mSelectHandleLeft.getIntrinsicWidth(), 4557 start_y + mSelectHandleLeft.getIntrinsicHeight()); 4558 if (mSelectHandleRight == null) { 4559 mSelectHandleRight = mContext.getResources().getDrawable( 4560 com.android.internal.R.drawable.text_select_handle_right); 4561 } 4562 end_x -= mSelectHandleRight.getIntrinsicWidth() / 4; 4563 mSelectHandleRight.setBounds(end_x, end_y, 4564 end_x + mSelectHandleRight.getIntrinsicWidth(), 4565 end_y + mSelectHandleRight.getIntrinsicHeight()); 4566 mSelectHandleLeft.draw(canvas); 4567 mSelectHandleRight.draw(canvas); 4568 } 4569 4570 // draw history 4571 private boolean mDrawHistory = false; 4572 private Picture mHistoryPicture = null; 4573 private int mHistoryWidth = 0; 4574 private int mHistoryHeight = 0; 4575 4576 // Only check the flag, can be called from WebCore thread 4577 boolean drawHistory() { 4578 return mDrawHistory; 4579 } 4580 4581 int getHistoryPictureWidth() { 4582 return (mHistoryPicture != null) ? mHistoryPicture.getWidth() : 0; 4583 } 4584 4585 // Should only be called in UI thread 4586 void switchOutDrawHistory() { 4587 if (null == mWebViewCore) return; // CallbackProxy may trigger this 4588 if (mDrawHistory && (getProgress() == 100 || nativeHasContent())) { 4589 mDrawHistory = false; 4590 mHistoryPicture = null; 4591 invalidate(); 4592 int oldScrollX = mScrollX; 4593 int oldScrollY = mScrollY; 4594 mScrollX = pinLocX(mScrollX); 4595 mScrollY = pinLocY(mScrollY); 4596 if (oldScrollX != mScrollX || oldScrollY != mScrollY) { 4597 onScrollChanged(mScrollX, mScrollY, oldScrollX, oldScrollY); 4598 } else { 4599 sendOurVisibleRect(); 4600 } 4601 } 4602 } 4603 4604 WebViewCore.CursorData cursorData() { 4605 WebViewCore.CursorData result = cursorDataNoPosition(); 4606 Point position = nativeCursorPosition(); 4607 result.mX = position.x; 4608 result.mY = position.y; 4609 return result; 4610 } 4611 4612 WebViewCore.CursorData cursorDataNoPosition() { 4613 WebViewCore.CursorData result = new WebViewCore.CursorData(); 4614 result.mMoveGeneration = nativeMoveGeneration(); 4615 result.mFrame = nativeCursorFramePointer(); 4616 return result; 4617 } 4618 4619 /** 4620 * Delete text from start to end in the focused textfield. If there is no 4621 * focus, or if start == end, silently fail. If start and end are out of 4622 * order, swap them. 4623 * @param start Beginning of selection to delete. 4624 * @param end End of selection to delete. 4625 */ 4626 /* package */ void deleteSelection(int start, int end) { 4627 mTextGeneration++; 4628 WebViewCore.TextSelectionData data 4629 = new WebViewCore.TextSelectionData(start, end); 4630 mWebViewCore.sendMessage(EventHub.DELETE_SELECTION, mTextGeneration, 0, 4631 data); 4632 } 4633 4634 /** 4635 * Set the selection to (start, end) in the focused textfield. If start and 4636 * end are out of order, swap them. 4637 * @param start Beginning of selection. 4638 * @param end End of selection. 4639 */ 4640 /* package */ void setSelection(int start, int end) { 4641 if (mWebViewCore != null) { 4642 mWebViewCore.sendMessage(EventHub.SET_SELECTION, start, end); 4643 } 4644 } 4645 4646 @Override 4647 public InputConnection onCreateInputConnection(EditorInfo outAttrs) { 4648 InputConnection connection = super.onCreateInputConnection(outAttrs); 4649 outAttrs.imeOptions |= EditorInfo.IME_FLAG_NO_FULLSCREEN; 4650 return connection; 4651 } 4652 4653 /** 4654 * Called in response to a message from webkit telling us that the soft 4655 * keyboard should be launched. 4656 */ 4657 private void displaySoftKeyboard(boolean isTextView) { 4658 InputMethodManager imm = (InputMethodManager) 4659 getContext().getSystemService(Context.INPUT_METHOD_SERVICE); 4660 4661 // bring it back to the default level scale so that user can enter text 4662 boolean zoom = mZoomManager.getScale() < mZoomManager.getDefaultScale(); 4663 if (zoom) { 4664 mZoomManager.setZoomCenter(mLastTouchX, mLastTouchY); 4665 mZoomManager.setZoomScale(mZoomManager.getDefaultScale(), false); 4666 } 4667 if (isTextView) { 4668 rebuildWebTextView(); 4669 if (inEditingMode()) { 4670 imm.showSoftInput(mWebTextView, 0, mWebTextView.getResultReceiver()); 4671 if (zoom) { 4672 didUpdateWebTextViewDimensions(INTERSECTS_SCREEN); 4673 } 4674 return; 4675 } 4676 } 4677 // Used by plugins and contentEditable. 4678 // Also used if the navigation cache is out of date, and 4679 // does not recognize that a textfield is in focus. In that 4680 // case, use WebView as the targeted view. 4681 // see http://b/issue?id=2457459 4682 imm.showSoftInput(this, 0); 4683 } 4684 4685 // Called by WebKit to instruct the UI to hide the keyboard 4686 private void hideSoftKeyboard() { 4687 InputMethodManager imm = InputMethodManager.peekInstance(); 4688 if (imm != null && (imm.isActive(this) 4689 || (inEditingMode() && imm.isActive(mWebTextView)))) { 4690 imm.hideSoftInputFromWindow(this.getWindowToken(), 0); 4691 } 4692 } 4693 4694 /* 4695 * This method checks the current focus and cursor and potentially rebuilds 4696 * mWebTextView to have the appropriate properties, such as password, 4697 * multiline, and what text it contains. It also removes it if necessary. 4698 */ 4699 /* package */ void rebuildWebTextView() { 4700 // If the WebView does not have focus, do nothing until it gains focus. 4701 if (!hasFocus() && (null == mWebTextView || !mWebTextView.hasFocus())) { 4702 return; 4703 } 4704 boolean alreadyThere = inEditingMode(); 4705 // inEditingMode can only return true if mWebTextView is non-null, 4706 // so we can safely call remove() if (alreadyThere) 4707 if (0 == mNativeClass || !nativeFocusCandidateIsTextInput()) { 4708 if (alreadyThere) { 4709 mWebTextView.remove(); 4710 } 4711 return; 4712 } 4713 // At this point, we know we have found an input field, so go ahead 4714 // and create the WebTextView if necessary. 4715 if (mWebTextView == null) { 4716 mWebTextView = new WebTextView(mContext, WebView.this, mAutoFillData.getQueryId()); 4717 // Initialize our generation number. 4718 mTextGeneration = 0; 4719 } 4720 mWebTextView.updateTextSize(); 4721 Rect visibleRect = new Rect(); 4722 calcOurContentVisibleRect(visibleRect); 4723 // Note that sendOurVisibleRect calls viewToContent, so the coordinates 4724 // should be in content coordinates. 4725 Rect bounds = nativeFocusCandidateNodeBounds(); 4726 Rect vBox = contentToViewRect(bounds); 4727 mWebTextView.setRect(vBox.left, vBox.top, vBox.width(), vBox.height()); 4728 if (!Rect.intersects(bounds, visibleRect)) { 4729 revealSelection(); 4730 } 4731 String text = nativeFocusCandidateText(); 4732 int nodePointer = nativeFocusCandidatePointer(); 4733 mWebTextView.setGravity(nativeFocusCandidateIsRtlText() ? 4734 Gravity.RIGHT : Gravity.NO_GRAVITY); 4735 // This needs to be called before setType, which may call 4736 // requestFormData, and it needs to have the correct nodePointer. 4737 mWebTextView.setNodePointer(nodePointer); 4738 mWebTextView.setType(nativeFocusCandidateType()); 4739 updateWebTextViewPadding(); 4740 if (null == text) { 4741 if (DebugFlags.WEB_VIEW) { 4742 Log.v(LOGTAG, "rebuildWebTextView null == text"); 4743 } 4744 text = ""; 4745 } 4746 mWebTextView.setTextAndKeepSelection(text); 4747 InputMethodManager imm = InputMethodManager.peekInstance(); 4748 if (imm != null && imm.isActive(mWebTextView)) { 4749 imm.restartInput(mWebTextView); 4750 } 4751 if (isFocused()) { 4752 mWebTextView.requestFocus(); 4753 } 4754 } 4755 4756 /** 4757 * Update the padding of mWebTextView based on the native textfield/textarea 4758 */ 4759 void updateWebTextViewPadding() { 4760 Rect paddingRect = nativeFocusCandidatePaddingRect(); 4761 if (paddingRect != null) { 4762 // Use contentToViewDimension since these are the dimensions of 4763 // the padding. 4764 mWebTextView.setPadding( 4765 contentToViewDimension(paddingRect.left), 4766 contentToViewDimension(paddingRect.top), 4767 contentToViewDimension(paddingRect.right), 4768 contentToViewDimension(paddingRect.bottom)); 4769 } 4770 } 4771 4772 /** 4773 * Tell webkit to put the cursor on screen. 4774 */ 4775 /* package */ void revealSelection() { 4776 if (mWebViewCore != null) { 4777 mWebViewCore.sendMessage(EventHub.REVEAL_SELECTION); 4778 } 4779 } 4780 4781 /** 4782 * Called by WebTextView to find saved form data associated with the 4783 * textfield 4784 * @param name Name of the textfield. 4785 * @param nodePointer Pointer to the node of the textfield, so it can be 4786 * compared to the currently focused textfield when the data is 4787 * retrieved. 4788 * @param autoFillable true if WebKit has determined this field is part of 4789 * a form that can be auto filled. 4790 * @param autoComplete true if the attribute "autocomplete" is set to true 4791 * on the textfield. 4792 */ 4793 /* package */ void requestFormData(String name, int nodePointer, 4794 boolean autoFillable, boolean autoComplete) { 4795 if (mWebViewCore.getSettings().getSaveFormData()) { 4796 Message update = mPrivateHandler.obtainMessage(REQUEST_FORM_DATA); 4797 update.arg1 = nodePointer; 4798 RequestFormData updater = new RequestFormData(name, getUrl(), 4799 update, autoFillable, autoComplete); 4800 Thread t = new Thread(updater); 4801 t.start(); 4802 } 4803 } 4804 4805 /** 4806 * Pass a message to find out the <label> associated with the <input> 4807 * identified by nodePointer 4808 * @param framePointer Pointer to the frame containing the <input> node 4809 * @param nodePointer Pointer to the node for which a <label> is desired. 4810 */ 4811 /* package */ void requestLabel(int framePointer, int nodePointer) { 4812 mWebViewCore.sendMessage(EventHub.REQUEST_LABEL, framePointer, 4813 nodePointer); 4814 } 4815 4816 /* 4817 * This class requests an Adapter for the WebTextView which shows past 4818 * entries stored in the database. It is a Runnable so that it can be done 4819 * in its own thread, without slowing down the UI. 4820 */ 4821 private class RequestFormData implements Runnable { 4822 private String mName; 4823 private String mUrl; 4824 private Message mUpdateMessage; 4825 private boolean mAutoFillable; 4826 private boolean mAutoComplete; 4827 private WebSettings mWebSettings; 4828 4829 public RequestFormData(String name, String url, Message msg, 4830 boolean autoFillable, boolean autoComplete) { 4831 mName = name; 4832 mUrl = WebTextView.urlForAutoCompleteData(url); 4833 mUpdateMessage = msg; 4834 mAutoFillable = autoFillable; 4835 mAutoComplete = autoComplete; 4836 mWebSettings = getSettings(); 4837 } 4838 4839 public void run() { 4840 ArrayList<String> pastEntries = new ArrayList<String>(); 4841 4842 if (mAutoFillable) { 4843 // Note that code inside the adapter click handler in WebTextView depends 4844 // on the AutoFill item being at the top of the drop down list. If you change 4845 // the order, make sure to do it there too! 4846 if (mWebSettings != null && mWebSettings.getAutoFillProfile() != null) { 4847 pastEntries.add(getResources().getText( 4848 com.android.internal.R.string.autofill_this_form).toString() + 4849 " " + 4850 mAutoFillData.getPreviewString()); 4851 mWebTextView.setAutoFillProfileIsSet(true); 4852 } else { 4853 // There is no autofill profile set up yet, so add an option that 4854 // will invite the user to set their profile up. 4855 pastEntries.add(getResources().getText( 4856 com.android.internal.R.string.setup_autofill).toString()); 4857 mWebTextView.setAutoFillProfileIsSet(false); 4858 } 4859 } 4860 4861 if (mAutoComplete) { 4862 pastEntries.addAll(mDatabase.getFormData(mUrl, mName)); 4863 } 4864 4865 if (pastEntries.size() > 0) { 4866 AutoCompleteAdapter adapter = new 4867 AutoCompleteAdapter(mContext, pastEntries); 4868 mUpdateMessage.obj = adapter; 4869 mUpdateMessage.sendToTarget(); 4870 } 4871 } 4872 } 4873 4874 /** 4875 * Dump the display tree to "/sdcard/displayTree.txt" 4876 * 4877 * @hide debug only 4878 */ 4879 public void dumpDisplayTree() { 4880 nativeDumpDisplayTree(getUrl()); 4881 } 4882 4883 /** 4884 * Dump the dom tree to adb shell if "toFile" is False, otherwise dump it to 4885 * "/sdcard/domTree.txt" 4886 * 4887 * @hide debug only 4888 */ 4889 public void dumpDomTree(boolean toFile) { 4890 mWebViewCore.sendMessage(EventHub.DUMP_DOMTREE, toFile ? 1 : 0, 0); 4891 } 4892 4893 /** 4894 * Dump the render tree to adb shell if "toFile" is False, otherwise dump it 4895 * to "/sdcard/renderTree.txt" 4896 * 4897 * @hide debug only 4898 */ 4899 public void dumpRenderTree(boolean toFile) { 4900 mWebViewCore.sendMessage(EventHub.DUMP_RENDERTREE, toFile ? 1 : 0, 0); 4901 } 4902 4903 /** 4904 * Called by DRT on UI thread, need to proxy to WebCore thread. 4905 * 4906 * @hide debug only 4907 */ 4908 public void useMockDeviceOrientation() { 4909 mWebViewCore.sendMessage(EventHub.USE_MOCK_DEVICE_ORIENTATION); 4910 } 4911 4912 /** 4913 * Called by DRT on WebCore thread. 4914 * 4915 * @hide debug only 4916 */ 4917 public void setMockDeviceOrientation(boolean canProvideAlpha, double alpha, 4918 boolean canProvideBeta, double beta, boolean canProvideGamma, double gamma) { 4919 mWebViewCore.setMockDeviceOrientation(canProvideAlpha, alpha, canProvideBeta, beta, 4920 canProvideGamma, gamma); 4921 } 4922 4923 /** 4924 * Dump the V8 counters to standard output. 4925 * Note that you need a build with V8 and WEBCORE_INSTRUMENTATION set to 4926 * true. Otherwise, this will do nothing. 4927 * 4928 * @hide debug only 4929 */ 4930 public void dumpV8Counters() { 4931 mWebViewCore.sendMessage(EventHub.DUMP_V8COUNTERS); 4932 } 4933 4934 // This is used to determine long press with the center key. Does not 4935 // affect long press with the trackball/touch. 4936 private boolean mGotCenterDown = false; 4937 4938 @Override 4939 public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) { 4940 if (mBlockWebkitViewMessages) { 4941 return false; 4942 } 4943 // send complex characters to webkit for use by JS and plugins 4944 if (keyCode == KeyEvent.KEYCODE_UNKNOWN && event.getCharacters() != null) { 4945 // pass the key to DOM 4946 mWebViewCore.sendMessage(EventHub.KEY_DOWN, event); 4947 mWebViewCore.sendMessage(EventHub.KEY_UP, event); 4948 // return true as DOM handles the key 4949 return true; 4950 } 4951 return false; 4952 } 4953 4954 private boolean isEnterActionKey(int keyCode) { 4955 return keyCode == KeyEvent.KEYCODE_DPAD_CENTER 4956 || keyCode == KeyEvent.KEYCODE_ENTER 4957 || keyCode == KeyEvent.KEYCODE_NUMPAD_ENTER; 4958 } 4959 4960 @Override 4961 public boolean onKeyDown(int keyCode, KeyEvent event) { 4962 if (DebugFlags.WEB_VIEW) { 4963 Log.v(LOGTAG, "keyDown at " + System.currentTimeMillis() 4964 + "keyCode=" + keyCode 4965 + ", " + event + ", unicode=" + event.getUnicodeChar()); 4966 } 4967 if (mBlockWebkitViewMessages) { 4968 return false; 4969 } 4970 4971 // don't implement accelerator keys here; defer to host application 4972 if (event.isCtrlPressed()) { 4973 return false; 4974 } 4975 4976 if (mNativeClass == 0) { 4977 return false; 4978 } 4979 4980 // do this hack up front, so it always works, regardless of touch-mode 4981 if (AUTO_REDRAW_HACK && (keyCode == KeyEvent.KEYCODE_CALL)) { 4982 mAutoRedraw = !mAutoRedraw; 4983 if (mAutoRedraw) { 4984 invalidate(); 4985 } 4986 return true; 4987 } 4988 4989 // Bubble up the key event if 4990 // 1. it is a system key; or 4991 // 2. the host application wants to handle it; 4992 if (event.isSystem() 4993 || mCallbackProxy.uiOverrideKeyEvent(event)) { 4994 return false; 4995 } 4996 4997 // accessibility support 4998 if (accessibilityScriptInjected()) { 4999 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 5000 // if an accessibility script is injected we delegate to it the key handling. 5001 // this script is a screen reader which is a fully fledged solution for blind 5002 // users to navigate in and interact with web pages. 5003 mWebViewCore.sendMessage(EventHub.KEY_DOWN, event); 5004 return true; 5005 } else { 5006 // Clean up if accessibility was disabled after loading the current URL. 5007 mAccessibilityScriptInjected = false; 5008 } 5009 } else if (mAccessibilityInjector != null) { 5010 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 5011 if (mAccessibilityInjector.onKeyEvent(event)) { 5012 // if an accessibility injector is present (no JavaScript enabled or the site 5013 // opts out injecting our JavaScript screen reader) we let it decide whether 5014 // to act on and consume the event. 5015 return true; 5016 } 5017 } else { 5018 // Clean up if accessibility was disabled after loading the current URL. 5019 mAccessibilityInjector = null; 5020 } 5021 } 5022 5023 if (keyCode == KeyEvent.KEYCODE_PAGE_UP) { 5024 if (event.hasNoModifiers()) { 5025 pageUp(false); 5026 return true; 5027 } else if (event.hasModifiers(KeyEvent.META_ALT_ON)) { 5028 pageUp(true); 5029 return true; 5030 } 5031 } 5032 5033 if (keyCode == KeyEvent.KEYCODE_PAGE_DOWN) { 5034 if (event.hasNoModifiers()) { 5035 pageDown(false); 5036 return true; 5037 } else if (event.hasModifiers(KeyEvent.META_ALT_ON)) { 5038 pageDown(true); 5039 return true; 5040 } 5041 } 5042 5043 if (keyCode == KeyEvent.KEYCODE_MOVE_HOME && event.hasNoModifiers()) { 5044 pageUp(true); 5045 return true; 5046 } 5047 5048 if (keyCode == KeyEvent.KEYCODE_MOVE_END && event.hasNoModifiers()) { 5049 pageDown(true); 5050 return true; 5051 } 5052 5053 if (keyCode >= KeyEvent.KEYCODE_DPAD_UP 5054 && keyCode <= KeyEvent.KEYCODE_DPAD_RIGHT) { 5055 switchOutDrawHistory(); 5056 if (nativePageShouldHandleShiftAndArrows()) { 5057 letPageHandleNavKey(keyCode, event.getEventTime(), true, event.getMetaState()); 5058 return true; 5059 } 5060 if (event.hasModifiers(KeyEvent.META_ALT_ON)) { 5061 switch (keyCode) { 5062 case KeyEvent.KEYCODE_DPAD_UP: 5063 pageUp(true); 5064 return true; 5065 case KeyEvent.KEYCODE_DPAD_DOWN: 5066 pageDown(true); 5067 return true; 5068 case KeyEvent.KEYCODE_DPAD_LEFT: 5069 nativeClearCursor(); // start next trackball movement from page edge 5070 return pinScrollTo(0, mScrollY, true, 0); 5071 case KeyEvent.KEYCODE_DPAD_RIGHT: 5072 nativeClearCursor(); // start next trackball movement from page edge 5073 return pinScrollTo(mContentWidth, mScrollY, true, 0); 5074 } 5075 } 5076 if (mSelectingText) { 5077 int xRate = keyCode == KeyEvent.KEYCODE_DPAD_LEFT 5078 ? -1 : keyCode == KeyEvent.KEYCODE_DPAD_RIGHT ? 1 : 0; 5079 int yRate = keyCode == KeyEvent.KEYCODE_DPAD_UP ? 5080 -1 : keyCode == KeyEvent.KEYCODE_DPAD_DOWN ? 1 : 0; 5081 int multiplier = event.getRepeatCount() + 1; 5082 moveSelection(xRate * multiplier, yRate * multiplier); 5083 return true; 5084 } 5085 if (navHandledKey(keyCode, 1, false, event.getEventTime())) { 5086 playSoundEffect(keyCodeToSoundsEffect(keyCode)); 5087 return true; 5088 } 5089 // Bubble up the key event as WebView doesn't handle it 5090 return false; 5091 } 5092 5093 if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER) { 5094 switchOutDrawHistory(); 5095 boolean wantsKeyEvents = nativeCursorNodePointer() == 0 5096 || nativeCursorWantsKeyEvents(); 5097 if (event.getRepeatCount() == 0) { 5098 if (mSelectingText) { 5099 return true; // discard press if copy in progress 5100 } 5101 mGotCenterDown = true; 5102 mPrivateHandler.sendMessageDelayed(mPrivateHandler 5103 .obtainMessage(LONG_PRESS_CENTER), LONG_PRESS_TIMEOUT); 5104 // Already checked mNativeClass, so we do not need to check it 5105 // again. 5106 nativeRecordButtons(hasFocus() && hasWindowFocus(), true, true); 5107 if (!wantsKeyEvents) return true; 5108 } 5109 // Bubble up the key event as WebView doesn't handle it 5110 if (!wantsKeyEvents) return false; 5111 } 5112 5113 if (getSettings().getNavDump()) { 5114 switch (keyCode) { 5115 case KeyEvent.KEYCODE_4: 5116 dumpDisplayTree(); 5117 break; 5118 case KeyEvent.KEYCODE_5: 5119 case KeyEvent.KEYCODE_6: 5120 dumpDomTree(keyCode == KeyEvent.KEYCODE_5); 5121 break; 5122 case KeyEvent.KEYCODE_7: 5123 case KeyEvent.KEYCODE_8: 5124 dumpRenderTree(keyCode == KeyEvent.KEYCODE_7); 5125 break; 5126 case KeyEvent.KEYCODE_9: 5127 nativeInstrumentReport(); 5128 return true; 5129 } 5130 } 5131 5132 if (nativeCursorIsTextInput()) { 5133 // This message will put the node in focus, for the DOM's notion 5134 // of focus. 5135 mWebViewCore.sendMessage(EventHub.FAKE_CLICK, nativeCursorFramePointer(), 5136 nativeCursorNodePointer()); 5137 // This will bring up the WebTextView and put it in focus, for 5138 // our view system's notion of focus 5139 rebuildWebTextView(); 5140 // Now we need to pass the event to it 5141 if (inEditingMode()) { 5142 mWebTextView.setDefaultSelection(); 5143 return mWebTextView.dispatchKeyEvent(event); 5144 } 5145 } else if (nativeHasFocusNode()) { 5146 // In this case, the cursor is not on a text input, but the focus 5147 // might be. Check it, and if so, hand over to the WebTextView. 5148 rebuildWebTextView(); 5149 if (inEditingMode()) { 5150 mWebTextView.setDefaultSelection(); 5151 return mWebTextView.dispatchKeyEvent(event); 5152 } 5153 } 5154 5155 // TODO: should we pass all the keys to DOM or check the meta tag 5156 if (nativeCursorWantsKeyEvents() || true) { 5157 // pass the key to DOM 5158 mWebViewCore.sendMessage(EventHub.KEY_DOWN, event); 5159 // return true as DOM handles the key 5160 return true; 5161 } 5162 5163 // Bubble up the key event as WebView doesn't handle it 5164 return false; 5165 } 5166 5167 @Override 5168 public boolean onKeyUp(int keyCode, KeyEvent event) { 5169 if (DebugFlags.WEB_VIEW) { 5170 Log.v(LOGTAG, "keyUp at " + System.currentTimeMillis() 5171 + ", " + event + ", unicode=" + event.getUnicodeChar()); 5172 } 5173 if (mBlockWebkitViewMessages) { 5174 return false; 5175 } 5176 5177 if (mNativeClass == 0) { 5178 return false; 5179 } 5180 5181 // special CALL handling when cursor node's href is "tel:XXX" 5182 if (keyCode == KeyEvent.KEYCODE_CALL && nativeHasCursorNode()) { 5183 String text = nativeCursorText(); 5184 if (!nativeCursorIsTextInput() && text != null 5185 && text.startsWith(SCHEME_TEL)) { 5186 Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse(text)); 5187 getContext().startActivity(intent); 5188 return true; 5189 } 5190 } 5191 5192 // Bubble up the key event if 5193 // 1. it is a system key; or 5194 // 2. the host application wants to handle it; 5195 if (event.isSystem() 5196 || mCallbackProxy.uiOverrideKeyEvent(event)) { 5197 return false; 5198 } 5199 5200 // accessibility support 5201 if (accessibilityScriptInjected()) { 5202 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 5203 // if an accessibility script is injected we delegate to it the key handling. 5204 // this script is a screen reader which is a fully fledged solution for blind 5205 // users to navigate in and interact with web pages. 5206 mWebViewCore.sendMessage(EventHub.KEY_UP, event); 5207 return true; 5208 } else { 5209 // Clean up if accessibility was disabled after loading the current URL. 5210 mAccessibilityScriptInjected = false; 5211 } 5212 } else if (mAccessibilityInjector != null) { 5213 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 5214 if (mAccessibilityInjector.onKeyEvent(event)) { 5215 // if an accessibility injector is present (no JavaScript enabled or the site 5216 // opts out injecting our JavaScript screen reader) we let it decide whether to 5217 // act on and consume the event. 5218 return true; 5219 } 5220 } else { 5221 // Clean up if accessibility was disabled after loading the current URL. 5222 mAccessibilityInjector = null; 5223 } 5224 } 5225 5226 if (keyCode >= KeyEvent.KEYCODE_DPAD_UP 5227 && keyCode <= KeyEvent.KEYCODE_DPAD_RIGHT) { 5228 if (nativePageShouldHandleShiftAndArrows()) { 5229 letPageHandleNavKey(keyCode, event.getEventTime(), false, event.getMetaState()); 5230 return true; 5231 } 5232 // always handle the navigation keys in the UI thread 5233 // Bubble up the key event as WebView doesn't handle it 5234 return false; 5235 } 5236 5237 if (isEnterActionKey(keyCode)) { 5238 // remove the long press message first 5239 mPrivateHandler.removeMessages(LONG_PRESS_CENTER); 5240 mGotCenterDown = false; 5241 5242 if (mSelectingText) { 5243 if (mExtendSelection) { 5244 copySelection(); 5245 selectionDone(); 5246 } else { 5247 mExtendSelection = true; 5248 nativeSetExtendSelection(); 5249 invalidate(); // draw the i-beam instead of the arrow 5250 } 5251 return true; // discard press if copy in progress 5252 } 5253 5254 // perform the single click 5255 Rect visibleRect = sendOurVisibleRect(); 5256 // Note that sendOurVisibleRect calls viewToContent, so the 5257 // coordinates should be in content coordinates. 5258 if (!nativeCursorIntersects(visibleRect)) { 5259 return false; 5260 } 5261 WebViewCore.CursorData data = cursorData(); 5262 mWebViewCore.sendMessage(EventHub.SET_MOVE_MOUSE, data); 5263 playSoundEffect(SoundEffectConstants.CLICK); 5264 if (nativeCursorIsTextInput()) { 5265 rebuildWebTextView(); 5266 centerKeyPressOnTextField(); 5267 if (inEditingMode()) { 5268 mWebTextView.setDefaultSelection(); 5269 } 5270 return true; 5271 } 5272 clearTextEntry(); 5273 nativeShowCursorTimed(); 5274 if (mCallbackProxy.uiOverrideUrlLoading(nativeCursorText())) { 5275 return true; 5276 } 5277 if (nativeCursorNodePointer() != 0 && !nativeCursorWantsKeyEvents()) { 5278 mWebViewCore.sendMessage(EventHub.CLICK, data.mFrame, 5279 nativeCursorNodePointer()); 5280 return true; 5281 } 5282 } 5283 5284 // TODO: should we pass all the keys to DOM or check the meta tag 5285 if (nativeCursorWantsKeyEvents() || true) { 5286 // pass the key to DOM 5287 mWebViewCore.sendMessage(EventHub.KEY_UP, event); 5288 // return true as DOM handles the key 5289 return true; 5290 } 5291 5292 // Bubble up the key event as WebView doesn't handle it 5293 return false; 5294 } 5295 5296 /* 5297 * Enter selecting text mode, and see if CAB should be shown. 5298 * Returns true if the WebView is now in 5299 * selecting text mode (including if it was already in that mode, and this 5300 * method did nothing). 5301 */ 5302 private boolean setUpSelect(boolean selectWord, int x, int y) { 5303 if (0 == mNativeClass) return false; // client isn't initialized 5304 if (inFullScreenMode()) return false; 5305 if (mSelectingText) return true; 5306 nativeResetSelection(); 5307 if (selectWord && !nativeWordSelection(x, y)) { 5308 selectionDone(); 5309 return false; 5310 } 5311 mSelectCallback = new SelectActionModeCallback(); 5312 mSelectCallback.setWebView(this); 5313 if (startActionMode(mSelectCallback) == null) { 5314 // There is no ActionMode, so do not allow the user to modify a 5315 // selection. 5316 selectionDone(); 5317 return false; 5318 } 5319 mExtendSelection = false; 5320 mSelectingText = mDrawSelectionPointer = true; 5321 // don't let the picture change during text selection 5322 WebViewCore.pauseUpdatePicture(mWebViewCore); 5323 if (nativeHasCursorNode()) { 5324 Rect rect = nativeCursorNodeBounds(); 5325 mSelectX = contentToViewX(rect.left); 5326 mSelectY = contentToViewY(rect.top); 5327 } else if (mLastTouchY > getVisibleTitleHeightImpl()) { 5328 mSelectX = mScrollX + mLastTouchX; 5329 mSelectY = mScrollY + mLastTouchY; 5330 } else { 5331 mSelectX = mScrollX + getViewWidth() / 2; 5332 mSelectY = mScrollY + getViewHeightWithTitle() / 2; 5333 } 5334 nativeHideCursor(); 5335 mMinAutoScrollX = 0; 5336 mMaxAutoScrollX = getViewWidth(); 5337 mMinAutoScrollY = 0; 5338 mMaxAutoScrollY = getViewHeightWithTitle(); 5339 mScrollingLayer = nativeScrollableLayer(viewToContentX(mSelectX), 5340 viewToContentY(mSelectY), mScrollingLayerRect, 5341 mScrollingLayerBounds); 5342 if (mScrollingLayer != 0) { 5343 if (mScrollingLayerRect.left != mScrollingLayerRect.right) { 5344 mMinAutoScrollX = Math.max(mMinAutoScrollX, 5345 contentToViewX(mScrollingLayerBounds.left)); 5346 mMaxAutoScrollX = Math.min(mMaxAutoScrollX, 5347 contentToViewX(mScrollingLayerBounds.right)); 5348 } 5349 if (mScrollingLayerRect.top != mScrollingLayerRect.bottom) { 5350 mMinAutoScrollY = Math.max(mMinAutoScrollY, 5351 contentToViewY(mScrollingLayerBounds.top)); 5352 mMaxAutoScrollY = Math.min(mMaxAutoScrollY, 5353 contentToViewY(mScrollingLayerBounds.bottom)); 5354 } 5355 } 5356 mMinAutoScrollX += SELECT_SCROLL; 5357 mMaxAutoScrollX -= SELECT_SCROLL; 5358 mMinAutoScrollY += SELECT_SCROLL; 5359 mMaxAutoScrollY -= SELECT_SCROLL; 5360 return true; 5361 } 5362 5363 /** 5364 * Use this method to put the WebView into text selection mode. 5365 * Do not rely on this functionality; it will be deprecated in the future. 5366 * @deprecated This method is now obsolete. 5367 */ 5368 @Deprecated 5369 public void emulateShiftHeld() { 5370 checkThread(); 5371 setUpSelect(false, 0, 0); 5372 } 5373 5374 /** 5375 * Select all of the text in this WebView. 5376 * 5377 * @hide pending API council approval. 5378 */ 5379 public void selectAll() { 5380 if (0 == mNativeClass) return; // client isn't initialized 5381 if (inFullScreenMode()) return; 5382 if (!mSelectingText) { 5383 // retrieve a point somewhere within the text 5384 Point select = nativeSelectableText(); 5385 if (!selectText(select.x, select.y)) return; 5386 } 5387 nativeSelectAll(); 5388 mDrawSelectionPointer = false; 5389 mExtendSelection = true; 5390 invalidate(); 5391 } 5392 5393 /** 5394 * Called when the selection has been removed. 5395 */ 5396 void selectionDone() { 5397 if (mSelectingText) { 5398 mSelectingText = false; 5399 // finish is idempotent, so this is fine even if selectionDone was 5400 // called by mSelectCallback.onDestroyActionMode 5401 mSelectCallback.finish(); 5402 mSelectCallback = null; 5403 WebViewCore.resumePriority(); 5404 WebViewCore.resumeUpdatePicture(mWebViewCore); 5405 invalidate(); // redraw without selection 5406 mAutoScrollX = 0; 5407 mAutoScrollY = 0; 5408 mSentAutoScrollMessage = false; 5409 } 5410 } 5411 5412 /** 5413 * Copy the selection to the clipboard 5414 * 5415 * @hide pending API council approval. 5416 */ 5417 public boolean copySelection() { 5418 boolean copiedSomething = false; 5419 String selection = getSelection(); 5420 if (selection != null && selection != "") { 5421 if (DebugFlags.WEB_VIEW) { 5422 Log.v(LOGTAG, "copySelection \"" + selection + "\""); 5423 } 5424 Toast.makeText(mContext 5425 , com.android.internal.R.string.text_copied 5426 , Toast.LENGTH_SHORT).show(); 5427 copiedSomething = true; 5428 ClipboardManager cm = (ClipboardManager)getContext() 5429 .getSystemService(Context.CLIPBOARD_SERVICE); 5430 cm.setText(selection); 5431 } 5432 invalidate(); // remove selection region and pointer 5433 return copiedSomething; 5434 } 5435 5436 /** 5437 * @hide pending API Council approval. 5438 */ 5439 public SearchBox getSearchBox() { 5440 if ((mWebViewCore == null) || (mWebViewCore.getBrowserFrame() == null)) { 5441 return null; 5442 } 5443 return mWebViewCore.getBrowserFrame().getSearchBox(); 5444 } 5445 5446 /** 5447 * Returns the currently highlighted text as a string. 5448 */ 5449 String getSelection() { 5450 if (mNativeClass == 0) return ""; 5451 return nativeGetSelection(); 5452 } 5453 5454 @Override 5455 protected void onAttachedToWindow() { 5456 super.onAttachedToWindow(); 5457 if (hasWindowFocus()) setActive(true); 5458 final ViewTreeObserver treeObserver = getViewTreeObserver(); 5459 if (mGlobalLayoutListener == null) { 5460 mGlobalLayoutListener = new InnerGlobalLayoutListener(); 5461 treeObserver.addOnGlobalLayoutListener(mGlobalLayoutListener); 5462 } 5463 if (mScrollChangedListener == null) { 5464 mScrollChangedListener = new InnerScrollChangedListener(); 5465 treeObserver.addOnScrollChangedListener(mScrollChangedListener); 5466 } 5467 5468 addAccessibilityApisToJavaScript(); 5469 5470 mTouchEventQueue.reset(); 5471 } 5472 5473 @Override 5474 protected void onDetachedFromWindow() { 5475 clearHelpers(); 5476 mZoomManager.dismissZoomPicker(); 5477 if (hasWindowFocus()) setActive(false); 5478 5479 final ViewTreeObserver treeObserver = getViewTreeObserver(); 5480 if (mGlobalLayoutListener != null) { 5481 treeObserver.removeGlobalOnLayoutListener(mGlobalLayoutListener); 5482 mGlobalLayoutListener = null; 5483 } 5484 if (mScrollChangedListener != null) { 5485 treeObserver.removeOnScrollChangedListener(mScrollChangedListener); 5486 mScrollChangedListener = null; 5487 } 5488 5489 removeAccessibilityApisFromJavaScript(); 5490 5491 super.onDetachedFromWindow(); 5492 } 5493 5494 @Override 5495 protected void onVisibilityChanged(View changedView, int visibility) { 5496 super.onVisibilityChanged(changedView, visibility); 5497 // The zoomManager may be null if the webview is created from XML that 5498 // specifies the view's visibility param as not visible (see http://b/2794841) 5499 if (visibility != View.VISIBLE && mZoomManager != null) { 5500 mZoomManager.dismissZoomPicker(); 5501 } 5502 } 5503 5504 /** 5505 * @deprecated WebView no longer needs to implement 5506 * ViewGroup.OnHierarchyChangeListener. This method does nothing now. 5507 */ 5508 @Deprecated 5509 public void onChildViewAdded(View parent, View child) {} 5510 5511 /** 5512 * @deprecated WebView no longer needs to implement 5513 * ViewGroup.OnHierarchyChangeListener. This method does nothing now. 5514 */ 5515 @Deprecated 5516 public void onChildViewRemoved(View p, View child) {} 5517 5518 /** 5519 * @deprecated WebView should not have implemented 5520 * ViewTreeObserver.OnGlobalFocusChangeListener. This method does nothing now. 5521 */ 5522 @Deprecated 5523 public void onGlobalFocusChanged(View oldFocus, View newFocus) { 5524 } 5525 5526 void setActive(boolean active) { 5527 if (active) { 5528 if (hasFocus()) { 5529 // If our window regained focus, and we have focus, then begin 5530 // drawing the cursor ring 5531 mDrawCursorRing = true; 5532 setFocusControllerActive(true); 5533 if (mNativeClass != 0) { 5534 nativeRecordButtons(true, false, true); 5535 } 5536 } else { 5537 if (!inEditingMode()) { 5538 // If our window gained focus, but we do not have it, do not 5539 // draw the cursor ring. 5540 mDrawCursorRing = false; 5541 setFocusControllerActive(false); 5542 } 5543 // We do not call nativeRecordButtons here because we assume 5544 // that when we lost focus, or window focus, it got called with 5545 // false for the first parameter 5546 } 5547 } else { 5548 if (!mZoomManager.isZoomPickerVisible()) { 5549 /* 5550 * The external zoom controls come in their own window, so our 5551 * window loses focus. Our policy is to not draw the cursor ring 5552 * if our window is not focused, but this is an exception since 5553 * the user can still navigate the web page with the zoom 5554 * controls showing. 5555 */ 5556 mDrawCursorRing = false; 5557 } 5558 mKeysPressed.clear(); 5559 mPrivateHandler.removeMessages(SWITCH_TO_LONGPRESS); 5560 mTouchMode = TOUCH_DONE_MODE; 5561 if (mNativeClass != 0) { 5562 nativeRecordButtons(false, false, true); 5563 } 5564 setFocusControllerActive(false); 5565 } 5566 invalidate(); 5567 } 5568 5569 // To avoid drawing the cursor ring, and remove the TextView when our window 5570 // loses focus. 5571 @Override 5572 public void onWindowFocusChanged(boolean hasWindowFocus) { 5573 setActive(hasWindowFocus); 5574 if (hasWindowFocus) { 5575 JWebCoreJavaBridge.setActiveWebView(this); 5576 if (mPictureUpdatePausedForFocusChange) { 5577 WebViewCore.resumeUpdatePicture(mWebViewCore); 5578 nativeSetIsScrolling(false); 5579 mPictureUpdatePausedForFocusChange = false; 5580 } 5581 } else { 5582 JWebCoreJavaBridge.removeActiveWebView(this); 5583 final WebSettings settings = getSettings(); 5584 if (settings != null && settings.enableSmoothTransition() && 5585 mWebViewCore != null && !WebViewCore.isUpdatePicturePaused(mWebViewCore)) { 5586 WebViewCore.pauseUpdatePicture(mWebViewCore); 5587 nativeSetIsScrolling(true); 5588 mPictureUpdatePausedForFocusChange = true; 5589 } 5590 } 5591 super.onWindowFocusChanged(hasWindowFocus); 5592 } 5593 5594 /* 5595 * Pass a message to WebCore Thread, telling the WebCore::Page's 5596 * FocusController to be "inactive" so that it will 5597 * not draw the blinking cursor. It gets set to "active" to draw the cursor 5598 * in WebViewCore.cpp, when the WebCore thread receives key events/clicks. 5599 */ 5600 /* package */ void setFocusControllerActive(boolean active) { 5601 if (mWebViewCore == null) return; 5602 mWebViewCore.sendMessage(EventHub.SET_ACTIVE, active ? 1 : 0, 0); 5603 // Need to send this message after the document regains focus. 5604 if (active && mListBoxMessage != null) { 5605 mWebViewCore.sendMessage(mListBoxMessage); 5606 mListBoxMessage = null; 5607 } 5608 } 5609 5610 @Override 5611 protected void onFocusChanged(boolean focused, int direction, 5612 Rect previouslyFocusedRect) { 5613 if (DebugFlags.WEB_VIEW) { 5614 Log.v(LOGTAG, "MT focusChanged " + focused + ", " + direction); 5615 } 5616 if (focused) { 5617 // When we regain focus, if we have window focus, resume drawing 5618 // the cursor ring 5619 if (hasWindowFocus()) { 5620 mDrawCursorRing = true; 5621 if (mNativeClass != 0) { 5622 nativeRecordButtons(true, false, true); 5623 } 5624 setFocusControllerActive(true); 5625 //} else { 5626 // The WebView has gained focus while we do not have 5627 // windowfocus. When our window lost focus, we should have 5628 // called nativeRecordButtons(false...) 5629 } 5630 } else { 5631 // When we lost focus, unless focus went to the TextView (which is 5632 // true if we are in editing mode), stop drawing the cursor ring. 5633 if (!inEditingMode()) { 5634 mDrawCursorRing = false; 5635 if (mNativeClass != 0) { 5636 nativeRecordButtons(false, false, true); 5637 } 5638 setFocusControllerActive(false); 5639 } 5640 mKeysPressed.clear(); 5641 } 5642 5643 super.onFocusChanged(focused, direction, previouslyFocusedRect); 5644 } 5645 5646 void setGLRectViewport() { 5647 // Use the getGlobalVisibleRect() to get the intersection among the parents 5648 // visible == false means we're clipped - send a null rect down to indicate that 5649 // we should not draw 5650 boolean visible = getGlobalVisibleRect(mGLRectViewport); 5651 if (visible) { 5652 // Then need to invert the Y axis, just for GL 5653 View rootView = getRootView(); 5654 int rootViewHeight = rootView.getHeight(); 5655 mViewRectViewport.set(mGLRectViewport); 5656 int savedWebViewBottom = mGLRectViewport.bottom; 5657 mGLRectViewport.bottom = rootViewHeight - mGLRectViewport.top - getVisibleTitleHeightImpl(); 5658 mGLRectViewport.top = rootViewHeight - savedWebViewBottom; 5659 mGLViewportEmpty = false; 5660 } else { 5661 mGLViewportEmpty = true; 5662 } 5663 nativeUpdateDrawGLFunction(mGLViewportEmpty ? null : mGLRectViewport, 5664 mGLViewportEmpty ? null : mViewRectViewport); 5665 } 5666 5667 /** 5668 * @hide 5669 */ 5670 @Override 5671 protected boolean setFrame(int left, int top, int right, int bottom) { 5672 boolean changed = super.setFrame(left, top, right, bottom); 5673 if (!changed && mHeightCanMeasure) { 5674 // When mHeightCanMeasure is true, we will set mLastHeightSent to 0 5675 // in WebViewCore after we get the first layout. We do call 5676 // requestLayout() when we get contentSizeChanged(). But the View 5677 // system won't call onSizeChanged if the dimension is not changed. 5678 // In this case, we need to call sendViewSizeZoom() explicitly to 5679 // notify the WebKit about the new dimensions. 5680 sendViewSizeZoom(false); 5681 } 5682 setGLRectViewport(); 5683 return changed; 5684 } 5685 5686 @Override 5687 protected void onSizeChanged(int w, int h, int ow, int oh) { 5688 super.onSizeChanged(w, h, ow, oh); 5689 5690 // adjust the max viewport width depending on the view dimensions. This 5691 // is to ensure the scaling is not going insane. So do not shrink it if 5692 // the view size is temporarily smaller, e.g. when soft keyboard is up. 5693 int newMaxViewportWidth = (int) (Math.max(w, h) / mZoomManager.getDefaultMinZoomScale()); 5694 if (newMaxViewportWidth > sMaxViewportWidth) { 5695 sMaxViewportWidth = newMaxViewportWidth; 5696 } 5697 5698 mZoomManager.onSizeChanged(w, h, ow, oh); 5699 5700 if (mLoadedPicture != null && mDelaySetPicture == null) { 5701 // Size changes normally result in a new picture 5702 // Re-set the loaded picture to simulate that 5703 // However, do not update the base layer as that hasn't changed 5704 setNewPicture(mLoadedPicture, false); 5705 } 5706 } 5707 5708 @Override 5709 protected void onScrollChanged(int l, int t, int oldl, int oldt) { 5710 super.onScrollChanged(l, t, oldl, oldt); 5711 if (!mInOverScrollMode) { 5712 sendOurVisibleRect(); 5713 // update WebKit if visible title bar height changed. The logic is same 5714 // as getVisibleTitleHeightImpl. 5715 int titleHeight = getTitleHeight(); 5716 if (Math.max(titleHeight - t, 0) != Math.max(titleHeight - oldt, 0)) { 5717 sendViewSizeZoom(false); 5718 } 5719 } 5720 } 5721 5722 @Override 5723 public boolean dispatchKeyEvent(KeyEvent event) { 5724 switch (event.getAction()) { 5725 case KeyEvent.ACTION_DOWN: 5726 mKeysPressed.add(Integer.valueOf(event.getKeyCode())); 5727 break; 5728 case KeyEvent.ACTION_MULTIPLE: 5729 // Always accept the action. 5730 break; 5731 case KeyEvent.ACTION_UP: 5732 int location = mKeysPressed.indexOf(Integer.valueOf(event.getKeyCode())); 5733 if (location == -1) { 5734 // We did not receive the key down for this key, so do not 5735 // handle the key up. 5736 return false; 5737 } else { 5738 // We did receive the key down. Handle the key up, and 5739 // remove it from our pressed keys. 5740 mKeysPressed.remove(location); 5741 } 5742 break; 5743 default: 5744 // Accept the action. This should not happen, unless a new 5745 // action is added to KeyEvent. 5746 break; 5747 } 5748 if (inEditingMode() && mWebTextView.isFocused()) { 5749 // Ensure that the WebTextView gets the event, even if it does 5750 // not currently have a bounds. 5751 return mWebTextView.dispatchKeyEvent(event); 5752 } else { 5753 return super.dispatchKeyEvent(event); 5754 } 5755 } 5756 5757 /* 5758 * Here is the snap align logic: 5759 * 1. If it starts nearly horizontally or vertically, snap align; 5760 * 2. If there is a dramitic direction change, let it go; 5761 * 5762 * Adjustable parameters. Angle is the radians on a unit circle, limited 5763 * to quadrant 1. Values range from 0f (horizontal) to PI/2 (vertical) 5764 */ 5765 private static final float HSLOPE_TO_START_SNAP = .25f; 5766 private static final float HSLOPE_TO_BREAK_SNAP = .4f; 5767 private static final float VSLOPE_TO_START_SNAP = 1.25f; 5768 private static final float VSLOPE_TO_BREAK_SNAP = .95f; 5769 /* 5770 * These values are used to influence the average angle when entering 5771 * snap mode. If is is the first movement entering snap, we set the average 5772 * to the appropriate ideal. If the user is entering into snap after the 5773 * first movement, then we average the average angle with these values. 5774 */ 5775 private static final float ANGLE_VERT = 2f; 5776 private static final float ANGLE_HORIZ = 0f; 5777 /* 5778 * The modified moving average weight. 5779 * Formula: MAV[t]=MAV[t-1] + (P[t]-MAV[t-1])/n 5780 */ 5781 private static final float MMA_WEIGHT_N = 5; 5782 5783 private boolean hitFocusedPlugin(int contentX, int contentY) { 5784 if (DebugFlags.WEB_VIEW) { 5785 Log.v(LOGTAG, "nativeFocusIsPlugin()=" + nativeFocusIsPlugin()); 5786 Rect r = nativeFocusNodeBounds(); 5787 Log.v(LOGTAG, "nativeFocusNodeBounds()=(" + r.left + ", " + r.top 5788 + ", " + r.right + ", " + r.bottom + ")"); 5789 } 5790 return nativeFocusIsPlugin() 5791 && nativeFocusNodeBounds().contains(contentX, contentY); 5792 } 5793 5794 private boolean shouldForwardTouchEvent() { 5795 if (mFullScreenHolder != null) return true; 5796 if (mBlockWebkitViewMessages) return false; 5797 return mForwardTouchEvents 5798 && !mSelectingText 5799 && mPreventDefault != PREVENT_DEFAULT_IGNORE 5800 && mPreventDefault != PREVENT_DEFAULT_NO; 5801 } 5802 5803 private boolean inFullScreenMode() { 5804 return mFullScreenHolder != null; 5805 } 5806 5807 private void dismissFullScreenMode() { 5808 if (inFullScreenMode()) { 5809 mFullScreenHolder.hide(); 5810 mFullScreenHolder = null; 5811 } 5812 } 5813 5814 void onPinchToZoomAnimationStart() { 5815 // cancel the single touch handling 5816 cancelTouch(); 5817 onZoomAnimationStart(); 5818 } 5819 5820 void onPinchToZoomAnimationEnd(ScaleGestureDetector detector) { 5821 onZoomAnimationEnd(); 5822 // start a drag, TOUCH_PINCH_DRAG, can't use TOUCH_INIT_MODE as 5823 // it may trigger the unwanted click, can't use TOUCH_DRAG_MODE 5824 // as it may trigger the unwanted fling. 5825 mTouchMode = TOUCH_PINCH_DRAG; 5826 mConfirmMove = true; 5827 startTouch(detector.getFocusX(), detector.getFocusY(), mLastTouchTime); 5828 } 5829 5830 // See if there is a layer at x, y and switch to TOUCH_DRAG_LAYER_MODE if a 5831 // layer is found. 5832 private void startScrollingLayer(float x, float y) { 5833 int contentX = viewToContentX((int) x + mScrollX); 5834 int contentY = viewToContentY((int) y + mScrollY); 5835 mScrollingLayer = nativeScrollableLayer(contentX, contentY, 5836 mScrollingLayerRect, mScrollingLayerBounds); 5837 if (mScrollingLayer != 0) { 5838 mTouchMode = TOUCH_DRAG_LAYER_MODE; 5839 } 5840 } 5841 5842 // 1/(density * density) used to compute the distance between points. 5843 // Computed in init(). 5844 private float DRAG_LAYER_INVERSE_DENSITY_SQUARED; 5845 5846 // The distance between two points reported in onTouchEvent scaled by the 5847 // density of the screen. 5848 private static final int DRAG_LAYER_FINGER_DISTANCE = 20000; 5849 5850 @Override 5851 public boolean onHoverEvent(MotionEvent event) { 5852 if (mNativeClass == 0) { 5853 return false; 5854 } 5855 WebViewCore.CursorData data = cursorDataNoPosition(); 5856 data.mX = viewToContentX((int) event.getX() + mScrollX); 5857 data.mY = viewToContentY((int) event.getY() + mScrollY); 5858 mWebViewCore.sendMessage(EventHub.SET_MOVE_MOUSE, data); 5859 return true; 5860 } 5861 5862 @Override 5863 public boolean onTouchEvent(MotionEvent ev) { 5864 if (mNativeClass == 0 || (!isClickable() && !isLongClickable())) { 5865 return false; 5866 } 5867 5868 if (DebugFlags.WEB_VIEW) { 5869 Log.v(LOGTAG, ev + " at " + ev.getEventTime() 5870 + " mTouchMode=" + mTouchMode 5871 + " numPointers=" + ev.getPointerCount()); 5872 } 5873 5874 // If WebKit wasn't interested in this multitouch gesture, enqueue 5875 // the event for handling directly rather than making the round trip 5876 // to WebKit and back. 5877 if (ev.getPointerCount() > 1 && mPreventDefault != PREVENT_DEFAULT_NO) { 5878 passMultiTouchToWebKit(ev, mTouchEventQueue.nextTouchSequence()); 5879 } else { 5880 mTouchEventQueue.enqueueTouchEvent(ev); 5881 } 5882 5883 // Since all events are handled asynchronously, we always want the gesture stream. 5884 return true; 5885 } 5886 5887 private float calculateDragAngle(int dx, int dy) { 5888 dx = Math.abs(dx); 5889 dy = Math.abs(dy); 5890 return (float) Math.atan2(dy, dx); 5891 } 5892 5893 /* 5894 * Common code for single touch and multi-touch. 5895 * (x, y) denotes current focus point, which is the touch point for single touch 5896 * and the middle point for multi-touch. 5897 */ 5898 private boolean handleTouchEventCommon(MotionEvent ev, int action, int x, int y) { 5899 long eventTime = ev.getEventTime(); 5900 5901 // Due to the touch screen edge effect, a touch closer to the edge 5902 // always snapped to the edge. As getViewWidth() can be different from 5903 // getWidth() due to the scrollbar, adjusting the point to match 5904 // getViewWidth(). Same applied to the height. 5905 x = Math.min(x, getViewWidth() - 1); 5906 y = Math.min(y, getViewHeightWithTitle() - 1); 5907 5908 int deltaX = mLastTouchX - x; 5909 int deltaY = mLastTouchY - y; 5910 int contentX = viewToContentX(x + mScrollX); 5911 int contentY = viewToContentY(y + mScrollY); 5912 5913 switch (action) { 5914 case MotionEvent.ACTION_DOWN: { 5915 mPreventDefault = PREVENT_DEFAULT_NO; 5916 mConfirmMove = false; 5917 mInitialHitTestResult = null; 5918 if (!mScroller.isFinished()) { 5919 // stop the current scroll animation, but if this is 5920 // the start of a fling, allow it to add to the current 5921 // fling's velocity 5922 mScroller.abortAnimation(); 5923 mTouchMode = TOUCH_DRAG_START_MODE; 5924 mConfirmMove = true; 5925 mPrivateHandler.removeMessages(RESUME_WEBCORE_PRIORITY); 5926 } else if (mPrivateHandler.hasMessages(RELEASE_SINGLE_TAP)) { 5927 mPrivateHandler.removeMessages(RELEASE_SINGLE_TAP); 5928 if (USE_WEBKIT_RINGS || getSettings().supportTouchOnly()) { 5929 removeTouchHighlight(); 5930 } 5931 if (deltaX * deltaX + deltaY * deltaY < mDoubleTapSlopSquare) { 5932 mTouchMode = TOUCH_DOUBLE_TAP_MODE; 5933 } else { 5934 // commit the short press action for the previous tap 5935 doShortPress(); 5936 mTouchMode = TOUCH_INIT_MODE; 5937 mDeferTouchProcess = !mBlockWebkitViewMessages 5938 && (!inFullScreenMode() && mForwardTouchEvents) 5939 ? hitFocusedPlugin(contentX, contentY) 5940 : false; 5941 } 5942 } else { // the normal case 5943 mTouchMode = TOUCH_INIT_MODE; 5944 mDeferTouchProcess = !mBlockWebkitViewMessages 5945 && (!inFullScreenMode() && mForwardTouchEvents) 5946 ? hitFocusedPlugin(contentX, contentY) 5947 : false; 5948 if (!mBlockWebkitViewMessages) { 5949 mWebViewCore.sendMessage( 5950 EventHub.UPDATE_FRAME_CACHE_IF_LOADING); 5951 } 5952 if (USE_WEBKIT_RINGS || getSettings().supportTouchOnly()) { 5953 TouchHighlightData data = new TouchHighlightData(); 5954 data.mX = contentX; 5955 data.mY = contentY; 5956 data.mNativeLayerRect = new Rect(); 5957 data.mNativeLayer = nativeScrollableLayer( 5958 contentX, contentY, data.mNativeLayerRect, null); 5959 data.mSlop = viewToContentDimension(mNavSlop); 5960 mTouchHighlightRegion.setEmpty(); 5961 if (!mBlockWebkitViewMessages) { 5962 mTouchHighlightRequested = System.currentTimeMillis(); 5963 mWebViewCore.sendMessageAtFrontOfQueue( 5964 EventHub.GET_TOUCH_HIGHLIGHT_RECTS, data); 5965 } 5966 if (DEBUG_TOUCH_HIGHLIGHT) { 5967 if (getSettings().getNavDump()) { 5968 mTouchHighlightX = (int) x + mScrollX; 5969 mTouchHighlightY = (int) y + mScrollY; 5970 mPrivateHandler.postDelayed(new Runnable() { 5971 public void run() { 5972 mTouchHighlightX = mTouchHighlightY = 0; 5973 invalidate(); 5974 } 5975 }, TOUCH_HIGHLIGHT_ELAPSE_TIME); 5976 } 5977 } 5978 } 5979 if (mLogEvent && eventTime - mLastTouchUpTime < 1000) { 5980 EventLog.writeEvent(EventLogTags.BROWSER_DOUBLE_TAP_DURATION, 5981 (eventTime - mLastTouchUpTime), eventTime); 5982 } 5983 if (mSelectingText) { 5984 mDrawSelectionPointer = false; 5985 mSelectionStarted = nativeStartSelection(contentX, contentY); 5986 if (DebugFlags.WEB_VIEW) { 5987 Log.v(LOGTAG, "select=" + contentX + "," + contentY); 5988 } 5989 invalidate(); 5990 } 5991 } 5992 // Trigger the link 5993 if (!mSelectingText && (mTouchMode == TOUCH_INIT_MODE 5994 || mTouchMode == TOUCH_DOUBLE_TAP_MODE)) { 5995 mPrivateHandler.sendEmptyMessageDelayed( 5996 SWITCH_TO_SHORTPRESS, TAP_TIMEOUT); 5997 mPrivateHandler.sendEmptyMessageDelayed( 5998 SWITCH_TO_LONGPRESS, LONG_PRESS_TIMEOUT); 5999 if (inFullScreenMode() || mDeferTouchProcess) { 6000 mPreventDefault = PREVENT_DEFAULT_YES; 6001 } else if (!mBlockWebkitViewMessages && mForwardTouchEvents) { 6002 mPreventDefault = PREVENT_DEFAULT_MAYBE_YES; 6003 } else { 6004 mPreventDefault = PREVENT_DEFAULT_NO; 6005 } 6006 // pass the touch events from UI thread to WebCore thread 6007 if (shouldForwardTouchEvent()) { 6008 TouchEventData ted = new TouchEventData(); 6009 ted.mAction = action; 6010 ted.mIds = new int[1]; 6011 ted.mIds[0] = ev.getPointerId(0); 6012 ted.mPoints = new Point[1]; 6013 ted.mPoints[0] = new Point(contentX, contentY); 6014 ted.mPointsInView = new Point[1]; 6015 ted.mPointsInView[0] = new Point(x, y); 6016 ted.mMetaState = ev.getMetaState(); 6017 ted.mReprocess = mDeferTouchProcess; 6018 ted.mNativeLayer = nativeScrollableLayer( 6019 contentX, contentY, ted.mNativeLayerRect, null); 6020 ted.mSequence = mTouchEventQueue.nextTouchSequence(); 6021 mTouchEventQueue.preQueueTouchEventData(ted); 6022 mWebViewCore.sendMessage(EventHub.TOUCH_EVENT, ted); 6023 if (mDeferTouchProcess) { 6024 // still needs to set them for compute deltaX/Y 6025 mLastTouchX = x; 6026 mLastTouchY = y; 6027 break; 6028 } 6029 if (!inFullScreenMode()) { 6030 mPrivateHandler.removeMessages(PREVENT_DEFAULT_TIMEOUT); 6031 mPrivateHandler.sendMessageDelayed(mPrivateHandler 6032 .obtainMessage(PREVENT_DEFAULT_TIMEOUT, 6033 action, 0), TAP_TIMEOUT); 6034 } 6035 } 6036 } 6037 startTouch(x, y, eventTime); 6038 break; 6039 } 6040 case MotionEvent.ACTION_MOVE: { 6041 boolean firstMove = false; 6042 if (!mConfirmMove && (deltaX * deltaX + deltaY * deltaY) 6043 >= mTouchSlopSquare) { 6044 mPrivateHandler.removeMessages(SWITCH_TO_SHORTPRESS); 6045 mPrivateHandler.removeMessages(SWITCH_TO_LONGPRESS); 6046 mConfirmMove = true; 6047 firstMove = true; 6048 if (mTouchMode == TOUCH_DOUBLE_TAP_MODE) { 6049 mTouchMode = TOUCH_INIT_MODE; 6050 } 6051 if (USE_WEBKIT_RINGS || getSettings().supportTouchOnly()) { 6052 removeTouchHighlight(); 6053 } 6054 } 6055 // pass the touch events from UI thread to WebCore thread 6056 if (shouldForwardTouchEvent() && mConfirmMove && (firstMove 6057 || eventTime - mLastSentTouchTime > mCurrentTouchInterval)) { 6058 TouchEventData ted = new TouchEventData(); 6059 ted.mAction = action; 6060 ted.mIds = new int[1]; 6061 ted.mIds[0] = ev.getPointerId(0); 6062 ted.mPoints = new Point[1]; 6063 ted.mPoints[0] = new Point(contentX, contentY); 6064 ted.mPointsInView = new Point[1]; 6065 ted.mPointsInView[0] = new Point(x, y); 6066 ted.mMetaState = ev.getMetaState(); 6067 ted.mReprocess = mDeferTouchProcess; 6068 ted.mNativeLayer = mScrollingLayer; 6069 ted.mNativeLayerRect.set(mScrollingLayerRect); 6070 ted.mSequence = mTouchEventQueue.nextTouchSequence(); 6071 mTouchEventQueue.preQueueTouchEventData(ted); 6072 mWebViewCore.sendMessage(EventHub.TOUCH_EVENT, ted); 6073 mLastSentTouchTime = eventTime; 6074 if (mDeferTouchProcess) { 6075 break; 6076 } 6077 if (firstMove && !inFullScreenMode()) { 6078 mPrivateHandler.sendMessageDelayed(mPrivateHandler 6079 .obtainMessage(PREVENT_DEFAULT_TIMEOUT, 6080 action, 0), TAP_TIMEOUT); 6081 } 6082 } 6083 if (mTouchMode == TOUCH_DONE_MODE 6084 || mPreventDefault == PREVENT_DEFAULT_YES) { 6085 // no dragging during scroll zoom animation, or when prevent 6086 // default is yes 6087 break; 6088 } 6089 if (mVelocityTracker == null) { 6090 Log.e(LOGTAG, "Got null mVelocityTracker when " 6091 + "mPreventDefault = " + mPreventDefault 6092 + " mDeferTouchProcess = " + mDeferTouchProcess 6093 + " mTouchMode = " + mTouchMode); 6094 } else { 6095 mVelocityTracker.addMovement(ev); 6096 } 6097 if (mSelectingText && mSelectionStarted) { 6098 if (DebugFlags.WEB_VIEW) { 6099 Log.v(LOGTAG, "extend=" + contentX + "," + contentY); 6100 } 6101 ViewParent parent = getParent(); 6102 if (parent != null) { 6103 parent.requestDisallowInterceptTouchEvent(true); 6104 } 6105 mAutoScrollX = x <= mMinAutoScrollX ? -SELECT_SCROLL 6106 : x >= mMaxAutoScrollX ? SELECT_SCROLL : 0; 6107 mAutoScrollY = y <= mMinAutoScrollY ? -SELECT_SCROLL 6108 : y >= mMaxAutoScrollY ? SELECT_SCROLL : 0; 6109 if ((mAutoScrollX != 0 || mAutoScrollY != 0) 6110 && !mSentAutoScrollMessage) { 6111 mSentAutoScrollMessage = true; 6112 mPrivateHandler.sendEmptyMessageDelayed( 6113 SCROLL_SELECT_TEXT, SELECT_SCROLL_INTERVAL); 6114 } 6115 if (deltaX != 0 || deltaY != 0) { 6116 nativeExtendSelection(contentX, contentY); 6117 invalidate(); 6118 } 6119 break; 6120 } 6121 6122 if (mTouchMode != TOUCH_DRAG_MODE && 6123 mTouchMode != TOUCH_DRAG_LAYER_MODE) { 6124 6125 if (!mConfirmMove) { 6126 break; 6127 } 6128 6129 if (mPreventDefault == PREVENT_DEFAULT_MAYBE_YES 6130 || mPreventDefault == PREVENT_DEFAULT_NO_FROM_TOUCH_DOWN) { 6131 // track mLastTouchTime as we may need to do fling at 6132 // ACTION_UP 6133 mLastTouchTime = eventTime; 6134 break; 6135 } 6136 6137 // Only lock dragging to one axis if we don't have a scale in progress. 6138 // Scaling implies free-roaming movement. Note this is only ever a question 6139 // if mZoomManager.supportsPanDuringZoom() is true. 6140 final ScaleGestureDetector detector = 6141 mZoomManager.getMultiTouchGestureDetector(); 6142 mAverageAngle = calculateDragAngle(deltaX, deltaY); 6143 if (detector == null || !detector.isInProgress()) { 6144 // if it starts nearly horizontal or vertical, enforce it 6145 if (mAverageAngle < HSLOPE_TO_START_SNAP) { 6146 mSnapScrollMode = SNAP_X; 6147 mSnapPositive = deltaX > 0; 6148 mAverageAngle = ANGLE_HORIZ; 6149 } else if (mAverageAngle > VSLOPE_TO_START_SNAP) { 6150 mSnapScrollMode = SNAP_Y; 6151 mSnapPositive = deltaY > 0; 6152 mAverageAngle = ANGLE_VERT; 6153 } 6154 } 6155 6156 mTouchMode = TOUCH_DRAG_MODE; 6157 mLastTouchX = x; 6158 mLastTouchY = y; 6159 deltaX = 0; 6160 deltaY = 0; 6161 6162 startScrollingLayer(x, y); 6163 startDrag(); 6164 } 6165 6166 // do pan 6167 boolean done = false; 6168 boolean keepScrollBarsVisible = false; 6169 if (deltaX == 0 && deltaY == 0) { 6170 keepScrollBarsVisible = done = true; 6171 } else { 6172 mAverageAngle += 6173 (calculateDragAngle(deltaX, deltaY) - mAverageAngle) 6174 / MMA_WEIGHT_N; 6175 if (mSnapScrollMode != SNAP_NONE) { 6176 if (mSnapScrollMode == SNAP_Y) { 6177 // radical change means getting out of snap mode 6178 if (mAverageAngle < VSLOPE_TO_BREAK_SNAP) { 6179 mSnapScrollMode = SNAP_NONE; 6180 } 6181 } 6182 if (mSnapScrollMode == SNAP_X) { 6183 // radical change means getting out of snap mode 6184 if (mAverageAngle > HSLOPE_TO_BREAK_SNAP) { 6185 mSnapScrollMode = SNAP_NONE; 6186 } 6187 } 6188 } else { 6189 if (mAverageAngle < HSLOPE_TO_START_SNAP) { 6190 mSnapScrollMode = SNAP_X; 6191 mSnapPositive = deltaX > 0; 6192 mAverageAngle = (mAverageAngle + ANGLE_HORIZ) / 2; 6193 } else if (mAverageAngle > VSLOPE_TO_START_SNAP) { 6194 mSnapScrollMode = SNAP_Y; 6195 mSnapPositive = deltaY > 0; 6196 mAverageAngle = (mAverageAngle + ANGLE_VERT) / 2; 6197 } 6198 } 6199 if (mSnapScrollMode != SNAP_NONE) { 6200 if ((mSnapScrollMode & SNAP_X) == SNAP_X) { 6201 deltaY = 0; 6202 } else { 6203 deltaX = 0; 6204 } 6205 } 6206 mLastTouchX = x; 6207 mLastTouchY = y; 6208 if ((deltaX | deltaY) != 0) { 6209 mHeldMotionless = MOTIONLESS_FALSE; 6210 } 6211 mLastTouchTime = eventTime; 6212 } 6213 6214 doDrag(deltaX, deltaY); 6215 6216 // Turn off scrollbars when dragging a layer. 6217 if (keepScrollBarsVisible && 6218 mTouchMode != TOUCH_DRAG_LAYER_MODE) { 6219 if (mHeldMotionless != MOTIONLESS_TRUE) { 6220 mHeldMotionless = MOTIONLESS_TRUE; 6221 invalidate(); 6222 } 6223 // keep the scrollbar on the screen even there is no scroll 6224 awakenScrollBars(ViewConfiguration.getScrollDefaultDelay(), 6225 false); 6226 // return false to indicate that we can't pan out of the 6227 // view space 6228 return !done; 6229 } 6230 break; 6231 } 6232 case MotionEvent.ACTION_UP: { 6233 if (!isFocused()) requestFocus(); 6234 // pass the touch events from UI thread to WebCore thread 6235 if (shouldForwardTouchEvent()) { 6236 TouchEventData ted = new TouchEventData(); 6237 ted.mIds = new int[1]; 6238 ted.mIds[0] = ev.getPointerId(0); 6239 ted.mAction = action; 6240 ted.mPoints = new Point[1]; 6241 ted.mPoints[0] = new Point(contentX, contentY); 6242 ted.mPointsInView = new Point[1]; 6243 ted.mPointsInView[0] = new Point(x, y); 6244 ted.mMetaState = ev.getMetaState(); 6245 ted.mReprocess = mDeferTouchProcess; 6246 ted.mNativeLayer = mScrollingLayer; 6247 ted.mNativeLayerRect.set(mScrollingLayerRect); 6248 ted.mSequence = mTouchEventQueue.nextTouchSequence(); 6249 mTouchEventQueue.preQueueTouchEventData(ted); 6250 mWebViewCore.sendMessage(EventHub.TOUCH_EVENT, ted); 6251 } 6252 mLastTouchUpTime = eventTime; 6253 if (mSentAutoScrollMessage) { 6254 mAutoScrollX = mAutoScrollY = 0; 6255 } 6256 switch (mTouchMode) { 6257 case TOUCH_DOUBLE_TAP_MODE: // double tap 6258 mPrivateHandler.removeMessages(SWITCH_TO_SHORTPRESS); 6259 mPrivateHandler.removeMessages(SWITCH_TO_LONGPRESS); 6260 if (inFullScreenMode() || mDeferTouchProcess) { 6261 TouchEventData ted = new TouchEventData(); 6262 ted.mIds = new int[1]; 6263 ted.mIds[0] = ev.getPointerId(0); 6264 ted.mAction = WebViewCore.ACTION_DOUBLETAP; 6265 ted.mPoints = new Point[1]; 6266 ted.mPoints[0] = new Point(contentX, contentY); 6267 ted.mPointsInView = new Point[1]; 6268 ted.mPointsInView[0] = new Point(x, y); 6269 ted.mMetaState = ev.getMetaState(); 6270 ted.mReprocess = mDeferTouchProcess; 6271 ted.mNativeLayer = nativeScrollableLayer( 6272 contentX, contentY, 6273 ted.mNativeLayerRect, null); 6274 ted.mSequence = mTouchEventQueue.nextTouchSequence(); 6275 mTouchEventQueue.preQueueTouchEventData(ted); 6276 mWebViewCore.sendMessage(EventHub.TOUCH_EVENT, ted); 6277 } else if (mPreventDefault != PREVENT_DEFAULT_YES){ 6278 mZoomManager.handleDoubleTap(mLastTouchX, mLastTouchY); 6279 mTouchMode = TOUCH_DONE_MODE; 6280 } 6281 break; 6282 case TOUCH_INIT_MODE: // tap 6283 case TOUCH_SHORTPRESS_START_MODE: 6284 case TOUCH_SHORTPRESS_MODE: 6285 mPrivateHandler.removeMessages(SWITCH_TO_SHORTPRESS); 6286 mPrivateHandler.removeMessages(SWITCH_TO_LONGPRESS); 6287 if (mConfirmMove) { 6288 Log.w(LOGTAG, "Miss a drag as we are waiting for" + 6289 " WebCore's response for touch down."); 6290 if (mPreventDefault != PREVENT_DEFAULT_YES 6291 && (computeMaxScrollX() > 0 6292 || computeMaxScrollY() > 0)) { 6293 // If the user has performed a very quick touch 6294 // sequence it is possible that we may get here 6295 // before WebCore has had a chance to process the events. 6296 // In this case, any call to preventDefault in the 6297 // JS touch handler will not have been executed yet. 6298 // Hence we will see both the UI (now) and WebCore 6299 // (when context switches) handling the event, 6300 // regardless of whether the web developer actually 6301 // doeses preventDefault in their touch handler. This 6302 // is the nature of our asynchronous touch model. 6303 6304 // we will not rewrite drag code here, but we 6305 // will try fling if it applies. 6306 WebViewCore.reducePriority(); 6307 // to get better performance, pause updating the 6308 // picture 6309 WebViewCore.pauseUpdatePicture(mWebViewCore); 6310 // fall through to TOUCH_DRAG_MODE 6311 } else { 6312 // WebKit may consume the touch event and modify 6313 // DOM. drawContentPicture() will be called with 6314 // animateSroll as true for better performance. 6315 // Force redraw in high-quality. 6316 invalidate(); 6317 break; 6318 } 6319 } else { 6320 if (mSelectingText) { 6321 // tapping on selection or controls does nothing 6322 if (!nativeHitSelection(contentX, contentY)) { 6323 selectionDone(); 6324 } 6325 break; 6326 } 6327 // only trigger double tap if the WebView is 6328 // scalable 6329 if (mTouchMode == TOUCH_INIT_MODE 6330 && (canZoomIn() || canZoomOut())) { 6331 mPrivateHandler.sendEmptyMessageDelayed( 6332 RELEASE_SINGLE_TAP, ViewConfiguration 6333 .getDoubleTapTimeout()); 6334 } else { 6335 doShortPress(); 6336 } 6337 break; 6338 } 6339 case TOUCH_DRAG_MODE: 6340 case TOUCH_DRAG_LAYER_MODE: 6341 mPrivateHandler.removeMessages(DRAG_HELD_MOTIONLESS); 6342 mPrivateHandler.removeMessages(AWAKEN_SCROLL_BARS); 6343 // if the user waits a while w/o moving before the 6344 // up, we don't want to do a fling 6345 if (eventTime - mLastTouchTime <= MIN_FLING_TIME) { 6346 if (mVelocityTracker == null) { 6347 Log.e(LOGTAG, "Got null mVelocityTracker when " 6348 + "mPreventDefault = " 6349 + mPreventDefault 6350 + " mDeferTouchProcess = " 6351 + mDeferTouchProcess); 6352 } else { 6353 mVelocityTracker.addMovement(ev); 6354 } 6355 // set to MOTIONLESS_IGNORE so that it won't keep 6356 // removing and sending message in 6357 // drawCoreAndCursorRing() 6358 mHeldMotionless = MOTIONLESS_IGNORE; 6359 doFling(); 6360 break; 6361 } else { 6362 if (mScroller.springBack(mScrollX, mScrollY, 0, 6363 computeMaxScrollX(), 0, 6364 computeMaxScrollY())) { 6365 invalidate(); 6366 } 6367 } 6368 // redraw in high-quality, as we're done dragging 6369 mHeldMotionless = MOTIONLESS_TRUE; 6370 invalidate(); 6371 // fall through 6372 case TOUCH_DRAG_START_MODE: 6373 // TOUCH_DRAG_START_MODE should not happen for the real 6374 // device as we almost certain will get a MOVE. But this 6375 // is possible on emulator. 6376 mLastVelocity = 0; 6377 WebViewCore.resumePriority(); 6378 if (!mSelectingText) { 6379 WebViewCore.resumeUpdatePicture(mWebViewCore); 6380 } 6381 break; 6382 } 6383 stopTouch(); 6384 break; 6385 } 6386 case MotionEvent.ACTION_CANCEL: { 6387 if (mTouchMode == TOUCH_DRAG_MODE) { 6388 mScroller.springBack(mScrollX, mScrollY, 0, 6389 computeMaxScrollX(), 0, computeMaxScrollY()); 6390 invalidate(); 6391 } 6392 cancelWebCoreTouchEvent(contentX, contentY, false); 6393 cancelTouch(); 6394 break; 6395 } 6396 } 6397 return true; 6398 } 6399 6400 private void passMultiTouchToWebKit(MotionEvent ev, long sequence) { 6401 TouchEventData ted = new TouchEventData(); 6402 ted.mAction = ev.getActionMasked(); 6403 final int count = ev.getPointerCount(); 6404 ted.mIds = new int[count]; 6405 ted.mPoints = new Point[count]; 6406 ted.mPointsInView = new Point[count]; 6407 for (int c = 0; c < count; c++) { 6408 ted.mIds[c] = ev.getPointerId(c); 6409 int x = viewToContentX((int) ev.getX(c) + mScrollX); 6410 int y = viewToContentY((int) ev.getY(c) + mScrollY); 6411 ted.mPoints[c] = new Point(x, y); 6412 ted.mPointsInView[c] = new Point((int) ev.getX(c), (int) ev.getY(c)); 6413 } 6414 if (ted.mAction == MotionEvent.ACTION_POINTER_DOWN 6415 || ted.mAction == MotionEvent.ACTION_POINTER_UP) { 6416 ted.mActionIndex = ev.getActionIndex(); 6417 } 6418 ted.mMetaState = ev.getMetaState(); 6419 ted.mReprocess = true; 6420 ted.mMotionEvent = MotionEvent.obtain(ev); 6421 ted.mSequence = sequence; 6422 mTouchEventQueue.preQueueTouchEventData(ted); 6423 mWebViewCore.sendMessage(EventHub.TOUCH_EVENT, ted); 6424 cancelLongPress(); 6425 mPrivateHandler.removeMessages(SWITCH_TO_LONGPRESS); 6426 } 6427 6428 void handleMultiTouchInWebView(MotionEvent ev) { 6429 if (DebugFlags.WEB_VIEW) { 6430 Log.v(LOGTAG, "multi-touch: " + ev + " at " + ev.getEventTime() 6431 + " mTouchMode=" + mTouchMode 6432 + " numPointers=" + ev.getPointerCount() 6433 + " scrolloffset=(" + mScrollX + "," + mScrollY + ")"); 6434 } 6435 6436 final ScaleGestureDetector detector = 6437 mZoomManager.getMultiTouchGestureDetector(); 6438 6439 // A few apps use WebView but don't instantiate gesture detector. 6440 // We don't need to support multi touch for them. 6441 if (detector == null) return; 6442 6443 float x = ev.getX(); 6444 float y = ev.getY(); 6445 6446 if (mPreventDefault != PREVENT_DEFAULT_YES) { 6447 detector.onTouchEvent(ev); 6448 6449 if (detector.isInProgress()) { 6450 if (DebugFlags.WEB_VIEW) { 6451 Log.v(LOGTAG, "detector is in progress"); 6452 } 6453 mLastTouchTime = ev.getEventTime(); 6454 x = detector.getFocusX(); 6455 y = detector.getFocusY(); 6456 6457 cancelLongPress(); 6458 mPrivateHandler.removeMessages(SWITCH_TO_LONGPRESS); 6459 if (!mZoomManager.supportsPanDuringZoom()) { 6460 return; 6461 } 6462 mTouchMode = TOUCH_DRAG_MODE; 6463 if (mVelocityTracker == null) { 6464 mVelocityTracker = VelocityTracker.obtain(); 6465 } 6466 } 6467 } 6468 6469 int action = ev.getActionMasked(); 6470 if (action == MotionEvent.ACTION_POINTER_DOWN) { 6471 cancelTouch(); 6472 action = MotionEvent.ACTION_DOWN; 6473 } else if (action == MotionEvent.ACTION_POINTER_UP && ev.getPointerCount() >= 2) { 6474 // set mLastTouchX/Y to the remaining points for multi-touch. 6475 mLastTouchX = Math.round(x); 6476 mLastTouchY = Math.round(y); 6477 } else if (action == MotionEvent.ACTION_MOVE) { 6478 // negative x or y indicate it is on the edge, skip it. 6479 if (x < 0 || y < 0) { 6480 return; 6481 } 6482 } 6483 6484 handleTouchEventCommon(ev, action, Math.round(x), Math.round(y)); 6485 } 6486 6487 private void cancelWebCoreTouchEvent(int x, int y, boolean removeEvents) { 6488 if (shouldForwardTouchEvent()) { 6489 if (removeEvents) { 6490 mWebViewCore.removeMessages(EventHub.TOUCH_EVENT); 6491 } 6492 TouchEventData ted = new TouchEventData(); 6493 ted.mIds = new int[1]; 6494 ted.mIds[0] = 0; 6495 ted.mPoints = new Point[1]; 6496 ted.mPoints[0] = new Point(x, y); 6497 ted.mPointsInView = new Point[1]; 6498 int viewX = contentToViewX(x) - mScrollX; 6499 int viewY = contentToViewY(y) - mScrollY; 6500 ted.mPointsInView[0] = new Point(viewX, viewY); 6501 ted.mAction = MotionEvent.ACTION_CANCEL; 6502 ted.mNativeLayer = nativeScrollableLayer( 6503 x, y, ted.mNativeLayerRect, null); 6504 ted.mSequence = mTouchEventQueue.nextTouchSequence(); 6505 mWebViewCore.sendMessage(EventHub.TOUCH_EVENT, ted); 6506 mPreventDefault = PREVENT_DEFAULT_IGNORE; 6507 6508 if (removeEvents) { 6509 // Mark this after sending the message above; we should 6510 // be willing to ignore the cancel event that we just sent. 6511 mTouchEventQueue.ignoreCurrentlyMissingEvents(); 6512 } 6513 } 6514 } 6515 6516 private void startTouch(float x, float y, long eventTime) { 6517 // Remember where the motion event started 6518 mStartTouchX = mLastTouchX = Math.round(x); 6519 mStartTouchY = mLastTouchY = Math.round(y); 6520 mLastTouchTime = eventTime; 6521 mVelocityTracker = VelocityTracker.obtain(); 6522 mSnapScrollMode = SNAP_NONE; 6523 } 6524 6525 private void startDrag() { 6526 WebViewCore.reducePriority(); 6527 // to get better performance, pause updating the picture 6528 WebViewCore.pauseUpdatePicture(mWebViewCore); 6529 nativeSetIsScrolling(true); 6530 6531 if (!mDragFromTextInput) { 6532 nativeHideCursor(); 6533 } 6534 6535 if (mHorizontalScrollBarMode != SCROLLBAR_ALWAYSOFF 6536 || mVerticalScrollBarMode != SCROLLBAR_ALWAYSOFF) { 6537 mZoomManager.invokeZoomPicker(); 6538 } 6539 } 6540 6541 private void doDrag(int deltaX, int deltaY) { 6542 if ((deltaX | deltaY) != 0) { 6543 int oldX = mScrollX; 6544 int oldY = mScrollY; 6545 int rangeX = computeMaxScrollX(); 6546 int rangeY = computeMaxScrollY(); 6547 int overscrollDistance = mOverscrollDistance; 6548 6549 // Check for the original scrolling layer in case we change 6550 // directions. mTouchMode might be TOUCH_DRAG_MODE if we have 6551 // reached the edge of a layer but mScrollingLayer will be non-zero 6552 // if we initiated the drag on a layer. 6553 if (mScrollingLayer != 0) { 6554 final int contentX = viewToContentDimension(deltaX); 6555 final int contentY = viewToContentDimension(deltaY); 6556 6557 // Check the scrolling bounds to see if we will actually do any 6558 // scrolling. The rectangle is in document coordinates. 6559 final int maxX = mScrollingLayerRect.right; 6560 final int maxY = mScrollingLayerRect.bottom; 6561 final int resultX = Math.max(0, 6562 Math.min(mScrollingLayerRect.left + contentX, maxX)); 6563 final int resultY = Math.max(0, 6564 Math.min(mScrollingLayerRect.top + contentY, maxY)); 6565 6566 if (resultX != mScrollingLayerRect.left || 6567 resultY != mScrollingLayerRect.top) { 6568 // In case we switched to dragging the page. 6569 mTouchMode = TOUCH_DRAG_LAYER_MODE; 6570 deltaX = contentX; 6571 deltaY = contentY; 6572 oldX = mScrollingLayerRect.left; 6573 oldY = mScrollingLayerRect.top; 6574 rangeX = maxX; 6575 rangeY = maxY; 6576 } else { 6577 // Scroll the main page if we are not going to scroll the 6578 // layer. This does not reset mScrollingLayer in case the 6579 // user changes directions and the layer can scroll the 6580 // other way. 6581 mTouchMode = TOUCH_DRAG_MODE; 6582 } 6583 } 6584 6585 if (mOverScrollGlow != null) { 6586 mOverScrollGlow.setOverScrollDeltas(deltaX, deltaY); 6587 } 6588 6589 overScrollBy(deltaX, deltaY, oldX, oldY, 6590 rangeX, rangeY, 6591 mOverscrollDistance, mOverscrollDistance, true); 6592 if (mOverScrollGlow != null && mOverScrollGlow.isAnimating()) { 6593 invalidate(); 6594 } 6595 } 6596 mZoomManager.keepZoomPickerVisible(); 6597 } 6598 6599 private void stopTouch() { 6600 if (mScroller.isFinished() && !mSelectingText 6601 && (mTouchMode == TOUCH_DRAG_MODE || mTouchMode == TOUCH_DRAG_LAYER_MODE)) { 6602 WebViewCore.resumePriority(); 6603 WebViewCore.resumeUpdatePicture(mWebViewCore); 6604 nativeSetIsScrolling(false); 6605 } 6606 6607 // we also use mVelocityTracker == null to tell us that we are 6608 // not "moving around", so we can take the slower/prettier 6609 // mode in the drawing code 6610 if (mVelocityTracker != null) { 6611 mVelocityTracker.recycle(); 6612 mVelocityTracker = null; 6613 } 6614 6615 // Release any pulled glows 6616 if (mOverScrollGlow != null) { 6617 mOverScrollGlow.releaseAll(); 6618 } 6619 } 6620 6621 private void cancelTouch() { 6622 // we also use mVelocityTracker == null to tell us that we are 6623 // not "moving around", so we can take the slower/prettier 6624 // mode in the drawing code 6625 if (mVelocityTracker != null) { 6626 mVelocityTracker.recycle(); 6627 mVelocityTracker = null; 6628 } 6629 6630 if ((mTouchMode == TOUCH_DRAG_MODE 6631 || mTouchMode == TOUCH_DRAG_LAYER_MODE) && !mSelectingText) { 6632 WebViewCore.resumePriority(); 6633 WebViewCore.resumeUpdatePicture(mWebViewCore); 6634 nativeSetIsScrolling(false); 6635 } 6636 mPrivateHandler.removeMessages(SWITCH_TO_SHORTPRESS); 6637 mPrivateHandler.removeMessages(SWITCH_TO_LONGPRESS); 6638 mPrivateHandler.removeMessages(DRAG_HELD_MOTIONLESS); 6639 mPrivateHandler.removeMessages(AWAKEN_SCROLL_BARS); 6640 if (USE_WEBKIT_RINGS || getSettings().supportTouchOnly()) { 6641 removeTouchHighlight(); 6642 } 6643 mHeldMotionless = MOTIONLESS_TRUE; 6644 mTouchMode = TOUCH_DONE_MODE; 6645 nativeHideCursor(); 6646 } 6647 6648 @Override 6649 public boolean onGenericMotionEvent(MotionEvent event) { 6650 if ((event.getSource() & InputDevice.SOURCE_CLASS_POINTER) != 0) { 6651 switch (event.getAction()) { 6652 case MotionEvent.ACTION_SCROLL: { 6653 final float vscroll; 6654 final float hscroll; 6655 if ((event.getMetaState() & KeyEvent.META_SHIFT_ON) != 0) { 6656 vscroll = 0; 6657 hscroll = event.getAxisValue(MotionEvent.AXIS_VSCROLL); 6658 } else { 6659 vscroll = -event.getAxisValue(MotionEvent.AXIS_VSCROLL); 6660 hscroll = event.getAxisValue(MotionEvent.AXIS_HSCROLL); 6661 } 6662 if (hscroll != 0 || vscroll != 0) { 6663 final int vdelta = (int) (vscroll * getVerticalScrollFactor()); 6664 final int hdelta = (int) (hscroll * getHorizontalScrollFactor()); 6665 if (pinScrollBy(hdelta, vdelta, false, 0)) { 6666 return true; 6667 } 6668 } 6669 } 6670 } 6671 } 6672 return super.onGenericMotionEvent(event); 6673 } 6674 6675 private long mTrackballFirstTime = 0; 6676 private long mTrackballLastTime = 0; 6677 private float mTrackballRemainsX = 0.0f; 6678 private float mTrackballRemainsY = 0.0f; 6679 private int mTrackballXMove = 0; 6680 private int mTrackballYMove = 0; 6681 private boolean mSelectingText = false; 6682 private boolean mSelectionStarted = false; 6683 private boolean mExtendSelection = false; 6684 private boolean mDrawSelectionPointer = false; 6685 private static final int TRACKBALL_KEY_TIMEOUT = 1000; 6686 private static final int TRACKBALL_TIMEOUT = 200; 6687 private static final int TRACKBALL_WAIT = 100; 6688 private static final int TRACKBALL_SCALE = 400; 6689 private static final int TRACKBALL_SCROLL_COUNT = 5; 6690 private static final int TRACKBALL_MOVE_COUNT = 10; 6691 private static final int TRACKBALL_MULTIPLIER = 3; 6692 private static final int SELECT_CURSOR_OFFSET = 16; 6693 private static final int SELECT_SCROLL = 5; 6694 private int mSelectX = 0; 6695 private int mSelectY = 0; 6696 private boolean mFocusSizeChanged = false; 6697 private boolean mTrackballDown = false; 6698 private long mTrackballUpTime = 0; 6699 private long mLastCursorTime = 0; 6700 private Rect mLastCursorBounds; 6701 6702 // Set by default; BrowserActivity clears to interpret trackball data 6703 // directly for movement. Currently, the framework only passes 6704 // arrow key events, not trackball events, from one child to the next 6705 private boolean mMapTrackballToArrowKeys = true; 6706 6707 private DrawData mDelaySetPicture; 6708 private DrawData mLoadedPicture; 6709 6710 public void setMapTrackballToArrowKeys(boolean setMap) { 6711 checkThread(); 6712 mMapTrackballToArrowKeys = setMap; 6713 } 6714 6715 void resetTrackballTime() { 6716 mTrackballLastTime = 0; 6717 } 6718 6719 @Override 6720 public boolean onTrackballEvent(MotionEvent ev) { 6721 long time = ev.getEventTime(); 6722 if ((ev.getMetaState() & KeyEvent.META_ALT_ON) != 0) { 6723 if (ev.getY() > 0) pageDown(true); 6724 if (ev.getY() < 0) pageUp(true); 6725 return true; 6726 } 6727 if (ev.getAction() == MotionEvent.ACTION_DOWN) { 6728 if (mSelectingText) { 6729 return true; // discard press if copy in progress 6730 } 6731 mTrackballDown = true; 6732 if (mNativeClass == 0) { 6733 return false; 6734 } 6735 nativeRecordButtons(hasFocus() && hasWindowFocus(), true, true); 6736 if (time - mLastCursorTime <= TRACKBALL_TIMEOUT 6737 && !mLastCursorBounds.equals(nativeGetCursorRingBounds())) { 6738 nativeSelectBestAt(mLastCursorBounds); 6739 } 6740 if (DebugFlags.WEB_VIEW) { 6741 Log.v(LOGTAG, "onTrackballEvent down ev=" + ev 6742 + " time=" + time 6743 + " mLastCursorTime=" + mLastCursorTime); 6744 } 6745 if (isInTouchMode()) requestFocusFromTouch(); 6746 return false; // let common code in onKeyDown at it 6747 } 6748 if (ev.getAction() == MotionEvent.ACTION_UP) { 6749 // LONG_PRESS_CENTER is set in common onKeyDown 6750 mPrivateHandler.removeMessages(LONG_PRESS_CENTER); 6751 mTrackballDown = false; 6752 mTrackballUpTime = time; 6753 if (mSelectingText) { 6754 if (mExtendSelection) { 6755 copySelection(); 6756 selectionDone(); 6757 } else { 6758 mExtendSelection = true; 6759 nativeSetExtendSelection(); 6760 invalidate(); // draw the i-beam instead of the arrow 6761 } 6762 return true; // discard press if copy in progress 6763 } 6764 if (DebugFlags.WEB_VIEW) { 6765 Log.v(LOGTAG, "onTrackballEvent up ev=" + ev 6766 + " time=" + time 6767 ); 6768 } 6769 return false; // let common code in onKeyUp at it 6770 } 6771 if ((mMapTrackballToArrowKeys && (ev.getMetaState() & KeyEvent.META_SHIFT_ON) == 0) || 6772 AccessibilityManager.getInstance(mContext).isEnabled()) { 6773 if (DebugFlags.WEB_VIEW) Log.v(LOGTAG, "onTrackballEvent gmail quit"); 6774 return false; 6775 } 6776 if (mTrackballDown) { 6777 if (DebugFlags.WEB_VIEW) Log.v(LOGTAG, "onTrackballEvent down quit"); 6778 return true; // discard move if trackball is down 6779 } 6780 if (time - mTrackballUpTime < TRACKBALL_TIMEOUT) { 6781 if (DebugFlags.WEB_VIEW) Log.v(LOGTAG, "onTrackballEvent up timeout quit"); 6782 return true; 6783 } 6784 // TODO: alternatively we can do panning as touch does 6785 switchOutDrawHistory(); 6786 if (time - mTrackballLastTime > TRACKBALL_TIMEOUT) { 6787 if (DebugFlags.WEB_VIEW) { 6788 Log.v(LOGTAG, "onTrackballEvent time=" 6789 + time + " last=" + mTrackballLastTime); 6790 } 6791 mTrackballFirstTime = time; 6792 mTrackballXMove = mTrackballYMove = 0; 6793 } 6794 mTrackballLastTime = time; 6795 if (DebugFlags.WEB_VIEW) { 6796 Log.v(LOGTAG, "onTrackballEvent ev=" + ev + " time=" + time); 6797 } 6798 mTrackballRemainsX += ev.getX(); 6799 mTrackballRemainsY += ev.getY(); 6800 doTrackball(time, ev.getMetaState()); 6801 return true; 6802 } 6803 6804 void moveSelection(float xRate, float yRate) { 6805 if (mNativeClass == 0) 6806 return; 6807 int width = getViewWidth(); 6808 int height = getViewHeight(); 6809 mSelectX += xRate; 6810 mSelectY += yRate; 6811 int maxX = width + mScrollX; 6812 int maxY = height + mScrollY; 6813 mSelectX = Math.min(maxX, Math.max(mScrollX - SELECT_CURSOR_OFFSET 6814 , mSelectX)); 6815 mSelectY = Math.min(maxY, Math.max(mScrollY - SELECT_CURSOR_OFFSET 6816 , mSelectY)); 6817 if (DebugFlags.WEB_VIEW) { 6818 Log.v(LOGTAG, "moveSelection" 6819 + " mSelectX=" + mSelectX 6820 + " mSelectY=" + mSelectY 6821 + " mScrollX=" + mScrollX 6822 + " mScrollY=" + mScrollY 6823 + " xRate=" + xRate 6824 + " yRate=" + yRate 6825 ); 6826 } 6827 nativeMoveSelection(viewToContentX(mSelectX), viewToContentY(mSelectY)); 6828 int scrollX = mSelectX < mScrollX ? -SELECT_CURSOR_OFFSET 6829 : mSelectX > maxX - SELECT_CURSOR_OFFSET ? SELECT_CURSOR_OFFSET 6830 : 0; 6831 int scrollY = mSelectY < mScrollY ? -SELECT_CURSOR_OFFSET 6832 : mSelectY > maxY - SELECT_CURSOR_OFFSET ? SELECT_CURSOR_OFFSET 6833 : 0; 6834 pinScrollBy(scrollX, scrollY, true, 0); 6835 Rect select = new Rect(mSelectX, mSelectY, mSelectX + 1, mSelectY + 1); 6836 requestRectangleOnScreen(select); 6837 invalidate(); 6838 } 6839 6840 private int scaleTrackballX(float xRate, int width) { 6841 int xMove = (int) (xRate / TRACKBALL_SCALE * width); 6842 int nextXMove = xMove; 6843 if (xMove > 0) { 6844 if (xMove > mTrackballXMove) { 6845 xMove -= mTrackballXMove; 6846 } 6847 } else if (xMove < mTrackballXMove) { 6848 xMove -= mTrackballXMove; 6849 } 6850 mTrackballXMove = nextXMove; 6851 return xMove; 6852 } 6853 6854 private int scaleTrackballY(float yRate, int height) { 6855 int yMove = (int) (yRate / TRACKBALL_SCALE * height); 6856 int nextYMove = yMove; 6857 if (yMove > 0) { 6858 if (yMove > mTrackballYMove) { 6859 yMove -= mTrackballYMove; 6860 } 6861 } else if (yMove < mTrackballYMove) { 6862 yMove -= mTrackballYMove; 6863 } 6864 mTrackballYMove = nextYMove; 6865 return yMove; 6866 } 6867 6868 private int keyCodeToSoundsEffect(int keyCode) { 6869 switch(keyCode) { 6870 case KeyEvent.KEYCODE_DPAD_UP: 6871 return SoundEffectConstants.NAVIGATION_UP; 6872 case KeyEvent.KEYCODE_DPAD_RIGHT: 6873 return SoundEffectConstants.NAVIGATION_RIGHT; 6874 case KeyEvent.KEYCODE_DPAD_DOWN: 6875 return SoundEffectConstants.NAVIGATION_DOWN; 6876 case KeyEvent.KEYCODE_DPAD_LEFT: 6877 return SoundEffectConstants.NAVIGATION_LEFT; 6878 } 6879 throw new IllegalArgumentException("keyCode must be one of " + 6880 "{KEYCODE_DPAD_UP, KEYCODE_DPAD_RIGHT, KEYCODE_DPAD_DOWN, " + 6881 "KEYCODE_DPAD_LEFT}."); 6882 } 6883 6884 private void doTrackball(long time, int metaState) { 6885 int elapsed = (int) (mTrackballLastTime - mTrackballFirstTime); 6886 if (elapsed == 0) { 6887 elapsed = TRACKBALL_TIMEOUT; 6888 } 6889 float xRate = mTrackballRemainsX * 1000 / elapsed; 6890 float yRate = mTrackballRemainsY * 1000 / elapsed; 6891 int viewWidth = getViewWidth(); 6892 int viewHeight = getViewHeight(); 6893 if (mSelectingText) { 6894 if (!mDrawSelectionPointer) { 6895 // The last selection was made by touch, disabling drawing the 6896 // selection pointer. Allow the trackball to adjust the 6897 // position of the touch control. 6898 mSelectX = contentToViewX(nativeSelectionX()); 6899 mSelectY = contentToViewY(nativeSelectionY()); 6900 mDrawSelectionPointer = mExtendSelection = true; 6901 nativeSetExtendSelection(); 6902 } 6903 moveSelection(scaleTrackballX(xRate, viewWidth), 6904 scaleTrackballY(yRate, viewHeight)); 6905 mTrackballRemainsX = mTrackballRemainsY = 0; 6906 return; 6907 } 6908 float ax = Math.abs(xRate); 6909 float ay = Math.abs(yRate); 6910 float maxA = Math.max(ax, ay); 6911 if (DebugFlags.WEB_VIEW) { 6912 Log.v(LOGTAG, "doTrackball elapsed=" + elapsed 6913 + " xRate=" + xRate 6914 + " yRate=" + yRate 6915 + " mTrackballRemainsX=" + mTrackballRemainsX 6916 + " mTrackballRemainsY=" + mTrackballRemainsY); 6917 } 6918 int width = mContentWidth - viewWidth; 6919 int height = mContentHeight - viewHeight; 6920 if (width < 0) width = 0; 6921 if (height < 0) height = 0; 6922 ax = Math.abs(mTrackballRemainsX * TRACKBALL_MULTIPLIER); 6923 ay = Math.abs(mTrackballRemainsY * TRACKBALL_MULTIPLIER); 6924 maxA = Math.max(ax, ay); 6925 int count = Math.max(0, (int) maxA); 6926 int oldScrollX = mScrollX; 6927 int oldScrollY = mScrollY; 6928 if (count > 0) { 6929 int selectKeyCode = ax < ay ? mTrackballRemainsY < 0 ? 6930 KeyEvent.KEYCODE_DPAD_UP : KeyEvent.KEYCODE_DPAD_DOWN : 6931 mTrackballRemainsX < 0 ? KeyEvent.KEYCODE_DPAD_LEFT : 6932 KeyEvent.KEYCODE_DPAD_RIGHT; 6933 count = Math.min(count, TRACKBALL_MOVE_COUNT); 6934 if (DebugFlags.WEB_VIEW) { 6935 Log.v(LOGTAG, "doTrackball keyCode=" + selectKeyCode 6936 + " count=" + count 6937 + " mTrackballRemainsX=" + mTrackballRemainsX 6938 + " mTrackballRemainsY=" + mTrackballRemainsY); 6939 } 6940 if (mNativeClass != 0 && nativePageShouldHandleShiftAndArrows()) { 6941 for (int i = 0; i < count; i++) { 6942 letPageHandleNavKey(selectKeyCode, time, true, metaState); 6943 } 6944 letPageHandleNavKey(selectKeyCode, time, false, metaState); 6945 } else if (navHandledKey(selectKeyCode, count, false, time)) { 6946 playSoundEffect(keyCodeToSoundsEffect(selectKeyCode)); 6947 } 6948 mTrackballRemainsX = mTrackballRemainsY = 0; 6949 } 6950 if (count >= TRACKBALL_SCROLL_COUNT) { 6951 int xMove = scaleTrackballX(xRate, width); 6952 int yMove = scaleTrackballY(yRate, height); 6953 if (DebugFlags.WEB_VIEW) { 6954 Log.v(LOGTAG, "doTrackball pinScrollBy" 6955 + " count=" + count 6956 + " xMove=" + xMove + " yMove=" + yMove 6957 + " mScrollX-oldScrollX=" + (mScrollX-oldScrollX) 6958 + " mScrollY-oldScrollY=" + (mScrollY-oldScrollY) 6959 ); 6960 } 6961 if (Math.abs(mScrollX - oldScrollX) > Math.abs(xMove)) { 6962 xMove = 0; 6963 } 6964 if (Math.abs(mScrollY - oldScrollY) > Math.abs(yMove)) { 6965 yMove = 0; 6966 } 6967 if (xMove != 0 || yMove != 0) { 6968 pinScrollBy(xMove, yMove, true, 0); 6969 } 6970 } 6971 } 6972 6973 /** 6974 * Compute the maximum horizontal scroll position. Used by {@link OverScrollGlow}. 6975 * @return Maximum horizontal scroll position within real content 6976 */ 6977 int computeMaxScrollX() { 6978 return Math.max(computeRealHorizontalScrollRange() - getViewWidth(), 0); 6979 } 6980 6981 /** 6982 * Compute the maximum vertical scroll position. Used by {@link OverScrollGlow}. 6983 * @return Maximum vertical scroll position within real content 6984 */ 6985 int computeMaxScrollY() { 6986 return Math.max(computeRealVerticalScrollRange() + getTitleHeight() 6987 - getViewHeightWithTitle(), 0); 6988 } 6989 6990 boolean updateScrollCoordinates(int x, int y) { 6991 int oldX = mScrollX; 6992 int oldY = mScrollY; 6993 mScrollX = x; 6994 mScrollY = y; 6995 if (oldX != mScrollX || oldY != mScrollY) { 6996 onScrollChanged(mScrollX, mScrollY, oldX, oldY); 6997 return true; 6998 } else { 6999 return false; 7000 } 7001 } 7002 7003 public void flingScroll(int vx, int vy) { 7004 checkThread(); 7005 mScroller.fling(mScrollX, mScrollY, vx, vy, 0, computeMaxScrollX(), 0, 7006 computeMaxScrollY(), mOverflingDistance, mOverflingDistance); 7007 invalidate(); 7008 } 7009 7010 private void doFling() { 7011 if (mVelocityTracker == null) { 7012 return; 7013 } 7014 int maxX = computeMaxScrollX(); 7015 int maxY = computeMaxScrollY(); 7016 7017 mVelocityTracker.computeCurrentVelocity(1000, mMaximumFling); 7018 int vx = (int) mVelocityTracker.getXVelocity(); 7019 int vy = (int) mVelocityTracker.getYVelocity(); 7020 7021 int scrollX = mScrollX; 7022 int scrollY = mScrollY; 7023 int overscrollDistance = mOverscrollDistance; 7024 int overflingDistance = mOverflingDistance; 7025 7026 // Use the layer's scroll data if applicable. 7027 if (mTouchMode == TOUCH_DRAG_LAYER_MODE) { 7028 scrollX = mScrollingLayerRect.left; 7029 scrollY = mScrollingLayerRect.top; 7030 maxX = mScrollingLayerRect.right; 7031 maxY = mScrollingLayerRect.bottom; 7032 // No overscrolling for layers. 7033 overscrollDistance = overflingDistance = 0; 7034 } 7035 7036 if (mSnapScrollMode != SNAP_NONE) { 7037 if ((mSnapScrollMode & SNAP_X) == SNAP_X) { 7038 vy = 0; 7039 } else { 7040 vx = 0; 7041 } 7042 } 7043 if ((maxX == 0 && vy == 0) || (maxY == 0 && vx == 0)) { 7044 WebViewCore.resumePriority(); 7045 if (!mSelectingText) { 7046 WebViewCore.resumeUpdatePicture(mWebViewCore); 7047 } 7048 if (mScroller.springBack(scrollX, scrollY, 0, maxX, 0, maxY)) { 7049 invalidate(); 7050 } 7051 return; 7052 } 7053 float currentVelocity = mScroller.getCurrVelocity(); 7054 float velocity = (float) Math.hypot(vx, vy); 7055 if (mLastVelocity > 0 && currentVelocity > 0 && velocity 7056 > mLastVelocity * MINIMUM_VELOCITY_RATIO_FOR_ACCELERATION) { 7057 float deltaR = (float) (Math.abs(Math.atan2(mLastVelY, mLastVelX) 7058 - Math.atan2(vy, vx))); 7059 final float circle = (float) (Math.PI) * 2.0f; 7060 if (deltaR > circle * 0.9f || deltaR < circle * 0.1f) { 7061 vx += currentVelocity * mLastVelX / mLastVelocity; 7062 vy += currentVelocity * mLastVelY / mLastVelocity; 7063 velocity = (float) Math.hypot(vx, vy); 7064 if (DebugFlags.WEB_VIEW) { 7065 Log.v(LOGTAG, "doFling vx= " + vx + " vy=" + vy); 7066 } 7067 } else if (DebugFlags.WEB_VIEW) { 7068 Log.v(LOGTAG, "doFling missed " + deltaR / circle); 7069 } 7070 } else if (DebugFlags.WEB_VIEW) { 7071 Log.v(LOGTAG, "doFling start last=" + mLastVelocity 7072 + " current=" + currentVelocity 7073 + " vx=" + vx + " vy=" + vy 7074 + " maxX=" + maxX + " maxY=" + maxY 7075 + " scrollX=" + scrollX + " scrollY=" + scrollY 7076 + " layer=" + mScrollingLayer); 7077 } 7078 7079 // Allow sloppy flings without overscrolling at the edges. 7080 if ((scrollX == 0 || scrollX == maxX) && Math.abs(vx) < Math.abs(vy)) { 7081 vx = 0; 7082 } 7083 if ((scrollY == 0 || scrollY == maxY) && Math.abs(vy) < Math.abs(vx)) { 7084 vy = 0; 7085 } 7086 7087 if (overscrollDistance < overflingDistance) { 7088 if ((vx > 0 && scrollX == -overscrollDistance) || 7089 (vx < 0 && scrollX == maxX + overscrollDistance)) { 7090 vx = 0; 7091 } 7092 if ((vy > 0 && scrollY == -overscrollDistance) || 7093 (vy < 0 && scrollY == maxY + overscrollDistance)) { 7094 vy = 0; 7095 } 7096 } 7097 7098 mLastVelX = vx; 7099 mLastVelY = vy; 7100 mLastVelocity = velocity; 7101 7102 // no horizontal overscroll if the content just fits 7103 mScroller.fling(scrollX, scrollY, -vx, -vy, 0, maxX, 0, maxY, 7104 maxX == 0 ? 0 : overflingDistance, overflingDistance); 7105 // Duration is calculated based on velocity. With range boundaries and overscroll 7106 // we may not know how long the final animation will take. (Hence the deprecation 7107 // warning on the call below.) It's not a big deal for scroll bars but if webcore 7108 // resumes during this effect we will take a performance hit. See computeScroll; 7109 // we resume webcore there when the animation is finished. 7110 final int time = mScroller.getDuration(); 7111 7112 // Suppress scrollbars for layer scrolling. 7113 if (mTouchMode != TOUCH_DRAG_LAYER_MODE) { 7114 awakenScrollBars(time); 7115 } 7116 7117 invalidate(); 7118 } 7119 7120 /** 7121 * Returns a view containing zoom controls i.e. +/- buttons. The caller is 7122 * in charge of installing this view to the view hierarchy. This view will 7123 * become visible when the user starts scrolling via touch and fade away if 7124 * the user does not interact with it. 7125 * <p/> 7126 * API version 3 introduces a built-in zoom mechanism that is shown 7127 * automatically by the MapView. This is the preferred approach for 7128 * showing the zoom UI. 7129 * 7130 * @deprecated The built-in zoom mechanism is preferred, see 7131 * {@link WebSettings#setBuiltInZoomControls(boolean)}. 7132 */ 7133 @Deprecated 7134 public View getZoomControls() { 7135 checkThread(); 7136 if (!getSettings().supportZoom()) { 7137 Log.w(LOGTAG, "This WebView doesn't support zoom."); 7138 return null; 7139 } 7140 return mZoomManager.getExternalZoomPicker(); 7141 } 7142 7143 void dismissZoomControl() { 7144 mZoomManager.dismissZoomPicker(); 7145 } 7146 7147 float getDefaultZoomScale() { 7148 return mZoomManager.getDefaultScale(); 7149 } 7150 7151 /** 7152 * @return TRUE if the WebView can be zoomed in. 7153 */ 7154 public boolean canZoomIn() { 7155 checkThread(); 7156 return mZoomManager.canZoomIn(); 7157 } 7158 7159 /** 7160 * @return TRUE if the WebView can be zoomed out. 7161 */ 7162 public boolean canZoomOut() { 7163 checkThread(); 7164 return mZoomManager.canZoomOut(); 7165 } 7166 7167 /** 7168 * Perform zoom in in the webview 7169 * @return TRUE if zoom in succeeds. FALSE if no zoom changes. 7170 */ 7171 public boolean zoomIn() { 7172 checkThread(); 7173 return mZoomManager.zoomIn(); 7174 } 7175 7176 /** 7177 * Perform zoom out in the webview 7178 * @return TRUE if zoom out succeeds. FALSE if no zoom changes. 7179 */ 7180 public boolean zoomOut() { 7181 checkThread(); 7182 return mZoomManager.zoomOut(); 7183 } 7184 7185 private void updateSelection() { 7186 if (mNativeClass == 0) { 7187 return; 7188 } 7189 // mLastTouchX and mLastTouchY are the point in the current viewport 7190 int contentX = viewToContentX(mLastTouchX + mScrollX); 7191 int contentY = viewToContentY(mLastTouchY + mScrollY); 7192 int slop = viewToContentDimension(mNavSlop); 7193 Rect rect = new Rect(contentX - slop, contentY - slop, 7194 contentX + slop, contentY + slop); 7195 nativeSelectBestAt(rect); 7196 mInitialHitTestResult = hitTestResult(null); 7197 } 7198 7199 /** 7200 * Scroll the focused text field to match the WebTextView 7201 * @param xPercent New x position of the WebTextView from 0 to 1. 7202 */ 7203 /*package*/ void scrollFocusedTextInputX(float xPercent) { 7204 if (!inEditingMode() || mWebViewCore == null) { 7205 return; 7206 } 7207 mWebViewCore.sendMessage(EventHub.SCROLL_TEXT_INPUT, 0, 7208 new Float(xPercent)); 7209 } 7210 7211 /** 7212 * Scroll the focused textarea vertically to match the WebTextView 7213 * @param y New y position of the WebTextView in view coordinates 7214 */ 7215 /* package */ void scrollFocusedTextInputY(int y) { 7216 if (!inEditingMode() || mWebViewCore == null) { 7217 return; 7218 } 7219 mWebViewCore.sendMessage(EventHub.SCROLL_TEXT_INPUT, 0, viewToContentDimension(y)); 7220 } 7221 7222 /** 7223 * Set our starting point and time for a drag from the WebTextView. 7224 */ 7225 /*package*/ void initiateTextFieldDrag(float x, float y, long eventTime) { 7226 if (!inEditingMode()) { 7227 return; 7228 } 7229 mLastTouchX = Math.round(x + mWebTextView.getLeft() - mScrollX); 7230 mLastTouchY = Math.round(y + mWebTextView.getTop() - mScrollY); 7231 mLastTouchTime = eventTime; 7232 if (!mScroller.isFinished()) { 7233 abortAnimation(); 7234 mPrivateHandler.removeMessages(RESUME_WEBCORE_PRIORITY); 7235 } 7236 mSnapScrollMode = SNAP_NONE; 7237 mVelocityTracker = VelocityTracker.obtain(); 7238 mTouchMode = TOUCH_DRAG_START_MODE; 7239 } 7240 7241 /** 7242 * Given a motion event from the WebTextView, set its location to our 7243 * coordinates, and handle the event. 7244 */ 7245 /*package*/ boolean textFieldDrag(MotionEvent event) { 7246 if (!inEditingMode()) { 7247 return false; 7248 } 7249 mDragFromTextInput = true; 7250 event.offsetLocation((float) (mWebTextView.getLeft() - mScrollX), 7251 (float) (mWebTextView.getTop() - mScrollY)); 7252 boolean result = onTouchEvent(event); 7253 mDragFromTextInput = false; 7254 return result; 7255 } 7256 7257 /** 7258 * Due a touch up from a WebTextView. This will be handled by webkit to 7259 * change the selection. 7260 * @param event MotionEvent in the WebTextView's coordinates. 7261 */ 7262 /*package*/ void touchUpOnTextField(MotionEvent event) { 7263 if (!inEditingMode()) { 7264 return; 7265 } 7266 int x = viewToContentX((int) event.getX() + mWebTextView.getLeft()); 7267 int y = viewToContentY((int) event.getY() + mWebTextView.getTop()); 7268 int slop = viewToContentDimension(mNavSlop); 7269 nativeMotionUp(x, y, slop); 7270 } 7271 7272 /** 7273 * Called when pressing the center key or trackball on a textfield. 7274 */ 7275 /*package*/ void centerKeyPressOnTextField() { 7276 mWebViewCore.sendMessage(EventHub.CLICK, nativeCursorFramePointer(), 7277 nativeCursorNodePointer()); 7278 } 7279 7280 private void doShortPress() { 7281 if (mNativeClass == 0) { 7282 return; 7283 } 7284 if (mPreventDefault == PREVENT_DEFAULT_YES) { 7285 return; 7286 } 7287 mTouchMode = TOUCH_DONE_MODE; 7288 switchOutDrawHistory(); 7289 // mLastTouchX and mLastTouchY are the point in the current viewport 7290 int contentX = viewToContentX(mLastTouchX + mScrollX); 7291 int contentY = viewToContentY(mLastTouchY + mScrollY); 7292 int slop = viewToContentDimension(mNavSlop); 7293 if (USE_WEBKIT_RINGS && !mTouchHighlightRegion.isEmpty()) { 7294 // set mTouchHighlightRequested to 0 to cause an immediate 7295 // drawing of the touch rings 7296 mTouchHighlightRequested = 0; 7297 invalidate(mTouchHighlightRegion.getBounds()); 7298 mPrivateHandler.postDelayed(new Runnable() { 7299 @Override 7300 public void run() { 7301 removeTouchHighlight(); 7302 } 7303 }, ViewConfiguration.getPressedStateDuration()); 7304 } 7305 if (getSettings().supportTouchOnly()) { 7306 removeTouchHighlight(); 7307 WebViewCore.TouchUpData touchUpData = new WebViewCore.TouchUpData(); 7308 // use "0" as generation id to inform WebKit to use the same x/y as 7309 // it used when processing GET_TOUCH_HIGHLIGHT_RECTS 7310 touchUpData.mMoveGeneration = 0; 7311 mWebViewCore.sendMessage(EventHub.TOUCH_UP, touchUpData); 7312 } else if (nativePointInNavCache(contentX, contentY, slop)) { 7313 WebViewCore.MotionUpData motionUpData = new WebViewCore 7314 .MotionUpData(); 7315 motionUpData.mFrame = nativeCacheHitFramePointer(); 7316 motionUpData.mNode = nativeCacheHitNodePointer(); 7317 motionUpData.mBounds = nativeCacheHitNodeBounds(); 7318 motionUpData.mX = contentX; 7319 motionUpData.mY = contentY; 7320 mWebViewCore.sendMessageAtFrontOfQueue(EventHub.VALID_NODE_BOUNDS, 7321 motionUpData); 7322 } else { 7323 doMotionUp(contentX, contentY); 7324 } 7325 } 7326 7327 private void doMotionUp(int contentX, int contentY) { 7328 int slop = viewToContentDimension(mNavSlop); 7329 if (nativeMotionUp(contentX, contentY, slop) && mLogEvent) { 7330 EventLog.writeEvent(EventLogTags.BROWSER_SNAP_CENTER); 7331 } 7332 if (nativeHasCursorNode() && !nativeCursorIsTextInput()) { 7333 playSoundEffect(SoundEffectConstants.CLICK); 7334 } 7335 } 7336 7337 /** 7338 * Returns plugin bounds if x/y in content coordinates corresponds to a 7339 * plugin. Otherwise a NULL rectangle is returned. 7340 */ 7341 Rect getPluginBounds(int x, int y) { 7342 int slop = viewToContentDimension(mNavSlop); 7343 if (nativePointInNavCache(x, y, slop) && nativeCacheHitIsPlugin()) { 7344 return nativeCacheHitNodeBounds(); 7345 } else { 7346 return null; 7347 } 7348 } 7349 7350 /* 7351 * Return true if the rect (e.g. plugin) is fully visible and maximized 7352 * inside the WebView. 7353 */ 7354 boolean isRectFitOnScreen(Rect rect) { 7355 final int rectWidth = rect.width(); 7356 final int rectHeight = rect.height(); 7357 final int viewWidth = getViewWidth(); 7358 final int viewHeight = getViewHeightWithTitle(); 7359 float scale = Math.min((float) viewWidth / rectWidth, (float) viewHeight / rectHeight); 7360 scale = mZoomManager.computeScaleWithLimits(scale); 7361 return !mZoomManager.willScaleTriggerZoom(scale) 7362 && contentToViewX(rect.left) >= mScrollX 7363 && contentToViewX(rect.right) <= mScrollX + viewWidth 7364 && contentToViewY(rect.top) >= mScrollY 7365 && contentToViewY(rect.bottom) <= mScrollY + viewHeight; 7366 } 7367 7368 /* 7369 * Maximize and center the rectangle, specified in the document coordinate 7370 * space, inside the WebView. If the zoom doesn't need to be changed, do an 7371 * animated scroll to center it. If the zoom needs to be changed, find the 7372 * zoom center and do a smooth zoom transition. The rect is in document 7373 * coordinates 7374 */ 7375 void centerFitRect(Rect rect) { 7376 final int rectWidth = rect.width(); 7377 final int rectHeight = rect.height(); 7378 final int viewWidth = getViewWidth(); 7379 final int viewHeight = getViewHeightWithTitle(); 7380 float scale = Math.min((float) viewWidth / rectWidth, (float) viewHeight 7381 / rectHeight); 7382 scale = mZoomManager.computeScaleWithLimits(scale); 7383 if (!mZoomManager.willScaleTriggerZoom(scale)) { 7384 pinScrollTo(contentToViewX(rect.left + rectWidth / 2) - viewWidth / 2, 7385 contentToViewY(rect.top + rectHeight / 2) - viewHeight / 2, 7386 true, 0); 7387 } else { 7388 float actualScale = mZoomManager.getScale(); 7389 float oldScreenX = rect.left * actualScale - mScrollX; 7390 float rectViewX = rect.left * scale; 7391 float rectViewWidth = rectWidth * scale; 7392 float newMaxWidth = mContentWidth * scale; 7393 float newScreenX = (viewWidth - rectViewWidth) / 2; 7394 // pin the newX to the WebView 7395 if (newScreenX > rectViewX) { 7396 newScreenX = rectViewX; 7397 } else if (newScreenX > (newMaxWidth - rectViewX - rectViewWidth)) { 7398 newScreenX = viewWidth - (newMaxWidth - rectViewX); 7399 } 7400 float zoomCenterX = (oldScreenX * scale - newScreenX * actualScale) 7401 / (scale - actualScale); 7402 float oldScreenY = rect.top * actualScale + getTitleHeight() 7403 - mScrollY; 7404 float rectViewY = rect.top * scale + getTitleHeight(); 7405 float rectViewHeight = rectHeight * scale; 7406 float newMaxHeight = mContentHeight * scale + getTitleHeight(); 7407 float newScreenY = (viewHeight - rectViewHeight) / 2; 7408 // pin the newY to the WebView 7409 if (newScreenY > rectViewY) { 7410 newScreenY = rectViewY; 7411 } else if (newScreenY > (newMaxHeight - rectViewY - rectViewHeight)) { 7412 newScreenY = viewHeight - (newMaxHeight - rectViewY); 7413 } 7414 float zoomCenterY = (oldScreenY * scale - newScreenY * actualScale) 7415 / (scale - actualScale); 7416 mZoomManager.setZoomCenter(zoomCenterX, zoomCenterY); 7417 mZoomManager.startZoomAnimation(scale, false); 7418 } 7419 } 7420 7421 // Called by JNI to handle a touch on a node representing an email address, 7422 // address, or phone number 7423 private void overrideLoading(String url) { 7424 mCallbackProxy.uiOverrideUrlLoading(url); 7425 } 7426 7427 @Override 7428 public boolean requestFocus(int direction, Rect previouslyFocusedRect) { 7429 // FIXME: If a subwindow is showing find, and the user touches the 7430 // background window, it can steal focus. 7431 if (mFindIsUp) return false; 7432 boolean result = false; 7433 if (inEditingMode()) { 7434 result = mWebTextView.requestFocus(direction, 7435 previouslyFocusedRect); 7436 } else { 7437 result = super.requestFocus(direction, previouslyFocusedRect); 7438 if (mWebViewCore.getSettings().getNeedInitialFocus() && !isInTouchMode()) { 7439 // For cases such as GMail, where we gain focus from a direction, 7440 // we want to move to the first available link. 7441 // FIXME: If there are no visible links, we may not want to 7442 int fakeKeyDirection = 0; 7443 switch(direction) { 7444 case View.FOCUS_UP: 7445 fakeKeyDirection = KeyEvent.KEYCODE_DPAD_UP; 7446 break; 7447 case View.FOCUS_DOWN: 7448 fakeKeyDirection = KeyEvent.KEYCODE_DPAD_DOWN; 7449 break; 7450 case View.FOCUS_LEFT: 7451 fakeKeyDirection = KeyEvent.KEYCODE_DPAD_LEFT; 7452 break; 7453 case View.FOCUS_RIGHT: 7454 fakeKeyDirection = KeyEvent.KEYCODE_DPAD_RIGHT; 7455 break; 7456 default: 7457 return result; 7458 } 7459 if (mNativeClass != 0 && !nativeHasCursorNode()) { 7460 navHandledKey(fakeKeyDirection, 1, true, 0); 7461 } 7462 } 7463 } 7464 return result; 7465 } 7466 7467 @Override 7468 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 7469 super.onMeasure(widthMeasureSpec, heightMeasureSpec); 7470 7471 int heightMode = MeasureSpec.getMode(heightMeasureSpec); 7472 int heightSize = MeasureSpec.getSize(heightMeasureSpec); 7473 int widthMode = MeasureSpec.getMode(widthMeasureSpec); 7474 int widthSize = MeasureSpec.getSize(widthMeasureSpec); 7475 7476 int measuredHeight = heightSize; 7477 int measuredWidth = widthSize; 7478 7479 // Grab the content size from WebViewCore. 7480 int contentHeight = contentToViewDimension(mContentHeight); 7481 int contentWidth = contentToViewDimension(mContentWidth); 7482 7483// Log.d(LOGTAG, "------- measure " + heightMode); 7484 7485 if (heightMode != MeasureSpec.EXACTLY) { 7486 mHeightCanMeasure = true; 7487 measuredHeight = contentHeight; 7488 if (heightMode == MeasureSpec.AT_MOST) { 7489 // If we are larger than the AT_MOST height, then our height can 7490 // no longer be measured and we should scroll internally. 7491 if (measuredHeight > heightSize) { 7492 measuredHeight = heightSize; 7493 mHeightCanMeasure = false; 7494 measuredHeight |= MEASURED_STATE_TOO_SMALL; 7495 } 7496 } 7497 } else { 7498 mHeightCanMeasure = false; 7499 } 7500 if (mNativeClass != 0) { 7501 nativeSetHeightCanMeasure(mHeightCanMeasure); 7502 } 7503 // For the width, always use the given size unless unspecified. 7504 if (widthMode == MeasureSpec.UNSPECIFIED) { 7505 mWidthCanMeasure = true; 7506 measuredWidth = contentWidth; 7507 } else { 7508 if (measuredWidth < contentWidth) { 7509 measuredWidth |= MEASURED_STATE_TOO_SMALL; 7510 } 7511 mWidthCanMeasure = false; 7512 } 7513 7514 synchronized (this) { 7515 setMeasuredDimension(measuredWidth, measuredHeight); 7516 } 7517 } 7518 7519 @Override 7520 public boolean requestChildRectangleOnScreen(View child, 7521 Rect rect, 7522 boolean immediate) { 7523 if (mNativeClass == 0) { 7524 return false; 7525 } 7526 // don't scroll while in zoom animation. When it is done, we will adjust 7527 // the necessary components (e.g., WebTextView if it is in editing mode) 7528 if (mZoomManager.isFixedLengthAnimationInProgress()) { 7529 return false; 7530 } 7531 7532 rect.offset(child.getLeft() - child.getScrollX(), 7533 child.getTop() - child.getScrollY()); 7534 7535 Rect content = new Rect(viewToContentX(mScrollX), 7536 viewToContentY(mScrollY), 7537 viewToContentX(mScrollX + getWidth() 7538 - getVerticalScrollbarWidth()), 7539 viewToContentY(mScrollY + getViewHeightWithTitle())); 7540 content = nativeSubtractLayers(content); 7541 int screenTop = contentToViewY(content.top); 7542 int screenBottom = contentToViewY(content.bottom); 7543 int height = screenBottom - screenTop; 7544 int scrollYDelta = 0; 7545 7546 if (rect.bottom > screenBottom) { 7547 int oneThirdOfScreenHeight = height / 3; 7548 if (rect.height() > 2 * oneThirdOfScreenHeight) { 7549 // If the rectangle is too tall to fit in the bottom two thirds 7550 // of the screen, place it at the top. 7551 scrollYDelta = rect.top - screenTop; 7552 } else { 7553 // If the rectangle will still fit on screen, we want its 7554 // top to be in the top third of the screen. 7555 scrollYDelta = rect.top - (screenTop + oneThirdOfScreenHeight); 7556 } 7557 } else if (rect.top < screenTop) { 7558 scrollYDelta = rect.top - screenTop; 7559 } 7560 7561 int screenLeft = contentToViewX(content.left); 7562 int screenRight = contentToViewX(content.right); 7563 int width = screenRight - screenLeft; 7564 int scrollXDelta = 0; 7565 7566 if (rect.right > screenRight && rect.left > screenLeft) { 7567 if (rect.width() > width) { 7568 scrollXDelta += (rect.left - screenLeft); 7569 } else { 7570 scrollXDelta += (rect.right - screenRight); 7571 } 7572 } else if (rect.left < screenLeft) { 7573 scrollXDelta -= (screenLeft - rect.left); 7574 } 7575 7576 if ((scrollYDelta | scrollXDelta) != 0) { 7577 return pinScrollBy(scrollXDelta, scrollYDelta, !immediate, 0); 7578 } 7579 7580 return false; 7581 } 7582 7583 /* package */ void replaceTextfieldText(int oldStart, int oldEnd, 7584 String replace, int newStart, int newEnd) { 7585 WebViewCore.ReplaceTextData arg = new WebViewCore.ReplaceTextData(); 7586 arg.mReplace = replace; 7587 arg.mNewStart = newStart; 7588 arg.mNewEnd = newEnd; 7589 mTextGeneration++; 7590 arg.mTextGeneration = mTextGeneration; 7591 mWebViewCore.sendMessage(EventHub.REPLACE_TEXT, oldStart, oldEnd, arg); 7592 } 7593 7594 /* package */ void passToJavaScript(String currentText, KeyEvent event) { 7595 WebViewCore.JSKeyData arg = new WebViewCore.JSKeyData(); 7596 arg.mEvent = event; 7597 arg.mCurrentText = currentText; 7598 // Increase our text generation number, and pass it to webcore thread 7599 mTextGeneration++; 7600 mWebViewCore.sendMessage(EventHub.PASS_TO_JS, mTextGeneration, 0, arg); 7601 // WebKit's document state is not saved until about to leave the page. 7602 // To make sure the host application, like Browser, has the up to date 7603 // document state when it goes to background, we force to save the 7604 // document state. 7605 mWebViewCore.removeMessages(EventHub.SAVE_DOCUMENT_STATE); 7606 mWebViewCore.sendMessageDelayed(EventHub.SAVE_DOCUMENT_STATE, 7607 cursorData(), 1000); 7608 } 7609 7610 /** 7611 * @hide 7612 */ 7613 public synchronized WebViewCore getWebViewCore() { 7614 return mWebViewCore; 7615 } 7616 7617 /** 7618 * Used only by TouchEventQueue to store pending touch events. 7619 */ 7620 private static class QueuedTouch { 7621 long mSequence; 7622 MotionEvent mEvent; // Optional 7623 TouchEventData mTed; // Optional 7624 7625 QueuedTouch mNext; 7626 7627 public QueuedTouch set(TouchEventData ted) { 7628 mSequence = ted.mSequence; 7629 mTed = ted; 7630 mEvent = null; 7631 mNext = null; 7632 return this; 7633 } 7634 7635 public QueuedTouch set(MotionEvent ev, long sequence) { 7636 mEvent = MotionEvent.obtain(ev); 7637 mSequence = sequence; 7638 mTed = null; 7639 mNext = null; 7640 return this; 7641 } 7642 7643 public QueuedTouch add(QueuedTouch other) { 7644 if (other.mSequence < mSequence) { 7645 other.mNext = this; 7646 return other; 7647 } 7648 7649 QueuedTouch insertAt = this; 7650 while (insertAt.mNext != null && insertAt.mNext.mSequence < other.mSequence) { 7651 insertAt = insertAt.mNext; 7652 } 7653 other.mNext = insertAt.mNext; 7654 insertAt.mNext = other; 7655 return this; 7656 } 7657 } 7658 7659 /** 7660 * WebView handles touch events asynchronously since some events must be passed to WebKit 7661 * for potentially slower processing. TouchEventQueue serializes touch events regardless 7662 * of which path they take to ensure that no events are ever processed out of order 7663 * by WebView. 7664 */ 7665 private class TouchEventQueue { 7666 private long mNextTouchSequence = Long.MIN_VALUE + 1; 7667 private long mLastHandledTouchSequence = Long.MIN_VALUE; 7668 private long mIgnoreUntilSequence = Long.MIN_VALUE + 1; 7669 7670 // Events waiting to be processed. 7671 private QueuedTouch mTouchEventQueue; 7672 7673 // Known events that are waiting on a response before being enqueued. 7674 private QueuedTouch mPreQueue; 7675 7676 // Pool of QueuedTouch objects saved for later use. 7677 private QueuedTouch mQueuedTouchRecycleBin; 7678 private int mQueuedTouchRecycleCount; 7679 7680 private long mLastEventTime = Long.MAX_VALUE; 7681 private static final int MAX_RECYCLED_QUEUED_TOUCH = 15; 7682 7683 // milliseconds until we abandon hope of getting all of a previous gesture 7684 private static final int QUEUED_GESTURE_TIMEOUT = 1000; 7685 7686 private QueuedTouch obtainQueuedTouch() { 7687 if (mQueuedTouchRecycleBin != null) { 7688 QueuedTouch result = mQueuedTouchRecycleBin; 7689 mQueuedTouchRecycleBin = result.mNext; 7690 mQueuedTouchRecycleCount--; 7691 return result; 7692 } 7693 return new QueuedTouch(); 7694 } 7695 7696 /** 7697 * Allow events with any currently missing sequence numbers to be skipped in processing. 7698 */ 7699 public void ignoreCurrentlyMissingEvents() { 7700 mIgnoreUntilSequence = mNextTouchSequence; 7701 7702 // Run any events we have available and complete, pre-queued or otherwise. 7703 runQueuedAndPreQueuedEvents(); 7704 } 7705 7706 private void runQueuedAndPreQueuedEvents() { 7707 QueuedTouch qd = mPreQueue; 7708 boolean fromPreQueue = true; 7709 while (qd != null && qd.mSequence == mLastHandledTouchSequence + 1) { 7710 handleQueuedTouch(qd); 7711 QueuedTouch recycleMe = qd; 7712 if (fromPreQueue) { 7713 mPreQueue = qd.mNext; 7714 } else { 7715 mTouchEventQueue = qd.mNext; 7716 } 7717 recycleQueuedTouch(recycleMe); 7718 mLastHandledTouchSequence++; 7719 7720 long nextPre = mPreQueue != null ? mPreQueue.mSequence : Long.MAX_VALUE; 7721 long nextQueued = mTouchEventQueue != null ? 7722 mTouchEventQueue.mSequence : Long.MAX_VALUE; 7723 fromPreQueue = nextPre < nextQueued; 7724 qd = fromPreQueue ? mPreQueue : mTouchEventQueue; 7725 } 7726 } 7727 7728 /** 7729 * Add a TouchEventData to the pre-queue. 7730 * 7731 * An event in the pre-queue is an event that we know about that 7732 * has been sent to webkit, but that we haven't received back and 7733 * enqueued into the normal touch queue yet. If webkit ever times 7734 * out and we need to ignore currently missing events, we'll run 7735 * events from the pre-queue to patch the holes. 7736 * 7737 * @param ted TouchEventData to pre-queue 7738 */ 7739 public void preQueueTouchEventData(TouchEventData ted) { 7740 QueuedTouch newTouch = obtainQueuedTouch().set(ted); 7741 if (mPreQueue == null) { 7742 mPreQueue = newTouch; 7743 } else { 7744 QueuedTouch insertionPoint = mPreQueue; 7745 while (insertionPoint.mNext != null && 7746 insertionPoint.mNext.mSequence < newTouch.mSequence) { 7747 insertionPoint = insertionPoint.mNext; 7748 } 7749 newTouch.mNext = insertionPoint.mNext; 7750 insertionPoint.mNext = newTouch; 7751 } 7752 } 7753 7754 private void recycleQueuedTouch(QueuedTouch qd) { 7755 if (mQueuedTouchRecycleCount < MAX_RECYCLED_QUEUED_TOUCH) { 7756 qd.mNext = mQueuedTouchRecycleBin; 7757 mQueuedTouchRecycleBin = qd; 7758 mQueuedTouchRecycleCount++; 7759 } 7760 } 7761 7762 /** 7763 * Reset the touch event queue. This will dump any pending events 7764 * and reset the sequence numbering. 7765 */ 7766 public void reset() { 7767 mNextTouchSequence = Long.MIN_VALUE + 1; 7768 mLastHandledTouchSequence = Long.MIN_VALUE; 7769 mIgnoreUntilSequence = Long.MIN_VALUE + 1; 7770 while (mTouchEventQueue != null) { 7771 QueuedTouch recycleMe = mTouchEventQueue; 7772 mTouchEventQueue = mTouchEventQueue.mNext; 7773 recycleQueuedTouch(recycleMe); 7774 } 7775 while (mPreQueue != null) { 7776 QueuedTouch recycleMe = mPreQueue; 7777 mPreQueue = mPreQueue.mNext; 7778 recycleQueuedTouch(recycleMe); 7779 } 7780 } 7781 7782 /** 7783 * Return the next valid sequence number for tagging incoming touch events. 7784 * @return The next touch event sequence number 7785 */ 7786 public long nextTouchSequence() { 7787 return mNextTouchSequence++; 7788 } 7789 7790 /** 7791 * Enqueue a touch event in the form of TouchEventData. 7792 * The sequence number will be read from the mSequence field of the argument. 7793 * 7794 * If the touch event's sequence number is the next in line to be processed, it will 7795 * be handled before this method returns. Any subsequent events that have already 7796 * been queued will also be processed in their proper order. 7797 * 7798 * @param ted Touch data to be processed in order. 7799 * @return true if the event was processed before returning, false if it was just enqueued. 7800 */ 7801 public boolean enqueueTouchEvent(TouchEventData ted) { 7802 // Remove from the pre-queue if present 7803 QueuedTouch preQueue = mPreQueue; 7804 if (preQueue != null) { 7805 // On exiting this block, preQueue is set to the pre-queued QueuedTouch object 7806 // if it was present in the pre-queue, and removed from the pre-queue itself. 7807 if (preQueue.mSequence == ted.mSequence) { 7808 mPreQueue = preQueue.mNext; 7809 } else { 7810 QueuedTouch prev = preQueue; 7811 preQueue = null; 7812 while (prev.mNext != null) { 7813 if (prev.mNext.mSequence == ted.mSequence) { 7814 preQueue = prev.mNext; 7815 prev.mNext = preQueue.mNext; 7816 break; 7817 } else { 7818 prev = prev.mNext; 7819 } 7820 } 7821 } 7822 } 7823 7824 if (ted.mSequence < mLastHandledTouchSequence) { 7825 // Stale event and we already moved on; drop it. (Should not be common.) 7826 Log.w(LOGTAG, "Stale touch event " + MotionEvent.actionToString(ted.mAction) + 7827 " received from webcore; ignoring"); 7828 return false; 7829 } 7830 7831 if (dropStaleGestures(ted.mMotionEvent, ted.mSequence)) { 7832 return false; 7833 } 7834 7835 // dropStaleGestures above might have fast-forwarded us to 7836 // an event we have already. 7837 runNextQueuedEvents(); 7838 7839 if (mLastHandledTouchSequence + 1 == ted.mSequence) { 7840 if (preQueue != null) { 7841 recycleQueuedTouch(preQueue); 7842 preQueue = null; 7843 } 7844 handleQueuedTouchEventData(ted); 7845 7846 mLastHandledTouchSequence++; 7847 7848 // Do we have any more? Run them if so. 7849 runNextQueuedEvents(); 7850 } else { 7851 // Reuse the pre-queued object if we had it. 7852 QueuedTouch qd = preQueue != null ? preQueue : obtainQueuedTouch().set(ted); 7853 mTouchEventQueue = mTouchEventQueue == null ? qd : mTouchEventQueue.add(qd); 7854 } 7855 return true; 7856 } 7857 7858 /** 7859 * Enqueue a touch event in the form of a MotionEvent from the framework. 7860 * 7861 * If the touch event's sequence number is the next in line to be processed, it will 7862 * be handled before this method returns. Any subsequent events that have already 7863 * been queued will also be processed in their proper order. 7864 * 7865 * @param ev MotionEvent to be processed in order 7866 */ 7867 public void enqueueTouchEvent(MotionEvent ev) { 7868 final long sequence = nextTouchSequence(); 7869 7870 if (dropStaleGestures(ev, sequence)) { 7871 return; 7872 } 7873 7874 // dropStaleGestures above might have fast-forwarded us to 7875 // an event we have already. 7876 runNextQueuedEvents(); 7877 7878 if (mLastHandledTouchSequence + 1 == sequence) { 7879 handleQueuedMotionEvent(ev); 7880 7881 mLastHandledTouchSequence++; 7882 7883 // Do we have any more? Run them if so. 7884 runNextQueuedEvents(); 7885 } else { 7886 QueuedTouch qd = obtainQueuedTouch().set(ev, sequence); 7887 mTouchEventQueue = mTouchEventQueue == null ? qd : mTouchEventQueue.add(qd); 7888 } 7889 } 7890 7891 private void runNextQueuedEvents() { 7892 QueuedTouch qd = mTouchEventQueue; 7893 while (qd != null && qd.mSequence == mLastHandledTouchSequence + 1) { 7894 handleQueuedTouch(qd); 7895 QueuedTouch recycleMe = qd; 7896 qd = qd.mNext; 7897 recycleQueuedTouch(recycleMe); 7898 mLastHandledTouchSequence++; 7899 } 7900 mTouchEventQueue = qd; 7901 } 7902 7903 private boolean dropStaleGestures(MotionEvent ev, long sequence) { 7904 if (ev != null && ev.getAction() == MotionEvent.ACTION_MOVE && !mConfirmMove) { 7905 // This is to make sure that we don't attempt to process a tap 7906 // or long press when webkit takes too long to get back to us. 7907 // The movement will be properly confirmed when we process the 7908 // enqueued event later. 7909 final int dx = Math.round(ev.getX()) - mLastTouchX; 7910 final int dy = Math.round(ev.getY()) - mLastTouchY; 7911 if (dx * dx + dy * dy > mTouchSlopSquare) { 7912 mPrivateHandler.removeMessages(SWITCH_TO_SHORTPRESS); 7913 mPrivateHandler.removeMessages(SWITCH_TO_LONGPRESS); 7914 } 7915 } 7916 7917 if (mTouchEventQueue == null) { 7918 return sequence <= mLastHandledTouchSequence; 7919 } 7920 7921 // If we have a new down event and it's been a while since the last event 7922 // we saw, catch up as best we can and keep going. 7923 if (ev != null && ev.getAction() == MotionEvent.ACTION_DOWN) { 7924 long eventTime = ev.getEventTime(); 7925 long lastHandledEventTime = mLastEventTime; 7926 if (eventTime > lastHandledEventTime + QUEUED_GESTURE_TIMEOUT) { 7927 Log.w(LOGTAG, "Got ACTION_DOWN but still waiting on stale event. " + 7928 "Catching up."); 7929 runQueuedAndPreQueuedEvents(); 7930 7931 // Drop leftovers that we truly don't have. 7932 QueuedTouch qd = mTouchEventQueue; 7933 while (qd != null && qd.mSequence < sequence) { 7934 QueuedTouch recycleMe = qd; 7935 qd = qd.mNext; 7936 recycleQueuedTouch(recycleMe); 7937 } 7938 mTouchEventQueue = qd; 7939 mLastHandledTouchSequence = sequence - 1; 7940 } 7941 } 7942 7943 if (mIgnoreUntilSequence - 1 > mLastHandledTouchSequence) { 7944 QueuedTouch qd = mTouchEventQueue; 7945 while (qd != null && qd.mSequence < mIgnoreUntilSequence) { 7946 QueuedTouch recycleMe = qd; 7947 qd = qd.mNext; 7948 recycleQueuedTouch(recycleMe); 7949 } 7950 mTouchEventQueue = qd; 7951 mLastHandledTouchSequence = mIgnoreUntilSequence - 1; 7952 } 7953 7954 if (mPreQueue != null) { 7955 // Drop stale prequeued events 7956 QueuedTouch qd = mPreQueue; 7957 while (qd != null && qd.mSequence < mIgnoreUntilSequence) { 7958 QueuedTouch recycleMe = qd; 7959 qd = qd.mNext; 7960 recycleQueuedTouch(recycleMe); 7961 } 7962 mPreQueue = qd; 7963 } 7964 7965 return sequence <= mLastHandledTouchSequence; 7966 } 7967 7968 private void handleQueuedTouch(QueuedTouch qt) { 7969 if (qt.mTed != null) { 7970 handleQueuedTouchEventData(qt.mTed); 7971 } else { 7972 handleQueuedMotionEvent(qt.mEvent); 7973 qt.mEvent.recycle(); 7974 } 7975 } 7976 7977 private void handleQueuedMotionEvent(MotionEvent ev) { 7978 mLastEventTime = ev.getEventTime(); 7979 int action = ev.getActionMasked(); 7980 if (ev.getPointerCount() > 1) { // Multi-touch 7981 handleMultiTouchInWebView(ev); 7982 } else { 7983 final ScaleGestureDetector detector = mZoomManager.getMultiTouchGestureDetector(); 7984 if (detector != null && mPreventDefault != PREVENT_DEFAULT_YES) { 7985 // ScaleGestureDetector needs a consistent event stream to operate properly. 7986 // It won't take any action with fewer than two pointers, but it needs to 7987 // update internal bookkeeping state. 7988 detector.onTouchEvent(ev); 7989 } 7990 7991 handleTouchEventCommon(ev, action, Math.round(ev.getX()), Math.round(ev.getY())); 7992 } 7993 } 7994 7995 private void handleQueuedTouchEventData(TouchEventData ted) { 7996 if (ted.mMotionEvent != null) { 7997 mLastEventTime = ted.mMotionEvent.getEventTime(); 7998 } 7999 if (!ted.mReprocess) { 8000 if (ted.mAction == MotionEvent.ACTION_DOWN 8001 && mPreventDefault == PREVENT_DEFAULT_MAYBE_YES) { 8002 // if prevent default is called from WebCore, UI 8003 // will not handle the rest of the touch events any 8004 // more. 8005 mPreventDefault = ted.mNativeResult ? PREVENT_DEFAULT_YES 8006 : PREVENT_DEFAULT_NO_FROM_TOUCH_DOWN; 8007 } else if (ted.mAction == MotionEvent.ACTION_MOVE 8008 && mPreventDefault == PREVENT_DEFAULT_NO_FROM_TOUCH_DOWN) { 8009 // the return for the first ACTION_MOVE will decide 8010 // whether UI will handle touch or not. Currently no 8011 // support for alternating prevent default 8012 mPreventDefault = ted.mNativeResult ? PREVENT_DEFAULT_YES 8013 : PREVENT_DEFAULT_NO; 8014 } 8015 if (mPreventDefault == PREVENT_DEFAULT_YES) { 8016 mTouchHighlightRegion.setEmpty(); 8017 } 8018 } else { 8019 if (ted.mPoints.length > 1) { // multi-touch 8020 if (!ted.mNativeResult && mPreventDefault != PREVENT_DEFAULT_YES) { 8021 mPreventDefault = PREVENT_DEFAULT_NO; 8022 handleMultiTouchInWebView(ted.mMotionEvent); 8023 } else { 8024 mPreventDefault = PREVENT_DEFAULT_YES; 8025 } 8026 return; 8027 } 8028 8029 // prevent default is not called in WebCore, so the 8030 // message needs to be reprocessed in UI 8031 if (!ted.mNativeResult) { 8032 // Following is for single touch. 8033 switch (ted.mAction) { 8034 case MotionEvent.ACTION_DOWN: 8035 mLastDeferTouchX = ted.mPointsInView[0].x; 8036 mLastDeferTouchY = ted.mPointsInView[0].y; 8037 mDeferTouchMode = TOUCH_INIT_MODE; 8038 break; 8039 case MotionEvent.ACTION_MOVE: { 8040 // no snapping in defer process 8041 int x = ted.mPointsInView[0].x; 8042 int y = ted.mPointsInView[0].y; 8043 8044 if (mDeferTouchMode != TOUCH_DRAG_MODE) { 8045 mDeferTouchMode = TOUCH_DRAG_MODE; 8046 mLastDeferTouchX = x; 8047 mLastDeferTouchY = y; 8048 startScrollingLayer(x, y); 8049 startDrag(); 8050 } 8051 int deltaX = pinLocX((int) (mScrollX 8052 + mLastDeferTouchX - x)) 8053 - mScrollX; 8054 int deltaY = pinLocY((int) (mScrollY 8055 + mLastDeferTouchY - y)) 8056 - mScrollY; 8057 doDrag(deltaX, deltaY); 8058 if (deltaX != 0) mLastDeferTouchX = x; 8059 if (deltaY != 0) mLastDeferTouchY = y; 8060 break; 8061 } 8062 case MotionEvent.ACTION_UP: 8063 case MotionEvent.ACTION_CANCEL: 8064 if (mDeferTouchMode == TOUCH_DRAG_MODE) { 8065 // no fling in defer process 8066 mScroller.springBack(mScrollX, mScrollY, 0, 8067 computeMaxScrollX(), 0, 8068 computeMaxScrollY()); 8069 invalidate(); 8070 WebViewCore.resumePriority(); 8071 WebViewCore.resumeUpdatePicture(mWebViewCore); 8072 } 8073 mDeferTouchMode = TOUCH_DONE_MODE; 8074 break; 8075 case WebViewCore.ACTION_DOUBLETAP: 8076 // doDoubleTap() needs mLastTouchX/Y as anchor 8077 mLastDeferTouchX = ted.mPointsInView[0].x; 8078 mLastDeferTouchY = ted.mPointsInView[0].y; 8079 mZoomManager.handleDoubleTap(mLastTouchX, mLastTouchY); 8080 mDeferTouchMode = TOUCH_DONE_MODE; 8081 break; 8082 case WebViewCore.ACTION_LONGPRESS: 8083 HitTestResult hitTest = getHitTestResult(); 8084 if (hitTest != null && hitTest.mType 8085 != HitTestResult.UNKNOWN_TYPE) { 8086 performLongClick(); 8087 } 8088 mDeferTouchMode = TOUCH_DONE_MODE; 8089 break; 8090 } 8091 } 8092 } 8093 } 8094 } 8095 8096 //------------------------------------------------------------------------- 8097 // Methods can be called from a separate thread, like WebViewCore 8098 // If it needs to call the View system, it has to send message. 8099 //------------------------------------------------------------------------- 8100 8101 /** 8102 * General handler to receive message coming from webkit thread 8103 */ 8104 class PrivateHandler extends Handler { 8105 @Override 8106 public void handleMessage(Message msg) { 8107 // exclude INVAL_RECT_MSG_ID since it is frequently output 8108 if (DebugFlags.WEB_VIEW && msg.what != INVAL_RECT_MSG_ID) { 8109 if (msg.what >= FIRST_PRIVATE_MSG_ID 8110 && msg.what <= LAST_PRIVATE_MSG_ID) { 8111 Log.v(LOGTAG, HandlerPrivateDebugString[msg.what 8112 - FIRST_PRIVATE_MSG_ID]); 8113 } else if (msg.what >= FIRST_PACKAGE_MSG_ID 8114 && msg.what <= LAST_PACKAGE_MSG_ID) { 8115 Log.v(LOGTAG, HandlerPackageDebugString[msg.what 8116 - FIRST_PACKAGE_MSG_ID]); 8117 } else { 8118 Log.v(LOGTAG, Integer.toString(msg.what)); 8119 } 8120 } 8121 if (mWebViewCore == null) { 8122 // after WebView's destroy() is called, skip handling messages. 8123 return; 8124 } 8125 if (mBlockWebkitViewMessages 8126 && msg.what != WEBCORE_INITIALIZED_MSG_ID) { 8127 // Blocking messages from webkit 8128 return; 8129 } 8130 switch (msg.what) { 8131 case REMEMBER_PASSWORD: { 8132 mDatabase.setUsernamePassword( 8133 msg.getData().getString("host"), 8134 msg.getData().getString("username"), 8135 msg.getData().getString("password")); 8136 ((Message) msg.obj).sendToTarget(); 8137 break; 8138 } 8139 case NEVER_REMEMBER_PASSWORD: { 8140 mDatabase.setUsernamePassword( 8141 msg.getData().getString("host"), null, null); 8142 ((Message) msg.obj).sendToTarget(); 8143 break; 8144 } 8145 case PREVENT_DEFAULT_TIMEOUT: { 8146 // if timeout happens, cancel it so that it won't block UI 8147 // to continue handling touch events 8148 if ((msg.arg1 == MotionEvent.ACTION_DOWN 8149 && mPreventDefault == PREVENT_DEFAULT_MAYBE_YES) 8150 || (msg.arg1 == MotionEvent.ACTION_MOVE 8151 && mPreventDefault == PREVENT_DEFAULT_NO_FROM_TOUCH_DOWN)) { 8152 cancelWebCoreTouchEvent( 8153 viewToContentX(mLastTouchX + mScrollX), 8154 viewToContentY(mLastTouchY + mScrollY), 8155 true); 8156 } 8157 break; 8158 } 8159 case SCROLL_SELECT_TEXT: { 8160 if (mAutoScrollX == 0 && mAutoScrollY == 0) { 8161 mSentAutoScrollMessage = false; 8162 break; 8163 } 8164 if (mScrollingLayer == 0) { 8165 pinScrollBy(mAutoScrollX, mAutoScrollY, true, 0); 8166 } else { 8167 mScrollingLayerRect.left += mAutoScrollX; 8168 mScrollingLayerRect.top += mAutoScrollY; 8169 nativeScrollLayer(mScrollingLayer, 8170 mScrollingLayerRect.left, 8171 mScrollingLayerRect.top); 8172 invalidate(); 8173 } 8174 sendEmptyMessageDelayed( 8175 SCROLL_SELECT_TEXT, SELECT_SCROLL_INTERVAL); 8176 break; 8177 } 8178 case SWITCH_TO_SHORTPRESS: { 8179 mInitialHitTestResult = null; // set by updateSelection() 8180 if (mTouchMode == TOUCH_INIT_MODE) { 8181 if (!getSettings().supportTouchOnly() 8182 && mPreventDefault != PREVENT_DEFAULT_YES) { 8183 mTouchMode = TOUCH_SHORTPRESS_START_MODE; 8184 updateSelection(); 8185 } else { 8186 // set to TOUCH_SHORTPRESS_MODE so that it won't 8187 // trigger double tap any more 8188 mTouchMode = TOUCH_SHORTPRESS_MODE; 8189 } 8190 } else if (mTouchMode == TOUCH_DOUBLE_TAP_MODE) { 8191 mTouchMode = TOUCH_DONE_MODE; 8192 } 8193 break; 8194 } 8195 case SWITCH_TO_LONGPRESS: { 8196 if (USE_WEBKIT_RINGS || getSettings().supportTouchOnly()) { 8197 removeTouchHighlight(); 8198 } 8199 if (inFullScreenMode() || mDeferTouchProcess) { 8200 TouchEventData ted = new TouchEventData(); 8201 ted.mAction = WebViewCore.ACTION_LONGPRESS; 8202 ted.mIds = new int[1]; 8203 ted.mIds[0] = 0; 8204 ted.mPoints = new Point[1]; 8205 ted.mPoints[0] = new Point(viewToContentX(mLastTouchX + mScrollX), 8206 viewToContentY(mLastTouchY + mScrollY)); 8207 ted.mPointsInView = new Point[1]; 8208 ted.mPointsInView[0] = new Point(mLastTouchX, mLastTouchY); 8209 // metaState for long press is tricky. Should it be the 8210 // state when the press started or when the press was 8211 // released? Or some intermediary key state? For 8212 // simplicity for now, we don't set it. 8213 ted.mMetaState = 0; 8214 ted.mReprocess = mDeferTouchProcess; 8215 ted.mNativeLayer = nativeScrollableLayer( 8216 ted.mPoints[0].x, ted.mPoints[0].y, 8217 ted.mNativeLayerRect, null); 8218 ted.mSequence = mTouchEventQueue.nextTouchSequence(); 8219 mTouchEventQueue.preQueueTouchEventData(ted); 8220 mWebViewCore.sendMessage(EventHub.TOUCH_EVENT, ted); 8221 } else if (mPreventDefault != PREVENT_DEFAULT_YES) { 8222 mTouchMode = TOUCH_DONE_MODE; 8223 performLongClick(); 8224 } 8225 break; 8226 } 8227 case RELEASE_SINGLE_TAP: { 8228 doShortPress(); 8229 break; 8230 } 8231 case SCROLL_TO_MSG_ID: { 8232 // arg1 = animate, arg2 = onlyIfImeIsShowing 8233 // obj = Point(x, y) 8234 if (msg.arg2 == 1) { 8235 // This scroll is intended to bring the textfield into 8236 // view, but is only necessary if the IME is showing 8237 InputMethodManager imm = InputMethodManager.peekInstance(); 8238 if (imm == null || !imm.isAcceptingText() 8239 || (!imm.isActive(WebView.this) && (!inEditingMode() 8240 || !imm.isActive(mWebTextView)))) { 8241 break; 8242 } 8243 } 8244 final Point p = (Point) msg.obj; 8245 if (msg.arg1 == 1) { 8246 spawnContentScrollTo(p.x, p.y); 8247 } else { 8248 setContentScrollTo(p.x, p.y); 8249 } 8250 break; 8251 } 8252 case UPDATE_ZOOM_RANGE: { 8253 WebViewCore.ViewState viewState = (WebViewCore.ViewState) msg.obj; 8254 // mScrollX contains the new minPrefWidth 8255 mZoomManager.updateZoomRange(viewState, getViewWidth(), viewState.mScrollX); 8256 break; 8257 } 8258 case REPLACE_BASE_CONTENT: { 8259 nativeReplaceBaseContent(msg.arg1); 8260 break; 8261 } 8262 case NEW_PICTURE_MSG_ID: { 8263 // called for new content 8264 final WebViewCore.DrawData draw = (WebViewCore.DrawData) msg.obj; 8265 setNewPicture(draw, true); 8266 break; 8267 } 8268 case WEBCORE_INITIALIZED_MSG_ID: 8269 // nativeCreate sets mNativeClass to a non-zero value 8270 String drawableDir = BrowserFrame.getRawResFilename( 8271 BrowserFrame.DRAWABLEDIR, mContext); 8272 nativeCreate(msg.arg1, drawableDir); 8273 if (mDelaySetPicture != null) { 8274 setNewPicture(mDelaySetPicture, true); 8275 mDelaySetPicture = null; 8276 } 8277 break; 8278 case UPDATE_TEXTFIELD_TEXT_MSG_ID: 8279 // Make sure that the textfield is currently focused 8280 // and representing the same node as the pointer. 8281 if (inEditingMode() && 8282 mWebTextView.isSameTextField(msg.arg1)) { 8283 if (msg.arg2 == mTextGeneration) { 8284 String text = (String) msg.obj; 8285 if (null == text) { 8286 text = ""; 8287 } 8288 mWebTextView.setTextAndKeepSelection(text); 8289 } 8290 } 8291 break; 8292 case REQUEST_KEYBOARD_WITH_SELECTION_MSG_ID: 8293 displaySoftKeyboard(true); 8294 // fall through to UPDATE_TEXT_SELECTION_MSG_ID 8295 case UPDATE_TEXT_SELECTION_MSG_ID: 8296 updateTextSelectionFromMessage(msg.arg1, msg.arg2, 8297 (WebViewCore.TextSelectionData) msg.obj); 8298 break; 8299 case FORM_DID_BLUR: 8300 if (inEditingMode() 8301 && mWebTextView.isSameTextField(msg.arg1)) { 8302 hideSoftKeyboard(); 8303 } 8304 break; 8305 case RETURN_LABEL: 8306 if (inEditingMode() 8307 && mWebTextView.isSameTextField(msg.arg1)) { 8308 mWebTextView.setHint((String) msg.obj); 8309 InputMethodManager imm 8310 = InputMethodManager.peekInstance(); 8311 // The hint is propagated to the IME in 8312 // onCreateInputConnection. If the IME is already 8313 // active, restart it so that its hint text is updated. 8314 if (imm != null && imm.isActive(mWebTextView)) { 8315 imm.restartInput(mWebTextView); 8316 } 8317 } 8318 break; 8319 case UNHANDLED_NAV_KEY: 8320 navHandledKey(msg.arg1, 1, false, 0); 8321 break; 8322 case UPDATE_TEXT_ENTRY_MSG_ID: 8323 // this is sent after finishing resize in WebViewCore. Make 8324 // sure the text edit box is still on the screen. 8325 if (inEditingMode() && nativeCursorIsTextInput()) { 8326 rebuildWebTextView(); 8327 } 8328 break; 8329 case CLEAR_TEXT_ENTRY: 8330 clearTextEntry(); 8331 break; 8332 case INVAL_RECT_MSG_ID: { 8333 Rect r = (Rect)msg.obj; 8334 if (r == null) { 8335 invalidate(); 8336 } else { 8337 // we need to scale r from content into view coords, 8338 // which viewInvalidate() does for us 8339 viewInvalidate(r.left, r.top, r.right, r.bottom); 8340 } 8341 break; 8342 } 8343 case REQUEST_FORM_DATA: 8344 AutoCompleteAdapter adapter = (AutoCompleteAdapter) msg.obj; 8345 if (mWebTextView.isSameTextField(msg.arg1)) { 8346 mWebTextView.setAdapterCustom(adapter); 8347 } 8348 break; 8349 case RESUME_WEBCORE_PRIORITY: 8350 WebViewCore.resumePriority(); 8351 WebViewCore.resumeUpdatePicture(mWebViewCore); 8352 break; 8353 8354 case LONG_PRESS_CENTER: 8355 // as this is shared by keydown and trackballdown, reset all 8356 // the states 8357 mGotCenterDown = false; 8358 mTrackballDown = false; 8359 performLongClick(); 8360 break; 8361 8362 case WEBCORE_NEED_TOUCH_EVENTS: 8363 mForwardTouchEvents = (msg.arg1 != 0); 8364 break; 8365 8366 case PREVENT_TOUCH_ID: 8367 if (inFullScreenMode()) { 8368 break; 8369 } 8370 TouchEventData ted = (TouchEventData) msg.obj; 8371 8372 if (mTouchEventQueue.enqueueTouchEvent(ted)) { 8373 // WebCore is responding to us; remove pending timeout. 8374 // It will be re-posted when needed. 8375 removeMessages(PREVENT_DEFAULT_TIMEOUT); 8376 } 8377 break; 8378 8379 case REQUEST_KEYBOARD: 8380 if (msg.arg1 == 0) { 8381 hideSoftKeyboard(); 8382 } else { 8383 displaySoftKeyboard(false); 8384 } 8385 break; 8386 8387 case FIND_AGAIN: 8388 // Ignore if find has been dismissed. 8389 if (mFindIsUp && mFindCallback != null) { 8390 mFindCallback.findAll(); 8391 } 8392 break; 8393 8394 case DRAG_HELD_MOTIONLESS: 8395 mHeldMotionless = MOTIONLESS_TRUE; 8396 invalidate(); 8397 // fall through to keep scrollbars awake 8398 8399 case AWAKEN_SCROLL_BARS: 8400 if (mTouchMode == TOUCH_DRAG_MODE 8401 && mHeldMotionless == MOTIONLESS_TRUE) { 8402 awakenScrollBars(ViewConfiguration 8403 .getScrollDefaultDelay(), false); 8404 mPrivateHandler.sendMessageDelayed(mPrivateHandler 8405 .obtainMessage(AWAKEN_SCROLL_BARS), 8406 ViewConfiguration.getScrollDefaultDelay()); 8407 } 8408 break; 8409 8410 case DO_MOTION_UP: 8411 doMotionUp(msg.arg1, msg.arg2); 8412 break; 8413 8414 case SCREEN_ON: 8415 setKeepScreenOn(msg.arg1 == 1); 8416 break; 8417 8418 case ENTER_FULLSCREEN_VIDEO: 8419 int layerId = msg.arg1; 8420 8421 String url = (String) msg.obj; 8422 if (mHTML5VideoViewProxy != null) { 8423 mHTML5VideoViewProxy.enterFullScreenVideo(layerId, url); 8424 } 8425 break; 8426 8427 case SHOW_FULLSCREEN: { 8428 View view = (View) msg.obj; 8429 int orientation = msg.arg1; 8430 int npp = msg.arg2; 8431 8432 if (inFullScreenMode()) { 8433 Log.w(LOGTAG, "Should not have another full screen."); 8434 dismissFullScreenMode(); 8435 } 8436 mFullScreenHolder = new PluginFullScreenHolder(WebView.this, orientation, npp); 8437 mFullScreenHolder.setContentView(view); 8438 mFullScreenHolder.show(); 8439 8440 break; 8441 } 8442 case HIDE_FULLSCREEN: 8443 dismissFullScreenMode(); 8444 break; 8445 8446 case DOM_FOCUS_CHANGED: 8447 if (inEditingMode()) { 8448 nativeClearCursor(); 8449 rebuildWebTextView(); 8450 } 8451 break; 8452 8453 case SHOW_RECT_MSG_ID: { 8454 WebViewCore.ShowRectData data = (WebViewCore.ShowRectData) msg.obj; 8455 int x = mScrollX; 8456 int left = contentToViewX(data.mLeft); 8457 int width = contentToViewDimension(data.mWidth); 8458 int maxWidth = contentToViewDimension(data.mContentWidth); 8459 int viewWidth = getViewWidth(); 8460 if (width < viewWidth) { 8461 // center align 8462 x += left + width / 2 - mScrollX - viewWidth / 2; 8463 } else { 8464 x += (int) (left + data.mXPercentInDoc * width 8465 - mScrollX - data.mXPercentInView * viewWidth); 8466 } 8467 if (DebugFlags.WEB_VIEW) { 8468 Log.v(LOGTAG, "showRectMsg=(left=" + left + ",width=" + 8469 width + ",maxWidth=" + maxWidth + 8470 ",viewWidth=" + viewWidth + ",x=" 8471 + x + ",xPercentInDoc=" + data.mXPercentInDoc + 8472 ",xPercentInView=" + data.mXPercentInView+ ")"); 8473 } 8474 // use the passing content width to cap x as the current 8475 // mContentWidth may not be updated yet 8476 x = Math.max(0, 8477 (Math.min(maxWidth, x + viewWidth)) - viewWidth); 8478 int top = contentToViewY(data.mTop); 8479 int height = contentToViewDimension(data.mHeight); 8480 int maxHeight = contentToViewDimension(data.mContentHeight); 8481 int viewHeight = getViewHeight(); 8482 int y = (int) (top + data.mYPercentInDoc * height - 8483 data.mYPercentInView * viewHeight); 8484 if (DebugFlags.WEB_VIEW) { 8485 Log.v(LOGTAG, "showRectMsg=(top=" + top + ",height=" + 8486 height + ",maxHeight=" + maxHeight + 8487 ",viewHeight=" + viewHeight + ",y=" 8488 + y + ",yPercentInDoc=" + data.mYPercentInDoc + 8489 ",yPercentInView=" + data.mYPercentInView+ ")"); 8490 } 8491 // use the passing content height to cap y as the current 8492 // mContentHeight may not be updated yet 8493 y = Math.max(0, 8494 (Math.min(maxHeight, y + viewHeight) - viewHeight)); 8495 // We need to take into account the visible title height 8496 // when scrolling since y is an absolute view position. 8497 y = Math.max(0, y - getVisibleTitleHeightImpl()); 8498 scrollTo(x, y); 8499 } 8500 break; 8501 8502 case CENTER_FIT_RECT: 8503 centerFitRect((Rect)msg.obj); 8504 break; 8505 8506 case SET_SCROLLBAR_MODES: 8507 mHorizontalScrollBarMode = msg.arg1; 8508 mVerticalScrollBarMode = msg.arg2; 8509 break; 8510 8511 case SELECTION_STRING_CHANGED: 8512 if (mAccessibilityInjector != null) { 8513 String selectionString = (String) msg.obj; 8514 mAccessibilityInjector.onSelectionStringChange(selectionString); 8515 } 8516 break; 8517 8518 case SET_TOUCH_HIGHLIGHT_RECTS: 8519 @SuppressWarnings("unchecked") 8520 ArrayList<Rect> rects = (ArrayList<Rect>) msg.obj; 8521 setTouchHighlightRects(rects); 8522 break; 8523 8524 case SAVE_WEBARCHIVE_FINISHED: 8525 SaveWebArchiveMessage saveMessage = (SaveWebArchiveMessage)msg.obj; 8526 if (saveMessage.mCallback != null) { 8527 saveMessage.mCallback.onReceiveValue(saveMessage.mResultFile); 8528 } 8529 break; 8530 8531 case SET_AUTOFILLABLE: 8532 mAutoFillData = (WebViewCore.AutoFillData) msg.obj; 8533 if (mWebTextView != null) { 8534 mWebTextView.setAutoFillable(mAutoFillData.getQueryId()); 8535 rebuildWebTextView(); 8536 } 8537 break; 8538 8539 case AUTOFILL_COMPLETE: 8540 if (mWebTextView != null) { 8541 // Clear the WebTextView adapter when AutoFill finishes 8542 // so that the drop down gets cleared. 8543 mWebTextView.setAdapterCustom(null); 8544 } 8545 break; 8546 8547 case SELECT_AT: 8548 nativeSelectAt(msg.arg1, msg.arg2); 8549 break; 8550 8551 default: 8552 super.handleMessage(msg); 8553 break; 8554 } 8555 } 8556 } 8557 8558 private void setTouchHighlightRects(ArrayList<Rect> rects) { 8559 invalidate(mTouchHighlightRegion.getBounds()); 8560 mTouchHighlightRegion.setEmpty(); 8561 if (rects != null) { 8562 for (Rect rect : rects) { 8563 Rect viewRect = contentToViewRect(rect); 8564 // some sites, like stories in nytimes.com, set 8565 // mouse event handler in the top div. It is not 8566 // user friendly to highlight the div if it covers 8567 // more than half of the screen. 8568 if (viewRect.width() < getWidth() >> 1 8569 || viewRect.height() < getHeight() >> 1) { 8570 mTouchHighlightRegion.union(viewRect); 8571 } else { 8572 Log.w(LOGTAG, "Skip the huge selection rect:" 8573 + viewRect); 8574 } 8575 } 8576 invalidate(mTouchHighlightRegion.getBounds()); 8577 } 8578 } 8579 8580 /** @hide Called by JNI when pages are swapped (only occurs with hardware 8581 * acceleration) */ 8582 protected void pageSwapCallback() { 8583 if (inEditingMode()) { 8584 didUpdateWebTextViewDimensions(ANYWHERE); 8585 } 8586 } 8587 8588 void setNewPicture(final WebViewCore.DrawData draw, boolean updateBaseLayer) { 8589 if (mNativeClass == 0) { 8590 if (mDelaySetPicture != null) { 8591 throw new IllegalStateException("Tried to setNewPicture with" 8592 + " a delay picture already set! (memory leak)"); 8593 } 8594 // Not initialized yet, delay set 8595 mDelaySetPicture = draw; 8596 return; 8597 } 8598 WebViewCore.ViewState viewState = draw.mViewState; 8599 boolean isPictureAfterFirstLayout = viewState != null; 8600 8601 if (updateBaseLayer) { 8602 // Request a callback on pageSwap (to reposition the webtextview) 8603 boolean registerPageSwapCallback = 8604 !mZoomManager.isFixedLengthAnimationInProgress() && inEditingMode(); 8605 8606 setBaseLayer(draw.mBaseLayer, draw.mInvalRegion, 8607 getSettings().getShowVisualIndicator(), 8608 isPictureAfterFirstLayout, registerPageSwapCallback); 8609 } 8610 final Point viewSize = draw.mViewSize; 8611 if (isPictureAfterFirstLayout) { 8612 // Reset the last sent data here since dealing with new page. 8613 mLastWidthSent = 0; 8614 mZoomManager.onFirstLayout(draw); 8615 if (!mDrawHistory) { 8616 // Do not send the scroll event for this particular 8617 // scroll message. Note that a scroll event may 8618 // still be fired if the user scrolls before the 8619 // message can be handled. 8620 mSendScrollEvent = false; 8621 setContentScrollTo(viewState.mScrollX, viewState.mScrollY); 8622 mSendScrollEvent = true; 8623 8624 // As we are on a new page, remove the WebTextView. This 8625 // is necessary for page loads driven by webkit, and in 8626 // particular when the user was on a password field, so 8627 // the WebTextView was visible. 8628 clearTextEntry(); 8629 } 8630 } 8631 8632 // We update the layout (i.e. request a layout from the 8633 // view system) if the last view size that we sent to 8634 // WebCore matches the view size of the picture we just 8635 // received in the fixed dimension. 8636 final boolean updateLayout = viewSize.x == mLastWidthSent 8637 && viewSize.y == mLastHeightSent; 8638 // Don't send scroll event for picture coming from webkit, 8639 // since the new picture may cause a scroll event to override 8640 // the saved history scroll position. 8641 mSendScrollEvent = false; 8642 recordNewContentSize(draw.mContentSize.x, 8643 draw.mContentSize.y, updateLayout); 8644 mSendScrollEvent = true; 8645 if (DebugFlags.WEB_VIEW) { 8646 Rect b = draw.mInvalRegion.getBounds(); 8647 Log.v(LOGTAG, "NEW_PICTURE_MSG_ID {" + 8648 b.left+","+b.top+","+b.right+","+b.bottom+"}"); 8649 } 8650 invalidateContentRect(draw.mInvalRegion.getBounds()); 8651 8652 if (mPictureListener != null) { 8653 mPictureListener.onNewPicture(WebView.this, capturePicture()); 8654 } 8655 8656 // update the zoom information based on the new picture 8657 mZoomManager.onNewPicture(draw); 8658 8659 if (draw.mFocusSizeChanged && inEditingMode()) { 8660 mFocusSizeChanged = true; 8661 } 8662 if (isPictureAfterFirstLayout) { 8663 mViewManager.postReadyToDrawAll(); 8664 } 8665 } 8666 8667 /** 8668 * Used when receiving messages for REQUEST_KEYBOARD_WITH_SELECTION_MSG_ID 8669 * and UPDATE_TEXT_SELECTION_MSG_ID. Update the selection of WebTextView. 8670 */ 8671 private void updateTextSelectionFromMessage(int nodePointer, 8672 int textGeneration, WebViewCore.TextSelectionData data) { 8673 if (inEditingMode() 8674 && mWebTextView.isSameTextField(nodePointer) 8675 && textGeneration == mTextGeneration) { 8676 mWebTextView.setSelectionFromWebKit(data.mStart, data.mEnd); 8677 } 8678 } 8679 8680 // Class used to use a dropdown for a <select> element 8681 private class InvokeListBox implements Runnable { 8682 // Whether the listbox allows multiple selection. 8683 private boolean mMultiple; 8684 // Passed in to a list with multiple selection to tell 8685 // which items are selected. 8686 private int[] mSelectedArray; 8687 // Passed in to a list with single selection to tell 8688 // where the initial selection is. 8689 private int mSelection; 8690 8691 private Container[] mContainers; 8692 8693 // Need these to provide stable ids to my ArrayAdapter, 8694 // which normally does not have stable ids. (Bug 1250098) 8695 private class Container extends Object { 8696 /** 8697 * Possible values for mEnabled. Keep in sync with OptionStatus in 8698 * WebViewCore.cpp 8699 */ 8700 final static int OPTGROUP = -1; 8701 final static int OPTION_DISABLED = 0; 8702 final static int OPTION_ENABLED = 1; 8703 8704 String mString; 8705 int mEnabled; 8706 int mId; 8707 8708 @Override 8709 public String toString() { 8710 return mString; 8711 } 8712 } 8713 8714 /** 8715 * Subclass ArrayAdapter so we can disable OptionGroupLabels, 8716 * and allow filtering. 8717 */ 8718 private class MyArrayListAdapter extends ArrayAdapter<Container> { 8719 public MyArrayListAdapter() { 8720 super(mContext, 8721 mMultiple ? com.android.internal.R.layout.select_dialog_multichoice : 8722 com.android.internal.R.layout.webview_select_singlechoice, 8723 mContainers); 8724 } 8725 8726 @Override 8727 public View getView(int position, View convertView, 8728 ViewGroup parent) { 8729 // Always pass in null so that we will get a new CheckedTextView 8730 // Otherwise, an item which was previously used as an <optgroup> 8731 // element (i.e. has no check), could get used as an <option> 8732 // element, which needs a checkbox/radio, but it would not have 8733 // one. 8734 convertView = super.getView(position, null, parent); 8735 Container c = item(position); 8736 if (c != null && Container.OPTION_ENABLED != c.mEnabled) { 8737 // ListView does not draw dividers between disabled and 8738 // enabled elements. Use a LinearLayout to provide dividers 8739 LinearLayout layout = new LinearLayout(mContext); 8740 layout.setOrientation(LinearLayout.VERTICAL); 8741 if (position > 0) { 8742 View dividerTop = new View(mContext); 8743 dividerTop.setBackgroundResource( 8744 android.R.drawable.divider_horizontal_bright); 8745 layout.addView(dividerTop); 8746 } 8747 8748 if (Container.OPTGROUP == c.mEnabled) { 8749 // Currently select_dialog_multichoice uses CheckedTextViews. 8750 // If that changes, the class cast will no longer be valid. 8751 if (mMultiple) { 8752 Assert.assertTrue(convertView instanceof CheckedTextView); 8753 ((CheckedTextView) convertView).setCheckMarkDrawable(null); 8754 } 8755 } else { 8756 // c.mEnabled == Container.OPTION_DISABLED 8757 // Draw the disabled element in a disabled state. 8758 convertView.setEnabled(false); 8759 } 8760 8761 layout.addView(convertView); 8762 if (position < getCount() - 1) { 8763 View dividerBottom = new View(mContext); 8764 dividerBottom.setBackgroundResource( 8765 android.R.drawable.divider_horizontal_bright); 8766 layout.addView(dividerBottom); 8767 } 8768 return layout; 8769 } 8770 return convertView; 8771 } 8772 8773 @Override 8774 public boolean hasStableIds() { 8775 // AdapterView's onChanged method uses this to determine whether 8776 // to restore the old state. Return false so that the old (out 8777 // of date) state does not replace the new, valid state. 8778 return false; 8779 } 8780 8781 private Container item(int position) { 8782 if (position < 0 || position >= getCount()) { 8783 return null; 8784 } 8785 return (Container) getItem(position); 8786 } 8787 8788 @Override 8789 public long getItemId(int position) { 8790 Container item = item(position); 8791 if (item == null) { 8792 return -1; 8793 } 8794 return item.mId; 8795 } 8796 8797 @Override 8798 public boolean areAllItemsEnabled() { 8799 return false; 8800 } 8801 8802 @Override 8803 public boolean isEnabled(int position) { 8804 Container item = item(position); 8805 if (item == null) { 8806 return false; 8807 } 8808 return Container.OPTION_ENABLED == item.mEnabled; 8809 } 8810 } 8811 8812 private InvokeListBox(String[] array, int[] enabled, int[] selected) { 8813 mMultiple = true; 8814 mSelectedArray = selected; 8815 8816 int length = array.length; 8817 mContainers = new Container[length]; 8818 for (int i = 0; i < length; i++) { 8819 mContainers[i] = new Container(); 8820 mContainers[i].mString = array[i]; 8821 mContainers[i].mEnabled = enabled[i]; 8822 mContainers[i].mId = i; 8823 } 8824 } 8825 8826 private InvokeListBox(String[] array, int[] enabled, int selection) { 8827 mSelection = selection; 8828 mMultiple = false; 8829 8830 int length = array.length; 8831 mContainers = new Container[length]; 8832 for (int i = 0; i < length; i++) { 8833 mContainers[i] = new Container(); 8834 mContainers[i].mString = array[i]; 8835 mContainers[i].mEnabled = enabled[i]; 8836 mContainers[i].mId = i; 8837 } 8838 } 8839 8840 /* 8841 * Whenever the data set changes due to filtering, this class ensures 8842 * that the checked item remains checked. 8843 */ 8844 private class SingleDataSetObserver extends DataSetObserver { 8845 private long mCheckedId; 8846 private ListView mListView; 8847 private Adapter mAdapter; 8848 8849 /* 8850 * Create a new observer. 8851 * @param id The ID of the item to keep checked. 8852 * @param l ListView for getting and clearing the checked states 8853 * @param a Adapter for getting the IDs 8854 */ 8855 public SingleDataSetObserver(long id, ListView l, Adapter a) { 8856 mCheckedId = id; 8857 mListView = l; 8858 mAdapter = a; 8859 } 8860 8861 @Override 8862 public void onChanged() { 8863 // The filter may have changed which item is checked. Find the 8864 // item that the ListView thinks is checked. 8865 int position = mListView.getCheckedItemPosition(); 8866 long id = mAdapter.getItemId(position); 8867 if (mCheckedId != id) { 8868 // Clear the ListView's idea of the checked item, since 8869 // it is incorrect 8870 mListView.clearChoices(); 8871 // Search for mCheckedId. If it is in the filtered list, 8872 // mark it as checked 8873 int count = mAdapter.getCount(); 8874 for (int i = 0; i < count; i++) { 8875 if (mAdapter.getItemId(i) == mCheckedId) { 8876 mListView.setItemChecked(i, true); 8877 break; 8878 } 8879 } 8880 } 8881 } 8882 } 8883 8884 public void run() { 8885 final ListView listView = (ListView) LayoutInflater.from(mContext) 8886 .inflate(com.android.internal.R.layout.select_dialog, null); 8887 final MyArrayListAdapter adapter = new MyArrayListAdapter(); 8888 AlertDialog.Builder b = new AlertDialog.Builder(mContext) 8889 .setView(listView).setCancelable(true) 8890 .setInverseBackgroundForced(true); 8891 8892 if (mMultiple) { 8893 b.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { 8894 public void onClick(DialogInterface dialog, int which) { 8895 mWebViewCore.sendMessage( 8896 EventHub.LISTBOX_CHOICES, 8897 adapter.getCount(), 0, 8898 listView.getCheckedItemPositions()); 8899 }}); 8900 b.setNegativeButton(android.R.string.cancel, 8901 new DialogInterface.OnClickListener() { 8902 public void onClick(DialogInterface dialog, int which) { 8903 mWebViewCore.sendMessage( 8904 EventHub.SINGLE_LISTBOX_CHOICE, -2, 0); 8905 }}); 8906 } 8907 mListBoxDialog = b.create(); 8908 listView.setAdapter(adapter); 8909 listView.setFocusableInTouchMode(true); 8910 // There is a bug (1250103) where the checks in a ListView with 8911 // multiple items selected are associated with the positions, not 8912 // the ids, so the items do not properly retain their checks when 8913 // filtered. Do not allow filtering on multiple lists until 8914 // that bug is fixed. 8915 8916 listView.setTextFilterEnabled(!mMultiple); 8917 if (mMultiple) { 8918 listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE); 8919 int length = mSelectedArray.length; 8920 for (int i = 0; i < length; i++) { 8921 listView.setItemChecked(mSelectedArray[i], true); 8922 } 8923 } else { 8924 listView.setOnItemClickListener(new OnItemClickListener() { 8925 public void onItemClick(AdapterView<?> parent, View v, 8926 int position, long id) { 8927 // Rather than sending the message right away, send it 8928 // after the page regains focus. 8929 mListBoxMessage = Message.obtain(null, 8930 EventHub.SINGLE_LISTBOX_CHOICE, (int) id, 0); 8931 mListBoxDialog.dismiss(); 8932 mListBoxDialog = null; 8933 } 8934 }); 8935 if (mSelection != -1) { 8936 listView.setSelection(mSelection); 8937 listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE); 8938 listView.setItemChecked(mSelection, true); 8939 DataSetObserver observer = new SingleDataSetObserver( 8940 adapter.getItemId(mSelection), listView, adapter); 8941 adapter.registerDataSetObserver(observer); 8942 } 8943 } 8944 mListBoxDialog.setOnCancelListener(new DialogInterface.OnCancelListener() { 8945 public void onCancel(DialogInterface dialog) { 8946 mWebViewCore.sendMessage( 8947 EventHub.SINGLE_LISTBOX_CHOICE, -2, 0); 8948 mListBoxDialog = null; 8949 } 8950 }); 8951 mListBoxDialog.show(); 8952 } 8953 } 8954 8955 private Message mListBoxMessage; 8956 8957 /* 8958 * Request a dropdown menu for a listbox with multiple selection. 8959 * 8960 * @param array Labels for the listbox. 8961 * @param enabledArray State for each element in the list. See static 8962 * integers in Container class. 8963 * @param selectedArray Which positions are initally selected. 8964 */ 8965 void requestListBox(String[] array, int[] enabledArray, int[] 8966 selectedArray) { 8967 mPrivateHandler.post( 8968 new InvokeListBox(array, enabledArray, selectedArray)); 8969 } 8970 8971 /* 8972 * Request a dropdown menu for a listbox with single selection or a single 8973 * <select> element. 8974 * 8975 * @param array Labels for the listbox. 8976 * @param enabledArray State for each element in the list. See static 8977 * integers in Container class. 8978 * @param selection Which position is initally selected. 8979 */ 8980 void requestListBox(String[] array, int[] enabledArray, int selection) { 8981 mPrivateHandler.post( 8982 new InvokeListBox(array, enabledArray, selection)); 8983 } 8984 8985 // called by JNI 8986 private void sendMoveFocus(int frame, int node) { 8987 mWebViewCore.sendMessage(EventHub.SET_MOVE_FOCUS, 8988 new WebViewCore.CursorData(frame, node, 0, 0)); 8989 } 8990 8991 // called by JNI 8992 private void sendMoveMouse(int frame, int node, int x, int y) { 8993 mWebViewCore.sendMessage(EventHub.SET_MOVE_MOUSE, 8994 new WebViewCore.CursorData(frame, node, x, y)); 8995 } 8996 8997 /* 8998 * Send a mouse move event to the webcore thread. 8999 * 9000 * @param removeFocus Pass true to remove the WebTextView, if present. 9001 * @param stopPaintingCaret Stop drawing the blinking caret if true. 9002 * called by JNI 9003 */ 9004 @SuppressWarnings("unused") 9005 private void sendMoveMouseIfLatest(boolean removeFocus, boolean stopPaintingCaret) { 9006 if (removeFocus) { 9007 clearTextEntry(); 9008 } 9009 mWebViewCore.sendMessage(EventHub.SET_MOVE_MOUSE_IF_LATEST, 9010 stopPaintingCaret ? 1 : 0, 0, 9011 cursorData()); 9012 } 9013 9014 /** 9015 * Called by JNI to send a message to the webcore thread that the user 9016 * touched the webpage. 9017 * @param touchGeneration Generation number of the touch, to ignore touches 9018 * after a new one has been generated. 9019 * @param frame Pointer to the frame holding the node that was touched. 9020 * @param node Pointer to the node touched. 9021 * @param x x-position of the touch. 9022 * @param y y-position of the touch. 9023 */ 9024 private void sendMotionUp(int touchGeneration, 9025 int frame, int node, int x, int y) { 9026 WebViewCore.TouchUpData touchUpData = new WebViewCore.TouchUpData(); 9027 touchUpData.mMoveGeneration = touchGeneration; 9028 touchUpData.mFrame = frame; 9029 touchUpData.mNode = node; 9030 touchUpData.mX = x; 9031 touchUpData.mY = y; 9032 touchUpData.mNativeLayer = nativeScrollableLayer( 9033 x, y, touchUpData.mNativeLayerRect, null); 9034 mWebViewCore.sendMessage(EventHub.TOUCH_UP, touchUpData); 9035 } 9036 9037 9038 private int getScaledMaxXScroll() { 9039 int width; 9040 if (mHeightCanMeasure == false) { 9041 width = getViewWidth() / 4; 9042 } else { 9043 Rect visRect = new Rect(); 9044 calcOurVisibleRect(visRect); 9045 width = visRect.width() / 2; 9046 } 9047 // FIXME the divisor should be retrieved from somewhere 9048 return viewToContentX(width); 9049 } 9050 9051 private int getScaledMaxYScroll() { 9052 int height; 9053 if (mHeightCanMeasure == false) { 9054 height = getViewHeight() / 4; 9055 } else { 9056 Rect visRect = new Rect(); 9057 calcOurVisibleRect(visRect); 9058 height = visRect.height() / 2; 9059 } 9060 // FIXME the divisor should be retrieved from somewhere 9061 // the closest thing today is hard-coded into ScrollView.java 9062 // (from ScrollView.java, line 363) int maxJump = height/2; 9063 return Math.round(height * mZoomManager.getInvScale()); 9064 } 9065 9066 /** 9067 * Called by JNI to invalidate view 9068 */ 9069 private void viewInvalidate() { 9070 invalidate(); 9071 } 9072 9073 /** 9074 * Pass the key directly to the page. This assumes that 9075 * nativePageShouldHandleShiftAndArrows() returned true. 9076 */ 9077 private void letPageHandleNavKey(int keyCode, long time, boolean down, int metaState) { 9078 int keyEventAction; 9079 int eventHubAction; 9080 if (down) { 9081 keyEventAction = KeyEvent.ACTION_DOWN; 9082 eventHubAction = EventHub.KEY_DOWN; 9083 playSoundEffect(keyCodeToSoundsEffect(keyCode)); 9084 } else { 9085 keyEventAction = KeyEvent.ACTION_UP; 9086 eventHubAction = EventHub.KEY_UP; 9087 } 9088 9089 KeyEvent event = new KeyEvent(time, time, keyEventAction, keyCode, 9090 1, (metaState & KeyEvent.META_SHIFT_ON) 9091 | (metaState & KeyEvent.META_ALT_ON) 9092 | (metaState & KeyEvent.META_SYM_ON) 9093 , KeyCharacterMap.VIRTUAL_KEYBOARD, 0, 0); 9094 mWebViewCore.sendMessage(eventHubAction, event); 9095 } 9096 9097 // return true if the key was handled 9098 private boolean navHandledKey(int keyCode, int count, boolean noScroll, 9099 long time) { 9100 if (mNativeClass == 0) { 9101 return false; 9102 } 9103 mInitialHitTestResult = null; 9104 mLastCursorTime = time; 9105 mLastCursorBounds = nativeGetCursorRingBounds(); 9106 boolean keyHandled 9107 = nativeMoveCursor(keyCode, count, noScroll) == false; 9108 if (DebugFlags.WEB_VIEW) { 9109 Log.v(LOGTAG, "navHandledKey mLastCursorBounds=" + mLastCursorBounds 9110 + " mLastCursorTime=" + mLastCursorTime 9111 + " handled=" + keyHandled); 9112 } 9113 if (keyHandled == false) { 9114 return keyHandled; 9115 } 9116 Rect contentCursorRingBounds = nativeGetCursorRingBounds(); 9117 if (contentCursorRingBounds.isEmpty()) return keyHandled; 9118 Rect viewCursorRingBounds = contentToViewRect(contentCursorRingBounds); 9119 // set last touch so that context menu related functions will work 9120 mLastTouchX = (viewCursorRingBounds.left + viewCursorRingBounds.right) / 2; 9121 mLastTouchY = (viewCursorRingBounds.top + viewCursorRingBounds.bottom) / 2; 9122 if (mHeightCanMeasure == false) { 9123 return keyHandled; 9124 } 9125 Rect visRect = new Rect(); 9126 calcOurVisibleRect(visRect); 9127 Rect outset = new Rect(visRect); 9128 int maxXScroll = visRect.width() / 2; 9129 int maxYScroll = visRect.height() / 2; 9130 outset.inset(-maxXScroll, -maxYScroll); 9131 if (Rect.intersects(outset, viewCursorRingBounds) == false) { 9132 return keyHandled; 9133 } 9134 // FIXME: Necessary because ScrollView/ListView do not scroll left/right 9135 int maxH = Math.min(viewCursorRingBounds.right - visRect.right, 9136 maxXScroll); 9137 if (maxH > 0) { 9138 pinScrollBy(maxH, 0, true, 0); 9139 } else { 9140 maxH = Math.max(viewCursorRingBounds.left - visRect.left, 9141 -maxXScroll); 9142 if (maxH < 0) { 9143 pinScrollBy(maxH, 0, true, 0); 9144 } 9145 } 9146 if (mLastCursorBounds.isEmpty()) return keyHandled; 9147 if (mLastCursorBounds.equals(contentCursorRingBounds)) { 9148 return keyHandled; 9149 } 9150 if (DebugFlags.WEB_VIEW) { 9151 Log.v(LOGTAG, "navHandledKey contentCursorRingBounds=" 9152 + contentCursorRingBounds); 9153 } 9154 requestRectangleOnScreen(viewCursorRingBounds); 9155 return keyHandled; 9156 } 9157 9158 /** 9159 * @return Whether accessibility script has been injected. 9160 */ 9161 private boolean accessibilityScriptInjected() { 9162 // TODO: Maybe the injected script should announce its presence in 9163 // the page meta-tag so the nativePageShouldHandleShiftAndArrows 9164 // will check that as one of the conditions it looks for 9165 return mAccessibilityScriptInjected; 9166 } 9167 9168 /** 9169 * Set the background color. It's white by default. Pass 9170 * zero to make the view transparent. 9171 * @param color the ARGB color described by Color.java 9172 */ 9173 @Override 9174 public void setBackgroundColor(int color) { 9175 mBackgroundColor = color; 9176 mWebViewCore.sendMessage(EventHub.SET_BACKGROUND_COLOR, color); 9177 } 9178 9179 /** 9180 * @deprecated This method is now obsolete. 9181 */ 9182 @Deprecated 9183 public void debugDump() { 9184 checkThread(); 9185 nativeDebugDump(); 9186 mWebViewCore.sendMessage(EventHub.DUMP_NAVTREE); 9187 } 9188 9189 /** 9190 * Draw the HTML page into the specified canvas. This call ignores any 9191 * view-specific zoom, scroll offset, or other changes. It does not draw 9192 * any view-specific chrome, such as progress or URL bars. 9193 * 9194 * @hide only needs to be accessible to Browser and testing 9195 */ 9196 public void drawPage(Canvas canvas) { 9197 nativeDraw(canvas, 0, 0, false); 9198 } 9199 9200 /** 9201 * Enable the communication b/t the webView and VideoViewProxy 9202 * 9203 * @hide only used by the Browser 9204 */ 9205 public void setHTML5VideoViewProxy(HTML5VideoViewProxy proxy) { 9206 mHTML5VideoViewProxy = proxy; 9207 } 9208 9209 /** 9210 * Set the time to wait between passing touches to WebCore. See also the 9211 * TOUCH_SENT_INTERVAL member for further discussion. 9212 * 9213 * @hide This is only used by the DRT test application. 9214 */ 9215 public void setTouchInterval(int interval) { 9216 mCurrentTouchInterval = interval; 9217 } 9218 9219 /** 9220 * Update our cache with updatedText. 9221 * @param updatedText The new text to put in our cache. 9222 * @hide 9223 */ 9224 protected void updateCachedTextfield(String updatedText) { 9225 // Also place our generation number so that when we look at the cache 9226 // we recognize that it is up to date. 9227 nativeUpdateCachedTextfield(updatedText, mTextGeneration); 9228 } 9229 9230 /*package*/ void autoFillForm(int autoFillQueryId) { 9231 mWebViewCore.sendMessage(EventHub.AUTOFILL_FORM, autoFillQueryId, /* unused */0); 9232 } 9233 9234 /* package */ ViewManager getViewManager() { 9235 return mViewManager; 9236 } 9237 9238 private static void checkThread() { 9239 if (Looper.myLooper() != Looper.getMainLooper()) { 9240 RuntimeException exception = new RuntimeException( 9241 "A WebView method was called on thread '" + 9242 Thread.currentThread().getName() + "'. " + 9243 "All WebView methods must be called on the UI thread. " + 9244 "Future versions of WebView may not support use on other threads."); 9245 Log.e(LOGTAG, Log.getStackTraceString(exception)); 9246 StrictMode.onWebViewMethodCalledOnWrongThread(exception); 9247 } 9248 } 9249 9250 /** @hide send content invalidate */ 9251 protected void contentInvalidateAll() { 9252 if (mWebViewCore != null && !mBlockWebkitViewMessages) { 9253 mWebViewCore.sendMessage(EventHub.CONTENT_INVALIDATE_ALL); 9254 } 9255 } 9256 9257 /** @hide call pageSwapCallback upon next page swap */ 9258 protected void registerPageSwapCallback() { 9259 nativeRegisterPageSwapCallback(); 9260 } 9261 9262 /** 9263 * Begin collecting per-tile profiling data 9264 * 9265 * @hide only used by profiling tests 9266 */ 9267 public void tileProfilingStart() { 9268 nativeTileProfilingStart(); 9269 } 9270 /** 9271 * Return per-tile profiling data 9272 * 9273 * @hide only used by profiling tests 9274 */ 9275 public float tileProfilingStop() { 9276 return nativeTileProfilingStop(); 9277 } 9278 9279 /** @hide only used by profiling tests */ 9280 public void tileProfilingClear() { 9281 nativeTileProfilingClear(); 9282 } 9283 /** @hide only used by profiling tests */ 9284 public int tileProfilingNumFrames() { 9285 return nativeTileProfilingNumFrames(); 9286 } 9287 /** @hide only used by profiling tests */ 9288 public int tileProfilingNumTilesInFrame(int frame) { 9289 return nativeTileProfilingNumTilesInFrame(frame); 9290 } 9291 /** @hide only used by profiling tests */ 9292 public int tileProfilingGetInt(int frame, int tile, String key) { 9293 return nativeTileProfilingGetInt(frame, tile, key); 9294 } 9295 /** @hide only used by profiling tests */ 9296 public float tileProfilingGetFloat(int frame, int tile, String key) { 9297 return nativeTileProfilingGetFloat(frame, tile, key); 9298 } 9299 9300 private native int nativeCacheHitFramePointer(); 9301 private native boolean nativeCacheHitIsPlugin(); 9302 private native Rect nativeCacheHitNodeBounds(); 9303 private native int nativeCacheHitNodePointer(); 9304 /* package */ native void nativeClearCursor(); 9305 private native void nativeCreate(int ptr, String drawableDir); 9306 private native int nativeCursorFramePointer(); 9307 private native Rect nativeCursorNodeBounds(); 9308 private native int nativeCursorNodePointer(); 9309 private native boolean nativeCursorIntersects(Rect visibleRect); 9310 private native boolean nativeCursorIsAnchor(); 9311 private native boolean nativeCursorIsTextInput(); 9312 private native Point nativeCursorPosition(); 9313 private native String nativeCursorText(); 9314 /** 9315 * Returns true if the native cursor node says it wants to handle key events 9316 * (ala plugins). This can only be called if mNativeClass is non-zero! 9317 */ 9318 private native boolean nativeCursorWantsKeyEvents(); 9319 private native void nativeDebugDump(); 9320 private native void nativeDestroy(); 9321 9322 /** 9323 * Draw the picture set with a background color and extra. If 9324 * "splitIfNeeded" is true and the return value is not 0, the return value 9325 * MUST be passed to WebViewCore with SPLIT_PICTURE_SET message so that the 9326 * native allocation can be freed. 9327 */ 9328 private native int nativeDraw(Canvas canvas, int color, int extra, 9329 boolean splitIfNeeded); 9330 private native void nativeDumpDisplayTree(String urlOrNull); 9331 private native boolean nativeEvaluateLayersAnimations(); 9332 private native int nativeGetDrawGLFunction(Rect rect, Rect viewRect, 9333 float scale, int extras); 9334 private native void nativeUpdateDrawGLFunction(Rect rect, Rect viewRect); 9335 private native void nativeExtendSelection(int x, int y); 9336 private native int nativeFindAll(String findLower, String findUpper, 9337 boolean sameAsLastSearch); 9338 private native void nativeFindNext(boolean forward); 9339 /* package */ native int nativeFocusCandidateFramePointer(); 9340 /* package */ native boolean nativeFocusCandidateHasNextTextfield(); 9341 /* package */ native boolean nativeFocusCandidateIsPassword(); 9342 private native boolean nativeFocusCandidateIsRtlText(); 9343 private native boolean nativeFocusCandidateIsTextInput(); 9344 /* package */ native int nativeFocusCandidateMaxLength(); 9345 /* package */ native boolean nativeFocusCandidateIsAutoComplete(); 9346 /* package */ native String nativeFocusCandidateName(); 9347 private native Rect nativeFocusCandidateNodeBounds(); 9348 /** 9349 * @return A Rect with left, top, right, bottom set to the corresponding 9350 * padding values in the focus candidate, if it is a textfield/textarea with 9351 * a style. Otherwise return null. This is not actually a rectangle; Rect 9352 * is being used to pass four integers. 9353 */ 9354 private native Rect nativeFocusCandidatePaddingRect(); 9355 /* package */ native int nativeFocusCandidatePointer(); 9356 private native String nativeFocusCandidateText(); 9357 /* package */ native float nativeFocusCandidateTextSize(); 9358 /* package */ native int nativeFocusCandidateLineHeight(); 9359 /** 9360 * Returns an integer corresponding to WebView.cpp::type. 9361 * See WebTextView.setType() 9362 */ 9363 private native int nativeFocusCandidateType(); 9364 private native boolean nativeFocusIsPlugin(); 9365 private native Rect nativeFocusNodeBounds(); 9366 /* package */ native int nativeFocusNodePointer(); 9367 private native Rect nativeGetCursorRingBounds(); 9368 private native String nativeGetSelection(); 9369 private native boolean nativeHasCursorNode(); 9370 private native boolean nativeHasFocusNode(); 9371 private native void nativeHideCursor(); 9372 private native boolean nativeHitSelection(int x, int y); 9373 private native String nativeImageURI(int x, int y); 9374 private native void nativeInstrumentReport(); 9375 private native Rect nativeLayerBounds(int layer); 9376 /* package */ native boolean nativeMoveCursorToNextTextInput(); 9377 // return true if the page has been scrolled 9378 private native boolean nativeMotionUp(int x, int y, int slop); 9379 // returns false if it handled the key 9380 private native boolean nativeMoveCursor(int keyCode, int count, 9381 boolean noScroll); 9382 private native int nativeMoveGeneration(); 9383 private native void nativeMoveSelection(int x, int y); 9384 /** 9385 * @return true if the page should get the shift and arrow keys, rather 9386 * than select text/navigation. 9387 * 9388 * If the focus is a plugin, or if the focus and cursor match and are 9389 * a contentEditable element, then the page should handle these keys. 9390 */ 9391 private native boolean nativePageShouldHandleShiftAndArrows(); 9392 private native boolean nativePointInNavCache(int x, int y, int slop); 9393 // Like many other of our native methods, you must make sure that 9394 // mNativeClass is not null before calling this method. 9395 private native void nativeRecordButtons(boolean focused, 9396 boolean pressed, boolean invalidate); 9397 private native void nativeResetSelection(); 9398 private native Point nativeSelectableText(); 9399 private native void nativeSelectAll(); 9400 private native void nativeSelectBestAt(Rect rect); 9401 private native void nativeSelectAt(int x, int y); 9402 private native int nativeSelectionX(); 9403 private native int nativeSelectionY(); 9404 private native int nativeFindIndex(); 9405 private native void nativeSetExtendSelection(); 9406 private native void nativeSetFindIsEmpty(); 9407 private native void nativeSetFindIsUp(boolean isUp); 9408 private native void nativeSetHeightCanMeasure(boolean measure); 9409 private native void nativeSetBaseLayer(int layer, Region invalRegion, 9410 boolean showVisualIndicator, boolean isPictureAfterFirstLayout, 9411 boolean registerPageSwapCallback); 9412 private native int nativeGetBaseLayer(); 9413 private native void nativeShowCursorTimed(); 9414 private native void nativeReplaceBaseContent(int content); 9415 private native void nativeCopyBaseContentToPicture(Picture pict); 9416 private native boolean nativeHasContent(); 9417 private native void nativeSetSelectionPointer(boolean set, 9418 float scale, int x, int y); 9419 private native boolean nativeStartSelection(int x, int y); 9420 private native void nativeStopGL(); 9421 private native Rect nativeSubtractLayers(Rect content); 9422 private native int nativeTextGeneration(); 9423 private native void nativeRegisterPageSwapCallback(); 9424 private native void nativeTileProfilingStart(); 9425 private native float nativeTileProfilingStop(); 9426 private native void nativeTileProfilingClear(); 9427 private native int nativeTileProfilingNumFrames(); 9428 private native int nativeTileProfilingNumTilesInFrame(int frame); 9429 private native int nativeTileProfilingGetInt(int frame, int tile, String key); 9430 private native float nativeTileProfilingGetFloat(int frame, int tile, String key); 9431 // Never call this version except by updateCachedTextfield(String) - 9432 // we always want to pass in our generation number. 9433 private native void nativeUpdateCachedTextfield(String updatedText, 9434 int generation); 9435 private native boolean nativeWordSelection(int x, int y); 9436 // return NO_LEFTEDGE means failure. 9437 static final int NO_LEFTEDGE = -1; 9438 native int nativeGetBlockLeftEdge(int x, int y, float scale); 9439 9440 private native void nativeUseHardwareAccelSkia(boolean enabled); 9441 9442 // Returns a pointer to the scrollable LayerAndroid at the given point. 9443 private native int nativeScrollableLayer(int x, int y, Rect scrollRect, 9444 Rect scrollBounds); 9445 /** 9446 * Scroll the specified layer. 9447 * @param layer Id of the layer to scroll, as determined by nativeScrollableLayer. 9448 * @param newX Destination x position to which to scroll. 9449 * @param newY Destination y position to which to scroll. 9450 * @return True if the layer is successfully scrolled. 9451 */ 9452 private native boolean nativeScrollLayer(int layer, int newX, int newY); 9453 private native void nativeSetIsScrolling(boolean isScrolling); 9454 private native int nativeGetBackgroundColor(); 9455 native boolean nativeSetProperty(String key, String value); 9456 native String nativeGetProperty(String key); 9457 private native void nativeGetTextSelectionRegion(Region region); 9458 /** 9459 * See {@link ComponentCallbacks2} for the trim levels and descriptions 9460 */ 9461 private static native void nativeOnTrimMemory(int level); 9462} 9463