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