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