WebTextView.java revision 407772390f4a1b4e1196820ea22b9327eea54019
1/* 2 * Copyright (C) 2007 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 com.android.internal.widget.EditableInputConnection; 20 21import android.content.Context; 22import android.graphics.Canvas; 23import android.graphics.Color; 24import android.graphics.ColorFilter; 25import android.graphics.Paint; 26import android.graphics.PixelFormat; 27import android.graphics.Rect; 28import android.graphics.drawable.Drawable; 29import android.os.Handler; 30import android.os.Message; 31import android.text.BoringLayout.Metrics; 32import android.text.DynamicLayout; 33import android.text.Editable; 34import android.text.InputFilter; 35import android.text.Layout; 36import android.text.Layout.Alignment; 37import android.text.Selection; 38import android.text.Spannable; 39import android.text.TextPaint; 40import android.text.TextUtils; 41import android.text.method.MovementMethod; 42import android.text.method.Touch; 43import android.util.Log; 44import android.util.TypedValue; 45import android.view.Gravity; 46import android.view.KeyCharacterMap; 47import android.view.KeyEvent; 48import android.view.MotionEvent; 49import android.view.View; 50import android.view.ViewConfiguration; 51import android.view.ViewGroup; 52import android.view.inputmethod.EditorInfo; 53import android.view.inputmethod.InputMethodManager; 54import android.view.inputmethod.InputConnection; 55import android.widget.AbsoluteLayout.LayoutParams; 56import android.widget.AdapterView; 57import android.widget.ArrayAdapter; 58import android.widget.AutoCompleteTextView; 59import android.widget.TextView; 60 61import java.util.ArrayList; 62 63import junit.framework.Assert; 64 65/** 66 * WebTextView is a specialized version of EditText used by WebView 67 * to overlay html textfields (and textareas) to use our standard 68 * text editing. 69 */ 70/* package */ class WebTextView extends AutoCompleteTextView { 71 72 static final String LOGTAG = "webtextview"; 73 74 private WebView mWebView; 75 private boolean mSingle; 76 private int mWidthSpec; 77 private int mHeightSpec; 78 private int mNodePointer; 79 // FIXME: This is a hack for blocking unmatched key ups, in particular 80 // on the enter key. The method for blocking unmatched key ups prevents 81 // the shift key from working properly. 82 private boolean mGotEnterDown; 83 private int mMaxLength; 84 // Keep track of the text before the change so we know whether we actually 85 // need to send down the DOM events. 86 private String mPreChange; 87 private Drawable mBackground; 88 // Variables for keeping track of the touch down, to send to the WebView 89 // when a drag starts 90 private float mDragStartX; 91 private float mDragStartY; 92 private long mDragStartTime; 93 private boolean mDragSent; 94 // True if the most recent drag event has caused either the TextView to 95 // scroll or the web page to scroll. Gets reset after a touch down. 96 private boolean mScrolled; 97 // Whether or not a selection change was generated from webkit. If it was, 98 // we do not need to pass the selection back to webkit. 99 private boolean mFromWebKit; 100 // Whether or not a selection change was generated from the WebTextView 101 // gaining focus. If it is, we do not want to pass it to webkit. This 102 // selection comes from the MovementMethod, but we behave differently. If 103 // WebTextView gained focus from a touch, webkit will determine the 104 // selection. 105 private boolean mFromFocusChange; 106 // Whether or not a selection change was generated from setInputType. We 107 // do not want to pass this change to webkit. 108 private boolean mFromSetInputType; 109 private boolean mGotTouchDown; 110 // Keep track of whether a long press has happened. Only meaningful after 111 // an ACTION_DOWN MotionEvent 112 private boolean mHasPerformedLongClick; 113 private boolean mInSetTextAndKeepSelection; 114 // Array to store the final character added in onTextChanged, so that its 115 // KeyEvents may be determined. 116 private char[] mCharacter = new char[1]; 117 // This is used to reset the length filter when on a textfield 118 // with no max length. 119 // FIXME: This can be replaced with TextView.NO_FILTERS if that 120 // is made public/protected. 121 private static final InputFilter[] NO_FILTERS = new InputFilter[0]; 122 // For keeping track of the fact that the delete key was pressed, so 123 // we can simply pass a delete key instead of calling deleteSelection. 124 private boolean mGotDelete; 125 private int mDelSelStart; 126 private int mDelSelEnd; 127 128 // Keep in sync with native constant in 129 // external/webkit/WebKit/android/WebCoreSupport/autofill/WebAutoFill.cpp 130 /* package */ static final int FORM_NOT_AUTOFILLABLE = -1; 131 132 private boolean mAutoFillable; // Is this textview part of an autofillable form? 133 private int mQueryId; 134 private boolean mAutoFillProfileIsSet; 135 // Used to determine whether onFocusChanged was called as a result of 136 // calling remove(). 137 private boolean mInsideRemove; 138 139 // Types used with setType. Keep in sync with CachedInput.h 140 private static final int NORMAL_TEXT_FIELD = 0; 141 private static final int TEXT_AREA = 1; 142 private static final int PASSWORD = 2; 143 private static final int SEARCH = 3; 144 private static final int EMAIL = 4; 145 private static final int NUMBER = 5; 146 private static final int TELEPHONE = 6; 147 private static final int URL = 7; 148 149 private static final int AUTOFILL_FORM = 100; 150 private Handler mHandler; 151 152 /** 153 * Create a new WebTextView. 154 * @param context The Context for this WebTextView. 155 * @param webView The WebView that created this. 156 */ 157 /* package */ WebTextView(Context context, WebView webView, int autoFillQueryId) { 158 super(context, null, com.android.internal.R.attr.webTextViewStyle); 159 mWebView = webView; 160 mMaxLength = -1; 161 setAutoFillable(autoFillQueryId); 162 // Turn on subpixel text, and turn off kerning, so it better matches 163 // the text in webkit. 164 TextPaint paint = getPaint(); 165 int flags = paint.getFlags() & ~Paint.DEV_KERN_TEXT_FLAG 166 | Paint.SUBPIXEL_TEXT_FLAG | Paint.DITHER_FLAG; 167 paint.setFlags(flags); 168 169 // Set the text color to black, regardless of the theme. This ensures 170 // that other applications that use embedded WebViews will properly 171 // display the text in password textfields. 172 setTextColor(DebugFlags.DRAW_WEBTEXTVIEW ? Color.RED : Color.BLACK); 173 // This helps to align the text better with the text in the web page. 174 setIncludeFontPadding(false); 175 176 mHandler = new Handler() { 177 @Override 178 public void handleMessage(Message msg) { 179 switch (msg.what) { 180 case AUTOFILL_FORM: 181 mWebView.autoFillForm(mQueryId); 182 break; 183 } 184 } 185 }; 186 187 } 188 189 public void setAutoFillable(int queryId) { 190 mAutoFillable = mWebView.getSettings().getAutoFillEnabled() 191 && (queryId != FORM_NOT_AUTOFILLABLE); 192 mQueryId = queryId; 193 } 194 195 @Override 196 public boolean dispatchKeyEvent(KeyEvent event) { 197 if (event.isSystem()) { 198 return super.dispatchKeyEvent(event); 199 } 200 // Treat ACTION_DOWN and ACTION MULTIPLE the same 201 boolean down = event.getAction() != KeyEvent.ACTION_UP; 202 int keyCode = event.getKeyCode(); 203 204 boolean isArrowKey = false; 205 switch(keyCode) { 206 case KeyEvent.KEYCODE_DPAD_LEFT: 207 case KeyEvent.KEYCODE_DPAD_RIGHT: 208 case KeyEvent.KEYCODE_DPAD_UP: 209 case KeyEvent.KEYCODE_DPAD_DOWN: 210 isArrowKey = true; 211 break; 212 } 213 214 if (KeyEvent.KEYCODE_TAB == keyCode) { 215 if (down) { 216 onEditorAction(EditorInfo.IME_ACTION_NEXT); 217 } 218 return true; 219 } 220 Spannable text = (Spannable) getText(); 221 int oldStart = Selection.getSelectionStart(text); 222 int oldEnd = Selection.getSelectionEnd(text); 223 // Normally the delete key's dom events are sent via onTextChanged. 224 // However, if the cursor is at the beginning of the field, which 225 // includes the case where it has zero length, then the text is not 226 // changed, so send the events immediately. 227 if (KeyEvent.KEYCODE_DEL == keyCode) { 228 if (oldStart == 0 && oldEnd == 0) { 229 sendDomEvent(event); 230 return true; 231 } 232 if (down) { 233 mGotDelete = true; 234 mDelSelStart = oldStart; 235 mDelSelEnd = oldEnd; 236 } 237 } 238 239 if (mSingle && (KeyEvent.KEYCODE_ENTER == keyCode 240 || KeyEvent.KEYCODE_NUMPAD_ENTER == keyCode)) { 241 if (isPopupShowing()) { 242 return super.dispatchKeyEvent(event); 243 } 244 if (!down) { 245 // Hide the keyboard, since the user has just submitted this 246 // form. The submission happens thanks to the two calls 247 // to sendDomEvent. 248 InputMethodManager.getInstance(mContext) 249 .hideSoftInputFromWindow(getWindowToken(), 0); 250 sendDomEvent(new KeyEvent(KeyEvent.ACTION_DOWN, keyCode)); 251 sendDomEvent(event); 252 } 253 return super.dispatchKeyEvent(event); 254 } else if (KeyEvent.KEYCODE_DPAD_CENTER == keyCode) { 255 // Note that this handles center key and trackball. 256 if (isPopupShowing()) { 257 return super.dispatchKeyEvent(event); 258 } 259 // Center key should be passed to a potential onClick 260 if (!down) { 261 mWebView.centerKeyPressOnTextField(); 262 } 263 // Pass to super to handle longpress. 264 return super.dispatchKeyEvent(event); 265 } 266 267 // Ensure there is a layout so arrow keys are handled properly. 268 if (getLayout() == null) { 269 measure(mWidthSpec, mHeightSpec); 270 } 271 272 int oldLength = text.length(); 273 boolean maxedOut = mMaxLength != -1 && oldLength == mMaxLength; 274 // If we are at max length, and there is a selection rather than a 275 // cursor, we need to store the text to compare later, since the key 276 // may have changed the string. 277 String oldText; 278 if (maxedOut && oldEnd != oldStart) { 279 oldText = text.toString(); 280 } else { 281 oldText = ""; 282 } 283 if (super.dispatchKeyEvent(event)) { 284 // If the WebTextView handled the key it was either an alphanumeric 285 // key, a delete, or a movement within the text. All of those are 286 // ok to pass to javascript. 287 288 // UNLESS there is a max length determined by the html. In that 289 // case, if the string was already at the max length, an 290 // alphanumeric key will be erased by the LengthFilter, 291 // so do not pass down to javascript, and instead 292 // return true. If it is an arrow key or a delete key, we can go 293 // ahead and pass it down. 294 if (KeyEvent.KEYCODE_ENTER == keyCode 295 || KeyEvent.KEYCODE_NUMPAD_ENTER == keyCode) { 296 // For multi-line text boxes, newlines will 297 // trigger onTextChanged for key down (which will send both 298 // key up and key down) but not key up. 299 mGotEnterDown = true; 300 } 301 if (maxedOut && !isArrowKey && keyCode != KeyEvent.KEYCODE_DEL) { 302 if (oldEnd == oldStart) { 303 // Return true so the key gets dropped. 304 return true; 305 } else if (!oldText.equals(getText().toString())) { 306 // FIXME: This makes the text work properly, but it 307 // does not pass down the key event, so it may not 308 // work for a textfield that has the type of 309 // behavior of GoogleSuggest. That said, it is 310 // unlikely that a site would combine the two in 311 // one textfield. 312 Spannable span = (Spannable) getText(); 313 int newStart = Selection.getSelectionStart(span); 314 int newEnd = Selection.getSelectionEnd(span); 315 mWebView.replaceTextfieldText(0, oldLength, span.toString(), 316 newStart, newEnd); 317 return true; 318 } 319 } 320 /* FIXME: 321 * In theory, we would like to send the events for the arrow keys. 322 * However, the TextView can arbitrarily change the selection (i.e. 323 * long press followed by using the trackball). Therefore, we keep 324 * in sync with the TextView via onSelectionChanged. If we also 325 * send the DOM event, we lose the correct selection. 326 if (isArrowKey) { 327 // Arrow key does not change the text, but we still want to send 328 // the DOM events. 329 sendDomEvent(event); 330 } 331 */ 332 return true; 333 } 334 // Ignore the key up event for newlines. This prevents 335 // multiple newlines in the native textarea. 336 if (mGotEnterDown && !down) { 337 return true; 338 } 339 // if it is a navigation key, pass it to WebView 340 if (isArrowKey) { 341 // WebView check the trackballtime in onKeyDown to avoid calling 342 // native from both trackball and key handling. As this is called 343 // from WebTextView, we always want WebView to check with native. 344 // Reset trackballtime to ensure it. 345 mWebView.resetTrackballTime(); 346 return down ? mWebView.onKeyDown(keyCode, event) : mWebView 347 .onKeyUp(keyCode, event); 348 } 349 return false; 350 } 351 352 void ensureLayout() { 353 if (getLayout() == null) { 354 // Ensure we have a Layout 355 measure(mWidthSpec, mHeightSpec); 356 LayoutParams params = (LayoutParams) getLayoutParams(); 357 if (params != null) { 358 layout(params.x, params.y, params.x + params.width, 359 params.y + params.height); 360 } 361 } 362 } 363 364 /** 365 * Determine whether this WebTextView currently represents the node 366 * represented by ptr. 367 * @param ptr Pointer to a node to compare to. 368 * @return boolean Whether this WebTextView already represents the node 369 * pointed to by ptr. 370 */ 371 /* package */ boolean isSameTextField(int ptr) { 372 return ptr == mNodePointer; 373 } 374 375 /** 376 * Ensure that the underlying textfield is lined up with the WebTextView. 377 */ 378 private void lineUpScroll() { 379 Layout layout = getLayout(); 380 if (mWebView != null && layout != null) { 381 float maxScrollX = Touch.getMaxScrollX(this, layout, mScrollY); 382 if (DebugFlags.WEB_TEXT_VIEW) { 383 Log.v(LOGTAG, "onTouchEvent x=" + mScrollX + " y=" 384 + mScrollY + " maxX=" + maxScrollX); 385 } 386 mWebView.scrollFocusedTextInput(maxScrollX > 0 ? 387 mScrollX / maxScrollX : 0, mScrollY); 388 } 389 } 390 391 @Override 392 protected void makeNewLayout(int w, int hintWidth, Metrics boring, 393 Metrics hintBoring, int ellipsisWidth, boolean bringIntoView) { 394 // Necessary to get a Layout to work with, and to do the other work that 395 // makeNewLayout does. 396 super.makeNewLayout(w, hintWidth, boring, hintBoring, ellipsisWidth, 397 bringIntoView); 398 399 // For fields that do not draw, create a layout which is altered so that 400 // the text lines up. 401 if (DebugFlags.DRAW_WEBTEXTVIEW || willNotDraw()) { 402 float lineHeight = -1; 403 if (mWebView != null) { 404 float height = mWebView.nativeFocusCandidateLineHeight(); 405 if (height != -1) { 406 lineHeight = height * mWebView.getScale(); 407 } 408 } 409 CharSequence text = getText(); 410 // Copy from the existing Layout. 411 mLayout = new WebTextViewLayout(text, text, getPaint(), w, 412 mLayout.getAlignment(), mLayout.getSpacingMultiplier(), 413 mLayout.getSpacingAdd(), false, null, ellipsisWidth, 414 lineHeight); 415 } 416 } 417 418 /** 419 * Custom layout which figures out its line spacing. If -1 is passed in for 420 * the height, it will use the ascent and descent from the paint to 421 * determine the line spacing. Otherwise it will use the spacing provided. 422 */ 423 private static class WebTextViewLayout extends DynamicLayout { 424 private float mLineHeight; 425 private float mDifference; 426 public WebTextViewLayout(CharSequence base, CharSequence display, 427 TextPaint paint, 428 int width, Alignment align, 429 float spacingMult, float spacingAdd, 430 boolean includepad, 431 TextUtils.TruncateAt ellipsize, int ellipsizedWidth, 432 float lineHeight) { 433 super(base, display, paint, width, align, spacingMult, spacingAdd, 434 includepad, ellipsize, ellipsizedWidth); 435 float paintLineHeight = paint.descent() - paint.ascent(); 436 if (lineHeight == -1f) { 437 mLineHeight = paintLineHeight; 438 mDifference = 0f; 439 } else { 440 mLineHeight = lineHeight; 441 // Through trial and error, I found this calculation to improve 442 // the accuracy of line placement. 443 mDifference = (lineHeight - paintLineHeight) / 2; 444 } 445 } 446 447 @Override 448 public int getLineTop(int line) { 449 return Math.round(mLineHeight * line - mDifference); 450 } 451 } 452 453 @Override public InputConnection onCreateInputConnection( 454 EditorInfo outAttrs) { 455 InputConnection connection = super.onCreateInputConnection(outAttrs); 456 if (mWebView != null) { 457 // Use the name of the textfield + the url. Use backslash as an 458 // arbitrary separator. 459 outAttrs.fieldName = mWebView.nativeFocusCandidateName() + "\\" 460 + mWebView.getUrl(); 461 } 462 return connection; 463 } 464 465 /** 466 * In general, TextView makes a call to InputMethodManager.updateSelection 467 * in onDraw. However, in the general case of WebTextView, we do not draw. 468 * This method is called by WebView.onDraw to take care of the part that 469 * needs to be called. 470 */ 471 /* package */ void onDrawSubstitute() { 472 if (!willNotDraw()) { 473 // If the WebTextView is set to draw, such as in the case of a 474 // password, onDraw calls updateSelection(), so this code path is 475 // unnecessary. 476 return; 477 } 478 // This code is copied from TextView.onDraw(). That code does not get 479 // executed, however, because the WebTextView does not draw, allowing 480 // webkit's drawing to show through. 481 InputMethodManager imm = InputMethodManager.peekInstance(); 482 if (imm != null && imm.isActive(this)) { 483 Spannable sp = (Spannable) getText(); 484 int selStart = Selection.getSelectionStart(sp); 485 int selEnd = Selection.getSelectionEnd(sp); 486 int candStart = EditableInputConnection.getComposingSpanStart(sp); 487 int candEnd = EditableInputConnection.getComposingSpanEnd(sp); 488 imm.updateSelection(this, selStart, selEnd, candStart, candEnd); 489 } 490 updateCursorControllerPositions(); 491 } 492 493 @Override 494 protected void onDraw(Canvas canvas) { 495 // onDraw should only be called for password fields. If WebTextView is 496 // still drawing, but is no longer corresponding to a password field, 497 // remove it. 498 if (!DebugFlags.DRAW_WEBTEXTVIEW && (mWebView == null 499 || !mWebView.nativeFocusCandidateIsPassword() 500 || !isSameTextField(mWebView.nativeFocusCandidatePointer()))) { 501 // Although calling remove() would seem to make more sense here, 502 // changing it to not be a password field will make it not draw. 503 // Other code will make sure that it is removed completely, but this 504 // way the user will not see it. 505 setInPassword(false); 506 } else { 507 super.onDraw(canvas); 508 } 509 } 510 511 @Override 512 public void onEditorAction(int actionCode) { 513 switch (actionCode) { 514 case EditorInfo.IME_ACTION_NEXT: 515 if (mWebView.nativeMoveCursorToNextTextInput()) { 516 // Preemptively rebuild the WebTextView, so that the action will 517 // be set properly. 518 mWebView.rebuildWebTextView(); 519 setDefaultSelection(); 520 mWebView.invalidate(); 521 } 522 break; 523 case EditorInfo.IME_ACTION_DONE: 524 super.onEditorAction(actionCode); 525 break; 526 case EditorInfo.IME_ACTION_GO: 527 case EditorInfo.IME_ACTION_SEARCH: 528 // Send an enter and hide the soft keyboard 529 InputMethodManager.getInstance(mContext) 530 .hideSoftInputFromWindow(getWindowToken(), 0); 531 sendDomEvent(new KeyEvent(KeyEvent.ACTION_DOWN, 532 KeyEvent.KEYCODE_ENTER)); 533 sendDomEvent(new KeyEvent(KeyEvent.ACTION_UP, 534 KeyEvent.KEYCODE_ENTER)); 535 536 default: 537 break; 538 } 539 } 540 541 @Override 542 protected void onFocusChanged(boolean focused, int direction, 543 Rect previouslyFocusedRect) { 544 mFromFocusChange = true; 545 super.onFocusChanged(focused, direction, previouslyFocusedRect); 546 if (focused) { 547 mWebView.setActive(true); 548 } else if (!mInsideRemove) { 549 mWebView.setActive(false); 550 } 551 mFromFocusChange = false; 552 } 553 554 @Override 555 protected void onScrollChanged(int l, int t, int oldl, int oldt) { 556 super.onScrollChanged(l, t, oldl, oldt); 557 lineUpScroll(); 558 } 559 560 @Override 561 protected void onSelectionChanged(int selStart, int selEnd) { 562 if (!mFromWebKit && !mFromFocusChange && !mFromSetInputType 563 && mWebView != null && !mInSetTextAndKeepSelection) { 564 if (DebugFlags.WEB_TEXT_VIEW) { 565 Log.v(LOGTAG, "onSelectionChanged selStart=" + selStart 566 + " selEnd=" + selEnd); 567 } 568 mWebView.setSelection(selStart, selEnd); 569 lineUpScroll(); 570 } 571 } 572 573 @Override 574 protected void onTextChanged(CharSequence s,int start,int before,int count){ 575 super.onTextChanged(s, start, before, count); 576 String postChange = s.toString(); 577 // Prevent calls to setText from invoking onTextChanged (since this will 578 // mean we are on a different textfield). Also prevent the change when 579 // going from a textfield with a string of text to one with a smaller 580 // limit on text length from registering the onTextChanged event. 581 if (mPreChange == null || mPreChange.equals(postChange) || 582 (mMaxLength > -1 && mPreChange.length() > mMaxLength && 583 mPreChange.substring(0, mMaxLength).equals(postChange))) { 584 return; 585 } 586 mPreChange = postChange; 587 if (0 == count) { 588 if (before > 0) { 589 // For this and all changes to the text, update our cache 590 updateCachedTextfield(); 591 if (mGotDelete) { 592 mGotDelete = false; 593 int oldEnd = start + before; 594 if (mDelSelEnd == oldEnd 595 && (mDelSelStart == start 596 || (mDelSelStart == oldEnd && before == 1))) { 597 // If the selection is set up properly before the 598 // delete, send the DOM events. 599 sendDomEvent(new KeyEvent(KeyEvent.ACTION_DOWN, 600 KeyEvent.KEYCODE_DEL)); 601 sendDomEvent(new KeyEvent(KeyEvent.ACTION_UP, 602 KeyEvent.KEYCODE_DEL)); 603 return; 604 } 605 } 606 // This was simply a delete or a cut, so just delete the 607 // selection. 608 mWebView.deleteSelection(start, start + before); 609 } 610 mGotDelete = false; 611 // before should never be negative, so whether it was a cut 612 // (handled above), or before is 0, in which case nothing has 613 // changed, we should return. 614 return; 615 } 616 // Ensure that this flag gets cleared, since with autocorrect on, a 617 // delete key press may have a more complex result than deleting one 618 // character or the existing selection, so it will not get cleared 619 // above. 620 mGotDelete = false; 621 // Find the last character being replaced. If it can be represented by 622 // events, we will pass them to native (after replacing the beginning 623 // of the changed text), so we can see javascript events. 624 // Otherwise, replace the text being changed (including the last 625 // character) in the textfield. 626 TextUtils.getChars(s, start + count - 1, start + count, mCharacter, 0); 627 KeyCharacterMap kmap = KeyCharacterMap.load(KeyCharacterMap.VIRTUAL_KEYBOARD); 628 KeyEvent[] events = kmap.getEvents(mCharacter); 629 boolean cannotUseKeyEvents = null == events; 630 int charactersFromKeyEvents = cannotUseKeyEvents ? 0 : 1; 631 if (count > 1 || cannotUseKeyEvents) { 632 String replace = s.subSequence(start, 633 start + count - charactersFromKeyEvents).toString(); 634 mWebView.replaceTextfieldText(start, start + before, replace, 635 start + count - charactersFromKeyEvents, 636 start + count - charactersFromKeyEvents); 637 } else { 638 // This corrects the selection which may have been affected by the 639 // trackball or auto-correct. 640 if (DebugFlags.WEB_TEXT_VIEW) { 641 Log.v(LOGTAG, "onTextChanged start=" + start 642 + " start + before=" + (start + before)); 643 } 644 if (!mInSetTextAndKeepSelection) { 645 mWebView.setSelection(start, start + before); 646 } 647 } 648 if (!cannotUseKeyEvents) { 649 int length = events.length; 650 for (int i = 0; i < length; i++) { 651 // We never send modifier keys to native code so don't send them 652 // here either. 653 if (!KeyEvent.isModifierKey(events[i].getKeyCode())) { 654 sendDomEvent(events[i]); 655 } 656 } 657 } 658 updateCachedTextfield(); 659 } 660 661 @Override 662 public boolean onTouchEvent(MotionEvent event) { 663 switch (event.getAction()) { 664 case MotionEvent.ACTION_DOWN: 665 super.onTouchEvent(event); 666 // This event may be the start of a drag, so store it to pass to the 667 // WebView if it is. 668 mDragStartX = event.getX(); 669 mDragStartY = event.getY(); 670 mDragStartTime = event.getEventTime(); 671 mDragSent = false; 672 mScrolled = false; 673 mGotTouchDown = true; 674 mHasPerformedLongClick = false; 675 break; 676 case MotionEvent.ACTION_MOVE: 677 if (mHasPerformedLongClick) { 678 mGotTouchDown = false; 679 return false; 680 } 681 int slop = ViewConfiguration.get(mContext).getScaledTouchSlop(); 682 Spannable buffer = getText(); 683 int initialScrollX = Touch.getInitialScrollX(this, buffer); 684 int initialScrollY = Touch.getInitialScrollY(this, buffer); 685 super.onTouchEvent(event); 686 int dx = Math.abs(mScrollX - initialScrollX); 687 int dy = Math.abs(mScrollY - initialScrollY); 688 // Use a smaller slop when checking to see if we've moved far enough 689 // to scroll the text, because experimentally, slop has shown to be 690 // to big for the case of a small textfield. 691 int smallerSlop = slop/2; 692 if (dx > smallerSlop || dy > smallerSlop) { 693 // Scrolling is handled in onScrollChanged. 694 mScrolled = true; 695 cancelLongPress(); 696 return true; 697 } 698 if (Math.abs((int) event.getX() - mDragStartX) < slop 699 && Math.abs((int) event.getY() - mDragStartY) < slop) { 700 // If the user has not scrolled further than slop, we should not 701 // send the drag. Instead, do nothing, and when the user lifts 702 // their finger, we will change the selection. 703 return true; 704 } 705 if (mWebView != null) { 706 // Only want to set the initial state once. 707 if (!mDragSent) { 708 mWebView.initiateTextFieldDrag(mDragStartX, mDragStartY, 709 mDragStartTime); 710 mDragSent = true; 711 } 712 boolean scrolled = mWebView.textFieldDrag(event); 713 if (scrolled) { 714 mScrolled = true; 715 cancelLongPress(); 716 return true; 717 } 718 } 719 return false; 720 case MotionEvent.ACTION_UP: 721 case MotionEvent.ACTION_CANCEL: 722 super.onTouchEvent(event); 723 if (mHasPerformedLongClick) { 724 mGotTouchDown = false; 725 return false; 726 } 727 if (!mScrolled) { 728 // If the page scrolled, or the TextView scrolled, we do not 729 // want to change the selection 730 cancelLongPress(); 731 if (mGotTouchDown && mWebView != null) { 732 mWebView.touchUpOnTextField(event); 733 } 734 } 735 // Necessary for the WebView to reset its state 736 if (mWebView != null && mDragSent) { 737 mWebView.onTouchEvent(event); 738 } 739 mGotTouchDown = false; 740 break; 741 default: 742 break; 743 } 744 return true; 745 } 746 747 @Override 748 public boolean onTrackballEvent(MotionEvent event) { 749 if (isPopupShowing()) { 750 return super.onTrackballEvent(event); 751 } 752 if (event.getAction() != MotionEvent.ACTION_MOVE) { 753 return false; 754 } 755 Spannable text = getText(); 756 MovementMethod move = getMovementMethod(); 757 if (move != null && getLayout() != null && 758 move.onTrackballEvent(this, text, event)) { 759 // Selection is changed in onSelectionChanged 760 return true; 761 } 762 return false; 763 } 764 765 @Override 766 public boolean performLongClick() { 767 mHasPerformedLongClick = true; 768 return super.performLongClick(); 769 } 770 771 /** 772 * Remove this WebTextView from its host WebView, and return 773 * focus to the host. 774 */ 775 /* package */ void remove() { 776 // hide the soft keyboard when the edit text is out of focus 777 InputMethodManager imm = InputMethodManager.getInstance(mContext); 778 if (imm.isActive(this)) { 779 imm.hideSoftInputFromWindow(getWindowToken(), 0); 780 } 781 mInsideRemove = true; 782 mWebView.removeView(this); 783 mWebView.requestFocus(); 784 mInsideRemove = false; 785 } 786 787 /** 788 * Move the caret/selection into view. 789 */ 790 /* package */ void bringIntoView() { 791 bringPointIntoView(Selection.getSelectionEnd(getText())); 792 } 793 794 @Override 795 public boolean bringPointIntoView(int offset) { 796 if (mWebView == null) return false; 797 if (mWebView.nativeFocusCandidateIsPassword()) { 798 return getLayout() != null && super.bringPointIntoView(offset); 799 } 800 // For non password text input, tell webkit to move the caret/selection 801 // on screen, since webkit draws them. 802 mWebView.revealSelection(); 803 return true; 804 } 805 806 /** 807 * Send the DOM events for the specified event. 808 * @param event KeyEvent to be translated into a DOM event. 809 */ 810 private void sendDomEvent(KeyEvent event) { 811 mWebView.passToJavaScript(getText().toString(), event); 812 } 813 814 /** 815 * Always use this instead of setAdapter, as this has features specific to 816 * the WebTextView. 817 */ 818 public void setAdapterCustom(AutoCompleteAdapter adapter) { 819 if (adapter != null) { 820 setInputType(getInputType() 821 | EditorInfo.TYPE_TEXT_FLAG_AUTO_COMPLETE); 822 adapter.setTextView(this); 823 } 824 super.setAdapter(adapter); 825 if (mAutoFillable) { 826 setOnItemClickListener(new AdapterView.OnItemClickListener() { 827 @Override 828 public void onItemClick(AdapterView<?> parent, View view, int position, long id) { 829 if (id == 0 && position == 0) { 830 // Blank out the text box while we wait for WebCore to fill the form. 831 replaceText(""); 832 WebSettings settings = mWebView.getSettings(); 833 if (mAutoFillProfileIsSet) { 834 // Call a webview method to tell WebCore to autofill the form. 835 mWebView.autoFillForm(mQueryId); 836 } else { 837 // There is no autofill profile setup yet and the user has 838 // elected to try and set one up. Call through to the 839 // embedder to action that. 840 mWebView.getWebChromeClient().setupAutoFill( 841 mHandler.obtainMessage(AUTOFILL_FORM)); 842 } 843 } 844 } 845 }); 846 } else { 847 setOnItemClickListener(null); 848 } 849 showDropDown(); 850 } 851 852 /** 853 * This is a special version of ArrayAdapter which changes its text size 854 * to match the text size of its host TextView. 855 */ 856 public static class AutoCompleteAdapter extends ArrayAdapter<String> { 857 private TextView mTextView; 858 859 public AutoCompleteAdapter(Context context, ArrayList<String> entries) { 860 super(context, com.android.internal.R.layout 861 .web_text_view_dropdown, entries); 862 } 863 864 /** 865 * {@inheritDoc} 866 */ 867 public View getView(int position, View convertView, ViewGroup parent) { 868 TextView tv = 869 (TextView) super.getView(position, convertView, parent); 870 if (tv != null && mTextView != null) { 871 tv.setTextSize(mTextView.getTextSize()); 872 } 873 return tv; 874 } 875 876 /** 877 * Set the TextView so we can match its text size. 878 */ 879 private void setTextView(TextView tv) { 880 mTextView = tv; 881 } 882 } 883 884 /** 885 * Sets the selection when the user clicks on a textfield or textarea with 886 * the trackball or center key, or starts typing into it without clicking on 887 * it. 888 */ 889 /* package */ void setDefaultSelection() { 890 Spannable text = (Spannable) getText(); 891 int selection = mSingle ? text.length() : 0; 892 if (Selection.getSelectionStart(text) == selection 893 && Selection.getSelectionEnd(text) == selection) { 894 // The selection of the UI copy is set correctly, but the 895 // WebTextView still needs to inform the webkit thread to set the 896 // selection. Normally that is done in onSelectionChanged, but 897 // onSelectionChanged will not be called because the UI copy is not 898 // changing. (This can happen when the WebTextView takes focus. 899 // That onSelectionChanged was blocked because the selection set 900 // when focusing is not necessarily the desirable selection for 901 // WebTextView.) 902 if (mWebView != null) { 903 mWebView.setSelection(selection, selection); 904 } 905 } else { 906 Selection.setSelection(text, selection, selection); 907 } 908 if (mWebView != null) mWebView.incrementTextGeneration(); 909 } 910 911 /** 912 * Determine whether to use the system-wide password disguising method, 913 * or to use none. 914 * @param inPassword True if the textfield is a password field. 915 */ 916 /* package */ void setInPassword(boolean inPassword) { 917 if (inPassword) { 918 setInputType(EditorInfo.TYPE_CLASS_TEXT | EditorInfo. 919 TYPE_TEXT_VARIATION_WEB_PASSWORD); 920 createBackground(); 921 } 922 // For password fields, draw the WebTextView. For others, just show 923 // webkit's drawing. 924 if (!DebugFlags.DRAW_WEBTEXTVIEW) { 925 setWillNotDraw(!inPassword); 926 } 927 setBackgroundDrawable(inPassword ? mBackground : null); 928 } 929 930 /** 931 * Private class used for the background of a password textfield. 932 */ 933 private static class OutlineDrawable extends Drawable { 934 private Paint mBackgroundPaint; 935 private Paint mOutlinePaint; 936 private float[] mLines; 937 public OutlineDrawable() { 938 mBackgroundPaint = new Paint(Paint.ANTI_ALIAS_FLAG); 939 mBackgroundPaint.setColor(Color.WHITE); 940 941 mOutlinePaint = new Paint(Paint.ANTI_ALIAS_FLAG); 942 mOutlinePaint.setColor(Color.BLACK); 943 mOutlinePaint.setStyle(Paint.Style.STROKE); 944 945 mLines = new float[16]; 946 } 947 @Override 948 public void setBounds(int left, int top, int right, int bottom) { 949 super.setBounds(left, top, right, bottom); 950 // Top line 951 mLines[0] = left; 952 mLines[1] = top + 1; 953 mLines[2] = right; 954 mLines[3] = top + 1; 955 // Right line 956 mLines[4] = right; 957 mLines[5] = top; 958 mLines[6] = right; 959 mLines[7] = bottom; 960 // Bottom line 961 mLines[8] = left; 962 mLines[9] = bottom; 963 mLines[10] = right; 964 mLines[11] = bottom; 965 // Left line 966 mLines[12] = left + 1; 967 mLines[13] = top; 968 mLines[14] = left + 1; 969 mLines[15] = bottom; 970 } 971 @Override 972 public void draw(Canvas canvas) { 973 // Draw the background. 974 canvas.drawRect(getBounds(), mBackgroundPaint); 975 // Draw the outline. 976 canvas.drawLines(mLines, mOutlinePaint); 977 } 978 // Always want it to be opaque. 979 @Override 980 public int getOpacity() { 981 return PixelFormat.OPAQUE; 982 } 983 // These are needed because they are abstract in Drawable. 984 @Override 985 public void setAlpha(int alpha) { } 986 @Override 987 public void setColorFilter(ColorFilter cf) { } 988 } 989 990 /** 991 * Create a background for the WebTextView and set up the paint for drawing 992 * the text. This way, we can see the password transformation of the 993 * system, which (optionally) shows the actual text before changing to dots. 994 * The background is necessary to hide the webkit-drawn text beneath. 995 */ 996 private void createBackground() { 997 if (mBackground != null) { 998 return; 999 } 1000 mBackground = new OutlineDrawable(); 1001 1002 setGravity(Gravity.CENTER_VERTICAL); 1003 } 1004 1005 @Override 1006 public void setInputType(int type) { 1007 mFromSetInputType = true; 1008 super.setInputType(type); 1009 mFromSetInputType = false; 1010 } 1011 1012 private void setMaxLength(int maxLength) { 1013 mMaxLength = maxLength; 1014 if (-1 == maxLength) { 1015 setFilters(NO_FILTERS); 1016 } else { 1017 setFilters(new InputFilter[] { 1018 new InputFilter.LengthFilter(maxLength) }); 1019 } 1020 } 1021 1022 /** 1023 * Set the pointer for this node so it can be determined which node this 1024 * WebTextView represents. 1025 * @param ptr Integer representing the pointer to the node which this 1026 * WebTextView represents. 1027 */ 1028 /* package */ void setNodePointer(int ptr) { 1029 mNodePointer = ptr; 1030 } 1031 1032 /** 1033 * Determine the position and size of WebTextView, and add it to the 1034 * WebView's view heirarchy. All parameters are presumed to be in 1035 * view coordinates. Also requests Focus and sets the cursor to not 1036 * request to be in view. 1037 * @param x x-position of the textfield. 1038 * @param y y-position of the textfield. 1039 * @param width width of the textfield. 1040 * @param height height of the textfield. 1041 */ 1042 /* package */ void setRect(int x, int y, int width, int height) { 1043 LayoutParams lp = (LayoutParams) getLayoutParams(); 1044 if (null == lp) { 1045 lp = new LayoutParams(width, height, x, y); 1046 } else { 1047 lp.x = x; 1048 lp.y = y; 1049 lp.width = width; 1050 lp.height = height; 1051 } 1052 if (getParent() == null) { 1053 mWebView.addView(this, lp); 1054 } else { 1055 setLayoutParams(lp); 1056 } 1057 // Set up a measure spec so a layout can always be recreated. 1058 mWidthSpec = MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY); 1059 mHeightSpec = MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY); 1060 } 1061 1062 /** 1063 * Set the selection, and disable our onSelectionChanged action. 1064 */ 1065 /* package */ void setSelectionFromWebKit(int start, int end) { 1066 if (start < 0 || end < 0) return; 1067 Spannable text = (Spannable) getText(); 1068 int length = text.length(); 1069 if (start > length || end > length) return; 1070 mFromWebKit = true; 1071 Selection.setSelection(text, start, end); 1072 mFromWebKit = false; 1073 } 1074 1075 /** 1076 * Update the text size according to the size of the focus candidate's text 1077 * size in mWebView. Should only be called from mWebView. 1078 */ 1079 /* package */ void updateTextSize() { 1080 Assert.assertNotNull("updateTextSize should only be called from " 1081 + "mWebView, so mWebView should never be null!", mWebView); 1082 // Note that this is approximately WebView.contentToViewDimension, 1083 // without being rounded. 1084 float size = mWebView.nativeFocusCandidateTextSize() 1085 * mWebView.getScale(); 1086 setTextSize(TypedValue.COMPLEX_UNIT_PX, size); 1087 } 1088 1089 /** 1090 * Set the text to the new string, but use the old selection, making sure 1091 * to keep it within the new string. 1092 * @param text The new text to place in the textfield. 1093 */ 1094 /* package */ void setTextAndKeepSelection(String text) { 1095 mPreChange = text.toString(); 1096 Editable edit = (Editable) getText(); 1097 int selStart = Selection.getSelectionStart(edit); 1098 int selEnd = Selection.getSelectionEnd(edit); 1099 mInSetTextAndKeepSelection = true; 1100 edit.replace(0, edit.length(), text); 1101 int newLength = edit.length(); 1102 if (selStart > newLength) selStart = newLength; 1103 if (selEnd > newLength) selEnd = newLength; 1104 Selection.setSelection(edit, selStart, selEnd); 1105 mInSetTextAndKeepSelection = false; 1106 updateCachedTextfield(); 1107 } 1108 1109 /** 1110 * Called by WebView.rebuildWebTextView(). Based on the type of the <input> 1111 * element, set up the WebTextView, its InputType, and IME Options properly. 1112 * @param type int corresponding to enum "Type" defined in CachedInput.h. 1113 * Does not correspond to HTMLInputElement::InputType so this 1114 * is unaffected if that changes, and also because that has no 1115 * type corresponding to textarea (which is its own tag). 1116 */ 1117 /* package */ void setType(int type) { 1118 if (mWebView == null) return; 1119 boolean single = true; 1120 boolean inPassword = false; 1121 int maxLength = -1; 1122 int inputType = EditorInfo.TYPE_CLASS_TEXT 1123 | EditorInfo.TYPE_TEXT_VARIATION_WEB_EDIT_TEXT; 1124 int imeOptions = EditorInfo.IME_FLAG_NO_EXTRACT_UI 1125 | EditorInfo.IME_FLAG_NO_FULLSCREEN; 1126 if (TEXT_AREA != type 1127 && mWebView.nativeFocusCandidateHasNextTextfield()) { 1128 imeOptions |= EditorInfo.IME_FLAG_NAVIGATE_NEXT; 1129 } 1130 switch (type) { 1131 case NORMAL_TEXT_FIELD: 1132 imeOptions |= EditorInfo.IME_ACTION_GO; 1133 break; 1134 case TEXT_AREA: 1135 single = false; 1136 inputType |= EditorInfo.TYPE_TEXT_FLAG_MULTI_LINE 1137 | EditorInfo.TYPE_TEXT_FLAG_CAP_SENTENCES 1138 | EditorInfo.TYPE_TEXT_FLAG_AUTO_CORRECT; 1139 imeOptions |= EditorInfo.IME_ACTION_NONE; 1140 break; 1141 case PASSWORD: 1142 inPassword = true; 1143 imeOptions |= EditorInfo.IME_ACTION_GO; 1144 break; 1145 case SEARCH: 1146 imeOptions |= EditorInfo.IME_ACTION_SEARCH; 1147 break; 1148 case EMAIL: 1149 inputType = EditorInfo.TYPE_TEXT_VARIATION_WEB_EMAIL_ADDRESS; 1150 imeOptions |= EditorInfo.IME_ACTION_GO; 1151 break; 1152 case NUMBER: 1153 inputType |= EditorInfo.TYPE_CLASS_NUMBER; 1154 // Number and telephone do not have both a Tab key and an 1155 // action, so set the action to NEXT 1156 imeOptions |= EditorInfo.IME_ACTION_NEXT; 1157 break; 1158 case TELEPHONE: 1159 inputType |= EditorInfo.TYPE_CLASS_PHONE; 1160 imeOptions |= EditorInfo.IME_ACTION_NEXT; 1161 break; 1162 case URL: 1163 // TYPE_TEXT_VARIATION_URI prevents Tab key from showing, so 1164 // exclude it for now. 1165 imeOptions |= EditorInfo.IME_ACTION_GO; 1166 break; 1167 default: 1168 imeOptions |= EditorInfo.IME_ACTION_GO; 1169 break; 1170 } 1171 setHint(null); 1172 if (single) { 1173 mWebView.requestLabel(mWebView.nativeFocusCandidateFramePointer(), 1174 mNodePointer); 1175 maxLength = mWebView.nativeFocusCandidateMaxLength(); 1176 boolean autoComplete = mWebView.nativeFocusCandidateIsAutoComplete(); 1177 if (type != PASSWORD && (mAutoFillable || autoComplete)) { 1178 String name = mWebView.nativeFocusCandidateName(); 1179 if (name != null && name.length() > 0) { 1180 mWebView.requestFormData(name, mNodePointer, mAutoFillable, 1181 autoComplete); 1182 } 1183 } 1184 } 1185 mSingle = single; 1186 setMaxLength(maxLength); 1187 setHorizontallyScrolling(single); 1188 setInputType(inputType); 1189 setImeOptions(imeOptions); 1190 setInPassword(inPassword); 1191 AutoCompleteAdapter adapter = null; 1192 setAdapterCustom(adapter); 1193 } 1194 1195 /** 1196 * Update the cache to reflect the current text. 1197 */ 1198 /* package */ void updateCachedTextfield() { 1199 mWebView.updateCachedTextfield(getText().toString()); 1200 } 1201 1202 /* package */ void setAutoFillProfileIsSet(boolean autoFillProfileIsSet) { 1203 mAutoFillProfileIsSet = autoFillProfileIsSet; 1204 } 1205} 1206