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