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