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