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