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