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