WebView.java revision 178db41234abd08925fea9a4dc5180218f7da737
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 private 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 float zoomScale; 3287 int interval = (int) (SystemClock.uptimeMillis() - mZoomManager.mZoomStart); 3288 if (interval < mZoomManager.ZOOM_ANIMATION_LENGTH) { 3289 float ratio = (float) interval / mZoomManager.ZOOM_ANIMATION_LENGTH; 3290 zoomScale = 1.0f / (mZoomManager.mInvInitialZoomScale 3291 + (mZoomManager.mInvFinalZoomScale - mZoomManager.mInvInitialZoomScale) * ratio); 3292 invalidate(); 3293 } else { 3294 zoomScale = mZoomManager.mZoomScale; 3295 // set mZoomScale to be 0 as we have done animation 3296 mZoomManager.mZoomScale = 0; 3297 WebViewCore.resumeUpdatePicture(mWebViewCore); 3298 // call invalidate() again to draw with the final filters 3299 invalidate(); 3300 if (mNeedToAdjustWebTextView) { 3301 mNeedToAdjustWebTextView = false; 3302 if (didUpdateTextViewBounds(false) 3303 && nativeFocusCandidateIsPassword()) { 3304 // If it is a password field, start drawing the 3305 // WebTextView once again. 3306 mWebTextView.setInPassword(true); 3307 } 3308 } 3309 } 3310 // calculate the intermediate scroll position. As we need to use 3311 // zoomScale, we can't use pinLocX/Y directly. Copy the logic here. 3312 float scale = zoomScale * mZoomManager.mInvInitialZoomScale; 3313 int tx = Math.round(scale * (mZoomManager.mInitialScrollX + mZoomManager.mZoomCenterX) 3314 - mZoomManager.mZoomCenterX); 3315 tx = -pinLoc(tx, getViewWidth(), Math.round(mContentWidth 3316 * zoomScale)) + mScrollX; 3317 int titleHeight = getTitleHeight(); 3318 int ty = Math.round(scale 3319 * (mZoomManager.mInitialScrollY + mZoomManager.mZoomCenterY - titleHeight) 3320 - (mZoomManager.mZoomCenterY - titleHeight)); 3321 ty = -(ty <= titleHeight ? Math.max(ty, 0) : pinLoc(ty 3322 - titleHeight, getViewHeight(), Math.round(mContentHeight 3323 * zoomScale)) + titleHeight) + mScrollY; 3324 canvas.translate(tx, ty); 3325 canvas.scale(zoomScale, zoomScale); 3326 if (inEditingMode() && !mNeedToAdjustWebTextView 3327 && mZoomManager.isZoomAnimating()) { 3328 // The WebTextView is up. Keep track of this so we can adjust 3329 // its size and placement when we finish zooming 3330 mNeedToAdjustWebTextView = true; 3331 // If it is in password mode, turn it off so it does not draw 3332 // misplaced. 3333 if (nativeFocusCandidateIsPassword()) { 3334 mWebTextView.setInPassword(false); 3335 } 3336 } 3337 } else { 3338 canvas.scale(mZoomManager.mActualScale, mZoomManager.mActualScale); 3339 } 3340 3341 boolean UIAnimationsRunning = false; 3342 // Currently for each draw we compute the animation values; 3343 // We may in the future decide to do that independently. 3344 if (mNativeClass != 0 && nativeEvaluateLayersAnimations()) { 3345 UIAnimationsRunning = true; 3346 // If we have unfinished (or unstarted) animations, 3347 // we ask for a repaint. 3348 invalidate(); 3349 } 3350 mWebViewCore.drawContentPicture(canvas, color, 3351 (animateZoom || mZoomManager.mPreviewZoomOnly || UIAnimationsRunning), 3352 animateScroll); 3353 if (mNativeClass == 0) return; 3354 // decide which adornments to draw 3355 int extras = DRAW_EXTRAS_NONE; 3356 if (mFindIsUp) { 3357 // When the FindDialog is up, only draw the matches if we are not in 3358 // the process of scrolling them into view. 3359 if (!animateScroll) { 3360 extras = DRAW_EXTRAS_FIND; 3361 } 3362 } else if (mShiftIsPressed 3363 && !nativePageShouldHandleShiftAndArrows()) { 3364 if (!animateZoom && !mZoomManager.mPreviewZoomOnly) { 3365 extras = DRAW_EXTRAS_SELECTION; 3366 nativeSetSelectionRegion(mTouchSelection || mExtendSelection); 3367 nativeSetSelectionPointer(!mTouchSelection, mZoomManager.mInvActualScale, 3368 mSelectX, mSelectY - getTitleHeight(), 3369 mExtendSelection); 3370 } 3371 } else if (drawCursorRing) { 3372 extras = DRAW_EXTRAS_CURSOR_RING; 3373 } 3374 drawExtras(canvas, extras, UIAnimationsRunning); 3375 3376 if (extras == DRAW_EXTRAS_CURSOR_RING) { 3377 if (mTouchMode == TOUCH_SHORTPRESS_START_MODE) { 3378 mTouchMode = TOUCH_SHORTPRESS_MODE; 3379 HitTestResult hitTest = getHitTestResult(); 3380 if (hitTest == null 3381 || hitTest.mType == HitTestResult.UNKNOWN_TYPE) { 3382 mPrivateHandler.removeMessages(SWITCH_TO_LONGPRESS); 3383 } 3384 } 3385 } 3386 if (mFocusSizeChanged) { 3387 mFocusSizeChanged = false; 3388 // If we are zooming, this will get handled above, when the zoom 3389 // finishes. We also do not need to do this unless the WebTextView 3390 // is showing. 3391 if (!animateZoom && inEditingMode()) { 3392 didUpdateTextViewBounds(true); 3393 } 3394 } 3395 } 3396 3397 // draw history 3398 private boolean mDrawHistory = false; 3399 private Picture mHistoryPicture = null; 3400 private int mHistoryWidth = 0; 3401 private int mHistoryHeight = 0; 3402 3403 // Only check the flag, can be called from WebCore thread 3404 boolean drawHistory() { 3405 return mDrawHistory; 3406 } 3407 3408 // Should only be called in UI thread 3409 void switchOutDrawHistory() { 3410 if (null == mWebViewCore) return; // CallbackProxy may trigger this 3411 if (mDrawHistory && mWebViewCore.pictureReady()) { 3412 mDrawHistory = false; 3413 mHistoryPicture = null; 3414 invalidate(); 3415 int oldScrollX = mScrollX; 3416 int oldScrollY = mScrollY; 3417 mScrollX = pinLocX(mScrollX); 3418 mScrollY = pinLocY(mScrollY); 3419 if (oldScrollX != mScrollX || oldScrollY != mScrollY) { 3420 mUserScroll = false; 3421 mWebViewCore.sendMessage(EventHub.SYNC_SCROLL, oldScrollX, 3422 oldScrollY); 3423 onScrollChanged(mScrollX, mScrollY, oldScrollX, oldScrollY); 3424 } else { 3425 sendOurVisibleRect(); 3426 } 3427 } 3428 } 3429 3430 WebViewCore.CursorData cursorData() { 3431 WebViewCore.CursorData result = new WebViewCore.CursorData(); 3432 result.mMoveGeneration = nativeMoveGeneration(); 3433 result.mFrame = nativeCursorFramePointer(); 3434 Point position = nativeCursorPosition(); 3435 result.mX = position.x; 3436 result.mY = position.y; 3437 return result; 3438 } 3439 3440 /** 3441 * Delete text from start to end in the focused textfield. If there is no 3442 * focus, or if start == end, silently fail. If start and end are out of 3443 * order, swap them. 3444 * @param start Beginning of selection to delete. 3445 * @param end End of selection to delete. 3446 */ 3447 /* package */ void deleteSelection(int start, int end) { 3448 mTextGeneration++; 3449 WebViewCore.TextSelectionData data 3450 = new WebViewCore.TextSelectionData(start, end); 3451 mWebViewCore.sendMessage(EventHub.DELETE_SELECTION, mTextGeneration, 0, 3452 data); 3453 } 3454 3455 /** 3456 * Set the selection to (start, end) in the focused textfield. If start and 3457 * end are out of order, swap them. 3458 * @param start Beginning of selection. 3459 * @param end End of selection. 3460 */ 3461 /* package */ void setSelection(int start, int end) { 3462 mWebViewCore.sendMessage(EventHub.SET_SELECTION, start, end); 3463 } 3464 3465 @Override 3466 public InputConnection onCreateInputConnection(EditorInfo outAttrs) { 3467 InputConnection connection = super.onCreateInputConnection(outAttrs); 3468 outAttrs.imeOptions |= EditorInfo.IME_FLAG_NO_FULLSCREEN; 3469 return connection; 3470 } 3471 3472 /** 3473 * Called in response to a message from webkit telling us that the soft 3474 * keyboard should be launched. 3475 */ 3476 private void displaySoftKeyboard(boolean isTextView) { 3477 InputMethodManager imm = (InputMethodManager) 3478 getContext().getSystemService(Context.INPUT_METHOD_SERVICE); 3479 3480 // bring it back to the default scale so that user can enter text 3481 boolean zoom = mZoomManager.mActualScale < mZoomManager.mDefaultScale; 3482 if (zoom) { 3483 mZoomManager.setZoomCenter(mLastTouchX, mLastTouchY); 3484 mZoomManager.mInZoomOverview = false; 3485 mZoomManager.setZoomScale(mZoomManager.mDefaultScale, false); 3486 } 3487 if (isTextView) { 3488 rebuildWebTextView(); 3489 if (inEditingMode()) { 3490 imm.showSoftInput(mWebTextView, 0); 3491 if (zoom) { 3492 didUpdateTextViewBounds(true); 3493 } 3494 return; 3495 } 3496 } 3497 // Used by plugins. 3498 // Also used if the navigation cache is out of date, and 3499 // does not recognize that a textfield is in focus. In that 3500 // case, use WebView as the targeted view. 3501 // see http://b/issue?id=2457459 3502 imm.showSoftInput(this, 0); 3503 } 3504 3505 // Called by WebKit to instruct the UI to hide the keyboard 3506 private void hideSoftKeyboard() { 3507 InputMethodManager imm = (InputMethodManager) 3508 getContext().getSystemService(Context.INPUT_METHOD_SERVICE); 3509 3510 imm.hideSoftInputFromWindow(this.getWindowToken(), 0); 3511 } 3512 3513 /* 3514 * This method checks the current focus and cursor and potentially rebuilds 3515 * mWebTextView to have the appropriate properties, such as password, 3516 * multiline, and what text it contains. It also removes it if necessary. 3517 */ 3518 /* package */ void rebuildWebTextView() { 3519 // If the WebView does not have focus, do nothing until it gains focus. 3520 if (!hasFocus() && (null == mWebTextView || !mWebTextView.hasFocus())) { 3521 return; 3522 } 3523 boolean alreadyThere = inEditingMode(); 3524 // inEditingMode can only return true if mWebTextView is non-null, 3525 // so we can safely call remove() if (alreadyThere) 3526 if (0 == mNativeClass || !nativeFocusCandidateIsTextInput()) { 3527 if (alreadyThere) { 3528 mWebTextView.remove(); 3529 } 3530 return; 3531 } 3532 // At this point, we know we have found an input field, so go ahead 3533 // and create the WebTextView if necessary. 3534 if (mWebTextView == null) { 3535 mWebTextView = new WebTextView(mContext, WebView.this); 3536 // Initialize our generation number. 3537 mTextGeneration = 0; 3538 } 3539 mWebTextView.setTextSize(TypedValue.COMPLEX_UNIT_PX, 3540 contentToViewDimension(nativeFocusCandidateTextSize())); 3541 Rect visibleRect = new Rect(); 3542 calcOurContentVisibleRect(visibleRect); 3543 // Note that sendOurVisibleRect calls viewToContent, so the coordinates 3544 // should be in content coordinates. 3545 Rect bounds = nativeFocusCandidateNodeBounds(); 3546 Rect vBox = contentToViewRect(bounds); 3547 mWebTextView.setRect(vBox.left, vBox.top, vBox.width(), vBox.height()); 3548 if (!Rect.intersects(bounds, visibleRect)) { 3549 mWebTextView.bringIntoView(); 3550 } 3551 String text = nativeFocusCandidateText(); 3552 int nodePointer = nativeFocusCandidatePointer(); 3553 if (alreadyThere && mWebTextView.isSameTextField(nodePointer)) { 3554 // It is possible that we have the same textfield, but it has moved, 3555 // i.e. In the case of opening/closing the screen. 3556 // In that case, we need to set the dimensions, but not the other 3557 // aspects. 3558 // If the text has been changed by webkit, update it. However, if 3559 // there has been more UI text input, ignore it. We will receive 3560 // another update when that text is recognized. 3561 if (text != null && !text.equals(mWebTextView.getText().toString()) 3562 && nativeTextGeneration() == mTextGeneration) { 3563 mWebTextView.setTextAndKeepSelection(text); 3564 } 3565 } else { 3566 mWebTextView.setGravity(nativeFocusCandidateIsRtlText() ? 3567 Gravity.RIGHT : Gravity.NO_GRAVITY); 3568 // This needs to be called before setType, which may call 3569 // requestFormData, and it needs to have the correct nodePointer. 3570 mWebTextView.setNodePointer(nodePointer); 3571 mWebTextView.setType(nativeFocusCandidateType()); 3572 if (null == text) { 3573 if (DebugFlags.WEB_VIEW) { 3574 Log.v(LOGTAG, "rebuildWebTextView null == text"); 3575 } 3576 text = ""; 3577 } 3578 mWebTextView.setTextAndKeepSelection(text); 3579 InputMethodManager imm = InputMethodManager.peekInstance(); 3580 if (imm != null && imm.isActive(mWebTextView)) { 3581 imm.restartInput(mWebTextView); 3582 } 3583 } 3584 mWebTextView.requestFocus(); 3585 } 3586 3587 /** 3588 * Called by WebTextView to find saved form data associated with the 3589 * textfield 3590 * @param name Name of the textfield. 3591 * @param nodePointer Pointer to the node of the textfield, so it can be 3592 * compared to the currently focused textfield when the data is 3593 * retrieved. 3594 */ 3595 /* package */ void requestFormData(String name, int nodePointer) { 3596 if (mWebViewCore.getSettings().getSaveFormData()) { 3597 Message update = mPrivateHandler.obtainMessage(REQUEST_FORM_DATA); 3598 update.arg1 = nodePointer; 3599 RequestFormData updater = new RequestFormData(name, getUrl(), 3600 update); 3601 Thread t = new Thread(updater); 3602 t.start(); 3603 } 3604 } 3605 3606 /** 3607 * Pass a message to find out the <label> associated with the <input> 3608 * identified by nodePointer 3609 * @param framePointer Pointer to the frame containing the <input> node 3610 * @param nodePointer Pointer to the node for which a <label> is desired. 3611 */ 3612 /* package */ void requestLabel(int framePointer, int nodePointer) { 3613 mWebViewCore.sendMessage(EventHub.REQUEST_LABEL, framePointer, 3614 nodePointer); 3615 } 3616 3617 /* 3618 * This class requests an Adapter for the WebTextView which shows past 3619 * entries stored in the database. It is a Runnable so that it can be done 3620 * in its own thread, without slowing down the UI. 3621 */ 3622 private class RequestFormData implements Runnable { 3623 private String mName; 3624 private String mUrl; 3625 private Message mUpdateMessage; 3626 3627 public RequestFormData(String name, String url, Message msg) { 3628 mName = name; 3629 mUrl = url; 3630 mUpdateMessage = msg; 3631 } 3632 3633 public void run() { 3634 ArrayList<String> pastEntries = mDatabase.getFormData(mUrl, mName); 3635 if (pastEntries.size() > 0) { 3636 AutoCompleteAdapter adapter = new 3637 AutoCompleteAdapter(mContext, pastEntries); 3638 mUpdateMessage.obj = adapter; 3639 mUpdateMessage.sendToTarget(); 3640 } 3641 } 3642 } 3643 3644 /** 3645 * Dump the display tree to "/sdcard/displayTree.txt" 3646 * 3647 * @hide debug only 3648 */ 3649 public void dumpDisplayTree() { 3650 nativeDumpDisplayTree(getUrl()); 3651 } 3652 3653 /** 3654 * Dump the dom tree to adb shell if "toFile" is False, otherwise dump it to 3655 * "/sdcard/domTree.txt" 3656 * 3657 * @hide debug only 3658 */ 3659 public void dumpDomTree(boolean toFile) { 3660 mWebViewCore.sendMessage(EventHub.DUMP_DOMTREE, toFile ? 1 : 0, 0); 3661 } 3662 3663 /** 3664 * Dump the render tree to adb shell if "toFile" is False, otherwise dump it 3665 * to "/sdcard/renderTree.txt" 3666 * 3667 * @hide debug only 3668 */ 3669 public void dumpRenderTree(boolean toFile) { 3670 mWebViewCore.sendMessage(EventHub.DUMP_RENDERTREE, toFile ? 1 : 0, 0); 3671 } 3672 3673 /** 3674 * Dump the V8 counters to standard output. 3675 * Note that you need a build with V8 and WEBCORE_INSTRUMENTATION set to 3676 * true. Otherwise, this will do nothing. 3677 * 3678 * @hide debug only 3679 */ 3680 public void dumpV8Counters() { 3681 mWebViewCore.sendMessage(EventHub.DUMP_V8COUNTERS); 3682 } 3683 3684 // This is used to determine long press with the center key. Does not 3685 // affect long press with the trackball/touch. 3686 private boolean mGotCenterDown = false; 3687 3688 @Override 3689 public boolean onKeyDown(int keyCode, KeyEvent event) { 3690 if (DebugFlags.WEB_VIEW) { 3691 Log.v(LOGTAG, "keyDown at " + System.currentTimeMillis() 3692 + ", " + event + ", unicode=" + event.getUnicodeChar()); 3693 } 3694 3695 if (mNativeClass == 0) { 3696 return false; 3697 } 3698 3699 // do this hack up front, so it always works, regardless of touch-mode 3700 if (AUTO_REDRAW_HACK && (keyCode == KeyEvent.KEYCODE_CALL)) { 3701 mAutoRedraw = !mAutoRedraw; 3702 if (mAutoRedraw) { 3703 invalidate(); 3704 } 3705 return true; 3706 } 3707 3708 // Bubble up the key event if 3709 // 1. it is a system key; or 3710 // 2. the host application wants to handle it; 3711 // 3. the accessibility injector is present and wants to handle it; 3712 if (event.isSystem() 3713 || mCallbackProxy.uiOverrideKeyEvent(event) 3714 || (mAccessibilityInjector != null && mAccessibilityInjector.onKeyEvent(event))) { 3715 return false; 3716 } 3717 3718 if (keyCode == KeyEvent.KEYCODE_SHIFT_LEFT 3719 || keyCode == KeyEvent.KEYCODE_SHIFT_RIGHT) { 3720 if (nativePageShouldHandleShiftAndArrows()) { 3721 mShiftIsPressed = true; 3722 } else if (!nativeCursorWantsKeyEvents() && !mShiftIsPressed) { 3723 setUpSelectXY(); 3724 } 3725 } 3726 3727 if (keyCode >= KeyEvent.KEYCODE_DPAD_UP 3728 && keyCode <= KeyEvent.KEYCODE_DPAD_RIGHT) { 3729 switchOutDrawHistory(); 3730 if (nativePageShouldHandleShiftAndArrows()) { 3731 letPageHandleNavKey(keyCode, event.getEventTime(), true); 3732 return true; 3733 } 3734 if (mShiftIsPressed) { 3735 int xRate = keyCode == KeyEvent.KEYCODE_DPAD_LEFT 3736 ? -1 : keyCode == KeyEvent.KEYCODE_DPAD_RIGHT ? 1 : 0; 3737 int yRate = keyCode == KeyEvent.KEYCODE_DPAD_UP ? 3738 -1 : keyCode == KeyEvent.KEYCODE_DPAD_DOWN ? 1 : 0; 3739 int multiplier = event.getRepeatCount() + 1; 3740 moveSelection(xRate * multiplier, yRate * multiplier); 3741 return true; 3742 } 3743 if (navHandledKey(keyCode, 1, false, event.getEventTime())) { 3744 playSoundEffect(keyCodeToSoundsEffect(keyCode)); 3745 return true; 3746 } 3747 // Bubble up the key event as WebView doesn't handle it 3748 return false; 3749 } 3750 3751 if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER) { 3752 switchOutDrawHistory(); 3753 if (event.getRepeatCount() == 0) { 3754 if (mShiftIsPressed 3755 && !nativePageShouldHandleShiftAndArrows()) { 3756 return true; // discard press if copy in progress 3757 } 3758 mGotCenterDown = true; 3759 mPrivateHandler.sendMessageDelayed(mPrivateHandler 3760 .obtainMessage(LONG_PRESS_CENTER), LONG_PRESS_TIMEOUT); 3761 // Already checked mNativeClass, so we do not need to check it 3762 // again. 3763 nativeRecordButtons(hasFocus() && hasWindowFocus(), true, true); 3764 return true; 3765 } 3766 // Bubble up the key event as WebView doesn't handle it 3767 return false; 3768 } 3769 3770 if (keyCode != KeyEvent.KEYCODE_SHIFT_LEFT 3771 && keyCode != KeyEvent.KEYCODE_SHIFT_RIGHT) { 3772 // turn off copy select if a shift-key combo is pressed 3773 mExtendSelection = mShiftIsPressed = false; 3774 if (mTouchMode == TOUCH_SELECT_MODE) { 3775 mTouchMode = TOUCH_INIT_MODE; 3776 } 3777 } 3778 3779 if (getSettings().getNavDump()) { 3780 switch (keyCode) { 3781 case KeyEvent.KEYCODE_4: 3782 dumpDisplayTree(); 3783 break; 3784 case KeyEvent.KEYCODE_5: 3785 case KeyEvent.KEYCODE_6: 3786 dumpDomTree(keyCode == KeyEvent.KEYCODE_5); 3787 break; 3788 case KeyEvent.KEYCODE_7: 3789 case KeyEvent.KEYCODE_8: 3790 dumpRenderTree(keyCode == KeyEvent.KEYCODE_7); 3791 break; 3792 case KeyEvent.KEYCODE_9: 3793 nativeInstrumentReport(); 3794 return true; 3795 } 3796 } 3797 3798 if (nativeCursorIsTextInput()) { 3799 // This message will put the node in focus, for the DOM's notion 3800 // of focus, and make the focuscontroller active 3801 mWebViewCore.sendMessage(EventHub.CLICK, nativeCursorFramePointer(), 3802 nativeCursorNodePointer()); 3803 // This will bring up the WebTextView and put it in focus, for 3804 // our view system's notion of focus 3805 rebuildWebTextView(); 3806 // Now we need to pass the event to it 3807 if (inEditingMode()) { 3808 mWebTextView.setDefaultSelection(); 3809 return mWebTextView.dispatchKeyEvent(event); 3810 } 3811 } else if (nativeHasFocusNode()) { 3812 // In this case, the cursor is not on a text input, but the focus 3813 // might be. Check it, and if so, hand over to the WebTextView. 3814 rebuildWebTextView(); 3815 if (inEditingMode()) { 3816 mWebTextView.setDefaultSelection(); 3817 return mWebTextView.dispatchKeyEvent(event); 3818 } 3819 } 3820 3821 // TODO: should we pass all the keys to DOM or check the meta tag 3822 if (nativeCursorWantsKeyEvents() || true) { 3823 // pass the key to DOM 3824 mWebViewCore.sendMessage(EventHub.KEY_DOWN, event); 3825 // return true as DOM handles the key 3826 return true; 3827 } 3828 3829 // Bubble up the key event as WebView doesn't handle it 3830 return false; 3831 } 3832 3833 @Override 3834 public boolean onKeyUp(int keyCode, KeyEvent event) { 3835 if (DebugFlags.WEB_VIEW) { 3836 Log.v(LOGTAG, "keyUp at " + System.currentTimeMillis() 3837 + ", " + event + ", unicode=" + event.getUnicodeChar()); 3838 } 3839 3840 if (mNativeClass == 0) { 3841 return false; 3842 } 3843 3844 // special CALL handling when cursor node's href is "tel:XXX" 3845 if (keyCode == KeyEvent.KEYCODE_CALL && nativeHasCursorNode()) { 3846 String text = nativeCursorText(); 3847 if (!nativeCursorIsTextInput() && text != null 3848 && text.startsWith(SCHEME_TEL)) { 3849 Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse(text)); 3850 getContext().startActivity(intent); 3851 return true; 3852 } 3853 } 3854 3855 // Bubble up the key event if 3856 // 1. it is a system key; or 3857 // 2. the host application wants to handle it; 3858 // 3. the accessibility injector is present and wants to handle it; 3859 if (event.isSystem() 3860 || mCallbackProxy.uiOverrideKeyEvent(event) 3861 || (mAccessibilityInjector != null && mAccessibilityInjector.onKeyEvent(event))) { 3862 return false; 3863 } 3864 3865 if (keyCode == KeyEvent.KEYCODE_SHIFT_LEFT 3866 || keyCode == KeyEvent.KEYCODE_SHIFT_RIGHT) { 3867 if (nativePageShouldHandleShiftAndArrows()) { 3868 mShiftIsPressed = false; 3869 } else if (commitCopy()) { 3870 return true; 3871 } 3872 } 3873 3874 if (keyCode >= KeyEvent.KEYCODE_DPAD_UP 3875 && keyCode <= KeyEvent.KEYCODE_DPAD_RIGHT) { 3876 if (nativePageShouldHandleShiftAndArrows()) { 3877 letPageHandleNavKey(keyCode, event.getEventTime(), false); 3878 return true; 3879 } 3880 // always handle the navigation keys in the UI thread 3881 // Bubble up the key event as WebView doesn't handle it 3882 return false; 3883 } 3884 3885 if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER) { 3886 // remove the long press message first 3887 mPrivateHandler.removeMessages(LONG_PRESS_CENTER); 3888 mGotCenterDown = false; 3889 3890 if (mShiftIsPressed && !nativePageShouldHandleShiftAndArrows()) { 3891 if (mExtendSelection) { 3892 commitCopy(); 3893 } else { 3894 mExtendSelection = true; 3895 invalidate(); // draw the i-beam instead of the arrow 3896 } 3897 return true; // discard press if copy in progress 3898 } 3899 3900 // perform the single click 3901 Rect visibleRect = sendOurVisibleRect(); 3902 // Note that sendOurVisibleRect calls viewToContent, so the 3903 // coordinates should be in content coordinates. 3904 if (!nativeCursorIntersects(visibleRect)) { 3905 return false; 3906 } 3907 WebViewCore.CursorData data = cursorData(); 3908 mWebViewCore.sendMessage(EventHub.SET_MOVE_MOUSE, data); 3909 playSoundEffect(SoundEffectConstants.CLICK); 3910 if (nativeCursorIsTextInput()) { 3911 rebuildWebTextView(); 3912 centerKeyPressOnTextField(); 3913 if (inEditingMode()) { 3914 mWebTextView.setDefaultSelection(); 3915 } 3916 return true; 3917 } 3918 clearTextEntry(true); 3919 nativeSetFollowedLink(true); 3920 if (!mCallbackProxy.uiOverrideUrlLoading(nativeCursorText())) { 3921 mWebViewCore.sendMessage(EventHub.CLICK, data.mFrame, 3922 nativeCursorNodePointer()); 3923 } 3924 return true; 3925 } 3926 3927 // TODO: should we pass all the keys to DOM or check the meta tag 3928 if (nativeCursorWantsKeyEvents() || true) { 3929 // pass the key to DOM 3930 mWebViewCore.sendMessage(EventHub.KEY_UP, event); 3931 // return true as DOM handles the key 3932 return true; 3933 } 3934 3935 // Bubble up the key event as WebView doesn't handle it 3936 return false; 3937 } 3938 3939 private void setUpSelectXY() { 3940 mExtendSelection = false; 3941 mShiftIsPressed = true; 3942 if (nativeHasCursorNode()) { 3943 Rect rect = nativeCursorNodeBounds(); 3944 mSelectX = contentToViewX(rect.left); 3945 mSelectY = contentToViewY(rect.top); 3946 } else if (mLastTouchY > getVisibleTitleHeight()) { 3947 mSelectX = mScrollX + (int) mLastTouchX; 3948 mSelectY = mScrollY + (int) mLastTouchY; 3949 } else { 3950 mSelectX = mScrollX + getViewWidth() / 2; 3951 mSelectY = mScrollY + getViewHeightWithTitle() / 2; 3952 } 3953 nativeHideCursor(); 3954 } 3955 3956 /** 3957 * Use this method to put the WebView into text selection mode. 3958 * Do not rely on this functionality; it will be deprecated in the future. 3959 */ 3960 public void emulateShiftHeld() { 3961 if (0 == mNativeClass) return; // client isn't initialized 3962 setUpSelectXY(); 3963 } 3964 3965 private boolean commitCopy() { 3966 boolean copiedSomething = false; 3967 if (mExtendSelection) { 3968 String selection = nativeGetSelection(); 3969 if (selection != "") { 3970 if (DebugFlags.WEB_VIEW) { 3971 Log.v(LOGTAG, "commitCopy \"" + selection + "\""); 3972 } 3973 Toast.makeText(mContext 3974 , com.android.internal.R.string.text_copied 3975 , Toast.LENGTH_SHORT).show(); 3976 copiedSomething = true; 3977 try { 3978 IClipboard clip = IClipboard.Stub.asInterface( 3979 ServiceManager.getService("clipboard")); 3980 clip.setClipboardText(selection); 3981 } catch (android.os.RemoteException e) { 3982 Log.e(LOGTAG, "Clipboard failed", e); 3983 } 3984 } 3985 mExtendSelection = false; 3986 } 3987 mShiftIsPressed = false; 3988 invalidate(); // remove selection region and pointer 3989 if (mTouchMode == TOUCH_SELECT_MODE) { 3990 mTouchMode = TOUCH_INIT_MODE; 3991 } 3992 return copiedSomething; 3993 } 3994 3995 @Override 3996 protected void onAttachedToWindow() { 3997 super.onAttachedToWindow(); 3998 if (hasWindowFocus()) setActive(true); 3999 } 4000 4001 @Override 4002 protected void onDetachedFromWindow() { 4003 clearTextEntry(false); 4004 mZoomManager.dismissZoomPicker(); 4005 if (hasWindowFocus()) setActive(false); 4006 super.onDetachedFromWindow(); 4007 } 4008 4009 @Override 4010 protected void onVisibilityChanged(View changedView, int visibility) { 4011 super.onVisibilityChanged(changedView, visibility); 4012 if (visibility != View.VISIBLE) { 4013 mZoomManager.dismissZoomPicker(); 4014 } 4015 } 4016 4017 /** 4018 * @deprecated WebView no longer needs to implement 4019 * ViewGroup.OnHierarchyChangeListener. This method does nothing now. 4020 */ 4021 @Deprecated 4022 public void onChildViewAdded(View parent, View child) {} 4023 4024 /** 4025 * @deprecated WebView no longer needs to implement 4026 * ViewGroup.OnHierarchyChangeListener. This method does nothing now. 4027 */ 4028 @Deprecated 4029 public void onChildViewRemoved(View p, View child) {} 4030 4031 /** 4032 * @deprecated WebView should not have implemented 4033 * ViewTreeObserver.OnGlobalFocusChangeListener. This method 4034 * does nothing now. 4035 */ 4036 @Deprecated 4037 public void onGlobalFocusChanged(View oldFocus, View newFocus) { 4038 } 4039 4040 private void setActive(boolean active) { 4041 if (active) { 4042 if (hasFocus()) { 4043 // If our window regained focus, and we have focus, then begin 4044 // drawing the cursor ring 4045 mDrawCursorRing = true; 4046 if (mNativeClass != 0) { 4047 nativeRecordButtons(true, false, true); 4048 if (inEditingMode()) { 4049 mWebViewCore.sendMessage(EventHub.SET_ACTIVE, 1, 0); 4050 } 4051 } 4052 } else { 4053 // If our window gained focus, but we do not have it, do not 4054 // draw the cursor ring. 4055 mDrawCursorRing = false; 4056 // We do not call nativeRecordButtons here because we assume 4057 // that when we lost focus, or window focus, it got called with 4058 // false for the first parameter 4059 } 4060 } else { 4061 if (!mZoomManager.isZoomPickerVisible()) { 4062 /* 4063 * The external zoom controls come in their own window, so our 4064 * window loses focus. Our policy is to not draw the cursor ring 4065 * if our window is not focused, but this is an exception since 4066 * the user can still navigate the web page with the zoom 4067 * controls showing. 4068 */ 4069 mDrawCursorRing = false; 4070 } 4071 mGotKeyDown = false; 4072 mShiftIsPressed = false; 4073 mPrivateHandler.removeMessages(SWITCH_TO_LONGPRESS); 4074 mTouchMode = TOUCH_DONE_MODE; 4075 if (mNativeClass != 0) { 4076 nativeRecordButtons(false, false, true); 4077 } 4078 setFocusControllerInactive(); 4079 } 4080 invalidate(); 4081 } 4082 4083 // To avoid drawing the cursor ring, and remove the TextView when our window 4084 // loses focus. 4085 @Override 4086 public void onWindowFocusChanged(boolean hasWindowFocus) { 4087 setActive(hasWindowFocus); 4088 if (hasWindowFocus) { 4089 BrowserFrame.sJavaBridge.setActiveWebView(this); 4090 } else { 4091 BrowserFrame.sJavaBridge.removeActiveWebView(this); 4092 } 4093 super.onWindowFocusChanged(hasWindowFocus); 4094 } 4095 4096 /* 4097 * Pass a message to WebCore Thread, telling the WebCore::Page's 4098 * FocusController to be "inactive" so that it will 4099 * not draw the blinking cursor. It gets set to "active" to draw the cursor 4100 * in WebViewCore.cpp, when the WebCore thread receives key events/clicks. 4101 */ 4102 /* package */ void setFocusControllerInactive() { 4103 // Do not need to also check whether mWebViewCore is null, because 4104 // mNativeClass is only set if mWebViewCore is non null 4105 if (mNativeClass == 0) return; 4106 mWebViewCore.sendMessage(EventHub.SET_ACTIVE, 0, 0); 4107 } 4108 4109 @Override 4110 protected void onFocusChanged(boolean focused, int direction, 4111 Rect previouslyFocusedRect) { 4112 if (DebugFlags.WEB_VIEW) { 4113 Log.v(LOGTAG, "MT focusChanged " + focused + ", " + direction); 4114 } 4115 if (focused) { 4116 // When we regain focus, if we have window focus, resume drawing 4117 // the cursor ring 4118 if (hasWindowFocus()) { 4119 mDrawCursorRing = true; 4120 if (mNativeClass != 0) { 4121 nativeRecordButtons(true, false, true); 4122 } 4123 //} else { 4124 // The WebView has gained focus while we do not have 4125 // windowfocus. When our window lost focus, we should have 4126 // called nativeRecordButtons(false...) 4127 } 4128 } else { 4129 // When we lost focus, unless focus went to the TextView (which is 4130 // true if we are in editing mode), stop drawing the cursor ring. 4131 if (!inEditingMode()) { 4132 mDrawCursorRing = false; 4133 if (mNativeClass != 0) { 4134 nativeRecordButtons(false, false, true); 4135 } 4136 setFocusControllerInactive(); 4137 } 4138 mGotKeyDown = false; 4139 } 4140 4141 super.onFocusChanged(focused, direction, previouslyFocusedRect); 4142 } 4143 4144 /** 4145 * @hide 4146 */ 4147 @Override 4148 protected boolean setFrame(int left, int top, int right, int bottom) { 4149 boolean changed = super.setFrame(left, top, right, bottom); 4150 if (!changed && mHeightCanMeasure) { 4151 // When mHeightCanMeasure is true, we will set mLastHeightSent to 0 4152 // in WebViewCore after we get the first layout. We do call 4153 // requestLayout() when we get contentSizeChanged(). But the View 4154 // system won't call onSizeChanged if the dimension is not changed. 4155 // In this case, we need to call sendViewSizeZoom() explicitly to 4156 // notify the WebKit about the new dimensions. 4157 sendViewSizeZoom(false); 4158 } 4159 return changed; 4160 } 4161 4162 private static class PostScale implements Runnable { 4163 final WebView mWebView; 4164 final boolean mUpdateTextWrap; 4165 4166 public PostScale(WebView webView, boolean updateTextWrap) { 4167 mWebView = webView; 4168 mUpdateTextWrap = updateTextWrap; 4169 } 4170 4171 public void run() { 4172 if (mWebView.mWebViewCore != null) { 4173 // we always force, in case our height changed, in which case we 4174 // still want to send the notification over to webkit. 4175 mWebView.mZoomManager.refreshZoomScale(mUpdateTextWrap); 4176 // update the zoom buttons as the scale can be changed 4177 mWebView.mZoomManager.updateZoomPicker(); 4178 } 4179 } 4180 } 4181 4182 @Override 4183 protected void onSizeChanged(int w, int h, int ow, int oh) { 4184 super.onSizeChanged(w, h, ow, oh); 4185 // reset zoom and anchor to the top left corner of the screen 4186 // unless we are already zooming 4187 if (!mZoomManager.isZoomAnimating()) { 4188 int visibleTitleHeight = getVisibleTitleHeight(); 4189 mZoomManager.setZoomCenter(0, visibleTitleHeight); 4190 mAnchorX = viewToContentX(mScrollX); 4191 mAnchorY = viewToContentY(visibleTitleHeight + mScrollY); 4192 } 4193 4194 // adjust the max viewport width depending on the view dimensions. This 4195 // is to ensure the scaling is not going insane. So do not shrink it if 4196 // the view size is temporarily smaller, e.g. when soft keyboard is up. 4197 int newMaxViewportWidth = (int) (Math.max(w, h) / mZoomManager.DEFAULT_MIN_ZOOM_SCALE); 4198 if (newMaxViewportWidth > sMaxViewportWidth) { 4199 sMaxViewportWidth = newMaxViewportWidth; 4200 } 4201 4202 // update mMinZoomScale if the minimum zoom scale is not fixed 4203 if (!mZoomManager.mMinZoomScaleFixed) { 4204 // when change from narrow screen to wide screen, the new viewWidth 4205 // can be wider than the old content width. We limit the minimum 4206 // scale to 1.0f. The proper minimum scale will be calculated when 4207 // the new picture shows up. 4208 mZoomManager.mMinZoomScale = Math.min(1.0f, (float) getViewWidth() 4209 / (mDrawHistory ? mHistoryPicture.getWidth() 4210 : mZoomManager.mZoomOverviewWidth)); 4211 if (mInitialScaleInPercent > 0) { 4212 // limit the minZoomScale to the initialScale if it is set 4213 float initialScale = mInitialScaleInPercent / 100.0f; 4214 if (mZoomManager.mMinZoomScale > initialScale) { 4215 mZoomManager.mMinZoomScale = initialScale; 4216 } 4217 } 4218 } 4219 4220 mZoomManager.dismissZoomPicker(); 4221 4222 // onSizeChanged() is called during WebView layout. And any 4223 // requestLayout() is blocked during layout. As setNewZoomScale() will 4224 // call its child View to reposition itself through ViewManager's 4225 // scaleAll(), we need to post a Runnable to ensure requestLayout(). 4226 // <b/> 4227 // only update the text wrap scale if width changed. 4228 post(new PostScale(this, w != ow)); 4229 } 4230 4231 @Override 4232 protected void onScrollChanged(int l, int t, int oldl, int oldt) { 4233 super.onScrollChanged(l, t, oldl, oldt); 4234 sendOurVisibleRect(); 4235 // update WebKit if visible title bar height changed. The logic is same 4236 // as getVisibleTitleHeight. 4237 int titleHeight = getTitleHeight(); 4238 if (Math.max(titleHeight - t, 0) != Math.max(titleHeight - oldt, 0)) { 4239 sendViewSizeZoom(false); 4240 } 4241 } 4242 4243 @Override 4244 public boolean dispatchKeyEvent(KeyEvent event) { 4245 boolean dispatch = true; 4246 4247 // Textfields, plugins, and contentEditable nodes need to receive the 4248 // shift up key even if another key was released while the shift key 4249 // was held down. 4250 if (!inEditingMode() && (mNativeClass == 0 4251 || !nativePageShouldHandleShiftAndArrows())) { 4252 if (event.getAction() == KeyEvent.ACTION_DOWN) { 4253 mGotKeyDown = true; 4254 } else { 4255 if (!mGotKeyDown) { 4256 /* 4257 * We got a key up for which we were not the recipient of 4258 * the original key down. Don't give it to the view. 4259 */ 4260 dispatch = false; 4261 } 4262 mGotKeyDown = false; 4263 } 4264 } 4265 4266 if (dispatch) { 4267 return super.dispatchKeyEvent(event); 4268 } else { 4269 // We didn't dispatch, so let something else handle the key 4270 return false; 4271 } 4272 } 4273 4274 // Here are the snap align logic: 4275 // 1. If it starts nearly horizontally or vertically, snap align; 4276 // 2. If there is a dramitic direction change, let it go; 4277 // 3. If there is a same direction back and forth, lock it. 4278 4279 // adjustable parameters 4280 private int mMinLockSnapReverseDistance; 4281 private static final float MAX_SLOPE_FOR_DIAG = 1.5f; 4282 private static final int MIN_BREAK_SNAP_CROSS_DISTANCE = 80; 4283 4284 private static int sign(float x) { 4285 return x > 0 ? 1 : (x < 0 ? -1 : 0); 4286 } 4287 4288 // if the page can scroll <= this value, we won't allow the drag tracker 4289 // to have any effect. 4290 private static final int MIN_SCROLL_AMOUNT_TO_DISABLE_DRAG_TRACKER = 4; 4291 4292 private class DragTrackerHandler { 4293 private final DragTracker mProxy; 4294 private final float mStartY, mStartX; 4295 private final float mMinDY, mMinDX; 4296 private final float mMaxDY, mMaxDX; 4297 private float mCurrStretchY, mCurrStretchX; 4298 private int mSX, mSY; 4299 private Interpolator mInterp; 4300 private float[] mXY = new float[2]; 4301 4302 // inner (non-state) classes can't have enums :( 4303 private static final int DRAGGING_STATE = 0; 4304 private static final int ANIMATING_STATE = 1; 4305 private static final int FINISHED_STATE = 2; 4306 private int mState; 4307 4308 public DragTrackerHandler(float x, float y, DragTracker proxy) { 4309 mProxy = proxy; 4310 4311 int docBottom = computeVerticalScrollRange() + getTitleHeight(); 4312 int viewTop = getScrollY(); 4313 int viewBottom = viewTop + getHeight(); 4314 4315 mStartY = y; 4316 mMinDY = -viewTop; 4317 mMaxDY = docBottom - viewBottom; 4318 4319 if (DebugFlags.DRAG_TRACKER || DEBUG_DRAG_TRACKER) { 4320 Log.d(DebugFlags.DRAG_TRACKER_LOGTAG, " dragtracker y= " + y + 4321 " up/down= " + mMinDY + " " + mMaxDY); 4322 } 4323 4324 int docRight = computeHorizontalScrollRange(); 4325 int viewLeft = getScrollX(); 4326 int viewRight = viewLeft + getWidth(); 4327 mStartX = x; 4328 mMinDX = -viewLeft; 4329 mMaxDX = docRight - viewRight; 4330 4331 mState = DRAGGING_STATE; 4332 mProxy.onStartDrag(x, y); 4333 4334 // ensure we buildBitmap at least once 4335 mSX = -99999; 4336 } 4337 4338 private float computeStretch(float delta, float min, float max) { 4339 float stretch = 0; 4340 if (max - min > MIN_SCROLL_AMOUNT_TO_DISABLE_DRAG_TRACKER) { 4341 if (delta < min) { 4342 stretch = delta - min; 4343 } else if (delta > max) { 4344 stretch = delta - max; 4345 } 4346 } 4347 return stretch; 4348 } 4349 4350 public void dragTo(float x, float y) { 4351 float sy = computeStretch(mStartY - y, mMinDY, mMaxDY); 4352 float sx = computeStretch(mStartX - x, mMinDX, mMaxDX); 4353 4354 if ((mSnapScrollMode & SNAP_X) != 0) { 4355 sy = 0; 4356 } else if ((mSnapScrollMode & SNAP_Y) != 0) { 4357 sx = 0; 4358 } 4359 4360 if (mCurrStretchX != sx || mCurrStretchY != sy) { 4361 mCurrStretchX = sx; 4362 mCurrStretchY = sy; 4363 if (DebugFlags.DRAG_TRACKER || DEBUG_DRAG_TRACKER) { 4364 Log.d(DebugFlags.DRAG_TRACKER_LOGTAG, "---- stretch " + sx + 4365 " " + sy); 4366 } 4367 if (mProxy.onStretchChange(sx, sy)) { 4368 invalidate(); 4369 } 4370 } 4371 } 4372 4373 public void stopDrag() { 4374 final int DURATION = 200; 4375 int now = (int)SystemClock.uptimeMillis(); 4376 mInterp = new Interpolator(2); 4377 mXY[0] = mCurrStretchX; 4378 mXY[1] = mCurrStretchY; 4379 // float[] blend = new float[] { 0.5f, 0, 0.75f, 1 }; 4380 float[] blend = new float[] { 0, 0.5f, 0.75f, 1 }; 4381 mInterp.setKeyFrame(0, now, mXY, blend); 4382 float[] zerozero = new float[] { 0, 0 }; 4383 mInterp.setKeyFrame(1, now + DURATION, zerozero, null); 4384 mState = ANIMATING_STATE; 4385 4386 if (DebugFlags.DRAG_TRACKER || DEBUG_DRAG_TRACKER) { 4387 Log.d(DebugFlags.DRAG_TRACKER_LOGTAG, "----- stopDrag, starting animation"); 4388 } 4389 } 4390 4391 // Call this after each draw. If it ruturns null, the tracker is done 4392 public boolean isFinished() { 4393 return mState == FINISHED_STATE; 4394 } 4395 4396 private int hiddenHeightOfTitleBar() { 4397 return getTitleHeight() - getVisibleTitleHeight(); 4398 } 4399 4400 // need a way to know if 565 or 8888 is the right config for 4401 // capturing the display and giving it to the drag proxy 4402 private Bitmap.Config offscreenBitmapConfig() { 4403 // hard code 565 for now 4404 return Bitmap.Config.RGB_565; 4405 } 4406 4407 /* If the tracker draws, then this returns true, otherwise it will 4408 return false, and draw nothing. 4409 */ 4410 public boolean draw(Canvas canvas) { 4411 if (mCurrStretchX != 0 || mCurrStretchY != 0) { 4412 int sx = getScrollX(); 4413 int sy = getScrollY() - hiddenHeightOfTitleBar(); 4414 if (mSX != sx || mSY != sy) { 4415 buildBitmap(sx, sy); 4416 mSX = sx; 4417 mSY = sy; 4418 } 4419 4420 if (mState == ANIMATING_STATE) { 4421 Interpolator.Result result = mInterp.timeToValues(mXY); 4422 if (result == Interpolator.Result.FREEZE_END) { 4423 mState = FINISHED_STATE; 4424 return false; 4425 } else { 4426 mProxy.onStretchChange(mXY[0], mXY[1]); 4427 invalidate(); 4428 // fall through to the draw 4429 } 4430 } 4431 int count = canvas.save(Canvas.MATRIX_SAVE_FLAG); 4432 canvas.translate(sx, sy); 4433 mProxy.onDraw(canvas); 4434 canvas.restoreToCount(count); 4435 return true; 4436 } 4437 if (DebugFlags.DRAG_TRACKER || DEBUG_DRAG_TRACKER) { 4438 Log.d(DebugFlags.DRAG_TRACKER_LOGTAG, " -- draw false " + 4439 mCurrStretchX + " " + mCurrStretchY); 4440 } 4441 return false; 4442 } 4443 4444 private void buildBitmap(int sx, int sy) { 4445 int w = getWidth(); 4446 int h = getViewHeight(); 4447 Bitmap bm = Bitmap.createBitmap(w, h, offscreenBitmapConfig()); 4448 Canvas canvas = new Canvas(bm); 4449 canvas.translate(-sx, -sy); 4450 drawContent(canvas); 4451 4452 if (DebugFlags.DRAG_TRACKER || DEBUG_DRAG_TRACKER) { 4453 Log.d(DebugFlags.DRAG_TRACKER_LOGTAG, "--- buildBitmap " + sx + 4454 " " + sy + " " + w + " " + h); 4455 } 4456 mProxy.onBitmapChange(bm); 4457 } 4458 } 4459 4460 /** @hide */ 4461 public static class DragTracker { 4462 public void onStartDrag(float x, float y) {} 4463 public boolean onStretchChange(float sx, float sy) { 4464 // return true to have us inval the view 4465 return false; 4466 } 4467 public void onStopDrag() {} 4468 public void onBitmapChange(Bitmap bm) {} 4469 public void onDraw(Canvas canvas) {} 4470 } 4471 4472 /** @hide */ 4473 public DragTracker getDragTracker() { 4474 return mDragTracker; 4475 } 4476 4477 /** @hide */ 4478 public void setDragTracker(DragTracker tracker) { 4479 mDragTracker = tracker; 4480 } 4481 4482 private DragTracker mDragTracker; 4483 private DragTrackerHandler mDragTrackerHandler; 4484 4485 private class ScaleDetectorListener implements 4486 ScaleGestureDetector.OnScaleGestureListener { 4487 4488 public boolean onScaleBegin(ScaleGestureDetector detector) { 4489 // cancel the single touch handling 4490 cancelTouch(); 4491 mZoomManager.dismissZoomPicker(); 4492 // reset the zoom overview mode so that the page won't auto grow 4493 mZoomManager.mInZoomOverview = false; 4494 // If it is in password mode, turn it off so it does not draw 4495 // misplaced. 4496 if (inEditingMode() && nativeFocusCandidateIsPassword()) { 4497 mWebTextView.setInPassword(false); 4498 } 4499 4500 mViewManager.startZoom(); 4501 4502 return true; 4503 } 4504 4505 public void onScaleEnd(ScaleGestureDetector detector) { 4506 if (mZoomManager.mPreviewZoomOnly) { 4507 mZoomManager.mPreviewZoomOnly = false; 4508 mAnchorX = viewToContentX((int) mZoomManager.mZoomCenterX + mScrollX); 4509 mAnchorY = viewToContentY((int) mZoomManager.mZoomCenterY + mScrollY); 4510 // don't reflow when zoom in; when zoom out, do reflow if the 4511 // new scale is almost minimum scale; 4512 boolean reflowNow = mZoomManager.isZoomedOut() 4513 || (mZoomManager.mActualScale <= 0.8 * mZoomManager.mTextWrapScale); 4514 // force zoom after mPreviewZoomOnly is set to false so that the 4515 // new view size will be passed to the WebKit 4516 mZoomManager.refreshZoomScale(reflowNow); 4517 // call invalidate() to draw without zoom filter 4518 invalidate(); 4519 } 4520 // adjust the edit text view if needed 4521 if (inEditingMode() && didUpdateTextViewBounds(false) 4522 && nativeFocusCandidateIsPassword()) { 4523 // If it is a password field, start drawing the 4524 // WebTextView once again. 4525 mWebTextView.setInPassword(true); 4526 } 4527 // start a drag, TOUCH_PINCH_DRAG, can't use TOUCH_INIT_MODE as it 4528 // may trigger the unwanted click, can't use TOUCH_DRAG_MODE as it 4529 // may trigger the unwanted fling. 4530 mTouchMode = TOUCH_PINCH_DRAG; 4531 mConfirmMove = true; 4532 startTouch(detector.getFocusX(), detector.getFocusY(), 4533 mLastTouchTime); 4534 4535 mViewManager.endZoom(); 4536 } 4537 4538 public boolean onScale(ScaleGestureDetector detector) { 4539 float scale = (float) (Math.round(detector.getScaleFactor() 4540 * mZoomManager.mActualScale * 100) / 100.0); 4541 if (mZoomManager.willScaleTriggerZoom(scale)) { 4542 mZoomManager.mPreviewZoomOnly = true; 4543 // limit the scale change per step 4544 if (scale > mZoomManager.mActualScale) { 4545 scale = Math.min(scale, mZoomManager.mActualScale * 1.25f); 4546 } else { 4547 scale = Math.max(scale, mZoomManager.mActualScale * 0.8f); 4548 } 4549 mZoomManager.setZoomCenter(detector.getFocusX(), detector.getFocusY()); 4550 mZoomManager.setZoomScale(scale, false); 4551 invalidate(); 4552 return true; 4553 } 4554 return false; 4555 } 4556 } 4557 4558 private boolean hitFocusedPlugin(int contentX, int contentY) { 4559 if (DebugFlags.WEB_VIEW) { 4560 Log.v(LOGTAG, "nativeFocusIsPlugin()=" + nativeFocusIsPlugin()); 4561 Rect r = nativeFocusNodeBounds(); 4562 Log.v(LOGTAG, "nativeFocusNodeBounds()=(" + r.left + ", " + r.top 4563 + ", " + r.right + ", " + r.bottom + ")"); 4564 } 4565 return nativeFocusIsPlugin() 4566 && nativeFocusNodeBounds().contains(contentX, contentY); 4567 } 4568 4569 private boolean shouldForwardTouchEvent() { 4570 return mFullScreenHolder != null || (mForwardTouchEvents 4571 && mTouchMode != TOUCH_SELECT_MODE 4572 && mPreventDefault != PREVENT_DEFAULT_IGNORE); 4573 } 4574 4575 private boolean inFullScreenMode() { 4576 return mFullScreenHolder != null; 4577 } 4578 4579 @Override 4580 public boolean onTouchEvent(MotionEvent ev) { 4581 if (mNativeClass == 0 || !isClickable() || !isLongClickable()) { 4582 return false; 4583 } 4584 4585 if (DebugFlags.WEB_VIEW) { 4586 Log.v(LOGTAG, ev + " at " + ev.getEventTime() + " mTouchMode=" 4587 + mTouchMode); 4588 } 4589 4590 int action; 4591 float x, y; 4592 long eventTime = ev.getEventTime(); 4593 4594 // FIXME: we may consider to give WebKit an option to handle multi-touch 4595 // events later. 4596 if (mSupportMultiTouch && ev.getPointerCount() > 1) { 4597 if (mZoomManager.mMinZoomScale < mZoomManager.mMaxZoomScale) { 4598 mScaleDetector.onTouchEvent(ev); 4599 if (mScaleDetector.isInProgress()) { 4600 mLastTouchTime = eventTime; 4601 return true; 4602 } 4603 x = mScaleDetector.getFocusX(); 4604 y = mScaleDetector.getFocusY(); 4605 action = ev.getAction() & MotionEvent.ACTION_MASK; 4606 if (action == MotionEvent.ACTION_POINTER_DOWN) { 4607 cancelTouch(); 4608 action = MotionEvent.ACTION_DOWN; 4609 } else if (action == MotionEvent.ACTION_POINTER_UP) { 4610 // set mLastTouchX/Y to the remaining point 4611 mLastTouchX = x; 4612 mLastTouchY = y; 4613 } else if (action == MotionEvent.ACTION_MOVE) { 4614 // negative x or y indicate it is on the edge, skip it. 4615 if (x < 0 || y < 0) { 4616 return true; 4617 } 4618 } 4619 } else { 4620 // if the page disallow zoom, skip multi-pointer action 4621 return true; 4622 } 4623 } else { 4624 action = ev.getAction(); 4625 x = ev.getX(); 4626 y = ev.getY(); 4627 } 4628 4629 // Due to the touch screen edge effect, a touch closer to the edge 4630 // always snapped to the edge. As getViewWidth() can be different from 4631 // getWidth() due to the scrollbar, adjusting the point to match 4632 // getViewWidth(). Same applied to the height. 4633 if (x > getViewWidth() - 1) { 4634 x = getViewWidth() - 1; 4635 } 4636 if (y > getViewHeightWithTitle() - 1) { 4637 y = getViewHeightWithTitle() - 1; 4638 } 4639 4640 float fDeltaX = mLastTouchX - x; 4641 float fDeltaY = mLastTouchY - y; 4642 int deltaX = (int) fDeltaX; 4643 int deltaY = (int) fDeltaY; 4644 int contentX = viewToContentX((int) x + mScrollX); 4645 int contentY = viewToContentY((int) y + mScrollY); 4646 4647 switch (action) { 4648 case MotionEvent.ACTION_DOWN: { 4649 mPreventDefault = PREVENT_DEFAULT_NO; 4650 mConfirmMove = false; 4651 if (!mScroller.isFinished()) { 4652 // stop the current scroll animation, but if this is 4653 // the start of a fling, allow it to add to the current 4654 // fling's velocity 4655 mScroller.abortAnimation(); 4656 mTouchMode = TOUCH_DRAG_START_MODE; 4657 mConfirmMove = true; 4658 mPrivateHandler.removeMessages(RESUME_WEBCORE_PRIORITY); 4659 } else if (!inFullScreenMode() && mShiftIsPressed) { 4660 mSelectX = mScrollX + (int) x; 4661 mSelectY = mScrollY + (int) y; 4662 mTouchMode = TOUCH_SELECT_MODE; 4663 if (DebugFlags.WEB_VIEW) { 4664 Log.v(LOGTAG, "select=" + mSelectX + "," + mSelectY); 4665 } 4666 nativeMoveSelection(contentX, contentY, false); 4667 mTouchSelection = mExtendSelection = true; 4668 invalidate(); // draw the i-beam instead of the arrow 4669 } else if (mPrivateHandler.hasMessages(RELEASE_SINGLE_TAP)) { 4670 mPrivateHandler.removeMessages(RELEASE_SINGLE_TAP); 4671 if (getSettings().supportTouchOnly()) { 4672 removeTouchHighlight(true); 4673 } 4674 if (deltaX * deltaX + deltaY * deltaY < mDoubleTapSlopSquare) { 4675 mTouchMode = TOUCH_DOUBLE_TAP_MODE; 4676 } else { 4677 // commit the short press action for the previous tap 4678 doShortPress(); 4679 mTouchMode = TOUCH_INIT_MODE; 4680 mDeferTouchProcess = (!inFullScreenMode() 4681 && mForwardTouchEvents) ? hitFocusedPlugin( 4682 contentX, contentY) : false; 4683 } 4684 } else { // the normal case 4685 mZoomManager.mPreviewZoomOnly = false; 4686 mTouchMode = TOUCH_INIT_MODE; 4687 mDeferTouchProcess = (!inFullScreenMode() 4688 && mForwardTouchEvents) ? hitFocusedPlugin( 4689 contentX, contentY) : false; 4690 mWebViewCore.sendMessage( 4691 EventHub.UPDATE_FRAME_CACHE_IF_LOADING); 4692 if (getSettings().supportTouchOnly()) { 4693 TouchHighlightData data = new TouchHighlightData(); 4694 data.mX = contentX; 4695 data.mY = contentY; 4696 data.mSlop = viewToContentDimension(mNavSlop); 4697 mWebViewCore.sendMessageDelayed( 4698 EventHub.GET_TOUCH_HIGHLIGHT_RECTS, data, 4699 ViewConfiguration.getTapTimeout()); 4700 if (DEBUG_TOUCH_HIGHLIGHT) { 4701 if (getSettings().getNavDump()) { 4702 mTouchHighlightX = (int) x + mScrollX; 4703 mTouchHighlightY = (int) y + mScrollY; 4704 mPrivateHandler.postDelayed(new Runnable() { 4705 public void run() { 4706 mTouchHighlightX = mTouchHighlightY = 0; 4707 invalidate(); 4708 } 4709 }, TOUCH_HIGHLIGHT_ELAPSE_TIME); 4710 } 4711 } 4712 } 4713 if (mLogEvent && eventTime - mLastTouchUpTime < 1000) { 4714 EventLog.writeEvent(EventLogTags.BROWSER_DOUBLE_TAP_DURATION, 4715 (eventTime - mLastTouchUpTime), eventTime); 4716 } 4717 } 4718 // Trigger the link 4719 if (mTouchMode == TOUCH_INIT_MODE 4720 || mTouchMode == TOUCH_DOUBLE_TAP_MODE) { 4721 mPrivateHandler.sendEmptyMessageDelayed( 4722 SWITCH_TO_SHORTPRESS, TAP_TIMEOUT); 4723 mPrivateHandler.sendEmptyMessageDelayed( 4724 SWITCH_TO_LONGPRESS, LONG_PRESS_TIMEOUT); 4725 if (inFullScreenMode() || mDeferTouchProcess) { 4726 mPreventDefault = PREVENT_DEFAULT_YES; 4727 } else if (mForwardTouchEvents) { 4728 mPreventDefault = PREVENT_DEFAULT_MAYBE_YES; 4729 } else { 4730 mPreventDefault = PREVENT_DEFAULT_NO; 4731 } 4732 // pass the touch events from UI thread to WebCore thread 4733 if (shouldForwardTouchEvent()) { 4734 TouchEventData ted = new TouchEventData(); 4735 ted.mAction = action; 4736 ted.mX = contentX; 4737 ted.mY = contentY; 4738 ted.mMetaState = ev.getMetaState(); 4739 ted.mReprocess = mDeferTouchProcess; 4740 mWebViewCore.sendMessage(EventHub.TOUCH_EVENT, ted); 4741 if (mDeferTouchProcess) { 4742 // still needs to set them for compute deltaX/Y 4743 mLastTouchX = x; 4744 mLastTouchY = y; 4745 break; 4746 } 4747 if (!inFullScreenMode()) { 4748 mPrivateHandler.removeMessages(PREVENT_DEFAULT_TIMEOUT); 4749 mPrivateHandler.sendMessageDelayed(mPrivateHandler 4750 .obtainMessage(PREVENT_DEFAULT_TIMEOUT, 4751 action, 0), TAP_TIMEOUT); 4752 } 4753 } 4754 } 4755 startTouch(x, y, eventTime); 4756 break; 4757 } 4758 case MotionEvent.ACTION_MOVE: { 4759 boolean firstMove = false; 4760 if (!mConfirmMove && (deltaX * deltaX + deltaY * deltaY) 4761 >= mTouchSlopSquare) { 4762 mPrivateHandler.removeMessages(SWITCH_TO_SHORTPRESS); 4763 mPrivateHandler.removeMessages(SWITCH_TO_LONGPRESS); 4764 mConfirmMove = true; 4765 firstMove = true; 4766 if (mTouchMode == TOUCH_DOUBLE_TAP_MODE) { 4767 mTouchMode = TOUCH_INIT_MODE; 4768 } 4769 if (getSettings().supportTouchOnly()) { 4770 removeTouchHighlight(true); 4771 } 4772 } 4773 // pass the touch events from UI thread to WebCore thread 4774 if (shouldForwardTouchEvent() && mConfirmMove && (firstMove 4775 || eventTime - mLastSentTouchTime > mCurrentTouchInterval)) { 4776 TouchEventData ted = new TouchEventData(); 4777 ted.mAction = action; 4778 ted.mX = contentX; 4779 ted.mY = contentY; 4780 ted.mMetaState = ev.getMetaState(); 4781 ted.mReprocess = mDeferTouchProcess; 4782 mWebViewCore.sendMessage(EventHub.TOUCH_EVENT, ted); 4783 mLastSentTouchTime = eventTime; 4784 if (mDeferTouchProcess) { 4785 break; 4786 } 4787 if (firstMove && !inFullScreenMode()) { 4788 mPrivateHandler.sendMessageDelayed(mPrivateHandler 4789 .obtainMessage(PREVENT_DEFAULT_TIMEOUT, 4790 action, 0), TAP_TIMEOUT); 4791 } 4792 } 4793 if (mTouchMode == TOUCH_DONE_MODE 4794 || mPreventDefault == PREVENT_DEFAULT_YES) { 4795 // no dragging during scroll zoom animation, or when prevent 4796 // default is yes 4797 break; 4798 } 4799 if (mVelocityTracker == null) { 4800 Log.e(LOGTAG, "Got null mVelocityTracker when " 4801 + "mPreventDefault = " + mPreventDefault 4802 + " mDeferTouchProcess = " + mDeferTouchProcess 4803 + " mTouchMode = " + mTouchMode); 4804 } 4805 mVelocityTracker.addMovement(ev); 4806 if (mTouchMode != TOUCH_DRAG_MODE) { 4807 if (mTouchMode == TOUCH_SELECT_MODE) { 4808 mSelectX = mScrollX + (int) x; 4809 mSelectY = mScrollY + (int) y; 4810 if (DebugFlags.WEB_VIEW) { 4811 Log.v(LOGTAG, "xtend=" + mSelectX + "," + mSelectY); 4812 } 4813 nativeMoveSelection(contentX, contentY, true); 4814 invalidate(); 4815 break; 4816 } 4817 4818 if (!mConfirmMove) { 4819 break; 4820 } 4821 4822 if (mPreventDefault == PREVENT_DEFAULT_MAYBE_YES 4823 || mPreventDefault == PREVENT_DEFAULT_NO_FROM_TOUCH_DOWN) { 4824 // track mLastTouchTime as we may need to do fling at 4825 // ACTION_UP 4826 mLastTouchTime = eventTime; 4827 break; 4828 } 4829 // if it starts nearly horizontal or vertical, enforce it 4830 int ax = Math.abs(deltaX); 4831 int ay = Math.abs(deltaY); 4832 if (ax > MAX_SLOPE_FOR_DIAG * ay) { 4833 mSnapScrollMode = SNAP_X; 4834 mSnapPositive = deltaX > 0; 4835 } else if (ay > MAX_SLOPE_FOR_DIAG * ax) { 4836 mSnapScrollMode = SNAP_Y; 4837 mSnapPositive = deltaY > 0; 4838 } 4839 4840 mTouchMode = TOUCH_DRAG_MODE; 4841 mLastTouchX = x; 4842 mLastTouchY = y; 4843 fDeltaX = 0.0f; 4844 fDeltaY = 0.0f; 4845 deltaX = 0; 4846 deltaY = 0; 4847 4848 startDrag(); 4849 } 4850 4851 if (mDragTrackerHandler != null) { 4852 mDragTrackerHandler.dragTo(x, y); 4853 } 4854 4855 // do pan 4856 int newScrollX = pinLocX(mScrollX + deltaX); 4857 int newDeltaX = newScrollX - mScrollX; 4858 if (deltaX != newDeltaX) { 4859 deltaX = newDeltaX; 4860 fDeltaX = (float) newDeltaX; 4861 } 4862 int newScrollY = pinLocY(mScrollY + deltaY); 4863 int newDeltaY = newScrollY - mScrollY; 4864 if (deltaY != newDeltaY) { 4865 deltaY = newDeltaY; 4866 fDeltaY = (float) newDeltaY; 4867 } 4868 boolean done = false; 4869 boolean keepScrollBarsVisible = false; 4870 if (Math.abs(fDeltaX) < 1.0f && Math.abs(fDeltaY) < 1.0f) { 4871 mLastTouchX = x; 4872 mLastTouchY = y; 4873 keepScrollBarsVisible = done = true; 4874 } else { 4875 if (mSnapScrollMode == SNAP_X || mSnapScrollMode == SNAP_Y) { 4876 int ax = Math.abs(deltaX); 4877 int ay = Math.abs(deltaY); 4878 if (mSnapScrollMode == SNAP_X) { 4879 // radical change means getting out of snap mode 4880 if (ay > MAX_SLOPE_FOR_DIAG * ax 4881 && ay > MIN_BREAK_SNAP_CROSS_DISTANCE) { 4882 mSnapScrollMode = SNAP_NONE; 4883 } 4884 // reverse direction means lock in the snap mode 4885 if (ax > MAX_SLOPE_FOR_DIAG * ay && 4886 (mSnapPositive 4887 ? deltaX < -mMinLockSnapReverseDistance 4888 : deltaX > mMinLockSnapReverseDistance)) { 4889 mSnapScrollMode |= SNAP_LOCK; 4890 } 4891 } else { 4892 // radical change means getting out of snap mode 4893 if (ax > MAX_SLOPE_FOR_DIAG * ay 4894 && ax > MIN_BREAK_SNAP_CROSS_DISTANCE) { 4895 mSnapScrollMode = SNAP_NONE; 4896 } 4897 // reverse direction means lock in the snap mode 4898 if (ay > MAX_SLOPE_FOR_DIAG * ax && 4899 (mSnapPositive 4900 ? deltaY < -mMinLockSnapReverseDistance 4901 : deltaY > mMinLockSnapReverseDistance)) { 4902 mSnapScrollMode |= SNAP_LOCK; 4903 } 4904 } 4905 } 4906 if (mSnapScrollMode != SNAP_NONE) { 4907 if ((mSnapScrollMode & SNAP_X) == SNAP_X) { 4908 deltaY = 0; 4909 } else { 4910 deltaX = 0; 4911 } 4912 } 4913 if ((deltaX | deltaY) != 0) { 4914 if (deltaX != 0) { 4915 mLastTouchX = x; 4916 } 4917 if (deltaY != 0) { 4918 mLastTouchY = y; 4919 } 4920 mHeldMotionless = MOTIONLESS_FALSE; 4921 } else { 4922 // keep the scrollbar on the screen even there is no 4923 // scroll 4924 mLastTouchX = x; 4925 mLastTouchY = y; 4926 keepScrollBarsVisible = true; 4927 } 4928 mLastTouchTime = eventTime; 4929 mUserScroll = true; 4930 } 4931 4932 doDrag(deltaX, deltaY); 4933 4934 if (keepScrollBarsVisible) { 4935 if (mHeldMotionless != MOTIONLESS_TRUE) { 4936 mHeldMotionless = MOTIONLESS_TRUE; 4937 invalidate(); 4938 } 4939 // keep the scrollbar on the screen even there is no scroll 4940 awakenScrollBars(ViewConfiguration.getScrollDefaultDelay(), 4941 false); 4942 // return false to indicate that we can't pan out of the 4943 // view space 4944 return !done; 4945 } 4946 break; 4947 } 4948 case MotionEvent.ACTION_UP: { 4949 if (!isFocused()) requestFocus(); 4950 // pass the touch events from UI thread to WebCore thread 4951 if (shouldForwardTouchEvent()) { 4952 TouchEventData ted = new TouchEventData(); 4953 ted.mAction = action; 4954 ted.mX = contentX; 4955 ted.mY = contentY; 4956 ted.mMetaState = ev.getMetaState(); 4957 ted.mReprocess = mDeferTouchProcess; 4958 mWebViewCore.sendMessage(EventHub.TOUCH_EVENT, ted); 4959 } 4960 mLastTouchUpTime = eventTime; 4961 switch (mTouchMode) { 4962 case TOUCH_DOUBLE_TAP_MODE: // double tap 4963 mPrivateHandler.removeMessages(SWITCH_TO_SHORTPRESS); 4964 mPrivateHandler.removeMessages(SWITCH_TO_LONGPRESS); 4965 if (inFullScreenMode() || mDeferTouchProcess) { 4966 TouchEventData ted = new TouchEventData(); 4967 ted.mAction = WebViewCore.ACTION_DOUBLETAP; 4968 ted.mX = contentX; 4969 ted.mY = contentY; 4970 ted.mMetaState = ev.getMetaState(); 4971 ted.mReprocess = mDeferTouchProcess; 4972 mWebViewCore.sendMessage(EventHub.TOUCH_EVENT, ted); 4973 } else if (mPreventDefault != PREVENT_DEFAULT_YES){ 4974 doDoubleTap(); 4975 mTouchMode = TOUCH_DONE_MODE; 4976 } 4977 break; 4978 case TOUCH_SELECT_MODE: 4979 commitCopy(); 4980 mTouchSelection = false; 4981 break; 4982 case TOUCH_INIT_MODE: // tap 4983 case TOUCH_SHORTPRESS_START_MODE: 4984 case TOUCH_SHORTPRESS_MODE: 4985 mPrivateHandler.removeMessages(SWITCH_TO_SHORTPRESS); 4986 mPrivateHandler.removeMessages(SWITCH_TO_LONGPRESS); 4987 if (mConfirmMove) { 4988 Log.w(LOGTAG, "Miss a drag as we are waiting for" + 4989 " WebCore's response for touch down."); 4990 if (mPreventDefault != PREVENT_DEFAULT_YES 4991 && (computeMaxScrollX() > 0 4992 || computeMaxScrollY() > 0)) { 4993 // If the user has performed a very quick touch 4994 // sequence it is possible that we may get here 4995 // before WebCore has had a chance to process the events. 4996 // In this case, any call to preventDefault in the 4997 // JS touch handler will not have been executed yet. 4998 // Hence we will see both the UI (now) and WebCore 4999 // (when context switches) handling the event, 5000 // regardless of whether the web developer actually 5001 // doeses preventDefault in their touch handler. This 5002 // is the nature of our asynchronous touch model. 5003 5004 // we will not rewrite drag code here, but we 5005 // will try fling if it applies. 5006 WebViewCore.reducePriority(); 5007 // to get better performance, pause updating the 5008 // picture 5009 WebViewCore.pauseUpdatePicture(mWebViewCore); 5010 // fall through to TOUCH_DRAG_MODE 5011 } else { 5012 // WebKit may consume the touch event and modify 5013 // DOM. drawContentPicture() will be called with 5014 // animateSroll as true for better performance. 5015 // Force redraw in high-quality. 5016 invalidate(); 5017 break; 5018 } 5019 } else { 5020 if (mTouchMode == TOUCH_INIT_MODE) { 5021 mPrivateHandler.sendEmptyMessageDelayed( 5022 RELEASE_SINGLE_TAP, ViewConfiguration 5023 .getDoubleTapTimeout()); 5024 } else { 5025 doShortPress(); 5026 } 5027 break; 5028 } 5029 case TOUCH_DRAG_MODE: 5030 mPrivateHandler.removeMessages(DRAG_HELD_MOTIONLESS); 5031 mPrivateHandler.removeMessages(AWAKEN_SCROLL_BARS); 5032 // if the user waits a while w/o moving before the 5033 // up, we don't want to do a fling 5034 if (eventTime - mLastTouchTime <= MIN_FLING_TIME) { 5035 if (mVelocityTracker == null) { 5036 Log.e(LOGTAG, "Got null mVelocityTracker when " 5037 + "mPreventDefault = " 5038 + mPreventDefault 5039 + " mDeferTouchProcess = " 5040 + mDeferTouchProcess); 5041 } 5042 mVelocityTracker.addMovement(ev); 5043 // set to MOTIONLESS_IGNORE so that it won't keep 5044 // removing and sending message in 5045 // drawCoreAndCursorRing() 5046 mHeldMotionless = MOTIONLESS_IGNORE; 5047 doFling(); 5048 break; 5049 } 5050 // redraw in high-quality, as we're done dragging 5051 mHeldMotionless = MOTIONLESS_TRUE; 5052 invalidate(); 5053 // fall through 5054 case TOUCH_DRAG_START_MODE: 5055 // TOUCH_DRAG_START_MODE should not happen for the real 5056 // device as we almost certain will get a MOVE. But this 5057 // is possible on emulator. 5058 mLastVelocity = 0; 5059 WebViewCore.resumePriority(); 5060 WebViewCore.resumeUpdatePicture(mWebViewCore); 5061 break; 5062 } 5063 stopTouch(); 5064 break; 5065 } 5066 case MotionEvent.ACTION_CANCEL: { 5067 if (mTouchMode == TOUCH_DRAG_MODE) { 5068 invalidate(); 5069 } 5070 cancelWebCoreTouchEvent(contentX, contentY, false); 5071 cancelTouch(); 5072 break; 5073 } 5074 } 5075 return true; 5076 } 5077 5078 private void cancelWebCoreTouchEvent(int x, int y, boolean removeEvents) { 5079 if (shouldForwardTouchEvent()) { 5080 if (removeEvents) { 5081 mWebViewCore.removeMessages(EventHub.TOUCH_EVENT); 5082 } 5083 TouchEventData ted = new TouchEventData(); 5084 ted.mX = x; 5085 ted.mY = y; 5086 ted.mAction = MotionEvent.ACTION_CANCEL; 5087 mWebViewCore.sendMessage(EventHub.TOUCH_EVENT, ted); 5088 mPreventDefault = PREVENT_DEFAULT_IGNORE; 5089 } 5090 } 5091 5092 private void startTouch(float x, float y, long eventTime) { 5093 // Remember where the motion event started 5094 mLastTouchX = x; 5095 mLastTouchY = y; 5096 mLastTouchTime = eventTime; 5097 mVelocityTracker = VelocityTracker.obtain(); 5098 mSnapScrollMode = SNAP_NONE; 5099 if (mDragTracker != null) { 5100 mDragTrackerHandler = new DragTrackerHandler(x, y, mDragTracker); 5101 } 5102 } 5103 5104 private void startDrag() { 5105 WebViewCore.reducePriority(); 5106 // to get better performance, pause updating the picture 5107 WebViewCore.pauseUpdatePicture(mWebViewCore); 5108 if (!mDragFromTextInput) { 5109 nativeHideCursor(); 5110 } 5111 5112 if (mHorizontalScrollBarMode != SCROLLBAR_ALWAYSOFF 5113 || mVerticalScrollBarMode != SCROLLBAR_ALWAYSOFF) { 5114 mZoomManager.invokeZoomPicker(); 5115 } 5116 } 5117 5118 private void doDrag(int deltaX, int deltaY) { 5119 if ((deltaX | deltaY) != 0) { 5120 scrollBy(deltaX, deltaY); 5121 } 5122 mZoomManager.keepZoomPickerVisible(); 5123 } 5124 5125 private void stopTouch() { 5126 if (mDragTrackerHandler != null) { 5127 mDragTrackerHandler.stopDrag(); 5128 } 5129 // we also use mVelocityTracker == null to tell us that we are 5130 // not "moving around", so we can take the slower/prettier 5131 // mode in the drawing code 5132 if (mVelocityTracker != null) { 5133 mVelocityTracker.recycle(); 5134 mVelocityTracker = null; 5135 } 5136 } 5137 5138 private void cancelTouch() { 5139 if (mDragTrackerHandler != null) { 5140 mDragTrackerHandler.stopDrag(); 5141 } 5142 // we also use mVelocityTracker == null to tell us that we are 5143 // not "moving around", so we can take the slower/prettier 5144 // mode in the drawing code 5145 if (mVelocityTracker != null) { 5146 mVelocityTracker.recycle(); 5147 mVelocityTracker = null; 5148 } 5149 if (mTouchMode == TOUCH_DRAG_MODE) { 5150 WebViewCore.resumePriority(); 5151 WebViewCore.resumeUpdatePicture(mWebViewCore); 5152 } 5153 mPrivateHandler.removeMessages(SWITCH_TO_SHORTPRESS); 5154 mPrivateHandler.removeMessages(SWITCH_TO_LONGPRESS); 5155 mPrivateHandler.removeMessages(DRAG_HELD_MOTIONLESS); 5156 mPrivateHandler.removeMessages(AWAKEN_SCROLL_BARS); 5157 if (getSettings().supportTouchOnly()) { 5158 removeTouchHighlight(true); 5159 } 5160 mHeldMotionless = MOTIONLESS_TRUE; 5161 mTouchMode = TOUCH_DONE_MODE; 5162 nativeHideCursor(); 5163 } 5164 5165 private long mTrackballFirstTime = 0; 5166 private long mTrackballLastTime = 0; 5167 private float mTrackballRemainsX = 0.0f; 5168 private float mTrackballRemainsY = 0.0f; 5169 private int mTrackballXMove = 0; 5170 private int mTrackballYMove = 0; 5171 private boolean mExtendSelection = false; 5172 private boolean mTouchSelection = false; 5173 private static final int TRACKBALL_KEY_TIMEOUT = 1000; 5174 private static final int TRACKBALL_TIMEOUT = 200; 5175 private static final int TRACKBALL_WAIT = 100; 5176 private static final int TRACKBALL_SCALE = 400; 5177 private static final int TRACKBALL_SCROLL_COUNT = 5; 5178 private static final int TRACKBALL_MOVE_COUNT = 10; 5179 private static final int TRACKBALL_MULTIPLIER = 3; 5180 private static final int SELECT_CURSOR_OFFSET = 16; 5181 private int mSelectX = 0; 5182 private int mSelectY = 0; 5183 private boolean mFocusSizeChanged = false; 5184 private boolean mShiftIsPressed = false; 5185 private boolean mTrackballDown = false; 5186 private long mTrackballUpTime = 0; 5187 private long mLastCursorTime = 0; 5188 private Rect mLastCursorBounds; 5189 5190 // Set by default; BrowserActivity clears to interpret trackball data 5191 // directly for movement. Currently, the framework only passes 5192 // arrow key events, not trackball events, from one child to the next 5193 private boolean mMapTrackballToArrowKeys = true; 5194 5195 public void setMapTrackballToArrowKeys(boolean setMap) { 5196 mMapTrackballToArrowKeys = setMap; 5197 } 5198 5199 void resetTrackballTime() { 5200 mTrackballLastTime = 0; 5201 } 5202 5203 @Override 5204 public boolean onTrackballEvent(MotionEvent ev) { 5205 long time = ev.getEventTime(); 5206 if ((ev.getMetaState() & KeyEvent.META_ALT_ON) != 0) { 5207 if (ev.getY() > 0) pageDown(true); 5208 if (ev.getY() < 0) pageUp(true); 5209 return true; 5210 } 5211 boolean shiftPressed = mShiftIsPressed && (mNativeClass == 0 5212 || !nativePageShouldHandleShiftAndArrows()); 5213 if (ev.getAction() == MotionEvent.ACTION_DOWN) { 5214 if (shiftPressed) { 5215 return true; // discard press if copy in progress 5216 } 5217 mTrackballDown = true; 5218 if (mNativeClass == 0) { 5219 return false; 5220 } 5221 nativeRecordButtons(hasFocus() && hasWindowFocus(), true, true); 5222 if (time - mLastCursorTime <= TRACKBALL_TIMEOUT 5223 && !mLastCursorBounds.equals(nativeGetCursorRingBounds())) { 5224 nativeSelectBestAt(mLastCursorBounds); 5225 } 5226 if (DebugFlags.WEB_VIEW) { 5227 Log.v(LOGTAG, "onTrackballEvent down ev=" + ev 5228 + " time=" + time 5229 + " mLastCursorTime=" + mLastCursorTime); 5230 } 5231 if (isInTouchMode()) requestFocusFromTouch(); 5232 return false; // let common code in onKeyDown at it 5233 } 5234 if (ev.getAction() == MotionEvent.ACTION_UP) { 5235 // LONG_PRESS_CENTER is set in common onKeyDown 5236 mPrivateHandler.removeMessages(LONG_PRESS_CENTER); 5237 mTrackballDown = false; 5238 mTrackballUpTime = time; 5239 if (shiftPressed) { 5240 if (mExtendSelection) { 5241 commitCopy(); 5242 } else { 5243 mExtendSelection = true; 5244 invalidate(); // draw the i-beam instead of the arrow 5245 } 5246 return true; // discard press if copy in progress 5247 } 5248 if (DebugFlags.WEB_VIEW) { 5249 Log.v(LOGTAG, "onTrackballEvent up ev=" + ev 5250 + " time=" + time 5251 ); 5252 } 5253 return false; // let common code in onKeyUp at it 5254 } 5255 if (mMapTrackballToArrowKeys && mShiftIsPressed == false) { 5256 if (DebugFlags.WEB_VIEW) Log.v(LOGTAG, "onTrackballEvent gmail quit"); 5257 return false; 5258 } 5259 if (mTrackballDown) { 5260 if (DebugFlags.WEB_VIEW) Log.v(LOGTAG, "onTrackballEvent down quit"); 5261 return true; // discard move if trackball is down 5262 } 5263 if (time - mTrackballUpTime < TRACKBALL_TIMEOUT) { 5264 if (DebugFlags.WEB_VIEW) Log.v(LOGTAG, "onTrackballEvent up timeout quit"); 5265 return true; 5266 } 5267 // TODO: alternatively we can do panning as touch does 5268 switchOutDrawHistory(); 5269 if (time - mTrackballLastTime > TRACKBALL_TIMEOUT) { 5270 if (DebugFlags.WEB_VIEW) { 5271 Log.v(LOGTAG, "onTrackballEvent time=" 5272 + time + " last=" + mTrackballLastTime); 5273 } 5274 mTrackballFirstTime = time; 5275 mTrackballXMove = mTrackballYMove = 0; 5276 } 5277 mTrackballLastTime = time; 5278 if (DebugFlags.WEB_VIEW) { 5279 Log.v(LOGTAG, "onTrackballEvent ev=" + ev + " time=" + time); 5280 } 5281 mTrackballRemainsX += ev.getX(); 5282 mTrackballRemainsY += ev.getY(); 5283 doTrackball(time); 5284 return true; 5285 } 5286 5287 void moveSelection(float xRate, float yRate) { 5288 if (mNativeClass == 0) 5289 return; 5290 int width = getViewWidth(); 5291 int height = getViewHeight(); 5292 mSelectX += xRate; 5293 mSelectY += yRate; 5294 int maxX = width + mScrollX; 5295 int maxY = height + mScrollY; 5296 mSelectX = Math.min(maxX, Math.max(mScrollX - SELECT_CURSOR_OFFSET 5297 , mSelectX)); 5298 mSelectY = Math.min(maxY, Math.max(mScrollY - SELECT_CURSOR_OFFSET 5299 , mSelectY)); 5300 if (DebugFlags.WEB_VIEW) { 5301 Log.v(LOGTAG, "moveSelection" 5302 + " mSelectX=" + mSelectX 5303 + " mSelectY=" + mSelectY 5304 + " mScrollX=" + mScrollX 5305 + " mScrollY=" + mScrollY 5306 + " xRate=" + xRate 5307 + " yRate=" + yRate 5308 ); 5309 } 5310 nativeMoveSelection(viewToContentX(mSelectX), 5311 viewToContentY(mSelectY), mExtendSelection); 5312 int scrollX = mSelectX < mScrollX ? -SELECT_CURSOR_OFFSET 5313 : mSelectX > maxX - SELECT_CURSOR_OFFSET ? SELECT_CURSOR_OFFSET 5314 : 0; 5315 int scrollY = mSelectY < mScrollY ? -SELECT_CURSOR_OFFSET 5316 : mSelectY > maxY - SELECT_CURSOR_OFFSET ? SELECT_CURSOR_OFFSET 5317 : 0; 5318 pinScrollBy(scrollX, scrollY, true, 0); 5319 Rect select = new Rect(mSelectX, mSelectY, mSelectX + 1, mSelectY + 1); 5320 requestRectangleOnScreen(select); 5321 invalidate(); 5322 } 5323 5324 private int scaleTrackballX(float xRate, int width) { 5325 int xMove = (int) (xRate / TRACKBALL_SCALE * width); 5326 int nextXMove = xMove; 5327 if (xMove > 0) { 5328 if (xMove > mTrackballXMove) { 5329 xMove -= mTrackballXMove; 5330 } 5331 } else if (xMove < mTrackballXMove) { 5332 xMove -= mTrackballXMove; 5333 } 5334 mTrackballXMove = nextXMove; 5335 return xMove; 5336 } 5337 5338 private int scaleTrackballY(float yRate, int height) { 5339 int yMove = (int) (yRate / TRACKBALL_SCALE * height); 5340 int nextYMove = yMove; 5341 if (yMove > 0) { 5342 if (yMove > mTrackballYMove) { 5343 yMove -= mTrackballYMove; 5344 } 5345 } else if (yMove < mTrackballYMove) { 5346 yMove -= mTrackballYMove; 5347 } 5348 mTrackballYMove = nextYMove; 5349 return yMove; 5350 } 5351 5352 private int keyCodeToSoundsEffect(int keyCode) { 5353 switch(keyCode) { 5354 case KeyEvent.KEYCODE_DPAD_UP: 5355 return SoundEffectConstants.NAVIGATION_UP; 5356 case KeyEvent.KEYCODE_DPAD_RIGHT: 5357 return SoundEffectConstants.NAVIGATION_RIGHT; 5358 case KeyEvent.KEYCODE_DPAD_DOWN: 5359 return SoundEffectConstants.NAVIGATION_DOWN; 5360 case KeyEvent.KEYCODE_DPAD_LEFT: 5361 return SoundEffectConstants.NAVIGATION_LEFT; 5362 } 5363 throw new IllegalArgumentException("keyCode must be one of " + 5364 "{KEYCODE_DPAD_UP, KEYCODE_DPAD_RIGHT, KEYCODE_DPAD_DOWN, " + 5365 "KEYCODE_DPAD_LEFT}."); 5366 } 5367 5368 private void doTrackball(long time) { 5369 int elapsed = (int) (mTrackballLastTime - mTrackballFirstTime); 5370 if (elapsed == 0) { 5371 elapsed = TRACKBALL_TIMEOUT; 5372 } 5373 float xRate = mTrackballRemainsX * 1000 / elapsed; 5374 float yRate = mTrackballRemainsY * 1000 / elapsed; 5375 int viewWidth = getViewWidth(); 5376 int viewHeight = getViewHeight(); 5377 if (mShiftIsPressed && (mNativeClass == 0 5378 || !nativePageShouldHandleShiftAndArrows())) { 5379 moveSelection(scaleTrackballX(xRate, viewWidth), 5380 scaleTrackballY(yRate, viewHeight)); 5381 mTrackballRemainsX = mTrackballRemainsY = 0; 5382 return; 5383 } 5384 float ax = Math.abs(xRate); 5385 float ay = Math.abs(yRate); 5386 float maxA = Math.max(ax, ay); 5387 if (DebugFlags.WEB_VIEW) { 5388 Log.v(LOGTAG, "doTrackball elapsed=" + elapsed 5389 + " xRate=" + xRate 5390 + " yRate=" + yRate 5391 + " mTrackballRemainsX=" + mTrackballRemainsX 5392 + " mTrackballRemainsY=" + mTrackballRemainsY); 5393 } 5394 int width = mContentWidth - viewWidth; 5395 int height = mContentHeight - viewHeight; 5396 if (width < 0) width = 0; 5397 if (height < 0) height = 0; 5398 ax = Math.abs(mTrackballRemainsX * TRACKBALL_MULTIPLIER); 5399 ay = Math.abs(mTrackballRemainsY * TRACKBALL_MULTIPLIER); 5400 maxA = Math.max(ax, ay); 5401 int count = Math.max(0, (int) maxA); 5402 int oldScrollX = mScrollX; 5403 int oldScrollY = mScrollY; 5404 if (count > 0) { 5405 int selectKeyCode = ax < ay ? mTrackballRemainsY < 0 ? 5406 KeyEvent.KEYCODE_DPAD_UP : KeyEvent.KEYCODE_DPAD_DOWN : 5407 mTrackballRemainsX < 0 ? KeyEvent.KEYCODE_DPAD_LEFT : 5408 KeyEvent.KEYCODE_DPAD_RIGHT; 5409 count = Math.min(count, TRACKBALL_MOVE_COUNT); 5410 if (DebugFlags.WEB_VIEW) { 5411 Log.v(LOGTAG, "doTrackball keyCode=" + selectKeyCode 5412 + " count=" + count 5413 + " mTrackballRemainsX=" + mTrackballRemainsX 5414 + " mTrackballRemainsY=" + mTrackballRemainsY); 5415 } 5416 if (mNativeClass != 0 && nativePageShouldHandleShiftAndArrows()) { 5417 for (int i = 0; i < count; i++) { 5418 letPageHandleNavKey(selectKeyCode, time, true); 5419 } 5420 letPageHandleNavKey(selectKeyCode, time, false); 5421 } else if (navHandledKey(selectKeyCode, count, false, time)) { 5422 playSoundEffect(keyCodeToSoundsEffect(selectKeyCode)); 5423 } 5424 mTrackballRemainsX = mTrackballRemainsY = 0; 5425 } 5426 if (count >= TRACKBALL_SCROLL_COUNT) { 5427 int xMove = scaleTrackballX(xRate, width); 5428 int yMove = scaleTrackballY(yRate, height); 5429 if (DebugFlags.WEB_VIEW) { 5430 Log.v(LOGTAG, "doTrackball pinScrollBy" 5431 + " count=" + count 5432 + " xMove=" + xMove + " yMove=" + yMove 5433 + " mScrollX-oldScrollX=" + (mScrollX-oldScrollX) 5434 + " mScrollY-oldScrollY=" + (mScrollY-oldScrollY) 5435 ); 5436 } 5437 if (Math.abs(mScrollX - oldScrollX) > Math.abs(xMove)) { 5438 xMove = 0; 5439 } 5440 if (Math.abs(mScrollY - oldScrollY) > Math.abs(yMove)) { 5441 yMove = 0; 5442 } 5443 if (xMove != 0 || yMove != 0) { 5444 pinScrollBy(xMove, yMove, true, 0); 5445 } 5446 mUserScroll = true; 5447 } 5448 } 5449 5450 private int computeMaxScrollX() { 5451 return Math.max(computeHorizontalScrollRange() - getViewWidth(), 0); 5452 } 5453 5454 private int computeMaxScrollY() { 5455 return Math.max(computeVerticalScrollRange() + getTitleHeight() 5456 - getViewHeightWithTitle(), 0); 5457 } 5458 5459 boolean updateScrollCoordinates(int x, int y) { 5460 int oldX = mScrollX; 5461 int oldY = mScrollY; 5462 mScrollX = x; 5463 mScrollY = y; 5464 if (oldX != mScrollX || oldY != mScrollY) { 5465 onScrollChanged(mScrollX, mScrollY, oldX, oldY); 5466 return true; 5467 } else { 5468 return false; 5469 } 5470 } 5471 5472 public void flingScroll(int vx, int vy) { 5473 mScroller.fling(mScrollX, mScrollY, vx, vy, 0, computeMaxScrollX(), 0, 5474 computeMaxScrollY()); 5475 invalidate(); 5476 } 5477 5478 private void doFling() { 5479 if (mVelocityTracker == null) { 5480 return; 5481 } 5482 int maxX = computeMaxScrollX(); 5483 int maxY = computeMaxScrollY(); 5484 5485 mVelocityTracker.computeCurrentVelocity(1000, mMaximumFling); 5486 int vx = (int) mVelocityTracker.getXVelocity(); 5487 int vy = (int) mVelocityTracker.getYVelocity(); 5488 5489 if (mSnapScrollMode != SNAP_NONE) { 5490 if ((mSnapScrollMode & SNAP_X) == SNAP_X) { 5491 vy = 0; 5492 } else { 5493 vx = 0; 5494 } 5495 } 5496 if (true /* EMG release: make our fling more like Maps' */) { 5497 // maps cuts their velocity in half 5498 vx = vx * 3 / 4; 5499 vy = vy * 3 / 4; 5500 } 5501 if ((maxX == 0 && vy == 0) || (maxY == 0 && vx == 0)) { 5502 WebViewCore.resumePriority(); 5503 WebViewCore.resumeUpdatePicture(mWebViewCore); 5504 return; 5505 } 5506 float currentVelocity = mScroller.getCurrVelocity(); 5507 float velocity = (float) Math.hypot(vx, vy); 5508 if (mLastVelocity > 0 && currentVelocity > 0 && velocity 5509 > mLastVelocity * MINIMUM_VELOCITY_RATIO_FOR_ACCELERATION) { 5510 float deltaR = (float) (Math.abs(Math.atan2(mLastVelY, mLastVelX) 5511 - Math.atan2(vy, vx))); 5512 final float circle = (float) (Math.PI) * 2.0f; 5513 if (deltaR > circle * 0.9f || deltaR < circle * 0.1f) { 5514 vx += currentVelocity * mLastVelX / mLastVelocity; 5515 vy += currentVelocity * mLastVelY / mLastVelocity; 5516 velocity = (float) Math.hypot(vx, vy); 5517 if (DebugFlags.WEB_VIEW) { 5518 Log.v(LOGTAG, "doFling vx= " + vx + " vy=" + vy); 5519 } 5520 } else if (DebugFlags.WEB_VIEW) { 5521 Log.v(LOGTAG, "doFling missed " + deltaR / circle); 5522 } 5523 } else if (DebugFlags.WEB_VIEW) { 5524 Log.v(LOGTAG, "doFling start last=" + mLastVelocity 5525 + " current=" + currentVelocity 5526 + " vx=" + vx + " vy=" + vy 5527 + " maxX=" + maxX + " maxY=" + maxY 5528 + " mScrollX=" + mScrollX + " mScrollY=" + mScrollY); 5529 } 5530 mLastVelX = vx; 5531 mLastVelY = vy; 5532 mLastVelocity = velocity; 5533 5534 mScroller.fling(mScrollX, mScrollY, -vx, -vy, 0, maxX, 0, maxY); 5535 // TODO: duration is calculated based on velocity, if the range is 5536 // small, the animation will stop before duration is up. We may 5537 // want to calculate how long the animation is going to run to precisely 5538 // resume the webcore update. 5539 final int time = mScroller.getDuration(); 5540 mPrivateHandler.sendEmptyMessageDelayed(RESUME_WEBCORE_PRIORITY, time); 5541 awakenScrollBars(time); 5542 invalidate(); 5543 } 5544 5545 /** 5546 * Returns a view containing zoom controls i.e. +/- buttons. The caller is 5547 * in charge of installing this view to the view hierarchy. This view will 5548 * become visible when the user starts scrolling via touch and fade away if 5549 * the user does not interact with it. 5550 * <p/> 5551 * API version 3 introduces a built-in zoom mechanism that is shown 5552 * automatically by the MapView. This is the preferred approach for 5553 * showing the zoom UI. 5554 * 5555 * @deprecated The built-in zoom mechanism is preferred, see 5556 * {@link WebSettings#setBuiltInZoomControls(boolean)}. 5557 */ 5558 @Deprecated 5559 public View getZoomControls() { 5560 if (!getSettings().supportZoom()) { 5561 Log.w(LOGTAG, "This WebView doesn't support zoom."); 5562 return null; 5563 } 5564 return mZoomManager.getExternalZoomPicker(); 5565 } 5566 5567 void dismissZoomControl() { 5568 mZoomManager.dismissZoomPicker(); 5569 } 5570 5571 float getDefaultZoomScale() { 5572 return mZoomManager.mDefaultScale; 5573 } 5574 5575 /** 5576 * Perform zoom in in the webview 5577 * @return TRUE if zoom in succeeds. FALSE if no zoom changes. 5578 */ 5579 public boolean zoomIn() { 5580 return mZoomManager.zoomIn(); 5581 } 5582 5583 /** 5584 * Perform zoom out in the webview 5585 * @return TRUE if zoom out succeeds. FALSE if no zoom changes. 5586 */ 5587 public boolean zoomOut() { 5588 return mZoomManager.zoomOut(); 5589 } 5590 5591 private void updateSelection() { 5592 if (mNativeClass == 0) { 5593 return; 5594 } 5595 // mLastTouchX and mLastTouchY are the point in the current viewport 5596 int contentX = viewToContentX((int) mLastTouchX + mScrollX); 5597 int contentY = viewToContentY((int) mLastTouchY + mScrollY); 5598 Rect rect = new Rect(contentX - mNavSlop, contentY - mNavSlop, 5599 contentX + mNavSlop, contentY + mNavSlop); 5600 nativeSelectBestAt(rect); 5601 } 5602 5603 /** 5604 * Scroll the focused text field/area to match the WebTextView 5605 * @param xPercent New x position of the WebTextView from 0 to 1. 5606 * @param y New y position of the WebTextView in view coordinates 5607 */ 5608 /*package*/ void scrollFocusedTextInput(float xPercent, int y) { 5609 if (!inEditingMode() || mWebViewCore == null) { 5610 return; 5611 } 5612 mWebViewCore.sendMessage(EventHub.SCROLL_TEXT_INPUT, 5613 // Since this position is relative to the top of the text input 5614 // field, we do not need to take the title bar's height into 5615 // consideration. 5616 viewToContentDimension(y), 5617 new Float(xPercent)); 5618 } 5619 5620 /** 5621 * Set our starting point and time for a drag from the WebTextView. 5622 */ 5623 /*package*/ void initiateTextFieldDrag(float x, float y, long eventTime) { 5624 if (!inEditingMode()) { 5625 return; 5626 } 5627 mLastTouchX = x + (float) (mWebTextView.getLeft() - mScrollX); 5628 mLastTouchY = y + (float) (mWebTextView.getTop() - mScrollY); 5629 mLastTouchTime = eventTime; 5630 if (!mScroller.isFinished()) { 5631 abortAnimation(); 5632 mPrivateHandler.removeMessages(RESUME_WEBCORE_PRIORITY); 5633 } 5634 mSnapScrollMode = SNAP_NONE; 5635 mVelocityTracker = VelocityTracker.obtain(); 5636 mTouchMode = TOUCH_DRAG_START_MODE; 5637 } 5638 5639 /** 5640 * Given a motion event from the WebTextView, set its location to our 5641 * coordinates, and handle the event. 5642 */ 5643 /*package*/ boolean textFieldDrag(MotionEvent event) { 5644 if (!inEditingMode()) { 5645 return false; 5646 } 5647 mDragFromTextInput = true; 5648 event.offsetLocation((float) (mWebTextView.getLeft() - mScrollX), 5649 (float) (mWebTextView.getTop() - mScrollY)); 5650 boolean result = onTouchEvent(event); 5651 mDragFromTextInput = false; 5652 return result; 5653 } 5654 5655 /** 5656 * Due a touch up from a WebTextView. This will be handled by webkit to 5657 * change the selection. 5658 * @param event MotionEvent in the WebTextView's coordinates. 5659 */ 5660 /*package*/ void touchUpOnTextField(MotionEvent event) { 5661 if (!inEditingMode()) { 5662 return; 5663 } 5664 int x = viewToContentX((int) event.getX() + mWebTextView.getLeft()); 5665 int y = viewToContentY((int) event.getY() + mWebTextView.getTop()); 5666 nativeMotionUp(x, y, mNavSlop); 5667 } 5668 5669 /** 5670 * Called when pressing the center key or trackball on a textfield. 5671 */ 5672 /*package*/ void centerKeyPressOnTextField() { 5673 mWebViewCore.sendMessage(EventHub.CLICK, nativeCursorFramePointer(), 5674 nativeCursorNodePointer()); 5675 } 5676 5677 private void doShortPress() { 5678 if (mNativeClass == 0) { 5679 return; 5680 } 5681 if (mPreventDefault == PREVENT_DEFAULT_YES) { 5682 return; 5683 } 5684 mTouchMode = TOUCH_DONE_MODE; 5685 switchOutDrawHistory(); 5686 // mLastTouchX and mLastTouchY are the point in the current viewport 5687 int contentX = viewToContentX((int) mLastTouchX + mScrollX); 5688 int contentY = viewToContentY((int) mLastTouchY + mScrollY); 5689 if (getSettings().supportTouchOnly()) { 5690 removeTouchHighlight(false); 5691 WebViewCore.TouchUpData touchUpData = new WebViewCore.TouchUpData(); 5692 // use "0" as generation id to inform WebKit to use the same x/y as 5693 // it used when processing GET_TOUCH_HIGHLIGHT_RECTS 5694 touchUpData.mMoveGeneration = 0; 5695 mWebViewCore.sendMessage(EventHub.TOUCH_UP, touchUpData); 5696 } else if (nativePointInNavCache(contentX, contentY, mNavSlop)) { 5697 WebViewCore.MotionUpData motionUpData = new WebViewCore 5698 .MotionUpData(); 5699 motionUpData.mFrame = nativeCacheHitFramePointer(); 5700 motionUpData.mNode = nativeCacheHitNodePointer(); 5701 motionUpData.mBounds = nativeCacheHitNodeBounds(); 5702 motionUpData.mX = contentX; 5703 motionUpData.mY = contentY; 5704 mWebViewCore.sendMessageAtFrontOfQueue(EventHub.VALID_NODE_BOUNDS, 5705 motionUpData); 5706 } else { 5707 doMotionUp(contentX, contentY); 5708 } 5709 } 5710 5711 private void doMotionUp(int contentX, int contentY) { 5712 if (mLogEvent && nativeMotionUp(contentX, contentY, mNavSlop)) { 5713 EventLog.writeEvent(EventLogTags.BROWSER_SNAP_CENTER); 5714 } 5715 if (nativeHasCursorNode() && !nativeCursorIsTextInput()) { 5716 playSoundEffect(SoundEffectConstants.CLICK); 5717 } 5718 } 5719 5720 /* 5721 * Return true if the view (Plugin) is fully visible and maximized inside 5722 * the WebView. 5723 */ 5724 private boolean isPluginFitOnScreen(ViewManager.ChildView view) { 5725 int viewWidth = getViewWidth(); 5726 int viewHeight = getViewHeightWithTitle(); 5727 float scale = Math.min((float) viewWidth / view.width, 5728 (float) viewHeight / view.height); 5729 if (scale < mZoomManager.mMinZoomScale) { 5730 scale = mZoomManager.mMinZoomScale; 5731 } else if (scale > mZoomManager.mMaxZoomScale) { 5732 scale = mZoomManager.mMaxZoomScale; 5733 } 5734 if (!mZoomManager.willScaleTriggerZoom(scale)) { 5735 if (contentToViewX(view.x) >= mScrollX 5736 && contentToViewX(view.x + view.width) <= mScrollX 5737 + viewWidth 5738 && contentToViewY(view.y) >= mScrollY 5739 && contentToViewY(view.y + view.height) <= mScrollY 5740 + viewHeight) { 5741 return true; 5742 } 5743 } 5744 return false; 5745 } 5746 5747 /* 5748 * Maximize and center the rectangle, specified in the document coordinate 5749 * space, inside the WebView. If the zoom doesn't need to be changed, do an 5750 * animated scroll to center it. If the zoom needs to be changed, find the 5751 * zoom center and do a smooth zoom transition. 5752 */ 5753 private void centerFitRect(int docX, int docY, int docWidth, int docHeight) { 5754 int viewWidth = getViewWidth(); 5755 int viewHeight = getViewHeightWithTitle(); 5756 float scale = Math.min((float) viewWidth / docWidth, (float) viewHeight 5757 / docHeight); 5758 if (scale < mZoomManager.mMinZoomScale) { 5759 scale = mZoomManager.mMinZoomScale; 5760 } else if (scale > mZoomManager.mMaxZoomScale) { 5761 scale = mZoomManager.mMaxZoomScale; 5762 } 5763 if (!mZoomManager.willScaleTriggerZoom(scale)) { 5764 pinScrollTo(contentToViewX(docX + docWidth / 2) - viewWidth / 2, 5765 contentToViewY(docY + docHeight / 2) - viewHeight / 2, 5766 true, 0); 5767 } else { 5768 float actualScale = mZoomManager.mActualScale; 5769 float oldScreenX = docX * actualScale - mScrollX; 5770 float rectViewX = docX * scale; 5771 float rectViewWidth = docWidth * scale; 5772 float newMaxWidth = mContentWidth * scale; 5773 float newScreenX = (viewWidth - rectViewWidth) / 2; 5774 // pin the newX to the WebView 5775 if (newScreenX > rectViewX) { 5776 newScreenX = rectViewX; 5777 } else if (newScreenX > (newMaxWidth - rectViewX - rectViewWidth)) { 5778 newScreenX = viewWidth - (newMaxWidth - rectViewX); 5779 } 5780 float zoomCenterX = (oldScreenX * scale - newScreenX * actualScale) 5781 / (scale - actualScale); 5782 float oldScreenY = docY * actualScale + getTitleHeight() 5783 - mScrollY; 5784 float rectViewY = docY * scale + getTitleHeight(); 5785 float rectViewHeight = docHeight * scale; 5786 float newMaxHeight = mContentHeight * scale + getTitleHeight(); 5787 float newScreenY = (viewHeight - rectViewHeight) / 2; 5788 // pin the newY to the WebView 5789 if (newScreenY > rectViewY) { 5790 newScreenY = rectViewY; 5791 } else if (newScreenY > (newMaxHeight - rectViewY - rectViewHeight)) { 5792 newScreenY = viewHeight - (newMaxHeight - rectViewY); 5793 } 5794 float zoomCenterY = (oldScreenY * scale - newScreenY * actualScale) 5795 / (scale - actualScale); 5796 mZoomManager.setZoomCenter(zoomCenterX, zoomCenterY); 5797 mZoomManager.animateZoom(scale, false); 5798 } 5799 } 5800 5801 // Rule for double tap: 5802 // 1. if the current scale is not same as the text wrap scale and layout 5803 // algorithm is NARROW_COLUMNS, fit to column; 5804 // 2. if the current state is not overview mode, change to overview mode; 5805 // 3. if the current state is overview mode, change to default scale. 5806 private void doDoubleTap() { 5807 if (mWebViewCore.getSettings().getUseWideViewPort() == false) { 5808 return; 5809 } 5810 mZoomManager.setZoomCenter(mLastTouchX, mLastTouchY); 5811 mAnchorX = viewToContentX((int) mLastTouchX + mScrollX); 5812 mAnchorY = viewToContentY((int) mLastTouchX + mScrollY); 5813 WebSettings settings = getSettings(); 5814 settings.setDoubleTapToastCount(0); 5815 // remove the zoom control after double tap 5816 mZoomManager.dismissZoomPicker(); 5817 ViewManager.ChildView plugin = mViewManager.hitTest(mAnchorX, mAnchorY); 5818 if (plugin != null) { 5819 if (isPluginFitOnScreen(plugin)) { 5820 mZoomManager.zoomToOverview(); 5821 } else { 5822 mZoomManager.mInZoomOverview = false; 5823 centerFitRect(plugin.x, plugin.y, plugin.width, plugin.height); 5824 } 5825 return; 5826 } 5827 boolean zoomToDefault = false; 5828 if ((settings.getLayoutAlgorithm() == WebSettings.LayoutAlgorithm.NARROW_COLUMNS) 5829 && mZoomManager.willScaleTriggerZoom(mZoomManager.mTextWrapScale)) { 5830 mZoomManager.refreshZoomScale(true); 5831 float overviewScale = (float) getViewWidth() / mZoomManager.mZoomOverviewWidth; 5832 if (!mZoomManager.willScaleTriggerZoom(overviewScale)) { 5833 mZoomManager.mInZoomOverview = true; 5834 } 5835 } else if (!mZoomManager.mInZoomOverview) { 5836 float newScale = (float) getViewWidth() / mZoomManager.mZoomOverviewWidth; 5837 if (mZoomManager.willScaleTriggerZoom(newScale)) { 5838 mZoomManager.zoomToOverview(); 5839 } else if (mZoomManager.willScaleTriggerZoom(mZoomManager.mDefaultScale)) { 5840 zoomToDefault = true; 5841 } 5842 } else { 5843 zoomToDefault = true; 5844 } 5845 if (zoomToDefault) { 5846 int left = nativeGetBlockLeftEdge(mAnchorX, mAnchorY, mZoomManager.mActualScale); 5847 if (left != NO_LEFTEDGE) { 5848 // add a 5pt padding to the left edge. 5849 int viewLeft = contentToViewX(left < 5 ? 0 : (left - 5)) 5850 - mScrollX; 5851 // Re-calculate the zoom center so that the new scroll x will be 5852 // on the left edge. 5853 if (viewLeft > 0) { 5854 mZoomManager.mZoomCenterX = viewLeft * mZoomManager.mDefaultScale 5855 / (mZoomManager.mDefaultScale - mZoomManager.mActualScale); 5856 } else { 5857 scrollBy(viewLeft, 0); 5858 mZoomManager.mZoomCenterX = 0; 5859 } 5860 } 5861 mZoomManager.zoomToDefaultLevel(true); 5862 } 5863 } 5864 5865 // Called by JNI to handle a touch on a node representing an email address, 5866 // address, or phone number 5867 private void overrideLoading(String url) { 5868 mCallbackProxy.uiOverrideUrlLoading(url); 5869 } 5870 5871 @Override 5872 public boolean requestFocus(int direction, Rect previouslyFocusedRect) { 5873 // FIXME: If a subwindow is showing find, and the user touches the 5874 // background window, it can steal focus. 5875 if (mFindIsUp) return false; 5876 boolean result = false; 5877 if (inEditingMode()) { 5878 result = mWebTextView.requestFocus(direction, 5879 previouslyFocusedRect); 5880 } else { 5881 result = super.requestFocus(direction, previouslyFocusedRect); 5882 if (mWebViewCore.getSettings().getNeedInitialFocus()) { 5883 // For cases such as GMail, where we gain focus from a direction, 5884 // we want to move to the first available link. 5885 // FIXME: If there are no visible links, we may not want to 5886 int fakeKeyDirection = 0; 5887 switch(direction) { 5888 case View.FOCUS_UP: 5889 fakeKeyDirection = KeyEvent.KEYCODE_DPAD_UP; 5890 break; 5891 case View.FOCUS_DOWN: 5892 fakeKeyDirection = KeyEvent.KEYCODE_DPAD_DOWN; 5893 break; 5894 case View.FOCUS_LEFT: 5895 fakeKeyDirection = KeyEvent.KEYCODE_DPAD_LEFT; 5896 break; 5897 case View.FOCUS_RIGHT: 5898 fakeKeyDirection = KeyEvent.KEYCODE_DPAD_RIGHT; 5899 break; 5900 default: 5901 return result; 5902 } 5903 if (mNativeClass != 0 && !nativeHasCursorNode()) { 5904 navHandledKey(fakeKeyDirection, 1, true, 0); 5905 } 5906 } 5907 } 5908 return result; 5909 } 5910 5911 @Override 5912 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 5913 super.onMeasure(widthMeasureSpec, heightMeasureSpec); 5914 5915 int heightMode = MeasureSpec.getMode(heightMeasureSpec); 5916 int heightSize = MeasureSpec.getSize(heightMeasureSpec); 5917 int widthMode = MeasureSpec.getMode(widthMeasureSpec); 5918 int widthSize = MeasureSpec.getSize(widthMeasureSpec); 5919 5920 int measuredHeight = heightSize; 5921 int measuredWidth = widthSize; 5922 5923 // Grab the content size from WebViewCore. 5924 int contentHeight = contentToViewDimension(mContentHeight); 5925 int contentWidth = contentToViewDimension(mContentWidth); 5926 5927// Log.d(LOGTAG, "------- measure " + heightMode); 5928 5929 if (heightMode != MeasureSpec.EXACTLY) { 5930 mHeightCanMeasure = true; 5931 measuredHeight = contentHeight; 5932 if (heightMode == MeasureSpec.AT_MOST) { 5933 // If we are larger than the AT_MOST height, then our height can 5934 // no longer be measured and we should scroll internally. 5935 if (measuredHeight > heightSize) { 5936 measuredHeight = heightSize; 5937 mHeightCanMeasure = false; 5938 } 5939 } 5940 } else { 5941 mHeightCanMeasure = false; 5942 } 5943 if (mNativeClass != 0) { 5944 nativeSetHeightCanMeasure(mHeightCanMeasure); 5945 } 5946 // For the width, always use the given size unless unspecified. 5947 if (widthMode == MeasureSpec.UNSPECIFIED) { 5948 mWidthCanMeasure = true; 5949 measuredWidth = contentWidth; 5950 } else { 5951 mWidthCanMeasure = false; 5952 } 5953 5954 synchronized (this) { 5955 setMeasuredDimension(measuredWidth, measuredHeight); 5956 } 5957 } 5958 5959 @Override 5960 public boolean requestChildRectangleOnScreen(View child, 5961 Rect rect, 5962 boolean immediate) { 5963 // don't scroll while in zoom animation. When it is done, we will adjust 5964 // the necessary components (e.g., WebTextView if it is in editing mode) 5965 if(mZoomManager.isZoomAnimating()) { 5966 return false; 5967 } 5968 5969 rect.offset(child.getLeft() - child.getScrollX(), 5970 child.getTop() - child.getScrollY()); 5971 5972 Rect content = new Rect(viewToContentX(mScrollX), 5973 viewToContentY(mScrollY), 5974 viewToContentX(mScrollX + getWidth() 5975 - getVerticalScrollbarWidth()), 5976 viewToContentY(mScrollY + getViewHeightWithTitle())); 5977 content = nativeSubtractLayers(content); 5978 int screenTop = contentToViewY(content.top); 5979 int screenBottom = contentToViewY(content.bottom); 5980 int height = screenBottom - screenTop; 5981 int scrollYDelta = 0; 5982 5983 if (rect.bottom > screenBottom) { 5984 int oneThirdOfScreenHeight = height / 3; 5985 if (rect.height() > 2 * oneThirdOfScreenHeight) { 5986 // If the rectangle is too tall to fit in the bottom two thirds 5987 // of the screen, place it at the top. 5988 scrollYDelta = rect.top - screenTop; 5989 } else { 5990 // If the rectangle will still fit on screen, we want its 5991 // top to be in the top third of the screen. 5992 scrollYDelta = rect.top - (screenTop + oneThirdOfScreenHeight); 5993 } 5994 } else if (rect.top < screenTop) { 5995 scrollYDelta = rect.top - screenTop; 5996 } 5997 5998 int screenLeft = contentToViewX(content.left); 5999 int screenRight = contentToViewX(content.right); 6000 int width = screenRight - screenLeft; 6001 int scrollXDelta = 0; 6002 6003 if (rect.right > screenRight && rect.left > screenLeft) { 6004 if (rect.width() > width) { 6005 scrollXDelta += (rect.left - screenLeft); 6006 } else { 6007 scrollXDelta += (rect.right - screenRight); 6008 } 6009 } else if (rect.left < screenLeft) { 6010 scrollXDelta -= (screenLeft - rect.left); 6011 } 6012 6013 if ((scrollYDelta | scrollXDelta) != 0) { 6014 return pinScrollBy(scrollXDelta, scrollYDelta, !immediate, 0); 6015 } 6016 6017 return false; 6018 } 6019 6020 /* package */ void replaceTextfieldText(int oldStart, int oldEnd, 6021 String replace, int newStart, int newEnd) { 6022 WebViewCore.ReplaceTextData arg = new WebViewCore.ReplaceTextData(); 6023 arg.mReplace = replace; 6024 arg.mNewStart = newStart; 6025 arg.mNewEnd = newEnd; 6026 mTextGeneration++; 6027 arg.mTextGeneration = mTextGeneration; 6028 mWebViewCore.sendMessage(EventHub.REPLACE_TEXT, oldStart, oldEnd, arg); 6029 } 6030 6031 /* package */ void passToJavaScript(String currentText, KeyEvent event) { 6032 WebViewCore.JSKeyData arg = new WebViewCore.JSKeyData(); 6033 arg.mEvent = event; 6034 arg.mCurrentText = currentText; 6035 // Increase our text generation number, and pass it to webcore thread 6036 mTextGeneration++; 6037 mWebViewCore.sendMessage(EventHub.PASS_TO_JS, mTextGeneration, 0, arg); 6038 // WebKit's document state is not saved until about to leave the page. 6039 // To make sure the host application, like Browser, has the up to date 6040 // document state when it goes to background, we force to save the 6041 // document state. 6042 mWebViewCore.removeMessages(EventHub.SAVE_DOCUMENT_STATE); 6043 mWebViewCore.sendMessageDelayed(EventHub.SAVE_DOCUMENT_STATE, 6044 cursorData(), 1000); 6045 } 6046 6047 /* package */ synchronized WebViewCore getWebViewCore() { 6048 return mWebViewCore; 6049 } 6050 6051 //------------------------------------------------------------------------- 6052 // Methods can be called from a separate thread, like WebViewCore 6053 // If it needs to call the View system, it has to send message. 6054 //------------------------------------------------------------------------- 6055 6056 /** 6057 * General handler to receive message coming from webkit thread 6058 */ 6059 class PrivateHandler extends Handler { 6060 @Override 6061 public void handleMessage(Message msg) { 6062 // exclude INVAL_RECT_MSG_ID since it is frequently output 6063 if (DebugFlags.WEB_VIEW && msg.what != INVAL_RECT_MSG_ID) { 6064 if (msg.what >= FIRST_PRIVATE_MSG_ID 6065 && msg.what <= LAST_PRIVATE_MSG_ID) { 6066 Log.v(LOGTAG, HandlerPrivateDebugString[msg.what 6067 - FIRST_PRIVATE_MSG_ID]); 6068 } else if (msg.what >= FIRST_PACKAGE_MSG_ID 6069 && msg.what <= LAST_PACKAGE_MSG_ID) { 6070 Log.v(LOGTAG, HandlerPackageDebugString[msg.what 6071 - FIRST_PACKAGE_MSG_ID]); 6072 } else { 6073 Log.v(LOGTAG, Integer.toString(msg.what)); 6074 } 6075 } 6076 if (mWebViewCore == null) { 6077 // after WebView's destroy() is called, skip handling messages. 6078 return; 6079 } 6080 switch (msg.what) { 6081 case REMEMBER_PASSWORD: { 6082 mDatabase.setUsernamePassword( 6083 msg.getData().getString("host"), 6084 msg.getData().getString("username"), 6085 msg.getData().getString("password")); 6086 ((Message) msg.obj).sendToTarget(); 6087 break; 6088 } 6089 case NEVER_REMEMBER_PASSWORD: { 6090 mDatabase.setUsernamePassword( 6091 msg.getData().getString("host"), null, null); 6092 ((Message) msg.obj).sendToTarget(); 6093 break; 6094 } 6095 case PREVENT_DEFAULT_TIMEOUT: { 6096 // if timeout happens, cancel it so that it won't block UI 6097 // to continue handling touch events 6098 if ((msg.arg1 == MotionEvent.ACTION_DOWN 6099 && mPreventDefault == PREVENT_DEFAULT_MAYBE_YES) 6100 || (msg.arg1 == MotionEvent.ACTION_MOVE 6101 && mPreventDefault == PREVENT_DEFAULT_NO_FROM_TOUCH_DOWN)) { 6102 cancelWebCoreTouchEvent( 6103 viewToContentX((int) mLastTouchX + mScrollX), 6104 viewToContentY((int) mLastTouchY + mScrollY), 6105 true); 6106 } 6107 break; 6108 } 6109 case SWITCH_TO_SHORTPRESS: { 6110 if (mTouchMode == TOUCH_INIT_MODE) { 6111 if (!getSettings().supportTouchOnly() 6112 && mPreventDefault != PREVENT_DEFAULT_YES) { 6113 mTouchMode = TOUCH_SHORTPRESS_START_MODE; 6114 updateSelection(); 6115 } else { 6116 // set to TOUCH_SHORTPRESS_MODE so that it won't 6117 // trigger double tap any more 6118 mTouchMode = TOUCH_SHORTPRESS_MODE; 6119 } 6120 } else if (mTouchMode == TOUCH_DOUBLE_TAP_MODE) { 6121 mTouchMode = TOUCH_DONE_MODE; 6122 } 6123 break; 6124 } 6125 case SWITCH_TO_LONGPRESS: { 6126 if (getSettings().supportTouchOnly()) { 6127 removeTouchHighlight(false); 6128 } 6129 if (inFullScreenMode() || mDeferTouchProcess) { 6130 TouchEventData ted = new TouchEventData(); 6131 ted.mAction = WebViewCore.ACTION_LONGPRESS; 6132 ted.mX = viewToContentX((int) mLastTouchX + mScrollX); 6133 ted.mY = viewToContentY((int) mLastTouchY + mScrollY); 6134 // metaState for long press is tricky. Should it be the 6135 // state when the press started or when the press was 6136 // released? Or some intermediary key state? For 6137 // simplicity for now, we don't set it. 6138 ted.mMetaState = 0; 6139 ted.mReprocess = mDeferTouchProcess; 6140 mWebViewCore.sendMessage(EventHub.TOUCH_EVENT, ted); 6141 } else if (mPreventDefault != PREVENT_DEFAULT_YES) { 6142 mTouchMode = TOUCH_DONE_MODE; 6143 performLongClick(); 6144 } 6145 break; 6146 } 6147 case RELEASE_SINGLE_TAP: { 6148 doShortPress(); 6149 break; 6150 } 6151 case SCROLL_BY_MSG_ID: 6152 setContentScrollBy(msg.arg1, msg.arg2, (Boolean) msg.obj); 6153 break; 6154 case SYNC_SCROLL_TO_MSG_ID: 6155 if (mUserScroll) { 6156 // if user has scrolled explicitly, don't sync the 6157 // scroll position any more 6158 mUserScroll = false; 6159 break; 6160 } 6161 // fall through 6162 case SCROLL_TO_MSG_ID: 6163 if (setContentScrollTo(msg.arg1, msg.arg2)) { 6164 // if we can't scroll to the exact position due to pin, 6165 // send a message to WebCore to re-scroll when we get a 6166 // new picture 6167 mUserScroll = false; 6168 mWebViewCore.sendMessage(EventHub.SYNC_SCROLL, 6169 msg.arg1, msg.arg2); 6170 } 6171 break; 6172 case SPAWN_SCROLL_TO_MSG_ID: 6173 spawnContentScrollTo(msg.arg1, msg.arg2); 6174 break; 6175 case UPDATE_ZOOM_RANGE: { 6176 WebViewCore.RestoreState restoreState 6177 = (WebViewCore.RestoreState) msg.obj; 6178 // mScrollX contains the new minPrefWidth 6179 updateZoomRange(restoreState, getViewWidth(), 6180 restoreState.mScrollX, false); 6181 break; 6182 } 6183 case NEW_PICTURE_MSG_ID: { 6184 // If we've previously delayed deleting a root 6185 // layer, do it now. 6186 if (mDelayedDeleteRootLayer) { 6187 mDelayedDeleteRootLayer = false; 6188 nativeSetRootLayer(0); 6189 } 6190 WebSettings settings = mWebViewCore.getSettings(); 6191 // called for new content 6192 final int viewWidth = getViewWidth(); 6193 final WebViewCore.DrawData draw = 6194 (WebViewCore.DrawData) msg.obj; 6195 final Point viewSize = draw.mViewPoint; 6196 boolean useWideViewport = settings.getUseWideViewPort(); 6197 WebViewCore.RestoreState restoreState = draw.mRestoreState; 6198 boolean hasRestoreState = restoreState != null; 6199 if (hasRestoreState) { 6200 updateZoomRange(restoreState, viewSize.x, 6201 draw.mMinPrefWidth, true); 6202 if (!mDrawHistory) { 6203 mZoomManager.mInZoomOverview = false; 6204 6205 if (mInitialScaleInPercent > 0) { 6206 final float initialScale = mInitialScaleInPercent / 100.0f; 6207 final boolean reflowText = 6208 mInitialScaleInPercent != mZoomManager.mTextWrapScale * 100; 6209 mZoomManager.setZoomScale(initialScale, reflowText); 6210 } else if (restoreState.mViewScale > 0) { 6211 mZoomManager.mTextWrapScale = restoreState.mTextWrapScale; 6212 mZoomManager.setZoomScale(restoreState.mViewScale, false); 6213 } else { 6214 mZoomManager.mInZoomOverview = useWideViewport 6215 && settings.getLoadWithOverviewMode(); 6216 float scale; 6217 if (mZoomManager.mInZoomOverview) { 6218 scale = (float) viewWidth 6219 / DEFAULT_VIEWPORT_WIDTH; 6220 } else { 6221 scale = restoreState.mTextWrapScale; 6222 } 6223 mZoomManager.setZoomScale(scale, 6224 ZoomManager.exceedsMinScaleIncrement( 6225 mZoomManager.mTextWrapScale, scale)); 6226 } 6227 setContentScrollTo(restoreState.mScrollX, 6228 restoreState.mScrollY); 6229 // As we are on a new page, remove the WebTextView. This 6230 // is necessary for page loads driven by webkit, and in 6231 // particular when the user was on a password field, so 6232 // the WebTextView was visible. 6233 clearTextEntry(false); 6234 // update the zoom buttons as the scale can be changed 6235 mZoomManager.updateZoomPicker(); 6236 } 6237 } 6238 // We update the layout (i.e. request a layout from the 6239 // view system) if the last view size that we sent to 6240 // WebCore matches the view size of the picture we just 6241 // received in the fixed dimension. 6242 final boolean updateLayout = viewSize.x == mLastWidthSent 6243 && viewSize.y == mLastHeightSent; 6244 recordNewContentSize(draw.mWidthHeight.x, 6245 draw.mWidthHeight.y, updateLayout); 6246 if (DebugFlags.WEB_VIEW) { 6247 Rect b = draw.mInvalRegion.getBounds(); 6248 Log.v(LOGTAG, "NEW_PICTURE_MSG_ID {" + 6249 b.left+","+b.top+","+b.right+","+b.bottom+"}"); 6250 } 6251 invalidateContentRect(draw.mInvalRegion.getBounds()); 6252 if (mPictureListener != null) { 6253 mPictureListener.onNewPicture(WebView.this, capturePicture()); 6254 } 6255 if (useWideViewport) { 6256 // limit mZoomOverviewWidth upper bound to 6257 // sMaxViewportWidth so that if the page doesn't behave 6258 // well, the WebView won't go insane. limit the lower 6259 // bound to match the default scale for mobile sites. 6260 mZoomManager.mZoomOverviewWidth = Math.min(sMaxViewportWidth, Math 6261 .max((int) (viewWidth / mZoomManager.mDefaultScale), 6262 Math.max(draw.mMinPrefWidth, 6263 draw.mViewPoint.x))); 6264 } 6265 if (!mZoomManager.mMinZoomScaleFixed) { 6266 mZoomManager.mMinZoomScale = (float) viewWidth / 6267 mZoomManager.mZoomOverviewWidth; 6268 } 6269 if (!mDrawHistory && mZoomManager.mInZoomOverview) { 6270 // fit the content width to the current view. Ignore 6271 // the rounding error case. 6272 if (Math.abs((viewWidth * mZoomManager.mInvActualScale) 6273 - mZoomManager.mZoomOverviewWidth) > 1) { 6274 mZoomManager.setZoomScale( 6275 (float) viewWidth / mZoomManager.mZoomOverviewWidth, 6276 !mZoomManager.willScaleTriggerZoom(mZoomManager.mTextWrapScale)); 6277 } 6278 } 6279 if (draw.mFocusSizeChanged && inEditingMode()) { 6280 mFocusSizeChanged = true; 6281 } 6282 if (hasRestoreState) { 6283 mViewManager.postReadyToDrawAll(); 6284 } 6285 break; 6286 } 6287 case WEBCORE_INITIALIZED_MSG_ID: 6288 // nativeCreate sets mNativeClass to a non-zero value 6289 nativeCreate(msg.arg1); 6290 break; 6291 case UPDATE_TEXTFIELD_TEXT_MSG_ID: 6292 // Make sure that the textfield is currently focused 6293 // and representing the same node as the pointer. 6294 if (inEditingMode() && 6295 mWebTextView.isSameTextField(msg.arg1)) { 6296 if (msg.getData().getBoolean("password")) { 6297 Spannable text = (Spannable) mWebTextView.getText(); 6298 int start = Selection.getSelectionStart(text); 6299 int end = Selection.getSelectionEnd(text); 6300 mWebTextView.setInPassword(true); 6301 // Restore the selection, which may have been 6302 // ruined by setInPassword. 6303 Spannable pword = 6304 (Spannable) mWebTextView.getText(); 6305 Selection.setSelection(pword, start, end); 6306 // If the text entry has created more events, ignore 6307 // this one. 6308 } else if (msg.arg2 == mTextGeneration) { 6309 mWebTextView.setTextAndKeepSelection( 6310 (String) msg.obj); 6311 } 6312 } 6313 break; 6314 case REQUEST_KEYBOARD_WITH_SELECTION_MSG_ID: 6315 displaySoftKeyboard(true); 6316 // fall through to UPDATE_TEXT_SELECTION_MSG_ID 6317 case UPDATE_TEXT_SELECTION_MSG_ID: 6318 updateTextSelectionFromMessage(msg.arg1, msg.arg2, 6319 (WebViewCore.TextSelectionData) msg.obj); 6320 break; 6321 case RETURN_LABEL: 6322 if (inEditingMode() 6323 && mWebTextView.isSameTextField(msg.arg1)) { 6324 mWebTextView.setHint((String) msg.obj); 6325 InputMethodManager imm 6326 = InputMethodManager.peekInstance(); 6327 // The hint is propagated to the IME in 6328 // onCreateInputConnection. If the IME is already 6329 // active, restart it so that its hint text is updated. 6330 if (imm != null && imm.isActive(mWebTextView)) { 6331 imm.restartInput(mWebTextView); 6332 } 6333 } 6334 break; 6335 case UNHANDLED_NAV_KEY: 6336 navHandledKey(msg.arg1, 1, false, 0); 6337 break; 6338 case UPDATE_TEXT_ENTRY_MSG_ID: 6339 // this is sent after finishing resize in WebViewCore. Make 6340 // sure the text edit box is still on the screen. 6341 if (inEditingMode() && nativeCursorIsTextInput()) { 6342 mWebTextView.bringIntoView(); 6343 rebuildWebTextView(); 6344 } 6345 break; 6346 case CLEAR_TEXT_ENTRY: 6347 clearTextEntry(false); 6348 break; 6349 case INVAL_RECT_MSG_ID: { 6350 Rect r = (Rect)msg.obj; 6351 if (r == null) { 6352 invalidate(); 6353 } else { 6354 // we need to scale r from content into view coords, 6355 // which viewInvalidate() does for us 6356 viewInvalidate(r.left, r.top, r.right, r.bottom); 6357 } 6358 break; 6359 } 6360 case IMMEDIATE_REPAINT_MSG_ID: { 6361 invalidate(); 6362 break; 6363 } 6364 case SET_ROOT_LAYER_MSG_ID: { 6365 if (0 == msg.arg1) { 6366 // Null indicates deleting the old layer, but 6367 // don't actually do so until we've got the 6368 // new page to display. 6369 mDelayedDeleteRootLayer = true; 6370 } else { 6371 mDelayedDeleteRootLayer = false; 6372 nativeSetRootLayer(msg.arg1); 6373 invalidate(); 6374 } 6375 break; 6376 } 6377 case REQUEST_FORM_DATA: 6378 AutoCompleteAdapter adapter = (AutoCompleteAdapter) msg.obj; 6379 if (mWebTextView.isSameTextField(msg.arg1)) { 6380 mWebTextView.setAdapterCustom(adapter); 6381 } 6382 break; 6383 case RESUME_WEBCORE_PRIORITY: 6384 WebViewCore.resumePriority(); 6385 WebViewCore.resumeUpdatePicture(mWebViewCore); 6386 break; 6387 6388 case LONG_PRESS_CENTER: 6389 // as this is shared by keydown and trackballdown, reset all 6390 // the states 6391 mGotCenterDown = false; 6392 mTrackballDown = false; 6393 performLongClick(); 6394 break; 6395 6396 case WEBCORE_NEED_TOUCH_EVENTS: 6397 mForwardTouchEvents = (msg.arg1 != 0); 6398 break; 6399 6400 case PREVENT_TOUCH_ID: 6401 if (inFullScreenMode()) { 6402 break; 6403 } 6404 if (msg.obj == null) { 6405 if (msg.arg1 == MotionEvent.ACTION_DOWN 6406 && mPreventDefault == PREVENT_DEFAULT_MAYBE_YES) { 6407 // if prevent default is called from WebCore, UI 6408 // will not handle the rest of the touch events any 6409 // more. 6410 mPreventDefault = msg.arg2 == 1 ? PREVENT_DEFAULT_YES 6411 : PREVENT_DEFAULT_NO_FROM_TOUCH_DOWN; 6412 } else if (msg.arg1 == MotionEvent.ACTION_MOVE 6413 && mPreventDefault == PREVENT_DEFAULT_NO_FROM_TOUCH_DOWN) { 6414 // the return for the first ACTION_MOVE will decide 6415 // whether UI will handle touch or not. Currently no 6416 // support for alternating prevent default 6417 mPreventDefault = msg.arg2 == 1 ? PREVENT_DEFAULT_YES 6418 : PREVENT_DEFAULT_NO; 6419 } 6420 if (mPreventDefault == PREVENT_DEFAULT_YES) { 6421 mTouchHighlightRegion.setEmpty(); 6422 } 6423 } else if (msg.arg2 == 0) { 6424 // prevent default is not called in WebCore, so the 6425 // message needs to be reprocessed in UI 6426 TouchEventData ted = (TouchEventData) msg.obj; 6427 switch (ted.mAction) { 6428 case MotionEvent.ACTION_DOWN: 6429 mLastDeferTouchX = contentToViewX(ted.mX) 6430 - mScrollX; 6431 mLastDeferTouchY = contentToViewY(ted.mY) 6432 - mScrollY; 6433 mDeferTouchMode = TOUCH_INIT_MODE; 6434 break; 6435 case MotionEvent.ACTION_MOVE: { 6436 // no snapping in defer process 6437 int x = contentToViewX(ted.mX) - mScrollX; 6438 int y = contentToViewY(ted.mY) - mScrollY; 6439 if (mDeferTouchMode != TOUCH_DRAG_MODE) { 6440 mDeferTouchMode = TOUCH_DRAG_MODE; 6441 mLastDeferTouchX = x; 6442 mLastDeferTouchY = y; 6443 startDrag(); 6444 } 6445 int deltaX = pinLocX((int) (mScrollX 6446 + mLastDeferTouchX - x)) 6447 - mScrollX; 6448 int deltaY = pinLocY((int) (mScrollY 6449 + mLastDeferTouchY - y)) 6450 - mScrollY; 6451 doDrag(deltaX, deltaY); 6452 if (deltaX != 0) mLastDeferTouchX = x; 6453 if (deltaY != 0) mLastDeferTouchY = y; 6454 break; 6455 } 6456 case MotionEvent.ACTION_UP: 6457 case MotionEvent.ACTION_CANCEL: 6458 if (mDeferTouchMode == TOUCH_DRAG_MODE) { 6459 // no fling in defer process 6460 WebViewCore.resumePriority(); 6461 WebViewCore.resumeUpdatePicture(mWebViewCore); 6462 } 6463 mDeferTouchMode = TOUCH_DONE_MODE; 6464 break; 6465 case WebViewCore.ACTION_DOUBLETAP: 6466 // doDoubleTap() needs mLastTouchX/Y as anchor 6467 mLastTouchX = contentToViewX(ted.mX) - mScrollX; 6468 mLastTouchY = contentToViewY(ted.mY) - mScrollY; 6469 doDoubleTap(); 6470 mDeferTouchMode = TOUCH_DONE_MODE; 6471 break; 6472 case WebViewCore.ACTION_LONGPRESS: 6473 HitTestResult hitTest = getHitTestResult(); 6474 if (hitTest != null && hitTest.mType 6475 != HitTestResult.UNKNOWN_TYPE) { 6476 performLongClick(); 6477 } 6478 mDeferTouchMode = TOUCH_DONE_MODE; 6479 break; 6480 } 6481 } 6482 break; 6483 6484 case REQUEST_KEYBOARD: 6485 if (msg.arg1 == 0) { 6486 hideSoftKeyboard(); 6487 } else { 6488 displaySoftKeyboard(false); 6489 } 6490 break; 6491 6492 case FIND_AGAIN: 6493 // Ignore if find has been dismissed. 6494 if (mFindIsUp) { 6495 findAll(mLastFind); 6496 } 6497 break; 6498 6499 case DRAG_HELD_MOTIONLESS: 6500 mHeldMotionless = MOTIONLESS_TRUE; 6501 invalidate(); 6502 // fall through to keep scrollbars awake 6503 6504 case AWAKEN_SCROLL_BARS: 6505 if (mTouchMode == TOUCH_DRAG_MODE 6506 && mHeldMotionless == MOTIONLESS_TRUE) { 6507 awakenScrollBars(ViewConfiguration 6508 .getScrollDefaultDelay(), false); 6509 mPrivateHandler.sendMessageDelayed(mPrivateHandler 6510 .obtainMessage(AWAKEN_SCROLL_BARS), 6511 ViewConfiguration.getScrollDefaultDelay()); 6512 } 6513 break; 6514 6515 case DO_MOTION_UP: 6516 doMotionUp(msg.arg1, msg.arg2); 6517 break; 6518 6519 case SHOW_FULLSCREEN: { 6520 View view = (View) msg.obj; 6521 int npp = msg.arg1; 6522 6523 if (mFullScreenHolder != null) { 6524 Log.w(LOGTAG, "Should not have another full screen."); 6525 mFullScreenHolder.dismiss(); 6526 } 6527 mFullScreenHolder = new PluginFullScreenHolder(WebView.this, npp); 6528 mFullScreenHolder.setContentView(view); 6529 mFullScreenHolder.setCancelable(false); 6530 mFullScreenHolder.setCanceledOnTouchOutside(false); 6531 mFullScreenHolder.show(); 6532 6533 break; 6534 } 6535 case HIDE_FULLSCREEN: 6536 if (inFullScreenMode()) { 6537 mFullScreenHolder.dismiss(); 6538 mFullScreenHolder = null; 6539 } 6540 break; 6541 6542 case DOM_FOCUS_CHANGED: 6543 if (inEditingMode()) { 6544 nativeClearCursor(); 6545 rebuildWebTextView(); 6546 } 6547 break; 6548 6549 case SHOW_RECT_MSG_ID: { 6550 WebViewCore.ShowRectData data = (WebViewCore.ShowRectData) msg.obj; 6551 int x = mScrollX; 6552 int left = contentToViewX(data.mLeft); 6553 int width = contentToViewDimension(data.mWidth); 6554 int maxWidth = contentToViewDimension(data.mContentWidth); 6555 int viewWidth = getViewWidth(); 6556 if (width < viewWidth) { 6557 // center align 6558 x += left + width / 2 - mScrollX - viewWidth / 2; 6559 } else { 6560 x += (int) (left + data.mXPercentInDoc * width 6561 - mScrollX - data.mXPercentInView * viewWidth); 6562 } 6563 if (DebugFlags.WEB_VIEW) { 6564 Log.v(LOGTAG, "showRectMsg=(left=" + left + ",width=" + 6565 width + ",maxWidth=" + maxWidth + 6566 ",viewWidth=" + viewWidth + ",x=" 6567 + x + ",xPercentInDoc=" + data.mXPercentInDoc + 6568 ",xPercentInView=" + data.mXPercentInView+ ")"); 6569 } 6570 // use the passing content width to cap x as the current 6571 // mContentWidth may not be updated yet 6572 x = Math.max(0, 6573 (Math.min(maxWidth, x + viewWidth)) - viewWidth); 6574 int top = contentToViewY(data.mTop); 6575 int height = contentToViewDimension(data.mHeight); 6576 int maxHeight = contentToViewDimension(data.mContentHeight); 6577 int viewHeight = getViewHeight(); 6578 int y = (int) (top + data.mYPercentInDoc * height - 6579 data.mYPercentInView * viewHeight); 6580 if (DebugFlags.WEB_VIEW) { 6581 Log.v(LOGTAG, "showRectMsg=(top=" + top + ",height=" + 6582 height + ",maxHeight=" + maxHeight + 6583 ",viewHeight=" + viewHeight + ",y=" 6584 + y + ",yPercentInDoc=" + data.mYPercentInDoc + 6585 ",yPercentInView=" + data.mYPercentInView+ ")"); 6586 } 6587 // use the passing content height to cap y as the current 6588 // mContentHeight may not be updated yet 6589 y = Math.max(0, 6590 (Math.min(maxHeight, y + viewHeight) - viewHeight)); 6591 // We need to take into account the visible title height 6592 // when scrolling since y is an absolute view position. 6593 y = Math.max(0, y - getVisibleTitleHeight()); 6594 scrollTo(x, y); 6595 } 6596 break; 6597 6598 case CENTER_FIT_RECT: 6599 Rect r = (Rect)msg.obj; 6600 mZoomManager.mInZoomOverview = false; 6601 centerFitRect(r.left, r.top, r.width(), r.height()); 6602 break; 6603 6604 case SET_SCROLLBAR_MODES: 6605 mHorizontalScrollBarMode = msg.arg1; 6606 mVerticalScrollBarMode = msg.arg2; 6607 break; 6608 6609 case SELECTION_STRING_CHANGED: 6610 if (mAccessibilityInjector != null) { 6611 String selectionString = (String) msg.obj; 6612 mAccessibilityInjector.onSelectionStringChange(selectionString); 6613 } 6614 break; 6615 6616 case SET_TOUCH_HIGHLIGHT_RECTS: 6617 invalidate(mTouchHighlightRegion.getBounds()); 6618 mTouchHighlightRegion.setEmpty(); 6619 if (msg.obj != null) { 6620 ArrayList<Rect> rects = (ArrayList<Rect>) msg.obj; 6621 for (Rect rect : rects) { 6622 Rect viewRect = contentToViewRect(rect); 6623 // some sites, like stories in nytimes.com, set 6624 // mouse event handler in the top div. It is not 6625 // user friendly to highlight the div if it covers 6626 // more than half of the screen. 6627 if (viewRect.width() < getWidth() >> 1 6628 || viewRect.height() < getHeight() >> 1) { 6629 mTouchHighlightRegion.union(viewRect); 6630 invalidate(viewRect); 6631 } else { 6632 Log.w(LOGTAG, "Skip the huge selection rect:" 6633 + viewRect); 6634 } 6635 } 6636 } 6637 break; 6638 6639 default: 6640 super.handleMessage(msg); 6641 break; 6642 } 6643 } 6644 } 6645 6646 /** 6647 * Used when receiving messages for REQUEST_KEYBOARD_WITH_SELECTION_MSG_ID 6648 * and UPDATE_TEXT_SELECTION_MSG_ID. Update the selection of WebTextView. 6649 */ 6650 private void updateTextSelectionFromMessage(int nodePointer, 6651 int textGeneration, WebViewCore.TextSelectionData data) { 6652 if (inEditingMode() 6653 && mWebTextView.isSameTextField(nodePointer) 6654 && textGeneration == mTextGeneration) { 6655 mWebTextView.setSelectionFromWebKit(data.mStart, data.mEnd); 6656 } 6657 } 6658 6659 // Class used to use a dropdown for a <select> element 6660 private class InvokeListBox implements Runnable { 6661 // Whether the listbox allows multiple selection. 6662 private boolean mMultiple; 6663 // Passed in to a list with multiple selection to tell 6664 // which items are selected. 6665 private int[] mSelectedArray; 6666 // Passed in to a list with single selection to tell 6667 // where the initial selection is. 6668 private int mSelection; 6669 6670 private Container[] mContainers; 6671 6672 // Need these to provide stable ids to my ArrayAdapter, 6673 // which normally does not have stable ids. (Bug 1250098) 6674 private class Container extends Object { 6675 /** 6676 * Possible values for mEnabled. Keep in sync with OptionStatus in 6677 * WebViewCore.cpp 6678 */ 6679 final static int OPTGROUP = -1; 6680 final static int OPTION_DISABLED = 0; 6681 final static int OPTION_ENABLED = 1; 6682 6683 String mString; 6684 int mEnabled; 6685 int mId; 6686 6687 public String toString() { 6688 return mString; 6689 } 6690 } 6691 6692 /** 6693 * Subclass ArrayAdapter so we can disable OptionGroupLabels, 6694 * and allow filtering. 6695 */ 6696 private class MyArrayListAdapter extends ArrayAdapter<Container> { 6697 public MyArrayListAdapter(Context context, Container[] objects, boolean multiple) { 6698 super(context, 6699 multiple ? com.android.internal.R.layout.select_dialog_multichoice : 6700 com.android.internal.R.layout.select_dialog_singlechoice, 6701 objects); 6702 } 6703 6704 @Override 6705 public View getView(int position, View convertView, 6706 ViewGroup parent) { 6707 // Always pass in null so that we will get a new CheckedTextView 6708 // Otherwise, an item which was previously used as an <optgroup> 6709 // element (i.e. has no check), could get used as an <option> 6710 // element, which needs a checkbox/radio, but it would not have 6711 // one. 6712 convertView = super.getView(position, null, parent); 6713 Container c = item(position); 6714 if (c != null && Container.OPTION_ENABLED != c.mEnabled) { 6715 // ListView does not draw dividers between disabled and 6716 // enabled elements. Use a LinearLayout to provide dividers 6717 LinearLayout layout = new LinearLayout(mContext); 6718 layout.setOrientation(LinearLayout.VERTICAL); 6719 if (position > 0) { 6720 View dividerTop = new View(mContext); 6721 dividerTop.setBackgroundResource( 6722 android.R.drawable.divider_horizontal_bright); 6723 layout.addView(dividerTop); 6724 } 6725 6726 if (Container.OPTGROUP == c.mEnabled) { 6727 // Currently select_dialog_multichoice and 6728 // select_dialog_singlechoice are CheckedTextViews. If 6729 // that changes, the class cast will no longer be valid. 6730 Assert.assertTrue( 6731 convertView instanceof CheckedTextView); 6732 ((CheckedTextView) convertView).setCheckMarkDrawable( 6733 null); 6734 } else { 6735 // c.mEnabled == Container.OPTION_DISABLED 6736 // Draw the disabled element in a disabled state. 6737 convertView.setEnabled(false); 6738 } 6739 6740 layout.addView(convertView); 6741 if (position < getCount() - 1) { 6742 View dividerBottom = new View(mContext); 6743 dividerBottom.setBackgroundResource( 6744 android.R.drawable.divider_horizontal_bright); 6745 layout.addView(dividerBottom); 6746 } 6747 return layout; 6748 } 6749 return convertView; 6750 } 6751 6752 @Override 6753 public boolean hasStableIds() { 6754 // AdapterView's onChanged method uses this to determine whether 6755 // to restore the old state. Return false so that the old (out 6756 // of date) state does not replace the new, valid state. 6757 return false; 6758 } 6759 6760 private Container item(int position) { 6761 if (position < 0 || position >= getCount()) { 6762 return null; 6763 } 6764 return (Container) getItem(position); 6765 } 6766 6767 @Override 6768 public long getItemId(int position) { 6769 Container item = item(position); 6770 if (item == null) { 6771 return -1; 6772 } 6773 return item.mId; 6774 } 6775 6776 @Override 6777 public boolean areAllItemsEnabled() { 6778 return false; 6779 } 6780 6781 @Override 6782 public boolean isEnabled(int position) { 6783 Container item = item(position); 6784 if (item == null) { 6785 return false; 6786 } 6787 return Container.OPTION_ENABLED == item.mEnabled; 6788 } 6789 } 6790 6791 private InvokeListBox(String[] array, int[] enabled, int[] selected) { 6792 mMultiple = true; 6793 mSelectedArray = selected; 6794 6795 int length = array.length; 6796 mContainers = new Container[length]; 6797 for (int i = 0; i < length; i++) { 6798 mContainers[i] = new Container(); 6799 mContainers[i].mString = array[i]; 6800 mContainers[i].mEnabled = enabled[i]; 6801 mContainers[i].mId = i; 6802 } 6803 } 6804 6805 private InvokeListBox(String[] array, int[] enabled, int selection) { 6806 mSelection = selection; 6807 mMultiple = false; 6808 6809 int length = array.length; 6810 mContainers = new Container[length]; 6811 for (int i = 0; i < length; i++) { 6812 mContainers[i] = new Container(); 6813 mContainers[i].mString = array[i]; 6814 mContainers[i].mEnabled = enabled[i]; 6815 mContainers[i].mId = i; 6816 } 6817 } 6818 6819 /* 6820 * Whenever the data set changes due to filtering, this class ensures 6821 * that the checked item remains checked. 6822 */ 6823 private class SingleDataSetObserver extends DataSetObserver { 6824 private long mCheckedId; 6825 private ListView mListView; 6826 private Adapter mAdapter; 6827 6828 /* 6829 * Create a new observer. 6830 * @param id The ID of the item to keep checked. 6831 * @param l ListView for getting and clearing the checked states 6832 * @param a Adapter for getting the IDs 6833 */ 6834 public SingleDataSetObserver(long id, ListView l, Adapter a) { 6835 mCheckedId = id; 6836 mListView = l; 6837 mAdapter = a; 6838 } 6839 6840 public void onChanged() { 6841 // The filter may have changed which item is checked. Find the 6842 // item that the ListView thinks is checked. 6843 int position = mListView.getCheckedItemPosition(); 6844 long id = mAdapter.getItemId(position); 6845 if (mCheckedId != id) { 6846 // Clear the ListView's idea of the checked item, since 6847 // it is incorrect 6848 mListView.clearChoices(); 6849 // Search for mCheckedId. If it is in the filtered list, 6850 // mark it as checked 6851 int count = mAdapter.getCount(); 6852 for (int i = 0; i < count; i++) { 6853 if (mAdapter.getItemId(i) == mCheckedId) { 6854 mListView.setItemChecked(i, true); 6855 break; 6856 } 6857 } 6858 } 6859 } 6860 6861 public void onInvalidate() {} 6862 } 6863 6864 public void run() { 6865 final ListView listView = (ListView) LayoutInflater.from(mContext) 6866 .inflate(com.android.internal.R.layout.select_dialog, null); 6867 final MyArrayListAdapter adapter = new 6868 MyArrayListAdapter(mContext, mContainers, mMultiple); 6869 AlertDialog.Builder b = new AlertDialog.Builder(mContext) 6870 .setView(listView).setCancelable(true) 6871 .setInverseBackgroundForced(true); 6872 6873 if (mMultiple) { 6874 b.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { 6875 public void onClick(DialogInterface dialog, int which) { 6876 mWebViewCore.sendMessage( 6877 EventHub.LISTBOX_CHOICES, 6878 adapter.getCount(), 0, 6879 listView.getCheckedItemPositions()); 6880 }}); 6881 b.setNegativeButton(android.R.string.cancel, 6882 new DialogInterface.OnClickListener() { 6883 public void onClick(DialogInterface dialog, int which) { 6884 mWebViewCore.sendMessage( 6885 EventHub.SINGLE_LISTBOX_CHOICE, -2, 0); 6886 }}); 6887 } 6888 final AlertDialog dialog = b.create(); 6889 listView.setAdapter(adapter); 6890 listView.setFocusableInTouchMode(true); 6891 // There is a bug (1250103) where the checks in a ListView with 6892 // multiple items selected are associated with the positions, not 6893 // the ids, so the items do not properly retain their checks when 6894 // filtered. Do not allow filtering on multiple lists until 6895 // that bug is fixed. 6896 6897 listView.setTextFilterEnabled(!mMultiple); 6898 if (mMultiple) { 6899 listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE); 6900 int length = mSelectedArray.length; 6901 for (int i = 0; i < length; i++) { 6902 listView.setItemChecked(mSelectedArray[i], true); 6903 } 6904 } else { 6905 listView.setOnItemClickListener(new OnItemClickListener() { 6906 public void onItemClick(AdapterView parent, View v, 6907 int position, long id) { 6908 mWebViewCore.sendMessage( 6909 EventHub.SINGLE_LISTBOX_CHOICE, (int)id, 0); 6910 dialog.dismiss(); 6911 } 6912 }); 6913 if (mSelection != -1) { 6914 listView.setSelection(mSelection); 6915 listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE); 6916 listView.setItemChecked(mSelection, true); 6917 DataSetObserver observer = new SingleDataSetObserver( 6918 adapter.getItemId(mSelection), listView, adapter); 6919 adapter.registerDataSetObserver(observer); 6920 } 6921 } 6922 dialog.setOnCancelListener(new DialogInterface.OnCancelListener() { 6923 public void onCancel(DialogInterface dialog) { 6924 mWebViewCore.sendMessage( 6925 EventHub.SINGLE_LISTBOX_CHOICE, -2, 0); 6926 } 6927 }); 6928 dialog.show(); 6929 } 6930 } 6931 6932 /* 6933 * Request a dropdown menu for a listbox with multiple selection. 6934 * 6935 * @param array Labels for the listbox. 6936 * @param enabledArray State for each element in the list. See static 6937 * integers in Container class. 6938 * @param selectedArray Which positions are initally selected. 6939 */ 6940 void requestListBox(String[] array, int[] enabledArray, int[] 6941 selectedArray) { 6942 mPrivateHandler.post( 6943 new InvokeListBox(array, enabledArray, selectedArray)); 6944 } 6945 6946 private void updateZoomRange(WebViewCore.RestoreState restoreState, 6947 int viewWidth, int minPrefWidth, boolean updateZoomOverview) { 6948 if (restoreState.mMinScale == 0) { 6949 if (restoreState.mMobileSite) { 6950 if (minPrefWidth > Math.max(0, viewWidth)) { 6951 mZoomManager.mMinZoomScale = (float) viewWidth / minPrefWidth; 6952 mZoomManager.mMinZoomScaleFixed = false; 6953 if (updateZoomOverview) { 6954 WebSettings settings = getSettings(); 6955 mZoomManager.mInZoomOverview = settings.getUseWideViewPort() && 6956 settings.getLoadWithOverviewMode(); 6957 } 6958 } else { 6959 mZoomManager.mMinZoomScale = restoreState.mDefaultScale; 6960 mZoomManager.mMinZoomScaleFixed = true; 6961 } 6962 } else { 6963 mZoomManager.mMinZoomScale = mZoomManager.DEFAULT_MIN_ZOOM_SCALE; 6964 mZoomManager.mMinZoomScaleFixed = false; 6965 } 6966 } else { 6967 mZoomManager.mMinZoomScale = restoreState.mMinScale; 6968 mZoomManager.mMinZoomScaleFixed = true; 6969 } 6970 if (restoreState.mMaxScale == 0) { 6971 mZoomManager.mMaxZoomScale = mZoomManager.DEFAULT_MAX_ZOOM_SCALE; 6972 } else { 6973 mZoomManager.mMaxZoomScale = restoreState.mMaxScale; 6974 } 6975 } 6976 6977 /* 6978 * Request a dropdown menu for a listbox with single selection or a single 6979 * <select> element. 6980 * 6981 * @param array Labels for the listbox. 6982 * @param enabledArray State for each element in the list. See static 6983 * integers in Container class. 6984 * @param selection Which position is initally selected. 6985 */ 6986 void requestListBox(String[] array, int[] enabledArray, int selection) { 6987 mPrivateHandler.post( 6988 new InvokeListBox(array, enabledArray, selection)); 6989 } 6990 6991 // called by JNI 6992 private void sendMoveFocus(int frame, int node) { 6993 mWebViewCore.sendMessage(EventHub.SET_MOVE_FOCUS, 6994 new WebViewCore.CursorData(frame, node, 0, 0)); 6995 } 6996 6997 // called by JNI 6998 private void sendMoveMouse(int frame, int node, int x, int y) { 6999 mWebViewCore.sendMessage(EventHub.SET_MOVE_MOUSE, 7000 new WebViewCore.CursorData(frame, node, x, y)); 7001 } 7002 7003 /* 7004 * Send a mouse move event to the webcore thread. 7005 * 7006 * @param removeFocus Pass true if the "mouse" cursor is now over a node 7007 * which wants key events, but it is not the focus. This 7008 * will make the visual appear as though nothing is in 7009 * focus. Remove the WebTextView, if present, and stop 7010 * drawing the blinking caret. 7011 * called by JNI 7012 */ 7013 private void sendMoveMouseIfLatest(boolean removeFocus) { 7014 if (removeFocus) { 7015 clearTextEntry(true); 7016 } 7017 mWebViewCore.sendMessage(EventHub.SET_MOVE_MOUSE_IF_LATEST, 7018 cursorData()); 7019 } 7020 7021 // called by JNI 7022 private void sendMotionUp(int touchGeneration, 7023 int frame, int node, int x, int y) { 7024 WebViewCore.TouchUpData touchUpData = new WebViewCore.TouchUpData(); 7025 touchUpData.mMoveGeneration = touchGeneration; 7026 touchUpData.mFrame = frame; 7027 touchUpData.mNode = node; 7028 touchUpData.mX = x; 7029 touchUpData.mY = y; 7030 mWebViewCore.sendMessage(EventHub.TOUCH_UP, touchUpData); 7031 } 7032 7033 7034 private int getScaledMaxXScroll() { 7035 int width; 7036 if (mHeightCanMeasure == false) { 7037 width = getViewWidth() / 4; 7038 } else { 7039 Rect visRect = new Rect(); 7040 calcOurVisibleRect(visRect); 7041 width = visRect.width() / 2; 7042 } 7043 // FIXME the divisor should be retrieved from somewhere 7044 return viewToContentX(width); 7045 } 7046 7047 private int getScaledMaxYScroll() { 7048 int height; 7049 if (mHeightCanMeasure == false) { 7050 height = getViewHeight() / 4; 7051 } else { 7052 Rect visRect = new Rect(); 7053 calcOurVisibleRect(visRect); 7054 height = visRect.height() / 2; 7055 } 7056 // FIXME the divisor should be retrieved from somewhere 7057 // the closest thing today is hard-coded into ScrollView.java 7058 // (from ScrollView.java, line 363) int maxJump = height/2; 7059 return Math.round(height * mZoomManager.mInvActualScale); 7060 } 7061 7062 /** 7063 * Called by JNI to invalidate view 7064 */ 7065 private void viewInvalidate() { 7066 invalidate(); 7067 } 7068 7069 /** 7070 * Pass the key directly to the page. This assumes that 7071 * nativePageShouldHandleShiftAndArrows() returned true. 7072 */ 7073 private void letPageHandleNavKey(int keyCode, long time, boolean down) { 7074 int keyEventAction; 7075 int eventHubAction; 7076 if (down) { 7077 keyEventAction = KeyEvent.ACTION_DOWN; 7078 eventHubAction = EventHub.KEY_DOWN; 7079 playSoundEffect(keyCodeToSoundsEffect(keyCode)); 7080 } else { 7081 keyEventAction = KeyEvent.ACTION_UP; 7082 eventHubAction = EventHub.KEY_UP; 7083 } 7084 KeyEvent event = new KeyEvent(time, time, keyEventAction, keyCode, 7085 1, (mShiftIsPressed ? KeyEvent.META_SHIFT_ON : 0) 7086 | (false ? KeyEvent.META_ALT_ON : 0) // FIXME 7087 | (false ? KeyEvent.META_SYM_ON : 0) // FIXME 7088 , 0, 0, 0); 7089 mWebViewCore.sendMessage(eventHubAction, event); 7090 } 7091 7092 // return true if the key was handled 7093 private boolean navHandledKey(int keyCode, int count, boolean noScroll, 7094 long time) { 7095 if (mNativeClass == 0) { 7096 return false; 7097 } 7098 mLastCursorTime = time; 7099 mLastCursorBounds = nativeGetCursorRingBounds(); 7100 boolean keyHandled 7101 = nativeMoveCursor(keyCode, count, noScroll) == false; 7102 if (DebugFlags.WEB_VIEW) { 7103 Log.v(LOGTAG, "navHandledKey mLastCursorBounds=" + mLastCursorBounds 7104 + " mLastCursorTime=" + mLastCursorTime 7105 + " handled=" + keyHandled); 7106 } 7107 if (keyHandled == false || mHeightCanMeasure == false) { 7108 return keyHandled; 7109 } 7110 Rect contentCursorRingBounds = nativeGetCursorRingBounds(); 7111 if (contentCursorRingBounds.isEmpty()) return keyHandled; 7112 Rect viewCursorRingBounds = contentToViewRect(contentCursorRingBounds); 7113 Rect visRect = new Rect(); 7114 calcOurVisibleRect(visRect); 7115 Rect outset = new Rect(visRect); 7116 int maxXScroll = visRect.width() / 2; 7117 int maxYScroll = visRect.height() / 2; 7118 outset.inset(-maxXScroll, -maxYScroll); 7119 if (Rect.intersects(outset, viewCursorRingBounds) == false) { 7120 return keyHandled; 7121 } 7122 // FIXME: Necessary because ScrollView/ListView do not scroll left/right 7123 int maxH = Math.min(viewCursorRingBounds.right - visRect.right, 7124 maxXScroll); 7125 if (maxH > 0) { 7126 pinScrollBy(maxH, 0, true, 0); 7127 } else { 7128 maxH = Math.max(viewCursorRingBounds.left - visRect.left, 7129 -maxXScroll); 7130 if (maxH < 0) { 7131 pinScrollBy(maxH, 0, true, 0); 7132 } 7133 } 7134 if (mLastCursorBounds.isEmpty()) return keyHandled; 7135 if (mLastCursorBounds.equals(contentCursorRingBounds)) { 7136 return keyHandled; 7137 } 7138 if (DebugFlags.WEB_VIEW) { 7139 Log.v(LOGTAG, "navHandledKey contentCursorRingBounds=" 7140 + contentCursorRingBounds); 7141 } 7142 requestRectangleOnScreen(viewCursorRingBounds); 7143 mUserScroll = true; 7144 return keyHandled; 7145 } 7146 7147 /** 7148 * Set the background color. It's white by default. Pass 7149 * zero to make the view transparent. 7150 * @param color the ARGB color described by Color.java 7151 */ 7152 public void setBackgroundColor(int color) { 7153 mBackgroundColor = color; 7154 mWebViewCore.sendMessage(EventHub.SET_BACKGROUND_COLOR, color); 7155 } 7156 7157 public void debugDump() { 7158 nativeDebugDump(); 7159 mWebViewCore.sendMessage(EventHub.DUMP_NAVTREE); 7160 } 7161 7162 /** 7163 * Draw the HTML page into the specified canvas. This call ignores any 7164 * view-specific zoom, scroll offset, or other changes. It does not draw 7165 * any view-specific chrome, such as progress or URL bars. 7166 * 7167 * @hide only needs to be accessible to Browser and testing 7168 */ 7169 public void drawPage(Canvas canvas) { 7170 mWebViewCore.drawContentPicture(canvas, 0, false, false); 7171 } 7172 7173 /** 7174 * Set the time to wait between passing touches to WebCore. See also the 7175 * TOUCH_SENT_INTERVAL member for further discussion. 7176 * 7177 * @hide This is only used by the DRT test application. 7178 */ 7179 public void setTouchInterval(int interval) { 7180 mCurrentTouchInterval = interval; 7181 } 7182 7183 /** 7184 * Update our cache with updatedText. 7185 * @param updatedText The new text to put in our cache. 7186 */ 7187 /* package */ void updateCachedTextfield(String updatedText) { 7188 // Also place our generation number so that when we look at the cache 7189 // we recognize that it is up to date. 7190 nativeUpdateCachedTextfield(updatedText, mTextGeneration); 7191 } 7192 7193 private native int nativeCacheHitFramePointer(); 7194 private native Rect nativeCacheHitNodeBounds(); 7195 private native int nativeCacheHitNodePointer(); 7196 /* package */ native void nativeClearCursor(); 7197 private native void nativeCreate(int ptr); 7198 private native int nativeCursorFramePointer(); 7199 private native Rect nativeCursorNodeBounds(); 7200 private native int nativeCursorNodePointer(); 7201 /* package */ native boolean nativeCursorMatchesFocus(); 7202 private native boolean nativeCursorIntersects(Rect visibleRect); 7203 private native boolean nativeCursorIsAnchor(); 7204 private native boolean nativeCursorIsTextInput(); 7205 private native Point nativeCursorPosition(); 7206 private native String nativeCursorText(); 7207 /** 7208 * Returns true if the native cursor node says it wants to handle key events 7209 * (ala plugins). This can only be called if mNativeClass is non-zero! 7210 */ 7211 private native boolean nativeCursorWantsKeyEvents(); 7212 private native void nativeDebugDump(); 7213 private native void nativeDestroy(); 7214 private native boolean nativeEvaluateLayersAnimations(); 7215 private native void nativeDrawExtras(Canvas canvas, int extra); 7216 private native void nativeDumpDisplayTree(String urlOrNull); 7217 private native int nativeFindAll(String findLower, String findUpper); 7218 private native void nativeFindNext(boolean forward); 7219 /* package */ native int nativeFocusCandidateFramePointer(); 7220 /* package */ native boolean nativeFocusCandidateHasNextTextfield(); 7221 /* package */ native boolean nativeFocusCandidateIsPassword(); 7222 private native boolean nativeFocusCandidateIsRtlText(); 7223 private native boolean nativeFocusCandidateIsTextInput(); 7224 /* package */ native int nativeFocusCandidateMaxLength(); 7225 /* package */ native String nativeFocusCandidateName(); 7226 private native Rect nativeFocusCandidateNodeBounds(); 7227 /* package */ native int nativeFocusCandidatePointer(); 7228 private native String nativeFocusCandidateText(); 7229 private native int nativeFocusCandidateTextSize(); 7230 /** 7231 * Returns an integer corresponding to WebView.cpp::type. 7232 * See WebTextView.setType() 7233 */ 7234 private native int nativeFocusCandidateType(); 7235 private native boolean nativeFocusIsPlugin(); 7236 private native Rect nativeFocusNodeBounds(); 7237 /* package */ native int nativeFocusNodePointer(); 7238 private native Rect nativeGetCursorRingBounds(); 7239 private native String nativeGetSelection(); 7240 private native boolean nativeHasCursorNode(); 7241 private native boolean nativeHasFocusNode(); 7242 private native void nativeHideCursor(); 7243 private native String nativeImageURI(int x, int y); 7244 private native void nativeInstrumentReport(); 7245 /* package */ native boolean nativeMoveCursorToNextTextInput(); 7246 // return true if the page has been scrolled 7247 private native boolean nativeMotionUp(int x, int y, int slop); 7248 // returns false if it handled the key 7249 private native boolean nativeMoveCursor(int keyCode, int count, 7250 boolean noScroll); 7251 private native int nativeMoveGeneration(); 7252 private native void nativeMoveSelection(int x, int y, 7253 boolean extendSelection); 7254 /** 7255 * @return true if the page should get the shift and arrow keys, rather 7256 * than select text/navigation. 7257 * 7258 * If the focus is a plugin, or if the focus and cursor match and are 7259 * a contentEditable element, then the page should handle these keys. 7260 */ 7261 private native boolean nativePageShouldHandleShiftAndArrows(); 7262 private native boolean nativePointInNavCache(int x, int y, int slop); 7263 // Like many other of our native methods, you must make sure that 7264 // mNativeClass is not null before calling this method. 7265 private native void nativeRecordButtons(boolean focused, 7266 boolean pressed, boolean invalidate); 7267 private native void nativeSelectBestAt(Rect rect); 7268 private native int nativeFindIndex(); 7269 private native void nativeSetFindIsEmpty(); 7270 private native void nativeSetFindIsUp(boolean isUp); 7271 private native void nativeSetFollowedLink(boolean followed); 7272 private native void nativeSetHeightCanMeasure(boolean measure); 7273 private native void nativeSetRootLayer(int layer); 7274 private native void nativeSetSelectionPointer(boolean set, 7275 float scale, int x, int y, boolean extendSelection); 7276 private native void nativeSetSelectionRegion(boolean set); 7277 private native Rect nativeSubtractLayers(Rect content); 7278 private native int nativeTextGeneration(); 7279 // Never call this version except by updateCachedTextfield(String) - 7280 // we always want to pass in our generation number. 7281 private native void nativeUpdateCachedTextfield(String updatedText, 7282 int generation); 7283 // return NO_LEFTEDGE means failure. 7284 private static final int NO_LEFTEDGE = -1; 7285 private native int nativeGetBlockLeftEdge(int x, int y, float scale); 7286} 7287