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