WebTextView.java revision d3997e556eb0509248c72b668c2cd955b7842b55
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 mOkayForFocusNotToMatch = true; 332 break; 333 case EditorInfo.IME_ACTION_DONE: 334 super.onEditorAction(actionCode); 335 break; 336 case EditorInfo.IME_ACTION_GO: 337 // Send an enter and hide the soft keyboard 338 InputMethodManager.getInstance(mContext) 339 .hideSoftInputFromWindow(getWindowToken(), 0); 340 sendDomEvent(new KeyEvent(KeyEvent.ACTION_DOWN, 341 KeyEvent.KEYCODE_ENTER)); 342 sendDomEvent(new KeyEvent(KeyEvent.ACTION_UP, 343 KeyEvent.KEYCODE_ENTER)); 344 345 default: 346 break; 347 } 348 } 349 350 @Override 351 protected void onSelectionChanged(int selStart, int selEnd) { 352 // This code is copied from TextView.onDraw(). That code does not get 353 // executed, however, because the WebTextView does not draw, allowing 354 // webkit's drawing to show through. 355 InputMethodManager imm = InputMethodManager.peekInstance(); 356 if (imm != null && imm.isActive(this)) { 357 Spannable sp = (Spannable) getText(); 358 int candStart = EditableInputConnection.getComposingSpanStart(sp); 359 int candEnd = EditableInputConnection.getComposingSpanEnd(sp); 360 imm.updateSelection(this, selStart, selEnd, candStart, candEnd); 361 } 362 if (!mFromWebKit && mWebView != null) { 363 if (DebugFlags.WEB_TEXT_VIEW) { 364 Log.v(LOGTAG, "onSelectionChanged selStart=" + selStart 365 + " selEnd=" + selEnd); 366 } 367 mWebView.setSelection(selStart, selEnd); 368 } 369 } 370 371 @Override 372 protected void onTextChanged(CharSequence s,int start,int before,int count){ 373 super.onTextChanged(s, start, before, count); 374 String postChange = s.toString(); 375 // Prevent calls to setText from invoking onTextChanged (since this will 376 // mean we are on a different textfield). Also prevent the change when 377 // going from a textfield with a string of text to one with a smaller 378 // limit on text length from registering the onTextChanged event. 379 if (mPreChange == null || mPreChange.equals(postChange) || 380 (mMaxLength > -1 && mPreChange.length() > mMaxLength && 381 mPreChange.substring(0, mMaxLength).equals(postChange))) { 382 return; 383 } 384 mPreChange = postChange; 385 // This was simply a delete or a cut, so just delete the selection. 386 if (before > 0 && 0 == count) { 387 mWebView.deleteSelection(start, start + before); 388 // For this and all changes to the text, update our cache 389 updateCachedTextfield(); 390 return; 391 } 392 // Find the last character being replaced. If it can be represented by 393 // events, we will pass them to native (after replacing the beginning 394 // of the changed text), so we can see javascript events. 395 // Otherwise, replace the text being changed (including the last 396 // character) in the textfield. 397 TextUtils.getChars(s, start + count - 1, start + count, mCharacter, 0); 398 KeyCharacterMap kmap = 399 KeyCharacterMap.load(KeyCharacterMap.BUILT_IN_KEYBOARD); 400 KeyEvent[] events = kmap.getEvents(mCharacter); 401 boolean cannotUseKeyEvents = null == events; 402 int charactersFromKeyEvents = cannotUseKeyEvents ? 0 : 1; 403 if (count > 1 || cannotUseKeyEvents) { 404 String replace = s.subSequence(start, 405 start + count - charactersFromKeyEvents).toString(); 406 mWebView.replaceTextfieldText(start, start + before, replace, 407 start + count - charactersFromKeyEvents, 408 start + count - charactersFromKeyEvents); 409 } else { 410 // This corrects the selection which may have been affected by the 411 // trackball or auto-correct. 412 if (DebugFlags.WEB_TEXT_VIEW) { 413 Log.v(LOGTAG, "onTextChanged start=" + start 414 + " start + before=" + (start + before)); 415 } 416 mWebView.setSelection(start, start + before); 417 } 418 if (!cannotUseKeyEvents) { 419 int length = events.length; 420 for (int i = 0; i < length; i++) { 421 // We never send modifier keys to native code so don't send them 422 // here either. 423 if (!KeyEvent.isModifierKey(events[i].getKeyCode())) { 424 sendDomEvent(events[i]); 425 } 426 } 427 } 428 updateCachedTextfield(); 429 } 430 431 @Override 432 public boolean onTouchEvent(MotionEvent event) { 433 switch (event.getAction()) { 434 case MotionEvent.ACTION_DOWN: 435 super.onTouchEvent(event); 436 // This event may be the start of a drag, so store it to pass to the 437 // WebView if it is. 438 mDragStartX = event.getX(); 439 mDragStartY = event.getY(); 440 mDragStartTime = event.getEventTime(); 441 mDragSent = false; 442 mScrolled = false; 443 mGotTouchDown = true; 444 break; 445 case MotionEvent.ACTION_MOVE: 446 int slop = ViewConfiguration.get(mContext).getScaledTouchSlop(); 447 Spannable buffer = getText(); 448 int initialScrollX = Touch.getInitialScrollX(this, buffer); 449 int initialScrollY = Touch.getInitialScrollY(this, buffer); 450 super.onTouchEvent(event); 451 int dx = Math.abs(mScrollX - initialScrollX); 452 int dy = Math.abs(mScrollY - initialScrollY); 453 // Use a smaller slop when checking to see if we've moved far enough 454 // to scroll the text, because experimentally, slop has shown to be 455 // to big for the case of a small textfield. 456 int smallerSlop = slop/2; 457 if (dx > smallerSlop || dy > smallerSlop) { 458 if (mWebView != null) { 459 mWebView.scrollFocusedTextInput(mScrollX, mScrollY); 460 } 461 mScrolled = true; 462 return true; 463 } 464 if (Math.abs((int) event.getX() - mDragStartX) < slop 465 && Math.abs((int) event.getY() - mDragStartY) < slop) { 466 // If the user has not scrolled further than slop, we should not 467 // send the drag. Instead, do nothing, and when the user lifts 468 // their finger, we will change the selection. 469 return true; 470 } 471 if (mWebView != null) { 472 // Only want to set the initial state once. 473 if (!mDragSent) { 474 mWebView.initiateTextFieldDrag(mDragStartX, mDragStartY, 475 mDragStartTime); 476 mDragSent = true; 477 } 478 boolean scrolled = mWebView.textFieldDrag(event); 479 if (scrolled) { 480 mScrolled = true; 481 cancelLongPress(); 482 return true; 483 } 484 } 485 return false; 486 case MotionEvent.ACTION_UP: 487 case MotionEvent.ACTION_CANCEL: 488 if (!mScrolled) { 489 // If the page scrolled, or the TextView scrolled, we do not 490 // want to change the selection 491 cancelLongPress(); 492 if (mGotTouchDown && mWebView != null) { 493 mWebView.touchUpOnTextField(event); 494 } 495 } 496 // Necessary for the WebView to reset its state 497 if (mWebView != null && mDragSent) { 498 mWebView.onTouchEvent(event); 499 } 500 mGotTouchDown = false; 501 break; 502 default: 503 break; 504 } 505 return true; 506 } 507 508 @Override 509 public boolean onTrackballEvent(MotionEvent event) { 510 if (isPopupShowing()) { 511 return super.onTrackballEvent(event); 512 } 513 if (event.getAction() != MotionEvent.ACTION_MOVE) { 514 return false; 515 } 516 // If the Cursor is not on the text input, webview should handle the 517 // trackball 518 if (!mWebView.nativeCursorMatchesFocus()) { 519 return mWebView.onTrackballEvent(event); 520 } 521 Spannable text = (Spannable) getText(); 522 MovementMethod move = getMovementMethod(); 523 if (move != null && getLayout() != null && 524 move.onTrackballEvent(this, text, event)) { 525 // Selection is changed in onSelectionChanged 526 return true; 527 } 528 return false; 529 } 530 531 /** 532 * Remove this WebTextView from its host WebView, and return 533 * focus to the host. 534 */ 535 /* package */ void remove() { 536 // hide the soft keyboard when the edit text is out of focus 537 InputMethodManager.getInstance(mContext).hideSoftInputFromWindow( 538 getWindowToken(), 0); 539 mWebView.removeView(this); 540 mWebView.requestFocus(); 541 } 542 543 /* package */ void bringIntoView() { 544 if (getLayout() != null) { 545 bringPointIntoView(Selection.getSelectionEnd(getText())); 546 } 547 } 548 549 /** 550 * Send the DOM events for the specified event. 551 * @param event KeyEvent to be translated into a DOM event. 552 */ 553 private void sendDomEvent(KeyEvent event) { 554 mWebView.passToJavaScript(getText().toString(), event); 555 } 556 557 /** 558 * Always use this instead of setAdapter, as this has features specific to 559 * the WebTextView. 560 */ 561 public void setAdapterCustom(AutoCompleteAdapter adapter) { 562 if (adapter != null) { 563 setInputType(EditorInfo.TYPE_TEXT_FLAG_AUTO_COMPLETE); 564 adapter.setTextView(this); 565 } 566 super.setAdapter(adapter); 567 } 568 569 /** 570 * This is a special version of ArrayAdapter which changes its text size 571 * to match the text size of its host TextView. 572 */ 573 public static class AutoCompleteAdapter extends ArrayAdapter<String> { 574 private TextView mTextView; 575 576 public AutoCompleteAdapter(Context context, ArrayList<String> entries) { 577 super(context, com.android.internal.R.layout 578 .search_dropdown_item_1line, entries); 579 } 580 581 /** 582 * {@inheritDoc} 583 */ 584 public View getView(int position, View convertView, ViewGroup parent) { 585 TextView tv = 586 (TextView) super.getView(position, convertView, parent); 587 if (tv != null && mTextView != null) { 588 tv.setTextSize(mTextView.getTextSize()); 589 } 590 return tv; 591 } 592 593 /** 594 * Set the TextView so we can match its text size. 595 */ 596 private void setTextView(TextView tv) { 597 mTextView = tv; 598 } 599 } 600 601 /** 602 * Determine whether to use the system-wide password disguising method, 603 * or to use none. 604 * @param inPassword True if the textfield is a password field. 605 */ 606 /* package */ void setInPassword(boolean inPassword) { 607 if (inPassword) { 608 setInputType(EditorInfo.TYPE_CLASS_TEXT | EditorInfo. 609 TYPE_TEXT_VARIATION_PASSWORD); 610 createBackground(); 611 } 612 // For password fields, draw the WebTextView. For others, just show 613 // webkit's drawing. 614 setWillNotDraw(!inPassword); 615 setBackgroundDrawable(inPassword ? mBackground : null); 616 // For non-password fields, avoid the invals from TextView's blinking 617 // cursor 618 setCursorVisible(inPassword); 619 } 620 621 /** 622 * Private class used for the background of a password textfield. 623 */ 624 private static class OutlineDrawable extends Drawable { 625 public void draw(Canvas canvas) { 626 Rect bounds = getBounds(); 627 Paint paint = new Paint(); 628 paint.setAntiAlias(true); 629 // Draw the background. 630 paint.setColor(Color.WHITE); 631 canvas.drawRect(bounds, paint); 632 // Draw the outline. 633 paint.setStyle(Paint.Style.STROKE); 634 paint.setColor(Color.BLACK); 635 canvas.drawRect(bounds, paint); 636 } 637 // Always want it to be opaque. 638 public int getOpacity() { 639 return PixelFormat.OPAQUE; 640 } 641 // These are needed because they are abstract in Drawable. 642 public void setAlpha(int alpha) { } 643 public void setColorFilter(ColorFilter cf) { } 644 } 645 646 /** 647 * Create a background for the WebTextView and set up the paint for drawing 648 * the text. This way, we can see the password transformation of the 649 * system, which (optionally) shows the actual text before changing to dots. 650 * The background is necessary to hide the webkit-drawn text beneath. 651 */ 652 private void createBackground() { 653 if (mBackground != null) { 654 return; 655 } 656 mBackground = new OutlineDrawable(); 657 658 setGravity(Gravity.CENTER_VERTICAL); 659 // Turn on subpixel text, and turn off kerning, so it better matches 660 // the text in webkit. 661 TextPaint paint = getPaint(); 662 int flags = paint.getFlags() | Paint.SUBPIXEL_TEXT_FLAG | 663 Paint.ANTI_ALIAS_FLAG & ~Paint.DEV_KERN_TEXT_FLAG; 664 paint.setFlags(flags); 665 // Set the text color to black, regardless of the theme. This ensures 666 // that other applications that use embedded WebViews will properly 667 // display the text in password textfields. 668 setTextColor(Color.BLACK); 669 } 670 671 /* package */ void setMaxLength(int maxLength) { 672 mMaxLength = maxLength; 673 if (-1 == maxLength) { 674 setFilters(NO_FILTERS); 675 } else { 676 setFilters(new InputFilter[] { 677 new InputFilter.LengthFilter(maxLength) }); 678 } 679 } 680 681 /** 682 * Set the pointer for this node so it can be determined which node this 683 * WebTextView represents. 684 * @param ptr Integer representing the pointer to the node which this 685 * WebTextView represents. 686 */ 687 /* package */ void setNodePointer(int ptr) { 688 mNodePointer = ptr; 689 } 690 691 /** 692 * Determine the position and size of WebTextView, and add it to the 693 * WebView's view heirarchy. All parameters are presumed to be in 694 * view coordinates. Also requests Focus and sets the cursor to not 695 * request to be in view. 696 * @param x x-position of the textfield. 697 * @param y y-position of the textfield. 698 * @param width width of the textfield. 699 * @param height height of the textfield. 700 */ 701 /* package */ void setRect(int x, int y, int width, int height) { 702 LayoutParams lp = (LayoutParams) getLayoutParams(); 703 if (null == lp) { 704 lp = new LayoutParams(width, height, x, y); 705 } else { 706 lp.x = x; 707 lp.y = y; 708 lp.width = width; 709 lp.height = height; 710 } 711 if (getParent() == null) { 712 mWebView.addView(this, lp); 713 } else { 714 setLayoutParams(lp); 715 } 716 // Set up a measure spec so a layout can always be recreated. 717 mWidthSpec = MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY); 718 mHeightSpec = MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY); 719 requestFocus(); 720 } 721 722 /** 723 * Set the selection, and disable our onSelectionChanged action. 724 */ 725 /* package */ void setSelectionFromWebKit(int start, int end) { 726 if (start < 0 || end < 0) return; 727 Spannable text = (Spannable) getText(); 728 int length = text.length(); 729 if (start > length || end > length) return; 730 mFromWebKit = true; 731 Selection.setSelection(text, start, end); 732 mFromWebKit = false; 733 } 734 735 /** 736 * Set whether this is a single-line textfield or a multi-line textarea. 737 * Textfields scroll horizontally, and do not handle the enter key. 738 * Textareas behave oppositely. 739 * Do NOT call this after calling setInPassword(true). This will result in 740 * removing the password input type. 741 */ 742 public void setSingleLine(boolean single) { 743 int inputType = EditorInfo.TYPE_CLASS_TEXT 744 | EditorInfo.TYPE_TEXT_VARIATION_WEB_EDIT_TEXT; 745 if (single) { 746 int action = mWebView.nativeTextFieldAction(); 747 switch (action) { 748 // Keep in sync with CachedRoot::ImeAction 749 case 0: // NEXT 750 setImeOptions(EditorInfo.IME_ACTION_NEXT); 751 break; 752 case 1: // GO 753 setImeOptions(EditorInfo.IME_ACTION_GO); 754 break; 755 case -1: // FAILURE 756 case 2: // DONE 757 setImeOptions(EditorInfo.IME_ACTION_DONE); 758 break; 759 } 760 } else { 761 inputType |= EditorInfo.TYPE_TEXT_FLAG_MULTI_LINE 762 | EditorInfo.TYPE_TEXT_FLAG_CAP_SENTENCES 763 | EditorInfo.TYPE_TEXT_FLAG_AUTO_CORRECT; 764 setImeOptions(EditorInfo.IME_ACTION_NONE); 765 } 766 mSingle = single; 767 setHorizontallyScrolling(single); 768 setInputType(inputType); 769 } 770 771 /** 772 * Set the text for this WebTextView, and set the selection to (start, end) 773 * @param text Text to go into this WebTextView. 774 * @param start Beginning of the selection. 775 * @param end End of the selection. 776 */ 777 /* package */ void setText(CharSequence text, int start, int end) { 778 mPreChange = text.toString(); 779 setText(text); 780 Spannable span = (Spannable) getText(); 781 int length = span.length(); 782 if (end > length) { 783 end = length; 784 } 785 if (start < 0) { 786 start = 0; 787 } else if (start > length) { 788 start = length; 789 } 790 if (DebugFlags.WEB_TEXT_VIEW) { 791 Log.v(LOGTAG, "setText start=" + start 792 + " end=" + end); 793 } 794 Selection.setSelection(span, start, end); 795 } 796 797 /** 798 * Set the text to the new string, but use the old selection, making sure 799 * to keep it within the new string. 800 * @param text The new text to place in the textfield. 801 */ 802 /* package */ void setTextAndKeepSelection(String text) { 803 mPreChange = text.toString(); 804 Editable edit = (Editable) getText(); 805 edit.replace(0, edit.length(), text); 806 updateCachedTextfield(); 807 } 808 809 /** 810 * Update the cache to reflect the current text. 811 */ 812 /* package */ void updateCachedTextfield() { 813 mWebView.updateCachedTextfield(getText().toString()); 814 } 815} 816