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