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