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