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