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