Home | History | Annotate | Download | only in webkit
      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 
     17 package android.webkit;
     18 
     19 import com.android.internal.widget.EditableInputConnection;
     20 
     21 import android.content.Context;
     22 import android.graphics.Canvas;
     23 import android.graphics.Color;
     24 import android.graphics.ColorFilter;
     25 import android.graphics.Paint;
     26 import android.graphics.PixelFormat;
     27 import android.graphics.Rect;
     28 import android.graphics.drawable.Drawable;
     29 import android.text.Editable;
     30 import android.text.InputFilter;
     31 import android.text.Layout;
     32 import android.text.Selection;
     33 import android.text.Spannable;
     34 import android.text.TextPaint;
     35 import android.text.TextUtils;
     36 import android.text.method.MovementMethod;
     37 import android.text.method.Touch;
     38 import android.util.Log;
     39 import android.view.Gravity;
     40 import android.view.KeyCharacterMap;
     41 import android.view.KeyEvent;
     42 import android.view.MotionEvent;
     43 import android.view.View;
     44 import android.view.ViewConfiguration;
     45 import android.view.ViewGroup;
     46 import android.view.inputmethod.EditorInfo;
     47 import android.view.inputmethod.InputMethodManager;
     48 import android.view.inputmethod.InputConnection;
     49 import android.widget.AbsoluteLayout.LayoutParams;
     50 import android.widget.ArrayAdapter;
     51 import android.widget.AutoCompleteTextView;
     52 import android.widget.TextView;
     53 
     54 import 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 oldLength = text.length();
    157         // Normally the delete key's dom events are sent via onTextChanged.
    158         // However, if the length is zero, the text did not change, so we
    159         // go ahead and pass the key down immediately.
    160         if (KeyEvent.KEYCODE_DEL == keyCode && 0 == oldLength) {
    161             sendDomEvent(event);
    162             return true;
    163         }
    164 
    165         if ((mSingle && KeyEvent.KEYCODE_ENTER == keyCode)) {
    166             if (isPopupShowing()) {
    167                 return super.dispatchKeyEvent(event);
    168             }
    169             if (!down) {
    170                 // Hide the keyboard, since the user has just submitted this
    171                 // form.  The submission happens thanks to the two calls
    172                 // to sendDomEvent.
    173                 InputMethodManager.getInstance(mContext)
    174                         .hideSoftInputFromWindow(getWindowToken(), 0);
    175                 sendDomEvent(new KeyEvent(KeyEvent.ACTION_DOWN, keyCode));
    176                 sendDomEvent(event);
    177             }
    178             return super.dispatchKeyEvent(event);
    179         } else if (KeyEvent.KEYCODE_DPAD_CENTER == keyCode) {
    180             // Note that this handles center key and trackball.
    181             if (isPopupShowing()) {
    182                 return super.dispatchKeyEvent(event);
    183             }
    184             if (!mWebView.nativeCursorMatchesFocus()) {
    185                 return down ? mWebView.onKeyDown(keyCode, event) : mWebView
    186                         .onKeyUp(keyCode, event);
    187             }
    188             // Center key should be passed to a potential onClick
    189             if (!down) {
    190                 mWebView.centerKeyPressOnTextField();
    191             }
    192             // Pass to super to handle longpress.
    193             return super.dispatchKeyEvent(event);
    194         }
    195 
    196         // Ensure there is a layout so arrow keys are handled properly.
    197         if (getLayout() == null) {
    198             measure(mWidthSpec, mHeightSpec);
    199         }
    200         int oldStart = Selection.getSelectionStart(text);
    201         int oldEnd = Selection.getSelectionEnd(text);
    202 
    203         boolean maxedOut = mMaxLength != -1 && oldLength == mMaxLength;
    204         // If we are at max length, and there is a selection rather than a
    205         // cursor, we need to store the text to compare later, since the key
    206         // may have changed the string.
    207         String oldText;
    208         if (maxedOut && oldEnd != oldStart) {
    209             oldText = text.toString();
    210         } else {
    211             oldText = "";
    212         }
    213         if (super.dispatchKeyEvent(event)) {
    214             // If the WebTextView handled the key it was either an alphanumeric
    215             // key, a delete, or a movement within the text. All of those are
    216             // ok to pass to javascript.
    217 
    218             // UNLESS there is a max length determined by the html.  In that
    219             // case, if the string was already at the max length, an
    220             // alphanumeric key will be erased by the LengthFilter,
    221             // so do not pass down to javascript, and instead
    222             // return true.  If it is an arrow key or a delete key, we can go
    223             // ahead and pass it down.
    224             if (KeyEvent.KEYCODE_ENTER == keyCode) {
    225                 // For multi-line text boxes, newlines will
    226                 // trigger onTextChanged for key down (which will send both
    227                 // key up and key down) but not key up.
    228                 mGotEnterDown = true;
    229             }
    230             if (maxedOut && !isArrowKey && keyCode != KeyEvent.KEYCODE_DEL) {
    231                 if (oldEnd == oldStart) {
    232                     // Return true so the key gets dropped.
    233                     return true;
    234                 } else if (!oldText.equals(getText().toString())) {
    235                     // FIXME: This makes the text work properly, but it
    236                     // does not pass down the key event, so it may not
    237                     // work for a textfield that has the type of
    238                     // behavior of GoogleSuggest.  That said, it is
    239                     // unlikely that a site would combine the two in
    240                     // one textfield.
    241                     Spannable span = (Spannable) getText();
    242                     int newStart = Selection.getSelectionStart(span);
    243                     int newEnd = Selection.getSelectionEnd(span);
    244                     mWebView.replaceTextfieldText(0, oldLength, span.toString(),
    245                             newStart, newEnd);
    246                     return true;
    247                 }
    248             }
    249             /* FIXME:
    250              * In theory, we would like to send the events for the arrow keys.
    251              * However, the TextView can arbitrarily change the selection (i.e.
    252              * long press followed by using the trackball).  Therefore, we keep
    253              * in sync with the TextView via onSelectionChanged.  If we also
    254              * send the DOM event, we lose the correct selection.
    255             if (isArrowKey) {
    256                 // Arrow key does not change the text, but we still want to send
    257                 // the DOM events.
    258                 sendDomEvent(event);
    259             }
    260              */
    261             return true;
    262         }
    263         // Ignore the key up event for newlines. This prevents
    264         // multiple newlines in the native textarea.
    265         if (mGotEnterDown && !down) {
    266             return true;
    267         }
    268         // if it is a navigation key, pass it to WebView
    269         if (isArrowKey) {
    270             // WebView check the trackballtime in onKeyDown to avoid calling
    271             // native from both trackball and key handling. As this is called
    272             // from WebTextView, we always want WebView to check with native.
    273             // Reset trackballtime to ensure it.
    274             mWebView.resetTrackballTime();
    275             return down ? mWebView.onKeyDown(keyCode, event) : mWebView
    276                     .onKeyUp(keyCode, event);
    277         }
    278         return false;
    279     }
    280 
    281     /**
    282      *  Determine whether this WebTextView currently represents the node
    283      *  represented by ptr.
    284      *  @param  ptr Pointer to a node to compare to.
    285      *  @return boolean Whether this WebTextView already represents the node
    286      *          pointed to by ptr.
    287      */
    288     /* package */ boolean isSameTextField(int ptr) {
    289         return ptr == mNodePointer;
    290     }
    291 
    292     /**
    293      * Ensure that the underlying textfield is lined up with the WebTextView.
    294      */
    295     private void lineUpScroll() {
    296         Layout layout = getLayout();
    297         if (mWebView != null && layout != null) {
    298             float maxScrollX = Touch.getMaxScrollX(this, layout, mScrollY);
    299             if (DebugFlags.WEB_TEXT_VIEW) {
    300                 Log.v(LOGTAG, "onTouchEvent x=" + mScrollX + " y="
    301                         + mScrollY + " maxX=" + maxScrollX);
    302             }
    303             mWebView.scrollFocusedTextInput(maxScrollX > 0 ?
    304                     mScrollX / maxScrollX : 0, mScrollY);
    305         }
    306     }
    307 
    308     @Override public InputConnection onCreateInputConnection(
    309             EditorInfo outAttrs) {
    310         InputConnection connection = super.onCreateInputConnection(outAttrs);
    311         if (mWebView != null) {
    312             // Use the name of the textfield + the url.  Use backslash as an
    313             // arbitrary separator.
    314             outAttrs.fieldName = mWebView.nativeFocusCandidateName() + "\\"
    315                     + mWebView.getUrl();
    316         }
    317         return connection;
    318     }
    319 
    320     @Override
    321     protected void onDraw(Canvas canvas) {
    322         // onDraw should only be called for password fields.  If WebTextView is
    323         // still drawing, but is no longer corresponding to a password field,
    324         // remove it.
    325         if (mWebView == null || !mWebView.nativeFocusCandidateIsPassword()
    326                 || !isSameTextField(mWebView.nativeFocusCandidatePointer())) {
    327             // Although calling remove() would seem to make more sense here,
    328             // changing it to not be a password field will make it not draw.
    329             // Other code will make sure that it is removed completely, but this
    330             // way the user will not see it.
    331             setInPassword(false);
    332         } else {
    333             super.onDraw(canvas);
    334         }
    335     }
    336 
    337     public void onDrawSubstitute() {
    338       updateCursorControllerPositions();
    339     }
    340 
    341     @Override
    342     public void onEditorAction(int actionCode) {
    343         switch (actionCode) {
    344         case EditorInfo.IME_ACTION_NEXT:
    345             if (mWebView.nativeMoveCursorToNextTextInput()) {
    346                 // Since the cursor will no longer be in the same place as the
    347                 // focus, set the focus controller back to inactive
    348                 mWebView.setFocusControllerInactive();
    349                 // Preemptively rebuild the WebTextView, so that the action will
    350                 // be set properly.
    351                 mWebView.rebuildWebTextView();
    352                 setDefaultSelection();
    353                 mWebView.invalidate();
    354             }
    355             break;
    356         case EditorInfo.IME_ACTION_DONE:
    357             super.onEditorAction(actionCode);
    358             break;
    359         case EditorInfo.IME_ACTION_GO:
    360         case EditorInfo.IME_ACTION_SEARCH:
    361             // Send an enter and hide the soft keyboard
    362             InputMethodManager.getInstance(mContext)
    363                     .hideSoftInputFromWindow(getWindowToken(), 0);
    364             sendDomEvent(new KeyEvent(KeyEvent.ACTION_DOWN,
    365                     KeyEvent.KEYCODE_ENTER));
    366             sendDomEvent(new KeyEvent(KeyEvent.ACTION_UP,
    367                     KeyEvent.KEYCODE_ENTER));
    368 
    369         default:
    370             break;
    371         }
    372     }
    373 
    374     @Override
    375     protected void onFocusChanged(boolean focused, int direction,
    376             Rect previouslyFocusedRect) {
    377         mFromFocusChange = true;
    378         super.onFocusChanged(focused, direction, previouslyFocusedRect);
    379         mFromFocusChange = false;
    380     }
    381 
    382     @Override
    383     protected void onScrollChanged(int l, int t, int oldl, int oldt) {
    384         super.onScrollChanged(l, t, oldl, oldt);
    385         lineUpScroll();
    386     }
    387 
    388     @Override
    389     protected void onSelectionChanged(int selStart, int selEnd) {
    390         if (mInSetTextAndKeepSelection) return;
    391         // This code is copied from TextView.onDraw().  That code does not get
    392         // executed, however, because the WebTextView does not draw, allowing
    393         // webkit's drawing to show through.
    394         InputMethodManager imm = InputMethodManager.peekInstance();
    395         if (imm != null && imm.isActive(this)) {
    396             Spannable sp = (Spannable) getText();
    397             int candStart = EditableInputConnection.getComposingSpanStart(sp);
    398             int candEnd = EditableInputConnection.getComposingSpanEnd(sp);
    399             imm.updateSelection(this, selStart, selEnd, candStart, candEnd);
    400         }
    401         if (!mFromWebKit && !mFromFocusChange && !mFromSetInputType
    402                 && mWebView != null) {
    403             if (DebugFlags.WEB_TEXT_VIEW) {
    404                 Log.v(LOGTAG, "onSelectionChanged selStart=" + selStart
    405                         + " selEnd=" + selEnd);
    406             }
    407             mWebView.setSelection(selStart, selEnd);
    408             lineUpScroll();
    409         }
    410     }
    411 
    412     @Override
    413     protected void onTextChanged(CharSequence s,int start,int before,int count){
    414         super.onTextChanged(s, start, before, count);
    415         String postChange = s.toString();
    416         // Prevent calls to setText from invoking onTextChanged (since this will
    417         // mean we are on a different textfield).  Also prevent the change when
    418         // going from a textfield with a string of text to one with a smaller
    419         // limit on text length from registering the onTextChanged event.
    420         if (mPreChange == null || mPreChange.equals(postChange) ||
    421                 (mMaxLength > -1 && mPreChange.length() > mMaxLength &&
    422                 mPreChange.substring(0, mMaxLength).equals(postChange))) {
    423             return;
    424         }
    425         mPreChange = postChange;
    426         if (0 == count) {
    427             if (before > 0) {
    428                 // This was simply a delete or a cut, so just delete the
    429                 // selection.
    430                 mWebView.deleteSelection(start, start + before);
    431                 // For this and all changes to the text, update our cache
    432                 updateCachedTextfield();
    433             }
    434             // before should never be negative, so whether it was a cut
    435             // (handled above), or before is 0, in which case nothing has
    436             // changed, we should return.
    437             return;
    438         }
    439         // Find the last character being replaced.  If it can be represented by
    440         // events, we will pass them to native (after replacing the beginning
    441         // of the changed text), so we can see javascript events.
    442         // Otherwise, replace the text being changed (including the last
    443         // character) in the textfield.
    444         TextUtils.getChars(s, start + count - 1, start + count, mCharacter, 0);
    445         KeyCharacterMap kmap =
    446                 KeyCharacterMap.load(KeyCharacterMap.BUILT_IN_KEYBOARD);
    447         KeyEvent[] events = kmap.getEvents(mCharacter);
    448         boolean cannotUseKeyEvents = null == events;
    449         int charactersFromKeyEvents = cannotUseKeyEvents ? 0 : 1;
    450         if (count > 1 || cannotUseKeyEvents) {
    451             String replace = s.subSequence(start,
    452                     start + count - charactersFromKeyEvents).toString();
    453             mWebView.replaceTextfieldText(start, start + before, replace,
    454                     start + count - charactersFromKeyEvents,
    455                     start + count - charactersFromKeyEvents);
    456         } else {
    457             // This corrects the selection which may have been affected by the
    458             // trackball or auto-correct.
    459             if (DebugFlags.WEB_TEXT_VIEW) {
    460                 Log.v(LOGTAG, "onTextChanged start=" + start
    461                         + " start + before=" + (start + before));
    462             }
    463             if (!mInSetTextAndKeepSelection) {
    464                 mWebView.setSelection(start, start + before);
    465             }
    466         }
    467         if (!cannotUseKeyEvents) {
    468             int length = events.length;
    469             for (int i = 0; i < length; i++) {
    470                 // We never send modifier keys to native code so don't send them
    471                 // here either.
    472                 if (!KeyEvent.isModifierKey(events[i].getKeyCode())) {
    473                     sendDomEvent(events[i]);
    474                 }
    475             }
    476         }
    477         updateCachedTextfield();
    478     }
    479 
    480     @Override
    481     public boolean onTouchEvent(MotionEvent event) {
    482         switch (event.getAction()) {
    483         case MotionEvent.ACTION_DOWN:
    484             super.onTouchEvent(event);
    485             // This event may be the start of a drag, so store it to pass to the
    486             // WebView if it is.
    487             mDragStartX = event.getX();
    488             mDragStartY = event.getY();
    489             mDragStartTime = event.getEventTime();
    490             mDragSent = false;
    491             mScrolled = false;
    492             mGotTouchDown = true;
    493             mHasPerformedLongClick = false;
    494             break;
    495         case MotionEvent.ACTION_MOVE:
    496             if (mHasPerformedLongClick) {
    497                 mGotTouchDown = false;
    498                 return false;
    499             }
    500             int slop = ViewConfiguration.get(mContext).getScaledTouchSlop();
    501             Spannable buffer = getText();
    502             int initialScrollX = Touch.getInitialScrollX(this, buffer);
    503             int initialScrollY = Touch.getInitialScrollY(this, buffer);
    504             super.onTouchEvent(event);
    505             int dx = Math.abs(mScrollX - initialScrollX);
    506             int dy = Math.abs(mScrollY - initialScrollY);
    507             // Use a smaller slop when checking to see if we've moved far enough
    508             // to scroll the text, because experimentally, slop has shown to be
    509             // to big for the case of a small textfield.
    510             int smallerSlop = slop/2;
    511             if (dx > smallerSlop || dy > smallerSlop) {
    512                 // Scrolling is handled in onScrollChanged.
    513                 mScrolled = true;
    514                 cancelLongPress();
    515                 return true;
    516             }
    517             if (Math.abs((int) event.getX() - mDragStartX) < slop
    518                     && Math.abs((int) event.getY() - mDragStartY) < slop) {
    519                 // If the user has not scrolled further than slop, we should not
    520                 // send the drag.  Instead, do nothing, and when the user lifts
    521                 // their finger, we will change the selection.
    522                 return true;
    523             }
    524             if (mWebView != null) {
    525                 // Only want to set the initial state once.
    526                 if (!mDragSent) {
    527                     mWebView.initiateTextFieldDrag(mDragStartX, mDragStartY,
    528                             mDragStartTime);
    529                     mDragSent = true;
    530                 }
    531                 boolean scrolled = mWebView.textFieldDrag(event);
    532                 if (scrolled) {
    533                     mScrolled = true;
    534                     cancelLongPress();
    535                     return true;
    536                 }
    537             }
    538             return false;
    539         case MotionEvent.ACTION_UP:
    540         case MotionEvent.ACTION_CANCEL:
    541             super.onTouchEvent(event);
    542             if (mHasPerformedLongClick) {
    543                 mGotTouchDown = false;
    544                 return false;
    545             }
    546             if (!mScrolled) {
    547                 // If the page scrolled, or the TextView scrolled, we do not
    548                 // want to change the selection
    549                 cancelLongPress();
    550                 if (mGotTouchDown && mWebView != null) {
    551                     mWebView.touchUpOnTextField(event);
    552                 }
    553             }
    554             // Necessary for the WebView to reset its state
    555             if (mWebView != null && mDragSent) {
    556                 mWebView.onTouchEvent(event);
    557             }
    558             mGotTouchDown = false;
    559             break;
    560         default:
    561             break;
    562         }
    563         return true;
    564     }
    565 
    566     @Override
    567     public boolean onTrackballEvent(MotionEvent event) {
    568         if (isPopupShowing()) {
    569             return super.onTrackballEvent(event);
    570         }
    571         if (event.getAction() != MotionEvent.ACTION_MOVE) {
    572             return false;
    573         }
    574         // If the Cursor is not on the text input, webview should handle the
    575         // trackball
    576         if (!mWebView.nativeCursorMatchesFocus()) {
    577             return mWebView.onTrackballEvent(event);
    578         }
    579         Spannable text = (Spannable) getText();
    580         MovementMethod move = getMovementMethod();
    581         if (move != null && getLayout() != null &&
    582             move.onTrackballEvent(this, text, event)) {
    583             // Selection is changed in onSelectionChanged
    584             return true;
    585         }
    586         return false;
    587     }
    588 
    589     @Override
    590     public boolean performLongClick() {
    591         mHasPerformedLongClick = true;
    592         return super.performLongClick();
    593     }
    594 
    595     /**
    596      * Remove this WebTextView from its host WebView, and return
    597      * focus to the host.
    598      */
    599     /* package */ void remove() {
    600         // hide the soft keyboard when the edit text is out of focus
    601         InputMethodManager.getInstance(mContext).hideSoftInputFromWindow(
    602                 getWindowToken(), 0);
    603         mWebView.removeView(this);
    604         mWebView.requestFocus();
    605     }
    606 
    607     /* package */ void bringIntoView() {
    608         if (getLayout() != null) {
    609             bringPointIntoView(Selection.getSelectionEnd(getText()));
    610         }
    611     }
    612 
    613     /**
    614      *  Send the DOM events for the specified event.
    615      *  @param event    KeyEvent to be translated into a DOM event.
    616      */
    617     private void sendDomEvent(KeyEvent event) {
    618         mWebView.passToJavaScript(getText().toString(), event);
    619     }
    620 
    621     /**
    622      *  Always use this instead of setAdapter, as this has features specific to
    623      *  the WebTextView.
    624      */
    625     public void setAdapterCustom(AutoCompleteAdapter adapter) {
    626         if (adapter != null) {
    627             setInputType(getInputType()
    628                     | EditorInfo.TYPE_TEXT_FLAG_AUTO_COMPLETE);
    629             adapter.setTextView(this);
    630         }
    631         super.setAdapter(adapter);
    632     }
    633 
    634     /**
    635      *  This is a special version of ArrayAdapter which changes its text size
    636      *  to match the text size of its host TextView.
    637      */
    638     public static class AutoCompleteAdapter extends ArrayAdapter<String> {
    639         private TextView mTextView;
    640 
    641         public AutoCompleteAdapter(Context context, ArrayList<String> entries) {
    642             super(context, com.android.internal.R.layout
    643                     .search_dropdown_item_1line, entries);
    644         }
    645 
    646         /**
    647          * {@inheritDoc}
    648          */
    649         public View getView(int position, View convertView, ViewGroup parent) {
    650             TextView tv =
    651                     (TextView) super.getView(position, convertView, parent);
    652             if (tv != null && mTextView != null) {
    653                 tv.setTextSize(mTextView.getTextSize());
    654             }
    655             return tv;
    656         }
    657 
    658         /**
    659          * Set the TextView so we can match its text size.
    660          */
    661         private void setTextView(TextView tv) {
    662             mTextView = tv;
    663         }
    664     }
    665 
    666     /**
    667      * Sets the selection when the user clicks on a textfield or textarea with
    668      * the trackball or center key, or starts typing into it without clicking on
    669      * it.
    670      */
    671     /* package */ void setDefaultSelection() {
    672         Spannable text = (Spannable) getText();
    673         int selection = mSingle ? text.length() : 0;
    674         if (Selection.getSelectionStart(text) == selection
    675                 && Selection.getSelectionEnd(text) == selection) {
    676             // The selection of the UI copy is set correctly, but the
    677             // WebTextView still needs to inform the webkit thread to set the
    678             // selection.  Normally that is done in onSelectionChanged, but
    679             // onSelectionChanged will not be called because the UI copy is not
    680             // changing.  (This can happen when the WebTextView takes focus.
    681             // That onSelectionChanged was blocked because the selection set
    682             // when focusing is not necessarily the desirable selection for
    683             // WebTextView.)
    684             if (mWebView != null) {
    685                 mWebView.setSelection(selection, selection);
    686             }
    687         } else {
    688             Selection.setSelection(text, selection, selection);
    689         }
    690     }
    691 
    692     /**
    693      * Determine whether to use the system-wide password disguising method,
    694      * or to use none.
    695      * @param   inPassword  True if the textfield is a password field.
    696      */
    697     /* package */ void setInPassword(boolean inPassword) {
    698         if (inPassword) {
    699             setInputType(EditorInfo.TYPE_CLASS_TEXT | EditorInfo.
    700                     TYPE_TEXT_VARIATION_PASSWORD);
    701             createBackground();
    702         }
    703         // For password fields, draw the WebTextView.  For others, just show
    704         // webkit's drawing.
    705         setWillNotDraw(!inPassword);
    706         setBackgroundDrawable(inPassword ? mBackground : null);
    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     @Override
    941     public boolean requestRectangleOnScreen(Rect rectangle) {
    942         // don't scroll while in zoom animation. When it is done, we will adjust
    943         // the WebTextView if it is in editing mode.
    944         if (!mWebView.inAnimateZoom()) {
    945             return super.requestRectangleOnScreen(rectangle);
    946         }
    947         return false;
    948     }
    949 }
    950