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