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