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