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