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