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