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