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