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