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