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