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