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