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