WebView.java revision 87b17be55e02e3d5aef146bfd3caa5116088afd8
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.isZoomedOut()) { 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.isZoomedOut()) { 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.isZoomedOut() 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 if (mTouchMode == TOUCH_INIT_MODE) { 5005 mPrivateHandler.sendEmptyMessageDelayed( 5006 RELEASE_SINGLE_TAP, ViewConfiguration 5007 .getDoubleTapTimeout()); 5008 } else { 5009 doShortPress(); 5010 } 5011 break; 5012 } 5013 case TOUCH_DRAG_MODE: 5014 mPrivateHandler.removeMessages(DRAG_HELD_MOTIONLESS); 5015 mPrivateHandler.removeMessages(AWAKEN_SCROLL_BARS); 5016 // if the user waits a while w/o moving before the 5017 // up, we don't want to do a fling 5018 if (eventTime - mLastTouchTime <= MIN_FLING_TIME) { 5019 if (mVelocityTracker == null) { 5020 Log.e(LOGTAG, "Got null mVelocityTracker when " 5021 + "mPreventDefault = " 5022 + mPreventDefault 5023 + " mDeferTouchProcess = " 5024 + mDeferTouchProcess); 5025 } 5026 mVelocityTracker.addMovement(ev); 5027 // set to MOTIONLESS_IGNORE so that it won't keep 5028 // removing and sending message in 5029 // drawCoreAndCursorRing() 5030 mHeldMotionless = MOTIONLESS_IGNORE; 5031 doFling(); 5032 break; 5033 } 5034 // redraw in high-quality, as we're done dragging 5035 mHeldMotionless = MOTIONLESS_TRUE; 5036 invalidate(); 5037 // fall through 5038 case TOUCH_DRAG_START_MODE: 5039 // TOUCH_DRAG_START_MODE should not happen for the real 5040 // device as we almost certain will get a MOVE. But this 5041 // is possible on emulator. 5042 mLastVelocity = 0; 5043 WebViewCore.resumePriority(); 5044 WebViewCore.resumeUpdatePicture(mWebViewCore); 5045 break; 5046 } 5047 stopTouch(); 5048 break; 5049 } 5050 case MotionEvent.ACTION_CANCEL: { 5051 if (mTouchMode == TOUCH_DRAG_MODE) { 5052 invalidate(); 5053 } 5054 cancelWebCoreTouchEvent(contentX, contentY, false); 5055 cancelTouch(); 5056 break; 5057 } 5058 } 5059 return true; 5060 } 5061 5062 private void cancelWebCoreTouchEvent(int x, int y, boolean removeEvents) { 5063 if (shouldForwardTouchEvent()) { 5064 if (removeEvents) { 5065 mWebViewCore.removeMessages(EventHub.TOUCH_EVENT); 5066 } 5067 TouchEventData ted = new TouchEventData(); 5068 ted.mX = x; 5069 ted.mY = y; 5070 ted.mAction = MotionEvent.ACTION_CANCEL; 5071 mWebViewCore.sendMessage(EventHub.TOUCH_EVENT, ted); 5072 mPreventDefault = PREVENT_DEFAULT_IGNORE; 5073 } 5074 } 5075 5076 private void startTouch(float x, float y, long eventTime) { 5077 // Remember where the motion event started 5078 mLastTouchX = x; 5079 mLastTouchY = y; 5080 mLastTouchTime = eventTime; 5081 mVelocityTracker = VelocityTracker.obtain(); 5082 mSnapScrollMode = SNAP_NONE; 5083 if (mDragTracker != null) { 5084 mDragTrackerHandler = new DragTrackerHandler(x, y, mDragTracker); 5085 } 5086 } 5087 5088 private void startDrag() { 5089 WebViewCore.reducePriority(); 5090 // to get better performance, pause updating the picture 5091 WebViewCore.pauseUpdatePicture(mWebViewCore); 5092 if (!mDragFromTextInput) { 5093 nativeHideCursor(); 5094 } 5095 5096 if (mHorizontalScrollBarMode != SCROLLBAR_ALWAYSOFF 5097 || mVerticalScrollBarMode != SCROLLBAR_ALWAYSOFF) { 5098 mZoomManager.invokeZoomPicker(); 5099 } 5100 } 5101 5102 private void doDrag(int deltaX, int deltaY) { 5103 if ((deltaX | deltaY) != 0) { 5104 scrollBy(deltaX, deltaY); 5105 } 5106 mZoomManager.keepZoomPickerVisible(); 5107 } 5108 5109 private void stopTouch() { 5110 if (mDragTrackerHandler != null) { 5111 mDragTrackerHandler.stopDrag(); 5112 } 5113 // we also use mVelocityTracker == null to tell us that we are 5114 // not "moving around", so we can take the slower/prettier 5115 // mode in the drawing code 5116 if (mVelocityTracker != null) { 5117 mVelocityTracker.recycle(); 5118 mVelocityTracker = null; 5119 } 5120 } 5121 5122 private void cancelTouch() { 5123 if (mDragTrackerHandler != null) { 5124 mDragTrackerHandler.stopDrag(); 5125 } 5126 // we also use mVelocityTracker == null to tell us that we are 5127 // not "moving around", so we can take the slower/prettier 5128 // mode in the drawing code 5129 if (mVelocityTracker != null) { 5130 mVelocityTracker.recycle(); 5131 mVelocityTracker = null; 5132 } 5133 if (mTouchMode == TOUCH_DRAG_MODE) { 5134 WebViewCore.resumePriority(); 5135 WebViewCore.resumeUpdatePicture(mWebViewCore); 5136 } 5137 mPrivateHandler.removeMessages(SWITCH_TO_SHORTPRESS); 5138 mPrivateHandler.removeMessages(SWITCH_TO_LONGPRESS); 5139 mPrivateHandler.removeMessages(DRAG_HELD_MOTIONLESS); 5140 mPrivateHandler.removeMessages(AWAKEN_SCROLL_BARS); 5141 if (getSettings().supportTouchOnly()) { 5142 removeTouchHighlight(true); 5143 } 5144 mHeldMotionless = MOTIONLESS_TRUE; 5145 mTouchMode = TOUCH_DONE_MODE; 5146 nativeHideCursor(); 5147 } 5148 5149 private long mTrackballFirstTime = 0; 5150 private long mTrackballLastTime = 0; 5151 private float mTrackballRemainsX = 0.0f; 5152 private float mTrackballRemainsY = 0.0f; 5153 private int mTrackballXMove = 0; 5154 private int mTrackballYMove = 0; 5155 private boolean mExtendSelection = false; 5156 private boolean mTouchSelection = false; 5157 private static final int TRACKBALL_KEY_TIMEOUT = 1000; 5158 private static final int TRACKBALL_TIMEOUT = 200; 5159 private static final int TRACKBALL_WAIT = 100; 5160 private static final int TRACKBALL_SCALE = 400; 5161 private static final int TRACKBALL_SCROLL_COUNT = 5; 5162 private static final int TRACKBALL_MOVE_COUNT = 10; 5163 private static final int TRACKBALL_MULTIPLIER = 3; 5164 private static final int SELECT_CURSOR_OFFSET = 16; 5165 private int mSelectX = 0; 5166 private int mSelectY = 0; 5167 private boolean mFocusSizeChanged = false; 5168 private boolean mShiftIsPressed = false; 5169 private boolean mTrackballDown = false; 5170 private long mTrackballUpTime = 0; 5171 private long mLastCursorTime = 0; 5172 private Rect mLastCursorBounds; 5173 5174 // Set by default; BrowserActivity clears to interpret trackball data 5175 // directly for movement. Currently, the framework only passes 5176 // arrow key events, not trackball events, from one child to the next 5177 private boolean mMapTrackballToArrowKeys = true; 5178 5179 public void setMapTrackballToArrowKeys(boolean setMap) { 5180 mMapTrackballToArrowKeys = setMap; 5181 } 5182 5183 void resetTrackballTime() { 5184 mTrackballLastTime = 0; 5185 } 5186 5187 @Override 5188 public boolean onTrackballEvent(MotionEvent ev) { 5189 long time = ev.getEventTime(); 5190 if ((ev.getMetaState() & KeyEvent.META_ALT_ON) != 0) { 5191 if (ev.getY() > 0) pageDown(true); 5192 if (ev.getY() < 0) pageUp(true); 5193 return true; 5194 } 5195 boolean shiftPressed = mShiftIsPressed && (mNativeClass == 0 5196 || !nativePageShouldHandleShiftAndArrows()); 5197 if (ev.getAction() == MotionEvent.ACTION_DOWN) { 5198 if (shiftPressed) { 5199 return true; // discard press if copy in progress 5200 } 5201 mTrackballDown = true; 5202 if (mNativeClass == 0) { 5203 return false; 5204 } 5205 nativeRecordButtons(hasFocus() && hasWindowFocus(), true, true); 5206 if (time - mLastCursorTime <= TRACKBALL_TIMEOUT 5207 && !mLastCursorBounds.equals(nativeGetCursorRingBounds())) { 5208 nativeSelectBestAt(mLastCursorBounds); 5209 } 5210 if (DebugFlags.WEB_VIEW) { 5211 Log.v(LOGTAG, "onTrackballEvent down ev=" + ev 5212 + " time=" + time 5213 + " mLastCursorTime=" + mLastCursorTime); 5214 } 5215 if (isInTouchMode()) requestFocusFromTouch(); 5216 return false; // let common code in onKeyDown at it 5217 } 5218 if (ev.getAction() == MotionEvent.ACTION_UP) { 5219 // LONG_PRESS_CENTER is set in common onKeyDown 5220 mPrivateHandler.removeMessages(LONG_PRESS_CENTER); 5221 mTrackballDown = false; 5222 mTrackballUpTime = time; 5223 if (shiftPressed) { 5224 if (mExtendSelection) { 5225 commitCopy(); 5226 } else { 5227 mExtendSelection = true; 5228 invalidate(); // draw the i-beam instead of the arrow 5229 } 5230 return true; // discard press if copy in progress 5231 } 5232 if (DebugFlags.WEB_VIEW) { 5233 Log.v(LOGTAG, "onTrackballEvent up ev=" + ev 5234 + " time=" + time 5235 ); 5236 } 5237 return false; // let common code in onKeyUp at it 5238 } 5239 if (mMapTrackballToArrowKeys && mShiftIsPressed == false) { 5240 if (DebugFlags.WEB_VIEW) Log.v(LOGTAG, "onTrackballEvent gmail quit"); 5241 return false; 5242 } 5243 if (mTrackballDown) { 5244 if (DebugFlags.WEB_VIEW) Log.v(LOGTAG, "onTrackballEvent down quit"); 5245 return true; // discard move if trackball is down 5246 } 5247 if (time - mTrackballUpTime < TRACKBALL_TIMEOUT) { 5248 if (DebugFlags.WEB_VIEW) Log.v(LOGTAG, "onTrackballEvent up timeout quit"); 5249 return true; 5250 } 5251 // TODO: alternatively we can do panning as touch does 5252 switchOutDrawHistory(); 5253 if (time - mTrackballLastTime > TRACKBALL_TIMEOUT) { 5254 if (DebugFlags.WEB_VIEW) { 5255 Log.v(LOGTAG, "onTrackballEvent time=" 5256 + time + " last=" + mTrackballLastTime); 5257 } 5258 mTrackballFirstTime = time; 5259 mTrackballXMove = mTrackballYMove = 0; 5260 } 5261 mTrackballLastTime = time; 5262 if (DebugFlags.WEB_VIEW) { 5263 Log.v(LOGTAG, "onTrackballEvent ev=" + ev + " time=" + time); 5264 } 5265 mTrackballRemainsX += ev.getX(); 5266 mTrackballRemainsY += ev.getY(); 5267 doTrackball(time); 5268 return true; 5269 } 5270 5271 void moveSelection(float xRate, float yRate) { 5272 if (mNativeClass == 0) 5273 return; 5274 int width = getViewWidth(); 5275 int height = getViewHeight(); 5276 mSelectX += xRate; 5277 mSelectY += yRate; 5278 int maxX = width + mScrollX; 5279 int maxY = height + mScrollY; 5280 mSelectX = Math.min(maxX, Math.max(mScrollX - SELECT_CURSOR_OFFSET 5281 , mSelectX)); 5282 mSelectY = Math.min(maxY, Math.max(mScrollY - SELECT_CURSOR_OFFSET 5283 , mSelectY)); 5284 if (DebugFlags.WEB_VIEW) { 5285 Log.v(LOGTAG, "moveSelection" 5286 + " mSelectX=" + mSelectX 5287 + " mSelectY=" + mSelectY 5288 + " mScrollX=" + mScrollX 5289 + " mScrollY=" + mScrollY 5290 + " xRate=" + xRate 5291 + " yRate=" + yRate 5292 ); 5293 } 5294 nativeMoveSelection(viewToContentX(mSelectX), 5295 viewToContentY(mSelectY), mExtendSelection); 5296 int scrollX = mSelectX < mScrollX ? -SELECT_CURSOR_OFFSET 5297 : mSelectX > maxX - SELECT_CURSOR_OFFSET ? SELECT_CURSOR_OFFSET 5298 : 0; 5299 int scrollY = mSelectY < mScrollY ? -SELECT_CURSOR_OFFSET 5300 : mSelectY > maxY - SELECT_CURSOR_OFFSET ? SELECT_CURSOR_OFFSET 5301 : 0; 5302 pinScrollBy(scrollX, scrollY, true, 0); 5303 Rect select = new Rect(mSelectX, mSelectY, mSelectX + 1, mSelectY + 1); 5304 requestRectangleOnScreen(select); 5305 invalidate(); 5306 } 5307 5308 private int scaleTrackballX(float xRate, int width) { 5309 int xMove = (int) (xRate / TRACKBALL_SCALE * width); 5310 int nextXMove = xMove; 5311 if (xMove > 0) { 5312 if (xMove > mTrackballXMove) { 5313 xMove -= mTrackballXMove; 5314 } 5315 } else if (xMove < mTrackballXMove) { 5316 xMove -= mTrackballXMove; 5317 } 5318 mTrackballXMove = nextXMove; 5319 return xMove; 5320 } 5321 5322 private int scaleTrackballY(float yRate, int height) { 5323 int yMove = (int) (yRate / TRACKBALL_SCALE * height); 5324 int nextYMove = yMove; 5325 if (yMove > 0) { 5326 if (yMove > mTrackballYMove) { 5327 yMove -= mTrackballYMove; 5328 } 5329 } else if (yMove < mTrackballYMove) { 5330 yMove -= mTrackballYMove; 5331 } 5332 mTrackballYMove = nextYMove; 5333 return yMove; 5334 } 5335 5336 private int keyCodeToSoundsEffect(int keyCode) { 5337 switch(keyCode) { 5338 case KeyEvent.KEYCODE_DPAD_UP: 5339 return SoundEffectConstants.NAVIGATION_UP; 5340 case KeyEvent.KEYCODE_DPAD_RIGHT: 5341 return SoundEffectConstants.NAVIGATION_RIGHT; 5342 case KeyEvent.KEYCODE_DPAD_DOWN: 5343 return SoundEffectConstants.NAVIGATION_DOWN; 5344 case KeyEvent.KEYCODE_DPAD_LEFT: 5345 return SoundEffectConstants.NAVIGATION_LEFT; 5346 } 5347 throw new IllegalArgumentException("keyCode must be one of " + 5348 "{KEYCODE_DPAD_UP, KEYCODE_DPAD_RIGHT, KEYCODE_DPAD_DOWN, " + 5349 "KEYCODE_DPAD_LEFT}."); 5350 } 5351 5352 private void doTrackball(long time) { 5353 int elapsed = (int) (mTrackballLastTime - mTrackballFirstTime); 5354 if (elapsed == 0) { 5355 elapsed = TRACKBALL_TIMEOUT; 5356 } 5357 float xRate = mTrackballRemainsX * 1000 / elapsed; 5358 float yRate = mTrackballRemainsY * 1000 / elapsed; 5359 int viewWidth = getViewWidth(); 5360 int viewHeight = getViewHeight(); 5361 if (mShiftIsPressed && (mNativeClass == 0 5362 || !nativePageShouldHandleShiftAndArrows())) { 5363 moveSelection(scaleTrackballX(xRate, viewWidth), 5364 scaleTrackballY(yRate, viewHeight)); 5365 mTrackballRemainsX = mTrackballRemainsY = 0; 5366 return; 5367 } 5368 float ax = Math.abs(xRate); 5369 float ay = Math.abs(yRate); 5370 float maxA = Math.max(ax, ay); 5371 if (DebugFlags.WEB_VIEW) { 5372 Log.v(LOGTAG, "doTrackball elapsed=" + elapsed 5373 + " xRate=" + xRate 5374 + " yRate=" + yRate 5375 + " mTrackballRemainsX=" + mTrackballRemainsX 5376 + " mTrackballRemainsY=" + mTrackballRemainsY); 5377 } 5378 int width = mContentWidth - viewWidth; 5379 int height = mContentHeight - viewHeight; 5380 if (width < 0) width = 0; 5381 if (height < 0) height = 0; 5382 ax = Math.abs(mTrackballRemainsX * TRACKBALL_MULTIPLIER); 5383 ay = Math.abs(mTrackballRemainsY * TRACKBALL_MULTIPLIER); 5384 maxA = Math.max(ax, ay); 5385 int count = Math.max(0, (int) maxA); 5386 int oldScrollX = mScrollX; 5387 int oldScrollY = mScrollY; 5388 if (count > 0) { 5389 int selectKeyCode = ax < ay ? mTrackballRemainsY < 0 ? 5390 KeyEvent.KEYCODE_DPAD_UP : KeyEvent.KEYCODE_DPAD_DOWN : 5391 mTrackballRemainsX < 0 ? KeyEvent.KEYCODE_DPAD_LEFT : 5392 KeyEvent.KEYCODE_DPAD_RIGHT; 5393 count = Math.min(count, TRACKBALL_MOVE_COUNT); 5394 if (DebugFlags.WEB_VIEW) { 5395 Log.v(LOGTAG, "doTrackball keyCode=" + selectKeyCode 5396 + " count=" + count 5397 + " mTrackballRemainsX=" + mTrackballRemainsX 5398 + " mTrackballRemainsY=" + mTrackballRemainsY); 5399 } 5400 if (mNativeClass != 0 && nativePageShouldHandleShiftAndArrows()) { 5401 for (int i = 0; i < count; i++) { 5402 letPageHandleNavKey(selectKeyCode, time, true); 5403 } 5404 letPageHandleNavKey(selectKeyCode, time, false); 5405 } else if (navHandledKey(selectKeyCode, count, false, time)) { 5406 playSoundEffect(keyCodeToSoundsEffect(selectKeyCode)); 5407 } 5408 mTrackballRemainsX = mTrackballRemainsY = 0; 5409 } 5410 if (count >= TRACKBALL_SCROLL_COUNT) { 5411 int xMove = scaleTrackballX(xRate, width); 5412 int yMove = scaleTrackballY(yRate, height); 5413 if (DebugFlags.WEB_VIEW) { 5414 Log.v(LOGTAG, "doTrackball pinScrollBy" 5415 + " count=" + count 5416 + " xMove=" + xMove + " yMove=" + yMove 5417 + " mScrollX-oldScrollX=" + (mScrollX-oldScrollX) 5418 + " mScrollY-oldScrollY=" + (mScrollY-oldScrollY) 5419 ); 5420 } 5421 if (Math.abs(mScrollX - oldScrollX) > Math.abs(xMove)) { 5422 xMove = 0; 5423 } 5424 if (Math.abs(mScrollY - oldScrollY) > Math.abs(yMove)) { 5425 yMove = 0; 5426 } 5427 if (xMove != 0 || yMove != 0) { 5428 pinScrollBy(xMove, yMove, true, 0); 5429 } 5430 mUserScroll = true; 5431 } 5432 } 5433 5434 private int computeMaxScrollX() { 5435 return Math.max(computeHorizontalScrollRange() - getViewWidth(), 0); 5436 } 5437 5438 private int computeMaxScrollY() { 5439 return Math.max(computeVerticalScrollRange() + getTitleHeight() 5440 - getViewHeightWithTitle(), 0); 5441 } 5442 5443 boolean updateScrollCoordinates(int x, int y) { 5444 int oldX = mScrollX; 5445 int oldY = mScrollY; 5446 mScrollX = x; 5447 mScrollY = y; 5448 if (oldX != mScrollX || oldY != mScrollY) { 5449 onScrollChanged(mScrollX, mScrollY, oldX, oldY); 5450 return true; 5451 } else { 5452 return false; 5453 } 5454 } 5455 5456 public void flingScroll(int vx, int vy) { 5457 mScroller.fling(mScrollX, mScrollY, vx, vy, 0, computeMaxScrollX(), 0, 5458 computeMaxScrollY()); 5459 invalidate(); 5460 } 5461 5462 private void doFling() { 5463 if (mVelocityTracker == null) { 5464 return; 5465 } 5466 int maxX = computeMaxScrollX(); 5467 int maxY = computeMaxScrollY(); 5468 5469 mVelocityTracker.computeCurrentVelocity(1000, mMaximumFling); 5470 int vx = (int) mVelocityTracker.getXVelocity(); 5471 int vy = (int) mVelocityTracker.getYVelocity(); 5472 5473 if (mSnapScrollMode != SNAP_NONE) { 5474 if ((mSnapScrollMode & SNAP_X) == SNAP_X) { 5475 vy = 0; 5476 } else { 5477 vx = 0; 5478 } 5479 } 5480 if (true /* EMG release: make our fling more like Maps' */) { 5481 // maps cuts their velocity in half 5482 vx = vx * 3 / 4; 5483 vy = vy * 3 / 4; 5484 } 5485 if ((maxX == 0 && vy == 0) || (maxY == 0 && vx == 0)) { 5486 WebViewCore.resumePriority(); 5487 WebViewCore.resumeUpdatePicture(mWebViewCore); 5488 return; 5489 } 5490 float currentVelocity = mScroller.getCurrVelocity(); 5491 float velocity = (float) Math.hypot(vx, vy); 5492 if (mLastVelocity > 0 && currentVelocity > 0 && velocity 5493 > mLastVelocity * MINIMUM_VELOCITY_RATIO_FOR_ACCELERATION) { 5494 float deltaR = (float) (Math.abs(Math.atan2(mLastVelY, mLastVelX) 5495 - Math.atan2(vy, vx))); 5496 final float circle = (float) (Math.PI) * 2.0f; 5497 if (deltaR > circle * 0.9f || deltaR < circle * 0.1f) { 5498 vx += currentVelocity * mLastVelX / mLastVelocity; 5499 vy += currentVelocity * mLastVelY / mLastVelocity; 5500 velocity = (float) Math.hypot(vx, vy); 5501 if (DebugFlags.WEB_VIEW) { 5502 Log.v(LOGTAG, "doFling vx= " + vx + " vy=" + vy); 5503 } 5504 } else if (DebugFlags.WEB_VIEW) { 5505 Log.v(LOGTAG, "doFling missed " + deltaR / circle); 5506 } 5507 } else if (DebugFlags.WEB_VIEW) { 5508 Log.v(LOGTAG, "doFling start last=" + mLastVelocity 5509 + " current=" + currentVelocity 5510 + " vx=" + vx + " vy=" + vy 5511 + " maxX=" + maxX + " maxY=" + maxY 5512 + " mScrollX=" + mScrollX + " mScrollY=" + mScrollY); 5513 } 5514 mLastVelX = vx; 5515 mLastVelY = vy; 5516 mLastVelocity = velocity; 5517 5518 mScroller.fling(mScrollX, mScrollY, -vx, -vy, 0, maxX, 0, maxY); 5519 // TODO: duration is calculated based on velocity, if the range is 5520 // small, the animation will stop before duration is up. We may 5521 // want to calculate how long the animation is going to run to precisely 5522 // resume the webcore update. 5523 final int time = mScroller.getDuration(); 5524 mPrivateHandler.sendEmptyMessageDelayed(RESUME_WEBCORE_PRIORITY, time); 5525 awakenScrollBars(time); 5526 invalidate(); 5527 } 5528 5529 /** 5530 * Returns a view containing zoom controls i.e. +/- buttons. The caller is 5531 * in charge of installing this view to the view hierarchy. This view will 5532 * become visible when the user starts scrolling via touch and fade away if 5533 * the user does not interact with it. 5534 * <p/> 5535 * API version 3 introduces a built-in zoom mechanism that is shown 5536 * automatically by the MapView. This is the preferred approach for 5537 * showing the zoom UI. 5538 * 5539 * @deprecated The built-in zoom mechanism is preferred, see 5540 * {@link WebSettings#setBuiltInZoomControls(boolean)}. 5541 */ 5542 @Deprecated 5543 public View getZoomControls() { 5544 if (!getSettings().supportZoom()) { 5545 Log.w(LOGTAG, "This WebView doesn't support zoom."); 5546 return null; 5547 } 5548 return mZoomManager.getExternalZoomPicker(); 5549 } 5550 5551 void dismissZoomControl() { 5552 mZoomManager.dismissZoomPicker(); 5553 } 5554 5555 float getDefaultZoomScale() { 5556 return mZoomManager.mDefaultScale; 5557 } 5558 5559 /** 5560 * Perform zoom in in the webview 5561 * @return TRUE if zoom in succeeds. FALSE if no zoom changes. 5562 */ 5563 public boolean zoomIn() { 5564 return mZoomManager.zoomIn(); 5565 } 5566 5567 /** 5568 * Perform zoom out in the webview 5569 * @return TRUE if zoom out succeeds. FALSE if no zoom changes. 5570 */ 5571 public boolean zoomOut() { 5572 return mZoomManager.zoomOut(); 5573 } 5574 5575 private void updateSelection() { 5576 if (mNativeClass == 0) { 5577 return; 5578 } 5579 // mLastTouchX and mLastTouchY are the point in the current viewport 5580 int contentX = viewToContentX((int) mLastTouchX + mScrollX); 5581 int contentY = viewToContentY((int) mLastTouchY + mScrollY); 5582 Rect rect = new Rect(contentX - mNavSlop, contentY - mNavSlop, 5583 contentX + mNavSlop, contentY + mNavSlop); 5584 nativeSelectBestAt(rect); 5585 } 5586 5587 /** 5588 * Scroll the focused text field/area to match the WebTextView 5589 * @param xPercent New x position of the WebTextView from 0 to 1. 5590 * @param y New y position of the WebTextView in view coordinates 5591 */ 5592 /*package*/ void scrollFocusedTextInput(float xPercent, int y) { 5593 if (!inEditingMode() || mWebViewCore == null) { 5594 return; 5595 } 5596 mWebViewCore.sendMessage(EventHub.SCROLL_TEXT_INPUT, 5597 // Since this position is relative to the top of the text input 5598 // field, we do not need to take the title bar's height into 5599 // consideration. 5600 viewToContentDimension(y), 5601 new Float(xPercent)); 5602 } 5603 5604 /** 5605 * Set our starting point and time for a drag from the WebTextView. 5606 */ 5607 /*package*/ void initiateTextFieldDrag(float x, float y, long eventTime) { 5608 if (!inEditingMode()) { 5609 return; 5610 } 5611 mLastTouchX = x + (float) (mWebTextView.getLeft() - mScrollX); 5612 mLastTouchY = y + (float) (mWebTextView.getTop() - mScrollY); 5613 mLastTouchTime = eventTime; 5614 if (!mScroller.isFinished()) { 5615 abortAnimation(); 5616 mPrivateHandler.removeMessages(RESUME_WEBCORE_PRIORITY); 5617 } 5618 mSnapScrollMode = SNAP_NONE; 5619 mVelocityTracker = VelocityTracker.obtain(); 5620 mTouchMode = TOUCH_DRAG_START_MODE; 5621 } 5622 5623 /** 5624 * Given a motion event from the WebTextView, set its location to our 5625 * coordinates, and handle the event. 5626 */ 5627 /*package*/ boolean textFieldDrag(MotionEvent event) { 5628 if (!inEditingMode()) { 5629 return false; 5630 } 5631 mDragFromTextInput = true; 5632 event.offsetLocation((float) (mWebTextView.getLeft() - mScrollX), 5633 (float) (mWebTextView.getTop() - mScrollY)); 5634 boolean result = onTouchEvent(event); 5635 mDragFromTextInput = false; 5636 return result; 5637 } 5638 5639 /** 5640 * Due a touch up from a WebTextView. This will be handled by webkit to 5641 * change the selection. 5642 * @param event MotionEvent in the WebTextView's coordinates. 5643 */ 5644 /*package*/ void touchUpOnTextField(MotionEvent event) { 5645 if (!inEditingMode()) { 5646 return; 5647 } 5648 int x = viewToContentX((int) event.getX() + mWebTextView.getLeft()); 5649 int y = viewToContentY((int) event.getY() + mWebTextView.getTop()); 5650 nativeMotionUp(x, y, mNavSlop); 5651 } 5652 5653 /** 5654 * Called when pressing the center key or trackball on a textfield. 5655 */ 5656 /*package*/ void centerKeyPressOnTextField() { 5657 mWebViewCore.sendMessage(EventHub.CLICK, nativeCursorFramePointer(), 5658 nativeCursorNodePointer()); 5659 } 5660 5661 private void doShortPress() { 5662 if (mNativeClass == 0) { 5663 return; 5664 } 5665 if (mPreventDefault == PREVENT_DEFAULT_YES) { 5666 return; 5667 } 5668 mTouchMode = TOUCH_DONE_MODE; 5669 switchOutDrawHistory(); 5670 // mLastTouchX and mLastTouchY are the point in the current viewport 5671 int contentX = viewToContentX((int) mLastTouchX + mScrollX); 5672 int contentY = viewToContentY((int) mLastTouchY + mScrollY); 5673 if (getSettings().supportTouchOnly()) { 5674 removeTouchHighlight(false); 5675 WebViewCore.TouchUpData touchUpData = new WebViewCore.TouchUpData(); 5676 // use "0" as generation id to inform WebKit to use the same x/y as 5677 // it used when processing GET_TOUCH_HIGHLIGHT_RECTS 5678 touchUpData.mMoveGeneration = 0; 5679 mWebViewCore.sendMessage(EventHub.TOUCH_UP, touchUpData); 5680 } else if (nativePointInNavCache(contentX, contentY, mNavSlop)) { 5681 WebViewCore.MotionUpData motionUpData = new WebViewCore 5682 .MotionUpData(); 5683 motionUpData.mFrame = nativeCacheHitFramePointer(); 5684 motionUpData.mNode = nativeCacheHitNodePointer(); 5685 motionUpData.mBounds = nativeCacheHitNodeBounds(); 5686 motionUpData.mX = contentX; 5687 motionUpData.mY = contentY; 5688 mWebViewCore.sendMessageAtFrontOfQueue(EventHub.VALID_NODE_BOUNDS, 5689 motionUpData); 5690 } else { 5691 doMotionUp(contentX, contentY); 5692 } 5693 } 5694 5695 private void doMotionUp(int contentX, int contentY) { 5696 if (mLogEvent && nativeMotionUp(contentX, contentY, mNavSlop)) { 5697 EventLog.writeEvent(EventLogTags.BROWSER_SNAP_CENTER); 5698 } 5699 if (nativeHasCursorNode() && !nativeCursorIsTextInput()) { 5700 playSoundEffect(SoundEffectConstants.CLICK); 5701 } 5702 } 5703 5704 /* 5705 * Return true if the view (Plugin) is fully visible and maximized inside 5706 * the WebView. 5707 */ 5708 private boolean isPluginFitOnScreen(ViewManager.ChildView view) { 5709 int viewWidth = getViewWidth(); 5710 int viewHeight = getViewHeightWithTitle(); 5711 float scale = Math.min((float) viewWidth / view.width, 5712 (float) viewHeight / view.height); 5713 if (scale < mZoomManager.mMinZoomScale) { 5714 scale = mZoomManager.mMinZoomScale; 5715 } else if (scale > mZoomManager.mMaxZoomScale) { 5716 scale = mZoomManager.mMaxZoomScale; 5717 } 5718 if (!mZoomManager.willScaleTriggerZoom(scale)) { 5719 if (contentToViewX(view.x) >= mScrollX 5720 && contentToViewX(view.x + view.width) <= mScrollX 5721 + viewWidth 5722 && contentToViewY(view.y) >= mScrollY 5723 && contentToViewY(view.y + view.height) <= mScrollY 5724 + viewHeight) { 5725 return true; 5726 } 5727 } 5728 return false; 5729 } 5730 5731 /* 5732 * Maximize and center the rectangle, specified in the document coordinate 5733 * space, inside the WebView. If the zoom doesn't need to be changed, do an 5734 * animated scroll to center it. If the zoom needs to be changed, find the 5735 * zoom center and do a smooth zoom transition. 5736 */ 5737 private void centerFitRect(int docX, int docY, int docWidth, int docHeight) { 5738 int viewWidth = getViewWidth(); 5739 int viewHeight = getViewHeightWithTitle(); 5740 float scale = Math.min((float) viewWidth / docWidth, (float) viewHeight 5741 / docHeight); 5742 if (scale < mZoomManager.mMinZoomScale) { 5743 scale = mZoomManager.mMinZoomScale; 5744 } else if (scale > mZoomManager.mMaxZoomScale) { 5745 scale = mZoomManager.mMaxZoomScale; 5746 } 5747 if (!mZoomManager.willScaleTriggerZoom(scale)) { 5748 pinScrollTo(contentToViewX(docX + docWidth / 2) - viewWidth / 2, 5749 contentToViewY(docY + docHeight / 2) - viewHeight / 2, 5750 true, 0); 5751 } else { 5752 float actualScale = mZoomManager.mActualScale; 5753 float oldScreenX = docX * actualScale - mScrollX; 5754 float rectViewX = docX * scale; 5755 float rectViewWidth = docWidth * scale; 5756 float newMaxWidth = mContentWidth * scale; 5757 float newScreenX = (viewWidth - rectViewWidth) / 2; 5758 // pin the newX to the WebView 5759 if (newScreenX > rectViewX) { 5760 newScreenX = rectViewX; 5761 } else if (newScreenX > (newMaxWidth - rectViewX - rectViewWidth)) { 5762 newScreenX = viewWidth - (newMaxWidth - rectViewX); 5763 } 5764 float zoomCenterX = (oldScreenX * scale - newScreenX * actualScale) 5765 / (scale - actualScale); 5766 float oldScreenY = docY * actualScale + getTitleHeight() 5767 - mScrollY; 5768 float rectViewY = docY * scale + getTitleHeight(); 5769 float rectViewHeight = docHeight * scale; 5770 float newMaxHeight = mContentHeight * scale + getTitleHeight(); 5771 float newScreenY = (viewHeight - rectViewHeight) / 2; 5772 // pin the newY to the WebView 5773 if (newScreenY > rectViewY) { 5774 newScreenY = rectViewY; 5775 } else if (newScreenY > (newMaxHeight - rectViewY - rectViewHeight)) { 5776 newScreenY = viewHeight - (newMaxHeight - rectViewY); 5777 } 5778 float zoomCenterY = (oldScreenY * scale - newScreenY * actualScale) 5779 / (scale - actualScale); 5780 mZoomManager.setZoomCenter(zoomCenterX, zoomCenterY); 5781 mZoomManager.startZoomAnimation(scale, false); 5782 } 5783 } 5784 5785 // Rule for double tap: 5786 // 1. if the current scale is not same as the text wrap scale and layout 5787 // algorithm is NARROW_COLUMNS, fit to column; 5788 // 2. if the current state is not overview mode, change to overview mode; 5789 // 3. if the current state is overview mode, change to default scale. 5790 private void doDoubleTap() { 5791 if (mWebViewCore.getSettings().getUseWideViewPort() == false) { 5792 return; 5793 } 5794 mZoomManager.setZoomCenter(mLastTouchX, mLastTouchY); 5795 mAnchorX = viewToContentX((int) mLastTouchX + mScrollX); 5796 mAnchorY = viewToContentY((int) mLastTouchX + mScrollY); 5797 WebSettings settings = getSettings(); 5798 settings.setDoubleTapToastCount(0); 5799 // remove the zoom control after double tap 5800 mZoomManager.dismissZoomPicker(); 5801 ViewManager.ChildView plugin = mViewManager.hitTest(mAnchorX, mAnchorY); 5802 if (plugin != null) { 5803 if (isPluginFitOnScreen(plugin)) { 5804 mZoomManager.zoomToOverview(); 5805 } else { 5806 mZoomManager.mInZoomOverview = false; 5807 centerFitRect(plugin.x, plugin.y, plugin.width, plugin.height); 5808 } 5809 return; 5810 } 5811 boolean zoomToDefault = false; 5812 if ((settings.getLayoutAlgorithm() == WebSettings.LayoutAlgorithm.NARROW_COLUMNS) 5813 && mZoomManager.willScaleTriggerZoom(mZoomManager.mTextWrapScale)) { 5814 mZoomManager.refreshZoomScale(true); 5815 float overviewScale = (float) getViewWidth() / mZoomManager.mZoomOverviewWidth; 5816 if (!mZoomManager.willScaleTriggerZoom(overviewScale)) { 5817 mZoomManager.mInZoomOverview = true; 5818 } 5819 } else if (!mZoomManager.mInZoomOverview) { 5820 float newScale = (float) getViewWidth() / mZoomManager.mZoomOverviewWidth; 5821 if (mZoomManager.willScaleTriggerZoom(newScale)) { 5822 mZoomManager.zoomToOverview(); 5823 } else if (mZoomManager.willScaleTriggerZoom(mZoomManager.mDefaultScale)) { 5824 zoomToDefault = true; 5825 } 5826 } else { 5827 zoomToDefault = true; 5828 } 5829 if (zoomToDefault) { 5830 int left = nativeGetBlockLeftEdge(mAnchorX, mAnchorY, mZoomManager.mActualScale); 5831 if (left != NO_LEFTEDGE) { 5832 // add a 5pt padding to the left edge. 5833 int viewLeft = contentToViewX(left < 5 ? 0 : (left - 5)) 5834 - mScrollX; 5835 // Re-calculate the zoom center so that the new scroll x will be 5836 // on the left edge. 5837 if (viewLeft > 0) { 5838 mZoomManager.mZoomCenterX = viewLeft * mZoomManager.mDefaultScale 5839 / (mZoomManager.mDefaultScale - mZoomManager.mActualScale); 5840 } else { 5841 scrollBy(viewLeft, 0); 5842 mZoomManager.mZoomCenterX = 0; 5843 } 5844 } 5845 mZoomManager.zoomToDefaultLevel(true); 5846 } 5847 } 5848 5849 // Called by JNI to handle a touch on a node representing an email address, 5850 // address, or phone number 5851 private void overrideLoading(String url) { 5852 mCallbackProxy.uiOverrideUrlLoading(url); 5853 } 5854 5855 @Override 5856 public boolean requestFocus(int direction, Rect previouslyFocusedRect) { 5857 // FIXME: If a subwindow is showing find, and the user touches the 5858 // background window, it can steal focus. 5859 if (mFindIsUp) return false; 5860 boolean result = false; 5861 if (inEditingMode()) { 5862 result = mWebTextView.requestFocus(direction, 5863 previouslyFocusedRect); 5864 } else { 5865 result = super.requestFocus(direction, previouslyFocusedRect); 5866 if (mWebViewCore.getSettings().getNeedInitialFocus()) { 5867 // For cases such as GMail, where we gain focus from a direction, 5868 // we want to move to the first available link. 5869 // FIXME: If there are no visible links, we may not want to 5870 int fakeKeyDirection = 0; 5871 switch(direction) { 5872 case View.FOCUS_UP: 5873 fakeKeyDirection = KeyEvent.KEYCODE_DPAD_UP; 5874 break; 5875 case View.FOCUS_DOWN: 5876 fakeKeyDirection = KeyEvent.KEYCODE_DPAD_DOWN; 5877 break; 5878 case View.FOCUS_LEFT: 5879 fakeKeyDirection = KeyEvent.KEYCODE_DPAD_LEFT; 5880 break; 5881 case View.FOCUS_RIGHT: 5882 fakeKeyDirection = KeyEvent.KEYCODE_DPAD_RIGHT; 5883 break; 5884 default: 5885 return result; 5886 } 5887 if (mNativeClass != 0 && !nativeHasCursorNode()) { 5888 navHandledKey(fakeKeyDirection, 1, true, 0); 5889 } 5890 } 5891 } 5892 return result; 5893 } 5894 5895 @Override 5896 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 5897 super.onMeasure(widthMeasureSpec, heightMeasureSpec); 5898 5899 int heightMode = MeasureSpec.getMode(heightMeasureSpec); 5900 int heightSize = MeasureSpec.getSize(heightMeasureSpec); 5901 int widthMode = MeasureSpec.getMode(widthMeasureSpec); 5902 int widthSize = MeasureSpec.getSize(widthMeasureSpec); 5903 5904 int measuredHeight = heightSize; 5905 int measuredWidth = widthSize; 5906 5907 // Grab the content size from WebViewCore. 5908 int contentHeight = contentToViewDimension(mContentHeight); 5909 int contentWidth = contentToViewDimension(mContentWidth); 5910 5911// Log.d(LOGTAG, "------- measure " + heightMode); 5912 5913 if (heightMode != MeasureSpec.EXACTLY) { 5914 mHeightCanMeasure = true; 5915 measuredHeight = contentHeight; 5916 if (heightMode == MeasureSpec.AT_MOST) { 5917 // If we are larger than the AT_MOST height, then our height can 5918 // no longer be measured and we should scroll internally. 5919 if (measuredHeight > heightSize) { 5920 measuredHeight = heightSize; 5921 mHeightCanMeasure = false; 5922 } 5923 } 5924 } else { 5925 mHeightCanMeasure = false; 5926 } 5927 if (mNativeClass != 0) { 5928 nativeSetHeightCanMeasure(mHeightCanMeasure); 5929 } 5930 // For the width, always use the given size unless unspecified. 5931 if (widthMode == MeasureSpec.UNSPECIFIED) { 5932 mWidthCanMeasure = true; 5933 measuredWidth = contentWidth; 5934 } else { 5935 mWidthCanMeasure = false; 5936 } 5937 5938 synchronized (this) { 5939 setMeasuredDimension(measuredWidth, measuredHeight); 5940 } 5941 } 5942 5943 @Override 5944 public boolean requestChildRectangleOnScreen(View child, 5945 Rect rect, 5946 boolean immediate) { 5947 // don't scroll while in zoom animation. When it is done, we will adjust 5948 // the necessary components (e.g., WebTextView if it is in editing mode) 5949 if(mZoomManager.isZoomAnimating()) { 5950 return false; 5951 } 5952 5953 rect.offset(child.getLeft() - child.getScrollX(), 5954 child.getTop() - child.getScrollY()); 5955 5956 Rect content = new Rect(viewToContentX(mScrollX), 5957 viewToContentY(mScrollY), 5958 viewToContentX(mScrollX + getWidth() 5959 - getVerticalScrollbarWidth()), 5960 viewToContentY(mScrollY + getViewHeightWithTitle())); 5961 content = nativeSubtractLayers(content); 5962 int screenTop = contentToViewY(content.top); 5963 int screenBottom = contentToViewY(content.bottom); 5964 int height = screenBottom - screenTop; 5965 int scrollYDelta = 0; 5966 5967 if (rect.bottom > screenBottom) { 5968 int oneThirdOfScreenHeight = height / 3; 5969 if (rect.height() > 2 * oneThirdOfScreenHeight) { 5970 // If the rectangle is too tall to fit in the bottom two thirds 5971 // of the screen, place it at the top. 5972 scrollYDelta = rect.top - screenTop; 5973 } else { 5974 // If the rectangle will still fit on screen, we want its 5975 // top to be in the top third of the screen. 5976 scrollYDelta = rect.top - (screenTop + oneThirdOfScreenHeight); 5977 } 5978 } else if (rect.top < screenTop) { 5979 scrollYDelta = rect.top - screenTop; 5980 } 5981 5982 int screenLeft = contentToViewX(content.left); 5983 int screenRight = contentToViewX(content.right); 5984 int width = screenRight - screenLeft; 5985 int scrollXDelta = 0; 5986 5987 if (rect.right > screenRight && rect.left > screenLeft) { 5988 if (rect.width() > width) { 5989 scrollXDelta += (rect.left - screenLeft); 5990 } else { 5991 scrollXDelta += (rect.right - screenRight); 5992 } 5993 } else if (rect.left < screenLeft) { 5994 scrollXDelta -= (screenLeft - rect.left); 5995 } 5996 5997 if ((scrollYDelta | scrollXDelta) != 0) { 5998 return pinScrollBy(scrollXDelta, scrollYDelta, !immediate, 0); 5999 } 6000 6001 return false; 6002 } 6003 6004 /* package */ void replaceTextfieldText(int oldStart, int oldEnd, 6005 String replace, int newStart, int newEnd) { 6006 WebViewCore.ReplaceTextData arg = new WebViewCore.ReplaceTextData(); 6007 arg.mReplace = replace; 6008 arg.mNewStart = newStart; 6009 arg.mNewEnd = newEnd; 6010 mTextGeneration++; 6011 arg.mTextGeneration = mTextGeneration; 6012 mWebViewCore.sendMessage(EventHub.REPLACE_TEXT, oldStart, oldEnd, arg); 6013 } 6014 6015 /* package */ void passToJavaScript(String currentText, KeyEvent event) { 6016 WebViewCore.JSKeyData arg = new WebViewCore.JSKeyData(); 6017 arg.mEvent = event; 6018 arg.mCurrentText = currentText; 6019 // Increase our text generation number, and pass it to webcore thread 6020 mTextGeneration++; 6021 mWebViewCore.sendMessage(EventHub.PASS_TO_JS, mTextGeneration, 0, arg); 6022 // WebKit's document state is not saved until about to leave the page. 6023 // To make sure the host application, like Browser, has the up to date 6024 // document state when it goes to background, we force to save the 6025 // document state. 6026 mWebViewCore.removeMessages(EventHub.SAVE_DOCUMENT_STATE); 6027 mWebViewCore.sendMessageDelayed(EventHub.SAVE_DOCUMENT_STATE, 6028 cursorData(), 1000); 6029 } 6030 6031 /* package */ synchronized WebViewCore getWebViewCore() { 6032 return mWebViewCore; 6033 } 6034 6035 //------------------------------------------------------------------------- 6036 // Methods can be called from a separate thread, like WebViewCore 6037 // If it needs to call the View system, it has to send message. 6038 //------------------------------------------------------------------------- 6039 6040 /** 6041 * General handler to receive message coming from webkit thread 6042 */ 6043 class PrivateHandler extends Handler { 6044 @Override 6045 public void handleMessage(Message msg) { 6046 // exclude INVAL_RECT_MSG_ID since it is frequently output 6047 if (DebugFlags.WEB_VIEW && msg.what != INVAL_RECT_MSG_ID) { 6048 if (msg.what >= FIRST_PRIVATE_MSG_ID 6049 && msg.what <= LAST_PRIVATE_MSG_ID) { 6050 Log.v(LOGTAG, HandlerPrivateDebugString[msg.what 6051 - FIRST_PRIVATE_MSG_ID]); 6052 } else if (msg.what >= FIRST_PACKAGE_MSG_ID 6053 && msg.what <= LAST_PACKAGE_MSG_ID) { 6054 Log.v(LOGTAG, HandlerPackageDebugString[msg.what 6055 - FIRST_PACKAGE_MSG_ID]); 6056 } else { 6057 Log.v(LOGTAG, Integer.toString(msg.what)); 6058 } 6059 } 6060 if (mWebViewCore == null) { 6061 // after WebView's destroy() is called, skip handling messages. 6062 return; 6063 } 6064 switch (msg.what) { 6065 case REMEMBER_PASSWORD: { 6066 mDatabase.setUsernamePassword( 6067 msg.getData().getString("host"), 6068 msg.getData().getString("username"), 6069 msg.getData().getString("password")); 6070 ((Message) msg.obj).sendToTarget(); 6071 break; 6072 } 6073 case NEVER_REMEMBER_PASSWORD: { 6074 mDatabase.setUsernamePassword( 6075 msg.getData().getString("host"), null, null); 6076 ((Message) msg.obj).sendToTarget(); 6077 break; 6078 } 6079 case PREVENT_DEFAULT_TIMEOUT: { 6080 // if timeout happens, cancel it so that it won't block UI 6081 // to continue handling touch events 6082 if ((msg.arg1 == MotionEvent.ACTION_DOWN 6083 && mPreventDefault == PREVENT_DEFAULT_MAYBE_YES) 6084 || (msg.arg1 == MotionEvent.ACTION_MOVE 6085 && mPreventDefault == PREVENT_DEFAULT_NO_FROM_TOUCH_DOWN)) { 6086 cancelWebCoreTouchEvent( 6087 viewToContentX((int) mLastTouchX + mScrollX), 6088 viewToContentY((int) mLastTouchY + mScrollY), 6089 true); 6090 } 6091 break; 6092 } 6093 case SWITCH_TO_SHORTPRESS: { 6094 if (mTouchMode == TOUCH_INIT_MODE) { 6095 if (!getSettings().supportTouchOnly() 6096 && mPreventDefault != PREVENT_DEFAULT_YES) { 6097 mTouchMode = TOUCH_SHORTPRESS_START_MODE; 6098 updateSelection(); 6099 } else { 6100 // set to TOUCH_SHORTPRESS_MODE so that it won't 6101 // trigger double tap any more 6102 mTouchMode = TOUCH_SHORTPRESS_MODE; 6103 } 6104 } else if (mTouchMode == TOUCH_DOUBLE_TAP_MODE) { 6105 mTouchMode = TOUCH_DONE_MODE; 6106 } 6107 break; 6108 } 6109 case SWITCH_TO_LONGPRESS: { 6110 if (getSettings().supportTouchOnly()) { 6111 removeTouchHighlight(false); 6112 } 6113 if (inFullScreenMode() || mDeferTouchProcess) { 6114 TouchEventData ted = new TouchEventData(); 6115 ted.mAction = WebViewCore.ACTION_LONGPRESS; 6116 ted.mX = viewToContentX((int) mLastTouchX + mScrollX); 6117 ted.mY = viewToContentY((int) mLastTouchY + mScrollY); 6118 // metaState for long press is tricky. Should it be the 6119 // state when the press started or when the press was 6120 // released? Or some intermediary key state? For 6121 // simplicity for now, we don't set it. 6122 ted.mMetaState = 0; 6123 ted.mReprocess = mDeferTouchProcess; 6124 mWebViewCore.sendMessage(EventHub.TOUCH_EVENT, ted); 6125 } else if (mPreventDefault != PREVENT_DEFAULT_YES) { 6126 mTouchMode = TOUCH_DONE_MODE; 6127 performLongClick(); 6128 } 6129 break; 6130 } 6131 case RELEASE_SINGLE_TAP: { 6132 doShortPress(); 6133 break; 6134 } 6135 case SCROLL_BY_MSG_ID: 6136 setContentScrollBy(msg.arg1, msg.arg2, (Boolean) msg.obj); 6137 break; 6138 case SYNC_SCROLL_TO_MSG_ID: 6139 if (mUserScroll) { 6140 // if user has scrolled explicitly, don't sync the 6141 // scroll position any more 6142 mUserScroll = false; 6143 break; 6144 } 6145 // fall through 6146 case SCROLL_TO_MSG_ID: 6147 if (setContentScrollTo(msg.arg1, msg.arg2)) { 6148 // if we can't scroll to the exact position due to pin, 6149 // send a message to WebCore to re-scroll when we get a 6150 // new picture 6151 mUserScroll = false; 6152 mWebViewCore.sendMessage(EventHub.SYNC_SCROLL, 6153 msg.arg1, msg.arg2); 6154 } 6155 break; 6156 case SPAWN_SCROLL_TO_MSG_ID: 6157 spawnContentScrollTo(msg.arg1, msg.arg2); 6158 break; 6159 case UPDATE_ZOOM_RANGE: { 6160 WebViewCore.RestoreState restoreState 6161 = (WebViewCore.RestoreState) msg.obj; 6162 // mScrollX contains the new minPrefWidth 6163 updateZoomRange(restoreState, getViewWidth(), 6164 restoreState.mScrollX, false); 6165 break; 6166 } 6167 case NEW_PICTURE_MSG_ID: { 6168 // If we've previously delayed deleting a root 6169 // layer, do it now. 6170 if (mDelayedDeleteRootLayer) { 6171 mDelayedDeleteRootLayer = false; 6172 nativeSetRootLayer(0); 6173 } 6174 WebSettings settings = mWebViewCore.getSettings(); 6175 // called for new content 6176 final int viewWidth = getViewWidth(); 6177 final WebViewCore.DrawData draw = 6178 (WebViewCore.DrawData) msg.obj; 6179 final Point viewSize = draw.mViewPoint; 6180 boolean useWideViewport = settings.getUseWideViewPort(); 6181 WebViewCore.RestoreState restoreState = draw.mRestoreState; 6182 boolean hasRestoreState = restoreState != null; 6183 if (hasRestoreState) { 6184 updateZoomRange(restoreState, viewSize.x, 6185 draw.mMinPrefWidth, true); 6186 if (!mDrawHistory) { 6187 mZoomManager.mInZoomOverview = false; 6188 6189 if (mInitialScaleInPercent > 0) { 6190 final float initialScale = mInitialScaleInPercent / 100.0f; 6191 final boolean reflowText = 6192 mInitialScaleInPercent != mZoomManager.mTextWrapScale * 100; 6193 mZoomManager.setZoomScale(initialScale, reflowText); 6194 } else if (restoreState.mViewScale > 0) { 6195 mZoomManager.mTextWrapScale = restoreState.mTextWrapScale; 6196 mZoomManager.setZoomScale(restoreState.mViewScale, false); 6197 } else { 6198 mZoomManager.mInZoomOverview = useWideViewport 6199 && settings.getLoadWithOverviewMode(); 6200 float scale; 6201 if (mZoomManager.mInZoomOverview) { 6202 scale = (float) viewWidth 6203 / DEFAULT_VIEWPORT_WIDTH; 6204 } else { 6205 scale = restoreState.mTextWrapScale; 6206 } 6207 mZoomManager.setZoomScale(scale, 6208 ZoomManager.exceedsMinScaleIncrement( 6209 mZoomManager.mTextWrapScale, scale)); 6210 } 6211 setContentScrollTo(restoreState.mScrollX, 6212 restoreState.mScrollY); 6213 // As we are on a new page, remove the WebTextView. This 6214 // is necessary for page loads driven by webkit, and in 6215 // particular when the user was on a password field, so 6216 // the WebTextView was visible. 6217 clearTextEntry(false); 6218 // update the zoom buttons as the scale can be changed 6219 mZoomManager.updateZoomPicker(); 6220 } 6221 } 6222 // We update the layout (i.e. request a layout from the 6223 // view system) if the last view size that we sent to 6224 // WebCore matches the view size of the picture we just 6225 // received in the fixed dimension. 6226 final boolean updateLayout = viewSize.x == mLastWidthSent 6227 && viewSize.y == mLastHeightSent; 6228 recordNewContentSize(draw.mWidthHeight.x, 6229 draw.mWidthHeight.y, updateLayout); 6230 if (DebugFlags.WEB_VIEW) { 6231 Rect b = draw.mInvalRegion.getBounds(); 6232 Log.v(LOGTAG, "NEW_PICTURE_MSG_ID {" + 6233 b.left+","+b.top+","+b.right+","+b.bottom+"}"); 6234 } 6235 invalidateContentRect(draw.mInvalRegion.getBounds()); 6236 if (mPictureListener != null) { 6237 mPictureListener.onNewPicture(WebView.this, capturePicture()); 6238 } 6239 if (useWideViewport) { 6240 // limit mZoomOverviewWidth upper bound to 6241 // sMaxViewportWidth so that if the page doesn't behave 6242 // well, the WebView won't go insane. limit the lower 6243 // bound to match the default scale for mobile sites. 6244 mZoomManager.mZoomOverviewWidth = Math.min(sMaxViewportWidth, Math 6245 .max((int) (viewWidth / mZoomManager.mDefaultScale), 6246 Math.max(draw.mMinPrefWidth, 6247 draw.mViewPoint.x))); 6248 } 6249 if (!mZoomManager.mMinZoomScaleFixed) { 6250 mZoomManager.mMinZoomScale = (float) viewWidth / 6251 mZoomManager.mZoomOverviewWidth; 6252 } 6253 if (!mDrawHistory && mZoomManager.mInZoomOverview) { 6254 // fit the content width to the current view. Ignore 6255 // the rounding error case. 6256 if (Math.abs((viewWidth * mZoomManager.mInvActualScale) 6257 - mZoomManager.mZoomOverviewWidth) > 1) { 6258 mZoomManager.setZoomScale( 6259 (float) viewWidth / mZoomManager.mZoomOverviewWidth, 6260 !mZoomManager.willScaleTriggerZoom(mZoomManager.mTextWrapScale)); 6261 } 6262 } 6263 if (draw.mFocusSizeChanged && inEditingMode()) { 6264 mFocusSizeChanged = true; 6265 } 6266 if (hasRestoreState) { 6267 mViewManager.postReadyToDrawAll(); 6268 } 6269 break; 6270 } 6271 case WEBCORE_INITIALIZED_MSG_ID: 6272 // nativeCreate sets mNativeClass to a non-zero value 6273 nativeCreate(msg.arg1); 6274 break; 6275 case UPDATE_TEXTFIELD_TEXT_MSG_ID: 6276 // Make sure that the textfield is currently focused 6277 // and representing the same node as the pointer. 6278 if (inEditingMode() && 6279 mWebTextView.isSameTextField(msg.arg1)) { 6280 if (msg.getData().getBoolean("password")) { 6281 Spannable text = (Spannable) mWebTextView.getText(); 6282 int start = Selection.getSelectionStart(text); 6283 int end = Selection.getSelectionEnd(text); 6284 mWebTextView.setInPassword(true); 6285 // Restore the selection, which may have been 6286 // ruined by setInPassword. 6287 Spannable pword = 6288 (Spannable) mWebTextView.getText(); 6289 Selection.setSelection(pword, start, end); 6290 // If the text entry has created more events, ignore 6291 // this one. 6292 } else if (msg.arg2 == mTextGeneration) { 6293 mWebTextView.setTextAndKeepSelection( 6294 (String) msg.obj); 6295 } 6296 } 6297 break; 6298 case REQUEST_KEYBOARD_WITH_SELECTION_MSG_ID: 6299 displaySoftKeyboard(true); 6300 // fall through to UPDATE_TEXT_SELECTION_MSG_ID 6301 case UPDATE_TEXT_SELECTION_MSG_ID: 6302 updateTextSelectionFromMessage(msg.arg1, msg.arg2, 6303 (WebViewCore.TextSelectionData) msg.obj); 6304 break; 6305 case RETURN_LABEL: 6306 if (inEditingMode() 6307 && mWebTextView.isSameTextField(msg.arg1)) { 6308 mWebTextView.setHint((String) msg.obj); 6309 InputMethodManager imm 6310 = InputMethodManager.peekInstance(); 6311 // The hint is propagated to the IME in 6312 // onCreateInputConnection. If the IME is already 6313 // active, restart it so that its hint text is updated. 6314 if (imm != null && imm.isActive(mWebTextView)) { 6315 imm.restartInput(mWebTextView); 6316 } 6317 } 6318 break; 6319 case UNHANDLED_NAV_KEY: 6320 navHandledKey(msg.arg1, 1, false, 0); 6321 break; 6322 case UPDATE_TEXT_ENTRY_MSG_ID: 6323 // this is sent after finishing resize in WebViewCore. Make 6324 // sure the text edit box is still on the screen. 6325 if (inEditingMode() && nativeCursorIsTextInput()) { 6326 mWebTextView.bringIntoView(); 6327 rebuildWebTextView(); 6328 } 6329 break; 6330 case CLEAR_TEXT_ENTRY: 6331 clearTextEntry(false); 6332 break; 6333 case INVAL_RECT_MSG_ID: { 6334 Rect r = (Rect)msg.obj; 6335 if (r == null) { 6336 invalidate(); 6337 } else { 6338 // we need to scale r from content into view coords, 6339 // which viewInvalidate() does for us 6340 viewInvalidate(r.left, r.top, r.right, r.bottom); 6341 } 6342 break; 6343 } 6344 case IMMEDIATE_REPAINT_MSG_ID: { 6345 invalidate(); 6346 break; 6347 } 6348 case SET_ROOT_LAYER_MSG_ID: { 6349 if (0 == msg.arg1) { 6350 // Null indicates deleting the old layer, but 6351 // don't actually do so until we've got the 6352 // new page to display. 6353 mDelayedDeleteRootLayer = true; 6354 } else { 6355 mDelayedDeleteRootLayer = false; 6356 nativeSetRootLayer(msg.arg1); 6357 invalidate(); 6358 } 6359 break; 6360 } 6361 case REQUEST_FORM_DATA: 6362 AutoCompleteAdapter adapter = (AutoCompleteAdapter) msg.obj; 6363 if (mWebTextView.isSameTextField(msg.arg1)) { 6364 mWebTextView.setAdapterCustom(adapter); 6365 } 6366 break; 6367 case RESUME_WEBCORE_PRIORITY: 6368 WebViewCore.resumePriority(); 6369 WebViewCore.resumeUpdatePicture(mWebViewCore); 6370 break; 6371 6372 case LONG_PRESS_CENTER: 6373 // as this is shared by keydown and trackballdown, reset all 6374 // the states 6375 mGotCenterDown = false; 6376 mTrackballDown = false; 6377 performLongClick(); 6378 break; 6379 6380 case WEBCORE_NEED_TOUCH_EVENTS: 6381 mForwardTouchEvents = (msg.arg1 != 0); 6382 break; 6383 6384 case PREVENT_TOUCH_ID: 6385 if (inFullScreenMode()) { 6386 break; 6387 } 6388 if (msg.obj == null) { 6389 if (msg.arg1 == MotionEvent.ACTION_DOWN 6390 && mPreventDefault == PREVENT_DEFAULT_MAYBE_YES) { 6391 // if prevent default is called from WebCore, UI 6392 // will not handle the rest of the touch events any 6393 // more. 6394 mPreventDefault = msg.arg2 == 1 ? PREVENT_DEFAULT_YES 6395 : PREVENT_DEFAULT_NO_FROM_TOUCH_DOWN; 6396 } else if (msg.arg1 == MotionEvent.ACTION_MOVE 6397 && mPreventDefault == PREVENT_DEFAULT_NO_FROM_TOUCH_DOWN) { 6398 // the return for the first ACTION_MOVE will decide 6399 // whether UI will handle touch or not. Currently no 6400 // support for alternating prevent default 6401 mPreventDefault = msg.arg2 == 1 ? PREVENT_DEFAULT_YES 6402 : PREVENT_DEFAULT_NO; 6403 } 6404 if (mPreventDefault == PREVENT_DEFAULT_YES) { 6405 mTouchHighlightRegion.setEmpty(); 6406 } 6407 } else if (msg.arg2 == 0) { 6408 // prevent default is not called in WebCore, so the 6409 // message needs to be reprocessed in UI 6410 TouchEventData ted = (TouchEventData) msg.obj; 6411 switch (ted.mAction) { 6412 case MotionEvent.ACTION_DOWN: 6413 mLastDeferTouchX = contentToViewX(ted.mX) 6414 - mScrollX; 6415 mLastDeferTouchY = contentToViewY(ted.mY) 6416 - mScrollY; 6417 mDeferTouchMode = TOUCH_INIT_MODE; 6418 break; 6419 case MotionEvent.ACTION_MOVE: { 6420 // no snapping in defer process 6421 int x = contentToViewX(ted.mX) - mScrollX; 6422 int y = contentToViewY(ted.mY) - mScrollY; 6423 if (mDeferTouchMode != TOUCH_DRAG_MODE) { 6424 mDeferTouchMode = TOUCH_DRAG_MODE; 6425 mLastDeferTouchX = x; 6426 mLastDeferTouchY = y; 6427 startDrag(); 6428 } 6429 int deltaX = pinLocX((int) (mScrollX 6430 + mLastDeferTouchX - x)) 6431 - mScrollX; 6432 int deltaY = pinLocY((int) (mScrollY 6433 + mLastDeferTouchY - y)) 6434 - mScrollY; 6435 doDrag(deltaX, deltaY); 6436 if (deltaX != 0) mLastDeferTouchX = x; 6437 if (deltaY != 0) mLastDeferTouchY = y; 6438 break; 6439 } 6440 case MotionEvent.ACTION_UP: 6441 case MotionEvent.ACTION_CANCEL: 6442 if (mDeferTouchMode == TOUCH_DRAG_MODE) { 6443 // no fling in defer process 6444 WebViewCore.resumePriority(); 6445 WebViewCore.resumeUpdatePicture(mWebViewCore); 6446 } 6447 mDeferTouchMode = TOUCH_DONE_MODE; 6448 break; 6449 case WebViewCore.ACTION_DOUBLETAP: 6450 // doDoubleTap() needs mLastTouchX/Y as anchor 6451 mLastTouchX = contentToViewX(ted.mX) - mScrollX; 6452 mLastTouchY = contentToViewY(ted.mY) - mScrollY; 6453 doDoubleTap(); 6454 mDeferTouchMode = TOUCH_DONE_MODE; 6455 break; 6456 case WebViewCore.ACTION_LONGPRESS: 6457 HitTestResult hitTest = getHitTestResult(); 6458 if (hitTest != null && hitTest.mType 6459 != HitTestResult.UNKNOWN_TYPE) { 6460 performLongClick(); 6461 } 6462 mDeferTouchMode = TOUCH_DONE_MODE; 6463 break; 6464 } 6465 } 6466 break; 6467 6468 case REQUEST_KEYBOARD: 6469 if (msg.arg1 == 0) { 6470 hideSoftKeyboard(); 6471 } else { 6472 displaySoftKeyboard(false); 6473 } 6474 break; 6475 6476 case FIND_AGAIN: 6477 // Ignore if find has been dismissed. 6478 if (mFindIsUp) { 6479 findAll(mLastFind); 6480 } 6481 break; 6482 6483 case DRAG_HELD_MOTIONLESS: 6484 mHeldMotionless = MOTIONLESS_TRUE; 6485 invalidate(); 6486 // fall through to keep scrollbars awake 6487 6488 case AWAKEN_SCROLL_BARS: 6489 if (mTouchMode == TOUCH_DRAG_MODE 6490 && mHeldMotionless == MOTIONLESS_TRUE) { 6491 awakenScrollBars(ViewConfiguration 6492 .getScrollDefaultDelay(), false); 6493 mPrivateHandler.sendMessageDelayed(mPrivateHandler 6494 .obtainMessage(AWAKEN_SCROLL_BARS), 6495 ViewConfiguration.getScrollDefaultDelay()); 6496 } 6497 break; 6498 6499 case DO_MOTION_UP: 6500 doMotionUp(msg.arg1, msg.arg2); 6501 break; 6502 6503 case SHOW_FULLSCREEN: { 6504 View view = (View) msg.obj; 6505 int npp = msg.arg1; 6506 6507 if (mFullScreenHolder != null) { 6508 Log.w(LOGTAG, "Should not have another full screen."); 6509 mFullScreenHolder.dismiss(); 6510 } 6511 mFullScreenHolder = new PluginFullScreenHolder(WebView.this, npp); 6512 mFullScreenHolder.setContentView(view); 6513 mFullScreenHolder.setCancelable(false); 6514 mFullScreenHolder.setCanceledOnTouchOutside(false); 6515 mFullScreenHolder.show(); 6516 6517 break; 6518 } 6519 case HIDE_FULLSCREEN: 6520 if (inFullScreenMode()) { 6521 mFullScreenHolder.dismiss(); 6522 mFullScreenHolder = null; 6523 } 6524 break; 6525 6526 case DOM_FOCUS_CHANGED: 6527 if (inEditingMode()) { 6528 nativeClearCursor(); 6529 rebuildWebTextView(); 6530 } 6531 break; 6532 6533 case SHOW_RECT_MSG_ID: { 6534 WebViewCore.ShowRectData data = (WebViewCore.ShowRectData) msg.obj; 6535 int x = mScrollX; 6536 int left = contentToViewX(data.mLeft); 6537 int width = contentToViewDimension(data.mWidth); 6538 int maxWidth = contentToViewDimension(data.mContentWidth); 6539 int viewWidth = getViewWidth(); 6540 if (width < viewWidth) { 6541 // center align 6542 x += left + width / 2 - mScrollX - viewWidth / 2; 6543 } else { 6544 x += (int) (left + data.mXPercentInDoc * width 6545 - mScrollX - data.mXPercentInView * viewWidth); 6546 } 6547 if (DebugFlags.WEB_VIEW) { 6548 Log.v(LOGTAG, "showRectMsg=(left=" + left + ",width=" + 6549 width + ",maxWidth=" + maxWidth + 6550 ",viewWidth=" + viewWidth + ",x=" 6551 + x + ",xPercentInDoc=" + data.mXPercentInDoc + 6552 ",xPercentInView=" + data.mXPercentInView+ ")"); 6553 } 6554 // use the passing content width to cap x as the current 6555 // mContentWidth may not be updated yet 6556 x = Math.max(0, 6557 (Math.min(maxWidth, x + viewWidth)) - viewWidth); 6558 int top = contentToViewY(data.mTop); 6559 int height = contentToViewDimension(data.mHeight); 6560 int maxHeight = contentToViewDimension(data.mContentHeight); 6561 int viewHeight = getViewHeight(); 6562 int y = (int) (top + data.mYPercentInDoc * height - 6563 data.mYPercentInView * viewHeight); 6564 if (DebugFlags.WEB_VIEW) { 6565 Log.v(LOGTAG, "showRectMsg=(top=" + top + ",height=" + 6566 height + ",maxHeight=" + maxHeight + 6567 ",viewHeight=" + viewHeight + ",y=" 6568 + y + ",yPercentInDoc=" + data.mYPercentInDoc + 6569 ",yPercentInView=" + data.mYPercentInView+ ")"); 6570 } 6571 // use the passing content height to cap y as the current 6572 // mContentHeight may not be updated yet 6573 y = Math.max(0, 6574 (Math.min(maxHeight, y + viewHeight) - viewHeight)); 6575 // We need to take into account the visible title height 6576 // when scrolling since y is an absolute view position. 6577 y = Math.max(0, y - getVisibleTitleHeight()); 6578 scrollTo(x, y); 6579 } 6580 break; 6581 6582 case CENTER_FIT_RECT: 6583 Rect r = (Rect)msg.obj; 6584 mZoomManager.mInZoomOverview = false; 6585 centerFitRect(r.left, r.top, r.width(), r.height()); 6586 break; 6587 6588 case SET_SCROLLBAR_MODES: 6589 mHorizontalScrollBarMode = msg.arg1; 6590 mVerticalScrollBarMode = msg.arg2; 6591 break; 6592 6593 case SELECTION_STRING_CHANGED: 6594 if (mAccessibilityInjector != null) { 6595 String selectionString = (String) msg.obj; 6596 mAccessibilityInjector.onSelectionStringChange(selectionString); 6597 } 6598 break; 6599 6600 case SET_TOUCH_HIGHLIGHT_RECTS: 6601 invalidate(mTouchHighlightRegion.getBounds()); 6602 mTouchHighlightRegion.setEmpty(); 6603 if (msg.obj != null) { 6604 ArrayList<Rect> rects = (ArrayList<Rect>) msg.obj; 6605 for (Rect rect : rects) { 6606 Rect viewRect = contentToViewRect(rect); 6607 // some sites, like stories in nytimes.com, set 6608 // mouse event handler in the top div. It is not 6609 // user friendly to highlight the div if it covers 6610 // more than half of the screen. 6611 if (viewRect.width() < getWidth() >> 1 6612 || viewRect.height() < getHeight() >> 1) { 6613 mTouchHighlightRegion.union(viewRect); 6614 invalidate(viewRect); 6615 } else { 6616 Log.w(LOGTAG, "Skip the huge selection rect:" 6617 + viewRect); 6618 } 6619 } 6620 } 6621 break; 6622 6623 default: 6624 super.handleMessage(msg); 6625 break; 6626 } 6627 } 6628 } 6629 6630 /** 6631 * Used when receiving messages for REQUEST_KEYBOARD_WITH_SELECTION_MSG_ID 6632 * and UPDATE_TEXT_SELECTION_MSG_ID. Update the selection of WebTextView. 6633 */ 6634 private void updateTextSelectionFromMessage(int nodePointer, 6635 int textGeneration, WebViewCore.TextSelectionData data) { 6636 if (inEditingMode() 6637 && mWebTextView.isSameTextField(nodePointer) 6638 && textGeneration == mTextGeneration) { 6639 mWebTextView.setSelectionFromWebKit(data.mStart, data.mEnd); 6640 } 6641 } 6642 6643 // Class used to use a dropdown for a <select> element 6644 private class InvokeListBox implements Runnable { 6645 // Whether the listbox allows multiple selection. 6646 private boolean mMultiple; 6647 // Passed in to a list with multiple selection to tell 6648 // which items are selected. 6649 private int[] mSelectedArray; 6650 // Passed in to a list with single selection to tell 6651 // where the initial selection is. 6652 private int mSelection; 6653 6654 private Container[] mContainers; 6655 6656 // Need these to provide stable ids to my ArrayAdapter, 6657 // which normally does not have stable ids. (Bug 1250098) 6658 private class Container extends Object { 6659 /** 6660 * Possible values for mEnabled. Keep in sync with OptionStatus in 6661 * WebViewCore.cpp 6662 */ 6663 final static int OPTGROUP = -1; 6664 final static int OPTION_DISABLED = 0; 6665 final static int OPTION_ENABLED = 1; 6666 6667 String mString; 6668 int mEnabled; 6669 int mId; 6670 6671 public String toString() { 6672 return mString; 6673 } 6674 } 6675 6676 /** 6677 * Subclass ArrayAdapter so we can disable OptionGroupLabels, 6678 * and allow filtering. 6679 */ 6680 private class MyArrayListAdapter extends ArrayAdapter<Container> { 6681 public MyArrayListAdapter(Context context, Container[] objects, boolean multiple) { 6682 super(context, 6683 multiple ? com.android.internal.R.layout.select_dialog_multichoice : 6684 com.android.internal.R.layout.select_dialog_singlechoice, 6685 objects); 6686 } 6687 6688 @Override 6689 public View getView(int position, View convertView, 6690 ViewGroup parent) { 6691 // Always pass in null so that we will get a new CheckedTextView 6692 // Otherwise, an item which was previously used as an <optgroup> 6693 // element (i.e. has no check), could get used as an <option> 6694 // element, which needs a checkbox/radio, but it would not have 6695 // one. 6696 convertView = super.getView(position, null, parent); 6697 Container c = item(position); 6698 if (c != null && Container.OPTION_ENABLED != c.mEnabled) { 6699 // ListView does not draw dividers between disabled and 6700 // enabled elements. Use a LinearLayout to provide dividers 6701 LinearLayout layout = new LinearLayout(mContext); 6702 layout.setOrientation(LinearLayout.VERTICAL); 6703 if (position > 0) { 6704 View dividerTop = new View(mContext); 6705 dividerTop.setBackgroundResource( 6706 android.R.drawable.divider_horizontal_bright); 6707 layout.addView(dividerTop); 6708 } 6709 6710 if (Container.OPTGROUP == c.mEnabled) { 6711 // Currently select_dialog_multichoice and 6712 // select_dialog_singlechoice are CheckedTextViews. If 6713 // that changes, the class cast will no longer be valid. 6714 Assert.assertTrue( 6715 convertView instanceof CheckedTextView); 6716 ((CheckedTextView) convertView).setCheckMarkDrawable( 6717 null); 6718 } else { 6719 // c.mEnabled == Container.OPTION_DISABLED 6720 // Draw the disabled element in a disabled state. 6721 convertView.setEnabled(false); 6722 } 6723 6724 layout.addView(convertView); 6725 if (position < getCount() - 1) { 6726 View dividerBottom = new View(mContext); 6727 dividerBottom.setBackgroundResource( 6728 android.R.drawable.divider_horizontal_bright); 6729 layout.addView(dividerBottom); 6730 } 6731 return layout; 6732 } 6733 return convertView; 6734 } 6735 6736 @Override 6737 public boolean hasStableIds() { 6738 // AdapterView's onChanged method uses this to determine whether 6739 // to restore the old state. Return false so that the old (out 6740 // of date) state does not replace the new, valid state. 6741 return false; 6742 } 6743 6744 private Container item(int position) { 6745 if (position < 0 || position >= getCount()) { 6746 return null; 6747 } 6748 return (Container) getItem(position); 6749 } 6750 6751 @Override 6752 public long getItemId(int position) { 6753 Container item = item(position); 6754 if (item == null) { 6755 return -1; 6756 } 6757 return item.mId; 6758 } 6759 6760 @Override 6761 public boolean areAllItemsEnabled() { 6762 return false; 6763 } 6764 6765 @Override 6766 public boolean isEnabled(int position) { 6767 Container item = item(position); 6768 if (item == null) { 6769 return false; 6770 } 6771 return Container.OPTION_ENABLED == item.mEnabled; 6772 } 6773 } 6774 6775 private InvokeListBox(String[] array, int[] enabled, int[] selected) { 6776 mMultiple = true; 6777 mSelectedArray = selected; 6778 6779 int length = array.length; 6780 mContainers = new Container[length]; 6781 for (int i = 0; i < length; i++) { 6782 mContainers[i] = new Container(); 6783 mContainers[i].mString = array[i]; 6784 mContainers[i].mEnabled = enabled[i]; 6785 mContainers[i].mId = i; 6786 } 6787 } 6788 6789 private InvokeListBox(String[] array, int[] enabled, int selection) { 6790 mSelection = selection; 6791 mMultiple = false; 6792 6793 int length = array.length; 6794 mContainers = new Container[length]; 6795 for (int i = 0; i < length; i++) { 6796 mContainers[i] = new Container(); 6797 mContainers[i].mString = array[i]; 6798 mContainers[i].mEnabled = enabled[i]; 6799 mContainers[i].mId = i; 6800 } 6801 } 6802 6803 /* 6804 * Whenever the data set changes due to filtering, this class ensures 6805 * that the checked item remains checked. 6806 */ 6807 private class SingleDataSetObserver extends DataSetObserver { 6808 private long mCheckedId; 6809 private ListView mListView; 6810 private Adapter mAdapter; 6811 6812 /* 6813 * Create a new observer. 6814 * @param id The ID of the item to keep checked. 6815 * @param l ListView for getting and clearing the checked states 6816 * @param a Adapter for getting the IDs 6817 */ 6818 public SingleDataSetObserver(long id, ListView l, Adapter a) { 6819 mCheckedId = id; 6820 mListView = l; 6821 mAdapter = a; 6822 } 6823 6824 public void onChanged() { 6825 // The filter may have changed which item is checked. Find the 6826 // item that the ListView thinks is checked. 6827 int position = mListView.getCheckedItemPosition(); 6828 long id = mAdapter.getItemId(position); 6829 if (mCheckedId != id) { 6830 // Clear the ListView's idea of the checked item, since 6831 // it is incorrect 6832 mListView.clearChoices(); 6833 // Search for mCheckedId. If it is in the filtered list, 6834 // mark it as checked 6835 int count = mAdapter.getCount(); 6836 for (int i = 0; i < count; i++) { 6837 if (mAdapter.getItemId(i) == mCheckedId) { 6838 mListView.setItemChecked(i, true); 6839 break; 6840 } 6841 } 6842 } 6843 } 6844 6845 public void onInvalidate() {} 6846 } 6847 6848 public void run() { 6849 final ListView listView = (ListView) LayoutInflater.from(mContext) 6850 .inflate(com.android.internal.R.layout.select_dialog, null); 6851 final MyArrayListAdapter adapter = new 6852 MyArrayListAdapter(mContext, mContainers, mMultiple); 6853 AlertDialog.Builder b = new AlertDialog.Builder(mContext) 6854 .setView(listView).setCancelable(true) 6855 .setInverseBackgroundForced(true); 6856 6857 if (mMultiple) { 6858 b.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { 6859 public void onClick(DialogInterface dialog, int which) { 6860 mWebViewCore.sendMessage( 6861 EventHub.LISTBOX_CHOICES, 6862 adapter.getCount(), 0, 6863 listView.getCheckedItemPositions()); 6864 }}); 6865 b.setNegativeButton(android.R.string.cancel, 6866 new DialogInterface.OnClickListener() { 6867 public void onClick(DialogInterface dialog, int which) { 6868 mWebViewCore.sendMessage( 6869 EventHub.SINGLE_LISTBOX_CHOICE, -2, 0); 6870 }}); 6871 } 6872 final AlertDialog dialog = b.create(); 6873 listView.setAdapter(adapter); 6874 listView.setFocusableInTouchMode(true); 6875 // There is a bug (1250103) where the checks in a ListView with 6876 // multiple items selected are associated with the positions, not 6877 // the ids, so the items do not properly retain their checks when 6878 // filtered. Do not allow filtering on multiple lists until 6879 // that bug is fixed. 6880 6881 listView.setTextFilterEnabled(!mMultiple); 6882 if (mMultiple) { 6883 listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE); 6884 int length = mSelectedArray.length; 6885 for (int i = 0; i < length; i++) { 6886 listView.setItemChecked(mSelectedArray[i], true); 6887 } 6888 } else { 6889 listView.setOnItemClickListener(new OnItemClickListener() { 6890 public void onItemClick(AdapterView parent, View v, 6891 int position, long id) { 6892 mWebViewCore.sendMessage( 6893 EventHub.SINGLE_LISTBOX_CHOICE, (int)id, 0); 6894 dialog.dismiss(); 6895 } 6896 }); 6897 if (mSelection != -1) { 6898 listView.setSelection(mSelection); 6899 listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE); 6900 listView.setItemChecked(mSelection, true); 6901 DataSetObserver observer = new SingleDataSetObserver( 6902 adapter.getItemId(mSelection), listView, adapter); 6903 adapter.registerDataSetObserver(observer); 6904 } 6905 } 6906 dialog.setOnCancelListener(new DialogInterface.OnCancelListener() { 6907 public void onCancel(DialogInterface dialog) { 6908 mWebViewCore.sendMessage( 6909 EventHub.SINGLE_LISTBOX_CHOICE, -2, 0); 6910 } 6911 }); 6912 dialog.show(); 6913 } 6914 } 6915 6916 /* 6917 * Request a dropdown menu for a listbox with multiple selection. 6918 * 6919 * @param array Labels for the listbox. 6920 * @param enabledArray State for each element in the list. See static 6921 * integers in Container class. 6922 * @param selectedArray Which positions are initally selected. 6923 */ 6924 void requestListBox(String[] array, int[] enabledArray, int[] 6925 selectedArray) { 6926 mPrivateHandler.post( 6927 new InvokeListBox(array, enabledArray, selectedArray)); 6928 } 6929 6930 private void updateZoomRange(WebViewCore.RestoreState restoreState, 6931 int viewWidth, int minPrefWidth, boolean updateZoomOverview) { 6932 if (restoreState.mMinScale == 0) { 6933 if (restoreState.mMobileSite) { 6934 if (minPrefWidth > Math.max(0, viewWidth)) { 6935 mZoomManager.mMinZoomScale = (float) viewWidth / minPrefWidth; 6936 mZoomManager.mMinZoomScaleFixed = false; 6937 if (updateZoomOverview) { 6938 WebSettings settings = getSettings(); 6939 mZoomManager.mInZoomOverview = settings.getUseWideViewPort() && 6940 settings.getLoadWithOverviewMode(); 6941 } 6942 } else { 6943 mZoomManager.mMinZoomScale = restoreState.mDefaultScale; 6944 mZoomManager.mMinZoomScaleFixed = true; 6945 } 6946 } else { 6947 mZoomManager.mMinZoomScale = mZoomManager.DEFAULT_MIN_ZOOM_SCALE; 6948 mZoomManager.mMinZoomScaleFixed = false; 6949 } 6950 } else { 6951 mZoomManager.mMinZoomScale = restoreState.mMinScale; 6952 mZoomManager.mMinZoomScaleFixed = true; 6953 } 6954 if (restoreState.mMaxScale == 0) { 6955 mZoomManager.mMaxZoomScale = mZoomManager.DEFAULT_MAX_ZOOM_SCALE; 6956 } else { 6957 mZoomManager.mMaxZoomScale = restoreState.mMaxScale; 6958 } 6959 } 6960 6961 /* 6962 * Request a dropdown menu for a listbox with single selection or a single 6963 * <select> element. 6964 * 6965 * @param array Labels for the listbox. 6966 * @param enabledArray State for each element in the list. See static 6967 * integers in Container class. 6968 * @param selection Which position is initally selected. 6969 */ 6970 void requestListBox(String[] array, int[] enabledArray, int selection) { 6971 mPrivateHandler.post( 6972 new InvokeListBox(array, enabledArray, selection)); 6973 } 6974 6975 // called by JNI 6976 private void sendMoveFocus(int frame, int node) { 6977 mWebViewCore.sendMessage(EventHub.SET_MOVE_FOCUS, 6978 new WebViewCore.CursorData(frame, node, 0, 0)); 6979 } 6980 6981 // called by JNI 6982 private void sendMoveMouse(int frame, int node, int x, int y) { 6983 mWebViewCore.sendMessage(EventHub.SET_MOVE_MOUSE, 6984 new WebViewCore.CursorData(frame, node, x, y)); 6985 } 6986 6987 /* 6988 * Send a mouse move event to the webcore thread. 6989 * 6990 * @param removeFocus Pass true if the "mouse" cursor is now over a node 6991 * which wants key events, but it is not the focus. This 6992 * will make the visual appear as though nothing is in 6993 * focus. Remove the WebTextView, if present, and stop 6994 * drawing the blinking caret. 6995 * called by JNI 6996 */ 6997 private void sendMoveMouseIfLatest(boolean removeFocus) { 6998 if (removeFocus) { 6999 clearTextEntry(true); 7000 } 7001 mWebViewCore.sendMessage(EventHub.SET_MOVE_MOUSE_IF_LATEST, 7002 cursorData()); 7003 } 7004 7005 // called by JNI 7006 private void sendMotionUp(int touchGeneration, 7007 int frame, int node, int x, int y) { 7008 WebViewCore.TouchUpData touchUpData = new WebViewCore.TouchUpData(); 7009 touchUpData.mMoveGeneration = touchGeneration; 7010 touchUpData.mFrame = frame; 7011 touchUpData.mNode = node; 7012 touchUpData.mX = x; 7013 touchUpData.mY = y; 7014 mWebViewCore.sendMessage(EventHub.TOUCH_UP, touchUpData); 7015 } 7016 7017 7018 private int getScaledMaxXScroll() { 7019 int width; 7020 if (mHeightCanMeasure == false) { 7021 width = getViewWidth() / 4; 7022 } else { 7023 Rect visRect = new Rect(); 7024 calcOurVisibleRect(visRect); 7025 width = visRect.width() / 2; 7026 } 7027 // FIXME the divisor should be retrieved from somewhere 7028 return viewToContentX(width); 7029 } 7030 7031 private int getScaledMaxYScroll() { 7032 int height; 7033 if (mHeightCanMeasure == false) { 7034 height = getViewHeight() / 4; 7035 } else { 7036 Rect visRect = new Rect(); 7037 calcOurVisibleRect(visRect); 7038 height = visRect.height() / 2; 7039 } 7040 // FIXME the divisor should be retrieved from somewhere 7041 // the closest thing today is hard-coded into ScrollView.java 7042 // (from ScrollView.java, line 363) int maxJump = height/2; 7043 return Math.round(height * mZoomManager.mInvActualScale); 7044 } 7045 7046 /** 7047 * Called by JNI to invalidate view 7048 */ 7049 private void viewInvalidate() { 7050 invalidate(); 7051 } 7052 7053 /** 7054 * Pass the key directly to the page. This assumes that 7055 * nativePageShouldHandleShiftAndArrows() returned true. 7056 */ 7057 private void letPageHandleNavKey(int keyCode, long time, boolean down) { 7058 int keyEventAction; 7059 int eventHubAction; 7060 if (down) { 7061 keyEventAction = KeyEvent.ACTION_DOWN; 7062 eventHubAction = EventHub.KEY_DOWN; 7063 playSoundEffect(keyCodeToSoundsEffect(keyCode)); 7064 } else { 7065 keyEventAction = KeyEvent.ACTION_UP; 7066 eventHubAction = EventHub.KEY_UP; 7067 } 7068 KeyEvent event = new KeyEvent(time, time, keyEventAction, keyCode, 7069 1, (mShiftIsPressed ? KeyEvent.META_SHIFT_ON : 0) 7070 | (false ? KeyEvent.META_ALT_ON : 0) // FIXME 7071 | (false ? KeyEvent.META_SYM_ON : 0) // FIXME 7072 , 0, 0, 0); 7073 mWebViewCore.sendMessage(eventHubAction, event); 7074 } 7075 7076 // return true if the key was handled 7077 private boolean navHandledKey(int keyCode, int count, boolean noScroll, 7078 long time) { 7079 if (mNativeClass == 0) { 7080 return false; 7081 } 7082 mLastCursorTime = time; 7083 mLastCursorBounds = nativeGetCursorRingBounds(); 7084 boolean keyHandled 7085 = nativeMoveCursor(keyCode, count, noScroll) == false; 7086 if (DebugFlags.WEB_VIEW) { 7087 Log.v(LOGTAG, "navHandledKey mLastCursorBounds=" + mLastCursorBounds 7088 + " mLastCursorTime=" + mLastCursorTime 7089 + " handled=" + keyHandled); 7090 } 7091 if (keyHandled == false || mHeightCanMeasure == false) { 7092 return keyHandled; 7093 } 7094 Rect contentCursorRingBounds = nativeGetCursorRingBounds(); 7095 if (contentCursorRingBounds.isEmpty()) return keyHandled; 7096 Rect viewCursorRingBounds = contentToViewRect(contentCursorRingBounds); 7097 Rect visRect = new Rect(); 7098 calcOurVisibleRect(visRect); 7099 Rect outset = new Rect(visRect); 7100 int maxXScroll = visRect.width() / 2; 7101 int maxYScroll = visRect.height() / 2; 7102 outset.inset(-maxXScroll, -maxYScroll); 7103 if (Rect.intersects(outset, viewCursorRingBounds) == false) { 7104 return keyHandled; 7105 } 7106 // FIXME: Necessary because ScrollView/ListView do not scroll left/right 7107 int maxH = Math.min(viewCursorRingBounds.right - visRect.right, 7108 maxXScroll); 7109 if (maxH > 0) { 7110 pinScrollBy(maxH, 0, true, 0); 7111 } else { 7112 maxH = Math.max(viewCursorRingBounds.left - visRect.left, 7113 -maxXScroll); 7114 if (maxH < 0) { 7115 pinScrollBy(maxH, 0, true, 0); 7116 } 7117 } 7118 if (mLastCursorBounds.isEmpty()) return keyHandled; 7119 if (mLastCursorBounds.equals(contentCursorRingBounds)) { 7120 return keyHandled; 7121 } 7122 if (DebugFlags.WEB_VIEW) { 7123 Log.v(LOGTAG, "navHandledKey contentCursorRingBounds=" 7124 + contentCursorRingBounds); 7125 } 7126 requestRectangleOnScreen(viewCursorRingBounds); 7127 mUserScroll = true; 7128 return keyHandled; 7129 } 7130 7131 /** 7132 * Set the background color. It's white by default. Pass 7133 * zero to make the view transparent. 7134 * @param color the ARGB color described by Color.java 7135 */ 7136 public void setBackgroundColor(int color) { 7137 mBackgroundColor = color; 7138 mWebViewCore.sendMessage(EventHub.SET_BACKGROUND_COLOR, color); 7139 } 7140 7141 public void debugDump() { 7142 nativeDebugDump(); 7143 mWebViewCore.sendMessage(EventHub.DUMP_NAVTREE); 7144 } 7145 7146 /** 7147 * Draw the HTML page into the specified canvas. This call ignores any 7148 * view-specific zoom, scroll offset, or other changes. It does not draw 7149 * any view-specific chrome, such as progress or URL bars. 7150 * 7151 * @hide only needs to be accessible to Browser and testing 7152 */ 7153 public void drawPage(Canvas canvas) { 7154 mWebViewCore.drawContentPicture(canvas, 0, false, false); 7155 } 7156 7157 /** 7158 * Set the time to wait between passing touches to WebCore. See also the 7159 * TOUCH_SENT_INTERVAL member for further discussion. 7160 * 7161 * @hide This is only used by the DRT test application. 7162 */ 7163 public void setTouchInterval(int interval) { 7164 mCurrentTouchInterval = interval; 7165 } 7166 7167 /** 7168 * Update our cache with updatedText. 7169 * @param updatedText The new text to put in our cache. 7170 */ 7171 /* package */ void updateCachedTextfield(String updatedText) { 7172 // Also place our generation number so that when we look at the cache 7173 // we recognize that it is up to date. 7174 nativeUpdateCachedTextfield(updatedText, mTextGeneration); 7175 } 7176 7177 private native int nativeCacheHitFramePointer(); 7178 private native Rect nativeCacheHitNodeBounds(); 7179 private native int nativeCacheHitNodePointer(); 7180 /* package */ native void nativeClearCursor(); 7181 private native void nativeCreate(int ptr); 7182 private native int nativeCursorFramePointer(); 7183 private native Rect nativeCursorNodeBounds(); 7184 private native int nativeCursorNodePointer(); 7185 /* package */ native boolean nativeCursorMatchesFocus(); 7186 private native boolean nativeCursorIntersects(Rect visibleRect); 7187 private native boolean nativeCursorIsAnchor(); 7188 private native boolean nativeCursorIsTextInput(); 7189 private native Point nativeCursorPosition(); 7190 private native String nativeCursorText(); 7191 /** 7192 * Returns true if the native cursor node says it wants to handle key events 7193 * (ala plugins). This can only be called if mNativeClass is non-zero! 7194 */ 7195 private native boolean nativeCursorWantsKeyEvents(); 7196 private native void nativeDebugDump(); 7197 private native void nativeDestroy(); 7198 private native boolean nativeEvaluateLayersAnimations(); 7199 private native void nativeDrawExtras(Canvas canvas, int extra); 7200 private native void nativeDumpDisplayTree(String urlOrNull); 7201 private native int nativeFindAll(String findLower, String findUpper); 7202 private native void nativeFindNext(boolean forward); 7203 /* package */ native int nativeFocusCandidateFramePointer(); 7204 /* package */ native boolean nativeFocusCandidateHasNextTextfield(); 7205 /* package */ native boolean nativeFocusCandidateIsPassword(); 7206 private native boolean nativeFocusCandidateIsRtlText(); 7207 private native boolean nativeFocusCandidateIsTextInput(); 7208 /* package */ native int nativeFocusCandidateMaxLength(); 7209 /* package */ native String nativeFocusCandidateName(); 7210 private native Rect nativeFocusCandidateNodeBounds(); 7211 /* package */ native int nativeFocusCandidatePointer(); 7212 private native String nativeFocusCandidateText(); 7213 private native int nativeFocusCandidateTextSize(); 7214 /** 7215 * Returns an integer corresponding to WebView.cpp::type. 7216 * See WebTextView.setType() 7217 */ 7218 private native int nativeFocusCandidateType(); 7219 private native boolean nativeFocusIsPlugin(); 7220 private native Rect nativeFocusNodeBounds(); 7221 /* package */ native int nativeFocusNodePointer(); 7222 private native Rect nativeGetCursorRingBounds(); 7223 private native String nativeGetSelection(); 7224 private native boolean nativeHasCursorNode(); 7225 private native boolean nativeHasFocusNode(); 7226 private native void nativeHideCursor(); 7227 private native String nativeImageURI(int x, int y); 7228 private native void nativeInstrumentReport(); 7229 /* package */ native boolean nativeMoveCursorToNextTextInput(); 7230 // return true if the page has been scrolled 7231 private native boolean nativeMotionUp(int x, int y, int slop); 7232 // returns false if it handled the key 7233 private native boolean nativeMoveCursor(int keyCode, int count, 7234 boolean noScroll); 7235 private native int nativeMoveGeneration(); 7236 private native void nativeMoveSelection(int x, int y, 7237 boolean extendSelection); 7238 /** 7239 * @return true if the page should get the shift and arrow keys, rather 7240 * than select text/navigation. 7241 * 7242 * If the focus is a plugin, or if the focus and cursor match and are 7243 * a contentEditable element, then the page should handle these keys. 7244 */ 7245 private native boolean nativePageShouldHandleShiftAndArrows(); 7246 private native boolean nativePointInNavCache(int x, int y, int slop); 7247 // Like many other of our native methods, you must make sure that 7248 // mNativeClass is not null before calling this method. 7249 private native void nativeRecordButtons(boolean focused, 7250 boolean pressed, boolean invalidate); 7251 private native void nativeSelectBestAt(Rect rect); 7252 private native int nativeFindIndex(); 7253 private native void nativeSetFindIsEmpty(); 7254 private native void nativeSetFindIsUp(boolean isUp); 7255 private native void nativeSetFollowedLink(boolean followed); 7256 private native void nativeSetHeightCanMeasure(boolean measure); 7257 private native void nativeSetRootLayer(int layer); 7258 private native void nativeSetSelectionPointer(boolean set, 7259 float scale, int x, int y, boolean extendSelection); 7260 private native void nativeSetSelectionRegion(boolean set); 7261 private native Rect nativeSubtractLayers(Rect content); 7262 private native int nativeTextGeneration(); 7263 // Never call this version except by updateCachedTextfield(String) - 7264 // we always want to pass in our generation number. 7265 private native void nativeUpdateCachedTextfield(String updatedText, 7266 int generation); 7267 // return NO_LEFTEDGE means failure. 7268 private static final int NO_LEFTEDGE = -1; 7269 private native int nativeGetBlockLeftEdge(int x, int y, float scale); 7270} 7271