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