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