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