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