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