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