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