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