WebTextView.java revision 94c715d662e803b43dde8984a60f937a26706c7d
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.Selection; 32import android.text.Spannable; 33import android.text.TextPaint; 34import android.text.TextUtils; 35import android.text.method.MovementMethod; 36import android.text.method.Touch; 37import android.util.Log; 38import android.view.Gravity; 39import android.view.KeyCharacterMap; 40import android.view.KeyEvent; 41import android.view.MotionEvent; 42import android.view.View; 43import android.view.ViewConfiguration; 44import android.view.ViewGroup; 45import android.view.inputmethod.EditorInfo; 46import android.view.inputmethod.InputMethodManager; 47import android.view.inputmethod.InputConnection; 48import android.widget.AbsoluteLayout.LayoutParams; 49import android.widget.ArrayAdapter; 50import android.widget.AutoCompleteTextView; 51import android.widget.TextView; 52 53import java.util.ArrayList; 54 55/** 56 * WebTextView is a specialized version of EditText used by WebView 57 * to overlay html textfields (and textareas) to use our standard 58 * text editing. 59 */ 60/* package */ class WebTextView extends AutoCompleteTextView { 61 62 static final String LOGTAG = "webtextview"; 63 64 private WebView mWebView; 65 private boolean mSingle; 66 private int mWidthSpec; 67 private int mHeightSpec; 68 private int mNodePointer; 69 // FIXME: This is a hack for blocking unmatched key ups, in particular 70 // on the enter key. The method for blocking unmatched key ups prevents 71 // the shift key from working properly. 72 private boolean mGotEnterDown; 73 private int mMaxLength; 74 // Keep track of the text before the change so we know whether we actually 75 // need to send down the DOM events. 76 private String mPreChange; 77 private Drawable mBackground; 78 // Variables for keeping track of the touch down, to send to the WebView 79 // when a drag starts 80 private float mDragStartX; 81 private float mDragStartY; 82 private long mDragStartTime; 83 private boolean mDragSent; 84 // True if the most recent drag event has caused either the TextView to 85 // scroll or the web page to scroll. Gets reset after a touch down. 86 private boolean mScrolled; 87 // Gets set to true when the the IME jumps to the next textfield. When this 88 // happens, the next time the user hits a key it is okay for the focus 89 // pointer to not match the WebTextView's node pointer 90 private boolean mOkayForFocusNotToMatch; 91 // Whether or not a selection change was generated from webkit. If it was, 92 // we do not need to pass the selection back to webkit. 93 private boolean mFromWebKit; 94 private boolean mGotTouchDown; 95 // Array to store the final character added in onTextChanged, so that its 96 // KeyEvents may be determined. 97 private char[] mCharacter = new char[1]; 98 // This is used to reset the length filter when on a textfield 99 // with no max length. 100 // FIXME: This can be replaced with TextView.NO_FILTERS if that 101 // is made public/protected. 102 private static final InputFilter[] NO_FILTERS = new InputFilter[0]; 103 104 /** 105 * Create a new WebTextView. 106 * @param context The Context for this WebTextView. 107 * @param webView The WebView that created this. 108 */ 109 /* package */ WebTextView(Context context, WebView webView) { 110 super(context); 111 mWebView = webView; 112 mMaxLength = -1; 113 } 114 115 @Override 116 public boolean dispatchKeyEvent(KeyEvent event) { 117 if (event.isSystem()) { 118 return super.dispatchKeyEvent(event); 119 } 120 // Treat ACTION_DOWN and ACTION MULTIPLE the same 121 boolean down = event.getAction() != KeyEvent.ACTION_UP; 122 int keyCode = event.getKeyCode(); 123 124 boolean isArrowKey = false; 125 switch(keyCode) { 126 case KeyEvent.KEYCODE_DPAD_LEFT: 127 case KeyEvent.KEYCODE_DPAD_RIGHT: 128 case KeyEvent.KEYCODE_DPAD_UP: 129 case KeyEvent.KEYCODE_DPAD_DOWN: 130 if (!mWebView.nativeCursorMatchesFocus()) { 131 return down ? mWebView.onKeyDown(keyCode, event) : mWebView 132 .onKeyUp(keyCode, event); 133 134 } 135 isArrowKey = true; 136 break; 137 } 138 if (!isArrowKey && !mOkayForFocusNotToMatch 139 && mWebView.nativeFocusNodePointer() != mNodePointer) { 140 mWebView.nativeClearCursor(); 141 // Do not call remove() here, which hides the soft keyboard. If 142 // the soft keyboard is being displayed, the user will still want 143 // it there. 144 mWebView.removeView(this); 145 mWebView.requestFocus(); 146 return mWebView.dispatchKeyEvent(event); 147 } 148 // After a jump to next textfield and the first key press, the cursor 149 // and focus will once again match, so reset this value. 150 mOkayForFocusNotToMatch = false; 151 152 Spannable text = (Spannable) getText(); 153 int oldLength = text.length(); 154 // Normally the delete key's dom events are sent via onTextChanged. 155 // However, if the length is zero, the text did not change, so we 156 // go ahead and pass the key down immediately. 157 if (KeyEvent.KEYCODE_DEL == keyCode && 0 == oldLength) { 158 sendDomEvent(event); 159 return true; 160 } 161 162 if ((mSingle && KeyEvent.KEYCODE_ENTER == keyCode)) { 163 if (isPopupShowing()) { 164 return super.dispatchKeyEvent(event); 165 } 166 if (!down) { 167 // Hide the keyboard, since the user has just submitted this 168 // form. The submission happens thanks to the two calls 169 // to sendDomEvent. 170 InputMethodManager.getInstance(mContext) 171 .hideSoftInputFromWindow(getWindowToken(), 0); 172 sendDomEvent(new KeyEvent(KeyEvent.ACTION_DOWN, keyCode)); 173 sendDomEvent(event); 174 } 175 return super.dispatchKeyEvent(event); 176 } else if (KeyEvent.KEYCODE_DPAD_CENTER == keyCode) { 177 // Note that this handles center key and trackball. 178 if (isPopupShowing()) { 179 return super.dispatchKeyEvent(event); 180 } 181 if (!mWebView.nativeCursorMatchesFocus()) { 182 return down ? mWebView.onKeyDown(keyCode, event) : mWebView 183 .onKeyUp(keyCode, event); 184 } 185 // Center key should be passed to a potential onClick 186 if (!down) { 187 mWebView.shortPressOnTextField(); 188 } 189 // Pass to super to handle longpress. 190 return super.dispatchKeyEvent(event); 191 } 192 193 // Ensure there is a layout so arrow keys are handled properly. 194 if (getLayout() == null) { 195 measure(mWidthSpec, mHeightSpec); 196 } 197 int oldStart = Selection.getSelectionStart(text); 198 int oldEnd = Selection.getSelectionEnd(text); 199 200 boolean maxedOut = mMaxLength != -1 && oldLength == mMaxLength; 201 // If we are at max length, and there is a selection rather than a 202 // cursor, we need to store the text to compare later, since the key 203 // may have changed the string. 204 String oldText; 205 if (maxedOut && oldEnd != oldStart) { 206 oldText = text.toString(); 207 } else { 208 oldText = ""; 209 } 210 if (super.dispatchKeyEvent(event)) { 211 // If the WebTextView handled the key it was either an alphanumeric 212 // key, a delete, or a movement within the text. All of those are 213 // ok to pass to javascript. 214 215 // UNLESS there is a max length determined by the html. In that 216 // case, if the string was already at the max length, an 217 // alphanumeric key will be erased by the LengthFilter, 218 // so do not pass down to javascript, and instead 219 // return true. If it is an arrow key or a delete key, we can go 220 // ahead and pass it down. 221 if (KeyEvent.KEYCODE_ENTER == keyCode) { 222 // For multi-line text boxes, newlines will 223 // trigger onTextChanged for key down (which will send both 224 // key up and key down) but not key up. 225 mGotEnterDown = true; 226 } 227 if (maxedOut && !isArrowKey && keyCode != KeyEvent.KEYCODE_DEL) { 228 if (oldEnd == oldStart) { 229 // Return true so the key gets dropped. 230 return true; 231 } else if (!oldText.equals(getText().toString())) { 232 // FIXME: This makes the text work properly, but it 233 // does not pass down the key event, so it may not 234 // work for a textfield that has the type of 235 // behavior of GoogleSuggest. That said, it is 236 // unlikely that a site would combine the two in 237 // one textfield. 238 Spannable span = (Spannable) getText(); 239 int newStart = Selection.getSelectionStart(span); 240 int newEnd = Selection.getSelectionEnd(span); 241 mWebView.replaceTextfieldText(0, oldLength, span.toString(), 242 newStart, newEnd); 243 return true; 244 } 245 } 246 /* FIXME: 247 * In theory, we would like to send the events for the arrow keys. 248 * However, the TextView can arbitrarily change the selection (i.e. 249 * long press followed by using the trackball). Therefore, we keep 250 * in sync with the TextView via onSelectionChanged. If we also 251 * send the DOM event, we lose the correct selection. 252 if (isArrowKey) { 253 // Arrow key does not change the text, but we still want to send 254 // the DOM events. 255 sendDomEvent(event); 256 } 257 */ 258 return true; 259 } 260 // Ignore the key up event for newlines. This prevents 261 // multiple newlines in the native textarea. 262 if (mGotEnterDown && !down) { 263 return true; 264 } 265 // if it is a navigation key, pass it to WebView 266 if (isArrowKey) { 267 // WebView check the trackballtime in onKeyDown to avoid calling 268 // native from both trackball and key handling. As this is called 269 // from WebTextView, we always want WebView to check with native. 270 // Reset trackballtime to ensure it. 271 mWebView.resetTrackballTime(); 272 return down ? mWebView.onKeyDown(keyCode, event) : mWebView 273 .onKeyUp(keyCode, event); 274 } 275 return false; 276 } 277 278 /** 279 * Create a fake touch up event at (x,y) with respect to this WebTextView. 280 * This is used by WebView to act as though a touch event which happened 281 * before we placed the WebTextView actually hit it, so that it can place 282 * the cursor accordingly. 283 */ 284 /* package */ void fakeTouchEvent(float x, float y) { 285 // We need to ensure that there is a Layout, since the Layout is used 286 // in determining where to place the cursor. 287 if (getLayout() == null) { 288 measure(mWidthSpec, mHeightSpec); 289 } 290 // Create a fake touch up, which is used to place the cursor. 291 MotionEvent ev = MotionEvent.obtain(0, 0, MotionEvent.ACTION_UP, 292 x, y, 0); 293 onTouchEvent(ev); 294 ev.recycle(); 295 } 296 297 /** 298 * Determine whether this WebTextView currently represents the node 299 * represented by ptr. 300 * @param ptr Pointer to a node to compare to. 301 * @return boolean Whether this WebTextView already represents the node 302 * pointed to by ptr. 303 */ 304 /* package */ boolean isSameTextField(int ptr) { 305 return ptr == mNodePointer; 306 } 307 308 @Override public InputConnection onCreateInputConnection( 309 EditorInfo outAttrs) { 310 InputConnection connection = super.onCreateInputConnection(outAttrs); 311 if (mWebView != null) { 312 // Use the name of the textfield + the url. Use backslash as an 313 // arbitrary separator. 314 outAttrs.fieldName = mWebView.nativeFocusCandidateName() + "\\" 315 + mWebView.getUrl(); 316 } 317 return connection; 318 } 319 320 @Override 321 public void onEditorAction(int actionCode) { 322 switch (actionCode) { 323 case EditorInfo.IME_ACTION_NEXT: 324 mWebView.nativeMoveCursorToNextTextInput(); 325 // Preemptively rebuild the WebTextView, so that the action will 326 // be set properly. 327 mWebView.rebuildWebTextView(); 328 // Since the cursor will no longer be in the same place as the 329 // focus, set the focus controller back to inactive 330 mWebView.setFocusControllerInactive(); 331 mWebView.invalidate(); 332 mOkayForFocusNotToMatch = true; 333 break; 334 case EditorInfo.IME_ACTION_DONE: 335 super.onEditorAction(actionCode); 336 break; 337 case EditorInfo.IME_ACTION_GO: 338 // Send an enter and hide the soft keyboard 339 InputMethodManager.getInstance(mContext) 340 .hideSoftInputFromWindow(getWindowToken(), 0); 341 sendDomEvent(new KeyEvent(KeyEvent.ACTION_DOWN, 342 KeyEvent.KEYCODE_ENTER)); 343 sendDomEvent(new KeyEvent(KeyEvent.ACTION_UP, 344 KeyEvent.KEYCODE_ENTER)); 345 346 default: 347 break; 348 } 349 } 350 351 @Override 352 protected void onSelectionChanged(int selStart, int selEnd) { 353 // This code is copied from TextView.onDraw(). That code does not get 354 // executed, however, because the WebTextView does not draw, allowing 355 // webkit's drawing to show through. 356 InputMethodManager imm = InputMethodManager.peekInstance(); 357 if (imm != null && imm.isActive(this)) { 358 Spannable sp = (Spannable) getText(); 359 int candStart = EditableInputConnection.getComposingSpanStart(sp); 360 int candEnd = EditableInputConnection.getComposingSpanEnd(sp); 361 imm.updateSelection(this, selStart, selEnd, candStart, candEnd); 362 } 363 if (!mFromWebKit && mWebView != null) { 364 if (DebugFlags.WEB_TEXT_VIEW) { 365 Log.v(LOGTAG, "onSelectionChanged selStart=" + selStart 366 + " selEnd=" + selEnd); 367 } 368 mWebView.setSelection(selStart, selEnd); 369 } 370 } 371 372 @Override 373 protected void onTextChanged(CharSequence s,int start,int before,int count){ 374 super.onTextChanged(s, start, before, count); 375 String postChange = s.toString(); 376 // Prevent calls to setText from invoking onTextChanged (since this will 377 // mean we are on a different textfield). Also prevent the change when 378 // going from a textfield with a string of text to one with a smaller 379 // limit on text length from registering the onTextChanged event. 380 if (mPreChange == null || mPreChange.equals(postChange) || 381 (mMaxLength > -1 && mPreChange.length() > mMaxLength && 382 mPreChange.substring(0, mMaxLength).equals(postChange))) { 383 return; 384 } 385 mPreChange = postChange; 386 // This was simply a delete or a cut, so just delete the selection. 387 if (before > 0 && 0 == count) { 388 mWebView.deleteSelection(start, start + before); 389 // For this and all changes to the text, update our cache 390 updateCachedTextfield(); 391 return; 392 } 393 // Find the last character being replaced. If it can be represented by 394 // events, we will pass them to native (after replacing the beginning 395 // of the changed text), so we can see javascript events. 396 // Otherwise, replace the text being changed (including the last 397 // character) in the textfield. 398 TextUtils.getChars(s, start + count - 1, start + count, mCharacter, 0); 399 KeyCharacterMap kmap = 400 KeyCharacterMap.load(KeyCharacterMap.BUILT_IN_KEYBOARD); 401 KeyEvent[] events = kmap.getEvents(mCharacter); 402 boolean cannotUseKeyEvents = null == events; 403 int charactersFromKeyEvents = cannotUseKeyEvents ? 0 : 1; 404 if (count > 1 || cannotUseKeyEvents) { 405 String replace = s.subSequence(start, 406 start + count - charactersFromKeyEvents).toString(); 407 mWebView.replaceTextfieldText(start, start + before, replace, 408 start + count - charactersFromKeyEvents, 409 start + count - charactersFromKeyEvents); 410 } else { 411 // This corrects the selection which may have been affected by the 412 // trackball or auto-correct. 413 if (DebugFlags.WEB_TEXT_VIEW) { 414 Log.v(LOGTAG, "onTextChanged start=" + start 415 + " start + before=" + (start + before)); 416 } 417 mWebView.setSelection(start, start + before); 418 } 419 if (!cannotUseKeyEvents) { 420 int length = events.length; 421 for (int i = 0; i < length; i++) { 422 // We never send modifier keys to native code so don't send them 423 // here either. 424 if (!KeyEvent.isModifierKey(events[i].getKeyCode())) { 425 sendDomEvent(events[i]); 426 } 427 } 428 } 429 updateCachedTextfield(); 430 } 431 432 @Override 433 public boolean onTouchEvent(MotionEvent event) { 434 switch (event.getAction()) { 435 case MotionEvent.ACTION_DOWN: 436 super.onTouchEvent(event); 437 // This event may be the start of a drag, so store it to pass to the 438 // WebView if it is. 439 mDragStartX = event.getX(); 440 mDragStartY = event.getY(); 441 mDragStartTime = event.getEventTime(); 442 mDragSent = false; 443 mScrolled = false; 444 mGotTouchDown = true; 445 break; 446 case MotionEvent.ACTION_MOVE: 447 int slop = ViewConfiguration.get(mContext).getScaledTouchSlop(); 448 Spannable buffer = getText(); 449 int initialScrollX = Touch.getInitialScrollX(this, buffer); 450 int initialScrollY = Touch.getInitialScrollY(this, buffer); 451 super.onTouchEvent(event); 452 int dx = Math.abs(mScrollX - initialScrollX); 453 int dy = Math.abs(mScrollY - initialScrollY); 454 // Use a smaller slop when checking to see if we've moved far enough 455 // to scroll the text, because experimentally, slop has shown to be 456 // to big for the case of a small textfield. 457 int smallerSlop = slop/2; 458 if (dx > smallerSlop || dy > smallerSlop) { 459 if (mWebView != null) { 460 mWebView.scrollFocusedTextInput(mScrollX, mScrollY); 461 } 462 mScrolled = true; 463 return true; 464 } 465 if (Math.abs((int) event.getX() - mDragStartX) < slop 466 && Math.abs((int) event.getY() - mDragStartY) < slop) { 467 // If the user has not scrolled further than slop, we should not 468 // send the drag. Instead, do nothing, and when the user lifts 469 // their finger, we will change the selection. 470 return true; 471 } 472 if (mWebView != null) { 473 // Only want to set the initial state once. 474 if (!mDragSent) { 475 mWebView.initiateTextFieldDrag(mDragStartX, mDragStartY, 476 mDragStartTime); 477 mDragSent = true; 478 } 479 boolean scrolled = mWebView.textFieldDrag(event); 480 if (scrolled) { 481 mScrolled = true; 482 cancelLongPress(); 483 return true; 484 } 485 } 486 return false; 487 case MotionEvent.ACTION_UP: 488 case MotionEvent.ACTION_CANCEL: 489 if (!mScrolled) { 490 // If the page scrolled, or the TextView scrolled, we do not 491 // want to change the selection 492 cancelLongPress(); 493 if (mGotTouchDown && mWebView != null) { 494 mWebView.touchUpOnTextField(event); 495 } 496 } 497 // Necessary for the WebView to reset its state 498 if (mWebView != null && mDragSent) { 499 mWebView.onTouchEvent(event); 500 } 501 mGotTouchDown = false; 502 break; 503 default: 504 break; 505 } 506 return true; 507 } 508 509 @Override 510 public boolean onTrackballEvent(MotionEvent event) { 511 if (isPopupShowing()) { 512 return super.onTrackballEvent(event); 513 } 514 if (event.getAction() != MotionEvent.ACTION_MOVE) { 515 return false; 516 } 517 // If the Cursor is not on the text input, webview should handle the 518 // trackball 519 if (!mWebView.nativeCursorMatchesFocus()) { 520 return mWebView.onTrackballEvent(event); 521 } 522 Spannable text = (Spannable) getText(); 523 MovementMethod move = getMovementMethod(); 524 if (move != null && getLayout() != null && 525 move.onTrackballEvent(this, text, event)) { 526 // Selection is changed in onSelectionChanged 527 return true; 528 } 529 return false; 530 } 531 532 /** 533 * Remove this WebTextView from its host WebView, and return 534 * focus to the host. 535 */ 536 /* package */ void remove() { 537 // hide the soft keyboard when the edit text is out of focus 538 InputMethodManager.getInstance(mContext).hideSoftInputFromWindow( 539 getWindowToken(), 0); 540 mWebView.removeView(this); 541 mWebView.requestFocus(); 542 } 543 544 /* package */ void bringIntoView() { 545 if (getLayout() != null) { 546 bringPointIntoView(Selection.getSelectionEnd(getText())); 547 } 548 } 549 550 /** 551 * Send the DOM events for the specified event. 552 * @param event KeyEvent to be translated into a DOM event. 553 */ 554 private void sendDomEvent(KeyEvent event) { 555 mWebView.passToJavaScript(getText().toString(), event); 556 } 557 558 /** 559 * Always use this instead of setAdapter, as this has features specific to 560 * the WebTextView. 561 */ 562 public void setAdapterCustom(AutoCompleteAdapter adapter) { 563 if (adapter != null) { 564 setInputType(EditorInfo.TYPE_TEXT_FLAG_AUTO_COMPLETE); 565 adapter.setTextView(this); 566 } 567 super.setAdapter(adapter); 568 } 569 570 /** 571 * This is a special version of ArrayAdapter which changes its text size 572 * to match the text size of its host TextView. 573 */ 574 public static class AutoCompleteAdapter extends ArrayAdapter<String> { 575 private TextView mTextView; 576 577 public AutoCompleteAdapter(Context context, ArrayList<String> entries) { 578 super(context, com.android.internal.R.layout 579 .search_dropdown_item_1line, entries); 580 } 581 582 /** 583 * {@inheritDoc} 584 */ 585 public View getView(int position, View convertView, ViewGroup parent) { 586 TextView tv = 587 (TextView) super.getView(position, convertView, parent); 588 if (tv != null && mTextView != null) { 589 tv.setTextSize(mTextView.getTextSize()); 590 } 591 return tv; 592 } 593 594 /** 595 * Set the TextView so we can match its text size. 596 */ 597 private void setTextView(TextView tv) { 598 mTextView = tv; 599 } 600 } 601 602 /** 603 * Determine whether to use the system-wide password disguising method, 604 * or to use none. 605 * @param inPassword True if the textfield is a password field. 606 */ 607 /* package */ void setInPassword(boolean inPassword) { 608 if (inPassword) { 609 setInputType(EditorInfo.TYPE_CLASS_TEXT | EditorInfo. 610 TYPE_TEXT_VARIATION_PASSWORD); 611 createBackground(); 612 } 613 // For password fields, draw the WebTextView. For others, just show 614 // webkit's drawing. 615 setWillNotDraw(!inPassword); 616 setBackgroundDrawable(inPassword ? mBackground : null); 617 // For non-password fields, avoid the invals from TextView's blinking 618 // cursor 619 setCursorVisible(inPassword); 620 } 621 622 /** 623 * Private class used for the background of a password textfield. 624 */ 625 private static class OutlineDrawable extends Drawable { 626 public void draw(Canvas canvas) { 627 Rect bounds = getBounds(); 628 Paint paint = new Paint(); 629 paint.setAntiAlias(true); 630 // Draw the background. 631 paint.setColor(Color.WHITE); 632 canvas.drawRect(bounds, paint); 633 // Draw the outline. 634 paint.setStyle(Paint.Style.STROKE); 635 paint.setColor(Color.BLACK); 636 canvas.drawRect(bounds, paint); 637 } 638 // Always want it to be opaque. 639 public int getOpacity() { 640 return PixelFormat.OPAQUE; 641 } 642 // These are needed because they are abstract in Drawable. 643 public void setAlpha(int alpha) { } 644 public void setColorFilter(ColorFilter cf) { } 645 } 646 647 /** 648 * Create a background for the WebTextView and set up the paint for drawing 649 * the text. This way, we can see the password transformation of the 650 * system, which (optionally) shows the actual text before changing to dots. 651 * The background is necessary to hide the webkit-drawn text beneath. 652 */ 653 private void createBackground() { 654 if (mBackground != null) { 655 return; 656 } 657 mBackground = new OutlineDrawable(); 658 659 setGravity(Gravity.CENTER_VERTICAL); 660 // Turn on subpixel text, and turn off kerning, so it better matches 661 // the text in webkit. 662 TextPaint paint = getPaint(); 663 int flags = paint.getFlags() | Paint.SUBPIXEL_TEXT_FLAG | 664 Paint.ANTI_ALIAS_FLAG & ~Paint.DEV_KERN_TEXT_FLAG; 665 paint.setFlags(flags); 666 // Set the text color to black, regardless of the theme. This ensures 667 // that other applications that use embedded WebViews will properly 668 // display the text in password textfields. 669 setTextColor(Color.BLACK); 670 } 671 672 /* package */ void setMaxLength(int maxLength) { 673 mMaxLength = maxLength; 674 if (-1 == maxLength) { 675 setFilters(NO_FILTERS); 676 } else { 677 setFilters(new InputFilter[] { 678 new InputFilter.LengthFilter(maxLength) }); 679 } 680 } 681 682 /** 683 * Set the pointer for this node so it can be determined which node this 684 * WebTextView represents. 685 * @param ptr Integer representing the pointer to the node which this 686 * WebTextView represents. 687 */ 688 /* package */ void setNodePointer(int ptr) { 689 mNodePointer = ptr; 690 } 691 692 /** 693 * Determine the position and size of WebTextView, and add it to the 694 * WebView's view heirarchy. All parameters are presumed to be in 695 * view coordinates. Also requests Focus and sets the cursor to not 696 * request to be in view. 697 * @param x x-position of the textfield. 698 * @param y y-position of the textfield. 699 * @param width width of the textfield. 700 * @param height height of the textfield. 701 */ 702 /* package */ void setRect(int x, int y, int width, int height) { 703 LayoutParams lp = (LayoutParams) getLayoutParams(); 704 if (null == lp) { 705 lp = new LayoutParams(width, height, x, y); 706 } else { 707 lp.x = x; 708 lp.y = y; 709 lp.width = width; 710 lp.height = height; 711 } 712 if (getParent() == null) { 713 mWebView.addView(this, lp); 714 } else { 715 setLayoutParams(lp); 716 } 717 // Set up a measure spec so a layout can always be recreated. 718 mWidthSpec = MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY); 719 mHeightSpec = MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY); 720 requestFocus(); 721 } 722 723 /** 724 * Set the selection, and disable our onSelectionChanged action. 725 */ 726 /* package */ void setSelectionFromWebKit(int start, int end) { 727 if (start < 0 || end < 0) return; 728 Spannable text = (Spannable) getText(); 729 int length = text.length(); 730 if (start > length || end > length) return; 731 mFromWebKit = true; 732 Selection.setSelection(text, start, end); 733 mFromWebKit = false; 734 } 735 736 /** 737 * Set whether this is a single-line textfield or a multi-line textarea. 738 * Textfields scroll horizontally, and do not handle the enter key. 739 * Textareas behave oppositely. 740 * Do NOT call this after calling setInPassword(true). This will result in 741 * removing the password input type. 742 */ 743 public void setSingleLine(boolean single) { 744 int inputType = EditorInfo.TYPE_CLASS_TEXT 745 | EditorInfo.TYPE_TEXT_VARIATION_WEB_EDIT_TEXT; 746 if (single) { 747 int action = mWebView.nativeTextFieldAction(); 748 switch (action) { 749 // Keep in sync with CachedRoot::ImeAction 750 case 0: // NEXT 751 setImeOptions(EditorInfo.IME_ACTION_NEXT); 752 break; 753 case 1: // GO 754 setImeOptions(EditorInfo.IME_ACTION_GO); 755 break; 756 case -1: // FAILURE 757 case 2: // DONE 758 setImeOptions(EditorInfo.IME_ACTION_DONE); 759 break; 760 } 761 } else { 762 inputType |= EditorInfo.TYPE_TEXT_FLAG_MULTI_LINE 763 | EditorInfo.TYPE_TEXT_FLAG_CAP_SENTENCES 764 | EditorInfo.TYPE_TEXT_FLAG_AUTO_CORRECT; 765 setImeOptions(EditorInfo.IME_ACTION_NONE); 766 } 767 mSingle = single; 768 setHorizontallyScrolling(single); 769 setInputType(inputType); 770 } 771 772 /** 773 * Set the text for this WebTextView, and set the selection to (start, end) 774 * @param text Text to go into this WebTextView. 775 * @param start Beginning of the selection. 776 * @param end End of the selection. 777 */ 778 /* package */ void setText(CharSequence text, int start, int end) { 779 mPreChange = text.toString(); 780 setText(text); 781 Spannable span = (Spannable) getText(); 782 int length = span.length(); 783 if (end > length) { 784 end = length; 785 } 786 if (start < 0) { 787 start = 0; 788 } else if (start > length) { 789 start = length; 790 } 791 if (DebugFlags.WEB_TEXT_VIEW) { 792 Log.v(LOGTAG, "setText start=" + start 793 + " end=" + end); 794 } 795 Selection.setSelection(span, start, end); 796 } 797 798 /** 799 * Set the text to the new string, but use the old selection, making sure 800 * to keep it within the new string. 801 * @param text The new text to place in the textfield. 802 */ 803 /* package */ void setTextAndKeepSelection(String text) { 804 mPreChange = text.toString(); 805 Editable edit = (Editable) getText(); 806 edit.replace(0, edit.length(), text); 807 updateCachedTextfield(); 808 } 809 810 /** 811 * Update the cache to reflect the current text. 812 */ 813 /* package */ void updateCachedTextfield() { 814 mWebView.updateCachedTextfield(getText().toString()); 815 } 816 817 @Override 818 public boolean requestRectangleOnScreen(Rect rectangle) { 819 // don't scroll while in zoom animation. When it is done, we will adjust 820 // the WebTextView if it is in editing mode. 821 if (!mWebView.inAnimateZoom()) { 822 return super.requestRectangleOnScreen(rectangle); 823 } 824 return false; 825 } 826} 827