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