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