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